diff --git a/.github/.test/samples.json b/.github/.test/samples.json index 6520d1fbf0..4d9f501e14 100644 --- a/.github/.test/samples.json +++ b/.github/.test/samples.json @@ -1226,6 +1226,12 @@ "Client: TypeScript" ] }, + { + "input": "typescript-nestjs-v8-petstore-provided-in-root.sh", + "matches": [ + "Client: TypeScript" + ] + }, { "input": "typescript-node-petstore-with-npm.sh", "matches": [ diff --git a/.github/workflows/misc-test.yaml b/.github/workflows/misc-test.yaml new file mode 100644 index 0000000000..d359aab4b2 --- /dev/null +++ b/.github/workflows/misc-test.yaml @@ -0,0 +1,32 @@ +name: Misc Tests + +on: + push: + branches: + - master + - '[5-9]+.[0-9]+.x' + pull_request: + branches: + - master + - '[5-9]+.[0-9]+.x' + +jobs: + build: + name: Misc tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: '2.6' + bundler-cache: false # runs 'bundle install' and caches installed gems automatically + - name: Detect tabs + run: /bin/bash ./bin/utils/detect_tab_in_templates.sh + - name: Detect changes in test files + run: ./bin/utils/detect_test_file_changes.rb bin/utils/test_file_list.yaml + - name: Detect carriage return + run: /bin/bash ./bin/utils/detect_carriage_return.sh + - name: Detect merge conflicts + run: /bin/bash ./bin/utils/detect_merge_conflict.sh + - name: Detect tabs + run: /bin/bash ./bin/utils/detect_tab_in_java_class.sh diff --git a/.github/workflows/openapi-generator.yaml b/.github/workflows/openapi-generator.yaml index bd062d7d03..423cec9906 100644 --- a/.github/workflows/openapi-generator.yaml +++ b/.github/workflows/openapi-generator.yaml @@ -80,6 +80,44 @@ jobs: name: surefire-test-results path: '**/surefire-reports/TEST-*.xml' + functional-test: + name: Functional tests + runs-on: ubuntu-latest + needs: + - build + strategy: + matrix: + java-version: [11, 17] + steps: + - uses: actions/checkout@v3 + - name: Set up JDK + uses: actions/setup-java@v3 + with: + java-version: ${{ matrix.java-version }} + distribution: 'temurin' + - name: Cache maven dependencies + uses: actions/cache@v3 + env: + cache-name: cache-maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + !~/.gradle/caches/*/plugin-resolution/ + !~/.m2/repository/org/openapitools/ + key: ${{ runner.os }}-test-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + - name: Run unit tests + run: cd modules/openapi-generator && mvn --no-snapshot-updates --batch-mode -Dtest="**/functional/*Test" test -Dorg.slf4j.simpleLogger.defaultLogLevel=error + - name: Publish unit test reports + if: ${{ always() }} + uses: actions/upload-artifact@v3 + with: + name: surefire-test-results + path: '**/surefire-reports/TEST-*.xml' + documentation: name: Docs up-to-date runs-on: ubuntu-latest @@ -217,5 +255,7 @@ jobs: - name: Run tests run: | mvn --no-snapshot-updates --batch-mode --quiet install -DskipTests -Dorg.slf4j.simpleLogger.defaultLogLevel=error - (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildGoSdk) + (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildGoSdk) # using gradle-6.8.3 via wrapper (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew openApiGenerate) + (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildDotnetSdk) + (cd modules/openapi-generator-gradle-plugin/samples/local-spec && gradle buildJavaResttemplateSdk) # not using gradle wrapper diff --git a/.github/workflows/samples-dotnet.yaml b/.github/workflows/samples-dotnet.yaml index fc2fab472a..b89b473d47 100644 --- a/.github/workflows/samples-dotnet.yaml +++ b/.github/workflows/samples-dotnet.yaml @@ -24,9 +24,10 @@ jobs: - samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt - samples/server/petstore/aspnetcore-6.0 - samples/server/petstore/aspnetcore-6.0-pocoModels + - samples/server/petstore/aspnetcore-6.0-project4Models steps: - uses: actions/checkout@v3 - - uses: actions/setup-dotnet@v2 + - uses: actions/setup-dotnet@v3.0.2 with: dotnet-version: '6.0.x' - name: Build diff --git a/.github/workflows/samples-java-client-jdk11.yaml b/.github/workflows/samples-java-client-jdk11.yaml index 62bad2df6c..2c2cda527e 100644 --- a/.github/workflows/samples-java-client-jdk11.yaml +++ b/.github/workflows/samples-java-client-jdk11.yaml @@ -3,10 +3,18 @@ name: Samples Java Client JDK11 on: push: paths: - - 'samples/client/petstore/java*/**' + - 'samples/client/petstore/java/**' + - samples/client/petstore/jaxrs-cxf-client/** + - samples/client/petstore/java-micronaut-client/** + - samples/openapi3/client/petstore/java/jersey2-java8-special-characters/** + - samples/openapi3/client/petstore/java/native/** pull_request: paths: - - 'samples/client/petstore/java*/**' + - 'samples/client/petstore/java/**' + - samples/client/petstore/jaxrs-cxf-client/** + - samples/client/petstore/java-micronaut-client/** + - samples/openapi3/client/petstore/java/jersey2-java8-special-characters/** + - samples/openapi3/client/petstore/java/native/** jobs: build: name: Build Java Client JDK11 @@ -38,6 +46,8 @@ jobs: - samples/client/petstore/java/apache-httpclient - samples/client/petstore/java/feign - samples/client/petstore/java/jersey1 + - samples/openapi3/client/petstore/java/jersey2-java8-special-characters + - samples/openapi3/client/petstore/java/native steps: - uses: actions/checkout@v3 - uses: actions/setup-java@v3 diff --git a/.github/workflows/samples-jdk17.yaml b/.github/workflows/samples-jdk17.yaml index 36b76e0347..6d89ce09da 100644 --- a/.github/workflows/samples-jdk17.yaml +++ b/.github/workflows/samples-jdk17.yaml @@ -3,15 +3,23 @@ on: push: paths: # clients - - samples/openapi3/client/petstore/spring-cloud-3 + - samples/openapi3/client/petstore/spring-cloud-3/** + - samples/client/petstore/java-helidon-client/mp/** + - samples/client/petstore/java-helidon-client/se/** # servers - - samples/openapi3/server/petstore/springboot-3 + - samples/openapi3/server/petstore/springboot-3/** + - samples/server/petstore/java-helidon-server/mp/** + - samples/server/petstore/java-helidon-server/se/** pull_request: paths: # clients - - samples/openapi3/client/petstore/spring-cloud-3 + - samples/openapi3/client/petstore/spring-cloud-3/** + - samples/client/petstore/java-helidon-client/mp/** + - samples/client/petstore/java-helidon-client/se/** # servers - - samples/openapi3/server/petstore/springboot-3 + - samples/openapi3/server/petstore/springboot-3/** + - samples/server/petstore/java-helidon-server/mp/** + - samples/server/petstore/java-helidon-server/se/** jobs: build: name: Build with JDK17 @@ -22,8 +30,12 @@ jobs: sample: # clients - samples/openapi3/client/petstore/spring-cloud-3 + - samples/client/petstore/java-helidon-client/mp + - samples/client/petstore/java-helidon-client/se # servers - samples/openapi3/server/petstore/springboot-3 + - samples/server/petstore/java-helidon-server/mp + - samples/server/petstore/java-helidon-server/se steps: - uses: actions/checkout@v3 - uses: actions/setup-java@v3 diff --git a/.github/workflows/samples-scala.yaml b/.github/workflows/samples-scala.yaml index 9b91e8ca2b..81372fccdc 100644 --- a/.github/workflows/samples-scala.yaml +++ b/.github/workflows/samples-scala.yaml @@ -19,6 +19,7 @@ jobs: sample: # clients - samples/client/petstore/scalaz + #- samples/client/petstore/scala-sttp # won't pass while the same tests in circleci pass # servers - samples/server/petstore/scala-lagom-server - samples/server/petstore/scala-play-server diff --git a/.github/workflows/samples-spring.yaml b/.github/workflows/samples-spring.yaml index 941c9f3ad2..8c51f45a8c 100644 --- a/.github/workflows/samples-spring.yaml +++ b/.github/workflows/samples-spring.yaml @@ -41,6 +41,7 @@ jobs: - samples/server/petstore/spring-boot-defaultInterface-unhandledException - samples/openapi3/server/petstore/spring-boot-oneof - samples/server/petstore/springboot-virtualan + - samples/server/petstore/springboot-implicitHeaders-annotationLibrary steps: - uses: actions/checkout@v3 - uses: actions/setup-java@v3 diff --git a/.gitignore b/.gitignore index c31896c826..850adb6fac 100644 --- a/.gitignore +++ b/.gitignore @@ -224,6 +224,8 @@ samples/client/petstore/R/**/petstore.Rcheck/ samples/client/petstore/R/**/*.tar.gz samples/client/petstore/R/R.Rproj samples/client/petstore/R/man/ +samples/client/petstore/R-httr2-wrapper/man/ +samples/client/petstore/R-httr2/man/ # elixir samples/client/petstore/elixir/_build/ @@ -251,6 +253,7 @@ samples/server/petstore/erlang-server/rebar.lock # JS samples/client/petstore/javascript-es6/package-lock.json samples/client/petstore/javascript-promise-es6/package-lock.json +samples/client/petstore/javascript-apollo/package-lock.json # elm samples/client/petstore/elm/index.html diff --git a/.travis.yml b/.travis.yml index 0f5b038ec8..ddec30b70b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -111,6 +111,8 @@ before_install: - cmake --version # install Qt5 #- sudo apt install -y --no-install-recommends qt5-default + # install boost + - sudo apt install -y --no-install-recommends libboost-all-dev # perl dep - cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib) - cpanm --quiet --no-interactive Test::Exception Test::More Log::Any LWP::UserAgent URI::Query Module::Runtime DateTime Module::Find Moose::Role JSON || echo "Ignored failure from cpanm" @@ -145,16 +147,6 @@ script: - set -e # show docker buildx version - docker buildx version - # fail if the template files contains tabs - - /bin/bash ./bin/utils/detect_tab_in_templates.sh - # fail if the test files have changes - - bin/utils/detect_test_file_changes.rb bin/utils/test_file_list.yaml - # fail if templates/generators contain carriage return '\r' - - /bin/bash ./bin/utils/detect_carriage_return.sh - # fail if generators contain merge conflicts - - /bin/bash ./bin/utils/detect_merge_conflict.sh - # fail if generators contain tab '\t' - - /bin/bash ./bin/utils/detect_tab_in_java_class.sh # run integration tests defined in maven pom.xml # WARN: Travis will timeout after 10 minutes of no stdout/stderr activity, which is problematic with mvn --quiet. - mvn -e --no-snapshot-updates --quiet --batch-mode --show-version clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=error @@ -197,7 +189,7 @@ after_success: export build_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ"); docker buildx create --use; if [ ! -z "$TRAVIS_TAG" ]; then - docker buildx build --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-online --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_GENERATOR_IMAGE_NAME:latest -t $DOCKER_GENERATOR_IMAGE_NAME:$TRAVIS_TAG -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/openapi-generator-online; + docker buildx build --push --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-online --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_GENERATOR_IMAGE_NAME:latest -t $DOCKER_GENERATOR_IMAGE_NAME:$TRAVIS_TAG -t $DOCKER_GENERATOR_IMAGE_NAME -t $DOCKER_GENERATOR_IMAGE_NAME:latest-release ./modules/openapi-generator-online; echo "Built and tagged $DOCKER_GENERATOR_IMAGE_NAME"; fi; if [ -z "$TRAVIS_TAG" ] && [ "$TRAVIS_BRANCH" = "master" ] && [ "$TRAVIS_PULL_REQUEST" = "false" ]; then @@ -214,7 +206,7 @@ after_success: docker buildx create --use; docker buildx build --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-cli --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli; if [ ! -z "$TRAVIS_TAG" ]; then - docker buildx build --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-cli --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest -t $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli; + docker buildx build --push --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-cli --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest -t $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG -t $DOCKER_CODEGEN_CLI_IMAGE_NAME -t $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest-release ./modules/openapi-generator-cli; echo "Built and tagged $DOCKER_GENERATOR_IMAGE_NAME"; fi; if [ -z "$TRAVIS_TAG" ] && [ "$TRAVIS_BRANCH" = "master" ] && [ "$TRAVIS_PULL_REQUEST" = "false" ]; then diff --git a/CI/circle_parallel.sh b/CI/circle_parallel.sh index 1d96dae7b1..6cba564ffb 100755 --- a/CI/circle_parallel.sh +++ b/CI/circle_parallel.sh @@ -79,8 +79,8 @@ elif [ "$NODE_INDEX" = "4" ]; then #mvn --no-snapshot-updates --quiet verify -Psamples.circleci.node4 -Dorg.slf4j.simpleLogger.defaultLogLevel=error (cd samples/openapi3/client/petstore/python && make test) - (cd samples/openapi3/client/petstore/python-experimental && make test) - (cd samples/openapi3/client/3_0_3_unit_test/python-experimental && make test) + (cd samples/openapi3/client/petstore/python-prior && make test) + (cd samples/openapi3/client/3_0_3_unit_test/python && make test) else echo "Running node $NODE_INDEX to test 'samples.circleci.others' defined in pom.xml ..." diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4e59158cdb..60b08e90b3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -52,15 +52,15 @@ Code change should conform to the programming style guide of the respective lang - Clojure: https://github.com/bbatsov/clojure-style-guide - Crystal: https://crystal-lang.org/reference/conventions/coding_style.html - Dart: https://www.dartlang.org/guides/language/effective-dart/style -- Elixir: https://github.com/christopheradams/elixir_style_guide - Eiffel: https://www.eiffel.org/doc/eiffel/Coding%20Standards +- Elixir: https://github.com/christopheradams/elixir_style_guide - Erlang: https://github.com/inaka/erlang_guidelines +- Go: https://github.com/golang/go/wiki/CodeReviewComments +- Groovy: http://groovy-lang.org/style-guide.html - Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md - Java: https://google.github.io/styleguide/javaguide.html - JavaScript: https://github.com/airbnb/javascript/ - Kotlin: https://kotlinlang.org/docs/reference/coding-conventions.html -- Groovy: http://groovy-lang.org/style-guide.html -- Go: https://github.com/golang/go/wiki/CodeReviewComments - ObjC: https://github.com/NYTimes/objective-c-style-guide - Perl: http://perldoc.perl.org/perlstyle.html - PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-12-extended-coding-style-guide.md @@ -90,7 +90,7 @@ To test the templates, please perform the following: - Update the Petstore sample by running the shell scripts under the `bin` folder. For example, run `./bin/generate-samples.sh ./bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/tree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files generated or unexpected changes as a result of the update, that's not unusual as the test cases are added to the OpenAPI spec from time to time. If you've questions or concerns, please open a ticket to start a discussion) - During development, it can be helpful to quickly regenerate the samples without recompiling all of openapi-generator, e.g. when you have only updated the mustache templates. This can be done by passing the `-t` parameter: `-t modules/openapi-generator/src/main/resources/python`. -- Run the tests in the sample folder using maven `mvn integration-test -f /path/to/pom.xml`, e.g. `mvn integration-test -f samples/client/petstore/python/pom.xml`. (some languages may not contain unit testing for Petstore and we're looking for contribution from the community to implement those tests) +- Run the tests in the sample folder using maven `mvn integration-test -f /path/to/pom.xml`, e.g. `mvn integration-test -f samples/client/petstore/python/pom.xml`. (some languages may not contain unit testing for Petstore and we're looking for contribution from the community to implement those tests). __Please notice:__ you must run a local instance of the Petstore server in order to perform the tests, as running them against petstore.swagger.io is not supported anymore. Please refer to item 3 of [Integration Tests - How to add integration tests for new Petstore samples](https://github.com/OpenAPITools/openapi-generator/wiki/Integration-Tests#how-to-add-integration-tests-for-new-petstore-samples) to learn how to quickly configure and run it. - Finally, git commit the updated samples files: `git commit -a` (`git add -A` if added files with new test cases) - For new test cases, please add to the [Fake Petstore spec](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml) diff --git a/README.md b/README.md index 277035284e..ba0dc63d56 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@
-[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`6.1.0`): +[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`6.2.1`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.com/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) [![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator) @@ -68,13 +68,13 @@ If you find OpenAPI Generator useful for work, please consider asking your compa ## Overview OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification) (both 2.0 and 3.0 are supported). Currently, the following languages/frameworks are supported: -| | Languages/Frameworks | -| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| | Languages/Frameworks | +| -------------------------------- |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.1, .NET Core 3.1, .NET 5.0. Libraries: RestSharp, GenericHost, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient, 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, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 13.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) | -| **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **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/), [Apache Camel](https://camel.apache.org/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [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**, **Markdown**, **PlantUML** | -| **Configuration files** | [**Apache2**](https://httpd.apache.org/) | -| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer**, **WSDL** | +| **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **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/), [Apache Camel](https://camel.apache.org/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** ([rust-server](https://openapi-generator.tech/docs/generators/rust-server/)), **Scala** (Akka, [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**, **Markdown**, **PlantUML** | +| **Configuration files** | [**Apache2**](https://httpd.apache.org/) | +| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer**, **WSDL** | ## Table of contents @@ -113,8 +113,9 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 | OpenAPI Generator Version | Release Date | Notes | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- | | 7.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.0.0-SNAPSHOT/) | Feb/Mar 2023 | Major release with breaking changes (no fallback) | -| 6.1.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/6.1.0-SNAPSHOT/) | 03.08 2022 | Minor release with breaking changes (with fallback) | -| [6.0.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v6.0.1) (latest stable release) | 03.07.2022 | Patch release (enhancements, bug fixes, etc) | +| 6.3.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/6.3.0-SNAPSHOT/) | 24.11.2022 | Minor release with breaking changes (with fallback) | +| 6.2.1 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/6.2.1-SNAPSHOT/) | 24.10.2022 | Patch release (enhancements, bug fixes, etc) | +| [6.2.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v6.2.0) (latest stable release) | 24.09.2022 | Minor release with breaking changes (with fallback) | | [5.4.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.4.0) | 31.01.2022 | Minor release with breaking changes (with fallback) | | [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) | @@ -172,16 +173,16 @@ See the different versions of the [openapi-generator-cli](https://search.maven.o If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum): -JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.0.1/openapi-generator-cli-6.0.1.jar` +JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.2.0/openapi-generator-cli-6.2.0.jar` For **Mac/Linux** users: ```sh -wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.0.1/openapi-generator-cli-6.0.1.jar -O openapi-generator-cli.jar +wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.2.0/openapi-generator-cli-6.2.0.jar -O openapi-generator-cli.jar ``` For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g. ``` -Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.0.1/openapi-generator-cli-6.0.1.jar +Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.2.0/openapi-generator-cli-6.2.0.jar ``` After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage. @@ -406,7 +407,7 @@ openapi-generator-cli version To use a specific version of "openapi-generator-cli" ```sh -openapi-generator-cli version-manager set 6.0.1 +openapi-generator-cli version-manager set 6.2.0 ``` Or install it as dev-dependency: @@ -430,7 +431,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat (if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php -o c:\temp\php_api_client`) -You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.0.1/openapi-generator-cli-6.0.1.jar) +You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.2.0/openapi-generator-cli-6.2.0.jar) To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate` @@ -582,6 +583,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [Arduino](https://www.arduino.cc/) - [b<>com](https://b-com.com/en) - [百度营销](https://e.baidu.com) +- [Bandwidth](https://dev.bandwidth.com) - [Banzai Cloud](https://banzaicloud.com) - [BIMData.io](https://bimdata.io) - [Bithost GmbH](https://www.bithost.ch) @@ -865,9 +867,18 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - 2022-04-06 - [Effective Software Development using OpenAPI Generator](https://apexlabs.ai/post/openapi-generator) by Ajil Oommen (Senior Flutter Developer) - 2022-05-13 - [A Path From an API To Client Libraries](https://www.youtube.com/watch?v=XC8oVn_efTw) by [Filip Srnec](https://www.devoxx.co.uk/talk/?id=11211) at Infobip - 2022-06-01 - [API First, using OpenAPI and Spring Boot](https://medium.com/xgeeks/api-first-using-openapi-and-spring-boot-2602c04bb0d3) by [Micael Estrázulas Vianna](https://estrazulas.medium.com/) +- 2022-07-01 - [Generate API contract using OpenAPI Generator Maven plugin](https://huongdanjava.com/generate-api-contract-using-openapi-generator-maven-plugin.html) by [Khanh Nguyen](https://huongdanjava.com/) +- 2022-07-22 - [使用OpenAPI Generator Maven plugin开发api优先的java客户端和服务端代码](https://blog.roccoshi.top/2022/java/openapi-generator%E7%9A%84%E4%BD%BF%E7%94%A8/) by [Lincest](https://github.com/Lincest) +- 2022-08-01 - [Tutorial: Etsy Open API v3 (ruby)](https://blog.tjoyal.dev/etsy-open-api-v3/) by [Thierry Joyal](https://github.com/tjoyal) +- 2022-09-03 - [OpenAPI Generator For Go Web Development](https://blog.kevinhu.me/2022/09/03/03-openapi-generator/) by [Kevin Hu](https://twitter.com/Oldgunix) +- 2022-10-01 - [OpenAPI Generatorをカスタマイズしたコードを生成する(Swagger Codegenとほぼ同じ)](https://nainaistar.hatenablog.com/entry/2022/10/03/120000) by [きり丸](https://twitter.com/nainaistar) ## [6 - About Us](#table-of-contents) +What's the design philosophy or principle behind OpenAPI Generator? + +We focus on developer experience. The generators should produce code, config, documentation, and more that are easily understandable and consumable by users. We focused on simple use cases to start with (bottom-up approach). Since then the project and the community have grown a lot: 300k weekly downloads via NPM CLI wrapper, 20M downloads via openapi-generator-cli docker image just to highlight a few. We've gradually supported more features (e.g. oneOf, anyOf introduced in OpenAPI 3.0) in various generators and we will continue this approach to deliver something based on our understanding of user demand and what they want, and continue to add support of new features introduced in OpenAPI specification (such as v3.1 and future versions of the OpenAPI specification). + ### [6.1 - OpenAPI Generator Core Team](#table-of-contents) OpenAPI Generator core team members are contributors who have been making significant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. @@ -1092,7 +1103,7 @@ If you want to join the committee, please kindly apply by sending an email to te | Groovy | | | Haskell | | | Java | @bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) | -| Java Spring | @cachescrubber (2022/02) @welshm (2022/02) @MelleD (2022/02) @atextor (2022/02) @manedev79 (2022/02) @javisst (2022/02) @borsch (2022/02) @banlevente (2022/02) | +| Java Spring | @cachescrubber (2022/02) @welshm (2022/02) @MelleD (2022/02) @atextor (2022/02) @manedev79 (2022/02) @javisst (2022/02) @borsch (2022/02) @banlevente (2022/02) @Zomzog (2022/09) | | JMeter | @kannkyo (2021/01) | | Kotlin | @jimschubert (2017/09) [:heart:](https://www.patreon.com/jimschubert), @dr4ke616 (2018/08) @karismann (2019/03) @Zomzog (2019/04) @andrewemery (2019/10) @4brunu (2019/11) @yutaka0m (2020/03) | | Lua | @daurnimator (2017/08) | @@ -1103,14 +1114,21 @@ If you want to join the committee, please kindly apply by sending an email to te | Perl | @wing328 (2017/07) [:heart:](https://www.patreon.com/wing328) @yue9944882 (2019/06) | | PHP | @jebentier (2017/07), @dkarlovi (2017/07), @mandrean (2017/08), @jfastnacht (2017/09), [@ybelenko](https://github.com/ybelenko) (2018/07), @renepardon (2018/12) | | PowerShell | @wing328 (2020/05) | -| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11) @tomplus (2018/10) @arun-nalla (2019/11) @spacether (2019/11) [:heart:][spacether sponsorship] | +| Python | @spacether (2019/11) [:heart:][spacether sponsorship] | | R | @Ramanth (2019/07) @saigiridhar21 (2019/07) | | Ruby | @cliffano (2017/07) @zlx (2017/09) @autopp (2019/02) | -| Rust | @frol (2017/07) @farcaller (2017/08) @richardwhiuk (2019/07) @paladinzh (2020/05) | +| Rust | @frol (2017/07) @farcaller (2017/08) @richardwhiuk (2019/07) @paladinzh (2020/05) @jacob-pro (2022/10) | | Scala | @clasnake (2017/07), @jimschubert (2017/09) [:heart:](https://www.patreon.com/jimschubert), @shijinkui (2018/01), @ramzimaalej (2018/03), @chameleon82 (2020/03), @Bouillie (2020/04) | | Swift | @jgavris (2017/07) @ehyche (2017/08) @Edubits (2017/09) @jaz-ah (2017/09) @4brunu (2019/11) | | TypeScript | @TiFu (2017/07) @taxpon (2017/07) @sebastianhaas (2017/07) @kenisteward (2017/07) @Vrolijkx (2017/09) @macjohnny (2018/01) @topce (2018/10) @akehir (2019/07) @petejohansonxo (2019/11) @amakhrov (2020/02) @davidgamero (2022/03) @mkusaka (2022/04) | + +Past Members of Technical Committee: +| Languages/Generators | Member (join date) | +| :---------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11) @tomplus (2018/10) @arun-nalla (2019/11) | + + :heart: = Link to support the contributor directly ### [6.3 - History of OpenAPI Generator](#table-of-contents) diff --git a/appveyor.yml b/appveyor.yml index 6c13691390..c5483fe836 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -55,6 +55,8 @@ build_script: - dotnet build samples\client\petstore\csharp-netcore\OpenAPIClientCore\Org.OpenAPITools.sln # build C# API client (.net framework 4.7) - dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient-net47\Org.OpenAPITools.sln + # build C# API client (.net framework 4.8) + - dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient-net48\Org.OpenAPITools.sln # build C# API client (.net 5.0) - dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient-net5.0\Org.OpenAPITools.sln # build C# API client (.net 5.0 with ConditionalSerialization) @@ -84,6 +86,8 @@ test_script: - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj # test C# API client (.net framework 4.7) - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient-net47\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj + # test C# API client (.net framework 4.8) + - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient-net48\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj # test C# API client (.net 5.0) - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient-net5.0\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj # test C# API Client using conditional-serialization diff --git a/bin/configs/aspnetcore-6.0-project4Models.yaml b/bin/configs/aspnetcore-6.0-project4Models.yaml new file mode 100644 index 0000000000..bb8b63602c --- /dev/null +++ b/bin/configs/aspnetcore-6.0-project4Models.yaml @@ -0,0 +1,9 @@ +generatorName: aspnetcore +outputDir: samples/server/petstore/aspnetcore-6.0-project4Models +inputSpec: modules/openapi-generator/src/test/resources/3_0/aspnetcore/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/aspnetcore/3.0 +additionalProperties: + packageGuid: '{3C799344-F285-4669-8FD5-7ED9B795D5C5}' + aspnetCoreVersion: "6.0" + userSecretsGuid: 'cb87e868-8646-48ef-9bb6-344b537d0d37' + useSeperateModelProject: true diff --git a/bin/configs/avro-schema.yaml b/bin/configs/avro-schema.yaml index bf44846dc0..872043a696 100644 --- a/bin/configs/avro-schema.yaml +++ b/bin/configs/avro-schema.yaml @@ -1,4 +1,4 @@ generatorName: avro-schema outputDir: samples/openapi3/schema/petstore/avro-schema -inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/avro-schema/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/avro-schema diff --git a/bin/configs/cpp-restbed-server.yaml b/bin/configs/cpp-restbed-server.yaml new file mode 100644 index 0000000000..6dc3929ec0 --- /dev/null +++ b/bin/configs/cpp-restbed-server.yaml @@ -0,0 +1,4 @@ +generatorName: cpp-restbed-server +outputDir: samples/server/petstore/cpp-restbed/generated/3_0 +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/cpp-restbed-server diff --git a/bin/configs/crystal.yaml b/bin/configs/crystal.yaml index 74badcce66..c578838173 100644 --- a/bin/configs/crystal.yaml +++ b/bin/configs/crystal.yaml @@ -1,6 +1,6 @@ generatorName: crystal outputDir: samples/client/petstore/crystal -inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/crystal/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/crystal additionalProperties: shardVersion: 1.0.0 diff --git a/bin/configs/csharp-netcore-OpenAPIClient-net48.yaml b/bin/configs/csharp-netcore-OpenAPIClient-net48.yaml new file mode 100644 index 0000000000..11c2583671 --- /dev/null +++ b/bin/configs/csharp-netcore-OpenAPIClient-net48.yaml @@ -0,0 +1,11 @@ +# for .net standard +generatorName: csharp-netcore +outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient-net48 +inputSpec: modules/openapi-generator/src/test/resources/3_0/csharp/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +templateDir: modules/openapi-generator/src/main/resources/csharp-netcore +additionalProperties: + packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' + useCompareNetObjects: true + disallowAdditionalPropertiesIfNotPresent: false + useOneOfDiscriminatorLookup: true + targetFramework: net48 diff --git a/bin/configs/csharp-netcore-functions.yaml b/bin/configs/csharp-netcore-functions.yaml index 6d7e9a691b..3ce5234a94 100644 --- a/bin/configs/csharp-netcore-functions.yaml +++ b/bin/configs/csharp-netcore-functions.yaml @@ -2,5 +2,6 @@ generatorName: csharp-netcore-functions outputDir: samples/client/petstore/csharp-netcore-functions inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/csharp-netcore-functions -#additionalProperties: -# packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' +additionalProperties: + packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' + userSecretsGuid: "76e9e993-9159-441c-9c5b-fe95e7f4f020" diff --git a/bin/configs/dart-dio-oneof-polymorphism-and-inheritance.yaml b/bin/configs/dart-dio-oneof-polymorphism-and-inheritance.yaml new file mode 100644 index 0000000000..d3d5b622bc --- /dev/null +++ b/bin/configs/dart-dio-oneof-polymorphism-and-inheritance.yaml @@ -0,0 +1,11 @@ +generatorName: dart-dio +outputDir: samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance +inputSpec: modules/openapi-generator/src/test/resources/3_0/oneof_polymorphism_and_inheritance.yaml +templateDir: modules/openapi-generator/src/main/resources/dart/libraries/dio +typeMappings: + Client: "ModelClient" + File: "ModelFile" + EnumClass: "ModelEnumClass" +additionalProperties: + hideGenerationTimestamp: "true" + enumUnknownDefaultCase: "true" diff --git a/bin/configs/dart-dio-oneof-primitive.yaml b/bin/configs/dart-dio-oneof-primitive.yaml new file mode 100644 index 0000000000..29130b5dc4 --- /dev/null +++ b/bin/configs/dart-dio-oneof-primitive.yaml @@ -0,0 +1,11 @@ +generatorName: dart-dio +outputDir: samples/openapi3/client/petstore/dart-dio/oneof_primitive +inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOf_primitive.yaml +templateDir: modules/openapi-generator/src/main/resources/dart/libraries/dio +typeMappings: + Client: "ModelClient" + File: "ModelFile" + EnumClass: "ModelEnumClass" +additionalProperties: + hideGenerationTimestamp: "true" + enumUnknownDefaultCase: "true" diff --git a/bin/configs/dart-dio-oneof.yaml b/bin/configs/dart-dio-oneof.yaml new file mode 100644 index 0000000000..865312cdd4 --- /dev/null +++ b/bin/configs/dart-dio-oneof.yaml @@ -0,0 +1,11 @@ +generatorName: dart-dio +outputDir: samples/openapi3/client/petstore/dart-dio/oneof +inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOf.yaml +templateDir: modules/openapi-generator/src/main/resources/dart/libraries/dio +typeMappings: + Client: "ModelClient" + File: "ModelFile" + EnumClass: "ModelEnumClass" +additionalProperties: + hideGenerationTimestamp: "true" + enumUnknownDefaultCase: "true" diff --git a/bin/configs/java-helidon-client-mp.yaml b/bin/configs/java-helidon-client-mp.yaml new file mode 100644 index 0000000000..5dc5c6883c --- /dev/null +++ b/bin/configs/java-helidon-client-mp.yaml @@ -0,0 +1,13 @@ +generatorName: java-helidon-client +library: mp +outputDir: samples/client/petstore/java-helidon-client/mp +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +additionalProperties: + artifactId: petstore-helidon-client-mp + hideGenerationTimestamp: "true" + configureAuth: "false" + build: "all" + test: "spock" + requiredPropertiesInConstructor: "false" + visitable: "true" + fullProject: "true" diff --git a/bin/configs/java-helidon-client-se.yaml b/bin/configs/java-helidon-client-se.yaml new file mode 100644 index 0000000000..bd4d7a363f --- /dev/null +++ b/bin/configs/java-helidon-client-se.yaml @@ -0,0 +1,13 @@ +generatorName: java-helidon-client +library: se +outputDir: samples/client/petstore/java-helidon-client/se +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +additionalProperties: + artifactId: petstore-helidon-client-se + hideGenerationTimestamp: "true" + configureAuth: "false" + build: "all" + test: "spock" + requiredPropertiesInConstructor: "false" + visitable: "true" + fullProject: "true" diff --git a/bin/configs/java-helidon-server-mp.yaml b/bin/configs/java-helidon-server-mp.yaml new file mode 100644 index 0000000000..80a72e4f3b --- /dev/null +++ b/bin/configs/java-helidon-server-mp.yaml @@ -0,0 +1,12 @@ +generatorName: java-helidon-server +library: mp +outputDir: samples/server/petstore/java-helidon-server/mp +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/java-helidon/server +additionalProperties: + artifactId: petstore-helidon-server-mp + hideGenerationTimestamp: "true" + build: "all" + test: "spock" + useAuth: "false" + fullProject: "true" \ No newline at end of file diff --git a/bin/configs/java-helidon-server-se.yaml b/bin/configs/java-helidon-server-se.yaml new file mode 100644 index 0000000000..641f131f5e --- /dev/null +++ b/bin/configs/java-helidon-server-se.yaml @@ -0,0 +1,9 @@ +generatorName: java-helidon-server +library: se +outputDir: samples/server/petstore/java-helidon-server/se +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/java-helidon/server +additionalProperties: + artifactId: petstore-helidon-server-se + hideGenerationTimestamp: "true" + fullProject: "true" \ No newline at end of file diff --git a/bin/configs/javascript-apollo.yaml b/bin/configs/javascript-apollo.yaml new file mode 100644 index 0000000000..74853eec57 --- /dev/null +++ b/bin/configs/javascript-apollo.yaml @@ -0,0 +1,7 @@ +generatorName: javascript +outputDir: samples/client/petstore/javascript-apollo +library: apollo +inputSpec: modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/Javascript +additionalProperties: + appName: PetstoreClient diff --git a/bin/configs/javascript-es6.yaml b/bin/configs/javascript-es6.yaml index d561ad52c6..67f013b0c5 100644 --- a/bin/configs/javascript-es6.yaml +++ b/bin/configs/javascript-es6.yaml @@ -1,6 +1,7 @@ generatorName: javascript outputDir: samples/client/petstore/javascript-es6 +library: javascript inputSpec: modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml -templateDir: modules/openapi-generator/src/main/resources/Javascript/es6 +templateDir: modules/openapi-generator/src/main/resources/Javascript additionalProperties: appName: PetstoreClient diff --git a/bin/configs/javascript-promise-es6.yaml b/bin/configs/javascript-promise-es6.yaml index 6947fd7044..9ffae513eb 100644 --- a/bin/configs/javascript-promise-es6.yaml +++ b/bin/configs/javascript-promise-es6.yaml @@ -1,7 +1,8 @@ generatorName: javascript outputDir: samples/client/petstore/javascript-promise-es6 +library: javascript inputSpec: modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml -templateDir: modules/openapi-generator/src/main/resources/Javascript/es6 +templateDir: modules/openapi-generator/src/main/resources/Javascript additionalProperties: usePromises: "true" appName: PetstoreClient diff --git a/bin/configs/kotlin-default-values-numbers.yaml b/bin/configs/kotlin-default-values-numbers.yaml new file mode 100644 index 0000000000..1a76dd1dfd --- /dev/null +++ b/bin/configs/kotlin-default-values-numbers.yaml @@ -0,0 +1,9 @@ +generatorName: kotlin +outputDir: samples/client/petstore/kotlin-default-values-numbers +inputSpec: modules/openapi-generator/src/test/resources/3_0/kotlin/issue13506-defaultValue-numbers.yaml +templateDir: modules/openapi-generator/src/main/resources/kotlin-client +additionalProperties: + artifactId: kotlin-default-values-numbers + serializationLibrary: gson +globalProperties: + models: "" \ No newline at end of file diff --git a/bin/configs/kotlin-json-request-string.yaml b/bin/configs/kotlin-json-request-string.yaml index bbe5ddd428..31943045ab 100644 --- a/bin/configs/kotlin-json-request-string.yaml +++ b/bin/configs/kotlin-json-request-string.yaml @@ -7,3 +7,5 @@ additionalProperties: artifactId: kotlin-petstore-json-request-string parcelizeModels: true supportAndroidApiLevel25AndBelow: true + serializationLibrary: kotlinx_serialization + enumUnknownDefaultCase: "true" diff --git a/bin/configs/kotlin-uppercase-enum.yaml b/bin/configs/kotlin-uppercase-enum.yaml index b3501dd8af..f4066ef7db 100644 --- a/bin/configs/kotlin-uppercase-enum.yaml +++ b/bin/configs/kotlin-uppercase-enum.yaml @@ -5,3 +5,5 @@ templateDir: modules/openapi-generator/src/main/resources/kotlin-client additionalProperties: artifactId: kotlin-uppercase-enum enumPropertyNaming: UPPERCASE + serializationLibrary: kotlinx_serialization + enumUnknownDefaultCase: "true" diff --git a/bin/configs/other/cpp-restbed-server-cpp-restbed.yaml b/bin/configs/other/cpp-restbed-server-cpp-restbed.yaml deleted file mode 100644 index 8863620d2a..0000000000 --- a/bin/configs/other/cpp-restbed-server-cpp-restbed.yaml +++ /dev/null @@ -1,4 +0,0 @@ -generatorName: cpp-restbed-server -outputDir: samples/server/petstore/cpp-restbed -inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml -templateDir: modules/openapi-generator/src/main/resources/cpp-restbed-server diff --git a/bin/configs/other/javascript-apollo.yaml b/bin/configs/other/javascript-apollo.yaml deleted file mode 100644 index c462a62220..0000000000 --- a/bin/configs/other/javascript-apollo.yaml +++ /dev/null @@ -1,6 +0,0 @@ -generatorName: javascript-apollo -outputDir: samples/client/petstore/javascript-apollo -inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml -templateDir: modules/openapi-generator/src/main/resources/Javascript-Apollo -additionalProperties: - appName: PetstoreClient diff --git a/bin/configs/other/openapi3/cpp-restbed-server-cpp-restbed.yaml b/bin/configs/other/openapi3/cpp-restbed-server-cpp-restbed.yaml deleted file mode 100644 index d0acbda2d0..0000000000 --- a/bin/configs/other/openapi3/cpp-restbed-server-cpp-restbed.yaml +++ /dev/null @@ -1,4 +0,0 @@ -generatorName: cpp-restbed-server -outputDir: samples/server/petstore/cpp-restbed -inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml -templateDir: modules/openapi-generator/src/main/resources/cpp-restbed-server diff --git a/bin/configs/other/rust-hyper-fileResponseTest.yaml b/bin/configs/other/rust-hyper-fileResponseTest.yaml deleted file mode 100644 index fc26c786be..0000000000 --- a/bin/configs/other/rust-hyper-fileResponseTest.yaml +++ /dev/null @@ -1,9 +0,0 @@ -generatorName: rust -outputDir: samples/client/petstore/rust/hyper/fileResponseTest -library: hyper -inputSpec: modules/openapi-generator/src/test/resources/2_0/fileResponseTest.json -templateDir: modules/openapi-generator/src/main/resources/rust -generateAliasAsModel: true -additionalProperties: - supportAsync: "false" - packageName: fileResponseTest-hyper diff --git a/bin/configs/other/rust-hyper-test.yaml b/bin/configs/other/rust-hyper-test.yaml deleted file mode 100644 index 371d69150d..0000000000 --- a/bin/configs/other/rust-hyper-test.yaml +++ /dev/null @@ -1,8 +0,0 @@ -generatorName: rust -outputDir: samples/client/petstore/rust/hyper/rust-test -library: hyper -inputSpec: modules/openapi-generator/src/test/resources/3_0/rust/rust-test.yaml -templateDir: modules/openapi-generator/src/main/resources/rust -additionalProperties: - supportAsync: "false" - packageName: rust-test-hyper diff --git a/bin/configs/other/rust-reqwest-fileResponseTest.yaml b/bin/configs/other/rust-reqwest-fileResponseTest.yaml deleted file mode 100644 index 15aadb7217..0000000000 --- a/bin/configs/other/rust-reqwest-fileResponseTest.yaml +++ /dev/null @@ -1,8 +0,0 @@ -generatorName: rust -outputDir: samples/client/petstore/rust/reqwest/fileResponseTest -library: reqwest -inputSpec: modules/openapi-generator/src/test/resources/2_0/fileResponseTest.json -templateDir: modules/openapi-generator/src/main/resources/rust -additionalProperties: - supportAsync: "false" - packageName: fileResponseTest-reqwest diff --git a/bin/configs/other/rust-reqwest-test.yaml b/bin/configs/other/rust-reqwest-test.yaml deleted file mode 100644 index 74dbb40a81..0000000000 --- a/bin/configs/other/rust-reqwest-test.yaml +++ /dev/null @@ -1,8 +0,0 @@ -generatorName: rust -outputDir: samples/client/petstore/rust/reqwest/rust-test -library: reqwest -inputSpec: modules/openapi-generator/src/test/resources/3_0/rust/rust-test.yaml -templateDir: modules/openapi-generator/src/main/resources/rust -additionalProperties: - supportAsync: "false" - packageName: rust-test-reqwest diff --git a/bin/configs/protobuf-schema.yaml b/bin/configs/protobuf-schema.yaml index 2b368f5d50..30f606c915 100644 --- a/bin/configs/protobuf-schema.yaml +++ b/bin/configs/protobuf-schema.yaml @@ -1,6 +1,6 @@ generatorName: protobuf-schema outputDir: samples/config/petstore/protobuf-schema -inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/protobuf/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/protobuf-schema additionalProperties: packageName: petstore diff --git a/bin/configs/python-experimental.yaml b/bin/configs/python-experimental.yaml deleted file mode 100644 index dd204f4493..0000000000 --- a/bin/configs/python-experimental.yaml +++ /dev/null @@ -1,7 +0,0 @@ -generatorName: python-experimental -outputDir: samples/openapi3/client/petstore/python-experimental -inputSpec: modules/openapi-generator/src/test/resources/3_0/python-experimental/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml -templateDir: modules/openapi-generator/src/main/resources/python-experimental -additionalProperties: - packageName: petstore_api - recursionLimit: "1234" diff --git a/bin/configs/python-experimental_3_0_3_unit_test.yaml b/bin/configs/python-experimental_3_0_3_unit_test.yaml deleted file mode 100644 index a6428fb1ad..0000000000 --- a/bin/configs/python-experimental_3_0_3_unit_test.yaml +++ /dev/null @@ -1,6 +0,0 @@ -generatorName: python-experimental -outputDir: samples/openapi3/client/3_0_3_unit_test/python-experimental -inputSpec: modules/openapi-generator/src/test/resources/3_0/unit_test_spec/3_0_3_unit_test_spec.yaml -templateDir: modules/openapi-generator/src/main/resources/python-experimental -additionalProperties: - packageName: unit_test_api diff --git a/bin/configs/python-extensions-x-auth-id-alias.yaml b/bin/configs/python-extensions-x-auth-id-alias.yaml deleted file mode 100644 index 6f6fd89e37..0000000000 --- a/bin/configs/python-extensions-x-auth-id-alias.yaml +++ /dev/null @@ -1,6 +0,0 @@ -generatorName: python -outputDir: samples/openapi3/client/extensions/x-auth-id-alias/python/ -inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml -templateDir: modules/openapi-generator/src/main/resources/python -additionalProperties: - packageName: x_auth_id_alias diff --git a/bin/configs/python-oas2.yaml b/bin/configs/python-oas2.yaml deleted file mode 100644 index 7c548fb392..0000000000 --- a/bin/configs/python-oas2.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# this file exists because in this file we omit setting disallowAdditionalPropertiesIfNotPresent -# which makes it default to false -# that false setting is needed for composed schemas to work -# Composed schemas are schemas that contain the allOf/oneOf/anyOf keywords. v2 specs only support the allOf keyword. -generatorName: python -outputDir: samples/client/petstore/python -inputSpec: modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml -templateDir: modules/openapi-generator/src/main/resources/python -additionalProperties: - packageName: petstore_api diff --git a/bin/configs/python-oas2_disallowAdditionalPropertiesIfNotPresent.yaml b/bin/configs/python-oas2_disallowAdditionalPropertiesIfNotPresent.yaml deleted file mode 100644 index 841cf77854..0000000000 --- a/bin/configs/python-oas2_disallowAdditionalPropertiesIfNotPresent.yaml +++ /dev/null @@ -1,7 +0,0 @@ -generatorName: python -outputDir: samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent -inputSpec: modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml -templateDir: modules/openapi-generator/src/main/resources/python -additionalProperties: - disallowAdditionalPropertiesIfNotPresent: "true" - packageName: petstore_api diff --git a/bin/configs/python-prior-extensions-x-auth-id-alias.yaml b/bin/configs/python-prior-extensions-x-auth-id-alias.yaml new file mode 100644 index 0000000000..a017b13b22 --- /dev/null +++ b/bin/configs/python-prior-extensions-x-auth-id-alias.yaml @@ -0,0 +1,6 @@ +generatorName: python-prior +outputDir: samples/openapi3/client/extensions/x-auth-id-alias/python-prior/ +inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml +templateDir: modules/openapi-generator/src/main/resources/python +additionalProperties: + packageName: x_auth_id_alias diff --git a/bin/configs/python-prior-oas2.yaml b/bin/configs/python-prior-oas2.yaml new file mode 100644 index 0000000000..160afab7d9 --- /dev/null +++ b/bin/configs/python-prior-oas2.yaml @@ -0,0 +1,10 @@ +# this file exists because in this file we omit setting disallowAdditionalPropertiesIfNotPresent +# which makes it default to false +# that false setting is needed for composed schemas to work +# Composed schemas are schemas that contain the allOf/oneOf/anyOf keywords. v2 specs only support the allOf keyword. +generatorName: python-prior +outputDir: samples/client/petstore/python-prior +inputSpec: modules/openapi-generator/src/test/resources/2_0/python-prior/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/python-prior +additionalProperties: + packageName: petstore_api diff --git a/bin/configs/python-prior-oas2_disallowAdditionalPropertiesIfNotPresent.yaml b/bin/configs/python-prior-oas2_disallowAdditionalPropertiesIfNotPresent.yaml new file mode 100644 index 0000000000..e524b83b4e --- /dev/null +++ b/bin/configs/python-prior-oas2_disallowAdditionalPropertiesIfNotPresent.yaml @@ -0,0 +1,7 @@ +generatorName: python-prior +outputDir: samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent +inputSpec: modules/openapi-generator/src/test/resources/2_0/python-prior/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/python-prior +additionalProperties: + disallowAdditionalPropertiesIfNotPresent: "true" + packageName: petstore_api diff --git a/bin/configs/python-prior.yaml b/bin/configs/python-prior.yaml new file mode 100644 index 0000000000..11a918d1ad --- /dev/null +++ b/bin/configs/python-prior.yaml @@ -0,0 +1,8 @@ +generatorName: python-prior +outputDir: samples/openapi3/client/petstore/python-prior +inputSpec: modules/openapi-generator/src/test/resources/3_0/python-prior/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +templateDir: modules/openapi-generator/src/main/resources/python-prior +additionalProperties: + packageName: petstore_api + recursionLimit: "1234" + initRequiredVars: false diff --git a/bin/configs/python.yaml b/bin/configs/python.yaml index f66aab2699..37d0948cc6 100644 --- a/bin/configs/python.yaml +++ b/bin/configs/python.yaml @@ -5,4 +5,3 @@ templateDir: modules/openapi-generator/src/main/resources/python additionalProperties: packageName: petstore_api recursionLimit: "1234" - initRequiredVars: false diff --git a/bin/configs/python_3_0_3_unit_test.yaml b/bin/configs/python_3_0_3_unit_test.yaml new file mode 100644 index 0000000000..a388d87347 --- /dev/null +++ b/bin/configs/python_3_0_3_unit_test.yaml @@ -0,0 +1,6 @@ +generatorName: python +outputDir: samples/openapi3/client/3_0_3_unit_test/python +inputSpec: modules/openapi-generator/src/test/resources/3_0/unit_test_spec/3_0_3_unit_test_spec.yaml +templateDir: modules/openapi-generator/src/main/resources/python +additionalProperties: + packageName: unit_test_api diff --git a/bin/configs/r-client.yaml b/bin/configs/r-client.yaml index e6d0fca8d6..d52db86cac 100644 --- a/bin/configs/r-client.yaml +++ b/bin/configs/r-client.yaml @@ -9,3 +9,5 @@ additionalProperties: useRlangExceptionHandling: true returnExceptionOnFailure: true errorObjectType: "ModelApiResponse" + operationIdNaming: PascalCase #default + disallowAdditionalPropertiesIfNotPresent: false diff --git a/bin/configs/r-httr2-client.yaml b/bin/configs/r-httr2-client.yaml new file mode 100644 index 0000000000..15779e26d3 --- /dev/null +++ b/bin/configs/r-httr2-client.yaml @@ -0,0 +1,13 @@ +generatorName: r +outputDir: samples/client/petstore/R-httr2 +inputSpec: modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/r +httpUserAgent: PetstoreAgent +library: httr2 +additionalProperties: + packageName: petstore + exceptionPackage: rlang + useRlangExceptionHandling: true + returnExceptionOnFailure: true + errorObjectType: "ModelApiResponse" + operationIdNaming: snake_case diff --git a/bin/configs/r-httr2-wrapper-client.yaml b/bin/configs/r-httr2-wrapper-client.yaml new file mode 100644 index 0000000000..18b3dbc4bb --- /dev/null +++ b/bin/configs/r-httr2-wrapper-client.yaml @@ -0,0 +1,16 @@ +generatorName: r +outputDir: samples/client/petstore/R-httr2-wrapper +inputSpec: modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/r +httpUserAgent: PetstoreAgent +library: httr2 +additionalProperties: + packageName: petstore + exceptionPackage: rlang + useRlangExceptionHandling: true + returnExceptionOnFailure: true + errorObjectType: "ModelApiResponse" + operationIdNaming: snake_case + generateWrapper: true + useOneOfDiscriminatorLookup: true + disallowAdditionalPropertiesIfNotPresent: false diff --git a/bin/configs/ruby-autoload.yaml b/bin/configs/ruby-autoload.yaml new file mode 100644 index 0000000000..ee8e82896d --- /dev/null +++ b/bin/configs/ruby-autoload.yaml @@ -0,0 +1,12 @@ +generatorName: ruby +outputDir: samples/client/petstore/ruby-autoload +library: typhoeus +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/ruby-client +additionalProperties: + gemVersion: 1.0.0 + moduleName: Petstore + gemName: petstore + skipFormModel: "true" + useAutoload: true +strictSpecBehavior: false diff --git a/bin/configs/rust-reqwest-petstore-async.yaml b/bin/configs/rust-reqwest-petstore-async.yaml index e045f8485f..ed156ec550 100644 --- a/bin/configs/rust-reqwest-petstore-async.yaml +++ b/bin/configs/rust-reqwest-petstore-async.yaml @@ -1,7 +1,7 @@ generatorName: rust outputDir: samples/client/petstore/rust/reqwest/petstore-async library: reqwest -inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/rust additionalProperties: supportAsync: true diff --git a/bin/configs/rust-reqwest-petstore-awsv4signature.yaml b/bin/configs/rust-reqwest-petstore-awsv4signature.yaml index 82f44cae58..3ffd335719 100644 --- a/bin/configs/rust-reqwest-petstore-awsv4signature.yaml +++ b/bin/configs/rust-reqwest-petstore-awsv4signature.yaml @@ -1,7 +1,7 @@ generatorName: rust outputDir: samples/client/petstore/rust/reqwest/petstore-awsv4signature library: reqwest -inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/rust additionalProperties: supportAsync: false diff --git a/bin/configs/scala-sttp.yaml b/bin/configs/scala-sttp.yaml index 01e211c9a7..abcd83a23b 100644 --- a/bin/configs/scala-sttp.yaml +++ b/bin/configs/scala-sttp.yaml @@ -1,6 +1,6 @@ generatorName: scala-sttp outputDir: samples/client/petstore/scala-sttp -inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/scala/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/scala-sttp additionalProperties: artifactId: scala-sttp-petstore diff --git a/bin/configs/spring-boot-implicitHeaders-annotationLibrary.yaml b/bin/configs/spring-boot-implicitHeaders-annotationLibrary.yaml new file mode 100644 index 0000000000..7e9fb4758c --- /dev/null +++ b/bin/configs/spring-boot-implicitHeaders-annotationLibrary.yaml @@ -0,0 +1,10 @@ +generatorName: spring +outputDir: samples/server/petstore/springboot-implicitHeaders-annotationLibrary +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/JavaSpring +additionalProperties: + artifactId: springboot-implicitHeaders-annotationLibrary + documentationProvider: none + annotationLibrary: none + hideGenerationTimestamp: "true" + implicitHeadersRegex: .* diff --git a/bin/configs/spring-stubs.yaml b/bin/configs/spring-stubs.yaml index bdbefb1e58..349c5e229c 100644 --- a/bin/configs/spring-stubs.yaml +++ b/bin/configs/spring-stubs.yaml @@ -1,5 +1,5 @@ generatorName: spring -outputDir: samples/client/petstore/spring-stubs +outputDir: samples/server/petstore/spring-stubs inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/JavaSpring additionalProperties: diff --git a/bin/configs/swift5-alamofireLibrary.yaml b/bin/configs/swift5-alamofireLibrary.yaml index 4c248326d5..c21a158fcd 100644 --- a/bin/configs/swift5-alamofireLibrary.yaml +++ b/bin/configs/swift5-alamofireLibrary.yaml @@ -4,6 +4,7 @@ library: alamofire inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml templateDir: modules/openapi-generator/src/main/resources/swift5 generateAliasAsModel: true +useCustomDateWithoutTime: true additionalProperties: podAuthors: "" podSummary: PetstoreClient diff --git a/bin/configs/typescript-angular-v14-provided-in-root.yaml b/bin/configs/typescript-angular-v14-provided-in-root.yaml new file mode 100644 index 0000000000..d125554b05 --- /dev/null +++ b/bin/configs/typescript-angular-v14-provided-in-root.yaml @@ -0,0 +1,7 @@ +generatorName: typescript-angular +outputDir: samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-angular +additionalProperties: + ngVersion: 14.0.5 + supportsES6: true diff --git a/bin/configs/typescript-angular-v14-query-param-object-format.yaml b/bin/configs/typescript-angular-v14-query-param-object-format.yaml new file mode 100644 index 0000000000..f347fe5317 --- /dev/null +++ b/bin/configs/typescript-angular-v14-query-param-object-format.yaml @@ -0,0 +1,8 @@ +generatorName: typescript-angular +outputDir: samples/client/petstore/typescript-angular-v14-query-param-object-format +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-angular +additionalProperties: + ngVersion: 14.0.5 + supportsES6: true + queryParamObjectFormat: json diff --git a/bin/configs/typescript-axios-with-separate-models-and-api-inheritance.yaml b/bin/configs/typescript-axios-with-separate-models-and-api-inheritance.yaml new file mode 100644 index 0000000000..155f7f435f --- /dev/null +++ b/bin/configs/typescript-axios-with-separate-models-and-api-inheritance.yaml @@ -0,0 +1,8 @@ +generatorName: typescript-axios +outputDir: samples/client/others/typescript-axios/with-separate-models-and-api-inheritance +inputSpec: modules/openapi-generator/src/test/resources/3_0/typescript-axios/with-separate-models-and-api-inheritance.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-axios +additionalProperties: + apiPackage: api + modelPackage: model + withSeparateModelsAndApi: true diff --git a/bin/configs/typescript-fetch-allOf-readonly.yaml b/bin/configs/typescript-fetch-allOf-readonly.yaml new file mode 100644 index 0000000000..f872c77267 --- /dev/null +++ b/bin/configs/typescript-fetch-allOf-readonly.yaml @@ -0,0 +1,4 @@ +generatorName: typescript-fetch +outputDir: samples/client/petstore/typescript-fetch/builds/allOf-readonly +inputSpec: modules/openapi-generator/src/test/resources/3_0/allOf-readonly.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-fetch diff --git a/bin/configs/typescript-nestjs-v8-provided-in-root.yaml b/bin/configs/typescript-nestjs-v8-provided-in-root.yaml new file mode 100644 index 0000000000..16a957708c --- /dev/null +++ b/bin/configs/typescript-nestjs-v8-provided-in-root.yaml @@ -0,0 +1,10 @@ +generatorName: typescript-nestjs +outputDir: samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-nestjs +additionalProperties: + nestVersion: 8.0.0 + "npmName": "@openapitools/typescript-nestjs-petstore" + "npmVersion": "1.0.0" + "npmRepository" : "https://skimdb.npmjs.com/registry" + "snapshot" : false diff --git a/bin/configs/unmaintained/README.md b/bin/configs/unmaintained/README.md new file mode 100644 index 0000000000..b00f3e1a7a --- /dev/null +++ b/bin/configs/unmaintained/README.md @@ -0,0 +1,8 @@ +# Unmaintained Sample Configs + +These are legacy configs which are no longer maintained. This means: + +- They are not automatically generated when using the `./bin/generate-samples.sh` command (unless you manually specify + the paths) +- The merge checks will not ensure that the corresponding samples have been generated or are up-to-date. +- The sample code currently in Git is unlikely to be up-to-date. diff --git a/bin/configs/other/ada.yaml b/bin/configs/unmaintained/ada.yaml similarity index 100% rename from bin/configs/other/ada.yaml rename to bin/configs/unmaintained/ada.yaml diff --git a/bin/configs/other/android-httpclient.yaml b/bin/configs/unmaintained/android-httpclient.yaml similarity index 100% rename from bin/configs/other/android-httpclient.yaml rename to bin/configs/unmaintained/android-httpclient.yaml diff --git a/bin/configs/other/android-volley.yaml b/bin/configs/unmaintained/android-volley.yaml similarity index 100% rename from bin/configs/other/android-volley.yaml rename to bin/configs/unmaintained/android-volley.yaml diff --git a/bin/configs/other/apache2.yaml b/bin/configs/unmaintained/apache2.yaml similarity index 100% rename from bin/configs/other/apache2.yaml rename to bin/configs/unmaintained/apache2.yaml diff --git a/bin/configs/other/asciidoc.yaml b/bin/configs/unmaintained/asciidoc.yaml similarity index 100% rename from bin/configs/other/asciidoc.yaml rename to bin/configs/unmaintained/asciidoc.yaml diff --git a/bin/configs/other/clojure.yaml b/bin/configs/unmaintained/clojure.yaml similarity index 100% rename from bin/configs/other/clojure.yaml rename to bin/configs/unmaintained/clojure.yaml diff --git a/bin/configs/unmaintained/cpp-restbed-server.yaml b/bin/configs/unmaintained/cpp-restbed-server.yaml new file mode 100644 index 0000000000..d7242c4b60 --- /dev/null +++ b/bin/configs/unmaintained/cpp-restbed-server.yaml @@ -0,0 +1,4 @@ +generatorName: cpp-restbed-server +outputDir: samples/server/petstore/cpp-restbed/generated/2_0 +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/cpp-restbed-server diff --git a/bin/configs/other/cpp-tizen.yaml b/bin/configs/unmaintained/cpp-tizen.yaml similarity index 100% rename from bin/configs/other/cpp-tizen.yaml rename to bin/configs/unmaintained/cpp-tizen.yaml diff --git a/bin/configs/other/csharp-OpenAPIClientNet35.yaml b/bin/configs/unmaintained/csharp-OpenAPIClientNet35.yaml similarity index 100% rename from bin/configs/other/csharp-OpenAPIClientNet35.yaml rename to bin/configs/unmaintained/csharp-OpenAPIClientNet35.yaml diff --git a/bin/configs/other/csharp-OpenAPIClientNet40.yaml b/bin/configs/unmaintained/csharp-OpenAPIClientNet40.yaml similarity index 100% rename from bin/configs/other/csharp-OpenAPIClientNet40.yaml rename to bin/configs/unmaintained/csharp-OpenAPIClientNet40.yaml diff --git a/bin/configs/other/csharp-OpenAPIClientNetCoreProject.yaml b/bin/configs/unmaintained/csharp-OpenAPIClientNetCoreProject.yaml similarity index 100% rename from bin/configs/other/csharp-OpenAPIClientNetCoreProject.yaml rename to bin/configs/unmaintained/csharp-OpenAPIClientNetCoreProject.yaml diff --git a/bin/configs/other/csharp-OpenAPIClientNetStandard.yaml b/bin/configs/unmaintained/csharp-OpenAPIClientNetStandard.yaml similarity index 100% rename from bin/configs/other/csharp-OpenAPIClientNetStandard.yaml rename to bin/configs/unmaintained/csharp-OpenAPIClientNetStandard.yaml diff --git a/bin/configs/other/csharp-OpenAPIClientWithPropertyChanged.yaml b/bin/configs/unmaintained/csharp-OpenAPIClientWithPropertyChanged.yaml similarity index 100% rename from bin/configs/other/csharp-OpenAPIClientWithPropertyChanged.yaml rename to bin/configs/unmaintained/csharp-OpenAPIClientWithPropertyChanged.yaml diff --git a/bin/configs/other/csharp-dotnet2-OpenAPIClient.yaml b/bin/configs/unmaintained/csharp-dotnet2-OpenAPIClient.yaml similarity index 100% rename from bin/configs/other/csharp-dotnet2-OpenAPIClient.yaml rename to bin/configs/unmaintained/csharp-dotnet2-OpenAPIClient.yaml diff --git a/bin/configs/other/cwiki.yaml b/bin/configs/unmaintained/cwiki.yaml similarity index 100% rename from bin/configs/other/cwiki.yaml rename to bin/configs/unmaintained/cwiki.yaml diff --git a/bin/configs/other/dynamic-html.yaml b/bin/configs/unmaintained/dynamic-html.yaml similarity index 100% rename from bin/configs/other/dynamic-html.yaml rename to bin/configs/unmaintained/dynamic-html.yaml diff --git a/bin/configs/other/eiffel.yaml b/bin/configs/unmaintained/eiffel.yaml similarity index 100% rename from bin/configs/other/eiffel.yaml rename to bin/configs/unmaintained/eiffel.yaml diff --git a/bin/configs/other/erlang-client.yaml b/bin/configs/unmaintained/erlang-client.yaml similarity index 100% rename from bin/configs/other/erlang-client.yaml rename to bin/configs/unmaintained/erlang-client.yaml diff --git a/bin/configs/other/erlang-proper.yaml b/bin/configs/unmaintained/erlang-proper.yaml similarity index 100% rename from bin/configs/other/erlang-proper.yaml rename to bin/configs/unmaintained/erlang-proper.yaml diff --git a/bin/configs/other/fsharp-functions.yaml b/bin/configs/unmaintained/fsharp-functions.yaml similarity index 100% rename from bin/configs/other/fsharp-functions.yaml rename to bin/configs/unmaintained/fsharp-functions.yaml diff --git a/bin/configs/other/fsharp-giraffe-server-fsharp-giraffe.yaml b/bin/configs/unmaintained/fsharp-giraffe-server-fsharp-giraffe.yaml similarity index 100% rename from bin/configs/other/fsharp-giraffe-server-fsharp-giraffe.yaml rename to bin/configs/unmaintained/fsharp-giraffe-server-fsharp-giraffe.yaml diff --git a/bin/configs/other/graphql-nodejs-express-server.yaml b/bin/configs/unmaintained/graphql-nodejs-express-server.yaml similarity index 100% rename from bin/configs/other/graphql-nodejs-express-server.yaml rename to bin/configs/unmaintained/graphql-nodejs-express-server.yaml diff --git a/bin/configs/other/graphql-schema.yaml b/bin/configs/unmaintained/graphql-schema.yaml similarity index 100% rename from bin/configs/other/graphql-schema.yaml rename to bin/configs/unmaintained/graphql-schema.yaml diff --git a/bin/configs/other/html.md.yaml b/bin/configs/unmaintained/html.md.yaml similarity index 100% rename from bin/configs/other/html.md.yaml rename to bin/configs/unmaintained/html.md.yaml diff --git a/bin/configs/other/html.yaml b/bin/configs/unmaintained/html.yaml similarity index 100% rename from bin/configs/other/html.yaml rename to bin/configs/unmaintained/html.yaml diff --git a/bin/configs/other/html2.yaml b/bin/configs/unmaintained/html2.yaml similarity index 100% rename from bin/configs/other/html2.yaml rename to bin/configs/unmaintained/html2.yaml diff --git a/bin/configs/other/java-inflector.yaml b/bin/configs/unmaintained/java-inflector.yaml similarity index 100% rename from bin/configs/other/java-inflector.yaml rename to bin/configs/unmaintained/java-inflector.yaml diff --git a/bin/configs/other/java-native-async.yaml b/bin/configs/unmaintained/java-native-async.yaml similarity index 100% rename from bin/configs/other/java-native-async.yaml rename to bin/configs/unmaintained/java-native-async.yaml diff --git a/bin/configs/other/java-pkmst.yaml b/bin/configs/unmaintained/java-pkmst.yaml similarity index 100% rename from bin/configs/other/java-pkmst.yaml rename to bin/configs/unmaintained/java-pkmst.yaml diff --git a/bin/configs/other/java-vertx-async.yaml b/bin/configs/unmaintained/java-vertx-async.yaml similarity index 100% rename from bin/configs/other/java-vertx-async.yaml rename to bin/configs/unmaintained/java-vertx-async.yaml diff --git a/bin/configs/other/java-vertx-rx.yaml b/bin/configs/unmaintained/java-vertx-rx.yaml similarity index 100% rename from bin/configs/other/java-vertx-rx.yaml rename to bin/configs/unmaintained/java-vertx-rx.yaml diff --git a/bin/configs/other/javascript-closure-angular.yaml b/bin/configs/unmaintained/javascript-closure-angular.yaml similarity index 100% rename from bin/configs/other/javascript-closure-angular.yaml rename to bin/configs/unmaintained/javascript-closure-angular.yaml diff --git a/bin/configs/other/javascript-flowtyped.yaml b/bin/configs/unmaintained/javascript-flowtyped.yaml similarity index 100% rename from bin/configs/other/javascript-flowtyped.yaml rename to bin/configs/unmaintained/javascript-flowtyped.yaml diff --git a/bin/configs/other/jaxrs-cxf-client-jackson.yaml b/bin/configs/unmaintained/jaxrs-cxf-client-jackson.yaml similarity index 100% rename from bin/configs/other/jaxrs-cxf-client-jackson.yaml rename to bin/configs/unmaintained/jaxrs-cxf-client-jackson.yaml diff --git a/bin/configs/other/jaxrs-cxf-client.yaml b/bin/configs/unmaintained/jaxrs-cxf-client.yaml similarity index 100% rename from bin/configs/other/jaxrs-cxf-client.yaml rename to bin/configs/unmaintained/jaxrs-cxf-client.yaml diff --git a/bin/configs/other/jaxrs-cxf-extended-jaxrs-cxf-test-data.yaml b/bin/configs/unmaintained/jaxrs-cxf-extended-jaxrs-cxf-test-data.yaml similarity index 100% rename from bin/configs/other/jaxrs-cxf-extended-jaxrs-cxf-test-data.yaml rename to bin/configs/unmaintained/jaxrs-cxf-extended-jaxrs-cxf-test-data.yaml diff --git a/bin/configs/other/jaxrs-spec-interface-response.yaml b/bin/configs/unmaintained/jaxrs-spec-interface-response.yaml similarity index 100% rename from bin/configs/other/jaxrs-spec-interface-response.yaml rename to bin/configs/unmaintained/jaxrs-spec-interface-response.yaml diff --git a/bin/configs/other/jmeter.yaml b/bin/configs/unmaintained/jmeter.yaml similarity index 100% rename from bin/configs/other/jmeter.yaml rename to bin/configs/unmaintained/jmeter.yaml diff --git a/bin/configs/other/k6.yaml b/bin/configs/unmaintained/k6.yaml similarity index 100% rename from bin/configs/other/k6.yaml rename to bin/configs/unmaintained/k6.yaml diff --git a/bin/configs/other/kotlin-jvm-retrofit2-coroutines.yaml b/bin/configs/unmaintained/kotlin-jvm-retrofit2-coroutines.yaml similarity index 100% rename from bin/configs/other/kotlin-jvm-retrofit2-coroutines.yaml rename to bin/configs/unmaintained/kotlin-jvm-retrofit2-coroutines.yaml diff --git a/bin/configs/other/kotlin-jvm-retrofit2-rx.yaml b/bin/configs/unmaintained/kotlin-jvm-retrofit2-rx.yaml similarity index 100% rename from bin/configs/other/kotlin-jvm-retrofit2-rx.yaml rename to bin/configs/unmaintained/kotlin-jvm-retrofit2-rx.yaml diff --git a/bin/configs/other/kotlin-jvm-retrofit2-rx2-kotlinx_serialization.yaml b/bin/configs/unmaintained/kotlin-jvm-retrofit2-rx2-kotlinx_serialization.yaml similarity index 100% rename from bin/configs/other/kotlin-jvm-retrofit2-rx2-kotlinx_serialization.yaml rename to bin/configs/unmaintained/kotlin-jvm-retrofit2-rx2-kotlinx_serialization.yaml diff --git a/bin/configs/other/kotlin-jvm-retrofit2-rx2.yaml b/bin/configs/unmaintained/kotlin-jvm-retrofit2-rx2.yaml similarity index 100% rename from bin/configs/other/kotlin-jvm-retrofit2-rx2.yaml rename to bin/configs/unmaintained/kotlin-jvm-retrofit2-rx2.yaml diff --git a/bin/configs/other/kotlin-multiplatform.yaml b/bin/configs/unmaintained/kotlin-multiplatform.yaml similarity index 100% rename from bin/configs/other/kotlin-multiplatform.yaml rename to bin/configs/unmaintained/kotlin-multiplatform.yaml diff --git a/bin/configs/other/kotlin-spring-boot-reactive.yaml b/bin/configs/unmaintained/kotlin-spring-boot-reactive.yaml similarity index 100% rename from bin/configs/other/kotlin-spring-boot-reactive.yaml rename to bin/configs/unmaintained/kotlin-spring-boot-reactive.yaml diff --git a/bin/configs/other/kotlin-spring-boot.yaml b/bin/configs/unmaintained/kotlin-spring-boot.yaml similarity index 100% rename from bin/configs/other/kotlin-spring-boot.yaml rename to bin/configs/unmaintained/kotlin-spring-boot.yaml diff --git a/bin/configs/other/kotlin.yaml b/bin/configs/unmaintained/kotlin.yaml similarity index 100% rename from bin/configs/other/kotlin.yaml rename to bin/configs/unmaintained/kotlin.yaml diff --git a/bin/configs/other/markdown.yaml b/bin/configs/unmaintained/markdown.yaml similarity index 100% rename from bin/configs/other/markdown.yaml rename to bin/configs/unmaintained/markdown.yaml diff --git a/bin/configs/other/nodejs-express-server.yaml b/bin/configs/unmaintained/nodejs-express-server.yaml similarity index 100% rename from bin/configs/other/nodejs-express-server.yaml rename to bin/configs/unmaintained/nodejs-express-server.yaml diff --git a/bin/configs/other/objc-core-data.yaml b/bin/configs/unmaintained/objc-core-data.yaml similarity index 100% rename from bin/configs/other/objc-core-data.yaml rename to bin/configs/unmaintained/objc-core-data.yaml diff --git a/bin/configs/other/objc-default.yaml b/bin/configs/unmaintained/objc-default.yaml similarity index 100% rename from bin/configs/other/objc-default.yaml rename to bin/configs/unmaintained/objc-default.yaml diff --git a/bin/configs/other/ocaml.yaml b/bin/configs/unmaintained/ocaml.yaml similarity index 100% rename from bin/configs/other/ocaml.yaml rename to bin/configs/unmaintained/ocaml.yaml diff --git a/bin/configs/other/openapi3/android-httpclient.yaml b/bin/configs/unmaintained/openapi3/android-httpclient.yaml similarity index 100% rename from bin/configs/other/openapi3/android-httpclient.yaml rename to bin/configs/unmaintained/openapi3/android-httpclient.yaml diff --git a/bin/configs/other/openapi3/android-volley.yaml b/bin/configs/unmaintained/openapi3/android-volley.yaml similarity index 100% rename from bin/configs/other/openapi3/android-volley.yaml rename to bin/configs/unmaintained/openapi3/android-volley.yaml diff --git a/bin/configs/other/openapi3/avro-schema.yaml b/bin/configs/unmaintained/openapi3/avro-schema.yaml similarity index 100% rename from bin/configs/other/openapi3/avro-schema.yaml rename to bin/configs/unmaintained/openapi3/avro-schema.yaml diff --git a/bin/configs/other/openapi3/bash.yaml b/bin/configs/unmaintained/openapi3/bash.yaml similarity index 100% rename from bin/configs/other/openapi3/bash.yaml rename to bin/configs/unmaintained/openapi3/bash.yaml diff --git a/bin/configs/other/openapi3/clojure.yaml b/bin/configs/unmaintained/openapi3/clojure.yaml similarity index 100% rename from bin/configs/other/openapi3/clojure.yaml rename to bin/configs/unmaintained/openapi3/clojure.yaml diff --git a/bin/configs/other/openapi3/cpp-pistache-server-cpp-pistache.yaml b/bin/configs/unmaintained/openapi3/cpp-pistache-server-cpp-pistache.yaml similarity index 100% rename from bin/configs/other/openapi3/cpp-pistache-server-cpp-pistache.yaml rename to bin/configs/unmaintained/openapi3/cpp-pistache-server-cpp-pistache.yaml diff --git a/bin/configs/other/openapi3/cpp-qt5-client-cpp-qt5.yaml b/bin/configs/unmaintained/openapi3/cpp-qt5-client-cpp-qt5.yaml similarity index 100% rename from bin/configs/other/openapi3/cpp-qt5-client-cpp-qt5.yaml rename to bin/configs/unmaintained/openapi3/cpp-qt5-client-cpp-qt5.yaml diff --git a/bin/configs/other/openapi3/cpp-qt5-qhttpengine-server.yaml b/bin/configs/unmaintained/openapi3/cpp-qt5-qhttpengine-server.yaml similarity index 100% rename from bin/configs/other/openapi3/cpp-qt5-qhttpengine-server.yaml rename to bin/configs/unmaintained/openapi3/cpp-qt5-qhttpengine-server.yaml diff --git a/bin/configs/unmaintained/openapi3/cpp-restbed-server-cpp-restbed-deprecated.yaml b/bin/configs/unmaintained/openapi3/cpp-restbed-server-cpp-restbed-deprecated.yaml new file mode 100644 index 0000000000..8a9b93fffe --- /dev/null +++ b/bin/configs/unmaintained/openapi3/cpp-restbed-server-cpp-restbed-deprecated.yaml @@ -0,0 +1,4 @@ +generatorName: cpp-restbed-server-deprecated +outputDir: samples/server/petstore/cpp-restbed-deprecated +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated diff --git a/bin/configs/unmaintained/openapi3/cpp-restbed-server-cpp-restbed.yaml b/bin/configs/unmaintained/openapi3/cpp-restbed-server-cpp-restbed.yaml new file mode 100644 index 0000000000..6dc3929ec0 --- /dev/null +++ b/bin/configs/unmaintained/openapi3/cpp-restbed-server-cpp-restbed.yaml @@ -0,0 +1,4 @@ +generatorName: cpp-restbed-server +outputDir: samples/server/petstore/cpp-restbed/generated/3_0 +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/cpp-restbed-server diff --git a/bin/configs/other/openapi3/cpp-tizen.yaml b/bin/configs/unmaintained/openapi3/cpp-tizen.yaml similarity index 100% rename from bin/configs/other/openapi3/cpp-tizen.yaml rename to bin/configs/unmaintained/openapi3/cpp-tizen.yaml diff --git a/bin/configs/other/openapi3/csharp-OpenAPIClient.yaml b/bin/configs/unmaintained/openapi3/csharp-OpenAPIClient.yaml similarity index 100% rename from bin/configs/other/openapi3/csharp-OpenAPIClient.yaml rename to bin/configs/unmaintained/openapi3/csharp-OpenAPIClient.yaml diff --git a/bin/configs/other/openapi3/csharp-OpenAPIClientNetStandard.yaml b/bin/configs/unmaintained/openapi3/csharp-OpenAPIClientNetStandard.yaml similarity index 100% rename from bin/configs/other/openapi3/csharp-OpenAPIClientNetStandard.yaml rename to bin/configs/unmaintained/openapi3/csharp-OpenAPIClientNetStandard.yaml diff --git a/bin/configs/other/openapi3/csharp-OpenAPIClientWithPropertyChanged.yaml b/bin/configs/unmaintained/openapi3/csharp-OpenAPIClientWithPropertyChanged.yaml similarity index 100% rename from bin/configs/other/openapi3/csharp-OpenAPIClientWithPropertyChanged.yaml rename to bin/configs/unmaintained/openapi3/csharp-OpenAPIClientWithPropertyChanged.yaml diff --git a/bin/configs/other/openapi3/csharp-dotnet2-OpenAPIClient.yaml b/bin/configs/unmaintained/openapi3/csharp-dotnet2-OpenAPIClient.yaml similarity index 100% rename from bin/configs/other/openapi3/csharp-dotnet2-OpenAPIClient.yaml rename to bin/configs/unmaintained/openapi3/csharp-dotnet2-OpenAPIClient.yaml diff --git a/bin/configs/other/openapi3/elixir.yaml b/bin/configs/unmaintained/openapi3/elixir.yaml similarity index 100% rename from bin/configs/other/openapi3/elixir.yaml rename to bin/configs/unmaintained/openapi3/elixir.yaml diff --git a/bin/configs/other/openapi3/go-gin-server-go-gin-api-server.yaml b/bin/configs/unmaintained/openapi3/go-gin-server-go-gin-api-server.yaml similarity index 100% rename from bin/configs/other/openapi3/go-gin-server-go-gin-api-server.yaml rename to bin/configs/unmaintained/openapi3/go-gin-server-go-gin-api-server.yaml diff --git a/bin/configs/other/openapi3/go-petstore.yaml b/bin/configs/unmaintained/openapi3/go-petstore.yaml similarity index 100% rename from bin/configs/other/openapi3/go-petstore.yaml rename to bin/configs/unmaintained/openapi3/go-petstore.yaml diff --git a/bin/configs/other/openapi3/go-server-go-api-server.yaml b/bin/configs/unmaintained/openapi3/go-server-go-api-server.yaml similarity index 100% rename from bin/configs/other/openapi3/go-server-go-api-server.yaml rename to bin/configs/unmaintained/openapi3/go-server-go-api-server.yaml diff --git a/bin/configs/other/openapi3/graphql-nodejs-express-server.yaml b/bin/configs/unmaintained/openapi3/graphql-nodejs-express-server.yaml similarity index 100% rename from bin/configs/other/openapi3/graphql-nodejs-express-server.yaml rename to bin/configs/unmaintained/openapi3/graphql-nodejs-express-server.yaml diff --git a/bin/configs/other/openapi3/haskell-http-client.yaml b/bin/configs/unmaintained/openapi3/haskell-http-client.yaml similarity index 100% rename from bin/configs/other/openapi3/haskell-http-client.yaml rename to bin/configs/unmaintained/openapi3/haskell-http-client.yaml diff --git a/bin/configs/other/openapi3/haskell-servant.yaml b/bin/configs/unmaintained/openapi3/haskell-servant.yaml similarity index 100% rename from bin/configs/other/openapi3/haskell-servant.yaml rename to bin/configs/unmaintained/openapi3/haskell-servant.yaml diff --git a/bin/configs/other/openapi3/javascript-closure-angular.yaml b/bin/configs/unmaintained/openapi3/javascript-closure-angular.yaml similarity index 100% rename from bin/configs/other/openapi3/javascript-closure-angular.yaml rename to bin/configs/unmaintained/openapi3/javascript-closure-angular.yaml diff --git a/bin/configs/other/openapi3/jaxrs-cxf-client-jackson-nullable.yaml b/bin/configs/unmaintained/openapi3/jaxrs-cxf-client-jackson-nullable.yaml similarity index 100% rename from bin/configs/other/openapi3/jaxrs-cxf-client-jackson-nullable.yaml rename to bin/configs/unmaintained/openapi3/jaxrs-cxf-client-jackson-nullable.yaml diff --git a/bin/configs/other/openapi3/jaxrs-cxf-client.yaml b/bin/configs/unmaintained/openapi3/jaxrs-cxf-client.yaml similarity index 100% rename from bin/configs/other/openapi3/jaxrs-cxf-client.yaml rename to bin/configs/unmaintained/openapi3/jaxrs-cxf-client.yaml diff --git a/bin/configs/other/openapi3/php-laravel.yaml b/bin/configs/unmaintained/openapi3/php-laravel.yaml similarity index 100% rename from bin/configs/other/openapi3/php-laravel.yaml rename to bin/configs/unmaintained/openapi3/php-laravel.yaml diff --git a/bin/configs/other/openapi3/php-slim4.yaml b/bin/configs/unmaintained/openapi3/php-slim4.yaml similarity index 100% rename from bin/configs/other/openapi3/php-slim4.yaml rename to bin/configs/unmaintained/openapi3/php-slim4.yaml diff --git a/bin/configs/other/openapi3/php-symfony-SymfonyBundle-php.yaml b/bin/configs/unmaintained/openapi3/php-symfony-SymfonyBundle-php.yaml similarity index 100% rename from bin/configs/other/openapi3/php-symfony-SymfonyBundle-php.yaml rename to bin/configs/unmaintained/openapi3/php-symfony-SymfonyBundle-php.yaml diff --git a/bin/configs/other/openapi3/python-flask-python2.yaml b/bin/configs/unmaintained/openapi3/python-flask-python2.yaml similarity index 100% rename from bin/configs/other/openapi3/python-flask-python2.yaml rename to bin/configs/unmaintained/openapi3/python-flask-python2.yaml diff --git a/bin/configs/other/openapi3/python-flask.yaml b/bin/configs/unmaintained/openapi3/python-flask.yaml similarity index 100% rename from bin/configs/other/openapi3/python-flask.yaml rename to bin/configs/unmaintained/openapi3/python-flask.yaml diff --git a/bin/configs/other/openapi3/r-R.yaml b/bin/configs/unmaintained/openapi3/r-R.yaml similarity index 100% rename from bin/configs/other/openapi3/r-R.yaml rename to bin/configs/unmaintained/openapi3/r-R.yaml diff --git a/bin/configs/other/openapi3/rust.yaml b/bin/configs/unmaintained/openapi3/rust.yaml similarity index 100% rename from bin/configs/other/openapi3/rust.yaml rename to bin/configs/unmaintained/openapi3/rust.yaml diff --git a/bin/configs/other/openapi3/scala-finch.yaml b/bin/configs/unmaintained/openapi3/scala-finch.yaml similarity index 100% rename from bin/configs/other/openapi3/scala-finch.yaml rename to bin/configs/unmaintained/openapi3/scala-finch.yaml diff --git a/bin/configs/other/openapi3/typescript-angular-default.yaml b/bin/configs/unmaintained/openapi3/typescript-angular-default.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-angular-default.yaml rename to bin/configs/unmaintained/openapi3/typescript-angular-default.yaml diff --git a/bin/configs/other/openapi3/typescript-angular-npm.yaml b/bin/configs/unmaintained/openapi3/typescript-angular-npm.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-angular-npm.yaml rename to bin/configs/unmaintained/openapi3/typescript-angular-npm.yaml diff --git a/bin/configs/other/openapi3/typescript-angular-with-interfaces.yaml b/bin/configs/unmaintained/openapi3/typescript-angular-with-interfaces.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-angular-with-interfaces.yaml rename to bin/configs/unmaintained/openapi3/typescript-angular-with-interfaces.yaml diff --git a/bin/configs/other/openapi3/typescript-aurelia-default.yaml b/bin/configs/unmaintained/openapi3/typescript-aurelia-default.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-aurelia-default.yaml rename to bin/configs/unmaintained/openapi3/typescript-aurelia-default.yaml diff --git a/bin/configs/other/openapi3/typescript-fetch-default.yaml b/bin/configs/unmaintained/openapi3/typescript-fetch-default.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-fetch-default.yaml rename to bin/configs/unmaintained/openapi3/typescript-fetch-default.yaml diff --git a/bin/configs/other/openapi3/typescript-fetch-es6-target.yaml b/bin/configs/unmaintained/openapi3/typescript-fetch-es6-target.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-fetch-es6-target.yaml rename to bin/configs/unmaintained/openapi3/typescript-fetch-es6-target.yaml diff --git a/bin/configs/other/openapi3/typescript-fetch-with-interfaces.yaml b/bin/configs/unmaintained/openapi3/typescript-fetch-with-interfaces.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-fetch-with-interfaces.yaml rename to bin/configs/unmaintained/openapi3/typescript-fetch-with-interfaces.yaml diff --git a/bin/configs/other/openapi3/typescript-fetch-with-npm-version.yaml b/bin/configs/unmaintained/openapi3/typescript-fetch-with-npm-version.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-fetch-with-npm-version.yaml rename to bin/configs/unmaintained/openapi3/typescript-fetch-with-npm-version.yaml diff --git a/bin/configs/other/openapi3/typescript-inversify.yaml b/bin/configs/unmaintained/openapi3/typescript-inversify.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-inversify.yaml rename to bin/configs/unmaintained/openapi3/typescript-inversify.yaml diff --git a/bin/configs/other/openapi3/typescript-jquery-default.yaml b/bin/configs/unmaintained/openapi3/typescript-jquery-default.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-jquery-default.yaml rename to bin/configs/unmaintained/openapi3/typescript-jquery-default.yaml diff --git a/bin/configs/other/openapi3/typescript-jquery-npm.yaml b/bin/configs/unmaintained/openapi3/typescript-jquery-npm.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-jquery-npm.yaml rename to bin/configs/unmaintained/openapi3/typescript-jquery-npm.yaml diff --git a/bin/configs/other/openapi3/typescript-node-default.yaml b/bin/configs/unmaintained/openapi3/typescript-node-default.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-node-default.yaml rename to bin/configs/unmaintained/openapi3/typescript-node-default.yaml diff --git a/bin/configs/other/openapi3/typescript-node-npm.yaml b/bin/configs/unmaintained/openapi3/typescript-node-npm.yaml similarity index 100% rename from bin/configs/other/openapi3/typescript-node-npm.yaml rename to bin/configs/unmaintained/openapi3/typescript-node-npm.yaml diff --git a/bin/configs/other/php-laravel.yaml b/bin/configs/unmaintained/php-laravel.yaml similarity index 100% rename from bin/configs/other/php-laravel.yaml rename to bin/configs/unmaintained/php-laravel.yaml diff --git a/bin/configs/other/php-slim4.yaml b/bin/configs/unmaintained/php-slim4.yaml similarity index 100% rename from bin/configs/other/php-slim4.yaml rename to bin/configs/unmaintained/php-slim4.yaml diff --git a/bin/configs/other/plantuml.yaml b/bin/configs/unmaintained/plantuml.yaml similarity index 100% rename from bin/configs/other/plantuml.yaml rename to bin/configs/unmaintained/plantuml.yaml diff --git a/bin/configs/other/ruby-on-rails.yaml b/bin/configs/unmaintained/ruby-on-rails.yaml similarity index 100% rename from bin/configs/other/ruby-on-rails.yaml rename to bin/configs/unmaintained/ruby-on-rails.yaml diff --git a/bin/configs/other/ruby-sinatra.yaml b/bin/configs/unmaintained/ruby-sinatra.yaml similarity index 100% rename from bin/configs/other/ruby-sinatra.yaml rename to bin/configs/unmaintained/ruby-sinatra.yaml diff --git a/bin/configs/other/scala-finch.yaml b/bin/configs/unmaintained/scala-finch.yaml similarity index 100% rename from bin/configs/other/scala-finch.yaml rename to bin/configs/unmaintained/scala-finch.yaml diff --git a/bin/configs/other/scala-gatling.yaml b/bin/configs/unmaintained/scala-gatling.yaml similarity index 100% rename from bin/configs/other/scala-gatling.yaml rename to bin/configs/unmaintained/scala-gatling.yaml diff --git a/bin/configs/other/scala-httpclient-deprecated-scala-httpclient.yaml b/bin/configs/unmaintained/scala-httpclient-deprecated-scala-httpclient.yaml similarity index 100% rename from bin/configs/other/scala-httpclient-deprecated-scala-httpclient.yaml rename to bin/configs/unmaintained/scala-httpclient-deprecated-scala-httpclient.yaml diff --git a/bin/configs/other/scala-lagom-server.yaml b/bin/configs/unmaintained/scala-lagom-server.yaml similarity index 100% rename from bin/configs/other/scala-lagom-server.yaml rename to bin/configs/unmaintained/scala-lagom-server.yaml diff --git a/bin/configs/other/scala-play-server.yaml b/bin/configs/unmaintained/scala-play-server.yaml similarity index 100% rename from bin/configs/other/scala-play-server.yaml rename to bin/configs/unmaintained/scala-play-server.yaml diff --git a/bin/configs/other/scalatra.yaml b/bin/configs/unmaintained/scalatra.yaml similarity index 100% rename from bin/configs/other/scalatra.yaml rename to bin/configs/unmaintained/scalatra.yaml diff --git a/bin/configs/other/scalaz.yaml b/bin/configs/unmaintained/scalaz.yaml similarity index 100% rename from bin/configs/other/scalaz.yaml rename to bin/configs/unmaintained/scalaz.yaml diff --git a/bin/configs/other/typescript-redux-query-default.yaml b/bin/configs/unmaintained/typescript-redux-query-default.yaml similarity index 100% rename from bin/configs/other/typescript-redux-query-default.yaml rename to bin/configs/unmaintained/typescript-redux-query-default.yaml diff --git a/bin/utils/detect_tab_in_templates.sh b/bin/utils/detect_tab_in_templates.sh index e3ac60b104..070b47e8a4 100755 --- a/bin/utils/detect_tab_in_templates.sh +++ b/bin/utils/detect_tab_in_templates.sh @@ -6,11 +6,11 @@ ## declare an array of folders declare -a samples=("modules/openapi-generator/src/main/resources/kotlin-server" "modules/openapi-generator/src/main/resources/kotlin-spring" - "modules/openapi-generator/src/main/resources/dart-dio" "modules/openapi-generator/src/main/resources/dart" "modules/openapi-generator/src/main/resources/dart2" "modules/openapi-generator/src/main/resources/aspnetcore" "modules/openapi-generator/src/main/resources/powershell" + "modules/openapi-generator/src/main/resources/r" ) ## now loop through the above array diff --git a/bin/utils/test_file_list.yaml b/bin/utils/test_file_list.yaml index 286c876104..e294749026 100644 --- a/bin/utils/test_file_list.yaml +++ b/bin/utils/test_file_list.yaml @@ -1,7 +1,7 @@ --- # csharp-netcore test files and image for upload - filename: "samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/JSONComposedSchemaTests.cs" - sha256: 95e40cace36e7cd1608fa494161f06291f4cfb8f859ec4196ae9939f520b152a + sha256: aaa596db60531417994533b0e7962eca21dcaf8fa3aea1e2e3cb8b1b216cb89f - filename: "samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs" sha256: dae985015ba461297927d544a78267f2def35e07c3f14ca66468fd61e1fd1c26 - filename: "samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/linux-logo.png" diff --git a/docs/contributing.md b/docs/contributing.md index f47d79bd09..de8dcade6b 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -56,15 +56,15 @@ Code change should conform to the programming style guide of the respective lang - Clojure: https://github.com/bbatsov/clojure-style-guide - Crystal: https://crystal-lang.org/reference/conventions/coding_style.html - Dart: https://www.dartlang.org/guides/language/effective-dart/style -- Elixir: https://github.com/christopheradams/elixir_style_guide - Eiffel: https://www.eiffel.org/doc/eiffel/Coding%20Standards +- Elixir: https://github.com/christopheradams/elixir_style_guide - Erlang: https://github.com/inaka/erlang_guidelines +- Go: https://github.com/golang/go/wiki/CodeReviewComments +- Groovy: http://groovy-lang.org/style-guide.html - Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md - Java: https://google.github.io/styleguide/javaguide.html - JavaScript: https://github.com/airbnb/javascript/ - Kotlin: https://kotlinlang.org/docs/reference/coding-conventions.html -- Groovy: http://groovy-lang.org/style-guide.html -- Go: https://github.com/golang/go/wiki/CodeReviewComments - ObjC: https://github.com/NYTimes/objective-c-style-guide - Perl: http://perldoc.perl.org/perlstyle.html - PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-12-extended-coding-style-guide.md @@ -94,7 +94,7 @@ To test the templates, please perform the following: - Update the Petstore sample by running the shell scripts under the `bin` folder. For example, run `./bin/generate-samples.sh ./bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/tree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files generated or unexpected changes as a result of the update, that's not unusual as the test cases are added to the OpenAPI spec from time to time. If you've questions or concerns, please open a ticket to start a discussion) - During development, it can be helpful to quickly regenerate the samples without recompiling all of openapi-generator, e.g. when you have only updated the mustache templates. This can be done by passing the `-t` parameter: `-t modules/openapi-generator/src/main/resources/python`. -- Run the tests in the sample folder using maven `mvn integration-test -f /path/to/pom.xml`, e.g. `mvn integration-test -f samples/client/petstore/python/pom.xml`. (some languages may not contain unit testing for Petstore and we're looking for contribution from the community to implement those tests) +- Run the tests in the sample folder using maven `mvn integration-test -f /path/to/pom.xml`, e.g. `mvn integration-test -f samples/client/petstore/python/pom.xml`. (some languages may not contain unit testing for Petstore and we're looking for contribution from the community to implement those tests). __Please notice:__ you must run a local instance of the Petstore server in order to perform the tests, as running them against petstore.swagger.io is not supported anymore. Please refer to item 3 of [Integration Tests - How to add integration tests for new Petstore samples](https://github.com/OpenAPITools/openapi-generator/wiki/Integration-Tests#how-to-add-integration-tests-for-new-petstore-samples) to learn how to quickly configure and run it. - Finally, git commit the updated samples files: `git commit -a` (`git add -A` if added files with new test cases) - For new test cases, please add to the [Fake Petstore spec](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml) diff --git a/docs/customization.md b/docs/customization.md index e7c7cebc55..39d45c3834 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -110,7 +110,7 @@ java -cp "out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.ja Note the `my-codegen` is an option for `-g` now, and you can use the usual arguments for generating your code: ```sh -java -cp out/codegens/customCodegen/target/my-codegen-openapi-generator-1.0.0.jar:modules/openapi-generator-cli/target/openapi-generator-cli.jar \ +java -cp out/generators/my-codegen/target/my-codegen-openapi-generator-1.0.0.jar:modules/openapi-generator-cli/target/openapi-generator-cli.jar \ org.openapitools.codegen.OpenAPIGenerator generate -g my-codegen \ -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \ -o ./out/myClient diff --git a/docs/generators.md b/docs/generators.md index af370cd663..cd0466f9ad 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -32,9 +32,10 @@ The following generators are available: * [groovy](generators/groovy.md) * [haskell-http-client](generators/haskell-http-client.md) * [java](generators/java.md) +* [java-helidon-client (beta)](generators/java-helidon-client.md) * [java-micronaut-client (beta)](generators/java-micronaut-client.md) * [javascript](generators/javascript.md) -* [javascript-apollo (beta)](generators/javascript-apollo.md) +* [javascript-apollo-deprecated (deprecated)](generators/javascript-apollo-deprecated.md) * [javascript-closure-angular](generators/javascript-closure-angular.md) * [javascript-flowtyped](generators/javascript-flowtyped.md) * [jaxrs-cxf-client](generators/jaxrs-cxf-client.md) @@ -50,8 +51,8 @@ The following generators are available: * [php-dt (beta)](generators/php-dt.md) * [powershell (beta)](generators/powershell.md) * [python](generators/python.md) -* [python-experimental (experimental)](generators/python-experimental.md) * [python-legacy](generators/python-legacy.md) +* [python-prior](generators/python-prior.md) * [r](generators/r.md) * [ruby](generators/ruby.md) * [rust](generators/rust.md) @@ -80,6 +81,7 @@ The following generators are available: * [cpp-pistache-server](generators/cpp-pistache-server.md) * [cpp-qt-qhttpengine-server](generators/cpp-qt-qhttpengine-server.md) * [cpp-restbed-server](generators/cpp-restbed-server.md) +* [cpp-restbed-server-deprecated](generators/cpp-restbed-server-deprecated.md) * [csharp-netcore-functions](generators/csharp-netcore-functions.md) * [erlang-server](generators/erlang-server.md) * [fsharp-functions (beta)](generators/fsharp-functions.md) @@ -91,6 +93,7 @@ The following generators are available: * [haskell](generators/haskell.md) * [haskell-yesod (beta)](generators/haskell-yesod.md) * [java-camel](generators/java-camel.md) +* [java-helidon-server (beta)](generators/java-helidon-server.md) * [java-inflector](generators/java-inflector.md) * [java-micronaut-server (beta)](generators/java-micronaut-server.md) * [java-msf4j](generators/java-msf4j.md) diff --git a/docs/generators/aspnetcore.md b/docs/generators/aspnetcore.md index c4dc4acb6d..b7f2193194 100644 --- a/docs/generators/aspnetcore.md +++ b/docs/generators/aspnetcore.md @@ -45,12 +45,13 @@ These options may be applied as additional-properties (cli) or configOptions (pl |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |src| -|swashbuckleVersion|Swashbuckle version: 3.0.0, 4.0.0, 5.0.0, 6.0.0|
**3.0.0**
Swashbuckle 3.0.0
**4.0.0**
Swashbuckle 4.0.0
**5.0.0**
Swashbuckle 5.0.0
**6.0.0**
Swashbuckle 6.0.0
|3.0.0| +|swashbuckleVersion|Swashbuckle version: 3.0.0 (deprecated), 4.0.0 (deprecated), 5.0.0 (deprecated), 6.4.0|
**3.0.0**
Swashbuckle 3.0.0
**4.0.0**
Swashbuckle 4.0.0
**5.0.0**
Swashbuckle 5.0.0
**6.4.0**
Swashbuckle 6.4.0
|3.0.0| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useDefaultRouting|Use default routing for the ASP.NET Core version.| |true| |useFrameworkReference|Use frameworkReference for ASP.NET Core 3.0+ and PackageReference ASP.NET Core 2.2 or earlier.| |false| |useNewtonsoft|Uses the Newtonsoft JSON library.| |true| +|useSeperateModelProject|Create a seperate project for models| |false| |useSwashbuckle|Uses the Swashbuckle.AspNetCore NuGet package for documentation.| |true| ## IMPORT MAPPING diff --git a/docs/generators/cpp-pistache-server.md b/docs/generators/cpp-pistache-server.md index 708e09aebf..5730d711ab 100644 --- a/docs/generators/cpp-pistache-server.md +++ b/docs/generators/cpp-pistache-server.md @@ -29,6 +29,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Type/Alias | Imports | | ---------- | ------- | |Object|#include "Object.h"| +|nlohmann::json|#include <nlohmann/json.hpp>| |std::map|#include <map>| |std::string|#include <string>| |std::vector|#include <vector>| diff --git a/docs/generators/cpp-restbed-server-deprecated.md b/docs/generators/cpp-restbed-server-deprecated.md new file mode 100644 index 0000000000..13f7b83d31 --- /dev/null +++ b/docs/generators/cpp-restbed-server-deprecated.md @@ -0,0 +1,265 @@ +--- +title: Documentation for the cpp-restbed-server-deprecated Generator +--- + +## METADATA + +| Property | Value | Notes | +| -------- | ----- | ----- | +| generator name | cpp-restbed-server-deprecated | pass this to the generate command after -g | +| generator stability | STABLE | | +| generator type | SERVER | | +| generator language | C++ | | +| generator default templating engine | mustache | | +| helpTxt | Generates a C++ API Server with Restbed (https://github.com/Corvusoft/restbed). | | + +## CONFIG OPTIONS +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|apiPackage|C++ namespace for apis (convention: name.space.api).| |org.openapitools.server.api| +|declspec|C++ preprocessor to place before the class name for handling dllexport/dllimport.| || +|defaultInclude|The default include statement that should be placed in all headers for including things like the declspec (convention: #include "Commons.h" | || +|modelPackage|C++ namespace for models (convention: name.space.model).| |org.openapitools.server.model| +|packageVersion|C++ package version.| |1.0.0| +|reservedWordPrefix|Prefix to prepend to reserved words in order to avoid conflicts| |r_| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|Object|#include "Object.h"| +|restbed::Bytes|#include <corvusoft/restbed/byte.hpp>| +|std::map|#include <map>| +|std::string|#include <string>| +|std::vector|#include <vector>| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Uuid|✗| +|Array|✓|OAS2,OAS3 +|Null|✗|OAS3 +|AnyType|✗|OAS2,OAS3 +|Object|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 +|allOf|✗|OAS2,OAS3 +|anyOf|✗|OAS3 +|oneOf|✗|OAS3 +|not|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✗|OAS2,OAS3 +|ApiKey|✗|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/cpp-restbed-server.md b/docs/generators/cpp-restbed-server.md index f376b503cc..a0450db79d 100644 --- a/docs/generators/cpp-restbed-server.md +++ b/docs/generators/cpp-restbed-server.md @@ -29,9 +29,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Type/Alias | Imports | | ---------- | ------- | -|Object|#include "Object.h"| +|file|#include <string>| |restbed::Bytes|#include <corvusoft/restbed/byte.hpp>| |std::map|#include <map>| +|std::set|#include <set>| |std::string|#include <string>| |std::vector|#include <vector>| diff --git a/docs/generators/crystal.md b/docs/generators/crystal.md index 6d4341efa0..1f3bc4a655 100644 --- a/docs/generators/crystal.md +++ b/docs/generators/crystal.md @@ -24,6 +24,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|
**false**
No changes to the enum's are made, this is the default option.
**true**
With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
|false| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|moduleName|module name (e.g. TwitterClient| |OpenAPIClient| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |shardAuthor|shard author (only one is supported).| |null| |shardAuthorEmail|shard author email (only one is supported).| |null| diff --git a/docs/generators/csharp-netcore.md b/docs/generators/csharp-netcore.md index 1e88fb7ac4..481ffa3fee 100644 --- a/docs/generators/csharp-netcore.md +++ b/docs/generators/csharp-netcore.md @@ -42,7 +42,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |releaseNote|Release note, default to 'Minor update'.| |Minor update| |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |sourceFolder|source folder for generated code| |src| -|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.1`|
**netstandard1.3**
.NET Standard 1.3 compatible
**netstandard1.4**
.NET Standard 1.4 compatible
**netstandard1.5**
.NET Standard 1.5 compatible
**netstandard1.6**
.NET Standard 1.6 compatible
**netstandard2.0**
.NET Standard 2.0 compatible
**netstandard2.1**
.NET Standard 2.1 compatible
**netcoreapp3.1**
.NET Core 3.1 compatible
**net47**
.NET Framework 4.7 compatible
**net5.0**
.NET 5.0 compatible
**net6.0**
.NET 6.0 compatible
|netstandard2.0| +|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.1`|
**netstandard1.3**
.NET Standard 1.3 compatible
**netstandard1.4**
.NET Standard 1.4 compatible
**netstandard1.5**
.NET Standard 1.5 compatible
**netstandard1.6**
.NET Standard 1.6 compatible
**netstandard2.0**
.NET Standard 2.0 compatible
**netstandard2.1**
.NET Standard 2.1 compatible
**netcoreapp3.1**
.NET Core 3.1 compatible
**net47**
.NET Framework 4.7 compatible
**net48**
.NET Framework 4.8 compatible
**net5.0**
.NET 5.0 compatible
**net6.0**
.NET 6.0 compatible
|netstandard2.0| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false| @@ -307,7 +307,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |BearerToken|✗|OAS3 |OAuth2_Implicit|✓|OAS2,OAS3 |OAuth2_Password|✗|OAS2,OAS3 -|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 ### Wire Format Feature diff --git a/docs/generators/java-helidon-client.md b/docs/generators/java-helidon-client.md new file mode 100644 index 0000000000..13b1af6a31 --- /dev/null +++ b/docs/generators/java-helidon-client.md @@ -0,0 +1,316 @@ +--- +title: Documentation for the java-helidon-client Generator +--- + +## METADATA + +| Property | Value | Notes | +| -------- | ----- | ----- | +| generator name | java-helidon-client | pass this to the generate command after -g | +| generator stability | BETA | | +| generator type | CLIENT | | +| generator language | Java | | +| generator default templating engine | mustache | | +| helpTxt | Generates a Helidon MP or SE client | | + +## CONFIG OPTIONS +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|additionalEnumTypeAnnotations|Additional annotations for enum type(class level annotations)| |null| +|additionalModelTypeAnnotations|Additional annotations for model type(class level annotations). List separated by semicolon(;) or new line (Linux or Windows)| |null| +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|apiPackage|package for generated api classes| |org.openapitools.client.api| +|artifactDescription|artifact description in generated pom.xml| |OpenAPI Java| +|artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-java-client| +|artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| +|artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| +|booleanGetterPrefix|Set booleanGetterPrefix| |get| +|configKey|Config key in @RegisterRestClient. Default to none.| |null| +|dateLibrary|Option. Date library to use|
**joda**
Joda (for legacy app only)
**legacy**
Legacy java.util.Date
**java8-localdatetime**
Java 8 using LocalDateTime (for legacy app only)
**java8**
Java 8 native JSR310 (preferred for jdk 1.8+)
|java8| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|
**false**
No changes to the enum's are made, this is the default option.
**true**
With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
|false| +|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| +|fullProject|If set to true, it will generate all files; if set to false, it will only generate API files. If unspecified, the behavior depends on whether a project exists or not: if it does not, same as true; if it does, same as false. Note that test files are never overwritten.| || +|groupId|groupId in generated pom.xml| |org.openapitools| +|helidonVersion|Helidon version for generated code| |3.0.1| +|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| +|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false| +|implicitHeaders|Skip header parameters in the generated API methods using @ApiImplicitParams annotation.| |false| +|implicitHeadersRegex|Skip header parameters that matches given regex in the generated API methods using @ApiImplicitParams annotation. Note: this parameter is ignored when implicitHeaders=true| |null| +|invokerPackage|root package for generated code| |org.openapitools.client| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|library|library template (sub-template) to use|
**mp**
Helidon MP Client
**se**
Helidon SE Client
|mp| +|licenseName|The name of the license| |Unlicense| +|licenseUrl|The URL of the license| |http://unlicense.org| +|modelPackage|package for generated models| |org.openapitools.client.model| +|openApiNullable|Enable OpenAPI Jackson Nullable library| |true| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|rootJavaEEPackage|Root package name for Java EE| |Helidon 2.x and earlier: javax; Helidon 3.x and later: jakarta| +|serializableModel|boolean - toggle "implements Serializable" for generated models| |false| +|serializationLibrary|Serialization library, defaults to Jackson|
**jsonb**
Use JSON-B as serialization library
**jackson**
Use Jackson as serialization library
|null| +|snapshotVersion|Uses a SNAPSHOT version.|
**true**
Use a SnapShot Version
**false**
Use a Release Version
|null| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceFolder|source folder for generated code| |src/main/java| +|testOutput|Set output folder for models and APIs tests| |${project.build.directory}/generated-test-sources/openapi| +|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false| + +## SUPPORTED VENDOR EXTENSIONS + +| Extension name | Description | Applicable for | Default value | +| -------------- | ----------- | -------------- | ------------- | +|x-discriminator-value|Used with model inheritance to specify value for discriminator that identifies current model|MODEL| +|x-implements|Ability to specify interfaces that model must implements|MODEL|empty array +|x-setter-extra-annotation|Custom annotation that can be specified over java setter for specific field|FIELD|When field is array & uniqueItems, then this extension is used to add `@JsonDeserialize(as = LinkedHashSet.class)` over setter, otherwise no value +|x-tags|Specify multiple swagger tags for operation|OPERATION|null +|x-accepts|Specify custom value for 'Accept' header for operation|OPERATION|null +|x-content-type|Specify custom value for 'Content-Type' header for operation|OPERATION|null +|x-class-extra-annotation|List of custom annotations to be added to model|MODEL|null +|x-field-extra-annotation|List of custom annotations to be added to property|FIELD|null +|x-webclient-blocking|Specifies if method for specific operation should be blocking or non-blocking(ex: return `Mono/Flux` or `return T/List/Set` & execute `.block()` inside generated method)|OPERATION|false + + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|Array|java.util.List| +|ArrayList|java.util.ArrayList| +|BigDecimal|java.math.BigDecimal| +|Date|java.util.Date| +|DateTime|org.joda.time.*| +|File|java.io.File| +|HashMap|java.util.HashMap| +|LinkedHashSet|java.util.LinkedHashSet| +|List|java.util.*| +|LocalDate|org.joda.time.*| +|LocalDateTime|org.joda.time.*| +|LocalTime|org.joda.time.*| +|Map|java.util.Map| +|Set|java.util.*| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|ArrayList| +|map|HashMap| +|set|LinkedHashSet| + + +## LANGUAGE PRIMITIVES + +
    +
  • Boolean
  • +
  • Double
  • +
  • Float
  • +
  • Integer
  • +
  • Long
  • +
  • Object
  • +
  • String
  • +
  • boolean
  • +
  • byte[]
  • +
+ +## RESERVED WORDS + +
    +
  • abstract
  • +
  • apiclient
  • +
  • apiexception
  • +
  • apiresponse
  • +
  • assert
  • +
  • boolean
  • +
  • break
  • +
  • byte
  • +
  • case
  • +
  • catch
  • +
  • char
  • +
  • class
  • +
  • configuration
  • +
  • const
  • +
  • continue
  • +
  • default
  • +
  • do
  • +
  • double
  • +
  • else
  • +
  • enum
  • +
  • extends
  • +
  • file
  • +
  • final
  • +
  • finally
  • +
  • float
  • +
  • for
  • +
  • goto
  • +
  • if
  • +
  • implements
  • +
  • import
  • +
  • instanceof
  • +
  • int
  • +
  • interface
  • +
  • list
  • +
  • localreturntype
  • +
  • localvaraccept
  • +
  • localvaraccepts
  • +
  • localvarauthnames
  • +
  • localvarcollectionqueryparams
  • +
  • localvarcontenttype
  • +
  • localvarcontenttypes
  • +
  • localvarcookieparams
  • +
  • localvarformparams
  • +
  • localvarheaderparams
  • +
  • localvarpath
  • +
  • localvarpostbody
  • +
  • localvarqueryparams
  • +
  • long
  • +
  • native
  • +
  • new
  • +
  • null
  • +
  • object
  • +
  • package
  • +
  • private
  • +
  • protected
  • +
  • public
  • +
  • return
  • +
  • short
  • +
  • static
  • +
  • strictfp
  • +
  • stringutil
  • +
  • super
  • +
  • switch
  • +
  • synchronized
  • +
  • this
  • +
  • throw
  • +
  • throws
  • +
  • transient
  • +
  • try
  • +
  • void
  • +
  • volatile
  • +
  • while
  • +
+ +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✓|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Uuid|✗| +|Array|✓|OAS2,OAS3 +|Null|✗|OAS3 +|AnyType|✗|OAS2,OAS3 +|Object|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✓|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✓|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 +|allOf|✗|OAS2,OAS3 +|anyOf|✗|OAS3 +|oneOf|✗|OAS3 +|not|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✗|OAS2,OAS3 +|ApiKey|✗|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/java-helidon-server.md b/docs/generators/java-helidon-server.md new file mode 100644 index 0000000000..a33de1eb38 --- /dev/null +++ b/docs/generators/java-helidon-server.md @@ -0,0 +1,318 @@ +--- +title: Documentation for the java-helidon-server Generator +--- + +## METADATA + +| Property | Value | Notes | +| -------- | ----- | ----- | +| generator name | java-helidon-server | pass this to the generate command after -g | +| generator stability | BETA | | +| generator type | SERVER | | +| generator language | Java | | +| generator default templating engine | mustache | | +| helpTxt | Generates a Java Helidon Server application. | | + +## CONFIG OPTIONS +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|additionalEnumTypeAnnotations|Additional annotations for enum type(class level annotations)| |null| +|additionalModelTypeAnnotations|Additional annotations for model type(class level annotations). List separated by semicolon(;) or new line (Linux or Windows)| |null| +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|apiPackage|package for generated api classes| |org.openapitools.server.api| +|artifactDescription|artifact description in generated pom.xml| |OpenAPI Java| +|artifactId|artifactId in generated pom.xml. This also becomes part of the generated library's filename| |openapi-java-server| +|artifactUrl|artifact URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| +|artifactVersion|artifact version in generated pom.xml. This also becomes part of the generated library's filename| |1.0.0| +|bigDecimalAsString|Treat BigDecimal values as Strings to avoid precision loss.| |false| +|booleanGetterPrefix|Set booleanGetterPrefix| |get| +|dateLibrary|Option. Date library to use|
**joda**
Joda (for legacy app only)
**legacy**
Legacy java.util.Date
**java8-localdatetime**
Java 8 using LocalDateTime (for legacy app only)
**java8**
Java 8 native JSR310 (preferred for jdk 1.8+)
|java8| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| +|discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|
**false**
No changes to the enum's are made, this is the default option.
**true**
With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
|false| +|fullJavaUtil|whether to use fully qualified name for classes under java.util. This option only works for Java API client| |false| +|fullProject|If set to true, it will generate all files; if set to false, it will only generate API files. If unspecified, the behavior depends on whether a project exists or not: if it does not, same as true; if it does, same as false. Note that test files are never overwritten.| || +|gradleProject|Whether to generate gradle project instead of maven.| |false| +|groupId|groupId in generated pom.xml| |org.openapitools| +|helidonVersion|Helidon version for generated code| |3.0.1| +|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| +|ignoreAnyOfInEnum|Ignore anyOf keyword in enum| |false| +|implicitHeaders|Skip header parameters in the generated API methods using @ApiImplicitParams annotation.| |false| +|implicitHeadersRegex|Skip header parameters that matches given regex in the generated API methods using @ApiImplicitParams annotation. Note: this parameter is ignored when implicitHeaders=true| |null| +|invokerPackage|root package for generated code| |org.openapitools.server| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|library|library template (sub-template) to use|
**mp**
Helidon MP Server
**se**
Helidon SE Server
**nima**
Helidon NIMA Server
**nima-annotations**
Helidon NIMA Annotations Server
|se| +|licenseName|The name of the license| |Unlicense| +|licenseUrl|The URL of the license| |http://unlicense.org| +|modelPackage|package for generated models| |org.openapitools.server.model| +|openApiNullable|Enable OpenAPI Jackson Nullable library| |true| +|performBeanValidation|Perform BeanValidation| |false| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|rootJavaEEPackage|Root package name for Java EE| |Helidon 2.x and earlier: javax; Helidon 3.x and later: jakarta| +|serializableModel|boolean - toggle "implements Serializable" for generated models| |false| +|serializationLibrary|Serialization library, defaults to Jackson|
**jsonb**
Use JSON-B as serialization library
**jackson**
Use Jackson as serialization library
|null| +|snapshotVersion|Uses a SNAPSHOT version.|
**true**
Use a SnapShot Version
**false**
Use a Release Version
|null| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceFolder|source folder for generated code| |src/main/java| +|testOutput|Set output folder for models and APIs tests| |${project.build.directory}/generated-test-sources/openapi| +|useAbstractClass|Whether to generate abstract classes for REST API instead of interfaces.| |false| +|useBeanValidation|Use Bean Validation| |false| +|withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false| + +## SUPPORTED VENDOR EXTENSIONS + +| Extension name | Description | Applicable for | Default value | +| -------------- | ----------- | -------------- | ------------- | +|x-discriminator-value|Used with model inheritance to specify value for discriminator that identifies current model|MODEL| +|x-implements|Ability to specify interfaces that model must implements|MODEL|empty array +|x-setter-extra-annotation|Custom annotation that can be specified over java setter for specific field|FIELD|When field is array & uniqueItems, then this extension is used to add `@JsonDeserialize(as = LinkedHashSet.class)` over setter, otherwise no value +|x-tags|Specify multiple swagger tags for operation|OPERATION|null +|x-accepts|Specify custom value for 'Accept' header for operation|OPERATION|null +|x-content-type|Specify custom value for 'Content-Type' header for operation|OPERATION|null +|x-class-extra-annotation|List of custom annotations to be added to model|MODEL|null +|x-field-extra-annotation|List of custom annotations to be added to property|FIELD|null + + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|Array|java.util.List| +|ArrayList|java.util.ArrayList| +|BigDecimal|java.math.BigDecimal| +|Date|java.util.Date| +|DateTime|org.joda.time.*| +|File|java.io.File| +|HashMap|java.util.HashMap| +|LinkedHashSet|java.util.LinkedHashSet| +|List|java.util.*| +|LocalDate|org.joda.time.*| +|LocalDateTime|org.joda.time.*| +|LocalTime|org.joda.time.*| +|Map|java.util.Map| +|Set|java.util.*| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|ArrayList| +|map|HashMap| +|set|LinkedHashSet| + + +## LANGUAGE PRIMITIVES + +
    +
  • Boolean
  • +
  • Double
  • +
  • Float
  • +
  • Integer
  • +
  • Long
  • +
  • Object
  • +
  • String
  • +
  • boolean
  • +
  • byte[]
  • +
+ +## RESERVED WORDS + +
    +
  • abstract
  • +
  • apiclient
  • +
  • apiexception
  • +
  • apiresponse
  • +
  • assert
  • +
  • boolean
  • +
  • break
  • +
  • byte
  • +
  • case
  • +
  • catch
  • +
  • char
  • +
  • class
  • +
  • configuration
  • +
  • const
  • +
  • continue
  • +
  • default
  • +
  • do
  • +
  • double
  • +
  • else
  • +
  • enum
  • +
  • extends
  • +
  • file
  • +
  • final
  • +
  • finally
  • +
  • float
  • +
  • for
  • +
  • goto
  • +
  • if
  • +
  • implements
  • +
  • import
  • +
  • instanceof
  • +
  • int
  • +
  • interface
  • +
  • list
  • +
  • localreturntype
  • +
  • localvaraccept
  • +
  • localvaraccepts
  • +
  • localvarauthnames
  • +
  • localvarcollectionqueryparams
  • +
  • localvarcontenttype
  • +
  • localvarcontenttypes
  • +
  • localvarcookieparams
  • +
  • localvarformparams
  • +
  • localvarheaderparams
  • +
  • localvarpath
  • +
  • localvarpostbody
  • +
  • localvarqueryparams
  • +
  • long
  • +
  • native
  • +
  • new
  • +
  • null
  • +
  • object
  • +
  • package
  • +
  • private
  • +
  • protected
  • +
  • public
  • +
  • return
  • +
  • short
  • +
  • static
  • +
  • strictfp
  • +
  • stringutil
  • +
  • super
  • +
  • switch
  • +
  • synchronized
  • +
  • this
  • +
  • throw
  • +
  • throws
  • +
  • transient
  • +
  • try
  • +
  • void
  • +
  • volatile
  • +
  • while
  • +
+ +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✓|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Uuid|✗| +|Array|✓|OAS2,OAS3 +|Null|✗|OAS3 +|AnyType|✗|OAS2,OAS3 +|Object|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✓|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 +|allOf|✗|OAS2,OAS3 +|anyOf|✗|OAS3 +|oneOf|✗|OAS3 +|not|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✗|OAS2,OAS3 +|ApiKey|✗|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/javascript-apollo-deprecated.md b/docs/generators/javascript-apollo-deprecated.md new file mode 100644 index 0000000000..ffc30f726a --- /dev/null +++ b/docs/generators/javascript-apollo-deprecated.md @@ -0,0 +1,274 @@ +--- +title: Documentation for the javascript-apollo-deprecated Generator +--- + +## METADATA + +| Property | Value | Notes | +| -------- | ----- | ----- | +| generator name | javascript-apollo-deprecated | pass this to the generate command after -g | +| generator stability | DEPRECATED | | +| generator type | CLIENT | | +| generator language | Javascript | | +| generator default templating engine | mustache | | +| helpTxt | Generates a JavaScript client library (beta) using Apollo RESTDatasource. | | + +## CONFIG OPTIONS +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|apiPackage|package for generated api classes| |null| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| +|emitJSDoc|generate JSDoc comments| |true| +|emitModelMethods|generate getters and setters for model properties| |false| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|
**false**
No changes to the enum's are made, this is the default option.
**true**
With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
|false| +|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| +|invokerPackage|root package for generated code| |null| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|licenseName|name of the license the project uses (Default: using info.license.name)| |null| +|modelPackage|package for generated models| |null| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|moduleName|module name for AMD, Node or globals (Default: generated from <projectName>)| |null| +|npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|projectDescription|description of the project (Default: using info.description or "Client library of <projectName>")| |null| +|projectName|name of the project (Default: generated from info.title or "openapi-js-client")| |null| +|projectVersion|version of the project (Default: using info.version or "1.0.0")| |null| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceFolder|source folder for generated code| |src| +|useInheritance|use JavaScript prototype chains & delegation for inheritance| |true| +|usePromises|use Promises as return values from the client API, instead of superagent callbacks| |false| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|Array| +|list|Array| +|map|Object| +|set|Array| + + +## LANGUAGE PRIMITIVES + +
    +
  • Array
  • +
  • Blob
  • +
  • Boolean
  • +
  • Date
  • +
  • File
  • +
  • Number
  • +
  • Object
  • +
  • String
  • +
+ +## RESERVED WORDS + +
    +
  • Array
  • +
  • Date
  • +
  • Infinity
  • +
  • Math
  • +
  • NaN
  • +
  • Number
  • +
  • Object
  • +
  • String
  • +
  • abstract
  • +
  • arguments
  • +
  • boolean
  • +
  • break
  • +
  • byte
  • +
  • case
  • +
  • catch
  • +
  • char
  • +
  • class
  • +
  • const
  • +
  • continue
  • +
  • debugger
  • +
  • default
  • +
  • delete
  • +
  • do
  • +
  • double
  • +
  • else
  • +
  • enum
  • +
  • eval
  • +
  • export
  • +
  • extends
  • +
  • false
  • +
  • final
  • +
  • finally
  • +
  • float
  • +
  • for
  • +
  • function
  • +
  • goto
  • +
  • hasOwnProperty
  • +
  • if
  • +
  • implements
  • +
  • import
  • +
  • in
  • +
  • instanceof
  • +
  • int
  • +
  • interface
  • +
  • isFinite
  • +
  • isNaN
  • +
  • isPrototypeOf
  • +
  • let
  • +
  • long
  • +
  • native
  • +
  • new
  • +
  • null
  • +
  • package
  • +
  • private
  • +
  • protected
  • +
  • prototype
  • +
  • public
  • +
  • return
  • +
  • short
  • +
  • static
  • +
  • super
  • +
  • switch
  • +
  • synchronized
  • +
  • this
  • +
  • throw
  • +
  • throws
  • +
  • toString
  • +
  • transient
  • +
  • true
  • +
  • try
  • +
  • typeof
  • +
  • undefined
  • +
  • valueOf
  • +
  • var
  • +
  • void
  • +
  • volatile
  • +
  • while
  • +
  • with
  • +
  • yield
  • +
+ +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Uuid|✗| +|Array|✓|OAS2,OAS3 +|Null|✗|OAS3 +|AnyType|✗|OAS2,OAS3 +|Object|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✓|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✓|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✓|OAS2,OAS3 +|Union|✗|OAS3 +|allOf|✗|OAS2,OAS3 +|anyOf|✗|OAS3 +|oneOf|✗|OAS3 +|not|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✓|OAS2,OAS3 +|OAuth2_ClientCredentials|✓|OAS2,OAS3 +|OAuth2_AuthorizationCode|✓|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/javascript-apollo.md b/docs/generators/javascript-apollo.md index 59150ad9e8..e128d136e2 100644 --- a/docs/generators/javascript-apollo.md +++ b/docs/generators/javascript-apollo.md @@ -7,7 +7,7 @@ title: Documentation for the javascript-apollo Generator | Property | Value | Notes | | -------- | ----- | ----- | | generator name | javascript-apollo | pass this to the generate command after -g | -| generator stability | BETA | | +| generator stability | DEPRECATED | | | generator type | CLIENT | | | generator language | Javascript | | | generator default templating engine | mustache | | @@ -22,6 +22,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |apiPackage|package for generated api classes| |null| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| |emitJSDoc|generate JSDoc comments| |true| +|emitModelMethods|generate getters and setters for model properties| |false| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|
**false**
No changes to the enum's are made, this is the default option.
**true**
With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
|false| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| @@ -40,6 +41,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |src| |useInheritance|use JavaScript prototype chains & delegation for inheritance| |true| +|usePromises|use Promises as return values from the client API, instead of superagent callbacks| |false| ## IMPORT MAPPING @@ -54,6 +56,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |array|Array| |list|Array| |map|Object| +|set|Array| ## LANGUAGE PRIMITIVES @@ -72,9 +75,16 @@ These options may be applied as additional-properties (cli) or configOptions (pl ## RESERVED WORDS
    +
  • Array
  • +
  • Date
  • +
  • Infinity
  • +
  • Math
  • +
  • NaN
  • +
  • Number
  • +
  • Object
  • +
  • String
  • abstract
  • arguments
  • -
  • array
  • boolean
  • break
  • byte
  • @@ -84,7 +94,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • class
  • const
  • continue
  • -
  • date
  • debugger
  • default
  • delete
  • @@ -102,27 +111,22 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • for
  • function
  • goto
  • -
  • hasownproperty
  • +
  • hasOwnProperty
  • if
  • implements
  • import
  • in
  • -
  • infinity
  • instanceof
  • int
  • interface
  • -
  • isfinite
  • -
  • isnan
  • -
  • isprototypeof
  • +
  • isFinite
  • +
  • isNaN
  • +
  • isPrototypeOf
  • let
  • long
  • -
  • math
  • -
  • nan
  • native
  • new
  • null
  • -
  • number
  • -
  • object
  • package
  • private
  • protected
  • @@ -131,20 +135,19 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • return
  • short
  • static
  • -
  • string
  • super
  • switch
  • synchronized
  • this
  • throw
  • throws
  • -
  • tostring
  • +
  • toString
  • transient
  • true
  • try
  • typeof
  • undefined
  • -
  • valueof
  • +
  • valueOf
  • var
  • void
  • volatile
  • diff --git a/docs/generators/javascript.md b/docs/generators/javascript.md index 5c1c2b4724..b9259f14ab 100644 --- a/docs/generators/javascript.md +++ b/docs/generators/javascript.md @@ -28,6 +28,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |invokerPackage|root package for generated code| |null| |legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
    **true**
    The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
    **false**
    The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
    |true| +|library|library template (sub-template)|
    **javascript**
    JavaScript client library
    **apollo**
    Apollo REST DataSource
    |javascript| |licenseName|name of the license the project uses (Default: using info.license.name)| |null| |modelPackage|package for generated models| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md index 8daa145ec4..ee8399a2a4 100644 --- a/docs/generators/kotlin-server.md +++ b/docs/generators/kotlin-server.md @@ -105,6 +105,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • const
  • constructor
  • continue
  • +
  • contract
  • crossinline
  • data
  • delegate
  • diff --git a/docs/generators/kotlin-spring.md b/docs/generators/kotlin-spring.md index 030356edbc..a7de5eea62 100644 --- a/docs/generators/kotlin-spring.md +++ b/docs/generators/kotlin-spring.md @@ -114,6 +114,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • const
  • constructor
  • continue
  • +
  • contract
  • crossinline
  • data
  • delegate
  • diff --git a/docs/generators/kotlin-vertx.md b/docs/generators/kotlin-vertx.md index 6080b3c98b..7a25d890a7 100644 --- a/docs/generators/kotlin-vertx.md +++ b/docs/generators/kotlin-vertx.md @@ -93,6 +93,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • const
  • constructor
  • continue
  • +
  • contract
  • crossinline
  • data
  • delegate
  • diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md index 473ee4ec3d..7f562302f2 100644 --- a/docs/generators/kotlin.md +++ b/docs/generators/kotlin.md @@ -107,6 +107,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • const
  • constructor
  • continue
  • +
  • contract
  • crossinline
  • data
  • delegate
  • diff --git a/docs/generators/php-dt.md b/docs/generators/php-dt.md index 752e5027cd..7f9d0789bd 100644 --- a/docs/generators/php-dt.md +++ b/docs/generators/php-dt.md @@ -56,7 +56,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • bool
  • boolean
  • byte
  • -
  • double
  • float
  • int
  • integer
  • diff --git a/docs/generators/php-laravel.md b/docs/generators/php-laravel.md index 122c3f56cc..9c606506d7 100644 --- a/docs/generators/php-laravel.md +++ b/docs/generators/php-laravel.md @@ -57,7 +57,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • bool
  • boolean
  • byte
  • -
  • double
  • float
  • int
  • integer
  • diff --git a/docs/generators/php-lumen.md b/docs/generators/php-lumen.md index f8b02f001c..28ac527eef 100644 --- a/docs/generators/php-lumen.md +++ b/docs/generators/php-lumen.md @@ -57,7 +57,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • bool
  • boolean
  • byte
  • -
  • double
  • float
  • int
  • integer
  • diff --git a/docs/generators/php-mezzio-ph.md b/docs/generators/php-mezzio-ph.md index f94d54b3b3..01cb9eb6cc 100644 --- a/docs/generators/php-mezzio-ph.md +++ b/docs/generators/php-mezzio-ph.md @@ -56,7 +56,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • bool
  • boolean
  • byte
  • -
  • double
  • float
  • int
  • integer
  • diff --git a/docs/generators/php-slim-deprecated.md b/docs/generators/php-slim-deprecated.md index 508fe455b3..f5844cd709 100644 --- a/docs/generators/php-slim-deprecated.md +++ b/docs/generators/php-slim-deprecated.md @@ -57,7 +57,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • bool
  • boolean
  • byte
  • -
  • double
  • float
  • int
  • integer
  • diff --git a/docs/generators/php-slim4.md b/docs/generators/php-slim4.md index a995e88349..fd30427de4 100644 --- a/docs/generators/php-slim4.md +++ b/docs/generators/php-slim4.md @@ -58,7 +58,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • bool
  • boolean
  • byte
  • -
  • double
  • float
  • int
  • integer
  • diff --git a/docs/generators/php-symfony.md b/docs/generators/php-symfony.md index 608dee4938..f818259b0e 100644 --- a/docs/generators/php-symfony.md +++ b/docs/generators/php-symfony.md @@ -62,7 +62,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • array
  • bool
  • byte
  • -
  • double
  • float
  • int
  • mixed
  • diff --git a/docs/generators/php.md b/docs/generators/php.md index 7d71c4ce00..298d059c38 100644 --- a/docs/generators/php.md +++ b/docs/generators/php.md @@ -58,7 +58,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • bool
  • boolean
  • byte
  • -
  • double
  • float
  • int
  • integer
  • diff --git a/docs/generators/protobuf-schema.md b/docs/generators/protobuf-schema.md index b61298ede4..e4b37f2a86 100644 --- a/docs/generators/protobuf-schema.md +++ b/docs/generators/protobuf-schema.md @@ -32,6 +32,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Type/Alias | Instantiated By | | ---------- | --------------- | |array|repeat| +|set|repeat| ## LANGUAGE PRIMITIVES @@ -47,6 +48,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • int32
  • int64
  • map
  • +
  • set
  • sfixed32
  • sfixed64
  • sint32
  • diff --git a/docs/generators/python-aiohttp.md b/docs/generators/python-aiohttp.md index d2ba3f9ec0..2f6f7e4e51 100644 --- a/docs/generators/python-aiohttp.md +++ b/docs/generators/python-aiohttp.md @@ -34,7 +34,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |serverPort|TCP port to listen to in app.run| |8080| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| -|supportPython2|support python2. This option has been deprecated and will be removed in the 5.x release.| |false| |testsUsePythonSrcRoot|generates test under the pythonSrcRoot folder.| |false| |useNose|use the nose test framework| |false| |usePythonSrcRootInImports|include pythonSrcRoot in import namespaces.| |false| diff --git a/docs/generators/python-blueplanet.md b/docs/generators/python-blueplanet.md index 9e10d91343..ce4b7ae98d 100644 --- a/docs/generators/python-blueplanet.md +++ b/docs/generators/python-blueplanet.md @@ -10,7 +10,7 @@ title: Documentation for the python-blueplanet Generator | generator stability | STABLE | | | generator type | SERVER | | | generator language | Python | | -| generator language version | 2.7+ and 3.5.2+ | | +| generator language version | 3.5.2+ | | | generator default templating engine | mustache | | | helpTxt | Generates a Python server library using the Connexion project. By default, it will also generate service classes -- which you can disable with the `-Dnoservice` environment variable. | | @@ -34,7 +34,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |serverPort|TCP port to listen to in app.run| |8080| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| -|supportPython2|support python2. This option has been deprecated and will be removed in the 5.x release.| |false| |testsUsePythonSrcRoot|generates test under the pythonSrcRoot folder.| |false| |useNose|use the nose test framework| |false| |usePythonSrcRootInImports|include pythonSrcRoot in import namespaces.| |false| diff --git a/docs/generators/python-experimental.md b/docs/generators/python-experimental.md deleted file mode 100644 index ab5862d321..0000000000 --- a/docs/generators/python-experimental.md +++ /dev/null @@ -1,242 +0,0 @@ ---- -title: Documentation for the python-experimental Generator ---- - -## METADATA - -| Property | Value | Notes | -| -------- | ----- | ----- | -| generator name | python-experimental | pass this to the generate command after -g | -| generator stability | EXPERIMENTAL | | -| generator type | CLIENT | | -| generator language | Python | | -| generator language version | >=3.9 | | -| generator default templating engine | handlebars | | -| helpTxt | Generates a Python client library

    Features in this generator:
    - type hints on endpoints and model creation
    - model parameter names use the spec defined keys and cases
    - robust composition (oneOf/anyOf/allOf/not) where payload data is stored in one instance only
    - endpoint parameter names use the spec defined keys and cases
    - inline schemas are supported at any location including composition
    - multiple content types supported in request body and response bodies
    - run time type checking
    - Sending/receiving decimals as strings supported with type:string format: number -> DecimalSchema
    - Sending/receiving uuids as strings supported with type:string format: uuid -> UUIDSchema
    - quicker load time for python modules (a single endpoint can be imported and used without loading others)
    - all instances of schemas dynamically inherit from all matching schemas so one can use isinstance to check if validation passed
    - composed schemas with type constraints supported (type:object + oneOf/anyOf/allOf)
    - schemas are not coerced/cast. For example string + date are both stored as string, and there is a date accessor
    - Exceptions: int/float is stored as Decimal, When receiving data from headers it will start as str and may need to be cast for example to int | | - -## CONFIG OPTIONS -These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. - -| Option | Description | Values | Default | -| ------ | ----------- | ------ | ------- | -|generateSourceCodeOnly|Specifies that only a library source code is to be generated.| |false| -|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| -|library|library template (sub-template) to use: urllib3| |urllib3| -|packageName|python package name (convention: snake_case).| |openapi_client| -|packageUrl|python package URL.| |null| -|packageVersion|python package version.| |1.0.0| -|projectName|python project name in setup.py (e.g. petstore-api).| |null| -|recursionLimit|Set the recursion limit. If not set, use the system default value.| |null| -|useInlineModelResolver|use the inline model resolver, if true inline complex models will be extracted into components and $refs to them will be used| |false| -|useNose|use the nose test framework| |false| - -## IMPORT MAPPING - -| Type/Alias | Imports | -| ---------- | ------- | - - -## INSTANTIATION TYPES - -| Type/Alias | Instantiated By | -| ---------- | --------------- | -|map|dict| - - -## LANGUAGE PRIMITIVES - -
      -
    • bool
    • -
    • bytes
    • -
    • date
    • -
    • datetime
    • -
    • dict
    • -
    • file
    • -
    • file_type
    • -
    • float
    • -
    • int
    • -
    • list
    • -
    • none_type
    • -
    • object
    • -
    • str
    • -
    - -## RESERVED WORDS - -
      -
    • all_params
    • -
    • and
    • -
    • as
    • -
    • assert
    • -
    • async
    • -
    • auth_settings
    • -
    • await
    • -
    • body_params
    • -
    • bool
    • -
    • break
    • -
    • class
    • -
    • continue
    • -
    • def
    • -
    • del
    • -
    • dict
    • -
    • elif
    • -
    • else
    • -
    • except
    • -
    • exec
    • -
    • false
    • -
    • file_type
    • -
    • finally
    • -
    • float
    • -
    • for
    • -
    • form_params
    • -
    • from
    • -
    • frozendict
    • -
    • global
    • -
    • header_params
    • -
    • if
    • -
    • import
    • -
    • in
    • -
    • int
    • -
    • is
    • -
    • lambda
    • -
    • list
    • -
    • local_var_files
    • -
    • none
    • -
    • none_type
    • -
    • nonlocal
    • -
    • not
    • -
    • or
    • -
    • pass
    • -
    • path_params
    • -
    • print
    • -
    • property
    • -
    • query_params
    • -
    • raise
    • -
    • resource_path
    • -
    • return
    • -
    • self
    • -
    • str
    • -
    • true
    • -
    • try
    • -
    • tuple
    • -
    • while
    • -
    • with
    • -
    • yield
    • -
    - -## FEATURE SET - - -### Client Modification Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|BasePath|✗|ToolingExtension -|Authorizations|✗|ToolingExtension -|UserAgent|✗|ToolingExtension -|MockServer|✗|ToolingExtension - -### Data Type Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Custom|✗|OAS2,OAS3 -|Int32|✓|OAS2,OAS3 -|Int64|✓|OAS2,OAS3 -|Float|✓|OAS2,OAS3 -|Double|✓|OAS2,OAS3 -|Decimal|✓|ToolingExtension -|String|✓|OAS2,OAS3 -|Byte|✓|OAS2,OAS3 -|Binary|✓|OAS2,OAS3 -|Boolean|✓|OAS2,OAS3 -|Date|✓|OAS2,OAS3 -|DateTime|✓|OAS2,OAS3 -|Password|✓|OAS2,OAS3 -|File|✓|OAS2 -|Uuid|✓| -|Array|✓|OAS2,OAS3 -|Null|✓|OAS3 -|AnyType|✓|OAS2,OAS3 -|Object|✓|OAS2,OAS3 -|Maps|✓|ToolingExtension -|CollectionFormat|✓|OAS2 -|CollectionFormatMulti|✓|OAS2 -|Enum|✓|OAS2,OAS3 -|ArrayOfEnum|✓|ToolingExtension -|ArrayOfModel|✓|ToolingExtension -|ArrayOfCollectionOfPrimitives|✓|ToolingExtension -|ArrayOfCollectionOfModel|✓|ToolingExtension -|ArrayOfCollectionOfEnum|✓|ToolingExtension -|MapOfEnum|✓|ToolingExtension -|MapOfModel|✓|ToolingExtension -|MapOfCollectionOfPrimitives|✓|ToolingExtension -|MapOfCollectionOfModel|✓|ToolingExtension -|MapOfCollectionOfEnum|✓|ToolingExtension - -### Documentation Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Readme|✓|ToolingExtension -|Model|✓|ToolingExtension -|Api|✓|ToolingExtension - -### Global Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Host|✓|OAS2,OAS3 -|BasePath|✓|OAS2,OAS3 -|Info|✓|OAS2,OAS3 -|Schemes|✗|OAS2,OAS3 -|PartialSchemes|✓|OAS2,OAS3 -|Consumes|✓|OAS2 -|Produces|✓|OAS2 -|ExternalDocumentation|✓|OAS2,OAS3 -|Examples|✓|OAS2,OAS3 -|XMLStructureDefinitions|✗|OAS2,OAS3 -|MultiServer|✗|OAS3 -|ParameterizedServer|✓|OAS3 -|ParameterStyling|✓|OAS3 -|Callbacks|✗|OAS3 -|LinkObjects|✗|OAS3 - -### Parameter Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Path|✓|OAS2,OAS3 -|Query|✓|OAS2,OAS3 -|Header|✓|OAS2,OAS3 -|Body|✓|OAS2 -|FormUnencoded|✓|OAS2 -|FormMultipart|✓|OAS2 -|Cookie|✗|OAS3 - -### Schema Support Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Simple|✓|OAS2,OAS3 -|Composite|✓|OAS2,OAS3 -|Polymorphism|✓|OAS2,OAS3 -|Union|✓|OAS3 -|allOf|✓|OAS2,OAS3 -|anyOf|✓|OAS3 -|oneOf|✓|OAS3 -|not|✓|OAS3 - -### Security Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|BasicAuth|✓|OAS2,OAS3 -|ApiKey|✓|OAS2,OAS3 -|OpenIDConnect|✗|OAS3 -|BearerToken|✓|OAS3 -|OAuth2_Implicit|✓|OAS2,OAS3 -|OAuth2_Password|✗|OAS2,OAS3 -|OAuth2_ClientCredentials|✗|OAS2,OAS3 -|OAuth2_AuthorizationCode|✗|OAS2,OAS3 - -### Wire Format Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|JSON|✓|OAS2,OAS3 -|XML|✗|OAS2,OAS3 -|PROTOBUF|✗|ToolingExtension -|Custom|✓|OAS2,OAS3 diff --git a/docs/generators/python-flask.md b/docs/generators/python-flask.md index 2c82d53900..5624ecb8a0 100644 --- a/docs/generators/python-flask.md +++ b/docs/generators/python-flask.md @@ -10,7 +10,7 @@ title: Documentation for the python-flask Generator | generator stability | STABLE | | | generator type | SERVER | | | generator language | Python | | -| generator language version | 2.7 and 3.5.2+ | | +| generator language version | 3.5.2+ | | | generator default templating engine | mustache | | | helpTxt | Generates a Python server library using the Connexion project. By default, it will also generate service classes -- which you can disable with the `-Dnoservice` environment variable. | | @@ -34,7 +34,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |serverPort|TCP port to listen to in app.run| |8080| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| -|supportPython2|support python2. This option has been deprecated and will be removed in the 5.x release.| |false| |testsUsePythonSrcRoot|generates test under the pythonSrcRoot folder.| |false| |useNose|use the nose test framework| |false| |usePythonSrcRootInImports|include pythonSrcRoot in import namespaces.| |false| diff --git a/docs/generators/python-prior.md b/docs/generators/python-prior.md new file mode 100644 index 0000000000..00a89120d7 --- /dev/null +++ b/docs/generators/python-prior.md @@ -0,0 +1,233 @@ +--- +title: Documentation for the python-prior Generator +--- + +## METADATA + +| Property | Value | Notes | +| -------- | ----- | ----- | +| generator name | python-prior | pass this to the generate command after -g | +| generator stability | STABLE | | +| generator type | CLIENT | | +| generator language | Python | | +| generator language version | >=3.6 | | +| generator default templating engine | mustache | | +| helpTxt | Generates a Python client library. | | + +## CONFIG OPTIONS +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. NOTE: this option breaks composition and will be removed in 6.0.0
    |false| +|generateSourceCodeOnly|Specifies that only a library source code is to be generated.| |false| +|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| +|initRequiredVars|If set to true then the required variables are included as positional arguments in __init__ and _from_openapi_data methods. Note: this can break some composition use cases. To learn more read PR #8802.| |false| +|library|library template (sub-template) to use: asyncio, tornado, urllib3| |urllib3| +|packageName|python package name (convention: snake_case).| |openapi_client| +|packageUrl|python package URL.| |null| +|packageVersion|python package version.| |1.0.0| +|projectName|python project name in setup.py (e.g. petstore-api).| |null| +|pythonAttrNoneIfUnset|when accessing unset attribute, return `None` instead of raising `ApiAttributeError`| |false| +|recursionLimit|Set the recursion limit. If not set, use the system default value.| |null| +|useNose|use the nose test framework| |false| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + +
      +
    • bool
    • +
    • bytes
    • +
    • date
    • +
    • datetime
    • +
    • dict
    • +
    • file
    • +
    • file_type
    • +
    • float
    • +
    • int
    • +
    • list
    • +
    • none_type
    • +
    • object
    • +
    • str
    • +
    + +## RESERVED WORDS + +
      +
    • all_params
    • +
    • and
    • +
    • as
    • +
    • assert
    • +
    • async
    • +
    • auth_settings
    • +
    • await
    • +
    • body_params
    • +
    • break
    • +
    • class
    • +
    • continue
    • +
    • def
    • +
    • del
    • +
    • elif
    • +
    • else
    • +
    • except
    • +
    • exec
    • +
    • false
    • +
    • finally
    • +
    • for
    • +
    • form_params
    • +
    • from
    • +
    • global
    • +
    • header_params
    • +
    • if
    • +
    • import
    • +
    • in
    • +
    • is
    • +
    • lambda
    • +
    • local_var_files
    • +
    • none
    • +
    • nonlocal
    • +
    • not
    • +
    • or
    • +
    • pass
    • +
    • path_params
    • +
    • print
    • +
    • property
    • +
    • query_params
    • +
    • raise
    • +
    • resource_path
    • +
    • return
    • +
    • self
    • +
    • true
    • +
    • try
    • +
    • while
    • +
    • with
    • +
    • yield
    • +
    + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Uuid|✗| +|Array|✓|OAS2,OAS3 +|Null|✗|OAS3 +|AnyType|✗|OAS2,OAS3 +|Object|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✓|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 +|allOf|✗|OAS2,OAS3 +|anyOf|✗|OAS3 +|oneOf|✗|OAS3 +|not|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✓|OAS2,OAS3 diff --git a/docs/generators/python.md b/docs/generators/python.md index 34875d8c86..4cbf616d09 100644 --- a/docs/generators/python.md +++ b/docs/generators/python.md @@ -10,26 +10,25 @@ title: Documentation for the python Generator | generator stability | STABLE | | | generator type | CLIENT | | | generator language | Python | | -| generator language version | >=3.6 | | -| generator default templating engine | mustache | | -| helpTxt | Generates a Python client library. | | +| generator language version | >=3.7 | | +| generator default templating engine | handlebars | | +| helpTxt | Generates a Python client library

    Features in this generator:
    - type hints on endpoints and model creation
    - model parameter names use the spec defined keys and cases
    - robust composition (oneOf/anyOf/allOf/not) where payload data is stored in one instance only
    - endpoint parameter names use the spec defined keys and cases
    - inline schemas are supported at any location including composition
    - multiple content types supported in request body and response bodies
    - run time type checking
    - Sending/receiving decimals as strings supported with type:string format: number -> DecimalSchema
    - Sending/receiving uuids as strings supported with type:string format: uuid -> UUIDSchema
    - quicker load time for python modules (a single endpoint can be imported and used without loading others)
    - all instances of schemas dynamically inherit from all matching schemas so one can use isinstance to check if validation passed
    - composed schemas with type constraints supported (type:object + oneOf/anyOf/allOf)
    - schemas are not coerced/cast. For example string + date are both stored as string, and there is a date accessor
    - Exceptions: int/float is stored as Decimal, When receiving data from headers it will start as str and may need to be cast for example to int | | ## CONFIG OPTIONS These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | -|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. NOTE: this option breaks composition and will be removed in 6.0.0
    |false| |generateSourceCodeOnly|Specifies that only a library source code is to be generated.| |false| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| -|initRequiredVars|If set to true then the required variables are included as positional arguments in __init__ and _from_openapi_data methods. Note: this can break some composition use cases. To learn more read PR #8802.| |false| -|library|library template (sub-template) to use: asyncio, tornado, urllib3| |urllib3| +|library|library template (sub-template) to use: urllib3| |urllib3| +|nonCompliantUseDiscriminatorIfCompositionFails|When true, If the payload fails to validate against composed schemas (allOf/anyOf/oneOf/not) and a discriminator is present, then ignore the composition validation errors and attempt to use the discriminator to validate the payload.<br />Note: setting this to true makes the generated client not comply with json schema because it ignores composition validation errors. Please consider making your schemas more restrictive rather than setting this to true. You can do that by:<ul><li>defining the propertyName as an enum with only one value in the schemas that are in your discriminator map</li><li>setting additionalProperties: false in your schemas</li></ul>|
    **true**
    If composition fails and a discriminator exists, the composition errors will be ignored and validation will be attempted with the discriminator
    **false**
    Composition validation must succeed. Discriminator validation must succeed.
    |false| |packageName|python package name (convention: snake_case).| |openapi_client| |packageUrl|python package URL.| |null| |packageVersion|python package version.| |1.0.0| |projectName|python project name in setup.py (e.g. petstore-api).| |null| -|pythonAttrNoneIfUnset|when accessing unset attribute, return `None` instead of raising `ApiAttributeError`| |false| |recursionLimit|Set the recursion limit. If not set, use the system default value.| |null| +|useInlineModelResolver|use the inline model resolver, if true inline complex models will be extracted into components and $refs to them will be used| |false| |useNose|use the nose test framework| |false| ## IMPORT MAPPING @@ -42,6 +41,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Type/Alias | Instantiated By | | ---------- | --------------- | +|map|dict| ## LANGUAGE PRIMITIVES @@ -73,29 +73,37 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • auth_settings
  • await
  • body_params
  • +
  • bool
  • break
  • class
  • continue
  • def
  • del
  • +
  • dict
  • elif
  • else
  • except
  • exec
  • false
  • +
  • file_type
  • finally
  • +
  • float
  • for
  • form_params
  • from
  • +
  • frozendict
  • global
  • header_params
  • if
  • import
  • in
  • +
  • int
  • is
  • lambda
  • +
  • list
  • local_var_files
  • none
  • +
  • none_type
  • nonlocal
  • not
  • or
  • @@ -108,8 +116,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • resource_path
  • return
  • self
  • +
  • str
  • true
  • try
  • +
  • tuple
  • while
  • with
  • yield
  • @@ -143,10 +153,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |DateTime|✓|OAS2,OAS3 |Password|✓|OAS2,OAS3 |File|✓|OAS2 -|Uuid|✗| +|Uuid|✓| |Array|✓|OAS2,OAS3 -|Null|✗|OAS3 -|AnyType|✗|OAS2,OAS3 +|Null|✓|OAS3 +|AnyType|✓|OAS2,OAS3 |Object|✓|OAS2,OAS3 |Maps|✓|ToolingExtension |CollectionFormat|✓|OAS2 @@ -185,7 +195,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |XMLStructureDefinitions|✗|OAS2,OAS3 |MultiServer|✗|OAS3 |ParameterizedServer|✓|OAS3 -|ParameterStyling|✗|OAS3 +|ParameterStyling|✓|OAS3 |Callbacks|✗|OAS3 |LinkObjects|✗|OAS3 @@ -205,12 +215,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl | ---- | --------- | ---------- | |Simple|✓|OAS2,OAS3 |Composite|✓|OAS2,OAS3 -|Polymorphism|✗|OAS2,OAS3 -|Union|✗|OAS3 -|allOf|✗|OAS2,OAS3 -|anyOf|✗|OAS3 -|oneOf|✗|OAS3 -|not|✗|OAS3 +|Polymorphism|✓|OAS2,OAS3 +|Union|✓|OAS3 +|allOf|✓|OAS2,OAS3 +|anyOf|✓|OAS3 +|oneOf|✓|OAS3 +|not|✓|OAS3 ### Security Feature | Name | Supported | Defined By | @@ -228,6 +238,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Name | Supported | Defined By | | ---- | --------- | ---------- | |JSON|✓|OAS2,OAS3 -|XML|✓|OAS2,OAS3 +|XML|✗|OAS2,OAS3 |PROTOBUF|✗|ToolingExtension |Custom|✓|OAS2,OAS3 diff --git a/docs/generators/r.md b/docs/generators/r.md index a25d0d4468..c15ba4ad71 100644 --- a/docs/generators/r.md +++ b/docs/generators/r.md @@ -18,9 +18,13 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |errorObjectType|Error object type.| |null| |exceptionPackage|Specify the exception handling package|
    **default**
    Use stop() for raising exceptions.
    **rlang**
    Use rlang package for exceptions.
    |default| +|generateWrapper|Generate a wrapper class (single point of access) for the R client. This option only works with `httr2` library.| |false| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| +|library|HTTP library template (sub-template) to use|
    **httr2**
    httr2 (https://httr2.r-lib.org/)
    **httr**
    httr (https://cran.r-project.org/web/packages/httr/index.html)
    |httr| +|operationIdNaming|Naming convention for operationId (function name in the API)|
    **PascalCase**
    Pascal case (default)
    **snake_case**
    Snake case
    **camelCase**
    Camel case
    |null| |packageName|R package name (convention: lowercase).| |openapi| |packageVersion|R package version.| |1.0.0| |returnExceptionOnFailure|Throw an exception on non success response codes| |false| diff --git a/docs/generators/ruby.md b/docs/generators/ruby.md index 703f7ef7e0..7e88dbc2cf 100644 --- a/docs/generators/ruby.md +++ b/docs/generators/ruby.md @@ -38,6 +38,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|useAutoload|Use autoload instead of require to load modules.| |false| ## IMPORT MAPPING diff --git a/docs/generators/rust-server.md b/docs/generators/rust-server.md index ece538a608..14cea87981 100644 --- a/docs/generators/rust-server.md +++ b/docs/generators/rust-server.md @@ -11,7 +11,7 @@ title: Documentation for the rust-server Generator | generator type | SERVER | | | generator language | Rust | | | generator default templating engine | mustache | | -| helpTxt | Generates a Rust client/server library (beta) using the openapi-generator project. | | +| helpTxt | Generates a Rust Hyper/Tower server library. Also generates a matching Hyper client library within the same crate that implements the same trait. | | ## CONFIG OPTIONS These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. @@ -59,9 +59,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl ## RESERVED WORDS
      +
    • Self
    • abstract
    • -
    • alignof
    • as
    • +
    • async
    • +
    • await
    • become
    • box
    • break
    • @@ -69,6 +71,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
    • continue
    • crate
    • do
    • +
    • dyn
    • else
    • enum
    • extern
    • @@ -86,21 +89,18 @@ These options may be applied as additional-properties (cli) or configOptions (pl
    • mod
    • move
    • mut
    • -
    • offsetof
    • override
    • priv
    • -
    • proc
    • pub
    • -
    • pure
    • ref
    • return
    • self
    • -
    • sizeof
    • static
    • struct
    • super
    • trait
    • true
    • +
    • try
    • type
    • typeof
    • unsafe
    • diff --git a/docs/generators/rust.md b/docs/generators/rust.md index 03303f46ec..e0ac78e620 100644 --- a/docs/generators/rust.md +++ b/docs/generators/rust.md @@ -66,8 +66,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl ## RESERVED WORDS
        +
      • Self
      • abstract
      • -
      • alignof
      • as
      • async
      • await
      • @@ -96,16 +96,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl
      • mod
      • move
      • mut
      • -
      • offsetof
      • override
      • priv
      • -
      • proc
      • pub
      • -
      • pure
      • ref
      • return
      • self
      • -
      • sizeof
      • static
      • struct
      • super
      • diff --git a/docs/generators/scala-sttp.md b/docs/generators/scala-sttp.md index 089a70ac98..c56f756df9 100644 --- a/docs/generators/scala-sttp.md +++ b/docs/generators/scala-sttp.md @@ -53,6 +53,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl |LocalDate|org.joda.time.*| |LocalDateTime|org.joda.time.*| |LocalTime|org.joda.time.*| +|Seq|scala.collection.immutable.Seq| +|Set|scala.collection.immutable.Set| |Timestamp|java.sql.Timestamp| |URI|java.net.URI| |UUID|java.util.UUID| diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index 92d3265b1b..2fc6ba96fb 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -53,6 +53,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |swiftUseApiNamespace|Flag to make all the API classes inner-class of {{projectName}}API| |null| |useBacktickEscapes|Escape reserved words using backticks (default: false)| |false| |useClasses|Use final classes for models instead of structs (default: false)| |false| +|useCustomDateWithoutTime|Uses a custom type to decode and encode dates without time information to support OpenAPIs date format (default: false)| |false| |useJsonEncodable|Make models conform to JSONEncodable protocol (default: true)| |true| |useSPMFileStructure|Use SPM file structure and set the source path to Sources/{{projectName}} (default: false).| |null| @@ -83,6 +84,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
      • Int
      • Int32
      • Int64
      • +
      • OpenAPIDateWithoutTime
      • String
      • URL
      • UUID
      • diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index f41324a02e..7fde34c39a 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -11,7 +11,7 @@ title: Documentation for the typescript-angular Generator | generator type | CLIENT | | | generator language | Typescript | | | generator default templating engine | mustache | | -| helpTxt | Generates a TypeScript Angular (9.x - 13.x) client library. | | +| helpTxt | Generates a TypeScript Angular (9.x - 14.x) client library. | | ## CONFIG OPTIONS These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. @@ -31,7 +31,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |modelFileSuffix|The suffix of the file of the generated model (model<suffix>.ts).| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |modelSuffix|The suffix of the generated model.| |null| -|ngVersion|The version of Angular. (At least 9.0.0)| |13.0.1| +|ngVersion|The version of Angular. (At least 9.0.0)| |14.0.5| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| @@ -232,7 +232,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |XMLStructureDefinitions|✗|OAS2,OAS3 |MultiServer|✗|OAS3 |ParameterizedServer|✗|OAS3 -|ParameterStyling|✗|OAS3 +|ParameterStyling|✓|OAS3 |Callbacks|✗|OAS3 |LinkObjects|✗|OAS3 diff --git a/docs/generators/typescript-nestjs.md b/docs/generators/typescript-nestjs.md index 99d70502c6..38720fb941 100644 --- a/docs/generators/typescript-nestjs.md +++ b/docs/generators/typescript-nestjs.md @@ -11,7 +11,7 @@ title: Documentation for the typescript-nestjs Generator | generator type | CLIENT | | | generator language | Typescript | | | generator default templating engine | mustache | | -| helpTxt | Generates a TypeScript Nestjs 6.x client library. | | +| helpTxt | Generates a TypeScript Nestjs 8.x or 6.x client library. | | ## CONFIG OPTIONS These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. @@ -29,7 +29,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |modelFileSuffix|The suffix of the file of the generated model (model<suffix>.ts).| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |modelSuffix|The suffix of the generated model.| |null| -|nestVersion|The version of Nestjs.| |6.0.0| +|nestVersion|The version of Nestjs.|
        **8.0.0**
        Use new HttpModule and HttpService from @nestjs/axios.
        **6.0.0**
        Use old HttpModule and HttpService from @nestjs/common.
        |8.0.0| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/docs/installation.md b/docs/installation.md index 4aadfcbf3e..c56c97a00d 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -103,18 +103,18 @@ docker run --rm \ If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum): -JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.0.1/openapi-generator-cli-6.0.1.jar` +JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.2.0/openapi-generator-cli-6.2.0.jar` For **Mac/Linux** users: ```bash -wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.0.1/openapi-generator-cli-6.0.1.jar -O openapi-generator-cli.jar +wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.2.0/openapi-generator-cli-6.2.0.jar -O openapi-generator-cli.jar ``` For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g. ```powershell -Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.0.1/openapi-generator-cli-6.0.1.jar +Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.2.0/openapi-generator-cli-6.2.0.jar ``` diff --git a/modules/openapi-generator-gradle-plugin/README.adoc b/modules/openapi-generator-gradle-plugin/README.adoc index 9f993fb548..9982ec5e12 100644 --- a/modules/openapi-generator-gradle-plugin/README.adoc +++ b/modules/openapi-generator-gradle-plugin/README.adoc @@ -97,7 +97,7 @@ task validateGoodSpec(type: org.openapitools.generator.gradle.plugin.tasks.Valid [source,group] ---- plugins { - id "org.openapi.generator" version "6.0.1" + id "org.openapi.generator" version "6.2.0" } ---- @@ -113,7 +113,7 @@ buildscript { // url "https://plugins.gradle.org/m2/" } dependencies { - classpath "org.openapitools:openapi-generator-gradle-plugin:6.0.1" + classpath "org.openapitools:openapi-generator-gradle-plugin:6.2.0" } } @@ -695,7 +695,7 @@ buildscript { } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' - classpath('org.openapitools:openapi-generator-gradle-plugin:6.0.1') { + classpath('org.openapitools:openapi-generator-gradle-plugin:6.2.0') { exclude group: 'com.google.guava' } } diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md b/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md index d3ffccdb69..6428a36a3c 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md @@ -1,6 +1,6 @@ # Local Spec Sample -This example assumes you have Gradle 5.6.4+ installed. No gradle wrapper is provided in samples. +This example assumes you have Gradle 6.8.3+ installed. No gradle wrapper is provided in samples. First, publish the openapi-generator-gradle-plugin locally via `./gradlew assemble publishToMavenLocal` in the module directory. @@ -12,11 +12,12 @@ gradle openApiMeta # expected outcome: BUILD SUCCESSFUL gradle openApiValidate # expected outcome: BUILD FAILED gradle buildGoSdk # expected outcome: BUILD SUCCESSFUL gradle buildDotnetSdk # expected outcome: BUILD SUCCESSFUL +gradle buildJavaResttemplateSdk # expected outcome: BUILD SUCCESSFUL gradle generateGoWithInvalidSpec # expected outcome: BUILD FAILED ``` The samples can be tested against other versions of the plugin using the `openApiGeneratorVersion` property. For example: ```bash -gradle -PopenApiGeneratorVersion=6.0.1 openApiValidate +gradle -PopenApiGeneratorVersion=6.2.0 openApiValidate ``` diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/build.gradle b/modules/openapi-generator-gradle-plugin/samples/local-spec/build.gradle index cb99b8838f..06e7ed8891 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/build.gradle +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/build.gradle @@ -54,6 +54,25 @@ openApiGenerate { enablePostProcessFile = false } +task buildJavaResttemplateSdk(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) { + generatorName = "java" + library = "resttemplate" + inputSpec = "$rootDir/petstore-v3.0.yaml".toString() + outputDir = "$buildDir/java-resttemplate-api-client" + apiPackage = "com.example.client" + invokerPackage = "com.example.invoker" + modelPackage = "com.example.cdm" + configOptions = [ + dateLibrary: "java8" + ] + groupId = 'com.example' + id = 'client' + skipValidateSpec = true + logToStderr = true + generateAliasAsModel = false + enablePostProcessFile = false +} + task buildGoSdk(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask){ generatorName = "go" inputSpec = "$rootDir/petstore-v3.0.yaml".toString() diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle/wrapper/gradle-wrapper.properties b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle/wrapper/gradle-wrapper.properties index 5028f28f8e..442d9132ea 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle/wrapper/gradle-wrapper.properties +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew index 2fe81a7d95..20b741fb46 100755 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew @@ -44,7 +44,7 @@ APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" @@ -82,6 +82,7 @@ esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then @@ -92,14 +93,12 @@ if [ -n "$JAVA_HOME" ] ; then fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi @@ -129,6 +128,7 @@ fi if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew.bat b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew.bat index 9618d8d960..6a68175eb7 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew.bat +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew.bat @@ -29,15 +29,18 @@ if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" +set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -51,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -61,28 +64,14 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt index 2adddbdfcf..82fe7e761e 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt @@ -495,12 +495,14 @@ open class GenerateTask : DefaultTask() { } } + protected open fun createDefaultCodegenConfigurator(): CodegenConfigurator = CodegenConfigurator() + @Suppress("unused") @TaskAction fun doWork() { val configurator: CodegenConfigurator = if (configFile.isPresent) { CodegenConfigurator.fromFile(configFile.get()) - } else CodegenConfigurator() + } else createDefaultCodegenConfigurator() try { if (globalProperties.isPresent) { diff --git a/modules/openapi-generator-maven-plugin/README.md b/modules/openapi-generator-maven-plugin/README.md index cfa93b506d..38e54029cd 100644 --- a/modules/openapi-generator-maven-plugin/README.md +++ b/modules/openapi-generator-maven-plugin/README.md @@ -12,7 +12,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase) org.openapitools openapi-generator-maven-plugin - 6.0.1 + 6.2.0 diff --git a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java index 44e49ca521..f796ca6002 100644 --- a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java +++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java @@ -95,8 +95,7 @@ public class CodeGenMojo extends AbstractMojo { /** * Location of the output directory. */ - @Parameter(name = "output", property = "openapi.generator.maven.plugin.output", - defaultValue = "${project.build.directory}/generated-sources/openapi") + @Parameter(name = "output", property = "openapi.generator.maven.plugin.output") private File output; /** @@ -464,6 +463,12 @@ public class CodeGenMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { File inputSpecFile = new File(inputSpec); + + if (output == null) { + output = new File(project.getBuild().getDirectory(), + LifecyclePhase.GENERATE_TEST_SOURCES.id().equals(mojo.getLifecyclePhase()) ? + "generated-test-sources/openapi" : "generated-sources/openapi"); + } addCompileSourceRootIfConfigured(); try { @@ -913,21 +918,16 @@ public class CodeGenMojo extends AbstractMojo { name = Files.getNameWithoutExtension(segments[segments.length - 1]); } - return new File(output.getPath() + File.separator + ".openapi-generator" + File.separator + name + "-" + mojo.getExecutionId() + ".sha256"); + return new File(output.getPath() + File.separatorChar + ".openapi-generator" + File.separatorChar + name + "-" + mojo.getExecutionId() + ".sha256"); } private String getCompileSourceRoot() { final Object sourceFolderObject = configOptions == null ? null : configOptions .get(CodegenConstants.SOURCE_FOLDER); - final String sourceFolder; - if (sourceFolderObject != null) { - sourceFolder = sourceFolderObject.toString(); - } else { - sourceFolder = addTestCompileSourceRoot ? "src/test/java" : "src/main/java"; - } + final String sourceFolder = sourceFolderObject != null ? sourceFolderObject.toString() : "src/main/java"; - return output.toString() + "/" + sourceFolder; + return output.getPath() + File.separatorChar + sourceFolder; } private void addCompileSourceRootIfConfigured() throws MojoExecutionException { diff --git a/modules/openapi-generator/pom.xml b/modules/openapi-generator/pom.xml index 44f602e74d..e2baf341d1 100644 --- a/modules/openapi-generator/pom.xml +++ b/modules/openapi-generator/pom.xml @@ -247,11 +247,6 @@ - - io.swagger.core.v3 - swagger-core - ${swagger-core.version} - ${swagger-parser-groupid.version} swagger-parser diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java index 1890fc0d73..2917c2ee0a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java @@ -328,4 +328,6 @@ public interface CodegenConfig { List getSupportedVendorExtensions(); boolean getUseInlineModelResolver(); + + boolean getAddSuffixToDuplicateOperationNicknames(); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java index 1efd6b2502..2ee0c5474f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java @@ -388,7 +388,10 @@ public class CodegenConstants { public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC = "If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. " + "If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default."; - + public static final String UNSUPPORTED_V310_SPEC_MSG = + "Generation using 3.1.0 specs is in development and is not officially supported yet. " + + "If you would like to expedite development, please consider woking on the open issues in the 3.1.0 project: https://github.com/orgs/OpenAPITools/projects/4/views/1 " + + "and reach out to our team on Slack at https://join.slack.com/t/openapi-generator/shared_invite/zt-12jxxd7p2-XUeQM~4pzsU9x~eGLQqX2g"; public static final String ENUM_UNKNOWN_DEFAULT_CASE = "enumUnknownDefaultCase"; public static final String ENUM_UNKNOWN_DEFAULT_CASE_DESC = "If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response." + @@ -401,4 +404,15 @@ public class CodegenConstants { public static final String ERROR_OBJECT_TYPE = "errorObjectType"; + public static final String NON_COMPLIANT_USE_DISCR_IF_COMPOSITION_FAILS = "nonCompliantUseDiscriminatorIfCompositionFails"; + + public static final String NON_COMPLIANT_USE_DISCR_IF_COMPOSITION_FAILS_DESC = + "When true, If the payload fails to validate against composed schemas (allOf/anyOf/oneOf/not) and a " + + "discriminator is present, then ignore the composition validation errors and attempt to use the " + + "discriminator to validate the payload.
        " + + "Note: setting this to true makes the generated client not comply with json schema because it ignores " + + "composition validation errors. Please consider making your schemas more restrictive rather than " + + "setting this to true. You can do that by:
          " + + "
        • defining the propertyName as an enum with only one value in the schemas that are in your discriminator map
        • " + + "
        • setting additionalProperties: false in your schemas
        "; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenDiscriminator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenDiscriminator.java index dc99a94585..6cef953b7d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenDiscriminator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenDiscriminator.java @@ -22,6 +22,7 @@ public class CodegenDiscriminator { private String propertyGetter; private String propertyType; private Map mapping; + private boolean isEnum; // mappedModels is populated differently if legacyDiscriminatorBehavior is // True or False. When: @@ -88,6 +89,14 @@ public class CodegenDiscriminator { this.mappedModels = mappedModels; } + public boolean getIsEnum() { + return isEnum; + } + + public void setIsEnum(boolean isEnum) { + this.isEnum = isEnum; + } + /** * An object to hold discriminator mappings between payload values and schema names or * references. diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenMediaType.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenMediaType.java index 965e503194..2728bc632f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenMediaType.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenMediaType.java @@ -1,15 +1,20 @@ package org.openapitools.codegen; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Objects; public class CodegenMediaType { private CodegenProperty schema; private LinkedHashMap encoding; + private HashMap testCases = new HashMap<>(); - public CodegenMediaType(CodegenProperty schema, LinkedHashMap encoding) { + public CodegenMediaType(CodegenProperty schema, LinkedHashMap encoding, HashMap testCases) { this.schema = schema; this.encoding = encoding; + if (testCases != null) { + this.testCases = testCases; + } } public CodegenProperty getSchema() { @@ -20,6 +25,8 @@ public class CodegenMediaType { return encoding; } + public HashMap getTestCases() { return testCases; } + public String toString() { final StringBuilder sb = new StringBuilder("CodegenMediaType{"); sb.append("schema=").append(schema); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java index a8107fb07d..26d06d5fbb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java @@ -111,6 +111,12 @@ public class CodegenModel implements IJsonSchemaValidationProperties { private CodegenComposedSchemas composedSchemas; private boolean hasMultipleTypes = false; public HashMap testCases = new HashMap<>(); + private boolean schemaIsFromAdditionalProperties; + private boolean isBooleanSchemaTrue; + private boolean isBooleanSchemaFalse; + private String format; + private LinkedHashMap> dependentRequired; + private CodegenProperty contains; /** * The type of the value for the additionalProperties keyword in the OAS document. @@ -147,6 +153,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties { private Integer maxProperties; private Integer minProperties; private boolean uniqueItems; + private Boolean uniqueItemsBoolean; private Integer maxItems; private Integer minItems; private Integer maxLength; @@ -164,6 +171,8 @@ public class CodegenModel implements IJsonSchemaValidationProperties { private boolean hasDiscriminatorWithNonEmptyMapping; private boolean isAnyType; private boolean isUuid; + private Map requiredVarsMap; + private String ref; public String getAdditionalPropertiesType() { return additionalPropertiesType; @@ -173,6 +182,76 @@ public class CodegenModel implements IJsonSchemaValidationProperties { this.additionalPropertiesType = additionalPropertiesType; } + @Override + public CodegenProperty getContains() { + return contains; + } + + @Override + public void setContains(CodegenProperty contains) { + this.contains = contains; + } + + @Override + public LinkedHashMap> getDependentRequired() { + return dependentRequired; + } + + @Override + public void setDependentRequired(LinkedHashMap> dependentRequired) { + this.dependentRequired = dependentRequired; + } + + @Override + public boolean getIsBooleanSchemaTrue() { + return isBooleanSchemaTrue; + } + + @Override + public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) { + this.isBooleanSchemaTrue = isBooleanSchemaTrue; + } + + @Override + public boolean getIsBooleanSchemaFalse() { + return isBooleanSchemaFalse; + } + + @Override + public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) { + this.isBooleanSchemaFalse = isBooleanSchemaFalse; + } + + @Override + public String getFormat() { + return format; + } + + @Override + public void setFormat(String format) { + this.format = format; + } + + @Override + public String getRef() { + return ref; + } + + @Override + public void setRef(String ref) { + this.ref = ref; + } + + @Override + public boolean getSchemaIsFromAdditionalProperties() { + return schemaIsFromAdditionalProperties; + } + + @Override + public void setSchemaIsFromAdditionalProperties(boolean schemaIsFromAdditionalProperties) { + this.schemaIsFromAdditionalProperties = schemaIsFromAdditionalProperties; + } + public Set getAllMandatory() { return allMandatory; } @@ -546,6 +625,16 @@ public class CodegenModel implements IJsonSchemaValidationProperties { this.uniqueItems = uniqueItems; } + @Override + public Boolean getUniqueItemsBoolean() { + return uniqueItemsBoolean; + } + + @Override + public void setUniqueItemsBoolean(Boolean uniqueItemsBoolean) { + this.uniqueItemsBoolean = uniqueItemsBoolean; + } + @Override public Integer getMinProperties() { return minProperties; @@ -825,8 +914,6 @@ public class CodegenModel implements IJsonSchemaValidationProperties { return hasDiscriminatorWithNonEmptyMapping; } - ; - @Override public void setHasDiscriminatorWithNonEmptyMapping(boolean hasDiscriminatorWithNonEmptyMapping) { this.hasDiscriminatorWithNonEmptyMapping = hasDiscriminatorWithNonEmptyMapping; @@ -923,11 +1010,20 @@ public class CodegenModel implements IJsonSchemaValidationProperties { hasMultipleTypes == that.getHasMultipleTypes() && hasDiscriminatorWithNonEmptyMapping == that.getHasDiscriminatorWithNonEmptyMapping() && isUuid == that.getIsUuid() && + isBooleanSchemaTrue == that.getIsBooleanSchemaTrue() && + isBooleanSchemaFalse == that.getIsBooleanSchemaFalse() && + getSchemaIsFromAdditionalProperties() == that.getSchemaIsFromAdditionalProperties() && getIsAnyType() == that.getIsAnyType() && getAdditionalPropertiesIsAnyType() == that.getAdditionalPropertiesIsAnyType() && getUniqueItems() == that.getUniqueItems() && getExclusiveMinimum() == that.getExclusiveMinimum() && getExclusiveMaximum() == that.getExclusiveMaximum() && + Objects.equals(contains, that.getContains()) && + Objects.equals(dependentRequired, that.getDependentRequired()) && + Objects.equals(format, that.getFormat()) && + Objects.equals(uniqueItemsBoolean, that.getUniqueItemsBoolean()) && + Objects.equals(ref, that.getRef()) && + Objects.equals(requiredVarsMap, that.getRequiredVarsMap()) && Objects.equals(composedSchemas, that.composedSchemas) && Objects.equals(parent, that.parent) && Objects.equals(parentSchema, that.parentSchema) && @@ -1000,7 +1096,9 @@ public class CodegenModel implements IJsonSchemaValidationProperties { getMinItems(), getMaxLength(), getMinLength(), getExclusiveMinimum(), getExclusiveMaximum(), getMinimum(), getMaximum(), getPattern(), getMultipleOf(), getItems(), getAdditionalProperties(), getIsModel(), getAdditionalPropertiesIsAnyType(), hasDiscriminatorWithNonEmptyMapping, - isAnyType, getComposedSchemas(), hasMultipleTypes, isDecimal, isUuid); + isAnyType, getComposedSchemas(), hasMultipleTypes, isDecimal, isUuid, requiredVarsMap, ref, + uniqueItemsBoolean, schemaIsFromAdditionalProperties, isBooleanSchemaTrue, isBooleanSchemaFalse, + format, dependentRequired, contains); } @Override @@ -1075,6 +1173,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties { sb.append(", maxProperties=").append(maxProperties); sb.append(", minProperties=").append(minProperties); sb.append(", uniqueItems=").append(uniqueItems); + sb.append(", uniqueItemsBoolean=").append(uniqueItemsBoolean); sb.append(", maxItems=").append(maxItems); sb.append(", minItems=").append(minItems); sb.append(", maxLength=").append(maxLength); @@ -1097,6 +1196,14 @@ public class CodegenModel implements IJsonSchemaValidationProperties { sb.append(", hasMultipleTypes=").append(hasMultipleTypes); sb.append(", isDecimal=").append(isDecimal); sb.append(", isUUID=").append(isUuid); + sb.append(", requiredVarsMap=").append(requiredVarsMap); + sb.append(", ref=").append(ref); + sb.append(", schemaIsFromAdditionalProperties=").append(schemaIsFromAdditionalProperties); + sb.append(", isBooleanSchemaTrue=").append(isBooleanSchemaTrue); + sb.append(", isBooleanSchemaFalse=").append(isBooleanSchemaFalse); + sb.append(", format=").append(format); + sb.append(", dependentRequired=").append(dependentRequired); + sb.append(", contains=").append(contains); sb.append('}'); return sb.toString(); } @@ -1124,6 +1231,12 @@ public class CodegenModel implements IJsonSchemaValidationProperties { return this.items != null; } + @Override + public Map getRequiredVarsMap() { return requiredVarsMap; } + + @Override + public void setRequiredVarsMap(Map requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; } + /** * Remove duplicated properties in all variable list */ diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java index 16daa41f58..2672a1709a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java @@ -27,7 +27,7 @@ public class CodegenOperation { public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, hasRequiredParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMap, isArray, isMultipart, - isResponseBinary = false, isResponseFile = false, isResponseOptional = false, hasReference = false, + isResponseBinary = false, isResponseFile = false, isResponseOptional = false, hasReference = false, defaultReturnType = false, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false, hasErrorResponseObject; // if 4xx, 5xx responses have at least one error object defined @@ -193,6 +193,27 @@ public class CodegenOperation { return responses.stream().anyMatch(response -> response.isDefault); } + public boolean getAllResponsesAreErrors() { + return responses.stream().allMatch(response -> response.is4xx || response.is5xx); + } + + /** + * @return contentTypeToOperation + * returns a map where the key is the request body content type and the value is the current CodegenOperation + * this is needed by templates when a different signature is needed for each request body content type + */ + public Map getContentTypeToOperation() { + LinkedHashMap contentTypeToOperation = new LinkedHashMap<>(); + if (bodyParam == null) { + return null; + } + LinkedHashMap content = bodyParam.getContent(); + for (String contentType: content.keySet()) { + contentTypeToOperation.put(contentType, this); + } + return contentTypeToOperation; + } + /** * Check if there's at least one vendor extension * diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index af222869bf..ca8ac29eb3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -29,7 +29,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, isDeepObject, isAllowEmptyValue; public String baseName, paramName, dataType, datatypeWithEnum, dataFormat, contentType, - collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style; + collectionFormat, description, unescapedDescription, baseType, defaultValue, enumDefaultValue, enumName, style; public String nameInLowerCase; // property name in lower case public String example; // example value (x-example) @@ -99,6 +99,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { * See http://json-schema.org/latest/json-schema-validation.html#anchor49 */ public boolean uniqueItems; + private Boolean uniqueItemsBoolean; /** * See http://json-schema.org/latest/json-schema-validation.html#anchor14 */ @@ -111,6 +112,10 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { private CodegenComposedSchemas composedSchemas; private boolean hasMultipleTypes = false; private LinkedHashMap content; + private Map requiredVarsMap; + private String ref; + + private boolean schemaIsFromAdditionalProperties; public CodegenParameter copy() { CodegenParameter output = new CodegenParameter(); @@ -146,9 +151,11 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { output.maxItems = this.maxItems; output.minItems = this.minItems; output.uniqueItems = this.uniqueItems; + output.setUniqueItemsBoolean(this.uniqueItemsBoolean); output.multipleOf = this.multipleOf; output.jsonSchema = this.jsonSchema; output.defaultValue = this.defaultValue; + output.enumDefaultValue = this.enumDefaultValue; output.example = this.example; output.isEnum = this.isEnum; output.maxProperties = this.maxProperties; @@ -163,6 +170,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { output.setHasRequired(this.hasRequired); output.setHasDiscriminatorWithNonEmptyMapping(this.hasDiscriminatorWithNonEmptyMapping); output.setHasMultipleTypes(this.hasMultipleTypes); + output.setSchemaIsFromAdditionalProperties(this.schemaIsFromAdditionalProperties); if (this.content != null) { output.setContent(this.content); @@ -194,6 +202,12 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { if (this.vendorExtensions != null) { output.vendorExtensions = new HashMap(this.vendorExtensions); } + if (this.requiredVarsMap != null) { + output.setRequiredVarsMap(this.requiredVarsMap); + } + if (this.ref != null) { + output.setRef(this.ref); + } output.hasValidation = this.hasValidation; output.isNullable = this.isNullable; output.isDeprecated = this.isDeprecated; @@ -230,7 +244,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { @Override public int hashCode() { - return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, isAllowEmptyValue, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content); + return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumDefaultValue, enumName, style, isDeepObject, isAllowEmptyValue, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content, requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties); } @Override @@ -281,11 +295,15 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { hasDiscriminatorWithNonEmptyMapping == that.getHasDiscriminatorWithNonEmptyMapping() && getAdditionalPropertiesIsAnyType() == that.getAdditionalPropertiesIsAnyType() && hasMultipleTypes == that.getHasMultipleTypes() && + getSchemaIsFromAdditionalProperties() == that.getSchemaIsFromAdditionalProperties() && getHasVars() == that.getHasVars() && getHasRequired() == that.getHasRequired() && getExclusiveMaximum() == that.getExclusiveMaximum() && getExclusiveMinimum() == that.getExclusiveMinimum() && getUniqueItems() == that.getUniqueItems() && + Objects.equals(uniqueItemsBoolean, that.getUniqueItemsBoolean()) && + Objects.equals(ref, that.getRef()) && + Objects.equals(requiredVarsMap, that.getRequiredVarsMap()) && Objects.equals(content, that.getContent()) && Objects.equals(schema, that.getSchema()) && Objects.equals(composedSchemas, that.getComposedSchemas()) && @@ -299,6 +317,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { Objects.equals(unescapedDescription, that.unescapedDescription) && Objects.equals(baseType, that.baseType) && Objects.equals(defaultValue, that.defaultValue) && + Objects.equals(enumDefaultValue, that.enumDefaultValue) && Objects.equals(enumName, that.enumName) && Objects.equals(style, that.style) && Objects.equals(isDeepObject, that.isDeepObject) && @@ -350,6 +369,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { sb.append(", unescapedDescription='").append(unescapedDescription).append('\''); sb.append(", baseType='").append(baseType).append('\''); sb.append(", defaultValue='").append(defaultValue).append('\''); + sb.append(", enumDefaultValue='").append(enumDefaultValue).append('\''); sb.append(", enumName='").append(enumName).append('\''); sb.append(", style='").append(style).append('\''); sb.append(", deepObject='").append(isDeepObject).append('\''); @@ -404,6 +424,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { sb.append(", maxItems=").append(maxItems); sb.append(", minItems=").append(minItems); sb.append(", uniqueItems=").append(uniqueItems); + sb.append(", uniqueItemsBoolean=").append(uniqueItemsBoolean); sb.append(", contentType=").append(contentType); sb.append(", multipleOf=").append(multipleOf); sb.append(", isNull=").append(isNull); @@ -415,10 +436,63 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { sb.append(", hasMultipleTypes=").append(hasMultipleTypes); sb.append(", schema=").append(schema); sb.append(", content=").append(content); + sb.append(", requiredVarsMap=").append(requiredVarsMap); + sb.append(", ref=").append(ref); + sb.append(", schemaIsFromAdditionalProperties=").append(schemaIsFromAdditionalProperties); sb.append('}'); return sb.toString(); } + // use schema.getContains or content.mediaType.schema.getContains instead of this + @Override + public CodegenProperty getContains() { + return null; + } + + // use schema.setContains or content.mediaType.schema.setContains instead of this + @Override + public void setContains(CodegenProperty contains) {} + + // use schema.getDependentRequired or content.mediaType.schema.getDependentRequired instead of this + @Override + public LinkedHashMap> getDependentRequired() { + return null; + } + + // use schema.setDependentRequired or content.mediaType.schema.setDependentRequired instead of this + @Override + public void setDependentRequired(LinkedHashMap> dependentRequired) {} + + // use schema.getIsBooleanSchemaTrue or content.mediaType.schema.getIsBooleanSchemaTrue instead of this + @Override + public boolean getIsBooleanSchemaTrue() { + return false; + } + + // use schema.setIsBooleanSchemaTrue or content.mediaType.schema.setIsBooleanSchemaTrue instead of this + @Override + public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) {} + + // use schema.getIsBooleanSchemaFalse or content.mediaType.schema.getIsBooleanSchemaFalse instead of this + @Override + public boolean getIsBooleanSchemaFalse() { + return false; + } + + // use schema.setIsBooleanSchemaFalse or content.mediaType.schema.setIsBooleanSchemaFalse instead of this + @Override + public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) {} + + // use schema.getFormat or content.mediaType.schema.getFormat instead of this + @Override + public String getFormat() { + return null; + } + + // use schema.setFormat or content.mediaType.schema.setFormat instead of this + @Override + public void setFormat(String format) {} + @Override public String getPattern() { return pattern; @@ -519,6 +593,16 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { this.uniqueItems = uniqueItems; } + @Override + public Boolean getUniqueItemsBoolean() { + return uniqueItemsBoolean; + } + + @Override + public void setUniqueItemsBoolean(Boolean uniqueItemsBoolean) { + this.uniqueItemsBoolean = uniqueItemsBoolean; + } + @Override public Integer getMinProperties() { return minProperties; @@ -815,5 +899,27 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { public String getBaseType() { return baseType; } + + @Override + public Map getRequiredVarsMap() { return requiredVarsMap; } + + @Override + public void setRequiredVarsMap(Map requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; } + + @Override + public String getRef() { return ref; } + + @Override + public void setRef(String ref) { this.ref=ref; } + + @Override + public boolean getSchemaIsFromAdditionalProperties() { + return schemaIsFromAdditionalProperties; + } + + @Override + public void setSchemaIsFromAdditionalProperties(boolean schemaIsFromAdditionalProperties) { + this.schemaIsFromAdditionalProperties = schemaIsFromAdditionalProperties; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java index 56aee00ce3..e5fe46954b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java @@ -149,6 +149,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti public boolean isArray; public boolean isMap; public boolean isEnum; + public boolean isInnerEnum; // Enums declared inline will be located inside the generic model, changing how the enum is referenced in some cases. public boolean isReadOnly; public boolean isWriteOnly; public boolean isNullable; @@ -180,6 +181,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti private Integer maxProperties; private Integer minProperties; private boolean uniqueItems; + private Boolean uniqueItemsBoolean; // XML public boolean isXmlAttribute = false; @@ -193,6 +195,60 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti private boolean hasDiscriminatorWithNonEmptyMapping; private CodegenComposedSchemas composedSchemas = null; private boolean hasMultipleTypes = false; + private Map requiredVarsMap; + private String ref; + private boolean schemaIsFromAdditionalProperties; + private boolean isBooleanSchemaTrue; + private boolean isBooleanSchemaFalse; + private String format; + private LinkedHashMap> dependentRequired; + private CodegenProperty contains; + + @Override + public CodegenProperty getContains() { + return contains; + } + + @Override + public void setContains(CodegenProperty contains) { + this.contains = contains; + } + + @Override + public LinkedHashMap> getDependentRequired() { + return dependentRequired; + } + + @Override + public void setDependentRequired(LinkedHashMap> dependentRequired) { + this.dependentRequired = dependentRequired; + } + + @Override + public void setFormat(String format) { this.format = format; } + + @Override + public String getFormat() { return format; } + + @Override + public boolean getIsBooleanSchemaTrue() { + return isBooleanSchemaTrue; + } + + @Override + public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) { + this.isBooleanSchemaTrue = true; + } + + @Override + public boolean getIsBooleanSchemaFalse() { + return isBooleanSchemaFalse; + } + + @Override + public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) { + this.isBooleanSchemaFalse = isBooleanSchemaFalse; + } public String getBaseName() { return baseName; @@ -340,6 +396,16 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti this.unescapedDescription = unescapedDescription; } + @Override + public boolean getSchemaIsFromAdditionalProperties() { + return schemaIsFromAdditionalProperties; + } + + @Override + public void setSchemaIsFromAdditionalProperties(boolean schemaIsFromAdditionalProperties) { + this.schemaIsFromAdditionalProperties = schemaIsFromAdditionalProperties; + } + @Override public Integer getMaxLength() { return maxLength; @@ -658,6 +724,16 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti return composedSchemas; } + @Override + public void setRef(String ref) { + this.ref = ref; + } + + @Override + public String getRef() { + return ref; + } + @Override public CodegenProperty clone() { try { @@ -689,6 +765,21 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti if (this.composedSchemas != null) { cp.composedSchemas = this.composedSchemas; } + if (this.requiredVarsMap != null) { + cp.setRequiredVarsMap(this.requiredVarsMap); + } + if (this.ref != null) { + cp.setRef(this.ref); + } + if (this.format != null) { + cp.setFormat(this.format); + } + if (this.dependentRequired != null) { + cp.setDependentRequired(this.dependentRequired); + } + if (this.contains != null) { + cp.setContains(this.contains); + } return cp; } catch (CloneNotSupportedException e) { @@ -706,6 +797,16 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti this.uniqueItems = uniqueItems; } + @Override + public Boolean getUniqueItemsBoolean() { + return uniqueItemsBoolean; + } + + @Override + public void setUniqueItemsBoolean(Boolean uniqueItemsBoolean) { + this.uniqueItemsBoolean = uniqueItemsBoolean; + } + @Override public Integer getMinProperties() { return minProperties; @@ -866,6 +967,12 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti public void setIsUuid(boolean isUuid) { this.isUuid = isUuid; } + @Override + public Map getRequiredVarsMap() { return requiredVarsMap; } + + @Override + public void setRequiredVarsMap(Map requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; } + @Override public String toString() { final StringBuilder sb = new StringBuilder("CodegenProperty{"); @@ -925,6 +1032,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti sb.append(", isArray=").append(isArray); sb.append(", isMap=").append(isMap); sb.append(", isEnum=").append(isEnum); + sb.append(", isInnerEnum=").append(isInnerEnum); sb.append(", isAnyType=").append(isAnyType); sb.append(", isReadOnly=").append(isReadOnly); sb.append(", isWriteOnly=").append(isWriteOnly); @@ -951,6 +1059,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti sb.append(", maxProperties=").append(maxProperties); sb.append(", minProperties=").append(minProperties); sb.append(", uniqueItems=").append(uniqueItems); + sb.append(", uniqueItemsBoolean=").append(uniqueItemsBoolean); sb.append(", multipleOf=").append(multipleOf); sb.append(", isXmlAttribute=").append(isXmlAttribute); sb.append(", xmlPrefix='").append(xmlPrefix).append('\''); @@ -964,6 +1073,14 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti sb.append(", getHasDiscriminatorWithNonEmptyMapping=").append(hasDiscriminatorWithNonEmptyMapping); sb.append(", composedSchemas=").append(composedSchemas); sb.append(", hasMultipleTypes=").append(hasMultipleTypes); + sb.append(", requiredVarsMap=").append(requiredVarsMap); + sb.append(", ref=").append(ref); + sb.append(", schemaIsFromAdditionalProperties=").append(schemaIsFromAdditionalProperties); + sb.append(", isBooleanSchemaTrue=").append(isBooleanSchemaTrue); + sb.append(", isBooleanSchemaFalse=").append(isBooleanSchemaFalse); + sb.append(", format=").append(format); + sb.append(", dependentRequired=").append(dependentRequired); + sb.append(", contains=").append(contains); sb.append('}'); return sb.toString(); } @@ -1004,6 +1121,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti isArray == that.isArray && isMap == that.isMap && isEnum == that.isEnum && + isInnerEnum == that.isInnerEnum && isAnyType == that.isAnyType && isReadOnly == that.isReadOnly && isWriteOnly == that.isWriteOnly && @@ -1018,9 +1136,18 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti isNull == that.isNull && hasMultipleTypes == that.getHasMultipleTypes() && hasDiscriminatorWithNonEmptyMapping == that.hasDiscriminatorWithNonEmptyMapping && + isBooleanSchemaTrue == that.getIsBooleanSchemaTrue() && + isBooleanSchemaFalse == that.getIsBooleanSchemaFalse() && + getSchemaIsFromAdditionalProperties() == that.getSchemaIsFromAdditionalProperties() && getAdditionalPropertiesIsAnyType() == that.getAdditionalPropertiesIsAnyType() && getHasVars() == that.getHasVars() && getHasRequired() == that.getHasRequired() && + Objects.equals(contains, that.getContains()) && + Objects.equals(dependentRequired, that.getDependentRequired()) && + Objects.equals(format, that.getFormat()) && + Objects.equals(uniqueItemsBoolean, that.getUniqueItemsBoolean()) && + Objects.equals(ref, that.getRef()) && + Objects.equals(requiredVarsMap, that.getRequiredVarsMap()) && Objects.equals(composedSchemas, that.composedSchemas) && Objects.equals(openApiType, that.openApiType) && Objects.equals(baseName, that.baseName) && @@ -1078,12 +1205,14 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti hasMoreNonReadOnly, isPrimitiveType, isModel, isContainer, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, - isArray, isMap, isEnum, isAnyType, isReadOnly, isWriteOnly, isNullable, isShort, + isArray, isMap, isEnum, isInnerEnum, isAnyType, isReadOnly, isWriteOnly, isNullable, isShort, isUnboundedInteger, isSelfReference, isCircularReference, isDiscriminator, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, isInherited, discriminatorValue, nameInCamelCase, nameInSnakeCase, enumName, maxItems, minItems, isXmlAttribute, xmlPrefix, xmlName, xmlNamespace, isXmlWrapped, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, - hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes); + hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, requiredVarsMap, + ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties, isBooleanSchemaTrue, isBooleanSchemaFalse, + format, dependentRequired, contains); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index f27d5bb13a..aa6b103b77 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -67,6 +67,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { private Integer maxProperties; private Integer minProperties; private boolean uniqueItems; + private Boolean uniqueItemsBoolean; private Integer maxItems; private Integer minItems; private Integer maxLength; @@ -89,6 +90,9 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { private CodegenComposedSchemas composedSchemas; private boolean hasMultipleTypes = false; private LinkedHashMap content; + private Map requiredVarsMap; + private String ref; + private boolean schemaIsFromAdditionalProperties; @Override public int hashCode() { @@ -100,7 +104,8 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { getMaxProperties(), getMinProperties(), uniqueItems, getMaxItems(), getMinItems(), getMaxLength(), getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern(), is1xx, is2xx, is3xx, is4xx, is5xx, additionalPropertiesIsAnyType, hasVars, hasRequired, - hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, responseHeaders, content); + hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, responseHeaders, content, + requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties); } @Override @@ -146,9 +151,13 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { is5xx == that.is5xx && hasDiscriminatorWithNonEmptyMapping == that.getHasDiscriminatorWithNonEmptyMapping() && hasMultipleTypes == that.getHasMultipleTypes() && + getSchemaIsFromAdditionalProperties() == that.getSchemaIsFromAdditionalProperties() && getAdditionalPropertiesIsAnyType() == that.getAdditionalPropertiesIsAnyType() && getHasVars() == that.getHasVars() && getHasRequired() == that.getHasRequired() && + Objects.equals(uniqueItemsBoolean, that.getUniqueItemsBoolean()) && + Objects.equals(ref, that.getRef()) && + Objects.equals(requiredVarsMap, that.getRequiredVarsMap()) && Objects.equals(content, that.getContent()) && Objects.equals(responseHeaders, that.getResponseHeaders()) && Objects.equals(composedSchemas, that.getComposedSchemas()) && @@ -180,6 +189,56 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { } + // use content.mediaType.schema.getContains instead of this + @Override + public CodegenProperty getContains() { + return null; + } + + // use content.mediaType.schema.setContains instead of this + @Override + public void setContains(CodegenProperty contains) {} + + // use content.mediaType.schema.getDependentRequired instead of this + @Override + public LinkedHashMap> getDependentRequired() { + return null; + } + + // use content.mediaType.schema.setDependentRequired instead of this + @Override + public void setDependentRequired(LinkedHashMap> dependentRequired) {} + + // use content.mediaType.schema.getIsBooleanSchemaTrue instead of this + @Override + public boolean getIsBooleanSchemaTrue() { + return false; + } + + // use content.mediaType.schema.setIsBooleanSchemaTrue instead of this + @Override + public void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue) {} + + // use content.mediaType.schema.getIsBooleanSchemaFalse instead of this + @Override + public boolean getIsBooleanSchemaFalse() { + return false; + } + + // use content.mediaType.schema.setIsBooleanSchemaFalse instead of this + @Override + public void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse) {} + + // use content.mediaType.schema.getFormat instead of this + @Override + public String getFormat() { + return null; + } + + // use content.mediaType.schema.setFormat instead of this + @Override + public void setFormat(String format) {} + public LinkedHashMap getContent() { return content; } @@ -296,6 +355,17 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { this.uniqueItems = uniqueItems; } + @Override + public Boolean getUniqueItemsBoolean() { + return uniqueItemsBoolean; + } + + @Override + public void setUniqueItemsBoolean(Boolean uniqueItemsBoolean) { + this.uniqueItemsBoolean = uniqueItemsBoolean; + } + + @Override public Integer getMinProperties() { return minProperties; @@ -514,6 +584,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { sb.append(", maxProperties=").append(maxProperties); sb.append(", minProperties=").append(minProperties); sb.append(", uniqueItems=").append(uniqueItems); + sb.append(", uniqueItemsBoolean=").append(uniqueItemsBoolean); sb.append(", maxItems=").append(maxItems); sb.append(", minItems=").append(minItems); sb.append(", maxLength=").append(maxLength); @@ -538,6 +609,9 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { sb.append(", hasMultipleTypes=").append(hasMultipleTypes); sb.append(", responseHeaders=").append(responseHeaders); sb.append(", content=").append(content); + sb.append(", requiredVarsMap=").append(requiredVarsMap); + sb.append(", ref=").append(ref); + sb.append(", schemaIsFromAdditionalProperties=").append(schemaIsFromAdditionalProperties); sb.append('}'); return sb.toString(); } @@ -665,4 +739,26 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { public String getBaseType() { return baseType; } + + @Override + public Map getRequiredVarsMap() { return requiredVarsMap; } + + @Override + public void setRequiredVarsMap(Map requiredVarsMap) { this.requiredVarsMap=requiredVarsMap; } + + @Override + public String getRef() { return ref; } + + @Override + public void setRef(String ref) { this.ref=ref; } + + @Override + public boolean getSchemaIsFromAdditionalProperties() { + return schemaIsFromAdditionalProperties; + } + + @Override + public void setSchemaIsFromAdditionalProperties(boolean schemaIsFromAdditionalProperties) { + this.schemaIsFromAdditionalProperties = schemaIsFromAdditionalProperties; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index cc015079a4..d6eef2a422 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -79,6 +79,7 @@ import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.oas.models.servers.ServerVariable; import io.swagger.v3.parser.util.SchemaTypeUtil; +import static org.openapitools.codegen.CodegenConstants.UNSUPPORTED_V310_SPEC_MSG; import static org.openapitools.codegen.utils.OnceLogger.once; import static org.openapitools.codegen.utils.StringUtils.*; @@ -90,6 +91,10 @@ public class DefaultCodegen implements CodegenConfig { // A cache of sanitized words. The sanitizeName() method is invoked many times with the same // arguments, this cache is used to optimized performance. private static Cache sanitizedNameCache; + private static final String xSchemaTestExamplesKey = "x-schema-test-examples"; + private static final String xSchemaTestExamplesRefPrefix = "#/components/x-schema-test-examples/"; + protected static Schema falseSchema; + protected static Schema trueSchema = new Schema(); static { DefaultFeatureSet = FeatureSet.newBuilder() @@ -142,6 +147,8 @@ public class DefaultCodegen implements CodegenConfig { .expireAfterAccess(cacheExpiry, TimeUnit.SECONDS) .ticker(Ticker.systemTicker()) .build(); + falseSchema = new Schema(); + falseSchema.setNot(new Schema()); } protected GeneratorMetadata generatorMetadata; @@ -149,6 +156,7 @@ public class DefaultCodegen implements CodegenConfig { protected String outputFolder = ""; protected Set defaultIncludes; protected Map typeMapping; + // instantiationTypes map from container types only: set, map, and array to the in language-type protected Map instantiationTypes; protected Set reservedWords; protected Set languageSpecificPrimitives = new HashSet<>(); @@ -279,6 +287,22 @@ public class DefaultCodegen implements CodegenConfig { protected boolean loadDeepObjectIntoItems = true; + // if true then baseTypes will be imported + protected boolean importBaseType = true; + + // if true then container types will be imported + protected boolean importContainerType = true; + + // if True codegenParameter and codegenResponse imports will come + // from deeper schema defined locations + protected boolean addSchemaImportsFromV3SpecLocations = false; + + protected boolean addSuffixToDuplicateOperationNicknames = true; + + public boolean getAddSuffixToDuplicateOperationNicknames() { + return addSuffixToDuplicateOperationNicknames; + } + @Override public List cliOptions() { return cliOptions; @@ -286,6 +310,7 @@ public class DefaultCodegen implements CodegenConfig { @Override public void processOpts() { + if (additionalProperties.containsKey(CodegenConstants.TEMPLATE_DIR)) { this.setTemplateDir((String) additionalProperties.get(CodegenConstants.TEMPLATE_DIR)); } @@ -802,6 +827,19 @@ public class DefaultCodegen implements CodegenConfig { */ @Override public void setOpenAPI(OpenAPI openAPI) { + String originalSpecVersion; + String xOriginalSwaggerVersion = "x-original-swagger-version"; + if (openAPI.getExtensions() != null && !openAPI.getExtensions().isEmpty() && openAPI.getExtensions().containsValue(xOriginalSwaggerVersion)) { + originalSpecVersion = (String) openAPI.getExtensions().get(xOriginalSwaggerVersion); + } else { + originalSpecVersion = openAPI.getOpenapi(); + } + Integer specMajorVersion = Integer.parseInt(originalSpecVersion.substring(0, 1)); + Integer specMinorVersion = Integer.parseInt(originalSpecVersion.substring(2, 3)); + boolean specVersionGreaterThanOrEqualTo310 = (specMajorVersion == 3 && specMinorVersion >= 1); + if (specVersionGreaterThanOrEqualTo310) { + LOGGER.warn(UNSUPPORTED_V310_SPEC_MSG); + } this.openAPI = openAPI; // Set global settings such that helper functions in ModelUtils can lookup the value // of the CLI option. @@ -2456,15 +2494,17 @@ public class DefaultCodegen implements CodegenConfig { } private static class NamedSchema { - private NamedSchema(String name, Schema s, boolean required) { + private NamedSchema(String name, Schema s, boolean required, boolean schemaIsFromAdditionalProperties) { this.name = name; this.schema = s; this.required = required; + this.schemaIsFromAdditionalProperties = schemaIsFromAdditionalProperties; } private String name; private Schema schema; private boolean required; + private boolean schemaIsFromAdditionalProperties; @Override public boolean equals(Object o) { @@ -2473,12 +2513,13 @@ public class DefaultCodegen implements CodegenConfig { NamedSchema that = (NamedSchema) o; return Objects.equals(required, that.required) && Objects.equals(name, that.name) && - Objects.equals(schema, that.schema); + Objects.equals(schema, that.schema) && + Objects.equals(schemaIsFromAdditionalProperties, that.schemaIsFromAdditionalProperties); } @Override public int hashCode() { - return Objects.hash(name, schema, required); + return Objects.hash(name, schema, required, schemaIsFromAdditionalProperties); } } @@ -2690,6 +2731,7 @@ public class DefaultCodegen implements CodegenConfig { } // process 'additionalProperties' setAddProps(schema, m); + addRequiredVarsMap(schema, m); } protected void updateModelForAnyType(CodegenModel m, Schema schema) { @@ -2710,6 +2752,7 @@ public class DefaultCodegen implements CodegenConfig { } // process 'additionalProperties' setAddProps(schema, m); + addRequiredVarsMap(schema, m); } protected String toTestCaseName(String specTestCaseName) { @@ -2729,17 +2772,20 @@ public class DefaultCodegen implements CodegenConfig { /** * Processes any test cases if they exist in the components.x-test-examples vendor extensions * If they exist then cast them to java class instances and return them back in a map - * @param schemaName the component schema name that the test cases are for - * @param vendorExtensions the extensions that may or may not hold the data + * @param refToTestCases the component schema name that the test cases are for */ - private HashMap extractSchemaTestCases(String schemaName, HashMap vendorExtensions) { - String testExamplesKey = "x-schema-test-examples"; + private HashMap extractSchemaTestCases(String refToTestCases) { // schemaName to a map of test case name to test case - if (vendorExtensions == null || !vendorExtensions.containsKey(testExamplesKey)) { + HashMap vendorExtensions = (HashMap) openAPI.getComponents().getExtensions(); + if (vendorExtensions == null || !vendorExtensions.containsKey(xSchemaTestExamplesKey)) { return null; } + if (!refToTestCases.startsWith(xSchemaTestExamplesRefPrefix)) { + return null; + } + String schemaName = refToTestCases.substring(xSchemaTestExamplesRefPrefix.length()); HashMap schemaTestCases = new HashMap<>(); - LinkedHashMap schemaNameToTestCases = (LinkedHashMap) vendorExtensions.get(testExamplesKey); + LinkedHashMap schemaNameToTestCases = (LinkedHashMap) vendorExtensions.get(xSchemaTestExamplesKey); if (!schemaNameToTestCases.containsKey(schemaName)) { return null; @@ -2759,6 +2805,52 @@ public class DefaultCodegen implements CodegenConfig { return schemaTestCases; } + /** + * Sets the booleans that define the model's type + * + * @param model the model to update + * @param schema the model's schema + */ + protected void updateModelForString(CodegenModel model, Schema schema) { + // NOTE: String schemas as CodegenModel is a rare use case and may be removed at a later date. + if (ModelUtils.isDateTimeSchema(schema)) { + // NOTE: DateTime schemas as CodegenModel is a rare use case and may be removed at a later date. + model.setIsString(false); // for backward compatibility with 2.x + model.isDateTime = Boolean.TRUE; + } else if (ModelUtils.isDateSchema(schema)) { + // NOTE: Date schemas as CodegenModel is a rare use case and may be removed at a later date. + model.setIsString(false); // for backward compatibility with 2.x + model.isDate = Boolean.TRUE; + } else if (ModelUtils.isUUIDSchema(schema)) { + // NOTE: UUID schemas as CodegenModel is a rare use case and may be removed at a later date. + model.setIsString(false); + model.setIsUuid(true); + } + } + + protected void updateModelForNumber(CodegenModel model, Schema schema) { + // NOTE: Number schemas as CodegenModel is a rare use case and may be removed at a later date. + model.isNumeric = Boolean.TRUE; + if (ModelUtils.isFloatSchema(schema)) { // float + model.isFloat = Boolean.TRUE; + } else if (ModelUtils.isDoubleSchema(schema)) { // double + model.isDouble = Boolean.TRUE; + } + } + + protected void updateModelForInteger(CodegenModel model, Schema schema) { + // NOTE: Integral schemas as CodegenModel is a rare use case and may be removed at a later date. + model.isNumeric = Boolean.TRUE; + if (ModelUtils.isLongSchema(schema)) { // int64/long format + model.isLong = Boolean.TRUE; + } else { + model.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int + if (ModelUtils.isShortSchema(schema)) { // int32 + model.setIsShort(Boolean.TRUE); + } + } + } + /** * Convert OAS Model object to Codegen Model object. * @@ -2774,6 +2866,12 @@ public class DefaultCodegen implements CodegenConfig { typeAliases = getAllAliases(allDefinitions); } + CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + if (schema.equals(trueSchema)) { + m.setIsBooleanSchemaTrue(true); + } else if (schema.equals(falseSchema)) { + m.setIsBooleanSchemaFalse(true); + } // unalias schema schema = unaliasSchema(schema); if (schema == null) { @@ -2781,11 +2879,9 @@ public class DefaultCodegen implements CodegenConfig { return null; } - CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL); ModelUtils.syncValidationProperties(schema, m); if (openAPI != null) { - HashMap vendorExtensions = (HashMap) openAPI.getComponents().getExtensions(); - HashMap schemaTestCases = extractSchemaTestCases(name, vendorExtensions); + HashMap schemaTestCases = extractSchemaTestCases(xSchemaTestExamplesRefPrefix + name); m.testCases = schemaTestCases; } @@ -2836,6 +2932,7 @@ public class DefaultCodegen implements CodegenConfig { } m.setTypeProperties(schema); + m.setFormat(schema.getFormat()); m.setComposedSchemas(getComposedSchemas(schema)); if (ModelUtils.isArraySchema(schema)) { CodegenProperty arrayProperty = fromProperty(name, schema, false); @@ -2843,39 +2940,11 @@ public class DefaultCodegen implements CodegenConfig { m.arrayModelType = arrayProperty.complexType; addParentContainer(m, name, schema); } else if (ModelUtils.isIntegerSchema(schema)) { // integer type - // NOTE: Integral schemas as CodegenModel is a rare use case and may be removed at a later date. - m.isNumeric = Boolean.TRUE; - if (ModelUtils.isLongSchema(schema)) { // int64/long format - m.isLong = Boolean.TRUE; - } else { - m.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int - if (ModelUtils.isShortSchema(schema)) { // int32 - m.setIsShort(Boolean.TRUE); - } - } + updateModelForInteger(m, schema); } else if (ModelUtils.isStringSchema(schema)) { - // NOTE: String schemas as CodegenModel is a rare use case and may be removed at a later date. - if (ModelUtils.isDateTimeSchema(schema)) { - // NOTE: DateTime schemas as CodegenModel is a rare use case and may be removed at a later date. - m.setIsString(false); // for backward compatibility with 2.x - m.isDateTime = Boolean.TRUE; - } else if (ModelUtils.isDateSchema(schema)) { - // NOTE: Date schemas as CodegenModel is a rare use case and may be removed at a later date. - m.setIsString(false); // for backward compatibility with 2.x - m.isDate = Boolean.TRUE; - } else if (ModelUtils.isUUIDSchema(schema)) { - // NOTE: UUID schemas as CodegenModel is a rare use case and may be removed at a later date. - m.setIsString(false); - m.setIsUuid(true); - } + updateModelForString(m, schema); } else if (ModelUtils.isNumberSchema(schema)) { - // NOTE: Number schemas as CodegenModel is a rare use case and may be removed at a later date. - m.isNumeric = Boolean.TRUE; - if (ModelUtils.isFloatSchema(schema)) { // float - m.isFloat = Boolean.TRUE; - } else if (ModelUtils.isDoubleSchema(schema)) { // double - m.isDouble = Boolean.TRUE; - } + updateModelForNumber(m, schema); } else if (ModelUtils.isAnyType(schema)) { updateModelForAnyType(m, schema); } else if (ModelUtils.isTypeObjectSchema(schema)) { @@ -2886,6 +2955,9 @@ public class DefaultCodegen implements CodegenConfig { // schema by unaliasSchema and one of the above code paths will be taken ; } + if (schema.get$ref() != null) { + m.setRef(schema.get$ref()); + } if (schema instanceof ComposedSchema) { updateModelForComposedSchema(m, schema, allDefinitions); @@ -2940,6 +3012,9 @@ public class DefaultCodegen implements CodegenConfig { } } + if (addSchemaImportsFromV3SpecLocations) { + addImports(m.imports, m.getImports(importContainerType, importBaseType, generatorMetadata.getFeatureSet())); + } return m; } @@ -3309,8 +3384,19 @@ public class DefaultCodegen implements CodegenConfig { discriminator.setPropertyName(toVarName(discPropName)); discriminator.setPropertyBaseName(sourceDiscriminator.getPropertyName()); discriminator.setPropertyGetter(toGetter(discriminator.getPropertyName())); + // FIXME: for now, we assume that the discriminator property is String discriminator.setPropertyType(typeMapping.get("string")); + + // check to see if the discriminator property is an enum string + if (schema.getProperties() != null && + schema.getProperties().get(discPropName) instanceof StringSchema) { + StringSchema s = (StringSchema) schema.getProperties().get(discPropName); + if (s.getEnum() != null && !s.getEnum().isEmpty()) { // it's an enum string + discriminator.setIsEnum(true); + } + } + discriminator.setMapping(sourceDiscriminator.getMapping()); List uniqueDescendants = new ArrayList<>(); if (sourceDiscriminator.getMapping() != null && !sourceDiscriminator.getMapping().isEmpty()) { @@ -3486,7 +3572,10 @@ public class DefaultCodegen implements CodegenConfig { if (Boolean.FALSE.equals(p.getNullable())) { LOGGER.warn("Schema '{}' is any type, which includes the 'null' value. 'nullable' cannot be set to 'false'", p.getName()); } - property.isNullable = true; + ComposedSchema composedSchema = p instanceof ComposedSchema + ? (ComposedSchema) p + : null; + property.isNullable = property.isNullable || composedSchema == null || composedSchema.getAllOf() == null || composedSchema.getAllOf().size() == 0; if (languageSpecificPrimitives.contains(property.dataType)) { property.isPrimitiveType = true; } @@ -3525,6 +3614,42 @@ public class DefaultCodegen implements CodegenConfig { property.pattern = toRegularExpression(p.getPattern()); } + protected void updatePropertyForNumber(CodegenProperty property, Schema p) { + property.isNumeric = Boolean.TRUE; + if (ModelUtils.isFloatSchema(p)) { // float + property.isFloat = Boolean.TRUE; + } else if (ModelUtils.isDoubleSchema(p)) { // double + property.isDouble = Boolean.TRUE; + } + } + + protected void updatePropertyForInteger(CodegenProperty property, Schema p) { + property.isNumeric = Boolean.TRUE; + if (ModelUtils.isLongSchema(p)) { // int64/long format + property.isLong = Boolean.TRUE; + } else { + property.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int + if (ModelUtils.isShortSchema(p)) { // int32 + property.setIsShort(Boolean.TRUE); + } + } + } + + /** + * TODO remove this in 7.0.0 as a breaking change + * This method was kept when required was added to the fromProperty signature + * to ensure that the change was non-breaking + * + * @param name name of the property + * @param p OAS property schema + * @param required true if the property is required in the next higher object schema, false otherwise + * @return Codegen Property object + */ + public CodegenProperty fromProperty(String name, Schema p, boolean required) { + return fromProperty(name, p, required, false); + } + + /** * TODO remove this in 7.0.0 as a breaking change * This method was kept when required was added to the fromProperty signature @@ -3535,7 +3660,7 @@ public class DefaultCodegen implements CodegenConfig { * @return Codegen Property object */ public CodegenProperty fromProperty(String name, Schema p) { - return fromProperty(name, p, false); + return fromProperty(name, p, false, false); } /** @@ -3550,26 +3675,38 @@ public class DefaultCodegen implements CodegenConfig { * @param name name of the property * @param p OAS property schema * @param required true if the property is required in the next higher object schema, false otherwise + * @param schemaIsFromAdditionalProperties true if the property is a required property defined by additional properties schema + * If this is the actual additionalProperties schema not defining a required property, then + * the value should be false * @return Codegen Property object */ - public CodegenProperty fromProperty(String name, Schema p, boolean required) { + public CodegenProperty fromProperty(String name, Schema p, boolean required, boolean schemaIsFromAdditionalProperties) { if (p == null) { LOGGER.error("Undefined property/schema for `{}`. Default to type:string.", name); return null; } LOGGER.debug("debugging fromProperty for {} : {}", name, p); - NamedSchema ns = new NamedSchema(name, p, required); + NamedSchema ns = new NamedSchema(name, p, required, schemaIsFromAdditionalProperties); CodegenProperty cpc = schemaCodegenPropertyCache.get(ns); if (cpc != null) { LOGGER.debug("Cached fromProperty for {} : {} required={}", name, p.getName(), required); return cpc; } + + CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); + if (p.equals(trueSchema)) { + property.setIsBooleanSchemaTrue(true); + } else if (p.equals(falseSchema)) { + property.setIsBooleanSchemaFalse(true); + } + // unalias schema p = unaliasSchema(p); - CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); + property.setSchemaIsFromAdditionalProperties(schemaIsFromAdditionalProperties); property.required = required; ModelUtils.syncValidationProperties(p, property); + property.setFormat(p.getFormat()); property.name = toVarName(name); property.baseName = name; @@ -3646,6 +3783,7 @@ public class DefaultCodegen implements CodegenConfig { property._enum.add(String.valueOf(i)); } property.isEnum = true; + property.isInnerEnum = true; Map allowableValues = new HashMap<>(); allowableValues.put("values", _enum); @@ -3686,15 +3824,7 @@ public class DefaultCodegen implements CodegenConfig { property.setTypeProperties(p); property.setComposedSchemas(getComposedSchemas(p)); if (ModelUtils.isIntegerSchema(p)) { // integer type - property.isNumeric = Boolean.TRUE; - if (ModelUtils.isLongSchema(p)) { // int64/long format - property.isLong = Boolean.TRUE; - } else { - property.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int - if (ModelUtils.isShortSchema(p)) { // int32 - property.setIsShort(Boolean.TRUE); - } - } + updatePropertyForInteger(property, p); } else if (ModelUtils.isBooleanSchema(p)) { // boolean type property.getter = toBooleanGetter(name); } else if (ModelUtils.isFileSchema(p) && !ModelUtils.isStringSchema(p)) { @@ -3703,12 +3833,7 @@ public class DefaultCodegen implements CodegenConfig { } else if (ModelUtils.isStringSchema(p)) { updatePropertyForString(property, p); } else if (ModelUtils.isNumberSchema(p)) { - property.isNumeric = Boolean.TRUE; - if (ModelUtils.isFloatSchema(p)) { // float - property.isFloat = Boolean.TRUE; - } else if (ModelUtils.isDoubleSchema(p)) { // double - property.isDouble = Boolean.TRUE; - } + updatePropertyForNumber(property, p); } else if (ModelUtils.isArraySchema(p)) { // default to string if inner item is undefined property.isContainer = true; @@ -3745,6 +3870,9 @@ public class DefaultCodegen implements CodegenConfig { // referenced model ; } + if (p.get$ref() != null) { + property.setRef(p.get$ref()); + } boolean isAnyTypeWithNothingElseSet = (ModelUtils.isAnyType(p) && (p.getProperties() == null || p.getProperties().isEmpty()) && @@ -3791,6 +3919,7 @@ public class DefaultCodegen implements CodegenConfig { // isEnum is set to true when the type is an enum // or the inner type of an array/map is an enum property.isEnum = true; + property.isInnerEnum = true; // update datatypeWithEnum and default value for array // e.g. List => List updateDataTypeWithEnumForArray(property); @@ -3827,6 +3956,7 @@ public class DefaultCodegen implements CodegenConfig { // isEnum is set to true when the type is an enum // or the inner type of an array/map is an enum property.isEnum = true; + property.isInnerEnum = true; // update datatypeWithEnum and default value for map // e.g. Dictionary => Dictionary updateDataTypeWithEnumForMap(property); @@ -4144,14 +4274,16 @@ public class DefaultCodegen implements CodegenConfig { String mediaTypeSchemaSuffix = String.format(Locale.ROOT, "%sResponseBody", r.code); r.setContent(getContent(response.getContent(), imports, mediaTypeSchemaSuffix)); - if (r.baseType != null && - !defaultIncludes.contains(r.baseType) && - !languageSpecificPrimitives.contains(r.baseType)) { - imports.add(r.baseType); - } - if ("set".equals(r.containerType) && typeMapping.containsKey(r.containerType)) { - op.uniqueItems = true; - imports.add(typeMapping.get(r.containerType)); + if (!addSchemaImportsFromV3SpecLocations) { + if (r.baseType != null && + !defaultIncludes.contains(r.baseType) && + !languageSpecificPrimitives.contains(r.baseType)) { + imports.add(r.baseType); + } + if ("set".equals(r.containerType) && typeMapping.containsKey(r.containerType)) { + op.uniqueItems = true; + imports.add(typeMapping.get(r.containerType)); + } } op.responses.add(r); @@ -4161,6 +4293,9 @@ public class DefaultCodegen implements CodegenConfig { if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.is2xx) && Boolean.FALSE.equals(op.isResponseFile)) { op.isResponseFile = Boolean.TRUE; } + if (Boolean.TRUE.equals(r.isDefault)) { + op.defaultReturnType = Boolean.TRUE; + } // check if any 4xx or 5xx response has an error response object defined if ((Boolean.TRUE.equals(r.is4xx) || Boolean.TRUE.equals(r.is5xx)) && @@ -4637,10 +4772,12 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.isContainer = true; codegenParameter.isMap = true; - // recursively add import - while (codegenProperty != null) { - imports.add(codegenProperty.baseType); - codegenProperty = codegenProperty.items; + if (!addSchemaImportsFromV3SpecLocations) { + // recursively add import + while (codegenProperty != null) { + imports.add(codegenProperty.baseType); + codegenProperty = codegenProperty.items; + } } } @@ -4725,6 +4862,9 @@ public class DefaultCodegen implements CodegenConfig { prop = fromProperty(parameter.getName(), parameterSchema, false); } codegenParameter.setSchema(prop); + if (addSchemaImportsFromV3SpecLocations) { + addImports(imports, prop.getImports(importContainerType, importBaseType, generatorMetadata.getFeatureSet())); + } } else if (parameter.getContent() != null) { Content content = parameter.getContent(); if (content.size() > 1) { @@ -4758,7 +4898,7 @@ public class DefaultCodegen implements CodegenConfig { return codegenParameter; } - // TODO need to reivew replacing empty map with schemaMapping instead + // TODO need to review replacing empty map with schemaMapping instead parameterSchema = unaliasSchema(parameterSchema); if (parameterSchema == null) { LOGGER.warn("warning! Schema not found for parameter \" {} \"", parameter.getName()); @@ -4850,11 +4990,12 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.mostInnerItems = itemsProperty.mostInnerItems; codegenParameter.baseType = itemsProperty.dataType; codegenParameter.isContainer = true; - - // recursively add import - while (itemsProperty != null) { - imports.add(itemsProperty.baseType); - itemsProperty = itemsProperty.items; + if (!addSchemaImportsFromV3SpecLocations) { + // recursively add import + while (itemsProperty != null) { + imports.add(itemsProperty.baseType); + itemsProperty = itemsProperty.items; + } } } else { // referenced schemas @@ -4874,25 +5015,30 @@ public class DefaultCodegen implements CodegenConfig { } else { codegenParameter.dataType = codegenProperty.dataType; } - if (ModelUtils.isSet(parameterSchema)) { - imports.add(codegenProperty.baseType); + if (!addSchemaImportsFromV3SpecLocations) { + if (ModelUtils.isSet(parameterSchema)) { + imports.add(codegenProperty.baseType); + } } codegenParameter.dataFormat = codegenProperty.dataFormat; if (parameter.getRequired() != null) { codegenParameter.required = parameter.getRequired().booleanValue(); } - if (codegenProperty.isEnum) { - codegenParameter.datatypeWithEnum = codegenProperty.datatypeWithEnum; - codegenParameter.enumName = codegenProperty.enumName; - } - // enum updateCodegenPropertyEnum(codegenProperty); codegenParameter.isEnum = codegenProperty.isEnum; codegenParameter._enum = codegenProperty._enum; codegenParameter.allowableValues = codegenProperty.allowableValues; + if (codegenProperty.isEnum) { + codegenParameter.datatypeWithEnum = codegenProperty.datatypeWithEnum; + codegenParameter.enumName = codegenProperty.enumName; + if (codegenProperty.defaultValue != null) { + codegenParameter.enumDefaultValue = codegenProperty.defaultValue.replace(codegenProperty.enumName + ".", ""); + } + } + if (codegenProperty.items != null && codegenProperty.items.isEnum) { codegenParameter.datatypeWithEnum = codegenProperty.datatypeWithEnum; codegenParameter.enumName = codegenProperty.enumName; @@ -4905,10 +5051,11 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.isCollectionFormatMulti = true; } codegenParameter.paramName = toParamName(parameter.getName()); - - // import - if (codegenProperty.complexType != null) { - imports.add(codegenProperty.complexType); + if (!addSchemaImportsFromV3SpecLocations) { + // import + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } } codegenParameter.pattern = toRegularExpression(parameterSchema.getPattern()); @@ -5279,15 +5426,17 @@ public class DefaultCodegen implements CodegenConfig { final CodegenProperty property = fromProperty(name, schema, false); addImport(model, property.complexType); model.parent = toInstantiationType(schema); - final String containerType = property.containerType; - final String instantiationType = instantiationTypes.get(containerType); - if (instantiationType != null) { - addImport(model, instantiationType); - } + if (!addSchemaImportsFromV3SpecLocations) { + final String containerType = property.containerType; + final String instantiationType = instantiationTypes.get(containerType); + if (instantiationType != null) { + addImport(model, instantiationType); + } - final String mappedType = typeMapping.get(containerType); - if (mappedType != null) { - addImport(model, mappedType); + final String mappedType = typeMapping.get(containerType); + if (mappedType != null) { + addImport(model, mappedType); + } } } @@ -5318,7 +5467,7 @@ public class DefaultCodegen implements CodegenConfig { } protected void addImports(Set importsToBeAddedTo, IJsonSchemaValidationProperties type) { - addImports(importsToBeAddedTo, type.getImports(true)); + addImports(importsToBeAddedTo, type.getImports(importContainerType, importBaseType, generatorMetadata.getFeatureSet())); } protected void addImports(Set importsToBeAddedTo, Set importsToAdd) { @@ -5395,7 +5544,7 @@ public class DefaultCodegen implements CodegenConfig { if (allProperties != null) { Set allMandatory = allRequired == null ? Collections.emptySet() : new TreeSet<>(allRequired); - // update "vars" with parent's properties (all, required) + // update "allVars" with parent's properties (all, required) addVars(m, m.allVars, allProperties, allMandatory); m.allMandatory = allMandatory; } else { // without parent, allVars and vars are the same @@ -5431,18 +5580,40 @@ public class DefaultCodegen implements CodegenConfig { if (properties == null) { return; } + + HashMap varsMap = new HashMap<>(); CodegenModel cm = null; if (m instanceof CodegenModel) { cm = (CodegenModel) m; - } - for (Map.Entry entry : properties.entrySet()) { + if (cm.allVars == vars) { // processing allVars + for (CodegenProperty var : cm.vars) { + // create a map of codegen properties for lookup later + varsMap.put(var.baseName, var); + } + } + } + + for (Map.Entry entry : properties.entrySet()) { final String key = entry.getKey(); final Schema prop = entry.getValue(); if (prop == null) { LOGGER.warn("Please report the issue. There shouldn't be null property for {}", key); } else { - final CodegenProperty cp = fromProperty(key, prop, mandatory.contains(key)); + final CodegenProperty cp; + + if (cm != null && cm.allVars == vars && varsMap.keySet().contains(key)) { + // when updating allVars, reuse the codegen property from the child model if it's already present + // the goal is to avoid issues when the property is defined in both child, parent but the + // definition is not identical, e.g. required vs optional, integer vs string + LOGGER.debug("The property `{}` already defined in the child model. Using the one from child.", + key); + cp = varsMap.get(key); + } else { + // properties in the parent model only + cp = fromProperty(key, prop, mandatory.contains(key)); + } + vars.add(cp); m.setHasVars(true); @@ -5465,8 +5636,9 @@ public class DefaultCodegen implements CodegenConfig { if (!Boolean.TRUE.equals(cp.isReadOnly)) { cm.hasOnlyReadOnly = false; } - - addImportsForPropertyType(cm, cp); + if (!addSchemaImportsFromV3SpecLocations) { + addImportsForPropertyType(cm, cp); + } // if required, add to the list "requiredVars" if (Boolean.FALSE.equals(cp.required)) { @@ -5499,7 +5671,7 @@ public class DefaultCodegen implements CodegenConfig { */ protected void addImportsForPropertyType(CodegenModel model, CodegenProperty property) { if (property.isArray) { - if (property.getUniqueItems()) { // set + if (Boolean.TRUE.equals(property.getUniqueItemsBoolean())) { // set addImport(model.imports, typeMapping.get("set")); } else { // array addImport(model.imports, typeMapping.get("array")); @@ -5853,7 +6025,7 @@ public class DefaultCodegen implements CodegenConfig { for (String lib : supportedLibraries.keySet()) { sb.append("\n").append(lib).append(" - ").append(supportedLibraries.get(lib)); } - return new CliOption("library", sb.toString()); + return new CliOption(CodegenConstants.LIBRARY, sb.toString()); } /** @@ -6604,10 +6776,12 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.collectionFormat = StringUtils.isEmpty(collectionFormat) ? "csv" : collectionFormat; codegenParameter.isCollectionFormatMulti = "multi".equals(collectionFormat); - // recursively add import - while (arrayInnerProperty != null) { - imports.add(arrayInnerProperty.baseType); - arrayInnerProperty = arrayInnerProperty.items; + if (!addSchemaImportsFromV3SpecLocations) { + // recursively add import + while (arrayInnerProperty != null) { + imports.add(arrayInnerProperty.baseType); + arrayInnerProperty = arrayInnerProperty.items; + } } } else { // referenced schemas @@ -6633,13 +6807,17 @@ public class DefaultCodegen implements CodegenConfig { if (codegenProperty.isEnum) { codegenParameter.datatypeWithEnum = codegenProperty.datatypeWithEnum; codegenParameter.enumName = codegenProperty.enumName; + if (codegenProperty.defaultValue != null) { + codegenParameter.enumDefaultValue = codegenProperty.defaultValue.replace(codegenProperty.enumName + ".", ""); + } } - // import - if (codegenProperty.complexType != null) { - imports.add(codegenProperty.complexType); + if (!addSchemaImportsFromV3SpecLocations) { + // import + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } } - setParameterExampleValue(codegenParameter); // set nullable setParameterNullable(codegenParameter, codegenProperty); @@ -6668,13 +6846,18 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.dataType = getTypeDeclaration(codegenModel.classname); codegenParameter.description = codegenModel.description; codegenParameter.isNullable = codegenModel.isNullable; - imports.add(codegenParameter.baseType); + if (!addSchemaImportsFromV3SpecLocations) { + imports.add(codegenParameter.baseType); + } } else { CodegenProperty codegenProperty = fromProperty("property", schema, false); if (codegenProperty != null && codegenProperty.getComplexType() != null && codegenProperty.getComplexType().contains(" | ")) { - List parts = Arrays.asList(codegenProperty.getComplexType().split(" \\| ")); - imports.addAll(parts); + if (!addSchemaImportsFromV3SpecLocations) { + // TODO move this splitting logic to the generator that needs it only + List parts = Arrays.asList(codegenProperty.getComplexType().split(" \\| ")); + imports.addAll(parts); + } String codegenModelName = codegenProperty.getComplexType(); codegenParameter.baseName = codegenModelName; codegenParameter.paramName = toParamName(codegenParameter.baseName); @@ -6712,10 +6895,12 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.baseType = codegenModelName; codegenParameter.dataType = getTypeDeclaration(codegenModelName); codegenParameter.description = codegenModelDescription; - imports.add(codegenParameter.baseType); + if (!addSchemaImportsFromV3SpecLocations) { + imports.add(codegenParameter.baseType); - if (codegenProperty.complexType != null) { - imports.add(codegenProperty.complexType); + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } } } } @@ -6737,14 +6922,15 @@ public class DefaultCodegen implements CodegenConfig { } CodegenProperty codegenProperty = fromProperty("property", schema, false); - imports.add(codegenProperty.baseType); - - CodegenProperty innerCp = codegenProperty; - while (innerCp != null) { - if (innerCp.complexType != null) { - imports.add(innerCp.complexType); + if (!addSchemaImportsFromV3SpecLocations) { + imports.add(codegenProperty.baseType); + CodegenProperty innerCp = codegenProperty; + while (innerCp != null) { + if (innerCp.complexType != null) { + imports.add(innerCp.complexType); + } + innerCp = innerCp.items; } - innerCp = innerCp.items; } if (StringUtils.isEmpty(bodyParameterName)) { @@ -6782,10 +6968,11 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.pattern = codegenProperty.pattern; codegenParameter.isNullable = codegenProperty.isNullable; - if (codegenProperty.complexType != null) { - imports.add(codegenProperty.complexType); + if (!addSchemaImportsFromV3SpecLocations) { + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } } - } // set nullable setParameterNullable(codegenParameter, codegenProperty); @@ -6831,19 +7018,31 @@ public class DefaultCodegen implements CodegenConfig { final ArraySchema arraySchema = (ArraySchema) schema; Schema inner = getSchemaItems(arraySchema); CodegenProperty codegenProperty = fromProperty("property", arraySchema, false); - imports.add(codegenProperty.baseType); + if (codegenProperty == null) { + throw new RuntimeException("CodegenProperty cannot be null. arraySchema for debugging: " + arraySchema); + } + + if (!addSchemaImportsFromV3SpecLocations) { + imports.add(codegenProperty.baseType); + } CodegenProperty innerCp = codegenProperty; CodegenProperty mostInnerItem = innerCp; // loop through multidimensional array to add proper import // also find the most inner item while (innerCp != null) { - if (innerCp.complexType != null) { - imports.add(innerCp.complexType); + if (!addSchemaImportsFromV3SpecLocations) { + if (innerCp.complexType != null) { + imports.add(innerCp.complexType); + } } mostInnerItem = innerCp; innerCp = innerCp.items; } + if (mostInnerItem == null) { + throw new RuntimeException("mostInnerItem (codegen property of array item) cannot be null. " + arraySchema); + } + if (StringUtils.isEmpty(bodyParameterName)) { if (StringUtils.isEmpty(mostInnerItem.complexType)) { codegenParameter.baseName = "request_body"; @@ -6864,9 +7063,11 @@ public class DefaultCodegen implements CodegenConfig { // set nullable setParameterNullable(codegenParameter, codegenProperty); - while (codegenProperty != null) { - imports.add(codegenProperty.baseType); - codegenProperty = codegenProperty.items; + if (!addSchemaImportsFromV3SpecLocations) { + while (codegenProperty != null) { + imports.add(codegenProperty.baseType); + codegenProperty = codegenProperty.items; + } } } } @@ -6966,10 +7167,27 @@ public class DefaultCodegen implements CodegenConfig { if (mt.getSchema() != null) { schemaProp = fromProperty(toMediaTypeSchemaName(contentType, mediaTypeSchemaSuffix), mt.getSchema(), false); } - CodegenMediaType codegenMt = new CodegenMediaType(schemaProp, ceMap); + HashMap schemaTestCases = null; + if (mt.getExtensions() != null && mt.getExtensions().containsKey(xSchemaTestExamplesKey)) { + Object objNodeWithRef = mt.getExtensions().get(xSchemaTestExamplesKey); + if (objNodeWithRef instanceof LinkedHashMap) { + LinkedHashMap nodeWithRef = (LinkedHashMap) objNodeWithRef; + String refKey = "$ref"; + String refToTestCases = nodeWithRef.getOrDefault(refKey, null); + if (refToTestCases != null) { + schemaTestCases = extractSchemaTestCases(refToTestCases); + } + } + } + + CodegenMediaType codegenMt = new CodegenMediaType(schemaProp, ceMap, schemaTestCases); cmtContent.put(contentType, codegenMt); if (schemaProp != null) { - addImports(imports, schemaProp.getImports(false)); + if (addSchemaImportsFromV3SpecLocations) { + addImports(imports, schemaProp.getImports(importContainerType, importBaseType, generatorMetadata.getFeatureSet())); + } else { + addImports(imports, schemaProp.getImports(false, importBaseType, generatorMetadata.getFeatureSet())); + } } } return cmtContent; @@ -7060,6 +7278,7 @@ public class DefaultCodegen implements CodegenConfig { updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); } + addJsonSchemaForBodyRequestInCaseItsNotPresent(codegenParameter, body); // set the parameter's example value @@ -7069,11 +7288,70 @@ public class DefaultCodegen implements CodegenConfig { return codegenParameter; } + protected void addRequiredVarsMap(Schema schema, IJsonSchemaValidationProperties property) { + /* + this should be called after vars and additionalProperties are set + Features added by storing codegenProperty values: + - complexType stores reference to additionalProperties definition + - baseName stores original name (can be invalid in a programming language) + - nameInSnakeCase can store valid name for a programming language + */ + Map properties = schema.getProperties(); + Map requiredVarsMap = new HashMap<>(); + List requiredPropertyNames = schema.getRequired(); + if (requiredPropertyNames == null) { + return; + } + for (String requiredPropertyName: requiredPropertyNames) { + // required property is defined in properties, value is that CodegenProperty + String usedRequiredPropertyName = handleSpecialCharacters(requiredPropertyName); + if (properties != null && properties.containsKey(requiredPropertyName)) { + // get cp from property + boolean found = false; + for (CodegenProperty cp: property.getVars()) { + if (cp.baseName.equals(requiredPropertyName)) { + found = true; + requiredVarsMap.put(requiredPropertyName, cp); + break; + } + } + if (found == false) { + throw new RuntimeException("Property " + requiredPropertyName + " is missing from getVars"); + } + } else if (schema.getAdditionalProperties() instanceof Boolean && Boolean.FALSE.equals(schema.getAdditionalProperties())) { + // TODO add processing for requiredPropertyName + // required property is not defined in properties, and additionalProperties is false, value is null + requiredVarsMap.put(usedRequiredPropertyName, null); + } else { + // required property is not defined in properties, and additionalProperties is true or unset value is CodegenProperty made from empty schema + // required property is not defined in properties, and additionalProperties is schema, value is CodegenProperty made from schema + if (supportsAdditionalPropertiesWithComposedSchema && !disallowAdditionalPropertiesIfNotPresent) { + CodegenProperty cp; + if (schema.getAdditionalProperties() == null) { + // additionalProperties is null + cp = fromProperty(usedRequiredPropertyName, new Schema(), true, true); + } else if (schema.getAdditionalProperties() instanceof Boolean && Boolean.TRUE.equals(schema.getAdditionalProperties())) { + // additionalProperties is True + cp = fromProperty(requiredPropertyName, new Schema(), true, true); + } else { + // additionalProperties is schema + cp = fromProperty(requiredPropertyName, (Schema) schema.getAdditionalProperties(), true, true); + } + requiredVarsMap.put(usedRequiredPropertyName, cp); + } + } + } + if (!requiredVarsMap.isEmpty()) { + property.setRequiredVarsMap(requiredVarsMap); + } + } + protected void addVarsRequiredVarsAdditionalProps(Schema schema, IJsonSchemaValidationProperties property) { setAddProps(schema, property); Set mandatory = schema.getRequired() == null ? Collections.emptySet() : new TreeSet<>(schema.getRequired()); addVars(property, property.getVars(), schema.getProperties(), mandatory); + addRequiredVarsMap(schema, property); } private void addJsonSchemaForBodyRequestInCaseItsNotPresent(CodegenParameter codegenParameter, RequestBody body) { @@ -7580,16 +7858,16 @@ public class DefaultCodegen implements CodegenConfig { Schema notSchema = schema.getNot(); CodegenProperty notProperty = null; if (notSchema != null) { - notProperty = fromProperty("NotSchema", notSchema, false); + notProperty = fromProperty("not_schema", notSchema, false); } List allOf = new ArrayList<>(); List oneOf = new ArrayList<>(); List anyOf = new ArrayList<>(); if (schema instanceof ComposedSchema) { ComposedSchema cs = (ComposedSchema) schema; - allOf = getComposedProperties(cs.getAllOf(), "allOf"); - oneOf = getComposedProperties(cs.getOneOf(), "oneOf"); - anyOf = getComposedProperties(cs.getAnyOf(), "anyOf"); + allOf = getComposedProperties(cs.getAllOf(), "all_of"); + oneOf = getComposedProperties(cs.getOneOf(), "one_of"); + anyOf = getComposedProperties(cs.getAnyOf(), "any_of"); } return new CodegenComposedSchemas( allOf, @@ -7635,4 +7913,41 @@ public class DefaultCodegen implements CodegenConfig { @Override public boolean getUseInlineModelResolver() { return true; } + + /* + A function to convert yaml or json ingested strings like property names + And convert special characters like newline, tab, carriage return + Into strings that can be rendered in the language that the generator will output to + */ + protected String handleSpecialCharacters(String name) { return name; } + + /** + * Used to ensure that null or Schema is returned given an input Boolean/Schema/null + * This will be used in openapi 3.1.0 spec processing to ensure that Booleans become Schemas + * Because our generators only understand Schemas + * Note: use getIsBooleanSchemaTrue or getIsBooleanSchemaFalse on the IJsonSchemaValidationProperties + * if you need to be able to detect if the original schema's value was true or false + * + * @param schema the input Boolean or Schema data to convert to a Schema + * @return Schema the input data converted to a Schema if possible + */ + protected Schema getSchemaFromBooleanOrSchema(Object schema) { + if (schema instanceof Boolean) { + if (Boolean.TRUE.equals(schema)) { + return trueSchema; + } else if (Boolean.FALSE.equals(schema)) { + return falseSchema; + } + // null case + return null; + } else if (schema instanceof Schema) { + if (schema == null) { + return null; + } + return (Schema) schema; + } else if (schema == null) { + return null; + } + throw new IllegalArgumentException("Invalid schema type; type must be Boolean or Schema"); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java index 151e13596a..2da1e53f84 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java @@ -40,8 +40,8 @@ import org.openapitools.codegen.config.GlobalSettings; import org.openapitools.codegen.api.TemplatingEngineAdapter; import org.openapitools.codegen.api.TemplateFileType; import org.openapitools.codegen.ignore.CodegenIgnoreProcessor; +import org.openapitools.codegen.languages.PythonPriorClientCodegen; import org.openapitools.codegen.languages.PythonClientCodegen; -import org.openapitools.codegen.languages.PythonExperimentalClientCodegen; import org.openapitools.codegen.meta.GeneratorMetadata; import org.openapitools.codegen.meta.Stability; import org.openapitools.codegen.model.ApiInfoMap; @@ -254,6 +254,15 @@ public class DefaultGenerator implements Generator { } config.processOpts(); + + // resolve inline models + if (config.getUseInlineModelResolver()) { + InlineModelResolver inlineModelResolver = new InlineModelResolver(); + inlineModelResolver.setInlineSchemaNameMapping(config.inlineSchemaNameMapping()); + inlineModelResolver.setInlineSchemaNameDefaults(config.inlineSchemaNameDefault()); + inlineModelResolver.flatten(openAPI); + } + config.preprocessOpenAPI(openAPI); // set OpenAPI to make these available to all methods @@ -532,7 +541,7 @@ public class DefaultGenerator implements Generator { ModelMap modelTemplate = modelList.get(0); if (modelTemplate != null && modelTemplate.getModel() != null) { CodegenModel m = modelTemplate.getModel(); - if (m.isAlias && !((config instanceof PythonClientCodegen) || (config instanceof PythonExperimentalClientCodegen))) { + if (m.isAlias && !((config instanceof PythonPriorClientCodegen) || (config instanceof PythonClientCodegen))) { // alias to number, string, enum, etc, which should not be generated as model // for PythonClientCodegen, all aliases are generated as models continue; // Don't create user-defined classes for aliases @@ -889,14 +898,6 @@ public class DefaultGenerator implements Generator { } } - // resolve inline models - if (config.getUseInlineModelResolver()) { - InlineModelResolver inlineModelResolver = new InlineModelResolver(); - inlineModelResolver.setInlineSchemaNameMapping(config.inlineSchemaNameMapping()); - inlineModelResolver.setInlineSchemaNameDefaults(config.inlineSchemaNameDefault()); - inlineModelResolver.flatten(openAPI); - } - configureGeneratorProperties(); configureOpenAPIInfo(); @@ -1199,16 +1200,18 @@ public class DefaultGenerator implements Generator { objs.setClassname(config.toApiName(tag)); objs.setPathPrefix(config.toApiVarName(tag)); - // check for operationId uniqueness - Set opIds = new HashSet<>(); - int counter = 0; - for (CodegenOperation op : ops) { - String opId = op.nickname; - if (opIds.contains(opId)) { - counter++; - op.nickname += "_" + counter; + // check for nickname uniqueness + if (config.getAddSuffixToDuplicateOperationNicknames()) { + Set opIds = new HashSet<>(); + int counter = 0; + for (CodegenOperation op : ops) { + String opId = op.nickname; + if (opIds.contains(opId)) { + counter++; + op.nickname += "_" + counter; + } + opIds.add(opId); } - opIds.add(opId); } objs.setOperation(ops); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java index c3cf15fc36..d5e8f7faa1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java @@ -1,15 +1,28 @@ package org.openapitools.codegen; +import java.util.Arrays; import java.util.Collections; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.Stream; import io.swagger.v3.oas.models.media.Schema; +import org.openapitools.codegen.meta.FeatureSet; +import org.openapitools.codegen.meta.features.SchemaSupportFeature; import org.openapitools.codegen.utils.ModelUtils; public interface IJsonSchemaValidationProperties { + CodegenProperty getContains(); + + void setContains(CodegenProperty contains); + + LinkedHashMap> getDependentRequired(); + + void setDependentRequired(LinkedHashMap> dependentRequired); + String getPattern(); void setPattern(String pattern); @@ -46,10 +59,18 @@ public interface IJsonSchemaValidationProperties { void setMaxItems(Integer maxItems); + // TODO update this value to Boolean in 7.0.0 boolean getUniqueItems(); + // TODO update this value to Boolean in 7.0.0 void setUniqueItems(boolean uniqueItems); + // TODO remove in 7.0.0 + Boolean getUniqueItemsBoolean(); + + // TODO remove in 7.0.0 + void setUniqueItemsBoolean(Boolean uniqueItems); + Integer getMinProperties(); void setMinProperties(Integer minProperties); @@ -115,6 +136,17 @@ public interface IJsonSchemaValidationProperties { void setRequiredVars(List requiredVars); + Map getRequiredVarsMap(); + + // goes from required propertyName to its CodegenProperty + // Use Cases: + // 1. required property is defined in properties, value is that CodegenProperty + // 2. required property is not defined in properties, and additionalProperties is true or unset value is CodegenProperty made from empty schema + // 3. required property is not defined in properties, and additionalProperties is schema, value is CodegenProperty made from schema + // 4. required property is not defined in properties, and additionalProperties is false, value is null + void setRequiredVarsMap(Map requiredVarsMap); + + boolean getIsNull(); void setIsNull(boolean isNull); @@ -153,6 +185,10 @@ public interface IJsonSchemaValidationProperties { void setIsAnyType(boolean isAnyType); + String getRef(); + + void setRef(String ref); + CodegenComposedSchemas getComposedSchemas(); void setComposedSchemas(CodegenComposedSchemas composedSchemas); @@ -161,6 +197,24 @@ public interface IJsonSchemaValidationProperties { void setHasMultipleTypes(boolean hasMultipleTypes); + // for when the schema is just the boolean true in a spec + boolean getIsBooleanSchemaTrue(); + + void setIsBooleanSchemaTrue(boolean isBooleanSchemaTrue); + + // for when the schema is just the boolean false in a spec + boolean getIsBooleanSchemaFalse(); + + void setIsBooleanSchemaFalse(boolean isBooleanSchemaFalse); + + boolean getSchemaIsFromAdditionalProperties(); + + void setSchemaIsFromAdditionalProperties(boolean schemaIsFromAdditionalProperties); + + void setFormat(String format); + + String getFormat(); + /** * Syncs all the schema's type properties into the IJsonSchemaValidationProperties instance * for now this only supports types without format information @@ -245,32 +299,79 @@ public interface IJsonSchemaValidationProperties { /** * Recursively collect all necessary imports to include so that the type may be resolved. * - * @param includeContainerTypes whether or not to include the container types in the returned imports. + * @param importContainerType whether or not to include the container types in the returned imports. + * @param importBaseType whether or not to include the base types in the returned imports. + * @param featureSet the generator feature set, used to determine if composed schemas should be added * @return all of the imports */ - default Set getImports(boolean includeContainerTypes) { + default Set getImports(boolean importContainerType, boolean importBaseType, FeatureSet featureSet) { Set imports = new HashSet<>(); if (this.getComposedSchemas() != null) { - CodegenComposedSchemas composed = (CodegenComposedSchemas) this.getComposedSchemas(); - List allOfs = composed.getAllOf() == null ? Collections.emptyList() : composed.getAllOf(); - List oneOfs = composed.getOneOf() == null ? Collections.emptyList() : composed.getOneOf(); - Stream innerTypes = Stream.concat(allOfs.stream(), oneOfs.stream()); - innerTypes.flatMap(cp -> cp.getImports(includeContainerTypes).stream()).forEach(s -> imports.add(s)); - } else if (includeContainerTypes || !(this.getIsArray() || this.getIsMap())) { - // this is our base case, add imports for referenced schemas - // this can't be broken out as a separate if block because Typescript only generates union types as A | B - // and would need to handle this differently - imports.add(this.getComplexType()); - imports.add(this.getBaseType()); + CodegenComposedSchemas composed = this.getComposedSchemas(); + List allOfs = Collections.emptyList(); + List oneOfs = Collections.emptyList(); + List anyOfs = Collections.emptyList(); + List nots = Collections.emptyList(); + if (composed.getAllOf() != null && featureSet.getSchemaSupportFeatures().contains(SchemaSupportFeature.allOf)) { + allOfs = composed.getAllOf(); + } + if (composed.getOneOf() != null && featureSet.getSchemaSupportFeatures().contains(SchemaSupportFeature.oneOf)) { + oneOfs = composed.getOneOf(); + } + if (composed.getAnyOf() != null && featureSet.getSchemaSupportFeatures().contains(SchemaSupportFeature.anyOf)) { + anyOfs = composed.getAnyOf(); + } + if (composed.getNot() != null && featureSet.getSchemaSupportFeatures().contains(SchemaSupportFeature.not)) { + nots = Arrays.asList(composed.getNot()); + } + Stream innerTypes = Stream.of( + allOfs.stream(), anyOfs.stream(), oneOfs.stream(), nots.stream()) + .flatMap(i -> i); + innerTypes.flatMap(cp -> cp.getImports(importContainerType, importBaseType, featureSet).stream()).forEach(s -> imports.add(s)); } - if (this.getItems() !=null && this.getIsArray()) { - imports.addAll(this.getItems().getImports(includeContainerTypes)); + // items can exist for AnyType and type array + if (this.getItems() != null && this.getIsArray()) { + imports.addAll(this.getItems().getImports(importContainerType, importBaseType, featureSet)); } + // additionalProperties can exist for AnyType and type object if (this.getAdditionalProperties() != null) { - imports.addAll(this.getAdditionalProperties().getImports(includeContainerTypes)); + imports.addAll(this.getAdditionalProperties().getImports(importContainerType, importBaseType, featureSet)); } + // vars can exist for AnyType and type object if (this.getVars() != null && !this.getVars().isEmpty()) { - this.getVars().stream().flatMap(v -> v.getImports(includeContainerTypes).stream()).forEach(s -> imports.add(s)); + this.getVars().stream().flatMap(v -> v.getImports(importContainerType, importBaseType, featureSet).stream()).forEach(s -> imports.add(s)); + } + if (this.getIsArray() || this.getIsMap()) { + if (importContainerType) { + /* + use-case for this complexType block: + DefaultCodegenTest.objectQueryParamIdentifyAsObject + DefaultCodegenTest.mapParamImportInnerObject + */ + String complexType = this.getComplexType(); + if (complexType != null) { + imports.add(complexType); + } + /* + use-case: + Adding List/Map etc, Java uses this + */ + String baseType = this.getBaseType(); + if (importBaseType && baseType != null) { + imports.add(baseType); + } + } + } else { + // referenced or inline schemas + String complexType = this.getComplexType(); + if (complexType != null) { + imports.add(complexType); + } + String baseType = this.getBaseType(); + if (importBaseType && baseType != null) { + imports.add(baseType); + } + return imports; } return imports; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java index b839960d28..ef684023d3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java @@ -167,7 +167,7 @@ public class InlineModelResolver { * Return true if a model should be generated e.g. object with properties, * enum, oneOf, allOf, anyOf, etc. * - * @param schema target schema + * @param schema target schema * @param visitedSchemas Visited schemas */ private boolean isModelNeeded(Schema schema, Set visitedSchemas) { @@ -189,6 +189,17 @@ public class InlineModelResolver { if (schema instanceof ComposedSchema) { // allOf, anyOf, oneOf ComposedSchema m = (ComposedSchema) schema; + + if (m.getAllOf() != null && m.getAllOf().size() == 1 && m.getReadOnly() != null && m.getReadOnly()) { + // Check if this composed schema only contains an allOf and a readOnly. + ComposedSchema c = new ComposedSchema(); + c.setAllOf(m.getAllOf()); + c.setReadOnly(true); + if (m.equals(c)) { + return isModelNeeded(m.getAllOf().get(0), visitedSchemas); + } + } + if (m.getAllOf() != null && !m.getAllOf().isEmpty()) { // check to ensure at least of the allOf item is model for (Schema inner : m.getAllOf()) { @@ -429,6 +440,10 @@ public class InlineModelResolver { if (requestBody.get$ref() != null) { String ref = ModelUtils.getSimpleRef(requestBody.get$ref()); requestBody = openAPI.getComponents().getRequestBodies().get(ref); + + if (requestBody == null) { + return; + } } flattenContent(requestBody.getContent(), diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java index 960a6ae7f3..4281abea4f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java @@ -118,7 +118,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co ); mapTypes = new HashSet<>( - Arrays.asList("IDictionary") + Arrays.asList("IDictionary", "Dictionary") ); // NOTE: C# uses camel cased reserved words, while models are title cased. We don't want lowercase comparisons. @@ -292,7 +292,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co // {{sourceFolder}} if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); - + // TODO: Move to its own option when a parameter for 'testFolder' is added. setTestFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } else { @@ -428,6 +428,17 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); + if (property.isInnerEnum && property.items != null) { + // format maps of inner enums to include the classname eg: Dictionary + property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.datatypeWithEnum, model.classname + "." + property.items.datatypeWithEnum); + property.dataType = property.datatypeWithEnum; + } + if (property.isMap || property.isContainer) { + // maps of enums will be marked both isMap and isEnum, correct that now + property.isEnum = false; + property.isInnerEnum = false; + property.isString = false; + } } @Override @@ -459,9 +470,59 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co postProcessEnumRefs(processed); updateValueTypeProperty(processed); updateNullableTypeProperty(processed); + + for (Map.Entry entry : objs.entrySet()) { + CodegenModel model = ModelUtils.getModelByName(entry.getKey(), objs); + + // https://github.com/OpenAPITools/openapi-generator/issues/12324 + // TODO: why do these collections contain different instances? + // fixing allVars should suffice instead of patching every collection + for (CodegenProperty property : model.allVars){ + patchProperty(model, property); + } + for (CodegenProperty property : model.vars){ + patchProperty(model, property); + } + for (CodegenProperty property : model.readWriteVars){ + patchProperty(model, property); + } + for (CodegenProperty property : model.optionalVars){ + patchProperty(model, property); + } + for (CodegenProperty property : model.parentVars){ + patchProperty(model, property); + } + for (CodegenProperty property : model.requiredVars){ + patchProperty(model, property); + } + for (CodegenProperty property : model.readOnlyVars){ + patchProperty(model, property); + } + for (CodegenProperty property : model.nonNullableVars){ + patchProperty(model, property); + } + } return processed; } + private void patchProperty(CodegenModel model, CodegenProperty property){ + /** + * Hotfix for this issue + * https://github.com/OpenAPITools/openapi-generator/issues/12155 + */ + if (property.dataType.equals("List") && property.getComposedSchemas() != null && property.getComposedSchemas().getAllOf() != null){ + List composedSchemas = property.getComposedSchemas().getAllOf(); + if (composedSchemas.size() == 0) { + return; + } + CodegenProperty composedProperty = composedSchemas.stream().findFirst().get(); + property.dataType = composedProperty.dataType; + property.datatypeWithEnum = composedProperty.datatypeWithEnum; + property.isMap = composedProperty.isMap; + property.isContainer = composedProperty.isContainer; + } + } + @Override protected List> buildEnumVars(List values, String dataType) { List> enumVars = super.buildEnumVars(values, dataType); @@ -472,7 +533,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co if ("string?".equals(dataType)){ enumVars.forEach((enumVar) -> { enumVar.put("isString", true); - }); + }); } return enumVars; @@ -493,7 +554,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co for (Map.Entry entry : models.entrySet()) { CodegenModel model = ModelUtils.getModelByName(entry.getKey(), models); if (model.isEnum) { - enumRefs.put(entry.getKey(), model); + enumRefs.put(model.getClassname(), model); } } @@ -675,6 +736,15 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co var.vendorExtensions.put("x-csharp-value-type", true); } } + + // https://github.com/OpenAPITools/openapi-generator/issues/12324 + // we should not need to iterate both vars and allVars + // the collections dont have the same instance, so we have to do it again + for (CodegenProperty var : model.allVars) { + if (!var.isContainer && (nullableType.contains(var.dataType) || var.isEnum)) { + var.vendorExtensions.put("x-csharp-value-type", true); + } + } } } } @@ -712,7 +782,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co } } else { operation.returnContainer = operation.returnType; - operation.isMap = this.mapTypes.contains(typeMapping); + operation.isMap = this.mapTypes.stream().anyMatch(t -> typeMapping.startsWith(t)); } } @@ -980,7 +1050,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co } } else if (ModelUtils.isStringSchema(p)) { if (p.getDefault() != null) { - String _default = (String) p.getDefault(); + String _default = String.valueOf(p.getDefault()); if (p.getEnum() == null) { return "\"" + _default + "\""; } else { @@ -1172,7 +1242,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } - + public void setTestFolder(String testFolder) { this.testFolder = testFolder; } @@ -1428,8 +1498,8 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co public void postProcessParameter(CodegenParameter parameter) { super.postProcessParameter(parameter); - // ensure a method's parameters are marked as nullable when nullable or when nullReferences are enabled - // this is mostly needed for reference types used as a method's parameters + // TODO: instead of appending the ? + // use isNullable, OptionalParameterLambda, or RequiredParameterLambda if (!parameter.required && (nullReferenceTypesFlag || nullableType.contains(parameter.dataType))) { parameter.dataType = parameter.dataType.endsWith("?") ? parameter.dataType diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java index 7cbb943a98..d989776bd3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java @@ -160,6 +160,14 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg Boolean.toString(this.variableNameFirstCharacterUppercase)); } + @Override + @SuppressWarnings("static-method") + public String sanitizeName(String name) { + String sanitizedName = super.sanitizeName(name); + sanitizedName = sanitizedName.replaceAll("-", ""); + return sanitizedName; + } + @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection @@ -188,7 +196,9 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg || languageSpecificPrimitives.contains(type)) { return type; } else { - return sanitizeName(modelNamePrefix + Character.toUpperCase(type.charAt(0)) + type.substring(1)); + String sanitizedName = sanitizeName(modelNamePrefix + Character.toUpperCase(type.charAt(0)) + type.substring(1)); + sanitizedName = sanitizedName.replaceFirst("^([^_a-zA-Z])", reservedWordPrefix + "$1"); + return sanitizedName; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java index edbfb173c9..e024a49f14 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java @@ -330,6 +330,11 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege return apiName; } + @Override + public String toApiTestFilename(String name) { + return toApiFilename(name) + "_test"; + } + /** * Return the golang implementation type for the specified property. * @@ -625,13 +630,14 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege boolean addedOSImport = false; for (ModelMap m : objs.getModels()) { CodegenModel model = m.getModel(); - for (CodegenProperty param : model.vars) { - if (!addedTimeImport - && ("time.Time".equals(param.dataType) || ("[]time.Time".equals(param.dataType)))) { + for (CodegenProperty cp : model.vars) { + if (!addedTimeImport && ("time.Time".equals(cp.dataType) || + (cp.items != null && "time.Time".equals(cp.items.dataType)))) { imports.add(createMapping("import", "time")); addedTimeImport = true; } - if (!addedOSImport && "*os.File".equals(param.baseType)) { + if (!addedOSImport && ("*os.File".equals(cp.dataType) || + (cp.items != null && "*os.File".equals(cp.items.dataType)))) { imports.add(createMapping("import", "os")); addedOSImport = true; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java index 2556ed2edf..ea6fa237fb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java @@ -130,6 +130,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected boolean implicitHeaders = false; protected String implicitHeadersRegex = null; + private Map schemaKeyToModelNameCache = new HashMap<>(); + public AbstractJavaCodegen() { super(); @@ -830,6 +832,12 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code return schemaMapping.get(name); } + // memoization + String origName = name; + if (schemaKeyToModelNameCache.containsKey(origName)) { + return schemaKeyToModelNameCache.get(origName); + } + final String sanitizedName = sanitizeName(name); String nameWithPrefixSuffix = sanitizedName; @@ -850,6 +858,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { final String modelName = "Model" + camelizedName; + schemaKeyToModelNameCache.put(origName, modelName); LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", camelizedName, modelName); return modelName; } @@ -857,11 +866,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code // model name starts with number if (camelizedName.matches("^\\d.*")) { final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) + schemaKeyToModelNameCache.put(origName, modelName); LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } + schemaKeyToModelNameCache.put(origName, camelizedName); + return camelizedName; } @@ -958,7 +970,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code return null; } else if (ModelUtils.isURISchema(schema)) { if (schema.getDefault() != null) { - return "URI.create(\"" + escapeText((String) schema.getDefault()) + "\")"; + return "URI.create(\"" + escapeText(String.valueOf(schema.getDefault())) + "\")"; } return null; } else if (ModelUtils.isStringSchema(schema)) { @@ -980,8 +992,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } else { return null; } + } else if (schema.getDefault() instanceof UUID) { + return "UUID.fromString(\"" + String.valueOf(schema.getDefault()) + "\")"; } else { - _default = (String) schema.getDefault(); + _default = String.valueOf(schema.getDefault()); } if (schema.getEnum() == null) { @@ -1285,9 +1299,21 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code if ("BigDecimal".equals(codegenModel.dataType)) { codegenModel.imports.add("BigDecimal"); } + + // additional import for different cases + addAdditionalImports(codegenModel, codegenModel.oneOf); + addAdditionalImports(codegenModel, codegenModel.anyOf); return codegenModel; } + private void addAdditionalImports(CodegenModel model, Set dataTypeSet) { + for (String dataType : dataTypeSet) { + if (null != importMapping().get(dataType)) { + model.imports.add(dataType); + } + } + } + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { if (model.getIsClassnameSanitized() && additionalProperties.containsKey(JACKSON)) { @@ -1524,6 +1550,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code return getSymbolName(value).toUpperCase(Locale.ROOT); } + if (" ".equals(value)) { + return "SPACE"; + } + // number if ("Integer".equals(datatype) || "Long".equals(datatype) || "Float".equals(datatype) || "Double".equals(datatype) || "BigDecimal".equals(datatype)) { @@ -2121,4 +2151,24 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code extensions.add(VendorExtension.X_FIELD_EXTRA_ANNOTATION); return extensions; } + + public boolean isAddNullableImports(CodegenModel cm, boolean addImports, CodegenProperty var) { + if (this.openApiNullable) { + boolean isOptionalNullable = Boolean.FALSE.equals(var.required) && Boolean.TRUE.equals(var.isNullable); + // only add JsonNullable and related imports to optional and nullable values + addImports |= isOptionalNullable; + var.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable); + findByName(var.name, cm.readOnlyVars) + .ifPresent(p -> p.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable)); + } + return addImports; + } + public static void addImports(List> imports, CodegenModel cm, Map imports2Classnames) { + for (Map.Entry entry : imports2Classnames.entrySet()) { + cm.imports.add(entry.getKey()); + Map importsItem = new HashMap<>(); + importsItem.put("import", entry.getValue()); + imports.add(importsItem); + } + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java index 20517280da..bd3b2279d1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java @@ -35,6 +35,7 @@ import java.io.File; import java.io.IOException; import java.util.*; import java.util.function.Function; +import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -75,6 +76,8 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co // ref: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-hash-map/ protected Set propertyAdditionalKeywords = new HashSet<>(Arrays.asList("entries", "keys", "size", "values")); + private Map schemaKeyToModelNameCache = new HashMap<>(); + public AbstractKotlinCodegen() { super(); @@ -115,6 +118,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co "const", "constructor", "continue", + "contract", "crossinline", "data", "delegate", @@ -668,6 +672,11 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co */ @Override public String toModelName(final String name) { + // memoization + String origName = name; + if (schemaKeyToModelNameCache.containsKey(origName)) { + return schemaKeyToModelNameCache.get(origName); + } // Allow for explicitly configured kotlin.* and java.* types if (name.startsWith("kotlin.") || name.startsWith("java.")) { @@ -717,7 +726,8 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co return modelName; } - return titleCase(modifiedName); + schemaKeyToModelNameCache.put(origName, titleCase(modifiedName)); + return schemaKeyToModelNameCache.get(origName); } /** @@ -769,7 +779,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co } // Fallback, replace unknowns with underscore. - word = word.replaceAll("\\W+", "_"); + word = Pattern.compile("\\W+", Pattern.UNICODE_CHARACTER_CLASS).matcher(word).replaceAll("_"); if (word.matches("\\d.*")) { word = "_" + word; } @@ -991,6 +1001,20 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co } } + private String fixNumberValue(String number, Schema p) { + if (ModelUtils.isFloatSchema(p)) { + return number + "f"; + } else if (ModelUtils.isDoubleSchema(p)) { + if (number.contains(".")) { + return number; + } + return number + ".0"; + } else if (ModelUtils.isLongSchema(p)) { + return number + "L"; + } + return number; + } + @Override public String toDefaultValue(Schema schema) { Schema p = ModelUtils.getReferencedSchema(this.openAPI, schema); @@ -1004,11 +1028,11 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co // TODO } else if (ModelUtils.isNumberSchema(p)) { if (p.getDefault() != null) { - return p.getDefault().toString(); + return fixNumberValue(p.getDefault().toString(), p); } } else if (ModelUtils.isIntegerSchema(p)) { if (p.getDefault() != null) { - return p.getDefault().toString(); + return fixNumberValue(p.getDefault().toString(), p); } } else if (ModelUtils.isURISchema(p)) { if (p.getDefault() != null) { @@ -1018,6 +1042,9 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co if (p.getDefault() != null) { String arrInstantiationType = ModelUtils.isSet(p) ? "set" : "arrayList"; + if (!(p.getDefault() instanceof ArrayNode)) { + return null; + } ArrayNode _default = (ArrayNode) p.getDefault(); if (_default.isEmpty()) { return arrInstantiationType + "Of()"; @@ -1034,7 +1061,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co } } else if (ModelUtils.isStringSchema(p)) { if (p.getDefault() != null) { - String _default = (String) p.getDefault(); + String _default = String.valueOf(p.getDefault()); if (p.getEnum() == null) { return "\"" + escapeText(_default) + "\""; } else { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java index 8dcee6d2cb..98fd8f9221 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java @@ -60,6 +60,8 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg protected String abstractNamePrefix = "Abstract", abstractNameSuffix = ""; protected String traitNamePrefix = "", traitNameSuffix = "Trait"; + private Map schemaKeyToModelNameCache = new HashMap<>(); + public AbstractPhpCodegen() { super(); @@ -89,7 +91,6 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg "boolean", "int", "integer", - "double", "float", "string", "object", @@ -117,7 +118,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg typeMapping.put("number", "float"); typeMapping.put("float", "float"); typeMapping.put("decimal", "float"); - typeMapping.put("double", "double"); + typeMapping.put("double", "float"); typeMapping.put("string", "string"); typeMapping.put("byte", "int"); typeMapping.put("boolean", "bool"); @@ -244,21 +245,22 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg return packageName; } - public String toSrcPath(String packageName, String basePath) { - packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - if (basePath != null && basePath.length() > 0) { - basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separator; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + public String toSrcPath(final String packageName, final String basePath) { + String modifiedPackageName = packageName.replace(invokerPackage, ""); + String modifiedBasePath = basePath; + if (basePath != null && !basePath.isEmpty()) { + modifiedBasePath = basePath.replaceAll("[\\\\/]?$", "") + File.separator; } // Trim prefix file separators from package path String packagePath = StringUtils.removeStart( // Replace period, backslash, forward slash with file separator in package name - packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement("/")), + modifiedPackageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement("/")), File.separator ); // Trim trailing file separators from the overall path - return StringUtils.removeEnd(basePath + packagePath, File.separator); + return StringUtils.removeEnd(modifiedBasePath + packagePath, File.separator); } @Override @@ -463,6 +465,12 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg @Override public String toModelName(String name) { + // memoization + String origName = name; + if (schemaKeyToModelNameCache.containsKey(origName)) { + return schemaKeyToModelNameCache.get(origName); + } + name = toGenericName(name); // add prefix and/or suffix only if name does not start wth \ (e.g. \DateTime) @@ -478,7 +486,9 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg // camelize the model name // phone_number => PhoneNumber - return camelize(name); + String camelizedName = camelize(name); + schemaKeyToModelNameCache.put(origName, camelizedName); + return camelizedName; } @Override @@ -646,7 +656,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg @Override public String toEnumValue(String value, String datatype) { - if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + if ("int".equals(datatype) || "float".equals(datatype)) { return value; } else { return "\'" + escapeText(value) + "\'"; @@ -674,7 +684,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg } // number - if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + if ("int".equals(datatype) || "float".equals(datatype)) { String varName = name; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java index 080112520c..fa38462af8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java @@ -637,6 +637,8 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co String sanitizedName = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // remove dollar sign sanitizedName = sanitizedName.replaceAll("$", ""); + // remove whitespace + sanitizedName = sanitizedName.replaceAll("\\s+", ""); String nameWithPrefixSuffix = sanitizedName; if (!StringUtils.isEmpty(modelNamePrefix)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java index 77c3c6bead..5f0f932c8d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java @@ -16,6 +16,12 @@ package org.openapitools.codegen.languages; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; @@ -42,16 +48,23 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; +import java.io.IOException; import java.util.*; import static org.openapitools.codegen.utils.StringUtils.camelize; public abstract class AbstractPythonConnexionServerCodegen extends AbstractPythonCodegen implements CodegenConfig { + private static class PythonBooleanSerializer extends JsonSerializer { + @Override + public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeRawValue(value ? "True" : "False"); + } + } + private final Logger LOGGER = LoggerFactory.getLogger(AbstractPythonConnexionServerCodegen.class); public static final String CONTROLLER_PACKAGE = "controllerPackage"; public static final String DEFAULT_CONTROLLER = "defaultController"; - public static final String SUPPORT_PYTHON2 = "supportPython2"; public static final String FEATURE_CORS = "featureCORS"; // nose is a python testing framework, we use pytest if USE_NOSE is unset public static final String USE_NOSE = "useNose"; @@ -60,6 +73,10 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho public static final String MOVE_TESTS_UNDER_PYTHON_SRC_ROOT = "testsUsePythonSrcRoot"; static final String MEDIA_TYPE = "mediaType"; + // An object mapper that is used to convert an example string to + // a "python-compliant" example string (boolean as True/False). + final ObjectMapper MAPPER = new ObjectMapper(); + protected int serverPort = 8080; protected String controllerPackage; protected String defaultController; @@ -80,6 +97,10 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho modelPackage = "models"; testPackage = "test"; + SimpleModule simpleModule = new SimpleModule(); + simpleModule.addSerializer(Boolean.class, new PythonBooleanSerializer()); + MAPPER.registerModule(simpleModule); + // TODO may remove these later to default to the setting in abstract python base class instead languageSpecificPrimitives.add("List"); languageSpecificPrimitives.add("Dict"); @@ -130,8 +151,6 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho defaultValue("controllers")); cliOptions.add(new CliOption(DEFAULT_CONTROLLER, "default controller"). defaultValue("default_controller")); - cliOptions.add(new CliOption(SUPPORT_PYTHON2, "support python2. This option has been deprecated and will be removed in the 5.x release."). - defaultValue("false")); cliOptions.add(new CliOption("serverPort", "TCP port to listen to in app.run"). defaultValue("8080")); cliOptions.add(CliOption.newBoolean(FEATURE_CORS, "use flask-cors for handling CORS requests"). @@ -178,10 +197,6 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho this.defaultController = "default_controller"; additionalProperties.put(DEFAULT_CONTROLLER, this.defaultController); } - if (Boolean.TRUE.equals(additionalProperties.get(SUPPORT_PYTHON2))) { - additionalProperties.put(SUPPORT_PYTHON2, Boolean.TRUE); - typeMapping.put("long", "long"); - } if (additionalProperties.containsKey(FEATURE_CORS)) { setFeatureCORS(String.valueOf(additionalProperties.get(FEATURE_CORS))); } @@ -695,7 +710,16 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho if (operation.requestBodyExamples != null) { for (Map example : operation.requestBodyExamples) { if (example.get("contentType") != null && example.get("contentType").equals("application/json")) { - operation.bodyParam.example = example.get("example"); + // Make an example dictionary more python-like (Booleans True/False). + // If fails, use the original string. + try { + Map result = MAPPER.readValue(example.get("example"), + new TypeReference>() { + }); + operation.bodyParam.example = MAPPER.writeValueAsString(result); + } catch (IOException e) { + operation.bodyParam.example = example.get("example"); + } } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java index a57af7989a..3ecbc7d2f4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java @@ -161,7 +161,7 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code } else if (p.getDefault() instanceof java.time.OffsetDateTime) { return "Time.parse(\"" + String.format(Locale.ROOT, ((java.time.OffsetDateTime) p.getDefault()).atZoneSameInstant(ZoneId.systemDefault()).toString(), "") + "\")"; } else { - return "'" + escapeText((String) p.getDefault()) + "'"; + return "'" + escapeText((String.valueOf(p.getDefault()))) + "'"; } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRustCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRustCodegen.java new file mode 100644 index 0000000000..20cf80dcca --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRustCodegen.java @@ -0,0 +1,337 @@ +package org.openapitools.codegen.languages; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Strings; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.GeneratorLanguage; +import org.openapitools.codegen.utils.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; +import java.math.BigInteger; +import java.util.*; +import java.util.function.Function; + +import static org.openapitools.codegen.utils.StringUtils.*; + +public abstract class AbstractRustCodegen extends DefaultCodegen implements CodegenConfig { + + private final Logger LOGGER = LoggerFactory.getLogger(AbstractRustCodegen.class); + + protected List charactersToAllow = Collections.singletonList("_"); + protected Set keywordsThatDoNotSupportRawIdentifiers = new HashSet<>( + Arrays.asList("super", "self", "Self", "extern", "crate")); + protected String enumSuffix = ""; + + public AbstractRustCodegen() { + super(); + // All 'Strict' and 'Reserved' keywords from https://doc.rust-lang.org/reference/keywords.html + // Note: These are case-sensitive + this.reservedWords = new HashSet<>( + Arrays.asList( + "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", + "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", + "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", + "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final", "macro", + "override", "priv", "typeof", "unsized", "virtual", "yield", "try" + ) + ); + } + + @Override + public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.RUST; } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + @Override + public boolean isReservedWord(String word) { + // This is overridden to take account of Rust reserved words being case-sensitive. + return word != null && reservedWords.contains(word); + } + + /** + * Determine the best fitting Rust type for an integer property. This is intended for use when a specific format + * has not been defined in the specification. Where the minimum or maximum is not known then the returned type + * will default to having at least 32 bits. + * @param minimum The minimum value as set in the specification. + * @param exclusiveMinimum If the minimum value itself is excluded by the specification. + * @param maximum The maximum value as set in the specification. + * @param exclusiveMaximum If the maximum value itself is excluded by the specification. + * @param preferUnsigned Use unsigned types where the effective minimum is greater than or equal to zero. + * @return The Rust data type name. + */ + @VisibleForTesting + public String bestFittingIntegerType(@Nullable BigInteger minimum, + boolean exclusiveMinimum, + @Nullable BigInteger maximum, + boolean exclusiveMaximum, + boolean preferUnsigned) { + if (exclusiveMinimum) { + minimum = Optional.ofNullable(minimum).map(min -> min.add(BigInteger.ONE)).orElse(null); + } + if (exclusiveMaximum) { + maximum = Optional.ofNullable(maximum).map(max -> max.subtract(BigInteger.ONE)).orElse(null); + } + + // If the minimum value is greater than or equal to zero, then it is safe to use an unsigned type + boolean guaranteedPositive = Optional.ofNullable(minimum).map(min -> min.signum() >= 0).orElse(false); + + int requiredBits = Math.max( + Optional.ofNullable(minimum).map(BigInteger::bitLength).orElse(0), + Optional.ofNullable(maximum).map(BigInteger::bitLength).orElse(0) + ); + + // We will only enable the smaller types (less than 32 bits) if we know both the minimum and maximum + boolean knownRange = !(Objects.isNull(minimum) || Objects.isNull(maximum)); + + if (guaranteedPositive && preferUnsigned) { + if (requiredBits <= 8 && knownRange) { + return "u8"; + } else if (requiredBits <= 16 && knownRange) { + return "u16"; + } else if (requiredBits <= 32) { + return "u32"; + } else if (requiredBits <= 64) { + return "u64"; + } else if (requiredBits <= 128) { + return "u128"; + } + } else { + if (requiredBits <= 7 && knownRange) { + return "i8"; + } else if (requiredBits <= 15 && knownRange) { + return "i16"; + } else if (requiredBits <= 31) { + return "i32"; + } else if (requiredBits <= 63) { + return "i64"; + } else if (requiredBits <= 127) { + return "i128"; + } + } + + throw new RuntimeException("Number is too large to fit into i128"); + } + + /** + * Determine if an integer property can be guaranteed to fit into an unsigned data type. + * @param minimum The minimum value as set in the specification. + * @param exclusiveMinimum If boundary values are excluded by the specification. + * @return True if the effective minimum is greater than or equal to zero. + */ + @VisibleForTesting + public boolean canFitIntoUnsigned(@Nullable BigInteger minimum, boolean exclusiveMinimum) { + return Optional.ofNullable(minimum).map(min -> { + if (exclusiveMinimum) { + min = min.add(BigInteger.ONE); + } + return min.signum() >= 0; + }).orElse(false); + } + + public enum CasingType {CAMEL_CASE, SNAKE_CASE}; + + /** + * General purpose sanitizing function for Rust identifiers (fields, variables, structs, parameters, etc.).
        + * Rules for Rust are fairly simple: + *
          + *
        • Characters must belong to [A-Za-z0-9_] + *
        • Cannot use reserved words (but can sometimes prefix with "r#") + *
        • Cannot begin with a number + *
        + * @param name The input string + * @param casingType Which casing type to apply + * @param escapePrefix Prefix to escape words beginning with numbers or reserved words + * @param type The type of identifier (used for logging) + * @param allowRawIdentifiers Raw identifiers can't always be used, because of filename vs import mismatch. + * @return Sanitized string + */ + public String sanitizeIdentifier(String name, CasingType casingType, String escapePrefix, String type, boolean allowRawIdentifiers) { + String originalName = name; + + Function casingFunction; + switch (casingType) { + case CAMEL_CASE: + // This probably seems odd, but it is necessary for two reasons + // Compatibility with rust-server, such that MyIDList => my_id_list => MyIdList + // Conversion from SCREAMING_SNAKE_CASE to ScreamingSnakeCase + casingFunction = (input) -> camelize(underscore(input)); + break; + case SNAKE_CASE: + casingFunction = StringUtils::underscore; + break; + default: + throw new IllegalArgumentException("Unknown CasingType"); + } + + // Replace hyphens with underscores + name = name.replaceAll("-", "_"); + + // Apply special character escapes, e.g. "@type" => "At_type" + // Remove the trailing underscore if necessary + if (!Strings.isNullOrEmpty(name)) { + boolean endedWithUnderscore = name.endsWith("_"); + name = escape(name, specialCharReplacements, charactersToAllow, "_"); + if (!endedWithUnderscore && name.endsWith("_")) { + name = org.apache.commons.lang3.StringUtils.chop(name); + } + } + + // Sanitize any other special characters that weren't replaced + name = sanitizeName(name); + + // Keep track of modifications prior to casing + boolean nameWasModified = !originalName.equals(name); + + // Convert casing + name = casingFunction.apply(name); + + // If word starts with number add a prefix + // Note: this must be done after casing since CamelCase will strip leading underscores + if (name.matches("^\\d.*")) { + nameWasModified = true; + name = casingFunction.apply(escapePrefix + '_' + name); + } + + // Escape reserved words - this is case-sensitive so must be done after casing + // There is currently a bug in Rust where this doesn't work for a few reserved words :( + // https://internals.rust-lang.org/t/raw-identifiers-dont-work-for-all-identifiers/9094 + if (isReservedWord(name)) { + nameWasModified = true; + if (this.keywordsThatDoNotSupportRawIdentifiers.contains(name) || !allowRawIdentifiers) { + name = casingFunction.apply(escapePrefix + '_' + name); + } else { + name = "r#" + name; + }; + } + + // If the name had to be modified (not just because of casing), log the change + if (nameWasModified) { + LOGGER.warn("{} cannot be used as a {} name. Renamed to {}", casingFunction.apply(originalName), type, name); + } + + return name; + } + + @Override + public String toVarName(String name) { + return sanitizeIdentifier(name, CasingType.SNAKE_CASE, "param", "field/variable", true); + } + + @Override + public String toParamName(String name) { + return sanitizeIdentifier(name, CasingType.SNAKE_CASE, "param", "parameter", true); + } + + @Override + public String toOperationId(String operationId) { + return sanitizeIdentifier(operationId, CasingType.SNAKE_CASE, "call", "method", true); + } + + //// Model naming //// + + protected String addModelNamePrefixAndSuffix(String name) { + if (!Strings.isNullOrEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + if (!Strings.isNullOrEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + return name; + } + + @Override + public String toModelName(String name) { + return sanitizeIdentifier(addModelNamePrefixAndSuffix(name), CasingType.CAMEL_CASE, "model", "model", false); + } + + @Override + public String toModelFilename(String name) { + return sanitizeIdentifier(addModelNamePrefixAndSuffix(name), CasingType.SNAKE_CASE, "model", "model file", false); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + //// Enum naming //// + + @Override + public String toEnumVarName(String name, String datatype) { + // Empty strings need to be mapped to "Empty" + // https://github.com/OpenAPITools/openapi-generator/issues/13453 + if (Strings.isNullOrEmpty(name)) { + return "Empty"; + } + // Rust Enum variants should be camel cased + return sanitizeIdentifier(name, CasingType.CAMEL_CASE, "variant", "enum variant", true); + } + + @Override + public String toEnumName(CodegenProperty property) { + // Note: Strangely this function is only used for inline enums, schema enums go through the toModelName function + String name = property.name; + if (!Strings.isNullOrEmpty(enumSuffix)) { + name = name + "_" + enumSuffix; + } + return sanitizeIdentifier(name, CasingType.CAMEL_CASE, "enum", "enum", false); + } + + @Override + public String toEnumValue(String value, String datatype) { + // This is the representation of the enum that will be serialized / deserialized + // Note: generators currently only support string enums, so checking the type here is pointless + return escapeText(value); + } + + @Override + public String toEnumDefaultValue(String value, String datatype) { + // TODO: Bug: currently the templates ignore this function and just use `Self::{{ enumVars.0.name }}` + // Return the Rust type name of the variant so we can `impl Default` with it + return toEnumVarName(value, datatype); + } + + //// API naming //// + + protected String addApiNamePrefixAndSuffix(String name) { + if (Strings.isNullOrEmpty(name)) { + name = "default"; + } + if (!Strings.isNullOrEmpty(apiNamePrefix)) { + name = apiNamePrefix + "_" + name; + } + if (!Strings.isNullOrEmpty(apiNameSuffix)) { + name = name + "_" + apiNameSuffix; + } + return name; + } + + @Override + public String toApiName(String name) { + return sanitizeIdentifier(addApiNamePrefixAndSuffix(name), CasingType.CAMEL_CASE, "api", "API", false); + } + + @Override + public String toApiFilename(String name) { + return sanitizeIdentifier(addApiNamePrefixAndSuffix(name), CasingType.SNAKE_CASE, "api", "API file", false); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java index f7f6997a2f..91c7bb1acc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -24,6 +24,7 @@ import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.parameters.Parameter; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; +import org.checkerframework.checker.nullness.qual.Nullable; import org.openapitools.codegen.CodegenConstants.ENUM_PROPERTY_NAMING_TYPE; import org.openapitools.codegen.CodegenConstants.MODEL_PROPERTY_NAMING_TYPE; import org.openapitools.codegen.CodegenConstants.PARAM_NAMING_TYPE; @@ -39,13 +40,183 @@ import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; +import java.util.function.BiPredicate; +import java.util.function.Function; +import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; +import static org.openapitools.codegen.languages.AbstractTypeScriptClientCodegen.ParameterExpander.ParamStyle.*; import static org.openapitools.codegen.utils.StringUtils.camelize; import static org.openapitools.codegen.utils.StringUtils.underscore; public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { + + /** + * Help generating code for any kind of URL parameters (path, matrix, query). + *

        + * Generators may use this class when substituting URL-parameter-placeholders + * with generated code: + *

        + *

        + * While parsing placeholders character-by-character, this class helps accumulating these characters and + * building the final placeholder name. + *

        + *

        + * With the placeholder name, this class tries to find the parameter in the operation. + * The class then uses this parameter to build code that is usable by the generator. + *

        + */ + // TODO: this class grew quite large and most code now is specific to TypeScriptAngularClientCodeGen.java. + // => move code-generation to the concrete generator and let the generator pass this as lambda + @SuppressWarnings("StringBufferField") + public static class ParameterExpander { + private static final Pattern JS_QUOTE_PATTERN = Pattern.compile("\""); + private static final String JS_QUOTE_REPLACEMENT = "\\\""; + + /** + * How the parameter is formatted/converted/encoded in the actual request. + *

        + * See e.g. OpenAPI 3.1 spec: Style Values. + *

        + */ + public enum ParamStyle { + matrix, + label, + form, + simple, + spaceDelimited, + pipeDelimited, + deepObject; + + public String asString() { + return name(); + } + } + + /** + * Where the parameter is located in the request. + *

        + * See e.g. OpenAPI 3.1 spec: Parameter Locations + *

        + */ + public enum Location { + query((operation, param) -> operation.queryParams.contains(param), form), + header((operation, param) -> operation.headerParams.contains(param), simple), + path((operation, param) -> operation.pathParams.contains(param), simple), + cookie((operation, param) -> operation.cookieParams.contains(param), form); + + public final ParamStyle defaultStyle; + public final BiPredicate isPresentIn; + + Location(BiPredicate isPresentIn, ParamStyle defaultStyle) { + this.defaultStyle = defaultStyle; + this.isPresentIn = isPresentIn; + } + + public String defaultStyle(@Nullable String style) { + if (style != null && !style.trim().isEmpty()) { + return style; + } + return defaultStyle.asString(); + } + + public static Location fromParam(CodegenOperation op, CodegenParameter param) { + return Arrays.stream(values()) + .filter(v -> v.isPresentIn.test(op, param)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(String.format( + Locale.ROOT, + "Cannot find param ' %s' in operation '%s'", + param, op.operationId + ))); + } + } + + private final StringBuilder parameterName = new StringBuilder(); + private final CodegenOperation op; + private final Function toParameterName; + + public ParameterExpander(CodegenOperation op, Function toParameterName) { + this.op = op; + this.toParameterName = toParameterName; + } + + private void reset() { + parameterName.setLength(0); + } + + public void appendToParameterName(char c) { + parameterName.append(c); + } + + public String buildPathEntry() { + CodegenParameter parameter = findPathParameterByName(); + + String result = ""; + if (parameter != null) { + String generatedParameterName = toParameterName.apply(parameterName.toString()); + result = buildPathEntry(parameter, generatedParameterName); + } + + reset(); + return result; + } + + private String buildPathEntry(CodegenParameter parameter, String generatedParameterName) { + Location location = Location.fromParam(op, parameter); + String style = location.defaultStyle(parameter.style); + + String optsObject = String.format( + Locale.ROOT, + "{name: %s, value: %s, in: %s, style: %s, explode: %s, dataType: %s, dataFormat: %s}", + quotedJSString(parameter.paramName), + generatedParameterName, + quotedJSString(location.name()), + quotedJSString(style), + parameter.isExplode, + quotedJSString(parameter.dataType), + nullableQuotedJSString(parameter.dataFormat) + ); + + String result = String.format(Locale.ROOT, "${this.configuration.encodeParam(%s)}", optsObject); + return result; + } + + private @Nullable CodegenParameter findPathParameterByName() { + for (CodegenParameter param : op.pathParams) { + if (param.baseName.equals(parameterName.toString())) { + return param; + } + } + return null; + } + + private static String quotedJSString(String string) { + String escaped = escapeForQuotedJSString(string); + String result = '"' + escaped + '"'; + return result; + } + + protected static String escapeForQuotedJSString(String string) { + String quoted = JS_QUOTE_PATTERN.matcher(string) + .replaceAll(JS_QUOTE_REPLACEMENT); + + return quoted; + } + + + protected String nullableQuotedJSString(@Nullable String string) { + if (string == null) { + return "undefined"; + } + + String result = quotedJSString(string); + + return result; + } + } + private final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class); private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value"; @@ -436,9 +607,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp String nullSafeSuffix = getNullSafeAdditionalProps() ? " | undefined" : ""; return "{ [key: string]: " + getTypeDeclaration(unaliasSchema(inner)) + nullSafeSuffix + "; }"; } else if (ModelUtils.isFileSchema(p)) { - return "any"; + return "File"; } else if (ModelUtils.isBinarySchema(p)) { - return "any"; + return "ArrayBuffer"; } return super.getTypeDeclaration(p); } @@ -547,7 +718,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp return UNDEFINED_VALUE; } else if (ModelUtils.isStringSchema(p)) { if (p.getDefault() != null) { - return "'" + escapeText((String) p.getDefault()) + "'"; + return "'" + escapeText(String.valueOf(p.getDefault())) + "'"; } return UNDEFINED_VALUE; } else { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java index b220aa8b1c..4ee7821aef 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java @@ -44,6 +44,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { public static final String USE_SWASHBUCKLE = "useSwashbuckle"; public static final String MODEL_POCOMODE = "pocoModels"; + public static final String USE_MODEL_SEPERATEPROJECT = "useSeperateModelProject"; public static final String ASPNET_CORE_VERSION = "aspnetCoreVersion"; public static final String SWASHBUCKLE_VERSION = "swashbuckleVersion"; public static final String CLASS_MODIFIER = "classModifier"; @@ -72,9 +73,10 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { private boolean useSwashbuckle = true; private boolean pocoModels = false; + private boolean useSeperateModelProject = false; protected int serverPort = 8080; protected String serverHost = "0.0.0.0"; - protected CliOption swashbuckleVersion = new CliOption(SWASHBUCKLE_VERSION, "Swashbuckle version: 3.0.0, 4.0.0, 5.0.0, 6.0.0"); + protected CliOption swashbuckleVersion = new CliOption(SWASHBUCKLE_VERSION, "Swashbuckle version: 3.0.0 (deprecated), 4.0.0 (deprecated), 5.0.0 (deprecated), 6.4.0"); protected CliOption aspnetCoreVersion = new CliOption(ASPNET_CORE_VERSION, "ASP.NET Core version: 6.0, 5.0, 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)"); private CliOption classModifier = new CliOption(CLASS_MODIFIER, "Class Modifier for controller classes: Empty string or abstract."); private CliOption operationModifier = new CliOption(OPERATION_MODIFIER, "Operation Modifier can be virtual or abstract"); @@ -210,7 +212,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { swashbuckleVersion.addEnum("3.0.0", "Swashbuckle 3.0.0"); swashbuckleVersion.addEnum("4.0.0", "Swashbuckle 4.0.0"); swashbuckleVersion.addEnum("5.0.0", "Swashbuckle 5.0.0"); - swashbuckleVersion.addEnum("6.0.0", "Swashbuckle 6.0.0"); + swashbuckleVersion.addEnum("6.4.0", "Swashbuckle 6.4.0"); swashbuckleVersion.setDefault("3.0.0"); swashbuckleVersion.setOptValue(swashbuckleVersion.getDefault()); cliOptions.add(swashbuckleVersion); @@ -244,6 +246,10 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { "Build POCO Models", pocoModels); + addSwitch(USE_MODEL_SEPERATEPROJECT, + "Create a seperate project for models", + useSeperateModelProject); + addSwitch(IS_LIBRARY, "Is the build a library", isLibrary); @@ -367,6 +373,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { setOperationModifier(); setModelClassModifier(); setPocoModels(); + setUseSeperateModelProject(); setUseSwashbuckle(); setOperationIsAsync(); @@ -393,17 +400,30 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { setIsFramework(); setUseNewtonsoft(); setUseEndpointRouting(); - + supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh")); supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); supportingFiles.add(new SupportingFile("gitignore", packageFolder, ".gitignore")); supportingFiles.add(new SupportingFile("validateModel.mustache", packageFolder + File.separator + "Attributes", "ValidateModelStateAttribute.cs")); - supportingFiles.add(new SupportingFile("typeConverter.mustache", packageFolder + File.separator + "Converters", "CustomEnumConverter.cs")); + + if (useSeperateModelProject) + { + supportingFiles.add(new SupportingFile("typeConverter.mustache", sourceFolder + File.separator + modelPackage + File.separator + "Converters", "CustomEnumConverter.cs")); + } else { + supportingFiles.add(new SupportingFile("typeConverter.mustache", packageFolder + File.separator + "Converters", "CustomEnumConverter.cs")); + } + if (aspnetCoreVersion.getOptValue().startsWith("3.") || aspnetCoreVersion.getOptValue().startsWith("5.0") || aspnetCoreVersion.getOptValue().startsWith("6.")) { supportingFiles.add(new SupportingFile("OpenApi" + File.separator + "TypeExtensions.mustache", packageFolder + File.separator + "OpenApi", "TypeExtensions.cs")); } + + if (useSeperateModelProject) + { + supportingFiles.add(new SupportingFile("ModelsProject.csproj.mustache", sourceFolder + File.separator + modelPackage, modelPackage + ".csproj")); + } + supportingFiles.add(new SupportingFile("Project.csproj.mustache", packageFolder, packageName + ".csproj")); if (!isLibrary) { supportingFiles.add(new SupportingFile("Dockerfile.mustache", packageFolder, "Dockerfile")); @@ -445,7 +465,12 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Models"; + if (!useSeperateModelProject) + { + return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Models"; + } else { + return outputFolder + File.separator + sourceFolder + File.separator + modelPackage; + } } @Override @@ -671,6 +696,18 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { } } + private void setUseSeperateModelProject() { + if (additionalProperties.containsKey(USE_MODEL_SEPERATEPROJECT)) { + useSeperateModelProject = convertPropertyToBooleanAndWriteBack(USE_MODEL_SEPERATEPROJECT); + if (useSeperateModelProject) + { + LOGGER.info("Using seperate model project"); + } + } else { + additionalProperties.put(USE_MODEL_SEPERATEPROJECT, useSeperateModelProject); + } + } + private void setUseSwashbuckle() { if (isLibrary) { LOGGER.warn("isLibrary is true so changing default useSwashbuckle to false"); @@ -760,13 +797,18 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { private void setSwashbuckleVersion() { setCliOption(swashbuckleVersion); - if (aspnetCoreVersion.getOptValue().startsWith("3.") || aspnetCoreVersion.getOptValue().startsWith("5.")) { - LOGGER.warn("ASP.NET core version is {} so changing default Swashbuckle version to 5.0.0.", aspnetCoreVersion.getOptValue()); - swashbuckleVersion.setOptValue("5.0.0"); + if (aspnetCoreVersion.getOptValue().startsWith("3.")) { + LOGGER.warn("ASP.NET core version is {} so changing default Swashbuckle version to 6.4.0.", aspnetCoreVersion.getOptValue()); + swashbuckleVersion.setOptValue("6.4.0"); + additionalProperties.put(SWASHBUCKLE_VERSION, swashbuckleVersion.getOptValue()); + } else if (aspnetCoreVersion.getOptValue().startsWith("5.")) { + // for aspnet core 5.x, use Swashbuckle 6.4 instead + LOGGER.warn("ASP.NET core version is {} so changing default Swashbuckle version to 6.4.0.", aspnetCoreVersion.getOptValue()); + swashbuckleVersion.setOptValue("6.4.0"); additionalProperties.put(SWASHBUCKLE_VERSION, swashbuckleVersion.getOptValue()); } else if (aspnetCoreVersion.getOptValue().startsWith("6.")) { - LOGGER.warn("ASP.NET core version is {} so changing default Swashbuckle version to 6.0.0.", aspnetCoreVersion.getOptValue()); - swashbuckleVersion.setOptValue("6.0.0"); + LOGGER.warn("ASP.NET core version is {} so changing default Swashbuckle version to 6.4.0.", aspnetCoreVersion.getOptValue()); + swashbuckleVersion.setOptValue("6.4.0"); additionalProperties.put(SWASHBUCKLE_VERSION, swashbuckleVersion.getOptValue()); } else { // default, do nothing diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java index a7e1ad495c..8297567602 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java @@ -77,6 +77,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { FrameworkStrategy.NETSTANDARD_2_1, FrameworkStrategy.NETCOREAPP_3_1, FrameworkStrategy.NETFRAMEWORK_4_7, + FrameworkStrategy.NETFRAMEWORK_4_8, FrameworkStrategy.NET_5_0, FrameworkStrategy.NET_6_0 ); @@ -84,6 +85,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { protected final Map frameworks; protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase(Locale.ROOT) + "}"; protected String clientPackage = "Org.OpenAPITools.Client"; + protected String authFolder = "Auth"; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; @@ -119,6 +121,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.OAuth2_Implicit, + SecurityFeature.OAuth2_ClientCredentials, SecurityFeature.BasicAuth, SecurityFeature.ApiKey )) @@ -729,6 +732,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { if (!additionalProperties.containsKey(CodegenConstants.NULLABLE_REFERENCE_TYPES) && !strategies.stream().anyMatch(s -> s.equals(FrameworkStrategy.NETCOREAPP_3_1) || s.equals(FrameworkStrategy.NET_5_0) || + s.equals(FrameworkStrategy.NETFRAMEWORK_4_8) || s.equals(FrameworkStrategy.NETFRAMEWORK_4_7))) { // starting in .net 6.0, NRT is enabled by default. If not specified, lets enable NRT to match the framework's default setNullableReferenceTypes(true); @@ -759,6 +763,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { String packageFolder = sourceFolder + File.separator + packageName; String clientPackageDir = packageFolder + File.separator + clientPackage; String modelPackageDir = packageFolder + File.separator + modelPackage; + String authPackageDir = clientPackageDir + File.separator + authFolder; String testPackageFolder = testFolder + File.separator + testPackageName; additionalProperties.put("testPackageName", testPackageName); @@ -782,17 +787,23 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { if (HTTPCLIENT.equals(getLibrary())) { supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs")); typeMapping.put("file", "FileParameter"); - addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir); + addSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir, authPackageDir); additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); } else if (GENERICHOST.equals(getLibrary())) { addGenericHostSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir); additionalProperties.put("apiDocPath", apiDocPath + File.separatorChar + "apis"); additionalProperties.put("modelDocPath", modelDocPath + File.separatorChar + "models"); - } else { - addRestSharpSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir); + } else { //restsharp + addSupportingFiles(clientPackageDir, packageFolder, excludeTests, testPackageFolder, testPackageName, modelPackageDir, authPackageDir); additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); + + if (ProcessUtils.hasOAuthMethods(openAPI)) { + supportingFiles.add(new SupportingFile("auth/OAuthAuthenticator.mustache", authPackageDir, "OAuthAuthenticator.cs")); + supportingFiles.add(new SupportingFile("auth/TokenResponse.mustache", authPackageDir, "TokenResponse.cs")); + supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authPackageDir, "OAuthFlow.cs")); + } } addTestInstructions(); @@ -848,8 +859,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { } } - public void addRestSharpSupportingFiles(final String clientPackageDir, final String packageFolder, - final AtomicReference excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir) { + public void addSupportingFiles(final String clientPackageDir, final String packageFolder, + final AtomicReference excludeTests, final String testPackageFolder, final String testPackageName, final String modelPackageDir, final String authPackageDir) { supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", clientPackageDir, "ApiClient.cs")); @@ -1232,6 +1243,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { }; static FrameworkStrategy NETFRAMEWORK_4_7 = new FrameworkStrategy("net47", ".NET Framework 4.7 compatible", "net47", Boolean.FALSE) { }; + static FrameworkStrategy NETFRAMEWORK_4_8 = new FrameworkStrategy("net48", ".NET Framework 4.8 compatible", "net48", Boolean.FALSE) { + }; static FrameworkStrategy NET_5_0 = new FrameworkStrategy("net5.0", ".NET 5.0 compatible", "net5.0", Boolean.FALSE) { }; static FrameworkStrategy NET_6_0 = new FrameworkStrategy("net6.0", ".NET 6.0 compatible", "net6.0", Boolean.FALSE) { @@ -1476,6 +1489,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { cm.readOnlyVars.removeIf(item -> item.baseName.equals(v.baseName)); cm.requiredVars.removeIf(item -> item.baseName.equals(v.baseName)); cm.allVars.removeIf(item -> item.baseName.equals(v.baseName)); + cm.nonNullableVars.removeIf(item -> item.baseName.equals(v.baseName)); }); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java index 00cd52dbab..1026f9e9eb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java @@ -139,12 +139,14 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen { typeMapping.put("UUID", "std::string"); typeMapping.put("URI", "std::string"); typeMapping.put("ByteArray", "std::string"); + typeMapping.put("AnyType", "nlohmann::json"); super.importMapping = new HashMap<>(); importMapping.put("std::vector", "#include "); importMapping.put("std::map", "#include "); importMapping.put("std::string", "#include "); importMapping.put("Object", "#include \"Object.h\""); + importMapping.put("nlohmann::json", "#include "); } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java index 9d7ce46baf..93ade02496 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java @@ -38,6 +38,8 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { public static final String DECLSPEC = "declspec"; public static final String DEFAULT_INCLUDE = "defaultInclude"; + private static final String OPEN_API_PATH_PARAM_PATTERN = "^\\{(.*)\\}$"; + private static final String X_CODEGEN_OTHER_METHODS = "x-codegen-other-methods"; protected String packageVersion = "1.0.0"; protected String declspec = ""; @@ -96,6 +98,9 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("model-helpers-header.mustache", modelFileFolder(), "helpers.h")); + supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", "", "CMakeLists.txt")); + supportingFiles.add(new SupportingFile("FindRestbedAndBoost.cmake", "", "FindRestbedAndBoost.cmake")); languageSpecificPrimitives = new HashSet<>( Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t")); @@ -109,10 +114,12 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { typeMapping.put("boolean", "bool"); typeMapping.put("array", "std::vector"); typeMapping.put("map", "std::map"); + typeMapping.put("set", "std::set"); typeMapping.put("file", "std::string"); - typeMapping.put("object", "Object"); + typeMapping.put("object", "std::string"); typeMapping.put("binary", "restbed::Bytes"); typeMapping.put("number", "double"); + typeMapping.put("decimal", "std::string"); typeMapping.put("UUID", "std::string"); typeMapping.put("URI", "std::string"); typeMapping.put("ByteArray", "std::string"); @@ -120,8 +127,9 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { super.importMapping = new HashMap<>(); importMapping.put("std::vector", "#include "); importMapping.put("std::map", "#include "); + importMapping.put("std::set", "#include "); + importMapping.put("file", "#include "); importMapping.put("std::string", "#include "); - importMapping.put("Object", "#include \"Object.h\""); importMapping.put("restbed::Bytes", "#include "); } @@ -203,6 +211,11 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { return "Generates a C++ API Server with Restbed (https://github.com/Corvusoft/restbed)."; } + @Override + public String getTypeDeclaration(String str) { + return toModelName(str); + } + @Override public void processOpts() { super.processOpts(); @@ -267,10 +280,6 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { codegenModel.imports.add(newImp); } } - // Import vector if an enum is present - if (codegenModel.hasEnums) { - codegenModel.imports.add("#include "); - } return codegenModel; } @@ -284,6 +293,32 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { return toApiName(name); } + + private String capitalizeFirstChar(String str) { + if (str.length() > 1) { + return Character.toUpperCase(str.charAt(0)) + str.substring(1); + } else { + return str.toUpperCase(Locale.ENGLISH); + } + } + + private String convertPathSegmentToResourceNamePart(String pathSegment) { + String convertedSegnemt = pathSegment; + if (pathSegment.matches(OPEN_API_PATH_PARAM_PATTERN)) { + convertedSegnemt = pathSegment.substring(1, pathSegment.length() - 1); + } + return capitalizeFirstChar(sanitizeName(convertedSegnemt)); + } + + private String convertPathParamPattern(String pathSegment) { + if (pathSegment.matches(OPEN_API_PATH_PARAM_PATTERN)) { + String pattern = pathSegment.substring(0, pathSegment.length() - 1); + pattern += ": .*}"; + return pattern; + } + return pathSegment; + } + @Override public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { OperationMap operations = objs.getOperations(); @@ -291,46 +326,31 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { List newOpList = new ArrayList<>(); for (CodegenOperation op : operationList) { - String path = op.path; - - String[] items = path.split("/", -1); + String[] pathSegments = op.path.split("/", -1); String resourceNameCamelCase = ""; - op.path = ""; - for (String item : items) { - if (item.length() > 1) { - if (item.matches("^\\{(.*)\\}$")) { - String tmpResourceName = item.substring(1, item.length() - 1); - resourceNameCamelCase += Character.toUpperCase(tmpResourceName.charAt(0)) + tmpResourceName.substring(1); - item = item.substring(0, item.length() - 1); - item += ": .*}"; - } else { - resourceNameCamelCase += Character.toUpperCase(item.charAt(0)) + item.substring(1); + StringJoiner joiner = new StringJoiner("/"); + for (String pathSegment : pathSegments) { + resourceNameCamelCase += convertPathSegmentToResourceNamePart(pathSegment); + String convertedPathSegment = convertPathParamPattern(pathSegment); + joiner.add(convertedPathSegment); } - } else if (item.length() == 1) { - resourceNameCamelCase += Character.toUpperCase(item.charAt(0)); - } - op.path += item + "/"; - } + + op.path = joiner.toString(); op.vendorExtensions.put("x-codegen-resource-name", resourceNameCamelCase); - boolean foundInNewList = false; - for (CodegenOperation op1 : newOpList) { - if (!foundInNewList) { - if (op1.path.equals(op.path)) { - foundInNewList = true; - final String X_CODEGEN_OTHER_METHODS = "x-codegen-other-methods"; - @SuppressWarnings("unchecked") - List currentOtherMethodList = (List) op1.vendorExtensions.get(X_CODEGEN_OTHER_METHODS); - if (currentOtherMethodList == null) { - currentOtherMethodList = new ArrayList<>(); - } + + CodegenOperation op1 = newOpList.stream() + .filter(opInList -> opInList.path.equals(op.path)) + .findAny() + .orElse(null); + + if (op1 != null) { + List currentOtherMethodList = getCodegenXCodegenOtherMethodsOperations(op1); op.operationIdCamelCase = op1.operationIdCamelCase; currentOtherMethodList.add(op); op1.vendorExtensions.put(X_CODEGEN_OTHER_METHODS, currentOtherMethodList); } - } - } - if (!foundInNewList) { + else { newOpList.add(op); } } @@ -338,6 +358,14 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { return objs; } + private List getCodegenXCodegenOtherMethodsOperations(CodegenOperation newOperation) { + List currentOtherMethodList = (List) newOperation.vendorExtensions.get(X_CODEGEN_OTHER_METHODS); + if (currentOtherMethodList == null) { + currentOtherMethodList = new ArrayList<>(); + } + return currentOtherMethodList; + } + /** * Optional - type declaration. This is a String which is used by the * templates to instantiate your types. There is typically special handling @@ -359,14 +387,16 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { return getSchemaType(p) + ""; } else if (ModelUtils.isByteArraySchema(p)) { return "std::string"; + } else if (ModelUtils.isFileSchema(p)) { + return "std::string"; } else if (ModelUtils.isStringSchema(p) || ModelUtils.isDateSchema(p) - || ModelUtils.isDateTimeSchema(p) || ModelUtils.isFileSchema(p) + || ModelUtils.isDateTimeSchema(p) || languageSpecificPrimitives.contains(openAPIType)) { return toModelName(openAPIType); } - return "std::shared_ptr<" + openAPIType + ">"; + return openAPIType; } @Override @@ -395,6 +425,12 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { } else { return "\"\""; } + } else if (ModelUtils.isFileSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); + } else { + return "std::string{}"; + } } else if (ModelUtils.isNumberSchema(p)) { if (ModelUtils.isFloatSchema(p)) { // float if (p.getDefault() != null) { @@ -432,15 +468,19 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { } else if (ModelUtils.isMapSchema(p)) { String inner = getSchemaType(getAdditionalProperties(p)); return "std::map()"; + } else if (ModelUtils.isSet(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); + return "std::set<" + inner + ">()"; } else if (ModelUtils.isArraySchema(p)) { ArraySchema ap = (ArraySchema) p; String inner = getSchemaType(ap.getItems()); - if (!languageSpecificPrimitives.contains(inner)) { - inner = "std::shared_ptr<" + inner + ">"; - } return "std::vector<" + inner + ">()"; + } else if (ModelUtils.isModel(p)) { + String modelName = getTypeDeclaration(p); + return modelName + "{}"; } else if (!StringUtils.isEmpty(p.get$ref())) { - return "std::make_shared<" + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + ">()"; + return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "{}"; } return "nullptr"; @@ -455,8 +495,7 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { boolean isString = parameter.isString == Boolean.TRUE; if (!isPrimitiveType && !isArray && !isString && !parameter.dataType.startsWith("std::shared_ptr")) { - parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">"; - parameter.defaultValue = "std::make_shared<" + parameter.dataType + ">()"; + parameter.defaultValue = parameter.dataType + "{}"; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerDeprecatedCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerDeprecatedCodegen.java new file mode 100644 index 0000000000..0e243b2f61 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerDeprecatedCodegen.java @@ -0,0 +1,490 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * 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.media.ArraySchema; +import io.swagger.v3.oas.models.media.Schema; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.model.ModelMap; +import org.openapitools.codegen.model.ModelsMap; +import org.openapitools.codegen.model.OperationMap; +import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.utils.ModelUtils; + +import java.io.File; +import java.util.*; +import java.util.Map.Entry; + +import static org.openapitools.codegen.utils.StringUtils.camelize; + +public class CppRestbedServerDeprecatedCodegen extends AbstractCppCodegen { + + public static final String DECLSPEC = "declspec"; + public static final String DEFAULT_INCLUDE = "defaultInclude"; + + protected String packageVersion = "1.0.0"; + protected String declspec = ""; + protected String defaultInclude = ""; + + public CppRestbedServerDeprecatedCodegen() { + super(); + + // TODO: cpp-restbed-server maintainer review + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling, + GlobalFeature.MultiServer + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + ); + + apiPackage = "org.openapitools.server.api"; + modelPackage = "org.openapitools.server.model"; + + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-source.mustache", ".cpp"); + + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-source.mustache", ".cpp"); + + embeddedTemplateDir = templateDir = "cpp-restbed-server-deprecated"; + + cliOptions.clear(); + + // CLI options + addOption(CodegenConstants.MODEL_PACKAGE, "C++ namespace for models (convention: name.space.model).", + this.modelPackage); + addOption(CodegenConstants.API_PACKAGE, "C++ namespace for apis (convention: name.space.api).", + this.apiPackage); + addOption(CodegenConstants.PACKAGE_VERSION, "C++ package version.", this.packageVersion); + addOption(DECLSPEC, "C++ preprocessor to place before the class name for handling dllexport/dllimport.", + this.declspec); + addOption(DEFAULT_INCLUDE, + "The default include statement that should be placed in all headers for including things like the declspec (convention: #include \"Commons.h\" ", + this.defaultInclude); + addOption(RESERVED_WORD_PREFIX_OPTION, + RESERVED_WORD_PREFIX_DESC, + this.reservedWordPrefix); + + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + languageSpecificPrimitives = new HashSet<>( + Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t")); + + typeMapping = new HashMap<>(); + typeMapping.put("date", "std::string"); + typeMapping.put("DateTime", "std::string"); + typeMapping.put("string", "std::string"); + typeMapping.put("integer", "int32_t"); + typeMapping.put("long", "int64_t"); + typeMapping.put("boolean", "bool"); + typeMapping.put("array", "std::vector"); + typeMapping.put("map", "std::map"); + typeMapping.put("file", "std::string"); + typeMapping.put("object", "Object"); + typeMapping.put("binary", "restbed::Bytes"); + typeMapping.put("number", "double"); + typeMapping.put("UUID", "std::string"); + typeMapping.put("URI", "std::string"); + typeMapping.put("ByteArray", "std::string"); + + super.importMapping = new HashMap<>(); + importMapping.put("std::vector", "#include "); + importMapping.put("std::map", "#include "); + importMapping.put("std::string", "#include "); + importMapping.put("Object", "#include \"Object.h\""); + importMapping.put("restbed::Bytes", "#include "); + } + + @Override + public Map updateAllModels(Map objs) { + // Index all CodegenModels by model name. + Map allModels = getAllModels(objs); + + // Clean interfaces of ambiguity + for (Entry cm : allModels.entrySet()) { + if (cm.getValue().getInterfaces() != null && !cm.getValue().getInterfaces().isEmpty()) { + List newIntf = new ArrayList<>(cm.getValue().getInterfaces()); + + for (String intf : allModels.get(cm.getKey()).getInterfaces()) { + if (allModels.get(intf).getInterfaces() != null && !allModels.get(intf).getInterfaces().isEmpty()) { + for (String intfInner : allModels.get(intf).getInterfaces()) { + newIntf.remove(intfInner); + } + } + } + cm.getValue().setInterfaces(newIntf); + } + } + + objs = super.updateAllModels(objs); + return objs; + } + + /** + * Camelize the method name of the getter and setter, but keep underscores at the front + * + * @param name string to be camelized + * @return Camelized string + */ + @Override + public String getterAndSetterCapitalize(String name) { + if (name == null || name.length() == 0) { + return name; + } + + name = toVarName(name); + + if (name.startsWith("_")) { + return "_" + camelize(name); + } + + return camelize(name); + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + */ + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + /** + * Configures a friendly name for the generator. This will be used by the + * generator to select the library with the -g flag. + * + * @return the friendly name for the generator + */ + @Override + public String getName() { + return "cpp-restbed-server-deprecated"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with + * help tips, parameters here + * + * @return A string value for the help message + */ + @Override + public String getHelp() { + return "Generates a C++ API Server with Restbed (https://github.com/Corvusoft/restbed)."; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(DECLSPEC)) { + declspec = additionalProperties.get(DECLSPEC).toString(); + } + + if (additionalProperties.containsKey(DEFAULT_INCLUDE)) { + defaultInclude = additionalProperties.get(DEFAULT_INCLUDE).toString(); + } + + if (additionalProperties.containsKey(RESERVED_WORD_PREFIX_OPTION)) { + reservedWordPrefix = additionalProperties.get(RESERVED_WORD_PREFIX_OPTION).toString(); + } + + additionalProperties.put("modelNamespaceDeclarations", modelPackage.split("\\.")); + additionalProperties.put("modelNamespace", modelPackage.replaceAll("\\.", "::")); + additionalProperties.put("apiNamespaceDeclarations", apiPackage.split("\\.")); + additionalProperties.put("apiNamespace", apiPackage.replaceAll("\\.", "::")); + additionalProperties.put("declspec", declspec); + additionalProperties.put("defaultInclude", defaultInclude); + additionalProperties.put(RESERVED_WORD_PREFIX_OPTION, reservedWordPrefix); + } + + /** + * Location to write model files. You can use the modelPackage() as defined + * when the class is instantiated + */ + @Override + public String modelFileFolder() { + return (outputFolder + "/model").replace("/", File.separator); + } + + /** + * Location to write api files. You can use the apiPackage() as defined when + * the class is instantiated + */ + @Override + public String apiFileFolder() { + return (outputFolder + "/api").replace("/", File.separator); + } + + @Override + public String toModelImport(String name) { + if (importMapping.containsKey(name)) { + return importMapping.get(name); + } else { + return "#include \"" + name + ".h\""; + } + } + + @Override + public CodegenModel fromModel(String name, Schema model) { + CodegenModel codegenModel = super.fromModel(name, model); + + Set oldImports = codegenModel.imports; + codegenModel.imports = new HashSet<>(); + for (String imp : oldImports) { + String newImp = toModelImport(imp); + if (!newImp.isEmpty()) { + codegenModel.imports.add(newImp); + } + } + // Import vector if an enum is present + if (codegenModel.hasEnums) { + codegenModel.imports.add("#include "); + } + return codegenModel; + } + + @Override + public String toModelFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiFilename(String name) { + return toApiName(name); + } + + @Override + public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { + OperationMap operations = objs.getOperations(); + List operationList = operations.getOperation(); + List newOpList = new ArrayList<>(); + + for (CodegenOperation op : operationList) { + String path = op.path; + + String[] items = path.split("/", -1); + String resourceNameCamelCase = ""; + op.path = ""; + for (String item : items) { + if (item.length() > 1) { + if (item.matches("^\\{(.*)\\}$")) { + String tmpResourceName = item.substring(1, item.length() - 1); + resourceNameCamelCase += Character.toUpperCase(tmpResourceName.charAt(0)) + tmpResourceName.substring(1); + item = item.substring(0, item.length() - 1); + item += ": .*}"; + } else { + resourceNameCamelCase += Character.toUpperCase(item.charAt(0)) + item.substring(1); + } + } else if (item.length() == 1) { + resourceNameCamelCase += Character.toUpperCase(item.charAt(0)); + } + op.path += item + "/"; + } + op.vendorExtensions.put("x-codegen-resource-name", resourceNameCamelCase); + + boolean foundInNewList = false; + for (CodegenOperation op1 : newOpList) { + if (!foundInNewList) { + if (op1.path.equals(op.path)) { + foundInNewList = true; + final String X_CODEGEN_OTHER_METHODS = "x-codegen-other-methods"; + @SuppressWarnings("unchecked") + List currentOtherMethodList = (List) op1.vendorExtensions.get(X_CODEGEN_OTHER_METHODS); + if (currentOtherMethodList == null) { + currentOtherMethodList = new ArrayList<>(); + } + op.operationIdCamelCase = op1.operationIdCamelCase; + currentOtherMethodList.add(op); + op1.vendorExtensions.put(X_CODEGEN_OTHER_METHODS, currentOtherMethodList); + } + } + } + if (!foundInNewList) { + newOpList.add(op); + } + } + operations.setOperation(newOpList); + return objs; + } + + /** + * Optional - type declaration. This is a String which is used by the + * templates to instantiate your types. There is typically special handling + * for different property types + * + * @return a string value used as the `dataType` field for model templates, + * `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); + + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = getAdditionalProperties(p); + return getSchemaType(p) + ""; + } else if (ModelUtils.isByteArraySchema(p)) { + return "std::string"; + } else if (ModelUtils.isStringSchema(p) + || ModelUtils.isDateSchema(p) + || ModelUtils.isDateTimeSchema(p) || ModelUtils.isFileSchema(p) + || languageSpecificPrimitives.contains(openAPIType)) { + return toModelName(openAPIType); + } + + return "std::shared_ptr<" + openAPIType + ">"; + } + + @Override + public String toDefaultValue(Schema p) { + if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + return "\"" + p.getDefault().toString() + "\""; + } else { + return "\"\""; + } + } else if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + return p.getDefault().toString(); + } else { + return "false"; + } + } else if (ModelUtils.isDateSchema(p)) { + if (p.getDefault() != null) { + return "\"" + p.getDefault().toString() + "\""; + } else { + return "\"\""; + } + } else if (ModelUtils.isDateTimeSchema(p)) { + if (p.getDefault() != null) { + return "\"" + p.getDefault().toString() + "\""; + } else { + return "\"\""; + } + } else if (ModelUtils.isNumberSchema(p)) { + if (ModelUtils.isFloatSchema(p)) { // float + if (p.getDefault() != null) { + return p.getDefault().toString() + "f"; + } else { + return "0.0f"; + } + } else { // double + if (p.getDefault() != null) { + return p.getDefault().toString(); + } else { + return "0.0"; + } + } + } else if (ModelUtils.isIntegerSchema(p)) { + if (ModelUtils.isLongSchema(p)) { // long + if (p.getDefault() != null) { + return p.getDefault().toString() + "L"; + } else { + return "0L"; + } + } else { // integer + if (p.getDefault() != null) { + return p.getDefault().toString(); + } else { + return "0"; + } + } + } else if (ModelUtils.isByteArraySchema(p)) { + if (p.getDefault() != null) { + return "\"" + p.getDefault().toString() + "\""; + } else { + return "\"\""; + } + } else if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType(getAdditionalProperties(p)); + return "std::map()"; + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); + if (!languageSpecificPrimitives.contains(inner)) { + inner = "std::shared_ptr<" + inner + ">"; + } + return "std::vector<" + inner + ">()"; + } else if (!StringUtils.isEmpty(p.get$ref())) { + return "std::make_shared<" + toModelName(ModelUtils.getSimpleRef(p.get$ref())) + ">()"; + } + + return "nullptr"; + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + super.postProcessParameter(parameter); + + boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE; + boolean isArray = parameter.isArray == Boolean.TRUE; + boolean isString = parameter.isString == Boolean.TRUE; + + if (!isPrimitiveType && !isArray && !isString && !parameter.dataType.startsWith("std::shared_ptr")) { + parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">"; + parameter.defaultValue = "std::make_shared<" + parameter.dataType + ">()"; + } + } + + /** + * Optional - OpenAPI type conversion. This is used to map OpenAPI types in + * a `Schema` into either language specific types via `typeMapping` or + * into complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + */ + @Override + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); + String type = null; + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); + if (languageSpecificPrimitives.contains(type)) + return toModelName(type); + } else + type = openAPIType; + return toModelName(type); + } + + @Override + public void updateCodegenPropertyEnum(CodegenProperty var) { + // Remove prefix added by DefaultCodegen + String originalDefaultValue = var.defaultValue; + super.updateCodegenPropertyEnum(var); + var.defaultValue = originalDefaultValue; + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java index 01702710e5..2bad546e9b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java @@ -50,8 +50,8 @@ public class CrystalClientCodegen extends DefaultCodegen { private static final String NUMERIC_ENUM_PREFIX = "N"; protected static int emptyMethodNameCounter = 0; - protected String shardName; - protected String moduleName; + protected String shardName = "openapi_client"; + protected String moduleName = "OpenAPIClient"; protected String shardVersion = "1.0.0"; protected String specFolder = "spec"; protected String srcFolder = "src"; @@ -65,6 +65,7 @@ public class CrystalClientCodegen extends DefaultCodegen { protected String modelDocPath = "docs/"; public static final String SHARD_NAME = "shardName"; + public static final String MODULE_NAME = "moduleName"; public static final String SHARD_VERSION = "shardVersion"; public static final String SHARD_LICENSE = "shardLicense"; public static final String SHARD_HOMEPAGE = "shardHomepage"; @@ -171,7 +172,7 @@ public class CrystalClientCodegen extends DefaultCodegen { typeMapping.put("float", "Float32"); typeMapping.put("double", "Float64"); typeMapping.put("number", "Float64"); - typeMapping.put("decimal", "Float64"); + typeMapping.put("decimal", "BigDecimal"); typeMapping.put("date", "Time"); typeMapping.put("DateTime", "Time"); typeMapping.put("array", "Array"); @@ -196,6 +197,9 @@ public class CrystalClientCodegen extends DefaultCodegen { cliOptions.add(new CliOption(SHARD_NAME, "shard name (e.g. twitter_client"). defaultValue("openapi_client")); + cliOptions.add(new CliOption(MODULE_NAME, "module name (e.g. TwitterClient"). + defaultValue("OpenAPIClient")); + cliOptions.add(new CliOption(SHARD_VERSION, "shard version.").defaultValue("1.0.0")); cliOptions.add(new CliOption(SHARD_LICENSE, "shard license."). @@ -228,6 +232,11 @@ public class CrystalClientCodegen extends DefaultCodegen { } additionalProperties.put(SHARD_NAME, shardName); + if (additionalProperties.containsKey(MODULE_NAME)) { + setModuleName((String) additionalProperties.get(MODULE_NAME)); + } + additionalProperties.put(MODULE_NAME, moduleName); + if (additionalProperties.containsKey(SHARD_VERSION)) { setShardVersion((String) additionalProperties.get(SHARD_VERSION)); } else { @@ -819,7 +828,7 @@ public class CrystalClientCodegen extends DefaultCodegen { } else if (p.getDefault() instanceof java.time.OffsetDateTime) { return "Time.parse(\"" + String.format(Locale.ROOT, ((java.time.OffsetDateTime) p.getDefault()).atZoneSameInstant(ZoneId.systemDefault()).toString(), "") + "\")"; } else { - return "\"" + escapeText((String) p.getDefault()) + "\""; + return "\"" + escapeText((String.valueOf(p.getDefault()))) + "\""; } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java index 5ddaa48456..60886a15db 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java @@ -304,7 +304,12 @@ public class CsharpNetcoreFunctionsServerCodegen extends AbstractCSharpCodegen { setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID)); } additionalProperties.put("packageGuid", packageGuid); - additionalProperties.put("userSecretsGuid", userSecretsGuid); + + if (!additionalProperties.containsKey("userSecretsGuid")) { + additionalProperties.put("userSecretsGuid", userSecretsGuid); + } else { + userSecretsGuid = (String) additionalProperties.get("userSecretsGuid"); + } if (!additionalProperties.containsKey(NEWTONSOFT_VERSION)) { additionalProperties.put(NEWTONSOFT_VERSION, newtonsoftVersion); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java index b8ec826fd9..711a111be6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java @@ -20,6 +20,7 @@ import com.google.common.collect.Sets; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import io.swagger.v3.oas.models.media.Schema; +import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; import org.openapitools.codegen.api.TemplatePathLocator; @@ -27,6 +28,7 @@ import org.openapitools.codegen.config.GlobalSettings; import org.openapitools.codegen.meta.GeneratorMetadata; import org.openapitools.codegen.meta.Stability; import org.openapitools.codegen.meta.features.ClientModificationFeature; +import org.openapitools.codegen.meta.features.SchemaSupportFeature; import org.openapitools.codegen.model.ModelMap; import org.openapitools.codegen.model.ModelsMap; import org.openapitools.codegen.model.OperationMap; @@ -43,6 +45,7 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.openapitools.codegen.utils.StringUtils.underscore; @@ -78,6 +81,13 @@ public class DartDioClientCodegen extends AbstractDartCodegen { .includeClientModificationFeatures( ClientModificationFeature.Authorizations, ClientModificationFeature.UserAgent + ).includeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism, + SchemaSupportFeature.Union, + SchemaSupportFeature.Composite, + SchemaSupportFeature.allOf, + SchemaSupportFeature.oneOf, + SchemaSupportFeature.anyOf ) ); generatorMetadata = GeneratorMetadata.newBuilder() @@ -150,6 +160,9 @@ public class DartDioClientCodegen extends AbstractDartCodegen { LOGGER.debug("Serialization library not set, using default {}", SERIALIZATION_LIBRARY_DEFAULT); } setLibrary(additionalProperties.get(CodegenConstants.SERIALIZATION_LIBRARY).toString()); + if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library)) { + this.setLegacyDiscriminatorBehavior(false); + } if (!additionalProperties.containsKey(DATE_LIBRARY)) { additionalProperties.put(DATE_LIBRARY, DATE_LIBRARY_DEFAULT); @@ -331,6 +344,213 @@ public class DartDioClientCodegen extends AbstractDartCodegen { return objs; } + /// Gets all ancestors of a given model, and puts it in accumulator + private void getAncestors(CodegenModel cm, Map allModels, Set accumulator) { + + // get direct parents + Set directParentNames = cm.allOf; + if (directParentNames != null && !directParentNames.isEmpty()) { + for (String directParentName : directParentNames) { + if (accumulator.add(directParentName)) { + CodegenModel parent = allModels.get(directParentName); + getAncestors(parent, allModels, accumulator); + } + } + } + } + + private void syncRootTypesWithInnerVars(Map objs) { + Map allModels = new HashMap<>(); + for (ModelsMap modelsEntries : objs.values()) { + for (ModelMap modelsMap : modelsEntries.getModels()) { + CodegenModel model = modelsMap.getModel(); + allModels.put(model.getClassname(), model); + } + } + + for (CodegenModel model : allModels.values()) { + syncRootTypesWithInnerVars(allModels, model); + } + } + private void syncRootTypesWithInnerVars(Map objs, CodegenModel model) { + List allVars = new ArrayList<>(); + allVars.addAll(((Collection) model.vendorExtensions.get(kSelfAndAncestorOnlyProps))); + allVars.addAll(((Collection) model.vendorExtensions.get(kSelfOnlyProps))); + allVars.addAll(((Collection) model.vendorExtensions.get(kAncestorOnlyProps))); + + for (CodegenProperty prop : allVars) { + //check if type exists in parent map + String type = prop.openApiType; + if (objs.containsKey(type)) { + //get the type + CodegenModel relatedModel = objs.get(type); + //fill the property's VendorExtensions with the type's VendorExtensions + prop.getVendorExtensions().put(kIsParent, relatedModel.getVendorExtensions().get(kIsParent)); + prop.isEnum = relatedModel.isEnum; + + } + } + } + private final String kIsChild = "x-is-child"; + private final String kIsParent = "x-is-parent"; + private final String kIsPure = "x-is-pure"; + private final String kSelfOnlyProps = "x-self-only-props"; + private final String kHasSelfOnlyProps = "x-has-self-only-props"; + private final String kAncestorOnlyProps = "x-ancestor-only-props"; + private final String kHasAncestorOnlyProps = "x-has-ancestor-only-props"; + private final String kSelfAndAncestorOnlyProps = "x-self-and-ancestor-only-props"; + private final String kHasSelfAndAncestorOnlyProps = "x-has-self-and-ancestor-only-props"; + + // adapts codegen models and property to dart rules of inheritance + private void adaptToDartInheritance(Map objs) { + // get all models + Map allModels = new HashMap<>(); + for (ModelsMap modelsEntries : objs.values()) { + for (ModelMap modelsMap : modelsEntries.getModels()) { + CodegenModel model = modelsMap.getModel(); + allModels.put(model.getClassname(), model); + } + } + + // all ancestors + Set allAncestorsForAllModelsFlat = new HashSet<>(); + // maps a model to its ancestors + Map> allAncestorsForAllModels = new HashMap<>(); + for (java.util.Map.Entry cm : allModels.entrySet()) { + Set allAncestors = new HashSet<>(); + // get all ancestors + // TODO: optimize this logic ? + getAncestors(cm.getValue(), allModels, allAncestors); + // just in case, a model can't be its own ancestor + allAncestors.remove(cm.getKey()); + + allAncestorsForAllModels.put(cm.getKey(), allAncestors); + allAncestorsForAllModelsFlat.addAll(allAncestors); + } + + + + Set allPureClasses = new HashSet<>(); + // set isChild,isParent,isPure + for (java.util.Map.Entry cmEntry : allModels.entrySet()) { + String key = cmEntry.getKey(); + CodegenModel cm = cmEntry.getValue(); + // get all ancestors + Set allAncestors = allAncestorsForAllModels.get(key); + + // a class is a parent when it's an ancestor to another class + boolean isParent = allAncestorsForAllModelsFlat.contains(key); + // a class is a child when it has any ancestor + boolean isChild = !allAncestors.isEmpty(); + // a class is pure when it's not a child, and has no oneOf nor anyOf + boolean isPure = !isChild && (cm.oneOf == null || cm.oneOf.isEmpty()) + && (cm.anyOf == null || cm.anyOf.isEmpty()); + + cm.vendorExtensions.put(kIsChild, isChild); + cm.vendorExtensions.put(kIsParent, isParent); + cm.vendorExtensions.put(kIsPure, isPure); + // when pure: + // vars = allVars = selfOnlyProperties = kSelfAndAncestorOnlyProps + // ancestorOnlyProps = empty + if (isPure) { + cm.vendorExtensions.put(kSelfOnlyProps, new ArrayList<>(cm.getVars())); + cm.vendorExtensions.put(kHasSelfOnlyProps, !cm.getVars().isEmpty()); + cm.vendorExtensions.put(kAncestorOnlyProps, new ArrayList()); + cm.vendorExtensions.put(kHasAncestorOnlyProps, false); + cm.vendorExtensions.put(kSelfAndAncestorOnlyProps, new ArrayList<>(cm.getVars())); + cm.vendorExtensions.put(kHasSelfAndAncestorOnlyProps, !cm.getVars().isEmpty()); + + allPureClasses.add(key); + } + } + + // handle impure models + for (java.util.Map.Entry cmEntry : allModels.entrySet()) { + String key = cmEntry.getKey(); + CodegenModel cm = cmEntry.getValue(); + if (allPureClasses.contains(key)) { + continue; + } + // get all ancestors + Set allAncestors = allAncestorsForAllModels.get(key); + + // get direct parents + // Set directParentNames = cm.allOf == null ? new HashSet<>() : + // cm.allOf; + Set compositeProperties = new HashSet<>(); + + Set compositeModelNames = new HashSet(); + compositeModelNames.addAll(ObjectUtils.firstNonNull(cm.oneOf, new HashSet<>())); + compositeModelNames.addAll(ObjectUtils.firstNonNull(cm.anyOf, new HashSet<>())); + compositeModelNames.addAll(allAncestors); + + for (String compositeModelName : compositeModelNames) { + CodegenModel model = allModels.get(compositeModelName); + if (model == null) + continue; + List allVars = ObjectUtils.firstNonNull(model.getAllVars(), new ArrayList<>()); + for (CodegenProperty prop : allVars) { + compositeProperties.add(prop.getName()); + } + } + // dart classes declare selfOnlyProperties as direct members (they exist in + // "vars") + // for pure models, this will equal vars + Map selfOnlyProperties = new HashMap<>(); + + // ancestorOnlyProperties are properties defined by all ancestors + // NOTE: oneOf,anyOf are NOT considered ancestors + // since a child in dart must implment ALL OF the parent (using implements) + Map ancestorOnlyProperties = new HashMap<>(); + + // combines both selfOnlyProperties and ancestorOnlyProperties + // this will be used by the custom serializer as "x-handled-vars" and + // "x-has-handled-vars" + Map selfAndAncestorOnlyProperties = new HashMap<>(); + + // STEP 1: calculating selfOnlyProperties + // get all vars of all ancestors and add them to ancestorPropNames + // Set _ancestorPropNames = new HashSet<>(); + for (String ancestorKey : allAncestors) { + CodegenModel ancestorCM = allModels.get(ancestorKey); + for (CodegenProperty prop : ancestorCM.getVars()) { + ancestorOnlyProperties.put(prop.getName(), prop); + } + } + for (CodegenProperty p : cm.getVars()) { + p.isInherited = ancestorOnlyProperties.containsKey(p.getName()); + if (!p.isInherited && !compositeProperties.contains(p.getName())) { + selfOnlyProperties.put(p.getName(), p); + } + } + selfAndAncestorOnlyProperties.putAll(selfOnlyProperties); + selfAndAncestorOnlyProperties.putAll(ancestorOnlyProperties); + + cm.vendorExtensions.put(kSelfOnlyProps, new ArrayList<>(selfOnlyProperties.values())); + cm.vendorExtensions.put(kHasSelfOnlyProps, !selfOnlyProperties.isEmpty()); + cm.vendorExtensions.put(kAncestorOnlyProps, new ArrayList<>(ancestorOnlyProperties.values())); + cm.vendorExtensions.put(kHasAncestorOnlyProps, !ancestorOnlyProperties.isEmpty()); + cm.vendorExtensions.put(kSelfAndAncestorOnlyProps, new ArrayList<>(selfAndAncestorOnlyProperties.values())); + cm.vendorExtensions.put(kHasSelfAndAncestorOnlyProps, !selfAndAncestorOnlyProperties.isEmpty()); + // fixes missing imports + Set interfaceImports = new HashSet(); + interfaceImports.addAll(cm.allOf); + interfaceImports.addAll(cm.oneOf); + interfaceImports.addAll(cm.anyOf); + cm.imports.addAll(rewriteImports(interfaceImports, true)); + } + } + + @Override + public Map postProcessAllModels(Map objs) { + objs = super.postProcessAllModels(objs); + if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library)) { + adaptToDartInheritance(objs); + syncRootTypesWithInnerVars(objs); + } + return objs; + } + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); @@ -361,7 +581,7 @@ public class DartDioClientCodegen extends AbstractDartCodegen { public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { super.postProcessOperationsWithModels(objs, allModels); OperationMap operations = objs.getOperations(); - List operationList = operations.getOperation(); + List operationList = operations.getOperation(); Set resultImports = new HashSet<>(); @@ -403,7 +623,7 @@ public class DartDioClientCodegen extends AbstractDartCodegen { for (CodegenParameter param : op.allParams) { // Generate serializer factories for all container type parameters. // But skip binary and file parameters, JSON serializers don't make sense there. - if (param.isContainer && !(param.isBinary || param.isFile )) { + if (param.isContainer && !(param.isBinary || param.isFile)) { addBuiltValueSerializer(new BuiltValueSerializer( param.isArray, param.uniqueItems, @@ -459,6 +679,14 @@ public class DartDioClientCodegen extends AbstractDartCodegen { private Set rewriteImports(Set originalImports, boolean isModel) { Set resultImports = Sets.newHashSet(); for (String modelImport : originalImports) { + if (modelImport.startsWith("BuiltList", 0)) { + modelImport = "BuiltList"; + } else if (modelImport.startsWith("BuiltSet", 0)) { + modelImport = "BuiltSet"; + } else if (modelImport.startsWith("BuiltMap", 0)) { + modelImport = "BuiltMap"; + } + if (imports.containsKey(modelImport)) { String i = imports.get(modelImport); if (Objects.equals(i, DIO_IMPORT) && !isModel) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java index 1c98aefeaf..e145e4a385 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java @@ -100,6 +100,7 @@ public class GoClientCodegen extends AbstractGoCodegen { apiTemplateFiles.put("api.mustache", ".go"); modelTemplateFiles.put("model.mustache", ".go"); + apiTestTemplateFiles.put("api_test.mustache", ".go"); modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); @@ -304,6 +305,11 @@ public class GoClientCodegen extends AbstractGoCodegen { return outputFolder + File.separator; } + @Override + public String apiTestFileFolder() { + return outputFolder + File.separator + "test" + File.separator; + } + @Override public String apiDocFileFolder() { return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java index cedd19cfaf..c2b5ad4863 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java @@ -918,18 +918,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen List> imports = objs.getImports(); for (ModelMap mo : models) { CodegenModel cm = mo.getModel(); - boolean addImports = false; + boolean addNullableImports = false; for (CodegenProperty var : cm.vars) { - if (this.openApiNullable) { - boolean isOptionalNullable = Boolean.FALSE.equals(var.required) && Boolean.TRUE.equals(var.isNullable); - // only add JsonNullable and related imports to optional and nullable values - addImports |= isOptionalNullable; - var.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable); - findByName(var.name, cm.readOnlyVars) - .ifPresent(p -> p.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable)); - } - + addNullableImports = isAddNullableImports(cm, addNullableImports, var); if (Boolean.TRUE.equals(var.getVendorExtensions().get("x-enum-as-string"))) { // treat enum string as just string var.datatypeWithEnum = var.dataType; @@ -956,17 +948,12 @@ public class JavaClientCodegen extends AbstractJavaCodegen } - if (addImports) { + if (addNullableImports) { Map imports2Classnames = new HashMap<>(); imports2Classnames.put("JsonNullable", "org.openapitools.jackson.nullable.JsonNullable"); imports2Classnames.put("NoSuchElementException", "java.util.NoSuchElementException"); imports2Classnames.put("JsonIgnore", "com.fasterxml.jackson.annotation.JsonIgnore"); - for (Map.Entry entry : imports2Classnames.entrySet()) { - cm.imports.add(entry.getKey()); - Map importsItem = new HashMap<>(); - importsItem.put("import", entry.getValue()); - imports.add(importsItem); - } + addImports(imports, cm, imports2Classnames); } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonClientCodegen.java new file mode 100644 index 0000000000..755a624762 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonClientCodegen.java @@ -0,0 +1,530 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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 java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Function; + +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.servers.Server; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenResponse; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.VendorExtension; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.DocumentationFeature; +import org.openapitools.codegen.meta.features.GlobalFeature; +import org.openapitools.codegen.model.ModelMap; +import org.openapitools.codegen.model.ModelsMap; +import org.openapitools.codegen.model.OperationsMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.openapitools.codegen.CodegenConstants.SERIALIZATION_LIBRARY; + +public class JavaHelidonClientCodegen extends JavaHelidonCommonCodegen { + + private final Logger LOGGER = LoggerFactory.getLogger(JavaHelidonClientCodegen.class); + + private static final String X_HELIDON_REQUIRED_IMPL_IMPORTS = "x-helidon-requiredImplImports"; + private static final String X_HELIDON_IMPL_IMPORTS = "x-helidon-implImports"; + public static final String CONFIG_KEY = "configKey"; + + protected String configKey = null; + protected boolean useBeanValidation = false; + protected boolean performBeanValidation = false; + protected boolean useGzipFeature = false; + protected boolean caseInsensitiveResponseHeaders = false; + protected Path invokerFolder; + protected Path apiFolder; + protected String serializationLibrary = null; + + /** + * Constructor for this generator. Uses the embedded template dir to find common templates + * shared between Helidon client and server generators. + * + * @see org.openapitools.codegen.templating.GeneratorTemplateContentLocator#getFullTemplatePath + */ + public JavaHelidonClientCodegen() { + // beta for now + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + // TODO: Move GlobalFeature.ParameterizedServer to library: jersey after moving featureSet to generatorMetadata + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .includeGlobalFeatures(GlobalFeature.ParameterizedServer) + ); + + outputFolder = "generated-code" + File.separator + "java"; + embeddedTemplateDir = "java-helidon" + File.separator + "common"; // use embedded for common + templateDir = "java-helidon" + File.separator + "client"; + invokerPackage = "org.openapitools.client"; + artifactId = "openapi-java-client"; + apiPackage = invokerPackage + ".api"; + modelPackage = invokerPackage + ".model"; + + updateOption(CodegenConstants.INVOKER_PACKAGE, getInvokerPackage()); + updateOption(CodegenConstants.ARTIFACT_ID, getArtifactId()); + updateOption(CodegenConstants.API_PACKAGE, apiPackage); + updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage); + + modelTestTemplateFiles.put("model_test.mustache", ".java"); + + cliOptions.add(CliOption.newString(CONFIG_KEY, "Config key in @RegisterRestClient. Default to none.")); + + supportedLibraries.put(HELIDON_MP, "Helidon MP Client"); + supportedLibraries.put(HELIDON_SE, "Helidon SE Client"); + + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, + "library template (sub-template) to use"); + libraryOption.setEnum(supportedLibraries); + libraryOption.setDefault(HELIDON_MP); + cliOptions.add(libraryOption); + setLibrary(HELIDON_MP); // default + + CliOption serializationLibrary = new CliOption(SERIALIZATION_LIBRARY, + "Serialization library, defaults to Jackson"); + Map serializationOptions = new HashMap<>(); + serializationOptions.put(SERIALIZATION_LIBRARY_JACKSON, "Use Jackson as serialization library"); + serializationOptions.put(SERIALIZATION_LIBRARY_JSONB, "Use JSON-B as serialization library"); + serializationLibrary.setEnum(serializationOptions); + cliOptions.add(serializationLibrary); + setSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); // default + + removeUnusedOptions(); + + // Ensure the OAS 3.x discriminator mappings include any descendent schemas that allOf + // inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, + // and the discriminator mapping schemas in the OAS document. + this.setLegacyDiscriminatorBehavior(false); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "java-helidon-client"; + } + + @Override + public String getHelp() { + return "Generates a Helidon MP or SE client"; + } + + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, + Map> operations) { + super.addOperationToGroup(tag, resourcePath, operation, co, operations); + if (HELIDON_MP.equals(getLibrary())) { + co.subresourceOperation = !co.path.isEmpty(); + } + } + + @Override + public String apiFilename(String templateName, String tag) { + if (templateName.contains("_impl")) { + String suffix = apiTemplateFiles().get(templateName); + return apiFileFolder() + File.separator + toApiFilename(tag) + "Impl" + suffix; + } + return super.apiFilename(templateName, tag); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(SERIALIZATION_LIBRARY)) { + setSerializationLibrary(additionalProperties.get(SERIALIZATION_LIBRARY).toString()); + } + + if (additionalProperties.containsKey(CONFIG_KEY)) { + setConfigKey(additionalProperties.get(CONFIG_KEY).toString()); + } + + String invokerPath = invokerPackage.replace('.', File.separatorChar); + invokerFolder = Paths.get(sourceFolder, invokerPath); + apiFolder = Paths.get(outputFolder).relativize(Paths.get(apiFileFolder())); + + if (isLibrary(HELIDON_MP)) { + String apiExceptionFolder = Paths.get(sourceFolder, + apiPackage().replace('.', File.separatorChar)).toString(); + + List modifiable = new ArrayList<>(); + modifiable.add(new SupportingFile("pom.mustache", "", "pom.xml")); + modifiable.add(new SupportingFile("README.mustache", "", "README.md")); + List unmodifiable = new ArrayList<>(); + unmodifiable.add(new SupportingFile("api_exception.mustache", apiExceptionFolder, "ApiException.java")); + unmodifiable.add(new SupportingFile("api_exception_mapper.mustache", apiExceptionFolder, "ApiExceptionMapper.java")); + if (additionalProperties.containsKey("jsr310")) { + unmodifiable.add(new SupportingFile("JavaTimeFormatter.mustache", + invokerFolder.toString(), "JavaTimeFormatter.java")); + } + processSupportingFiles(modifiable, unmodifiable); + } else if (isLibrary(HELIDON_SE)) { + apiTemplateFiles.put("api_impl.mustache", ".java"); + importMapping.put("StringJoiner", "java.util.StringJoiner"); + importMapping.put("WebClientRequestHeaders", "io.helidon.webclient.WebClientRequestHeaders"); + importMapping.put("Pair", invokerPackage + ".Pair"); + + + List modifiable = new ArrayList<>(); + modifiable.add(new SupportingFile("pom.mustache", "", "pom.xml")); + modifiable.add(new SupportingFile("README.mustache", "", "README.md")); + + List unmodifiable = new ArrayList<>(); + unmodifiable.add(new SupportingFile("ApiResponse.mustache", invokerFolder.toString(), "ApiResponse.java")); + unmodifiable.add(new SupportingFile("ApiResponseBase.mustache", invokerFolder.toString(), "ApiResponseBase.java")); + unmodifiable.add(new SupportingFile("ApiClient.mustache", invokerFolder.toString(), "ApiClient.java")); + unmodifiable.add(new SupportingFile("Pair.mustache", invokerFolder.toString(), "Pair.java")); + unmodifiable.add(new SupportingFile("ResponseType.mustache", apiFolder.toString(), "ResponseType.java")); + + processSupportingFiles(modifiable, unmodifiable); + } + else { + LOGGER.error("Unknown library option (-l/--library): {}", getLibrary()); + } + + if (getSerializationLibrary() == null) { + LOGGER.info("No serializationLibrary configured, using '{}' as fallback", SERIALIZATION_LIBRARY_JACKSON); + setSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); + } + switch (getSerializationLibrary()) { + case SERIALIZATION_LIBRARY_JACKSON: + additionalProperties.put(SERIALIZATION_LIBRARY_JACKSON, "true"); + additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder.toString(), "RFC3339DateFormat.java")); + break; + case SERIALIZATION_LIBRARY_JSONB: + openApiNullable = false; // for Jackson only + additionalProperties.put(SERIALIZATION_LIBRARY_JSONB, "true"); + additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON); + break; + default: + additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON); + additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB); + LOGGER.error("Unknown serialization library option"); + break; + } + } + + /** + * Check if pom file and src directory already exist. + * + * @return outcome of test + */ + @Override + protected boolean projectFilesExist() { + Path projectFolder = Paths.get(getOutputTestFolder()); + Path pom = projectFolder.resolve("pom.xml"); + Path src = projectFolder.resolve(invokerFolder); + return pom.toFile().exists() && src.toFile().exists(); + } + + @Override + public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { + if (isLibrary(HELIDON_MP)) { + super.postProcessOperationsWithModels(objs, allModels); + return AbstractJavaJAXRSServerCodegen.jaxrsPostProcessOperations(objs); + } else { + // Compute the imports to declare in the generated API impl class. + List> imports = objs.getImports(); + List> implImports = new ArrayList<>(imports); + + Set requiredImplImportClassNames = new HashSet<>(); + for (CodegenOperation op : objs.getOperations().getOperation()) { + requiredImplImportClassNames.addAll((Set) op.vendorExtensions.get(X_HELIDON_REQUIRED_IMPL_IMPORTS)); + } + + Set missingImportClassNames = new TreeSet<>(requiredImplImportClassNames); + imports.stream() + .map(m -> m.get("classname")) + .forEach(missingImportClassNames::remove); + + missingImportClassNames.forEach(c -> { + Map singleImportMap = new HashMap<>(); + singleImportMap.put("classname", c); + singleImportMap.put("import", Objects.requireNonNull(importMapping.get(c), "no mapping for " + c)); + implImports.add(singleImportMap); + }); + + objs.put(X_HELIDON_IMPL_IMPORTS, implImports); + return objs; + } + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); + // We use two templates, one for the API interface and one for the impl class. + // Add to the normal imports for this operation only those imports used in both + // the API and the impl. Create a vendor extension on the operation to record the + // additional imports needed for the implementation class. + Set requiredImplImports = new TreeSet<>(); + if (op.isArray) { + op.imports.add("List"); + } + if (op.isMap) { + op.imports.add("Map"); + } + if (op.getHasQueryParams()) { + requiredImplImports.add("List"); + requiredImplImports.add("ArrayList"); + requiredImplImports.add("Pair"); + } + if (op.getHasHeaderParams()) { + requiredImplImports.add("WebClientRequestHeaders"); + } + if (op.getHasFormParams()) { + requiredImplImports.add("StringJoiner"); + } + if (op.getHasCookieParams()) { + requiredImplImports.add("StringJoiner"); + } + if (op.bodyParams.stream().anyMatch(JavaHelidonClientCodegen::checkIsArray) + || op.allParams.stream().anyMatch(JavaHelidonClientCodegen::checkIsArray) + || op.responses.stream().anyMatch(CodegenResponse::getIsArray)) { + requiredImplImports.add("List"); + op.imports.add("List"); + } + if (op.bodyParams.stream().anyMatch(JavaHelidonClientCodegen::checkIsMap) + || op.allParams.stream().anyMatch(JavaHelidonClientCodegen::checkIsMap) + || op.responses.stream().anyMatch(CodegenResponse::getIsMap)) { + requiredImplImports.add("Map"); + op.imports.add("Map"); + } + + op.vendorExtensions.put(X_HELIDON_REQUIRED_IMPL_IMPORTS, requiredImplImports); + return op; + } + + private static boolean checkIsArray(CodegenParameter p) { + return p.isArray || !(p.getSchema() != null && p.getSchema().getIsArray()); + } + + private static boolean checkIsMap(CodegenParameter p) { + return p.isMap || !(p.getSchema() != null && p.getSchema().getIsMap()); + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + + if (!BooleanUtils.toBoolean(model.isEnum) + && additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON)) { + model.imports.add("JsonProperty"); + model.imports.add("JsonValue"); + model.imports.add("JsonInclude"); + model.imports.add("JsonTypeName"); + } else if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON)) { + model.imports.add("JsonValue"); + model.imports.add("JsonCreator"); + } + + if (HELIDON_MP.equals(getLibrary())) { + model.imports.remove("ApiModelProperty"); + model.imports.remove("ApiModel"); + model.imports.remove("JsonSerialize"); + model.imports.remove("ToStringSerializer"); + } else if (HELIDON_SE.equals(getLibrary())) { + // TODO check for SE-specifics + model.imports.remove("ApiModelProperty"); + model.imports.remove("ApiModel"); + model.imports.remove("JsonSerialize"); + model.imports.remove("ToStringSerializer"); + } + + if ("set".equals(property.containerType) && !JACKSON.equals(serializationLibrary)) { + // clean-up + model.imports.remove("JsonDeserialize"); + property.vendorExtensions.remove("x-setter-extra-annotation"); + } + } + + @Override + public CodegenModel fromModel(String name, Schema model) { + CodegenModel codegenModel = super.fromModel(name, model); + if (isLibrary(HELIDON_MP)) { + if (codegenModel.imports.contains("ApiModel")) { + // Remove io.swagger.annotations.ApiModel import + codegenModel.imports.remove("ApiModel"); + } + } else if (isLibrary(HELIDON_SE)) { + if (codegenModel.imports.contains("ApiModel")) { + // Remove io.swagger.annotations.ApiModel import + codegenModel.imports.remove("ApiModel"); + } + } + return codegenModel; + } + + @SuppressWarnings("unchecked") + @Override + public ModelsMap postProcessModels(ModelsMap objs) { + objs = super.postProcessModels(objs); + List models = objs.getModels(); + + if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON)) { + List> imports = objs.getImports(); + for (ModelMap mo : models) { + CodegenModel cm = mo.getModel(); + boolean addImports = false; + + for (CodegenProperty var : cm.vars) { + if (this.openApiNullable) { + boolean isOptionalNullable = Boolean.FALSE.equals(var.required) && Boolean.TRUE.equals(var.isNullable); + // only add JsonNullable and related imports to optional and nullable values + addImports |= isOptionalNullable; + var.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable); + } + + if (Boolean.TRUE.equals(var.getVendorExtensions().get("x-enum-as-string"))) { + // treat enum string as just string + var.datatypeWithEnum = var.dataType; + + if (StringUtils.isNotEmpty(var.defaultValue)) { // has default value + String defaultValue = var.defaultValue.substring(var.defaultValue.lastIndexOf('.') + 1); + for (Map enumVars : (List>) var.getAllowableValues().get("enumVars")) { + if (defaultValue.equals(enumVars.get("name"))) { + // update default to use the string directly instead of enum string + var.defaultValue = (String) enumVars.get("value"); + } + } + } + + // add import for Set, HashSet + cm.imports.add("Set"); + Map importsSet = new HashMap<>(); + importsSet.put("import", "java.util.Set"); + imports.add(importsSet); + Map importsHashSet = new HashMap<>(); + importsHashSet.put("import", "java.util.HashSet"); + imports.add(importsHashSet); + } + + } + + if (addImports) { + Map imports2Classnames = new HashMap<>(); + imports2Classnames.put("JsonNullable", "org.openapitools.jackson.nullable.JsonNullable"); + imports2Classnames.put("NoSuchElementException", "java.util.NoSuchElementException"); + imports2Classnames.put("JsonIgnore", "com.fasterxml.jackson.annotation.JsonIgnore"); + for (Map.Entry entry : imports2Classnames.entrySet()) { + cm.imports.add(entry.getKey()); + Map importsItem = new HashMap<>(); + importsItem.put("import", entry.getValue()); + imports.add(importsItem); + } + } + } + } + + return objs; + } + + public void setConfigKey(String configKey) { + this.configKey = configKey; + } + + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } + + public void setPerformBeanValidation(boolean performBeanValidation) { + this.performBeanValidation = performBeanValidation; + } + + public void setUseGzipFeature(boolean useGzipFeature) { + this.useGzipFeature = useGzipFeature; + } + + public void setCaseInsensitiveResponseHeaders(final Boolean caseInsensitiveResponseHeaders) { + this.caseInsensitiveResponseHeaders = caseInsensitiveResponseHeaders; + } + + public String getSerializationLibrary() { + return serializationLibrary; + } + + public void setSerializationLibrary(String serializationLibrary) { + if (SERIALIZATION_LIBRARY_JACKSON.equalsIgnoreCase(serializationLibrary)) { + this.serializationLibrary = SERIALIZATION_LIBRARY_JACKSON; + } else if (SERIALIZATION_LIBRARY_JSONB.equalsIgnoreCase(serializationLibrary)) { + this.serializationLibrary = SERIALIZATION_LIBRARY_JSONB; + } else { + throw new IllegalArgumentException("Unexpected serializationLibrary value: " + serializationLibrary); + } + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + generateYAMLSpecFile(objs); + return super.postProcessSupportingFileData(objs); + } + + @Override + public String toApiVarName(String name) { + String apiVarName = super.toApiVarName(name); + if (reservedWords.contains(apiVarName)) { + apiVarName = escapeReservedWord(apiVarName); + } + return apiVarName; + } + + @Override + public void addImportsToOneOfInterface(List> imports) { + for (String i : Arrays.asList("JsonSubTypes", "JsonTypeInfo", "JsonIgnoreProperties")) { + Map oneImport = new HashMap<>(); + oneImport.put("import", importMapping.get(i)); + if (!imports.contains(oneImport)) { + imports.add(oneImport); + } + } + } + + @Override + public List getSupportedVendorExtensions() { + List extensions = super.getSupportedVendorExtensions(); + extensions.add(VendorExtension.X_WEBCLIENT_BLOCKING); + return extensions; + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonCommonCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonCommonCodegen.java new file mode 100644 index 0000000000..ac87b1006b --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonCommonCodegen.java @@ -0,0 +1,326 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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 java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.servers.Server; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.languages.features.BeanValidationFeatures; +import org.openapitools.codegen.languages.features.PerformBeanValidationFeatures; + +import static org.openapitools.codegen.CodegenConstants.DEVELOPER_EMAIL; +import static org.openapitools.codegen.CodegenConstants.DEVELOPER_NAME; +import static org.openapitools.codegen.CodegenConstants.DEVELOPER_ORGANIZATION; +import static org.openapitools.codegen.CodegenConstants.DEVELOPER_ORGANIZATION_URL; +import static org.openapitools.codegen.CodegenConstants.PARENT_ARTIFACT_ID; +import static org.openapitools.codegen.CodegenConstants.PARENT_GROUP_ID; +import static org.openapitools.codegen.CodegenConstants.PARENT_VERSION; +import static org.openapitools.codegen.CodegenConstants.SCM_CONNECTION; +import static org.openapitools.codegen.CodegenConstants.SCM_DEVELOPER_CONNECTION; +import static org.openapitools.codegen.CodegenConstants.SCM_URL; + +public abstract class JavaHelidonCommonCodegen extends AbstractJavaCodegen + implements BeanValidationFeatures, PerformBeanValidationFeatures { + + static final String HELIDON_MP = "mp"; + static final String HELIDON_SE = "se"; + + static final String HELIDON_NIMA = "nima"; + static final String HELIDON_NIMA_ANNOTATIONS = "nima-annotations"; + + static final String MICROPROFILE_ROOT_PACKAGE = "rootJavaEEPackage"; + static final String MICROPROFILE_ROOT_DEP_PREFIX = "x-helidon-rootJavaEEDepPrefix"; + static final String X_HAS_RETURN_TYPE = "x-helidon-hasReturnType"; + static final String X_RETURN_TYPE_EXAMPLE_VALUE = "x-helidon-exampleReturnTypeValue"; + static final String MICROPROFILE_ROOT_PACKAGE_DESC = "Root package name for Java EE"; + static final String MICROPROFILE_ROOT_PACKAGE_JAVAX = "javax"; + static final String MICROPROFILE_ROOT_PACKAGE_JAKARTA = "jakarta"; + private static final String VALIDATION_ARTIFACT_PREFIX_KEY = "x-helidon-validationArtifactPrefix"; + private static final String VALIDATION_ARTIFACT_PREFIX_JAVAX = ""; + private static final String VALIDATION_ARTIFACT_PREFIX_JAKARTA = MICROPROFILE_ROOT_PACKAGE_JAKARTA + "."; + + private static final Map EXAMPLE_RETURN_VALUES = new HashMap() { + { + put("set", "Set"); + put("array", "List"); + put("map", "Map"); + } + }; + + // for generated doc + static final String MICROPROFILE_ROOT_PACKAGE_DEFAULT = + "Helidon 2.x and earlier: " + MICROPROFILE_ROOT_PACKAGE_JAVAX + + "; Helidon 3.x and later: " + MICROPROFILE_ROOT_PACKAGE_JAKARTA; + + static final String SERIALIZATION_LIBRARY_JACKSON = "jackson"; + static final String SERIALIZATION_LIBRARY_JSONB = "jsonb"; + + public static final String HELIDON_VERSION = "helidonVersion"; + public static final String DEFAULT_HELIDON_VERSION = "3.0.1"; + static final String HELIDON_VERSION_DESC = "Helidon version for generated code"; + + static final String FULL_PROJECT = "fullProject"; + static final String FULL_PROJECT_DESC = "If set to true, it will generate all files; if set to false, " + + "it will only generate API files. If unspecified, the behavior depends on whether a project " + + "exists or not: if it does not, same as true; if it does, same as false. Note that test files " + + "are never overwritten."; + + private String helidonVersion; + private String rootJavaEEPackage; + private String rootJavaEEDepPrefix; + + public JavaHelidonCommonCodegen() { + super(); + cliOptions.add(new CliOption(HELIDON_VERSION, HELIDON_VERSION_DESC) + .defaultValue(DEFAULT_HELIDON_VERSION)); + cliOptions.add(new CliOption(MICROPROFILE_ROOT_PACKAGE, MICROPROFILE_ROOT_PACKAGE_DESC) + .defaultValue(MICROPROFILE_ROOT_PACKAGE_DEFAULT)); + cliOptions.add(new CliOption(FULL_PROJECT, FULL_PROJECT_DESC) + .defaultValue("")); // depends on project state + } + + @Override + public void processOpts() { + super.processOpts(); + + String userHelidonVersion = ""; + String userParentVersion = ""; + + if (additionalProperties.containsKey(CodegenConstants.PARENT_VERSION)) { + userParentVersion = additionalProperties.get(CodegenConstants.PARENT_VERSION).toString(); + } + + if (additionalProperties.containsKey(HELIDON_VERSION)) { + userHelidonVersion = additionalProperties.get(HELIDON_VERSION).toString(); + } + + if (!userHelidonVersion.isEmpty()) { + if (!userParentVersion.isEmpty() && !userHelidonVersion.equals(userParentVersion)) { + throw new IllegalArgumentException( + String.format(Locale.ROOT, + "Both %s and %s properties were set with different value.", + CodegenConstants.PARENT_VERSION, + HELIDON_VERSION)); + } + setHelidonVersion(userHelidonVersion); + } else if (!userParentVersion.isEmpty()) { + setHelidonVersion(userParentVersion); + } else { + setHelidonVersion(DEFAULT_HELIDON_VERSION); + } + + additionalProperties.put(HELIDON_VERSION, helidonVersion); + setEEPackageAndDependencies(helidonVersion); + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); + op.vendorExtensions.put(X_HAS_RETURN_TYPE, op.returnType != null && !op.returnType.equals("void")); + op.vendorExtensions.put(X_RETURN_TYPE_EXAMPLE_VALUE, chooseExampleReturnTypeValue(op)); + return op; + } + + /** + * Remove set of options not currently used by any Helidon generator. Should be + * called during construction but only on leaf classes. + */ + protected void removeUnusedOptions() { + removeCliOptions(SCM_CONNECTION, + SCM_DEVELOPER_CONNECTION, + SCM_URL, + DEVELOPER_NAME, + DEVELOPER_ORGANIZATION, + DEVELOPER_ORGANIZATION_URL, + DEVELOPER_EMAIL, + PARENT_ARTIFACT_ID, + PARENT_VERSION, + PARENT_GROUP_ID, + DISABLE_HTML_ESCAPING); + } + + /** + * Determine whether to generate or overwrite files depending on fullProject property. + * If property is unspecified, then check if sources are already there and avoid overwriting + * modifiable files. + * + * @param modifiable list of modifiable files to be processed + * @param unmodifiable list of unmodifiable files to be processed + */ + protected void processSupportingFiles(List modifiable, List unmodifiable) { + Boolean fullProject = !additionalProperties.containsKey(FULL_PROJECT) ? null : + Boolean.parseBoolean(additionalProperties.get(FULL_PROJECT).toString()); + + if (fullProject == null && !projectFilesExist()) { // not explicitly set + supportingFiles.addAll(modifiable); + } else if (Boolean.TRUE.equals(fullProject)) { // explicitly set to true + supportingFiles.addAll(modifiable); + } + supportingFiles.addAll(unmodifiable); + } + + /** + * Check if project is already generated to determine default for the fullProject + * flag. Can be overridden in subclasses to strengthen test condition. + * + * @return outcome of test + */ + protected boolean projectFilesExist() { + return Paths.get(getOutputTestFolder()).toFile().exists(); + } + + protected String rootJavaEEPackage() { + return rootJavaEEPackage; + } + + private void setHelidonVersion(String version) { + helidonVersion = version; + setParentVersion(version); + } + + private void setEEPackageAndDependencies(String version) { + + rootJavaEEPackage = checkAndSelectRootEEPackage(version); + additionalProperties.put(MICROPROFILE_ROOT_PACKAGE, rootJavaEEPackage); + + rootJavaEEDepPrefix = checkAndSelectRootEEDepPrefix(version); + additionalProperties.put(MICROPROFILE_ROOT_DEP_PREFIX, rootJavaEEDepPrefix); + + additionalProperties.put(VALIDATION_ARTIFACT_PREFIX_KEY, + rootJavaEEDepPrefix.equals(MICROPROFILE_ROOT_PACKAGE_JAVAX) + ? VALIDATION_ARTIFACT_PREFIX_JAVAX + : VALIDATION_ARTIFACT_PREFIX_JAKARTA); + } + + private String checkAndSelectRootEEPackage(String version) { + String packagePrefixImpliedByVersion = usesJakartaPackages(version) + ? MICROPROFILE_ROOT_PACKAGE_JAKARTA + : MICROPROFILE_ROOT_PACKAGE_JAVAX; + + // Make sure any user-specified root EE package is correct for the chosen Helidon version. + if (additionalProperties.containsKey(MICROPROFILE_ROOT_PACKAGE)) { + String userRootEEPackage = additionalProperties.get(MICROPROFILE_ROOT_PACKAGE).toString(); + if (!packagePrefixImpliedByVersion.equals(userRootEEPackage)) { + throw new IllegalArgumentException( + String.format(Locale.ROOT, + "Helidon version %s uses the %s namespace but options specified '%s'", + version, + packagePrefixImpliedByVersion, + userRootEEPackage)); + } + return userRootEEPackage; + } + + // No explicit setting for the root EE package. + return packagePrefixImpliedByVersion; + } + + private String checkAndSelectRootEEDepPrefix(String version) { + String mavenDepPrefixImpliedByVersion = usesJakartaPrefix(version) + ? MICROPROFILE_ROOT_PACKAGE_JAKARTA + : MICROPROFILE_ROOT_PACKAGE_JAVAX; + + // Make sure any user-specified prefix is correct for the chosen Helidon version. + if (additionalProperties.containsKey(MICROPROFILE_ROOT_DEP_PREFIX)) { + String userMavenDepPrefix = additionalProperties.get(MICROPROFILE_ROOT_DEP_PREFIX).toString(); + if (!mavenDepPrefixImpliedByVersion.equals(userMavenDepPrefix)) { + throw new IllegalArgumentException( + String.format(Locale.ROOT, + "Helidon version %s uses the %s prefix for EE dependencies but options specified '%s'", + version, + mavenDepPrefixImpliedByVersion, + userMavenDepPrefix)); + } + return userMavenDepPrefix; + } + + // No explicit setting for the dependency prefix. + return mavenDepPrefixImpliedByVersion; + } + + private boolean usesJakartaPackages(String version) { + return !version.startsWith("2.") && !version.startsWith("1."); + } + + private boolean usesJakartaPrefix(String version) { + return !version.startsWith("1."); + } + + protected void removeCliOptions(String... opt) { + List opts = Arrays.asList(opt); + Set forRemoval = cliOptions.stream() + .filter(cliOption -> opts.contains(cliOption.getOpt())) + .collect(Collectors.toSet()); + forRemoval.forEach(cliOptions::remove); + } + + private String chooseExampleReturnTypeValue(CodegenOperation op) { + + + // See DefaultCodegen#handleMethodResponse to see how the various op fields related to the return type are set. + if (op.returnType == null) { + return ""; // won't be used anyway in the templates + } + if (op.returnContainer != null) { + return "java.util.Collections.empty" + EXAMPLE_RETURN_VALUES.get(op.returnContainer) + "()"; + } + switch (op.returnType) { + case "Integer": + return "new Integer(0)"; + + case "byte[]": + return "new byte[0]"; + + case "Float": + return "new Float(0.0f)"; + + case "boolean": + return "false"; + + case "Long": + return "new Long(0L)"; + + case "Object": + return "new Object()"; + + case "String": + return "\"\""; + + case "Boolean": + return "new Boolean(false)"; + + case "Double": + return "new Double(0.0d)"; + + default: + return "null"; + } + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonServerCodegen.java new file mode 100644 index 0000000000..852ccbab4b --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonServerCodegen.java @@ -0,0 +1,420 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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 java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.servers.Server; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.DocumentationFeature; +import org.openapitools.codegen.model.ModelMap; +import org.openapitools.codegen.model.OperationMap; +import org.openapitools.codegen.model.OperationsMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.openapitools.codegen.utils.StringUtils.camelize; + +public class JavaHelidonServerCodegen extends JavaHelidonCommonCodegen { + + private final Logger LOGGER = LoggerFactory.getLogger(JavaHelidonServerCodegen.class); + + public static final String USE_ABSTRACT_CLASS = "useAbstractClass"; + public static final String GRADLE_PROJECT = "gradleProject"; + + protected boolean useBeanValidation = true; + protected String implFolder = "src/main/java"; + protected String serializationLibrary = null; + + private boolean useAbstractClass = false; + private boolean gradleProject = false; + + public JavaHelidonServerCodegen() { + super(); + // beta for now + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); + + outputFolder = "generated-code" + File.separator + "java"; + embeddedTemplateDir = templateDir = "java-helidon" + File.separator + "server"; + invokerPackage = "org.openapitools.server"; + artifactId = "openapi-java-server"; + apiPackage = invokerPackage + ".api"; + modelPackage = invokerPackage + ".model"; + sourceFolder = "src" + File.separator + "main" + File.separator + "java"; + + // clioOptions default redefinition need to be updated + updateOption(CodegenConstants.INVOKER_PACKAGE, this.getInvokerPackage()); + updateOption(CodegenConstants.ARTIFACT_ID, this.getArtifactId()); + updateOption(CodegenConstants.API_PACKAGE, apiPackage); + updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage); + + modelTestTemplateFiles.put("model_test.mustache", ".java"); + + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use Bean Validation")); + cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Perform BeanValidation")); + cliOptions.add(CliOption.newBoolean(USE_ABSTRACT_CLASS, + "Whether to generate abstract classes for REST API instead of interfaces.", useAbstractClass)); + cliOptions.add(CliOption.newBoolean(GRADLE_PROJECT, + "Whether to generate gradle project instead of maven.", gradleProject)); + + // clear model and api doc template as this codegen + // does not support auto-generated markdown doc at the moment + modelDocTemplateFiles.remove("model_doc.mustache"); + apiDocTemplateFiles.remove("api_doc.mustache"); + + // clear test templates + // as this codegen does not support api tests at the moment + apiTestTemplateFiles.clear(); + + supportedLibraries.put(HELIDON_MP, "Helidon MP Server"); + supportedLibraries.put(HELIDON_SE, "Helidon SE Server"); + supportedLibraries.put(HELIDON_NIMA, "Helidon NIMA Server"); + supportedLibraries.put(HELIDON_NIMA_ANNOTATIONS, "Helidon NIMA Annotations Server"); + + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + libraryOption.setEnum(supportedLibraries); + libraryOption.setDefault(HELIDON_SE); + cliOptions.add(libraryOption); + setLibrary(HELIDON_SE); + + CliOption serializationLibrary = new CliOption(CodegenConstants.SERIALIZATION_LIBRARY, + "Serialization library, defaults to Jackson"); + Map serializationOptions = new HashMap<>(); + serializationOptions.put(SERIALIZATION_LIBRARY_JACKSON, "Use Jackson as serialization library"); + serializationOptions.put(SERIALIZATION_LIBRARY_JSONB, "Use JSON-B as serialization library"); + serializationLibrary.setEnum(serializationOptions); + cliOptions.add(serializationLibrary); + setSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); + + removeUnusedOptions(); + + this.setLegacyDiscriminatorBehavior(false); + } + + @Override + public void processOpts() { + super.processOpts(); + supportingFiles.clear(); + dateLibrary = "java8"; + + addApiTemplateFiles(); + SupportingFile pomFile = new SupportingFile("pom.mustache", "", "pom.xml"); + SupportingFile readmeFile = new SupportingFile("README.mustache", "", "README.md"); + SupportingFile openApiFile = new SupportingFile("openapi.mustache", + ("src/main/resources/META-INF").replace("/", File.separator), "openapi.yml"); + SupportingFile logFile = new SupportingFile("logging.mustache", + ("src.main.resources").replace(".", File.separator), "logging.properties"); + SupportingFile packageInfoFile = new SupportingFile("package-info.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), + "package-info.java"); + List modifiable = new ArrayList<>(); + modifiable.add(pomFile); + modifiable.add(readmeFile); + modifiable.add(logFile); + modifiable.add(packageInfoFile); + List unmodifiable = new ArrayList<>(); + unmodifiable.add(openApiFile); + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + } + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + + importMapping.put("ObjectMapper", "com.fasterxml.jackson.databind.ObjectMapper"); + importMapping.put("Jsonb", rootJavaEEPackage() + ".json.bind.Jsonb"); + importMapping.put("JsonbBuilder", rootJavaEEPackage() + ".json.bind.JsonbBuilder"); + + if (additionalProperties.containsKey(USE_ABSTRACT_CLASS)) { + useAbstractClass = Boolean.parseBoolean(additionalProperties.get(USE_ABSTRACT_CLASS).toString()); + } + if (!useAbstractClass) { + additionalProperties.remove(USE_ABSTRACT_CLASS); + } + + if (additionalProperties.containsKey(GRADLE_PROJECT)) { + gradleProject = Boolean.parseBoolean(additionalProperties.get(GRADLE_PROJECT).toString()); + } + if (!gradleProject) { + additionalProperties.remove(GRADLE_PROJECT); + } else { + modifiable.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + modifiable.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + modifiable.remove(pomFile); + } + + if (additionalProperties.containsKey(CodegenConstants.SERIALIZATION_LIBRARY)) { + setSerializationLibrary(additionalProperties.get(CodegenConstants.SERIALIZATION_LIBRARY).toString()); + } + + String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); + + if (additionalProperties.containsKey("jsr310") && isLibrary(HELIDON_MP)) { + supportingFiles.add(new SupportingFile("JavaTimeFormatter.mustache", invokerFolder, "JavaTimeFormatter.java")); + } + + if (isLibrary(HELIDON_MP)) { + String resourceFolder = "src" + File.separator + "main" + File.separator + "resources"; + String metaInfFolder = resourceFolder + File.separator + "META-INF"; + supportingFiles.add(new SupportingFile("RestApplication.mustache", invokerFolder, "RestApplication.java")); + supportingFiles.add(new SupportingFile("microprofile-config.properties.mustache", metaInfFolder, "microprofile" + + "-config.properties")); + supportingFiles.add(new SupportingFile("beans.xml.mustache", metaInfFolder, "beans.xml")); + processSupportingFiles(modifiable, unmodifiable); + } else if (isLibrary(HELIDON_SE)) { + artifactId = "openapi-helidon-se-server"; + + modifiable.add(new SupportingFile("application.mustache", + ("src.main.resources").replace(".", java.io.File.separator), "application.yaml")); + modifiable.add(new SupportingFile("mainTest.mustache", + (testFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), + "MainTest.java")); + modifiable.add(new SupportingFile("main.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), + "Main.java")); + unmodifiable.add(new SupportingFile("validatorUtils.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), + "ValidatorUtils.java")); + if (useAbstractClass) { + importMapping.put("Map", "java.util.Map"); + importMapping.put("HashMap", "java.util.HashMap"); + importMapping.put("InputStream", "java.io.InputStream"); + importMapping.put("ReadableBodyPart", "io.helidon.media.multipart.ReadableBodyPart"); + importMapping.put("ArrayList", "java.util.ArrayList"); + importMapping.put("ByteArrayOutputStream", "java.io.ByteArrayOutputStream"); + importMapping.put("DataChunk", "io.helidon.common.http.DataChunk"); + importMapping.put("UncheckedIOException", "java.io.UncheckedIOException"); + importMapping.put("IOException", "java.io.IOException"); + importMapping.put("ByteArrayInputStream", "java.io.ByteArrayInputStream"); + } + importMapping.put("Handler", "io.helidon.webserver.Handler"); + processSupportingFiles(modifiable, unmodifiable); + } else if (isLibrary(HELIDON_NIMA)) { + throw new UnsupportedOperationException("Not implemented"); + } else if (isLibrary(HELIDON_NIMA_ANNOTATIONS)) { + throw new UnsupportedOperationException("Not implemented"); + } else { + LOGGER.error("Unknown library option (-l/--library): {}", getLibrary()); + throw new IllegalArgumentException( + String.format(Locale.ROOT, + "Unknown library option %s for Helidon Server", + getLibrary() + ) + ); + } + + if (getSerializationLibrary() == null) { + LOGGER.info("No serializationLibrary configured, using '{}' as fallback", SERIALIZATION_LIBRARY_JACKSON); + setSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); + } + switch (getSerializationLibrary()) { + case SERIALIZATION_LIBRARY_JACKSON: + additionalProperties.put(SERIALIZATION_LIBRARY_JACKSON, "true"); + additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB); + supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java")); + if (isLibrary(HELIDON_SE)) { + supportingFiles.add(new SupportingFile("jsonProvider.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), + "JsonProvider.java")); + } + break; + case SERIALIZATION_LIBRARY_JSONB: + additionalProperties.put(SERIALIZATION_LIBRARY_JSONB, "true"); + additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON); + break; + default: + additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON); + additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB); + LOGGER.error("Unknown serialization library option"); + break; + } + } + + private void addApiTemplateFiles() { + Boolean fullProject = !additionalProperties.containsKey(FULL_PROJECT) ? null : + Boolean.parseBoolean(additionalProperties.get(FULL_PROJECT).toString()); + if (fullProject == null && !projectFilesExist()) { + apiTemplateFiles.put("apiImpl.mustache", "Impl.java"); + } else if (Boolean.TRUE.equals(fullProject)) { + apiTemplateFiles.put("apiImpl.mustache", "Impl.java"); + } + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { + CodegenOperation codegenOperation = super.fromOperation(path, httpMethod, operation, servers); + if (HELIDON_SE.equals(getLibrary())) { + if (additionalProperties.containsKey(JACKSON)) { + codegenOperation.imports.add("ObjectMapper"); + } + if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JSONB)) { + codegenOperation.imports.add("Jsonb"); + codegenOperation.imports.add("JsonbBuilder"); + } + if (codegenOperation.bodyParam != null) { + codegenOperation.imports.add("Handler"); + } + if (codegenOperation.queryParams.size() > 0 && useAbstractClass) { + codegenOperation.imports.add("List"); + } + if (codegenOperation.formParams.size() > 0 && useAbstractClass) { + codegenOperation.imports.add("Map"); + codegenOperation.imports.add("HashMap"); + codegenOperation.imports.add("InputStream"); + codegenOperation.imports.add("ReadableBodyPart"); + codegenOperation.imports.add("ArrayList"); + codegenOperation.imports.add("DataChunk"); + codegenOperation.imports.add("ByteArrayOutputStream"); + codegenOperation.imports.add("IOException"); + codegenOperation.imports.add("UncheckedIOException"); + codegenOperation.imports.add("ByteArrayInputStream"); + } + } + return codegenOperation; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + generateYAMLSpecFile(objs); + return super.postProcessSupportingFileData(objs); + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultService"; + } + name = sanitizeName(name); + return camelize(name) + "Service"; + } + + @Override + public CodegenModel fromModel(String name, Schema model) { + CodegenModel codegenModel = super.fromModel(name, model); + // remove swagger imports + codegenModel.imports.remove("ApiModelProperty"); + codegenModel.imports.remove("ApiModel"); + + return codegenModel; + } + + @Override + public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { + OperationMap operations = objs.getOperations(); + if (HELIDON_MP.equals(getLibrary())) { + return AbstractJavaJAXRSServerCodegen.jaxrsPostProcessOperations(objs); + } + if (operations != null && HELIDON_SE.equals(getLibrary())) { + List ops = operations.getOperation(); + for (CodegenOperation operation : ops) { + if (operation.formParams.size() > 0) { + objs.put("isFormParamsFunctions", true); + } + } + } + return objs; + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + + if (Boolean.TRUE.equals(model.hasEnums)) { + // Add imports for Jackson + if (additionalProperties.containsKey(JACKSON)) { + model.imports.add("JsonValue"); + model.imports.add("JsonCreator"); + } + } + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "java-helidon-server"; + } + + @Override + public String getHelp() { + return "Generates a Java Helidon Server application."; + } + + + @Override + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } + + @Override + public void setPerformBeanValidation(boolean performBeanValidation) { + throw new UnsupportedOperationException("Not implemented"); + } + + public String getSerializationLibrary() { + return serializationLibrary; + } + + public void setSerializationLibrary(String serializationLibrary) { + if (SERIALIZATION_LIBRARY_JACKSON.equalsIgnoreCase(serializationLibrary)) { + this.serializationLibrary = SERIALIZATION_LIBRARY_JACKSON; + } else if (SERIALIZATION_LIBRARY_JSONB.equalsIgnoreCase(serializationLibrary)) { + this.serializationLibrary = SERIALIZATION_LIBRARY_JSONB; + } else { + throw new IllegalArgumentException("Unexpected serializationLibrary value: " + serializationLibrary); + } + } + + /** + * Check if pom file and src directory already exist. + * + * @return outcome of test + */ + @Override + protected boolean projectFilesExist() { + Path projectFolder = Paths.get(getOutputTestFolder()); + Path pom = projectFolder.resolve("pom.xml"); + Path buildGradle = projectFolder.resolve("build.gradle"); + Path src = projectFolder.resolve(Paths.get(sourceFolder, invokerPackage.replace('.', File.separatorChar))); + return (pom.toFile().exists() || buildGradle.toFile().exists()) && src.toFile().exists(); + } +} + diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java index c46996afdd..d996d7f83d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -169,6 +169,10 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen supportingFiles.add(new SupportingFile("README.mustache", "", "README.md") .doNotOverwrite()); + supportingFiles.add(new SupportingFile("RestResourceRoot.mustache", + (sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestResourceRoot.java") + .doNotOverwrite()); + if (generatePom) { supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml") .doNotOverwrite()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java index d27716dffd..686542b761 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java @@ -20,6 +20,7 @@ import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.ComposedSchema; import io.swagger.v3.oas.models.media.Schema; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; @@ -49,8 +50,11 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod public static final String MODULE_NAME = "moduleName"; public static final String PROJECT_DESCRIPTION = "projectDescription"; public static final String PROJECT_VERSION = "projectVersion"; + public static final String USE_PROMISES = "usePromises"; public static final String USE_INHERITANCE = "useInheritance"; + public static final String EMIT_MODEL_METHODS = "emitModelMethods"; public static final String EMIT_JS_DOC = "emitJSDoc"; + public static final String USE_ES6 = "useES6"; public static final String NPM_REPOSITORY = "npmRepository"; final String[][] JAVASCRIPT_SUPPORTING_FILES = { @@ -60,7 +64,8 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod new String[]{"git_push.sh.mustache", "git_push.sh"}, new String[]{"README.mustache", "README.md"}, new String[]{"mocha.opts", "mocha.opts"}, - new String[]{"travis.yml", ".travis.yml"} + new String[]{"travis.yml", ".travis.yml"}, + new String[]{"gitignore.mustache", ".gitignore"} }; final String[][] JAVASCRIPT_ES6_SUPPORTING_FILES = { @@ -71,7 +76,8 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod new String[]{"README.mustache", "README.md"}, new String[]{"mocha.opts", "mocha.opts"}, new String[]{"travis.yml", ".travis.yml"}, - new String[]{".babelrc.mustache", ".babelrc"} + new String[]{".babelrc.mustache", ".babelrc"}, + new String[]{"gitignore.mustache", ".gitignore"} }; protected String projectName; @@ -82,11 +88,14 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod protected String invokerPackage; protected String sourceFolder = "src"; + protected boolean usePromises; + protected boolean emitModelMethods; protected boolean emitJSDoc = true; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; protected String apiTestPath = "api/"; protected String modelTestPath = "model/"; + protected boolean useES6 = true; // default is ES6 protected String npmRepository = null; private String modelPropertyNaming = "camelCase"; @@ -96,7 +105,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) - .stability(Stability.BETA) + .stability(Stability.DEPRECATED) .build(); outputFolder = "generated-code/js"; @@ -115,7 +124,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod hideGenerationTimestamp = Boolean.TRUE; // reference: http://www.w3schools.com/js/js_reserved.asp - setReservedWordsLowerCase( + reservedWords = new HashSet<>( Arrays.asList( "abstract", "arguments", "boolean", "break", "byte", "case", "catch", "char", "class", "const", @@ -142,10 +151,12 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod defaultIncludes = new HashSet<>(languageSpecificPrimitives); instantiationTypes.put("array", "Array"); + instantiationTypes.put("set", "Array"); instantiationTypes.put("list", "Array"); instantiationTypes.put("map", "Object"); typeMapping.clear(); typeMapping.put("array", "Array"); + typeMapping.put("set", "Array"); typeMapping.put("map", "Object"); typeMapping.put("List", "Array"); typeMapping.put("boolean", "Boolean"); @@ -153,7 +164,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod typeMapping.put("int", "Number"); typeMapping.put("float", "Number"); typeMapping.put("number", "Number"); - typeMapping.put("BigDecimal", "Number"); + typeMapping.put("decimal", "Number"); typeMapping.put("DateTime", "Date"); typeMapping.put("date", "Date"); typeMapping.put("long", "Number"); @@ -167,6 +178,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod typeMapping.put("file", "File"); typeMapping.put("UUID", "String"); typeMapping.put("URI", "String"); + typeMapping.put("AnyType", "Object"); importMapping.clear(); @@ -184,6 +196,12 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod "version of the project (Default: using info.version or \"1.0.0\")")); cliOptions.add(new CliOption(CodegenConstants.LICENSE_NAME, "name of the license the project uses (Default: using info.license.name)")); + cliOptions.add(new CliOption(USE_PROMISES, + "use Promises as return values from the client API, instead of superagent callbacks") + .defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(EMIT_MODEL_METHODS, + "generate getters and setters for model properties") + .defaultValue(Boolean.FALSE.toString())); cliOptions.add(new CliOption(EMIT_JS_DOC, "generate JSDoc comments") .defaultValue(Boolean.TRUE.toString())); @@ -203,7 +221,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod @Override public String getName() { - return "javascript-apollo"; + return "javascript-apollo-deprecated"; } @Override @@ -241,12 +259,18 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } + if (additionalProperties.containsKey(USE_PROMISES)) { + setUsePromises(convertPropertyToBooleanAndWriteBack(USE_PROMISES)); + } if (additionalProperties.containsKey(USE_INHERITANCE)) { setUseInheritance(convertPropertyToBooleanAndWriteBack(USE_INHERITANCE)); } else { supportsInheritance = true; supportsMixins = true; } + if (additionalProperties.containsKey(EMIT_MODEL_METHODS)) { + setEmitModelMethods(convertPropertyToBooleanAndWriteBack(EMIT_MODEL_METHODS)); + } if (additionalProperties.containsKey(EMIT_JS_DOC)) { setEmitJSDoc(convertPropertyToBooleanAndWriteBack(EMIT_JS_DOC)); } @@ -277,7 +301,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod if (StringUtils.isEmpty(info.getDescription())) { projectDescription = "JS API client generated by OpenAPI Generator"; } else { - projectDescription = sanitizeName(info.getDescription()); + projectDescription = info.getDescription(); } } @@ -293,7 +317,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod projectName = "openapi-js-client"; } if (StringUtils.isBlank(moduleName)) { - moduleName = camelize(underscore(projectName)); + moduleName = camelize(underscore(sanitizeName(projectName))); } if (StringUtils.isBlank(projectVersion)) { projectVersion = "1.0.0"; @@ -314,8 +338,11 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder); + additionalProperties.put(USE_PROMISES, usePromises); additionalProperties.put(USE_INHERITANCE, supportsInheritance); + additionalProperties.put(EMIT_MODEL_METHODS, emitModelMethods); additionalProperties.put(EMIT_JS_DOC, emitJSDoc); + additionalProperties.put(USE_ES6, useES6); additionalProperties.put(NPM_REPOSITORY, npmRepository); // make api and model doc path available in mustache template @@ -323,6 +350,9 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod additionalProperties.put("modelDocPath", modelDocPath); String[][] supportingTemplateFiles = JAVASCRIPT_SUPPORTING_FILES; + if (useES6) { + supportingTemplateFiles = JAVASCRIPT_ES6_SUPPORTING_FILES; + } for (String[] supportingTemplateFile : supportingTemplateFiles) { supportingFiles.add(new SupportingFile(supportingTemplateFile[0], "", supportingTemplateFile[1])); @@ -417,6 +447,10 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod this.licenseName = licenseName; } + public void setUsePromises(boolean usePromises) { + this.usePromises = usePromises; + } + public void setNpmRepository(String npmRepository) { this.npmRepository = npmRepository; } @@ -426,6 +460,10 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod this.supportsMixins = useInheritance; } + public void setEmitModelMethods(boolean emitModelMethods) { + this.emitModelMethods = emitModelMethods; + } + public void setEmitJSDoc(boolean emitJSDoc) { this.emitJSDoc = emitJSDoc; } @@ -507,6 +545,11 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod return name; } + @Override + protected boolean isReservedWord(String word) { + return word != null && reservedWords.contains(word); + } + @Override public String toParamName(String name) { // should be the same as variable name @@ -867,22 +910,36 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod return null; } + private String getModelledType(String dataType) { + return "module:" + (StringUtils.isEmpty(invokerPackage) ? "" : (invokerPackage + "/")) + + (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType; + } + private String getJSDocType(CodegenModel cm, CodegenProperty cp) { if (Boolean.TRUE.equals(cp.isContainer)) { - if (cp.containerType.equals("array")) - return "Array.<" + cp.items + ">"; + if (cp.containerType.equals("array") || cp.containerType.equals("set")) + return "Array.<" + getJSDocType(cm, cp.items) + ">"; else if (cp.containerType.equals("map")) - return "Object."; + return "Object."; } String dataType = trimBrackets(cp.datatypeWithEnum); if (cp.isEnum) { dataType = cm.classname + '.' + dataType; } + if (isModelledType(cp)) + dataType = getModelledType(dataType); return dataType; } + private boolean isModelledType(CodegenProperty cp) { + // N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library). + return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType); + } + private String getJSDocType(CodegenParameter cp) { String dataType = trimBrackets(cp.dataType); + if (isModelledType(cp)) + dataType = getModelledType(dataType); if (Boolean.TRUE.equals(cp.isArray)) { return "Array.<" + dataType + ">"; } else if (Boolean.TRUE.equals(cp.isMap)) { @@ -891,9 +948,16 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod return dataType; } + private boolean isModelledType(CodegenParameter cp) { + // N.B. enums count as modelled types, file is not modelled (SuperAgent uses some 3rd party library). + return cp.isEnum || !languageSpecificPrimitives.contains(cp.baseType == null ? cp.dataType : cp.baseType); + } + private String getJSDocType(CodegenOperation co) { String returnType = trimBrackets(co.returnType); if (returnType != null) { + if (isModelledType(co)) + returnType = getModelledType(returnType); if (Boolean.TRUE.equals(co.isArray)) { return "Array.<" + returnType + ">"; } else if (Boolean.TRUE.equals(co.isMap)) { @@ -903,12 +967,16 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod return returnType; } + private boolean isModelledType(CodegenOperation co) { + // This seems to be the only way to tell whether an operation return type is modelled. + return !Boolean.TRUE.equals(co.returnTypeIsPrimitive); + } + private boolean isPrimitiveType(String type) { final String[] primitives = {"number", "integer", "string", "boolean", "null"}; return Arrays.asList(primitives).contains(type); } - @SuppressWarnings("unchecked") @Override public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { // Generate and store argument list string of each operation into @@ -937,6 +1005,9 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod argList.add("opts"); } + // add the 'requestInit' parameter + argList.add("requestInit"); + String joinedArgList = StringUtils.join(argList, ", "); operation.vendorExtensions.put("x-codegen-arg-list", joinedArgList); operation.vendorExtensions.put("x-codegen-has-optional-params", hasOptionalParams); @@ -1145,6 +1216,24 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod } } + @Override + protected String getCollectionFormat(CodegenParameter codegenParameter) { + // This method will return `passthrough` when the parameter data format is binary and an array. + // `passthrough` is not part of the OAS spec. However, this will act like a flag that we should + // not do any processing on the collection type (i.e. convert to tsv, csv, etc..). This is + // critical to support multi file uploads correctly. + if (codegenParameter.isArray && Objects.equals(codegenParameter.dataFormat, "binary")) { + return "passthrough"; + } + return super.getCollectionFormat(codegenParameter); + } + @Override public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.JAVASCRIPT; } + + @Override + protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName ) { + // import everything (including child schema of a composed schema) + addImport(model, modelName); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java index fcac1e9d60..eac98040cc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java @@ -56,28 +56,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo public static final String USE_ES6 = "useES6"; public static final String NPM_REPOSITORY = "npmRepository"; - final String[][] JAVASCRIPT_SUPPORTING_FILES = { - new String[]{"package.mustache", "package.json"}, - // new String[]{"index.mustache", "src/index.js", }, - // new String[]{"ApiClient.mustache", "src/ApiClient.js"}, - new String[]{"git_push.sh.mustache", "git_push.sh"}, - new String[]{"README.mustache", "README.md"}, - new String[]{"mocha.opts", "mocha.opts"}, - new String[]{"travis.yml", ".travis.yml"}, - new String[]{"gitignore.mustache", ".gitignore"} - }; - - final String[][] JAVASCRIPT_ES6_SUPPORTING_FILES = { - new String[]{"package.mustache", "package.json"}, - // new String[]{"index.mustache", "src/index.js"}, - // new String[]{"ApiClient.mustache", "src/ApiClient.js"}, - new String[]{"git_push.sh.mustache", "git_push.sh"}, - new String[]{"README.mustache", "README.md"}, - new String[]{"mocha.opts", "mocha.opts"}, - new String[]{"travis.yml", ".travis.yml"}, - new String[]{".babelrc.mustache", ".babelrc"}, - new String[]{"gitignore.mustache", ".gitignore"} - }; + public static final String LIBRARY_JAVASCRIPT = "javascript"; + public static final String LIBRARY_APOLLO = "apollo"; protected String projectName; protected String moduleName; @@ -109,7 +89,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo apiTemplateFiles.put("api.mustache", ".js"); apiTestTemplateFiles.put("api_test.mustache", ".js"); // subfolder Javascript/es6 - embeddedTemplateDir = templateDir = "Javascript" + File.separator + "es6"; + embeddedTemplateDir = templateDir = "Javascript"; apiPackage = "api"; modelPackage = "model"; modelDocTemplateFiles.put("model_doc.mustache", ".md"); @@ -207,6 +187,13 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json")); + + supportedLibraries.put(LIBRARY_JAVASCRIPT, "JavaScript client library"); + supportedLibraries.put(LIBRARY_APOLLO, "Apollo REST DataSource"); + setLibrary(LIBRARY_JAVASCRIPT); + final CliOption library = new CliOption(CodegenConstants.LIBRARY, CodegenConstants.LIBRARY_DESC).defaultValue(LIBRARY_JAVASCRIPT); + library.setEnum(supportedLibraries); + cliOptions.add(library); } @Override @@ -275,6 +262,9 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo if (additionalProperties.containsKey(NPM_REPOSITORY)) { setNpmRepository(((String) additionalProperties.get(NPM_REPOSITORY))); } + if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { + setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); + } } @Override @@ -296,7 +286,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo if (StringUtils.isEmpty(info.getDescription())) { projectDescription = "JS API client generated by OpenAPI Generator"; } else { - projectDescription = sanitizeName(info.getDescription()); + projectDescription = info.getDescription(); } } @@ -312,7 +302,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo projectName = "openapi-js-client"; } if (StringUtils.isBlank(moduleName)) { - moduleName = camelize(underscore(projectName)); + moduleName = camelize(underscore(sanitizeName(projectName))); } if (StringUtils.isBlank(projectVersion)) { projectVersion = "1.0.0"; @@ -344,18 +334,18 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); - String[][] supportingTemplateFiles = JAVASCRIPT_SUPPORTING_FILES; - if (useES6) { - supportingTemplateFiles = JAVASCRIPT_ES6_SUPPORTING_FILES; - } - - for (String[] supportingTemplateFile : supportingTemplateFiles) { - supportingFiles.add(new SupportingFile(supportingTemplateFile[0], "", supportingTemplateFile[1])); - } - + supportingFiles.add(new SupportingFile("package.mustache", "package.json")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "git_push.sh")); + supportingFiles.add(new SupportingFile("README.mustache", "README.md")); + supportingFiles.add(new SupportingFile("mocha.opts", "mocha.opts")); + supportingFiles.add(new SupportingFile("travis.yml", ".travis.yml")); + supportingFiles.add(new SupportingFile("gitignore.mustache", ".gitignore")); supportingFiles.add(new SupportingFile("index.mustache", createPath(sourceFolder, invokerPackage), "index.js")); supportingFiles.add(new SupportingFile("ApiClient.mustache", createPath(sourceFolder, invokerPackage), "ApiClient.js")); + if (useES6 || LIBRARY_APOLLO.equals(library)) { + supportingFiles.add(new SupportingFile(".babelrc.mustache", ".babelrc")); + } } @Override @@ -862,8 +852,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { final Schema parentModel = allDefinitions.get(codegenModel.parentSchema); - final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); - codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); + if (parentModel != null) { + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); + codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); + } } if (ModelUtils.isArraySchema(model)) { ArraySchema am = (ArraySchema) model; @@ -1000,9 +992,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo argList.add("opts"); } - if (!usePromises) { + // Add extra function arguments after the required and optional API call parameters: + if (LIBRARY_JAVASCRIPT.equals(library) && !usePromises) { argList.add("callback"); } + if (LIBRARY_APOLLO.equals(library)) { + argList.add("requestInit"); + } + String joinedArgList = StringUtils.join(argList, ", "); operation.vendorExtensions.put("x-codegen-arg-list", joinedArgList); operation.vendorExtensions.put("x-codegen-has-optional-params", hasOptionalParams); @@ -1224,10 +1221,12 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo } @Override - public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.JAVASCRIPT; } + public GeneratorLanguage generatorLanguage() { + return GeneratorLanguage.JAVASCRIPT; + } @Override - protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName ) { + protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName) { // import everything (including child schema of a composed schema) addImport(model, modelName); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java index c9785fc215..afc56451f1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java @@ -187,10 +187,10 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { @SuppressWarnings("unchecked") Set exampleValues = ((Map) rawValue).values().stream() - .map(x -> quoteExample( - StringEscapeUtils.escapeEcmaScript( - String.valueOf(x.getValue())))) - .collect(Collectors.toCollection(TreeSet::new)); + .map(x -> quoteExample( + StringEscapeUtils.escapeEcmaScript( + String.valueOf(x.getValue())))) + .collect(Collectors.toCollection(TreeSet::new)); if (!exampleValues.isEmpty()) { @@ -203,7 +203,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { writer.write(noExampleParamValue); } - // handle as (single) 'example' + // handle as (single) 'example' } else { writer.write(String.join("", quoteExample( @@ -214,7 +214,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { " // extracted from 'example' field defined at the parameter level of OpenAPI spec")); } - // param needs to be initialized for subsequent data extraction - see `X_OPERATION_DATAEXTRACT` K6 vendor extension + // param needs to be initialized for subsequent data extraction - see `X_OPERATION_DATAEXTRACT` K6 vendor extension } else if (fragment.context() instanceof K6ClientCodegen.Parameter && ((K6ClientCodegen.Parameter) fragment.context()).initialize) { @@ -304,8 +304,8 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { DataExtractSubstituteParameter dataExtract; public HTTPRequest(String method, String path, @Nullable List query, @Nullable HTTPBody body, - boolean hasBodyExample, @Nullable HTTPParameters params, @Nullable List k6Checks, - DataExtractSubstituteParameter dataExtract) { + boolean hasBodyExample, @Nullable HTTPParameters params, @Nullable List k6Checks, + DataExtractSubstituteParameter dataExtract) { // NOTE: https://k6.io/docs/javascript-api/k6-http/del-url-body-params this.method = method.equals("delete") ? "del" : method; this.isDelete = method.equals("delete"); @@ -592,37 +592,38 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { String responseType = getDoubleQuotedString(accepts); try { + if (operation != null && operation.getParameters() != null) { + for (io.swagger.v3.oas.models.parameters.Parameter parameter : operation.getParameters()) { + switch (parameter.getIn()) { + case "header": + httpParams.add(new Parameter(parameter.getName(), getTemplateString(toVarName(parameter.getName())))); + extraParameters.add(new Parameter(toVarName(parameter.getName()), parameter.getName().toUpperCase(Locale.ROOT))); + break; + case "path": + case "query": + if (parameter.getIn().equals("query")) + queryParams.add(new Parameter(parameter.getName(), getTemplateVariable(parameter.getName()))); + if (!pathVariables.containsKey(path)) { + // use 'example' field defined at the parameter level of OpenAPI spec + if (Objects.nonNull(parameter.getExample())) { + variables.add(new Parameter(toVarName(parameter.getName()), + parameter.getExample(), true)); - for (io.swagger.v3.oas.models.parameters.Parameter parameter : operation.getParameters()) { - switch (parameter.getIn()) { - case "header": - httpParams.add(new Parameter(parameter.getName(), getTemplateString(toVarName(parameter.getName())))); - extraParameters.add(new Parameter(toVarName(parameter.getName()), parameter.getName().toUpperCase(Locale.ROOT))); - break; - case "path": - case "query": - if (parameter.getIn().equals("query")) - queryParams.add(new Parameter(parameter.getName(), getTemplateVariable(parameter.getName()))); - if (!pathVariables.containsKey(path)) { - // use 'example' field defined at the parameter level of OpenAPI spec - if (Objects.nonNull(parameter.getExample())) { - variables.add(new Parameter(toVarName(parameter.getName()), - parameter.getExample(), true)); + // use 'examples' field defined at the parameter level of OpenAPI spec + } else if (Objects.nonNull(parameter.getExamples())) { + variables.add(new Parameter(toVarName(parameter.getName()), + parameter.getExamples(), true)); - // use 'examples' field defined at the parameter level of OpenAPI spec - } else if (Objects.nonNull(parameter.getExamples())) { - variables.add(new Parameter(toVarName(parameter.getName()), - parameter.getExamples(), true)); - - // no example provided, generated script will contain placeholder value - } else { - variables.add(new Parameter(toVarName(parameter.getName()), - parameter.getName().toUpperCase(Locale.ROOT))); + // no example provided, generated script will contain placeholder value + } else { + variables.add(new Parameter(toVarName(parameter.getName()), + parameter.getName().toUpperCase(Locale.ROOT))); + } } - } - break; - default: - break; + break; + default: + break; + } } } } catch (NullPointerException e) { @@ -893,7 +894,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { * @param requests */ private void addOrUpdateRequestGroup(Map requestGroups, String groupName, - Set variables, Map requests) { + Set variables, Map requests) { if (requestGroups.containsKey(groupName)) { HTTPRequestGroup existingHTTPRequestGroup = requestGroups.get(groupName); existingHTTPRequestGroup.addRequests(requests); @@ -956,16 +957,16 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { for (Map.Entry xOperationDataExtractPropertiesEntry : xOperationDataExtractProperties.entrySet()) { switch (String.valueOf(xOperationDataExtractPropertiesEntry.getKey())) { - case X_OPERATION_DATAEXTRACT_OPERATION_ID: - operationId = Optional.of(String.valueOf(xOperationDataExtractPropertiesEntry.getValue())); - continue; + case X_OPERATION_DATAEXTRACT_OPERATION_ID: + operationId = Optional.of(String.valueOf(xOperationDataExtractPropertiesEntry.getValue())); + continue; - case X_OPERATION_DATAEXTRACT_VALUE_PATH: - valuePath = Optional.of(String.valueOf(xOperationDataExtractPropertiesEntry.getValue())); - continue; + case X_OPERATION_DATAEXTRACT_VALUE_PATH: + valuePath = Optional.of(String.valueOf(xOperationDataExtractPropertiesEntry.getValue())); + continue; - case X_OPERATION_DATAEXTRACT_PARAMETER_NAME: - parameterName = Optional.of(String.valueOf(xOperationDataExtractPropertiesEntry.getValue())); + case X_OPERATION_DATAEXTRACT_PARAMETER_NAME: + parameterName = Optional.of(String.valueOf(xOperationDataExtractPropertiesEntry.getValue())); } } @@ -1005,12 +1006,12 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { if (cgOperation.getHasVendorExtensions() && cgOperation.vendorExtensions.containsKey(X_OPERATION_GROUPING) && cgOperation.vendorExtensions.get(X_OPERATION_GROUPING) instanceof java.util.Map) { - Map.Entry operationGroupingEntry = ((Map) cgOperation.vendorExtensions .get(X_OPERATION_GROUPING)).entrySet().stream().findFirst().orElse(null); - - return Optional.of(new OperationGrouping(String.valueOf(operationGroupingEntry.getKey()), - Integer.parseInt(String.valueOf(operationGroupingEntry.getValue())))); + if (operationGroupingEntry != null) { + return Optional.of(new OperationGrouping(String.valueOf(operationGroupingEntry.getKey()), + Integer.parseInt(String.valueOf(operationGroupingEntry.getValue())))); + } } return operationGrouping; @@ -1061,7 +1062,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { * @param bodyOrFormParams */ private void extractRequestBodyExample(RequestBody requestBody, String contentTypeValue, - List bodyOrFormParams) { + List bodyOrFormParams) { Optional> requestBodyExampleEntry = requestBody.getContent().get(contentTypeValue) .getExamples().entrySet().stream().findFirst(); @@ -1108,14 +1109,14 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { } else { switch (requestsSize) { - case 0: - case 1: - requestOrder = requestsSize; - break; + case 0: + case 1: + requestOrder = requestsSize; + break; - default: - requestOrder = (requestsSize - 1); - break; + default: + requestOrder = (requestsSize - 1); + break; } } @@ -1123,6 +1124,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { } // + /** * Any variables not defined yet but used for subsequent data extraction must be * initialized @@ -1147,5 +1149,7 @@ public class K6ClientCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.K_SIX; } + public GeneratorLanguage generatorLanguage() { + return GeneratorLanguage.K_SIX; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java index bcdc4f9eef..6b9dd53321 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java @@ -596,13 +596,13 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { private void addSupportingSerializerAdapters(final String infrastructureFolder) { supportingFiles.add(new SupportingFile("jvm-common/infrastructure/Serializer.kt.mustache", infrastructureFolder, "Serializer.kt")); - supportingFiles.add(new SupportingFile("jvm-common/infrastructure/ByteArrayAdapter.kt.mustache", infrastructureFolder, "ByteArrayAdapter.kt")); switch (getSerializationLibrary()) { case moshi: if (enumUnknownDefaultCase) { supportingFiles.add(new SupportingFile("jvm-common/infrastructure/SerializerHelper.kt.mustache", infrastructureFolder, "SerializerHelper.kt")); } + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/ByteArrayAdapter.kt.mustache", infrastructureFolder, "ByteArrayAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/UUIDAdapter.kt.mustache", infrastructureFolder, "UUIDAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); @@ -613,6 +613,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { break; case gson: + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/ByteArrayAdapter.kt.mustache", infrastructureFolder, "ByteArrayAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java index bfae655bbd..d4a44799ba 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java @@ -31,6 +31,8 @@ import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; import java.util.regex.Matcher; import static org.openapitools.codegen.utils.StringUtils.camelize; @@ -39,6 +41,7 @@ import static org.openapitools.codegen.utils.StringUtils.underscore; public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { private final Logger LOGGER = LoggerFactory.getLogger(PerlClientCodegen.class); + protected static int emptyFunctionNameCounter = 0; public static final String MODULE_NAME = "moduleName"; public static final String MODULE_VERSION = "moduleVersion"; protected String moduleName = "WWW::OpenAPIClient"; @@ -47,7 +50,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; - protected static int emptyFunctionNameCounter = 0; + private Map schemaKeyToModelNameCache = new HashMap<>(); public PerlClientCodegen() { super(); @@ -334,6 +337,18 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelName(String name) { + // We need to check if schema-mapping has a different model for this class, so we use it + // instead of the auto-generated one. + if (schemaMapping.containsKey(name)) { + return schemaMapping.get(name); + } + + // memoization + String origName = name; + if (schemaKeyToModelNameCache.containsKey(origName)) { + return schemaKeyToModelNameCache.get(origName); + } + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. // model name cannot use reserved keyword @@ -360,7 +375,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { // camelize the model name // phone_number => PhoneNumber - return camelize(name); + String camelizedName = camelize(name); + schemaKeyToModelNameCache.put(origName, camelizedName); + return camelizedName; } @Override @@ -646,6 +663,40 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { System.out.println("################################################################################"); } + /** + * Convert OAS Model object to Codegen Model object + * A custom version is made for this method to ensure that + * model.format remains empty string + * + * @param name the name of the model + * @param sc OAS Model object + * @return Codegen Model object + */ + @Override + public CodegenModel fromModel(String name, Schema sc) { + CodegenModel cm = super.fromModel(name, sc); + cm.setFormat(""); + return cm; + } + + /** + * Convert OAS Property object to Codegen Property object + * A custom version is made for this method to ensure that + * property.format remains empty string + * + * @param name name of the property + * @param p OAS property schema + * @param required true if the property is required in the next higher object schema, false otherwise + * @param schemaIsFromAdditionalProperties true if the property is defined by additional properties schema + * @return Codegen Property object + */ + @Override + public CodegenProperty fromProperty(String name, Schema p, boolean required, boolean schemaIsFromAdditionalProperties) { + CodegenProperty property = super.fromProperty(name, p, required, schemaIsFromAdditionalProperties); + property.setFormat(""); + return property; + } + @Override public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.PERL; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java index 9f4cb5651d..796d8ad847 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java @@ -92,9 +92,6 @@ public class PhpDataTransferClientCodegen extends AbstractPhpCodegen { .stability(Stability.BETA) .build(); - //no point to use double - http://php.net/manual/en/language.types.float.php , especially because of PHP 7+ float type declaration - typeMapping.put("double", "float"); - // remove these from primitive types to make the output works languageSpecificPrimitives.remove("\\DateTime"); languageSpecificPrimitives.remove("\\SplFileObject"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java index 62f7d164ea..dadc17a6ff 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java @@ -382,7 +382,7 @@ public class PhpLaravelServerCodegen extends AbstractPhpCodegen { } // number - if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + if ("int".equals(datatype) || "float".equals(datatype)) { String varName = "NUMBER_" + value; varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("\\+", "PLUS_"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java index cd81b3174a..50050aa23f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java @@ -87,9 +87,6 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { ) ); - //no point to use double - http://php.net/manual/en/language.types.float.php , especially because of PHP 7+ float type declaration - typeMapping.put("double", "float"); - // remove these from primitive types to make the output works languageSpecificPrimitives.remove("\\DateTime"); languageSpecificPrimitives.remove("\\SplFileObject"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java index fd71068832..373381eafe 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java @@ -98,7 +98,6 @@ public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConf "boolean", "int", "integer", - "double", "float", "string", "object", @@ -115,7 +114,7 @@ public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConf typeMapping.put("integer", "int"); typeMapping.put("long", "int"); typeMapping.put("float", "float"); - typeMapping.put("double", "double"); + typeMapping.put("double", "float"); typeMapping.put("string", "string"); typeMapping.put("byte", "int"); typeMapping.put("boolean", "boolean"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java index ea70427fb3..4d1fb30fa2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java @@ -106,12 +106,12 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg importMapping.clear(); supportsInheritance = true; - srcBasePath = "."; + srcBasePath = ""; setInvokerPackage("OpenAPI\\Server"); setBundleName("OpenAPIServer"); setBundleAlias("open_api_server"); modelDirName = "Model"; - docsBasePath = "Resources" + "/" + "docs"; + docsBasePath = "docs"; apiDocPath = docsBasePath + "/" + apiDirName; modelDocPath = docsBasePath + "/" + modelDirName; outputFolder = "generated-code" + File.separator + "php"; @@ -147,7 +147,6 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg Arrays.asList( "bool", "int", - "double", "float", "string", "object", @@ -183,7 +182,7 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg typeMapping.put("decimal", "float"); typeMapping.put("number", "float"); typeMapping.put("float", "float"); - typeMapping.put("double", "double"); + typeMapping.put("double", "float"); typeMapping.put("string", "string"); typeMapping.put("byte", "int"); typeMapping.put("boolean", "bool"); @@ -317,6 +316,9 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg additionalProperties.put("bundleExtensionName", bundleExtensionName); additionalProperties.put("bundleAlias", bundleAlias); + // add trailing slash for mustache templates + additionalProperties.put("relativeSrcBasePath", srcBasePath.isEmpty() ? "" : srcBasePath + "/"); + // make api and model src path available in mustache template additionalProperties.put("apiSrcPath", "." + "/" + toSrcPath(apiPackage, srcBasePath)); additionalProperties.put("modelSrcPath", "." + "/" + toSrcPath(modelPackage, srcBasePath)); @@ -337,11 +339,12 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg final String configDir = "Resources" + File.separator + "config"; final String dependencyInjectionDir = "DependencyInjection"; + final String compilerDir = dependencyInjectionDir + File.separator + "Compiler"; supportingFiles.add(new SupportingFile("Controller.mustache", toSrcPath(controllerPackage, srcBasePath), "Controller.php")); - supportingFiles.add(new SupportingFile("Bundle.mustache", "", bundleClassName + ".php")); - supportingFiles.add(new SupportingFile("Extension.mustache", dependencyInjectionDir, bundleExtensionName + ".php")); - supportingFiles.add(new SupportingFile("ApiPass.mustache", dependencyInjectionDir + File.separator + "Compiler", bundleName + "ApiPass.php")); + supportingFiles.add(new SupportingFile("Bundle.mustache", toSrcPath("", srcBasePath), bundleClassName + ".php")); + supportingFiles.add(new SupportingFile("Extension.mustache", toSrcPath(dependencyInjectionDir, srcBasePath), bundleExtensionName + ".php")); + supportingFiles.add(new SupportingFile("ApiPass.mustache", toSrcPath(compilerDir, srcBasePath), bundleName + "ApiPass.php")); supportingFiles.add(new SupportingFile("ApiServer.mustache", toSrcPath(apiPackage, srcBasePath), "ApiServer.php")); // Serialization components @@ -358,10 +361,10 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg supportingFiles.add(new SupportingFile("testing/phpunit.xml.mustache", "", "phpunit.xml.dist")); supportingFiles.add(new SupportingFile("testing/AppKernel.mustache", toSrcPath(testsPackage, srcBasePath), "AppKernel.php")); supportingFiles.add(new SupportingFile("testing/ControllerTest.mustache", toSrcPath(controllerTestsPackage, srcBasePath), "ControllerTest.php")); - supportingFiles.add(new SupportingFile("testing/test_config.yml", toSrcPath(testsPackage, srcBasePath), "test_config.yml")); + supportingFiles.add(new SupportingFile("testing/test_config.yml", toSrcPath(testsPackage, srcBasePath), "test_config.yaml")); - supportingFiles.add(new SupportingFile("routing.mustache", configDir, "routing.yml")); - supportingFiles.add(new SupportingFile("services.mustache", configDir, "services.yml")); + supportingFiles.add(new SupportingFile("routing.mustache", toSrcPath(configDir, srcBasePath), "routing.yaml")); + supportingFiles.add(new SupportingFile("services.mustache", toSrcPath(configDir, srcBasePath), "services.yaml")); supportingFiles.add(new SupportingFile("composer.mustache", "", "composer.json")); supportingFiles.add(new SupportingFile("autoload.mustache", "", "autoload.php")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); @@ -588,7 +591,7 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg @Override public String toEnumValue(String value, String datatype) { - if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + if ("int".equals(datatype) || "float".equals(datatype)) { return value; } else { return "\"" + escapeText(value) + "\""; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java index 79d878b385..2a6c52fc20 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java @@ -70,6 +70,8 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo protected String modelsCmdletVerb = "Initialize"; protected boolean useClassNameInModelsExamples = true; + private Map schemaKeyToModelNameCache = new HashMap<>(); + /** * Constructs an instance of `PowerShellClientCodegen`. */ @@ -907,6 +909,18 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo */ @Override public String toModelName(String name) { + // check if schema-mapping has a different model for this class, so we can use it + // instead of the auto-generated one. + if (schemaMapping.containsKey(name)) { + return schemaMapping.get(name); + } + + // memoization + String origName = name; + if (schemaKeyToModelNameCache.containsKey(origName)) { + return schemaKeyToModelNameCache.get(origName); + } + if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; } @@ -933,6 +947,8 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo name = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) } + schemaKeyToModelNameCache.put(origName, name); + return name; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java index b0d1419275..79a55ee8ba 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java @@ -42,8 +42,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.regex.Pattern; -import static org.openapitools.codegen.utils.StringUtils.camelize; -import static org.openapitools.codegen.utils.StringUtils.underscore; +import static org.openapitools.codegen.utils.StringUtils.*; public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConfig { @@ -101,12 +100,14 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf defaultIncludes = new HashSet<>( Arrays.asList( "map", + "set", "array") ); languageSpecificPrimitives = new HashSet<>( Arrays.asList( "map", + "set", "array", "bool", "bytes", @@ -127,9 +128,12 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf instantiationTypes.clear(); instantiationTypes.put("array", "repeat"); + instantiationTypes.put("set", "repeat"); + // ref: https://developers.google.com/protocol-buffers/docs/proto typeMapping.clear(); + typeMapping.put("set", "array"); typeMapping.put("array", "array"); typeMapping.put("map", "map"); typeMapping.put("integer", "int32"); @@ -173,8 +177,7 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - } - else { + } else { additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } @@ -218,22 +221,22 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf * NOTE: Enum values use C++ scoping rules, meaning that enum values are siblings of their type, not children of it. Therefore, enum value must be unique * * @param allowableValues allowable values - * @param prefix added prefix + * @param prefix added prefix */ - public void addEnumValuesPrefix(Map allowableValues, String prefix){ - if(allowableValues.containsKey("enumVars")) { - List> enumVars = (List>)allowableValues.get("enumVars"); + public void addEnumValuesPrefix(Map allowableValues, String prefix) { + if (allowableValues.containsKey("enumVars")) { + List> enumVars = (List>) allowableValues.get("enumVars"); - for(Map value : enumVars) { - String name = (String)value.get("name"); + for (Map value : enumVars) { + String name = (String) value.get("name"); value.put("name", prefix + "_" + name); value.put("value", "\"" + prefix + "_" + name + "\""); } } - if(allowableValues.containsKey("values")) { - List values = (List)allowableValues.get("values"); - for(String value : values) { + if (allowableValues.containsKey("values")) { + List values = (List) allowableValues.get("values"); + for (String value : values) { value = prefix + "_" + value; } } @@ -245,9 +248,9 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf * @param allowableValues allowable values */ public void addUnknownToAllowableValues(Map allowableValues) { - if(startEnumsWithUnknown) { - if(allowableValues.containsKey("enumVars")) { - List> enumVars = (List>)allowableValues.get("enumVars"); + if (startEnumsWithUnknown) { + if (allowableValues.containsKey("enumVars")) { + List> enumVars = (List>) allowableValues.get("enumVars"); HashMap unknown = new HashMap(); unknown.put("name", "UNKNOWN"); @@ -257,8 +260,8 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf enumVars.add(0, unknown); } - if(allowableValues.containsKey("values")) { - List values = (List)allowableValues.get("values"); + if (allowableValues.containsKey("values")) { + List values = (List) allowableValues.get("values"); values.add(0, "UNKNOWN"); } } @@ -284,12 +287,12 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf for (ModelMap mo : objs.getModels()) { CodegenModel cm = mo.getModel(); - if(cm.isEnum) { + if (cm.isEnum) { Map allowableValues = cm.getAllowableValues(); addUnknownToAllowableValues(allowableValues); addEnumValuesPrefix(allowableValues, cm.getClassname()); if (allowableValues.containsKey("enumVars")) { - List> enumVars = (List>)allowableValues.get("enumVars"); + List> enumVars = (List>) allowableValues.get("enumVars"); addEnumIndexes(enumVars); } } @@ -299,8 +302,7 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf // add x-protobuf-type: repeated if it's an array if (Boolean.TRUE.equals(var.isArray)) { var.vendorExtensions.put("x-protobuf-type", "repeated"); - } - else if (Boolean.TRUE.equals(var.isNullable && var.isPrimitiveType)) { + } else if (Boolean.TRUE.equals(var.isNullable && var.isPrimitiveType)) { var.vendorExtensions.put("x-protobuf-type", "optional"); } @@ -317,19 +319,18 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf if (var.isEnum) { addUnknownToAllowableValues(var.allowableValues); addEnumValuesPrefix(var.allowableValues, var.getEnumName()); - - if(var.allowableValues.containsKey("enumVars")) { + + if (var.allowableValues.containsKey("enumVars")) { List> enumVars = (List>) var.allowableValues.get("enumVars"); addEnumIndexes(enumVars); } } // Add x-protobuf-index, unless already specified - if(this.numberedFieldNumberList) { + if (this.numberedFieldNumberList) { var.vendorExtensions.putIfAbsent("x-protobuf-index", index); index++; - } - else { + } else { try { var.vendorExtensions.putIfAbsent("x-protobuf-index", generateFieldNumberFromString(var.getName())); } catch (ProtoBufIndexComputationException e) { @@ -495,6 +496,11 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf return underscore(toModelName(name)); } + @Override + public String toVarName(final String name) { + return name; + } + @Override public String toModelName(String name) { name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. @@ -550,14 +556,12 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf int index = 1; for (CodegenParameter p : op.allParams) { // add x-protobuf-type: repeated if it's an array - + if (Boolean.TRUE.equals(p.isArray)) { p.vendorExtensions.put("x-protobuf-type", "repeated"); - } - else if (Boolean.TRUE.equals(p.isNullable && p.isPrimitiveType)) { + } else if (Boolean.TRUE.equals(p.isNullable && p.isPrimitiveType)) { p.vendorExtensions.put("x-protobuf-type", "optional"); - } - else if (Boolean.TRUE.equals(p.isMap)) { + } else if (Boolean.TRUE.equals(p.isMap)) { LOGGER.warn("Map parameter (name: {}, operation ID: {}) not yet supported", p.paramName, op.operationId); } @@ -644,5 +648,7 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf } @Override - public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.PROTOBUF; } + public GeneratorLanguage generatorLanguage() { + return GeneratorLanguage.PROTOBUF; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java index fd381e5297..5f5b8852e1 100755 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java @@ -101,10 +101,6 @@ public class PythonBluePlanetServerCodegen extends AbstractPythonConnexionServer this.defaultController = "default_controller"; additionalProperties.put(DEFAULT_CONTROLLER, this.defaultController); } - if (Boolean.TRUE.equals(additionalProperties.get(SUPPORT_PYTHON2))) { - additionalProperties.put(SUPPORT_PYTHON2, Boolean.TRUE); - typeMapping.put("long", "long"); - } String APP_PATH = "app" + File.separatorChar; String APP_PACKAGE_PATH = APP_PATH + packageName; @@ -266,5 +262,5 @@ public class PythonBluePlanetServerCodegen extends AbstractPythonConnexionServer } @Override - public String generatorLanguageVersion() { return "2.7+ and 3.5.2+"; }; + public String generatorLanguageVersion() { return "3.5.2+"; }; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java index 74a5bf2c60..5100b00017 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java @@ -16,118 +16,236 @@ package org.openapitools.codegen.languages; -import com.google.common.collect.Sets; +import com.github.curiousoddman.rgxgen.RgxGen; +import com.github.curiousoddman.rgxgen.config.RgxGenOption; +import com.github.curiousoddman.rgxgen.config.RgxGenProperties; +import com.google.common.base.CaseFormat; +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.Paths; +import io.swagger.v3.oas.models.servers.Server; +import io.swagger.v3.oas.models.tags.Tag; + +import org.apache.commons.io.FileUtils; +import org.openapitools.codegen.api.TemplatePathLocator; +import org.openapitools.codegen.ignore.CodegenIgnoreProcessor; +import org.openapitools.codegen.model.ModelMap; +import org.openapitools.codegen.model.ModelsMap; +import org.openapitools.codegen.model.OperationMap; +import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.templating.*; import io.swagger.v3.core.util.Json; import io.swagger.v3.oas.models.media.*; -import io.swagger.v3.oas.models.media.ArraySchema; -import io.swagger.v3.oas.models.media.MediaType; -import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.parameters.RequestBody; import io.swagger.v3.oas.models.security.SecurityScheme; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; import org.openapitools.codegen.CodegenDiscriminator.MappedModel; -import org.openapitools.codegen.meta.features.*; -import org.openapitools.codegen.model.ModelMap; -import org.openapitools.codegen.model.ModelsMap; -import org.openapitools.codegen.model.OperationMap; -import org.openapitools.codegen.model.OperationsMap; -import org.openapitools.codegen.utils.ModelUtils; -import org.openapitools.codegen.utils.ProcessUtils; +import org.openapitools.codegen.api.TemplatingEngineAdapter; import org.openapitools.codegen.meta.GeneratorMetadata; import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.utils.ProcessUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.github.curiousoddman.rgxgen.RgxGen; -import com.github.curiousoddman.rgxgen.config.RgxGenOption; -import com.github.curiousoddman.rgxgen.config.RgxGenProperties; +import org.openapitools.codegen.api.TemplateProcessor; +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.nio.file.Path; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -import java.io.File; import java.util.*; -import java.util.regex.Pattern; import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import static org.openapitools.codegen.utils.OnceLogger.once; +import static org.openapitools.codegen.utils.StringUtils.camelize; +import static org.openapitools.codegen.utils.StringUtils.underscore; -public class PythonClientCodegen extends PythonLegacyClientCodegen { +public class PythonClientCodegen extends AbstractPythonCodegen { private final Logger LOGGER = LoggerFactory.getLogger(PythonClientCodegen.class); + public static final String PACKAGE_URL = "packageUrl"; + public static final String DEFAULT_LIBRARY = "urllib3"; + // nose is a python testing framework, we use pytest if USE_NOSE is unset + public static final String USE_NOSE = "useNose"; + public static final String RECURSION_LIMIT = "recursionLimit"; + public static final String USE_INLINE_MODEL_RESOLVER = "useInlineModelResolver"; + + protected String packageUrl; + protected String apiDocPath = "docs/apis/tags/"; + protected String modelDocPath = "docs/models/"; + protected boolean useNose = false; + protected boolean useInlineModelResolver = false; + + protected Map regexModifiers; + + private String testFolder; + // A cache to efficiently lookup a Schema instance based on the return value of `toModelName()`. private Map modelNameToSchemaCache; private DateTimeFormatter iso8601Date = DateTimeFormatter.ISO_DATE; private DateTimeFormatter iso8601DateTime = DateTimeFormatter.ISO_DATE_TIME; + private String templateExtension; + protected CodegenIgnoreProcessor ignoreProcessor; + protected TemplateProcessor templateProcessor = null; + + // for apis.tags imports + private Map tagModuleNameToApiClassname = new LinkedHashMap<>(); + // for apis.tags enum tag definition + private Map enumToTag = new LinkedHashMap<>(); + // for apis.tags tag api definition + private Map tagEnumToApiClassname = new LinkedHashMap<>(); + + private boolean nonCompliantUseDiscrIfCompositionFails = false; + public PythonClientCodegen() { super(); - - embeddedTemplateDir = templateDir = "python"; - - // Composed schemas can have the 'additionalProperties' keyword, as specified in JSON schema. - // In principle, this should be enabled by default for all code generators. However due to limitations - // in other code generators, support needs to be enabled on a case-by-case basis. - supportsAdditionalPropertiesWithComposedSchema = true; + loadDeepObjectIntoItems = false; + importBaseType = false; + addSchemaImportsFromV3SpecLocations = true; + sortModelPropertiesByRequiredFlag = Boolean.TRUE; + sortParamsByRequiredFlag = Boolean.TRUE; + addSuffixToDuplicateOperationNicknames = false; modifyFeatureSet(features -> features + .includeSchemaSupportFeatures( + SchemaSupportFeature.Simple, + SchemaSupportFeature.Composite, + SchemaSupportFeature.Polymorphism, + SchemaSupportFeature.Union, + SchemaSupportFeature.allOf, + SchemaSupportFeature.anyOf, + SchemaSupportFeature.oneOf, + SchemaSupportFeature.not + ) .includeDocumentationFeatures(DocumentationFeature.Readme) - .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( SecurityFeature.BasicAuth, SecurityFeature.BearerToken, SecurityFeature.ApiKey, SecurityFeature.OAuth2_Implicit )) + .includeDataTypeFeatures( + DataTypeFeature.Null, + DataTypeFeature.AnyType, + DataTypeFeature.Uuid + ) .includeGlobalFeatures( - GlobalFeature.ParameterizedServer + GlobalFeature.ParameterizedServer, + GlobalFeature.ParameterStyling ) .excludeGlobalFeatures( GlobalFeature.XMLStructureDefinitions, GlobalFeature.Callbacks, - GlobalFeature.LinkObjects, - GlobalFeature.ParameterStyling + GlobalFeature.LinkObjects ) .excludeSchemaSupportFeatures( - SchemaSupportFeature.Polymorphism ) .excludeParameterFeatures( ParameterFeature.Cookie ) ); - // needed for type object with additionalProperties: false - typeMapping.put("object", "dict"); + + // clear import mapping (from default generator) as python does not use it + // at the moment + importMapping.clear(); + + modelPackage = "model"; + apiPackage = "apis"; + outputFolder = "generated-code" + File.separatorChar + "python"; + + embeddedTemplateDir = templateDir = "python"; + + testFolder = "test"; + + // default HIDE_GENERATION_TIMESTAMP to true + hideGenerationTimestamp = Boolean.TRUE; + + // from https://docs.python.org/3/reference/lexical_analysis.html#keywords + setReservedWordsLowerCase( + Arrays.asList( + // local variable name used in API methods (endpoints) + "all_params", "resource_path", "path_params", "query_params", + "header_params", "form_params", "local_var_files", "body_params", "auth_settings", + // @property + "property", + // python reserved words + "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", + "assert", "else", "if", "pass", "yield", "break", "except", "import", + "print", "class", "exec", "in", "raise", "continue", "finally", "is", + "return", "def", "for", "lambda", "try", "self", "nonlocal", "None", "True", + "False", "async", "await", + // types + "float", "int", "str", "bool", "none_type", "dict", "frozendict", "list", "tuple", "file_type")); + + regexModifiers = new HashMap(); + regexModifiers.put('i', "IGNORECASE"); + regexModifiers.put('l', "LOCALE"); + regexModifiers.put('m', "MULTILINE"); + regexModifiers.put('s', "DOTALL"); + regexModifiers.put('u', "UNICODE"); + regexModifiers.put('x', "VERBOSE"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") + .defaultValue("openapi_client")); + cliOptions.add(new CliOption(CodegenConstants.PROJECT_NAME, "python project name in setup.py (e.g. petstore-api).")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(PACKAGE_URL, "python package URL.")); + // this generator does not use SORT_PARAMS_BY_REQUIRED_FLAG + // this generator uses the following order for endpoint paramters and model properties + // required params + // optional params which are set to unset as their default for method signatures only + // optional params as **kwargs + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) + .defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.SOURCECODEONLY_GENERATION, CodegenConstants.SOURCECODEONLY_GENERATION_DESC) + .defaultValue(Boolean.FALSE.toString())); + cliOptions.add(CliOption.newBoolean(USE_NOSE, "use the nose test framework"). + defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(RECURSION_LIMIT, "Set the recursion limit. If not set, use the system default value.")); + cliOptions.add(CliOption.newBoolean(USE_INLINE_MODEL_RESOLVER, "use the inline model resolver, if true inline complex models will be extracted into components and $refs to them will be used"). + defaultValue(Boolean.FALSE.toString())); + CliOption nonCompliantUseDiscrIfCompositionFails = CliOption.newBoolean(CodegenConstants.NON_COMPLIANT_USE_DISCR_IF_COMPOSITION_FAILS, CodegenConstants.NON_COMPLIANT_USE_DISCR_IF_COMPOSITION_FAILS_DESC); + Map nonCompliantUseDiscrIfCompositionFailsOpts = new HashMap<>(); + nonCompliantUseDiscrIfCompositionFailsOpts.put("true", "If composition fails and a discriminator exists, the composition errors will be ignored and validation will be attempted with the discriminator"); + nonCompliantUseDiscrIfCompositionFailsOpts.put("false", "Composition validation must succeed. Discriminator validation must succeed."); + nonCompliantUseDiscrIfCompositionFails.setEnum(nonCompliantUseDiscrIfCompositionFailsOpts); + + cliOptions.add(nonCompliantUseDiscrIfCompositionFails); + + supportedLibraries.put("urllib3", "urllib3-based client"); + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use: urllib3"); + libraryOption.setDefault(DEFAULT_LIBRARY); + cliOptions.add(libraryOption); + setLibrary(DEFAULT_LIBRARY); + + // Composed schemas can have the 'additionalProperties' keyword, as specified in JSON schema. + // In principle, this should be enabled by default for all code generators. However due to limitations + // in other code generators, support needs to be enabled on a case-by-case basis. + supportsAdditionalPropertiesWithComposedSchema = true; + + // When the 'additionalProperties' keyword is not present in a OAS schema, allow + // undeclared properties. This is compliant with the JSON schema specification. + this.setDisallowAdditionalPropertiesIfNotPresent(false); + + // this may set datatype right for additional properties + instantiationTypes.put("map", "dict"); languageSpecificPrimitives.add("file_type"); languageSpecificPrimitives.add("none_type"); - - // this generator does not use SORT_PARAMS_BY_REQUIRED_FLAG - // this generator uses the following order for endpoint parameters and model properties - // required params/props with no enum of length one - // required params/props with enum of length one (which is used to set a default value as a python named arg value) - // optional params/props with **kwargs in python - cliOptions.remove(4); - - cliOptions.add(new CliOption(CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET, CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET_DESC) - .defaultValue(Boolean.FALSE.toString())); - - cliOptions.add(new CliOption(CodegenConstants.INIT_REQUIRED_VARS, CodegenConstants.INIT_REQUIRED_VARS_DESC) - .defaultValue(Boolean.FALSE.toString())); - - // option to change how we process + set the data in the 'additionalProperties' keyword. - CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean( - CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, - CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.FALSE.toString()); - Map disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>(); - disallowAdditionalPropertiesIfNotPresentOpts.put("false", - "The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications."); - disallowAdditionalPropertiesIfNotPresentOpts.put("true", - "Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. NOTE: "+ - "this option breaks composition and will be removed in 6.0.0" - ); - disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts); - cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt); + typeMapping.put("decimal", "str"); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.STABLE) @@ -139,28 +257,81 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { this.setLegacyDiscriminatorBehavior(false); super.processOpts(); - modelPackage = packageName + "." + "model"; - supportingFiles.add(new SupportingFile("model_utils.mustache", packagePath(), "model_utils.py")); + TemplatingEngineAdapter te = getTemplatingEngine(); + if (te instanceof HandlebarsEngineAdapter) { + HandlebarsEngineAdapter hea = (HandlebarsEngineAdapter) te; + hea.infiniteLoops(true); + hea.setPrettyPrint(true); + } else { + throw new RuntimeException("Only the HandlebarsEngineAdapter is supported for this generator"); + } + TemplatePathLocator commonTemplateLocator = new CommonTemplateContentLocator(); + TemplatePathLocator generatorTemplateLocator = new GeneratorTemplateContentLocator(this); + TemplateManagerOptions templateManagerOptions = new TemplateManagerOptions(this.isEnableMinimalUpdate(),this.isSkipOverwrite()); + templateProcessor = new TemplateManager( + templateManagerOptions, + te, + new TemplatePathLocator[]{generatorTemplateLocator, commonTemplateLocator} + ); + templateExtension = te.getIdentifier(); - // add the models and apis folders - supportingFiles.add(new SupportingFile("__init__models.mustache", packagePath() + File.separatorChar + "models", "__init__.py")); - SupportingFile originalInitModel = supportingFiles.stream() - .filter(sf -> sf.getTemplateFile().equals("__init__model.mustache")) - .reduce((a, b) -> { - throw new IllegalStateException("Multiple elements: " + a + ", " + b); - }) - .orElse(null); - supportingFiles.remove(originalInitModel); - supportingFiles.add(new SupportingFile("__init__model.mustache", packagePath() + File.separatorChar + "model", "__init__.py")); - supportingFiles.add(new SupportingFile("__init__apis.mustache", packagePath() + File.separatorChar + "apis", "__init__.py")); - // Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS. - Map securitySchemeMap = openAPI != null ? - (openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null; - List authMethods = fromSecurity(securitySchemeMap); - if (ProcessUtils.hasHttpSignatureMethods(authMethods)) { - supportingFiles.add(new SupportingFile("signing.mustache", packagePath(), "signing.py")); + String ignoreFileLocation = this.getIgnoreFilePathOverride(); + if (ignoreFileLocation != null) { + final File ignoreFile = new File(ignoreFileLocation); + if (ignoreFile.exists() && ignoreFile.canRead()) { + this.ignoreProcessor = new CodegenIgnoreProcessor(ignoreFile); + } else { + LOGGER.warn("Ignore file specified at {} is not valid. This will fall back to an existing ignore file if present in the output directory.", ignoreFileLocation); + } + } + + if (this.ignoreProcessor == null) { + this.ignoreProcessor = new CodegenIgnoreProcessor(this.getOutputDir()); + } + + modelTemplateFiles.put("model." + templateExtension, ".py"); + /* + This stub file exists to allow pycharm to read and use typing.overload decorators for it to see that + dict_instance["someProp"] is of type SomeClass.properties.someProp + See https://youtrack.jetbrains.com/issue/PY-42137/PyCharm-type-hinting-doesnt-work-well-with-overload-decorator + */ + modelTemplateFiles.put("model_stub." + templateExtension, ".pyi"); + apiTemplateFiles.put("api." + templateExtension, ".py"); + modelTestTemplateFiles.put("model_test." + templateExtension, ".py"); + modelDocTemplateFiles.put("model_doc." + templateExtension, ".md"); + apiDocTemplateFiles.put("api_doc." + templateExtension, ".md"); + + if (StringUtils.isEmpty(System.getenv("PYTHON_POST_PROCESS_FILE"))) { + LOGGER.info("Environment variable PYTHON_POST_PROCESS_FILE not defined so the Python code may not be properly formatted. To define it, try 'export PYTHON_POST_PROCESS_FILE=\"/usr/local/bin/yapf -i\"' (Linux/Mac)"); + LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI)."); + } + + Boolean excludeTests = false; + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } + + if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) { + setProjectName((String) additionalProperties.get(CodegenConstants.PROJECT_NAME)); + } else { + // default: set project based on package name + // e.g. petstore_api (package name) => petstore-api (project name) + setProjectName(packageName.replaceAll("_", "-")); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } + + additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + + if (additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { + excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); } Boolean generateSourceCodeOnly = false; @@ -168,34 +339,115 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { generateSourceCodeOnly = Boolean.valueOf(additionalProperties.get(CodegenConstants.SOURCECODEONLY_GENERATION).toString()); } + if (generateSourceCodeOnly) { + // tests in test + testFolder = packagePath() + File.separatorChar + testFolder; + // api docs in /docs/apis/tags/ + apiDocPath = packagePath() + File.separatorChar + apiDocPath; + // model docs in /docs/models/ + modelDocPath = packagePath() + File.separatorChar + modelDocPath; + } + // make api and model doc path available in templates + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + + if (additionalProperties.containsKey(PACKAGE_URL)) { + setPackageUrl((String) additionalProperties.get(PACKAGE_URL)); + } + + if (additionalProperties.containsKey(USE_NOSE)) { + setUseNose((String) additionalProperties.get(USE_NOSE)); + } + + if (additionalProperties.containsKey(USE_INLINE_MODEL_RESOLVER)) { + setUseInlineModelResolver((String) additionalProperties.get(USE_INLINE_MODEL_RESOLVER)); + } + + // check to see if setRecursionLimit is set and whether it's an integer + if (additionalProperties.containsKey(RECURSION_LIMIT)) { + try { + Integer.parseInt((String) additionalProperties.get(RECURSION_LIMIT)); + } catch (NumberFormatException | NullPointerException e) { + throw new IllegalArgumentException("recursionLimit must be an integer, e.g. 2000."); + } + } + + if (additionalProperties.containsKey(CodegenConstants.NON_COMPLIANT_USE_DISCR_IF_COMPOSITION_FAILS)) { + nonCompliantUseDiscrIfCompositionFails = Boolean.parseBoolean( + additionalProperties.get(CodegenConstants.NON_COMPLIANT_USE_DISCR_IF_COMPOSITION_FAILS).toString() + ); + } + + String readmePath = "README.md"; + String readmeTemplate = "README." + templateExtension; + if (generateSourceCodeOnly) { + readmePath = packagePath() + "_" + readmePath; + readmeTemplate = "README_onlypackage." + templateExtension; + } + supportingFiles.add(new SupportingFile(readmeTemplate, "", readmePath)); + + if (!generateSourceCodeOnly) { + supportingFiles.add(new SupportingFile("tox." + templateExtension, "", "tox.ini")); + supportingFiles.add(new SupportingFile("test-requirements." + templateExtension, "", "test-requirements.txt")); + supportingFiles.add(new SupportingFile("requirements." + templateExtension, "", "requirements.txt")); + supportingFiles.add(new SupportingFile("setup_cfg." + templateExtension, "", "setup.cfg")); + + supportingFiles.add(new SupportingFile("git_push.sh." + templateExtension, "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore." + templateExtension, "", ".gitignore")); + supportingFiles.add(new SupportingFile("travis." + templateExtension, "", ".travis.yml")); + supportingFiles.add(new SupportingFile("gitlab-ci." + templateExtension, "", ".gitlab-ci.yml")); + supportingFiles.add(new SupportingFile("setup." + templateExtension, "", "setup.py")); + } + supportingFiles.add(new SupportingFile("configuration." + templateExtension, packagePath(), "configuration.py")); + supportingFiles.add(new SupportingFile("__init__package." + templateExtension, packagePath(), "__init__.py")); + + // If the package name consists of dots(openapi.client), then we need to create the directory structure like openapi/client with __init__ files. + String[] packageNameSplits = packageName.split("\\."); + String currentPackagePath = ""; + for (int i = 0; i < packageNameSplits.length - 1; i++) { + if (i > 0) { + currentPackagePath = currentPackagePath + File.separatorChar; + } + currentPackagePath = currentPackagePath + packageNameSplits[i]; + supportingFiles.add(new SupportingFile("__init__." + templateExtension, currentPackagePath, "__init__.py")); + } + + supportingFiles.add(new SupportingFile("exceptions." + templateExtension, packagePath(), "exceptions.py")); + + if (Boolean.FALSE.equals(excludeTests)) { + supportingFiles.add(new SupportingFile("__init__." + templateExtension, testFolder, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__." + templateExtension, testFolder + File.separator + "test_models", "__init__.py")); + } + + supportingFiles.add(new SupportingFile("api_client." + templateExtension, packagePath(), "api_client.py")); + + if ("asyncio".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("asyncio/rest." + templateExtension, packagePath(), "rest.py")); + additionalProperties.put("asyncio", "true"); + } else if ("tornado".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("tornado/rest." + templateExtension, packagePath(), "rest.py")); + additionalProperties.put("tornado", "true"); + } else { + supportingFiles.add(new SupportingFile("rest." + templateExtension, packagePath(), "rest.py")); + } + + supportingFiles.add(new SupportingFile("schemas." + templateExtension, packagePath(), "schemas.py")); + + // add the models and apis folders + supportingFiles.add(new SupportingFile("__init__models." + templateExtension, packagePath() + File.separatorChar + "models", "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model." + templateExtension, packagePath() + File.separatorChar + modelPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__apis." + templateExtension, packagePath() + File.separatorChar + apiPackage, "__init__.py")); + // Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS. + Map securitySchemeMap = openAPI != null ? + (openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null; + List authMethods = fromSecurity(securitySchemeMap); + if (ProcessUtils.hasHttpSignatureMethods(authMethods)) { + supportingFiles.add(new SupportingFile("signing." + templateExtension, packagePath(), "signing.py")); + } + // default this to true so the python ModelSimple models will be generated ModelUtils.setGenerateAliasAsModel(true); - LOGGER.info( - "{} is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums", - CodegenConstants.GENERATE_ALIAS_AS_MODEL); - - Boolean attrNoneIfUnset = false; - if (additionalProperties.containsKey(CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET)) { - attrNoneIfUnset = Boolean.valueOf(additionalProperties.get(CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET).toString()); - } - additionalProperties.put("attrNoneIfUnset", attrNoneIfUnset); - - // When the 'additionalProperties' keyword is not present in a OAS schema, allow - // undeclared properties. This is compliant with the JSON schema specification. - // setting this to false is required to have composed schemas work because: - // anyOf SchemaA + SchemaB, requires that props present only in A are accepted in B because in B - // they are additional properties - Boolean disallowAddProps = false; - if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) { - disallowAddProps = Boolean.valueOf(additionalProperties.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()); - } - this.setDisallowAdditionalPropertiesIfNotPresent(disallowAddProps); - - Boolean initRequiredVars = false; - if (additionalProperties.containsKey(CodegenConstants.INIT_REQUIRED_VARS)) { - initRequiredVars = Boolean.valueOf(additionalProperties.get(CodegenConstants.INIT_REQUIRED_VARS).toString()); - } - additionalProperties.put("initRequiredVars", initRequiredVars); + LOGGER.info(CodegenConstants.GENERATE_ALIAS_AS_MODEL + " is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums"); // check library option to ensure only urllib3 is supported if (!DEFAULT_LIBRARY.equals(getLibrary())) { @@ -203,6 +455,264 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { } } + public String packageFilename(List pathSegments) { + String prefix = outputFolder + File.separatorChar + packagePath() + File.separatorChar; + String suffix = pathSegments.stream().collect(Collectors.joining(File.separator)); + return prefix + suffix; + } + + public String filenameFromRoot(List pathSegments) { + String prefix = outputFolder + File.separatorChar; + String suffix = pathSegments.stream().collect(Collectors.joining(File.separator)); + return prefix + suffix; + } + + protected File processTemplateToFile(Map templateData, String templateName, String outputFilename, boolean shouldGenerate, String skippedByOption) throws IOException { + String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar); + File target = new File(adjustedOutputFilename); + if (ignoreProcessor.allowsFile(target)) { + if (shouldGenerate) { + Path outDir = java.nio.file.Paths.get(this.getOutputDir()).toAbsolutePath(); + Path absoluteTarget = target.toPath().toAbsolutePath(); + if (!absoluteTarget.startsWith(outDir)) { + throw new RuntimeException(String.format(Locale.ROOT, "Target files must be generated within the output directory; absoluteTarget=%s outDir=%s", absoluteTarget, outDir)); + } + return this.templateProcessor.write(templateData,templateName, target); + } else { + this.templateProcessor.skip(target.toPath(), String.format(Locale.ROOT, "Skipped by %s options supplied by user.", skippedByOption)); + return null; + } + } else { + this.templateProcessor.ignore(target.toPath(), "Ignored by rule in ignore file."); + return null; + } + } + + @Override + public String apiFilename(String templateName, String tag) { + String suffix = apiTemplateFiles().get(templateName); + return apiFileFolder() + File.separator + toApiFilename(tag) + suffix; + } + + private void generateFiles(List> processTemplateToFileInfos, boolean shouldGenerate, String skippedByOption) { + for (List processTemplateToFileInfo: processTemplateToFileInfos) { + Map templateData = (Map) processTemplateToFileInfo.get(0); + String templateName = (String) processTemplateToFileInfo.get(1); + String outputFilename = (String) processTemplateToFileInfo.get(2); + try { + processTemplateToFile(templateData, templateName, outputFilename, shouldGenerate, skippedByOption); + } catch (IOException e) { + LOGGER.error("Error when writing template file {}", e.toString()); + } + } + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + return toModelName(name) + apiNameSuffix; + } + + /* + I made this method because endpoint parameters not contain a lot of needed metadata + It is very verbose to write all of this info into the api template + This ingests all operations under a tag in the objs input and writes out one file for each endpoint + */ + protected void generateEndpoints(OperationsMap objs) { + if (!(Boolean) additionalProperties.get(CodegenConstants.GENERATE_APIS)) { + return; + } + Paths paths = openAPI.getPaths(); + if (paths == null) { + return; + } + List> pathsFiles = new ArrayList<>(); + List> apisFiles = new ArrayList<>(); + List> testFiles = new ArrayList<>(); + String outputFilename; + + // endpoint tags may not exist in the root of the spec file + // this is allowed per openapi + // because spec tags may be empty ro incomplete, tags are also accumulated from endpoints + List tags = openAPI.getTags(); + if (tags != null) { + for (Tag tag: tags) { + String tagName = tag.getName(); + String tagModuleName = toApiFilename(tagName); + String apiClassname = toApiName(tagName); + tagModuleNameToApiClassname.put(tagModuleName, apiClassname); + String tagEnum = toEnumVarName(tagName, "str"); + enumToTag.put(tagEnum, tagName); + tagEnumToApiClassname.put(tagEnum, apiClassname); + } + } + + OperationMap operations = objs.getOperations(); + List codegenOperations = operations.getOperation(); + HashMap pathModuleToPath = new HashMap<>(); + // paths.some_path.post.py (single endpoint definition) + for (CodegenOperation co: codegenOperations) { + if (co.tags != null) { + for (Tag tag: co.tags) { + String tagName = tag.getName(); + String tagModuleName = toApiFilename(tagName); + String apiClassname = toApiName(tagName); + tagModuleNameToApiClassname.put(tagModuleName, apiClassname); + String tagEnum = toEnumVarName(tagName, "str"); + enumToTag.put(tagEnum, tagName); + tagEnumToApiClassname.put(tagEnum, apiClassname); + } + } + String path = co.path; + String pathModuleName = co.nickname; + if (!pathModuleToPath.containsKey(pathModuleName)) { + pathModuleToPath.put(pathModuleName, path); + } + Map endpointMap = new HashMap<>(); + endpointMap.put("operation", co); + endpointMap.put("imports", co.imports); + endpointMap.put("packageName", packageName); + outputFilename = packageFilename(Arrays.asList("paths", pathModuleName, co.httpMethod + ".py")); + pathsFiles.add(Arrays.asList(endpointMap, "endpoint.handlebars", outputFilename)); + /* + This stub file exists to allow pycharm to read and use typing.overload decorators for it to see that + dict_instance["someProp"] is of type SomeClass.properties.someProp + See https://youtrack.jetbrains.com/issue/PY-42137/PyCharm-type-hinting-doesnt-work-well-with-overload-decorator + */ + String stubOutputFilename = packageFilename(Arrays.asList("paths", pathModuleName, co.httpMethod + ".pyi")); + pathsFiles.add(Arrays.asList(endpointMap, "endpoint_stub.handlebars", stubOutputFilename)); + + Map endpointTestMap = new HashMap<>(); + endpointTestMap.put("operation", co); + endpointTestMap.put("packageName", packageName); + outputFilename = filenameFromRoot(Arrays.asList("test", "test_paths", "test_" + pathModuleName, "test_" + co.httpMethod + ".py")); + testFiles.add(Arrays.asList(endpointTestMap, "api_test.handlebars", outputFilename)); + outputFilename = filenameFromRoot(Arrays.asList("test", "test_paths", "test_" + pathModuleName, "__init__.py")); + testFiles.add(Arrays.asList(new HashMap<>(), "__init__.handlebars", outputFilename)); + } + outputFilename = filenameFromRoot(Arrays.asList("test", "test_paths", "__init__.py")); + testFiles.add(Arrays.asList(new HashMap<>(), "__init__test_paths.handlebars", outputFilename)); + + Map pathValToVar = new LinkedHashMap<>(); + Map pathModuleToApiClassname = new LinkedHashMap<>(); + Map pathEnumToApiClassname = new LinkedHashMap<>(); + for (Map.Entry pathsEntry : paths.entrySet()) { + String path = pathsEntry.getKey(); + String pathEnumVar = toEnumVarName(path, "str"); + pathValToVar.put(path, pathEnumVar); + String apiClassName = toModelName(path); + pathEnumToApiClassname.put(pathEnumVar, apiClassName); + pathModuleToApiClassname.put(toVarName(path), apiClassName); + } + // Note: __init__apis.handlebars is generated as a supporting file + // apis.tag_to_api.py + Map tagToApiMap = new HashMap<>(); + tagToApiMap.put("packageName", packageName); + tagToApiMap.put("apiClassname", "Api"); + tagToApiMap.put("tagModuleNameToApiClassname", tagModuleNameToApiClassname); + tagToApiMap.put("tagEnumToApiClassname", tagEnumToApiClassname); + outputFilename = packageFilename(Arrays.asList("apis", "tag_to_api.py")); + apisFiles.add(Arrays.asList(tagToApiMap, "apis_tag_to_api.handlebars", outputFilename)); + // apis.path_to_api.py + Map allByPathsFileMap = new HashMap<>(); + allByPathsFileMap.put("packageName", packageName); + allByPathsFileMap.put("apiClassname", "Api"); + allByPathsFileMap.put("pathModuleToApiClassname", pathModuleToApiClassname); + allByPathsFileMap.put("pathEnumToApiClassname", pathEnumToApiClassname); + outputFilename = packageFilename(Arrays.asList("apis", "path_to_api.py")); + apisFiles.add(Arrays.asList(allByPathsFileMap, "apis_path_to_api.handlebars", outputFilename)); + // apis.paths.__init__.py + Map initApiTagsMap = new HashMap<>(); + initApiTagsMap.put("packageName", packageName); + initApiTagsMap.put("enumToTag", enumToTag); + outputFilename = packageFilename(Arrays.asList("apis", "tags", "__init__.py")); + apisFiles.add(Arrays.asList(initApiTagsMap, "__init__apis_tags.handlebars", outputFilename)); + + // paths.__init__.py (contains path str enum) + Map initOperationMap = new HashMap<>(); + initOperationMap.put("packageName", packageName); + initOperationMap.put("apiClassname", "Api"); + initOperationMap.put("pathValToVar", pathValToVar); + outputFilename = packageFilename(Arrays.asList("paths", "__init__.py")); + pathsFiles.add(Arrays.asList(initOperationMap, "__init__paths_enum.handlebars", outputFilename)); + // apis.paths.__init__.py + outputFilename = packageFilename(Arrays.asList("apis", "paths", "__init__.py")); + apisFiles.add(Arrays.asList(initOperationMap, "__init__paths.handlebars", outputFilename)); + // paths.some_path.__init__.py + // apis.paths.some_path.py + for (Map.Entry entry: pathModuleToPath.entrySet()) { + String pathModule = entry.getKey(); + String path = entry.getValue(); + String pathVar = pathValToVar.get(path); + Map pathApiMap = new HashMap<>(); + pathApiMap.put("packageName", packageName); + pathApiMap.put("pathModule", pathModule); + pathApiMap.put("apiClassName", "Api"); + pathApiMap.put("pathVar", pathVar); + outputFilename = packageFilename(Arrays.asList("paths", pathModule, "__init__.py")); + pathsFiles.add(Arrays.asList(pathApiMap, "__init__paths_x.handlebars", outputFilename)); + + PathItem pi = openAPI.getPaths().get(path); + String apiClassName = pathEnumToApiClassname.get(pathVar); + Map operationMap = new HashMap<>(); + operationMap.put("packageName", packageName); + operationMap.put("pathModule", pathModule); + operationMap.put("apiClassName", apiClassName); + operationMap.put("pathItem", pi); + outputFilename = packageFilename(Arrays.asList("apis", "paths", pathModule + ".py")); + apisFiles.add(Arrays.asList(operationMap, "apis_path_module.handlebars", outputFilename)); + } + boolean shouldGenerateApis = (boolean) additionalProperties().get(CodegenConstants.GENERATE_APIS); + boolean shouldGenerateApiTests = (boolean) additionalProperties().get(CodegenConstants.GENERATE_API_TESTS); + generateFiles(pathsFiles, shouldGenerateApis, CodegenConstants.APIS); + generateFiles(apisFiles, shouldGenerateApis, CodegenConstants.APIS); + generateFiles(testFiles, shouldGenerateApiTests, CodegenConstants.API_TESTS); + } + + /* + We have a custom version of this method so for composed schemas and object schemas we add properties only if they + are defined in that schema (x.properties). We do this because validation should be done independently in each schema + If properties are hosted into composed schemas, they can collide or incorrectly list themself as required when + they are not. + */ + @Override + protected void addVarsRequiredVarsAdditionalProps(Schema schema, IJsonSchemaValidationProperties property){ + setAddProps(schema, property); + if (ModelUtils.isAnyType(schema) && supportsAdditionalPropertiesWithComposedSchema) { + // if anyType schema has properties then add them + if (schema.getProperties() != null && !schema.getProperties().isEmpty()) { + if (schema instanceof ComposedSchema) { + ComposedSchema cs = (ComposedSchema) schema; + if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { + LOGGER.warn("'oneOf' is intended to include only the additional optional OAS extension discriminator object. " + + "For more details, see https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.section.9.2.1.3 and the OAS section on 'Composition and Inheritance'."); + } + } + HashSet requiredVars = new HashSet<>(); + if (schema.getRequired() != null) { + requiredVars.addAll(schema.getRequired()); + } + addVars(property, property.getVars(), schema.getProperties(), requiredVars); + } + addRequiredVarsMap(schema, property); + return; + } else if (ModelUtils.isTypeObjectSchema(schema)) { + HashSet requiredVars = new HashSet<>(); + if (schema.getRequired() != null) { + requiredVars.addAll(schema.getRequired()); + property.setHasRequired(true); + } + addVars(property, property.getVars(), schema.getProperties(), requiredVars); + if (property.getVars() != null && !property.getVars().isEmpty()) { + property.setHasVars(true); + } + } + addRequiredVarsMap(schema, property); + return; + } + /** * Configures a friendly name for the generator. This will be used by the * generator to select the library with the -g flag. @@ -214,6 +724,29 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { return "python"; } + @Override + public String getHelp() { + String newLine = System.getProperty("line.separator"); + return String.join("
        ", + "Generates a Python client library", + "", + "Features in this generator:", + "- type hints on endpoints and model creation", + "- model parameter names use the spec defined keys and cases", + "- robust composition (oneOf/anyOf/allOf/not) where payload data is stored in one instance only", + "- endpoint parameter names use the spec defined keys and cases", + "- inline schemas are supported at any location including composition", + "- multiple content types supported in request body and response bodies", + "- run time type checking", + "- Sending/receiving decimals as strings supported with type:string format: number -> DecimalSchema", + "- Sending/receiving uuids as strings supported with type:string format: uuid -> UUIDSchema", + "- quicker load time for python modules (a single endpoint can be imported and used without loading others)", + "- all instances of schemas dynamically inherit from all matching schemas so one can use isinstance to check if validation passed", + "- composed schemas with type constraints supported (type:object + oneOf/anyOf/allOf)", + "- schemas are not coerced/cast. For example string + date are both stored as string, and there is a date accessor", + " - Exceptions: int/float is stored as Decimal, When receiving data from headers it will start as str and may need to be cast for example to int"); + } + @Override public Schema unaliasSchema(Schema schema) { Map allSchemas = ModelUtils.getSchemas(openAPI); @@ -262,11 +795,10 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { // free form object (type: object) if (ModelUtils.hasValidation(ref)) { return schema; - } else if (!getAllOfDescendants(simpleRef, openAPI).isEmpty()) { + } else if (getAllOfDescendants(simpleRef, openAPI).size() > 0) { return schema; - } else { - return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); } + return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); } } else if (ModelUtils.hasValidation(ref)) { // non object non array non map schemas that have validations @@ -275,6 +807,10 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { // - preserve the validations in that model class in python // - use those validations when we use this schema in composed oneOf schemas return schema; + } else if (Boolean.TRUE.equals(ref.getNullable()) && ref.getEnum() == null) { + // non enum primitive with nullable True + // we make these models so instances of this will be subclasses of this model + return schema; } else { return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); } @@ -289,14 +825,14 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { try { date = (OffsetDateTime) dateValue; } catch (ClassCastException e) { - LOGGER.warn("Invalid `date` format for value {}", dateValue); + LOGGER.warn("Invalid `date` format for value {}", dateValue.toString()); date = ((Date) dateValue).toInstant().atOffset(ZoneOffset.UTC); } strValue = date.format(iso8601Date); } else { strValue = dateValue.toString(); } - return "dateutil_parser('" + strValue + "').date()"; + return strValue; } public String pythonDateTime(Object dateTimeValue) { @@ -306,14 +842,14 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { try { dateTime = (OffsetDateTime) dateTimeValue; } catch (ClassCastException e) { - LOGGER.warn("Invalid `date-time` format for value {}", dateTimeValue); + LOGGER.warn("Invalid `date-time` format for value {}", dateTimeValue.toString()); dateTime = ((Date) dateTimeValue).toInstant().atOffset(ZoneOffset.UTC); } strValue = dateTime.format(iso8601DateTime); } else { strValue = dateTimeValue.toString(); } - return "dateutil_parser('" + strValue + "')"; + return strValue; } /** @@ -324,15 +860,9 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { */ @Override public String toDefaultValue(Schema p) { - // if a variable has no default set and only has one allowed value - // using enum of length == 1 we use that value. Server/client usage: - // python servers: should only use default values for optional params - // python clients: should only use default values for required params Object defaultObject = null; if (p.getDefault() != null) { defaultObject = p.getDefault(); - } else if (p.getEnum() != null && p.getEnum().size() == 1) { - defaultObject = p.getEnum().get(0); } if (defaultObject == null) { @@ -347,7 +877,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { } else if (ModelUtils.isStringSchema(p) && !ModelUtils.isByteArraySchema(p) && !ModelUtils.isBinarySchema(p) && !ModelUtils.isFileSchema(p) && !ModelUtils.isUUIDSchema(p) && !ModelUtils.isEmailSchema(p)) { defaultValue = ensureQuotes(defaultValue); } else if (ModelUtils.isBooleanSchema(p)) { - if (!Boolean.valueOf(defaultValue)) { + if (Boolean.valueOf(defaultValue) == false) { defaultValue = "False"; } else { defaultValue = "True"; @@ -359,7 +889,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { @Override public String toModelImport(String name) { // name looks like Cat - return "from " + modelPackage() + "." + toModelFilename(name) + " import " + toModelName(name); + return "from " + packagePath() + "." + modelPackage() + "." + toModelFilename(name) + " import " + toModelName(name); } @Override @@ -372,7 +902,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { OperationMap val = objs.getOperations(); List operations = val.getOperation(); for (CodegenOperation operation : operations) { - if (operation.imports.isEmpty()) { + if (operation.imports.size() == 0) { continue; } String[] modelNames = operation.imports.toArray(new String[0]); @@ -381,6 +911,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { operation.imports.add(toModelImport(modelName)); } } + generateEndpoints(objs); return objs; } @@ -392,46 +923,99 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { * this means that the generated client does not use these models * because they are not used we do not write them * - fix the model imports, go from model name to the full import string with toModelImport + globalImportFixer + * Also cleans the test folder if test cases exist and the testFolder is set because the tests are autogenerated * - * @param objs a map going from the model name to an object holding the model info + * @param objs a map going from the model name to a object hoding the model info * @return the updated objs */ @Override public Map postProcessAllModels(Map objs) { super.postProcessAllModels(objs); - List modelsToRemove = new ArrayList<>(); + boolean anyModelContainsTestCases = false; Map allDefinitions = ModelUtils.getSchemas(this.openAPI); for (String schemaName : allDefinitions.keySet()) { - Schema refSchema = new Schema().$ref("#/components/schemas/" + schemaName); - Schema unaliasedSchema = unaliasSchema(refSchema); String modelName = toModelName(schemaName); - if (unaliasedSchema.get$ref() == null) { - modelsToRemove.add(modelName); - } else { - ModelsMap objModel = objs.get(modelName); - if (objModel != null) { // to avoid form parameter's models that are not generated (skipFormModel=true) - for (ModelMap model : objModel.getModels()) { - CodegenModel cm = model.getModel(); - String[] importModelNames = cm.imports.toArray(new String[0]); - cm.imports.clear(); - for (String importModelName : importModelNames) { - cm.imports.add(toModelImport(importModelName)); - String globalImportFixer = "globals()['" + importModelName + "'] = " + importModelName; - cm.imports.add(globalImportFixer); - } - } + ModelsMap objModel = objs.get(modelName); + if (objModel == null) { + // to avoid form parameter's models that are not generated (skipFormModel=true) + continue; + } + for (ModelMap model : objModel.getModels()) { + CodegenModel cm = model.getModel(); + if (cm.testCases != null && !cm.testCases.isEmpty()) { + anyModelContainsTestCases = true; + } + String[] importModelNames = cm.imports.toArray(new String[0]); + cm.imports.clear(); + for (String importModelName : importModelNames) { + cm.imports.add(toModelImport(importModelName)); } } } + boolean testFolderSet = testFolder != null; + if (testFolderSet && anyModelContainsTestCases) { + // delete the test folder because tests there will be autogenerated + String testPath = outputFolder + File.separatorChar + testFolder; + File testDirectory = new File(testPath); + try { + FileUtils.cleanDirectory(testDirectory); + } catch (IOException e) { + LOGGER.info("Unable to delete the test folder because of exception=" + e.toString()); + } - for (String modelName : modelsToRemove) { - objs.remove(modelName); } return objs; } + public CodegenParameter fromParameter(Parameter parameter, Set imports) { + CodegenParameter cp = super.fromParameter(parameter, imports); + if (parameter.getStyle() != null) { + switch(parameter.getStyle()) { + case MATRIX: + cp.style = "MATRIX"; + break; + case LABEL: + cp.style = "LABEL"; + break; + case FORM: + cp.style = "FORM"; + break; + case SIMPLE: + cp.style = "SIMPLE"; + break; + case SPACEDELIMITED: + cp.style = "SPACE_DELIMITED"; + break; + case PIPEDELIMITED: + cp.style = "PIPE_DELIMITED"; + break; + case DEEPOBJECT: + cp.style = "DEEP_OBJECT"; + break; + } + } + // clone this so we can change some properties on it + CodegenProperty schemaProp = cp.getSchema(); + // parameters may have valid python names like some_val or invalid ones like Content-Type + // we always set nameInSnakeCase to null so special handling will not be done for these names + // invalid python names will be handled in python by using a TypedDict which will allow us to have a type hint + // for keys that cannot be variable names to the schema baseName + if (schemaProp != null) { + schemaProp = schemaProp.clone(); + schemaProp.nameInSnakeCase = null; + schemaProp.baseName = toModelName(cp.baseName) + "Schema"; + cp.setSchema(schemaProp); + } + return cp; + } + + private boolean isValidPythonVarOrClassName(String name) { + return name.matches("^[_a-zA-Z][_a-zA-Z0-9]*$"); + } + + /** * Convert OAS Property object to Codegen Property object * We have a custom version of this method to always set allowableValues.enumVars on all enum variables @@ -439,24 +1023,72 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { * This method is used by fromResponse * * @param name name of the property - * @param p OAS property object + * @param p OAS property schema + * @param required true if the property is required in the next higher object schema, false otherwise + * @param schemaIsFromAdditionalProperties true if the property is defined by additional properties schema * @return Codegen Property object */ @Override - public CodegenProperty fromProperty(String name, Schema p, boolean required) { - CodegenProperty cp = super.fromProperty(name, p, required); + public CodegenProperty fromProperty(String name, Schema p, boolean required, boolean schemaIsFromAdditionalProperties) { + // fix needed for values with /n /t etc in them + String fixedName = handleSpecialCharacters(name); + CodegenProperty cp = super.fromProperty(fixedName, p, required, schemaIsFromAdditionalProperties); + + if (cp.isAnyType && cp.isNullable) { + cp.isNullable = false; + } + if (cp.isNullable && cp.complexType == null) { + cp.setIsNull(true); + cp.isNullable = false; + cp.setHasMultipleTypes(true); + } + if (p.getPattern() != null) { + postProcessPattern(p.getPattern(), cp.vendorExtensions); + } + // if we have a property that has a difficult name, either: + // 1. name is reserved, like class int float + // 2. name is invalid in python like '3rd' or 'Content-Type' + // set cp.nameInSnakeCase to a value so we can tell that we are in this use case + // we handle this in the schema templates + // templates use its presence to handle these badly named variables / keys + if ((isReservedWord(cp.baseName) || !isValidPythonVarOrClassName(cp.baseName)) && !cp.baseName.equals(cp.name)) { + cp.nameInSnakeCase = cp.name; + } else { + cp.nameInSnakeCase = null; + } if (cp.isEnum) { updateCodegenPropertyEnum(cp); } - if (cp.isPrimitiveType && p.get$ref() != null) { + Schema unaliasedSchema = unaliasSchema(p); + if (cp.isPrimitiveType && unaliasedSchema.get$ref() != null) { cp.complexType = cp.dataType; } - if (cp.isArray && cp.complexType == null && cp.mostInnerItems.complexType != null) { - cp.complexType = cp.mostInnerItems.complexType; - } + setAdditionalPropsAndItemsVarNames(cp); return cp; } + private void setAdditionalPropsAndItemsVarNames(IJsonSchemaValidationProperties item) { + if (item.getAdditionalProperties() != null) { + item.getAdditionalProperties().setBaseName("additional_properties"); + } + if (item.getItems() != null) { + item.getItems().setBaseName("items"); + } + } + + /** + * checks if the data should be classified as "string" in enum + * e.g. double in C# needs to be double-quoted (e.g. "2.8") by treating it as a string + * In the future, we may rename this function to "isEnumString" + * + * @param dataType data type + * @return true if it's a enum string + */ + @Override + public boolean isDataTypeString(String dataType) { + return "str".equals(dataType); + } + /** * Update codegen property's enum by adding "enumVars" (with name and value) * @@ -502,7 +1134,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { * We have a custom version of this method to produce links to models when they are * primitive type (not map, not array, not object) and include validations or are enums * - * @param body request body + * @param body requesst body * @param imports import collection * @param bodyParameterName body parameter name * @return the resultant CodegenParameter @@ -510,6 +1142,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { @Override public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName); + cp.baseName = "body"; Schema schema = ModelUtils.getSchemaFromRequestBody(body); if (schema.get$ref() == null) { return cp; @@ -532,6 +1165,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { * With this customization, we ensure that when schemas are passed to getSchemaType * - if they have ref in them they are a model * - if they do not have ref in them they are not a model + * and code is also customized to allow anyType request body schemas * * @param codegenParameter the body parameter * @param name model schema ref key in components @@ -549,7 +1183,55 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { forceSimpleRef = true; } } - super.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, forceSimpleRef); + + CodegenModel codegenModel = null; + if (StringUtils.isNotBlank(name)) { + schema.setName(name); + codegenModel = fromModel(name, schema); + } + + if (codegenModel != null && (codegenModel.hasVars || forceSimpleRef)) { + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = codegenModel.classname; + } else { + codegenParameter.baseName = bodyParameterName; + } + codegenParameter.paramName = toParamName(codegenParameter.baseName); + codegenParameter.baseType = codegenModel.classname; + codegenParameter.dataType = getTypeDeclaration(codegenModel.classname); + codegenParameter.description = codegenModel.description; + codegenParameter.isNullable = codegenModel.isNullable; + } else { + CodegenProperty codegenProperty = fromProperty("property", schema, false); + + if (ModelUtils.isMapSchema(schema)) {// http body is map + // LOGGER.error("Map should be supported. Please report to openapi-generator github repo about the issue."); + } else if (codegenProperty != null) { + String codegenModelName, codegenModelDescription; + + if (codegenModel != null) { + codegenModelName = codegenModel.classname; + codegenModelDescription = codegenModel.description; + } else { + codegenModelName = "anyType"; + codegenModelDescription = ""; + } + + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = codegenModelName; + } else { + codegenParameter.baseName = bodyParameterName; + } + + codegenParameter.paramName = toParamName(codegenParameter.baseName); + codegenParameter.baseType = codegenModelName; + codegenParameter.dataType = getTypeDeclaration(codegenModelName); + codegenParameter.description = codegenModelDescription; + } + + // set nullable + setParameterNullable(codegenParameter, codegenProperty); + } } @@ -565,38 +1247,145 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { // our enum var names are keys in a python dict, so change spaces to underscores if (value.length() == 0) { return "EMPTY"; + } else if (value.equals("null")) { + return "NONE"; } - String var = value.replaceAll("\\s+", "_").toUpperCase(Locale.ROOT); - return var; + String intPattern = "^[-\\+]?\\d+$"; + String floatPattern = "^[-\\+]?\\d+\\.\\d+$"; + Boolean intMatch = Pattern.matches(intPattern, value); + Boolean floatMatch = Pattern.matches(floatPattern, value); + if (intMatch || floatMatch) { + String plusSign = "^\\+.+"; + String negSign = "^-.+"; + if (Pattern.matches(plusSign, value)) { + value = value.replace("+", "POSITIVE_"); + } else if (Pattern.matches(negSign, value)) { + value = value.replace("-", "NEGATIVE_"); + } else { + value = "POSITIVE_" + value; + } + if (floatMatch) { + value = value.replace(".", "_PT_"); + } + return value; + } + // Replace " " with _ + String usedValue = value.replaceAll("\\s+", "_"); + // strip first character if it is invalid + usedValue = usedValue.replaceAll("^[^_a-zA-Z]", ""); + // Replace / with _ for path enums + usedValue = usedValue.replaceAll("/", "_"); + // Replace . with _ for tag enums + usedValue = usedValue.replaceAll("\\.", "_"); + // add underscore at camelCase locations + String regex = "([a-z])([A-Z]+)"; + String replacement = "$1_$2"; + usedValue = usedValue.replaceAll(regex, replacement); + // Replace invalid characters with empty space + usedValue = usedValue.replaceAll("[^_a-zA-Z0-9]*", ""); + // uppercase + usedValue = usedValue.toUpperCase(Locale.ROOT); + + if (usedValue.length() == 0) { + for (int i = 0; i < value.length(); i++){ + Character c = value.charAt(i); + String charName = Character.getName(c.hashCode()); + usedValue += charNameToVarName(charName); + } + // remove trailing _ + usedValue = usedValue.replaceAll("[_]$", ""); + } + return usedValue; } /** - * Return the enum value in the language specified format - * e.g. status becomes "status" + * Replace - and " " with _ + * Remove SIGN * - * @param value enum variable name - * @param datatype data type - * @return the sanitized value for enum + * @param charName + * @return */ - public String toEnumValue(String value, String datatype) { - if ("int".equals(datatype) || "float".equals(datatype)) { - return value; - } else if ("bool".equals(datatype)) { - return value.substring(0, 1).toUpperCase(Locale.ROOT) + value.substring(1); - } else { - return ensureQuotes(value); - } + private String charNameToVarName(String charName) { + String varName = charName.replaceAll("[\\-\\s]", "_"); + varName = varName.replaceAll("SIGN", ""); + return varName; } - @Override - public void postProcessModelProperty(CodegenModel model, CodegenProperty p) { - postProcessPattern(p.pattern, p.vendorExtensions); - // set property.complexType so the model docs will link to the ClassName.md - if (p.complexType == null && p.isArray && p.mostInnerItems.complexType != null && !languageSpecificPrimitives.contains(p.mostInnerItems.complexType)) { - // fix ListContainers - p.complexType = p.mostInnerItems.complexType; + protected List> buildEnumVars(List values, String dataType) { + List> enumVars = new ArrayList<>(); + int truncateIdx = 0; + + if (isRemoveEnumValuePrefix()) { + String commonPrefix = findCommonPrefixOfVars(values); + truncateIdx = commonPrefix.length(); } + + for (Object value : values) { + Map enumVar = new HashMap<>(); + String enumName; + if (truncateIdx == 0) { + enumName = String.valueOf(value); + } else { + enumName = value.toString().substring(truncateIdx); + if (enumName.isEmpty()) { + enumName = value.toString(); + } + } + + enumVar.put("name", toEnumVarName(enumName, dataType)); + if (value instanceof Integer) { + enumVar.put("value", value); + } else if (value instanceof Double) { + enumVar.put("value", value); + } else if (value instanceof Long) { + enumVar.put("value", value); + } else if (value instanceof Float) { + enumVar.put("value", value); + } else if (value instanceof BigDecimal) { + enumVar.put("value", value); + } else if (value == null) { + enumVar.put("value", "schemas.NoneClass.NONE"); + } else if (value instanceof Boolean) { + if (value.equals(Boolean.TRUE)) { + enumVar.put("value", "schemas.BoolClass.TRUE"); + } else { + enumVar.put("value", "schemas.BoolClass.FALSE"); + } + } else { + String fixedValue = (String) processTestExampleData(value); + enumVar.put("value", ensureQuotes(fixedValue)); + } + enumVar.put("isString", isDataTypeString(dataType)); + enumVars.add(enumVar); + } + + if (enumUnknownDefaultCase) { + // If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response. + // With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case. + Map enumVar = new HashMap<>(); + String enumName = enumUnknownDefaultCaseName; + + String enumValue; + if (isDataTypeString(dataType)) { + enumValue = enumUnknownDefaultCaseName; + } else { + // This is a dummy value that attempts to avoid collisions with previously specified cases. + // Int.max / 192 + // The number 192 that is used to calculate this random value, is the Swift Evolution proposal for frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // Since this functionality was born in the Swift 5 generator and latter on broth to all generators + // https://github.com/OpenAPITools/openapi-generator/pull/11013 + enumValue = String.valueOf(11184809); + } + + enumVar.put("name", toEnumVarName(enumName, dataType)); + enumVar.put("value", toEnumValue(enumValue, dataType)); + enumVar.put("isString", isDataTypeString(dataType)); + enumVars.add(enumVar); + } + + return enumVars; } @Override @@ -608,66 +1397,6 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { } } - private void fixComposedSchemaRequiredVars(Schema schema, CodegenModel result) { - // for composed schema models, if the required properties are only from oneOf or anyOf models - // remove them from the composed schema's required vars - // for composed schemas our code adds oneOf and anyOf required properties to - // the composed schema's required properties - // but they should not be required because if we have ComposedSchema: oneOf -schemaA -schemaB - // and the required props are only in schemaB, we do not need to use them when making an instance of - // ComposedSchema + schemaA - ComposedSchema cs = (ComposedSchema) schema; - - // these are the properties that are from properties in self cs or cs allOf - Map selfProperties = new LinkedHashMap<>(); - List selfRequired = new ArrayList<>(); - - // these are the properties that are from properties in cs oneOf or cs anyOf - Map otherProperties = new LinkedHashMap<>(); - List otherRequired = new ArrayList<>(); - - List oneOfanyOfSchemas = new ArrayList<>(); - List oneOf = cs.getOneOf(); - if (oneOf != null) { - oneOfanyOfSchemas.addAll(oneOf); - } - List anyOf = cs.getAnyOf(); - if (anyOf != null) { - oneOfanyOfSchemas.addAll(anyOf); - } - for (Schema sc : oneOfanyOfSchemas) { - Schema refSchema = ModelUtils.getReferencedSchema(this.openAPI, sc); - addProperties(otherProperties, otherRequired, refSchema, new HashSet<>()); - } - Set otherRequiredSet = new HashSet<>(otherRequired); - - List allOf = cs.getAllOf(); - if ((schema.getProperties() != null && !schema.getProperties().isEmpty()) || allOf != null) { - // NOTE: this function also adds the allOf properties inside schema - addProperties(selfProperties, selfRequired, schema, new HashSet<>()); - } - if (result.discriminator != null) { - selfRequired.add(result.discriminator.getPropertyBaseName()); - } - Set selfRequiredSet = new HashSet<>(selfRequired); - - List reqVars = result.getRequiredVars(); - List reqVarsThatMustBeOptional = new ArrayList<>(); - if (reqVars != null) { - for (CodegenProperty cp : reqVars) { - String propName = cp.baseName; - if (otherRequiredSet.contains(propName) && !selfRequiredSet.contains(propName)) { - cp.required = false; - reqVarsThatMustBeOptional.add(cp); - } - } - } - for (CodegenProperty cp : reqVarsThatMustBeOptional) { - result.getRequiredVars().remove(cp); - result.getOptionalVars().add(cp); - } - } - /** * Sets the value of the 'model.parent' property in CodegenModel * We have a custom version of this function so we can add the dataType on the ArrayModel @@ -676,10 +1405,76 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { protected void addParentContainer(CodegenModel model, String name, Schema schema) { super.addParentContainer(model, name, schema); - List referencedModelNames = new ArrayList<>(); + List referencedModelNames = new ArrayList(); model.dataType = getTypeString(schema, "", "", referencedModelNames); } + protected String toTestCaseName(String specTestCaseName) { + return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, specTestCaseName); + } + + protected String handleSpecialCharacters(String value) { + // handles escape characters and the like + String stringValue = value; + String backslash = "\\"; + if (stringValue.contains(backslash)) { + stringValue = stringValue.replace(backslash, "\\\\"); + } + String nullChar = "\0"; + if (stringValue.contains(nullChar)) { + stringValue = stringValue.replace(nullChar, "\\x00"); + } + String doubleQuoteChar = "\""; + if (stringValue.contains(doubleQuoteChar)) { + stringValue = stringValue.replace(doubleQuoteChar, "\\\""); + } + String lineSep = System.lineSeparator(); + if (stringValue.contains(lineSep)) { + stringValue = stringValue.replace(lineSep, "\\n"); + } + String carriageReturn = "\r"; + if (stringValue.contains(carriageReturn)) { + stringValue = stringValue.replace(carriageReturn, "\\r"); + } + String tab = "\t"; + if (stringValue.contains(tab)) { + stringValue = stringValue.replace(tab, "\\t"); + } + String formFeed = "\f"; + if (stringValue.contains(formFeed)) { + stringValue = stringValue.replace(formFeed, "\\f"); + } + return stringValue; + } + + protected Object processTestExampleData(Object value) { + if (value instanceof Integer){ + return value; + } else if (value instanceof Double || value instanceof Float || value instanceof Boolean){ + return value; + } else if (value instanceof String) { + return handleSpecialCharacters((String) value); + } else if (value instanceof LinkedHashMap) { + LinkedHashMap fixedValues = new LinkedHashMap(); + for (Map.Entry entry: ((LinkedHashMap) value).entrySet()) { + String entryKey = (String) processTestExampleData(entry.getKey()); + Object entryValue = processTestExampleData(entry.getValue()); + fixedValues.put(entryKey, entryValue); + } + return fixedValues; + } else if (value instanceof ArrayList) { + ArrayList fixedValues = (ArrayList) value; + for (int i = 0; i < fixedValues.size(); i++) { + Object item = processTestExampleData(fixedValues.get(i)); + fixedValues.set(i, item); + } + return fixedValues; + } else if (value == null) { + return value; + } + return value; + } + /** * Convert OAS Model object to Codegen Model object * We have a custom version of this method so we can: @@ -693,45 +1488,24 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { @Override public CodegenModel fromModel(String name, Schema sc) { CodegenModel cm = super.fromModel(name, sc); - if (cm.requiredVars.size() > 0 && (cm.oneOf.size() > 0 || cm.anyOf.size() > 0)) { - fixComposedSchemaRequiredVars(sc, cm); + if (sc.getPattern() != null) { + postProcessPattern(sc.getPattern(), cm.vendorExtensions); + String pattern = (String) cm.vendorExtensions.get("x-regex"); + cm.setPattern(pattern); } - ArrayList> listOfLists = new ArrayList<>(); - listOfLists.add(cm.requiredVars); - listOfLists.add(cm.optionalVars); - for (List cpList : listOfLists) { - for (CodegenProperty cp : cpList) { - // sets regex values - postProcessModelProperty(cm, cp); - } + if (cm.isNullable) { + cm.setIsNull(true); + cm.isNullable = false; + cm.setHasMultipleTypes(true); } Boolean isNotPythonModelSimpleModel = (ModelUtils.isComposedSchema(sc) || ModelUtils.isObjectSchema(sc) || ModelUtils.isMapSchema(sc)); + setAdditionalPropsAndItemsVarNames(cm); if (isNotPythonModelSimpleModel) { return cm; } - // Use cases for default values / enums of length one - // 1. no default exists - // schema does not contain default - // cm.defaultValue unset, cm.hasRequired = true - // 2. spec has a default - // schema contains default - // cm.defaultValue set, cm.hasRequired = false - // different value here to differentiate between use case 3 below - // This defaultValue is used when a consumer (client or server) lacks the input argument, defaultValue will be used - // 3. only one value is allowed in an enum - // schema does not contain default - // cm.defaultValue set, cm.hasRequired = false - // because we know what value needs to be set so the user doesn't need to input it - // This defaultValue is used in the client and is sent to the server String defaultValue = toDefaultValue(sc); - if (sc.getDefault() == null && defaultValue == null) { - cm.hasRequired = true; - } else if (sc.getDefault() != null) { + if (sc.getDefault() != null) { cm.defaultValue = defaultValue; - cm.hasRequired = false; - } else if (defaultValue != null && cm.defaultValue == null) { - cm.defaultValue = defaultValue; - cm.hasRequired = false; } return cm; } @@ -763,62 +1537,6 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { return null; } - @Override - protected Schema getAdditionalProperties(Schema schema) { - /* - Use cases: - 1. addProps set to schema in spec: return that schema - 2. addProps unset w/ getDisallowAdditionalPropertiesIfNotPresent -> null - 3. addProps unset w/ getDisallowAdditionalPropertiesIfNotPresent=False -> new Schema() - 4. addProps true -> new Schema() NOTE: v3 only - 5. addprops false -> null NOTE: v3 only - */ - Object addProps = schema.getAdditionalProperties(); - if (addProps instanceof Schema) { - return (Schema) addProps; - } - if (addProps == null) { - // When reaching this code path, this should indicate the 'additionalProperties' keyword is - // not present in the OAS schema. This is true for OAS 3.0 documents. - // However, the parsing logic is broken for OAS 2.0 documents because of the - // https://github.com/swagger-api/swagger-parser/issues/1369 issue. - // When OAS 2.0 documents are parsed, the swagger-v2-converter ignores the 'additionalProperties' - // keyword if the value is boolean. That means codegen is unable to determine whether - // additional properties are allowed or not. - // - // The original behavior was to assume additionalProperties had been set to false. - if (getDisallowAdditionalPropertiesIfNotPresent()) { - // If the 'additionalProperties' keyword is not present in a OAS schema, - // interpret as if the 'additionalProperties' keyword had been set to false. - // This is NOT compliant with the JSON schema specification. It is the original - // 'openapi-generator' behavior. - return null; - } - /* - // The disallowAdditionalPropertiesIfNotPresent CLI option has been set to true, - // but for now that only works with OAS 3.0 documents. - // The new behavior does not work with OAS 2.0 documents. - if (extensions == null || !extensions.containsKey(EXTENSION_OPENAPI_DOC_VERSION)) { - // Fallback to the legacy behavior. - return null; - } - // Get original swagger version from OAS extension. - // Note openAPI.getOpenapi() is always set to 3.x even when the document - // is converted from a OAS/Swagger 2.0 document. - // https://github.com/swagger-api/swagger-parser/pull/1374 - SemVer version = new SemVer((String)extensions.get(EXTENSION_OPENAPI_DOC_VERSION)); - if (version.major != 3) { - return null; - } - */ - } - if (addProps == null || (addProps instanceof Boolean && (Boolean) addProps)) { - // Return empty schema to allow any type - return new Schema(); - } - return null; - } - /** * Return a string representation of the Python types for the specified OAS schema. * Primitive types in the OAS specification are implemented in Python using the corresponding @@ -858,41 +1576,30 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { } } if (ModelUtils.isAnyType(p)) { - // for v2 specs only, swagger-parser never generates an AnyType schemas even though it should generate them - // https://github.com/swagger-api/swagger-parser/issues/1378 - // switch to v3 if you need AnyType to work return prefix + "bool, date, datetime, dict, float, int, list, str, none_type" + suffix; } - String originalSpecVersion = "X"; - if (this.openAPI.getExtensions() != null && this.openAPI.getExtensions().containsKey("x-original-swagger-version")) { - originalSpecVersion = (String) this.openAPI.getExtensions().get("x-original-swagger-version"); - originalSpecVersion = originalSpecVersion.substring(0, 1); - - } - Boolean v2DisallowAdditionalPropertiesIfNotPresentAddPropsNullCase = (getAdditionalProperties(p) == null && this.getDisallowAdditionalPropertiesIfNotPresent() && originalSpecVersion.equals("2")); - Schema emptySchema = new Schema(); - Boolean v2WithCompositionAddPropsAnyTypeSchemaCase = (getAdditionalProperties(p) != null && emptySchema.equals(getAdditionalProperties(p)) && originalSpecVersion.equals("2")); - if (isFreeFormObject(p) && (v2DisallowAdditionalPropertiesIfNotPresentAddPropsNullCase || v2WithCompositionAddPropsAnyTypeSchemaCase)) { - // for v2 specs only, input AnyType schemas (type unset) or schema {} results in FreeFromObject schemas - // per https://github.com/swagger-api/swagger-parser/issues/1378 - // v2 spec uses cases - // 1. AnyType schemas - // 2. type object schema with no other info - // use case 1 + 2 -> both become use case 1 - // switch to v3 if you need use cases 1 + 2 to work correctly - return prefix + "bool, date, datetime, dict, float, int, list, str, none_type" + fullSuffix; - } // Resolve $ref because ModelUtils.isXYZ methods do not automatically resolve references. if (ModelUtils.isNullable(ModelUtils.getReferencedSchema(this.openAPI, p))) { fullSuffix = ", none_type" + suffix; } - Boolean v3WithCompositionAddPropsAnyTypeSchemaCase = (getAdditionalProperties(p) != null && emptySchema.equals(getAdditionalProperties(p)) && originalSpecVersion.equals("3")); - if (isFreeFormObject(p) && v3WithCompositionAddPropsAnyTypeSchemaCase) { - // v3 code path, use case: type object schema with no other schema info - return prefix + "{str: (bool, date, datetime, dict, float, int, list, str, none_type)}" + fullSuffix; - } else if ((ModelUtils.isMapSchema(p) || "object".equals(p.getType())) && getAdditionalProperties(p) != null) { - Schema inner = getAdditionalProperties(p); - return prefix + "{str: " + getTypeString(inner, "(", ")", referencedModelNames) + "}" + fullSuffix; + if (ModelUtils.isNumberSchema(p)) { + return prefix + "int, float" + fullSuffix; + } else if (ModelUtils.isTypeObjectSchema(p)) { + if (p.getAdditionalProperties() != null && p.getAdditionalProperties().equals(false)) { + if (p.getProperties() == null) { + // type object with no properties and additionalProperties = false, empty dict only + return prefix + "{str: typing.Any}" + fullSuffix; + } else { + // properties only + // TODO add type hints for those properties only as values + return prefix + "{str: typing.Any}" + fullSuffix; + } + } else { + // additionalProperties exists + Schema inner = getAdditionalProperties(p); + return prefix + "{str: " + getTypeString(inner, "(", ")", referencedModelNames) + "}" + fullSuffix; + // TODO add code here to add property values too if they exist + } } else if (ModelUtils.isArraySchema(p)) { ArraySchema ap = (ArraySchema) p; Schema inner = ap.getItems(); @@ -909,8 +1616,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { } else { return prefix + getTypeString(inner, "[", "]", referencedModelNames) + fullSuffix; } - } - if (ModelUtils.isFileSchema(p)) { + } else if (ModelUtils.isFileSchema(p)) { return prefix + "file_type" + fullSuffix; } String baseType = getSchemaType(p); @@ -942,22 +1648,6 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { @Override protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { - Schema addProps = getAdditionalProperties(schema); - if (addProps != null) { - // if AdditionalProperties exists, get its datatype and - // store it in codegenModel.additionalPropertiesType. - // The 'addProps' may be a reference, getTypeDeclaration will resolve - // the reference. - List referencedModelNames = new ArrayList<>(); - getTypeString(addProps, "", "", referencedModelNames); - if (referencedModelNames.size() != 0) { - // Models that are referenced in the 'additionalPropertiesType' keyword - // must be added to the imports. - codegenModel.imports.addAll(referencedModelNames); - } - } - // If addProps is null, the value of the 'additionalProperties' keyword is set - // to false, i.e. no additional properties are allowed. } /** @@ -995,12 +1685,6 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { * @return quoted string */ private String ensureQuotes(String in) { - Pattern pattern = Pattern.compile("\r\n|\r|\n"); - Matcher matcher = pattern.matcher(in); - if (matcher.find()) { - // if a string has a new line in it add triple quotes to make it a python multiline string - return "'''" + in + "'''"; - } String strPattern = "^['\"].*?['\"]$"; if (in.matches(strPattern)) { return in; @@ -1010,14 +1694,14 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { @Override public String toExampleValue(Schema schema) { - Object objExample = getObjectExample(schema); String modelName = getModelName(schema); - return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, Sets.newHashSet()); + Object objExample = getObjectExample(schema); + return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, new ArrayList<>()); } public String toExampleValue(Schema schema, Object objExample) { String modelName = getModelName(schema); - return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, Sets.newHashSet()); + return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, new ArrayList<>()); } private Boolean simpleStringSchema(Schema schema) { @@ -1050,12 +1734,12 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { * @param schema the schema that we need an example for * @param objExample the example that applies to this schema, for now only string example are used * @param indentationLevel integer indentation level that we are currently at - * we assume the indentation amount is 4 spaces times this integer + * we assume the indentaion amount is 4 spaces times this integer * @param prefix the string prefix that we will use when assigning an example for this line * this is used when setting key: value, pairs "key: " is the prefix * and this is used when setting properties like some_property='some_property_example' - * @param exampleLine this is the current line that we are generating an example for, starts at 0 - * we don't indent the 0th line because using the example value looks like: + * @param exampleLine this is the current line that we are generatign an example for, starts at 0 + * we don't indentin the 0th line because using the example value looks like: * prop = ModelName( line 0 * some_property='some_property_example' line 1 * ) line 2 @@ -1063,12 +1747,17 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { * ModelName( line 0 * some_property='some_property_example' line 1 * ) line 2 - * @param seenSchemas This set contains all the schemas passed into the recursive function. It is used to check - * if a schema was already passed into the function and breaks the infinite recursive loop. The - * only schemas that are not added are ones that contain $ref != null + * @param includedSchemas are a list of schemas that we have moved through to get here. If the new schemas that we + * are looking at is in includedSchemas then we have hit a cycle. * @return the string example */ - private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine, Set seenSchemas) { + private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine, List includedSchemas) { + boolean couldHaveCycle = includedSchemas.size() > 0 && potentiallySelfReferencingSchema(schema); + // If we have seen the ContextAwareSchemaNode more than once before, we must be in a cycle. + boolean cycleFound = false; + if (couldHaveCycle) { + cycleFound = includedSchemas.subList(0, includedSchemas.size()-1).stream().anyMatch(s -> schema.equals(s)); + } final String indentionConst = " "; String currentIndentation = ""; String closingIndentation = ""; @@ -1092,43 +1781,83 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { if (objExample != null) { example = objExample.toString(); } - // checks if the current schema has already been passed in. If so, breaks the current recursive pass - if (seenSchemas.contains(schema)) { - if (modelName != null) { - return fullPrefix + closeChars; - } else { - // this is a recursive schema - // need to add a reasonable example to avoid - // infinite recursion - if (ModelUtils.isNullable(schema)) { - // if the schema is nullable, then 'None' is a valid value - return fullPrefix + "None" + closeChars; - } else if (ModelUtils.isArraySchema(schema)) { - // the schema is an array, add an empty array - return fullPrefix + "[]" + closeChars; - } else { - // the schema is an object, make an empty object - return fullPrefix + "{}" + closeChars; - } - } - } - if (null != schema.get$ref()) { Map allDefinitions = ModelUtils.getSchemas(this.openAPI); String ref = ModelUtils.getSimpleRef(schema.get$ref()); Schema refSchema = allDefinitions.get(ref); if (null == refSchema) { - LOGGER.warn("Unable to find referenced schema {}\n", schema.get$ref()); + LOGGER.warn("Unable to find referenced schema " + schema.get$ref() + "\n"); return fullPrefix + "None" + closeChars; } String refModelName = getModelName(schema); - return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine, seenSchemas); - } else if (ModelUtils.isNullType(schema) || ModelUtils.isAnyType(schema)) { + return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine, includedSchemas); + } else if (ModelUtils.isNullType(schema)) { // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, // though this tooling supports it. return fullPrefix + "None" + closeChars; + } else if (ModelUtils.isAnyType(schema)) { + /* + This schema may be a composed schema + TODO generate examples for some of these use cases in the future like + only oneOf without a discriminator + */ + if (cycleFound) { + return ""; + } + Boolean hasProperties = (schema.getProperties() != null && !schema.getProperties().isEmpty()); + CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); + if (ModelUtils.isComposedSchema(schema)) { + if(includedSchemas.contains(schema)) { + return ""; + } + includedSchemas.add(schema); + // complex composed object type schemas not yet handled and the code returns early + if (hasProperties) { + // what if this composed schema defined properties + allOf? + // or items + properties, both a ist and a dict could be accepted as payloads + return fullPrefix + "{}" + closeChars; + } + ComposedSchema cs = (ComposedSchema) schema; + Integer allOfExists = 0; + if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { + allOfExists = 1; + } + Integer anyOfExists = 0; + if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { + anyOfExists = 1; + } + Integer oneOfExists = 0; + if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { + oneOfExists = 1; + } + if (allOfExists + anyOfExists + oneOfExists > 1) { + // what if it needs one oneOf schema, one anyOf schema, and two allOf schemas? + return fullPrefix + "None" + closeChars; + } + // for now only oneOf with discriminator is supported + if (oneOfExists == 1 && disc != null) { + ; + } else { + return fullPrefix + "None" + closeChars; + } + } + if (disc != null) { + // a discriminator means that the type must be object + MappedModel mm = getDiscriminatorMappedModel(disc); + if (mm == null) { + return fullPrefix + "None" + closeChars; + } + String discPropNameValue = mm.getMappingName(); + String chosenModelName = mm.getModelName(); + Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); + CodegenProperty cp = new CodegenProperty(); + cp.setName(disc.getPropertyName()); + cp.setExample(discPropNameValue); + return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, includedSchemas); + } + return fullPrefix + "None" + closeChars; } else if (ModelUtils.isBooleanSchema(schema)) { - if (objExample == null) { + if (example == null) { example = "True"; } else { if ("false".equalsIgnoreCase(objExample.toString())) { @@ -1138,85 +1867,69 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { } } return fullPrefix + example + closeChars; - } else if (ModelUtils.isDateSchema(schema)) { - if (objExample == null) { - example = pythonDate("1970-01-01"); - } else { - example = pythonDate(objExample); - } - return fullPrefix + example + closeChars; - } else if (ModelUtils.isDateTimeSchema(schema)) { - if (objExample == null) { - example = pythonDateTime("1970-01-01T00:00:00.00Z"); - } else { - example = pythonDateTime(objExample); - } - return fullPrefix + example + closeChars; - } else if (ModelUtils.isBinarySchema(schema)) { - if (objExample == null) { - example = "/path/to/file"; - } - example = "open('" + example + "', 'rb')"; - return fullPrefix + example + closeChars; - } else if (ModelUtils.isByteArraySchema(schema)) { - if (objExample == null) { - example = "'YQ=='"; - } - return fullPrefix + example + closeChars; } else if (ModelUtils.isStringSchema(schema)) { - if (objExample == null) { - // a BigDecimal: - if ("Number".equalsIgnoreCase(schema.getFormat())) { - example = "2"; - return fullPrefix + example + closeChars; - } else if (StringUtils.isNotBlank(schema.getPattern())) { - String pattern = schema.getPattern(); - /* - RxGen does not support our ECMA dialect https://github.com/curious-odd-man/RgxGen/issues/56 - So strip off the leading / and trailing / and turn on ignore case if we have it - */ - Pattern valueExtractor = Pattern.compile("^/?(.+?)/?(.?)$"); - Matcher m = valueExtractor.matcher(pattern); - RgxGen rgxGen = null; - if (m.find()) { - int groupCount = m.groupCount(); - if (groupCount == 1) { - // only pattern found - String isolatedPattern = m.group(1); - rgxGen = new RgxGen(isolatedPattern); - } else if (groupCount == 2) { - // patterns and flag found - String isolatedPattern = m.group(1); - String flags = m.group(2); - if (flags.contains("i")) { - rgxGen = new RgxGen(isolatedPattern); - RgxGenProperties properties = new RgxGenProperties(); - RgxGenOption.CASE_INSENSITIVE.setInProperties(properties, true); - rgxGen.setProperties(properties); - } else { - rgxGen = new RgxGen(isolatedPattern); - } - } - } else { - rgxGen = new RgxGen(pattern); - } - - // this seed makes it so if we have [a-z] we pick a - Random random = new Random(18); - if (rgxGen != null) { - example = rgxGen.generate(random); - } else { - throw new RuntimeException("rgxGen cannot be null. Please open an issue in the openapi-generator github repo."); - } - } else if (schema.getMinLength() != null) { - example = ""; - int len = schema.getMinLength().intValue(); - for (int i = 0; i < len; i++) example += "a"; - } else if (ModelUtils.isUUIDSchema(schema)) { - example = "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; + if (example != null) { + return fullPrefix + ensureQuotes(handleSpecialCharacters(example)) + closeChars; + } + if (ModelUtils.isDateSchema(schema)) { + if (objExample == null) { + example = pythonDate("1970-01-01"); } else { - example = "string_example"; + example = pythonDate(objExample); } + } else if (ModelUtils.isDateTimeSchema(schema)) { + if (objExample == null) { + example = pythonDateTime("1970-01-01T00:00:00.00Z"); + } else { + example = pythonDateTime(objExample); + } + } else if (ModelUtils.isBinarySchema(schema)) { + if (example == null) { + example = "/path/to/file"; + } + example = "open('" + example + "', 'rb')"; + return fullPrefix + example + closeChars; + } else if (ModelUtils.isByteArraySchema(schema)) { + if (objExample == null) { + example = "'YQ=='"; + } + } else if ("Number".equalsIgnoreCase(schema.getFormat())) { + // a BigDecimal: + example = "2"; + } else if (StringUtils.isNotBlank(schema.getPattern())) { + String pattern = schema.getPattern(); + List results = getPatternAndModifiers(pattern); + String extractedPattern = (String) results.get(0); + List regexFlags = (List) results.get(1); + /* + RxGen does not support our ECMA dialect https://github.com/curious-odd-man/RgxGen/issues/56 + So strip off the leading / and trailing / and turn on ignore case if we have it + */ + RgxGen rgxGen = null; + if (regexFlags.size() > 0 && regexFlags.contains("i")) { + rgxGen = new RgxGen(extractedPattern); + RgxGenProperties properties = new RgxGenProperties(); + RgxGenOption.CASE_INSENSITIVE.setInProperties(properties, true); + rgxGen.setProperties(properties); + } else { + rgxGen = new RgxGen(extractedPattern); + } + + // this seed makes it so if we have [a-z] we pick a + Random random = new Random(18); + if (rgxGen != null) { + example = rgxGen.generate(random); + } else { + throw new RuntimeException("rgxGen cannot be null. Please open an issue in the openapi-generator github repo."); + } + } else if (schema.getMinLength() != null) { + example = ""; + int len = schema.getMinLength().intValue(); + for (int i = 0; i < len; i++) example += "a"; + } else if (ModelUtils.isUUIDSchema(schema)) { + example = "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; + } else { + example = "string_example"; } return fullPrefix + ensureQuotes(example) + closeChars; } else if (ModelUtils.isIntegerSchema(schema)) { @@ -1238,25 +1951,85 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { } return fullPrefix + example + closeChars; } else if (ModelUtils.isArraySchema(schema)) { + if (objExample instanceof Iterable) { + // If the example is already a list, return it directly instead of wrongly wrap it in another list + return fullPrefix + objExample.toString() + closeChars; + } + if (ModelUtils.isComposedSchema(schema)) { + // complex composed array type schemas not yet handled and the code returns early + return fullPrefix + "[]" + closeChars; + } ArraySchema arrayschema = (ArraySchema) schema; Schema itemSchema = arrayschema.getItems(); String itemModelName = getModelName(itemSchema); - if (objExample instanceof Iterable && itemModelName == null) { - // If the example is already a list, return it directly instead of wrongly wrap it in another list - return fullPrefix + objExample + closeChars; + if(includedSchemas.contains(schema)) { + return ""; } - Set newSeenSchemas = new HashSet<>(seenSchemas); - newSeenSchemas.add(schema); - example = fullPrefix + "[" + "\n" + toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, "", exampleLine + 1, newSeenSchemas) + ",\n" + closingIndentation + "]" + closeChars; - return example; - } else if (ModelUtils.isMapSchema(schema)) { + includedSchemas.add(schema); + String itemExample = toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, "", exampleLine + 1, includedSchemas); + if (StringUtils.isEmpty(itemExample) || cycleFound) { + return fullPrefix + "[]" + closeChars; + } else { + return fullPrefix + "[" + "\n" + itemExample + "\n" + closingIndentation + "]" + closeChars; + } + } else if (ModelUtils.isTypeObjectSchema(schema)) { if (modelName == null) { - fullPrefix += "{"; - closeChars = "}"; + fullPrefix += "dict("; + closeChars = ")"; + } + if (cycleFound) { + return fullPrefix + closeChars; + } + Boolean hasProperties = (schema.getProperties() != null && !schema.getProperties().isEmpty()); + CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); + if (ModelUtils.isComposedSchema(schema)) { + // complex composed object type schemas not yet handled and the code returns early + if (hasProperties) { + // what if this composed schema defined properties + allOf? + return fullPrefix + closeChars; + } + ComposedSchema cs = (ComposedSchema) schema; + Integer allOfExists = 0; + if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { + allOfExists = 1; + } + Integer anyOfExists = 0; + if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { + anyOfExists = 1; + } + Integer oneOfExists = 0; + if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { + oneOfExists = 1; + } + if (allOfExists + anyOfExists + oneOfExists > 1) { + // what if it needs one oneOf schema, one anyOf schema, and two allOf schemas? + return fullPrefix + closeChars; + } + // for now only oneOf with discriminator is supported + if (oneOfExists == 1 && disc != null) { + ; + } else { + return fullPrefix + closeChars; + } + } + if (disc != null) { + MappedModel mm = getDiscriminatorMappedModel(disc); + if (mm == null) { + return fullPrefix + closeChars; + } + String discPropNameValue = mm.getMappingName(); + String chosenModelName = mm.getModelName(); + Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); + CodegenProperty cp = new CodegenProperty(); + cp.setName(disc.getPropertyName()); + cp.setExample(discPropNameValue); + return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, includedSchemas); } Object addPropsObj = schema.getAdditionalProperties(); - // TODO handle true case for additionalProperties - if (addPropsObj instanceof Schema) { + if (hasProperties) { + return exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation, includedSchemas); + } else if (addPropsObj instanceof Schema) { + // TODO handle true case for additionalProperties Schema addPropsSchema = (Schema) addPropsObj; String key = "key"; Object addPropsExample = getObjectExample(addPropsSchema); @@ -1269,93 +2042,43 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { addPropPrefix = ensureQuotes(key) + ": "; } String addPropsModelName = getModelName(addPropsSchema); - Set newSeenSchemas = new HashSet<>(seenSchemas); - newSeenSchemas.add(schema); - example = fullPrefix + "\n" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1, newSeenSchemas) + ",\n" + closingIndentation + closeChars; + if(includedSchemas.contains(schema)) { + return ""; + } + includedSchemas.add(schema); + + example = fullPrefix + "\n" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1, includedSchemas) + ",\n" + closingIndentation + closeChars; } else { example = fullPrefix + closeChars; } - return example; - } else if (ModelUtils.isObjectSchema(schema)) { - if (modelName == null) { - fullPrefix += "{"; - closeChars = "}"; - } - CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); - if (disc != null) { - MappedModel mm = getDiscriminatorMappedModel(disc); - if (mm != null) { - String discPropNameValue = mm.getMappingName(); - String chosenModelName = mm.getModelName(); - // TODO handle this case in the future, this is when the discriminated - // schema allOf includes this schema, like Cat allOf includes Pet - // so this is the composed schema use case - } else { - return fullPrefix + closeChars; - } - } - Set newSeenSchemas = new HashSet<>(seenSchemas); - newSeenSchemas.add(schema); - String exampleForObjectModel = exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation, newSeenSchemas); - return exampleForObjectModel; - } else if (ModelUtils.isComposedSchema(schema)) { - // TODO add examples for composed schema models without discriminators - - CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); - if (disc != null) { - MappedModel mm = getDiscriminatorMappedModel(disc); - if (mm != null) { - String discPropNameValue = mm.getMappingName(); - String chosenModelName = mm.getModelName(); - Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); - CodegenProperty cp = new CodegenProperty(); - cp.setName(disc.getPropertyName()); - cp.setExample(discPropNameValue); - // Adds schema to seenSchemas before running example model function. removes schema after running - // the function. It also doesn't keep track of any schemas within the ObjectModel. - Set newSeenSchemas = new HashSet<>(seenSchemas); - newSeenSchemas.add(schema); - String exampleForObjectModel = exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, newSeenSchemas); - return exampleForObjectModel; - } else { - return fullPrefix + closeChars; - } - } - return fullPrefix + closeChars; } else { - LOGGER.warn("Type {} not handled properly in toExampleValue", schema.getType()); + LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue"); } return example; } - private String exampleForObjectModel(Schema schema, String fullPrefix, String closeChars, CodegenProperty discProp, int indentationLevel, int exampleLine, String closingIndentation, Set seenSchemas) { + private boolean potentiallySelfReferencingSchema(Schema schema) { + return null != schema.get$ref() || ModelUtils.isArraySchema(schema) || ModelUtils.isMapSchema(schema) || ModelUtils.isObjectSchema(schema) || ModelUtils.isComposedSchema(schema); + } + + private String exampleForObjectModel(Schema schema, String fullPrefix, String closeChars, CodegenProperty discProp, int indentationLevel, int exampleLine, String closingIndentation, List includedSchemas) { + Map requiredAndOptionalProps = schema.getProperties(); if (requiredAndOptionalProps == null || requiredAndOptionalProps.isEmpty()) { return fullPrefix + closeChars; } + if(includedSchemas.contains(schema)) { + return ""; + } + includedSchemas.add(schema); + String example = fullPrefix + "\n"; + for (Map.Entry entry : requiredAndOptionalProps.entrySet()) { String propName = entry.getKey(); Schema propSchema = entry.getValue(); - boolean readOnly = false; - if (propSchema.getReadOnly() != null) { - readOnly = propSchema.getReadOnly(); - } - if (readOnly) { - continue; - } - String ref = propSchema.get$ref(); - if (ref != null) { - Schema refSchema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); - if (refSchema.getReadOnly() != null) { - readOnly = refSchema.getReadOnly(); - } - if (readOnly) { - continue; - } - } propName = toVarName(propName); String propModelName = null; Object propExample = null; @@ -1364,13 +2087,25 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { propExample = discProp.example; } else { propModelName = getModelName(propSchema); - propExample = exampleFromStringOrArraySchema(propSchema, null, propName); + propExample = exampleFromStringOrArraySchema( + propSchema, + null, + propName); } - example += toExampleValueRecursive(propModelName, propSchema, propExample, indentationLevel + 1, propName + "=", exampleLine + 1, seenSchemas) + ",\n"; + + example += toExampleValueRecursive(propModelName, + propSchema, + propExample, + indentationLevel + 1, + propName + "=", + exampleLine + 1, + includedSchemas) + ",\n"; } + // TODO handle additionalProperties also example += closingIndentation + closeChars; return example; + } private Object exampleFromStringOrArraySchema(Schema sc, Object currentExample, String propName) { @@ -1501,7 +2236,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { protected Map getModelNameToSchemaCache() { if (modelNameToSchemaCache == null) { // Create a cache to efficiently lookup schema based on model name. - Map m = new HashMap<>(); + Map m = new HashMap(); ModelUtils.getSchemas(openAPI).forEach((key, schema) -> { m.put(toModelName(key), schema); }); @@ -1510,12 +2245,545 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { return modelNameToSchemaCache; } + /** + * Use cases: + * additional properties is unset: do nothing + * additional properties is true: add definiton to property + * additional properties is false: add definiton to property + * additional properties is schema: add definiton to property + * + * @param schema the schema that may contain an additional property schema + * @param property the property for the above schema + */ @Override - public String generatorLanguageVersion() { return ">=3.6"; }; + protected void setAddProps(Schema schema, IJsonSchemaValidationProperties property){ + Schema addPropsSchema = getSchemaFromBooleanOrSchema(schema.getAdditionalProperties()); + if (addPropsSchema == null) { + return; + } + CodegenProperty addPropProp = fromProperty("", addPropsSchema, false, false); + property.setAdditionalProperties(addPropProp); + } + + /** + * Update property for array(list) container + * + * @param property Codegen property + * @param innerProperty Codegen inner property of map or list + */ + @Override + protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) { + if (innerProperty == null) { + if(LOGGER.isWarnEnabled()) { + LOGGER.warn("skipping invalid array property {}", Json.pretty(property)); + } + return; + } + property.dataFormat = innerProperty.dataFormat; + if (languageSpecificPrimitives.contains(innerProperty.baseType)) { + property.isPrimitiveType = true; + } + property.items = innerProperty; + property.mostInnerItems = getMostInnerItems(innerProperty); + // inner item is Enum + if (isPropertyInnerMostEnum(property)) { + // isEnum is set to true when the type is an enum + // or the inner type of an array/map is an enum + property.isEnum = true; + // update datatypeWithEnum and default value for array + // e.g. List => List + updateDataTypeWithEnumForArray(property); + // set allowable values to enum values (including array/map of enum) + property.allowableValues = getInnerEnumAllowableValues(property); + } + + } + + /** + * Sets the booleans that define the model's type + * + * @param model the model to update + * @param schema the model's schema + */ + protected void updateModelForString(CodegenModel model, Schema schema) { + if (ModelUtils.isDateTimeSchema(schema)) { + // isString stays true, format stores that this is a date-time + } else if (ModelUtils.isDateSchema(schema)) { + // isString stays true, format stores that this is a date + } else if (ModelUtils.isUUIDSchema(schema)) { + // isString stays true, format stores that this is a uuid + } else if (ModelUtils.isDecimalSchema(schema)) { + // isString stays true, format stores that this is a uuid + } else if (ModelUtils.isBinarySchema(schema)) { + // format stores that this is binary + model.isString = true; + } + } + + protected void updateModelForNumber(CodegenModel model, Schema schema) { + model.setIsNumber(true); + // float vs double info is stored in format + } + + protected void updateModelForInteger(CodegenModel model, Schema schema) { + model.isInteger = true; + // int32 int64 info is stored in format + } + + protected void updatePropertyForString(CodegenProperty property, Schema p) { + if (ModelUtils.isByteArraySchema(p)) { + // isString stays true, format stores that this is a byte + } else if (ModelUtils.isBinarySchema(p)) { + // format stores that this is binary + property.isString = true; + } else if (ModelUtils.isUUIDSchema(p)) { + // isString stays true, format stores that this is a uuid + } else if (ModelUtils.isURISchema(p)) { + property.isUri = true; + } else if (ModelUtils.isEmailSchema(p)) { + property.isEmail = true; + } else if (ModelUtils.isDateSchema(p)) { // date format + // isString stays true, format stores that this is a date + } else if (ModelUtils.isDateTimeSchema(p)) { // date-time format + // isString stays true, format stores that this is a date-time + } else if (ModelUtils.isDecimalSchema(p)) { // type: string, format: number + // isString stays true, format stores that this is a number + } + property.pattern = toRegularExpression(p.getPattern()); + } @Override - protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName ) { - // import everything (including child schema of a composed schema) - addImport(model, modelName); + public String toRegularExpression(String pattern) { + if (pattern == null) { + return null; + } + List results = getPatternAndModifiers(pattern); + String extractedPattern = (String) results.get(0); + return extractedPattern; } -} + + protected void updatePropertyForNumber(CodegenProperty property, Schema p) { + property.setIsNumber(true); + // float and double differentiation is determined with format info + } + + protected void updatePropertyForInteger(CodegenProperty property, Schema p) { + property.isInteger = true; + // int32 and int64 differentiation is determined with format info + } + + + @Override + protected void updatePropertyForObject(CodegenProperty property, Schema p) { + addVarsRequiredVarsAdditionalProps(p, property); + } + + @Override + protected void updatePropertyForAnyType(CodegenProperty property, Schema p) { + // The 'null' value is allowed when the OAS schema is 'any type'. + // See https://github.com/OAI/OpenAPI-Specification/issues/1389 + if (Boolean.FALSE.equals(p.getNullable())) { + LOGGER.warn("Schema '{}' is any type, which includes the 'null' value. 'nullable' cannot be set to 'false'", p.getName()); + } + addVarsRequiredVarsAdditionalProps(p, property); + } + + @Override + protected void updateModelForObject(CodegenModel m, Schema schema) { + // custom version of this method so properties are always added with addVars + if (schema.getProperties() != null || schema.getRequired() != null) { + // passing null to allProperties and allRequired as there's no parent + addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null); + } + // an object or anyType composed schema that has additionalProperties set + addAdditionPropertiesToCodeGenModel(m, schema); + // process 'additionalProperties' + setAddProps(schema, m); + addRequiredVarsMap(schema, m); + } + + @Override + protected void updateModelForAnyType(CodegenModel m, Schema schema) { + // The 'null' value is allowed when the OAS schema is 'any type'. + // See https://github.com/OAI/OpenAPI-Specification/issues/1389 + if (Boolean.FALSE.equals(schema.getNullable())) { + LOGGER.error("Schema '{}' is any type, which includes the 'null' value. 'nullable' cannot be set to 'false'", m.name); + } + // todo add items support here in the future + if (schema.getProperties() != null || schema.getRequired() != null) { + // passing null to allProperties and allRequired as there's no parent + addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null); + } + addAdditionPropertiesToCodeGenModel(m, schema); + // process 'additionalProperties' + setAddProps(schema, m); + addRequiredVarsMap(schema, m); + } + + @Override + protected void updateModelForComposedSchema(CodegenModel m, Schema schema, Map allDefinitions) { + final ComposedSchema composed = (ComposedSchema) schema; + + // TODO revise the logic below to set discriminator, xml attributes + if (composed.getAllOf() != null) { + int modelImplCnt = 0; // only one inline object allowed in a ComposedModel + int modelDiscriminators = 0; // only one discriminator allowed in a ComposedModel + for (Schema innerSchema : composed.getAllOf()) { // TODO need to work with anyOf, oneOf as well + if (m.discriminator == null && innerSchema.getDiscriminator() != null) { + LOGGER.debug("discriminator is set to null (not correctly set earlier): {}", m.name); + m.setDiscriminator(createDiscriminator(m.name, innerSchema, this.openAPI)); + if (!this.getLegacyDiscriminatorBehavior()) { + m.addDiscriminatorMappedModelsImports(); + } + modelDiscriminators++; + } + + if (innerSchema.getXml() != null) { + m.xmlPrefix = innerSchema.getXml().getPrefix(); + m.xmlNamespace = innerSchema.getXml().getNamespace(); + m.xmlName = innerSchema.getXml().getName(); + } + if (modelDiscriminators > 1) { + LOGGER.error("Allof composed schema is inheriting >1 discriminator. Only use one discriminator: {}", composed); + } + + if (modelImplCnt++ > 1) { + LOGGER.warn("More than one inline schema specified in allOf:. Only the first one is recognized. All others are ignored."); + break; // only one schema with discriminator allowed in allOf + } + } + } + + CodegenComposedSchemas cs = m.getComposedSchemas(); + if (cs != null) { + if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { + for (CodegenProperty cp: cs.getAllOf()) { + if (cp.complexType != null) { + addImport(m, cp.complexType); + } + } + } + if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { + for (CodegenProperty cp: cs.getOneOf()) { + if (cp.complexType != null) { + addImport(m, cp.complexType); + } + } + } + if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { + for (CodegenProperty cp: cs.getAnyOf()) { + if (cp.complexType != null) { + addImport(m, cp.complexType); + } + } + } + } + } + + @Override + public ModelsMap postProcessModels(ModelsMap objs) { + // process enum in models + return postProcessModelsEnum(objs); + } + + /** + * @param pattern the regex pattern + * @return List> + */ + private List getPatternAndModifiers(String pattern) { + /* + Notes: + RxGen does not support our ECMA dialect https://github.com/curious-odd-man/RgxGen/issues/56 + So strip off the leading / and trailing / and turn on ignore case if we have it + + json schema test cases omit the leading and trailing /s, so make sure that the regex allows that + */ + Pattern valueExtractor = Pattern.compile("^/?(.+?)/?([simu]{0,4})$"); + Matcher m = valueExtractor.matcher(pattern); + if (m.find()) { + int groupCount = m.groupCount(); + if (groupCount == 1) { + // only pattern found + String isolatedPattern = m.group(1); + return Arrays.asList(isolatedPattern, null); + } else if (groupCount == 2) { + List modifiers = new ArrayList(); + // patterns and flag found + String isolatedPattern = m.group(1); + String flags = m.group(2); + if (flags.contains("s")) { + modifiers.add("DOTALL"); + } + if (flags.contains("i")) { + modifiers.add("IGNORECASE"); + } + if (flags.contains("m")) { + modifiers.add("MULTILINE"); + } + return Arrays.asList(isolatedPattern, modifiers); + } + } + return Arrays.asList(pattern, new ArrayList()); + } + + /* + * The OpenAPI pattern spec follows the Perl convention and style of modifiers. Python + * does not support this in as natural a way so it needs to convert it. See + * https://docs.python.org/2/howto/regex.html#compilation-flags for details. + */ + public void postProcessPattern(String pattern, Map vendorExtensions) { + if (pattern != null) { + List results = getPatternAndModifiers(pattern); + String extractedPattern = (String) results.get(0); + List modifiers = (List) results.get(1); + + vendorExtensions.put("x-regex", extractedPattern); + if (modifiers.size() > 0) { + vendorExtensions.put("x-modifiers", modifiers); + } + } + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String addRegularExpressionDelimiter(String pattern) { + if (StringUtils.isEmpty(pattern)) { + return pattern; + } + + if (!pattern.matches("^/.*")) { + // Perform a negative lookbehind on each `/` to ensure that it is escaped. + return "/" + pattern.replaceAll("(? + * (PEP 0008) Python packages should also have short, all-lowercase names, + * although the use of underscores is discouraged. + * + * @param packageName Package name + * @return Python package name that conforms to PEP 0008 + */ + @SuppressWarnings("static-method") + public String generatePackageName(String packageName) { + return underscore(packageName.replaceAll("[^\\w]+", "")); + } + + /** + * A custom version of this method is needed to ensure that the form object parameter is kept as-is + * as an object and is not exploded into separate parameters + * @param body the body that is being handled + * @param imports the imports for this body + * @return the list of length one containing a single type object CodegenParameter + */ + @Override + public List fromRequestBodyToFormParameters(RequestBody body, Set imports) { + List parameters = new ArrayList<>(); + LOGGER.debug("debugging fromRequestBodyToFormParameters= {}", body); + Schema schema = ModelUtils.getSchemaFromRequestBody(body); + schema = ModelUtils.getReferencedSchema(this.openAPI, schema); + CodegenParameter cp = fromFormProperty("body", schema, imports); + cp.setContent(getContent(body.getContent(), imports, "RequestBody")); + cp.isFormParam = false; + cp.isBodyParam = true; + parameters.add(cp); + return parameters; + } + + /** + * Custom version of this method so we can move the body parameter into bodyParam + * + * @param path the path of the operation + * @param httpMethod HTTP method + * @param operation OAS operation object + * @param servers list of servers + * @return the resultant CodegenOperation instance + */ + @Override + public CodegenOperation fromOperation(String path, + String httpMethod, + Operation operation, + List servers) { + CodegenOperation co = super.fromOperation(path, httpMethod, operation, servers); + co.httpMethod = httpMethod.toLowerCase(Locale.ROOT); + // smuggle the path enum variable name in operationIdLowerCase + co.operationIdLowerCase = toEnumVarName(co.path, "str"); + // smuggle pathModuleName in nickname + String pathModuleName = toVarName(path); + co.nickname = pathModuleName; + // smuggle path Api class name ins operationIdSnakeCase + co.operationIdSnakeCase = toModelName(path); + + if (co.bodyParam == null) { + for (CodegenParameter cp: co.allParams) { + if (cp.isBodyParam) { + co.bodyParam = cp; + co.bodyParams.add(cp); + } + } + } + return co; + } + + /** + * Custom version of this method to prevent mutation of + * codegenOperation.operationIdLowerCase/operationIdSnakeCase + * Property Usages: + * - operationId: endpoint method name when using tagged apis + * - httpMethod: endpoint method name when using path apis + * - operationIdCamelCase: Api class name containing single endpoint for tagged apis + * - operationIdLowerCase: (smuggled) path enum variable name + * - nickname: (smuggled) path module name for path apis + * - operationIdSnakeCase: (smuggled) path Api class name when using path apis + * + * @param tag name of the tag + * @param resourcePath path of the resource + * @param operation OAS Operation object + * @param co Codegen Operation object + * @param operations map of Codegen operations + */ + @Override + @SuppressWarnings("static-method") + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation + co, Map> operations) { + List opList = operations.get(tag); + if (opList == null) { + opList = new ArrayList<>(); + operations.put(tag, opList); + } + // check for operationId uniqueness + String uniqueName = co.operationId; + int counter = 0; + for (CodegenOperation op : opList) { + if (uniqueName.equals(op.operationId)) { + uniqueName = co.operationId + "_" + counter; + counter++; + } + } + if (!co.operationId.equals(uniqueName)) { + LOGGER.warn("generated unique operationId `{}`", uniqueName); + } + co.operationId = uniqueName; + co.operationIdCamelCase = camelize(uniqueName); + opList.add(co); + co.baseName = tag; + } + + @Override + public String defaultTemplatingEngine() { + return "handlebars"; + } + + @Override + public String generatorLanguageVersion() { return ">=3.7"; }; + + @Override + public void preprocessOpenAPI(OpenAPI openAPI) { + String originalSpecVersion; + String xOriginalSwaggerVersion = "x-original-swagger-version"; + if (openAPI.getExtensions() != null && !openAPI.getExtensions().isEmpty() && openAPI.getExtensions().containsValue(xOriginalSwaggerVersion)) { + originalSpecVersion = (String) openAPI.getExtensions().get(xOriginalSwaggerVersion); + } else { + originalSpecVersion = openAPI.getOpenapi(); + } + Integer specMajorVersion = Integer.parseInt(originalSpecVersion.substring(0, 1)); + if (specMajorVersion < 3) { + throw new RuntimeException("Your spec version of "+originalSpecVersion+" is too low. python-experimental only works with specs with version >= 3.X.X. Please use a tool like Swagger Editor or Swagger Converter to convert your spec to v3"); + } + } + + /** + * Note: a custom version of this function is used so the original tag value can be used + * + * @param tag Tag + * @return the tag to use + */ + @Override + public String sanitizeTag(String tag) { + return tag; + } + + public Map postProcessSupportingFileData(Map objs) { + objs.put(CodegenConstants.NON_COMPLIANT_USE_DISCR_IF_COMPOSITION_FAILS, nonCompliantUseDiscrIfCompositionFails); + return objs; + } + + @Override + public void postProcess() { + System.out.println("################################################################################"); + System.out.println("# Thanks for using OpenAPI Generator. #"); + System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); + System.out.println("# https://opencollective.com/openapi_generator/donate #"); + System.out.println("# #"); + System.out.println("# This generator was written by Justin Black (https://github.com/spacether) #"); + System.out.println("# Please support his work directly via https://github.com/sponsors/spacether \uD83D\uDE4F#"); + System.out.println("################################################################################"); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonExperimentalClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonExperimentalClientCodegen.java deleted file mode 100644 index 9f24ff08d9..0000000000 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonExperimentalClientCodegen.java +++ /dev/null @@ -1,2439 +0,0 @@ -/* - * 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 com.github.curiousoddman.rgxgen.RgxGen; -import com.github.curiousoddman.rgxgen.config.RgxGenOption; -import com.github.curiousoddman.rgxgen.config.RgxGenProperties; -import com.google.common.base.CaseFormat; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.servers.Server; -import io.swagger.v3.oas.models.tags.Tag; - -import org.apache.commons.io.FileUtils; -import org.openapitools.codegen.api.TemplatePathLocator; -import org.openapitools.codegen.ignore.CodegenIgnoreProcessor; -import org.openapitools.codegen.model.ModelMap; -import org.openapitools.codegen.model.ModelsMap; -import org.openapitools.codegen.model.OperationMap; -import org.openapitools.codegen.model.OperationsMap; -import org.openapitools.codegen.templating.*; -import io.swagger.v3.core.util.Json; -import io.swagger.v3.oas.models.media.*; -import io.swagger.v3.oas.models.parameters.Parameter; -import io.swagger.v3.oas.models.parameters.RequestBody; -import io.swagger.v3.oas.models.security.SecurityScheme; -import org.apache.commons.lang3.StringUtils; -import org.openapitools.codegen.*; -import org.openapitools.codegen.CodegenDiscriminator.MappedModel; -import org.openapitools.codegen.api.TemplatingEngineAdapter; -import org.openapitools.codegen.meta.GeneratorMetadata; -import org.openapitools.codegen.meta.Stability; -import org.openapitools.codegen.meta.features.*; -import org.openapitools.codegen.utils.ModelUtils; -import org.openapitools.codegen.utils.ProcessUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.openapitools.codegen.api.TemplateProcessor; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.openapitools.codegen.utils.OnceLogger.once; -import static org.openapitools.codegen.utils.StringUtils.underscore; - -public class PythonExperimentalClientCodegen extends AbstractPythonCodegen { - private final Logger LOGGER = LoggerFactory.getLogger(PythonExperimentalClientCodegen.class); - - public static final String PACKAGE_URL = "packageUrl"; - public static final String DEFAULT_LIBRARY = "urllib3"; - // nose is a python testing framework, we use pytest if USE_NOSE is unset - public static final String USE_NOSE = "useNose"; - public static final String RECURSION_LIMIT = "recursionLimit"; - public static final String USE_INLINE_MODEL_RESOLVER = "useInlineModelResolver"; - - protected String packageUrl; - protected String apiDocPath = "docs/"; - protected String modelDocPath = "docs/"; - protected boolean useNose = false; - protected boolean useInlineModelResolver = false; - - protected Map regexModifiers; - - private String testFolder; - - // A cache to efficiently lookup a Schema instance based on the return value of `toModelName()`. - private Map modelNameToSchemaCache; - private DateTimeFormatter iso8601Date = DateTimeFormatter.ISO_DATE; - private DateTimeFormatter iso8601DateTime = DateTimeFormatter.ISO_DATE_TIME; - - private String templateExtension; - protected CodegenIgnoreProcessor ignoreProcessor; - protected TemplateProcessor templateProcessor = null; - - public PythonExperimentalClientCodegen() { - super(); - loadDeepObjectIntoItems = false; - - modifyFeatureSet(features -> features - .includeSchemaSupportFeatures( - SchemaSupportFeature.Simple, - SchemaSupportFeature.Composite, - SchemaSupportFeature.Polymorphism, - SchemaSupportFeature.Union, - SchemaSupportFeature.allOf, - SchemaSupportFeature.anyOf, - SchemaSupportFeature.oneOf, - SchemaSupportFeature.not - ) - .includeDocumentationFeatures(DocumentationFeature.Readme) - .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.Custom)) - .securityFeatures(EnumSet.of( - SecurityFeature.BasicAuth, - SecurityFeature.BearerToken, - SecurityFeature.ApiKey, - SecurityFeature.OAuth2_Implicit - )) - .includeDataTypeFeatures( - DataTypeFeature.Null, - DataTypeFeature.AnyType, - DataTypeFeature.Uuid - ) - .includeGlobalFeatures( - GlobalFeature.ParameterizedServer, - GlobalFeature.ParameterStyling - ) - .excludeGlobalFeatures( - GlobalFeature.XMLStructureDefinitions, - GlobalFeature.Callbacks, - GlobalFeature.LinkObjects - ) - .excludeSchemaSupportFeatures( - ) - .excludeParameterFeatures( - ParameterFeature.Cookie - ) - ); - - // clear import mapping (from default generator) as python does not use it - // at the moment - importMapping.clear(); - - modelPackage = "model"; - apiPackage = "api"; - outputFolder = "generated-code" + File.separatorChar + "python"; - - embeddedTemplateDir = templateDir = "python-experimental"; - - testFolder = "test"; - - // default HIDE_GENERATION_TIMESTAMP to true - hideGenerationTimestamp = Boolean.TRUE; - - // from https://docs.python.org/3/reference/lexical_analysis.html#keywords - setReservedWordsLowerCase( - Arrays.asList( - // local variable name used in API methods (endpoints) - "all_params", "resource_path", "path_params", "query_params", - "header_params", "form_params", "local_var_files", "body_params", "auth_settings", - // @property - "property", - // python reserved words - "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", - "assert", "else", "if", "pass", "yield", "break", "except", "import", - "print", "class", "exec", "in", "raise", "continue", "finally", "is", - "return", "def", "for", "lambda", "try", "self", "nonlocal", "None", "True", - "False", "async", "await", - // types - "float", "int", "str", "bool", "none_type", "dict", "frozendict", "list", "tuple", "file_type")); - - regexModifiers = new HashMap(); - regexModifiers.put('i', "IGNORECASE"); - regexModifiers.put('l', "LOCALE"); - regexModifiers.put('m', "MULTILINE"); - regexModifiers.put('s', "DOTALL"); - regexModifiers.put('u', "UNICODE"); - regexModifiers.put('x', "VERBOSE"); - - cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") - .defaultValue("openapi_client")); - cliOptions.add(new CliOption(CodegenConstants.PROJECT_NAME, "python project name in setup.py (e.g. petstore-api).")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") - .defaultValue("1.0.0")); - cliOptions.add(new CliOption(PACKAGE_URL, "python package URL.")); - // this generator does not use SORT_PARAMS_BY_REQUIRED_FLAG - // this generator uses the following order for endpoint paramters and model properties - // required params - // optional params which are set to unset as their default for method signatures only - // optional params as **kwargs - cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) - .defaultValue(Boolean.TRUE.toString())); - cliOptions.add(new CliOption(CodegenConstants.SOURCECODEONLY_GENERATION, CodegenConstants.SOURCECODEONLY_GENERATION_DESC) - .defaultValue(Boolean.FALSE.toString())); - cliOptions.add(CliOption.newBoolean(USE_NOSE, "use the nose test framework"). - defaultValue(Boolean.FALSE.toString())); - cliOptions.add(new CliOption(RECURSION_LIMIT, "Set the recursion limit. If not set, use the system default value.")); - cliOptions.add(CliOption.newBoolean(USE_INLINE_MODEL_RESOLVER, "use the inline model resolver, if true inline complex models will be extracted into components and $refs to them will be used"). - defaultValue(Boolean.FALSE.toString())); - - supportedLibraries.put("urllib3", "urllib3-based client"); - CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use: urllib3"); - libraryOption.setDefault(DEFAULT_LIBRARY); - cliOptions.add(libraryOption); - setLibrary(DEFAULT_LIBRARY); - - // Composed schemas can have the 'additionalProperties' keyword, as specified in JSON schema. - // In principle, this should be enabled by default for all code generators. However due to limitations - // in other code generators, support needs to be enabled on a case-by-case basis. - supportsAdditionalPropertiesWithComposedSchema = true; - - // When the 'additionalProperties' keyword is not present in a OAS schema, allow - // undeclared properties. This is compliant with the JSON schema specification. - this.setDisallowAdditionalPropertiesIfNotPresent(false); - - // this may set datatype right for additional properties - instantiationTypes.put("map", "dict"); - - languageSpecificPrimitives.add("file_type"); - languageSpecificPrimitives.add("none_type"); - typeMapping.put("decimal", "str"); - - generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) - .stability(Stability.EXPERIMENTAL) - .build(); - } - - @Override - public void processOpts() { - this.setLegacyDiscriminatorBehavior(false); - - super.processOpts(); - - TemplatingEngineAdapter te = getTemplatingEngine(); - if (te instanceof HandlebarsEngineAdapter) { - HandlebarsEngineAdapter hea = (HandlebarsEngineAdapter) te; - hea.infiniteLoops(true); - hea.setPrettyPrint(true); - } else { - throw new RuntimeException("Only the HandlebarsEngineAdapter is supported for this generator"); - } - - TemplatePathLocator commonTemplateLocator = new CommonTemplateContentLocator(); - TemplatePathLocator generatorTemplateLocator = new GeneratorTemplateContentLocator(this); - TemplateManagerOptions templateManagerOptions = new TemplateManagerOptions(this.isEnableMinimalUpdate(),this.isSkipOverwrite()); - templateProcessor = new TemplateManager( - templateManagerOptions, - te, - new TemplatePathLocator[]{generatorTemplateLocator, commonTemplateLocator} - ); - templateExtension = te.getIdentifier(); - - String ignoreFileLocation = this.getIgnoreFilePathOverride(); - if (ignoreFileLocation != null) { - final File ignoreFile = new File(ignoreFileLocation); - if (ignoreFile.exists() && ignoreFile.canRead()) { - this.ignoreProcessor = new CodegenIgnoreProcessor(ignoreFile); - } else { - LOGGER.warn("Ignore file specified at {} is not valid. This will fall back to an existing ignore file if present in the output directory.", ignoreFileLocation); - } - } - - if (this.ignoreProcessor == null) { - this.ignoreProcessor = new CodegenIgnoreProcessor(this.getOutputDir()); - } - - modelTemplateFiles.put("model." + templateExtension, ".py"); - apiTemplateFiles.put("api." + templateExtension, ".py"); - modelTestTemplateFiles.put("model_test." + templateExtension, ".py"); - apiTestTemplateFiles.put("api_test." + templateExtension, ".py"); - modelDocTemplateFiles.put("model_doc." + templateExtension, ".md"); - apiDocTemplateFiles.put("api_doc." + templateExtension, ".md"); - - if (StringUtils.isEmpty(System.getenv("PYTHON_POST_PROCESS_FILE"))) { - LOGGER.info("Environment variable PYTHON_POST_PROCESS_FILE not defined so the Python code may not be properly formatted. To define it, try 'export PYTHON_POST_PROCESS_FILE=\"/usr/local/bin/yapf -i\"' (Linux/Mac)"); - LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI)."); - } - - Boolean excludeTests = false; - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { - setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); - } - - if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) { - setProjectName((String) additionalProperties.get(CodegenConstants.PROJECT_NAME)); - } else { - // default: set project based on package name - // e.g. petstore_api (package name) => petstore-api (project name) - setProjectName(packageName.replaceAll("_", "-")); - } - - if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { - setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); - } - - additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName); - additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); - additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); - - if (additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) { - excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString()); - } - - Boolean generateSourceCodeOnly = false; - if (additionalProperties.containsKey(CodegenConstants.SOURCECODEONLY_GENERATION)) { - generateSourceCodeOnly = Boolean.valueOf(additionalProperties.get(CodegenConstants.SOURCECODEONLY_GENERATION).toString()); - } - - if (generateSourceCodeOnly) { - // tests in /test - testFolder = packagePath() + File.separatorChar + testFolder; - // api/model docs in /docs - apiDocPath = packagePath() + File.separatorChar + apiDocPath; - modelDocPath = packagePath() + File.separatorChar + modelDocPath; - } - // make api and model doc path available in templates - additionalProperties.put("apiDocPath", apiDocPath); - additionalProperties.put("modelDocPath", modelDocPath); - - if (additionalProperties.containsKey(PACKAGE_URL)) { - setPackageUrl((String) additionalProperties.get(PACKAGE_URL)); - } - - if (additionalProperties.containsKey(USE_NOSE)) { - setUseNose((String) additionalProperties.get(USE_NOSE)); - } - - if (additionalProperties.containsKey(USE_INLINE_MODEL_RESOLVER)) { - setUseInlineModelResolver((String) additionalProperties.get(USE_INLINE_MODEL_RESOLVER)); - } - - // check to see if setRecursionLimit is set and whether it's an integer - if (additionalProperties.containsKey(RECURSION_LIMIT)) { - try { - Integer.parseInt((String) additionalProperties.get(RECURSION_LIMIT)); - } catch (NumberFormatException | NullPointerException e) { - throw new IllegalArgumentException("recursionLimit must be an integer, e.g. 2000."); - } - } - - String readmePath = "README.md"; - String readmeTemplate = "README." + templateExtension; - if (generateSourceCodeOnly) { - readmePath = packagePath() + "_" + readmePath; - readmeTemplate = "README_onlypackage." + templateExtension; - } - supportingFiles.add(new SupportingFile(readmeTemplate, "", readmePath)); - - if (!generateSourceCodeOnly) { - supportingFiles.add(new SupportingFile("tox." + templateExtension, "", "tox.ini")); - supportingFiles.add(new SupportingFile("test-requirements." + templateExtension, "", "test-requirements.txt")); - supportingFiles.add(new SupportingFile("requirements." + templateExtension, "", "requirements.txt")); - supportingFiles.add(new SupportingFile("setup_cfg." + templateExtension, "", "setup.cfg")); - - supportingFiles.add(new SupportingFile("git_push.sh." + templateExtension, "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore." + templateExtension, "", ".gitignore")); - supportingFiles.add(new SupportingFile("travis." + templateExtension, "", ".travis.yml")); - supportingFiles.add(new SupportingFile("gitlab-ci." + templateExtension, "", ".gitlab-ci.yml")); - supportingFiles.add(new SupportingFile("setup." + templateExtension, "", "setup.py")); - } - supportingFiles.add(new SupportingFile("configuration." + templateExtension, packagePath(), "configuration.py")); - supportingFiles.add(new SupportingFile("__init__package." + templateExtension, packagePath(), "__init__.py")); - - // If the package name consists of dots(openapi.client), then we need to create the directory structure like openapi/client with __init__ files. - String[] packageNameSplits = packageName.split("\\."); - String currentPackagePath = ""; - for (int i = 0; i < packageNameSplits.length - 1; i++) { - if (i > 0) { - currentPackagePath = currentPackagePath + File.separatorChar; - } - currentPackagePath = currentPackagePath + packageNameSplits[i]; - supportingFiles.add(new SupportingFile("__init__." + templateExtension, currentPackagePath, "__init__.py")); - } - - supportingFiles.add(new SupportingFile("exceptions." + templateExtension, packagePath(), "exceptions.py")); - - if (Boolean.FALSE.equals(excludeTests)) { - supportingFiles.add(new SupportingFile("__init__." + templateExtension, testFolder, "__init__.py")); - } - - supportingFiles.add(new SupportingFile("api_client." + templateExtension, packagePath(), "api_client.py")); - - if ("asyncio".equals(getLibrary())) { - supportingFiles.add(new SupportingFile("asyncio/rest." + templateExtension, packagePath(), "rest.py")); - additionalProperties.put("asyncio", "true"); - } else if ("tornado".equals(getLibrary())) { - supportingFiles.add(new SupportingFile("tornado/rest." + templateExtension, packagePath(), "rest.py")); - additionalProperties.put("tornado", "true"); - } else { - supportingFiles.add(new SupportingFile("rest." + templateExtension, packagePath(), "rest.py")); - } - - supportingFiles.add(new SupportingFile("schemas." + templateExtension, packagePath(), "schemas.py")); - - // add the models and apis folders - supportingFiles.add(new SupportingFile("__init__models." + templateExtension, packagePath() + File.separatorChar + "models", "__init__.py")); - supportingFiles.add(new SupportingFile("__init__model." + templateExtension, packagePath() + File.separatorChar + modelPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__apis." + templateExtension, packagePath() + File.separatorChar + "apis", "__init__.py")); - supportingFiles.add(new SupportingFile("__init__api." + templateExtension, packagePath() + File.separatorChar + apiPackage, "__init__.py")); - // Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS. - Map securitySchemeMap = openAPI != null ? - (openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null; - List authMethods = fromSecurity(securitySchemeMap); - if (ProcessUtils.hasHttpSignatureMethods(authMethods)) { - supportingFiles.add(new SupportingFile("signing." + templateExtension, packagePath(), "signing.py")); - } - - // default this to true so the python ModelSimple models will be generated - ModelUtils.setGenerateAliasAsModel(true); - LOGGER.info(CodegenConstants.GENERATE_ALIAS_AS_MODEL + " is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums"); - - // check library option to ensure only urllib3 is supported - if (!DEFAULT_LIBRARY.equals(getLibrary())) { - throw new RuntimeException("Only the `urllib3` library is supported in the refactored `python` client generator at the moment. Please fall back to `python-legacy` client generator for the time being. We welcome contributions to add back `asyncio`, `tornado` support to the `python` client generator."); - } - } - - public String endpointFilename(String templateName, String tag, String operationId) { - return apiFileFolder() + File.separator + toApiFilename(tag) + "_endpoints" + File.separator + operationId + ".py"; - } - - protected File processTemplateToFile(Map templateData, String templateName, String outputFilename, boolean shouldGenerate, String skippedByOption) throws IOException { - String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar); - File target = new File(adjustedOutputFilename); - if (ignoreProcessor.allowsFile(target)) { - if (shouldGenerate) { - Path outDir = java.nio.file.Paths.get(this.getOutputDir()).toAbsolutePath(); - Path absoluteTarget = target.toPath().toAbsolutePath(); - if (!absoluteTarget.startsWith(outDir)) { - throw new RuntimeException(String.format(Locale.ROOT, "Target files must be generated within the output directory; absoluteTarget=%s outDir=%s", absoluteTarget, outDir)); - } - return this.templateProcessor.write(templateData,templateName, target); - } else { - this.templateProcessor.skip(target.toPath(), String.format(Locale.ROOT, "Skipped by %s options supplied by user.", skippedByOption)); - return null; - } - } else { - this.templateProcessor.ignore(target.toPath(), "Ignored by rule in ignore file."); - return null; - } - } - - /* - I made this method because endpoint parameters not contain a lot of needed metadata - It is very verbose to write all of this info into the api template - This ingests all operations under a tag in the objs input and writes out one file for each endpoint - */ - protected void generateEndpoints(OperationsMap objs) { - if (!(Boolean) additionalProperties.get(CodegenConstants.GENERATE_APIS)) { - return; - } - OperationMap operations = objs.getOperations(); - List codegenOperations = operations.getOperation(); - Set tagsNeedingInitFiles = new HashSet<>(); - for (CodegenOperation co: codegenOperations) { - for (Tag tag: co.tags) { - String tagName = tag.getName(); - String pythonTagName = toVarName(tagName); - Map operationMap = new HashMap<>(); - operationMap.put("operation", co); - operationMap.put("imports", co.imports); - operationMap.put("packageName", packageName); - - String templateName = "endpoint.handlebars"; - String filename = endpointFilename(templateName, pythonTagName, co.operationId); - tagsNeedingInitFiles.add(pythonTagName); - try { - processTemplateToFile(operationMap, templateName, filename, true, CodegenConstants.APIS); - } catch (IOException e) { - LOGGER.error("Error when writing template file {}", e.toString()); - } - } - } - String templateName = "__init__api_endpoints.handlebars"; - for (String tagNeedingInitFiles: tagsNeedingInitFiles) { - try { - Map operationMap = new HashMap<>(); - String apiModuleName = toApiFilename(tagNeedingInitFiles); - operationMap.put("packageName", packageName); - operationMap.put("apiModuleName", apiModuleName); - operationMap.put("classname", toApiName(tagNeedingInitFiles)); - String filename = endpointFilename(templateName, tagNeedingInitFiles, "__init__"); - processTemplateToFile(operationMap, templateName, filename, true, CodegenConstants.APIS); - } catch (IOException e) { - LOGGER.error("Error when writing endpoint __init__ file {}", e.toString()); - } - } - } - - /* - We have a custom version of this method so for composed schemas and object schemas we add properties only if they - are defined in that schema (x.properties). We do this because validation should be done independently in each schema - If properties are hosted into composed schemas, they can collide or incorrectly list themself as required when - they are not. - */ - @Override - protected void addVarsRequiredVarsAdditionalProps(Schema schema, IJsonSchemaValidationProperties property){ - setAddProps(schema, property); - if (ModelUtils.isAnyType(schema) && supportsAdditionalPropertiesWithComposedSchema) { - // if anyType schema has properties then add them - if (schema.getProperties() != null && !schema.getProperties().isEmpty()) { - if (schema instanceof ComposedSchema) { - ComposedSchema cs = (ComposedSchema) schema; - if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { - LOGGER.warn("'oneOf' is intended to include only the additional optional OAS extension discriminator object. " + - "For more details, see https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.section.9.2.1.3 and the OAS section on 'Composition and Inheritance'."); - } - } - HashSet requiredVars = new HashSet<>(); - if (schema.getRequired() != null) { - requiredVars.addAll(schema.getRequired()); - } - addVars(property, property.getVars(), schema.getProperties(), requiredVars); - } - return; - } else if (ModelUtils.isTypeObjectSchema(schema)) { - HashSet requiredVars = new HashSet<>(); - if (schema.getRequired() != null) { - requiredVars.addAll(schema.getRequired()); - property.setHasRequired(true); - } - addVars(property, property.getVars(), schema.getProperties(), requiredVars); - if (property.getVars() != null && !property.getVars().isEmpty()) { - property.setHasVars(true); - } - } - return; - } - - /** - * Configures a friendly name for the generator. This will be used by the - * generator to select the library with the -g flag. - * - * @return the friendly name for the generator - */ - @Override - public String getName() { - return "python-experimental"; - } - - @Override - public String getHelp() { - String newLine = System.getProperty("line.separator"); - return String.join("
        ", - "Generates a Python client library", - "", - "Features in this generator:", - "- type hints on endpoints and model creation", - "- model parameter names use the spec defined keys and cases", - "- robust composition (oneOf/anyOf/allOf/not) where payload data is stored in one instance only", - "- endpoint parameter names use the spec defined keys and cases", - "- inline schemas are supported at any location including composition", - "- multiple content types supported in request body and response bodies", - "- run time type checking", - "- Sending/receiving decimals as strings supported with type:string format: number -> DecimalSchema", - "- Sending/receiving uuids as strings supported with type:string format: uuid -> UUIDSchema", - "- quicker load time for python modules (a single endpoint can be imported and used without loading others)", - "- all instances of schemas dynamically inherit from all matching schemas so one can use isinstance to check if validation passed", - "- composed schemas with type constraints supported (type:object + oneOf/anyOf/allOf)", - "- schemas are not coerced/cast. For example string + date are both stored as string, and there is a date accessor", - " - Exceptions: int/float is stored as Decimal, When receiving data from headers it will start as str and may need to be cast for example to int"); - } - - @Override - public Schema unaliasSchema(Schema schema) { - Map allSchemas = ModelUtils.getSchemas(openAPI); - if (allSchemas == null || allSchemas.isEmpty()) { - // skip the warning as the spec can have no model defined - //LOGGER.warn("allSchemas cannot be null/empty in unaliasSchema. Returned 'schema'"); - return schema; - } - - if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) { - String simpleRef = ModelUtils.getSimpleRef(schema.get$ref()); - if (schemaMapping.containsKey(simpleRef)) { - LOGGER.debug("Schema unaliasing of {} omitted because aliased class is to be mapped to {}", simpleRef, schemaMapping.get(simpleRef)); - return schema; - } - Schema ref = allSchemas.get(simpleRef); - if (ref == null) { - once(LOGGER).warn("{} is not defined", schema.get$ref()); - return schema; - } else if (ref.getEnum() != null && !ref.getEnum().isEmpty()) { - // top-level enum class - return schema; - } else if (ModelUtils.isArraySchema(ref)) { - if (ModelUtils.isGenerateAliasAsModel(ref)) { - return schema; // generate a model extending array - } else { - return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); - } - } else if (ModelUtils.isComposedSchema(ref)) { - return schema; - } else if (ModelUtils.isMapSchema(ref)) { - if (ref.getProperties() != null && !ref.getProperties().isEmpty()) // has at least one property - return schema; // treat it as model - else { - if (ModelUtils.isGenerateAliasAsModel(ref)) { - return schema; // generate a model extending map - } else { - // treat it as a typical map - return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); - } - } - } else if (ModelUtils.isObjectSchema(ref)) { // model - if (ref.getProperties() != null && !ref.getProperties().isEmpty()) { // has at least one property - return schema; - } else { - // free form object (type: object) - if (ModelUtils.hasValidation(ref)) { - return schema; - } else if (getAllOfDescendants(simpleRef, openAPI).size() > 0) { - return schema; - } - return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); - } - } else if (ModelUtils.hasValidation(ref)) { - // non object non array non map schemas that have validations - // are returned so we can generate those schemas as models - // we do this to: - // - preserve the validations in that model class in python - // - use those validations when we use this schema in composed oneOf schemas - return schema; - } else if (Boolean.TRUE.equals(ref.getNullable()) && ref.getEnum() == null) { - // non enum primitive with nullable True - // we make these models so instances of this will be subclasses of this model - return schema; - } else { - return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); - } - } - return schema; - } - - public String pythonDate(Object dateValue) { - String strValue = null; - if (dateValue instanceof OffsetDateTime) { - OffsetDateTime date = null; - try { - date = (OffsetDateTime) dateValue; - } catch (ClassCastException e) { - LOGGER.warn("Invalid `date` format for value {}", dateValue.toString()); - date = ((Date) dateValue).toInstant().atOffset(ZoneOffset.UTC); - } - strValue = date.format(iso8601Date); - } else { - strValue = dateValue.toString(); - } - return strValue; - } - - public String pythonDateTime(Object dateTimeValue) { - String strValue = null; - if (dateTimeValue instanceof OffsetDateTime) { - OffsetDateTime dateTime = null; - try { - dateTime = (OffsetDateTime) dateTimeValue; - } catch (ClassCastException e) { - LOGGER.warn("Invalid `date-time` format for value {}", dateTimeValue.toString()); - dateTime = ((Date) dateTimeValue).toInstant().atOffset(ZoneOffset.UTC); - } - strValue = dateTime.format(iso8601DateTime); - } else { - strValue = dateTimeValue.toString(); - } - return strValue; - } - - /** - * Return the default value of the property - * - * @param p OpenAPI property object - * @return string presentation of the default value of the property - */ - @Override - public String toDefaultValue(Schema p) { - Object defaultObject = null; - if (p.getDefault() != null) { - defaultObject = p.getDefault(); - } - - if (defaultObject == null) { - return null; - } - - String defaultValue = defaultObject.toString(); - if (ModelUtils.isDateSchema(p)) { - defaultValue = pythonDate(defaultObject); - } else if (ModelUtils.isDateTimeSchema(p)) { - defaultValue = pythonDateTime(defaultObject); - } else if (ModelUtils.isStringSchema(p) && !ModelUtils.isByteArraySchema(p) && !ModelUtils.isBinarySchema(p) && !ModelUtils.isFileSchema(p) && !ModelUtils.isUUIDSchema(p) && !ModelUtils.isEmailSchema(p)) { - defaultValue = ensureQuotes(defaultValue); - } else if (ModelUtils.isBooleanSchema(p)) { - if (Boolean.valueOf(defaultValue) == false) { - defaultValue = "False"; - } else { - defaultValue = "True"; - } - } - return defaultValue; - } - - @Override - public String toModelImport(String name) { - // name looks like Cat - return "from " + packagePath() + "." + modelPackage() + "." + toModelFilename(name) + " import " + toModelName(name); - } - - @Override - @SuppressWarnings("static-method") - public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { - // fix the imports that each model has, add the module reference to the model - // loops through imports and converts them all - // from 'Pet' to 'from petstore_api.model.pet import Pet' - - OperationMap val = objs.getOperations(); - List operations = val.getOperation(); - List> imports = objs.getImports(); - for (CodegenOperation operation : operations) { - if (operation.imports.size() == 0) { - continue; - } - String[] modelNames = operation.imports.toArray(new String[0]); - operation.imports.clear(); - for (String modelName : modelNames) { - operation.imports.add(toModelImport(modelName)); - } - } - generateEndpoints(objs); - return objs; - } - - /*** - * Override with special post-processing for all models. - * we have a custom version of this method to: - * - remove any primitive models that do not contain validations - * these models are unaliased as inline definitions wherever the spec has them as refs - * this means that the generated client does not use these models - * because they are not used we do not write them - * - fix the model imports, go from model name to the full import string with toModelImport + globalImportFixer - * Also cleans the test folder if test cases exist and the testFolder is set because the tests are autogenerated - * - * @param objs a map going from the model name to a object hoding the model info - * @return the updated objs - */ - @Override - public Map postProcessAllModels(Map objs) { - super.postProcessAllModels(objs); - - boolean anyModelContainsTestCases = false; - Map allDefinitions = ModelUtils.getSchemas(this.openAPI); - for (String schemaName : allDefinitions.keySet()) { - Schema refSchema = new Schema().$ref("#/components/schemas/" + schemaName); - Schema unaliasedSchema = unaliasSchema(refSchema); - String modelName = toModelName(schemaName); - if (unaliasedSchema.get$ref() == null) { - continue; - } - ModelsMap objModel = objs.get(modelName); - if (objModel == null) { - // to avoid form parameter's models that are not generated (skipFormModel=true) - continue; - } - for (ModelMap model : objModel.getModels()) { - CodegenModel cm = model.getModel(); - if (cm.testCases != null && !cm.testCases.isEmpty()) { - anyModelContainsTestCases = true; - } - String[] importModelNames = cm.imports.toArray(new String[0]); - cm.imports.clear(); - for (String importModelName : importModelNames) { - cm.imports.add(toModelImport(importModelName)); - } - } - } - boolean testFolderSet = testFolder != null; - if (testFolderSet && anyModelContainsTestCases) { - // delete the test folder because tests there will be autogenerated - String modelTestFolder = modelTestFileFolder(); - File testDirectory = new File(modelTestFolder); - try { - FileUtils.cleanDirectory(testDirectory); - } catch (IOException e) { - LOGGER.info("Unable to delete the test folder because of exception=" + e.toString()); - } - - } - - return objs; - } - - public CodegenParameter fromParameter(Parameter parameter, Set imports) { - CodegenParameter cp = super.fromParameter(parameter, imports); - if (parameter.getStyle() != null) { - switch(parameter.getStyle()) { - case MATRIX: - cp.style = "MATRIX"; - break; - case LABEL: - cp.style = "LABEL"; - break; - case FORM: - cp.style = "FORM"; - break; - case SIMPLE: - cp.style = "SIMPLE"; - break; - case SPACEDELIMITED: - cp.style = "SPACE_DELIMITED"; - break; - case PIPEDELIMITED: - cp.style = "PIPE_DELIMITED"; - break; - case DEEPOBJECT: - cp.style = "DEEP_OBJECT"; - break; - } - } - // clone this so we can change some properties on it - CodegenProperty schemaProp = cp.getSchema().clone(); - // parameters may have valid python names like some_val or invalid ones like Content-Type - // we always set nameInSnakeCase to null so special handling will not be done for these names - // invalid python names will be handled in python by using a TypedDict which will allow us to have a type hint - // for keys that cannot be variable names to the schema baseName - if (schemaProp != null) { - schemaProp.nameInSnakeCase = null; - schemaProp.baseName = toModelName(cp.baseName) + "Schema"; - cp.setSchema(schemaProp); - } - return cp; - } - - private boolean isValidPythonVarOrClassName(String name) { - return name.matches("^[_a-zA-Z][_a-zA-Z0-9]*$"); - } - - - /** - * Convert OAS Property object to Codegen Property object - * We have a custom version of this method to always set allowableValues.enumVars on all enum variables - * Together with unaliasSchema this sets primitive types with validations as models - * This method is used by fromResponse - * - * @param name name of the property - * @param p OAS property object - * @return Codegen Property object - */ - @Override - public CodegenProperty fromProperty(String name, Schema p, boolean required) { - CodegenProperty cp = super.fromProperty(name, p, required); - if (cp.isAnyType && cp.isNullable) { - cp.isNullable = false; - } - if (cp.isNullable && cp.complexType == null) { - cp.setIsNull(true); - cp.isNullable = false; - cp.setHasMultipleTypes(true); - } - postProcessPattern(cp.pattern, cp.vendorExtensions); - // if we have a property that has a difficult name, either: - // 1. name is reserved, like class int float - // 2. name is invalid in python like '3rd' or 'Content-Type' - // set cp.nameInSnakeCase to a value so we can tell that we are in this use case - // we handle this in the schema templates - // templates use its presence to handle these badly named variables / keys - if ((isReservedWord(name) || !isValidPythonVarOrClassName(name)) && !name.equals(cp.name)) { - cp.nameInSnakeCase = cp.name; - cp.baseName = (String) processTestExampleData(name); - } else { - cp.nameInSnakeCase = null; - } - if (cp.isEnum) { - updateCodegenPropertyEnum(cp); - } - Schema unaliasedSchema = unaliasSchema(p); - if (cp.isPrimitiveType && unaliasedSchema.get$ref() != null) { - cp.complexType = cp.dataType; - } - setAdditionalPropsAndItemsVarNames(cp); - return cp; - } - - private void setAdditionalPropsAndItemsVarNames(IJsonSchemaValidationProperties item) { - if (item.getAdditionalProperties() != null) { - item.getAdditionalProperties().setBaseName("_additional_properties"); - } - if (item.getItems() != null) { - item.getItems().setBaseName("_items"); - } - } - - /** - * checks if the data should be classified as "string" in enum - * e.g. double in C# needs to be double-quoted (e.g. "2.8") by treating it as a string - * In the future, we may rename this function to "isEnumString" - * - * @param dataType data type - * @return true if it's a enum string - */ - @Override - public boolean isDataTypeString(String dataType) { - return "str".equals(dataType); - } - - /** - * Update codegen property's enum by adding "enumVars" (with name and value) - * - * @param var list of CodegenProperty - */ - @Override - public void updateCodegenPropertyEnum(CodegenProperty var) { - // we have a custom version of this method to omit overwriting the defaultValue - Map allowableValues = var.allowableValues; - - // handle array - if (var.mostInnerItems != null) { - allowableValues = var.mostInnerItems.allowableValues; - } - - if (allowableValues == null) { - return; - } - - List values = (List) allowableValues.get("values"); - if (values == null) { - return; - } - - String varDataType = var.mostInnerItems != null ? var.mostInnerItems.dataType : var.dataType; - Schema referencedSchema = getModelNameToSchemaCache().get(varDataType); - String dataType = (referencedSchema != null) ? getTypeDeclaration(referencedSchema) : varDataType; - - // put "enumVars" map into `allowableValues", including `name` and `value` - List> enumVars = buildEnumVars(values, dataType); - - // if "x-enum-varnames" or "x-enum-descriptions" defined, update varnames - Map extensions = var.mostInnerItems != null ? var.mostInnerItems.getVendorExtensions() : var.getVendorExtensions(); - if (referencedSchema != null) { - extensions = referencedSchema.getExtensions(); - } - updateEnumVarsWithExtensions(enumVars, extensions, dataType); - allowableValues.put("enumVars", enumVars); - // overwriting defaultValue omitted from here - } - - /*** - * We have a custom version of this method to produce links to models when they are - * primitive type (not map, not array, not object) and include validations or are enums - * - * @param body requesst body - * @param imports import collection - * @param bodyParameterName body parameter name - * @return the resultant CodegenParameter - */ - @Override - public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { - CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName); - cp.baseName = "body"; - Schema schema = ModelUtils.getSchemaFromRequestBody(body); - if (schema.get$ref() == null) { - return cp; - } - Schema unaliasedSchema = unaliasSchema(schema); - CodegenProperty unaliasedProp = fromProperty("body", unaliasedSchema, false); - Boolean dataTypeMismatch = !cp.dataType.equals(unaliasedProp.dataType); - Boolean baseTypeMismatch = !cp.baseType.equals(unaliasedProp.complexType) && unaliasedProp.complexType != null; - if (dataTypeMismatch || baseTypeMismatch) { - cp.dataType = unaliasedProp.dataType; - cp.baseType = unaliasedProp.complexType; - } - return cp; - } - - /*** - * Adds the body model schema to the body parameter - * We have a custom version of this method so we can flip forceSimpleRef - * to True based upon the results of unaliasSchema - * With this customization, we ensure that when schemas are passed to getSchemaType - * - if they have ref in them they are a model - * - if they do not have ref in them they are not a model - * and code is also customized to allow anyType request body schemas - * - * @param codegenParameter the body parameter - * @param name model schema ref key in components - * @param schema the model schema (not refed) - * @param imports collection of imports - * @param bodyParameterName body parameter name - * @param forceSimpleRef if true use a model reference - */ - @Override - protected void addBodyModelSchema(CodegenParameter codegenParameter, String name, Schema schema, Set imports, String bodyParameterName, boolean forceSimpleRef) { - if (name != null) { - Schema bodySchema = new Schema().$ref("#/components/schemas/" + name); - Schema unaliased = unaliasSchema(bodySchema); - if (unaliased.get$ref() != null) { - forceSimpleRef = true; - } - } - - CodegenModel codegenModel = null; - if (StringUtils.isNotBlank(name)) { - schema.setName(name); - codegenModel = fromModel(name, schema); - } - if (codegenModel != null) { - codegenParameter.isModel = true; - } - - if (codegenModel != null && (codegenModel.hasVars || forceSimpleRef)) { - if (StringUtils.isEmpty(bodyParameterName)) { - codegenParameter.baseName = codegenModel.classname; - } else { - codegenParameter.baseName = bodyParameterName; - } - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.baseType = codegenModel.classname; - codegenParameter.dataType = getTypeDeclaration(codegenModel.classname); - codegenParameter.description = codegenModel.description; - codegenParameter.isNullable = codegenModel.isNullable; - imports.add(codegenParameter.baseType); - } else { - CodegenProperty codegenProperty = fromProperty("property", schema, false); - - if (codegenProperty != null && codegenProperty.getComplexType() != null && codegenProperty.getComplexType().contains(" | ")) { - List parts = Arrays.asList(codegenProperty.getComplexType().split(" \\| ")); - imports.addAll(parts); - String codegenModelName = codegenProperty.getComplexType(); - codegenParameter.baseName = codegenModelName; - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.baseType = codegenParameter.baseName; - codegenParameter.dataType = getTypeDeclaration(codegenModelName); - codegenParameter.description = codegenProperty.getDescription(); - codegenParameter.isNullable = codegenProperty.isNullable; - } else { - if (ModelUtils.isMapSchema(schema)) {// http body is map - LOGGER.error("Map should be supported. Please report to openapi-generator github repo about the issue."); - } else if (codegenProperty != null) { - String codegenModelName, codegenModelDescription; - - if (codegenModel != null) { - codegenModelName = codegenModel.classname; - codegenModelDescription = codegenModel.description; - } else { - codegenModelName = "anyType"; - codegenModelDescription = ""; - } - - if (StringUtils.isEmpty(bodyParameterName)) { - codegenParameter.baseName = codegenModelName; - } else { - codegenParameter.baseName = bodyParameterName; - } - - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.baseType = codegenModelName; - codegenParameter.dataType = getTypeDeclaration(codegenModelName); - codegenParameter.description = codegenModelDescription; - - if (codegenProperty.complexType != null) { - imports.add(codegenProperty.complexType); - } - } - } - - // set nullable - setParameterNullable(codegenParameter, codegenProperty); - } - - } - - - /** - * Return the sanitized variable name for enum - * - * @param value enum variable name - * @param datatype data type - * @return the sanitized variable name for enum - */ - public String toEnumVarName(String value, String datatype) { - // our enum var names are keys in a python dict, so change spaces to underscores - if (value.length() == 0) { - return "EMPTY"; - } - - String intPattern = "^[-\\+]?\\d+$"; - String floatPattern = "^[-\\+]?\\d+\\.\\d+$"; - Boolean intMatch = Pattern.matches(intPattern, value); - Boolean floatMatch = Pattern.matches(floatPattern, value); - if (intMatch || floatMatch) { - String plusSign = "^\\+.+"; - String negSign = "^-.+"; - if (Pattern.matches(plusSign, value)) { - value = value.replace("+", "POSITIVE_"); - } else if (Pattern.matches(negSign, value)) { - value = value.replace("-", "NEGATIVE_"); - } else { - value = "POSITIVE_" + value; - } - if (floatMatch) { - value = value.replace(".", "_PT_"); - } - return value; - } - // Replace " " with _ - String usedValue = value.replaceAll("\\s+", "_").toUpperCase(Locale.ROOT); - // strip first character if it is invalid - usedValue = usedValue.replaceAll("^[^_a-zA-Z]", ""); - usedValue = usedValue.replaceAll("[^_a-zA-Z0-9]*", ""); - if (usedValue.length() == 0) { - for (int i = 0; i < value.length(); i++){ - Character c = value.charAt(i); - String charName = Character.getName(c.hashCode()); - usedValue += charNameToVarName(charName); - } - // remove trailing _ - usedValue = usedValue.replaceAll("[_]$", ""); - } - return usedValue; - } - - /** - * Replace - and " " with _ - * Remove SIGN - * - * @param charName - * @return - */ - private String charNameToVarName(String charName) { - String varName = charName.replaceAll("[\\-\\s]", "_"); - varName = varName.replaceAll("SIGN", ""); - return varName; - } - - /** - * Return the enum value in the language specified format - * e.g. status becomes "status" - * - * @param value enum variable name - * @param datatype data type - * @return the sanitized value for enum - */ - public String toEnumValue(String value, String datatype) { - if ("int".equals(datatype) || "float".equals(datatype) || datatype.equals("int, float")) { - return value; - } else if ("bool".equals(datatype)) { - if (value.equals("true")) { - return "BoolClass.TRUE"; - } - return "BoolClass.FALSE"; - } else { - String fixedValue = (String) processTestExampleData(value); - return ensureQuotes(fixedValue); - } - } - - @Override - public void postProcessParameter(CodegenParameter p) { - postProcessPattern(p.pattern, p.vendorExtensions); - if (p.baseType != null && languageSpecificPrimitives.contains(p.baseType)) { - // set baseType to null so the api docs will not point to a model for languageSpecificPrimitives - p.baseType = null; - } - } - - /** - * Sets the value of the 'model.parent' property in CodegenModel - * We have a custom version of this function so we can add the dataType on the ArrayModel - */ - @Override - protected void addParentContainer(CodegenModel model, String name, Schema schema) { - super.addParentContainer(model, name, schema); - - List referencedModelNames = new ArrayList(); - model.dataType = getTypeString(schema, "", "", referencedModelNames); - } - - protected String toTestCaseName(String specTestCaseName) { - return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, specTestCaseName); - } - - protected Object processTestExampleData(Object value) { - if (value instanceof Integer){ - return value; - } else if (value instanceof Double || value instanceof Float || value instanceof Boolean){ - return value; - } else if (value instanceof String) { - String stringValue = (String) value; - String backslash = "\\"; - if (stringValue.contains(backslash)) { - stringValue = stringValue.replace(backslash, "\\\\"); - } - String nullChar = "\0"; - if (stringValue.contains(nullChar)) { - stringValue = stringValue.replace(nullChar, "\\x00"); - } - String doubleQuoteChar = "\""; - if (stringValue.contains(doubleQuoteChar)) { - stringValue = stringValue.replace(doubleQuoteChar, "\\\""); - } - String lineSep = System.lineSeparator(); - if (stringValue.contains(lineSep)) { - stringValue = stringValue.replace(lineSep, "\\n"); - } - String carriageReturn = "\r"; - if (stringValue.contains(carriageReturn)) { - stringValue = stringValue.replace(carriageReturn, "\\r"); - } - String tab = "\t"; - if (stringValue.contains(tab)) { - stringValue = stringValue.replace(tab, "\\t"); - } - String formFeed = "\f"; - if (stringValue.contains(formFeed)) { - stringValue = stringValue.replace(formFeed, "\\f"); - } - return stringValue; - } else if (value instanceof LinkedHashMap) { - LinkedHashMap fixedValues = new LinkedHashMap(); - for (Map.Entry entry: ((LinkedHashMap) value).entrySet()) { - String entryKey = (String) processTestExampleData(entry.getKey()); - Object entryValue = processTestExampleData(entry.getValue()); - fixedValues.put(entryKey, entryValue); - } - return fixedValues; - } else if (value instanceof ArrayList) { - ArrayList fixedValues = (ArrayList) value; - for (int i = 0; i < fixedValues.size(); i++) { - Object item = processTestExampleData(fixedValues.get(i)); - fixedValues.set(i, item); - } - return fixedValues; - } else if (value == null) { - return value; - } - return value; - } - - /** - * Convert OAS Model object to Codegen Model object - * We have a custom version of this method so we can: - * - set the correct regex values for requiredVars + optionalVars - * - set model.defaultValue and model.hasRequired per the three use cases defined in this method - * - * @param name the name of the model - * @param sc OAS Model object - * @return Codegen Model object - */ - @Override - public CodegenModel fromModel(String name, Schema sc) { - CodegenModel cm = super.fromModel(name, sc); - Schema unaliasedSchema = unaliasSchema(sc); - if (unaliasedSchema != null) { - if (ModelUtils.isDecimalSchema(unaliasedSchema)) { // type: string, format: number - cm.isString = false; - cm.isDecimal = true; - } - } - - if (cm.isNullable) { - cm.setIsNull(true); - cm.isNullable = false; - cm.setHasMultipleTypes(true); - } - // TODO improve this imports addition code - if (cm.isArray && cm.getItems() != null && cm.getItems().complexType != null) { - cm.imports.add(cm.getItems().complexType); - } - if (cm.isArray && cm.getItems() != null && cm.getItems().mostInnerItems != null && cm.getItems().mostInnerItems.complexType != null) { - cm.imports.add(cm.getItems().mostInnerItems.complexType); - } - Boolean isNotPythonModelSimpleModel = (ModelUtils.isComposedSchema(sc) || ModelUtils.isObjectSchema(sc) || ModelUtils.isMapSchema(sc)); - setAdditionalPropsAndItemsVarNames(cm); - if (isNotPythonModelSimpleModel) { - return cm; - } - String defaultValue = toDefaultValue(sc); - if (sc.getDefault() != null) { - cm.defaultValue = defaultValue; - } - return cm; - } - - /** - * Returns the python type for the property. - * - * @param schema property schema - * @return string presentation of the type - **/ - @SuppressWarnings("static-method") - @Override - public String getSchemaType(Schema schema) { - String openAPIType = getSingleSchemaType(schema); - if (typeMapping.containsKey(openAPIType)) { - String type = typeMapping.get(openAPIType); - return type; - } - return toModelName(openAPIType); - } - - public String getModelName(Schema sc) { - if (sc.get$ref() != null) { - Schema unaliasedSchema = unaliasSchema(sc); - if (unaliasedSchema.get$ref() != null) { - return toModelName(ModelUtils.getSimpleRef(sc.get$ref())); - } - } - return null; - } - - /** - * Return a string representation of the Python types for the specified OAS schema. - * Primitive types in the OAS specification are implemented in Python using the corresponding - * Python primitive types. - * Composed types (e.g. allAll, oneOf, anyOf) are represented in Python using list of types. - *

        - * The caller should set the prefix and suffix arguments to empty string, except when - * getTypeString invokes itself recursively. A non-empty prefix/suffix may be specified - * to wrap the return value in a python dict, list or tuple. - *

        - * Examples: - * - "bool, date, float" The data must be a bool, date or float. - * - "[bool, date]" The data must be an array, and the array items must be a bool or date. - * - * @param p The OAS schema. - * @param prefix prepended to the returned value. - * @param suffix appended to the returned value. - * @param referencedModelNames a list of models that are being referenced while generating the types, - * may be used to generate imports. - * @return a comma-separated string representation of the Python types - */ - private String getTypeString(Schema p, String prefix, String suffix, List referencedModelNames) { - String fullSuffix = suffix; - if (")".equals(suffix)) { - fullSuffix = "," + suffix; - } - if (StringUtils.isNotEmpty(p.get$ref())) { - // The input schema is a reference. If the resolved schema is - // a composed schema, convert the name to a Python class. - Schema unaliasedSchema = unaliasSchema(p); - if (unaliasedSchema.get$ref() != null) { - String modelName = toModelName(ModelUtils.getSimpleRef(p.get$ref())); - if (referencedModelNames != null) { - referencedModelNames.add(modelName); - } - return prefix + modelName + fullSuffix; - } - } - if (ModelUtils.isAnyType(p)) { - return prefix + "bool, date, datetime, dict, float, int, list, str, none_type" + suffix; - } - // Resolve $ref because ModelUtils.isXYZ methods do not automatically resolve references. - if (ModelUtils.isNullable(ModelUtils.getReferencedSchema(this.openAPI, p))) { - fullSuffix = ", none_type" + suffix; - } - if (ModelUtils.isNumberSchema(p)) { - return prefix + "int, float" + fullSuffix; - } else if (ModelUtils.isTypeObjectSchema(p)) { - if (p.getAdditionalProperties() != null && p.getAdditionalProperties().equals(false)) { - if (p.getProperties() == null) { - // type object with no properties and additionalProperties = false, empty dict only - return prefix + "{str: typing.Any}" + fullSuffix; - } else { - // properties only - // TODO add type hints for those properties only as values - return prefix + "{str: typing.Any}" + fullSuffix; - } - } else { - // additionalProperties exists - Schema inner = getAdditionalProperties(p); - return prefix + "{str: " + getTypeString(inner, "(", ")", referencedModelNames) + "}" + fullSuffix; - // TODO add code here to add property values too if they exist - } - } else if (ModelUtils.isArraySchema(p)) { - ArraySchema ap = (ArraySchema) p; - Schema inner = ap.getItems(); - if (inner == null) { - // In OAS 3.0.x, the array "items" attribute is required. - // In OAS >= 3.1, the array "items" attribute is optional such that the OAS - // specification is aligned with the JSON schema specification. - // When "items" is not specified, the elements of the array may be anything at all. - // In that case, the return value should be: - // "[bool, date, datetime, dict, float, int, list, str, none_type]" - // Using recursion to wrap the allowed python types in an array. - Schema anyType = new Schema(); // A Schema without any attribute represents 'any type'. - return getTypeString(anyType, "[", "]", referencedModelNames); - } else { - return prefix + getTypeString(inner, "[", "]", referencedModelNames) + fullSuffix; - } - } else if (ModelUtils.isFileSchema(p)) { - return prefix + "file_type" + fullSuffix; - } - String baseType = getSchemaType(p); - return prefix + baseType + fullSuffix; - } - - /** - * Output the type declaration of a given name - * - * @param p property schema - * @return a string presentation of the type - */ - @Override - public String getTypeDeclaration(Schema p) { - // this is used to set dataType, which defines a python tuple of classes - // in Python we will wrap this in () to make it a tuple but here we - // will omit the parens so the generated documentation will not include - // them - return getTypeString(p, "", "", null); - } - - @Override - public String toInstantiationType(Schema property) { - if (ModelUtils.isArraySchema(property) || ModelUtils.isMapSchema(property) || property.getAdditionalProperties() != null) { - return getSchemaType(property); - } - return super.toInstantiationType(property); - } - - @Override - protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { - Schema addProps = getAdditionalProperties(schema); - if (addProps != null) { - // if AdditionalProperties exists, get its datatype and - // store it in codegenModel.additionalPropertiesType. - // The 'addProps' may be a reference, getTypeDeclaration will resolve - // the reference. - List referencedModelNames = new ArrayList(); - codegenModel.additionalPropertiesType = getTypeString(addProps, "", "", referencedModelNames); - if (referencedModelNames.size() != 0) { - // Models that are referenced in the 'additionalPropertiesType' keyword - // must be added to the imports. - codegenModel.imports.addAll(referencedModelNames); - } - } - // If addProps is null, the value of the 'additionalProperties' keyword is set - // to false, i.e. no additional properties are allowed. - } - - /** - * Gets an example if it exists - * - * @param sc input schema - * @return the example value - */ - protected Object getObjectExample(Schema sc) { - Schema schema = sc; - String ref = sc.get$ref(); - if (ref != null) { - schema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); - } - // TODO handle examples in object models in the future - Boolean objectModel = (ModelUtils.isObjectSchema(schema) || ModelUtils.isMapSchema(schema) || ModelUtils.isComposedSchema(schema)); - if (objectModel) { - return null; - } - if (schema.getExample() != null) { - return schema.getExample(); - } - if (schema.getDefault() != null) { - return schema.getDefault(); - } else if (schema.getEnum() != null && !schema.getEnum().isEmpty()) { - return schema.getEnum().get(0); - } - return null; - } - - /*** - * Ensures that the string has a leading and trailing quote - * - * @param in input string - * @return quoted string - */ - private String ensureQuotes(String in) { - String strPattern = "^['\"].*?['\"]$"; - if (in.matches(strPattern)) { - return in; - } - return "\"" + in + "\""; - } - - @Override - public String toExampleValue(Schema schema) { - String modelName = getModelName(schema); - Object objExample = getObjectExample(schema); - return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, new ArrayList<>()); - } - - public String toExampleValue(Schema schema, Object objExample) { - String modelName = getModelName(schema); - return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, new ArrayList<>()); - } - - private Boolean simpleStringSchema(Schema schema) { - Schema sc = schema; - String ref = schema.get$ref(); - if (ref != null) { - sc = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); - } - if (ModelUtils.isStringSchema(sc) && !ModelUtils.isDateSchema(sc) && !ModelUtils.isDateTimeSchema(sc) && !"Number".equalsIgnoreCase(sc.getFormat()) && !ModelUtils.isByteArraySchema(sc) && !ModelUtils.isBinarySchema(sc) && schema.getPattern() == null) { - return true; - } - return false; - } - - private MappedModel getDiscriminatorMappedModel(CodegenDiscriminator disc) { - for (MappedModel mm : disc.getMappedModels()) { - String modelName = mm.getModelName(); - Schema modelSchema = getModelNameToSchemaCache().get(modelName); - if (ModelUtils.isObjectSchema(modelSchema)) { - return mm; - } - } - return null; - } - - /*** - * Recursively generates string examples for schemas - * - * @param modelName the string name of the refed model that will be generated for the schema or null - * @param schema the schema that we need an example for - * @param objExample the example that applies to this schema, for now only string example are used - * @param indentationLevel integer indentation level that we are currently at - * we assume the indentaion amount is 4 spaces times this integer - * @param prefix the string prefix that we will use when assigning an example for this line - * this is used when setting key: value, pairs "key: " is the prefix - * and this is used when setting properties like some_property='some_property_example' - * @param exampleLine this is the current line that we are generatign an example for, starts at 0 - * we don't indentin the 0th line because using the example value looks like: - * prop = ModelName( line 0 - * some_property='some_property_example' line 1 - * ) line 2 - * and our example value is: - * ModelName( line 0 - * some_property='some_property_example' line 1 - * ) line 2 - * @param includedSchemas are a list of schemas that we have moved through to get here. If the new schemas that we - * are looking at is in includedSchemas then we have hit a cycle. - * @return the string example - */ - private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine, List includedSchemas) { - boolean couldHaveCycle = includedSchemas.size() > 0 && potentiallySelfReferencingSchema(schema); - // If we have seen the ContextAwareSchemaNode more than once before, we must be in a cycle. - boolean cycleFound = false; - if (couldHaveCycle) { - cycleFound = includedSchemas.subList(0, includedSchemas.size()-1).stream().anyMatch(s -> schema.equals(s)); - } - final String indentionConst = " "; - String currentIndentation = ""; - String closingIndentation = ""; - for (int i = 0; i < indentationLevel; i++) currentIndentation += indentionConst; - if (exampleLine.equals(0)) { - closingIndentation = currentIndentation; - currentIndentation = ""; - } else { - closingIndentation = currentIndentation; - } - String openChars = ""; - String closeChars = ""; - if (modelName != null) { - openChars = modelName + "("; - closeChars = ")"; - } - - String fullPrefix = currentIndentation + prefix + openChars; - - String example = null; - if (objExample != null) { - example = objExample.toString(); - } - if (null != schema.get$ref()) { - Map allDefinitions = ModelUtils.getSchemas(this.openAPI); - String ref = ModelUtils.getSimpleRef(schema.get$ref()); - Schema refSchema = allDefinitions.get(ref); - if (null == refSchema) { - LOGGER.warn("Unable to find referenced schema " + schema.get$ref() + "\n"); - return fullPrefix + "None" + closeChars; - } - String refModelName = getModelName(schema); - return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine, includedSchemas); - } else if (ModelUtils.isNullType(schema)) { - // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, - // though this tooling supports it. - return fullPrefix + "None" + closeChars; - } else if (ModelUtils.isAnyType(schema)) { - /* - This schema may be a composed schema - TODO generate examples for some of these use cases in the future like - only oneOf without a discriminator - */ - Boolean hasProperties = (schema.getProperties() != null && !schema.getProperties().isEmpty()); - CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); - if (ModelUtils.isComposedSchema(schema)) { - // complex composed object type schemas not yet handled and the code returns early - if (hasProperties) { - // what if this composed schema defined properties + allOf? - // or items + properties, both a ist and a dict could be accepted as payloads - return fullPrefix + "{}" + closeChars; - } - ComposedSchema cs = (ComposedSchema) schema; - Integer allOfExists = 0; - if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { - allOfExists = 1; - } - Integer anyOfExists = 0; - if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { - anyOfExists = 1; - } - Integer oneOfExists = 0; - if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { - oneOfExists = 1; - } - if (allOfExists + anyOfExists + oneOfExists > 1) { - // what if it needs one oneOf schema, one anyOf schema, and two allOf schemas? - return fullPrefix + "None" + closeChars; - } - // for now only oneOf with discriminator is supported - if (oneOfExists == 1 && disc != null) { - ; - } else { - return fullPrefix + "None" + closeChars; - } - } - if (disc != null) { - // a discriminator means that the type must be object - MappedModel mm = getDiscriminatorMappedModel(disc); - if (mm == null) { - return fullPrefix + "None" + closeChars; - } - String discPropNameValue = mm.getMappingName(); - String chosenModelName = mm.getModelName(); - Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); - CodegenProperty cp = new CodegenProperty(); - cp.setName(disc.getPropertyName()); - cp.setExample(discPropNameValue); - return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, includedSchemas); - } - return fullPrefix + "None" + closeChars; - } else if (ModelUtils.isBooleanSchema(schema)) { - if (example == null) { - example = "True"; - } else { - if ("false".equalsIgnoreCase(objExample.toString())) { - example = "False"; - } else { - example = "True"; - } - } - return fullPrefix + example + closeChars; - } else if (ModelUtils.isStringSchema(schema)) { - if (example != null) { - return fullPrefix + ensureQuotes(example) + closeChars; - } - if (ModelUtils.isDateSchema(schema)) { - if (objExample == null) { - example = pythonDate("1970-01-01"); - } else { - example = pythonDate(objExample); - } - } else if (ModelUtils.isDateTimeSchema(schema)) { - if (objExample == null) { - example = pythonDateTime("1970-01-01T00:00:00.00Z"); - } else { - example = pythonDateTime(objExample); - } - } else if (ModelUtils.isBinarySchema(schema)) { - if (example == null) { - example = "/path/to/file"; - } - example = "open('" + example + "', 'rb')"; - return fullPrefix + example + closeChars; - } else if (ModelUtils.isByteArraySchema(schema)) { - if (objExample == null) { - example = "'YQ=='"; - } - } else if ("Number".equalsIgnoreCase(schema.getFormat())) { - // a BigDecimal: - example = "2"; - } else if (StringUtils.isNotBlank(schema.getPattern())) { - String pattern = schema.getPattern(); - /* - RxGen does not support our ECMA dialect https://github.com/curious-odd-man/RgxGen/issues/56 - So strip off the leading / and trailing / and turn on ignore case if we have it - */ - Pattern valueExtractor = Pattern.compile("^/?(.+?)/?(.?)$"); - Matcher m = valueExtractor.matcher(pattern); - RgxGen rgxGen = null; - if (m.find()) { - int groupCount = m.groupCount(); - if (groupCount == 1) { - // only pattern found - String isolatedPattern = m.group(1); - rgxGen = new RgxGen(isolatedPattern); - } else if (groupCount == 2) { - // patterns and flag found - String isolatedPattern = m.group(1); - String flags = m.group(2); - if (flags.contains("i")) { - rgxGen = new RgxGen(isolatedPattern); - RgxGenProperties properties = new RgxGenProperties(); - RgxGenOption.CASE_INSENSITIVE.setInProperties(properties, true); - rgxGen.setProperties(properties); - } else { - rgxGen = new RgxGen(isolatedPattern); - } - } - } else { - rgxGen = new RgxGen(pattern); - } - - // this seed makes it so if we have [a-z] we pick a - Random random = new Random(18); - if (rgxGen != null) { - example = rgxGen.generate(random); - } else { - throw new RuntimeException("rgxGen cannot be null. Please open an issue in the openapi-generator github repo."); - } - } else if (schema.getMinLength() != null) { - example = ""; - int len = schema.getMinLength().intValue(); - for (int i = 0; i < len; i++) example += "a"; - } else if (ModelUtils.isUUIDSchema(schema)) { - example = "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; - } else { - example = "string_example"; - } - return fullPrefix + ensureQuotes(example) + closeChars; - } else if (ModelUtils.isIntegerSchema(schema)) { - if (objExample == null) { - if (schema.getMinimum() != null) { - example = schema.getMinimum().toString(); - } else { - example = "1"; - } - } - return fullPrefix + example + closeChars; - } else if (ModelUtils.isNumberSchema(schema)) { - if (objExample == null) { - if (schema.getMinimum() != null) { - example = schema.getMinimum().toString(); - } else { - example = "3.14"; - } - } - return fullPrefix + example + closeChars; - } else if (ModelUtils.isArraySchema(schema)) { - if (objExample instanceof Iterable) { - // If the example is already a list, return it directly instead of wrongly wrap it in another list - return fullPrefix + objExample.toString() + closeChars; - } - if (ModelUtils.isComposedSchema(schema)) { - // complex composed array type schemas not yet handled and the code returns early - return fullPrefix + "[]" + closeChars; - } - ArraySchema arrayschema = (ArraySchema) schema; - Schema itemSchema = arrayschema.getItems(); - String itemModelName = getModelName(itemSchema); - includedSchemas.add(schema); - String itemExample = toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, "", exampleLine + 1, includedSchemas); - if (StringUtils.isEmpty(itemExample) || cycleFound) { - return fullPrefix + "[]" + closeChars; - } else { - return fullPrefix + "[" + "\n" + itemExample + "\n" + closingIndentation + "]" + closeChars; - } - } else if (ModelUtils.isTypeObjectSchema(schema)) { - if (modelName == null) { - fullPrefix += "dict("; - closeChars = ")"; - } - if (cycleFound) { - return fullPrefix + closeChars; - } - Boolean hasProperties = (schema.getProperties() != null && !schema.getProperties().isEmpty()); - CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); - if (ModelUtils.isComposedSchema(schema)) { - // complex composed object type schemas not yet handled and the code returns early - if (hasProperties) { - // what if this composed schema defined properties + allOf? - return fullPrefix + closeChars; - } - ComposedSchema cs = (ComposedSchema) schema; - Integer allOfExists = 0; - if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { - allOfExists = 1; - } - Integer anyOfExists = 0; - if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { - anyOfExists = 1; - } - Integer oneOfExists = 0; - if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { - oneOfExists = 1; - } - if (allOfExists + anyOfExists + oneOfExists > 1) { - // what if it needs one oneOf schema, one anyOf schema, and two allOf schemas? - return fullPrefix + closeChars; - } - // for now only oneOf with discriminator is supported - if (oneOfExists == 1 && disc != null) { - ; - } else { - return fullPrefix + closeChars; - } - } - if (disc != null) { - MappedModel mm = getDiscriminatorMappedModel(disc); - if (mm == null) { - return fullPrefix + closeChars; - } - String discPropNameValue = mm.getMappingName(); - String chosenModelName = mm.getModelName(); - Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); - CodegenProperty cp = new CodegenProperty(); - cp.setName(disc.getPropertyName()); - cp.setExample(discPropNameValue); - return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, includedSchemas); - } - Object addPropsObj = schema.getAdditionalProperties(); - if (hasProperties) { - return exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation, includedSchemas); - } else if (addPropsObj instanceof Schema) { - // TODO handle true case for additionalProperties - Schema addPropsSchema = (Schema) addPropsObj; - String key = "key"; - Object addPropsExample = getObjectExample(addPropsSchema); - if (addPropsSchema.getEnum() != null && !addPropsSchema.getEnum().isEmpty()) { - key = addPropsSchema.getEnum().get(0).toString(); - } - addPropsExample = exampleFromStringOrArraySchema(addPropsSchema, addPropsExample, key); - String addPropPrefix = key + "="; - if (modelName == null) { - addPropPrefix = ensureQuotes(key) + ": "; - } - String addPropsModelName = getModelName(addPropsSchema); - includedSchemas.add(schema); - example = fullPrefix + "\n" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1, includedSchemas) + ",\n" + closingIndentation + closeChars; - } else { - example = fullPrefix + closeChars; - } - } else { - LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue"); - } - - return example; - } - - private boolean potentiallySelfReferencingSchema(Schema schema) { - return null != schema.get$ref() || ModelUtils.isArraySchema(schema) || ModelUtils.isMapSchema(schema) || ModelUtils.isObjectSchema(schema) || ModelUtils.isComposedSchema(schema); - } - - private String exampleForObjectModel(Schema schema, String fullPrefix, String closeChars, CodegenProperty discProp, int indentationLevel, int exampleLine, String closingIndentation, List includedSchemas) { - Map requiredAndOptionalProps = schema.getProperties(); - if (requiredAndOptionalProps == null || requiredAndOptionalProps.isEmpty()) { - return fullPrefix + closeChars; - } - - String example = fullPrefix + "\n"; - for (Map.Entry entry : requiredAndOptionalProps.entrySet()) { - String propName = entry.getKey(); - Schema propSchema = entry.getValue(); - propName = toVarName(propName); - String propModelName = null; - Object propExample = null; - if (discProp != null && propName.equals(discProp.name)) { - propModelName = null; - propExample = discProp.example; - } else { - propModelName = getModelName(propSchema); - propExample = exampleFromStringOrArraySchema(propSchema, null, propName); - } - includedSchemas.add(schema); - example += toExampleValueRecursive(propModelName, propSchema, propExample, indentationLevel + 1, propName + "=", exampleLine + 1, includedSchemas) + ",\n"; - } - // TODO handle additionalProperties also - example += closingIndentation + closeChars; - return example; - } - - private Object exampleFromStringOrArraySchema(Schema sc, Object currentExample, String propName) { - if (currentExample != null) { - return currentExample; - } - Schema schema = sc; - String ref = sc.get$ref(); - if (ref != null) { - schema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); - } - Object example = getObjectExample(schema); - if (example != null) { - return example; - } else if (simpleStringSchema(schema)) { - return propName + "_example"; - } else if (ModelUtils.isArraySchema(schema)) { - ArraySchema arraySchema = (ArraySchema) schema; - Schema itemSchema = arraySchema.getItems(); - example = getObjectExample(itemSchema); - if (example != null) { - return example; - } else if (simpleStringSchema(itemSchema)) { - return propName + "_example"; - } - } - return null; - } - - - /*** - * - * Set the codegenParameter example value - * We have a custom version of this function so we can invoke toExampleValue - * - * @param codegenParameter the item we are setting the example on - * @param parameter the base parameter that came from the spec - */ - @Override - public void setParameterExampleValue(CodegenParameter codegenParameter, Parameter parameter) { - Schema schema = parameter.getSchema(); - if (schema == null) { - LOGGER.warn("CodegenParameter.example defaulting to null because parameter lacks a schema"); - return; - } - - Object example = null; - if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { - example = codegenParameter.vendorExtensions.get("x-example"); - } else if (parameter.getExample() != null) { - example = parameter.getExample(); - } else if (parameter.getExamples() != null && !parameter.getExamples().isEmpty() && parameter.getExamples().values().iterator().next().getValue() != null) { - example = parameter.getExamples().values().iterator().next().getValue(); - } else { - example = getObjectExample(schema); - } - example = exampleFromStringOrArraySchema(schema, example, parameter.getName()); - String finalExample = toExampleValue(schema, example); - codegenParameter.example = finalExample; - } - - /** - * Return the example value of the parameter. - * - * @param codegenParameter Codegen parameter - * @param requestBody Request body - */ - @Override - public void setParameterExampleValue(CodegenParameter codegenParameter, RequestBody requestBody) { - if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { - codegenParameter.example = Json.pretty(codegenParameter.vendorExtensions.get("x-example")); - } - - Content content = requestBody.getContent(); - - if (content.size() > 1) { - // @see ModelUtils.getSchemaFromContent() - once(LOGGER).warn("Multiple MediaTypes found, using only the first one"); - } - - MediaType mediaType = content.values().iterator().next(); - Schema schema = mediaType.getSchema(); - if (schema == null) { - LOGGER.warn("CodegenParameter.example defaulting to null because requestBody content lacks a schema"); - return; - } - - Object example = null; - if (mediaType.getExample() != null) { - example = mediaType.getExample(); - } else if (mediaType.getExamples() != null && !mediaType.getExamples().isEmpty() && mediaType.getExamples().values().iterator().next().getValue() != null) { - example = mediaType.getExamples().values().iterator().next().getValue(); - } else { - example = getObjectExample(schema); - } - example = exampleFromStringOrArraySchema(schema, example, codegenParameter.paramName); - codegenParameter.example = toExampleValue(schema, example); - } - - /** - * Create a CodegenParameter for a Form Property - * We have a custom version of this method so we can invoke - * setParameterExampleValue(codegenParameter, parameter) - * rather than setParameterExampleValue(codegenParameter) - * This ensures that all of our samples are generated in - * toExampleValueRecursive - * - * @param name the property name - * @param propertySchema the property schema - * @param imports our import set - * @return the resultant CodegenParameter - */ - @Override - public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set imports) { - CodegenParameter cp = super.fromFormProperty(name, propertySchema, imports); - Parameter p = new Parameter(); - p.setSchema(propertySchema); - p.setName(cp.paramName); - setParameterExampleValue(cp, p); - return cp; - } - - /** - * Return a map from model name to Schema for efficient lookup. - * - * @return map from model name to Schema. - */ - protected Map getModelNameToSchemaCache() { - if (modelNameToSchemaCache == null) { - // Create a cache to efficiently lookup schema based on model name. - Map m = new HashMap(); - ModelUtils.getSchemas(openAPI).forEach((key, schema) -> { - m.put(toModelName(key), schema); - }); - modelNameToSchemaCache = Collections.unmodifiableMap(m); - } - return modelNameToSchemaCache; - } - - @Override - protected void setAddProps(Schema schema, IJsonSchemaValidationProperties property){ - if (schema.equals(new Schema())) { - // if we are trying to set additionalProperties on an empty schema stop recursing - return; - } - boolean additionalPropertiesIsAnyType = false; - CodegenModel m = null; - if (property instanceof CodegenModel) { - m = (CodegenModel) property; - } - CodegenProperty addPropProp = null; - boolean isAdditionalPropertiesTrue = false; - if (schema.getAdditionalProperties() == null) { - if (!disallowAdditionalPropertiesIfNotPresent) { - isAdditionalPropertiesTrue = true; - addPropProp = fromProperty("", new Schema()); - addPropProp.nameInSnakeCase = null; - additionalPropertiesIsAnyType = true; - } - } else if (schema.getAdditionalProperties() instanceof Boolean) { - if (Boolean.TRUE.equals(schema.getAdditionalProperties())) { - isAdditionalPropertiesTrue = true; - addPropProp = fromProperty("", new Schema()); - addPropProp.nameInSnakeCase = null; - additionalPropertiesIsAnyType = true; - } - } else { - addPropProp = fromProperty("", (Schema) schema.getAdditionalProperties()); - addPropProp.nameInSnakeCase = null; - if (isAnyTypeSchema((Schema) schema.getAdditionalProperties())) { - additionalPropertiesIsAnyType = true; - } - } - if (additionalPropertiesIsAnyType) { - property.setAdditionalPropertiesIsAnyType(true); - } - if (m != null && isAdditionalPropertiesTrue) { - m.isAdditionalPropertiesTrue = true; - } - if (ModelUtils.isComposedSchema(schema) && !supportsAdditionalPropertiesWithComposedSchema) { - return; - } - if (addPropProp != null) { - property.setAdditionalProperties(addPropProp); - } - } - - /** - * Update property for array(list) container - * - * @param property Codegen property - * @param innerProperty Codegen inner property of map or list - */ - @Override - protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) { - if (innerProperty == null) { - if(LOGGER.isWarnEnabled()) { - LOGGER.warn("skipping invalid array property {}", Json.pretty(property)); - } - return; - } - property.dataFormat = innerProperty.dataFormat; - if (languageSpecificPrimitives.contains(innerProperty.baseType)) { - property.isPrimitiveType = true; - } - property.items = innerProperty; - property.mostInnerItems = getMostInnerItems(innerProperty); - // inner item is Enum - if (isPropertyInnerMostEnum(property)) { - // isEnum is set to true when the type is an enum - // or the inner type of an array/map is an enum - property.isEnum = true; - // update datatypeWithEnum and default value for array - // e.g. List => List - updateDataTypeWithEnumForArray(property); - // set allowable values to enum values (including array/map of enum) - property.allowableValues = getInnerEnumAllowableValues(property); - } - - } - - protected void updatePropertyForString(CodegenProperty property, Schema p) { - if (ModelUtils.isByteArraySchema(p)) { - property.isByteArray = true; - property.setIsString(false); - } else if (ModelUtils.isBinarySchema(p)) { - property.isBinary = true; - property.isFile = true; // file = binary in OAS3 - } else if (ModelUtils.isUUIDSchema(p)) { - property.setIsString(false); // so the templates only see isUuid - property.setIsUuid(true); - } else if (ModelUtils.isURISchema(p)) { - property.isUri = true; - } else if (ModelUtils.isEmailSchema(p)) { - property.isEmail = true; - } else if (ModelUtils.isDateSchema(p)) { // date format - property.setIsString(false); // so the templates only see isDate - property.isDate = true; - } else if (ModelUtils.isDateTimeSchema(p)) { // date-time format - property.setIsString(false); // so the templates only see isDateTime - property.isDateTime = true; - } else if (ModelUtils.isDecimalSchema(p)) { // type: string, format: number - property.setIsString(false); // so the templates only see isDecimal - property.isDecimal = true; - } - property.pattern = toRegularExpression(p.getPattern()); - } - - @Override - protected void updatePropertyForObject(CodegenProperty property, Schema p) { - addVarsRequiredVarsAdditionalProps(p, property); - } - - @Override - protected void updatePropertyForAnyType(CodegenProperty property, Schema p) { - // The 'null' value is allowed when the OAS schema is 'any type'. - // See https://github.com/OAI/OpenAPI-Specification/issues/1389 - if (Boolean.FALSE.equals(p.getNullable())) { - LOGGER.warn("Schema '{}' is any type, which includes the 'null' value. 'nullable' cannot be set to 'false'", p.getName()); - } - addVarsRequiredVarsAdditionalProps(p, property); - } - - @Override - protected void updateModelForObject(CodegenModel m, Schema schema) { - if (schema.getProperties() != null || schema.getRequired() != null) { - // passing null to allProperties and allRequired as there's no parent - addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null); - } - // an object or anyType composed schema that has additionalProperties set - addAdditionPropertiesToCodeGenModel(m, schema); - // process 'additionalProperties' - setAddProps(schema, m); - } - - @Override - protected void updateModelForAnyType(CodegenModel m, Schema schema) { - // The 'null' value is allowed when the OAS schema is 'any type'. - // See https://github.com/OAI/OpenAPI-Specification/issues/1389 - if (Boolean.FALSE.equals(schema.getNullable())) { - LOGGER.error("Schema '{}' is any type, which includes the 'null' value. 'nullable' cannot be set to 'false'", m.name); - } - // todo add items support here in the future - if (schema.getProperties() != null || schema.getRequired() != null) { - // passing null to allProperties and allRequired as there's no parent - addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null); - } - addAdditionPropertiesToCodeGenModel(m, schema); - // process 'additionalProperties' - setAddProps(schema, m); - } - - @Override - protected void updateModelForComposedSchema(CodegenModel m, Schema schema, Map allDefinitions) { - final ComposedSchema composed = (ComposedSchema) schema; - - // TODO revise the logic below to set discriminator, xml attributes - if (composed.getAllOf() != null) { - int modelImplCnt = 0; // only one inline object allowed in a ComposedModel - int modelDiscriminators = 0; // only one discriminator allowed in a ComposedModel - for (Schema innerSchema : composed.getAllOf()) { // TODO need to work with anyOf, oneOf as well - if (m.discriminator == null && innerSchema.getDiscriminator() != null) { - LOGGER.debug("discriminator is set to null (not correctly set earlier): {}", m.name); - m.setDiscriminator(createDiscriminator(m.name, innerSchema, this.openAPI)); - if (!this.getLegacyDiscriminatorBehavior()) { - m.addDiscriminatorMappedModelsImports(); - } - modelDiscriminators++; - } - - if (innerSchema.getXml() != null) { - m.xmlPrefix = innerSchema.getXml().getPrefix(); - m.xmlNamespace = innerSchema.getXml().getNamespace(); - m.xmlName = innerSchema.getXml().getName(); - } - if (modelDiscriminators > 1) { - LOGGER.error("Allof composed schema is inheriting >1 discriminator. Only use one discriminator: {}", composed); - } - - if (modelImplCnt++ > 1) { - LOGGER.warn("More than one inline schema specified in allOf:. Only the first one is recognized. All others are ignored."); - break; // only one schema with discriminator allowed in allOf - } - } - } - - CodegenComposedSchemas cs = m.getComposedSchemas(); - if (cs != null) { - if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { - for (CodegenProperty cp: cs.getAllOf()) { - if (cp.complexType != null) { - addImport(m, cp.complexType); - } - } - } - if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { - for (CodegenProperty cp: cs.getOneOf()) { - if (cp.complexType != null) { - addImport(m, cp.complexType); - } - } - } - if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { - for (CodegenProperty cp: cs.getAnyOf()) { - if (cp.complexType != null) { - addImport(m, cp.complexType); - } - } - } - } - } - - @Override - public ModelsMap postProcessModels(ModelsMap objs) { - // process enum in models - return postProcessModelsEnum(objs); - } - - /* - * The OpenAPI pattern spec follows the Perl convention and style of modifiers. Python - * does not support this in as natural a way so it needs to convert it. See - * https://docs.python.org/2/howto/regex.html#compilation-flags for details. - */ - public void postProcessPattern(String pattern, Map vendorExtensions) { - if (pattern != null) { - int i = pattern.lastIndexOf('/'); - - //Must follow Perl /pattern/modifiers convention - if (pattern.charAt(0) != '/' || i < 2) { - throw new IllegalArgumentException("Pattern must follow the Perl " - + "/pattern/modifiers convention. " + pattern + " is not valid."); - } - - String regex = pattern.substring(1, i).replace("'", "\\'"); - List modifiers = new ArrayList(); - - for (char c : pattern.substring(i).toCharArray()) { - if (regexModifiers.containsKey(c)) { - String modifier = regexModifiers.get(c); - modifiers.add(modifier); - } - } - - vendorExtensions.put("x-regex", regex); - vendorExtensions.put("x-modifiers", modifiers); - } - } - - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - @Override - public String apiDocFileFolder() { - return (outputFolder + "/" + apiDocPath); - } - - @Override - public String modelDocFileFolder() { - return (outputFolder + "/" + modelDocPath); - } - - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - - @Override - public String toApiDocFilename(String name) { - return toApiName(name); - } - - @Override - public String addRegularExpressionDelimiter(String pattern) { - if (StringUtils.isEmpty(pattern)) { - return pattern; - } - - if (!pattern.matches("^/.*")) { - // Perform a negative lookbehind on each `/` to ensure that it is escaped. - return "/" + pattern.replaceAll("(? - * (PEP 0008) Python packages should also have short, all-lowercase names, - * although the use of underscores is discouraged. - * - * @param packageName Package name - * @return Python package name that conforms to PEP 0008 - */ - @SuppressWarnings("static-method") - public String generatePackageName(String packageName) { - return underscore(packageName.replaceAll("[^\\w]+", "")); - } - - /** - * A custom version of this method is needed to ensure that the form object parameter is kept as-is - * as an object and is not exploded into separate parameters - * @param body the body that is being handled - * @param imports the imports for this body - * @return the list of length one containing a single type object CodegenParameter - */ - @Override - public List fromRequestBodyToFormParameters(RequestBody body, Set imports) { - List parameters = new ArrayList<>(); - LOGGER.debug("debugging fromRequestBodyToFormParameters= {}", body); - Schema schema = ModelUtils.getSchemaFromRequestBody(body); - schema = ModelUtils.getReferencedSchema(this.openAPI, schema); - CodegenParameter cp = fromFormProperty("body", schema, imports); - cp.setContent(getContent(body.getContent(), imports, "RequestBody")); - cp.isFormParam = false; - cp.isBodyParam = true; - parameters.add(cp); - return parameters; - } - - /** - * Custom version of this method so we can move the body parameter into bodyParam - * - * @param path the path of the operation - * @param httpMethod HTTP method - * @param operation OAS operation object - * @param servers list of servers - * @return the resultant CodegenOperation instance - */ - @Override - public CodegenOperation fromOperation(String path, - String httpMethod, - Operation operation, - List servers) { - CodegenOperation co = super.fromOperation(path, httpMethod, operation, servers); - if (co.bodyParam == null) { - for (CodegenParameter cp: co.allParams) { - if (cp.isBodyParam) { - co.bodyParam = cp; - co.bodyParams.add(cp); - } - } - } - return co; - } - - @Override - public String defaultTemplatingEngine() { - return "handlebars"; - } - - @Override - public String generatorLanguageVersion() { return ">=3.9"; }; - - @Override - public void preprocessOpenAPI(OpenAPI openAPI) { - String originalSpecVersion; - String xOriginalSwaggerVersion = "x-original-swagger-version"; - if (openAPI.getExtensions() != null && !openAPI.getExtensions().isEmpty() && openAPI.getExtensions().containsValue(xOriginalSwaggerVersion)) { - originalSpecVersion = (String) openAPI.getExtensions().get(xOriginalSwaggerVersion); - } else { - originalSpecVersion = openAPI.getOpenapi(); - } - Integer specMajorVersion = Integer.parseInt(originalSpecVersion.substring(0, 1)); - if (specMajorVersion < 3) { - throw new RuntimeException("Your spec version of "+originalSpecVersion+" is too low. python-experimental only works with specs with version >= 3.X.X. Please use a tool like Swagger Editor or Swagger Converter to convert your spec to v3"); - } - } - - @Override - public void postProcess() { - System.out.println("################################################################################"); - System.out.println("# Thanks for using OpenAPI Generator. #"); - System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); - System.out.println("# https://opencollective.com/openapi_generator/donate #"); - System.out.println("# #"); - System.out.println("# This generator was written by Justin Black (https://github.com/spacether) #"); - System.out.println("# Please support his work directly via https://github.com/sponsors/spacether \uD83D\uDE4F#"); - System.out.println("################################################################################"); - } -} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java index a9358b4007..f667f7b6fc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFlaskConnexionServerCodegen.java @@ -56,5 +56,5 @@ public class PythonFlaskConnexionServerCodegen extends AbstractPythonConnexionSe } @Override - public String generatorLanguageVersion() { return "2.7 and 3.5.2+"; }; + public String generatorLanguageVersion() { return "3.5.2+"; }; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonPriorClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonPriorClientCodegen.java new file mode 100644 index 0000000000..c6d071e3b9 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonPriorClientCodegen.java @@ -0,0 +1,1521 @@ +/* + * 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 com.google.common.collect.Sets; +import io.swagger.v3.core.util.Json; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.parameters.RequestBody; +import io.swagger.v3.oas.models.security.SecurityScheme; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.CodegenDiscriminator.MappedModel; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.model.ModelMap; +import org.openapitools.codegen.model.ModelsMap; +import org.openapitools.codegen.model.OperationMap; +import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.utils.ProcessUtils; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.github.curiousoddman.rgxgen.RgxGen; +import com.github.curiousoddman.rgxgen.config.RgxGenOption; +import com.github.curiousoddman.rgxgen.config.RgxGenProperties; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.io.File; +import java.util.*; +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import static org.openapitools.codegen.utils.OnceLogger.once; + +public class PythonPriorClientCodegen extends PythonLegacyClientCodegen { + private final Logger LOGGER = LoggerFactory.getLogger(PythonPriorClientCodegen.class); + + // A cache to efficiently lookup a Schema instance based on the return value of `toModelName()`. + private Map modelNameToSchemaCache; + private DateTimeFormatter iso8601Date = DateTimeFormatter.ISO_DATE; + private DateTimeFormatter iso8601DateTime = DateTimeFormatter.ISO_DATE_TIME; + + public PythonPriorClientCodegen() { + super(); + + embeddedTemplateDir = templateDir = "python-prior"; + + // Composed schemas can have the 'additionalProperties' keyword, as specified in JSON schema. + // In principle, this should be enabled by default for all code generators. However due to limitations + // in other code generators, support needs to be enabled on a case-by-case basis. + supportsAdditionalPropertiesWithComposedSchema = true; + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) + .securityFeatures(EnumSet.of( + SecurityFeature.BasicAuth, + SecurityFeature.BearerToken, + SecurityFeature.ApiKey, + SecurityFeature.OAuth2_Implicit + )) + .includeGlobalFeatures( + GlobalFeature.ParameterizedServer + ) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + ); + // needed for type object with additionalProperties: false + typeMapping.put("object", "dict"); + + languageSpecificPrimitives.add("file_type"); + languageSpecificPrimitives.add("none_type"); + + // this generator does not use SORT_PARAMS_BY_REQUIRED_FLAG + // this generator uses the following order for endpoint parameters and model properties + // required params/props with no enum of length one + // required params/props with enum of length one (which is used to set a default value as a python named arg value) + // optional params/props with **kwargs in python + cliOptions.remove(4); + + cliOptions.add(new CliOption(CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET, CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET_DESC) + .defaultValue(Boolean.FALSE.toString())); + + cliOptions.add(new CliOption(CodegenConstants.INIT_REQUIRED_VARS, CodegenConstants.INIT_REQUIRED_VARS_DESC) + .defaultValue(Boolean.FALSE.toString())); + + // option to change how we process + set the data in the 'additionalProperties' keyword. + CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean( + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.FALSE.toString()); + Map disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>(); + disallowAdditionalPropertiesIfNotPresentOpts.put("false", + "The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications."); + disallowAdditionalPropertiesIfNotPresentOpts.put("true", + "Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. NOTE: "+ + "this option breaks composition and will be removed in 6.0.0" + ); + disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts); + cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.STABLE) + .build(); + } + + @Override + public void processOpts() { + this.setLegacyDiscriminatorBehavior(false); + + super.processOpts(); + modelPackage = packageName + "." + "model"; + + supportingFiles.add(new SupportingFile("model_utils.mustache", packagePath(), "model_utils.py")); + + + // add the models and apis folders + supportingFiles.add(new SupportingFile("__init__models.mustache", packagePath() + File.separatorChar + "models", "__init__.py")); + SupportingFile originalInitModel = supportingFiles.stream() + .filter(sf -> sf.getTemplateFile().equals("__init__model.mustache")) + .reduce((a, b) -> { + throw new IllegalStateException("Multiple elements: " + a + ", " + b); + }) + .orElse(null); + supportingFiles.remove(originalInitModel); + supportingFiles.add(new SupportingFile("__init__model.mustache", packagePath() + File.separatorChar + "model", "__init__.py")); + supportingFiles.add(new SupportingFile("__init__apis.mustache", packagePath() + File.separatorChar + "apis", "__init__.py")); + // Generate the 'signing.py' module, but only if the 'HTTP signature' security scheme is specified in the OAS. + Map securitySchemeMap = openAPI != null ? + (openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null) : null; + List authMethods = fromSecurity(securitySchemeMap); + if (ProcessUtils.hasHttpSignatureMethods(authMethods)) { + supportingFiles.add(new SupportingFile("signing.mustache", packagePath(), "signing.py")); + } + + Boolean generateSourceCodeOnly = false; + if (additionalProperties.containsKey(CodegenConstants.SOURCECODEONLY_GENERATION)) { + generateSourceCodeOnly = Boolean.valueOf(additionalProperties.get(CodegenConstants.SOURCECODEONLY_GENERATION).toString()); + } + + // default this to true so the python ModelSimple models will be generated + ModelUtils.setGenerateAliasAsModel(true); + LOGGER.info( + "{} is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums", + CodegenConstants.GENERATE_ALIAS_AS_MODEL); + + Boolean attrNoneIfUnset = false; + if (additionalProperties.containsKey(CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET)) { + attrNoneIfUnset = Boolean.valueOf(additionalProperties.get(CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET).toString()); + } + additionalProperties.put("attrNoneIfUnset", attrNoneIfUnset); + + // When the 'additionalProperties' keyword is not present in a OAS schema, allow + // undeclared properties. This is compliant with the JSON schema specification. + // setting this to false is required to have composed schemas work because: + // anyOf SchemaA + SchemaB, requires that props present only in A are accepted in B because in B + // they are additional properties + Boolean disallowAddProps = false; + if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) { + disallowAddProps = Boolean.valueOf(additionalProperties.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()); + } + this.setDisallowAdditionalPropertiesIfNotPresent(disallowAddProps); + + Boolean initRequiredVars = false; + if (additionalProperties.containsKey(CodegenConstants.INIT_REQUIRED_VARS)) { + initRequiredVars = Boolean.valueOf(additionalProperties.get(CodegenConstants.INIT_REQUIRED_VARS).toString()); + } + additionalProperties.put("initRequiredVars", initRequiredVars); + + // check library option to ensure only urllib3 is supported + if (!DEFAULT_LIBRARY.equals(getLibrary())) { + throw new RuntimeException("Only the `urllib3` library is supported in the refactored `python` client generator at the moment. Please fall back to `python-legacy` client generator for the time being. We welcome contributions to add back `asyncio`, `tornado` support to the `python` client generator."); + } + } + + /** + * Configures a friendly name for the generator. This will be used by the + * generator to select the library with the -g flag. + * + * @return the friendly name for the generator + */ + @Override + public String getName() { + return "python-prior"; + } + + @Override + public Schema unaliasSchema(Schema schema) { + Map allSchemas = ModelUtils.getSchemas(openAPI); + if (allSchemas == null || allSchemas.isEmpty()) { + // skip the warning as the spec can have no model defined + //LOGGER.warn("allSchemas cannot be null/empty in unaliasSchema. Returned 'schema'"); + return schema; + } + + if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) { + String simpleRef = ModelUtils.getSimpleRef(schema.get$ref()); + if (schemaMapping.containsKey(simpleRef)) { + LOGGER.debug("Schema unaliasing of {} omitted because aliased class is to be mapped to {}", simpleRef, schemaMapping.get(simpleRef)); + return schema; + } + Schema ref = allSchemas.get(simpleRef); + if (ref == null) { + once(LOGGER).warn("{} is not defined", schema.get$ref()); + return schema; + } else if (ref.getEnum() != null && !ref.getEnum().isEmpty()) { + // top-level enum class + return schema; + } else if (ModelUtils.isArraySchema(ref)) { + if (ModelUtils.isGenerateAliasAsModel(ref)) { + return schema; // generate a model extending array + } else { + return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); + } + } else if (ModelUtils.isComposedSchema(ref)) { + return schema; + } else if (ModelUtils.isMapSchema(ref)) { + if (ref.getProperties() != null && !ref.getProperties().isEmpty()) // has at least one property + return schema; // treat it as model + else { + if (ModelUtils.isGenerateAliasAsModel(ref)) { + return schema; // generate a model extending map + } else { + // treat it as a typical map + return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); + } + } + } else if (ModelUtils.isObjectSchema(ref)) { // model + if (ref.getProperties() != null && !ref.getProperties().isEmpty()) { // has at least one property + return schema; + } else { + // free form object (type: object) + if (ModelUtils.hasValidation(ref)) { + return schema; + } else if (!getAllOfDescendants(simpleRef, openAPI).isEmpty()) { + return schema; + } else { + return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); + } + } + } else if (ModelUtils.hasValidation(ref)) { + // non object non array non map schemas that have validations + // are returned so we can generate those schemas as models + // we do this to: + // - preserve the validations in that model class in python + // - use those validations when we use this schema in composed oneOf schemas + return schema; + } else { + return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref()))); + } + } + return schema; + } + + public String pythonDate(Object dateValue) { + String strValue = null; + if (dateValue instanceof OffsetDateTime) { + OffsetDateTime date = null; + try { + date = (OffsetDateTime) dateValue; + } catch (ClassCastException e) { + LOGGER.warn("Invalid `date` format for value {}", dateValue); + date = ((Date) dateValue).toInstant().atOffset(ZoneOffset.UTC); + } + strValue = date.format(iso8601Date); + } else { + strValue = dateValue.toString(); + } + return "dateutil_parser('" + strValue + "').date()"; + } + + public String pythonDateTime(Object dateTimeValue) { + String strValue = null; + if (dateTimeValue instanceof OffsetDateTime) { + OffsetDateTime dateTime = null; + try { + dateTime = (OffsetDateTime) dateTimeValue; + } catch (ClassCastException e) { + LOGGER.warn("Invalid `date-time` format for value {}", dateTimeValue); + dateTime = ((Date) dateTimeValue).toInstant().atOffset(ZoneOffset.UTC); + } + strValue = dateTime.format(iso8601DateTime); + } else { + strValue = dateTimeValue.toString(); + } + return "dateutil_parser('" + strValue + "')"; + } + + /** + * Return the default value of the property + * + * @param p OpenAPI property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Schema p) { + // if a variable has no default set and only has one allowed value + // using enum of length == 1 we use that value. Server/client usage: + // python servers: should only use default values for optional params + // python clients: should only use default values for required params + Object defaultObject = null; + if (p.getDefault() != null) { + defaultObject = p.getDefault(); + } else if (p.getEnum() != null && p.getEnum().size() == 1) { + defaultObject = p.getEnum().get(0); + } + + if (defaultObject == null) { + return null; + } + + String defaultValue = defaultObject.toString(); + if (ModelUtils.isDateSchema(p)) { + defaultValue = pythonDate(defaultObject); + } else if (ModelUtils.isDateTimeSchema(p)) { + defaultValue = pythonDateTime(defaultObject); + } else if (ModelUtils.isStringSchema(p) && !ModelUtils.isByteArraySchema(p) && !ModelUtils.isBinarySchema(p) && !ModelUtils.isFileSchema(p) && !ModelUtils.isUUIDSchema(p) && !ModelUtils.isEmailSchema(p)) { + defaultValue = ensureQuotes(defaultValue); + } else if (ModelUtils.isBooleanSchema(p)) { + if (!Boolean.valueOf(defaultValue)) { + defaultValue = "False"; + } else { + defaultValue = "True"; + } + } + return defaultValue; + } + + @Override + public String toModelImport(String name) { + // name looks like Cat + return "from " + modelPackage() + "." + toModelFilename(name) + " import " + toModelName(name); + } + + @Override + @SuppressWarnings("static-method") + public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { + // fix the imports that each model has, add the module reference to the model + // loops through imports and converts them all + // from 'Pet' to 'from petstore_api.model.pet import Pet' + + OperationMap val = objs.getOperations(); + List operations = val.getOperation(); + for (CodegenOperation operation : operations) { + if (operation.imports.isEmpty()) { + continue; + } + String[] modelNames = operation.imports.toArray(new String[0]); + operation.imports.clear(); + for (String modelName : modelNames) { + operation.imports.add(toModelImport(modelName)); + } + } + return objs; + } + + /*** + * Override with special post-processing for all models. + * we have a custom version of this method to: + * - remove any primitive models that do not contain validations + * these models are unaliased as inline definitions wherever the spec has them as refs + * this means that the generated client does not use these models + * because they are not used we do not write them + * - fix the model imports, go from model name to the full import string with toModelImport + globalImportFixer + * + * @param objs a map going from the model name to an object holding the model info + * @return the updated objs + */ + @Override + public Map postProcessAllModels(Map objs) { + super.postProcessAllModels(objs); + + List modelsToRemove = new ArrayList<>(); + Map allDefinitions = ModelUtils.getSchemas(this.openAPI); + for (String schemaName : allDefinitions.keySet()) { + Schema refSchema = new Schema().$ref("#/components/schemas/" + schemaName); + Schema unaliasedSchema = unaliasSchema(refSchema); + String modelName = toModelName(schemaName); + if (unaliasedSchema.get$ref() == null) { + modelsToRemove.add(modelName); + } else { + ModelsMap objModel = objs.get(modelName); + if (objModel != null) { // to avoid form parameter's models that are not generated (skipFormModel=true) + for (ModelMap model : objModel.getModels()) { + CodegenModel cm = model.getModel(); + String[] importModelNames = cm.imports.toArray(new String[0]); + cm.imports.clear(); + for (String importModelName : importModelNames) { + cm.imports.add(toModelImport(importModelName)); + String globalImportFixer = "globals()['" + importModelName + "'] = " + importModelName; + cm.imports.add(globalImportFixer); + } + } + } + } + } + + for (String modelName : modelsToRemove) { + objs.remove(modelName); + } + + return objs; + } + + /** + * Convert OAS Property object to Codegen Property object + * We have a custom version of this method to always set allowableValues.enumVars on all enum variables + * Together with unaliasSchema this sets primitive types with validations as models + * This method is used by fromResponse + * + * @param name name of the property + * @param p OAS property object + * @return Codegen Property object + */ + @Override + public CodegenProperty fromProperty(String name, Schema p, boolean required) { + CodegenProperty cp = super.fromProperty(name, p, required); + if (cp.isEnum) { + updateCodegenPropertyEnum(cp); + } + if (cp.isPrimitiveType && p.get$ref() != null) { + cp.complexType = cp.dataType; + } + if (cp.isArray && cp.complexType == null && cp.mostInnerItems.complexType != null) { + cp.complexType = cp.mostInnerItems.complexType; + } + return cp; + } + + /** + * Update codegen property's enum by adding "enumVars" (with name and value) + * + * @param var list of CodegenProperty + */ + @Override + public void updateCodegenPropertyEnum(CodegenProperty var) { + // we have a custom version of this method to omit overwriting the defaultValue + Map allowableValues = var.allowableValues; + + // handle array + if (var.mostInnerItems != null) { + allowableValues = var.mostInnerItems.allowableValues; + } + + if (allowableValues == null) { + return; + } + + List values = (List) allowableValues.get("values"); + if (values == null) { + return; + } + + String varDataType = var.mostInnerItems != null ? var.mostInnerItems.dataType : var.dataType; + Schema referencedSchema = getModelNameToSchemaCache().get(varDataType); + String dataType = (referencedSchema != null) ? getTypeDeclaration(referencedSchema) : varDataType; + + // put "enumVars" map into `allowableValues", including `name` and `value` + List> enumVars = buildEnumVars(values, dataType); + + // if "x-enum-varnames" or "x-enum-descriptions" defined, update varnames + Map extensions = var.mostInnerItems != null ? var.mostInnerItems.getVendorExtensions() : var.getVendorExtensions(); + if (referencedSchema != null) { + extensions = referencedSchema.getExtensions(); + } + updateEnumVarsWithExtensions(enumVars, extensions, dataType); + allowableValues.put("enumVars", enumVars); + // overwriting defaultValue omitted from here + } + + /*** + * We have a custom version of this method to produce links to models when they are + * primitive type (not map, not array, not object) and include validations or are enums + * + * @param body request body + * @param imports import collection + * @param bodyParameterName body parameter name + * @return the resultant CodegenParameter + */ + @Override + public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { + CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName); + Schema schema = ModelUtils.getSchemaFromRequestBody(body); + if (schema.get$ref() == null) { + return cp; + } + Schema unaliasedSchema = unaliasSchema(schema); + CodegenProperty unaliasedProp = fromProperty("body", unaliasedSchema, false); + Boolean dataTypeMismatch = !cp.dataType.equals(unaliasedProp.dataType); + Boolean baseTypeMismatch = !cp.baseType.equals(unaliasedProp.complexType) && unaliasedProp.complexType != null; + if (dataTypeMismatch || baseTypeMismatch) { + cp.dataType = unaliasedProp.dataType; + cp.baseType = unaliasedProp.complexType; + } + return cp; + } + + /*** + * Adds the body model schema to the body parameter + * We have a custom version of this method so we can flip forceSimpleRef + * to True based upon the results of unaliasSchema + * With this customization, we ensure that when schemas are passed to getSchemaType + * - if they have ref in them they are a model + * - if they do not have ref in them they are not a model + * + * @param codegenParameter the body parameter + * @param name model schema ref key in components + * @param schema the model schema (not refed) + * @param imports collection of imports + * @param bodyParameterName body parameter name + * @param forceSimpleRef if true use a model reference + */ + @Override + protected void addBodyModelSchema(CodegenParameter codegenParameter, String name, Schema schema, Set imports, String bodyParameterName, boolean forceSimpleRef) { + if (name != null) { + Schema bodySchema = new Schema().$ref("#/components/schemas/" + name); + Schema unaliased = unaliasSchema(bodySchema); + if (unaliased.get$ref() != null) { + forceSimpleRef = true; + } + } + super.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, forceSimpleRef); + + } + + + /** + * Return the sanitized variable name for enum + * + * @param value enum variable name + * @param datatype data type + * @return the sanitized variable name for enum + */ + public String toEnumVarName(String value, String datatype) { + // our enum var names are keys in a python dict, so change spaces to underscores + if (value.length() == 0) { + return "EMPTY"; + } + + String var = value.replaceAll("\\s+", "_").toUpperCase(Locale.ROOT); + return var; + } + + /** + * Return the enum value in the language specified format + * e.g. status becomes "status" + * + * @param value enum variable name + * @param datatype data type + * @return the sanitized value for enum + */ + public String toEnumValue(String value, String datatype) { + if ("int".equals(datatype) || "float".equals(datatype)) { + return value; + } else if ("bool".equals(datatype)) { + return value.substring(0, 1).toUpperCase(Locale.ROOT) + value.substring(1); + } else { + return ensureQuotes(value); + } + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty p) { + postProcessPattern(p.pattern, p.vendorExtensions); + // set property.complexType so the model docs will link to the ClassName.md + if (p.complexType == null && p.isArray && p.mostInnerItems.complexType != null && !languageSpecificPrimitives.contains(p.mostInnerItems.complexType)) { + // fix ListContainers + p.complexType = p.mostInnerItems.complexType; + } + } + + @Override + public void postProcessParameter(CodegenParameter p) { + postProcessPattern(p.pattern, p.vendorExtensions); + if (p.baseType != null && languageSpecificPrimitives.contains(p.baseType)) { + // set baseType to null so the api docs will not point to a model for languageSpecificPrimitives + p.baseType = null; + } + } + + private void fixComposedSchemaRequiredVars(Schema schema, CodegenModel result) { + // for composed schema models, if the required properties are only from oneOf or anyOf models + // remove them from the composed schema's required vars + // for composed schemas our code adds oneOf and anyOf required properties to + // the composed schema's required properties + // but they should not be required because if we have ComposedSchema: oneOf -schemaA -schemaB + // and the required props are only in schemaB, we do not need to use them when making an instance of + // ComposedSchema + schemaA + ComposedSchema cs = (ComposedSchema) schema; + + // these are the properties that are from properties in self cs or cs allOf + Map selfProperties = new LinkedHashMap<>(); + List selfRequired = new ArrayList<>(); + + // these are the properties that are from properties in cs oneOf or cs anyOf + Map otherProperties = new LinkedHashMap<>(); + List otherRequired = new ArrayList<>(); + + List oneOfanyOfSchemas = new ArrayList<>(); + List oneOf = cs.getOneOf(); + if (oneOf != null) { + oneOfanyOfSchemas.addAll(oneOf); + } + List anyOf = cs.getAnyOf(); + if (anyOf != null) { + oneOfanyOfSchemas.addAll(anyOf); + } + for (Schema sc : oneOfanyOfSchemas) { + Schema refSchema = ModelUtils.getReferencedSchema(this.openAPI, sc); + addProperties(otherProperties, otherRequired, refSchema, new HashSet<>()); + } + Set otherRequiredSet = new HashSet<>(otherRequired); + + List allOf = cs.getAllOf(); + if ((schema.getProperties() != null && !schema.getProperties().isEmpty()) || allOf != null) { + // NOTE: this function also adds the allOf properties inside schema + addProperties(selfProperties, selfRequired, schema, new HashSet<>()); + } + if (result.discriminator != null) { + selfRequired.add(result.discriminator.getPropertyBaseName()); + } + Set selfRequiredSet = new HashSet<>(selfRequired); + + List reqVars = result.getRequiredVars(); + List reqVarsThatMustBeOptional = new ArrayList<>(); + if (reqVars != null) { + for (CodegenProperty cp : reqVars) { + String propName = cp.baseName; + if (otherRequiredSet.contains(propName) && !selfRequiredSet.contains(propName)) { + cp.required = false; + reqVarsThatMustBeOptional.add(cp); + } + } + } + for (CodegenProperty cp : reqVarsThatMustBeOptional) { + result.getRequiredVars().remove(cp); + result.getOptionalVars().add(cp); + } + } + + /** + * Sets the value of the 'model.parent' property in CodegenModel + * We have a custom version of this function so we can add the dataType on the ArrayModel + */ + @Override + protected void addParentContainer(CodegenModel model, String name, Schema schema) { + super.addParentContainer(model, name, schema); + + List referencedModelNames = new ArrayList<>(); + model.dataType = getTypeString(schema, "", "", referencedModelNames); + } + + /** + * Convert OAS Model object to Codegen Model object + * We have a custom version of this method so we can: + * - set the correct regex values for requiredVars + optionalVars + * - set model.defaultValue and model.hasRequired per the three use cases defined in this method + * + * @param name the name of the model + * @param sc OAS Model object + * @return Codegen Model object + */ + @Override + public CodegenModel fromModel(String name, Schema sc) { + CodegenModel cm = super.fromModel(name, sc); + if (cm.requiredVars.size() > 0 && (cm.oneOf.size() > 0 || cm.anyOf.size() > 0)) { + fixComposedSchemaRequiredVars(sc, cm); + } + ArrayList> listOfLists = new ArrayList<>(); + listOfLists.add(cm.requiredVars); + listOfLists.add(cm.optionalVars); + for (List cpList : listOfLists) { + for (CodegenProperty cp : cpList) { + // sets regex values + postProcessModelProperty(cm, cp); + } + } + Boolean isNotPythonModelSimpleModel = (ModelUtils.isComposedSchema(sc) || ModelUtils.isObjectSchema(sc) || ModelUtils.isMapSchema(sc)); + if (isNotPythonModelSimpleModel) { + return cm; + } + // Use cases for default values / enums of length one + // 1. no default exists + // schema does not contain default + // cm.defaultValue unset, cm.hasRequired = true + // 2. spec has a default + // schema contains default + // cm.defaultValue set, cm.hasRequired = false + // different value here to differentiate between use case 3 below + // This defaultValue is used when a consumer (client or server) lacks the input argument, defaultValue will be used + // 3. only one value is allowed in an enum + // schema does not contain default + // cm.defaultValue set, cm.hasRequired = false + // because we know what value needs to be set so the user doesn't need to input it + // This defaultValue is used in the client and is sent to the server + String defaultValue = toDefaultValue(sc); + if (sc.getDefault() == null && defaultValue == null) { + cm.hasRequired = true; + } else if (sc.getDefault() != null) { + cm.defaultValue = defaultValue; + cm.hasRequired = false; + } else if (defaultValue != null && cm.defaultValue == null) { + cm.defaultValue = defaultValue; + cm.hasRequired = false; + } + return cm; + } + + /** + * Returns the python type for the property. + * + * @param schema property schema + * @return string presentation of the type + **/ + @SuppressWarnings("static-method") + @Override + public String getSchemaType(Schema schema) { + String openAPIType = getSingleSchemaType(schema); + if (typeMapping.containsKey(openAPIType)) { + String type = typeMapping.get(openAPIType); + return type; + } + return toModelName(openAPIType); + } + + public String getModelName(Schema sc) { + if (sc.get$ref() != null) { + Schema unaliasedSchema = unaliasSchema(sc); + if (unaliasedSchema.get$ref() != null) { + return toModelName(ModelUtils.getSimpleRef(sc.get$ref())); + } + } + return null; + } + + @Override + protected Schema getAdditionalProperties(Schema schema) { + /* + Use cases: + 1. addProps set to schema in spec: return that schema + 2. addProps unset w/ getDisallowAdditionalPropertiesIfNotPresent -> null + 3. addProps unset w/ getDisallowAdditionalPropertiesIfNotPresent=False -> new Schema() + 4. addProps true -> new Schema() NOTE: v3 only + 5. addprops false -> null NOTE: v3 only + */ + Object addProps = schema.getAdditionalProperties(); + if (addProps instanceof Schema) { + return (Schema) addProps; + } + if (addProps == null) { + // When reaching this code path, this should indicate the 'additionalProperties' keyword is + // not present in the OAS schema. This is true for OAS 3.0 documents. + // However, the parsing logic is broken for OAS 2.0 documents because of the + // https://github.com/swagger-api/swagger-parser/issues/1369 issue. + // When OAS 2.0 documents are parsed, the swagger-v2-converter ignores the 'additionalProperties' + // keyword if the value is boolean. That means codegen is unable to determine whether + // additional properties are allowed or not. + // + // The original behavior was to assume additionalProperties had been set to false. + if (getDisallowAdditionalPropertiesIfNotPresent()) { + // If the 'additionalProperties' keyword is not present in a OAS schema, + // interpret as if the 'additionalProperties' keyword had been set to false. + // This is NOT compliant with the JSON schema specification. It is the original + // 'openapi-generator' behavior. + return null; + } + /* + // The disallowAdditionalPropertiesIfNotPresent CLI option has been set to true, + // but for now that only works with OAS 3.0 documents. + // The new behavior does not work with OAS 2.0 documents. + if (extensions == null || !extensions.containsKey(EXTENSION_OPENAPI_DOC_VERSION)) { + // Fallback to the legacy behavior. + return null; + } + // Get original swagger version from OAS extension. + // Note openAPI.getOpenapi() is always set to 3.x even when the document + // is converted from a OAS/Swagger 2.0 document. + // https://github.com/swagger-api/swagger-parser/pull/1374 + SemVer version = new SemVer((String)extensions.get(EXTENSION_OPENAPI_DOC_VERSION)); + if (version.major != 3) { + return null; + } + */ + } + if (addProps == null || (addProps instanceof Boolean && (Boolean) addProps)) { + // Return empty schema to allow any type + return new Schema(); + } + return null; + } + + /** + * Return a string representation of the Python types for the specified OAS schema. + * Primitive types in the OAS specification are implemented in Python using the corresponding + * Python primitive types. + * Composed types (e.g. allAll, oneOf, anyOf) are represented in Python using list of types. + *

        + * The caller should set the prefix and suffix arguments to empty string, except when + * getTypeString invokes itself recursively. A non-empty prefix/suffix may be specified + * to wrap the return value in a python dict, list or tuple. + *

        + * Examples: + * - "bool, date, float" The data must be a bool, date or float. + * - "[bool, date]" The data must be an array, and the array items must be a bool or date. + * + * @param p The OAS schema. + * @param prefix prepended to the returned value. + * @param suffix appended to the returned value. + * @param referencedModelNames a list of models that are being referenced while generating the types, + * may be used to generate imports. + * @return a comma-separated string representation of the Python types + */ + private String getTypeString(Schema p, String prefix, String suffix, List referencedModelNames) { + String fullSuffix = suffix; + if (")".equals(suffix)) { + fullSuffix = "," + suffix; + } + if (StringUtils.isNotEmpty(p.get$ref())) { + // The input schema is a reference. If the resolved schema is + // a composed schema, convert the name to a Python class. + Schema unaliasedSchema = unaliasSchema(p); + if (unaliasedSchema.get$ref() != null) { + String modelName = toModelName(ModelUtils.getSimpleRef(p.get$ref())); + if (referencedModelNames != null) { + referencedModelNames.add(modelName); + } + return prefix + modelName + fullSuffix; + } + } + if (ModelUtils.isAnyType(p)) { + // for v2 specs only, swagger-parser never generates an AnyType schemas even though it should generate them + // https://github.com/swagger-api/swagger-parser/issues/1378 + // switch to v3 if you need AnyType to work + return prefix + "bool, date, datetime, dict, float, int, list, str, none_type" + suffix; + } + String originalSpecVersion = "X"; + if (this.openAPI.getExtensions() != null && this.openAPI.getExtensions().containsKey("x-original-swagger-version")) { + originalSpecVersion = (String) this.openAPI.getExtensions().get("x-original-swagger-version"); + originalSpecVersion = originalSpecVersion.substring(0, 1); + + } + Boolean v2DisallowAdditionalPropertiesIfNotPresentAddPropsNullCase = (getAdditionalProperties(p) == null && this.getDisallowAdditionalPropertiesIfNotPresent() && originalSpecVersion.equals("2")); + Schema emptySchema = new Schema(); + Boolean v2WithCompositionAddPropsAnyTypeSchemaCase = (getAdditionalProperties(p) != null && emptySchema.equals(getAdditionalProperties(p)) && originalSpecVersion.equals("2")); + if (isFreeFormObject(p) && (v2DisallowAdditionalPropertiesIfNotPresentAddPropsNullCase || v2WithCompositionAddPropsAnyTypeSchemaCase)) { + // for v2 specs only, input AnyType schemas (type unset) or schema {} results in FreeFromObject schemas + // per https://github.com/swagger-api/swagger-parser/issues/1378 + // v2 spec uses cases + // 1. AnyType schemas + // 2. type object schema with no other info + // use case 1 + 2 -> both become use case 1 + // switch to v3 if you need use cases 1 + 2 to work correctly + return prefix + "bool, date, datetime, dict, float, int, list, str, none_type" + fullSuffix; + } + // Resolve $ref because ModelUtils.isXYZ methods do not automatically resolve references. + if (ModelUtils.isNullable(ModelUtils.getReferencedSchema(this.openAPI, p))) { + fullSuffix = ", none_type" + suffix; + } + Boolean v3WithCompositionAddPropsAnyTypeSchemaCase = (getAdditionalProperties(p) != null && emptySchema.equals(getAdditionalProperties(p)) && originalSpecVersion.equals("3")); + if (isFreeFormObject(p) && v3WithCompositionAddPropsAnyTypeSchemaCase) { + // v3 code path, use case: type object schema with no other schema info + return prefix + "{str: (bool, date, datetime, dict, float, int, list, str, none_type)}" + fullSuffix; + } else if ((ModelUtils.isMapSchema(p) || "object".equals(p.getType())) && getAdditionalProperties(p) != null) { + Schema inner = getAdditionalProperties(p); + return prefix + "{str: " + getTypeString(inner, "(", ")", referencedModelNames) + "}" + fullSuffix; + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + if (inner == null) { + // In OAS 3.0.x, the array "items" attribute is required. + // In OAS >= 3.1, the array "items" attribute is optional such that the OAS + // specification is aligned with the JSON schema specification. + // When "items" is not specified, the elements of the array may be anything at all. + // In that case, the return value should be: + // "[bool, date, datetime, dict, float, int, list, str, none_type]" + // Using recursion to wrap the allowed python types in an array. + Schema anyType = new Schema(); // A Schema without any attribute represents 'any type'. + return getTypeString(anyType, "[", "]", referencedModelNames); + } else { + return prefix + getTypeString(inner, "[", "]", referencedModelNames) + fullSuffix; + } + } + if (ModelUtils.isFileSchema(p)) { + return prefix + "file_type" + fullSuffix; + } + String baseType = getSchemaType(p); + return prefix + baseType + fullSuffix; + } + + /** + * Output the type declaration of a given name + * + * @param p property schema + * @return a string presentation of the type + */ + @Override + public String getTypeDeclaration(Schema p) { + // this is used to set dataType, which defines a python tuple of classes + // in Python we will wrap this in () to make it a tuple but here we + // will omit the parens so the generated documentation will not include + // them + return getTypeString(p, "", "", null); + } + + @Override + public String toInstantiationType(Schema property) { + if (ModelUtils.isArraySchema(property) || ModelUtils.isMapSchema(property) || property.getAdditionalProperties() != null) { + return getSchemaType(property); + } + return super.toInstantiationType(property); + } + + @Override + protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { + Schema addProps = getAdditionalProperties(schema); + if (addProps != null) { + // if AdditionalProperties exists, get its datatype and + // store it in codegenModel.additionalPropertiesType. + // The 'addProps' may be a reference, getTypeDeclaration will resolve + // the reference. + List referencedModelNames = new ArrayList<>(); + getTypeString(addProps, "", "", referencedModelNames); + if (referencedModelNames.size() != 0) { + // Models that are referenced in the 'additionalPropertiesType' keyword + // must be added to the imports. + codegenModel.imports.addAll(referencedModelNames); + } + } + // If addProps is null, the value of the 'additionalProperties' keyword is set + // to false, i.e. no additional properties are allowed. + } + + /** + * Gets an example if it exists + * + * @param sc input schema + * @return the example value + */ + protected Object getObjectExample(Schema sc) { + Schema schema = sc; + String ref = sc.get$ref(); + if (ref != null) { + schema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); + } + // TODO handle examples in object models in the future + Boolean objectModel = (ModelUtils.isObjectSchema(schema) || ModelUtils.isMapSchema(schema) || ModelUtils.isComposedSchema(schema)); + if (objectModel) { + return null; + } + if (schema.getExample() != null) { + return schema.getExample(); + } + if (schema.getDefault() != null) { + return schema.getDefault(); + } else if (schema.getEnum() != null && !schema.getEnum().isEmpty()) { + return schema.getEnum().get(0); + } + return null; + } + + /*** + * Ensures that the string has a leading and trailing quote + * + * @param in input string + * @return quoted string + */ + private String ensureQuotes(String in) { + Pattern pattern = Pattern.compile("\r\n|\r|\n"); + Matcher matcher = pattern.matcher(in); + if (matcher.find()) { + // if a string has a new line in it add triple quotes to make it a python multiline string + return "'''" + in + "'''"; + } + String strPattern = "^['\"].*?['\"]$"; + if (in.matches(strPattern)) { + return in; + } + return "\"" + in + "\""; + } + + @Override + public String toExampleValue(Schema schema) { + Object objExample = getObjectExample(schema); + String modelName = getModelName(schema); + return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, Sets.newHashSet()); + } + + public String toExampleValue(Schema schema, Object objExample) { + String modelName = getModelName(schema); + return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0, Sets.newHashSet()); + } + + private Boolean simpleStringSchema(Schema schema) { + Schema sc = schema; + String ref = schema.get$ref(); + if (ref != null) { + sc = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); + } + if (ModelUtils.isStringSchema(sc) && !ModelUtils.isDateSchema(sc) && !ModelUtils.isDateTimeSchema(sc) && !"Number".equalsIgnoreCase(sc.getFormat()) && !ModelUtils.isByteArraySchema(sc) && !ModelUtils.isBinarySchema(sc) && schema.getPattern() == null) { + return true; + } + return false; + } + + private MappedModel getDiscriminatorMappedModel(CodegenDiscriminator disc) { + for (MappedModel mm : disc.getMappedModels()) { + String modelName = mm.getModelName(); + Schema modelSchema = getModelNameToSchemaCache().get(modelName); + if (ModelUtils.isObjectSchema(modelSchema)) { + return mm; + } + } + return null; + } + + /*** + * Recursively generates string examples for schemas + * + * @param modelName the string name of the refed model that will be generated for the schema or null + * @param schema the schema that we need an example for + * @param objExample the example that applies to this schema, for now only string example are used + * @param indentationLevel integer indentation level that we are currently at + * we assume the indentation amount is 4 spaces times this integer + * @param prefix the string prefix that we will use when assigning an example for this line + * this is used when setting key: value, pairs "key: " is the prefix + * and this is used when setting properties like some_property='some_property_example' + * @param exampleLine this is the current line that we are generating an example for, starts at 0 + * we don't indent the 0th line because using the example value looks like: + * prop = ModelName( line 0 + * some_property='some_property_example' line 1 + * ) line 2 + * and our example value is: + * ModelName( line 0 + * some_property='some_property_example' line 1 + * ) line 2 + * @param seenSchemas This set contains all the schemas passed into the recursive function. It is used to check + * if a schema was already passed into the function and breaks the infinite recursive loop. The + * only schemas that are not added are ones that contain $ref != null + * @return the string example + */ + private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine, Set seenSchemas) { + final String indentionConst = " "; + String currentIndentation = ""; + String closingIndentation = ""; + for (int i = 0; i < indentationLevel; i++) currentIndentation += indentionConst; + if (exampleLine.equals(0)) { + closingIndentation = currentIndentation; + currentIndentation = ""; + } else { + closingIndentation = currentIndentation; + } + String openChars = ""; + String closeChars = ""; + if (modelName != null) { + openChars = modelName + "("; + closeChars = ")"; + } + + String fullPrefix = currentIndentation + prefix + openChars; + + String example = null; + if (objExample != null) { + example = objExample.toString(); + } + // checks if the current schema has already been passed in. If so, breaks the current recursive pass + if (seenSchemas.contains(schema)) { + if (modelName != null) { + return fullPrefix + closeChars; + } else { + // this is a recursive schema + // need to add a reasonable example to avoid + // infinite recursion + if (ModelUtils.isNullable(schema)) { + // if the schema is nullable, then 'None' is a valid value + return fullPrefix + "None" + closeChars; + } else if (ModelUtils.isArraySchema(schema)) { + // the schema is an array, add an empty array + return fullPrefix + "[]" + closeChars; + } else { + // the schema is an object, make an empty object + return fullPrefix + "{}" + closeChars; + } + } + } + + if (null != schema.get$ref()) { + Map allDefinitions = ModelUtils.getSchemas(this.openAPI); + String ref = ModelUtils.getSimpleRef(schema.get$ref()); + Schema refSchema = allDefinitions.get(ref); + if (null == refSchema) { + LOGGER.warn("Unable to find referenced schema {}\n", schema.get$ref()); + return fullPrefix + "None" + closeChars; + } + String refModelName = getModelName(schema); + return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine, seenSchemas); + } else if (ModelUtils.isNullType(schema) || ModelUtils.isAnyType(schema)) { + // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, + // though this tooling supports it. + return fullPrefix + "None" + closeChars; + } else if (ModelUtils.isBooleanSchema(schema)) { + if (objExample == null) { + example = "True"; + } else { + if ("false".equalsIgnoreCase(objExample.toString())) { + example = "False"; + } else { + example = "True"; + } + } + return fullPrefix + example + closeChars; + } else if (ModelUtils.isDateSchema(schema)) { + if (objExample == null) { + example = pythonDate("1970-01-01"); + } else { + example = pythonDate(objExample); + } + return fullPrefix + example + closeChars; + } else if (ModelUtils.isDateTimeSchema(schema)) { + if (objExample == null) { + example = pythonDateTime("1970-01-01T00:00:00.00Z"); + } else { + example = pythonDateTime(objExample); + } + return fullPrefix + example + closeChars; + } else if (ModelUtils.isBinarySchema(schema)) { + if (objExample == null) { + example = "/path/to/file"; + } + example = "open('" + example + "', 'rb')"; + return fullPrefix + example + closeChars; + } else if (ModelUtils.isByteArraySchema(schema)) { + if (objExample == null) { + example = "'YQ=='"; + } + return fullPrefix + example + closeChars; + } else if (ModelUtils.isStringSchema(schema)) { + if (objExample == null) { + // a BigDecimal: + if ("Number".equalsIgnoreCase(schema.getFormat())) { + example = "2"; + return fullPrefix + example + closeChars; + } else if (StringUtils.isNotBlank(schema.getPattern())) { + String pattern = schema.getPattern(); + /* + RxGen does not support our ECMA dialect https://github.com/curious-odd-man/RgxGen/issues/56 + So strip off the leading /, trailing / and trailing /i, and turn on ignore case if we have it + */ + Pattern valueExtractor = Pattern.compile("^/?(.+?)/?(i?)$"); + Matcher m = valueExtractor.matcher(pattern); + RgxGen rgxGen = null; + if (m.find()) { + int groupCount = m.groupCount(); + if (groupCount == 1) { + // only pattern found + String isolatedPattern = m.group(1); + rgxGen = new RgxGen(isolatedPattern); + } else if (groupCount == 2) { + // patterns and flag found + String isolatedPattern = m.group(1); + String flags = m.group(2); + if (flags.contains("i")) { + rgxGen = new RgxGen(isolatedPattern); + RgxGenProperties properties = new RgxGenProperties(); + RgxGenOption.CASE_INSENSITIVE.setInProperties(properties, true); + rgxGen.setProperties(properties); + } else { + rgxGen = new RgxGen(isolatedPattern); + } + } + } else { + rgxGen = new RgxGen(pattern); + } + + // this seed makes it so if we have [a-z] we pick a + Random random = new Random(18); + if (rgxGen != null) { + example = rgxGen.generate(random); + } else { + throw new RuntimeException("rgxGen cannot be null. Please open an issue in the openapi-generator github repo."); + } + } else if (schema.getMinLength() != null) { + example = ""; + int len = schema.getMinLength().intValue(); + for (int i = 0; i < len; i++) example += "a"; + } else if (ModelUtils.isUUIDSchema(schema)) { + example = "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; + } else { + example = "string_example"; + } + } + return fullPrefix + ensureQuotes(example) + closeChars; + } else if (ModelUtils.isIntegerSchema(schema)) { + if (objExample == null) { + if (schema.getMinimum() != null) { + example = schema.getMinimum().toString(); + } else { + example = "1"; + } + } + return fullPrefix + example + closeChars; + } else if (ModelUtils.isNumberSchema(schema)) { + if (objExample == null) { + if (schema.getMinimum() != null) { + example = schema.getMinimum().toString(); + } else { + example = "3.14"; + } + } + return fullPrefix + example + closeChars; + } else if (ModelUtils.isArraySchema(schema)) { + ArraySchema arrayschema = (ArraySchema) schema; + Schema itemSchema = arrayschema.getItems(); + String itemModelName = getModelName(itemSchema); + if (objExample instanceof Iterable && itemModelName == null) { + // If the example is already a list, return it directly instead of wrongly wrap it in another list + return fullPrefix + objExample + closeChars; + } + Set newSeenSchemas = new HashSet<>(seenSchemas); + newSeenSchemas.add(schema); + example = fullPrefix + "[" + "\n" + toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, "", exampleLine + 1, newSeenSchemas) + ",\n" + closingIndentation + "]" + closeChars; + return example; + } else if (ModelUtils.isMapSchema(schema)) { + if (modelName == null) { + fullPrefix += "{"; + closeChars = "}"; + } + Object addPropsObj = schema.getAdditionalProperties(); + // TODO handle true case for additionalProperties + if (addPropsObj instanceof Schema) { + Schema addPropsSchema = (Schema) addPropsObj; + String key = "key"; + Object addPropsExample = getObjectExample(addPropsSchema); + if (addPropsSchema.getEnum() != null && !addPropsSchema.getEnum().isEmpty()) { + key = addPropsSchema.getEnum().get(0).toString(); + } + addPropsExample = exampleFromStringOrArraySchema(addPropsSchema, addPropsExample, key); + String addPropPrefix = key + "="; + if (modelName == null) { + addPropPrefix = ensureQuotes(key) + ": "; + } + String addPropsModelName = getModelName(addPropsSchema); + Set newSeenSchemas = new HashSet<>(seenSchemas); + newSeenSchemas.add(schema); + example = fullPrefix + "\n" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1, newSeenSchemas) + ",\n" + closingIndentation + closeChars; + } else { + example = fullPrefix + closeChars; + } + return example; + } else if (ModelUtils.isObjectSchema(schema)) { + if (modelName == null) { + fullPrefix += "{"; + closeChars = "}"; + } + CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); + if (disc != null) { + MappedModel mm = getDiscriminatorMappedModel(disc); + if (mm != null) { + String discPropNameValue = mm.getMappingName(); + String chosenModelName = mm.getModelName(); + // TODO handle this case in the future, this is when the discriminated + // schema allOf includes this schema, like Cat allOf includes Pet + // so this is the composed schema use case + } else { + return fullPrefix + closeChars; + } + } + Set newSeenSchemas = new HashSet<>(seenSchemas); + newSeenSchemas.add(schema); + String exampleForObjectModel = exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation, newSeenSchemas); + return exampleForObjectModel; + } else if (ModelUtils.isComposedSchema(schema)) { + // TODO add examples for composed schema models without discriminators + + CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); + if (disc != null) { + MappedModel mm = getDiscriminatorMappedModel(disc); + if (mm != null) { + String discPropNameValue = mm.getMappingName(); + String chosenModelName = mm.getModelName(); + Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); + CodegenProperty cp = new CodegenProperty(); + cp.setName(disc.getPropertyName()); + cp.setExample(discPropNameValue); + // Adds schema to seenSchemas before running example model function. removes schema after running + // the function. It also doesn't keep track of any schemas within the ObjectModel. + Set newSeenSchemas = new HashSet<>(seenSchemas); + newSeenSchemas.add(schema); + String exampleForObjectModel = exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, newSeenSchemas); + return exampleForObjectModel; + } else { + return fullPrefix + closeChars; + } + } + return fullPrefix + closeChars; + } else { + LOGGER.warn("Type {} not handled properly in toExampleValue", schema.getType()); + } + + return example; + } + + private String exampleForObjectModel(Schema schema, String fullPrefix, String closeChars, CodegenProperty discProp, int indentationLevel, int exampleLine, String closingIndentation, Set seenSchemas) { + Map requiredAndOptionalProps = schema.getProperties(); + if (requiredAndOptionalProps == null || requiredAndOptionalProps.isEmpty()) { + return fullPrefix + closeChars; + } + + String example = fullPrefix + "\n"; + for (Map.Entry entry : requiredAndOptionalProps.entrySet()) { + String propName = entry.getKey(); + Schema propSchema = entry.getValue(); + boolean readOnly = false; + if (propSchema.getReadOnly() != null) { + readOnly = propSchema.getReadOnly(); + } + if (readOnly) { + continue; + } + String ref = propSchema.get$ref(); + if (ref != null) { + Schema refSchema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); + if (refSchema.getReadOnly() != null) { + readOnly = refSchema.getReadOnly(); + } + if (readOnly) { + continue; + } + } + propName = toVarName(propName); + String propModelName = null; + Object propExample = null; + if (discProp != null && propName.equals(discProp.name)) { + propModelName = null; + propExample = discProp.example; + } else { + propModelName = getModelName(propSchema); + propExample = exampleFromStringOrArraySchema(propSchema, null, propName); + } + example += toExampleValueRecursive(propModelName, propSchema, propExample, indentationLevel + 1, propName + "=", exampleLine + 1, seenSchemas) + ",\n"; + } + // TODO handle additionalProperties also + example += closingIndentation + closeChars; + return example; + } + + private Object exampleFromStringOrArraySchema(Schema sc, Object currentExample, String propName) { + if (currentExample != null) { + return currentExample; + } + Schema schema = sc; + String ref = sc.get$ref(); + if (ref != null) { + schema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); + } + Object example = getObjectExample(schema); + if (example != null) { + return example; + } else if (simpleStringSchema(schema)) { + return propName + "_example"; + } else if (ModelUtils.isArraySchema(schema)) { + ArraySchema arraySchema = (ArraySchema) schema; + Schema itemSchema = arraySchema.getItems(); + example = getObjectExample(itemSchema); + if (example != null) { + return example; + } else if (simpleStringSchema(itemSchema)) { + return propName + "_example"; + } + } + return null; + } + + + /*** + * + * Set the codegenParameter example value + * We have a custom version of this function so we can invoke toExampleValue + * + * @param codegenParameter the item we are setting the example on + * @param parameter the base parameter that came from the spec + */ + @Override + public void setParameterExampleValue(CodegenParameter codegenParameter, Parameter parameter) { + Schema schema = parameter.getSchema(); + if (schema == null) { + LOGGER.warn("CodegenParameter.example defaulting to null because parameter lacks a schema"); + return; + } + + Object example = null; + if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { + example = codegenParameter.vendorExtensions.get("x-example"); + } else if (parameter.getExample() != null) { + example = parameter.getExample(); + } else if (parameter.getExamples() != null && !parameter.getExamples().isEmpty() && parameter.getExamples().values().iterator().next().getValue() != null) { + example = parameter.getExamples().values().iterator().next().getValue(); + } else { + example = getObjectExample(schema); + } + example = exampleFromStringOrArraySchema(schema, example, parameter.getName()); + String finalExample = toExampleValue(schema, example); + codegenParameter.example = finalExample; + } + + /** + * Return the example value of the parameter. + * + * @param codegenParameter Codegen parameter + * @param requestBody Request body + */ + @Override + public void setParameterExampleValue(CodegenParameter codegenParameter, RequestBody requestBody) { + if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { + codegenParameter.example = Json.pretty(codegenParameter.vendorExtensions.get("x-example")); + } + + Content content = requestBody.getContent(); + + if (content.size() > 1) { + // @see ModelUtils.getSchemaFromContent() + once(LOGGER).warn("Multiple MediaTypes found, using only the first one"); + } + + MediaType mediaType = content.values().iterator().next(); + Schema schema = mediaType.getSchema(); + if (schema == null) { + LOGGER.warn("CodegenParameter.example defaulting to null because requestBody content lacks a schema"); + return; + } + + Object example = null; + if (mediaType.getExample() != null) { + example = mediaType.getExample(); + } else if (mediaType.getExamples() != null && !mediaType.getExamples().isEmpty() && mediaType.getExamples().values().iterator().next().getValue() != null) { + example = mediaType.getExamples().values().iterator().next().getValue(); + } else { + example = getObjectExample(schema); + } + example = exampleFromStringOrArraySchema(schema, example, codegenParameter.paramName); + codegenParameter.example = toExampleValue(schema, example); + } + + /** + * Create a CodegenParameter for a Form Property + * We have a custom version of this method so we can invoke + * setParameterExampleValue(codegenParameter, parameter) + * rather than setParameterExampleValue(codegenParameter) + * This ensures that all of our samples are generated in + * toExampleValueRecursive + * + * @param name the property name + * @param propertySchema the property schema + * @param imports our import set + * @return the resultant CodegenParameter + */ + @Override + public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set imports) { + CodegenParameter cp = super.fromFormProperty(name, propertySchema, imports); + Parameter p = new Parameter(); + p.setSchema(propertySchema); + p.setName(cp.paramName); + setParameterExampleValue(cp, p); + return cp; + } + + /** + * Return a map from model name to Schema for efficient lookup. + * + * @return map from model name to Schema. + */ + protected Map getModelNameToSchemaCache() { + if (modelNameToSchemaCache == null) { + // Create a cache to efficiently lookup schema based on model name. + Map m = new HashMap<>(); + ModelUtils.getSchemas(openAPI).forEach((key, schema) -> { + m.put(toModelName(key), schema); + }); + modelNameToSchemaCache = Collections.unmodifiableMap(m); + } + return modelNameToSchemaCache; + } + + @Override + public String generatorLanguageVersion() { return ">=3.6"; }; + + @Override + protected void addImport(ComposedSchema composed, Schema childSchema, CodegenModel model, String modelName ) { + // import everything (including child schema of a composed schema) + addImport(model, modelName); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java index 9a391ec70f..1328efd8ec 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java @@ -21,6 +21,7 @@ import com.samskivert.mustache.Mustache.Lambda; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; +//import com.sun.media.sound.InvalidDataException; import io.swagger.v3.oas.models.examples.Example; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; @@ -61,12 +62,23 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String EXCEPTION_PACKAGE = "exceptionPackage"; public static final String USE_DEFAULT_EXCEPTION = "useDefaultExceptionHandling"; public static final String USE_RLANG_EXCEPTION = "useRlangExceptionHandling"; + public static final String GENERATE_WRAPPER = "generateWrapper"; public static final String DEFAULT = "default"; public static final String RLANG = "rlang"; + public static final String HTTR = "httr"; + public static final String HTTR2 = "httr2"; + + // naming convention for operationId (function names in the API) + public static final String OPERATIONID_NAMING = "operationIdNaming"; protected boolean useDefaultExceptionHandling = false; protected boolean useRlangExceptionHandling = false; protected String errorObjectType; + protected String operationIdNaming; + protected boolean generateWrapper; + protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup + + private Map schemaKeyToModelNameCache = new HashMap<>(); public CodegenType getTag() { return CodegenType.CLIENT; @@ -164,7 +176,10 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("map", "map"); typeMapping.put("object", "object"); + // no need for import mapping as R doesn't reqiure api,model import + // https://github.com/OpenAPITools/openapi-generator/issues/2217 importMapping.clear(); + cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "R package name (convention: lowercase).") .defaultValue("openapi")); @@ -175,6 +190,14 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption(CodegenConstants.EXCEPTION_ON_FAILURE, CodegenConstants.EXCEPTION_ON_FAILURE_DESC) .defaultValue(Boolean.FALSE.toString())); + CliOption operationIdNaming = CliOption.newString(OPERATIONID_NAMING, "Naming convention for operationId (function name in the API)"); + Map operationIdNamingOptions = new HashMap<>(); + operationIdNamingOptions.put("snake_case", "Snake case"); + operationIdNamingOptions.put("camelCase", "Camel case"); + operationIdNamingOptions.put("PascalCase", "Pascal case (default)"); + operationIdNaming.setEnum(operationIdNamingOptions); + cliOptions.add(operationIdNaming); + exceptionPackages.put(DEFAULT, "Use stop() for raising exceptions."); exceptionPackages.put(RLANG, "Use rlang package for exceptions."); @@ -184,6 +207,32 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(exceptionPackage); cliOptions.add(CliOption.newString(CodegenConstants.ERROR_OBJECT_TYPE, "Error object type.")); + + supportedLibraries.put(HTTR2, "httr2 (https://httr2.r-lib.org/)"); + supportedLibraries.put(HTTR, "httr (https://cran.r-project.org/web/packages/httr/index.html)"); + + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "HTTP library template (sub-template) to use"); + libraryOption.setEnum(supportedLibraries); + // set httr as the default + libraryOption.setDefault(HTTR); + cliOptions.add(libraryOption); + setLibrary(HTTR); + + cliOptions.add(CliOption.newBoolean(GENERATE_WRAPPER, "Generate a wrapper class (single point of access) for the R client. This option only works with `httr2` library.")); + + // option to change how we process + set the data in the 'additionalProperties' keyword. + CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean( + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.TRUE.toString()); + Map disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>(); + disallowAdditionalPropertiesIfNotPresentOpts.put("false", + "The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications."); + disallowAdditionalPropertiesIfNotPresentOpts.put("true", + "Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default."); + disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts); + cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt); + this.setDisallowAdditionalPropertiesIfNotPresent(true); + } @Override @@ -203,15 +252,14 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { } if (additionalProperties.containsKey(CodegenConstants.EXCEPTION_ON_FAILURE)) { - boolean booleanValue = Boolean.parseBoolean(additionalProperties.get(CodegenConstants.EXCEPTION_ON_FAILURE).toString()); - setReturnExceptionOnFailure(booleanValue); + setReturnExceptionOnFailure(Boolean.parseBoolean( + additionalProperties.get(CodegenConstants.EXCEPTION_ON_FAILURE).toString())); } else { setReturnExceptionOnFailure(false); } if (additionalProperties.containsKey(EXCEPTION_PACKAGE)) { - String exceptionPackage = additionalProperties.get(EXCEPTION_PACKAGE).toString(); - setExceptionPackageToUse(exceptionPackage); + setExceptionPackageToUse(additionalProperties.get(EXCEPTION_PACKAGE).toString()); } else { setExceptionPackageToUse(DEFAULT); } @@ -221,6 +269,31 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { } additionalProperties.put(CodegenConstants.ERROR_OBJECT_TYPE, errorObjectType); + if (additionalProperties.containsKey(OPERATIONID_NAMING)) { + this.setOperationIdNaming(additionalProperties.get(OPERATIONID_NAMING).toString()); + } else { + this.setOperationIdNaming("PascalCase"); // default to PascalCase for backward compatibility + } + additionalProperties.put(CodegenConstants.ERROR_OBJECT_TYPE, errorObjectType); + + if (additionalProperties.containsKey(GENERATE_WRAPPER)) { + this.setGenerateWrapper(Boolean.parseBoolean( + additionalProperties.get(GENERATE_WRAPPER).toString())); + } else { + this.setGenerateWrapper(false); + } + + if (additionalProperties.containsKey(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)) { + setUseOneOfDiscriminatorLookup(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP)); + } else { + additionalProperties.put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, useOneOfDiscriminatorLookup); + } + + if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) { + this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.parseBoolean(additionalProperties + .get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString())); + } + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); additionalProperties.put(CodegenConstants.EXCEPTION_ON_FAILURE, returnExceptionOnFailure); @@ -244,15 +317,28 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("description.mustache", "", "DESCRIPTION")); supportingFiles.add(new SupportingFile("Rbuildignore.mustache", "", ".Rbuildignore")); - supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); + supportingFiles.add(new SupportingFile(".travis.yml.mustache", "", ".travis.yml")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", File.separator + "R", "api_response.R")); - //supportingFiles.add(new SupportingFile("element.mustache", File.separator + "R", "Element.R")); supportingFiles.add(new SupportingFile("api_client.mustache", File.separator + "R", "api_client.R")); supportingFiles.add(new SupportingFile("NAMESPACE.mustache", "", "NAMESPACE")); supportingFiles.add(new SupportingFile("testthat.mustache", File.separator + "tests", "testthat.R")); supportingFiles.add(new SupportingFile("r-client.mustache", File.separator + ".github" + File.separator + "workflows", "r-client.yaml")); supportingFiles.add(new SupportingFile("lintr.mustache", "", ".lintr")); + if (HTTR.equals(getLibrary())) { + // for httr + setLibrary(HTTR); + } else if (HTTR2.equals(getLibrary())) { + // for httr2 + setLibrary(HTTR2); + additionalProperties.put("isHttr2", Boolean.TRUE); + if (generateWrapper) { // generateWrapper option only supports in httr2 library + supportingFiles.add(new SupportingFile("api_wrapper.mustache", "R", packageName.toLowerCase(Locale.ROOT) + "_api.R")); + } + } else { + throw new IllegalArgumentException("Invalid HTTP library " + getLibrary() + ". Only httr, httr2 are supported."); + } + // add lambda for mustache templates to fix license field additionalProperties.put("lambdaLicense", new Mustache.Lambda() { @Override @@ -263,6 +349,16 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { } }); + // add lambda for mustache templates to escape % + additionalProperties.put("lambdaRdocEscape", new Mustache.Lambda() { + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + String content = fragment.execute(); + content = content.trim().replace("%", "\\%"); + writer.write(content); + } + }); + } @Override @@ -341,6 +437,18 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelName(String name) { + // We need to check if schema-mapping has a different model for this class, so we use it + // instead of the auto-generated one. + if (schemaMapping.containsKey(name)) { + return schemaMapping.get(name); + } + + // memoization + String origName = name; + if (schemaKeyToModelNameCache.containsKey(origName)) { + return schemaKeyToModelNameCache.get(origName); + } + if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; } @@ -364,6 +472,7 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } + schemaKeyToModelNameCache.put(origName, camelize(name)); return camelize(name); } @@ -454,7 +563,16 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { sanitizedOperationId = "call_" + sanitizedOperationId; } - return camelize(sanitizedOperationId); + if ("PascalCase".equals(operationIdNaming)) { + return camelize(sanitizedOperationId); + } else if ("camelCase".equals(operationIdNaming)) { + return camelize(sanitizedOperationId, true); + } else if ("snake_case".equals(operationIdNaming)) { + return underscore(sanitizedOperationId); + } else { + LOGGER.error("Invalid operationIdNaming: {}. Please report the issue. Default to PascalCase for the time being", operationIdNaming); + return camelize(sanitizedOperationId); + } } @Override @@ -467,33 +585,23 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { LOGGER.debug("Empty baseName `` (empty string) in the model `{}` has been renamed to `empty_string` to avoid compilation errors.", cm.classname); var.baseName = "empty_string"; } + + // create extension x-r-doc-type to store the data type in r doc format + var.vendorExtensions.put("x-r-doc-type", constructRdocType(var)); } - } - // remove model imports to avoid error - List> imports = objs.getImports(); - final String prefix = modelPackage(); - Iterator> iterator = imports.iterator(); - while (iterator.hasNext()) { - String _import = iterator.next().get("import"); - if (_import.startsWith(prefix)) - iterator.remove(); - } - - // recursively add import for mapping one type to multiple imports - List> recursiveImports = objs.getImports(); - if (recursiveImports != null) { - ListIterator> listIterator = imports.listIterator(); - while (listIterator.hasNext()) { - String _import = listIterator.next().get("import"); - // if the import package happens to be found in the importMapping (key) - // add the corresponding import package to the list - if (importMapping.containsKey(_import)) { - listIterator.add(createMapping("import", importMapping.get(_import))); + // apply the same fix, enhancement for allVars + for (CodegenProperty var : cm.allVars) { + // check to see if base name is an empty string + if ("".equals(var.baseName)) { + LOGGER.debug("Empty baseName `` (empty string) in the model `{}` has been renamed to `empty_string` to avoid compilation errors.", cm.classname); + var.baseName = "empty_string"; } + + // create extension x-r-doc-type to store the data type in r doc format + var.vendorExtensions.put("x-r-doc-type", constructRdocType(var)); } } - return postProcessModelsEnum(objs); } @@ -527,6 +635,34 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { this.errorObjectType = errorObjectType; } + public void setGenerateWrapper(final boolean generateWrapper) { + this.generateWrapper = generateWrapper; + } + + public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) { + this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup; + } + + public boolean getUseOneOfDiscriminatorLookup() { + return this.useOneOfDiscriminatorLookup; + } + + public void setOperationIdNaming(final String operationIdNaming) { + if (!("PascalCase".equals(operationIdNaming) || "camelCase".equals(operationIdNaming) || + "snake_case".equals(operationIdNaming))) { + throw new IllegalArgumentException("Invalid operationIdNaming: " + operationIdNaming + + ". Must be PascalCase, camelCase or snake_case"); + } + + if ("snake_case".equals(operationIdNaming)) { + additionalProperties.put("WithHttpInfo", "_with_http_info"); + } else { + additionalProperties.put("WithHttpInfo", "WithHttpInfo"); + } + + this.operationIdNaming = operationIdNaming; + } + @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection @@ -712,10 +848,10 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { } } else if (ModelUtils.isStringSchema(p)) { if (p.getDefault() != null) { - if (Pattern.compile("\r\n|\r|\n").matcher((String) p.getDefault()).find()) - return "'''" + p.getDefault() + "'''"; + if (Pattern.compile("\r\n|\r|\n").matcher((String.valueOf(p.getDefault()))).find()) + return "'''" + p.getDefault().toString() + "'''"; else - return "\"" + ((String) p.getDefault()).replaceAll("\"", "\\\"") + "\""; + return "\"" + ((String.valueOf(p.getDefault()))).replaceAll("\"", "\\\"") + "\""; } } else if (ModelUtils.isArraySchema(p)) { if (p.getDefault() != null) { @@ -765,11 +901,30 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { return objs; } + /** + * Return the R doc type (e.g. list(\link{Media}), character) + * + * @param codegenProperty Codegen property + * @return R doc type + */ + public String constructRdocType(CodegenProperty codegenProperty) { + if (codegenProperty.isArray) { + return "list(" + constructRdocType(codegenProperty.items) + ")"; + } else if (codegenProperty.isMap) { + return "named list(" + constructRdocType(codegenProperty.items) + ")"; + } else if (languageSpecificPrimitives.contains(codegenProperty.dataType)) { + // primitive type + return codegenProperty.dataType; + } else { // model + return "\\link{" + codegenProperty.dataType + "}"; + } + } + public String constructExampleCode(CodegenParameter codegenParameter, HashMap modelMaps) { if (codegenParameter.isArray) { // array return "list(" + constructExampleCode(codegenParameter.items, modelMaps, 0) + ")"; - } else if (codegenParameter.isMap) { // TODO: map - return "TODO"; + } else if (codegenParameter.isMap) { // map + return "list(key = " + constructExampleCode(codegenParameter.items, modelMaps, 0) + ")"; } else if (languageSpecificPrimitives.contains(codegenParameter.dataType)) { // primitive type return codegenParameter.example; } else { // model @@ -789,8 +944,8 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { if (codegenProperty.isArray) { // array return "list(" + constructExampleCode(codegenProperty.items, modelMaps, depth) + ")"; - } else if (codegenProperty.isMap) { // TODO: map - return "TODO"; + } else if (codegenProperty.isMap) { // map + return "list(key = " + constructExampleCode(codegenProperty.items, modelMaps, depth) + ")"; } else if (languageSpecificPrimitives.contains(codegenProperty.dataType)) { // primitive type if ("character".equals(codegenProperty.dataType)) { if (StringUtils.isEmpty(codegenProperty.example)) { @@ -859,4 +1014,23 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.R; } + + @Override + public String toRegularExpression(String pattern) { + if (pattern == null) { + return null; + } + + // remove leading '/' + if (pattern.charAt(0) == '/') { + pattern = pattern.substring(1); + } + + // remove trailing '/' + if (pattern.charAt(pattern.length() - 1) == '/') { + pattern = pattern.substring(0, pattern.length() - 1); + } + + return escapeText(pattern); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java index 4d1bbeb16c..103114282a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java @@ -45,6 +45,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { public static final String GEM_AUTHOR_EMAIL = "gemAuthorEmail"; public static final String FARADAY = "faraday"; public static final String TYPHOEUS = "typhoeus"; + public static final String USE_AUTOLOAD = "useAutoload"; private final Logger LOGGER = LoggerFactory.getLogger(RubyClientCodegen.class); private static final String NUMERIC_ENUM_PREFIX = "N"; protected static int emptyMethodNameCounter = 0; @@ -62,6 +63,9 @@ public class RubyClientCodegen extends AbstractRubyCodegen { protected String gemAuthorEmail = ""; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + protected boolean useAutoload = false; + + private Map schemaKeyToModelNameCache = new HashMap<>(); public RubyClientCodegen() { super(); @@ -163,6 +167,9 @@ public class RubyClientCodegen extends AbstractRubyCodegen { cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC). defaultValue(Boolean.TRUE.toString())); + cliOptions.add(CliOption.newBoolean(USE_AUTOLOAD, "Use autoload instead of require to load modules."). + defaultValue(Boolean.FALSE.toString())); + supportedLibraries.put(FARADAY, "Faraday (https://github.com/lostisland/faraday) (Beta support)"); supportedLibraries.put(TYPHOEUS, "Typhoeus >= 1.0.1 (https://github.com/typhoeus/typhoeus)"); @@ -232,6 +239,10 @@ public class RubyClientCodegen extends AbstractRubyCodegen { setGemAuthorEmail((String) additionalProperties.get(GEM_AUTHOR_EMAIL)); } + if (additionalProperties.containsKey(USE_AUTOLOAD)) { + setUseAutoload(convertPropertyToBooleanAndWriteBack(USE_AUTOLOAD)); + } + // make api and model doc path available in mustache template additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); @@ -295,7 +306,6 @@ public class RubyClientCodegen extends AbstractRubyCodegen { * Generate Ruby module name from the gem name, e.g. use "OpenAPIClient" for "openapi_client". * * @param gemName Ruby gem name - * * @return Ruby module name */ @SuppressWarnings("static-method") @@ -307,7 +317,6 @@ public class RubyClientCodegen extends AbstractRubyCodegen { * Generate Ruby gem name from the module name, e.g. use "openapi_client" for "OpenAPIClient". * * @param moduleName Ruby module name - * * @return Ruby gem name */ @SuppressWarnings("static-method") @@ -367,6 +376,18 @@ public class RubyClientCodegen extends AbstractRubyCodegen { @Override public String toModelName(final String name) { + // We need to check if schema-mapping has a different model for this class, so we use it + // instead of the auto-generated one. + if (schemaMapping.containsKey(name)) { + return schemaMapping.get(name); + } + + // memoization + String origName = name; + if (schemaKeyToModelNameCache.containsKey(origName)) { + return schemaKeyToModelNameCache.get(origName); + } + String modelName; modelName = sanitizeName(name); @@ -382,6 +403,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { if (isReservedWord(modelName)) { modelName = camelize("Model" + modelName); LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); + schemaKeyToModelNameCache.put(origName, modelName); return modelName; } @@ -394,7 +416,9 @@ public class RubyClientCodegen extends AbstractRubyCodegen { // camelize the model name // phone_number => PhoneNumber - return camelize(modelName); + String camelizedName = camelize(modelName); + schemaKeyToModelNameCache.put(origName, camelizedName); + return camelizedName; } @Override @@ -566,6 +590,10 @@ public class RubyClientCodegen extends AbstractRubyCodegen { this.gemAuthorEmail = gemAuthorEmail; } + public void setUseAutoload(boolean useAutoload) { + this.useAutoload = useAutoload; + } + @Override protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) { final Schema additionalProperties = getAdditionalProperties(schema); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java index 21a96617b0..7355917194 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java @@ -17,14 +17,13 @@ package org.openapitools.codegen.languages; -import com.samskivert.mustache.Mustache.Lambda; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; -import com.google.common.base.Strings; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.parser.util.SchemaTypeUtil; +import joptsimple.internal.Strings; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.model.ModelMap; @@ -40,12 +39,12 @@ import java.io.File; import java.io.IOException; import java.io.Writer; import java.math.BigDecimal; +import java.math.BigInteger; import java.util.*; import static org.openapitools.codegen.utils.StringUtils.camelize; -import static org.openapitools.codegen.utils.StringUtils.underscore; -public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { +public class RustClientCodegen extends AbstractRustCodegen implements CodegenConfig { private final Logger LOGGER = LoggerFactory.getLogger(RustClientCodegen.class); private boolean useSingleRequestParameter = false; private boolean supportAsync = true; @@ -69,8 +68,6 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { protected String modelDocPath = "docs/"; protected String apiFolder = "src/apis"; protected String modelFolder = "src/models"; - protected String enumSuffix = ""; // default to empty string for backward compatibility - protected Map unsignedMapping; public CodegenType getTag() { return CodegenType.CLIENT; @@ -124,22 +121,6 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { embeddedTemplateDir = templateDir = "rust"; - setReservedWordsLowerCase( - Arrays.asList( - "abstract", "alignof", "as", "become", "box", - "break", "const", "continue", "crate", "do", - "else", "enum", "extern", "false", "final", - "fn", "for", "if", "impl", "in", - "let", "loop", "macro", "match", "mod", - "move", "mut", "offsetof", "override", "priv", - "proc", "pub", "pure", "ref", "return", - "Self", "self", "sizeof", "static", "struct", - "super", "trait", "true", "type", "typeof", - "unsafe", "unsized", "use", "virtual", "where", - "while", "yield", "async", "await", "dyn", "try" - ) - ); - defaultIncludes = new HashSet<>( Arrays.asList( "map", @@ -180,12 +161,6 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "serde_json::Value"); typeMapping.put("AnyType", "serde_json::Value"); - unsignedMapping = new HashMap<>(); - unsignedMapping.put("i8", "u8"); - unsignedMapping.put("i16", "u16"); - unsignedMapping.put("i32", "u32"); - unsignedMapping.put("i64", "u64"); - // no need for rust //importMapping = new HashMap(); @@ -410,100 +385,16 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { this.useSingleRequestParameter = useSingleRequestParameter; } - @Override - public String escapeReservedWord(String name) { - if (this.reservedWordsMappings().containsKey(name)) { - return this.reservedWordsMappings().get(name); - } - return '_' + name; - } - @Override public String apiFileFolder() { return (outputFolder + File.separator + apiFolder).replace("/", File.separator); } + @Override public String modelFileFolder() { return (outputFolder + File.separator + modelFolder).replace("/", File.separator); } - @Override - public String toVarName(String name) { - // translate @ for properties (like @type) to at_. - // Otherwise an additional "type" property will leed to duplcates - name = name.replaceAll("^@", "at_"); - - // replace - with _ e.g. created-at => created_at - name = sanitizeName(name.replaceAll("-", "_")); - - // if it's all upper case, convert to lower case - if (name.matches("^[A-Z_]*$")) - return name.toLowerCase(Locale.ROOT); - - // snake_case, e.g. PetId => pet_id - name = underscore(name); - - // for reserved word or word starting with number, append _ - if (isReservedWord(name)) - name = escapeReservedWord(name); - - // for reserved word or word starting with number, append _ - if (name.matches("^\\d.*")) - name = "var_" + name; - - return name; - } - - @Override - public String toParamName(String name) { - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // camelize the model name - // phone_number => PhoneNumber - return camelize(toModelFilename(name)); - } - - @Override - public String toModelFilename(String name) { - - if (!Strings.isNullOrEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; - } - - if (!Strings.isNullOrEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; - } - - name = sanitizeName(name); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(name)) { - LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, "model_" + name); - name = "model_" + name; // e.g. return => ModelReturn (after camelize) - } - - // model name starts with number - if (name.matches("^\\d.*")) { - LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, - "model_" + name); - name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) - } - - return underscore(name); - } - - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // e.g. PetApi.rs => pet_api.rs - return underscore(name) + "_api"; - } - @Override public String apiDocFileFolder() { return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); @@ -514,16 +405,6 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); } - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - - @Override - public String toApiDocFilename(String name) { - return toApiName(name); - } - @Override public String getTypeDeclaration(Schema p) { if (ModelUtils.isArraySchema(p)) { @@ -569,57 +450,39 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { String schemaType = super.getSchemaType(p); String type = typeMapping.getOrDefault(schemaType, schemaType); - boolean bestFit = convertPropertyToBoolean(BEST_FIT_INT); - boolean unsigned = convertPropertyToBoolean(PREFER_UNSIGNED_INT); + if (Objects.equals(p.getType(), "integer")) { + boolean bestFit = convertPropertyToBoolean(BEST_FIT_INT); + boolean preferUnsigned = convertPropertyToBoolean(PREFER_UNSIGNED_INT); - if (bestFit || unsigned) { - BigDecimal maximum = p.getMaximum(); - BigDecimal minimum = p.getMinimum(); + BigInteger minimum = Optional.ofNullable(p.getMinimum()).map(BigDecimal::toBigInteger).orElse(null); + boolean exclusiveMinimum = Optional.ofNullable(p.getExclusiveMinimum()).orElse(false); - try { - if (maximum != null && minimum != null) { - long max = maximum.longValueExact(); - long min = minimum.longValueExact(); + boolean unsigned = preferUnsigned && canFitIntoUnsigned(minimum, exclusiveMinimum); - if (unsigned && bestFit && max <= (Byte.MAX_VALUE * 2) + 1 && min >= 0) { - type = "u8"; - } else if (bestFit && max <= Byte.MAX_VALUE && min >= Byte.MIN_VALUE) { - type = "i8"; - } else if (unsigned && bestFit && max <= (Short.MAX_VALUE * 2) + 1 && min >= 0) { - type = "u16"; - } else if (bestFit && max <= Short.MAX_VALUE && min >= Short.MIN_VALUE) { - type = "i16"; - } else if (unsigned && bestFit && max <= (Integer.MAX_VALUE * 2L) + 1 && min >= 0) { - type = "u32"; - } else if (bestFit && max <= Integer.MAX_VALUE && min >= Integer.MIN_VALUE) { - type = "i32"; - } - } - } catch (ArithmeticException a) { - // no-op; case will be handled in the next if block - } - - if (unsigned && minimum != null && minimum.compareTo(BigDecimal.ZERO) >= 0 && unsignedMapping.containsKey(type)) { - type = unsignedMapping.get(type); + if (Strings.isNullOrEmpty(p.getFormat())) { + if (bestFit) { + return bestFittingIntegerType( + minimum, + exclusiveMinimum, + Optional.ofNullable(p.getMaximum()).map(BigDecimal::toBigInteger).orElse(null), + Optional.ofNullable(p.getExclusiveMaximum()).orElse(false), + preferUnsigned); + } else { + return unsigned ? "u32" : "i32"; + } + } else { + switch (p.getFormat()) { + case "int32": + return unsigned ? "u32" : "i32"; + case "int64": + return unsigned ? "u64" : "i64"; + } } } return type; } - @Override - public String toOperationId(String operationId) { - String sanitizedOperationId = sanitizeName(operationId); - - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, StringUtils.underscore("call_" + operationId)); - sanitizedOperationId = "call_" + sanitizedOperationId; - } - - return StringUtils.underscore(sanitizedOperationId); - } - @Override public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { OperationMap objectMap = objs.getOperations(); @@ -691,12 +554,6 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { return objs; } - @Override - protected boolean needToImport(String type) { - return !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type); - } - public void setPackageName(String packageName) { this.packageName = packageName; } @@ -705,83 +562,6 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { this.packageVersion = packageVersion; } - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - - @Override - public String toEnumValue(String value, String datatype) { - if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { - return value; - } else { - return escapeText(value); - } - } - - @Override - public String toEnumDefaultValue(String value, String datatype) { - return datatype + "_" + value; - } - - @Override - public String toEnumVarName(String name, String datatype) { - if (name.length() == 0) { - return "Empty"; - } - - // number - if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { - String varName = name; - varName = varName.replaceAll("-", "Minus"); - varName = varName.replaceAll("\\+", "Plus"); - varName = varName.replaceAll("\\.", "Dot"); - return varName; - } - - // for symbol, e.g. $, # - if (getSymbolName(name) != null) { - return getSymbolName(name); - } - - // string - String enumName = camelize(sanitizeName(name)); - enumName = enumName.replaceFirst("^_", ""); - enumName = enumName.replaceFirst("_$", ""); - - if (isReservedWord(enumName) || enumName.matches("\\d.*")) { // reserved word or starts with number - return escapeReservedWord(enumName); - } else { - return enumName; - } - } - - @Override - public String toEnumName(CodegenProperty property) { - String name = property.name; - if (!org.apache.commons.lang3.StringUtils.isEmpty(enumSuffix)) { - name = name + "_" + enumSuffix; - } - // camelize the enum name - // phone_number => PhoneNumber - String enumName = camelize(toModelName(name)); - - // remove [] for array or map of enum - enumName = enumName.replace("[]", ""); - - if (enumName.matches("\\d.*")) { // starts with number - return "_" + enumName; - } else { - return enumName; - } - } - @Override public String toDefaultValue(Schema p) { if (p.getDefault() != null) { @@ -791,6 +571,4 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { } } - @Override - public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.RUST; } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java index a8da0e6ddd..5d8d88d943 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java @@ -30,6 +30,7 @@ import io.swagger.v3.oas.models.parameters.Parameter; 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 joptsimple.internal.Strings; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; @@ -46,6 +47,7 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; +import java.math.BigInteger; import java.net.URL; import java.util.*; import java.util.Map.Entry; @@ -55,14 +57,12 @@ import java.util.regex.Pattern; import static org.openapitools.codegen.utils.StringUtils.camelize; import static org.openapitools.codegen.utils.StringUtils.underscore; -public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { +public class RustServerCodegen extends AbstractRustCodegen implements CodegenConfig { private final Logger LOGGER = LoggerFactory.getLogger(RustServerCodegen.class); private Map modelXmlNames = new HashMap(); - private static final String NO_FORMAT = "%%NO_FORMAT"; - protected String apiVersion = "1.0.0"; protected String serverHost = "localhost"; protected int serverPort = 8080; @@ -150,22 +150,6 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { */ embeddedTemplateDir = templateDir = "rust-server"; - /* - * Reserved words. Override this with reserved words specific to your language - */ - setReservedWordsLowerCase( - Arrays.asList( - // From https://doc.rust-lang.org/grammar.html#keywords - "abstract", "alignof", "as", "become", "box", "break", "const", - "continue", "crate", "do", "else", "enum", "extern", "false", - "final", "fn", "for", "if", "impl", "in", "let", "loop", "macro", - "match", "mod", "move", "mut", "offsetof", "override", "priv", - "proc", "pub", "pure", "ref", "return", "Self", "self", "sizeof", - "static", "struct", "super", "trait", "true", "type", "typeof", - "unsafe", "unsized", "use", "virtual", "where", "while", "yield" - ) - ); - defaultIncludes = new HashSet<>( Arrays.asList( "map", @@ -335,7 +319,8 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { */ @Override public String getHelp() { - return "Generates a Rust client/server library (beta) using the openapi-generator project."; + return "Generates a Rust Hyper/Tower server library. Also generates a matching Hyper client library within " + + "the same crate that implements the same trait."; } @Override @@ -367,21 +352,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { if (name.isEmpty()) { return "default"; } - return underscore(name); - } - - /** - * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reserved words - * - * @return the escaped term - */ - @Override - public String escapeReservedWord(String name) { - if (this.reservedWordsMappings().containsKey(name)) { - return this.reservedWordsMappings().get(name); - } - return name + "_"; // add an underscore _suffix_ to the name - a prefix implies unused + return sanitizeIdentifier(name, CasingType.SNAKE_CASE, "api", "API", true); } /** @@ -393,148 +364,16 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); } - @Override - public String toModelName(String name) { - // camelize the model name - // phone_number => PhoneNumber - String camelizedName = camelize(toModelFilename(name)); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(camelizedName)) { - final String modelName = "Model" + camelizedName; - LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", camelizedName, modelName); - return modelName; - } - - // model name starts with number - else if (camelizedName.matches("^\\d.*")) { - // e.g. 200Response => Model200Response (after camelize) - camelizedName = "Model" + camelizedName; - LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, - camelizedName); - } - - return camelizedName; - - } - - @Override - public String toParamName(String name) { - // should be the same as variable name (stolen from RubyClientCodegen) - return toVarName(name); - } - - @Override - public String toVarName(String name) { - // translate @ for properties (like @type) to at_. - // Otherwise an additional "type" property will leed to duplcates - name = name.replaceAll("^@", "at_"); - - String sanitizedName = super.sanitizeName(name); - // for reserved word, append _ - if (isReservedWord(sanitizedName)) { - sanitizedName = escapeReservedWord(sanitizedName); - } - // for word starting with number, prepend "param_" - else if (sanitizedName.matches("^\\d.*")) { - sanitizedName = "param_" + sanitizedName; - } - - return underscore(sanitizedName); - } - @Override public String toOperationId(String operationId) { - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize("call_" + operationId)); - operationId = "call_" + operationId; - } else if (operationId.matches("\\d.*")) { - LOGGER.warn("{} cannot be used as method name because it starts with a digit. Renamed to {}", operationId, - camelize("call_" + operationId)); - operationId = "call_" + operationId; - } - - return camelize(operationId); - } - - @Override - public String toModelFilename(String name) { - if (!StringUtils.isEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; - } - - if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; - } - - name = sanitizeName(name); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(name)) { - LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); - name = "model_" + name; // e.g. return => ModelReturn (after camelize) - } - - return underscore(name); - } - - @Override - public String toEnumName(CodegenProperty property) { - return sanitizeName(camelize(property.name)) + "Enum"; - } - - @Override - public String toEnumVarName(String value, String datatype) { - String var = null; - if (value.isEmpty()) { - var = "EMPTY"; - } - - // for symbol, e.g. $, # - else if (getSymbolName(value) != null) { - var = getSymbolName(value).toUpperCase(Locale.ROOT); - } - - // number - else if ("Integer".equals(datatype) || "Long".equals(datatype) || - "Float".equals(datatype) || "Double".equals(datatype)) { - String varName = "NUMBER_" + value; - varName = varName.replaceAll("-", "MINUS_"); - varName = varName.replaceAll("\\+", "PLUS_"); - varName = varName.replaceAll("\\.", "_DOT_"); - var = varName; - } - - // string - else { - var = value.replaceAll("\\W+", "_").toUpperCase(Locale.ROOT); - if (var.matches("\\d.*")) { - var = "_" + var; - } else { - var = sanitizeName(var); - } - } - return var; + // rust-server uses camel case instead + return sanitizeIdentifier(operationId, CasingType.CAMEL_CASE, "call", "method", true); } @Override public String toEnumValue(String value, String datatype) { - if ("Integer".equals(datatype) || "Long".equals(datatype) || - "Float".equals(datatype) || "Double".equals(datatype)) { - return value; - } else { - return "\"" + escapeText(value) + "\""; - } - } - - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // e.g. PetApi.go => pet_api.go - return underscore(name); + // rust-server templates expect value to be in quotes + return "\"" + super.toEnumValue(value, datatype) + "\""; } @Override @@ -547,27 +386,11 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); } - @Override - public String toModelDocFilename(String name) { - return toModelName(name); - } - @Override public String toApiDocFilename(String name) { return toApiName(name) + "_api"; } - @Override - public String escapeQuotationMark(String input) { - // remove " to avoid code injection - return input.replace("\"", ""); - } - - @Override - public String escapeUnsafeCharacters(String input) { - return input.replace("*/", "*_/").replace("/*", "/_*"); - } - private boolean isMimetypeXml(String mimetype) { return mimetype.toLowerCase(Locale.ROOT).startsWith(xmlMimeType) || mimetype.toLowerCase(Locale.ROOT).startsWith(problemXmlMimeType) || @@ -734,6 +557,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { // basePath on the front. for (CodegenParameter param : op.pathParams) { // Replace {baseName} with (?P[^/?#]*) for regex + // TODO: Sanitize baseName to avoid using '-' (see clippy::invalid_regex) String paramSearch = "{" + param.baseName + "}"; String paramReplace = "(?P<" + param.baseName + ">[^/?#]*)"; @@ -1110,9 +934,12 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { // only generate operation for the first tag of the tags - if (tag != null && co.tags.size() > 1 && !tag.equals(co.tags.get(0).getName())) { - LOGGER.info("generated skip additional tag `{}` with operationId={}", tag, co.operationId); - return; + if (tag != null && co.tags.size() > 1) { + String expectedTag = sanitizeTag(co.tags.get(0).getName()); + if (!tag.equals(expectedTag)) { + LOGGER.info("generated skip additional tag `{}` with operationId={}", tag, co.operationId); + return; + } } super.addOperationToGroup(tag, resourcePath, operation, co, operations); } @@ -1455,46 +1282,42 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { property.isPrimitiveType = true; } - if ("integer".equals(property.baseType)) { - // custom integer formats (legacy) - if ("uint32".equals(property.dataFormat)) { - property.dataType = "u32"; - } else if ("uint64".equals(property.dataFormat)) { - property.dataType = "u64"; + // Integer type fitting + if (Objects.equals(property.baseType, "integer")) { + BigInteger minimum = Optional.ofNullable(property.getMinimum()).map(BigInteger::new).orElse(null); + BigInteger maximum = Optional.ofNullable(property.getMaximum()).map(BigInteger::new).orElse(null); + + boolean unsigned = canFitIntoUnsigned(minimum, property.getExclusiveMinimum()); + + if (Strings.isNullOrEmpty(property.dataFormat)) { + property.dataType = bestFittingIntegerType(minimum, + property.getExclusiveMinimum(), + maximum, + property.getExclusiveMaximum(), + true); } else { - // match int type to schema constraints - Long inclusiveMinimum = property.minimum != null ? Long.parseLong(property.minimum) : null; - if (inclusiveMinimum != null && property.exclusiveMinimum) { - inclusiveMinimum++; - } - - // a signed int is required unless a minimum greater than zero is set - boolean unsigned = inclusiveMinimum != null && inclusiveMinimum >= 0; - - Long inclusiveMaximum = property.maximum != null ? Long.parseLong(property.maximum) : null; - if (inclusiveMaximum != null && property.exclusiveMaximum) { - inclusiveMaximum--; - } - - switch (property.dataFormat == null ? NO_FORMAT : property.dataFormat) { - // standard swagger formats + switch (property.dataFormat) { + // custom integer formats (legacy) + case "uint32": + property.dataType = "u32"; + break; + case "uint64": + property.dataType = "u64"; + break; case "int32": property.dataType = unsigned ? "u32" : "i32"; break; - case "int64": property.dataType = unsigned ? "u64" : "i64"; break; - - case NO_FORMAT: - property.dataType = matchingIntType(unsigned, inclusiveMinimum, inclusiveMaximum); - break; - default: - // unknown format LOGGER.warn("The integer format '{}' is not recognized and will be ignored.", property.dataFormat); - property.dataType = matchingIntType(unsigned, inclusiveMinimum, inclusiveMaximum); + property.dataType = bestFittingIntegerType(minimum, + property.getExclusiveMinimum(), + maximum, + property.getExclusiveMaximum(), + true); } } } @@ -1517,46 +1340,6 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { } } - private long requiredBits(Long bound, boolean unsigned) { - if (bound == null) return 0; - - if (unsigned) { - if (bound < 0) { - throw new RuntimeException("Unsigned bound is negative: " + bound); - } - return 65L - Long.numberOfLeadingZeros(bound >> 1); - } - - return 65L - Long.numberOfLeadingZeros( - // signed bounds go from (-n) to (n - 1), i.e. i8 goes from -128 to 127 - bound < 0 ? Math.abs(bound) - 1 : bound); - } - - private String matchingIntType(boolean unsigned, Long inclusiveMin, Long inclusiveMax) { - long requiredMinBits = requiredBits(inclusiveMin, unsigned); - long requiredMaxBits = requiredBits(inclusiveMax, unsigned); - long requiredBits = Math.max(requiredMinBits, requiredMaxBits); - - if (requiredMaxBits == 0 && requiredMinBits <= 16) { - // rust 'size' types are arch-specific and thus somewhat loose - // so they are used when no format or maximum are specified - // and as long as minimum stays within plausible smallest ptr size (16 bits) - // this way all rust types are obtainable without defining custom formats - // this behavior (default int size) could also follow a generator flag - return unsigned ? "usize" : "isize"; - - } else if (requiredBits <= 8) { - return unsigned ? "u8" : "i8"; - - } else if (requiredBits <= 16) { - return unsigned ? "u16" : "i16"; - - } else if (requiredBits <= 32) { - return unsigned ? "u32" : "i32"; - } - return unsigned ? "u64" : "i64"; - } - @Override public ModelsMap postProcessModels(ModelsMap objs) { for (ModelMap mo : objs.getModels()) { @@ -1740,9 +1523,6 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { } } - @Override - public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.RUST; } - @Override protected String getParameterDataType(Parameter parameter, Schema schema) { if (parameter.get$ref() != null) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java index e9d9039220..a5ef96adc7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java @@ -115,7 +115,7 @@ public class ScalaSttpClientCodegen extends AbstractScalaCodegen implements Code String jsonLibrary = JSON_LIBRARY_PROPERTY.getValue(additionalProperties); - String jsonValueClass = jsonLibrary == "circe" ? "io.circe.Json" : "org.json4s.JValue"; + String jsonValueClass = "circe".equals(jsonLibrary) ? "io.circe.Json" : "org.json4s.JValue"; additionalProperties.put(CodegenConstants.GROUP_ID, groupId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); @@ -127,10 +127,10 @@ public class ScalaSttpClientCodegen extends AbstractScalaCodegen implements Code additionalProperties.put("fnCamelize", new CamelizeLambda(false)); additionalProperties.put("fnEnumEntry", new EnumEntryLambda()); - importMapping.remove("Seq"); - importMapping.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); +// importMapping.remove("Seq"); +// importMapping.remove("List"); +// importMapping.remove("Set"); +// importMapping.remove("Map"); // TODO: there is no specific sttp mapping. All Scala Type mappings should be in AbstractScala typeMapping = new HashMap<>(); @@ -409,6 +409,30 @@ public class ScalaSttpClientCodegen extends AbstractScalaCodegen implements Code } } + /** + * Update datatypeWithEnum for array container + * + * @param property Codegen property + */ + @Override + protected void updateDataTypeWithEnumForArray(CodegenProperty property) { + CodegenProperty baseItem = property.items; + while (baseItem != null && (Boolean.TRUE.equals(baseItem.isMap) + || Boolean.TRUE.equals(baseItem.isArray))) { + baseItem = baseItem.items; + } + if (baseItem != null) { + // set datetypeWithEnum as only the inner type is enum + property.datatypeWithEnum = toEnumName(baseItem); + // naming the enum with respect to the language enum naming convention + // e.g. remove [], {} from array/map of enum + property.enumName = toEnumName(property); + property._enum = baseItem._enum; + + updateCodegenPropertyEnum(property); + } + } + public static abstract class Property { final String name; final String description; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java index cfd0f1c1bc..7820efb942 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java @@ -83,6 +83,7 @@ public class SpringCodegen extends AbstractJavaCodegen public static final String BASE_PACKAGE = "basePackage"; public static final String INTERFACE_ONLY = "interfaceOnly"; public static final String USE_FEIGN_CLIENT_URL = "useFeignClientUrl"; + public static final String USE_FEIGN_CLIENT = "useFeignClient"; public static final String DELEGATE_PATTERN = "delegatePattern"; public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; public static final String VIRTUAL_SERVICE = "virtualService"; @@ -110,6 +111,7 @@ public class SpringCodegen extends AbstractJavaCodegen protected String basePackage = "org.openapitools"; protected boolean interfaceOnly = false; protected boolean useFeignClientUrl = true; + protected boolean useFeignClient = false; protected boolean delegatePattern = false; protected boolean delegateMethod = false; protected boolean singleContentTypes = false; @@ -297,10 +299,12 @@ public class SpringCodegen extends AbstractJavaCodegen LOGGER.info("Set base package to invoker package ({})", basePackage); } - super.processOpts(); useOneOfInterfaces = true; legacyDiscriminatorBehavior = false; + // Please refrain from updating values of Config Options after super.ProcessOpts() is called + super.processOpts(); + if (DocumentationProvider.SPRINGFOX.equals(getDocumentationProvider())) { LOGGER.warn("The springfox documentation provider is deprecated for removal. Use the springdoc provider instead."); } @@ -489,6 +493,8 @@ public class SpringCodegen extends AbstractJavaCodegen additionalProperties.put(SINGLE_CONTENT_TYPES, "true"); this.setSingleContentTypes(true); } + additionalProperties.put(USE_FEIGN_CLIENT, "true"); + this.setUseFeignClient(true); } else { apiTemplateFiles.put("apiController.mustache", "Controller.java"); supportingFiles.add(new SupportingFile("application.mustache", @@ -844,6 +850,10 @@ public class SpringCodegen extends AbstractJavaCodegen this.singleContentTypes = singleContentTypes; } + public void setUseFeignClient( boolean useFeignClient ) { + this.useFeignClient = useFeignClient; + } + public void setSkipDefaultInterface(boolean skipDefaultInterface) { this.skipDefaultInterface = skipDefaultInterface; } @@ -967,7 +977,7 @@ public class SpringCodegen extends AbstractJavaCodegen parentVar.isInherited = true; LOGGER.info("adding parent variable {}", property.name); codegenModel.parentVars.add(parentVar); - Set imports = parentVar.getImports(true).stream().filter(Objects::nonNull).collect(Collectors.toSet()); + Set imports = parentVar.getImports(true, this.importBaseType, generatorMetadata.getFeatureSet()).stream().filter(Objects::nonNull).collect(Collectors.toSet()); for (String imp: imports) { // Avoid dupes if (!codegenModel.getImports().contains(imp)) { @@ -1034,13 +1044,21 @@ public class SpringCodegen extends AbstractJavaCodegen final List> imports = objs.getImports(); for (ModelMap mo : objs.getModels()) { CodegenModel cm = mo.getModel(); - // for enum model + boolean addNullableImports = false; + for (CodegenProperty var : cm.vars) { + addNullableImports = isAddNullableImports(cm, addNullableImports, var); + } if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) { cm.imports.add(importMapping.get("JsonValue")); final Map item = new HashMap<>(); item.put("import", importMapping.get("JsonValue")); imports.add(item); } + if (addNullableImports) { + Map imports2Classnames = new HashMap<>(); + imports2Classnames.put("NoSuchElementException", "java.util.NoSuchElementException"); + addImports(imports, cm, imports2Classnames); + } } return objs; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java index 4c0b8326a4..4d430ac4ee 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java @@ -72,6 +72,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig public static final String HASHABLE_MODELS = "hashableModels"; public static final String USE_JSON_ENCODABLE = "useJsonEncodable"; public static final String MAP_FILE_BINARY_TO_DATA = "mapFileBinaryToData"; + public static final String USE_CUSTOM_DATE_WITHOUT_TIME = "useCustomDateWithoutTime"; protected static final String LIBRARY_ALAMOFIRE = "alamofire"; protected static final String LIBRARY_URLSESSION = "urlsession"; protected static final String LIBRARY_VAPOR = "vapor"; @@ -96,6 +97,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig protected boolean hashableModels = true; protected boolean useJsonEncodable = true; protected boolean mapFileBinaryToData = false; + protected boolean useCustomDateWithoutTime = false; protected String[] responseAs = new String[0]; protected String sourceFolder = swiftPackagePath; protected HashSet objcReservedWords; @@ -134,6 +136,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig "String", "Data", "Date", + "OpenAPIDateWithoutTime", "Character", "UUID", "URL", @@ -221,7 +224,6 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("array", "Array"); typeMapping.put("map", "Dictionary"); typeMapping.put("set", "Set"); - typeMapping.put("date", "Date"); typeMapping.put("Date", "Date"); typeMapping.put("DateTime", "Date"); typeMapping.put("boolean", "Bool"); @@ -309,6 +311,10 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig "[WARNING] This option will be removed and enabled by default in the future once we've enhanced the code to work with `Data` in all the different situations. Map File and Binary to Data (default: false)") .defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(USE_CUSTOM_DATE_WITHOUT_TIME, + "Uses a custom type to decode and encode dates without time information to support OpenAPIs date format (default: false)") + .defaultValue(Boolean.FALSE.toString())); + supportedLibraries.put(LIBRARY_URLSESSION, "[DEFAULT] HTTP client: URLSession"); supportedLibraries.put(LIBRARY_ALAMOFIRE, "HTTP client: Alamofire"); supportedLibraries.put(LIBRARY_VAPOR, "HTTP client: Vapor"); @@ -517,6 +523,16 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("binary", "Data"); } + if (additionalProperties.containsKey(USE_CUSTOM_DATE_WITHOUT_TIME)) { + setUseCustomDateWithoutTime(convertPropertyToBooleanAndWriteBack(USE_CUSTOM_DATE_WITHOUT_TIME)); + } + additionalProperties.put(USE_CUSTOM_DATE_WITHOUT_TIME, useCustomDateWithoutTime); + if (useCustomDateWithoutTime) { + typeMapping.put("date", "OpenAPIDateWithoutTime"); + } else { + typeMapping.put("date", "Date"); + } + if (additionalProperties.containsKey(USE_CLASSES)) { setUseClasses(convertPropertyToBooleanAndWriteBack(USE_CLASSES)); } @@ -538,9 +554,6 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("CodableHelper.mustache", sourceFolder, "CodableHelper.swift")); - supportingFiles.add(new SupportingFile("OpenISO8601DateFormatter.mustache", - sourceFolder, - "OpenISO8601DateFormatter.swift")); supportingFiles.add(new SupportingFile("JSONDataEncoding.mustache", sourceFolder, "JSONDataEncoding.swift")); @@ -572,6 +585,14 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); + supportingFiles.add(new SupportingFile("OpenISO8601DateFormatter.mustache", + sourceFolder, + "OpenISO8601DateFormatter.swift")); + if (useCustomDateWithoutTime) { + supportingFiles.add(new SupportingFile("OpenAPIDateWithoutTime.mustache", + sourceFolder, + "OpenAPIDateWithoutTime.swift")); + } supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); @@ -581,6 +602,9 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("swiftformat.mustache", + "", + ".swiftformat")); switch (getLibrary()) { case LIBRARY_ALAMOFIRE: @@ -612,6 +636,10 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig this.mapFileBinaryToData = mapFileBinaryToData; } + public void setUseCustomDateWithoutTime(boolean useCustomDateWithoutTime) { + this.useCustomDateWithoutTime = useCustomDateWithoutTime; + } + @Override protected boolean isReservedWord(String word) { return word != null && reservedWords.contains(word); //don't lowercase as super does diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java index 73903cdf95..3457324b53 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java @@ -20,6 +20,7 @@ package org.openapitools.codegen.languages; import io.swagger.v3.oas.models.media.Schema; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.DocumentationFeature; +import org.openapitools.codegen.meta.features.GlobalFeature; import org.openapitools.codegen.model.ModelMap; import org.openapitools.codegen.model.ModelsMap; import org.openapitools.codegen.model.OperationMap; @@ -69,7 +70,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode public static final String STRING_ENUMS_DESC = "Generate string enums instead of objects for enum values."; public static final String QUERY_PARAM_OBJECT_FORMAT = "queryParamObjectFormat"; - protected String ngVersion = "13.0.1"; + protected String ngVersion = "14.0.5"; protected String npmRepository = null; private boolean useSingleRequestParameter = false; protected String serviceSuffix = "Service"; @@ -86,7 +87,10 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode public TypeScriptAngularClientCodegen() { super(); - modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .includeGlobalFeatures(GlobalFeature.ParameterStyling) + ); this.outputFolder = "generated-code/typescript-angular"; @@ -145,7 +149,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode @Override public String getHelp() { - return "Generates a TypeScript Angular (9.x - 13.x) client library."; + return "Generates a TypeScript Angular (9.x - 14.x) client library."; } @Override @@ -160,6 +164,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), "configuration.ts")); supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts")); supportingFiles.add(new SupportingFile("encoder.mustache", getIndexDirectory(), "encoder.ts")); + supportingFiles.add(new SupportingFile("param.mustache", getIndexDirectory(), "param.ts")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md")); @@ -274,7 +279,9 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } // Set the typescript version compatible to the Angular version - if (ngVersion.atLeast("13.0.0")) { + if (ngVersion.atLeast("14.0.0")) { + additionalProperties.put("tsVersion", ">=4.6.0 <=4.8.0"); + } else if (ngVersion.atLeast("13.0.0")) { additionalProperties.put("tsVersion", ">=4.4.2 <4.5.0"); } else if (ngVersion.atLeast("12.0.0")) { additionalProperties.put("tsVersion", ">=4.3.0 <4.4.0"); @@ -289,7 +296,9 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } // Set the rxJS version compatible to the Angular version - if (ngVersion.atLeast("13.0.0")) { + if (ngVersion.atLeast("14.0.0")) { + additionalProperties.put("rxjsVersion", "7.5.5"); + } else if (ngVersion.atLeast("13.0.0")) { additionalProperties.put("rxjsVersion", "7.4.0"); } else if (ngVersion.atLeast("10.0.0")) { additionalProperties.put("rxjsVersion", "6.6.0"); @@ -300,7 +309,10 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode supportingFiles.add(new SupportingFile("ng-package.mustache", getIndexDirectory(), "ng-package.json")); // Specific ng-packagr configuration - if (ngVersion.atLeast("13.0.0")) { + if (ngVersion.atLeast("14.0.0")) { + additionalProperties.put("ngPackagrVersion", "14.0.2"); + additionalProperties.put("tsickleVersion", "0.46.3"); + } else if (ngVersion.atLeast("13.0.0")) { additionalProperties.put("ngPackagrVersion", "13.0.3"); additionalProperties.put("tsickleVersion", "0.43.0"); } else if (ngVersion.atLeast("12.0.0")) { @@ -318,7 +330,9 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } // set zone.js version - if (ngVersion.atLeast("12.0.0")) { + if (ngVersion.atLeast("14.0.0")) { + additionalProperties.put("zonejsVersion", "0.11.5"); + } else if (ngVersion.atLeast("12.0.0")) { additionalProperties.put("zonejsVersion", "0.11.4"); } else if (ngVersion.atLeast("11.0.0")) { additionalProperties.put("zonejsVersion", "0.11.3"); @@ -395,6 +409,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode List ops = objs.getOperation(); boolean hasSomeFormParams = false; + boolean hasSomeEncodableParams = false; for (CodegenOperation op : ops) { if (op.getHasFormParams()) { hasSomeFormParams = true; @@ -404,7 +419,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode // Prep a string buffer where we're going to set up our new version of the string. StringBuilder pathBuffer = new StringBuilder(); - StringBuilder parameterName = new StringBuilder(); + ParameterExpander paramExpander = new ParameterExpander(op, this::toParamName); int insideCurly = 0; // Iterate through existing string, one character at a time. @@ -413,27 +428,18 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode case '{': // We entered curly braces, so track that. insideCurly++; - - // Add the more complicated component instead of just the brace. - pathBuffer.append("${encodeURIComponent(String("); break; case '}': // We exited curly braces, so track that. insideCurly--; - // Add the more complicated component instead of just the brace. - CodegenParameter parameter = findPathParameterByName(op, parameterName.toString()); - pathBuffer.append(toParamName(parameterName.toString())); - if (parameter != null && parameter.isDateTime) { - pathBuffer.append(".toISOString()"); - } - pathBuffer.append("))}"); - parameterName.setLength(0); + pathBuffer.append(paramExpander.buildPathEntry()); + hasSomeEncodableParams = true; break; default: char nextChar = op.path.charAt(i); if (insideCurly > 0) { - parameterName.append(nextChar); + paramExpander.appendToParameterName(nextChar); } else { pathBuffer.append(nextChar); } @@ -446,6 +452,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } operations.put("hasSomeFormParams", hasSomeFormParams); + operations.put("hasSomeEncodableParams", hasSomeEncodableParams); // Add additional filename information for model imports in the services List> imports = operations.getImports(); @@ -458,22 +465,6 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode return operations; } - /** - * Finds and returns a path parameter of an operation by its name - * - * @param operation the operation - * @param parameterName the name of the parameter - * @return param - */ - private CodegenParameter findPathParameterByName(CodegenOperation operation, String parameterName) { - for (CodegenParameter param : operation.pathParams) { - if (param.baseName.equals(parameterName)) { - return param; - } - } - return null; - } - @Override public ModelsMap postProcessModels(ModelsMap objs) { ModelsMap result = super.postProcessModels(objs); @@ -597,7 +588,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode if (importMapping.containsKey(name)) { return importMapping.get(name); } - return DEFAULT_IMPORT_PREFIX + this.convertUsingFileNamingConvention(this.sanitizeName(name)) + modelFileSuffix; + return DEFAULT_IMPORT_PREFIX + this.convertUsingFileNamingConvention(super.toModelFilename(name)) + modelFileSuffix; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java index e459db754c..1dec842568 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java @@ -282,6 +282,10 @@ public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodege supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json")); + // in case ECMAScript 6 is supported add another tsconfig for an ESM (ECMAScript Module) + if (supportsES6) { + supportingFiles.add(new SupportingFile("tsconfig.esm.mustache", "", "tsconfig.esm.json")); + } } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java index 26895f643b..934fef9246 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java @@ -114,9 +114,6 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo this.generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.EXPERIMENTAL).build(); - // clear import mapping (from default generator) as TS does not use it - // at the moment - importMapping.clear(); outputFolder = "generated-code" + File.separator + "typescript"; embeddedTemplateDir = templateDir = "typescript"; @@ -237,7 +234,7 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo supportingFiles.add(new SupportingFile("types" + File.separator + "ObjectParamAPI.mustache", "types", "ObjectParamAPI.ts")); // models - setModelPackage(""); + setModelPackage("models"); supportingFiles.add(new SupportingFile("model" + File.separator + "ObjectSerializer.mustache", "models", "ObjectSerializer.ts")); modelTemplateFiles.put("model" + File.separator + "model.mustache", ".ts"); @@ -325,8 +322,7 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo // Add additional filename information for model imports in the apis List> imports = operations.getImports(); for (Map im : imports) { - im.put("filename", im.get("import").replace(".", "/")); - im.put("classname", getModelnameFromModelFilename(im.get("import"))); + im.put("filename", im.get("import")); } OperationMap operationsMap = operations.getOperations(); @@ -362,11 +358,6 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo return String.join(" | ", returnTypes); } - private String getModelnameFromModelFilename(String filename) { - String name = filename.substring((modelPackage() + File.separator).length()); - return camelize(name); - } - @Override public String escapeReservedWord(String name) { if (this.reservedWordsMappings().containsKey(name)) { @@ -413,6 +404,11 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo return toTypescriptTypeName(fullModelName, "Model"); } + @Override + public String toModelImport(String name) { + return ".." + File.separator + modelPackage() + File.separator + toModelName(name); + } + protected String addPrefix(String name, String prefix) { if (!StringUtils.isEmpty(prefix)) { name = prefix + "_" + name; @@ -466,7 +462,6 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo return toModelName(name); } - @Override protected String getParameterDataType(Parameter parameter, Schema p) { // handle enums of various data types @@ -731,14 +726,13 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo HashMap tsImport = new HashMap<>(); // TVG: This is used as class name in the import statements of the model file tsImport.put("classname", im); - tsImport.put("filename", toModelFilename(im)); + tsImport.put("filename", importMapping.getOrDefault(im, toModelImport(im))); tsImports.add(tsImport); } } return tsImports; } - @Override public Map postProcessAllModels(Map objs) { Map result = super.postProcessAllModels(objs); @@ -809,7 +803,6 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo // change package names apiPackage = this.apiPackage + ".apis"; - modelPackage = this.modelPackage + ".models"; testPackage = this.testPackage + ".tests"; additionalProperties.putIfAbsent(FRAMEWORK_SWITCH, FRAMEWORKS[0]); @@ -887,7 +880,7 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo inner = ((ArraySchema) p).getItems(); return this.getSchemaType(p) + "<" + this.getTypeDeclaration(unaliasSchema(inner)) + ">"; } else if (ModelUtils.isMapSchema(p)) { - inner = (Schema) p.getAdditionalProperties(); + inner = getSchemaAdditionalProperties(p); return "{ [key: string]: " + this.getTypeDeclaration(unaliasSchema(inner)) + "; }"; } else if (ModelUtils.isFileSchema(p)) { return "HttpFile"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java index 8ff85cb156..298c776bdf 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java @@ -973,6 +973,14 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege return TypeScriptFetchClientCodegen.getItemsDataType(this.items); } + public boolean isDateType() { + return isDate && "Date".equals(dataType); + } + + public boolean isDateTimeType() { + return isDateTime && "Date".equals(dataType); + } + public ExtendedCodegenParameter(CodegenParameter cp) { super(); @@ -1110,6 +1118,14 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege return TypeScriptFetchClientCodegen.getItemsDataType(this.items); } + public boolean isDateType() { + return isDate && "Date".equals(dataType); + } + + public boolean isDateTimeType() { + return isDateTime && "Date".equals(dataType); + } + public ExtendedCodegenProperty(CodegenProperty cp) { super(); @@ -1361,6 +1377,14 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege public String returnPassthrough; public boolean hasReturnPassthroughVoid; + public boolean isDateType() { + return isDate && "Date".equals(dataType); + } + + public boolean isDateTimeType() { + return isDateTime && "Date".equals(dataType); + } + public ExtendedCodegenModel(CodegenModel cm) { super(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNestjsClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNestjsClientCodegen.java index 5814238c94..19b9369bd8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNestjsClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNestjsClientCodegen.java @@ -53,7 +53,7 @@ public class TypeScriptNestjsClientCodegen extends AbstractTypeScriptClientCodeg public static final String STRING_ENUMS = "stringEnums"; public static final String STRING_ENUMS_DESC = "Generate string enums instead of objects for enum values."; - protected String nestVersion = "6.0.0"; + protected String nestVersion = "8.0.0"; protected String npmRepository = null; protected String serviceSuffix = "Service"; protected String serviceFileSuffix = ".service"; @@ -91,7 +91,7 @@ public class TypeScriptNestjsClientCodegen extends AbstractTypeScriptClientCodeg this.cliOptions.add(CliOption.newBoolean(TAGGED_UNIONS, "Use discriminators to create tagged unions instead of extending interfaces.", this.taggedUnions)); - this.cliOptions.add(new CliOption(NEST_VERSION, "The version of Nestjs.").defaultValue(this.nestVersion)); + this.cliOptions.add(new CliOption(NEST_VERSION, "The version of Nestjs.").addEnum("8.0.0","Use new HttpModule and HttpService from @nestjs/axios.").addEnum("6.0.0","Use old HttpModule and HttpService from @nestjs/common.").defaultValue(this.nestVersion)); this.cliOptions.add(new CliOption(SERVICE_SUFFIX, "The suffix of the generated service.").defaultValue(this.serviceSuffix)); this.cliOptions.add(new CliOption(SERVICE_FILE_SUFFIX, "The suffix of the file of the generated service (service.ts).").defaultValue(this.serviceFileSuffix)); this.cliOptions.add(new CliOption(MODEL_SUFFIX, "The suffix of the generated model.")); @@ -113,7 +113,7 @@ public class TypeScriptNestjsClientCodegen extends AbstractTypeScriptClientCodeg @Override public String getHelp() { - return "Generates a TypeScript Nestjs 6.x client library."; + return "Generates a TypeScript Nestjs 8.x or 6.x client library."; } @Override @@ -170,6 +170,7 @@ public class TypeScriptNestjsClientCodegen extends AbstractTypeScriptClientCodeg additionalProperties.put("injectionToken", nestVersion.atLeast("4.0.0") ? "InjectionToken" : "OpaqueToken"); additionalProperties.put("injectionTokenTyped", nestVersion.atLeast("4.0.0")); additionalProperties.put("useHttpClient", nestVersion.atLeast("4.3.0")); + additionalProperties.put("useAxiosHttpModule", nestVersion.atLeast("8.0.0")); if (additionalProperties.containsKey(SERVICE_SUFFIX)) { serviceSuffix = additionalProperties.get(SERVICE_SUFFIX).toString(); validateClassSuffixArgument("Service", serviceSuffix); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java index 09bc8dc2c8..fbabd3bd5a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java @@ -746,7 +746,7 @@ public class ModelUtils { if (null != schema.getProperties() && !schema.getProperties().isEmpty() && // has properties (schema.getAdditionalProperties() == null || // no additionalProperties is set - (schema.getAdditionalProperties() instanceof Boolean && !(Boolean)schema.getAdditionalProperties()))) { + (schema.getAdditionalProperties() instanceof Boolean && !(Boolean) schema.getAdditionalProperties()))) { return true; } return false; @@ -1088,11 +1088,11 @@ public class ModelUtils { * Has self reference? * * @param openAPI OpenAPI spec. - * @param schema Schema + * @param schema Schema * @return boolean true if it has at least one self reference */ public static boolean hasSelfReference(OpenAPI openAPI, - Schema schema) { + Schema schema) { return hasSelfReference(openAPI, schema, null); } @@ -1100,13 +1100,13 @@ public class ModelUtils { * Has self reference? * * @param openAPI OpenAPI spec. - * @param schema Schema + * @param schema Schema * @param visitedSchemaNames A set of visited schema names * @return boolean true if it has at least one self reference */ public static boolean hasSelfReference(OpenAPI openAPI, - Schema schema, - Set visitedSchemaNames) { + Schema schema, + Set visitedSchemaNames) { if (visitedSchemaNames == null) { visitedSchemaNames = new HashSet(); } @@ -1165,7 +1165,7 @@ public class ModelUtils { return hasSelfReference(openAPI, schema.getNot(), visitedSchemaNames); } else if (schema.getProperties() != null && !schema.getProperties().isEmpty()) { // go through properties to see if there's any self-reference - for (Schema property : ((Map)schema.getProperties()).values()) { + for (Schema property : ((Map) schema.getProperties()).values()) { if (hasSelfReference(openAPI, property, visitedSchemaNames)) { return true; } @@ -1240,14 +1240,10 @@ public class ModelUtils { } } else if (isObjectSchema(ref)) { // model if (ref.getProperties() != null && !ref.getProperties().isEmpty()) { // has at least one property - if (hasSelfReference(openAPI, ref)) { - // it's self referencing so returning itself instead - return schema; - } else { - // TODO we may revise below to return `ref` instead of schema - // which is the last reference to the actual model/object - return schema; - } + // TODO we may need to check `hasSelfReference(openAPI, ref)` as a special/edge case: + // TODO we may also need to revise below to return `ref` instead of schema + // which is the last reference to the actual model/object + return schema; } else { // free form object (type: object) return unaliasSchema(openAPI, allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), schemaMappings); @@ -1352,7 +1348,7 @@ public class ModelUtils { Map>> groupedByParent = allSchemas.entrySet().stream() .filter(entry -> isComposedSchema(entry.getValue())) - .filter(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas)!=null) + .filter(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas) != null) .collect(Collectors.groupingBy(entry -> getParentName((ComposedSchema) entry.getValue(), allSchemas))); return groupedByParent.entrySet().stream() @@ -1451,7 +1447,7 @@ public class ModelUtils { // allOf with a single $ref (no discriminator) // TODO to be removed in 5.x or 6.x release LOGGER.info("[deprecated] inheritance without use of 'discriminator.propertyName' has been deprecated" + - " in the 5.x release. Composed schema name: {}. Title: {}", + " in the 5.x release. Composed schema name: {}. Title: {}", composedSchema.getName(), composedSchema.getTitle()); } @@ -1507,8 +1503,7 @@ public class ModelUtils { private static boolean hasOrInheritsDiscriminator(Schema schema, Map allSchemas) { if (schema.getDiscriminator() != null && StringUtils.isNotEmpty(schema.getDiscriminator().getPropertyName())) { return true; - } - else if (StringUtils.isNotEmpty(schema.get$ref())) { + } else if (StringUtils.isNotEmpty(schema.get$ref())) { String parentName = getSimpleRef(schema.get$ref()); Schema s = allSchemas.get(parentName); if (s != null) { @@ -1626,6 +1621,10 @@ public class ModelUtils { * @return boolean */ public static boolean isAnyType(Schema schema) { + // $ref is not a type, it is a keyword + // TODO remove the ref check here, or pass in the spec version + // openapi 3.1.0 specs allow ref to be adjacent to any keyword + // openapi 3.0.3 and earlier do not allow adjacent keywords to refs return (schema.get$ref() == null && schema.getType() == null); } @@ -1678,6 +1677,7 @@ public class ModelUtils { if (minItems != null) target.setMinItems(minItems); if (maxItems != null) target.setMaxItems(maxItems); if (uniqueItems != null) target.setUniqueItems(uniqueItems); + if (uniqueItems != null) target.setUniqueItemsBoolean(uniqueItems); } private static void setObjectValidations(Integer minProperties, Integer maxProperties, IJsonSchemaValidationProperties target) { @@ -1713,7 +1713,7 @@ public class ModelUtils { private static ObjectMapper getRightMapper(String data) { ObjectMapper mapper; - if(data.trim().startsWith("{")) { + if (data.trim().startsWith("{")) { mapper = JSON_MAPPER; } else { mapper = YAML_MAPPER; @@ -1733,7 +1733,7 @@ public class ModelUtils { */ public static JsonNode readWithInfo(String location, List auths) throws Exception { String data; - location = location.replaceAll("\\\\","/"); + location = location.replaceAll("\\\\", "/"); if (location.toLowerCase(Locale.ROOT).startsWith("http")) { data = RemoteUrl.urlToString(location, auths); } else { diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache index e632773ee2..1df70b4839 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache @@ -781,45 +781,49 @@ fail: {{^required}}if ({{{name}}}) { {{/required}} {{#isPrimitiveType}} cJSON *{{{name}}}_local_map = NULL; - if(!cJSON_IsObject({{{name}}})) { + if(!cJSON_IsObject({{{name}}}) && !cJSON_IsNull({{{name}}})) + { goto end;//primitive map container } - {{{name}}}List = list_createList(); - keyValuePair_t *localMapKeyPair; - cJSON_ArrayForEach({{{name}}}_local_map, {{{name}}}) + if(cJSON_IsObject({{{name}}})) { - cJSON *localMapObject = {{{name}}}_local_map; - {{#items}} - {{#isString}} - if(!cJSON_IsString(localMapObject)) + {{{name}}}List = list_createList(); + keyValuePair_t *localMapKeyPair; + cJSON_ArrayForEach({{{name}}}_local_map, {{{name}}}) { - goto end; + cJSON *localMapObject = {{{name}}}_local_map; + {{#items}} + {{#isString}} + if(!cJSON_IsString(localMapObject)) + { + goto end; + } + localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),strdup(localMapObject->valuestring)); + {{/isString}} + {{#isByteArray}} + if(!cJSON_IsString(localMapObject)) + { + goto end; + } + localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),strdup(localMapObject->valuestring)); + {{/isByteArray}} + {{#isBoolean}} + if(!cJSON_IsBool(localMapObject)) + { + goto end; + } + localMapKeyPair = keyValuePair_create(strdup(localMapObject->string), &localMapObject->valueint); + {{/isBoolean}} + {{#isNumeric}} + if(!cJSON_IsNumber(localMapObject)) + { + goto end; + } + localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),&localMapObject->valuedouble ); + {{/isNumeric}} + {{/items}} + list_addElement({{{name}}}List , localMapKeyPair); } - localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),strdup(localMapObject->valuestring)); - {{/isString}} - {{#isByteArray}} - if(!cJSON_IsString(localMapObject)) - { - goto end; - } - localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),strdup(localMapObject->valuestring)); - {{/isByteArray}} - {{#isBoolean}} - if(!cJSON_IsBool(localMapObject)) - { - goto end; - } - localMapKeyPair = keyValuePair_create(strdup(localMapObject->string), &localMapObject->valueint); - {{/isBoolean}} - {{#isNumeric}} - if(!cJSON_IsNumber(localMapObject)) - { - goto end; - } - localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),&localMapObject->valuedouble ); - {{/isNumeric}} - {{/items}} - list_addElement({{{name}}}List , localMapKeyPair); } {{/isPrimitiveType}} {{^isPrimitiveType}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/ApiClient.mustache index 2162321690..7e4d2181f5 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/ApiClient.mustache @@ -57,6 +57,7 @@ import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.nio.file.Paths; @@ -752,7 +753,14 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } else if (value instanceof byte[]) { multiPartBuilder.addBinaryBody(paramEntry.getKey(), (byte[]) value); } else { - multiPartBuilder.addTextBody(paramEntry.getKey(), parameterToString(paramEntry.getValue())); + Charset charset = contentType.getCharset(); + if (charset != null) { + ContentType customContentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset); + multiPartBuilder.addTextBody(paramEntry.getKey(), parameterToString(paramEntry.getValue()), + customContentType); + } else { + multiPartBuilder.addTextBody(paramEntry.getKey(), parameterToString(paramEntry.getValue())); + } } } return multiPartBuilder.build(); @@ -761,11 +769,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { for (Entry paramEntry : formParams.entrySet()) { formValues.add(new BasicNameValuePair(paramEntry.getKey(), parameterToString(paramEntry.getValue()))); } - try { - return new UrlEncodedFormEntity(formValues); - } catch (UnsupportedEncodingException e) { - throw new ApiException(e); - } + return new UrlEncodedFormEntity(formValues, contentType.getCharset()); } else { // Handle files with unknown content type if (obj instanceof File) { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/auth/OAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/auth/OAuth.mustache index 7b54e9b8ae..5416da238c 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/auth/OAuth.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/auth/OAuth.mustache @@ -77,7 +77,7 @@ public abstract class OAuth implements RequestInterceptor { public synchronized String getAccessToken() { // If first time, get the token - if (expirationTimeSeconds == null || System.currentTimeMillis() >= expirationTimeSeconds) { + if (expirationTimeSeconds == null || System.currentTimeMillis() >= expirationTimeSeconds * MILLIS_PER_SECOND) { updateAccessToken(); } return accessToken; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/api.mustache index e6fccb9a3a..756f0c129a 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/api.mustache @@ -173,7 +173,7 @@ public class {{classname}} { public class API{{operationId}}Request { {{#allParams}} - private {{#isRequired}}final {{/isRequired}}{{{dataType}}} {{paramName}}; + private {{{dataType}}} {{paramName}}; {{/allParams}} private API{{operationId}}Request({{#pathParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/pathParams}}) { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/api.mustache index 16cd006886..4ba6a6e955 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/api.mustache @@ -173,7 +173,7 @@ public class {{classname}} { public class API{{operationId}}Request { {{#allParams}} - private {{#isRequired}}final {{/isRequired}}{{{dataType}}} {{paramName}}; + private {{{dataType}}} {{paramName}}; {{/allParams}} private API{{operationId}}Request({{#pathParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/pathParams}}) { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/AbstractOpenApiSchema.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/AbstractOpenApiSchema.mustache index 19bf0a6347..d3b4281597 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/AbstractOpenApiSchema.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/AbstractOpenApiSchema.mustache @@ -2,7 +2,6 @@ package {{modelPackage}}; -import {{invokerPackage}}.ApiException; import java.util.Objects; import java.lang.reflect.Type; import java.util.Map; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/build.gradle.mustache index abeb66295a..6bfd3f6fed 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/build.gradle.mustache @@ -63,7 +63,7 @@ artifacts { ext { swagger_annotations_version = "1.5.22" - jackson_version = "2.13.0" + jackson_version = "2.13.4" jakarta_annotation_version = "1.3.5" junit_version = "4.13.2" } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/pom.mustache index 2b7635be35..af79371467 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/pom.mustache @@ -221,7 +221,7 @@ 1.5.22 11 11 - 2.13.0 + 2.13.4 0.2.3 1.3.5 4.13.2 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 9b1812a955..67dcd41e64 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -1084,6 +1084,8 @@ public class ApiClient { content = null; } return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create(MediaType.parse(contentType), (String) obj); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache index 248211a3c1..b2d6a19420 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache @@ -105,10 +105,22 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{/vendorExtensions.x-is-jackson-optional-nullable}} {{/vars}} - public {{classname}}() { {{#parent}}{{#parcelableModel}} - super();{{/parcelableModel}}{{/parent}}{{#gson}}{{#discriminator}} - this.{{{discriminatorName}}} = this.getClass().getSimpleName();{{/discriminator}}{{/gson}} - }{{#vendorExtensions.x-has-readonly-properties}}{{^withXml}} + public {{classname}}() { + {{#parent}} + {{#parcelableModel}} + super(); + {{/parcelableModel}} + {{/parent}} + {{#gson}} + {{#discriminator}} + {{^discriminator.isEnum}} + this.{{{discriminatorName}}} = this.getClass().getSimpleName(); + {{/discriminator.isEnum}} + {{/discriminator}} + {{/gson}} + } + {{#vendorExtensions.x-has-readonly-properties}} + {{^withXml}} {{#jsonb}}@JsonbCreator{{/jsonb}}{{#jackson}}@JsonCreator{{/jackson}} public {{classname}}( @@ -120,7 +132,9 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{#readOnlyVars}} this.{{name}} = {{name}}; {{/readOnlyVars}} - }{{/withXml}}{{/vendorExtensions.x-has-readonly-properties}} + } + {{/withXml}} + {{/vendorExtensions.x-has-readonly-properties}} {{#vars}} {{^isReadOnly}} @@ -422,9 +436,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if ({{classname}}.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!{{classname}}.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in {{{classname}}} is not found in the empty JSON string", {{classname}}.openapiRequiredFields.toString())); } } @@ -455,56 +467,59 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{#vars}} {{#isArray}} {{#items.isModel}} - JsonArray jsonArray{{name}} = jsonObj.getAsJsonArray("{{{baseName}}}"); - {{#isRequired}} + {{#required}} // ensure the json data is an array if (!jsonObj.get("{{{baseName}}}").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); } + JsonArray jsonArray{{name}} = jsonObj.getAsJsonArray("{{{baseName}}}"); // validate the required field `{{{baseName}}}` (array) for (int i = 0; i < jsonArray{{name}}.size(); i++) { {{{items.dataType}}}.validateJsonObject(jsonArray{{name}}.get(i).getAsJsonObject()); }; - {{/isRequired}} - {{^isRequired}} - if (jsonArray{{name}} != null) { - // ensure the json data is an array - if (!jsonObj.get("{{{baseName}}}").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); - } + {{/required}} + {{^required}} + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + JsonArray jsonArray{{name}} = jsonObj.getAsJsonArray("{{{baseName}}}"); + if (jsonArray{{name}} != null) { + // ensure the json data is an array + if (!jsonObj.get("{{{baseName}}}").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); + } - // validate the optional field `{{{baseName}}}` (array) - for (int i = 0; i < jsonArray{{name}}.size(); i++) { - {{{items.dataType}}}.validateJsonObject(jsonArray{{name}}.get(i).getAsJsonObject()); - }; + // validate the optional field `{{{baseName}}}` (array) + for (int i = 0; i < jsonArray{{name}}.size(); i++) { + {{{items.dataType}}}.validateJsonObject(jsonArray{{name}}.get(i).getAsJsonObject()); + }; + } } - {{/isRequired}} + {{/required}} {{/items.isModel}} {{^items.isModel}} // ensure the json data is an array - if ({{^isRequired}}jsonObj.get("{{{baseName}}}") != null && {{/isRequired}}!jsonObj.get("{{{baseName}}}").isJsonArray()) { + if ({{#required}}(jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) && {{/required}}!jsonObj.get("{{{baseName}}}").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); } {{/items.isModel}} {{/isArray}} {{^isContainer}} {{#isString}} - if ({{^isRequired}}jsonObj.get("{{{baseName}}}") != null && {{/isRequired}}!jsonObj.get("{{{baseName}}}").isJsonPrimitive()) { + if ({{^required}}(jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) && {{/required}}!jsonObj.get("{{{baseName}}}").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be a primitive type in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); } {{/isString}} {{#isModel}} - {{#isRequired}} + {{#required}} // validate the required field `{{{baseName}}}` {{{dataType}}}.validateJsonObject(jsonObj.getAsJsonObject("{{{baseName}}}")); - {{/isRequired}} - {{^isRequired}} + {{/required}} + {{^required}} // validate the optional field `{{{baseName}}}` - if (jsonObj.getAsJsonObject("{{{baseName}}}") != null) { + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { {{{dataType}}}.validateJsonObject(jsonObj.getAsJsonObject("{{{baseName}}}")); } - {{/isRequired}} + {{/required}} {{/isModel}} {{/isContainer}} {{/vars}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache index 441e5036ea..fe7575723d 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache @@ -672,6 +672,38 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { Entity entity = serialize(body, formParams, contentType); + try (Response response = invoke(invocationBuilder, method, entity)) { + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = buildResponseHeaders(response); + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), + message, + buildResponseHeaders(response), + respBody); + } + } + } + + private Response invoke(Invocation.Builder invocationBuilder, String method, Entity entity) throws ApiException { Response response = null; if ("GET".equals(method)) { @@ -694,36 +726,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { throw new ApiException(500, "unknown method type " + method); } - statusCode = response.getStatusInfo().getStatusCode(); - responseHeaders = buildResponseHeaders(response); - - if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { - return null; - } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { - if (returnType == null) - return null; - else - return deserialize(response, returnType); - } else { - String message = "error"; - String respBody = null; - if (response.hasEntity()) { - try { - respBody = String.valueOf(response.readEntity(String.class)); - message = respBody; - } catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatus(), - message, - buildResponseHeaders(response), - respBody); - } + return response; } - /** + /** * Build the Client used to make HTTP requests. */ private Client buildHttpClient(boolean debugging) { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache index 16507d2f22..12f66fe085 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache @@ -239,6 +239,11 @@ jackson-dataformat-xml ${jackson-version} + + io.github.threeten-jaxb + threeten-jaxb-core + 1.2 + {{/withXml}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache index 234288394a..f2e8a1b2c8 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache @@ -74,7 +74,7 @@ public class {{classname}} { {{#isDeprecated}} @Deprecated {{/isDeprecated}} - public {{#returnType}}{{{.}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.Resource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws RestClientException { + public {{#returnType}}{{#isResponseFile}}{{#useAbstractionForFiles}}org.springframework.core.io.Resource{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{.}}}{{/useAbstractionForFiles}}{{/isResponseFile}}{{^isResponseFile}}{{{.}}}{{/isResponseFile}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.Resource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws RestClientException { {{#returnType}} return {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).getBody(); {{/returnType}} @@ -105,7 +105,7 @@ public class {{classname}} { {{#isDeprecated}} @Deprecated {{/isDeprecated}} - public ResponseEntity<{{{returnType}}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.Resource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws RestClientException { + public ResponseEntity<{{#returnType}}{{#isResponseFile}}{{#useAbstractionForFiles}}org.springframework.core.io.Resource{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{.}}}{{/useAbstractionForFiles}}{{/isResponseFile}}{{^isResponseFile}}{{{.}}}{{/isResponseFile}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.Resource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws RestClientException { Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set @@ -148,7 +148,7 @@ public class {{classname}} { String[] localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}} }; - {{#returnType}}ParameterizedTypeReference<{{{returnType}}}> localReturnType = new ParameterizedTypeReference<{{{returnType}}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {};{{/returnType}} + {{#returnType}}ParameterizedTypeReference<{{#returnType}}{{#isResponseFile}}{{#useAbstractionForFiles}}org.springframework.core.io.Resource{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{.}}}{{/useAbstractionForFiles}}{{/isResponseFile}}{{^isResponseFile}}{{{.}}}{{/isResponseFile}}{{/returnType}}> localReturnType = new ParameterizedTypeReference<{{#returnType}}{{#isResponseFile}}{{#useAbstractionForFiles}}org.springframework.core.io.Resource{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{.}}}{{/useAbstractionForFiles}}{{/isResponseFile}}{{^isResponseFile}}{{{.}}}{{/isResponseFile}}{{/returnType}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {};{{/returnType}} return apiClient.invokeAPI("{{{path}}}", HttpMethod.{{httpMethod}}, {{#hasPathParams}}uriVariables{{/hasPathParams}}{{^hasPathParams}}Collections.emptyMap(){{/hasPathParams}}, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); } {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache index 856ff8ded7..223bc90517 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/pom.mustache @@ -258,30 +258,34 @@ {{#withXml}} - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson-version} - - + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson-version} + + + io.github.threeten-jaxb + threeten-jaxb-core + 1.2 + {{/withXml}} - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson-version} - + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + {{#joda}} - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} - - - joda-time - joda-time - ${jodatime-version} - + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + joda-time + joda-time + ${jodatime-version} + {{/joda}} jakarta.annotation @@ -302,8 +306,8 @@ UTF-8 1.5.22 5.3.18 - 2.10.5 - 2.11.4 + 2.12.7 + 2.12.7 0.2.3 1.3.5 {{#joda}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache index 7b0922700e..974f306340 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache @@ -152,10 +152,39 @@ public class {{classname}} { {{^returnType}}{{^vendorExtensions.x-webclient-blocking}}return {{/vendorExtensions.x-webclient-blocking}}{{/returnType}}{{#returnType}}return {{/returnType}}{{operationId}}RequestCreation({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).{{#isArray}}bodyToFlux{{/isArray}}{{^isArray}}bodyToMono{{/isArray}}(localVarReturnType){{#vendorExtensions.x-webclient-blocking}}{{#isArray}}{{#uniqueItems}}.collect(Collectors.toSet()){{/uniqueItems}}{{^uniqueItems}}.collectList(){{/uniqueItems}}{{/isArray}}.block(){{/vendorExtensions.x-webclient-blocking}}; } + /** + * {{summary}} + * {{notes}} +{{#responses}} *

        {{code}}{{#message}} - {{.}}{{/message}} +{{/responses}}{{#allParams}} * @param {{paramName}} {{description}}{{^description}}The {{paramName}} parameter{{/description}} +{{/allParams}}{{#returnType}} * @return ResponseEntity<{{.}}> +{{/returnType}} * @throws WebClientResponseException if an error occurs while attempting to invoke the API +{{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation +{{/externalDocs}} + */ public {{#vendorExtensions.x-webclient-blocking}}{{#returnType}}{{#isArray}}ResponseEntity>{{/isArray}}{{^isArray}}ResponseEntity<{{{returnType}}}>{{/isArray}}{{/returnType}}{{^returnType}}ResponseEntity{{/returnType}} {{/vendorExtensions.x-webclient-blocking}}{{^vendorExtensions.x-webclient-blocking}}{{#returnType}}{{#isArray}}Mono>>{{/isArray}}{{^isArray}}Mono>{{/isArray}}{{/returnType}}{{^returnType}}Mono>{{/returnType}} {{/vendorExtensions.x-webclient-blocking}}{{operationId}}WithHttpInfo({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException { {{#returnType}}ParameterizedTypeReference<{{#isArray}}{{{returnBaseType}}}{{/isArray}}{{^isArray}}{{{returnType}}}{{/isArray}}> localVarReturnType = new ParameterizedTypeReference<{{#isArray}}{{{returnBaseType}}}{{/isArray}}{{^isArray}}{{{returnType}}}{{/isArray}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {};{{/returnType}} return {{operationId}}RequestCreation({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).{{#isArray}}toEntityList{{/isArray}}{{^isArray}}toEntity{{/isArray}}(localVarReturnType){{#vendorExtensions.x-webclient-blocking}}.block(){{/vendorExtensions.x-webclient-blocking}}; } + + /** + * {{summary}} + * {{notes}} +{{#responses}} *

        {{code}}{{#message}} - {{.}}{{/message}} +{{/responses}}{{#allParams}} * @param {{paramName}} {{description}}{{^description}}The {{paramName}} parameter{{/description}} +{{/allParams}} + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API +{{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation +{{/externalDocs}} + */ + public ResponseSpec {{operationId}}WithResponseSpec({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException { + return {{operationId}}RequestCreation({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + } {{/operation}} } {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/build.gradle.mustache index 25b4865735..27d2cd43e7 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/build.gradle.mustache @@ -114,8 +114,8 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.6.3" spring_boot_version = "2.6.6" - jackson_version = "2.11.4" - jackson_databind_version = "2.11.4" + jackson_version = "2.12.7" + jackson_databind_version = "2.12.7" {{#openApiNullable}} jackson_databind_nullable_version = "0.2.3" {{/openApiNullable}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/pom.mustache index e64caffb31..660e76a1d4 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/pom.mustache @@ -148,8 +148,8 @@ UTF-8 1.6.3 2.6.6 - 2.11.3 - 2.11.4 + 2.12.7 + 2.12.7 {{#openApiNullable}} 0.2.3 {{/openApiNullable}} diff --git a/modules/openapi-generator/src/main/resources/Java/model.mustache b/modules/openapi-generator/src/main/resources/Java/model.mustache index 0c4d165f64..df2051798c 100644 --- a/modules/openapi-generator/src/main/resources/Java/model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/model.mustache @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonCreator; {{/jackson}} {{#withXml}} import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; {{/withXml}} {{#jsonb}} import java.lang.reflect.Type; diff --git a/modules/openapi-generator/src/main/resources/Java/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/pojo.mustache index 84ea11480c..5972ac9f29 100644 --- a/modules/openapi-generator/src/main/resources/Java/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/pojo.mustache @@ -59,6 +59,9 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens @XmlElementWrapper({{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}name = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") {{/isXmlWrapped}} {{/isContainer}} + {{#isDateTime}} + @XmlJavaTypeAdapter(OffsetDateTimeXmlAdapter.class) + {{/isDateTime}} {{/isXmlAttribute}} {{/withXml}} {{#gson}} @@ -85,10 +88,21 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{/vendorExtensions.x-is-jackson-optional-nullable}} {{/vars}} - public {{classname}}() { {{#parent}}{{#parcelableModel}} - super();{{/parcelableModel}}{{/parent}}{{#gson}}{{#discriminator}} - this.{{{discriminatorName}}} = this.getClass().getSimpleName();{{/discriminator}}{{/gson}} - }{{#vendorExtensions.x-has-readonly-properties}}{{^withXml}} + public {{classname}}() { + {{#parent}} + {{#parcelableModel}} + super();{{/parcelableModel}} + {{/parent}} + {{#gson}} + {{#discriminator}} + {{#discriminator.isEnum}} + this.{{{discriminatorName}}} = this.getClass().getSimpleName(); + {{/discriminator.isEnum}} + {{/discriminator}} + {{/gson}} + } + {{#vendorExtensions.x-has-readonly-properties}} + {{^withXml}} {{#jsonb}}@JsonbCreator{{/jsonb}}{{#jackson}}@JsonCreator{{/jackson}} public {{classname}}( @@ -100,7 +114,9 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{#readOnlyVars}} this.{{name}} = {{#vendorExtensions.x-is-jackson-optional-nullable}}{{name}} == null ? JsonNullable.<{{{datatypeWithEnum}}}>undefined() : JsonNullable.of({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{name}}{{/vendorExtensions.x-is-jackson-optional-nullable}}; {{/readOnlyVars}} - }{{/withXml}}{{/vendorExtensions.x-has-readonly-properties}} + } + {{/withXml}} + {{/vendorExtensions.x-has-readonly-properties}} {{#vars}} {{^isReadOnly}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/RestApplication.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/RestApplication.mustache index 3dd570e9c3..56618f1541 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/RestApplication.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/RestApplication.mustache @@ -3,7 +3,7 @@ package {{invokerPackage}}; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; -@ApplicationPath("{{{contextPath}}}") +@ApplicationPath(RestResourceRoot.APPLICATION_PATH) public class RestApplication extends Application { } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/RestResourceRoot.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/RestResourceRoot.mustache new file mode 100644 index 0000000000..669fc2b4f9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/RestResourceRoot.mustache @@ -0,0 +1,5 @@ +package {{invokerPackage}}; + +public class RestResourceRoot { + public static final String APPLICATION_PATH = "{{{contextPath}}}"; +} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache index f83dd80a62..071a73e0c0 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache @@ -17,24 +17,46 @@ import com.fasterxml.jackson.annotation.JsonTypeName; {{{vendorExtensions.x-class-extra-annotation}}} {{/vendorExtensions.x-class-extra-annotation}} public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { - {{#vars}}{{#isEnum}}{{^isContainer}} - -{{>enumClass}}{{/isContainer}}{{#isContainer}}{{#mostInnerItems}} - -{{>enumClass}}{{/mostInnerItems}}{{/isContainer}}{{/isEnum}} + {{#vars}} + {{#isEnum}} + {{^isContainer}} + {{>enumClass}} + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} + {{>enumClass}} + {{/mostInnerItems}} + {{/isContainer}} + {{/isEnum}} {{#vendorExtensions.x-field-extra-annotation}} {{{vendorExtensions.x-field-extra-annotation}}} {{/vendorExtensions.x-field-extra-annotation}} - private {{#useBeanValidation}}@Valid {{/useBeanValidation}}{{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};{{/vars}}{{#generateBuilders}}{{^additionalProperties}} + {{#isContainer}} + private {{#useBeanValidation}}@Valid {{/useBeanValidation}}{{{datatypeWithEnum}}} {{name}}{{#required}}{{^isNullable}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/isNullable}}{{#isNullable}} = null{{/isNullable}}{{/required}}{{^required}} = null{{/required}}; + {{/isContainer}} + {{^isContainer}} + private {{#useBeanValidation}}@Valid {{/useBeanValidation}}{{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{/isContainer}} + {{/vars}} + {{#generateBuilders}} + {{^additionalProperties}} protected {{classname}}({{classname}}Builder b) { - {{#parent}}super(b); - {{/parent}}{{#vars}}this.{{name}} = b.{{name}};{{/vars}} + {{#parent}} + super(b); + {{/parent}} + {{#vars}} + this.{{name}} = b.{{name}}; + {{/vars}} } - public {{classname}}() { }{{/additionalProperties}}{{/generateBuilders}} + public {{classname}}() { + } + {{/additionalProperties}} + {{/generateBuilders}} - {{#vars}}/** + {{#vars}} + /** {{#description}} * {{.}} {{/description}} diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache index 0b9c2bb4de..cf48c4834a 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache @@ -96,6 +96,11 @@ import javax.annotation.Generated; {{#virtualService}} @VirtualService {{/virtualService}} +{{^useFeignClient}} +{{=<% %>=}} +@RequestMapping("${openapi.<%title%>.base-path:<%>defaultBasePath%>}") +<%={{ }}=%> +{{/useFeignClient}} public interface {{classname}} { {{#jdk8-default-interface}} {{^isDelegate}} @@ -204,14 +209,15 @@ public interface {{classname}} { {{#implicitHeadersParams}} {{>paramDoc}}{{^-last}},{{/-last}} {{/implicitHeadersParams}} + }) {{/swagger2AnnotationLibrary}} {{#swagger1AnnotationLibrary}} @ApiImplicitParams({ {{#implicitHeadersParams}} {{>implicitHeader}}{{^-last}},{{/-last}} {{/implicitHeadersParams}} - {{/swagger1AnnotationLibrary}} }) + {{/swagger1AnnotationLibrary}} {{/implicitHeadersParams.0}} @RequestMapping( method = RequestMethod.{{httpMethod}}, diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/apiController.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/apiController.mustache index aa091238bc..85589bb7b6 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/apiController.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/apiController.mustache @@ -58,9 +58,6 @@ import javax.annotation.Generated; {{>generatedAnnotation}} @Controller -{{=<% %>=}} -@RequestMapping("${openapi.<%title%>.base-path:<%>defaultBasePath%>}") -<%={{ }}=%> {{#operations}} public class {{classname}}Controller implements {{classname}} { {{#isDelegate}} diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/defaultBasePath.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/defaultBasePath.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/defaultBasePath.mustache rename to modules/openapi-generator/src/main/resources/JavaSpring/defaultBasePath.mustache diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/headerParams.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/headerParams.mustache index b5ff71e038..b9589c1477 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/headerParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}{{>paramDoc}} @RequestHeader(value = "{{baseName}}", required = {{#required}}true{{/required}}{{^required}}false{{/required}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{>dateTimeParam}} {{>optionalDataType}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{>paramDoc}} @RequestHeader(value = "{{baseName}}", required = {{#required}}true{{/required}}{{^required}}false{{/required}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{>dateTimeParam}} {{>optionalDataType}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache index adc5145d08..f00a6c3b6f 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/apiClient.mustache @@ -3,6 +3,8 @@ package {{package}}; import org.springframework.cloud.openfeign.FeignClient; import {{configPackage}}.ClientConfiguration; -@FeignClient(name="${{openbrace}}{{classVarName}}.name:{{classVarName}}{{closebrace}}", {{#useFeignClientUrl}}url="${{openbrace}}{{classVarName}}.url:{{basePath}}{{closebrace}}", {{/useFeignClientUrl}}configuration = ClientConfiguration.class) +{{=<% %>=}} +@FeignClient(name="${<%classVarName%>.name:<%classVarName%>}", url="${<%classVarName%>.url:<%basePath%>}", configuration = ClientConfiguration.class) +<%={{ }}=%> public interface {{classname}}Client extends {{classname}} { } diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/pom-sb3.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/pom-sb3.mustache index f61faca014..f03e991483 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/pom-sb3.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/pom-sb3.mustache @@ -30,7 +30,7 @@ org.springframework.boot spring-boot-starter-parent - 3.0.0-M3 + 3.0.0-M4 {{/parentOverridden}} @@ -53,7 +53,7 @@ org.springframework.cloud spring-cloud-starter-parent - 2022.0.0-M2 + 2022.0.0-M3 pom import diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache index 6305be42a1..e5f9c6136c 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache @@ -146,6 +146,9 @@ public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{^parent}} {{#useBeanValidation}} {{>beanValidation}} {{/useBeanValidation}} + {{^useBeanValidation}} + {{#required}}@NotNull{{/required}} + {{/useBeanValidation}} {{#swagger2AnnotationLibrary}} @Schema(name = "{{{baseName}}}", {{#isReadOnly}}accessMode = Schema.AccessMode.READ_ONLY, {{/isReadOnly}}{{#example}}example = "{{{.}}}", {{/example}}{{#description}}description = "{{{.}}}", {{/description}}required = {{{required}}}) {{/swagger2AnnotationLibrary}} diff --git a/modules/openapi-generator/src/main/resources/JavaVertXWebServer/supportFiles/pom.mustache b/modules/openapi-generator/src/main/resources/JavaVertXWebServer/supportFiles/pom.mustache index 0d7bb4c6f0..f1c266b5dc 100644 --- a/modules/openapi-generator/src/main/resources/JavaVertXWebServer/supportFiles/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaVertXWebServer/supportFiles/pom.mustache @@ -20,7 +20,7 @@ 4.2.4 5.7.0 1.7.30 - 2.11.2 + 2.12.7 {{invokerPackage}}.HttpServerVerticle diff --git a/modules/openapi-generator/src/main/resources/Javascript-Apollo/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Javascript-Apollo/ApiClient.mustache index 8914ecf5e4..44d7eb3ded 100644 --- a/modules/openapi-generator/src/main/resources/Javascript-Apollo/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript-Apollo/ApiClient.mustache @@ -1,6 +1,6 @@ {{>licenseInfo}} -import RESTDataSource from 'apollo-datasource-rest'; +import { RESTDataSource } from 'apollo-datasource-rest'; {{#emitJSDoc}}/** * @module {{#invokerPackage}}{{.}}/{{/invokerPackage}}ApiClient @@ -14,9 +14,16 @@ import RESTDataSource from 'apollo-datasource-rest'; * @class */{{/emitJSDoc}} export default class ApiClient extends RESTDataSource { - constructor() { + constructor(baseURL = '{{{basePath}}}') { super() + {{#emitJSDoc}}/** + * The base URL against which to resolve every API call's (relative) path. + * @type {String} + * @default {{{basePath}}} + */{{/emitJSDoc}} + this.baseURL = baseURL.replace(/\/+$/, ''); + {{#emitJSDoc}}/** * The authentication methods to be included for all API calls. * @type {Array.} @@ -53,7 +60,7 @@ export default class ApiClient extends RESTDataSource { } parametrizePath(path, pathParams) { - return url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { + return path.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { var value; if (pathParams.hasOwnProperty(key)) { value = this.paramToString(pathParams[key]); @@ -176,7 +183,7 @@ export default class ApiClient extends RESTDataSource { async callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, - returnType) { + contentTypes, accepts, returnType, requestInit) { var parameterizedPath = this.parametrizePath(path, pathParams); var fetchOptions = { @@ -203,9 +210,9 @@ export default class ApiClient extends RESTDataSource { var httpMethodFn = httpMethod.toLowerCase(); if (httpMethodFn == 'get' || httpMethodFn == 'delete') { - response = await this[httpMethodFn](parameterizedPath, fetchOptions); + response = await this[httpMethodFn](parameterizedPath, [], requestInit); } else { - response = await this[httpMethodFn](parameterizedPath, body, fetchOptions) + response = await this[httpMethodFn](parameterizedPath, body, requestInit) } var convertedResponse = ApiClient.convertToType(response, returnType); @@ -234,7 +241,7 @@ export default class ApiClient extends RESTDataSource { case 'Blob': return data; default: - if (type === Object) { + if (typeof type === "object") { // generic object, return directly return data; } else if (typeof type.constructFromObject === 'function') { diff --git a/modules/openapi-generator/src/main/resources/Javascript-Apollo/api.mustache b/modules/openapi-generator/src/main/resources/Javascript-Apollo/api.mustache index 63cb101aad..82ab5f8c99 100644 --- a/modules/openapi-generator/src/main/resources/Javascript-Apollo/api.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript-Apollo/api.mustache @@ -19,9 +19,8 @@ export default class <&classname> extends ApiClient { * @alias module:<#invokerPackage><&invokerPackage>/<#apiPackage><&apiPackage>/ * @class */ - constructor() { - super(); - this.baseURL = <#servers.0>basePath<^servers.0>null; + constructor(baseURL = '<&basePath>') { + super(baseURL); } <#operations><#operation><#emitJSDoc> @@ -31,6 +30,7 @@ export default class <&classname> extends ApiClient { * @param {<&vendorExtensions.x-jsdoc-type>} <¶mName> <&description><#hasOptionalParams> * @param {Object} opts Optional parameters<#allParams><^required> * @param {<&vendorExtensions.x-jsdoc-type>} opts.<¶mName> <&description><#defaultValue> (default to <&.>) + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} <=| |=>* @return {Promise|#returnType|<|&vendorExtensions.x-jsdoc-type|>|/returnType|}|=< >=| */ async () { @@ -80,7 +80,7 @@ export default class <&classname> extends ApiClient { return this.callApi( '<&path>', '', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } diff --git a/modules/openapi-generator/src/main/resources/Javascript-Apollo/api_test.mustache b/modules/openapi-generator/src/main/resources/Javascript-Apollo/api_test.mustache index f04f1bc3cc..ec22d00bef 100644 --- a/modules/openapi-generator/src/main/resources/Javascript-Apollo/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript-Apollo/api_test.mustache @@ -1,32 +1,38 @@ {{>licenseInfo}} -// CommonJS-like environments that support module.exports, like Node. -factory(require('expect.js'), require(process.cwd()+'/src/{{#invokerPackage}}{{.}}/{{/invokerPackage}}index')); +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/{{#invokerPackage}}{{.}}/{{/invokerPackage}}index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/{{#invokerPackage}}{{.}}/{{/invokerPackage}}index')); + } +}(this, function(expect, {{moduleName}}) { + 'use strict'; -'use strict'; + var instance; -var instance; + beforeEach(function() { + instance = new {{moduleName}}.{{classname}}(); + }); -beforeEach(function() { - instance = new {{moduleName}}.{{classname}}(); -}); + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } -var getProperty = function(object, getter, property) { - // Use getter method if present; otherwise, get the property directly. - if (typeof object[getter] === 'function') - return object[getter](); - else - return object[property]; -} + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } -var setProperty = function(object, setter, property, value) { - // Use setter method if present; otherwise, set the property directly. - if (typeof object[setter] === 'function') - object[setter](value); - else - object[property] = value; -} - -describe('{{classname}}', function() { + describe('{{classname}}', function() { {{#operations}} {{#operation}} describe('{{operationId}}', function() { @@ -41,4 +47,6 @@ describe('{{classname}}', function() { }); {{/operation}} {{/operations}} -}); \ No newline at end of file + }); + +})); diff --git a/modules/openapi-generator/src/main/resources/Javascript-Apollo/package.mustache b/modules/openapi-generator/src/main/resources/Javascript-Apollo/package.mustache index e6d3c75229..60e3876d46 100644 --- a/modules/openapi-generator/src/main/resources/Javascript-Apollo/package.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript-Apollo/package.mustache @@ -3,8 +3,10 @@ "version": "{{{projectVersion}}}", "description": "{{{projectDescription}}}", "license": "{{licenseName}}", - "main": "src/index.js", + "main": "dist{{#invokerPackage}}/{{.}}{{/invokerPackage}}/index.js", "scripts": { + "build": "babel src -d dist", + "prepare": "npm run build", "test": "mocha --require @babel/register --recursive" }, "browser": { @@ -16,14 +18,35 @@ }, {{/npmRepository}} "dependencies": { - "apollo-datasource-rest": "^0.7.0" + "@babel/cli": "^7.0.0", + "apollo-datasource-rest": "^3.6.1", + "superagent": "^5.3.0" }, "devDependencies": { + "@babel/core": "^7.0.0", + "@babel/plugin-proposal-class-properties": "^7.0.0", + "@babel/plugin-proposal-decorators": "^7.0.0", + "@babel/plugin-proposal-do-expressions": "^7.0.0", + "@babel/plugin-proposal-export-default-from": "^7.0.0", + "@babel/plugin-proposal-export-namespace-from": "^7.0.0", + "@babel/plugin-proposal-function-bind": "^7.0.0", + "@babel/plugin-proposal-function-sent": "^7.0.0", + "@babel/plugin-proposal-json-strings": "^7.0.0", + "@babel/plugin-proposal-logical-assignment-operators": "^7.0.0", + "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0", + "@babel/plugin-proposal-numeric-separator": "^7.0.0", + "@babel/plugin-proposal-optional-chaining": "^7.0.0", + "@babel/plugin-proposal-pipeline-operator": "^7.0.0", + "@babel/plugin-proposal-throw-expressions": "^7.0.0", + "@babel/plugin-syntax-dynamic-import": "^7.0.0", + "@babel/plugin-syntax-import-meta": "^7.0.0", + "@babel/preset-env": "^7.0.0", + "@babel/register": "^7.0.0", "expect.js": "^0.3.1", - "mocha": "^5.2.0", + "mocha": "^8.0.1", "sinon": "^7.2.0" }, "files": [ - "src" + "dist" ] } diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/.babelrc.mustache b/modules/openapi-generator/src/main/resources/Javascript/.babelrc.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/.babelrc.mustache rename to modules/openapi-generator/src/main/resources/Javascript/.babelrc.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/README.mustache b/modules/openapi-generator/src/main/resources/Javascript/README.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/README.mustache rename to modules/openapi-generator/src/main/resources/Javascript/README.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/api_doc.mustache b/modules/openapi-generator/src/main/resources/Javascript/api_doc.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/api_doc.mustache rename to modules/openapi-generator/src/main/resources/Javascript/api_doc.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/api_test.mustache b/modules/openapi-generator/src/main/resources/Javascript/api_test.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/api_test.mustache rename to modules/openapi-generator/src/main/resources/Javascript/api_test.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/enumClass.mustache b/modules/openapi-generator/src/main/resources/Javascript/enumClass.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/enumClass.mustache rename to modules/openapi-generator/src/main/resources/Javascript/enumClass.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/gitignore.mustache b/modules/openapi-generator/src/main/resources/Javascript/es6/gitignore.mustache deleted file mode 100644 index e920c16718..0000000000 --- a/modules/openapi-generator/src/main/resources/Javascript/es6/gitignore.mustache +++ /dev/null @@ -1,33 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* - -# Runtime data -pids -*.pid -*.seed - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directory -node_modules - -# Optional npm cache directory -.npm - -# Optional REPL history -.node_repl_history diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/model.mustache b/modules/openapi-generator/src/main/resources/Javascript/es6/model.mustache deleted file mode 100644 index 3ddf83730f..0000000000 --- a/modules/openapi-generator/src/main/resources/Javascript/es6/model.mustache +++ /dev/null @@ -1,4 +0,0 @@ -{{>licenseInfo}} -import ApiClient from '../ApiClient'; -{{#imports}}import {{import}} from './{{import}}'; -{{/imports}}{{#models}}{{#model}}{{#isEnum}}{{>partial_model_enum_class}}{{/isEnum}}{{^isEnum}}{{>partial_model_generic}}{{/isEnum}}{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/partial_model_generic.mustache b/modules/openapi-generator/src/main/resources/Javascript/es6/partial_model_generic.mustache deleted file mode 100644 index c367e4b820..0000000000 --- a/modules/openapi-generator/src/main/resources/Javascript/es6/partial_model_generic.mustache +++ /dev/null @@ -1,102 +0,0 @@ - -{{#models}}{{#model}}{{#emitJSDoc}}/** - * The {{classname}} model module. - * @module {{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{classname}} - * @version {{projectVersion}} - */{{/emitJSDoc}} -class {{classname}} {{#parent}}{{^parentModel}}{{#vendorExtensions.x-is-array}}extends Array {{/vendorExtensions.x-is-array}}{{/parentModel}}{{/parent}}{ - {{#emitJSDoc}}/** - * Constructs a new {{classname}}.{{#description}} - * {{.}}{{/description}} - * @alias module:{{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{classname}}{{#useInheritance}}{{#parent}} - * @extends {{#parentModel}}module:{{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{classname}}{{/parentModel}}{{^parentModel}}{{#vendorExtensions.x-is-array}}Array{{/vendorExtensions.x-is-array}}{{#vendorExtensions.x-is-map}}Object{{/vendorExtensions.x-is-map}}{{/parentModel}}{{/parent}}{{#interfaces}} - * @implements module:{{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{.}}{{/interfaces}}{{/useInheritance}}{{#vendorExtensions.x-all-required}} - * @param {{name}} {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{{description}}}{{/vendorExtensions.x-all-required}} - */{{/emitJSDoc}} - constructor({{#vendorExtensions.x-all-required}}{{name}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-all-required}}) { {{#parent}}{{^parentModel}}{{#vendorExtensions.x-is-array}} - super(); - {{/vendorExtensions.x-is-array}}{{/parentModel}}{{/parent}}{{#useInheritance}} - {{#interfaceModels}}{{classname}}.initialize(this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}});{{/interfaceModels}}{{/useInheritance}} - {{classname}}.initialize(this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}}); - } - - {{#emitJSDoc}}/** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */{{/emitJSDoc}} - static initialize(obj{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}}) { {{#vars}}{{#required}} - {{#defaultValue}}obj['{{baseName}}'] = {{name}} || {{{defaultValue}}};{{/defaultValue}}{{^defaultValue}}obj['{{baseName}}'] = {{name}};{{/defaultValue}}{{/required}}{{/vars}} - } - - {{#emitJSDoc}}/** - * Constructs a {{classname}} from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {{=< >=}}{module:<#invokerPackage>/<#modelPackage>/}<={{ }}=> obj Optional instance to populate. - * @return {{=< >=}}{module:<#invokerPackage>/<#modelPackage>/}<={{ }}=> The populated {{classname}} instance. - */{{/emitJSDoc}} - static constructFromObject(data, obj) { - if (data){{! TODO: support polymorphism: discriminator property on data determines class to instantiate.}} { - obj = obj || new {{classname}}();{{#parent}}{{^parentModel}} - - ApiClient.constructFromObject(data, obj, '{{vendorExtensions.x-item-type}}'); - {{/parentModel}}{{/parent}}{{#useInheritance}}{{#parentModel}} - {{classname}}.constructFromObject(data, obj);{{/parentModel}}{{#interfaces}} - {{.}}.constructFromObject(data, obj);{{/interfaces}}{{/useInheritance}} - - {{#vars}} - if (data.hasOwnProperty('{{baseName}}')) { - obj['{{baseName}}']{{{defaultValueWithParam}}} - } - {{/vars}} - } - return obj; - } - -{{#emitModelMethods}}{{#vars}}{{#emitJSDoc}}/**{{#description}} - * Returns {{{.}}}{{/description}}{{#minimum}} - * minimum: {{.}}{{/minimum}}{{#maximum}} - * maximum: {{.}}{{/maximum}} - * @return {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> - */{{/emitJSDoc}} - {{getter}}() { - return this.{{baseName}}; - } - - {{#emitJSDoc}}/**{{#description}} - * Sets {{{.}}}{{/description}} - * @param {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{name}}{{#description}} {{{.}}}{{/description}} - */{{/emitJSDoc}} - {{setter}}({{name}}) { - this['{{baseName}}'] = {{name}}; - } -{{/vars}}{{/emitModelMethods}}{{/model}} -} - -{{#vars}}{{#emitJSDoc}}/**{{#description}} - * {{{.}}}{{/description}} - * @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}{{#defaultValue}} - * @default {{{.}}}{{/defaultValue}} - */{{/emitJSDoc}} -{{classname}}.prototype['{{baseName}}'] = {{{defaultValue}}}{{^defaultValue}}undefined{{/defaultValue}}; - -{{/vars}} - -{{#useInheritance}}{{#interfaceModels}}// Implement {{classname}} interface: -{{#allVars}}{{#emitJSDoc}}/**{{#description}} - * {{{.}}}{{/description}} - * @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}{{#defaultValue}} - * @default {{{.}}}{{/defaultValue}} - */{{/emitJSDoc}} -{{classname}}.prototype['{{baseName}}'] = {{{defaultValue}}}{{^defaultValue}}undefined{{/defaultValue}}; -{{/allVars}}{{/interfaceModels}}{{/useInheritance}} - -{{#vars}}{{#isEnum}}{{^isContainer}} -{{>partial_model_inner_enum}} -{{/isContainer}}{{/isEnum}}{{#items.isEnum}}{{#items}}{{^isContainer}} -{{>partial_model_inner_enum}} -{{/isContainer}}{{/items}}{{/items.isEnum}}{{/vars}} - -export default {{classname}}; -{{/models}} diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/Javascript/git_push.sh.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/git_push.sh.mustache rename to modules/openapi-generator/src/main/resources/Javascript/git_push.sh.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/gitignore.mustache b/modules/openapi-generator/src/main/resources/Javascript/gitignore.mustache new file mode 100644 index 0000000000..6a7d6d8ef6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Javascript/gitignore.mustache @@ -0,0 +1,130 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp +.cache + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/index.mustache b/modules/openapi-generator/src/main/resources/Javascript/index.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/index.mustache rename to modules/openapi-generator/src/main/resources/Javascript/index.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/libraries/apollo/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Javascript/libraries/apollo/ApiClient.mustache new file mode 100644 index 0000000000..4f84ef57bd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Javascript/libraries/apollo/ApiClient.mustache @@ -0,0 +1,308 @@ +{{>licenseInfo}} + +import { RESTDataSource } from 'apollo-datasource-rest'; + +{{#emitJSDoc}}/** +* @module {{#invokerPackage}}{{.}}/{{/invokerPackage}}ApiClient +* @version {{projectVersion}} +*/ + +/** +* Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an +* application to use this class directly - the *Api and model classes provide the public API for the service. +* @alias module:{{#invokerPackage}}{{.}}/{{/invokerPackage}}ApiClient +* @class +*/{{/emitJSDoc}} +export default class ApiClient extends RESTDataSource { + constructor(baseURL = '{{{basePath}}}') { + super() + + {{#emitJSDoc}}/** + * The base URL against which to resolve every API call's (relative) path. + * @type {String} + * @default {{{basePath}}} + */{{/emitJSDoc}} + this.baseURL = baseURL.replace(/\/+$/, ''); + + {{#emitJSDoc}}/** + * The authentication methods to be included for all API calls. + * @type {Array.} + */{{/emitJSDoc}}{{=< >=}} + this.authentications = { +<#authMethods> +<#isBasic> +<#isBasicBasic> + '': {type: 'basic'}<^-last>, + +<#isBasicBearer> + '': {type: 'bearer'}<^-last>,<#bearerFormat> // <&.> + + +<#isApiKey> + '': {type: 'apiKey', 'in': <#isKeyInHeader>'header'<^isKeyInHeader>'query', name: ''}<^-last>, + +<#isOAuth> + '': {type: 'oauth2'}<^-last>, + + + } + } + + paramToString(param) { + if (param == undefined || param == null) { + return ''; + } + if (param instanceof Date) { + return param.toJSON(); + } + + return param.toString(); + } + + parametrizePath(path, pathParams) { + return path.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { + var value; + if (pathParams.hasOwnProperty(key)) { + value = this.paramToString(pathParams[key]); + } else { + value = fullMatch; + } + + return encodeURIComponent(value); + }); + } + + isFileParam(param) { + // fs.ReadStream in Node.js and Electron (but not in runtime like browserify) + if (typeof require === 'function') { + let fs; + try { + fs = require('fs'); + } catch (err) {} + if (fs && fs.ReadStream && param instanceof fs.ReadStream) { + return true; + } + } + + // Buffer in Node.js + if (typeof Buffer === 'function' && param instanceof Buffer) { + return true; + } + + // Blob in browser + if (typeof Blob === 'function' && param instanceof Blob) { + return true; + } + + // File in browser (it seems File object is also instance of Blob, but keep this for safe) + if (typeof File === 'function' && param instanceof File) { + return true; + } + + return false; + } + + normalizeParams(params) { + var newParams = {}; + for (var key in params) { + if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) { + var value = params[key]; + if (this.isFileParam(value) || Array.isArray(value)) { + newParams[key] = value; + } else { + newParams[key] = this.paramToString(value); + } + } + } + + return newParams; + } + + buildCollectionParam(param, collectionFormat) { + if (param == null) { + return null; + } + switch (collectionFormat) { + case 'csv': + return param.map(this.paramToString).join(','); + case 'ssv': + return param.map(this.paramToString).join(' '); + case 'tsv': + return param.map(this.paramToString).join('\t'); + case 'pipes': + return param.map(this.paramToString).join('|'); + case 'multi': + //return the array directly as SuperAgent will handle it as expected + return param.map(this.paramToString); + default: + throw new Error('Unknown collection format: ' + collectionFormat); + } + } + + applyAuthOptions(fetchOptions, authNames) { + fetchOptions.headers = fetchOptions.headers || {}; + + authNames.forEach((authName) => { + var auth = this.authentications[authName]; + switch (auth.type) { + case 'basic': + if (auth.username || auth.password) { + fetchOptions.headers['Authorization'] = 'Basic ' + base64.encode(auth.username + ":" + auth.password); + } + + break; + case 'bearer': + case 'oauth2': + if (auth.accessToken) { + fetchOptions.headers['Authorization'] = 'Bearer ' + auth.accessToken; + } + + break; + case 'apiKey': + if (auth.apiKey) { + var data = {}; + if (auth.apiKeyPrefix) { + data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey; + } else { + data[auth.name] = auth.apiKey; + } + + if (auth['in'] === 'header') { + Object.assign(fetchOptions.headers, data); + } else { + Object.assign(fetchOptions.params, data); + } + } + + break; + default: + throw new Error('Unknown authentication type: ' + auth.type); + } + }); + } + + async callApi(path, httpMethod, pathParams, + queryParams, headerParams, formParams, bodyParam, authNames, + contentTypes, accepts, returnType, requestInit) { + + var normalizedQueryParams = this.normalizeParams(queryParams); + + var parameterizedPath = this.parametrizePath(path, pathParams); + var fetchOptions = { + headers: headerParams, + params: normalizedQueryParams + }; + + this.applyAuthOptions(fetchOptions, authNames); + + var body = null; + + if (bodyParam !== null && bodyParam !== undefined) { + body = bodyParam; + } else if (formParams !== null && formParams !== undefined) { + var _formParams = this.normalizeParams(formParams); + for (var key in _formParams) { + if (_formParams.hasOwnProperty(key)) { + body[key] = _formParams[key]; + } + } + } + + var response; + var httpMethodFn = httpMethod.toLowerCase(); + + if (httpMethodFn == 'get' || httpMethodFn == 'delete') { + response = await this[httpMethodFn](parameterizedPath, normalizedQueryParams, requestInit); + } else { + response = await this[httpMethodFn](parameterizedPath, body, requestInit) + } + + var convertedResponse = ApiClient.convertToType(response, returnType); + return convertedResponse; + } + + static parseDate(str) { + return new Date(str); + } + + static convertToType(data, type) { + if (data === null || data === undefined) + return data + + switch (type) { + case 'Boolean': + return Boolean(data); + case 'Integer': + return parseInt(data, 10); + case 'Number': + return parseFloat(data); + case 'String': + return String(data); + case 'Date': + return ApiClient.parseDate(String(data)); + case 'Blob': + return data; + default: + if (typeof type === "object") { + // generic object, return directly + return data; + } else if (typeof type.constructFromObject === 'function') { + // for model type like User and enum class + return type.constructFromObject(data); + } else if (Array.isArray(type)) { + // for array type like: ['String'] + var itemType = type[0]; + + return data.map((item) => { + return ApiClient.convertToType(item, itemType); + }); + } else if (typeof type === 'object') { + // for plain object type like: {'String': 'Integer'} + var keyType, valueType; + for (var k in type) { + if (type.hasOwnProperty(k)) { + keyType = k; + valueType = type[k]; + break; + } + } + + var result = {}; + for (var k in data) { + if (data.hasOwnProperty(k)) { + var key = ApiClient.convertToType(k, keyType); + var value = ApiClient.convertToType(data[k], valueType); + result[key] = value; + } + } + + return result; + } else { + // for unknown type, return the data directly + return data; + } + } + } + + static constructFromObject(data, obj, itemType) { + if (Array.isArray(data)) { + for (var i = 0; i < data.length; i++) { + if (data.hasOwnProperty(i)) + obj[i] = ApiClient.convertToType(data[i], itemType); + } + } else { + for (var k in data) { + if (data.hasOwnProperty(k)) + obj[k] = ApiClient.convertToType(data[k], itemType); + } + } + }; +} + +ApiClient.CollectionFormatEnum = { + CSV: ',', + SSV: ' ', + TSV: '\t', + PIPES: '|', + MULTI: 'multi' +}; diff --git a/modules/openapi-generator/src/main/resources/Javascript/libraries/apollo/api.mustache b/modules/openapi-generator/src/main/resources/Javascript/libraries/apollo/api.mustache new file mode 100644 index 0000000000..82ab5f8c99 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Javascript/libraries/apollo/api.mustache @@ -0,0 +1,89 @@ +{{>licenseInfo}} + +{{=< >=}} + +import ApiClient from "../ApiClient"; +<#imports>import <&import> from '../<#modelPackage><&modelPackage>/'; + + +<#emitJSDoc>/** +* service. +* @module <#invokerPackage><&invokerPackage>/<#apiPackage><&apiPackage>/ +* @version <&projectVersion> +*/ +export default class <&classname> extends ApiClient { + + <#emitJSDoc>/** + * Constructs a new <&classname>. <#description> + * + * @alias module:<#invokerPackage><&invokerPackage>/<#apiPackage><&apiPackage>/ + * @class + */ + constructor(baseURL = '<&basePath>') { + super(baseURL); + } + +<#operations><#operation><#emitJSDoc> + /**<#summary> + * <&summary><#notes> + * <¬es><#allParams><#required> + * @param {<&vendorExtensions.x-jsdoc-type>} <¶mName> <&description><#hasOptionalParams> + * @param {Object} opts Optional parameters<#allParams><^required> + * @param {<&vendorExtensions.x-jsdoc-type>} opts.<¶mName> <&description><#defaultValue> (default to <&.>) + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + <=| |=>* @return {Promise|#returnType|<|&vendorExtensions.x-jsdoc-type|>|/returnType|}|=< >=| + */ + async () { + <#vendorExtensions.x-codegen-has-optional-params> + opts = opts || {}; + + let postBody = <#bodyParam><#required><^required>opts['']<^bodyParam>null; +<#allParams> +<#required> + // verify the required parameter '' is set + if ( === undefined || === null) { + throw new Error("Missing the required parameter '' when calling "); + } + + + + let pathParams = {<#pathParams> + '': <#required><^required>opts['']<^-last>, + }; + let queryParams = {<#queryParams> + '': <#collectionFormat>this.buildCollectionParam(<#required><^required>opts[''], '')<^collectionFormat><#required><^required>opts['']<^-last>, + }; + let headerParams = { + 'User-Agent': '<#httpUserAgent><.><^httpUserAgent>OpenAPI-Generator/<&projectVersion>/Javascript',<#headerParams> + '': <#required><^required>opts['']<^-last>, + }; + let formParams = {<#formParams> + '': <#collectionFormat>this.buildCollectionParam(<#required><^required>opts[''], '')<^collectionFormat><#required><^required>opts['']<^-last>, + }; + + let authNames = [<#authMethods>''<^-last>, ]; + let contentTypes = [<#consumes>'<& mediaType>'<^-last>, ]; + let accepts = [<#produces>'<& mediaType>'<^-last>, ]; + let returnType = <#vendorExtensions.x-return-type><&vendorExtensions.x-return-type><^vendorExtensions.x-return-type>null; + <#servers.0> + let basePaths = [<#servers>''<^-last>, ]; + let basePath = basePaths[0]; // by default use the first one in "servers" defined in OpenAPI + if (typeof opts['_base_path_index'] !== 'undefined') { + if (opts['_base_path_index'] >= basePaths.length || opts['_base_path_index'] < 0) { + throw new Error("Invalid index " + opts['_base_path_index'] + " when selecting the host settings. Must be less than " + basePaths.length); + } + basePath = basePaths[opts['_base_path_index']]; + } + + + + return this.callApi( + '<&path>', '', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + +} +<={{ }}=> diff --git a/modules/openapi-generator/src/main/resources/Javascript/libraries/apollo/package.mustache b/modules/openapi-generator/src/main/resources/Javascript/libraries/apollo/package.mustache new file mode 100644 index 0000000000..60e3876d46 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Javascript/libraries/apollo/package.mustache @@ -0,0 +1,52 @@ +{ + "name": "{{{projectName}}}", + "version": "{{{projectVersion}}}", + "description": "{{{projectDescription}}}", + "license": "{{licenseName}}", + "main": "dist{{#invokerPackage}}/{{.}}{{/invokerPackage}}/index.js", + "scripts": { + "build": "babel src -d dist", + "prepare": "npm run build", + "test": "mocha --require @babel/register --recursive" + }, + "browser": { + "fs": false + }, +{{#npmRepository}} + "publishConfig":{ + "registry":"{{npmRepository}}" + }, +{{/npmRepository}} + "dependencies": { + "@babel/cli": "^7.0.0", + "apollo-datasource-rest": "^3.6.1", + "superagent": "^5.3.0" + }, + "devDependencies": { + "@babel/core": "^7.0.0", + "@babel/plugin-proposal-class-properties": "^7.0.0", + "@babel/plugin-proposal-decorators": "^7.0.0", + "@babel/plugin-proposal-do-expressions": "^7.0.0", + "@babel/plugin-proposal-export-default-from": "^7.0.0", + "@babel/plugin-proposal-export-namespace-from": "^7.0.0", + "@babel/plugin-proposal-function-bind": "^7.0.0", + "@babel/plugin-proposal-function-sent": "^7.0.0", + "@babel/plugin-proposal-json-strings": "^7.0.0", + "@babel/plugin-proposal-logical-assignment-operators": "^7.0.0", + "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0", + "@babel/plugin-proposal-numeric-separator": "^7.0.0", + "@babel/plugin-proposal-optional-chaining": "^7.0.0", + "@babel/plugin-proposal-pipeline-operator": "^7.0.0", + "@babel/plugin-proposal-throw-expressions": "^7.0.0", + "@babel/plugin-syntax-dynamic-import": "^7.0.0", + "@babel/plugin-syntax-import-meta": "^7.0.0", + "@babel/preset-env": "^7.0.0", + "@babel/register": "^7.0.0", + "expect.js": "^0.3.1", + "mocha": "^8.0.1", + "sinon": "^7.2.0" + }, + "files": [ + "dist" + ] +} diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Javascript/libraries/javascript/ApiClient.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/ApiClient.mustache rename to modules/openapi-generator/src/main/resources/Javascript/libraries/javascript/ApiClient.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/api.mustache b/modules/openapi-generator/src/main/resources/Javascript/libraries/javascript/api.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/api.mustache rename to modules/openapi-generator/src/main/resources/Javascript/libraries/javascript/api.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/package.mustache b/modules/openapi-generator/src/main/resources/Javascript/libraries/javascript/package.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/package.mustache rename to modules/openapi-generator/src/main/resources/Javascript/libraries/javascript/package.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/Javascript/licenseInfo.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/licenseInfo.mustache rename to modules/openapi-generator/src/main/resources/Javascript/licenseInfo.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/mocha.opts b/modules/openapi-generator/src/main/resources/Javascript/mocha.opts similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/mocha.opts rename to modules/openapi-generator/src/main/resources/Javascript/mocha.opts diff --git a/modules/openapi-generator/src/main/resources/Javascript/model.mustache b/modules/openapi-generator/src/main/resources/Javascript/model.mustache new file mode 100644 index 0000000000..ab9f0f3e8f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Javascript/model.mustache @@ -0,0 +1,28 @@ +{{>licenseInfo}} +import ApiClient from '../ApiClient'; +{{#imports}}import {{import}} from './{{import}}'; +{{/imports}} +{{#models}} +{{#model}} +{{#isEnum}} +{{>partial_model_enum_class}} +{{/isEnum}} +{{^isEnum}} +{{#oneOf}} +{{#-first}} +{{>partial_model_oneof}} +{{/-first}} +{{/oneOf}} +{{^oneOf}} +{{#anyOf}} +{{#-first}} +// TODO: add anyof model support +{{/-first}} +{{/anyOf}} +{{^anyOf}} +{{>partial_model_generic}} +{{/anyOf}} +{{/oneOf}} +{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/model_doc.mustache b/modules/openapi-generator/src/main/resources/Javascript/model_doc.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/model_doc.mustache rename to modules/openapi-generator/src/main/resources/Javascript/model_doc.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/model_test.mustache b/modules/openapi-generator/src/main/resources/Javascript/model_test.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/model_test.mustache rename to modules/openapi-generator/src/main/resources/Javascript/model_test.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/partial_model_enum_class.mustache b/modules/openapi-generator/src/main/resources/Javascript/partial_model_enum_class.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/partial_model_enum_class.mustache rename to modules/openapi-generator/src/main/resources/Javascript/partial_model_enum_class.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/partial_model_generic.mustache b/modules/openapi-generator/src/main/resources/Javascript/partial_model_generic.mustache new file mode 100644 index 0000000000..174a9a0064 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Javascript/partial_model_generic.mustache @@ -0,0 +1,178 @@ + +{{#models}}{{#model}}{{#emitJSDoc}}/** + * The {{classname}} model module. + * @module {{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{classname}} + * @version {{projectVersion}} + */{{/emitJSDoc}} +class {{classname}} {{#parent}}{{^parentModel}}{{#vendorExtensions.x-is-array}}extends Array {{/vendorExtensions.x-is-array}}{{/parentModel}}{{/parent}}{ + {{#emitJSDoc}}/** + * Constructs a new {{classname}}.{{#description}} + * {{.}}{{/description}} + * @alias module:{{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{classname}}{{#useInheritance}}{{#parent}} + * @extends {{#parentModel}}module:{{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{classname}}{{/parentModel}}{{^parentModel}}{{#vendorExtensions.x-is-array}}Array{{/vendorExtensions.x-is-array}}{{#vendorExtensions.x-is-map}}Object{{/vendorExtensions.x-is-map}}{{/parentModel}}{{/parent}}{{#interfaces}} + * @implements module:{{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{.}}{{/interfaces}}{{/useInheritance}}{{#vendorExtensions.x-all-required}} + * @param {{name}} {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{{description}}}{{/vendorExtensions.x-all-required}} + */{{/emitJSDoc}} + constructor({{#vendorExtensions.x-all-required}}{{name}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-all-required}}) { {{#parent}}{{^parentModel}}{{#vendorExtensions.x-is-array}} + super(); + {{/vendorExtensions.x-is-array}}{{/parentModel}}{{/parent}}{{#useInheritance}} + {{#interfaceModels}}{{classname}}.initialize(this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}});{{/interfaceModels}}{{/useInheritance}} + {{classname}}.initialize(this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}}); + } + + {{#emitJSDoc}}/** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */{{/emitJSDoc}} + static initialize(obj{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}}) { {{#vars}}{{#required}} + {{#defaultValue}}obj['{{baseName}}'] = {{name}} || {{{defaultValue}}};{{/defaultValue}}{{^defaultValue}}obj['{{baseName}}'] = {{name}};{{/defaultValue}}{{/required}}{{/vars}} + } + + {{#emitJSDoc}}/** + * Constructs a {{classname}} from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {{=< >=}}{module:<#invokerPackage>/<#modelPackage>/}<={{ }}=> obj Optional instance to populate. + * @return {{=< >=}}{module:<#invokerPackage>/<#modelPackage>/}<={{ }}=> The populated {{classname}} instance. + */{{/emitJSDoc}} + static constructFromObject(data, obj) { + if (data){{! TODO: support polymorphism: discriminator property on data determines class to instantiate.}} { + obj = obj || new {{classname}}();{{#parent}}{{^parentModel}} + + ApiClient.constructFromObject(data, obj, '{{vendorExtensions.x-item-type}}'); + {{/parentModel}}{{/parent}}{{#useInheritance}}{{#parentModel}} + {{classname}}.constructFromObject(data, obj);{{/parentModel}}{{#interfaces}} + {{.}}.constructFromObject(data, obj);{{/interfaces}}{{/useInheritance}} + + {{#vars}} + if (data.hasOwnProperty('{{baseName}}')) { + obj['{{baseName}}']{{{defaultValueWithParam}}} + } + {{/vars}} + } + return obj; + } + + {{#emitJSDoc}}/** + * Validates the JSON data with respect to {{classname}}. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to {{classname}}. + */{{/emitJSDoc}} + static validateJSON(data) { + {{#requiredVars}} + {{#-first}} + // check to make sure all required properties are present in the JSON string + for (const property of {{classname}}.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + {{/-first}} + {{/requiredVars}} + {{#vars}} + {{#isArray}} + {{#items.isModel}} + {{#isRequired}} + // ensure the json data is an array + if (!Array.isArray(data['{{{baseName}}}'])) { + throw new Error("Expected the field `{{{baseName}}}` to be an array in the JSON data but got " + data['{{{baseName}}}']); + } + // validate the required field `{{{baseName}}}` (array) + for (const item of data['{{{baseName}}}']) { + {{{items.dataType}}}.validateJsonObject(item); + }; + {{/isRequired}} + {{^isRequired}} + if (data['{{{baseName}}}']) { // data not null + // ensure the json data is an array + if (!Array.isArray(data['{{{baseName}}}'])) { + throw new Error("Expected the field `{{{baseName}}}` to be an array in the JSON data but got " + data['{{{baseName}}}']); + } + // validate the optional field `{{{baseName}}}` (array) + for (const item of data['{{{baseName}}}']) { + {{{items.dataType}}}.validateJsonObject(item); + }; + } + {{/isRequired}} + {{/items.isModel}} + {{^items.isModel}} + // ensure the json data is an array + if (!Array.isArray(data['{{{baseName}}}'])) { + throw new Error("Expected the field `{{{baseName}}}` to be an array in the JSON data but got " + data['{{{baseName}}}']); + } + {{/items.isModel}} + {{/isArray}} + {{^isContainer}} + {{#isString}} + // ensure the json data is a string + if ({{^isRequired}}data['{{{baseName}}}']{{/isRequired}} && !(typeof data['{{{baseName}}}'] === 'string' || data['{{{baseName}}}'] instanceof String)) { + throw new Error("Expected the field `{{{baseName}}}` to be a primitive type in the JSON string but got " + data['{{{baseName}}}']); + } + {{/isString}} + {{#isModel}} + {{#isRequired}} + // validate the required field `{{{baseName}}}` + {{{dataType}}}.validateJSON(data['{{{baseName}}}']); + {{/isRequired}} + {{^isRequired}} + // validate the optional field `{{{baseName}}}` + if (data['{{{baseName}}}']) { // data not null + {{{dataType}}}.validateJSON(data['{{{baseName}}}']); + } + {{/isRequired}} + {{/isModel}} + {{/isContainer}} + {{/vars}} + + return true; + } + +{{#emitModelMethods}}{{#vars}}{{#emitJSDoc}}/**{{#description}} + * Returns {{{.}}}{{/description}}{{#minimum}} + * minimum: {{.}}{{/minimum}}{{#maximum}} + * maximum: {{.}}{{/maximum}} + * @return {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> + */{{/emitJSDoc}} + {{getter}}() { + return this.{{baseName}}; + } + + {{#emitJSDoc}}/**{{#description}} + * Sets {{{.}}}{{/description}} + * @param {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{name}}{{#description}} {{{.}}}{{/description}} + */{{/emitJSDoc}} + {{setter}}({{name}}) { + this['{{baseName}}'] = {{name}}; + } +{{/vars}}{{/emitModelMethods}}{{/model}} +} + +{{#requiredVars}}{{#-first}}{{classname}}.RequiredProperties = [{{/-first}}"{{{baseName}}}"{{^-last}}, {{/-last}}{{#-last}}];{{/-last}}{{/requiredVars}} + +{{#vars}}{{#emitJSDoc}}/**{{#description}} + * {{{.}}}{{/description}} + * @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}{{#defaultValue}} + * @default {{{.}}}{{/defaultValue}} + */{{/emitJSDoc}} +{{classname}}.prototype['{{baseName}}'] = {{{defaultValue}}}{{^defaultValue}}undefined{{/defaultValue}}; + +{{/vars}} + +{{#useInheritance}}{{#interfaceModels}}// Implement {{classname}} interface: +{{#allVars}}{{#emitJSDoc}}/**{{#description}} + * {{{.}}}{{/description}} + * @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}{{#defaultValue}} + * @default {{{.}}}{{/defaultValue}} + */{{/emitJSDoc}} +{{classname}}.prototype['{{baseName}}'] = {{{defaultValue}}}{{^defaultValue}}undefined{{/defaultValue}}; +{{/allVars}}{{/interfaceModels}}{{/useInheritance}} + +{{#vars}}{{#isEnum}}{{^isContainer}} +{{>partial_model_inner_enum}} +{{/isContainer}}{{/isEnum}}{{#items.isEnum}}{{#items}}{{^isContainer}} +{{>partial_model_inner_enum}} +{{/isContainer}}{{/items}}{{/items.isEnum}}{{/vars}} + +export default {{classname}}; +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/partial_model_inner_enum.mustache b/modules/openapi-generator/src/main/resources/Javascript/partial_model_inner_enum.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/partial_model_inner_enum.mustache rename to modules/openapi-generator/src/main/resources/Javascript/partial_model_inner_enum.mustache diff --git a/modules/openapi-generator/src/main/resources/Javascript/partial_model_oneof.mustache b/modules/openapi-generator/src/main/resources/Javascript/partial_model_oneof.mustache new file mode 100644 index 0000000000..b226851ffc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Javascript/partial_model_oneof.mustache @@ -0,0 +1,282 @@ + +{{#emitJSDoc}} +/** + * The {{classname}} model module. + * @module {{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{classname}} + * @version {{projectVersion}} + */ +{{/emitJSDoc}} +class {{classname}} { + {{#emitJSDoc}}/** + * Constructs a new {{classname}}.{{#description}} + * {{.}}{{/description}} + * @alias module:{{#invokerPackage}}{{.}}/{{/invokerPackage}}{{#modelPackage}}{{.}}/{{/modelPackage}}{{classname}} + * @param {{=< >=}}{(<#oneOf>module:<#invokerPackage>/<#modelPackage>/<&.><^-last>|)}<={{ }}=> instance The actual instance to initialize {{classname}}. + */ + {{/emitJSDoc}} + constructor(instance = null) { + if (instance === null) { + this.actualInstance = null; + return; + } + var match = 0; + var errorMessages = []; + {{#composedSchemas.oneOf}} + {{#description}} + // {{{description}}} + {{/description}} + try { + {{#isPrimitiveType}} + {{#isArray}} + // validate array data type + if (!Array.isArray(instance)) { + throw new Error("Invalid data type. Expecting array. Input: " + instance); + } + {{#minItems}} + {{#maxItems}} + if (instance.length > {{{maxItems}}} || instance.length < {{{minItems}}}) { + throw new Error("Invalid array size. Minimim: {{minItems}}. Maximum: {{maxItems}}. Input: " + instance); + } + {{/maxItems}} + {{^maxItems}} + if (instance.length < {{{minItems}}}) { + throw new Error("Invalid array size. Minimim: {{minItems}}. Input: " + instance); + } + {{/maxItems}} + {{/minItems}} + {{^minItems}} + {{#maxItems}} + if (instance.length > {{{maxItems}}}) { + throw new Error("Invalid array size. Maximum: {{maxItems}}. Input: " + instance); + } + {{/maxItems}} + {{/minItems}} + {{#items.isInteger}} + // validate array of integer + for (const item of instance) { + if (!(typeof item === 'number' && item % 1 === 0)) { + throw new Error("Invalid array items. Must be integer. Input: " + instance); + } + {{#items.maximum}} + {{#items.minimum}} + if (item > {{items.maximum}} || item < {{items.minimum}}) { + throw new Error("Invalid integer value in an array items. Max.: {{items.maximum}}. Min.: {{items.minimum}}. Input: " + instance); + } + {{/items.minimum}} + {{^items.minimum}} + if (item > {{items.maximum}}) { + throw new Error("Invalid integer value in an array items. Max.: {{items.maximum}}. Input: " + instance); + } + {{/items.minimum}} + {{/items.maximum}} + {{^items.maximum}} + {{#items.minimum}} + if (item < {{items.minimum}}) { + throw new Error("Invalid integer value in an array items. Min.: {{items.minimum}}. Input: " + instance); + } + {{/items.minimum}} + {{/items.maximum}} + } + {{/items.isInteger}} + {{#items.isString}} + // validate array of string + for (const item of instance) { + if (!(typeof item === 'number' && item % 1 === 0)) { + throw new Error("Invalid array items. Must be string. Input: " + instance); + } + {{#items.pattern}} + if (!{{{items.pattern}}}.test(item)) { + throw new Error("Invalid string value in an array items. Must conform to {{{items.pattern}}}. Input: " + item); + } + {{/items.pattern}} + {{#items.minLength}} + {{#items.maxLength}} + if (item.length > {{items.maxLength}} && item.length < {{items.minLength}}) { + throw new Error("Invalid string value in an array items. Max. length: {{{items.maxLength}}}. Min. length: {{{items.minLength}}}. Input: " + item); + } + {{/items.maxLength}} + {{^items.maxLength}} + if (item.length < {{items.minLength}}) { + throw new Error("Invalid string value in an array items. Min. length: {{{items.minLength}}}. Input: " + item); + } + {{/items.maxLength}} + {{/items.minLength}} + {{^items.minLength}} + {{#items.maxLength}} + if (item.length > {{items.maxLength}}) { + throw new Error("Invalid string value in an array items. Max. length: {{{items.maxLength}}}. Input: " + item) + } + {{/items.maxLength}} + {{/items.minLength}} + } + {{/items.isString}} + {{#items.isNumber}} + // validate array of string + for (const item of instance) { + if (!(typeof instance === 'number' && instance % 1 != 0)) { + throw new Error("Invalid array items. Must be number. Input: " + JSON.stringify(instance)); + } + } + {{/items.isNumber}} + {{/isArray}} + {{^isArray}} + {{#isInteger}} + // validate array of integer + if (!(typeof instance === 'number' && instance % 1 === 0)) { + throw new Error("Invalid array items. Must be integer. Input: " + JSON.stringify(instance)); + } + {{#maximum}} + {{#minimum}} + if (instance > {{maximum}} || instance < {{minimum}}) { + throw new Error("Invalid integer value in an array items. Max.: {{maximum}}. Min.: {{minimum}}. Input: " + JSON.stringify(instance)); + } + {{/minimum}} + {{^minimum}} + if (instance > {{maximum}}) { + throw new Error("Invalid integer value in an array items. Max.: {{maximum}}. Input: " + JSON.stringify(instance)); + } + {{/minimum}} + {{/maximum}} + {{^maximum}} + {{#minimum}} + if (instance < {{minimum}}) { + throw new Error("Invalid integer value in an array items. Min.: {{minimum}}. Input: " + JSON.stringify(instance)); + } + {{/minimum}} + {{/maximum}} + {{/isInteger}} + {{#isString}} + // validate array of string + if (!(typeof instance === 'string')) { + throw new Error("Invalid input. Must be string. Input: " + JSON.stringify(instance)); + } + {{#pattern}} + if (!{{{pattern}}}.test(instance)) { + throw new Error("Invalid string value in an array items. Must conform to {{{.}}}. Input: " + JSON.stringify(instance)); + } + {{/pattern}} + {{#minLength}} + {{#maxLength}} + if (instance.length > {{maxLength}} && instance.length < {{minLength}}) { + throw new Error("Invalid string value in an array items. Max. length: {{{maxLength}}}. Min. length: {{{minLength}}}. Input: " + JSON.stringify(instance)); + } + {{/maxLength}} + {{^maxLength}} + if (instance.length < {{minLength}}) { + throw new Error("Invalid string value in an array items. Min. length: {{{minLength}}}. Input: " + instance); + } + {{/maxLength}} + {{/minLength}} + {{^minLength}} + {{#maxLength}} + if (instance.length > {{maxLength}}) { + throw new Error("Invalid string value in an array items. Max. length: {{{maxLength}}}. Input: " + JSON.stringify(instance)); + } + {{/maxLength}} + {{/minLength}} + {{/isString}} + {{#isNumber}} + // validate array of string + if (!(typeof instance === 'number' && instance % 1 != 0)) { + throw new Error("Invalid array items. Must be number. Input: " + JSON.stringify(instance)); + } + {{/isNumber}} + {{/isArray}} + this.actualInstance = instance; + {{/isPrimitiveType}} + {{^isPrimitiveType}} + if (typeof instance === "{{{dataType}}}") { + this.actualInstance = instance; + } else { + // plain JS object + // validate the object + {{{dataType}}}.validateJSON(instance); // throw an exception if no match + // create {{{dataType}}} from JS object + this.actualInstance = {{{dataType}}}.constructFromObject(instance); + } + {{/isPrimitiveType}} + match++; + } catch(err) { + // json data failed to deserialize into {{{dataType}}} + errorMessages.push("Failed to construct {{{dataType}}}: " + err) + } + + {{/composedSchemas.oneOf}} + if (match > 1) { + throw new Error("Multiple matches found constructing `{{{classname}}}` with oneOf schemas {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Input: " + JSON.stringify(instance)); + } else if (match === 0) { + this.actualInstance = null; // clear the actual instance in case there are multiple matches + throw new Error("No match found constructing `{{{classname}}}` with oneOf schemas {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + + errorMessages.join(", ")); + } else { // only 1 match + // the input is valid + } + } + + {{#emitJSDoc}} + /** + * Constructs a {{classname}} from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {{=< >=}}{module:<#invokerPackage>/<#modelPackage>/}<={{ }}=> obj Optional instance to populate. + * @return {{=< >=}}{module:<#invokerPackage>/<#modelPackage>/}<={{ }}=> The populated {{classname}} instance. + */ + {{/emitJSDoc}} + static constructFromObject(data, obj) { + return new {{classname}}(data); + } + + {{#emitJSDoc}} + /** + * Gets the actaul instance, which can be {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. + * @return {{=< >=}}{(<#oneOf>module:<#invokerPackage>/<#modelPackage>/<&.><^-last>|)}<={{ }}=> The actual instance. + */ + {{/emitJSDoc}} + getActualInstance() { + return this.actualInstance; + } + + {{#emitJSDoc}} + /** + * Sets the actaul instance, which can be {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. + * @param {{=< >=}}{(<#oneOf>module:<#invokerPackage>/<#modelPackage>/<&.><^-last>|)}<={{ }}=> obj The actual instance. + */ + {{/emitJSDoc}} + setActualInstance(obj) { + this.actualInstance = {{classname}}.constructFromObject(obj).getActualInstance(); + } + + {{#emitJSDoc}} + /** + * Returns the JSON representation of the actual intance. + * @return {string} + */ + {{/emitJSDoc}} + toJSON = function(){ + return this.getActualInstance(); + } + + {{#emitJSDoc}} + /** + * Create an instance of {{classname}} from a JSON string. + * @param {string} json_string JSON string. + * @return {{=< >=}}{module:<#invokerPackage>/<#modelPackage>/<&classname>}<={{ }}=> An instance of {{classname}}. + */ + {{/emitJSDoc}} + static fromJSON = function(json_string){ + return {{classname}}.constructFromObject(JSON.parse(json_string)); + } +} + +{{#vars}}{{#emitJSDoc}}/**{{#description}} + * {{{.}}}{{/description}} + * @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}{{#defaultValue}} + * @default {{{.}}}{{/defaultValue}} + */{{/emitJSDoc}} +{{classname}}.prototype['{{baseName}}'] = {{{defaultValue}}}{{^defaultValue}}undefined{{/defaultValue}}; + +{{/vars}} + +{{classname}}.OneOf = [{{#oneOf}}"{{{.}}}"{{^-last}}, {{/-last}}{{/oneOf}}]; + +export default {{classname}}; diff --git a/modules/openapi-generator/src/main/resources/Javascript/es6/travis.yml b/modules/openapi-generator/src/main/resources/Javascript/travis.yml similarity index 100% rename from modules/openapi-generator/src/main/resources/Javascript/es6/travis.yml rename to modules/openapi-generator/src/main/resources/Javascript/travis.yml 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 fdc47bd6d9..92dcb24bbc 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 @@ -15,6 +15,7 @@ org.openapitools.codegen.languages.CppQtClientCodegen org.openapitools.codegen.languages.CppQtQHttpEngineServerCodegen org.openapitools.codegen.languages.CppPistacheServerCodegen org.openapitools.codegen.languages.CppRestbedServerCodegen +org.openapitools.codegen.languages.CppRestbedServerDeprecatedCodegen org.openapitools.codegen.languages.CppRestSdkClientCodegen org.openapitools.codegen.languages.CppTinyClientCodegen org.openapitools.codegen.languages.CppTizenClientCodegen @@ -50,6 +51,8 @@ org.openapitools.codegen.languages.HaskellServantCodegen org.openapitools.codegen.languages.HaskellYesodServerCodegen org.openapitools.codegen.languages.JavaClientCodegen org.openapitools.codegen.languages.JavaCXFClientCodegen +org.openapitools.codegen.languages.JavaHelidonClientCodegen +org.openapitools.codegen.languages.JavaHelidonServerCodegen org.openapitools.codegen.languages.JavaInflectorServerCodegen org.openapitools.codegen.languages.JavaMicronautClientCodegen org.openapitools.codegen.languages.JavaMicronautServerCodegen @@ -97,7 +100,7 @@ org.openapitools.codegen.languages.ProtobufSchemaCodegen org.openapitools.codegen.languages.PythonLegacyClientCodegen org.openapitools.codegen.languages.PythonClientCodegen org.openapitools.codegen.languages.PythonFastAPIServerCodegen -org.openapitools.codegen.languages.PythonExperimentalClientCodegen +org.openapitools.codegen.languages.PythonPriorClientCodegen org.openapitools.codegen.languages.PythonFlaskConnexionServerCodegen org.openapitools.codegen.languages.PythonAiohttpConnexionServerCodegen org.openapitools.codegen.languages.PythonBluePlanetServerCodegen diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/README.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/README.mustache index eb041c5f9e..1f0fa79b58 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/README.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/README.mustache @@ -4,6 +4,32 @@ {{{.}}} {{/appDescriptionWithNewLines}} +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + ## Run Linux/OS X: diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/mapReturn.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/mapReturn.mustache index 94f16e11fd..0b63864f64 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/2.0/mapReturn.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.0/mapReturn.mustache @@ -1,4 +1,4 @@ var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : new Dictionary<{{{returnType}}}>(); \ No newline at end of file + ? JsonConvert.DeserializeObject<{{{returnType}}}>(exampleJson) + : new {{{returnType}}}(); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/README.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/README.mustache index 3602e5d507..eaab139716 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/README.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/README.mustache @@ -4,6 +4,32 @@ {{{.}}} {{/appDescriptionWithNewLines}} +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + ## Run Linux/OS X: diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/mapReturn.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/mapReturn.mustache index 94f16e11fd..0b63864f64 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/2.1/mapReturn.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/2.1/mapReturn.mustache @@ -1,4 +1,4 @@ var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : new Dictionary<{{{returnType}}}>(); \ No newline at end of file + ? JsonConvert.DeserializeObject<{{{returnType}}}>(exampleJson) + : new {{{returnType}}}(); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/ModelsProject.csproj.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/ModelsProject.csproj.mustache new file mode 100644 index 0000000000..c02910a04e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/ModelsProject.csproj.mustache @@ -0,0 +1,38 @@ + + + {{packageDescription}}{{^packageDescription}}{{modelPackage}}{{/packageDescription}} + {{packageCopyright}} + {{packageAuthors}} + {{targetFramework}} + true + true + {{packageVersion}} +{{#nullableReferenceTypes}} + annotations +{{/nullableReferenceTypes}} + Library + {{modelPackage}} + {{modelPackage}} + + + +{{#useSwashbuckle}} + +{{#useNewtonsoft}} + +{{/useNewtonsoft}} +{{^useNewtonsoft}} + +{{/useNewtonsoft}} + +{{/useSwashbuckle}} +{{^useSwashbuckle}} +{{#useNewtonsoft}} + +{{/useNewtonsoft}} +{{/useSwashbuckle}} + + + + + diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache index 889efc0161..c663a71f5d 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache @@ -20,6 +20,9 @@ ..\.. +{{#useSeperateModelProject}} + +{{/useSeperateModelProject}} {{#useFrameworkReference}} {{#isLibrary}} @@ -28,7 +31,9 @@ {{^useFrameworkReference}} {{/useFrameworkReference}} +{{^useSeperateModelProject}} +{{/useSeperateModelProject}} {{#useSwashbuckle}} {{#useNewtonsoft}} diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/README.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/README.mustache index 3602e5d507..eaab139716 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/README.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/README.mustache @@ -4,6 +4,32 @@ {{{.}}} {{/appDescriptionWithNewLines}} +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + ## Run Linux/OS X: diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Solution.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Solution.mustache index 8c6d69ea93..b72da20f3d 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Solution.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Solution.mustache @@ -5,6 +5,10 @@ VisualStudioVersion = 15.0.27428.2043 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{packageName}}", "{{sourceFolder}}\{{packageName}}\{{packageName}}.csproj", "{{packageGuid}}" EndProject +{{#useSeperateModelProject}} +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{modelPackage}}", "{{sourceFolder}}\{{modelPackage}}\{{modelPackage}}.csproj", "{B8D18F25-F379-4B87-ACCC-F8A17E0AED38}" +EndProject +{{/useSeperateModelProject}} Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +19,12 @@ Global {{packageGuid}}.Debug|Any CPU.Build.0 = Debug|Any CPU {{packageGuid}}.Release|Any CPU.ActiveCfg = Release|Any CPU {{packageGuid}}.Release|Any CPU.Build.0 = Release|Any CPU +{{#useSeperateModelProject}} + {B8D18F25-F379-4B87-ACCC-F8A17E0AED38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8D18F25-F379-4B87-ACCC-F8A17E0AED38}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8D18F25-F379-4B87-ACCC-F8A17E0AED38}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8D18F25-F379-4B87-ACCC-F8A17E0AED38}.Release|Any CPU.Build.0 = Release|Any CPU +{{/useSeperateModelProject}} EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Startup.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Startup.mustache index d94e1e6bb1..b9f38b815b 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Startup.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Startup.mustache @@ -86,6 +86,8 @@ namespace {{packageName}} services .AddSwaggerGen(c => { + c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true); + c.SwaggerDoc("{{{version}}}{{^version}}v1{{/version}}", new OpenApiInfo { Title = "{{{appName}}}{{^appName}}{{packageName}}{{/appName}}", diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/mapReturn.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/mapReturn.mustache index 94f16e11fd..0b63864f64 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/mapReturn.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/mapReturn.mustache @@ -1,4 +1,4 @@ var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : new Dictionary<{{{returnType}}}>(); \ No newline at end of file + ? JsonConvert.DeserializeObject<{{{returnType}}}>(exampleJson) + : new {{{returnType}}}(); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/model.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/model.mustache index 43d92560b7..e96ce19cf5 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/model.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/model.mustache @@ -11,6 +11,7 @@ using Newtonsoft.Json; {{#model}} {{#discriminator}} using JsonSubTypes; +using Swashbuckle.AspNetCore.Annotations; {{/discriminator}} {{/model}} {{/models}} @@ -26,8 +27,10 @@ namespace {{modelPackage}} [DataContract] {{#discriminator}} [JsonConverter(typeof(JsonSubtypes), "{{{discriminatorName}}}")] + [SwaggerDiscriminator("{{{discriminatorName}}}")] {{#mappedModels}} [JsonSubtypes.KnownSubType(typeof({{{modelName}}}), "{{^vendorExtensions.x-discriminator-value}}{{{mappingName}}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{.}}}{{/vendorExtensions.x-discriminator-value}}")] + [SwaggerSubType(typeof({{{modelName}}}), DiscriminatorValue = "{{^vendorExtensions.x-discriminator-value}}{{{mappingName}}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{.}}}{{/vendorExtensions.x-discriminator-value}}")] {{/mappedModels}} {{/discriminator}} public {{#modelClassModifier}}{{.}} {{/modelClassModifier}}class {{classname}} {{#parent}}: {{{.}}}{{^pocoModels}}, {{/pocoModels}}{{/parent}}{{^pocoModels}}{{^parent}}: {{/parent}}IEquatable<{{classname}}>{{/pocoModels}} diff --git a/modules/openapi-generator/src/main/resources/avro-schema/typeArray.mustache b/modules/openapi-generator/src/main/resources/avro-schema/typeArray.mustache index 01aba0e204..f648b30d0e 100644 --- a/modules/openapi-generator/src/main/resources/avro-schema/typeArray.mustache +++ b/modules/openapi-generator/src/main/resources/avro-schema/typeArray.mustache @@ -1,4 +1,4 @@ { "type": "{{dataType}}", - {{#items}}"items": "{{#isModel}}{{package}}.{{/isModel}}{{dataType}}"{{/items}} + {{#items}}"items": "{{^isPrimitiveType}}{{package}}.{{/isPrimitiveType}}{{dataType}}"{{/items}} } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache index 8c2df227ea..b03b9c4315 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache @@ -19,9 +19,21 @@ namespace {{modelNamespace}} struct {{classname}} { + {{#isEnum}}{{#allowableValues}} + enum e{{classname}} { + // To have a valid default value. + // Avoiding name clashes with user defined + // enum values + INVALID_VALUE_OPENAPI_GENERATED = 0, + {{#enumVars}} + {{{name}}}{{^-last}}, {{/-last}} + {{/enumVars}} + };{{/allowableValues}}{{/isEnum}} + {{#vars}} {{^required}}std::optional<{{/required}}{{{dataType}}}{{^required}}>{{/required}} {{name}}; {{/vars}} + {{#isEnum}}{{classname}}::e{{classname}} value = {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED;{{/isEnum}}{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}}{{{this}}} m_value;{{/-first}}{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}} bool operator==(const {{classname}}& other) const; bool operator!=(const {{classname}}& other) const; diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache index 7b1db917e2..9ced9452ae 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache @@ -41,7 +41,7 @@ bool {{classname}}::validate(std::stringstream& msg, const std::string& pathPref const std::string _pathPrefix = pathPrefix.empty() ? "{{classname}}" : pathPrefix; {{#isEnum}}{{! Special case for enum types }} - if (m_value == {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED) + if (value == {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED) { success = false; msg << _pathPrefix << ": has no value;"; @@ -73,7 +73,9 @@ bool {{classname}}::validate(std::stringstream& msg, const std::string& pathPref bool {{classname}}::operator==(const {{classname}}& other) const { - return {{#vars}}{{name}} == other.{{name}}{{^-last}} && {{/-last}}{{/vars}}; + return + {{#isEnum}}value == other.value{{/isEnum}} + {{#vars}}{{name}} == other.{{name}}{{^-last}} && {{/-last}}{{/vars}}; } bool {{classname}}::operator!=(const {{classname}}& other) const @@ -87,6 +89,20 @@ void to_json(nlohmann::json& j, const {{classname}}& o) {{^required}}if (o.{{name}}.has_value()){{/required}} j["{{baseName}}"] = o.{{name}}{{^required}}.value(){{/required}}; {{/vars}} + {{#isEnum}}{{#allowableValues}} + switch (o.value) + { + {{#enumVars}} + {{#-first}} + case {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED: + j = "INVALID_VALUE_OPENAPI_GENERATED"; + break; + {{/-first}} + case {{classname}}::e{{classname}}::{{name}}: + j = "{{value}}"; + break; + {{/enumVars}} + }{{/allowableValues}}{{/isEnum}}{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}}to_json(j, o.m_value);{{/-first}}{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}} } void from_json(const nlohmann::json& j, {{classname}}& o) @@ -96,9 +112,23 @@ void from_json(const nlohmann::json& j, {{classname}}& o) {{^required}}if (j.find("{{baseName}}") != j.end()) { {{{dataType}}} temporary_{{name}}; j.at("{{baseName}}").get_to(temporary_{{name}}); - o.{{name}} = temporary_{{name}}; + o.{{name}} = std::move(temporary_{{name}}); }{{/required}} {{/vars}} + {{#isEnum}}{{#allowableValues}} + auto s = j.get(); + {{#enumVars}} + {{#-first}} + if{{/-first}}{{^-first}}else if{{/-first}}(s == "{{value}}") { + o.value = {{classname}}::e{{classname}}::{{name}}; + } {{#-last}} else { + std::stringstream ss; + ss << "Unexpected value " << s << " in json" + << " cannot be converted to enum of type" + << " {{classname}}::e{{classname}}"; + throw std::invalid_argument(ss.str()); + } {{/-last}} + {{/enumVars}}{{/allowableValues}}{{/isEnum}} } } // namespace {{modelNamespace}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache index 0da1decf03..f6f4d89070 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache @@ -196,7 +196,7 @@ void {{prefix}}HttpRequestWorker::execute({{prefix}}HttpRequestInput *input) { if (input->vars.count() > 0) { bool first = true; isFormData = true; - foreach (QString key, input->vars.keys()) { + for (QString key : input->vars.keys()) { if (!first) { request_content.append("&"); } @@ -227,7 +227,7 @@ void {{prefix}}HttpRequestWorker::execute({{prefix}}HttpRequestInput *input) { QString new_line = "\r\n"; // add variables - foreach (QString key, input->vars.keys()) { + for (QString key : input->vars.keys()) { // add boundary request_content.append(boundary_delimiter.toUtf8()); request_content.append(boundary.toUtf8()); @@ -329,7 +329,7 @@ void {{prefix}}HttpRequestWorker::execute({{prefix}}HttpRequestInput *input) { request.setSslConfiguration(*{{prefix}}HttpRequestWorker::sslDefaultConfiguration); } request.setRawHeader("User-Agent", "{{httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{apiVersion}}/cpp-qt{{/httpUserAgent}}"); - foreach (QString key, input->headers.keys()) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } + for (QString key : input->headers.keys()) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } if (request_content.size() > 0 && !isFormData && (input->var_layout != MULTIPART)) { if (!input->headers.contains("Content-Type")) { diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache index 8204c12e9e..83db65526d 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache @@ -74,7 +74,7 @@ void {{classname}}::setServerIndex(const QString &operation, int serverIndex) { } void {{classname}}::setApiKey(const QString &apiKeyName, const QString &apiKey) { - _apiKeys.insert(apiKeyName,apiKey); + _apiKeys.insert(apiKeyName, apiKey); } void {{classname}}::setBearerToken(const QString &token) { @@ -271,7 +271,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} QString paramString = (pathStyle == "matrix" && {{isExplode}}) ? pathPrefix : pathPrefix+"{{baseName}}"+pathSuffix; QJsonObject parameter = {{paramName}}{{^required}}.value(){{/required}}.asJsonObject(); qint32 count = 0; - foreach(const QString& key, parameter.keys()) { + for(const QString& key : parameter.keys()) { if (count > 0) { pathDelimiter = (pathStyle == "matrix" && {{isExplode}}) ? ";" : getParamStyleDelimiter(pathStyle, key, {{isExplode}}); paramString.append(pathDelimiter); @@ -320,7 +320,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} if ({{{paramName}}}{{^required}}.value(){{/required}}.size() > 0) { QString paramString = (pathStyle == "matrix") ? pathPrefix+"{{baseName}}"+pathSuffix : pathPrefix; qint32 count = 0; - foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value(){{/required}}) { + for ({{{baseType}}} t : {{paramName}}{{^required}}.value(){{/required}}) { if (count > 0) { fullPath.append(pathDelimiter); } @@ -353,7 +353,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} QString paramString = (queryStyle == "form" && {{isExplode}}) ? "" : (queryStyle == "form" && !({{isExplode}})) ? "{{baseName}}"+querySuffix : ""; QJsonObject parameter = {{paramName}}{{^required}}.value(){{/required}}.asJsonObject(); qint32 count = 0; - foreach(const QString& key, parameter.keys()) { + for(const QString& key : parameter.keys()) { if (count > 0) { queryDelimiter = ((queryStyle == "form" || queryStyle == "deepObject") && {{isExplode}}) ? "&" : getParamStyleDelimiter(queryStyle, key, {{isExplode}}); paramString.append(queryDelimiter); @@ -403,7 +403,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} {{#collectionFormat}} if ({{{paramName}}}{{^required}}.value(){{/required}}.size() > 0) { if (QString("{{collectionFormat}}").indexOf("multi") == 0) { - foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value(){{/required}}) { + for ({{{baseType}}} t : {{paramName}}{{^required}}.value(){{/required}}) { if (fullPath.indexOf("?") > 0) fullPath.append(queryPrefix); else @@ -416,7 +416,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} else fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix); qint32 count = 0; - foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value(){{/required}}) { + for ({{{baseType}}} t : {{paramName}}{{^required}}.value(){{/required}}) { if (count > 0) { fullPath.append(({{isExplode}})? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter)); } @@ -429,7 +429,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} else fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix); qint32 count = 0; - foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value(){{/required}}) { + for ({{{baseType}}} t : {{paramName}}{{^required}}.value(){{/required}}) { if (count > 0) { fullPath.append("\t"); } @@ -442,7 +442,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} else fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix); qint32 count = 0; - foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value(){{/required}}) { + for ({{{baseType}}} t : {{paramName}}{{^required}}.value(){{/required}}) { if (count > 0) { fullPath.append(queryDelimiter); } @@ -455,7 +455,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} else fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix); qint32 count = 0; - foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value(){{/required}}) { + for ({{{baseType}}} t : {{paramName}}{{^required}}.value(){{/required}}) { if (count > 0) { fullPath.append(queryDelimiter); } @@ -468,7 +468,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} else fullPath.append("?").append(queryPrefix).append("{{baseName}}").append(querySuffix); qint32 count = 0; - foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value(){{/required}}) { + for ({{{baseType}}} t : {{paramName}}{{^required}}.value(){{/required}}) { if (count > 0) { fullPath.append(queryDelimiter); } @@ -530,7 +530,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} QString headerString; QJsonObject parameter = {{paramName}}{{^required}}.value(){{/required}}.asJsonObject(); qint32 count = 0; - foreach(const QString& key, parameter.keys()) { + for (const QString& key : parameter.keys()) { if (count > 0) { headerString.append(","); } @@ -577,7 +577,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} QString headerString; if ({{{paramName}}}{{^required}}.value(){{/required}}.size() > 0) { qint32 count = 0; - foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value(){{/required}}) { + for ({{{baseType}}} t : {{paramName}}{{^required}}.value(){{/required}}) { if (count > 0) { headerString.append(","); } @@ -599,7 +599,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} QString cookieString = "{{baseName}}="; QJsonObject parameter = {{paramName}}{{^required}}.value(){{/required}}.asJsonObject(); qint32 count = 0; - foreach(const QString& key, parameter.keys()) { + for (const QString& key : parameter.keys()) { if (count > 0) { cookieString.append(","); } @@ -649,7 +649,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} QString cookieString = "{{baseName}}="; if ({{{paramName}}}.size() > 0) { qint32 count = 0; - foreach ({{{baseType}}} t, {{paramName}}{{^required}}.value(){{/required}}) { + for ({{{baseType}}} t : {{paramName}}{{^required}}.value(){{/required}}) { if (count > 0) { cookieString.append(","); } @@ -697,7 +697,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} _latestWorker->setWorkingDirectory(_workingDirectory);{{#contentCompression}} _latestWorker->setResponseCompressionEnabled(isResponseCompressionEnabled); _latestWorker->setRequestCompressionEnabled(isRequestCompressionEnabled);{{/contentCompression}} - + connect(_latestWorker, &{{prefix}}HttpRequestWorker::on_execution_finished, this, &{{classname}}::{{nickname}}Callback); connect(this, &{{classname}}::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -727,7 +727,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} _latestWorker->setWorkingDirectory(_workingDirectory);{{#contentCompression}} _latestWorker->setResponseCompressionEnabled(isResponseCompressionEnabled); _latestWorker->setRequestCompressionEnabled(isRequestCompressionEnabled);{{/contentCompression}} - + connect(_latestWorker, &{{prefix}}HttpRequestWorker::on_execution_finished, this, &{{classname}}::{{nickname}}Callback); connect(this, &{{classname}}::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -757,7 +757,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} _latestWorker->setWorkingDirectory(_workingDirectory);{{#contentCompression}} _latestWorker->setResponseCompressionEnabled(isResponseCompressionEnabled); _latestWorker->setRequestCompressionEnabled(isRequestCompressionEnabled);{{/contentCompression}} - + connect(_latestWorker, &{{prefix}}HttpRequestWorker::on_execution_finished, this, &{{classname}}::{{nickname}}Callback); connect(this, &{{classname}}::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -787,7 +787,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} _latestWorker->setWorkingDirectory(_workingDirectory);{{#contentCompression}} _latestWorker->setResponseCompressionEnabled(isResponseCompressionEnabled); _latestWorker->setRequestCompressionEnabled(isRequestCompressionEnabled);{{/contentCompression}} - + connect(_latestWorker, &{{prefix}}HttpRequestWorker::on_execution_finished, this, &{{classname}}::{{nickname}}Callback); connect(this, &{{classname}}::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -817,7 +817,7 @@ void {{classname}}::{{nickname}}Callback({{prefix}}HttpRequestWorker *worker) { QByteArray array(json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonArray jsonArray = doc.array(); - foreach (QJsonValue obj, jsonArray) { + for (QJsonValue obj : jsonArray) { {{{returnBaseType}}} val; ::{{cppNamespace}}::fromJsonValue(val, obj); {{#uniqueItems}} @@ -841,7 +841,7 @@ void {{classname}}::{{nickname}}Callback({{prefix}}HttpRequestWorker *worker) { QByteArray array(json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject obj = doc.object(); - foreach (QString key, obj.keys()) { + for (QString key : obj.keys()) { {{returnBaseType}} val; ::{{cppNamespace}}::fromJsonValue(val, obj[key]); output.insert(key, val); @@ -917,8 +917,8 @@ void {{classname}}::{{nickname}}Callback({{prefix}}HttpRequestWorker *worker) { {{/operation}} {{/operations}} void {{classname}}::tokenAvailable(){ - - oauthToken token; + + oauthToken token; switch (_OauthMethod) { case 1: //implicit flow token = _implicitFlow.getToken(_latestScope.join(" ")); @@ -936,7 +936,7 @@ void {{classname}}::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _authFlow.removeToken(_latestScope.join(" ")); + _authFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -946,7 +946,7 @@ void {{classname}}::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -956,7 +956,7 @@ void {{classname}}::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.cpp.mustache index 7d4ec2b44f..1573bc654e 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.cpp.mustache @@ -329,8 +329,7 @@ void ReplyServer::read() QMap queryParams; - QPair tokenPair; - foreach (tokenPair, tokens) { + for (auto tokenPair : tokens) { QString key = QUrl::fromPercentEncoding(QByteArray().append(tokenPair.first.trimmed().toLatin1())); QString value = QUrl::fromPercentEncoding(QByteArray().append(tokenPair.second.trimmed().toLatin1())); queryParams.insert(key, value); diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/README.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/README.mustache new file mode 100644 index 0000000000..0dc00706b1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/README.mustache @@ -0,0 +1,23 @@ +# REST API Server for {{appName}} + +## Overview +This API Server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. +It uses the [Restbed](https://github.com/Corvusoft/restbed) Framework. + + +## Installation +Put the package under your project folder and import the API stubs. +You need to complete the server stub, as it needs to be connected to a source. + + +## Libraries required +boost_system +ssl (if Restbed was built with SSL Support) +crypto +pthread +restbed + + +## Namespaces +{{{apiPackage}}} +{{{modelPackage}}} diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-header.mustache new file mode 100644 index 0000000000..80c7b0d4dd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-header.mustache @@ -0,0 +1,203 @@ +{{>licenseInfo}} +{{#operations}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef {{classname}}_H_ +#define {{classname}}_H_ + +{{{defaultInclude}}} +#include +#include +#include + +#include +#include +#include +#include +#include + +{{#imports}}{{{import}}} +{{/imports}} + +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +using namespace {{modelNamespace}}; + +/// +/// Exception to flag problems in the handlers +/// +class {{declspec}} {{classname}}Exception: public std::exception +{ +public: + {{classname}}Exception(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +{{#operation}} +///

        +/// {{summary}} +/// +/// +/// {{notes}} +/// +class {{declspec}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource: public restbed::Resource +{ +public: + {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context = "{{contextPath}}"); + virtual ~{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual {{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); + + {{#vendorExtensions.x-codegen-other-methods}} + virtual {{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); + {{/vendorExtensions.x-codegen-other-methods}} + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + {{#hasPathParams}} + {{#pathParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getPathParam_{{{paramName}}}(const std::shared_ptr& request) + { + return request->get_path_parameter("{{{paramName}}}", {{{defaultValue}}}); + } + + {{/isPrimitiveType}} + {{/pathParams}} + {{/hasPathParams}} + {{#hasQueryParams}} + {{#queryParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getQueryParam_{{{paramName}}}(const std::shared_ptr& request) + { + return request->get_query_parameter("{{{paramName}}}", {{{defaultValue}}}); + } + + {{/isPrimitiveType}} + {{/queryParams}} + {{/hasQueryParams}} + {{#hasHeaderParams}} + {{#headerParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getHeader_{{{baseName}}}(const std::shared_ptr& request) + { + return request->get_header("{{baseName}}", {{{defaultValue}}}); + } + + {{/isPrimitiveType}} + {{/headerParams}} + {{/hasHeaderParams}} + + {{#vendorExtensions.x-codegen-other-methods}} + {{#hasPathParams}} + {{#pathParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getPathParam_{{{paramName}}}_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("{{{paramName}}}", {{{defaultValue}}}); + } + {{/isPrimitiveType}} + {{/pathParams}} + {{/hasPathParams}} + {{#hasQueryParams}} + {{#queryParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getQueryParam_{{{paramName}}}_x_extension(const std::shared_ptr& request) + { + return request->get_query_parameter("{{{paramName}}}", {{{defaultValue}}}); + } + {{/isPrimitiveType}} + {{/queryParams}} + {{/hasQueryParams}} + {{#hasHeaderParams}} + {{#headerParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getHeader_{{{baseName}}}_x_extension(const std::shared_ptr& request) + { + return request->get_header("{{baseName}}", {{{defaultValue}}}); + } + {{/isPrimitiveType}} + {{/headerParams}} + {{/hasHeaderParams}} + {{/vendorExtensions.x-codegen-other-methods}} + + virtual std::pair handle{{classname}}Exception(const {{classname}}Exception& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_{{httpMethod}}_internal(const std::shared_ptr session); + {{#vendorExtensions.x-codegen-other-methods}} + void handler_{{httpMethod}}_internal(const std::shared_ptr session); + {{/vendorExtensions.x-codegen-other-methods}} +}; + + +{{/operation}} + +// +// The restbed service to actually implement the REST server +// +class {{declspec}} {{classname}} +{ +public: + explicit {{classname}}(std::shared_ptr const& restbedService); + virtual ~{{classname}}(); + + {{#operation}} + virtual void set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource); + {{/operation}} + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + {{#operation}} + std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource; + {{/operation}} + +private: + std::shared_ptr m_service; +}; + + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} + +#endif /* {{classname}}_H_ */ + +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-source.mustache new file mode 100644 index 0000000000..6a9c99ab28 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-source.mustache @@ -0,0 +1,400 @@ +{{>licenseInfo}} +{{#operations}} + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "{{classname}}.h" + +{{#apiNamespaceDeclarations}} +namespace {{this}} { +{{/apiNamespaceDeclarations}} + +using namespace {{modelNamespace}}; + +{{classname}}Exception::{{classname}}Exception(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int {{classname}}Exception::getStatus() const +{ + return m_status; +} +const char* {{classname}}Exception::what() const noexcept +{ + return m_what.c_str(); +} + + +template +std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = std::make_shared(pt); + return model; +} + +template +std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector>(); + for (const auto& child: pt) { + arrayRet.emplace_back(std::make_shared(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +{{#operation}} +{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context /* = "{{contextPath}}" */) +{ + this->set_path(context + "{{path}}"); + this->set_method_handler("{{httpMethod}}", + std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this, + std::placeholders::_1)); + {{#vendorExtensions.x-codegen-other-methods}} + this->set_method_handler("{{httpMethod}}", + std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this, + std::placeholders::_1)); + {{/vendorExtensions.x-codegen-other-methods}} +} + +{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::~{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource() +{ +} + +std::pair {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handle{{classname}}Exception(const {{classname}}Exception& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + {{#hasBodyParam}} + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + {{#allParams}} + {{#isModel}} + auto {{paramName}} = extractJsonModelBodyParam<{{{baseType}}}>(bodyContent); + {{/isModel}} + {{#isArray}} + auto {{paramName}} = extractJsonArrayBodyParam<{{{baseType}}}>(bodyContent); + {{/isArray}} + {{/allParams}} + {{/hasBodyParam}} + + {{#hasPathParams}} + // Getting the path params + {{#pathParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getPathParam_{{paramName}}(request); + {{/isPrimitiveType}} + {{/pathParams}} + {{/hasPathParams}} + + {{#hasQueryParams}} + // Getting the query params + {{#queryParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getQueryParam_{{paramName}}(request); + {{/isPrimitiveType}} + {{/queryParams}} + {{/hasQueryParams}} + + {{#hasHeaderParams}} + // Getting the headers + {{#headerParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getHeader_{{baseName}}(request); + {{/isPrimitiveType}} + {{/headerParams}} + {{/hasHeaderParams}} + + int status_code = 500; + {{#returnType}} + {{{.}}} resultObject = {{{defaultResponse}}}; + {{/returnType}} + std::string result = ""; + + try { + {{#returnType}} + std::tie(status_code, resultObject) = + {{/returnType}} + {{^returnType}} + status_code = + {{/returnType}} + handler_{{httpMethod}}({{#allParams}}{{paramName}}{{^-last}}, {{ / -last}}{{ / allParams}}); + } + catch(const {{classname}}Exception& e) { + std::tie(status_code, result) = handle{{classname}}Exception(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + {{#responses}} + if (status_code == {{code}}) { + {{#returnType}} + {{#isModel}} + {{#isString}} + result = resultObject; + {{/isString}} + {{^isString}} + result = resultObject->toJsonString(); + {{/isString}} + {{/isModel}} + {{#isMap}} + result = convertMapResponse(resultObject); + {{/isMap}} + {{/returnType}} + {{#headers}} + // Description: {{{description}}} + setResponseHeader(session, "{{baseName}}"); + {{/headers}} + + {{#primitiveType}} + const constexpr auto contentType = "text/plain"; + {{/primitiveType}} + {{^primitiveType}} + const constexpr auto contentType = "application/json"; + {{/primitiveType}} + returnResponse(session, {{code}}, result.empty() ? "{{message}}" : result, contentType); + return; + } + {{/responses}} + defaultSessionClose(session, status_code, result); +} + +{{#vendorExtensions.x-codegen-other-methods}} +// x-extension +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + {{#hasBodyParam}} + std::string bodyContent = extractBodyContent(session); + + // body params or form params here from the body content string + {{#allParams}} + {{#isModel}} + auto {{paramName}} = extractJsonModelBodyParam<{{{baseType}}}>(bodyContent); + {{/isModel}} + {{#isArray}} + auto {{paramName}} = extractJsonArrayBodyParam<{{{baseType}}}>(bodyContent); + {{/isArray}} + {{^isModel}} + {{^isArray}} + auto {{paramName}} = std::make_shared<{{{baseType}}}>(bodyContent); + {{/isArray}} + {{/isModel}} + {{/allParams}} + {{/hasBodyParam}} + + {{#hasPathParams}} + // Getting the path params + {{#pathParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getPathParam_{{paramName}}_x_extension(request); + + {{/isPrimitiveType}} + {{/pathParams}} + {{/hasPathParams}} + {{#hasQueryParams}} + // Getting the query params + {{#queryParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getQueryParam_{{paramName}}_x_extension(request); + + {{/isPrimitiveType}} + {{/queryParams}} + {{/hasQueryParams}} + {{#hasHeaderParams}} + // Getting the headers + {{#headerParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getHeader_{{baseName}}_x_extension(request); + + {{/isPrimitiveType}} + {{/headerParams}} + {{/hasHeaderParams}} + + int status_code = 500; + {{#returnType}} + {{{.}}} resultObject = {{{defaultResponse}}}; + {{/returnType}} + std::string result = ""; + + try { + {{#returnType}} + std::tie(status_code, resultObject) = + {{/returnType}} + {{^returnType}} + status_code = + {{/returnType}} + handler_{{httpMethod}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + } + catch(const {{classname}}Exception& e) { + std::tie(status_code, result) = handle{{classname}}Exception(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + {{#responses}} + if (status_code == {{code}}) { + {{#returnType}} + {{#isModel}} + {{#isString}} + result = resultObject; + {{/isString}} + {{^isString}} + result = resultObject->toJsonString(); + {{/isString}} + {{/isModel}} + {{#isMap}} + result = convertMapResponse(resultObject); + {{/isMap}} + {{/returnType}} + {{#headers}} + // Description: {{{description}}} + setResponseHeader(session, "{{baseName}}"); + {{/headers}} + + {{#primitiveType}} + const constexpr auto contentType = "text/plain"; + {{/primitiveType}} + {{^primitiveType}} + const constexpr auto contentType = "application/json"; + {{/primitiveType}} + returnResponse(session, {{code}}, result.empty() ? "{{message}}" : result, contentType); + return; + } + {{/responses}} + defaultSessionClose(session, status_code, result); +} +{{/vendorExtensions.x-codegen-other-methods}} + +{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) +{ + throw {{classname}}Exception(501, "Not implemented"); +} + +{{#vendorExtensions.x-codegen-other-methods}} +{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) +{ + throw {{classname}}Exception(501, "Not implemented"); +} +{{/vendorExtensions.x-codegen-other-methods}} + +std::string {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +{{/operation}} + +{{classname}}::{{classname}}(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +{{classname}}::~{{classname}}() {} + +{{#operation}} +void {{classname}}::set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource) { + m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource = sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource; + m_service->publish(m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource); +} +{{/operation}} + + +void {{classname}}::publishDefaultResources() { + {{#operation}} + if (!m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource) { + set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::make_shared<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource>()); + } + {{/operation}} +} + +std::shared_ptr {{classname}}::service() { + return m_service; +} + + +{{#apiNamespaceDeclarations}} +} +{{/apiNamespaceDeclarations}} + +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/python/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/git_push.sh.mustache old mode 100755 new mode 100644 similarity index 100% rename from modules/openapi-generator/src/main/resources/python/git_push.sh.mustache rename to modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/git_push.sh.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/gitignore.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/gitignore.mustache new file mode 100644 index 0000000000..4581ef2eee --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/gitignore.mustache @@ -0,0 +1,29 @@ +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/licenseInfo.mustache new file mode 100644 index 0000000000..85213c8b15 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} + * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI-Generator {{{generatorVersion}}}. + * https://openapi-generator.tech + * Do not edit the class manually. + */ diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/model-header.mustache new file mode 100644 index 0000000000..2568ccb676 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/model-header.mustache @@ -0,0 +1,98 @@ +{{>licenseInfo}} +{{#models}}{{#model}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef {{classname}}_H_ +#define {{classname}}_H_ + +{{{defaultInclude}}} + +{{#imports}}{{{this}}} +{{/imports}} +#include +#include +{{#hasEnums}} +#include +{{/hasEnums}} +#include + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +/// +/// {{description}} +/// +{{#circularReferences}} +class {{{this}}}; +{{/circularReferences}} +class {{declspec}} {{classname}} {{#interfaces}}{{#-first}}:{{/-first}}{{^-first}},{{/-first}} public {{{this}}}{{/interfaces}} +{ +public: + {{classname}}() = default; + explicit {{classname}}(boost::property_tree::ptree const& pt); + virtual ~{{classname}}() = default; + + std::string toJsonString(bool prettyJson = false); + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree(); + void fromPropertyTree(boost::property_tree::ptree const& pt); + + ///////////////////////////////////////////// + /// {{classname}} members + {{#vars}} + + /// + /// {{description}} + /// + {{{dataType}}} {{getter}}() const; + void {{setter}}({{{dataType}}} value); + {{/vars}} + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + {{#vars}} + {{^isContainer}} + {{^isModel}} + {{{dataType}}} m_{{name}} = {{{defaultValue}}}; + {{/isModel}} + {{#isModel}} + {{{dataType}}} m_{{name}}; + {{/isModel}} + {{/isContainer}} + {{#isContainer}} + {{{dataType}}} m_{{name}}; + {{/isContainer}} + {{/vars}} + {{#vars}} + {{#isEnum}} + const std::array m_{{enumName}} = { + {{#allowableValues}}{{#enumVars}}"{{{value}}}"{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} + }; + + {{/isEnum}} + {{/vars}} +}; + +std::vector<{{classname}}> create{{classname}}VectorFromJsonString(const std::string& json); + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +#endif /* {{classname}}_H_ */ +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/model-source.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/model-source.mustache new file mode 100644 index 0000000000..395e415c6b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/model-source.mustache @@ -0,0 +1,233 @@ +{{>licenseInfo}} +{{#models}}{{#model}} + +#include "{{classname}}.h" + +#include +#include +#include +#include +{{#hasEnums}} +#include +{{/hasEnums}} +#include +#include + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +{{classname}}::{{classname}}(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + +std::string {{classname}}::toJsonString(bool prettyJson /* = false */) +{ + return toJsonString_internal(prettyJson); +} + +void {{classname}}::fromJsonString(std::string const& jsonString) +{ + fromJsonString_internal(jsonString); +} + +boost::property_tree::ptree {{classname}}::toPropertyTree() +{ + return toPropertyTree_internal(); +} + +void {{classname}}::fromPropertyTree(boost::property_tree::ptree const& pt) +{ + fromPropertyTree_internal(pt); +} + +std::string {{classname}}::toJsonString_internal(bool prettyJson) +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + return ss.str(); +} + +void {{classname}}::fromJsonString_internal(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree {{classname}}::toPropertyTree_internal() +{ + ptree pt; + ptree tmp_node; + {{#vars}} + {{^isContainer}} + {{#isPrimitiveType}} + pt.put("{{baseName}}", m_{{name}}); + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isString}} + pt.put("{{baseName}}", m_{{name}}); + {{/isString}} + {{#isDate}} + pt.put("{{baseName}}", m_{{name}}); + {{/isDate}} + {{#isDateTime}} + pt.put("{{baseName}}", m_{{name}}); + {{/isDateTime}} + {{#isModel}} + if (m_{{name}} != nullptr) { + pt.add_child("{{baseName}}", m_{{name}}->toPropertyTree()); + } + {{/isModel}} + {{/isPrimitiveType}} + {{/isContainer}} + {{#isContainer}} + // generate tree for {{name}} + if (!m_{{name}}.empty()) { + for (const auto &childEntry : m_{{name}}) { + {{#items}} + {{#isModel}} + tmp_node.push_back(std::make_pair("", childEntry->toPropertyTree())); + {{/isModel}} + {{^isModel}} + ptree {{name}}_node; + {{name}}_node.put("", childEntry); + tmp_node.push_back(std::make_pair("", {{name}}_node)); + {{/isModel}} + {{/items}} + } + pt.add_child("{{baseName}}", tmp_node); + tmp_node.clear(); + } + {{/isContainer}} + {{/vars}} + return pt; +} + +void {{classname}}::fromPropertyTree_internal(ptree const &pt) +{ + ptree tmp_node; + {{#vars}} + {{^isContainer}} + {{^isEnum}} + {{#isPrimitiveType}} + m_{{name}} = pt.get("{{baseName}}", {{{defaultValue}}}); + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isString}} + m_{{name}} = pt.get("{{baseName}}", {{{defaultValue}}}); + {{/isString}} + {{#isDate}} + m_{{name}} = pt.get("{{baseName}}", {{{defaultValue}}}); + {{/isDate}} + {{#isDateTime}} + m_{{name}} = pt.get("{{baseName}}", {{{defaultValue}}}); + {{/isDateTime}} + {{/isPrimitiveType}} + {{/isEnum}} + {{#isEnum}} + {{setter}}(pt.get("{{baseName}}", {{{defaultValue}}})); + {{/isEnum}} + {{#isModel}} + if (pt.get_child_optional("{{baseName}}")) { + m_{{name}} = {{{defaultValue}}}; + m_{{name}}->fromPropertyTree(pt.get_child("{{baseName}}")); + } + {{/isModel}} + {{/isContainer}} + {{#isContainer}} + {{^isModelContainer}} + // push all items of {{name}} into member vector + if (pt.get_child_optional("{{baseName}}")) { + for (const auto &childTree : pt.get_child("{{baseName}}")) { + {{#mostInnerItems}} + {{{dataType}}} val = + {{#isNumeric}} + {{^isFloat}} + {{^isLong}} + {{^isInteger}} + std::stod(childTree.second.data()); + {{/isInteger}} + {{/isLong}} + {{/isFloat}} + {{#isDouble}} + std::stod(childTree.second.data()); + {{/isDouble}} + {{#isFloat}} + std::stof(childTree.second.data()); + {{/isFloat}} + {{#isInteger}} + std::stoi(childTree.second.data()); + {{/isInteger}} + {{#isLong}} + std::stol(childTree.second.data()); + {{/isLong}} + {{/isNumeric}} + {{#isString}} + childTree.second.data(); + {{/isString}} + {{#isModel}} + std::make_shared<{{baseType}}>(childTree.second); + {{/isModel}} + m_{{name}}.emplace_back(std::move(val)); + {{/mostInnerItems}} + } + } + {{/isModelContainer}} + {{#isModelContainer}} + // generate new {{complexType}} Object for each item and assign it to the current + if (pt.get_child_optional("{{baseName}}")) { + for (const auto &childTree : pt.get_child("{{baseName}}")) { + {{#mostInnerItems}} + m_{{name}}.emplace_back({{{defaultValue}}}); + m_{{name}}.back()->fromPropertyTree(childTree.second); + {{/mostInnerItems}} + } + } + {{/isModelContainer}} + {{/isContainer}} + {{/vars}} +} + +{{#vars}} +{{{dataType}}} {{classname}}::{{getter}}() const +{ + return m_{{name}}; +} + +void {{classname}}::{{setter}}({{{dataType}}} value) +{ + {{#isEnum}}if (std::find(m_{{enumName}}.begin(), m_{{enumName}}.end(), value) != m_{{enumName}}.end()) { + {{/isEnum}}m_{{name}} = value;{{#isEnum}} + } else { + throw std::runtime_error("Value " + value + " not allowed"); + }{{/isEnum}} +} +{{/vars}} + +std::vector<{{classname}}> create{{classname}}VectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector<{{{classname}}}>(); + for (const auto& child: pt) { + vec.emplace_back({{{classname}}}(child.second)); + } + + return vec; +} + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/CMakeLists.txt.mustache new file mode 100644 index 0000000000..1ab7dc0f7f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/CMakeLists.txt.mustache @@ -0,0 +1,34 @@ +set(TARGET_NAME {{{apiPackage}}}Stubs) + +# Get generated filenames +file(STRINGS "${CMAKE_CURRENT_LIST_DIR}/.openapi-generator/FILES" GENERATED_SOURCES) +list(FILTER GENERATED_SOURCES INCLUDE REGEX ".*cpp$") + +set(GENERATED_SOURCES_INCLUDE_DIRS + ${CMAKE_CURRENT_LIST_DIR}/model + ${CMAKE_CURRENT_LIST_DIR}/api + ${CMAKE_CURRENT_LIST_DIR} +) + + +add_library(${TARGET_NAME} SHARED) + +target_sources(${TARGET_NAME} + PRIVATE + ${GENERATED_SOURCES}) + +target_include_directories(${TARGET_NAME} + PUBLIC + ${GENERATED_SOURCES_INCLUDE_DIRS} +) + + +target_include_directories(${TARGET_NAME} + SYSTEM PUBLIC + ${restbed_SOURCE_DIR}/source) + +target_link_libraries(${TARGET_NAME} + PUBLIC + Boost::system + restbed-shared + -lpthread) diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/FindRestbedAndBoost.cmake b/modules/openapi-generator/src/main/resources/cpp-restbed-server/FindRestbedAndBoost.cmake new file mode 100644 index 0000000000..630464c6fe --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/FindRestbedAndBoost.cmake @@ -0,0 +1,22 @@ + +include(FetchContent) + +## Restbed +FetchContent_Declare( + restbed + GIT_REPOSITORY https://github.com/Corvusoft/restbed + GIT_TAG 4.7 +) + +FetchContent_MakeAvailable(restbed) + +FetchContent_GetProperties(restbed) +if(NOT restbed_POPULATED) + + FetchContent_Populate(restbed) + add_subdirectory(${restbed_SOURCE_DIR} ${restbed_BINARY_DIR}) +endif() + + +## Boost +find_package(Boost 1.7.0 COMPONENTS system REQUIRED) diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/README.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/README.mustache index 0dc00706b1..60d33765d4 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/README.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/README.mustache @@ -21,3 +21,50 @@ restbed ## Namespaces {{{apiPackage}}} {{{modelPackage}}} + + +## Example + +The handler functionality can be implemented in two different ways. +Either inherit the given resource and override the handler methods. +Or set a handler lambda to a resource. + +This example shows how this can be done with the pet store API. + +``` +#include "api/StoreApi.h" +#include "api/UserApi.h" + +using namespace org::openapitools::server::api; +using namespace org::openapitools::server::api::StoreApiResources; +using namespace org::openapitools::server::api::UserApiResources; + +/* 1. variant: inherit from the resource and override handler method */ +class MyStoreApiStoreOrderResource : public StoreOrderResource { +public: + std::pair + handler_POST(Order &order) override { + auto ret = Order(); + /* ... add your implementation here .... */ + return std::make_pair(200, ret); + } +}; + +int main() { + const auto service = std::make_shared(); + + auto storeApi = StoreApi(service); + storeApi.setResource(std::make_shared()); + + auto userApi = UserApi(service); + /* 2. variant: implement handler as lambda */ + userApi.getUserResource()->handler_POST_func = [](auto& user) { + /* ... add your implementation here .... */ + return 200;}; + + const auto settings = std::make_shared(); + settings->set_port(1236); + + service->start(settings); +} +``` diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache index 80c7b0d4dd..b2c7dccf57 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -44,6 +45,7 @@ private: std::string m_what; }; +namespace {{classname}}Resources { {{#operation}} /// /// {{summary}} @@ -51,23 +53,47 @@ private: /// /// {{notes}} /// -class {{declspec}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource: public restbed::Resource +class {{declspec}} {{vendorExtensions.x-codegen-resource-name}}Resource: public restbed::Resource { public: - {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context = "{{contextPath}}"); - virtual ~{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(); + {{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context = "{{contextPath}}"); + virtual ~{{vendorExtensions.x-codegen-resource-name}}Resource() = default; + + {{vendorExtensions.x-codegen-resource-name}}Resource( + const {{vendorExtensions.x-codegen-resource-name}}Resource& other) = default; // copy constructor + {{vendorExtensions.x-codegen-resource-name}}Resource({{vendorExtensions.x-codegen-resource-name}}Resource&& other) noexcept = default; // move constructor + + {{vendorExtensions.x-codegen-resource-name}}Resource& operator=(const {{vendorExtensions.x-codegen-resource-name}}Resource& other) = default; // copy assignment + {{vendorExtensions.x-codegen-resource-name}}Resource& operator=({{vendorExtensions.x-codegen-resource-name}}Resource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function<{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}}( + {{#allParams}}{{{dataType}}} & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}})> handler_{{httpMethod}}_func = + []({{#allParams}}{{{dataType}}} &{{^-last}}, {{/-last}}{{/allParams}}) -> {{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} + { throw {{classname}}Exception(501, "Not implemented"); }; + + {{#vendorExtensions.x-codegen-other-methods}} + std::function<{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}}( + {{#allParams}}{{{dataType}}} & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}})> handler_{{httpMethod}}_func = + []({{#allParams}}{{{dataType}}} &{{^-last}}, {{/-last}}{{/allParams}}) -> {{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} + { throw {{classname}}Exception(501, "Not implemented"); }; + + {{/vendorExtensions.x-codegen-other-methods}} protected: ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // ////////////////////////////////////////////////////////// virtual {{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} handler_{{httpMethod}}( - {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#allParams}}{{{dataType}}} & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); {{#vendorExtensions.x-codegen-other-methods}} virtual {{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} handler_{{httpMethod}}( - {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#allParams}}{{{dataType}}} & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); {{/vendorExtensions.x-codegen-other-methods}} protected: @@ -76,73 +102,7 @@ protected: ////////////////////////////////////// virtual std::string extractBodyContent(const std::shared_ptr& session); - - {{#hasPathParams}} - {{#pathParams}} - {{#isPrimitiveType}} - virtual {{{dataType}}} getPathParam_{{{paramName}}}(const std::shared_ptr& request) - { - return request->get_path_parameter("{{{paramName}}}", {{{defaultValue}}}); - } - - {{/isPrimitiveType}} - {{/pathParams}} - {{/hasPathParams}} - {{#hasQueryParams}} - {{#queryParams}} - {{#isPrimitiveType}} - virtual {{{dataType}}} getQueryParam_{{{paramName}}}(const std::shared_ptr& request) - { - return request->get_query_parameter("{{{paramName}}}", {{{defaultValue}}}); - } - - {{/isPrimitiveType}} - {{/queryParams}} - {{/hasQueryParams}} - {{#hasHeaderParams}} - {{#headerParams}} - {{#isPrimitiveType}} - virtual {{{dataType}}} getHeader_{{{baseName}}}(const std::shared_ptr& request) - { - return request->get_header("{{baseName}}", {{{defaultValue}}}); - } - - {{/isPrimitiveType}} - {{/headerParams}} - {{/hasHeaderParams}} - - {{#vendorExtensions.x-codegen-other-methods}} - {{#hasPathParams}} - {{#pathParams}} - {{#isPrimitiveType}} - virtual {{{dataType}}} getPathParam_{{{paramName}}}_x_extension(const std::shared_ptr& request) - { - return request->get_path_parameter("{{{paramName}}}", {{{defaultValue}}}); - } - {{/isPrimitiveType}} - {{/pathParams}} - {{/hasPathParams}} - {{#hasQueryParams}} - {{#queryParams}} - {{#isPrimitiveType}} - virtual {{{dataType}}} getQueryParam_{{{paramName}}}_x_extension(const std::shared_ptr& request) - { - return request->get_query_parameter("{{{paramName}}}", {{{defaultValue}}}); - } - {{/isPrimitiveType}} - {{/queryParams}} - {{/hasQueryParams}} - {{#hasHeaderParams}} - {{#headerParams}} - {{#isPrimitiveType}} - virtual {{{dataType}}} getHeader_{{{baseName}}}_x_extension(const std::shared_ptr& request) - { - return request->get_header("{{baseName}}", {{{defaultValue}}}); - } - {{/isPrimitiveType}} - {{/headerParams}} - {{/hasHeaderParams}} - {{/vendorExtensions.x-codegen-other-methods}} + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); virtual std::pair handle{{classname}}Exception(const {{classname}}Exception& e); virtual std::pair handleStdException(const std::exception& e); @@ -151,9 +111,8 @@ protected: virtual void setResponseHeader(const std::shared_ptr& session, const std::string& header); - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); + const int status, const std::string& result, std::multimap& contentType); virtual void defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result); @@ -164,7 +123,11 @@ private: {{/vendorExtensions.x-codegen-other-methods}} }; +{{/operation}} +} /* namespace {{classname}}Resources */ +{{#operation}} +using {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource [[deprecated]] = {{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource; {{/operation}} // @@ -177,7 +140,15 @@ public: virtual ~{{classname}}(); {{#operation}} - virtual void set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource); + std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> get{{vendorExtensions.x-codegen-resource-name}}Resource(); + {{/operation}} + + {{#operation}} + void setResource(std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> resource); + {{/operation}} + {{#operation}} + [[deprecated("use setResource()")]] + virtual void set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource); {{/operation}} virtual void publishDefaultResources(); @@ -186,7 +157,7 @@ public: protected: {{#operation}} - std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource; + std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> m_sp{{vendorExtensions.x-codegen-resource-name}}Resource; {{/operation}} private: diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source-HandlerBody.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source-HandlerBody.mustache new file mode 100644 index 0000000000..811d07845f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source-HandlerBody.mustache @@ -0,0 +1,167 @@ +const auto request = session->get_request(); +{{#hasBodyParam}} +// body params or form params here from the body content string +std::string bodyContent = extractBodyContent(session); +{{#bodyParams}} +{{#isModel}} +auto {{paramName}} = extractJsonModelBodyParam<{{{baseType}}}>(bodyContent); +{{/isModel}} +{{#isArray}} +auto {{paramName}} = extractJsonArrayBodyParam<{{{baseType}}}>(bodyContent); +{{/isArray}} +{{#isMap}} +{{{dataType}}} {{paramName}}; // TODO +{{/isMap}} +{{^isModel}} +{{^isArray}} +{{^isMap}} +auto {{paramName}} = boost::lexical_cast<{{{dataType}}}>(bodyContent); +{{/isMap}} +{{/isArray}} +{{/isModel}} +{{/bodyParams}} +{{/hasBodyParam}} +{{#hasFormParams}} +{{#formParams}} +{{#isContainer}} +std::string {{{paramName}}}_raw = extractFormParamsFromBody("{{paramName}}", extractBodyContent(session)); +{{{dataType}}} {{{paramName}}}; +boost::split({{{paramName}}}, {{{paramName}}}_raw, boost::is_any_of(",")); +{{/isContainer}} +{{^isContainer}} +auto {{paramName}} = boost::lexical_cast<{{{dataType}}}>(extractFormParamsFromBody("{{paramName}}", extractBodyContent(session))); +{{/isContainer}} +{{/formParams}} +{{/hasFormParams}} +{{#hasPathParams}} +// Getting the path params +{{#pathParams}} +{{#isPrimitiveType}} +{{{dataType}}} {{{paramName}}} = request->get_path_parameter("{{{baseName}}}", {{{defaultValue}}}); +{{/isPrimitiveType}} +{{/pathParams}} +{{/hasPathParams}} +{{#hasQueryParams}} +// Getting the query params +{{#queryParams}} +{{#isPrimitiveType}} +{{{dataType}}} {{{paramName}}} = request->get_query_parameter("{{{paramName}}}", {{{defaultValue}}}); +{{/isPrimitiveType}} +{{^isPrimitiveType}} +{{#isArray}} +std::string {{{paramName}}}_raw = request->get_query_parameter("{{{paramName}}}"); +{{{dataType}}} {{{paramName}}}; +std::vector {{{paramName}}}_temp; +boost::split({{{paramName}}}_temp, {{{paramName}}}_raw, boost::is_any_of(",")); +{{#items}} +{{#isString}} +std::copy({{{paramName}}}_temp.begin(), {{{paramName}}}_temp.end(), std::inserter({{{paramName}}}, std::next({{{paramName}}}.begin()))); +{{/isString}} +{{^isString}} +std::transform({{{paramName}}}_temp.begin(), {{{paramName}}}_temp.end(), std::back_inserter({{{paramName}}}), [](const auto& i){ {{{dataType}}} ret; ret.fromString(i); return ret;}); +{{/isString}} +{{/items}} +{{/isArray}} +{{#isMap}} +std::stringstream {{{paramName}}}_raw(request->get_query_parameter("{{{paramName}}}")); +boost::property_tree::ptree {{{paramName}}}_pt; +boost::property_tree::json_parser::read_json({{{paramName}}}_raw,{{{paramName}}}_pt); +{{{dataType}}} {{{paramName}}} = {{{defaultValue}}}; +for (auto& item: {{{paramName}}}_pt) { + {{{paramName}}}.emplace(item.first, item.second.get_value<{{{baseType}}}>()); +} +{{/isMap}} +{{/isPrimitiveType}} +{{/queryParams}} +{{/hasQueryParams}} +{{#hasHeaderParams}} +// Getting the headers +{{#headerParams}} +{{#isPrimitiveType}} +{{{dataType}}} {{{paramName}}} = request->get_header("{{{baseName}}}", {{{defaultValue}}}); +{{/isPrimitiveType}} +{{#isContainer}} +std::string {{{paramName}}}_raw = request->get_header("{{{paramName}}}"); +{{{dataType}}} {{{paramName}}}; +boost::split({{{paramName}}}, {{{paramName}}}_raw, boost::is_any_of(",")); +{{/isContainer}} +{{/headerParams}} +{{/hasHeaderParams}} + +int status_code = 500; +{{#returnType}} +{{{.}}} resultObject = {{{defaultResponse}}}; +{{/returnType}} +std::string result = ""; + +try { +{{#returnType}} + std::tie(status_code, resultObject) = +{{/returnType}} +{{^returnType}} + status_code = +{{/returnType}} + handler_{{httpMethod}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); +} +catch(const {{classname}}Exception& e) { + std::tie(status_code, result) = handle{{classname}}Exception(e); +} +catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); +} +catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); +} + +std::multimap< std::string, std::string > responseHeaders {}; +static const std::vector contentTypes{ +{{#hasProduces}} + {{#produces}}"{{{mediaType}}}",{{/produces}} +{{/hasProduces}} +{{^hasProduces}} + "application/json" +{{/hasProduces}} +}; +static const std::string acceptTypes{ +{{#hasConsumes}} + "{{#consumes}}{{{mediaType}}}, {{/consumes}}" +{{/hasConsumes}} +}; + +{{#responses}} +if (status_code == {{code}}) { +{{#is2xx}} + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } +{{/is2xx}} +{{^is2xx}} + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "{{message}}"; +{{/is2xx}} + +{{#returnType}} +{{#isModel}} +{{#isString}} + result = resultObject; +{{/isString}} +{{^isString}} +{{^isMap}} + result = resultObject.toJsonString(); +{{/isMap}} +{{/isString}} +{{/isModel}} +{{#isMap}} + result = convertMapResponse(resultObject); +{{/isMap}} +{{/returnType}} +{{#headers}} + // Description: {{{description}}} + setResponseHeader(session, "{{baseName}}"); +{{/headers}} + returnResponse(session, {{code}}, result.empty() ? "{}" : result, responseHeaders); + return; +} +{{/responses}} +defaultSessionClose(session, status_code, result); diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source.mustache index 6a9c99ab28..37275cd03e 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source.mustache @@ -19,6 +19,32 @@ namespace {{this}} { using namespace {{modelNamespace}}; +namespace { +[[maybe_unused]] +std::string selectPreferredContentType(const std::vector& contentTypes) { + if (contentTypes.size() == 0) { + return "application/json"; + } + + if (contentTypes.size() == 1) { + return contentTypes.at(0); + } + + static const std::array preferredTypes = {"json", "xml"}; + for (const auto& preferredType: preferredTypes) { + const auto ret = std::find_if(contentTypes.cbegin(), + contentTypes.cend(), + [preferredType](const std::string& str) { + return str.find(preferredType) != std::string::npos;}); + if (ret != contentTypes.cend()) { + return *ret; + } + } + + return contentTypes.at(0); +} +} + {{classname}}Exception::{{classname}}Exception(int status_code, std::string what) : m_status(status_code), m_what(what) @@ -36,26 +62,26 @@ const char* {{classname}}Exception::what() const noexcept template -std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) +MODEL_T extractJsonModelBodyParam(const std::string& bodyContent) { std::stringstream sstream(bodyContent); boost::property_tree::ptree pt; boost::property_tree::json_parser::read_json(sstream, pt); - auto model = std::make_shared(pt); + auto model = MODEL_T(pt); return model; } template -std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) +std::vector extractJsonArrayBodyParam(const std::string& bodyContent) { std::stringstream sstream(bodyContent); boost::property_tree::ptree pt; boost::property_tree::json_parser::read_json(sstream, pt); - auto arrayRet = std::vector>(); + auto arrayRet = std::vector(); for (const auto& child: pt) { - arrayRet.emplace_back(std::make_shared(child.second)); + arrayRet.emplace_back(MODEL_T(child.second)); } return arrayRet; } @@ -76,282 +102,85 @@ std::string convertMapResponse(const std::map& map) return result; } +namespace {{classname}}Resources { {{#operation}} -{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context /* = "{{contextPath}}" */) +{{vendorExtensions.x-codegen-resource-name}}Resource::{{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context /* = "{{contextPath}}" */) { this->set_path(context + "{{path}}"); this->set_method_handler("{{httpMethod}}", - std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this, + std::bind(&{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this, std::placeholders::_1)); {{#vendorExtensions.x-codegen-other-methods}} this->set_method_handler("{{httpMethod}}", - std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this, + std::bind(&{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this, std::placeholders::_1)); {{/vendorExtensions.x-codegen-other-methods}} } -{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::~{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource() -{ -} - -std::pair {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handle{{classname}}Exception(const {{classname}}Exception& e) +std::pair {{vendorExtensions.x-codegen-resource-name}}Resource::handle{{classname}}Exception(const {{classname}}Exception& e) { return std::make_pair(e.getStatus(), e.what()); } -std::pair {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handleStdException(const std::exception& e) +std::pair {{vendorExtensions.x-codegen-resource-name}}Resource::handleStdException(const std::exception& e) { return std::make_pair(500, e.what()); } -std::pair {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handleUnspecifiedException() +std::pair {{vendorExtensions.x-codegen-resource-name}}Resource::handleUnspecifiedException() { return std::make_pair(500, "Unknown exception occurred"); } -void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +void {{vendorExtensions.x-codegen-resource-name}}Resource::setResponseHeader(const std::shared_ptr& session, const std::string& header) { session->set_header(header, ""); } -void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +void {{vendorExtensions.x-codegen-resource-name}}Resource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) { - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); } -void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +void {{vendorExtensions.x-codegen-resource-name}}Resource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) { session->close(status, result, { {"Connection", "close"} }); } -void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr session) +void {{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr session) { - const auto request = session->get_request(); - {{#hasBodyParam}} - std::string bodyContent = extractBodyContent(session); + {{#lambda.indented}} + {{>api-source-HandlerBody}} + {{/lambda.indented}} - // Get body params or form params here from the body content string - {{#allParams}} - {{#isModel}} - auto {{paramName}} = extractJsonModelBodyParam<{{{baseType}}}>(bodyContent); - {{/isModel}} - {{#isArray}} - auto {{paramName}} = extractJsonArrayBodyParam<{{{baseType}}}>(bodyContent); - {{/isArray}} - {{/allParams}} - {{/hasBodyParam}} - - {{#hasPathParams}} - // Getting the path params - {{#pathParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = getPathParam_{{paramName}}(request); - {{/isPrimitiveType}} - {{/pathParams}} - {{/hasPathParams}} - - {{#hasQueryParams}} - // Getting the query params - {{#queryParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = getQueryParam_{{paramName}}(request); - {{/isPrimitiveType}} - {{/queryParams}} - {{/hasQueryParams}} - - {{#hasHeaderParams}} - // Getting the headers - {{#headerParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = getHeader_{{baseName}}(request); - {{/isPrimitiveType}} - {{/headerParams}} - {{/hasHeaderParams}} - - int status_code = 500; - {{#returnType}} - {{{.}}} resultObject = {{{defaultResponse}}}; - {{/returnType}} - std::string result = ""; - - try { - {{#returnType}} - std::tie(status_code, resultObject) = - {{/returnType}} - {{^returnType}} - status_code = - {{/returnType}} - handler_{{httpMethod}}({{#allParams}}{{paramName}}{{^-last}}, {{ / -last}}{{ / allParams}}); - } - catch(const {{classname}}Exception& e) { - std::tie(status_code, result) = handle{{classname}}Exception(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - {{#responses}} - if (status_code == {{code}}) { - {{#returnType}} - {{#isModel}} - {{#isString}} - result = resultObject; - {{/isString}} - {{^isString}} - result = resultObject->toJsonString(); - {{/isString}} - {{/isModel}} - {{#isMap}} - result = convertMapResponse(resultObject); - {{/isMap}} - {{/returnType}} - {{#headers}} - // Description: {{{description}}} - setResponseHeader(session, "{{baseName}}"); - {{/headers}} - - {{#primitiveType}} - const constexpr auto contentType = "text/plain"; - {{/primitiveType}} - {{^primitiveType}} - const constexpr auto contentType = "application/json"; - {{/primitiveType}} - returnResponse(session, {{code}}, result.empty() ? "{{message}}" : result, contentType); - return; - } - {{/responses}} - defaultSessionClose(session, status_code, result); } {{#vendorExtensions.x-codegen-other-methods}} // x-extension -void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr session) { +void {{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr session) { + {{#lambda.indented}} + {{>api-source-HandlerBody}} + {{/lambda.indented}} - const auto request = session->get_request(); - {{#hasBodyParam}} - std::string bodyContent = extractBodyContent(session); - - // body params or form params here from the body content string - {{#allParams}} - {{#isModel}} - auto {{paramName}} = extractJsonModelBodyParam<{{{baseType}}}>(bodyContent); - {{/isModel}} - {{#isArray}} - auto {{paramName}} = extractJsonArrayBodyParam<{{{baseType}}}>(bodyContent); - {{/isArray}} - {{^isModel}} - {{^isArray}} - auto {{paramName}} = std::make_shared<{{{baseType}}}>(bodyContent); - {{/isArray}} - {{/isModel}} - {{/allParams}} - {{/hasBodyParam}} - - {{#hasPathParams}} - // Getting the path params - {{#pathParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = getPathParam_{{paramName}}_x_extension(request); - - {{/isPrimitiveType}} - {{/pathParams}} - {{/hasPathParams}} - {{#hasQueryParams}} - // Getting the query params - {{#queryParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = getQueryParam_{{paramName}}_x_extension(request); - - {{/isPrimitiveType}} - {{/queryParams}} - {{/hasQueryParams}} - {{#hasHeaderParams}} - // Getting the headers - {{#headerParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = getHeader_{{baseName}}_x_extension(request); - - {{/isPrimitiveType}} - {{/headerParams}} - {{/hasHeaderParams}} - - int status_code = 500; - {{#returnType}} - {{{.}}} resultObject = {{{defaultResponse}}}; - {{/returnType}} - std::string result = ""; - - try { - {{#returnType}} - std::tie(status_code, resultObject) = - {{/returnType}} - {{^returnType}} - status_code = - {{/returnType}} - handler_{{httpMethod}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); - } - catch(const {{classname}}Exception& e) { - std::tie(status_code, result) = handle{{classname}}Exception(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - {{#responses}} - if (status_code == {{code}}) { - {{#returnType}} - {{#isModel}} - {{#isString}} - result = resultObject; - {{/isString}} - {{^isString}} - result = resultObject->toJsonString(); - {{/isString}} - {{/isModel}} - {{#isMap}} - result = convertMapResponse(resultObject); - {{/isMap}} - {{/returnType}} - {{#headers}} - // Description: {{{description}}} - setResponseHeader(session, "{{baseName}}"); - {{/headers}} - - {{#primitiveType}} - const constexpr auto contentType = "text/plain"; - {{/primitiveType}} - {{^primitiveType}} - const constexpr auto contentType = "application/json"; - {{/primitiveType}} - returnResponse(session, {{code}}, result.empty() ? "{{message}}" : result, contentType); - return; - } - {{/responses}} - defaultSessionClose(session, status_code, result); } {{/vendorExtensions.x-codegen-other-methods}} -{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}( - {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) +{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} {{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) { - throw {{classname}}Exception(501, "Not implemented"); + return handler_{{httpMethod}}_func({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); } {{#vendorExtensions.x-codegen-other-methods}} -{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}( - {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) +{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} {{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) { - throw {{classname}}Exception(501, "Not implemented"); + return handler_{{httpMethod}}_func({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); } {{/vendorExtensions.x-codegen-other-methods}} -std::string {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::extractBodyContent(const std::shared_ptr& session) { +std::string {{vendorExtensions.x-codegen-resource-name}}Resource::extractBodyContent(const std::shared_ptr& session) { const auto request = session->get_request(); int content_length = request->get_header("Content-Length", 0); std::string bodyContent; @@ -363,8 +192,20 @@ std::string {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::e }); return bodyContent; } + +std::string {{vendorExtensions.x-codegen-resource-name}}Resource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} {{/operation}} +} /* namespace {{classname}}Resources */ + {{classname}}::{{classname}}(std::shared_ptr const& restbedService) : m_service(restbedService) { @@ -373,17 +214,31 @@ std::string {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::e {{classname}}::~{{classname}}() {} {{#operation}} -void {{classname}}::set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource) { - m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource = sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource; - m_service->publish(m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource); +std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> {{classname}}::get{{vendorExtensions.x-codegen-resource-name}}Resource() { + if (!m_sp{{vendorExtensions.x-codegen-resource-name}}Resource) { + setResource(std::make_shared<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource>()); + } + return m_sp{{vendorExtensions.x-codegen-resource-name}}Resource; +} +{{/operation}} +{{#operation}} +void {{classname}}::setResource(std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> resource) { + m_sp{{vendorExtensions.x-codegen-resource-name}}Resource = resource; + m_service->publish(m_sp{{vendorExtensions.x-codegen-resource-name}}Resource); +} +{{/operation}} +{{#operation}} +void {{classname}}::set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{vendorExtensions.x-codegen-resource-name}}Resource) { + m_sp{{vendorExtensions.x-codegen-resource-name}}Resource = sp{{vendorExtensions.x-codegen-resource-name}}Resource; + m_service->publish(m_sp{{vendorExtensions.x-codegen-resource-name}}Resource); } {{/operation}} void {{classname}}::publishDefaultResources() { {{#operation}} - if (!m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource) { - set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::make_shared<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource>()); + if (!m_sp{{vendorExtensions.x-codegen-resource-name}}Resource) { + setResource(std::make_shared<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource>()); } {{/operation}} } diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-header.mustache index 2568ccb676..56c16eaa7a 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-header.mustache @@ -18,6 +18,10 @@ #include {{/hasEnums}} #include +{{#interfaces}} +#include "{{{this}}}.h" +{{/interfaces}} +#include "helpers.h" {{#modelNamespaceDeclarations}} namespace {{this}} { @@ -36,13 +40,28 @@ public: explicit {{classname}}(boost::property_tree::ptree const& pt); virtual ~{{classname}}() = default; - std::string toJsonString(bool prettyJson = false); + {{classname}}(const {{classname}}& other) = default; // copy constructor + {{classname}}({{classname}}&& other) noexcept = default; // move constructor + + {{classname}}& operator=(const {{classname}}& other) = default; // copy assignment + {{classname}}& operator=({{classname}}&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; void fromJsonString(std::string const& jsonString); - boost::property_tree::ptree toPropertyTree(); + boost::property_tree::ptree toPropertyTree() const; void fromPropertyTree(boost::property_tree::ptree const& pt); + {{#isEnum}} + std::string toString() const; + void fromString(const std::string& str); + {{/isEnum}} + ///////////////////////////////////////////// /// {{classname}} members + {{#isEnum}} + {{{dataType}}} getEnumValue() const; + void setEnumValue(const {{{dataType}}}& val); + {{/isEnum}} {{#vars}} /// @@ -53,17 +72,9 @@ public: {{/vars}} protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string toJsonString_internal(bool prettyJson = false); - virtual void fromJsonString_internal(std::string const& jsonString); - virtual boost::property_tree::ptree toPropertyTree_internal(); - virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); - - -protected: + {{#isEnum}} + {{{dataType}}} m_{{{name}}}EnumValue; + {{/isEnum}} {{#vars}} {{^isContainer}} {{^isModel}} @@ -77,18 +88,22 @@ protected: {{{dataType}}} m_{{name}}; {{/isContainer}} {{/vars}} - {{#vars}} - {{#isEnum}} - const std::array m_{{enumName}} = { - {{#allowableValues}}{{#enumVars}}"{{{value}}}"{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} - }; - - {{/isEnum}} - {{/vars}} }; std::vector<{{classname}}> create{{classname}}VectorFromJsonString(const std::string& json); +template<> +inline boost::property_tree::ptree toPt<{{classname}}>(const {{classname}}& val) { + return val.toPropertyTree(); +} + +template<> +inline {{classname}} fromPt<{{classname}}>(const boost::property_tree::ptree& pt) { + {{classname}} ret; + ret.fromPropertyTree(pt); + return ret; +} + {{#modelNamespaceDeclarations}} } {{/modelNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-helpers-header.mustache new file mode 100644 index 0000000000..b33cd9e0dd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-helpers-header.mustache @@ -0,0 +1,136 @@ +{{>licenseInfo}} + +#ifndef OPENAPI_MODELS_HELPER_H_ +#define OPENAPI_MODELS_HELPER_H_ + +{{{defaultInclude}}} + +#include +#include +#include +#include + +{{#modelNamespaceDeclarations}} +namespace {{this}} { +{{/modelNamespaceDeclarations}} + +template +boost::property_tree::ptree toPt(const T& val) { + boost::property_tree::ptree pt; + pt.put_value(val); + return pt; +} + +template +boost::property_tree::ptree toPt(const std::vector & vec) { + boost::property_tree::ptree pt; + for (auto &childEntry : vec) { + boost::property_tree::ptree childNode = toPt(childEntry); + pt.push_back(std::make_pair("", childNode)); + } + return pt; +} + +template +boost::property_tree::ptree toPt(const std::map & map) { + boost::property_tree::ptree pt; + for (auto &childEntry : map) { + boost::property_tree::ptree childNode = toPt(childEntry.second); + pt.push_back(boost::property_tree::ptree::value_type(childEntry.first, childNode)); + } + return pt; +} + +template +boost::property_tree::ptree toPt(const std::set & set) { + boost::property_tree::ptree pt; + for (auto &childEntry : set) { + boost::property_tree::ptree childNode = toPt(childEntry); + pt.push_back(std::make_pair("", childNode)); + } + return pt; +} + + +template +struct is_vector +{ + static constexpr bool value = false; +}; + +template +struct is_vector> +{ + static constexpr bool value = true; +}; + +template +struct is_map +{ + static constexpr bool value = false; +}; + +template +struct is_map> +{ + static constexpr bool value = true; +}; + +template +struct is_set +{ + static constexpr bool value = false; +}; + +template +struct is_set> +{ + static constexpr bool value = true; +}; + + +template +std::enable_if_t::value && !is_map::value && !is_set::value, T> +fromPt(const boost::property_tree::ptree& pt) { + return pt.get_value(); +} + +template +std::enable_if_t::value,T> +fromPt(const boost::property_tree::ptree& pt) { + T vec; + for (const auto &child: pt) { + typename T::value_type childElement = fromPt(child.second); + vec.emplace_back(childElement); + } + return vec; +} + +template +std::enable_if_t::value,T> +fromPt(const boost::property_tree::ptree &pt) { + T map; + for (const auto &child: pt) { + using ChildType = typename T::mapped_type; + ChildType childElement = fromPt(child.second); + map.insert(std::make_pair(child.first, childElement)); + } + return map; +} + +template +std::enable_if_t::value,T> +fromPt(const boost::property_tree::ptree& pt) { + T set; + for (const auto &child: pt) { + typename T::value_type childElement = fromPt(child.second); + set.insert(childElement); + } + return set; +} + +{{#modelNamespaceDeclarations}} +} +{{/modelNamespaceDeclarations}} + +#endif /* OPENAPI_MODELS_HELPER_H_ */ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-source.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-source.mustache index 395e415c6b..80f87442b2 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-source.mustache @@ -5,13 +5,17 @@ #include #include +#include #include #include +#include {{#hasEnums}} #include {{/hasEnums}} +#include #include #include +#include "helpers.h" using boost::property_tree::ptree; using boost::property_tree::read_json; @@ -26,34 +30,18 @@ namespace {{this}} { fromPropertyTree(pt); } -std::string {{classname}}::toJsonString(bool prettyJson /* = false */) -{ - return toJsonString_internal(prettyJson); -} -void {{classname}}::fromJsonString(std::string const& jsonString) -{ - fromJsonString_internal(jsonString); -} - -boost::property_tree::ptree {{classname}}::toPropertyTree() -{ - return toPropertyTree_internal(); -} - -void {{classname}}::fromPropertyTree(boost::property_tree::ptree const& pt) -{ - fromPropertyTree_internal(pt); -} - -std::string {{classname}}::toJsonString_internal(bool prettyJson) +std::string {{classname}}::toJsonString(bool prettyJson /* = false */) const { std::stringstream ss; write_json(ss, this->toPropertyTree(), prettyJson); - return ss.str(); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; } -void {{classname}}::fromJsonString_internal(std::string const& jsonString) +void {{classname}}::fromJsonString(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; @@ -61,7 +49,7 @@ void {{classname}}::fromJsonString_internal(std::string const& jsonString) this->fromPropertyTree(pt); } -ptree {{classname}}::toPropertyTree_internal() +ptree {{classname}}::toPropertyTree() const { ptree pt; ptree tmp_node; @@ -81,36 +69,34 @@ ptree {{classname}}::toPropertyTree_internal() pt.put("{{baseName}}", m_{{name}}); {{/isDateTime}} {{#isModel}} - if (m_{{name}} != nullptr) { - pt.add_child("{{baseName}}", m_{{name}}->toPropertyTree()); - } + pt.add_child("{{baseName}}", m_{{name}}.toPropertyTree()); {{/isModel}} {{/isPrimitiveType}} {{/isContainer}} {{#isContainer}} // generate tree for {{name}} + {{#isMap}} + {{^isModel}} + if (!m_{{name}}.empty()) { + tmp_node = toPt(m_{{name}}); + pt.add_child("{{baseName}}", tmp_node); + } + {{/isModel}} + {{/isMap}} + tmp_node.clear(); + {{^isMap}} if (!m_{{name}}.empty()) { - for (const auto &childEntry : m_{{name}}) { - {{#items}} - {{#isModel}} - tmp_node.push_back(std::make_pair("", childEntry->toPropertyTree())); - {{/isModel}} - {{^isModel}} - ptree {{name}}_node; - {{name}}_node.put("", childEntry); - tmp_node.push_back(std::make_pair("", {{name}}_node)); - {{/isModel}} - {{/items}} - } + tmp_node = toPt(m_{{name}}); pt.add_child("{{baseName}}", tmp_node); tmp_node.clear(); } + {{/isMap}} {{/isContainer}} {{/vars}} return pt; } -void {{classname}}::fromPropertyTree_internal(ptree const &pt) +void {{classname}}::fromPropertyTree(ptree const &pt) { ptree tmp_node; {{#vars}} @@ -136,65 +122,58 @@ void {{classname}}::fromPropertyTree_internal(ptree const &pt) {{/isEnum}} {{#isModel}} if (pt.get_child_optional("{{baseName}}")) { - m_{{name}} = {{{defaultValue}}}; - m_{{name}}->fromPropertyTree(pt.get_child("{{baseName}}")); + m_{{{name}}} = fromPt<{{{dataType}}}>(pt.get_child("{{baseName}}")); } {{/isModel}} {{/isContainer}} {{#isContainer}} - {{^isModelContainer}} - // push all items of {{name}} into member vector + {{#isMap}} + if (pt.get_child_optional("{{baseName}}")) { + m_{{{name}}} = fromPt<{{{dataType}}}>(pt.get_child("{{baseName}}")); + } + {{/isMap}} + {{^isMap}} + {{^isModelContainer}} + // push all items of {{name}} into member if (pt.get_child_optional("{{baseName}}")) { - for (const auto &childTree : pt.get_child("{{baseName}}")) { - {{#mostInnerItems}} - {{{dataType}}} val = - {{#isNumeric}} - {{^isFloat}} - {{^isLong}} - {{^isInteger}} - std::stod(childTree.second.data()); - {{/isInteger}} - {{/isLong}} - {{/isFloat}} - {{#isDouble}} - std::stod(childTree.second.data()); - {{/isDouble}} - {{#isFloat}} - std::stof(childTree.second.data()); - {{/isFloat}} - {{#isInteger}} - std::stoi(childTree.second.data()); - {{/isInteger}} - {{#isLong}} - std::stol(childTree.second.data()); - {{/isLong}} - {{/isNumeric}} - {{#isString}} - childTree.second.data(); - {{/isString}} - {{#isModel}} - std::make_shared<{{baseType}}>(childTree.second); - {{/isModel}} - m_{{name}}.emplace_back(std::move(val)); - {{/mostInnerItems}} - } + m_{{{name}}} = fromPt<{{{dataType}}}>(pt.get_child("{{baseName}}")); } - {{/isModelContainer}} - {{#isModelContainer}} - // generate new {{complexType}} Object for each item and assign it to the current - if (pt.get_child_optional("{{baseName}}")) { - for (const auto &childTree : pt.get_child("{{baseName}}")) { - {{#mostInnerItems}} - m_{{name}}.emplace_back({{{defaultValue}}}); - m_{{name}}.back()->fromPropertyTree(childTree.second); - {{/mostInnerItems}} - } - } - {{/isModelContainer}} + {{/isModelContainer}} + {{#isModelContainer}} + // generate new {{complexType}} Object for each item and assign it to the current + if (pt.get_child_optional("{{baseName}}")) { + m_{{{name}}} = fromPt<{{{dataType}}}>(pt.get_child("{{baseName}}")); + } + {{/isModelContainer}} + {{/isMap}} {{/isContainer}} {{/vars}} } +{{#isEnum}} +std::string {{classname}}::toString() const { + return boost::lexical_cast(getEnumValue()); +} + +void {{classname}}::fromString(const std::string& str) { + setEnumValue(boost::lexical_cast<{{{dataType}}}>(str)); +} + +{{{dataType}}} {{classname}}::getEnumValue() const { + return m_{{{name}}}EnumValue; +} + +void {{classname}}::setEnumValue(const {{{dataType}}}& val) { + static const std::array<{{#complexType}}{{{.}}}{{/complexType}}{{^complexType}}{{{dataType}}}{{/complexType}}, {{#allowableValues}}{{#enumVars}}{{#-last}}{{-index}}{{/-last}}{{/enumVars}}{{/allowableValues}}> allowedValues = { + {{#allowableValues}}{{#enumVars}}{{^isNumeric}}"{{/isNumeric}}{{{value}}}{{^isNumeric}}"{{/isNumeric}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} + }; + if (std::find(allowedValues.begin(), allowedValues.end(), val) != allowedValues.end()) { + m_{{{name}}}EnumValue = val; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(val) + " not allowed"); + } +} +{{/isEnum}} {{#vars}} {{{dataType}}} {{classname}}::{{getter}}() const { @@ -203,12 +182,42 @@ void {{classname}}::fromPropertyTree_internal(ptree const &pt) void {{classname}}::{{setter}}({{{dataType}}} value) { - {{#isEnum}}if (std::find(m_{{enumName}}.begin(), m_{{enumName}}.end(), value) != m_{{enumName}}.end()) { - {{/isEnum}}m_{{name}} = value;{{#isEnum}} + {{#isEnum}} + static const std::array<{{#complexType}}{{{.}}}{{/complexType}}{{^complexType}}{{{dataType}}}{{/complexType}}, {{#allowableValues}}{{#enumVars}}{{#-last}}{{-index}}{{/-last}}{{/enumVars}}{{/allowableValues}}> allowedValues = { + {{#allowableValues}}{{#enumVars}}{{^isNumeric}}"{{/isNumeric}}{{{value}}}{{^isNumeric}}"{{/isNumeric}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} + }; + + {{#isContainer}} + {{#isMap}} + for (const auto &v: value) { + if (std::find(allowedValues.begin(), allowedValues.end(), v.first) == allowedValues.end()) { + throw std::runtime_error("Value " + boost::lexical_cast(v.first) + " not allowed"); + } + } + m_{{name}} = value; + {{/isMap}} + {{^isMap}} + for (const auto &v: value) { + if (std::find(allowedValues.begin(), allowedValues.end(), v) == allowedValues.end()) { + throw std::runtime_error("Value " + boost::lexical_cast(v) + " not allowed"); + } + } + {{/isMap}} + {{/isContainer}} + {{^isContainer}} + if (std::find(allowedValues.begin(), allowedValues.end(), value) != allowedValues.end()) { + m_{{name}} = value; } else { - throw std::runtime_error("Value " + value + " not allowed"); - }{{/isEnum}} + throw std::runtime_error("Value " + boost::lexical_cast(value) + " not allowed"); + } + {{/isContainer}} + {{/isEnum}} + {{^isEnum}} + m_{{name}} = value; + {{/isEnum}} } + + {{/vars}} std::vector<{{classname}}> create{{classname}}VectorFromJsonString(const std::string& json) diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache index 7f083d7e26..e4fdbd1598 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache @@ -7,6 +7,7 @@ #include "Dom/JsonObject.h" #include "HttpRetrySystem.h" #include "Containers/Ticker.h" +#include "Runtime/Launch/Resources/Version.h" {{#cppNamespaceDeclarations}} namespace {{this}} @@ -16,7 +17,13 @@ namespace {{this}} typedef TSharedRef> JsonWriter; using namespace FHttpRetrySystem; -struct {{dllapi}} HttpRetryManager : public FManager, public FTickerObjectBase +struct {{dllapi}} HttpRetryManager + : public FManager +#if ENGINE_MAJOR_VERSION <= 4 + , public FTickerObjectBase +#else + , public FTSTickerObjectBase +#endif { using FManager::FManager; diff --git a/modules/openapi-generator/src/main/resources/crystal/model.mustache b/modules/openapi-generator/src/main/resources/crystal/model.mustache index 021857ee40..3330b7ad23 100644 --- a/modules/openapi-generator/src/main/resources/crystal/model.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/model.mustache @@ -1,5 +1,6 @@ # {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} +require "big" require "json" require "time" diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache index 776d94518b..f6e850c865 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache @@ -448,84 +448,101 @@ namespace {{packageName}}.Client IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { + CancellationTokenSource timeoutTokenSource = null; + CancellationTokenSource finalTokenSource = null; var deserializer = new CustomJsonCodec(SerializerSettings, configuration); - var finalToken = cancellationToken; - if (configuration.Timeout > 0) + try { - var tokenSource = new CancellationTokenSource(configuration.Timeout); - finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token; - } - - if (configuration.Proxy != null) - { - if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); - _httpClientHandler.Proxy = configuration.Proxy; - } - - if (configuration.ClientCertificates != null) - { - if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); - _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); - } - - var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; - - if (cookieContainer != null) - { - if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); - foreach (var cookie in cookieContainer) + if (configuration.Timeout > 0) { - _httpClientHandler.CookieContainer.Add(cookie); + timeoutTokenSource = new CancellationTokenSource(configuration.Timeout); + finalTokenSource = CancellationTokenSource.CreateLinkedTokenSource(finalToken, timeoutTokenSource.Token); + finalToken = finalTokenSource.Token; + } + + if (configuration.Proxy != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.Proxy = configuration.Proxy; + } + + if (configuration.ClientCertificates != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); + } + + var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; + + if (cookieContainer != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + foreach (var cookie in cookieContainer) + { + _httpClientHandler.CookieContainer.Add(cookie); + } + } + + InterceptRequest(req); + + HttpResponseMessage response; + {{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy + .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, finalToken)) + .ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? + policyResult.Result : new HttpResponseMessage() + { + ReasonPhrase = policyResult.FinalException.ToString(), + RequestMessage = req + }; + } + else + { + {{/supportsRetry}} + response = await _httpClient.SendAsync(req, finalToken).ConfigureAwait(false); + {{#supportsRetry}} + } + {{/supportsRetry}} + + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri); + } + + object responseData = await deserializer.Deserialize(response); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + responseData = (T) (object) await response.Content.ReadAsStreamAsync(); + } + + InterceptResponse(req, response); + + return await ToApiResponse(response, responseData, req.RequestUri); + } + finally + { + if (timeoutTokenSource != null) + { + timeoutTokenSource.Dispose(); + } + + if (finalTokenSource != null) + { + finalTokenSource.Dispose(); } } - - InterceptRequest(req); - - HttpResponseMessage response; -{{#supportsRetry}} - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy - .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, cancellationToken)) - .ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? - policyResult.Result : new HttpResponseMessage() - { - ReasonPhrase = policyResult.FinalException.ToString(), - RequestMessage = req - }; - } - else - { -{{/supportsRetry}} - response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false); -{{#supportsRetry}} - } -{{/supportsRetry}} - - if (!response.IsSuccessStatusCode) - { - return await ToApiResponse(response, default(T), req.RequestUri); - } - - object responseData = await deserializer.Deserialize(response); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - responseData = (T) (object) await response.Content.ReadAsStreamAsync(); - } - - InterceptResponse(req, response); - - return await ToApiResponse(response, responseData, req.RequestUri); } {{#supportsAsync}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache index 6eb1a2359d..8e52641d0c 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache @@ -32,7 +32,7 @@ /// {{description}} {{/description}} {{^conditionalSerialization}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } {{#isReadOnly}} @@ -48,7 +48,7 @@ {{/conditionalSerialization}} {{#conditionalSerialization}} {{#isReadOnly}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } @@ -63,7 +63,7 @@ {{/isReadOnly}} {{^isReadOnly}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get{ return _{{name}};} @@ -180,7 +180,7 @@ /// {{#description}} /// {{description}}{{/description}} {{^conditionalSerialization}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] {{#isDate}} [JsonConverter(typeof(OpenAPIDateConverter))] {{/isDate}} @@ -199,7 +199,7 @@ {{/conditionalSerialization}} {{#conditionalSerialization}} {{#isReadOnly}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] {{#isDate}} [JsonConverter(typeof(OpenAPIDateConverter))] {{/isDate}} @@ -218,7 +218,7 @@ {{#isDate}} [JsonConverter(typeof(OpenAPIDateConverter))] {{/isDate}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] public {{{dataType}}} {{name}} { get{ return _{{name}};} @@ -397,7 +397,7 @@ {{#parent}} {{^isArray}} {{^isMap}} - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach(var x in {{#discriminator}}base.{{/discriminator}}BaseValidate(validationContext)) yield return x; {{/isMap}} {{/isArray}} {{/parent}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache index d605f1752d..a919c37996 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache @@ -19,20 +19,22 @@ using System.Web; {{/netStandard}} using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; -using RestSharp.Deserializers; +using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; {{#supportsRetry}} using Polly; {{/supportsRetry}} +{{#hasOAuthMethods}} +using {{packageName}}.Client.Auth; +{{/hasOAuthMethods}} namespace {{packageName}}.Client { /// /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// - internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; @@ -78,7 +80,9 @@ namespace {{packageName}}.Client } } - public T Deserialize(IRestResponse response) + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; @@ -90,7 +94,7 @@ namespace {{packageName}}.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(IRestResponse response, Type type) + internal object Deserialize(RestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { @@ -143,15 +147,22 @@ namespace {{packageName}}.Client } } - public string RootElement { get; set; } - public string Namespace { get; set; } - public string DateFormat { get; set; } + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } + + public DataFormat DataFormat => DataFormat.Json; } {{! NOTE: Any changes related to RestSharp should be done in this class. All other client classes are for extensibility by consumers.}} /// @@ -183,14 +194,14 @@ namespace {{packageName}}.Client /// Allows for extending request processing for generated code. /// /// The RestSharp request object - partial void InterceptRequest(IRestRequest request); + partial void InterceptRequest(RestRequest request); /// /// Allows for extending response processing for generated code. /// /// The RestSharp request object /// The RestSharp response object - partial void InterceptResponse(IRestRequest request, IRestResponse response); + partial void InterceptResponse(RestRequest request, RestResponse response); /// /// Initializes a new instance of the , defaulting to the global configurations' base url. @@ -225,25 +236,25 @@ namespace {{packageName}}.Client switch (method) { case HttpMethod.Get: - other = RestSharpMethod.GET; + other = RestSharpMethod.Get; break; case HttpMethod.Post: - other = RestSharpMethod.POST; + other = RestSharpMethod.Post; break; case HttpMethod.Put: - other = RestSharpMethod.PUT; + other = RestSharpMethod.Put; break; case HttpMethod.Delete: - other = RestSharpMethod.DELETE; + other = RestSharpMethod.Delete; break; case HttpMethod.Head: - other = RestSharpMethod.HEAD; + other = RestSharpMethod.Head; break; case HttpMethod.Options: - other = RestSharpMethod.OPTIONS; + other = RestSharpMethod.Options; break; case HttpMethod.Patch: - other = RestSharpMethod.PATCH; + other = RestSharpMethod.Patch; break; default: throw new ArgumentOutOfRangeException("method", method, null); @@ -274,11 +285,7 @@ namespace {{packageName}}.Client if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); - RestRequest request = new RestRequest(Method(method)) - { - Resource = path, - JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) - }; + RestRequest request = new RestRequest(path, Method(method)); if (options.PathParameters != null) { @@ -373,25 +380,17 @@ namespace {{packageName}}.Client var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); else - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } } } - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - request.AddCookie(cookie.Name, cookie.Value); - } - } - return request; } - private ApiResponse ToApiResponse(IRestResponse response) + private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; string rawContent = response.Content; @@ -410,9 +409,17 @@ namespace {{packageName}}.Client } } + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + if (response.Cookies != null) { - foreach (var responseCookies in response.Cookies) + foreach (var responseCookies in response.Cookies.Cast()) { transformed.Cookies.Add( new Cookie( @@ -430,54 +437,48 @@ namespace {{packageName}}.Client private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else - { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } } - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.Proxy = configuration.Proxy; - } - - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + {{#hasOAuthMethods}} + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } + {{/hasOAuthMethods}} InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; @@ -513,6 +514,10 @@ namespace {{packageName}}.Client { response.Data = (T)(object)response.RawBytes; } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } InterceptResponse(req, response); @@ -525,7 +530,7 @@ namespace {{packageName}}.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, @@ -555,54 +560,37 @@ namespace {{packageName}}.Client private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + {{#hasOAuthMethods}} + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); - } - - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) - { - client.Proxy = configuration.Proxy; - } - - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } + {{/hasOAuthMethods}} InterceptRequest(req); - IRestResponse response; + RestResponse response; {{#supportsRetry}} if (RetryConfiguration.AsyncRetryPolicy != null) { @@ -647,7 +635,7 @@ namespace {{packageName}}.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache index 59684096e7..8de1caf4bf 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache @@ -116,6 +116,16 @@ namespace {{packageName}}.Client return Convert.ToString(obj, CultureInfo.InvariantCulture); } + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + /// /// Encode string in base64 format. /// diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/Configuration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/Configuration.mustache index 20c1fcf645..7f43f567b3 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/Configuration.mustache @@ -11,6 +11,11 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Net.Http; +{{#useRestSharp}} +{{#hasOAuthMethods}}using {{packageName}}.Client.Auth; +{{/hasOAuthMethods}} +{{/useRestSharp}} namespace {{packageName}}.Client { @@ -118,7 +123,7 @@ namespace {{packageName}}.Client public Configuration() { Proxy = null; - UserAgent = "{{httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{packageVersion}}/csharp{{/httpUserAgent}}"; + UserAgent = WebUtility.UrlEncode("{{httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{packageVersion}}/csharp{{/httpUserAgent}}"); BasePath = "{{{basePath}}}"; DefaultHeaders = new {{^net35}}Concurrent{{/net35}}Dictionary(); ApiKey = new {{^net35}}Concurrent{{/net35}}Dictionary(); @@ -328,6 +333,34 @@ namespace {{packageName}}.Client /// The access token. public virtual string AccessToken { get; set; } + {{#useRestSharp}} + {{#hasOAuthMethods}} + /// + /// Gets or sets the token URL for OAuth2 authentication. + /// + /// The OAuth Token URL. + public virtual string OAuthTokenUrl { get; set; } + + /// + /// Gets or sets the client ID for OAuth2 authentication. + /// + /// The OAuth Client ID. + public virtual string OAuthClientId { get; set; } + + /// + /// Gets or sets the client secret for OAuth2 authentication. + /// + /// The OAuth Client Secret. + public virtual string OAuthClientSecret { get; set; } + + /// + /// Gets or sets the flow for OAuth2 authentication. + /// + /// The OAuth Flow. + public virtual OAuthFlow? OAuthFlow { get; set; } + + {{/hasOAuthMethods}} + {{/useRestSharp}} /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// @@ -655,6 +688,14 @@ namespace {{packageName}}.Client Username = second.Username ?? first.Username, Password = second.Password ?? first.Password, AccessToken = second.AccessToken ?? first.AccessToken, + {{#useRestSharp}} + {{#hasOAuthMethods}} + OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl, + OAuthClientId = second.OAuthClientId ?? first.OAuthClientId, + OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret, + OAuthFlow = second.OAuthFlow ?? first.OAuthFlow, + {{/hasOAuthMethods}} + {{/useRestSharp}} {{#hasHttpSignatureMethods}} HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, {{/hasHttpSignatureMethods}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache index 58a961b5da..6b773b8d59 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache @@ -317,14 +317,18 @@ namespace {{packageName}}.Client /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { - if (!File.Exists(KeyFilePath)) + string keyStr = string.Empty; + if (File.Exists(KeyFilePath)) { - throw new Exception("key file path does not exist."); + keyStr = File.ReadAllText(KeyFilePath); + } + else + { + keyStr = KeyFilePath; } const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; - var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); var ecdsa = ECDsa.Create(); @@ -422,11 +426,15 @@ namespace {{packageName}}.Client bool isPrivateKeyFile = true; byte[] pemkey = null; - if (!File.Exists(pemfile)) + string pemstr = string.Empty; + if (File.Exists(pemfile)) { - throw new Exception("private key file does not exist."); + pemstr = File.ReadAllText(pemfile).Trim(); + } + else + { + pemstr = pemfile; } - string pemstr = File.ReadAllText(pemfile).Trim(); if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) { @@ -717,9 +725,16 @@ namespace {{packageName}}.Client /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { - if (!File.Exists(keyFilePath)) + string[] key = null; + + if (File.Exists(keyFilePath)) { - throw new Exception("Key file path does not exist."); + key = File.ReadAllLines(keyFilePath); + } + else + { + // The ApiKeyFilePath is passed as string + key = new string[] { keyFilePath }; } const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; @@ -729,7 +744,6 @@ namespace {{packageName}}.Client //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; PrivateKeyType keyType; - var key = File.ReadAllLines(keyFilePath); if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) @@ -743,7 +757,7 @@ namespace {{packageName}}.Client } else { - throw new Exception("Either the key is invalid or key is not supported"); + throw new Exception("The key file path does not exist or key is invalid or key is not supported"); } return keyType; } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/IReadableConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/IReadableConfiguration.mustache index f4044f6125..3d364834a6 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/IReadableConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/IReadableConfiguration.mustache @@ -4,6 +4,10 @@ using System; using System.Collections.Generic; using System.Net; using System.Security.Cryptography.X509Certificates; +{{#useRestSharp}} +{{#hasOAuthMethods}}using {{packageName}}.Client.Auth; +{{/hasOAuthMethods}} +{{/useRestSharp}} namespace {{packageName}}.Client { @@ -18,6 +22,34 @@ namespace {{packageName}}.Client /// Access token. string AccessToken { get; } + {{#useRestSharp}} + {{#hasOAuthMethods}} + /// + /// Gets the OAuth token URL. + /// + /// OAuth Token URL. + string OAuthTokenUrl { get; } + + /// + /// Gets the OAuth client ID. + /// + /// OAuth Client ID. + string OAuthClientId { get; } + + /// + /// Gets the OAuth client secret. + /// + /// OAuth Client Secret. + string OAuthClientSecret { get; } + + /// + /// Gets the OAuth flow. + /// + /// OAuth Flow. + OAuthFlow? OAuthFlow { get; } + + {{/hasOAuthMethods}} + {{/useRestSharp}} /// /// Gets the API key. /// diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/RequestOptions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/RequestOptions.mustache index 7eadf26f4e..40436b9657 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/RequestOptions.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/RequestOptions.mustache @@ -60,6 +60,13 @@ namespace {{packageName}}.Client /// public Object Data { get; set; } + {{#hasOAuthMethods}} + /// + /// If request should be authenticated with OAuth. + /// + public bool OAuth { get; set; } + + {{/hasOAuthMethods}} /// /// Constructs a new instance of /// diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/RetryConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/RetryConfiguration.mustache index 4cc953487a..93ba14d939 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/RetryConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/RetryConfiguration.mustache @@ -19,12 +19,12 @@ namespace {{packageName}}.Client /// /// Retry policy /// - public static Policy RetryPolicy { get; set; } + public static Policy RetryPolicy { get; set; } /// /// Async retry policy /// - public static AsyncPolicy AsyncRetryPolicy { get; set; } + public static AsyncPolicy AsyncRetryPolicy { get; set; } {{/useRestSharp}} {{#useHttpClient}} /// diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache index 54dde461ff..99d24d2aaa 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache @@ -7,6 +7,8 @@ using System.Linq; using System.Net; using System.Net.Mime; using {{packageName}}.Client; +{{#hasOAuthMethods}}using {{packageName}}.Client.Auth; +{{/hasOAuthMethods}} {{#hasImport}}using {{packageName}}.{{modelPackage}}; {{/hasImport}} @@ -369,7 +371,7 @@ namespace {{packageName}}.{{apiPackage}} {{/isArray}} {{/isFile}} {{^isFile}} - localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.{{#isPrimitiveType}}ParameterToString{{/isPrimitiveType}}{{^isPrimitiveType}}Serialize{{/isPrimitiveType}}({{paramName}})); // form parameter {{/isFile}} {{/required}} {{^required}} @@ -438,9 +440,21 @@ namespace {{packageName}}.{{apiPackage}} {{/isBasicBearer}} {{#isOAuth}} // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{#hasOAuthMethods}} + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + {{/hasOAuthMethods}} } {{/isOAuth}} {{#isHttpSignature}} @@ -669,9 +683,21 @@ namespace {{packageName}}.{{apiPackage}} {{/isBasic}} {{#isOAuth}} // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{#hasOAuthMethods}} + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + {{/hasOAuthMethods}} } {{/isOAuth}} {{#isHttpSignature}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/auth/OAuthAuthenticator.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/auth/OAuthAuthenticator.mustache new file mode 100644 index 0000000000..cc0b3894a0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/auth/OAuthAuthenticator.mustache @@ -0,0 +1,87 @@ +{{>partial_header}} + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace {{packageName}}.Client.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : AuthenticatorBase + { + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) : base("") + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// Access token to create a parameter from. + /// An authentication parameter. + protected override async ValueTask GetAuthenticationParameter(string accessToken) + { + var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl) + .UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration)); + + var request = new RestRequest() + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + var response = await client.PostAsync(request); + return $"{response.TokenType} {response.AccessToken}"; + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/auth/OAuthFlow.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/auth/OAuthFlow.mustache new file mode 100644 index 0000000000..768ddd0aa4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/auth/OAuthFlow.mustache @@ -0,0 +1,19 @@ +{{>partial_header}} + +namespace {{packageName}}.Client.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/auth/TokenResponse.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/auth/TokenResponse.mustache new file mode 100644 index 0000000000..f118b97a9d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/auth/TokenResponse.mustache @@ -0,0 +1,14 @@ +{{>partial_header}} + +using Newtonsoft.Json; + +namespace {{packageName}}.Client.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache index 793bcca771..866f036e65 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache @@ -450,84 +450,101 @@ namespace {{packageName}}.Client IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { + CancellationTokenSource timeoutTokenSource = null; + CancellationTokenSource finalTokenSource = null; var deserializer = new CustomJsonCodec(SerializerSettings, configuration); - var finalToken = cancellationToken; - if (configuration.Timeout > 0) + try { - var tokenSource = new CancellationTokenSource(configuration.Timeout); - finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token; - } - - if (configuration.Proxy != null) - { - if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); - _httpClientHandler.Proxy = configuration.Proxy; - } - - if (configuration.ClientCertificates != null) - { - if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); - _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); - } - - var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; - - if (cookieContainer != null) - { - if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); - foreach (var cookie in cookieContainer) + if (configuration.Timeout > 0) { - _httpClientHandler.CookieContainer.Add(cookie); + timeoutTokenSource = new CancellationTokenSource(configuration.Timeout); + finalTokenSource = CancellationTokenSource.CreateLinkedTokenSource(finalToken, timeoutTokenSource.Token); + finalToken = finalTokenSource.Token; + } + + if (configuration.Proxy != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.Proxy = configuration.Proxy; + } + + if (configuration.ClientCertificates != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); + } + + var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; + + if (cookieContainer != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + foreach (var cookie in cookieContainer) + { + _httpClientHandler.CookieContainer.Add(cookie); + } + } + + InterceptRequest(req); + + HttpResponseMessage response; + {{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy + .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, finalToken)) + .ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? + policyResult.Result : new HttpResponseMessage() + { + ReasonPhrase = policyResult.FinalException.ToString(), + RequestMessage = req + }; + } + else + { + {{/supportsRetry}} + response = await _httpClient.SendAsync(req, finalToken).ConfigureAwait(false); + {{#supportsRetry}} + } + {{/supportsRetry}} + + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri); + } + + object responseData = await deserializer.Deserialize(response); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + responseData = (T) (object) await response.Content.ReadAsStreamAsync(); + } + + InterceptResponse(req, response); + + return await ToApiResponse(response, responseData, req.RequestUri); + } + finally + { + if (timeoutTokenSource != null) + { + timeoutTokenSource.Dispose(); + } + + if (finalTokenSource != null) + { + finalTokenSource.Dispose(); } } - - InterceptRequest(req); - - HttpResponseMessage response; -{{#supportsRetry}} - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy - .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, cancellationToken)) - .ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? - policyResult.Result : new HttpResponseMessage() - { - ReasonPhrase = policyResult.FinalException.ToString(), - RequestMessage = req - }; - } - else - { -{{/supportsRetry}} - response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false); -{{#supportsRetry}} - } -{{/supportsRetry}} - - if (!response.IsSuccessStatusCode) - { - return await ToApiResponse(response, default(T), req.RequestUri); - } - - object responseData = await deserializer.Deserialize(response); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - responseData = (T) (object) await response.Content.ReadAsStreamAsync(); - } - - InterceptResponse(req, response); - - return await ToApiResponse(response, responseData, req.RequestUri); } {{#supportsAsync}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache index a808b9c161..7e318b309c 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache @@ -1,3 +1,4 @@ +{{#model}} /// /// {{description}}{{^description}}{{classname}}{{/description}} /// @@ -22,20 +23,22 @@ } {{/isNullable}} - {{#anyOf}} + {{#composedSchemas.anyOf}} + {{^isNull}} /// /// Initializes a new instance of the class - /// with the class + /// with the class /// - /// An instance of {{{.}}}. - public {{classname}}({{{.}}} actualInstance) + /// An instance of {{dataType}}. + public {{classname}}({{{dataType}}} actualInstance) { - this.IsNullable = {{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}; + this.IsNullable = {{#model.isNullable}}true{{/model.isNullable}}{{^model.isNullable}}false{{/model.isNullable}}; this.SchemaType= "anyOf"; - this.ActualInstance = actualInstance{{^isNullable}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isNullable}}; + this.ActualInstance = actualInstance{{^model.isNullable}}{{^isPrimitiveType}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isPrimitiveType}}{{#isPrimitiveType}}{{#isArray}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isArray}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isFreeFormObject}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isFreeFormObject}}{{/isPrimitiveType}}{{#isPrimitiveType}}{{#isString}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isString}}{{/isPrimitiveType}}{{/model.isNullable}}; } - {{/anyOf}} + {{/isNull}} + {{/composedSchemas.anyOf}} private Object _actualInstance; @@ -62,18 +65,20 @@ } } } - {{#anyOf}} + {{#composedSchemas.anyOf}} + {{^isNull}} /// - /// Get the actual instance of `{{{.}}}`. If the actual instance is not `{{{.}}}`, + /// Get the actual instance of `{{dataType}}`. If the actual instance is not `{{dataType}}`, /// the InvalidClassException will be thrown /// - /// An instance of {{{.}}} - public {{{.}}} Get{{{.}}}() + /// An instance of {{dataType}} + public {{{dataType}}} Get{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}}{{#isArray}}{{#lambda.titlecase}}{{{dataFormat}}}{{/lambda.titlecase}}{{/isArray}}() { - return ({{{.}}})this.ActualInstance; + return ({{{dataType}}})this.ActualInstance; } - {{/anyOf}} + {{/isNull}} + {{/composedSchemas.anyOf}} /// /// Returns the string presentation of the object @@ -233,3 +238,4 @@ return false; } } +{{/model}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache index a998c81e7c..3b61b31644 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache @@ -38,7 +38,7 @@ /// {{.}} {{/description}} {{^conditionalSerialization}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] {{#deprecated}} [Obsolete] {{/deprecated}} @@ -57,7 +57,7 @@ {{/conditionalSerialization}} {{#conditionalSerialization}} {{#isReadOnly}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] {{#deprecated}} [Obsolete] {{/deprecated}} @@ -75,7 +75,7 @@ {{/isReadOnly}} {{^isReadOnly}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] {{#deprecated}} [Obsolete] {{/deprecated}} @@ -209,7 +209,7 @@ /// {{#description}} /// {{.}}{{/description}} {{^conditionalSerialization}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] {{#isDate}} [JsonConverter(typeof(OpenAPIDateConverter))] {{/isDate}} @@ -231,7 +231,7 @@ {{/conditionalSerialization}} {{#conditionalSerialization}} {{#isReadOnly}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] {{#isDate}} [JsonConverter(typeof(OpenAPIDateConverter))] {{/isDate}} @@ -253,7 +253,7 @@ {{#isDate}} [JsonConverter(typeof(OpenAPIDateConverter))] {{/isDate}} - [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#required}}true{{/required}}{{^required}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/required}}{{/vendorExtensions.x-emit-default-value}})] {{#deprecated}} [Obsolete] {{/deprecated}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache index 30c1ceaf2f..3befcffaf4 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache @@ -28,11 +28,11 @@ {{/useCompareNetObjects}} {{^useGenericHost}} - + {{/useGenericHost}} {{#useRestSharp}} - + {{/useRestSharp}} {{#useGenericHost}} @@ -49,4 +49,16 @@ {{/validatable}} + + + {{#net48}} + + {{/net48}} + + + + {{#net48}} + + {{/net48}} + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/nuspec.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/nuspec.mustache index b7044b79d7..0bc477b3e3 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/nuspec.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/nuspec.mustache @@ -32,12 +32,12 @@ {{#useRestSharp}} - + {{/useRestSharp}} {{#useCompareNetObjects}} {{/useCompareNetObjects}} - + {{#validatable}} {{/validatable}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/validatable.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/validatable.mustache index 6322bf599f..aefcf8fd2e 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/validatable.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/validatable.mustache @@ -29,7 +29,7 @@ {{#parent}} {{^isArray}} {{^isMap}} - foreach (var x in BaseValidate(validationContext)) + foreach (var x in {{#discriminator}}base.{{/discriminator}}BaseValidate(validationContext)) { yield return x; } diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/model.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/model.mustache index 5fdbb1b77c..1917decaf6 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/model.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/model.mustache @@ -1,4 +1,5 @@ {{>header}} +// ignore_for_file: unused_element {{#models}} {{#model}} {{#imports}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache index 4a919c21c0..4faed4e3dc 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache @@ -14,8 +14,10 @@ environment: dependencies: dio: '>=4.0.1 <5.0.0' {{#useBuiltValue}} - built_value: '>=8.1.0 <9.0.0' - built_collection: '>=5.1.0 <6.0.0' + one_of: '>=1.5.0 <2.0.0' + one_of_serializer: '>=1.5.0 <2.0.0' + built_value: '>=8.4.0 <9.0.0' + built_collection: '>=5.1.1 <6.0.0' {{/useBuiltValue}} {{#useJsonSerializable}} json_annotation: '^4.4.0' @@ -26,7 +28,7 @@ dependencies: dev_dependencies: {{#useBuiltValue}} - built_value_generator: '>=8.1.0 <9.0.0' + built_value_generator: '>=8.4.0 <9.0.0' build_runner: any {{/useBuiltValue}} {{#useJsonSerializable}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache index 66fe59788b..a8a1339c63 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache @@ -1,154 +1,17 @@ import 'package:built_value/built_value.dart'; -import 'package:built_value/serializer.dart'; +import 'package:built_value/serializer.dart';{{#oneOf}}{{#-first}} +import 'package:one_of/one_of.dart';{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}} +import 'package:one_of/any_of.dart';{{/-first}}{{/anyOf}} +{{#imports}} +{{/imports}} part '{{classFilename}}.g.dart'; -{{! - Classes with polymorphism or composition may generate unused imports, - these need to be ignored for said classes so that there are no lint errors. -}} -{{#parentModel}} -// ignore_for_file: unused_import - -{{/parentModel}} -/// {{{description}}}{{^description}}{{classname}}{{/description}} -{{#hasVars}} -/// -/// Properties: -{{#allVars}} -/// * [{{{name}}}] {{#description}}- {{{.}}}{{/description}} -{{/allVars}} -{{/hasVars}} -abstract class {{classname}} implements Built<{{classname}}, {{classname}}Builder> { -{{#vars}} - {{#description}} - /// {{{.}}} - {{/description}} - @BuiltValueField(wireName: r'{{baseName}}') - {{>serialization/built_value/variable_type}}{{^isNullable}}{{^required}}?{{/required}}{{/isNullable}} get {{name}}; - {{#allowableValues}} - // {{#min}}range from {{{min}}} to {{{max}}}{{/min}}{{^min}}enum {{name}}Enum { {{#values}} {{{.}}}, {{/values}} };{{/min}} - {{/allowableValues}} - -{{/vars}} - {{classname}}._(); - - @BuiltValueHook(initializeBuilder: true) - static void _defaults({{{classname}}}Builder b) => b{{#vars}}{{#defaultValue}} - ..{{{name}}} = {{#isEnum}}{{^isContainer}}const {{{enumName}}}._({{/isContainer}}{{/isEnum}}{{{defaultValue}}}{{#isEnum}}{{^isContainer}}){{/isContainer}}{{/isEnum}}{{/defaultValue}}{{/vars}}; - - factory {{classname}}([void updates({{classname}}Builder b)]) = _${{classname}}; - - @BuiltValueSerializer(custom: true) - static Serializer<{{classname}}> get serializer => _${{classname}}Serializer(); +{{>serialization/built_value/class_header}} { +{{>serialization/built_value/class_members}} } -{{! - Generate a custom serializer in order to support combinations of required and nullable. - By default built_value does not serialize null fields. -}} -class _${{classname}}Serializer implements StructuredSerializer<{{classname}}> { - @override - final Iterable types = const [{{classname}}, _${{classname}}]; +{{>serialization/built_value/class_serializer}}{{#vendorExtensions.x-is-parent}} - @override - final String wireName = r'{{classname}}'; - - @override - Iterable serialize(Serializers serializers, {{{classname}}} object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - {{#vars}} - {{#required}} - {{! - A required property need to always be part of the serialized output. - When it is nullable, null is serialized, otherwise it is an error if it is null. - }} - result - ..add(r'{{baseName}}') - ..add({{#isNullable}}object.{{{name}}} == null ? null : {{/isNullable}}serializers.serialize(object.{{{name}}}, - specifiedType: const {{>serialization/built_value/variable_serializer_type}})); - {{/required}} - {{^required}} - if (object.{{{name}}} != null) { - {{! Non-required properties are only serialized if not null. }} - result - ..add(r'{{baseName}}') - ..add(serializers.serialize(object.{{{name}}}, - specifiedType: const {{>serialization/built_value/variable_serializer_type}})); - } - {{/required}} - {{/vars}} - return result; - } - - @override - {{classname}} deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = {{classname}}Builder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - {{#vars}} - case r'{{baseName}}': - final valueDes = serializers.deserialize(value, - specifiedType: const {{>serialization/built_value/variable_serializer_type}}) as {{>serialization/built_value/variable_type}}; - {{#isNullable}} - if (valueDes == null) continue; - {{/isNullable}} - {{#isContainer}} - result.{{{name}}}.replace(valueDes); - {{/isContainer}} - {{^isContainer}} - {{#isEnum}} - result.{{{name}}} = valueDes; - {{/isEnum}} - {{^isEnum}} - {{#isModel}} - {{#isPrimitiveType}} - {{! These are models that have been manually marked as primitive via generator param. }} - result.{{{name}}} = valueDes; - {{/isPrimitiveType}} - {{^isPrimitiveType}} - result.{{{name}}}.replace(valueDes); - {{/isPrimitiveType}} - {{/isModel}} - {{^isModel}} - result.{{{name}}} = valueDes; - {{/isModel}} - {{/isEnum}} - {{/isContainer}} - break; - {{/vars}} - } - } - return result.build(); - } -} -{{! - Generate an enum for any variables that are declared as inline enums - isEnum is only true for inline variables that are enums. - If an enum is declared as a definition, isEnum is false and the enum is generated from the - enum.mustache template. -}} -{{#vars}} - {{^isModel}} - {{#isEnum}} - {{^isContainer}} - -{{>serialization/built_value/enum_inline}} - {{/isContainer}} - {{#isContainer}} - {{#mostInnerItems}} - -{{>serialization/built_value/enum_inline}} - {{/mostInnerItems}} - {{/isContainer}} - {{/isEnum}} - {{/isModel}} -{{/vars}} \ No newline at end of file +{{>serialization/built_value/class_concrete}}{{/vendorExtensions.x-is-parent}} +{{>serialization/built_value/class_inline_enums}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_concrete.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_concrete.mustache new file mode 100644 index 0000000000..44cad76301 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_concrete.mustache @@ -0,0 +1,56 @@ +/// a concrete implementation of [{{classname}}], since [{{classname}}] is not instantiable +@BuiltValue(instantiable: true) +abstract class ${{classname}} implements {{classname}}, Built<${{classname}}, ${{classname}}Builder> { + ${{classname}}._(); + + factory ${{classname}}([void Function(${{classname}}Builder)? updates]) = _$${{classname}}; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(${{classname}}Builder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer<${{classname}}> get serializer => _$${{classname}}Serializer(); +} + +class _$${{classname}}Serializer implements PrimitiveSerializer<${{classname}}> { + @override + final Iterable types = const [${{classname}}, _$${{classname}}]; + + @override + final String wireName = r'${{classname}}'; + + @override + Object serialize( + Serializers serializers, + ${{{classname}}} object, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.serialize(object, specifiedType: FullType({{classname}}))!; + } + +{{#vendorExtensions.x-has-self-and-ancestor-only-props}}{{>serialization/built_value/deserialize_properties}} + +{{/vendorExtensions.x-has-self-and-ancestor-only-props}} + @override + ${{classname}} deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ${{classname}}Builder(); + {{#vendorExtensions.x-has-self-and-ancestor-only-props}} + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + {{! when discriminator is involved, read it, then return based on value }} + return result.build(); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_header.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_header.mustache new file mode 100644 index 0000000000..e0b80af1db --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_header.mustache @@ -0,0 +1,10 @@ +/// {{{description}}}{{^description}}{{classname}}{{/description}} +{{#hasVars}} +/// +/// Properties: +{{#allVars}} +/// * [{{{name}}}] {{#description}}- {{{.}}}{{/description}} +{{/allVars}} +{{/hasVars}} +@BuiltValue({{#vendorExtensions.x-is-parent}}instantiable: false{{/vendorExtensions.x-is-parent}}) +abstract class {{classname}} {{^allOf}}{{^vendorExtensions.x-is-parent}}implements {{/vendorExtensions.x-is-parent}}{{/allOf}}{{#allOf}}{{#-first}}implements {{/-first}}{{/allOf}}{{#allOf}}{{{.}}}{{^-last}}, {{/-last}}{{/allOf}}{{^vendorExtensions.x-is-parent}}{{#allOf}}{{#-first}}, {{/-first}}{{/allOf}}{{/vendorExtensions.x-is-parent}}{{^vendorExtensions.x-is-parent}}Built<{{classname}}, {{classname}}Builder>{{/vendorExtensions.x-is-parent}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_inline_enums.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_inline_enums.mustache new file mode 100644 index 0000000000..1105c1b70b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_inline_enums.mustache @@ -0,0 +1,23 @@ +{{! + Generate an enum for any variables that are declared as inline enums + isEnum is only true for inline variables that are enums. + If an enum is declared as a definition, isEnum is false and the enum is generated from the + enum.mustache template. + enumName only exists for inline enums +}} +{{#vars}} + {{^isModel}} + {{#enumName}} + {{^isContainer}} + +{{>serialization/built_value/enum_inline}} + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} + +{{>serialization/built_value/enum_inline}} + {{/mostInnerItems}} + {{/isContainer}} + {{/enumName}} + {{/isModel}} +{{/vars}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_members.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_members.mustache new file mode 100644 index 0000000000..ad2e2b0650 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_members.mustache @@ -0,0 +1,35 @@ +{{! define variables that aren't inherited from allOf/anyOf/oneOf }} +{{#vendorExtensions.x-self-only-props}} + {{#description}} + /// {{{.}}} + {{/description}} + @BuiltValueField(wireName: r'{{baseName}}') + {{>serialization/built_value/variable_type}}{{^isNullable}}{{^required}}?{{/required}}{{/isNullable}} get {{name}}; + {{#allowableValues}} + // {{#min}}range from {{{min}}} to {{{max}}}{{/min}}{{^min}}enum {{name}}Enum { {{#values}} {{{.}}}, {{/values}} };{{/min}} + {{/allowableValues}} + +{{/vendorExtensions.x-self-only-props}}{{#anyOf}}{{#-first}} /// Any Of {{#anyOf}}[{{{.}}}]{{^-last}}, {{/-last}}{{/anyOf}} + AnyOf get anyOf; + +{{/-first}}{{/anyOf}}{{#oneOf}}{{#-first}} /// One Of {{#oneOf}}[{{{.}}}]{{^-last}}, {{/-last}}{{/oneOf}} + OneOf get oneOf; + +{{/-first}}{{/oneOf}}{{#discriminator}} static const String discriminatorFieldName = r'{{propertyName}}';{{#hasDiscriminatorWithNonEmptyMapping}} + + static const Map discriminatorMapping = { + {{#mappedModels}} + r'{{mappingName}}': {{modelName}}, + {{/mappedModels}} + };{{/hasDiscriminatorWithNonEmptyMapping}} + +{{/discriminator}}{{^vendorExtensions.x-is-parent}} {{classname}}._(); + + factory {{classname}}([void updates({{classname}}Builder b)]) = _${{classname}}; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults({{{classname}}}Builder b) => b{{#vendorExtensions.x-self-and-ancestor-only-props}}{{#defaultValue}} + ..{{{name}}} = {{#isEnum}}{{^isContainer}}const {{{enumName}}}._({{/isContainer}}{{/isEnum}}{{{defaultValue}}}{{#isEnum}}{{^isContainer}}){{/isContainer}}{{/isEnum}}{{/defaultValue}}{{/vendorExtensions.x-self-and-ancestor-only-props}}; + +{{/vendorExtensions.x-is-parent}} @BuiltValueSerializer(custom: true) + static Serializer<{{classname}}> get serializer => _${{classname}}Serializer(); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_serializer.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_serializer.mustache new file mode 100644 index 0000000000..d3b3d8916c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class_serializer.mustache @@ -0,0 +1,306 @@ +class _${{classname}}Serializer implements PrimitiveSerializer<{{classname}}> { + @override + final Iterable types = const [{{classname}}{{^vendorExtensions.x-is-parent}}, _${{classname}}{{/vendorExtensions.x-is-parent}}]; + + @override + final String wireName = r'{{classname}}'; + + Iterable _serializeProperties( + Serializers serializers, + {{{classname}}} object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + {{#vendorExtensions.x-self-and-ancestor-only-props}} + {{#required}} + {{! + A required property need to always be part of the serialized output. + When it is nullable, null is serialized, otherwise it is an error if it is null. + }} + yield r'{{baseName}}'; + yield {{#isNullable}}object.{{{name}}} == null ? null : {{/isNullable}}serializers.serialize( + object.{{{name}}}, + specifiedType: const {{>serialization/built_value/variable_serializer_type}}, + ); + {{/required}} + {{^required}} + if (object.{{{name}}} != null) { + {{! Non-required properties are only serialized if not null. }} + yield r'{{baseName}}'; + yield serializers.serialize( + object.{{{name}}}, + specifiedType: const {{>serialization/built_value/variable_serializer_type}}, + ); + } + {{/required}} + {{/vendorExtensions.x-self-and-ancestor-only-props}} + } + + @override + Object serialize( + Serializers serializers, + {{{classname}}} object, { + FullType specifiedType = FullType.unspecified, + }) { + {{! oneOf }} + {{#oneOf}} + {{#-first}} + final oneOf = object.oneOf; + {{#vendorExtensions.x-self-and-ancestor-only-props}} + final result = _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + result.addAll(serializers.serialize(oneOf.value, specifiedType: FullType(oneOf.valueType)) as Iterable); + return result; + {{/vendorExtensions.x-self-and-ancestor-only-props}} + {{^vendorExtensions.x-self-and-ancestor-only-props}} + return serializers.serialize(oneOf.value, specifiedType: FullType(oneOf.valueType))!; + {{/vendorExtensions.x-self-and-ancestor-only-props}} + {{/-first}} + {{/oneOf}} + {{! anyOf }} + {{#anyOf}} + {{#-first}} + final anyOf = object.anyOf; + final result = {{^vendorExtensions.x-has-self-and-ancestor-only-props}}[]{{/vendorExtensions.x-has-self-and-ancestor-only-props}}{{#vendorExtensions.x-has-self-and-ancestor-only-props}}_serializeProperties(serializers, object, specifiedType: specifiedType).toList(){{/vendorExtensions.x-has-self-and-ancestor-only-props}}; + for (var _valueEntry in anyOf.values.entries) { + final _typeIndex = _valueEntry.key; + final _type = anyOf.types[_typeIndex]; + final _value = _valueEntry.value; + result.addAll(serializers.serialize(_value, specifiedType: FullType(_type)) as Iterable); + } + return result; + {{/-first}} + {{/anyOf}} + {{^oneOf}} + {{^anyOf}} + {{#hasDiscriminatorWithNonEmptyMapping}} + {{#discriminator}} + {{! handle discriminator }} + {{#mappedModels}} + if (object is {{modelName}}) { + return serializers.serialize(object, specifiedType: FullType({{modelName}}))!; + } + {{/mappedModels}} + {{/discriminator}} + {{/hasDiscriminatorWithNonEmptyMapping}} + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + {{/anyOf}} + {{/oneOf}} + } + +{{#vendorExtensions.x-has-self-and-ancestor-only-props}}{{^vendorExtensions.x-is-parent}}{{>serialization/built_value/deserialize_properties}} + +{{/vendorExtensions.x-is-parent}}{{/vendorExtensions.x-has-self-and-ancestor-only-props}} @override + {{classname}} deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + {{! oneOf }} + {{#oneOf}} + {{#-first}} + final result = {{#vendorExtensions.x-is-parent}}${{/vendorExtensions.x-is-parent}}{{classname}}Builder(); + Object? oneOfDataSrc; + {{#hasDiscriminatorWithNonEmptyMapping}} + {{#discriminator}} + {{! has props, assign them to result, and extract unhandled }} + final serializedList = (serialized as Iterable).toList(); + final discIndex = serializedList.indexOf({{classname}}.discriminatorFieldName) + 1; + final discValue = serializers.deserialize(serializedList[discIndex], specifiedType: FullType(String)) as String; + {{#vendorExtensions.x-has-self-and-ancestor-only-props}} + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result + ); + {{! only deserialize unhandled props }} + oneOfDataSrc = unhandled; + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + {{^vendorExtensions.x-has-self-and-ancestor-only-props}} + oneOfDataSrc = serialized; + {{! has no probs at all, pass the serialized as is }} + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + final oneOfTypes = [{{#mappedModels}}{{modelName}}, {{/mappedModels}}{{#vendorExtensions.x-is-parent}}${{classname}}{{/vendorExtensions.x-is-parent}}]; + Object oneOfResult; + Type oneOfType; + switch (discValue) { + {{#mappedModels}} + case '{{mappingName}}': + oneOfResult = serializers.deserialize( + oneOfDataSrc, + specifiedType: FullType({{modelName}}), + ) as {{modelName}}; + oneOfType = {{modelName}}; + break; + {{/mappedModels}} + default: + {{#vendorExtensions.x-is-parent}} + oneOfResult = serializers.deserialize( + oneOfDataSrc, + specifiedType: FullType(${{classname}}), + ) as ${{classname}}; + oneOfType = ${{classname}}; + {{/vendorExtensions.x-is-parent}} + {{^vendorExtensions.x-is-parent}} + throw UnsupportedError("Couldn't deserialize oneOf for the discriminator value: ${discValue}"); + {{/vendorExtensions.x-is-parent}} + } + result.oneOf = OneOfDynamic(typeIndex: oneOfTypes.indexOf(oneOfType), types: oneOfTypes, value: oneOfResult); + {{/discriminator}} + {{/hasDiscriminatorWithNonEmptyMapping}} + {{^hasDiscriminatorWithNonEmptyMapping}} + {{! use the OneOfSerializer when there is no discriminator }} + final targetType = const FullType(OneOf, [{{#composedSchemas}}{{#oneOf}}{{>serialization/built_value/variable_serializer_type}}, {{/oneOf}}{{/composedSchemas}}]); + {{#vendorExtensions.x-has-self-and-ancestor-only-props}} + {{! has props, assign them to result, and extract unhandled }} + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + {{! only deserialize unhandled props }} + oneOfDataSrc = unhandled; + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + {{^vendorExtensions.x-has-self-and-ancestor-only-props}} + {{! has no probs at all, pass the serialized as is }} + oneOfDataSrc = serialized; + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + result.oneOf = serializers.deserialize(oneOfDataSrc, specifiedType: targetType) as OneOf; + {{/hasDiscriminatorWithNonEmptyMapping}} + return result.build(); + {{/-first}} + {{/oneOf}} + {{! anyOf }} + {{#anyOf}} + {{#-first}} + final result = {{#vendorExtensions.x-is-parent}}${{/vendorExtensions.x-is-parent}}{{classname}}Builder(); + Object? anyOfDataSrc; + {{#hasDiscriminatorWithNonEmptyMapping}} + {{#discriminator}} + {{! has props, assign them to result, and extract unhandled }} + final serializedList = (serialized as Iterable).toList(); + final discIndex = serializedList.indexOf({{classname}}.discriminatorFieldName) + 1; + final discValue = serializers.deserialize(serializedList[discIndex], specifiedType: FullType(String)) as String; + {{#vendorExtensions.x-has-self-and-ancestor-only-props}} + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + {{! only deserialize unhandled props }} + anyOfDataSrc = unhandled; + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + {{^vendorExtensions.x-has-self-and-ancestor-only-props}} + anyOfDataSrc = serialized; + {{! has no probs at all, pass the serialized as is }} + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + final anyOfTypes = [{{#mappedModels}}{{modelName}}, {{/mappedModels}}{{#vendorExtensions.x-is-parent}}${{classname}}{{/vendorExtensions.x-is-parent}}]; + Object anyOfResult; + Type anyOfType; + switch (discValue) { + {{#mappedModels}} + case '{{mappingName}}': + anyOfResult = serializers.deserialize(anyOfDataSrc, specifiedType: FullType({{modelName}})) as {{modelName}}; + anyOfType = {{modelName}}; + break; + {{/mappedModels}} + default: + {{#vendorExtensions.x-is-parent}} + anyOfResult = serializers.deserialize(anyOfDataSrc, specifiedType: FullType(${{classname}})) as ${{classname}}; + anyOfType = ${{classname}}; + {{/vendorExtensions.x-is-parent}} + {{^vendorExtensions.x-is-parent}} + throw UnsupportedError("Couldn't deserialize anyOf for the discriminator value: ${discValue}"); + {{/vendorExtensions.x-is-parent}} + } + result.anyOf = AnyOfDynamic(values: {anyOfTypes.indexOf(anyOfType): anyOfResult}, types: anyOfTypes); + {{/discriminator}} + {{/hasDiscriminatorWithNonEmptyMapping}} + {{^hasDiscriminatorWithNonEmptyMapping}} + {{! use the OneOfSerializer when there is no discriminator }} + final targetType = const FullType(AnyOf, [{{#composedSchemas}}{{#anyOf}}{{>serialization/built_value/variable_serializer_type}}, {{/anyOf}}{{/composedSchemas}}]); + {{#vendorExtensions.x-has-self-and-ancestor-only-props}} + {{! has props, assign them to result, and extract unhandled }} + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + {{! only deserialize unhandled props }} + anyOfDataSrc = unhandled; + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + {{^vendorExtensions.x-has-self-and-ancestor-only-props}} + {{! has no probs at all, pass the serialized as is }} + anyOfDataSrc = serialized; + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + result.anyOf = serializers.deserialize(anyOfDataSrc, specifiedType: targetType) as AnyOf; + {{/hasDiscriminatorWithNonEmptyMapping}} + return result.build(); + {{/-first}} + {{/anyOf}} + {{! no anyOf nor oneOf, handles allOf trees }} + {{^oneOf}} + {{^anyOf}} + {{#vendorExtensions.x-is-parent}} + {{! + parent classes don't have builder + so they must delegate to another serializer using + 1) discriminator + mapping + 2) concrete implmentation ($classname) + }} + {{#hasDiscriminatorWithNonEmptyMapping}} + {{#discriminator}} + final serializedList = (serialized as Iterable).toList(); + final discIndex = serializedList.indexOf({{classname}}.discriminatorFieldName) + 1; + final discValue = serializers.deserialize(serializedList[discIndex], specifiedType: FullType(String)) as String; + switch (discValue) { + {{#mappedModels}} + case '{{mappingName}}': + return serializers.deserialize(serialized, specifiedType: FullType({{modelName}})) as {{modelName}}; + {{/mappedModels}} + default: + return serializers.deserialize(serialized, specifiedType: FullType(${{classname}})) as ${{classname}}; + } + {{/discriminator}} + {{/hasDiscriminatorWithNonEmptyMapping}} + {{^hasDiscriminatorWithNonEmptyMapping}} + return serializers.deserialize(serialized, specifiedType: FullType(${{classname}})) as ${{classname}}; + {{/hasDiscriminatorWithNonEmptyMapping}} + {{/vendorExtensions.x-is-parent}} + {{^vendorExtensions.x-is-parent}} + final result = {{classname}}Builder(); + final serializedList = (serialized as Iterable).toList(); + {{#vendorExtensions.x-has-self-and-ancestor-only-props}} + {{! has props, assign them to result, and extract unhandled }} + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + {{/vendorExtensions.x-has-self-and-ancestor-only-props}} + return result.build(); + {{/vendorExtensions.x-is-parent}} + {{/anyOf}} + {{/oneOf}} + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/deserialize_properties.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/deserialize_properties.mustache new file mode 100644 index 0000000000..d64ec8086c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/deserialize_properties.mustache @@ -0,0 +1,57 @@ + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required {{classname}}Builder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + {{#vendorExtensions.x-self-and-ancestor-only-props}} + case r'{{baseName}}': + final valueDes = serializers.deserialize( + value, + specifiedType: const {{>serialization/built_value/variable_serializer_type}}, + ) as {{>serialization/built_value/variable_type}}; + {{#isNullable}} + if (valueDes == null) continue; + {{/isNullable}} + {{#isContainer}} + result.{{{name}}}.replace(valueDes); + {{/isContainer}} + {{^isContainer}} + {{#isEnum}} + result.{{{name}}} = valueDes; + {{/isEnum}} + {{^isEnum}} + {{#isModel}} + {{#isPrimitiveType}} + {{! These are models that have been manually marked as primitive via generator param. }} + result.{{{name}}} = valueDes; + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#vendorExtensions.x-is-parent}} + result.{{{name}}} = valueDes; + {{/vendorExtensions.x-is-parent}} + {{^vendorExtensions.x-is-parent}} + result.{{{name}}}.replace(valueDes); + {{/vendorExtensions.x-is-parent}} + {{/isPrimitiveType}} + {{/isModel}} + {{^isModel}} + result.{{{name}}} = valueDes; + {{/isModel}} + {{/isEnum}} + {{/isContainer}} + break; + {{/vendorExtensions.x-self-and-ancestor-only-props}} + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache index 7ef191808e..aa49d9aef9 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache @@ -1,6 +1,8 @@ {{>header}} // ignore_for_file: unused_import +import 'package:one_of_serializer/any_of_serializer.dart'; +import 'package:one_of_serializer/one_of_serializer.dart'; import 'package:built_collection/built_collection.dart'; import 'package:built_value/json_object.dart'; import 'package:built_value/serializer.dart'; @@ -17,7 +19,7 @@ import 'package:{{pubName}}/{{sourceFolder}}/offset_date_serializer.dart';{{/use part 'serializers.g.dart'; @SerializersFor([{{#models}}{{#model}} - {{classname}},{{/model}}{{/models}} + {{classname}},{{#vendorExtensions.x-is-parent}}${{classname}},{{/vendorExtensions.x-is-parent}}{{/model}}{{/models}} ]) Serializers serializers = (_$serializers.toBuilder(){{#builtValueSerializers}} ..addBuilderFactory( @@ -29,7 +31,10 @@ Serializers serializers = (_$serializers.toBuilder(){{#builtValueSerializers}} const FullType(BuiltMap, [FullType(String), FullType{{#isNullable}}.nullable{{/isNullable}}({{dataType}})]), () => MapBuilder(), {{/isMap}} - ){{/builtValueSerializers}}{{#useDateLibTimeMachine}} + ){{/builtValueSerializers}} + {{#models}}{{#model}}{{#vendorExtensions.x-is-parent}}..add({{classname}}.serializer) + {{/vendorExtensions.x-is-parent}}{{/model}}{{/models}}..add(const OneOfSerializer()) + ..add(const AnyOfSerializer()){{#useDateLibTimeMachine}} ..add(const OffsetDateSerializer()) ..add(const OffsetDateTimeSerializer()){{/useDateLibTimeMachine}}{{#useDateLibCore}} ..add(const DateSerializer()) diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/test_instance.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/test_instance.mustache index 4ee29fff3c..2d92c472df 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/test_instance.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/test_instance.mustache @@ -1,2 +1,2 @@ - final instance = {{{classname}}}Builder(); + {{#vendorExtensions.x-is-parent}}//{{/vendorExtensions.x-is-parent}}final instance = {{{classname}}}Builder(); // TODO add properties to the builder and call build() \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache index d8db09013b..b340a97457 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -1,11 +1,13 @@ {{>header}} {{>part_of}} class ApiClient { - ApiClient({this.basePath = '{{{basePath}}}', this.authentication}); + ApiClient({this.basePath = '{{{basePath}}}', this.authentication,}); final String basePath; + final Authentication? authentication; var _client = Client(); + final _defaultHeaderMap = {}; /// Returns the current HTTP [Client] instance to use in this class. /// @@ -17,15 +19,12 @@ class ApiClient { _client = newClient; } - final _defaultHeaderMap = {}; - final Authentication? authentication; + Map get defaultHeaderMap => _defaultHeaderMap; void addDefaultHeader(String key, String value) { _defaultHeaderMap[key] = value; } - Map get defaultHeaderMap => _defaultHeaderMap; - // We don't use a Map for queryParams. // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( @@ -37,7 +36,7 @@ class ApiClient { Map formParams, String? contentType, ) async { - _updateParamsForAuth(queryParams, headerParams); + await authentication?.applyToParams(queryParams, headerParams); headerParams.addAll(_defaultHeaderMap); if (contentType != null) { @@ -157,16 +156,6 @@ class ApiClient { @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') String serialize(Object? value) => value == null ? '' : json.encode(value); - /// Update query and header parameters based on authentication settings. - void _updateParamsForAuth( - List queryParams, - Map headerParams, - ) { - if (authentication != null) { - authentication!.applyToParams(queryParams, headerParams); - } - } - {{#native_serialization}} static dynamic _deserialize(dynamic value, String targetType, {bool growable = false}) { try { diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache index b4f5a45872..4b8f707eeb 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/api_key_auth.mustache @@ -10,7 +10,7 @@ class ApiKeyAuth implements Authentication { String apiKey = ''; @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { final paramValue = apiKeyPrefix.isEmpty ? apiKey : '$apiKeyPrefix $apiKey'; if (paramValue.isNotEmpty) { diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/authentication.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/authentication.mustache index e8aaaa4d54..6eff61ede0 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/authentication.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/authentication.mustache @@ -3,5 +3,5 @@ // ignore: one_member_abstracts abstract class Authentication { /// Apply authentication settings to header and query params. - void applyToParams(List queryParams, Map headerParams); + Future applyToParams(List queryParams, Map headerParams); } diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache index 5442197339..c83d037c79 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/http_basic_auth.mustache @@ -7,7 +7,7 @@ class HttpBasicAuth implements Authentication { String password; @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { if (username.isNotEmpty && password.isNotEmpty) { final credentials = '$username:$password'; headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache index 7c480c5e81..6c1d3c0e84 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/http_bearer_auth.mustache @@ -17,7 +17,7 @@ class HttpBearerAuth implements Authentication { } @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { if (_accessToken == null) { return; } diff --git a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache index c5c64d5221..0e65baa4c6 100644 --- a/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/auth/oauth.mustache @@ -6,7 +6,7 @@ class OAuth implements Authentication { String accessToken; @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { if (accessToken.isNotEmpty) { headerParams['Authorization'] = 'Bearer $accessToken'; } diff --git a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache index 63c061a1ff..dd656c53e7 100644 --- a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache @@ -52,59 +52,59 @@ class {{{classname}}} { String toString() => '{{{classname}}}[{{#vars}}{{{name}}}=${{{name}}}{{^-last}}, {{/-last}}{{/vars}}]'; Map toJson() { - final _json = {}; + final json = {}; {{#vars}} {{#isNullable}} - if ({{{name}}} != null) { + if (this.{{{name}}} != null) { {{/isNullable}} {{^isNullable}} {{^required}} {{^defaultValue}} - if ({{{name}}} != null) { + if (this.{{{name}}} != null) { {{/defaultValue}} {{/required}} {{/isNullable}} {{#isDateTime}} {{#pattern}} - _json[r'{{{baseName}}}'] = _dateEpochMarker == '{{{pattern}}}' - ? {{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.millisecondsSinceEpoch - : {{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc().toIso8601String(); + json[r'{{{baseName}}}'] = _dateEpochMarker == '{{{pattern}}}' + ? this.{{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.millisecondsSinceEpoch + : this.{{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc().toIso8601String(); {{/pattern}} {{^pattern}} - _json[r'{{{baseName}}}'] = {{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc().toIso8601String(); + json[r'{{{baseName}}}'] = this.{{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc().toIso8601String(); {{/pattern}} {{/isDateTime}} {{#isDate}} {{#pattern}} - _json[r'{{{baseName}}}'] = _dateEpochMarker == '{{{pattern}}}' - ? {{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.millisecondsSinceEpoch - : _dateFormatter.format({{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc()); + json[r'{{{baseName}}}'] = _dateEpochMarker == '{{{pattern}}}' + ? this.{{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.millisecondsSinceEpoch + : _dateFormatter.format(this.{{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc()); {{/pattern}} {{^pattern}} - _json[r'{{{baseName}}}'] = _dateFormatter.format({{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc()); + json[r'{{{baseName}}}'] = _dateFormatter.format(this.{{{name}}}{{#isNullable}}!{{/isNullable}}{{^isNullable}}{{^required}}{{^defaultValue}}!{{/defaultValue}}{{/required}}{{/isNullable}}.toUtc()); {{/pattern}} {{/isDate}} {{^isDateTime}} {{^isDate}} - _json[r'{{{baseName}}}'] = {{{name}}}; + json[r'{{{baseName}}}'] = this.{{{name}}}; {{/isDate}} {{/isDateTime}} {{#isNullable}} } else { - _json[r'{{{baseName}}}'] = null; + json[r'{{{baseName}}}'] = null; } {{/isNullable}} {{^isNullable}} {{^required}} {{^defaultValue}} } else { - _json[r'{{{baseName}}}'] = null; + json[r'{{{baseName}}}'] = null; } {{/defaultValue}} {{/required}} {{/isNullable}} {{/vars}} - return _json; + return json; } /// Returns a new [{{{classname}}}] instance and imports its values from diff --git a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum.mustache b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum.mustache index 6f4b8a62ed..60dd4f3982 100644 --- a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum.mustache @@ -61,7 +61,7 @@ class {{{classname}}}TypeTransformer { /// and users are still using an old app with the old code. {{{classname}}}? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { {{#allowableValues}} {{#enumVars}} case {{#isString}}r{{/isString}}{{{value}}}: return {{{classname}}}.{{{name}}}; diff --git a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum_inline.mustache b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum_inline.mustache index b434d2d018..4eedb4d45c 100644 --- a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum_inline.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_enum_inline.mustache @@ -61,7 +61,7 @@ class {{{enumName}}}TypeTransformer { /// and users are still using an old app with the old code. {{{enumName}}}? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { {{#allowableValues}} {{#enumVars}} case {{#isString}}r{{/isString}}{{{value}}}: return {{{enumName}}}.{{{name}}}; diff --git a/modules/openapi-generator/src/main/resources/elixir/README.md.mustache b/modules/openapi-generator/src/main/resources/elixir/README.md.mustache index a7b8e8d6a1..11d51400e8 100644 --- a/modules/openapi-generator/src/main/resources/elixir/README.md.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/README.md.mustache @@ -2,33 +2,46 @@ {{appDescription}} -### Building +## Building To install the required dependencies and to build the elixir project, run: -``` + +```console mix local.hex --force mix do deps.get, compile ``` ## Installation -If [available in Hex](https://hex.pm/docs/publish), the package can be installed -by adding `{{#underscored}}{{packageName}}{{/underscored}}` to your list of dependencies in `mix.exs`: +If [available in Hex][], the package can be installed by adding `{{#underscored}}{{packageName}}{{/underscored}}` to +your list of dependencies in `mix.exs`: ```elixir -def deps do - [{:{{#underscored}}{{packageName}}{{/underscored}}, "~> 0.1.0"}] -end +{{=<% %>=}}def deps do + [{<%#atom%><%#underscored%><%packageName%><%/underscored%><%/atom%>, "~> <%appVersion%>"}] +end<%={{ }}=%> ``` -Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) -and published on [HexDocs](https://hexdocs.pm). Once published, the docs can -be found at [https://hexdocs.pm/{{#underscored}}{{packageName}}{{/underscored}}](https://hexdocs.pm/{{#underscored}}{{packageName}}{{/underscored}}). - +Documentation can be generated with [ExDoc][] and published on [HexDocs][]. Once published, the docs can be found at +[https://hexdocs.pm/{{#underscored}}{{packageName}}{{/underscored}}][docs]. ## Configuration -You can override the URL of your server (e.g. if you have a separate development and production server in your configuration files. +You can override the URL of your server (e.g. if you have a separate development and production server in your +configuration files). + ```elixir -config :{{#underscored}}{{appName}}{{/underscored}}, base_url: "{{{basePath}}}" -``` \ No newline at end of file +config :{{#underscored}}{{packageName}}{{/underscored}}, base_url: "{{{basePath}}}" +``` + +Multiple clients for the same API with different URLs can be created passing different `base_url`s when calling +`{{moduleName}}.Connection.new/1`: + +```elixir +client = {{moduleName}}.Connection.new(base_url: "{{{basePath}}}") +``` + +[exdoc]: https://github.com/elixir-lang/ex_doc +[hexdocs]: https://hexdocs.pm +[available in hex]: https://hex.pm/docs/publish +[docs]: https://hexdocs.pm/{{#underscored}}{{packageName}}{{/underscored}} diff --git a/modules/openapi-generator/src/main/resources/elixir/api.mustache b/modules/openapi-generator/src/main/resources/elixir/api.mustache index 6d5e0d44fa..cc072de072 100644 --- a/modules/openapi-generator/src/main/resources/elixir/api.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/api.mustache @@ -6,9 +6,8 @@ defmodule {{moduleName}}.Api.{{classname}} do alias {{moduleName}}.Connection import {{moduleName}}.RequestBuilder - {{#operations}} - {{#operation}} +{{#operation}} @doc """ {{#summary}} @@ -18,25 +17,26 @@ defmodule {{moduleName}}.Api.{{classname}} do {{¬es}} {{/notes}} - ## Parameters + ### Parameters - - connection ({{&moduleName}}.Connection): Connection to server + - `connection` ({{&moduleName}}.Connection): Connection to server {{#requiredParams}} - - {{#underscored}}{{¶mName}}{{/underscored}} ({{&dataType}}): {{&description}} + - `{{#underscored}}{{¶mName}}{{/underscored}}` ({{&dataType}}): {{&description}} {{/requiredParams}} - - opts (KeywordList): [optional] Optional parameters + - `opts` (keyword): Optional parameters {{#optionalParams}} {{#isBodyParam}} - - :body ({{dataType}}): {{&description}} + - `:body` ({{dataType}}): {{&description}} {{/isBodyParam}} {{^isBodyParam}} - - {{#underscored}}:{{¶mName}}{{/underscored}} ({{&dataType}}): {{&description}} + - `{{#atom}}{{&baseName}}{{/atom}}` ({{&dataType}}): {{&description}} {{/isBodyParam}} {{/optionalParams}} - ## Returns - {:ok, {{#isArray}}[%{{&returnBaseType}}{}, ...]{{/isArray}}{{#isMap}}%{}{{/isMap}}{{^returnType}}nil{{/returnType}}{{#returnSimpleType}}{{#returnType}}{{{.}}}{{/returnType}}{{/returnSimpleType}}} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, {{#isArray}}[%{{&returnBaseType}}{}, ...]{{/isArray}}{{#isMap}}%{}{{/isMap}}{{^returnType}}nil{{/returnType}}{{#returnSimpleType}}{{#returnType}}{{{.}}}{{/returnType}}{{/returnSimpleType}}}` on success + - `{:error, Tesla.Env.t}` on failure """ {{{typespec}}} def {{{operationId}}}(connection, {{#requiredParams}}{{#underscored}}{{{paramName}}}{{/underscored}}, {{/requiredParams}}{{^hasOptionalParams}}_{{/hasOptionalParams}}opts \\ []) do @@ -52,29 +52,33 @@ defmodule {{moduleName}}.Api.{{classname}} do {{/isBodyParam}} {{#-last}} } + {{/-last}} {{/optionalParams}} - %{} - |> method(:{{#underscored}}{{httpMethod}}{{/underscored}}) - |> url("{{replacedPathName}}") + request = + %{} + |> method({{#atom}}{{#underscored}}{{httpMethod}}{{/underscored}}{{/atom}}) + |> url("{{replacedPathName}}") {{#requiredParams}} {{^isPathParam}} - |> add_param({{#isBodyParam}}:body{{/isBodyParam}}{{#isFormParam}}{{#isMultipart}}{{#isFile}}:file{{/isFile}}{{^isFile}}:form{{/isFile}}{{/isMultipart}}{{^isMultipart}}:form{{/isMultipart}}{{/isFormParam}}{{#isQueryParam}}:query{{/isQueryParam}}{{#isHeaderParam}}:headers{{/isHeaderParam}}, {{#isBodyParam}}:body, {{/isBodyParam}}{{^isBodyParam}}{{#atom}}{{baseName}}{{/atom}}, {{/isBodyParam}}{{#underscored}}{{paramName}}{{/underscored}}) + |> add_param({{#isBodyParam}}:body{{/isBodyParam}}{{#isFormParam}}{{#isMultipart}}{{#isFile}}:file{{/isFile}}{{^isFile}}:form{{/isFile}}{{/isMultipart}}{{^isMultipart}}:form{{/isMultipart}}{{/isFormParam}}{{#isQueryParam}}:query{{/isQueryParam}}{{#isHeaderParam}}:headers{{/isHeaderParam}}, {{#isBodyParam}}:body{{/isBodyParam}}{{^isBodyParam}}{{#atom}}{{baseName}}{{/atom}}{{/isBodyParam}}, {{#underscored}}{{paramName}}{{/underscored}}) {{/isPathParam}} {{/requiredParams}} {{#optionalParams}} {{#-first}} - |> add_optional_params(optional_params, opts) + |> add_optional_params(optional_params, opts) {{/-first}} {{/optionalParams}} {{#requiresHttpcWorkaround}} - |> ensure_body() + |> ensure_body() {{/requiresHttpcWorkaround}} - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response({{#responses}}{{#-first}}[ {{/-first}} - { {{& codeMappingKey}}, {{decodedStruct}}}{{^-last}},{{/-last}} + {{=<% %>=}}{<%& codeMappingKey%>, <%decodedStruct%>}<%={{ }}=%>{{^-last}},{{/-last}} {{#-last}} ]{{/-last}}{{/responses}}) end {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/elixir/config.exs.mustache b/modules/openapi-generator/src/main/resources/elixir/config.exs.mustache index 05fd56545d..3f4b326a26 100644 --- a/modules/openapi-generator/src/main/resources/elixir/config.exs.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/config.exs.mustache @@ -7,7 +7,7 @@ # General application configuration import Config -config :{{#underscored}}{{appName}}{{/underscored}}, base_url: "{{{basePath}}}" +config {{#atom}}{{#underscored}}{{packageName}}{{/underscored}}{{/atom}}, base_url: "{{{basePath}}}" # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. diff --git a/modules/openapi-generator/src/main/resources/elixir/connection.ex.mustache b/modules/openapi-generator/src/main/resources/elixir/connection.ex.mustache index 60ec9e3e25..15f29d734c 100644 --- a/modules/openapi-generator/src/main/resources/elixir/connection.ex.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/connection.ex.mustache @@ -2,91 +2,306 @@ defmodule {{moduleName}}.Connection do @moduledoc """ Handle Tesla connections for {{moduleName}}. + + Additional middleware can be set in the compile-time or runtime configuration: + + config :tesla, {{moduleName}}.Connection, + base_url: "{{{basePath}}}", + adapter: Tesla.Adapter.Hackney + + The default base URL can also be set as: + + config {{#atom}}{{#underscored}}{{packageName}}{{/underscored}}{{/atom}}, + :base_url, "{{{basePath}}}" """ - use Tesla + @default_base_url Application.compile_env( + {{#atom}}{{#underscored}}{{packageName}}{{/underscored}}{{/atom}}, + :base_url, + "{{{basePath}}}" + ) - # Add any middleware here (authentication) - plug Tesla.Middleware.BaseUrl, Application.get_env(:{{#underscored}}{{appName}}{{/underscored}}, :base_url, "{{{basePath}}}") - plug Tesla.Middleware.Headers, [{"user-agent", "Elixir"}] - plug Tesla.Middleware.EncodeJson, engine: Poison - - {{#hasAuthMethods}} - {{#authMethods}} - {{#isOAuth}} - @scopes [ + {{#hasOAuthMethods}} + {{#oauthMethods}} + @default_scopes [ {{#scopes}} - "{{scope}}"{{^-last}},{{/-last}} {{#description}}# {{.}}{{/description}} + {{#description}}# {{.}}{{/description}} + "{{scope}}"{{^-last}},{{/-last}} {{/scopes}} ] + {{/oauthMethods}} + + @typedoc """ + An arity-1 function or module/function tuple specification which, given + a list of scopes, obtains an OAuth2 token. + """ + @type token_fetcher :: (scopes :: list(String.t()) -> String.t()) | {module(), atom()} + {{/hasOAuthMethods}} + + @typedoc """ + The list of options that can be passed to new/1. + + - `base_url`: Overrides the base URL on a per-client basis. + - `user_agent`: Overrides the User-Agent header. + {{#hasOAuthMethods}} + - `token`: An OAuth2 token or a token fetcher function. + - `token_scopes`: A list of OAuth2 scope strings for use with a token + fetcher function. + {{/hasOAuthMethods}} + {{#hasHttpBasicMethods}} + - `username`: A username for basic authentication. + - `password`: A password for basic authentication. + {{/hasHttpBasicMethods}} + """ + @type options :: [ + {:base_url, String.t()}, + {:user_agent, String.t()}, + {{#hasOAuthMethods}} + {:token, String.t() | token_fetcher}, + {:token_scopes, list(String.t())}, + {{/hasOAuthMethods}} + {{#hasHttpBasicMethods}} + {:username, String.t() | nil}, + {:password, String.t() | nil}, + {{/hasHttpBasicMethods}} + ] + + @doc "Forward requests to Tesla." + @spec request(Tesla.Client.t(), [Tesla.option()]) :: Tesla.Env.result() + defdelegate request(client, options), to: Tesla @doc """ - Configure a client connection using a provided OAuth2 token as a Bearer token + Configure a client with no authentication. - ## Parameters - - - token (String): Bearer token - - ## Returns + ### Returns Tesla.Env.client """ - @spec new(String.t) :: Tesla.Env.client - def new(token) when is_binary(token) do - Tesla.client([ - {Tesla.Middleware.Headers, [{"authorization", "Bearer #{token}"}]} - ]) - end - - @doc """ - Configure a client connection using a function which yields a Bearer token. - - ## Parameters - - - token_fetcher (function arity of 1): Callback which provides an OAuth2 token - given a list of scopes - - ## Returns - - Tesla.Env.client - """ - @spec new(((list(String.t)) -> String.t)) :: Tesla.Env.client - def new(token_fetcher) when is_function(token_fetcher) do - token_fetcher.(@scopes) - |> new - end - {{/isOAuth}} - {{#isBasic}} - @doc """ - Configure a client connection using Basic authentication. - - ## Parameters - - - username (String): Username used for authentication - - password (String): Password used for authentication - - # Returns - - Tesla.Env.client - """ - @spec new(String.t, String.t) :: Tesla.Env.client - def new(username, password) do - Tesla.client([ - {Tesla.Middleware.BasicAuth, %{username: username, password: password}} - ]) - end - {{/isBasic}} - {{/authMethods}} - {{/hasAuthMethods}} - @doc """ - Configure an authless client connection - - # Returns - - Tesla.Env.client - """ - @spec new() :: Tesla.Env.client + @spec new() :: Tesla.Env.client() def new do - Tesla.client([]) + Tesla.client(middleware(), adapter()) + end + + @doc """ + Configure a client that may have authentication. + + ### Parameters + + {{#hasOAuthMethods}} + The first parameter *may* be a `token` (a string, a token fetcher class, + or a module/function tuple) or a keyword list of `options`. They are + documented separately, but only *one* of them will be passed. + + - `token`: a String or a function of arity one. This value, or the result + of the function call, will be set as a bearer token in the + `authorization` header. + {{/hasOAuthMethods}} + - `options`: a keyword list of OpenAPIPetstore.Connection.options. + + ### Returns + + Tesla.Env.client + """ + {{#hasOAuthMethods}} + @spec new(String.t() | token_fetcher | options) :: Tesla.Env.client() + {{/hasOAuthMethods}} + {{^hasOAuthMethods}} + @spec new(options) :: Tesla.Env.client() + {{/hasOAuthMethods}} + {{#hasOAuthMethods}} + def new(token) when is_binary(token) or is_function(token, 1) or is_tuple(token) do + new(token: token) + end + {{/hasOAuthMethods}} + + def new(options) when is_list(options) do + options + |> middleware() + |> Tesla.client(adapter()) + end + + {{#hasOAuthMethods}} + {{#hasHttpBasicMethods}} + @doc """ + Configure a client using bearer authentication with scopes, or with + username and password for basic authentication. + + ### Parameters + + - `token_or_username`: a String representing a bearer token or a username, + depending on the type of the next parameter, or a function arity one + that returns a bearer token. + - `scopes_or_password`: a list of Strings represenging OAuth2 scopes, or + a single string that is the password for the username provided. + - `options`: a keyword list of OpenAPIPetstore.Connection.options. + + ### Returns + + Tesla.Env.client + """ + @spec new( + token_or_username :: String.t() | token_fetcher, + scopes_or_password :: list(String.t()) | String.t(), + options + ) :: Tesla.Env.client() + {{/hasHttpBasicMethods}} + {{^hasHttpBasicMethods}} + @doc """ + Configure a client using bearer authentication with scopes. + + ### Parameters + + - `token`: a String or a function of arity one. This value, or the result + of the function call, will be set as a bearer token in the + `authorization` header. + - `scopes`: a list of Strings represenging OAuth2 scopes. + - `options`: a keyword list of OpenAPIPetstore.Connection.options. + + ### Returns + + Tesla.Env.client + """ + @spec new(String.t() | token_fetcher, list(String.t()), options) :: Tesla.Env.client() + {{/hasHttpBasicMethods}} + {{/hasOAuthMethods}} + {{^hasOAuthMethods}} + {{#hasHttpBasicMethods}} + @doc """ + Configure a client using username and password for basic authentication. + + ### Parameters + + - `username`: a String representing a username. + - `password`: a String representing a password. + - `options`: a keyword list of {{moduleName}}.Connection.options. + + ### Returns + + Tesla.Env.client + """ + @spec new(String.t(), String.t()), options) :: Tesla.Env.client() + {{/hasHttpBasicMethods}} + {{/hasOAuthMethods}} + + {{#hasOAuthMethods}} + def new(token_or_username, scopes_or_password, options \\ []) + + def new(token, scopes, options) + when (is_binary(token) or is_function(token, 1) or is_tuple(token)) and is_list(scopes) do + options + |> Keyword.merge(token: token, token_scopes: scopes) + |> new() + end + {{/hasOAuthMethods}} + + {{#hasHttpBasicMethods}} + def new(username, password, options) when is_binary(username) and is_binary(password) do + options + |> Keyword.merge(username: username, password: password) + |> new() + end + {{/hasHttpBasicMethods}} + + @doc """ + Returns fully configured middleware for passing to Tesla.client/2. + """ + @spec middleware(options) :: [Tesla.Client.middleware()] + def middleware(options \\ []) do + base_url = + Keyword.get( + options, + :base_url, + Application.get_env({{#atom}}{{#underscored}}{{packageName}}{{/underscored}}{{/atom}}, :base_url, @default_base_url) + ) + + tesla_options = Application.get_env(:tesla, __MODULE__, []) + middleware = Keyword.get(tesla_options, :middleware, []) + json_engine = Keyword.get(tesla_options, :json, Poison) + + user_agent = + Keyword.get( + options, + :user_agent, + Keyword.get( + tesla_options, + :user_agent, + "openapi-generator - {{moduleName}} {{appVersion}} - elixir" + ) + ) + + {{#hasHttpBasicMethods}} + username = Keyword.get(options, :username) + password = Keyword.get(options, :password) + middleware = + if username || password do + [{Tesla.Middleware.BasicAuth, %{username: username, password: password}} | middleware] + else + middleware + end + {{/hasHttpBasicMethods}} + + {{#hasOAuthMethods}} + middleware = + if token = Keyword.get(options, :token) do + scopes = Keyword.get(options, :token_scopes, @default_scopes) + [authorization(token, scopes) | middleware] + else + middleware + end + {{/hasOAuthMethods}} + + [ + {Tesla.Middleware.BaseUrl, base_url}, + {Tesla.Middleware.Headers, [{"user-agent", user_agent}]}, + {Tesla.Middleware.EncodeJson, engine: json_engine} + | middleware + ] + end + + {{#hasOAuthMethods}} + @doc """ + Returns an authentication middleware tuple for a Tesla client that sets + the `authorization` header to the value of the provided bearer token. If + the token is provided as a function of arity one, it will be called with + a list of requested scopes that will obtain an OAuth2 token. + + ### Parameters + + - `token`: a String or a function of arity one. This value, or the result + of the function call, will be set as a bearer token in the + `authorization` header. + + - `scopes`: an optional list of scopes for use with the token fetcher + function. Ignored when `token` is provided as a String. Defaults to + `#{inspect(@default_scopes)}`. + + ### Returns + + `{Tesla.Middleware.Headers, [{"authorization", TOKEN}]}` + """ + @spec authorization(String.t() | token_fetcher, list(String.t())) :: + Tesla.Client.middleware() + def authorization(token, scopes \\ @default_scopes) + + def authorization(token, _scopes) when is_binary(token) do + {Tesla.Middlware.Headers, ["authorization", token]} + end + + def authorization({module, function}, scopes) when is_atom(module) and is_atom(function) do + apply(module, function, [scopes]) + end + + def authorization(token_fetcher, scopes) when is_function(token_fetcher, 1) do + authorization(token_fetcher.(scopes)) + end + {{/hasOAuthMethods}} + + @doc """ + Returns the default adapter for this API. + """ + def adapter do + :tesla + |> Application.get_env(__MODULE__, []) + |> Keyword.get(:adapter, nil) end end diff --git a/modules/openapi-generator/src/main/resources/elixir/deserializer.ex.mustache b/modules/openapi-generator/src/main/resources/elixir/deserializer.ex.mustache index ada1cf1346..91e6414afd 100644 --- a/modules/openapi-generator/src/main/resources/elixir/deserializer.ex.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/deserializer.ex.mustache @@ -12,24 +12,33 @@ defmodule {{moduleName}}.Deserializer do model |> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: [struct(mod)]])))) end + def deserialize(model, field, :struct, mod, options) do model |> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: struct(mod)])))) end + def deserialize(model, field, :map, mod, options) do model - |> Map.update!(field, &(Map.new(&1, fn {key, val} -> {key, Poison.Decode.decode(val, Keyword.merge(options, [as: struct(mod)]))} end))) + |> Map.update!( + field, + &Map.new(&1, fn {key, val} -> + {key, Poison.Decode.decode(val, Keyword.merge(options, [as: struct(mod)]))} + end) + ) end + def deserialize(model, field, :date, _, _options) do value = Map.get(model, field) case is_binary(value) do - true -> case DateTime.from_iso8601(value) do - {:ok, datetime, _offset} -> - Map.put(model, field, datetime) - _ -> - model - end - false -> model + true -> + case DateTime.from_iso8601(value) do + {:ok, datetime, _offset} -> Map.put(model, field, datetime) + _ -> model + end + + false -> + model end end end diff --git a/modules/openapi-generator/src/main/resources/elixir/gitignore.mustache b/modules/openapi-generator/src/main/resources/elixir/gitignore.mustache index b6012c77a3..5aa3f68181 100644 --- a/modules/openapi-generator/src/main/resources/elixir/gitignore.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/gitignore.mustache @@ -18,3 +18,6 @@ erl_crash.dump # Also ignore archive artifacts (built via "mix archive.build"). *.ez + +# Ignore elixir LS +/.elixir_ls diff --git a/modules/openapi-generator/src/main/resources/elixir/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/elixir/licenseInfo.mustache index 6e4e7a44c6..d1a2fd0a00 100644 --- a/modules/openapi-generator/src/main/resources/elixir/licenseInfo.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/licenseInfo.mustache @@ -1,6 +1,5 @@ {{#licenseHeader}}{{.}} {{/licenseHeader}} -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator {{generatorVersion}} (https://openapi-generator.tech). +# Do not edit this file manually. diff --git a/modules/openapi-generator/src/main/resources/elixir/mix.exs.mustache b/modules/openapi-generator/src/main/resources/elixir/mix.exs.mustache index aa05473908..71b8143b9c 100644 --- a/modules/openapi-generator/src/main/resources/elixir/mix.exs.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/mix.exs.mustache @@ -2,14 +2,16 @@ defmodule {{moduleName}}.Mixfile do use Mix.Project def project do - [app: :{{#underscored}}{{packageName}}{{/underscored}}, - version: "{{appVersion}}", - elixir: "~> {{supportedElixirVersion}}", - build_embedded: Mix.env == :prod, - start_permanent: Mix.env == :prod, - package: package(), - description: "{{appDescription}}", - deps: deps()] + [ + app: {{#atom}}{{#underscored}}{{packageName}}{{/underscored}}{{/atom}}, + version: "{{appVersion}}", + elixir: "~> {{supportedElixirVersion}}", + build_embedded: Mix.env() == :prod, + start_permanent: Mix.env() == :prod, + package: package(), + description: "{{appDescription}}", + deps: deps() + ] end # Configuration for the OTP application @@ -37,11 +39,13 @@ defmodule {{moduleName}}.Mixfile do ] end - defp package() do - [ - name: "{{#underscored}}{{packageName}}{{/underscored}}", - files: ~w(.formatter.exs config lib mix.exs README* LICENSE*), - licenses: ["{{licenseId}}"] - ] + defp package do + [ + name: "{{#underscored}}{{packageName}}{{/underscored}}", + files: ~w(.formatter.exs config lib mix.exs README* LICENSE*), +{{#licenseId}} + licenses: ["{{licenseId}}"] +{{/licenseId}} + ] end end diff --git a/modules/openapi-generator/src/main/resources/elixir/request_builder.ex.mustache b/modules/openapi-generator/src/main/resources/elixir/request_builder.ex.mustache index 70e6fe297c..825beac5a4 100644 --- a/modules/openapi-generator/src/main/resources/elixir/request_builder.ex.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/request_builder.ex.mustache @@ -5,113 +5,130 @@ defmodule {{moduleName}}.RequestBuilder do """ @doc """ - Specify the request method when building a request + Specify the request `method` when building a request. - ## Parameters + Does not override the `method` if one has already been specified. - - request (Map) - Collected request options - - m (atom) - Request method + ### Parameters - ## Returns + - `request` (Map) - Collected request options + - `method` (atom) - Request method + + ### Returns Map """ - @spec method(map(), atom) :: map() - def method(request, m) do - Map.put_new(request, :method, m) + @spec method(map(), atom()) :: map() + def method(request, method) do + Map.put_new(request, :method, method) end @doc """ - Specify the request method when building a request + Specify the request URL when building a request. - ## Parameters + Does not override the `url` if one has already been specified. - - request (Map) - Collected request options - - u (String) - Request URL + ### Parameters - ## Returns + - `request` (Map) - Collected request options + - `url` (String) - Request URL + + ### Returns Map """ - @spec url(map(), String.t) :: map() - def url(request, u) do - Map.put_new(request, :url, u) + @spec url(map(), String.t()) :: map() + def url(request, url) do + Map.put_new(request, :url, url) end @doc """ - Add optional parameters to the request + Add optional parameters to the request. - ## Parameters + ### Parameters - - request (Map) - Collected request options - - definitions (Map) - Map of parameter name to parameter location. - - options (KeywordList) - The provided optional parameters + - `request` (Map) - Collected request options + - `definitions` (Map) - Map of parameter name to parameter location. + - `options` (KeywordList) - The provided optional parameters - ## Returns + ### Returns Map """ - @spec add_optional_params(map(), %{optional(atom) => atom}, keyword()) :: map() + @spec add_optional_params(map(), %{optional(atom) => atom()}, keyword()) :: map() def add_optional_params(request, _, []), do: request + def add_optional_params(request, definitions, [{key, value} | tail]) do case definitions do %{^key => location} -> request |> add_param(location, key, value) |> add_optional_params(definitions, tail) + _ -> add_optional_params(request, definitions, tail) end end @doc """ - Add optional parameters to the request + Add non-optional parameters to the request. - ## Parameters + ### Parameters - - request (Map) - Collected request options - - location (atom) - Where to put the parameter - - key (atom) - The name of the parameter - - value (any) - The value of the parameter + - `request` (Map) - Collected request options + - `location` (atom) - Where to put the parameter + - `key` (atom) - The name of the parameter + - `value` (any) - The value of the parameter - ## Returns + ### Returns Map """ - @spec add_param(map(), atom, atom, any()) :: map() + @spec add_param(map(), atom(), atom(), any()) :: map() def add_param(request, :body, :body, value), do: Map.put(request, :body, value) + def add_param(request, :body, key, value) do request |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0) - |> Map.update!(:body, &(Tesla.Multipart.add_field(&1, key, Poison.encode!(value), headers: [{:"Content-Type", "application/json"}]))) + |> Map.update!(:body, fn multipart -> + Tesla.Multipart.add_field( + multipart, + key, + Poison.encode!(value), + headers: [{:"Content-Type", "application/json"}] + ) + end) end + def add_param(request, :headers, key, value) do - request - |> Tesla.put_header(key, value) + Tesla.put_header(request, key, value) end + def add_param(request, :file, name, path) do request |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0) |> Map.update!(:body, &(Tesla.Multipart.add_file(&1, path, name: name))) end + def add_param(request, :form, name, value) do - request - |> Map.update(:body, %{name => value}, &(Map.put(&1, name, value))) + Map.update(request, :body, %{name => value}, &(Map.put(&1, name, value))) end + def add_param(request, location, key, value) do Map.update(request, location, [{key, value}], &(&1 ++ [{key, value}])) end @doc """ - Due to a bug in httpc, POST, PATCH and PUT requests will fail, if the body is empty + This function ensures that the `body` parameter is always set. - This function will ensure, that the body param is always set + When using Tesla with the `httpc` adapter (the default adapter), there is a + bug where POST, PATCH and PUT requests will fail if the body is empty. - ## Parameters + ### Parameters - - request (Map) - Collected request options + - `request` (Map) - Collected request options - ## Returns + ### Returns Map """ @@ -124,39 +141,44 @@ defmodule {{moduleName}}.RequestBuilder do Map.put_new(request, :body, "") end + @type status_code :: 100..599 + @type response_mapping :: [{status_code, struct() | false}] + @doc """ - Handle the response for a Tesla request + Evaluate the response from a Tesla request. + Decode the response for a Tesla request. - ## Parameters + ### Parameters - - arg1 (Tesla.Env.t | term) - The response object - - arg2 (:false | struct | [struct]) - The shape of the struct to deserialize into + - `result` (Tesla.Env.result()): The response from Tesla.request/2. + - `mapping` ([{http_status, struct}]): The mapping for status to struct for decoding. - ## Returns + ### Returns - {:ok, struct} on success - {:error, term} on failure + - `{:ok, struct}` or `{:ok, Tesla.Env.t()}` on success + - `{:error, term}` on failure """ - @spec decode(Tesla.Env.t() | term(), false | struct() | [struct()]) :: - {:ok, struct()} | {:ok, Tesla.Env.t()} | {:error, any} - def decode(%Tesla.Env{} = env, false), do: {:ok, env} - def decode(%Tesla.Env{body: body}, struct), do: Poison.decode(body, as: struct) - + @spec evaluate_response(Tesla.Env.result(), response_mapping) :: {:ok, struct()} | Tesla.Env.result() def evaluate_response({:ok, %Tesla.Env{} = env}, mapping) do - resolve_mapping(env, mapping) + resolve_mapping(env, mapping, nil) end def evaluate_response({:error, _} = error, _), do: error - def resolve_mapping(env, mapping, default \\ nil) - - def resolve_mapping(%Tesla.Env{status: status} = env, [{mapping_status, struct} | _], _) + defp resolve_mapping(%Tesla.Env{status: status} = env, [{mapping_status, struct} | _], _) when status == mapping_status do decode(env, struct) end - def resolve_mapping(env, [{:default, struct} | tail], _), do: resolve_mapping(env, tail, struct) - def resolve_mapping(env, [_ | tail], struct), do: resolve_mapping(env, tail, struct) - def resolve_mapping(env, [], nil), do: {:error, env} - def resolve_mapping(env, [], struct), do: decode(env, struct) + defp resolve_mapping(env, [{:default, struct} | tail], _), do: resolve_mapping(env, tail, struct) + + defp resolve_mapping(env, [_ | tail], struct), do: resolve_mapping(env, tail, struct) + + defp resolve_mapping(env, [], nil), do: {:error, env} + + defp resolve_mapping(env, [], struct), do: decode(env, struct) + + defp decode(%Tesla.Env{} = env, false), do: {:ok, env} + + defp decode(%Tesla.Env{body: body}, struct), do: Poison.decode(body, as: struct) end diff --git a/modules/openapi-generator/src/main/resources/elixir/runtime.exs.mustache b/modules/openapi-generator/src/main/resources/elixir/runtime.exs.mustache index e10c690c80..30d2a8f9f4 100644 --- a/modules/openapi-generator/src/main/resources/elixir/runtime.exs.mustache +++ b/modules/openapi-generator/src/main/resources/elixir/runtime.exs.mustache @@ -7,6 +7,6 @@ import Config # any compile-time configuration in here, as it won't be applied. # The block below contains prod specific runtime configuration. -if env = System.get_env("{{#env_var}}{{appName}}{{/env_var}}_BASE_URI") do - config :{{#underscored}}{{appName}}{{/underscored}}, base_url: env +if base_url = System.get_env("{{#env_var}}{{packageName}}{{/env_var}}_BASE_URI") do + config {{#atom}}{{#underscored}}{{packageName}}{{/underscored}}{{/atom}}, base_url: base_url end diff --git a/modules/openapi-generator/src/main/resources/go/README.mustache b/modules/openapi-generator/src/main/resources/go/README.mustache index b00e98e55c..f13136a8f3 100644 --- a/modules/openapi-generator/src/main/resources/go/README.mustache +++ b/modules/openapi-generator/src/main/resources/go/README.mustache @@ -69,7 +69,7 @@ Each operation can use different server URL defined using `OperationServers` map An operation is uniquely identified by `"{classname}Service.{nickname}"` string. Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. -``` +```golang ctx := context.WithValue(context.Background(), {{packageName}}.ContextOperationServerIndices, map[string]int{ "{classname}Service.{nickname}": 2, }) diff --git a/modules/openapi-generator/src/main/resources/go/api.mustache b/modules/openapi-generator/src/main/resources/go/api.mustache index 000fe627c1..c2c977178b 100644 --- a/modules/openapi-generator/src/main/resources/go/api.mustache +++ b/modules/openapi-generator/src/main/resources/go/api.mustache @@ -371,7 +371,7 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class if localVarHTTPResponse.StatusCode >= 400 && localVarHTTPResponse.StatusCode < 500 { {{/is4xx}} {{#is5xx}} - if localVarHTTPResponse.StatusCode >= 500 + if localVarHTTPResponse.StatusCode >= 500 { {{/is5xx}} {{/range}} {{^range}} diff --git a/modules/openapi-generator/src/main/resources/go/api_test.mustache b/modules/openapi-generator/src/main/resources/go/api_test.mustache new file mode 100644 index 0000000000..0bbbbf757b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go/api_test.mustache @@ -0,0 +1,52 @@ +/* +{{#appName}} +{{{.}}} +{{/appName}} + +Testing {{classname}}Service + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package {{packageName}} + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + {{goImportAlias}} "./openapi" +) + +func Test_{{packageName}}_{{classname}}Service(t *testing.T) { + + configuration := {{goImportAlias}}.NewConfiguration() + apiClient := {{goImportAlias}}.NewAPIClient(configuration) + +{{#operations}} +{{#operation}} + t.Run("Test {{classname}}Service {{{nickname}}}", func(t *testing.T) { + + {{^pathParams}} + t.Skip("skip test") // remove to run test + {{/pathParams}} + {{#pathParams}} + {{#-first}} + t.Skip("skip test") // remove to run test + + {{/-first}} + var {{paramName}} {{{dataType}}} + {{/pathParams}} + + resp, httpRes, err := apiClient.{{classname}}.{{operationId}}(context.Background(){{#pathParams}}, {{paramName}}{{/pathParams}}).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +{{/operation}} +{{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/htmlDocs2/index.mustache b/modules/openapi-generator/src/main/resources/htmlDocs2/index.mustache index 0c9f5e7436..3f6fc2c8a2 100644 --- a/modules/openapi-generator/src/main/resources/htmlDocs2/index.mustache +++ b/modules/openapi-generator/src/main/resources/htmlDocs2/index.mustache @@ -456,6 +456,7 @@ if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/JavaTimeFormatter.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/JavaTimeFormatter.mustache new file mode 100644 index 0000000000..f3fb34e559 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/JavaTimeFormatter.mustache @@ -0,0 +1,53 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +{{>generatedAnnotation}} +public class JavaTimeFormatter { + + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + /** + * Format the given {@code OffsetDateTime} object into string. + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/RFC3339DateFormat.mustache new file mode 100644 index 0000000000..311616a4ef --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/RFC3339DateFormat.mustache @@ -0,0 +1,46 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.text.DecimalFormat; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + this.numberFormat = new DecimalFormat(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return super.clone(); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/StringUtil.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/StringUtil.mustache new file mode 100644 index 0000000000..e3d5d6e908 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/StringUtil.mustache @@ -0,0 +1,72 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.util.Collection; +import java.util.Iterator; + +{{>generatedAnnotation}} +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

        + * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

        + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/additionalEnumTypeAnnotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/additionalEnumTypeAnnotations.mustache new file mode 100644 index 0000000000..aa524798b4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/additionalEnumTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalEnumTypeAnnotations}}{{{.}}} +{{/additionalEnumTypeAnnotations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/additionalModelTypeAnnotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/additionalModelTypeAnnotations.mustache new file mode 100644 index 0000000000..f4871c02cc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/additionalModelTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalModelTypeAnnotations}}{{{.}}} +{{/additionalModelTypeAnnotations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api.mustache new file mode 100644 index 0000000000..6367b03ed2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api.mustache @@ -0,0 +1,61 @@ +{{>licenseInfo}} +package {{package}}; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import {{rootJavaEEPackage}}.ws.rs.*; +import {{rootJavaEEPackage}}.ws.rs.core.Response; +import {{rootJavaEEPackage}}.ws.rs.core.MediaType; + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +{{#imports}}import {{import}}; +{{/imports}} + +{{#appName}} +/** + * {{{appName}}} + * + {{#appDescription}} + *

        {{{.}}} + {{/appDescription}} + */ +{{/appName}} +@RegisterRestClient{{#configKey}}(configKey="{{configKey}}"){{/configKey}} +@RegisterProvider(ApiExceptionMapper.class) +@Path("{{#useAnnotatedBasePath}}{{contextPath}}{{/useAnnotatedBasePath}}{{commonPath}}") +public interface {{classname}} { +{{#operations}} +{{#operation}} + + {{#summary}} + /** + * {{summary}} + {{#notes}} + * {{.}} + {{/notes}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{/summary}} + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{{path}}}"){{/subresourceOperation}} +{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }) +{{/hasConsumes}} +{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }) +{{/hasProduces}} + {{{returnType}}}{{^returnType}}void{{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>cookieParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException, ProcessingException; +{{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/apiOperation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/apiOperation.mustache new file mode 100644 index 0000000000..97adb0ea28 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/apiOperation.mustache @@ -0,0 +1,28 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import io.swagger.v3.oas.models.Operation; + +public class ApiOperation { + private final String path; + private final String method; + private final Operation operation; + + public ApiOperation(String path, String method, Operation operation) { + this.path = path; + this.method = method; + this.operation = operation; + } + + public Operation getOperation() { + return operation; + } + + public String getPath() { + return path; + } + + public String getMethod() { + return method; + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_doc.mustache new file mode 100644 index 0000000000..ba9757d1ed --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_doc.mustache @@ -0,0 +1,55 @@ +# {{classname}}{{#description}} + +{{.}}{{/description}} + +All URIs are relative to *{{basePath}}* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +{{#operations}}{{#operation}}| [**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{commonPath}}{{path}} | {{summary}} | +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{operationId}} + +> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + +{{summary}}{{#notes}} + +{{.}}{{/notes}} + +### Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------|{{/-last}}{{/allParams}} +{{#allParams}}| **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{^isContainer}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}}{{/isContainer}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} | +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
        {{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_exception.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_exception.mustache new file mode 100644 index 0000000000..d9fb5ee91d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_exception.mustache @@ -0,0 +1,19 @@ +{{>licenseInfo}} +package {{apiPackage}}; + +import {{rootJavaEEPackage}}.ws.rs.core.Response; + +public class ApiException extends Exception { + private static final long serialVersionUID = 1L; + + private final Response response; + + public ApiException(Response response) { + super("Api response has status code " + response.getStatus()); + this.response = response; + } + + public Response getResponse() { + return this.response; + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_exception_mapper.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_exception_mapper.mustache new file mode 100644 index 0000000000..ac4db62e8b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_exception_mapper.mustache @@ -0,0 +1,22 @@ +{{>licenseInfo}} +package {{apiPackage}}; + +import {{rootJavaEEPackage}}.ws.rs.core.MultivaluedMap; +import {{rootJavaEEPackage}}.ws.rs.core.Response; +import {{rootJavaEEPackage}}.ws.rs.ext.Provider; + +import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper; + +@Provider +public class ApiExceptionMapper implements ResponseExceptionMapper { + + @Override + public boolean handles(int status, MultivaluedMap headers) { + return status >= 400; + } + + @Override + public ApiException toThrowable(Response response) { + return new ApiException(response); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_test.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_test.mustache new file mode 100644 index 0000000000..cbe676a88b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/api_test.mustache @@ -0,0 +1,64 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +{{/fullJavaUtil}} + +/** + {{#appName}} + * {{{.}}} Test + * + {{/appName}} + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private static {{classname}} client; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() throws MalformedURLException { + client = RestClientBuilder.newBuilder() + .baseUrl(new URL(baseUrl)) + .register(ApiException.class) + .build({{classname}}.class); + } + + {{#operations}}{{#operation}} + /** + {{#summary}} + * {{summary}} + * + {{#notes}} + * {{.}} + * + {{/notes}} + {{/summary}} + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() throws Exception { + {{#allParams}} + {{/allParams}} + //{{#returnType}}{{{.}}} response = {{/returnType}}client.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + //{{#returnType}}assertNotNull(response);{{/returnType}} + } + {{/operation}}{{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/auth/ApiKeyAuth.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/auth/ApiKeyAuth.mustache new file mode 100644 index 0000000000..991ae23500 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/auth/ApiKeyAuth.mustache @@ -0,0 +1,66 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; + +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/auth/HttpBasicAuth.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/auth/HttpBasicAuth.mustache new file mode 100644 index 0000000000..b5c72de6e7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/auth/HttpBasicAuth.mustache @@ -0,0 +1,42 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; + +import java.util.Base64; +import java.nio.charset.StandardCharsets; + +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.put("Authorization", "Basic " + Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/auth/HttpBearerAuth.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/auth/HttpBearerAuth.mustache new file mode 100644 index 0000000000..322281f871 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/auth/HttpBearerAuth.mustache @@ -0,0 +1,49 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; + +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return bearerToken; + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { + if(bearerToken == null) { + return; + } + + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/bodyParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/bodyParams.mustache new file mode 100644 index 0000000000..c7d1abfe52 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/cookieParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/cookieParams.mustache new file mode 100644 index 0000000000..fea14348d7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/cookieParams.mustache @@ -0,0 +1 @@ +{{#isCookieParam}}@CookieParam("{{baseName}}"){{^isContainer}}{{#defaultValue}} @DefaultValue("{{{.}}}"){{/defaultValue}}{{/isContainer}} {{#useSwaggerAnnotations}}{{#description}} @ApiParam("{{.}}"){{/description}}{{/useSwaggerAnnotations}} {{{dataType}}} {{paramName}}{{/isCookieParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/enumClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/enumClass.mustache new file mode 100644 index 0000000000..d32efebf48 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/enumClass.mustache @@ -0,0 +1,46 @@ +{{#jsonb}} + @JsonbTypeSerializer({{datatypeWithEnum}}.Serializer.class) + @JsonbTypeDeserializer({{datatypeWithEnum}}.Deserializer.class) +{{/jsonb}} +{{>additionalEnumTypeAnnotations}}public enum {{datatypeWithEnum}} { + + {{#allowableValues}} + {{#enumVars}}{{name}}({{dataType}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{/allowableValues}} + + {{dataType}} value; + + {{datatypeWithEnum}} ({{dataType}} v) { + value = v; + } + + public {{dataType}} value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + {{#jsonb}} + public static final class Deserializer implements JsonbDeserializer<{{datatypeWithEnum}}> { + @Override + public {{datatypeWithEnum}} deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(parser.getString())) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");{{/useNullForUnknownEnumValue}} + } + } + + public static final class Serializer implements JsonbSerializer<{{datatypeWithEnum}}> { + @Override + public void serialize({{datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.value); + } + } + {{/jsonb}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/enumOuterClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/enumOuterClass.mustache new file mode 100644 index 0000000000..39417c635f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/enumOuterClass.mustache @@ -0,0 +1,39 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +{{/jackson}} + +/** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ +{{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override +{{#jackson}} + @JsonValue +{{/jackson}} + public String toString() { + return String.valueOf(value); + } + +{{#jackson}} + @JsonCreator +{{/jackson}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + text + "'");{{/useNullForUnknownEnumValue}} + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/enum_outer_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/enum_outer_doc.mustache new file mode 100644 index 0000000000..20c512aaea --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/enum_outer_doc.mustache @@ -0,0 +1,7 @@ +# {{classname}} + +## Enum + +{{#allowableValues}}{{#enumVars}} +* `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/formParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/formParams.mustache new file mode 100644 index 0000000000..fa85e0c894 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/generatedAnnotation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/generatedAnnotation.mustache new file mode 100644 index 0000000000..356a48872a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/generatedAnnotation.mustache @@ -0,0 +1 @@ +@{{rootJavaEEPackage}}.annotation.Generated(value = "{{generatorClass}}"{{^hideGenerationTimestamp}}, date = "{{generatedDate}}"{{/hideGenerationTimestamp}}) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/headerParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/headerParams.mustache new file mode 100644 index 0000000000..25d690c90e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/jackson_annotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/jackson_annotations.mustache new file mode 100644 index 0000000000..ccde126f54 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/jackson_annotations.mustache @@ -0,0 +1,19 @@ +{{! + If this is map and items are nullable, make sure that nulls are included. + To determine what JsonInclude.Include method to use, consider the following: + * If the field is required, always include it, even if it is null. + * Else use custom behaviour, IOW use whatever is defined on the object mapper + }} + @JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}) + @JsonInclude({{#isMap}}{{#items.isNullable}}content = JsonInclude.Include.ALWAYS, {{/items.isNullable}}{{/isMap}}value = JsonInclude.Include.{{#required}}ALWAYS{{/required}}{{^required}}USE_DEFAULTS{{/required}}) + {{#withXml}} + {{^isContainer}} + @JacksonXmlProperty({{#isXmlAttribute}}isAttribute = true, {{/isXmlAttribute}}{{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}localName = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/isContainer}} + {{#isContainer}} + {{#isXmlWrapped}} + // items.xmlName={{items.xmlName}} + @JacksonXmlElementWrapper(useWrapping = {{isXmlWrapped}}, {{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}localName = "{{#items.xmlName}}{{items.xmlName}}{{/items.xmlName}}{{^items.xmlName}}{{items.baseName}}{{/items.xmlName}}") + {{/isXmlWrapped}} + {{/isContainer}} + {{/withXml}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/licenseInfo.mustache new file mode 100644 index 0000000000..be193d0c4f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} + * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/model.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/model.mustache new file mode 100644 index 0000000000..ad4e98b8a4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/model.mustache @@ -0,0 +1,19 @@ +{{>licenseInfo}} +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} + +{{#models}} +{{#model}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} +{{^isEnum}} +{{>pojo}} +{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/modelInnerEnum.mustache new file mode 100644 index 0000000000..a9c99783fd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/modelInnerEnum.mustache @@ -0,0 +1,95 @@ + /** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ +{{#gson}} + @JsonAdapter({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.Adapter.class) +{{/gson}} +{{#jsonb}} + @JsonbTypeSerializer({{datatypeWithEnum}}.Serializer.class) + @JsonbTypeDeserializer({{datatypeWithEnum}}.Deserializer.class) +{{/jsonb}} +{{#withXml}} + @XmlType(name="{{datatypeWithEnum}}") + @XmlEnum({{dataType}}.class) +{{/withXml}} + {{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { + {{#allowableValues}} + {{#enumVars}} + {{#enumDescription}} + /** + * {{.}} + */ + {{/enumDescription}} + {{#withXml}} + @XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{/withXml}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + +{{#jackson}} + @JsonValue +{{/jackson}} + public {{{dataType}}} getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +{{#jackson}} + @JsonCreator +{{/jackson}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue({{{dataType}}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.equals(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/isNullable}} + } +{{#gson}} + + public static class Adapter extends TypeAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}> { + @Override + public void write(final JsonWriter jsonWriter, final {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isFloat}}(float){{/isFloat}} jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{^isNumber}}{{^isInteger}}{{#isFloat}}nextDouble{{/isFloat}}{{^isFloat}}next{{{dataType}}}{{/isFloat}}(){{/isInteger}}{{/isNumber}}; + return {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } + } +{{/gson}} +{{#jsonb}} + public static final class Deserializer implements JsonbDeserializer<{{datatypeWithEnum}}> { + @Override + public {{datatypeWithEnum}} deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(parser.getString())) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");{{/useNullForUnknownEnumValue}} + } + } + + public static final class Serializer implements JsonbSerializer<{{datatypeWithEnum}}> { + @Override + public void serialize({{datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.value); + } + } +{{/jsonb}} + } diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/model_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/model_doc.mustache new file mode 100644 index 0000000000..9a7fe146a4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/model_doc.mustache @@ -0,0 +1,4 @@ +{{#models}}{{#model}} + +{{#isEnum}}{{>enum_outer_doc}}{{/isEnum}}{{^isEnum}}{{>pojo_doc}}{{/isEnum}} +{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/model_test.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/model_test.mustache new file mode 100644 index 0000000000..92c1e7ee2e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/model_test.mustache @@ -0,0 +1,49 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import org.junit.jupiter.api.Test; + +{{#fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * Model tests for {{classname}} + */ +public class {{classname}}Test { + {{#models}} + {{#model}} + {{^vendorExtensions.x-is-one-of-interface}} + {{^isEnum}} + private final {{classname}} model = new {{classname}}(); + + {{/isEnum}} + /** + * Model tests for {{classname}} + */ + @Test + public void test{{classname}}() { + // TODO: test {{classname}} + } + + {{#allVars}} + /** + * Test the property '{{name}}' + */ + @Test + public void {{name}}Test() { + // TODO: test {{name}} + } + + {{/allVars}} + {{/vendorExtensions.x-is-one-of-interface}} + {{/model}} + {{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/oneof_interface.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/oneof_interface.mustache new file mode 100644 index 0000000000..02deb483d5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/oneof_interface.mustache @@ -0,0 +1,6 @@ +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>typeInfoAnnotation}}{{>xmlAnnotation}} +public interface {{classname}} {{#vendorExtensions.x-implements}}{{#-first}}extends {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { + {{#discriminator}} + public {{propertyType}} {{propertyGetter}}(); + {{/discriminator}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/openapi.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/openapi.mustache new file mode 100644 index 0000000000..34fbb53f33 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pathParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pathParams.mustache new file mode 100644 index 0000000000..ba153467a6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo.mustache new file mode 100644 index 0000000000..84115fa7d0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo.mustache @@ -0,0 +1,155 @@ + +{{#jsonb}} +import java.lang.reflect.Type; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeDeserializer; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.DeserializationContext; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbDeserializer; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.SerializationContext; +import {{rootJavaEEPackage}}.json.stream.JsonGenerator; +import {{rootJavaEEPackage}}.json.stream.JsonParser; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbProperty; +{{#vendorExtensions.x-has-readonly-properties}} +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbCreator; +{{/vendorExtensions.x-has-readonly-properties}} +{{/jsonb}} + +{{#description}} +/** + * {{{.}}} + **/ +{{/description}} +{{>additionalModelTypeAnnotations}} +{{#vendorExtensions.x-class-extra-annotation}} +{{{vendorExtensions.x-class-extra-annotation}}} +{{/vendorExtensions.x-class-extra-annotation}} +public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensions.x-implements}}{{#-first}} implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { + {{#vars}}{{#isEnum}}{{^isContainer}} +{{>enumClass}}{{/isContainer}}{{#isContainer}}{{#mostInnerItems}} +{{>enumClass}}{{/mostInnerItems}}{{/isContainer}}{{/isEnum}} +{{#description}} + /** + * {{{.}}} + **/ +{{/description}} +{{#vendorExtensions.x-field-extra-annotation}} +{{{vendorExtensions.x-field-extra-annotation}}} +{{/vendorExtensions.x-field-extra-annotation}} +{{#isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#required}} = {{{defaultValue}}}{{/required}}{{^required}} = null{{/required}}; +{{/isContainer}} +{{^isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; +{{/isContainer}} + {{/vars}} +{{#vendorExtensions.x-has-readonly-properties}}{{#jsonb}} + public {{classname}}() { + } + + @JsonbCreator + public {{classname}}( + {{#readOnlyVars}} + @JsonbProperty("{{baseName}}") {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} + {{/readOnlyVars}} + ) { + {{#readOnlyVars}} + this.{{name}} = {{name}}; + {{/readOnlyVars}} + } + {{/jsonb}}{{/vendorExtensions.x-has-readonly-properties}} + {{#vars}} + /** + {{#description}} + * {{.}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + * @return {{name}} + {{#deprecated}} + * @deprecated + {{/deprecated}} + **/ +{{#deprecated}} + @Deprecated +{{/deprecated}} +{{#vendorExtensions.x-extra-annotation}} + {{{vendorExtensions.x-extra-annotation}}} +{{/vendorExtensions.x-extra-annotation}} + {{#withXml}}{{#isEnum}}{{^isArray}}{{^isMap}}public {{dataType}} {{getter}}() { + if ({{name}} == null) { + return null; + } + return {{name}}.value(); + }{{/isMap}}{{/isArray}}{{/isEnum}}{{/withXml}}{{^withXml}}{{#isEnum}}{{^isArray}}{{^isMap}}public {{datatypeWithEnum}} {{getter}}() { + return {{name}}; + }{{/isMap}}{{/isArray}}{{/isEnum}}{{/withXml}}{{#isEnum}}{{#isArray}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isArray}}{{/isEnum}}{{#isEnum}}{{#isMap}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isMap}}{{/isEnum}}{{^isEnum}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isEnum}} + + {{^isReadOnly}} + /** + * Set {{name}} + **/ + {{#vendorExtensions.x-setter-extra-annotation}} {{{vendorExtensions.x-setter-extra-annotation}}} + {{/vendorExtensions.x-setter-extra-annotation}}public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + {{#isArray}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.add({{name}}Item); + return this; + } + {{/isArray}} + {{#isMap}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMap}} + {{/isReadOnly}} + + {{/vars}} + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo_doc.mustache new file mode 100644 index 0000000000..bae0bc48cd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo_doc.mustache @@ -0,0 +1,37 @@ +# {{#vendorExtensions.x-is-one-of-interface}}Interface {{/vendorExtensions.x-is-one-of-interface}}{{classname}} + +{{#description}}{{&description}} +{{/description}} +{{^vendorExtensions.x-is-one-of-interface}} + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +{{#vars}}|**{{name}}** | {{#isEnum}}[**{{datatypeWithEnum}}**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isContainer}}{{#isArray}}{{#items}}{{#isModel}}[{{/isModel}}{{/items}}**{{baseType}}{{#items}}<{{dataType}}>**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/items}}{{/isArray}}{{#isMap}}{{#items}}{{#isModel}}[{{/isModel}}**Map<String, {{dataType}}>**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/items}}{{/isMap}}{{/isContainer}}{{^isContainer}}{{#isModel}}[{{/isModel}}**{{dataType}}**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/isContainer}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#isReadOnly}} [readonly]{{/isReadOnly}} | +{{/vars}} +{{#vars}}{{#isEnum}} + + +## Enum: {{datatypeWithEnum}} + +| Name | Value | +|---- | -----|{{#allowableValues}}{{#enumVars}} +| {{name}} | {{value}} |{{/enumVars}}{{/allowableValues}} +{{/isEnum}}{{/vars}} +{{#vendorExtensions.x-implements.0}} + +## Implemented Interfaces + +{{#vendorExtensions.x-implements}} +* {{{.}}} +{{/vendorExtensions.x-implements}} +{{/vendorExtensions.x-implements.0}} +{{/vendorExtensions.x-is-one-of-interface}} +{{#vendorExtensions.x-is-one-of-interface}} +## Implementing Classes + +{{#oneOf}} +* {{{.}}} +{{/oneOf}} +{{/vendorExtensions.x-is-one-of-interface}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pom.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pom.mustache new file mode 100644 index 0000000000..6deab37c81 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pom.mustache @@ -0,0 +1,90 @@ + + 4.0.0 + {{groupId}} + + io.helidon.applications + helidon-mp + {{helidonVersion}} + + + {{artifactId}} + {{artifactId}} + {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} + jar + + + + io.helidon.microprofile.rest-client + helidon-microprofile-rest-client + + + io.helidon.microprofile.config + helidon-microprofile-config + + + org.glassfish.jersey.ext.cdi + jersey-cdi1x + + + {{x-helidon-rootJavaEEDepPrefix}}.enterprise + {{x-helidon-rootJavaEEDepPrefix}}.enterprise.cdi-api + + + {{x-helidon-rootJavaEEDepPrefix}}.json + {{x-helidon-rootJavaEEDepPrefix}}.json-api + +{{#jackson}} + + org.glassfish.jersey.media + jersey-media-json-jackson + + + org.openapitools + jackson-databind-nullable + 0.2.2 + +{{/jackson}} +{{#jsonb}} + + org.glassfish.jersey.media + jersey-media-json-binding + + + {{x-helidon-rootJavaEEDepPrefix}}.json.bind + {{x-helidon-rootJavaEEDepPrefix}}.json.bind-api + +{{/jsonb}} + + org.junit.jupiter + junit-jupiter-api + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libs + + + + + org.jboss.jandex + jandex-maven-plugin + + + make-index + + + + + + diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/queryParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/queryParams.mustache new file mode 100644 index 0000000000..4b1a980896 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@QueryParam("{{baseName}}") {{^isContainer}}{{#defaultValue}}@DefaultValue("{{{.}}}") {{/defaultValue}}{{/isContainer}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/returnTypes.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/returnTypes.mustache new file mode 100644 index 0000000000..32f96a9047 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/returnTypes.mustache @@ -0,0 +1,4 @@ +{{#useGenericResponse}}Response{{/useGenericResponse}}{{! non-generic response: +}}{{^useGenericResponse}}{{! +}}{{{returnType}}}{{! +}}{{/useGenericResponse}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/typeInfoAnnotation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/typeInfoAnnotation.mustache new file mode 100644 index 0000000000..c833321ebf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/typeInfoAnnotation.mustache @@ -0,0 +1,17 @@ +{{#jackson}} + +@JsonIgnoreProperties( + value = "{{{discriminator.propertyBaseName}}}", // ignore manually set {{{discriminator.propertyBaseName}}}, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the {{{discriminator.propertyBaseName}}} to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{{discriminator.propertyBaseName}}}", visible = true) +{{#discriminator.mappedModels}} +{{#-first}} +@JsonSubTypes({ +{{/-first}} + @JsonSubTypes.Type(value = {{modelName}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{mappingName}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), +{{#-last}} +}) +{{/-last}} +{{/discriminator.mappedModels}} +{{/jackson}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ApiClient.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ApiClient.mustache new file mode 100644 index 0000000000..1ca0223fb4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ApiClient.mustache @@ -0,0 +1,276 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +{{#jsonb}}import {{rootJavaEEPackage}}.json.bind.JsonbBuilder; +import {{rootJavaEEPackage}}.json.bind.JsonbConfig; +{{/jsonb}} +{{#jackson}}import com.fasterxml.jackson.databind.ObjectMapper; +{{/jackson}} +{{#openApiNullable}} +{{#jackson}} +import org.openapitools.jackson.nullable.JsonNullableModule; +{{/jackson}} +{{/openApiNullable}} + +import io.helidon.config.Config; +{{#jsonb}} +import io.helidon.media.jsonb.JsonbSupport; +{{/jsonb}} +{{#jackson}} +import io.helidon.media.jackson.JacksonSupport; +{{/jackson}} +import io.helidon.webclient.WebClient; + +import java.net.URI; +import java.net.URLEncoder; +import java.time.Duration; +{{#java8}} +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +{{/java8}} +import java.util.Collection; +import java.util.Collections; +import java.util.List; +{{#jsonb}} +import java.util.Map; +{{/jsonb}} +import java.util.StringJoiner; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import static java.nio.charset.StandardCharsets.UTF_8; + +/** + * Configuration and utility class for API clients. + *

        + * Use the {@link ApiClient.Builder} class to prepare and ultimately create the {@code ApiClient} instance. + *

        + */ +public class ApiClient { + + private final WebClient webClient; + + /** + * @return a {@code Builder} for an {@code ApiClient} + */ + public static ApiClient.Builder builder() { + return new Builder(); + } + + /** + * URL encode a string in the UTF-8 encoding. + * + * @param s String to encode. + * @return URL-encoded representation of the input string. + */ + public static String urlEncode(String s) { + return URLEncoder.encode(s, UTF_8); + } + + /** + * Convert a URL query name/value parameter to a list of encoded {@link Pair} + * objects. + * + *

        The value can be null, in which case an empty list is returned.

        + * + * @param name The query name parameter. + * @param value The query value, which may not be a collection but may be + * null. + * @return A singleton list of the {@link Pair} objects representing the input + * parameters, which is encoded for use in a URL. If the value is null, an + * empty list is returned. + */ + public static List parameterToPairs(String name, Object value) { + if (name == null || name.isEmpty() || value == null) { + return Collections.emptyList(); + } + return Collections.singletonList(new Pair(urlEncode(name), urlEncode(valueToString(value)))); + } + + /** + * Convert a URL query name/collection parameter to a list of encoded + * {@link Pair} objects. + * + * @param collectionFormat The swagger collectionFormat string (csv, tsv, etc). + * @param name The query name parameter. + * @param values A collection of values for the given query name, which may be + * null. + * @return A list of {@link Pair} objects representing the input parameters, + * which is encoded for use in a URL. If the values collection is null, an + * empty list is returned. + */ + public static List parameterToPairs( + String collectionFormat, String name, Collection values) { + if (name == null || name.isEmpty() || values == null || values.isEmpty()) { + return Collections.emptyList(); + } + + // get the collection format (default: csv) + String format = collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat; + + // create the params based on the collection format + if ("multi".equals(format)) { + return values.stream() + .map(value -> new Pair(urlEncode(name), urlEncode(valueToString(value)))) + .collect(Collectors.toList()); + } + + String delimiter; + switch(format) { + case "csv": + delimiter = urlEncode(","); + break; + case "ssv": + delimiter = urlEncode(" "); + break; + case "tsv": + delimiter = urlEncode("\t"); + break; + case "pipes": + delimiter = urlEncode("|"); + break; + default: + throw new IllegalArgumentException("Illegal collection format: " + collectionFormat); + } + + StringJoiner joiner = new StringJoiner(delimiter); + for (Object value : values) { + joiner.add(urlEncode(valueToString(value))); + } + + return Collections.singletonList(new Pair(urlEncode(name), joiner.toString())); + } + + private ApiClient(Builder builder) { + webClient = builder.webClientBuilder().build(); + } + + /** + * Get the {@link WebClient} prepared by the builder of this {@code ApiClient}. + * + * @return the WebClient + */ + public WebClient webClient() { + return webClient; + } + + private static String valueToString(Object value) { + if (value == null) { + return ""; + } + {{#java8}} + if (value instanceof OffsetDateTime) { + return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + {{/java8}} + return value.toString(); + } + + /** + * Builder for creating a new {@code ApiClient} instance. + * + *

        + * The builder accepts a {@link WebClient.Builder} via the {@code webClientBuilder} method but will provide a default one + * using available configuration (the {@code client} node) and the base URI set in the OpenAPI document. + *

        + */ + public static class Builder { + + private WebClient.Builder webClientBuilder; + private Config clientConfig; + {{#jsonb}} + private JsonbConfig jsonbConfig; + {{/jsonb}} + {{#jackson}} + private ObjectMapper objectMapper; + {{/jackson}} + + public ApiClient build() { + return new ApiClient(this); + } + + /** + * Sets the {@code WebClient.Builder} which the {@code ApiClient.Builder} uses. Any previous setting is discarded. + * + * @param webClientBuilder the {@code WebClient.Builder} to be used going forward + * @return the updated builder + */ + public Builder webClientBuilder(WebClient.Builder webClientBuilder) { + this.webClientBuilder = webClientBuilder; + return this; + } + + /** + * Sets the client {@code Config} which the {@code ApiClient.Builder} uses in preparing a default {@code WebClient.Builder}. + * The builder ignores this setting if you provide your own {@code WebClient.Builder} by invoking the + * {@code webClientBuilder} method. + * + * @param clientConfig the {@code Config} node containing client settings + * @return the updated builder + */ + public Builder clientConfig(Config clientConfig) { + this.clientConfig = clientConfig; + return this; + } + + /** + * @return the previously-stored web client builder or, if none, a default one using the provided or defaulted + * client configuration + */ + public WebClient.Builder webClientBuilder() { + if (webClientBuilder == null) { + webClientBuilder = defaultWebClientBuilder(); + } + return webClientBuilder; + } + + {{#jsonb}} + /** + * Stores the JSON-B configuration the builder uses in preparing the {@code WebClient}. + * + * @param jsonbConfig the JSON-B config to use in all API invocations via the built {@code ApiClient} + * @return the updated builder + */ + public Builder jsonbConfig(JsonbConfig jsonbConfig) { + this.jsonbConfig = jsonbConfig; + return this; + } + {{/jsonb}} + {{#jackson}} + /** + * Stores the Jackson {@code ObjectMapper} the builder uses in preparing the {@code WebClient}. + * + * @param objectMapper the Jackson object mapper to use in all API invocations via the built {@code ApiClient} + * @return the updated builder + */ + public Builder objectMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + return this; + } + {{/jackson}} + + private WebClient.Builder defaultWebClientBuilder() { + WebClient.Builder defaultWebClientBuilder = WebClient.builder() + .baseUri("{{basePath}}") + .config(clientConfig()); + {{#jsonb}} + defaultWebClientBuilder.addMediaSupport(jsonbConfig == null + ? JsonbSupport.create() + : JsonbSupport.create(jsonbConfig)); + {{/jsonb}} + {{#jackson}} + defaultWebClientBuilder.addMediaSupport(objectMapper == null + ? JacksonSupport.create() + : JacksonSupport.create(objectMapper)); + {{/jackson}} + return defaultWebClientBuilder; + } + + private Config clientConfig() { + if (clientConfig == null) { + clientConfig = Config.create().get("client"); + } + return clientConfig; + } + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ApiResponse.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ApiResponse.mustache new file mode 100644 index 0000000000..b651e0b4f2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ApiResponse.mustache @@ -0,0 +1,34 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import java.util.concurrent.ExecutionException; + +import io.helidon.common.GenericType; +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +{{#appName}} +/** + * Generic-typed response. + * + * Return type for generated API methods. + * + * @param type of the return value from the generated API method + */ +{{/appName}} +public interface ApiResponse { + + static ApiResponse create(GenericType responseType, Single webClientResponse) { + return new ApiResponseBase<>(responseType, webClientResponse); + } + + /** + * @returns reactive access to the {@link WebClientResponse} describing the response from the server + */ + Single webClientResponse(); + + /** + * @return reactive access to the value returned in the response from the server + */ + Single result() throws ExecutionException, InterruptedException; +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ApiResponseBase.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ApiResponseBase.mustache new file mode 100644 index 0000000000..31228f0dc3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ApiResponseBase.mustache @@ -0,0 +1,36 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import java.util.concurrent.ExecutionException; + +import io.helidon.common.GenericType; +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +{{#appName}} +/** + * Implementation of a generic-typed response. + * + * @param type of the return value from the generated API method + */ +{{/appName}} +class ApiResponseBase implements ApiResponse { + + private final Single webClientResponse; + private final GenericType responseType; + + protected ApiResponseBase(GenericType responseType, Single webClientResponse) { + this.webClientResponse = webClientResponse; + this.responseType = responseType; + } + + @Override + public Single webClientResponse() { + return webClientResponse; + } + + @Override + public Single result() throws ExecutionException, InterruptedException { + return webClientResponse.get().content().as(responseType); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/JavaTimeFormatter.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/JavaTimeFormatter.mustache new file mode 100644 index 0000000000..f3fb34e559 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/JavaTimeFormatter.mustache @@ -0,0 +1,53 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +{{>generatedAnnotation}} +public class JavaTimeFormatter { + + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + /** + * Format the given {@code OffsetDateTime} object into string. + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/Pair.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/Pair.mustache new file mode 100644 index 0000000000..e20dacb774 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/Pair.mustache @@ -0,0 +1,45 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) { + return; + } + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) { + return; + } + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) { + return false; + } + + return true; + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/README.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/README.mustache new file mode 100644 index 0000000000..eab4ac23ff --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/README.mustache @@ -0,0 +1,26 @@ +# {{appName}} + +{{#appDescriptionWithNewLines}} +{{{.}}} + +{{/appDescriptionWithNewLines}} + +## Overview +This project was generated using the Helidon OpenAPI Generator. + +The generated classes use the programming model from the Helidon WebClient implementation, primarily the `WebClient` interface and its +`WebClient.Builder` class. Refer to the Helidon WebClient documentation for complete information about them. + +## Using the Generated Classes and Interfaces +The generated `ApiClient` class wraps a `WebClient` instance. Similarly, the `ApiClient.Builder` class wraps the `WebClient.Builder` class. + +The generated `xxxApi` interfaces and `xxxApiImpl` classes make it very simple for your code to send requests (with input parameters) to the remote service which the OpenAPI document describes and to process the response (with output values) from the remote service. + +To use the generated API, your code performs the following steps. + +1. Create an instance of the `ApiClient` using its `Builder`. +2. Create an instance of a `xxxApi` it wants to access, typically by invoking `xxxApiImpl.create(ApiClient)` and passing the `ApiClient` instance just created. +3. Invoke any of the `public` methods on the `xxxApi` instance, passing the input parameters and saving the returned `Single` object. +4. Invoke methods on the returned `Single` to process the response and any output from it. + +Browse the methods and JavaDoc on the generated classes for more information. diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/RFC3339DateFormat.mustache new file mode 100644 index 0000000000..311616a4ef --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/RFC3339DateFormat.mustache @@ -0,0 +1,46 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.text.DecimalFormat; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + this.numberFormat = new DecimalFormat(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return super.clone(); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ResponseType.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ResponseType.mustache new file mode 100644 index 0000000000..d730fccb6c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/ResponseType.mustache @@ -0,0 +1,32 @@ +{{>licenseInfo}} +package {{apiPackage}}; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import io.helidon.common.GenericType; + +class ResponseType { + + static GenericType create(Type rawType, Type... typeParams) { + return typeParams.length == 0 + ? GenericType.create(rawType) + : GenericType.create(new ParameterizedType() { + + @Override + public Type[] getActualTypeArguments() { + return typeParams; + } + + @Override + public Type getRawType() { + return rawType; + } + + @Override + public Type getOwnerType() { + return null; + } + }); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/StringUtil.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/StringUtil.mustache new file mode 100644 index 0000000000..e3d5d6e908 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/StringUtil.mustache @@ -0,0 +1,72 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.util.Collection; +import java.util.Iterator; + +{{>generatedAnnotation}} +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

        + * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

        + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/additionalEnumTypeAnnotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/additionalEnumTypeAnnotations.mustache new file mode 100644 index 0000000000..aa524798b4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/additionalEnumTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalEnumTypeAnnotations}}{{{.}}} +{{/additionalEnumTypeAnnotations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/additionalModelTypeAnnotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/additionalModelTypeAnnotations.mustache new file mode 100644 index 0000000000..f4871c02cc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/additionalModelTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalModelTypeAnnotations}}{{{.}}} +{{/additionalModelTypeAnnotations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api.mustache new file mode 100644 index 0000000000..f0d7ee5618 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api.mustache @@ -0,0 +1,43 @@ +{{>licenseInfo}} +package {{package}}; + +import {{invokerPackage}}.ApiResponse; +{{#imports}}import {{import}}; +{{/imports}} + +{{#appName}} +/** + * {{{appName}}} + * + {{#appDescription}} + *

        {{{.}}} + {{/appDescription}} + */ +{{/appName}} +public interface {{classname}} { + +{{#operations}} +{{#operation}} + {{#summary}} + /** + * {{summary}} + {{#notes}} + * {{.}} + {{/notes}} + {{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/isContainer}}{{/required}} + {{/allParams}} + * @return {@code {{>operationResponseSig}}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{/summary}} + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + {{>operationResponseSig}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + +{{/operation}} +{{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/apiOperation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/apiOperation.mustache new file mode 100644 index 0000000000..97adb0ea28 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/apiOperation.mustache @@ -0,0 +1,28 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import io.swagger.v3.oas.models.Operation; + +public class ApiOperation { + private final String path; + private final String method; + private final Operation operation; + + public ApiOperation(String path, String method, Operation operation) { + this.path = path; + this.method = method; + this.operation = operation; + } + + public Operation getOperation() { + return operation; + } + + public String getPath() { + return path; + } + + public String getMethod() { + return method; + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api_doc.mustache new file mode 100644 index 0000000000..3d3203957e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api_doc.mustache @@ -0,0 +1,108 @@ +# {{classname}}{{#description}} + +{{.}}{{/description}} + +All URIs are relative to *{{basePath}}* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +{{#operations}}{{#operation}}| [**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{commonPath}}{{path}} | {{summary}} | +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{operationId}} + +> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + +{{summary}}{{#notes}} + +{{.}}{{/notes}} + +### Example + +```java +// Import classes: +import {{{invokerPackage}}}.ApiClient; +import {{{invokerPackage}}}.ApiException; +import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}} +import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}} +import {{{invokerPackage}}}.models.*; +import {{{package}}}.{{{classname}}}; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("{{{basePath}}}"); + {{#hasAuthMethods}} + {{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setUsername("YOUR USERNAME"); + {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{{classname}}} apiInstance = new {{{classname}}}(defaultClient); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------|{{/-last}}{{/allParams}} +{{#allParams}}| **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{^isContainer}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}}{{/isContainer}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} | +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
        {{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api_impl.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api_impl.mustache new file mode 100644 index 0000000000..4da8503056 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api_impl.mustache @@ -0,0 +1,182 @@ +{{>licenseInfo}} +package {{package}}; + +import java.util.Objects; +import {{invokerPackage}}.ApiResponse; + +{{#jsonb}} +import {{rootJavaEEPackage}}.json.bind.JsonbBuilder; +{{/jsonb}} +{{#jackson}} +import com.fasterxml.jackson.databind.ObjectMapper; +{{/jackson}} + +import io.helidon.common.GenericType; +import io.helidon.common.http.MediaType; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.media.common.MediaSupport; +{{#jsonb}}import io.helidon.media.jsonb.JsonbSupport;{{/jsonb}} +{{#jackson}}import io.helidon.media.jackson.JacksonSupport;{{/jackson}} +import io.helidon.webclient.WebClientRequestBuilder; +import io.helidon.webclient.WebClientResponse; + +import {{invokerPackage}}.ApiClient; + +{{#x-helidon-implImports}}import {{import}}; +{{/x-helidon-implImports}} + +{{#appName}} +/** + * {{{appName}}} + * + {{#appDescription}} + *

        {{{.}}} + {{/appDescription}} + */ +{{/appName}} +public class {{classname}}Impl implements {{classname}} { + + private final ApiClient apiClient; + +{{#operations}} + {{#operation}} + protected static final GenericType<{{>operationResponseTypeDecl}}> RESPONSE_TYPE_{{operationId}} = ResponseType.create({{#isArray}}List.class, {{/isArray}}{{#isMap}}Map.class, String.class, {{/isMap}}{{#returnBaseType}}{{returnBaseType}}{{/returnBaseType}}{{^returnBaseType}}Void{{/returnBaseType}}.class); + {{/operation}} +{{/operations}} + + /** + * Creates a new instance of {{classname}}Impl initialized with the specified {@link ApiClient}. + * + */ + public static {{classname}}Impl create(ApiClient apiClient) { + return new {{classname}}Impl(apiClient); + } + + protected {{classname}}Impl(ApiClient apiClient) { + this.apiClient = apiClient; + } + +{{#operations}} +{{#operation}} + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + @Override + public {{>operationResponseSig}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) { + {{#requiredParams}} + Objects.requireNonNull({{paramName}}, "Required parameter '{{paramName}}' not specified"); + {{/requiredParams}} + WebClientRequestBuilder webClientRequestBuilder = {{operationId}}RequestBuilder({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + return {{operationId}}Submit(webClientRequestBuilder{{#allParams}}, {{paramName}}{{/allParams}}); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the {{operationId}} operation. + * Optional customization point for subclasses. + * + {{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/isContainer}}{{/required}} + {{/allParams}} + * @return WebClientRequestBuilder for {{operationId}} + */ + protected WebClientRequestBuilder {{operationId}}RequestBuilder({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("{{httpMethod}}"); + + {{#hasQueryParams}} + {{javaUtilPrefix}}List queryParams = new {{javaUtilPrefix}}ArrayList<>(); + {{#queryParams}} + {{#collectionFormat}} + queryParams.addAll(ApiClient.parameterToPairs("{{{collectionFormat}}}", "{{baseName}}", {{paramName}})); + {{/collectionFormat}} + {{^collectionFormat}} + {{#isDeepObject}} + if ({{paramName}} != null) { + {{#items.vars}} + queryParams.addAll(ApiClient.parameterToPairs({{#isArray}}"csv", {{/isArray}}"{{baseName}}", {{paramName}}.{{getter}}())); + {{/items.vars}} + } + {{/isDeepObject}} + {{^isDeepObject}} + {{#isExplode}} + {{#hasVars}} + {{#vars}} + queryParams.addAll(ApiClent.parameterToPairs("{{baseName}}", {{paramName}}.{{getter}}())); + {{/vars}} + {{/hasVars}} + {{^hasVars}} + queryParams.addAll(ApiClient.parameterToPairs("{{baseName}}", {{paramName}})); + {{/hasVars}} + {{/isExplode}} + {{^isExplode}} + queryParams.addAll(ApiClient.parameterToPairs("{{baseName}}", {{paramName}})); + {{/isExplode}} + {{/isDeepObject}} + {{/collectionFormat}} + {{/queryParams}} + queryParams.forEach(p -> webClientRequestBuilder.queryParam(p.getName(), p.getValue())); + + {{/hasQueryParams}} + {{#hasHeaderParams}} + WebClientRequestHeaders headers = webClientRequestBuilder.headers(); + {{#headerParams}} + if ({{paramName}} != null) { + headers.put("{{baseName}}", {{paramName}}{{^isString}}.toString(){{/isString}}); + } + {{/headerParams}} + + {{/hasHeaderParams}} + {{#hasCookieParams}} + String cookies = new StringJoiner("; ") + {{#cookieParams}} + .add("{{{baseName}}}=" + {{{paramName}}}) + {{/cookieParams}} + .toString(); + webClientRequestBuilder.headers().add("Cookie", cookies); + + {{/hasCookieParams}} + {{#hasPathParams}} + String path = "{{{path}}}" + {{! Switch delimiters from double braces to <% and %> for baseName so we can use curly braces in the string as literals and not have mustache + interpret them, then switch back. }} + {{#pathParams}} + .replace({{=<% %>=}}"{<%baseName%>}"<%={{ }}=%>, ApiClient.urlEncode({{{paramName}}}{{^isString}}.toString(){{/isString}})){{/pathParams}}; + {{/hasPathParams}} + webClientRequestBuilder.path({{#hasPathParams}}path{{/hasPathParams}}{{^hasPathParams}}"{{{path}}}"{{/hasPathParams}}); + {{#bodyParam}} + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + {{/bodyParam}} + {{#hasFormParams}} + webClientRequestBuilder.contentType(MediaType.APPLICATION_FORM_URLENCODED); + {{/hasFormParams}} + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the {{operationId}} operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + {{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/isContainer}}{{/required}} + {{/allParams}} + * @return {@code {{>operationResponseSig}}} for the submitted request + */ + protected {{>operationResponseSig}} {{operationId}}Submit(WebClientRequestBuilder webClientRequestBuilder{{#allParams}}, {{{dataType}}} {{paramName}}{{/allParams}}) { + {{#hasFormParams}} + String formParams = new StringJoiner("&") + {{#formParams}} + .add("{{{baseName}}}=" + {{paramName}}) + {{/formParams}} + .toString(); + {{/hasFormParams}} + Single webClientResponse = webClientRequestBuilder.submit({{#bodyParam}}{{paramName}}{{/bodyParam}}{{#hasFormParams}}formParams{{/hasFormParams}}); + return ApiResponse.create(RESPONSE_TYPE_{{operationId}}, webClientResponse); + } + +{{/operation}} +{{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api_test.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api_test.mustache new file mode 100644 index 0000000000..de7bb1db80 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/api_test.mustache @@ -0,0 +1,72 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiResponse; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * {{#appName}} + * {{{.}}} Test + * + * {{/appName}} + * API tests for {{classname}} + */ +public class {{classname}}Test { + + private static ApiClient apiClient; + private static {{classname}} api; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() { + apiClient = ApiClient.builder().build(); + api = {{classname}}Impl.create(apiClient); + } + + {{#operations}} + {{#operation}} + /** + * {{summary}} + {{#notes}} + * {{.}} + {{/notes}} + */ + @Test + public void {{operationId}}Test() { + {{#allParams}} + // TODO - assign values to the input arguments. + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse<{{>operationResponseTypeDecl}}> response = api.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + {{/operation}} + {{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/bodyParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/bodyParams.mustache new file mode 100644 index 0000000000..c7d1abfe52 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/cookieParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/cookieParams.mustache new file mode 100644 index 0000000000..fea14348d7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/cookieParams.mustache @@ -0,0 +1 @@ +{{#isCookieParam}}@CookieParam("{{baseName}}"){{^isContainer}}{{#defaultValue}} @DefaultValue("{{{.}}}"){{/defaultValue}}{{/isContainer}} {{#useSwaggerAnnotations}}{{#description}} @ApiParam("{{.}}"){{/description}}{{/useSwaggerAnnotations}} {{{dataType}}} {{paramName}}{{/isCookieParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/enumClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/enumClass.mustache new file mode 100644 index 0000000000..d32efebf48 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/enumClass.mustache @@ -0,0 +1,46 @@ +{{#jsonb}} + @JsonbTypeSerializer({{datatypeWithEnum}}.Serializer.class) + @JsonbTypeDeserializer({{datatypeWithEnum}}.Deserializer.class) +{{/jsonb}} +{{>additionalEnumTypeAnnotations}}public enum {{datatypeWithEnum}} { + + {{#allowableValues}} + {{#enumVars}}{{name}}({{dataType}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{/allowableValues}} + + {{dataType}} value; + + {{datatypeWithEnum}} ({{dataType}} v) { + value = v; + } + + public {{dataType}} value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + {{#jsonb}} + public static final class Deserializer implements JsonbDeserializer<{{datatypeWithEnum}}> { + @Override + public {{datatypeWithEnum}} deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(parser.getString())) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");{{/useNullForUnknownEnumValue}} + } + } + + public static final class Serializer implements JsonbSerializer<{{datatypeWithEnum}}> { + @Override + public void serialize({{datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.value); + } + } + {{/jsonb}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/enumOuterClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/enumOuterClass.mustache new file mode 100644 index 0000000000..39417c635f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/enumOuterClass.mustache @@ -0,0 +1,39 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +{{/jackson}} + +/** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ +{{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override +{{#jackson}} + @JsonValue +{{/jackson}} + public String toString() { + return String.valueOf(value); + } + +{{#jackson}} + @JsonCreator +{{/jackson}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + text + "'");{{/useNullForUnknownEnumValue}} + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/enum_outer_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/enum_outer_doc.mustache new file mode 100644 index 0000000000..20c512aaea --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/enum_outer_doc.mustache @@ -0,0 +1,7 @@ +# {{classname}} + +## Enum + +{{#allowableValues}}{{#enumVars}} +* `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/formParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/formParams.mustache new file mode 100644 index 0000000000..fa85e0c894 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}@FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/generatedAnnotation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/generatedAnnotation.mustache new file mode 100644 index 0000000000..356a48872a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/generatedAnnotation.mustache @@ -0,0 +1 @@ +@{{rootJavaEEPackage}}.annotation.Generated(value = "{{generatorClass}}"{{^hideGenerationTimestamp}}, date = "{{generatedDate}}"{{/hideGenerationTimestamp}}) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/headerParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/headerParams.mustache new file mode 100644 index 0000000000..25d690c90e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/jackson_annotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/jackson_annotations.mustache new file mode 100644 index 0000000000..ccde126f54 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/jackson_annotations.mustache @@ -0,0 +1,19 @@ +{{! + If this is map and items are nullable, make sure that nulls are included. + To determine what JsonInclude.Include method to use, consider the following: + * If the field is required, always include it, even if it is null. + * Else use custom behaviour, IOW use whatever is defined on the object mapper + }} + @JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}) + @JsonInclude({{#isMap}}{{#items.isNullable}}content = JsonInclude.Include.ALWAYS, {{/items.isNullable}}{{/isMap}}value = JsonInclude.Include.{{#required}}ALWAYS{{/required}}{{^required}}USE_DEFAULTS{{/required}}) + {{#withXml}} + {{^isContainer}} + @JacksonXmlProperty({{#isXmlAttribute}}isAttribute = true, {{/isXmlAttribute}}{{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}localName = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/isContainer}} + {{#isContainer}} + {{#isXmlWrapped}} + // items.xmlName={{items.xmlName}} + @JacksonXmlElementWrapper(useWrapping = {{isXmlWrapped}}, {{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}localName = "{{#items.xmlName}}{{items.xmlName}}{{/items.xmlName}}{{^items.xmlName}}{{items.baseName}}{{/items.xmlName}}") + {{/isXmlWrapped}} + {{/isContainer}} + {{/withXml}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/licenseInfo.mustache new file mode 100644 index 0000000000..be193d0c4f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} + * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/manifest.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/manifest.mustache new file mode 100644 index 0000000000..f44bd07d0a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/manifest.mustache @@ -0,0 +1,3 @@ + + + diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/maven.yml.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/maven.yml.mustache new file mode 100644 index 0000000000..f3c4733c30 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/maven.yml.mustache @@ -0,0 +1,31 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# +# This file is auto-generated by OpenAPI Generator (https://openapi-generator.tech) + +name: Java CI with Maven + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build: + name: Build {{{appName}}} + runs-on: ubuntu-latest + strategy: + matrix: + java: [ '8' ] + steps: + - uses: actions/checkout@v2 + - name: Set up JDK + uses: actions/setup-java@v2 + with: + {{=< >=}} + java-version: ${{ matrix.java }} + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --no-transfer-progress --file pom.xml diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/model.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/model.mustache new file mode 100644 index 0000000000..ad4e98b8a4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/model.mustache @@ -0,0 +1,19 @@ +{{>licenseInfo}} +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} + +{{#models}} +{{#model}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} +{{^isEnum}} +{{>pojo}} +{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/modelInnerEnum.mustache new file mode 100644 index 0000000000..a9c99783fd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/modelInnerEnum.mustache @@ -0,0 +1,95 @@ + /** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ +{{#gson}} + @JsonAdapter({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.Adapter.class) +{{/gson}} +{{#jsonb}} + @JsonbTypeSerializer({{datatypeWithEnum}}.Serializer.class) + @JsonbTypeDeserializer({{datatypeWithEnum}}.Deserializer.class) +{{/jsonb}} +{{#withXml}} + @XmlType(name="{{datatypeWithEnum}}") + @XmlEnum({{dataType}}.class) +{{/withXml}} + {{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { + {{#allowableValues}} + {{#enumVars}} + {{#enumDescription}} + /** + * {{.}} + */ + {{/enumDescription}} + {{#withXml}} + @XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{/withXml}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + +{{#jackson}} + @JsonValue +{{/jackson}} + public {{{dataType}}} getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +{{#jackson}} + @JsonCreator +{{/jackson}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue({{{dataType}}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.equals(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/isNullable}} + } +{{#gson}} + + public static class Adapter extends TypeAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}> { + @Override + public void write(final JsonWriter jsonWriter, final {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isFloat}}(float){{/isFloat}} jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{^isNumber}}{{^isInteger}}{{#isFloat}}nextDouble{{/isFloat}}{{^isFloat}}next{{{dataType}}}{{/isFloat}}(){{/isInteger}}{{/isNumber}}; + return {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } + } +{{/gson}} +{{#jsonb}} + public static final class Deserializer implements JsonbDeserializer<{{datatypeWithEnum}}> { + @Override + public {{datatypeWithEnum}} deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(parser.getString())) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");{{/useNullForUnknownEnumValue}} + } + } + + public static final class Serializer implements JsonbSerializer<{{datatypeWithEnum}}> { + @Override + public void serialize({{datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.value); + } + } +{{/jsonb}} + } diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/model_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/model_doc.mustache new file mode 100644 index 0000000000..9a7fe146a4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/model_doc.mustache @@ -0,0 +1,4 @@ +{{#models}}{{#model}} + +{{#isEnum}}{{>enum_outer_doc}}{{/isEnum}}{{^isEnum}}{{>pojo_doc}}{{/isEnum}} +{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/model_test.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/model_test.mustache new file mode 100644 index 0000000000..92c1e7ee2e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/model_test.mustache @@ -0,0 +1,49 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import org.junit.jupiter.api.Test; + +{{#fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * Model tests for {{classname}} + */ +public class {{classname}}Test { + {{#models}} + {{#model}} + {{^vendorExtensions.x-is-one-of-interface}} + {{^isEnum}} + private final {{classname}} model = new {{classname}}(); + + {{/isEnum}} + /** + * Model tests for {{classname}} + */ + @Test + public void test{{classname}}() { + // TODO: test {{classname}} + } + + {{#allVars}} + /** + * Test the property '{{name}}' + */ + @Test + public void {{name}}Test() { + // TODO: test {{name}} + } + + {{/allVars}} + {{/vendorExtensions.x-is-one-of-interface}} + {{/model}} + {{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/oneof_interface.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/oneof_interface.mustache new file mode 100644 index 0000000000..02deb483d5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/oneof_interface.mustache @@ -0,0 +1,6 @@ +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>typeInfoAnnotation}}{{>xmlAnnotation}} +public interface {{classname}} {{#vendorExtensions.x-implements}}{{#-first}}extends {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { + {{#discriminator}} + public {{propertyType}} {{propertyGetter}}(); + {{/discriminator}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/openapi.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/openapi.mustache new file mode 100644 index 0000000000..34fbb53f33 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/operationResponseSig.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/operationResponseSig.mustache new file mode 100644 index 0000000000..499dc7ede7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/operationResponseSig.mustache @@ -0,0 +1 @@ +ApiResponse<{{>operationResponseTypeDecl}}> \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/operationResponseTypeDecl.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/operationResponseTypeDecl.mustache new file mode 100644 index 0000000000..47f7200702 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/operationResponseTypeDecl.mustache @@ -0,0 +1 @@ +{{#returnType}}{{#isArray}}List<{{/isArray}}{{#isMap}}Map{{/isArray}}{{#isMap}}>{{/isMap}}{{/returnType}}{{^returnType}}Void{{/returnType}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pathParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pathParams.mustache new file mode 100644 index 0000000000..ba153467a6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo.mustache new file mode 100644 index 0000000000..84115fa7d0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo.mustache @@ -0,0 +1,155 @@ + +{{#jsonb}} +import java.lang.reflect.Type; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeDeserializer; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.DeserializationContext; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbDeserializer; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.SerializationContext; +import {{rootJavaEEPackage}}.json.stream.JsonGenerator; +import {{rootJavaEEPackage}}.json.stream.JsonParser; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbProperty; +{{#vendorExtensions.x-has-readonly-properties}} +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbCreator; +{{/vendorExtensions.x-has-readonly-properties}} +{{/jsonb}} + +{{#description}} +/** + * {{{.}}} + **/ +{{/description}} +{{>additionalModelTypeAnnotations}} +{{#vendorExtensions.x-class-extra-annotation}} +{{{vendorExtensions.x-class-extra-annotation}}} +{{/vendorExtensions.x-class-extra-annotation}} +public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensions.x-implements}}{{#-first}} implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { + {{#vars}}{{#isEnum}}{{^isContainer}} +{{>enumClass}}{{/isContainer}}{{#isContainer}}{{#mostInnerItems}} +{{>enumClass}}{{/mostInnerItems}}{{/isContainer}}{{/isEnum}} +{{#description}} + /** + * {{{.}}} + **/ +{{/description}} +{{#vendorExtensions.x-field-extra-annotation}} +{{{vendorExtensions.x-field-extra-annotation}}} +{{/vendorExtensions.x-field-extra-annotation}} +{{#isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#required}} = {{{defaultValue}}}{{/required}}{{^required}} = null{{/required}}; +{{/isContainer}} +{{^isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; +{{/isContainer}} + {{/vars}} +{{#vendorExtensions.x-has-readonly-properties}}{{#jsonb}} + public {{classname}}() { + } + + @JsonbCreator + public {{classname}}( + {{#readOnlyVars}} + @JsonbProperty("{{baseName}}") {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} + {{/readOnlyVars}} + ) { + {{#readOnlyVars}} + this.{{name}} = {{name}}; + {{/readOnlyVars}} + } + {{/jsonb}}{{/vendorExtensions.x-has-readonly-properties}} + {{#vars}} + /** + {{#description}} + * {{.}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + * @return {{name}} + {{#deprecated}} + * @deprecated + {{/deprecated}} + **/ +{{#deprecated}} + @Deprecated +{{/deprecated}} +{{#vendorExtensions.x-extra-annotation}} + {{{vendorExtensions.x-extra-annotation}}} +{{/vendorExtensions.x-extra-annotation}} + {{#withXml}}{{#isEnum}}{{^isArray}}{{^isMap}}public {{dataType}} {{getter}}() { + if ({{name}} == null) { + return null; + } + return {{name}}.value(); + }{{/isMap}}{{/isArray}}{{/isEnum}}{{/withXml}}{{^withXml}}{{#isEnum}}{{^isArray}}{{^isMap}}public {{datatypeWithEnum}} {{getter}}() { + return {{name}}; + }{{/isMap}}{{/isArray}}{{/isEnum}}{{/withXml}}{{#isEnum}}{{#isArray}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isArray}}{{/isEnum}}{{#isEnum}}{{#isMap}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isMap}}{{/isEnum}}{{^isEnum}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isEnum}} + + {{^isReadOnly}} + /** + * Set {{name}} + **/ + {{#vendorExtensions.x-setter-extra-annotation}} {{{vendorExtensions.x-setter-extra-annotation}}} + {{/vendorExtensions.x-setter-extra-annotation}}public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + {{#isArray}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.add({{name}}Item); + return this; + } + {{/isArray}} + {{#isMap}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMap}} + {{/isReadOnly}} + + {{/vars}} + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo_doc.mustache new file mode 100644 index 0000000000..bae0bc48cd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo_doc.mustache @@ -0,0 +1,37 @@ +# {{#vendorExtensions.x-is-one-of-interface}}Interface {{/vendorExtensions.x-is-one-of-interface}}{{classname}} + +{{#description}}{{&description}} +{{/description}} +{{^vendorExtensions.x-is-one-of-interface}} + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +{{#vars}}|**{{name}}** | {{#isEnum}}[**{{datatypeWithEnum}}**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isContainer}}{{#isArray}}{{#items}}{{#isModel}}[{{/isModel}}{{/items}}**{{baseType}}{{#items}}<{{dataType}}>**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/items}}{{/isArray}}{{#isMap}}{{#items}}{{#isModel}}[{{/isModel}}**Map<String, {{dataType}}>**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/items}}{{/isMap}}{{/isContainer}}{{^isContainer}}{{#isModel}}[{{/isModel}}**{{dataType}}**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/isContainer}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#isReadOnly}} [readonly]{{/isReadOnly}} | +{{/vars}} +{{#vars}}{{#isEnum}} + + +## Enum: {{datatypeWithEnum}} + +| Name | Value | +|---- | -----|{{#allowableValues}}{{#enumVars}} +| {{name}} | {{value}} |{{/enumVars}}{{/allowableValues}} +{{/isEnum}}{{/vars}} +{{#vendorExtensions.x-implements.0}} + +## Implemented Interfaces + +{{#vendorExtensions.x-implements}} +* {{{.}}} +{{/vendorExtensions.x-implements}} +{{/vendorExtensions.x-implements.0}} +{{/vendorExtensions.x-is-one-of-interface}} +{{#vendorExtensions.x-is-one-of-interface}} +## Implementing Classes + +{{#oneOf}} +* {{{.}}} +{{/oneOf}} +{{/vendorExtensions.x-is-one-of-interface}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pom.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pom.mustache new file mode 100644 index 0000000000..489af6b157 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pom.mustache @@ -0,0 +1,83 @@ + + 4.0.0 + {{groupId}} + + io.helidon.applications + helidon-se + {{helidonVersion}} + + + {{artifactId}} + {{artifactId}} + {{#appDescription}} + {{.}} + {{/appDescription}} + {{artifactVersion}} + jar + + + + io.helidon.webclient + helidon-webclient + + + io.helidon.config + helidon-config + + + {{x-helidon-rootJavaEEDepPrefix}}.json + {{x-helidon-rootJavaEEDepPrefix}}.json-api + +{{#jackson}} + + io.helidon.media + helidon-media-jackson + + + org.glassfish.jersey.media + jersey-media-json-jackson + + + org.openapitools + jackson-databind-nullable + 0.2.2 + +{{/jackson}} +{{#jsonb}} + + org.glassfish.jersey.media + jersey-media-json-binding + + + {{x-helidon-rootJavaEEDepPrefix}}.json.bind + {{x-helidon-rootJavaEEDepPrefix}}.json.bind-api + +{{/jsonb}} + + org.junit.jupiter + junit-jupiter-api + test + + + org.hamcrest + hamcrest-all + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libs + + + + + + diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/queryParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/queryParams.mustache new file mode 100644 index 0000000000..4b1a980896 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@QueryParam("{{baseName}}") {{^isContainer}}{{#defaultValue}}@DefaultValue("{{{.}}}") {{/defaultValue}}{{/isContainer}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/returnTypes.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/returnTypes.mustache new file mode 100644 index 0000000000..32f96a9047 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/returnTypes.mustache @@ -0,0 +1,4 @@ +{{#useGenericResponse}}Response{{/useGenericResponse}}{{! non-generic response: +}}{{^useGenericResponse}}{{! +}}{{{returnType}}}{{! +}}{{/useGenericResponse}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/typeInfoAnnotation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/typeInfoAnnotation.mustache new file mode 100644 index 0000000000..c833321ebf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/typeInfoAnnotation.mustache @@ -0,0 +1,17 @@ +{{#jackson}} + +@JsonIgnoreProperties( + value = "{{{discriminator.propertyBaseName}}}", // ignore manually set {{{discriminator.propertyBaseName}}}, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the {{{discriminator.propertyBaseName}}} to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{{discriminator.propertyBaseName}}}", visible = true) +{{#discriminator.mappedModels}} +{{#-first}} +@JsonSubTypes({ +{{/-first}} + @JsonSubTypes.Type(value = {{modelName}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{mappingName}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), +{{#-last}} +}) +{{/-last}} +{{/discriminator.mappedModels}} +{{/jackson}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/common/README.mustache b/modules/openapi-generator/src/main/resources/java-helidon/common/README.mustache new file mode 100644 index 0000000000..961c4207f4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/common/README.mustache @@ -0,0 +1,9 @@ +# {{appName}} + +{{#appDescriptionWithNewLines}} +{{{.}}} + +{{/appDescriptionWithNewLines}} + +## Overview +This project was generated using the Helidon OpenAPI Generator. diff --git a/samples/openapi3/client/petstore/java/native/.gitignore b/modules/openapi-generator/src/main/resources/java-helidon/common/gitignore.mustache similarity index 100% rename from samples/openapi3/client/petstore/java/native/.gitignore rename to modules/openapi-generator/src/main/resources/java-helidon/common/gitignore.mustache diff --git a/modules/openapi-generator/src/main/resources/java-helidon/common/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/common/licenseInfo.mustache new file mode 100644 index 0000000000..be193d0c4f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/common/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} + * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ diff --git a/modules/openapi-generator/src/main/resources/java-helidon/common/model.mustache b/modules/openapi-generator/src/main/resources/java-helidon/common/model.mustache new file mode 100644 index 0000000000..00a3c3db13 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/common/model.mustache @@ -0,0 +1,23 @@ +{{>licenseInfo}} +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} +{{#useBeanValidation}} +import {{rootJavaEEPackage}}.validation.constraints.*; +import {{rootJavaEEPackage}}.validation.Valid; +{{/useBeanValidation}} + +{{#models}} +{{#model}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} +{{^isEnum}} +{{>pojo}} +{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/common/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/common/pojo.mustache new file mode 100644 index 0000000000..944ae48295 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/common/pojo.mustache @@ -0,0 +1,121 @@ +{{#jsonb}} +import java.lang.reflect.Type; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeDeserializer; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.DeserializationContext; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbDeserializer; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.SerializationContext; +import {{rootJavaEEPackage}}.json.stream.JsonGenerator; +import {{rootJavaEEPackage}}.json.stream.JsonParser; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbProperty; +{{#vendorExtensions.x-has-readonly-properties}} +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbCreator; +{{/vendorExtensions.x-has-readonly-properties}} +{{/jsonb}} + +{{#description}} +/** + * {{{.}}} + */{{/description}} +public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { + +{{#vars}} + {{#isEnum}} + + {{^isContainer}} +{{>enumClass}} + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} +{{>enumClass}} + {{/mostInnerItems}} + {{/isContainer}} + + {{/isEnum}} + private {{{datatypeWithEnum}}} {{{name}}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; +{{/vars}} + + /** + * Default constructor. + */ + public {{classname}}() { + // JSON-B / Jackson + } + + /** + * Create {{classname}}. + * +{{#vars}} + * @param {{name}} {{description}}{{^description}}{{name}}{{/description}} +{{/vars}} + */ + public {{classname}}( +{{#vars}} + {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} +{{/vars}} + ) { +{{#vars}} + this.{{name}} = {{name}}; +{{/vars}} + } + +{{#vars}}{{#vendorExtensions.x-has-readonly-properties}}{{#jsonb}} + @JsonbCreator + public {{classname}}( + {{#readOnlyVars}} + @JsonbProperty("{{baseName}}") {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} + {{/readOnlyVars}} + ) { + {{#readOnlyVars}} + this.{{name}} = {{name}}; + {{/readOnlyVars}} + }{{/jsonb}}{{/vendorExtensions.x-has-readonly-properties}} + + /** + {{#description}} + * {{{.}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + * @return {{name}} + */ + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + }{{/vars}} + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/README.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/README.mustache new file mode 100644 index 0000000000..81d0db100a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/README.mustache @@ -0,0 +1,34 @@ +# Helidon Server with OpenAPI + +## Build and run + +With JDK11+ +```bash +mvn package +java -jar target/{{{artifactId}}}.jar +``` + +## Exercise the application + +``` +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}curl -X {{httpMethod}} {{{basePath}}}{{{path}}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +``` + +## Try health and metrics + +``` +curl -s -X GET {{{basePath}}}/health +{"outcome":"UP",... +. . . + +# Prometheus Format +curl -s -X GET {{{basePath}}}/metrics +# TYPE base:gc_g1_young_generation_count gauge +. . . + +# JSON Format +curl -H 'Accept: application/json' -X GET {{{basePath}}}/metrics +{"base":... +. . . +``` \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/RFC3339DateFormat.mustache new file mode 100644 index 0000000000..0f7f49e861 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/RFC3339DateFormat.mustache @@ -0,0 +1,39 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/JavaTimeFormatter.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/JavaTimeFormatter.mustache new file mode 100644 index 0000000000..f3fb34e559 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/JavaTimeFormatter.mustache @@ -0,0 +1,53 @@ +{{>licenseInfo}} +package {{invokerPackage}}; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +{{>generatedAnnotation}} +public class JavaTimeFormatter { + + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + /** + * Format the given {@code OffsetDateTime} object into string. + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/RestApplication.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/RestApplication.mustache new file mode 100644 index 0000000000..341f5e4751 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/RestApplication.mustache @@ -0,0 +1,11 @@ +package {{invokerPackage}}; + +import {{rootJavaEEPackage}}.enterprise.context.ApplicationScoped; +import {{rootJavaEEPackage}}.ws.rs.ApplicationPath; +import {{rootJavaEEPackage}}.ws.rs.core.Application; + +@ApplicationScoped +@ApplicationPath("{{{contextPath}}}") +public class RestApplication extends Application { + +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/StringUtil.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/StringUtil.mustache new file mode 100644 index 0000000000..e3d5d6e908 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/StringUtil.mustache @@ -0,0 +1,72 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.util.Collection; +import java.util.Iterator; + +{{>generatedAnnotation}} +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

        + * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

        + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/additionalEnumTypeAnnotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/additionalEnumTypeAnnotations.mustache new file mode 100644 index 0000000000..aa524798b4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/additionalEnumTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalEnumTypeAnnotations}}{{{.}}} +{{/additionalEnumTypeAnnotations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/additionalModelTypeAnnotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/additionalModelTypeAnnotations.mustache new file mode 100644 index 0000000000..f4871c02cc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/additionalModelTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalModelTypeAnnotations}}{{{.}}} +{{/additionalModelTypeAnnotations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api.mustache new file mode 100644 index 0000000000..495b0cc759 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api.mustache @@ -0,0 +1,33 @@ +{{>licenseInfo}} +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import {{rootJavaEEPackage}}.ws.rs.*; +{{#returnResponse}} +import {{rootJavaEEPackage}}.ws.rs.core.Response; +{{/returnResponse}} +{{#supportAsync}} +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; +{{/supportAsync}} + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +{{#useBeanValidation}}import {{rootJavaEEPackage}}.validation.constraints.*; +import {{rootJavaEEPackage}}.validation.Valid;{{/useBeanValidation}} + +@Path("{{commonPath}}"){{#hasConsumes}} +@Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} +@Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}} +{{>generatedAnnotation}} +public {{^useAbstractClass}}interface{{/useAbstractClass}}{{#useAbstractClass}}abstract class{{/useAbstractClass}} {{classname}} { +{{#operations}} +{{#operation}} + +{{>apiAbstract}} +{{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/apiAbstract.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/apiAbstract.mustache new file mode 100644 index 0000000000..a2d82121b0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/apiAbstract.mustache @@ -0,0 +1,5 @@ + @{{httpMethod}}{{#subresourceOperation}} + @Path("{{{path}}}"){{/subresourceOperation}}{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}} + {{#useAbstractClass}}abstract {{/useAbstractClass}}{{#supportAsync}}{{>returnAsyncTypeInterface}}{{/supportAsync}}{{^supportAsync}}{{>returnTypes}}{{/supportAsync}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>cookieParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{/allParams}}); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/apiImpl.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/apiImpl.mustache new file mode 100644 index 0000000000..9c9db82b24 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/apiImpl.mustache @@ -0,0 +1,34 @@ +{{>licenseInfo}} +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import {{rootJavaEEPackage}}.ws.rs.*; +{{#returnResponse}} +import {{rootJavaEEPackage}}.ws.rs.core.Response; +{{/returnResponse}} + +{{#supportAsync}} +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; +{{/supportAsync}} + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +{{#useBeanValidation}}import {{rootJavaEEPackage}}.validation.constraints.*; +import {{rootJavaEEPackage}}.validation.Valid;{{/useBeanValidation}} + +@Path("{{commonPath}}"){{#hasConsumes}} +@Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} +@Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}} +{{>generatedAnnotation}} +public class {{classname}}Impl {{^useAbstractClass}}implements{{/useAbstractClass}}{{#useAbstractClass}}extends{{/useAbstractClass}} {{classname}} { +{{#operations}} +{{#operation}} + +{{>apiMethod}} +{{/operation}} +} +{{/operations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/apiMethod.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/apiMethod.mustache new file mode 100644 index 0000000000..b1c07572f6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/apiMethod.mustache @@ -0,0 +1,22 @@ + @{{httpMethod}}{{#subresourceOperation}} + @Path("{{{path}}}"){{/subresourceOperation}}{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}} + public {{#supportAsync}}{{>returnAsyncTypeInterface}}{{/supportAsync}}{{^supportAsync}}{{>returnTypes}}{{/supportAsync}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>cookieParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}) { + {{#returnResponse}} + return {{#supportAsync}}CompletableFuture.supplyAsync(() -> {{/supportAsync}}Response.ok({{#vendorExtensions.x-helidon-hasReturnType}}/* Pass {{{returnType}}} entity payload */{{/vendorExtensions.x-helidon-hasReturnType}}).build(){{#supportAsync}}){{/supportAsync}}; // Replace with correct business logic. + {{/returnResponse}} + {{^returnResponse}} + {{#vendorExtensions.x-helidon-hasReturnType}} + {{{returnType}}} result = {{{vendorExtensions.x-helidon-exampleReturnTypeValue}}}; // Replace with correct business logic. + {{/vendorExtensions.x-helidon-hasReturnType}} + {{#supportAsync}} + return CompletableFuture.supplyAsync(() -> {{#vendorExtensions.x-helidon-hasReturnType}}result{{/vendorExtensions.x-helidon-hasReturnType}}{{^vendorExtensions.x-helidon-hasReturnType}}null{{/vendorExtensions.x-helidon-hasReturnType}}); + {{/supportAsync}} + {{^supportAsync}} + {{#vendorExtensions.x-helidon-hasReturnType}} + return result; + {{/vendorExtensions.x-helidon-hasReturnType}} + {{/supportAsync}} + {{/returnResponse}} + } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_doc.mustache new file mode 100644 index 0000000000..3d3203957e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_doc.mustache @@ -0,0 +1,108 @@ +# {{classname}}{{#description}} + +{{.}}{{/description}} + +All URIs are relative to *{{basePath}}* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +{{#operations}}{{#operation}}| [**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{commonPath}}{{path}} | {{summary}} | +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{operationId}} + +> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + +{{summary}}{{#notes}} + +{{.}}{{/notes}} + +### Example + +```java +// Import classes: +import {{{invokerPackage}}}.ApiClient; +import {{{invokerPackage}}}.ApiException; +import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}} +import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}} +import {{{invokerPackage}}}.models.*; +import {{{package}}}.{{{classname}}}; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("{{{basePath}}}"); + {{#hasAuthMethods}} + {{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setUsername("YOUR USERNAME"); + {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{{classname}}} apiInstance = new {{{classname}}}(defaultClient); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------|{{/-last}}{{/allParams}} +{{#allParams}}| **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{^isContainer}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}}{{/isContainer}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} | +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
        {{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_exception.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_exception.mustache new file mode 100644 index 0000000000..d9fb5ee91d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_exception.mustache @@ -0,0 +1,19 @@ +{{>licenseInfo}} +package {{apiPackage}}; + +import {{rootJavaEEPackage}}.ws.rs.core.Response; + +public class ApiException extends Exception { + private static final long serialVersionUID = 1L; + + private final Response response; + + public ApiException(Response response) { + super("Api response has status code " + response.getStatus()); + this.response = response; + } + + public Response getResponse() { + return this.response; + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_exception_mapper.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_exception_mapper.mustache new file mode 100644 index 0000000000..ac4db62e8b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_exception_mapper.mustache @@ -0,0 +1,22 @@ +{{>licenseInfo}} +package {{apiPackage}}; + +import {{rootJavaEEPackage}}.ws.rs.core.MultivaluedMap; +import {{rootJavaEEPackage}}.ws.rs.core.Response; +import {{rootJavaEEPackage}}.ws.rs.ext.Provider; + +import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper; + +@Provider +public class ApiExceptionMapper implements ResponseExceptionMapper { + + @Override + public boolean handles(int status, MultivaluedMap headers) { + return status >= 400; + } + + @Override + public ApiException toThrowable(Response response) { + return new ApiException(response); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_test.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_test.mustache new file mode 100644 index 0000000000..431834b779 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/api_test.mustache @@ -0,0 +1,59 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import {{rootJavaEEPackage}}.inject.Inject; +import {{rootJavaEEPackage}}.ws.rs.client.WebTarget; + +import org.junit.jupiter.api.Test; + +import io.helidon.microprofile.tests.junit5.HelidonTest; + +import java.net.URL; +import java.net.MalformedURLException; +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +{{/fullJavaUtil}} + +/** + {{#appName}} + * {{{.}}} Test + * + {{/appName}} + * API tests for {{classname}} + */ +@HelidonTest +public class {{classname}}Test { + + @Inject + private WebTarget target; + + {{#operations}}{{#operation}} + /** + {{#summary}} + * {{summary}} + * + {{#notes}} + * {{.}} + * + {{/notes}} + {{/summary}} + * @throws ApiException if the Api call fails + */ + @Test + public void {{operationId}}Test() throws Exception { + // TODO: test validations + {{#allParams}} + {{^isFile}}{{{dataType}}} {{paramName}} = null;{{/isFile}} + {{/allParams}} + //{{#returnType}}{{{.}}} response = {{/returnType}}target.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + //{{#returnType}}assertNotNull(response);{{/returnType}} + } + {{/operation}}{{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidatedType.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidatedType.mustache new file mode 100644 index 0000000000..8f2816b2c7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidatedType.mustache @@ -0,0 +1 @@ +{{#isArray}}{{baseType}}<{{#items}}{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}}{{>beanValidatedType}}{{/items}}>{{/isArray}}{{^isArray}}{{{datatypeWithEnum}}}{{/isArray}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidation.mustache new file mode 100644 index 0000000000..c8c6946fef --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidation.mustache @@ -0,0 +1,4 @@ +{{#required}} + @NotNull +{{/required}} +{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationCore.mustache new file mode 100644 index 0000000000..d6e2f13b45 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationCore.mustache @@ -0,0 +1,20 @@ +{{#pattern}} @Pattern(regexp="{{{.}}}"){{/pattern}}{{! +minLength && maxLength set +}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{! +minLength set, maxLength not +}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{! +minLength not set, maxLength set +}}{{^minLength}}{{#maxLength}} @Size(max={{.}}){{/maxLength}}{{/minLength}}{{! +@Size: minItems && maxItems set +}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{! +@Size: minItems set, maxItems not +}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{! +@Size: minItems not set && maxItems set +}}{{^minItems}}{{#maxItems}} @Size(max={{.}}){{/maxItems}}{{/minItems}}{{! +check for integer or long / all others=decimal type with @Decimal* +isInteger set +}}{{#isInteger}}{{#minimum}} @Min({{.}}){{/minimum}}{{#maximum}} @Max({{.}}){{/maximum}}{{/isInteger}}{{! +isLong set +}}{{#isLong}}{{#minimum}} @Min({{.}}L){{/minimum}}{{#maximum}} @Max({{.}}L){{/maximum}}{{/isLong}}{{! +Not Integer, not Long => we have a decimal value! +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationHeaderParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationHeaderParams.mustache new file mode 100644 index 0000000000..c4ff01d7e5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationHeaderParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationPathParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationPathParams.mustache new file mode 100644 index 0000000000..051bd53c0a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationQueryParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationQueryParams.mustache new file mode 100644 index 0000000000..c4ff01d7e5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beans.xml.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beans.xml.mustache new file mode 100644 index 0000000000..125ef995e5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/beans.xml.mustache @@ -0,0 +1,9 @@ + + + + diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/bodyParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/bodyParams.mustache new file mode 100644 index 0000000000..f938cb5b6b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{#useBeanValidation}}@Valid {{#required}}{{^isNullable}}@NotNull {{/isNullable}}{{/required}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/build.gradle.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/build.gradle.mustache new file mode 100644 index 0000000000..4de685654d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/build.gradle.mustache @@ -0,0 +1,79 @@ +plugins { + id 'java' + id 'application' +} + +group = '{{{groupId}}}' +version = '{{{artifactVersion}}}' + +{{#appDescription}} +description = """{{.}}""" +{{/appDescription}} + + +sourceCompatibility = 11 +targetCompatibility = 11 + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + +ext { + helidonVersion = '{{{helidonVersion}}}' + mainClass='io.helidon.microprofile.cdi.Main' +} + +test { + useJUnitPlatform() +} + +repositories { + mavenCentral() + mavenLocal() +} + +dependencies { + // import Helidon BOM + implementation enforcedPlatform("io.helidon:helidon-dependencies:${project.helidonVersion}") + implementation 'io.helidon.microprofile.bundles:helidon-microprofile-core' + implementation 'io.helidon.microprofile.cdi:helidon-microprofile-cdi' + implementation '{{rootJavaEEPackage}}.enterprise:{{rootJavaEEPackage}}.enterprise.cdi-api' + implementation '{{rootJavaEEPackage}}.ws.rs:{{rootJavaEEPackage}}.ws.rs-api' +{{#jackson}} + implementation 'org.glassfish.jersey.media:jersey-media-json-jackson' +{{/jackson}} +{{#jsonb}} + implementation 'org.glassfish.jersey.media:jersey-media-json-binding' + implementation '{{rootJavaEEPackage}}.json.bind:{{rootJavaEEPackage}}.json.bind-api' +{{/jsonb}} + testImplementation 'junit:junit' + testImplementation 'io.helidon.microprofile.tests:helidon-microprofile-tests-junit5' +} + +// define a custom task to copy all dependencies in the runtime classpath +// into build/libs/libs +// uses built-in Copy +task copyLibs(type: Copy) { + from configurations.runtimeClasspath + into 'build/libs/libs' +} + +// add it as a dependency of built-in task 'assemble' +copyLibs.dependsOn jar +assemble.dependsOn copyLibs + +// default jar configuration +// set the main classpath +// add each jar under build/libs/libs into the classpath +jar { + archiveFileName = "${project.name}.jar" + manifest { + attributes ('Main-Class': "${project.mainClass}", + 'Class-Path': configurations.runtimeClasspath.files.collect { "libs/$it.name" }.join(' ') + ) + } +} + +application { +mainClass = "${project.mainClass}" +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/cookieParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/cookieParams.mustache new file mode 100644 index 0000000000..3aa861dd0f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/cookieParams.mustache @@ -0,0 +1 @@ +{{#isCookieParam}}@CookieParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{^isContainer}}{{#defaultValue}} @DefaultValue("{{{.}}}"){{/defaultValue}}{{/isContainer}} {{{dataType}}} {{paramName}}{{/isCookieParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumClass.mustache new file mode 100644 index 0000000000..441eab3534 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumClass.mustache @@ -0,0 +1,48 @@ +{{>additionalEnumTypeAnnotations}}public enum {{datatypeWithEnum}} { + + {{#allowableValues}} + {{#enumVars}}{{name}}({{dataType}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{/allowableValues}} + + + private {{dataType}} value; + + {{datatypeWithEnum}} ({{dataType}} v) { + value = v; + } + + public {{dataType}} value() { + return value; + } + + @Override + {{#jackson}}@JsonValue{{/jackson}} + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into {{dataType}}, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static {{datatypeWithEnum}} fromString(String s) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected string value '" + s + "'");{{/isNullable}} + } + + {{#jackson}}@JsonCreator{{/jackson}} + public static {{datatypeWithEnum}} fromValue({{dataType}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.equals(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/isNullable}} + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumOuterClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumOuterClass.mustache new file mode 100644 index 0000000000..3d9a35ead9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumOuterClass.mustache @@ -0,0 +1,61 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +{{/jackson}} +{{#jsonb}} +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbCreator; +{{/jsonb}} + +/** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ +{{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + /** + * Convert a String into {{dataType}}, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromString(String s) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected string value '" + s + "'");{{/isNullable}} + } + + @Override + {{#jackson}}@JsonValue{{/jackson}} + public String toString() { + return String.valueOf(value); + } + + {{#jackson}}@JsonCreator{{/jackson}}{{#jsonb}}@JsonbCreator{{/jsonb}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue({{{dataType}}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.equals(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/isNullable}} + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/formParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/formParams.mustache new file mode 100644 index 0000000000..885966e644 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{^isFile}}@FormParam(value = "{{baseName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}} @FormParam(value = "{{baseName}}") InputStream {{paramName}}InputStream{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/generatedAnnotation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/generatedAnnotation.mustache new file mode 100644 index 0000000000..356a48872a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/generatedAnnotation.mustache @@ -0,0 +1 @@ +@{{rootJavaEEPackage}}.annotation.Generated(value = "{{generatorClass}}"{{^hideGenerationTimestamp}}, date = "{{generatedDate}}"{{/hideGenerationTimestamp}}) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/headerParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/headerParams.mustache new file mode 100644 index 0000000000..ef50692b02 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@HeaderParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationHeaderParams}}{{/useBeanValidation}} {{#defaultValue}} @DefaultValue("{{{.}}}"){{/defaultValue}} {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/logging.properties.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/logging.properties.mustache new file mode 100644 index 0000000000..3e909fb7d9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/logging.properties.mustache @@ -0,0 +1,25 @@ +# Example Logging Configuration File +# For more information see $JAVA_HOME/jre/lib/logging.properties + +## Send messages to the console +handlers=io.helidon.common.HelidonConsoleHandler +# +## HelidonConsoleHandler uses a SimpleFormatter subclass that replaces "!thread!" with the current thread +java.util.logging.SimpleFormatter.format=%1$tY.%1$tm.%1$td %1$tH:%1$tM:%1$tS %4$s %3$s !thread!: %5$s%6$s%n +# +## Global logging level. Can be overridden by specific loggers +.level=INFO + +# Quiet Weld +org.jboss.level=WARNING + +# +# Component specific log levels +#io.helidon.webserver.level=INFO +#io.helidon.config.level=INFO +#io.helidon.security.level=INFO +#io.helidon.microprofile.level=INFO +#io.helidon.common.level=INFO +#io.netty.level=INFO +#org.glassfish.jersey.level=INFO +#org.jboss.weld=INFO diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/microprofile-config.properties.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/microprofile-config.properties.mustache new file mode 100644 index 0000000000..38988f20e5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/microprofile-config.properties.mustache @@ -0,0 +1,11 @@ +# Microprofile server properties + +# Application properties. This is the default greeting +app.greeting=Hello + +# Microprofile server properties +server.port=8080 +server.host=0.0.0.0 + +# Enable the optional MicroProfile Metrics REST.request metrics +metrics.rest-request.enabled=true diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/model.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/model.mustache new file mode 100644 index 0000000000..00a3c3db13 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/model.mustache @@ -0,0 +1,23 @@ +{{>licenseInfo}} +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} +{{#useBeanValidation}} +import {{rootJavaEEPackage}}.validation.constraints.*; +import {{rootJavaEEPackage}}.validation.Valid; +{{/useBeanValidation}} + +{{#models}} +{{#model}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} +{{^isEnum}} +{{>pojo}} +{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/modelEnum.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/modelEnum.mustache new file mode 100644 index 0000000000..1eb5bb263c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/modelEnum.mustache @@ -0,0 +1,73 @@ + /** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ +{{#jsonb}} + @JsonbTypeSerializer({{datatypeWithEnum}}.Serializer.class) + @JsonbTypeDeserializer({{datatypeWithEnum}}.Deserializer.class) +{{/jsonb}} +{{#withXml}} + @XmlType(name="{{datatypeWithEnum}}") + @XmlEnum({{dataType}}.class) +{{/withXml}} + {{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { + {{#allowableValues}} + {{#enumVars}} + {{#enumDescription}} + /** + * {{.}} + */ + {{/enumDescription}} + {{#withXml}} + @XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{/withXml}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + {{#jackson}}@JsonValue{{/jackson}} + public {{{dataType}}} getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + {{#jackson}}@JsonCreator{{/jackson}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue({{{dataType}}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.equals(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/isNullable}} + } +{{#jsonb}} + public static final class Deserializer implements JsonbDeserializer<{{datatypeWithEnum}}> { + @Override + public {{datatypeWithEnum}} deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(parser.getString())) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");{{/useNullForUnknownEnumValue}} + } + } + + public static final class Serializer implements JsonbSerializer<{{datatypeWithEnum}}> { + @Override + public void serialize({{datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.value); + } + } +{{/jsonb}} + } diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/model_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/model_doc.mustache new file mode 100644 index 0000000000..9a7fe146a4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/model_doc.mustache @@ -0,0 +1,4 @@ +{{#models}}{{#model}} + +{{#isEnum}}{{>enum_outer_doc}}{{/isEnum}}{{^isEnum}}{{>pojo_doc}}{{/isEnum}} +{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/openapi.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/openapi.mustache new file mode 100644 index 0000000000..51ebafb018 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pathParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pathParams.mustache new file mode 100644 index 0000000000..9e8455d5ac --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@PathParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}} {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo.mustache new file mode 100644 index 0000000000..8cb61daf3d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo.mustache @@ -0,0 +1,161 @@ + +{{#jsonb}} +import java.lang.reflect.Type; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeDeserializer; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.DeserializationContext; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbDeserializer; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.SerializationContext; +import {{rootJavaEEPackage}}.json.stream.JsonGenerator; +import {{rootJavaEEPackage}}.json.stream.JsonParser; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbProperty; +{{#vendorExtensions.x-has-readonly-properties}} +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbCreator; +{{/vendorExtensions.x-has-readonly-properties}} +{{/jsonb}} +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; +{{/jackson}} + +{{#description}} +/** + * {{{.}}} + **/ +{{/description}} +{{>additionalModelTypeAnnotations}} +{{#vendorExtensions.x-class-extra-annotation}} +{{{vendorExtensions.x-class-extra-annotation}}} +{{/vendorExtensions.x-class-extra-annotation}} +public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensions.x-implements}}{{#-first}} implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { + {{#vars}}{{#isEnum}}{{^isContainer}} +{{>enumClass}}{{/isContainer}}{{#isContainer}}{{#mostInnerItems}} +{{>enumClass}}{{/mostInnerItems}}{{/isContainer}}{{/isEnum}} +{{#description}} + /** + * {{{.}}} + **/ +{{/description}} +{{#vendorExtensions.x-field-extra-annotation}} +{{{vendorExtensions.x-field-extra-annotation}}} +{{/vendorExtensions.x-field-extra-annotation}} +{{#isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#required}} = {{{defaultValue}}}{{/required}}{{^required}} = null{{/required}}; +{{/isContainer}} +{{^isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; +{{/isContainer}} + {{/vars}} +{{#vendorExtensions.x-has-readonly-properties}}{{^withXml}} + public {{classname}}() { + } + + {{#jsonb}}@JsonbCreator{{/jsonb}}{{#jackson}}@JsonCreator{{/jackson}} + public {{classname}}( + {{#readOnlyVars}} + {{#jsonb}}@JsonbProperty("{{baseName}}") {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}}{{/jsonb}} + {{#jackson}}@JsonProperty(value="{{baseName}}") {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}}{{/jackson}} + {{/readOnlyVars}} + ) { + {{#readOnlyVars}} + this.{{name}} = {{name}}; + {{/readOnlyVars}} + } + {{/withXml}}{{/vendorExtensions.x-has-readonly-properties}} + {{#vars}} + /** + {{#description}} + * {{.}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + * @return {{name}} + {{#deprecated}} + * @deprecated + {{/deprecated}} + **/ +{{#deprecated}} + @Deprecated +{{/deprecated}} +{{#vendorExtensions.x-extra-annotation}} + {{{vendorExtensions.x-extra-annotation}}} +{{/vendorExtensions.x-extra-annotation}} +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} {{#withXml}}{{#isEnum}}{{^isArray}}{{^isMap}}public {{dataType}} {{getter}}() { + if ({{name}} == null) { + return null; + } + return {{name}}.value(); + }{{/isMap}}{{/isArray}}{{/isEnum}}{{/withXml}}{{^withXml}}{{#isEnum}}{{^isArray}}{{^isMap}}public {{datatypeWithEnum}} {{getter}}() { + return {{name}}; + }{{/isMap}}{{/isArray}}{{/isEnum}}{{/withXml}}{{#isEnum}}{{#isArray}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isArray}}{{/isEnum}}{{#isEnum}}{{#isMap}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isMap}}{{/isEnum}}{{^isEnum}}public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + }{{/isEnum}} + + {{^isReadOnly}} + /** + * Set {{name}} + **/ + {{#vendorExtensions.x-setter-extra-annotation}} {{{vendorExtensions.x-setter-extra-annotation}}} + {{/vendorExtensions.x-setter-extra-annotation}}public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + {{#isArray}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.add({{name}}Item); + return this; + } + {{/isArray}} + {{#isMap}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMap}} + {{/isReadOnly}} + + {{/vars}} + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo_doc.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo_doc.mustache new file mode 100644 index 0000000000..bae0bc48cd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo_doc.mustache @@ -0,0 +1,37 @@ +# {{#vendorExtensions.x-is-one-of-interface}}Interface {{/vendorExtensions.x-is-one-of-interface}}{{classname}} + +{{#description}}{{&description}} +{{/description}} +{{^vendorExtensions.x-is-one-of-interface}} + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +{{#vars}}|**{{name}}** | {{#isEnum}}[**{{datatypeWithEnum}}**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isContainer}}{{#isArray}}{{#items}}{{#isModel}}[{{/isModel}}{{/items}}**{{baseType}}{{#items}}<{{dataType}}>**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/items}}{{/isArray}}{{#isMap}}{{#items}}{{#isModel}}[{{/isModel}}**Map<String, {{dataType}}>**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/items}}{{/isMap}}{{/isContainer}}{{^isContainer}}{{#isModel}}[{{/isModel}}**{{dataType}}**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/isContainer}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#isReadOnly}} [readonly]{{/isReadOnly}} | +{{/vars}} +{{#vars}}{{#isEnum}} + + +## Enum: {{datatypeWithEnum}} + +| Name | Value | +|---- | -----|{{#allowableValues}}{{#enumVars}} +| {{name}} | {{value}} |{{/enumVars}}{{/allowableValues}} +{{/isEnum}}{{/vars}} +{{#vendorExtensions.x-implements.0}} + +## Implemented Interfaces + +{{#vendorExtensions.x-implements}} +* {{{.}}} +{{/vendorExtensions.x-implements}} +{{/vendorExtensions.x-implements.0}} +{{/vendorExtensions.x-is-one-of-interface}} +{{#vendorExtensions.x-is-one-of-interface}} +## Implementing Classes + +{{#oneOf}} +* {{{.}}} +{{/oneOf}} +{{/vendorExtensions.x-is-one-of-interface}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pom.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pom.mustache new file mode 100644 index 0000000000..e58df32a5b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pom.mustache @@ -0,0 +1,100 @@ + + 4.0.0 + {{groupId}} + + io.helidon.applications + helidon-mp + {{{helidonVersion}}} + + + {{artifactId}} + {{artifactId}} + {{#appDescription}} + {{.}} + {{/appDescription}} + {{artifactVersion}} + jar + +{{#openApiNullable}} + + 0.2.3 + +{{/openApiNullable}} + + + + io.helidon.microprofile.bundles + helidon-microprofile-core + + + io.helidon.microprofile.cdi + helidon-microprofile-cdi + + + {{x-helidon-rootJavaEEDepPrefix}}.enterprise + {{x-helidon-rootJavaEEDepPrefix}}.enterprise.cdi-api + + + {{x-helidon-rootJavaEEDepPrefix}}.ws.rs + {{x-helidon-rootJavaEEDepPrefix}}.ws.rs-api + +{{#openApiNullable}} + + org.openapitools + jackson-databind-nullable + ${version.jackson.databind.nullable} + +{{/openApiNullable}} +{{#jackson}} + + org.glassfish.jersey.media + jersey-media-json-jackson + +{{/jackson}} +{{#jsonb}} + + org.glassfish.jersey.media + jersey-media-json-binding + + + {{x-helidon-rootJavaEEDepPrefix}}.json.bind + {{x-helidon-rootJavaEEDepPrefix}}.json.bind-api + +{{/jsonb}} + + org.junit.jupiter + junit-jupiter-api + test + + + io.helidon.microprofile.tests + helidon-microprofile-tests-junit5 + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libs + + + + + org.jboss.jandex + jandex-maven-plugin + + + make-index + + + + + + diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/queryParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/queryParams.mustache new file mode 100644 index 0000000000..38bfb9ed06 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@QueryParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}} {{^isContainer}}{{#defaultValue}}@DefaultValue("{{{.}}}") {{/defaultValue}}{{/isContainer}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/returnAsyncTypeInterface.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/returnAsyncTypeInterface.mustache new file mode 100644 index 0000000000..0da348c7a2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/returnAsyncTypeInterface.mustache @@ -0,0 +1 @@ +CompletionStage<{{#returnResponse}}Response{{/returnResponse}}{{^returnResponse}}{{#returnContainer}}{{#isMap}}Map{{/isMap}}{{#isArray}}{{{returnContainer}}}<{{{returnBaseType}}}>{{/isArray}}{{/returnContainer}}{{^returnContainer}}{{{returnBaseType}}}{{/returnContainer}}{{/returnResponse}}> \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/returnTypes.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/returnTypes.mustache new file mode 100644 index 0000000000..87831bd299 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/returnTypes.mustache @@ -0,0 +1 @@ +{{#returnResponse}}Response{{/returnResponse}}{{^returnResponse}}{{#returnContainer}}{{#isMap}}Map{{/isMap}}{{#isArray}}{{{returnContainer}}}<{{{returnBaseType}}}>{{/isArray}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnResponse}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/typeInfoAnnotation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/typeInfoAnnotation.mustache new file mode 100644 index 0000000000..c833321ebf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/typeInfoAnnotation.mustache @@ -0,0 +1,17 @@ +{{#jackson}} + +@JsonIgnoreProperties( + value = "{{{discriminator.propertyBaseName}}}", // ignore manually set {{{discriminator.propertyBaseName}}}, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the {{{discriminator.propertyBaseName}}} to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{{discriminator.propertyBaseName}}}", visible = true) +{{#discriminator.mappedModels}} +{{#-first}} +@JsonSubTypes({ +{{/-first}} + @JsonSubTypes.Type(value = {{modelName}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{mappingName}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), +{{#-last}} +}) +{{/-last}} +{{/discriminator.mappedModels}} +{{/jackson}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/README.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/README.mustache new file mode 100644 index 0000000000..8d2420f463 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/README.mustache @@ -0,0 +1,34 @@ +# Helidon SE Server with OpenAPI + +## Build and run + +With JDK11+ +```bash +mvn package +java -jar target/{{{artifactId}}}.jar +``` + +## Exercise the application + +``` +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}curl -X {{httpMethod}} {{{basePath}}}{{{path}}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +``` + +## Try health and metrics + +``` +curl -s -X GET {{{basePath}}}/health +{"outcome":"UP",... +. . . + +# Prometheus Format +curl -s -X GET {{{basePath}}}/metrics +# TYPE base:gc_g1_young_generation_count gauge +. . . + +# JSON Format +curl -H 'Accept: application/json' -X GET {{{basePath}}}/metrics +{"base":... +. . . +``` \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/additionalEnumTypeAnnotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/additionalEnumTypeAnnotations.mustache new file mode 100644 index 0000000000..aa524798b4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/additionalEnumTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalEnumTypeAnnotations}}{{{.}}} +{{/additionalEnumTypeAnnotations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/additionalModelTypeAnnotations.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/additionalModelTypeAnnotations.mustache new file mode 100644 index 0000000000..f4871c02cc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/additionalModelTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalModelTypeAnnotations}}{{{.}}} +{{/additionalModelTypeAnnotations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/api.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/api.mustache new file mode 100644 index 0000000000..c44408d778 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/api.mustache @@ -0,0 +1,78 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +{{#useAbstractClass}} +import java.util.Optional; +import java.util.logging.Logger; + +import io.helidon.common.GenericType; +import io.helidon.common.reactive.Single; +{{/useAbstractClass}} +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; +import io.helidon.webserver.Service; + +{{#operations}} +{{^useAbstractClass}}public interface {{classname}} extends Service { {{/useAbstractClass}} +{{#useAbstractClass}}public abstract class {{classname}} implements Service { + + protected static final Logger LOGGER = Logger.getLogger({{classname}}.class.getName()); +{{#jackson}} + protected static final ObjectMapper MAPPER = JsonProvider.objectMapper();{{/jackson}} +{{#jsonb}} + protected static final Jsonb JSONB = JsonbBuilder.create();{{/jsonb}} +{{/useAbstractClass}} + + /** + * A service registers itself by updating the routing rules. + * @param rules the routing rules. + */ + @Override + {{#useAbstractClass}}public{{/useAbstractClass}}{{^useAbstractClass}}default{{/useAbstractClass}} void update(Routing.Rules rules) { +{{#operation}} + rules.{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}("{{{path}}}", {{! + }}{{#bodyParam}}{{#isModel}}Handler.create({{{dataType}}}.class, {{/isModel}}this::{{{operationId}}}){{#isModel}}){{/isModel}}{{/bodyParam}}{{! + }}{{^bodyParam}}this::{{{operationId}}}){{/bodyParam}}; +{{/operation}} + } +{{#useAbstractClass}}{{#isFormParamsFunctions}} + + {{!}}{{>formParamsFunctions}} +{{/isFormParamsFunctions}}{{/useAbstractClass}} +{{#operation}} + + /** + * {{httpMethod}} {{{path}}}{{#summary}} : {{.}}{{/summary}}. + * @param request the server request + * @param response the server response{{#allParams}}{{#isBodyParam}}{{#isModel}} + * @param {{paramName}} {{{description}}}{{^description}}{{paramName}}{{/description}} {{/isModel}}{{/isBodyParam}}{{/allParams}} + */ + void {{{operationId}}}(ServerRequest request, ServerResponse response{{#allParams}}{{#isBodyParam}}{{#isModel}}, {{{dataType}}} {{paramName}}{{/isModel}}{{/isBodyParam}}{{/allParams}}){{^useAbstractClass}};{{/useAbstractClass}}{{#useAbstractClass}} { {{#formParams}}{{#-first}} + {{>formParamsInitial}}{{/-first}}{{/formParams}} + Single.create({{^hasParams}}Single.empty(){{/hasParams}}{{#hasParams}}{{^bodyParam}}{{#formParams}}{{#-first}}formSingle{{/-first}}{{/formParams}}{{^formParams}}Single.empty(){{/formParams}}{{/bodyParam}}{{#bodyParam}}{{^isModel}}request.content().as(new GenericType<{{{dataType}}}>() { }){{/isModel}}{{#isModel}}Single.empty(){{/isModel}}{{/bodyParam}}{{/hasParams}}) + .thenAccept({{#bodyParam}}{{^isModel}}{{paramName}}{{/isModel}}{{#isModel}}val{{/isModel}}{{/bodyParam}}{{^bodyParam}}val{{/bodyParam}} -> { +{{#allParams}} + {{> queryParams }}{{> pathParams }}{{> headerParams}}{{> bodyParams}}{{> formParams}}{{> cookieParams}} +{{/allParams}} + handle{{#lambda.titlecase}}{{{operationId}}}{{/lambda.titlecase}}(request, response{{#allParams}}, {{paramName}}{{/allParams}}); + }) + .exceptionally(throwable -> handleError(request, response, throwable)); + } + + /** + * Handle {{httpMethod}} {{{path}}}{{#summary}} : {{.}}{{/summary}}. + * @param request the server request + * @param response the server response{{#allParams}} + * @param {{paramName}} {{{description}}}{{^description}}{{paramName}}{{/description}} {{/allParams}} + */ + abstract void handle{{#lambda.titlecase}}{{{operationId}}}{{/lambda.titlecase}}(ServerRequest request, ServerResponse response{{#allParams}}, {{>dataType}} {{paramName}}{{/allParams}}); +{{/useAbstractClass}} + +{{/operation}} +{{#useAbstractClass}} abstract Void handleError(ServerRequest request, ServerResponse response, Throwable throwable);{{! +}}{{/useAbstractClass}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/apiImpl.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/apiImpl.mustache new file mode 100644 index 0000000000..b6cf71293f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/apiImpl.mustache @@ -0,0 +1,40 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +{{^useAbstractClass}} +import java.util.logging.Logger;{{/useAbstractClass}} + +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; + +{{#operations}} +public class {{classname}}Impl {{^useAbstractClass}}implements{{/useAbstractClass}}{{#useAbstractClass}}extends{{/useAbstractClass}} {{classname}} { + + private static final int HTTP_CODE_NOT_IMPLEMENTED = 501; +{{^useAbstractClass}} + private static final Logger LOGGER = Logger.getLogger({{classname}}.class.getName()); +{{#jackson}} + private static final ObjectMapper MAPPER = JsonProvider.objectMapper();{{/jackson}} +{{#jsonb}} + private static final Jsonb JSONB = JsonbBuilder.create();{{/jsonb}} +{{/useAbstractClass}} +{{#operation}} + +{{#useAbstractClass}} + public void handle{{#lambda.titlecase}}{{{operationId}}}{{/lambda.titlecase}}(ServerRequest request, ServerResponse response{{#allParams}}, {{>dataType}} {{paramName}}{{/allParams}}) { +{{/useAbstractClass}} +{{^useAbstractClass}} + public void {{{operationId}}}(ServerRequest request, ServerResponse response{{#allParams}}{{#isBodyParam}}{{#isModel}}, {{{dataType}}} {{paramName}}{{/isModel}}{{/isBodyParam}}{{/allParams}}) { +{{/useAbstractClass}} + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } +{{/operation}} + +{{#useAbstractClass}} + public Void handleError(ServerRequest request, ServerResponse response, Throwable throwable) { + return response.send(throwable); + } +{{/useAbstractClass}} +} +{{/operations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/application.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/application.mustache new file mode 100644 index 0000000000..2418f6ef27 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/application.mustache @@ -0,0 +1,3 @@ +server: + port: {{port}}{{^port}}8080{{/port}} + host: {{host}}{{^host}}localhost{{/host}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationCore.mustache new file mode 100644 index 0000000000..d0479eb939 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationCore.mustache @@ -0,0 +1,16 @@ +{{#pattern}}{{#isString}} + ValidatorUtils.validatePattern({{paramName}}, "{{{pattern}}}");{{/isString}}{{/pattern}}{{#minLength}}{{#maxLength}} + ValidatorUtils.validateSize({{paramName}}, {{minLength}}, {{maxLength}});{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} + ValidatorUtils.validateSize({{paramName}}, {{minLength}}, null);{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} + ValidatorUtils.validateSize({{paramName}}, null, {{.}});{{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} + ValidatorUtils.validateSize({{paramName}}, {{minItems}}, {{maxItems}});{{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} + ValidatorUtils.validateSize({{paramName}}, {{minItems}}, null);{{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} + ValidatorUtils.validateSize({{paramName}}, null, {{.}});{{/maxItems}}{{/minItems}}{{#useBeanValidation}}{{#isEmail}} + //RFC 5322 for Email Validation + ValidatorUtils.validatePattern({{paramName}}, "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$");{{/isEmail}}{{/useBeanValidation}}{{#isInteger}}{{#minimum}} + ValidatorUtils.validateMin({{paramName}}, {{.}});{{/minimum}}{{#maximum}} + ValidatorUtils.validateMax({{paramName}}, {{.}});{{/maximum}}{{/isInteger}}{{#isLong}}{{#minimum}} + ValidatorUtils.validateMin({{paramName}}.intValue(), {{.}});{{/minimum}}{{#maximum}} + ValidatorUtils.validateMax({{paramName}}.intValue(), {{.}});{{/maximum}}{{/isLong}}{{^isInteger}}{{^isLong}}{{#minimum}} + ValidatorUtils.validateMin({{paramName}}, "{{minimum}}", {{#exclusiveMinimum}}false{{/exclusiveMinimum}}{{^exclusiveMinimum}}true{{/exclusiveMinimum}});{{/minimum}}{{#maximum}} + ValidatorUtils.validateMax({{paramName}}, "{{maximum}}", {{#exclusiveMaximum}}false{{/exclusiveMaximum}}{{^exclusiveMaximum}}true{{/exclusiveMaximum}});{{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationHeaderParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationHeaderParams.mustache new file mode 100644 index 0000000000..b590d59fd0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationHeaderParams.mustache @@ -0,0 +1,2 @@ +{{#required}}{{!}} + {{!}}ValidatorUtils.checkNonNull({{paramName}});{{/required}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationPathParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationPathParams.mustache new file mode 100644 index 0000000000..60b256f885 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationPathParams.mustache @@ -0,0 +1,2 @@ +{{! PathParam is always required, no @NotNull necessary }} +ValidatorUtils.checkNonNull({{paramName}});{{#isPrimitiveType}}{{>beanValidationCore}}{{/isPrimitiveType}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationQueryParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationQueryParams.mustache new file mode 100644 index 0000000000..dfec605af6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/beanValidationQueryParams.mustache @@ -0,0 +1,2 @@ +{{#required}}{{!}} + {{!}}ValidatorUtils.checkNonNull({{paramName}});{{/required}}{{#isPrimitiveType}}{{>beanValidationCore}}{{/isPrimitiveType}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/bodyParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/bodyParams.mustache new file mode 100644 index 0000000000..7994e23e02 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}ValidatorUtils.checkNonNull({{paramName}});{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/build.gradle.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/build.gradle.mustache new file mode 100644 index 0000000000..32b1002ae4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/build.gradle.mustache @@ -0,0 +1,88 @@ +plugins { + id 'java' + id 'application' +} + +group = '{{{groupId}}}' +version = '{{{artifactVersion}}}' + +{{#appDescription}} +description = """{{.}}""" +{{/appDescription}} + + +sourceCompatibility = 11 +targetCompatibility = 11 + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + +ext { + helidonVersion = '{{{helidonVersion}}}' +{{^interfaceOnly}} + mainClass='{{{invokerPackage}}}.Main' +{{/interfaceOnly}} + validationApiVersion = '2.0.1.Final' +} + +test { + useJUnitPlatform() +} + +repositories { + mavenCentral() + mavenLocal() +} + +dependencies { + // import Helidon BOM + implementation enforcedPlatform("io.helidon:helidon-dependencies:${project.helidonVersion}") + implementation "{{x-helidon-validationArtifactPrefix}}.validation:{{x-helidon-validationArtifactPrefix}}validation-api:${project.validationApiVersion}" + implementation 'io.helidon.webserver:helidon-webserver' + implementation 'io.helidon.media:helidon-media-jsonp' +{{#jackson}} + implementation 'io.helidon.media:helidon-media-jackson' +{{/jackson}} +{{#jsonb}} + implementation 'io.helidon.media:helidon-media-jsonb' +{{/jsonb}} + implementation 'io.helidon.media:helidon-media-multipart' + implementation 'io.helidon.config:helidon-config-yaml' + implementation 'io.helidon.health:helidon-health' + implementation 'io.helidon.health:helidon-health-checks' + implementation 'io.helidon.metrics:helidon-metrics' + implementation 'io.helidon.openapi:helidon-openapi' + testImplementation 'org.junit.jupiter:junit-jupiter-api' + testImplementation 'io.helidon.webclient:helidon-webclient' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' +} + +// define a custom task to copy all dependencies in the runtime classpath +// into build/libs/libs +// uses built-in Copy +task copyLibs(type: Copy) { + from configurations.runtimeClasspath + into 'build/libs/libs' +} + +// add it as a dependency of built-in task 'assemble' +copyLibs.dependsOn jar +assemble.dependsOn copyLibs + +// default jar configuration +// set the main classpath +// add each jar under build/libs/libs into the classpath +jar { + archiveFileName = "${project.name}.jar" + manifest { + attributes ({{^interfaceOnly}}'Main-Class': "${project.mainClass}",{{/interfaceOnly}} + 'Class-Path': configurations.runtimeClasspath.files.collect { "libs/$it.name" }.join(' ') + ) + } +} +{{^interfaceOnly}} +application { +mainClass = "${project.mainClass}" +} +{{/interfaceOnly}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/cookieParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/cookieParams.mustache new file mode 100644 index 0000000000..c11ce65725 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/cookieParams.mustache @@ -0,0 +1 @@ +{{#isCookieParam}}{{>dataType}} {{paramName}} = {{>paramValue}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{/isCookieParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/dataType.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/dataType.mustache new file mode 100644 index 0000000000..cc2a3d0d4d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/dataType.mustache @@ -0,0 +1,11 @@ +{{#isPrimitiveType}}{{^isFile}}{{{dataType}}}{{/isFile}}{{#isFile}}InputStream{{/isFile}}{{/isPrimitiveType}}{{! +}}{{^isPrimitiveType}}{{! + }}{{#isArray}}{{! + }}{{#isBodyParam}}{{{dataType}}}{{/isBodyParam}}{{! + }}{{^isBodyParam}}{{! + }}List<{{#isFormParam}}{{#isFile}}InputStream{{/isFile}}{{^isFile}}String{{/isFile}}{{/isFormParam}}{{! + }}{{^isFormParam}}{{#isModel}}{{{dataType}}}{{/isModel}}{{^isModel}}String{{/isModel}}{{/isFormParam}}>{{! + }}{{/isBodyParam}}{{! + }}{{/isArray}}{{! + }}{{^isArray}}{{^isModel}}String{{/isModel}}{{#isModel}}{{{dataType}}}{{/isModel}}{{/isArray}}{{! +}}{{/isPrimitiveType}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/enumClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/enumClass.mustache new file mode 100644 index 0000000000..b9eeee0040 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/enumClass.mustache @@ -0,0 +1,62 @@ + /** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{{description}}} + */ + {{#jsonb}} + @JsonbTypeSerializer({{datatypeWithEnum}}.Serializer.class) + @JsonbTypeDeserializer({{datatypeWithEnum}}.Deserializer.class) + {{/jsonb}} + {{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}} { + {{#allowableValues}}{{#enumVars}}{{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + {{#jackson}} + @JsonValue + {{/jackson}} + public {{{dataType}}} getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + {{#jsonb}} + public static final class Deserializer implements JsonbDeserializer<{{datatypeWithEnum}}> { + @Override + public {{datatypeWithEnum}} deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(parser.getString())) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");{{/useNullForUnknownEnumValue}} + } + } + + public static final class Serializer implements JsonbSerializer<{{datatypeWithEnum}}> { + @Override + public void serialize({{datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.value); + } + } + {{/jsonb}} + + {{#jackson}} + @JsonCreator + {{/jackson}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + text + "'");{{/useNullForUnknownEnumValue}} + } + } diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/enumOuterClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/enumOuterClass.mustache new file mode 100644 index 0000000000..a695da1902 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/enumOuterClass.mustache @@ -0,0 +1,80 @@ +{{#jsonb}}import java.lang.reflect.Type; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeDeserializer; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.DeserializationContext; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbDeserializer; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.SerializationContext; +import {{rootJavaEEPackage}}.json.stream.JsonGenerator; +import {{rootJavaEEPackage}}.json.stream.JsonParser; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbProperty; +{{#vendorExtensions.x-has-readonly-properties}} +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbCreator; +{{/vendorExtensions.x-has-readonly-properties}}{{/jsonb}} +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue;{{/jackson}} + +/** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{{description}}} + */ +{{#jsonb}} +@JsonbTypeSerializer({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.Serializer.class) +@JsonbTypeDeserializer({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.Deserializer.class){{/jsonb}} +public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + +{{#allowableValues}} + {{#enumVars}} + {{{name}}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} +{{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + {{#jackson}} + @JsonValue + {{/jackson}} + public {{{dataType}}} getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +{{#jsonb}} + public static final class Deserializer implements JsonbDeserializer<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}> { + @Override + public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(parser.getString())) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'");{{/useNullForUnknownEnumValue}} + } + } + + public static final class Serializer implements JsonbSerializer<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}> { + @Override + public void serialize({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.value); + } + } +{{/jsonb}} +{{#jackson}} + @JsonCreator{{/jackson}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + {{#useNullForUnknownEnumValue}}return null;{{/useNullForUnknownEnumValue}}{{^useNullForUnknownEnumValue}}throw new IllegalArgumentException("Unexpected value '" + text + "'");{{/useNullForUnknownEnumValue}} + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/formParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/formParams.mustache new file mode 100644 index 0000000000..82c0f5d715 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{^isFile}}{{>dataType}} {{paramName}} = {{>paramValue}}{{/isFile}}{{#isFile}}{{#isArray}}List<{{/isArray}}InputStream{{#isArray}}>{{/isArray}} {{paramName}} = {{>paramValue}}{{/isFile}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/formParamsFunctions.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/formParamsFunctions.mustache new file mode 100644 index 0000000000..f4e382d481 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/formParamsFunctions.mustache @@ -0,0 +1,17 @@ +private void processNonFileFormField(String name, Map> nonFileFormContent, ReadableBodyPart part) { + List content = nonFileFormContent.computeIfAbsent(name, key -> new ArrayList<>()); + part.content().as(String.class).thenAccept(content::add); + } + + private void processFileFormField(String name, Map> fileFormContent, ReadableBodyPart part) { + List content = fileFormContent.computeIfAbsent(name, key -> new ArrayList<>()); + part.content().map(DataChunk::bytes) + .collect(ByteArrayOutputStream::new, (stream, bytes) -> { + try { + stream.write(bytes); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) + .thenAccept(byteStream -> content.add(new ByteArrayInputStream(byteStream.toByteArray()))); + } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/formParamsInitial.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/formParamsInitial.mustache new file mode 100644 index 0000000000..08d90802b6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/formParamsInitial.mustache @@ -0,0 +1,11 @@ +Map> nonFileFormContent = new HashMap<>(); + Map> fileFormContent = new HashMap<>(); + Single formSingle = request.content().asStream(ReadableBodyPart.class) + .forEach(part -> { + String name = part.name();{{#formParams}} + if ("{{baseName}}".equals(name)) { + {{^isFile}}processNonFileFormField(name, nonFileFormContent, part);{{/isFile}}{{! + }}{{#isFile}}processFileFormField(name, fileFormContent, part);{{/isFile}} + }{{/formParams}} + part.drain(); + }); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/generatedAnnotation.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/generatedAnnotation.mustache new file mode 100644 index 0000000000..6f4eb2cb74 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/generatedAnnotation.mustache @@ -0,0 +1 @@ +@{{rootJavaEEPackage}}.annotation.Generated(value = "{{{generatorClass}}}"{{^hideGenerationTimestamp}}, date = "{{{generatedDate}}}"{{/hideGenerationTimestamp}}) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/headerParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/headerParams.mustache new file mode 100644 index 0000000000..89fb5e8f51 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{>dataType}} {{paramName}} = {{>paramValue}}{{#useBeanValidation}}{{>beanValidationHeaderParams}}{{/useBeanValidation}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/jsonProvider.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/jsonProvider.mustache new file mode 100644 index 0000000000..9a3b6f4c10 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/jsonProvider.mustache @@ -0,0 +1,20 @@ +package {{apiPackage}}; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +public class JsonProvider { + + public static ObjectMapper objectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); + mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false); + return mapper; + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/main.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/main.mustache new file mode 100644 index 0000000000..575d370444 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/main.mustache @@ -0,0 +1,101 @@ +package {{invokerPackage}}; +{{#apiInfo}}{{#apis}}{{#operations}} +import {{package}}.{{classname}}Impl;{{/operations}}{{/apis}}{{/apiInfo}} + +import io.helidon.common.LogConfig; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.health.HealthSupport; +import io.helidon.health.checks.HealthChecks; +import io.helidon.media.jsonp.JsonpSupport; +{{#jsonb}} +import io.helidon.media.jsonb.JsonbSupport; +{{/jsonb}} +{{#jackson}} +import io.helidon.media.jackson.JacksonSupport; +import {{apiPackage}}.JsonProvider; +{{/jackson}} +import io.helidon.metrics.MetricsSupport; +import io.helidon.openapi.OpenAPISupport; +import io.helidon.webserver.Routing; +import io.helidon.webserver.WebServer; + +/** +* The application main class. +*/ +public final class Main { + + /** + * Cannot be instantiated. + */ + private Main() { + } + + /** + * Application main entry point. + * @param args command line arguments. + */ + public static void main(final String[] args) { + startServer(); + } + + /** + * Start the server. + * @return the created {@link WebServer} instance + */ + static Single startServer() { + + // load logging configuration + LogConfig.configureRuntime(); + + // By default this will pick up application.yaml from the classpath + Config config = Config.create(); + + WebServer server = WebServer.builder(createRouting(config)) + .config(config.get("server")) + .addMediaSupport(JsonpSupport.create()) +{{#jsonb}} + .addMediaSupport(JsonbSupport.create()) +{{/jsonb}} +{{#jackson}} + .addMediaSupport(JacksonSupport.create(JsonProvider.objectMapper())) +{{/jackson}} + .build(); + + Single webserver = server.start(); + + // Try to start the server. If successful, print some info and arrange to + // print a message at shutdown. If unsuccessful, print the exception. + webserver.thenAccept(ws -> { + System.out.println("WEB server is up! {{{basePath}}}"); + ws.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!")); + }) + .exceptionallyAccept(t -> { + System.err.println("Startup failed: " + t.getMessage()); + t.printStackTrace(System.err); + }); + + return webserver; + } + + /** + * Creates new {@link Routing}. + * + * @return routing configured with JSON support, a health check, and a service + * @param config configuration of this server + */ + private static Routing createRouting(Config config) { + + MetricsSupport metrics = MetricsSupport.create(); + HealthSupport health = HealthSupport.builder() + .addLiveness(HealthChecks.healthChecks()) // Adds a convenient set of checks + .build(); + + return Routing.builder() + .register(OpenAPISupport.create(config.get(OpenAPISupport.Builder.CONFIG_KEY))) + .register(health) // Health at "/health" + .register(metrics) // Metrics at "/metrics"{{#apiInfo}}{{#apis}}{{#operations}} + .register("/", new {{classname}}Impl()){{/operations}}{{/apis}}{{/apiInfo}} + .build(); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/mainTest.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/mainTest.mustache new file mode 100644 index 0000000000..78c4e89b58 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/mainTest.mustache @@ -0,0 +1,47 @@ +package {{invokerPackage}}; + +import java.util.Collections; +import java.util.concurrent.TimeUnit; + +import {{rootJavaEEPackage}}.json.Json; +import {{rootJavaEEPackage}}.json.JsonBuilderFactory; + +import io.helidon.media.jsonp.JsonpSupport; +import io.helidon.webclient.WebClient; +import io.helidon.webserver.WebServer; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public class MainTest { + + private static WebServer webServer; + private static WebClient webClient; + private static final JsonBuilderFactory JSON_BUILDER = Json.createBuilderFactory(Collections.emptyMap()); + + @BeforeAll + public static void startTheServer() throws Exception { + webServer = Main.startServer().await(); + + webClient = WebClient.builder() + .baseUri("http://localhost:" + webServer.port()) + .addMediaSupport(JsonpSupport.create()) + .build(); + } + + @AfterAll + public static void stopServer() throws Exception { + if (webServer != null) { + webServer.shutdown() + .toCompletableFuture() + .get(10, TimeUnit.SECONDS); + } + } + + @Test + public void test() throws Exception { + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/model.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/model.mustache new file mode 100644 index 0000000000..dbe0359ada --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/model.mustache @@ -0,0 +1,10 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +{{#models}} +{{#model}}{{#isEnum}} +{{>enumOuterClass}}{{/isEnum}}{{^isEnum}} +{{>pojo}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/paramValue.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/paramValue.mustache new file mode 100644 index 0000000000..52ad10dd60 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/paramValue.mustache @@ -0,0 +1,14 @@ +{{#isPathParam}}Optional.ofNullable(request.path().param("{{baseName}}")){{/isPathParam}}{{! +}}{{#isQueryParam}}{{#isPrimitiveType}}request.queryParams().toMap().getOrDefault("{{baseName}}", List.of()).stream().findFirst(){{/isPrimitiveType}}{{/isQueryParam}}{{! +}}{{#isQueryParam}}{{^isPrimitiveType}}Optional.ofNullable(request.queryParams().toMap().get("{{baseName}}")){{/isPrimitiveType}}{{/isQueryParam}}{{! +}}{{#isCookieParam}}{{#isPrimitiveType}}request.headers().cookies().toMap().getOrDefault("{{baseName}}", List.of()).stream().findFirst(){{/isPrimitiveType}}{{/isCookieParam}}{{! +}}{{#isCookieParam}}{{^isPrimitiveType}}Optional.ofNullable(request.headers().cookies().toMap().get("{{baseName}}")){{/isPrimitiveType}}{{/isCookieParam}}{{! +}}{{#isHeaderParam}}request.headers().value("{{baseName}}"){{/isHeaderParam}}{{! +}}{{#isFormParam}}Optional.ofNullable({{#isFile}}fileFormContent{{/isFile}}{{^isFile}}nonFileFormContent{{/isFile}}.get("{{baseName}}")){{^isArray}}.flatMap(list->list.stream().findFirst()){{/isArray}}{{/isFormParam}}{{! +}}{{#isPrimitiveType}}{{^isFile}}{{^isString}}.map({{! + }}{{#isDecimal}}BigDecimal::new{{/isDecimal}}{{! + }}{{#isNumber}}BigDecimal::new{{/isNumber}}{{! + }}{{#isDate}}LocalDate::parse{{/isDate}}{{#isDateTime}}OffsetDateTime::parse{{/isDateTime}}{{! + }}{{^isDecimal}}{{^isNumber}}{{^isDate}}{{^isDateTime}}{{{dataType}}}::valueOf{{/isDateTime}}{{/isDate}}{{/isNumber}}{{/isDecimal}}){{! +}}{{/isString}}{{/isFile}}{{/isPrimitiveType}}{{! +}}.orElse(null); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pathParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pathParams.mustache new file mode 100644 index 0000000000..14464296f1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pathParams.mustache @@ -0,0 +1,2 @@ +{{#isPathParam}}{{> dataType }} {{paramName}} = {{> paramValue }}{{#useBeanValidation}} + {{>beanValidationPathParams}}{{/useBeanValidation}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pojo.mustache new file mode 100644 index 0000000000..944ae48295 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pojo.mustache @@ -0,0 +1,121 @@ +{{#jsonb}} +import java.lang.reflect.Type; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeDeserializer; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbTypeSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.DeserializationContext; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbDeserializer; +import {{rootJavaEEPackage}}.json.bind.serializer.JsonbSerializer; +import {{rootJavaEEPackage}}.json.bind.serializer.SerializationContext; +import {{rootJavaEEPackage}}.json.stream.JsonGenerator; +import {{rootJavaEEPackage}}.json.stream.JsonParser; +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbProperty; +{{#vendorExtensions.x-has-readonly-properties}} +import {{rootJavaEEPackage}}.json.bind.annotation.JsonbCreator; +{{/vendorExtensions.x-has-readonly-properties}} +{{/jsonb}} + +{{#description}} +/** + * {{{.}}} + */{{/description}} +public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { + +{{#vars}} + {{#isEnum}} + + {{^isContainer}} +{{>enumClass}} + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} +{{>enumClass}} + {{/mostInnerItems}} + {{/isContainer}} + + {{/isEnum}} + private {{{datatypeWithEnum}}} {{{name}}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; +{{/vars}} + + /** + * Default constructor. + */ + public {{classname}}() { + // JSON-B / Jackson + } + + /** + * Create {{classname}}. + * +{{#vars}} + * @param {{name}} {{description}}{{^description}}{{name}}{{/description}} +{{/vars}} + */ + public {{classname}}( +{{#vars}} + {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} +{{/vars}} + ) { +{{#vars}} + this.{{name}} = {{name}}; +{{/vars}} + } + +{{#vars}}{{#vendorExtensions.x-has-readonly-properties}}{{#jsonb}} + @JsonbCreator + public {{classname}}( + {{#readOnlyVars}} + @JsonbProperty("{{baseName}}") {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} + {{/readOnlyVars}} + ) { + {{#readOnlyVars}} + this.{{name}} = {{name}}; + {{/readOnlyVars}} + }{{/jsonb}}{{/vendorExtensions.x-has-readonly-properties}} + + /** + {{#description}} + * {{{.}}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + * @return {{name}} + */ + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + }{{/vars}} + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pom.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pom.mustache new file mode 100644 index 0000000000..720ea80bde --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pom.mustache @@ -0,0 +1,116 @@ + + + 4.0.0 + + io.helidon.applications + helidon-se + {{{helidonVersion}}} + + + {{{groupId}}} + {{{artifactId}}} + {{{artifactVersion}}} + {{{artifactId}}} + {{#appDescription}} + {{.}} + {{/appDescription}} + + + {{{invokerPackage}}}.Main + 0.2.3 + + + + + {{x-helidon-rootJavaEEDepPrefix}}.validation + {{x-helidon-validationArtifactPrefix}}validation-api + + + io.helidon.webserver + helidon-webserver + + + io.helidon.media + helidon-media-jsonp + + + io.helidon.media + helidon-media-multipart + + + io.helidon.config + helidon-config-yaml + + + io.helidon.health + helidon-health + + + io.helidon.health + helidon-health-checks + + + io.helidon.metrics + helidon-metrics + + + io.helidon.openapi + helidon-openapi + +{{#openApiNullable}} + + org.openapitools + jackson-databind-nullable + ${version.jackson.databind.nullable} + +{{/openApiNullable}} +{{#jackson}} + + io.helidon.media + helidon-media-jackson + +{{/jackson}} +{{#jsonb}} + + io.helidon.media + helidon-media-jsonb + ${helidon.version} + +{{/jsonb}} + + org.junit.jupiter + junit-jupiter-api + test + + + io.helidon.webclient + helidon-webclient + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libs + + + + + io.helidon.build-tools + helidon-maven-plugin + + + third-party-license-report + + + + + + diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/queryParams.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/queryParams.mustache new file mode 100644 index 0000000000..6b27696451 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{>dataType}} {{paramName}} = {{>paramValue}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/validatorUtils.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/validatorUtils.mustache new file mode 100644 index 0000000000..323407d0c1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/validatorUtils.mustache @@ -0,0 +1,112 @@ +package {{apiPackage}}; + +import java.lang.reflect.Array; +import java.math.BigDecimal; +import java.util.Collection; +import java.util.Map; +import java.util.Objects; + +import {{rootJavaEEPackage}}.validation.ValidationException; + +/** +* Validation utility methods. +*/ +public final class ValidatorUtils { + + public static boolean validateMin(Integer value, Integer min) { + checkNonNull(value); + if (value < min) { + throw new ValidationException(String.format("%s is less than %s", value, min)); + } + return true; + } + + public static boolean validateMax(Integer value, Integer max) { + checkNonNull(value); + if (value > max) { + throw new ValidationException(String.format("%s is more than %s", value, max)); + } + return true; + } + + public static boolean validateSize(Object value, Integer min, Integer max) { + checkNonNull(value); + Integer size = -1; + if (value instanceof Map) { + size = ((Map) value).size(); + } + if (value instanceof CharSequence) { + size = ((CharSequence) value).length(); + } + if (value instanceof Collection) { + size = ((Collection) value).size(); + } + if (value.getClass().isArray()) { + size = Array.getLength(value); + } + if (size == -1) { + throw new ValidationException("Value has incorrect type"); + } + if (min != null) { + validateMin(size, min); + } + if (max != null) { + validateMax(size, max); + } + return true; + } + + public static boolean validatePattern(String value, String pattern) { + checkNonNull(value, pattern); + if (value.matches(pattern)) { + return true; + } + throw new ValidationException(String.format("'%s' does not match the pattern '%s'", value, pattern)); + } + + public static boolean validateMin(BigDecimal value, String stringMinValue, boolean inclusive) { + checkNonNull(value); + BigDecimal minValue = new BigDecimal(stringMinValue); + int result = value.compareTo(minValue); + if (inclusive) { + if (result >= 0) { + return true; + } + } else { + if (result > 0) { + return true; + } + } + throw new ValidationException( + String.format("%s is not valid value. Min value '%s'. Inclusive - %s.", value, stringMinValue, inclusive) + ); + } + + public static boolean validateMax(BigDecimal value, String stringMaxValue, boolean inclusive) { + checkNonNull(value); + BigDecimal maxValue = new BigDecimal(stringMaxValue); + int result = value.compareTo(maxValue); + if (inclusive) { + if (result <= 0) { + return true; + } + } else { + if (result < 0) { + return true; + } + } + throw new ValidationException( + String.format("%s is not valid value. Max value '%s'. Inclusive - %s.", value, stringMaxValue, inclusive) + ); + } + + public static void checkNonNull(Object... args) { + try { + for (Object o : args) { + Objects.requireNonNull(o); + } + } catch (Exception e) { + throw new ValidationException(e); + } + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/licenseInfo.mustache new file mode 100644 index 0000000000..c66209f279 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/licenseInfo.mustache @@ -0,0 +1,11 @@ +/* + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} + * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/logging.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/logging.mustache new file mode 100644 index 0000000000..cd238eb661 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/logging.mustache @@ -0,0 +1,19 @@ + +# Example Logging Configuration File +# For more information see $JAVA_HOME/jre/lib/logging.properties + +# Send messages to the console +handlers=io.helidon.common.HelidonConsoleHandler + +# HelidonConsoleHandler uses a SimpleFormatter subclass that replaces "!thread!" with the current thread +java.util.logging.SimpleFormatter.format=%1$tY.%1$tm.%1$td %1$tH:%1$tM:%1$tS %4$s %3$s !thread!: %5$s%6$s%n + +# Global logging level. Can be overridden by specific loggers +.level=INFO + +# Component specific log levels +#io.helidon.webserver.level=INFO +#io.helidon.config.level=INFO +#io.helidon.security.level=INFO +#io.helidon.common.level=INFO +#io.netty.level=INFO diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/model_test.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/model_test.mustache new file mode 100644 index 0000000000..c0fa11d181 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/model_test.mustache @@ -0,0 +1,47 @@ +{{>licenseInfo}} +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.jupiter.api.Test; + +{{#fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * Model tests for {{classname}} + */ +public class {{classname}}Test { + {{#models}} + {{#model}} + {{^vendorExtensions.x-is-one-of-interface}} + {{^isEnum}} + private final {{classname}} model = new {{classname}}(); + + {{/isEnum}} + /** + * Model tests for {{classname}} + */ + @Test + public void test{{classname}}() { + // TODO: test {{classname}} + } + + {{#allVars}} + /** + * Test the property '{{name}}' + */ + @Test + public void {{name}}Test() { + // TODO: test {{name}} + } + + {{/allVars}} + {{/vendorExtensions.x-is-one-of-interface}} + {{/model}} + {{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/openapi.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/openapi.mustache new file mode 100644 index 0000000000..51ebafb018 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/package-info.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/package-info.mustache new file mode 100644 index 0000000000..c0a6d4bbb9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/package-info.mustache @@ -0,0 +1 @@ +package {{invokerPackage}}; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/settings.gradle.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/settings.gradle.mustache new file mode 100644 index 0000000000..448dc07602 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/settings.gradle.mustache @@ -0,0 +1 @@ +rootProject.name = '{{artifactId}}' \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-undertow-server/pom.mustache b/modules/openapi-generator/src/main/resources/java-undertow-server/pom.mustache index 2f2a80196a..b339616cd5 100644 --- a/modules/openapi-generator/src/main/resources/java-undertow-server/pom.mustache +++ b/modules/openapi-generator/src/main/resources/java-undertow-server/pom.mustache @@ -16,8 +16,8 @@ 1.8 UTF-8 0.1.1 - 2.10.5 - 2.10.5.1 + 2.12.7 + 2.12.7 1.7.21 0.5.2 4.5.3 @@ -29,7 +29,7 @@ 1.2.0 4.13.2 2.1.0-beta.124 - 2.1.6.Final + 2.2.19.Final 2.2.0 4.5.13 4.1.2 diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/README.mustache index 45bf156f8a..d6dca22f5f 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/README.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/README.mustache @@ -1,5 +1,22 @@ # {{packageName}} - Kotlin client library for {{appName}} +{{#appDescriptionWithNewLines}} +{{{.}}} +{{/appDescriptionWithNewLines}} + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + ## Requires {{#jvm}} @@ -89,4 +106,9 @@ Authentication schemes defined for the API: {{/scopes}} {{/isOAuth}} -{{/authMethods}} +{{/authMethods}}{{#infoEmail}} + +## Author + +{{{.}}} +{{/infoEmail}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache index ef2426d833..5716f8656c 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache @@ -3,15 +3,15 @@ version '{{artifactVersion}}' {{^omitGradleWrapper}} wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } {{/omitGradleWrapper}} buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' {{#jvm-ktor}} - ext.ktor_version = '1.6.7' + ext.ktor_version = '2.0.3' {{/jvm-ktor}} {{#jvm-retrofit2}} ext.retrofitVersion = '2.9.0' @@ -72,46 +72,49 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" {{^doNotUseRxAndCoroutines}} {{#useCoroutines}} - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.3" {{/useCoroutines}} {{/doNotUseRxAndCoroutines}} {{#moshi}} {{^moshiCodeGen}} implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" {{/moshiCodeGen}} {{#moshiCodeGen}} - implementation "com.squareup.moshi:moshi:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.12.0" + implementation "com.squareup.moshi:moshi:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + kapt "com.squareup.moshi:moshi-kotlin-codegen:1.13.0" {{/moshiCodeGen}} {{/moshi}} {{#gson}} - implementation "com.google.code.gson:gson:2.8.7" + implementation "com.google.code.gson:gson:2.9.0" {{/gson}} {{#jackson}} implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.3" - implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.3" + implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.13.3" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.3" {{/jackson}} {{#kotlinx_serialization}} - implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1" + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.3" {{/kotlinx_serialization}} {{#jvm-ktor}} implementation "io.ktor:ktor-client-core:$ktor_version" + implementation "io.ktor:ktor-client-content-negotiation:$ktor_version" {{#gson}} + implementation "io.ktor:ktor-serialization-gson:$ktor_version" implementation "io.ktor:ktor-client-gson:$ktor_version" {{/gson}} {{#jackson}} implementation "io.ktor:ktor-client-jackson:$ktor_version" + implementation "io.ktor:ktor-serialization-jackson:$ktor_version" {{/jackson}} {{/jvm-ktor}} {{#jvm-okhttp3}} implementation "com.squareup.okhttp3:okhttp:3.12.13" {{/jvm-okhttp3}} {{#jvm-okhttp4}} - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.okhttp3:okhttp:4.10.0" {{/jvm-okhttp4}} {{#threetenbp}} implementation "org.threeten:threetenbp:1.5.1" @@ -120,7 +123,7 @@ dependencies { {{#hasOAuthMethods}} implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" {{/hasOAuthMethods}} - implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "com.squareup.okhttp3:logging-interceptor:4.10.0" {{#useRxJava}} implementation "io.reactivex:rxjava:$rxJavaVersion" implementation "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion" diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache index 5f5b4da03c..8d2c28acd4 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache @@ -19,6 +19,13 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo import {{#serializableModel}}kotlinx.serialization.Serializable as KSerializable{{/serializableModel}}{{^serializableModel}}kotlinx.serialization.Serializable{{/serializableModel}} import kotlinx.serialization.SerialName import kotlinx.serialization.Contextual +{{#enumUnknownDefaultCase}} +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +{{/enumUnknownDefaultCase}} {{#hasEnums}} {{/hasEnums}} {{/kotlinx_serialization}} @@ -88,7 +95,7 @@ import {{packageName}}.infrastructure.ITransformForStorage */ {{^multiplatform}} {{#kotlinx_serialization}} - {{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{/serializableModel}} + {{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{#enumUnknownDefaultCase}}(with = {{classname}}Serializer::class){{/enumUnknownDefaultCase}}{{/serializableModel}} {{/kotlinx_serialization}} {{/multiplatform}} {{#multiplatform}} @@ -116,7 +123,22 @@ import {{packageName}}.infrastructure.ITransformForStorage {{/multiplatform}} {{/enumVars}} {{/allowableValues}} - } + }{{#kotlinx_serialization}}{{#enumUnknownDefaultCase}} + + @Serializer(forClass = {{{nameInCamelCase}}}::class) + internal object {{nameInCamelCase}}Serializer : KSerializer<{{nameInCamelCase}}> { + override val descriptor = {{{dataType}}}.serializer().descriptor + + override fun deserialize(decoder: Decoder): {{nameInCamelCase}} { + val value = decoder.decodeSerializableValue({{{dataType}}}.serializer()) + return {{nameInCamelCase}}.values().firstOrNull { it.value == value } + ?: {{nameInCamelCase}}.{{#allowableValues}}{{#enumVars}}{{#-last}}{{&name}}{{/-last}}{{/enumVars}}{{/allowableValues}} + } + + override fun serialize(encoder: Encoder, value: {{nameInCamelCase}}) { + encoder.encodeSerializableValue({{{dataType}}}.serializer(), value.value) + } + }{{/enumUnknownDefaultCase}}{{/kotlinx_serialization}} {{/isEnum}} {{/vars}} {{/hasEnums}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache index fcdcd87ffa..4d11f8f265 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache @@ -11,6 +11,13 @@ import com.fasterxml.jackson.annotation.JsonProperty {{#kotlinx_serialization}} import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +{{#enumUnknownDefaultCase}} +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +{{/enumUnknownDefaultCase}} {{/kotlinx_serialization}} {{/multiplatform}} {{#multiplatform}} @@ -22,7 +29,7 @@ import kotlinx.serialization.* * * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ -{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}@Serializable{{/kotlinx_serialization}} +{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}@Serializable{{#enumUnknownDefaultCase}}(with = {{classname}}Serializer::class){{/enumUnknownDefaultCase}}{{/kotlinx_serialization}} {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{classname}}(val value: {{{dataType}}}) { {{#allowableValues}}{{#enumVars}} {{^multiplatform}} @@ -79,4 +86,19 @@ import kotlinx.serialization.* } } } -} +}{{#kotlinx_serialization}}{{#enumUnknownDefaultCase}} + +@Serializer(forClass = {{classname}}::class) +internal object {{classname}}Serializer : KSerializer<{{classname}}> { + override val descriptor = {{{dataType}}}.serializer().descriptor + + override fun deserialize(decoder: Decoder): {{classname}} { + val value = decoder.decodeSerializableValue({{{dataType}}}.serializer()) + return {{classname}}.values().firstOrNull { it.value == value } + ?: {{classname}}.{{#allowableValues}}{{#enumVars}}{{#-last}}{{&name}}{{/-last}}{{/enumVars}}{{/allowableValues}} + } + + override fun serialize(encoder: Encoder, value: {{classname}}) { + encoder.encodeSerializableValue({{{dataType}}}.serializer(), value.value) + } +}{{/enumUnknownDefaultCase}}{{/kotlinx_serialization}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicBooleanAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicBooleanAdapter.kt.mustache index e7409f3eca..098ff54c6a 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicBooleanAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicBooleanAdapter.kt.mustache @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.util.concurrent.atomic.AtomicBoolean @Serializer(forClass = AtomicBoolean::class) -object AtomicBooleanAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object AtomicBooleanAdapter : KSerializer { override fun serialize(encoder: Encoder, value: AtomicBoolean) { encoder.encodeBoolean(value.get()) } @@ -18,4 +18,4 @@ object AtomicBooleanAdapter : KSerializer { override fun deserialize(decoder: Decoder): AtomicBoolean = AtomicBoolean(decoder.decodeBoolean()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicBoolean", PrimitiveKind.BOOLEAN) -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicIntegerAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicIntegerAdapter.kt.mustache index 5b79c7e6c3..6e16b5b78a 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicIntegerAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicIntegerAdapter.kt.mustache @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.util.concurrent.atomic.AtomicInteger @Serializer(forClass = AtomicInteger::class) -object AtomicIntegerAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object AtomicIntegerAdapter : KSerializer { override fun serialize(encoder: Encoder, value: AtomicInteger) { encoder.encodeInt(value.get()) } @@ -18,4 +18,4 @@ object AtomicIntegerAdapter : KSerializer { override fun deserialize(decoder: Decoder): AtomicInteger = AtomicInteger(decoder.decodeInt()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicInteger", PrimitiveKind.INT) -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicLongAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicLongAdapter.kt.mustache index ce91e34742..bc2142c676 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicLongAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/AtomicLongAdapter.kt.mustache @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.util.concurrent.atomic.AtomicLong @Serializer(forClass = AtomicLong::class) -object AtomicLongAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object AtomicLongAdapter : KSerializer { override fun serialize(encoder: Encoder, value: AtomicLong) { encoder.encodeLong(value.get()) } @@ -18,4 +18,4 @@ object AtomicLongAdapter : KSerializer { override fun deserialize(decoder: Decoder): AtomicLong = AtomicLong(decoder.decodeLong()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicLong", PrimitiveKind.LONG) -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache index 609d15a34d..fd08ed4a04 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache @@ -15,12 +15,16 @@ import com.squareup.moshi.ToJson {{/moshi}} import java.math.BigDecimal -{{#kotlinx_serialization}}@Serializer(forClass = BigDecimal::class) -object BigDecimalAdapter : KSerializer { +{{#kotlinx_serialization}} +@Serializer(forClass = BigDecimal::class) +{{#nonPublicApi}}internal {{/nonPublicApi}}object BigDecimalAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): BigDecimal = BigDecimal(decoder.decodeString()) override fun serialize(encoder: Encoder, value: BigDecimal) = encoder.encodeString(value.toPlainString()) -}{{/kotlinx_serialization}}{{#moshi}}{{#nonPublicApi}}internal {{/nonPublicApi}}class BigDecimalAdapter { +} +{{/kotlinx_serialization}} +{{#moshi}} +{{#nonPublicApi}}internal {{/nonPublicApi}}class BigDecimalAdapter { @ToJson fun toJson(value: BigDecimal): String { return value.toPlainString() @@ -30,4 +34,5 @@ object BigDecimalAdapter : KSerializer { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -}{{/moshi}} \ No newline at end of file +} +{{/moshi}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache index 2924e8f63a..5110e25b1d 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache @@ -15,8 +15,9 @@ import com.squareup.moshi.ToJson {{/moshi}} import java.math.BigInteger -{{#kotlinx_serialization}}@Serializer(forClass = BigInteger::class) -object BigIntegerAdapter : KSerializer { +{{#kotlinx_serialization}} +@Serializer(forClass = BigInteger::class) +{{#nonPublicApi}}internal {{/nonPublicApi}}object BigIntegerAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigInteger", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): BigInteger { return BigInteger(decoder.decodeString()) @@ -25,7 +26,10 @@ object BigIntegerAdapter : KSerializer { override fun serialize(encoder: Encoder, value: BigInteger) { encoder.encodeString(value.toString()) } -}{{/kotlinx_serialization}}{{#moshi}}{{#nonPublicApi}}internal {{/nonPublicApi}}class BigIntegerAdapter { +} +{{/kotlinx_serialization}} +{{#moshi}} +{{#nonPublicApi}}internal {{/nonPublicApi}}class BigIntegerAdapter { @ToJson fun toJson(value: BigInteger): String { return value.toString() @@ -35,4 +39,5 @@ object BigIntegerAdapter : KSerializer { fun fromJson(value: String): BigInteger { return BigInteger(value) } -}{{/moshi}} \ No newline at end of file +} +{{/moshi}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache index 97b5fd6619..cdcf444ec3 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache @@ -72,7 +72,7 @@ import org.threeten.bp.format.DateTimeFormatter {{/gson}} {{#kotlinx_serialization}} @Serializer(forClass = LocalDate::class) -object LocalDateAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object LocalDateAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDate", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: LocalDate) { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache index 3608ddb0db..8d793d1ff4 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache @@ -72,7 +72,7 @@ import org.threeten.bp.format.DateTimeFormatter {{/gson}} {{#kotlinx_serialization}} @Serializer(forClass = LocalDateTime::class) -object LocalDateTimeAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object LocalDateTimeAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDateTime", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: LocalDateTime) { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache index 855b4c87df..fff7ded5c2 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache @@ -72,7 +72,7 @@ import org.threeten.bp.format.DateTimeFormatter {{/gson}} {{#kotlinx_serialization}} @Serializer(forClass = OffsetDateTime::class) -object OffsetDateTimeAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object OffsetDateTimeAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("OffsetDateTime", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: OffsetDateTime) { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache index 884e16846b..3120046572 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache @@ -98,8 +98,13 @@ import java.util.concurrent.atomic.AtomicLong .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) {{/jackson}} {{#kotlinx_serialization}} + @Deprecated("Use Serializer.kotlinxSerializationAdapters instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationAdapters")) @JvmStatic - val kotlinSerializationAdapters = SerializersModule { + val kotlinSerializationAdapters: SerializersModule + get() { return kotlinxSerializationAdapters } + + @JvmStatic + val kotlinxSerializationAdapters = SerializersModule { contextual(BigDecimal::class, BigDecimalAdapter) contextual(BigInteger::class, BigIntegerAdapter) contextual(LocalDate::class, LocalDateAdapter) @@ -114,7 +119,18 @@ import java.util.concurrent.atomic.AtomicLong contextual(StringBuilder::class, StringBuilderAdapter) } + @Deprecated("Use Serializer.kotlinxSerializationJson instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationJson")) @JvmStatic - val jvmJson: Json by lazy { Json { serializersModule = kotlinSerializationAdapters } } + val jvmJson: Json + get() { return kotlinxSerializationJson } + + @JvmStatic + val kotlinxSerializationJson: Json by lazy { + Json { + serializersModule = kotlinxSerializationAdapters + ignoreUnknownKeys = true + isLenient = true + } + } {{/kotlinx_serialization}} } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/StringBuilderAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/StringBuilderAdapter.kt.mustache index 4b428095a7..3d53670307 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/StringBuilderAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/StringBuilderAdapter.kt.mustache @@ -9,7 +9,7 @@ import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.SerialDescriptor @Serializer(forClass = StringBuilder::class) -object StringBuilderAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object StringBuilderAdapter : KSerializer { override fun serialize(encoder: Encoder, value: StringBuilder) { encoder.encodeString(value.toString()) } @@ -17,4 +17,4 @@ object StringBuilderAdapter : KSerializer { override fun deserialize(decoder: Decoder): StringBuilder = StringBuilder(decoder.decodeString()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("StringBuilder", PrimitiveKind.STRING) -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache index c958295555..2fae6a3b6b 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache @@ -26,7 +26,7 @@ import java.net.URI {{/moshi}} {{#kotlinx_serialization}} @Serializer(forClass = URI::class) -object URIAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object URIAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URI) { encoder.encodeString(value.toASCIIString()) } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache index eaebad52cc..b437ff89ae 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.net.URL @Serializer(forClass = URL::class) -object URLAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object URLAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URL) { encoder.encodeString(value.toExternalForm()) } @@ -18,4 +18,4 @@ object URLAdapter : KSerializer { override fun deserialize(decoder: Decoder): URL = URL(decoder.decodeString()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URL", PrimitiveKind.STRING) -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache index ea903c36ca..d0ec45c471 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache @@ -26,7 +26,7 @@ import java.util.UUID {{/moshi}} {{#kotlinx_serialization}} @Serializer(forClass = UUID::class) -object UUIDAdapter : KSerializer { +{{#nonPublicApi}}internal {{/nonPublicApi}}object UUIDAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: UUID) { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/proguard-rules.pro.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/proguard-rules.pro.mustache index 8b56c506d0..6da4eba506 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/proguard-rules.pro.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/proguard-rules.pro.mustache @@ -8,4 +8,4 @@ # project specific. -keep,includedescriptorclasses class {{modelPackage}}.**$$serializer { *; } -keepclassmembers class {{modelPackage}}.** { *** Companion; } --keepclasseswithmembers class {{modelPackage}}.** { kotlinx.serialization.KSerializer serializer(...); } \ No newline at end of file +-keepclasseswithmembers class {{modelPackage}}.** { kotlinx.serialization.KSerializer serializer(...); } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/api.mustache index 5b6c968d38..168401c674 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/api.mustache @@ -9,9 +9,10 @@ import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.http.ParametersBuilder - {{#gson}} import com.google.gson.Gson +import com.google.gson.GsonBuilder +import java.text.DateFormat {{/gson}} {{#jackson}} import com.fasterxml.jackson.databind.ObjectMapper @@ -22,8 +23,13 @@ import com.fasterxml.jackson.databind.ObjectMapper baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: {{#gson}}Gson{{/gson}}{{#jackson}}ObjectMapper{{/jackson}} = ApiClient.JSON_DEFAULT, - ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, json) { + {{#gson}} + jsonBlock: GsonBuilder.() -> Unit = ApiClient.JSON_DEFAULT, + {{/gson}} + {{#jackson}} + jsonBlock: ObjectMapper.() -> Unit = ApiClient.JSON_DEFAULT, + {{/jackson}} + ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonBlock) { {{#operation}} /** diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache index b852ac8ec1..51a0a5f504 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache @@ -1,50 +1,68 @@ package {{packageName}}.infrastructure + import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.JsonFeature -import io.ktor.client.features.json.JsonSerializer -import io.ktor.client.request.* +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter +import io.ktor.client.request.request +import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse -import io.ktor.client.utils.EmptyContent -import io.ktor.http.* -import io.ktor.http.content.ByteArrayContent -import io.ktor.http.content.OutgoingContent +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpMethod +import io.ktor.http.Parameters +import io.ktor.http.URLBuilder import io.ktor.http.content.PartData -import kotlin.Unit - +import io.ktor.http.encodeURLQueryComponent +import io.ktor.http.encodedPath +import io.ktor.http.takeFrom {{#gson}} -import com.google.gson.Gson -import java.nio.charset.StandardCharsets +import io.ktor.serialization.gson.* +import com.google.gson.GsonBuilder +import java.text.DateFormat {{/gson}} {{#jackson}} +import io.ktor.serialization.jackson.* +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.SerializationFeature +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule +import com.fasterxml.jackson.core.util.DefaultIndenter +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter {{/jackson}} - +import org.openapitools.client.auth.ApiKeyAuth +import org.openapitools.client.auth.Authentication +import org.openapitools.client.auth.HttpBasicAuth +import org.openapitools.client.auth.HttpBearerAuth +import org.openapitools.client.auth.OAuth import {{packageName}}.auth.* {{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: {{#gson}}Gson{{/gson}}{{#jackson}}ObjectMapper{{/jackson}}, + {{#gson}} + jsonBlock: GsonBuilder.() -> Unit = JSON_DEFAULT, + {{/gson}} + {{#jackson}} + jsonBlock: ObjectMapper.() -> Unit = JSON_DEFAULT, + {{/jackson}} ) { - private val serializer: JsonSerializer by lazy { - JsonSerializerImpl(json) - } - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { { - // Hold a reference to the serializer to avoid freezing the entire ApiClient instance - // when the JsonFeature is configured. - val serializerReference = serializer - it.install(JsonFeature) { serializer = serializerReference } + it.install(ContentNegotiation) { + {{#gson}} + gson { jsonBlock() } + {{/gson}} + {{#jackson}} + jackson { jsonBlock() } + {{/jackson}} + } httpClientConfig?.invoke(it) } } @@ -67,9 +85,24 @@ import {{packageName}}.auth.* {{/hasAuthMethods}} {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - const val BASE_URL = "{{{basePath}}}" - val JSON_DEFAULT = {{#gson}}Gson(){{/gson}}{{#jackson}}ObjectMapper(){{/jackson}} - protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) + const val BASE_URL = "{{{basePath}}}" + {{#gson}} + val JSON_DEFAULT : GsonBuilder.() -> Unit = { + setDateFormat(DateFormat.LONG) + setPrettyPrinting() + } + {{/gson}} + {{#jackson}} + val JSON_DEFAULT: ObjectMapper.() -> Unit = { + configure(SerializationFeature.INDENT_OUTPUT, true) + setDefaultPrettyPrinter(DefaultPrettyPrinter().apply { + indentArraysWith(DefaultPrettyPrinter.FixedSpaceIndenter.instance) + indentObjectsWith(DefaultIndenter(" ", "\n")) + }) + registerModule(JavaTimeModule()) + } + {{/jackson}} + protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) } /** @@ -78,7 +111,7 @@ import {{packageName}}.auth.* * @param username Username */ fun setUsername(username: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? ?: throw Exception("No HTTP basic authentication configured") auth.username = username } @@ -89,7 +122,7 @@ import {{packageName}}.auth.* * @param password Password */ fun setPassword(password: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? ?: throw Exception("No HTTP basic authentication configured") auth.password = password } @@ -101,7 +134,7 @@ import {{packageName}}.auth.* * @param paramName The name of the API key parameter, or null or set the first key. */ fun setApiKey(apiKey: String, paramName: String? = null) { - val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? + val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? ?: throw Exception("No API key authentication configured") auth.apiKey = apiKey } @@ -113,7 +146,7 @@ import {{packageName}}.auth.* * @param paramName The name of the API key parameter, or null or set the first key. */ fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) { - val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? + val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? ?: throw Exception("No API key authentication configured") auth.apiKeyPrefix = apiKeyPrefix } @@ -124,7 +157,7 @@ import {{packageName}}.auth.* * @param accessToken Access token */ fun setAccessToken(accessToken: String) { - val auth = authentications?.values?.firstOrNull { it is OAuth } as OAuth? + val auth = authentications.values.firstOrNull { it is OAuth } as OAuth? ?: throw Exception("No OAuth2 authentication configured") auth.accessToken = accessToken } @@ -135,7 +168,7 @@ import {{packageName}}.auth.* * @param bearerToken The bearer token. */ fun setBearerToken(bearerToken: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? + val auth = authentications.values.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? ?: throw Exception("No Bearer authentication configured") auth.bearerToken = bearerToken } @@ -148,18 +181,13 @@ import {{packageName}}.auth.* return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) } - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } - ?: ContentType.Application.Json) - return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) - else request(requestConfig, authNames = authNames) - } + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.request { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -172,8 +200,7 @@ import {{packageName}}.auth.* this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - this.body = body - + setBody(body) } } @@ -199,13 +226,3 @@ import {{packageName}}.auth.* RequestMethod.OPTIONS -> HttpMethod.Options } } - -{{#gson}}private class JsonSerializerImpl(private val gson: Gson) : JsonSerializer { - override fun write(data: Any, contentType: ContentType): OutgoingContent = - ByteArrayContent(gson.toJson(data).toByteArray(StandardCharsets.UTF_8), contentType) -}{{/gson}} - -{{#jackson}}private class JsonSerializerImpl(private val objectMapper: ObjectMapper) : JsonSerializer { - override fun write(data: Any, contentType: ContentType): OutgoingContent = - ByteArrayContent(objectMapper.writeValueAsBytes(data), contentType) -}{{/jackson}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/HttpResponse.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/HttpResponse.kt.mustache index 12d2656746..87a68f3084 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/HttpResponse.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/HttpResponse.kt.mustache @@ -1,9 +1,9 @@ package {{packageName}}.infrastructure -import io.ktor.client.call.TypeInfo -import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo {{#nonPublicApi}}internal {{/nonPublicApi}}open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { val status: Int = response.status.value @@ -29,11 +29,11 @@ import io.ktor.http.isSuccess {{#nonPublicApi}}internal {{/nonPublicApi}}class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { @Suppress("UNCHECKED_CAST") override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.receive(type) as T + response.call.body(type) as T @Suppress("UNCHECKED_CAST") override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.receive(type) as V + response.call.body(type) as V } {{#nonPublicApi}}internal {{/nonPublicApi}}class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache index 4631295540..5c467a1b88 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache @@ -3,6 +3,7 @@ package {{apiPackage}} import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl {{#imports}}import {{import}} {{/imports}} @@ -130,7 +131,7 @@ import {{packageName}}.infrastructure.toMultiValue {{#isDeprecated}} @Deprecated(message = "This operation is deprecated.") {{/isDeprecated}} - {{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}_{{operationId}}>{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : {{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{^doNotUseRxAndCoroutines}}{{#useCoroutines}} = withContext(Dispatchers.IO){{/useCoroutines}}{{/doNotUseRxAndCoroutines}} { + {{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}_{{operationId}}>{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : {{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{^doNotUseRxAndCoroutines}}{{#useCoroutines}} = withContext(Dispatchers.IO){{/useCoroutines}}{{/doNotUseRxAndCoroutines}} { {{#isDeprecated}} @Suppress("DEPRECATION") {{/isDeprecated}} @@ -224,7 +225,7 @@ import {{packageName}}.infrastructure.toMultiValue return RequestConfig( method = RequestMethod.{{httpMethod}}, - path = "{{path}}"{{#pathParams}}.replace("{"+"{{baseName}}"+"}", {{#isContainer}}{{paramName}}.joinToString(","){{/isContainer}}{{^isContainer}}{{{paramName}}}{{#isEnum}}.value{{/isEnum}}.toString(){{/isContainer}}){{/pathParams}}, + path = "{{path}}"{{#pathParams}}.replace("{"+"{{baseName}}"+"}", encodeURIComponent({{#isContainer}}{{paramName}}.joinToString(","){{/isContainer}}{{^isContainer}}{{{paramName}}}{{#isEnum}}.value{{/isEnum}}.toString(){{/isContainer}})){{/pathParams}}, query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -232,5 +233,8 @@ import {{packageName}}.infrastructure.toMultiValue } {{/operation}} + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments{{#jvm-okhttp3}}(){{/jvm-okhttp3}}[0] } {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache index 32b2028281..3c1a0b156f 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache @@ -116,6 +116,12 @@ import com.squareup.moshi.adapter protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + {{#jvm-okhttp3}} + content is File -> RequestBody.create(MediaType.parse(mediaType ?: guessContentTypeFromFile(content)), content) + {{/jvm-okhttp3}} + {{#jvm-okhttp4}} + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) + {{/jvm-okhttp4}} mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -123,27 +129,41 @@ import com.squareup.moshi.adapter // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart({{#jvm-okhttp3}}Headers.of(headers){{/jvm-okhttp3}}{{#jvm-okhttp4}}headers.toHeaders(){{/jvm-okhttp4}}, - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + {{#jvm-okhttp3}} + val fileMediaType = MediaType.parse(guessContentTypeFromFile(part.body)) + addPart( + Headers.of(partHeaders), + RequestBody.create(fileMediaType, part.body) + ) + {{/jvm-okhttp3}} + {{#jvm-okhttp4}} + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + {{/jvm-okhttp4}} + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + {{#jvm-okhttp3}} + addPart( + Headers.of(partHeaders), + RequestBody.create(null, parameterToString(part.body)) + ) + {{/jvm-okhttp3}} + {{#jvm-okhttp4}} + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) + {{/jvm-okhttp4}} } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - {{#jvm-okhttp3}} - content is File -> RequestBody.create(MediaType.parse(mediaType ?: guessContentTypeFromFile(content)), content) - {{/jvm-okhttp3}} - {{#jvm-okhttp4}} - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) - {{/jvm-okhttp4}} mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -169,7 +189,7 @@ import com.squareup.moshi.adapter MediaType.parse(mediaType ?: JsonMediaType), Serializer.jacksonObjectMapper.writeValueAsString(content) {{/jackson}} {{#kotlinx_serialization}} - MediaType.parse(mediaType ?: JsonMediaType), Serializer.jvmJson.encodeToString(content) + MediaType.parse(mediaType ?: JsonMediaType), Serializer.kotlinxSerializationJson.encodeToString(content) {{/kotlinx_serialization}} ) } @@ -188,7 +208,7 @@ import com.squareup.moshi.adapter Serializer.jacksonObjectMapper.writeValueAsString(content) {{/jackson}} {{#kotlinx_serialization}} - Serializer.jvmJson.encodeToString(content) + Serializer.kotlinxSerializationJson.encodeToString(content) {{/kotlinx_serialization}} .toRequestBody((mediaType ?: JsonMediaType).toMediaTypeOrNull()) } @@ -236,7 +256,7 @@ import com.squareup.moshi.adapter {{#moshi}}Serializer.moshi.adapter().fromJson(bodyContent){{/moshi}}{{! }}{{#gson}}Serializer.gson.fromJson(bodyContent, (object: TypeToken(){}).getType()){{/gson}}{{! }}{{#jackson}}Serializer.jacksonObjectMapper.readValue(bodyContent, object: TypeReference() {}){{/jackson}}{{! - }}{{#kotlinx_serialization}}Serializer.jvmJson.decodeFromString(bodyContent){{/kotlinx_serialization}} + }}{{#kotlinx_serialization}}Serializer.kotlinxSerializationJson.decodeFromString(bodyContent){{/kotlinx_serialization}} else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } @@ -313,7 +333,7 @@ import com.squareup.moshi.adapter {{/hasAuthMethods}} val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -323,7 +343,7 @@ import com.squareup.moshi.adapter }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -331,16 +351,16 @@ import com.squareup.moshi.adapter } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -432,7 +452,7 @@ import com.squareup.moshi.adapter return Serializer.jacksonObjectMapper.writeValueAsString(value).replace("\"", "") {{/jackson}} {{#kotlinx_serialization}} - return Serializer.jvmJson.encodeToString(value).replace("\"", "") + return Serializer.kotlinxSerializationJson.encodeToString(value).replace("\"", "") {{/kotlinx_serialization}} {{/toJson}} {{^toJson}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache index afc245c8f6..3626029f76 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache @@ -36,6 +36,24 @@ import io.reactivex.rxjava3.core.Completable {{/useRxJava3}} {{/returnType}} {{/doNotUseRxAndCoroutines}} +{{^multiplatform}} +{{#gson}} +import com.google.gson.annotations.SerializedName +{{/gson}} +{{#moshi}} +import com.squareup.moshi.Json +{{/moshi}} +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonProperty +{{/jackson}} +{{#kotlinx_serialization}} +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +{{/kotlinx_serialization}} +{{/multiplatform}} +{{#multiplatform}} +import kotlinx.serialization.* +{{/multiplatform}} {{#imports}}import {{import}} {{/imports}} @@ -55,15 +73,71 @@ import okhttp3.ResponseBody {{/operation}} interface {{classname}} { {{#operation}} + {{#allParams}} + {{#isEnum}} + + /** + * enum for parameter {{paramName}} + */ + {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{enumName}}_{{operationId}}(val value: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}kotlin.String{{/isContainer}}) { + {{^enumUnknownDefaultCase}} + {{#allowableValues}} + {{#enumVars}} + {{^multiplatform}} + {{#moshi}} + @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} + {{/moshi}} + {{#gson}} + @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} + {{/gson}} + {{#jackson}} + @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} + {{/jackson}} + {{#kotlinx_serialization}} + @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} + {{/kotlinx_serialization}} + {{/multiplatform}} + {{#multiplatform}} + @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} + {{/multiplatform}} + {{/enumVars}} + {{/allowableValues}} + {{/enumUnknownDefaultCase}} + {{#enumUnknownDefaultCase}} + {{#allowableValues}} + {{#enumVars}} + {{^-last}} + {{^multiplatform}} + {{#moshi}} + @Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), + {{/moshi}} + {{#gson}} + @SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), + {{/gson}} + {{#jackson}} + @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), + {{/jackson}} + {{#kotlinx_serialization}} + @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), + {{/kotlinx_serialization}} + {{/multiplatform}} + {{#multiplatform}} + @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), + {{/multiplatform}} + {{/-last}} + {{/enumVars}} + {{/allowableValues}} + {{/enumUnknownDefaultCase}} + } + + {{/isEnum}} + {{/allParams}} /** * {{summary}} * {{notes}} * Responses:{{#responses}} * - {{code}}: {{{message}}}{{/responses}} - * - {{#allParams}} - * @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}} - {{/allParams}} + *{{>paramJavadoc}} * @return {{^useCoroutines}}[Call]<{{/useCoroutines}}{{#isResponseFile}}[ResponseBody]{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}[{{{.}}}]{{/returnType}}{{^returnType}}[Unit]{{/returnType}}{{/isResponseFile}}{{^useCoroutines}}>{{/useCoroutines}} */ {{#isDeprecated}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/explodedQueryParam.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/explodedQueryParam.mustache new file mode 100644 index 0000000000..3aaa4e67fb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/explodedQueryParam.mustache @@ -0,0 +1 @@ +@Query("{{baseName}}") {{{baseName}}}: {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache index 8878e666c5..70bf5ef3b3 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@Header("{{baseName}}") {{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@Header("{{baseName}}") {{{paramName}}}: {{#isEnum}}{{enumName}}_{{operationId}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache index 4146c154b2..4b48bdcb7d 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache @@ -51,7 +51,7 @@ import retrofit2.converter.moshi.MoshiConverterFactory {{#kotlinx_serialization}} import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory -import {{packageName}}.infrastructure.Serializer.jvmJson +import {{packageName}}.infrastructure.Serializer.kotlinxSerializationJson import okhttp3.MediaType.Companion.toMediaType {{/kotlinx_serialization}} @@ -84,7 +84,7 @@ import okhttp3.MediaType.Companion.toMediaType .addConverterFactory(MoshiConverterFactory.create(serializerBuilder.build())) {{/moshi}} {{#kotlinx_serialization}} - .addConverterFactory(jvmJson.asConverterFactory("application/json".toMediaType())) + .addConverterFactory(kotlinxSerializationJson.asConverterFactory("application/json".toMediaType())) {{/kotlinx_serialization}} .apply { if (converterFactory != null) { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/paramJavadoc.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/paramJavadoc.mustache new file mode 100644 index 0000000000..fe821c41b4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/paramJavadoc.mustache @@ -0,0 +1,5 @@ +{{#allParams}}{{#isDeepObject}} + * @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}}{{/isDeepObject}}{{^isDeepObject}}{{#isExplode}}{{#hasVars}}{{#vars}} + * @param {{{baseName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}}{{/vars}}{{/hasVars}}{{^hasVars}} + * @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}}{{/hasVars}}{{/isExplode}}{{^isExplode}} + * @param {{{paramName}}} {{description}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}{{/required}}{{/isExplode}}{{/isDeepObject}}{{/allParams}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParam.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParam.mustache new file mode 100644 index 0000000000..0fdab94eed --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParam.mustache @@ -0,0 +1 @@ +@Query("{{baseName}}") {{{paramName}}}: {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{#isEnum}}{{enumName}}_{{operationId}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{/collectionFormat}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}_{{operationId}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache index e5dfc02237..ab229cf40e 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@Query("{{baseName}}") {{{paramName}}}: {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}}{{#required}}{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{{defaultValue}}}{{/isNumber}}{{#isNumber}}{{{dataType}}}("{{{defaultValue}}}"){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}{{#isDeepObject}}{{>queryParam}}{{/isDeepObject}}{{^isDeepObject}}{{#isExplode}}{{#hasVars}}{{#vars}}{{>explodedQueryParam}}{{^-last}}, {{/-last}}{{/vars}}{{/hasVars}}{{^hasVars}}{{>queryParam}}{{/hasVars}}{{/isExplode}}{{^isExplode}}{{>queryParam}}{{/isExplode}}{{/isDeepObject}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache index be8b316440..4ee453f296 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache @@ -8,7 +8,6 @@ import {{packageName}}.infrastructure.* import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json import io.ktor.http.ParametersBuilder import kotlinx.serialization.* diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache index 42826ffff6..797279d5d4 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache @@ -8,10 +8,10 @@ plugins { group = "{{groupId}}" version = "{{artifactVersion}}" -val kotlin_version = "1.6.0" -val coroutines_version = "1.5.2" -val serialization_version = "1.3.0" -val ktor_version = "1.6.4" +val kotlin_version = "1.6.10" +val coroutines_version = "1.6.3" +val serialization_version = "1.3.3" +val ktor_version = "2.0.3" repositories { mavenCentral() @@ -30,9 +30,11 @@ kotlin { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") + api("io.ktor:ktor-client-core:$ktor_version") - api("io.ktor:ktor-client-json:$ktor_version") api("io.ktor:ktor-client-serialization:$ktor_version") + api("io.ktor:ktor-client-content-negotiation:$ktor_version") + api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache index 470c4bc292..bc5d9b1950 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache @@ -3,43 +3,31 @@ package {{packageName}}.infrastructure import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.JsonFeature -import io.ktor.client.features.json.JsonSerializer -import io.ktor.client.features.json.serializer.KotlinxSerializer +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.serialization.kotlinx.json.* import io.ktor.client.request.* import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse -import io.ktor.client.utils.EmptyContent import io.ktor.http.* -import io.ktor.http.content.OutgoingContent import io.ktor.http.content.PartData import kotlin.Unit import kotlinx.serialization.json.Json -import {{apiPackage}}.* -import {{modelPackage}}.* import {{packageName}}.auth.* {{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - private val json: Json + private val jsonBlock: Json ) { - private val serializer: JsonSerializer by lazy { - KotlinxSerializer(json).ignoreOutgoingContent() - } - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { { - // Hold a reference to the serializer to avoid freezing the entire ApiClient instance - // when the JsonFeature is configured. - val serializerReference = serializer - it.install(JsonFeature) { serializer = serializerReference } + it.install(ContentNegotiation) { json(jsonBlock) } httpClientConfig?.invoke(it) } } @@ -63,7 +51,11 @@ import {{packageName}}.auth.* {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { const val BASE_URL = "{{{basePath}}}" - val JSON_DEFAULT = Json { ignoreUnknownKeys = true } + val JSON_DEFAULT = Json { + ignoreUnknownKeys = true + prettyPrint = true + isLenient = true + } protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) } @@ -143,18 +135,13 @@ import {{packageName}}.auth.* return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) } - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } - ?: ContentType.Application.Json) - return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) - else request(requestConfig, authNames = authNames) - } + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.request { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -167,7 +154,7 @@ import {{packageName}}.auth.* this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - this.body = body + this.setBody(body) } } @@ -193,14 +180,4 @@ import {{packageName}}.auth.* RequestMethod.POST -> HttpMethod.Post RequestMethod.OPTIONS -> HttpMethod.Options } -} - -// https://github.com/ktorio/ktor/issues/851 -private fun JsonSerializer.ignoreOutgoingContent() = IgnoreOutgoingContentJsonSerializer(this) - -private class IgnoreOutgoingContentJsonSerializer(private val delegate: JsonSerializer) : JsonSerializer by delegate { - override fun write(data: Any): OutgoingContent { - if (data is OutgoingContent) return data - return delegate.write(data) - } -} +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache index 3ade97210c..39825fbe38 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache @@ -14,7 +14,7 @@ private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it private fun Int.toBase64(): Char = BASE64_ALPHABET[this] private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() -internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { writeStringUtf8(dropLastWhile { it == BASE64_PAD }) }.decodeBase64Bytes().readBytes() +internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { dropLastWhile { it == BASE64_PAD } }.decodeBase64Bytes().readBytes() /** * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache index 12d2656746..87a68f3084 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache @@ -1,9 +1,9 @@ package {{packageName}}.infrastructure -import io.ktor.client.call.TypeInfo -import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo {{#nonPublicApi}}internal {{/nonPublicApi}}open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { val status: Int = response.status.value @@ -29,11 +29,11 @@ import io.ktor.http.isSuccess {{#nonPublicApi}}internal {{/nonPublicApi}}class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { @Suppress("UNCHECKED_CAST") override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.receive(type) as T + response.call.body(type) as T @Suppress("UNCHECKED_CAST") override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.receive(type) as V + response.call.body(type) as V } {{#nonPublicApi}}internal {{/nonPublicApi}}class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/licenseInfo.mustache index d344667db1..d11e8934fe 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/licenseInfo.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/licenseInfo.mustache @@ -1,14 +1,9 @@ /** - * {{{appName}}} - * - * {{{appDescription}}} - * - * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} - * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache index a937222e86..1e5a00489a 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache @@ -1,5 +1,5 @@ {{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}} - @Schema({{#example}}example = "{{{.}}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} - @ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}}{{#deprecated}} + @Schema({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @ApiModelProperty({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}}{{#deprecated}} @Deprecated(message = ""){{/deprecated}} @field:JsonProperty("{{{baseName}}}"){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInCamelCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache index 30ff9e9a7c..95e6de71f0 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache @@ -1,4 +1,4 @@ {{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}} - @Schema({{#example}}example = "{{{.}}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} - @ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}} + @Schema({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @ApiModelProperty({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}} @field:JsonProperty("{{{baseName}}}", required = true){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInCamelCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isReadOnly}}?{{/isReadOnly}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{#isReadOnly}}{{^defaultValue}} = null{{/defaultValue}}{{/isReadOnly}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/perl/ApiClient.mustache b/modules/openapi-generator/src/main/resources/perl/ApiClient.mustache index 023891413b..6c82377adf 100644 --- a/modules/openapi-generator/src/main/resources/perl/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/perl/ApiClient.mustache @@ -243,10 +243,12 @@ sub deserialize } elsif (grep /^$class$/, ('DATE_TIME', 'DATE')) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ($class eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($class eq 'object') { return $data; } elsif (grep /^$class$/, ('int', 'float', 'double')) { + return undef unless defined $data; return $data + 0; } elsif ($class eq 'bool') { return !!$data; diff --git a/modules/openapi-generator/src/main/resources/perl/BaseObject.mustache b/modules/openapi-generator/src/main/resources/perl/BaseObject.mustache index 47fe46dcb2..1259d75b9e 100644 --- a/modules/openapi-generator/src/main/resources/perl/BaseObject.mustache +++ b/modules/openapi-generator/src/main/resources/perl/BaseObject.mustache @@ -90,21 +90,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -160,8 +164,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/modules/openapi-generator/src/main/resources/php-symfony/Extension.mustache b/modules/openapi-generator/src/main/resources/php-symfony/Extension.mustache index dffd4cbb33..43914fe672 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/Extension.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/Extension.mustache @@ -37,7 +37,7 @@ class {{bundleExtensionName}} extends Extension public function load(array $configs, ContainerBuilder $container): void { $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); - $loader->load('services.yml'); + $loader->load('services.yaml'); } public function getAlias(): string diff --git a/modules/openapi-generator/src/main/resources/php-symfony/README.mustache b/modules/openapi-generator/src/main/resources/php-symfony/README.mustache index 7cc1cda471..186feb6273 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/README.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/README.mustache @@ -71,7 +71,7 @@ Step 3: Register the routes: ```yaml # app/config/routes.yaml {{bundleAlias}}: - resource: "@{{bundleName}}Bundle/Resources/config/routing.yml" + resource: "@{{bundleName}}Bundle/Resources/config/routing.yaml" ``` Step 4: Implement the API calls: @@ -119,7 +119,7 @@ class {{baseName}}Api implements {{classname}} // An interface is autogenerated Step 5: Tag your API implementation: ```yaml -# config/services.yml +# config/services.yaml services: # ... Acme\MyBundle\Api\{{baseName}}Api: diff --git a/modules/openapi-generator/src/main/resources/php-symfony/api_doc.mustache b/modules/openapi-generator/src/main/resources/php-symfony/api_doc.mustache index 67bedf3ed7..e244934ae9 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/api_doc.mustache @@ -11,7 +11,7 @@ Method | HTTP request | Description {{#operations}} ## Service Declaration ```yaml -# config/services.yml +# config/services.yaml services: # ... Acme\MyBundle\Api\{{baseName}}Api: diff --git a/modules/openapi-generator/src/main/resources/php-symfony/autoload.mustache b/modules/openapi-generator/src/main/resources/php-symfony/autoload.mustache index 28ce32ae50..0171bf4bd7 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/autoload.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/autoload.mustache @@ -6,7 +6,7 @@ * * After registering this autoload function with SPL, the following line * would cause the function to attempt to load the \{{invokerPackage}}\Baz\Qux class - * from /path/to/project/{{srcBasePath}}/Baz/Qux.php: + * from /path/to/project/{{relativeSrcBasePath}}Baz/Qux.php: * * new \{{invokerPackage}}\Baz\Qux; * @@ -20,7 +20,7 @@ spl_autoload_register(function ($class) { $prefix = '{{escapedInvokerPackage}}\\'; // base directory for the namespace prefix - $base_dir = __DIR__ . '/{{srcBasePath}}/'; + $base_dir = __DIR__ . '/{{relativeSrcBasePath}}'; // does the class use the namespace prefix? $len = strlen($prefix); diff --git a/modules/openapi-generator/src/main/resources/php-symfony/composer.mustache b/modules/openapi-generator/src/main/resources/php-symfony/composer.mustache index b337e44bb8..e4ecd72994 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/composer.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/composer.mustache @@ -36,7 +36,7 @@ }, "autoload": { "psr-4": { - "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" + "{{escapedInvokerPackage}}\\" : "{{relativeSrcBasePath}}" } } } diff --git a/modules/openapi-generator/src/main/resources/php-symfony/gitignore b/modules/openapi-generator/src/main/resources/php-symfony/gitignore index 3f90ef253e..6070e9bfda 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/gitignore +++ b/modules/openapi-generator/src/main/resources/php-symfony/gitignore @@ -18,7 +18,7 @@ !var/sessions/.gitkeep # Parameters -/app/config/parameters.yml +/app/config/parameters.yaml /app/config/parameters.ini # Managed by Composer diff --git a/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache b/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache index bd7d559d8a..4a77c9a463 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache @@ -77,10 +77,10 @@ {{/minimum}} {{#maximum}} {{#exclusiveMaximum}} - * @Assert\LessThan({{minimum}}) + * @Assert\LessThan({{maximum}}) {{/exclusiveMaximum}} {{^exclusiveMaximum}} - * @Assert\LessThanOrEqual({{minimum}}) + * @Assert\LessThanOrEqual({{maximum}}) {{/exclusiveMaximum}} {{/maximum}} {{#pattern}} diff --git a/modules/openapi-generator/src/main/resources/php-symfony/testing/AppKernel.mustache b/modules/openapi-generator/src/main/resources/php-symfony/testing/AppKernel.mustache index dfd5e83f1f..acc9505579 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/testing/AppKernel.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/testing/AppKernel.mustache @@ -24,6 +24,6 @@ class AppKernel extends Kernel */ public function registerContainerConfiguration(LoaderInterface $loader) { - $loader->load(__DIR__.'/test_config.yml'); + $loader->load(__DIR__.'/test_config.yaml'); } } diff --git a/modules/openapi-generator/src/main/resources/php-symfony/testing/test_config.yml b/modules/openapi-generator/src/main/resources/php-symfony/testing/test_config.yml index 4c7970ab71..9cd9521cbc 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/testing/test_config.yml +++ b/modules/openapi-generator/src/main/resources/php-symfony/testing/test_config.yml @@ -1,8 +1,8 @@ imports: - - { resource: "../Resources/config/services.yml" } + - { resource: "../Resources/config/services.yaml" } framework: secret: "testsecret" test: ~ router: - resource: "%kernel.project_dir%/Resources/config/routing.yml" + resource: "%kernel.project_dir%/Resources/config/routing.yaml" diff --git a/modules/openapi-generator/src/main/resources/php/Configuration.mustache b/modules/openapi-generator/src/main/resources/php/Configuration.mustache index 8879997659..60c040a134 100644 --- a/modules/openapi-generator/src/main/resources/php/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/php/Configuration.mustache @@ -496,32 +496,31 @@ class Configuration } /** - * Returns URL based on the index and variables - * - * @param int $index index of the host settings - * @param array|null $variables hash of variable and the corresponding value (optional) - * @return string URL based on host settings - */ - public function getHostFromSettings($index, $variables = null) + * Returns URL based on host settings, index and variables + * + * @param array $hostSettings array of host settings, generated from getHostSettings() or equivalent from the API clients + * @param int $hostIndex index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public static function getHostString(array $hostsSettings, $hostIndex, array $variables = null) { if (null === $variables) { $variables = []; } - $hosts = $this->getHostSettings(); - // check array index out of bound - if ($index < 0 || $index >= sizeof($hosts)) { - throw new \InvalidArgumentException("Invalid index $index when selecting the host. Must be less than ".sizeof($hosts)); + if ($hostIndex < 0 || $hostIndex >= count($hostsSettings)) { + throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostsSettings)); } - $host = $hosts[$index]; + $host = $hostsSettings[$hostIndex]; $url = $host["url"]; // go through variable and assign a value foreach ($host["variables"] ?? [] as $name => $variable) { if (array_key_exists($name, $variables)) { // check to see if it's in the variables provided by the user - if (in_array($variables[$name], $variable["enum_values"], true)) { // check to see if the value is in the enum + if (!isset($variable['enum_values']) || in_array($variables[$name], $variable["enum_values"], true)) { // check to see if the value is in the enum $url = str_replace("{".$name."}", $variables[$name], $url); } else { throw new \InvalidArgumentException("The variable `$name` in the host URL has invalid value ".$variables[$name].". Must be ".join(',', $variable["enum_values"])."."); @@ -534,4 +533,16 @@ class Configuration return $url; } + + /** + * Returns URL based on the index and variables + * + * @param int $index index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public function getHostFromSettings($index, $variables = null) + { + return self::getHostString($this->getHostSettings(), $index, $variables); + } } diff --git a/modules/openapi-generator/src/main/resources/php/ObjectSerializer.mustache b/modules/openapi-generator/src/main/resources/php/ObjectSerializer.mustache index 20122a9550..476938159f 100644 --- a/modules/openapi-generator/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/openapi-generator/src/main/resources/php/ObjectSerializer.mustache @@ -180,6 +180,11 @@ class ObjectSerializer } } + # Handle DateTime objects in query + if($openApiType === "\\DateTime" && $value instanceof \DateTime) { + return ["{$paramName}" => $value->format(self::$dateTimeFormat)]; + } + $query = []; $value = (in_array($openApiType, ['object', 'array'], true)) ? (array)$value : $value; diff --git a/modules/openapi-generator/src/main/resources/php/api.mustache b/modules/openapi-generator/src/main/resources/php/api.mustache index cb143c12c0..41c22daee0 100644 --- a/modules/openapi-generator/src/main/resources/php/api.mustache +++ b/modules/openapi-generator/src/main/resources/php/api.mustache @@ -124,9 +124,20 @@ use {{invokerPackage}}\ObjectSerializer; {{/vendorExtensions.x-group-parameters}} {{#servers}} {{#-first}} - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. {{/-first}} * URL: {{{url}}} +{{#variables}} +{{#-first}} + * Variables: +{{/-first}} + * - {{{name}}}: {{{description}}}{{^description}} No description provided{{/description}}{{#enumValues}} +{{#-first}} + * Allowed values: +{{/-first}} + * - {{{.}}}{{/enumValues}} +{{/variables}} {{#-last}} * {{/-last}} @@ -134,6 +145,12 @@ use {{invokerPackage}}\ObjectSerializer; {{#allParams}} * @param {{{dataType}}} ${{paramName}}{{#description}} {{.}}{{/description}}{{^description}} {{paramName}}{{/description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} {{/allParams}} +{{#servers}} +{{#-first}} + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. +{{/-first}} +{{/servers}} * * @throws \{{invokerPackage}}\ApiException on non-2xx response * @throws \InvalidArgumentException @@ -142,9 +159,9 @@ use {{invokerPackage}}\ObjectSerializer; * @deprecated {{/isDeprecated}} */ - public function {{operationId}}({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) + public function {{operationId}}({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}?int $hostIndex = null, array $variables = []{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) { - {{#returnType}}list($response) = {{/returnType}}$this->{{operationId}}WithHttpInfo({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}});{{#returnType}} + {{#returnType}}list($response) = {{/returnType}}$this->{{operationId}}WithHttpInfo({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}$hostIndex, $variables{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}});{{#returnType}} return $response;{{/returnType}} } @@ -165,9 +182,20 @@ use {{invokerPackage}}\ObjectSerializer; {{/vendorExtensions.x-group-parameters}} {{#servers}} {{#-first}} - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. {{/-first}} * URL: {{{url}}} +{{#variables}} +{{#-first}} + * Variables: +{{/-first}} + * - {{{name}}}: {{{description}}}{{^description}} No description provided{{/description}}{{#enumValues}} +{{#-first}} + * Allowed values: +{{/-first}} + * - {{{.}}}{{/enumValues}} +{{/variables}} {{#-last}} * {{/-last}} @@ -175,6 +203,12 @@ use {{invokerPackage}}\ObjectSerializer; {{#allParams}} * @param {{{dataType}}} ${{paramName}}{{#description}} {{.}}{{/description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} {{/allParams}} +{{#servers}} +{{#-first}} + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. +{{/-first}} +{{/servers}} * * @throws \{{invokerPackage}}\ApiException on non-2xx response * @throws \InvalidArgumentException @@ -183,9 +217,9 @@ use {{invokerPackage}}\ObjectSerializer; * @deprecated {{/isDeprecated}} */ - public function {{operationId}}WithHttpInfo({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) + public function {{operationId}}WithHttpInfo({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}?int $hostIndex = null, array $variables = []{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) { - $request = $this->{{operationId}}Request({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}); + $request = $this->{{operationId}}Request({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}$hostIndex, $variables{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}); try { $options = $this->createHttpClientOption(); @@ -227,13 +261,13 @@ use {{invokerPackage}}\ObjectSerializer; switch($statusCode) { {{/-first}} - {{#dataType}} + {{#dataType}}{{^isRange}} {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} if ('{{{dataType}}}' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer } else { $content = (string) $response->getBody(); - if ('{{dataType}}' !== 'string') { + if ('{{{dataType}}}' !== 'string') { $content = json_decode($content); } } @@ -243,7 +277,7 @@ use {{invokerPackage}}\ObjectSerializer; $response->getStatusCode(), $response->getHeaders() ]; - {{/dataType}} + {{/isRange}}{{/dataType}} {{#-last}} } {{/-last}} @@ -273,7 +307,7 @@ use {{invokerPackage}}\ObjectSerializer; } catch (ApiException $e) { switch ($e->getCode()) { {{#responses}} - {{#dataType}} + {{#dataType}}{{^isRange}} {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -282,7 +316,7 @@ use {{invokerPackage}}\ObjectSerializer; ); $e->setResponseObject($data); break; - {{/dataType}} + {{/isRange}}{{/dataType}} {{/responses}} } throw $e; @@ -306,9 +340,20 @@ use {{invokerPackage}}\ObjectSerializer; {{/vendorExtensions.x-group-parameters}} {{#servers}} {{#-first}} - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. {{/-first}} * URL: {{{url}}} +{{#variables}} +{{#-first}} + * Variables: +{{/-first}} + * - {{{name}}}: {{{description}}}{{^description}} No description provided{{/description}}{{#enumValues}} +{{#-first}} + * Allowed values: +{{/-first}} + * - {{{.}}}{{/enumValues}} +{{/variables}} {{#-last}} * {{/-last}} @@ -316,6 +361,12 @@ use {{invokerPackage}}\ObjectSerializer; {{#allParams}} * @param {{{dataType}}} ${{paramName}}{{#description}} {{.}}{{/description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} {{/allParams}} +{{#servers}} +{{#-first}} + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. +{{/-first}} +{{/servers}} * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface @@ -323,9 +374,9 @@ use {{invokerPackage}}\ObjectSerializer; * @deprecated {{/isDeprecated}} */ - public function {{operationId}}Async({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) + public function {{operationId}}Async({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}?int $hostIndex = null, array $variables = []{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) { - return $this->{{operationId}}AsyncWithHttpInfo({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) + return $this->{{operationId}}AsyncWithHttpInfo({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}$hostIndex, $variables{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) ->then( function ($response) { return $response[0]; @@ -350,9 +401,20 @@ use {{invokerPackage}}\ObjectSerializer; {{/vendorExtensions.x-group-parameters}} {{#servers}} {{#-first}} - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. {{/-first}} * URL: {{{url}}} +{{#variables}} +{{#-first}} + * Variables: +{{/-first}} + * - {{{name}}}: {{{description}}}{{^description}} No description provided{{/description}}{{#enumValues}} +{{#-first}} + * Allowed values: +{{/-first}} + * - {{{.}}}{{/enumValues}} +{{/variables}} {{#-last}} * {{/-last}} @@ -360,6 +422,12 @@ use {{invokerPackage}}\ObjectSerializer; {{#allParams}} * @param {{{dataType}}} ${{paramName}}{{#description}} {{.}}{{/description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} {{/allParams}} +{{#servers}} +{{#-first}} + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. +{{/-first}} +{{/servers}} * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface @@ -367,10 +435,10 @@ use {{invokerPackage}}\ObjectSerializer; * @deprecated {{/isDeprecated}} */ - public function {{operationId}}AsyncWithHttpInfo({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) + public function {{operationId}}AsyncWithHttpInfo({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}?int $hostIndex = null, array $variables = []{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) { $returnType = '{{{returnType}}}'; - $request = $this->{{operationId}}Request({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}); + $request = $this->{{operationId}}Request({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}$hostIndex, $variables{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}); return $this->client ->sendAsync($request, $this->createHttpClientOption()) @@ -422,9 +490,20 @@ use {{invokerPackage}}\ObjectSerializer; {{/vendorExtensions.x-group-parameters}} {{#servers}} {{#-first}} - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. {{/-first}} * URL: {{{url}}} +{{#variables}} +{{#-first}} + * Variables: +{{/-first}} + * - {{{name}}}: {{{description}}}{{^description}} No description provided{{/description}}{{#enumValues}} +{{#-first}} + * Allowed values: +{{/-first}} + * - {{{.}}}{{/enumValues}} +{{/variables}} {{#-last}} * {{/-last}} @@ -432,6 +511,12 @@ use {{invokerPackage}}\ObjectSerializer; {{#allParams}} * @param {{{dataType}}} ${{paramName}}{{#description}} {{.}}{{/description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} {{/allParams}} +{{#servers}} +{{#-first}} + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. +{{/-first}} +{{/servers}} * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request @@ -439,16 +524,16 @@ use {{invokerPackage}}\ObjectSerializer; * @deprecated {{/isDeprecated}} */ - public function {{operationId}}Request({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) + public function {{operationId}}Request({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^required}} = {{#defaultValue}}{{{.}}}{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}?int $hostIndex = null, array $variables = []{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associative_array{{/vendorExtensions.x-group-parameters}}) { {{#vendorExtensions.x-group-parameters}} // unbox the parameters from the associative array - {{#allParams}} +{{#allParams}} ${{paramName}} = array_key_exists('{{paramName}}', $associative_array) ? $associative_array['{{paramName}}'] : {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}}; - {{/allParams}} - - {{/vendorExtensions.x-group-parameters}} - {{#allParams}} +{{/allParams}}{{#servers.0}} + $hostIndex = $associative_array['hostIndex']; + $variables = array_key_exists('variables', $associative_array) ? $associative_array['variables'] : []; +{{/servers.0}}{{/vendorExtensions.x-group-parameters}}{{#allParams}} {{#required}} // verify the required parameter '{{paramName}}' is set if (${{paramName}} === null || (is_array(${{paramName}}) && count(${{paramName}}) === 0)) { @@ -653,22 +738,70 @@ use {{invokerPackage}}\ObjectSerializer; ); {{#servers.0}} - $operationHosts = [{{#servers}}"{{{url}}}"{{^-last}}, {{/-last}}{{/servers}}]; - if ($this->hostIndex < 0 || $this->hostIndex >= sizeof($operationHosts)) { - throw new \InvalidArgumentException("Invalid index {$this->hostIndex} when selecting the host. Must be less than ".sizeof($operationHosts)); + # Preserve the original behavior of server indexing. + if ($hostIndex === null) { + $hostIndex = $this->hostIndex; } - $operationHost = $operationHosts[$this->hostIndex]; + $hostSettings = $this->getHostSettingsFor{{operationId}}(); + + if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { + throw new \InvalidArgumentException("Invalid index {$hostIndex} when selecting the host. Must be less than ".count($hostSettings)); + } + $operationHost = Configuration::getHostString($hostSettings, $hostIndex, $variables); + {{/servers.0}} + {{^servers.0}} + $operationHost = $this->config->getHost(); {{/servers.0}} $query = ObjectSerializer::buildQuery($queryParams); return new Request( '{{httpMethod}}', - {{^servers.0}}$this->config->getHost(){{/servers.0}}{{#servers.0}}$operationHost{{/servers.0}} . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); } + {{#servers.0}} + /** + * Returns an array of host settings for Operation {{operationId}} + * + * @return array an array of host settings + */ + protected function getHostSettingsFor{{operationId}}(): array + { + return [ + {{#servers}} + [ + "url" => "{{{url}}}", + "description" => "{{{description}}}{{^description}}No description provided{{/description}}", + {{#variables}} + {{#-first}} + "variables" => [ + {{/-first}} + "{{{name}}}" => [ + "description" => "{{{description}}}{{^description}}No description provided{{/description}}", + "default_value" => "{{{defaultValue}}}", + {{#enumValues}} + {{#-first}} + "enum_values" => [ + {{/-first}} + "{{{.}}}", + {{#-last}} + ] + {{/-last}} + {{/enumValues}} + ]{{^-last}},{{/-last}} + {{#-last}} + ] + {{/-last}} + {{/variables}} + ]{{^-last}},{{/-last}} + {{/servers}} + ]; + } + + {{/servers.0}} {{/operation}} /** * Create http client option diff --git a/modules/openapi-generator/src/main/resources/php/api_doc.mustache b/modules/openapi-generator/src/main/resources/php/api_doc.mustache index 7c8460fe48..db04fa56ce 100644 --- a/modules/openapi-generator/src/main/resources/php/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/php/api_doc.mustache @@ -2,11 +2,11 @@ {{.}}{{/description}} -All URIs are relative to {{basePath}}. +All URIs are relative to {{basePath}}, except if the operation defines another base path. -Method | HTTP request | Description -------------- | ------------- | ------------- -{{#operations}}{{#operation}}[**{{operationId}}()**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +{{#operations}}{{#operation}}| [**{{operationId}}()**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} | {{/operation}}{{/operations}}{{#operations}}{{#operation}} ## `{{{operationId}}}()` @@ -14,7 +14,21 @@ Method | HTTP request | Description ```php {{{operationId}}}({{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}: {{{.}}}{{/returnType}} ``` - +{{#servers}} +{{#-first}} +### URI(s): +{{/-first}} +- {{{url}}} {{#description}}{{.}}{{/description}}{{#variables}} +{{#-first}} + - Variables: +{{/-first}} + - {{{name}}}: {{{description}}}{{^description}} No description provided{{/description}}{{#enumValues}} +{{#-first}} + - Allowed values: +{{/-first}} + - {{{.}}}{{/enumValues}}{{#defaultValue}} + - Default value: {{{.}}} +{{/defaultValue}}{{/variables}}{{/servers}} {{{summary}}}{{#notes}} {{{.}}}{{/notes}} @@ -34,15 +48,25 @@ $apiInstance = new {{invokerPackage}}\Api\{{classname}}( ); {{^vendorExtensions.x-group-parameters}} {{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}}{{#description}} | {{{.}}}{{/description}} +{{/allParams}}{{#servers}}{{#-first}} +$hostIndex = 0; +$variables = [{{#variables}} + '{{{name}}}' => '{{{default}}}{{^default}}YOUR_VALUE{{/default}}',{{/variables}} +]; +{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}} +$associative_array = [ +{{#allParams}} '{{paramName}}' => {{{example}}}, // {{{dataType}}}{{#description}} | {{{.}}}{{/description}} {{/allParams}} -{{/vendorExtensions.x-group-parameters}} -{{#vendorExtensions.x-group-parameters}} -{{#allParams}}$associate_array['{{paramName}}'] = {{{example}}}; // {{{dataType}}}{{#description}} | {{{.}}}{{/description}} -{{/allParams}} +{{#servers}}{{#-first}} + 'hostIndex' => 0, + $variables = [{{#variables}} + '{{{name}}}' => '{{{default}}}{{^default}}YOUR_VALUE{{/default}}',{{/variables}} + ], +{{/-first}}{{/servers}}]; {{/vendorExtensions.x-group-parameters}} try { - {{#returnType}}$result = {{/returnType}}$apiInstance->{{{operationId}}}({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associate_array{{/vendorExtensions.x-group-parameters}});{{#returnType}} + {{#returnType}}$result = {{/returnType}}$apiInstance->{{{operationId}}}({{^vendorExtensions.x-group-parameters}}{{#allParams}}${{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#servers}}{{#-first}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}$hostIndex, $variables{{/-first}}{{/servers}}{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}$associate_array{{/vendorExtensions.x-group-parameters}});{{#returnType}} print_r($result);{{/returnType}} } catch (Exception $e) { echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), PHP_EOL; @@ -52,13 +76,15 @@ try { ### Parameters {{#vendorExtensions.x-group-parameters}} -Note: the input parameter is an associative array with the keys listed as the parameter name below. +Note: the input parameter is an associative array with the keys listed as the parameter names below. {{/vendorExtensions.x-group-parameters}} -{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}Name | Type | Description | Notes -------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{{dataType}}}**](../Model/{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}} -{{/allParams}} +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- |{{/-last}}{{/allParams}} +{{#allParams}}| **{{paramName}}** | {{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{{dataType}}}**](../Model/{{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}} | +{{/allParams}}{{#servers}}{{#-first}}| hostIndex | null|int | Host index. Defaults to null. If null, then the library will use $this->hostIndex instead | [optional] | +| variables | array | Associative array of variables to pass to the host. Defaults to empty array. | [optional] |{{/-first}} +{{/servers}} ### Return type diff --git a/modules/openapi-generator/src/main/resources/php/model_generic.mustache b/modules/openapi-generator/src/main/resources/php/model_generic.mustache index f09167eaa8..97bb1d9320 100644 --- a/modules/openapi-generator/src/main/resources/php/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/php/model_generic.mustache @@ -88,6 +88,16 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}}{{/parentSchema}}{{^par return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/modules/openapi-generator/src/main/resources/python-aiohttp/requirements.mustache b/modules/openapi-generator/src/main/resources/python-aiohttp/requirements.mustache index b828c50f4a..e2ef30b1d4 100644 --- a/modules/openapi-generator/src/main/resources/python-aiohttp/requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-aiohttp/requirements.mustache @@ -5,8 +5,8 @@ connexion[aiohttp,swagger-ui] <= 2.3.0; python_version=="3.5" or python_version= # we must peg werkzeug versions below to fix connexion # https://github.com/zalando/connexion/pull/1044 werkzeug == 0.16.1; python_version=="3.5" or python_version=="3.4" -swagger-ui-bundle == 0.0.6 -aiohttp_jinja2 == 1.2.0 +swagger-ui-bundle == 0.0.9 +aiohttp_jinja2 == 1.5.0 {{#featureCORS}} aiohttp_cors >= 0.7.0 {{/featureCORS}} diff --git a/modules/openapi-generator/src/main/resources/python-aiohttp/setup.mustache b/modules/openapi-generator/src/main/resources/python-aiohttp/setup.mustache index 364384593d..706eab4f50 100644 --- a/modules/openapi-generator/src/main/resources/python-aiohttp/setup.mustache +++ b/modules/openapi-generator/src/main/resources/python-aiohttp/setup.mustache @@ -14,9 +14,9 @@ VERSION = "{{packageVersion}}" # http://pypi.python.org/pypi/setuptools REQUIRES = [ - "connexion==2.6.0", - "swagger-ui-bundle==0.0.6", - "aiohttp_jinja2==1.2.0", + "connexion==2.14.1", + "swagger-ui-bundle==0.0.9", + "aiohttp_jinja2==1.5.0", ] setup( diff --git a/modules/openapi-generator/src/main/resources/python-aiohttp/test-requirements.mustache b/modules/openapi-generator/src/main/resources/python-aiohttp/test-requirements.mustache index 16ba4a4811..a408e178b3 100644 --- a/modules/openapi-generator/src/main/resources/python-aiohttp/test-requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-aiohttp/test-requirements.mustache @@ -6,8 +6,8 @@ py>=1.4.31 randomize>=0.13 {{/useNose}} {{^useNose}} -pytest~=4.6.7 # needed for python 2.7+3.4 +pytest~=7.1.0 pytest-cov>=2.8.1 -pytest-randomly==1.2.3 # needed for python 2.7+3.4 +pytest-randomly>=1.2.3 pytest-aiohttp>=0.3.0 {{/useNose}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-blueplanet/app/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/python-blueplanet/app/Dockerfile.mustache index d96f8f2cc3..f93e045260 100644 --- a/modules/openapi-generator/src/main/resources/python-blueplanet/app/Dockerfile.mustache +++ b/modules/openapi-generator/src/main/resources/python-blueplanet/app/Dockerfile.mustache @@ -1,9 +1,4 @@ -{{#supportPython2}} -FROM python:2-alpine -{{/supportPython2}} -{{^supportPython2}} FROM python:3-alpine -{{/supportPython2}} ARG GLTOKEN @@ -19,12 +14,7 @@ WORKDIR /bp2/src COPY requirements.txt /bp2/src -{{#supportPython2}} -RUN pip install --extra-index-url https://GLTOKEN:$GLTOKEN@pypi.blueplanet.com/simple --no-cache-dir -r requirements.txt -{{/supportPython2}} -{{^supportPython2}} RUN pip3 install --extra-index-url https://GLTOKEN:$GLTOKEN@pypi.blueplanet.com/simple --no-cache-dir -r requirements.txt -{{/supportPython2}} COPY . /bp2/src @@ -33,11 +23,6 @@ ENV SBIS=bpocore \ EXPOSE {{serverPort}} -{{#supportPython2}} -ENTRYPOINT ["python"] -{{/supportPython2}} -{{^supportPython2}} ENTRYPOINT ["python3"] -{{/supportPython2}} CMD ["-B", "-m", "{{packageName}}"] diff --git a/modules/openapi-generator/src/main/resources/python-blueplanet/app/README.mustache b/modules/openapi-generator/src/main/resources/python-blueplanet/app/README.mustache index b73b9e311b..2c62f0f01a 100644 --- a/modules/openapi-generator/src/main/resources/python-blueplanet/app/README.mustache +++ b/modules/openapi-generator/src/main/resources/python-blueplanet/app/README.mustache @@ -8,25 +8,14 @@ is an example of building a swagger-enabled Flask server. This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. ## Requirements -{{#supportPython2}} -Python 2.7+ -{{/supportPython2}} -{{^supportPython2}} Python 3.5.2+ -{{/supportPython2}} ## Usage To run the server, please execute the following from the root directory: ``` -{{#supportPython2}} -pip install -r requirements.txt -python -m {{packageName}} -{{/supportPython2}} -{{^supportPython2}} pip3 install -r requirements.txt python3 -m {{packageName}} -{{/supportPython2}} ``` and open your browser to here: diff --git a/modules/openapi-generator/src/main/resources/python-blueplanet/app/requirements.mustache b/modules/openapi-generator/src/main/resources/python-blueplanet/app/requirements.mustache index 275787f38c..5989d62ff7 100644 --- a/modules/openapi-generator/src/main/resources/python-blueplanet/app/requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-blueplanet/app/requirements.mustache @@ -1,8 +1,5 @@ connexion == 1.1.15 python_dateutil == 2.6.0 -{{#supportPython2}} -typing == 3.5.2.2 -{{/supportPython2}} setuptools >= 21.0.0 bp2hookutil==3.3.0 plansdk diff --git a/modules/openapi-generator/src/main/resources/python-blueplanet/app/tox.mustache b/modules/openapi-generator/src/main/resources/python-blueplanet/app/tox.mustache index d774cfd8db..9391d6aafa 100644 --- a/modules/openapi-generator/src/main/resources/python-blueplanet/app/tox.mustache +++ b/modules/openapi-generator/src/main/resources/python-blueplanet/app/tox.mustache @@ -1,5 +1,5 @@ [tox] -envlist = {{#supportPython2}}py27, {{/supportPython2}}py35 +envlist = py35 [testenv] deps=-r{toxinidir}/requirements.txt diff --git a/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/__main__.mustache b/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/__main__.mustache index ab6835dac8..f558123c30 100644 --- a/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/__main__.mustache +++ b/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/__main__.mustache @@ -1,9 +1,4 @@ -{{#supportPython2}} -#!/usr/bin/env python -{{/supportPython2}} -{{^supportPython2}} #!/usr/bin/env python3 -{{/supportPython2}} import connexion {{#featureCORS}} diff --git a/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/models/base_model_.mustache b/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/models/base_model_.mustache index 54517a06d5..888fa98964 100644 --- a/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/models/base_model_.mustache +++ b/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/models/base_model_.mustache @@ -1,15 +1,11 @@ import pprint import six -{{^supportPython2}} import typing -{{/supportPython2}} from {{packageName}} import util -{{^supportPython2}} T = typing.TypeVar('T') -{{/supportPython2}} class Model(object): @@ -22,7 +18,7 @@ class Model(object): attribute_map = {} @classmethod - def from_dict(cls{{^supportPython2}}: typing.Type[T]{{/supportPython2}}, dikt){{^supportPython2}} -> T{{/supportPython2}}: + def from_dict(cls: typing.Type[T], dikt) -> T: """Returns the dict as a model""" return util.deserialize_model(dikt, cls) diff --git a/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/models/model.mustache b/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/models/model.mustache index 587589e600..d9aa9bfd34 100644 --- a/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/models/model.mustache +++ b/modules/openapi-generator/src/main/resources/python-blueplanet/app/{{packageName}}/models/model.mustache @@ -27,7 +27,7 @@ class {{classname}}(Model): {{/-last}} {{/enumVars}}{{/allowableValues}} - def __init__(self{{#vars}}, {{name}}{{^supportPython2}}: {{datatype}}{{/supportPython2}}={{{defaultValue}}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): # noqa: E501 + def __init__(self{{#vars}}, {{name}}: {{datatype}}={{{defaultValue}}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): # noqa: E501 """{{classname}} - a model defined in Swagger {{#vars}} @@ -52,7 +52,7 @@ class {{classname}}(Model): {{/vars}} @classmethod - def from_dict(cls, dikt){{^supportPython2}} -> '{{classname}}'{{/supportPython2}}: + def from_dict(cls, dikt) -> '{{classname}}': """Returns the dict as a model :param dikt: A dict. @@ -64,7 +64,7 @@ class {{classname}}(Model): {{/-first}} @property - def {{name}}(self){{^supportPython2}} -> {{datatype}}{{/supportPython2}}: + def {{name}}(self) -> {{datatype}}: """Gets the {{name}} of this {{classname}}. {{#description}} @@ -77,7 +77,7 @@ class {{classname}}(Model): return self._{{name}} @{{name}}.setter - def {{name}}(self, {{name}}{{^supportPython2}}: {{datatype}}{{/supportPython2}}): + def {{name}}(self, {{name}}: {{datatype}}): """Sets the {{name}} of this {{classname}}. {{#description}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/README.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/README.handlebars deleted file mode 100644 index aee6b66db6..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/README.handlebars +++ /dev/null @@ -1,57 +0,0 @@ -# {{{projectName}}} -{{#if appDescriptionWithNewLines}} -{{{appDescriptionWithNewLines}}} -{{/if}} - -This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: {{appVersion}} -- Package version: {{packageVersion}} -{{#unless hideGenerationTimestamp}} -- Build date: {{generatedDate}} -{{/unless}} -- Build package: {{generatorClass}} -{{#if infoUrl}} -For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) -{{/if}} - -## Requirements. - -Python {{generatorLanguageVersion}} -v3.9 is needed so one can combine classmethod and property decorators to define -object schema properties as classes - -## Installation & Usage -### pip install - -If the python package is hosted on a repository, you can install directly using: - -```sh -pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git -``` -(you may need to run `pip` with root permission: `sudo pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git`) - -Then import the package: -```python -import {{{packageName}}} -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: -```python -import {{{packageName}}} -``` - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -{{> README_common }} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__api.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/__init__api.handlebars deleted file mode 100644 index 1e059f7361..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/__init__api.handlebars +++ /dev/null @@ -1,9 +0,0 @@ -{{#with apiInfo}} -{{#each apis}} -{{#if @first}} -# do not import all apis into this module because that uses a lot of memory and stack frames -# if you need the ability to import all apis from one package, import them with -# from {{packageName}}.apis import {{classname}} -{{/if}} -{{/each}} -{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__api_endpoints.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/__init__api_endpoints.handlebars deleted file mode 100644 index 2bb5d7837b..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/__init__api_endpoints.handlebars +++ /dev/null @@ -1,3 +0,0 @@ -# do not import all endpoints into this module because that uses a lot of memory and stack frames -# if you need the ability to import all endpoints from this module, import them with -# from {{packageName}}.api.{{apiModuleName}} import {{classname}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__apis.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/__init__apis.handlebars deleted file mode 100644 index 16dfd5cd69..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/__init__apis.handlebars +++ /dev/null @@ -1,24 +0,0 @@ -{{#with apiInfo}} -{{#each apis}} -{{#if @first}} -# coding: utf-8 - -# flake8: noqa - -# Import all APIs into this package. -# If you have many APIs here with many many models used in each API this may -# raise a `RecursionError`. -# In order to avoid this, import only the API that you directly need like: -# -# from {{packageName}}.{{apiPackage}}.{{classFilename}} import {{classname}} -# -# or import this package, but before doing it, use: -# -# import sys -# sys.setrecursionlimit(n) - -# Import APIs into API package: -{{/if}} -from {{packageName}}.{{apiPackage}}.{{classFilename}} import {{classname}} -{{/each}} -{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/api.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/api.handlebars deleted file mode 100644 index c6c0b42370..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/api.handlebars +++ /dev/null @@ -1,26 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -from {{packageName}}.api_client import ApiClient -{{#with operations}} -{{#each operation}} -from {{packageName}}.api.{{classFilename}}_endpoints.{{operationId}} import {{operationIdCamelCase}} -{{/each}} -{{/with}} - - -{{#with operations}} -class {{classname}}( -{{#each operation}} - {{operationIdCamelCase}}, -{{/each}} - ApiClient, -): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass -{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/api_doc_schema_type_hint.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/api_doc_schema_type_hint.handlebars deleted file mode 100644 index ffed97b72b..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/api_doc_schema_type_hint.handlebars +++ /dev/null @@ -1,10 +0,0 @@ - -#### {{baseName}} -{{#if complexType}} -Type | Description | Notes -------------- | ------------- | ------------- -[**{{dataType}}**]({{complexType}}.md) | {{#if description}}{{description}}{{/if}} | {{#if isReadOnly}}[readonly] {{/if}} - -{{else}} -{{> schema_doc }} -{{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/api_test.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/api_test.handlebars deleted file mode 100644 index 2f52783c60..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/api_test.handlebars +++ /dev/null @@ -1,34 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import unittest - -import {{packageName}} -from {{packageName}}.{{apiPackage}}.{{classFilename}} import {{classname}} # noqa: E501 - - -class {{#with operations}}Test{{classname}}(unittest.TestCase): - """{{classname}} unit test stubs""" - - def setUp(self): - self.api = {{classname}}() # noqa: E501 - - def tearDown(self): - pass - - {{#each operation}} - def test_{{operationId}}(self): - """Test case for {{{operationId}}} - -{{#if summary}} - {{{summary}}} # noqa: E501 -{{/if}} - """ - pass - - {{/each}} -{{/with}} - -if __name__ == '__main__': - unittest.main() diff --git a/modules/openapi-generator/src/main/resources/python-experimental/endpoint.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/endpoint.handlebars deleted file mode 100644 index cb2c0191b3..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/endpoint.handlebars +++ /dev/null @@ -1,559 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -{{#with operation}} -{{#or headerParams bodyParam produces}} -from urllib3._collections import HTTPHeaderDict -{{/or}} -{{/with}} - -from {{packageName}} import api_client, exceptions -{{> model_templates/imports_schema_types }} -{{> model_templates/imports_schemas }} - -{{#with operation}} -{{#if queryParams}} -# query params -{{#each queryParams}} -{{#with schema}} -{{> model_templates/schema }} -{{/with}} -{{/each}} -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { -{{#each queryParams}} -{{#if required}} - '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} -{{/if}} -{{/each}} - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { -{{#each queryParams}} -{{#unless required}} - '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} -{{/unless}} -{{/each}} - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -{{#each queryParams}} -{{> endpoint_parameter }} -{{/each}} -{{/if}} -{{#if headerParams}} -# header params -{{#each headerParams}} -{{#with schema}} -{{> model_templates/schema }} -{{/with}} -{{/each}} -RequestRequiredHeaderParams = typing.TypedDict( - 'RequestRequiredHeaderParams', - { -{{#each headerParams}} -{{#if required}} - '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} -{{/if}} -{{/each}} - } -) -RequestOptionalHeaderParams = typing.TypedDict( - 'RequestOptionalHeaderParams', - { -{{#each headerParams}} -{{#unless required}} - '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} -{{/unless}} -{{/each}} - }, - total=False -) - - -class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): - pass - - -{{#each headerParams}} -{{> endpoint_parameter }} -{{/each}} -{{/if}} -{{#if pathParams}} -# path params -{{#each pathParams}} -{{#with schema}} -{{> model_templates/schema }} -{{/with}} -{{/each}} -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { -{{#each pathParams}} -{{#if required}} - '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} -{{/if}} -{{/each}} - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { -{{#each pathParams}} -{{#unless required}} - '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} -{{/unless}} -{{/each}} - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -{{#each pathParams}} -{{> endpoint_parameter }} -{{/each}} -{{/if}} -{{#if cookieParams}} -# cookie params -{{#each cookieParams}} -{{#with schema}} -{{> model_templates/schema }} -{{/with}} -{{/each}} -RequestRequiredCookieParams = typing.TypedDict( - 'RequestRequiredCookieParams', - { -{{#each cookieParams}} -{{#if required}} - '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} -{{/if}} -{{/each}} - } -) -RequestOptionalCookieParams = typing.TypedDict( - 'RequestOptionalCookieParams', - { -{{#each cookieParams}} -{{#unless required}} - '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} -{{/unless}} -{{/each}} - }, - total=False -) - - -class RequestCookieParams(RequestRequiredCookieParams, RequestOptionalCookieParams): - pass - - -{{#each cookieParams}} -{{> endpoint_parameter }} -{{/each}} -{{/if}} -{{#with bodyParam}} -# body param -{{#each content}} -{{#with this.schema}} -{{> model_templates/schema }} -{{/with}} -{{/each}} - - -request_body_{{paramName}} = api_client.RequestBody( - content={ -{{#each content}} - '{{{@key}}}': api_client.MediaType({{#if this.schema}} - schema={{this.schema.baseName}}{{/if}}), -{{/each}} - }, -{{#if required}} - required=True, -{{/if}} -) -{{/with}} -_path = '{{{path}}}' -_method = '{{httpMethod}}' -{{#each authMethods}} -{{#if @first}} -_auth = [ -{{/if}} - '{{name}}', -{{#if @last}} -] -{{/if}} -{{/each}} -{{#each servers}} -{{#if @first}} -_servers = ( -{{/if}} - { - 'url': "{{{url}}}", - 'description': "{{#unless description}}No description provided{{else}}{{{description}}}{{/unless}}", - {{#each variables}} - {{#if @first}} - 'variables': { - {{/if}} - '{{{name}}}': { - 'description': "{{#unless description}}No description provided{{else}}{{{description}}}{{/unless}}", - 'default_value': "{{{defaultValue}}}", - {{#each enumValues}} - {{#if @first}} - 'enum_values': [ - {{/if}} - "{{{.}}}"{{#unless @last}},{{/unless}} - {{#if @last}} - ] - {{/if}} - {{/each}} - }{{#unless @last}},{{/unless}} - {{#if @last}} - } - {{/if}} - {{/each}} - }, -{{#if @last}} -) -{{/if}} -{{/each}} -{{#each responses}} -{{#each responseHeaders}} -{{#with schema}} -{{> model_templates/schema }} -{{/with}} -{{paramName}}_parameter = api_client.HeaderParameter( - name="{{baseName}}", -{{#if style}} - style=api_client.ParameterStyle.{{style}}, -{{/if}} -{{#if schema}} -{{#with schema}} - schema={{baseName}}, -{{/with}} -{{/if}} -{{#if required}} - required=True, -{{/if}} -{{#if isExplode}} - explode=True, -{{/if}} -) -{{/each}} -{{#each content}} -{{#with this.schema}} -{{> model_templates/schema }} -{{/with}} -{{/each}} -{{#if responseHeaders}} -ResponseHeadersFor{{code}} = typing.TypedDict( - 'ResponseHeadersFor{{code}}', - { -{{#each responseHeaders}} - '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} -{{/each}} - } -) -{{/if}} - - -@dataclass -{{#if isDefault}} -class ApiResponseForDefault(api_client.ApiResponse): -{{else}} -class ApiResponseFor{{code}}(api_client.ApiResponse): -{{/if}} - response: urllib3.HTTPResponse -{{#and responseHeaders content}} - body: typing.Union[ -{{#each content}} -{{#if this.schema}} - {{this.schema.baseName}}, -{{else}} - Unset, -{{/if}} -{{/each}} - ] - headers: ResponseHeadersFor{{code}} -{{else}} -{{#or responseHeaders content}} -{{#if responseHeaders}} - headers: ResponseHeadersFor{{code}} - body: Unset = unset -{{else}} - body: typing.Union[ -{{#each content}} -{{#if this.schema}} - {{this.schema.baseName}}, -{{else}} - Unset, -{{/if}} -{{/each}} - ] - headers: Unset = unset -{{/if}} -{{/or}} -{{/and}} -{{#unless responseHeaders}} -{{#unless content}} - body: Unset = unset - headers: Unset = unset -{{/unless}} -{{/unless}} - - -{{#if isDefault}} -_response_for_default = api_client.OpenApiResponse( - response_cls=ApiResponseForDefault, -{{else}} -_response_for_{{code}} = api_client.OpenApiResponse( - response_cls=ApiResponseFor{{code}}, -{{/if}} -{{#each content}} -{{#if @first}} - content={ -{{/if}} - '{{{@key}}}': api_client.MediaType({{#if this.schema}} - schema={{this.schema.baseName}}{{/if}}), -{{#if @last}} - }, -{{/if}} -{{/each}} -{{#if responseHeaders}} - headers=[ -{{#each responseHeaders}} - {{paramName}}_parameter, -{{/each}} - ] -{{/if}} -) -{{/each}} -_status_code_to_response = { -{{#each responses}} -{{#if isDefault}} - 'default': _response_for_default, -{{else}} - '{{code}}': _response_for_{{code}}, -{{/if}} -{{/each}} -} -{{#each produces}} -{{#if @first}} -_all_accept_content_types = ( -{{/if}} - '{{{this.mediaType}}}', -{{#if @last}} -) -{{/if}} -{{/each}} - - -class {{operationIdCamelCase}}(api_client.Api): - - def {{operationId}}( - self: api_client.Api, - {{#if bodyParam}} - {{#with bodyParam}} - {{baseName}}: typing.Union[{{#each content}}{{#unless @first}}, {{/unless}}{{this.schema.baseName}}{{/each}}{{#unless required}}, Unset] = unset{{else}}]{{/unless}}, - {{/with}} - {{/if}} - {{#if queryParams}} - query_params: RequestQueryParams = frozendict(), - {{/if}} - {{#if headerParams}} - header_params: RequestHeaderParams = frozendict(), - {{/if}} - {{#if pathParams}} - path_params: RequestPathParams = frozendict(), - {{/if}} - {{#if cookieParams}} - cookie_params: RequestCookieParams = frozendict(), - {{/if}} - {{#with bodyParam}} - {{#each content}} - {{#if @first}} - content_type: str = '{{{@key}}}', - {{/if}} - {{/each}} - {{/with}} - {{#if produces}} - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - {{/if}} - {{#if servers}} - host_index: typing.Optional[int] = None, - {{/if}} - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - {{#each responses}} - {{#if isDefault}} - ApiResponseForDefault, - {{else}} - {{#if is2xx}} - ApiResponseFor{{code}}, - {{/if}} - {{/if}} - {{/each}} - api_client.ApiResponseWithoutDeserialization - ]: - """ - {{#if summary}} - {{summary}} - {{/if}} - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - {{#if queryParams}} - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - {{/if}} - {{#if headerParams}} - self._verify_typed_dict_inputs(RequestHeaderParams, header_params) - {{/if}} - {{#if pathParams}} - self._verify_typed_dict_inputs(RequestPathParams, path_params) - {{/if}} - {{#if cookieParams}} - self._verify_typed_dict_inputs(RequestCookieParams, cookie_params) - {{/if}} - used_path = _path - {{#if pathParams}} - - _path_params = {} - for parameter in ( - {{#each pathParams}} - request_path_{{paramName}}, - {{/each}} - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - {{/if}} - {{#if queryParams}} - - prefix_separator_iterator = None - for parameter in ( - {{#each queryParams}} - request_query_{{paramName}}, - {{/each}} - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - {{/if}} - {{#or headerParams bodyParam produces}} - - _headers = HTTPHeaderDict() - {{else}} - {{/or}} - {{#if headerParams}} - for parameter in ( - {{#each headerParams}} - request_header_{{paramName}}, - {{/each}} - ): - parameter_data = header_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _headers.extend(serialized_data) - {{/if}} - # TODO add cookie handling - {{#if produces}} - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - {{/if}} - {{#with bodyParam}} - - {{#if required}} - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - {{/if}} - _fields = None - _body = None - {{#if required}} - {{> endpoint_body_serialization }} - {{else}} - if body is not unset: - {{> endpoint_body_serialization }} - {{/if}} - {{/with}} - {{#if servers}} - - host = self.get_host('{{operationId}}', _servers, host_index) - {{/if}} - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - {{#or headerParams bodyParam produces}} - headers=_headers, - {{/or}} - {{#if bodyParam}} - fields=_fields, - body=_body, - {{/if}} - {{#if hasAuthMethods}} - auth_settings=_auth, - {{/if}} - {{#if servers}} - host=host, - {{/if}} - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - {{#if hasDefaultResponse}} - default_response = _status_code_to_response.get('default') - if default_response: - api_response = default_response.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - {{else}} - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - {{/if}} - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response -{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/endpoint_parameter.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/endpoint_parameter.handlebars deleted file mode 100644 index 4b9d815af8..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/endpoint_parameter.handlebars +++ /dev/null @@ -1,17 +0,0 @@ -request_{{#if isQueryParam}}query{{/if}}{{#if isPathParam}}path{{/if}}{{#if isHeaderParam}}header{{/if}}{{#if isCookieParam}}cookie{{/if}}_{{paramName}} = api_client.{{#if isQueryParam}}Query{{/if}}{{#if isPathParam}}Path{{/if}}{{#if isHeaderParam}}Header{{/if}}{{#if isCookieParam}}Cookie{{/if}}Parameter( - name="{{baseName}}", -{{#if style}} - style=api_client.ParameterStyle.{{style}}, -{{/if}} -{{#if schema}} -{{#with schema}} - schema={{baseName}}, -{{/with}} -{{/if}} -{{#if required}} - required=True, -{{/if}} -{{#if isExplode}} - explode=True, -{{/if}} -) diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model.handlebars deleted file mode 100644 index 03f72a86b8..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model.handlebars +++ /dev/null @@ -1,18 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -{{#each models}} -{{#with model}} -{{> model_templates/imports_schema_types }} -{{> model_templates/schema }} -{{> model_templates/imports_schemas }} -{{/with}} -{{/each}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_doc.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_doc.handlebars deleted file mode 100644 index 2c4136a142..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_doc.handlebars +++ /dev/null @@ -1,9 +0,0 @@ -{{#each models}} -{{#with model}} -# {{classname}} -{{> schema_doc }} -{{/with}} -{{/each}} - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/composed_schemas.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/composed_schemas.handlebars deleted file mode 100644 index 8cfeccc6cd..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/composed_schemas.handlebars +++ /dev/null @@ -1,90 +0,0 @@ -@classmethod -@property -@functools.cache -def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading -{{#with composedSchemas}} -{{#each allOf}} -{{#unless complexType}} - {{> model_templates/schema }} -{{/unless}} -{{/each}} -{{#each oneOf}} -{{#unless complexType}} - {{> model_templates/schema }} -{{/unless}} -{{/each}} -{{#each anyOf}} -{{#unless complexType}} - {{> model_templates/schema }} -{{/unless}} -{{/each}} -{{#with not}} -{{#unless complexType}} - {{> model_templates/schema }} -{{/unless}} -{{/with}} -{{/with}} - return { - 'allOf': [ -{{#with composedSchemas}} -{{#each allOf}} -{{#if complexType}} - {{complexType}}, -{{else}} - {{#if nameInSnakeCase}} - {{name}}, - {{else}} - {{baseName}}, - {{/if}} -{{/if}} -{{/each}} - ], - 'oneOf': [ -{{#each oneOf}} -{{#if complexType}} - {{complexType}}, -{{else}} - {{#if nameInSnakeCase}} - {{name}}, - {{else}} - {{baseName}}, - {{/if}} -{{/if}} -{{/each}} - ], - 'anyOf': [ -{{#each anyOf}} -{{#if complexType}} - {{complexType}}, -{{else}} - {{#if nameInSnakeCase}} - {{name}}, - {{else}} - {{baseName}}, - {{/if}} -{{/if}} -{{/each}} - ], - 'not': -{{#with not}} -{{#if complexType}} - {{complexType}} -{{else}} - {{#if nameInSnakeCase}} - {{name}} - {{else}} - {{baseName}} - {{/if}} -{{/if}} -{{else}} - None -{{/with}} -{{/with}} - } diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/dict_partial.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/dict_partial.handlebars deleted file mode 100644 index 15338b38f1..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/dict_partial.handlebars +++ /dev/null @@ -1,54 +0,0 @@ -{{#if getHasRequired}} - _required_property_names = set(( - {{#each requiredVars}} - '{{baseName}}', - {{/each}} - )) -{{/if}} -{{#each vars}} -{{#if complexType}} - - @classmethod - @property - def {{baseName}}(cls) -> typing.Type['{{complexType}}']: - return {{complexType}} -{{else}} - {{> model_templates/schema }} -{{/if}} -{{/each}} -{{#if getHasDiscriminatorWithNonEmptyMapping}} -{{#with discriminator}} -{{#each mappedModels}} -{{#if @first}} - - @classmethod - @property - def _discriminator(cls): - return { - '{{{propertyBaseName}}}': { -{{/if}} - '{{mappingName}}': {{{modelName}}}, -{{#if @last}} - } - } -{{/if}} -{{/each}} -{{/with}} -{{/if}} -{{#with additionalProperties}} -{{#if complexType}} - - @classmethod - @property - def _additional_properties(cls) -> typing.Type['{{complexType}}']: - return {{complexType}} -{{/if}} -{{#unless complexType}} -{{#unless isAnyType}} - {{> model_templates/schema }} -{{/unless}} -{{/unless}} -{{/with}} -{{#unless additionalProperties}} - _additional_properties = None -{{/unless}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/enum_value_to_name.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/enum_value_to_name.handlebars deleted file mode 100644 index 511dc75597..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/enum_value_to_name.handlebars +++ /dev/null @@ -1,12 +0,0 @@ -_SchemaEnumMaker( - enum_value_to_name={ -{{#if isNull}} - NoneClass.NONE: "NONE", -{{/if}} -{{#with allowableValues}} -{{#each enumVars}} - {{{value}}}: "{{name}}", -{{/each}} -{{/with}} - } -), diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/enums.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/enums.handlebars deleted file mode 100644 index 68dd1f03db..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/enums.handlebars +++ /dev/null @@ -1,16 +0,0 @@ -{{#if isNull}} - -@classmethod -@property -def NONE(cls): - return cls(None) -{{/if}} -{{#with allowableValues}} -{{#each enumVars}} - -@classmethod -@property -def {{name}}(cls): - return cls({{{value}}}) -{{/each}} -{{/with}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/imports_schema_types.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/imports_schema_types.handlebars deleted file mode 100644 index 48b47a7e34..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/imports_schema_types.handlebars +++ /dev/null @@ -1,50 +0,0 @@ -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from {{packageName}}.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/new.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/new.handlebars deleted file mode 100644 index a05493c42e..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/new.handlebars +++ /dev/null @@ -1,53 +0,0 @@ -def __new__( - cls, - *args: typing.Union[{{#if isAnyType}}dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes{{/if}}{{#if isUnboundedInteger}}int, {{/if}}{{#if isNumber}}float, {{/if}}{{#if isBoolean}}bool, {{/if}}{{#if isArray}}list, tuple, {{/if}}{{#if isMap}}dict, frozendict, {{/if}}{{#if isString}}str, {{/if}}{{#if isNull}}None, {{/if}}], -{{#unless isNull}} -{{#if getHasRequired}} -{{#each requiredVars}} -{{#unless nameInSnakeCase}} - {{baseName}}: {{baseName}}, -{{/unless}} -{{/each}} -{{/if}} -{{/unless}} -{{#each vars}} -{{#unless nameInSnakeCase}} -{{#unless getRequired}} -{{#unless complexType}} - {{baseName}}: typing.Union[{{baseName}}, Unset] = unset, -{{/unless}} -{{#if complexType}} - {{baseName}}: typing.Union['{{complexType}}', Unset] = unset, -{{/if}} -{{/unless}} -{{/unless}} -{{/each}} - _configuration: typing.Optional[Configuration] = None, -{{#with additionalProperties}} - **kwargs: typing.Type[Schema], -{{/with}} -) -> '{{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}}': - return super().__new__( - cls, - *args, -{{#unless isNull}} -{{#if getHasRequired}} -{{#each requiredVars}} -{{#unless nameInSnakeCase}} - {{baseName}}={{baseName}}, -{{/unless}} -{{/each}} -{{/if}} -{{/unless}} -{{#each vars}} -{{#unless getRequired}} -{{#unless nameInSnakeCase}} - {{baseName}}={{baseName}}, -{{/unless}} -{{/unless}} -{{/each}} - _configuration=_configuration, -{{#with additionalProperties}} - **kwargs, -{{/with}} - ) diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema.handlebars deleted file mode 100644 index 8b57741841..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema.handlebars +++ /dev/null @@ -1,46 +0,0 @@ -{{#if composedSchemas}} -{{> model_templates/schema_composed_or_anytype }} -{{/if}} -{{#unless composedSchemas}} - {{#if getHasMultipleTypes}} -{{> model_templates/schema_composed_or_anytype }} - {{else}} - {{#or isMap isArray isAnyType}} - {{#if isMap}} - {{#or hasVars hasValidation hasRequiredVars getHasDiscriminatorWithNonEmptyMapping}} -{{> model_templates/schema_dict }} - {{else}} - {{#if additionalPropertiesIsAnyType}} -{{> model_templates/var_equals_cls }} - {{else}} -{{> model_templates/schema_dict }} - {{/if}} - {{/or}} - {{/if}} - {{#if isArray}} - {{#or hasItems hasValidation}} -{{> model_templates/schema_list }} - {{else}} -{{> model_templates/var_equals_cls }} - {{/or}} - {{/if}} - {{#if isAnyType}} - {{#or isEnum hasVars hasValidation hasRequiredVars getHasDiscriminatorWithNonEmptyMapping items}} -{{> model_templates/schema_composed_or_anytype }} - {{else}} -{{> model_templates/var_equals_cls }} - {{/or}} - {{/if}} - {{else}} - {{#or isEnum hasValidation}} -{{> model_templates/schema_simple }} - {{else}} -{{> model_templates/var_equals_cls }} - {{/or}} - {{/or}} - {{#if nameInSnakeCase}} -locals()["{{{baseName}}}"] = {{name}} -del locals()['{{name}}'] - {{/if}} - {{/if}} -{{/unless}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_composed_or_anytype.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_composed_or_anytype.handlebars deleted file mode 100644 index 3ea4a7c841..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_composed_or_anytype.handlebars +++ /dev/null @@ -1,48 +0,0 @@ - - -class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}}( -{{#if hasValidation}} - {{> model_templates/validations }} -{{/if}} -{{#if getIsAnyType}} - {{#if composedSchemas}} - ComposedSchema - {{else}} - AnyTypeSchema - {{/if}} -{{else}} - {{#if getHasMultipleTypes}} - _SchemaTypeChecker(typing.Union[{{#if isArray}}tuple, {{/if}}{{#if isMap}}frozendict, {{/if}}{{#if isNull}}NoneClass, {{/if}}{{#if isString}}str, {{/if}}{{#if isByteArray}}str, {{/if}}{{#if isUnboundedInteger}}decimal.Decimal, {{/if}}{{#if isShort}}decimal.Decimal, {{/if}}{{#if isLong}}decimal.Decimal, {{/if}}{{#if isFloat}}decimal.Decimal, {{/if}}{{#if isDouble}}decimal.Decimal, {{/if}}{{#if isNumber}}decimal.Decimal, {{/if}}{{#if isDate}}str, {{/if}}{{#if isDateTime}}str, {{/if}}{{#if isDecimal}}str, {{/if}}{{#if isBoolean}}BoolClass, {{/if}}]), - {{/if}} - {{#if composedSchemas}} - ComposedBase, - {{/if}} - {{#if isEnum}} - {{> model_templates/enum_value_to_name }} - {{/if}} - {{> model_templates/xbase_schema }} -{{/if}} -): -{{#if this.classname}} - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. -{{#if description}} - - {{{unescapedDescription}}} -{{/if}} - """ -{{/if}} -{{#or isMap isAnyType}} -{{> model_templates/dict_partial }} -{{/or}} -{{#if composedSchemas}} - - {{> model_templates/composed_schemas }} -{{/if}} -{{#if isEnum}} - {{> model_templates/enums }} -{{/if}} - - {{> model_templates/new }} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_dict.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_dict.handlebars deleted file mode 100644 index c17e0f5764..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_dict.handlebars +++ /dev/null @@ -1,23 +0,0 @@ - - -class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}}( -{{#if hasValidation}} - {{> model_templates/validations }} -{{/if}} - DictSchema -): -{{#if this.classname}} - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. -{{#if description}} - - {{{unescapedDescription}}} -{{/if}} - """ -{{/if}} -{{> model_templates/dict_partial }} - - - {{> model_templates/new }} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_list.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_list.handlebars deleted file mode 100644 index 542b486ab4..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_list.handlebars +++ /dev/null @@ -1,30 +0,0 @@ - - -class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}}( -{{#if hasValidation}} - {{> model_templates/validations }} -{{/if}} - ListSchema -): -{{#if this.classname}} - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. -{{#if description}} - - {{{unescapedDescription}}} -{{/if}} - """ -{{/if}} -{{#with items}} -{{#if complexType}} - - @classmethod - @property - def _items(cls) -> typing.Type['{{complexType}}']: - return {{complexType}} -{{else}} - {{> model_templates/schema }} -{{/if}} -{{/with}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_simple.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_simple.handlebars deleted file mode 100644 index ea12a00ff4..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_simple.handlebars +++ /dev/null @@ -1,27 +0,0 @@ - - -class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}}( -{{#if hasValidation}} - {{> model_templates/validations }} -{{/if}} -{{#if isEnum}} - {{> model_templates/enum_value_to_name }} -{{/if}} - {{> model_templates/xbase_schema }} -): -{{#if this.classname}} - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. -{{#if description}} - - {{{unescapedDescription}}} -{{/if}} - """ -{{/if}} -{{#if isEnum}} - {{> model_templates/enums }} -{{else}} - pass -{{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/validations.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/validations.handlebars deleted file mode 100644 index efb463b0a7..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/validations.handlebars +++ /dev/null @@ -1,50 +0,0 @@ -_SchemaValidator( -{{#if getUniqueItems}} - unique_items=True, -{{/if}} -{{#if maxLength}} - max_length={{maxLength}}, -{{/if}} -{{#if minLength}} - min_length={{minLength}}, -{{/if}} -{{#if maxItems}} - max_items={{maxItems}}, -{{/if}} -{{#if minItems}} - min_items={{minItems}}, -{{/if}} -{{#neq maxProperties null }} - max_properties={{maxProperties}}, -{{/neq}} -{{#if minProperties}} - min_properties={{minProperties}}, -{{/if}} -{{#if maximum}} - {{#if exclusiveMaximum}}exclusive_maximum{{/if}}inclusive_maximum{{#unless exclusiveMaximum}}{{/unless}}={{maximum}}, -{{/if}} -{{#if minimum}} - {{#if exclusiveMinimum}}exclusive_minimum{{/if}}inclusive_minimum{{#unless exclusiveMinimum}}{{/unless}}={{minimum}}, -{{/if}} -{{#if pattern}} - regex=[{ -{{#if vendorExtensions.x-regex}} - 'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501 -{{else}} - 'pattern': r'{{{pattern}}}', # noqa: E501 -{{/if}} -{{#each vendorExtensions.x-modifiers}} -{{#if @first}} - 'flags': ( -{{/if}} - {{#unless @first}}| {{/unless}}re.{{.}} -{{#if @last}} - ) -{{/if}} -{{/each}} - }], -{{/if}} -{{#if multipleOf}} - multiple_of={{multipleOf}}, -{{/if}} -), diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/var_equals_cls.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/var_equals_cls.handlebars deleted file mode 100644 index b25c727564..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/var_equals_cls.handlebars +++ /dev/null @@ -1 +0,0 @@ -{{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}} = {{#if complexType}}{{complexType}}{{else}}{{#if isNullable}}Nullable{{/if}}{{#if getIsNull}}None{{/if}}{{#if isAnyType}}AnyType{{/if}}{{#if isMap}}Dict{{/if}}{{#if isArray}}List{{/if}}{{#if isString}}Str{{/if}}{{#if isByteArray}}Str{{/if}}{{#if getIsUuid}}UUID{{/if}}{{#if isDate}}Date{{/if}}{{#if isDateTime}}DateTime{{/if}}{{#if isDecimal}}Decimal{{/if}}{{#if isUnboundedInteger}}Int{{/if}}{{#if isShort}}Int32{{/if}}{{#if isLong}}Int64{{/if}}{{#if isFloat}}Float32{{/if}}{{#if isDouble}}Float64{{/if}}{{#if isNumber}}Number{{/if}}{{#if isBoolean}}Bool{{/if}}{{#if isBinary}}Binary{{/if}}Schema{{/if}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/xbase_schema.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/xbase_schema.handlebars deleted file mode 100644 index 98271f4346..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/xbase_schema.handlebars +++ /dev/null @@ -1,54 +0,0 @@ -{{#if isArray}} -List{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isMap}} -Dict{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isString}} -Str{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isByteArray}} -Str{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isUnboundedInteger}} -Int{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isNumber}} -Number{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#isShort}} -Int32{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/isShort}} -{{#isLong}} -Int64{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/isLong}} -{{#isFloat}} -Float32{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/isFloat}} -{{#isDouble}} -Float64{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/isDouble}} -{{#if getIsUuid}} -UUID{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isDate}} -Date{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isDateTime}} -DateTime{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isDecimal}} -Decimal{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isBoolean}} -Bool{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isBinary}} -Binary{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if isNull}} -None{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} -{{/if}} -{{#if getHasMultipleTypes}} -Schema -{{/if}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/requirements.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/requirements.handlebars deleted file mode 100644 index c9227e58a1..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/requirements.handlebars +++ /dev/null @@ -1,5 +0,0 @@ -certifi >= 14.05.14 -frozendict >= 2.0.3 -python_dateutil >= 2.5.3 -setuptools >= 21.0.0 -urllib3 >= 1.15.1 diff --git a/modules/openapi-generator/src/main/resources/python-experimental/schema_doc.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/schema_doc.handlebars deleted file mode 100644 index 5fe246825e..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/schema_doc.handlebars +++ /dev/null @@ -1,32 +0,0 @@ - -{{#if description}} -{{&description}} - -{{/if}} -{{#or vars additionalProperties}} -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - {{#each vars}} -**{{baseName}}** | {{#unless complexType}}**{{dataType}}**{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexType}}.md){{/if}} | {{#if description}}{{description}}{{/if}} | {{#unless required}}[optional] {{/unless}}{{#if isReadOnly}}[readonly] {{/if}}{{#if defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/if}} - {{/each}} - {{#with additionalProperties}} -**any string name** | **{{dataType}}** | any string name can be used but the value must be the correct type | [optional] - {{/with}} -{{else}} -Type | Description | Notes -------------- | ------------- | ------------- - {{#if isAnyType}} -typing.Union[dict, frozendict, str, date, datetime, int, float, bool, Decimal, None, list, tuple, bytes] | | - {{else}} - {{#if hasMultipleTypes}} -typing.Union[{{#if isMap}}dict, frozendict, {{/if}}{{#if isString}}str, {{/if}}{{#if isDate}}date, {{/if}}{{#if isDataTime}}datetime, {{/if}}{{#or isLong isShort isUnboundedInteger}}int, {{/or}}{{#or isFloat isDouble}}float, {{/or}}{{#if isNumber}}Decimal, {{/if}}{{#if isBoolean}}bool, {{/if}}{{#if isNull}}None, {{/if}}{{#if isArray}}list, tuple, {{/if}}{{#if isBinary}}bytes{{/if}}] | | {{#with allowableValues}}{{#if defaultValue}}, {{/if}} must be one of [{{#each enumVars}}{{{value}}}, {{/each}}]{{/with}} - {{else}} - {{#if isArray}} -{{#unless arrayModelType}}**{{dataType}}**{{/unless}}{{#if arrayModelType}}[**{{dataType}}**]({{arrayModelType}}.md){{/if}} | {{#if description}}{{description}}{{/if}} | {{#if defaultValue}}{{#if hasRequired}} if omitted the server will use the default value of {{/if}}{{#unless hasRequired}}defaults to {{/unless}}{{{defaultValue}}}{{/if}} - {{else}} -{{#unless arrayModelType}}**{{dataType}}**{{/unless}} | {{#if description}}{{description}}{{/if}} | {{#if defaultValue}}{{#if hasRequired}} if omitted the server will use the default value of {{/if}}{{#unless hasRequired}}defaults to {{/unless}}{{{defaultValue}}}{{/if}}{{#with allowableValues}}{{#if defaultValue}}, {{/if}} must be one of [{{#each enumVars}}{{{value}}}, {{/each}}]{{/with}} - {{/if}} - {{/if}} - {{/if}} -{{/or}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/schemas.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/schemas.handlebars deleted file mode 100644 index 7e442ffca8..0000000000 --- a/modules/openapi-generator/src/main/resources/python-experimental/schemas.handlebars +++ /dev/null @@ -1,2151 +0,0 @@ -# coding: utf-8 - -{{>partial_header}} - -from collections import defaultdict -from datetime import date, datetime, timedelta # noqa: F401 -import functools -import decimal -import io -import os -import re -import tempfile -import typing -import uuid - -from dateutil.parser.isoparser import isoparser, _takes_ascii -from frozendict import frozendict - -from {{packageName}}.exceptions import ( - ApiTypeError, - ApiValueError, -) -from {{packageName}}.configuration import ( - Configuration, -) - - -class Unset(object): - """ - An instance of this class is set as the default value for object type(dict) properties that are optional - When a property has an unset value, that property will not be assigned in the dict - """ - pass - -unset = Unset() - -none_type = type(None) -file_type = io.IOBase - - -class FileIO(io.FileIO): - """ - A class for storing files - Note: this class is not immutable - """ - - def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader]): - if isinstance(arg, (io.FileIO, io.BufferedReader)): - if arg.closed: - raise ApiValueError('Invalid file state; file is closed and must be open') - arg.close() - inst = super(FileIO, cls).__new__(cls, arg.name) - super(FileIO, inst).__init__(arg.name) - return inst - raise ApiValueError('FileIO must be passed arg which contains the open file') - - def __init__(self, arg: typing.Union[io.FileIO, io.BufferedReader]): - pass - - -def update(d: dict, u: dict): - """ - Adds u to d - Where each dict is defaultdict(set) - """ - if not u: - return d - for k, v in u.items(): - if not v: - continue - if k not in d: - d[k] = v - else: - d[k] = d[k] | v - - -class ValidationMetadata(frozendict): - """ - A class storing metadata that is needed to validate OpenApi Schema payloads - """ - def __new__( - cls, - path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), - from_server: bool = False, - configuration: typing.Optional[Configuration] = None, - seen_classes: typing.FrozenSet[typing.Type] = frozenset(), - validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set['Schema']] = frozendict() - ): - """ - Args: - path_to_item: the path to the current data being instantiated. - For {'a': [1]} if the code is handling, 1, then the path is ('args[0]', 'a', 0) - This changes from location to location - from_server: whether or not this data came form the server - True when receiving server data - False when instantiating model with client side data not form the server - This does not change from location to location - configuration: the Configuration instance to use - This is needed because in Configuration: - - one can disable validation checking - This does not change from location to location - seen_classes: when deserializing data that matches multiple schemas, this is used to store - the schemas that have been traversed. This is used to stop processing when a cycle is seen. - This changes from location to location - validated_path_to_schemas: stores the already validated schema classes for a given path location - This does not change from location to location - """ - return super().__new__( - cls, - path_to_item=path_to_item, - from_server=from_server, - configuration=configuration, - seen_classes=seen_classes, - validated_path_to_schemas=validated_path_to_schemas - ) - - def validation_ran_earlier(self, cls: type) -> bool: - validated_schemas = self.validated_path_to_schemas.get(self.path_to_item, set()) - validation_ran_earlier = validated_schemas and cls in validated_schemas - if validation_ran_earlier: - return True - if cls in self.seen_classes: - return True - return False - - @property - def path_to_item(self) -> typing.Tuple[typing.Union[str, int], ...]: - return self.get('path_to_item') - - @property - def from_server(self) -> bool: - return self.get('from_server') - - @property - def configuration(self) -> typing.Optional[Configuration]: - return self.get('configuration') - - @property - def seen_classes(self) -> typing.FrozenSet[typing.Type]: - return self.get('seen_classes') - - @property - def validated_path_to_schemas(self) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set['Schema']]: - return self.get('validated_path_to_schemas') - - -class ValidatorBase: - @staticmethod - def __is_json_validation_enabled(schema_keyword, configuration=None): - """Returns true if JSON schema validation is enabled for the specified - validation keyword. This can be used to skip JSON schema structural validation - as requested in the configuration. - - Args: - schema_keyword (string): the name of a JSON schema validation keyword. - configuration (Configuration): the configuration class. - """ - - return (configuration is None or - not hasattr(configuration, '_disabled_client_side_validations') or - schema_keyword not in configuration._disabled_client_side_validations) - - @staticmethod - def __raise_validation_error_message(value, constraint_msg, constraint_value, path_to_item, additional_txt=""): - raise ApiValueError( - "Invalid value `{value}`, {constraint_msg} `{constraint_value}`{additional_txt} at {path_to_item}".format( - value=value, - constraint_msg=constraint_msg, - constraint_value=constraint_value, - additional_txt=additional_txt, - path_to_item=path_to_item, - ) - ) - - @classmethod - def __check_str_validations(cls, - validations, input_values, - validation_metadata: ValidationMetadata): - - if (cls.__is_json_validation_enabled('maxLength', validation_metadata.configuration) and - 'max_length' in validations and - len(input_values) > validations['max_length']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="length must be less than or equal to", - constraint_value=validations['max_length'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minLength', validation_metadata.configuration) and - 'min_length' in validations and - len(input_values) < validations['min_length']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="length must be greater than or equal to", - constraint_value=validations['min_length'], - path_to_item=validation_metadata.path_to_item - ) - - checked_value = input_values - if (cls.__is_json_validation_enabled('pattern', validation_metadata.configuration) and - 'regex' in validations): - for regex_dict in validations['regex']: - flags = regex_dict.get('flags', 0) - if not re.search(regex_dict['pattern'], checked_value, flags=flags): - if flags != 0: - # Don't print the regex flags if the flags are not - # specified in the OAS document. - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must match regular expression", - constraint_value=regex_dict['pattern'], - path_to_item=validation_metadata.path_to_item, - additional_txt=" with flags=`{}`".format(flags) - ) - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must match regular expression", - constraint_value=regex_dict['pattern'], - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def __check_tuple_validations( - cls, validations, input_values, - validation_metadata: ValidationMetadata): - - if (cls.__is_json_validation_enabled('maxItems', validation_metadata.configuration) and - 'max_items' in validations and - len(input_values) > validations['max_items']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of items must be less than or equal to", - constraint_value=validations['max_items'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minItems', validation_metadata.configuration) and - 'min_items' in validations and - len(input_values) < validations['min_items']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of items must be greater than or equal to", - constraint_value=validations['min_items'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('uniqueItems', validation_metadata.configuration) and - 'unique_items' in validations and validations['unique_items'] and input_values): - unique_items = set(input_values) - if len(input_values) > len(unique_items): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="duplicate items were found, and the tuple must not contain duplicates because", - constraint_value='unique_items==True', - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def __check_dict_validations( - cls, validations, input_values, - validation_metadata: ValidationMetadata): - - if (cls.__is_json_validation_enabled('maxProperties', validation_metadata.configuration) and - 'max_properties' in validations and - len(input_values) > validations['max_properties']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of properties must be less than or equal to", - constraint_value=validations['max_properties'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minProperties', validation_metadata.configuration) and - 'min_properties' in validations and - len(input_values) < validations['min_properties']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of properties must be greater than or equal to", - constraint_value=validations['min_properties'], - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def __check_numeric_validations( - cls, validations, input_values, - validation_metadata: ValidationMetadata): - - if cls.__is_json_validation_enabled('multipleOf', - validation_metadata.configuration) and 'multiple_of' in validations: - multiple_of_value = validations['multiple_of'] - if (isinstance(input_values, decimal.Decimal) and - not (float(input_values) / multiple_of_value).is_integer() - ): - # Note 'multipleOf' will be as good as the floating point arithmetic. - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="value must be a multiple of", - constraint_value=multiple_of_value, - path_to_item=validation_metadata.path_to_item - ) - - checking_max_or_min_values = {'exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', - 'inclusive_minimum'}.isdisjoint(validations) is False - if not checking_max_or_min_values: - return - max_val = input_values - min_val = input_values - - if (cls.__is_json_validation_enabled('exclusiveMaximum', validation_metadata.configuration) and - 'exclusive_maximum' in validations and - max_val >= validations['exclusive_maximum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value less than", - constraint_value=validations['exclusive_maximum'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('maximum', validation_metadata.configuration) and - 'inclusive_maximum' in validations and - max_val > validations['inclusive_maximum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value less than or equal to", - constraint_value=validations['inclusive_maximum'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('exclusiveMinimum', validation_metadata.configuration) and - 'exclusive_minimum' in validations and - min_val <= validations['exclusive_minimum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value greater than", - constraint_value=validations['exclusive_maximum'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minimum', validation_metadata.configuration) and - 'inclusive_minimum' in validations and - min_val < validations['inclusive_minimum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value greater than or equal to", - constraint_value=validations['inclusive_minimum'], - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def _check_validations_for_types( - cls, - validations, - input_values, - validation_metadata: ValidationMetadata - ): - if isinstance(input_values, str): - cls.__check_str_validations(validations, input_values, validation_metadata) - elif isinstance(input_values, tuple): - cls.__check_tuple_validations(validations, input_values, validation_metadata) - elif isinstance(input_values, frozendict): - cls.__check_dict_validations(validations, input_values, validation_metadata) - elif isinstance(input_values, decimal.Decimal): - cls.__check_numeric_validations(validations, input_values, validation_metadata) - - -class Singleton: - """ - Enums and singletons are the same - The same instance is returned for a given key of (cls, arg) - """ - _instances = {} - - def __new__(cls, arg: typing.Any, **kwargs): - key = (cls, arg) - if key not in cls._instances: - if arg in {None, True, False}: - inst = super().__new__(cls) - cls._instances[key] = inst - elif isinstance(arg, BoolClass): - inst = super().__new__(cls) - cls._instances[key] = inst - elif isinstance(arg, NoneClass): - inst = super().__new__(cls) - cls._instances[key] = inst - else: - cls._instances[key] = super().__new__(cls, arg) - return cls._instances[key] - - def __repr__(self): - if isinstance(self, NoneClass): - return f'<{self.__class__.__name__}: None>' - elif isinstance(self, BoolClass): - if bool(self): - return f'<{self.__class__.__name__}: True>' - return f'<{self.__class__.__name__}: False>' - return f'<{self.__class__.__name__}: {super().__repr__()}>' - - -class NoneClass(Singleton): - @classmethod - @property - def NONE(cls): - return cls(None) - - def __bool__(self) -> bool: - return False - - -class BoolClass(Singleton): - @classmethod - @property - def TRUE(cls): - return cls(True) - - @classmethod - @property - def FALSE(cls): - return cls(False) - - @functools.cache - def __bool__(self) -> bool: - for key, instance in self._instances.items(): - if self is instance: - return bool(key[1]) - raise ValueError('Unable to find the boolean value of this instance') - - -class Validator(typing.Protocol): - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - pass - - -def _SchemaValidator(**validations: typing.Union[str, bool, None, int, float, list[dict[str, typing.Union[str, int, float]]]]) -> Validator: - class SchemaValidator(ValidatorBase): - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - SchemaValidator _validate - Validates that validations pass - """ - cls._check_validations_for_types(validations, arg, validation_metadata) - return super()._validate(arg, validation_metadata) - - return SchemaValidator - - -def _SchemaTypeChecker(union_type_cls: typing.Union[typing.Any]) -> Validator: - if typing.get_origin(union_type_cls) is typing.Union: - union_classes = typing.get_args(union_type_cls) - else: - # note: when a union of a single class is passed in, the union disappears - union_classes = tuple([union_type_cls]) - """ - I want the type hint... union_type_cls - and to use it as a base class but when I do, I get - TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases - """ - class SchemaTypeChecker: - @staticmethod - def __get_valid_classes_phrase(input_classes): - """Returns a string phrase describing what types are allowed""" - all_classes = list(input_classes) - all_classes = sorted(all_classes, key=lambda cls: cls.__name__) - all_class_names = [cls.__name__ for cls in all_classes] - if len(all_class_names) == 1: - return "is {0}".format(all_class_names[0]) - return "is one of [{0}]".format(", ".join(all_class_names)) - - @classmethod - def __type_error_message( - cls, var_value=None, var_name=None, valid_classes=None, key_type=None - ): - """ - Keyword Args: - var_value (any): the variable which has the type_error - var_name (str): the name of the variable which has the typ error - valid_classes (tuple): the accepted classes for current_item's - value - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a tuple - """ - key_or_value = "value" - if key_type: - key_or_value = "key" - valid_classes_phrase = cls.__get_valid_classes_phrase(valid_classes) - msg = "Invalid type. Required {1} type {2} and " "passed type was {3}".format( - var_name, - key_or_value, - valid_classes_phrase, - type(var_value).__name__, - ) - return msg - - @classmethod - def _get_type_error(cls, var_value, path_to_item, valid_classes, key_type=False): - error_msg = cls.__type_error_message( - var_name=path_to_item[-1], - var_value=var_value, - valid_classes=valid_classes, - key_type=key_type, - ) - return ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=valid_classes, - key_type=key_type, - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - SchemaTypeChecker _validate - Validates arg's type - """ - arg_type = type(arg) - if arg_type in union_classes: - return super()._validate(arg, validation_metadata) - raise cls._get_type_error( - arg, - validation_metadata.path_to_item, - union_classes, - key_type=False, - ) - - return SchemaTypeChecker - - -class EnumMakerBase: - pass - - -class EnumMakerInterface(Validator): - @classmethod - @property - def _enum_value_to_name( - cls - ) -> typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]: - pass - - -def _SchemaEnumMaker(enum_value_to_name: typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]) -> EnumMakerInterface: - class SchemaEnumMaker(EnumMakerBase): - @classmethod - @property - def _enum_value_to_name( - cls - ) -> typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]: - pass - try: - super_enum_value_to_name = super()._enum_value_to_name - except AttributeError: - return enum_value_to_name - intersection = dict(enum_value_to_name.items() & super_enum_value_to_name.items()) - return intersection - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - SchemaEnumMaker _validate - Validates that arg is in the enum's allowed values - """ - try: - cls._enum_value_to_name[arg] - except KeyError: - raise ApiValueError("Invalid value {} passed in to {}, {}".format(arg, cls, cls._enum_value_to_name)) - return super()._validate(arg, validation_metadata) - - return SchemaEnumMaker - - -class BoolBase: - def is_true(self) -> bool: - """ - A replacement for x is True - True if the instance is a BoolClass True Singleton - """ - if not issubclass(self.__class__, BoolClass): - return False - return bool(self) - - def is_false(self) -> bool: - """ - A replacement for x is False - True if the instance is a BoolClass False Singleton - """ - if not issubclass(self.__class__, BoolClass): - return False - return bool(self) is False - - -class NoneBase: - def is_none(self) -> bool: - """ - A replacement for x is None - True if the instance is a NoneClass None Singleton - """ - if issubclass(self.__class__, NoneClass): - return True - return False - - -class StrBase: - @property - def as_str(self) -> str: - return self - - @property - def as_date(self) -> date: - raise Exception('not implemented') - - @property - def as_datetime(self) -> datetime: - raise Exception('not implemented') - - @property - def as_decimal(self) -> decimal.Decimal: - raise Exception('not implemented') - - @property - def as_uuid(self) -> uuid.UUID: - raise Exception('not implemented') - - -class UUIDBase(StrBase): - @property - @functools.cache - def as_uuid(self) -> uuid.UUID: - return uuid.UUID(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - uuid.UUID(arg) - return True - except ValueError: - raise ApiValueError( - "Invalid value '{}' for type UUID at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: typing.Optional[ValidationMetadata] = None, - ): - """ - UUIDBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class CustomIsoparser(isoparser): - - @_takes_ascii - def parse_isodatetime(self, dt_str): - components, pos = self._parse_isodate(dt_str) - if len(dt_str) > pos: - if self._sep is None or dt_str[pos:pos + 1] == self._sep: - components += self._parse_isotime(dt_str[pos + 1:]) - else: - raise ValueError('String contains unknown ISO components') - - if len(components) > 3 and components[3] == 24: - components[3] = 0 - return datetime(*components) + timedelta(days=1) - - if len(components) <= 3: - raise ValueError('Value is not a datetime') - - return datetime(*components) - - @_takes_ascii - def parse_isodate(self, datestr): - components, pos = self._parse_isodate(datestr) - - if len(datestr) > pos: - raise ValueError('String contains invalid time components') - - if len(components) > 3: - raise ValueError('String contains invalid time components') - - return date(*components) - - -DEFAULT_ISOPARSER = CustomIsoparser() - - -class DateBase(StrBase): - @property - @functools.cache - def as_date(self) -> date: - return DEFAULT_ISOPARSER.parse_isodate(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - DEFAULT_ISOPARSER.parse_isodate(arg) - return True - except ValueError: - raise ApiValueError( - "Value does not conform to the required ISO-8601 date format. " - "Invalid value '{}' for type date at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: typing.Optional[ValidationMetadata] = None, - ): - """ - DateBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class DateTimeBase: - @property - @functools.cache - def as_datetime(self) -> datetime: - return DEFAULT_ISOPARSER.parse_isodatetime(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - DEFAULT_ISOPARSER.parse_isodatetime(arg) - return True - except ValueError: - raise ApiValueError( - "Value does not conform to the required ISO-8601 datetime format. " - "Invalid value '{}' for type datetime at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - DateTimeBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class DecimalBase(StrBase): - """ - A class for storing decimals that are sent over the wire as strings - These schemas must remain based on StrBase rather than NumberBase - because picking base classes must be deterministic - """ - - @property - @functools.cache - def as_decimal(self) -> decimal.Decimal: - return decimal.Decimal(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - decimal.Decimal(arg) - return True - except decimal.InvalidOperation: - raise ApiValueError( - "Value cannot be converted to a decimal. " - "Invalid value '{}' for type decimal at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - DecimalBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class NumberBase: - @property - def as_int(self) -> int: - try: - return self._as_int - except AttributeError: - """ - Note: for some numbers like 9.0 they could be represented as an - integer but our code chooses to store them as - >>> Decimal('9.0').as_tuple() - DecimalTuple(sign=0, digits=(9, 0), exponent=-1) - so we can tell that the value came from a float and convert it back to a float - during later serialization - """ - if self.as_tuple().exponent < 0: - # this could be represented as an integer but should be represented as a float - # because that's what it was serialized from - raise ApiValueError(f'{self} is not an integer') - self._as_int = int(self) - return self._as_int - - @property - def as_float(self) -> float: - try: - return self._as_float - except AttributeError: - if self.as_tuple().exponent >= 0: - raise ApiValueError(f'{self} is not an float') - self._as_float = float(self) - return self._as_float - - -class ListBase: - @classmethod - def _validate_items(cls, list_items, validation_metadata: ValidationMetadata): - """ - Ensures that: - - values passed in for items are valid - Exceptions will be raised if: - - invalid arguments were passed in - - Args: - list_items: the input list of items - - Raises: - ApiTypeError - for missing required arguments, or for invalid properties - """ - - # if we have definitions for an items schema, use it - # otherwise accept anything - item_cls = getattr(cls, '_items', AnyTypeSchema) - path_to_schemas = {} - for i, value in enumerate(list_items): - item_validation_metadata = ValidationMetadata( - from_server=validation_metadata.from_server, - configuration=validation_metadata.configuration, - path_to_item=validation_metadata.path_to_item+(i,), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - if item_validation_metadata.validation_ran_earlier(item_cls): - continue - other_path_to_schemas = item_cls._validate( - value, validation_metadata=item_validation_metadata) - update(path_to_schemas, other_path_to_schemas) - return path_to_schemas - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - ListBase _validate - We return dynamic classes of different bases depending upon the inputs - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Returns: - new_cls (type): the new class - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - _path_to_schemas = super()._validate(arg, validation_metadata=validation_metadata) - if not isinstance(arg, tuple): - return _path_to_schemas - updated_vm = ValidationMetadata( - configuration=validation_metadata.configuration, - from_server=validation_metadata.from_server, - path_to_item=validation_metadata.path_to_item, - seen_classes=validation_metadata.seen_classes | frozenset({cls}), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - other_path_to_schemas = cls._validate_items(arg, validation_metadata=updated_vm) - update(_path_to_schemas, other_path_to_schemas) - return _path_to_schemas - - @classmethod - def _get_items( - cls: 'Schema', - arg: typing.List[typing.Any], - path_to_item: typing.Tuple[typing.Union[str, int], ...], - path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] - ): - ''' - ListBase _get_items - ''' - list_items = arg - cast_items = [] - # if we have definitions for an items schema, use it - # otherwise accept anything - - cls_item_cls = getattr(cls, '_items', AnyTypeSchema) - for i, value in enumerate(list_items): - item_path_to_item = path_to_item + (i,) - item_cls = path_to_schemas.get(item_path_to_item) - if item_cls is None: - item_cls = cls_item_cls - - if isinstance(value, item_cls): - cast_items.append(value) - continue - - new_value = item_cls._get_new_instance_without_conversion( - value, - item_path_to_item, - path_to_schemas - ) - cast_items.append(new_value) - - return cast_items - - -class Discriminable: - @classmethod - def _ensure_discriminator_value_present(cls, disc_property_name: str, validation_metadata: ValidationMetadata, *args): - if not args or args and disc_property_name not in args[0]: - # The input data does not contain the discriminator property - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '{}' is missing at path: {}".format(disc_property_name, validation_metadata.path_to_item) - ) - - @classmethod - def _get_discriminated_class(cls, disc_property_name: str, disc_payload_value: str): - """ - Used in schemas with discriminators - """ - if not hasattr(cls, '_discriminator'): - return None - disc = cls._discriminator - if disc_property_name not in disc: - return None - discriminated_cls = disc[disc_property_name].get(disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - elif not hasattr(cls, '_composed_schemas'): - return None - # TODO stop traveling if a cycle is hit - for allof_cls in cls._composed_schemas['allOf']: - discriminated_cls = allof_cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - for oneof_cls in cls._composed_schemas['oneOf']: - discriminated_cls = oneof_cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - for anyof_cls in cls._composed_schemas['anyOf']: - discriminated_cls = anyof_cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - return None - - -class DictBase(Discriminable): - # subclass properties - _required_property_names = set() - - @classmethod - def _validate_arg_presence(cls, arg): - """ - Ensures that: - - all required arguments are passed in - - the input variable names are valid - - present in properties or - - accepted because additionalProperties exists - Exceptions will be raised if: - - invalid arguments were passed in - - a var_name is invalid if additionProperties == None and var_name not in _properties - - required properties were not passed in - - Args: - arg: the input dict - - Raises: - ApiTypeError - for missing required arguments, or for invalid properties - """ - seen_required_properties = set() - invalid_arguments = [] - for property_name in arg: - if property_name in cls._required_property_names: - seen_required_properties.add(property_name) - elif property_name in cls._property_names: - continue - elif cls._additional_properties: - continue - else: - invalid_arguments.append(property_name) - missing_required_arguments = list(cls._required_property_names - seen_required_properties) - if missing_required_arguments: - missing_required_arguments.sort() - raise ApiTypeError( - "{} is missing {} required argument{}: {}".format( - cls.__name__, - len(missing_required_arguments), - "s" if len(missing_required_arguments) > 1 else "", - missing_required_arguments - ) - ) - if invalid_arguments: - invalid_arguments.sort() - raise ApiTypeError( - "{} was passed {} invalid argument{}: {}".format( - cls.__name__, - len(invalid_arguments), - "s" if len(invalid_arguments) > 1 else "", - invalid_arguments - ) - ) - - @classmethod - def _validate_args(cls, arg, validation_metadata: ValidationMetadata): - """ - Ensures that: - - values passed in for properties are valid - Exceptions will be raised if: - - invalid arguments were passed in - - Args: - arg: the input dict - - Raises: - ApiTypeError - for missing required arguments, or for invalid properties - """ - path_to_schemas = {} - for property_name, value in arg.items(): - if property_name in cls._required_property_names or property_name in cls._property_names: - schema = getattr(cls, property_name) - elif cls._additional_properties: - schema = cls._additional_properties - else: - raise ApiTypeError('Unable to find schema for value={} in class={} at path_to_item={}'.format( - value, cls, validation_metadata.path_to_item+(property_name,) - )) - arg_validation_metadata = ValidationMetadata( - from_server=validation_metadata.from_server, - configuration=validation_metadata.configuration, - path_to_item=validation_metadata.path_to_item+(property_name,), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - if arg_validation_metadata.validation_ran_earlier(schema): - continue - other_path_to_schemas = schema._validate(value, validation_metadata=arg_validation_metadata) - update(path_to_schemas, other_path_to_schemas) - return path_to_schemas - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - DictBase _validate - We return dynamic classes of different bases depending upon the inputs - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Returns: - new_cls (type): the new class - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - if isinstance(arg, cls): - # an instance of the correct type was passed in - return {} - _path_to_schemas = super()._validate(arg, validation_metadata=validation_metadata) - if not isinstance(arg, frozendict): - return _path_to_schemas - cls._validate_arg_presence(arg) - other_path_to_schemas = cls._validate_args(arg, validation_metadata=validation_metadata) - update(_path_to_schemas, other_path_to_schemas) - try: - _discriminator = cls._discriminator - except AttributeError: - return _path_to_schemas - # discriminator exists - disc_prop_name = list(_discriminator.keys())[0] - cls._ensure_discriminator_value_present(disc_prop_name, validation_metadata, arg) - discriminated_cls = cls._get_discriminated_class( - disc_property_name=disc_prop_name, disc_payload_value=arg[disc_prop_name]) - if discriminated_cls is None: - raise ApiValueError( - "Invalid discriminator value was passed in to {}.{} Only the values {} are allowed at {}".format( - cls.__name__, - disc_prop_name, - list(_discriminator[disc_prop_name].keys()), - validation_metadata.path_to_item + (disc_prop_name,) - ) - ) - updated_vm = ValidationMetadata( - configuration=validation_metadata.configuration, - from_server=validation_metadata.from_server, - path_to_item=validation_metadata.path_to_item, - seen_classes=validation_metadata.seen_classes | frozenset({cls}), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - if updated_vm.validation_ran_earlier(discriminated_cls): - return _path_to_schemas - other_path_to_schemas = discriminated_cls._validate(arg, validation_metadata=updated_vm) - update(_path_to_schemas, other_path_to_schemas) - return _path_to_schemas - - @classmethod - @property - def _additional_properties(cls): - return AnyTypeSchema - - @classmethod - @property - @functools.cache - def _property_names(cls): - property_names = set() - for var_name, var_value in cls.__dict__.items(): - # referenced models are classmethods - is_classmethod = type(var_value) is classmethod - if is_classmethod: - property_names.add(var_name) - continue - is_class = type(var_value) is type - if not is_class: - continue - if not issubclass(var_value, Schema): - continue - if var_name == '_additional_properties': - continue - property_names.add(var_name) - property_names = list(property_names) - property_names.sort() - return tuple(property_names) - - @classmethod - def _get_properties( - cls, - arg: typing.Dict[str, typing.Any], - path_to_item: typing.Tuple[typing.Union[str, int], ...], - path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] - ): - """ - DictBase _get_properties, this is how properties are set - These values already passed validation - """ - dict_items = {} - # if we have definitions for property schemas convert values using it - # otherwise accept anything - - for property_name_js, value in arg.items(): - property_cls = getattr(cls, property_name_js, cls._additional_properties) - property_path_to_item = path_to_item + (property_name_js,) - stored_property_cls = path_to_schemas.get(property_path_to_item) - if stored_property_cls: - property_cls = stored_property_cls - - if isinstance(value, property_cls): - dict_items[property_name_js] = value - continue - - new_value = property_cls._get_new_instance_without_conversion( - value, - property_path_to_item, - path_to_schemas - ) - dict_items[property_name_js] = new_value - return dict_items - - def __setattr__(self, name, value): - if not isinstance(self, FileIO): - raise AttributeError('property setting not supported on immutable instances') - - def __getattr__(self, name): - if isinstance(self, frozendict): - # if an attribute does not exist - try: - return self[name] - except KeyError as ex: - raise AttributeError(str(ex)) - return super().__getattr__(self, name) - - def __getattribute__(self, name): - # if an attribute does exist (for example as a class property but not as an instance method) - try: - return self[name] - except (KeyError, TypeError): - return super().__getattribute__(name) - - -inheritable_primitive_types_set = {decimal.Decimal, str, tuple, frozendict, FileIO, bytes, BoolClass, NoneClass} - - -class Schema: - """ - the base class of all swagger/openapi schemas/models - - ensures that: - - payload passes required validations - - payload is of allowed types - - payload value is an allowed enum value - """ - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - Schema _validate - Runs all schema validation logic and - returns a dynamic class of different bases depending upon the input - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Use cases: - 1. inheritable type: string/decimal.Decimal/frozendict/tuple - 2. singletons: bool/None -> uses the base classes BoolClass/NoneClass - - Required Steps: - 1. verify type of input is valid vs the allowed _types - 2. check validations that are applicable for this type of input - 3. if enums exist, check that the value exists in the enum - - Returns: - path_to_schemas: a map of path to schemas - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - base_class = type(arg) - path_to_schemas = {validation_metadata.path_to_item: set()} - path_to_schemas[validation_metadata.path_to_item].add(cls) - path_to_schemas[validation_metadata.path_to_item].add(base_class) - return path_to_schemas - - @staticmethod - def __process_schema_classes( - schema_classes: typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]] - ): - """ - Processes and mutates schema_classes - If a SomeSchema is a subclass of DictSchema then remove DictSchema because it is already included - """ - if len(schema_classes) < 2: - return - x_schema = schema_type_classes & schema_classes - if not x_schema: - return - x_schema = x_schema.pop() - if any(c is not x_schema and issubclass(c, x_schema) for c in schema_classes): - # needed to not have a mro error in get_new_class - schema_classes.remove(x_schema) - - @classmethod - def __get_new_cls( - cls, - arg, - validation_metadata: ValidationMetadata - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], 'Schema']: - """ - Make a new dynamic class and return an instance of that class - We are making an instance of cls, but instead of making cls - make a new class, new_cls - which includes dynamic bases including cls - return an instance of that new class - - Dict property + List Item Assignment Use cases: - 1. value is NOT an instance of the required schema class - the value is validated by _validate - _validate returns a key value pair - where the key is the path to the item, and the value will be the required manufactured class - made out of the matching schemas - 2. value is an instance of the the correct schema type - the value is NOT validated by _validate, _validate only checks that the instance is of the correct schema type - for this value, _validate does NOT return an entry for it in _path_to_schemas - and in list/dict _get_items,_get_properties the value will be directly assigned - because value is of the correct type, and validation was run earlier when the instance was created - """ - _path_to_schemas = {} - if validation_metadata.validated_path_to_schemas: - update(_path_to_schemas, validation_metadata.validated_path_to_schemas) - if not validation_metadata.validation_ran_earlier(cls): - other_path_to_schemas = cls._validate(arg, validation_metadata=validation_metadata) - update(_path_to_schemas, other_path_to_schemas) - # loop through it make a new class for each entry - # do not modify the returned result because it is cached and we would be modifying the cached value - path_to_schemas = {} - for path, schema_classes in _path_to_schemas.items(): - """ - Use cases - 1. N number of schema classes + enum + type != bool/None, classes in path_to_schemas: tuple/frozendict/str/Decimal/bytes/FileIo - needs Singleton added - 2. N number of schema classes + enum + type == bool/None, classes in path_to_schemas: BoolClass/NoneClass - Singleton already added - 3. N number of schema classes, classes in path_to_schemas: BoolClass/NoneClass/tuple/frozendict/str/Decimal/bytes/FileIo - """ - cls.__process_schema_classes(schema_classes) - enum_schema = any( - hasattr(this_cls, '_enum_value_to_name') for this_cls in schema_classes) - inheritable_primitive_type = schema_classes.intersection(inheritable_primitive_types_set) - chosen_schema_classes = schema_classes - inheritable_primitive_type - suffix = tuple(inheritable_primitive_type) - if enum_schema and suffix[0] not in {NoneClass, BoolClass}: - suffix = (Singleton,) + suffix - - used_classes = tuple(sorted(chosen_schema_classes, key=lambda a_cls: a_cls.__name__)) + suffix - mfg_cls = get_new_class(class_name='DynamicSchema', bases=used_classes) - path_to_schemas[path] = mfg_cls - - return path_to_schemas - - @classmethod - def _get_new_instance_without_conversion( - cls: 'Schema', - arg: typing.Any, - path_to_item: typing.Tuple[typing.Union[str, int], ...], - path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] - ): - # We have a Dynamic class and we are making an instance of it - if issubclass(cls, frozendict): - print(cls.__bases__) - properties = cls._get_properties(arg, path_to_item, path_to_schemas) - return super(Schema, cls).__new__(cls, properties) - elif issubclass(cls, tuple): - items = cls._get_items(arg, path_to_item, path_to_schemas) - return super(Schema, cls).__new__(cls, items) - """ - str = openapi str, date, and datetime - decimal.Decimal = openapi int and float - FileIO = openapi binary type and the user inputs a file - bytes = openapi binary type and the user inputs bytes - """ - return super(Schema, cls).__new__(cls, arg) - - @classmethod - def _from_openapi_data( - cls, - arg: typing.Union[ - str, - date, - datetime, - int, - float, - decimal.Decimal, - bool, - None, - 'Schema', - dict, - frozendict, - tuple, - list, - io.FileIO, - io.BufferedReader, - bytes - ], - _configuration: typing.Optional[Configuration] - ): - """ - Schema _from_openapi_data - """ - from_server = True - validated_path_to_schemas = {} - arg = cast_to_allowed_types(arg, from_server, validated_path_to_schemas) - validation_metadata = ValidationMetadata( - from_server=from_server, configuration=_configuration, validated_path_to_schemas=validated_path_to_schemas) - path_to_schemas = cls.__get_new_cls(arg, validation_metadata) - new_cls = path_to_schemas[validation_metadata.path_to_item] - new_inst = new_cls._get_new_instance_without_conversion( - arg, - validation_metadata.path_to_item, - path_to_schemas - ) - return new_inst - - @staticmethod - def __get_input_dict(*args, **kwargs) -> frozendict: - input_dict = {} - if args and isinstance(args[0], (dict, frozendict)): - input_dict.update(args[0]) - if kwargs: - input_dict.update(kwargs) - return frozendict(input_dict) - - @staticmethod - def __remove_unsets(kwargs): - return {key: val for key, val in kwargs.items() if val is not unset} - - def __new__(cls, *args: typing.Union[dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], _configuration: typing.Optional[Configuration] = None, **kwargs: typing.Union[dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset]): - """ - Schema __new__ - - Args: - args (int/float/decimal.Decimal/str/list/tuple/dict/frozendict/bool/None): the value - kwargs (str, int/float/decimal.Decimal/str/list/tuple/dict/frozendict/bool/None): dict values - _configuration: contains the Configuration that enables json schema validation keywords - like minItems, minLength etc - """ - kwargs = cls.__remove_unsets(kwargs) - if not args and not kwargs: - raise TypeError( - 'No input given. args or kwargs must be given.' - ) - if not kwargs and args and not isinstance(args[0], dict): - arg = args[0] - else: - arg = cls.__get_input_dict(*args, **kwargs) - from_server = False - validated_path_to_schemas = {} - arg = cast_to_allowed_types( - arg, from_server, validated_path_to_schemas) - validation_metadata = ValidationMetadata( - configuration=_configuration, from_server=from_server, validated_path_to_schemas=validated_path_to_schemas) - path_to_schemas = cls.__get_new_cls(arg, validation_metadata) - new_cls = path_to_schemas[validation_metadata.path_to_item] - return new_cls._get_new_instance_without_conversion( - arg, - validation_metadata.path_to_item, - path_to_schemas - ) - - def __init__( - self, - *args: typing.Union[ - dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Union[ - dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset - ] - ): - """ - this is needed to fix 'Unexpected argument' warning in pycharm - this code does nothing because all Schema instances are immutable - this means that all input data is passed into and used in new, and after the new instance is made - no new attributes are assigned and init is not used - """ - pass - - -def cast_to_allowed_types( - arg: typing.Union[str, date, datetime, uuid.UUID, decimal.Decimal, int, float, None, dict, frozendict, list, tuple, bytes, Schema], - from_server: bool, - validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]], - path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), -) -> typing.Union[frozendict, tuple, decimal.Decimal, str, bytes, BoolClass, NoneClass, FileIO]: - """ - Casts the input payload arg into the allowed types - The input validated_path_to_schemas is mutated by running this function - - When from_server is False then - - date/datetime is cast to str - - int/float is cast to Decimal - - If a Schema instance is passed in it is converted back to a primitive instance because - One may need to validate that data to the original Schema class AND additional different classes - those additional classes will need to be added to the new manufactured class for that payload - If the code didn't do this and kept the payload as a Schema instance it would fail to validate to other - Schema classes and the code wouldn't be able to mfg a new class that includes all valid schemas - TODO: store the validated schema classes in validation_metadata - - Args: - arg: the payload - from_server: whether this payload came from the server or not - validated_path_to_schemas: a dict that stores the validated classes at any path location in the payload - """ - if isinstance(arg, Schema): - # store the already run validations - schema_classes = set() - for cls in arg.__class__.__bases__: - if cls is Singleton: - continue - schema_classes.add(cls) - validated_path_to_schemas[path_to_item] = schema_classes - - if isinstance(arg, str): - return str(arg) - elif isinstance(arg, (dict, frozendict)): - return frozendict({key: cast_to_allowed_types(val, from_server, validated_path_to_schemas, path_to_item + (key,)) for key, val in arg.items()}) - elif isinstance(arg, (bool, BoolClass)): - """ - this check must come before isinstance(arg, (int, float)) - because isinstance(True, int) is True - """ - if arg: - return BoolClass.TRUE - return BoolClass.FALSE - elif isinstance(arg, int): - return decimal.Decimal(arg) - elif isinstance(arg, float): - decimal_from_float = decimal.Decimal(arg) - if decimal_from_float.as_integer_ratio()[1] == 1: - # 9.0 -> Decimal('9.0') - # 3.4028234663852886e+38 -> Decimal('340282346638528859811704183484516925440.0') - return decimal.Decimal(str(decimal_from_float)+'.0') - return decimal_from_float - elif isinstance(arg, (tuple, list)): - return tuple([cast_to_allowed_types(item, from_server, validated_path_to_schemas, path_to_item + (i,)) for i, item in enumerate(arg)]) - elif isinstance(arg, (none_type, NoneClass)): - return NoneClass.NONE - elif isinstance(arg, (date, datetime)): - if not from_server: - return arg.isoformat() - # ApiTypeError will be thrown later by _validate_type - return arg - elif isinstance(arg, uuid.UUID): - if not from_server: - return str(arg) - # ApiTypeError will be thrown later by _validate_type - return arg - elif isinstance(arg, decimal.Decimal): - return decimal.Decimal(arg) - elif isinstance(arg, bytes): - return bytes(arg) - elif isinstance(arg, (io.FileIO, io.BufferedReader)): - return FileIO(arg) - raise ValueError('Invalid type passed in got input={} type={}'.format(arg, type(arg))) - - -class ComposedBase(Discriminable): - - @classmethod - def __get_allof_classes(cls, arg, validation_metadata: ValidationMetadata): - path_to_schemas = defaultdict(set) - for allof_cls in cls._composed_schemas['allOf']: - if validation_metadata.validation_ran_earlier(allof_cls): - continue - other_path_to_schemas = allof_cls._validate(arg, validation_metadata=validation_metadata) - update(path_to_schemas, other_path_to_schemas) - return path_to_schemas - - @classmethod - def __get_oneof_class( - cls, - arg, - discriminated_cls, - validation_metadata: ValidationMetadata, - path_to_schemas: typing.Dict[typing.Tuple, typing.Set[typing.Type[Schema]]] - ): - oneof_classes = [] - path_to_schemas = defaultdict(set) - for oneof_cls in cls._composed_schemas['oneOf']: - if oneof_cls in path_to_schemas[validation_metadata.path_to_item]: - oneof_classes.append(oneof_cls) - continue - if validation_metadata.validation_ran_earlier(oneof_cls): - oneof_classes.append(oneof_cls) - continue - try: - path_to_schemas = oneof_cls._validate(arg, validation_metadata=validation_metadata) - except (ApiValueError, ApiTypeError) as ex: - if discriminated_cls is not None and oneof_cls is discriminated_cls: - raise ex - continue - oneof_classes.append(oneof_cls) - if not oneof_classes: - raise ApiValueError( - "Invalid inputs given to generate an instance of {}. None " - "of the oneOf schemas matched the input data.".format(cls) - ) - elif len(oneof_classes) > 1: - raise ApiValueError( - "Invalid inputs given to generate an instance of {}. Multiple " - "oneOf schemas {} matched the inputs, but a max of one is allowed.".format(cls, oneof_classes) - ) - return path_to_schemas - - @classmethod - def __get_anyof_classes( - cls, - arg, - discriminated_cls, - validation_metadata: ValidationMetadata - ): - anyof_classes = [] - path_to_schemas = defaultdict(set) - for anyof_cls in cls._composed_schemas['anyOf']: - if validation_metadata.validation_ran_earlier(anyof_cls): - anyof_classes.append(anyof_cls) - continue - - try: - other_path_to_schemas = anyof_cls._validate(arg, validation_metadata=validation_metadata) - except (ApiValueError, ApiTypeError) as ex: - if discriminated_cls is not None and anyof_cls is discriminated_cls: - raise ex - continue - anyof_classes.append(anyof_cls) - update(path_to_schemas, other_path_to_schemas) - if not anyof_classes: - raise ApiValueError( - "Invalid inputs given to generate an instance of {}. None " - "of the anyOf schemas matched the input data.".format(cls) - ) - return path_to_schemas - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - ComposedBase _validate - We return dynamic classes of different bases depending upon the inputs - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Returns: - new_cls (type): the new class - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - if isinstance(arg, Schema) and validation_metadata.from_server is False: - if isinstance(arg, cls): - # an instance of the correct type was passed in - return {} - raise ApiTypeError( - 'Incorrect type passed in, required type was {} and passed type was {} at {}'.format( - cls, - type(arg), - validation_metadata.path_to_item - ) - ) - - # validation checking on types, validations, and enums - path_to_schemas = super()._validate(arg, validation_metadata=validation_metadata) - - updated_vm = ValidationMetadata( - configuration=validation_metadata.configuration, - from_server=validation_metadata.from_server, - path_to_item=validation_metadata.path_to_item, - seen_classes=validation_metadata.seen_classes | frozenset({cls}), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - - # process composed schema - _discriminator = getattr(cls, '_discriminator', None) - discriminated_cls = None - if _discriminator and arg and isinstance(arg, frozendict): - disc_property_name = list(_discriminator.keys())[0] - cls._ensure_discriminator_value_present(disc_property_name, updated_vm, arg) - # get discriminated_cls by looking at the dict in the current class - discriminated_cls = cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=arg[disc_property_name]) - if discriminated_cls is None: - raise ApiValueError( - "Invalid discriminator value '{}' was passed in to {}.{} Only the values {} are allowed at {}".format( - arg[disc_property_name], - cls.__name__, - disc_property_name, - list(_discriminator[disc_property_name].keys()), - updated_vm.path_to_item + (disc_property_name,) - ) - ) - - if cls._composed_schemas['allOf']: - other_path_to_schemas = cls.__get_allof_classes(arg, validation_metadata=updated_vm) - update(path_to_schemas, other_path_to_schemas) - if cls._composed_schemas['oneOf']: - other_path_to_schemas = cls.__get_oneof_class( - arg, - discriminated_cls=discriminated_cls, - validation_metadata=updated_vm, - path_to_schemas=path_to_schemas - ) - update(path_to_schemas, other_path_to_schemas) - if cls._composed_schemas['anyOf']: - other_path_to_schemas = cls.__get_anyof_classes( - arg, - discriminated_cls=discriminated_cls, - validation_metadata=updated_vm - ) - update(path_to_schemas, other_path_to_schemas) - not_cls = cls._composed_schemas['not'] - if not_cls: - other_path_to_schemas = None - not_exception = ApiValueError( - "Invalid value '{}' was passed in to {}. Value is invalid because it is disallowed by {}".format( - arg, - cls.__name__, - not_cls.__name__, - ) - ) - if updated_vm.validation_ran_earlier(not_cls): - raise not_exception - - try: - other_path_to_schemas = not_cls._validate(arg, validation_metadata=updated_vm) - except (ApiValueError, ApiTypeError): - pass - if other_path_to_schemas: - raise not_exception - - if discriminated_cls is not None and not updated_vm.validation_ran_earlier(discriminated_cls): - # TODO use an exception from this package here - assert discriminated_cls in path_to_schemas[updated_vm.path_to_item] - return path_to_schemas - - -# DictBase, ListBase, NumberBase, StrBase, BoolBase, NoneBase -class ComposedSchema( - _SchemaTypeChecker(typing.Union[NoneClass, str, decimal.Decimal, BoolClass, tuple, frozendict]), - ComposedBase, - DictBase, - ListBase, - NumberBase, - StrBase, - BoolBase, - NoneBase, - Schema -): - - # subclass properties - _composed_schemas = {} - - @classmethod - def _from_openapi_data(cls, *args: typing.Any, _configuration: typing.Optional[Configuration] = None, **kwargs): - if not args: - if not kwargs: - raise ApiTypeError('{} is missing required input data in args or kwargs'.format(cls.__name__)) - args = (kwargs, ) - return super()._from_openapi_data(args[0], _configuration=_configuration) - - -class ListSchema( - _SchemaTypeChecker(typing.Union[tuple]), - ListBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.List[typing.Any], _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[list, tuple], **kwargs: ValidationMetadata): - return super().__new__(cls, arg, **kwargs) - - -class NoneSchema( - _SchemaTypeChecker(typing.Union[NoneClass]), - NoneBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: None, _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: None, **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class NumberSchema( - _SchemaTypeChecker(typing.Union[decimal.Decimal]), - NumberBase, - Schema -): - """ - This is used for type: number with no format - Both integers AND floats are accepted - """ - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[int, float, decimal.Decimal], _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[decimal.Decimal, int, float], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class IntBase(NumberBase): - @property - def as_int(self) -> int: - try: - return self._as_int - except AttributeError: - self._as_int = int(self) - return self._as_int - - @classmethod - def _validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): - if isinstance(arg, decimal.Decimal): - - denominator = arg.as_integer_ratio()[-1] - if denominator != 1: - raise ApiValueError( - "Invalid value '{}' for type integer at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - IntBase _validate - TODO what about types = (int, number) -> IntBase, NumberBase? We could drop int and keep number only - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class IntSchema(IntBase, NumberSchema): - - @classmethod - def _from_openapi_data(cls, arg: int, _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[decimal.Decimal, int], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class Int32Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-2147483648), - inclusive_maximum=decimal.Decimal(2147483647) - ), -): - pass - - -class Int32Schema( - Int32Base, - IntSchema -): - pass - - -class Int64Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-9223372036854775808), - inclusive_maximum=decimal.Decimal(9223372036854775807) - ), -): - pass - - -class Int64Schema( - Int64Base, - IntSchema -): - pass - - -class Float32Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-3.4028234663852886e+38), - inclusive_maximum=decimal.Decimal(3.4028234663852886e+38) - ), -): - pass - - -class Float32Schema( - Float32Base, - NumberSchema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[float, decimal.Decimal], _configuration: typing.Optional[Configuration] = None): - # todo check format - return super()._from_openapi_data(arg, _configuration=_configuration) - - -class Float64Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-1.7976931348623157E+308), - inclusive_maximum=decimal.Decimal(1.7976931348623157E+308) - ), -): - pass - - -class Float64Schema( - Float64Base, - NumberSchema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[float, decimal.Decimal], _configuration: typing.Optional[Configuration] = None): - # todo check format - return super()._from_openapi_data(arg, _configuration=_configuration) - - -class StrSchema( - _SchemaTypeChecker(typing.Union[str]), - StrBase, - Schema -): - """ - date + datetime string types must inherit from this class - That is because one can validate a str payload as both: - - type: string (format unset) - - type: string, format: date - """ - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[str], _configuration: typing.Optional[Configuration] = None) -> 'StrSchema': - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[str, date, datetime, uuid.UUID], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class UUIDSchema(UUIDBase, StrSchema): - - def __new__(cls, arg: typing.Union[str, uuid.UUID], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class DateSchema(DateBase, StrSchema): - - def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class DateTimeSchema(DateTimeBase, StrSchema): - - def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class DecimalSchema(DecimalBase, StrSchema): - - def __new__(cls, arg: typing.Union[str], **kwargs: typing.Union[ValidationMetadata]): - """ - Note: Decimals may not be passed in because cast_to_allowed_types is only invoked once for payloads - which can be simple (str) or complex (dicts or lists with nested values) - Because casting is only done once and recursively casts all values prior to validation then for a potential - client side Decimal input if Decimal was accepted as an input in DecimalSchema then one would not know - if one was using it for a StrSchema (where it should be cast to str) or one is using it for NumberSchema - where it should stay as Decimal. - """ - return super().__new__(cls, arg, **kwargs) - - -class BytesSchema( - _SchemaTypeChecker(typing.Union[bytes]), - Schema, -): - """ - this class will subclass bytes and is immutable - """ - def __new__(cls, arg: typing.Union[bytes], **kwargs: typing.Union[ValidationMetadata]): - return super(Schema, cls).__new__(cls, arg) - - -class FileSchema( - _SchemaTypeChecker(typing.Union[FileIO]), - Schema, -): - """ - This class is NOT immutable - Dynamic classes are built using it for example when AnyType allows in binary data - Al other schema classes ARE immutable - If one wanted to make this immutable one could make this a DictSchema with required properties: - - data = BytesSchema (which would be an immutable bytes based schema) - - file_name = StrSchema - and cast_to_allowed_types would convert bytes and file instances into dicts containing data + file_name - The downside would be that data would be stored in memory which one may not want to do for very large files - - The developer is responsible for closing this file and deleting it - - This class was kept as mutable: - - to allow file reading and writing to disk - - to be able to preserve file name info - """ - - def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader], **kwargs: typing.Union[ValidationMetadata]): - return super(Schema, cls).__new__(cls, arg) - - -class BinaryBase: - pass - - -class BinarySchema( - _SchemaTypeChecker(typing.Union[bytes, FileIO]), - ComposedBase, - BinaryBase, - Schema, -): - - @classmethod - @property - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [], - 'oneOf': [ - BytesSchema, - FileSchema, - ], - 'anyOf': [ - ], - 'not': None - } - - def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader, bytes], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg) - - -class BoolSchema( - _SchemaTypeChecker(typing.Union[BoolClass]), - BoolBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: bool, _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: bool, **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class AnyTypeSchema( - _SchemaTypeChecker( - typing.Union[frozendict, tuple, decimal.Decimal, str, BoolClass, NoneClass, bytes, FileIO] - ), - DictBase, - ListBase, - NumberBase, - StrBase, - BoolBase, - NoneBase, - Schema -): - pass - - -class DictSchema( - _SchemaTypeChecker(typing.Union[frozendict]), - DictBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.Dict[str, typing.Any], _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, *args: typing.Union[dict, frozendict], **kwargs: typing.Union[dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, bytes, Schema, Unset, ValidationMetadata]): - return super().__new__(cls, *args, **kwargs) - - -schema_type_classes = set([NoneSchema, DictSchema, ListSchema, NumberSchema, StrSchema, BoolSchema]) - - -def deserialize_file(response_data, configuration, content_disposition=None): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - Args: - param response_data (str): the file data to write - configuration (Configuration): the instance to use to convert files - - Keyword Args: - content_disposition (str): the value of the Content-Disposition - header - - Returns: - (file_type): the deserialized file which is open - The user is responsible for closing and reading the file - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - if isinstance(response_data, str): - # change str to bytes so we can write it - response_data = response_data.encode('utf-8') - f.write(response_data) - - f = open(path, "rb") - return f - - -@functools.cache -def get_new_class( - class_name: str, - bases: typing.Tuple[typing.Type[typing.Union[Schema, typing.Any]], ...] -) -> typing.Type[Schema]: - """ - Returns a new class that is made with the subclass bases - """ - return type(class_name, bases, {}) - - -LOG_CACHE_USAGE = False - - -def log_cache_usage(cache_fn): - if LOG_CACHE_USAGE: - print(cache_fn.__name__, cache_fn.cache_info()) diff --git a/modules/openapi-generator/src/main/resources/python-flask/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/python-flask/Dockerfile.mustache index f040d41ad6..465eff45c5 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/Dockerfile.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/Dockerfile.mustache @@ -1,31 +1,16 @@ -{{#supportPython2}} -FROM python:2-alpine -{{/supportPython2}} -{{^supportPython2}} FROM python:3-alpine -{{/supportPython2}} RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY requirements.txt /usr/src/app/ -{{#supportPython2}} -RUN pip install --no-cache-dir -r requirements.txt -{{/supportPython2}} -{{^supportPython2}} RUN pip3 install --no-cache-dir -r requirements.txt -{{/supportPython2}} COPY . /usr/src/app EXPOSE {{serverPort}} -{{#supportPython2}} -ENTRYPOINT ["python"] -{{/supportPython2}} -{{^supportPython2}} ENTRYPOINT ["python3"] -{{/supportPython2}} CMD ["-m", "{{packageName}}"] \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-flask/README.mustache b/modules/openapi-generator/src/main/resources/python-flask/README.mustache index 3612c2617d..f36875e450 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/README.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/README.mustache @@ -8,25 +8,14 @@ is an example of building a OpenAPI-enabled Flask server. This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. ## Requirements -{{#supportPython2}} -Python 2.7+ -{{/supportPython2}} -{{^supportPython2}} Python 3.5.2+ -{{/supportPython2}} ## Usage To run the server, please execute the following from the root directory: ``` -{{#supportPython2}} -pip install -r requirements.txt -python -m {{packageName}} -{{/supportPython2}} -{{^supportPython2}} pip3 install -r requirements.txt python3 -m {{packageName}} -{{/supportPython2}} ``` and open your browser to here: diff --git a/modules/openapi-generator/src/main/resources/python-flask/__main__.mustache b/modules/openapi-generator/src/main/resources/python-flask/__main__.mustache index b6018a3af0..4dfeb86aee 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/__main__.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/__main__.mustache @@ -1,9 +1,4 @@ -{{#supportPython2}} -#!/usr/bin/env python -{{/supportPython2}} -{{^supportPython2}} #!/usr/bin/env python3 -{{/supportPython2}} import connexion {{#featureCORS}} diff --git a/modules/openapi-generator/src/main/resources/python-flask/base_model_.mustache b/modules/openapi-generator/src/main/resources/python-flask/base_model_.mustache index e2a33d46b8..c771c9e58d 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/base_model_.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/base_model_.mustache @@ -1,28 +1,24 @@ import pprint import six -{{^supportPython2}} import typing -{{/supportPython2}} from {{packageName}} import util -{{^supportPython2}} T = typing.TypeVar('T') -{{/supportPython2}} -class Model({{#supportPython2}}object{{/supportPython2}}): +class Model(object): # openapiTypes: The key is attribute name and the # value is attribute type. - openapi_types{{^supportPython2}}: typing.Dict[str, type]{{/supportPython2}} = {} + openapi_types: typing.Dict[str, type] = {} # attributeMap: The key is attribute name and the # value is json key in definition. - attribute_map{{^supportPython2}}: typing.Dict[str, str]{{/supportPython2}} = {} + attribute_map: typing.Dict[str, str] = {} @classmethod - def from_dict(cls{{^supportPython2}}: typing.Type[T]{{/supportPython2}}, dikt){{^supportPython2}} -> T{{/supportPython2}}: + def from_dict(cls: typing.Type[T], dikt) -> T: """Returns the dict as a model""" return util.deserialize_model(dikt, cls) diff --git a/modules/openapi-generator/src/main/resources/python-flask/model.mustache b/modules/openapi-generator/src/main/resources/python-flask/model.mustache index 8bb3d65d73..300938389a 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/model.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/model.mustache @@ -58,11 +58,11 @@ class {{classname}}(Model): } {{#vars}}{{#-first}} {{/-first}} - self._{{name}} = {{name}} + self.{{name}} = {{name}} {{/vars}} @classmethod - def from_dict(cls, dikt){{^supportPython2}} -> '{{classname}}'{{/supportPython2}}: + def from_dict(cls, dikt) -> '{{classname}}': """Returns the dict as a model :param dikt: A dict. diff --git a/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache b/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache index 2d1a20a019..8161173186 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache @@ -1,9 +1,6 @@ connexion[swagger-ui] >= 2.6.0; python_version>="3.6" # 2.3 is the last version that supports python 3.4-3.5 connexion[swagger-ui] <= 2.3.0; python_version=="3.5" or python_version=="3.4" -{{#supportPython2}} -connexion[swagger-ui] == 2.4.0; python_version<="2.7" -{{/supportPython2}} # connexion requires werkzeug but connexion < 2.4.0 does not install werkzeug # we must peg werkzeug versions below to fix connexion # https://github.com/zalando/connexion/pull/1044 @@ -14,12 +11,5 @@ python_dateutil >= 2.6.0 # should support both Python 2 and Python 3 flask-cors >= 3.0.10 {{/featureCORS}} -{{#supportPython2}} -typing >= 3.5.2.2 -# For specs with timestamps, pyyaml 5.3 broke connexion's spec parsing in python 2. -# Connexion uses copy.deepcopy() on the spec, thus hitting this bug: -# https://github.com/yaml/pyyaml/issues/387 -pyyaml < 5.3; python_version<="2.7" -{{/supportPython2}} setuptools >= 21.0.0 -Flask == 1.1.2 +Flask == 2.1.1 diff --git a/modules/openapi-generator/src/main/resources/python-flask/setup.mustache b/modules/openapi-generator/src/main/resources/python-flask/setup.mustache index 722f43969c..ec06a7798b 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/setup.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/setup.mustache @@ -16,8 +16,7 @@ VERSION = "{{packageVersion}}" REQUIRES = [ "connexion>=2.0.2", "swagger-ui-bundle>=0.0.2", - "python_dateutil>=2.6.0"{{#supportPython2}}, - "typing>=3.5.2.2"{{/supportPython2}} + "python_dateutil>=2.6.0" ] setup( diff --git a/modules/openapi-generator/src/main/resources/python-flask/test-requirements.mustache b/modules/openapi-generator/src/main/resources/python-flask/test-requirements.mustache index 7157c73aa3..1de59f8559 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/test-requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/test-requirements.mustache @@ -6,8 +6,8 @@ py>=1.4.31 randomize>=0.13 {{/useNose}} {{^useNose}} -pytest~=4.6.7 # needed for python 2.7+3.4 +pytest~=7.1.0 pytest-cov>=2.8.1 -pytest-randomly==1.2.3 # needed for python 2.7+3.4 +pytest-randomly>=1.2.3 {{/useNose}} -Flask-Testing==0.8.0 +Flask-Testing==0.8.1 diff --git a/modules/openapi-generator/src/main/resources/python-flask/tox.mustache b/modules/openapi-generator/src/main/resources/python-flask/tox.mustache index d342cd5f57..76e368c239 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/tox.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/tox.mustache @@ -1,5 +1,5 @@ [tox] -envlist = {{#supportPython2}}py27, {{/supportPython2}}py3 +envlist = py3 skipsdist=True [testenv] diff --git a/modules/openapi-generator/src/main/resources/python-flask/travis.mustache b/modules/openapi-generator/src/main/resources/python-flask/travis.mustache index e03b816ecc..ad71ee5ca0 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/travis.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/travis.mustache @@ -1,9 +1,6 @@ # ref: https://docs.travis-ci.com/user/languages/python language: python python: -{{#supportPython2}} - - "2.7" -{{/supportPython2}} - "3.2" - "3.3" - "3.4" diff --git a/modules/openapi-generator/src/main/resources/python/README.mustache b/modules/openapi-generator/src/main/resources/python-prior/README.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/README.mustache rename to modules/openapi-generator/src/main/resources/python-prior/README.mustache diff --git a/modules/openapi-generator/src/main/resources/python/README_common.mustache b/modules/openapi-generator/src/main/resources/python-prior/README_common.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/README_common.mustache rename to modules/openapi-generator/src/main/resources/python-prior/README_common.mustache diff --git a/modules/openapi-generator/src/main/resources/python/README_onlypackage.mustache b/modules/openapi-generator/src/main/resources/python-prior/README_onlypackage.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/README_onlypackage.mustache rename to modules/openapi-generator/src/main/resources/python-prior/README_onlypackage.mustache diff --git a/modules/openapi-generator/src/main/resources/python/__init__.mustache b/modules/openapi-generator/src/main/resources/python-prior/__init__.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/__init__.mustache rename to modules/openapi-generator/src/main/resources/python-prior/__init__.mustache diff --git a/modules/openapi-generator/src/main/resources/python/__init__api.mustache b/modules/openapi-generator/src/main/resources/python-prior/__init__api.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/__init__api.mustache rename to modules/openapi-generator/src/main/resources/python-prior/__init__api.mustache diff --git a/modules/openapi-generator/src/main/resources/python/__init__apis.mustache b/modules/openapi-generator/src/main/resources/python-prior/__init__apis.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/__init__apis.mustache rename to modules/openapi-generator/src/main/resources/python-prior/__init__apis.mustache diff --git a/modules/openapi-generator/src/main/resources/python/__init__model.mustache b/modules/openapi-generator/src/main/resources/python-prior/__init__model.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/__init__model.mustache rename to modules/openapi-generator/src/main/resources/python-prior/__init__model.mustache diff --git a/modules/openapi-generator/src/main/resources/python/__init__models.mustache b/modules/openapi-generator/src/main/resources/python-prior/__init__models.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/__init__models.mustache rename to modules/openapi-generator/src/main/resources/python-prior/__init__models.mustache diff --git a/modules/openapi-generator/src/main/resources/python/__init__package.mustache b/modules/openapi-generator/src/main/resources/python-prior/__init__package.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/__init__package.mustache rename to modules/openapi-generator/src/main/resources/python-prior/__init__package.mustache diff --git a/modules/openapi-generator/src/main/resources/python/api.mustache b/modules/openapi-generator/src/main/resources/python-prior/api.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/api.mustache rename to modules/openapi-generator/src/main/resources/python-prior/api.mustache diff --git a/modules/openapi-generator/src/main/resources/python/api_client.mustache b/modules/openapi-generator/src/main/resources/python-prior/api_client.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/api_client.mustache rename to modules/openapi-generator/src/main/resources/python-prior/api_client.mustache diff --git a/modules/openapi-generator/src/main/resources/python/api_doc.mustache b/modules/openapi-generator/src/main/resources/python-prior/api_doc.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/api_doc.mustache rename to modules/openapi-generator/src/main/resources/python-prior/api_doc.mustache diff --git a/modules/openapi-generator/src/main/resources/python/api_doc_example.mustache b/modules/openapi-generator/src/main/resources/python-prior/api_doc_example.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/api_doc_example.mustache rename to modules/openapi-generator/src/main/resources/python-prior/api_doc_example.mustache diff --git a/modules/openapi-generator/src/main/resources/python/api_test.mustache b/modules/openapi-generator/src/main/resources/python-prior/api_test.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/api_test.mustache rename to modules/openapi-generator/src/main/resources/python-prior/api_test.mustache diff --git a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache b/modules/openapi-generator/src/main/resources/python-prior/asyncio/rest.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache rename to modules/openapi-generator/src/main/resources/python-prior/asyncio/rest.mustache diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python-prior/configuration.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/configuration.mustache rename to modules/openapi-generator/src/main/resources/python-prior/configuration.mustache diff --git a/modules/openapi-generator/src/main/resources/python/exceptions.mustache b/modules/openapi-generator/src/main/resources/python-prior/exceptions.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/exceptions.mustache rename to modules/openapi-generator/src/main/resources/python-prior/exceptions.mustache diff --git a/modules/openapi-generator/src/main/resources/python-prior/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/python-prior/git_push.sh.mustache new file mode 100755 index 0000000000..0e3776ae6d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-prior/git_push.sh.mustache @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="{{{gitHost}}}" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/modules/openapi-generator/src/main/resources/python/gitignore.mustache b/modules/openapi-generator/src/main/resources/python-prior/gitignore.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/gitignore.mustache rename to modules/openapi-generator/src/main/resources/python-prior/gitignore.mustache diff --git a/modules/openapi-generator/src/main/resources/python/gitlab-ci.mustache b/modules/openapi-generator/src/main/resources/python-prior/gitlab-ci.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/gitlab-ci.mustache rename to modules/openapi-generator/src/main/resources/python-prior/gitlab-ci.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model.mustache b/modules/openapi-generator/src/main/resources/python-prior/model.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_doc.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_doc.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_doc.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_doc.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/classvars.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/classvars.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/classvars.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/classvars.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/docstring_allowed.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/docstring_allowed.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/docstring_allowed.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/docstring_allowed.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/docstring_init_required_kwargs.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/docstring_init_required_kwargs.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/docstring_init_required_kwargs.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/docstring_init_required_kwargs.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/docstring_openapi_validations.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/docstring_openapi_validations.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/docstring_openapi_validations.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/docstring_openapi_validations.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/invalid_pos_args.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/invalid_pos_args.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/invalid_pos_args.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/invalid_pos_args.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_composed.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/method_from_openapi_data_composed.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_composed.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/method_from_openapi_data_composed.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_normal.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/method_from_openapi_data_normal.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_normal.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/method_from_openapi_data_normal.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_shared.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/method_from_openapi_data_shared.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_shared.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/method_from_openapi_data_shared.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_simple.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/method_from_openapi_data_simple.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_simple.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/method_from_openapi_data_simple.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/method_init_composed.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/method_init_composed.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/method_init_normal.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/method_init_normal.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/method_init_shared.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/method_init_shared.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/method_init_simple.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/method_init_simple.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_set_attribute.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/method_set_attribute.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/method_set_attribute.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/method_set_attribute.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/methods_setattr_getattr_composed.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_setattr_getattr_composed.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/methods_setattr_getattr_composed.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_setattr_getattr_composed.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/methods_setattr_getattr_normal.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_setattr_getattr_normal.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/methods_setattr_getattr_normal.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_setattr_getattr_normal.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/methods_shared.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_shared.mustache similarity index 95% rename from modules/openapi-generator/src/main/resources/python/model_templates/methods_shared.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_shared.mustache index 5ffef97f6b..e38832a4a5 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/methods_shared.mustache +++ b/modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_shared.mustache @@ -27,7 +27,7 @@ if self.get("_spec_property_naming", False): new_inst = cls._new_from_openapi_data() else: - new_inst = cls.__new__(cls) + new_inst = cls.__new__(cls, **self.__dict__) for k, v in self.__dict__.items(): setattr(new_inst, k, deepcopy(v, memo)) diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/methods_todict_tostr_eq_shared.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_todict_tostr_eq_shared.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/methods_todict_tostr_eq_shared.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_todict_tostr_eq_shared.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/methods_tostr_eq_simple.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_tostr_eq_simple.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/methods_tostr_eq_simple.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/methods_tostr_eq_simple.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/model_composed.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/model_composed.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/model_normal.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/model_normal.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/model_simple.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/model_simple.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/validations.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_templates/validations.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_templates/validations.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_templates/validations.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_test.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_test.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_test.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_test.mustache diff --git a/modules/openapi-generator/src/main/resources/python/model_utils.mustache b/modules/openapi-generator/src/main/resources/python-prior/model_utils.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/model_utils.mustache rename to modules/openapi-generator/src/main/resources/python-prior/model_utils.mustache diff --git a/modules/openapi-generator/src/main/resources/python/partial_header.mustache b/modules/openapi-generator/src/main/resources/python-prior/partial_header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/partial_header.mustache rename to modules/openapi-generator/src/main/resources/python-prior/partial_header.mustache diff --git a/modules/openapi-generator/src/main/resources/python/python_doc_auth_partial.mustache b/modules/openapi-generator/src/main/resources/python-prior/python_doc_auth_partial.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/python_doc_auth_partial.mustache rename to modules/openapi-generator/src/main/resources/python-prior/python_doc_auth_partial.mustache diff --git a/modules/openapi-generator/src/main/resources/python/requirements.mustache b/modules/openapi-generator/src/main/resources/python-prior/requirements.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/requirements.mustache rename to modules/openapi-generator/src/main/resources/python-prior/requirements.mustache diff --git a/modules/openapi-generator/src/main/resources/python/rest.mustache b/modules/openapi-generator/src/main/resources/python-prior/rest.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/rest.mustache rename to modules/openapi-generator/src/main/resources/python-prior/rest.mustache diff --git a/modules/openapi-generator/src/main/resources/python/setup.mustache b/modules/openapi-generator/src/main/resources/python-prior/setup.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/setup.mustache rename to modules/openapi-generator/src/main/resources/python-prior/setup.mustache diff --git a/modules/openapi-generator/src/main/resources/python/setup_cfg.mustache b/modules/openapi-generator/src/main/resources/python-prior/setup_cfg.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/setup_cfg.mustache rename to modules/openapi-generator/src/main/resources/python-prior/setup_cfg.mustache diff --git a/modules/openapi-generator/src/main/resources/python/signing.mustache b/modules/openapi-generator/src/main/resources/python-prior/signing.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/signing.mustache rename to modules/openapi-generator/src/main/resources/python-prior/signing.mustache diff --git a/modules/openapi-generator/src/main/resources/python/test-requirements.mustache b/modules/openapi-generator/src/main/resources/python-prior/test-requirements.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/test-requirements.mustache rename to modules/openapi-generator/src/main/resources/python-prior/test-requirements.mustache diff --git a/modules/openapi-generator/src/main/resources/python/tornado/rest.mustache b/modules/openapi-generator/src/main/resources/python-prior/tornado/rest.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/tornado/rest.mustache rename to modules/openapi-generator/src/main/resources/python-prior/tornado/rest.mustache diff --git a/modules/openapi-generator/src/main/resources/python/tox.mustache b/modules/openapi-generator/src/main/resources/python-prior/tox.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/tox.mustache rename to modules/openapi-generator/src/main/resources/python-prior/tox.mustache diff --git a/modules/openapi-generator/src/main/resources/python/travis.mustache b/modules/openapi-generator/src/main/resources/python-prior/travis.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/python/travis.mustache rename to modules/openapi-generator/src/main/resources/python-prior/travis.mustache diff --git a/modules/openapi-generator/src/main/resources/python/README.handlebars b/modules/openapi-generator/src/main/resources/python/README.handlebars new file mode 100644 index 0000000000..b8819d2116 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/README.handlebars @@ -0,0 +1,146 @@ +# {{{projectName}}} +{{#if appDescriptionWithNewLines}} +{{{appDescriptionWithNewLines}}} +{{/if}} + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{#unless hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/unless}} +- Build package: {{generatorClass}} +{{#if infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/if}} + +## Requirements. + +Python {{generatorLanguageVersion}} + +## Migration from other generators like python and python-legacy + +### Changes +1. This generator uses spec case for all (object) property names and parameter names. + - So if the spec has a property name like camelCase, it will use camelCase rather than camel_case + - So you will need to update how you input and read properties to use spec case +2. Endpoint parameters are stored in dictionaries to prevent collisions (explanation below) + - So you will need to update how you pass data in to endpoints +3. Endpoint responses now include the original response, the deserialized response body, and (todo)the deserialized headers + - So you will need to update your code to use response.body to access deserialized data +4. All validated data is instantiated in an instance that subclasses all validated Schema classes and Decimal/str/list/tuple/frozendict/NoneClass/BoolClass/bytes/io.FileIO + - This means that you can use isinstance to check if a payload validated against a schema class + - This means that no data will be of type None/True/False + - ingested None will subclass NoneClass + - ingested True will subclass BoolClass + - ingested False will subclass BoolClass + - So if you need to check is True/False/None, instead use instance.is_true_oapg()/.is_false_oapg()/.is_none_oapg() +5. All validated class instances are immutable except for ones based on io.File + - This is because if properties were changed after validation, that validation would no longer apply + - So no changing values or property values after a class has been instantiated +6. String + Number types with formats + - String type data is stored as a string and if you need to access types based on its format like date, + date-time, uuid, number etc then you will need to use accessor functions on the instance + - type string + format: See .as_date_oapg, .as_datetime_oapg, .as_decimal_oapg, .as_uuid_oapg + - type number + format: See .as_float_oapg, .as_int_oapg + - this was done because openapi/json-schema defines constraints. string data may be type string with no format + keyword in one schema, and include a format constraint in another schema + - So if you need to access a string format based type, use as_date_oapg/as_datetime_oapg/as_decimal_oapg/as_uuid_oapg + - So if you need to access a number format based type, use as_int_oapg/as_float_oapg +7. Property access on AnyType(type unset) or object(dict) schemas + - Only required keys with valid python names are properties like .someProp and have type hints + - All optional keys may not exist, so properties are not defined for them + - One can access optional values with dict_instance['optionalProp'] and KeyError will be raised if it does not exist + - Use get_item_oapg if you need a way to always get a value whether or not the key exists + - If the key does not exist, schemas.unset is returned from calling dict_instance.get_item_oapg('optionalProp') + - All required and optional keys have type hints for this method, and @typing.overload is used + - A type hint is also generated for additionalProperties accessed using this method + - So you will need to update you code to use some_instance['optionalProp'] to access optional property + and additionalProperty values +8. The location of the api classes has changed + - Api classes are located in your_package.apis.tags.some_api + - This change was made to eliminate redundant code generation + - Legacy generators generated the same endpoint twice if it had > 1 tag on it + - This generator defines an endpoint in one class, then inherits that class to generate + apis by tags and by paths + - This change reduces code and allows quicker run time if you use the path apis + - path apis are at your_package.apis.paths.some_path + - Those apis will only load their needed models, which is less to load than all of the resources needed in a tag api + - So you will need to update your import paths to the api classes + +### Why are Oapg and _oapg used in class and method names? +Classes can have arbitrarily named properties set on them +Endpoints can have arbitrary operationId method names set +For those reasons, I use the prefix Oapg and _oapg to greatly reduce the likelihood of collisions +on protected + public classes/methods. +oapg stands for OpenApi Python Generator. + +### Object property spec case +This was done because when payloads are ingested, they can be validated against N number of schemas. +If the input signature used a different property name then that has mutated the payload. +So SchemaA and SchemaB must both see the camelCase spec named variable. +Also it is possible to send in two properties, named camelCase and camel_case in the same payload. +That use case should be support so spec case is used. + +### Parameter spec case +Parameters can be included in different locations including: +- query +- path +- header +- cookie + +Any of those parameters could use the same parameter names, so if every parameter +was included as an endpoint parameter in a function signature, they would collide. +For that reason, each of those inputs have been separated out into separate typed dictionaries: +- query_params +- path_params +- header_params +- cookie_params + +So when updating your code, you will need to pass endpoint parameters in using those +dictionaries. + +### Endpoint responses +Endpoint responses have been enriched to now include more information. +Any response reom an endpoint will now include the following properties: +response: urllib3.HTTPResponse +body: typing.Union[Unset, Schema] +headers: typing.Union[Unset, TODO] +Note: response header deserialization has not yet been added + + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git`) + +Then import the package: +```python +import {{{packageName}}} +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import {{{packageName}}} +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +{{> README_common }} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/README_common.handlebars b/modules/openapi-generator/src/main/resources/python/README_common.handlebars similarity index 95% rename from modules/openapi-generator/src/main/resources/python-experimental/README_common.handlebars rename to modules/openapi-generator/src/main/resources/python/README_common.handlebars index 4a6dd287ea..bb33cc728d 100644 --- a/modules/openapi-generator/src/main/resources/python-experimental/README_common.handlebars +++ b/modules/openapi-generator/src/main/resources/python/README_common.handlebars @@ -6,7 +6,7 @@ from pprint import pprint {{#with apiInfo}} {{#each apis}} {{#if @first}} -from {{packageName}}.{{apiPackage}} import {{classFilename}} +from {{packageName}}.{{apiPackage}}.tags import {{classFilename}} {{#each imports}} {{{import}}} {{/each}} @@ -42,7 +42,7 @@ All URIs are relative to *{{basePath}}* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -{{#with apiInfo}}{{#each apis}}{{#with operations}}{{#each operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#if summary}}{{summary}}{{/if}} +{{#with apiInfo}}{{#each apis}}{{#with operations}}{{#each operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#if summary}}{{summary}}{{/if}} {{/each}}{{/with}}{{/each}}{{/with}} ## Documentation For Models diff --git a/modules/openapi-generator/src/main/resources/python-experimental/README_onlypackage.handlebars b/modules/openapi-generator/src/main/resources/python/README_onlypackage.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/README_onlypackage.handlebars rename to modules/openapi-generator/src/main/resources/python/README_onlypackage.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__.handlebars b/modules/openapi-generator/src/main/resources/python/__init__.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/__init__.handlebars rename to modules/openapi-generator/src/main/resources/python/__init__.handlebars diff --git a/modules/openapi-generator/src/main/resources/python/__init__apis.handlebars b/modules/openapi-generator/src/main/resources/python/__init__apis.handlebars new file mode 100644 index 0000000000..7840f7726f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/__init__apis.handlebars @@ -0,0 +1,3 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints then import them from +# tags, paths, or path_to_api, or tag_to_api \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/__init__apis_tags.handlebars b/modules/openapi-generator/src/main/resources/python/__init__apis_tags.handlebars new file mode 100644 index 0000000000..7a6fa76d6b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/__init__apis_tags.handlebars @@ -0,0 +1,11 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from {{packageName}}.apis.tag_to_api import tag_to_api + +import enum + + +class TagValues(str, enum.Enum): +{{#each enumToTag}} + {{@key}} = "{{this}}" +{{/each}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__model.handlebars b/modules/openapi-generator/src/main/resources/python/__init__model.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/__init__model.handlebars rename to modules/openapi-generator/src/main/resources/python/__init__model.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__models.handlebars b/modules/openapi-generator/src/main/resources/python/__init__models.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/__init__models.handlebars rename to modules/openapi-generator/src/main/resources/python/__init__models.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__package.handlebars b/modules/openapi-generator/src/main/resources/python/__init__package.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/__init__package.handlebars rename to modules/openapi-generator/src/main/resources/python/__init__package.handlebars diff --git a/modules/openapi-generator/src/main/resources/python/__init__paths.handlebars b/modules/openapi-generator/src/main/resources/python/__init__paths.handlebars new file mode 100644 index 0000000000..3d3103913d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/__init__paths.handlebars @@ -0,0 +1,3 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from {{packageName}}.apis.path_to_api import path_to_api diff --git a/modules/openapi-generator/src/main/resources/python/__init__paths_enum.handlebars b/modules/openapi-generator/src/main/resources/python/__init__paths_enum.handlebars new file mode 100644 index 0000000000..ba97a8cd83 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/__init__paths_enum.handlebars @@ -0,0 +1,11 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from {{packageName}}.apis.path_to_api import path_to_api + +import enum + + +class PathValues(str, enum.Enum): +{{#each pathValToVar}} + {{this}} = "{{@key}}" +{{/each}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/__init__paths_x.handlebars b/modules/openapi-generator/src/main/resources/python/__init__paths_x.handlebars new file mode 100644 index 0000000000..64d1977b67 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/__init__paths_x.handlebars @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from {{packageName}}.paths.{{pathModule}} import {{apiClassName}} + +from {{packageName}}.paths import PathValues + +path = PathValues.{{{pathVar}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/__init__test_paths.handlebars b/modules/openapi-generator/src/main/resources/python/__init__test_paths.handlebars new file mode 100644 index 0000000000..1309632d3d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/__init__test_paths.handlebars @@ -0,0 +1,68 @@ +import json +import typing + +import urllib3 +from urllib3._collections import HTTPHeaderDict + + +class ApiTestMixin: + json_content_type = 'application/json' + user_agent = 'OpenAPI-Generator/1.0.0/python' + + @classmethod + def assert_pool_manager_request_called_with( + cls, + mock_request, + url: str, + method: str = 'POST', + body: typing.Optional[bytes] = None, + content_type: typing.Optional[str] = None, + accept_content_type: typing.Optional[str] = None, + stream: bool = False, + ): + headers = { + 'User-Agent': cls.user_agent + } + if accept_content_type: + headers['Accept'] = accept_content_type + if content_type: + headers['Content-Type'] = content_type + kwargs = dict( + headers=HTTPHeaderDict(headers), + preload_content=not stream, + timeout=None, + ) + if content_type and method != 'GET': + kwargs['body'] = body + mock_request.assert_called_with( + method, + url, + **kwargs + ) + + @staticmethod + def headers_for_content_type(content_type: str) -> typing.Dict[str, str]: + return {'content-type': content_type} + + @classmethod + def response( + cls, + body: typing.Union[str, bytes], + status: int = 200, + content_type: str = json_content_type, + headers: typing.Optional[typing.Dict[str, str]] = None, + preload_content: bool = True + ) -> urllib3.HTTPResponse: + if headers is None: + headers = {} + headers.update(cls.headers_for_content_type(content_type)) + return urllib3.HTTPResponse( + body, + headers=headers, + status=status, + preload_content=preload_content + ) + + @staticmethod + def json_bytes(in_data: typing.Any) -> bytes: + return json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode('utf-8') diff --git a/modules/openapi-generator/src/main/resources/python/api.handlebars b/modules/openapi-generator/src/main/resources/python/api.handlebars new file mode 100644 index 0000000000..da9b50150d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/api.handlebars @@ -0,0 +1,24 @@ +# coding: utf-8 + +{{>partial_header}} + +{{#with operations}} +{{#each operation}} +from {{packageName}}.paths.{{nickname}}.{{httpMethod}} import {{operationIdCamelCase}} +{{/each}} +{{/with}} + + +{{#with operations}} +class {{classname}}( +{{#each operation}} + {{operationIdCamelCase}}, +{{/each}} +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass +{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/api_client.handlebars b/modules/openapi-generator/src/main/resources/python/api_client.handlebars similarity index 80% rename from modules/openapi-generator/src/main/resources/python-experimental/api_client.handlebars rename to modules/openapi-generator/src/main/resources/python/api_client.handlebars index 38b68c510c..bdcd4519ff 100644 --- a/modules/openapi-generator/src/main/resources/python-experimental/api_client.handlebars +++ b/modules/openapi-generator/src/main/resources/python/api_client.handlebars @@ -13,14 +13,16 @@ from multiprocessing.pool import ThreadPool import re import tempfile import typing +import typing_extensions import urllib3 from urllib3._collections import HTTPHeaderDict -from urllib.parse import quote +from urllib.parse import urlparse, quote from urllib3.fields import RequestField as RequestFieldBase {{#if tornado}} import tornado.gen {{/if}} +import frozendict from {{packageName}} import rest from {{packageName}}.configuration import Configuration @@ -34,7 +36,6 @@ from {{packageName}}.schemas import ( date, datetime, none_type, - frozendict, Unset, unset, ) @@ -48,6 +49,8 @@ class RequestField(RequestFieldBase): class JSONEncoder(json.JSONEncoder): + compact_separators = (',', ':') + def default(self, obj): if isinstance(obj, str): return str(obj) @@ -63,7 +66,7 @@ class JSONEncoder(json.JSONEncoder): return None elif isinstance(obj, BoolClass): return bool(obj) - elif isinstance(obj, (dict, frozendict)): + elif isinstance(obj, (dict, frozendict.frozendict)): return {key: self.default(val) for key, val in obj.items()} elif isinstance(obj, (list, tuple)): return [self.default(item) for item in obj] @@ -88,31 +91,31 @@ class ParameterStyle(enum.Enum): class PrefixSeparatorIterator: - # A class to store prefixes and separators for rfc6570 expansions + # A class to store prefixes and separators for rfc6570 expansions - def __init__(self, prefix: str, separator: str): - self.prefix = prefix - self.separator = separator - self.first = True - if separator in {'.', '|', '%20'}: - item_separator = separator - else: - item_separator = ',' - self.item_separator = item_separator + def __init__(self, prefix: str, separator: str): + self.prefix = prefix + self.separator = separator + self.first = True + if separator in {'.', '|', '%20'}: + item_separator = separator + else: + item_separator = ',' + self.item_separator = item_separator - def __iter__(self): - return self + def __iter__(self): + return self - def __next__(self): - if self.first: - self.first = False - return self.prefix - return self.separator + def __next__(self): + if self.first: + self.first = False + return self.prefix + return self.separator class ParameterSerializerBase: @classmethod - def get_default_explode(cls, style: ParameterStyle) -> bool: + def _get_default_explode(cls, style: ParameterStyle) -> bool: return False @staticmethod @@ -142,11 +145,89 @@ class ParameterSerializerBase: raise ApiValueError('Unable to generate a ref6570 item representation of {}'.format(in_data)) @staticmethod - def to_dict(name: str, value: str): + def _to_dict(name: str, value: str): return {name: value} @classmethod - def ref6570_expansion( + def __ref6570_str_float_int_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + item_value = cls.__ref6570_item_value(in_data, percent_encode) + if item_value is None or (item_value == '' and prefix_separator_iterator.separator == ';'): + return next(prefix_separator_iterator) + var_name_piece + value_pair_equals = '=' if named_parameter_expansion else '' + return next(prefix_separator_iterator) + var_name_piece + value_pair_equals + item_value + + @classmethod + def __ref6570_list_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + item_values = [cls.__ref6570_item_value(v, percent_encode) for v in in_data] + item_values = [v for v in item_values if v is not None] + if not item_values: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + value_pair_equals = '=' if named_parameter_expansion else '' + if not explode: + return ( + next(prefix_separator_iterator) + + var_name_piece + + value_pair_equals + + prefix_separator_iterator.item_separator.join(item_values) + ) + # exploded + return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( + [var_name_piece + value_pair_equals + val for val in item_values] + ) + + @classmethod + def __ref6570_dict_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + in_data_transformed = {key: cls.__ref6570_item_value(val, percent_encode) for key, val in in_data.items()} + in_data_transformed = {key: val for key, val in in_data_transformed.items() if val is not None} + if not in_data_transformed: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + value_pair_equals = '=' if named_parameter_expansion else '' + if not explode: + return ( + next(prefix_separator_iterator) + + var_name_piece + value_pair_equals + + prefix_separator_iterator.item_separator.join( + prefix_separator_iterator.item_separator.join( + item_pair + ) for item_pair in in_data_transformed.items() + ) + ) + # exploded + return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( + [key + '=' + val for key, val in in_data_transformed.items()] + ) + + @classmethod + def _ref6570_expansion( cls, variable_name: str, in_data: typing.Any, @@ -160,54 +241,37 @@ class ParameterSerializerBase: named_parameter_expansion = prefix_separator_iterator.separator in {'&', ';'} var_name_piece = variable_name if named_parameter_expansion else '' if type(in_data) in {str, float, int}: - item_value = cls.__ref6570_item_value(in_data, percent_encode) - if item_value is None: - return next(prefix_separator_iterator) + var_name_piece - elif item_value == '' and prefix_separator_iterator.separator == ';': - return next(prefix_separator_iterator) + var_name_piece - value_pair_equals = '=' if named_parameter_expansion else '' - return next(prefix_separator_iterator) + var_name_piece + value_pair_equals + item_value + return cls.__ref6570_str_float_int_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) elif isinstance(in_data, none_type): # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 return "" elif isinstance(in_data, list): - item_values = [cls.__ref6570_item_value(v, percent_encode) for v in in_data] - item_values = [v for v in item_values if v is not None] - if not item_values: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return "" - value_pair_equals = '=' if named_parameter_expansion else '' - if not explode: - return ( - next(prefix_separator_iterator) + - var_name_piece + - value_pair_equals + - prefix_separator_iterator.item_separator.join(item_values) - ) - # exploded - return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( - [var_name_piece + value_pair_equals + val for val in item_values] + return cls.__ref6570_list_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion ) elif isinstance(in_data, dict): - in_data_transformed = {key: cls.__ref6570_item_value(val, percent_encode) for key, val in in_data.items()} - in_data_transformed = {key: val for key, val in in_data_transformed.items() if val is not None} - if not in_data_transformed: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return "" - value_pair_equals = '=' if named_parameter_expansion else '' - if not explode: - return ( - next(prefix_separator_iterator) + - var_name_piece + value_pair_equals + - prefix_separator_iterator.item_separator.join( - prefix_separator_iterator.item_separator.join( - item_pair - ) for item_pair in in_data_transformed.items() - ) - ) - # exploded - return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( - [key + '=' + val for key, val in in_data_transformed.items()] + return cls.__ref6570_dict_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion ) # bool, bytes, etc raise ApiValueError('Unable to generate a ref6570 representation of {}'.format(in_data)) @@ -215,12 +279,12 @@ class ParameterSerializerBase: class StyleFormSerializer(ParameterSerializerBase): @classmethod - def get_default_explode(cls, style: ParameterStyle) -> bool: + def _get_default_explode(cls, style: ParameterStyle) -> bool: if style is ParameterStyle.FORM: return True - return super().get_default_explode(style) + return super()._get_default_explode(style) - def serialize_form( + def _serialize_form( self, in_data: typing.Union[None, int, float, str, bool, dict, list], name: str, @@ -230,7 +294,7 @@ class StyleFormSerializer(ParameterSerializerBase): ) -> str: if prefix_separator_iterator is None: prefix_separator_iterator = PrefixSeparatorIterator('?', '&') - return self.ref6570_expansion( + return self._ref6570_expansion( variable_name=name, in_data=in_data, explode=explode, @@ -241,7 +305,7 @@ class StyleFormSerializer(ParameterSerializerBase): class StyleSimpleSerializer(ParameterSerializerBase): - def serialize_simple( + def _serialize_simple( self, in_data: typing.Union[None, int, float, str, bool, dict, list], name: str, @@ -249,7 +313,7 @@ class StyleSimpleSerializer(ParameterSerializerBase): percent_encode: bool ) -> str: prefix_separator_iterator = PrefixSeparatorIterator('', ',') - return self.ref6570_expansion( + return self._ref6570_expansion( variable_name=name, in_data=in_data, explode=explode, @@ -258,8 +322,25 @@ class StyleSimpleSerializer(ParameterSerializerBase): ) +class JSONDetector: + """ + Works for: + application/json + application/json; charset=UTF-8 + application/json-patch+json + application/geo+json + """ + __json_content_type_pattern = re.compile("application/[^+]*[+]?(json);?.*") + + @classmethod + def _content_type_is_json(cls, content_type: str) -> bool: + if cls.__json_content_type_pattern.match(content_type): + return True + return False + + @dataclass -class ParameterBase: +class ParameterBase(JSONDetector): name: str in_type: ParameterInType required: bool @@ -286,7 +367,6 @@ class ParameterBase: } __disallowed_header_names = {'Accept', 'Content-Type', 'Authorization'} _json_encoder = JSONEncoder() - _json_content_type = 'application/json' @classmethod def __verify_style_to_in_type(cls, style: typing.Optional[ParameterStyle], in_type: ParameterInType): @@ -331,19 +411,13 @@ class ParameterBase: self.schema = schema self.content = content - @staticmethod - def _remove_empty_and_cast( - in_data: typing.Tuple[typing.Tuple[str, str]], - ) -> typing.Dict[str, str]: - data = tuple(t for t in in_data if t) - if not data: - return dict() - return dict(data) - def _serialize_json( self, - in_data: typing.Union[None, int, float, str, bool, dict, list] + in_data: typing.Union[None, int, float, str, bool, dict, list], + eliminate_whitespace: bool = False ) -> str: + if eliminate_whitespace: + return json.dumps(in_data, separators=self._json_encoder.compact_separators) return json.dumps(in_data) @@ -370,50 +444,50 @@ class PathParameter(ParameterBase, StyleSimpleSerializer): content=content ) - def _serialize_label( + def __serialize_label( self, in_data: typing.Union[None, int, float, str, bool, dict, list] ) -> typing.Dict[str, str]: prefix_separator_iterator = PrefixSeparatorIterator('.', '.') - value = self.ref6570_expansion( + value = self._ref6570_expansion( variable_name=self.name, in_data=in_data, explode=self.explode, percent_encode=True, prefix_separator_iterator=prefix_separator_iterator ) - return self.to_dict(self.name, value) + return self._to_dict(self.name, value) - def _serialize_matrix( + def __serialize_matrix( self, in_data: typing.Union[None, int, float, str, bool, dict, list] ) -> typing.Dict[str, str]: prefix_separator_iterator = PrefixSeparatorIterator(';', ';') - value = self.ref6570_expansion( + value = self._ref6570_expansion( variable_name=self.name, in_data=in_data, explode=self.explode, percent_encode=True, prefix_separator_iterator=prefix_separator_iterator ) - return self.to_dict(self.name, value) + return self._to_dict(self.name, value) - def _serialize_simple( + def __serialize_simple( self, in_data: typing.Union[None, int, float, str, bool, dict, list], ) -> typing.Dict[str, str]: - value = self.serialize_simple( + value = self._serialize_simple( in_data=in_data, name=self.name, explode=self.explode, percent_encode=True ) - return self.to_dict(self.name, value) + return self._to_dict(self.name, value) def serialize( self, in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] ) -> typing.Dict[str, str]: if self.schema: cast_in_data = self.schema(in_data) @@ -429,18 +503,18 @@ class PathParameter(ParameterBase, StyleSimpleSerializer): """ if self.style: if self.style is ParameterStyle.SIMPLE: - return self._serialize_simple(cast_in_data) + return self.__serialize_simple(cast_in_data) elif self.style is ParameterStyle.LABEL: - return self._serialize_label(cast_in_data) + return self.__serialize_label(cast_in_data) elif self.style is ParameterStyle.MATRIX: - return self._serialize_matrix(cast_in_data) + return self.__serialize_matrix(cast_in_data) # self.content will be length one for content_type, schema in self.content.items(): cast_in_data = schema(in_data) cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: + if self._content_type_is_json(content_type): value = self._serialize_json(cast_in_data) - return self.to_dict(self.name, value) + return self._to_dict(self.name, value) raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) @@ -456,8 +530,8 @@ class QueryParameter(ParameterBase, StyleFormSerializer): schema: typing.Optional[typing.Type[Schema]] = None, content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None ): - used_style = ParameterStyle.FORM if style is None and content is None and schema else style - used_explode = self.get_default_explode(used_style) if explode is None else explode + used_style = ParameterStyle.FORM if style is None else style + used_explode = self._get_default_explode(used_style) if explode is None else explode super().__init__( name, @@ -477,14 +551,14 @@ class QueryParameter(ParameterBase, StyleFormSerializer): ) -> typing.Dict[str, str]: if prefix_separator_iterator is None: prefix_separator_iterator = self.get_prefix_separator_iterator() - value = self.ref6570_expansion( + value = self._ref6570_expansion( variable_name=self.name, in_data=in_data, explode=self.explode, percent_encode=True, prefix_separator_iterator=prefix_separator_iterator ) - return self.to_dict(self.name, value) + return self._to_dict(self.name, value) def __serialize_pipe_delimited( self, @@ -493,14 +567,14 @@ class QueryParameter(ParameterBase, StyleFormSerializer): ) -> typing.Dict[str, str]: if prefix_separator_iterator is None: prefix_separator_iterator = self.get_prefix_separator_iterator() - value = self.ref6570_expansion( + value = self._ref6570_expansion( variable_name=self.name, in_data=in_data, explode=self.explode, percent_encode=True, prefix_separator_iterator=prefix_separator_iterator ) - return self.to_dict(self.name, value) + return self._to_dict(self.name, value) def __serialize_form( self, @@ -509,18 +583,16 @@ class QueryParameter(ParameterBase, StyleFormSerializer): ) -> typing.Dict[str, str]: if prefix_separator_iterator is None: prefix_separator_iterator = self.get_prefix_separator_iterator() - value = self.serialize_form( + value = self._serialize_form( in_data, name=self.name, explode=self.explode, percent_encode=True, prefix_separator_iterator=prefix_separator_iterator ) - return self.to_dict(self.name, value) + return self._to_dict(self.name, value) def get_prefix_separator_iterator(self) -> typing.Optional[PrefixSeparatorIterator]: - if not self.schema: - return None if self.style is ParameterStyle.FORM: return PrefixSeparatorIterator('?', '&') elif self.style is ParameterStyle.SPACE_DELIMITED: @@ -531,7 +603,7 @@ class QueryParameter(ParameterBase, StyleFormSerializer): def serialize( self, in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict], + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict], prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None ) -> typing.Dict[str, str]: if self.schema: @@ -559,12 +631,17 @@ class QueryParameter(ParameterBase, StyleFormSerializer): elif self.style is ParameterStyle.PIPE_DELIMITED: return self.__serialize_pipe_delimited(cast_in_data, prefix_separator_iterator) # self.content will be length one + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() for content_type, schema in self.content.items(): cast_in_data = schema(in_data) cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: - value = self._serialize_json(cast_in_data) - return self.to_dict(self.name, value) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data, eliminate_whitespace=True) + return self._to_dict( + self.name, + next(prefix_separator_iterator) + self.name + '=' + quote(value) + ) raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) @@ -581,7 +658,7 @@ class CookieParameter(ParameterBase, StyleFormSerializer): content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None ): used_style = ParameterStyle.FORM if style is None and content is None and schema else style - used_explode = self.get_default_explode(used_style) if explode is None else explode + used_explode = self._get_default_explode(used_style) if explode is None else explode super().__init__( name, @@ -597,7 +674,7 @@ class CookieParameter(ParameterBase, StyleFormSerializer): def serialize( self, in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] ) -> typing.Dict[str, str]: if self.schema: cast_in_data = self.schema(in_data) @@ -611,21 +688,21 @@ class CookieParameter(ParameterBase, StyleFormSerializer): TODO add escaping of comma, space, equals or turn encoding on """ - value = self.serialize_form( + value = self._serialize_form( cast_in_data, explode=self.explode, name=self.name, percent_encode=False, prefix_separator_iterator=PrefixSeparatorIterator('', '&') ) - return self.to_dict(self.name, value) + return self._to_dict(self.name, value) # self.content will be length one for content_type, schema in self.content.items(): cast_in_data = schema(in_data) cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: + if self._content_type_is_json(content_type): value = self._serialize_json(cast_in_data) - return self.to_dict(self.name, value) + return self._to_dict(self.name, value) raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) @@ -652,7 +729,7 @@ class HeaderParameter(ParameterBase, StyleSimpleSerializer): ) @staticmethod - def __to_headers(in_data: typing.Tuple[typing.Tuple[str, str], ...]) -> HTTPHeaderDict[str, str]: + def __to_headers(in_data: typing.Tuple[typing.Tuple[str, str], ...]) -> HTTPHeaderDict: data = tuple(t for t in in_data if t) headers = HTTPHeaderDict() if not data: @@ -660,17 +737,11 @@ class HeaderParameter(ParameterBase, StyleSimpleSerializer): headers.extend(data) return headers - def _serialize_simple( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - ) -> str: - return self.serialize_simple(in_data, self.name, self.explode, False) - def serialize( self, in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] - ) -> HTTPHeaderDict[str, str]: + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> HTTPHeaderDict: if self.schema: cast_in_data = self.schema(in_data) cast_in_data = self._json_encoder.default(cast_in_data) @@ -680,13 +751,13 @@ class HeaderParameter(ParameterBase, StyleSimpleSerializer): returns headers: dict """ if self.style: - value = self._serialize_simple(cast_in_data) + value = self._serialize_simple(cast_in_data, self.name, self.explode, False) return self.__to_headers(((self.name, value),)) # self.content will be length one for content_type, schema in self.content.items(): cast_in_data = schema(in_data) cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: + if self._content_type_is_json(content_type): value = self._serialize_json(cast_in_data) return self.__to_headers(((self.name, value),)) raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) @@ -725,7 +796,7 @@ class MediaType: @dataclass class ApiResponse: response: urllib3.HTTPResponse - body: typing.Union[Unset, typing.Type[Schema]] + body: typing.Union[Unset, Schema] headers: typing.Union[Unset, typing.List[HeaderParameter]] def __init__( @@ -749,20 +820,9 @@ class ApiResponseWithoutDeserialization(ApiResponse): headers: typing.Union[Unset, typing.List[HeaderParameter]] = unset -class JSONDetector: - @staticmethod - def content_type_is_json(content_type: str) -> bool: - """ - for when content_type strings also include charset info like: - application/json; charset=UTF-8 - """ - content_type_piece = content_type.split(';')[0] - if content_type_piece == 'application/json': - return True - return False - - class OpenApiResponse(JSONDetector): + __filename_content_disposition_pattern = re.compile('filename="(.+?)"') + def __init__( self, response_cls: typing.Type[ApiResponse] = ApiResponse, @@ -781,10 +841,23 @@ class OpenApiResponse(JSONDetector): return json.loads(response.data) @staticmethod - def __file_name_from_content_disposition(content_disposition: typing.Optional[str]) -> typing.Optional[str]: + def __file_name_from_response_url(response_url: typing.Optional[str]) -> typing.Optional[str]: + if response_url is None: + return None + url_path = urlparse(response_url).path + if url_path: + path_basename = os.path.basename(url_path) + if path_basename: + _filename, ext = os.path.splitext(path_basename) + if ext: + return path_basename + return None + + @classmethod + def __file_name_from_content_disposition(cls, content_disposition: typing.Optional[str]) -> typing.Optional[str]: if content_disposition is None: return None - match = re.search('filename="(.+?)"', content_disposition) + match = cls.__filename_content_disposition_pattern.search(content_disposition) if not match: return None return match.group(1) @@ -799,13 +872,16 @@ class OpenApiResponse(JSONDetector): a file will be written and returned """ if response.supports_chunked_reads(): - file_name = self.__file_name_from_content_disposition(response.headers.get('content-disposition')) + file_name = ( + self.__file_name_from_content_disposition(response.headers.get('content-disposition')) + or self.__file_name_from_response_url(response.geturl()) + ) if file_name is None: _fd, path = tempfile.mkstemp() else: path = os.path.join(tempfile.gettempdir(), file_name) - # TODO get file_name from the filename at the end of the url if it exists + with open(path, 'wb') as new_file: chunk_size = 1024 while True: @@ -847,8 +923,8 @@ class OpenApiResponse(JSONDetector): if self.content is not None: if content_type not in self.content: raise ApiValueError( - f'Invalid content_type={content_type} returned for response with ' - 'status_code={str(response.status)}' + f"Invalid content_type returned. Content_type='{content_type}' was returned " + f"when only {str(set(self.content))} are defined for status_code={str(response.status)}" ) body_schema = self.content[content_type].schema if body_schema is None: @@ -859,7 +935,7 @@ class OpenApiResponse(JSONDetector): body=unset ) - if self.content_type_is_json(content_type): + if self._content_type_is_json(content_type): body_data = self.__deserialize_json(response) elif content_type == 'application/octet-stream': body_data = self.__deserialize_application_octet_stream(response) @@ -868,7 +944,7 @@ class OpenApiResponse(JSONDetector): content_type = 'multipart/form-data' else: raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type)) - deserialized_body = body_schema._from_openapi_data( + deserialized_body = body_schema.from_openapi_data_oapg( body_data, _configuration=configuration) elif streamed: response.release_conn() @@ -903,7 +979,6 @@ class ApiClient: """ _pool = None - __json_encoder = JSONEncoder() def __init__( self, @@ -919,7 +994,7 @@ class ApiClient: self.pool_threads = pool_threads self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} + self.default_headers = HTTPHeaderDict() if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie @@ -979,15 +1054,18 @@ class ApiClient: ) -> urllib3.HTTPResponse: # header parameters - headers = headers or {} - headers.update(self.default_headers) + used_headers = HTTPHeaderDict(self.default_headers) if self.cookie: headers['Cookie'] = self.cookie # auth setting - self.update_params_for_auth(headers, + self.update_params_for_auth(used_headers, auth_settings, resource_path, method, body) + # must happen after cookie setting and auth setting in case user is overriding those + if headers: + used_headers.update(headers) + # request url if host is None: url = self.configuration.host + resource_path @@ -999,7 +1077,7 @@ class ApiClient: response = {{#if asyncio}}await {{/if}}{{#if tornado}}yield {{/if}}self.request( method, url, - headers=headers, + headers=used_headers, fields=fields, body=body, stream=stream, @@ -1160,33 +1238,34 @@ class ApiClient: for auth in auth_settings: auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if auth_setting['in'] == 'cookie': - headers.add('Cookie', auth_setting['value']) - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers.add(auth_setting['key'], auth_setting['value']) + if not auth_setting: + continue + if auth_setting['in'] == 'cookie': + headers.add('Cookie', auth_setting['value']) + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers.add(auth_setting['key'], auth_setting['value']) {{#if hasHttpSignatureMethods}} - else: - # The HTTP signature scheme requires multiple HTTP headers - # that are calculated dynamically. - signing_info = self.configuration.signing_info - querys = tuple() - auth_headers = signing_info.get_http_signature_headers( - resource_path, method, headers, body, querys) - for key, value in auth_headers.items(): - headers.add(key, value) -{{/if}} - elif auth_setting['in'] == 'query': - """ TODO implement auth in query - need to pass in prefix_separator_iterator - and need to output resource_path with query params added - """ - raise ApiValueError("Auth in query not yet implemented") else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) + # The HTTP signature scheme requires multiple HTTP headers + # that are calculated dynamically. + signing_info = self.configuration.signing_info + querys = tuple() + auth_headers = signing_info.get_http_signature_headers( + resource_path, method, headers, body, querys) + for key, value in auth_headers.items(): + headers.add(key, value) +{{/if}} + elif auth_setting['in'] == 'query': + """ TODO implement auth in query + need to pass in prefix_separator_iterator + and need to output resource_path with query params added + """ + raise ApiValueError("Auth in query not yet implemented") + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) class Api: @@ -1202,7 +1281,7 @@ class Api: self.api_client = api_client @staticmethod - def _verify_typed_dict_inputs(cls: typing.Type[typing.TypedDict], data: typing.Dict[str, typing.Any]): + def _verify_typed_dict_inputs_oapg(cls: typing.Type[typing_extensions.TypedDict], data: typing.Dict[str, typing.Any]): """ Ensures that: - required keys are present @@ -1244,7 +1323,7 @@ class Api: ) ) - def get_host( + def _get_host_oapg( self, operation_id: str, servers: typing.Tuple[typing.Dict[str, str], ...] = tuple(), @@ -1274,9 +1353,9 @@ class Api: return host -class SerializedRequestBody(typing.TypedDict, total=False): +class SerializedRequestBody(typing_extensions.TypedDict, total=False): body: typing.Union[str, bytes] - fields: typing.Tuple[typing.Union[RequestField, tuple[str, str]], ...] + fields: typing.Tuple[typing.Union[RequestField, typing.Tuple[str, str]], ...] class RequestBody(StyleFormSerializer, JSONDetector): @@ -1308,8 +1387,8 @@ class RequestBody(StyleFormSerializer, JSONDetector): @staticmethod def __serialize_text_plain(in_data: typing.Any) -> typing.Dict[str, str]: - if isinstance(in_data, frozendict): - raise ValueError('Unable to serialize type frozendict to text/plain') + if isinstance(in_data, frozendict.frozendict): + raise ValueError('Unable to serialize type frozendict.frozendict to text/plain') elif isinstance(in_data, tuple): raise ValueError('Unable to serialize type tuple to text/plain') elif isinstance(in_data, NoneClass): @@ -1342,7 +1421,7 @@ class RequestBody(StyleFormSerializer, JSONDetector): def __serialize_multipart_form_data( self, in_data: Schema ) -> typing.Dict[str, typing.Tuple[RequestField, ...]]: - if not isinstance(in_data, frozendict): + if not isinstance(in_data, frozendict.frozendict): raise ValueError(f'Unable to serialize {in_data} to multipart/form-data because it is not a dict of data') """ In a multipart/form-data request body, each schema property, or each element of a schema array property, @@ -1389,11 +1468,11 @@ class RequestBody(StyleFormSerializer, JSONDetector): """ POST submission of form data in body """ - if not isinstance(in_data, frozendict): + if not isinstance(in_data, frozendict.frozendict): raise ValueError( f'Unable to serialize {in_data} to application/x-www-form-urlencoded because it is not a dict of data') cast_in_data = self.__json_encoder.default(in_data) - value = self.serialize_form(cast_in_data, name='', explode=True, percent_encode=False) + value = self._serialize_form(cast_in_data, name='', explode=True, percent_encode=False) return dict(body=value) def serialize( @@ -1411,13 +1490,13 @@ class RequestBody(StyleFormSerializer, JSONDetector): media_type = self.content[content_type] if isinstance(in_data, media_type.schema): cast_in_data = in_data - elif isinstance(in_data, (dict, frozendict)) and in_data: + elif isinstance(in_data, (dict, frozendict.frozendict)) and in_data: cast_in_data = media_type.schema(**in_data) else: cast_in_data = media_type.schema(in_data) # TODO check for and use encoding if it exists # and content_type is multipart or application/x-www-form-urlencoded - if self.content_type_is_json(content_type): + if self._content_type_is_json(content_type): return self.__serialize_json(cast_in_data) elif content_type == 'text/plain': return self.__serialize_text_plain(cast_in_data) diff --git a/modules/openapi-generator/src/main/resources/python-experimental/api_doc.handlebars b/modules/openapi-generator/src/main/resources/python/api_doc.handlebars similarity index 81% rename from modules/openapi-generator/src/main/resources/python-experimental/api_doc.handlebars rename to modules/openapi-generator/src/main/resources/python/api_doc.handlebars index 01790e0643..1c279b5a37 100644 --- a/modules/openapi-generator/src/main/resources/python-experimental/api_doc.handlebars +++ b/modules/openapi-generator/src/main/resources/python/api_doc.handlebars @@ -1,16 +1,18 @@ -# {{packageName}}.{{classname}}{{#if description}} + +# {{packageName}}.{{apiPackage}}.tags.{{classFilename}}.{{classname}}{{#if description}} {{description}}{{/if}} All URIs are relative to *{{basePath}}* Method | HTTP request | Description ------------- | ------------- | ------------- -{{#with operations}}{{#each operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#if summary}}{{summary}}{{/if}} +{{#with operations}}{{#each operation}}[**{{operationId}}**](#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#if summary}}{{summary}}{{/if}} {{/each}}{{/with}} {{#with operations}} {{#each operation}} # **{{{operationId}}}** + > {{#if returnType}}{{{returnType}}} {{/if}}{{{operationId}}}({{#each requiredParams}}{{#unless defaultValue}}{{paramName}}{{#if hasMore}}, {{/if}}{{/unless}}{{/each}}) {{#if summary}}{{{summary}}}{{/if}}{{#if notes}} @@ -79,7 +81,7 @@ skip_deserialization | bool | default is False | when True, headers and body wil ### body {{#each content}} {{#with this.schema}} -{{> api_doc_schema_type_hint }} +{{> api_doc_schema_type_hint complexTypePrefix="../../models/" }} {{/with}} {{/each}} {{/with}} @@ -96,7 +98,7 @@ Name | Type | Description | Notes {{#each queryParams}} {{#with schema}} -{{> api_doc_schema_type_hint }} +{{> api_doc_schema_type_hint complexTypePrefix="../../models/" }} {{/with}} {{/each}} {{/if}} @@ -112,7 +114,7 @@ Name | Type | Description | Notes {{/each}} {{#each headerParams}} {{#with schema}} -{{> api_doc_schema_type_hint }} +{{> api_doc_schema_type_hint complexTypePrefix="../../models/" }} {{/with}} {{/each}} {{/if}} @@ -128,7 +130,7 @@ Name | Type | Description | Notes {{/each}} {{#each pathParams}} {{#with schema}} -{{> api_doc_schema_type_hint }} +{{> api_doc_schema_type_hint complexTypePrefix="../../models/" }} {{/with}} {{/each}} {{/if}} @@ -144,7 +146,7 @@ Name | Type | Description | Notes {{/each}} {{#each cookieParams}} {{#with schema}} -{{> api_doc_schema_type_hint }} +{{> api_doc_schema_type_hint complexTypePrefix="../../models/" }} {{/with}} {{/each}} {{/if}} @@ -159,18 +161,18 @@ Code | Class | Description n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned {{#each responses}} {{#if isDefault}} -default | ApiResponseForDefault | {{message}} +default | [ApiResponseForDefault](#{{operationId}}.ApiResponseForDefault) | {{message}} {{else}} -{{code}} | ApiResponseFor{{code}} | {{message}} +{{code}} | [ApiResponseFor{{code}}](#{{operationId}}.ApiResponseFor{{code}}) | {{message}} {{/if}} {{/each}} {{#each responses}} {{#if isDefault}} -#### ApiResponseForDefault +#### {{operationId}}.ApiResponseForDefault {{else}} -#### ApiResponseFor{{code}} +#### {{operationId}}.ApiResponseFor{{code}} {{/if}} Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- @@ -179,7 +181,7 @@ body | {{#unless content}}Unset{{else}}typing.Union[{{#each content}}{{#if this. headers | {{#unless responseHeaders}}Unset{{else}}ResponseHeadersFor{{code}}{{/unless}} | {{#unless responseHeaders}}headers were not defined{{/unless}} | {{#each content}} {{#with this.schema}} -{{> api_doc_schema_type_hint }} +{{> api_doc_schema_type_hint complexTypePrefix="../../models/" }} {{/with}} {{/each}} {{#if responseHeaders}} @@ -192,21 +194,18 @@ Name | Type | Description | Notes {{/each}} {{#each responseHeaders}} {{#with schema}} -{{> api_doc_schema_type_hint }} +{{> api_doc_schema_type_hint complexTypePrefix="../../models/" }} {{/with}} {{/each}} {{/if}} {{/each}} - -{{#if returnType}}{{#if returnTypeIsPrimitive}}**{{{returnType}}}**{{/if}}{{#unless returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/unless}}{{/if}}{{#unless returnType}}void (empty response body){{/unless}} - ### Authorization -{{#unless authMethods}}No authorization required{{/unless}}{{#each authMethods}}[{{{name}}}](../README.md#{{{name}}}){{#unless @last}}, {{/unless}}{{/each}} +{{#unless authMethods}}No authorization required{{/unless}}{{#each authMethods}}[{{{name}}}](../../../README.md#{{{name}}}){{#unless @last}}, {{/unless}}{{/each}} -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) {{/each}} {{/with}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/api_doc_example.handlebars b/modules/openapi-generator/src/main/resources/python/api_doc_example.handlebars similarity index 98% rename from modules/openapi-generator/src/main/resources/python-experimental/api_doc_example.handlebars rename to modules/openapi-generator/src/main/resources/python/api_doc_example.handlebars index e6fa0bd4ed..10661156ce 100644 --- a/modules/openapi-generator/src/main/resources/python-experimental/api_doc_example.handlebars +++ b/modules/openapi-generator/src/main/resources/python/api_doc_example.handlebars @@ -1,6 +1,6 @@ ```python import {{{packageName}}} -from {{packageName}}.{{apiPackage}} import {{classFilename}} +from {{packageName}}.{{apiPackage}}.tags import {{classFilename}} {{#each imports}} {{{.}}} {{/each}} diff --git a/modules/openapi-generator/src/main/resources/python/api_doc_schema_type_hint.handlebars b/modules/openapi-generator/src/main/resources/python/api_doc_schema_type_hint.handlebars new file mode 100644 index 0000000000..27aa7a499b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/api_doc_schema_type_hint.handlebars @@ -0,0 +1,10 @@ + +# {{baseName}} +{{#if complexType}} +Type | Description | Notes +------------- | ------------- | ------------- +[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md) | {{#if description}}{{description}}{{/if}} | {{#if isReadOnly}}[readonly] {{/if}} + +{{else}} +{{> schema_doc complexTypePrefix="{{complexTypePrefix}}" }} +{{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/api_test.handlebars b/modules/openapi-generator/src/main/resources/python/api_test.handlebars new file mode 100644 index 0000000000..142ec8b435 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/api_test.handlebars @@ -0,0 +1,143 @@ +# coding: utf-8 + +{{>partial_header}} + +import unittest +from unittest.mock import patch + +import urllib3 + +import {{packageName}} +from {{packageName}}.paths.{{operation.nickname}} import {{operation.httpMethod}} # noqa: E501 +from {{packageName}} import configuration, schemas, api_client + +from .. import ApiTestMixin + + +{{#with operation}} +class Test{{operationIdSnakeCase}}(ApiTestMixin, unittest.TestCase): + """ + {{operationIdSnakeCase}} unit test stubs +{{#if summary}} + {{{summary}}} # noqa: E501 +{{/if}} + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = {{httpMethod}}.ApiFor{{httpMethod}}(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + +{{#each responses}} + {{#if @first}} + response_status = {{code}} +{{#if content}} +{{#each content}} + +{{#if this.testCases}} +{{#each testCases}} +{{#with this }} + def test_{{@key}}_{{#if valid}}passes{{else}}fails{{/if}}(self): + # {{description}} + accept_content_type = '{{{../@key}}}' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( +{{#with data}} + {{> model_templates/payload_renderer endChar='' }} +{{/with}} + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) +{{#if valid}} + {{> api_test_partial }} + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, {{httpMethod}}.{{schema.baseName}}) + deserialized_response_body = {{httpMethod}}.{{schema.baseName}}.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body +{{else}} + with self.assertRaises(({{packageName}}.ApiValueError, {{packageName}}.ApiTypeError)): + self.api.{{httpMethod}}( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '{{{path}}}', + method='{{httpMethod}}'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) +{{/if}} +{{/with}} + +{{/each}} + +{{/if}} +{{/each}} +{{else}} + response_body = '' +{{/if}} +{{/if}} +{{/each}} +{{#if bodyParam}} +{{#with bodyParam}} +{{#if required}} +{{#each content}} +{{#if this.testCases}} + +{{#each testCases}} +{{#with this }} + def test_{{@key}}_{{#if valid}}passes{{else}}fails{{/if}}(self): + content_type = '{{{../@key}}}' + # {{description}} + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( +{{#with data}} + {{> model_templates/payload_renderer endChar='' }} +{{/with}} + ) +{{#if valid}} + body = {{httpMethod}}.{{schema.baseName}}.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + {{> api_test_partial }} + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) +{{else}} + with self.assertRaises(({{packageName}}.ApiValueError, {{packageName}}.ApiTypeError)): + body = {{httpMethod}}.{{schema.baseName}}.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.{{httpMethod}}(body=body) +{{/if}} +{{/with}} + +{{/each}} + +{{/if}} +{{/each}} +{{/if}} +{{/with}} +{{else}} + {{/if}} + +{{/with}} + +if __name__ == '__main__': + unittest.main() diff --git a/modules/openapi-generator/src/main/resources/python/api_test_partial.handlebars b/modules/openapi-generator/src/main/resources/python/api_test_partial.handlebars new file mode 100644 index 0000000000..e129e34d85 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/api_test_partial.handlebars @@ -0,0 +1,21 @@ +api_response = self.api.{{httpMethod}}( +{{#if bodyParam}} + body=body, + content_type=content_type +{{/if}} +{{#if produces}} + accept_content_types=(accept_content_type,) +{{/if}} +) +self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '{{{path}}}', + method='{{httpMethod}}'.upper(), +{{#if bodyParam}} + body=self.json_bytes(payload), + content_type=content_type, +{{/if}} +{{#if produces}} + accept_content_type=accept_content_type, +{{/if}} +) diff --git a/modules/openapi-generator/src/main/resources/python/apis_path_module.handlebars b/modules/openapi-generator/src/main/resources/python/apis_path_module.handlebars new file mode 100644 index 0000000000..226894c62b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/apis_path_module.handlebars @@ -0,0 +1,52 @@ +{{#if pathItem.get}} +from {{packageName}}.paths.{{pathModule}}.get import ApiForget +{{/if}} +{{#if pathItem.put}} +from {{packageName}}.paths.{{pathModule}}.put import ApiForput +{{/if}} +{{#if pathItem.post}} +from {{packageName}}.paths.{{pathModule}}.post import ApiForpost +{{/if}} +{{#if pathItem.delete}} +from {{packageName}}.paths.{{pathModule}}.delete import ApiFordelete +{{/if}} +{{#if pathItem.options}} +from {{packageName}}.paths.{{pathModule}}.options import ApiForoptions +{{/if}} +{{#if pathItem.head}} +from {{packageName}}.paths.{{pathModule}}.head import ApiForhead +{{/if}} +{{#if pathItem.patch}} +from {{packageName}}.paths.{{pathModule}}.patch import ApiForpatch +{{/if}} +{{#if pathItem.trace}} +from {{packageName}}.paths.{{pathModule}}.trace import ApiFortrace +{{/if}} + + +class {{apiClassName}}( +{{#if pathItem.get}} + ApiForget, +{{/if}} +{{#if pathItem.put}} + ApiForput, +{{/if}} +{{#if pathItem.post}} + ApiForpost, +{{/if}} +{{#if pathItem.delete}} + ApiFordelete, +{{/if}} +{{#if pathItem.options}} + ApiForoptions, +{{/if}} +{{#if pathItem.head}} + ApiForhead, +{{/if}} +{{#if pathItem.patch}} + ApiForpatch, +{{/if}} +{{#if pathItem.trace}} + ApiFortrace, +{{/if}}): + pass diff --git a/modules/openapi-generator/src/main/resources/python/apis_path_to_api.handlebars b/modules/openapi-generator/src/main/resources/python/apis_path_to_api.handlebars new file mode 100644 index 0000000000..a52df9cf15 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/apis_path_to_api.handlebars @@ -0,0 +1,23 @@ +import typing_extensions + +from {{packageName}}.paths import PathValues +{{#each pathModuleToApiClassname}} +from {{packageName}}.apis.paths.{{@key}} import {{this}} +{{/each}} + +PathToApi = typing_extensions.TypedDict( + 'PathToApi', + { +{{#each pathEnumToApiClassname}} + PathValues.{{@key}}: {{this}}, +{{/each}} + } +) + +path_to_api = PathToApi( + { +{{#each pathEnumToApiClassname}} + PathValues.{{@key}}: {{this}}, +{{/each}} + } +) diff --git a/modules/openapi-generator/src/main/resources/python/apis_tag_to_api.handlebars b/modules/openapi-generator/src/main/resources/python/apis_tag_to_api.handlebars new file mode 100644 index 0000000000..dacbc478aa --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/apis_tag_to_api.handlebars @@ -0,0 +1,23 @@ +import typing_extensions + +from {{packageName}}.apis.tags import TagValues +{{#each tagModuleNameToApiClassname}} +from {{packageName}}.apis.tags.{{@key}} import {{this}} +{{/each}} + +TagToApi = typing_extensions.TypedDict( + 'TagToApi', + { +{{#each tagEnumToApiClassname}} + TagValues.{{@key}}: {{this}}, +{{/each}} + } +) + +tag_to_api = TagToApi( + { +{{#each tagEnumToApiClassname}} + TagValues.{{@key}}: {{this}}, +{{/each}} + } +) diff --git a/modules/openapi-generator/src/main/resources/python-experimental/comma.handlebars b/modules/openapi-generator/src/main/resources/python/comma.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/comma.handlebars rename to modules/openapi-generator/src/main/resources/python/comma.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/configuration.handlebars b/modules/openapi-generator/src/main/resources/python/configuration.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/configuration.handlebars rename to modules/openapi-generator/src/main/resources/python/configuration.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/doc_auth_partial.handlebars b/modules/openapi-generator/src/main/resources/python/doc_auth_partial.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/doc_auth_partial.handlebars rename to modules/openapi-generator/src/main/resources/python/doc_auth_partial.handlebars diff --git a/modules/openapi-generator/src/main/resources/python/endpoint.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint.handlebars new file mode 100644 index 0000000000..8190bd78e3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/endpoint.handlebars @@ -0,0 +1,463 @@ +# coding: utf-8 + +{{>partial_header}} + +from dataclasses import dataclass +import typing_extensions +import urllib3 +{{#with operation}} +{{#or headerParams bodyParam produces}} +from urllib3._collections import HTTPHeaderDict +{{/or}} +{{/with}} + +from {{packageName}} import api_client, exceptions +{{> model_templates/imports_schema_types }} +{{> model_templates/imports_schemas }} + +{{#unless isStub}} +from . import path + +{{/unless}} +{{#with operation}} +{{#if queryParams}} +{{> endpoint_parameter_schema_and_def xParams=queryParams xParamsName="Query" }} +{{/if}} +{{#if headerParams}} +{{> endpoint_parameter_schema_and_def xParams=headerParams xParamsName="Header" }} +{{/if}} +{{#if pathParams}} +{{> endpoint_parameter_schema_and_def xParams=pathParams xParamsName="Path" }} +{{/if}} +{{#if cookieParams}} +{{> endpoint_parameter_schema_and_def xParams=cookieParams xParamsName="Cookie" }} +{{/if}} +{{#with bodyParam}} +# body param +{{#each content}} +{{#with this.schema}} +{{> model_templates/schema }} +{{/with}} +{{/each}} + + +request_body_{{paramName}} = api_client.RequestBody( + content={ +{{#each content}} + '{{{@key}}}': api_client.MediaType({{#if this.schema}} + schema={{this.schema.baseName}}{{/if}}), +{{/each}} + }, +{{#if required}} + required=True, +{{/if}} +) +{{/with}} +{{#unless isStub}} +{{#each authMethods}} +{{#if @first}} +_auth = [ +{{/if}} + '{{name}}', +{{#if @last}} +] +{{/if}} +{{/each}} +{{#each servers}} +{{#if @first}} +_servers = ( +{{/if}} + { + 'url': "{{{url}}}", + 'description': "{{#unless description}}No description provided{{else}}{{{description}}}{{/unless}}", + {{#each variables}} + {{#if @first}} + 'variables': { + {{/if}} + '{{{name}}}': { + 'description': "{{#unless description}}No description provided{{else}}{{{description}}}{{/unless}}", + 'default_value': "{{{defaultValue}}}", + {{#each enumValues}} + {{#if @first}} + 'enum_values': [ + {{/if}} + "{{{.}}}"{{#unless @last}},{{/unless}} + {{#if @last}} + ] + {{/if}} + {{/each}} + }{{#unless @last}},{{/unless}} + {{#if @last}} + } + {{/if}} + {{/each}} + }, +{{#if @last}} +) +{{/if}} +{{/each}} +{{/unless}} +{{#each responses}} +{{#each responseHeaders}} +{{#with schema}} +{{> model_templates/schema }} +{{/with}} +{{#unless isStub}} +{{paramName}}_parameter = api_client.HeaderParameter( + name="{{baseName}}", +{{#if style}} + style=api_client.ParameterStyle.{{style}}, +{{/if}} +{{#if schema}} +{{#with schema}} + schema={{baseName}}, +{{/with}} +{{/if}} +{{#if required}} + required=True, +{{/if}} +{{#if isExplode}} + explode=True, +{{/if}} +) +{{/unless}} +{{/each}} +{{#each content}} +{{#with this.schema}} +{{> model_templates/schema }} +{{/with}} +{{/each}} +{{#if responseHeaders}} +ResponseHeadersFor{{code}} = typing_extensions.TypedDict( + 'ResponseHeadersFor{{code}}', + { +{{#each responseHeaders}} + '{{baseName}}': {{#with schema}}{{baseName}},{{/with}} +{{/each}} + } +) +{{/if}} + + +@dataclass +{{#if isDefault}} +class ApiResponseForDefault(api_client.ApiResponse): +{{else}} +class ApiResponseFor{{code}}(api_client.ApiResponse): +{{/if}} + response: urllib3.HTTPResponse +{{#and responseHeaders content}} + body: typing.Union[ +{{#each content}} +{{#if this.schema}} + {{this.schema.baseName}}, +{{else}} + schemas.Unset, +{{/if}} +{{/each}} + ] + headers: ResponseHeadersFor{{code}} +{{else}} +{{#or responseHeaders content}} +{{#if responseHeaders}} + headers: ResponseHeadersFor{{code}} + body: schemas.Unset = schemas.unset +{{else}} + body: typing.Union[ +{{#each content}} +{{#if this.schema}} + {{this.schema.baseName}}, +{{else}} + schemas.Unset, +{{/if}} +{{/each}} + ] + headers: schemas.Unset = schemas.unset +{{/if}} +{{/or}} +{{/and}} +{{#unless responseHeaders}} +{{#unless content}} + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset +{{/unless}} +{{/unless}} + + +{{#if isDefault}} +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +{{else}} +_response_for_{{code}} = api_client.OpenApiResponse( + response_cls=ApiResponseFor{{code}}, +{{/if}} +{{#each content}} +{{#if @first}} + content={ +{{/if}} + '{{{@key}}}': api_client.MediaType({{#if this.schema}} + schema={{this.schema.baseName}}{{/if}}), +{{#if @last}} + }, +{{/if}} +{{/each}} +{{#if responseHeaders}} + headers=[ +{{#each responseHeaders}} + {{paramName}}_parameter, +{{/each}} + ] +{{/if}} +) +{{/each}} +{{#unless isStub}} +_status_code_to_response = { +{{#each responses}} +{{#if isDefault}} + 'default': _response_for_default, +{{else}} + '{{code}}': _response_for_{{code}}, +{{/if}} +{{/each}} +} +{{/unless}} +{{#each produces}} +{{#if @first}} +_all_accept_content_types = ( +{{/if}} + '{{{this.mediaType}}}', +{{#if @last}} +) +{{/if}} +{{/each}} + + +class BaseApi(api_client.Api): +{{#if bodyParam}} + {{#each getContentTypeToOperation}} + {{> endpoint_args_baseapi_wrapper contentType=@key this=this}} + + {{/each}} + {{> endpoint_args_baseapi_wrapper contentType="null" this=this}} + +{{else}} + @typing.overload + def _{{operationId}}_oapg( + {{> endpoint_args isOverload=true skipDeserialization="False" contentType="null"}} +{{/if}} + + @typing.overload + def _{{operationId}}_oapg( + {{> endpoint_args isOverload=true skipDeserialization="True" contentType="null"}} + + @typing.overload + def _{{operationId}}_oapg( + {{> endpoint_args isOverload=true skipDeserialization="null" contentType="null"}} + + def _{{operationId}}_oapg( + {{> endpoint_args isOverload=false skipDeserialization="null" contentType="null"}} + """ + {{#if summary}} + {{summary}} + {{/if}} + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + {{#if queryParams}} + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + {{/if}} + {{#if headerParams}} + self._verify_typed_dict_inputs_oapg(RequestHeaderParams, header_params) + {{/if}} + {{#if pathParams}} + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + {{/if}} + {{#if cookieParams}} + self._verify_typed_dict_inputs_oapg(RequestCookieParams, cookie_params) + {{/if}} + used_path = path.value + {{#if pathParams}} + + _path_params = {} + for parameter in ( + {{#each pathParams}} + request_path_{{paramName}}, + {{/each}} + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + {{/if}} + {{#if queryParams}} + + prefix_separator_iterator = None + for parameter in ( + {{#each queryParams}} + request_query_{{paramName}}, + {{/each}} + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + {{/if}} + {{#or headerParams bodyParam produces}} + + _headers = HTTPHeaderDict() + {{else}} + {{/or}} + {{#if headerParams}} + for parameter in ( + {{#each headerParams}} + request_header_{{paramName}}, + {{/each}} + ): + parameter_data = header_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _headers.extend(serialized_data) + {{/if}} + # TODO add cookie handling + {{#if produces}} + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + {{/if}} + {{#with bodyParam}} + + {{#if required}} + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + {{/if}} + _fields = None + _body = None + {{#if required}} + {{> endpoint_body_serialization }} + {{else}} + if body is not schemas.unset: + {{> endpoint_body_serialization }} + {{/if}} + {{/with}} + {{#if servers}} + + host = self._get_host_oapg('{{operationId}}', _servers, host_index) + {{/if}} + + response = self.api_client.call_api( + resource_path=used_path, + method='{{httpMethod}}'.upper(), + {{#or headerParams bodyParam produces}} + headers=_headers, + {{/or}} + {{#if bodyParam}} + fields=_fields, + body=_body, + {{/if}} + {{#if hasAuthMethods}} + auth_settings=_auth, + {{/if}} + {{#if servers}} + host=host, + {{/if}} + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + {{#if hasDefaultResponse}} + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + {{else}} + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + {{/if}} + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class {{operationIdCamelCase}}(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + +{{#if bodyParam}} + {{#each getContentTypeToOperation}} + {{> endpoint_args_operationid_wrapper contentType=@key this=this}} + + {{/each}} + {{> endpoint_args_operationid_wrapper contentType="null" this=this}} + +{{else}} + @typing.overload + def {{operationId}}( + {{> endpoint_args isOverload=true skipDeserialization="False" contentType="null"}} +{{/if}} + + @typing.overload + def {{operationId}}( + {{> endpoint_args isOverload=true skipDeserialization="True" contentType="null"}} + + @typing.overload + def {{operationId}}( + {{> endpoint_args isOverload=true skipDeserialization="null" contentType="null"}} + + def {{operationId}}( + {{> endpoint_args isOverload=false skipDeserialization="null" contentType="null"}} + return self._{{operationId}}_oapg( + {{> endpoint_args_passed }} + ) + + +class ApiFor{{httpMethod}}(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + +{{#if bodyParam}} + {{#each getContentTypeToOperation}} + {{> endpoint_args_httpmethod_wrapper contentType=@key this=this}} + + {{/each}} + {{> endpoint_args_httpmethod_wrapper contentType="null" this=this}} + +{{else}} + @typing.overload + def {{httpMethod}}( + {{> endpoint_args isOverload=true skipDeserialization="False" contentType="null"}} +{{/if}} + + @typing.overload + def {{httpMethod}}( + {{> endpoint_args isOverload=true skipDeserialization="True" contentType="null"}} + + @typing.overload + def {{httpMethod}}( + {{> endpoint_args isOverload=true skipDeserialization="null" contentType="null"}} + + def {{httpMethod}}( + {{> endpoint_args isOverload=false skipDeserialization="null" contentType="null"}} + return self._{{operationId}}_oapg( + {{> endpoint_args_passed }} + ) + + +{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python/endpoint_args.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint_args.handlebars new file mode 100644 index 0000000000..bff216a72f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/endpoint_args.handlebars @@ -0,0 +1,141 @@ + self, +{{#if bodyParam}} + {{#if bodyParam.required}} + {{#with bodyParam}} + {{#eq ../contentType "null"}} + body: typing.Union[{{#each getContent}}{{#with this.schema}}{{baseName}},{{> model_templates/schema_python_types }}{{/with}}{{/each}}], + {{else}} + body: typing.Union[{{#each getContent}}{{#eq @key ../../contentType }}{{#with this.schema}}{{baseName}},{{> model_templates/schema_python_types }}{{/with}}{{/eq}}{{/each}}], + {{/eq}} + {{/with}} + {{#if isOverload}} + {{#eq skipDeserialization "True"}} + skip_deserialization: typing_extensions.Literal[True], + {{/eq}} + {{#neq contentType "null"}} + {{#with bodyParam}} + {{#each content}} + {{#eq @key ../../contentType}} + {{#if @first}} + content_type: typing_extensions.Literal["{{{@key}}}"] = ..., + {{else}} + content_type: typing_extensions.Literal["{{{@key}}}"], + {{/if}} + {{/eq}} + {{/each}} + {{/with}} + {{else}} + content_type: str = ..., + {{/neq}} + {{else}} + {{#with bodyParam}} + {{#each getContent}} + {{#if @first}} + content_type: str = '{{{@key}}}', + {{/if}} + {{/each}} + {{/with}} + {{/if}} + {{else}} + {{#if isOverload}} + {{#eq skipDeserialization "True"}} + skip_deserialization: typing_extensions.Literal[True], + {{/eq}} + {{#neq contentType "null"}} + {{#with bodyParam}} + {{#each getContent}} + {{#eq @key ../../contentType}} + {{#if @first}} + content_type: typing_extensions.Literal["{{{@key}}}"] = ..., + {{else}} + content_type: typing_extensions.Literal["{{{@key}}}"], + {{/if}} + {{/eq}} + {{/each}} + {{/with}} + {{else}} + content_type: str = ..., + {{/neq}} + {{else}} + {{#with bodyParam}} + {{#each getContent}} + {{#if @first}} + content_type: str = '{{{@key}}}', + {{/if}} + {{/each}} + {{/with}} + {{/if}} + {{#with bodyParam}} + {{#eq ../contentType "null"}} + body: typing.Union[{{#each getContent}}{{#with this.schema}}{{baseName}}, {{> model_templates/schema_python_types }}{{/with}}{{/each}}schemas.Unset] = schemas.unset, + {{else}} + body: typing.Union[{{#each getContent}}{{#eq @key ../../contentType }}{{#with this.schema}}{{baseName}}, {{> model_templates/schema_python_types }}{{/with}}{{/eq}}{{/each}}schemas.Unset] = schemas.unset, + {{/eq}} + {{/with}} + {{/if}} +{{/if}} +{{#if queryParams}} + query_params: RequestQueryParams = frozendict.frozendict(), +{{/if}} +{{#if headerParams}} + header_params: RequestHeaderParams = frozendict.frozendict(), +{{/if}} +{{#if pathParams}} + path_params: RequestPathParams = frozendict.frozendict(), +{{/if}} +{{#if cookieParams}} + cookie_params: RequestCookieParams = frozendict.frozendict(), +{{/if}} +{{#if produces}} + accept_content_types: typing.Tuple[str] = _all_accept_content_types, +{{/if}} +{{#if servers}} + host_index: typing.Optional[int] = None, +{{/if}} + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + {{#if isOverload}} + {{#eq skipDeserialization "False"}} + skip_deserialization: typing_extensions.Literal[False] = ..., + {{/eq}} + {{#eq skipDeserialization "null"}} + skip_deserialization: bool = ..., + {{/eq}} + {{else}} + skip_deserialization: bool = False, + {{/if}} +{{#eq skipDeserialization "True"}} +) -> api_client.ApiResponseWithoutDeserialization: ... +{{/eq}} +{{#eq skipDeserialization "False"}} +) -> {{#if getAllResponsesAreErrors}}api_client.ApiResponseWithoutDeserialization: ...{{else}}typing.Union[ + {{#each responses}} + {{#if isDefault}} + ApiResponseForDefault, + {{else}} + {{#if is2xx}} + ApiResponseFor{{code}}, + {{/if}} + {{/if}} + {{/each}} +]: ... + {{/if}} +{{/eq}} +{{#eq skipDeserialization "null"}} +{{#if isOverload}} +) -> typing.Union[ + {{#each responses}} + {{#if isDefault}} + ApiResponseForDefault, + {{else}} + {{#if is2xx}} + ApiResponseFor{{code}}, + {{/if}} + {{/if}} + {{/each}} + api_client.ApiResponseWithoutDeserialization, +]: ... +{{else}} +): +{{/if}} +{{/eq}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/endpoint_args_baseapi_wrapper.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint_args_baseapi_wrapper.handlebars new file mode 100644 index 0000000000..cd73d02e9c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/endpoint_args_baseapi_wrapper.handlebars @@ -0,0 +1,5 @@ +@typing.overload +{{#with this}} +def _{{operationId}}_oapg( +{{> endpoint_args isOverload=true skipDeserialization="False" contentType=contentType}} +{{/with}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/endpoint_args_httpmethod_wrapper.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint_args_httpmethod_wrapper.handlebars new file mode 100644 index 0000000000..f28bd735a5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/endpoint_args_httpmethod_wrapper.handlebars @@ -0,0 +1,5 @@ +@typing.overload +{{#with this}} +def {{httpMethod}}( +{{> endpoint_args isOverload=true skipDeserialization="False" contentType=contentType}} +{{/with}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/endpoint_args_operationid_wrapper.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint_args_operationid_wrapper.handlebars new file mode 100644 index 0000000000..47b5ea64ca --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/endpoint_args_operationid_wrapper.handlebars @@ -0,0 +1,5 @@ +@typing.overload +{{#with this}} +def {{operationId}}( +{{> endpoint_args isOverload=true skipDeserialization="False" contentType=contentType}} +{{/with}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/endpoint_args_passed.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint_args_passed.handlebars new file mode 100644 index 0000000000..8deb2cd260 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/endpoint_args_passed.handlebars @@ -0,0 +1,33 @@ +{{#if bodyParam}} +{{#with bodyParam}} +body=body, +{{/with}} +{{/if}} +{{#if queryParams}} +query_params=query_params, +{{/if}} +{{#if headerParams}} +header_params=header_params, +{{/if}} +{{#if pathParams}} +path_params=path_params, +{{/if}} +{{#if cookieParams}} +cookie_params=cookie_params, +{{/if}} +{{#with bodyParam}} +{{#each content}} +{{#if @first}} +content_type=content_type, +{{/if}} +{{/each}} +{{/with}} +{{#if produces}} +accept_content_types=accept_content_types, +{{/if}} +{{#if servers}} +host_index=host_index, +{{/if}} +stream=stream, +timeout=timeout, +skip_deserialization=skip_deserialization diff --git a/modules/openapi-generator/src/main/resources/python-experimental/endpoint_body_serialization.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint_body_serialization.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/endpoint_body_serialization.handlebars rename to modules/openapi-generator/src/main/resources/python/endpoint_body_serialization.handlebars diff --git a/modules/openapi-generator/src/main/resources/python/endpoint_parameter.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint_parameter.handlebars new file mode 100644 index 0000000000..8c18c997e3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/endpoint_parameter.handlebars @@ -0,0 +1,24 @@ +request_{{#if isQueryParam}}query{{/if}}{{#if isPathParam}}path{{/if}}{{#if isHeaderParam}}header{{/if}}{{#if isCookieParam}}cookie{{/if}}_{{paramName}} = api_client.{{#if isQueryParam}}Query{{/if}}{{#if isPathParam}}Path{{/if}}{{#if isHeaderParam}}Header{{/if}}{{#if isCookieParam}}Cookie{{/if}}Parameter( + name="{{baseName}}", +{{#if style}} + style=api_client.ParameterStyle.{{style}}, +{{/if}} +{{#if schema}} + {{#with schema}} + schema={{baseName}}, + {{/with}} +{{/if}} +{{#if getContent}} + content={ +{{#each getContent}} + "{{@key}}": {{#with this}}{{#with schema}}{{baseName}}{{/with}}{{/with}}, +{{/each}} + }, +{{/if}} +{{#if required}} + required=True, +{{/if}} +{{#if isExplode}} + explode=True, +{{/if}} +) diff --git a/modules/openapi-generator/src/main/resources/python/endpoint_parameter_schema_and_def.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint_parameter_schema_and_def.handlebars new file mode 100644 index 0000000000..313a64dc20 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/endpoint_parameter_schema_and_def.handlebars @@ -0,0 +1,56 @@ +# {{xParamsName}} params +{{#each xParams}} + {{#if schema}} + {{#with schema}} +{{> model_templates/schema }} + {{/with}} + {{else}} + {{#if getContent}} + {{#each getContent}} + {{#with this}} + {{#with schema}} +{{> model_templates/schema }} + {{/with}} + {{/with}} + {{/each}} + {{/if}} + {{/if}} +{{/each}} +RequestRequired{{xParamsName}}Params = typing_extensions.TypedDict( + 'RequestRequired{{xParamsName}}Params', + { +{{#each xParams}} +{{#if required}} +{{#if schema}} + '{{baseName}}': {{#with schema}}typing.Union[{{baseName}}, {{> model_templates/schema_python_types }}],{{/with}} +{{else}} + '{{baseName}}': {{#each getContent}}{{#with this}}{{#with schema}}typing.Union[{{baseName}}, {{> model_templates/schema_python_types }}],{{/with}}{{/with}}{{/each}} +{{/if}} +{{/if}} +{{/each}} + } +) +RequestOptional{{xParamsName}}Params = typing_extensions.TypedDict( + 'RequestOptional{{xParamsName}}Params', + { +{{#each xParams}} +{{#unless required}} +{{#if schema}} + '{{baseName}}': {{#with schema}}typing.Union[{{baseName}}, {{> model_templates/schema_python_types }}],{{/with}} +{{else}} + '{{baseName}}': {{#each getContent}}{{#with this}}{{#with schema}}typing.Union[{{baseName}}, {{> model_templates/schema_python_types }}],{{/with}}{{/with}}{{/each}} +{{/if}} +{{/unless}} +{{/each}} + }, + total=False +) + + +class Request{{xParamsName}}Params(RequestRequired{{xParamsName}}Params, RequestOptional{{xParamsName}}Params): + pass + + +{{#each xParams}} +{{> endpoint_parameter }} +{{/each}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/endpoint_stub.handlebars b/modules/openapi-generator/src/main/resources/python/endpoint_stub.handlebars new file mode 100644 index 0000000000..b84c7698d3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/endpoint_stub.handlebars @@ -0,0 +1 @@ +{{> endpoint isStub=true }} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/exceptions.handlebars b/modules/openapi-generator/src/main/resources/python/exceptions.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/exceptions.handlebars rename to modules/openapi-generator/src/main/resources/python/exceptions.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/git_push.sh.handlebars b/modules/openapi-generator/src/main/resources/python/git_push.sh.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/git_push.sh.handlebars rename to modules/openapi-generator/src/main/resources/python/git_push.sh.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/gitignore.handlebars b/modules/openapi-generator/src/main/resources/python/gitignore.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/gitignore.handlebars rename to modules/openapi-generator/src/main/resources/python/gitignore.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/gitlab-ci.handlebars b/modules/openapi-generator/src/main/resources/python/gitlab-ci.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/gitlab-ci.handlebars rename to modules/openapi-generator/src/main/resources/python/gitlab-ci.handlebars diff --git a/modules/openapi-generator/src/main/resources/python/model.handlebars b/modules/openapi-generator/src/main/resources/python/model.handlebars new file mode 100644 index 0000000000..54827ce889 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model.handlebars @@ -0,0 +1,11 @@ +# coding: utf-8 + +{{>partial_header}} + +{{#each models}} +{{#with model}} +{{> model_templates/imports_schema_types }} +{{> model_templates/schema }} +{{> model_templates/imports_schemas }} +{{/with}} +{{/each}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_doc.handlebars b/modules/openapi-generator/src/main/resources/python/model_doc.handlebars new file mode 100644 index 0000000000..ae96a37f42 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_doc.handlebars @@ -0,0 +1,9 @@ +{{#each models}} +{{#with model}} +# {{packageName}}.{{modelPackage}}.{{classFilename}}.{{classname}} +{{> schema_doc complexTypePrefix="" }} +{{/with}} +{{/each}} + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/modules/openapi-generator/src/main/resources/python/model_stub.handlebars b/modules/openapi-generator/src/main/resources/python/model_stub.handlebars new file mode 100644 index 0000000000..50700cf72d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_stub.handlebars @@ -0,0 +1 @@ +{{> model isStub=true }} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/classname.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/classname.handlebars new file mode 100644 index 0000000000..fbde863fae --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/classname.handlebars @@ -0,0 +1 @@ +{{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/composed_schemas.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/composed_schemas.handlebars new file mode 100644 index 0000000000..9deb056577 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/composed_schemas.handlebars @@ -0,0 +1,109 @@ +{{#with composedSchemas}} +{{#each allOf}} +{{#unless complexType}} +{{> model_templates/schema }} +{{/unless}} +{{/each}} +{{#each oneOf}} +{{#unless complexType}} +{{> model_templates/schema }} +{{/unless}} +{{/each}} +{{#each anyOf}} +{{#unless complexType}} +{{> model_templates/schema }} +{{/unless}} +{{/each}} +{{/with}} +{{#with composedSchemas}} +{{#if allOf}} + +@classmethod +@functools.lru_cache() +def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ +{{#each allOf}} +{{#if complexType}} + {{complexType}}, +{{else}} + {{#if nameInSnakeCase}} + cls.{{name}}, + {{else}} + cls.{{baseName}}, + {{/if}} +{{/if}} +{{/each}} + ] +{{/if}} +{{#if oneOf}} + +@classmethod +@functools.lru_cache() +def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ +{{#each oneOf}} +{{#if complexType}} + {{complexType}}, +{{else}} + {{#if nameInSnakeCase}} + cls.{{name}}, + {{else}} + cls.{{baseName}}, + {{/if}} +{{/if}} +{{/each}} + ] +{{/if}} +{{#if anyOf}} + +@classmethod +@functools.lru_cache() +def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ +{{#each anyOf}} +{{#if complexType}} + {{complexType}}, +{{else}} + {{#if nameInSnakeCase}} + cls.{{name}}, + {{else}} + cls.{{baseName}}, + {{/if}} +{{/if}} +{{/each}} + ] +{{/if}} +{{#if not}} +{{#with not}} +{{#if complexType}} + +@staticmethod +def {{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}() -> typing.Type['{{complexType}}']: + return {{complexType}} +{{else}} +{{> model_templates/schema }} +{{/if}} +{{/with}} +{{/if}} +{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/dict_partial.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/dict_partial.handlebars new file mode 100644 index 0000000000..9ff3e7c37e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/dict_partial.handlebars @@ -0,0 +1,58 @@ +{{#if getRequiredVarsMap}} +required = { +{{#each getRequiredVarsMap}} + "{{{@key}}}", +{{/each}} +} +{{/if}} +{{#if getHasDiscriminatorWithNonEmptyMapping}} +{{#with discriminator}} +{{#each mappedModels}} +{{#if @first}} + +@staticmethod +def discriminator(): + return { + '{{{propertyBaseName}}}': { +{{/if}} + '{{mappingName}}': {{{modelName}}}, +{{#if @last}} + } + } +{{/if}} +{{/each}} +{{/with}} +{{/if}} +{{#if vars}} + +class properties: +{{#each vars}} +{{#if complexType}} + + @staticmethod + def {{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}() -> typing.Type['{{complexType}}']: + return {{complexType}} +{{else}} + {{> model_templates/schema }} +{{/if}} +{{/each}} + __annotations__ = { +{{#each vars}} +{{#if nameInSnakeCase}} + "{{{baseName}}}": {{name}}, +{{else}} + "{{{baseName}}}": {{baseName}}, +{{/if}} +{{/each}} + } +{{/if}} +{{#with additionalProperties}} +{{#if complexType}} + +@staticmethod +def {{baseName}}() -> typing.Type['{{complexType}}']: + return {{complexType}} +{{else}} +{{> model_templates/schema }} +{{/if}} +{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/enums.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/enums.handlebars new file mode 100644 index 0000000000..8c3108e425 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/enums.handlebars @@ -0,0 +1,20 @@ +{{#with allowableValues}} +{{#each enumVars}} + +@schemas.classproperty +def {{name}}(cls): + {{#eq value "schemas.NoneClass.NONE"}} + return cls(None) + {{else}} + {{#eq value "schemas.BoolClass.TRUE"}} + return cls(True) + {{else}} + {{#eq value "schemas.BoolClass.FALSE"}} + return cls(False) + {{else}} + return cls({{{value}}}) + {{/eq}} + {{/eq}} + {{/eq}} +{{/each}} +{{/with}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/format_base.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/format_base.handlebars new file mode 100644 index 0000000000..9bbd87d8c8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/format_base.handlebars @@ -0,0 +1,27 @@ +{{#eq getFormat "uuid"}} +schemas.UUIDBase, +{{/eq}} +{{#eq getFormat "date"}} +schemas.DateBase, +{{/eq}} +{{#eq getFormat "date-time"}} +schemas.DateTimeBase, +{{/eq}} +{{#eq getFormat "number"}} +schemas.DecimalBase, +{{/eq}} +{{#eq getFormat "binary"}} +schemas.BinaryBase, +{{/eq}} +{{#eq getFormat "int32"}} +schemas.Int32Base, +{{/eq}} +{{#eq getFormat "int64"}} +schemas.Int64Base, +{{/eq}} +{{#eq getFormat "float"}} +schemas.Float32Base, +{{/eq}} +{{#eq getFormat "double"}} +schemas.Float64Base, +{{/eq}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/imports_schema_types.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/imports_schema_types.handlebars new file mode 100644 index 0000000000..522c8f2c93 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/imports_schema_types.handlebars @@ -0,0 +1,12 @@ +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from {{packageName}} import schemas # noqa: F401 diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/imports_schemas.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/imports_schemas.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/model_templates/imports_schemas.handlebars rename to modules/openapi-generator/src/main/resources/python/model_templates/imports_schemas.handlebars diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/list_partial.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/list_partial.handlebars new file mode 100644 index 0000000000..97c4003fe9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/list_partial.handlebars @@ -0,0 +1,10 @@ +{{#with items}} +{{#if complexType}} + +@staticmethod +def {{baseName}}() -> typing.Type['{{complexType}}']: + return {{complexType}} +{{else}} +{{> model_templates/schema }} +{{/if}} +{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/new.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/new.handlebars new file mode 100644 index 0000000000..eb47a54a03 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/new.handlebars @@ -0,0 +1,92 @@ +def __new__( + cls, +{{#if getHasMultipleTypes}} + *args: typing.Union[{{> model_templates/schema_python_types }}], +{{else}} +{{#if isArray }} + arg: typing.Union[typing.Tuple[{{#with items}}{{#if complexType}}'{{complexType}}'{{else}}typing.Union[MetaOapg.{{baseName}}, {{> model_templates/schema_python_types }}]{{/if}}{{/with}}], typing.List[{{#with items}}{{#if complexType}}'{{complexType}}'{{else}}typing.Union[MetaOapg.{{baseName}}, {{> model_templates/schema_python_types }}]{{/if}}{{/with}}]], +{{else}} + *args: typing.Union[{{> model_templates/schema_python_types }}], +{{/if}} +{{/if}} +{{#unless isNull}} +{{#if getHasRequired}} +{{#each getRequiredVarsMap}} +{{#with this}} +{{#unless nameInSnakeCase}} +{{#if complexType}} + {{baseName}}: '{{complexType}}', +{{else}} + {{baseName}}: typing.Union[MetaOapg.properties.{{baseName}}, {{> model_templates/schema_python_types }}], +{{/if}} +{{/unless}} +{{/with}} +{{/each}} +{{/if}} +{{/unless}} +{{#each vars}} +{{#unless nameInSnakeCase}} +{{#unless getRequired}} +{{#if complexType}} + {{baseName}}: typing.Union['{{complexType}}', schemas.Unset] = schemas.unset, +{{else}} + {{baseName}}: typing.Union[MetaOapg.properties.{{baseName}}, {{> model_templates/schema_python_types }}schemas.Unset] = schemas.unset, +{{/if}} +{{/unless}} +{{/unless}} +{{/each}} + _configuration: typing.Optional[schemas.Configuration] = None, +{{#with additionalProperties}} +{{#unless getIsBooleanSchemaFalse}} +{{#if complexType}} + **kwargs: '{{complexType}}', +{{else}} + **kwargs: typing.Union[MetaOapg.additional_properties, {{> model_templates/schema_python_types }}], +{{/if}} +{{/unless}} +{{else}} +{{#or isMap isAnyType}} + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], +{{/or}} +{{/with}} +) -> '{{> model_templates/classname }}': + return super().__new__( + cls, +{{#if getHasMultipleTypes}} + *args, +{{else}} +{{#if isArray }} + arg, +{{else}} + *args, +{{/if}} +{{/if}} +{{#unless isNull}} +{{#if getHasRequired}} +{{#each getRequiredVarsMap}} +{{#with this}} +{{#unless nameInSnakeCase}} + {{baseName}}={{baseName}}, +{{/unless}} +{{/with}} +{{/each}} +{{/if}} +{{/unless}} +{{#each vars}} +{{#unless getRequired}} +{{#unless nameInSnakeCase}} + {{baseName}}={{baseName}}, +{{/unless}} +{{/unless}} +{{/each}} + _configuration=_configuration, +{{#with additionalProperties}} +{{#unless getIsBooleanSchemaFalse}} + **kwargs, +{{/unless}} +{{else}} +{{#or isMap isAnyType}} + **kwargs, +{{/or}} +{{/with}} + ) diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/notes_msg.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/notes_msg.handlebars new file mode 100644 index 0000000000..43d1163b5c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/notes_msg.handlebars @@ -0,0 +1 @@ +{{#unless isArray}}{{#unless complexType}}{{#with allowableValues}}must be one of [{{#each enumVars}}{{#eq value "schemas.NoneClass.NONE"}}None{{else}}{{#eq value "schemas.BoolClass.TRUE"}}True{{else}}{{#eq value "schemas.BoolClass.FALSE"}}False{{else}}{{{value}}}{{/eq}}{{/eq}}{{/eq}}, {{/each}}] {{/with}}{{#if defaultValue}}{{#unless hasRequired}}if omitted the server will use the default value of {{{defaultValue}}}{{/unless}}{{/if}}{{#eq getFormat "uuid"}}value must be a uuid{{/eq}}{{#eq getFormat "date"}}value must conform to RFC-3339 full-date YYYY-MM-DD{{/eq}}{{#eq getFormat "date-time"}}value must conform to RFC-3339 date-time{{/eq}}{{#eq getFormat "number"}}value must be numeric and storable in decimal.Decimal{{/eq}}{{#eq getFormat "int32"}}value must be a 32 bit integer{{/eq}}{{#eq getFormat "int64"}}value must be a 64 bit integer{{/eq}}{{#eq getFormat "double"}}value must be a 64 bit float{{/eq}}{{#eq getFormat "float"}}value must be a 32 bit float{{/eq}}{{/unless}}{{/unless}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/payload_renderer.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/payload_renderer.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/model_templates/payload_renderer.handlebars rename to modules/openapi-generator/src/main/resources/python/model_templates/payload_renderer.handlebars diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/property_getitems_with_addprops.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/property_getitems_with_addprops.handlebars new file mode 100644 index 0000000000..6fd1d8a3a3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/property_getitems_with_addprops.handlebars @@ -0,0 +1,108 @@ +{{#if getRequiredVarsMap}} +{{#each getRequiredVarsMap}} +{{#with this}} + +@typing.overload +{{#if complexType}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> '{{complexType}}': ... +{{else}} +{{#if schemaIsFromAdditionalProperties}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.additional_properties: ... +{{else}} +{{#if nameInSnakeCase}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.properties.{{name}}: ... +{{else}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.properties.{{baseName}}: ... +{{/if}} +{{/if}} +{{/if}} +{{/with}} +{{/each}} +{{/if}} +{{#if vars}} +{{#each vars}} +{{#unless required}} + +@typing.overload +{{#if complexType}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> '{{complexType}}': ... +{{else}} +{{#if nameInSnakeCase}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.properties.{{name}}: ... +{{else}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.properties.{{baseName}}: ... +{{/if}} +{{/if}} +{{/unless}} +{{/each}} +{{/if}} +{{#or vars getRequiredVarsMap}} +{{#with additionalProperties}} +{{#unless getIsBooleanSchemaFalse}} + +@typing.overload +def __getitem__(self, name: str) -> {{#if complexType}}'{{complexType}}'{{else}}MetaOapg.{{baseName}}{{/if}}: ... +{{/unless}} +{{/with}} + +{{> model_templates/property_getitems_with_addprops_getitem methodName="__getitem__" }} +{{else}} +{{#not additionalProperties.getIsBooleanSchemaFalse}} + +{{> model_templates/property_getitems_with_addprops_getitem methodName="__getitem__" }} +{{/not}} +{{/or}} +{{#if getRequiredVarsMap}} +{{#each getRequiredVarsMap}} +{{#with this}} + +@typing.overload +{{#if complexType}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> '{{complexType}}': ... +{{else}} +{{#if schemaIsFromAdditionalProperties}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.additional_properties: ... +{{else}} +{{#if nameInSnakeCase}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.properties.{{name}}: ... +{{else}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.properties.{{baseName}}: ... +{{/if}} +{{/if}} +{{/if}} +{{/with}} +{{/each}} +{{/if}} +{{#if vars}} +{{#each vars}} +{{#unless required}} + +@typing.overload +{{#if complexType}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> typing.Union['{{complexType}}', schemas.Unset]: ... +{{else}} +{{#if nameInSnakeCase}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> typing.Union[MetaOapg.properties.{{name}}, schemas.Unset]: ... +{{else}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> typing.Union[MetaOapg.properties.{{baseName}}, schemas.Unset]: ... +{{/if}} +{{/if}} +{{/unless}} +{{/each}} +{{/if}} +{{#or vars getRequiredVarsMap}} +{{#with additionalProperties}} +{{#unless getIsBooleanSchemaFalse}} + +@typing.overload +def get_item_oapg(self, name: str) -> typing.Union[{{#if complexType}}'{{complexType}}'{{else}}MetaOapg.{{baseName}}{{/if}}, schemas.Unset]: ... +{{/unless}} +{{/with}} + +{{> model_templates/property_getitems_with_addprops_getitem methodName="get_item_oapg" }} +{{else}} +{{#not additionalProperties.getIsBooleanSchemaFalse}} + +{{> model_templates/property_getitems_with_addprops_getitem methodName="get_item_oapg" }} +{{/not}} +{{/or}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/property_getitems_with_addprops_getitem.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/property_getitems_with_addprops_getitem.handlebars new file mode 100644 index 0000000000..f35667373f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/property_getitems_with_addprops_getitem.handlebars @@ -0,0 +1,5 @@ +def {{methodName}}(self, name: typing.Union[{{#each getRequiredVarsMap}}{{#with this}}typing_extensions.Literal["{{{baseName}}}"], {{/with}}{{/each}}{{#each vars}}{{#unless required}}typing_extensions.Literal["{{{baseName}}}"], {{/unless}}{{/each}}{{#with additionalProperties}}{{#unless getIsBooleanSchemaFalse}}str, {{/unless}}{{/with}}]){{#not vars}}{{#not getRequiredVarsMap}}{{#with additionalProperties}}{{#unless getIsBooleanSchemaFalse}} -> {{#if complexType}}'{{complexType}}'{{else}}MetaOapg.{{baseName}}{{/if}}{{/unless}}{{/with}}{{/not}}{{/not}}: +{{#eq methodName "__getitem__"}} + # dict_instance[name] accessor +{{/eq}} + return super().{{methodName}}(name) diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/property_getitems_without_addprops.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/property_getitems_without_addprops.handlebars new file mode 100644 index 0000000000..efb37d4ca1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/property_getitems_without_addprops.handlebars @@ -0,0 +1,45 @@ +{{#if vars}} +{{#each vars}} + +@typing.overload +{{#if complexType}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> '{{complexType}}': ... +{{else}} +{{#if nameInSnakeCase}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.properties.{{name}}: ... +{{else}} +def __getitem__(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> MetaOapg.properties.{{baseName}}: ... +{{/if}} +{{/if}} +{{/each}} + +@typing.overload +def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + +def __getitem__(self, name: typing.Union[typing_extensions.Literal[{{#each vars}}"{{{baseName}}}", {{/each}}], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + +{{/if}} +{{#if vars}} +{{#each vars}} + +@typing.overload +{{#if complexType}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> {{#unless required}}typing.Union[{{/unless}}'{{complexType}}'{{#unless required}}, schemas.Unset]{{/unless}}: ... +{{else}} +{{#if nameInSnakeCase}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> {{#unless required}}typing.Union[{{/unless}}MetaOapg.properties.{{name}}{{#unless required}}, schemas.Unset]{{/unless}}: ... +{{else}} +def get_item_oapg(self, name: typing_extensions.Literal["{{{baseName}}}"]) -> {{#unless required}}typing.Union[{{/unless}}MetaOapg.properties.{{baseName}}{{#unless required}}, schemas.Unset]{{/unless}}: ... +{{/if}} +{{/if}} +{{/each}} + +@typing.overload +def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + +def get_item_oapg(self, name: typing.Union[typing_extensions.Literal[{{#each vars}}"{{{baseName}}}", {{/each}}], str]): + return super().get_item_oapg(name) + +{{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/property_type_hints.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/property_type_hints.handlebars new file mode 100644 index 0000000000..395c6e2aea --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/property_type_hints.handlebars @@ -0,0 +1,13 @@ +{{#if getRequiredVarsMap}} + +{{#if additionalProperties}} +{{> model_templates/property_type_hints_required }} +{{else}} +{{> model_templates/property_type_hints_required addPropsUnset=true }} +{{/if}} +{{/if}} +{{#if additionalProperties}} +{{> model_templates/property_getitems_with_addprops }} +{{else}} +{{> model_templates/property_getitems_without_addprops }} +{{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/property_type_hints_required.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/property_type_hints_required.handlebars new file mode 100644 index 0000000000..2a265d61d7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/property_type_hints_required.handlebars @@ -0,0 +1,19 @@ +{{#each getRequiredVarsMap}} +{{#with this}} +{{#unless nameInSnakeCase}} +{{#if complexType}} +{{baseName}}: '{{complexType}}' +{{else}} +{{#if schemaIsFromAdditionalProperties}} +{{#if addPropsUnset}} +{{baseName}}: schemas.AnyTypeSchema +{{else}} +{{baseName}}: MetaOapg.additional_properties +{{/if}} +{{else}} +{{baseName}}: MetaOapg.properties.{{baseName}} +{{/if}} +{{/if}} +{{/unless}} +{{/with}} +{{/each}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/schema.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/schema.handlebars new file mode 100644 index 0000000000..6f9d565ada --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/schema.handlebars @@ -0,0 +1,42 @@ +{{#if composedSchemas}} + {{#if getIsBooleanSchemaFalse}} +{{> model_templates/var_equals_cls }} + {{else}} +{{> model_templates/schema_composed_or_anytype }} + {{/if}} +{{/if}} +{{#unless composedSchemas}} + {{#if getHasMultipleTypes}} +{{> model_templates/schema_composed_or_anytype }} + {{else}} + {{#or isMap isArray isAnyType}} + {{#if isMap}} + {{#or hasVars hasValidation getRequiredVarsMap getHasDiscriminatorWithNonEmptyMapping additionalProperties }} +{{> model_templates/schema_dict }} + {{else}} +{{> model_templates/var_equals_cls }} + {{/or}} + {{/if}} + {{#if isArray}} + {{#or hasItems hasValidation}} +{{> model_templates/schema_list }} + {{else}} +{{> model_templates/var_equals_cls }} + {{/or}} + {{/if}} + {{#if isAnyType}} + {{#or isEnum hasVars hasValidation getRequiredVarsMap getHasDiscriminatorWithNonEmptyMapping items getFormat}} +{{> model_templates/schema_composed_or_anytype }} + {{else}} +{{> model_templates/var_equals_cls }} + {{/or}} + {{/if}} + {{else}} + {{#or isEnum hasValidation}} +{{> model_templates/schema_simple }} + {{else}} +{{> model_templates/var_equals_cls }} + {{/or}} + {{/or}} + {{/if}} +{{/unless}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/schema_accessed_types.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/schema_accessed_types.handlebars new file mode 100644 index 0000000000..8d0dcc0f4b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/schema_accessed_types.handlebars @@ -0,0 +1 @@ +{{#if isAnyType}}frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO{{/if}}{{#if isArray}}tuple, {{/if}}{{#if isMap}}frozendict.frozendict, {{/if}}{{#if isNull}}NoneClass, {{/if}}{{#if isString }}{{#neq format "binary"}}str, {{/neq}}{{#eq format "binary"}}bytes, FileIO, {{/eq}}{{/if}}{{#or isInteger isNumber}}decimal.Decimal, {{/or}}{{#if isBoolean}}BoolClass, {{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/schema_composed_or_anytype.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/schema_composed_or_anytype.handlebars new file mode 100644 index 0000000000..8c7b667493 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/schema_composed_or_anytype.handlebars @@ -0,0 +1,71 @@ + + +class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}}( +{{#if getIsAnyType}} + {{#if getFormat}} + {{> model_templates/format_base }} + {{/if}} + {{#if composedSchemas}} + schemas.ComposedSchema, + {{else}} + schemas.AnyTypeSchema, + {{/if}} +{{else}} + {{#if composedSchemas}} + schemas.ComposedBase, + {{/if}} + {{#if isEnum}} + schemas.EnumBase, + {{/if}} + {{> model_templates/xbase_schema }} +{{/if}} +): +{{#if this.classname}} + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. +{{#if description}} + + {{{unescapedDescription}}} +{{/if}} + """ +{{/if}} +{{#or hasValidation composedSchemas getItems additionalProperties getRequiredVarsMap getHasDiscriminatorWithNonEmptyMapping vars getFormat isEnum}} + + + class MetaOapg: +{{#if getFormat}} + format = '{{getFormat}}' +{{/if}} +{{#if isEnum}} +{{#with allowableValues}} + enum_value_to_name = { +{{#each enumVars}} + {{{value}}}: "{{name}}", +{{/each}} + } +{{/with}} +{{/if}} +{{#if getItems}} + {{> model_templates/list_partial }} +{{/if}} +{{#or additionalProperties getRequiredVarsMap getHasDiscriminatorWithNonEmptyMapping vars}} + {{> model_templates/dict_partial }} +{{/or}} +{{#unless isStub}} +{{#if hasValidation}} + {{> model_templates/validations }} +{{/if}} +{{/unless}} +{{#if composedSchemas}} + {{> model_templates/composed_schemas }} +{{/if}} +{{/or}} +{{#if isEnum}} + {{> model_templates/enums }} +{{/if}} + + {{> model_templates/property_type_hints }} + + {{> model_templates/new }} diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/schema_dict.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/schema_dict.handlebars new file mode 100644 index 0000000000..1bee51b306 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/schema_dict.handlebars @@ -0,0 +1,35 @@ + + +class {{> model_templates/classname }}( + schemas.DictSchema +): +{{#if this.classname}} + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. +{{#if description}} + + {{{unescapedDescription}}} +{{/if}} + """ +{{/if}} +{{#if isStub}} +{{#or additionalProperties getRequiredVarsMap getHasDiscriminatorWithNonEmptyMapping vars}} + + + class MetaOapg: + {{> model_templates/dict_partial }} +{{/or}} +{{else}} +{{#or additionalProperties getRequiredVarsMap getHasDiscriminatorWithNonEmptyMapping vars hasValidation}} + + + class MetaOapg: + {{> model_templates/dict_partial }} + {{> model_templates/validations }} +{{/or}} +{{/if}} + {{> model_templates/property_type_hints }} + + {{> model_templates/new }} diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/schema_list.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/schema_list.handlebars new file mode 100644 index 0000000000..ae52b3e923 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/schema_list.handlebars @@ -0,0 +1,39 @@ + + +class {{> model_templates/classname }}( + schemas.ListSchema +): +{{#if this.classname}} + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. +{{#if description}} + + {{{unescapedDescription}}} +{{/if}} + """ +{{/if}} +{{#if isStub}} +{{#if items}} + + + class MetaOapg: + {{> model_templates/list_partial }} +{{/if}} +{{else}} +{{#or getItems hasValidation}} + + + class MetaOapg: +{{#if hasValidation}} + {{> model_templates/validations }} +{{/if}} + {{> model_templates/list_partial }} +{{/or}} +{{/if}} + + {{> model_templates/new }} + + def __getitem__(self, i: int) -> {{#with items}}{{#if complexType}}'{{complexType}}'{{else}}MetaOapg.items{{/if}}{{/with}}: + return super().__getitem__(i) diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/schema_python_types.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/schema_python_types.handlebars new file mode 100644 index 0000000000..613e586130 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/schema_python_types.handlebars @@ -0,0 +1 @@ +{{#if isAnyType}}dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, {{/if}}{{#if isArray}}list, tuple, {{/if}}{{#if isMap}}dict, frozendict.frozendict, {{/if}}{{#if isNull}}None, {{/if}}{{#if isString }}{{#neq format "binary"}}str, {{/neq}}{{#eq format "date"}}date, {{/eq}}{{#eq format "date-time"}}datetime, {{/eq}}{{#eq format "uuid"}}uuid.UUID, {{/eq}}{{#eq format "binary"}}bytes, io.FileIO, io.BufferedReader, {{/eq}}{{/if}}{{#if isInteger}}decimal.Decimal, int, {{/if}}{{#if isNumber}}decimal.Decimal, int, float, {{/if}}{{#if isBoolean}}bool, {{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/schema_simple.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/schema_simple.handlebars new file mode 100644 index 0000000000..0d880043e4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/schema_simple.handlebars @@ -0,0 +1,49 @@ + + +class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}}( +{{#if isEnum}} + schemas.EnumBase, +{{/if}} + {{> model_templates/xbase_schema }} +): +{{#if this.classname}} + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. +{{#if description}} + + {{{unescapedDescription}}} +{{/if}} + """ +{{/if}} +{{#unless isStub}} +{{#or hasValidation isEnum getFormat}} + + + class MetaOapg: +{{#if getFormat}} + format = '{{getFormat}}' +{{/if}} + {{> model_templates/validations }} +{{#if isEnum}} +{{#with allowableValues}} + enum_value_to_name = { +{{#each enumVars}} + {{{value}}}: "{{name}}", +{{/each}} + } +{{/with}} +{{/if}} +{{/or}} +{{/unless}} +{{#if isEnum}} + {{> model_templates/enums }} +{{/if}} +{{#if isStub}} +{{#if hasValidation}} +{{#unless isEnum}} + pass +{{/unless}} +{{/if}} +{{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/validations.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/validations.handlebars new file mode 100644 index 0000000000..7e4909e1d9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/validations.handlebars @@ -0,0 +1,48 @@ +{{#neq getUniqueItemsBoolean null}} +unique_items = {{#if getUniqueItemsBoolean}}True{{else}}False{{/if}} +{{/neq}} +{{#neq maxLength null}} +max_length = {{maxLength}} +{{/neq}} +{{#neq minLength null}} +min_length = {{minLength}} +{{/neq}} +{{#neq maxItems null}} +max_items = {{maxItems}} +{{/neq}} +{{#neq minItems null}} +min_items = {{minItems}} +{{/neq}} +{{#neq maxProperties null }} +max_properties = {{maxProperties}} +{{/neq}} +{{#neq minProperties null}} +min_properties = {{minProperties}} +{{/neq}} +{{#neq maximum null}} +{{#if exclusiveMaximum}}exclusive_maximum{{/if}}inclusive_maximum{{#unless exclusiveMaximum}}{{/unless}} = {{maximum}} +{{/neq}} +{{#neq minimum null}} +{{#if exclusiveMinimum}}exclusive_minimum{{/if}}inclusive_minimum{{#unless exclusiveMinimum}}{{/unless}} = {{minimum}} +{{/neq}} +{{#neq pattern null}} +regex=[{ +{{#if vendorExtensions.x-regex}} + 'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501 +{{else}} + 'pattern': r'{{{pattern}}}', # noqa: E501 +{{/if}} +{{#each vendorExtensions.x-modifiers}} +{{#if @first}} + 'flags': ( +{{/if}} + {{#unless @first}}| {{/unless}}re.{{.}} +{{#if @last}} + ) +{{/if}} +{{/each}} +}] +{{/neq}} +{{#neq multipleOf null}} +multiple_of = {{multipleOf}} +{{/neq}} diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/var_equals_cls.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/var_equals_cls.handlebars new file mode 100644 index 0000000000..4e1177d37b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/var_equals_cls.handlebars @@ -0,0 +1 @@ +{{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}} = {{#or getIsBooleanSchemaTrue getIsBooleanSchemaFalse}}{{#if getIsBooleanSchemaTrue}}schemas.AnyTypeSchema{{else}}schemas.NotAnyTypeSchema{{/if}}{{else}}{{#if complexType}}{{complexType}}{{else}}schemas.{{#if isNullable}}Nullable{{/if}}{{#if getIsNull}}None{{/if}}{{#if isAnyType}}AnyType{{/if}}{{#if isMap}}Dict{{/if}}{{#if isArray}}List{{/if}}{{#if isString}}{{#eq format "date"}}Date{{/eq}}{{#eq format "date-time"}}DateTime{{/eq}}{{#eq format "uuid"}}UUID{{/eq}}{{#eq format "number"}}Decimal{{/eq}}{{#eq format "binary"}}Binary{{/eq}}{{#neq format "date"}}{{#neq format "date-time"}}{{#neq format "uuid"}}{{#neq format "number"}}{{#neq format "binary"}}Str{{/neq}}{{/neq}}{{/neq}}{{/neq}}{{/neq}}{{/if}}{{#if isInteger}}{{#eq format "int32"}}Int32{{/eq}}{{#eq format "int64"}}Int64{{/eq}}{{#neq format "int32"}}{{#neq format "int64"}}Int{{/neq}}{{/neq}}{{/if}}{{#if isNumber}}{{#eq format "float"}}Float32{{/eq}}{{#eq format "double"}}Float64{{/eq}}{{#neq format "float"}}{{#neq format "double"}}Number{{/neq}}{{/neq}}{{/if}}{{#if isBoolean}}Bool{{/if}}Schema{{/if}}{{/or}} diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/xbase_schema.handlebars b/modules/openapi-generator/src/main/resources/python/model_templates/xbase_schema.handlebars new file mode 100644 index 0000000000..d9543507d7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/xbase_schema.handlebars @@ -0,0 +1,109 @@ +{{#if isArray}} +schemas.List{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} +{{/if}} +{{#if isMap}} +schemas.Dict{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} +{{/if}} +{{#if isString}} +{{#if getHasMultipleTypes}} +{{#eq format "date"}} +schemas.DateBase, +{{/eq}} +{{#eq format "date-time"}} +schemas.DateTimeBase, +{{/eq}} +{{#eq format "uuid"}} +schemas.UUIDBase, +{{/eq}} +{{#eq format "number"}} +schemas.DecimalBase, +{{/eq}} +{{#eq format "binary"}} +schemas.BinaryBase, +{{/eq}} +schemas.StrBase, +{{else}} +{{#eq format "date"}} +schemas.DateSchema +{{/eq}} +{{#eq format "date-time"}} +schemas.DateTimeSchema +{{/eq}} +{{#eq format "uuid"}} +schemas.UUIDSchema +{{/eq}} +{{#eq format "number"}} +schemas.DecimalSchema +{{/eq}} +{{#eq format "binary"}} +schemas.BinarySchema +{{/eq}} +{{#neq format "date"}} +{{#neq format "date-time"}} +{{#neq format "uuid"}} +{{#neq format "number"}} +{{#neq format "binary"}} +schemas.StrSchema +{{/neq}} +{{/neq}} +{{/neq}} +{{/neq}} +{{/neq}} +{{/if}} +{{/if}} +{{#if isNumber}} +{{#if getHasMultipleTypes}} +{{#eq format "float"}} +schemas.Float32Base, +{{/eq}} +{{#eq format "double"}} +schemas.Float64Base, +{{/eq}} +schemas.NumberBase, +{{else}} +{{#eq format "float"}} +schemas.Float32Schema +{{/eq}} +{{#eq format "double"}} +schemas.Float64Schema +{{/eq}} +{{#neq format "float"}} +{{#neq format "double"}} +schemas.NumberSchema +{{/neq}} +{{/neq}} +{{/if}} +{{/if}} +{{#if isInteger}} +{{#if getHasMultipleTypes}} +{{#eq format "int32"}} +schemas.Int32Base, +{{/eq}} +{{#eq format "int64"}} +schemas.Int64Base, +{{/eq}} +schemas.IntBase, +{{else}} +{{#eq format "int32"}} +schemas.Int32Schema +{{/eq}} +{{#eq format "int64"}} +schemas.Int64Schema +{{/eq}} +{{#neq format "int32"}} +{{#neq format "int64"}} +schemas.IntSchema +{{/neq}} +{{/neq}} +{{/if}} +{{/if}} +{{#if isBoolean}} +schemas.Bool{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} +{{/if}} +{{#if isNull}} +schemas.None{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} +{{/if}} +{{#if getHasMultipleTypes}} +schemas.Schema, +schemas.{{#if isNull}}None{{/if}}{{#if isMap}}FrozenDict{{/if}}{{#if isArray}}Tuple{{/if}}{{#if isString }}Str{{/if}}{{#or isInteger isNumber}}Decimal{{/or}}{{#if isBoolean}}Bool{{/if}}Mixin +{{/if}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_test.handlebars b/modules/openapi-generator/src/main/resources/python/model_test.handlebars similarity index 91% rename from modules/openapi-generator/src/main/resources/python-experimental/model_test.handlebars rename to modules/openapi-generator/src/main/resources/python/model_test.handlebars index 174fe3a176..9f6de3a835 100644 --- a/modules/openapi-generator/src/main/resources/python-experimental/model_test.handlebars +++ b/modules/openapi-generator/src/main/resources/python/model_test.handlebars @@ -20,7 +20,7 @@ class Test{{classname}}(unittest.TestCase): def test_{{@key}}_{{#if valid}}passes{{else}}fails{{/if}}(self): # {{description}} {{#if valid}} - {{classname}}._from_openapi_data( + {{classname}}.from_openapi_data_oapg( {{#with data}} {{> model_templates/payload_renderer endChar=',' }} {{/with}} @@ -28,7 +28,7 @@ class Test{{classname}}(unittest.TestCase): ) {{else}} with self.assertRaises(({{packageName}}.ApiValueError, {{packageName}}.ApiTypeError)): - {{classname}}._from_openapi_data( + {{classname}}.from_openapi_data_oapg( {{#with data}} {{> model_templates/payload_renderer endChar=','}} {{/with}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/partial_header.handlebars b/modules/openapi-generator/src/main/resources/python/partial_header.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/partial_header.handlebars rename to modules/openapi-generator/src/main/resources/python/partial_header.handlebars diff --git a/modules/openapi-generator/src/main/resources/python/required_libraries.handlebars b/modules/openapi-generator/src/main/resources/python/required_libraries.handlebars new file mode 100644 index 0000000000..f8395307a8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/required_libraries.handlebars @@ -0,0 +1,16 @@ +{{#if asyncio}} +{{#if quoted}}"{{/if}}aiohttp >= 3.0.0{{#if quoted}}",{{/if}} +{{/if}} +{{#if quoted}}"{{/if}}certifi >= 14.5.14{{#if quoted}}",{{/if}} +{{#if quoted}}"{{/if}}frozendict ~= 2.3.4{{#if quoted}}",{{/if}} +{{#if hasHttpSignatureMethods}} +{{#if quoted}}"{{/if}}pem >= 19.3.0{{#if quoted}}",{{/if}} +{{#if quoted}}"{{/if}}pycryptodome >= 3.9.0{{#if quoted}}",{{/if}} +{{/if}} +{{#if quoted}}"{{/if}}python-dateutil ~= 2.7.0{{#if quoted}}",{{/if}} +{{#if quoted}}"{{/if}}setuptools >= 21.0.0{{#if quoted}}",{{/if}} +{{#if tornado}} +{{#if quoted}}"{{/if}}tornado >= 4.2{{#if quoted}}",{{/if}} +{{/if}} +{{#if quoted}}"{{/if}}typing_extensions ~= 4.3.0{{#if quoted}}",{{/if}} +{{#if quoted}}"{{/if}}urllib3 ~= 1.26.7{{#if quoted}}",{{/if}} diff --git a/modules/openapi-generator/src/main/resources/python/requirements.handlebars b/modules/openapi-generator/src/main/resources/python/requirements.handlebars new file mode 100644 index 0000000000..b1f24de150 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/requirements.handlebars @@ -0,0 +1 @@ +{{> required_libraries quoted=false }} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/rest.handlebars b/modules/openapi-generator/src/main/resources/python/rest.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/rest.handlebars rename to modules/openapi-generator/src/main/resources/python/rest.handlebars diff --git a/modules/openapi-generator/src/main/resources/python/schema_doc.handlebars b/modules/openapi-generator/src/main/resources/python/schema_doc.handlebars new file mode 100644 index 0000000000..8e67813ed6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/schema_doc.handlebars @@ -0,0 +1,136 @@ + +{{#if description}} +{{&description}} + +{{/if}} +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{> model_templates/schema_python_types }} | {{> model_templates/schema_accessed_types }} | {{#if description}}{{description}}{{/if}} | {{> model_templates/notes_msg }} +{{#or vars additionalProperties}} + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- + {{#each getRequiredVarsMap}} +**{{#with this}}{{#unless complexType}}{{#or isArray isMap composedSchemas}}[{{/or}}{{/unless}}{{/with}}{{{@key}}}{{#with this}}{{#unless complexType}}{{#or isArray isMap composedSchemas}}](#{{baseName}}){{/or}}{{/unless}}{{/with}}** | {{#with this}}{{#unless complexType}}{{> model_templates/schema_python_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#unless complexType}}{{> model_templates/schema_accessed_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#if description}}{{description}}{{/if}} | {{> model_templates/notes_msg }}{{/with}} + {{/each}} + {{#each vars}} + {{#unless required}} +**{{#unless complexType}}{{#or isArray isMap composedSchemas}}[{{/or}}{{/unless}}{{baseName}}{{#unless complexType}}{{#or isArray isMap composedSchemas}}](#{{baseName}}){{/or}}{{/unless}}** | {{#unless complexType}}{{> model_templates/schema_python_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#unless complexType}}{{> model_templates/schema_accessed_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#if description}}{{description}}{{/if}} | [optional] {{> model_templates/notes_msg }} + {{/unless}} + {{/each}} + {{#with additionalProperties}} + {{#unless getIsBooleanSchemaFalse}} + {{#if getIsBooleanSchemaTrue}} +**any_string_name** | {{> model_templates/schema_python_types }} | {{> model_templates/schema_accessed_types }} | any string name can be used but the value must be the correct type{{#if description}} {{description}}{{/if}} | [optional] + {{else}} +**{{#unless complexType}}{{#or isArray isMap composedSchemas}}[{{/or}}{{/unless}}any_string_name{{#unless complexType}}{{#or isArray isMap composedSchemas}}](#any_string_name){{/or}}{{/unless}}** | {{#unless complexType}}{{> model_templates/schema_python_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#unless complexType}}{{> model_templates/schema_accessed_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | any string name can be used but the value must be the correct type{{#if description}} {{description}}{{/if}} | [optional] {{> model_templates/notes_msg }} + {{/if}} + {{/unless}} + {{else}} +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + {{/with}} +{{/or}} +{{#each vars}} +{{#unless complexType}} +{{#or isArray isMap composedSchemas}} + +# {{baseName}} +{{> schema_doc }} +{{/or}} +{{/unless}} +{{/each}} +{{#with additionalProperties}} +{{#unless getIsBooleanSchemaFalse}} +{{#unless getIsBooleanSchemaTrue}} +{{#unless complexType}} +{{#or isArray isMap composedSchemas}} + +# any_string_name +{{> schema_doc }} +{{/or}} +{{/unless}} +{{/unless}} +{{/unless}} +{{/with}} +{{#if items}} + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +{{#with items}} +{{#unless complexType}}{{#or isArray isMap composedSchemas}}[{{/or}}{{baseName}}{{#or isArray isMap composedSchemas}}](#{{baseName}}){{/or}}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#unless complexType}}{{> model_templates/schema_python_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#unless complexType}}{{> model_templates/schema_accessed_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#if description}}{{description}}{{/if}} | {{> model_templates/notes_msg }} +{{#unless complexType}} +{{#or isArray isMap composedSchemas}} + +# {{baseName}} +{{> schema_doc }} +{{/or}} +{{/unless}} +{{/with}} +{{/if}} +{{#if composedSchemas}} +{{#with composedSchemas}} + +### Composed Schemas (allOf/anyOf/oneOf/not) +{{#if allOf}} +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +{{#each allOf}} +{{#if complexType}}[{{dataType}}]({{complexTypePrefix}}{{complexType}}.md){{else}}[{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}](#{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}){{/if}} | {{#unless complexType}}{{> model_templates/schema_python_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#unless complexType}}{{> model_templates/schema_accessed_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#if description}}{{description}}{{/if}} | {{> model_templates/notes_msg }} +{{/each}} +{{#each allOf}} +{{#unless complexType}} + +# {{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}} +{{> schema_doc }} +{{/unless}} +{{/each}} +{{/if}} +{{#if anyOf}} +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +{{#each anyOf}} +{{#if complexType}}[{{dataType}}]({{complexTypePrefix}}{{complexType}}.md){{else}}[{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}](#{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}){{/if}} | {{#unless complexType}}{{> model_templates/schema_python_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#unless complexType}}{{> model_templates/schema_accessed_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#if description}}{{description}}{{/if}} | {{> model_templates/notes_msg }} +{{/each}} +{{#each anyOf}} +{{#unless complexType}} + +# {{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}} +{{> schema_doc }} +{{/unless}} +{{/each}} +{{/if}} +{{#if oneOf}} +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +{{#each oneOf}} +{{#if complexType}}[{{dataType}}]({{complexTypePrefix}}{{complexType}}.md){{else}}[{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}](#{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}){{/if}} | {{#unless complexType}}{{> model_templates/schema_python_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#unless complexType}}{{> model_templates/schema_accessed_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#if description}}{{description}}{{/if}} | {{> model_templates/notes_msg }} +{{/each}} +{{#each oneOf}} +{{#unless complexType}} + +# {{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}} +{{> schema_doc }} +{{/unless}} +{{/each}} +{{/if}} +{{#if not}} +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +{{#with not}} +{{#if complexType}}[{{dataType}}]({{complexTypePrefix}}{{complexType}}.md){{else}}[{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}](#{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}){{/if}} | {{#unless complexType}}{{> model_templates/schema_python_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#unless complexType}}{{> model_templates/schema_accessed_types }}{{/unless}}{{#if complexType}}[**{{dataType}}**]({{complexTypePrefix}}{{complexType}}.md){{/if}} | {{#if description}}{{description}}{{/if}} | {{> model_templates/notes_msg }} +{{#unless complexType}} + +# {{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}} +{{> schema_doc }} +{{/unless}} +{{/with}} +{{/if}} +{{/with}} +{{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/schemas.handlebars b/modules/openapi-generator/src/main/resources/python/schemas.handlebars new file mode 100644 index 0000000000..e61dd99ac7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/schemas.handlebars @@ -0,0 +1,2495 @@ +# coding: utf-8 + +{{>partial_header}} + +from collections import defaultdict +from datetime import date, datetime, timedelta # noqa: F401 +import functools +import decimal +import io +import re +import types +import typing +import uuid + +from dateutil.parser.isoparser import isoparser, _takes_ascii +import frozendict + +from {{packageName}}.exceptions import ( + ApiTypeError, + ApiValueError, +) +from {{packageName}}.configuration import ( + Configuration, +) + + +class Unset(object): + """ + An instance of this class is set as the default value for object type(dict) properties that are optional + When a property has an unset value, that property will not be assigned in the dict + """ + pass + +unset = Unset() + +none_type = type(None) +file_type = io.IOBase + + +class FileIO(io.FileIO): + """ + A class for storing files + Note: this class is not immutable + """ + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader]): + if isinstance(arg, (io.FileIO, io.BufferedReader)): + if arg.closed: + raise ApiValueError('Invalid file state; file is closed and must be open') + arg.close() + inst = super(FileIO, cls).__new__(cls, arg.name) + super(FileIO, inst).__init__(arg.name) + return inst + raise ApiValueError('FileIO must be passed arg which contains the open file') + + def __init__(self, arg: typing.Union[io.FileIO, io.BufferedReader]): + pass + + +def update(d: dict, u: dict): + """ + Adds u to d + Where each dict is defaultdict(set) + """ + if not u: + return d + for k, v in u.items(): + if k not in d: + d[k] = v + else: + d[k] = d[k] | v + + +class ValidationMetadata(frozendict.frozendict): + """ + A class storing metadata that is needed to validate OpenApi Schema payloads + """ + def __new__( + cls, + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), + from_server: bool = False, + configuration: typing.Optional[Configuration] = None, + seen_classes: typing.FrozenSet[typing.Type] = frozenset(), + validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]] = frozendict.frozendict() + ): + """ + Args: + path_to_item: the path to the current data being instantiated. + For {'a': [1]} if the code is handling, 1, then the path is ('args[0]', 'a', 0) + This changes from location to location + from_server: whether or not this data came form the server + True when receiving server data + False when instantiating model with client side data not form the server + This does not change from location to location + configuration: the Configuration instance to use + This is needed because in Configuration: + - one can disable validation checking + This does not change from location to location + seen_classes: when deserializing data that matches multiple schemas, this is used to store + the schemas that have been traversed. This is used to stop processing when a cycle is seen. + This changes from location to location + validated_path_to_schemas: stores the already validated schema classes for a given path location + This does not change from location to location + """ + return super().__new__( + cls, + path_to_item=path_to_item, + from_server=from_server, + configuration=configuration, + seen_classes=seen_classes, + validated_path_to_schemas=validated_path_to_schemas + ) + + def validation_ran_earlier(self, cls: type) -> bool: + validated_schemas = self.validated_path_to_schemas.get(self.path_to_item, set()) + validation_ran_earlier = validated_schemas and cls in validated_schemas + if validation_ran_earlier: + return True + if cls in self.seen_classes: + return True + return False + + @property + def path_to_item(self) -> typing.Tuple[typing.Union[str, int], ...]: + return self.get('path_to_item') + + @property + def from_server(self) -> bool: + return self.get('from_server') + + @property + def configuration(self) -> typing.Optional[Configuration]: + return self.get('configuration') + + @property + def seen_classes(self) -> typing.FrozenSet[typing.Type]: + return self.get('seen_classes') + + @property + def validated_path_to_schemas(self) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]]: + return self.get('validated_path_to_schemas') + + +class Singleton: + """ + Enums and singletons are the same + The same instance is returned for a given key of (cls, arg) + """ + _instances = {} + + def __new__(cls, arg: typing.Any, **kwargs): + """ + cls base classes: BoolClass, NoneClass, str, decimal.Decimal + The 3rd key is used in the tuple below for a corner case where an enum contains integer 1 + However 1.0 can also be ingested into that enum schema because 1.0 == 1 and + Decimal('1.0') == Decimal('1') + But if we omitted the 3rd value in the key, then Decimal('1.0') would be stored as Decimal('1') + and json serializing that instance would be '1' rather than the expected '1.0' + Adding the 3rd value, the str of arg ensures that 1.0 -> Decimal('1.0') which is serialized as 1.0 + """ + key = (cls, arg, str(arg)) + if key not in cls._instances: + if isinstance(arg, (none_type, bool, BoolClass, NoneClass)): + inst = super().__new__(cls) + cls._instances[key] = inst + else: + cls._instances[key] = super().__new__(cls, arg) + return cls._instances[key] + + def __repr__(self): + if isinstance(self, NoneClass): + return f'<{self.__class__.__name__}: None>' + elif isinstance(self, BoolClass): + if bool(self): + return f'<{self.__class__.__name__}: True>' + return f'<{self.__class__.__name__}: False>' + return f'<{self.__class__.__name__}: {super().__repr__()}>' + + +class classproperty: + + def __init__(self, fget): + self.fget = fget + + def __get__(self, owner_self, owner_cls): + return self.fget(owner_cls) + + +class NoneClass(Singleton): + @classproperty + def NONE(cls): + return cls(None) + + def __bool__(self) -> bool: + return False + + +class BoolClass(Singleton): + @classproperty + def TRUE(cls): + return cls(True) + + @classproperty + def FALSE(cls): + return cls(False) + + @functools.lru_cache() + def __bool__(self) -> bool: + for key, instance in self._instances.items(): + if self is instance: + return bool(key[1]) + raise ValueError('Unable to find the boolean value of this instance') + + +class MetaOapgTyped: + exclusive_maximum: typing.Union[int, float] + inclusive_maximum: typing.Union[int, float] + exclusive_minimum: typing.Union[int, float] + inclusive_minimum: typing.Union[int, float] + max_items: int + min_items: int + discriminator: typing.Dict[str, typing.Dict[str, typing.Type['Schema']]] + + + class properties: + # to hold object properties + pass + + additional_properties: typing.Optional[typing.Type['Schema']] + max_properties: int + min_properties: int + all_of: typing.List[typing.Type['Schema']] + one_of: typing.List[typing.Type['Schema']] + any_of: typing.List[typing.Type['Schema']] + not_schema: typing.Type['Schema'] + max_length: int + min_length: int + items: typing.Type['Schema'] + + +class Schema: + """ + the base class of all swagger/openapi schemas/models + """ + __inheritable_primitive_types_set = {decimal.Decimal, str, tuple, frozendict.frozendict, FileIO, bytes, BoolClass, NoneClass} + _types: typing.Set[typing.Type] + MetaOapg = MetaOapgTyped + + @staticmethod + def __get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed""" + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return "is {0}".format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + @staticmethod + def _get_class_oapg(item_cls: typing.Union[types.FunctionType, staticmethod, typing.Type['Schema']]) -> typing.Type['Schema']: + if isinstance(item_cls, types.FunctionType): + # referenced schema + return item_cls() + elif isinstance(item_cls, staticmethod): + # referenced schema + return item_cls.__func__() + return item_cls + + @classmethod + def __type_error_message( + cls, var_value=None, var_name=None, valid_classes=None, key_type=None + ): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a tuple + """ + key_or_value = "value" + if key_type: + key_or_value = "key" + valid_classes_phrase = cls.__get_valid_classes_phrase(valid_classes) + msg = "Invalid type. Required {1} type {2} and " "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + return msg + + @classmethod + def __get_type_error(cls, var_value, path_to_item, valid_classes, key_type=False): + error_msg = cls.__type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type, + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type, + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + Schema _validate_oapg + All keyword validation except for type checking was done in calling stack frames + If those validations passed, the validated classes are collected in path_to_schemas + + Returns: + path_to_schemas: a map of path to schemas + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + base_class = type(arg) + if base_class not in cls._types: + raise cls.__get_type_error( + arg, + validation_metadata.path_to_item, + cls._types, + key_type=False, + ) + + path_to_schemas = {validation_metadata.path_to_item: set()} + path_to_schemas[validation_metadata.path_to_item].add(cls) + path_to_schemas[validation_metadata.path_to_item].add(base_class) + return path_to_schemas + + @staticmethod + def _process_schema_classes_oapg( + schema_classes: typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]] + ): + """ + Processes and mutates schema_classes + If a SomeSchema is a subclass of DictSchema then remove DictSchema because it is already included + """ + if len(schema_classes) < 2: + return + if len(schema_classes) > 2 and UnsetAnyTypeSchema in schema_classes: + schema_classes.remove(UnsetAnyTypeSchema) + x_schema = schema_type_classes & schema_classes + if not x_schema: + return + x_schema = x_schema.pop() + if any(c is not x_schema and issubclass(c, x_schema) for c in schema_classes): + # needed to not have a mro error in get_new_class + schema_classes.remove(x_schema) + + @classmethod + def __get_new_cls( + cls, + arg, + validation_metadata: ValidationMetadata + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']]: + """ + Make a new dynamic class and return an instance of that class + We are making an instance of cls, but instead of making cls + make a new class, new_cls + which includes dynamic bases including cls + return an instance of that new class + + Dict property + List Item Assignment Use cases: + 1. value is NOT an instance of the required schema class + the value is validated by _validate_oapg + _validate_oapg returns a key value pair + where the key is the path to the item, and the value will be the required manufactured class + made out of the matching schemas + 2. value is an instance of the the correct schema type + the value is NOT validated by _validate_oapg, _validate_oapg only checks that the instance is of the correct schema type + for this value, _validate_oapg does NOT return an entry for it in _path_to_schemas + and in list/dict _get_items_oapg,_get_properties_oapg the value will be directly assigned + because value is of the correct type, and validation was run earlier when the instance was created + """ + _path_to_schemas = {} + if validation_metadata.validated_path_to_schemas: + update(_path_to_schemas, validation_metadata.validated_path_to_schemas) + if not validation_metadata.validation_ran_earlier(cls): + other_path_to_schemas = cls._validate_oapg(arg, validation_metadata=validation_metadata) + update(_path_to_schemas, other_path_to_schemas) + # loop through it make a new class for each entry + # do not modify the returned result because it is cached and we would be modifying the cached value + path_to_schemas = {} + for path, schema_classes in _path_to_schemas.items(): + """ + Use cases + 1. N number of schema classes + enum + type != bool/None, classes in path_to_schemas: tuple/frozendict.frozendict/str/Decimal/bytes/FileIo + needs Singleton added + 2. N number of schema classes + enum + type == bool/None, classes in path_to_schemas: BoolClass/NoneClass + Singleton already added + 3. N number of schema classes, classes in path_to_schemas: BoolClass/NoneClass/tuple/frozendict.frozendict/str/Decimal/bytes/FileIo + """ + cls._process_schema_classes_oapg(schema_classes) + enum_schema = any( + issubclass(this_cls, EnumBase) for this_cls in schema_classes) + inheritable_primitive_type = schema_classes.intersection(cls.__inheritable_primitive_types_set) + chosen_schema_classes = schema_classes - inheritable_primitive_type + suffix = tuple(inheritable_primitive_type) + if enum_schema and suffix[0] not in {NoneClass, BoolClass}: + suffix = (Singleton,) + suffix + + used_classes = tuple(sorted(chosen_schema_classes, key=lambda a_cls: a_cls.__name__)) + suffix + mfg_cls = get_new_class(class_name='DynamicSchema', bases=used_classes) + path_to_schemas[path] = mfg_cls + + return path_to_schemas + + @classmethod + def _get_new_instance_without_conversion_oapg( + cls, + arg: typing.Any, + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + # We have a Dynamic class and we are making an instance of it + if issubclass(cls, frozendict.frozendict) and issubclass(cls, DictBase): + properties = cls._get_properties_oapg(arg, path_to_item, path_to_schemas) + return super(Schema, cls).__new__(cls, properties) + elif issubclass(cls, tuple) and issubclass(cls, ListBase): + items = cls._get_items_oapg(arg, path_to_item, path_to_schemas) + return super(Schema, cls).__new__(cls, items) + """ + str = openapi str, date, and datetime + decimal.Decimal = openapi int and float + FileIO = openapi binary type and the user inputs a file + bytes = openapi binary type and the user inputs bytes + """ + return super(Schema, cls).__new__(cls, arg) + + @classmethod + def from_openapi_data_oapg( + cls, + arg: typing.Union[ + str, + date, + datetime, + int, + float, + decimal.Decimal, + bool, + None, + 'Schema', + dict, + frozendict.frozendict, + tuple, + list, + io.FileIO, + io.BufferedReader, + bytes + ], + _configuration: typing.Optional[Configuration] + ): + """ + Schema from_openapi_data_oapg + """ + from_server = True + validated_path_to_schemas = {} + arg = cast_to_allowed_types(arg, from_server, validated_path_to_schemas) + validation_metadata = ValidationMetadata( + from_server=from_server, configuration=_configuration, validated_path_to_schemas=validated_path_to_schemas) + path_to_schemas = cls.__get_new_cls(arg, validation_metadata) + new_cls = path_to_schemas[validation_metadata.path_to_item] + new_inst = new_cls._get_new_instance_without_conversion_oapg( + arg, + validation_metadata.path_to_item, + path_to_schemas + ) + return new_inst + + @staticmethod + def __get_input_dict(*args, **kwargs) -> frozendict.frozendict: + input_dict = {} + if args and isinstance(args[0], (dict, frozendict.frozendict)): + input_dict.update(args[0]) + if kwargs: + input_dict.update(kwargs) + return frozendict.frozendict(input_dict) + + @staticmethod + def __remove_unsets(kwargs): + return {key: val for key, val in kwargs.items() if val is not unset} + + def __new__(cls, *args: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], _configuration: typing.Optional[Configuration] = None, **kwargs: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset]): + """ + Schema __new__ + + Args: + args (int/float/decimal.Decimal/str/list/tuple/dict/frozendict.frozendict/bool/None): the value + kwargs (str, int/float/decimal.Decimal/str/list/tuple/dict/frozendict.frozendict/bool/None): dict values + _configuration: contains the Configuration that enables json schema validation keywords + like minItems, minLength etc + + Note: double underscores are used here because pycharm thinks that these variables + are instance properties if they are named normally :( + """ + __kwargs = cls.__remove_unsets(kwargs) + if not args and not __kwargs: + raise TypeError( + 'No input given. args or kwargs must be given.' + ) + if not __kwargs and args and not isinstance(args[0], dict): + __arg = args[0] + else: + __arg = cls.__get_input_dict(*args, **__kwargs) + __from_server = False + __validated_path_to_schemas = {} + __arg = cast_to_allowed_types( + __arg, __from_server, __validated_path_to_schemas) + __validation_metadata = ValidationMetadata( + configuration=_configuration, from_server=__from_server, validated_path_to_schemas=__validated_path_to_schemas) + __path_to_schemas = cls.__get_new_cls(__arg, __validation_metadata) + __new_cls = __path_to_schemas[__validation_metadata.path_to_item] + return __new_cls._get_new_instance_without_conversion_oapg( + __arg, + __validation_metadata.path_to_item, + __path_to_schemas + ) + + def __init__( + self, + *args: typing.Union[ + dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], + _configuration: typing.Optional[Configuration] = None, + **kwargs: typing.Union[ + dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset + ] + ): + """ + this is needed to fix 'Unexpected argument' warning in pycharm + this code does nothing because all Schema instances are immutable + this means that all input data is passed into and used in new, and after the new instance is made + no new attributes are assigned and init is not used + """ + pass + +""" +import itertools +data_types = ('None', 'FrozenDict', 'Tuple', 'Str', 'Decimal', 'Bool') +type_to_cls = { + 'None': 'NoneClass', + 'FrozenDict': 'frozendict.frozendict', + 'Tuple': 'tuple', + 'Str': 'str', + 'Decimal': 'decimal.Decimal', + 'Bool': 'BoolClass' +} +cls_tuples = [v for v in itertools.combinations(data_types, 5)] +typed_classes = [f"class {''.join(cls_tuple)}Mixin({', '.join(type_to_cls[typ] for typ in cls_tuple)}):\n pass" for cls_tuple in cls_tuples] +for cls in typed_classes: + print(cls) +object_classes = [f"{''.join(cls_tuple)}Mixin = object" for cls_tuple in cls_tuples] +for cls in object_classes: + print(cls) +""" +if typing.TYPE_CHECKING: + # qty 1 + NoneMixin = NoneClass + FrozenDictMixin = frozendict.frozendict + TupleMixin = tuple + StrMixin = str + DecimalMixin = decimal.Decimal + BoolMixin = BoolClass + BytesMixin = bytes + FileMixin = FileIO + # qty 2 + class BinaryMixin(bytes, FileIO): + pass + class NoneFrozenDictMixin(NoneClass, frozendict.frozendict): + pass + class NoneTupleMixin(NoneClass, tuple): + pass + class NoneStrMixin(NoneClass, str): + pass + class NoneDecimalMixin(NoneClass, decimal.Decimal): + pass + class NoneBoolMixin(NoneClass, BoolClass): + pass + class FrozenDictTupleMixin(frozendict.frozendict, tuple): + pass + class FrozenDictStrMixin(frozendict.frozendict, str): + pass + class FrozenDictDecimalMixin(frozendict.frozendict, decimal.Decimal): + pass + class FrozenDictBoolMixin(frozendict.frozendict, BoolClass): + pass + class TupleStrMixin(tuple, str): + pass + class TupleDecimalMixin(tuple, decimal.Decimal): + pass + class TupleBoolMixin(tuple, BoolClass): + pass + class StrDecimalMixin(str, decimal.Decimal): + pass + class StrBoolMixin(str, BoolClass): + pass + class DecimalBoolMixin(decimal.Decimal, BoolClass): + pass + # qty 3 + class NoneFrozenDictTupleMixin(NoneClass, frozendict.frozendict, tuple): + pass + class NoneFrozenDictStrMixin(NoneClass, frozendict.frozendict, str): + pass + class NoneFrozenDictDecimalMixin(NoneClass, frozendict.frozendict, decimal.Decimal): + pass + class NoneFrozenDictBoolMixin(NoneClass, frozendict.frozendict, BoolClass): + pass + class NoneTupleStrMixin(NoneClass, tuple, str): + pass + class NoneTupleDecimalMixin(NoneClass, tuple, decimal.Decimal): + pass + class NoneTupleBoolMixin(NoneClass, tuple, BoolClass): + pass + class NoneStrDecimalMixin(NoneClass, str, decimal.Decimal): + pass + class NoneStrBoolMixin(NoneClass, str, BoolClass): + pass + class NoneDecimalBoolMixin(NoneClass, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrMixin(frozendict.frozendict, tuple, str): + pass + class FrozenDictTupleDecimalMixin(frozendict.frozendict, tuple, decimal.Decimal): + pass + class FrozenDictTupleBoolMixin(frozendict.frozendict, tuple, BoolClass): + pass + class FrozenDictStrDecimalMixin(frozendict.frozendict, str, decimal.Decimal): + pass + class FrozenDictStrBoolMixin(frozendict.frozendict, str, BoolClass): + pass + class FrozenDictDecimalBoolMixin(frozendict.frozendict, decimal.Decimal, BoolClass): + pass + class TupleStrDecimalMixin(tuple, str, decimal.Decimal): + pass + class TupleStrBoolMixin(tuple, str, BoolClass): + pass + class TupleDecimalBoolMixin(tuple, decimal.Decimal, BoolClass): + pass + class StrDecimalBoolMixin(str, decimal.Decimal, BoolClass): + pass + # qty 4 + class NoneFrozenDictTupleStrMixin(NoneClass, frozendict.frozendict, tuple, str): + pass + class NoneFrozenDictTupleDecimalMixin(NoneClass, frozendict.frozendict, tuple, decimal.Decimal): + pass + class NoneFrozenDictTupleBoolMixin(NoneClass, frozendict.frozendict, tuple, BoolClass): + pass + class NoneFrozenDictStrDecimalMixin(NoneClass, frozendict.frozendict, str, decimal.Decimal): + pass + class NoneFrozenDictStrBoolMixin(NoneClass, frozendict.frozendict, str, BoolClass): + pass + class NoneFrozenDictDecimalBoolMixin(NoneClass, frozendict.frozendict, decimal.Decimal, BoolClass): + pass + class NoneTupleStrDecimalMixin(NoneClass, tuple, str, decimal.Decimal): + pass + class NoneTupleStrBoolMixin(NoneClass, tuple, str, BoolClass): + pass + class NoneTupleDecimalBoolMixin(NoneClass, tuple, decimal.Decimal, BoolClass): + pass + class NoneStrDecimalBoolMixin(NoneClass, str, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrDecimalMixin(frozendict.frozendict, tuple, str, decimal.Decimal): + pass + class FrozenDictTupleStrBoolMixin(frozendict.frozendict, tuple, str, BoolClass): + pass + class FrozenDictTupleDecimalBoolMixin(frozendict.frozendict, tuple, decimal.Decimal, BoolClass): + pass + class FrozenDictStrDecimalBoolMixin(frozendict.frozendict, str, decimal.Decimal, BoolClass): + pass + class TupleStrDecimalBoolMixin(tuple, str, decimal.Decimal, BoolClass): + pass + # qty 5 + class NoneFrozenDictTupleStrDecimalMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal): + pass + class NoneFrozenDictTupleStrBoolMixin(NoneClass, frozendict.frozendict, tuple, str, BoolClass): + pass + class NoneFrozenDictTupleDecimalBoolMixin(NoneClass, frozendict.frozendict, tuple, decimal.Decimal, BoolClass): + pass + class NoneFrozenDictStrDecimalBoolMixin(NoneClass, frozendict.frozendict, str, decimal.Decimal, BoolClass): + pass + class NoneTupleStrDecimalBoolMixin(NoneClass, tuple, str, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrDecimalBoolMixin(frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass): + pass + # qty 6 + class NoneFrozenDictTupleStrDecimalBoolMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass): + pass + # qty 8 + class NoneFrozenDictTupleStrDecimalBoolFileBytesMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass, FileIO, bytes): + pass +else: + # qty 1 + class NoneMixin: + _types = {NoneClass} + class FrozenDictMixin: + _types = {frozendict.frozendict} + class TupleMixin: + _types = {tuple} + class StrMixin: + _types = {str} + class DecimalMixin: + _types = {decimal.Decimal} + class BoolMixin: + _types = {BoolClass} + class BytesMixin: + _types = {bytes} + class FileMixin: + _types = {FileIO} + # qty 2 + class BinaryMixin: + _types = {bytes, FileIO} + class NoneFrozenDictMixin: + _types = {NoneClass, frozendict.frozendict} + class NoneTupleMixin: + _types = {NoneClass, tuple} + class NoneStrMixin: + _types = {NoneClass, str} + class NoneDecimalMixin: + _types = {NoneClass, decimal.Decimal} + class NoneBoolMixin: + _types = {NoneClass, BoolClass} + class FrozenDictTupleMixin: + _types = {frozendict.frozendict, tuple} + class FrozenDictStrMixin: + _types = {frozendict.frozendict, str} + class FrozenDictDecimalMixin: + _types = {frozendict.frozendict, decimal.Decimal} + class FrozenDictBoolMixin: + _types = {frozendict.frozendict, BoolClass} + class TupleStrMixin: + _types = {tuple, str} + class TupleDecimalMixin: + _types = {tuple, decimal.Decimal} + class TupleBoolMixin: + _types = {tuple, BoolClass} + class StrDecimalMixin: + _types = {str, decimal.Decimal} + class StrBoolMixin: + _types = {str, BoolClass} + class DecimalBoolMixin: + _types = {decimal.Decimal, BoolClass} + # qty 3 + class NoneFrozenDictTupleMixin: + _types = {NoneClass, frozendict.frozendict, tuple} + class NoneFrozenDictStrMixin: + _types = {NoneClass, frozendict.frozendict, str} + class NoneFrozenDictDecimalMixin: + _types = {NoneClass, frozendict.frozendict, decimal.Decimal} + class NoneFrozenDictBoolMixin: + _types = {NoneClass, frozendict.frozendict, BoolClass} + class NoneTupleStrMixin: + _types = {NoneClass, tuple, str} + class NoneTupleDecimalMixin: + _types = {NoneClass, tuple, decimal.Decimal} + class NoneTupleBoolMixin: + _types = {NoneClass, tuple, BoolClass} + class NoneStrDecimalMixin: + _types = {NoneClass, str, decimal.Decimal} + class NoneStrBoolMixin: + _types = {NoneClass, str, BoolClass} + class NoneDecimalBoolMixin: + _types = {NoneClass, decimal.Decimal, BoolClass} + class FrozenDictTupleStrMixin: + _types = {frozendict.frozendict, tuple, str} + class FrozenDictTupleDecimalMixin: + _types = {frozendict.frozendict, tuple, decimal.Decimal} + class FrozenDictTupleBoolMixin: + _types = {frozendict.frozendict, tuple, BoolClass} + class FrozenDictStrDecimalMixin: + _types = {frozendict.frozendict, str, decimal.Decimal} + class FrozenDictStrBoolMixin: + _types = {frozendict.frozendict, str, BoolClass} + class FrozenDictDecimalBoolMixin: + _types = {frozendict.frozendict, decimal.Decimal, BoolClass} + class TupleStrDecimalMixin: + _types = {tuple, str, decimal.Decimal} + class TupleStrBoolMixin: + _types = {tuple, str, BoolClass} + class TupleDecimalBoolMixin: + _types = {tuple, decimal.Decimal, BoolClass} + class StrDecimalBoolMixin: + _types = {str, decimal.Decimal, BoolClass} + # qty 4 + class NoneFrozenDictTupleStrMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str} + class NoneFrozenDictTupleDecimalMixin: + _types = {NoneClass, frozendict.frozendict, tuple, decimal.Decimal} + class NoneFrozenDictTupleBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, BoolClass} + class NoneFrozenDictStrDecimalMixin: + _types = {NoneClass, frozendict.frozendict, str, decimal.Decimal} + class NoneFrozenDictStrBoolMixin: + _types = {NoneClass, frozendict.frozendict, str, BoolClass} + class NoneFrozenDictDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, decimal.Decimal, BoolClass} + class NoneTupleStrDecimalMixin: + _types = {NoneClass, tuple, str, decimal.Decimal} + class NoneTupleStrBoolMixin: + _types = {NoneClass, tuple, str, BoolClass} + class NoneTupleDecimalBoolMixin: + _types = {NoneClass, tuple, decimal.Decimal, BoolClass} + class NoneStrDecimalBoolMixin: + _types = {NoneClass, str, decimal.Decimal, BoolClass} + class FrozenDictTupleStrDecimalMixin: + _types = {frozendict.frozendict, tuple, str, decimal.Decimal} + class FrozenDictTupleStrBoolMixin: + _types = {frozendict.frozendict, tuple, str, BoolClass} + class FrozenDictTupleDecimalBoolMixin: + _types = {frozendict.frozendict, tuple, decimal.Decimal, BoolClass} + class FrozenDictStrDecimalBoolMixin: + _types = {frozendict.frozendict, str, decimal.Decimal, BoolClass} + class TupleStrDecimalBoolMixin: + _types = {tuple, str, decimal.Decimal, BoolClass} + # qty 5 + class NoneFrozenDictTupleStrDecimalMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal} + class NoneFrozenDictTupleStrBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, BoolClass} + class NoneFrozenDictTupleDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, decimal.Decimal, BoolClass} + class NoneFrozenDictStrDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, str, decimal.Decimal, BoolClass} + class NoneTupleStrDecimalBoolMixin: + _types = {NoneClass, tuple, str, decimal.Decimal, BoolClass} + class FrozenDictTupleStrDecimalBoolMixin: + _types = {frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass} + # qty 6 + class NoneFrozenDictTupleStrDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass} + # qty 8 + class NoneFrozenDictTupleStrDecimalBoolFileBytesMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass, FileIO, bytes} + + +class ValidatorBase: + @staticmethod + def _is_json_validation_enabled_oapg(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + Note: the suffix _oapg stands for openapi python (experimental) generator and + it has been added to prevent collisions with other methods and properties + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + @staticmethod + def _raise_validation_errror_message_oapg(value, constraint_msg, constraint_value, path_to_item, additional_txt=""): + raise ApiValueError( + "Invalid value `{value}`, {constraint_msg} `{constraint_value}`{additional_txt} at {path_to_item}".format( + value=value, + constraint_msg=constraint_msg, + constraint_value=constraint_value, + additional_txt=additional_txt, + path_to_item=path_to_item, + ) + ) + + +class EnumBase: + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + EnumBase _validate_oapg + Validates that arg is in the enum's allowed values + """ + try: + cls.MetaOapg.enum_value_to_name[arg] + except KeyError: + raise ApiValueError("Invalid value {} passed in to {}, allowed_values={}".format(arg, cls, cls.MetaOapg.enum_value_to_name.keys())) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class BoolBase: + def is_true_oapg(self) -> bool: + """ + A replacement for x is True + True if the instance is a BoolClass True Singleton + """ + if not issubclass(self.__class__, BoolClass): + return False + return bool(self) + + def is_false_oapg(self) -> bool: + """ + A replacement for x is False + True if the instance is a BoolClass False Singleton + """ + if not issubclass(self.__class__, BoolClass): + return False + return bool(self) is False + + +class NoneBase: + def is_none_oapg(self) -> bool: + """ + A replacement for x is None + True if the instance is a NoneClass None Singleton + """ + if issubclass(self.__class__, NoneClass): + return True + return False + + +class StrBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @property + def as_str_oapg(self) -> str: + return self + + @property + def as_date_oapg(self) -> date: + raise Exception('not implemented') + + @property + def as_datetime_oapg(self) -> datetime: + raise Exception('not implemented') + + @property + def as_decimal_oapg(self) -> decimal.Decimal: + raise Exception('not implemented') + + @property + def as_uuid_oapg(self) -> uuid.UUID: + raise Exception('not implemented') + + @classmethod + def __check_str_validations( + cls, + arg: str, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxLength', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_length') and + len(arg) > cls.MetaOapg.max_length): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="length must be less than or equal to", + constraint_value=cls.MetaOapg.max_length, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minLength', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_length') and + len(arg) < cls.MetaOapg.min_length): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="length must be greater than or equal to", + constraint_value=cls.MetaOapg.min_length, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('pattern', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'regex')): + for regex_dict in cls.MetaOapg.regex: + flags = regex_dict.get('flags', 0) + if not re.search(regex_dict['pattern'], arg, flags=flags): + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must match regular expression", + constraint_value=regex_dict['pattern'], + path_to_item=validation_metadata.path_to_item, + additional_txt=" with flags=`{}`".format(flags) + ) + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must match regular expression", + constraint_value=regex_dict['pattern'], + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + StrBase _validate_oapg + Validates that validations pass + """ + if isinstance(arg, str): + cls.__check_str_validations(arg, validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class UUIDBase: + @property + @functools.lru_cache() + def as_uuid_oapg(self) -> uuid.UUID: + return uuid.UUID(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + uuid.UUID(arg) + return True + except ValueError: + raise ApiValueError( + "Invalid value '{}' for type UUID at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: typing.Optional[ValidationMetadata] = None, + ): + """ + UUIDBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class CustomIsoparser(isoparser): + + @_takes_ascii + def parse_isodatetime(self, dt_str): + components, pos = self._parse_isodate(dt_str) + if len(dt_str) > pos: + if self._sep is None or dt_str[pos:pos + 1] == self._sep: + components += self._parse_isotime(dt_str[pos + 1:]) + else: + raise ValueError('String contains unknown ISO components') + + if len(components) > 3 and components[3] == 24: + components[3] = 0 + return datetime(*components) + timedelta(days=1) + + if len(components) <= 3: + raise ValueError('Value is not a datetime') + + return datetime(*components) + + @_takes_ascii + def parse_isodate(self, datestr): + components, pos = self._parse_isodate(datestr) + + if len(datestr) > pos: + raise ValueError('String contains invalid time components') + + if len(components) > 3: + raise ValueError('String contains invalid time components') + + return date(*components) + + +DEFAULT_ISOPARSER = CustomIsoparser() + + +class DateBase: + @property + @functools.lru_cache() + def as_date_oapg(self) -> date: + return DEFAULT_ISOPARSER.parse_isodate(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + DEFAULT_ISOPARSER.parse_isodate(arg) + return True + except ValueError: + raise ApiValueError( + "Value does not conform to the required ISO-8601 date format. " + "Invalid value '{}' for type date at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: typing.Optional[ValidationMetadata] = None, + ): + """ + DateBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class DateTimeBase: + @property + @functools.lru_cache() + def as_datetime_oapg(self) -> datetime: + return DEFAULT_ISOPARSER.parse_isodatetime(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + DEFAULT_ISOPARSER.parse_isodatetime(arg) + return True + except ValueError: + raise ApiValueError( + "Value does not conform to the required ISO-8601 datetime format. " + "Invalid value '{}' for type datetime at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DateTimeBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class DecimalBase: + """ + A class for storing decimals that are sent over the wire as strings + These schemas must remain based on StrBase rather than NumberBase + because picking base classes must be deterministic + """ + + @property + @functools.lru_cache() + def as_decimal_oapg(self) -> decimal.Decimal: + return decimal.Decimal(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + decimal.Decimal(arg) + return True + except decimal.InvalidOperation: + raise ApiValueError( + "Value cannot be converted to a decimal. " + "Invalid value '{}' for type decimal at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DecimalBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class NumberBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @property + def as_int_oapg(self) -> int: + try: + return self._as_int + except AttributeError: + """ + Note: for some numbers like 9.0 they could be represented as an + integer but our code chooses to store them as + >>> Decimal('9.0').as_tuple() + DecimalTuple(sign=0, digits=(9, 0), exponent=-1) + so we can tell that the value came from a float and convert it back to a float + during later serialization + """ + if self.as_tuple().exponent < 0: + # this could be represented as an integer but should be represented as a float + # because that's what it was serialized from + raise ApiValueError(f'{self} is not an integer') + self._as_int = int(self) + return self._as_int + + @property + def as_float_oapg(self) -> float: + try: + return self._as_float + except AttributeError: + if self.as_tuple().exponent >= 0: + raise ApiValueError(f'{self} is not an float') + self._as_float = float(self) + return self._as_float + + @classmethod + def __check_numeric_validations( + cls, + arg, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if cls._is_json_validation_enabled_oapg('multipleOf', + validation_metadata.configuration) and hasattr(cls.MetaOapg, 'multiple_of'): + multiple_of_value = cls.MetaOapg.multiple_of + if (not (float(arg) / multiple_of_value).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="value must be a multiple of", + constraint_value=multiple_of_value, + path_to_item=validation_metadata.path_to_item + ) + + checking_max_or_min_values = any( + hasattr(cls.MetaOapg, validation_key) for validation_key in { + 'exclusive_maximum', + 'inclusive_maximum', + 'exclusive_minimum', + 'inclusive_minimum', + } + ) + if not checking_max_or_min_values: + return + + if (cls._is_json_validation_enabled_oapg('exclusiveMaximum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'exclusive_maximum') and + arg >= cls.MetaOapg.exclusive_maximum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value less than", + constraint_value=cls.MetaOapg.exclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('maximum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'inclusive_maximum') and + arg > cls.MetaOapg.inclusive_maximum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value less than or equal to", + constraint_value=cls.MetaOapg.inclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('exclusiveMinimum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'exclusive_minimum') and + arg <= cls.MetaOapg.exclusive_minimum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value greater than", + constraint_value=cls.MetaOapg.exclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minimum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'inclusive_minimum') and + arg < cls.MetaOapg.inclusive_minimum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value greater than or equal to", + constraint_value=cls.MetaOapg.inclusive_minimum, + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + NumberBase _validate_oapg + Validates that validations pass + """ + if isinstance(arg, decimal.Decimal): + cls.__check_numeric_validations(arg, validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class ListBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @classmethod + def __validate_items(cls, list_items, validation_metadata: ValidationMetadata): + """ + Ensures that: + - values passed in for items are valid + Exceptions will be raised if: + - invalid arguments were passed in + + Args: + list_items: the input list of items + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + + # if we have definitions for an items schema, use it + # otherwise accept anything + item_cls = getattr(cls.MetaOapg, 'items', UnsetAnyTypeSchema) + item_cls = cls._get_class_oapg(item_cls) + path_to_schemas = {} + for i, value in enumerate(list_items): + item_validation_metadata = ValidationMetadata( + from_server=validation_metadata.from_server, + configuration=validation_metadata.configuration, + path_to_item=validation_metadata.path_to_item+(i,), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if item_validation_metadata.validation_ran_earlier(item_cls): + continue + other_path_to_schemas = item_cls._validate_oapg( + value, validation_metadata=item_validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __check_tuple_validations( + cls, arg, + validation_metadata: ValidationMetadata): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_items') and + len(arg) > cls.MetaOapg.max_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of items must be less than or equal to", + constraint_value=cls.MetaOapg.max_items, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_items') and + len(arg) < cls.MetaOapg.min_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of items must be greater than or equal to", + constraint_value=cls.MetaOapg.min_items, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('uniqueItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'unique_items') and cls.MetaOapg.unique_items and arg): + unique_items = set(arg) + if len(arg) > len(unique_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="duplicate items were found, and the tuple must not contain duplicates because", + constraint_value='unique_items==True', + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + ListBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + if isinstance(arg, tuple): + cls.__check_tuple_validations(arg, validation_metadata) + _path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + if not isinstance(arg, tuple): + return _path_to_schemas + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + other_path_to_schemas = cls.__validate_items(arg, validation_metadata=updated_vm) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_items_oapg( + cls: 'Schema', + arg: typing.List[typing.Any], + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + ''' + ListBase _get_items_oapg + ''' + cast_items = [] + + for i, value in enumerate(arg): + item_path_to_item = path_to_item + (i,) + item_cls = path_to_schemas[item_path_to_item] + new_value = item_cls._get_new_instance_without_conversion_oapg( + value, + item_path_to_item, + path_to_schemas + ) + cast_items.append(new_value) + + return cast_items + + +class Discriminable: + MetaOapg: MetaOapgTyped + + @classmethod + def _ensure_discriminator_value_present_oapg(cls, disc_property_name: str, validation_metadata: ValidationMetadata, *args): + if not args or args and disc_property_name not in args[0]: + # The input data does not contain the discriminator property + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '{}' is missing at path: {}".format(disc_property_name, validation_metadata.path_to_item) + ) + + @classmethod + def get_discriminated_class_oapg(cls, disc_property_name: str, disc_payload_value: str): + """ + Used in schemas with discriminators + """ + if not hasattr(cls.MetaOapg, 'discriminator'): + return None + disc = cls.MetaOapg.discriminator() + if disc_property_name not in disc: + return None + discriminated_cls = disc[disc_property_name].get(disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if not hasattr(cls, 'MetaOapg'): + return None + elif not ( + hasattr(cls.MetaOapg, 'all_of') or + hasattr(cls.MetaOapg, 'one_of') or + hasattr(cls.MetaOapg, 'any_of') + ): + return None + # TODO stop traveling if a cycle is hit + if hasattr(cls.MetaOapg, 'all_of'): + for allof_cls in cls.MetaOapg.all_of(): + discriminated_cls = allof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if hasattr(cls.MetaOapg, 'one_of'): + for oneof_cls in cls.MetaOapg.one_of(): + discriminated_cls = oneof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if hasattr(cls.MetaOapg, 'any_of'): + for anyof_cls in cls.MetaOapg.any_of(): + discriminated_cls = anyof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + return None + + +class DictBase(Discriminable, ValidatorBase): + + @classmethod + def __validate_arg_presence(cls, arg): + """ + Ensures that: + - all required arguments are passed in + - the input variable names are valid + - present in properties or + - accepted because additionalProperties exists + Exceptions will be raised if: + - invalid arguments were passed in + - a var_name is invalid if additional_properties == NotAnyTypeSchema + and var_name not in properties.__annotations__ + - required properties were not passed in + + Args: + arg: the input dict + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + seen_required_properties = set() + invalid_arguments = [] + required_property_names = getattr(cls.MetaOapg, 'required', set()) + additional_properties = getattr(cls.MetaOapg, 'additional_properties', UnsetAnyTypeSchema) + properties = getattr(cls.MetaOapg, 'properties', {}) + property_annotations = getattr(properties, '__annotations__', {}) + for property_name in arg: + if property_name in required_property_names: + seen_required_properties.add(property_name) + elif property_name in property_annotations: + continue + elif additional_properties is not NotAnyTypeSchema: + continue + else: + invalid_arguments.append(property_name) + missing_required_arguments = list(required_property_names - seen_required_properties) + if missing_required_arguments: + missing_required_arguments.sort() + raise ApiTypeError( + "{} is missing {} required argument{}: {}".format( + cls.__name__, + len(missing_required_arguments), + "s" if len(missing_required_arguments) > 1 else "", + missing_required_arguments + ) + ) + if invalid_arguments: + invalid_arguments.sort() + raise ApiTypeError( + "{} was passed {} invalid argument{}: {}".format( + cls.__name__, + len(invalid_arguments), + "s" if len(invalid_arguments) > 1 else "", + invalid_arguments + ) + ) + + @classmethod + def __validate_args(cls, arg, validation_metadata: ValidationMetadata): + """ + Ensures that: + - values passed in for properties are valid + Exceptions will be raised if: + - invalid arguments were passed in + + Args: + arg: the input dict + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + path_to_schemas = {} + additional_properties = getattr(cls.MetaOapg, 'additional_properties', UnsetAnyTypeSchema) + properties = getattr(cls.MetaOapg, 'properties', {}) + property_annotations = getattr(properties, '__annotations__', {}) + for property_name, value in arg.items(): + path_to_item = validation_metadata.path_to_item+(property_name,) + if property_name in property_annotations: + schema = property_annotations[property_name] + elif additional_properties is not NotAnyTypeSchema: + if additional_properties is UnsetAnyTypeSchema: + """ + If additionalProperties is unset and this path_to_item does not yet have + any validations on it, validate it. + If it already has validations on it, skip this validation. + """ + if path_to_item in path_to_schemas: + continue + schema = additional_properties + else: + raise ApiTypeError('Unable to find schema for value={} in class={} at path_to_item={}'.format( + value, cls, validation_metadata.path_to_item+(property_name,) + )) + schema = cls._get_class_oapg(schema) + arg_validation_metadata = ValidationMetadata( + from_server=validation_metadata.from_server, + configuration=validation_metadata.configuration, + path_to_item=path_to_item, + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if arg_validation_metadata.validation_ran_earlier(schema): + continue + other_path_to_schemas = schema._validate_oapg(value, validation_metadata=arg_validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __check_dict_validations( + cls, + arg, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxProperties', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_properties') and + len(arg) > cls.MetaOapg.max_properties): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of properties must be less than or equal to", + constraint_value=cls.MetaOapg.max_properties, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minProperties', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_properties') and + len(arg) < cls.MetaOapg.min_properties): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of properties must be greater than or equal to", + constraint_value=cls.MetaOapg.min_properties, + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DictBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + if isinstance(arg, frozendict.frozendict): + cls.__check_dict_validations(arg, validation_metadata) + _path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + if not isinstance(arg, frozendict.frozendict): + return _path_to_schemas + cls.__validate_arg_presence(arg) + other_path_to_schemas = cls.__validate_args(arg, validation_metadata=validation_metadata) + update(_path_to_schemas, other_path_to_schemas) + try: + discriminator = cls.MetaOapg.discriminator() + except AttributeError: + return _path_to_schemas + # discriminator exists + disc_prop_name = list(discriminator.keys())[0] + cls._ensure_discriminator_value_present_oapg(disc_prop_name, validation_metadata, arg) + discriminated_cls = cls.get_discriminated_class_oapg( + disc_property_name=disc_prop_name, disc_payload_value=arg[disc_prop_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value was passed in to {}.{} Only the values {} are allowed at {}".format( + cls.__name__, + disc_prop_name, + list(discriminator[disc_prop_name].keys()), + validation_metadata.path_to_item + (disc_prop_name,) + ) + ) + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if updated_vm.validation_ran_earlier(discriminated_cls): + return _path_to_schemas + other_path_to_schemas = discriminated_cls._validate_oapg(arg, validation_metadata=updated_vm) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_properties_oapg( + cls, + arg: typing.Dict[str, typing.Any], + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + """ + DictBase _get_properties_oapg, this is how properties are set + These values already passed validation + """ + dict_items = {} + + for property_name_js, value in arg.items(): + property_path_to_item = path_to_item + (property_name_js,) + property_cls = path_to_schemas[property_path_to_item] + new_value = property_cls._get_new_instance_without_conversion_oapg( + value, + property_path_to_item, + path_to_schemas + ) + dict_items[property_name_js] = new_value + + return dict_items + + def __setattr__(self, name: str, value: typing.Any): + if not isinstance(self, FileIO): + raise AttributeError('property setting not supported on immutable instances') + + def __getattr__(self, name: str): + """ + for instance.name access + Properties are only type hinted for required properties + so that hasattr(instance, 'optionalProp') is False when that key is not present + """ + if not isinstance(self, frozendict.frozendict): + return super().__getattr__(name) + if name not in self.__class__.__annotations__: + raise AttributeError(f"{self} has no attribute '{name}'") + try: + value = self[name] + return value + except KeyError as ex: + raise AttributeError(str(ex)) + + def __getitem__(self, name: str): + """ + dict_instance[name] accessor + key errors thrown + """ + if not isinstance(self, frozendict.frozendict): + return super().__getattr__(name) + return super().__getitem__(name) + + def get_item_oapg(self, name: str) -> typing.Union['AnyTypeSchema', Unset]: + # dict_instance[name] accessor + if not isinstance(self, frozendict.frozendict): + raise NotImplementedError() + try: + return super().__getitem__(name) + except KeyError: + return unset + + +def cast_to_allowed_types( + arg: typing.Union[str, date, datetime, uuid.UUID, decimal.Decimal, int, float, None, dict, frozendict.frozendict, list, tuple, bytes, Schema, io.FileIO, io.BufferedReader], + from_server: bool, + validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]], + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), +) -> typing.Union[frozendict.frozendict, tuple, decimal.Decimal, str, bytes, BoolClass, NoneClass, FileIO]: + """ + Casts the input payload arg into the allowed types + The input validated_path_to_schemas is mutated by running this function + + When from_server is False then + - date/datetime is cast to str + - int/float is cast to Decimal + + If a Schema instance is passed in it is converted back to a primitive instance because + One may need to validate that data to the original Schema class AND additional different classes + those additional classes will need to be added to the new manufactured class for that payload + If the code didn't do this and kept the payload as a Schema instance it would fail to validate to other + Schema classes and the code wouldn't be able to mfg a new class that includes all valid schemas + TODO: store the validated schema classes in validation_metadata + + Args: + arg: the payload + from_server: whether this payload came from the server or not + validated_path_to_schemas: a dict that stores the validated classes at any path location in the payload + """ + if isinstance(arg, Schema): + # store the already run validations + schema_classes = set() + source_schema_was_unset = len(arg.__class__.__bases__) == 2 and UnsetAnyTypeSchema in arg.__class__.__bases__ + if not source_schema_was_unset: + """ + Do not include UnsetAnyTypeSchema and its base class because + it did not exist in the original spec schema definition + It was added to ensure that all instances are of type Schema and the allowed base types + """ + for cls in arg.__class__.__bases__: + if cls is Singleton: + # Skip Singleton + continue + schema_classes.add(cls) + validated_path_to_schemas[path_to_item] = schema_classes + + type_error = ApiTypeError(f"Invalid type. Required value type is str and passed type was {type(arg)} at {path_to_item}") + if isinstance(arg, str): + return str(arg) + elif isinstance(arg, (dict, frozendict.frozendict)): + return frozendict.frozendict({key: cast_to_allowed_types(val, from_server, validated_path_to_schemas, path_to_item + (key,)) for key, val in arg.items()}) + elif isinstance(arg, (bool, BoolClass)): + """ + this check must come before isinstance(arg, (int, float)) + because isinstance(True, int) is True + """ + if arg: + return BoolClass.TRUE + return BoolClass.FALSE + elif isinstance(arg, int): + return decimal.Decimal(arg) + elif isinstance(arg, float): + decimal_from_float = decimal.Decimal(arg) + if decimal_from_float.as_integer_ratio()[1] == 1: + # 9.0 -> Decimal('9.0') + # 3.4028234663852886e+38 -> Decimal('340282346638528859811704183484516925440.0') + return decimal.Decimal(str(decimal_from_float)+'.0') + return decimal_from_float + elif isinstance(arg, (tuple, list)): + return tuple([cast_to_allowed_types(item, from_server, validated_path_to_schemas, path_to_item + (i,)) for i, item in enumerate(arg)]) + elif isinstance(arg, (none_type, NoneClass)): + return NoneClass.NONE + elif isinstance(arg, (date, datetime)): + if not from_server: + return arg.isoformat() + raise type_error + elif isinstance(arg, uuid.UUID): + if not from_server: + return str(arg) + raise type_error + elif isinstance(arg, decimal.Decimal): + return decimal.Decimal(arg) + elif isinstance(arg, bytes): + return bytes(arg) + elif isinstance(arg, (io.FileIO, io.BufferedReader)): + return FileIO(arg) + raise ValueError('Invalid type passed in got input={} type={}'.format(arg, type(arg))) + + +class ComposedBase(Discriminable): + + @classmethod + def __get_allof_classes(cls, arg, validation_metadata: ValidationMetadata): + path_to_schemas = defaultdict(set) + for allof_cls in cls.MetaOapg.all_of(): + if validation_metadata.validation_ran_earlier(allof_cls): + continue + other_path_to_schemas = allof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __get_oneof_class( + cls, + arg, + discriminated_cls, + validation_metadata: ValidationMetadata, + ): + oneof_classes = [] + path_to_schemas = defaultdict(set) + for oneof_cls in cls.MetaOapg.one_of(): + if oneof_cls in path_to_schemas[validation_metadata.path_to_item]: + oneof_classes.append(oneof_cls) + continue + if validation_metadata.validation_ran_earlier(oneof_cls): + oneof_classes.append(oneof_cls) + continue + try: + path_to_schemas = oneof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and oneof_cls is discriminated_cls: + {{#if nonCompliantUseDiscriminatorIfCompositionFails}} + """ + suppress exception because code was generated with + nonCompliantUseDiscriminatorIfCompositionFails=true + """ + pass + {{else}} + raise ex + {{/if}} + continue + oneof_classes.append(oneof_cls) + if not oneof_classes: + {{#if nonCompliantUseDiscriminatorIfCompositionFails}} + if discriminated_cls: + """ + return without exception because code was generated with + nonCompliantUseDiscriminatorIfCompositionFails=true + """ + return {} + {{/if}} + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. None " + "of the oneOf schemas matched the input data.".format(cls) + ) + elif len(oneof_classes) > 1: + {{#if nonCompliantUseDiscriminatorIfCompositionFails}} + if discriminated_cls: + """ + return without exception because code was generated with + nonCompliantUseDiscriminatorIfCompositionFails=true + """ + return {} + {{/if}} + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. Multiple " + "oneOf schemas {} matched the inputs, but a max of one is allowed.".format(cls, oneof_classes) + ) + # exactly one class matches + return path_to_schemas + + @classmethod + def __get_anyof_classes( + cls, + arg, + discriminated_cls, + validation_metadata: ValidationMetadata + ): + anyof_classes = [] + path_to_schemas = defaultdict(set) + for anyof_cls in cls.MetaOapg.any_of(): + if validation_metadata.validation_ran_earlier(anyof_cls): + anyof_classes.append(anyof_cls) + continue + + try: + other_path_to_schemas = anyof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and anyof_cls is discriminated_cls: + {{#if nonCompliantUseDiscriminatorIfCompositionFails}} + """ + suppress exception because code was generated with + nonCompliantUseDiscriminatorIfCompositionFails=true + """ + pass + {{else}} + raise ex + {{/if}} + continue + anyof_classes.append(anyof_cls) + update(path_to_schemas, other_path_to_schemas) + if not anyof_classes: + {{#if nonCompliantUseDiscriminatorIfCompositionFails}} + if discriminated_cls: + """ + return without exception because code was generated with + nonCompliantUseDiscriminatorIfCompositionFails=true + """ + return {} + {{/if}} + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. None " + "of the anyOf schemas matched the input data.".format(cls) + ) + return path_to_schemas + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + ComposedBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + # validation checking on types, validations, and enums + path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + + # process composed schema + discriminator = None + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'discriminator'): + discriminator = cls.MetaOapg.discriminator() + discriminated_cls = None + if discriminator and arg and isinstance(arg, frozendict.frozendict): + disc_property_name = list(discriminator.keys())[0] + cls._ensure_discriminator_value_present_oapg(disc_property_name, updated_vm, arg) + # get discriminated_cls by looking at the dict in the current class + discriminated_cls = cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=arg[disc_property_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value '{}' was passed in to {}.{} Only the values {} are allowed at {}".format( + arg[disc_property_name], + cls.__name__, + disc_property_name, + list(discriminator[disc_property_name].keys()), + updated_vm.path_to_item + (disc_property_name,) + ) + ) + + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'all_of'): + other_path_to_schemas = cls.__get_allof_classes(arg, validation_metadata=updated_vm) + update(path_to_schemas, other_path_to_schemas) + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'one_of'): + other_path_to_schemas = cls.__get_oneof_class( + arg, + discriminated_cls=discriminated_cls, + validation_metadata=updated_vm + ) + update(path_to_schemas, other_path_to_schemas) + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'any_of'): + other_path_to_schemas = cls.__get_anyof_classes( + arg, + discriminated_cls=discriminated_cls, + validation_metadata=updated_vm + ) + update(path_to_schemas, other_path_to_schemas) + not_cls = None + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'not_schema'): + not_cls = cls.MetaOapg.not_schema + not_cls = cls._get_class_oapg(not_cls) + if not_cls: + other_path_to_schemas = None + not_exception = ApiValueError( + "Invalid value '{}' was passed in to {}. Value is invalid because it is disallowed by {}".format( + arg, + cls.__name__, + not_cls.__name__, + ) + ) + if updated_vm.validation_ran_earlier(not_cls): + raise not_exception + + try: + other_path_to_schemas = not_cls._validate_oapg(arg, validation_metadata=updated_vm) + except (ApiValueError, ApiTypeError): + pass + if other_path_to_schemas: + raise not_exception + + if discriminated_cls is not None and not updated_vm.validation_ran_earlier(discriminated_cls): + # TODO use an exception from this package here + assert discriminated_cls in path_to_schemas[updated_vm.path_to_item] + return path_to_schemas + + +# DictBase, ListBase, NumberBase, StrBase, BoolBase, NoneBase +class ComposedSchema( + ComposedBase, + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema, + NoneFrozenDictTupleStrDecimalBoolMixin +): + @classmethod + def from_openapi_data_oapg(cls, *args: typing.Any, _configuration: typing.Optional[Configuration] = None, **kwargs): + if not args: + if not kwargs: + raise ApiTypeError('{} is missing required input data in args or kwargs'.format(cls.__name__)) + args = (kwargs, ) + return super().from_openapi_data_oapg(args[0], _configuration=_configuration) + + +class ListSchema( + ListBase, + Schema, + TupleMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: typing.List[typing.Any], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[typing.List[typing.Any], typing.Tuple[typing.Any]], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class NoneSchema( + NoneBase, + Schema, + NoneMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: None, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: None, **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class NumberSchema( + NumberBase, + Schema, + DecimalMixin +): + """ + This is used for type: number with no format + Both integers AND floats are accepted + """ + + @classmethod + def from_openapi_data_oapg(cls, arg: typing.Union[int, float], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[decimal.Decimal, int, float], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class IntBase: + @property + def as_int_oapg(self) -> int: + try: + return self._as_int + except AttributeError: + self._as_int = int(self) + return self._as_int + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + + denominator = arg.as_integer_ratio()[-1] + if denominator != 1: + raise ApiValueError( + "Invalid value '{}' for type integer at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + IntBase _validate_oapg + TODO what about types = (int, number) -> IntBase, NumberBase? We could drop int and keep number only + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class IntSchema(IntBase, NumberSchema): + + @classmethod + def from_openapi_data_oapg(cls, arg: int, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[decimal.Decimal, int], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class Int32Base: + __inclusive_minimum = decimal.Decimal(-2147483648) + __inclusive_maximum = decimal.Decimal(2147483647) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal) and arg.as_tuple().exponent == 0: + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type int32 at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Int32Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Int32Schema( + Int32Base, + IntSchema +): + pass + + +class Int64Base: + __inclusive_minimum = decimal.Decimal(-9223372036854775808) + __inclusive_maximum = decimal.Decimal(9223372036854775807) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal) and arg.as_tuple().exponent == 0: + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type int64 at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Int64Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Int64Schema( + Int64Base, + IntSchema +): + pass + + +class Float32Base: + __inclusive_minimum = decimal.Decimal(-3.4028234663852886e+38) + __inclusive_maximum = decimal.Decimal(3.4028234663852886e+38) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type float at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Float32Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Float32Schema( + Float32Base, + NumberSchema +): + + @classmethod + def from_openapi_data_oapg(cls, arg: float, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + +class Float64Base: + __inclusive_minimum = decimal.Decimal(-1.7976931348623157E+308) + __inclusive_maximum = decimal.Decimal(1.7976931348623157E+308) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type double at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Float64Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + +class Float64Schema( + Float64Base, + NumberSchema +): + + @classmethod + def from_openapi_data_oapg(cls, arg: float, _configuration: typing.Optional[Configuration] = None): + # todo check format + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + +class StrSchema( + StrBase, + Schema, + StrMixin +): + """ + date + datetime string types must inherit from this class + That is because one can validate a str payload as both: + - type: string (format unset) + - type: string, format: date + """ + + @classmethod + def from_openapi_data_oapg(cls, arg: str, _configuration: typing.Optional[Configuration] = None) -> 'StrSchema': + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[str, date, datetime, uuid.UUID], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class UUIDSchema(UUIDBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, uuid.UUID], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DateSchema(DateBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, date], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DateTimeSchema(DateTimeBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, datetime], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DecimalSchema(DecimalBase, StrSchema): + + def __new__(cls, arg: str, **kwargs: Configuration): + """ + Note: Decimals may not be passed in because cast_to_allowed_types is only invoked once for payloads + which can be simple (str) or complex (dicts or lists with nested values) + Because casting is only done once and recursively casts all values prior to validation then for a potential + client side Decimal input if Decimal was accepted as an input in DecimalSchema then one would not know + if one was using it for a StrSchema (where it should be cast to str) or one is using it for NumberSchema + where it should stay as Decimal. + """ + return super().__new__(cls, arg, **kwargs) + + +class BytesSchema( + Schema, + BytesMixin +): + """ + this class will subclass bytes and is immutable + """ + def __new__(cls, arg: bytes, **kwargs: Configuration): + return super(Schema, cls).__new__(cls, arg) + + +class FileSchema( + Schema, + FileMixin +): + """ + This class is NOT immutable + Dynamic classes are built using it for example when AnyType allows in binary data + Al other schema classes ARE immutable + If one wanted to make this immutable one could make this a DictSchema with required properties: + - data = BytesSchema (which would be an immutable bytes based schema) + - file_name = StrSchema + and cast_to_allowed_types would convert bytes and file instances into dicts containing data + file_name + The downside would be that data would be stored in memory which one may not want to do for very large files + + The developer is responsible for closing this file and deleting it + + This class was kept as mutable: + - to allow file reading and writing to disk + - to be able to preserve file name info + """ + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader], **kwargs: Configuration): + return super(Schema, cls).__new__(cls, arg) + + +class BinaryBase: + pass + + +class BinarySchema( + ComposedBase, + BinaryBase, + Schema, + BinaryMixin +): + class MetaOapg: + @staticmethod + def one_of(): + return [ + BytesSchema, + FileSchema, + ] + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader, bytes], **kwargs: Configuration): + return super().__new__(cls, arg) + + +class BoolSchema( + BoolBase, + Schema, + BoolMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: bool, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: bool, **kwargs: ValidationMetadata): + return super().__new__(cls, arg, **kwargs) + + +class AnyTypeSchema( + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema, + NoneFrozenDictTupleStrDecimalBoolFileBytesMixin +): + # Python representation of a schema defined as true or {} + pass + + +class UnsetAnyTypeSchema(AnyTypeSchema): + # Used when additionalProperties/items was not explicitly defined and a defining schema is needed + pass + + +class NotAnyTypeSchema( + ComposedSchema, +): + """ + Python representation of a schema defined as false or {'not': {}} + Does not allow inputs in of AnyType + Note: validations on this class are never run because the code knows that no inputs will ever validate + """ + + class MetaOapg: + not_schema = AnyTypeSchema + + def __new__( + cls, + *args, + _configuration: typing.Optional[Configuration] = None, + ) -> 'NotAnyTypeSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + +class DictSchema( + DictBase, + Schema, + FrozenDictMixin +): + @classmethod + def from_openapi_data_oapg(cls, arg: typing.Dict[str, typing.Any], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, *args: typing.Union[dict, frozendict.frozendict], **kwargs: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, bytes, Schema, Unset, ValidationMetadata]): + return super().__new__(cls, *args, **kwargs) + + +schema_type_classes = {NoneSchema, DictSchema, ListSchema, NumberSchema, StrSchema, BoolSchema, AnyTypeSchema} + + +@functools.lru_cache() +def get_new_class( + class_name: str, + bases: typing.Tuple[typing.Type[typing.Union[Schema, typing.Any]], ...] +) -> typing.Type[Schema]: + """ + Returns a new class that is made with the subclass bases + """ + new_cls: typing.Type[Schema] = type(class_name, bases, {}) + return new_cls + + +LOG_CACHE_USAGE = False + + +def log_cache_usage(cache_fn): + if LOG_CACHE_USAGE: + print(cache_fn.__name__, cache_fn.cache_info()) diff --git a/modules/openapi-generator/src/main/resources/python-experimental/setup.handlebars b/modules/openapi-generator/src/main/resources/python/setup.handlebars similarity index 80% rename from modules/openapi-generator/src/main/resources/python-experimental/setup.handlebars rename to modules/openapi-generator/src/main/resources/python/setup.handlebars index 5633db861a..5cb64ff1e6 100644 --- a/modules/openapi-generator/src/main/resources/python-experimental/setup.handlebars +++ b/modules/openapi-generator/src/main/resources/python/setup.handlebars @@ -15,20 +15,7 @@ VERSION = "{{packageVersion}}" # http://pypi.python.org/pypi/setuptools REQUIRES = [ - "urllib3 >= 1.15", - "certifi", - "python-dateutil", - "frozendict >= 2.0.3", -{{#if asyncio}} - "aiohttp >= 3.0.0", -{{/if}} -{{#if tornado}} - "tornado>=4.2,<5", -{{/if}} -{{#if hasHttpSignatureMethods}} - "pem>=19.3.0", - "pycryptodome>=3.9.0", -{{/if}} + {{> required_libraries quoted=true }} ] setup( diff --git a/modules/openapi-generator/src/main/resources/python-experimental/setup_cfg.handlebars b/modules/openapi-generator/src/main/resources/python/setup_cfg.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/setup_cfg.handlebars rename to modules/openapi-generator/src/main/resources/python/setup_cfg.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/signing.handlebars b/modules/openapi-generator/src/main/resources/python/signing.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/signing.handlebars rename to modules/openapi-generator/src/main/resources/python/signing.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/test-requirements.handlebars b/modules/openapi-generator/src/main/resources/python/test-requirements.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/test-requirements.handlebars rename to modules/openapi-generator/src/main/resources/python/test-requirements.handlebars diff --git a/modules/openapi-generator/src/main/resources/python-experimental/tox.handlebars b/modules/openapi-generator/src/main/resources/python/tox.handlebars similarity index 83% rename from modules/openapi-generator/src/main/resources/python-experimental/tox.handlebars rename to modules/openapi-generator/src/main/resources/python/tox.handlebars index d1b68916df..b2544b81d4 100644 --- a/modules/openapi-generator/src/main/resources/python-experimental/tox.handlebars +++ b/modules/openapi-generator/src/main/resources/python/tox.handlebars @@ -1,7 +1,8 @@ [tox] -envlist = py39 +envlist = py37 [testenv] +passenv = PYTHON_VERSION deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt diff --git a/modules/openapi-generator/src/main/resources/python-experimental/travis.handlebars b/modules/openapi-generator/src/main/resources/python/travis.handlebars similarity index 100% rename from modules/openapi-generator/src/main/resources/python-experimental/travis.handlebars rename to modules/openapi-generator/src/main/resources/python/travis.handlebars diff --git a/modules/openapi-generator/src/main/resources/r/.travis.yml b/modules/openapi-generator/src/main/resources/r/.travis.yml deleted file mode 100644 index b96a0ef5a8..0000000000 --- a/modules/openapi-generator/src/main/resources/r/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -# ref: https://docs.travis-ci.com/user/languages/r/ -language: r -cache: - directories: - - /home/travis/R/Library -r_packages: -- jsonlite -- httr -- testthat -# uncomment below to install deps with devtools -#install: -#- R -e 'devtools::install_deps(dep = T)' -script: -- R CMD build . -- R CMD check *tar.gz -- R CMD INSTALL *tar.gz -after_failure: -- cat ${TRAVIS_BUILD_DIR}/namsor.Rcheck/tests/testthat.Rout.fail diff --git a/modules/openapi-generator/src/main/resources/r/.travis.yml.mustache b/modules/openapi-generator/src/main/resources/r/.travis.yml.mustache new file mode 100644 index 0000000000..a14eb1abdd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/r/.travis.yml.mustache @@ -0,0 +1,23 @@ +# ref: https://docs.travis-ci.com/user/languages/r/ +language: r +cache: + directories: + - /home/travis/R/Library +r_packages: +- jsonlite +{{^isHttr2}} +- httr +{{/isHttr2}} +{{#isHttr2}} +- httr2 +{{/isHttr2}} +- testthat +# uncomment below to install deps with devtools +#install: +#- R -e 'devtools::install_deps(dep = T)' +script: +- R CMD build . +- R CMD check *tar.gz +- R CMD INSTALL *tar.gz +after_failure: +- cat ${TRAVIS_BUILD_DIR}/namsor.Rcheck/tests/testthat.Rout.fail diff --git a/modules/openapi-generator/src/main/resources/r/ApiResponse.mustache b/modules/openapi-generator/src/main/resources/r/ApiResponse.mustache index 49499873c1..ca8c3f7858 100644 --- a/modules/openapi-generator/src/main/resources/r/ApiResponse.mustache +++ b/modules/openapi-generator/src/main/resources/r/ApiResponse.mustache @@ -5,12 +5,18 @@ #' @format An \code{R6Class} generator object #' @field content The deserialized response body. #' @field response The raw response from the endpoint. +#' @field status_code The HTTP response status code. +#' @field status_code_desc The brief descriptoin of the HTTP response status code. +#' @field headers The HTTP response headers. #' @export ApiResponse <- R6::R6Class( "ApiResponse", public = list( content = NULL, response = NULL, + status_code = NULL, + status_code_desc = NULL, + headers = NULL, #' Initialize a new ApiResponse class. #' #' @description @@ -18,10 +24,20 @@ ApiResponse <- R6::R6Class( #' #' @param content The deserialized response body. #' @param response The raw response from the endpoint. + #' @param status_code The HTTP response status code. + #' @param status_code_desc The brief description of the HTTP response status code. + #' @param headers The HTTP response headers. #' @export - initialize = function(content, response) { + initialize = function(content = NULL, + response = NULL, + status_code = NULL, + status_code_desc = NULL, + headers = NULL) { self$content <- content self$response <- response + self$status_code <- status_code + self$status_code_desc <- status_code_desc + self$headers <- headers } ) ) diff --git a/modules/openapi-generator/src/main/resources/r/NAMESPACE.mustache b/modules/openapi-generator/src/main/resources/r/NAMESPACE.mustache index b040f5adc4..709cb56438 100644 --- a/modules/openapi-generator/src/main/resources/r/NAMESPACE.mustache +++ b/modules/openapi-generator/src/main/resources/r/NAMESPACE.mustache @@ -3,8 +3,19 @@ import(R6) import(jsonlite) +{{^isHttr2}} import(httr) +{{/isHttr2}} +{{#isHttr2}} +import(httr2) +{{/isHttr2}} import(base64enc) +import(stringr) + +{{#generateWrapper}} +# Wrapper +export({{#lambda.lowercase}}{{{packageName}}}{{/lambda.lowercase}}_api) +{{/generateWrapper}} # Core export(ApiClient) diff --git a/modules/openapi-generator/src/main/resources/r/README.mustache b/modules/openapi-generator/src/main/resources/r/README.mustache index 1da3dffd0c..961894a3f2 100644 --- a/modules/openapi-generator/src/main/resources/r/README.mustache +++ b/modules/openapi-generator/src/main/resources/r/README.mustache @@ -63,6 +63,17 @@ install.packages("{{{packageName}}}_{{{packageVersion}}}.tar.gz", repos = NULL, library({{{packageName}}}) ``` +### Reformat code + +To reformat code using [styler](https://styler.r-lib.org/index.html), please run the following in the R console: + +```R +install.packages("remotes") +remotes::install_github("r-lib/styler@v1.7.0.9003") +library("styler") +style_dir() +``` + ## Documentation for API Endpoints All URIs are relative to *{{basePath}}* @@ -83,24 +94,52 @@ Class | Method | HTTP request | Description {{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} {{#authMethods}}### {{name}} -{{#isApiKey}}- **Type**: API key +{{#isApiKey}} +- **Type**: API key - **API key parameter name**: {{keyParamName}} - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} {{/isApiKey}} -{{#isBasic}}- **Type**: HTTP basic authentication +{{#isBasic}} +{{#isHttpSignature}} +- **Type**: HTTP signature authentication +{{/isHttpSignature}} +{{#isBasicBasic}} +- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}} +- **Type**: Bearer authentication +{{#bearerFormat}} +- **Bearer Format**: {{{.}}} +{{/bearerFormat}} +{{/isBasicBearer}} {{/isBasic}} -{{#isOAuth}}- **Type**: OAuth +{{#isOAuth}} +- **Type**: OAuth - **Flow**: {{flow}} +{{#authorizationUrl}} - **Authorization URL**: {{authorizationUrl}} +{{/authorizationUrl}} +{{#tokenUrl}} +- **Token URL**: {{tokenUrl}} +{{/tokenUrl}} +{{#refreshUrl}} +- **Refresh URL**: {{refreshUrl}} +{{/refreshUrl}} - **Scopes**: {{^scopes}}N/A{{/scopes}} -{{#scopes}} - {{scope}}: {{description}} +{{#scopes}} - `{{scope}}`: {{description}} {{/scopes}} {{/isOAuth}} {{/authMethods}} - +{{#apiInfo}} +{{#apis}} +{{#-last}} +{{#infoEmail}} ## Author -{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}} -{{/-last}}{{/apis}}{{/apiInfo}} +{{{infoEmail}}} +{{/infoEmail}} +{{/-last}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/r/Rbuildignore.mustache b/modules/openapi-generator/src/main/resources/r/Rbuildignore.mustache index b3cedf7751..8d82cac4c4 100644 --- a/modules/openapi-generator/src/main/resources/r/Rbuildignore.mustache +++ b/modules/openapi-generator/src/main/resources/r/Rbuildignore.mustache @@ -11,6 +11,7 @@ ^\.gitignore$ ^\.openapi-generator-ignore$ ^\.travis\.yml$ +^\.lintr$ ^\.github$ ^\.openapi-generator$ ^docs$ diff --git a/modules/openapi-generator/src/main/resources/r/api.mustache b/modules/openapi-generator/src/main/resources/r/api.mustache index 5526432950..db49260916 100644 --- a/modules/openapi-generator/src/main/resources/r/api.mustache +++ b/modules/openapi-generator/src/main/resources/r/api.mustache @@ -2,7 +2,7 @@ {{#operations}} #' @docType class #' @title {{baseName}} operations -#' @description {{importPath}} +#' @description {{{description}}}{{^description}}{{{classname}}}{{/description}} #' @format An \code{R6Class} generator object #' @field api_client Handles the client-server communication. #' @@ -10,9 +10,9 @@ {{! Adding the below changes for generating documentation for the api methods. }} #' \describe{ {{#operation}} -#' \strong{ {{operationId}} } \emph{ {{summary}} } +#' \strong{ {{operationId}} } \emph{ {{#lambdaRdocEscape}}{{summary}}{{/lambdaRdocEscape}} } {{#notes}} -#' {{notes}} +#' {{#lambdaRdocEscape}}{{{.}}}{{/lambdaRdocEscape}} {{/notes}} #' #' \itemize{ @@ -62,14 +62,14 @@ {{/useRlangExceptionHandling}} #' {{#responses}} -#' \item status code : {{code}} | {{message}} +#' \item status code : {{code}} | {{{message}}} #' -#'{{#dataType}} \item return type : {{.}} {{/dataType}} +#'{{#dataType}} \item return type : {{{.}}}{{/dataType}} #' \item response headers : #' #' \tabular{ll}{ {{#headers}} -#' {{name}} \tab {{description}} \cr +#' {{name}} \tab {{{description}}} \cr {{/headers}} #' } {{/responses}} @@ -86,57 +86,90 @@ #' #' library({{{packageName}}}) {{#allParams}} -#' var.{{{paramName}}} <- {{{example}}} # {{{dataType}}} | {{{description}}} +#' var_{{{paramName}}} <- {{{example}}} # {{{dataType}}} | {{{description}}} {{/allParams}} #' {{#summary}} #' #{{{.}}} {{/summary}} -#' api.instance <- {{{classname}}}$new() +{{#generateWrapper}} +#' api_instance <- {{#lambda.lowercase}}{{{packageName}}}{{/lambda.lowercase}}_api$new() +{{/generateWrapper}} +{{^generateWrapper}} +#' api_instance <- {{{classname}}}$new() +{{/generateWrapper}} {{#hasAuthMethods}} {{#authMethods}} #' {{#isBasic}} -#' #Configure HTTP basic authorization: {{{name}}} -#' # provide your username in the user-serial format -#' api.instance$api_client$username <- ''; -#' # provide your api key generated using the developer portal -#' api.instance$api_client$password <- ''; +{{#isBasicBasic}} +#' # Configure HTTP basic authorization: {{{name}}} +#' api_instance$api_client$username <- Sys.getenv("USERNAME") +#' api_instance$api_client$password <- Sys.getenv("PASSWORD") +{{/isBasicBasic}} +{{#isBasicBearer}} +#' # Configure HTTP bearer authorization: {{{name}}} +#' api_instance$api_client$bearer_token <- Sys.getenv("BEARER_TOKEN") +{{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} -#' #Configure API key authorization: {{{name}}} -#' api.instance$api_client$api_keys['{{{keyParamName}}}'] <- 'TODO_YOUR_API_KEY'; +#' # Configure API key authorization: {{{name}}} +#' api_instance$api_client$api_keys["{{{keyParamName}}}"] <- Sys.getenv("API_KEY") {{/isApiKey}} {{#isOAuth}} #' # Configure OAuth2 access token for authorization: {{{name}}} -#' api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} #' {{#returnExceptionOnFailure}} {{#useRlangExceptionHandling}} -#'result <- tryCatch( -#' api.instance${{{operationId}}}({{#requiredParams}}var.{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}}=var.{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' {{#returnType}} +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance{{#generateWrapper}}${{#lambda.snakecase}}{{{classname}}}{{/lambda.snakecase}}{{/generateWrapper}}${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}data_file = "result.txt"), +#' {{#vendorExtensions.x-streaming}} +#' # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. +#' # api_instance{{#generateWrapper}}${{#lambda.snakecase}}{{{classname}}}{{/lambda.snakecase}}{{/generateWrapper}}${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}stream_callback = function(x){ print(length(x)) }), +#' {{/vendorExtensions.x-streaming}} +#' {{/returnType}} +#' api_instance{{#generateWrapper}}${{#lambda.snakecase}}{{{classname}}}{{/lambda.snakecase}}{{/generateWrapper}}${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -{{#returnType}} -#' # deserialized response object -#' response.object <- result$content -{{/returnType}} -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `{{{operationId}}}`:") +#' dput(result$ApiException$toString()) +#' {{#errorObjectType}} +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' {{/errorObjectType}} +#' }{{#returnType}} else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } +{{/returnType}} +#' +{{^returnType}} +#' # This endpoint doesn't return data +{{/returnType}} {{/useRlangExceptionHandling}} {{/returnExceptionOnFailure}} {{^useRlangExceptionHandling}} -#' result <- api.instance${{{operationId}}}({{#requiredParams}}var.{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}}=var.{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}) +{{#returnType}} +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # result <- api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}data_file = "result.txt") +{{/returnType}} +{{#vendorExtensions.x-streaming}} +#' # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. +#' # api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}stream_callback = function(x){ print(length(x)) }) +{{/vendorExtensions.x-streaming}} +#' {{#returnType}}result <- {{/returnType}}api_instance{{#generateWrapper}}${{#lambda.snakecase}}{{{classname}}}{{/lambda.snakecase}}{{/generateWrapper}}${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}) +{{#returnType}} +#' dput(result) +{{/returnType}} {{/useRlangExceptionHandling}} #' #' @@ -176,7 +209,7 @@ #' @param {{{paramName}}} {{{description}}} {{/requiredParams}} {{#optionalParams}} - #' @param {{{paramName}}} (optional){{{description}}} {{#defaultValue}} (default value: {{{.}}}){{/defaultValue}} + #' @param {{{paramName}}} (optional) {{{description}}}{{^description}}No description{{/description}}{{#defaultValue}} (default value: {{{.}}}){{/defaultValue}} {{/optionalParams}} {{#vendorExtensions.x-streaming}} #' @param stream_callback (optional) callback function to process the data stream @@ -187,23 +220,22 @@ #' @param ... Other optional arguments #' @return {{{returnType}}}{{^returnType}}void{{/returnType}} #' @export - {{{operationId}}} = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#vendorExtensions.x-streaming}}stream_callback=NULL, {{/vendorExtensions.x-streaming}}{{#returnType}}data_file = NULL, {{/returnType}}...) { - api_response <- self${{{operationId}}}WithHttpInfo({{#allParams}}{{paramName}}, {{/allParams}}{{#vendorExtensions.x-streaming}}stream_callback = stream_callback, {{/vendorExtensions.x-streaming}}{{#returnType}}data_file = data_file, {{/returnType}}...) + {{{operationId}}} = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}} = {{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#vendorExtensions.x-streaming}}stream_callback = NULL, {{/vendorExtensions.x-streaming}}{{#returnType}}data_file = NULL, {{/returnType}}...) { + local_var_response <- self${{{operationId}}}{{WithHttpInfo}}({{#allParams}}{{paramName}}, {{/allParams}}{{#vendorExtensions.x-streaming}}stream_callback = stream_callback, {{/vendorExtensions.x-streaming}}{{#returnType}}data_file = data_file, {{/returnType}}...) {{#vendorExtensions.x-streaming}} if (typeof(stream_callback) == "closure") { # return void if streaming is enabled return(invisible(NULL)) } {{/vendorExtensions.x-streaming}} - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' {{{summary}}} @@ -215,7 +247,7 @@ #' @param {{{paramName}}} {{{description}}} {{/requiredParams}} {{#optionalParams}} - #' @param {{{paramName}}} (optional) {{{description}}}{{#defaultValue}} (default value: {{{.}}}){{/defaultValue}} + #' @param {{{paramName}}} (optional) {{{description}}}{{^description}}No description{{/description}}{{#defaultValue}} (default value: {{{.}}}){{/defaultValue}} {{/optionalParams}} {{#vendorExtensions.x-streaming}} #' @param stream_callback (optional) callback function to process the data stream @@ -226,10 +258,15 @@ #' @param ... Other optional arguments #' @return API response ({{{returnType}}}{{^returnType}}void{{/returnType}}) with additional information such as HTTP status code, headers #' @export - {{{operationId}}}WithHttpInfo = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#vendorExtensions.x-streaming}}stream_callback=NULL, {{/vendorExtensions.x-streaming}}{{#returnType}}data_file = NULL, {{/returnType}}...) { + {{{operationId}}}{{WithHttpInfo}} = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}} = {{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#vendorExtensions.x-streaming}}stream_callback = NULL, {{/vendorExtensions.x-streaming}}{{#returnType}}data_file = NULL, {{/returnType}}...) { args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE {{#requiredParams}} if (missing(`{{paramName}}`)) { @@ -245,36 +282,255 @@ } {{/requiredParams}} - {{#header_params}} + {{#allParams}} + {{#maxLength}} + if (nchar(`{{paramName}}`) > {{maxLength}}) { + {{#useDefaultExceptionHandling}} + stop("Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, must be smaller than or equal to {{maxLength}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, must be smaller than or equal to {{maxLength}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.")) + {{/useRlangExceptionHandling}} + } + {{/maxLength}} + {{#minLength}} + if (nchar(`{{paramName}}`) < {{minLength}}) { + {{#useDefaultExceptionHandling}} + stop("Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, must be bigger than or equal to {{minLength}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, must be bigger than or equal to {{minLength}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, must be bigger than or equal to {{minLength}}.")) + {{/useRlangExceptionHandling}} + } + {{/minLength}} + {{#maximum}} + if (`{{paramName}}` >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { + {{#useDefaultExceptionHandling}} + stop("Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.")) + {{/useRlangExceptionHandling}} + } + {{/maximum}} + {{#minimum}} + if (`{{paramName}}` <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { + {{#useDefaultExceptionHandling}} + stop("Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.")) + {{/useRlangExceptionHandling}} + } + {{/minimum}} + {{#pattern}} + if (!str_detect(`{{paramName}}`, "{{{pattern}}}")) { + {{#useDefaultExceptionHandling}} + stop("Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}, must conform to the pattern {{{pattern}}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}, must conform to the pattern {{{pattern}}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}, must conform to the pattern {{{pattern}}}.")) + {{/useRlangExceptionHandling}} + } + {{/pattern}} + {{#maxItems}} + if (length(`{{paramName}}`) > {{maxItems}}) { + {{#useDefaultExceptionHandling}} + stop("Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, number of items must be less than or equal to {{maxItems}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, number of items must be less than or equal to {{maxItems}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, number of items must be less than or equal to {{maxItems}}.")) + {{/useRlangExceptionHandling}} + } + {{/maxItems}} + {{#minItems}} + if (length(`{{paramName}}`) < {{minItems}}) { + {{#useDefaultExceptionHandling}} + stop("Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, number of items must be greater than or equal to {{minItems}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, number of items must be greater than or equal to {{minItems}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid length for `{{paramName}}` when calling {{classname}}${{operationId}}, number of items must be greater than or equal to {{minItems}}.")) + {{/useRlangExceptionHandling}} + } + {{/minItems}} + + {{/allParams}} + {{#headerParams}} header_params["{{baseName}}"] <- `{{paramName}}` - {{/header_params}} - {{#query_params}} - query_params["{{baseName}}"] <- {{paramName}} + {{/headerParams}} + {{#queryParams}} + {{#isArray}} + {{#uniqueItems}} + # check if items are unique + if (!identical(`{{{paramName}}}`, unique(`{{{paramName}}}`))) { + {{#useDefaultExceptionHandling}} + stop("Invalid value for {{{paramName}}} when calling {{classname}}${{operationId}}. Items must be unqiue.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Items must be unique.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Items must be unique.")) + {{/useRlangExceptionHandling}} + } + {{#isExplode}} + # explore + for (query_item in `{{{paramName}}}`) { + {{#items}} + {{#isEnum}} + # validate enum values + if (!(query_item %in% c({{#_enum}}"{{{.}}}"{{^-last}}, {{/-last}}{{/_enum}}))) { + {{#useDefaultExceptionHandling}} + stop("Invalid value for {{{paramName}}} when calling {{classname}}${{operationId}}. Must be {{_enum}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.")) + {{/useRlangExceptionHandling}} + } + {{/isEnum}} + {{/items}} + query_params[["{{{baseName}}}"]] <- c(query_params[["{{{baseName}}}"]], list(`{{{baseName}}}` = query_item)) + } + {{/isExplode}} + {{^isExplode}} + # no explore + {{#items}} + {{#isEnum}} + # validate enum values + for (query_item in `{{{paramName}}}`) { + if (!(query_item %in% c({{#_enum}}"{{{.}}}"{{^-last}}, {{/-last}}{{/_enum}}))) { + {{#useDefaultExceptionHandling}} + stop("Invalid value for {{{paramName}}} when calling {{classname}}${{operationId}}. Must be {{_enum}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.")) + {{/useRlangExceptionHandling}} + } + } + {{/isEnum}} + {{/items}} + query_params[["{{{baseName}}}"]] <- I(paste(lapply(`{{{paramName}}}`, URLencode, reserved = TRUE), collapse = ",")) + {{/isExplode}} + {{/uniqueItems}} + {{^uniqueItems}} + {{#isExplode}} + # explore + for (query_item in `{{{paramName}}}`) { + {{#items}} + {{#isEnum}} + # validate enum values + if (!(query_item %in% c({{#_enum}}"{{{.}}}"{{^-last}}, {{/-last}}{{/_enum}}))) { + {{#useDefaultExceptionHandling}} + stop("Invalid value for {{{paramName}}} when calling {{classname}}${{operationId}}. Must be {{_enum}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.")) + {{/useRlangExceptionHandling}} + } + {{/isEnum}} + {{/items}} + query_params[["{{{baseName}}}"]] <- c(query_params[["{{{baseName}}}"]], list(`{{{baseName}}}` = query_item)) + } + {{/isExplode}} + {{^isExplode}} + # no explore + {{#items}} + {{#isEnum}} + # validate enum values + for (query_item in `{{{paramName}}}`) { + if (!(query_item %in% c({{#_enum}}"{{{.}}}"{{^-last}}, {{/-last}}{{/_enum}}))) { + {{#useDefaultExceptionHandling}} + stop("Invalid value for {{{paramName}}} when calling {{classname}}${{operationId}}. Must be {{_enum}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.")) + {{/useRlangExceptionHandling}} + } + } + {{/isEnum}} + {{/items}} + query_params[["{{{baseName}}}"]] <- I(paste(lapply(`{{{paramName}}}`, URLencode, reserved = TRUE), collapse = ",")) + {{/isExplode}} + {{/uniqueItems}} + {{/isArray}} + {{^isArray}} + {{#isEnum}} + if (!(`{{paramName}}` %in% c({{#_enum}}"{{{.}}}"{{^-last}}, {{/-last}}{{/_enum}}))) { + {{#useDefaultExceptionHandling}} + stop("Invalid value for {{{paramName}}} when calling {{classname}}${{operationId}}. Must be {{_enum}}.") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `{{paramName}}` when calling {{classname}}${{operationId}}. Must be {{_enum}}.")) + {{/useRlangExceptionHandling}} + } + {{/isEnum}} + query_params[["{{baseName}}"]] <- `{{paramName}}` + {{/isArray}} - {{/query_params}} + {{/queryParams}} {{#hasFormParams}} - body <- list( - {{#formParams}} - {{^isFile}} - "{{baseName}}" = {{paramName}}{{^-last}},{{/-last}} - {{/isFile}} - {{#isFile}} - "{{baseName}}" = httr::upload_file({{paramName}}){{^-last}},{{/-last}} - {{/isFile}} - {{/formParams}} - ) - + {{#formParams}} + {{^isFile}} + form_params["{{baseName}}"] <- `{{paramName}}` + {{/isFile}} + {{#isFile}} + {{^isHttr2}} + file_params["{{baseName}}"] <- httr::upload_file(`{{paramName}}`) + {{/isHttr2}} + {{#isHttr2}} + file_params["{{baseName}}"] <- curl::form_file(`{{paramName}}`) + {{/isHttr2}} + {{/isFile}} + {{/formParams}} {{/hasFormParams}} {{#hasBodyParam}} {{#bodyParams}} - if (!missing(`{{paramName}}`)) { + if (!is.null(`{{paramName}}`)) { {{#isArray}} - body.items = paste(unlist(lapply({{paramName}}, function(param) {param$toJSONString()})), collapse = ",") - body <- paste0("[", body.items, "]") + body.items <- paste(unlist(lapply(`{{paramName}}`, function(param) { + param$toJSONString() + })), collapse = ",") + local_var_body <- paste0("[", body.items, "]") {{/isArray}} {{^isArray}} - body <- `{{paramName}}`$toJSONString() + local_var_body <- `{{paramName}}`$toJSONString() {{/isArray}} } else { body <- NULL @@ -282,16 +538,18 @@ {{/bodyParams}} {{/hasBodyParam}} - {{^hasBodyParam}} - {{^hasFormParams}} - body <- NULL - {{/hasFormParams}} - {{/hasBodyParam}} - url_path <- "{{path}}" + local_var_url_path <- "{{path}}" {{#hasPathParams}} {{#pathParams}} if (!missing(`{{paramName}}`)) { - url_path <- gsub(paste0("\\{", "{{baseName}}", "\\}"), URLencode(as.character(`{{paramName}}`), reserved = TRUE), url_path) + {{=< >=}} + <#isArray> + local_var_url_path <- gsub("\\{\\}", paste(URLencode(as.character(``), reserved = TRUE), collapse= ",", sep=""), local_var_url_path) + + <^isArray> + local_var_url_path <- gsub("\\{\\}", URLencode(as.character(``), reserved = TRUE), local_var_url_path) + + <={{ }}=> } {{/pathParams}} @@ -300,8 +558,16 @@ {{#isBasic}} {{#isBasicBasic}} # HTTP basic auth - header_params["Authorization"] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$api_client$username, self$api_client$password, sep = ":")))) + if (!is.null(self$api_client$username) || !is.null(self$api_client$password)) { + header_params["Authorization"] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$api_client$username, self$api_client$password, sep = ":")))) + } {{/isBasicBasic}} + {{#isBasicBearer}} + # Bearer token + if (!is.null(self$api_client$bearer_token)) { + header_params["Authorization"] <- paste("Bearer", self$api_client$bearer_token, sep = " ") + } + {{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} # API key authentication @@ -317,16 +583,29 @@ {{/isKeyInQuery}} {{/isApiKey}} {{#isOAuth}} - # OAuth token - header_params["Authorization"] <- paste("Bearer", self$api_client$access_token, sep = " ") + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "{{#scopes}}{{scope}}{{^-last}} {{/-last}}{{/scopes}}" {{/isOAuth}} {{/authMethods}} - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list({{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}}) + + # The Content-Type representation header + local_var_content_types <- list({{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}}) + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "{{httpMethod}}", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, {{#vendorExtensions.x-streaming}} stream_callback = stream_callback, {{/vendorExtensions.x-streaming}} @@ -338,15 +617,15 @@ } {{/vendorExtensions.x-streaming}} - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { {{#returnType}} {{#isPrimitiveType}} - content <- httr::content( - resp, "text", encoding = "UTF-8", simplifyVector = FALSE + local_var_content <- local_var_resp$response + local_var_resp, "text", encoding = "UTF-8", simplifyVector = FALSE ) # save response in a file if (!is.null(data_file)) { - write(content, data_file) + write(local_var_content, data_file) } ApiResponse$new(content,resp) @@ -354,83 +633,87 @@ {{^isPrimitiveType}} # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "{{returnType}}", loadNamespace("{{packageName}}")), + self$api_client$deserialize(local_var_resp$response, "{{returnType}}", loadNamespace("{{packageName}}")), error = function(e) { - {{#useDefaultExceptionHandling}} - stop("Failed to deserialize response") - {{/useDefaultExceptionHandling}} - {{#useRlangExceptionHandling}} - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - {{/useRlangExceptionHandling}} + {{#useDefaultExceptionHandling}} + stop("Failed to deserialize response") + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + {{/useRlangExceptionHandling}} } ) - ApiResponse$new(deserialized_resp_obj, resp) + local_var_resp$content <- deserialized_resp_obj {{/isPrimitiveType}} {{/returnType}} {{^returnType}} {{! Returning the ApiResponse object with NULL object when the endpoint doesn't return anything}} - ApiResponse$new(NULL, resp) + local_var_resp$content <- NULL {{/returnType}} - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { {{#returnExceptionOnFailure}} - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") } {{#useDefaultExceptionHandling}} - stop(error_msg) + stop(local_var_error_msg) + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + {{/useRlangExceptionHandling}} + {{/returnExceptionOnFailure}} + {{^returnExceptionOnFailure}} + ApiResponse$new(paste("Server returned ", local_var_resp$status_code, " response status code."), local_var_resp) + {{/returnExceptionOnFailure}} + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + {{#returnExceptionOnFailure}} + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + {{#useDefaultExceptionHandling}} + stop(local_var_error_msg) + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + {{/useRlangExceptionHandling}} + {{/returnExceptionOnFailure}} + {{^returnExceptionOnFailure}} + ApiResponse$new("API client error", local_var_resp) + {{/returnExceptionOnFailure}} + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + {{#returnExceptionOnFailure}} + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + {{#useDefaultExceptionHandling}} + stop(local_var_error_msg) {{/useDefaultExceptionHandling}} {{#useRlangExceptionHandling}} rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) {{/useRlangExceptionHandling}} - {{/returnExceptionOnFailure}} - {{^returnExceptionOnFailure}} - ApiResponse$new(paste("Server returned ", httr::status_code(resp), " response status code."), resp) - {{/returnExceptionOnFailure}} - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - {{#returnExceptionOnFailure}} - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." + {{/returnExceptionOnFailure}} + {{^returnExceptionOnFailure}} + if (is.null(local_var_resp$response) || local_var_resp$response == "") { + local_var_resp$response <- "API server error" } - {{#useDefaultExceptionHandling}} - stop(error_msg) - {{/useDefaultExceptionHandling}} - {{#useRlangExceptionHandling}} - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - {{/useRlangExceptionHandling}} - {{/returnExceptionOnFailure}} - {{^returnExceptionOnFailure}} - ApiResponse$new("API client error", resp) - {{/returnExceptionOnFailure}} - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - {{#returnExceptionOnFailure}} - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - {{#useDefaultExceptionHandling}} - stop(error_msg) - {{/useDefaultExceptionHandling}} - {{#useRlangExceptionHandling}} - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - {{/useRlangExceptionHandling}} - {{/returnExceptionOnFailure}} - {{^returnExceptionOnFailure}} - ApiResponse$new("API server error", resp) - {{/returnExceptionOnFailure}} + local_var_resp + {{/returnExceptionOnFailure}} } }{{^-last}},{{/-last}} {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/r/api_client.mustache b/modules/openapi-generator/src/main/resources/r/api_client.mustache index 1f40df7451..395ff41be4 100644 --- a/modules/openapi-generator/src/main/resources/r/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/r/api_client.mustache @@ -21,7 +21,21 @@ #' @field username Username for HTTP basic authentication #' @field password Password for HTTP basic authentication #' @field api_keys API keys +{{#hasOAuthMethods}} #' @field access_token Access token +#' @field oauth_client_id OAuth client ID +#' @field oauth_secret OAuth secret +#' @field oauth_refresh_token OAuth refresh token +{{#authMethods}} +{{#isOAuth}} +#' @field oauth_flow_type OAuth flow type +#' @field oauth_authorization_url Authoriziation URL +#' @field oauth_token_url Token URL +#' @field oauth_pkce Boolean flag to enable PKCE +{{/isOAuth}} +{{/authMethods}} +{{/hasOAuthMethods}} +#' @field bearer_token Bearer token #' @field timeout Default timeout in seconds #' @field retry_status_codes vector of status codes to retry #' @field max_retry_attempts maximum number of retries for the status codes @@ -30,7 +44,7 @@ #' @importFrom rlang abort {{/useRlangExceptionHandling}} #' @export -ApiClient <- R6::R6Class( +ApiClient <- R6::R6Class( "ApiClient", public = list( # base path of all requests @@ -45,8 +59,31 @@ ApiClient <- R6::R6Class( password = NULL, # API keys api_keys = NULL, + {{#hasOAuthMethods}} # Access token access_token = NULL, + # OAuth2 client ID + oauth_client_id = NULL, + # OAuth2 secret + oauth_secret = NULL, + # OAuth2 refresh token + oauth_refresh_token = NULL, + # OAuth2 + {{#authMethods}} + {{#isOAuth}} + # Flow type + oauth_flow_type = "{{flow}}", + # Authoriziation URL + oauth_authorization_url = "{{authorizationUrl}}", + # Token URL + oauth_token_url = "{{tokenUrl}}", + # Enable PKCE? + oauth_pkce = TRUE, + {{/isOAuth}} + {{/authMethods}} + {{/hasOAuthMethods}} + # Bearer token + bearer_token = NULL, # Time Out (seconds) timeout = NULL, # Vector of status codes to retry @@ -65,6 +102,7 @@ ApiClient <- R6::R6Class( #' @param password Password. #' @param api_keys API keys. #' @param access_token Access token. + #' @param bearer_token Bearer token. #' @param timeout Timeout. #' @param retry_status_codes Status codes for retry. #' @param max_retry_attempts Maxmium number of retry. @@ -72,7 +110,7 @@ ApiClient <- R6::R6Class( initialize = function(base_path = NULL, user_agent = NULL, default_headers = NULL, username = NULL, password = NULL, api_keys = NULL, - access_token = NULL, timeout = NULL, + access_token = NULL, bearer_token = NULL, timeout = NULL, retry_status_codes = NULL, max_retry_attempts = NULL) { if (!is.null(base_path)) { self$base_path <- base_path @@ -94,6 +132,10 @@ ApiClient <- R6::R6Class( self$access_token <- access_token } + if (!is.null(bearer_token)) { + self$bearer_token <- bearer_token + } + if (!is.null(api_keys)) { self$api_keys <- api_keys } else { @@ -125,15 +167,23 @@ ApiClient <- R6::R6Class( #' @param method HTTP method. #' @param query_params The query parameters. #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters for uploading files. + #' @param accepts The list of Accept headers. + #' @param content_types The list of Content-Type headers. #' @param body The HTTP request body. #' @param stream_callback Callback function to process the data stream #' @param ... Other optional arguments. #' @return HTTP response #' @export - CallApi = function(url, method, query_params, header_params, body, stream_callback = NULL, ...) { + CallApi = function(url, method, query_params, header_params, form_params, + file_params, accepts, content_types, + body, stream_callback = NULL, ...) { - resp <- self$Execute(url, method, query_params, header_params, body, stream_callback = stream_callback, ...) - status_code <- httr::status_code(resp) + resp <- self$Execute(url, method, query_params, header_params, + form_params, file_params, + accepts, content_types, + body, stream_callback = stream_callback, ...) if (is.null(self$max_retry_attempts)) { self$max_retry_attempts <- 3 @@ -142,10 +192,11 @@ ApiClient <- R6::R6Class( if (!is.null(self$retry_status_codes)) { for (i in 1 : self$max_retry_attempts) { - if (status_code %in% self$retry_status_codes) { + if (resp$status_code %in% self$retry_status_codes) { Sys.sleep((2 ^ i) + stats::runif(n = 1, min = 0, max = 1)) - resp <- self$Execute(url, method, query_params, header_params, body, stream_callback = stream_callback, ...) - status_code <- httr::status_code(resp) + resp <- self$Execute(url, method, query_params, header_params, + form_params, file_params, accepts, content_types, + body, stream_callback = stream_callback, ...) } else { break } @@ -163,12 +214,19 @@ ApiClient <- R6::R6Class( #' @param method HTTP method. #' @param query_params The query parameters. #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters for uploading files. + #' @param accepts The list of Accept headers + #' @param content_types The list of Content-Type headers #' @param body The HTTP request body. #' @param stream_callback Callback function to process data stream #' @param ... Other optional arguments. #' @return HTTP response #' @export - Execute = function(url, method, query_params, header_params, body, stream_callback = NULL, ...) { + Execute = function(url, method, query_params, header_params, + form_params, file_params, + accepts, content_types, + body, stream_callback = NULL, ...) { headers <- httr::add_headers(c(header_params, self$default_headers)) {{! Adding timeout that can be set at the apiClient object level}} @@ -177,87 +235,109 @@ ApiClient <- R6::R6Class( http_timeout <- httr::timeout(self$timeout) } - if (method == "GET") { - if (typeof(stream_callback) == "closure") { + # set HTTP accept header + accept = self$select_header(accepts) + if (!is.null(accept)) { + headers['Accept'] = accept + } + + # set HTTP content-type header + content_type = self$select_header(content_types) + if (!is.null(content_type)) { + headers['Content-Type'] = content_type + } + + if (typeof(stream_callback) == "closure") { # stream data + if (method == "GET") { httr::GET(url, query = query_params, headers, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::GET(url, query = query_params, headers, http_timeout, - httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "POST") { - if (typeof(stream_callback) == "closure") { + } else if (method == "POST") { httr::POST(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::POST(url, query = query_params, headers, body = body, - httr::content_type("application/json"), http_timeout, - httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "PUT") { - if (typeof(stream_callback) == "closure") { + } else if (method == "PUT") { httr::PUT(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::PUT(url, query = query_params, headers, body = body, - httr::content_type("application/json"), http_timeout, - http_timeout, httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "PATCH") { - if (typeof(stream_callback) == "closure") { + } else if (method == "PATCH") { httr::PATCH(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::PATCH(url, query = query_params, headers, body = body, - httr::content_type("application/json"), http_timeout, - http_timeout, httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "HEAD") { - if (typeof(stream_callback) == "closure") { + } else if (method == "HEAD") { httr::HEAD(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::HEAD(url, query = query_params, headers, http_timeout, - http_timeout, httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "DELETE") { - if (typeof(stream_callback) == "closure") { + } else if (method == "DELETE") { httr::DELETE(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) } else { - httr::DELETE(url, query = query_params, headers, http_timeout, - http_timeout, httr::user_agent(self$`user_agent`), ...) + err_msg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`." + {{#useDefaultExceptionHandling}} + stop(err_msg) + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = err_msg, + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, reason = err_msg)) + {{/useRlangExceptionHandling}} } - } else { - err_msg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`." - {{#useDefaultExceptionHandling}} - stop(err_msg) - {{/useDefaultExceptionHandling}} - {{#useRlangExceptionHandling}} - rlang::abort(message = err_msg, - .subclass = "ApiException", - ApiException = ApiException$new(status = 0, reason = err_msg)) - {{/useRlangExceptionHandling}} + } else { # no streaming + if (method == "GET") { + httr_response <- httr::GET(url, query = query_params, headers, http_timeout, + httr::user_agent(self$`user_agent`), ...) + } else if (method == "POST") { + httr_response <- httr::POST(url, query = query_params, headers, body = body, + httr::content_type("application/json"), http_timeout, + httr::user_agent(self$`user_agent`), ...) + } else if (method == "PUT") { + httr_response <- httr::PUT(url, query = query_params, headers, body = body, + httr::content_type("application/json"), http_timeout, + http_timeout, httr::user_agent(self$`user_agent`), ...) + } else if (method == "PATCH") { + httr_response <- httr::PATCH(url, query = query_params, headers, body = body, + httr::content_type("application/json"), http_timeout, + http_timeout, httr::user_agent(self$`user_agent`), ...) + } else if (method == "HEAD") { + httr_response <- httr::HEAD(url, query = query_params, headers, http_timeout, + http_timeout, httr::user_agent(self$`user_agent`), ...) + } else if (method == "DELETE") { + httr_response <- httr::DELETE(url, query = query_params, headers, http_timeout, + http_timeout, httr::user_agent(self$`user_agent`), ...) + } else { + err_msg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`." + {{#useDefaultExceptionHandling}} + stop(err_msg) + {{/useDefaultExceptionHandling}} + {{#useRlangExceptionHandling}} + rlang::abort(message = err_msg, + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, reason = err_msg)) + {{/useRlangExceptionHandling}} + } + + # return ApiResponse + api_response <- ApiResponse$new() + api_response$status_code <- httr::status_code(httr_response) + api_response$status_code_desc <- httr::http_status(httr_response)$reason + api_response$response <- httr::content(httr_response, "text", encoding = "UTF-8") + api_response$headers <- httr::headers(httr_response) + + api_response } }, - #' Deserialize the content of api response to the given type. + #' Deserialize the content of API response to the given type. #' #' @description - #' Deserialize the content of api response to the given type. + #' Deserialize the content of API response to the given type. #' - #' @param resp Response object. + #' @param raw_response Raw response. #' @param return_type R return type. #' @param pkg_env Package environment. #' @return Deserialized object. #' @export - deserialize = function(resp, return_type, pkg_env) { - resp_obj <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8")) + deserialize = function(raw_response, return_type, pkg_env) { + resp_obj <- jsonlite::fromJSON(raw_response) self$deserializeObj(resp_obj, return_type, pkg_env) }, - #' Deserialize the response from jsonlite object based on the given type #' #' @description @@ -308,6 +388,20 @@ ApiClient <- R6::R6Class( # To handle model objects which are not array or map containers. Ex:"Pet" return_type <- get(return_type, envir = as.environment(pkg_env)) return_obj <- return_type$new() + # check if discriminator is defined + if (!is.null(return_obj$`_discriminator_property_name`)) { + data_type <- return_obj$`_discriminator_property_name` + # use discriminator mapping if provided + if (!is.null(return_obj$`_discriminator_mapping_name`)) { + data_type <- (return_obj$`_discriminator_mapping_name`)[[obj[[data_type]]]] + } else { + # no mapping provided, use the value directly + data_type <- obj[[data_type]] + } + # create an object of the mapped type (e.g. Cat) + return_type <- get(data_type, envir = as.environment(pkg_env)) + return_obj <- return_type$new() + } return_obj$fromJSON( jsonlite::toJSON(obj, digits = NA, auto_unbox = TRUE) ) @@ -316,6 +410,30 @@ ApiClient <- R6::R6Class( return_obj <- obj } return_obj + }, + #' Return a propery header (for accept or content-type). + #' + #' @description + #' Return a propery header (for accept or content-type). If JSON-related MIME is found, + #' return it. Otherwise, return the first one, if any. + #' + #' @param headers A list of headers + #' @return A header (e.g. 'application/json') + #' @export + select_header = function(headers) { + if (length(headers) == 0) { + return(invisible(NULL)) + } else { + for (header in headers) { + if (str_detect(header, "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")) { + # return JSON-related MIME + return(header) + } + } + + # not json mime type, simply return the first one + return(headers[1]) + } } ) ) diff --git a/modules/openapi-generator/src/main/resources/r/api_doc.mustache b/modules/openapi-generator/src/main/resources/r/api_doc.mustache index ea99453e93..f75f21193e 100644 --- a/modules/openapi-generator/src/main/resources/r/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/r/api_doc.mustache @@ -21,28 +21,43 @@ Method | HTTP request | Description ```R library({{{packageName}}}) +{{#summary}} +# {{{.}}} +# +{{/summary}} {{#allParams}} -var_{{{paramName}}} <- {{{vendorExtensions.x-r-example}}} # {{{dataType}}} | {{{description}}} +{{#-first}} +# prepare function argument(s) +{{/-first}} +var_{{{paramName}}} <- {{{vendorExtensions.x-r-example}}} # {{{dataType}}} | {{{description}}}{{^required}} (Optional){{/required}} {{/allParams}} -{{#summary}} -#{{{.}}} -{{/summary}} +{{#generateWrapper}} +api_instance <- {{#lambda.lowercase}}{{{packageName}}}{{/lambda.lowercase}}_api$new() +{{/generateWrapper}} +{{^generateWrapper}} api_instance <- {{{classname}}}$new() +{{/generateWrapper}} {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} +{{#isBasicBasic}} # Configure HTTP basic authorization: {{{name}}} -api_instance$api_client$username <- 'TODO_YOUR_USERNAME'; -api_instance$api_client$password <- 'TODO_YOUR_PASSWORD'; +{{^-first}}# {{/-first}}api_instance$api_client$username <- Sys.getenv("USERNAME") +{{^-first}}# {{/-first}}api_instance$api_client$password <- Sys.getenv("PASSWORD") +{{/isBasicBasic}} +{{#isBasicBearer}} +# Configure HTTP bearer authorization: {{{name}}} +{{^-first}}# {{/-first}}api_instance$api_client$bearer_token <- Sys.getenv("BEARER_TOKEN") +{{/isBasicBearer}} {{/isBasic}} {{#isApiKey}} # Configure API key authorization: {{{name}}} -api_instance$api_client$api_keys['{{{keyParamName}}}'] <- 'TODO_YOUR_API_KEY'; +{{^-first}}# {{/-first}}api_instance$api_client$api_keys["{{{keyParamName}}}"] <- Sys.getenv("API_KEY") {{/isApiKey}} {{#isOAuth}} # Configure OAuth2 access token for authorization: {{{name}}} -api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +{{^-first}}# {{/-first}}api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} @@ -51,28 +66,33 @@ api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; result <- tryCatch( {{#returnType}} # to save the result into a file, simply add the optional `data_file` parameter, e.g. - # api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}data_file = "result.txt"), + # api_instance{{#generateWrapper}}${{#lambda.snakecase}}{{{classname}}}{{/lambda.snakecase}}{{/generateWrapper}}${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}data_file = "result.txt"), {{#vendorExtensions.x-streaming}} # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. - # api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}stream_callback = function(x){ print(length(x)) }), + # api_instance{{#generateWrapper}}${{#lambda.snakecase}}{{{classname}}}{{/lambda.snakecase}}{{/generateWrapper}}${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}stream_callback = function(x){ print(length(x)) }), {{/vendorExtensions.x-streaming}} {{/returnType}} - api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}), + api_instance{{#generateWrapper}}${{#lambda.snakecase}}{{{classname}}}{{/lambda.snakecase}}{{/generateWrapper}}${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - {{#returnType}} + print("Exception occurs when calling `{{{operationId}}}`:") + dput(result$ApiException$toString()) + {{#errorObjectType}} + # error object + dput(result$ApiException$error_object$toJSONString()) + {{/errorObjectType}} +}{{#returnType}} else { # deserialized response object - response.object <- result$content - {{/returnType}} - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } +{{/returnType}} + +{{^returnType}} +# This endpoint doesn't return data +{{/returnType}} {{/useRlangExceptionHandling}} {{/returnExceptionOnFailure}} {{^useRlangExceptionHandling}} @@ -84,7 +104,7 @@ if (!is.null(result$ApiException)) { # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. # api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}{{#allParams}}{{#-first}}, {{/-first}}{{/allParams}}stream_callback = function(x){ print(length(x)) }) {{/vendorExtensions.x-streaming}} -{{#returnType}}result <- {{/returnType}}api_instance${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}) +{{#returnType}}result <- {{/returnType}}api_instance{{#generateWrapper}}${{#lambda.snakecase}}{{{classname}}}{{/lambda.snakecase}}{{/generateWrapper}}${{{operationId}}}({{#requiredParams}}var_{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-first}}{{#requiredParams.0}}, {{/requiredParams.0}}{{/-first}}{{{paramName}}} = var_{{{paramName}}}{{^-last}}, {{/-last}}{{/optionalParams}}) {{#returnType}} dput(result) {{/returnType}} diff --git a/modules/openapi-generator/src/main/resources/r/api_exception.mustache b/modules/openapi-generator/src/main/resources/r/api_exception.mustache index 80c06e3266..64aa6c3d76 100644 --- a/modules/openapi-generator/src/main/resources/r/api_exception.mustache +++ b/modules/openapi-generator/src/main/resources/r/api_exception.mustache @@ -9,7 +9,7 @@ #' @field body Body of the http response #' @field headers Headers of the http response {{#errorObjectType}} -#' @field errorObject error object type +#' @field error_object error object type {{/errorObjectType}} #' @export ApiException <- R6::R6Class( @@ -20,7 +20,7 @@ ApiException <- R6::R6Class( body = NULL, headers = NULL, {{#errorObjectType}} - errorObject = NULL, + error_object = NULL, {{/errorObjectType}} #' Initialize a new ApiException class. #' @@ -34,15 +34,15 @@ ApiException <- R6::R6Class( initialize = function(status = NULL, reason = NULL, http_response = NULL) { if (!is.null(http_response)) { self$status <- http_response$status_code - errorMsg <- toString(content(http_response)) - if (errorMsg == "") { + errorMsg <- http_response$response + if (is.null(errorMsg) || errorMsg == "") { errorMsg <- "Api exception encountered. No details given." } self$body <- errorMsg self$headers <- http_response$headers - self$reason <- httr::http_status(http_response)$reason + self$reason <- http_response$http_status_desc {{#errorObjectType}} - self$errorObject <- {{errorObjectType}}$new()$fromJSONString(content(http_response, "text")) + self$error_object <- {{errorObjectType}}$new()$fromJSONString(http_response$response) {{/errorObjectType}} } else { self$status <- status @@ -50,7 +50,7 @@ ApiException <- R6::R6Class( self$body <- NULL self$headers <- NULL {{#errorObjectType}} - self$errorObject <- NULL + self$error_object <- NULL {{/errorObjectType}} } }, @@ -76,9 +76,9 @@ ApiException <- R6::R6Class( errorMsg <- paste(errorMsg, self$body, "\n") } {{#errorObjectType}} - if (!is.null(self$errorObject)) { + if (!is.null(self$error_object)) { errorMsg <- paste(errorMsg, "Error object : ", "\n", sep = "") - errorMsg <- paste(errorMsg, self$errorObject$toJSONString(), "\n") + errorMsg <- paste(errorMsg, self$error_object$toJSONString(), "\n") } {{/errorObjectType}} errorMsg diff --git a/modules/openapi-generator/src/main/resources/r/description.mustache b/modules/openapi-generator/src/main/resources/r/description.mustache index 2a16f842bf..01721a459a 100644 --- a/modules/openapi-generator/src/main/resources/r/description.mustache +++ b/modules/openapi-generator/src/main/resources/r/description.mustache @@ -11,5 +11,5 @@ Encoding: UTF-8 License: {{#lambdaLicense}}{{licenseInfo}}{{/lambdaLicense}}{{^licenseInfo}}Unlicense{{/licenseInfo}} LazyData: true Suggests: testthat -Imports: jsonlite, httr, R6, base64enc -RoxygenNote: 7.2.0 +Imports: jsonlite, httr{{#isHttr2}}2{{/isHttr2}}, R6, base64enc, stringr +RoxygenNote: 7.2.1 diff --git a/modules/openapi-generator/src/main/resources/r/libraries/httr2/api_client.mustache b/modules/openapi-generator/src/main/resources/r/libraries/httr2/api_client.mustache new file mode 100644 index 0000000000..fd9ddd884b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/r/libraries/httr2/api_client.mustache @@ -0,0 +1,444 @@ +{{>partial_header}} +#' ApiClient Class +#' +#' Generic API client for OpenAPI client library builds. +#' OpenAPI generic API client. This client handles the client- +#' server communication, and is invariant across implementations. Specifics of +#' the methods and models for each application are generated from the OpenAPI Generator +#' templates. +#' +#' NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +#' Ref: https://openapi-generator.tech +#' Do not edit the class manually. +#' +#' @docType class +#' @title ApiClient +#' @description ApiClient Class +#' @format An \code{R6Class} generator object +#' @field base_path Base url +#' @field user_agent Default user agent +#' @field default_headers Default headers +#' @field username Username for HTTP basic authentication +#' @field password Password for HTTP basic authentication +#' @field api_keys API keys +{{#hasOAuthMethods}} +#' @field access_token Access token +#' @field oauth_client_id OAuth client ID +#' @field oauth_secret OAuth secret +#' @field oauth_refresh_token OAuth refresh token +{{#authMethods}} +{{#isOAuth}} +#' @field oauth_flow_type OAuth flow type +#' @field oauth_authorization_url Authoriziation URL +#' @field oauth_token_url Token URL +#' @field oauth_pkce Boolean flag to enable PKCE +#' @field oauth_scopes OAuth scopes +{{/isOAuth}} +{{/authMethods}} +{{/hasOAuthMethods}} +#' @field bearer_token Bearer token +#' @field timeout Default timeout in seconds +#' @field retry_status_codes vector of status codes to retry +#' @field max_retry_attempts maximum number of retries for the status codes +{{#useRlangExceptionHandling}} +#' @importFrom rlang abort +{{/useRlangExceptionHandling}} +#' @export +ApiClient <- R6::R6Class( + "ApiClient", + public = list( + # base path of all requests + base_path = "{{{basePath}}}", + # user agent in the HTTP request + user_agent = "{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/r{{/httpUserAgent}}", + # default headers in the HTTP request + default_headers = NULL, + # username (HTTP basic authentication) + username = NULL, + # password (HTTP basic authentication) + password = NULL, + # API keys + api_keys = NULL, + {{#hasOAuthMethods}} + # Access token + access_token = NULL, + # OAuth2 client ID + oauth_client_id = NULL, + # OAuth2 secret + oauth_secret = NULL, + # OAuth2 refresh token + oauth_refresh_token = NULL, + # OAuth2 + {{#authMethods}} + {{#isOAuth}} + # Flow type + oauth_flow_type = "{{flow}}", + # Authoriziation URL + oauth_authorization_url = "{{authorizationUrl}}", + # Token URL + oauth_token_url = "{{tokenUrl}}", + # Enable PKCE? + oauth_pkce = TRUE, + # OAuth scopes + oauth_scopes = NULL, + {{/isOAuth}} + {{/authMethods}} + {{/hasOAuthMethods}} + # Bearer token + bearer_token = NULL, + # Time Out (seconds) + timeout = NULL, + # Vector of status codes to retry + retry_status_codes = NULL, + # Maximum number of retry attempts for the retry status codes + max_retry_attempts = NULL, + #' Initialize a new ApiClient. + #' + #' @description + #' Initialize a new ApiClient. + #' + #' @param base_path Base path. + #' @param user_agent User agent. + #' @param default_headers Default headers. + #' @param username User name. + #' @param password Password. + #' @param api_keys API keys. + #' @param access_token Access token. + #' @param bearer_token Bearer token. + #' @param timeout Timeout. + #' @param retry_status_codes Status codes for retry. + #' @param max_retry_attempts Maxmium number of retry. + #' @export + initialize = function(base_path = NULL, user_agent = NULL, + default_headers = NULL, + username = NULL, password = NULL, api_keys = NULL, + access_token = NULL, bearer_token = NULL, timeout = NULL, + retry_status_codes = NULL, max_retry_attempts = NULL) { + if (!is.null(base_path)) { + self$base_path <- base_path + } + + if (!is.null(default_headers)) { + self$default_headers <- default_headers + } + + if (!is.null(username)) { + self$username <- username + } + + if (!is.null(password)) { + self$password <- password + } + + if (!is.null(access_token)) { + self$access_token <- access_token + } + + if (!is.null(bearer_token)) { + self$bearer_token <- bearer_token + } + + if (!is.null(api_keys)) { + self$api_keys <- api_keys + } else { + self$api_keys <- list() + } + + if (!is.null(user_agent)) { + self$`user_agent` <- user_agent + } + + if (!is.null(timeout)) { + self$timeout <- timeout + } + + if (!is.null(retry_status_codes)) { + self$retry_status_codes <- retry_status_codes + } + + if (!is.null(max_retry_attempts)) { + self$max_retry_attempts <- max_retry_attempts + } + }, + #' Prepare to make an API call with the retry logic. + #' + #' @description + #' Prepare to make an API call with the retry logic. + #' + #' @param url URL. + #' @param method HTTP method. + #' @param query_params The query parameters. + #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters to upload files. + #' @param accepts The HTTP accpet headers. + #' @param content_types The HTTP content-type headers. + #' @param body The HTTP request body. + #' @param is_oauth True if the endpoints required OAuth authentication. + #' @param oauth_scopes OAuth scopes. + #' @param stream_callback Callback function to process the data stream. + #' @param ... Other optional arguments. + #' @return HTTP response + #' @export + CallApi = function(url, method, query_params, header_params, form_params, + file_params, accepts, content_types, body, + is_oauth = FALSE, oauth_scopes = NULL, stream_callback = NULL, ...) { + + # set the URL + req <- request(url) + + resp <- self$Execute(req, method, query_params, header_params, form_params, + file_params, accepts, content_types, body, is_oauth = is_oauth, + oauth_scopes = oauth_scopes, stream_callback = stream_callback, ...) + }, + #' Make an API call + #' + #' @description + #' Make an API call + #' + #' @param req httr2 request. + #' @param method HTTP method. + #' @param query_params The query parameters. + #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters for uploading files. + #' @param accepts The HTTP accpet headers. + #' @param content_types The HTTP content-type headers. + #' @param body The HTTP request body. + #' @param is_oauth True if the endpoints required OAuth authentication. + #' @param oauth_scopes OAuth scopes. + #' @param stream_callback Callback function to process data stream. + #' @param ... Other optional arguments. + #' @return HTTP response + #' @export + Execute = function(req, method, query_params, header_params, form_params, + file_params, accepts, content_types, body, + is_oauth = FALSE, oauth_scopes = NULL, stream_callback = NULL, ...) { + + ## add headers + req <- req %>% req_headers(!!!header_params) + + ## add default headers + req <- req %>% req_headers(!!!self$default_headers) + + # set HTTP accept header + accept <- self$select_header(accepts) + if (!is.null(accept)) { + req <- req %>% req_headers("Accept" = accept) + } + + # set HTTP content-type header + content_type <- self$select_header(content_types) + if (!is.null(content_type)) { + req <- req %>% req_headers("Content-Type" = content_type) + } + + ## add query parameters + for (query_param in names(query_params)) { + if (typeof(query_params[[query_param]]) == "list") { + # for explode, e.g. a=1,a=2,a=3 + req <- req %>% req_url_query(!!!query_params[[query_param]]) + } else { # for non-explode, e.g. a=1,2,3 + tmp <- list() + tmp[[query_param]] <- query_params[[query_param]] + req <- req %>% req_url_query(!!!tmp) + } + } + + # has file upload? + if (!is.null(file_params) && length(file_params) != 0) { + req <- req %>% req_body_multipart(!!!file_params) + + # add form parameters via req_body_multipart + if (!is.null(form_params) && length(form_params) != 0) { + req <- req %>% req_body_multipart(!!!form_params) + } + } else { # no file upload + # add form parameters via req_body_form + if (!is.null(form_params) && length(form_params) != 0) { + req <- req %>% req_body_form(!!!form_params) + } + } + + # add body parameters + if (!is.null(body)) { + req <- req %>% req_body_raw(body) + } + + # set timeout + {{! Adding timeout that can be set at the apiClient object level}} + if (!is.null(self$timeout)) { + req <- req %>% req_timeout(self$timeout) + } + + # set retry + if (!is.null(self$max_retry_attempts)) { + req <- req %>% retry_max_tries(self$timeout) + req <- req %>% retry_max_seconds(self$timeout) + } + + # set user agent + if (!is.null(self$user_agent)) { + req <- req %>% req_user_agent(self$user_agent) + } + + # set HTTP verb + req <- req %>% req_method(method) + + {{#hasOAuthMethods}} + # use oauth authentication if the endpoint requires it + if (is_oauth && !is.null(self$oauth_client_id) && !is.null(self$oauth_secret)) { + client <- oauth_client( + id = self$oauth_client_id, + secret = obfuscated(self$oauth_secret), + token_url = self$oauth_token_url, + name = "{{packageName}}-oauth" + ) + + req_oauth_scopes <- NULL + if (!is.null(self$oauth_scopes)) { + # use oauth scopes provided by the user + req_oauth_scopes <- self$oauth_scopes + } else { + # use oauth scopes defined in openapi spec + req_oauth_scopes <- oauth_scopes + } + + req <- req %>% req_oauth_auth_code(client, scope = req_oauth_scopes, + pkce = self$oauth_pkce, + auth_url = self$oauth_authoriziation_url) + } + + {{/hasOAuthMethods}} + # stream data + if (typeof(stream_callback) == "closure") { + req %>% req_stream(stream_callback) + } else { + # perform the HTTP request + resp <- req %>% + req_error(is_error = function(resp) FALSE) %>% + req_perform() + + # return ApiResponse + api_response <- ApiResponse$new() + api_response$status_code <- resp %>% resp_status() + api_response$status_code_desc <- resp %>% resp_status_desc() + api_response$response <- resp %>% resp_body_string() + api_response$headers <- resp %>% resp_headers() + + api_response + } + }, + #' Deserialize the content of API response to the given type. + #' + #' @description + #' Deserialize the content of API response to the given type. + #' + #' @param raw_response Raw response. + #' @param return_type R return type. + #' @param pkg_env Package environment. + #' @return Deserialized object. + #' @export + deserialize = function(raw_response, return_type, pkg_env) { + resp_obj <- jsonlite::fromJSON(raw_response) + self$deserializeObj(resp_obj, return_type, pkg_env) + }, + #' Deserialize the response from jsonlite object based on the given type. + #' + #' @description + #' Deserialize the response from jsonlite object based on the given type. + #' by handling complex and nested types by iterating recursively + #' Example return_types will be like "array[integer]", "map(Pet)", "array[map(Tag)]", etc. + #' + #' @param obj Response object. + #' @param return_type R return type. + #' @param pkg_env Package environment. + #' @return Deserialized object. + #' @export + deserializeObj = function(obj, return_type, pkg_env) { + return_obj <- NULL + primitive_types <- c("character", "numeric", "integer", "logical", "complex") + + # To handle the "map" type + if (startsWith(return_type, "map(")) { + inner_return_type <- regmatches(return_type, + regexec(pattern = "map\\((.*)\\)", return_type))[[1]][2] + return_obj <- lapply(names(obj), function(name) { + self$deserializeObj(obj[[name]], inner_return_type, pkg_env) + }) + names(return_obj) <- names(obj) + } else if (startsWith(return_type, "array[")) { + # To handle the "array" type + inner_return_type <- regmatches(return_type, + regexec(pattern = "array\\[(.*)\\]", return_type))[[1]][2] + if (c(inner_return_type) %in% primitive_types) { + return_obj <- vector("list", length = length(obj)) + if (length(obj) > 0) { + for (row in 1:length(obj)) { + return_obj[[row]] <- self$deserializeObj(obj[row], inner_return_type, pkg_env) + } + } + } else { + if (!is.null(nrow(obj))) { + return_obj <- vector("list", length = nrow(obj)) + if (nrow(obj) > 0) { + for (row in 1:nrow(obj)) { + return_obj[[row]] <- self$deserializeObj(obj[row, , drop = FALSE], + inner_return_type, pkg_env) + } + } + } + } + } else if (exists(return_type, pkg_env) && !(c(return_type) %in% primitive_types)) { + # To handle model objects which are not array or map containers (e.g. Pet) + return_type <- get(return_type, envir = as.environment(pkg_env)) + return_obj <- return_type$new() + # check if discriminator is defined + if (!is.null(return_obj$`_discriminator_property_name`)) { + data_type <- return_obj$`_discriminator_property_name` + # use discriminator mapping if provided + if (!is.null(return_obj$`_discriminator_mapping_name`)) { + data_type <- (return_obj$`_discriminator_mapping_name`)[[obj[[data_type]]]] + } else { + # no mapping provided, use the value directly + data_type <- obj[[data_type]] + } + # create an object of the mapped type (e.g. Cat) + return_type <- get(data_type, envir = as.environment(pkg_env)) + return_obj <- return_type$new() + } + return_obj$fromJSON( + jsonlite::toJSON(obj, digits = NA, auto_unbox = TRUE) + ) + } else { + # To handle primitive type + return_obj <- obj + } + return_obj + }, + #' Return a propery header (for accept or content-type). + #' + #' @description + #' Return a propery header (for accept or content-type). If JSON-related MIME is found, + #' return it. Otherwise, return the first one, if any. + #' + #' @param headers A list of headers + #' @return A header (e.g. 'application/json') + #' @export + select_header = function(headers) { + if (length(headers) == 0) { + return(invisible(NULL)) + } else { + for (header in headers) { + if (str_detect(header, "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")) { + # return JSON-related MIME + return(header) + } + } + + # not json mime type, simply return the first one + return(headers[1]) + } + } + ) +) diff --git a/modules/openapi-generator/src/main/resources/r/libraries/httr2/api_wrapper.mustache b/modules/openapi-generator/src/main/resources/r/libraries/httr2/api_wrapper.mustache new file mode 100644 index 0000000000..e0786e017b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/r/libraries/httr2/api_wrapper.mustache @@ -0,0 +1,73 @@ +{{>partial_header}} +#' {{{packageName}}} API Class +#' +#' A single point of access to the {{{packageName}}} API. +#' +#' NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +#' Ref: https://openapi-generator.tech +#' Do not edit the class manually. +#' +#' @docType class +#' @title ApiClient +#' @description ApiClient Class +#' @format An \code{R6Class} generator object +#' @field api_client API client +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#-first}} +#' @field {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}} an instance of {{classname}} +{{/-first}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +{{#useRlangExceptionHandling}} +#' @importFrom rlang abort +{{/useRlangExceptionHandling}} +#' @export +{{#lambda.lowercase}}{{{packageName}}}{{/lambda.lowercase}}_api <- R6::R6Class( + "{{#lambda.lowercase}}{{{packageName}}}{{/lambda.lowercase}}_api", + public = list( + api_client = NULL, + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#-first}} + {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}} = NULL, + {{/-first}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + #' Initialize a new {{{packageName}}} API Class. + #' + #' @description + #' Initialize a new {{{packageName}}} API Class. + #' + #' @param api_client An instance of API client (optional). + #' @export + initialize = function(api_client) { + if (missing(api_client)) { + self$api_client <- ApiClient$new() + } else { + self$api_client <- api_client + } + + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#-first}} + self${{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}} <- {{{classname}}}$new(self$api_client) + + {{/-first}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + } + ) +) diff --git a/modules/openapi-generator/src/main/resources/r/model.mustache b/modules/openapi-generator/src/main/resources/r/model.mustache index a91c6054c9..b34c50b515 100644 --- a/modules/openapi-generator/src/main/resources/r/model.mustache +++ b/modules/openapi-generator/src/main/resources/r/model.mustache @@ -1,4 +1,3 @@ -{{>partial_header}} {{#models}} {{#model}} {{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} diff --git a/modules/openapi-generator/src/main/resources/r/modelAnyOf.mustache b/modules/openapi-generator/src/main/resources/r/modelAnyOf.mustache index b4c6e8b240..ba288abfab 100644 --- a/modules/openapi-generator/src/main/resources/r/modelAnyOf.mustache +++ b/modules/openapi-generator/src/main/resources/r/modelAnyOf.mustache @@ -39,6 +39,18 @@ #' #' @description #' Deserialize JSON string into an instance of {{{classname}}}. + #' An alias to the method `fromJSON`. + #' + #' @param input The input JSON. + #' @return An instance of {{{classname}}}. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of {{{classname}}}. + #' + #' @description + #' Deserialize JSON string into an instance of {{{classname}}}. #' #' @param input The input JSON. #' @return An instance of {{{classname}}}. @@ -46,22 +58,32 @@ fromJSON = function(input) { error_messages <- list() - {{#anyOf}} - {{{.}}}_result <- tryCatch({ - {{{.}}}$public_methods$validateJSON(input) - {{{.}}}_instance <- {{{.}}}$new() - self$actual_instance <- {{{.}}}_instance$fromJSON(input) - self$actual_type <- "{{{.}}}" + {{#composedSchemas.anyOf}} + {{^isNull}} + {{{dataType}}}_result <- tryCatch({ + {{#isPrimitiveType}} + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "{{{dataType}}}") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "{{{dataType}}}", typeof(instance))) + } + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{{dataType}}}$public_methods$validateJSON(input) + {{{dataType}}}_instance <- {{{dataType}}}$new() + {{/isPrimitiveType}} + self$actual_instance <- {{{dataType}}}_instance$fromJSON(input) + self$actual_type <- "{{{dataType}}}" return(self) }, error = function(err) err ) - if (!is.null({{{.}}}_result["error"])) { - error_messages <- append(error_messages, {{{.}}}_result["message"]) + if (!is.null({{{dataType}}}_result["error"])) { + error_messages <- append(error_messages, {{{dataType}}}_result["message"]) } - {{/anyOf}} + {{/isNull}} + {{/composedSchemas.anyOf}} # no match stop(paste("No match found when deserializing the payload into {{{classname}}} with anyOf schemas {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: ", paste(error_messages, collapse = ", "))) @@ -129,6 +151,28 @@ ) jsoncontent <- paste(jsoncontent, collapse = ",") as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +#{{classname}}$unlock() +# +## Below is an example to define the print fnuction +#{{classname}}$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#{{classname}}$lock() diff --git a/modules/openapi-generator/src/main/resources/r/modelEnum.mustache b/modules/openapi-generator/src/main/resources/r/modelEnum.mustache index c648c0365f..8471a94cad 100644 --- a/modules/openapi-generator/src/main/resources/r/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/r/modelEnum.mustache @@ -1,48 +1,89 @@ +#' @docType class +#' @title {{classname}} +#' @description {{classname}} Class +#' @format An \code{R6Class} generator object +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON #' @export {{#allowableValues}} {{classname}} <- R6::R6Class( - "{{classname}}", - public = list( - initialize = function(...) { - local.optional.var <- list(...) - val <- unlist(local.optional.var) - enumvec <- .parse_{{name}}() + "{{classname}}", + public = list( + #' Initialize a new {{{classname}}} class. + #' + #' @description + #' Initialize a new {{{classname}}} class. + #' + #' @param ... Optional arguments. + #' @export + initialize = function(...) { + local.optional.var <- list(...) + val <- unlist(local.optional.var) + enumvec <- .parse_{{name}}() - stopifnot(length(val) == 1L) + stopifnot(length(val) == 1L) - if (!val %in% enumvec) - stop("Use one of the valid values: ", - paste0(enumvec, collapse = ", ")) - private$value <- val - }, - toJSON = function() { - jsonlite::toJSON(private$value, auto_unbox = TRUE) - }, - fromJSON = function({{classname}}Json) { - private$value <- jsonlite::fromJSON({{classname}}Json, - simplifyVector = FALSE) - self - }, - toJSONString = function() { - as.character(jsonlite::toJSON(private$value, - auto_unbox = TRUE)) - }, - fromJSONString = function({{classname}}Json) { - private$value <- jsonlite::fromJSON({{classname}}Json, - simplifyVector = FALSE) - self - } - ), - private = list( - value = NULL - ) + if (!val %in% enumvec) + stop("Use one of the valid values: ", + paste0(enumvec, collapse = ", ")) + private$value <- val + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return {{{classname}}} in JSON format + #' @export + toJSON = function() { + jsonlite::toJSON(private$value, auto_unbox = TRUE) + }, + #' Deserialize JSON string into an instance of {{{classname}}} + #' + #' @description + #' Deserialize JSON string into an instance of {{{classname}}} + #' + #' @param input_json the JSON input + #' @return the instance of {{{classname}}} + #' @export + fromJSON = function(input_json) { + private$value <- jsonlite::fromJSON(input_json, + simplifyVector = FALSE) + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return {{{classname}}} in JSON format + #' @export + toJSONString = function() { + as.character(jsonlite::toJSON(private$value, + auto_unbox = TRUE)) + }, + #' Deserialize JSON string into an instance of {{{classname}}} + #' + #' @description + #' Deserialize JSON string into an instance of {{{classname}}} + #' + #' @param input_json the JSON input + #' @return the instance of {{{classname}}} + #' @export + fromJSONString = function(input_json) { + private$value <- jsonlite::fromJSON(input_json, + simplifyVector = FALSE) + self + } + ), + private = list( + value = NULL + ) ) # add to utils.R .parse_{{name}} <- function(vals) { - res <- gsub("^\\[|\\]$", "", - "{{{values}}}" - ) - unlist(strsplit(res, ", ")) + res <- gsub("^\\[|\\]$", "", "{{{values}}}") + unlist(strsplit(res, ", ")) } {{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/r/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/r/modelGeneric.mustache index 0ecc59818b..d67e502b01 100644 --- a/modules/openapi-generator/src/main/resources/r/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/r/modelGeneric.mustache @@ -1,18 +1,21 @@ -{{#models}} -{{#model}} +#' Create a new {{{classname}}} +#' +#' @description +#' {{{description}}}{{^description}}{{classname}} Class{{/description}} +#' #' @docType class #' @title {{classname}} #' @description {{classname}} Class #' @format An \code{R6Class} generator object {{#vars}} -#' @field {{name}} {{title}} {{#isContainer}}{{#isArray}}list( {{/isArray}}{{#isMap}}named list( {{/isMap}}{{/isContainer}}{{^isPrimitiveType}}\link{{=<% %>=}}{<%/isPrimitiveType%><%={{ }}=%>{{#isContainer}}{{#items}}{{dataType}}{{/items}}{{/isContainer}}{{^isContainer}}{{dataType}}{{/isContainer}}{{=<% %>=}}<%^isPrimitiveType%>}<%={{ }}=%>{{/isPrimitiveType}}{{#isContainer}}{{#isArray}} ){{/isArray}}{{#isMap}} ){{/isMap}}{{/isContainer}}{{^required}} [optional]{{/required}} +#' @field {{name}} {{#lambdaRdocEscape}}{{{description}}}{{/lambdaRdocEscape}} {{{vendorExtensions.x-r-doc-type}}}{{^required}} [optional]{{/required}} {{/vars}} +{{#isAdditionalPropertiesTrue}} +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +{{/isAdditionalPropertiesTrue}} #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON -{{#isEnum}} -{{>modelEnum}} -{{/isEnum}} -{{^isEnum}} #' @export {{classname}} <- R6::R6Class( "{{classname}}", @@ -23,33 +26,47 @@ {{#vars}} `{{{name}}}` = NULL, {{/vars}} + {{#isAdditionalPropertiesTrue}} + `_field_list` = c({{#vars}}"{{{name}}}"{{^-last}}, {{/-last}}{{/vars}}), + `additional_properties` = list(), + {{/isAdditionalPropertiesTrue}} + {{#discriminator}} + `_discriminator_property_name` = '{{discriminator.propertyName}}', + {{#discriminator.mappedModels}}{{#-first}}`_discriminator_mapping_name` = c({{/-first}}'{{mappingName}}' = '{{modelName}}'{{^-last}}, {{/-last}}{{#-last}}),{{/-last}}{{/discriminator.mappedModels}} + {{/discriminator}} #' Initialize a new {{{classname}}} class. #' #' @description #' Initialize a new {{{classname}}} class. #' {{#requiredVars}} - #' @param {{name}} {{{description}}}{{^description}}{{{name}}}{{/description}} + #' @param {{name}} {{#lambdaRdocEscape}}{{{description}}}{{/lambdaRdocEscape}}{{^description}}{{{name}}}{{/description}} {{/requiredVars}} {{#optionalVars}} - #' @param {{name}} {{{description}}}{{^description}}{{{name}}}{{/description}}{{#defaultValue}}. Default to {{{.}}}.{{/defaultValue}} + #' @param {{name}} {{#lambdaRdocEscape}}{{{description}}}{{/lambdaRdocEscape}}{{^description}}{{{name}}}{{/description}}{{#defaultValue}}. Default to {{{.}}}.{{/defaultValue}} {{/optionalVars}} + {{#isAdditionalPropertiesTrue}} + #' @param additional_properties additonal properties (optional) + {{/isAdditionalPropertiesTrue}} #' @param ... Other optional arguments. #' @export - initialize = function( - {{#requiredVars}}`{{name}}`, {{/requiredVars}}{{#optionalVars}}`{{name}}` = {{{defaultValue}}}{{^defaultValue}}NULL{{/defaultValue}}, {{/optionalVars}}... - ) { + initialize = function({{#requiredVars}}`{{name}}`, {{/requiredVars}}{{#optionalVars}}`{{name}}` = {{{defaultValue}}}{{^defaultValue}}NULL{{/defaultValue}}, {{/optionalVars}}{{#isAdditionalPropertiesTrue}}additional_properties = NULL, {{/isAdditionalPropertiesTrue}}...) { {{#requiredVars}} if (!missing(`{{name}}`)) { {{^isContainer}} + {{#isEnum}} + if (!(`{{name}}` %in% c({{#_enum}}"{{{.}}}"{{^-last}}, {{/-last}}{{/_enum}}))) { + stop(paste("Error! \"", `{{name}}`, "\" cannot be assigned to `{{name}}`. Must be {{#_enum}}\"{{{.}}}\"{{^-last}}, {{/-last}}{{/_enum}}.", sep = "")) + } + {{/isEnum}} {{#isInteger}} stopifnot(is.numeric(`{{name}}`), length(`{{name}}`) == 1) {{/isInteger}} {{#isLong}} - stopifnot(is.numeric(`{{name}}`), length(`{{nme}}`) == 1) + stopifnot(is.numeric(`{{name}}`), length(`{{name}}`) == 1) {{/isLong}} {{#isFloat}} - stopifnot(is.numeric(`{{nme}}`), length(`{{nme}}`) == 1) + stopifnot(is.numeric(`{{name}}`), length(`{{name}}`) == 1) {{/isFloat}} {{#isDouble}} stopifnot(is.numeric(`{{name}}`), length(`{{name}}`) == 1) @@ -66,19 +83,26 @@ {{#isDateTime}} stopifnot(is.character(`{{name}}`), length(`{{name}}`) == 1) {{/isDateTime}} + {{#isUri}} + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(`{{name}}`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", `{{name}}`)) + } + {{/isUri}} {{^isPrimitiveType}} stopifnot(R6::is.R6(`{{name}}`)) {{/isPrimitiveType}} {{/isContainer}} {{#isContainer}} - {{#isPrimitiveType}} stopifnot(is.vector(`{{name}}`), length(`{{name}}`) != 0) - sapply(`{{name}}`, function(x) stopifnot(is.character(x))) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - stopifnot(is.vector(`{{name}}`), length(`{{name}}`) != 0) - sapply(`{{name}}`, function(x) stopifnot(R6::is.R6(x))) - {{/isPrimitiveType}} + sapply(`{{name}}`, function(x) stopifnot({{#isPrimitiveType}}is.character(x){{/isPrimitiveType}}{{^isPrimitiveType}}R6::is.R6(x){{/isPrimitiveType}})) + {{#isArray}} + {{#uniqueItems}} + if (!identical(`{{name}}`, unique(`{{name}}`))) { + stop("Error! Items in `{{name}}` are not unique.") + } + {{/uniqueItems}} + {{/isArray}} {{/isContainer}} self$`{{name}}` <- `{{name}}` } @@ -86,6 +110,11 @@ {{#optionalVars}} if (!is.null(`{{name}}`)) { {{^isContainer}} + {{#isEnum}} + if (!(`{{name}}` %in% c({{#_enum}}"{{{.}}}"{{^-last}}, {{/-last}}{{/_enum}}))) { + stop(paste("Error! \"", `{{name}}`, "\" cannot be assigned to `{{name}}`. Must be {{#_enum}}\"{{{.}}}\"{{^-last}}, {{/-last}}{{/_enum}}.", sep = "")) + } + {{/isEnum}} {{#isInteger}} stopifnot(is.numeric(`{{name}}`), length(`{{name}}`) == 1) {{/isInteger}} @@ -110,23 +139,37 @@ {{#isDateTime}} stopifnot(is.character(`{{name}}`), length(`{{name}}`) == 1) {{/isDateTime}} + {{#isUri}} + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(`{{name}}`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", `{{name}}`)) + } + {{/isUri}} {{^isPrimitiveType}} stopifnot(R6::is.R6(`{{name}}`)) {{/isPrimitiveType}} {{/isContainer}} {{#isContainer}} - {{#isPrimitiveType}} stopifnot(is.vector(`{{name}}`), length(`{{name}}`) != 0) - sapply(`{{name}}`, function(x) stopifnot(is.character(x))) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - stopifnot(is.vector(`{{name}}`), length(`{{name}}`) != 0) - sapply(`{{name}}`, function(x) stopifnot(R6::is.R6(x))) - {{/isPrimitiveType}} + sapply(`{{name}}`, function(x) stopifnot({{#isPrimitiveType}}is.character(x){{/isPrimitiveType}}{{^isPrimitiveType}}R6::is.R6(x){{/isPrimitiveType}})) + {{#isArray}} + {{#uniqueItems}} + if (!identical(`{{name}}`, unique(`{{name}}`))) { + stop("Error! Items in `{{name}}` are not unique.") + } + {{/uniqueItems}} + {{/isArray}} {{/isContainer}} self$`{{name}}` <- `{{name}}` } {{/optionalVars}} + {{#isAdditionalPropertiesTrue}} + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + {{/isAdditionalPropertiesTrue}} }, #' To JSON string #' @@ -140,35 +183,40 @@ {{#vars}} if (!is.null(self$`{{name}}`)) { {{classname}}Object[["{{baseName}}"]] <- - {{#isContainer}} - {{#isArray}} - {{#isPrimitiveType}} + {{#isContainer}} + {{#isArray}} + {{#isPrimitiveType}} self$`{{name}}` - {{/isPrimitiveType}} - {{^isPrimitiveType}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} lapply(self$`{{name}}`, function(x) x$toJSON()) - {{/isPrimitiveType}} - {{/isArray}} - {{#isMap}} - {{#isPrimitiveType}} + {{/isPrimitiveType}} + {{/isArray}} + {{#isMap}} + {{#isPrimitiveType}} self$`{{name}}` - {{/isPrimitiveType}} - {{^isPrimitiveType}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} lapply(self$`{{name}}`, function(x) x$toJSON()) - {{/isPrimitiveType}} - {{/isMap}} - {{/isContainer}} - {{^isContainer}} - {{#isPrimitiveType}} + {{/isPrimitiveType}} + {{/isMap}} + {{/isContainer}} + {{^isContainer}} + {{#isPrimitiveType}} self$`{{name}}` - {{/isPrimitiveType}} - {{^isPrimitiveType}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} self$`{{name}}`$toJSON() - {{/isPrimitiveType}} - {{/isContainer}} + {{/isPrimitiveType}} + {{/isContainer}} } {{/vars}} + {{#isAdditionalPropertiesTrue}} + for (key in names(self$additional_properties)) { + {{classname}}Object[[key]] <- self$additional_properties[[key]] + } + {{/isAdditionalPropertiesTrue}} {{classname}}Object }, #' Deserialize JSON string into an instance of {{{classname}}} @@ -185,9 +233,27 @@ if (!is.null(this_object$`{{baseName}}`)) { {{#isContainer}} self$`{{name}}` <- ApiClient$new()$deserializeObj(this_object$`{{baseName}}`, "{{dataType}}", loadNamespace("{{packageName}}")) + {{#isArray}} + {{#uniqueItems}} + if (!identical(self$`{{name}}`, unique(self$`{{name}}`))) { + stop("Error! Items in `{{name}}` are not unique.") + } + {{/uniqueItems}} + {{/isArray}} {{/isContainer}} {{^isContainer}} {{#isPrimitiveType}} + {{#isEnum}} + if (!is.null(this_object$`{{baseName}}`) && !(this_object$`{{baseName}}` %in% c({{#_enum}}"{{{.}}}"{{^-last}}, {{/-last}}{{/_enum}}))) { + stop(paste("Error! \"", this_object$`{{baseName}}`, "\" cannot be assigned to `{{baseName}}`. Must be {{#_enum}}\"{{{.}}}\"{{^-last}}, {{/-last}}{{/_enum}}.", sep = "")) + } + {{/isEnum}} + {{#isUri}} + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(this_object$`{{baseName}}`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", this_object$`{{baseName}}`)) + } + {{/isUri}} self$`{{name}}` <- this_object$`{{baseName}}` {{/isPrimitiveType}} {{^isPrimitiveType}} @@ -198,6 +264,15 @@ {{/isContainer}} } {{/vars}} + {{#isAdditionalPropertiesTrue}} + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + {{/isAdditionalPropertiesTrue}} self }, #' To JSON string @@ -239,18 +314,18 @@ {{#isContainer}} {{#isArray}} {{#isPrimitiveType}} - paste(unlist(lapply(self$`{{{name}}}`, function(x) paste0('"', x, '"'))), collapse=",") + paste(unlist(lapply(self$`{{{name}}}`, function(x) paste0('"', x, '"'))), collapse = ",") {{/isPrimitiveType}} {{^isPrimitiveType}} - paste(sapply(self$`{{{name}}}`, function(x) jsonlite::toJSON(x$toJSON(), auto_unbox=TRUE, digits = NA)), collapse=",") + paste(sapply(self$`{{{name}}}`, function(x) jsonlite::toJSON(x$toJSON(), auto_unbox = TRUE, digits = NA)), collapse = ",") {{/isPrimitiveType}} {{/isArray}} {{#isMap}} {{#isPrimitiveType}} - jsonlite::toJSON(lapply(self$`{{{name}}}`, function(x){ x }), auto_unbox = TRUE, digits=NA) + jsonlite::toJSON(lapply(self$`{{{name}}}`, function(x){ x }), auto_unbox = TRUE, digits = NA) {{/isPrimitiveType}} {{^isPrimitiveType}} - jsonlite::toJSON(lapply(self$`{{{name}}}`, function(x){ x$toJSON() }), auto_unbox = TRUE, digits=NA) + jsonlite::toJSON(lapply(self$`{{{name}}}`, function(x){ x$toJSON() }), auto_unbox = TRUE, digits = NA) {{/isPrimitiveType}} {{/isMap}} {{/isContainer}} @@ -259,7 +334,7 @@ {{#isBoolean}}tolower({{/isBoolean}}self$`{{name}}`{{#isBoolean}}){{/isBoolean}} {{/isPrimitiveType}} {{^isPrimitiveType}} - jsonlite::toJSON(self$`{{name}}`$toJSON(), auto_unbox=TRUE, digits = NA) + jsonlite::toJSON(self$`{{name}}`$toJSON(), auto_unbox = TRUE, digits = NA) {{/isPrimitiveType}} {{/isContainer}} ) @@ -267,7 +342,14 @@ {{/vars}} ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + {{#isAdditionalPropertiesTrue}} + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + {{/isAdditionalPropertiesTrue}} }, #' Deserialize JSON string into an instance of {{{classname}}} #' @@ -283,9 +365,27 @@ {{! AAPI - added condition for handling container type of parameters, map and array}} {{#isContainer}} self$`{{name}}` <- ApiClient$new()$deserializeObj(this_object$`{{name}}`, "{{dataType}}", loadNamespace("{{packageName}}")) + {{#isArray}} + {{#uniqueItems}} + if (!identical(self$`{{name}}`, unique(self$`{{name}}`))) { + stop("Error! Items in `{{name}}` are not unique.") + } + {{/uniqueItems}} + {{/isArray}} {{/isContainer}} {{^isContainer}} {{#isPrimitiveType}} + {{#isEnum}} + if (!is.null(this_object$`{{baseName}}`) && !(this_object$`{{baseName}}` %in% c({{#_enum}}"{{{.}}}"{{^-last}}, {{/-last}}{{/_enum}}))) { + stop(paste("Error! \"", this_object$`{{baseName}}`, "\" cannot be assigned to `{{baseName}}`. Must be {{#_enum}}\"{{{.}}}\"{{^-last}}, {{/-last}}{{/_enum}}.", sep = "")) + } + {{/isEnum}} + {{#isUri}} + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(this_object$`{{name}}`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", this_object$`{{name}}`)) + } + {{/isUri}} self$`{{name}}` <- this_object$`{{name}}` {{/isPrimitiveType}} {{^isPrimitiveType}} @@ -293,6 +393,15 @@ {{/isPrimitiveType}} {{/isContainer}} {{/vars}} + {{#isAdditionalPropertiesTrue}} + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + {{/isAdditionalPropertiesTrue}} self }, #' Validate JSON input with respect to {{classname}} @@ -332,19 +441,26 @@ {{#isDateTime}} stopifnot(is.character(input_json$`{{name}}`), length(input_json$`{{name}}`) == 1) {{/isDateTime}} + {{#isUri}} + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(input_json$`{{name}}`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", input_json$`{{name}}`)) + } + {{/isUri}} {{^isPrimitiveType}} stopifnot(R6::is.R6(input_json$`{{name}}`)) {{/isPrimitiveType}} {{/isContainer}} {{#isContainer}} - {{#isPrimitiveType}} stopifnot(is.vector(input_json$`{{name}}`), length(input_json$`{{name}}`) != 0) - tmp <- sapply(input_json$`{{name}}`, function(x) stopifnot(is.character(x))) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - stopifnot(is.vector(input_json$`{{name}}`), length(json_input$`{{name}}`) != 0) - tmp <- sapply(input_json$`{{name}}`, function(x) stopifnot(R6::is.R6(x))) - {{/isPrimitiveType}} + {{#isArray}} + {{#uniqueItems}} + if (!identical(input_json$`{{name}}`, unique(input_json$`{{name}}`))) { + stop("Error! Items in `{{name}}` are not unique.") + } + {{/uniqueItems}} + {{/isArray}} + tmp <- sapply(input_json$`{{name}}`, function(x) stopifnot({{#isPrimitiveType}}is.character(x){{/isPrimitiveType}}{{^isPrimitiveType}}R6::is.R6(x){{/isPrimitiveType}})) {{/isContainer}} } else { stop(paste("The JSON input `", input, "` is invalid for {{classname}}: the required field `{{name}}` is missing.")) @@ -360,9 +476,159 @@ #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + {{#allVars}} + {{^isNullable}} + {{#required}} + # check if the required `{{{name}}}` is null + if (is.null(self$`{{{name}}}`)) { + return(FALSE) + } + + {{/required}} + {{/isNullable}} + {{#hasValidation}} + {{#maxLength}} + if (nchar(self$`{{{name}}}`) > {{maxLength}}) { + return(FALSE) + } + {{/maxLength}} + {{#minLength}} + if (nchar(self$`{{{name}}}`) < {{minLength}}) { + return(FALSE) + } + {{/minLength}} + {{#maximum}} + if (self$`{{{name}}}` >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { + return(FALSE) + } + {{/maximum}} + {{#minimum}} + if (self$`{{{name}}}` <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { + return(FALSE) + } + {{/minimum}} + {{#pattern}} + if (!str_detect(self$`{{{name}}}`, "{{{pattern}}}")) { + return(FALSE) + } + {{/pattern}} + {{#isUri}} + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(self$`{{name}}`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + return(FALSE) + } + {{/isUri}} + {{#maxItems}} + if (length(self$`{{{name}}}`) > {{maxItems}}) { + return(FALSE) + } + {{/maxItems}} + {{#minItems}} + if (length(self$`{{{name}}}`) < {{minItems}}) { + return(FALSE) + } + {{/minItems}} + + {{/hasValidation}} + {{/allVars}} + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + {{#allVars}} + {{^isNullable}} + {{#required}} + # check if the required `{{{name}}}` is null + if (is.null(self$`{{{name}}}`)) { + invalid_fields["{{{name}}}"] <- "Non-nullable required field `{{{name}}}` cannot be null." + } + + {{/required}} + {{/isNullable}} + {{#hasValidation}} + {{#maxLength}} + if (nchar(self$`{{{name}}}`) > {{maxLength}}) { + invalid_fields["{{{name}}}"] <- "Invalid length for `{{{name}}}`, must be smaller than or equal to {{maxLength}}." + } + {{/maxLength}} + {{#minLength}} + if (nchar(self$`{{{name}}}`) < {{minLength}}) { + invalid_fields["{{{name}}}"] <- "Invalid length for `{{{name}}}`, must be bigger than or equal to {{minLength}}." + } + {{/minLength}} + {{#maximum}} + if (self$`{{{name}}}` >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { + invalid_fields["{{{name}}}"] <- "Invalid value for `{{{name}}}`, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}." + } + {{/maximum}} + {{#minimum}} + if (self$`{{{name}}}` <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { + invalid_fields["{{{name}}}"] <- "Invalid value for `{{{name}}}`, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}." + } + {{/minimum}} + {{#pattern}} + if (!str_detect(self$`{{{name}}}`, "{{{pattern}}}")) { + invalid_fields["{{{name}}}"] <- "Invalid value for `{{{name}}}`, must conform to the pattern {{{pattern}}}." + } + {{/pattern}} + {{#isUri}} + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(self$`{{name}}`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + invalid_fields["{{{name}}}"] <- "Invalid value for `{{{name}}}`, must be URL." + } + {{/isUri}} + {{#maxItems}} + if (length(self$`{{{name}}}`) > {{maxItems}}) { + invalid_fields["{{{name}}}"] <- "Invalid length for `{{{name}}}`, number of items must be less than or equal to {{maxItems}}." + } + {{/maxItems}} + {{#minItems}} + if (length(self$`{{{name}}}`) < {{minItems}}) { + invalid_fields["{{{name}}}"] <- "Invalid length for `{{{param}}}`, number of items must be greater than or equal to {{minItems}}." + } + {{/minItems}} + + {{/hasValidation}} + {{/allVars}} + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) -{{/isEnum}} -{{/model}} -{{/models}} +## Uncomment below to unlock the class to allow modifications of the method or field +# {{classname}}$unlock() +# +## Below is an example to define the print fnuction +# {{classname}}$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# {{classname}}$lock() diff --git a/modules/openapi-generator/src/main/resources/r/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/r/modelOneOf.mustache index bfa8f82e66..7211b50ed8 100644 --- a/modules/openapi-generator/src/main/resources/r/modelOneOf.mustache +++ b/modules/openapi-generator/src/main/resources/r/modelOneOf.mustache @@ -15,7 +15,7 @@ actual_instance = NULL, #' @field actual_type the type of the object stored in this instance. actual_type = NULL, - #' @field one_of a list of object types defined in the oneOf schema. + #' @field one_of a list of types defined in the oneOf schema. one_of = list({{#oneOf}}"{{{.}}}"{{^-last}}, {{/-last}}{{/oneOf}}), #' Initialize a new {{{classname}}}. #' @@ -39,6 +39,18 @@ #' #' @description #' Deserialize JSON string into an instance of {{{classname}}}. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of {{{classname}}}. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of {{{classname}}}. + #' + #' @description + #' Deserialize JSON string into an instance of {{{classname}}}. #' #' @param input The input JSON. #' @return An instance of {{{classname}}}. @@ -49,23 +61,66 @@ error_messages <- list() instance <- NULL - {{#oneOf}} - {{{.}}}_result <- tryCatch({ - {{{.}}}$public_methods$validateJSON(input) - {{{.}}}_instance <- {{{.}}}$new() - instance <- {{{.}}}_instance$fromJSON(input) - instance_type <- "{{{.}}}" - matched_schemas <- append(matched_schemas, "{{{.}}}") + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + oneof_lookup_result <- tryCatch({ + discriminatorValue <- (jsonlite::fromJSON(input, simplifyVector = FALSE))$`{{{propertyBaseName}}}` + switch(discriminatorValue, + {{#mappedModels}} + {{{mappingName}}}={ + {{{modelName}}}$public_methods$validateJSON(input) + {{{modelName}}}_instance <- {{{modelName}}}$new() + self$actual_instance <- {{{modelName}}}_instance$fromJSON(input) + self$actual_type <- "{{{modelName}}}" + return(self) + }{{^-last}},{{/-last}}{{#-last}})},{{/-last}} + {{/mappedModels}} + {{^mappedModels}} + {{#oneOf}} + {{{.}}}={ + {{{.}}}$public_methods$validateJSON(input) + {{{.}}}_instance <- {{{.}}}$new() + self$actual_instance <- {{{.}}}_instance$fromJSON(input) + self$actual_type <- "{{{.}}}" + return(self) + }{{^-last}},{{/-last}}{{#-last}})},{{/-last}} + {{/oneOf}} + {{/mappedModels}} + error = function(err) err + ) + if (!is.null(oneof_lookup_result["error"])) { + error_messages <- append(error_messages, sprintf("Failed to lookup discriminator value for {{classname}}. Error message: %s. Input: %s", oneof_lookup_result["message"], input)) + } + + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + {{#composedSchemas.oneOf}} + {{^isNull}} + {{{dataType}}}_result <- tryCatch({ + {{#isPrimitiveType}} + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "{{{dataType}}}") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "{{{dataType}}}", typeof(instance))) + } + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{{dataType}}}$public_methods$validateJSON(input) + {{{dataType}}}_instance <- {{{dataType}}}$new() + instance <- {{{dataType}}}_instance$fromJSON(input) + {{/isPrimitiveType}} + instance_type <- "{{{dataType}}}" + matched_schemas <- append(matched_schemas, "{{{dataType}}}") matched <- matched + 1 }, error = function(err) err ) - if (!is.null({{{.}}}_result["error"])) { - error_messages <- append(error_messages, {{{.}}}_result["message"]) + if (!is.null({{{dataType}}}_result["error"])) { + error_messages <- append(error_messages, {{{dataType}}}_result["message"]) } - {{/oneOf}} + {{/isNull}} + {{/composedSchemas.oneOf}} if (matched == 1) { # successfully match exactly 1 schema specified in oneOf self$actual_instance <- instance @@ -144,6 +199,28 @@ ) jsoncontent <- paste(jsoncontent, collapse = ",") as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +#{{classname}}$unlock() +# +## Below is an example to define the print fnuction +#{{classname}}$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#{{classname}}$lock() diff --git a/modules/openapi-generator/src/main/resources/r/model_doc.mustache b/modules/openapi-generator/src/main/resources/r/model_doc.mustache index c6ba5702e7..c0c8f5b7df 100644 --- a/modules/openapi-generator/src/main/resources/r/model_doc.mustache +++ b/modules/openapi-generator/src/main/resources/r/model_doc.mustache @@ -6,7 +6,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{.}}]{{/defaultValue}} +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{.}}] {{/defaultValue}}{{#maximum}}[Max: {{{.}}}] {{/maximum}}{{#minimum}}[Min: {{{.}}}] {{/minimum}}{{#isEnum}}[Enum: {{_enum}}] {{/isEnum}}{{#pattern}}[Pattern: {{.}}] {{/pattern}}{{#maxItems}}[Max. items: {{.}}] {{/maxItems}}{{#minItems}}[Min. items: {{.}}] {{/minItems}}{{#maxLength}}[Max. length: {{.}}] {{/maxLength}}{{#minLength}}[Min. length: {{.}}] {{/minLength}} {{/vars}} {{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/r/partial_header.mustache b/modules/openapi-generator/src/main/resources/r/partial_header.mustache index e3282fc971..81ebbd8df1 100644 --- a/modules/openapi-generator/src/main/resources/r/partial_header.mustache +++ b/modules/openapi-generator/src/main/resources/r/partial_header.mustache @@ -13,4 +13,4 @@ #' Contact: {{{.}}} {{/infoEmail}} #' Generated by: https://openapi-generator.tech -#' +#' \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ruby-client/api_client_faraday_partial.mustache b/modules/openapi-generator/src/main/resources/ruby-client/api_client_faraday_partial.mustache index 5d8e8d04e7..59dedfc853 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/api_client_faraday_partial.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/api_client_faraday_partial.mustache @@ -67,7 +67,6 @@ # Overload default options only if provided request.options.params_encoder = config.params_encoder if config.params_encoder request.options.timeout = config.timeout if config.timeout - request.options.verbose = config.debugging if config.debugging request.url url request.params = query_params @@ -91,7 +90,7 @@ case value when ::File, ::Tempfile # TODO hardcode to application/octet-stream, need better way to detect content type - data[key] = Faraday::UploadIO.new(value.path, 'application/octet-stream', value.path) + data[key] = Faraday::FilePart.new(value.path, 'application/octet-stream', value.path) when ::Array, nil # let Faraday handle Array and nil parameters data[key] = value diff --git a/modules/openapi-generator/src/main/resources/ruby-client/configuration.mustache b/modules/openapi-generator/src/main/resources/ruby-client/configuration.mustache index 46319a3cdb..8f7856537b 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/configuration.mustache @@ -111,9 +111,7 @@ module {{moduleName}} @ssl_ca_file = nil @ssl_client_cert = nil @ssl_client_key = nil - @middlewares = [] - @request_middlewares = [] - @response_middlewares = [] + @middlewares = Hash.new { |h, k| h[k] = [] } @timeout = 60 # return data as binary instead of file @return_binary_data = false @@ -350,31 +348,56 @@ module {{moduleName}} {{#isFaraday}} # Adds middleware to the stack def use(*middleware) - @middlewares << middleware + set_faraday_middleware(:use, *middleware) end # Adds request middleware to the stack def request(*middleware) - @request_middlewares << middleware + set_faraday_middleware(:request, *middleware) end # Adds response middleware to the stack def response(*middleware) - @response_middlewares << middleware + set_faraday_middleware(:response, *middleware) end + # Adds Faraday middleware setting information to the stack + # + # @example Use the `set_faraday_middleware` method to set middleware information + # config.set_faraday_middleware(:request, :retry, max: 3, methods: [:get, :post], retry_statuses: [503]) + # config.set_faraday_middleware(:response, :logger, nil, { bodies: true, log_level: :debug }) + # config.set_faraday_middleware(:use, Faraday::HttpCache, store: Rails.cache, shared_cache: false) + # config.set_faraday_middleware(:insert, 0, FaradayMiddleware::FollowRedirects, { standards_compliant: true, limit: 1 }) + # config.set_faraday_middleware(:swap, 0, Faraday::Response::Logger) + # config.set_faraday_middleware(:delete, Faraday::Multipart::Middleware) + # + # @see https://github.com/lostisland/faraday/blob/v2.3.0/lib/faraday/rack_builder.rb#L92-L143 + def set_faraday_middleware(operation, key, *args, &block) + unless [:request, :response, :use, :insert, :insert_before, :insert_after, :swap, :delete].include?(operation) + fail ArgumentError, "Invalid faraday middleware operation #{operation}. Must be" \ + " :request, :response, :use, :insert, :insert_before, :insert_after, :swap or :delete." + end + + @middlewares[operation] << [key, args, block] + end + ruby2_keywords(:set_faraday_middleware) if respond_to?(:ruby2_keywords, true) + # Set up middleware on the connection def configure_middleware(connection) - @middlewares.each do |middleware| - connection.use(*middleware) + return if @middlewares.empty? + + [:request, :response, :use, :insert, :insert_before, :insert_after, :swap].each do |operation| + next unless @middlewares.key?(operation) + + @middlewares[operation].each do |key, args, block| + connection.builder.send(operation, key, *args, &block) + end end - @request_middlewares.each do |middleware| - connection.request(*middleware) - end - - @response_middlewares.each do |middleware| - connection.response(*middleware) + if @middlewares.key?(:delete) + @middlewares[:delete].each do |key, _args, _block| + connection.builder.delete(key) + end end end {{/isFaraday}} diff --git a/modules/openapi-generator/src/main/resources/ruby-client/gem.mustache b/modules/openapi-generator/src/main/resources/ruby-client/gem.mustache index 70027d1f61..c366da006f 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/gem.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/gem.mustache @@ -9,6 +9,7 @@ require '{{gemName}}/version' require '{{gemName}}/configuration' # Models +{{^useAutoload}} {{#models}} {{#model}} {{^parent}} @@ -23,11 +24,24 @@ require '{{gemName}}/{{modelPackage}}/{{classFilename}}' {{/parent}} {{/model}} {{/models}} +{{/useAutoload}} +{{#useAutoload}} +{{#models}} +{{#model}} +{{moduleName}}.autoload :{{classname}}, '{{gemName}}/{{modelPackage}}/{{classFilename}}' +{{/model}} +{{/models}} +{{/useAutoload}} # APIs {{#apiInfo}} {{#apis}} +{{^useAutoload}} require '{{importPath}}' +{{/useAutoload}} +{{#useAutoload}} +{{moduleName}}.autoload :{{classname}}, '{{importPath}}' +{{/useAutoload}} {{/apis}} {{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/ruby-client/partial_model_enum_class.mustache b/modules/openapi-generator/src/main/resources/ruby-client/partial_model_enum_class.mustache index 4b8b5a0ffd..d2ddbff197 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/partial_model_enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/partial_model_enum_class.mustache @@ -2,6 +2,10 @@ {{{name}}} = {{{value}}}.freeze{{/enumVars}} {{/allowableValues}} + def self.all_vars + @all_vars ||= [{{#allowableValues}}{{#enumVars}}{{{name}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -13,8 +17,7 @@ # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = {{classname}}.constants.select { |c| {{classname}}::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #{{{classname}}}" if constantValues.empty? - value + return value if {{classname}}.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #{{{classname}}}" end end \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/ruby-client/partial_oneof_module_doc.mustache b/modules/openapi-generator/src/main/resources/ruby-client/partial_oneof_module_doc.mustache index 64a6c32dc8..f86cefe92b 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/partial_oneof_module_doc.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/partial_oneof_module_doc.mustache @@ -60,6 +60,7 @@ require '{{{gemName}}}' # } {{/-last}} {{/mappedModels}} +``` {{/discriminator}} ### build diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-callbacks.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-callbacks.mustache index bafd04b1b7..44e16903d9 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/client-callbacks.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/client-callbacks.mustache @@ -49,7 +49,7 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { {{#apiInfo}} {{#apis}} {{#operations}} @@ -58,7 +58,7 @@ impl RequestParser for ApiRequestParser { {{#urls}} {{#requests}} // {{{operationId}}} - {{{httpMethod}}} {{{path}}} - &hyper::Method::{{{vendorExtensions.x-http-method}}} if path.matched(paths::ID_{{{vendorExtensions.x-path-id}}}) => Some("{{{operationId}}}"), + hyper::Method::{{{vendorExtensions.x-http-method}}} if path.matched(paths::ID_{{{vendorExtensions.x-path-id}}}) => Some("{{{operationId}}}"), {{/requests}} {{/urls}} {{/callbacks}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache index 386c68eebc..c49bdd656d 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache @@ -21,7 +21,7 @@ fn into_base_path(input: impl TryInto, } } - let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let host = uri.host().ok_or(ClientInitError::MissingHost)?; let port = uri.port_u16().map(|x| format!(":{}", x)).unwrap_or_default(); Ok(format!("{}://{}{}{}", scheme, host, port, uri.path().trim_end_matches('/'))) } @@ -160,7 +160,7 @@ impl Client, C> where "https" => { let connector = connector.https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; HyperClient::Https(hyper::client::Client::builder().build(connector)) }, _ => { @@ -212,7 +212,7 @@ impl Client, C let https_connector = Connector::builder() .https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -233,7 +233,7 @@ impl Client, C .https() .pin_server_certificate(ca_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -261,7 +261,7 @@ impl Client, C .pin_server_certificate(ca_certificate) .client_authentication(client_key, client_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } } diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache index 768e846eb9..a93adb61e0 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache @@ -49,7 +49,7 @@ ¶m_{{{paramName}}}.iter().map(ToString::to_string).collect::>().join(",")); {{/isArray}} {{^isArray}} - ¶m_{{{paramName}}}.to_string()); + ¶m_{{{paramName}}}{{^isString}}.to_string(){{/isString}}); {{/isArray}} {{/x-consumes-json}} {{/vendorExtensions}} @@ -60,10 +60,8 @@ {{#authMethods}} {{#isApiKey}} {{#isKeyInQuery}} - if let Some(auth_data) = (context as &dyn Has>).get().as_ref() { - if let AuthData::ApiKey(ref api_key) = *auth_data { - query_string.append_pair("{{keyParamName}}", api_key); - } + if let Some(AuthData::ApiKey(ref api_key)) = (context as &dyn Has>).get().as_ref() { + query_string.append_pair("{{keyParamName}}", api_key); } {{/isKeyInQuery}} {{/isApiKey}} @@ -187,8 +185,8 @@ // no such boundary is used. let mut boundary = generate_boundary(); for b in boundary.iter_mut() { - if b == &('/' as u8) { - *b = '=' as u8; + if b == &(b'/') { + *b = b'='; } } @@ -257,7 +255,7 @@ {{/x-consumes-plain-text}} {{#required}} {{#x-consumes-xml}} - let body = param_{{{paramName}}}.to_xml(); + let body = param_{{{paramName}}}.as_xml(); {{/x-consumes-xml}} {{#x-consumes-json}} let body = serde_json::to_string(¶m_{{{paramName}}}).expect("impossible to fail to serialize"); @@ -266,7 +264,7 @@ {{^required}} let body = param_{{{paramName}}}.map(|ref body| { {{#x-consumes-xml}} - body.to_xml() + body.as_xml() {{/x-consumes-xml}} {{#x-consumes-json}} serde_json::to_string(body).expect("impossible to fail to serialize") @@ -298,15 +296,17 @@ {{/bodyParam}} {{/x-consumes-multipart}} {{/vendorExtensions}} - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); {{#hasAuthMethods}} + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { {{#authMethods}} {{#isBasicBasic}} @@ -364,6 +364,7 @@ {{/required}} request.headers_mut().append( HeaderName::from_static("{{{nameInLowerCase}}}"), + #[allow(clippy::redundant_clone)] match header::IntoHeaderValue(param_{{{paramName}}}.clone()).try_into() { Ok(header) => header, Err(e) => { @@ -382,7 +383,7 @@ {{/isMap}} {{/headerParams}} - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -398,12 +399,11 @@ return Err(ApiError(format!("Invalid response header {{baseName}} for response {{code}} - {}", e))); }, }; - let response_{{{name}}} = response_{{{name}}}.0; {{#required}} - response_{{{name}}} + response_{{{name}}}.0 {{/required}} {{^required}} - Some(response_{{{name}}}) + Some(response_{{{name}}}.0) {{/required}} }, {{#required}} @@ -415,8 +415,8 @@ }; {{/headers}} - let body = response.into_body(); {{#dataType}} + let body = response.into_body(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; @@ -450,7 +450,7 @@ {{#headers}} {{#-first}} { - body: body, + body, {{/-first}} {{{name}}}: response_{{name}}, {{#-last}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/context.mustache b/modules/openapi-generator/src/main/resources/rust-server/context.mustache index f3e1c5e130..4ec03e0d2e 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/context.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/context.mustache @@ -110,7 +110,7 @@ impl Service> for AddContext(&headers) { + if let Some(basic) = swagger::auth::from_headers::(headers) { let auth_data = AuthData::Basic(basic); let context = context.push(Some(auth_data)); let context = context.push(None::); @@ -123,7 +123,7 @@ impl Service> for AddContext(&headers) { + if let Some(bearer) = swagger::auth::from_headers::(headers) { let auth_data = AuthData::Bearer(bearer); let context = context.push(Some(auth_data)); let context = context.push(None::); @@ -137,7 +137,7 @@ impl Service> for AddContext(&headers) { + if let Some(bearer) = swagger::auth::from_headers::(headers) { let auth_data = AuthData::Bearer(bearer); let context = context.push(Some(auth_data)); let context = context.push(None::); @@ -151,7 +151,7 @@ impl Service> for AddContext); @@ -165,7 +165,7 @@ impl Service> for AddContext::new( service diff --git a/modules/openapi-generator/src/main/resources/rust-server/lib.mustache b/modules/openapi-generator/src/main/resources/rust-server/lib.mustache index 57147489c6..c642b08a65 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/lib.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/lib.mustache @@ -1,4 +1,6 @@ #![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::blacklisted_name)] use async_trait::async_trait; use futures::Stream; @@ -9,9 +11,9 @@ use serde::{Serialize, Deserialize}; type ServiceError = Box; -pub const BASE_PATH: &'static str = "{{{basePathWithoutHost}}}"; +pub const BASE_PATH: &str = "{{{basePathWithoutHost}}}"; {{#appVersion}} -pub const API_VERSION: &'static str = "{{{.}}}"; +pub const API_VERSION: &str = "{{{.}}}"; {{/appVersion}} {{#apiInfo}} @@ -25,6 +27,7 @@ pub const API_VERSION: &'static str = "{{{.}}}"; {{/apiInfo}} /// API #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait Api { fn poll_ready(&self, _cx: &mut Context) -> Poll>> { Poll::Ready(Ok(())) @@ -52,6 +55,7 @@ pub trait Api { /// API where `Context` isn't passed on every API call #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait ApiNoContext { fn poll_ready(&self, _cx: &mut Context) -> Poll>>; @@ -82,7 +86,7 @@ pub trait ApiNoContext { pub trait ContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> ContextWrapperExt for T { @@ -222,7 +226,7 @@ pub trait CallbackApiNoContext { pub trait CallbackContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> CallbackContextWrapperExt for T { diff --git a/modules/openapi-generator/src/main/resources/rust-server/models.mustache b/modules/openapi-generator/src/main/resources/rust-server/models.mustache index b319670038..30be5a54f3 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -33,7 +33,7 @@ impl std::fmt::Display for {{{classname}}} { match *self { {{#allowableValues}} {{#enumVars}} - {{{classname}}}::{{{name}}} => write!(f, "{}", {{{value}}}), + {{{classname}}}::{{{name}}} => write!(f, {{{value}}}), {{/enumVars}} {{/allowableValues}} } @@ -189,7 +189,7 @@ impl<'a> std::iter::IntoIterator for &'a {{{classname}}} { type IntoIter = std::slice::Iter<'a, {{{arrayModelType}}}>; fn into_iter(self) -> Self::IntoIter { - (&self.0).into_iter() + (&self.0).iter() } } @@ -198,7 +198,7 @@ impl<'a> std::iter::IntoIterator for &'a mut {{{classname}}} { type IntoIter = std::slice::IterMut<'a, {{{arrayModelType}}}>; fn into_iter(self) -> Self::IntoIter { - (&mut self.0).into_iter() + (&mut self.0).iter_mut() } } @@ -220,7 +220,7 @@ impl std::ops::DerefMut for {{{classname}}} { /// Should be implemented in a serde serializer impl std::string::ToString for {{{classname}}} { fn to_string(&self) -> String { - self.iter().map(|x| x.to_string()).collect::>().join(",").to_string() + self.iter().map(|x| x.to_string()).collect::>().join(",") } } @@ -274,9 +274,10 @@ pub struct {{{classname}}} { } impl {{{classname}}} { + #[allow(clippy::new_without_default)] pub fn new({{#vars}}{{^defaultValue}}{{{name}}}: {{#isNullable}}swagger::Nullable<{{/isNullable}}{{{dataType}}}{{#isNullable}}>{{/isNullable}}, {{/defaultValue}}{{/vars}}) -> {{{classname}}} { {{{classname}}} { -{{#vars}} {{{name}}}: {{{defaultValue}}}{{^defaultValue}}{{{name}}}{{/defaultValue}}, +{{#vars}} {{#defaultValue}}{{{name}}}: {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{{name}}}{{/defaultValue}}, {{/vars}} } } @@ -287,64 +288,68 @@ impl {{{classname}}} { /// Should be implemented in a serde serializer impl std::string::ToString for {{{classname}}} { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ {{#vars}} {{#isByteArray}} - // Skipping {{baseName}} in query parameter serialization + // Skipping {{baseName}} in query parameter serialization {{/isByteArray}} {{#isBinary}} - // Skipping {{baseName}} in query parameter serialization + // Skipping {{baseName}} in query parameter serialization {{/isBinary}} {{#isMap}} - // Skipping {{baseName}} in query parameter serialization + // Skipping {{baseName}} in query parameter serialization {{/isMap}} {{^isPrimitiveType}} - // Skipping {{baseName}} in query parameter serialization + // Skipping {{baseName}} in query parameter serialization {{/isPrimitiveType}} {{^isByteArray}}{{^isBinary}}{{^isMap}}{{#isPrimitiveType}} {{#required}} - params.push("{{{baseName}}}".to_string()); + Some("{{{baseName}}}".to_string()), {{^isArray}} {{#isNullable}} - params.push(self.{{{name}}}.as_ref().map_or("null".to_string(), |x| x.to_string())); + Some(self.{{{name}}}.as_ref().map_or("null".to_string(), |x| x.to_string())), {{/isNullable}} {{^isNullable}} - params.push(self.{{{name}}}.to_string()); + Some(self.{{{name}}}.to_string()), {{/isNullable}} {{/isArray}} {{#isArray}} {{#isNullable}} - params.push(self.{{{name}}}.as_ref().map_or(vec!["null".to_string()], |x| x.iter().map(|x| x.to_string()).collect::>().join(",").to_string())); + Some(self.{{{name}}}.as_ref().map_or(vec!["null".to_string()], |x| x.iter().map(|x| x.to_string()).collect::>().join(","))), {{/isNullable}} {{^isNullable}} - params.push(self.{{{name}}}.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + Some(self.{{{name}}}.iter().map(|x| x.to_string()).collect::>().join(",")), {{/isNullable}} {{/isArray}} {{/required}} {{^required}} - if let Some(ref {{{name}}}) = self.{{{name}}} { - params.push("{{{baseName}}}".to_string()); + self.{{{name}}}.as_ref().map(|{{{name}}}| { + vec![ + "{{{baseName}}}".to_string(), {{^isArray}} {{#isNullable}} - params.push({{{name}}}.as_ref().map_or("null".to_string(), |x| x.to_string())); + {{{name}}}.as_ref().map_or("null".to_string(), |x| x.to_string()), {{/isNullable}} {{^isNullable}} - params.push({{{name}}}.to_string()); + {{{name}}}.to_string(), {{/isNullable}} {{/isArray}} {{#isArray}} {{#isNullable}} - params.push({{{name}}}.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",").to_string())); + {{{name}}}.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",")), {{/isNullable}} {{^isNullable}} - params.push({{{name}}}.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + {{{name}}}.iter().map(|x| x.to_string()).collect::>().join(","), {{/isNullable}} {{/isArray}} - } + ].join(",") + }), {{/required}} {{/isPrimitiveType}}{{/isMap}}{{/isBinary}}{{/isByteArray}} {{/vars}} - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -355,8 +360,9 @@ impl std::str::FromStr for {{{classname}}} { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { {{#vars}} pub {{{name}}}: Vec<{{{dataType}}}>, @@ -366,7 +372,7 @@ impl std::str::FromStr for {{{classname}}} { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -376,6 +382,7 @@ impl std::str::FromStr for {{{classname}}} { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { {{#vars}} {{#isBinary}} @@ -394,7 +401,8 @@ impl std::str::FromStr for {{{classname}}} { "{{{baseName}}}" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in {{{classname}}}".to_string()), {{/isNullable}} {{^isNullable}} - "{{{baseName}}}" => intermediate_rep.{{{name}}}.push(<{{{dataType}}} as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "{{{baseName}}}" => intermediate_rep.{{{name}}}.push(<{{{dataType}}} as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), {{/isNullable}} {{/isContainer}} {{/isByteArray}} @@ -415,7 +423,7 @@ impl std::str::FromStr for {{{classname}}} { {{{name}}}: std::result::Result::Err("Nullable types not supported in {{{classname}}}".to_string())?, {{/isNullable}} {{^isNullable}} - {{{name}}}: intermediate_rep.{{{name}}}.into_iter().next(){{#required}}.ok_or("{{{baseName}}} missing in {{{classname}}}".to_string())?{{/required}}, + {{{name}}}: intermediate_rep.{{{name}}}.into_iter().next(){{#required}}.ok_or_else(|| "{{{baseName}}} missing in {{{classname}}}".to_string())?{{/required}}, {{/isNullable}} {{/vars}} }) @@ -479,7 +487,7 @@ impl {{{classname}}} { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { {{#xmlNamespace}} let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache index d38f3b5b3d..08e63ca087 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache @@ -28,13 +28,13 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { {{#apiInfo}} {{#apis}} {{#operations}} {{#operation}} // {{{operationId}}} - {{{httpMethod}}} {{{path}}} - &hyper::Method::{{{vendorExtensions.x-http-method}}} if path.matched(paths::ID_{{{vendorExtensions.x-path-id}}}) => Some("{{{operationId}}}"), + hyper::Method::{{{vendorExtensions.x-http-method}}} if path.matched(paths::ID_{{{vendorExtensions.x-path-id}}}) => Some("{{{operationId}}}"), {{/operation}} {{/operations}} {{/apis}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache index 0560d72e7d..a8ac8bbc80 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache @@ -1,10 +1,10 @@ // {{{operationId}}} - {{{httpMethod}}} {{{path}}} - &hyper::Method::{{vendorExtensions.x-http-method}} if path.matched(paths::ID_{{vendorExtensions.x-path-id}}) => { + hyper::Method::{{vendorExtensions.x-http-method}} if path.matched(paths::ID_{{vendorExtensions.x-path-id}}) => { {{#hasAuthMethods}} { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -50,10 +50,10 @@ {{/x-consumes-multipart}} {{#x-has-path-params}} // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_{{{x-path-id}}} - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE {{{x-path-id}}} in set but failed match against \"{}\"", path, paths::REGEX_{{{x-path-id}}}.as_str()) ); @@ -139,7 +139,7 @@ {{/required}} {{/vendorExtensions.x-consumes-json}} {{#vendorExtensions.x-consumes-json}} - .nth(0); + .next(); let param_{{{paramName}}} = match param_{{{paramName}}} { Some(param_{{{paramName}}}) => { let param_{{{paramName}}} = @@ -167,7 +167,7 @@ {{/vendorExtensions.x-consumes-json}} {{/isArray}} {{^isArray}} - .nth(0); + .next(); let param_{{{paramName}}} = match param_{{{paramName}}} { Some(param_{{{paramName}}}) => { let param_{{{paramName}}} = @@ -292,7 +292,7 @@ _ => { return Ok(Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Unable to process all message parts"))) + .body(Body::from("Unable to process all message parts".to_string())) .expect("Unable to create Bad Request response due to failure to process all message")) }, }; @@ -335,7 +335,7 @@ return Ok( Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Missing required form parameter {{{paramName}}}"))) + .body(Body::from("Missing required form parameter {{{paramName}}}".to_string())) .expect("Unable to create Bad Request due to missing required form parameter {{{paramName}}}")) {{/required}} {{^required}} @@ -378,9 +378,9 @@ // Extract the top-level content type header. let content_type_mime = headers .get(CONTENT_TYPE) - .ok_or("Missing content-type header".to_string()) + .ok_or_else(|| "Missing content-type header".to_string()) .and_then(|v| v.to_str().map_err(|e| format!("Couldn't read content-type header value for {{operationId}}: {}", e))) - .and_then(|v| v.parse::().map_err(|_e| format!("Couldn't parse content-type header value for {{operationId}}"))); + .and_then(|v| v.parse::().map_err(|_e| "Couldn't parse content-type header value for {{operationId}}".to_string())); // Insert top-level content type header into a Headers object. let mut multi_part_headers = Headers::new(); @@ -415,7 +415,7 @@ for node in nodes { if let Node::Part(part) = node { let content_type = part.content_type().map(|x| format!("{}",x)); - match content_type.as_ref().map(|x| x.as_str()) { + match content_type.as_deref() { {{#formParams}} {{^isBinary}} Some("{{{contentType}}}") if param_{{{paramName}}}.is_none() => { @@ -464,7 +464,7 @@ Some(x) => x, None => return Ok(Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Missing required multipart/related parameter {{{paramName}}}"))) + .body(Body::from("Missing required multipart/related parameter {{{paramName}}}".to_string())) .expect("Unable to create Bad Request response for missing multipart/related parameter {{{paramName}}} due to schema")) }; {{/required}} @@ -488,7 +488,7 @@ let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); {{#bodyParams}} @@ -641,7 +641,7 @@ }, Err(e) => Ok(Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read multipart body"))) + .body(Body::from("Couldn't read multipart body".to_string())) .expect("Unable to create Bad Request response due to unable read multipart body")), } {{/vendorExtensions}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-paths.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-paths.mustache index 2930a49e16..c5297d058d 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-paths.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-paths.mustache @@ -14,6 +14,7 @@ mod paths { {{#hasPathParams}} lazy_static! { pub static ref REGEX_{{{PATH_ID}}}: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^{{{basePathWithoutHost}}}{{{pathRegEx}}}") .expect("Unable to create regex for {{{PATH_ID}}}"); } diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-service-header.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-service-header.mustache index 76c0e9a854..01fde31fa1 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-service-header.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-service-header.mustache @@ -20,7 +20,7 @@ impl Service where { pub fn new(api_impl: T) -> Self { Service { - api_impl: api_impl, + api_impl, marker: PhantomData } } @@ -33,7 +33,7 @@ impl Clone for Service where fn clone(&self) -> Self { Service { api_impl: self.api_impl.clone(), - marker: self.marker.clone(), + marker: self.marker, } } } @@ -63,4 +63,4 @@ impl hyper::service::Service<(Request, C)> for Service where This match statement is duplicated below in `parse_operation_id()`. Please update both places if changing how this code is autogenerated. }} - match &method { + match method { diff --git a/modules/openapi-generator/src/main/resources/rust/Cargo.mustache b/modules/openapi-generator/src/main/resources/rust/Cargo.mustache index 24f536b558..9ca82500e3 100644 --- a/modules/openapi-generator/src/main/resources/rust/Cargo.mustache +++ b/modules/openapi-generator/src/main/resources/rust/Cargo.mustache @@ -18,6 +18,11 @@ serde_yaml = "0.7" base64 = "~0.7.0" futures = "^0.3" {{/hyper}} +{{#withAWSV4Signature}} +aws-sigv4 = "0.3.0" +http = "0.2.5" +secrecy = "0.8.0" +{{/withAWSV4Signature}} {{#reqwest}} {{^supportAsync}} reqwest = "~0.9" @@ -28,11 +33,6 @@ version = "^0.11" features = ["json", "multipart"] {{/supportAsync}} {{/reqwest}} -{{#withAWSV4Signature}} -aws-sigv4 = "0.3.0" -http = "0.2.5" -secrecy = "0.8.0" -{{/withAWSV4Signature}} [dev-dependencies] {{#hyper}} diff --git a/modules/openapi-generator/src/main/resources/rust/model.mustache b/modules/openapi-generator/src/main/resources/rust/model.mustache index 1bd2b8db9e..8e4dac90ce 100644 --- a/modules/openapi-generator/src/main/resources/rust/model.mustache +++ b/modules/openapi-generator/src/main/resources/rust/model.mustache @@ -82,7 +82,7 @@ impl {{{classname}}} { pub fn new({{#requiredVars}}{{{name}}}: {{#isNullable}}Option<{{/isNullable}}{{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}}>{{/isNullable}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}} { {{{classname}}} { {{#vars}} - {{{name}}}{{^required}}{{#isArray}}: None{{/isArray}}{{#isMap}}: None{{/isMap}}{{^isContainer}}: None{{/isContainer}}{{/required}}{{#required}}{{#isModel}}: Box::new({{{name}}}){{/isModel}}{{/required}}, + {{{name}}}{{^required}}{{#isArray}}: None{{/isArray}}{{#isMap}}: None{{/isMap}}{{^isContainer}}: None{{/isContainer}}{{/required}}{{#required}}{{#isModel}}: {{^isNullable}}Box::new({{{name}}}){{/isNullable}}{{#isNullable}}if let Some(x) = {{{name}}} {Some(Box::new(x))} else {None}{{/isNullable}}{{/isModel}}{{/required}}, {{/vars}} } } diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache index f7d5ba6f82..29ef3ce991 100644 --- a/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache +++ b/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache @@ -20,7 +20,7 @@ class {{classname}}(baseUrl: String) { {{#javadocRenderer}} {{>javadoc}} {{/javadocRenderer}} - def {{operationId}}({{>methodParameters}}): Request[{{#separateErrorChannel}}Either[ResponseException[String, Exception], {{>operationReturnType}}]{{/separateErrorChannel}}{{^separateErrorChannel}}{{>operationReturnType}}{{/separateErrorChannel}}, Nothing] = + def {{operationId}}({{>methodParameters}}): Request[{{#defaultReturnType}}Either[Either[String, String], Unit]{{/defaultReturnType}}{{^defaultReturnType}}{{#separateErrorChannel}}Either[ResponseException[String, Exception], {{>operationReturnType}}]{{/separateErrorChannel}}{{^separateErrorChannel}}{{>operationReturnType}}{{/separateErrorChannel}}{{/defaultReturnType}}, Any] = basicRequest .method(Method.{{httpMethod.toUpperCase}}, uri"$baseUrl{{{path}}}{{#queryParams.0}}?{{#queryParams}}{{baseName}}=${ {{{paramName}}} }{{^-last}}&{{/-last}}{{/queryParams}}{{/queryParams.0}}{{#isApiKey}}{{#isKeyInQuery}}{{^queryParams.0}}?{{/queryParams.0}}{{#queryParams.0}}&{{/queryParams.0}}{{keyParamName}}=${apiKey.value}&{{/isKeyInQuery}}{{/isApiKey}}") .contentType({{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}}){{#headerParams}} @@ -36,7 +36,7 @@ class {{classname}}(baseUrl: String) { {{>paramMultipartCreation}}{{^-last}}, {{/-last}}{{/formParams}} ).flatten){{/isMultipart}}{{/formParams.0}}{{#bodyParam}} .body({{paramName}}){{/bodyParam}} - .response({{#separateErrorChannel}}asJson{{/separateErrorChannel}}{{^separateErrorChannel}}asJsonAlwaysUnsafe{{/separateErrorChannel}}[{{>operationReturnType}}]) + .response({{#defaultReturnType}}asEither(asString, ignore){{/defaultReturnType}}{{^defaultReturnType}}{{#separateErrorChannel}}asJson{{/separateErrorChannel}}{{^separateErrorChannel}}asJsonAlwaysUnsafe{{/separateErrorChannel}}[{{>operationReturnType}}]{{/defaultReturnType}}) {{/operation}} } diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/model.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/model.mustache index 78e6f23820..ecece27a59 100644 --- a/modules/openapi-generator/src/main/resources/scala-sttp/model.mustache +++ b/modules/openapi-generator/src/main/resources/scala-sttp/model.mustache @@ -21,7 +21,7 @@ case class {{classname}}( {{#description}} /* {{{.}}} */ {{/description}} - {{{name}}}: {{^required}}Option[{{/required}}{{^isEnum}}{{dataType}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}] = None{{/required}}{{^-last}},{{/-last}} + {{{name}}}: {{^required}}Option[{{/required}}{{^isEnum}}{{dataType}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{classname}}Enums.{{datatypeWithEnum}}{{/isArray}}{{#isArray}}Seq[{{classname}}Enums.{{datatypeWithEnum}}]{{/isArray}}{{/isEnum}}{{^required}}] = None{{/required}}{{^-last}},{{/-last}} {{/vars}} ) {{/isEnum}} diff --git a/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache b/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache index 78c98979b9..1976389603 100644 --- a/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache @@ -63,6 +63,41 @@ import Vapor{{/useVapor}} return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -74,6 +109,7 @@ import Vapor{{/useVapor}} .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/modules/openapi-generator/src/main/resources/swift5/APIs.mustache b/modules/openapi-generator/src/main/resources/swift5/APIs.mustache index 847e9be559..564291dbcf 100644 --- a/modules/openapi-generator/src/main/resources/swift5/APIs.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/APIs.mustache @@ -37,17 +37,19 @@ import Vapor {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let method: String {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let URLString: String {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let requestTask: RequestTask = RequestTask() + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available.{{#useURLSession}} /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client.{{/useURLSession}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var onProgressReady: ((Progress) -> Void)? - required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders({{projectName}}API.customHeaders) } diff --git a/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache b/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache index d563d11b4a..0f3013e792 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache @@ -5,7 +5,8 @@ // import Foundation{{#useVapor}} -import Vapor{{/useVapor}} +import Vapor{{/useVapor}}{{#useAlamofire}} +import Alamofire{{/useAlamofire}} {{#swiftUseApiNamespace}} @available(*, deprecated, renamed: "{{projectName}}API.Configuration") @@ -20,9 +21,36 @@ extension {{projectName}}API { // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"{{/useVapor}} -} -{{#swiftUseApiNamespace}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var successfulStatusCodeRange: Range = 200..<300{{/useVapor}}{{#useAlamofire}} + /// ResponseSerializer that will be used by the generator for `Data` responses + /// + /// If unchanged, Alamofires default `DataResponseSerializer` will be used. + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var dataResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(DataResponseSerializer()) + /// ResponseSerializer that will be used by the generator for `String` responses + /// + /// If unchanged, Alamofires default `StringResponseSerializer` will be used. + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var stringResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(StringResponseSerializer()){{/useAlamofire}} } +{{#useAlamofire}} + +/// Type-erased ResponseSerializer +/// +/// This is needed in order to use `ResponseSerializer` as a Type in `Configuration`. Obsolete with `any` keyword in Swift >= 5.7 +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct AnyResponseSerializer: ResponseSerializer { + + let _serialize: (URLRequest?, HTTPURLResponse?, Data?, Error?) throws -> T + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(_ delegatee: V) where V.SerializedObject == T { + _serialize = delegatee.serialize + } + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T { + try _serialize(request, response, data, error) + } +}{{/useAlamofire}}{{#swiftUseApiNamespace}}} {{/swiftUseApiNamespace}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache index b18821ae14..882d773601 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache @@ -147,6 +147,17 @@ extension KeyedEncodingContainerProtocol { } } + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -186,11 +197,33 @@ extension KeyedDecodingContainerProtocol { return map } + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + }{{/generateModelAdditionalProperties}}{{^useVapor}} extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } }{{/useVapor}}{{#usePromiseKit}} diff --git a/modules/openapi-generator/src/main/resources/swift5/Models.mustache b/modules/openapi-generator/src/main/resources/swift5/Models.mustache index dc69d0c0b4..776a36f923 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Models.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Models.mustache @@ -19,7 +19,7 @@ extension CaseIterableDefaultsLast { /// Initializes an enum such that if a known raw value is found, then it is decoded. /// Otherwise the last case is used. /// - Parameter decoder: A decoder. - public init(from decoder: Decoder) throws { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(from decoder: Decoder) throws { if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { self = value } else if let lastValue = Self.allCases.last { @@ -106,15 +106,20 @@ extension NullEncodable: Codable where Wrapped: Codable { } } -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} final class RequestTask { +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} final class RequestTask{{#useAsyncAwait}}: @unchecked Sendable{{/useAsyncAwait}} { + private var lock = NSRecursiveLock() {{#useAlamofire}} private var request: Request? internal func set(request: Request) { + lock.lock() + defer { lock.unlock() } self.request = request } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func cancel() { + lock.lock() + defer { lock.unlock() } request?.cancel() request = nil } @@ -123,10 +128,14 @@ extension NullEncodable: Codable where Wrapped: Codable { private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/modules/openapi-generator/src/main/resources/swift5/OpenAPIDateWithoutTime.mustache b/modules/openapi-generator/src/main/resources/swift5/OpenAPIDateWithoutTime.mustache new file mode 100644 index 0000000000..9ffb2c4f86 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/swift5/OpenAPIDateWithoutTime.mustache @@ -0,0 +1,69 @@ +// OpenAPIDateWithoutTime.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +/// Represents a date without time information (e.g. a birthday) for transmission from and to a REST API +/// +/// This type is used as a representation for openapi specs `date` format which does not contain +/// time information as opposed to the `date-time` format. Although it internally uses `Date` for +/// (de-)serialization as well the generator needs to be able to distinguish between the two formats. +/// - note: As `Date` is agnostic to timezones (and calendars), timezone information is needed to be able to add +/// an appropriate padding in order to transform to GMT+0 which is the assumed timezone in ISO 8601. +/// When decoding, GMT+0 can be assumed (again: ISO8601) so there is no padding necessary and wrappedDate +/// can be used safely. +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct OpenAPIDateWithoutTime: Codable, Hashable, Equatable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let wrappedDate: Date + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let timezone: TimeZone + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: CodingKey, CaseIterable { + case wrappedDate + case timezone + } + + /// On decoding ISO8601 timezone is assumed + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + self.wrappedDate = try container.decode(Date.self) + self.timezone = OpenISO8601DateFormatter.withoutTime.timeZone + } + + /// Convenience Initializer which is useful when dealing with optionals a lot like e.g. in API mappers + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init?(wrappedDate: Date?, timezone: TimeZone = .current) { + guard let wrappedDate = wrappedDate else { + return nil + } + + self.init(wrappedDate: wrappedDate, timezone: timezone) + } + + /// Designated Initializer for `OpenAPIDateWithoutTime` + /// + /// Since usually `Date`s without time components - as e.g. birthdays - are created Calendar- and timezone-aware + // it is important to also provide a timezone so that the generator is able to normalize the supplied Date to ISO8601 (GMT+0) + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(wrappedDate: Date, timezone: TimeZone) { + self.wrappedDate = wrappedDate + self.timezone = timezone + } + + /// Only the wrappedDate is encoded normalized to GMT+0 with an offset derived from the supplied Timezone + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(OpenISO8601DateFormatter.withoutTime.string(from: normalizedWrappedDate())) + } + + /// Normalizes the wrappedDate to GMT+0 according to the supplied timezone + fileprivate func normalizedWrappedDate() -> Date { + return wrappedDate.addingTimeInterval( + Double(timezone.secondsFromGMT(for: wrappedDate))) + } +} + +extension OpenAPIDateWithoutTime: JSONEncodable { + func encodeToJSON() -> Any { + return OpenISO8601DateFormatter.withoutTime.string(from: self.normalizedWrappedDate()) + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/OpenISO8601DateFormatter.mustache b/modules/openapi-generator/src/main/resources/swift5/OpenISO8601DateFormatter.mustache index 29c28dac3f..dd451062fb 100644 --- a/modules/openapi-generator/src/main/resources/swift5/OpenISO8601DateFormatter.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/OpenISO8601DateFormatter.mustache @@ -18,6 +18,15 @@ import Foundation return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ import Foundation override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/modules/openapi-generator/src/main/resources/swift5/_param.mustache b/modules/openapi-generator/src/main/resources/swift5/_param.mustache index 770458343a..00b0c399c6 100644 --- a/modules/openapi-generator/src/main/resources/swift5/_param.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/_param.mustache @@ -1 +1 @@ -"{{baseName}}": {{paramName}}{{^required}}?{{/required}}.encodeToJSON() \ No newline at end of file +"{{baseName}}": {{#isQueryParam}}(wrappedValue: {{/isQueryParam}}{{paramName}}{{^required}}?{{/required}}.encodeToJSON(){{#isQueryParam}}, isExplode: {{isExplode}}){{/isQueryParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/api.mustache b/modules/openapi-generator/src/main/resources/swift5/api.mustache index a35ea0cc68..8ae155fc07 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api.mustache @@ -211,7 +211,8 @@ extension {{projectName}}API { {{/isDeprecated}} @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) async throws{{#returnType}} -> {{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{/returnType}} { - var requestTask: RequestTask? + let requestBuilder = {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -220,7 +221,7 @@ extension {{projectName}}API { return } - requestTask = {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute { result in + requestBuilder.execute { result in switch result { {{#returnType}} case let .success(response): @@ -235,8 +236,8 @@ extension {{projectName}}API { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } {{/useAsyncAwait}} @@ -466,7 +467,7 @@ extension {{projectName}}API { let localVariableRequestBuilder: RequestBuilder<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.{{#returnType}}getBuilder(){{/returnType}}{{^returnType}}getNonDecodableBuilder(){{/returnType}} - return localVariableRequestBuilder.init(method: "{{httpMethod}}", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "{{httpMethod}}", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: {{#hasAuthMethods}}true{{/hasAuthMethods}}{{^hasAuthMethods}}false{{/hasAuthMethods}}) } {{/useVapor}} {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache index 00cd597670..dd936dd68f 100644 --- a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache @@ -21,8 +21,8 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { private var managerStore = SynchronizedDictionary() {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class AlamofireRequestBuilder: RequestBuilder { - required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -103,21 +103,25 @@ private var managerStore = SynchronizedDictionary() let upload = manager.upload(multipartFormData: { mpForm in for (k, v) in self.parameters! { - switch v { - case let fileURL as URL: - if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { - mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } else { - mpForm.append(fileURL, withName: k) + for v in (v as? Array ?? [v]) { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } else { + mpForm.append(fileURL, withName: k) + } + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + case let data as Data: + mpForm.append(data, withName: k) + case let uuid as UUID: + mpForm.append(uuid.uuidString.data(using: String.Encoding.utf8)!, withName: k) + default: + fatalError("Unprocessable value \(v) with key \(k)") } - case let string as String: - mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) - case let number as NSNumber: - mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) - case let data as Data: - mpForm.append(data, withName: k) - default: - fatalError("Unprocessable value \(v) with key \(k)") } } }, to: URLString, method: xMethod, headers: nil) @@ -161,11 +165,13 @@ private var managerStore = SynchronizedDictionary() managerStore[managerId] = nil } - let validatedRequest = request.validate() + let validatedRequest = request.validate(statusCode: Configuration.successfulStatusCodeRange) switch T.self { case is Void.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { voidResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { voidResponse in cleanupRequest() switch voidResponse.result { @@ -253,11 +259,13 @@ private var managerStore = SynchronizedDictionary() managerStore[managerId] = nil } - let validatedRequest = request.validate() + let validatedRequest = request.validate(statusCode: Configuration.successfulStatusCodeRange) switch T.self { case is String.Type: - validatedRequest.responseString(queue: apiResponseQueue, completionHandler: { stringResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.stringResponseSerializer, + completionHandler: { stringResponse in cleanupRequest() switch stringResponse.result { @@ -269,7 +277,9 @@ private var managerStore = SynchronizedDictionary() }) case is URL.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { dataResponse in cleanupRequest() do { @@ -315,7 +325,9 @@ private var managerStore = SynchronizedDictionary() return }) case is Void.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { voidResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { voidResponse in cleanupRequest() switch voidResponse.result { @@ -327,7 +339,9 @@ private var managerStore = SynchronizedDictionary() }) case is Data.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { dataResponse in cleanupRequest() switch dataResponse.result { @@ -339,7 +353,9 @@ private var managerStore = SynchronizedDictionary() }) default: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { dataResponse in cleanupRequest() if case let .failure(error) = dataResponse.result { diff --git a/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache b/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache index 3734bf5e43..7fe17f29a5 100644 --- a/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache @@ -55,8 +55,8 @@ private var credentialStore = SynchronizedDictionary() @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ private var credentialStore = SynchronizedDictionary() default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/modules/openapi-generator/src/main/resources/swift5/swiftformat.mustache b/modules/openapi-generator/src/main/resources/swift5/swiftformat.mustache new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/swift5/swiftformat.mustache @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/README.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/README.mustache index 2a44a92c89..3a65b9117e 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/README.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/README.mustache @@ -201,3 +201,26 @@ import { environment } from '../environments/environment'; }) export class AppModule { } ``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache index 2ae3e11e0b..bd59162b7b 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache @@ -66,11 +66,15 @@ export class {{classname}} { public configuration = new {{configurationClassName}}(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: {{configurationClassName}}) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: {{configurationClassName}}) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -117,7 +121,11 @@ export class {{classname}} { if (typeof value === "object") { {{#isQueryParamObjectFormatJson}} - httpParams = httpParams.append(key, JSON.stringify(value)); + if (key != null) { + httpParams = httpParams.append(key, JSON.stringify(value)); + } else { + throw Error("key may not be null if value is a QueryParamObject"); + } {{/isQueryParamObjectFormatJson}} {{^isQueryParamObjectFormatJson}} if (Array.isArray(value)) { @@ -198,7 +206,7 @@ export class {{classname}} { {{/isCollectionFormatMulti}} {{^isCollectionFormatMulti}} localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']), '{{baseName}}'); + [...{{paramName}}].join(COLLECTION_FORMATS['{{collectionFormat}}']), '{{baseName}}'); {{/isCollectionFormatMulti}} {{/isQueryParamObjectFormatJson}} } @@ -216,7 +224,7 @@ export class {{classname}} { {{#headerParams}} {{#isArray}} if ({{paramName}}) { - localVarHeaders = localVarHeaders.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + localVarHeaders = localVarHeaders.set('{{baseName}}', [...{{paramName}}].join(COLLECTION_FORMATS['{{collectionFormat}}'])); } {{/isArray}} {{^isArray}} @@ -335,7 +343,7 @@ export class {{classname}} { localVarFormParams = localVarFormParams.append('{{baseName}}', element) as any || localVarFormParams; }) } else { - localVarFormParams = localVarFormParams.append('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])) as any || localVarFormParams; + localVarFormParams = localVarFormParams.append('{{baseName}}', [...{{paramName}}].join(COLLECTION_FORMATS['{{collectionFormat}}'])) as any || localVarFormParams; } {{/isCollectionFormatMulti}} } @@ -361,12 +369,20 @@ export class {{classname}} { } {{/isResponseFile}} - return this.httpClient.{{httpMethod}}{{^isResponseFile}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>{{/isResponseFile}}(`${this.configuration.basePath}{{{path}}}`,{{#isBodyAllowed}} - {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}{{#hasFormParams}}localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams{{/hasFormParams}}{{^hasFormParams}}null{{/hasFormParams}}{{/bodyParam}},{{/isBodyAllowed}} + let localVarPath = `{{{path}}}`; + return this.httpClient.request{{^isResponseFile}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>{{/isResponseFile}}('{{httpMethod}}', `${this.configuration.basePath}${localVarPath}`, { {{#httpContextInOptions}} context: localVarHttpContext, {{/httpContextInOptions}} + {{#bodyParam}} + body: {{paramName}}, + {{/bodyParam}} + {{^bodyParam}} + {{#hasFormParams}} + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + {{/hasFormParams}} + {{/bodyParam}} {{#hasQueryParamsOrAuth}} params: localVarQueryParameters, {{/hasQueryParamsOrAuth}} diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/configuration.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/configuration.mustache index 40aaec67f4..e73eeebf7b 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/configuration.mustache @@ -1,4 +1,5 @@ import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; export interface {{configurationParametersInterfaceName}} { /** @@ -13,7 +14,18 @@ export interface {{configurationParametersInterfaceName}} { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -35,7 +47,18 @@ export class {{configurationClassName}} { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -51,6 +74,12 @@ export class {{configurationClassName}} { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } if (configurationParameters.credentials) { this.credentials = configurationParameters.credentials; } @@ -157,4 +186,20 @@ export class {{configurationClassName}} { ? value() : value; } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/index.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/index.mustache index c312b70fa3..104dd3d21e 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/index.mustache @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/param.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/param.mustache new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-angular/param.mustache @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache index 1b9ad4ad45..921f3dc595 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache @@ -146,12 +146,16 @@ export const {{classname}}AxiosParamCreator = function (configuration?: Configur } {{/isArray}} {{^isArray}} - if ({{paramName}} !== undefined && {{paramName}} !== null) { + {{! `val == null` covers for both `null` and `undefined`}} + if ({{paramName}} != null) { {{#isString}} localVarHeaderParameter['{{baseName}}'] = String({{paramName}}); {{/isString}} {{^isString}} - localVarHeaderParameter['{{baseName}}'] = String(JSON.stringify({{paramName}})); + {{! isString is falsy also for $ref that defines a string or enum type}} + localVarHeaderParameter['{{baseName}}'] = typeof {{paramName}} === 'string' + ? {{paramName}} + : JSON.stringify({{paramName}}); {{/isString}} } {{/isArray}} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/common.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/common.mustache index 114bb3e92f..9a97e1c8e6 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/common.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/common.mustache @@ -75,24 +75,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/model.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/model.mustache index 46838a8a08..9e1e84422b 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/model.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/model.mustache @@ -2,8 +2,14 @@ /* eslint-disable */ {{>licenseInfo}} {{#withSeparateModelsAndApi}}{{#hasAllOf}}{{#allOf}} +// May contain unused imports in some cases +// @ts-ignore import { {{class}} } from './{{filename}}';{{/allOf}}{{/hasAllOf}}{{#hasOneOf}}{{#oneOf}} +// May contain unused imports in some cases +// @ts-ignore import { {{class}} } from './{{filename}}';{{/oneOf}}{{/hasOneOf}}{{^hasAllOf}}{{^hasOneOf}}{{#imports}} +// May contain unused imports in some cases +// @ts-ignore import { {{class}} } from './{{filename}}';{{/imports}}{{/hasOneOf}}{{/hasAllOf}}{{/withSeparateModelsAndApi}} {{#models}}{{#model}} {{#isEnum}}{{>modelEnum}}{{/isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#allOf}}{{#-first}}{{>modelAllOf}}{{/-first}}{{/allOf}}{{^isEnum}}{{^oneOf}}{{^allOf}}{{>modelGeneric}}{{/allOf}}{{/oneOf}}{{/isEnum}} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache index c4fc5b8cd4..1232bced6c 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache @@ -17,8 +17,12 @@ "license": "Unlicense", "main": "./dist/index.js", "typings": "./dist/index.d.ts", +{{#supportsES6}} + "module": "./dist/esm/index.js", + "sideEffects": false, +{{/supportsES6}} "scripts": { - "build": "tsc --outDir dist/", + "build": "tsc {{#supportsES6}}&& tsc -p tsconfig.esm.json{{/supportsES6}}", "prepare": "npm run build" }, "dependencies": { diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/tsconfig.esm.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/tsconfig.esm.mustache new file mode 100644 index 0000000000..2c0331cce0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-axios/tsconfig.esm.mustache @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "esnext", + "outDir": "dist/esm" + } +} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/tsconfig.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/tsconfig.mustache index bf5018dba8..d0ebbd47a6 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/tsconfig.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/tsconfig.mustache @@ -2,10 +2,13 @@ "compilerOptions": { "declaration": true, "target": "{{#supportsES6}}ES6{{/supportsES6}}{{^supportsES6}}ES5{{/supportsES6}}", - "module": "{{#supportsES6}}ES6{{/supportsES6}}{{^supportsES6}}CommonJS{{/supportsES6}}", + "module": "commonjs", "noImplicitAny": true, "outDir": "dist", "rootDir": ".", + {{#supportsES6}} + "moduleResolution": "node", + {{/supportsES6}} {{^supportsES6}} "lib": [ "es6", diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache index f494271ad6..24edd4d6ad 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache @@ -123,17 +123,17 @@ export class {{classname}} extends runtime.BaseAPI { {{/isArray}} {{^isArray}} if (requestParameters.{{paramName}} !== undefined) { - {{#isDateTime}} + {{#isDateTimeType}} queryParameters['{{baseName}}'] = (requestParameters.{{paramName}} as any).toISOString(); - {{/isDateTime}} - {{^isDateTime}} - {{#isDate}} + {{/isDateTimeType}} + {{^isDateTimeType}} + {{#isDateType}} queryParameters['{{baseName}}'] = (requestParameters.{{paramName}} as any).toISOString().substr(0,10); - {{/isDate}} - {{^isDate}} + {{/isDateType}} + {{^isDateType}} queryParameters['{{baseName}}'] = requestParameters.{{paramName}}; - {{/isDate}} - {{/isDateTime}} + {{/isDateType}} + {{/isDateTimeType}} } {{/isArray}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache index 9c6ebc44f3..1524de8b94 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache @@ -59,17 +59,17 @@ export function {{classname}}FromJSONTyped(json: any, ignoreDiscriminator: boole {{/additionalPropertiesType}} {{#vars}} {{#isPrimitiveType}} - {{#isDate}} + {{#isDateType}} '{{name}}': {{^required}}!exists(json, '{{baseName}}') ? undefined : {{/required}}({{#isNullable}}json['{{baseName}}'] === null ? null : {{/isNullable}}new Date(json['{{baseName}}'])), - {{/isDate}} - {{#isDateTime}} + {{/isDateType}} + {{#isDateTimeType}} '{{name}}': {{^required}}!exists(json, '{{baseName}}') ? undefined : {{/required}}({{#isNullable}}json['{{baseName}}'] === null ? null : {{/isNullable}}new Date(json['{{baseName}}'])), - {{/isDateTime}} - {{^isDate}} - {{^isDateTime}} + {{/isDateTimeType}} + {{^isDateType}} + {{^isDateTimeType}} '{{name}}': {{^required}}!exists(json, '{{baseName}}') ? undefined : {{/required}}json['{{baseName}}'], - {{/isDateTime}} - {{/isDate}} + {{/isDateTimeType}} + {{/isDateType}} {{/isPrimitiveType}} {{^isPrimitiveType}} {{#isArray}} @@ -118,7 +118,22 @@ export function {{classname}}ToJSON(value?: {{classname}} | null): any { {{#vars}} {{^isReadOnly}} {{#isPrimitiveType}} - '{{baseName}}': {{#isDate}}{{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}value.{{name}}.toISOString().substr(0,10)){{/isDate}}{{#isDateTime}}{{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}value.{{name}}.toISOString()){{/isDateTime}}{{^isDate}}{{^isDateTime}}value.{{name}}{{/isDateTime}}{{/isDate}}, + {{#isDateType}} + '{{baseName}}': {{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}value.{{name}}.toISOString().substr(0,10)), + {{/isDateType}} + {{#isDateTimeType}} + '{{baseName}}': {{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}value.{{name}}.toISOString()), + {{/isDateTimeType}} + {{#isArray}} + '{{baseName}}': {{#uniqueItems}}{{^required}}value.{{name}} === undefined ? undefined : {{/required}}{{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}Array.from(value.{{name}} as Set){{/uniqueItems}}{{^uniqueItems}}value.{{name}}{{/uniqueItems}}, + {{/isArray}} + {{^isDateType}} + {{^isDateTimeType}} + {{^isArray}} + '{{baseName}}': value.{{name}}, + {{/isArray}} + {{/isDateTimeType}} + {{/isDateType}} {{/isPrimitiveType}} {{^isPrimitiveType}} {{#isArray}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache index a72fe562f4..d47d980814 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache @@ -105,7 +105,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -182,7 +182,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -219,21 +223,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/modules/openapi-generator/src/main/resources/typescript-nestjs/README.mustache b/modules/openapi-generator/src/main/resources/typescript-nestjs/README.mustache index c3c32e9521..735f989033 100644 --- a/modules/openapi-generator/src/main/resources/typescript-nestjs/README.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-nestjs/README.mustache @@ -16,7 +16,7 @@ In your Nestjs project: ``` // without configuring providers import { ApiModule } from '{{npmName}}'; -import { HttpModule } from '@nestjs/common'; +import { HttpModule } from '@nestjs/{{#useAxiosHttpModule}}axios{{/useAxiosHttpModule}}{{^useAxiosHttpModule}}common{{/useAxiosHttpModule}}'; @Module({ imports: [ @@ -66,7 +66,7 @@ in order to avoid naming conflicts: ``` import { ApiModule } from 'my-api-path'; import { ApiModule as OtherApiModule } from 'my-other-api-path'; -import { HttpModule } from '@nestjs/common'; +import { HttpModule } from '@nestjs/{{#useAxiosHttpModule}}axios{{/useAxiosHttpModule}}{{^useAxiosHttpModule}}common{{/useAxiosHttpModule}}'; @Module({ imports: [ diff --git a/modules/openapi-generator/src/main/resources/typescript-nestjs/api.module.mustache b/modules/openapi-generator/src/main/resources/typescript-nestjs/api.module.mustache index 636f9ef25f..9cfdc25aec 100644 --- a/modules/openapi-generator/src/main/resources/typescript-nestjs/api.module.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-nestjs/api.module.mustache @@ -1,4 +1,10 @@ +{{#useAxiosHttpModule}} +import { DynamicModule, Module, Global } from '@nestjs/common'; +import { HttpModule, HttpService } from '@nestjs/axios'; +{{/useAxiosHttpModule}} +{{^useAxiosHttpModule}} import { DynamicModule, HttpService, HttpModule, Module, Global } from '@nestjs/common'; +{{/useAxiosHttpModule}} import { Configuration } from './configuration'; {{#apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/typescript-nestjs/api.service.mustache b/modules/openapi-generator/src/main/resources/typescript-nestjs/api.service.mustache index 1d3703f50d..066abea136 100644 --- a/modules/openapi-generator/src/main/resources/typescript-nestjs/api.service.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-nestjs/api.service.mustache @@ -1,7 +1,13 @@ {{>licenseInfo}} /* tslint:disable:no-unused-variable member-ordering */ +{{#useAxiosHttpModule}} +import { Inject, Injectable, Optional } from '@nestjs/common'; +import { HttpService } from '@nestjs/axios'; +{{/useAxiosHttpModule}} +{{^useAxiosHttpModule}} import { HttpService, Inject, Injectable, Optional } from '@nestjs/common'; +{{/useAxiosHttpModule}} import { AxiosResponse } from 'axios'; import { Observable } from 'rxjs'; {{#imports}} @@ -121,6 +127,9 @@ export class {{classname}} { {{/isKeyInHeader}} {{#isKeyInQuery}} + {{^hasQueryParams}} + let queryParameters = {}; + {{/hasQueryParams}} if (this.configuration.apiKeys["{{keyParamName}}"]) { queryParameters['{{keyParamName}}'] = this.configuration.apiKeys["{{keyParamName}}"]; } diff --git a/modules/openapi-generator/src/main/resources/typescript-rxjs/runtime.mustache b/modules/openapi-generator/src/main/resources/typescript-rxjs/runtime.mustache index c5f5edc6a0..e8a6eb9b8e 100644 --- a/modules/openapi-generator/src/main/resources/typescript-rxjs/runtime.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-rxjs/runtime.mustache @@ -131,7 +131,7 @@ export class BaseAPI { * export for not being a breaking change */ export class RequiredError extends Error { - name: 'RequiredError' = 'RequiredError'; + override name: 'RequiredError' = 'RequiredError'; } export const COLLECTION_FORMATS = { diff --git a/modules/openapi-generator/src/main/resources/typescript/api/api.mustache b/modules/openapi-generator/src/main/resources/typescript/api/api.mustache index a99424df3e..a28b911bd1 100644 --- a/modules/openapi-generator/src/main/resources/typescript/api/api.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/api/api.mustache @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi{{extensionForDeno}}'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi{{extensionForDeno}}'; import {Configuration} from '../configuration{{extensionForDeno}}'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http{{extensionForDeno}}'; {{#platforms}} @@ -18,7 +18,7 @@ import { injectable } from "inversify"; {{/useInversify}} {{#imports}} -import { {{classname}} } from '..{{filename}}{{extensionForDeno}}'; +import { {{classname}} } from '{{filename}}{{extensionForDeno}}'; {{/imports}} {{#operations}} diff --git a/modules/openapi-generator/src/main/resources/typescript/model/ObjectSerializer.mustache b/modules/openapi-generator/src/main/resources/typescript/model/ObjectSerializer.mustache index 2534008ab8..2109b58507 100644 --- a/modules/openapi-generator/src/main/resources/typescript/model/ObjectSerializer.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/model/ObjectSerializer.mustache @@ -1,12 +1,12 @@ {{#models}} {{#model}} -export * from './{{{ classFilename }}}{{extensionForDeno}}'; +export * from '{{{ importPath }}}{{extensionForDeno}}'; {{/model}} {{/models}} {{#models}} {{#model}} -import { {{classname}}{{#hasEnums}}{{#vars}}{{#isEnum}}, {{classname}}{{enumName}} {{/isEnum}} {{/vars}}{{/hasEnums}} } from './{{{ classFilename }}}{{extensionForDeno}}'; +import { {{classname}}{{#hasEnums}}{{#vars}}{{#isEnum}}, {{classname}}{{enumName}} {{/isEnum}} {{/vars}}{{/hasEnums}} } from '{{{ importPath }}}{{extensionForDeno}}'; {{/model}} {{/models}} @@ -244,6 +244,10 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } + if (mediaType === "text/plain") { + return rawData; + } + if (mediaType === "application/json") { return JSON.parse(rawData); } diff --git a/modules/openapi-generator/src/main/resources/typescript/model/model.mustache b/modules/openapi-generator/src/main/resources/typescript/model/model.mustache index e0e4f0bf39..f7a5d8aa68 100644 --- a/modules/openapi-generator/src/main/resources/typescript/model/model.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/model/model.mustache @@ -2,7 +2,7 @@ {{#models}} {{#model}} {{#tsImports}} -import { {{classname}} } from './{{filename}}{{extensionForDeno}}'; +import { {{classname}} } from '{{filename}}{{extensionForDeno}}'; {{/tsImports}} import { HttpFile } from '../http/http{{extensionForDeno}}'; diff --git a/modules/openapi-generator/src/main/resources/typescript/model/models_all.mustache b/modules/openapi-generator/src/main/resources/typescript/model/models_all.mustache index 43782db7ef..99adf56f71 100644 --- a/modules/openapi-generator/src/main/resources/typescript/model/models_all.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/model/models_all.mustache @@ -1,5 +1,5 @@ {{#models}} {{#model}} -export * from './{{{ classFilename }}}{{extensionForDeno}}' +export * from '{{{ importPath }}}{{extensionForDeno}}' {{/model}} {{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript/services/ObjectParamAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/services/ObjectParamAPI.mustache index e6aabfc122..860e2a0ff9 100644 --- a/modules/openapi-generator/src/main/resources/typescript/services/ObjectParamAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/services/ObjectParamAPI.mustache @@ -7,7 +7,7 @@ import type { Observable } from 'rxjs'; {{#models}} {{#model}} -import type { {{{ classname }}} } from '../models/{{{ classFilename }}}'; +import type { {{{ classname }}} } from '{{{ importPath }}}'; {{/model}} {{/models}} {{#apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/typescript/services/ObservableAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/services/ObservableAPI.mustache index 036d44dadf..336ec7aa2e 100644 --- a/modules/openapi-generator/src/main/resources/typescript/services/ObservableAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/services/ObservableAPI.mustache @@ -4,7 +4,7 @@ import type { Configuration } from "../configuration"; {{#models}} {{#model}} -import { {{{ classname }}} } from "../models/{{{ classFilename }}}"; +import { {{{ classname }}} } from "{{{ importPath }}}"; {{/model}} {{/models}} {{#apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/typescript/services/PromiseAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/services/PromiseAPI.mustache index e1455c52c8..1f6c1098ff 100644 --- a/modules/openapi-generator/src/main/resources/typescript/services/PromiseAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/services/PromiseAPI.mustache @@ -3,7 +3,7 @@ import type { Configuration } from "../configuration"; {{#models}} {{#model}} -import { {{{ classname }}} } from "../models/{{{ classFilename }}}"; +import { {{{ classname }}} } from "{{{ importPath }}}"; {{/model}} {{/models}} {{#apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/typescript/services/api.mustache b/modules/openapi-generator/src/main/resources/typescript/services/api.mustache index 1494e1f71e..24d254d74a 100644 --- a/modules/openapi-generator/src/main/resources/typescript/services/api.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/services/api.mustache @@ -2,7 +2,7 @@ import type { Configuration } from "../configuration"; import type { HttpFile, RequestContext, ResponseContext } from "../http/http"; {{#imports}} -import { {{classname}} } from "..{{filename}}"; +import { {{classname}} } from "{{filename}}"; {{/imports}} {{#operations}} diff --git a/modules/openapi-generator/src/main/resources/typescript/types/ObjectParamAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/types/ObjectParamAPI.mustache index 9a63903371..41969c178c 100644 --- a/modules/openapi-generator/src/main/resources/typescript/types/ObjectParamAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/types/ObjectParamAPI.mustache @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http{{extensionForDeno}}'; -import * as models from '../models/all{{extensionForDeno}}'; import { Configuration} from '../configuration{{extensionForDeno}}' {{#useRxJS}} import { Observable } from 'rxjs'; @@ -7,7 +6,7 @@ import { Observable } from 'rxjs'; {{#models}} {{#model}} -import { {{{ classname }}} } from '../models/{{{ classFilename }}}{{extensionForDeno}}'; +import { {{{ classname }}} } from '{{{ importPath }}}{{extensionForDeno}}'; {{/model}} {{/models}} {{#apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache index 80b41d3236..6016049375 100644 --- a/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http{{extensionForDeno}}'; -import * as models from '../models/all{{extensionForDeno}}'; import { Configuration} from '../configuration{{extensionForDeno}}' import { Observable, of, from } from {{#useRxJS}}'rxjs'{{/useRxJS}}{{^useRxJS}}'../rxjsStub{{extensionForDeno}}'{{/useRxJS}}; import {mergeMap, map} from {{#useRxJS}}'rxjs/operators'{{/useRxJS}}{{^useRxJS}}'../rxjsStub{{extensionForDeno}}'{{/useRxJS}}; @@ -9,7 +8,7 @@ import { AbstractConfiguration } from "../services/configuration{{extensionForDe {{/useInversify}} {{#models}} {{#model}} -import { {{{ classname }}} } from '../models/{{{ classFilename }}}{{extensionForDeno}}'; +import { {{{ classname }}} } from '{{{ importPath }}}{{extensionForDeno}}'; {{/model}} {{/models}} {{#apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache index 2c424db21f..058757c48d 100644 --- a/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http{{extensionForDeno}}'; -import * as models from '../models/all{{extensionForDeno}}'; import { Configuration} from '../configuration{{extensionForDeno}}' {{#useInversify}} import { injectable, inject, optional } from "inversify"; @@ -8,7 +7,7 @@ import { AbstractConfiguration } from "../services/configuration"; {{#models}} {{#model}} -import { {{{ classname }}} } from '../models/{{{ classFilename }}}{{extensionForDeno}}'; +import { {{{ classname }}} } from '{{{ importPath }}}{{extensionForDeno}}'; {{/model}} {{/models}} {{#apiInfo}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index ef0b59a12b..cfdc60aa0a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -268,7 +268,7 @@ public class DefaultCodegenTest { @Test public void testOriginalOpenApiDocumentVersion() { // Test with OAS 2.0 document. - String location = "src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml"; + String location = "src/test/resources/2_0/python-prior/petstore-with-fake-endpoints-models-for-testing.yaml"; OpenAPI openAPI = TestUtils.parseFlattenSpec(location); SemVer version = ModelUtils.getOpenApiVersion(openAPI, location, null); Assert.assertEquals(version, new SemVer("2.0.0")); @@ -4245,4 +4245,12 @@ public class DefaultCodegenTest { Assert.assertEquals(fooOptional.vars.get(0).name, "foo"); Assert.assertEquals(fooOptional.requiredVars.size(), 0); } + + @Test + public void testAssigning310SpecWorks() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_1/petstore.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.setOpenAPI(openAPI); + assertEquals(openAPI, codegen.openAPI); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/InlineModelResolverTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/InlineModelResolverTest.java index f3b2b4639e..6e4fa4f84f 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/InlineModelResolverTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/InlineModelResolverTest.java @@ -351,6 +351,19 @@ public class InlineModelResolverTest { assertTrue(user.getProperties().get("city") instanceof StringSchema); } + @Test + public void resolveRequestBodyInvalidRef() { + OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/inline_model_resolver.yaml"); + new InlineModelResolver().flatten(openAPI); + + RequestBody requestBodyReference = openAPI + .getPaths() + .get("/resolve_request_body_invalid_ref") + .getPost() + .getRequestBody(); + assertNull(requestBodyReference.getContent()); + } + @Test public void resolveInlineRequestBody() { OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/inline_model_resolver.yaml"); @@ -611,7 +624,7 @@ public class InlineModelResolverTest { Schema requestBodySchema = ModelUtils.getReferencedSchema(openAPI, mediaType.getSchema()); assertNotNull(requestBodySchema); assertEquals(1, requestBodySchema.getProperties().size(), 1); - assertTrue(requestBodySchema.getProperties().get("arbitrary_object_request_body_property") instanceof ObjectSchema); + assertTrue(requestBodySchema.getProperties().get("arbitrary_object_request_body_property") instanceof ObjectSchema); } @Test @@ -954,12 +967,12 @@ public class InlineModelResolverTest { .getContent() .get("application/json") .getSchema(); - //.getProperties() - //.get("nullable_request_body_property"); + //.getProperties() + //.get("nullable_request_body_property"); Schema nullableRequestBodySchema = ModelUtils.getReferencedSchema(openAPI, nullableRequestBodyReference); //assertEquals(nullableRequestBodySchema, ""); Schema nullableSchema = ModelUtils.getReferencedSchema(openAPI, - ((Schema)nullableRequestBodySchema.getProperties().get("nullable_request_body_property"))); + ((Schema) nullableRequestBodySchema.getProperties().get("nullable_request_body_property"))); assertTrue(nullableSchema.getNullable()); } @@ -1047,7 +1060,7 @@ public class InlineModelResolverTest { requestBodyReference.getContent().get("application/json").getSchema().get$ref()); //assertEquals("#/components/schemas/resolveInlineRequestBodyAllOf_request", requestBodyReference.get$ref()); - ComposedSchema allOfModel =(ComposedSchema) openAPI.getComponents().getSchemas().get("resolveInlineRequestBodyAllOf_request"); + ComposedSchema allOfModel = (ComposedSchema) openAPI.getComponents().getSchemas().get("resolveInlineRequestBodyAllOf_request"); assertEquals("#/components/schemas/resolveInlineRequestBody_request", allOfModel.getAllOf().get(0).get$ref()); //Schema allOfModel = ModelUtils.getReferencedSchema(openAPI, requestBodyReference.get$ref()); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/TestUtils.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/TestUtils.java index 9b53ebe626..d2aaa6592a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/TestUtils.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/TestUtils.java @@ -244,6 +244,16 @@ public class TestUtils { } } + public static void assertFileExists(Path path) { + try { + new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + // File exists, pass. + assertTrue(true); + } catch (IOException e) { + fail("File does not exist when it should: " + path); + } + } + public static void assertExtraAnnotationFiles(String baseOutputPath) { JavaFileAssert.assertThat(java.nio.file.Paths.get(baseOutputPath + "/EmployeeEntity.java")) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/confluencewiki/ConfluenceWikiTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/confluencewiki/ConfluenceWikiTest.java index 5352c9aa0f..5d2dbff557 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/confluencewiki/ConfluenceWikiTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/confluencewiki/ConfluenceWikiTest.java @@ -147,8 +147,8 @@ public class ConfluenceWikiTest { discriminator.setPropertyName("model_type"); parentModel.setDiscriminator(discriminator); - final ComposedSchema composedSchema = new ComposedSchema() - .addAllOfItem(new Schema().$ref(parentModel.getName())); + final ComposedSchema composedSchema = new ComposedSchema(); + composedSchema.addAllOfItem(new Schema().$ref(parentModel.getName())); composedSchema.setName("sample"); final ConfluenceWikiCodegen codegen = new ConfluenceWikiCodegen(); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/cpprestbed/CppRestbedServerTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/cpprestbed/CppRestbedServerTest.java new file mode 100644 index 0000000000..cb47b78b87 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/cpprestbed/CppRestbedServerTest.java @@ -0,0 +1,71 @@ +package org.openapitools.codegen.cpprestbed; + +import org.jetbrains.annotations.NotNull; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.languages.CppRestbedServerCodegen; +import org.openapitools.codegen.model.OperationMap; +import org.openapitools.codegen.model.OperationsMap; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CppRestbedServerTest { + + @DataProvider(name = "providedPaths") + public Object[][] providedPaths() { + Object[][] data = new Object[3][2]; + data[0][0] = "/abc/{id}"; + data[0][1] = "/abc/{id: .*}"; + + data[1][0] = "/{Foo}/"; + data[1][1] = "/{Foo: .*}/"; + + data[2][0] = "xyz/"; + data[2][1] = "xyz/"; + + return data; + } + + @Test(dataProvider = "providedPaths") + void testPathProcessing(String providedPath, String expectedPath) { + // Arrange + CppRestbedServerCodegen codegen = new CppRestbedServerCodegen(); + OperationsMap objs = setupOperationWithPath(providedPath); + + // Act + OperationsMap processedObjs = codegen.postProcessOperationsWithModels(objs, new ArrayList<>()); + + // Assert + List processedObjsOperationList = extractOperationsList(processedObjs); + + Assert.assertEquals(processedObjsOperationList.size(), 1); + Assert.assertEquals(processedObjsOperationList.get(0).path, expectedPath); + } + + private static List extractOperationsList(Map processedObjs) { + Map processedOperations = (Map) processedObjs.get("operations"); + List processedObjsOperationList = (List) processedOperations.get("operation"); + return processedObjsOperationList; + } + + @NotNull + private static OperationsMap setupOperationWithPath(String path) { + CodegenOperation op = new CodegenOperation(); + op.path = path; + + List operationsList = new ArrayList<>(); + operationsList.add(op); + + OperationMap operations = new OperationMap(); + operations.put("operation", operationsList); + + OperationsMap objs = new OperationsMap(); + objs.put("operations", operations); + return objs; + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java index dcbbdae0d1..894a105fb4 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java @@ -202,4 +202,24 @@ public class GoClientCodegenTest { TestUtils.assertFileContains(Paths.get(output + "/api_pet.go"), "type PetApiAddPetRequest struct"); } + + @Test + public void verifyTestFile() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("go") + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + files.forEach(File::deleteOnExit); + + TestUtils.assertFileExists(Paths.get(output + "/test/api_pet_test.go")); + TestUtils.assertFileContains(Paths.get(output + "/test/api_pet_test.go"), + "func Test_openapi_PetApiService(t *testing.T) {"); + } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java index 64b6c1cf38..11956bdec1 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java @@ -55,6 +55,14 @@ public class AbstractJavaCodegenTest { Assert.assertEquals(fakeJavaCodegen.toEnumVarName("_,.", "String"), "__"); } + /** + * As of Java 9, '_' is a keyword, and may not be used as an identifier. + */ + @Test + public void toEnumVarNameShouldNotResultInSingleUnderscore() throws Exception { + Assert.assertEquals(fakeJavaCodegen.toEnumVarName(" ", "String"), "SPACE"); + } + @Test public void toVarNameShouldAvoidOverloadingGetClassMethod() throws Exception { Assert.assertEquals(fakeJavaCodegen.toVarName("class"), "propertyClass"); @@ -847,6 +855,20 @@ public class AbstractJavaCodegenTest { Assert.assertEquals(fakeJavaCodegen.getTestFolder(), "src/test/java"); } + @Test + public void testOneOfModelImports() throws Exception { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/oneOf_nonPrimitive.yaml"); + final P_AbstractJavaCodegen codegen = new P_AbstractJavaCodegen(); + codegen.preprocessOpenAPI(openAPI); + + Schema schema = openAPI.getComponents().getSchemas().get("Example"); + CodegenModel cm = codegen.fromModel("Example", schema); + Assert.assertEquals(cm.imports.size(), 3); + Assert.assertTrue(cm.imports.contains("BigDecimal")); + Assert.assertTrue(cm.imports.contains("Date")); + Assert.assertTrue(cm.imports.contains("UUID")); + } + private static Schema createObjectSchemaWithMinItems() { return new ObjectSchema() .addProperties("id", new IntegerSchema().format("int32")) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java index 06f5aadc9f..e4b4fc94da 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -1573,6 +1573,38 @@ public class JavaClientCodegenTest { ); } + @Test + public void testRestTemplateResponseTypeWithUseAbstractionForFiles() throws IOException { + + Map properties = new HashMap<>(); + properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); + properties.put(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true); + + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setAdditionalProperties(properties) + .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + files.forEach(File::deleteOnExit); + + validateJavaSourceFiles(files); + + Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/ResourceApi.java"); + TestUtils.assertFileContains(defaultApi, + "org.springframework.core.io.Resource resourceInResponse()", + "ResponseEntity resourceInResponseWithHttpInfo()", + "ParameterizedTypeReference localReturnType = new ParameterizedTypeReference()" + ); + } + public void testExtraAnnotations(String library) throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java index eb263d3530..1f3f48e8a6 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java @@ -146,8 +146,8 @@ public class JavaModelEnumTest { discriminator.setPropertyName("model_type"); parentModel.setDiscriminator(discriminator); - final ComposedSchema composedSchema = new ComposedSchema() - .addAllOfItem(new Schema().$ref(parentModel.getName())); + final ComposedSchema composedSchema = new ComposedSchema(); + composedSchema.addAllOfItem(new Schema().$ref(parentModel.getName())); composedSchema.setName("sample"); final JavaClientCodegen codegen = new JavaClientCodegen(); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java index 67e45f82a5..45189c9de5 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java @@ -432,7 +432,7 @@ public class JavaModelTest { Assert.assertEquals(property.containerType, "set"); Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); - Assert.assertTrue(property.getUniqueItems()); + Assert.assertTrue(property.getUniqueItemsBoolean()); } @Test(description = "convert a model with an array property with item name") public void arrayModelWithItemNameTest() { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonCommonCodegenPackagePrefixTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonCommonCodegenPackagePrefixTest.java new file mode 100644 index 0000000000..d55c062f7e --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonCommonCodegenPackagePrefixTest.java @@ -0,0 +1,207 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates. + * + * 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 + * + * http://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.java.helidon; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class JavaHelidonCommonCodegenPackagePrefixTest { + + private static final String INPUT_FILE = "src/test/resources/3_0/helidon/petstore-for-testing.yaml"; + private static final String PACKAGE_PREFIX_KEY = "rootJavaEEPackage"; + private static final String HELIDON_VERSION_KEY = "helidonVersion"; + + private static final String EXCEPTION_MESSAGE_FRAGMENT = "namespace but options specified"; + + // The generated SE client does not depend on the jakarta/javax imports, so no need to test it. + private static final List> GENERATOR_LIBRARY_PAIRS = new ArrayList>() { + { + add(listOf("java-helidon-client", "mp")); + add(listOf("java-helidon-server", "se")); + add(listOf("java-helidon-server", "mp")); + } + }; + + private String outputDir; + + @BeforeMethod + public void setup() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + outputDir = output.getAbsolutePath().replace('\\', '/'); + } + + @Test(dataProvider = "valid") + public void checkValidCombinations(String explicitHelidonVersion, + String explicitPrefix, + String expectedPrefix, + String generatorName, + String libraryName) { + List files = runTest(explicitHelidonVersion, explicitPrefix, generatorName, libraryName); + checkFileForPackagePrefix(files, generatorName, libraryName, expectedPrefix); + } + + @Test(dataProvider = "invalid") + public void checkInvalidCombinations(String explicitHelidonVersion, + String explicitPrefix, + String generatorName, + String libraryName) { + IllegalArgumentException e = Assert.assertThrows(IllegalArgumentException.class, + () -> runTest(explicitHelidonVersion, explicitPrefix, generatorName, libraryName)); + Assert.assertTrue("Exception message '" + e.getMessage() + "' contains '" + EXCEPTION_MESSAGE_FRAGMENT + "'", + e.getMessage().contains(EXCEPTION_MESSAGE_FRAGMENT)); + } + + @DataProvider(name = "valid") + public Object [][] createValidData() { + Object [][] settingsForEachRun = new Object[][] { + {null, null, "jakarta"}, + {"3.0.1", null, "jakarta"}, + {"2.5.3", null, "javax"}, + {null, "jakarta", "jakarta"}, + {"3.0.1", "jakarta", "jakarta"}, + {"2.5.3", "javax", "javax"} + }; + + return prepareTestData(settingsForEachRun); + } + + @DataProvider(name = "invalid") + public Object [][] createInvalidData() { + Object [][] settingsForEachRun = new Object[][] { + {"2.5.3", "jakarta"}, + {null, "javax"}, + {"3.0.1", "javax"} + }; + + return prepareTestData(settingsForEachRun); + } + + /** + * Creates test data for each tested generator/library pair for all the version/prefix settings. + * + * @param settingsForEachRun version/prefix settings to test + * @return test data for driving a test method + */ + private Object[][] prepareTestData(Object[][] settingsForEachRun) { + Object [][] result = new Object[GENERATOR_LIBRARY_PAIRS.size() * settingsForEachRun.length][]; + int resultSlot = 0; + + int settingsLength = settingsForEachRun[0].length; + for (List generatorLibraryPair : GENERATOR_LIBRARY_PAIRS) { + for (Object[] settings : settingsForEachRun) { + result[resultSlot] = Arrays.copyOf(settings, settingsLength + 2); + result[resultSlot][settingsLength] = generatorLibraryPair.get(0); // generator + result[resultSlot][settingsLength + 1] = generatorLibraryPair.get(1); // library + resultSlot++; + } + } + return result; + } + + private static List listOf(String... values) { + return new ArrayList<>(Arrays.asList(values)); + } + + private List runTest(String explicitHelidonVersion, + String explicitPackagePrefix, + String generatorName, + String libraryName) { + Map additionalProperties = new HashMap<>(); + CodegenConfigurator clientConfigurator = new CodegenConfigurator() + .setGeneratorName(generatorName) + .setLibrary(libraryName) + .setInputSpec(INPUT_FILE) + .setOutputDir(outputDir); + + if (explicitHelidonVersion != null) { + additionalProperties.put(HELIDON_VERSION_KEY, explicitHelidonVersion); + } + if (explicitPackagePrefix != null) { + additionalProperties.put(PACKAGE_PREFIX_KEY, explicitPackagePrefix); + } + + // Use JSON-B for serialization to force jakarta or json imports into the generated POJOs. + additionalProperties.put(CodegenConstants.SERIALIZATION_LIBRARY, "jsonb"); + + clientConfigurator.setAdditionalProperties(additionalProperties); + + DefaultGenerator generator = new DefaultGenerator(); + generator.opts(clientConfigurator.toClientOptInput()); + + return generator.generate(); + } + + private void checkFileForPackagePrefix(List files, + String generatorName, + String libraryName, + String expectedPrefix) { + // The SE client does not use the rootJavaEEPackage so we don't check any file in that case. + if (generatorName.equals("java-helidon-client") && libraryName.equals("se")) { + return; + } + + // The MP client and server generator create PetAPI containing a wildcard include. + if (libraryName.equals("mp")) { + TestUtils.ensureContainsFile(files, Paths.get(outputDir).toFile(), generatedFilePath(generatorName, libraryName)); + TestUtils.assertFileContains(Paths.get(outputDir + "/" + generatedFilePath(generatorName, libraryName)), + "import " + expectedPrefix + ".ws.rs.*;"); + return; + } + + // The SE server generates 'import {{rootJavaEEPackage}}.json.stream.JsonParser;' in POJOs for JSON-B seriolization. + TestUtils.ensureContainsFile(files, Paths.get(outputDir).toFile(), generatedFilePath(generatorName, libraryName)); + TestUtils.assertFileContains(Paths.get(outputDir + "/" + generatedFilePath(generatorName, libraryName)), + "import " + expectedPrefix + ".json.stream.JsonParser;"); + } + + private String generatedFilePath(String generatorName, String libraryName) { + // The path to the file depends on client or server. + String serverOrClient = (generatorName.contains("server") ? "server" : "client"); + + // The file to check depends on the generator: e.g., PetApi for client, PetService for server. + String apiFileNameSuffix = (generatorName.contains("server") ? "Service" : "Api"); + + // For MP, check api/PetApi or api/PetService; for SE check model/Pet.java. + String filePath = (libraryName.equals("mp") + ? "api/Pet" + apiFileNameSuffix + : "model/Pet") + + ".java"; + + return "src/main/java/org/openapitools/" + + serverOrClient + + "/" + + filePath; + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonCommonCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonCommonCodegenTest.java new file mode 100644 index 0000000000..c92b404c09 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonCommonCodegenTest.java @@ -0,0 +1,106 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.junit.Assert; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class JavaHelidonCommonCodegenTest { + + private DefaultGenerator generator; + private CodegenConfigurator configurator; + private String outputDir; + + @BeforeMethod + public void setup() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + outputDir = output.getAbsolutePath().replace('\\', '/'); + + configurator = new CodegenConfigurator() + .setGeneratorName("java-helidon-server") + .setLibrary("mp") + .setInputSpec("src/test/resources/3_0/helidon/petstore-for-testing.yaml") + .setOutputDir(outputDir); + + generator = new DefaultGenerator(); + } + + @Test + public void defaultVersionTest() { + runVersionTest(null, null); + } + + @Test + public void customHelidonVersionOnlyTest() { + runVersionTest("3.0.0", null); + } + + @Test + public void customParentVersionOnlyTest() { + runVersionTest(null, "3.0.0"); + } + + @Test + public void bothEqualsVersionTest() { + runVersionTest("3.0.0", "3.0.0"); + } + + @Test + public void bothNotEqualsVersionTest() { + IllegalArgumentException e = Assert.assertThrows(IllegalArgumentException.class,() -> runVersionTest("1.0.0", "2.0.0")); + Assert.assertEquals( + "Both parentVersion and helidonVersion properties were set with different value.", + e.getMessage()); + } + + private void runVersionTest(String helidonVersion, String parentVersion) { + Map additionalProperties = new HashMap<>(); + String expected = "3.0.1"; + if (parentVersion != null) { + additionalProperties.put(CodegenConstants.PARENT_VERSION, parentVersion); + expected = parentVersion; + } + if (helidonVersion != null) { + additionalProperties.put("helidonVersion", helidonVersion); + expected = helidonVersion; + } + generator.opts(configurator.setAdditionalProperties(additionalProperties) + .toClientOptInput()); + List files = generator.generate(); + + TestUtils.ensureContainsFile(files, Paths.get(outputDir).toFile(), "pom.xml"); + TestUtils.assertFileContains(Paths.get(outputDir + "/pom.xml"), + String.format(Locale.ROOT, "%s", expected)); + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonMpClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonMpClientCodegenTest.java new file mode 100644 index 0000000000..3cecbf9b60 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonMpClientCodegenTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static org.openapitools.codegen.java.assertions.JavaFileAssert.assertThat; + +public class JavaHelidonMpClientCodegenTest { + + private String outputPath; + private List generatedFiles; + + @BeforeClass + public void setup() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + outputPath = output.getAbsolutePath().replace('\\', '/'); + + System.out.println("Generating java-helidon-client MP project in " + outputPath); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java-helidon-client") + .setLibrary("mp") + .setInputSpec("src/test/resources/3_0/helidon/petstore-no-multipart-for-testing.yaml") + .setOutputDir(outputPath); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + generator.opts(clientOptInput); + generatedFiles = generator.generate(); + } + + @Test + public void testPom() { + TestUtils.ensureContainsFile(generatedFiles, new File(outputPath), "pom.xml"); + } + + @Test + public void testPetApi() { + assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/client/api/PetApi.java")) + .assertMethod("addPet", "Pet") + .toFileAssert() + .assertMethod("deletePet", "Long", "String", "Long", "String", "Integer", + "List", "List") + .toFileAssert() + .assertMethod("findPetsByStatus", "List") + .toFileAssert() + .assertMethod("findPetsByTags", "List") + .toFileAssert() + .assertMethod("getPetById", "Long") + .toFileAssert() + .assertMethod("updatePet", "Pet") + .toFileAssert() + .assertMethod("updatePetWithForm", "Long", "String", "String") + .toFileAssert(); + } + + @Test + public void testStoreApi() { + assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/client/api/StoreApi.java")) + .assertMethod("deleteOrder", "String") + .toFileAssert() + .assertMethod("getInventory") + .toFileAssert() + .assertMethod("getOrderById", "BigDecimal") + .toFileAssert() + .assertMethod("placeOrder", "Order") + .toFileAssert(); + } + + @Test + public void testUserApi() { + assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/client/api/UserApi.java")) + .assertMethod("createUser", "User") + .toFileAssert() + .assertMethod("createUsersWithArrayInput", "List") + .toFileAssert() + .assertMethod("createUsersWithListInput", "List") + .toFileAssert() + .assertMethod("getUserByName", "String") + .toFileAssert() + .assertMethod("loginUser", "String", "String", "String", "Long", "BigDecimal") + .toFileAssert() + .assertMethod("updateUser", "String", "User") + .toFileAssert(); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonMpServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonMpServerCodegenTest.java new file mode 100644 index 0000000000..312d2f9d85 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonMpServerCodegenTest.java @@ -0,0 +1,252 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon; + +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.openapitools.codegen.java.assertions.JavaFileAssert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import static org.openapitools.codegen.CodegenConstants.SERIALIZATION_LIBRARY; + +public class JavaHelidonMpServerCodegenTest { + + private DefaultGenerator generator; + private String outputPath; + private String apiPackage; + private String modelPackage; + + @BeforeMethod + public void setup() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + outputPath = output.getAbsolutePath().replace('\\', '/'); + apiPackage = outputPath + "/src/main/java/org/openapitools/server/api"; + modelPackage = outputPath + "/src/main/java/org/openapitools/server/model"; + generator = new DefaultGenerator(); + } + + private CodegenConfigurator createConfigurator() { + return new CodegenConfigurator() + .setGeneratorName("java-helidon-server") + .setLibrary("mp") + .setInputSpec("src/test/resources/3_0/helidon/petstore-for-testing.yaml") + .setOutputDir(outputPath); + } + + private void generate(CodegenConfigurator config) { + generator.opts(config.toClientOptInput()); + generator.setGenerateMetadata(false); + generator.generate(); + } + + private void generate() { + generate(createConfigurator()); + } + + @Test + public void testRestApiFilesOnly() { + generate(createConfigurator().addAdditionalProperty("fullProject", "false")); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetService.java")) + .fileContains("public interface PetService"); + + File outputFile = Paths.get(outputPath).toFile(); + assertThat(Objects.requireNonNull(outputFile.listFiles()).length, is(1)); + } + + @Test + public void testJackson() { + generate(createConfigurator().addAdditionalProperty(SERIALIZATION_LIBRARY, "jackson")); + + JavaFileAssert.assertThat(Paths.get(modelPackage + "/Color.java")) + .fileContains("com.fasterxml.jackson.annotation.JsonCreator") + .fileContains("com.fasterxml.jackson.annotation.JsonValue"); + } + + @Test + public void testJsonb() { + generate(createConfigurator().addAdditionalProperty(SERIALIZATION_LIBRARY, "jsonb")); + + JavaFileAssert.assertThat(Paths.get(modelPackage + "/Color.java")) + .fileContains(".json.bind.annotation.JsonbCreator"); + } + + @Test + public void testAbstractClass() { + generate(createConfigurator().addAdditionalProperty("useAbstractClass", "true")); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetService.java")) + .fileContains("public abstract class PetService") + .assertMethod("addPet", "Pet") + .doesNotHaveImplementation(); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/StoreService.java")) + .fileContains("public abstract class StoreService") + .assertMethod("placeOrder", "Order") + .doesNotHaveImplementation() + .hasReturnType("Order"); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/StoreServiceImpl.java")) + .fileContains("public class StoreServiceImpl extends StoreService") + .assertMethod("placeOrder", "Order") + .hasReturnType("Order") + .bodyContainsLines("Order result = null; // Replace with correct business logic.", "return result;"); + } + + @Test + public void testFullProject() { + generate(createConfigurator().addAdditionalProperty("fullProject", "true")); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetService.java")) + .fileContains("public interface PetService") + .assertMethod("addPet", "Pet"); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/StoreService.java")) + .fileContains("public interface StoreService") + .assertMethod("placeOrder", "Order") + .hasReturnType("Order"); + } + + @Test + public void validatePetApi() { + generate(); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetService.java")) + .fileContains("org.openapitools.server.model.Pet") + .assertMethod("addPet", "Pet") + .toFileAssert() + .assertMethod("addPets", "String", "InputStream", "InputStream", "List", "List", "Integer") + .toFileAssert() + .assertMethod("deletePet", "Long", "String", "Long", "String", "Integer", "List", "List") + .toFileAssert() + .assertMethod("findPetsByStatus", "List") + .toFileAssert() + .assertMethod("findPetsByTags", "List") + .toFileAssert() + .assertMethod("getPetById", "Long") + .toFileAssert() + .assertMethod("updatePet", "Pet") + .toFileAssert() + .assertMethod("updatePetWithForm", "Long", "String", "String") + .toFileAssert() + .assertMethod("uploadFile", "Long", "Long", "String", "InputStream"); + } + + @Test + public void validateStoreApi() { + generate(); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/StoreService.java")) + .fileContains("org.openapitools.server.model.Order") + .assertMethod("deleteOrder", "String") + .toFileAssert() + .assertMethod("getInventory") + .toFileAssert() + .assertMethod("getOrderById", "BigDecimal") + .toFileAssert() + .assertMethod("placeOrder", "Order"); + } + + @Test + public void validateUserApi() { + generate(); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/UserService.java")) + .fileContains("org.openapitools.server.model.User") + .assertMethod("createUser", "User") + .toFileAssert() + .assertMethod("createUsersWithArrayInput", "List") + .toFileAssert() + .assertMethod("createUsersWithListInput", "List") + .toFileAssert() + .assertMethod("deleteUser", "String") + .toFileAssert() + .assertMethod("getUserByName", "String") + .toFileAssert() + .assertMethod("loginUser", "String", "String", "String", "Long", "BigDecimal") + .toFileAssert() + .assertMethod("logoutUser") + .toFileAssert() + .assertMethod("updateUser", "String", "User"); + } + + @Test + public void testGenerateGradleProject() { + generate(createConfigurator().addAdditionalProperty("gradleProject", "true")); + + assertThat(Paths.get(outputPath + "/build.gradle").toFile().exists(), is(true)); + assertThat(Paths.get(outputPath + "/settings.gradle").toFile().exists(), is(true)); + TestUtils.assertFileNotExists(Paths.get(outputPath + "/pom.xml")); + } + + @Test + public void testReturnResponse() { + generate(createConfigurator().addAdditionalProperty("returnResponse", "true")); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetService.java")) + .fileContains("public interface PetService") + .assertMethod("addPet", "Pet") + .hasReturnType("Response"); + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetService.java")) + .fileContains("public interface PetService") + .assertMethod("deletePet", "Long", "String", "Long", "String", "Integer", "List", "List") + .hasReturnType("Response"); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetServiceImpl.java")) + .fileContains("public class PetServiceImpl implements PetService") + .assertMethod("addPet", "Pet") + .hasReturnType("Response") + .bodyContainsLines("return Response.ok(/* Pass Pet entity payload */).build(); " + + "// Replace with correct business logic."); + } + + @Test + public void testSupportAsync() { + generate(createConfigurator().addAdditionalProperty("supportAsync", "true")); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetService.java")) + .fileContains("public interface PetService") + .assertMethod("addPet", "Pet") + .hasReturnType("CompletionStage"); + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetService.java")) + .fileContains("public interface PetService") + .assertMethod("deletePet", "Long", "String", "Long", "String", "Integer", "List", "List") + .hasReturnType("CompletionStage"); + + JavaFileAssert.assertThat(Paths.get(apiPackage + "/PetServiceImpl.java")) + .fileContains("public class PetServiceImpl implements PetService") + .assertMethod("addPet", "Pet") + .hasReturnType("CompletionStage") + .bodyContainsLines("Pet result = null; // Replace with correct business logic.", + "return CompletableFuture.supplyAsync(() -> result);"); + } + +} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonSeClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonSeClientCodegenTest.java new file mode 100644 index 0000000000..61e49d79f8 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonSeClientCodegenTest.java @@ -0,0 +1,122 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon; + +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +import static org.openapitools.codegen.java.assertions.JavaFileAssert.assertThat; + +public class JavaHelidonSeClientCodegenTest { + + private String outputPath; + private List generatedFiles; + + @BeforeClass + public void setup() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + outputPath = output.getAbsolutePath().replace('\\', '/'); + + System.out.println("Generating java-helidon-client SE project in " + outputPath); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java-helidon-client") + .setLibrary("se") + .setInputSpec("src/test/resources/3_0/helidon/petstore-no-multipart-for-testing.yaml") + .setOutputDir(outputPath); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + generator.opts(clientOptInput); + generatedFiles = generator.generate(); + } + + @DataProvider(name = "fileSuffix") + public Object[][] fileSuffixes() { + return new Object[][] { + {""}, + {"Impl"} + }; + } + + @Test + public void testPom() { + TestUtils.ensureContainsFile(generatedFiles, new File(outputPath), "pom.xml"); + } + + @Test(dataProvider = "fileSuffix") + public void testPetApi(String fileSuffix) { + assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/client/api/PetApi" + fileSuffix + ".java")) + .assertMethod("addPet", "Pet") + .toFileAssert() + .assertMethod("deletePet", "Long", "String", "Long", "String", "Integer", + "List", "List") + .toFileAssert() + .assertMethod("findPetsByStatus", "List") + .toFileAssert() + .assertMethod("findPetsByTags", "List") + .toFileAssert() + .assertMethod("getPetById", "Long") + .toFileAssert() + .assertMethod("updatePet", "Pet") + .toFileAssert() + .assertMethod("updatePetWithForm", "Long", "String", "String") + .toFileAssert(); + } + + @Test(dataProvider = "fileSuffix") + public void testStoreApi(String fileSuffix) { + assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/client/api/StoreApi" + fileSuffix + ".java")) + .assertMethod("deleteOrder", "String") + .toFileAssert() + .assertMethod("getInventory") + .toFileAssert() + .assertMethod("getOrderById", "BigDecimal") + .toFileAssert() + .assertMethod("placeOrder", "Order") + .toFileAssert(); + } + + @Test(dataProvider = "fileSuffix") + public void testUserApi(String fileSuffix) { + assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/client/api/UserApi" + fileSuffix + ".java")) + .assertMethod("createUser", "User") + .toFileAssert() + .assertMethod("createUsersWithArrayInput", "List") + .toFileAssert() + .assertMethod("createUsersWithListInput", "List") + .toFileAssert() + .assertMethod("getUserByName", "String") + .toFileAssert() + .assertMethod("loginUser", "String", "String", "String", "Long", "BigDecimal") + .toFileAssert() + .assertMethod("updateUser", "String", "User") + .toFileAssert(); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonSeServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonSeServerCodegenTest.java new file mode 100644 index 0000000000..0e415b8386 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/JavaHelidonSeServerCodegenTest.java @@ -0,0 +1,305 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.Generator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.openapitools.codegen.java.assertions.JavaFileAssert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertTrue; + +public class JavaHelidonSeServerCodegenTest { + + private DefaultGenerator generator; + private String outputPath; + + @BeforeMethod + public void setup() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + outputPath = output.getAbsolutePath().replace('\\', '/'); + + final CodegenConfigurator configurator = codegenConfigurator(new HashMap<>()); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + generator = new DefaultGenerator(); + generator.opts(clientOptInput); + } + + private CodegenConfigurator codegenConfigurator(Map additionalProperties) { + return new CodegenConfigurator() + .setGeneratorName("java-helidon-server") + .setLibrary("se") + .setAdditionalProperties(additionalProperties) + .setInputSpec("src/test/resources/3_0/helidon/petstore-for-testing.yaml") + .setOutputDir(outputPath); + } + + + @Test + public void testGenerateFullProject() { + generator.generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/PetServiceImpl.java")) + .fileContains( + "public class PetServiceImpl", + "response.status(HTTP_CODE_NOT_IMPLEMENTED).send();" + ); + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/Main.java")) + .fileContains( + "import org.openapitools.server.api.PetServiceImpl;", + ".register(\"/\", new PetServiceImpl())" + ); + } + + @Test + public void testGenerateProjectByDefault() { + generator.generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/PetService.java")) + .fileContains( + "public interface PetService extends Service {", + "default void update(Routing.Rules rules) {", + "void addPet(ServerRequest request, ServerResponse response, Pet pet);", + "void deletePet(ServerRequest request, ServerResponse response);" + ); + TestUtils.assertFileNotExists(Paths.get(outputPath + "/build.gradle")); + TestUtils.assertFileNotExists(Paths.get(outputPath + "/settings.gradle")); + } + + @Test + public void testGenerateGradleProject() { + Map additionalProperties = new HashMap<>(); + additionalProperties.put("gradleProject", true); + final CodegenConfigurator configurator = codegenConfigurator(additionalProperties); + generator.opts(configurator.toClientOptInput()).generate(); + + assertTrue(Paths.get(outputPath + "/build.gradle").toFile().exists()); + assertTrue(Paths.get(outputPath + "/settings.gradle").toFile().exists()); + TestUtils.assertFileNotExists(Paths.get(outputPath + "/pom.xml")); + } + + @Test + public void testGeneratePathParams() throws IOException { + Map additionalProperties = new HashMap<>(); + additionalProperties.put("useAbstractClass", true); + final CodegenConfigurator configurator = codegenConfigurator(additionalProperties); + generator.opts(configurator.toClientOptInput()).generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/PetService.java")) + .assertMethod("deletePet", "ServerRequest", "ServerResponse") + .bodyContainsLines( + "Long petId = Optional.ofNullable(request.path().param(\"petId\")).map(Long::valueOf).orElse" + + "(null);", + "ValidatorUtils.checkNonNull(petId);" + ) + .toFileAssert() + .assertMethod("getPetById") + .bodyContainsLines( + "Long petId = Optional.ofNullable(request.path().param(\"petId\")).map(Long::valueOf).orElse" + + "(null);", + "ValidatorUtils.checkNonNull(petId);" + ); + } + + @Test + public void testGenerateQueryParams() throws IOException { + Map additionalProperties = new HashMap<>(); + additionalProperties.put("useAbstractClass", true); + final CodegenConfigurator configurator = codegenConfigurator(additionalProperties); + generator.opts(configurator.toClientOptInput()).generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/PetService.java")) + .fileContains("import java.util.List;") + .assertMethod("findPetsByTags") + .bodyContainsLines( + "List tags = Optional.ofNullable(request.queryParams().toMap().get(\"tags\"))" + + ".orElse(null);", + "ValidatorUtils.checkNonNull(tags);" + ) + .toFileAssert() + .assertMethod("findPetsByStatus") + .bodyContainsLines( + "List status = Optional.ofNullable(request.queryParams().toMap().get(\"status\")).orElse" + + "(null);", + "ValidatorUtils.checkNonNull(status);" + ); + } + + @Test + public void testGenerateBodyParams() throws IOException { + Map additionalProperties = new HashMap<>(); + additionalProperties.put("useAbstractClass", true); + final CodegenConfigurator configurator = codegenConfigurator(additionalProperties); + generator.opts(configurator.toClientOptInput()).generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/PetService.java")) + .assertMethod("update") + .bodyContainsLines( + "rules.post(\"/pet\", Handler.create(Pet.class, this::addPet));", + "rules.put(\"/pet\", Handler.create(Pet.class, this::updatePet));" + ) + .toFileAssert() + .assertMethod("addPet", "ServerRequest", "ServerResponse", "Pet") + .bodyContainsLines( + "ValidatorUtils.checkNonNull(pet);", + "handleAddPet(request, response, pet);" + ) + .toFileAssert() + .assertMethod("updatePet", "ServerRequest", "ServerResponse", "Pet") + .bodyContainsLines( + "ValidatorUtils.checkNonNull(pet);", + "handleUpdatePet(request, response, pet);" + ); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/UserService.java")) + .assertMethod("update") + .bodyContainsLines( + "rules.post(\"/user\", Handler.create(User.class, this::createUser));", + "rules.post(\"/user/createWithArray\", this::createUsersWithArrayInput);", + "rules.post(\"/user/createWithList\", this::createUsersWithListInput);", + "rules.put(\"/user/{username}\", Handler.create(User.class, this::updateUser));" + ) + .toFileAssert() + .assertMethod("createUser", "ServerRequest", "ServerResponse", "User") + .bodyContainsLines( + "ValidatorUtils.checkNonNull(user);", + "handleCreateUser(request, response, user);" + ) + .toFileAssert() + .assertMethod("createUsersWithArrayInput", "ServerRequest", "ServerResponse") + .bodyContainsLines( + "Single.create(request.content().as(new GenericType>() { }))", + ".thenAccept(user -> {", + "ValidatorUtils.checkNonNull(user);", + "handleCreateUsersWithArrayInput(request, response, user);", + ".exceptionally(throwable -> handleError(request, response, throwable));" + ); + } + + @Test + public void testGenerateHeaderParams() throws IOException { + Map additionalProperties = new HashMap<>(); + additionalProperties.put("useAbstractClass", true); + final CodegenConfigurator configurator = codegenConfigurator(additionalProperties); + generator.opts(configurator.toClientOptInput()).generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/PetService.java")) + .assertMethod("deletePet", "ServerRequest", "ServerResponse") + .bodyContainsLines( + "String apiKey = request.headers().value(\"api_key\").orElse(null);", + "Long headerLong = request.headers().value(\"headerLong\").map(Long::valueOf).orElse(null);", + "ValidatorUtils.checkNonNull(headerLong);" + ); + } + + @Test + public void testGenerateCookiesParams() throws IOException { + Map additionalProperties = new HashMap<>(); + additionalProperties.put("useAbstractClass", true); + final CodegenConfigurator configurator = codegenConfigurator(additionalProperties); + generator.opts(configurator.toClientOptInput()).generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/PetService.java")) + .assertMethod("deletePet", "ServerRequest", "ServerResponse") + .bodyContainsLines( + "String cookieString = request.headers().cookies().toMap().getOrDefault(\"cookieString\", List.of" + + "()).stream().findFirst().orElse(null);", + "ValidatorUtils.checkNonNull(cookieString);", + "Integer cookieInt = request.headers().cookies().toMap().getOrDefault(\"cookieInt\", List.of())" + + ".stream().findFirst().map(Integer::valueOf).orElse(null);", + "List cookieIntArray = Optional.ofNullable(request.headers().cookies().toMap().get" + + "(\"cookieIntArray\")).orElse(null);", + "List cookieStringArray = Optional.ofNullable(request.headers().cookies().toMap().get" + + "(\"cookieStringArray\")).orElse(null);" + ); + } + + @Test + public void testGenerateFormParams() throws IOException { + Map additionalProperties = new HashMap<>(); + additionalProperties.put("useAbstractClass", true); + final CodegenConfigurator configurator = codegenConfigurator(additionalProperties); + generator.opts(configurator.toClientOptInput()).generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/PetService.java")) + .assertMethod("addPets", "ServerRequest", "ServerResponse") + .bodyContainsLines( + "Map> nonFileFormContent = new HashMap<>();", + "Map> fileFormContent = new HashMap<>();", + " Single formSingle = request.content().asStream(ReadableBodyPart.class)", + "if (\"images[]\".equals(name)) {", + "processFileFormField(name, fileFormContent, part);", + "if (\"image\".equals(name)) {", + "if (\"titles[]\".equals(name)) {", + "processNonFileFormField(name, nonFileFormContent, part);", + "if (\"longArray\".equals(name)) {", + "if (\"stringParam\".equals(name)) {", + "if (\"intParam\".equals(name)) {", + "List images = Optional.ofNullable(fileFormContent.get(\"images[]\")).orElse(null);", + "InputStream image = Optional.ofNullable(fileFormContent.get(\"image\")).flatMap(list->list" + + ".stream().findFirst()).orElse(null);", + "List titles = Optional.ofNullable(nonFileFormContent.get(\"titles[]\")).orElse(null);", + "List longArray = Optional.ofNullable(nonFileFormContent.get(\"longArray\")).orElse(null);", + "Integer intParam = Optional.ofNullable(nonFileFormContent.get(\"intParam\")).flatMap(list->list" + + ".stream().findFirst()).map(Integer::valueOf).orElse(null);" + ); + } + + @Test + public void testGenerateParamsValidation() throws IOException { + Map additionalProperties = new HashMap<>(); + additionalProperties.put("useAbstractClass", true); + final CodegenConfigurator configurator = codegenConfigurator(additionalProperties); + generator.opts(configurator.toClientOptInput()).generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/PetService.java")) + .assertMethod("findPetsByStatus") + .bodyContainsLines( + "ValidatorUtils.checkNonNull(status);", + "List status = Optional.ofNullable(request.queryParams().toMap().get(\"status\")).orElse" + + "(null);" + ) + .toFileAssert() + .assertMethod("findPetsByTags") + .bodyContainsLines( + "List tags = Optional.ofNullable(request.queryParams().toMap().get(\"tags\")).orElse" + + "(null);", + "ValidatorUtils.checkNonNull(tags);" + ); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/server/api/UserService.java")) + .assertMethod("loginUser") + .bodyContainsLines( + "ValidatorUtils.validatePattern(username, \"^[a-zA-Z0-9]+[a-zA-Z0-9\\\\" + + ".\\\\-_]*[a-zA-Z0-9]+$\");", + "" + ); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalBase.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalBase.java new file mode 100644 index 0000000000..15c858f435 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalBase.java @@ -0,0 +1,361 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon.functional; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.openapitools.codegen.languages.JavaHelidonCommonCodegen; +import org.testng.SkipException; + +import static java.util.Objects.requireNonNull; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +abstract class FunctionalBase { + + private static final Logger LOGGER = Logger.getLogger(FunctionalBase.class.getName()); + + private static final String MAVEN_SHIM_TARGET = "libexec/bin/mvn"; + private static final String MAVEN_HOME_VAR = "MAVEN_HOME"; + private static final String MVN_HOME_VAR = "MVN_HOME"; + private static final String PATH_VAR = "PATH"; + private static final String MAVEN_BINARY_NAME; + private static final boolean IS_WINDOWS_OS; + private static final List> DEFAULT_HELIDON_VERSIONS_FOR_JAVA_VERSIONS = new ArrayList<>(); + + protected static final String FULL_PROJECT = "fullProject"; + protected static final String USE_ABSTRACT_CLASS = "useAbstractClass"; + + static { + /* + The inferred Helidon version for tests is from the entry for which the Java major version does not exceed + the current runtime Java major version. + + For example, for Java 8 or 9 or 11: 2.5.3. For Java 13 or later: 3.0.1. + */ + DEFAULT_HELIDON_VERSIONS_FOR_JAVA_VERSIONS.add(new AbstractMap.SimpleEntry<>(11, "2.5.3")); + DEFAULT_HELIDON_VERSIONS_FOR_JAVA_VERSIONS.add(new AbstractMap.SimpleEntry<>(13, "3.0.1")); + } + + private String library; + private String generatorName; + private String inputSpec; + protected Path outputPath; + + private Path mvn; + + static { + IS_WINDOWS_OS = System.getProperty("os.name", "unknown") + .toLowerCase(Locale.ENGLISH) + .contains("win"); + MAVEN_BINARY_NAME = IS_WINDOWS_OS ? "mvn.cmd" : "mvn"; + } + + protected CodegenConfigurator createConfigurator() { + try { + return createConfigurator(Files.createTempDirectory("test")); + } catch (IOException e) { + throw new UncheckedIOException("Can not create temp directory", e); + } + } + + protected CodegenConfigurator createConfigurator(Path outputPath) { + Objects.requireNonNull(inputSpec); + this.outputPath = outputPath; + String sanitizedPath = outputPath.toFile() + .getAbsolutePath() + .replace('\\', '/'); + return new CodegenConfigurator() + .setGeneratorName(generatorName) + .setLibrary(library) + .setInputSpec(inputSpec) + .setOutputDir(sanitizedPath); + + } + + protected void generate(CodegenConfigurator config) { + String helidonVersionToUse = chooseHelidonVersion(config); + enforceJavaVersion(helidonVersionToUse); + DefaultGenerator generator = new DefaultGenerator(); + generator.opts(config.toClientOptInput()); + generator.generate(); + } + + protected void generate() { + generate(createConfigurator()); + } + + protected void generate(String inputSpec) { + inputSpec(inputSpec); + generate(createConfigurator()); + } + + protected void generatorName(String generatorName) { + this.generatorName = generatorName; + } + + protected void library(String library) { + this.library = library; + } + + protected void inputSpec(String inputSpec) { + this.inputSpec = inputSpec; + } + + /** + * Run maven command with provided arguments. + * + * @param args maven command arguments + * @return a {@link ProcessReader} + */ + protected ProcessReader runMavenProcess(String... args) { + return runMavenProcess(outputPath.toFile(), args); + } + + /** + * Run maven command and causes the current thread to wait for {@link Process} to terminate. + * + * @param args maven command arguments + * @return a {@link ProcessReader} + */ + protected ProcessReader runMavenProcessAndWait(String... args) { + ProcessReader process = runMavenProcess(args); + process.waitFor(10, TimeUnit.MINUTES); + return process; + } + + /** + * Run maven command in the provided directory. + * + * @param directory from where the command is executed + * @param args maven command arguments + * @return a {@link ProcessReader} + */ + protected ProcessReader runMavenProcess(File directory, String... args) { + List command = new ArrayList<>(Collections.singleton(mavenExecutable())); + Collections.addAll(command, args); + try { + Process process = new ProcessBuilder() + .directory(directory) + .command(command) + .start(); + return new ProcessReader(process); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Finds the {@code mvn} executable. Searches using the following, in order: + *
          + *
        1. The {@code MAVEN_HOME} environment variable
        2. + *
        3. The {@code MVN_HOME} environment variable
        4. + *
        5. The {@code PATH} environment variable
        6. + *
        + * + * @return The path. + */ + public String mavenExecutable() { + if (mvn == null) { + Path maven; + Optional path = findExecutableInPath(); + if (path.isPresent()) { + maven = path.get(); + } else { + maven = toMavenExecutable(MAVEN_HOME_VAR); + if (maven == null) { + maven = toMavenExecutable(MVN_HOME_VAR); + } + } + try { + assumeTrue( "Maven not found, test is skipped", maven != null); + maven = maven.toRealPath(); + Path shimmed = maven.getParent().getParent().resolve(MAVEN_SHIM_TARGET); + if (Files.exists(shimmed)) { + maven = shimmed; + } + mvn = maven.toRealPath(); + } catch (IOException ex) { + throw new IllegalStateException(ex.getMessage()); + } + } + return mvn.toString(); + } + + private String chooseHelidonVersion(CodegenConfigurator config) { + Map unprocessedAdditionalProperties = config.toContext() + .getGeneratorSettings() + .getAdditionalProperties(); + if (unprocessedAdditionalProperties.containsKey(JavaHelidonCommonCodegen.HELIDON_VERSION)) { + return unprocessedAdditionalProperties.get(JavaHelidonCommonCodegen.HELIDON_VERSION).toString(); + } + String result = inferredHelidonVersion(); + config.addAdditionalProperty(JavaHelidonCommonCodegen.HELIDON_VERSION, result); + return result; + } + + private void enforceJavaVersion(String helidonVersionToUse) { + int currentJavaVersion = getCurrentJavaMajorVersion(); + int requiredJavaVersion = getRequiredJavaVersion(helidonVersionToUse); + String errorJavaVersion = String.format(Locale.ROOT, "Java version must be %s, test is skipped", requiredJavaVersion); + assumeTrue(errorJavaVersion, currentJavaVersion == requiredJavaVersion); + } + + private int getRequiredJavaVersion(String helidonVersionToUse) { + return helidonVersionToUse + .startsWith("3.") ? 17 : 11; + } + + private int getCurrentJavaMajorVersion() { + String[] versionElements = System.getProperty("java.version").split("\\."); + int firstElement = Integer.parseInt(versionElements[0]); + if (firstElement == 1) { + return Integer.parseInt(versionElements[1]); + } else { + return firstElement; + } + } + + private String inferredHelidonVersion() { + int javaMajorVersion = getCurrentJavaMajorVersion(); + String result = null; + for (Map.Entry javaToHelidonVersionMapping : DEFAULT_HELIDON_VERSIONS_FOR_JAVA_VERSIONS) { + if (javaToHelidonVersionMapping.getKey() <= javaMajorVersion) { + result = javaToHelidonVersionMapping.getValue(); + } + } + if (result == null) { + String message = String.format(Locale.ROOT, "Unable to infer Helidon version from current Java major version %d using mapping %s", + javaMajorVersion, DEFAULT_HELIDON_VERSIONS_FOR_JAVA_VERSIONS); + LOGGER.log(Level.WARNING, message); + throw new SkipException(message); + } + return result; + } + + /** + * Find an executable in the {@code PATH} environment variable, if present. + * + * @return The path. + */ + private Optional findExecutableInPath() { + return Arrays.stream(requireNonNull(System.getenv(PATH_VAR)).split(File.pathSeparator)) + .map(Paths::get) + .map(path -> path.resolve(FunctionalBase.MAVEN_BINARY_NAME)) + .filter(Files::isExecutable) + .findFirst(); + } + + private Path toMavenExecutable(String mavenHomeEnvVar) { + Path mavenHome = envVarPath(mavenHomeEnvVar); + if (mavenHome != null) { + if (Files.isDirectory(mavenHome)) { + Path executable = mavenHome.resolve("bin").resolve(MAVEN_BINARY_NAME); + if (Files.exists(executable) && (IS_WINDOWS_OS || Files.isExecutable(executable))) { + return executable; + } + } + } + return null; + } + + private static Path envVarPath(String var) { + final String path = System.getenv(var); + return path == null ? null : Paths.get(path); + } + + /** + * Allow junit to skip test without throwing an exception and report tests as failed. + * + * @param message warning message + * @param condition to be checked + */ + protected static void assumeTrue(String message, boolean condition) { + if (!condition) { + LOGGER.log(Level.WARNING, message); + throw new SkipException(message); + } + } + + /** + * Convenience method to build project using Maven and verify test output. + * + * @param jarPath path to expected jar file + */ + protected void buildAndVerify(String jarPath) { + ProcessReader reader = runMavenProcessAndWait("package"); + Path executableJar = outputPath.resolve(jarPath); + String output = reader.readOutputConsole(); + assertThat(output, containsString("BUILD SUCCESS")); + assertThat(output, containsString("Errors: 0")); + assertThat(output, containsString("Failures: 0")); + assertThat(output, containsString("Skipped: 0")); + assertThat(Files.exists(executableJar), is(true)); + } + + /** + * {@link Process} wrapper to read I/O Stream. + */ + static class ProcessReader { + + private final Process process; + private final BufferedReader consoleReader; + + ProcessReader(Process process) { + this.process = process; + this.consoleReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)); + } + + public String readOutputConsole() { + return consoleReader.lines().collect(Collectors.joining("\n")); + } + + @SuppressWarnings("UnusedReturnValue") + public boolean waitFor(long timeout, TimeUnit unit) { + try { + return process.waitFor(timeout, unit); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonClientBase.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonClientBase.java new file mode 100644 index 0000000000..967e77bcba --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonClientBase.java @@ -0,0 +1,76 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates. + * + * 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 + * + * http://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.java.helidon.functional; + +import org.testng.annotations.Test; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; + +public class FunctionalHelidonClientBase extends FunctionalBase { + @Test + void buildPetstore() { + generate("src/test/resources/3_0/petstore.yaml"); + buildAndVerify("target/openapi-java-client.jar"); + } + + @Test + void buildPetstoreWithFakeEndpoints() { + generate("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml"); + buildAndVerify("target/openapi-java-client.jar"); + } + + @Test + void buildPetstoreNoMultipart() { + generate("src/test/resources/3_0/helidon/petstore-no-multipart-for-testing.yaml"); + buildAndVerify("target/openapi-java-client.jar"); + } + + @Test + void verifyFullProjectSemantics() { + inputSpec("src/test/resources/3_0/petstore.yaml"); + + // Generate project for first time and record pom's timestamp + generate(createConfigurator()); + buildAndVerify("target/openapi-java-client.jar"); + Path pom1 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom1), is(true)); + long lastModified = pom1.toFile().lastModified(); + + // Re-generate project over same directory with fullProject unspecified + generate(createConfigurator(outputPath)); + Path pom2 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom2), is(true)); + assertThat(pom2.toFile().lastModified(), is(lastModified)); // not overwritten + + // Re-generate project over same directory with fullProject false + generate(createConfigurator(outputPath).addAdditionalProperty(FULL_PROJECT, "false")); + Path pom3 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom3), is(true)); + assertThat(pom3.toFile().lastModified(), is(lastModified)); // not overwritten + + // Re-generate project over same directory with fullProject true + generate(createConfigurator(outputPath).addAdditionalProperty(FULL_PROJECT, "true")); + Path pom4 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom4), is(true)); + assertThat(pom4.toFile().lastModified(), is(not(lastModified))); // overwritten + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonMPClientTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonMPClientTest.java new file mode 100644 index 0000000000..7c2aa94355 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonMPClientTest.java @@ -0,0 +1,29 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon.functional; + +import org.testng.annotations.BeforeClass; + +public class FunctionalHelidonMPClientTest extends FunctionalHelidonClientBase { + + @BeforeClass + public void setup() { + library("mp"); + generatorName("java-helidon-client"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonMPServerTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonMPServerTest.java new file mode 100644 index 0000000000..ca19e93f7a --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonMPServerTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon.functional; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.openapitools.codegen.CodegenConstants.SERIALIZATION_LIBRARY; + +public class FunctionalHelidonMPServerTest extends FunctionalBase { + + @BeforeClass + public void setup() { + library("mp"); + generatorName("java-helidon-server"); + inputSpec("src/test/resources/3_0/helidon/petstore-for-testing.yaml"); + } + + @Test + void buildProjectDefaultOptions() { + generate(); + buildAndVerify("target/openapi-java-server.jar"); + } + + @Test + void buildProjectAbstractClasses() { + generate(createConfigurator().addAdditionalProperty(USE_ABSTRACT_CLASS, "true")); + buildAndVerify("target/openapi-java-server.jar"); + } + + @Test + void buildFullProject() { + generate(createConfigurator().addAdditionalProperty(FULL_PROJECT, "true")); + buildAndVerify("target/openapi-java-server.jar"); + } + + @Test + void verifyFullProjectSemantics() { + // Generate project for first time and record pom's timestamp + generate(createConfigurator()); + buildAndVerify("target/openapi-java-server.jar"); + Path pom1 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom1), is(true)); + long lastModified = pom1.toFile().lastModified(); + + // Re-generate project over same directory with fullProject unspecified + generate(createConfigurator(outputPath)); + Path pom2 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom2), is(true)); + assertThat(pom2.toFile().lastModified(), is(lastModified)); // not overwritten + + // Re-generate project over same directory with fullProject false + generate(createConfigurator(outputPath).addAdditionalProperty(FULL_PROJECT, "false")); + Path pom3 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom3), is(true)); + assertThat(pom3.toFile().lastModified(), is(lastModified)); // not overwritten + + // Re-generate project over same directory with fullProject true + generate(createConfigurator(outputPath).addAdditionalProperty(FULL_PROJECT, "true")); + Path pom4 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom4), is(true)); + assertThat(pom4.toFile().lastModified(), is(not(lastModified))); // overwritten + } + + @Test + void buildJsonbProject() { + generate(createConfigurator().addAdditionalProperty(SERIALIZATION_LIBRARY, "jsonb")); + buildAndVerify("target/openapi-java-server.jar"); + } + + @Test + void buildJacksonProject() { + generate(createConfigurator().addAdditionalProperty(SERIALIZATION_LIBRARY, "jackson")); + buildAndVerify("target/openapi-java-server.jar"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonSEClientTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonSEClientTest.java new file mode 100644 index 0000000000..8e390f5915 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonSEClientTest.java @@ -0,0 +1,30 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon.functional; + + +import org.testng.annotations.BeforeClass; + +public class FunctionalHelidonSEClientTest extends FunctionalHelidonClientBase { + + @BeforeClass + public void setup() { + library("se"); + generatorName("java-helidon-client"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonSeServerTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonSeServerTest.java new file mode 100644 index 0000000000..020c44257d --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/helidon/functional/FunctionalHelidonSeServerTest.java @@ -0,0 +1,80 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright (c) 2022 Oracle and/or its affiliates + * + * 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.java.helidon.functional; + +import java.nio.file.Files; +import java.nio.file.Path; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; + +public class FunctionalHelidonSeServerTest extends FunctionalBase { + + @BeforeClass + public void setup() { + library("se"); + generatorName("java-helidon-server"); + } + + @Test + void buildPetstoreWithDefaultOptions() { + generate("src/test/resources/3_0/petstore.yaml"); + buildAndVerify("target/openapi-java-server.jar"); + } + + @Test + void buildPetstoreWithAbstractClasses() { + inputSpec("src/test/resources/3_0/petstore.yaml"); + generate(createConfigurator().addAdditionalProperty(FunctionalBase.USE_ABSTRACT_CLASS, "true")); + buildAndVerify("target/openapi-java-server.jar"); + } + + @Test + void verifyFullProject() { + inputSpec("src/test/resources/3_0/petstore.yaml"); + + // Generate project for first time and record pom's timestamp + generate(createConfigurator()); + buildAndVerify("target/openapi-java-server.jar"); + Path pom1 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom1), is(true)); + long lastModified = pom1.toFile().lastModified(); + + // Re-generate project over same directory with fullProject unspecified + generate(createConfigurator(outputPath)); + Path pom2 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom2), is(true)); + assertThat(pom2.toFile().lastModified(), is(lastModified)); // not overwritten + + // Re-generate project over same directory with fullProject false + generate(createConfigurator(outputPath).addAdditionalProperty(FULL_PROJECT, "false")); + Path pom3 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom3), is(true)); + assertThat(pom3.toFile().lastModified(), is(lastModified)); // not overwritten + + // Re-generate project over same directory with fullProject true + generate(createConfigurator(outputPath).addAdditionalProperty(FULL_PROJECT, "true")); + Path pom4 = outputPath.resolve("pom.xml"); + assertThat(Files.exists(pom4), is(true)); + assertThat(pom4.toFile().lastModified(), is(not(lastModified))); // overwritten + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/JavaJAXRSSpecServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/JavaJAXRSSpecServerCodegenTest.java index 920d2b6a03..1fa2e72554 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/JavaJAXRSSpecServerCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/JavaJAXRSSpecServerCodegenTest.java @@ -380,9 +380,8 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest { String outputPath = output.getAbsolutePath().replace('\\', '/'); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/arrayParameter.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/3_0/setParameter.yaml", null, new ParseOptions()).getOpenAPI(); - openAPI.getComponents().getParameters().get("operationsQueryParam").setSchema(new ArraySchema().uniqueItems(true)); codegen.setOutputDir(output.getAbsolutePath()); codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); @@ -687,4 +686,43 @@ public class JavaJAXRSSpecServerCodegenTest extends JavaJaxrsBaseTest { .assertParameterAnnotations() .containsWithNameAndAttributes("DefaultValue", ImmutableMap.of("value", "\"true\"")); } + + @Test + public void arrayNullableDefaultValueTests() throws Exception { + final File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + final OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/issue_13025.yaml", null, new ParseOptions()).getOpenAPI(); + + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(SUPPORT_ASYNC, true); //Given support async is enabled + codegen.additionalProperties().put(INTERFACE_ONLY, true); //And only interfaces are generated + + final ClientOptInput input = new ClientOptInput() + .openAPI(openAPI) + .config(codegen); //Using JavaJAXRSSpecServerCodegen + + final DefaultGenerator generator = new DefaultGenerator(); + final List files = generator.opts(input).generate(); //When generating files + + //Then the java files are compilable + validateJavaSourceFiles(files); + + //And the generated model contains correct default value for array properties (optional) + TestUtils.ensureContainsFile(files, output, "src/gen/java/org/openapitools/model/Body.java"); + assertFileContains(output.toPath().resolve("src/gen/java/org/openapitools/model/Body.java"), + "\nprivate @Valid List arrayThatIsNull = null;\n"); + + //And the generated model contains correct default value for array properties (required, nullable) + TestUtils.ensureContainsFile(files, output, "src/gen/java/org/openapitools/model/BodyWithRequiredNullalble.java"); + assertFileContains(output.toPath().resolve("src/gen/java/org/openapitools/model/BodyWithRequiredNullalble.java"), + "\nprivate @Valid List arrayThatIsNull = null;\n"); + + //And the generated model contains correct default value for array properties (required) + TestUtils.ensureContainsFile(files, output, "src/gen/java/org/openapitools/model/BodyWithRequired.java"); + assertFileContains(output.toPath().resolve("src/gen/java/org/openapitools/model/BodyWithRequired.java"), + "\nprivate @Valid List arrayThatIsNotNull = new ArrayList<>();\n"); + + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java index 601b8c0769..ac1f12a3eb 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java @@ -33,12 +33,12 @@ import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.parser.core.models.ParseOptions; + import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; @@ -57,6 +57,7 @@ import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.AbstractJavaCodegen; import org.openapitools.codegen.languages.SpringCodegen; +import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.CXFServerFeatures; import org.openapitools.codegen.languages.features.DocumentationProviderFeatures; import org.testng.Assert; @@ -104,51 +105,52 @@ public class SpringCodegenTest { generator.opts(input).generate(); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ZebrasApi.java")) - .assertTypeAnnotations() - .hasSize(3) + .assertTypeAnnotations() + .hasSize(4) .containsWithName("Validated") .containsWithName("Generated") + .containsWithName("RequestMapping") .containsWithNameAndAttributes("Generated", ImmutableMap.of( - "value", "\"org.openapitools.codegen.languages.SpringCodegen\"" + "value", "\"org.openapitools.codegen.languages.SpringCodegen\"" )) .containsWithNameAndAttributes("Tag", ImmutableMap.of( - "name", "\"zebras\"" + "name", "\"zebras\"" )) - .toType() - .assertMethod("getZebras") + .toType() + .assertMethod("getZebras") .hasReturnType("ResponseEntity") .assertMethodAnnotations() .hasSize(2) .containsWithNameAndAttributes("Operation", ImmutableMap.of("operationId", "\"getZebras\"")) .containsWithNameAndAttributes("RequestMapping", ImmutableMap.of( - "method", "RequestMethod.GET", - "value", "\"/zebras\"" + "method", "RequestMethod.GET", + "value", "\"/zebras\"" )) - .toMethod() - .hasParameter("limit").withType("BigDecimal") - .assertParameterAnnotations() - .containsWithName("Valid") - .containsWithNameAndAttributes("Parameter", ImmutableMap.of("name", "\"limit\"")) - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("required", "false", "value", "\"limit\"")) - .toParameter() - .toMethod() - .hasParameter("animalParams").withType("AnimalParams") - .toMethod() - .commentContainsLines("GET /zebras", "@param limit (optional)") - .bodyContainsLines("return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)"); + .toMethod() + .hasParameter("limit").withType("BigDecimal") + .assertParameterAnnotations() + .containsWithName("Valid") + .containsWithNameAndAttributes("Parameter", ImmutableMap.of("name", "\"limit\"")) + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("required", "false", "value", "\"limit\"")) + .toParameter() + .toMethod() + .hasParameter("animalParams").withType("AnimalParams") + .toMethod() + .commentContainsLines("GET /zebras", "@param limit (optional)") + .bodyContainsLines("return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)"); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/model/AnimalParams.java")) - .hasImports("org.springframework.format.annotation.DateTimeFormat") - .hasProperty("born").withType("LocalDate") + .hasImports("org.springframework.format.annotation.DateTimeFormat") + .hasProperty("born").withType("LocalDate") .assertPropertyAnnotations() .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE")) .toProperty() - .toType() - .hasProperty("lastSeen").withType("OffsetDateTime") + .toType() + .hasProperty("lastSeen").withType("OffsetDateTime") .assertPropertyAnnotations() .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE_TIME")) - .toProperty().toType() - .assertMethod("born", "LocalDate") + .toProperty().toType() + .assertMethod("born", "LocalDate") .bodyContainsLines("this.born = born") .doesNotHaveComment(); } @@ -180,21 +182,21 @@ public class SpringCodegenTest { generator.opts(input).generate(); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ElephantsApi.java")) - .assertMethod("getElephants", "String", "BigDecimal") - .hasParameter("userToken") - .assertParameterAnnotations() - .containsWithNameAndAttributes("CookieValue", ImmutableMap.of("name", "\"userToken\"")); + .assertMethod("getElephants", "String", "BigDecimal") + .hasParameter("userToken") + .assertParameterAnnotations() + .containsWithNameAndAttributes("CookieValue", ImmutableMap.of("name", "\"userToken\"")); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ZebrasApi.java")) - .assertMethod("getZebras", "String") - .hasParameter("userToken") - .assertParameterAnnotations() - .containsWithNameAndAttributes("CookieValue", ImmutableMap.of("name", "\"userToken\"")); + .assertMethod("getZebras", "String") + .hasParameter("userToken") + .assertParameterAnnotations() + .containsWithNameAndAttributes("CookieValue", ImmutableMap.of("name", "\"userToken\"")); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/BirdsApi.java")) - .assertMethod("getBirds", "BigDecimal") - .doesNotHaveParameter("userToken") - .noneOfParameterHasAnnotation("CookieValue"); + .assertMethod("getBirds", "BigDecimal") + .doesNotHaveParameter("userToken") + .noneOfParameterHasAnnotation("CookieValue"); } @Test @@ -290,18 +292,18 @@ public class SpringCodegenTest { generator.opts(input).generate(); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ElephantsApi.java")) - .hasImports("org.springframework.format.annotation.DateTimeFormat") - .assertMethod("getElephants", "LocalDate") - .hasParameter("startDate") - .assertParameterAnnotations() - .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE")); + .hasImports("org.springframework.format.annotation.DateTimeFormat") + .assertMethod("getElephants", "LocalDate") + .hasParameter("startDate") + .assertParameterAnnotations() + .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE")); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ZebrasApi.java")) - .hasImports("org.springframework.format.annotation.DateTimeFormat") - .assertMethod("getZebras", "OffsetDateTime") - .hasParameter("startDateTime") - .assertParameterAnnotations() - .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE_TIME")); + .hasImports("org.springframework.format.annotation.DateTimeFormat") + .assertMethod("getZebras", "OffsetDateTime") + .hasParameter("startDateTime") + .assertParameterAnnotations() + .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE_TIME")); } @Test @@ -350,14 +352,14 @@ public class SpringCodegenTest { generator.opts(input).generate(); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ExampleApi.java")) - .assertMethod("exampleApiGet", "String", "Format") + .assertMethod("exampleApiGet", "String", "Format") .hasParameter("query") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("value", "\"query\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("value", "\"query\"")) .toParameter().toMethod() .hasParameter("format") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("value", "\"format\"")); + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("value", "\"format\"")); } @Test @@ -388,11 +390,11 @@ public class SpringCodegenTest { generator.opts(input).generate(); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ExampleApi.java")) - .assertMethod("exampleApiGet", "OffsetDateTime") - .hasParameter("start") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("value", "\"start\"")) - .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE_TIME")); + .assertMethod("exampleApiGet", "OffsetDateTime") + .hasParameter("start") + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("value", "\"start\"")) + .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE_TIME")); } @Test @@ -517,10 +519,10 @@ public class SpringCodegenTest { generator.opts(input).generate(); JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ExampleApi.java")) - .assertMethod("exampleApiPost", "ExampleApiPostRequest") - .hasParameter("exampleApiPostRequest") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestBody", ImmutableMap.of("required", "false")); + .assertMethod("exampleApiPost", "ExampleApiPostRequest") + .hasParameter("exampleApiPostRequest") + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestBody", ImmutableMap.of("required", "false")); assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ExampleApi.java"), "@RequestBody(required = false"); @@ -563,16 +565,16 @@ public class SpringCodegenTest { // Check that the delegate handles the array JavaFileAssert.assertThat(files.get("MultipartArrayApiDelegate.java")) - .assertMethod("multipartArray", "List") - .hasParameter("files").withType("List"); + .assertMethod("multipartArray", "List") + .hasParameter("files").withType("List"); // Check that the api handles the array JavaFileAssert.assertThat(files.get("MultipartArrayApi.java")) - .assertMethod("multipartArray", "List") - .hasParameter("files").withType("List") - .assertParameterAnnotations() - .containsWithNameAndAttributes("ApiParam", ImmutableMap.of("value", "\"Many files\"")) - .containsWithNameAndAttributes("RequestPart", ImmutableMap.of("value", "\"files\"", "required", "false")); + .assertMethod("multipartArray", "List") + .hasParameter("files").withType("List") + .assertParameterAnnotations() + .containsWithNameAndAttributes("ApiParam", ImmutableMap.of("value", "\"Many files\"")) + .containsWithNameAndAttributes("RequestPart", ImmutableMap.of("value", "\"files\"", "required", "false")); // UPDATE: the following test has been ignored due to https://github.com/OpenAPITools/openapi-generator/pull/11081/ // We will contact the contributor of the following test to see if the fix will break their use cases and @@ -583,25 +585,25 @@ public class SpringCodegenTest { // Check that the api handles the single file JavaFileAssert.assertThat(files.get("MultipartSingleApi.java")) - .assertMethod("multipartSingle", "MultipartFile") - .hasParameter("file").withType("MultipartFile") - .assertParameterAnnotations() - .containsWithNameAndAttributes("ApiParam", ImmutableMap.of("value", "\"One file\"")) - .containsWithNameAndAttributes("RequestPart", ImmutableMap.of("value", "\"file\"", "required", "false")); + .assertMethod("multipartSingle", "MultipartFile") + .hasParameter("file").withType("MultipartFile") + .assertParameterAnnotations() + .containsWithNameAndAttributes("ApiParam", ImmutableMap.of("value", "\"One file\"")) + .containsWithNameAndAttributes("RequestPart", ImmutableMap.of("value", "\"file\"", "required", "false")); // Check that api validates mixed multipart request JavaFileAssert.assertThat(files.get("MultipartMixedApi.java")) - .assertMethod("multipartMixed", "MultipartMixedStatus", "MultipartFile", "MultipartMixedRequestMarker") + .assertMethod("multipartMixed", "MultipartMixedStatus", "MultipartFile", "MultipartMixedRequestMarker") .hasParameter("status").withType("MultipartMixedStatus") .assertParameterAnnotations() .containsWithName("Valid") .containsWithNameAndAttributes("ApiParam", ImmutableMap.of("value", "\"\"")) .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("value", "\"status\"", "required", "true")) - .toParameter().toMethod() + .toParameter().toMethod() .hasParameter("file").withType("MultipartFile") .assertParameterAnnotations() .containsWithNameAndAttributes("RequestPart", ImmutableMap.of("value", "\"file\"", "required", "true")) - .toParameter().toMethod() + .toParameter().toMethod() .hasParameter("marker").withType("MultipartMixedRequestMarker") .assertParameterAnnotations() .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("value", "\"marker\"", "required", "false")); @@ -650,10 +652,40 @@ public class SpringCodegenTest { // Check that the api handles the array and the file final File multipartApi = files.get("MultipartApi.java"); assertFileContains(multipartApi.toPath(), - "List files", - "MultipartFile file"); + "List files", + "MultipartFile file"); } + @Test + public void testRequestMappingAnnotation() throws IOException { + final SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary("spring-boot"); + + final Map files = generateFiles(codegen, "src/test/resources/2_0/petstore.yaml"); + + // Check that the @RequestMapping annotation is generated in the Api file + final File petApiFile = files.get("PetApi.java"); + assertFileContains(petApiFile.toPath(), "@RequestMapping(\"${openapi.openAPIPetstore.base-path:/v2}\")"); + + // Check that the @RequestMapping annotation is not generated in the Controller file + final File petApiControllerFile = files.get("PetApiController.java"); + assertFileNotContains(petApiControllerFile.toPath(), "@RequestMapping(\"${openapi.openAPIPetstore.base-path:/v2}\")"); + } + + @Test + public void testNoRequestMappingAnnotation() throws IOException { + final SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary( "spring-cloud" ); + + final Map files = generateFiles( codegen, "src/test/resources/2_0/petstore.yaml" ); + + // Check that the @RequestMapping annotation is not generated in the Api file + final File petApiFile = files.get( "PetApi.java" ); + JavaFileAssert.assertThat( petApiFile ).assertTypeAnnotations().hasSize( 3 ).containsWithName( "Validated" ) + .containsWithName( "Generated" ).containsWithName( "Tag" ); + + } + @Test public void testSettersForConfigValues() throws Exception { final SpringCodegen codegen = new SpringCodegen(); @@ -843,12 +875,14 @@ public class SpringCodegenTest { generator.opts(input).generate(); assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/GetApi.java"), - "@RequestParam(value = \"testParameter1\", required = false, defaultValue = \"BAR\")", - "@RequestParam(value = \"TestParameter2\", required = false, defaultValue = \"BAR\")"); + "@RequestParam(value = \"testParameter1\", required = false, defaultValue = \"BAR\")", + "@RequestParam(value = \"TestParameter2\", required = false, defaultValue = \"BAR\")"); } - /**Define documentation providers to test */ + /** + * Define documentation providers to test + */ private final static String SPRINGFOX = "springfox"; private final static String SPRINGFOX_DESTINATIONFILE = "SpringFoxConfiguration.java"; private final static String SPRINGFOX_TEMPLATEFILE = "openapiDocumentationConfig.mustache"; @@ -874,7 +908,7 @@ public class SpringCodegenTest { testConfigFileCommon(SPRINGDOC, SPRINGDOC_DESTINATIONFILE, SPRINGDOC_TEMPLATEFILE); } - private void testConfigFileCommon(String documentationProvider, String destinationFile, String templateFileName){ + private void testConfigFileCommon(String documentationProvider, String destinationFile, String templateFileName) { final SpringCodegen codegen = new SpringCodegen(); codegen.additionalProperties().put(DOCUMENTATION_PROVIDER, documentationProvider); codegen.additionalProperties().put(SpringCodegen.INTERFACE_ONLY, false); @@ -970,7 +1004,7 @@ public class SpringCodegenTest { output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/issue_5381.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/3_0/issue_5381.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -1008,7 +1042,7 @@ public class SpringCodegenTest { output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/oneof_polymorphism_and_inheritance.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/3_0/oneof_polymorphism_and_inheritance.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -1070,7 +1104,7 @@ public class SpringCodegenTest { String outputPath = output.getAbsolutePath().replace('\\', '/'); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_11464.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_11464.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -1094,23 +1128,23 @@ public class SpringCodegenTest { @DataProvider public Object[][] issue11464TestCases() { - return new Object[][] { - { DocumentationProviderFeatures.DocumentationProvider.SPRINGDOC.name(), (Consumer) outputPath -> { - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/NoneApi.java"), - "@Operation( operationId = \"getNone\", summary = \"No Tag\", responses = {"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/SingleApi.java"), - "@Operation( operationId = \"getSingleTag\", summary = \"Single Tag\", tags = { \"tag1\" }, responses = {"); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/MultipleApi.java"), - "@Operation( operationId = \"getMultipleTags\", summary = \"Multiple Tags\", tags = { \"tag1\", \"tag2\" }, responses = {"); - }}, - { DocumentationProviderFeatures.DocumentationProvider.SPRINGFOX.name(), (Consumer) outputPath -> { - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/NoneApi.java"), - "@ApiOperation( value = \"No Tag\", nickname = \"getNone\", notes = \"\", response = "); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/SingleApi.java"), - "@ApiOperation( tags = { \"tag1\" }, value = \"Single Tag\", nickname = \"getSingleTag\", notes = \"\", response = "); - assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/MultipleApi.java"), - "@ApiOperation( tags = { \"tag1\", \"tag2\" }, value = \"Multiple Tags\", nickname = \"getMultipleTags\", notes = \"\", response = "); - }}, + return new Object[][]{ + {DocumentationProviderFeatures.DocumentationProvider.SPRINGDOC.name(), (Consumer) outputPath -> { + assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/NoneApi.java"), + "@Operation( operationId = \"getNone\", summary = \"No Tag\", responses = {"); + assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/SingleApi.java"), + "@Operation( operationId = \"getSingleTag\", summary = \"Single Tag\", tags = { \"tag1\" }, responses = {"); + assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/MultipleApi.java"), + "@Operation( operationId = \"getMultipleTags\", summary = \"Multiple Tags\", tags = { \"tag1\", \"tag2\" }, responses = {"); + }}, + {DocumentationProviderFeatures.DocumentationProvider.SPRINGFOX.name(), (Consumer) outputPath -> { + assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/NoneApi.java"), + "@ApiOperation( value = \"No Tag\", nickname = \"getNone\", notes = \"\", response = "); + assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/SingleApi.java"), + "@ApiOperation( tags = { \"tag1\" }, value = \"Single Tag\", nickname = \"getSingleTag\", notes = \"\", response = "); + assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/MultipleApi.java"), + "@ApiOperation( tags = { \"tag1\", \"tag2\" }, value = \"Multiple Tags\", nickname = \"getMultipleTags\", notes = \"\", response = "); + }}, }; } @@ -1130,7 +1164,7 @@ public class SpringCodegenTest { String outputPath = output.getAbsolutePath().replace('\\', '/'); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/spring/issue_11323.yml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/3_0/spring/issue_11323.yml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -1150,7 +1184,7 @@ public class SpringCodegenTest { generator.opts(input).generate(); assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/model/Address.java"), - "@JsonValue", "import com.fasterxml.jackson.annotation.JsonValue;"); + "@JsonValue", "import com.fasterxml.jackson.annotation.JsonValue;"); } @Test @@ -1160,7 +1194,7 @@ public class SpringCodegenTest { String outputPath = output.getAbsolutePath().replace('\\', '/'); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/petstore.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/3_0/petstore.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -1184,10 +1218,10 @@ public class SpringCodegenTest { for (File modelPath : generatedModels) { JavaFileAssert.assertThat(modelPath) - .assertTypeAnnotations() - .containsWithName("custom.Annotation") - .containsWithName("path.Annotation2") - .containsWithNameAndAttributes("path.Annotation", ImmutableMap.of("param1", "\"test1\"", "param2", "3")); + .assertTypeAnnotations() + .containsWithName("custom.Annotation") + .containsWithName("path.Annotation2") + .containsWithNameAndAttributes("path.Annotation", ImmutableMap.of("param1", "\"test1\"", "param2", "3")); } } @@ -1197,70 +1231,70 @@ public class SpringCodegenTest { output.deleteOnExit(); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/issue_8535.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/3_0/issue_8535.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setOutputDir(output.getAbsolutePath()); codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); ClientOptInput input = new ClientOptInput() - .openAPI(openAPI) - .config(codegen); + .openAPI(openAPI) + .config(codegen); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("TestHeadersApi.java")) - .assertMethod("headersTest") + .assertMethod("headersTest") .hasParameter("headerNumber").withType("BigDecimal") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"11.2\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"11.2\"")) .toParameter().toMethod() .hasParameter("headerString").withType("String") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"qwerty\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"qwerty\"")) .toParameter().toMethod() .hasParameter("headerStringWrapped").withType("String") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"qwerty\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"qwerty\"")) .toParameter().toMethod() .hasParameter("headerStringQuotes").withType("String") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"qwerty\\\"with quotes\\\" test\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"qwerty\\\"with quotes\\\" test\"")) .toParameter().toMethod() .hasParameter("headerStringQuotesWrapped").withType("String") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"qwerty\\\"with quotes\\\" test\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"qwerty\\\"with quotes\\\" test\"")) .toParameter().toMethod() .hasParameter("headerBoolean").withType("Boolean") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"true\"")); + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestHeader", ImmutableMap.of("defaultValue", "\"true\"")); JavaFileAssert.assertThat(files.get("TestQueryParamsApi.java")) - .assertMethod("queryParamsTest") + .assertMethod("queryParamsTest") .hasParameter("queryNumber").withType("BigDecimal") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"11.2\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"11.2\"")) .toParameter().toMethod() .hasParameter("queryString").withType("String") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"qwerty\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"qwerty\"")) .toParameter().toMethod() .hasParameter("queryStringWrapped").withType("String") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"qwerty\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"qwerty\"")) .toParameter().toMethod() .hasParameter("queryStringQuotes").withType("String") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"qwerty\\\"with quotes\\\" test\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"qwerty\\\"with quotes\\\" test\"")) .toParameter().toMethod() .hasParameter("queryStringQuotesWrapped").withType("String") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"qwerty\\\"with quotes\\\" test\"")) + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"qwerty\\\"with quotes\\\" test\"")) .toParameter().toMethod() .hasParameter("queryBoolean").withType("Boolean") - .assertParameterAnnotations() - .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"true\"")); + .assertParameterAnnotations() + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"true\"")); } @Test @@ -1299,7 +1333,7 @@ public class SpringCodegenTest { output.deleteOnExit(); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_11897.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_11897.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setLibrary(SPRING_BOOT); codegen.setOutputDir(output.getAbsolutePath()); @@ -1312,25 +1346,25 @@ public class SpringCodegenTest { codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, "jackson"); ClientOptInput input = new ClientOptInput() - .openAPI(openAPI) - .config(codegen); + .openAPI(openAPI) + .config(codegen); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("MetadataApi.java")) - .assertMethod("getWithArrayOfObjects").hasReturnType("ResponseEntity>") - .toFileAssert() - .assertMethod("getWithArrayOfString").hasReturnType("ResponseEntity>") - .toFileAssert() - .assertMethod("getWithSetOfObjects").hasReturnType("ResponseEntity>") - .toFileAssert() - .assertMethod("getWithSetOfStrings").hasReturnType("ResponseEntity>") - .toFileAssert() - .assertMethod("getWithMapOfObjects").hasReturnType("ResponseEntity>") - .toFileAssert() - .assertMethod("getWithMapOfStrings").hasReturnType("ResponseEntity>"); + .assertMethod("getWithArrayOfObjects").hasReturnType("ResponseEntity>") + .toFileAssert() + .assertMethod("getWithArrayOfString").hasReturnType("ResponseEntity>") + .toFileAssert() + .assertMethod("getWithSetOfObjects").hasReturnType("ResponseEntity>") + .toFileAssert() + .assertMethod("getWithSetOfStrings").hasReturnType("ResponseEntity>") + .toFileAssert() + .assertMethod("getWithMapOfObjects").hasReturnType("ResponseEntity>") + .toFileAssert() + .assertMethod("getWithMapOfStrings").hasReturnType("ResponseEntity>"); } @Test @@ -1339,7 +1373,7 @@ public class SpringCodegenTest { output.deleteOnExit(); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_11957.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_11957.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setLibrary(SPRING_BOOT); codegen.setOutputDir(output.getAbsolutePath()); @@ -1352,30 +1386,30 @@ public class SpringCodegenTest { codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, "jackson"); ClientOptInput input = new ClientOptInput() - .openAPI(openAPI) - .config(codegen); + .openAPI(openAPI) + .config(codegen); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("SearchApi.java")) - .assertMethod("defaultList") + .assertMethod("defaultList") .hasParameter("orderBy") .assertParameterAnnotations() .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"updatedAt:DESC,createdAt:DESC\"")) - .toParameter().toMethod().toFileAssert() - .assertMethod("defaultSet") + .toParameter().toMethod().toFileAssert() + .assertMethod("defaultSet") .hasParameter("orderBy") .assertParameterAnnotations() .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"updatedAt:DESC,createdAt:DESC\"")) - .toParameter().toMethod().toFileAssert() - .assertMethod("emptyDefaultList") + .toParameter().toMethod().toFileAssert() + .assertMethod("emptyDefaultList") .hasParameter("orderBy") .assertParameterAnnotations() .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"\"")) - .toParameter().toMethod().toFileAssert() - .assertMethod("emptyDefaultSet") + .toParameter().toMethod().toFileAssert() + .assertMethod("emptyDefaultSet") .hasParameter("orderBy") .assertParameterAnnotations() .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("defaultValue", "\"\"")); @@ -1387,21 +1421,21 @@ public class SpringCodegenTest { output.deleteOnExit(); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_12494.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_12494.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setOutputDir(output.getAbsolutePath()); ClientOptInput input = new ClientOptInput() - .openAPI(openAPI) - .config(codegen); + .openAPI(openAPI) + .config(codegen); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("ChildClass.java")) - .assertMethod("putSomeMapItem") - .bodyContainsLines("super.putSomeMapItem(key, someMapItem);"); + .assertMethod("putSomeMapItem") + .bodyContainsLines("super.putSomeMapItem(key, someMapItem);"); } @Test @@ -1410,22 +1444,22 @@ public class SpringCodegenTest { output.deleteOnExit(); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_11731.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_11731.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setLibrary(SPRING_BOOT); codegen.setOutputDir(output.getAbsolutePath()); ClientOptInput input = new ClientOptInput() - .openAPI(openAPI) - .config(codegen); + .openAPI(openAPI) + .config(codegen); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("CustomersApi.java")) - .assertMethod("getAllUsingGET1") - .bodyContainsLines("if (mediaType.isCompatibleWith(MediaType.valueOf(\"application/hal+json\"))) {"); + .assertMethod("getAllUsingGET1") + .bodyContainsLines("if (mediaType.isCompatibleWith(MediaType.valueOf(\"application/hal+json\"))) {"); } @Test @@ -1434,26 +1468,232 @@ public class SpringCodegenTest { output.deleteOnExit(); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_12457.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/bugs/issue_12457.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setLibrary(SPRING_BOOT); codegen.setOutputDir(output.getAbsolutePath()); codegen.additionalProperties().put(SpringCodegen.USE_TAGS, "true"); ClientOptInput input = new ClientOptInput() - .openAPI(openAPI) - .config(codegen); + .openAPI(openAPI) + .config(codegen); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("UsersApi.java")) - .assertMethod("wildcardSubTypeForContentType") - .assertMethodAnnotations() - .containsWithNameAndAttributes("RequestMapping", ImmutableMap.of( - "produces", "{ \"application/json\", \"application/*\" }", - "consumes", "{ \"application/octet-stream\", \"application/*\" }" - )); + .assertMethod("wildcardSubTypeForContentType") + .assertMethodAnnotations() + .containsWithNameAndAttributes("RequestMapping", ImmutableMap.of( + "produces", "{ \"application/json\", \"application/*\" }", + "consumes", "{ \"application/octet-stream\", \"application/*\" }" + )); + } + + @Test + public void shouldGenerateDiscriminatorFromAllOfWhenUsingLegacyDiscriminatorBehaviour_issue12692() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_12692.yml", null, new ParseOptions()).getOpenAPI(); + SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary(SPRING_BOOT); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true"); + + ClientOptInput input = new ClientOptInput() + .openAPI(openAPI) + .config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + generator.opts(input).generate(); + + String jsonTypeInfo = "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = \"type\", visible = true)"; + String jsonSubType = "@JsonSubTypes({\n" + + " @JsonSubTypes.Type(value = Cat.class, name = \"cat\")" + + "})"; + assertFileContains(Paths.get(output.getAbsolutePath() + "/src/main/java/org/openapitools/model/Pet.java"), jsonTypeInfo, jsonSubType); + } + + @Test + public void shouldGenerateBeanValidationOnHeaderParams() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_7125.json", null, new ParseOptions()).getOpenAPI(); + SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary(SPRING_BOOT); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(SpringCodegen.USE_TAGS, "true"); + codegen.additionalProperties().put(BeanValidationFeatures.USE_BEANVALIDATION, "true"); + + ClientOptInput input = new ClientOptInput() + .openAPI(openAPI) + .config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + Map files = generator.opts(input).generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + JavaFileAssert.assertThat(files.get("SomeMethodApi.java")) + .printFileContent() + .assertMethod("methodWithValidation") + .hasParameter("headerOne") + .assertParameterAnnotations() + .containsWithName("RequestHeader") + .containsWithName("NotNull") + .containsWithNameAndAttributes("Size", ImmutableMap.of( + "min", "1", + "max", "10" + )) + .containsWithNameAndAttributes("Pattern", ImmutableMap.of("regexp", "\"\\\\d+\"")) + .toParameter() + .toMethod() + .hasParameter("headerTwo") + .assertParameterAnnotations() + .containsWithName("RequestHeader") + .containsWithName("NotNull") + .containsWithNameAndAttributes("Min", ImmutableMap.of("value", "500")) + .containsWithNameAndAttributes("Max", ImmutableMap.of("value", "10000")); + } + + @Test + public void requiredFieldShouldIncludeNotNullAnnotation_issue13365() throws IOException { + + SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary(SPRING_BOOT); + codegen.additionalProperties().put(SpringCodegen.INTERFACE_ONLY, "true"); + codegen.additionalProperties().put(SpringCodegen.USE_BEANVALIDATION, "false"); + codegen.additionalProperties().put(SpringCodegen.PERFORM_BEANVALIDATION, "false"); + codegen.additionalProperties().put(SpringCodegen.OPENAPI_NULLABLE, "false"); + codegen.additionalProperties().put(SpringCodegen.UNHANDLED_EXCEPTION_HANDLING, "false"); + codegen.additionalProperties().put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, "false"); + codegen.additionalProperties().put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false"); + codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, "jackson"); + codegen.additionalProperties().put(CodegenConstants.ENUM_PROPERTY_NAMING, "PascalCase"); + codegen.additionalProperties().put(SpringCodegen.USE_TAGS, "true"); + + DefaultGenerator generator = new DefaultGenerator(); + Map files = generateFiles(codegen, "src/test/resources/bugs/issue_13365.yml"); + + //Assert that NotNull annotation exists alone with no other BeanValidation annotations + JavaFileAssert.assertThat(files.get("Person.java")) + .printFileContent().assertMethod("getName").assertMethodAnnotations() + .containsWithName("NotNull").anyMatch(annotation -> + !annotation.getNameAsString().equals("Valid") || + !annotation.getNameAsString().equals("Pattern") || + !annotation.getNameAsString().equals("Email") || + !annotation.getNameAsString().equals("Size")); + + } + + @Test + public void nonRequiredFieldShouldNotIncludeNotNullAnnotation_issue13365() throws IOException { + + SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary(SPRING_BOOT); + codegen.additionalProperties().put(SpringCodegen.INTERFACE_ONLY, "true"); + codegen.additionalProperties().put(SpringCodegen.USE_BEANVALIDATION, "false"); + codegen.additionalProperties().put(SpringCodegen.PERFORM_BEANVALIDATION, "false"); + codegen.additionalProperties().put(SpringCodegen.OPENAPI_NULLABLE, "false"); + codegen.additionalProperties().put(SpringCodegen.UNHANDLED_EXCEPTION_HANDLING, "false"); + codegen.additionalProperties().put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, "false"); + codegen.additionalProperties().put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false"); + codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, "jackson"); + codegen.additionalProperties().put(CodegenConstants.ENUM_PROPERTY_NAMING, "PascalCase"); + codegen.additionalProperties().put(SpringCodegen.USE_TAGS, "true"); + + Map files = generateFiles(codegen, "src/test/resources/bugs/issue_13365.yml"); + + JavaFileAssert.assertThat(files.get("Alien.java")) + .printFileContent().assertMethod("getName") + .assertMethodAnnotations().anyMatch(annotation -> !annotation.getNameAsString().equals("NotNull")); + } + + @Test + public void requiredFieldShouldIncludeNotNullAnnotationWithBeanValidationTrue_issue13365() throws IOException { + + SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary(SPRING_BOOT); + codegen.additionalProperties().put(SpringCodegen.INTERFACE_ONLY, "true"); + codegen.additionalProperties().put(SpringCodegen.USE_BEANVALIDATION, "true"); + codegen.additionalProperties().put(SpringCodegen.PERFORM_BEANVALIDATION, "false"); + codegen.additionalProperties().put(SpringCodegen.OPENAPI_NULLABLE, "false"); + codegen.additionalProperties().put(SpringCodegen.UNHANDLED_EXCEPTION_HANDLING, "false"); + codegen.additionalProperties().put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, "false"); + codegen.additionalProperties().put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false"); + codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, "jackson"); + codegen.additionalProperties().put(CodegenConstants.ENUM_PROPERTY_NAMING, "PascalCase"); + codegen.additionalProperties().put(SpringCodegen.USE_TAGS, "true"); + + Map files = generateFiles(codegen, "src/test/resources/bugs/issue_13365.yml"); + + JavaFileAssert.assertThat(files.get("Person.java")) + .printFileContent().assertMethod("getName").assertMethodAnnotations() + .containsWithName("NotNull").containsWithName("Size").containsWithName("Email"); + + } + + public void shouldUseEqualsNullableForArrayWhenSetInConfig_issue13385() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_13385.yml", null, new ParseOptions()).getOpenAPI(); + SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary(SPRING_BOOT); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(SpringCodegen.INTERFACE_ONLY, "true"); + codegen.additionalProperties().put(SpringCodegen.USE_BEANVALIDATION, "true"); + codegen.additionalProperties().put(SpringCodegen.PERFORM_BEANVALIDATION, "true"); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.controller"); + + ClientOptInput input = new ClientOptInput() + .openAPI(openAPI) + .config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + Map files = generator.opts(input).generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + JavaFileAssert.assertThat(files.get("TestObject.java")) + .printFileContent() + .assertMethod("equals") + .bodyContainsLines("return equalsNullable(this.picture, testObject.picture);"); + + } + + @Test + public void shouldNotUseEqualsNullableForArrayWhenNotSetInConfig_issue13385() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_13385_2.yml", null, new ParseOptions()).getOpenAPI(); + SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary(SPRING_BOOT); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(SpringCodegen.INTERFACE_ONLY, "true"); + codegen.additionalProperties().put(SpringCodegen.USE_BEANVALIDATION, "true"); + codegen.additionalProperties().put(SpringCodegen.PERFORM_BEANVALIDATION, "true"); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.controller"); + + ClientOptInput input = new ClientOptInput() + .openAPI(openAPI) + .config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + Map files = generator.opts(input).generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + JavaFileAssert.assertThat(files.get("TestObject.java")) + .printFileContent() + .assertMethod("equals") + .bodyContainsLines("return Arrays.equals(this.picture, testObject.picture);"); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinClientCodegenModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinClientCodegenModelTest.java index af6005a248..902b7fd916 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinClientCodegenModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinClientCodegenModelTest.java @@ -18,48 +18,66 @@ package org.openapitools.codegen.kotlin; import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.DateTimeSchema; +import io.swagger.v3.oas.models.media.IntegerSchema; +import io.swagger.v3.oas.models.media.MapSchema; +import io.swagger.v3.oas.models.media.ObjectSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.DefaultGenerator; import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.languages.KotlinClientCodegen; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @SuppressWarnings("static-method") public class KotlinClientCodegenModelTest { private Schema getArrayTestSchema() { return new ObjectSchema() - .description("a sample model") - .addProperties("id", new IntegerSchema().format("int64")) - .addProperties("examples", new ArraySchema().items(new StringSchema())) - .addRequiredItem("id"); + .description("a sample model") + .addProperties("id", new IntegerSchema().format("int64")) + .addProperties("examples", new ArraySchema().items(new StringSchema())) + .addRequiredItem("id"); } private Schema getSimpleSchema() { return new ObjectSchema() - .description("a sample model") - .addProperties("id", new IntegerSchema().format("int64")) - .addProperties("name", new StringSchema()) - .addProperties("createdAt", new DateTimeSchema()) - .addRequiredItem("id") - .addRequiredItem("name"); + .description("a sample model") + .addProperties("id", new IntegerSchema().format("int64")) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addRequiredItem("id") + .addRequiredItem("name"); } private Schema getMapSchema() { return new ObjectSchema() - .description("a sample model") - .addProperties("mapping", new MapSchema() - .additionalProperties(new StringSchema())); + .description("a sample model") + .addProperties("mapping", new MapSchema() + .additionalProperties(new StringSchema())); } private Schema getComplexSchema() { return new ObjectSchema() - .description("a sample model") - .addProperties("child", new ObjectSchema().$ref("#/components/schemas/Child")); + .description("a sample model") + .addProperties("child", new ObjectSchema().$ref("#/components/schemas/Child")); } @Test(description = "convert a simple model") @@ -321,11 +339,11 @@ public class KotlinClientCodegenModelTest { @DataProvider(name = "modelNames") public static Object[][] modelNames() { return new Object[][]{ - {"TestNs.TestClass", new ModelNameTest("TestNs.TestClass", "TestNsTestClass")}, - {"$", new ModelNameTest("$", "Dollar")}, - {"for", new ModelNameTest("`for`", "For")}, - {"One properties = new HashMap<>(); + properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); + + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("kotlin") + .setLibrary("jvm-retrofit2") + .setAdditionalProperties(properties) + .setInputSpec("src/test/resources/3_0/issue4808.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + + Assert.assertEquals(files.size(), 28); + TestUtils.assertFileContains(Paths.get(output + "/src/main/kotlin/xyz/abcdef/api/DefaultApi.kt"), + "fun getSomeValue(@Query(\"since\") since: kotlin.String? = null, @Query(\"sinceBuild\") sinceBuild: kotlin.String? = null, @Query(\"maxBuilds\") maxBuilds: kotlin.Int? = null, @Query(\"maxWaitSecs\") maxWaitSecs: kotlin.Int? = null)" + ); + } + private static class ModelNameTest { - private String expectedName; - private String expectedClassName; + private final String expectedName; + private final String expectedClassName; private ModelNameTest(String nameAndClass) { this.expectedName = nameAndClass; diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java index dd11b886a9..f4ed0384bf 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java @@ -19,7 +19,7 @@ package org.openapitools.codegen.options; import com.google.common.collect.ImmutableMap; import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.PythonClientCodegen; +import org.openapitools.codegen.languages.PythonPriorClientCodegen; import java.util.Map; @@ -42,7 +42,7 @@ public class PythonClientOptionsProvider implements OptionsProvider { @Override public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(PythonClientCodegen.PACKAGE_URL, PACKAGE_URL_VALUE) + return builder.put(PythonPriorClientCodegen.PACKAGE_URL, PACKAGE_URL_VALUE) .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.PROJECT_NAME, PROJECT_NAME_VALUE) .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) @@ -50,9 +50,9 @@ public class PythonClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.SOURCECODEONLY_GENERATION, "false") .put(CodegenConstants.LIBRARY, "urllib3") .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT) - .put(PythonClientCodegen.USE_NOSE, USE_NOSE_VALUE) - .put(PythonClientCodegen.RECURSION_LIMIT, RECURSION_LIMIT) - .put(PythonClientCodegen.PYTHON_ATTR_NONE_IF_UNSET, PYTHON_ATTR_NONE_IF_UNSET) + .put(PythonPriorClientCodegen.USE_NOSE, USE_NOSE_VALUE) + .put(PythonPriorClientCodegen.RECURSION_LIMIT, RECURSION_LIMIT) + .put(PythonPriorClientCodegen.PYTHON_ATTR_NONE_IF_UNSET, PYTHON_ATTR_NONE_IF_UNSET) .put(CodegenConstants.INIT_REQUIRED_VARS, INIT_REQUIRED_VARS) .build(); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java index 807c0035bd..45a656dd3c 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java @@ -24,8 +24,8 @@ import org.openapitools.codegen.languages.RubyClientCodegen; import java.util.Map; public class RubyClientOptionsProvider implements OptionsProvider { - public static final String GEM_NAME_VALUE = "swagger_client_ruby"; - public static final String MODULE_NAME_VALUE = "SwaggerClientRuby"; + public static final String GEM_NAME_VALUE = "openapi_client_ruby"; + public static final String MODULE_NAME_VALUE = "OpenApiClientRuby"; public static final String GEM_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SORT_PARAMS_VALUE = "false"; public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; @@ -35,12 +35,13 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String GEM_HOMEPAGE_VALUE = "homepage"; public static final String GEM_SUMMARY_VALUE = "summary"; public static final String GEM_DESCRIPTION_VALUE = "description"; - public static final String GEM_AUTHOR_VALUE = "foo"; + public static final String GEM_AUTHOR_VALUE = "foo"; public static final String GEM_AUTHOR_EMAIL_VALUE = "foo"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; public static final String LIBRARY = "typhoeus"; public static final String ENUM_UNKNOWN_DEFAULT_CASE_VALUE = "false"; + public static final String USE_AUTOLOAD_VALUE = "true"; @Override public String getLanguage() { @@ -70,6 +71,7 @@ public class RubyClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true") .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true") .put(CodegenConstants.ENUM_UNKNOWN_DEFAULT_CASE, ENUM_UNKNOWN_DEFAULT_CASE_VALUE) + .put(RubyClientCodegen.USE_AUTOLOAD, USE_AUTOLOAD_VALUE) .build(); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java index b41f76f9a9..79c19e189a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java @@ -101,6 +101,7 @@ public class Swift5OptionsProvider implements OptionsProvider { .put(Swift5ClientCodegen.HASHABLE_MODELS, HASHABLE_MODELS_VALUE) .put(Swift5ClientCodegen.USE_JSON_ENCODABLE, USE_JSON_ENCODABLE_VALUE) .put(Swift5ClientCodegen.MAP_FILE_BINARY_TO_DATA, "false") + .put(Swift5ClientCodegen.USE_CUSTOM_DATE_WITHOUT_TIME, "false") .put(Swift5ClientCodegen.USE_CLASSES, "false") .put(CodegenConstants.ENUM_UNKNOWN_DEFAULT_CASE, ENUM_UNKNOWN_DEFAULT_CASE_VALUE) .build(); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpSymfonyServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpSymfonyServerCodegenTest.java index c8bad04db1..b5144ff762 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpSymfonyServerCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpSymfonyServerCodegenTest.java @@ -17,11 +17,23 @@ package org.openapitools.codegen.php; +import java.io.File; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openapitools.codegen.ClientOptInput; import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.openapitools.codegen.languages.AbstractPhpCodegen; import org.openapitools.codegen.languages.PhpSymfonyServerCodegen; import org.testng.Assert; import org.testng.annotations.Test; + public class PhpSymfonyServerCodegenTest { @Test @@ -53,4 +65,112 @@ public class PhpSymfonyServerCodegenTest { Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); } + @Test + public void testGeneratePing() throws Exception { + Map properties = new HashMap<>(); + + File output = Files.createTempDirectory("test").toFile(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("php-symfony") + .setAdditionalProperties(properties) + .setInputSpec("src/test/resources/3_0/ping.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + + Assert.assertEquals(files.size(), 33); + TestUtils.ensureContainsFile(files, output, ".coveralls.yml"); + TestUtils.ensureContainsFile(files, output, ".gitignore"); + TestUtils.ensureContainsFile(files, output, ".openapi-generator-ignore"); + TestUtils.ensureContainsFile(files, output, ".openapi-generator/FILES"); + TestUtils.ensureContainsFile(files, output, ".openapi-generator/VERSION"); + TestUtils.ensureContainsFile(files, output, ".php_cs.dist"); + TestUtils.ensureContainsFile(files, output, ".travis.yml"); + TestUtils.ensureContainsFile(files, output, "autoload.php"); + TestUtils.ensureContainsFile(files, output, "composer.json"); + TestUtils.ensureContainsFile(files, output, "git_push.sh"); + TestUtils.ensureContainsFile(files, output, "phpunit.xml.dist"); + TestUtils.ensureContainsFile(files, output, "README.md"); + TestUtils.ensureContainsFile(files, output, "Api/ApiServer.php"); + TestUtils.ensureContainsFile(files, output, "Api/DefaultApiInterface.php"); + TestUtils.ensureContainsFile(files, output, "Controller/Controller.php"); + TestUtils.ensureContainsFile(files, output, "Controller/DefaultController.php"); + TestUtils.ensureContainsFile(files, output, "DependencyInjection/Compiler/OpenAPIServerApiPass.php"); + TestUtils.ensureContainsFile(files, output, "DependencyInjection/OpenAPIServerExtension.php"); + TestUtils.ensureContainsFile(files, output, "docs/Api/DefaultApiInterface.md"); + TestUtils.ensureContainsFile(files, output, "OpenAPIServerBundle.php"); + TestUtils.ensureContainsFile(files, output, "Resources/config/routing.yaml"); + TestUtils.ensureContainsFile(files, output, "Resources/config/services.yaml"); + TestUtils.ensureContainsFile(files, output, "Service/JmsSerializer.php"); + TestUtils.ensureContainsFile(files, output, "Service/SerializerInterface.php"); + TestUtils.ensureContainsFile(files, output, "Service/StrictJsonDeserializationVisitor.php"); + TestUtils.ensureContainsFile(files, output, "Service/StrictJsonDeserializationVisitorFactory.php"); + TestUtils.ensureContainsFile(files, output, "Service/SymfonyValidator.php"); + TestUtils.ensureContainsFile(files, output, "Service/TypeMismatchException.php"); + TestUtils.ensureContainsFile(files, output, "Service/ValidatorInterface.php"); + TestUtils.ensureContainsFile(files, output, "Tests/Api/DefaultApiInterfaceTest.php"); + TestUtils.ensureContainsFile(files, output, "Tests/AppKernel.php"); + TestUtils.ensureContainsFile(files, output, "Tests/Controller/ControllerTest.php"); + TestUtils.ensureContainsFile(files, output, "Tests/test_config.yaml"); + + output.deleteOnExit(); + } + + @Test + public void testGeneratePingWithDifferentSourceDirectory() throws Exception { + Map properties = new HashMap<>(); + properties.put(AbstractPhpCodegen.SRC_BASE_PATH, "src"); + + File output = Files.createTempDirectory("test").toFile(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("php-symfony") + .setAdditionalProperties(properties) + .setInputSpec("src/test/resources/3_0/ping.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + + Assert.assertEquals(files.size(), 33); + TestUtils.ensureContainsFile(files, output, ".coveralls.yml"); + TestUtils.ensureContainsFile(files, output, ".gitignore"); + TestUtils.ensureContainsFile(files, output, ".openapi-generator-ignore"); + TestUtils.ensureContainsFile(files, output, ".openapi-generator/FILES"); + TestUtils.ensureContainsFile(files, output, ".openapi-generator/VERSION"); + TestUtils.ensureContainsFile(files, output, ".php_cs.dist"); + TestUtils.ensureContainsFile(files, output, ".travis.yml"); + TestUtils.ensureContainsFile(files, output, "autoload.php"); + TestUtils.ensureContainsFile(files, output, "composer.json"); + TestUtils.ensureContainsFile(files, output, "git_push.sh"); + TestUtils.ensureContainsFile(files, output, "phpunit.xml.dist"); + TestUtils.ensureContainsFile(files, output, "README.md"); + TestUtils.ensureContainsFile(files, output, "docs/Api/DefaultApiInterface.md"); + TestUtils.ensureContainsFile(files, output, "src/Api/ApiServer.php"); + TestUtils.ensureContainsFile(files, output, "src/Api/DefaultApiInterface.php"); + TestUtils.ensureContainsFile(files, output, "src/Controller/Controller.php"); + TestUtils.ensureContainsFile(files, output, "src/Controller/DefaultController.php"); + TestUtils.ensureContainsFile(files, output, "src/DependencyInjection/Compiler/OpenAPIServerApiPass.php"); + TestUtils.ensureContainsFile(files, output, "src/DependencyInjection/OpenAPIServerExtension.php"); + TestUtils.ensureContainsFile(files, output, "src/OpenAPIServerBundle.php"); + TestUtils.ensureContainsFile(files, output, "src/Resources/config/routing.yaml"); + TestUtils.ensureContainsFile(files, output, "src/Resources/config/services.yaml"); + TestUtils.ensureContainsFile(files, output, "src/Service/JmsSerializer.php"); + TestUtils.ensureContainsFile(files, output, "src/Service/SerializerInterface.php"); + TestUtils.ensureContainsFile(files, output, "src/Service/StrictJsonDeserializationVisitor.php"); + TestUtils.ensureContainsFile(files, output, "src/Service/StrictJsonDeserializationVisitorFactory.php"); + TestUtils.ensureContainsFile(files, output, "src/Service/SymfonyValidator.php"); + TestUtils.ensureContainsFile(files, output, "src/Service/TypeMismatchException.php"); + TestUtils.ensureContainsFile(files, output, "src/Service/ValidatorInterface.php"); + TestUtils.ensureContainsFile(files, output, "src/Tests/Api/DefaultApiInterfaceTest.php"); + TestUtils.ensureContainsFile(files, output, "src/Tests/AppKernel.php"); + TestUtils.ensureContainsFile(files, output, "src/Tests/Controller/ControllerTest.php"); + TestUtils.ensureContainsFile(files, output, "src/Tests/test_config.yaml"); + + output.deleteOnExit(); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientOptionsTest.java deleted file mode 100644 index e423c6e858..0000000000 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientOptionsTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) - * Copyright 2018 SmartBear Software - * - * 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.python; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.PythonClientCodegen; -import org.openapitools.codegen.options.PythonClientOptionsProvider; -import org.testng.Assert; - -import java.io.File; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class PythonClientOptionsTest extends AbstractOptionsTest { - private PythonClientCodegen clientCodegen = mock(PythonClientCodegen.class, mockSettings); - - public PythonClientOptionsTest() { - super(new PythonClientOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void verifyOptions() { - Assert.assertEquals(clientCodegen.packagePath(), PythonClientOptionsProvider.PACKAGE_NAME_VALUE.replace('.', File.separatorChar)); - - verify(clientCodegen).setPackageName(PythonClientOptionsProvider.PACKAGE_NAME_VALUE); - verify(clientCodegen).setProjectName(PythonClientOptionsProvider.PROJECT_NAME_VALUE); - verify(clientCodegen).setPackageVersion(PythonClientOptionsProvider.PACKAGE_VERSION_VALUE); - verify(clientCodegen).setPackageUrl(PythonClientOptionsProvider.PACKAGE_URL_VALUE); - verify(clientCodegen).setUseNose(PythonClientOptionsProvider.USE_NOSE_VALUE); - } -} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientTest.java index 028316f419..47e5569c71 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientTest.java @@ -15,521 +15,186 @@ */ package org.openapitools.codegen.python; -import com.google.common.io.Resources; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import org.openapitools.codegen.config.CodegenConfigurator; -import com.google.common.collect.Sets; +import com.google.common.io.Resources; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.*; -import io.swagger.v3.parser.util.SchemaTypeUtil; - -import java.io.File; -import java.math.BigDecimal; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.openapitools.codegen.*; +import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.languages.PythonClientCodegen; import org.openapitools.codegen.utils.ModelUtils; import org.testng.Assert; -import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + @SuppressWarnings("static-method") public class PythonClientTest { - @Test(description = "convert a python model with dots") - public void modelTest() { - final OpenAPI openAPI= TestUtils.parseFlattenSpec("src/test/resources/2_0/v1beta3.json"); - final DefaultCodegen codegen = new PythonClientCodegen(); - codegen.setOpenAPI(openAPI); + @Test(description = "tests RecursiveExampleValueWithCycle") + public void testRecursiveExampleValueWithCycle() throws Exception { - codegen.setOpenAPI(openAPI); - final CodegenModel simpleName = codegen.fromModel("v1beta3.Binding", openAPI.getComponents().getSchemas().get("v1beta3.Binding")); - Assert.assertEquals(simpleName.name, "v1beta3.Binding"); - Assert.assertEquals(simpleName.classname, "V1beta3Binding"); - Assert.assertEquals(simpleName.classVarName, "v1beta3_binding"); - - codegen.setOpenAPI(openAPI); - final CodegenModel compoundName = codegen.fromModel("v1beta3.ComponentStatus", openAPI.getComponents().getSchemas().get("v1beta3.ComponentStatus")); - Assert.assertEquals(compoundName.name, "v1beta3.ComponentStatus"); - Assert.assertEquals(compoundName.classname, "V1beta3ComponentStatus"); - Assert.assertEquals(compoundName.classVarName, "v1beta3_component_status"); - - final String path = "/api/v1beta3/namespaces/{namespaces}/bindings"; - final Operation operation = openAPI.getPaths().get(path).getPost(); - final CodegenOperation codegenOperation = codegen.fromOperation(path, "post", operation, null); - Assert.assertEquals(codegenOperation.returnType, "V1beta3Binding"); - Assert.assertEquals(codegenOperation.returnBaseType, "V1beta3Binding"); - } - - @Test(description = "convert a simple java model") - public void simpleModelTest() { - final Schema schema = new Schema() - .description("a sample model") - .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) - .addProperties("name", new StringSchema()) - .addProperties("createdAt", new DateTimeSchema()) - .addRequiredItem("id") - .addRequiredItem("name"); - final DefaultCodegen codegen = new PythonClientCodegen(); - OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema); - codegen.setOpenAPI(openAPI); - final CodegenModel cm = codegen.fromModel("sample", schema); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 3); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.dataType, "int"); - Assert.assertEquals(property1.name, "id"); - Assert.assertNull(property1.defaultValue); - Assert.assertEquals(property1.baseType, "int"); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "name"); - Assert.assertEquals(property2.dataType, "str"); - Assert.assertEquals(property2.name, "name"); - Assert.assertNull(property2.defaultValue); - Assert.assertEquals(property2.baseType, "str"); - Assert.assertTrue(property2.required); - Assert.assertTrue(property2.isPrimitiveType); - - final CodegenProperty property3 = cm.vars.get(2); - Assert.assertEquals(property3.baseName, "createdAt"); - Assert.assertEquals(property3.dataType, "datetime"); - Assert.assertEquals(property3.name, "created_at"); - Assert.assertNull(property3.defaultValue); - Assert.assertEquals(property3.baseType, "datetime"); - Assert.assertFalse(property3.required); - } - - @Test(description = "convert a model with list property") - public void listPropertyTest() { - final Schema model = new Schema() - .description("a sample model") - .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) - .addProperties("urls", new ArraySchema() - .items(new StringSchema())) - .addRequiredItem("id"); - final DefaultCodegen codegen = new PythonClientCodegen(); - OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); - codegen.setOpenAPI(openAPI); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 2); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "id"); - Assert.assertEquals(property1.dataType, "int"); - Assert.assertEquals(property1.name, "id"); - Assert.assertNull(property1.defaultValue); - Assert.assertEquals(property1.baseType, "int"); - Assert.assertTrue(property1.required); - Assert.assertTrue(property1.isPrimitiveType); - - final CodegenProperty property2 = cm.vars.get(1); - Assert.assertEquals(property2.baseName, "urls"); - Assert.assertEquals(property2.dataType, "[str]"); - Assert.assertEquals(property2.name, "urls"); - Assert.assertNull(property2.defaultValue); - Assert.assertEquals(property2.baseType, "list"); - Assert.assertEquals(property2.containerType, "array"); - Assert.assertFalse(property2.required); - Assert.assertTrue(property2.isPrimitiveType); - Assert.assertTrue(property2.isContainer); - } - - @Test(description = "convert a model with a map property") - public void mapPropertyTest() { - final Schema model = new Schema() - .description("a sample model") - .addProperties("translations", new MapSchema() - .additionalProperties(new StringSchema())) - .addRequiredItem("id"); - final DefaultCodegen codegen = new PythonClientCodegen(); - OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); - codegen.setOpenAPI(openAPI); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "translations"); - Assert.assertEquals(property1.dataType, "{str: (str,)}"); - Assert.assertEquals(property1.name, "translations"); - Assert.assertEquals(property1.baseType, "dict"); - Assert.assertEquals(property1.containerType, "map"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - Assert.assertTrue(property1.isPrimitiveType); - } - - @Test(description = "convert a model with complex property") - public void complexPropertyTest() { - final DefaultCodegen codegen = new PythonClientCodegen(); - OpenAPI openAPI = TestUtils.createOpenAPI(); - final Schema model = new Schema() - .description("a sample model") - .addProperties("children", new Schema().$ref("#/components/schemas/Children")); - final Schema children = new Schema() - .type("object") - .addProperties("number", new Schema().type("integer")); - openAPI.getComponents().addSchemas("sample", model); - openAPI.getComponents().addSchemas("Children", children); - codegen.setOpenAPI(openAPI); - - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.dataType, "Children"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.baseType, "Children"); - Assert.assertFalse(property1.required); - Assert.assertFalse(property1.isContainer); - } - - @Test(description = "convert a model with complex list property") - public void complexListPropertyTest() { - final DefaultCodegen codegen = new PythonClientCodegen(); - OpenAPI openAPI = TestUtils.createOpenAPI(); - final Schema model = new Schema() - .description("a sample model") - .addProperties("children", new ArraySchema() - .items(new Schema().$ref("#/components/schemas/Children"))); - final Schema children = new Schema() - .type("object") - .addProperties("number", new Schema().type("integer")); - openAPI.getComponents().addSchemas("sample", model); - openAPI.getComponents().addSchemas("Children", children); - codegen.setOpenAPI(openAPI); - - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.dataType, "[Children]"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.baseType, "list"); - Assert.assertEquals(property1.containerType, "array"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - @Test(description = "convert a model with complex map property") - public void complexMapPropertyTest() { - final DefaultCodegen codegen = new PythonClientCodegen(); - OpenAPI openAPI = TestUtils.createOpenAPI(); - final Schema model = new Schema() - .description("a sample model") - .addProperties("children", new MapSchema() - .additionalProperties(new Schema().$ref("#/components/schemas/Children"))); - final Schema children = new Schema() - .type("object") - .addProperties("number", new Schema().type("integer")); - openAPI.getComponents().addSchemas("sample", model); - openAPI.getComponents().addSchemas("Children", children); - codegen.setOpenAPI(openAPI); - - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a sample model"); - Assert.assertEquals(cm.vars.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - - final CodegenProperty property1 = cm.vars.get(0); - Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.dataType, "{str: (Children,)}"); - Assert.assertEquals(property1.name, "children"); - Assert.assertEquals(property1.baseType, "dict"); - Assert.assertEquals(property1.containerType, "map"); - Assert.assertFalse(property1.required); - Assert.assertTrue(property1.isContainer); - } - - - // should not start with 'null'. need help from the community to investigate further - @Test(description = "convert an array model") - public void arrayModelTest() { + final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/issue_7532.yaml"); final PythonClientCodegen codegen = new PythonClientCodegen(); - OpenAPI openAPI = TestUtils.createOpenAPI(); - - final Schema model = new ArraySchema() - .items(new Schema().$ref("#/components/schemas/Children")) - .description("an array model"); - final Schema children = new Schema() - .type("object") - .addProperties("number", new Schema().type("integer")); - openAPI.getComponents().addSchemas("sample", model); - openAPI.getComponents().addSchemas("Children", children); codegen.setOpenAPI(openAPI); + Schema schemaWithCycleInTreesProperty = openAPI.getComponents().getSchemas().get("Forest"); + String exampleValue = codegen.toExampleValue(schemaWithCycleInTreesProperty, null); - final CodegenModel cm = codegen.fromModel("sample", model); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.classVarName, "sample"); - Assert.assertEquals(cm.description, "an array model"); - Assert.assertEquals(cm.vars.size(), 0); // the array model has no vars - Assert.assertEquals(cm.parent, "list"); - Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); - - final Map childExample = new HashMap<>(); - childExample.put("number", 3); - final List> example = Arrays.asList(childExample); - String exampleValue = codegen.toExampleValue(model, example); - Assert.assertEquals("[Children(number=1,),]", exampleValue.replaceAll("\\s+","")); - } - - // should not start with 'null'. need help from the community to investigate further - @Test(description = "convert a map model") - public void mapModelTest() { - final DefaultCodegen codegen = new PythonClientCodegen(); - OpenAPI openAPI = TestUtils.createOpenAPI(); - final Schema sample = new Schema() - .description("a map model") - .additionalProperties(new Schema().$ref("#/components/schemas/Children")); - final Schema children = new Schema() - .type("object") - .addProperties("number", new Schema().type("integer")); - openAPI.getComponents().addSchemas("sample", sample); - openAPI.getComponents().addSchemas("Children", children); - codegen.setOpenAPI(openAPI); - final CodegenModel cm = codegen.fromModel("sample", sample); - - Assert.assertEquals(cm.name, "sample"); - Assert.assertEquals(cm.classname, "Sample"); - Assert.assertEquals(cm.description, "a map model"); - Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.parent, null); - Assert.assertEquals(cm.imports.size(), 1); - } - - @Test(description = "parse date and date-time example value") - public void parseDateAndDateTimeExamplesTest() { - final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml"); - final DefaultCodegen codegen = new PythonClientCodegen(); - - Schema modelSchema = ModelUtils.getSchema(openAPI, "DateTimeTest"); - String defaultValue = codegen.toDefaultValue(modelSchema); - Assert.assertEquals(defaultValue, "dateutil_parser('2010-01-01T10:10:10.000111+01:00')"); - } - - @Test(description = "format imports of models containing special characters") - public void importSpecialModelNameTest() { - final PythonClientCodegen codegen = new PythonClientCodegen(); - - String importValue = codegen.toModelImport("special.ModelName"); - Assert.assertEquals(importValue, "from models.special_model_name import SpecialModelName"); - } - - @Test(description = "format imports of models containing special characters") - public void defaultSettingInPrimitiveModelWithValidations() { - final PythonClientCodegen codegen = new PythonClientCodegen(); - - OpenAPI openAPI = TestUtils.createOpenAPI(); - final Schema noDefault = new Schema() - .type("number") - .minimum(new BigDecimal("10")); - final Schema hasDefault = new Schema() - .type("number") - .minimum(new BigDecimal("10")); - hasDefault.setDefault("15.0"); - final Schema noDefaultEumLengthOne = new Schema() - .type("number") - .minimum(new BigDecimal("10")); - noDefaultEumLengthOne.setEnum(Arrays.asList("15.0")); - openAPI.getComponents().addSchemas("noDefaultModel", noDefault); - openAPI.getComponents().addSchemas("hasDefaultModel", hasDefault); - openAPI.getComponents().addSchemas("noDefaultEumLengthOneModel", noDefaultEumLengthOne); - codegen.setOpenAPI(openAPI); - - final CodegenModel noDefaultModel = codegen.fromModel("noDefaultModel", noDefault); - Assert.assertEquals(noDefaultModel.defaultValue, null); - Assert.assertEquals(noDefaultModel.hasRequired, true); - - final CodegenModel hasDefaultModel = codegen.fromModel("hasDefaultModel", hasDefault); - Assert.assertEquals(hasDefaultModel.defaultValue, "15.0"); - Assert.assertEquals(hasDefaultModel.hasRequired, false); - - final CodegenModel noDefaultEumLengthOneModel = codegen.fromModel("noDefaultEumLengthOneModel", noDefaultEumLengthOne); - Assert.assertEquals(noDefaultEumLengthOneModel.defaultValue, "15.0"); - Assert.assertEquals(noDefaultEumLengthOneModel.hasRequired, false); + String expectedValue = Resources.toString( + Resources.getResource("3_0/issue_7532_tree_example_value_expected.txt"), + StandardCharsets.UTF_8); + expectedValue = expectedValue.replaceAll("\\r\\n", "\n"); + Assert.assertEquals(exampleValue.trim(), expectedValue.trim()); } @Test - public void testObjectModelWithRefedAdditionalPropertiesIsGenerated() throws Exception { - File output = Files.createTempDirectory("test").toFile(); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("python") - .setInputSpec("src/test/resources/3_0/issue_7372.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - - TestUtils.ensureContainsFile(files, output, "openapi_client/model/a.py"); - TestUtils.ensureContainsFile(files, output, "openapi_client/model/b.py"); - output.deleteOnExit(); + public void testSpecWithTooLowVersionThrowsException() throws RuntimeException { + final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/2_0/petstore.yaml"); + final PythonClientCodegen codegen = new PythonClientCodegen(); + codegen.preprocessOpenAPI(openAPI); } @Test - public void testFreeFormSchemas() throws Exception { - File output = Files.createTempDirectory("test").toFile(); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("python") - .setInputSpec("src/test/resources/3_0/issue_7361.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - - TestUtils.ensureContainsFile(files, output, "openapi_client/model/free_form_with_validation.py"); - TestUtils.ensureContainsFile(files, output, "openapi_client/model/free_form_interface.py"); - TestUtils.ensureDoesNotContainsFile(files, output, "openapi_client/model/free_form.py"); - output.deleteOnExit(); + public void testSpecWithAcceptableVersion() { + final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/petstore.yaml"); + final PythonClientCodegen codegen = new PythonClientCodegen(); + codegen.preprocessOpenAPI(openAPI); + Assert.assertEquals(openAPI.getOpenapi() , "3.0.0"); + Assert.assertTrue(openAPI.getExtensions() == null); } - @Test(description = "tests ObjectWithValidations") - public void testObjectWithValidations() { - final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_7361.yaml"); - final DefaultCodegen codegen = new PythonClientCodegen(); - codegen.setOpenAPI(openAPI); - - String modelName = "FreeFormWithValidation"; - Schema modelSchema = ModelUtils.getSchema(openAPI, modelName); - final CodegenModel model = codegen.fromModel(modelName, modelSchema); - Assert.assertEquals((int) model.getMinProperties(), 1); + @Test + public void testSpecWithAcceptableVersionAndExtension() { + final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/issue_12196.yaml"); + final PythonClientCodegen codegen = new PythonClientCodegen(); + codegen.preprocessOpenAPI(openAPI); + Assert.assertEquals(openAPI.getOpenapi() , "3.0.0"); + Assert.assertFalse(openAPI.getExtensions().isEmpty()); + Assert.assertFalse(openAPI.getExtensions().containsValue("x-original-swagger-version")); } - @Test(description = "tests RegexObjects") - public void testRegexObjects() { - final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_11521.yaml"); - final DefaultCodegen codegen = new PythonClientCodegen(); - codegen.setOpenAPI(openAPI); + @Test(description = "tests GeoJson Example for GeoJsonGeometry") + public void testRecursiveGeoJsonExampleWhenTypeIsGeoJsonGeometry() throws IOException { + + testEndpointExampleValue("/geojson", + "src/test/resources/3_0/issue_13043_recursive_model.yaml", + "3_0/issue_13043_recursive_model_expected_value.txt"); + - String modelName = "DateTimeObject"; - Schema modelSchema = ModelUtils.getSchema(openAPI, modelName); - final CodegenModel model = codegen.fromModel(modelName, modelSchema); - final CodegenProperty property1 = model.vars.get(0); - Assert.assertEquals(property1.baseName, "datetime"); - Assert.assertEquals(property1.pattern, "/[\\d]{4}-[\\d]{2}-[\\d]{2}T[\\d]{1,2}:[\\d]{2}Z/"); - Assert.assertEquals(property1.vendorExtensions.get("x-regex"), "[\\d]{4}-[\\d]{2}-[\\d]{2}T[\\d]{1,2}:[\\d]{2}Z"); } - @Test(description = "tests RecursiveToExample") - public void testRecursiveToExample() throws IOException { - final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_8052_recursive_model.yaml"); + @Test(description = "tests GeoJson Example for GeometryCollection") + public void testRecursiveGeoJsonExampleWhenTypeIsGeometryCollection() throws IOException { + + testEndpointExampleValue("/geojson_geometry_collection", + "src/test/resources/3_0/issue_13043_recursive_model.yaml", + "3_0/issue_13043_geometry_collection_expected_value.txt"); + + } + + private void testEndpointExampleValue(String endpoint, String specFilePath, String expectedAnswerPath) throws IOException { + final OpenAPI openAPI = TestUtils.parseFlattenSpec(specFilePath); final PythonClientCodegen codegen = new PythonClientCodegen(); codegen.setOpenAPI(openAPI); - final Operation operation = openAPI.getPaths().get("/geojson").getPost(); + final Operation operation = openAPI.getPaths().get(endpoint).getPost(); Schema schema = ModelUtils.getSchemaFromRequestBody(operation.getRequestBody()); String exampleValue = codegen.toExampleValue(schema, null); // uncomment if you need to regenerate the expected value - // PrintWriter printWriter = new PrintWriter("src/test/resources/3_0/issue_8052_recursive_model_expected_value.txt"); + // PrintWriter printWriter = new PrintWriter("src/test/resources/" + expectedAnswerPath); // printWriter.write(exampleValue); // printWriter.close(); // org.junit.Assert.assertTrue(false); String expectedValue = Resources.toString( - Resources.getResource("3_0/issue_8052_recursive_model_expected_value.txt"), + Resources.getResource(expectedAnswerPath), StandardCharsets.UTF_8); expectedValue = expectedValue.replaceAll("\\r\\n", "\n"); - - Assert.assertEquals(exampleValue.trim(), expectedValue.trim()); } - @Test(description = "tests NoProxyPyClient") - public void testNoProxyPyClient() throws Exception { - - final String gen = "python"; - final String spec = "src/test/resources/3_0/petstore.yaml"; - + @Test + public void testApiTestsNotGenerated() throws Exception { File output = Files.createTempDirectory("test").toFile(); + + Map globalProperties = Collections.singletonMap("apiTests", "false"); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName(gen) - .setInputSpec(spec) + .setGlobalProperties(globalProperties) + .setGeneratorName("python") + .setInputSpec("src/test/resources/3_0/petstore.yaml") .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); List files = generator.opts(clientOptInput).generate(); + Assert.assertTrue(files.size() > 0); - for (String f : new String[] { "openapi_client/configuration.py", "openapi_client/rest.py" } ) { - TestUtils.ensureContainsFile(files, output, f); - Path p = output.toPath().resolve(f); - TestUtils.assertFileContains(p, "no_proxy"); - } + Path pathThatShouldNotExist = output.toPath().resolve("openapi_client/test/test_paths"); + Assert.assertFalse(Files.isDirectory(pathThatShouldNotExist)); + output.deleteOnExit(); } - @DataProvider - public Object[][] testToModelData() { - return new Object[][] { - new Object[] {"", "", "foo", "Foo"}, - new Object[] {"Abc", "", "foo", "AbcFoo"}, - new Object[] {"", "Abc", "foo", "FooAbc"}, - new Object[] {"Abc", "Xyz", "foo", "AbcFooXyz"}, + @Test + public void testApisNotGenerated() throws Exception { + File output = Files.createTempDirectory("test").toFile(); - new Object[] {"", "", "1", "Model1"}, - new Object[] {"Abc", "", "1", "Abc1"}, - new Object[] {"", "Abc", "1", "Model1Abc"}, - new Object[] {"Abc", "Xyz", "1", "Abc1Xyz"}, + Map globalProperties = Collections.singletonMap("models", ""); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGlobalProperties(globalProperties) + .setGeneratorName("python") + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - new Object[] {"", "", "and", "ModelAnd"}, - new Object[] {"Abc", "", "and", "AbcAnd"}, - new Object[] {"", "Abc", "and", "AndAbc"}, - new Object[] {"Abc", "Xyz", "and", "AbcAndXyz"}, - }; + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + Assert.assertTrue(files.size() > 0); + + Path pathThatShouldNotExist = output.toPath().resolve("openapi_client/paths"); + Assert.assertFalse(Files.isDirectory(pathThatShouldNotExist)); + output.deleteOnExit(); } - @Test(dataProvider = "testToModelData") - public void testToModel(String prefix, String suffix, String input, String want) { + @Test + public void testRegexWithoutTrailingSlashWorks() { + OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/11_regex.yaml"); PythonClientCodegen codegen = new PythonClientCodegen(); - codegen.setModelNamePrefix(prefix); - codegen.setModelNameSuffix(suffix); - Assert.assertEquals(codegen.toModelName(input), want); + codegen.setOpenAPI(openAPI); + + String modelName = "UUID"; + Schema schema = openAPI.getComponents().getSchemas().get(modelName); + + CodegenModel cm = codegen.fromModel(modelName, schema); + String expectedRegexPattern = "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"; + Assert.assertEquals(cm.getPattern(), expectedRegexPattern); + Assert.assertEquals(cm.vendorExtensions.get("x-regex"), expectedRegexPattern); + Assert.assertFalse(cm.vendorExtensions.containsKey("x-modifiers")); } + @Test + public void testRegexWithMultipleFlagsWorks() { + OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/11_regex.yaml"); + PythonClientCodegen codegen = new PythonClientCodegen(); + codegen.setOpenAPI(openAPI); -} + String modelName = "StringWithRegexWithThreeFlags"; + Schema schema = openAPI.getComponents().getSchemas().get(modelName); + + CodegenModel cm = codegen.fromModel(modelName, schema); + String expectedRegexPattern = "a."; + Assert.assertEquals(cm.getPattern(), expectedRegexPattern); + Assert.assertEquals(cm.vendorExtensions.get("x-regex"), expectedRegexPattern); + Assert.assertEquals(cm.vendorExtensions.get("x-modifiers"), Arrays.asList("DOTALL", "IGNORECASE", "MULTILINE")); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonExperimentalClientTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonExperimentalClientTest.java deleted file mode 100644 index 1c1c69f830..0000000000 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonExperimentalClientTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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.python; - -import com.google.common.io.Resources; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.media.*; -import org.openapitools.codegen.*; -import org.openapitools.codegen.languages.PythonExperimentalClientCodegen; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.nio.charset.StandardCharsets; - -@SuppressWarnings("static-method") -public class PythonExperimentalClientTest { - - @Test(description = "tests RecursiveExampleValueWithCycle") - public void testRecursiveExampleValueWithCycle() throws Exception { - - final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/issue_7532.yaml"); - final PythonExperimentalClientCodegen codegen = new PythonExperimentalClientCodegen(); - codegen.setOpenAPI(openAPI); - Schema schemaWithCycleInTreesProperty = openAPI.getComponents().getSchemas().get("Forest"); - String exampleValue = codegen.toExampleValue(schemaWithCycleInTreesProperty, null); - - String expectedValue = Resources.toString( - Resources.getResource("3_0/issue_7532_tree_example_value_expected.txt"), - StandardCharsets.UTF_8); - expectedValue = expectedValue.replaceAll("\\r\\n", "\n"); - Assert.assertEquals(exampleValue.trim(), expectedValue.trim()); - } - - @Test - public void testSpecWithTooLowVersionThrowsException() throws RuntimeException { - final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/2_0/petstore.yaml"); - final PythonExperimentalClientCodegen codegen = new PythonExperimentalClientCodegen(); - codegen.preprocessOpenAPI(openAPI); - } - - @Test - public void testSpecWithAcceptableVersion() { - final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/petstore.yaml"); - final PythonExperimentalClientCodegen codegen = new PythonExperimentalClientCodegen(); - codegen.preprocessOpenAPI(openAPI); - Assert.assertEquals(openAPI.getOpenapi() , "3.0.0"); - Assert.assertTrue(openAPI.getExtensions() == null); - } - - @Test - public void testSpecWithAcceptableVersionAndExtension() { - final OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/issue_12196.yaml"); - final PythonExperimentalClientCodegen codegen = new PythonExperimentalClientCodegen(); - codegen.preprocessOpenAPI(openAPI); - Assert.assertEquals(openAPI.getOpenapi() , "3.0.0"); - Assert.assertFalse(openAPI.getExtensions().isEmpty()); - Assert.assertFalse(openAPI.getExtensions().containsValue("x-original-swagger-version")); - } - -} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonPriorClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonPriorClientOptionsTest.java new file mode 100644 index 0000000000..6c26a85ff9 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonPriorClientOptionsTest.java @@ -0,0 +1,54 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * 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.python; + +import org.openapitools.codegen.AbstractOptionsTest; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.languages.PythonPriorClientCodegen; +import org.openapitools.codegen.options.PythonClientOptionsProvider; +import org.testng.Assert; + +import java.io.File; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class PythonPriorClientOptionsTest extends AbstractOptionsTest { + private PythonPriorClientCodegen clientCodegen = mock(PythonPriorClientCodegen.class, mockSettings); + + public PythonPriorClientOptionsTest() { + super(new PythonClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void verifyOptions() { + Assert.assertEquals(clientCodegen.packagePath(), PythonClientOptionsProvider.PACKAGE_NAME_VALUE.replace('.', File.separatorChar)); + + verify(clientCodegen).setPackageName(PythonClientOptionsProvider.PACKAGE_NAME_VALUE); + verify(clientCodegen).setProjectName(PythonClientOptionsProvider.PROJECT_NAME_VALUE); + verify(clientCodegen).setPackageVersion(PythonClientOptionsProvider.PACKAGE_VERSION_VALUE); + verify(clientCodegen).setPackageUrl(PythonClientOptionsProvider.PACKAGE_URL_VALUE); + verify(clientCodegen).setUseNose(PythonClientOptionsProvider.USE_NOSE_VALUE); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonPriorClientTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonPriorClientTest.java new file mode 100644 index 0000000000..df88361a53 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonPriorClientTest.java @@ -0,0 +1,562 @@ +/* + * 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.python; +import com.google.common.io.Resources; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import org.openapitools.codegen.config.CodegenConfigurator; + +import com.google.common.collect.Sets; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.parser.util.SchemaTypeUtil; + +import java.io.File; +import java.math.BigDecimal; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.openapitools.codegen.*; +import org.openapitools.codegen.languages.PythonPriorClientCodegen; +import org.openapitools.codegen.utils.ModelUtils; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +@SuppressWarnings("static-method") +public class PythonPriorClientTest { + + @Test(description = "convert a python model with dots") + public void modelTest() { + final OpenAPI openAPI= TestUtils.parseFlattenSpec("src/test/resources/2_0/v1beta3.json"); + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + codegen.setOpenAPI(openAPI); + + codegen.setOpenAPI(openAPI); + final CodegenModel simpleName = codegen.fromModel("v1beta3.Binding", openAPI.getComponents().getSchemas().get("v1beta3.Binding")); + Assert.assertEquals(simpleName.name, "v1beta3.Binding"); + Assert.assertEquals(simpleName.classname, "V1beta3Binding"); + Assert.assertEquals(simpleName.classVarName, "v1beta3_binding"); + + codegen.setOpenAPI(openAPI); + final CodegenModel compoundName = codegen.fromModel("v1beta3.ComponentStatus", openAPI.getComponents().getSchemas().get("v1beta3.ComponentStatus")); + Assert.assertEquals(compoundName.name, "v1beta3.ComponentStatus"); + Assert.assertEquals(compoundName.classname, "V1beta3ComponentStatus"); + Assert.assertEquals(compoundName.classVarName, "v1beta3_component_status"); + + final String path = "/api/v1beta3/namespaces/{namespaces}/bindings"; + final Operation operation = openAPI.getPaths().get(path).getPost(); + final CodegenOperation codegenOperation = codegen.fromOperation(path, "post", operation, null); + Assert.assertEquals(codegenOperation.returnType, "V1beta3Binding"); + Assert.assertEquals(codegenOperation.returnBaseType, "V1beta3Binding"); + } + + @Test(description = "convert a simple java model") + public void simpleModelTest() { + final Schema schema = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addRequiredItem("id") + .addRequiredItem("name"); + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", schema); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "int"); + Assert.assertEquals(property1.name, "id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "int"); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.dataType, "str"); + Assert.assertEquals(property2.name, "name"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "str"); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.dataType, "datetime"); + Assert.assertEquals(property3.name, "created_at"); + Assert.assertNull(property3.defaultValue); + Assert.assertEquals(property3.baseType, "datetime"); + Assert.assertFalse(property3.required); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("urls", new ArraySchema() + .items(new StringSchema())) + .addRequiredItem("id"); + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "int"); + Assert.assertEquals(property1.name, "id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "int"); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.dataType, "[str]"); + Assert.assertEquals(property2.name, "urls"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "list"); + Assert.assertEquals(property2.containerType, "array"); + Assert.assertFalse(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isContainer); + } + + @Test(description = "convert a model with a map property") + public void mapPropertyTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("translations", new MapSchema() + .additionalProperties(new StringSchema())) + .addRequiredItem("id"); + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "translations"); + Assert.assertEquals(property1.dataType, "{str: (str,)}"); + Assert.assertEquals(property1.name, "translations"); + Assert.assertEquals(property1.baseType, "dict"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertFalse(property1.required); + Assert.assertTrue(property1.isContainer); + Assert.assertTrue(property1.isPrimitiveType); + } + + @Test(description = "convert a model with complex property") + public void complexPropertyTest() { + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPI(); + final Schema model = new Schema() + .description("a sample model") + .addProperties("children", new Schema().$ref("#/components/schemas/Children")); + final Schema children = new Schema() + .type("object") + .addProperties("number", new Schema().type("integer")); + openAPI.getComponents().addSchemas("sample", model); + openAPI.getComponents().addSchemas("Children", children); + codegen.setOpenAPI(openAPI); + + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.dataType, "Children"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "Children"); + Assert.assertFalse(property1.required); + Assert.assertFalse(property1.isContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListPropertyTest() { + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPI(); + final Schema model = new Schema() + .description("a sample model") + .addProperties("children", new ArraySchema() + .items(new Schema().$ref("#/components/schemas/Children"))); + final Schema children = new Schema() + .type("object") + .addProperties("number", new Schema().type("integer")); + openAPI.getComponents().addSchemas("sample", model); + openAPI.getComponents().addSchemas("Children", children); + codegen.setOpenAPI(openAPI); + + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "Children"); + Assert.assertEquals(property1.dataType, "[Children]"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "list"); + Assert.assertEquals(property1.containerType, "array"); + Assert.assertFalse(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert a model with complex map property") + public void complexMapPropertyTest() { + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPI(); + final Schema model = new Schema() + .description("a sample model") + .addProperties("children", new MapSchema() + .additionalProperties(new Schema().$ref("#/components/schemas/Children"))); + final Schema children = new Schema() + .type("object") + .addProperties("number", new Schema().type("integer")); + openAPI.getComponents().addSchemas("sample", model); + openAPI.getComponents().addSchemas("Children", children); + codegen.setOpenAPI(openAPI); + + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "Children"); + Assert.assertEquals(property1.dataType, "{str: (Children,)}"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "dict"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertFalse(property1.required); + Assert.assertTrue(property1.isContainer); + } + + + // should not start with 'null'. need help from the community to investigate further + @Test(description = "convert an array model") + public void arrayModelTest() { + final PythonPriorClientCodegen codegen = new PythonPriorClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPI(); + + final Schema model = new ArraySchema() + .items(new Schema().$ref("#/components/schemas/Children")) + .description("an array model"); + final Schema children = new Schema() + .type("object") + .addProperties("number", new Schema().type("integer")); + openAPI.getComponents().addSchemas("sample", model); + openAPI.getComponents().addSchemas("Children", children); + codegen.setOpenAPI(openAPI); + + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.classVarName, "sample"); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); // the array model has no vars + Assert.assertEquals(cm.parent, "list"); + Assert.assertEquals(cm.imports.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + + final Map childExample = new HashMap<>(); + childExample.put("number", 3); + final List> example = Arrays.asList(childExample); + String exampleValue = codegen.toExampleValue(model, example); + Assert.assertEquals("[Children(number=1,),]", exampleValue.replaceAll("\\s+","")); + } + + // should not start with 'null'. need help from the community to investigate further + @Test(description = "convert a map model") + public void mapModelTest() { + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPI(); + final Schema sample = new Schema() + .description("a map model") + .additionalProperties(new Schema().$ref("#/components/schemas/Children")); + final Schema children = new Schema() + .type("object") + .addProperties("number", new Schema().type("integer")); + openAPI.getComponents().addSchemas("sample", sample); + openAPI.getComponents().addSchemas("Children", children); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", sample); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a map model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.parent, null); + Assert.assertEquals(cm.imports.size(), 1); + } + + @Test(description = "parse date and date-time example value") + public void parseDateAndDateTimeExamplesTest() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/python-prior/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml"); + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + + Schema modelSchema = ModelUtils.getSchema(openAPI, "DateTimeTest"); + String defaultValue = codegen.toDefaultValue(modelSchema); + Assert.assertEquals(defaultValue, "dateutil_parser('2010-01-01T10:10:10.000111+01:00')"); + } + + @Test(description = "format imports of models containing special characters") + public void importSpecialModelNameTest() { + final PythonPriorClientCodegen codegen = new PythonPriorClientCodegen(); + + String importValue = codegen.toModelImport("special.ModelName"); + Assert.assertEquals(importValue, "from models.special_model_name import SpecialModelName"); + } + + @Test(description = "format imports of models containing special characters") + public void defaultSettingInPrimitiveModelWithValidations() { + final PythonPriorClientCodegen codegen = new PythonPriorClientCodegen(); + + OpenAPI openAPI = TestUtils.createOpenAPI(); + final Schema noDefault = new Schema() + .type("number") + .minimum(new BigDecimal("10")); + final Schema hasDefault = new Schema() + .type("number") + .minimum(new BigDecimal("10")); + hasDefault.setDefault("15.0"); + final Schema noDefaultEumLengthOne = new Schema() + .type("number") + .minimum(new BigDecimal("10")); + noDefaultEumLengthOne.setEnum(Arrays.asList("15.0")); + openAPI.getComponents().addSchemas("noDefaultModel", noDefault); + openAPI.getComponents().addSchemas("hasDefaultModel", hasDefault); + openAPI.getComponents().addSchemas("noDefaultEumLengthOneModel", noDefaultEumLengthOne); + codegen.setOpenAPI(openAPI); + + final CodegenModel noDefaultModel = codegen.fromModel("noDefaultModel", noDefault); + Assert.assertEquals(noDefaultModel.defaultValue, null); + Assert.assertEquals(noDefaultModel.hasRequired, true); + + final CodegenModel hasDefaultModel = codegen.fromModel("hasDefaultModel", hasDefault); + Assert.assertEquals(hasDefaultModel.defaultValue, "15.0"); + Assert.assertEquals(hasDefaultModel.hasRequired, false); + + final CodegenModel noDefaultEumLengthOneModel = codegen.fromModel("noDefaultEumLengthOneModel", noDefaultEumLengthOne); + Assert.assertEquals(noDefaultEumLengthOneModel.defaultValue, "15.0"); + Assert.assertEquals(noDefaultEumLengthOneModel.hasRequired, false); + } + + @Test + public void testObjectModelWithRefedAdditionalPropertiesIsGenerated() throws Exception { + File output = Files.createTempDirectory("test").toFile(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("python") + .setInputSpec("src/test/resources/3_0/issue_7372.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + + TestUtils.ensureContainsFile(files, output, "openapi_client/model/a.py"); + TestUtils.ensureContainsFile(files, output, "openapi_client/model/b.py"); + output.deleteOnExit(); + } + + @Test + public void testFreeFormSchemas() throws Exception { + File output = Files.createTempDirectory("test").toFile(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("python-prior") + .setInputSpec("src/test/resources/3_0/issue_7361.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + + TestUtils.ensureContainsFile(files, output, "openapi_client/model/free_form_with_validation.py"); + TestUtils.ensureContainsFile(files, output, "openapi_client/model/free_form_interface.py"); + TestUtils.ensureDoesNotContainsFile(files, output, "openapi_client/model/free_form.py"); + output.deleteOnExit(); + } + + @Test(description = "tests ObjectWithValidations") + public void testObjectWithValidations() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_7361.yaml"); + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + codegen.setOpenAPI(openAPI); + + String modelName = "FreeFormWithValidation"; + Schema modelSchema = ModelUtils.getSchema(openAPI, modelName); + final CodegenModel model = codegen.fromModel(modelName, modelSchema); + Assert.assertEquals((int) model.getMinProperties(), 1); + } + + @Test(description = "tests RegexObjects") + public void testRegexObjects() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_11521.yaml"); + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + codegen.setOpenAPI(openAPI); + + String modelName = "DateTimeObject"; + Schema modelSchema = ModelUtils.getSchema(openAPI, modelName); + final CodegenModel model = codegen.fromModel(modelName, modelSchema); + final CodegenProperty property1 = model.vars.get(0); + Assert.assertEquals(property1.baseName, "datetime"); + Assert.assertEquals(property1.pattern, "/[\\d]{4}-[\\d]{2}-[\\d]{2}T[\\d]{1,2}:[\\d]{2}Z/"); + Assert.assertEquals(property1.vendorExtensions.get("x-regex"), "[\\d]{4}-[\\d]{2}-[\\d]{2}T[\\d]{1,2}:[\\d]{2}Z"); + + // ignore warnings, should be the same as in issue_11521.yaml + Pattern pattern = Pattern.compile("[\\d]{4}-[\\d]{2}-[\\d]{2}T[\\d]{1,2}:[\\d]{2}Z"); + Matcher matcher = pattern.matcher(property1.example); + Assert.assertTrue(matcher.find()); + } + + @Test(description = "tests uuid example works even if a pattern is provided") + public void testUuidExampleWorksEvenIfPatternIsDefined() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issues_13069.yaml"); + final DefaultCodegen codegen = new PythonPriorClientCodegen(); + codegen.setOpenAPI(openAPI); + + Operation operation = openAPI.getPaths().get("/test").getGet(); + CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + codegen.setParameterExampleValue(codegenParameter, operation.getParameters().get(0)); + + String modelName = "UUID"; + Schema modelSchema = ModelUtils.getSchema(openAPI, modelName); + final CodegenModel model = codegen.fromModel(modelName, modelSchema); + + Pattern pattern = Pattern.compile("[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"); + Matcher matcher = pattern.matcher(codegenParameter.example); + Assert.assertTrue(matcher.find()); + } + + @Test(description = "tests RecursiveToExample") + public void testRecursiveToExample() throws IOException { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_8052_recursive_model.yaml"); + final PythonPriorClientCodegen codegen = new PythonPriorClientCodegen(); + codegen.setOpenAPI(openAPI); + + final Operation operation = openAPI.getPaths().get("/geojson").getPost(); + Schema schema = ModelUtils.getSchemaFromRequestBody(operation.getRequestBody()); + String exampleValue = codegen.toExampleValue(schema, null); + + // uncomment if you need to regenerate the expected value + // PrintWriter printWriter = new PrintWriter("src/test/resources/3_0/issue_8052_recursive_model_expected_value.txt"); + // printWriter.write(exampleValue); + // printWriter.close(); + // org.junit.Assert.assertTrue(false); + + String expectedValue = Resources.toString( + Resources.getResource("3_0/issue_8052_recursive_model_expected_value.txt"), + StandardCharsets.UTF_8); + expectedValue = expectedValue.replaceAll("\\r\\n", "\n"); + + + Assert.assertEquals(exampleValue.trim(), expectedValue.trim()); + + } + + @Test(description = "tests NoProxyPyClient") + public void testNoProxyPyClient() throws Exception { + + final String gen = "python-prior"; + final String spec = "src/test/resources/3_0/petstore.yaml"; + + File output = Files.createTempDirectory("test").toFile(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName(gen) + .setInputSpec(spec) + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + + for (String f : new String[] { "openapi_client/configuration.py", "openapi_client/rest.py" } ) { + TestUtils.ensureContainsFile(files, output, f); + Path p = output.toPath().resolve(f); + TestUtils.assertFileContains(p, "no_proxy"); + } + } + + @DataProvider + public Object[][] testToModelData() { + return new Object[][] { + new Object[] {"", "", "foo", "Foo"}, + new Object[] {"Abc", "", "foo", "AbcFoo"}, + new Object[] {"", "Abc", "foo", "FooAbc"}, + new Object[] {"Abc", "Xyz", "foo", "AbcFooXyz"}, + + new Object[] {"", "", "1", "Model1"}, + new Object[] {"Abc", "", "1", "Abc1"}, + new Object[] {"", "Abc", "1", "Model1Abc"}, + new Object[] {"Abc", "Xyz", "1", "Abc1Xyz"}, + + new Object[] {"", "", "and", "ModelAnd"}, + new Object[] {"Abc", "", "and", "AbcAnd"}, + new Object[] {"", "Abc", "and", "AndAbc"}, + new Object[] {"Abc", "Xyz", "and", "AbcAndXyz"}, + }; + } + + @Test(dataProvider = "testToModelData") + public void testToModel(String prefix, String suffix, String input, String want) { + PythonPriorClientCodegen codegen = new PythonPriorClientCodegen(); + codegen.setModelNamePrefix(prefix); + codegen.setModelNameSuffix(suffix); + Assert.assertEquals(codegen.toModelName(input), want); + } + + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java index c44d3d9b1a..7f600322de 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java @@ -51,5 +51,6 @@ public class RubyClientOptionsTest extends AbstractOptionsTest { verify(clientCodegen).setGemAuthor(RubyClientOptionsProvider.GEM_AUTHOR_VALUE); verify(clientCodegen).setGemAuthorEmail(RubyClientOptionsProvider.GEM_AUTHOR_EMAIL_VALUE); verify(clientCodegen).setEnumUnknownDefaultCase(Boolean.parseBoolean(RubyClientOptionsProvider.ENUM_UNKNOWN_DEFAULT_CASE_VALUE)); + verify(clientCodegen).setUseAutoload(Boolean.parseBoolean(RubyClientOptionsProvider.USE_AUTOLOAD_VALUE)); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/AbstractRustCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/AbstractRustCodegenTest.java new file mode 100644 index 0000000000..ade249a90e --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/AbstractRustCodegenTest.java @@ -0,0 +1,244 @@ +package org.openapitools.codegen.rust; + +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.languages.AbstractRustCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.math.BigInteger; +import java.util.function.Function; + + +public class AbstractRustCodegenTest { + + private final AbstractRustCodegen codegen = new P_AbstractRustCodegen(); + + @Test + public void testIsReservedWord() { + Assert.assertTrue(codegen.isReservedWord("return")); + Assert.assertTrue(codegen.isReservedWord("self")); + Assert.assertTrue(codegen.isReservedWord("Self")); + + Assert.assertFalse(codegen.isReservedWord("Return")); + } + + @Test + public void testSanitizeIdentifier() { + // Functions to make this less verbose + Function sanitizeSnakeCase = (String name) -> + codegen.sanitizeIdentifier(name, AbstractRustCodegen.CasingType.SNAKE_CASE, "p", "Rust", true); + Function sanitizeCamelCase = (String name) -> + codegen.sanitizeIdentifier(name, AbstractRustCodegen.CasingType.CAMEL_CASE, "p", "Rust", true); + + // Underscores should be allowed through + Assert.assertEquals(sanitizeSnakeCase.apply("pet_name"), "pet_name"); + + // Hyphens should be replaced (https://github.com/OpenAPITools/openapi-generator/commit/4cb7f1d6135aa3a42ff38cf89771105c40e7e5a9) + Assert.assertEquals(sanitizeSnakeCase.apply("pet-name"), "pet_name"); + + // Special character mappings are applied + Assert.assertEquals(sanitizeSnakeCase.apply("@type"), "at_type"); + Assert.assertEquals(sanitizeCamelCase.apply("@type"), "AtType"); + + // Trailing underscore removed when appropriate + Assert.assertEquals(sanitizeSnakeCase.apply("pet@"), "pet_at"); + Assert.assertEquals(sanitizeSnakeCase.apply("pet_"), "pet_"); + Assert.assertEquals(sanitizeCamelCase.apply("*"), "Star"); + + // Any other special characters are sanitized + Assert.assertEquals(sanitizeSnakeCase.apply("Halloween\uD83C\uDF83"), "halloween"); + + // Regular reserved words + Assert.assertEquals(sanitizeSnakeCase.apply("return"), "r#return"); + Assert.assertEquals(sanitizeSnakeCase.apply("Return"), "r#return"); + Assert.assertEquals(sanitizeCamelCase.apply("return"), "Return"); + Assert.assertEquals(sanitizeCamelCase.apply("return"), "Return"); + + // Special reserved words + Assert.assertEquals(sanitizeCamelCase.apply("self"), "PSelf"); + Assert.assertEquals(sanitizeSnakeCase.apply("self"), "p_self"); + Assert.assertEquals(sanitizeCamelCase.apply("Self"), "PSelf"); + + // Must not start with a number + Assert.assertEquals(sanitizeSnakeCase.apply("1_PET"), "p_1_pet"); + Assert.assertEquals(sanitizeSnakeCase.apply("123_PET"), "p_123_pet"); + Assert.assertEquals(sanitizeCamelCase.apply("_12345AnyOf"), "P12345AnyOf"); + // Other numbers are allowed + Assert.assertEquals(sanitizeSnakeCase.apply("PET_2"), "pet_2"); + + // Check blank strings don't cause exceptions + Assert.assertEquals(sanitizeSnakeCase.apply(""), ""); + } + + @Test + public void testToVarName() { + // Should be converted to snake case + Assert.assertEquals(codegen.toVarName("PetName"), "pet_name"); + // Prefix is added when starting with a number + Assert.assertEquals(codegen.toVarName("1PetName"), "param_1_pet_name"); + } + + @Test + public void testToParamName() { + // Should be converted to snake case + Assert.assertEquals(codegen.toParamName("PetName"), "pet_name"); + // Prefix is added when starting with a number + Assert.assertEquals(codegen.toParamName("1PetName"), "param_1_pet_name"); + } + + @Test + public void testToOperationId() { + // Should be converted to camel case + Assert.assertEquals(codegen.toOperationId("createPet"), "create_pet"); + // Prefix is added when starting with a number + Assert.assertEquals(codegen.toOperationId("1CreatePet"), "call_1_create_pet"); + } + + @Test + public void testToModelName() { + // Should be converted to camel case + Assert.assertEquals(codegen.toModelName("pet_summary"), "PetSummary"); + // Prefix is added when starting with a number + Assert.assertEquals(codegen.toModelName("1_pet_summary"), "Model1PetSummary"); + } + + @Test + public void testToModelFileName() { + // Should be converted to snake case + Assert.assertEquals(codegen.toModelFilename("PetSummary"), "pet_summary"); + // Prefix is added when starting with a number + Assert.assertEquals(codegen.toModelFilename("1PetSummary"), "model_1_pet_summary"); + } + + @Test + public void testToEnumVarName() { + // Should be converted to camel case + Assert.assertEquals(codegen.toEnumVarName("pending", null), "Pending"); + // Enums are often represented in SCREAMING_SNAKE_CASE, check these are also converted to Rust enum camel case + Assert.assertEquals(codegen.toEnumVarName("SCREAMING_SNAKE_CASE", null), "ScreamingSnakeCase"); + // Prefix is added when starting with a number + Assert.assertEquals(codegen.toEnumVarName("1_pending", null), "Variant1Pending"); + // Empty strings need to be mapped to "Empty" + // https://github.com/OpenAPITools/openapi-generator/issues/13453 + Assert.assertEquals(codegen.toEnumVarName("", null), "Empty"); + } + + @Test + public void testToEnumName() { + Function toEnumName = (String name) -> { + CodegenProperty property = new CodegenProperty(); + property.name = name; + return codegen.toEnumName(property); + }; + // Should be converted to camel case + Assert.assertEquals(toEnumName.apply("pet_status"), "PetStatusWithSuffix"); + // Prefix is added when starting with a number + Assert.assertEquals(toEnumName.apply("1_pet_status"), "Enum1PetStatusWithSuffix"); + } + + @Test + public void testToEnumValue() { + // Value should match spec + Assert.assertEquals(codegen.toEnumValue("12345valueAbc#!", null), "12345valueAbc#!"); + // Quotes should be escaped so that the Rust string is valid + Assert.assertEquals(codegen.toEnumValue("\"quote\"", null), "\\\"quote\\\""); + } + + @Test + public void testToApiName() { + // Unnamed + Assert.assertEquals(codegen.toApiName(""), "DefaultWithSuffix"); + // Should be camel case + Assert.assertEquals(codegen.toApiName("pet"), "PetWithSuffix"); + // Prefix is added when starting with a number + Assert.assertEquals(codegen.toApiName("1_pet"), "Api1PetWithSuffix"); + } + + @Test + public void testToApiFilename() { + // Unnamed + Assert.assertEquals(codegen.toApiFilename(""), "default_with_suffix"); + // Should be snake case + Assert.assertEquals(codegen.toApiFilename("Pet"), "pet_with_suffix"); + // Prefix is added when starting with a number + Assert.assertEquals(codegen.toApiFilename("1Pet"), "api_1_pet_with_suffix"); + } + + @Test + public void testBestFittingIntegerType() { + final BigInteger u8_MAX = BigInteger.valueOf(255L); + final BigInteger u16_MAX = BigInteger.valueOf(65_535L); + final BigInteger u32_MAX = BigInteger.valueOf(4_294_967_295L); + + final BigInteger i8_MIN = BigInteger.valueOf(Byte.MIN_VALUE); + final BigInteger i16_MIN = BigInteger.valueOf(Short.MIN_VALUE); + final BigInteger i32_MIN = BigInteger.valueOf(Integer.MIN_VALUE); + + final BigInteger i8_MAX = BigInteger.valueOf(Byte.MAX_VALUE); + final BigInteger i16_MAX = BigInteger.valueOf(Short.MAX_VALUE); + final BigInteger i32_MAX = BigInteger.valueOf(Integer.MAX_VALUE); + + // No range specified + Assert.assertEquals(codegen.bestFittingIntegerType(null, false, null, false, true), "i32"); + + // Test when only minimum specified (prefer unsigned) + Assert.assertEquals(codegen.bestFittingIntegerType(i32_MIN.subtract(BigInteger.ONE), false, null, false, true), "i64"); + Assert.assertEquals(codegen.bestFittingIntegerType(i32_MIN, false, null, false, true), "i32"); + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.valueOf(-1), false, null, false, true), "i32"); + + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, null, false, true), "u32"); + Assert.assertEquals(codegen.bestFittingIntegerType(u32_MAX, false, null, false, true), "u32"); + Assert.assertEquals(codegen.bestFittingIntegerType(u32_MAX.add(BigInteger.ONE), false, null, false, true), "u64"); + + // Test when only minimum specified (disable unsigned) + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, null, false, false), "i32"); + Assert.assertEquals(codegen.bestFittingIntegerType(i32_MAX, false, null, false, false), "i32"); + Assert.assertEquals(codegen.bestFittingIntegerType(i32_MAX.add(BigInteger.ONE), false, null, false, false), "i64"); + + // Test when only maximum specified + Assert.assertEquals(codegen.bestFittingIntegerType(null, false, i32_MIN.subtract(BigInteger.ONE), false, true), "i64"); + Assert.assertEquals(codegen.bestFittingIntegerType(null, false, i32_MIN, false, true), "i32"); + Assert.assertEquals(codegen.bestFittingIntegerType(null, false, BigInteger.ZERO, false, true), "i32"); + + // Test when maximum bits biggest (prefer unsigned) + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, u8_MAX, false, true), "u8"); + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, u8_MAX.add(BigInteger.ONE), false, true), "u16"); + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, u16_MAX, false, true), "u16"); + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, u16_MAX.add(BigInteger.ONE), false, true), "u32"); + + // Test when maximum bits biggest (disable unsigned) + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, i8_MAX, false, false), "i8"); + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, i8_MAX.add(BigInteger.ONE), false, false), "i16"); + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, i16_MAX, false, false), "i16"); + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, false, i16_MAX.add(BigInteger.ONE), false, false), "i32"); + + // Test when minimum bits biggest + Assert.assertEquals(codegen.bestFittingIntegerType(i16_MIN.subtract(BigInteger.ONE), false, BigInteger.ZERO, false, true), "i32"); + Assert.assertEquals(codegen.bestFittingIntegerType(i16_MIN, false, BigInteger.ZERO, false, true), "i16"); + Assert.assertEquals(codegen.bestFittingIntegerType(i8_MIN.subtract(BigInteger.ONE), false, BigInteger.ZERO, false, true), "i16"); + Assert.assertEquals(codegen.bestFittingIntegerType(i8_MIN, false, BigInteger.ZERO, false, true), "i8"); + + // Test when exclusive bounds + Assert.assertEquals(codegen.bestFittingIntegerType(i8_MIN.subtract(BigInteger.ONE), true, BigInteger.ZERO, false, false), "i8"); + Assert.assertEquals(codegen.bestFittingIntegerType(BigInteger.ZERO, true, i8_MAX.add(BigInteger.ONE), true, false), "i8"); + } + + @Test + public void testCanFitIntoUnsigned() { + Assert.assertFalse(codegen.canFitIntoUnsigned(BigInteger.valueOf(-1), false)); + Assert.assertTrue(codegen.canFitIntoUnsigned(BigInteger.valueOf(0), false)); + Assert.assertTrue(codegen.canFitIntoUnsigned(BigInteger.valueOf(1), false)); + + Assert.assertTrue(codegen.canFitIntoUnsigned(BigInteger.valueOf(-1), true)); + } + + + private static class P_AbstractRustCodegen extends AbstractRustCodegen { + + P_AbstractRustCodegen() { + this.enumSuffix = "WithSuffix"; + this.apiNameSuffix = "WithSuffix"; + } + + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/RustClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/RustClientCodegenTest.java index 906e55e515..189dbeec55 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/RustClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/rust/RustClientCodegenTest.java @@ -78,151 +78,165 @@ public class RustClientCodegenTest { } @Test - public void testGetSchemaTypeIntegerNoBounds() { + public void testWithIntegerDefaults() { final IntegerSchema s = new IntegerSchema(); final RustClientCodegen codegen = new RustClientCodegen(); - codegen.setBestFitInt(true); + codegen.setBestFitInt(false); + codegen.setPreferUnsignedInt(false); codegen.processOpts(); - s.setType("i32"); + s.setMinimum(BigDecimal.valueOf(0)); + s.setMaximum(BigDecimal.valueOf(1)); - // min and max are null + s.setFormat("int32"); Assert.assertEquals(codegen.getSchemaType(s), "i32"); - s.setMinimum(BigDecimal.valueOf(Short.MIN_VALUE)); + s.setFormat("int64"); + Assert.assertEquals(codegen.getSchemaType(s), "i64"); - // max is null + // Clear format - should use default of i32 + s.setFormat(null); + + s.setMaximum(BigDecimal.valueOf(Byte.MAX_VALUE)); Assert.assertEquals(codegen.getSchemaType(s), "i32"); s.setMaximum(BigDecimal.valueOf(Short.MAX_VALUE)); - s.setMinimum(null); - - // min is null Assert.assertEquals(codegen.getSchemaType(s), "i32"); - } - @Test - public void testGetSchemaTypeI64() { - final IntegerSchema s = new IntegerSchema(); - final RustClientCodegen codegen = new RustClientCodegen(); - codegen.setBestFitInt(true); - codegen.processOpts(); - - s.setType("i64"); - s.setMinimum(BigDecimal.valueOf(Long.MIN_VALUE)); - s.setMaximum(BigDecimal.valueOf(Long.MAX_VALUE)); - - Assert.assertEquals(codegen.getSchemaType(s), "i64"); - } - - @Test - public void testGetSchemaTypeI32() { - final IntegerSchema s = new IntegerSchema(); - final RustClientCodegen codegen = new RustClientCodegen(); - codegen.setBestFitInt(true); - codegen.processOpts(); - - s.setType("i32"); - s.setMinimum(BigDecimal.valueOf(Integer.MIN_VALUE)); s.setMaximum(BigDecimal.valueOf(Integer.MAX_VALUE)); + Assert.assertEquals(codegen.getSchemaType(s), "i32"); + s.setMaximum(BigDecimal.valueOf(Long.MAX_VALUE)); Assert.assertEquals(codegen.getSchemaType(s), "i32"); } @Test - public void testGetSchemaTypeI16() { + public void testWithIntegerFitting() { final IntegerSchema s = new IntegerSchema(); final RustClientCodegen codegen = new RustClientCodegen(); codegen.setBestFitInt(true); + codegen.setPreferUnsignedInt(false); codegen.processOpts(); - s.setType("i32"); - s.setMinimum(BigDecimal.valueOf(Short.MIN_VALUE)); - s.setMaximum(BigDecimal.valueOf(Short.MAX_VALUE)); + // No bounds + Assert.assertEquals(codegen.getSchemaType(s), "i32"); - Assert.assertEquals(codegen.getSchemaType(s), "i16"); - } + // Set Bounds + s.setMinimum(BigDecimal.valueOf(0)); + s.setMaximum(BigDecimal.valueOf(1)); - @Test - public void testGetSchemaTypeI8() { - final IntegerSchema s = new IntegerSchema(); - final RustClientCodegen codegen = new RustClientCodegen(); - codegen.setBestFitInt(true); - codegen.processOpts(); + // Should respect hardcoded format + s.setFormat("int32"); + Assert.assertEquals(codegen.getSchemaType(s), "i32"); - s.setType("i32"); - s.setMinimum(BigDecimal.valueOf(-128)); - s.setMaximum(BigDecimal.valueOf(127)); + // Should respect hardcoded format + s.setFormat("int64"); + Assert.assertEquals(codegen.getSchemaType(s), "i64"); + // No format - use best fitting + s.setFormat(null); + + s.setMaximum(BigDecimal.valueOf(Byte.MAX_VALUE)); Assert.assertEquals(codegen.getSchemaType(s), "i8"); - } - @Test - public void testGetSchemaTypeU64() { - final IntegerSchema s = new IntegerSchema(); - final RustClientCodegen codegen = new RustClientCodegen(); - codegen.setPreferUnsignedInt(true); - codegen.processOpts(); + s.setMaximum(BigDecimal.valueOf(Short.MAX_VALUE)); + Assert.assertEquals(codegen.getSchemaType(s), "i16"); - s.setType("i64"); - s.setMinimum(BigDecimal.ZERO); - - Assert.assertEquals(codegen.getSchemaType(s), "u64"); - - s.setMaximum(BigDecimal.valueOf(Long.MAX_VALUE).add(BigDecimal.valueOf(Long.MAX_VALUE))); - - Assert.assertEquals(codegen.getSchemaType(s), "u64"); - - s.setMinimum(null); - s.setMaximum(null); + s.setMaximum(BigDecimal.valueOf(Integer.MAX_VALUE)); + Assert.assertEquals(codegen.getSchemaType(s), "i32"); + s.setMaximum(BigDecimal.valueOf(Long.MAX_VALUE)); Assert.assertEquals(codegen.getSchemaType(s), "i64"); } @Test - public void testGetSchemaTypeU32() { + public void testWithPreferUnsigned() { final IntegerSchema s = new IntegerSchema(); final RustClientCodegen codegen = new RustClientCodegen(); + codegen.setBestFitInt(false); codegen.setPreferUnsignedInt(true); codegen.processOpts(); - s.setType("i32"); - s.setMinimum(BigDecimal.ZERO); + // Minimum of zero, should fit in unsigned + s.setMinimum(BigDecimal.valueOf(0)); + // No integer fitting, but prefer unsigned + s.setMaximum(BigDecimal.valueOf(Byte.MAX_VALUE)); Assert.assertEquals(codegen.getSchemaType(s), "u32"); - s.setMaximum(BigDecimal.valueOf(65535)); - + s.setMaximum(BigDecimal.valueOf(Long.MAX_VALUE)); Assert.assertEquals(codegen.getSchemaType(s), "u32"); + + // Should respect hardcoded 32-bits, but prefer unsigned + s.setFormat("int32"); + Assert.assertEquals(codegen.getSchemaType(s), "u32"); + + // Should respect hardcoded 64-bits, but prefer unsigned + s.setFormat("int64"); + Assert.assertEquals(codegen.getSchemaType(s), "u64"); + + // Unknown minimum - should not use unsigned + s.setMinimum(null); + + s.setFormat(null); + Assert.assertEquals(codegen.getSchemaType(s), "i32"); + + s.setFormat("int32"); + Assert.assertEquals(codegen.getSchemaType(s), "i32"); + + s.setFormat("int64"); + Assert.assertEquals(codegen.getSchemaType(s), "i64"); } @Test - public void testGetSchemaTypeU16() { + public void testWithIntegerFittingAndPreferUnsigned() { final IntegerSchema s = new IntegerSchema(); final RustClientCodegen codegen = new RustClientCodegen(); codegen.setBestFitInt(true); codegen.setPreferUnsignedInt(true); codegen.processOpts(); - s.setType("i32"); - s.setMinimum(BigDecimal.ZERO); - s.setMaximum(BigDecimal.valueOf(65535)); + // Minimum of zero, should fit in unsigned + s.setMinimum(BigDecimal.valueOf(0)); + s.setMaximum(BigDecimal.valueOf(1)); - Assert.assertEquals(codegen.getSchemaType(s), "u16"); - } + // Should respect hardcoded 32-bits, but prefer unsigned + s.setFormat("int32"); + Assert.assertEquals(codegen.getSchemaType(s), "u32"); - @Test - public void testGetSchemaTypeU8() { - final IntegerSchema s = new IntegerSchema(); - final RustClientCodegen codegen = new RustClientCodegen(); - codegen.setBestFitInt(true); - codegen.setPreferUnsignedInt(true); - codegen.processOpts(); + // Should respect hardcoded 64-bits, but prefer unsigned + s.setFormat("int64"); + Assert.assertEquals(codegen.getSchemaType(s), "u64"); - s.setType("i32"); - s.setMinimum(BigDecimal.ZERO); - s.setMaximum(BigDecimal.valueOf(255)); + // No format - use best fitting + s.setFormat(null); + s.setMaximum(BigDecimal.valueOf(Byte.MAX_VALUE)); Assert.assertEquals(codegen.getSchemaType(s), "u8"); + + s.setMaximum(BigDecimal.valueOf(Short.MAX_VALUE)); + Assert.assertEquals(codegen.getSchemaType(s), "u16"); + + s.setMaximum(BigDecimal.valueOf(Integer.MAX_VALUE)); + Assert.assertEquals(codegen.getSchemaType(s), "u32"); + + s.setMaximum(BigDecimal.valueOf(Long.MAX_VALUE)); + Assert.assertEquals(codegen.getSchemaType(s), "u64"); + + // Unknown minimum - unable to use unsigned + s.setMinimum(null); + + s.setMaximum(BigDecimal.valueOf(Integer.MAX_VALUE)); + Assert.assertEquals(codegen.getSchemaType(s), "i32"); + + s.setMaximum(BigDecimal.valueOf(Long.MAX_VALUE)); + Assert.assertEquals(codegen.getSchemaType(s), "i64"); + + s.setFormat("int32"); + Assert.assertEquals(codegen.getSchemaType(s), "i32"); + + s.setFormat("int64"); + Assert.assertEquals(codegen.getSchemaType(s), "i64"); } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5ClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5ClientCodegenTest.java index 0f7e127371..59928dbc26 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5ClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5ClientCodegenTest.java @@ -122,8 +122,8 @@ public class Swift5ClientCodegenTest { Assert.assertTrue(op.responses.get(0).isBinary); } - @Test(description = "returns Date when response format is date", enabled = true) - public void dateTest() { + @Test(description = "returns Date when response format is date per default", enabled = true) + public void dateDefaultTest() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/datePropertyTest.json"); final DefaultCodegen codegen = new Swift5ClientCodegen(); codegen.setOpenAPI(openAPI); @@ -135,6 +135,37 @@ public class Swift5ClientCodegenTest { Assert.assertEquals(op.bodyParam.dataType, "Date"); } + @Test(description = "returns Date when response format is date and cli option is disabled", enabled = true) + public void dateDisabledCLITest() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/datePropertyTest.json"); + final DefaultCodegen codegen = new Swift5ClientCodegen(); + codegen.setOpenAPI(openAPI); + codegen.additionalProperties().put(Swift5ClientCodegen.USE_CUSTOM_DATE_WITHOUT_TIME, false); + codegen.processOpts(); + final String path = "/tests/dateResponse"; + final Operation p = openAPI.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, null); + + Assert.assertEquals(op.returnType, "Date"); + Assert.assertEquals(op.bodyParam.dataType, "Date"); + } + + @Test(description = "returns OpenAPIDateWithoutTime when response format is date and cli option is enabled", enabled = true) + public void dateWithoutTimeTest() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/datePropertyTest.json"); + final DefaultCodegen codegen = new Swift5ClientCodegen(); + codegen.setOpenAPI(openAPI); + codegen.additionalProperties().put(Swift5ClientCodegen.USE_CUSTOM_DATE_WITHOUT_TIME, true); + codegen.processOpts(); + + final String path = "/tests/dateResponse"; + final Operation p = openAPI.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, null); + + Assert.assertEquals(op.returnType, "OpenAPIDateWithoutTime"); + Assert.assertEquals(op.bodyParam.dataType, "OpenAPIDateWithoutTime"); + } + @Test(enabled = true) public void testDefaultPodAuthors() throws Exception { // Given diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5ModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5ModelTest.java index 895bb1703b..6a20d384a0 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5ModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5ModelTest.java @@ -122,4 +122,45 @@ public class Swift5ModelTest { Assert.assertFalse(property7.isContainer); } + @Test(description = "convert a simple java model", enabled = true) + public void useCustomDateTimeTest() { + final Schema schema = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addProperties("binary", new BinarySchema()) + .addProperties("byte", new ByteArraySchema()) + .addProperties("uuid", new UUIDSchema()) + .addProperties("dateOfBirth", new DateSchema()) + .addRequiredItem("id") + .addRequiredItem("name") + .discriminator(new Discriminator().propertyName("test")); + final DefaultCodegen codegen = new Swift5ClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema); + codegen.setOpenAPI(openAPI); + codegen.additionalProperties().put(Swift5ClientCodegen.USE_CUSTOM_DATE_WITHOUT_TIME, true); + codegen.processOpts(); + + final CodegenModel cm = codegen.fromModel("sample", schema); + final CodegenProperty property7 = cm.vars.get(6); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.dataType, "Date"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertNull(property3.defaultValue); + Assert.assertEquals(property3.baseType, "Date"); + Assert.assertFalse(property3.required); + Assert.assertFalse(property3.isContainer); + + Assert.assertEquals(property7.baseName, "dateOfBirth"); + Assert.assertEquals(property7.dataType, "OpenAPIDateWithoutTime"); + Assert.assertEquals(property7.name, "dateOfBirth"); + Assert.assertNull(property7.defaultValue); + Assert.assertEquals(property7.baseType, "OpenAPIDateWithoutTime"); + Assert.assertFalse(property7.required); + Assert.assertFalse(property7.isContainer); + } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/testutils/AssertFile.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/testutils/AssertFile.java index bfdb2452bd..d46798cd7f 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/testutils/AssertFile.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/testutils/AssertFile.java @@ -33,7 +33,7 @@ import java.util.Arrays; import java.util.List; import java.util.Locale; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.fail; /** @@ -84,9 +84,10 @@ public class AssertFile { Arrays.sort(actual); } - assertEquals(expected, - actual, - String.format(Locale.ROOT, "Directory content of '%s' and '%s' differ.", expectedDir, actualDir)); + // Use AssertJ as it also prints a diff + assertThat(actual) + .describedAs(String.format(Locale.ROOT, "Directory content of '%s' and '%s' differ.", expectedDir, actualDir)) + .containsExactly(expected); return FileVisitResult.CONTINUE; } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/SharedTypeScriptTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/SharedTypeScriptTest.java index 07f7943b3c..cdd43b5b09 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/SharedTypeScriptTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/SharedTypeScriptTest.java @@ -16,6 +16,9 @@ import java.util.List; import java.util.Map; import java.util.HashMap; +import static org.openapitools.codegen.typescript.TypeScriptGroups.*; + +@Test(groups = {TYPESCRIPT}) public class SharedTypeScriptTest { @Test public void typesInImportsAreSplittedTest() throws IOException { @@ -93,4 +96,4 @@ public class SharedTypeScriptTest { Assert.assertEquals(mapped, entry.getValue()); } } -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientCodegenTest.java index f5d75cc8a3..925a6adcbc 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientCodegenTest.java @@ -9,11 +9,18 @@ import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptClientCodegen; +import org.openapitools.codegen.model.ModelMap; +import org.openapitools.codegen.model.ModelsMap; import org.openapitools.codegen.utils.ModelUtils; import org.testng.Assert; import org.testng.annotations.Test; +import java.io.File; +import java.util.Collections; +import java.util.List; +import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT}) public class TypeScriptClientCodegenTest { @Test public void getTypeDeclarationTest() { @@ -79,4 +86,59 @@ public class TypeScriptClientCodegenTest { Assert.assertFalse(codegenModel.imports.contains("Set")); } + @Test + public void testWithAdditionalProperties() { + final Schema inner = new ObjectSchema(); + inner.setAdditionalProperties(true); + + final Schema root = new ObjectSchema() + .addProperties("inner", inner); + + final DefaultCodegen codegen = new TypeScriptClientCodegen(); + final OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", root); + codegen.setOpenAPI(openAPI); + + try { + // TypeScriptClientCodegen can generate codes without throwing exception. + codegen.fromModel("sample", root); + } catch (Exception e) { + Assert.fail("Exception was thrown."); + } + } + + @Test + public void defaultModelImportTest() { + final DefaultCodegen codegen = new TypeScriptClientCodegen(); + + final CodegenModel cm = new CodegenModel(); + cm.setImports(Collections.singleton("ApiResponse")); + final ModelsMap models = new ModelsMap(); + final ModelMap model = new ModelMap(); + model.setModel(cm); + models.setModels(Collections.singletonList(model)); + + final ModelsMap processedModels = codegen.postProcessModels(models); + final List> tsImports = (List>) processedModels.getModels().get(0).get("tsImports"); + Assert.assertEquals(tsImports.get(0).get("filename"), "../models/ApiResponse".replace("/", File.separator)); + Assert.assertEquals(tsImports.get(0).get("classname"), "ApiResponse"); + } + + @Test + public void modelImportWithMappingTest() { + final DefaultCodegen codegen = new TypeScriptClientCodegen(); + final String mappedName = "@namespace/dir/response"; + codegen.importMapping().put("ApiResponse", mappedName); + + final CodegenModel cm = new CodegenModel(); + cm.setImports(Collections.singleton("ApiResponse")); + final ModelsMap models = new ModelsMap(); + final ModelMap model = new ModelMap(); + model.setModel(cm); + models.setModels(Collections.singletonList(model)); + + final ModelsMap processedModels = codegen.postProcessModels(models); + final List> tsImports = (List>) processedModels.getModels().get(0).get("tsImports"); + Assert.assertEquals(tsImports.get(0).get("filename"), mappedName); + Assert.assertEquals(tsImports.get(0).get("classname"), "ApiResponse"); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientModelTest.java index 5a8333b5e5..5f9b2173ac 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientModelTest.java @@ -6,11 +6,11 @@ import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptClientCodegen; -import org.openapitools.codegen.utils.ModelUtils; import org.testng.Assert; import org.testng.annotations.Test; +@Test(groups = {TypeScriptGroups.TYPESCRIPT}) public class TypeScriptClientModelTest { @Test(description = "convert an array oneof model") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptGroups.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptGroups.java new file mode 100644 index 0000000000..fedc1e5f94 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptGroups.java @@ -0,0 +1,28 @@ +package org.openapitools.codegen.typescript; + +/** + * TestNG supports grouping using Test Groups. + *
        + *

        + * Using groups also enables running only a subset of tests, e.g. only for the generator you are currently working on. + *

        + *

        + * This speeds up development a lot, especially if run from an IDE with support for TestNG groups + * (e.g. IntelliJ IDEA and derivatives, VS Code, and lots of others) + *

        + *
        + *

        Suggested groups/group-names are:

        + *
          + *
        • one per language (e.g.: "typescript") since most generators for one language share lots of code
        • + *
        • one per language + generator (i.e. the generator name, e.g.: "typescript-angular")
        • + *
        + */ +public final class TypeScriptGroups { + public static final String TYPESCRIPT = "typescript"; + public static final String TYPESCRIPT_AURELIA = "typescript-aurelia"; + public static final String TYPESCRIPT_AXIOS = "typescript-axios"; + public static final String TYPESCRIPT_FETCH = "typescript-fetch"; + public static final String TYPESCRIPT_ANGULAR = "typescript-angular"; + public static final String TYPESCRIPT_NESTJS = "typescript-nestjs"; + public static final String TYPESCRIPT_NODE = "typescript-node"; +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java index be1801e640..8da6662021 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java @@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptAureliaClientCodegen; import org.openapitools.codegen.options.TypeScriptAureliaClientOptionsProvider; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_AURELIA}) public class TypeScriptAureliaClientOptionsTest extends AbstractOptionsTest { private TypeScriptAureliaClientCodegen clientCodegen = mock(TypeScriptAureliaClientCodegen.class, mockSettings); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/axios/TypeScriptAxiosClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/axios/TypeScriptAxiosClientCodegenTest.java index e73786adf3..da55a175fb 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/axios/TypeScriptAxiosClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/axios/TypeScriptAxiosClientCodegenTest.java @@ -1,11 +1,15 @@ package org.openapitools.codegen.typescript.axios; import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.languages.TypeScriptAxiosClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_AXIOS}) public class TypeScriptAxiosClientCodegenTest { TypeScriptAxiosClientCodegen codegen = new TypeScriptAxiosClientCodegen(); @@ -78,4 +82,33 @@ public class TypeScriptAxiosClientCodegenTest { assertEquals(codegen.toEnumVarName("b", "string"), "B"); } + @Test + public void containsESMTSConfigFileInCaseOfES6AndNPM() { + TypeScriptAxiosClientCodegen codegen = new TypeScriptAxiosClientCodegen(); + + codegen.additionalProperties().put("npmName", "@openapi/typescript-axios-petstore"); + codegen.additionalProperties().put("snapshot", false); + codegen.additionalProperties().put("npmVersion", "1.0.0-SNAPSHOT"); + codegen.setSupportsES6(true); + + codegen.processOpts(); + + assertThat(codegen.supportingFiles()).contains(new SupportingFile("tsconfig.mustache", "", "tsconfig.json")); + assertThat(codegen.supportingFiles()).contains(new SupportingFile("tsconfig.esm.mustache", "", "tsconfig.esm.json")); + } + + @Test + public void doesNotContainESMTSConfigFileInCaseOfES5AndNPM() { + TypeScriptAxiosClientCodegen codegen = new TypeScriptAxiosClientCodegen(); + + codegen.additionalProperties().put("npmName", "@openapi/typescript-axios-petstore"); + codegen.additionalProperties().put("snapshot", false); + codegen.additionalProperties().put("npmVersion", "1.0.0-SNAPSHOT"); + codegen.setSupportsES6(false); + + codegen.processOpts(); + + assertThat(codegen.supportingFiles()).contains(new SupportingFile("tsconfig.mustache", "", "tsconfig.json")); + assertThat(codegen.supportingFiles()).doesNotContain(new SupportingFile("tsconfig.esm.mustache", "", "tsconfig.esm.json")); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientCodegenTest.java index 379c2865a4..34e6740417 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientCodegenTest.java @@ -1,17 +1,22 @@ package org.openapitools.codegen.typescript.fetch; import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.MapSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.SupportingFile; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.openapitools.codegen.utils.ModelUtils; import org.testng.Assert; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_FETCH}) public class TypeScriptFetchClientCodegenTest { @Test public void testSnapshotVersion() { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java index 6d3f50e7be..9c4e471603 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java @@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen; import org.openapitools.codegen.options.TypeScriptFetchClientOptionsProvider; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_FETCH}) public class TypeScriptFetchClientOptionsTest extends AbstractOptionsTest { private TypeScriptFetchClientCodegen clientCodegen = mock(TypeScriptFetchClientCodegen.class, mockSettings); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchModelTest.java index 9bc7c70948..259b7f55c9 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchModelTest.java @@ -26,6 +26,7 @@ import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.Assert; import org.testng.annotations.Test; @@ -35,9 +36,11 @@ import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Locale; +import java.util.Map; /* import static io.swagger.codegen.CodegenConstants.IS_ENUM_EXT_NAME; @@ -45,6 +48,7 @@ import static io.swagger.codegen.languages.helpers.ExtensionHelper.getBooleanVal import static io.swagger.codegen.utils.ModelUtils.updateCodegenPropertyEnum; */ +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_FETCH}) @SuppressWarnings("static-method") public class TypeScriptFetchModelTest { @@ -117,6 +121,76 @@ public class TypeScriptFetchModelTest { Assert.assertFalse(property5.isContainer); } + @Test(description = "convert a simple TypeScript Angular model; overwrite date/DateTime type mapping") + public void simpleModelWithStringDateTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT)) + .addProperties("name", new StringSchema()) + .addProperties("createdAt", new DateTimeSchema()) + .addProperties("birthDate", new DateSchema()) + .addProperties("active", new BooleanSchema()) + .addRequiredItem("id") + .addRequiredItem("name"); + + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + codegen.typeMapping().put("date", "string"); + codegen.typeMapping().put("DateTime", "string"); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 5); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "number"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "undefined"); + Assert.assertEquals(property1.baseType, "number"); + Assert.assertTrue(property1.required); + Assert.assertFalse(property1.isContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.dataType, "string"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, "undefined"); + Assert.assertEquals(property2.baseType, "string"); + Assert.assertTrue(property2.required); + Assert.assertFalse(property2.isContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.complexType, null); + Assert.assertEquals(property3.dataType, "string"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertEquals(property3.defaultValue, "undefined"); + Assert.assertFalse(property3.required); + Assert.assertFalse(property3.isContainer); + + final CodegenProperty property4 = cm.vars.get(3); + Assert.assertEquals(property4.baseName, "birthDate"); + Assert.assertEquals(property4.complexType, null); + Assert.assertEquals(property4.dataType, "string"); + Assert.assertEquals(property4.name, "birthDate"); + Assert.assertEquals(property4.defaultValue, "undefined"); + Assert.assertFalse(property4.required); + Assert.assertFalse(property4.isContainer); + + final CodegenProperty property5 = cm.vars.get(4); + Assert.assertEquals(property5.baseName, "active"); + Assert.assertEquals(property5.complexType, null); + Assert.assertEquals(property5.dataType, "boolean"); + Assert.assertEquals(property5.name, "active"); + Assert.assertEquals(property5.defaultValue, "undefined"); + Assert.assertFalse(property5.required); + Assert.assertFalse(property5.isContainer); + } + @Test(description = "convert and check default values for a simple TypeScript Angular model") public void simpleModelDefaultValuesTest() throws ParseException { IntegerSchema integerSchema = new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT); @@ -386,4 +460,14 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(codegen.getTypeDeclaration(model), "{ [key: string]: string; }"); } + + @Test(description = "Don't generate new schemas for readonly references") + public void testNestedReadonlySchemas() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allOf-readonly.yaml"); + final DefaultCodegen codegen = new TypeScriptFetchClientCodegen(); + codegen.processOpts(); + codegen.setOpenAPI(openAPI); + final Map schemaBefore = openAPI.getComponents().getSchemas(); + Assert.assertEquals(schemaBefore.keySet(), Sets.newHashSet("club", "owner")); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java index 6123147299..a28daaaa0f 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java @@ -11,6 +11,7 @@ import io.swagger.v3.oas.models.responses.ApiResponses; import org.openapitools.codegen.*; import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.Assert; import org.testng.annotations.Test; @@ -21,6 +22,7 @@ import java.util.HashMap; import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR}) public class TypeScriptAngularClientCodegenTest { @Test public void toVarName() { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java index 38b1f0ee4d..7956206569 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java @@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; import org.openapitools.codegen.options.TypeScriptAngularClientOptionsProvider; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR}) public class TypeScriptAngularClientOptionsTest extends AbstractOptionsTest { private TypeScriptAngularClientCodegen clientCodegen = mock(TypeScriptAngularClientCodegen.class, mockSettings); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java index 0d9e8cb8f3..0994c14a82 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java @@ -27,6 +27,7 @@ import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.Assert; import org.testng.annotations.Test; @@ -38,6 +39,7 @@ import java.time.ZoneOffset; import java.util.Date; import java.util.Locale; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR}) @SuppressWarnings("static-method") public class TypeScriptAngularModelTest { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularAdditionalPropertiesIntegrationTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularAdditionalPropertiesIntegrationTest.java index 64ad61af31..ee87da560e 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularAdditionalPropertiesIntegrationTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularAdditionalPropertiesIntegrationTest.java @@ -21,12 +21,23 @@ import org.openapitools.codegen.AbstractIntegrationTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; +import java.io.IOException; import java.util.HashMap; import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR}) public class TypescriptAngularAdditionalPropertiesIntegrationTest extends AbstractIntegrationTest { + { + // when running repeatedly from an IDE, some files do not get overwritten + // and thus are missing from the FILES metadata. + // Since metadata-verification is not the core responsibility of this test: disable it. + generateMetadata = false; + } + @Override protected CodegenConfig getCodegenConfig() { return new TypeScriptAngularClientCodegen(); @@ -46,4 +57,11 @@ public class TypescriptAngularAdditionalPropertiesIntegrationTest extends Abstra protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { return new IntegrationTestPathsConfig("typescript/additional-properties"); } + + @Test + @Override + public void generatesCorrectDirectoryStructure() throws IOException { + // test are currently disabled in Superclass + super.generatesCorrectDirectoryStructure(); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularApiVersionTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularApiVersionTest.java index a577981314..399fe90a87 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularApiVersionTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularApiVersionTest.java @@ -3,9 +3,11 @@ package org.openapitools.codegen.typescript.typescriptangular; import io.swagger.v3.oas.models.OpenAPI; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.Assert; import org.testng.annotations.Test; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR}) public class TypescriptAngularApiVersionTest { @Test(description = "tests if API version specification is used if no version is provided in additional properties") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularArrayAndObjectIntegrationTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularArrayAndObjectIntegrationTest.java index 4a2bab73c2..9bbb9ea4ef 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularArrayAndObjectIntegrationTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularArrayAndObjectIntegrationTest.java @@ -21,12 +21,23 @@ import org.openapitools.codegen.AbstractIntegrationTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; +import java.io.IOException; import java.util.HashMap; import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR}) public class TypescriptAngularArrayAndObjectIntegrationTest extends AbstractIntegrationTest { + { + // when running repeatedly from an IDE, some files do not get overwritten + // and thus are missing from the FILES metadata. + // Since metadata-verification is not the core responsibility of this test: disable it. + generateMetadata = false; + } + @Override protected CodegenConfig getCodegenConfig() { return new TypeScriptAngularClientCodegen(); @@ -46,4 +57,11 @@ public class TypescriptAngularArrayAndObjectIntegrationTest extends AbstractInte protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { return new IntegrationTestPathsConfig("typescript/array-and-object"); } + + @Test + @Override + public void generatesCorrectDirectoryStructure() throws IOException { + // test are currently disabled in Superclass + super.generatesCorrectDirectoryStructure(); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularParamsStrategyCustomIntegrationTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularParamsStrategyCustomIntegrationTest.java new file mode 100644 index 0000000000..ceac06d46f --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularParamsStrategyCustomIntegrationTest.java @@ -0,0 +1,66 @@ +/* + * 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.typescript.typescriptangular; + +import org.openapitools.codegen.AbstractIntegrationTest; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; +import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR}) +public class TypescriptAngularParamsStrategyCustomIntegrationTest extends AbstractIntegrationTest { + + { + // when running repeatedly from an IDE, some files do not get overwritten + // and thus are missing from the FILES metadata. + // Since metadata-verification is not the core responsibility of this test: disable it. + generateMetadata = false; + } + + @Override + protected CodegenConfig getCodegenConfig() { + return new TypeScriptAngularClientCodegen(); + } + + @Override + protected Map configProperties() { + Map properties = new HashMap<>(); + properties.put("npmName", "custom-path-params-integration-test"); + properties.put("npmVersion", "1.0.3"); + properties.put("snapshot", "false"); + + return properties; + } + + @Override + protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { + return new IntegrationTestPathsConfig("typescript/custom-path-params"); + } + + @Test + @Override + public void generatesCorrectDirectoryStructure() throws IOException { + // test are currently disabled in Superclass + super.generatesCorrectDirectoryStructure(); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularPetstoreIntegrationTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularPetstoreIntegrationTest.java index 4a4fddf4c4..251463ce65 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularPetstoreIntegrationTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypescriptAngularPetstoreIntegrationTest.java @@ -21,12 +21,23 @@ import org.openapitools.codegen.AbstractIntegrationTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; +import java.io.IOException; import java.util.HashMap; import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_ANGULAR}) public class TypescriptAngularPetstoreIntegrationTest extends AbstractIntegrationTest { + { + // when running repeatedly from an IDE, some files do not get overwritten + // and thus are missing from the FILES metadata. + // Since metadata-verification is not the core responsibility of this test: disable it. + generateMetadata = false; + } + @Override protected CodegenConfig getCodegenConfig() { return new TypeScriptAngularClientCodegen(); @@ -46,4 +57,11 @@ public class TypescriptAngularPetstoreIntegrationTest extends AbstractIntegratio protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() { return new IntegrationTestPathsConfig("typescript/petstore"); } + + @Test + @Override + public void generatesCorrectDirectoryStructure() throws IOException { + // test are currently disabled in Superclass + super.generatesCorrectDirectoryStructure(); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientCodegenTest.java index 43775c6413..72aae1b236 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientCodegenTest.java @@ -10,10 +10,12 @@ import io.swagger.v3.oas.models.responses.ApiResponses; import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.Assert; import org.testng.annotations.Test; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS}) public class TypeScriptNestjsClientCodegenTest { @Test public void testModelFileSuffix() { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientOptionsTest.java index ba042c8471..7b812a7eb3 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientOptionsTest.java @@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen; import org.openapitools.codegen.options.TypeScriptNestjsClientOptionsProvider; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS}) public class TypeScriptNestjsClientOptionsTest extends AbstractOptionsTest { private TypeScriptNestjsClientCodegen clientCodegen = mock(TypeScriptNestjsClientCodegen.class, mockSettings); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsModelTest.java index 1ea2ed86c0..4338260cfd 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsModelTest.java @@ -25,9 +25,11 @@ import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.Assert; import org.testng.annotations.Test; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS}) @SuppressWarnings("static-method") public class TypeScriptNestjsModelTest { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsAdditionalPropertiesIntegrationTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsAdditionalPropertiesIntegrationTest.java index e0ab5cd60c..0844344ae9 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsAdditionalPropertiesIntegrationTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsAdditionalPropertiesIntegrationTest.java @@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractIntegrationTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen; import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS}) public class TypescriptNestjsAdditionalPropertiesIntegrationTest extends AbstractIntegrationTest { @Override diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsApiVersionTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsApiVersionTest.java index e767a1eeb0..8cafe9c97d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsApiVersionTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsApiVersionTest.java @@ -3,9 +3,11 @@ package org.openapitools.codegen.typescript.typescriptnestjs; import io.swagger.v3.oas.models.OpenAPI; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.Assert; import org.testng.annotations.Test; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS}) public class TypescriptNestjsApiVersionTest { @Test(description = "tests if API version specification is used if no version is provided in additional properties") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsArrayAndObjectIntegrationTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsArrayAndObjectIntegrationTest.java index 15d19d42af..af12b8b448 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsArrayAndObjectIntegrationTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsArrayAndObjectIntegrationTest.java @@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractIntegrationTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen; import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS}) public class TypescriptNestjsArrayAndObjectIntegrationTest extends AbstractIntegrationTest { @Override diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsPetstoreIntegrationTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsPetstoreIntegrationTest.java index 30e2e2cee7..285fe88b46 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsPetstoreIntegrationTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypescriptNestjsPetstoreIntegrationTest.java @@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractIntegrationTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen; import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NESTJS}) public class TypescriptNestjsPetstoreIntegrationTest extends AbstractIntegrationTest { @Override diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientCodegenTest.java index dacc57d2f7..2a9843669a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientCodegenTest.java @@ -11,12 +11,14 @@ import org.openapitools.codegen.model.ModelMap; import org.openapitools.codegen.model.ModelsMap; import org.openapitools.codegen.model.OperationMap; import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.*; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE}) public class TypeScriptNodeClientCodegenTest { private TypeScriptNodeClientCodegen codegen; diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java index 680759c870..61999253c9 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java @@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen; import org.openapitools.codegen.options.TypeScriptNodeClientOptionsProvider; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE}) public class TypeScriptNodeClientOptionsTest extends AbstractOptionsTest { private TypeScriptNodeClientCodegen clientCodegen = mock(TypeScriptNodeClientCodegen.class, mockSettings); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java index efacb8b5ff..42b7fbe1b4 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java @@ -18,17 +18,16 @@ package org.openapitools.codegen.typescript.typescriptnode; import com.google.common.collect.Sets; - import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.*; import io.swagger.v3.parser.util.SchemaTypeUtil; - import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen; import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen; +import org.openapitools.codegen.typescript.TypeScriptGroups; import org.testng.Assert; import org.testng.annotations.Test; @@ -40,6 +39,7 @@ import java.time.ZoneOffset; import java.util.Date; import java.util.Locale; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE}) @SuppressWarnings("static-method") public class TypeScriptNodeModelTest { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java index 8b200db6f3..b7fc1bcd36 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypescriptNodeES5IntegrationTest.java @@ -21,10 +21,13 @@ import org.openapitools.codegen.AbstractIntegrationTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen; import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE}) public class TypescriptNodeES5IntegrationTest extends AbstractIntegrationTest { @Override diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypescriptNodeEnumIntegrationTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypescriptNodeEnumIntegrationTest.java index e695fbe04b..d5490934a9 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypescriptNodeEnumIntegrationTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypescriptNodeEnumIntegrationTest.java @@ -20,10 +20,13 @@ import org.openapitools.codegen.AbstractIntegrationTest; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen; import org.openapitools.codegen.testutils.IntegrationTestPathsConfig; +import org.openapitools.codegen.typescript.TypeScriptGroups; +import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; +@Test(groups = {TypeScriptGroups.TYPESCRIPT, TypeScriptGroups.TYPESCRIPT_NODE}) public class TypescriptNodeEnumIntegrationTest extends AbstractIntegrationTest { @Override diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/ModelUtilsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/ModelUtilsTest.java index f962efee4e..23ffd0090e 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/ModelUtilsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/ModelUtilsTest.java @@ -206,7 +206,8 @@ public class ModelUtilsTest { */ @Test public void testComposedSchemasAreNotUnaliased() { - ComposedSchema composedSchema = new ComposedSchema().allOf(Arrays.asList( + ComposedSchema composedSchema = new ComposedSchema(); + composedSchema.allOf(Arrays.asList( new Schema<>().$ref("#/components/schemas/SomeSchema"), new ObjectSchema() )); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/validations/oas/OpenApiSchemaValidationsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/validations/oas/OpenApiSchemaValidationsTest.java index b2b2070ebe..7ac2fc746b 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/validations/oas/OpenApiSchemaValidationsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/validations/oas/OpenApiSchemaValidationsTest.java @@ -84,7 +84,8 @@ public class OpenApiSchemaValidationsTest { } private ComposedSchema getOneOfSample(boolean withProperties) { - ComposedSchema schema = new ComposedSchema().oneOf(Arrays.asList( + ComposedSchema schema = new ComposedSchema(); + schema.oneOf(Arrays.asList( new StringSchema(), new IntegerSchema().format("int64")) ); @@ -99,7 +100,8 @@ public class OpenApiSchemaValidationsTest { private ComposedSchema getAllOfSample(boolean withProperties) { // This doesn't matter if it's realistic; it's a structural check - ComposedSchema schema = new ComposedSchema().allOf(Arrays.asList( + ComposedSchema schema = new ComposedSchema(); + schema.allOf(Arrays.asList( new StringSchema(), new IntegerSchema().format("int64")) ); @@ -113,7 +115,8 @@ public class OpenApiSchemaValidationsTest { } private ComposedSchema getAnyOfSample(boolean withProperties) { - ComposedSchema schema = new ComposedSchema().anyOf(Arrays.asList( + ComposedSchema schema = new ComposedSchema(); + schema.anyOf(Arrays.asList( new StringSchema(), new IntegerSchema().format("int64")) ); diff --git a/modules/openapi-generator/src/test/resources/2_0/fileResponseTest.json b/modules/openapi-generator/src/test/resources/2_0/fileResponseTest.json deleted file mode 100644 index 3fd70ed45e..0000000000 --- a/modules/openapi-generator/src/test/resources/2_0/fileResponseTest.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "File Response Test", - "license": { - "name": "Apache-2.0", - "url": "https://www.apache.org/licenses/LICENSE-2.0.html" - } - }, - "basePath": "/v2", - "schemes": [ - "http" - ], - "paths": { - "/tests/fileResponse": { - "get": { - "operationId": "fileresponsetest", - "produces": [ - "application/octet-stream" - ], - "responses": { - "200": { - "description": "OutputFileData", - "schema": { - "type": "file" - } - } - } - } - } - } -} diff --git a/modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/2_0/python-prior/petstore-with-fake-endpoints-models-for-testing.yaml similarity index 100% rename from modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml rename to modules/openapi-generator/src/test/resources/2_0/python-prior/petstore-with-fake-endpoints-models-for-testing.yaml diff --git a/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml index 588fde8671..dac5c2a933 100644 --- a/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml @@ -45,6 +45,7 @@ paths: - petstore_auth: - 'write:pets' - 'read:pets' + - api_key_query: [] put: tags: - pet diff --git a/modules/openapi-generator/src/test/resources/3_0/11_regex.yaml b/modules/openapi-generator/src/test/resources/3_0/11_regex.yaml new file mode 100644 index 0000000000..1fd9eeadc9 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/11_regex.yaml @@ -0,0 +1,27 @@ +openapi: 3.0.3 +info: + title: Test + version: 1.0.0-SNAPSHOT +paths: + /test: + get: + tags: + - Test Resource + parameters: + - name: uuid + in: query + schema: + $ref: '#/components/schemas/UUID' + responses: + "200": + description: OK +components: + schemas: + UUID: + format: uuid + pattern: "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}" + type: string + StringWithRegexWithThreeFlags: + format: uuid + pattern: "/a./sim" + type: string \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/allOf-readonly.yaml b/modules/openapi-generator/src/test/resources/3_0/allOf-readonly.yaml new file mode 100644 index 0000000000..643803b6fd --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/allOf-readonly.yaml @@ -0,0 +1,40 @@ +openapi: 3.0.1 +info: + version: 1.0.0 + title: Example + license: + name: MIT +servers: + - url: http://api.example.xyz/v1 +paths: + /person/display/{personId}: + get: + parameters: + - name: personId + in: path + required: true + description: The id of the person to retrieve + schema: + type: string + operationId: list + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/club" +components: + schemas: + club: + properties: + owner: + allOf: + - $ref: '#/components/schemas/owner' + readOnly: true + + owner: + properties: + name: + type: string + maxLength: 255 \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/avro-schema/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/avro-schema/petstore.yaml new file mode 100644 index 0000000000..89461f2c97 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/avro-schema/petstore.yaml @@ -0,0 +1,748 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - api_key: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponseStatuses: + type: string + enum: + - success + - failure + - timeout + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + statuses: + type: array + items: + $ref: '#/components/schemas/ApiResponseStatuses' diff --git a/modules/openapi-generator/src/test/resources/3_0/crystal/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/crystal/petstore.yaml new file mode 100644 index 0000000000..002eaa2e8e --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/crystal/petstore.yaml @@ -0,0 +1,811 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - api_key: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + format_test: + type: object + required: + - number + - byte + - date + - password + properties: + integer: + type: integer + maximum: 100 + minimum: 10 + multipleOf: 2 + int32: + type: integer + format: int32 + maximum: 200 + minimum: 20 + int64: + type: integer + format: int64 + number: + maximum: 543.2 + minimum: 32.1 + type: number + multipleOf: 32.5 + float: + type: number + format: float + maximum: 987.6 + minimum: 54.3 + double: + type: number + format: double + maximum: 123.4 + minimum: 67.8 + decimal: + type: string + format: number + string: + type: string + pattern: '/[a-z]/i' + byte: + type: string + format: byte + binary: + type: string + format: binary + date: + type: string + format: date + example: '2020-02-02' + dateTime: + type: string + format: date-time + example: '2007-12-03T10:15:30+01:00' + uuid: + type: string + format: uuid + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + password: + type: string + format: password + maxLength: 64 + minLength: 10 + pattern_with_digits: + description: A string that is a 10 digit number. Can have leading zeros. + type: string + pattern: '^\d{10}$' + pattern_with_digits_and_delimiter: + description: A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + type: string + pattern: '/^image_\d{1,3}$/i' diff --git a/modules/openapi-generator/src/test/resources/3_0/go/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/go/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 674afde01d..7b11b81e32 100644 --- a/modules/openapi-generator/src/test/resources/3_0/go/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/go/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -839,6 +839,12 @@ paths: responses: '400': description: Someting wrong + '5XX': + description: Someting wrong + content: + 'applicatino/json': + schema: + $ref: '#/components/schemas/OuterNumber' /fake/outer/number: post: tags: @@ -1986,3 +1992,34 @@ components: type: array items: type: string + # `dup-prop` is defined in both parent and child models + # but not identical: optional vs required + DuplicatedPropChild: + allOf: + - $ref: '#/components/schemas/DuplicatedPropParent' + - type: object + properties: + 'dup-prop': + description: A discriminator value + type: string + DuplicatedPropParent: + description: parent model with duplicated property + type: object + discriminator: + propertyName: 'dup-prop' + required: + - 'dup-prop' + properties: + 'dup-prop': + description: A discriminator value + type: string + MapOfFileTest: + description: test map of file in a property + type: object + properties: + 'prop_test': + description: a property to test map of file + type: object + additionalProperties: + type: string + format: binary diff --git a/modules/openapi-generator/src/test/resources/3_0/helidon/petstore-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/helidon/petstore-for-testing.yaml new file mode 100644 index 0000000000..7384758e95 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/helidon/petstore-for-testing.yaml @@ -0,0 +1,860 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.helidon.io:8080/v2' +info: + description: >- + This spec is mainly for testing Petstore server and contains fake endpoints, + models. Please do not use this for any other purpose. For this sample, you can use the api key + `special-key` to test the authorization filters. Special characters: " + \ + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/schemas/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: integer + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: headerLong + in: header + required: true + schema: + type: integer + format: int64 + - name: cookieString + in: cookie + schema: + type: string + required: true + - name: cookieInt + in: cookie + schema: + type: integer + format: int32 + required: false + - name: cookieIntArray + in: cookie + schema: + type: array + items: + type: integer + required: false + - name: cookieStringArray + in: cookie + schema: + type: array + items: + type: string + required: false + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + - name: petDate + in: path + description: Date for test + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /pet/upload: + post: + tags: + - pet + summary: Add a few pets using form + description: '' + operationId: addPets + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/PetsForm' + description: Object that that contains info about pets + required: true + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: number + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + - name: sizeString + in: query + description: String param to test Size constraint + required: true + schema: + type: string + minLength: 5 + maxLength: 10 + - name: minLong + in: query + description: Min Long param for test + required: true + schema: + type: integer + format: int64 + minimum: 10 + - name: minDecimal + in: query + description: Min Decimal param for test + required: true + schema: + type: number + minimum: 0 + exclusiveMinimum: true + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - api_key: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + AnyValue: {} + Color: + type: string + enum: + - black + - white + - red + - green + - blue + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + PetsForm: + type: object + properties: + images[]: + type: array + items: + type: string + format: binary + image: + type: string + format: binary + titles[]: + type: array + items: + type: string + longArray: + type: array + items: + type: integer + format: int64 + stringParam: + type: string + intParam: + type: integer + format: int32 + required: + - stringParam \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/helidon/petstore-no-multipart-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/helidon/petstore-no-multipart-for-testing.yaml new file mode 100644 index 0000000000..bcf9906793 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/helidon/petstore-no-multipart-for-testing.yaml @@ -0,0 +1,789 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.helidon.io:8080/v2' +info: + description: >- + This spec is mainly for testing Petstore server and contains fake endpoints, + models. Please do not use this for any other purpose. For this sample, you can use the api key + `special-key` to test the authorization filters. Special characters: " + \ + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/schemas/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: integer + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: headerLong + in: header + required: true + schema: + type: integer + format: int64 + - name: cookieString + in: cookie + schema: + type: string + required: true + - name: cookieInt + in: cookie + schema: + type: integer + format: int32 + required: false + - name: cookieIntArray + in: cookie + schema: + type: array + items: + type: integer + required: false + - name: cookieStringArray + in: cookie + schema: + type: array + items: + type: string + required: false + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: number + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + - name: sizeString + in: query + description: String param to test Size constraint + required: true + schema: + type: string + minLength: 5 + maxLength: 10 + - name: minLong + in: query + description: Min Long param for test + required: true + schema: + type: integer + format: int64 + minimum: 10 + - name: minDecimal + in: query + description: Min Decimal param for test + required: true + schema: + type: number + minimum: 0 + exclusiveMinimum: true + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - api_key: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + AnyValue: {} + Color: + type: string + enum: + - black + - white + - red + - green + - blue + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + PetsForm: + type: object + properties: + images[]: + type: array + items: + type: string + format: binary + image: + type: string + format: binary + titles[]: + type: array + items: + type: string + longArray: + type: array + items: + type: integer + format: int64 + stringParam: + type: string + intParam: + type: integer + format: int32 + required: + - stringParam \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/inline_model_resolver.yaml b/modules/openapi-generator/src/test/resources/3_0/inline_model_resolver.yaml index e4e1e592e9..0741d3b5d7 100644 --- a/modules/openapi-generator/src/test/resources/3_0/inline_model_resolver.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/inline_model_resolver.yaml @@ -7,6 +7,14 @@ info: servers: - url: http://api.example.xyz/v1 paths: + /resolve_request_body_invalid_ref: + post: + requestBody: + $ref: '#/components/schemas/Invalid' + operationId: resolveRequestBodyInvalidRef + responses: + '200': + description: OK /resolve_inline_request_body: post: requestBody: @@ -348,6 +356,7 @@ paths: data: type: string components: + requestBodies: {} schemas: Users: type: array diff --git a/modules/openapi-generator/src/test/resources/3_0/issue13146_file_abstraction_response.yaml b/modules/openapi-generator/src/test/resources/3_0/issue13146_file_abstraction_response.yaml new file mode 100644 index 0000000000..ea4a6c6adc --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue13146_file_abstraction_response.yaml @@ -0,0 +1,19 @@ +openapi: '3.0.1' +info: + version: 1.0.0 + title: Response file abstraction test +paths: + /resource: + get: + tags: + - resource + description: Response file abstraction + operationId: resourceInResponse + responses: + '200': + description: Successful operation + content: + application/octet-stream: + schema: + type: string + format: binary \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_10865_default_values.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_10865_default_values.yaml index 3f24f7d112..c7fd7668cb 100644 --- a/modules/openapi-generator/src/test/resources/3_0/issue_10865_default_values.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/issue_10865_default_values.yaml @@ -145,6 +145,15 @@ paths: in: formData required: true type: number + - name: fn4 + in: formData + required: true + type: array + items: + type: string + default: + - item0 + responses: "200": diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_13025.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_13025.yaml new file mode 100644 index 0000000000..40cf1c1ed0 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_13025.yaml @@ -0,0 +1,44 @@ +openapi: "3.0.3" +info: + version: 1.0.0 + title: Array Not Null +paths: + /array/not/null: + post: + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Body" + responses: + "200": + description: Success +components: + schemas: + Body: + type: object + properties: + arrayThatIsNull: + type: array + nullable: true + items: + type: string + BodyWithRequiredNullalble: + type: object + required: + - arrayThatIsNull + properties: + arrayThatIsNull: + type: array + nullable: true + items: + type: string + BodyWithRequired: + type: object + required: + - arrayThatIsNotNull + properties: + arrayThatIsNotNull: + type: array + items: + type: string \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_13043_geometry_collection_expected_value.txt b/modules/openapi-generator/src/test/resources/3_0/issue_13043_geometry_collection_expected_value.txt new file mode 100644 index 0000000000..7d4d61650b --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_13043_geometry_collection_expected_value.txt @@ -0,0 +1,4 @@ +GeometryCollection( + type="GeometryCollection", + geometries=[], + ) \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_13043_recursive_model.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_13043_recursive_model.yaml new file mode 100644 index 0000000000..9b9f5d34c3 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_13043_recursive_model.yaml @@ -0,0 +1,103 @@ +openapi: 3.0.0 +info: + version: 01.01.00 + title: APITest API documentation. + termsOfService: http://api.apitest.com/party/tos/ +servers: + - url: https://api.apitest.com/v1 +paths: + /geojson: + post: + summary: Add a GeoJson Object + operationId: post-geojson + responses: + '201': + description: Created + content: + application/json: + schema: + type: string + description: GeoJson ID + '400': + description: Bad Request + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/GeoJsonGeometry' + parameters: [] + /geojson_geometry_collection: + post: + summary: Add a GeoJson GeometryCollection Object + operationId: post-geojson-geometry-collection + responses: + '201': + description: Created + content: + application/json: + schema: + type: string + description: GeoJson ID + '400': + description: Bad Request + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/GeometryCollection' + parameters: [] +components: + schemas: + GeoJsonGeometry: + title: GeoJsonGeometry + description: GeoJSON geometry + oneOf: + - $ref: '#/components/schemas/Point' + - $ref: '#/components/schemas/GeometryCollection' + discriminator: + propertyName: type + mapping: + Point: '#/components/schemas/Point' + GeometryCollection: '#/components/schemas/GeometryCollection' + externalDocs: + url: http://geojson.org/geojson-spec.html#geometry-objects + Point: + title: Point + type: object + description: GeoJSON geometry + externalDocs: + url: http://geojson.org/geojson-spec.html#id2 + properties: + coordinates: + title: Point3D + type: array + description: Point in 3D space + externalDocs: + url: http://geojson.org/geojson-spec.html#id2 + minItems: 2 + maxItems: 3 + items: + type: number + format: double + type: + type: string + default: Point + required: + - type + GeometryCollection: + title: GeometryCollection + type: object + description: GeoJSon geometry collection + required: + - type + - geometries + externalDocs: + url: http://geojson.org/geojson-spec.html#geometrycollection + properties: + type: + type: string + default: GeometryCollection + geometries: + type: array + items: + $ref: '#/components/schemas/GeoJsonGeometry' diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_13043_recursive_model_expected_value.txt b/modules/openapi-generator/src/test/resources/3_0/issue_13043_recursive_model_expected_value.txt new file mode 100644 index 0000000000..137db22fa9 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_13043_recursive_model_expected_value.txt @@ -0,0 +1,4 @@ +GeoJsonGeometry( + type="GeometryCollection", + geometries=[], + ) \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/issues_13069.yaml b/modules/openapi-generator/src/test/resources/3_0/issues_13069.yaml new file mode 100644 index 0000000000..fc644ef5ba --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issues_13069.yaml @@ -0,0 +1,23 @@ +--- +openapi: 3.0.3 +info: + title: Test + version: 1.0.0-SNAPSHOT +paths: + /test: + get: + parameters: + - name: uuid + in: query + schema: + $ref: '#/components/schemas/UUID' + responses: + "200": + description: OK + +components: + schemas: + UUID: + format: uuid + pattern: "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}" + type: string \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml index 5a1f2c2c08..f0f4fa1da3 100644 --- a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml @@ -1504,6 +1504,10 @@ components: type: string format: uuid example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + uuid_with_default: + type: string + format: uuid + default: 11111111-206d-4f12-9f12-3d1e525a8e84 password: type: string format: password @@ -2205,3 +2209,17 @@ components: properties: color: type: string + EnumStringDiscriminator: + type: object + description: An object to test discriminator of enum string + discriminator: + propertyName: enum_str_type + required: + - enum_str_type + properties: + enum_str_type: + description: enum string type + type: string + enum: + - type_a + - type_b diff --git a/modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml index 772d09dd0b..fadeb02edb 100644 --- a/modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1908,3 +1908,72 @@ components: deprecated: true items: $ref: '#/components/schemas/Bar' + Pig: + nullable: true + oneOf: + - $ref: '#/components/schemas/BasquePig' + - $ref: '#/components/schemas/DanishPig' + BasquePig: + type: object + properties: + className: + type: string + color: + type: string + required: + - className + - color + DanishPig: + type: object + properties: + className: + type: string + size: + type: integer + required: + - className + - size + NestedOneOf: + type: object + properties: + size: + type: integer + nested_pig: + $ref: '#/components/schemas/Pig' + NestedColor: + type: object + properties: + size: + type: integer + nested: + $ref: '#/components/schemas/Color' + RgbColor: + description: RGB three element array with values 0-255. + type: array + items: + type: integer + minimum: 0 + maximum: 255 + minItems: 3 + maxItems: 3 + RgbaColor: + description: RGBA four element array with values 0-255. + type: array + items: + type: integer + minimum: 0 + maximum: 255 + minItems: 4 + maxItems: 4 + HexColor: + description: 'Hex color string, such as #00FF00.' + type: string + pattern: ^#(?:[0-9a-fA-F]{3}){1,2}$ + minLength: 7 + maxLength: 7 + Color: + description: RGB array, RGBA array, or hex string. + oneOf: + - $ref: '#/components/schemas/RgbColor' + - $ref: '#/components/schemas/RgbaColor' + - $ref: '#/components/schemas/HexColor' diff --git a/modules/openapi-generator/src/test/resources/3_0/kotlin/issue13506-defaultValue-numbers.yaml b/modules/openapi-generator/src/test/resources/3_0/kotlin/issue13506-defaultValue-numbers.yaml new file mode 100644 index 0000000000..8ee94eaad2 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/kotlin/issue13506-defaultValue-numbers.yaml @@ -0,0 +1,51 @@ +openapi: 3.0.0 +info: + title: 'Issue X default value number with format' + version: latest +paths: + '/': + get: + operationId: operation + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ModelWithPropertyHavingDefault' +components: + schemas: + ModelWithPropertyHavingDefault: + properties: + propertyInt: + type: integer + default: 0 + format: int32 + propertyLong: + type: integer + default: 0 + format: int64 + propertyFloat1: + type: number + default: 0 + format: float + propertyFloat2: + type: number + default: 0.0 + format: float + propertyFloat3: + type: number + default: 0.01 + format: float + propertyDouble1: + type: number + default: 0 + format: double + propertyDouble2: + type: number + default: 0.0 + format: double + propertyDouble3: + type: number + default: 0.01 + format: double diff --git a/modules/openapi-generator/src/test/resources/3_0/oneOf_nonPrimitive.yaml b/modules/openapi-generator/src/test/resources/3_0/oneOf_nonPrimitive.yaml new file mode 100644 index 0000000000..fe9d58f0dd --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/oneOf_nonPrimitive.yaml @@ -0,0 +1,29 @@ +openapi: 3.0.1 +info: + version: 1.0.0 + title: Example - oneOf data type + license: + name: MIT +servers: + - url: http://api.example.xyz/v1 +paths: + /example: + get: + operationId: list + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Example" +components: + schemas: + Example: + oneOf: + - type: string + format: uuid + - type: string + format: date-time + - type: integer + - type: number diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-with-complex-headers.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-with-complex-headers.yaml index 2233d4e200..a21b6b4e0d 100644 --- a/modules/openapi-generator/src/test/resources/3_0/petstore-with-complex-headers.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-with-complex-headers.yaml @@ -43,6 +43,10 @@ paths: type: array items: $ref: '#/components/requestBodies/Pet' + - name: Accept + in: header + schema: + $ref: '#/components/schemas/MediaType' requestBody: $ref: '#/components/requestBodies/Pet' put: @@ -578,6 +582,9 @@ components: name: api_key in: header schemas: + MediaType: + type: string + enum: ['application/json', 'application/xml'] Order: title: Pet Order description: An order for a pets from the pet store diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml index 4a0777e930..4ff8806122 100644 --- a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -33,6 +33,21 @@ paths: servers: - url: 'http://petstore.swagger.io/v2' - url: 'http://path-server-test.petstore.local/v2' + - url: 'http://{server}.swagger.io:{port}/v2' + description: test server with variables + variables: + server: + description: target server + enum: + - 'petstore' + - 'qa-petstore' + - 'dev-petstore' + default: 'petstore' + port: + enum: + - 80 + - 8080 + default: 80 post: tags: - pet diff --git a/modules/openapi-generator/src/test/resources/3_0/protobuf/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/protobuf/petstore.yaml new file mode 100644 index 0000000000..3db600f31e --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/protobuf/petstore.yaml @@ -0,0 +1,748 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - api_key: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + OtherTest: + title: A model to test other use cases + description: A model to test other use cases + type: object + properties: + set_test: + type: array + uniqueItems: true + items: + type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/python-experimental/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/python-prior/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml similarity index 81% rename from modules/openapi-generator/src/test/resources/3_0/python-experimental/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml rename to modules/openapi-generator/src/test/resources/3_0/python-prior/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 9a63e801a6..8d040105b9 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python-experimental/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python-prior/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -16,6 +16,8 @@ tags: description: Access to Petstore orders - name: user description: Operations about user + - name: fake + description: Fake api used for feature testing paths: /foo: get: @@ -37,11 +39,9 @@ paths: tags: - pet summary: Add a new pet to the store - description: Add a new pet to the store + description: '' operationId: addPet responses: - '200': - description: Ok '405': description: Invalid input security: @@ -135,6 +135,7 @@ paths: type: array items: type: string + example: ['tag1', 'tag2'] responses: '200': description: successful operation @@ -247,45 +248,6 @@ paths: - petstore_auth: - 'write:pets' - 'read:pets' - '/pet/{petId}/uploadImage': - post: - tags: - - pet - summary: uploads an image - description: '' - operationId: uploadImage - parameters: - - name: petId - in: path - description: ID of pet to update - required: true - schema: - type: integer - format: int64 - responses: - '200': - description: successful operation - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - security: - - petstore_auth: - - 'write:pets' - - 'read:pets' - requestBody: - content: - multipart/form-data: - schema: - type: object - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - file: - description: file to upload - type: string - format: binary /store/inventory: get: tags: @@ -555,7 +517,7 @@ paths: - 'fake_classname_tags 123#$%^' summary: To test class name in snake case description: To test class name in snake case - operationId: Classname + operationId: testClassname responses: '200': description: successful operation @@ -573,7 +535,7 @@ paths: - fake summary: To test "client" model description: To test "client" model - operationId: ClientModel + operationId: testClientModel responses: '200': description: successful operation @@ -588,7 +550,7 @@ paths: - fake summary: To test enum parameters description: To test enum parameters - operationId: EnumParameters + operationId: testEnumParameters parameters: - name: enum_header_string_array in: header @@ -691,7 +653,7 @@ paths: 假端點 偽のエンドポイント 가짜 엔드 포인트 - operationId: EndpointParameters + operationId: testEndpointParameters responses: '400': description: Invalid username supplied @@ -730,12 +692,14 @@ paths: type: number format: float maximum: 987.6 + exclusiveMaximum: true double: description: None type: number format: double minimum: 67.8 maximum: 123.4 + exclusiveMaximum: true string: description: None type: string @@ -783,7 +747,7 @@ paths: - bearer_test: [] summary: Fake endpoint to test group parameters (optional) description: Fake endpoint to test group parameters (optional) - operationId: GroupParameters + operationId: testGroupParameters x-group-parameters: true parameters: - name: required_string_group @@ -918,6 +882,15 @@ paths: application/json: schema: $ref: '#/components/schemas/AnimalFarm' + examples: + simple-list: + summary: Simple list example + description: Should not get into code examples + value: + - className: foo + color: yellow + - className: bar + color: green required: false responses: '200': @@ -932,13 +905,13 @@ paths: tags: - fake description: Test serialization of object with $refed properties - operationId: ComposedOneOfDifferentTypes + operationId: ComposedOneOfNumberWithValidations requestBody: description: Input model content: application/json: schema: - $ref: '#/components/schemas/ComposedOneOfDifferentTypes' + $ref: '#/components/schemas/ComposedOneOfNumberWithValidations' required: false responses: '200': @@ -946,7 +919,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ComposedOneOfDifferentTypes' + $ref: '#/components/schemas/ComposedOneOfNumberWithValidations' /fake/refs/object_model_with_ref_props: post: tags: @@ -1009,6 +982,26 @@ paths: application/json: schema: $ref: '#/components/schemas/ArrayOfEnums' + /fake/refs/enum-test: + post: + tags: + - fake + summary: Object contains enum properties and array properties containing enums + operationId: EnumTest + requestBody: + description: Input object + content: + application/json: + schema: + $ref: '#/components/schemas/Enum_Test' + required: false + responses: + 200: + description: Got object containing enums + content: + application/json: + schema: + $ref: '#/components/schemas/Enum_Test' /fake/additional-properties-with-array-of-enums: get: tags: @@ -1035,7 +1028,7 @@ paths: - fake summary: test json serialization of form data description: '' - operationId: JsonFormData + operationId: testJsonFormData responses: '200': description: successful operation @@ -1060,7 +1053,7 @@ paths: - fake summary: test inline additionalProperties description: '' - operationId: InlineAdditionalProperties + operationId: testInlineAdditionalProperties responses: '200': description: successful operation @@ -1077,7 +1070,7 @@ paths: put: tags: - fake - operationId: BodyWithQueryParams + operationId: testBodyWithQueryParams parameters: - name: query in: query @@ -1116,7 +1109,7 @@ paths: description: >- For this test, the body for this request much reference a schema named `File`. - operationId: BodyWithFileSchema + operationId: testBodyWithFileSchema responses: '200': description: Success @@ -1126,37 +1119,12 @@ paths: schema: $ref: '#/components/schemas/FileSchemaTestClass' required: true - /fake/case-sensitive-params: - put: - tags: - - fake - description: Ensures that original naming is used in endpoint params, that way we on't have collisions - operationId: CaseSensitiveParams - parameters: - - name: someVar - in: query - required: true - schema: - type: string - - name: SomeVar - in: query - required: true - schema: - type: string - - name: some_var - in: query - required: true - schema: - type: string - responses: - "200": - description: Success - /fake/test-query-paramters: + /fake/test-query-parameters: put: tags: - fake description: To test the collection format in query parameters - operationId: QueryParameterCollectionFormat + operationId: testQueryParameterCollectionFormat parameters: - name: pipe in: query @@ -1199,153 +1167,37 @@ paths: type: array items: type: string - - name: refParam - in: query - required: true - schema: - $ref: '#/components/schemas/StringWithValidation' responses: "200": description: Success - '/fake/{petId}/uploadImageWithRequiredFile': - post: - tags: - - pet - summary: uploads an image (required) - description: '' - operationId: uploadFileWithRequiredFile - parameters: - - name: petId - in: path - description: ID of pet to update - required: true - schema: - type: integer - format: int64 - responses: - '200': - description: successful operation - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - security: - - petstore_auth: - - 'write:pets' - - 'read:pets' - requestBody: - content: - multipart/form-data: - schema: - type: object - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - requiredFile: - description: file to upload - type: string - format: binary - required: - - requiredFile - /fake/parameterCollisions/{1}/{aB}/{Ab}/{self}/{A-B}/: - post: + /{fileName}: + get: + servers: + - url: http://www.jtricks.com tags: - fake - summary: parameter collision case - operationId: parameterCollisions + summary: downloads a file using Content-Disposition + operationId: downloadAttachment parameters: - - name: 1 - in: query - schema: - type: string - - name: aB - in: query - schema: - type: string - - name: Ab - in: query - schema: - type: string - - name: self - in: query - schema: - type: string - - name: A-B - in: query - schema: - type: string - - name: 1 - in: header - schema: - type: string - - name: aB - in: header - schema: - type: string - - name: self - in: header - schema: - type: string - - name: A-B - in: header - schema: - type: string - - name: 1 + - name: fileName in: path + description: file name required: true schema: type: string - - name: aB - in: path - required: true - schema: - type: string - - name: Ab - in: path - required: true - schema: - type: string - - name: self - in: path - required: true - schema: - type: string - - name: A-B - in: path - required: true - schema: - type: string - - name: 1 - in: cookie - schema: - type: string - - name: aB - in: cookie - schema: - type: string - - name: Ab - in: cookie - schema: - type: string - - name: self - in: cookie - schema: - type: string - - name: A-B - in: cookie - schema: - type: string - requestBody: - content: - application/json: - schema: {} responses: 200: - description: success + description: successful operation content: - application/json: - schema: {} + 'text/plain': + schema: + type: string + format: binary + headers: + Content-Disposition: + schema: + type: string + description: "describes the received file. Looks like: 'attachment; filename=fileName.txt'" /fake/uploadFile: post: tags: @@ -1436,147 +1288,100 @@ paths: application/json: schema: $ref: '#/components/schemas/HealthCheckResult' - /fake/inlineComposition/: + /fake/postInlineAdditionalPropertiesRefPayload: post: tags: - fake - summary: testing composed schemas at inline locations - operationId: inlineComposition - parameters: - - name: compositionAtRoot - in: query - schema: - allOf: - - type: string - minLength: 1 - - name: compositionInProperty - in: query - schema: - type: object - properties: - someProp: - allOf: - - type: string - minLength: 1 + operationId: postInlineAdditionalPropertiesRefPayload + responses: + 200: + description: InlineAdditionalPropertiesRefPayload + content: + application/json: + schema: + $ref: '#/components/schemas/InlineAdditionalPropertiesRefPayload' requestBody: content: application/json: schema: - allOf: - - type: string - minLength: 1 - multipart/form-data: + $ref: '#/components/schemas/InlineAdditionalPropertiesRefPayload' + /fake/postInlineAdditionalPropertiesPayload: + post: + tags: + - fake + operationId: postInlineAdditionalPropertiesPayload + responses: + 200: + description: InlineAdditionalPropertiesPayload + content: + application/json: + schema: + description: this payload is used for verification that some model_to_dict issues are fixed + type: object + properties: + arrayData: + type: array + nullable: true + items: + type: object + properties: + labels: + type: array + items: + type: string + nullable: true + requestBody: + content: + application/json: schema: + description: this payload is used for verification that some model_to_dict issues are fixed type: object properties: - someProp: - allOf: - - type: string - minLength: 1 + arrayData: + type: array + nullable: true + items: + type: object + properties: + labels: + type: array + items: + type: string + nullable: true + /fake/TxRxAnyOfModel: + post: + tags: + - fake + operationId: txRxAnyOfModel + responses: + 200: + description: TxRxAnyOfModel + content: + application/json: + schema: + $ref: '#/components/schemas/GmFruitNoProperties' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/GmFruitNoProperties' + /fake/TxRxAllOfModel: + post: + tags: + - fake + operationId: txRxAllOfModel responses: 200: description: success content: application/json: schema: - allOf: - - type: string - minLength: 1 - multipart/form-data: - schema: - type: object - properties: - someProp: - allOf: - - type: string - minLength: 1 - '/fake/objInQuery': - get: - tags: - - fake - summary: user list - operationId: objectInQuery - parameters: - - name: mapBean - in: query - required: false - description: mapBean - style: deepObject - explode: true - schema: - type: object - properties: - keyword: - title: keyword - type: string - responses: - '200': - description: ok - '/fake/refObjInQuery': - get: - tags: - - fake - summary: user list - operationId: refObjectInQuery - parameters: - - name: mapBean - in: query - required: false - description: mapBean - style: deepObject - explode: true - schema: - $ref: '#/components/schemas/Foo' - responses: - '200': - description: ok - '/fake/jsonWithCharset': - post: - tags: - - fake - summary: json with charset tx and rx - operationId: jsonWithCharset + $ref: '#/components/schemas/StreamOptions' requestBody: content: - application/json; charset=utf-8: - schema: {} - responses: - 200: - description: success - content: - application/json; charset=utf-8: - schema: {} - "/fake/responseWithoutSchema": - get: - tags: - - fake - summary: receives a response without schema - operationId: responseWithoutSchema - responses: - '200': - description: contents without schema definition - content: - application/json: {} - application/xml: {} - /fake/deleteCoffee/{id}: - delete: - operationId: deleteCoffee - summary: Delete coffee - description: Delete the coffee identified by the given id, (delete without request body) - tags: - - fake - parameters: - - name: id - in: path - description: The internal object id - required: true - schema: - type: string - responses: - '200': - description: OK - default: - description: Unexpected error + application/json: + schema: + $ref: '#/components/schemas/StreamOptions' servers: - url: 'http://{server}.swagger.io:{port}/v2' description: petstore server @@ -1749,12 +1554,13 @@ components: Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - anyTypeExceptNullProp: - description: any type except 'null' - Here the 'type' attribute is not specified, which means the value can be anything, - including the null value, string, number, boolean, array or object. - not: - type: 'null' + # TODO: this should be supported, currently there are some issues in the code generation. + #anyTypeExceptNullProp: + # description: any type except 'null' + # Here the 'type' attribute is not specified, which means the value can be anything, + # including the null value, string, number, boolean, array or object. + # not: + # type: 'null' anyTypePropNullable: description: test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, @@ -1826,7 +1632,6 @@ components: description: Model for testing reserved words properties: return: - description: this is a reserved python keyword type: integer format: int32 xml: @@ -1844,18 +1649,19 @@ components: type: integer format: int32 property: - description: this is a reserved python keyword type: string + 123Number: + type: integer + readOnly: true xml: name: Name 200_response: - description: model with an invalid class name for python, starts with a number + description: Model for testing model name starting with number properties: name: type: integer format: int32 class: - description: this is a reserved python keyword type: string xml: name: Name @@ -1871,6 +1677,8 @@ components: properties: breed: type: string + legs: + $ref: '#/components/schemas/Legs' Cat: allOf: - $ref: '#/components/schemas/Animal' @@ -1878,6 +1686,19 @@ components: properties: declawed: type: boolean + Legs: + type: object + required: + - legs + properties: + legs: + enum: + - '2' + - '4' + default: '4' + x-enum-as-string: true + name: + type: string Address: type: object additionalProperties: @@ -1894,11 +1715,15 @@ components: color: type: string default: red + tail: + type: boolean + default: true + readOnly: true AnimalFarm: type: array items: $ref: '#/components/schemas/Animal' - FormatTest: + format_test: type: object required: - number @@ -1914,9 +1739,6 @@ components: int32: type: integer format: int32 - int32withValidations: - type: integer - format: int32 maximum: 200 minimum: 20 int64: @@ -1928,27 +1750,15 @@ components: type: number multipleOf: 32.5 float: - description: this is a reserved python keyword type: number format: float maximum: 987.6 minimum: 54.3 - float32: - type: number - format: float double: type: number format: double maximum: 123.4 minimum: 67.8 - float64: - type: number - format: double - arrayWithUniqueItems: - type: array - items: - type: number - uniqueItems: true string: type: string pattern: '/[a-z]/i' @@ -1986,8 +1796,6 @@ components: description: A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. type: string pattern: '/^image_\d{1,3}$/i' - noneProp: - type: 'null' EnumClass: type: string default: '-efg' @@ -2024,6 +1832,12 @@ components: enum: - 1.1 - -1.2 + enum_bool: + type: boolean + enum: + - false + boolEnum: + $ref: '#/components/schemas/BooleanEnum' stringEnum: $ref: '#/components/schemas/StringEnum' IntegerEnum: @@ -2034,6 +1848,12 @@ components: $ref: '#/components/schemas/IntegerEnumWithDefaultValue' IntegerEnumOneValue: $ref: '#/components/schemas/IntegerEnumOneValue' + InlineArrayOfStrEnum: + type: array + items: + $ref: '#/components/schemas/StringEnum' + ArrayOfStrEnum: + $ref: '#/components/schemas/ArrayOfEnums' AdditionalPropertiesClass: type: object properties: @@ -2078,6 +1898,11 @@ components: type: object additionalProperties: $ref: '#/components/schemas/Animal' + List: + type: object + properties: + 123-list: + type: string Client: type: object properties: @@ -2213,12 +2038,6 @@ components: - 0 - 1 - 2 - IntegerEnumBig: - type: integer - enum: - - 10 - - 11 - - 12 StringEnumWithDefaultValue: type: string enum: @@ -2237,51 +2056,29 @@ components: type: integer enum: - 0 - NullableString: - nullable: true - type: string ObjectModelWithRefProps: description: a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations type: object properties: - myNumber: + my_number: $ref: '#/definitions/NumberWithValidations' - myString: + my_readonly: + $ref: '#/definitions/Readonly' + my_string: $ref: '#/definitions/String' - myBoolean: + my_boolean: $ref: '#/definitions/Boolean' NumberWithValidations: type: number minimum: 10 maximum: 20 - ComposedAnyOfDifferentTypesNoValidations: - anyOf: - - type: object - - type: string - format: date - - type: string - format: date-time - - type: string - format: binary - - type: string - format: byte - - type: string - - type: object - - type: boolean - - type: 'null' - - type: array - items: {} - - type: number - - type: number - format: float - - type: number - format: double - - type: integer - - type: integer - format: int32 - - type: integer - format: int64 - ComposedOneOfDifferentTypes: + Readonly: + type: object + readOnly: true + properties: + name: + type: string + ComposedOneOfNumberWithValidations: description: this is a model that allows payloads of type object or number oneOf: - $ref: '#/components/schemas/NumberWithValidations' @@ -2289,16 +2086,6 @@ components: - type: 'null' - type: string format: date - - type: object - minProperties: 4 - maxProperties: 4 - - type: array - maxItems: 4 - minItems: 4 - items: {} - - type: string - format: date-time - pattern: '^2020.*' Number: type: number String: @@ -2325,26 +2112,13 @@ components: sourceURI: description: Test capitalization type: string - ObjectWithDifficultlyNamedProps: - type: object - description: model with properties that have invalid names for python + _special_model.name_: properties: '$special[property.name]': type: integer format: int64 - 123-list: - type: string - 123Number: - type: integer - readOnly: true - required: - - 123-list - _special_model.name_: - type: object - description: model with an invalid class name for python - properties: - a: - type: string + xml: + name: '$special[model.name]' HealthCheckResult: type: object properties: @@ -2391,6 +2165,9 @@ components: items: type: object nullable: true + object_nullable: + type: object + nullable: true object_nullable_prop: type: object nullable: true @@ -2408,9 +2185,21 @@ components: type: object nullable: true additionalProperties: - type: object nullable: true + ComposedSchemaWithPropsAndNoAddProps: + properties: + color: + type: string + allOf: + - $ref: '#/components/schemas/Tag' + # Below additionalProperties is set to false to validate the use + # case when a composed schema has additionalProperties set to false. + # This definition will only allow in object payloads that set color and no other properties because + # additionalProperties are evaluated at the schema level and do not include composed schema + # properties. Only color is defined here, all others are additional + additionalProperties: false fruit: + description: a schema that tests oneOf and includes a schema level property properties: color: type: string @@ -2452,8 +2241,6 @@ components: type: boolean className: type: string - enum: - - whale required: - className zebra: @@ -2467,8 +2254,6 @@ components: - grevys className: type: string - enum: - - zebra required: - className additionalProperties: true @@ -2483,8 +2268,6 @@ components: properties: className: type: string - enum: - - BasquePig required: - className DanishPig: @@ -2492,10 +2275,12 @@ components: properties: className: type: string - enum: - - DanishPig required: - className + GmFruitNoProperties: + anyOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' gmFruit: properties: color: @@ -2504,6 +2289,8 @@ components: - $ref: '#/components/schemas/apple' - $ref: '#/components/schemas/banana' fruitReq: + description: a schema where additionalProperties is on in the composed schema and off in the oneOf object schemas + also, this schem accepts null as a value oneOf: - type: 'null' - $ref: '#/components/schemas/appleReq' @@ -2574,23 +2361,25 @@ components: propertyName: shapeType NullableShape: description: The value may be a shape or the 'null' value. - For a composed schema to validate a null payload, - one of its chosen oneOf schemas must be type null - or nullable (introduced in OAS schema >= 3.0) + The 'nullable' attribute was introduced in OAS schema >= 3.0 + and has been deprecated in OAS schema >= 3.1. oneOf: - $ref: '#/components/schemas/Triangle' - $ref: '#/components/schemas/Quadrilateral' - - type: "null" - TriangleInterface: + discriminator: + propertyName: shapeType + nullable: true + ShapeInterface: properties: shapeType: type: string - enum: - - 'Triangle' + required: + - shapeType + TriangleInterface: + properties: triangleType: type: string required: - - shapeType - triangleType Triangle: oneOf: @@ -2603,41 +2392,21 @@ components: # equivalent to allowing undeclared properties of any type. EquilateralTriangle: allOf: + - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/TriangleInterface' - - type: object - properties: - triangleType: - type: string - enum: - - 'EquilateralTriangle' IsoscelesTriangle: allOf: + - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/TriangleInterface' - - type: object - properties: - triangleType: - type: string - enum: - - 'IsoscelesTriangle' ScaleneTriangle: allOf: + - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/TriangleInterface' - - type: object - properties: - triangleType: - type: string - enum: - - 'ScaleneTriangle' QuadrilateralInterface: properties: - shapeType: - type: string - enum: - - 'Quadrilateral' quadrilateralType: type: string required: - - shapeType - quadrilateralType Quadrilateral: oneOf: @@ -2647,22 +2416,12 @@ components: propertyName: quadrilateralType SimpleQuadrilateral: allOf: + - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/QuadrilateralInterface' - - type: object - properties: - quadrilateralType: - type: string - enum: - - 'SimpleQuadrilateral' ComplexQuadrilateral: allOf: + - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/QuadrilateralInterface' - - type: object - properties: - quadrilateralType: - type: string - enum: - - 'ComplexQuadrilateral' GrandparentAnimal: type: object required: @@ -2702,131 +2461,91 @@ components: type: object ObjectWithValidations: type: object - minProperties: 2 + minProperties: 1 SomeObject: allOf: - $ref: '#/components/schemas/ObjectInterface' - ArrayWithValidationsInItems: - type: array - maxItems: 2 - items: - type: integer - format: int64 - maximum: 7 - ArrayHoldingAnyType: - type: array - items: - description: any type can be stored here - DateWithValidations: - type: string - format: date - pattern: '^2020.*' - DateTimeWithValidations: - type: string - format: date-time - pattern: '^2020.*' - NoAdditionalProperties: + SomeObjectWithSelfAttr: type: object properties: - id: - type: integer - format: int64 - petId: - type: integer - format: int64 - required: - - id - additionalProperties: false - IntegerMax10: - type: integer - format: int64 - maximum: 10 - IntegerMin15: - type: integer - format: int64 - minimum: 15 - StringWithValidation: - type: string - minLength: 7 - Player: - type: object - description: a model that includes a self reference this forces properties and additionalProperties - to be lazy loaded in python models because the Player class has not fully loaded when defining - properties - properties: - name: + self: type: string - enemyPlayer: - $ref: '#/components/schemas/Player' + InlineAdditionalPropertiesRefPayload: + description: this payload is used for verification that some model_to_dict issues are fixed + type: object + properties: + arrayData: + type: array + nullable: true + items: + type: object + properties: + labels: + type: array + items: + type: string + nullable: true + Mole: + type: object + required: + - blind + - smell + - hearing + properties: + blind: + type: boolean + readOnly: true + smell: + type: string + readOnly: false + touch: + type: boolean + readOnly: true + taste: + type: string + readOnly: false + hearing: + type: boolean + seeingGhosts: + type: boolean BooleanEnum: type: boolean enum: - true - ComposedObject: - type: object - allOf: - - {} - ComposedNumber: - type: number - allOf: - - {} - ComposedString: - type: string - allOf: - - {} - ComposedBool: - type: boolean - allOf: - - {} - ComposedArray: - type: array - items: {} - allOf: - - {} - ComposedNone: - type: 'null' - allOf: - - {} - Currency: - type: string - enum: - - eur - - usd - Money: + FooObject: type: object properties: - amount: - type: string - format: number - currency: - $ref: '#/components/schemas/Currency' - required: - - amount - - currency - DecimalPayload: - type: string - format: number - ObjectWithDecimalProperties: + prop1: + type: array + items: + type: object + prop2: + type: object + StreamOptions: + allOf: + - $ref: "#/components/schemas/EgressThresholdOptions" + - $ref: "#/components/schemas/PublishOptions" + + EgressThresholdOptions: type: object properties: - length: - $ref: '#/components/schemas/DecimalPayload' - width: - type: string - format: number - cost: - $ref: '#/components/schemas/Money' - ObjectWithInlineCompositionProperty: + egressThresholds: + type: object + additionalProperties: + type: number + minimum: 0 + maximum: 1 + example: 0.9 + + PublishOptions: type: object properties: - someProp: - allOf: - - type: string - minLength: 1 - UUIDString: - type: string - format: uuid - minLength: 1 - AnyTypeNotString: - not: - type: string + publish: + type : object + properties: + egressUnknownDetections: + type: boolean + example: true + filterZeroDetections: + type: boolean + example: true diff --git a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 8d040105b9..deef554542 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -16,8 +16,6 @@ tags: description: Access to Petstore orders - name: user description: Operations about user - - name: fake - description: Fake api used for feature testing paths: /foo: get: @@ -33,15 +31,17 @@ paths: $ref: '#/components/schemas/Foo' /pet: servers: - - url: 'http://petstore.swagger.io/v2' - - url: 'http://path-server-test.petstore.local/v2' + - url: 'https://petstore.swagger.io/v2' + - url: 'https://path-server-test.petstore.local/v2' post: tags: - pet summary: Add a new pet to the store - description: '' + description: Add a new pet to the store operationId: addPet responses: + '200': + description: Ok '405': description: Invalid input security: @@ -135,7 +135,6 @@ paths: type: array items: type: string - example: ['tag1', 'tag2'] responses: '200': description: successful operation @@ -248,6 +247,45 @@ paths: - petstore_auth: - 'write:pets' - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadImage + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary /store/inventory: get: tags: @@ -507,8 +545,8 @@ paths: schema: type: string responses: - '400': - description: Invalid username supplied + '200': + description: Success '404': description: User not found /fake_classname_test: @@ -517,7 +555,7 @@ paths: - 'fake_classname_tags 123#$%^' summary: To test class name in snake case description: To test class name in snake case - operationId: testClassname + operationId: Classname responses: '200': description: successful operation @@ -535,7 +573,7 @@ paths: - fake summary: To test "client" model description: To test "client" model - operationId: testClientModel + operationId: ClientModel responses: '200': description: successful operation @@ -550,7 +588,7 @@ paths: - fake summary: To test enum parameters description: To test enum parameters - operationId: testEnumParameters + operationId: EnumParameters parameters: - name: enum_header_string_array in: header @@ -613,8 +651,8 @@ paths: - 1.1 - -1.2 responses: - '400': - description: Invalid request + '200': + description: Success '404': description: Not found requestBody: @@ -653,10 +691,10 @@ paths: 假端點 偽のエンドポイント 가짜 엔드 포인트 - operationId: testEndpointParameters + operationId: EndpointParameters responses: - '400': - description: Invalid username supplied + '200': + description: Success '404': description: User not found security: @@ -692,14 +730,12 @@ paths: type: number format: float maximum: 987.6 - exclusiveMaximum: true double: description: None type: number format: double minimum: 67.8 maximum: 123.4 - exclusiveMaximum: true string: description: None type: string @@ -747,7 +783,7 @@ paths: - bearer_test: [] summary: Fake endpoint to test group parameters (optional) description: Fake endpoint to test group parameters (optional) - operationId: testGroupParameters + operationId: GroupParameters x-group-parameters: true parameters: - name: required_string_group @@ -786,8 +822,8 @@ paths: type: integer format: int64 responses: - '400': - description: Someting wrong + '200': + description: succeeded /fake/refs/number: post: tags: @@ -882,15 +918,6 @@ paths: application/json: schema: $ref: '#/components/schemas/AnimalFarm' - examples: - simple-list: - summary: Simple list example - description: Should not get into code examples - value: - - className: foo - color: yellow - - className: bar - color: green required: false responses: '200': @@ -905,13 +932,13 @@ paths: tags: - fake description: Test serialization of object with $refed properties - operationId: ComposedOneOfNumberWithValidations + operationId: ComposedOneOfDifferentTypes requestBody: description: Input model content: application/json: schema: - $ref: '#/components/schemas/ComposedOneOfNumberWithValidations' + $ref: '#/components/schemas/ComposedOneOfDifferentTypes' required: false responses: '200': @@ -919,7 +946,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ComposedOneOfNumberWithValidations' + $ref: '#/components/schemas/ComposedOneOfDifferentTypes' /fake/refs/object_model_with_ref_props: post: tags: @@ -982,26 +1009,6 @@ paths: application/json: schema: $ref: '#/components/schemas/ArrayOfEnums' - /fake/refs/enum-test: - post: - tags: - - fake - summary: Object contains enum properties and array properties containing enums - operationId: EnumTest - requestBody: - description: Input object - content: - application/json: - schema: - $ref: '#/components/schemas/Enum_Test' - required: false - responses: - 200: - description: Got object containing enums - content: - application/json: - schema: - $ref: '#/components/schemas/Enum_Test' /fake/additional-properties-with-array-of-enums: get: tags: @@ -1028,7 +1035,7 @@ paths: - fake summary: test json serialization of form data description: '' - operationId: testJsonFormData + operationId: JsonFormData responses: '200': description: successful operation @@ -1053,7 +1060,7 @@ paths: - fake summary: test inline additionalProperties description: '' - operationId: testInlineAdditionalProperties + operationId: InlineAdditionalProperties responses: '200': description: successful operation @@ -1070,7 +1077,7 @@ paths: put: tags: - fake - operationId: testBodyWithQueryParams + operationId: BodyWithQueryParams parameters: - name: query in: query @@ -1109,7 +1116,7 @@ paths: description: >- For this test, the body for this request much reference a schema named `File`. - operationId: testBodyWithFileSchema + operationId: BodyWithFileSchema responses: '200': description: Success @@ -1119,12 +1126,37 @@ paths: schema: $ref: '#/components/schemas/FileSchemaTestClass' required: true - /fake/test-query-parameters: + /fake/case-sensitive-params: + put: + tags: + - fake + description: Ensures that original naming is used in endpoint params, that way we on't have collisions + operationId: CaseSensitiveParams + parameters: + - name: someVar + in: query + required: true + schema: + type: string + - name: SomeVar + in: query + required: true + schema: + type: string + - name: some_var + in: query + required: true + schema: + type: string + responses: + "200": + description: Success + /fake/test-query-paramters: put: tags: - fake description: To test the collection format in query parameters - operationId: testQueryParameterCollectionFormat + operationId: QueryParameterCollectionFormat parameters: - name: pipe in: query @@ -1167,37 +1199,153 @@ paths: type: array items: type: string + - name: refParam + in: query + required: true + schema: + $ref: '#/components/schemas/StringWithValidation' responses: "200": description: Success - /{fileName}: - get: - servers: - - url: http://www.jtricks.com + '/fake/{petId}/uploadImageWithRequiredFile': + post: + tags: + - pet + summary: uploads an image (required) + description: '' + operationId: uploadFileWithRequiredFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + type: string + format: binary + required: + - requiredFile + /fake/parameterCollisions/{1}/{aB}/{Ab}/{self}/{A-B}/: + post: tags: - fake - summary: downloads a file using Content-Disposition - operationId: downloadAttachment + summary: parameter collision case + operationId: parameterCollisions parameters: - - name: fileName + - name: 1 + in: query + schema: + type: string + - name: aB + in: query + schema: + type: string + - name: Ab + in: query + schema: + type: string + - name: self + in: query + schema: + type: string + - name: A-B + in: query + schema: + type: string + - name: 1 + in: header + schema: + type: string + - name: aB + in: header + schema: + type: string + - name: self + in: header + schema: + type: string + - name: A-B + in: header + schema: + type: string + - name: 1 in: path - description: file name required: true schema: type: string + - name: aB + in: path + required: true + schema: + type: string + - name: Ab + in: path + required: true + schema: + type: string + - name: self + in: path + required: true + schema: + type: string + - name: A-B + in: path + required: true + schema: + type: string + - name: 1 + in: cookie + schema: + type: string + - name: aB + in: cookie + schema: + type: string + - name: Ab + in: cookie + schema: + type: string + - name: self + in: cookie + schema: + type: string + - name: A-B + in: cookie + schema: + type: string + requestBody: + content: + application/json: + schema: {} responses: 200: - description: successful operation + description: success content: - 'text/plain': - schema: - type: string - format: binary - headers: - Content-Disposition: - schema: - type: string - description: "describes the received file. Looks like: 'attachment; filename=fileName.txt'" + application/json: + schema: {} /fake/uploadFile: post: tags: @@ -1288,100 +1436,182 @@ paths: application/json: schema: $ref: '#/components/schemas/HealthCheckResult' - /fake/postInlineAdditionalPropertiesRefPayload: + /fake/inlineComposition/: post: tags: - fake - operationId: postInlineAdditionalPropertiesRefPayload - responses: - 200: - description: InlineAdditionalPropertiesRefPayload - content: - application/json: - schema: - $ref: '#/components/schemas/InlineAdditionalPropertiesRefPayload' + summary: testing composed schemas at inline locations + operationId: inlineComposition + parameters: + - name: compositionAtRoot + in: query + schema: + allOf: + - type: string + minLength: 1 + - name: compositionInProperty + in: query + schema: + type: object + properties: + someProp: + allOf: + - type: string + minLength: 1 requestBody: content: application/json: schema: - $ref: '#/components/schemas/InlineAdditionalPropertiesRefPayload' - /fake/postInlineAdditionalPropertiesPayload: - post: - tags: - - fake - operationId: postInlineAdditionalPropertiesPayload - responses: - 200: - description: InlineAdditionalPropertiesPayload - content: - application/json: - schema: - description: this payload is used for verification that some model_to_dict issues are fixed - type: object - properties: - arrayData: - type: array - nullable: true - items: - type: object - properties: - labels: - type: array - items: - type: string - nullable: true - requestBody: - content: - application/json: + allOf: + - type: string + minLength: 1 + multipart/form-data: schema: - description: this payload is used for verification that some model_to_dict issues are fixed type: object properties: - arrayData: - type: array - nullable: true - items: - type: object - properties: - labels: - type: array - items: - type: string - nullable: true - /fake/TxRxAnyOfModel: - post: - tags: - - fake - operationId: txRxAnyOfModel - responses: - 200: - description: TxRxAnyOfModel - content: - application/json: - schema: - $ref: '#/components/schemas/GmFruitNoProperties' - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/GmFruitNoProperties' - /fake/TxRxAllOfModel: - post: - tags: - - fake - operationId: txRxAllOfModel + someProp: + allOf: + - type: string + minLength: 1 responses: 200: description: success content: application/json: schema: - $ref: '#/components/schemas/StreamOptions' + allOf: + - type: string + minLength: 1 + multipart/form-data: + schema: + type: object + properties: + someProp: + allOf: + - type: string + minLength: 1 + '/fake/objInQuery': + get: + tags: + - fake + summary: user list + operationId: objectInQuery + parameters: + - name: mapBean + in: query + required: false + description: mapBean + style: deepObject + explode: true + schema: + type: object + properties: + keyword: + title: keyword + type: string + responses: + '200': + description: ok + '/fake/refObjInQuery': + get: + tags: + - fake + summary: user list + operationId: refObjectInQuery + parameters: + - name: mapBean + in: query + required: false + description: mapBean + style: deepObject + explode: true + schema: + $ref: '#/components/schemas/Foo' + responses: + '200': + description: ok + '/fake/jsonWithCharset': + post: + tags: + - fake + summary: json with charset tx and rx + operationId: jsonWithCharset requestBody: content: - application/json: + application/json; charset=utf-8: + schema: {} + responses: + 200: + description: success + content: + application/json; charset=utf-8: + schema: {} + "/fake/responseWithoutSchema": + get: + tags: + - fake + summary: receives a response without schema + operationId: responseWithoutSchema + responses: + '200': + description: contents without schema definition + content: + application/json: {} + application/xml: {} + /fake/jsonPatch: + patch: + summary: json patch + description: json patch route with a requestBody + operationId: jsonPatch + tags: + - fake + requestBody: + content: + application/json-patch+json: schema: - $ref: '#/components/schemas/StreamOptions' + $ref: '#/components/schemas/JSONPatchRequest' + responses: + '200': + description: OK + /fake/deleteCoffee/{id}: + delete: + operationId: deleteCoffee + summary: Delete coffee + description: Delete the coffee identified by the given id, (delete without request body) + tags: + - fake + parameters: + - name: id + in: path + description: The internal object id + required: true + schema: + type: string + responses: + '200': + description: OK + default: + description: Unexpected error + /fake/queryParamWithJsonContentType: + get: + operationId: queryParamWithJsonContentType + summary: query param with json content-type + tags: + - fake + parameters: + - name: someParam + in: query + description: The internal object id + required: true + content: + application/json: + schema: {} + responses: + 200: + description: success + content: + application/json: + schema: {} servers: - url: 'http://{server}.swagger.io:{port}/v2' description: petstore server @@ -1554,13 +1784,12 @@ components: Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - # TODO: this should be supported, currently there are some issues in the code generation. - #anyTypeExceptNullProp: - # description: any type except 'null' - # Here the 'type' attribute is not specified, which means the value can be anything, - # including the null value, string, number, boolean, array or object. - # not: - # type: 'null' + anyTypeExceptNullProp: + description: any type except 'null' + Here the 'type' attribute is not specified, which means the value can be anything, + including the null value, string, number, boolean, array or object. + not: + type: 'null' anyTypePropNullable: description: test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, @@ -1632,6 +1861,7 @@ components: description: Model for testing reserved words properties: return: + description: this is a reserved python keyword type: integer format: int32 xml: @@ -1649,19 +1879,18 @@ components: type: integer format: int32 property: + description: this is a reserved python keyword type: string - 123Number: - type: integer - readOnly: true xml: name: Name 200_response: - description: Model for testing model name starting with number + description: model with an invalid class name for python, starts with a number properties: name: type: integer format: int32 class: + description: this is a reserved python keyword type: string xml: name: Name @@ -1677,8 +1906,6 @@ components: properties: breed: type: string - legs: - $ref: '#/components/schemas/Legs' Cat: allOf: - $ref: '#/components/schemas/Animal' @@ -1686,19 +1913,6 @@ components: properties: declawed: type: boolean - Legs: - type: object - required: - - legs - properties: - legs: - enum: - - '2' - - '4' - default: '4' - x-enum-as-string: true - name: - type: string Address: type: object additionalProperties: @@ -1715,15 +1929,11 @@ components: color: type: string default: red - tail: - type: boolean - default: true - readOnly: true AnimalFarm: type: array items: $ref: '#/components/schemas/Animal' - format_test: + FormatTest: type: object required: - number @@ -1739,6 +1949,9 @@ components: int32: type: integer format: int32 + int32withValidations: + type: integer + format: int32 maximum: 200 minimum: 20 int64: @@ -1750,15 +1963,27 @@ components: type: number multipleOf: 32.5 float: + description: this is a reserved python keyword type: number format: float maximum: 987.6 minimum: 54.3 + float32: + type: number + format: float double: type: number format: double maximum: 123.4 minimum: 67.8 + float64: + type: number + format: double + arrayWithUniqueItems: + type: array + items: + type: number + uniqueItems: true string: type: string pattern: '/[a-z]/i' @@ -1796,6 +2021,8 @@ components: description: A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. type: string pattern: '/^image_\d{1,3}$/i' + noneProp: + type: 'null' EnumClass: type: string default: '-efg' @@ -1803,6 +2030,8 @@ components: - _abc - '-efg' - (xyz) + - COUNT_1M + - COUNT_50M Enum_Test: type: object required: @@ -1832,12 +2061,6 @@ components: enum: - 1.1 - -1.2 - enum_bool: - type: boolean - enum: - - false - boolEnum: - $ref: '#/components/schemas/BooleanEnum' stringEnum: $ref: '#/components/schemas/StringEnum' IntegerEnum: @@ -1848,12 +2071,6 @@ components: $ref: '#/components/schemas/IntegerEnumWithDefaultValue' IntegerEnumOneValue: $ref: '#/components/schemas/IntegerEnumOneValue' - InlineArrayOfStrEnum: - type: array - items: - $ref: '#/components/schemas/StringEnum' - ArrayOfStrEnum: - $ref: '#/components/schemas/ArrayOfEnums' AdditionalPropertiesClass: type: object properties: @@ -1898,11 +2115,6 @@ components: type: object additionalProperties: $ref: '#/components/schemas/Animal' - List: - type: object - properties: - 123-list: - type: string Client: type: object properties: @@ -2032,12 +2244,19 @@ components: multiple lines - "double quote \n with newline" + - null IntegerEnum: type: integer enum: - 0 - 1 - 2 + IntegerEnumBig: + type: integer + enum: + - 10 + - 11 + - 12 StringEnumWithDefaultValue: type: string enum: @@ -2056,29 +2275,51 @@ components: type: integer enum: - 0 + NullableString: + nullable: true + type: string ObjectModelWithRefProps: description: a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations type: object properties: - my_number: + myNumber: $ref: '#/definitions/NumberWithValidations' - my_readonly: - $ref: '#/definitions/Readonly' - my_string: + myString: $ref: '#/definitions/String' - my_boolean: + myBoolean: $ref: '#/definitions/Boolean' NumberWithValidations: type: number minimum: 10 maximum: 20 - Readonly: - type: object - readOnly: true - properties: - name: - type: string - ComposedOneOfNumberWithValidations: + ComposedAnyOfDifferentTypesNoValidations: + anyOf: + - type: object + - type: string + format: date + - type: string + format: date-time + - type: string + format: binary + - type: string + format: byte + - type: string + - type: object + - type: boolean + - type: 'null' + - type: array + items: {} + - type: number + - type: number + format: float + - type: number + format: double + - type: integer + - type: integer + format: int32 + - type: integer + format: int64 + ComposedOneOfDifferentTypes: description: this is a model that allows payloads of type object or number oneOf: - $ref: '#/components/schemas/NumberWithValidations' @@ -2086,6 +2327,16 @@ components: - type: 'null' - type: string format: date + - type: object + minProperties: 4 + maxProperties: 4 + - type: array + maxItems: 4 + minItems: 4 + items: {} + - type: string + format: date-time + pattern: '^2020.*' Number: type: number String: @@ -2112,13 +2363,26 @@ components: sourceURI: description: Test capitalization type: string - _special_model.name_: + ObjectWithDifficultlyNamedProps: + type: object + description: model with properties that have invalid names for python properties: '$special[property.name]': type: integer format: int64 - xml: - name: '$special[model.name]' + 123-list: + type: string + 123Number: + type: integer + readOnly: true + required: + - 123-list + _special_model.name_: + type: object + description: model with an invalid class name for python + properties: + a: + type: string HealthCheckResult: type: object properties: @@ -2165,9 +2429,6 @@ components: items: type: object nullable: true - object_nullable: - type: object - nullable: true object_nullable_prop: type: object nullable: true @@ -2185,21 +2446,9 @@ components: type: object nullable: true additionalProperties: + type: object nullable: true - ComposedSchemaWithPropsAndNoAddProps: - properties: - color: - type: string - allOf: - - $ref: '#/components/schemas/Tag' - # Below additionalProperties is set to false to validate the use - # case when a composed schema has additionalProperties set to false. - # This definition will only allow in object payloads that set color and no other properties because - # additionalProperties are evaluated at the schema level and do not include composed schema - # properties. Only color is defined here, all others are additional - additionalProperties: false fruit: - description: a schema that tests oneOf and includes a schema level property properties: color: type: string @@ -2241,6 +2490,8 @@ components: type: boolean className: type: string + enum: + - whale required: - className zebra: @@ -2254,6 +2505,8 @@ components: - grevys className: type: string + enum: + - zebra required: - className additionalProperties: true @@ -2268,6 +2521,8 @@ components: properties: className: type: string + enum: + - BasquePig required: - className DanishPig: @@ -2275,12 +2530,10 @@ components: properties: className: type: string + enum: + - DanishPig required: - className - GmFruitNoProperties: - anyOf: - - $ref: '#/components/schemas/apple' - - $ref: '#/components/schemas/banana' gmFruit: properties: color: @@ -2289,8 +2542,6 @@ components: - $ref: '#/components/schemas/apple' - $ref: '#/components/schemas/banana' fruitReq: - description: a schema where additionalProperties is on in the composed schema and off in the oneOf object schemas - also, this schem accepts null as a value oneOf: - type: 'null' - $ref: '#/components/schemas/appleReq' @@ -2361,25 +2612,23 @@ components: propertyName: shapeType NullableShape: description: The value may be a shape or the 'null' value. - The 'nullable' attribute was introduced in OAS schema >= 3.0 - and has been deprecated in OAS schema >= 3.1. + For a composed schema to validate a null payload, + one of its chosen oneOf schemas must be type null + or nullable (introduced in OAS schema >= 3.0) oneOf: - $ref: '#/components/schemas/Triangle' - $ref: '#/components/schemas/Quadrilateral' - discriminator: - propertyName: shapeType - nullable: true - ShapeInterface: + - type: "null" + TriangleInterface: properties: shapeType: type: string - required: - - shapeType - TriangleInterface: - properties: + enum: + - 'Triangle' triangleType: type: string required: + - shapeType - triangleType Triangle: oneOf: @@ -2392,21 +2641,41 @@ components: # equivalent to allowing undeclared properties of any type. EquilateralTriangle: allOf: - - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/TriangleInterface' + - type: object + properties: + triangleType: + type: string + enum: + - 'EquilateralTriangle' IsoscelesTriangle: allOf: - - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/TriangleInterface' + - type: object + properties: + triangleType: + type: string + enum: + - 'IsoscelesTriangle' ScaleneTriangle: allOf: - - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/TriangleInterface' + - type: object + properties: + triangleType: + type: string + enum: + - 'ScaleneTriangle' QuadrilateralInterface: properties: + shapeType: + type: string + enum: + - 'Quadrilateral' quadrilateralType: type: string required: + - shapeType - quadrilateralType Quadrilateral: oneOf: @@ -2416,12 +2685,22 @@ components: propertyName: quadrilateralType SimpleQuadrilateral: allOf: - - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/QuadrilateralInterface' + - type: object + properties: + quadrilateralType: + type: string + enum: + - 'SimpleQuadrilateral' ComplexQuadrilateral: allOf: - - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/QuadrilateralInterface' + - type: object + properties: + quadrilateralType: + type: string + enum: + - 'ComplexQuadrilateral' GrandparentAnimal: type: object required: @@ -2461,91 +2740,242 @@ components: type: object ObjectWithValidations: type: object - minProperties: 1 + minProperties: 2 SomeObject: allOf: - $ref: '#/components/schemas/ObjectInterface' - SomeObjectWithSelfAttr: + ArrayWithValidationsInItems: + type: array + maxItems: 2 + items: + type: integer + format: int64 + maximum: 7 + ArrayHoldingAnyType: + type: array + items: + description: any type can be stored here + DateWithValidations: + type: string + format: date + pattern: '^2020.*' + DateTimeWithValidations: + type: string + format: date-time + pattern: '^2020.*' + NoAdditionalProperties: type: object properties: - self: - type: string - InlineAdditionalPropertiesRefPayload: - description: this payload is used for verification that some model_to_dict issues are fixed - type: object - properties: - arrayData: - type: array - nullable: true - items: - type: object - properties: - labels: - type: array - items: - type: string - nullable: true - Mole: - type: object + id: + type: integer + format: int64 + petId: + type: integer + format: int64 required: - - blind - - smell - - hearing + - id + additionalProperties: false + IntegerMax10: + type: integer + format: int64 + maximum: 10 + IntegerMin15: + type: integer + format: int64 + minimum: 15 + StringWithValidation: + type: string + minLength: 7 + Player: + type: object + description: a model that includes a self reference this forces properties and additionalProperties + to be lazy loaded in python models because the Player class has not fully loaded when defining + properties properties: - blind: - type: boolean - readOnly: true - smell: + name: type: string - readOnly: false - touch: - type: boolean - readOnly: true - taste: - type: string - readOnly: false - hearing: - type: boolean - seeingGhosts: - type: boolean + enemyPlayer: + $ref: '#/components/schemas/Player' BooleanEnum: type: boolean enum: - true - FooObject: + ComposedObject: type: object - properties: - prop1: - type: array - items: - type: object - prop2: - type: object - StreamOptions: allOf: - - $ref: "#/components/schemas/EgressThresholdOptions" - - $ref: "#/components/schemas/PublishOptions" - - EgressThresholdOptions: + - {} + ComposedNumber: + type: number + allOf: + - {} + ComposedString: + type: string + allOf: + - {} + ComposedBool: + type: boolean + allOf: + - {} + ComposedArray: + type: array + items: {} + allOf: + - {} + ComposedNone: + type: 'null' + allOf: + - {} + Currency: + type: string + enum: + - eur + - usd + Money: type: object properties: - egressThresholds: - type: object + amount: + type: string + format: number + currency: + $ref: '#/components/schemas/Currency' + required: + - amount + - currency + DecimalPayload: + type: string + format: number + ObjectWithDecimalProperties: + type: object + properties: + length: + $ref: '#/components/schemas/DecimalPayload' + width: + type: string + format: number + cost: + $ref: '#/components/schemas/Money' + ObjectWithInlineCompositionProperty: + type: object + properties: + someProp: + allOf: + - type: string + minLength: 1 + UUIDString: + type: string + format: uuid + minLength: 1 + AnyTypeNotString: + not: + type: string + JSONPatchRequest: + type: array + items: + oneOf: + - $ref: '#/components/schemas/JSONPatchRequestAddReplaceTest' + - $ref: '#/components/schemas/JSONPatchRequestRemove' + - $ref: '#/components/schemas/JSONPatchRequestMoveCopy' + JSONPatchRequestAddReplaceTest: + type: object + additionalProperties: false + required: + - value + - op + - path + properties: + path: + description: A JSON Pointer path. + type: string + value: + description: The value to add, replace or test. + op: + description: The operation to perform. + type: string + enum: + - add + - replace + - test + JSONPatchRequestRemove: + type: object + additionalProperties: false + required: + - op + - path + properties: + path: + description: A JSON Pointer path. + type: string + op: + description: The operation to perform. + type: string + enum: + - remove + JSONPatchRequestMoveCopy: + type: object + additionalProperties: false + required: + - from + - op + - path + properties: + from: + description: A JSON Pointer path. + type: string + path: + description: A JSON Pointer path. + type: string + op: + description: The operation to perform. + type: string + enum: + - move + - copy + AdditionalPropertiesValidator: + type: object + allOf: + - type: object + additionalProperties: true + - type: object additionalProperties: - type: number - minimum: 0 - maximum: 1 - example: 0.9 - - PublishOptions: + minLength: 3 + - type: object + additionalProperties: + maxLength: 5 + AnyTypeAndFormat: type: object properties: - publish: - type : object - properties: - egressUnknownDetections: - type: boolean - example: true - filterZeroDetections: - type: boolean - example: true + uuid: + format: uuid + date: + format: date + date-time: + format: date-time + number: + format: number + binary: + format: binary + int32: + format: int32 + int64: + format: int64 + double: + format: double + float: + format: float + FromSchema: + type: object + properties: + data: + type: string + id: + type: integer + ObjectWithInvalidNamedRefedProperties: + type: object + properties: + from: + $ref: "#/components/schemas/FromSchema" + "!reference": + $ref: "#/components/schemas/ArrayWithValidationsInItems" + required: + - from + - "!reference" \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml index dc669b62e2..55bedd6d47 100644 --- a/modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/r/petstore.yaml @@ -38,9 +38,7 @@ paths: '405': description: Invalid input security: - - petstore_auth: - - 'write:pets' - - 'read:pets' + - http_auth: [] requestBody: $ref: '#/components/requestBodies/Pet' put: @@ -84,7 +82,7 @@ paths: description: Status values that need to be considered for filter required: true style: form - explode: false + explode: true # change to true for testing purpose deprecated: true schema: type: array @@ -150,9 +148,10 @@ paths: $ref: '#/components/schemas/Pet' '400': description: Invalid tag value - security: - - petstore_auth: - - 'read:pets' + # comment out for testing purpose + #security: + # - petstore_auth: + # - 'read:pets' deprecated: true '/pet/{petId}': get: @@ -183,6 +182,97 @@ paths: description: Invalid ID supplied '404': description: Pet not found + security: + - BearerToken: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + #security: + # - petstore_auth: + # - 'write:pets' + # - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet_header_test': + get: + tags: + - pet + summary: Header test + description: Header test + operationId: test_header + x-streaming: true + parameters: + - name: header_test_int + in: header + description: header test int + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found security: - api_key: [] '/pet/{petId}?streaming': @@ -217,65 +307,6 @@ paths: description: Pet not found security: - api_key: [] - post: - tags: - - pet - summary: Updates a pet in the store with form data - description: '' - operationId: updatePetWithForm - parameters: - - name: petId - in: path - description: ID of pet that needs to be updated - required: true - schema: - type: integer - format: int64 - responses: - '405': - description: Invalid input - security: - - petstore_auth: - - 'write:pets' - - 'read:pets' - requestBody: - content: - application/x-www-form-urlencoded: - schema: - type: object - properties: - name: - description: Updated name of the pet - type: string - status: - description: Updated status of the pet - type: string - delete: - tags: - - pet - summary: Deletes a pet - description: '' - operationId: deletePet - parameters: - - name: api_key - in: header - required: false - schema: - type: string - - name: petId - in: path - description: Pet id to delete - required: true - schema: - type: integer - format: int64 - responses: - '400': - description: Invalid pet value - security: - - petstore_auth: - - 'write:pets' - - 'read:pets' '/pet/{petId}/uploadImage': post: tags: @@ -598,6 +629,43 @@ paths: description: User not found security: - api_key: [] + /fake/path_array/{path_array}/testing: + get: + tags: + - fake + summary: test array parameter in path + description: '' + operationId: fake_path_array + parameters: + - name: path_array + in: path + description: dummy path parameter + required: true + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + /fake/regular_expression: + get: + tags: + - fake + summary: test regular expression to ensure no exception + description: '' + operationId: fake_regular-expression + parameters: + - name: reg_exp_test + in: header + description: dummy required parameter + required: true + schema: + type: string + pattern: /^[A-Za-z0-9_]{1,15}$/ + responses: + '200': + description: successful operation /fake/data_file: get: tags: @@ -628,6 +696,58 @@ paths: application/json: schema: $ref: '#/components/schemas/User' + /fake/set_query_parameter: + get: + tags: + - fake + summary: test set query parameter + description: '' + operationId: fake_set_query + parameters: + - name: set_dummy + in: query + description: set query + required: true + schema: + type: array + uniqueItems: true + items: + type: string + - name: array_dummy + in: query + description: array query + required: true + schema: + type: array + uniqueItems: false + items: + type: string + responses: + '200': + description: successful operation + /fake/test_optional_body_parameter: + post: + tags: + - fake + summary: Add a new pet to the store (optional body) + description: '' + operationId: addPetOptional + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - http_auth: [] + requestBody: + $ref: '#/components/requestBodies/OptionalPet' externalDocs: description: Find out more about Swagger url: 'http://swagger.io' @@ -670,7 +790,41 @@ components: type: string description: Pet object that needs to be added to the store required: true + OptionalPet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + multipart/related: # message with binary body part + schema: + type: object + properties: # Request parts + jsonData: + $ref: '#/components/schemas/Pet' + binaryDataN2Information: + type: string + format: binary + encoding: + jsonData: + contentType: application/json + binaryDataN2Information: + contentType: application/vnd.3gpp.ngap + headers: + Content-Id: + schema: + type: string + description: Pet object that needs to be added to the store + required: false securitySchemes: + http_auth: + type : http + scheme : basic + BearerToken: + type : http + scheme : bearer petstore_auth: type: oauth2 flows: @@ -821,6 +975,11 @@ components: description: Describes the result of uploading an image resource type: object properties: + set_test: + uniqueItems: true + type: array + items: + type: string self: type: integer format: int32 @@ -906,3 +1065,59 @@ components: type: integer nested_pig: $ref: '#/components/schemas/Pig' + OneOfPrimitiveTypeTest: + oneOf: + - type: "integer" + - type: "string" + AnyOfPrimitiveTypeTest: + oneOf: + - type: "integer" + - type: "string" + mammal: + oneOf: + - $ref: '#/components/schemas/whale' + - $ref: '#/components/schemas/zebra' + discriminator: + propertyName: className + mapping: + whale: '#/components/schemas/whale' + zebra: '#/components/schemas/zebra' + whale: + type: object + properties: + hasBaleen: + type: boolean + hasTeeth: + type: boolean + className: + type: string + required: + - className + zebra: + type: object + properties: + type: + type: string + enum: + - plains + - mountain + - grevys + className: + type: string + required: + - className + Date: + description: to test the model name `Date` + type: object + properties: + className: + type: string + percent_description: + description: using % in the description + type: string + url_property: + type: string + format: uri + required: + - className + - url_property diff --git a/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml b/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml index 0bcea44a50..34eae5c8ed 100644 --- a/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml @@ -365,7 +365,7 @@ paths: type: string required: true get: - tags: [Repo, Info] + tags: [repo, Info] operationId: GetRepoInfo responses: "200": diff --git a/modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml index a22fbc7896..deaf6dd086 100644 --- a/modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml @@ -599,6 +599,31 @@ paths: description: Invalid username supplied '404': description: User not found + '/tests/fileResponse': + get: + tags: + - testing + summary: Returns an image file + responses: + '200': + description: An image file + content: + image/jpeg: + schema: + type: string + format: binary + '/tests/typeTesting': + get: + tags: + - testing + summary: Route to test the TypeTesting schema + responses: + '200': + description: The TypeTesting response + content: + application/json: + schema: + $ref: '#/components/schemas/TypeTesting' externalDocs: description: Find out more about Swagger url: 'http://swagger.io' @@ -777,3 +802,60 @@ components: uuid: type: string format: uuid + ActionContainer: + required: + - action + type: object + properties: + action: + allOf: + - $ref: '#/components/schemas/Baz' + - nullable: false + Baz: + description: Test handling of empty variants + enum: + - A + - B + - "" + type: string + TypeTesting: + description: Test handling of different field data types + type: object + required: + - int32 + - int64 + - float + - double + - string + - boolean + - uuid + properties: + int32: + type: integer + format: int32 + int64: + type: integer + format: int64 + float: + type: number + format: float + double: + type: number + format: double + string: + type: string + boolean: + type: boolean + uuid: + type: string + format: uuid + Return: + description: Test using keywords + type: object + properties: + match: + type: integer + async: + type: boolean + super: + type: boolean \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/rust/rust-test.yaml b/modules/openapi-generator/src/test/resources/3_0/rust/rust-test.yaml deleted file mode 100644 index 861e84ca8d..0000000000 --- a/modules/openapi-generator/src/test/resources/3_0/rust/rust-test.yaml +++ /dev/null @@ -1,31 +0,0 @@ -openapi: 3.0.1 -info: - title: Rust client test spec - description: Special testing for the Rust client generator - version: 1.0.7 -paths: - /dummy: - get: - summary: A dummy endpoint to make the spec valid. - responses: - '200': - description: Success -components: - schemas: - TypeTesting: - description: Test handling of differing types (see \#3463) - type: object - properties: - integer: - type: integer - long: - type: long - number: - type: number - float: - type: float - double: - type: double - uuid: - type: string - format: uuid diff --git a/modules/openapi-generator/src/test/resources/3_0/scala/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/scala/petstore.yaml new file mode 100644 index 0000000000..7087e8c5d3 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/scala/petstore.yaml @@ -0,0 +1,760 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - api_key: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + EnumTest: + properties: + emails: + items: + type: string + type: array + search: + enum: + - first_name + - last_name + - email + - full_name + type: string + sort_by: + items: + enum: + - first_name + - last_name + - email + type: string + type: array + type: object diff --git a/modules/openapi-generator/src/test/resources/3_0/setParameter.yaml b/modules/openapi-generator/src/test/resources/3_0/setParameter.yaml new file mode 100644 index 0000000000..2fc2dd5dc0 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/setParameter.yaml @@ -0,0 +1,22 @@ +openapi: 3.0.0 +paths: + /examples: + get: + tags: + - Examples + summary: Get a list of transactions + operationId: getFilteredTransactions + parameters: + - $ref: '#/components/parameters/operationsQueryParam' +components: + parameters: + operationsQueryParam: + name: operations + description: Operations list + in: query + required: false + schema: + type: array + items: + type: string + uniqueItems: true \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/typescript-axios/with-separate-models-and-api-inheritance.yaml b/modules/openapi-generator/src/test/resources/3_0/typescript-axios/with-separate-models-and-api-inheritance.yaml new file mode 100644 index 0000000000..d784ef25ba --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/typescript-axios/with-separate-models-and-api-inheritance.yaml @@ -0,0 +1,35 @@ +--- +openapi: 3.0.1 +info: + title: Example + version: '1' +paths: {} +components: + schemas: + BranchDto: + type: object + properties: + name: + type: string + AbstractUserDto: + type: object + properties: + username: + type: string + branch: + "$ref": "#/components/schemas/BranchDto" + type: + type: string + discriminator: + propertyName: type + mapping: + internal-authenticated: "#/components/schemas/InternalAuthenticatedUserDto" + remote-authenticated: "#/components/schemas/RemoteAuthenticatedUserDto" + InternalAuthenticatedUserDto: + type: object + allOf: + - "$ref": "#/components/schemas/AbstractUserDto" + RemoteAuthenticatedUserDto: + type: object + allOf: + - "$ref": "#/components/schemas/AbstractUserDto" diff --git a/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/3_0_3_unit_test_spec.yaml b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/3_0_3_unit_test_spec.yaml index d3ff930a90..053751510f 100644 --- a/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/3_0_3_unit_test_spec.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/3_0_3_unit_test_spec.yaml @@ -1,10 +1,3173 @@ openapi: 3.0.3 +servers: +- url: https://someserver.com/v1 info: title: openapi 3.0.3 sample spec + version: 0.0.1 description: sample spec for testing openapi functionality, built from json schema tests for draft6 - version: 0.0.1 -paths: {} +tags: +- name: operation.requestBody +- name: path.post +- name: contentType_json +- name: response.content.contentType.schema +- name: additionalProperties +- name: allOf +- name: anyOf +- name: default +- name: enum +- name: format +- name: items +- name: maximum +- name: maxItems +- name: maxLength +- name: maxProperties +- name: minimum +- name: minItems +- name: minLength +- name: minProperties +- name: multipleOf +- name: not +- name: oneOf +- name: pattern +- name: properties +- name: $ref +- name: required +- name: type +- name: uniqueItems +paths: + /requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody: + post: + operationId: postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalpropertiesAllowsASchemaWhichShouldValidate' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AdditionalpropertiesAllowsASchemaWhichShouldValidate' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - additionalProperties + /responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes: + post: + operationId: postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalpropertiesAllowsASchemaWhichShouldValidate' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AdditionalpropertiesAllowsASchemaWhichShouldValidate' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - additionalProperties + /requestBody/postAdditionalpropertiesCanExistByItselfRequestBody: + post: + operationId: postAdditionalpropertiesCanExistByItselfRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalpropertiesCanExistByItself' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AdditionalpropertiesCanExistByItself' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - additionalProperties + /responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes: + post: + operationId: postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalpropertiesCanExistByItself' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AdditionalpropertiesCanExistByItself' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - additionalProperties + /requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody: + post: + operationId: postAdditionalpropertiesAreAllowedByDefaultRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalpropertiesAreAllowedByDefault' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AdditionalpropertiesAreAllowedByDefault' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - additionalProperties + /responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes: + post: + operationId: postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalpropertiesAreAllowedByDefault' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AdditionalpropertiesAreAllowedByDefault' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - additionalProperties + /requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody: + post: + operationId: postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalpropertiesShouldNotLookInApplicators' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AdditionalpropertiesShouldNotLookInApplicators' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - additionalProperties + /responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes: + post: + operationId: postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalpropertiesShouldNotLookInApplicators' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AdditionalpropertiesShouldNotLookInApplicators' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - additionalProperties + /requestBody/postAllofRequestBody: + post: + operationId: postAllofRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Allof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Allof' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - allOf + /responseBody/postAllofResponseBodyForContentTypes: + post: + operationId: postAllofResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Allof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Allof' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - allOf + /requestBody/postAllofWithBaseSchemaRequestBody: + post: + operationId: postAllofWithBaseSchemaRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithBaseSchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithBaseSchema' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - allOf + /responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes: + post: + operationId: postAllofWithBaseSchemaResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithBaseSchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithBaseSchema' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - allOf + /requestBody/postAllofSimpleTypesRequestBody: + post: + operationId: postAllofSimpleTypesRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AllofSimpleTypes' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofSimpleTypes' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - allOf + /responseBody/postAllofSimpleTypesResponseBodyForContentTypes: + post: + operationId: postAllofSimpleTypesResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AllofSimpleTypes' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofSimpleTypes' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - allOf + /requestBody/postAllofWithOneEmptySchemaRequestBody: + post: + operationId: postAllofWithOneEmptySchemaRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithOneEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithOneEmptySchema' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - allOf + /responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes: + post: + operationId: postAllofWithOneEmptySchemaResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithOneEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithOneEmptySchema' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - allOf + /requestBody/postAllofWithTwoEmptySchemasRequestBody: + post: + operationId: postAllofWithTwoEmptySchemasRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithTwoEmptySchemas' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithTwoEmptySchemas' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - allOf + /responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes: + post: + operationId: postAllofWithTwoEmptySchemasResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithTwoEmptySchemas' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithTwoEmptySchemas' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - allOf + /requestBody/postAllofWithTheFirstEmptySchemaRequestBody: + post: + operationId: postAllofWithTheFirstEmptySchemaRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithTheFirstEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithTheFirstEmptySchema' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - allOf + /responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes: + post: + operationId: postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithTheFirstEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithTheFirstEmptySchema' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - allOf + /requestBody/postAllofWithTheLastEmptySchemaRequestBody: + post: + operationId: postAllofWithTheLastEmptySchemaRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithTheLastEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithTheLastEmptySchema' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - allOf + /responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes: + post: + operationId: postAllofWithTheLastEmptySchemaResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AllofWithTheLastEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofWithTheLastEmptySchema' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - allOf + /requestBody/postNestedAllofToCheckValidationSemanticsRequestBody: + post: + operationId: postNestedAllofToCheckValidationSemanticsRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NestedAllofToCheckValidationSemantics' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NestedAllofToCheckValidationSemantics' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - allOf + /responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes: + post: + operationId: postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/NestedAllofToCheckValidationSemantics' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NestedAllofToCheckValidationSemantics' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - allOf + /requestBody/postAllofCombinedWithAnyofOneofRequestBody: + post: + operationId: postAllofCombinedWithAnyofOneofRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AllofCombinedWithAnyofOneof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofCombinedWithAnyofOneof' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - allOf + /responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes: + post: + operationId: postAllofCombinedWithAnyofOneofResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AllofCombinedWithAnyofOneof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AllofCombinedWithAnyofOneof' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - allOf + /requestBody/postAnyofRequestBody: + post: + operationId: postAnyofRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Anyof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Anyof' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - anyOf + /responseBody/postAnyofResponseBodyForContentTypes: + post: + operationId: postAnyofResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Anyof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Anyof' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - anyOf + /requestBody/postAnyofWithBaseSchemaRequestBody: + post: + operationId: postAnyofWithBaseSchemaRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AnyofWithBaseSchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AnyofWithBaseSchema' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - anyOf + /responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes: + post: + operationId: postAnyofWithBaseSchemaResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AnyofWithBaseSchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AnyofWithBaseSchema' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - anyOf + /requestBody/postAnyofComplexTypesRequestBody: + post: + operationId: postAnyofComplexTypesRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AnyofComplexTypes' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AnyofComplexTypes' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - anyOf + /responseBody/postAnyofComplexTypesResponseBodyForContentTypes: + post: + operationId: postAnyofComplexTypesResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AnyofComplexTypes' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AnyofComplexTypes' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - anyOf + /requestBody/postAnyofWithOneEmptySchemaRequestBody: + post: + operationId: postAnyofWithOneEmptySchemaRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AnyofWithOneEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AnyofWithOneEmptySchema' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - anyOf + /responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes: + post: + operationId: postAnyofWithOneEmptySchemaResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/AnyofWithOneEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/AnyofWithOneEmptySchema' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - anyOf + /requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody: + post: + operationId: postNestedAnyofToCheckValidationSemanticsRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NestedAnyofToCheckValidationSemantics' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NestedAnyofToCheckValidationSemantics' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - anyOf + /responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes: + post: + operationId: postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/NestedAnyofToCheckValidationSemantics' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NestedAnyofToCheckValidationSemantics' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - anyOf + /requestBody/postInvalidStringValueForDefaultRequestBody: + post: + operationId: postInvalidStringValueForDefaultRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/InvalidStringValueForDefault' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/InvalidStringValueForDefault' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - default + /responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes: + post: + operationId: postInvalidStringValueForDefaultResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/InvalidStringValueForDefault' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/InvalidStringValueForDefault' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - default + /requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody: + post: + operationId: postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - default + /responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes: + post: + operationId: postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - default + /requestBody/postSimpleEnumValidationRequestBody: + post: + operationId: postSimpleEnumValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/SimpleEnumValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/SimpleEnumValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - enum + /responseBody/postSimpleEnumValidationResponseBodyForContentTypes: + post: + operationId: postSimpleEnumValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/SimpleEnumValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/SimpleEnumValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - enum + /requestBody/postEnumsInPropertiesRequestBody: + post: + operationId: postEnumsInPropertiesRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/EnumsInProperties' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumsInProperties' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - enum + /responseBody/postEnumsInPropertiesResponseBodyForContentTypes: + post: + operationId: postEnumsInPropertiesResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/EnumsInProperties' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumsInProperties' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - enum + /requestBody/postEnumWithEscapedCharactersRequestBody: + post: + operationId: postEnumWithEscapedCharactersRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWithEscapedCharacters' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWithEscapedCharacters' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - enum + /responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes: + post: + operationId: postEnumWithEscapedCharactersResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWithEscapedCharacters' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWithEscapedCharacters' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - enum + /requestBody/postEnumWithFalseDoesNotMatch0RequestBody: + post: + operationId: postEnumWithFalseDoesNotMatch0RequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWithFalseDoesNotMatch0' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWithFalseDoesNotMatch0' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - enum + /responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes: + post: + operationId: postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWithFalseDoesNotMatch0' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWithFalseDoesNotMatch0' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - enum + /requestBody/postEnumWithTrueDoesNotMatch1RequestBody: + post: + operationId: postEnumWithTrueDoesNotMatch1RequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWithTrueDoesNotMatch1' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWithTrueDoesNotMatch1' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - enum + /responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes: + post: + operationId: postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWithTrueDoesNotMatch1' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWithTrueDoesNotMatch1' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - enum + /requestBody/postEnumWith0DoesNotMatchFalseRequestBody: + post: + operationId: postEnumWith0DoesNotMatchFalseRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWith0DoesNotMatchFalse' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWith0DoesNotMatchFalse' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - enum + /responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes: + post: + operationId: postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWith0DoesNotMatchFalse' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWith0DoesNotMatchFalse' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - enum + /requestBody/postEnumWith1DoesNotMatchTrueRequestBody: + post: + operationId: postEnumWith1DoesNotMatchTrueRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWith1DoesNotMatchTrue' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWith1DoesNotMatchTrue' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - enum + /responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes: + post: + operationId: postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/EnumWith1DoesNotMatchTrue' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EnumWith1DoesNotMatchTrue' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - enum + /requestBody/postNulCharactersInStringsRequestBody: + post: + operationId: postNulCharactersInStringsRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NulCharactersInStrings' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NulCharactersInStrings' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - enum + /responseBody/postNulCharactersInStringsResponseBodyForContentTypes: + post: + operationId: postNulCharactersInStringsResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/NulCharactersInStrings' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NulCharactersInStrings' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - enum + /requestBody/postEmailFormatRequestBody: + post: + operationId: postEmailFormatRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/EmailFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EmailFormat' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - format + /responseBody/postEmailFormatResponseBodyForContentTypes: + post: + operationId: postEmailFormatResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/EmailFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/EmailFormat' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - format + /requestBody/postIpv4FormatRequestBody: + post: + operationId: postIpv4FormatRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Ipv4Format' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Ipv4Format' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - format + /responseBody/postIpv4FormatResponseBodyForContentTypes: + post: + operationId: postIpv4FormatResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Ipv4Format' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Ipv4Format' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - format + /requestBody/postIpv6FormatRequestBody: + post: + operationId: postIpv6FormatRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Ipv6Format' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Ipv6Format' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - format + /responseBody/postIpv6FormatResponseBodyForContentTypes: + post: + operationId: postIpv6FormatResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Ipv6Format' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Ipv6Format' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - format + /requestBody/postHostnameFormatRequestBody: + post: + operationId: postHostnameFormatRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/HostnameFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/HostnameFormat' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - format + /responseBody/postHostnameFormatResponseBodyForContentTypes: + post: + operationId: postHostnameFormatResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/HostnameFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/HostnameFormat' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - format + /requestBody/postDateTimeFormatRequestBody: + post: + operationId: postDateTimeFormatRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/DateTimeFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/DateTimeFormat' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - format + /responseBody/postDateTimeFormatResponseBodyForContentTypes: + post: + operationId: postDateTimeFormatResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/DateTimeFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/DateTimeFormat' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - format + /requestBody/postJsonPointerFormatRequestBody: + post: + operationId: postJsonPointerFormatRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/JsonPointerFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/JsonPointerFormat' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - format + /responseBody/postJsonPointerFormatResponseBodyForContentTypes: + post: + operationId: postJsonPointerFormatResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/JsonPointerFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/JsonPointerFormat' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - format + /requestBody/postUriFormatRequestBody: + post: + operationId: postUriFormatRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UriFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UriFormat' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - format + /responseBody/postUriFormatResponseBodyForContentTypes: + post: + operationId: postUriFormatResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/UriFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UriFormat' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - format + /requestBody/postUriReferenceFormatRequestBody: + post: + operationId: postUriReferenceFormatRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UriReferenceFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UriReferenceFormat' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - format + /responseBody/postUriReferenceFormatResponseBodyForContentTypes: + post: + operationId: postUriReferenceFormatResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/UriReferenceFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UriReferenceFormat' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - format + /requestBody/postUriTemplateFormatRequestBody: + post: + operationId: postUriTemplateFormatRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UriTemplateFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UriTemplateFormat' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - format + /responseBody/postUriTemplateFormatResponseBodyForContentTypes: + post: + operationId: postUriTemplateFormatResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/UriTemplateFormat' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UriTemplateFormat' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - format + /requestBody/postNestedItemsRequestBody: + post: + operationId: postNestedItemsRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NestedItems' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NestedItems' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - items + /responseBody/postNestedItemsResponseBodyForContentTypes: + post: + operationId: postNestedItemsResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/NestedItems' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NestedItems' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - items + /requestBody/postMaximumValidationRequestBody: + post: + operationId: postMaximumValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MaximumValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaximumValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - maximum + /responseBody/postMaximumValidationResponseBodyForContentTypes: + post: + operationId: postMaximumValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MaximumValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaximumValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - maximum + /requestBody/postMaximumValidationWithUnsignedIntegerRequestBody: + post: + operationId: postMaximumValidationWithUnsignedIntegerRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MaximumValidationWithUnsignedInteger' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaximumValidationWithUnsignedInteger' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - maximum + /responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes: + post: + operationId: postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MaximumValidationWithUnsignedInteger' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaximumValidationWithUnsignedInteger' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - maximum + /requestBody/postMaxitemsValidationRequestBody: + post: + operationId: postMaxitemsValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MaxitemsValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaxitemsValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - maxItems + /responseBody/postMaxitemsValidationResponseBodyForContentTypes: + post: + operationId: postMaxitemsValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MaxitemsValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaxitemsValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - maxItems + /requestBody/postMaxlengthValidationRequestBody: + post: + operationId: postMaxlengthValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MaxlengthValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaxlengthValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - maxLength + /responseBody/postMaxlengthValidationResponseBodyForContentTypes: + post: + operationId: postMaxlengthValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MaxlengthValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaxlengthValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - maxLength + /requestBody/postMaxpropertiesValidationRequestBody: + post: + operationId: postMaxpropertiesValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MaxpropertiesValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaxpropertiesValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - maxProperties + /responseBody/postMaxpropertiesValidationResponseBodyForContentTypes: + post: + operationId: postMaxpropertiesValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MaxpropertiesValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MaxpropertiesValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - maxProperties + /requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody: + post: + operationId: postMaxproperties0MeansTheObjectIsEmptyRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Maxproperties0MeansTheObjectIsEmpty' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Maxproperties0MeansTheObjectIsEmpty' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - maxProperties + /responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes: + post: + operationId: postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Maxproperties0MeansTheObjectIsEmpty' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Maxproperties0MeansTheObjectIsEmpty' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - maxProperties + /requestBody/postMinimumValidationRequestBody: + post: + operationId: postMinimumValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MinimumValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinimumValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - minimum + /responseBody/postMinimumValidationResponseBodyForContentTypes: + post: + operationId: postMinimumValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MinimumValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinimumValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - minimum + /requestBody/postMinimumValidationWithSignedIntegerRequestBody: + post: + operationId: postMinimumValidationWithSignedIntegerRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MinimumValidationWithSignedInteger' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinimumValidationWithSignedInteger' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - minimum + /responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes: + post: + operationId: postMinimumValidationWithSignedIntegerResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MinimumValidationWithSignedInteger' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinimumValidationWithSignedInteger' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - minimum + /requestBody/postMinitemsValidationRequestBody: + post: + operationId: postMinitemsValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MinitemsValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinitemsValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - minItems + /responseBody/postMinitemsValidationResponseBodyForContentTypes: + post: + operationId: postMinitemsValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MinitemsValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinitemsValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - minItems + /requestBody/postMinlengthValidationRequestBody: + post: + operationId: postMinlengthValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MinlengthValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinlengthValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - minLength + /responseBody/postMinlengthValidationResponseBodyForContentTypes: + post: + operationId: postMinlengthValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MinlengthValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinlengthValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - minLength + /requestBody/postMinpropertiesValidationRequestBody: + post: + operationId: postMinpropertiesValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MinpropertiesValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinpropertiesValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - minProperties + /responseBody/postMinpropertiesValidationResponseBodyForContentTypes: + post: + operationId: postMinpropertiesValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/MinpropertiesValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/MinpropertiesValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - minProperties + /requestBody/postByIntRequestBody: + post: + operationId: postByIntRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ByInt' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ByInt' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - multipleOf + /responseBody/postByIntResponseBodyForContentTypes: + post: + operationId: postByIntResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/ByInt' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ByInt' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - multipleOf + /requestBody/postByNumberRequestBody: + post: + operationId: postByNumberRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ByNumber' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ByNumber' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - multipleOf + /responseBody/postByNumberResponseBodyForContentTypes: + post: + operationId: postByNumberResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/ByNumber' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ByNumber' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - multipleOf + /requestBody/postBySmallNumberRequestBody: + post: + operationId: postBySmallNumberRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/BySmallNumber' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/BySmallNumber' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - multipleOf + /responseBody/postBySmallNumberResponseBodyForContentTypes: + post: + operationId: postBySmallNumberResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/BySmallNumber' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/BySmallNumber' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - multipleOf + /requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody: + post: + operationId: postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - multipleOf + /responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes: + post: + operationId: postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - multipleOf + /requestBody/postNotRequestBody: + post: + operationId: postNotRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Not' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Not' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - not + /responseBody/postNotResponseBodyForContentTypes: + post: + operationId: postNotResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Not' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Not' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - not + /requestBody/postNotMoreComplexSchemaRequestBody: + post: + operationId: postNotMoreComplexSchemaRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NotMoreComplexSchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NotMoreComplexSchema' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - not + /responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes: + post: + operationId: postNotMoreComplexSchemaResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/NotMoreComplexSchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NotMoreComplexSchema' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - not + /requestBody/postForbiddenPropertyRequestBody: + post: + operationId: postForbiddenPropertyRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ForbiddenProperty' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ForbiddenProperty' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - not + /responseBody/postForbiddenPropertyResponseBodyForContentTypes: + post: + operationId: postForbiddenPropertyResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/ForbiddenProperty' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ForbiddenProperty' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - not + /requestBody/postOneofRequestBody: + post: + operationId: postOneofRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Oneof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Oneof' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - oneOf + /responseBody/postOneofResponseBodyForContentTypes: + post: + operationId: postOneofResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Oneof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/Oneof' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - oneOf + /requestBody/postOneofWithBaseSchemaRequestBody: + post: + operationId: postOneofWithBaseSchemaRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OneofWithBaseSchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/OneofWithBaseSchema' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - oneOf + /responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes: + post: + operationId: postOneofWithBaseSchemaResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/OneofWithBaseSchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/OneofWithBaseSchema' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - oneOf + /requestBody/postOneofComplexTypesRequestBody: + post: + operationId: postOneofComplexTypesRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OneofComplexTypes' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/OneofComplexTypes' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - oneOf + /responseBody/postOneofComplexTypesResponseBodyForContentTypes: + post: + operationId: postOneofComplexTypesResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/OneofComplexTypes' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/OneofComplexTypes' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - oneOf + /requestBody/postOneofWithEmptySchemaRequestBody: + post: + operationId: postOneofWithEmptySchemaRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OneofWithEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/OneofWithEmptySchema' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - oneOf + /responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes: + post: + operationId: postOneofWithEmptySchemaResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/OneofWithEmptySchema' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/OneofWithEmptySchema' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - oneOf + /requestBody/postOneofWithRequiredRequestBody: + post: + operationId: postOneofWithRequiredRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OneofWithRequired' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/OneofWithRequired' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - oneOf + /responseBody/postOneofWithRequiredResponseBodyForContentTypes: + post: + operationId: postOneofWithRequiredResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/OneofWithRequired' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/OneofWithRequired' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - oneOf + /requestBody/postNestedOneofToCheckValidationSemanticsRequestBody: + post: + operationId: postNestedOneofToCheckValidationSemanticsRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NestedOneofToCheckValidationSemantics' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NestedOneofToCheckValidationSemantics' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - oneOf + /responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes: + post: + operationId: postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/NestedOneofToCheckValidationSemantics' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NestedOneofToCheckValidationSemantics' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - oneOf + /requestBody/postPatternValidationRequestBody: + post: + operationId: postPatternValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PatternValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/PatternValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - pattern + /responseBody/postPatternValidationResponseBodyForContentTypes: + post: + operationId: postPatternValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/PatternValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/PatternValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - pattern + /requestBody/postPatternIsNotAnchoredRequestBody: + post: + operationId: postPatternIsNotAnchoredRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PatternIsNotAnchored' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/PatternIsNotAnchored' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - pattern + /responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes: + post: + operationId: postPatternIsNotAnchoredResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/PatternIsNotAnchored' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/PatternIsNotAnchored' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - pattern + /requestBody/postObjectPropertiesValidationRequestBody: + post: + operationId: postObjectPropertiesValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ObjectPropertiesValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ObjectPropertiesValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - properties + /responseBody/postObjectPropertiesValidationResponseBodyForContentTypes: + post: + operationId: postObjectPropertiesValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/ObjectPropertiesValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ObjectPropertiesValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - properties + /requestBody/postPropertiesWithEscapedCharactersRequestBody: + post: + operationId: postPropertiesWithEscapedCharactersRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PropertiesWithEscapedCharacters' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/PropertiesWithEscapedCharacters' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - properties + /responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes: + post: + operationId: postPropertiesWithEscapedCharactersResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/PropertiesWithEscapedCharacters' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/PropertiesWithEscapedCharacters' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - properties + /requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody: + post: + operationId: postPropertyNamedRefThatIsNotAReferenceRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PropertyNamedRefThatIsNotAReference' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/PropertyNamedRefThatIsNotAReference' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - $ref + /responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes: + post: + operationId: postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/PropertyNamedRefThatIsNotAReference' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/PropertyNamedRefThatIsNotAReference' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - $ref + /requestBody/postRefInAdditionalpropertiesRequestBody: + post: + operationId: postRefInAdditionalpropertiesRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RefInAdditionalproperties' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInAdditionalproperties' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - $ref + /responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes: + post: + operationId: postRefInAdditionalpropertiesResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RefInAdditionalproperties' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInAdditionalproperties' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - $ref + /requestBody/postRefInItemsRequestBody: + post: + operationId: postRefInItemsRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RefInItems' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInItems' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - $ref + /responseBody/postRefInItemsResponseBodyForContentTypes: + post: + operationId: postRefInItemsResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RefInItems' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInItems' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - $ref + /requestBody/postRefInPropertyRequestBody: + post: + operationId: postRefInPropertyRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RefInProperty' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInProperty' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - $ref + /responseBody/postRefInPropertyResponseBodyForContentTypes: + post: + operationId: postRefInPropertyResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RefInProperty' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInProperty' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - $ref + /requestBody/postRefInAllofRequestBody: + post: + operationId: postRefInAllofRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RefInAllof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInAllof' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - $ref + /responseBody/postRefInAllofResponseBodyForContentTypes: + post: + operationId: postRefInAllofResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RefInAllof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInAllof' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - $ref + /requestBody/postRefInOneofRequestBody: + post: + operationId: postRefInOneofRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RefInOneof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInOneof' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - $ref + /responseBody/postRefInOneofResponseBodyForContentTypes: + post: + operationId: postRefInOneofResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RefInOneof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInOneof' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - $ref + /requestBody/postRefInAnyofRequestBody: + post: + operationId: postRefInAnyofRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RefInAnyof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInAnyof' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - $ref + /responseBody/postRefInAnyofResponseBodyForContentTypes: + post: + operationId: postRefInAnyofResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RefInAnyof' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInAnyof' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - $ref + /requestBody/postRefInNotRequestBody: + post: + operationId: postRefInNotRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RefInNot' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInNot' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - $ref + /responseBody/postRefInNotResponseBodyForContentTypes: + post: + operationId: postRefInNotResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RefInNot' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RefInNot' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - $ref + /requestBody/postRequiredValidationRequestBody: + post: + operationId: postRequiredValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RequiredValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RequiredValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - required + /responseBody/postRequiredValidationResponseBodyForContentTypes: + post: + operationId: postRequiredValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RequiredValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RequiredValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - required + /requestBody/postRequiredDefaultValidationRequestBody: + post: + operationId: postRequiredDefaultValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RequiredDefaultValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RequiredDefaultValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - required + /responseBody/postRequiredDefaultValidationResponseBodyForContentTypes: + post: + operationId: postRequiredDefaultValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RequiredDefaultValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RequiredDefaultValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - required + /requestBody/postRequiredWithEmptyArrayRequestBody: + post: + operationId: postRequiredWithEmptyArrayRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RequiredWithEmptyArray' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RequiredWithEmptyArray' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - required + /responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes: + post: + operationId: postRequiredWithEmptyArrayResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RequiredWithEmptyArray' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RequiredWithEmptyArray' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - required + /requestBody/postRequiredWithEscapedCharactersRequestBody: + post: + operationId: postRequiredWithEscapedCharactersRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RequiredWithEscapedCharacters' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RequiredWithEscapedCharacters' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - required + /responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes: + post: + operationId: postRequiredWithEscapedCharactersResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RequiredWithEscapedCharacters' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/RequiredWithEscapedCharacters' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - required + /requestBody/postIntegerTypeMatchesIntegersRequestBody: + post: + operationId: postIntegerTypeMatchesIntegersRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/IntegerTypeMatchesIntegers' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/IntegerTypeMatchesIntegers' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - type + /responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes: + post: + operationId: postIntegerTypeMatchesIntegersResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/IntegerTypeMatchesIntegers' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/IntegerTypeMatchesIntegers' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - type + /requestBody/postNumberTypeMatchesNumbersRequestBody: + post: + operationId: postNumberTypeMatchesNumbersRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NumberTypeMatchesNumbers' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NumberTypeMatchesNumbers' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - type + /responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes: + post: + operationId: postNumberTypeMatchesNumbersResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/NumberTypeMatchesNumbers' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NumberTypeMatchesNumbers' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - type + /requestBody/postStringTypeMatchesStringsRequestBody: + post: + operationId: postStringTypeMatchesStringsRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/StringTypeMatchesStrings' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/StringTypeMatchesStrings' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - type + /responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes: + post: + operationId: postStringTypeMatchesStringsResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/StringTypeMatchesStrings' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/StringTypeMatchesStrings' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - type + /requestBody/postObjectTypeMatchesObjectsRequestBody: + post: + operationId: postObjectTypeMatchesObjectsRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ObjectTypeMatchesObjects' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ObjectTypeMatchesObjects' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - type + /responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes: + post: + operationId: postObjectTypeMatchesObjectsResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/ObjectTypeMatchesObjects' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ObjectTypeMatchesObjects' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - type + /requestBody/postBooleanTypeMatchesBooleansRequestBody: + post: + operationId: postBooleanTypeMatchesBooleansRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/BooleanTypeMatchesBooleans' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/BooleanTypeMatchesBooleans' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - type + /responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes: + post: + operationId: postBooleanTypeMatchesBooleansResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/BooleanTypeMatchesBooleans' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/BooleanTypeMatchesBooleans' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - type + /requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody: + post: + operationId: postNullTypeMatchesOnlyTheNullObjectRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NullTypeMatchesOnlyTheNullObject' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NullTypeMatchesOnlyTheNullObject' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - type + /responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes: + post: + operationId: postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/NullTypeMatchesOnlyTheNullObject' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/NullTypeMatchesOnlyTheNullObject' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - type + /requestBody/postArrayTypeMatchesArraysRequestBody: + post: + operationId: postArrayTypeMatchesArraysRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ArrayTypeMatchesArrays' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ArrayTypeMatchesArrays' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - type + /responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes: + post: + operationId: postArrayTypeMatchesArraysResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/ArrayTypeMatchesArrays' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/ArrayTypeMatchesArrays' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - type + /requestBody/postUniqueitemsValidationRequestBody: + post: + operationId: postUniqueitemsValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UniqueitemsValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UniqueitemsValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - uniqueItems + /responseBody/postUniqueitemsValidationResponseBodyForContentTypes: + post: + operationId: postUniqueitemsValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/UniqueitemsValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UniqueitemsValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - uniqueItems + /requestBody/postUniqueitemsFalseValidationRequestBody: + post: + operationId: postUniqueitemsFalseValidationRequestBody + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UniqueitemsFalseValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UniqueitemsFalseValidation' + required: true + responses: + '200': + description: success + tags: + - operation.requestBody + - path.post + - contentType_json + - uniqueItems + /responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes: + post: + operationId: postUniqueitemsFalseValidationResponseBodyForContentTypes + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/UniqueitemsFalseValidation' + x-schema-test-examples: + $ref: '#/components/x-schema-test-examples/UniqueitemsFalseValidation' + tags: + - response.content.contentType.schema + - path.post + - contentType_json + - uniqueItems components: schemas: AdditionalpropertiesAllowsASchemaWhichShouldValidate: @@ -261,6 +3424,15 @@ components: oneOf: - type: number - {} + OneofWithRequired: + type: object + oneOf: + - required: + - foo + - bar + - required: + - foo + - baz NestedOneofToCheckValidationSemantics: oneOf: - oneOf: @@ -314,6 +3486,9 @@ components: RefInAnyof: anyOf: - $ref: '#/components/schemas/PropertyNamedRefThatIsNotAReference' + RefInNot: + not: + $ref: '#/components/schemas/PropertyNamedRefThatIsNotAReference' RequiredValidation: properties: foo: {} @@ -327,6 +3502,16 @@ components: properties: foo: {} required: [] + RequiredWithEscapedCharacters: + required: + - 'foo + + bar' + - foo"bar + - foo\bar + - "foo\rbar" + - "foo\tbar" + - "foo\fbar" IntegerTypeMatchesIntegers: type: integer NumberTypeMatchesNumbers: @@ -393,6 +3578,12 @@ components: foo: 1 bar: true valid: false + ValidTestCase: + description: valid test case + data: + foo: false + bar: true + valid: true Allof: Allof: description: allOf @@ -1274,6 +4465,10 @@ components: error data: 1.0e+308 valid: false + ValidIntegerWithMultipleofFloat: + description: valid integer with multipleOf float + data: 123456789 + valid: true Not: Allowed: description: allowed @@ -1373,6 +4568,31 @@ components: description: both valid - invalid data: 123 valid: false + OneofWithRequired: + BothInvalidInvalid: + description: both invalid - invalid + data: + bar: 2 + valid: false + FirstValidValid: + description: first valid - valid + data: + foo: 1 + bar: 2 + valid: true + SecondValidValid: + description: second valid - valid + data: + foo: 1 + baz: 3 + valid: true + BothValidInvalid: + description: both valid - invalid + data: + foo: 1 + bar: 2 + baz: 3 + valid: false NestedOneofToCheckValidationSemantics: NullIsValid: description: null is valid @@ -1560,6 +4780,17 @@ components: data: $ref: 2 valid: false + RefInNot: + PropertyNamedRefInvalid: + description: property named $ref invalid + data: + $ref: a + valid: false + PropertyNamedRefValid: + description: property named $ref valid + data: + $ref: 2 + valid: true RequiredValidation: PresentRequiredPropertyIsValid: description: present required property is valid @@ -1593,6 +4824,29 @@ components: description: property not required data: {} valid: true + RequiredWithEscapedCharacters: + ObjectWithAllPropertiesPresentIsValid: + description: object with all properties present is valid + data: + ? 'foo + + bar' + : 1 + foo"bar: 1 + foo\bar: 1 + "foo\rbar": 1 + "foo\tbar": 1 + "foo\fbar": 1 + valid: true + ObjectWithSomePropertiesMissingIsInvalid: + description: object with some properties missing is invalid + data: + ? 'foo + + bar' + : '1' + foo"bar: '1' + valid: false IntegerTypeMatchesIntegers: AnIntegerIsAnInteger: description: an integer is an integer diff --git a/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/openapi_additions/additionalProperties.json b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/openapi_additions/additionalProperties.json new file mode 100755 index 0000000000..e6c2f71701 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/openapi_additions/additionalProperties.json @@ -0,0 +1,18 @@ +[ + { + "description": "additionalProperties should not look in applicators", + "schema": { + "allOf": [ + {"properties": {"foo": {}}} + ], + "additionalProperties": {"type": "boolean"} + }, + "tests": [ + { + "description": "valid test case", + "data": {"foo": false, "bar": true}, + "valid": true + } + ] + } +] diff --git a/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/openapi_additions/multipleOf.json b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/openapi_additions/multipleOf.json new file mode 100755 index 0000000000..0b34974277 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/openapi_additions/multipleOf.json @@ -0,0 +1,13 @@ +[ + { + "description": "invalid instance should not raise error when float division = inf", + "schema": {"type": "integer", "multipleOf": 0.123456789}, + "tests": [ + { + "description": "valid integer with multipleOf float", + "data": 123456789, + "valid": true + } + ] + } +] diff --git a/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/spec_writer.py b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/spec_writer.py index c4843877a1..51c4b0ee0e 100644 --- a/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/spec_writer.py +++ b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/spec_writer.py @@ -100,9 +100,7 @@ class ExclusionReason: swagger_parser_anytype_bug = 'Swagger parser sets type incorrectly for this anyType schema https://github.com/swagger-api/swagger-parser/issues/1603' component_ref_component_bug = 'A component refing another component does not work, issue at https://github.com/OpenAPITools/openapi-generator/issues/12730' not_running_the_localhost_server = 'the openapo-generator is not running the localhost server needed to serve remoteRef files' - required_vars_missing_for_anytype_schema_bug = 'fails because of a bug where required vars are forgotten, see issue https://github.com/OpenAPITools/openapi-generator/issues/8906' v303_requires_that_the_default_value_is_an_allowed_type = 'v3.0.3 requires that the default value is an allowed type per the schema' - not_ref_import_missing = 'this test fails because of this open issue https://github.com/OpenAPITools/openapi-generator/issues/12756' json_schema_test_draft = 'draft6' openapi_additions = 'openapi_additions' @@ -149,7 +147,6 @@ FILEPATH_TO_EXCLUDED_CASE_AND_REASON = { 'oneOf with boolean schemas, one true': ExclusionReason.v303_does_not_support_boolean_schemas_in_location, 'oneOf with boolean schemas, more than one true': ExclusionReason.v303_does_not_support_boolean_schemas_in_location, 'oneOf with boolean schemas, all false': ExclusionReason.v303_does_not_support_boolean_schemas_in_location, - 'oneOf with required': ExclusionReason.required_vars_missing_for_anytype_schema_bug, }, (json_schema_test_draft, 'properties.json'): { 'properties, patternProperties, additionalProperties interaction': ExclusionReason.v303_does_not_support_patternProperties, @@ -181,7 +178,6 @@ FILEPATH_TO_EXCLUDED_CASE_AND_REASON = { 'property refs adjacent property': ExclusionReason.ref_to_adjacent_property_bug, 'property refs containing component schema': ExclusionReason.swagger_parser_anytype_bug, 'component refs another component': ExclusionReason.component_ref_component_bug, - 'ref in not': ExclusionReason.not_ref_import_missing }, (json_schema_test_draft, 'refRemote.json'): { 'base URI change - change folder': ExclusionReason.v303_does_not_support_id, @@ -193,9 +189,6 @@ FILEPATH_TO_EXCLUDED_CASE_AND_REASON = { 'fragment within remote ref': ExclusionReason.not_running_the_localhost_server, 'ref within remote ref': ExclusionReason.not_running_the_localhost_server, }, - (json_schema_test_draft, 'required.json'): { - 'required with escaped characters': ExclusionReason.required_vars_missing_for_anytype_schema_bug, - }, (json_schema_test_draft, 'type.json'): { 'multiple types can be specified in an array': ExclusionReason.v303_does_not_support_array_of_types, 'type as array with one item': ExclusionReason.v303_does_not_support_array_of_types, @@ -227,7 +220,7 @@ FILEPATH_TO_EXCLUDE_REASON = { JSON_SCHEMA_TEST_FILE_TO_FOLDERS = { 'additionalItems.json': (json_schema_test_draft,), - 'additionalProperties.json': (json_schema_test_draft,), + 'additionalProperties.json': (json_schema_test_draft, openapi_additions), 'allOf.json': (json_schema_test_draft,), 'anyOf.json': (json_schema_test_draft,), 'boolean_schema.json': (json_schema_test_draft,), @@ -251,7 +244,7 @@ JSON_SCHEMA_TEST_FILE_TO_FOLDERS = { 'minItems.json': (json_schema_test_draft,), 'minLength.json': (json_schema_test_draft,), 'minProperties.json': (json_schema_test_draft,), - 'multipleOf.json': (json_schema_test_draft,), + 'multipleOf.json': (json_schema_test_draft, openapi_additions), 'not.json': (json_schema_test_draft,), 'oneOf.json': (json_schema_test_draft,), 'pattern.json': (json_schema_test_draft,), @@ -266,6 +259,13 @@ JSON_SCHEMA_TEST_FILE_TO_FOLDERS = { 'unknownKeyword.json': (json_schema_test_draft,), } +file_name_to_tag_name = { + 'ref': '$ref', + 'id': '$id', + 'refRemote': '$ref', + 'unknownKeyword': None +} + def get_json_schema_test_schemas(file_path: typing.Tuple[str]) -> typing.List[JsonSchemaTestSchema]: json_schema_test_schemas = [] filename = file_path[-1] @@ -292,41 +292,93 @@ def get_json_schema_test_schemas(file_path: typing.Tuple[str]) -> typing.List[Js openapi_version = '3.0.3' - -@dataclasses.dataclass -class OpenApiDocumentInfo: - title: str - description: str - version: str - OpenApiSchema = typing.TypedDict( 'OpenApiSchema', { 'type': str, - 'x-test-examples': typing.Dict[str, JsonSchemaTestCase], 'items': 'OpenApiSchema', - 'properties': typing.Dict[str, 'OpenApiSchema'] - } + 'properties': typing.Dict[str, 'OpenApiSchema'], + '$ref': str + }, + total=False ) -@dataclasses.dataclass -class OpenApiExample: - description: str - value: typing.Union[str, int, float, bool, None, list, dict] +JsonSchemaTestCases = typing.Dict[str, JsonSchemaTestCase] OpenApiComponents = typing.TypedDict( 'OpenApiComponents', { - 'schemas': typing.Dict[str, typing.Union[bool, OpenApiSchema]], - 'x-schema-test-examples': typing.Dict[str, typing.Dict[str, JsonSchemaTestCase]] + 'schemas': typing.Dict[str, OpenApiSchema], + 'x-schema-test-examples': typing.Dict[str, JsonSchemaTestCases] } ) +OpenApiMediaType = typing.TypedDict( + 'OpenApiMediaType', + { + 'schema': OpenApiSchema, + 'x-schema-test-examples': JsonSchemaTestCases + }, + total=False +) + +class OpenApiRequestBody(typing.TypedDict, total=False): + description: str + content: typing.Dict[str, OpenApiMediaType] + required: bool + +class OpenApiResponseObject(typing.TypedDict): + description: str + headers: typing.Optional[typing.Dict[str, typing.Any]] = None + content: typing.Optional[typing.Dict[str, OpenApiMediaType]] = None + +class OpenApiOperation(typing.TypedDict, total=False): + tags: typing.List[str] + summary: str + description: str + operationId: str + requestBody: OpenApiRequestBody + responses: typing.Dict[str, OpenApiResponseObject] + +class OpenApiPathItem(typing.TypedDict, total=False): + summary: str + description: str + get: OpenApiOperation + put: OpenApiOperation + post: OpenApiOperation + delete: OpenApiOperation + options: OpenApiOperation + head: OpenApiOperation + patch: OpenApiOperation + trace: OpenApiOperation + +OpenApiPaths = typing.Dict[str, OpenApiPathItem] + + +@dataclasses.dataclass +class OpenApiDocumentInfo: + title: str + version: str + description: typing.Optional[str] = None + + +@dataclasses.dataclass +class OpenApiTag: + name: str + + +@dataclasses.dataclass +class OpenApiServer: + url: str + + @dataclasses.dataclass class OpenApiDocument: openapi: str + servers: typing.List[OpenApiServer] info: OpenApiDocumentInfo - paths: typing.Dict[str, typing.Any] + tags: typing.List[OpenApiTag] + paths: OpenApiPaths components: OpenApiComponents @@ -338,11 +390,13 @@ def get_new_openapi() -> OpenApiDocument: description=f"sample spec for testing openapi functionality, built from json schema tests for {json_schema_test_draft}", version="0.0.1" ), + servers=[OpenApiServer(url='https://someserver.com/v1')], + tags = [], paths={}, components=OpenApiComponents({ 'schemas': {}, 'x-schema-test-examples': {} - }) + }), ) def description_to_component_name(descr: str) -> str: @@ -353,7 +407,10 @@ def get_test_case_name(test: JsonSchemaTestSchema) -> str: res = ''.join(test.description.title().split()) return re.sub(r'[^A-Za-z0-9 ]+', '', res) -def get_component_schemas_and_test_examples(json_schema_test_file: str, folders: typing.Tuple[str]) -> typing.Dict[str, OpenApiSchema]: +def get_component_schemas_and_test_examples( + json_schema_test_file: str, + folders: typing.Tuple[str] +) -> typing.Tuple[typing.Dict[str, OpenApiSchema], typing.Dict[str, typing.Dict[str, JsonSchemaTestSchema]]]: component_schemas = {} component_name_to_test_examples = {} for folder in folders: @@ -374,12 +431,86 @@ def get_component_schemas_and_test_examples(json_schema_test_file: str, folders: component_name_to_test_examples[component_name][test_case_name] = test return component_schemas, component_name_to_test_examples +def generate_post_operation_with_request_body( + component_name: str, + tags: typing.List[OpenApiTag] +) -> OpenApiOperation: + method = 'post' + ref_schema_path = f'#/components/schemas/{component_name}' + ref_test_example_path = f'#/components/x-schema-test-examples/{component_name}' + media_type = OpenApiMediaType( + { + 'schema': OpenApiSchema({'$ref': ref_schema_path}), + 'x-schema-test-examples': {'$ref': ref_test_example_path} + } + ) + request_body = OpenApiRequestBody( + { + 'content': {'application/json': media_type}, + 'required': True + } + ) + operationId = f'{method}{component_name}RequestBody' + response_object = OpenApiResponseObject({'description': 'success'}) + return OpenApiOperation( + { + 'operationId': operationId, + 'requestBody': request_body, + 'responses': {'200': response_object}, + 'tags': [tag.name for tag in tags] + } + ) + + +def generate_post_operation_with_response_content_schema( + component_name: str, + tags: typing.List[OpenApiTag] +) -> OpenApiOperation: + method = 'post' + ref_schema_path = f'#/components/schemas/{component_name}' + ref_test_example_path = f'#/components/x-schema-test-examples/{component_name}' + media_type = OpenApiMediaType( + { + 'schema': OpenApiSchema({'$ref': ref_schema_path}), + 'x-schema-test-examples': {'$ref': ref_test_example_path} + } + ) + operationId = f'{method}{component_name}ResponseBodyForContentTypes' + response_object = OpenApiResponseObject( + { + 'description': 'success', + 'content': {'application/json': media_type} + } + ) + return OpenApiOperation( + { + 'operationId': operationId, + 'responses': {'200': response_object}, + 'tags': [tag.name for tag in tags] + } + ) + + def write_openapi_spec(): openapi = get_new_openapi() + request_body_tag = OpenApiTag(name='operation.requestBody') + post_tag = OpenApiTag(name='path.post') + json_tag = OpenApiTag(name='contentType_json') + response_content_tag = OpenApiTag(name='response.content.contentType.schema') + openapi.tags.extend([request_body_tag, post_tag, json_tag, response_content_tag]) + # write component schemas and tests for json_schema_test_file, folders in JSON_SCHEMA_TEST_FILE_TO_FOLDERS.items(): component_schemas, component_name_to_test_examples = ( get_component_schemas_and_test_examples(json_schema_test_file, folders) ) + if not component_schemas and not component_name_to_test_examples: + continue + json_schema_test_file_name = json_schema_test_file.split('.')[0] + json_schema_tag_name = file_name_to_tag_name.get(json_schema_test_file_name, json_schema_test_file_name) + json_schema_tag = None + if json_schema_tag_name is not None: + json_schema_tag = OpenApiTag(name=json_schema_tag_name) + openapi.tags.append(json_schema_tag) for component_name, schema in component_schemas.items(): if component_name in openapi.components['schemas']: raise ValueError('A component schema with that name is already defined!') @@ -388,6 +519,23 @@ def write_openapi_spec(): if component_name in openapi.components['x-schema-test-examples']: raise ValueError('A component schema test example map with that name is already defined!') openapi.components['x-schema-test-examples'][component_name] = test_examples + + request_body_tag_list = [request_body_tag, post_tag, json_tag] + if json_schema_tag is not None: + request_body_tag_list.append(json_schema_tag) + + operation = generate_post_operation_with_request_body(component_name, request_body_tag_list) + path_item = OpenApiPathItem(post=operation) + openapi.paths[f'/requestBody/{operation["operationId"]}'] = path_item + + # todo add put and patch with paths requestBody/someIdentifier + + response_body_tag_list = [response_content_tag, post_tag, json_tag] + if json_schema_tag is not None: + response_body_tag_list.append(json_schema_tag) + operation = generate_post_operation_with_response_content_schema(component_name, response_body_tag_list) + path_item = OpenApiPathItem(post=operation) + openapi.paths[f'/responseBody/{operation["operationId"]}'] = path_item print( yaml.dump( dataclasses.asdict(openapi), diff --git a/modules/openapi-generator/src/test/resources/3_1/petstore.yaml b/modules/openapi-generator/src/test/resources/3_1/petstore.yaml new file mode 100644 index 0000000000..6e83b7fdc2 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_1/petstore.yaml @@ -0,0 +1,738 @@ +openapi: 3.1.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - api_key: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string diff --git a/modules/openapi-generator/src/test/resources/bugs/issue_12692.yml b/modules/openapi-generator/src/test/resources/bugs/issue_12692.yml new file mode 100644 index 0000000000..607900199d --- /dev/null +++ b/modules/openapi-generator/src/test/resources/bugs/issue_12692.yml @@ -0,0 +1,45 @@ +openapi: 3.0.1 +info: + version: 1.0.0 + title: Swagger Petstore + license: + name: MIT +paths: + "/pets": + get: + operationId: listPets + responses: + '200': + description: description + content: + application/json: + schema: + type: array + items: + "$ref": "#/components/schemas/Pet" +components: + schemas: + Pet: + type: object + required: + - type + properties: + type: + type: string + discriminator: + propertyName: type + mapping: + cat: "#/components/schemas/Cat" + Cat: + allOf: + - "$ref": "#/components/schemas/Pet" + - type: object + required: + - type + properties: + type: + type: string + discriminator: + propertyName: type + mapping: + cat: "#/components/schemas/Cat" diff --git a/modules/openapi-generator/src/test/resources/bugs/issue_13365.yml b/modules/openapi-generator/src/test/resources/bugs/issue_13365.yml new file mode 100644 index 0000000000..020e1d8c99 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/bugs/issue_13365.yml @@ -0,0 +1,40 @@ +openapi: 3.0.0 +info: + description: Specification to reproduce nullable issue with Array + title: Required Api +paths: + '/person': + post: + summary: Inserts a person + operationId: postPerson + tags: + - person + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Person' + + responses: ... + +components: + schemas: + Person: + type: object + required: + - name + properties: + name: + type: string + maxLength: 50 + format: email + id: + type: integer + Alien: + type: object + properties: + name: + type: string + id: + type: integer \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/bugs/issue_13385.yml b/modules/openapi-generator/src/test/resources/bugs/issue_13385.yml new file mode 100644 index 0000000000..2940b410aa --- /dev/null +++ b/modules/openapi-generator/src/test/resources/bugs/issue_13385.yml @@ -0,0 +1,23 @@ +openapi: 3.0.3 +info: + version: 1.0.0 + description: Specification to reproduce nullable issue with Array + title: ArrayNullableTest Api +paths: + /arrayNullable: + get: + summary: dummy + operationId: dummy + responses: + '200': + description: OK + +components: + schemas: + TestObject: + type: object + properties: + picture: + type: string + format: byte + nullable: true \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/bugs/issue_13385_2.yml b/modules/openapi-generator/src/test/resources/bugs/issue_13385_2.yml new file mode 100644 index 0000000000..25b8bbc812 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/bugs/issue_13385_2.yml @@ -0,0 +1,23 @@ +openapi: 3.0.3 +info: + version: 1.0.0 + description: Specification to reproduce nullable issue with Array + title: ArrayNullableTest Api +paths: + /arrayNullable: + get: + summary: dummy + operationId: dummy + responses: + '200': + description: OK + +components: + schemas: + TestObject: + type: object + properties: + picture: + type: string + format: byte + nullable: false \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/bugs/issue_7125.json b/modules/openapi-generator/src/test/resources/bugs/issue_7125.json new file mode 100644 index 0000000000..4e04ee48d2 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/bugs/issue_7125.json @@ -0,0 +1,91 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "title", + "description": "description", + "version": "1.0.0", + "contact": { + "name": "name", + "url": "url", + "email": "email.com" + } + }, + "paths": { + "/someUrl/v1/smth": { + "post": { + "tags": [ + "someMethod" + ], + "summary": "summary", + "description": "description", + "operationId": "methodWithValidation", + "parameters": [ + { + "$ref": "#/components/parameters/HeaderOne" + }, + { + "$ref": "#/components/parameters/HeaderTwo" + } + ], + "requestBody": { + "description": "Request Body", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SomeBody" + } + } + }, + "required": true + }, + "responses": { + "202": { + "description": "success" + } + } + } + } + }, + "components": { + "schemas": { + "SomeBody": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "example": "123", + "description": "description" + } + } + } + }, + "parameters": { + "HeaderOne": { + "name": "HeaderOne", + "in": "header", + "description": "description", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 10, + "pattern": "\\d+" + } + }, + "HeaderTwo": { + "name": "HeaderTwo", + "in": "header", + "description": "description", + "required": true, + "schema": { + "type": "integer", + "minimum": 500, + "maximum": 10000 + } + } + } + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/.gitignore b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/.gitignore index 35e2fb2b02..149b576547 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/.gitignore +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/.gitignore @@ -1,3 +1,4 @@ wwwroot/*.js node_modules typings +dist diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/.openapi-generator-ignore b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/.openapi-generator-ignore deleted file mode 100644 index deed424f8a..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/.openapi-generator-ignore +++ /dev/null @@ -1,23 +0,0 @@ -# Swagger Codegen Ignore -# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen - -# 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 Swagger Codegen 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/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/LICENSE b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/LICENSE deleted file mode 100644 index 3f4d322ebd..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/README.md b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/README.md index 3ae010d2a4..d46ff5c06b 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/README.md +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/README.md @@ -2,7 +2,7 @@ ### Building -To build and compile the typescript sources to javascript use: +To install the required dependencies and to build the typescript sources run: ``` npm install npm run build @@ -10,11 +10,11 @@ npm run build ### publishing -First build the package than run ```npm publish``` +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) ### consuming -navigate to the folder of your consuming project and run one of next commando's. +Navigate to the folder of your consuming project and run one of next commands. _published:_ @@ -22,23 +22,205 @@ _published:_ npm install additionalPropertiesTest@1.0.2 --save ``` -_unPublished (not recommended):_ +_without publishing (not recommended):_ ``` -npm install PATH_TO_GENERATED_PACKAGE --save +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save ``` -In your angular2 project: +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link additionalPropertiesTest +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from 'additionalPropertiesTest'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from 'additionalPropertiesTest'; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from 'additionalPropertiesTest'; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from 'additionalPropertiesTest'; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` -TODO: paste example. ### Set service base path -If different than the generated base path, during app bootstrap, you can provide the base path to your service. +If different than the generated base path, during app bootstrap, you can provide the base path to your service. ``` -import { BASE_PATH } from './path-to-swagger-gen-service/index'; +import { BASE_PATH } from 'additionalPropertiesTest'; bootstrap(AppComponent, [ { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, ]); -``` +``` +or + +``` +import { BASE_PATH } from 'additionalPropertiesTest'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from 'additionalPropertiesTest'; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api.module.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api.module.ts index bb9f292627..31f437b388 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api.module.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api.module.ts @@ -1,21 +1,31 @@ -import { NgModule, ModuleWithProviders } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { HttpModule } from '@angular/http'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; import { UserService } from './api/user.service'; @NgModule({ - imports: [ CommonModule, HttpModule ], + imports: [], declarations: [], exports: [], - providers: [ UserService ] + providers: [] }) export class ApiModule { - public static forConfig(configuration: Configuration): ModuleWithProviders { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, - providers: [ {provide: Configuration, useValue: configuration}] + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); } } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api/api.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api/api.ts index e17ee5c7ac..e5e59a3e18 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api/api.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api/api.ts @@ -1 +1,3 @@ export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [UserService]; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api/user.service.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api/user.service.ts index 1ff0ea1ffc..f8e573e7c7 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api/user.service.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/api/user.service.ts @@ -1,166 +1,222 @@ /** - * Swagger Additional Properties + * OpenAPI Additional Properties * This is a test spec * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -import { Inject, Injectable, Optional } from '@angular/core'; -import { Http, Headers, URLSearchParams } from '@angular/http'; -import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; -import { Response, ResponseContentType } from '@angular/http'; - -import { Observable } from 'rxjs/Observable'; -import '../rxjs-operators'; - -import { User } from '../model/user'; - -import { BASE_PATH } from '../variables'; -import { Configuration } from '../configuration'; - /* tslint:disable:no-unused-variable member-ordering */ +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; -@Injectable() +// @ts-ignore +import { User } from '../model/user'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) export class UserService { - protected basePath = 'http://additional-properties.swagger.io/v2'; - public defaultHeaders: Headers = new Headers(); - public configuration: Configuration = new Configuration(); - constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { - if (basePath) { - this.basePath = basePath; - } + protected basePath = 'http://additional-properties.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; - this.basePath = basePath || configuration.basePath || this.basePath; } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; } /** * Add a new User to the store - * * @param body User object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public addUser(body?: User, extraHttpRequestParams?: any): Observable<{}> { - return this.addUserWithHttpInfo(body, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); + public addUser(body?: { [key: string]: string; }, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public addUser(body?: { [key: string]: string; }, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addUser(body?: { [key: string]: string; }, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addUser(body?: { [key: string]: string; }, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: body, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Update an existing User - * * @param body User object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public updateUser(body?: User, extraHttpRequestParams?: any): Observable<{}> { - return this.updateUserWithHttpInfo(body, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } + public updateUser(body?: { [key: string]: string; }, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updateUser(body?: { [key: string]: string; }, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(body?: { [key: string]: string; }, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(body?: { [key: string]: string; }, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + let localVarHeaders = this.defaultHeaders; - /** - * Add a new User to the store - * - * @param body User object that needs to be added to the store - */ - public addUserWithHttpInfo(body?: User, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user`; + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/json' ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } - // to determine the Accept header - let produces: string[] = [ - 'application/json' - ]; - - + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - headers.set('Content-Type', 'application/json'); - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Post, - headers: headers, - body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json - }); - - return this.http.request(path, requestOptions); - } - - /** - * Update an existing User - * - * @param body User object that needs to be added to the store - */ - public updateUserWithHttpInfo(body?: User, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - - // to determine the Content-Type header - let consumes: string[] = [ - 'application/json' - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/json' - ]; - - - - headers.set('Content-Type', 'application/json'); - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Put, - headers: headers, - body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json - }); - - return this.http.request(path, requestOptions); + let localVarPath = `/user`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: body, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/configuration.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/configuration.ts index ec087d2b0c..d38a4c153f 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/configuration.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/configuration.ts @@ -1,24 +1,166 @@ +import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; + export interface ConfigurationParameters { - apiKey?: string; - username?: string; - password?: string; - accessToken?: string; - basePath?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; } export class Configuration { - apiKey: string; - username: string; - password: string; - accessToken: string; - basePath: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + } - constructor(configurationParameters: ConfigurationParameters = {}) { - this.apiKey = configurationParameters.apiKey; - this.username = configurationParameters.username; - this.password = configurationParameters.password; - this.accessToken = configurationParameters.accessToken; - this.basePath = configurationParameters.basePath; - } + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/encoder.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/encoder.ts new file mode 100644 index 0000000000..138c4d5cf2 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/git_push.sh b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/git_push.sh index 484e8cc003..67b52e22d7 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/git_push.sh +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/git_push.sh @@ -1,11 +1,17 @@ #!/bin/sh # ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ # -# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" git_user_id=$1 git_repo_id=$2 release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi if [ "$git_user_id" = "" ]; then git_user_id="" @@ -28,7 +34,7 @@ git init # Adds the files in the local repository and stages them for commit. git add . -# Commits the tracked changes and prepares them to be pushed to a remote repository. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote @@ -37,9 +43,9 @@ if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@github.com/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git fi fi @@ -47,6 +53,5 @@ fi git pull origin master # Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" git push origin master 2>&1 | grep -v 'To https' - diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/index.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/index.ts index c312b70fa3..104dd3d21e 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/index.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/model/user.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/model/user.ts index 6a023abeea..a62b83bbe7 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/model/user.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/model/user.ts @@ -1,37 +1,24 @@ /** - * Swagger Additional Properties + * OpenAPI Additional Properties * This is a test spec * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ +export interface User { + [key: string]: string | any; -export interface User { - [key: string]: string | any; id?: number; - /** * User Status */ userStatus?: number; - } + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/ng-package.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/ng-package.json new file mode 100644 index 0000000000..3b17900dc9 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/ng-package.json @@ -0,0 +1,6 @@ +{ + "$schema": "./node_modules/ng-packagr/ng-package.schema.json", + "lib": { + "entryFile": "index.ts" + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/package.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/package.json index 54e4c8a12a..31e050fb00 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/package.json +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/package.json @@ -1,38 +1,34 @@ { "name": "additionalPropertiesTest", "version": "1.0.2", - "description": "swagger client for additionalPropertiesTest", - "author": "Swagger Codegen Contributors", + "description": "OpenAPI client for additionalPropertiesTest", + "author": "OpenAPI-Generator Contributors", + "repository": { + "type": "git", + "url": "https:////.git" + }, "keywords": [ - "swagger-client" + "openapi-client", + "openapi-generator" ], - "license": "Apache-2.0", - "main": "dist/index.js", - "typings": "dist/index.d.ts", + "license": "Unlicense", "scripts": { - "build": "typings install && tsc --outDir dist/" + "build": "ng-packagr -p ng-package.json" }, "peerDependencies": { - "@angular/core": "^2.0.0", - "@angular/http": "^2.0.0", - "@angular/common": "^2.0.0", - "@angular/compiler": "^2.0.0", - "core-js": "^2.4.0", - "reflect-metadata": "^0.1.3", - "rxjs": "5.0.0-beta.12", - "zone.js": "^0.6.17" + "@angular/core": "^14.0.5", + "rxjs": "^7.5.5" }, "devDependencies": { - "@angular/core": "^2.0.0", - "@angular/http": "^2.0.0", - "@angular/common": "^2.0.0", - "@angular/compiler": "^2.0.0", - "@angular/platform-browser": "^2.0.0", - "core-js": "^2.4.0", + "@angular/common": "^14.0.5", + "@angular/compiler": "^14.0.5", + "@angular/compiler-cli": "^14.0.5", + "@angular/core": "^14.0.5", + "@angular/platform-browser": "^14.0.5", + "ng-packagr": "^14.0.2", "reflect-metadata": "^0.1.3", - "rxjs": "5.0.0-beta.12", - "zone.js": "^0.6.17", - "typescript": "^4.0", - "typings": "^1.3.2" - } -} + "rxjs": "^7.5.5", + "tsickle": "^0.46.3", + "typescript": ">=4.6.0 <=4.8.0", + "zone.js": "^0.11.5" + }} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/param.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/rxjs-operators.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/rxjs-operators.ts deleted file mode 100644 index 5659cd0694..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/rxjs-operators.ts +++ /dev/null @@ -1,11 +0,0 @@ -// RxJS imports according to https://angular.io/docs/ts/latest/guide/server-communication.html#!#rxjs - -// See node_module/rxjs/Rxjs.js -// Import just the rxjs statics and operators we need for THIS app. - -// Statics -import 'rxjs/add/observable/throw'; - -// Operators -import 'rxjs/add/operator/catch'; -import 'rxjs/add/operator/map'; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/tsconfig.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/tsconfig.json index e1f949692b..c01ebe255d 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/tsconfig.json +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/tsconfig.json @@ -1,28 +1,28 @@ { - "compilerOptions": { - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "noImplicitAny": false, - "suppressImplicitAnyIndexErrors": true, - "target": "es5", - "module": "commonjs", - "moduleResolution": "node", - "removeComments": true, - "sourceMap": true, - "outDir": "./lib", - "noLib": false, - "declaration": true - }, - "exclude": [ - "node_modules", - "typings/main.d.ts", - "typings/main", - "lib", - "dist" - ], - "filesGlob": [ - "./model/*.ts", - "./api/*.ts", - "typings/browser.d.ts" - ] + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es5", + "module": "commonjs", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/typings.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/typings.json deleted file mode 100644 index 507c40e5cb..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/typings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "globalDependencies": { - "core-js": "registry:dt/core-js#0.0.0+20160725163759" - } -} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/variables.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/variables.ts index 27b987e9b2..6fe58549f3 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/variables.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/additional-properties-expected/variables.ts @@ -1,3 +1,9 @@ -import { OpaqueToken } from '@angular/core'; +import { InjectionToken } from '@angular/core'; -export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/.gitignore b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/.gitignore index 35e2fb2b02..149b576547 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/.gitignore +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/.gitignore @@ -1,3 +1,4 @@ wwwroot/*.js node_modules typings +dist diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/.openapi-generator-ignore b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/.openapi-generator-ignore deleted file mode 100644 index deed424f8a..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/.openapi-generator-ignore +++ /dev/null @@ -1,23 +0,0 @@ -# Swagger Codegen Ignore -# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen - -# 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 Swagger Codegen 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/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/LICENSE b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/LICENSE deleted file mode 100644 index 3f4d322ebd..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/README.md b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/README.md index 0dead26a31..9d5891ab4e 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/README.md +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/README.md @@ -2,7 +2,7 @@ ### Building -To build and compile the typescript sources to javascript use: +To install the required dependencies and to build the typescript sources run: ``` npm install npm run build @@ -10,11 +10,11 @@ npm run build ### publishing -First build the package than run ```npm publish``` +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) ### consuming -navigate to the folder of your consuming project and run one of next commando's. +Navigate to the folder of your consuming project and run one of next commands. _published:_ @@ -22,23 +22,205 @@ _published:_ npm install arrayAndAnyTest@1.0.2 --save ``` -_unPublished (not recommended):_ +_without publishing (not recommended):_ ``` -npm install PATH_TO_GENERATED_PACKAGE --save +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save ``` -In your angular2 project: +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link arrayAndAnyTest +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from 'arrayAndAnyTest'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from 'arrayAndAnyTest'; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from 'arrayAndAnyTest'; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from 'arrayAndAnyTest'; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` -TODO: paste example. ### Set service base path -If different than the generated base path, during app bootstrap, you can provide the base path to your service. +If different than the generated base path, during app bootstrap, you can provide the base path to your service. ``` -import { BASE_PATH } from './path-to-swagger-gen-service/index'; +import { BASE_PATH } from 'arrayAndAnyTest'; bootstrap(AppComponent, [ { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, ]); -``` +``` +or + +``` +import { BASE_PATH } from 'arrayAndAnyTest'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from 'arrayAndAnyTest'; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api.module.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api.module.ts index ec2e7e350a..2db45acb24 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api.module.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api.module.ts @@ -1,21 +1,31 @@ -import { NgModule, ModuleWithProviders } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { HttpModule } from '@angular/http'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; import { ProjectService } from './api/project.service'; @NgModule({ - imports: [ CommonModule, HttpModule ], + imports: [], declarations: [], exports: [], - providers: [ ProjectService ] + providers: [] }) export class ApiModule { - public static forConfig(configuration: Configuration): ModuleWithProviders { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, - providers: [ {provide: Configuration, useValue: configuration}] + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); } } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api/api.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api/api.ts index 82e8c1350d..1ec7e5747e 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api/api.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api/api.ts @@ -1 +1,3 @@ export * from './project.service'; +import { ProjectService } from './project.service'; +export const APIS = [ProjectService]; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api/project.service.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api/project.service.ts index 2a879789ec..960db464de 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api/project.service.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/api/project.service.ts @@ -1,58 +1,109 @@ /** * Cupix API - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * - * OpenAPI spec version: 1.7.0 + * The version of the OpenAPI document: 1.7.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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -import { Inject, Injectable, Optional } from '@angular/core'; -import { Http, Headers, URLSearchParams } from '@angular/http'; -import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; -import { Response, ResponseContentType } from '@angular/http'; - -import { Observable } from 'rxjs/Observable'; -import '../rxjs-operators'; - -import { ProjectEntity } from '../model/projectEntity'; -import { ProjectList } from '../model/projectList'; - -import { BASE_PATH } from '../variables'; -import { Configuration } from '../configuration'; - /* tslint:disable:no-unused-variable member-ordering */ +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; -@Injectable() +// @ts-ignore +import { ProjectEntity } from '../model/projectEntity'; +// @ts-ignore +import { ProjectList } from '../model/projectList'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) export class ProjectService { - protected basePath = 'https://localhost/v1'; - public defaultHeaders: Headers = new Headers(); - public configuration: Configuration = new Configuration(); - constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { - if (basePath) { - this.basePath = basePath; - } + protected basePath = '/v1'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; - this.basePath = basePath || configuration.basePath || this.basePath; } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; } /** @@ -63,233 +114,206 @@ export class ProjectService { * @param longitude * @param latitude * @param meta + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, extraHttpRequestParams?: any): Observable { - return this.createProjectWithHttpInfo(name, address, longitude, latitude, meta, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } + public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public createProject(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { - /** - * Delete a Project - * Returns a Project JSON object - * @param id Project id - */ - public deleteProjectById(id: number, extraHttpRequestParams?: any): Observable<{}> { - return this.deleteProjectByIdWithHttpInfo(id, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Get a Project - * Returns a Project JSON object - * @param id Project id - */ - public getProjectById(id: number, extraHttpRequestParams?: any): Observable { - return this.getProjectByIdWithHttpInfo(id, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Get project list - * Returns a Project JSON object - * @param page - * @param perPage - * @param kind - * @param q - * @param filter - * @param latitude Valid with kind as location - * @param longitude Valid with kind as location - * @param scope Valid with kind as location, and between 1~9 - */ - public getProjectList(page?: number, perPage?: number, kind?: string, q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, extraHttpRequestParams?: any): Observable { - return this.getProjectListWithHttpInfo(page, perPage, kind, q, filter, latitude, longitude, scope, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Update project - * - * @param id Project id - * @param name User ID - * @param address Address - * @param longitude - * @param latitude - * @param meta - * @param thumbnail Project thumbnail - */ - public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: any, extraHttpRequestParams?: any): Observable { - return this.updateProjectWithHttpInfo(id, name, address, longitude, latitude, meta, thumbnail, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - - /** - * Create a Project - * Creates an empty Project - * @param name - * @param address - * @param longitude - * @param latitude - * @param meta - */ - public createProjectWithHttpInfo(name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/projects`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - let formParams = new URLSearchParams(); + let localVarHeaders = this.defaultHeaders; + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/x-www-form-urlencoded' ]; - // to determine the Accept header - let produces: string[] = [ - 'application/json' - ]; - - - headers.set('Content-Type', 'application/x-www-form-urlencoded'); + const canConsumeForm = this.canConsumeForm(consumes); + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } if (name !== undefined) { - formParams.set('name', name); + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; } if (address !== undefined) { - formParams.set('address', address); + localVarFormParams = localVarFormParams.append('address', address) as any || localVarFormParams; } if (longitude !== undefined) { - formParams.set('longitude', longitude); + localVarFormParams = localVarFormParams.append('longitude', longitude) as any || localVarFormParams; } if (latitude !== undefined) { - formParams.set('latitude', latitude); + localVarFormParams = localVarFormParams.append('latitude', latitude) as any || localVarFormParams; } if (meta !== undefined) { - formParams.set('meta', meta); + localVarFormParams = localVarFormParams.append('meta', meta) as any || localVarFormParams; } - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Post, - headers: headers, - body: formParams.toString(), - search: queryParameters, - responseType: ResponseContentType.Json - }); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - return this.http.request(path, requestOptions); + let localVarPath = `/projects`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Delete a Project * Returns a Project JSON object * @param id Project id + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public deleteProjectByIdWithHttpInfo(id: number, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/projects/${id}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'id' is not null or undefined + public deleteProjectById(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public deleteProjectById(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public deleteProjectById(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public deleteProjectById(id: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling deleteProjectById.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - 'application/json' - ]; + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - // to determine the Accept header - let produces: string[] = [ - 'application/json' - ]; - - + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Delete, - headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json - }); - - return this.http.request(path, requestOptions); + let localVarPath = `/projects/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int32"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Get a Project * Returns a Project JSON object * @param id Project id + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public getProjectByIdWithHttpInfo(id: number, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/projects/${id}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'id' is not null or undefined + public getProjectById(id: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public getProjectById(id: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getProjectById(id: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getProjectById(id: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling getProjectById.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - 'application/json' - ]; + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } - // to determine the Accept header - let produces: string[] = [ - 'application/json' - ]; - - + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json - }); - - return this.http.request(path, requestOptions); + let localVarPath = `/projects/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int32"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** @@ -303,65 +327,95 @@ export class ProjectService { * @param latitude Valid with kind as location * @param longitude Valid with kind as location * @param scope Valid with kind as location, and between 1~9 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public getProjectListWithHttpInfo(page?: number, perPage?: number, kind?: string, q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/projects`; + public getProjectList(page?: number, perPage?: number, kind?: 'my_models' | 'published' | 'location', q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public getProjectList(page?: number, perPage?: number, kind?: 'my_models' | 'published' | 'location', q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getProjectList(page?: number, perPage?: number, kind?: 'my_models' | 'published' | 'location', q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getProjectList(page?: number, perPage?: number, kind?: 'my_models' | 'published' | 'location', q?: string, filter?: string, latitude?: number, longitude?: number, scope?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - if (page !== undefined) { - queryParameters.set('page', page); + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (page !== undefined && page !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + page, 'page'); } - if (perPage !== undefined) { - queryParameters.set('per_page', perPage); + if (perPage !== undefined && perPage !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + perPage, 'per_page'); } - if (kind !== undefined) { - queryParameters.set('kind', kind); + if (kind !== undefined && kind !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + kind, 'kind'); } - if (q !== undefined) { - queryParameters.set('q', q); + if (q !== undefined && q !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + q, 'q'); } - if (filter !== undefined) { - queryParameters.set('filter', filter); + if (filter !== undefined && filter !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + filter, 'filter'); } - if (latitude !== undefined) { - queryParameters.set('latitude', latitude); + if (latitude !== undefined && latitude !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + latitude, 'latitude'); } - if (longitude !== undefined) { - queryParameters.set('longitude', longitude); + if (longitude !== undefined && longitude !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + longitude, 'longitude'); } - if (scope !== undefined) { - queryParameters.set('scope', scope); + if (scope !== undefined && scope !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + scope, 'scope'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); } - // to determine the Content-Type header - let consumes: string[] = [ - 'application/json' - ]; + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - // to determine the Accept header - let produces: string[] = [ - 'application/json' - ]; - - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json - }); - - return this.http.request(path, requestOptions); + let localVarPath = `/projects`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Update project - * * @param id Project id * @param name User ID * @param address Address @@ -369,62 +423,97 @@ export class ProjectService { * @param latitude * @param meta * @param thumbnail Project thumbnail + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public updateProjectWithHttpInfo(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: any, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/projects/${id}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - let formParams = new URLSearchParams(); - - // verify required parameter 'id' is not null or undefined + public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public updateProject(id: number, name?: string, address?: string, longitude?: number, latitude?: number, meta?: string, thumbnail?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling updateProject.'); } + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'multipart/form-data' ]; - // to determine the Accept header - let produces: string[] = [ - 'application/json' - ]; - - - headers.set('Content-Type', 'application/x-www-form-urlencoded'); + const canConsumeForm = this.canConsumeForm(consumes); + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } if (name !== undefined) { - formParams.set('name', name); + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; } if (address !== undefined) { - formParams.set('address', address); + localVarFormParams = localVarFormParams.append('address', address) as any || localVarFormParams; } if (longitude !== undefined) { - formParams.set('longitude', longitude); + localVarFormParams = localVarFormParams.append('longitude', longitude) as any || localVarFormParams; } if (latitude !== undefined) { - formParams.set('latitude', latitude); + localVarFormParams = localVarFormParams.append('latitude', latitude) as any || localVarFormParams; } if (meta !== undefined) { - formParams.set('meta', meta); + localVarFormParams = localVarFormParams.append('meta', meta) as any || localVarFormParams; } if (thumbnail !== undefined) { - formParams.set('thumbnail', thumbnail); + localVarFormParams = localVarFormParams.append('thumbnail', thumbnail) as any || localVarFormParams; } - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Put, - headers: headers, - body: formParams.toString(), - search: queryParameters, - responseType: ResponseContentType.Json - }); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } - return this.http.request(path, requestOptions); + let localVarPath = `/projects/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int32"})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/configuration.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/configuration.ts index ec087d2b0c..d38a4c153f 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/configuration.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/configuration.ts @@ -1,24 +1,166 @@ +import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; + export interface ConfigurationParameters { - apiKey?: string; - username?: string; - password?: string; - accessToken?: string; - basePath?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; } export class Configuration { - apiKey: string; - username: string; - password: string; - accessToken: string; - basePath: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + } - constructor(configurationParameters: ConfigurationParameters = {}) { - this.apiKey = configurationParameters.apiKey; - this.username = configurationParameters.username; - this.password = configurationParameters.password; - this.accessToken = configurationParameters.accessToken; - this.basePath = configurationParameters.basePath; - } + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/encoder.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/encoder.ts new file mode 100644 index 0000000000..138c4d5cf2 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/git_push.sh b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/git_push.sh index 484e8cc003..67b52e22d7 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/git_push.sh +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/git_push.sh @@ -1,11 +1,17 @@ #!/bin/sh # ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ # -# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" git_user_id=$1 git_repo_id=$2 release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi if [ "$git_user_id" = "" ]; then git_user_id="" @@ -28,7 +34,7 @@ git init # Adds the files in the local repository and stages them for commit. git add . -# Commits the tracked changes and prepares them to be pushed to a remote repository. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote @@ -37,9 +43,9 @@ if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@github.com/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git fi fi @@ -47,6 +53,5 @@ fi git pull origin master # Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" git push origin master 2>&1 | grep -v 'To https' - diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/index.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/index.ts index c312b70fa3..104dd3d21e 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/index.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectEntity.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectEntity.ts index 76882ebe1b..a0fc28a83a 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectEntity.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectEntity.ts @@ -1,54 +1,34 @@ /** * Cupix API - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * - * OpenAPI spec version: 1.7.0 + * The version of the OpenAPI document: 1.7.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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - import { ProjectEntityLocation } from './projectEntityLocation'; -export interface ProjectEntity { +export interface ProjectEntity { id: number; - kind?: ProjectEntity.KindEnum; - - thumbnailUrl?: string; - + thumbnail_url?: string; name?: string; - state?: string; - - meta?: any; - + meta?: object; location?: ProjectEntityLocation; - - createdAt?: Date; - - updatedAt?: Date; - - publishedAt?: Date; - + created_at?: string; + updated_at?: string; + published_at?: string; } export namespace ProjectEntity { - export enum KindEnum { - Project = 'project' - } + export type KindEnum = 'project'; + export const KindEnum = { + Project: 'project' as KindEnum + }; } + + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectEntityLocation.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectEntityLocation.ts index 1f84395dae..30c1aaefd5 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectEntityLocation.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectEntityLocation.ts @@ -1,32 +1,18 @@ /** * Cupix API - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * - * OpenAPI spec version: 1.7.0 + * The version of the OpenAPI document: 1.7.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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -export interface ProjectEntityLocation { +export interface ProjectEntityLocation { lat?: number; - lon?: number; - } + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectList.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectList.ts index c5bdf4283b..7801e2f203 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectList.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/model/projectList.ts @@ -1,31 +1,18 @@ /** * Cupix API - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * - * OpenAPI spec version: 1.7.0 + * The version of the OpenAPI document: 1.7.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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - import { ProjectEntity } from './projectEntity'; -export interface ProjectList { +export interface ProjectList { contents: Array; - } + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/ng-package.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/ng-package.json new file mode 100644 index 0000000000..3b17900dc9 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/ng-package.json @@ -0,0 +1,6 @@ +{ + "$schema": "./node_modules/ng-packagr/ng-package.schema.json", + "lib": { + "entryFile": "index.ts" + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/package.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/package.json index 16a813c383..f813e8e5f7 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/package.json +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/package.json @@ -1,38 +1,34 @@ { "name": "arrayAndAnyTest", "version": "1.0.2", - "description": "swagger client for arrayAndAnyTest", - "author": "Swagger Codegen Contributors", + "description": "OpenAPI client for arrayAndAnyTest", + "author": "OpenAPI-Generator Contributors", + "repository": { + "type": "git", + "url": "https:////.git" + }, "keywords": [ - "swagger-client" + "openapi-client", + "openapi-generator" ], - "license": "Apache-2.0", - "main": "dist/index.js", - "typings": "dist/index.d.ts", + "license": "Unlicense", "scripts": { - "build": "typings install && tsc --outDir dist/" + "build": "ng-packagr -p ng-package.json" }, "peerDependencies": { - "@angular/core": "^2.0.0", - "@angular/http": "^2.0.0", - "@angular/common": "^2.0.0", - "@angular/compiler": "^2.0.0", - "core-js": "^2.4.0", - "reflect-metadata": "^0.1.3", - "rxjs": "5.0.0-beta.12", - "zone.js": "^0.6.17" + "@angular/core": "^14.0.5", + "rxjs": "^7.5.5" }, "devDependencies": { - "@angular/core": "^2.0.0", - "@angular/http": "^2.0.0", - "@angular/common": "^2.0.0", - "@angular/compiler": "^2.0.0", - "@angular/platform-browser": "^2.0.0", - "core-js": "^2.4.0", + "@angular/common": "^14.0.5", + "@angular/compiler": "^14.0.5", + "@angular/compiler-cli": "^14.0.5", + "@angular/core": "^14.0.5", + "@angular/platform-browser": "^14.0.5", + "ng-packagr": "^14.0.2", "reflect-metadata": "^0.1.3", - "rxjs": "5.0.0-beta.12", - "zone.js": "^0.6.17", - "typescript": "^4.0", - "typings": "^1.3.2" - } -} + "rxjs": "^7.5.5", + "tsickle": "^0.46.3", + "typescript": ">=4.6.0 <=4.8.0", + "zone.js": "^0.11.5" + }} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/param.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/rxjs-operators.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/rxjs-operators.ts deleted file mode 100644 index 5659cd0694..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/rxjs-operators.ts +++ /dev/null @@ -1,11 +0,0 @@ -// RxJS imports according to https://angular.io/docs/ts/latest/guide/server-communication.html#!#rxjs - -// See node_module/rxjs/Rxjs.js -// Import just the rxjs statics and operators we need for THIS app. - -// Statics -import 'rxjs/add/observable/throw'; - -// Operators -import 'rxjs/add/operator/catch'; -import 'rxjs/add/operator/map'; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/tsconfig.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/tsconfig.json index e1f949692b..c01ebe255d 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/tsconfig.json +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/tsconfig.json @@ -1,28 +1,28 @@ { - "compilerOptions": { - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "noImplicitAny": false, - "suppressImplicitAnyIndexErrors": true, - "target": "es5", - "module": "commonjs", - "moduleResolution": "node", - "removeComments": true, - "sourceMap": true, - "outDir": "./lib", - "noLib": false, - "declaration": true - }, - "exclude": [ - "node_modules", - "typings/main.d.ts", - "typings/main", - "lib", - "dist" - ], - "filesGlob": [ - "./model/*.ts", - "./api/*.ts", - "typings/browser.d.ts" - ] + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es5", + "module": "commonjs", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/typings.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/typings.json deleted file mode 100644 index 507c40e5cb..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/typings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "globalDependencies": { - "core-js": "registry:dt/core-js#0.0.0+20160725163759" - } -} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/variables.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/variables.ts index 27b987e9b2..6fe58549f3 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/variables.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/array-and-object-expected/variables.ts @@ -1,3 +1,9 @@ -import { OpaqueToken } from '@angular/core'; +import { InjectionToken } from '@angular/core'; -export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/.gitignore b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/.gitignore new file mode 100644 index 0000000000..149b576547 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/README.md b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/README.md new file mode 100644 index 0000000000..3dbfaf6cd4 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/README.md @@ -0,0 +1,226 @@ +## custom-path-params-integration-test@1.0.3 + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install custom-path-params-integration-test@1.0.3 --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link custom-path-params-integration-test +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from 'custom-path-params-integration-test'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from 'custom-path-params-integration-test'; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from 'custom-path-params-integration-test'; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from 'custom-path-params-integration-test'; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from 'custom-path-params-integration-test'; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from 'custom-path-params-integration-test'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from 'custom-path-params-integration-test'; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/api.module.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/api.module.ts new file mode 100644 index 0000000000..5dcf060157 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/api.module.ts @@ -0,0 +1,31 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { MatrixParamsService } from './api/matrixParams.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/api/api.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/api/api.ts new file mode 100644 index 0000000000..b6cf2e7c9c --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/api/api.ts @@ -0,0 +1,3 @@ +export * from './matrixParams.service'; +import { MatrixParamsService } from './matrixParams.service'; +export const APIS = [MatrixParamsService]; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/api/matrixParams.service.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/api/matrixParams.service.ts new file mode 100644 index 0000000000..42f3cbcbdd --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/api/matrixParams.service.ts @@ -0,0 +1,306 @@ +/** + * Path Parameter Stuff + * This API shows the usage of various path parameter styles + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { ComplexParams } from '../model/complexParams'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class MatrixParamsService { + + protected basePath = 'http://localhost'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * @param matrixParamExploded + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public complexMatrixParamExploded(matrixParamExploded?: ComplexParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public complexMatrixParamExploded(matrixParamExploded?: ComplexParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public complexMatrixParamExploded(matrixParamExploded?: ComplexParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public complexMatrixParamExploded(matrixParamExploded?: ComplexParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/complexMatrixParamExploded${this.configuration.encodeParam({name: "matrixParamExploded", value: matrixParamExploded, in: "path", style: "matrix", explode: true, dataType: "ComplexParams", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * @param matrixParamFlat + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public complexMatrixParamFlat(matrixParamFlat?: ComplexParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public complexMatrixParamFlat(matrixParamFlat?: ComplexParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public complexMatrixParamFlat(matrixParamFlat?: ComplexParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public complexMatrixParamFlat(matrixParamFlat?: ComplexParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/complexMatrixParamFlat${this.configuration.encodeParam({name: "matrixParamFlat", value: matrixParamFlat, in: "path", style: "matrix", explode: false, dataType: "ComplexParams", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * @param plainParamFlat + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public plainMatrixParamFlat(plainParamFlat?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public plainMatrixParamFlat(plainParamFlat?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public plainMatrixParamFlat(plainParamFlat?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public plainMatrixParamFlat(plainParamFlat?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/plainMatrixParamFlat${this.configuration.encodeParam({name: "plainParamFlat", value: plainParamFlat, in: "path", style: "matrix", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * @param dateTimeParamFlat + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public plainMatrixParamFlat_1(dateTimeParamFlat?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public plainMatrixParamFlat_1(dateTimeParamFlat?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public plainMatrixParamFlat_1(dateTimeParamFlat?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public plainMatrixParamFlat_1(dateTimeParamFlat?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/date-timeMatrixParamFlat${this.configuration.encodeParam({name: "dateTimeParamFlat", value: dateTimeParamFlat, in: "path", style: "matrix", explode: false, dataType: "string", dataFormat: "date-time"})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/configuration.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/configuration.ts new file mode 100644 index 0000000000..d38a4c153f --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/configuration.ts @@ -0,0 +1,166 @@ +import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/encoder.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/encoder.ts new file mode 100644 index 0000000000..138c4d5cf2 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/git_push.sh b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/git_push.sh new file mode 100644 index 0000000000..67b52e22d7 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/index.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/index.ts new file mode 100644 index 0000000000..104dd3d21e --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/index.ts @@ -0,0 +1,6 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; +export * from './param'; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/model/complexParams.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/model/complexParams.ts new file mode 100644 index 0000000000..bed1db7a6e --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/model/complexParams.ts @@ -0,0 +1,18 @@ +/** + * Path Parameter Stuff + * This API shows the usage of various path parameter styles + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface ComplexParams { + key?: string; + value?: number; +} + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/model/models.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/model/models.ts new file mode 100644 index 0000000000..329693285d --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/model/models.ts @@ -0,0 +1 @@ +export * from './complexParams'; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/ng-package.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/ng-package.json new file mode 100644 index 0000000000..3b17900dc9 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/ng-package.json @@ -0,0 +1,6 @@ +{ + "$schema": "./node_modules/ng-packagr/ng-package.schema.json", + "lib": { + "entryFile": "index.ts" + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/package.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/package.json new file mode 100644 index 0000000000..c68cbf4ebe --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/package.json @@ -0,0 +1,34 @@ +{ + "name": "custom-path-params-integration-test", + "version": "1.0.3", + "description": "OpenAPI client for custom-path-params-integration-test", + "author": "OpenAPI-Generator Contributors", + "repository": { + "type": "git", + "url": "https:////.git" + }, + "keywords": [ + "openapi-client", + "openapi-generator" + ], + "license": "Unlicense", + "scripts": { + "build": "ng-packagr -p ng-package.json" + }, + "peerDependencies": { + "@angular/core": "^14.0.5", + "rxjs": "^7.5.5" + }, + "devDependencies": { + "@angular/common": "^14.0.5", + "@angular/compiler": "^14.0.5", + "@angular/compiler-cli": "^14.0.5", + "@angular/core": "^14.0.5", + "@angular/platform-browser": "^14.0.5", + "ng-packagr": "^14.0.2", + "reflect-metadata": "^0.1.3", + "rxjs": "^7.5.5", + "tsickle": "^0.46.3", + "typescript": ">=4.6.0 <=4.8.0", + "zone.js": "^0.11.5" + }} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/param.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/tsconfig.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/tsconfig.json new file mode 100644 index 0000000000..c01ebe255d --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es5", + "module": "commonjs", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/variables.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/variables.ts new file mode 100644 index 0000000000..6fe58549f3 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-expected/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-spec.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-spec.json new file mode 100644 index 0000000000..f758f4c3c3 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/custom-path-params-spec.json @@ -0,0 +1,129 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "Path Parameter Stuff", + "description": "This API shows the usage of various path parameter styles", + "version": "1.0.0" + }, + "paths": { + "/complexMatrixParamExploded{matrixParamExploded}": { + "parameters": [ + { + "name": "matrixParamExploded", + "in": "path", + "style": "matrix", + "explode": true, + "required": false, + "schema": { + "$ref": "#/components/schemas/ComplexParams" + } + } + ], + "put": { + "tags": [ + "MatrixParams" + ], + "operationId": "complexMatrixParamExploded", + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/complexMatrixParamFlat{matrixParamFlat}": { + "parameters": [ + { + "name": "matrixParamFlat", + "in": "path", + "style": "matrix", + "explode": false, + "required": false, + "schema": { + "$ref": "#/components/schemas/ComplexParams" + } + } + ], + "put": { + "tags": [ + "MatrixParams" + ], + "operationId": "complexMatrixParamFlat", + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/plainMatrixParamFlat{plainParamFlat}": { + "parameters": [ + { + "name": "plainParamFlat", + "in": "path", + "style": "matrix", + "explode": false, + "required": false, + "schema": { + "$ref": "#/components/schemas/PlainParam" + } + } + ], + "put": { + "tags": [ + "MatrixParams" + ], + "operationId": "plainMatrixParamFlat", + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/date-timeMatrixParamFlat{dateTimeParamFlat}": { + "parameters": [ + { + "name": "dateTimeParamFlat", + "in": "path", + "style": "matrix", + "explode": false, + "required": false, + "schema": { + "type": "string", + "format": "date-time" + } + } + ], + "put": { + "tags": [ + "MatrixParams" + ], + "operationId": "plainMatrixParamFlat", + "responses": { + "200": { + "description": "OK" + } + } + } + } + }, + "components": { + "schemas": { + "PlainParam": { + "type": "string" + }, + "ComplexParams": { + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "number", + "format": "int64" + } + } + } + } + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/.gitignore b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/.gitignore index 35e2fb2b02..149b576547 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/.gitignore +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/.gitignore @@ -1,3 +1,4 @@ wwwroot/*.js node_modules typings +dist diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/.openapi-generator-ignore b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/.openapi-generator-ignore deleted file mode 100644 index deed424f8a..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/.openapi-generator-ignore +++ /dev/null @@ -1,23 +0,0 @@ -# Swagger Codegen Ignore -# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen - -# 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 Swagger Codegen 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/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/LICENSE b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/LICENSE deleted file mode 100644 index 3f4d322ebd..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/README.md b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/README.md index 25b7aaaf39..5865977635 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/README.md +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/README.md @@ -2,7 +2,7 @@ ### Building -To build and compile the typescript sources to javascript use: +To install the required dependencies and to build the typescript sources run: ``` npm install npm run build @@ -10,11 +10,11 @@ npm run build ### publishing -First build the package than run ```npm publish``` +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) ### consuming -navigate to the folder of your consuming project and run one of next commando's. +Navigate to the folder of your consuming project and run one of next commands. _published:_ @@ -22,23 +22,205 @@ _published:_ npm install petstore-integration-test@1.0.3 --save ``` -_unPublished (not recommended):_ +_without publishing (not recommended):_ ``` -npm install PATH_TO_GENERATED_PACKAGE --save +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save ``` -In your angular2 project: +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link petstore-integration-test +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from 'petstore-integration-test'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from 'petstore-integration-test'; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from 'petstore-integration-test'; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from 'petstore-integration-test'; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` -TODO: paste example. ### Set service base path -If different than the generated base path, during app bootstrap, you can provide the base path to your service. +If different than the generated base path, during app bootstrap, you can provide the base path to your service. ``` -import { BASE_PATH } from './path-to-swagger-gen-service/index'; +import { BASE_PATH } from 'petstore-integration-test'; bootstrap(AppComponent, [ { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, ]); -``` +``` +or + +``` +import { BASE_PATH } from 'petstore-integration-test'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from 'petstore-integration-test'; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api.module.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api.module.ts index 4a2ae9c2e9..2afb8f64e9 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api.module.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api.module.ts @@ -1,23 +1,33 @@ -import { NgModule, ModuleWithProviders } from '@angular/core'; -import { CommonModule } from '@angular/common'; -import { HttpModule } from '@angular/http'; +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; import { PetService } from './api/pet.service'; import { StoreService } from './api/store.service'; import { UserService } from './api/user.service'; @NgModule({ - imports: [ CommonModule, HttpModule ], + imports: [], declarations: [], exports: [], - providers: [ PetService, StoreService, UserService ] + providers: [] }) export class ApiModule { - public static forConfig(configuration: Configuration): ModuleWithProviders { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { return { ngModule: ApiModule, - providers: [ {provide: Configuration, useValue: configuration}] + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); } } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/api.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/api.ts index b7d674969f..8e44b64083 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/api.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/api.ts @@ -1,3 +1,7 @@ export * from './pet.service'; +import { PetService } from './pet.service'; export * from './store.service'; +import { StoreService } from './store.service'; export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/pet.service.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/pet.service.ts index a1517db0e3..9613f31f3f 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/pet.service.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/pet.service.ts @@ -1,646 +1,724 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -import { Inject, Injectable, Optional } from '@angular/core'; -import { Http, Headers, URLSearchParams } from '@angular/http'; -import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; -import { Response, ResponseContentType } from '@angular/http'; - -import { Observable } from 'rxjs/Observable'; -import '../rxjs-operators'; - -import { Pet } from '../model/pet'; -import { ApiResponse } from '../model/apiResponse'; - -import { BASE_PATH } from '../variables'; -import { Configuration } from '../configuration'; - /* tslint:disable:no-unused-variable member-ordering */ +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; -@Injectable() +// @ts-ignore +import { ApiResponse } from '../model/apiResponse'; +// @ts-ignore +import { Pet } from '../model/pet'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) export class PetService { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders: Headers = new Headers(); - public configuration: Configuration = new Configuration(); - constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { - if (basePath) { - this.basePath = basePath; - } + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; - this.basePath = basePath || configuration.basePath || this.basePath; } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); } - - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; } } - return objA; + return false; + } + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; } /** * Add a new pet to the store - * * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public addPet(body: Pet, extraHttpRequestParams?: any): Observable<{}> { - return this.addPetWithHttpInfo(body, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet(petId: number, apiKey?: string, extraHttpRequestParams?: any): Observable<{}> { - return this.deletePetWithHttpInfo(petId, apiKey, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus(status: Array, extraHttpRequestParams?: any): Observable> { - return this.findPetsByStatusWithHttpInfo(status, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags(tags: Array, extraHttpRequestParams?: any): Observable> { - return this.findPetsByTagsWithHttpInfo(tags, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return - */ - public getPetById(petId: number, extraHttpRequestParams?: any): Observable { - return this.getPetByIdWithHttpInfo(petId, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet(body: Pet, extraHttpRequestParams?: any): Observable<{}> { - return this.updatePetWithHttpInfo(body, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - public updatePetWithForm(petId: number, name?: string, status?: string, extraHttpRequestParams?: any): Observable<{}> { - return this.updatePetWithFormWithHttpInfo(petId, name, status, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any): Observable { - return this.uploadFileWithHttpInfo(petId, additionalMetadata, file, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPetWithHttpInfo(body: Pet, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/pet`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'body' is not null or undefined + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling addPet.'); } + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + // to determine the Content-Type header - let consumes: string[] = [ - 'application/json', + const consumes: string[] = [ + 'application/json', 'application/xml' ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - // authentication (petstore_auth) required - // oauth required - if (this.configuration.accessToken) - { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); - } - - - headers.set('Content-Type', 'application/json'); - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Post, - headers: headers, - body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); } - return this.http.request(path, requestOptions); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: body, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Deletes a pet - * * @param petId Pet id to delete * @param apiKey + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public deletePetWithHttpInfo(petId: number, apiKey?: string, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/pet/${petId}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'petId' is not null or undefined + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } + let localVarHeaders = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + localVarHeaders = localVarHeaders.set('api_key', String(apiKey)); + } - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - + let localVarCredential: string | undefined; // authentication (petstore_auth) required - // oauth required - if (this.configuration.accessToken) - { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); - } - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Delete, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); } - return this.http.request(path, requestOptions); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public findPetsByStatusWithHttpInfo(status: Array, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/pet/findByStatus`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'status' is not null or undefined + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { if (status === null || status === undefined) { throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); } - if (status !== undefined) { - queryParameters.set('status', status); + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (status) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + [...status].join(COLLECTION_FORMATS['csv']), 'status'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - + let localVarCredential: string | undefined; // authentication (petstore_auth) required - // oauth required - if (this.configuration.accessToken) - { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); - } - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); } - return this.http.request(path, requestOptions); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/findByStatus`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public findPetsByTagsWithHttpInfo(tags: Array, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/pet/findByTags`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'tags' is not null or undefined + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { if (tags === null || tags === undefined) { throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); } - if (tags !== undefined) { - queryParameters.set('tags', tags); + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (tags) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + [...tags].join(COLLECTION_FORMATS['csv']), 'tags'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - + let localVarCredential: string | undefined; // authentication (petstore_auth) required - // oauth required - if (this.configuration.accessToken) - { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); - } - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); } - return this.http.request(path, requestOptions); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/findByTags`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Find pet by ID * Returns a single pet * @param petId ID of pet to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public getPetByIdWithHttpInfo(petId: number, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/pet/${petId}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'petId' is not null or undefined + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - + let localVarCredential: string | undefined; // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); } - return this.http.request(path, requestOptions); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Update an existing pet - * * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public updatePetWithHttpInfo(body: Pet, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/pet`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'body' is not null or undefined + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updatePet.'); } + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + // to determine the Content-Type header - let consumes: string[] = [ - 'application/json', + const consumes: string[] = [ + 'application/json', 'application/xml' ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - // authentication (petstore_auth) required - // oauth required - if (this.configuration.accessToken) - { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); - } - - - headers.set('Content-Type', 'application/json'); - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Put, - headers: headers, - body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); } - return this.http.request(path, requestOptions); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: body, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Updates a pet in the store with form data - * * @param petId ID of pet that needs to be updated * @param name Updated name of the pet * @param status Updated status of the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public updatePetWithFormWithHttpInfo(petId: number, name?: string, status?: string, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/pet/${petId}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - let formParams = new URLSearchParams(); - - // verify required parameter 'petId' is not null or undefined + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'application/x-www-form-urlencoded' ]; - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - // authentication (petstore_auth) required - // oauth required - if (this.configuration.accessToken) - { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); - } - - headers.set('Content-Type', 'application/x-www-form-urlencoded'); + const canConsumeForm = this.canConsumeForm(consumes); + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } if (name !== undefined) { - formParams.set('name', name); + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; } if (status !== undefined) { - formParams.set('status', status); + localVarFormParams = localVarFormParams.append('status', status) as any || localVarFormParams; } - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Post, - headers: headers, - body: formParams.toString(), - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - return this.http.request(path, requestOptions); + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * uploads an image - * * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public uploadFileWithHttpInfo(petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/pet/${petId}/uploadImage`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - let formParams = new URLSearchParams(); - - // verify required parameter 'petId' is not null or undefined + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } // to determine the Content-Type header - let consumes: string[] = [ + const consumes: string[] = [ 'multipart/form-data' ]; - // to determine the Accept header - let produces: string[] = [ - 'application/json' - ]; - - // authentication (petstore_auth) required - // oauth required - if (this.configuration.accessToken) - { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); - } - - headers.set('Content-Type', 'application/x-www-form-urlencoded'); + const canConsumeForm = this.canConsumeForm(consumes); + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } if (additionalMetadata !== undefined) { - formParams.set('additionalMetadata', additionalMetadata); + localVarFormParams = localVarFormParams.append('additionalMetadata', additionalMetadata) as any || localVarFormParams; } if (file !== undefined) { - formParams.set('file', file); + localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; } - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Post, - headers: headers, - body: formParams.toString(), - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - return this.http.request(path, requestOptions); + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/store.service.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/store.service.ts index edc5f2df5d..374f8f02e7 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/store.service.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/store.service.ts @@ -1,313 +1,342 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -import { Inject, Injectable, Optional } from '@angular/core'; -import { Http, Headers, URLSearchParams } from '@angular/http'; -import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; -import { Response, ResponseContentType } from '@angular/http'; - -import { Observable } from 'rxjs/Observable'; -import '../rxjs-operators'; - -import { Order } from '../model/order'; - -import { BASE_PATH } from '../variables'; -import { Configuration } from '../configuration'; - /* tslint:disable:no-unused-variable member-ordering */ +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; -@Injectable() +// @ts-ignore +import { Order } from '../model/order'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) export class StoreService { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders: Headers = new Headers(); - public configuration: Configuration = new Configuration(); - constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { - if (basePath) { - this.basePath = basePath; - } + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; - this.basePath = basePath || configuration.basePath || this.basePath; } - } - - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object - */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; } - return objA; + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; } /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public deleteOrder(orderId: string, extraHttpRequestParams?: any): Observable<{}> { - return this.deleteOrderWithHttpInfo(orderId, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory(extraHttpRequestParams?: any): Observable<{ [key: string]: number; }> { - return this.getInventoryWithHttpInfo(extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public getOrderById(orderId: number, extraHttpRequestParams?: any): Observable { - return this.getOrderByIdWithHttpInfo(orderId, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder(body: Order, extraHttpRequestParams?: any): Observable { - return this.placeOrderWithHttpInfo(body, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public deleteOrderWithHttpInfo(orderId: string, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/store/order/${orderId}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'orderId' is not null or undefined + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Delete, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Returns pet inventories by status * Returns a map of status codes to quantities + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public getInventoryWithHttpInfo(extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/store/inventory`; + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + let localVarHeaders = this.defaultHeaders; - - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/json' - ]; - + let localVarCredential: string | undefined; // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); } - return this.http.request(path, requestOptions); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/inventory`; + return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public getOrderByIdWithHttpInfo(orderId: number, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/store/order/${orderId}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'orderId' is not null or undefined + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Place an order for a pet - * * @param body order placed for purchasing the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public placeOrderWithHttpInfo(body: Order, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/store/order`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'body' is not null or undefined + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling placeOrder.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - headers.set('Content-Type', 'application/json'); - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Post, - headers: headers, - body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/order`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: body, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/user.service.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/user.service.ts index 6c5eeee1b6..a15f9bca62 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/user.service.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/api/user.service.ts @@ -1,522 +1,537 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -import { Inject, Injectable, Optional } from '@angular/core'; -import { Http, Headers, URLSearchParams } from '@angular/http'; -import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; -import { Response, ResponseContentType } from '@angular/http'; - -import { Observable } from 'rxjs/Observable'; -import '../rxjs-operators'; - -import { User } from '../model/user'; - -import { BASE_PATH } from '../variables'; -import { Configuration } from '../configuration'; - /* tslint:disable:no-unused-variable member-ordering */ +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; -@Injectable() +// @ts-ignore +import { User } from '../model/user'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) export class UserService { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders: Headers = new Headers(); - public configuration: Configuration = new Configuration(); - constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { - if (basePath) { - this.basePath = basePath; - } + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; - this.basePath = basePath || configuration.basePath || this.basePath; } - } - - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object - */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; } - return objA; + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; } /** * Create user * This can only be done by the logged in user. * @param body Created user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public createUser(body: User, extraHttpRequestParams?: any): Observable<{}> { - return this.createUserWithHttpInfo(body, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput(body: Array, extraHttpRequestParams?: any): Observable<{}> { - return this.createUsersWithArrayInputWithHttpInfo(body, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput(body: Array, extraHttpRequestParams?: any): Observable<{}> { - return this.createUsersWithListInputWithHttpInfo(body, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser(username: string, extraHttpRequestParams?: any): Observable<{}> { - return this.deleteUserWithHttpInfo(username, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName(username: string, extraHttpRequestParams?: any): Observable { - return this.getUserByNameWithHttpInfo(username, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser(username: string, password: string, extraHttpRequestParams?: any): Observable { - return this.loginUserWithHttpInfo(username, password, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Logs out current logged in user session - * - */ - public logoutUser(extraHttpRequestParams?: any): Observable<{}> { - return this.logoutUserWithHttpInfo(extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser(username: string, body: User, extraHttpRequestParams?: any): Observable<{}> { - return this.updateUserWithHttpInfo(username, body, extraHttpRequestParams) - .map((response: Response) => { - if (response.status === 204) { - return undefined; - } else { - return response.json(); - } - }); - } - - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUserWithHttpInfo(body: User, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'body' is not null or undefined + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUser.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - headers.set('Content-Type', 'application/json'); - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Post, - headers: headers, - body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: body, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Creates list of users with given input array - * * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public createUsersWithArrayInputWithHttpInfo(body: Array, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user/createWithArray`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'body' is not null or undefined + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - headers.set('Content-Type', 'application/json'); - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Post, - headers: headers, - body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/createWithArray`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: body, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Creates list of users with given input array - * * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public createUsersWithListInputWithHttpInfo(body: Array, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user/createWithList`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'body' is not null or undefined + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - headers.set('Content-Type', 'application/json'); - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Post, - headers: headers, - body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/createWithList`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: body, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public deleteUserWithHttpInfo(username: string, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user/${username}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'username' is not null or undefined + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Delete, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Get user by user name - * * @param username The name that needs to be fetched. Use user1 for testing. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public getUserByNameWithHttpInfo(username: string, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user/${username}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'username' is not null or undefined + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Logs user into the system - * * @param username The user name for login * @param password The password for login in clear text + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public loginUserWithHttpInfo(username: string, password: string, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user/login`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'username' is not null or undefined + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling loginUser.'); } - // verify required parameter 'password' is not null or undefined if (password === null || password === undefined) { throw new Error('Required parameter password was null or undefined when calling loginUser.'); } - if (username !== undefined) { - queryParameters.set('username', username); + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (username !== undefined && username !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + username, 'username'); } - if (password !== undefined) { - queryParameters.set('password', password); + if (password !== undefined && password !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + password, 'password'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); } - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } } - return this.http.request(path, requestOptions); + let localVarPath = `/user/login`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** * Logs out current logged in user session - * + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public logoutUserWithHttpInfo(extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user/logout`; + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + let localVarHeaders = this.defaultHeaders; - - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Get, - headers: headers, - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/logout`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } /** @@ -524,50 +539,70 @@ export class UserService { * This can only be done by the logged in user. * @param username name that need to be deleted * @param body Updated user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. */ - public updateUserWithHttpInfo(username: string, body: User, extraHttpRequestParams?: any): Observable { - const path = this.basePath + `/user/${username}`; - - let queryParameters = new URLSearchParams(); - let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - // verify required parameter 'username' is not null or undefined + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } - // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling updateUser.'); } + let localVarHeaders = this.defaultHeaders; - // to determine the Content-Type header - let consumes: string[] = [ - ]; - - // to determine the Accept header - let produces: string[] = [ - 'application/xml', - 'application/json' - ]; - - - - headers.set('Content-Type', 'application/json'); - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ - method: RequestMethod.Put, - headers: headers, - body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters - }); - - // https://github.com/swagger-api/swagger-codegen/issues/4037 - if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } - return this.http.request(path, requestOptions); + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: body, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/configuration.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/configuration.ts index ec087d2b0c..5ea92c82cb 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/configuration.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/configuration.ts @@ -1,24 +1,186 @@ +import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; + export interface ConfigurationParameters { - apiKey?: string; - username?: string; - password?: string; - accessToken?: string; - basePath?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; } export class Configuration { - apiKey: string; - username: string; - password: string; - accessToken: string; - basePath: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } - constructor(configurationParameters: ConfigurationParameters = {}) { - this.apiKey = configurationParameters.apiKey; - this.username = configurationParameters.username; - this.password = configurationParameters.password; - this.accessToken = configurationParameters.accessToken; - this.basePath = configurationParameters.basePath; - } + // init default api_key credential + if (!this.credentials['api_key']) { + this.credentials['api_key'] = () => { + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } + }; + } + + // init default petstore_auth credential + if (!this.credentials['petstore_auth']) { + this.credentials['petstore_auth'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/encoder.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/encoder.ts new file mode 100644 index 0000000000..138c4d5cf2 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/git_push.sh b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/git_push.sh index 484e8cc003..67b52e22d7 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/git_push.sh +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/git_push.sh @@ -1,11 +1,17 @@ #!/bin/sh # ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ # -# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" git_user_id=$1 git_repo_id=$2 release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi if [ "$git_user_id" = "" ]; then git_user_id="" @@ -28,7 +34,7 @@ git init # Adds the files in the local repository and stages them for commit. git add . -# Commits the tracked changes and prepares them to be pushed to a remote repository. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote @@ -37,9 +43,9 @@ if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@github.com/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git fi fi @@ -47,6 +53,5 @@ fi git pull origin master # Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" git push origin master 2>&1 | grep -v 'To https' - diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/index.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/index.ts index c312b70fa3..104dd3d21e 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/index.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/apiResponse.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/apiResponse.ts index 8b880303aa..ca96abca93 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/apiResponse.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/apiResponse.ts @@ -1,34 +1,19 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -export interface ApiResponse { +export interface ApiResponse { code?: number; - type?: string; - message?: string; - } + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/category.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/category.ts index 53f4c45613..4e435cae1d 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/category.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/category.ts @@ -1,32 +1,18 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -export interface Category { +export interface Category { id?: number; - name?: string; - } + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/order.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/order.ts index 5086f6011c..a730d4c175 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/order.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/order.ts @@ -1,50 +1,34 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -export interface Order { +export interface Order { id?: number; - petId?: number; - quantity?: number; - - shipDate?: Date; - + shipDate?: string; /** * Order Status */ status?: Order.StatusEnum; - complete?: boolean; - } export namespace Order { - export enum StatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' - } + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; } + + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/pet.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/pet.ts index f61abab4a2..284185ddd1 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/pet.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/pet.ts @@ -1,52 +1,36 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - import { Category } from './category'; import { Tag } from './tag'; -export interface Pet { +export interface Pet { id?: number; - category?: Category; - name: string; - photoUrls: Array; - tags?: Array; - /** * pet status in the store */ status?: Pet.StatusEnum; - } export namespace Pet { - export enum StatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' - } + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; } + + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/tag.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/tag.ts index 7e59927e22..73dee10beb 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/tag.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/tag.ts @@ -1,32 +1,18 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -export interface Tag { +export interface Tag { id?: number; - name?: string; - } + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/user.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/user.ts index 71bfdedd40..b3c99357e7 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/user.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/model/user.ts @@ -1,47 +1,27 @@ /** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * 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 - * Contact: apiteam@swagger.io + * The version of the OpenAPI document: 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://openapi-generator.tech). + * https://openapi-generator.tech * Do not edit the class manually. - * - * 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. */ - -export interface User { +export interface User { id?: number; - username?: string; - firstName?: string; - lastName?: string; - email?: string; - password?: string; - phone?: string; - /** * User Status */ userStatus?: number; - } + diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/ng-package.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/ng-package.json new file mode 100644 index 0000000000..3b17900dc9 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/ng-package.json @@ -0,0 +1,6 @@ +{ + "$schema": "./node_modules/ng-packagr/ng-package.schema.json", + "lib": { + "entryFile": "index.ts" + } +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/package.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/package.json index 720ddd966f..685877325a 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/package.json +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/package.json @@ -1,38 +1,34 @@ { "name": "petstore-integration-test", "version": "1.0.3", - "description": "swagger client for petstore-integration-test", - "author": "Swagger Codegen Contributors", + "description": "OpenAPI client for petstore-integration-test", + "author": "OpenAPI-Generator Contributors", + "repository": { + "type": "git", + "url": "https:////.git" + }, "keywords": [ - "swagger-client" + "openapi-client", + "openapi-generator" ], - "license": "Apache-2.0", - "main": "dist/index.js", - "typings": "dist/index.d.ts", + "license": "Unlicense", "scripts": { - "build": "typings install && tsc --outDir dist/" + "build": "ng-packagr -p ng-package.json" }, "peerDependencies": { - "@angular/core": "^2.0.0", - "@angular/http": "^2.0.0", - "@angular/common": "^2.0.0", - "@angular/compiler": "^2.0.0", - "core-js": "^2.4.0", - "reflect-metadata": "^0.1.3", - "rxjs": "5.0.0-beta.12", - "zone.js": "^0.6.17" + "@angular/core": "^14.0.5", + "rxjs": "^7.5.5" }, "devDependencies": { - "@angular/core": "^2.0.0", - "@angular/http": "^2.0.0", - "@angular/common": "^2.0.0", - "@angular/compiler": "^2.0.0", - "@angular/platform-browser": "^2.0.0", - "core-js": "^2.4.0", + "@angular/common": "^14.0.5", + "@angular/compiler": "^14.0.5", + "@angular/compiler-cli": "^14.0.5", + "@angular/core": "^14.0.5", + "@angular/platform-browser": "^14.0.5", + "ng-packagr": "^14.0.2", "reflect-metadata": "^0.1.3", - "rxjs": "5.0.0-beta.12", - "zone.js": "^0.6.17", - "typescript": "^4.0", - "typings": "^1.3.2" - } -} + "rxjs": "^7.5.5", + "tsickle": "^0.46.3", + "typescript": ">=4.6.0 <=4.8.0", + "zone.js": "^0.11.5" + }} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/param.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/rxjs-operators.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/rxjs-operators.ts deleted file mode 100644 index 5659cd0694..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/rxjs-operators.ts +++ /dev/null @@ -1,11 +0,0 @@ -// RxJS imports according to https://angular.io/docs/ts/latest/guide/server-communication.html#!#rxjs - -// See node_module/rxjs/Rxjs.js -// Import just the rxjs statics and operators we need for THIS app. - -// Statics -import 'rxjs/add/observable/throw'; - -// Operators -import 'rxjs/add/operator/catch'; -import 'rxjs/add/operator/map'; diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/tsconfig.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/tsconfig.json index e1f949692b..c01ebe255d 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/tsconfig.json +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/tsconfig.json @@ -1,28 +1,28 @@ { - "compilerOptions": { - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "noImplicitAny": false, - "suppressImplicitAnyIndexErrors": true, - "target": "es5", - "module": "commonjs", - "moduleResolution": "node", - "removeComments": true, - "sourceMap": true, - "outDir": "./lib", - "noLib": false, - "declaration": true - }, - "exclude": [ - "node_modules", - "typings/main.d.ts", - "typings/main", - "lib", - "dist" - ], - "filesGlob": [ - "./model/*.ts", - "./api/*.ts", - "typings/browser.d.ts" - ] + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es5", + "module": "commonjs", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] } diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/typings.json b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/typings.json deleted file mode 100644 index 507c40e5cb..0000000000 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/typings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "globalDependencies": { - "core-js": "registry:dt/core-js#0.0.0+20160725163759" - } -} diff --git a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/variables.ts b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/variables.ts index 27b987e9b2..6fe58549f3 100644 --- a/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/variables.ts +++ b/modules/openapi-generator/src/test/resources/integrationtests/typescript/petstore-expected/variables.ts @@ -1,3 +1,9 @@ -import { OpaqueToken } from '@angular/core'; +import { InjectionToken } from '@angular/core'; -export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/pom.xml b/pom.xml index 9a5dee0e97..6098b7ed22 100644 --- a/pom.xml +++ b/pom.xml @@ -744,6 +744,30 @@ samples/server/petstore/java-micronaut-server + + java-helidon-client + + + env + java + + + + samples/client/petstore/java-helidon-client + + + + java-helidon-server + + + env + java + + + + samples/server/petstore/java-helidon-server + + java-msf4j-server @@ -1018,7 +1042,7 @@ - samples/client/petstore/python + samples/client/petstore/python-prior @@ -1131,21 +1155,17 @@ samples/client/petstore/php/OpenAPIClient-php - - samples/server/petstore/python-aiohttp - samples/server/petstore/python-aiohttp-srclayout - samples/server/petstore/python-fastapi - samples/server/petstore/python-flask - samples/server/petstore/rust-server + samples/client/petstore/perl samples/client/petstore/ruby-faraday samples/client/petstore/ruby + samples/client/petstore/ruby-autoload @@ -1170,6 +1190,10 @@ + samples/server/petstore/python-aiohttp + samples/server/petstore/python-aiohttp-srclayout + samples/server/petstore/python-fastapi + samples/server/petstore/python-flask samples/server/petstore/java-camel samples/server/petstore/java-vertx-web samples/server/petstore/java-inflector @@ -1201,8 +1225,8 @@ - samples/client/petstore/python - samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent + samples/client/petstore/python-prior + samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent @@ -1210,6 +1234,7 @@ samples/client/petstore/typescript-jquery/npm--> samples/client/petstore/typescript-angular-v12-provided-in-root samples/client/petstore/typescript-angular-v13-provided-in-root + samples/client/petstore/typescript-angular-v14-provided-in-root samples/openapi3/client/petstore/typescript/builds/default samples/openapi3/client/petstore/typescript/tests/default samples/openapi3/client/petstore/typescript/builds/jquery @@ -1247,7 +1272,7 @@ samples/openapi3/client/petstore/python - samples/openapi3/client/petstore/python-experimental + samples/openapi3/client/petstore/python-prior @@ -1270,6 +1295,7 @@ samples/client/petstore/java/jersey3 samples/client/others/java/okhttp-gson-streaming samples/client/petstore/java/okhttp-gson + samples/client/petstore/java-micronaut-client @@ -1323,6 +1349,9 @@ samples/openapi3/client/petstore/dart2/petstore_client_lib + samples/openapi3/client/petstore/dart-dio/oneof + samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance + samples/openapi3/client/petstore/dart-dio/oneof_primitive samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable @@ -1469,7 +1498,7 @@ 30.1.1-jre 4.2.1 2.10.0 - 2.13.1 + 2.13.4 0.8.7 1.14 4.13.2 @@ -1489,9 +1518,8 @@ 3.1.12.2 3.0.0-M6 7.22.0 - 2.1.12 io.swagger.parser.v3 - 2.0.31 + 2.1.1 7.5 1.34 3.4.3 diff --git a/samples/client/others/csharp-netcore-complex-files/docs/InlineObject.md b/samples/client/others/csharp-netcore-complex-files/docs/InlineObject.md deleted file mode 100644 index 6b0d642f07..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/docs/InlineObject.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Files** | **List<System.IO.Stream>** | Many files | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/others/csharp-netcore-complex-files/docs/InlineObject1.md b/samples/client/others/csharp-netcore-complex-files/docs/InlineObject1.md deleted file mode 100644 index dd54d6fa6a..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/docs/InlineObject1.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject1 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**File** | **System.IO.Stream** | One file | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/others/csharp-netcore-complex-files/docs/InlineObject2.md b/samples/client/others/csharp-netcore-complex-files/docs/InlineObject2.md deleted file mode 100644 index 8344e91b98..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/docs/InlineObject2.md +++ /dev/null @@ -1,12 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject2 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Status** | **MultipartMixedStatus** | | -**Marker** | [**MultipartMixedMarker**](MultipartMixedMarker.md) | | [optional] -**File** | **System.IO.Stream** | a file | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/others/csharp-netcore-complex-files/docs/MultipartMixedMarker.md b/samples/client/others/csharp-netcore-complex-files/docs/MultipartMixedMarker.md deleted file mode 100644 index 025eb119a4..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/docs/MultipartMixedMarker.md +++ /dev/null @@ -1,11 +0,0 @@ -# Org.OpenAPITools.Model.MultipartMixedMarker -additional object - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Api/MultipartApiTests.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Api/MultipartApiTests.cs index f86f020a9c..49d6b7ec39 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Api/MultipartApiTests.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Api/MultipartApiTests.cs @@ -72,9 +72,10 @@ namespace Org.OpenAPITools.Test.Api public void MultipartMixedTest() { // TODO uncomment below to test the method and replace null with proper value + //MultipartMixedStatus status = null; //System.IO.Stream file = null; - //MultipartMixedMarker marker = null; - //instance.MultipartMixed(file, marker); + //MultipartMixedRequestMarker marker = null; + //instance.MultipartMixed(status, file, marker); } /// diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs deleted file mode 100644 index 9d935ab665..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * MultipartFile test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineObject1 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject1Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject1 - //private InlineObject1 instance; - - public InlineObject1Tests() - { - // TODO uncomment below to create an instance of InlineObject1 - //instance = new InlineObject1(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject1 - /// - [Fact] - public void InlineObject1InstanceTest() - { - // TODO uncomment below to test "IsType" InlineObject1 - //Assert.IsType(instance); - } - - - /// - /// Test the property 'File' - /// - [Fact] - public void FileTest() - { - // TODO unit test for the property 'File' - } - - } - -} diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs deleted file mode 100644 index bfcd720e7c..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * MultipartFile test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineObject2 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject2Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject2 - //private InlineObject2 instance; - - public InlineObject2Tests() - { - // TODO uncomment below to create an instance of InlineObject2 - //instance = new InlineObject2(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject2 - /// - [Fact] - public void InlineObject2InstanceTest() - { - // TODO uncomment below to test "IsType" InlineObject2 - //Assert.IsType(instance); - } - - - /// - /// Test the property 'Marker' - /// - [Fact] - public void MarkerTest() - { - // TODO unit test for the property 'Marker' - } - /// - /// Test the property 'File' - /// - [Fact] - public void FileTest() - { - // TODO unit test for the property 'File' - } - - } - -} diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs deleted file mode 100644 index 92ff59e7e0..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * MultipartFile test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineObject - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObjectTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject - //private InlineObject instance; - - public InlineObjectTests() - { - // TODO uncomment below to create an instance of InlineObject - //instance = new InlineObject(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject - /// - [Fact] - public void InlineObjectInstanceTest() - { - // TODO uncomment below to test "IsType" InlineObject - //Assert.IsType(instance); - } - - - /// - /// Test the property 'Files' - /// - [Fact] - public void FilesTest() - { - // TODO unit test for the property 'Files' - } - - } - -} diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/MultipartMixedMarkerTests.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/MultipartMixedMarkerTests.cs deleted file mode 100644 index b1ac7cf230..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools.Test/Model/MultipartMixedMarkerTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * MultipartFile test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing MultipartMixedMarker - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class MultipartMixedMarkerTests : IDisposable - { - // TODO uncomment below to declare an instance variable for MultipartMixedMarker - //private MultipartMixedMarker instance; - - public MultipartMixedMarkerTests() - { - // TODO uncomment below to create an instance of MultipartMixedMarker - //instance = new MultipartMixedMarker(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of MultipartMixedMarker - /// - [Fact] - public void MultipartMixedMarkerInstanceTest() - { - // TODO uncomment below to test "IsType" MultipartMixedMarker - //Assert.IsType(instance); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs index 1c160451c5..a15b1e7c11 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs @@ -502,7 +502,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } - localVarRequestOptions.FormParameters.Add("status", Org.OpenAPITools.Client.ClientUtils.ParameterToString(status)); // form parameter + localVarRequestOptions.FormParameters.Add("status", Org.OpenAPITools.Client.ClientUtils.Serialize(status)); // form parameter if (marker != null) { localVarRequestOptions.FormParameters.Add("marker", Org.OpenAPITools.Client.ClientUtils.ParameterToString(marker)); // form parameter diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs index 47035360d0..4706ebce00 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs @@ -24,9 +24,8 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; -using RestSharp.Deserializers; +using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; @@ -35,7 +34,7 @@ namespace Org.OpenAPITools.Client /// /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// - internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; @@ -81,7 +80,9 @@ namespace Org.OpenAPITools.Client } } - public T Deserialize(IRestResponse response) + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; @@ -93,7 +94,7 @@ namespace Org.OpenAPITools.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(IRestResponse response, Type type) + internal object Deserialize(RestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { @@ -146,15 +147,22 @@ namespace Org.OpenAPITools.Client } } - public string RootElement { get; set; } - public string Namespace { get; set; } - public string DateFormat { get; set; } + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } + + public DataFormat DataFormat => DataFormat.Json; } /// /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), @@ -185,14 +193,14 @@ namespace Org.OpenAPITools.Client /// Allows for extending request processing for generated code. /// /// The RestSharp request object - partial void InterceptRequest(IRestRequest request); + partial void InterceptRequest(RestRequest request); /// /// Allows for extending response processing for generated code. /// /// The RestSharp request object /// The RestSharp response object - partial void InterceptResponse(IRestRequest request, IRestResponse response); + partial void InterceptResponse(RestRequest request, RestResponse response); /// /// Initializes a new instance of the , defaulting to the global configurations' base url. @@ -227,25 +235,25 @@ namespace Org.OpenAPITools.Client switch (method) { case HttpMethod.Get: - other = RestSharpMethod.GET; + other = RestSharpMethod.Get; break; case HttpMethod.Post: - other = RestSharpMethod.POST; + other = RestSharpMethod.Post; break; case HttpMethod.Put: - other = RestSharpMethod.PUT; + other = RestSharpMethod.Put; break; case HttpMethod.Delete: - other = RestSharpMethod.DELETE; + other = RestSharpMethod.Delete; break; case HttpMethod.Head: - other = RestSharpMethod.HEAD; + other = RestSharpMethod.Head; break; case HttpMethod.Options: - other = RestSharpMethod.OPTIONS; + other = RestSharpMethod.Options; break; case HttpMethod.Patch: - other = RestSharpMethod.PATCH; + other = RestSharpMethod.Patch; break; default: throw new ArgumentOutOfRangeException("method", method, null); @@ -276,11 +284,7 @@ namespace Org.OpenAPITools.Client if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); - RestRequest request = new RestRequest(Method(method)) - { - Resource = path, - JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) - }; + RestRequest request = new RestRequest(path, Method(method)); if (options.PathParameters != null) { @@ -375,25 +379,17 @@ namespace Org.OpenAPITools.Client var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); else - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } } } - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - request.AddCookie(cookie.Name, cookie.Value); - } - } - return request; } - private ApiResponse ToApiResponse(IRestResponse response) + private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; string rawContent = response.Content; @@ -412,9 +408,17 @@ namespace Org.OpenAPITools.Client } } + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + if (response.Cookies != null) { - foreach (var responseCookies in response.Cookies) + foreach (var responseCookies in response.Cookies.Cast()) { transformed.Cookies.Add( new Cookie( @@ -432,54 +436,32 @@ namespace Org.OpenAPITools.Client private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else - { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } } - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.Proxy = configuration.Proxy; - } + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; - } + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; @@ -515,6 +497,10 @@ namespace Org.OpenAPITools.Client { response.Data = (T)(object)response.RawBytes; } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } InterceptResponse(req, response); @@ -527,7 +513,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, @@ -556,54 +542,21 @@ namespace Org.OpenAPITools.Client private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else - { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); - } + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) - { - client.Proxy = configuration.Proxy; - } - - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; - } + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; @@ -644,7 +597,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/ClientUtils.cs index f287a97a02..3760fe4455 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -120,6 +120,16 @@ namespace Org.OpenAPITools.Client return Convert.ToString(obj, CultureInfo.InvariantCulture); } + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + /// /// Encode string in base64 format. /// diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/Configuration.cs index 31223cdbd7..3872b493b9 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/Configuration.cs @@ -17,6 +17,7 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Net.Http; namespace Org.OpenAPITools.Client { @@ -108,7 +109,7 @@ namespace Org.OpenAPITools.Client public Configuration() { Proxy = null; - UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); BasePath = "http://localhost"; DefaultHeaders = new ConcurrentDictionary(); ApiKey = new ConcurrentDictionary(); diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/RetryConfiguration.cs index f589a4482d..c02b5480e9 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/RetryConfiguration.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client /// /// Retry policy /// - public static Policy RetryPolicy { get; set; } + public static Policy RetryPolicy { get; set; } /// /// Async retry policy /// - public static AsyncPolicy AsyncRetryPolicy { get; set; } + public static AsyncPolicy AsyncRetryPolicy { get; set; } } } diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject.cs deleted file mode 100644 index ae2d365c5e..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject.cs +++ /dev/null @@ -1,121 +0,0 @@ -/* - * MultipartFile test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject - /// - [DataContract(Name = "inline_object")] - public partial class InlineObject : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// Many files. - public InlineObject(List files = default(List)) - { - this.Files = files; - } - - /// - /// Many files - /// - /// Many files - [DataMember(Name = "files", EmitDefaultValue = false)] - public List Files { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineObject {\n"); - sb.Append(" Files: ").Append(Files).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject).AreEqual; - } - - /// - /// Returns true if InlineObject instances are equal - /// - /// Instance of InlineObject to be compared - /// Boolean - public bool Equals(InlineObject input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.Files != null) - { - hashCode = (hashCode * 59) + this.Files.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject1.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject1.cs deleted file mode 100644 index aee5f5ed83..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject1.cs +++ /dev/null @@ -1,121 +0,0 @@ -/* - * MultipartFile test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject1 - /// - [DataContract(Name = "inline_object_1")] - public partial class InlineObject1 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// One file. - public InlineObject1(System.IO.Stream file = default(System.IO.Stream)) - { - this.File = file; - } - - /// - /// One file - /// - /// One file - [DataMember(Name = "file", EmitDefaultValue = false)] - public System.IO.Stream File { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineObject1 {\n"); - sb.Append(" File: ").Append(File).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject1).AreEqual; - } - - /// - /// Returns true if InlineObject1 instances are equal - /// - /// Instance of InlineObject1 to be compared - /// Boolean - public bool Equals(InlineObject1 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.File != null) - { - hashCode = (hashCode * 59) + this.File.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject2.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject2.cs deleted file mode 100644 index a067def186..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject2.cs +++ /dev/null @@ -1,154 +0,0 @@ -/* - * MultipartFile test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject2 - /// - [DataContract(Name = "inline_object_2")] - public partial class InlineObject2 : IEquatable, IValidatableObject - { - - /// - /// Gets or Sets Status - /// - [DataMember(Name = "status", IsRequired = true, EmitDefaultValue = false)] - public MultipartMixedStatus Status { get; set; } - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject2() { } - /// - /// Initializes a new instance of the class. - /// - /// status (required). - /// marker. - /// a file (required). - public InlineObject2(MultipartMixedStatus status = default(MultipartMixedStatus), MultipartMixedMarker marker = default(MultipartMixedMarker), System.IO.Stream file = default(System.IO.Stream)) - { - this.Status = status; - // to ensure "file" is required (not null) - if (file == null) - { - throw new ArgumentNullException("file is a required property for InlineObject2 and cannot be null"); - } - this.File = file; - this.Marker = marker; - } - - /// - /// Gets or Sets Marker - /// - [DataMember(Name = "marker", EmitDefaultValue = false)] - public MultipartMixedMarker Marker { get; set; } - - /// - /// a file - /// - /// a file - [DataMember(Name = "file", IsRequired = true, EmitDefaultValue = false)] - public System.IO.Stream File { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineObject2 {\n"); - sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" Marker: ").Append(Marker).Append("\n"); - sb.Append(" File: ").Append(File).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject2).AreEqual; - } - - /// - /// Returns true if InlineObject2 instances are equal - /// - /// Instance of InlineObject2 to be compared - /// Boolean - public bool Equals(InlineObject2 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - hashCode = (hashCode * 59) + this.Status.GetHashCode(); - if (this.Marker != null) - { - hashCode = (hashCode * 59) + this.Marker.GetHashCode(); - } - if (this.File != null) - { - hashCode = (hashCode * 59) + this.File.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedMarker.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedMarker.cs deleted file mode 100644 index ee18f1fc14..0000000000 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedMarker.cs +++ /dev/null @@ -1,120 +0,0 @@ -/* - * MultipartFile test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// additional object - /// - [DataContract(Name = "_multipart_mixed_marker")] - public partial class MultipartMixedMarker : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// name. - public MultipartMixedMarker(string name = default(string)) - { - this.Name = name; - } - - /// - /// Gets or Sets Name - /// - [DataMember(Name = "name", EmitDefaultValue = false)] - public string Name { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class MultipartMixedMarker {\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as MultipartMixedMarker).AreEqual; - } - - /// - /// Returns true if MultipartMixedMarker instances are equal - /// - /// Instance of MultipartMixedMarker to be compared - /// Boolean - public bool Equals(MultipartMixedMarker input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.Name != null) - { - hashCode = (hashCode * 59) + this.Name.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedRequest.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedRequest.cs index e105406809..40555d7f34 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedRequest.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedRequest.cs @@ -36,7 +36,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Status /// - [DataMember(Name = "status", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "status", IsRequired = true, EmitDefaultValue = true)] public MultipartMixedStatus Status { get; set; } /// /// Initializes a new instance of the class. @@ -71,7 +71,7 @@ namespace Org.OpenAPITools.Model /// a file /// /// a file - [DataMember(Name = "file", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "file", IsRequired = true, EmitDefaultValue = true)] public System.IO.Stream File { get; set; } /// diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 5889bffe70..830f64d090 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,11 +21,17 @@ - + - + + + + + + + diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java index 89471e3b8b..3e8b94b158 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java @@ -881,6 +881,8 @@ public class ApiClient { content = null; } return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create(MediaType.parse(contentType), (String) obj); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java index d68460b7e2..52b25858f9 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java @@ -114,7 +114,7 @@ public class SomeObj { @SerializedName(SERIALIZED_NAME_TYPE) private String type; - public SomeObj() { + public SomeObj() { } public SomeObj $type(TypeEnum $type) { @@ -303,9 +303,7 @@ public class SomeObj { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (SomeObj.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!SomeObj.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in SomeObj is not found in the empty JSON string", SomeObj.openapiRequiredFields.toString())); } } @@ -317,13 +315,13 @@ public class SomeObj { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SomeObj` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("$_type") != null && !jsonObj.get("$_type").isJsonPrimitive()) { + if ((jsonObj.get("$_type") != null && !jsonObj.get("$_type").isJsonNull()) && !jsonObj.get("$_type").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `$_type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("$_type").toString())); } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } - if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonPrimitive()) { + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); } } diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.gitignore b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.gitignore new file mode 100644 index 0000000000..149b576547 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.npmignore b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.npmignore new file mode 100644 index 0000000000..999d88df69 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.npmignore @@ -0,0 +1 @@ +# empty npmignore to ensure all required files (e.g., in the dist folder) are published by npm \ No newline at end of file diff --git a/samples/client/petstore/python/.openapi-generator-ignore b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator-ignore similarity index 100% rename from samples/client/petstore/python/.openapi-generator-ignore rename to samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator-ignore diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/FILES b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/FILES new file mode 100644 index 0000000000..54773e481d --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/FILES @@ -0,0 +1,13 @@ +.gitignore +.npmignore +api.ts +base.ts +common.ts +configuration.ts +git_push.sh +index.ts +model/abstract-user-dto.ts +model/branch-dto.ts +model/index.ts +model/internal-authenticated-user-dto.ts +model/remote-authenticated-user-dto.ts diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/VERSION b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/api.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/api.ts new file mode 100644 index 0000000000..76a72f3a74 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/api.ts @@ -0,0 +1,17 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + + diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/base.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/base.ts new file mode 100644 index 0000000000..9046b16626 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/base.ts @@ -0,0 +1,71 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { Configuration } from "./configuration"; +// Some imports not used depending on template conditions +// @ts-ignore +import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; + +export const BASE_PATH = "http://localhost".replace(/\/+$/, ""); + +/** + * + * @export + */ +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +/** + * + * @export + * @interface RequestArgs + */ +export interface RequestArgs { + url: string; + options: AxiosRequestConfig; +} + +/** + * + * @export + * @class BaseAPI + */ +export class BaseAPI { + protected configuration: Configuration | undefined; + + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { + if (configuration) { + this.configuration = configuration; + this.basePath = configuration.basePath || this.basePath; + } + } +}; + +/** + * + * @export + * @class RequiredError + * @extends {Error} + */ +export class RequiredError extends Error { + name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } +} diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/common.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/common.ts new file mode 100644 index 0000000000..76b5d76500 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/common.ts @@ -0,0 +1,148 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import { Configuration } from "./configuration"; +import { RequiredError, RequestArgs } from "./base"; +import { AxiosInstance, AxiosResponse } from 'axios'; + +/** + * + * @export + */ +export const DUMMY_BASE_URL = 'https://example.com' + +/** + * + * @throws {RequiredError} + * @export + */ +export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) { + if (paramValue === null || paramValue === undefined) { + throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`); + } +} + +/** + * + * @export + */ +export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) { + if (configuration && configuration.apiKey) { + const localVarApiKeyValue = typeof configuration.apiKey === 'function' + ? await configuration.apiKey(keyParamName) + : await configuration.apiKey; + object[keyParamName] = localVarApiKeyValue; + } +} + +/** + * + * @export + */ +export const setBasicAuthToObject = function (object: any, configuration?: Configuration) { + if (configuration && (configuration.username || configuration.password)) { + object["auth"] = { username: configuration.username, password: configuration.password }; + } +} + +/** + * + * @export + */ +export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const accessToken = typeof configuration.accessToken === 'function' + ? await configuration.accessToken() + : await configuration.accessToken; + object["Authorization"] = "Bearer " + accessToken; + } +} + +/** + * + * @export + */ +export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? await configuration.accessToken(name, scopes) + : await configuration.accessToken; + object["Authorization"] = "Bearer " + localVarAccessTokenValue; + } +} + +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + +/** + * + * @export + */ +export const setSearchParams = function (url: URL, ...objects: any[]) { + const searchParams = new URLSearchParams(url.search); + setFlattenedQueryParams(searchParams, objects); + url.search = searchParams.toString(); +} + +/** + * + * @export + */ +export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) { + const nonString = typeof value !== 'string'; + const needsSerialization = nonString && configuration && configuration.isJsonMime + ? configuration.isJsonMime(requestOptions.headers['Content-Type']) + : nonString; + return needsSerialization + ? JSON.stringify(value !== undefined ? value : {}) + : (value || ""); +} + +/** + * + * @export + */ +export const toPathString = function (url: URL) { + return url.pathname + url.search + url.hash +} + +/** + * + * @export + */ +export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { + return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { + const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || basePath) + axiosArgs.url}; + return axios.request(axiosRequestArgs); + }; +} diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/configuration.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/configuration.ts new file mode 100644 index 0000000000..5112550300 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/configuration.ts @@ -0,0 +1,101 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface ConfigurationParameters { + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + username?: string; + password?: string; + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + basePath?: string; + baseOptions?: any; + formDataCtor?: new () => any; +} + +export class Configuration { + /** + * parameter for apiKey security + * @param name security name + * @memberof Configuration + */ + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + username?: string; + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + password?: string; + /** + * parameter for oauth2 security + * @param name security name + * @param scopes oauth2 scope + * @memberof Configuration + */ + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + /** + * override base path + * + * @type {string} + * @memberof Configuration + */ + basePath?: string; + /** + * base options for axios calls + * + * @type {any} + * @memberof Configuration + */ + baseOptions?: any; + /** + * The FormData constructor that will be used to create multipart form data + * requests. You can inject this here so that execution environments that + * do not support the FormData class can still run the generated client. + * + * @type {new () => FormData} + */ + formDataCtor?: new () => any; + + constructor(param: ConfigurationParameters = {}) { + this.apiKey = param.apiKey; + this.username = param.username; + this.password = param.password; + this.accessToken = param.accessToken; + this.basePath = param.basePath; + this.baseOptions = param.baseOptions; + this.formDataCtor = param.formDataCtor; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } +} diff --git a/samples/client/petstore/python/git_push.sh b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/git_push.sh similarity index 100% rename from samples/client/petstore/python/git_push.sh rename to samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/git_push.sh diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/index.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/index.ts new file mode 100644 index 0000000000..09f94830a1 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/index.ts @@ -0,0 +1,18 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export * from "./api"; +export * from "./configuration"; +export * from "./model"; diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/abstract-user-dto.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/abstract-user-dto.ts new file mode 100644 index 0000000000..765c425883 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/abstract-user-dto.ts @@ -0,0 +1,45 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +// May contain unused imports in some cases +// @ts-ignore +import { BranchDto } from './branch-dto'; + +/** + * + * @export + * @interface AbstractUserDto + */ +export interface AbstractUserDto { + /** + * + * @type {string} + * @memberof AbstractUserDto + */ + 'username'?: string; + /** + * + * @type {BranchDto} + * @memberof AbstractUserDto + */ + 'branch'?: BranchDto; + /** + * + * @type {string} + * @memberof AbstractUserDto + */ + 'type'?: string; +} + diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/branch-dto.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/branch-dto.ts new file mode 100644 index 0000000000..4c6d31ceb2 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/branch-dto.ts @@ -0,0 +1,30 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +/** + * + * @export + * @interface BranchDto + */ +export interface BranchDto { + /** + * + * @type {string} + * @memberof BranchDto + */ + 'name'?: string; +} + diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/index.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/index.ts new file mode 100644 index 0000000000..f92a1d9cad --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/index.ts @@ -0,0 +1,4 @@ +export * from './abstract-user-dto'; +export * from './branch-dto'; +export * from './internal-authenticated-user-dto'; +export * from './remote-authenticated-user-dto'; diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/internal-authenticated-user-dto.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/internal-authenticated-user-dto.ts new file mode 100644 index 0000000000..790458e539 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/internal-authenticated-user-dto.ts @@ -0,0 +1,29 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +// May contain unused imports in some cases +// @ts-ignore +import { AbstractUserDto } from './abstract-user-dto'; +// May contain unused imports in some cases +// @ts-ignore +import { BranchDto } from './branch-dto'; + +/** + * @type InternalAuthenticatedUserDto + * @export + */ +export type InternalAuthenticatedUserDto = AbstractUserDto; + + diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/remote-authenticated-user-dto.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/remote-authenticated-user-dto.ts new file mode 100644 index 0000000000..b8071de442 --- /dev/null +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/model/remote-authenticated-user-dto.ts @@ -0,0 +1,29 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +// May contain unused imports in some cases +// @ts-ignore +import { AbstractUserDto } from './abstract-user-dto'; +// May contain unused imports in some cases +// @ts-ignore +import { BranchDto } from './branch-dto'; + +/** + * @type RemoteAuthenticatedUserDto + * @export + */ +export type RemoteAuthenticatedUserDto = AbstractUserDto; + + diff --git a/samples/client/others/typescript/builds/with-unique-items/apis/DefaultApi.ts b/samples/client/others/typescript/builds/with-unique-items/apis/DefaultApi.ts index 8a5468e0d6..537b79f078 100644 --- a/samples/client/others/typescript/builds/with-unique-items/apis/DefaultApi.ts +++ b/samples/client/others/typescript/builds/with-unique-items/apis/DefaultApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import {ObjectSerializer} from '../models/ObjectSerializer'; diff --git a/samples/client/others/typescript/builds/with-unique-items/models/ObjectSerializer.ts b/samples/client/others/typescript/builds/with-unique-items/models/ObjectSerializer.ts index 02e7264cf8..b833844acc 100644 --- a/samples/client/others/typescript/builds/with-unique-items/models/ObjectSerializer.ts +++ b/samples/client/others/typescript/builds/with-unique-items/models/ObjectSerializer.ts @@ -1,6 +1,6 @@ -export * from './Response'; +export * from '../models/Response'; -import { Response } from './Response'; +import { Response } from '../models/Response'; /* tslint:disable:no-unused-variable */ let primitives = [ @@ -216,6 +216,10 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } + if (mediaType === "text/plain") { + return rawData; + } + if (mediaType === "application/json") { return JSON.parse(rawData); } diff --git a/samples/client/others/typescript/builds/with-unique-items/models/all.ts b/samples/client/others/typescript/builds/with-unique-items/models/all.ts index 1497e2a37b..fb6a6246f9 100644 --- a/samples/client/others/typescript/builds/with-unique-items/models/all.ts +++ b/samples/client/others/typescript/builds/with-unique-items/models/all.ts @@ -1 +1 @@ -export * from './Response' +export * from '../models/Response' diff --git a/samples/client/others/typescript/builds/with-unique-items/types/ObjectParamAPI.ts b/samples/client/others/typescript/builds/with-unique-items/types/ObjectParamAPI.ts index e2a0f69d78..fa8ba7a0a9 100644 --- a/samples/client/others/typescript/builds/with-unique-items/types/ObjectParamAPI.ts +++ b/samples/client/others/typescript/builds/with-unique-items/types/ObjectParamAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Response } from '../models/Response'; diff --git a/samples/client/others/typescript/builds/with-unique-items/types/ObservableAPI.ts b/samples/client/others/typescript/builds/with-unique-items/types/ObservableAPI.ts index 42726c3f3d..683cd89061 100644 --- a/samples/client/others/typescript/builds/with-unique-items/types/ObservableAPI.ts +++ b/samples/client/others/typescript/builds/with-unique-items/types/ObservableAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Observable, of, from } from '../rxjsStub'; import {mergeMap, map} from '../rxjsStub'; diff --git a/samples/client/others/typescript/builds/with-unique-items/types/PromiseAPI.ts b/samples/client/others/typescript/builds/with-unique-items/types/PromiseAPI.ts index 6df624fc4a..d0e502467e 100644 --- a/samples/client/others/typescript/builds/with-unique-items/types/PromiseAPI.ts +++ b/samples/client/others/typescript/builds/with-unique-items/types/PromiseAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Response } from '../models/Response'; diff --git a/samples/client/petstore/R-httr2-wrapper/.Rbuildignore b/samples/client/petstore/R-httr2-wrapper/.Rbuildignore new file mode 100644 index 0000000000..d982e4aa88 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/.Rbuildignore @@ -0,0 +1,20 @@ +^.*\.Rproj$ # Designates the directory as an RStudio Project +^\.Rproj\.user$ # Used by RStudio for temporary files +^README\.Rmd$ # An Rmd file used to generate README.md +^LICENSE\.md$ # Full text of the license +^cran-comments\.md$ # Comments for CRAN submission +^data-raw$ # Code used to create data included in the package +^pkgdown$ # Resources used for the package website +^_pkgdown\.yml$ # Configuration info for the package website +^\.github$ # Contributing guidelines, CoC, issue templates, etc. +^\.Rhistory$ +^\.gitignore$ +^\.openapi-generator-ignore$ +^\.travis\.yml$ +^\.lintr$ +^\.github$ +^\.openapi-generator$ +^docs$ +^git_push\.sh$ +^petstore\.Rcheck$ +^\.\.Rcheck$ diff --git a/samples/client/petstore/R-httr2-wrapper/.github/workflows/r-client.yaml b/samples/client/petstore/R-httr2-wrapper/.github/workflows/r-client.yaml new file mode 100644 index 0000000000..216ebe6c00 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/.github/workflows/r-client.yaml @@ -0,0 +1,33 @@ +# This file is automatically generated by openapi-generator (https://openapi-generator.tech) +# +# Based on https://github.com/r-lib/actions/tree/v2/examples +on: + push: + branches: [main, master] + pull_request: + branches: [main, master] + +name: R-CMD-check + +jobs: + R-CMD-check: + runs-on: ubuntu-latest + env: + R_KEEP_PKG_SOURCE: yes + steps: + - uses: actions/checkout@v2 + - uses: r-lib/actions/setup-r@v2 + with: + use-public-rspm: true + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::rcmdcheck, any::roxygen2, any::lintr, local::. + needs: check, roxygen2, lint + - name: Lint + run: lintr::lint_package() + shell: Rscript {0} + - name: Roxygenize + run: | + roxygen2::roxygenize('.', roclets = c('rd', 'collate', 'namespace')) + shell: Rscript {0} + - uses: r-lib/actions/check-r-package@v2 diff --git a/samples/client/petstore/R-httr2-wrapper/.gitignore b/samples/client/petstore/R-httr2-wrapper/.gitignore new file mode 100644 index 0000000000..5d21150e0c --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/.gitignore @@ -0,0 +1,35 @@ +# ref: https://github.com/github/gitignore/blob/master/R.gitignore + +# History files +.Rhistory +.Rapp.history + +# Session Data files +.RData + +# Example code in package build process +*-Ex.R + +# Output files from R CMD build +/*.tar.gz + +# Output files from R CMD check +/*.Rcheck/ + +# RStudio files +.Rproj.user/ + +# produced vignettes +vignettes/*.html +vignettes/*.pdf + +# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 +.httr-oauth + +# knitr and R markdown default cache directories +/*_cache/ +/cache/ + +# Temporary files created by R markdown +*.utf8.md +*.knit.md diff --git a/samples/client/petstore/R-httr2-wrapper/.lintr b/samples/client/petstore/R-httr2-wrapper/.lintr new file mode 100644 index 0000000000..54ee36a49c --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/.lintr @@ -0,0 +1,7 @@ +linters: linters_with_defaults( + line_length_linter(160), + object_name_linter = NULL, + cyclocomp_linter = NULL + ) +exclusions: list( + ) diff --git a/samples/client/petstore/R-httr2-wrapper/.openapi-generator-ignore b/samples/client/petstore/R-httr2-wrapper/.openapi-generator-ignore new file mode 100644 index 0000000000..c5fa491b4c --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/client/petstore/R-httr2-wrapper/.openapi-generator/FILES b/samples/client/petstore/R-httr2-wrapper/.openapi-generator/FILES new file mode 100644 index 0000000000..c1007a68c4 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/.openapi-generator/FILES @@ -0,0 +1,72 @@ +.Rbuildignore +.github/workflows/r-client.yaml +.gitignore +.lintr +.travis.yml +DESCRIPTION +NAMESPACE +R/allof_tag_api_response.R +R/animal.R +R/any_of_pig.R +R/any_of_primitive_type_test.R +R/api_client.R +R/api_exception.R +R/api_response.R +R/basque_pig.R +R/cat.R +R/cat_all_of.R +R/category.R +R/danish_pig.R +R/date.R +R/dog.R +R/dog_all_of.R +R/fake_api.R +R/mammal.R +R/model_api_response.R +R/nested_one_of.R +R/one_of_primitive_type_test.R +R/order.R +R/pet.R +R/pet_api.R +R/petstore_api.R +R/pig.R +R/special.R +R/store_api.R +R/tag.R +R/update_pet_request.R +R/user.R +R/user_api.R +R/whale.R +R/zebra.R +README.md +docs/AllofTagApiResponse.md +docs/Animal.md +docs/AnyOfPig.md +docs/AnyOfPrimitiveTypeTest.md +docs/BasquePig.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/DanishPig.md +docs/Date.md +docs/Dog.md +docs/DogAllOf.md +docs/FakeApi.md +docs/Mammal.md +docs/ModelApiResponse.md +docs/NestedOneOf.md +docs/OneOfPrimitiveTypeTest.md +docs/Order.md +docs/Pet.md +docs/PetApi.md +docs/Pig.md +docs/Special.md +docs/StoreApi.md +docs/Tag.md +docs/UpdatePetRequest.md +docs/User.md +docs/UserApi.md +docs/Whale.md +docs/Zebra.md +git_push.sh +tests/testthat.R diff --git a/samples/client/petstore/R-httr2-wrapper/.openapi-generator/VERSION b/samples/client/petstore/R-httr2-wrapper/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/R-httr2-wrapper/.travis.yml b/samples/client/petstore/R-httr2-wrapper/.travis.yml new file mode 100644 index 0000000000..60f31f3107 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/.travis.yml @@ -0,0 +1,18 @@ +# ref: https://docs.travis-ci.com/user/languages/r/ +language: r +cache: + directories: + - /home/travis/R/Library +r_packages: +- jsonlite +- httr2 +- testthat +# uncomment below to install deps with devtools +#install: +#- R -e 'devtools::install_deps(dep = T)' +script: +- R CMD build . +- R CMD check *tar.gz +- R CMD INSTALL *tar.gz +after_failure: +- cat ${TRAVIS_BUILD_DIR}/namsor.Rcheck/tests/testthat.Rout.fail diff --git a/samples/client/petstore/R-httr2-wrapper/DESCRIPTION b/samples/client/petstore/R-httr2-wrapper/DESCRIPTION new file mode 100644 index 0000000000..1cb6b5af88 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/DESCRIPTION @@ -0,0 +1,15 @@ +Package: petstore +Title: R Package Client for OpenAPI Petstore +Version: 1.0.0 +Author: person("OpenAPI Generator community", email = "team@openapitools.org", role = c("aut", "cre")) +Maintainer: OpenAPI Generator community +Description: This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +URL: https://github.com/GIT_USER_ID/GIT_REPO_ID +BugReports: https://github.com/GIT_USER_ID/GIT_REPO_ID/issues +Depends: R (>= 3.3) +Encoding: UTF-8 +License: Apache License 2.0 +LazyData: true +Suggests: testthat +Imports: jsonlite, httr2, R6, base64enc, stringr +RoxygenNote: 7.2.1 diff --git a/samples/client/petstore/R-httr2-wrapper/NAMESPACE b/samples/client/petstore/R-httr2-wrapper/NAMESPACE new file mode 100644 index 0000000000..fe9db16d34 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/NAMESPACE @@ -0,0 +1,49 @@ +# Generated by openapi-generator: https://openapi-generator.tech +# Do not edit by hand + +import(R6) +import(jsonlite) +import(httr2) +import(base64enc) +import(stringr) + +# Wrapper +export(petstore_api) + +# Core +export(ApiClient) +export(ApiResponse) +export(ApiException) + +# Models +export(AllofTagApiResponse) +export(Animal) +export(AnyOfPig) +export(AnyOfPrimitiveTypeTest) +export(BasquePig) +export(Cat) +export(CatAllOf) +export(Category) +export(DanishPig) +export(Date) +export(Dog) +export(DogAllOf) +export(Mammal) +export(ModelApiResponse) +export(NestedOneOf) +export(OneOfPrimitiveTypeTest) +export(Order) +export(Pet) +export(Pig) +export(Special) +export(Tag) +export(UpdatePetRequest) +export(User) +export(Whale) +export(Zebra) + +# APIs +export(FakeApi) +export(PetApi) +export(StoreApi) +export(UserApi) diff --git a/samples/client/petstore/R-httr2-wrapper/R.Rproj b/samples/client/petstore/R-httr2-wrapper/R.Rproj new file mode 100644 index 0000000000..eaa6b8186b --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R.Rproj @@ -0,0 +1,18 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 2 +Encoding: UTF-8 + +RnwWeave: Sweave +LaTeX: pdfLaTeX + +BuildType: Package +PackageUseDevtools: Yes +PackageInstallArgs: --no-multiarch --with-keep.source +PackageRoxygenize: rd,collate,namespace diff --git a/samples/client/petstore/R-httr2-wrapper/R/allof_tag_api_response.R b/samples/client/petstore/R-httr2-wrapper/R/allof_tag_api_response.R new file mode 100644 index 0000000000..e485c15e4c --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/allof_tag_api_response.R @@ -0,0 +1,286 @@ +#' Create a new AllofTagApiResponse +#' +#' @description +#' AllofTagApiResponse Class +#' +#' @docType class +#' @title AllofTagApiResponse +#' @description AllofTagApiResponse Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field name character [optional] +#' @field code integer [optional] +#' @field type character [optional] +#' @field message character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +AllofTagApiResponse <- R6::R6Class( + "AllofTagApiResponse", + public = list( + `id` = NULL, + `name` = NULL, + `code` = NULL, + `type` = NULL, + `message` = NULL, + `_field_list` = c("id", "name", "code", "type", "message"), + `additional_properties` = list(), + #' Initialize a new AllofTagApiResponse class. + #' + #' @description + #' Initialize a new AllofTagApiResponse class. + #' + #' @param id id + #' @param name name + #' @param code code + #' @param type type + #' @param message message + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `name` = NULL, `code` = NULL, `type` = NULL, `message` = NULL, additional_properties = NULL, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + if (!is.null(`code`)) { + stopifnot(is.numeric(`code`), length(`code`) == 1) + self$`code` <- `code` + } + if (!is.null(`type`)) { + stopifnot(is.character(`type`), length(`type`) == 1) + self$`type` <- `type` + } + if (!is.null(`message`)) { + stopifnot(is.character(`message`), length(`message`) == 1) + self$`message` <- `message` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return AllofTagApiResponse in JSON format + #' @export + toJSON = function() { + AllofTagApiResponseObject <- list() + if (!is.null(self$`id`)) { + AllofTagApiResponseObject[["id"]] <- + self$`id` + } + if (!is.null(self$`name`)) { + AllofTagApiResponseObject[["name"]] <- + self$`name` + } + if (!is.null(self$`code`)) { + AllofTagApiResponseObject[["code"]] <- + self$`code` + } + if (!is.null(self$`type`)) { + AllofTagApiResponseObject[["type"]] <- + self$`type` + } + if (!is.null(self$`message`)) { + AllofTagApiResponseObject[["message"]] <- + self$`message` + } + for (key in names(self$additional_properties)) { + AllofTagApiResponseObject[[key]] <- self$additional_properties[[key]] + } + + AllofTagApiResponseObject + }, + #' Deserialize JSON string into an instance of AllofTagApiResponse + #' + #' @description + #' Deserialize JSON string into an instance of AllofTagApiResponse + #' + #' @param input_json the JSON input + #' @return the instance of AllofTagApiResponse + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`name`)) { + self$`name` <- this_object$`name` + } + if (!is.null(this_object$`code`)) { + self$`code` <- this_object$`code` + } + if (!is.null(this_object$`type`)) { + self$`type` <- this_object$`type` + } + if (!is.null(this_object$`message`)) { + self$`message` <- this_object$`message` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return AllofTagApiResponse in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`name`)) { + sprintf( + '"name": + "%s" + ', + self$`name` + ) + }, + if (!is.null(self$`code`)) { + sprintf( + '"code": + %d + ', + self$`code` + ) + }, + if (!is.null(self$`type`)) { + sprintf( + '"type": + "%s" + ', + self$`type` + ) + }, + if (!is.null(self$`message`)) { + sprintf( + '"message": + "%s" + ', + self$`message` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of AllofTagApiResponse + #' + #' @description + #' Deserialize JSON string into an instance of AllofTagApiResponse + #' + #' @param input_json the JSON input + #' @return the instance of AllofTagApiResponse + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`name` <- this_object$`name` + self$`code` <- this_object$`code` + self$`type` <- this_object$`type` + self$`message` <- this_object$`message` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to AllofTagApiResponse + #' + #' @description + #' Validate JSON input with respect to AllofTagApiResponse and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of AllofTagApiResponse + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# AllofTagApiResponse$unlock() +# +## Below is an example to define the print fnuction +# AllofTagApiResponse$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# AllofTagApiResponse$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/animal.R b/samples/client/petstore/R-httr2-wrapper/R/animal.R new file mode 100644 index 0000000000..632b160087 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/animal.R @@ -0,0 +1,235 @@ +#' Create a new Animal +#' +#' @description +#' Animal Class +#' +#' @docType class +#' @title Animal +#' @description Animal Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field color character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Animal <- R6::R6Class( + "Animal", + public = list( + `className` = NULL, + `color` = NULL, + `_field_list` = c("className", "color"), + `additional_properties` = list(), + `_discriminator_property_name` = 'className', + `_discriminator_mapping_name` = c('Cat' = 'Cat', 'Dog' = 'Dog'), + #' Initialize a new Animal class. + #' + #' @description + #' Initialize a new Animal class. + #' + #' @param className className + #' @param color color. Default to "red". + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `color` = "red", additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`color`)) { + stopifnot(is.character(`color`), length(`color`) == 1) + self$`color` <- `color` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Animal in JSON format + #' @export + toJSON = function() { + AnimalObject <- list() + if (!is.null(self$`className`)) { + AnimalObject[["className"]] <- + self$`className` + } + if (!is.null(self$`color`)) { + AnimalObject[["color"]] <- + self$`color` + } + for (key in names(self$additional_properties)) { + AnimalObject[[key]] <- self$additional_properties[[key]] + } + + AnimalObject + }, + #' Deserialize JSON string into an instance of Animal + #' + #' @description + #' Deserialize JSON string into an instance of Animal + #' + #' @param input_json the JSON input + #' @return the instance of Animal + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`color`)) { + self$`color` <- this_object$`color` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Animal in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`color`)) { + sprintf( + '"color": + "%s" + ', + self$`color` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Animal + #' + #' @description + #' Deserialize JSON string into an instance of Animal + #' + #' @param input_json the JSON input + #' @return the instance of Animal + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`color` <- this_object$`color` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Animal + #' + #' @description + #' Validate JSON input with respect to Animal and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Animal: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Animal + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Animal$unlock() +# +## Below is an example to define the print fnuction +# Animal$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Animal$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/any_of_pig.R b/samples/client/petstore/R-httr2-wrapper/R/any_of_pig.R new file mode 100644 index 0000000000..404b710472 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/any_of_pig.R @@ -0,0 +1,184 @@ +#' @docType class +#' @title AnyOfPig +#' +#' @description AnyOfPig Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +AnyOfPig <- R6::R6Class( + "AnyOfPig", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field any_of a list of object types defined in the anyOf schema. + any_of = list("BasquePig", "DanishPig"), + #' Initialize a new AnyOfPig. + #' + #' @description + #' Initialize a new AnyOfPig. + #' + #' @param instance an instance of the object defined in the anyOf schemas: "BasquePig", "DanishPig" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "BasquePig") { + self$actual_instance <- instance + self$actual_type <- "BasquePig" + } else if (get(class(instance)[[1]], pos = -1)$classname == "DanishPig") { + self$actual_instance <- instance + self$actual_type <- "DanishPig" + } else { + stop(paste("Failed to initialize AnyOfPig with anyOf schemas BasquePig, DanishPig. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of AnyOfPig. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPig. + #' An alias to the method `fromJSON`. + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPig. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of AnyOfPig. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPig. + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPig. + #' @export + fromJSON = function(input) { + error_messages <- list() + + BasquePig_result <- tryCatch({ + BasquePig$public_methods$validateJSON(input) + BasquePig_instance <- BasquePig$new() + self$actual_instance <- BasquePig_instance$fromJSON(input) + self$actual_type <- "BasquePig" + return(self) + }, + error = function(err) err + ) + + if (!is.null(BasquePig_result["error"])) { + error_messages <- append(error_messages, BasquePig_result["message"]) + } + + DanishPig_result <- tryCatch({ + DanishPig$public_methods$validateJSON(input) + DanishPig_instance <- DanishPig$new() + self$actual_instance <- DanishPig_instance$fromJSON(input) + self$actual_type <- "DanishPig" + return(self) + }, + error = function(err) err + ) + + if (!is.null(DanishPig_result["error"])) { + error_messages <- append(error_messages, DanishPig_result["message"]) + } + + # no match + stop(paste("No match found when deserializing the payload into AnyOfPig with anyOf schemas BasquePig, DanishPig. Details: ", + paste(error_messages, collapse = ", "))) + }, + #' Serialize AnyOfPig to JSON string. + #' + #' @description + #' Serialize AnyOfPig to JSON string. + #' + #' @return JSON string representation of the AnyOfPig. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify((self$actual_instance$toJSONString()))) + } else { + NULL + } + }, + #' Serialize AnyOfPig to JSON. + #' + #' @description + #' Serialize AnyOfPig to JSON. + #' + #' @return JSON representation of the AnyOfPig. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to AnyOfPig. + #' + #' @description + #' Validate the input JSON with respect to AnyOfPig and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"any_of": "%s"', paste(unlist(self$any_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#AnyOfPig$unlock() +# +## Below is an example to define the print fnuction +#AnyOfPig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#AnyOfPig$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/any_of_primitive_type_test.R b/samples/client/petstore/R-httr2-wrapper/R/any_of_primitive_type_test.R new file mode 100644 index 0000000000..374aa8c605 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/any_of_primitive_type_test.R @@ -0,0 +1,202 @@ +#' @docType class +#' @title AnyOfPrimitiveTypeTest +#' +#' @description AnyOfPrimitiveTypeTest Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +AnyOfPrimitiveTypeTest <- R6::R6Class( + "AnyOfPrimitiveTypeTest", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("character", "integer"), + #' Initialize a new AnyOfPrimitiveTypeTest. + #' + #' @description + #' Initialize a new AnyOfPrimitiveTypeTest. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "character", "integer" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "character") { + self$actual_instance <- instance + self$actual_type <- "character" + } else if (get(class(instance)[[1]], pos = -1)$classname == "integer") { + self$actual_instance <- instance + self$actual_type <- "integer" + } else { + stop(paste("Failed to initialize AnyOfPrimitiveTypeTest with oneOf schemas character, integer. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPrimitiveTypeTest. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPrimitiveTypeTest. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + integer_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "integer") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "integer", typeof(instance))) + } + instance_type <- "integer" + matched_schemas <- append(matched_schemas, "integer") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(integer_result["error"])) { + error_messages <- append(error_messages, integer_result["message"]) + } + + character_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "character") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "character", typeof(instance))) + } + instance_type <- "character" + matched_schemas <- append(matched_schemas, "character") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(character_result["error"])) { + error_messages <- append(error_messages, character_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into AnyOfPrimitiveTypeTest with oneOf schemas character, integer.") + } else { + # no match + stop(paste("No match found when deserializing the payload into AnyOfPrimitiveTypeTest with oneOf schemas character, integer. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize AnyOfPrimitiveTypeTest to JSON string. + #' + #' @description + #' Serialize AnyOfPrimitiveTypeTest to JSON string. + #' + #' @return JSON string representation of the AnyOfPrimitiveTypeTest. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize AnyOfPrimitiveTypeTest to JSON. + #' + #' @description + #' Serialize AnyOfPrimitiveTypeTest to JSON. + #' + #' @return JSON representation of the AnyOfPrimitiveTypeTest. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to AnyOfPrimitiveTypeTest. + #' + #' @description + #' Validate the input JSON with respect to AnyOfPrimitiveTypeTest and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#AnyOfPrimitiveTypeTest$unlock() +# +## Below is an example to define the print fnuction +#AnyOfPrimitiveTypeTest$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#AnyOfPrimitiveTypeTest$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/api_client.R b/samples/client/petstore/R-httr2-wrapper/R/api_client.R new file mode 100644 index 0000000000..3ca3cf9ce7 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/api_client.R @@ -0,0 +1,433 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' ApiClient Class +#' +#' Generic API client for OpenAPI client library builds. +#' OpenAPI generic API client. This client handles the client- +#' server communication, and is invariant across implementations. Specifics of +#' the methods and models for each application are generated from the OpenAPI Generator +#' templates. +#' +#' NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +#' Ref: https://openapi-generator.tech +#' Do not edit the class manually. +#' +#' @docType class +#' @title ApiClient +#' @description ApiClient Class +#' @format An \code{R6Class} generator object +#' @field base_path Base url +#' @field user_agent Default user agent +#' @field default_headers Default headers +#' @field username Username for HTTP basic authentication +#' @field password Password for HTTP basic authentication +#' @field api_keys API keys +#' @field access_token Access token +#' @field oauth_client_id OAuth client ID +#' @field oauth_secret OAuth secret +#' @field oauth_refresh_token OAuth refresh token +#' @field oauth_flow_type OAuth flow type +#' @field oauth_authorization_url Authoriziation URL +#' @field oauth_token_url Token URL +#' @field oauth_pkce Boolean flag to enable PKCE +#' @field oauth_scopes OAuth scopes +#' @field bearer_token Bearer token +#' @field timeout Default timeout in seconds +#' @field retry_status_codes vector of status codes to retry +#' @field max_retry_attempts maximum number of retries for the status codes +#' @importFrom rlang abort +#' @export +ApiClient <- R6::R6Class( + "ApiClient", + public = list( + # base path of all requests + base_path = "http://petstore.swagger.io/v2", + # user agent in the HTTP request + user_agent = "PetstoreAgent", + # default headers in the HTTP request + default_headers = NULL, + # username (HTTP basic authentication) + username = NULL, + # password (HTTP basic authentication) + password = NULL, + # API keys + api_keys = NULL, + # Access token + access_token = NULL, + # OAuth2 client ID + oauth_client_id = NULL, + # OAuth2 secret + oauth_secret = NULL, + # OAuth2 refresh token + oauth_refresh_token = NULL, + # OAuth2 + # Flow type + oauth_flow_type = "implicit", + # Authoriziation URL + oauth_authorization_url = "http://petstore.swagger.io/api/oauth/dialog", + # Token URL + oauth_token_url = "", + # Enable PKCE? + oauth_pkce = TRUE, + # OAuth scopes + oauth_scopes = NULL, + # Bearer token + bearer_token = NULL, + # Time Out (seconds) + timeout = NULL, + # Vector of status codes to retry + retry_status_codes = NULL, + # Maximum number of retry attempts for the retry status codes + max_retry_attempts = NULL, + #' Initialize a new ApiClient. + #' + #' @description + #' Initialize a new ApiClient. + #' + #' @param base_path Base path. + #' @param user_agent User agent. + #' @param default_headers Default headers. + #' @param username User name. + #' @param password Password. + #' @param api_keys API keys. + #' @param access_token Access token. + #' @param bearer_token Bearer token. + #' @param timeout Timeout. + #' @param retry_status_codes Status codes for retry. + #' @param max_retry_attempts Maxmium number of retry. + #' @export + initialize = function(base_path = NULL, user_agent = NULL, + default_headers = NULL, + username = NULL, password = NULL, api_keys = NULL, + access_token = NULL, bearer_token = NULL, timeout = NULL, + retry_status_codes = NULL, max_retry_attempts = NULL) { + if (!is.null(base_path)) { + self$base_path <- base_path + } + + if (!is.null(default_headers)) { + self$default_headers <- default_headers + } + + if (!is.null(username)) { + self$username <- username + } + + if (!is.null(password)) { + self$password <- password + } + + if (!is.null(access_token)) { + self$access_token <- access_token + } + + if (!is.null(bearer_token)) { + self$bearer_token <- bearer_token + } + + if (!is.null(api_keys)) { + self$api_keys <- api_keys + } else { + self$api_keys <- list() + } + + if (!is.null(user_agent)) { + self$`user_agent` <- user_agent + } + + if (!is.null(timeout)) { + self$timeout <- timeout + } + + if (!is.null(retry_status_codes)) { + self$retry_status_codes <- retry_status_codes + } + + if (!is.null(max_retry_attempts)) { + self$max_retry_attempts <- max_retry_attempts + } + }, + #' Prepare to make an API call with the retry logic. + #' + #' @description + #' Prepare to make an API call with the retry logic. + #' + #' @param url URL. + #' @param method HTTP method. + #' @param query_params The query parameters. + #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters to upload files. + #' @param accepts The HTTP accpet headers. + #' @param content_types The HTTP content-type headers. + #' @param body The HTTP request body. + #' @param is_oauth True if the endpoints required OAuth authentication. + #' @param oauth_scopes OAuth scopes. + #' @param stream_callback Callback function to process the data stream. + #' @param ... Other optional arguments. + #' @return HTTP response + #' @export + CallApi = function(url, method, query_params, header_params, form_params, + file_params, accepts, content_types, body, + is_oauth = FALSE, oauth_scopes = NULL, stream_callback = NULL, ...) { + + # set the URL + req <- request(url) + + resp <- self$Execute(req, method, query_params, header_params, form_params, + file_params, accepts, content_types, body, is_oauth = is_oauth, + oauth_scopes = oauth_scopes, stream_callback = stream_callback, ...) + }, + #' Make an API call + #' + #' @description + #' Make an API call + #' + #' @param req httr2 request. + #' @param method HTTP method. + #' @param query_params The query parameters. + #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters for uploading files. + #' @param accepts The HTTP accpet headers. + #' @param content_types The HTTP content-type headers. + #' @param body The HTTP request body. + #' @param is_oauth True if the endpoints required OAuth authentication. + #' @param oauth_scopes OAuth scopes. + #' @param stream_callback Callback function to process data stream. + #' @param ... Other optional arguments. + #' @return HTTP response + #' @export + Execute = function(req, method, query_params, header_params, form_params, + file_params, accepts, content_types, body, + is_oauth = FALSE, oauth_scopes = NULL, stream_callback = NULL, ...) { + + ## add headers + req <- req %>% req_headers(!!!header_params) + + ## add default headers + req <- req %>% req_headers(!!!self$default_headers) + + # set HTTP accept header + accept <- self$select_header(accepts) + if (!is.null(accept)) { + req <- req %>% req_headers("Accept" = accept) + } + + # set HTTP content-type header + content_type <- self$select_header(content_types) + if (!is.null(content_type)) { + req <- req %>% req_headers("Content-Type" = content_type) + } + + ## add query parameters + for (query_param in names(query_params)) { + if (typeof(query_params[[query_param]]) == "list") { + # for explode, e.g. a=1,a=2,a=3 + req <- req %>% req_url_query(!!!query_params[[query_param]]) + } else { # for non-explode, e.g. a=1,2,3 + tmp <- list() + tmp[[query_param]] <- query_params[[query_param]] + req <- req %>% req_url_query(!!!tmp) + } + } + + # has file upload? + if (!is.null(file_params) && length(file_params) != 0) { + req <- req %>% req_body_multipart(!!!file_params) + + # add form parameters via req_body_multipart + if (!is.null(form_params) && length(form_params) != 0) { + req <- req %>% req_body_multipart(!!!form_params) + } + } else { # no file upload + # add form parameters via req_body_form + if (!is.null(form_params) && length(form_params) != 0) { + req <- req %>% req_body_form(!!!form_params) + } + } + + # add body parameters + if (!is.null(body)) { + req <- req %>% req_body_raw(body) + } + + # set timeout + if (!is.null(self$timeout)) { + req <- req %>% req_timeout(self$timeout) + } + + # set retry + if (!is.null(self$max_retry_attempts)) { + req <- req %>% retry_max_tries(self$timeout) + req <- req %>% retry_max_seconds(self$timeout) + } + + # set user agent + if (!is.null(self$user_agent)) { + req <- req %>% req_user_agent(self$user_agent) + } + + # set HTTP verb + req <- req %>% req_method(method) + + # use oauth authentication if the endpoint requires it + if (is_oauth && !is.null(self$oauth_client_id) && !is.null(self$oauth_secret)) { + client <- oauth_client( + id = self$oauth_client_id, + secret = obfuscated(self$oauth_secret), + token_url = self$oauth_token_url, + name = "petstore-oauth" + ) + + req_oauth_scopes <- NULL + if (!is.null(self$oauth_scopes)) { + # use oauth scopes provided by the user + req_oauth_scopes <- self$oauth_scopes + } else { + # use oauth scopes defined in openapi spec + req_oauth_scopes <- oauth_scopes + } + + req <- req %>% req_oauth_auth_code(client, scope = req_oauth_scopes, + pkce = self$oauth_pkce, + auth_url = self$oauth_authoriziation_url) + } + + # stream data + if (typeof(stream_callback) == "closure") { + req %>% req_stream(stream_callback) + } else { + # perform the HTTP request + resp <- req %>% + req_error(is_error = function(resp) FALSE) %>% + req_perform() + + # return ApiResponse + api_response <- ApiResponse$new() + api_response$status_code <- resp %>% resp_status() + api_response$status_code_desc <- resp %>% resp_status_desc() + api_response$response <- resp %>% resp_body_string() + api_response$headers <- resp %>% resp_headers() + + api_response + } + }, + #' Deserialize the content of API response to the given type. + #' + #' @description + #' Deserialize the content of API response to the given type. + #' + #' @param raw_response Raw response. + #' @param return_type R return type. + #' @param pkg_env Package environment. + #' @return Deserialized object. + #' @export + deserialize = function(raw_response, return_type, pkg_env) { + resp_obj <- jsonlite::fromJSON(raw_response) + self$deserializeObj(resp_obj, return_type, pkg_env) + }, + #' Deserialize the response from jsonlite object based on the given type. + #' + #' @description + #' Deserialize the response from jsonlite object based on the given type. + #' by handling complex and nested types by iterating recursively + #' Example return_types will be like "array[integer]", "map(Pet)", "array[map(Tag)]", etc. + #' + #' @param obj Response object. + #' @param return_type R return type. + #' @param pkg_env Package environment. + #' @return Deserialized object. + #' @export + deserializeObj = function(obj, return_type, pkg_env) { + return_obj <- NULL + primitive_types <- c("character", "numeric", "integer", "logical", "complex") + + # To handle the "map" type + if (startsWith(return_type, "map(")) { + inner_return_type <- regmatches(return_type, + regexec(pattern = "map\\((.*)\\)", return_type))[[1]][2] + return_obj <- lapply(names(obj), function(name) { + self$deserializeObj(obj[[name]], inner_return_type, pkg_env) + }) + names(return_obj) <- names(obj) + } else if (startsWith(return_type, "array[")) { + # To handle the "array" type + inner_return_type <- regmatches(return_type, + regexec(pattern = "array\\[(.*)\\]", return_type))[[1]][2] + if (c(inner_return_type) %in% primitive_types) { + return_obj <- vector("list", length = length(obj)) + if (length(obj) > 0) { + for (row in 1:length(obj)) { + return_obj[[row]] <- self$deserializeObj(obj[row], inner_return_type, pkg_env) + } + } + } else { + if (!is.null(nrow(obj))) { + return_obj <- vector("list", length = nrow(obj)) + if (nrow(obj) > 0) { + for (row in 1:nrow(obj)) { + return_obj[[row]] <- self$deserializeObj(obj[row, , drop = FALSE], + inner_return_type, pkg_env) + } + } + } + } + } else if (exists(return_type, pkg_env) && !(c(return_type) %in% primitive_types)) { + # To handle model objects which are not array or map containers (e.g. Pet) + return_type <- get(return_type, envir = as.environment(pkg_env)) + return_obj <- return_type$new() + # check if discriminator is defined + if (!is.null(return_obj$`_discriminator_property_name`)) { + data_type <- return_obj$`_discriminator_property_name` + # use discriminator mapping if provided + if (!is.null(return_obj$`_discriminator_mapping_name`)) { + data_type <- (return_obj$`_discriminator_mapping_name`)[[obj[[data_type]]]] + } else { + # no mapping provided, use the value directly + data_type <- obj[[data_type]] + } + # create an object of the mapped type (e.g. Cat) + return_type <- get(data_type, envir = as.environment(pkg_env)) + return_obj <- return_type$new() + } + return_obj$fromJSON( + jsonlite::toJSON(obj, digits = NA, auto_unbox = TRUE) + ) + } else { + # To handle primitive type + return_obj <- obj + } + return_obj + }, + #' Return a propery header (for accept or content-type). + #' + #' @description + #' Return a propery header (for accept or content-type). If JSON-related MIME is found, + #' return it. Otherwise, return the first one, if any. + #' + #' @param headers A list of headers + #' @return A header (e.g. 'application/json') + #' @export + select_header = function(headers) { + if (length(headers) == 0) { + return(invisible(NULL)) + } else { + for (header in headers) { + if (str_detect(header, "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")) { + # return JSON-related MIME + return(header) + } + } + + # not json mime type, simply return the first one + return(headers[1]) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2-wrapper/R/api_exception.R b/samples/client/petstore/R-httr2-wrapper/R/api_exception.R new file mode 100644 index 0000000000..f31f27858b --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/api_exception.R @@ -0,0 +1,82 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title ApiException +#' @description ApiException Class +#' @format An \code{R6Class} generator object +#' @field status Status of the ApiException +#' @field reason Reason of the ApiException +#' @field body Body of the http response +#' @field headers Headers of the http response +#' @field error_object error object type +#' @export +ApiException <- R6::R6Class( + "ApiException", + public = list( + status = NULL, + reason = NULL, + body = NULL, + headers = NULL, + error_object = NULL, + #' Initialize a new ApiException class. + #' + #' @description + #' Initialize a new ApiExceptino class. + #' + #' @param status HTTP status. + #' @param reason Reason of the ApiException. + #' @param http_response HTTP response object. + #' @export + initialize = function(status = NULL, reason = NULL, http_response = NULL) { + if (!is.null(http_response)) { + self$status <- http_response$status_code + errorMsg <- http_response$response + if (is.null(errorMsg) || errorMsg == "") { + errorMsg <- "Api exception encountered. No details given." + } + self$body <- errorMsg + self$headers <- http_response$headers + self$reason <- http_response$http_status_desc + self$error_object <- ModelApiResponse$new()$fromJSONString(http_response$response) + } else { + self$status <- status + self$reason <- reason + self$body <- NULL + self$headers <- NULL + self$error_object <- NULL + } + }, + #' Returns the string format of ApiException. + #' + #' @description + #' Returns the string format of ApiException. + #' + #' @return the string format of ApiException. + #' @export + toString = function() { + errorMsg <- "" + errorMsg <- paste("status : ", self$status, "\n", sep = "") + errorMsg <- paste(errorMsg, "Reason : ", self$reason, "\n", sep = "") + if (!is.null(self$headers)) { + errorMsg <- paste(errorMsg, "Headers : ", "\n", sep = "") + for (name in names(self$headers)) { + errorMsg <- paste(errorMsg, name, " : ", self$headers[[name]], "\n", sep = " ") + } + } + if (!is.null(self$body)) { + errorMsg <- paste(errorMsg, "Body : ", "\n", sep = "") + errorMsg <- paste(errorMsg, self$body, "\n") + } + if (!is.null(self$error_object)) { + errorMsg <- paste(errorMsg, "Error object : ", "\n", sep = "") + errorMsg <- paste(errorMsg, self$error_object$toJSONString(), "\n") + } + errorMsg + } + ) +) diff --git a/samples/client/petstore/R-httr2-wrapper/R/api_response.R b/samples/client/petstore/R-httr2-wrapper/R/api_response.R new file mode 100644 index 0000000000..70431ae7e5 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/api_response.R @@ -0,0 +1,49 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title ApiResponse +#' @description ApiResponse Class +#' @format An \code{R6Class} generator object +#' @field content The deserialized response body. +#' @field response The raw response from the endpoint. +#' @field status_code The HTTP response status code. +#' @field status_code_desc The brief descriptoin of the HTTP response status code. +#' @field headers The HTTP response headers. +#' @export +ApiResponse <- R6::R6Class( + "ApiResponse", + public = list( + content = NULL, + response = NULL, + status_code = NULL, + status_code_desc = NULL, + headers = NULL, + #' Initialize a new ApiResponse class. + #' + #' @description + #' Initialize a new ApiResponse class. + #' + #' @param content The deserialized response body. + #' @param response The raw response from the endpoint. + #' @param status_code The HTTP response status code. + #' @param status_code_desc The brief description of the HTTP response status code. + #' @param headers The HTTP response headers. + #' @export + initialize = function(content = NULL, + response = NULL, + status_code = NULL, + status_code_desc = NULL, + headers = NULL) { + self$content <- content + self$response <- response + self$status_code <- status_code + self$status_code_desc <- status_code_desc + self$headers <- headers + } + ) +) diff --git a/samples/client/petstore/R-httr2-wrapper/R/basque_pig.R b/samples/client/petstore/R-httr2-wrapper/R/basque_pig.R new file mode 100644 index 0000000000..2335bbe37c --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/basque_pig.R @@ -0,0 +1,249 @@ +#' Create a new BasquePig +#' +#' @description +#' BasquePig Class +#' +#' @docType class +#' @title BasquePig +#' @description BasquePig Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field color character +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +BasquePig <- R6::R6Class( + "BasquePig", + public = list( + `className` = NULL, + `color` = NULL, + `_field_list` = c("className", "color"), + `additional_properties` = list(), + #' Initialize a new BasquePig class. + #' + #' @description + #' Initialize a new BasquePig class. + #' + #' @param className className + #' @param color color + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `color`, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!missing(`color`)) { + stopifnot(is.character(`color`), length(`color`) == 1) + self$`color` <- `color` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return BasquePig in JSON format + #' @export + toJSON = function() { + BasquePigObject <- list() + if (!is.null(self$`className`)) { + BasquePigObject[["className"]] <- + self$`className` + } + if (!is.null(self$`color`)) { + BasquePigObject[["color"]] <- + self$`color` + } + for (key in names(self$additional_properties)) { + BasquePigObject[[key]] <- self$additional_properties[[key]] + } + + BasquePigObject + }, + #' Deserialize JSON string into an instance of BasquePig + #' + #' @description + #' Deserialize JSON string into an instance of BasquePig + #' + #' @param input_json the JSON input + #' @return the instance of BasquePig + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`color`)) { + self$`color` <- this_object$`color` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return BasquePig in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`color`)) { + sprintf( + '"color": + "%s" + ', + self$`color` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of BasquePig + #' + #' @description + #' Deserialize JSON string into an instance of BasquePig + #' + #' @param input_json the JSON input + #' @return the instance of BasquePig + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`color` <- this_object$`color` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to BasquePig + #' + #' @description + #' Validate JSON input with respect to BasquePig and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for BasquePig: the required field `className` is missing.")) + } + # check the required field `color` + if (!is.null(input_json$`color`)) { + stopifnot(is.character(input_json$`color`), length(input_json$`color`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for BasquePig: the required field `color` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of BasquePig + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + # check if the required `color` is null + if (is.null(self$`color`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + # check if the required `color` is null + if (is.null(self$`color`)) { + invalid_fields["color"] <- "Non-nullable required field `color` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# BasquePig$unlock() +# +## Below is an example to define the print fnuction +# BasquePig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# BasquePig$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/cat.R b/samples/client/petstore/R-httr2-wrapper/R/cat.R new file mode 100644 index 0000000000..60d417950b --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/cat.R @@ -0,0 +1,257 @@ +#' Create a new Cat +#' +#' @description +#' Cat Class +#' +#' @docType class +#' @title Cat +#' @description Cat Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field color character [optional] +#' @field declawed character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Cat <- R6::R6Class( + "Cat", + inherit = Animal, + public = list( + `className` = NULL, + `color` = NULL, + `declawed` = NULL, + `_field_list` = c("className", "color", "declawed"), + `additional_properties` = list(), + #' Initialize a new Cat class. + #' + #' @description + #' Initialize a new Cat class. + #' + #' @param className className + #' @param color color. Default to "red". + #' @param declawed declawed + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `color` = "red", `declawed` = NULL, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`color`)) { + stopifnot(is.character(`color`), length(`color`) == 1) + self$`color` <- `color` + } + if (!is.null(`declawed`)) { + stopifnot(is.logical(`declawed`), length(`declawed`) == 1) + self$`declawed` <- `declawed` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Cat in JSON format + #' @export + toJSON = function() { + CatObject <- list() + if (!is.null(self$`className`)) { + CatObject[["className"]] <- + self$`className` + } + if (!is.null(self$`color`)) { + CatObject[["color"]] <- + self$`color` + } + if (!is.null(self$`declawed`)) { + CatObject[["declawed"]] <- + self$`declawed` + } + for (key in names(self$additional_properties)) { + CatObject[[key]] <- self$additional_properties[[key]] + } + + CatObject + }, + #' Deserialize JSON string into an instance of Cat + #' + #' @description + #' Deserialize JSON string into an instance of Cat + #' + #' @param input_json the JSON input + #' @return the instance of Cat + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`color`)) { + self$`color` <- this_object$`color` + } + if (!is.null(this_object$`declawed`)) { + self$`declawed` <- this_object$`declawed` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Cat in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`color`)) { + sprintf( + '"color": + "%s" + ', + self$`color` + ) + }, + if (!is.null(self$`declawed`)) { + sprintf( + '"declawed": + %s + ', + tolower(self$`declawed`) + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Cat + #' + #' @description + #' Deserialize JSON string into an instance of Cat + #' + #' @param input_json the JSON input + #' @return the instance of Cat + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`color` <- this_object$`color` + self$`declawed` <- this_object$`declawed` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Cat + #' + #' @description + #' Validate JSON input with respect to Cat and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Cat: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Cat + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Cat$unlock() +# +## Below is an example to define the print fnuction +# Cat$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Cat$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/cat_all_of.R b/samples/client/petstore/R-httr2-wrapper/R/cat_all_of.R new file mode 100644 index 0000000000..c3969fc055 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/cat_all_of.R @@ -0,0 +1,194 @@ +#' Create a new CatAllOf +#' +#' @description +#' CatAllOf Class +#' +#' @docType class +#' @title CatAllOf +#' @description CatAllOf Class +#' @format An \code{R6Class} generator object +#' @field declawed character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +CatAllOf <- R6::R6Class( + "CatAllOf", + public = list( + `declawed` = NULL, + `_field_list` = c("declawed"), + `additional_properties` = list(), + #' Initialize a new CatAllOf class. + #' + #' @description + #' Initialize a new CatAllOf class. + #' + #' @param declawed declawed + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`declawed` = NULL, additional_properties = NULL, ...) { + if (!is.null(`declawed`)) { + stopifnot(is.logical(`declawed`), length(`declawed`) == 1) + self$`declawed` <- `declawed` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return CatAllOf in JSON format + #' @export + toJSON = function() { + CatAllOfObject <- list() + if (!is.null(self$`declawed`)) { + CatAllOfObject[["declawed"]] <- + self$`declawed` + } + for (key in names(self$additional_properties)) { + CatAllOfObject[[key]] <- self$additional_properties[[key]] + } + + CatAllOfObject + }, + #' Deserialize JSON string into an instance of CatAllOf + #' + #' @description + #' Deserialize JSON string into an instance of CatAllOf + #' + #' @param input_json the JSON input + #' @return the instance of CatAllOf + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`declawed`)) { + self$`declawed` <- this_object$`declawed` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return CatAllOf in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`declawed`)) { + sprintf( + '"declawed": + %s + ', + tolower(self$`declawed`) + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of CatAllOf + #' + #' @description + #' Deserialize JSON string into an instance of CatAllOf + #' + #' @param input_json the JSON input + #' @return the instance of CatAllOf + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`declawed` <- this_object$`declawed` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to CatAllOf + #' + #' @description + #' Validate JSON input with respect to CatAllOf and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of CatAllOf + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# CatAllOf$unlock() +# +## Below is an example to define the print fnuction +# CatAllOf$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# CatAllOf$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/category.R b/samples/client/petstore/R-httr2-wrapper/R/category.R new file mode 100644 index 0000000000..2de263a568 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/category.R @@ -0,0 +1,225 @@ +#' Create a new Category +#' +#' @description +#' A category for a pet +#' +#' @docType class +#' @title Category +#' @description Category Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field name character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Category <- R6::R6Class( + "Category", + public = list( + `id` = NULL, + `name` = NULL, + `_field_list` = c("id", "name"), + `additional_properties` = list(), + #' Initialize a new Category class. + #' + #' @description + #' Initialize a new Category class. + #' + #' @param id id + #' @param name name + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `name` = NULL, additional_properties = NULL, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Category in JSON format + #' @export + toJSON = function() { + CategoryObject <- list() + if (!is.null(self$`id`)) { + CategoryObject[["id"]] <- + self$`id` + } + if (!is.null(self$`name`)) { + CategoryObject[["name"]] <- + self$`name` + } + for (key in names(self$additional_properties)) { + CategoryObject[[key]] <- self$additional_properties[[key]] + } + + CategoryObject + }, + #' Deserialize JSON string into an instance of Category + #' + #' @description + #' Deserialize JSON string into an instance of Category + #' + #' @param input_json the JSON input + #' @return the instance of Category + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`name`)) { + self$`name` <- this_object$`name` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Category in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`name`)) { + sprintf( + '"name": + "%s" + ', + self$`name` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Category + #' + #' @description + #' Deserialize JSON string into an instance of Category + #' + #' @param input_json the JSON input + #' @return the instance of Category + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`name` <- this_object$`name` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Category + #' + #' @description + #' Validate JSON input with respect to Category and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Category + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + if (!str_detect(self$`name`, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + if (!str_detect(self$`name`, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")) { + invalid_fields["name"] <- "Invalid value for `name`, must conform to the pattern ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Category$unlock() +# +## Below is an example to define the print fnuction +# Category$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Category$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/danish_pig.R b/samples/client/petstore/R-httr2-wrapper/R/danish_pig.R new file mode 100644 index 0000000000..737bfad4b9 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/danish_pig.R @@ -0,0 +1,249 @@ +#' Create a new DanishPig +#' +#' @description +#' DanishPig Class +#' +#' @docType class +#' @title DanishPig +#' @description DanishPig Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field size integer +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +DanishPig <- R6::R6Class( + "DanishPig", + public = list( + `className` = NULL, + `size` = NULL, + `_field_list` = c("className", "size"), + `additional_properties` = list(), + #' Initialize a new DanishPig class. + #' + #' @description + #' Initialize a new DanishPig class. + #' + #' @param className className + #' @param size size + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `size`, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!missing(`size`)) { + stopifnot(is.numeric(`size`), length(`size`) == 1) + self$`size` <- `size` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DanishPig in JSON format + #' @export + toJSON = function() { + DanishPigObject <- list() + if (!is.null(self$`className`)) { + DanishPigObject[["className"]] <- + self$`className` + } + if (!is.null(self$`size`)) { + DanishPigObject[["size"]] <- + self$`size` + } + for (key in names(self$additional_properties)) { + DanishPigObject[[key]] <- self$additional_properties[[key]] + } + + DanishPigObject + }, + #' Deserialize JSON string into an instance of DanishPig + #' + #' @description + #' Deserialize JSON string into an instance of DanishPig + #' + #' @param input_json the JSON input + #' @return the instance of DanishPig + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`size`)) { + self$`size` <- this_object$`size` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DanishPig in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`size`)) { + sprintf( + '"size": + %d + ', + self$`size` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of DanishPig + #' + #' @description + #' Deserialize JSON string into an instance of DanishPig + #' + #' @param input_json the JSON input + #' @return the instance of DanishPig + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`size` <- this_object$`size` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to DanishPig + #' + #' @description + #' Validate JSON input with respect to DanishPig and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for DanishPig: the required field `className` is missing.")) + } + # check the required field `size` + if (!is.null(input_json$`size`)) { + stopifnot(is.numeric(input_json$`size`), length(input_json$`size`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for DanishPig: the required field `size` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of DanishPig + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + # check if the required `size` is null + if (is.null(self$`size`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + # check if the required `size` is null + if (is.null(self$`size`)) { + invalid_fields["size"] <- "Non-nullable required field `size` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# DanishPig$unlock() +# +## Below is an example to define the print fnuction +# DanishPig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# DanishPig$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/date.R b/samples/client/petstore/R-httr2-wrapper/R/date.R new file mode 100644 index 0000000000..a26b7977d4 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/date.R @@ -0,0 +1,288 @@ +#' Create a new Date +#' +#' @description +#' to test the model name `Date` +#' +#' @docType class +#' @title Date +#' @description Date Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field percent_description using \% in the description character [optional] +#' @field url_property character +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Date <- R6::R6Class( + "Date", + public = list( + `className` = NULL, + `percent_description` = NULL, + `url_property` = NULL, + `_field_list` = c("className", "percent_description", "url_property"), + `additional_properties` = list(), + #' Initialize a new Date class. + #' + #' @description + #' Initialize a new Date class. + #' + #' @param className className + #' @param url_property url_property + #' @param percent_description using \% in the description + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `url_property`, `percent_description` = NULL, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!missing(`url_property`)) { + stopifnot(is.character(`url_property`), length(`url_property`) == 1) + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", `url_property`)) + } + self$`url_property` <- `url_property` + } + if (!is.null(`percent_description`)) { + stopifnot(is.character(`percent_description`), length(`percent_description`) == 1) + self$`percent_description` <- `percent_description` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Date in JSON format + #' @export + toJSON = function() { + DateObject <- list() + if (!is.null(self$`className`)) { + DateObject[["className"]] <- + self$`className` + } + if (!is.null(self$`percent_description`)) { + DateObject[["percent_description"]] <- + self$`percent_description` + } + if (!is.null(self$`url_property`)) { + DateObject[["url_property"]] <- + self$`url_property` + } + for (key in names(self$additional_properties)) { + DateObject[[key]] <- self$additional_properties[[key]] + } + + DateObject + }, + #' Deserialize JSON string into an instance of Date + #' + #' @description + #' Deserialize JSON string into an instance of Date + #' + #' @param input_json the JSON input + #' @return the instance of Date + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`percent_description`)) { + self$`percent_description` <- this_object$`percent_description` + } + if (!is.null(this_object$`url_property`)) { + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(this_object$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", this_object$`url_property`)) + } + self$`url_property` <- this_object$`url_property` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Date in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`percent_description`)) { + sprintf( + '"percent_description": + "%s" + ', + self$`percent_description` + ) + }, + if (!is.null(self$`url_property`)) { + sprintf( + '"url_property": + "%s" + ', + self$`url_property` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Date + #' + #' @description + #' Deserialize JSON string into an instance of Date + #' + #' @param input_json the JSON input + #' @return the instance of Date + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`percent_description` <- this_object$`percent_description` + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(this_object$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", this_object$`url_property`)) + } + self$`url_property` <- this_object$`url_property` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Date + #' + #' @description + #' Validate JSON input with respect to Date and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Date: the required field `className` is missing.")) + } + # check the required field `url_property` + if (!is.null(input_json$`url_property`)) { + stopifnot(is.character(input_json$`url_property`), length(input_json$`url_property`) == 1) + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(input_json$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", input_json$`url_property`)) + } + } else { + stop(paste("The JSON input `", input, "` is invalid for Date: the required field `url_property` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Date + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + # check if the required `url_property` is null + if (is.null(self$`url_property`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + # check if the required `url_property` is null + if (is.null(self$`url_property`)) { + invalid_fields["url_property"] <- "Non-nullable required field `url_property` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Date$unlock() +# +## Below is an example to define the print fnuction +# Date$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Date$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/dog.R b/samples/client/petstore/R-httr2-wrapper/R/dog.R new file mode 100644 index 0000000000..67fb8a315e --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/dog.R @@ -0,0 +1,257 @@ +#' Create a new Dog +#' +#' @description +#' Dog Class +#' +#' @docType class +#' @title Dog +#' @description Dog Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field color character [optional] +#' @field breed character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Dog <- R6::R6Class( + "Dog", + inherit = Animal, + public = list( + `className` = NULL, + `color` = NULL, + `breed` = NULL, + `_field_list` = c("className", "color", "breed"), + `additional_properties` = list(), + #' Initialize a new Dog class. + #' + #' @description + #' Initialize a new Dog class. + #' + #' @param className className + #' @param color color. Default to "red". + #' @param breed breed + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `color` = "red", `breed` = NULL, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`color`)) { + stopifnot(is.character(`color`), length(`color`) == 1) + self$`color` <- `color` + } + if (!is.null(`breed`)) { + stopifnot(is.character(`breed`), length(`breed`) == 1) + self$`breed` <- `breed` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Dog in JSON format + #' @export + toJSON = function() { + DogObject <- list() + if (!is.null(self$`className`)) { + DogObject[["className"]] <- + self$`className` + } + if (!is.null(self$`color`)) { + DogObject[["color"]] <- + self$`color` + } + if (!is.null(self$`breed`)) { + DogObject[["breed"]] <- + self$`breed` + } + for (key in names(self$additional_properties)) { + DogObject[[key]] <- self$additional_properties[[key]] + } + + DogObject + }, + #' Deserialize JSON string into an instance of Dog + #' + #' @description + #' Deserialize JSON string into an instance of Dog + #' + #' @param input_json the JSON input + #' @return the instance of Dog + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`color`)) { + self$`color` <- this_object$`color` + } + if (!is.null(this_object$`breed`)) { + self$`breed` <- this_object$`breed` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Dog in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`color`)) { + sprintf( + '"color": + "%s" + ', + self$`color` + ) + }, + if (!is.null(self$`breed`)) { + sprintf( + '"breed": + "%s" + ', + self$`breed` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Dog + #' + #' @description + #' Deserialize JSON string into an instance of Dog + #' + #' @param input_json the JSON input + #' @return the instance of Dog + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`color` <- this_object$`color` + self$`breed` <- this_object$`breed` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Dog + #' + #' @description + #' Validate JSON input with respect to Dog and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Dog: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Dog + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Dog$unlock() +# +## Below is an example to define the print fnuction +# Dog$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Dog$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/dog_all_of.R b/samples/client/petstore/R-httr2-wrapper/R/dog_all_of.R new file mode 100644 index 0000000000..ea44d583d7 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/dog_all_of.R @@ -0,0 +1,194 @@ +#' Create a new DogAllOf +#' +#' @description +#' DogAllOf Class +#' +#' @docType class +#' @title DogAllOf +#' @description DogAllOf Class +#' @format An \code{R6Class} generator object +#' @field breed character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +DogAllOf <- R6::R6Class( + "DogAllOf", + public = list( + `breed` = NULL, + `_field_list` = c("breed"), + `additional_properties` = list(), + #' Initialize a new DogAllOf class. + #' + #' @description + #' Initialize a new DogAllOf class. + #' + #' @param breed breed + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`breed` = NULL, additional_properties = NULL, ...) { + if (!is.null(`breed`)) { + stopifnot(is.character(`breed`), length(`breed`) == 1) + self$`breed` <- `breed` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DogAllOf in JSON format + #' @export + toJSON = function() { + DogAllOfObject <- list() + if (!is.null(self$`breed`)) { + DogAllOfObject[["breed"]] <- + self$`breed` + } + for (key in names(self$additional_properties)) { + DogAllOfObject[[key]] <- self$additional_properties[[key]] + } + + DogAllOfObject + }, + #' Deserialize JSON string into an instance of DogAllOf + #' + #' @description + #' Deserialize JSON string into an instance of DogAllOf + #' + #' @param input_json the JSON input + #' @return the instance of DogAllOf + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`breed`)) { + self$`breed` <- this_object$`breed` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DogAllOf in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`breed`)) { + sprintf( + '"breed": + "%s" + ', + self$`breed` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of DogAllOf + #' + #' @description + #' Deserialize JSON string into an instance of DogAllOf + #' + #' @param input_json the JSON input + #' @return the instance of DogAllOf + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`breed` <- this_object$`breed` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to DogAllOf + #' + #' @description + #' Validate JSON input with respect to DogAllOf and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of DogAllOf + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# DogAllOf$unlock() +# +## Below is an example to define the print fnuction +# DogAllOf$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# DogAllOf$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/fake_api.R b/samples/client/petstore/R-httr2-wrapper/R/fake_api.R new file mode 100644 index 0000000000..73cf0e8c54 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/fake_api.R @@ -0,0 +1,857 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title Fake operations +#' @description FakeApi +#' @format An \code{R6Class} generator object +#' @field api_client Handles the client-server communication. +#' +#' @section Methods: +#' \describe{ +#' \strong{ add_pet_optional } \emph{ Add a new pet to the store (optional body) } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet \link{Pet} +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 405 | Invalid input +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ fake_data_file } \emph{ test data_file to ensure it's escaped correctly } +#' +#' +#' \itemize{ +#' \item \emph{ @param } dummy character +#' \item \emph{ @param } var_data_file character +#' \item \emph{ @returnType } \link{User} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : User +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ fake_path_array } \emph{ test array parameter in path } +#' +#' +#' \itemize{ +#' \item \emph{ @param } path_array list( character ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ fake_regular_expression } \emph{ test regular expression to ensure no exception } +#' +#' +#' \itemize{ +#' \item \emph{ @param } reg_exp_test character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ fake_set_query } \emph{ test set query parameter } +#' +#' +#' \itemize{ +#' \item \emph{ @param } set_dummy list( character ) +#' \item \emph{ @param } array_dummy list( character ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' } +#' +#' +#' @examples +#' \dontrun{ +#' #################### add_pet_optional #################### +#' +#' library(petstore) +#' var_pet <- Pet$new() # Pet | Pet object that needs to be added to the store +#' +#' #Add a new pet to the store (optional body) +#' api_instance <- petstore_api$new() +#' +#' # Configure HTTP basic authorization: http_auth +#' api_instance$api_client$username <- Sys.getenv("USERNAME") +#' api_instance$api_client$password <- Sys.getenv("PASSWORD") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$fake_api$add_pet_optional(pet = var_pet, data_file = "result.txt"), +#' +#' +#' api_instance$fake_api$add_pet_optional(pet = var_pet), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `add_pet_optional`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### fake_data_file #################### +#' +#' library(petstore) +#' var_dummy <- "dummy_example" # character | dummy required parameter +#' var_var_data_file <- "var_data_file_example" # character | header data file +#' +#' #test data_file to ensure it's escaped correctly +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$fake_api$fake_data_file(var_dummy, var_data_file = var_var_data_file, data_file = "result.txt"), +#' +#' +#' api_instance$fake_api$fake_data_file(var_dummy, var_data_file = var_var_data_file), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `fake_data_file`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### fake_path_array #################### +#' +#' library(petstore) +#' var_path_array <- ["path_array_example"] # array[character] | dummy path parameter +#' +#' #test array parameter in path +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' api_instance$fake_api$fake_path_array(var_path_array), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `fake_path_array`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### fake_regular_expression #################### +#' +#' library(petstore) +#' var_reg_exp_test <- "reg_exp_test_example" # character | dummy required parameter +#' +#' #test regular expression to ensure no exception +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' api_instance$fake_api$fake_regular_expression(var_reg_exp_test), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `fake_regular_expression`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### fake_set_query #################### +#' +#' library(petstore) +#' var_set_dummy <- ["set_dummy_example"] # set[character] | set query +#' var_array_dummy <- ["array_dummy_example"] # array[character] | array query +#' +#' #test set query parameter +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' api_instance$fake_api$fake_set_query(var_set_dummy, var_array_dummy), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `fake_set_query`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' } +#' @importFrom R6 R6Class +#' @importFrom base64enc base64encode +#' @importFrom rlang abort +#' @export +FakeApi <- R6::R6Class( + "FakeApi", + public = list( + api_client = NULL, + #' Initialize a new FakeApi. + #' + #' @description + #' Initialize a new FakeApi. + #' + #' @param api_client An instance of API client. + #' @export + initialize = function(api_client) { + if (!missing(api_client)) { + self$api_client <- api_client + } else { + self$api_client <- ApiClient$new() + } + }, + #' Add a new pet to the store (optional body) + #' + #' @description + #' Add a new pet to the store (optional body) + #' + #' @param pet (optional) Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + add_pet_optional = function(pet = NULL, data_file = NULL, ...) { + local_var_response <- self$add_pet_optional_with_http_info(pet, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Add a new pet to the store (optional body) + #' + #' @description + #' Add a new pet to the store (optional body) + #' + #' @param pet (optional) Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + add_pet_optional_with_http_info = function(pet = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + + if (!is.null(`pet`)) { + local_var_body <- `pet`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/fake/test_optional_body_parameter" + # HTTP basic auth + if (!is.null(self$api_client$username) || !is.null(self$api_client$password)) { + header_params["Authorization"] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$api_client$username, self$api_client$password, sep = ":")))) + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json", "application/xml", "multipart/related") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test data_file to ensure it's escaped correctly + #' + #' @description + #' test data_file to ensure it's escaped correctly + #' + #' @param dummy dummy required parameter + #' @param var_data_file (optional) header data file + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return User + #' @export + fake_data_file = function(dummy, var_data_file = NULL, data_file = NULL, ...) { + local_var_response <- self$fake_data_file_with_http_info(dummy, var_data_file, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test data_file to ensure it's escaped correctly + #' + #' @description + #' test data_file to ensure it's escaped correctly + #' + #' @param dummy dummy required parameter + #' @param var_data_file (optional) header data file + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (User) with additional information such as HTTP status code, headers + #' @export + fake_data_file_with_http_info = function(dummy, var_data_file = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`dummy`)) { + rlang::abort(message = "Missing required parameter `dummy`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `dummy`.")) + } + + + + header_params["dummy"] <- `dummy` + + header_params["data_file"] <- `var_data_file` + + local_var_url_path <- "/fake/data_file" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "User", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test array parameter in path + #' + #' @description + #' test array parameter in path + #' + #' @param path_array dummy path parameter + #' @param ... Other optional arguments + #' @return void + #' @export + fake_path_array = function(path_array, ...) { + local_var_response <- self$fake_path_array_with_http_info(path_array, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test array parameter in path + #' + #' @description + #' test array parameter in path + #' + #' @param path_array dummy path parameter + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + fake_path_array_with_http_info = function(path_array, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`path_array`)) { + rlang::abort(message = "Missing required parameter `path_array`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `path_array`.")) + } + + + local_var_url_path <- "/fake/path_array/{path_array}/testing" + if (!missing(`path_array`)) { + local_var_url_path <- gsub("\\{path_array\\}", paste(URLencode(as.character(`path_array`), reserved = TRUE), collapse= ",", sep=""), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test regular expression to ensure no exception + #' + #' @description + #' test regular expression to ensure no exception + #' + #' @param reg_exp_test dummy required parameter + #' @param ... Other optional arguments + #' @return void + #' @export + fake_regular_expression = function(reg_exp_test, ...) { + local_var_response <- self$fake_regular_expression_with_http_info(reg_exp_test, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test regular expression to ensure no exception + #' + #' @description + #' test regular expression to ensure no exception + #' + #' @param reg_exp_test dummy required parameter + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + fake_regular_expression_with_http_info = function(reg_exp_test, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`reg_exp_test`)) { + rlang::abort(message = "Missing required parameter `reg_exp_test`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `reg_exp_test`.")) + } + + if (!str_detect(`reg_exp_test`, "^[A-Za-z0-9_]{1,15}$")) { + rlang::abort(message = "Invalid value for `reg_exp_test` when calling FakeApi$fake_regular_expression, must conform to the pattern ^[A-Za-z0-9_]{1,15}$.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `reg_exp_test` when calling FakeApi$fake_regular_expression, must conform to the pattern ^[A-Za-z0-9_]{1,15}$.")) + } + + header_params["reg_exp_test"] <- `reg_exp_test` + + local_var_url_path <- "/fake/regular_expression" + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test set query parameter + #' + #' @description + #' test set query parameter + #' + #' @param set_dummy set query + #' @param array_dummy array query + #' @param ... Other optional arguments + #' @return void + #' @export + fake_set_query = function(set_dummy, array_dummy, ...) { + local_var_response <- self$fake_set_query_with_http_info(set_dummy, array_dummy, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test set query parameter + #' + #' @description + #' test set query parameter + #' + #' @param set_dummy set query + #' @param array_dummy array query + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + fake_set_query_with_http_info = function(set_dummy, array_dummy, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`set_dummy`)) { + rlang::abort(message = "Missing required parameter `set_dummy`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `set_dummy`.")) + } + + if (missing(`array_dummy`)) { + rlang::abort(message = "Missing required parameter `array_dummy`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `array_dummy`.")) + } + + + + # check if items are unique + if (!identical(`set_dummy`, unique(`set_dummy`))) { + rlang::abort(message = "Invalid value for `set_dummy` when calling FakeApi$fake_set_query. Items must be unique.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `set_dummy` when calling FakeApi$fake_set_query. Items must be unique.")) + } + # explore + for (query_item in `set_dummy`) { + query_params[["set_dummy"]] <- c(query_params[["set_dummy"]], list(`set_dummy` = query_item)) + } + + # explore + for (query_item in `array_dummy`) { + query_params[["array_dummy"]] <- c(query_params[["array_dummy"]], list(`array_dummy` = query_item)) + } + + local_var_url_path <- "/fake/set_query_parameter" + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2-wrapper/R/mammal.R b/samples/client/petstore/R-httr2-wrapper/R/mammal.R new file mode 100644 index 0000000000..8ac1d6829d --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/mammal.R @@ -0,0 +1,223 @@ +#' @docType class +#' @title Mammal +#' +#' @description Mammal Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Mammal <- R6::R6Class( + "Mammal", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("Whale", "Zebra"), + #' Initialize a new Mammal. + #' + #' @description + #' Initialize a new Mammal. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "Whale", "Zebra" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "Whale") { + self$actual_instance <- instance + self$actual_type <- "Whale" + } else if (get(class(instance)[[1]], pos = -1)$classname == "Zebra") { + self$actual_instance <- instance + self$actual_type <- "Zebra" + } else { + stop(paste("Failed to initialize Mammal with oneOf schemas Whale, Zebra. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of Mammal. + #' + #' @description + #' Deserialize JSON string into an instance of Mammal. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of Mammal. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of Mammal. + #' + #' @description + #' Deserialize JSON string into an instance of Mammal. + #' + #' @param input The input JSON. + #' @return An instance of Mammal. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + oneof_lookup_result <- tryCatch({ + discriminatorValue <- (jsonlite::fromJSON(input, simplifyVector = FALSE))$`className` + switch(discriminatorValue, + whale={ + Whale$public_methods$validateJSON(input) + Whale_instance <- Whale$new() + self$actual_instance <- Whale_instance$fromJSON(input) + self$actual_type <- "Whale" + return(self) + }, + zebra={ + Zebra$public_methods$validateJSON(input) + Zebra_instance <- Zebra$new() + self$actual_instance <- Zebra_instance$fromJSON(input) + self$actual_type <- "Zebra" + return(self) + })}, + error = function(err) err + ) + if (!is.null(oneof_lookup_result["error"])) { + error_messages <- append(error_messages, sprintf("Failed to lookup discriminator value for Mammal. Error message: %s. Input: %s", oneof_lookup_result["message"], input)) + } + + Whale_result <- tryCatch({ + Whale$public_methods$validateJSON(input) + Whale_instance <- Whale$new() + instance <- Whale_instance$fromJSON(input) + instance_type <- "Whale" + matched_schemas <- append(matched_schemas, "Whale") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(Whale_result["error"])) { + error_messages <- append(error_messages, Whale_result["message"]) + } + + Zebra_result <- tryCatch({ + Zebra$public_methods$validateJSON(input) + Zebra_instance <- Zebra$new() + instance <- Zebra_instance$fromJSON(input) + instance_type <- "Zebra" + matched_schemas <- append(matched_schemas, "Zebra") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(Zebra_result["error"])) { + error_messages <- append(error_messages, Zebra_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into Mammal with oneOf schemas Whale, Zebra.") + } else { + # no match + stop(paste("No match found when deserializing the payload into Mammal with oneOf schemas Whale, Zebra. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize Mammal to JSON string. + #' + #' @description + #' Serialize Mammal to JSON string. + #' + #' @return JSON string representation of the Mammal. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize Mammal to JSON. + #' + #' @description + #' Serialize Mammal to JSON. + #' + #' @return JSON representation of the Mammal. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to Mammal. + #' + #' @description + #' Validate the input JSON with respect to Mammal and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#Mammal$unlock() +# +## Below is an example to define the print fnuction +#Mammal$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#Mammal$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/model_api_response.R b/samples/client/petstore/R-httr2-wrapper/R/model_api_response.R new file mode 100644 index 0000000000..03059bb522 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/model_api_response.R @@ -0,0 +1,240 @@ +#' Create a new ModelApiResponse +#' +#' @description +#' Describes the result of uploading an image resource +#' +#' @docType class +#' @title ModelApiResponse +#' @description ModelApiResponse Class +#' @format An \code{R6Class} generator object +#' @field code integer [optional] +#' @field type character [optional] +#' @field message character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +ModelApiResponse <- R6::R6Class( + "ModelApiResponse", + public = list( + `code` = NULL, + `type` = NULL, + `message` = NULL, + `_field_list` = c("code", "type", "message"), + `additional_properties` = list(), + #' Initialize a new ModelApiResponse class. + #' + #' @description + #' Initialize a new ModelApiResponse class. + #' + #' @param code code + #' @param type type + #' @param message message + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`code` = NULL, `type` = NULL, `message` = NULL, additional_properties = NULL, ...) { + if (!is.null(`code`)) { + stopifnot(is.numeric(`code`), length(`code`) == 1) + self$`code` <- `code` + } + if (!is.null(`type`)) { + stopifnot(is.character(`type`), length(`type`) == 1) + self$`type` <- `type` + } + if (!is.null(`message`)) { + stopifnot(is.character(`message`), length(`message`) == 1) + self$`message` <- `message` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return ModelApiResponse in JSON format + #' @export + toJSON = function() { + ModelApiResponseObject <- list() + if (!is.null(self$`code`)) { + ModelApiResponseObject[["code"]] <- + self$`code` + } + if (!is.null(self$`type`)) { + ModelApiResponseObject[["type"]] <- + self$`type` + } + if (!is.null(self$`message`)) { + ModelApiResponseObject[["message"]] <- + self$`message` + } + for (key in names(self$additional_properties)) { + ModelApiResponseObject[[key]] <- self$additional_properties[[key]] + } + + ModelApiResponseObject + }, + #' Deserialize JSON string into an instance of ModelApiResponse + #' + #' @description + #' Deserialize JSON string into an instance of ModelApiResponse + #' + #' @param input_json the JSON input + #' @return the instance of ModelApiResponse + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`code`)) { + self$`code` <- this_object$`code` + } + if (!is.null(this_object$`type`)) { + self$`type` <- this_object$`type` + } + if (!is.null(this_object$`message`)) { + self$`message` <- this_object$`message` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return ModelApiResponse in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`code`)) { + sprintf( + '"code": + %d + ', + self$`code` + ) + }, + if (!is.null(self$`type`)) { + sprintf( + '"type": + "%s" + ', + self$`type` + ) + }, + if (!is.null(self$`message`)) { + sprintf( + '"message": + "%s" + ', + self$`message` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of ModelApiResponse + #' + #' @description + #' Deserialize JSON string into an instance of ModelApiResponse + #' + #' @param input_json the JSON input + #' @return the instance of ModelApiResponse + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`code` <- this_object$`code` + self$`type` <- this_object$`type` + self$`message` <- this_object$`message` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to ModelApiResponse + #' + #' @description + #' Validate JSON input with respect to ModelApiResponse and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of ModelApiResponse + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# ModelApiResponse$unlock() +# +## Below is an example to define the print fnuction +# ModelApiResponse$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# ModelApiResponse$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/nested_one_of.R b/samples/client/petstore/R-httr2-wrapper/R/nested_one_of.R new file mode 100644 index 0000000000..68b0db6b37 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/nested_one_of.R @@ -0,0 +1,219 @@ +#' Create a new NestedOneOf +#' +#' @description +#' NestedOneOf Class +#' +#' @docType class +#' @title NestedOneOf +#' @description NestedOneOf Class +#' @format An \code{R6Class} generator object +#' @field size integer [optional] +#' @field nested_pig \link{Pig} [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +NestedOneOf <- R6::R6Class( + "NestedOneOf", + public = list( + `size` = NULL, + `nested_pig` = NULL, + `_field_list` = c("size", "nested_pig"), + `additional_properties` = list(), + #' Initialize a new NestedOneOf class. + #' + #' @description + #' Initialize a new NestedOneOf class. + #' + #' @param size size + #' @param nested_pig nested_pig + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`size` = NULL, `nested_pig` = NULL, additional_properties = NULL, ...) { + if (!is.null(`size`)) { + stopifnot(is.numeric(`size`), length(`size`) == 1) + self$`size` <- `size` + } + if (!is.null(`nested_pig`)) { + stopifnot(R6::is.R6(`nested_pig`)) + self$`nested_pig` <- `nested_pig` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return NestedOneOf in JSON format + #' @export + toJSON = function() { + NestedOneOfObject <- list() + if (!is.null(self$`size`)) { + NestedOneOfObject[["size"]] <- + self$`size` + } + if (!is.null(self$`nested_pig`)) { + NestedOneOfObject[["nested_pig"]] <- + self$`nested_pig`$toJSON() + } + for (key in names(self$additional_properties)) { + NestedOneOfObject[[key]] <- self$additional_properties[[key]] + } + + NestedOneOfObject + }, + #' Deserialize JSON string into an instance of NestedOneOf + #' + #' @description + #' Deserialize JSON string into an instance of NestedOneOf + #' + #' @param input_json the JSON input + #' @return the instance of NestedOneOf + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`size`)) { + self$`size` <- this_object$`size` + } + if (!is.null(this_object$`nested_pig`)) { + nested_pig_object <- Pig$new() + nested_pig_object$fromJSON(jsonlite::toJSON(this_object$nested_pig, auto_unbox = TRUE, digits = NA)) + self$`nested_pig` <- nested_pig_object + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return NestedOneOf in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`size`)) { + sprintf( + '"size": + %d + ', + self$`size` + ) + }, + if (!is.null(self$`nested_pig`)) { + sprintf( + '"nested_pig": + %s + ', + jsonlite::toJSON(self$`nested_pig`$toJSON(), auto_unbox = TRUE, digits = NA) + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of NestedOneOf + #' + #' @description + #' Deserialize JSON string into an instance of NestedOneOf + #' + #' @param input_json the JSON input + #' @return the instance of NestedOneOf + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`size` <- this_object$`size` + self$`nested_pig` <- Pig$new()$fromJSON(jsonlite::toJSON(this_object$nested_pig, auto_unbox = TRUE, digits = NA)) + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to NestedOneOf + #' + #' @description + #' Validate JSON input with respect to NestedOneOf and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of NestedOneOf + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# NestedOneOf$unlock() +# +## Below is an example to define the print fnuction +# NestedOneOf$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# NestedOneOf$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/one_of_primitive_type_test.R b/samples/client/petstore/R-httr2-wrapper/R/one_of_primitive_type_test.R new file mode 100644 index 0000000000..d558c0eb50 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/one_of_primitive_type_test.R @@ -0,0 +1,202 @@ +#' @docType class +#' @title OneOfPrimitiveTypeTest +#' +#' @description OneOfPrimitiveTypeTest Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +OneOfPrimitiveTypeTest <- R6::R6Class( + "OneOfPrimitiveTypeTest", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("character", "integer"), + #' Initialize a new OneOfPrimitiveTypeTest. + #' + #' @description + #' Initialize a new OneOfPrimitiveTypeTest. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "character", "integer" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "character") { + self$actual_instance <- instance + self$actual_type <- "character" + } else if (get(class(instance)[[1]], pos = -1)$classname == "integer") { + self$actual_instance <- instance + self$actual_type <- "integer" + } else { + stop(paste("Failed to initialize OneOfPrimitiveTypeTest with oneOf schemas character, integer. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of OneOfPrimitiveTypeTest. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' + #' @param input The input JSON. + #' @return An instance of OneOfPrimitiveTypeTest. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + integer_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "integer") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "integer", typeof(instance))) + } + instance_type <- "integer" + matched_schemas <- append(matched_schemas, "integer") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(integer_result["error"])) { + error_messages <- append(error_messages, integer_result["message"]) + } + + character_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "character") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "character", typeof(instance))) + } + instance_type <- "character" + matched_schemas <- append(matched_schemas, "character") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(character_result["error"])) { + error_messages <- append(error_messages, character_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into OneOfPrimitiveTypeTest with oneOf schemas character, integer.") + } else { + # no match + stop(paste("No match found when deserializing the payload into OneOfPrimitiveTypeTest with oneOf schemas character, integer. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize OneOfPrimitiveTypeTest to JSON string. + #' + #' @description + #' Serialize OneOfPrimitiveTypeTest to JSON string. + #' + #' @return JSON string representation of the OneOfPrimitiveTypeTest. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize OneOfPrimitiveTypeTest to JSON. + #' + #' @description + #' Serialize OneOfPrimitiveTypeTest to JSON. + #' + #' @return JSON representation of the OneOfPrimitiveTypeTest. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to OneOfPrimitiveTypeTest. + #' + #' @description + #' Validate the input JSON with respect to OneOfPrimitiveTypeTest and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#OneOfPrimitiveTypeTest$unlock() +# +## Below is an example to define the print fnuction +#OneOfPrimitiveTypeTest$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#OneOfPrimitiveTypeTest$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/order.R b/samples/client/petstore/R-httr2-wrapper/R/order.R new file mode 100644 index 0000000000..6f43799918 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/order.R @@ -0,0 +1,318 @@ +#' Create a new Order +#' +#' @description +#' An order for a pets from the pet store +#' +#' @docType class +#' @title Order +#' @description Order Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field petId integer [optional] +#' @field quantity integer [optional] +#' @field shipDate character [optional] +#' @field status Order Status character [optional] +#' @field complete character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Order <- R6::R6Class( + "Order", + public = list( + `id` = NULL, + `petId` = NULL, + `quantity` = NULL, + `shipDate` = NULL, + `status` = NULL, + `complete` = NULL, + `_field_list` = c("id", "petId", "quantity", "shipDate", "status", "complete"), + `additional_properties` = list(), + #' Initialize a new Order class. + #' + #' @description + #' Initialize a new Order class. + #' + #' @param id id + #' @param petId petId + #' @param quantity quantity + #' @param shipDate shipDate + #' @param status Order Status + #' @param complete complete. Default to FALSE. + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `petId` = NULL, `quantity` = NULL, `shipDate` = NULL, `status` = NULL, `complete` = FALSE, additional_properties = NULL, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`petId`)) { + stopifnot(is.numeric(`petId`), length(`petId`) == 1) + self$`petId` <- `petId` + } + if (!is.null(`quantity`)) { + stopifnot(is.numeric(`quantity`), length(`quantity`) == 1) + self$`quantity` <- `quantity` + } + if (!is.null(`shipDate`)) { + stopifnot(is.character(`shipDate`), length(`shipDate`) == 1) + self$`shipDate` <- `shipDate` + } + if (!is.null(`status`)) { + if (!(`status` %in% c("placed", "approved", "delivered"))) { + stop(paste("Error! \"", `status`, "\" cannot be assigned to `status`. Must be \"placed\", \"approved\", \"delivered\".", sep = "")) + } + stopifnot(is.character(`status`), length(`status`) == 1) + self$`status` <- `status` + } + if (!is.null(`complete`)) { + stopifnot(is.logical(`complete`), length(`complete`) == 1) + self$`complete` <- `complete` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Order in JSON format + #' @export + toJSON = function() { + OrderObject <- list() + if (!is.null(self$`id`)) { + OrderObject[["id"]] <- + self$`id` + } + if (!is.null(self$`petId`)) { + OrderObject[["petId"]] <- + self$`petId` + } + if (!is.null(self$`quantity`)) { + OrderObject[["quantity"]] <- + self$`quantity` + } + if (!is.null(self$`shipDate`)) { + OrderObject[["shipDate"]] <- + self$`shipDate` + } + if (!is.null(self$`status`)) { + OrderObject[["status"]] <- + self$`status` + } + if (!is.null(self$`complete`)) { + OrderObject[["complete"]] <- + self$`complete` + } + for (key in names(self$additional_properties)) { + OrderObject[[key]] <- self$additional_properties[[key]] + } + + OrderObject + }, + #' Deserialize JSON string into an instance of Order + #' + #' @description + #' Deserialize JSON string into an instance of Order + #' + #' @param input_json the JSON input + #' @return the instance of Order + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`petId`)) { + self$`petId` <- this_object$`petId` + } + if (!is.null(this_object$`quantity`)) { + self$`quantity` <- this_object$`quantity` + } + if (!is.null(this_object$`shipDate`)) { + self$`shipDate` <- this_object$`shipDate` + } + if (!is.null(this_object$`status`)) { + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("placed", "approved", "delivered"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"placed\", \"approved\", \"delivered\".", sep = "")) + } + self$`status` <- this_object$`status` + } + if (!is.null(this_object$`complete`)) { + self$`complete` <- this_object$`complete` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Order in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`petId`)) { + sprintf( + '"petId": + %d + ', + self$`petId` + ) + }, + if (!is.null(self$`quantity`)) { + sprintf( + '"quantity": + %d + ', + self$`quantity` + ) + }, + if (!is.null(self$`shipDate`)) { + sprintf( + '"shipDate": + "%s" + ', + self$`shipDate` + ) + }, + if (!is.null(self$`status`)) { + sprintf( + '"status": + "%s" + ', + self$`status` + ) + }, + if (!is.null(self$`complete`)) { + sprintf( + '"complete": + %s + ', + tolower(self$`complete`) + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Order + #' + #' @description + #' Deserialize JSON string into an instance of Order + #' + #' @param input_json the JSON input + #' @return the instance of Order + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`petId` <- this_object$`petId` + self$`quantity` <- this_object$`quantity` + self$`shipDate` <- this_object$`shipDate` + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("placed", "approved", "delivered"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"placed\", \"approved\", \"delivered\".", sep = "")) + } + self$`status` <- this_object$`status` + self$`complete` <- this_object$`complete` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Order + #' + #' @description + #' Validate JSON input with respect to Order and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Order + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Order$unlock() +# +## Below is an example to define the print fnuction +# Order$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Order$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/pet.R b/samples/client/petstore/R-httr2-wrapper/R/pet.R new file mode 100644 index 0000000000..63318448c0 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/pet.R @@ -0,0 +1,355 @@ +#' Create a new Pet +#' +#' @description +#' A pet for sale in the pet store +#' +#' @docType class +#' @title Pet +#' @description Pet Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field category \link{Category} [optional] +#' @field name character +#' @field photoUrls list(character) +#' @field tags list(\link{Tag}) [optional] +#' @field status pet status in the store character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Pet <- R6::R6Class( + "Pet", + public = list( + `id` = NULL, + `category` = NULL, + `name` = NULL, + `photoUrls` = NULL, + `tags` = NULL, + `status` = NULL, + `_field_list` = c("id", "category", "name", "photoUrls", "tags", "status"), + `additional_properties` = list(), + #' Initialize a new Pet class. + #' + #' @description + #' Initialize a new Pet class. + #' + #' @param name name + #' @param photoUrls photoUrls + #' @param id id + #' @param category category + #' @param tags tags + #' @param status pet status in the store + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`name`, `photoUrls`, `id` = NULL, `category` = NULL, `tags` = NULL, `status` = NULL, additional_properties = NULL, ...) { + if (!missing(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + if (!missing(`photoUrls`)) { + stopifnot(is.vector(`photoUrls`), length(`photoUrls`) != 0) + sapply(`photoUrls`, function(x) stopifnot(is.character(x))) + self$`photoUrls` <- `photoUrls` + } + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`category`)) { + stopifnot(R6::is.R6(`category`)) + self$`category` <- `category` + } + if (!is.null(`tags`)) { + stopifnot(is.vector(`tags`), length(`tags`) != 0) + sapply(`tags`, function(x) stopifnot(R6::is.R6(x))) + self$`tags` <- `tags` + } + if (!is.null(`status`)) { + if (!(`status` %in% c("available", "pending", "sold"))) { + stop(paste("Error! \"", `status`, "\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".", sep = "")) + } + stopifnot(is.character(`status`), length(`status`) == 1) + self$`status` <- `status` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Pet in JSON format + #' @export + toJSON = function() { + PetObject <- list() + if (!is.null(self$`id`)) { + PetObject[["id"]] <- + self$`id` + } + if (!is.null(self$`category`)) { + PetObject[["category"]] <- + self$`category`$toJSON() + } + if (!is.null(self$`name`)) { + PetObject[["name"]] <- + self$`name` + } + if (!is.null(self$`photoUrls`)) { + PetObject[["photoUrls"]] <- + self$`photoUrls` + } + if (!is.null(self$`tags`)) { + PetObject[["tags"]] <- + lapply(self$`tags`, function(x) x$toJSON()) + } + if (!is.null(self$`status`)) { + PetObject[["status"]] <- + self$`status` + } + for (key in names(self$additional_properties)) { + PetObject[[key]] <- self$additional_properties[[key]] + } + + PetObject + }, + #' Deserialize JSON string into an instance of Pet + #' + #' @description + #' Deserialize JSON string into an instance of Pet + #' + #' @param input_json the JSON input + #' @return the instance of Pet + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`category`)) { + category_object <- Category$new() + category_object$fromJSON(jsonlite::toJSON(this_object$category, auto_unbox = TRUE, digits = NA)) + self$`category` <- category_object + } + if (!is.null(this_object$`name`)) { + self$`name` <- this_object$`name` + } + if (!is.null(this_object$`photoUrls`)) { + self$`photoUrls` <- ApiClient$new()$deserializeObj(this_object$`photoUrls`, "array[character]", loadNamespace("petstore")) + } + if (!is.null(this_object$`tags`)) { + self$`tags` <- ApiClient$new()$deserializeObj(this_object$`tags`, "array[Tag]", loadNamespace("petstore")) + } + if (!is.null(this_object$`status`)) { + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("available", "pending", "sold"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".", sep = "")) + } + self$`status` <- this_object$`status` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Pet in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`category`)) { + sprintf( + '"category": + %s + ', + jsonlite::toJSON(self$`category`$toJSON(), auto_unbox = TRUE, digits = NA) + ) + }, + if (!is.null(self$`name`)) { + sprintf( + '"name": + "%s" + ', + self$`name` + ) + }, + if (!is.null(self$`photoUrls`)) { + sprintf( + '"photoUrls": + [%s] + ', + paste(unlist(lapply(self$`photoUrls`, function(x) paste0('"', x, '"'))), collapse = ",") + ) + }, + if (!is.null(self$`tags`)) { + sprintf( + '"tags": + [%s] +', + paste(sapply(self$`tags`, function(x) jsonlite::toJSON(x$toJSON(), auto_unbox = TRUE, digits = NA)), collapse = ",") + ) + }, + if (!is.null(self$`status`)) { + sprintf( + '"status": + "%s" + ', + self$`status` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Pet + #' + #' @description + #' Deserialize JSON string into an instance of Pet + #' + #' @param input_json the JSON input + #' @return the instance of Pet + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`category` <- Category$new()$fromJSON(jsonlite::toJSON(this_object$category, auto_unbox = TRUE, digits = NA)) + self$`name` <- this_object$`name` + self$`photoUrls` <- ApiClient$new()$deserializeObj(this_object$`photoUrls`, "array[character]", loadNamespace("petstore")) + self$`tags` <- ApiClient$new()$deserializeObj(this_object$`tags`, "array[Tag]", loadNamespace("petstore")) + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("available", "pending", "sold"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".", sep = "")) + } + self$`status` <- this_object$`status` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Pet + #' + #' @description + #' Validate JSON input with respect to Pet and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `name` + if (!is.null(input_json$`name`)) { + stopifnot(is.character(input_json$`name`), length(input_json$`name`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Pet: the required field `name` is missing.")) + } + # check the required field `photoUrls` + if (!is.null(input_json$`photoUrls`)) { + stopifnot(is.vector(input_json$`photoUrls`), length(input_json$`photoUrls`) != 0) + tmp <- sapply(input_json$`photoUrls`, function(x) stopifnot(is.character(x))) + } else { + stop(paste("The JSON input `", input, "` is invalid for Pet: the required field `photoUrls` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Pet + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `name` is null + if (is.null(self$`name`)) { + return(FALSE) + } + + # check if the required `photoUrls` is null + if (is.null(self$`photoUrls`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `name` is null + if (is.null(self$`name`)) { + invalid_fields["name"] <- "Non-nullable required field `name` cannot be null." + } + + # check if the required `photoUrls` is null + if (is.null(self$`photoUrls`)) { + invalid_fields["photoUrls"] <- "Non-nullable required field `photoUrls` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Pet$unlock() +# +## Below is an example to define the print fnuction +# Pet$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Pet$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/pet_api.R b/samples/client/petstore/R-httr2-wrapper/R/pet_api.R new file mode 100644 index 0000000000..837c4c3d5d --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/pet_api.R @@ -0,0 +1,1882 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title Pet operations +#' @description PetApi +#' @format An \code{R6Class} generator object +#' @field api_client Handles the client-server communication. +#' +#' @section Methods: +#' \describe{ +#' \strong{ add_pet } \emph{ Add a new pet to the store } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet \link{Pet} +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 405 | Invalid input +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ delete_pet } \emph{ Deletes a pet } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @param } api_key character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 400 | Invalid pet value +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ find_pets_by_status } \emph{ Finds Pets by status } +#' Multiple status values can be provided with comma separated strings +#' +#' \itemize{ +#' \item \emph{ @param } status Enum < [available, pending, sold] > +#' \item \emph{ @returnType } list( \link{Pet} ) \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : array[Pet] +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid status value +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ find_pets_by_tags } \emph{ Finds Pets by tags } +#' Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +#' +#' \itemize{ +#' \item \emph{ @param } tags list( character ) +#' \item \emph{ @returnType } list( \link{Pet} ) \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : array[Pet] +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid tag value +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_pet_by_id } \emph{ Find pet by ID } +#' Returns a single pet +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Pet not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_pet_by_id_streaming } \emph{ Find pet by ID (streaming) } +#' Returns a single pet +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Pet not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ test_header } \emph{ Header test } +#' Header test +#' +#' \itemize{ +#' \item \emph{ @param } header_test_int integer +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Pet not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ update_pet } \emph{ Update an existing pet } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet \link{Pet} +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Pet not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 405 | Validation exception +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ update_pet_with_form } \emph{ Updates a pet in the store with form data } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @param } name character +#' \item \emph{ @param } status character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 405 | Invalid input +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ upload_file } \emph{ uploads an image } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @param } additional_metadata character +#' \item \emph{ @param } file data.frame +#' \item \emph{ @returnType } \link{ModelApiResponse} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : ModelApiResponse +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' } +#' +#' +#' @examples +#' \dontrun{ +#' #################### add_pet #################### +#' +#' library(petstore) +#' var_pet <- Pet$new() # Pet | Pet object that needs to be added to the store +#' +#' #Add a new pet to the store +#' api_instance <- petstore_api$new() +#' +#' # Configure HTTP basic authorization: http_auth +#' api_instance$api_client$username <- Sys.getenv("USERNAME") +#' api_instance$api_client$password <- Sys.getenv("PASSWORD") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$pet_api$add_pet(var_pet, data_file = "result.txt"), +#' +#' +#' api_instance$pet_api$add_pet(var_pet), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `add_pet`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### delete_pet #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | Pet id to delete +#' var_api_key <- "api_key_example" # character | +#' +#' #Deletes a pet +#' api_instance <- petstore_api$new() +#' +#' # Configure OAuth2 access token for authorization: petstore_auth +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +#' +#' result <- tryCatch( +#' +#' api_instance$pet_api$delete_pet(var_pet_id, api_key = var_api_key), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `delete_pet`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### find_pets_by_status #################### +#' +#' library(petstore) +#' var_status <- ["status_example"] # array[character] | Status values that need to be considered for filter +#' +#' #Finds Pets by status +#' api_instance <- petstore_api$new() +#' +#' # Configure OAuth2 access token for authorization: petstore_auth +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$pet_api$find_pets_by_status(var_status, data_file = "result.txt"), +#' +#' +#' api_instance$pet_api$find_pets_by_status(var_status), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `find_pets_by_status`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### find_pets_by_tags #################### +#' +#' library(petstore) +#' var_tags <- ["tags_example"] # array[character] | Tags to filter by +#' +#' #Finds Pets by tags +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$pet_api$find_pets_by_tags(var_tags, data_file = "result.txt"), +#' +#' +#' api_instance$pet_api$find_pets_by_tags(var_tags), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `find_pets_by_tags`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### get_pet_by_id #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | ID of pet to return +#' +#' #Find pet by ID +#' api_instance <- petstore_api$new() +#' +#' # Configure HTTP bearer authorization: BearerToken +#' api_instance$api_client$bearer_token <- Sys.getenv("BEARER_TOKEN") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$pet_api$get_pet_by_id(var_pet_id, data_file = "result.txt"), +#' +#' +#' api_instance$pet_api$get_pet_by_id(var_pet_id), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_pet_by_id`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### get_pet_by_id_streaming #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | ID of pet to return +#' +#' #Find pet by ID (streaming) +#' api_instance <- petstore_api$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$pet_api$get_pet_by_id_streaming(var_pet_id, data_file = "result.txt"), +#' +#' # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. +#' # api_instance$pet_api$get_pet_by_id_streaming(var_pet_id, stream_callback = function(x){ print(length(x)) }), +#' +#' +#' api_instance$pet_api$get_pet_by_id_streaming(var_pet_id), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_pet_by_id_streaming`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### test_header #################### +#' +#' library(petstore) +#' var_header_test_int <- 56 # integer | header test int +#' +#' #Header test +#' api_instance <- petstore_api$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$pet_api$test_header(var_header_test_int, data_file = "result.txt"), +#' +#' # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. +#' # api_instance$pet_api$test_header(var_header_test_int, stream_callback = function(x){ print(length(x)) }), +#' +#' +#' api_instance$pet_api$test_header(var_header_test_int), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `test_header`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### update_pet #################### +#' +#' library(petstore) +#' var_pet <- Pet$new() # Pet | Pet object that needs to be added to the store +#' +#' #Update an existing pet +#' api_instance <- petstore_api$new() +#' +#' # Configure OAuth2 access token for authorization: petstore_auth +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$pet_api$update_pet(var_pet, data_file = "result.txt"), +#' +#' +#' api_instance$pet_api$update_pet(var_pet), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `update_pet`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### update_pet_with_form #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | ID of pet that needs to be updated +#' var_name <- "name_example" # character | Updated name of the pet +#' var_status <- "status_example" # character | Updated status of the pet +#' +#' #Updates a pet in the store with form data +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' api_instance$pet_api$update_pet_with_form(var_pet_id, name = var_name, status = var_status), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `update_pet_with_form`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### upload_file #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | ID of pet to update +#' var_additional_metadata <- "additional_metadata_example" # character | Additional data to pass to server +#' var_file <- File.new('/path/to/file') # data.frame | file to upload +#' +#' #uploads an image +#' api_instance <- petstore_api$new() +#' +#' # Configure OAuth2 access token for authorization: petstore_auth +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$pet_api$upload_file(var_pet_id, additional_metadata = var_additional_metadata, file = var_file, data_file = "result.txt"), +#' +#' +#' api_instance$pet_api$upload_file(var_pet_id, additional_metadata = var_additional_metadata, file = var_file), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `upload_file`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' } +#' @importFrom R6 R6Class +#' @importFrom base64enc base64encode +#' @importFrom rlang abort +#' @export +PetApi <- R6::R6Class( + "PetApi", + public = list( + api_client = NULL, + #' Initialize a new PetApi. + #' + #' @description + #' Initialize a new PetApi. + #' + #' @param api_client An instance of API client. + #' @export + initialize = function(api_client) { + if (!missing(api_client)) { + self$api_client <- api_client + } else { + self$api_client <- ApiClient$new() + } + }, + #' Add a new pet to the store + #' + #' @description + #' Add a new pet to the store + #' + #' @param pet Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + add_pet = function(pet, data_file = NULL, ...) { + local_var_response <- self$add_pet_with_http_info(pet, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Add a new pet to the store + #' + #' @description + #' Add a new pet to the store + #' + #' @param pet Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + add_pet_with_http_info = function(pet, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet`)) { + rlang::abort(message = "Missing required parameter `pet`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet`.")) + } + + + if (!is.null(`pet`)) { + local_var_body <- `pet`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/pet" + # HTTP basic auth + if (!is.null(self$api_client$username) || !is.null(self$api_client$password)) { + header_params["Authorization"] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$api_client$username, self$api_client$password, sep = ":")))) + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json", "application/xml", "multipart/related") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Deletes a pet + #' + #' @description + #' Deletes a pet + #' + #' @param pet_id Pet id to delete + #' @param api_key (optional) No description + #' @param ... Other optional arguments + #' @return void + #' @export + delete_pet = function(pet_id, api_key = NULL, ...) { + local_var_response <- self$delete_pet_with_http_info(pet_id, api_key, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Deletes a pet + #' + #' @description + #' Deletes a pet + #' + #' @param pet_id Pet id to delete + #' @param api_key (optional) No description + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + delete_pet_with_http_info = function(pet_id, api_key = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + + header_params["api_key"] <- `api_key` + + local_var_url_path <- "/pet/{petId}" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "write:pets read:pets" + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "DELETE", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Finds Pets by status + #' + #' @description + #' Finds Pets by status + #' + #' @param status Status values that need to be considered for filter + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return array[Pet] + #' @export + find_pets_by_status = function(status, data_file = NULL, ...) { + local_var_response <- self$find_pets_by_status_with_http_info(status, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Finds Pets by status + #' + #' @description + #' Finds Pets by status + #' + #' @param status Status values that need to be considered for filter + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (array[Pet]) with additional information such as HTTP status code, headers + #' @export + find_pets_by_status_with_http_info = function(status, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`status`)) { + rlang::abort(message = "Missing required parameter `status`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `status`.")) + } + + + # explore + for (query_item in `status`) { + # validate enum values + if (!(query_item %in% c("available", "pending", "sold"))) { + rlang::abort(message = "Invalid value for `status` when calling PetApi$find_pets_by_status. Must be [available, pending, sold].", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `status` when calling PetApi$find_pets_by_status. Must be [available, pending, sold].")) + } + query_params[["status"]] <- c(query_params[["status"]], list(`status` = query_item)) + } + + local_var_url_path <- "/pet/findByStatus" + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "read:pets" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "array[Pet]", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Finds Pets by tags + #' + #' @description + #' Finds Pets by tags + #' + #' @param tags Tags to filter by + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return array[Pet] + #' @export + find_pets_by_tags = function(tags, data_file = NULL, ...) { + local_var_response <- self$find_pets_by_tags_with_http_info(tags, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Finds Pets by tags + #' + #' @description + #' Finds Pets by tags + #' + #' @param tags Tags to filter by + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (array[Pet]) with additional information such as HTTP status code, headers + #' @export + find_pets_by_tags_with_http_info = function(tags, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`tags`)) { + rlang::abort(message = "Missing required parameter `tags`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `tags`.")) + } + + + # no explore + query_params[["tags"]] <- I(paste(lapply(`tags`, URLencode, reserved = TRUE), collapse = ",")) + + local_var_url_path <- "/pet/findByTags" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "array[Pet]", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Find pet by ID + #' + #' @description + #' Find pet by ID + #' + #' @param pet_id ID of pet to return + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + get_pet_by_id = function(pet_id, data_file = NULL, ...) { + local_var_response <- self$get_pet_by_id_with_http_info(pet_id, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Find pet by ID + #' + #' @description + #' Find pet by ID + #' + #' @param pet_id ID of pet to return + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + get_pet_by_id_with_http_info = function(pet_id, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + local_var_url_path <- "/pet/{petId}" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + # Bearer token + if (!is.null(self$api_client$bearer_token)) { + header_params["Authorization"] <- paste("Bearer", self$api_client$bearer_token, sep = " ") + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Find pet by ID (streaming) + #' + #' @description + #' Find pet by ID (streaming) + #' + #' @param pet_id ID of pet to return + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + get_pet_by_id_streaming = function(pet_id, stream_callback = NULL, data_file = NULL, ...) { + local_var_response <- self$get_pet_by_id_streaming_with_http_info(pet_id, stream_callback = stream_callback, data_file = data_file, ...) + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Find pet by ID (streaming) + #' + #' @description + #' Find pet by ID (streaming) + #' + #' @param pet_id ID of pet to return + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + get_pet_by_id_streaming_with_http_info = function(pet_id, stream_callback = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + local_var_url_path <- "/pet/{petId}?streaming" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + stream_callback = stream_callback, + ...) + + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Header test + #' + #' @description + #' Header test + #' + #' @param header_test_int header test int + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + test_header = function(header_test_int, stream_callback = NULL, data_file = NULL, ...) { + local_var_response <- self$test_header_with_http_info(header_test_int, stream_callback = stream_callback, data_file = data_file, ...) + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Header test + #' + #' @description + #' Header test + #' + #' @param header_test_int header test int + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + test_header_with_http_info = function(header_test_int, stream_callback = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`header_test_int`)) { + rlang::abort(message = "Missing required parameter `header_test_int`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `header_test_int`.")) + } + + + header_params["header_test_int"] <- `header_test_int` + + local_var_url_path <- "/pet_header_test" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + stream_callback = stream_callback, + ...) + + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Update an existing pet + #' + #' @description + #' Update an existing pet + #' + #' @param pet Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + update_pet = function(pet, data_file = NULL, ...) { + local_var_response <- self$update_pet_with_http_info(pet, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Update an existing pet + #' + #' @description + #' Update an existing pet + #' + #' @param pet Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + update_pet_with_http_info = function(pet, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet`)) { + rlang::abort(message = "Missing required parameter `pet`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet`.")) + } + + + if (!is.null(`pet`)) { + local_var_body <- `pet`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/pet" + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "write:pets read:pets" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json", "application/xml", "multipart/related") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "PUT", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Updates a pet in the store with form data + #' + #' @description + #' Updates a pet in the store with form data + #' + #' @param pet_id ID of pet that needs to be updated + #' @param name (optional) Updated name of the pet + #' @param status (optional) Updated status of the pet + #' @param ... Other optional arguments + #' @return void + #' @export + update_pet_with_form = function(pet_id, name = NULL, status = NULL, ...) { + local_var_response <- self$update_pet_with_form_with_http_info(pet_id, name, status, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Updates a pet in the store with form data + #' + #' @description + #' Updates a pet in the store with form data + #' + #' @param pet_id ID of pet that needs to be updated + #' @param name (optional) Updated name of the pet + #' @param status (optional) Updated status of the pet + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + update_pet_with_form_with_http_info = function(pet_id, name = NULL, status = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + + + form_params["name"] <- `name` + form_params["status"] <- `status` + local_var_url_path <- "/pet/{petId}" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/x-www-form-urlencoded") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' uploads an image + #' + #' @description + #' uploads an image + #' + #' @param pet_id ID of pet to update + #' @param additional_metadata (optional) Additional data to pass to server + #' @param file (optional) file to upload + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return ModelApiResponse + #' @export + upload_file = function(pet_id, additional_metadata = NULL, file = NULL, data_file = NULL, ...) { + local_var_response <- self$upload_file_with_http_info(pet_id, additional_metadata, file, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' uploads an image + #' + #' @description + #' uploads an image + #' + #' @param pet_id ID of pet to update + #' @param additional_metadata (optional) Additional data to pass to server + #' @param file (optional) file to upload + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (ModelApiResponse) with additional information such as HTTP status code, headers + #' @export + upload_file_with_http_info = function(pet_id, additional_metadata = NULL, file = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + + + form_params["additionalMetadata"] <- `additional_metadata` + file_params["file"] <- curl::form_file(`file`) + local_var_url_path <- "/pet/{petId}/uploadImage" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "write:pets read:pets" + + # The Accept request HTTP header + local_var_accepts <- list("application/json") + + # The Content-Type representation header + local_var_content_types <- list("multipart/form-data") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "ModelApiResponse", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2-wrapper/R/petstore_api.R b/samples/client/petstore/R-httr2-wrapper/R/petstore_api.R new file mode 100644 index 0000000000..f2ea0d2498 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/petstore_api.R @@ -0,0 +1,59 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' petstore API Class +#' +#' A single point of access to the petstore API. +#' +#' NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +#' Ref: https://openapi-generator.tech +#' Do not edit the class manually. +#' +#' @docType class +#' @title ApiClient +#' @description ApiClient Class +#' @format An \code{R6Class} generator object +#' @field api_client API client +#' @field fake_api an instance of FakeApi +#' @field pet_api an instance of PetApi +#' @field store_api an instance of StoreApi +#' @field user_api an instance of UserApi +#' @importFrom rlang abort +#' @export +petstore_api <- R6::R6Class( + "petstore_api", + public = list( + api_client = NULL, + fake_api = NULL, + pet_api = NULL, + store_api = NULL, + user_api = NULL, + #' Initialize a new petstore API Class. + #' + #' @description + #' Initialize a new petstore API Class. + #' + #' @param api_client An instance of API client (optional). + #' @export + initialize = function(api_client) { + if (missing(api_client)) { + self$api_client <- ApiClient$new() + } else { + self$api_client <- api_client + } + + self$fake_api <- FakeApi$new(self$api_client) + + self$pet_api <- PetApi$new(self$api_client) + + self$store_api <- StoreApi$new(self$api_client) + + self$user_api <- UserApi$new(self$api_client) + + } + ) +) diff --git a/samples/client/petstore/R-httr2-wrapper/R/pig.R b/samples/client/petstore/R-httr2-wrapper/R/pig.R new file mode 100644 index 0000000000..0a95e9dec7 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/pig.R @@ -0,0 +1,223 @@ +#' @docType class +#' @title Pig +#' +#' @description Pig Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Pig <- R6::R6Class( + "Pig", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("BasquePig", "DanishPig"), + #' Initialize a new Pig. + #' + #' @description + #' Initialize a new Pig. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "BasquePig", "DanishPig" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "BasquePig") { + self$actual_instance <- instance + self$actual_type <- "BasquePig" + } else if (get(class(instance)[[1]], pos = -1)$classname == "DanishPig") { + self$actual_instance <- instance + self$actual_type <- "DanishPig" + } else { + stop(paste("Failed to initialize Pig with oneOf schemas BasquePig, DanishPig. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of Pig. + #' + #' @description + #' Deserialize JSON string into an instance of Pig. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of Pig. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of Pig. + #' + #' @description + #' Deserialize JSON string into an instance of Pig. + #' + #' @param input The input JSON. + #' @return An instance of Pig. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + oneof_lookup_result <- tryCatch({ + discriminatorValue <- (jsonlite::fromJSON(input, simplifyVector = FALSE))$`className` + switch(discriminatorValue, + BasquePig={ + BasquePig$public_methods$validateJSON(input) + BasquePig_instance <- BasquePig$new() + self$actual_instance <- BasquePig_instance$fromJSON(input) + self$actual_type <- "BasquePig" + return(self) + }, + DanishPig={ + DanishPig$public_methods$validateJSON(input) + DanishPig_instance <- DanishPig$new() + self$actual_instance <- DanishPig_instance$fromJSON(input) + self$actual_type <- "DanishPig" + return(self) + })}, + error = function(err) err + ) + if (!is.null(oneof_lookup_result["error"])) { + error_messages <- append(error_messages, sprintf("Failed to lookup discriminator value for Pig. Error message: %s. Input: %s", oneof_lookup_result["message"], input)) + } + + BasquePig_result <- tryCatch({ + BasquePig$public_methods$validateJSON(input) + BasquePig_instance <- BasquePig$new() + instance <- BasquePig_instance$fromJSON(input) + instance_type <- "BasquePig" + matched_schemas <- append(matched_schemas, "BasquePig") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(BasquePig_result["error"])) { + error_messages <- append(error_messages, BasquePig_result["message"]) + } + + DanishPig_result <- tryCatch({ + DanishPig$public_methods$validateJSON(input) + DanishPig_instance <- DanishPig$new() + instance <- DanishPig_instance$fromJSON(input) + instance_type <- "DanishPig" + matched_schemas <- append(matched_schemas, "DanishPig") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(DanishPig_result["error"])) { + error_messages <- append(error_messages, DanishPig_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into Pig with oneOf schemas BasquePig, DanishPig.") + } else { + # no match + stop(paste("No match found when deserializing the payload into Pig with oneOf schemas BasquePig, DanishPig. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize Pig to JSON string. + #' + #' @description + #' Serialize Pig to JSON string. + #' + #' @return JSON string representation of the Pig. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize Pig to JSON. + #' + #' @description + #' Serialize Pig to JSON. + #' + #' @return JSON representation of the Pig. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to Pig. + #' + #' @description + #' Validate the input JSON with respect to Pig and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#Pig$unlock() +# +## Below is an example to define the print fnuction +#Pig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#Pig$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/special.R b/samples/client/petstore/R-httr2-wrapper/R/special.R new file mode 100644 index 0000000000..33f06cc6a6 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/special.R @@ -0,0 +1,344 @@ +#' Create a new Special +#' +#' @description +#' Describes the result of uploading an image resource +#' +#' @docType class +#' @title Special +#' @description Special Class +#' @format An \code{R6Class} generator object +#' @field set_test list(character) [optional] +#' @field item_self integer [optional] +#' @field item_private character [optional] +#' @field item_super character [optional] +#' @field 123_number character [optional] +#' @field array[test] character [optional] +#' @field empty_string character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Special <- R6::R6Class( + "Special", + public = list( + `set_test` = NULL, + `item_self` = NULL, + `item_private` = NULL, + `item_super` = NULL, + `123_number` = NULL, + `array[test]` = NULL, + `empty_string` = NULL, + `_field_list` = c("set_test", "item_self", "item_private", "item_super", "123_number", "array[test]", "empty_string"), + `additional_properties` = list(), + #' Initialize a new Special class. + #' + #' @description + #' Initialize a new Special class. + #' + #' @param set_test set_test + #' @param item_self item_self + #' @param item_private item_private + #' @param item_super item_super + #' @param 123_number 123_number + #' @param array[test] array[test] + #' @param empty_string empty_string + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`set_test` = NULL, `item_self` = NULL, `item_private` = NULL, `item_super` = NULL, `123_number` = NULL, `array[test]` = NULL, `empty_string` = NULL, additional_properties = NULL, ...) { + if (!is.null(`set_test`)) { + stopifnot(is.vector(`set_test`), length(`set_test`) != 0) + sapply(`set_test`, function(x) stopifnot(is.character(x))) + if (!identical(`set_test`, unique(`set_test`))) { + stop("Error! Items in `set_test` are not unique.") + } + self$`set_test` <- `set_test` + } + if (!is.null(`item_self`)) { + stopifnot(is.numeric(`item_self`), length(`item_self`) == 1) + self$`item_self` <- `item_self` + } + if (!is.null(`item_private`)) { + stopifnot(is.character(`item_private`), length(`item_private`) == 1) + self$`item_private` <- `item_private` + } + if (!is.null(`item_super`)) { + stopifnot(is.character(`item_super`), length(`item_super`) == 1) + self$`item_super` <- `item_super` + } + if (!is.null(`123_number`)) { + stopifnot(is.character(`123_number`), length(`123_number`) == 1) + self$`123_number` <- `123_number` + } + if (!is.null(`array[test]`)) { + stopifnot(is.character(`array[test]`), length(`array[test]`) == 1) + self$`array[test]` <- `array[test]` + } + if (!is.null(`empty_string`)) { + stopifnot(is.character(`empty_string`), length(`empty_string`) == 1) + self$`empty_string` <- `empty_string` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Special in JSON format + #' @export + toJSON = function() { + SpecialObject <- list() + if (!is.null(self$`set_test`)) { + SpecialObject[["set_test"]] <- + self$`set_test` + } + if (!is.null(self$`item_self`)) { + SpecialObject[["self"]] <- + self$`item_self` + } + if (!is.null(self$`item_private`)) { + SpecialObject[["private"]] <- + self$`item_private` + } + if (!is.null(self$`item_super`)) { + SpecialObject[["super"]] <- + self$`item_super` + } + if (!is.null(self$`123_number`)) { + SpecialObject[["123_number"]] <- + self$`123_number` + } + if (!is.null(self$`array[test]`)) { + SpecialObject[["array[test]"]] <- + self$`array[test]` + } + if (!is.null(self$`empty_string`)) { + SpecialObject[["empty_string"]] <- + self$`empty_string` + } + for (key in names(self$additional_properties)) { + SpecialObject[[key]] <- self$additional_properties[[key]] + } + + SpecialObject + }, + #' Deserialize JSON string into an instance of Special + #' + #' @description + #' Deserialize JSON string into an instance of Special + #' + #' @param input_json the JSON input + #' @return the instance of Special + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`set_test`)) { + self$`set_test` <- ApiClient$new()$deserializeObj(this_object$`set_test`, "set[character]", loadNamespace("petstore")) + if (!identical(self$`set_test`, unique(self$`set_test`))) { + stop("Error! Items in `set_test` are not unique.") + } + } + if (!is.null(this_object$`self`)) { + self$`item_self` <- this_object$`self` + } + if (!is.null(this_object$`private`)) { + self$`item_private` <- this_object$`private` + } + if (!is.null(this_object$`super`)) { + self$`item_super` <- this_object$`super` + } + if (!is.null(this_object$`123_number`)) { + self$`123_number` <- this_object$`123_number` + } + if (!is.null(this_object$`array[test]`)) { + self$`array[test]` <- this_object$`array[test]` + } + if (!is.null(this_object$`empty_string`)) { + self$`empty_string` <- this_object$`empty_string` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Special in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`set_test`)) { + sprintf( + '"set_test": + [%s] + ', + paste(unlist(lapply(self$`set_test`, function(x) paste0('"', x, '"'))), collapse = ",") + ) + }, + if (!is.null(self$`item_self`)) { + sprintf( + '"self": + %d + ', + self$`item_self` + ) + }, + if (!is.null(self$`item_private`)) { + sprintf( + '"private": + "%s" + ', + self$`item_private` + ) + }, + if (!is.null(self$`item_super`)) { + sprintf( + '"super": + "%s" + ', + self$`item_super` + ) + }, + if (!is.null(self$`123_number`)) { + sprintf( + '"123_number": + "%s" + ', + self$`123_number` + ) + }, + if (!is.null(self$`array[test]`)) { + sprintf( + '"array[test]": + "%s" + ', + self$`array[test]` + ) + }, + if (!is.null(self$`empty_string`)) { + sprintf( + '"empty_string": + "%s" + ', + self$`empty_string` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Special + #' + #' @description + #' Deserialize JSON string into an instance of Special + #' + #' @param input_json the JSON input + #' @return the instance of Special + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`set_test` <- ApiClient$new()$deserializeObj(this_object$`set_test`, "set[character]", loadNamespace("petstore")) + if (!identical(self$`set_test`, unique(self$`set_test`))) { + stop("Error! Items in `set_test` are not unique.") + } + self$`item_self` <- this_object$`item_self` + self$`item_private` <- this_object$`item_private` + self$`item_super` <- this_object$`item_super` + self$`123_number` <- this_object$`123_number` + self$`array[test]` <- this_object$`array[test]` + self$`empty_string` <- this_object$`empty_string` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Special + #' + #' @description + #' Validate JSON input with respect to Special and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Special + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Special$unlock() +# +## Below is an example to define the print fnuction +# Special$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Special$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/store_api.R b/samples/client/petstore/R-httr2-wrapper/R/store_api.R new file mode 100644 index 0000000000..3811d0e6a4 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/store_api.R @@ -0,0 +1,725 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title Store operations +#' @description StoreApi +#' @format An \code{R6Class} generator object +#' @field api_client Handles the client-server communication. +#' +#' @section Methods: +#' \describe{ +#' \strong{ delete_order } \emph{ Delete purchase order by ID } +#' For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +#' +#' \itemize{ +#' \item \emph{ @param } order_id character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Order not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_inventory } \emph{ Returns pet inventories by status } +#' Returns a map of status codes to quantities +#' +#' \itemize{ +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : map(integer) +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_order_by_id } \emph{ Find purchase order by ID } +#' For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +#' +#' \itemize{ +#' \item \emph{ @param } order_id integer +#' \item \emph{ @returnType } \link{Order} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Order +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Order not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ place_order } \emph{ Place an order for a pet } +#' +#' +#' \itemize{ +#' \item \emph{ @param } order \link{Order} +#' \item \emph{ @returnType } \link{Order} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Order +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid Order +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' } +#' +#' +#' @examples +#' \dontrun{ +#' #################### delete_order #################### +#' +#' library(petstore) +#' var_order_id <- "order_id_example" # character | ID of the order that needs to be deleted +#' +#' #Delete purchase order by ID +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' api_instance$store_api$delete_order(var_order_id), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `delete_order`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### get_inventory #################### +#' +#' library(petstore) +#' +#' #Returns pet inventories by status +#' api_instance <- petstore_api$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$store_api$get_inventory(data_file = "result.txt"), +#' +#' +#' api_instance$store_api$get_inventory(), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_inventory`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### get_order_by_id #################### +#' +#' library(petstore) +#' var_order_id <- 56 # integer | ID of pet that needs to be fetched +#' +#' #Find purchase order by ID +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$store_api$get_order_by_id(var_order_id, data_file = "result.txt"), +#' +#' +#' api_instance$store_api$get_order_by_id(var_order_id), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_order_by_id`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### place_order #################### +#' +#' library(petstore) +#' var_order <- Order$new() # Order | order placed for purchasing the pet +#' +#' #Place an order for a pet +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$store_api$place_order(var_order, data_file = "result.txt"), +#' +#' +#' api_instance$store_api$place_order(var_order), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `place_order`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' } +#' @importFrom R6 R6Class +#' @importFrom base64enc base64encode +#' @importFrom rlang abort +#' @export +StoreApi <- R6::R6Class( + "StoreApi", + public = list( + api_client = NULL, + #' Initialize a new StoreApi. + #' + #' @description + #' Initialize a new StoreApi. + #' + #' @param api_client An instance of API client. + #' @export + initialize = function(api_client) { + if (!missing(api_client)) { + self$api_client <- api_client + } else { + self$api_client <- ApiClient$new() + } + }, + #' Delete purchase order by ID + #' + #' @description + #' Delete purchase order by ID + #' + #' @param order_id ID of the order that needs to be deleted + #' @param ... Other optional arguments + #' @return void + #' @export + delete_order = function(order_id, ...) { + local_var_response <- self$delete_order_with_http_info(order_id, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Delete purchase order by ID + #' + #' @description + #' Delete purchase order by ID + #' + #' @param order_id ID of the order that needs to be deleted + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + delete_order_with_http_info = function(order_id, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`order_id`)) { + rlang::abort(message = "Missing required parameter `order_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `order_id`.")) + } + + + local_var_url_path <- "/store/order/{orderId}" + if (!missing(`order_id`)) { + local_var_url_path <- gsub("\\{orderId\\}", URLencode(as.character(`order_id`), reserved = TRUE), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "DELETE", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Returns pet inventories by status + #' + #' @description + #' Returns pet inventories by status + #' + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return map(integer) + #' @export + get_inventory = function(data_file = NULL, ...) { + local_var_response <- self$get_inventory_with_http_info(data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Returns pet inventories by status + #' + #' @description + #' Returns pet inventories by status + #' + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (map(integer)) with additional information such as HTTP status code, headers + #' @export + get_inventory_with_http_info = function(data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + local_var_url_path <- "/store/inventory" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list("application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "map(integer)", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Find purchase order by ID + #' + #' @description + #' Find purchase order by ID + #' + #' @param order_id ID of pet that needs to be fetched + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Order + #' @export + get_order_by_id = function(order_id, data_file = NULL, ...) { + local_var_response <- self$get_order_by_id_with_http_info(order_id, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Find purchase order by ID + #' + #' @description + #' Find purchase order by ID + #' + #' @param order_id ID of pet that needs to be fetched + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Order) with additional information such as HTTP status code, headers + #' @export + get_order_by_id_with_http_info = function(order_id, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`order_id`)) { + rlang::abort(message = "Missing required parameter `order_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `order_id`.")) + } + + if (`order_id` > 5) { + rlang::abort(message = "Invalid value for `order_id` when calling StoreApi$get_order_by_id, must be smaller than or equal to 5.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `order_id` when calling StoreApi$get_order_by_id, must be smaller than or equal to 5.")) + } + if (`order_id` < 1) { + rlang::abort(message = "Invalid value for `order_id` when calling StoreApi$get_order_by_id, must be bigger than or equal to 1.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `order_id` when calling StoreApi$get_order_by_id, must be bigger than or equal to 1.")) + } + + local_var_url_path <- "/store/order/{orderId}" + if (!missing(`order_id`)) { + local_var_url_path <- gsub("\\{orderId\\}", URLencode(as.character(`order_id`), reserved = TRUE), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Order", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Place an order for a pet + #' + #' @description + #' Place an order for a pet + #' + #' @param order order placed for purchasing the pet + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Order + #' @export + place_order = function(order, data_file = NULL, ...) { + local_var_response <- self$place_order_with_http_info(order, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Place an order for a pet + #' + #' @description + #' Place an order for a pet + #' + #' @param order order placed for purchasing the pet + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Order) with additional information such as HTTP status code, headers + #' @export + place_order_with_http_info = function(order, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`order`)) { + rlang::abort(message = "Missing required parameter `order`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `order`.")) + } + + + if (!is.null(`order`)) { + local_var_body <- `order`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/store/order" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Order", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2-wrapper/R/tag.R b/samples/client/petstore/R-httr2-wrapper/R/tag.R new file mode 100644 index 0000000000..bd4aac10e2 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/tag.R @@ -0,0 +1,217 @@ +#' Create a new Tag +#' +#' @description +#' A tag for a pet +#' +#' @docType class +#' @title Tag +#' @description Tag Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field name character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Tag <- R6::R6Class( + "Tag", + public = list( + `id` = NULL, + `name` = NULL, + `_field_list` = c("id", "name"), + `additional_properties` = list(), + #' Initialize a new Tag class. + #' + #' @description + #' Initialize a new Tag class. + #' + #' @param id id + #' @param name name + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `name` = NULL, additional_properties = NULL, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Tag in JSON format + #' @export + toJSON = function() { + TagObject <- list() + if (!is.null(self$`id`)) { + TagObject[["id"]] <- + self$`id` + } + if (!is.null(self$`name`)) { + TagObject[["name"]] <- + self$`name` + } + for (key in names(self$additional_properties)) { + TagObject[[key]] <- self$additional_properties[[key]] + } + + TagObject + }, + #' Deserialize JSON string into an instance of Tag + #' + #' @description + #' Deserialize JSON string into an instance of Tag + #' + #' @param input_json the JSON input + #' @return the instance of Tag + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`name`)) { + self$`name` <- this_object$`name` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Tag in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`name`)) { + sprintf( + '"name": + "%s" + ', + self$`name` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Tag + #' + #' @description + #' Deserialize JSON string into an instance of Tag + #' + #' @param input_json the JSON input + #' @return the instance of Tag + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`name` <- this_object$`name` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Tag + #' + #' @description + #' Validate JSON input with respect to Tag and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Tag + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Tag$unlock() +# +## Below is an example to define the print fnuction +# Tag$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Tag$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/update_pet_request.R b/samples/client/petstore/R-httr2-wrapper/R/update_pet_request.R new file mode 100644 index 0000000000..bde06df6a8 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/update_pet_request.R @@ -0,0 +1,218 @@ +#' Create a new UpdatePetRequest +#' +#' @description +#' UpdatePetRequest Class +#' +#' @docType class +#' @title UpdatePetRequest +#' @description UpdatePetRequest Class +#' @format An \code{R6Class} generator object +#' @field jsonData \link{Pet} [optional] +#' @field binaryDataN2Information data.frame [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +UpdatePetRequest <- R6::R6Class( + "UpdatePetRequest", + public = list( + `jsonData` = NULL, + `binaryDataN2Information` = NULL, + `_field_list` = c("jsonData", "binaryDataN2Information"), + `additional_properties` = list(), + #' Initialize a new UpdatePetRequest class. + #' + #' @description + #' Initialize a new UpdatePetRequest class. + #' + #' @param jsonData jsonData + #' @param binaryDataN2Information binaryDataN2Information + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`jsonData` = NULL, `binaryDataN2Information` = NULL, additional_properties = NULL, ...) { + if (!is.null(`jsonData`)) { + stopifnot(R6::is.R6(`jsonData`)) + self$`jsonData` <- `jsonData` + } + if (!is.null(`binaryDataN2Information`)) { + self$`binaryDataN2Information` <- `binaryDataN2Information` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return UpdatePetRequest in JSON format + #' @export + toJSON = function() { + UpdatePetRequestObject <- list() + if (!is.null(self$`jsonData`)) { + UpdatePetRequestObject[["jsonData"]] <- + self$`jsonData`$toJSON() + } + if (!is.null(self$`binaryDataN2Information`)) { + UpdatePetRequestObject[["binaryDataN2Information"]] <- + self$`binaryDataN2Information` + } + for (key in names(self$additional_properties)) { + UpdatePetRequestObject[[key]] <- self$additional_properties[[key]] + } + + UpdatePetRequestObject + }, + #' Deserialize JSON string into an instance of UpdatePetRequest + #' + #' @description + #' Deserialize JSON string into an instance of UpdatePetRequest + #' + #' @param input_json the JSON input + #' @return the instance of UpdatePetRequest + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`jsonData`)) { + jsondata_object <- Pet$new() + jsondata_object$fromJSON(jsonlite::toJSON(this_object$jsonData, auto_unbox = TRUE, digits = NA)) + self$`jsonData` <- jsondata_object + } + if (!is.null(this_object$`binaryDataN2Information`)) { + self$`binaryDataN2Information` <- this_object$`binaryDataN2Information` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return UpdatePetRequest in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`jsonData`)) { + sprintf( + '"jsonData": + %s + ', + jsonlite::toJSON(self$`jsonData`$toJSON(), auto_unbox = TRUE, digits = NA) + ) + }, + if (!is.null(self$`binaryDataN2Information`)) { + sprintf( + '"binaryDataN2Information": + "%s" + ', + self$`binaryDataN2Information` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of UpdatePetRequest + #' + #' @description + #' Deserialize JSON string into an instance of UpdatePetRequest + #' + #' @param input_json the JSON input + #' @return the instance of UpdatePetRequest + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`jsonData` <- Pet$new()$fromJSON(jsonlite::toJSON(this_object$jsonData, auto_unbox = TRUE, digits = NA)) + self$`binaryDataN2Information` <- this_object$`binaryDataN2Information` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to UpdatePetRequest + #' + #' @description + #' Validate JSON input with respect to UpdatePetRequest and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of UpdatePetRequest + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# UpdatePetRequest$unlock() +# +## Below is an example to define the print fnuction +# UpdatePetRequest$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# UpdatePetRequest$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/user.R b/samples/client/petstore/R-httr2-wrapper/R/user.R new file mode 100644 index 0000000000..153aacb3ea --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/user.R @@ -0,0 +1,355 @@ +#' Create a new User +#' +#' @description +#' A User who is purchasing from the pet store +#' +#' @docType class +#' @title User +#' @description User Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field username character [optional] +#' @field firstName character [optional] +#' @field lastName character [optional] +#' @field email character [optional] +#' @field password character [optional] +#' @field phone character [optional] +#' @field userStatus User Status integer [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +User <- R6::R6Class( + "User", + public = list( + `id` = NULL, + `username` = NULL, + `firstName` = NULL, + `lastName` = NULL, + `email` = NULL, + `password` = NULL, + `phone` = NULL, + `userStatus` = NULL, + `_field_list` = c("id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus"), + `additional_properties` = list(), + #' Initialize a new User class. + #' + #' @description + #' Initialize a new User class. + #' + #' @param id id + #' @param username username + #' @param firstName firstName + #' @param lastName lastName + #' @param email email + #' @param password password + #' @param phone phone + #' @param userStatus User Status + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `username` = NULL, `firstName` = NULL, `lastName` = NULL, `email` = NULL, `password` = NULL, `phone` = NULL, `userStatus` = NULL, additional_properties = NULL, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`username`)) { + stopifnot(is.character(`username`), length(`username`) == 1) + self$`username` <- `username` + } + if (!is.null(`firstName`)) { + stopifnot(is.character(`firstName`), length(`firstName`) == 1) + self$`firstName` <- `firstName` + } + if (!is.null(`lastName`)) { + stopifnot(is.character(`lastName`), length(`lastName`) == 1) + self$`lastName` <- `lastName` + } + if (!is.null(`email`)) { + stopifnot(is.character(`email`), length(`email`) == 1) + self$`email` <- `email` + } + if (!is.null(`password`)) { + stopifnot(is.character(`password`), length(`password`) == 1) + self$`password` <- `password` + } + if (!is.null(`phone`)) { + stopifnot(is.character(`phone`), length(`phone`) == 1) + self$`phone` <- `phone` + } + if (!is.null(`userStatus`)) { + stopifnot(is.numeric(`userStatus`), length(`userStatus`) == 1) + self$`userStatus` <- `userStatus` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return User in JSON format + #' @export + toJSON = function() { + UserObject <- list() + if (!is.null(self$`id`)) { + UserObject[["id"]] <- + self$`id` + } + if (!is.null(self$`username`)) { + UserObject[["username"]] <- + self$`username` + } + if (!is.null(self$`firstName`)) { + UserObject[["firstName"]] <- + self$`firstName` + } + if (!is.null(self$`lastName`)) { + UserObject[["lastName"]] <- + self$`lastName` + } + if (!is.null(self$`email`)) { + UserObject[["email"]] <- + self$`email` + } + if (!is.null(self$`password`)) { + UserObject[["password"]] <- + self$`password` + } + if (!is.null(self$`phone`)) { + UserObject[["phone"]] <- + self$`phone` + } + if (!is.null(self$`userStatus`)) { + UserObject[["userStatus"]] <- + self$`userStatus` + } + for (key in names(self$additional_properties)) { + UserObject[[key]] <- self$additional_properties[[key]] + } + + UserObject + }, + #' Deserialize JSON string into an instance of User + #' + #' @description + #' Deserialize JSON string into an instance of User + #' + #' @param input_json the JSON input + #' @return the instance of User + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`username`)) { + self$`username` <- this_object$`username` + } + if (!is.null(this_object$`firstName`)) { + self$`firstName` <- this_object$`firstName` + } + if (!is.null(this_object$`lastName`)) { + self$`lastName` <- this_object$`lastName` + } + if (!is.null(this_object$`email`)) { + self$`email` <- this_object$`email` + } + if (!is.null(this_object$`password`)) { + self$`password` <- this_object$`password` + } + if (!is.null(this_object$`phone`)) { + self$`phone` <- this_object$`phone` + } + if (!is.null(this_object$`userStatus`)) { + self$`userStatus` <- this_object$`userStatus` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return User in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`username`)) { + sprintf( + '"username": + "%s" + ', + self$`username` + ) + }, + if (!is.null(self$`firstName`)) { + sprintf( + '"firstName": + "%s" + ', + self$`firstName` + ) + }, + if (!is.null(self$`lastName`)) { + sprintf( + '"lastName": + "%s" + ', + self$`lastName` + ) + }, + if (!is.null(self$`email`)) { + sprintf( + '"email": + "%s" + ', + self$`email` + ) + }, + if (!is.null(self$`password`)) { + sprintf( + '"password": + "%s" + ', + self$`password` + ) + }, + if (!is.null(self$`phone`)) { + sprintf( + '"phone": + "%s" + ', + self$`phone` + ) + }, + if (!is.null(self$`userStatus`)) { + sprintf( + '"userStatus": + %d + ', + self$`userStatus` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of User + #' + #' @description + #' Deserialize JSON string into an instance of User + #' + #' @param input_json the JSON input + #' @return the instance of User + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`username` <- this_object$`username` + self$`firstName` <- this_object$`firstName` + self$`lastName` <- this_object$`lastName` + self$`email` <- this_object$`email` + self$`password` <- this_object$`password` + self$`phone` <- this_object$`phone` + self$`userStatus` <- this_object$`userStatus` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to User + #' + #' @description + #' Validate JSON input with respect to User and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of User + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# User$unlock() +# +## Below is an example to define the print fnuction +# User$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# User$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/user_api.R b/samples/client/petstore/R-httr2-wrapper/R/user_api.R new file mode 100644 index 0000000000..bc8daa69c9 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/user_api.R @@ -0,0 +1,1356 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title User operations +#' @description UserApi +#' @format An \code{R6Class} generator object +#' @field api_client Handles the client-server communication. +#' +#' @section Methods: +#' \describe{ +#' \strong{ create_user } \emph{ Create user } +#' This can only be done by the logged in user. +#' +#' \itemize{ +#' \item \emph{ @param } user \link{User} +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 0 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ create_users_with_array_input } \emph{ Creates list of users with given input array } +#' +#' +#' \itemize{ +#' \item \emph{ @param } user list( \link{User} ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 0 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ create_users_with_list_input } \emph{ Creates list of users with given input array } +#' +#' +#' \itemize{ +#' \item \emph{ @param } user list( \link{User} ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 0 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ delete_user } \emph{ Delete user } +#' This can only be done by the logged in user. +#' +#' \itemize{ +#' \item \emph{ @param } username character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 400 | Invalid username supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | User not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_user_by_name } \emph{ Get user by user name } +#' +#' +#' \itemize{ +#' \item \emph{ @param } username character +#' \item \emph{ @returnType } \link{User} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : User +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid username supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | User not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ login_user } \emph{ Logs user into the system } +#' +#' +#' \itemize{ +#' \item \emph{ @param } username character +#' \item \emph{ @param } password character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : character +#' \item response headers : +#' +#' \tabular{ll}{ +#' Set-Cookie \tab Cookie authentication key for use with the `api_key` apiKey authentication. \cr +#' X-Rate-Limit \tab calls per hour allowed by the user \cr +#' X-Expires-After \tab date in UTC when token expires \cr +#' } +#' \item status code : 400 | Invalid username/password supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ logout_user } \emph{ Logs out current logged in user session } +#' +#' +#' \itemize{ +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 0 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ update_user } \emph{ Updated user } +#' This can only be done by the logged in user. +#' +#' \itemize{ +#' \item \emph{ @param } username character +#' \item \emph{ @param } user \link{User} +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 400 | Invalid user supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | User not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' } +#' +#' +#' @examples +#' \dontrun{ +#' #################### create_user #################### +#' +#' library(petstore) +#' var_user <- User$new() # User | Created user object +#' +#' #Create user +#' api_instance <- petstore_api$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$user_api$create_user(var_user), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `create_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### create_users_with_array_input #################### +#' +#' library(petstore) +#' var_user <- [User$new()] # array[User] | List of user object +#' +#' #Creates list of users with given input array +#' api_instance <- petstore_api$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$user_api$create_users_with_array_input(var_user), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `create_users_with_array_input`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### create_users_with_list_input #################### +#' +#' library(petstore) +#' var_user <- [User$new()] # array[User] | List of user object +#' +#' #Creates list of users with given input array +#' api_instance <- petstore_api$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$user_api$create_users_with_list_input(var_user), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `create_users_with_list_input`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### delete_user #################### +#' +#' library(petstore) +#' var_username <- "username_example" # character | The name that needs to be deleted +#' +#' #Delete user +#' api_instance <- petstore_api$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$user_api$delete_user(var_username), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `delete_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### get_user_by_name #################### +#' +#' library(petstore) +#' var_username <- "username_example" # character | The name that needs to be fetched. Use user1 for testing. +#' +#' #Get user by user name +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$user_api$get_user_by_name(var_username, data_file = "result.txt"), +#' +#' +#' api_instance$user_api$get_user_by_name(var_username), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_user_by_name`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### login_user #################### +#' +#' library(petstore) +#' var_username <- "username_example" # character | The user name for login +#' var_password <- "password_example" # character | The password for login in clear text +#' +#' #Logs user into the system +#' api_instance <- petstore_api$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$user_api$login_user(var_username, var_password, data_file = "result.txt"), +#' +#' +#' api_instance$user_api$login_user(var_username, var_password), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `login_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### logout_user #################### +#' +#' library(petstore) +#' +#' #Logs out current logged in user session +#' api_instance <- petstore_api$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$user_api$logout_user(), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `logout_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### update_user #################### +#' +#' library(petstore) +#' var_username <- "username_example" # character | name that need to be deleted +#' var_user <- User$new() # User | Updated user object +#' +#' #Updated user +#' api_instance <- petstore_api$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$user_api$update_user(var_username, var_user), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `update_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' } +#' @importFrom R6 R6Class +#' @importFrom base64enc base64encode +#' @importFrom rlang abort +#' @export +UserApi <- R6::R6Class( + "UserApi", + public = list( + api_client = NULL, + #' Initialize a new UserApi. + #' + #' @description + #' Initialize a new UserApi. + #' + #' @param api_client An instance of API client. + #' @export + initialize = function(api_client) { + if (!missing(api_client)) { + self$api_client <- api_client + } else { + self$api_client <- ApiClient$new() + } + }, + #' Create user + #' + #' @description + #' Create user + #' + #' @param user Created user object + #' @param ... Other optional arguments + #' @return void + #' @export + create_user = function(user, ...) { + local_var_response <- self$create_user_with_http_info(user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Create user + #' + #' @description + #' Create user + #' + #' @param user Created user object + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + create_user_with_http_info = function(user, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`user`)) { + rlang::abort(message = "Missing required parameter `user`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `user`.")) + } + + + if (!is.null(`user`)) { + local_var_body <- `user`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/user" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Creates list of users with given input array + #' + #' @description + #' Creates list of users with given input array + #' + #' @param user List of user object + #' @param ... Other optional arguments + #' @return void + #' @export + create_users_with_array_input = function(user, ...) { + local_var_response <- self$create_users_with_array_input_with_http_info(user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Creates list of users with given input array + #' + #' @description + #' Creates list of users with given input array + #' + #' @param user List of user object + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + create_users_with_array_input_with_http_info = function(user, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`user`)) { + rlang::abort(message = "Missing required parameter `user`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `user`.")) + } + + + if (!is.null(`user`)) { + body.items <- paste(unlist(lapply(`user`, function(param) { + param$toJSONString() + })), collapse = ",") + local_var_body <- paste0("[", body.items, "]") + } else { + body <- NULL + } + + local_var_url_path <- "/user/createWithArray" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Creates list of users with given input array + #' + #' @description + #' Creates list of users with given input array + #' + #' @param user List of user object + #' @param ... Other optional arguments + #' @return void + #' @export + create_users_with_list_input = function(user, ...) { + local_var_response <- self$create_users_with_list_input_with_http_info(user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Creates list of users with given input array + #' + #' @description + #' Creates list of users with given input array + #' + #' @param user List of user object + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + create_users_with_list_input_with_http_info = function(user, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`user`)) { + rlang::abort(message = "Missing required parameter `user`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `user`.")) + } + + + if (!is.null(`user`)) { + body.items <- paste(unlist(lapply(`user`, function(param) { + param$toJSONString() + })), collapse = ",") + local_var_body <- paste0("[", body.items, "]") + } else { + body <- NULL + } + + local_var_url_path <- "/user/createWithList" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Delete user + #' + #' @description + #' Delete user + #' + #' @param username The name that needs to be deleted + #' @param ... Other optional arguments + #' @return void + #' @export + delete_user = function(username, ...) { + local_var_response <- self$delete_user_with_http_info(username, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Delete user + #' + #' @description + #' Delete user + #' + #' @param username The name that needs to be deleted + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + delete_user_with_http_info = function(username, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`username`)) { + rlang::abort(message = "Missing required parameter `username`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `username`.")) + } + + + local_var_url_path <- "/user/{username}" + if (!missing(`username`)) { + local_var_url_path <- gsub("\\{username\\}", URLencode(as.character(`username`), reserved = TRUE), local_var_url_path) + } + + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "DELETE", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Get user by user name + #' + #' @description + #' Get user by user name + #' + #' @param username The name that needs to be fetched. Use user1 for testing. + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return User + #' @export + get_user_by_name = function(username, data_file = NULL, ...) { + local_var_response <- self$get_user_by_name_with_http_info(username, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Get user by user name + #' + #' @description + #' Get user by user name + #' + #' @param username The name that needs to be fetched. Use user1 for testing. + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (User) with additional information such as HTTP status code, headers + #' @export + get_user_by_name_with_http_info = function(username, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`username`)) { + rlang::abort(message = "Missing required parameter `username`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `username`.")) + } + + + local_var_url_path <- "/user/{username}" + if (!missing(`username`)) { + local_var_url_path <- gsub("\\{username\\}", URLencode(as.character(`username`), reserved = TRUE), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "User", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Logs user into the system + #' + #' @description + #' Logs user into the system + #' + #' @param username The user name for login + #' @param password The password for login in clear text + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return character + #' @export + login_user = function(username, password, data_file = NULL, ...) { + local_var_response <- self$login_user_with_http_info(username, password, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Logs user into the system + #' + #' @description + #' Logs user into the system + #' + #' @param username The user name for login + #' @param password The password for login in clear text + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (character) with additional information such as HTTP status code, headers + #' @export + login_user_with_http_info = function(username, password, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`username`)) { + rlang::abort(message = "Missing required parameter `username`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `username`.")) + } + + if (missing(`password`)) { + rlang::abort(message = "Missing required parameter `password`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `password`.")) + } + + if (!str_detect(`username`, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")) { + rlang::abort(message = "Invalid value for `username` when calling UserApi$login_user, must conform to the pattern ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `username` when calling UserApi$login_user, must conform to the pattern ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$.")) + } + + + query_params[["username"]] <- `username` + + query_params[["password"]] <- `password` + + local_var_url_path <- "/user/login" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "character", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Logs out current logged in user session + #' + #' @description + #' Logs out current logged in user session + #' + #' @param ... Other optional arguments + #' @return void + #' @export + logout_user = function(...) { + local_var_response <- self$logout_user_with_http_info(...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Logs out current logged in user session + #' + #' @description + #' Logs out current logged in user session + #' + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + logout_user_with_http_info = function(...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + local_var_url_path <- "/user/logout" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Updated user + #' + #' @description + #' Updated user + #' + #' @param username name that need to be deleted + #' @param user Updated user object + #' @param ... Other optional arguments + #' @return void + #' @export + update_user = function(username, user, ...) { + local_var_response <- self$update_user_with_http_info(username, user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Updated user + #' + #' @description + #' Updated user + #' + #' @param username name that need to be deleted + #' @param user Updated user object + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + update_user_with_http_info = function(username, user, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`username`)) { + rlang::abort(message = "Missing required parameter `username`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `username`.")) + } + + if (missing(`user`)) { + rlang::abort(message = "Missing required parameter `user`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `user`.")) + } + + + + if (!is.null(`user`)) { + local_var_body <- `user`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/user/{username}" + if (!missing(`username`)) { + local_var_url_path <- gsub("\\{username\\}", URLencode(as.character(`username`), reserved = TRUE), local_var_url_path) + } + + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "PUT", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2-wrapper/R/whale.R b/samples/client/petstore/R-httr2-wrapper/R/whale.R new file mode 100644 index 0000000000..936b3a2573 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/whale.R @@ -0,0 +1,256 @@ +#' Create a new Whale +#' +#' @description +#' Whale Class +#' +#' @docType class +#' @title Whale +#' @description Whale Class +#' @format An \code{R6Class} generator object +#' @field hasBaleen character [optional] +#' @field hasTeeth character [optional] +#' @field className character +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Whale <- R6::R6Class( + "Whale", + public = list( + `hasBaleen` = NULL, + `hasTeeth` = NULL, + `className` = NULL, + `_field_list` = c("hasBaleen", "hasTeeth", "className"), + `additional_properties` = list(), + #' Initialize a new Whale class. + #' + #' @description + #' Initialize a new Whale class. + #' + #' @param className className + #' @param hasBaleen hasBaleen + #' @param hasTeeth hasTeeth + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `hasBaleen` = NULL, `hasTeeth` = NULL, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`hasBaleen`)) { + stopifnot(is.logical(`hasBaleen`), length(`hasBaleen`) == 1) + self$`hasBaleen` <- `hasBaleen` + } + if (!is.null(`hasTeeth`)) { + stopifnot(is.logical(`hasTeeth`), length(`hasTeeth`) == 1) + self$`hasTeeth` <- `hasTeeth` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Whale in JSON format + #' @export + toJSON = function() { + WhaleObject <- list() + if (!is.null(self$`hasBaleen`)) { + WhaleObject[["hasBaleen"]] <- + self$`hasBaleen` + } + if (!is.null(self$`hasTeeth`)) { + WhaleObject[["hasTeeth"]] <- + self$`hasTeeth` + } + if (!is.null(self$`className`)) { + WhaleObject[["className"]] <- + self$`className` + } + for (key in names(self$additional_properties)) { + WhaleObject[[key]] <- self$additional_properties[[key]] + } + + WhaleObject + }, + #' Deserialize JSON string into an instance of Whale + #' + #' @description + #' Deserialize JSON string into an instance of Whale + #' + #' @param input_json the JSON input + #' @return the instance of Whale + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`hasBaleen`)) { + self$`hasBaleen` <- this_object$`hasBaleen` + } + if (!is.null(this_object$`hasTeeth`)) { + self$`hasTeeth` <- this_object$`hasTeeth` + } + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Whale in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`hasBaleen`)) { + sprintf( + '"hasBaleen": + %s + ', + tolower(self$`hasBaleen`) + ) + }, + if (!is.null(self$`hasTeeth`)) { + sprintf( + '"hasTeeth": + %s + ', + tolower(self$`hasTeeth`) + ) + }, + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Whale + #' + #' @description + #' Deserialize JSON string into an instance of Whale + #' + #' @param input_json the JSON input + #' @return the instance of Whale + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`hasBaleen` <- this_object$`hasBaleen` + self$`hasTeeth` <- this_object$`hasTeeth` + self$`className` <- this_object$`className` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Whale + #' + #' @description + #' Validate JSON input with respect to Whale and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Whale: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Whale + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Whale$unlock() +# +## Below is an example to define the print fnuction +# Whale$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Whale$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/R/zebra.R b/samples/client/petstore/R-httr2-wrapper/R/zebra.R new file mode 100644 index 0000000000..5c090e84cb --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/R/zebra.R @@ -0,0 +1,242 @@ +#' Create a new Zebra +#' +#' @description +#' Zebra Class +#' +#' @docType class +#' @title Zebra +#' @description Zebra Class +#' @format An \code{R6Class} generator object +#' @field type character [optional] +#' @field className character +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Zebra <- R6::R6Class( + "Zebra", + public = list( + `type` = NULL, + `className` = NULL, + `_field_list` = c("type", "className"), + `additional_properties` = list(), + #' Initialize a new Zebra class. + #' + #' @description + #' Initialize a new Zebra class. + #' + #' @param className className + #' @param type type + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `type` = NULL, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`type`)) { + if (!(`type` %in% c("plains", "mountain", "grevys"))) { + stop(paste("Error! \"", `type`, "\" cannot be assigned to `type`. Must be \"plains\", \"mountain\", \"grevys\".", sep = "")) + } + stopifnot(is.character(`type`), length(`type`) == 1) + self$`type` <- `type` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Zebra in JSON format + #' @export + toJSON = function() { + ZebraObject <- list() + if (!is.null(self$`type`)) { + ZebraObject[["type"]] <- + self$`type` + } + if (!is.null(self$`className`)) { + ZebraObject[["className"]] <- + self$`className` + } + for (key in names(self$additional_properties)) { + ZebraObject[[key]] <- self$additional_properties[[key]] + } + + ZebraObject + }, + #' Deserialize JSON string into an instance of Zebra + #' + #' @description + #' Deserialize JSON string into an instance of Zebra + #' + #' @param input_json the JSON input + #' @return the instance of Zebra + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`type`)) { + if (!is.null(this_object$`type`) && !(this_object$`type` %in% c("plains", "mountain", "grevys"))) { + stop(paste("Error! \"", this_object$`type`, "\" cannot be assigned to `type`. Must be \"plains\", \"mountain\", \"grevys\".", sep = "")) + } + self$`type` <- this_object$`type` + } + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Zebra in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`type`)) { + sprintf( + '"type": + "%s" + ', + self$`type` + ) + }, + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Zebra + #' + #' @description + #' Deserialize JSON string into an instance of Zebra + #' + #' @param input_json the JSON input + #' @return the instance of Zebra + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`type`) && !(this_object$`type` %in% c("plains", "mountain", "grevys"))) { + stop(paste("Error! \"", this_object$`type`, "\" cannot be assigned to `type`. Must be \"plains\", \"mountain\", \"grevys\".", sep = "")) + } + self$`type` <- this_object$`type` + self$`className` <- this_object$`className` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Zebra + #' + #' @description + #' Validate JSON input with respect to Zebra and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Zebra: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Zebra + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Zebra$unlock() +# +## Below is an example to define the print fnuction +# Zebra$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Zebra$lock() + diff --git a/samples/client/petstore/R-httr2-wrapper/README.md b/samples/client/petstore/R-httr2-wrapper/README.md new file mode 100644 index 0000000000..bb481451cb --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/README.md @@ -0,0 +1,159 @@ +# R API client for petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.RClientCodegen + +## Installation + +### Prerequisites + +Install the dependencies + +```R +install.packages("jsonlite") +install.packages("httr") +install.packages("base64enc") +``` + +### Build the package + +```sh +git clone https://github.com/GIT_USER_ID/GIT_REPO_ID +cd GIT_REPO_ID +R CMD build . +R CMD check petstore_1.0.0.tar.gz --no-manual +R CMD INSTALL --preclean petstore_1.0.0.tar.gz +``` + +### Install the package + +```R +install.packages("petstore") +``` + +To install directly from Github, use `devtools`: +```R +install.packages("devtools") +library(devtools) +install_github("GIT_USER_ID/GIT_REPO_ID") +``` + +To install the package from a local file: +```R +install.packages("petstore_1.0.0.tar.gz", repos = NULL, type = "source") +``` + +### Usage + +```R +library(petstore) +``` + +### Reformat code + +To reformat code using [styler](https://styler.r-lib.org/index.html), please run the following in the R console: + +```R +install.packages("remotes") +remotes::install_github("r-lib/styler@v1.7.0.9003") +library("styler") +style_dir() +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*FakeApi* | [**add_pet_optional**](docs/FakeApi.md#add_pet_optional) | **POST** /fake/test_optional_body_parameter | Add a new pet to the store (optional body) +*FakeApi* | [**fake_data_file**](docs/FakeApi.md#fake_data_file) | **GET** /fake/data_file | test data_file to ensure it's escaped correctly +*FakeApi* | [**fake_path_array**](docs/FakeApi.md#fake_path_array) | **GET** /fake/path_array/{path_array}/testing | test array parameter in path +*FakeApi* | [**fake_regular_expression**](docs/FakeApi.md#fake_regular_expression) | **GET** /fake/regular_expression | test regular expression to ensure no exception +*FakeApi* | [**fake_set_query**](docs/FakeApi.md#fake_set_query) | **GET** /fake/set_query_parameter | test set query parameter +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**get_pet_by_id_streaming**](docs/PetApi.md#get_pet_by_id_streaming) | **GET** /pet/{petId}?streaming | Find pet by ID (streaming) +*PetApi* | [**test_header**](docs/PetApi.md#test_header) | **GET** /pet_header_test | Header test +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [AllofTagApiResponse](docs/AllofTagApiResponse.md) + - [Animal](docs/Animal.md) + - [AnyOfPig](docs/AnyOfPig.md) + - [AnyOfPrimitiveTypeTest](docs/AnyOfPrimitiveTypeTest.md) + - [BasquePig](docs/BasquePig.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [DanishPig](docs/DanishPig.md) + - [Date](docs/Date.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [Mammal](docs/Mammal.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [NestedOneOf](docs/NestedOneOf.md) + - [OneOfPrimitiveTypeTest](docs/OneOfPrimitiveTypeTest.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Pig](docs/Pig.md) + - [Special](docs/Special.md) + - [Tag](docs/Tag.md) + - [UpdatePetRequest](docs/UpdatePetRequest.md) + - [User](docs/User.md) + - [Whale](docs/Whale.md) + - [Zebra](docs/Zebra.md) + + +## Documentation for Authorization + + +### BearerToken + +- **Type**: Bearer authentication + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### http_auth + +- **Type**: HTTP basic authentication + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - `write:pets`: modify pets in your account + - `read:pets`: read your pets + + diff --git a/samples/client/petstore/R-httr2-wrapper/build_and_test.bash b/samples/client/petstore/R-httr2-wrapper/build_and_test.bash new file mode 100644 index 0000000000..2079f75da0 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/build_and_test.bash @@ -0,0 +1,26 @@ +#!/bin/bash + +set -e + +REPO=https://cloud.r-project.org + +export R_LIBS_USER=$HOME/R + +echo "R lib directory: $R_LIBS_USER" + +mkdir $R_LIBS_USER || true + +Rscript -e "install.packages('jsonlite', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('httr', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('testthat', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('R6', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('base64enc', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('rlang', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('rjson', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('devtools', repos='$REPO', lib='$R_LIBS_USER')" + +rm petstore_1.0.0.tar.gz || true + +R CMD build . +R CMD check *tar.gz --no-manual +R CMD install --preclean *tar.gz diff --git a/samples/client/petstore/R-httr2-wrapper/docs/AllofTagApiResponse.md b/samples/client/petstore/R-httr2-wrapper/docs/AllofTagApiResponse.md new file mode 100644 index 0000000000..14bcc1e22c --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/AllofTagApiResponse.md @@ -0,0 +1,13 @@ +# petstore::AllofTagApiResponse + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**name** | **character** | | [optional] +**code** | **integer** | | [optional] +**type** | **character** | | [optional] +**message** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Animal.md b/samples/client/petstore/R-httr2-wrapper/docs/Animal.md new file mode 100644 index 0000000000..21af972e0f --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Animal.md @@ -0,0 +1,10 @@ +# petstore::Animal + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | [optional] [default to "red"] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/AnyOfPig.md b/samples/client/petstore/R-httr2-wrapper/docs/AnyOfPig.md new file mode 100644 index 0000000000..296d7c7e33 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/AnyOfPig.md @@ -0,0 +1,11 @@ +# petstore::AnyOfPig + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | +**size** | **integer** | | + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/AnyOfPrimitiveTypeTest.md b/samples/client/petstore/R-httr2-wrapper/docs/AnyOfPrimitiveTypeTest.md new file mode 100644 index 0000000000..0d8ba0e63b --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/AnyOfPrimitiveTypeTest.md @@ -0,0 +1,8 @@ +# petstore::AnyOfPrimitiveTypeTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/ApiResponse.md b/samples/client/petstore/R-httr2-wrapper/docs/ApiResponse.md new file mode 100644 index 0000000000..ef38431e4c --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/ApiResponse.md @@ -0,0 +1,10 @@ +# petstore::ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **integer** | | [optional] +**type** | **character** | | [optional] +**message** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/BasquePig.md b/samples/client/petstore/R-httr2-wrapper/docs/BasquePig.md new file mode 100644 index 0000000000..9e00cec58b --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/BasquePig.md @@ -0,0 +1,10 @@ +# petstore::BasquePig + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Cat.md b/samples/client/petstore/R-httr2-wrapper/docs/Cat.md new file mode 100644 index 0000000000..9a717492c0 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Cat.md @@ -0,0 +1,11 @@ +# petstore::Cat + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | [optional] [default to "red"] +**declawed** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/CatAllOf.md b/samples/client/petstore/R-httr2-wrapper/docs/CatAllOf.md new file mode 100644 index 0000000000..ab2f71b88e --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/CatAllOf.md @@ -0,0 +1,9 @@ +# petstore::CatAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Category.md b/samples/client/petstore/R-httr2-wrapper/docs/Category.md new file mode 100644 index 0000000000..41b20285b8 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Category.md @@ -0,0 +1,11 @@ +# petstore::Category + +A category for a pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**name** | **character** | | [optional] [Pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/DanishPig.md b/samples/client/petstore/R-httr2-wrapper/docs/DanishPig.md new file mode 100644 index 0000000000..1d6c5bf2ac --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/DanishPig.md @@ -0,0 +1,10 @@ +# petstore::DanishPig + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**size** | **integer** | | + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Date.md b/samples/client/petstore/R-httr2-wrapper/docs/Date.md new file mode 100644 index 0000000000..ed61f58682 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Date.md @@ -0,0 +1,12 @@ +# petstore::Date + +to test the model name `Date` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**percent_description** | **character** | using % in the description | [optional] +**url_property** | **character** | | + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Dog.md b/samples/client/petstore/R-httr2-wrapper/docs/Dog.md new file mode 100644 index 0000000000..6893a5e18e --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Dog.md @@ -0,0 +1,11 @@ +# petstore::Dog + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | [optional] [default to "red"] +**breed** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/DogAllOf.md b/samples/client/petstore/R-httr2-wrapper/docs/DogAllOf.md new file mode 100644 index 0000000000..76783e8800 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/DogAllOf.md @@ -0,0 +1,9 @@ +# petstore::DogAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/FakeApi.md b/samples/client/petstore/R-httr2-wrapper/docs/FakeApi.md new file mode 100644 index 0000000000..85182dfc8f --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/FakeApi.md @@ -0,0 +1,308 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_pet_optional**](FakeApi.md#add_pet_optional) | **POST** /fake/test_optional_body_parameter | Add a new pet to the store (optional body) +[**fake_data_file**](FakeApi.md#fake_data_file) | **GET** /fake/data_file | test data_file to ensure it's escaped correctly +[**fake_path_array**](FakeApi.md#fake_path_array) | **GET** /fake/path_array/{path_array}/testing | test array parameter in path +[**fake_regular_expression**](FakeApi.md#fake_regular_expression) | **GET** /fake/regular_expression | test regular expression to ensure no exception +[**fake_set_query**](FakeApi.md#fake_set_query) | **GET** /fake/set_query_parameter | test set query parameter + + +# **add_pet_optional** +> Pet add_pet_optional(pet = var.pet) + +Add a new pet to the store (optional body) + + + +### Example +```R +library(petstore) + +# Add a new pet to the store (optional body) +# +# prepare function argument(s) +var_pet <- Pet$new("name_example", list("photoUrls_example"), 123, Category$new(123, "name_example"), list(Tag$new(123, "name_example")), "available") # Pet | Pet object that needs to be added to the store (Optional) + +api_instance <- petstore_api$new() +# Configure HTTP basic authorization: http_auth +api_instance$api_client$username <- Sys.getenv("USERNAME") +api_instance$api_client$password <- Sys.getenv("PASSWORD") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$fake_api$add_pet_optional(pet = var_pet, data_file = "result.txt"), + api_instance$fake_api$add_pet_optional(pet = var_pet), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `add_pet_optional`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml, multipart/related + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + +# **fake_data_file** +> User fake_data_file(dummy, var_data_file = var.var_data_file) + +test data_file to ensure it's escaped correctly + + + +### Example +```R +library(petstore) + +# test data_file to ensure it's escaped correctly +# +# prepare function argument(s) +var_dummy <- "dummy_example" # character | dummy required parameter +var_var_data_file <- "var_data_file_example" # character | header data file (Optional) + +api_instance <- petstore_api$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$fake_api$fake_data_file(var_dummy, var_data_file = var_var_data_file, data_file = "result.txt"), + api_instance$fake_api$fake_data_file(var_dummy, var_data_file = var_var_data_file), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `fake_data_file`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **dummy** | **character**| dummy required parameter | + **var_data_file** | **character**| header data file | [optional] + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **fake_path_array** +> fake_path_array(path_array) + +test array parameter in path + + + +### Example +```R +library(petstore) + +# test array parameter in path +# +# prepare function argument(s) +var_path_array <- list("inner_example") # array[character] | dummy path parameter + +api_instance <- petstore_api$new() +result <- tryCatch( + api_instance$fake_api$fake_path_array(var_path_array), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `fake_path_array`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **path_array** | list( **character** )| dummy path parameter | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **fake_regular_expression** +> fake_regular_expression(reg_exp_test) + +test regular expression to ensure no exception + + + +### Example +```R +library(petstore) + +# test regular expression to ensure no exception +# +# prepare function argument(s) +var_reg_exp_test <- "reg_exp_test_example" # character | dummy required parameter + +api_instance <- petstore_api$new() +result <- tryCatch( + api_instance$fake_api$fake_regular_expression(var_reg_exp_test), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `fake_regular_expression`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **reg_exp_test** | **character**| dummy required parameter | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **fake_set_query** +> fake_set_query(set_dummy, array_dummy) + +test set query parameter + + + +### Example +```R +library(petstore) + +# test set query parameter +# +# prepare function argument(s) +var_set_dummy <- list("inner_example") # set[character] | set query +var_array_dummy <- list("inner_example") # array[character] | array query + +api_instance <- petstore_api$new() +result <- tryCatch( + api_instance$fake_api$fake_set_query(var_set_dummy, var_array_dummy), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `fake_set_query`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **set_dummy** | list( **character** )| set query | + **array_dummy** | list( **character** )| array query | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Mammal.md b/samples/client/petstore/R-httr2-wrapper/docs/Mammal.md new file mode 100644 index 0000000000..a2835af3f4 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Mammal.md @@ -0,0 +1,12 @@ +# petstore::Mammal + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**hasBaleen** | **character** | | [optional] +**hasTeeth** | **character** | | [optional] +**className** | **character** | | +**type** | **character** | | [optional] [Enum: [plains, mountain, grevys]] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/ModelApiResponse.md b/samples/client/petstore/R-httr2-wrapper/docs/ModelApiResponse.md new file mode 100644 index 0000000000..c761ca7d5e --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ +# petstore::ModelApiResponse + +Describes the result of uploading an image resource + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **integer** | | [optional] +**type** | **character** | | [optional] +**message** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/NestedOneOf.md b/samples/client/petstore/R-httr2-wrapper/docs/NestedOneOf.md new file mode 100644 index 0000000000..ecc2ed8914 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/NestedOneOf.md @@ -0,0 +1,10 @@ +# petstore::NestedOneOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**size** | **integer** | | [optional] +**nested_pig** | [**Pig**](Pig.md) | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/OneOfPrimitiveTypeTest.md b/samples/client/petstore/R-httr2-wrapper/docs/OneOfPrimitiveTypeTest.md new file mode 100644 index 0000000000..82cf318431 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/OneOfPrimitiveTypeTest.md @@ -0,0 +1,8 @@ +# petstore::OneOfPrimitiveTypeTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Order.md b/samples/client/petstore/R-httr2-wrapper/docs/Order.md new file mode 100644 index 0000000000..85860b2fb8 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Order.md @@ -0,0 +1,15 @@ +# petstore::Order + +An order for a pets from the pet store + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**petId** | **integer** | | [optional] +**quantity** | **integer** | | [optional] +**shipDate** | **character** | | [optional] +**status** | **character** | Order Status | [optional] [Enum: [placed, approved, delivered]] +**complete** | **character** | | [optional] [default to FALSE] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Pet.md b/samples/client/petstore/R-httr2-wrapper/docs/Pet.md new file mode 100644 index 0000000000..29186b2a14 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Pet.md @@ -0,0 +1,15 @@ +# petstore::Pet + +A pet for sale in the pet store + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **character** | | +**photoUrls** | **array[character]** | | +**tags** | [**array[Tag]**](Tag.md) | | [optional] +**status** | **character** | pet status in the store | [optional] [Enum: [available, pending, sold]] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/PetApi.md b/samples/client/petstore/R-httr2-wrapper/docs/PetApi.md new file mode 100644 index 0000000000..c7cc5d9569 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/PetApi.md @@ -0,0 +1,659 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +[**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +[**get_pet_by_id_streaming**](PetApi.md#get_pet_by_id_streaming) | **GET** /pet/{petId}?streaming | Find pet by ID (streaming) +[**test_header**](PetApi.md#test_header) | **GET** /pet_header_test | Header test +[**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image + + +# **add_pet** +> Pet add_pet(pet) + +Add a new pet to the store + + + +### Example +```R +library(petstore) + +# Add a new pet to the store +# +# prepare function argument(s) +var_pet <- Pet$new("name_example", list("photoUrls_example"), 123, Category$new(123, "name_example"), list(Tag$new(123, "name_example")), "available") # Pet | Pet object that needs to be added to the store + +api_instance <- petstore_api$new() +# Configure HTTP basic authorization: http_auth +api_instance$api_client$username <- Sys.getenv("USERNAME") +api_instance$api_client$password <- Sys.getenv("PASSWORD") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$add_pet(var_pet, data_file = "result.txt"), + api_instance$pet_api$add_pet(var_pet), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `add_pet`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml, multipart/related + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + +# **delete_pet** +> delete_pet(pet_id, api_key = var.api_key) + +Deletes a pet + + + +### Example +```R +library(petstore) + +# Deletes a pet +# +# prepare function argument(s) +var_pet_id <- 56 # integer | Pet id to delete +var_api_key <- "api_key_example" # character | (Optional) + +api_instance <- petstore_api$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + api_instance$pet_api$delete_pet(var_pet_id, api_key = var_api_key), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `delete_pet`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| Pet id to delete | + **api_key** | **character**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid pet value | - | + +# **find_pets_by_status** +> array[Pet] find_pets_by_status(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```R +library(petstore) + +# Finds Pets by status +# +# prepare function argument(s) +var_status <- list("available") # array[character] | Status values that need to be considered for filter + +api_instance <- petstore_api$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$find_pets_by_status(var_status, data_file = "result.txt"), + api_instance$pet_api$find_pets_by_status(var_status), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `find_pets_by_status`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | Enum [available, pending, sold] | Status values that need to be considered for filter | + +### Return type + +[**array[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + +# **find_pets_by_tags** +> array[Pet] find_pets_by_tags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```R +library(petstore) + +# Finds Pets by tags +# +# prepare function argument(s) +var_tags <- list("inner_example") # array[character] | Tags to filter by + +api_instance <- petstore_api$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$find_pets_by_tags(var_tags, data_file = "result.txt"), + api_instance$pet_api$find_pets_by_tags(var_tags), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `find_pets_by_tags`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | list( **character** )| Tags to filter by | + +### Return type + +[**array[Pet]**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + +# **get_pet_by_id** +> Pet get_pet_by_id(pet_id) + +Find pet by ID + +Returns a single pet + +### Example +```R +library(petstore) + +# Find pet by ID +# +# prepare function argument(s) +var_pet_id <- 56 # integer | ID of pet to return + +api_instance <- petstore_api$new() +# Configure HTTP bearer authorization: BearerToken +api_instance$api_client$bearer_token <- Sys.getenv("BEARER_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$get_pet_by_id(var_pet_id, data_file = "result.txt"), + api_instance$pet_api$get_pet_by_id(var_pet_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_pet_by_id`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[BearerToken](../README.md#BearerToken) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +# **get_pet_by_id_streaming** +> Pet get_pet_by_id_streaming(pet_id) + +Find pet by ID (streaming) + +Returns a single pet + +### Example +```R +library(petstore) + +# Find pet by ID (streaming) +# +# prepare function argument(s) +var_pet_id <- 56 # integer | ID of pet to return + +api_instance <- petstore_api$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$get_pet_by_id_streaming(var_pet_id, data_file = "result.txt"), + # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. + # api_instance$pet_api$get_pet_by_id_streaming(var_pet_id, stream_callback = function(x){ print(length(x)) }), + api_instance$pet_api$get_pet_by_id_streaming(var_pet_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_pet_by_id_streaming`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +# **test_header** +> Pet test_header(header_test_int) + +Header test + +Header test + +### Example +```R +library(petstore) + +# Header test +# +# prepare function argument(s) +var_header_test_int <- 56 # integer | header test int + +api_instance <- petstore_api$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$test_header(var_header_test_int, data_file = "result.txt"), + # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. + # api_instance$pet_api$test_header(var_header_test_int, stream_callback = function(x){ print(length(x)) }), + api_instance$pet_api$test_header(var_header_test_int), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `test_header`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **header_test_int** | **integer**| header test int | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +# **update_pet** +> Pet update_pet(pet) + +Update an existing pet + + + +### Example +```R +library(petstore) + +# Update an existing pet +# +# prepare function argument(s) +var_pet <- Pet$new("name_example", list("photoUrls_example"), 123, Category$new(123, "name_example"), list(Tag$new(123, "name_example")), "available") # Pet | Pet object that needs to be added to the store + +api_instance <- petstore_api$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$update_pet(var_pet, data_file = "result.txt"), + api_instance$pet_api$update_pet(var_pet), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `update_pet`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml, multipart/related + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + +# **update_pet_with_form** +> update_pet_with_form(pet_id, name = var.name, status = var.status) + +Updates a pet in the store with form data + + + +### Example +```R +library(petstore) + +# Updates a pet in the store with form data +# +# prepare function argument(s) +var_pet_id <- 56 # integer | ID of pet that needs to be updated +var_name <- "name_example" # character | Updated name of the pet (Optional) +var_status <- "status_example" # character | Updated status of the pet (Optional) + +api_instance <- petstore_api$new() +result <- tryCatch( + api_instance$pet_api$update_pet_with_form(var_pet_id, name = var_name, status = var_status), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `update_pet_with_form`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| ID of pet that needs to be updated | + **name** | **character**| Updated name of the pet | [optional] + **status** | **character**| Updated status of the pet | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + +# **upload_file** +> ModelApiResponse upload_file(pet_id, additional_metadata = var.additional_metadata, file = var.file) + +uploads an image + + + +### Example +```R +library(petstore) + +# uploads an image +# +# prepare function argument(s) +var_pet_id <- 56 # integer | ID of pet to update +var_additional_metadata <- "additional_metadata_example" # character | Additional data to pass to server (Optional) +var_file <- File.new('/path/to/file') # data.frame | file to upload (Optional) + +api_instance <- petstore_api$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$upload_file(var_pet_id, additional_metadata = var_additional_metadata, file = var_file, data_file = "result.txt"), + api_instance$pet_api$upload_file(var_pet_id, additional_metadata = var_additional_metadata, file = var_file), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `upload_file`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| ID of pet to update | + **additional_metadata** | **character**| Additional data to pass to server | [optional] + **file** | **data.frame**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Pig.md b/samples/client/petstore/R-httr2-wrapper/docs/Pig.md new file mode 100644 index 0000000000..7906011bd4 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Pig.md @@ -0,0 +1,11 @@ +# petstore::Pig + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | +**size** | **integer** | | + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Special.md b/samples/client/petstore/R-httr2-wrapper/docs/Special.md new file mode 100644 index 0000000000..83c2794ec3 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Special.md @@ -0,0 +1,16 @@ +# petstore::Special + +Describes the result of uploading an image resource + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**set_test** | **set[character]** | | [optional] +**item_self** | **integer** | | [optional] +**item_private** | **character** | | [optional] +**item_super** | **character** | | [optional] +**123_number** | **character** | | [optional] +**array[test]** | **character** | | [optional] +**empty_string** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/StoreApi.md b/samples/client/petstore/R-httr2-wrapper/docs/StoreApi.md new file mode 100644 index 0000000000..91cfa8e765 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/StoreApi.md @@ -0,0 +1,251 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +[**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +[**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet + + +# **delete_order** +> delete_order(order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```R +library(petstore) + +# Delete purchase order by ID +# +# prepare function argument(s) +var_order_id <- "order_id_example" # character | ID of the order that needs to be deleted + +api_instance <- petstore_api$new() +result <- tryCatch( + api_instance$store_api$delete_order(var_order_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `delete_order`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **character**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +# **get_inventory** +> map(integer) get_inventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```R +library(petstore) + +# Returns pet inventories by status +# + +api_instance <- petstore_api$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$store_api$get_inventory(data_file = "result.txt"), + api_instance$store_api$get_inventory(), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_inventory`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**map(integer)** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **get_order_by_id** +> Order get_order_by_id(order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```R +library(petstore) + +# Find purchase order by ID +# +# prepare function argument(s) +var_order_id <- 56 # integer | ID of pet that needs to be fetched + +api_instance <- petstore_api$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$store_api$get_order_by_id(var_order_id, data_file = "result.txt"), + api_instance$store_api$get_order_by_id(var_order_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_order_by_id`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **integer**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +# **place_order** +> Order place_order(order) + +Place an order for a pet + + + +### Example +```R +library(petstore) + +# Place an order for a pet +# +# prepare function argument(s) +var_order <- Order$new(123, 123, 123, "shipDate_example", "placed", "complete_example") # Order | order placed for purchasing the pet + +api_instance <- petstore_api$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$store_api$place_order(var_order, data_file = "result.txt"), + api_instance$store_api$place_order(var_order), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `place_order`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Tag.md b/samples/client/petstore/R-httr2-wrapper/docs/Tag.md new file mode 100644 index 0000000000..3cb9bd184d --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Tag.md @@ -0,0 +1,11 @@ +# petstore::Tag + +A tag for a pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**name** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/UpdatePetRequest.md b/samples/client/petstore/R-httr2-wrapper/docs/UpdatePetRequest.md new file mode 100644 index 0000000000..619f0b2262 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/UpdatePetRequest.md @@ -0,0 +1,10 @@ +# petstore::UpdatePetRequest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**jsonData** | [**Pet**](Pet.md) | | [optional] +**binaryDataN2Information** | **data.frame** | | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/User.md b/samples/client/petstore/R-httr2-wrapper/docs/User.md new file mode 100644 index 0000000000..98d0316ea2 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/User.md @@ -0,0 +1,17 @@ +# petstore::User + +A User who is purchasing from the pet store + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**username** | **character** | | [optional] +**firstName** | **character** | | [optional] +**lastName** | **character** | | [optional] +**email** | **character** | | [optional] +**password** | **character** | | [optional] +**phone** | **character** | | [optional] +**userStatus** | **integer** | User Status | [optional] + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/UserApi.md b/samples/client/petstore/R-httr2-wrapper/docs/UserApi.md new file mode 100644 index 0000000000..4417f05e9b --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/UserApi.md @@ -0,0 +1,484 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_user**](UserApi.md#create_user) | **POST** /user | Create user +[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +[**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +[**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +[**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system +[**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +[**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +# **create_user** +> create_user(user) + +Create user + +This can only be done by the logged in user. + +### Example +```R +library(petstore) + +# Create user +# +# prepare function argument(s) +var_user <- User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123) # User | Created user object + +api_instance <- petstore_api$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$user_api$create_user(var_user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `create_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +# **create_users_with_array_input** +> create_users_with_array_input(user) + +Creates list of users with given input array + + + +### Example +```R +library(petstore) + +# Creates list of users with given input array +# +# prepare function argument(s) +var_user <- list(User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123)) # array[User] | List of user object + +api_instance <- petstore_api$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$user_api$create_users_with_array_input(var_user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `create_users_with_array_input`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | list( [**User**](User.md) )| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +# **create_users_with_list_input** +> create_users_with_list_input(user) + +Creates list of users with given input array + + + +### Example +```R +library(petstore) + +# Creates list of users with given input array +# +# prepare function argument(s) +var_user <- list(User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123)) # array[User] | List of user object + +api_instance <- petstore_api$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$user_api$create_users_with_list_input(var_user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `create_users_with_list_input`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | list( [**User**](User.md) )| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +# **delete_user** +> delete_user(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```R +library(petstore) + +# Delete user +# +# prepare function argument(s) +var_username <- "username_example" # character | The name that needs to be deleted + +api_instance <- petstore_api$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$user_api$delete_user(var_username), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `delete_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **character**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +# **get_user_by_name** +> User get_user_by_name(username) + +Get user by user name + + + +### Example +```R +library(petstore) + +# Get user by user name +# +# prepare function argument(s) +var_username <- "username_example" # character | The name that needs to be fetched. Use user1 for testing. + +api_instance <- petstore_api$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$user_api$get_user_by_name(var_username, data_file = "result.txt"), + api_instance$user_api$get_user_by_name(var_username), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_user_by_name`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **character**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +# **login_user** +> character login_user(username, password) + +Logs user into the system + + + +### Example +```R +library(petstore) + +# Logs user into the system +# +# prepare function argument(s) +var_username <- "username_example" # character | The user name for login +var_password <- "password_example" # character | The password for login in clear text + +api_instance <- petstore_api$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$user_api$login_user(var_username, var_password, data_file = "result.txt"), + api_instance$user_api$login_user(var_username, var_password), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `login_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **character**| The user name for login | + **password** | **character**| The password for login in clear text | + +### Return type + +**character** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
        * X-Rate-Limit - calls per hour allowed by the user
        * X-Expires-After - date in UTC when token expires
        | +| **400** | Invalid username/password supplied | - | + +# **logout_user** +> logout_user() + +Logs out current logged in user session + + + +### Example +```R +library(petstore) + +# Logs out current logged in user session +# + +api_instance <- petstore_api$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$user_api$logout_user(), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `logout_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +# **update_user** +> update_user(username, user) + +Updated user + +This can only be done by the logged in user. + +### Example +```R +library(petstore) + +# Updated user +# +# prepare function argument(s) +var_username <- "username_example" # character | name that need to be deleted +var_user <- User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123) # User | Updated user object + +api_instance <- petstore_api$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$user_api$update_user(var_username, var_user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `update_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **character**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Whale.md b/samples/client/petstore/R-httr2-wrapper/docs/Whale.md new file mode 100644 index 0000000000..bd0d148686 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Whale.md @@ -0,0 +1,11 @@ +# petstore::Whale + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**hasBaleen** | **character** | | [optional] +**hasTeeth** | **character** | | [optional] +**className** | **character** | | + + diff --git a/samples/client/petstore/R-httr2-wrapper/docs/Zebra.md b/samples/client/petstore/R-httr2-wrapper/docs/Zebra.md new file mode 100644 index 0000000000..51b7094126 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/docs/Zebra.md @@ -0,0 +1,10 @@ +# petstore::Zebra + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | **character** | | [optional] [Enum: [plains, mountain, grevys]] +**className** | **character** | | + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/git_push.sh b/samples/client/petstore/R-httr2-wrapper/git_push.sh similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/git_push.sh rename to samples/client/petstore/R-httr2-wrapper/git_push.sh diff --git a/samples/client/petstore/R-httr2-wrapper/pom.xml b/samples/client/petstore/R-httr2-wrapper/pom.xml new file mode 100644 index 0000000000..10fca31875 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + org.openapitools + RHttr2WrapperClientTests + pom + 1.0-SNAPSHOT + R Httr2 Wrapper Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + nose-test + integration-test + + exec + + + bash + + build_and_test.bash + + + + + + + + diff --git a/samples/client/petstore/R-httr2-wrapper/test_petstore.R b/samples/client/petstore/R-httr2-wrapper/test_petstore.R new file mode 100644 index 0000000000..de9bdcab69 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/test_petstore.R @@ -0,0 +1,241 @@ + +install.packages("petstore_1.0.0.tar.gz",repos=NULL, type="source") +library(petstore) +library(jsonlite) + + + +var_status <- list("something inside", "explode please", "123") # array[character] | Status values that need to be considered for filter + +# Finds Pets by status +api_instance <- petstore_api$new() +# Configure OAuth2 access token for authorization: petstore_auth +#api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$find_pets_by_status(var_status, data_file = "result.txt"), + api_instance$pet_api$find_pets_by_status(var_status), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `find_pets_by_status`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result) +} + + + +var_tags <- c("innerzzzzzzz", "second,example", "345") # array[character] | Tags to filter by + +# Finds Pets by tags +api_instance <- petstore_api$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$pet_api$find_pets_by_tags(var_tags, data_file = "result.txt"), + api_instance$pet_api$find_pets_by_tags(var_tags), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `find_pets_by_tags`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result) +} + +invokeRestart("abort") + +t <- Tag$new() +t$id <- 123 +t$additional_properties <- c("abc" = 849, "array" = list('a', 'b', 'c')) +t$additional_properties +t$additional_properties["abc"] +t$additional_properties["array"] + +print(t) +#print(t$toJSON()) +#print(t$toJSONString()) + +print("done tag") + + whale_json <- '{"className": "whale", "hasBaleen": true, "hasTeeth": true}' + zebra_json <- '{"className": "zebra", "type": "plains"}' + + mammal <- Mammal$new() + mammal$fromJSON(whale_json) + +api_client <- ApiClient$new() +api_client$username <- "username999" +api_client$password <- "password888" + +api_wrapper <- petstore_api$new(api_client) +# test api_client in pet_api of the wrapper +cat(api_wrapper$pet_api$api_client$username) +cat(api_wrapper$pet_api$api_client$password) + +#cat(address(api_client)) +#cat(address(api_wrapper$pet_api$api_client) +#cat(address(api_wrapper$api_client$api_client) + +print("DONE") + +var_pet <- Pet$new("name_example", list("photoUrls_example"), 56, Category$new(56, "name_example"), list(Tag$new(56, "name_example")), "available") # Pet | Pet object that needs to be added to the store +print(var_pet) + +print("DONE print") +#Add a new pet to the store +api_instance <- PetApi$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$AddPet(var_pet, data_file = "result.txt"), + api_instance$add_pet(var_pet), + ApiException = function(ex) ex + ) + +var_pet_id <- 56 # integer | ID of pet to return + +pet_response <- api_instance$get_pet_by_id(var_pet_id, data_file = "get_pet_by_id.json") +response <- read_json("get_pet_by_id.json") +dput(response) +# +## test streaming +#api_instance$get_pet_by_id_streaming(var_pet_id, stream_callback = function(x) { print(x) }) + +##Find pet by ID (streaming) +#api_instance <- PetApi$new() +## Configure API key authorization: api_key +#api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#result <- tryCatch( +# # to save the result into a file, simply add the optional `data_file` parameter, e.g. +# # api_instance$GetPetByIdStreaming(var_pet_id, data_file = "result.txt"), +# api_instance$GetPetByIdStreaming(var_pet_id, stream_callback = function(x) { print(x) }), +# ApiException = function(ex) ex +# ) +# In case of error, print the error object +#if (!is.null(result$ApiException)) { +# cat(result$ApiException$toString()) +#} #else { +# # deserialized response object +# response.object <- result$content +# # response headers +# response.headers <- result$response$headers +# # response status code +# response.status.code <- result$response$status_code +#} + +##errorMsg <- "{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}" +###errorMsg <- '{"code": 404, "message": "Not found"}' +##a <- ModelApiResponse$new()$fromJSONString(errorMsg) +##dput(a) +## +##var_pet_id <- 1231256 # integer | ID of pet to return +## +###Find pet by ID +##api_instance <- PetApi$new() +### Configure API key authorization: api_key +##api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +##result <- tryCatch( +## api_instance$GetPetById(var_pet_id), +## ApiException = function(ex) ex +## ) +### In case of error, print the error object +##if(!is.null(result$ApiException)) { +## cat(result$ApiException$toString()) +##} else { +## # deserialized response object +## response.object <- result$content +## # response headers +## response.headers <- result$response$headers +## # response status code +## response.status.code <- result$response$status_code +##} +# +#json2 <- +#'{"name": "pet", "photoUrls" : ["http://a.com", "http://b.com"]}' +# +#jsonlite::minify(json2) +# +#pet_api <- PetApi$new() +#pet_id <- 123321 +#pet <- Pet$new("name_test", +# photoUrls = list("photo_test", "second test"), +# category = Category$new(id = 450, name = "test_cat"), +# id = pet_id, +# tags = list( +# Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown") +# ), +# status = "available" +#) +# +##jsonlite::minify(pet$toJSONString()) +##cat(pet$toJSONString()) +#toString(pet$toString()) +# +##json <- +##'[ +## {"Name" : "Mario", "Age" : 32, "Occupation" : "Plumber"}, +## {"Name" : "Peach", "Age" : 21, "Occupation" : "Princess"}, +## {}, +## {"Name" : "Bowser", "Occupation" : "Koopa"} +##]' +## +## +###Pet$public_methods +###Pet$public_methods$fromJSON(json) +###Pet$public_methods$toJson() +###Pet$public_methods$validateJSON(json2) +###Pet$public_methods$validateJson(json) +###Pet$my_static_method <- function(x) { x + 2} +###Pet$public_methods$my_static_method(1) +## +# basque_pig_json <- +# '{"className2": "BasquePig", "color": "red"}' +## +## danish_pig_json <- +## '{"className2": "DanishPig", "size": 7}' +## +## wrong_json <- +## '[ +## {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"}, +## {}, +## {"Name" : "Ada", "Occupation" : "Engineer"} +## ]' +## +## print("==========") +# pig <- Pig$new() +# basque_pig <- pig$fromJSON(basque_pig_json) +## #print(basque_pig$actual_instance$color) +## #expect_equal(basque_pig$actual_type, "BasquePig") +## pig$fromJSON(danish_pig_json) +## #pig$fromJSON(wrong_json) +## pig$toJSON() +## +## #d <- DanishPig$new() +## #dp <- d$validateJSON(danish_pig_json) +## +## +# +## test nested oneOf +#nested_oneof <- NestedOneOf$new() +#nested_oneof$nested_pig <- pig +#nested_oneof$size <- 15 +# +#cat(nested_oneof$toJSONString()) +# + + + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat.R new file mode 100644 index 0000000000..d67bd9cf23 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat.R @@ -0,0 +1,4 @@ +library(testthat) +library(petstore) + +test_check("petstore") diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_allof_tag_api_response.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_allof_tag_api_response.R new file mode 100644 index 0000000000..90a5d04d3f --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_allof_tag_api_response.R @@ -0,0 +1,41 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test AllofTagApiResponse") + +model_instance <- AllofTagApiResponse$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("name", { + # tests for the property `name` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`name`, "EXPECTED_RESULT") +}) + +test_that("code", { + # tests for the property `code` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`code`, "EXPECTED_RESULT") +}) + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) + +test_that("message", { + # tests for the property `message` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`message`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_animal.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_animal.R new file mode 100644 index 0000000000..4402cf03c5 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_animal.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Animal") + +model_instance <- Animal$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_any_of_pig.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_any_of_pig.R new file mode 100644 index 0000000000..8ca3b8e73d --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_any_of_pig.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test AnyOfPig") + +model_instance <- AnyOfPig$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) + +test_that("size", { + # tests for the property `size` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`size`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_any_of_primitive_type_test.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_any_of_primitive_type_test.R new file mode 100644 index 0000000000..0679cfaf44 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_any_of_primitive_type_test.R @@ -0,0 +1,4 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test AnyOfPrimitiveTypeTest") diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_basque_pig.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_basque_pig.R new file mode 100644 index 0000000000..400268563d --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_basque_pig.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test BasquePig") + +model_instance <- BasquePig$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_cat.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_cat.R new file mode 100644 index 0000000000..ab85fe3340 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_cat.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Cat") + +model_instance <- Cat$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) + +test_that("declawed", { + # tests for the property `declawed` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`declawed`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_cat_all_of.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_cat_all_of.R new file mode 100644 index 0000000000..83ee2fb835 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_cat_all_of.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test CatAllOf") + +model_instance <- CatAllOf$new() + +test_that("declawed", { + # tests for the property `declawed` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`declawed`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_category.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_category.R new file mode 100644 index 0000000000..c7838edeb6 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_category.R @@ -0,0 +1,21 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Category") + +model.instance <- Category$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("name", { + # tests for the property `name` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`name`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_danish_pig.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_danish_pig.R new file mode 100644 index 0000000000..a7c2811d89 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_danish_pig.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test DanishPig") + +model_instance <- DanishPig$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("size", { + # tests for the property `size` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`size`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_date.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_date.R new file mode 100644 index 0000000000..214fd8a352 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_date.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Date") + +model_instance <- Date$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dog.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dog.R new file mode 100644 index 0000000000..9c04cc7806 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dog.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Dog") + +model_instance <- Dog$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) + +test_that("breed", { + # tests for the property `breed` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`breed`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dog_all_of.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dog_all_of.R new file mode 100644 index 0000000000..6d11847f66 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_dog_all_of.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test DogAllOf") + +model_instance <- DogAllOf$new() + +test_that("breed", { + # tests for the property `breed` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`breed`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_fake_api.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_fake_api.R new file mode 100644 index 0000000000..7514044ac1 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_fake_api.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test FakeApi") + +api.instance <- FakeApi$new() + +test_that("FakeDataFile", { + # tests for FakeDataFile + # base path: http://petstore.swagger.io/v2 + # test data_file to ensure it's escaped correctly + # + # @param dummy character dummy required parameter + # @param DataFile. character header data file (optional) + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_mammal.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_mammal.R new file mode 100644 index 0000000000..bc061ea799 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_mammal.R @@ -0,0 +1,34 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Mammal") + +model_instance <- Mammal$new() + +test_that("hasBaleen", { + # tests for the property `hasBaleen` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasBaleen`, "EXPECTED_RESULT") +}) + +test_that("hasTeeth", { + # tests for the property `hasTeeth` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasTeeth`, "EXPECTED_RESULT") +}) + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_model_api_response.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_model_api_response.R new file mode 100644 index 0000000000..d5dcef5716 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_model_api_response.R @@ -0,0 +1,28 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test ModelApiResponse") + +model.instance <- ModelApiResponse$new() + +test_that("code", { + # tests for the property `code` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`code`, "EXPECTED_RESULT") +}) + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) + +test_that("message", { + # tests for the property `message` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`message`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_nested_one_of.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_nested_one_of.R new file mode 100644 index 0000000000..940a7fba2a --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_nested_one_of.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test NestedOneOf") + +model_instance <- NestedOneOf$new() + +test_that("size", { + # tests for the property `size` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`size`, "EXPECTED_RESULT") +}) + +test_that("nested_pig", { + # tests for the property `nested_pig` (Pig) + + # uncomment below to test the property + #expect_equal(model.instance$`nested_pig`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_one_of_primitive_type_test.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_one_of_primitive_type_test.R new file mode 100644 index 0000000000..f9e7158359 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_one_of_primitive_type_test.R @@ -0,0 +1,4 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test OneOfPrimitiveTypeTest") diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_order.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_order.R new file mode 100644 index 0000000000..33b8752025 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_order.R @@ -0,0 +1,50 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Order") + +model.instance <- Order$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("petId", { + # tests for the property `petId` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`petId`, "EXPECTED_RESULT") +}) + +test_that("quantity", { + # tests for the property `quantity` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`quantity`, "EXPECTED_RESULT") +}) + +test_that("shipDate", { + # tests for the property `shipDate` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`shipDate`, "EXPECTED_RESULT") +}) + +test_that("status", { + # tests for the property `status` (character) + # Order Status + + # uncomment below to test the property + #expect_equal(model.instance$`status`, "EXPECTED_RESULT") +}) + +test_that("complete", { + # tests for the property `complete` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`complete`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_pet.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_pet.R new file mode 100644 index 0000000000..ac3e4f31dd --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_pet.R @@ -0,0 +1,50 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Pet") + +model.instance <- Pet$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("category", { + # tests for the property `category` (Category) + + # uncomment below to test the property + #expect_equal(model.instance$`category`, "EXPECTED_RESULT") +}) + +test_that("name", { + # tests for the property `name` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`name`, "EXPECTED_RESULT") +}) + +test_that("photoUrls", { + # tests for the property `photoUrls` (array[character]) + + # uncomment below to test the property + #expect_equal(model.instance$`photoUrls`, "EXPECTED_RESULT") +}) + +test_that("tags", { + # tests for the property `tags` (array[Tag]) + + # uncomment below to test the property + #expect_equal(model.instance$`tags`, "EXPECTED_RESULT") +}) + +test_that("status", { + # tests for the property `status` (character) + # pet status in the store + + # uncomment below to test the property + #expect_equal(model.instance$`status`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_pet_api.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_pet_api.R new file mode 100644 index 0000000000..7fbdd1a70d --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_pet_api.R @@ -0,0 +1,103 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test PetApi") + +api.instance <- PetApi$new() + +test_that("AddPet", { + # tests for AddPet + # base path: http://petstore.swagger.io/v2 + # Add a new pet to the store + # @param body Pet Pet object that needs to be added to the store + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("DeletePet", { + # tests for DeletePet + # base path: http://petstore.swagger.io/v2 + # Deletes a pet + # @param pet.id integer Pet id to delete + # @param api.key character (optional) + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("FindPetsByStatus", { + # tests for FindPetsByStatus + # base path: http://petstore.swagger.io/v2 + # Finds Pets by status + # Multiple status values can be provided with comma separated strings + # @param status array[character] Status values that need to be considered for filter + # @return [array[Pet]] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("FindPetsByTags", { + # tests for FindPetsByTags + # base path: http://petstore.swagger.io/v2 + # Finds Pets by tags + # Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + # @param tags array[character] Tags to filter by + # @return [array[Pet]] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("GetPetById", { + # tests for GetPetById + # base path: http://petstore.swagger.io/v2 + # Find pet by ID + # Returns a single pet + # @param pet.id integer ID of pet to return + # @return [Pet] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("UpdatePet", { + # tests for UpdatePet + # base path: http://petstore.swagger.io/v2 + # Update an existing pet + # @param body Pet Pet object that needs to be added to the store + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("UpdatePetWithForm", { + # tests for UpdatePetWithForm + # base path: http://petstore.swagger.io/v2 + # Updates a pet in the store with form data + # @param pet.id integer ID of pet that needs to be updated + # @param name character Updated name of the pet (optional) + # @param status character Updated status of the pet (optional) + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("UploadFile", { + # tests for UploadFile + # base path: http://petstore.swagger.io/v2 + # uploads an image + # @param pet.id integer ID of pet to update + # @param additional.metadata character Additional data to pass to server (optional) + # @param file data.frame file to upload (optional) + # @return [ModelApiResponse] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_petstore.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_petstore.R new file mode 100644 index 0000000000..7c19739714 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_petstore.R @@ -0,0 +1,615 @@ +context("basic functionality") + +## create api_client to test the wrapper +api_client <- ApiClient$new() +api_client$username <- "username999" +api_client$password <- "password888" + +## create a new pet and add to petstore server +pet_api <- PetApi$new() +pet_id <- 123321 +pet <- Pet$new("name_test", + photoUrls = list("photo_test", "second test"), + category = Category$new(id = 450, name = "test_cat"), + id = pet_id, + tags = list( + Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown") + ), + status = "available" +) +pet_api$api_client$username <- "username123" +pet_api$api_client$password <- "password123" +result <- pet_api$add_pet(pet) + +test_that("Test discriminator and mapping", { + d <- '{"breed": "bulldog","color":"white","className":"Dog"}' + dog <- ApiClient$new()$deserialize(d, "Animal", loadNamespace("petstore")) + expect_equal(class(dog)[1], "Dog") + expect_equal(dog$breed, "bulldog") + expect_equal(dog$color, "white") + expect_equal(dog$className, "Dog") +}) + +test_that("Invalid enum value test", { + expect_error(Pet$new("name_test", + photoUrls = list("photo_test", "second test"), + category = Category$new(id = 450, name = "test_cat"), + id = pet_id, + tags = list( + Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown") + ), + status = "error_available" + ), "Error! \"error_available\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".") +}) + +test_that("Additional Properties test", { + # test tag + t <- Tag$new(id = 393, name = "something") + t$additional_properties <- c("a1" = 998, "b2" = "bbccdd") + expect_equal(t$toJSONString(), "{\"id\":393,\"name\":\"something\",\"a1\":\"998\",\"b2\":\"bbccdd\"}") + + # test tag with additional_properties in `new` + t <- Tag$new(id = 393, name = "something", additional_properties = list("nested_object" = list("inside_item" = 8989))) + expect_equal(t$toJSONString(), "{\"id\":393,\"name\":\"something\",\"nested_object\":{\"inside_item\":8989}}") + + # test fromJSONString + json <- "{\"id\":393,\"name\":\"something\",\"a1\":\"998\",\"b2\":\"bbccdd\"}" + t2 <- Tag$new() + t2$fromJSONString(json) + expect_equal(t2$id, 393) + expect_equal(t2$name, "something") + expect_equal(t2$additional_properties[["a1"]], "998") + expect_equal(t2$additional_properties[["b2"]], "bbccdd") +}) + +test_that("Test toJSON toJSONString fromJSON fromJSONString print", { + # test pet + expect_equal(pet_id, 123321) + expect_equal(pet$toJSONString(), '{"id":123321,"category":{"id":450,"name":"test_cat"},"name":"name_test","photoUrls":["photo_test","second test"],"tags":[{"id":123,"name":"tag_test"},{"id":456,"name":"unknown"}],"status":"available"}') + print(pet) # should not return anything and output the result to the console + + # tests for other pet objects + pet0 <- Pet$new() + jsonpet <- pet0$toJSON() + pet2 <- pet0$fromJSON( + jsonlite::toJSON(jsonpet, auto_unbox = TRUE) + ) + expect_equal(pet0, pet2) + jsonpet <- pet0$toJSONString() + pet2 <- pet0$fromJSON( + jsonpet + ) + expect_equal(pet0, pet2) + + jsonpet <- pet0$toJSONString() + pet2 <- pet0$fromJSONString( + jsonpet + ) + expect_equal(pet0, pet2) + + pet1 <- Pet$new("name_test", + list("photo_test", "second test"), + category = Category$new(id = 450, name = "test_cat"), + id = pet_id, + tags = list( + Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown") + ), + status = "available" + ) + jsonpet <- pet1$toJSON() + pet2 <- pet1$fromJSON( + jsonlite::toJSON(jsonpet, auto_unbox = TRUE) + ) + expect_equal(pet1, pet2) + + jsonpet <- pet1$toJSONString() + pet2 <- pet1$fromJSON( + jsonpet + ) + expect_equal(pet1, pet2) + + jsonpet <- pet1$toJSONString() + pet2 <- pet1$fromJSONString( + jsonpet + ) + expect_equal(pet1, pet2) +}) + +test_that("Test Category", { + c1 <- Category$new(id = 450, name = "test_cat") + c2 <- Category$new() + c2$fromJSON(jsonlite::toJSON(c1$toJSON(), auto_unbox = TRUE)) + expect_equal(c1, c2) + c2$fromJSONString(c1$toJSONString()) + expect_equal(c1, c2) +}) + +test_that("get_pet_by_id", { + response <- pet_api$get_pet_by_id(pet_id) + expect_equal(response$id, pet_id) + expect_equal(response$name, "name_test") + expect_equal( + response$photoUrls, + list("photo_test", "second test") + ) + expect_equal(response$status, "available") + expect_equal(response$category, Category$new(id = 450, name = "test_cat")) + + expect_equal(pet$tags, response$tags) + expect_equal( + response$tags, + list(Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown")) + ) +}) + +test_that("get_pet_by_id via wrapper", { + api_wrapper <- petstore_api$new(api_client) + # test api_client in pet_api of the wrapper + expect_false(is.null(api_wrapper$pet_api$api_client)) + expect_equal(api_wrapper$pet_api$api_client$username, "username999") + expect_equal(api_wrapper$pet_api$api_client$password, "password888") + + # test api_client in user_api of the wrapper + expect_equal(api_wrapper$user_api$api_client$username, "username999") + expect_equal(api_wrapper$user_api$api_client$password, "password888") + + response <- api_wrapper$pet_api$get_pet_by_id(pet_id) + expect_equal(response$id, pet_id) + expect_equal(response$name, "name_test") + expect_equal( + response$photoUrls, + list("photo_test", "second test") + ) + expect_equal(response$status, "available") + expect_equal(response$category, Category$new(id = 450, name = "test_cat")) + + expect_equal(pet$tags, response$tags) + expect_equal( + response$tags, + list(Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown")) + ) +}) + +test_that("update_pet_with_form", { + ## add pet + update_pet_id <- 123999 + update_pet <- Pet$new("name_test", + photoUrls = list("photo_test", "second test"), + category = Category$new(id = 450, name = "test_cat"), + id = update_pet_id, + tags = list( + Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown") + ), + status = "available" + ) + pet_api$api_client$username <- "username123" + pet_api$api_client$password <- "password123" + result <- pet_api$add_pet(update_pet) + + ## update pet with form + pet_api$api_client$oauth_client_id <- "client_id_aaa" + pet_api$api_client$oauth_secret <- "secrete_bbb" + pet_api$api_client$oauth_scopes <- "write:pets read:pets" + update_result <- pet_api$update_pet_with_form(update_pet_id, name = "pet2", status = "sold") + + # get pet + response <- pet_api$get_pet_by_id(update_pet_id) + expect_equal(response$id, update_pet_id) + expect_equal(response$name, "pet2") + expect_equal(response$status, "sold") + expect_equal( + response$photoUrls, + list("photo_test", "second test") + ) + expect_equal(response$category, Category$new(id = 450, name = "test_cat")) + + expect_equal(pet$tags, response$tags) + expect_equal( + response$tags, + list(Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown")) + ) +}) + +test_that("get_pet_by_id_streaming", { + result <- tryCatch( + pet_api$get_pet_by_id_streaming(pet_id, stream_callback = function(x) { print(x) }), + ApiException = function(ex) ex + ) +}) + +test_that("Test header parameters", { + # test exception + result <- tryCatch(pet_api$test_header(45345), + ApiException = function(ex) ex + ) + + expect_true(!is.null(result)) + expect_true(!is.null(result$ApiException)) + expect_equal(result$ApiException$status, 404) + # test error object `ApiResponse` + #expect_equal(result$ApiException$error_object$toString(), "{\"code\":404,\"type\":\"unknown\",\"message\":\"null for uri: http://pet\n x[1]: store.swagger.io/v2/pet_header_test\"}") + expect_equal(result$ApiException$error_object$code, 404) +}) + + +test_that("Test GetPetById exception", { + # test exception + result <- tryCatch(pet_api$get_pet_by_id(98765), # petId not exist + ApiException = function(ex) ex + ) + + expect_true(!is.null(result)) + expect_true(!is.null(result$ApiException)) + expect_equal(result$ApiException$status, 404) + # test error object `ApiResponse` + expect_equal(result$ApiException$error_object$toString(), "{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}") + expect_equal(result$ApiException$error_object$code, 1) +}) + +test_that("GetPetById with data_file", { + # test to ensure json is saved to the file `get_pet_by_id.json` + pet_response <- pet_api$get_pet_by_id(pet_id, data_file = "get_pet_by_id.json") + response <- read_json("get_pet_by_id.json") + expect_true(!is.null(response)) + expect_equal(response$id, pet_id) + expect_equal(response$name, "name_test") +}) + +test_that("array test in path parameters", { + fake_api <- FakeApi$new() + # array input for path parameter + #array_dummy <- list(1, 2, 2, 3) + array_dummy <- list("hello world", "1&2") + expect_error(fake_api$fake_path_array(array_dummy), "") +}) + +test_that("optional body parameters test", { + fake_api <- FakeApi$new() + expect_error(fake_api$add_pet_optional(), "") + + pet_optional_test <- Pet$new("name_test", + photoUrls = list("photo_test", "second test"), + category = Category$new(id = 44550, name = "test_cat"), + id = 44550, + tags = list( + Tag$new(id = 44550, name = "tag_test"), Tag$new(id = 4880, name = "unknown 2") + ), + status = "available" + ) + expect_error(fake_api$add_pet_optional(pet_optional_test), "") + #result <- fake_api$add_pet_optional(pet_optional_test) + + #response <- pet_api$get_pet_by_id(44550) + #expect_equal(response$id, 44550) + #expect_equal(response$name, "name_test") + #expect_equal( + # response$photoUrls, + # list("photo_test", "second test") + #) + #expect_equal(response$status, "available") + #expect_equal(response$category, Category$new(id = 44500, name = "test_cat")) + + #expect_equal(pet$tags, response$tags) + #expect_equal( + # response$tags, + # list(Tag$new(id = 44550, name = "tag_test"), Tag$new(id = 4880, name = "unknown")) + #) +}) + +test_that("set validation test", { + fake_api <- FakeApi$new() + # array input invalid (not unique) + set_dummy <- list(1, 2, 2, 3) + array_dummy <- list(1, 2, 2, 3) + result <- tryCatch(fake_api$fake_set_query(set_dummy, array_dummy), + ApiException = function(ex) ex + ) + + expect_equal(result$ApiException$reason, "Invalid value for `set_dummy` when calling FakeApi$fake_set_query. Items must be unique.") + + # vector input invalid (not unique) + set_dummy <- c(1, 2, 2, 3) + array_dummy <- c(1, 2, 2, 3) + result <- tryCatch(fake_api$fake_set_query(set_dummy, array_dummy), + ApiException = function(ex) ex + ) + + expect_equal(result$ApiException$reason, "Invalid value for `set_dummy` when calling FakeApi$fake_set_query. Items must be unique.") +}) + +test_that("find_pets_by_status", { + # input invalid + var_status <- c("something") # array[character] | Tags to filter by + result <- tryCatch(pet_api$find_pets_by_status(var_status), + ApiException = function(ex) ex + ) + + expect_equal(result$ApiException$reason, "Invalid value for `status` when calling PetApi$find_pets_by_status. Must be [available, pending, sold].") +}) + +test_that("find_pets_by_tags", { + pet_tag_test <- Pet$new("name_test", + photoUrls = list("photo_test", "second test"), + category = Category$new(id = 4455, name = "test_cat"), + id = 4455, + tags = list( + Tag$new(id = 4455, name = "tag_test"), Tag$new(id = 488, name = "unknown 2") + ), + status = "available" + ) + result <- pet_api$add_pet(pet_tag_test) + + # vector as input + var_tags <- c("unknown", "unknown 2") # array[character] | Tags to filter by + result <- pet_api$find_pets_by_tags(var_tags) + expect_true(!is.null(result)) + expect_equal(result[[1]]$id, 123321) + expect_equal(result[[2]]$id, 123999) + expect_equal(result[[3]]$id, 4455) + + # list as input + var_tags <- list("unknown", "unknown 2") # array[character] | Tags to filter by + result <- pet_api$find_pets_by_tags(var_tags) + expect_true(!is.null(result)) + expect_equal(result[[1]]$id, 123321) + expect_equal(result[[2]]$id, 123999) + expect_equal(result[[3]]$id, 4455) +}) + +test_that("Tests allOf", { + # test allOf without discriminator + a1 <- AllofTagApiResponse$new(id = 450, name = "test_cat", code = 200, type = "test_type", message = "test_message") + + expect_true(!is.null(a1)) + expect_equal(a1$id, 450) + expect_equal(a1$name, "test_cat") +}) + +test_that("Tests allOf with discriminator", { + # test allOf without discriminator + c1 <- Cat$new(className = "cat", color = "red", declawed = TRUE) + + expect_true(!is.null(c1)) + expect_equal(c1$className, "cat") + expect_equal(c1$color, "red") + expect_true(c1$declawed) +}) + +test_that("Tests validateJSON", { + json <- + '{"name": "pet", "photoUrls" : ["http://a.com", "http://b.com"]}' + + json2 <- + '[ + {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"}, + {}, + {"Name" : "Ada", "Occupation" : "Engineer"} + ]' + + # validate `json` and no error throw + Pet$public_methods$validateJSON(json) + + # validate `json2` and should throw an error due to missing required fields + #expect_error(Pet$public_methods$validateJSON(json2), 'The JSON input ` [\n {\"Name\" : \"Tom\", \"Age\" : 32, \"Occupation\" : \"Consultant\"}, \n {},\n {\"Name\" : \"Ada\", \"Occupation\" : \"Engineer\"}\n ] ` is invalid for Pet: the required field `name` is missing.') + +}) + +# test set in object +test_that("Tests set in object", { + invalid_set <- + '{"self": 123, "private": "red", "super": "something", "set_test": ["1","2","2","4"]}' + expect_error(Special$new()$fromJSON(invalid_set), "Error! Items in `set_test` are not unique") + + special_json <- + '{"self": 123, "private": "red", "super": "something", "set_test": ["1","2","4"]}' + # test fromJSON + special <- Special$new()$fromJSON(special_json) + expect_equal(special$item_self, 123) + expect_equal(special$item_private, "red") + expect_equal(special$item_super, "something") + + # test toJSONString + expect_true(grepl('"private"', special$toJSONString())) + expect_true(grepl('"self"', special$toJSONString())) + expect_true(grepl('"super"', special$toJSONString())) + expect_equal('{"set_test":["1","2","4"],"self":123,"private":"red","super":"something"}', special$toJSONString()) + + # round trip test + s1 <- Special$new()$fromJSONString(special_json) + s2 <- Special$new()$fromJSONString(s1$toJSONString()) + expect_equal(s1, s2) + +}) + +# test object with special item names: self, private, super +test_that("Tests special item names", { + special_json <- + '{"self": 123, "private": "red", "super": "something"}' + + # test fromJSON + special <- Special$new()$fromJSON(special_json) + expect_equal(special$item_self, 123) + expect_equal(special$item_private, "red") + expect_equal(special$item_super, "something") + + # test toJSONString + expect_true(grepl('"private"', special$toJSONString())) + expect_true(grepl('"self"', special$toJSONString())) + expect_true(grepl('"super"', special$toJSONString())) + expect_equal('{"self":123,"private":"red","super":"something"}', special$toJSONString()) + + # round trip test + s1 <- Special$new()$fromJSONString(special_json) + s2 <- Special$new()$fromJSONString(s1$toJSONString()) + expect_equal(s1, s2) + +}) + +test_that ("Tests validations", { + invalid_pet <- Pet$new() + + expect_false(invalid_pet$isValid()) + + invalid_fields <- invalid_pet$getInvalidFields() + expect_equal(invalid_fields[["name"]], "Non-nullable required field `name` cannot be null.") + expect_equal(invalid_fields[["photoUrls"]], "Non-nullable required field `photoUrls` cannot be null.") + + # fix invalid fields + invalid_pet$name <- "valid pet" + invalid_pet$photoUrls <- list("photo_test", "second test") + + expect_true(invalid_pet$isValid()) + expect_equal(invalid_pet$getInvalidFields(), list()) + +}) + +test_that("Tests oneOf discriminator mapping", { + whale_json <- '{"className": "whale", "hasBaleen": true, "hasTeeth": true}' + zebra_json <- '{"className": "zebra", "type": "plains"}' + + mammal <- Mammal$new() + mammal$fromJSON(whale_json) + expect_equal(mammal$actual_type, "Whale") + expect_equal(mammal$actual_instance$hasBaleen, TRUE) + expect_equal(mammal$actual_instance$hasTeeth, TRUE) + + mammal$fromJSON(zebra_json) + expect_equal(mammal$actual_type, "Zebra") + expect_equal(mammal$actual_instance$type, "plains") + +}) + +test_that("Tests oneOf", { + basque_pig_json <- + '{"className": "BasquePig", "color": "red"}' + + danish_pig_json <- + '{"className": "DanishPig", "size": 7}' + + wrong_json <- + '[ + {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"}, + {}, + {"Name" : "Ada", "Occupation" : "Engineer"} + ]' + + original_danish_pig <- DanishPig$new()$fromJSON(danish_pig_json) + original_basque_pig <- BasquePig$new()$fromJSON(basque_pig_json) + + # test fromJSON, actual_tpye, actual_instance + pig <- Pig$new() + danish_pig <- pig$fromJSON(danish_pig_json) + pig$validateJSON(basque_pig_json) # validate JSON to ensure its actual_instance, actual_type are not updated + expect_equal(danish_pig$actual_type, "DanishPig") + expect_equal(danish_pig$actual_instance$size, 7) + expect_equal(danish_pig$actual_instance$className, "DanishPig") + + expect_equal(pig$actual_type, "DanishPig") + expect_equal(pig$actual_instance$size, 7) + expect_equal(pig$actual_instance$className, "DanishPig") + + # test toJSON + expect_equal(danish_pig$toJSONString(), original_danish_pig$toJSONString()) + + basque_pig <- pig$fromJSON(basque_pig_json) + expect_equal(basque_pig$actual_type, "BasquePig") + expect_equal(basque_pig$actual_instance$color, "red") + expect_equal(basque_pig$actual_instance$className, "BasquePig") + expect_equal(basque_pig$toJSONString(), original_basque_pig$toJSONString()) + + # test exception when no matche found + expect_error(pig$fromJSON('{}'), 'No match found when deserializing the payload into Pig with oneOf schemas BasquePig, DanishPig. Details: Failed to lookup discriminator value for Pig. Error message: EXPR must be a length 1 vector. Input: \\{\\}, The JSON input ` \\{\\} ` is invalid for BasquePig: the required field `className` is missing\\., The JSON input ` \\{\\} ` is invalid for DanishPig: the required field `className` is missing\\.') + expect_error(pig$validateJSON('{}'), 'No match found when deserializing the payload into Pig with oneOf schemas BasquePig, DanishPig. Details: Failed to lookup discriminator value for Pig. Error message: EXPR must be a length 1 vector. Input: \\{\\}, The JSON input ` \\{\\} ` is invalid for BasquePig: the required field `className` is missing\\., The JSON input ` \\{\\} ` is invalid for DanishPig: the required field `className` is missing\\.') + + # class name test + expect_equal(get(class(basque_pig$actual_instance)[[1]], pos = -1)$classname, "BasquePig") + + # test contructors + pig2 <- Pig$new(instance = basque_pig$actual_instance) + expect_equal(pig2$actual_type, "BasquePig") + expect_equal(pig2$actual_instance$color, "red") + expect_equal(pig2$actual_instance$className, "BasquePig") + expect_equal(pig2$toJSONString(), original_basque_pig$toJSONString()) + + expect_error(Pig$new(instance = basque_pig), 'Failed to initialize Pig with oneOf schemas BasquePig, DanishPig. Provided class name: Pig') + + # test nested oneOf toJSONString + nested_oneof <- NestedOneOf$new() + nested_oneof$nested_pig <- pig + nested_oneof$size <- 15 + expect_equal(nested_oneof$toJSONString(), '{"size":15,"nested_pig":{"className":"BasquePig","color":"red"}}') + + # test fromJSONString with nested oneOf + nested_json_str <- '{"size":15,"nested_pig":{"className":"BasquePig","color":"red"}}' + nested_oneof2 <- NestedOneOf$new()$fromJSONString(nested_json_str) + expect_equal(nested_oneof2$toJSONString(), '{"size":15,"nested_pig":{"className":"BasquePig","color":"red"}}') + + # test toString + expect_equal(as.character(jsonlite::minify(pig$toString())), "{\"actual_instance\":{\"className\":\"BasquePig\",\"color\":\"red\"},\"actual_type\":\"BasquePig\",\"one_of\":\"BasquePig, DanishPig\"}") + expect_equal(as.character(jsonlite::minify(Pig$new()$toString())), "{\"one_of\":\"BasquePig, DanishPig\"}") +}) + +test_that("Tests anyOf", { + basque_pig_json <- + '{"className": "BasquePig", "color": "red"}' + + danish_pig_json <- + '{"className": "DanishPig", "size": 7}' + + wrong_json <- + '[ + {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"}, + {}, + {"Name" : "Ada", "Occupation" : "Engineer"} + ]' + + original_danish_pig <- DanishPig$new()$fromJSON(danish_pig_json) + original_basque_pig <- BasquePig$new()$fromJSON(basque_pig_json) + + # test fromJSON, actual_tpye, actual_instance + pig <- AnyOfPig$new() + danish_pig <- pig$fromJSON(danish_pig_json) + expect_equal(danish_pig$actual_type, "DanishPig") + expect_equal(danish_pig$actual_instance$size, 7) + expect_equal(danish_pig$actual_instance$className, "DanishPig") + + expect_equal(pig$actual_type, "DanishPig") + expect_equal(pig$actual_instance$size, 7) + expect_equal(pig$actual_instance$className, "DanishPig") + + # test toJSONString + expect_equal(danish_pig$toJSONString(), original_danish_pig$toJSONString()) + + basque_pig <- pig$fromJSON(basque_pig_json) + expect_equal(basque_pig$actual_type, "BasquePig") + expect_equal(basque_pig$actual_instance$color, "red") + expect_equal(basque_pig$actual_instance$className, "BasquePig") + expect_equal(basque_pig$toJSONString(), original_basque_pig$toJSONString()) + + # test exception when no matche found + expect_error(pig$fromJSON('{}'), 'No match found when deserializing the payload into AnyOfPig with anyOf schemas BasquePig, DanishPig. Details: The JSON input ` \\{\\} ` is invalid for BasquePig: the required field `className` is missing\\., The JSON input ` \\{\\} ` is invalid for DanishPig: the required field `className` is missing\\.') + expect_error(pig$validateJSON('{}'), 'No match found when deserializing the payload into AnyOfPig with anyOf schemas BasquePig, DanishPig. Details: The JSON input ` \\{\\} ` is invalid for BasquePig: the required field `className` is missing\\., The JSON input ` \\{\\} ` is invalid for DanishPig: the required field `className` is missing\\.') + +}) + +test_that("Tests URL validation", { + valid_json <- '{"className":"date","percent_description":"abc","url_property":"https://stackoverflow.com/a/1/b/2"}' + Date$public_methods$validateJSON(valid_json) # shouldn't throw exception + + valid_json <- '{"className":"date","percent_description":"abc","url_property":"https://abc.com/a/1/b/2"}' + Date$public_methods$validateJSON(valid_json) # shouldn't throw exception + + invalid_json <- '{"className":"date","percent_description":"abc","url_property":"invalid_url"}' + expect_error(Date$public_methods$validateJSON(invalid_json), 'Error! Invalid URL: invalid_url') # should throw exception + + # test fromJSONString with valid data + d <- Date$new() + d$fromJSONString(valid_json) + expect_equal(d$className, "date") + expect_equal(d$percent_description, "abc") + expect_equal(d$url_property, "https://abc.com/a/1/b/2") + + # test fromJSONString with invalid data + d <- Date$new() + expect_error(d$fromJSONString(invalid_json), 'Error! Invalid URL: invalid_url') # should throw exception +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_pig.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_pig.R new file mode 100644 index 0000000000..4846cfbb0f --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_pig.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Pig") + +model_instance <- Pig$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) + +test_that("size", { + # tests for the property `size` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`size`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_special.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_special.R new file mode 100644 index 0000000000..c76671b213 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_special.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Special") + +model_instance <- Special$new() + +test_that("self", { + # tests for the property `self` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`self`, "EXPECTED_RESULT") +}) + +test_that("private", { + # tests for the property `private` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`private`, "EXPECTED_RESULT") +}) + +test_that("super", { + # tests for the property `super` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`super`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_store_api.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_store_api.R new file mode 100644 index 0000000000..1ebb3f82a6 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_store_api.R @@ -0,0 +1,53 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test StoreApi") + +api.instance <- StoreApi$new() + +test_that("DeleteOrder", { + # tests for DeleteOrder + # base path: http://petstore.swagger.io/v2 + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order.id character ID of the order that needs to be deleted + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("GetInventory", { + # tests for GetInventory + # base path: http://petstore.swagger.io/v2 + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @return [map(integer)] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("GetOrderById", { + # tests for GetOrderById + # base path: http://petstore.swagger.io/v2 + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order.id integer ID of pet that needs to be fetched + # @return [Order] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("PlaceOrder", { + # tests for PlaceOrder + # base path: http://petstore.swagger.io/v2 + # Place an order for a pet + # @param body Order order placed for purchasing the pet + # @return [Order] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_tag.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_tag.R new file mode 100644 index 0000000000..2dd6d369af --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_tag.R @@ -0,0 +1,21 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Tag") + +model.instance <- Tag$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("name", { + # tests for the property `name` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`name`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_update_pet_request.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_update_pet_request.R new file mode 100644 index 0000000000..b39b2b4d0d --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_update_pet_request.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test UpdatePetRequest") + +model_instance <- UpdatePetRequest$new() + +test_that("jsonData", { + # tests for the property `jsonData` (Pet) + + # uncomment below to test the property + #expect_equal(model.instance$`jsonData`, "EXPECTED_RESULT") +}) + +test_that("binaryDataN2Information", { + # tests for the property `binaryDataN2Information` (data.frame) + + # uncomment below to test the property + #expect_equal(model.instance$`binaryDataN2Information`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_user.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_user.R new file mode 100644 index 0000000000..9929623b42 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_user.R @@ -0,0 +1,64 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test User") + +model.instance <- User$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("username", { + # tests for the property `username` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`username`, "EXPECTED_RESULT") +}) + +test_that("firstName", { + # tests for the property `firstName` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`firstName`, "EXPECTED_RESULT") +}) + +test_that("lastName", { + # tests for the property `lastName` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`lastName`, "EXPECTED_RESULT") +}) + +test_that("email", { + # tests for the property `email` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`email`, "EXPECTED_RESULT") +}) + +test_that("password", { + # tests for the property `password` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`password`, "EXPECTED_RESULT") +}) + +test_that("phone", { + # tests for the property `phone` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`phone`, "EXPECTED_RESULT") +}) + +test_that("userStatus", { + # tests for the property `userStatus` (integer) + # User Status + + # uncomment below to test the property + #expect_equal(model.instance$`userStatus`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_user_api.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_user_api.R new file mode 100644 index 0000000000..8b8c3ba384 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_user_api.R @@ -0,0 +1,99 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test UserApi") + +api.instance <- UserApi$new() + +test_that("CreateUser", { + # tests for CreateUser + # base path: http://petstore.swagger.io/v2 + # Create user + # This can only be done by the logged in user. + # @param body User Created user object + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("CreateUsersWithArrayInput", { + # tests for CreateUsersWithArrayInput + # base path: http://petstore.swagger.io/v2 + # Creates list of users with given input array + # @param body array[User] List of user object + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("CreateUsersWithListInput", { + # tests for CreateUsersWithListInput + # base path: http://petstore.swagger.io/v2 + # Creates list of users with given input array + # @param body array[User] List of user object + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("DeleteUser", { + # tests for DeleteUser + # base path: http://petstore.swagger.io/v2 + # Delete user + # This can only be done by the logged in user. + # @param username character The name that needs to be deleted + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("GetUserByName", { + # tests for GetUserByName + # base path: http://petstore.swagger.io/v2 + # Get user by user name + # @param username character The name that needs to be fetched. Use user1 for testing. + # @return [User] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("LoginUser", { + # tests for LoginUser + # base path: http://petstore.swagger.io/v2 + # Logs user into the system + # @param username character The user name for login + # @param password character The password for login in clear text + # @return [character] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("LogoutUser", { + # tests for LogoutUser + # base path: http://petstore.swagger.io/v2 + # Logs out current logged in user session + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("UpdateUser", { + # tests for UpdateUser + # base path: http://petstore.swagger.io/v2 + # Updated user + # This can only be done by the logged in user. + # @param username character name that need to be deleted + # @param body User Updated user object + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_whale.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_whale.R new file mode 100644 index 0000000000..b19c7b9eb3 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_whale.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Whale") + +model_instance <- Whale$new() + +test_that("hasBaleen", { + # tests for the property `hasBaleen` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasBaleen`, "EXPECTED_RESULT") +}) + +test_that("hasTeeth", { + # tests for the property `hasTeeth` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasTeeth`, "EXPECTED_RESULT") +}) + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_zebra.R b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_zebra.R new file mode 100644 index 0000000000..444da2f8f7 --- /dev/null +++ b/samples/client/petstore/R-httr2-wrapper/tests/testthat/test_zebra.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Zebra") + +model_instance <- Zebra$new() + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/.Rbuildignore b/samples/client/petstore/R-httr2/.Rbuildignore new file mode 100644 index 0000000000..d982e4aa88 --- /dev/null +++ b/samples/client/petstore/R-httr2/.Rbuildignore @@ -0,0 +1,20 @@ +^.*\.Rproj$ # Designates the directory as an RStudio Project +^\.Rproj\.user$ # Used by RStudio for temporary files +^README\.Rmd$ # An Rmd file used to generate README.md +^LICENSE\.md$ # Full text of the license +^cran-comments\.md$ # Comments for CRAN submission +^data-raw$ # Code used to create data included in the package +^pkgdown$ # Resources used for the package website +^_pkgdown\.yml$ # Configuration info for the package website +^\.github$ # Contributing guidelines, CoC, issue templates, etc. +^\.Rhistory$ +^\.gitignore$ +^\.openapi-generator-ignore$ +^\.travis\.yml$ +^\.lintr$ +^\.github$ +^\.openapi-generator$ +^docs$ +^git_push\.sh$ +^petstore\.Rcheck$ +^\.\.Rcheck$ diff --git a/samples/client/petstore/R-httr2/.github/workflows/r-client.yaml b/samples/client/petstore/R-httr2/.github/workflows/r-client.yaml new file mode 100644 index 0000000000..216ebe6c00 --- /dev/null +++ b/samples/client/petstore/R-httr2/.github/workflows/r-client.yaml @@ -0,0 +1,33 @@ +# This file is automatically generated by openapi-generator (https://openapi-generator.tech) +# +# Based on https://github.com/r-lib/actions/tree/v2/examples +on: + push: + branches: [main, master] + pull_request: + branches: [main, master] + +name: R-CMD-check + +jobs: + R-CMD-check: + runs-on: ubuntu-latest + env: + R_KEEP_PKG_SOURCE: yes + steps: + - uses: actions/checkout@v2 + - uses: r-lib/actions/setup-r@v2 + with: + use-public-rspm: true + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::rcmdcheck, any::roxygen2, any::lintr, local::. + needs: check, roxygen2, lint + - name: Lint + run: lintr::lint_package() + shell: Rscript {0} + - name: Roxygenize + run: | + roxygen2::roxygenize('.', roclets = c('rd', 'collate', 'namespace')) + shell: Rscript {0} + - uses: r-lib/actions/check-r-package@v2 diff --git a/samples/client/petstore/R-httr2/.gitignore b/samples/client/petstore/R-httr2/.gitignore new file mode 100644 index 0000000000..5d21150e0c --- /dev/null +++ b/samples/client/petstore/R-httr2/.gitignore @@ -0,0 +1,35 @@ +# ref: https://github.com/github/gitignore/blob/master/R.gitignore + +# History files +.Rhistory +.Rapp.history + +# Session Data files +.RData + +# Example code in package build process +*-Ex.R + +# Output files from R CMD build +/*.tar.gz + +# Output files from R CMD check +/*.Rcheck/ + +# RStudio files +.Rproj.user/ + +# produced vignettes +vignettes/*.html +vignettes/*.pdf + +# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 +.httr-oauth + +# knitr and R markdown default cache directories +/*_cache/ +/cache/ + +# Temporary files created by R markdown +*.utf8.md +*.knit.md diff --git a/samples/client/petstore/R-httr2/.lintr b/samples/client/petstore/R-httr2/.lintr new file mode 100644 index 0000000000..54ee36a49c --- /dev/null +++ b/samples/client/petstore/R-httr2/.lintr @@ -0,0 +1,7 @@ +linters: linters_with_defaults( + line_length_linter(160), + object_name_linter = NULL, + cyclocomp_linter = NULL + ) +exclusions: list( + ) diff --git a/samples/client/petstore/R-httr2/.openapi-generator-ignore b/samples/client/petstore/R-httr2/.openapi-generator-ignore new file mode 100644 index 0000000000..c5fa491b4c --- /dev/null +++ b/samples/client/petstore/R-httr2/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/client/petstore/R-httr2/.openapi-generator/FILES b/samples/client/petstore/R-httr2/.openapi-generator/FILES new file mode 100644 index 0000000000..d539ea462d --- /dev/null +++ b/samples/client/petstore/R-httr2/.openapi-generator/FILES @@ -0,0 +1,71 @@ +.Rbuildignore +.github/workflows/r-client.yaml +.gitignore +.lintr +.travis.yml +DESCRIPTION +NAMESPACE +R/allof_tag_api_response.R +R/animal.R +R/any_of_pig.R +R/any_of_primitive_type_test.R +R/api_client.R +R/api_exception.R +R/api_response.R +R/basque_pig.R +R/cat.R +R/cat_all_of.R +R/category.R +R/danish_pig.R +R/date.R +R/dog.R +R/dog_all_of.R +R/fake_api.R +R/mammal.R +R/model_api_response.R +R/nested_one_of.R +R/one_of_primitive_type_test.R +R/order.R +R/pet.R +R/pet_api.R +R/pig.R +R/special.R +R/store_api.R +R/tag.R +R/update_pet_request.R +R/user.R +R/user_api.R +R/whale.R +R/zebra.R +README.md +docs/AllofTagApiResponse.md +docs/Animal.md +docs/AnyOfPig.md +docs/AnyOfPrimitiveTypeTest.md +docs/BasquePig.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/DanishPig.md +docs/Date.md +docs/Dog.md +docs/DogAllOf.md +docs/FakeApi.md +docs/Mammal.md +docs/ModelApiResponse.md +docs/NestedOneOf.md +docs/OneOfPrimitiveTypeTest.md +docs/Order.md +docs/Pet.md +docs/PetApi.md +docs/Pig.md +docs/Special.md +docs/StoreApi.md +docs/Tag.md +docs/UpdatePetRequest.md +docs/User.md +docs/UserApi.md +docs/Whale.md +docs/Zebra.md +git_push.sh +tests/testthat.R diff --git a/samples/client/petstore/R-httr2/.openapi-generator/VERSION b/samples/client/petstore/R-httr2/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/R-httr2/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/R-httr2/.travis.yml b/samples/client/petstore/R-httr2/.travis.yml new file mode 100644 index 0000000000..60f31f3107 --- /dev/null +++ b/samples/client/petstore/R-httr2/.travis.yml @@ -0,0 +1,18 @@ +# ref: https://docs.travis-ci.com/user/languages/r/ +language: r +cache: + directories: + - /home/travis/R/Library +r_packages: +- jsonlite +- httr2 +- testthat +# uncomment below to install deps with devtools +#install: +#- R -e 'devtools::install_deps(dep = T)' +script: +- R CMD build . +- R CMD check *tar.gz +- R CMD INSTALL *tar.gz +after_failure: +- cat ${TRAVIS_BUILD_DIR}/namsor.Rcheck/tests/testthat.Rout.fail diff --git a/samples/client/petstore/R-httr2/DESCRIPTION b/samples/client/petstore/R-httr2/DESCRIPTION new file mode 100644 index 0000000000..1cb6b5af88 --- /dev/null +++ b/samples/client/petstore/R-httr2/DESCRIPTION @@ -0,0 +1,15 @@ +Package: petstore +Title: R Package Client for OpenAPI Petstore +Version: 1.0.0 +Author: person("OpenAPI Generator community", email = "team@openapitools.org", role = c("aut", "cre")) +Maintainer: OpenAPI Generator community +Description: This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +URL: https://github.com/GIT_USER_ID/GIT_REPO_ID +BugReports: https://github.com/GIT_USER_ID/GIT_REPO_ID/issues +Depends: R (>= 3.3) +Encoding: UTF-8 +License: Apache License 2.0 +LazyData: true +Suggests: testthat +Imports: jsonlite, httr2, R6, base64enc, stringr +RoxygenNote: 7.2.1 diff --git a/samples/client/petstore/R-httr2/NAMESPACE b/samples/client/petstore/R-httr2/NAMESPACE new file mode 100644 index 0000000000..fbdc3618b4 --- /dev/null +++ b/samples/client/petstore/R-httr2/NAMESPACE @@ -0,0 +1,47 @@ +# Generated by openapi-generator: https://openapi-generator.tech +# Do not edit by hand + +import(R6) +import(jsonlite) +import(httr2) +import(base64enc) +import(stringr) + + +# Core +export(ApiClient) +export(ApiResponse) +export(ApiException) + +# Models +export(AllofTagApiResponse) +export(Animal) +export(AnyOfPig) +export(AnyOfPrimitiveTypeTest) +export(BasquePig) +export(Cat) +export(CatAllOf) +export(Category) +export(DanishPig) +export(Date) +export(Dog) +export(DogAllOf) +export(Mammal) +export(ModelApiResponse) +export(NestedOneOf) +export(OneOfPrimitiveTypeTest) +export(Order) +export(Pet) +export(Pig) +export(Special) +export(Tag) +export(UpdatePetRequest) +export(User) +export(Whale) +export(Zebra) + +# APIs +export(FakeApi) +export(PetApi) +export(StoreApi) +export(UserApi) diff --git a/samples/client/petstore/R-httr2/R.Rproj b/samples/client/petstore/R-httr2/R.Rproj new file mode 100644 index 0000000000..eaa6b8186b --- /dev/null +++ b/samples/client/petstore/R-httr2/R.Rproj @@ -0,0 +1,18 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 2 +Encoding: UTF-8 + +RnwWeave: Sweave +LaTeX: pdfLaTeX + +BuildType: Package +PackageUseDevtools: Yes +PackageInstallArgs: --no-multiarch --with-keep.source +PackageRoxygenize: rd,collate,namespace diff --git a/samples/client/petstore/R-httr2/R/allof_tag_api_response.R b/samples/client/petstore/R-httr2/R/allof_tag_api_response.R new file mode 100644 index 0000000000..de8c4c8003 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/allof_tag_api_response.R @@ -0,0 +1,253 @@ +#' Create a new AllofTagApiResponse +#' +#' @description +#' AllofTagApiResponse Class +#' +#' @docType class +#' @title AllofTagApiResponse +#' @description AllofTagApiResponse Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field name character [optional] +#' @field code integer [optional] +#' @field type character [optional] +#' @field message character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +AllofTagApiResponse <- R6::R6Class( + "AllofTagApiResponse", + public = list( + `id` = NULL, + `name` = NULL, + `code` = NULL, + `type` = NULL, + `message` = NULL, + #' Initialize a new AllofTagApiResponse class. + #' + #' @description + #' Initialize a new AllofTagApiResponse class. + #' + #' @param id id + #' @param name name + #' @param code code + #' @param type type + #' @param message message + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `name` = NULL, `code` = NULL, `type` = NULL, `message` = NULL, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + if (!is.null(`code`)) { + stopifnot(is.numeric(`code`), length(`code`) == 1) + self$`code` <- `code` + } + if (!is.null(`type`)) { + stopifnot(is.character(`type`), length(`type`) == 1) + self$`type` <- `type` + } + if (!is.null(`message`)) { + stopifnot(is.character(`message`), length(`message`) == 1) + self$`message` <- `message` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return AllofTagApiResponse in JSON format + #' @export + toJSON = function() { + AllofTagApiResponseObject <- list() + if (!is.null(self$`id`)) { + AllofTagApiResponseObject[["id"]] <- + self$`id` + } + if (!is.null(self$`name`)) { + AllofTagApiResponseObject[["name"]] <- + self$`name` + } + if (!is.null(self$`code`)) { + AllofTagApiResponseObject[["code"]] <- + self$`code` + } + if (!is.null(self$`type`)) { + AllofTagApiResponseObject[["type"]] <- + self$`type` + } + if (!is.null(self$`message`)) { + AllofTagApiResponseObject[["message"]] <- + self$`message` + } + AllofTagApiResponseObject + }, + #' Deserialize JSON string into an instance of AllofTagApiResponse + #' + #' @description + #' Deserialize JSON string into an instance of AllofTagApiResponse + #' + #' @param input_json the JSON input + #' @return the instance of AllofTagApiResponse + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`name`)) { + self$`name` <- this_object$`name` + } + if (!is.null(this_object$`code`)) { + self$`code` <- this_object$`code` + } + if (!is.null(this_object$`type`)) { + self$`type` <- this_object$`type` + } + if (!is.null(this_object$`message`)) { + self$`message` <- this_object$`message` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return AllofTagApiResponse in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`name`)) { + sprintf( + '"name": + "%s" + ', + self$`name` + ) + }, + if (!is.null(self$`code`)) { + sprintf( + '"code": + %d + ', + self$`code` + ) + }, + if (!is.null(self$`type`)) { + sprintf( + '"type": + "%s" + ', + self$`type` + ) + }, + if (!is.null(self$`message`)) { + sprintf( + '"message": + "%s" + ', + self$`message` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of AllofTagApiResponse + #' + #' @description + #' Deserialize JSON string into an instance of AllofTagApiResponse + #' + #' @param input_json the JSON input + #' @return the instance of AllofTagApiResponse + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`name` <- this_object$`name` + self$`code` <- this_object$`code` + self$`type` <- this_object$`type` + self$`message` <- this_object$`message` + self + }, + #' Validate JSON input with respect to AllofTagApiResponse + #' + #' @description + #' Validate JSON input with respect to AllofTagApiResponse and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of AllofTagApiResponse + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# AllofTagApiResponse$unlock() +# +## Below is an example to define the print fnuction +# AllofTagApiResponse$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# AllofTagApiResponse$lock() + diff --git a/samples/client/petstore/R-httr2/R/animal.R b/samples/client/petstore/R-httr2/R/animal.R new file mode 100644 index 0000000000..f111fd1252 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/animal.R @@ -0,0 +1,202 @@ +#' Create a new Animal +#' +#' @description +#' Animal Class +#' +#' @docType class +#' @title Animal +#' @description Animal Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field color character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Animal <- R6::R6Class( + "Animal", + public = list( + `className` = NULL, + `color` = NULL, + `_discriminator_property_name` = 'className', + `_discriminator_mapping_name` = c('Cat' = 'Cat', 'Dog' = 'Dog'), + #' Initialize a new Animal class. + #' + #' @description + #' Initialize a new Animal class. + #' + #' @param className className + #' @param color color. Default to "red". + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `color` = "red", ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`color`)) { + stopifnot(is.character(`color`), length(`color`) == 1) + self$`color` <- `color` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Animal in JSON format + #' @export + toJSON = function() { + AnimalObject <- list() + if (!is.null(self$`className`)) { + AnimalObject[["className"]] <- + self$`className` + } + if (!is.null(self$`color`)) { + AnimalObject[["color"]] <- + self$`color` + } + AnimalObject + }, + #' Deserialize JSON string into an instance of Animal + #' + #' @description + #' Deserialize JSON string into an instance of Animal + #' + #' @param input_json the JSON input + #' @return the instance of Animal + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`color`)) { + self$`color` <- this_object$`color` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Animal in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`color`)) { + sprintf( + '"color": + "%s" + ', + self$`color` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Animal + #' + #' @description + #' Deserialize JSON string into an instance of Animal + #' + #' @param input_json the JSON input + #' @return the instance of Animal + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`color` <- this_object$`color` + self + }, + #' Validate JSON input with respect to Animal + #' + #' @description + #' Validate JSON input with respect to Animal and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Animal: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Animal + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Animal$unlock() +# +## Below is an example to define the print fnuction +# Animal$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Animal$lock() + diff --git a/samples/client/petstore/R-httr2/R/any_of_pig.R b/samples/client/petstore/R-httr2/R/any_of_pig.R new file mode 100644 index 0000000000..404b710472 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/any_of_pig.R @@ -0,0 +1,184 @@ +#' @docType class +#' @title AnyOfPig +#' +#' @description AnyOfPig Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +AnyOfPig <- R6::R6Class( + "AnyOfPig", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field any_of a list of object types defined in the anyOf schema. + any_of = list("BasquePig", "DanishPig"), + #' Initialize a new AnyOfPig. + #' + #' @description + #' Initialize a new AnyOfPig. + #' + #' @param instance an instance of the object defined in the anyOf schemas: "BasquePig", "DanishPig" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "BasquePig") { + self$actual_instance <- instance + self$actual_type <- "BasquePig" + } else if (get(class(instance)[[1]], pos = -1)$classname == "DanishPig") { + self$actual_instance <- instance + self$actual_type <- "DanishPig" + } else { + stop(paste("Failed to initialize AnyOfPig with anyOf schemas BasquePig, DanishPig. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of AnyOfPig. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPig. + #' An alias to the method `fromJSON`. + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPig. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of AnyOfPig. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPig. + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPig. + #' @export + fromJSON = function(input) { + error_messages <- list() + + BasquePig_result <- tryCatch({ + BasquePig$public_methods$validateJSON(input) + BasquePig_instance <- BasquePig$new() + self$actual_instance <- BasquePig_instance$fromJSON(input) + self$actual_type <- "BasquePig" + return(self) + }, + error = function(err) err + ) + + if (!is.null(BasquePig_result["error"])) { + error_messages <- append(error_messages, BasquePig_result["message"]) + } + + DanishPig_result <- tryCatch({ + DanishPig$public_methods$validateJSON(input) + DanishPig_instance <- DanishPig$new() + self$actual_instance <- DanishPig_instance$fromJSON(input) + self$actual_type <- "DanishPig" + return(self) + }, + error = function(err) err + ) + + if (!is.null(DanishPig_result["error"])) { + error_messages <- append(error_messages, DanishPig_result["message"]) + } + + # no match + stop(paste("No match found when deserializing the payload into AnyOfPig with anyOf schemas BasquePig, DanishPig. Details: ", + paste(error_messages, collapse = ", "))) + }, + #' Serialize AnyOfPig to JSON string. + #' + #' @description + #' Serialize AnyOfPig to JSON string. + #' + #' @return JSON string representation of the AnyOfPig. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify((self$actual_instance$toJSONString()))) + } else { + NULL + } + }, + #' Serialize AnyOfPig to JSON. + #' + #' @description + #' Serialize AnyOfPig to JSON. + #' + #' @return JSON representation of the AnyOfPig. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to AnyOfPig. + #' + #' @description + #' Validate the input JSON with respect to AnyOfPig and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"any_of": "%s"', paste(unlist(self$any_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#AnyOfPig$unlock() +# +## Below is an example to define the print fnuction +#AnyOfPig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#AnyOfPig$lock() + diff --git a/samples/client/petstore/R-httr2/R/any_of_primitive_type_test.R b/samples/client/petstore/R-httr2/R/any_of_primitive_type_test.R new file mode 100644 index 0000000000..374aa8c605 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/any_of_primitive_type_test.R @@ -0,0 +1,202 @@ +#' @docType class +#' @title AnyOfPrimitiveTypeTest +#' +#' @description AnyOfPrimitiveTypeTest Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +AnyOfPrimitiveTypeTest <- R6::R6Class( + "AnyOfPrimitiveTypeTest", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("character", "integer"), + #' Initialize a new AnyOfPrimitiveTypeTest. + #' + #' @description + #' Initialize a new AnyOfPrimitiveTypeTest. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "character", "integer" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "character") { + self$actual_instance <- instance + self$actual_type <- "character" + } else if (get(class(instance)[[1]], pos = -1)$classname == "integer") { + self$actual_instance <- instance + self$actual_type <- "integer" + } else { + stop(paste("Failed to initialize AnyOfPrimitiveTypeTest with oneOf schemas character, integer. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPrimitiveTypeTest. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPrimitiveTypeTest. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + integer_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "integer") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "integer", typeof(instance))) + } + instance_type <- "integer" + matched_schemas <- append(matched_schemas, "integer") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(integer_result["error"])) { + error_messages <- append(error_messages, integer_result["message"]) + } + + character_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "character") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "character", typeof(instance))) + } + instance_type <- "character" + matched_schemas <- append(matched_schemas, "character") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(character_result["error"])) { + error_messages <- append(error_messages, character_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into AnyOfPrimitiveTypeTest with oneOf schemas character, integer.") + } else { + # no match + stop(paste("No match found when deserializing the payload into AnyOfPrimitiveTypeTest with oneOf schemas character, integer. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize AnyOfPrimitiveTypeTest to JSON string. + #' + #' @description + #' Serialize AnyOfPrimitiveTypeTest to JSON string. + #' + #' @return JSON string representation of the AnyOfPrimitiveTypeTest. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize AnyOfPrimitiveTypeTest to JSON. + #' + #' @description + #' Serialize AnyOfPrimitiveTypeTest to JSON. + #' + #' @return JSON representation of the AnyOfPrimitiveTypeTest. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to AnyOfPrimitiveTypeTest. + #' + #' @description + #' Validate the input JSON with respect to AnyOfPrimitiveTypeTest and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#AnyOfPrimitiveTypeTest$unlock() +# +## Below is an example to define the print fnuction +#AnyOfPrimitiveTypeTest$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#AnyOfPrimitiveTypeTest$lock() + diff --git a/samples/client/petstore/R-httr2/R/api_client.R b/samples/client/petstore/R-httr2/R/api_client.R new file mode 100644 index 0000000000..3ca3cf9ce7 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/api_client.R @@ -0,0 +1,433 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' ApiClient Class +#' +#' Generic API client for OpenAPI client library builds. +#' OpenAPI generic API client. This client handles the client- +#' server communication, and is invariant across implementations. Specifics of +#' the methods and models for each application are generated from the OpenAPI Generator +#' templates. +#' +#' NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +#' Ref: https://openapi-generator.tech +#' Do not edit the class manually. +#' +#' @docType class +#' @title ApiClient +#' @description ApiClient Class +#' @format An \code{R6Class} generator object +#' @field base_path Base url +#' @field user_agent Default user agent +#' @field default_headers Default headers +#' @field username Username for HTTP basic authentication +#' @field password Password for HTTP basic authentication +#' @field api_keys API keys +#' @field access_token Access token +#' @field oauth_client_id OAuth client ID +#' @field oauth_secret OAuth secret +#' @field oauth_refresh_token OAuth refresh token +#' @field oauth_flow_type OAuth flow type +#' @field oauth_authorization_url Authoriziation URL +#' @field oauth_token_url Token URL +#' @field oauth_pkce Boolean flag to enable PKCE +#' @field oauth_scopes OAuth scopes +#' @field bearer_token Bearer token +#' @field timeout Default timeout in seconds +#' @field retry_status_codes vector of status codes to retry +#' @field max_retry_attempts maximum number of retries for the status codes +#' @importFrom rlang abort +#' @export +ApiClient <- R6::R6Class( + "ApiClient", + public = list( + # base path of all requests + base_path = "http://petstore.swagger.io/v2", + # user agent in the HTTP request + user_agent = "PetstoreAgent", + # default headers in the HTTP request + default_headers = NULL, + # username (HTTP basic authentication) + username = NULL, + # password (HTTP basic authentication) + password = NULL, + # API keys + api_keys = NULL, + # Access token + access_token = NULL, + # OAuth2 client ID + oauth_client_id = NULL, + # OAuth2 secret + oauth_secret = NULL, + # OAuth2 refresh token + oauth_refresh_token = NULL, + # OAuth2 + # Flow type + oauth_flow_type = "implicit", + # Authoriziation URL + oauth_authorization_url = "http://petstore.swagger.io/api/oauth/dialog", + # Token URL + oauth_token_url = "", + # Enable PKCE? + oauth_pkce = TRUE, + # OAuth scopes + oauth_scopes = NULL, + # Bearer token + bearer_token = NULL, + # Time Out (seconds) + timeout = NULL, + # Vector of status codes to retry + retry_status_codes = NULL, + # Maximum number of retry attempts for the retry status codes + max_retry_attempts = NULL, + #' Initialize a new ApiClient. + #' + #' @description + #' Initialize a new ApiClient. + #' + #' @param base_path Base path. + #' @param user_agent User agent. + #' @param default_headers Default headers. + #' @param username User name. + #' @param password Password. + #' @param api_keys API keys. + #' @param access_token Access token. + #' @param bearer_token Bearer token. + #' @param timeout Timeout. + #' @param retry_status_codes Status codes for retry. + #' @param max_retry_attempts Maxmium number of retry. + #' @export + initialize = function(base_path = NULL, user_agent = NULL, + default_headers = NULL, + username = NULL, password = NULL, api_keys = NULL, + access_token = NULL, bearer_token = NULL, timeout = NULL, + retry_status_codes = NULL, max_retry_attempts = NULL) { + if (!is.null(base_path)) { + self$base_path <- base_path + } + + if (!is.null(default_headers)) { + self$default_headers <- default_headers + } + + if (!is.null(username)) { + self$username <- username + } + + if (!is.null(password)) { + self$password <- password + } + + if (!is.null(access_token)) { + self$access_token <- access_token + } + + if (!is.null(bearer_token)) { + self$bearer_token <- bearer_token + } + + if (!is.null(api_keys)) { + self$api_keys <- api_keys + } else { + self$api_keys <- list() + } + + if (!is.null(user_agent)) { + self$`user_agent` <- user_agent + } + + if (!is.null(timeout)) { + self$timeout <- timeout + } + + if (!is.null(retry_status_codes)) { + self$retry_status_codes <- retry_status_codes + } + + if (!is.null(max_retry_attempts)) { + self$max_retry_attempts <- max_retry_attempts + } + }, + #' Prepare to make an API call with the retry logic. + #' + #' @description + #' Prepare to make an API call with the retry logic. + #' + #' @param url URL. + #' @param method HTTP method. + #' @param query_params The query parameters. + #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters to upload files. + #' @param accepts The HTTP accpet headers. + #' @param content_types The HTTP content-type headers. + #' @param body The HTTP request body. + #' @param is_oauth True if the endpoints required OAuth authentication. + #' @param oauth_scopes OAuth scopes. + #' @param stream_callback Callback function to process the data stream. + #' @param ... Other optional arguments. + #' @return HTTP response + #' @export + CallApi = function(url, method, query_params, header_params, form_params, + file_params, accepts, content_types, body, + is_oauth = FALSE, oauth_scopes = NULL, stream_callback = NULL, ...) { + + # set the URL + req <- request(url) + + resp <- self$Execute(req, method, query_params, header_params, form_params, + file_params, accepts, content_types, body, is_oauth = is_oauth, + oauth_scopes = oauth_scopes, stream_callback = stream_callback, ...) + }, + #' Make an API call + #' + #' @description + #' Make an API call + #' + #' @param req httr2 request. + #' @param method HTTP method. + #' @param query_params The query parameters. + #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters for uploading files. + #' @param accepts The HTTP accpet headers. + #' @param content_types The HTTP content-type headers. + #' @param body The HTTP request body. + #' @param is_oauth True if the endpoints required OAuth authentication. + #' @param oauth_scopes OAuth scopes. + #' @param stream_callback Callback function to process data stream. + #' @param ... Other optional arguments. + #' @return HTTP response + #' @export + Execute = function(req, method, query_params, header_params, form_params, + file_params, accepts, content_types, body, + is_oauth = FALSE, oauth_scopes = NULL, stream_callback = NULL, ...) { + + ## add headers + req <- req %>% req_headers(!!!header_params) + + ## add default headers + req <- req %>% req_headers(!!!self$default_headers) + + # set HTTP accept header + accept <- self$select_header(accepts) + if (!is.null(accept)) { + req <- req %>% req_headers("Accept" = accept) + } + + # set HTTP content-type header + content_type <- self$select_header(content_types) + if (!is.null(content_type)) { + req <- req %>% req_headers("Content-Type" = content_type) + } + + ## add query parameters + for (query_param in names(query_params)) { + if (typeof(query_params[[query_param]]) == "list") { + # for explode, e.g. a=1,a=2,a=3 + req <- req %>% req_url_query(!!!query_params[[query_param]]) + } else { # for non-explode, e.g. a=1,2,3 + tmp <- list() + tmp[[query_param]] <- query_params[[query_param]] + req <- req %>% req_url_query(!!!tmp) + } + } + + # has file upload? + if (!is.null(file_params) && length(file_params) != 0) { + req <- req %>% req_body_multipart(!!!file_params) + + # add form parameters via req_body_multipart + if (!is.null(form_params) && length(form_params) != 0) { + req <- req %>% req_body_multipart(!!!form_params) + } + } else { # no file upload + # add form parameters via req_body_form + if (!is.null(form_params) && length(form_params) != 0) { + req <- req %>% req_body_form(!!!form_params) + } + } + + # add body parameters + if (!is.null(body)) { + req <- req %>% req_body_raw(body) + } + + # set timeout + if (!is.null(self$timeout)) { + req <- req %>% req_timeout(self$timeout) + } + + # set retry + if (!is.null(self$max_retry_attempts)) { + req <- req %>% retry_max_tries(self$timeout) + req <- req %>% retry_max_seconds(self$timeout) + } + + # set user agent + if (!is.null(self$user_agent)) { + req <- req %>% req_user_agent(self$user_agent) + } + + # set HTTP verb + req <- req %>% req_method(method) + + # use oauth authentication if the endpoint requires it + if (is_oauth && !is.null(self$oauth_client_id) && !is.null(self$oauth_secret)) { + client <- oauth_client( + id = self$oauth_client_id, + secret = obfuscated(self$oauth_secret), + token_url = self$oauth_token_url, + name = "petstore-oauth" + ) + + req_oauth_scopes <- NULL + if (!is.null(self$oauth_scopes)) { + # use oauth scopes provided by the user + req_oauth_scopes <- self$oauth_scopes + } else { + # use oauth scopes defined in openapi spec + req_oauth_scopes <- oauth_scopes + } + + req <- req %>% req_oauth_auth_code(client, scope = req_oauth_scopes, + pkce = self$oauth_pkce, + auth_url = self$oauth_authoriziation_url) + } + + # stream data + if (typeof(stream_callback) == "closure") { + req %>% req_stream(stream_callback) + } else { + # perform the HTTP request + resp <- req %>% + req_error(is_error = function(resp) FALSE) %>% + req_perform() + + # return ApiResponse + api_response <- ApiResponse$new() + api_response$status_code <- resp %>% resp_status() + api_response$status_code_desc <- resp %>% resp_status_desc() + api_response$response <- resp %>% resp_body_string() + api_response$headers <- resp %>% resp_headers() + + api_response + } + }, + #' Deserialize the content of API response to the given type. + #' + #' @description + #' Deserialize the content of API response to the given type. + #' + #' @param raw_response Raw response. + #' @param return_type R return type. + #' @param pkg_env Package environment. + #' @return Deserialized object. + #' @export + deserialize = function(raw_response, return_type, pkg_env) { + resp_obj <- jsonlite::fromJSON(raw_response) + self$deserializeObj(resp_obj, return_type, pkg_env) + }, + #' Deserialize the response from jsonlite object based on the given type. + #' + #' @description + #' Deserialize the response from jsonlite object based on the given type. + #' by handling complex and nested types by iterating recursively + #' Example return_types will be like "array[integer]", "map(Pet)", "array[map(Tag)]", etc. + #' + #' @param obj Response object. + #' @param return_type R return type. + #' @param pkg_env Package environment. + #' @return Deserialized object. + #' @export + deserializeObj = function(obj, return_type, pkg_env) { + return_obj <- NULL + primitive_types <- c("character", "numeric", "integer", "logical", "complex") + + # To handle the "map" type + if (startsWith(return_type, "map(")) { + inner_return_type <- regmatches(return_type, + regexec(pattern = "map\\((.*)\\)", return_type))[[1]][2] + return_obj <- lapply(names(obj), function(name) { + self$deserializeObj(obj[[name]], inner_return_type, pkg_env) + }) + names(return_obj) <- names(obj) + } else if (startsWith(return_type, "array[")) { + # To handle the "array" type + inner_return_type <- regmatches(return_type, + regexec(pattern = "array\\[(.*)\\]", return_type))[[1]][2] + if (c(inner_return_type) %in% primitive_types) { + return_obj <- vector("list", length = length(obj)) + if (length(obj) > 0) { + for (row in 1:length(obj)) { + return_obj[[row]] <- self$deserializeObj(obj[row], inner_return_type, pkg_env) + } + } + } else { + if (!is.null(nrow(obj))) { + return_obj <- vector("list", length = nrow(obj)) + if (nrow(obj) > 0) { + for (row in 1:nrow(obj)) { + return_obj[[row]] <- self$deserializeObj(obj[row, , drop = FALSE], + inner_return_type, pkg_env) + } + } + } + } + } else if (exists(return_type, pkg_env) && !(c(return_type) %in% primitive_types)) { + # To handle model objects which are not array or map containers (e.g. Pet) + return_type <- get(return_type, envir = as.environment(pkg_env)) + return_obj <- return_type$new() + # check if discriminator is defined + if (!is.null(return_obj$`_discriminator_property_name`)) { + data_type <- return_obj$`_discriminator_property_name` + # use discriminator mapping if provided + if (!is.null(return_obj$`_discriminator_mapping_name`)) { + data_type <- (return_obj$`_discriminator_mapping_name`)[[obj[[data_type]]]] + } else { + # no mapping provided, use the value directly + data_type <- obj[[data_type]] + } + # create an object of the mapped type (e.g. Cat) + return_type <- get(data_type, envir = as.environment(pkg_env)) + return_obj <- return_type$new() + } + return_obj$fromJSON( + jsonlite::toJSON(obj, digits = NA, auto_unbox = TRUE) + ) + } else { + # To handle primitive type + return_obj <- obj + } + return_obj + }, + #' Return a propery header (for accept or content-type). + #' + #' @description + #' Return a propery header (for accept or content-type). If JSON-related MIME is found, + #' return it. Otherwise, return the first one, if any. + #' + #' @param headers A list of headers + #' @return A header (e.g. 'application/json') + #' @export + select_header = function(headers) { + if (length(headers) == 0) { + return(invisible(NULL)) + } else { + for (header in headers) { + if (str_detect(header, "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")) { + # return JSON-related MIME + return(header) + } + } + + # not json mime type, simply return the first one + return(headers[1]) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2/R/api_exception.R b/samples/client/petstore/R-httr2/R/api_exception.R new file mode 100644 index 0000000000..f31f27858b --- /dev/null +++ b/samples/client/petstore/R-httr2/R/api_exception.R @@ -0,0 +1,82 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title ApiException +#' @description ApiException Class +#' @format An \code{R6Class} generator object +#' @field status Status of the ApiException +#' @field reason Reason of the ApiException +#' @field body Body of the http response +#' @field headers Headers of the http response +#' @field error_object error object type +#' @export +ApiException <- R6::R6Class( + "ApiException", + public = list( + status = NULL, + reason = NULL, + body = NULL, + headers = NULL, + error_object = NULL, + #' Initialize a new ApiException class. + #' + #' @description + #' Initialize a new ApiExceptino class. + #' + #' @param status HTTP status. + #' @param reason Reason of the ApiException. + #' @param http_response HTTP response object. + #' @export + initialize = function(status = NULL, reason = NULL, http_response = NULL) { + if (!is.null(http_response)) { + self$status <- http_response$status_code + errorMsg <- http_response$response + if (is.null(errorMsg) || errorMsg == "") { + errorMsg <- "Api exception encountered. No details given." + } + self$body <- errorMsg + self$headers <- http_response$headers + self$reason <- http_response$http_status_desc + self$error_object <- ModelApiResponse$new()$fromJSONString(http_response$response) + } else { + self$status <- status + self$reason <- reason + self$body <- NULL + self$headers <- NULL + self$error_object <- NULL + } + }, + #' Returns the string format of ApiException. + #' + #' @description + #' Returns the string format of ApiException. + #' + #' @return the string format of ApiException. + #' @export + toString = function() { + errorMsg <- "" + errorMsg <- paste("status : ", self$status, "\n", sep = "") + errorMsg <- paste(errorMsg, "Reason : ", self$reason, "\n", sep = "") + if (!is.null(self$headers)) { + errorMsg <- paste(errorMsg, "Headers : ", "\n", sep = "") + for (name in names(self$headers)) { + errorMsg <- paste(errorMsg, name, " : ", self$headers[[name]], "\n", sep = " ") + } + } + if (!is.null(self$body)) { + errorMsg <- paste(errorMsg, "Body : ", "\n", sep = "") + errorMsg <- paste(errorMsg, self$body, "\n") + } + if (!is.null(self$error_object)) { + errorMsg <- paste(errorMsg, "Error object : ", "\n", sep = "") + errorMsg <- paste(errorMsg, self$error_object$toJSONString(), "\n") + } + errorMsg + } + ) +) diff --git a/samples/client/petstore/R-httr2/R/api_response.R b/samples/client/petstore/R-httr2/R/api_response.R new file mode 100644 index 0000000000..70431ae7e5 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/api_response.R @@ -0,0 +1,49 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title ApiResponse +#' @description ApiResponse Class +#' @format An \code{R6Class} generator object +#' @field content The deserialized response body. +#' @field response The raw response from the endpoint. +#' @field status_code The HTTP response status code. +#' @field status_code_desc The brief descriptoin of the HTTP response status code. +#' @field headers The HTTP response headers. +#' @export +ApiResponse <- R6::R6Class( + "ApiResponse", + public = list( + content = NULL, + response = NULL, + status_code = NULL, + status_code_desc = NULL, + headers = NULL, + #' Initialize a new ApiResponse class. + #' + #' @description + #' Initialize a new ApiResponse class. + #' + #' @param content The deserialized response body. + #' @param response The raw response from the endpoint. + #' @param status_code The HTTP response status code. + #' @param status_code_desc The brief description of the HTTP response status code. + #' @param headers The HTTP response headers. + #' @export + initialize = function(content = NULL, + response = NULL, + status_code = NULL, + status_code_desc = NULL, + headers = NULL) { + self$content <- content + self$response <- response + self$status_code <- status_code + self$status_code_desc <- status_code_desc + self$headers <- headers + } + ) +) diff --git a/samples/client/petstore/R-httr2/R/basque_pig.R b/samples/client/petstore/R-httr2/R/basque_pig.R new file mode 100644 index 0000000000..0a83d2b254 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/basque_pig.R @@ -0,0 +1,216 @@ +#' Create a new BasquePig +#' +#' @description +#' BasquePig Class +#' +#' @docType class +#' @title BasquePig +#' @description BasquePig Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field color character +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +BasquePig <- R6::R6Class( + "BasquePig", + public = list( + `className` = NULL, + `color` = NULL, + #' Initialize a new BasquePig class. + #' + #' @description + #' Initialize a new BasquePig class. + #' + #' @param className className + #' @param color color + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `color`, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!missing(`color`)) { + stopifnot(is.character(`color`), length(`color`) == 1) + self$`color` <- `color` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return BasquePig in JSON format + #' @export + toJSON = function() { + BasquePigObject <- list() + if (!is.null(self$`className`)) { + BasquePigObject[["className"]] <- + self$`className` + } + if (!is.null(self$`color`)) { + BasquePigObject[["color"]] <- + self$`color` + } + BasquePigObject + }, + #' Deserialize JSON string into an instance of BasquePig + #' + #' @description + #' Deserialize JSON string into an instance of BasquePig + #' + #' @param input_json the JSON input + #' @return the instance of BasquePig + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`color`)) { + self$`color` <- this_object$`color` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return BasquePig in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`color`)) { + sprintf( + '"color": + "%s" + ', + self$`color` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of BasquePig + #' + #' @description + #' Deserialize JSON string into an instance of BasquePig + #' + #' @param input_json the JSON input + #' @return the instance of BasquePig + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`color` <- this_object$`color` + self + }, + #' Validate JSON input with respect to BasquePig + #' + #' @description + #' Validate JSON input with respect to BasquePig and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for BasquePig: the required field `className` is missing.")) + } + # check the required field `color` + if (!is.null(input_json$`color`)) { + stopifnot(is.character(input_json$`color`), length(input_json$`color`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for BasquePig: the required field `color` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of BasquePig + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + # check if the required `color` is null + if (is.null(self$`color`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + # check if the required `color` is null + if (is.null(self$`color`)) { + invalid_fields["color"] <- "Non-nullable required field `color` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# BasquePig$unlock() +# +## Below is an example to define the print fnuction +# BasquePig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# BasquePig$lock() + diff --git a/samples/client/petstore/R-httr2/R/cat.R b/samples/client/petstore/R-httr2/R/cat.R new file mode 100644 index 0000000000..f9bfc07a9a --- /dev/null +++ b/samples/client/petstore/R-httr2/R/cat.R @@ -0,0 +1,224 @@ +#' Create a new Cat +#' +#' @description +#' Cat Class +#' +#' @docType class +#' @title Cat +#' @description Cat Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field color character [optional] +#' @field declawed character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Cat <- R6::R6Class( + "Cat", + inherit = Animal, + public = list( + `className` = NULL, + `color` = NULL, + `declawed` = NULL, + #' Initialize a new Cat class. + #' + #' @description + #' Initialize a new Cat class. + #' + #' @param className className + #' @param color color. Default to "red". + #' @param declawed declawed + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `color` = "red", `declawed` = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`color`)) { + stopifnot(is.character(`color`), length(`color`) == 1) + self$`color` <- `color` + } + if (!is.null(`declawed`)) { + stopifnot(is.logical(`declawed`), length(`declawed`) == 1) + self$`declawed` <- `declawed` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Cat in JSON format + #' @export + toJSON = function() { + CatObject <- list() + if (!is.null(self$`className`)) { + CatObject[["className"]] <- + self$`className` + } + if (!is.null(self$`color`)) { + CatObject[["color"]] <- + self$`color` + } + if (!is.null(self$`declawed`)) { + CatObject[["declawed"]] <- + self$`declawed` + } + CatObject + }, + #' Deserialize JSON string into an instance of Cat + #' + #' @description + #' Deserialize JSON string into an instance of Cat + #' + #' @param input_json the JSON input + #' @return the instance of Cat + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`color`)) { + self$`color` <- this_object$`color` + } + if (!is.null(this_object$`declawed`)) { + self$`declawed` <- this_object$`declawed` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Cat in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`color`)) { + sprintf( + '"color": + "%s" + ', + self$`color` + ) + }, + if (!is.null(self$`declawed`)) { + sprintf( + '"declawed": + %s + ', + tolower(self$`declawed`) + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Cat + #' + #' @description + #' Deserialize JSON string into an instance of Cat + #' + #' @param input_json the JSON input + #' @return the instance of Cat + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`color` <- this_object$`color` + self$`declawed` <- this_object$`declawed` + self + }, + #' Validate JSON input with respect to Cat + #' + #' @description + #' Validate JSON input with respect to Cat and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Cat: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Cat + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Cat$unlock() +# +## Below is an example to define the print fnuction +# Cat$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Cat$lock() + diff --git a/samples/client/petstore/R-httr2/R/cat_all_of.R b/samples/client/petstore/R-httr2/R/cat_all_of.R new file mode 100644 index 0000000000..b54b944cd2 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/cat_all_of.R @@ -0,0 +1,161 @@ +#' Create a new CatAllOf +#' +#' @description +#' CatAllOf Class +#' +#' @docType class +#' @title CatAllOf +#' @description CatAllOf Class +#' @format An \code{R6Class} generator object +#' @field declawed character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +CatAllOf <- R6::R6Class( + "CatAllOf", + public = list( + `declawed` = NULL, + #' Initialize a new CatAllOf class. + #' + #' @description + #' Initialize a new CatAllOf class. + #' + #' @param declawed declawed + #' @param ... Other optional arguments. + #' @export + initialize = function(`declawed` = NULL, ...) { + if (!is.null(`declawed`)) { + stopifnot(is.logical(`declawed`), length(`declawed`) == 1) + self$`declawed` <- `declawed` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return CatAllOf in JSON format + #' @export + toJSON = function() { + CatAllOfObject <- list() + if (!is.null(self$`declawed`)) { + CatAllOfObject[["declawed"]] <- + self$`declawed` + } + CatAllOfObject + }, + #' Deserialize JSON string into an instance of CatAllOf + #' + #' @description + #' Deserialize JSON string into an instance of CatAllOf + #' + #' @param input_json the JSON input + #' @return the instance of CatAllOf + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`declawed`)) { + self$`declawed` <- this_object$`declawed` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return CatAllOf in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`declawed`)) { + sprintf( + '"declawed": + %s + ', + tolower(self$`declawed`) + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of CatAllOf + #' + #' @description + #' Deserialize JSON string into an instance of CatAllOf + #' + #' @param input_json the JSON input + #' @return the instance of CatAllOf + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`declawed` <- this_object$`declawed` + self + }, + #' Validate JSON input with respect to CatAllOf + #' + #' @description + #' Validate JSON input with respect to CatAllOf and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of CatAllOf + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# CatAllOf$unlock() +# +## Below is an example to define the print fnuction +# CatAllOf$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# CatAllOf$lock() + diff --git a/samples/client/petstore/R-httr2/R/category.R b/samples/client/petstore/R-httr2/R/category.R new file mode 100644 index 0000000000..ab4f475202 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/category.R @@ -0,0 +1,192 @@ +#' Create a new Category +#' +#' @description +#' A category for a pet +#' +#' @docType class +#' @title Category +#' @description Category Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field name character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Category <- R6::R6Class( + "Category", + public = list( + `id` = NULL, + `name` = NULL, + #' Initialize a new Category class. + #' + #' @description + #' Initialize a new Category class. + #' + #' @param id id + #' @param name name + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `name` = NULL, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Category in JSON format + #' @export + toJSON = function() { + CategoryObject <- list() + if (!is.null(self$`id`)) { + CategoryObject[["id"]] <- + self$`id` + } + if (!is.null(self$`name`)) { + CategoryObject[["name"]] <- + self$`name` + } + CategoryObject + }, + #' Deserialize JSON string into an instance of Category + #' + #' @description + #' Deserialize JSON string into an instance of Category + #' + #' @param input_json the JSON input + #' @return the instance of Category + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`name`)) { + self$`name` <- this_object$`name` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Category in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`name`)) { + sprintf( + '"name": + "%s" + ', + self$`name` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Category + #' + #' @description + #' Deserialize JSON string into an instance of Category + #' + #' @param input_json the JSON input + #' @return the instance of Category + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`name` <- this_object$`name` + self + }, + #' Validate JSON input with respect to Category + #' + #' @description + #' Validate JSON input with respect to Category and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Category + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + if (!str_detect(self$`name`, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + if (!str_detect(self$`name`, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")) { + invalid_fields["name"] <- "Invalid value for `name`, must conform to the pattern ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Category$unlock() +# +## Below is an example to define the print fnuction +# Category$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Category$lock() + diff --git a/samples/client/petstore/R-httr2/R/danish_pig.R b/samples/client/petstore/R-httr2/R/danish_pig.R new file mode 100644 index 0000000000..206cdeca85 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/danish_pig.R @@ -0,0 +1,216 @@ +#' Create a new DanishPig +#' +#' @description +#' DanishPig Class +#' +#' @docType class +#' @title DanishPig +#' @description DanishPig Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field size integer +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +DanishPig <- R6::R6Class( + "DanishPig", + public = list( + `className` = NULL, + `size` = NULL, + #' Initialize a new DanishPig class. + #' + #' @description + #' Initialize a new DanishPig class. + #' + #' @param className className + #' @param size size + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `size`, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!missing(`size`)) { + stopifnot(is.numeric(`size`), length(`size`) == 1) + self$`size` <- `size` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DanishPig in JSON format + #' @export + toJSON = function() { + DanishPigObject <- list() + if (!is.null(self$`className`)) { + DanishPigObject[["className"]] <- + self$`className` + } + if (!is.null(self$`size`)) { + DanishPigObject[["size"]] <- + self$`size` + } + DanishPigObject + }, + #' Deserialize JSON string into an instance of DanishPig + #' + #' @description + #' Deserialize JSON string into an instance of DanishPig + #' + #' @param input_json the JSON input + #' @return the instance of DanishPig + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`size`)) { + self$`size` <- this_object$`size` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DanishPig in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`size`)) { + sprintf( + '"size": + %d + ', + self$`size` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of DanishPig + #' + #' @description + #' Deserialize JSON string into an instance of DanishPig + #' + #' @param input_json the JSON input + #' @return the instance of DanishPig + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`size` <- this_object$`size` + self + }, + #' Validate JSON input with respect to DanishPig + #' + #' @description + #' Validate JSON input with respect to DanishPig and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for DanishPig: the required field `className` is missing.")) + } + # check the required field `size` + if (!is.null(input_json$`size`)) { + stopifnot(is.numeric(input_json$`size`), length(input_json$`size`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for DanishPig: the required field `size` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of DanishPig + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + # check if the required `size` is null + if (is.null(self$`size`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + # check if the required `size` is null + if (is.null(self$`size`)) { + invalid_fields["size"] <- "Non-nullable required field `size` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# DanishPig$unlock() +# +## Below is an example to define the print fnuction +# DanishPig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# DanishPig$lock() + diff --git a/samples/client/petstore/R-httr2/R/date.R b/samples/client/petstore/R-httr2/R/date.R new file mode 100644 index 0000000000..8af974b7ae --- /dev/null +++ b/samples/client/petstore/R-httr2/R/date.R @@ -0,0 +1,255 @@ +#' Create a new Date +#' +#' @description +#' to test the model name `Date` +#' +#' @docType class +#' @title Date +#' @description Date Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field percent_description using \% in the description character [optional] +#' @field url_property character +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Date <- R6::R6Class( + "Date", + public = list( + `className` = NULL, + `percent_description` = NULL, + `url_property` = NULL, + #' Initialize a new Date class. + #' + #' @description + #' Initialize a new Date class. + #' + #' @param className className + #' @param url_property url_property + #' @param percent_description using \% in the description + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `url_property`, `percent_description` = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!missing(`url_property`)) { + stopifnot(is.character(`url_property`), length(`url_property`) == 1) + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", `url_property`)) + } + self$`url_property` <- `url_property` + } + if (!is.null(`percent_description`)) { + stopifnot(is.character(`percent_description`), length(`percent_description`) == 1) + self$`percent_description` <- `percent_description` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Date in JSON format + #' @export + toJSON = function() { + DateObject <- list() + if (!is.null(self$`className`)) { + DateObject[["className"]] <- + self$`className` + } + if (!is.null(self$`percent_description`)) { + DateObject[["percent_description"]] <- + self$`percent_description` + } + if (!is.null(self$`url_property`)) { + DateObject[["url_property"]] <- + self$`url_property` + } + DateObject + }, + #' Deserialize JSON string into an instance of Date + #' + #' @description + #' Deserialize JSON string into an instance of Date + #' + #' @param input_json the JSON input + #' @return the instance of Date + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`percent_description`)) { + self$`percent_description` <- this_object$`percent_description` + } + if (!is.null(this_object$`url_property`)) { + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(this_object$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", this_object$`url_property`)) + } + self$`url_property` <- this_object$`url_property` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Date in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`percent_description`)) { + sprintf( + '"percent_description": + "%s" + ', + self$`percent_description` + ) + }, + if (!is.null(self$`url_property`)) { + sprintf( + '"url_property": + "%s" + ', + self$`url_property` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Date + #' + #' @description + #' Deserialize JSON string into an instance of Date + #' + #' @param input_json the JSON input + #' @return the instance of Date + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`percent_description` <- this_object$`percent_description` + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(this_object$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", this_object$`url_property`)) + } + self$`url_property` <- this_object$`url_property` + self + }, + #' Validate JSON input with respect to Date + #' + #' @description + #' Validate JSON input with respect to Date and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Date: the required field `className` is missing.")) + } + # check the required field `url_property` + if (!is.null(input_json$`url_property`)) { + stopifnot(is.character(input_json$`url_property`), length(input_json$`url_property`) == 1) + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(input_json$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", input_json$`url_property`)) + } + } else { + stop(paste("The JSON input `", input, "` is invalid for Date: the required field `url_property` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Date + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + # check if the required `url_property` is null + if (is.null(self$`url_property`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + # check if the required `url_property` is null + if (is.null(self$`url_property`)) { + invalid_fields["url_property"] <- "Non-nullable required field `url_property` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Date$unlock() +# +## Below is an example to define the print fnuction +# Date$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Date$lock() + diff --git a/samples/client/petstore/R-httr2/R/dog.R b/samples/client/petstore/R-httr2/R/dog.R new file mode 100644 index 0000000000..75299cdfc7 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/dog.R @@ -0,0 +1,224 @@ +#' Create a new Dog +#' +#' @description +#' Dog Class +#' +#' @docType class +#' @title Dog +#' @description Dog Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field color character [optional] +#' @field breed character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Dog <- R6::R6Class( + "Dog", + inherit = Animal, + public = list( + `className` = NULL, + `color` = NULL, + `breed` = NULL, + #' Initialize a new Dog class. + #' + #' @description + #' Initialize a new Dog class. + #' + #' @param className className + #' @param color color. Default to "red". + #' @param breed breed + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `color` = "red", `breed` = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`color`)) { + stopifnot(is.character(`color`), length(`color`) == 1) + self$`color` <- `color` + } + if (!is.null(`breed`)) { + stopifnot(is.character(`breed`), length(`breed`) == 1) + self$`breed` <- `breed` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Dog in JSON format + #' @export + toJSON = function() { + DogObject <- list() + if (!is.null(self$`className`)) { + DogObject[["className"]] <- + self$`className` + } + if (!is.null(self$`color`)) { + DogObject[["color"]] <- + self$`color` + } + if (!is.null(self$`breed`)) { + DogObject[["breed"]] <- + self$`breed` + } + DogObject + }, + #' Deserialize JSON string into an instance of Dog + #' + #' @description + #' Deserialize JSON string into an instance of Dog + #' + #' @param input_json the JSON input + #' @return the instance of Dog + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`color`)) { + self$`color` <- this_object$`color` + } + if (!is.null(this_object$`breed`)) { + self$`breed` <- this_object$`breed` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Dog in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`color`)) { + sprintf( + '"color": + "%s" + ', + self$`color` + ) + }, + if (!is.null(self$`breed`)) { + sprintf( + '"breed": + "%s" + ', + self$`breed` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Dog + #' + #' @description + #' Deserialize JSON string into an instance of Dog + #' + #' @param input_json the JSON input + #' @return the instance of Dog + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`color` <- this_object$`color` + self$`breed` <- this_object$`breed` + self + }, + #' Validate JSON input with respect to Dog + #' + #' @description + #' Validate JSON input with respect to Dog and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Dog: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Dog + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Dog$unlock() +# +## Below is an example to define the print fnuction +# Dog$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Dog$lock() + diff --git a/samples/client/petstore/R-httr2/R/dog_all_of.R b/samples/client/petstore/R-httr2/R/dog_all_of.R new file mode 100644 index 0000000000..fc8e7d0a6d --- /dev/null +++ b/samples/client/petstore/R-httr2/R/dog_all_of.R @@ -0,0 +1,161 @@ +#' Create a new DogAllOf +#' +#' @description +#' DogAllOf Class +#' +#' @docType class +#' @title DogAllOf +#' @description DogAllOf Class +#' @format An \code{R6Class} generator object +#' @field breed character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +DogAllOf <- R6::R6Class( + "DogAllOf", + public = list( + `breed` = NULL, + #' Initialize a new DogAllOf class. + #' + #' @description + #' Initialize a new DogAllOf class. + #' + #' @param breed breed + #' @param ... Other optional arguments. + #' @export + initialize = function(`breed` = NULL, ...) { + if (!is.null(`breed`)) { + stopifnot(is.character(`breed`), length(`breed`) == 1) + self$`breed` <- `breed` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DogAllOf in JSON format + #' @export + toJSON = function() { + DogAllOfObject <- list() + if (!is.null(self$`breed`)) { + DogAllOfObject[["breed"]] <- + self$`breed` + } + DogAllOfObject + }, + #' Deserialize JSON string into an instance of DogAllOf + #' + #' @description + #' Deserialize JSON string into an instance of DogAllOf + #' + #' @param input_json the JSON input + #' @return the instance of DogAllOf + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`breed`)) { + self$`breed` <- this_object$`breed` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return DogAllOf in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`breed`)) { + sprintf( + '"breed": + "%s" + ', + self$`breed` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of DogAllOf + #' + #' @description + #' Deserialize JSON string into an instance of DogAllOf + #' + #' @param input_json the JSON input + #' @return the instance of DogAllOf + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`breed` <- this_object$`breed` + self + }, + #' Validate JSON input with respect to DogAllOf + #' + #' @description + #' Validate JSON input with respect to DogAllOf and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of DogAllOf + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# DogAllOf$unlock() +# +## Below is an example to define the print fnuction +# DogAllOf$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# DogAllOf$lock() + diff --git a/samples/client/petstore/R-httr2/R/fake_api.R b/samples/client/petstore/R-httr2/R/fake_api.R new file mode 100644 index 0000000000..3ead57443a --- /dev/null +++ b/samples/client/petstore/R-httr2/R/fake_api.R @@ -0,0 +1,857 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title Fake operations +#' @description FakeApi +#' @format An \code{R6Class} generator object +#' @field api_client Handles the client-server communication. +#' +#' @section Methods: +#' \describe{ +#' \strong{ add_pet_optional } \emph{ Add a new pet to the store (optional body) } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet \link{Pet} +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 405 | Invalid input +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ fake_data_file } \emph{ test data_file to ensure it's escaped correctly } +#' +#' +#' \itemize{ +#' \item \emph{ @param } dummy character +#' \item \emph{ @param } var_data_file character +#' \item \emph{ @returnType } \link{User} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : User +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ fake_path_array } \emph{ test array parameter in path } +#' +#' +#' \itemize{ +#' \item \emph{ @param } path_array list( character ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ fake_regular_expression } \emph{ test regular expression to ensure no exception } +#' +#' +#' \itemize{ +#' \item \emph{ @param } reg_exp_test character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ fake_set_query } \emph{ test set query parameter } +#' +#' +#' \itemize{ +#' \item \emph{ @param } set_dummy list( character ) +#' \item \emph{ @param } array_dummy list( character ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' } +#' +#' +#' @examples +#' \dontrun{ +#' #################### add_pet_optional #################### +#' +#' library(petstore) +#' var_pet <- Pet$new() # Pet | Pet object that needs to be added to the store +#' +#' #Add a new pet to the store (optional body) +#' api_instance <- FakeApi$new() +#' +#' # Configure HTTP basic authorization: http_auth +#' api_instance$api_client$username <- Sys.getenv("USERNAME") +#' api_instance$api_client$password <- Sys.getenv("PASSWORD") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$add_pet_optional(pet = var_pet, data_file = "result.txt"), +#' +#' +#' api_instance$add_pet_optional(pet = var_pet), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `add_pet_optional`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### fake_data_file #################### +#' +#' library(petstore) +#' var_dummy <- "dummy_example" # character | dummy required parameter +#' var_var_data_file <- "var_data_file_example" # character | header data file +#' +#' #test data_file to ensure it's escaped correctly +#' api_instance <- FakeApi$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$fake_data_file(var_dummy, var_data_file = var_var_data_file, data_file = "result.txt"), +#' +#' +#' api_instance$fake_data_file(var_dummy, var_data_file = var_var_data_file), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `fake_data_file`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### fake_path_array #################### +#' +#' library(petstore) +#' var_path_array <- ["path_array_example"] # array[character] | dummy path parameter +#' +#' #test array parameter in path +#' api_instance <- FakeApi$new() +#' +#' result <- tryCatch( +#' +#' api_instance$fake_path_array(var_path_array), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `fake_path_array`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### fake_regular_expression #################### +#' +#' library(petstore) +#' var_reg_exp_test <- "reg_exp_test_example" # character | dummy required parameter +#' +#' #test regular expression to ensure no exception +#' api_instance <- FakeApi$new() +#' +#' result <- tryCatch( +#' +#' api_instance$fake_regular_expression(var_reg_exp_test), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `fake_regular_expression`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### fake_set_query #################### +#' +#' library(petstore) +#' var_set_dummy <- ["set_dummy_example"] # set[character] | set query +#' var_array_dummy <- ["array_dummy_example"] # array[character] | array query +#' +#' #test set query parameter +#' api_instance <- FakeApi$new() +#' +#' result <- tryCatch( +#' +#' api_instance$fake_set_query(var_set_dummy, var_array_dummy), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `fake_set_query`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' } +#' @importFrom R6 R6Class +#' @importFrom base64enc base64encode +#' @importFrom rlang abort +#' @export +FakeApi <- R6::R6Class( + "FakeApi", + public = list( + api_client = NULL, + #' Initialize a new FakeApi. + #' + #' @description + #' Initialize a new FakeApi. + #' + #' @param api_client An instance of API client. + #' @export + initialize = function(api_client) { + if (!missing(api_client)) { + self$api_client <- api_client + } else { + self$api_client <- ApiClient$new() + } + }, + #' Add a new pet to the store (optional body) + #' + #' @description + #' Add a new pet to the store (optional body) + #' + #' @param pet (optional) Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + add_pet_optional = function(pet = NULL, data_file = NULL, ...) { + local_var_response <- self$add_pet_optional_with_http_info(pet, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Add a new pet to the store (optional body) + #' + #' @description + #' Add a new pet to the store (optional body) + #' + #' @param pet (optional) Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + add_pet_optional_with_http_info = function(pet = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + + if (!is.null(`pet`)) { + local_var_body <- `pet`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/fake/test_optional_body_parameter" + # HTTP basic auth + if (!is.null(self$api_client$username) || !is.null(self$api_client$password)) { + header_params["Authorization"] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$api_client$username, self$api_client$password, sep = ":")))) + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json", "application/xml", "multipart/related") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test data_file to ensure it's escaped correctly + #' + #' @description + #' test data_file to ensure it's escaped correctly + #' + #' @param dummy dummy required parameter + #' @param var_data_file (optional) header data file + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return User + #' @export + fake_data_file = function(dummy, var_data_file = NULL, data_file = NULL, ...) { + local_var_response <- self$fake_data_file_with_http_info(dummy, var_data_file, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test data_file to ensure it's escaped correctly + #' + #' @description + #' test data_file to ensure it's escaped correctly + #' + #' @param dummy dummy required parameter + #' @param var_data_file (optional) header data file + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (User) with additional information such as HTTP status code, headers + #' @export + fake_data_file_with_http_info = function(dummy, var_data_file = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`dummy`)) { + rlang::abort(message = "Missing required parameter `dummy`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `dummy`.")) + } + + + + header_params["dummy"] <- `dummy` + + header_params["data_file"] <- `var_data_file` + + local_var_url_path <- "/fake/data_file" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "User", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test array parameter in path + #' + #' @description + #' test array parameter in path + #' + #' @param path_array dummy path parameter + #' @param ... Other optional arguments + #' @return void + #' @export + fake_path_array = function(path_array, ...) { + local_var_response <- self$fake_path_array_with_http_info(path_array, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test array parameter in path + #' + #' @description + #' test array parameter in path + #' + #' @param path_array dummy path parameter + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + fake_path_array_with_http_info = function(path_array, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`path_array`)) { + rlang::abort(message = "Missing required parameter `path_array`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `path_array`.")) + } + + + local_var_url_path <- "/fake/path_array/{path_array}/testing" + if (!missing(`path_array`)) { + local_var_url_path <- gsub("\\{path_array\\}", paste(URLencode(as.character(`path_array`), reserved = TRUE), collapse= ",", sep=""), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test regular expression to ensure no exception + #' + #' @description + #' test regular expression to ensure no exception + #' + #' @param reg_exp_test dummy required parameter + #' @param ... Other optional arguments + #' @return void + #' @export + fake_regular_expression = function(reg_exp_test, ...) { + local_var_response <- self$fake_regular_expression_with_http_info(reg_exp_test, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test regular expression to ensure no exception + #' + #' @description + #' test regular expression to ensure no exception + #' + #' @param reg_exp_test dummy required parameter + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + fake_regular_expression_with_http_info = function(reg_exp_test, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`reg_exp_test`)) { + rlang::abort(message = "Missing required parameter `reg_exp_test`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `reg_exp_test`.")) + } + + if (!str_detect(`reg_exp_test`, "^[A-Za-z0-9_]{1,15}$")) { + rlang::abort(message = "Invalid value for `reg_exp_test` when calling FakeApi$fake_regular_expression, must conform to the pattern ^[A-Za-z0-9_]{1,15}$.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `reg_exp_test` when calling FakeApi$fake_regular_expression, must conform to the pattern ^[A-Za-z0-9_]{1,15}$.")) + } + + header_params["reg_exp_test"] <- `reg_exp_test` + + local_var_url_path <- "/fake/regular_expression" + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test set query parameter + #' + #' @description + #' test set query parameter + #' + #' @param set_dummy set query + #' @param array_dummy array query + #' @param ... Other optional arguments + #' @return void + #' @export + fake_set_query = function(set_dummy, array_dummy, ...) { + local_var_response <- self$fake_set_query_with_http_info(set_dummy, array_dummy, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test set query parameter + #' + #' @description + #' test set query parameter + #' + #' @param set_dummy set query + #' @param array_dummy array query + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + fake_set_query_with_http_info = function(set_dummy, array_dummy, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`set_dummy`)) { + rlang::abort(message = "Missing required parameter `set_dummy`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `set_dummy`.")) + } + + if (missing(`array_dummy`)) { + rlang::abort(message = "Missing required parameter `array_dummy`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `array_dummy`.")) + } + + + + # check if items are unique + if (!identical(`set_dummy`, unique(`set_dummy`))) { + rlang::abort(message = "Invalid value for `set_dummy` when calling FakeApi$fake_set_query. Items must be unique.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `set_dummy` when calling FakeApi$fake_set_query. Items must be unique.")) + } + # explore + for (query_item in `set_dummy`) { + query_params[["set_dummy"]] <- c(query_params[["set_dummy"]], list(`set_dummy` = query_item)) + } + + # explore + for (query_item in `array_dummy`) { + query_params[["array_dummy"]] <- c(query_params[["array_dummy"]], list(`array_dummy` = query_item)) + } + + local_var_url_path <- "/fake/set_query_parameter" + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2/R/mammal.R b/samples/client/petstore/R-httr2/R/mammal.R new file mode 100644 index 0000000000..4b21d8564c --- /dev/null +++ b/samples/client/petstore/R-httr2/R/mammal.R @@ -0,0 +1,200 @@ +#' @docType class +#' @title Mammal +#' +#' @description Mammal Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Mammal <- R6::R6Class( + "Mammal", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("Whale", "Zebra"), + #' Initialize a new Mammal. + #' + #' @description + #' Initialize a new Mammal. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "Whale", "Zebra" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "Whale") { + self$actual_instance <- instance + self$actual_type <- "Whale" + } else if (get(class(instance)[[1]], pos = -1)$classname == "Zebra") { + self$actual_instance <- instance + self$actual_type <- "Zebra" + } else { + stop(paste("Failed to initialize Mammal with oneOf schemas Whale, Zebra. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of Mammal. + #' + #' @description + #' Deserialize JSON string into an instance of Mammal. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of Mammal. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of Mammal. + #' + #' @description + #' Deserialize JSON string into an instance of Mammal. + #' + #' @param input The input JSON. + #' @return An instance of Mammal. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + Whale_result <- tryCatch({ + Whale$public_methods$validateJSON(input) + Whale_instance <- Whale$new() + instance <- Whale_instance$fromJSON(input) + instance_type <- "Whale" + matched_schemas <- append(matched_schemas, "Whale") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(Whale_result["error"])) { + error_messages <- append(error_messages, Whale_result["message"]) + } + + Zebra_result <- tryCatch({ + Zebra$public_methods$validateJSON(input) + Zebra_instance <- Zebra$new() + instance <- Zebra_instance$fromJSON(input) + instance_type <- "Zebra" + matched_schemas <- append(matched_schemas, "Zebra") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(Zebra_result["error"])) { + error_messages <- append(error_messages, Zebra_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into Mammal with oneOf schemas Whale, Zebra.") + } else { + # no match + stop(paste("No match found when deserializing the payload into Mammal with oneOf schemas Whale, Zebra. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize Mammal to JSON string. + #' + #' @description + #' Serialize Mammal to JSON string. + #' + #' @return JSON string representation of the Mammal. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize Mammal to JSON. + #' + #' @description + #' Serialize Mammal to JSON. + #' + #' @return JSON representation of the Mammal. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to Mammal. + #' + #' @description + #' Validate the input JSON with respect to Mammal and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#Mammal$unlock() +# +## Below is an example to define the print fnuction +#Mammal$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#Mammal$lock() + diff --git a/samples/client/petstore/R-httr2/R/model_api_response.R b/samples/client/petstore/R-httr2/R/model_api_response.R new file mode 100644 index 0000000000..de8760bdf2 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/model_api_response.R @@ -0,0 +1,207 @@ +#' Create a new ModelApiResponse +#' +#' @description +#' Describes the result of uploading an image resource +#' +#' @docType class +#' @title ModelApiResponse +#' @description ModelApiResponse Class +#' @format An \code{R6Class} generator object +#' @field code integer [optional] +#' @field type character [optional] +#' @field message character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +ModelApiResponse <- R6::R6Class( + "ModelApiResponse", + public = list( + `code` = NULL, + `type` = NULL, + `message` = NULL, + #' Initialize a new ModelApiResponse class. + #' + #' @description + #' Initialize a new ModelApiResponse class. + #' + #' @param code code + #' @param type type + #' @param message message + #' @param ... Other optional arguments. + #' @export + initialize = function(`code` = NULL, `type` = NULL, `message` = NULL, ...) { + if (!is.null(`code`)) { + stopifnot(is.numeric(`code`), length(`code`) == 1) + self$`code` <- `code` + } + if (!is.null(`type`)) { + stopifnot(is.character(`type`), length(`type`) == 1) + self$`type` <- `type` + } + if (!is.null(`message`)) { + stopifnot(is.character(`message`), length(`message`) == 1) + self$`message` <- `message` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return ModelApiResponse in JSON format + #' @export + toJSON = function() { + ModelApiResponseObject <- list() + if (!is.null(self$`code`)) { + ModelApiResponseObject[["code"]] <- + self$`code` + } + if (!is.null(self$`type`)) { + ModelApiResponseObject[["type"]] <- + self$`type` + } + if (!is.null(self$`message`)) { + ModelApiResponseObject[["message"]] <- + self$`message` + } + ModelApiResponseObject + }, + #' Deserialize JSON string into an instance of ModelApiResponse + #' + #' @description + #' Deserialize JSON string into an instance of ModelApiResponse + #' + #' @param input_json the JSON input + #' @return the instance of ModelApiResponse + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`code`)) { + self$`code` <- this_object$`code` + } + if (!is.null(this_object$`type`)) { + self$`type` <- this_object$`type` + } + if (!is.null(this_object$`message`)) { + self$`message` <- this_object$`message` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return ModelApiResponse in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`code`)) { + sprintf( + '"code": + %d + ', + self$`code` + ) + }, + if (!is.null(self$`type`)) { + sprintf( + '"type": + "%s" + ', + self$`type` + ) + }, + if (!is.null(self$`message`)) { + sprintf( + '"message": + "%s" + ', + self$`message` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of ModelApiResponse + #' + #' @description + #' Deserialize JSON string into an instance of ModelApiResponse + #' + #' @param input_json the JSON input + #' @return the instance of ModelApiResponse + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`code` <- this_object$`code` + self$`type` <- this_object$`type` + self$`message` <- this_object$`message` + self + }, + #' Validate JSON input with respect to ModelApiResponse + #' + #' @description + #' Validate JSON input with respect to ModelApiResponse and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of ModelApiResponse + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# ModelApiResponse$unlock() +# +## Below is an example to define the print fnuction +# ModelApiResponse$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# ModelApiResponse$lock() + diff --git a/samples/client/petstore/R-httr2/R/nested_one_of.R b/samples/client/petstore/R-httr2/R/nested_one_of.R new file mode 100644 index 0000000000..542a11c4d2 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/nested_one_of.R @@ -0,0 +1,186 @@ +#' Create a new NestedOneOf +#' +#' @description +#' NestedOneOf Class +#' +#' @docType class +#' @title NestedOneOf +#' @description NestedOneOf Class +#' @format An \code{R6Class} generator object +#' @field size integer [optional] +#' @field nested_pig \link{Pig} [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +NestedOneOf <- R6::R6Class( + "NestedOneOf", + public = list( + `size` = NULL, + `nested_pig` = NULL, + #' Initialize a new NestedOneOf class. + #' + #' @description + #' Initialize a new NestedOneOf class. + #' + #' @param size size + #' @param nested_pig nested_pig + #' @param ... Other optional arguments. + #' @export + initialize = function(`size` = NULL, `nested_pig` = NULL, ...) { + if (!is.null(`size`)) { + stopifnot(is.numeric(`size`), length(`size`) == 1) + self$`size` <- `size` + } + if (!is.null(`nested_pig`)) { + stopifnot(R6::is.R6(`nested_pig`)) + self$`nested_pig` <- `nested_pig` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return NestedOneOf in JSON format + #' @export + toJSON = function() { + NestedOneOfObject <- list() + if (!is.null(self$`size`)) { + NestedOneOfObject[["size"]] <- + self$`size` + } + if (!is.null(self$`nested_pig`)) { + NestedOneOfObject[["nested_pig"]] <- + self$`nested_pig`$toJSON() + } + NestedOneOfObject + }, + #' Deserialize JSON string into an instance of NestedOneOf + #' + #' @description + #' Deserialize JSON string into an instance of NestedOneOf + #' + #' @param input_json the JSON input + #' @return the instance of NestedOneOf + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`size`)) { + self$`size` <- this_object$`size` + } + if (!is.null(this_object$`nested_pig`)) { + nested_pig_object <- Pig$new() + nested_pig_object$fromJSON(jsonlite::toJSON(this_object$nested_pig, auto_unbox = TRUE, digits = NA)) + self$`nested_pig` <- nested_pig_object + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return NestedOneOf in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`size`)) { + sprintf( + '"size": + %d + ', + self$`size` + ) + }, + if (!is.null(self$`nested_pig`)) { + sprintf( + '"nested_pig": + %s + ', + jsonlite::toJSON(self$`nested_pig`$toJSON(), auto_unbox = TRUE, digits = NA) + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of NestedOneOf + #' + #' @description + #' Deserialize JSON string into an instance of NestedOneOf + #' + #' @param input_json the JSON input + #' @return the instance of NestedOneOf + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`size` <- this_object$`size` + self$`nested_pig` <- Pig$new()$fromJSON(jsonlite::toJSON(this_object$nested_pig, auto_unbox = TRUE, digits = NA)) + self + }, + #' Validate JSON input with respect to NestedOneOf + #' + #' @description + #' Validate JSON input with respect to NestedOneOf and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of NestedOneOf + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# NestedOneOf$unlock() +# +## Below is an example to define the print fnuction +# NestedOneOf$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# NestedOneOf$lock() + diff --git a/samples/client/petstore/R-httr2/R/one_of_primitive_type_test.R b/samples/client/petstore/R-httr2/R/one_of_primitive_type_test.R new file mode 100644 index 0000000000..d558c0eb50 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/one_of_primitive_type_test.R @@ -0,0 +1,202 @@ +#' @docType class +#' @title OneOfPrimitiveTypeTest +#' +#' @description OneOfPrimitiveTypeTest Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +OneOfPrimitiveTypeTest <- R6::R6Class( + "OneOfPrimitiveTypeTest", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("character", "integer"), + #' Initialize a new OneOfPrimitiveTypeTest. + #' + #' @description + #' Initialize a new OneOfPrimitiveTypeTest. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "character", "integer" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "character") { + self$actual_instance <- instance + self$actual_type <- "character" + } else if (get(class(instance)[[1]], pos = -1)$classname == "integer") { + self$actual_instance <- instance + self$actual_type <- "integer" + } else { + stop(paste("Failed to initialize OneOfPrimitiveTypeTest with oneOf schemas character, integer. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of OneOfPrimitiveTypeTest. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' + #' @param input The input JSON. + #' @return An instance of OneOfPrimitiveTypeTest. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + integer_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "integer") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "integer", typeof(instance))) + } + instance_type <- "integer" + matched_schemas <- append(matched_schemas, "integer") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(integer_result["error"])) { + error_messages <- append(error_messages, integer_result["message"]) + } + + character_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "character") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "character", typeof(instance))) + } + instance_type <- "character" + matched_schemas <- append(matched_schemas, "character") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(character_result["error"])) { + error_messages <- append(error_messages, character_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into OneOfPrimitiveTypeTest with oneOf schemas character, integer.") + } else { + # no match + stop(paste("No match found when deserializing the payload into OneOfPrimitiveTypeTest with oneOf schemas character, integer. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize OneOfPrimitiveTypeTest to JSON string. + #' + #' @description + #' Serialize OneOfPrimitiveTypeTest to JSON string. + #' + #' @return JSON string representation of the OneOfPrimitiveTypeTest. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize OneOfPrimitiveTypeTest to JSON. + #' + #' @description + #' Serialize OneOfPrimitiveTypeTest to JSON. + #' + #' @return JSON representation of the OneOfPrimitiveTypeTest. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to OneOfPrimitiveTypeTest. + #' + #' @description + #' Validate the input JSON with respect to OneOfPrimitiveTypeTest and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#OneOfPrimitiveTypeTest$unlock() +# +## Below is an example to define the print fnuction +#OneOfPrimitiveTypeTest$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#OneOfPrimitiveTypeTest$lock() + diff --git a/samples/client/petstore/R-httr2/R/order.R b/samples/client/petstore/R-httr2/R/order.R new file mode 100644 index 0000000000..01b511bb35 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/order.R @@ -0,0 +1,285 @@ +#' Create a new Order +#' +#' @description +#' An order for a pets from the pet store +#' +#' @docType class +#' @title Order +#' @description Order Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field petId integer [optional] +#' @field quantity integer [optional] +#' @field shipDate character [optional] +#' @field status Order Status character [optional] +#' @field complete character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Order <- R6::R6Class( + "Order", + public = list( + `id` = NULL, + `petId` = NULL, + `quantity` = NULL, + `shipDate` = NULL, + `status` = NULL, + `complete` = NULL, + #' Initialize a new Order class. + #' + #' @description + #' Initialize a new Order class. + #' + #' @param id id + #' @param petId petId + #' @param quantity quantity + #' @param shipDate shipDate + #' @param status Order Status + #' @param complete complete. Default to FALSE. + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `petId` = NULL, `quantity` = NULL, `shipDate` = NULL, `status` = NULL, `complete` = FALSE, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`petId`)) { + stopifnot(is.numeric(`petId`), length(`petId`) == 1) + self$`petId` <- `petId` + } + if (!is.null(`quantity`)) { + stopifnot(is.numeric(`quantity`), length(`quantity`) == 1) + self$`quantity` <- `quantity` + } + if (!is.null(`shipDate`)) { + stopifnot(is.character(`shipDate`), length(`shipDate`) == 1) + self$`shipDate` <- `shipDate` + } + if (!is.null(`status`)) { + if (!(`status` %in% c("placed", "approved", "delivered"))) { + stop(paste("Error! \"", `status`, "\" cannot be assigned to `status`. Must be \"placed\", \"approved\", \"delivered\".", sep = "")) + } + stopifnot(is.character(`status`), length(`status`) == 1) + self$`status` <- `status` + } + if (!is.null(`complete`)) { + stopifnot(is.logical(`complete`), length(`complete`) == 1) + self$`complete` <- `complete` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Order in JSON format + #' @export + toJSON = function() { + OrderObject <- list() + if (!is.null(self$`id`)) { + OrderObject[["id"]] <- + self$`id` + } + if (!is.null(self$`petId`)) { + OrderObject[["petId"]] <- + self$`petId` + } + if (!is.null(self$`quantity`)) { + OrderObject[["quantity"]] <- + self$`quantity` + } + if (!is.null(self$`shipDate`)) { + OrderObject[["shipDate"]] <- + self$`shipDate` + } + if (!is.null(self$`status`)) { + OrderObject[["status"]] <- + self$`status` + } + if (!is.null(self$`complete`)) { + OrderObject[["complete"]] <- + self$`complete` + } + OrderObject + }, + #' Deserialize JSON string into an instance of Order + #' + #' @description + #' Deserialize JSON string into an instance of Order + #' + #' @param input_json the JSON input + #' @return the instance of Order + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`petId`)) { + self$`petId` <- this_object$`petId` + } + if (!is.null(this_object$`quantity`)) { + self$`quantity` <- this_object$`quantity` + } + if (!is.null(this_object$`shipDate`)) { + self$`shipDate` <- this_object$`shipDate` + } + if (!is.null(this_object$`status`)) { + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("placed", "approved", "delivered"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"placed\", \"approved\", \"delivered\".", sep = "")) + } + self$`status` <- this_object$`status` + } + if (!is.null(this_object$`complete`)) { + self$`complete` <- this_object$`complete` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Order in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`petId`)) { + sprintf( + '"petId": + %d + ', + self$`petId` + ) + }, + if (!is.null(self$`quantity`)) { + sprintf( + '"quantity": + %d + ', + self$`quantity` + ) + }, + if (!is.null(self$`shipDate`)) { + sprintf( + '"shipDate": + "%s" + ', + self$`shipDate` + ) + }, + if (!is.null(self$`status`)) { + sprintf( + '"status": + "%s" + ', + self$`status` + ) + }, + if (!is.null(self$`complete`)) { + sprintf( + '"complete": + %s + ', + tolower(self$`complete`) + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Order + #' + #' @description + #' Deserialize JSON string into an instance of Order + #' + #' @param input_json the JSON input + #' @return the instance of Order + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`petId` <- this_object$`petId` + self$`quantity` <- this_object$`quantity` + self$`shipDate` <- this_object$`shipDate` + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("placed", "approved", "delivered"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"placed\", \"approved\", \"delivered\".", sep = "")) + } + self$`status` <- this_object$`status` + self$`complete` <- this_object$`complete` + self + }, + #' Validate JSON input with respect to Order + #' + #' @description + #' Validate JSON input with respect to Order and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Order + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Order$unlock() +# +## Below is an example to define the print fnuction +# Order$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Order$lock() + diff --git a/samples/client/petstore/R-httr2/R/pet.R b/samples/client/petstore/R-httr2/R/pet.R new file mode 100644 index 0000000000..f840c7ca9a --- /dev/null +++ b/samples/client/petstore/R-httr2/R/pet.R @@ -0,0 +1,322 @@ +#' Create a new Pet +#' +#' @description +#' A pet for sale in the pet store +#' +#' @docType class +#' @title Pet +#' @description Pet Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field category \link{Category} [optional] +#' @field name character +#' @field photoUrls list(character) +#' @field tags list(\link{Tag}) [optional] +#' @field status pet status in the store character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Pet <- R6::R6Class( + "Pet", + public = list( + `id` = NULL, + `category` = NULL, + `name` = NULL, + `photoUrls` = NULL, + `tags` = NULL, + `status` = NULL, + #' Initialize a new Pet class. + #' + #' @description + #' Initialize a new Pet class. + #' + #' @param name name + #' @param photoUrls photoUrls + #' @param id id + #' @param category category + #' @param tags tags + #' @param status pet status in the store + #' @param ... Other optional arguments. + #' @export + initialize = function(`name`, `photoUrls`, `id` = NULL, `category` = NULL, `tags` = NULL, `status` = NULL, ...) { + if (!missing(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + if (!missing(`photoUrls`)) { + stopifnot(is.vector(`photoUrls`), length(`photoUrls`) != 0) + sapply(`photoUrls`, function(x) stopifnot(is.character(x))) + self$`photoUrls` <- `photoUrls` + } + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`category`)) { + stopifnot(R6::is.R6(`category`)) + self$`category` <- `category` + } + if (!is.null(`tags`)) { + stopifnot(is.vector(`tags`), length(`tags`) != 0) + sapply(`tags`, function(x) stopifnot(R6::is.R6(x))) + self$`tags` <- `tags` + } + if (!is.null(`status`)) { + if (!(`status` %in% c("available", "pending", "sold"))) { + stop(paste("Error! \"", `status`, "\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".", sep = "")) + } + stopifnot(is.character(`status`), length(`status`) == 1) + self$`status` <- `status` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Pet in JSON format + #' @export + toJSON = function() { + PetObject <- list() + if (!is.null(self$`id`)) { + PetObject[["id"]] <- + self$`id` + } + if (!is.null(self$`category`)) { + PetObject[["category"]] <- + self$`category`$toJSON() + } + if (!is.null(self$`name`)) { + PetObject[["name"]] <- + self$`name` + } + if (!is.null(self$`photoUrls`)) { + PetObject[["photoUrls"]] <- + self$`photoUrls` + } + if (!is.null(self$`tags`)) { + PetObject[["tags"]] <- + lapply(self$`tags`, function(x) x$toJSON()) + } + if (!is.null(self$`status`)) { + PetObject[["status"]] <- + self$`status` + } + PetObject + }, + #' Deserialize JSON string into an instance of Pet + #' + #' @description + #' Deserialize JSON string into an instance of Pet + #' + #' @param input_json the JSON input + #' @return the instance of Pet + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`category`)) { + category_object <- Category$new() + category_object$fromJSON(jsonlite::toJSON(this_object$category, auto_unbox = TRUE, digits = NA)) + self$`category` <- category_object + } + if (!is.null(this_object$`name`)) { + self$`name` <- this_object$`name` + } + if (!is.null(this_object$`photoUrls`)) { + self$`photoUrls` <- ApiClient$new()$deserializeObj(this_object$`photoUrls`, "array[character]", loadNamespace("petstore")) + } + if (!is.null(this_object$`tags`)) { + self$`tags` <- ApiClient$new()$deserializeObj(this_object$`tags`, "array[Tag]", loadNamespace("petstore")) + } + if (!is.null(this_object$`status`)) { + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("available", "pending", "sold"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".", sep = "")) + } + self$`status` <- this_object$`status` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Pet in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`category`)) { + sprintf( + '"category": + %s + ', + jsonlite::toJSON(self$`category`$toJSON(), auto_unbox = TRUE, digits = NA) + ) + }, + if (!is.null(self$`name`)) { + sprintf( + '"name": + "%s" + ', + self$`name` + ) + }, + if (!is.null(self$`photoUrls`)) { + sprintf( + '"photoUrls": + [%s] + ', + paste(unlist(lapply(self$`photoUrls`, function(x) paste0('"', x, '"'))), collapse = ",") + ) + }, + if (!is.null(self$`tags`)) { + sprintf( + '"tags": + [%s] +', + paste(sapply(self$`tags`, function(x) jsonlite::toJSON(x$toJSON(), auto_unbox = TRUE, digits = NA)), collapse = ",") + ) + }, + if (!is.null(self$`status`)) { + sprintf( + '"status": + "%s" + ', + self$`status` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Pet + #' + #' @description + #' Deserialize JSON string into an instance of Pet + #' + #' @param input_json the JSON input + #' @return the instance of Pet + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`category` <- Category$new()$fromJSON(jsonlite::toJSON(this_object$category, auto_unbox = TRUE, digits = NA)) + self$`name` <- this_object$`name` + self$`photoUrls` <- ApiClient$new()$deserializeObj(this_object$`photoUrls`, "array[character]", loadNamespace("petstore")) + self$`tags` <- ApiClient$new()$deserializeObj(this_object$`tags`, "array[Tag]", loadNamespace("petstore")) + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("available", "pending", "sold"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".", sep = "")) + } + self$`status` <- this_object$`status` + self + }, + #' Validate JSON input with respect to Pet + #' + #' @description + #' Validate JSON input with respect to Pet and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `name` + if (!is.null(input_json$`name`)) { + stopifnot(is.character(input_json$`name`), length(input_json$`name`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Pet: the required field `name` is missing.")) + } + # check the required field `photoUrls` + if (!is.null(input_json$`photoUrls`)) { + stopifnot(is.vector(input_json$`photoUrls`), length(input_json$`photoUrls`) != 0) + tmp <- sapply(input_json$`photoUrls`, function(x) stopifnot(is.character(x))) + } else { + stop(paste("The JSON input `", input, "` is invalid for Pet: the required field `photoUrls` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Pet + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `name` is null + if (is.null(self$`name`)) { + return(FALSE) + } + + # check if the required `photoUrls` is null + if (is.null(self$`photoUrls`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `name` is null + if (is.null(self$`name`)) { + invalid_fields["name"] <- "Non-nullable required field `name` cannot be null." + } + + # check if the required `photoUrls` is null + if (is.null(self$`photoUrls`)) { + invalid_fields["photoUrls"] <- "Non-nullable required field `photoUrls` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Pet$unlock() +# +## Below is an example to define the print fnuction +# Pet$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Pet$lock() + diff --git a/samples/client/petstore/R-httr2/R/pet_api.R b/samples/client/petstore/R-httr2/R/pet_api.R new file mode 100644 index 0000000000..563895e44b --- /dev/null +++ b/samples/client/petstore/R-httr2/R/pet_api.R @@ -0,0 +1,1882 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title Pet operations +#' @description PetApi +#' @format An \code{R6Class} generator object +#' @field api_client Handles the client-server communication. +#' +#' @section Methods: +#' \describe{ +#' \strong{ add_pet } \emph{ Add a new pet to the store } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet \link{Pet} +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 405 | Invalid input +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ delete_pet } \emph{ Deletes a pet } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @param } api_key character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 400 | Invalid pet value +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ find_pets_by_status } \emph{ Finds Pets by status } +#' Multiple status values can be provided with comma separated strings +#' +#' \itemize{ +#' \item \emph{ @param } status Enum < [available, pending, sold] > +#' \item \emph{ @returnType } list( \link{Pet} ) \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : array[Pet] +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid status value +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ find_pets_by_tags } \emph{ Finds Pets by tags } +#' Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +#' +#' \itemize{ +#' \item \emph{ @param } tags list( character ) +#' \item \emph{ @returnType } list( \link{Pet} ) \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : array[Pet] +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid tag value +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_pet_by_id } \emph{ Find pet by ID } +#' Returns a single pet +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Pet not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_pet_by_id_streaming } \emph{ Find pet by ID (streaming) } +#' Returns a single pet +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Pet not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ test_header } \emph{ Header test } +#' Header test +#' +#' \itemize{ +#' \item \emph{ @param } header_test_int integer +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Pet not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ update_pet } \emph{ Update an existing pet } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet \link{Pet} +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Pet not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 405 | Validation exception +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ update_pet_with_form } \emph{ Updates a pet in the store with form data } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @param } name character +#' \item \emph{ @param } status character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 405 | Invalid input +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ upload_file } \emph{ uploads an image } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet_id integer +#' \item \emph{ @param } additional_metadata character +#' \item \emph{ @param } file data.frame +#' \item \emph{ @returnType } \link{ModelApiResponse} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : ModelApiResponse +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' } +#' +#' +#' @examples +#' \dontrun{ +#' #################### add_pet #################### +#' +#' library(petstore) +#' var_pet <- Pet$new() # Pet | Pet object that needs to be added to the store +#' +#' #Add a new pet to the store +#' api_instance <- PetApi$new() +#' +#' # Configure HTTP basic authorization: http_auth +#' api_instance$api_client$username <- Sys.getenv("USERNAME") +#' api_instance$api_client$password <- Sys.getenv("PASSWORD") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$add_pet(var_pet, data_file = "result.txt"), +#' +#' +#' api_instance$add_pet(var_pet), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `add_pet`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### delete_pet #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | Pet id to delete +#' var_api_key <- "api_key_example" # character | +#' +#' #Deletes a pet +#' api_instance <- PetApi$new() +#' +#' # Configure OAuth2 access token for authorization: petstore_auth +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +#' +#' result <- tryCatch( +#' +#' api_instance$delete_pet(var_pet_id, api_key = var_api_key), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `delete_pet`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### find_pets_by_status #################### +#' +#' library(petstore) +#' var_status <- ["status_example"] # array[character] | Status values that need to be considered for filter +#' +#' #Finds Pets by status +#' api_instance <- PetApi$new() +#' +#' # Configure OAuth2 access token for authorization: petstore_auth +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$find_pets_by_status(var_status, data_file = "result.txt"), +#' +#' +#' api_instance$find_pets_by_status(var_status), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `find_pets_by_status`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### find_pets_by_tags #################### +#' +#' library(petstore) +#' var_tags <- ["tags_example"] # array[character] | Tags to filter by +#' +#' #Finds Pets by tags +#' api_instance <- PetApi$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$find_pets_by_tags(var_tags, data_file = "result.txt"), +#' +#' +#' api_instance$find_pets_by_tags(var_tags), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `find_pets_by_tags`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### get_pet_by_id #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | ID of pet to return +#' +#' #Find pet by ID +#' api_instance <- PetApi$new() +#' +#' # Configure HTTP bearer authorization: BearerToken +#' api_instance$api_client$bearer_token <- Sys.getenv("BEARER_TOKEN") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$get_pet_by_id(var_pet_id, data_file = "result.txt"), +#' +#' +#' api_instance$get_pet_by_id(var_pet_id), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_pet_by_id`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### get_pet_by_id_streaming #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | ID of pet to return +#' +#' #Find pet by ID (streaming) +#' api_instance <- PetApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$get_pet_by_id_streaming(var_pet_id, data_file = "result.txt"), +#' +#' # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. +#' # api_instance$get_pet_by_id_streaming(var_pet_id, stream_callback = function(x){ print(length(x)) }), +#' +#' +#' api_instance$get_pet_by_id_streaming(var_pet_id), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_pet_by_id_streaming`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### test_header #################### +#' +#' library(petstore) +#' var_header_test_int <- 56 # integer | header test int +#' +#' #Header test +#' api_instance <- PetApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$test_header(var_header_test_int, data_file = "result.txt"), +#' +#' # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. +#' # api_instance$test_header(var_header_test_int, stream_callback = function(x){ print(length(x)) }), +#' +#' +#' api_instance$test_header(var_header_test_int), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `test_header`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### update_pet #################### +#' +#' library(petstore) +#' var_pet <- Pet$new() # Pet | Pet object that needs to be added to the store +#' +#' #Update an existing pet +#' api_instance <- PetApi$new() +#' +#' # Configure OAuth2 access token for authorization: petstore_auth +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$update_pet(var_pet, data_file = "result.txt"), +#' +#' +#' api_instance$update_pet(var_pet), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `update_pet`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### update_pet_with_form #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | ID of pet that needs to be updated +#' var_name <- "name_example" # character | Updated name of the pet +#' var_status <- "status_example" # character | Updated status of the pet +#' +#' #Updates a pet in the store with form data +#' api_instance <- PetApi$new() +#' +#' result <- tryCatch( +#' +#' api_instance$update_pet_with_form(var_pet_id, name = var_name, status = var_status), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `update_pet_with_form`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### upload_file #################### +#' +#' library(petstore) +#' var_pet_id <- 56 # integer | ID of pet to update +#' var_additional_metadata <- "additional_metadata_example" # character | Additional data to pass to server +#' var_file <- File.new('/path/to/file') # data.frame | file to upload +#' +#' #uploads an image +#' api_instance <- PetApi$new() +#' +#' # Configure OAuth2 access token for authorization: petstore_auth +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$upload_file(var_pet_id, additional_metadata = var_additional_metadata, file = var_file, data_file = "result.txt"), +#' +#' +#' api_instance$upload_file(var_pet_id, additional_metadata = var_additional_metadata, file = var_file), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `upload_file`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' } +#' @importFrom R6 R6Class +#' @importFrom base64enc base64encode +#' @importFrom rlang abort +#' @export +PetApi <- R6::R6Class( + "PetApi", + public = list( + api_client = NULL, + #' Initialize a new PetApi. + #' + #' @description + #' Initialize a new PetApi. + #' + #' @param api_client An instance of API client. + #' @export + initialize = function(api_client) { + if (!missing(api_client)) { + self$api_client <- api_client + } else { + self$api_client <- ApiClient$new() + } + }, + #' Add a new pet to the store + #' + #' @description + #' Add a new pet to the store + #' + #' @param pet Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + add_pet = function(pet, data_file = NULL, ...) { + local_var_response <- self$add_pet_with_http_info(pet, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Add a new pet to the store + #' + #' @description + #' Add a new pet to the store + #' + #' @param pet Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + add_pet_with_http_info = function(pet, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet`)) { + rlang::abort(message = "Missing required parameter `pet`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet`.")) + } + + + if (!is.null(`pet`)) { + local_var_body <- `pet`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/pet" + # HTTP basic auth + if (!is.null(self$api_client$username) || !is.null(self$api_client$password)) { + header_params["Authorization"] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$api_client$username, self$api_client$password, sep = ":")))) + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json", "application/xml", "multipart/related") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Deletes a pet + #' + #' @description + #' Deletes a pet + #' + #' @param pet_id Pet id to delete + #' @param api_key (optional) No description + #' @param ... Other optional arguments + #' @return void + #' @export + delete_pet = function(pet_id, api_key = NULL, ...) { + local_var_response <- self$delete_pet_with_http_info(pet_id, api_key, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Deletes a pet + #' + #' @description + #' Deletes a pet + #' + #' @param pet_id Pet id to delete + #' @param api_key (optional) No description + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + delete_pet_with_http_info = function(pet_id, api_key = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + + header_params["api_key"] <- `api_key` + + local_var_url_path <- "/pet/{petId}" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "write:pets read:pets" + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "DELETE", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Finds Pets by status + #' + #' @description + #' Finds Pets by status + #' + #' @param status Status values that need to be considered for filter + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return array[Pet] + #' @export + find_pets_by_status = function(status, data_file = NULL, ...) { + local_var_response <- self$find_pets_by_status_with_http_info(status, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Finds Pets by status + #' + #' @description + #' Finds Pets by status + #' + #' @param status Status values that need to be considered for filter + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (array[Pet]) with additional information such as HTTP status code, headers + #' @export + find_pets_by_status_with_http_info = function(status, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`status`)) { + rlang::abort(message = "Missing required parameter `status`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `status`.")) + } + + + # explore + for (query_item in `status`) { + # validate enum values + if (!(query_item %in% c("available", "pending", "sold"))) { + rlang::abort(message = "Invalid value for `status` when calling PetApi$find_pets_by_status. Must be [available, pending, sold].", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `status` when calling PetApi$find_pets_by_status. Must be [available, pending, sold].")) + } + query_params[["status"]] <- c(query_params[["status"]], list(`status` = query_item)) + } + + local_var_url_path <- "/pet/findByStatus" + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "read:pets" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "array[Pet]", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Finds Pets by tags + #' + #' @description + #' Finds Pets by tags + #' + #' @param tags Tags to filter by + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return array[Pet] + #' @export + find_pets_by_tags = function(tags, data_file = NULL, ...) { + local_var_response <- self$find_pets_by_tags_with_http_info(tags, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Finds Pets by tags + #' + #' @description + #' Finds Pets by tags + #' + #' @param tags Tags to filter by + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (array[Pet]) with additional information such as HTTP status code, headers + #' @export + find_pets_by_tags_with_http_info = function(tags, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`tags`)) { + rlang::abort(message = "Missing required parameter `tags`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `tags`.")) + } + + + # no explore + query_params[["tags"]] <- I(paste(lapply(`tags`, URLencode, reserved = TRUE), collapse = ",")) + + local_var_url_path <- "/pet/findByTags" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "array[Pet]", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Find pet by ID + #' + #' @description + #' Find pet by ID + #' + #' @param pet_id ID of pet to return + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + get_pet_by_id = function(pet_id, data_file = NULL, ...) { + local_var_response <- self$get_pet_by_id_with_http_info(pet_id, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Find pet by ID + #' + #' @description + #' Find pet by ID + #' + #' @param pet_id ID of pet to return + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + get_pet_by_id_with_http_info = function(pet_id, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + local_var_url_path <- "/pet/{petId}" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + # Bearer token + if (!is.null(self$api_client$bearer_token)) { + header_params["Authorization"] <- paste("Bearer", self$api_client$bearer_token, sep = " ") + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Find pet by ID (streaming) + #' + #' @description + #' Find pet by ID (streaming) + #' + #' @param pet_id ID of pet to return + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + get_pet_by_id_streaming = function(pet_id, stream_callback = NULL, data_file = NULL, ...) { + local_var_response <- self$get_pet_by_id_streaming_with_http_info(pet_id, stream_callback = stream_callback, data_file = data_file, ...) + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Find pet by ID (streaming) + #' + #' @description + #' Find pet by ID (streaming) + #' + #' @param pet_id ID of pet to return + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + get_pet_by_id_streaming_with_http_info = function(pet_id, stream_callback = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + local_var_url_path <- "/pet/{petId}?streaming" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + stream_callback = stream_callback, + ...) + + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Header test + #' + #' @description + #' Header test + #' + #' @param header_test_int header test int + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + test_header = function(header_test_int, stream_callback = NULL, data_file = NULL, ...) { + local_var_response <- self$test_header_with_http_info(header_test_int, stream_callback = stream_callback, data_file = data_file, ...) + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Header test + #' + #' @description + #' Header test + #' + #' @param header_test_int header test int + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + test_header_with_http_info = function(header_test_int, stream_callback = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`header_test_int`)) { + rlang::abort(message = "Missing required parameter `header_test_int`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `header_test_int`.")) + } + + + header_params["header_test_int"] <- `header_test_int` + + local_var_url_path <- "/pet_header_test" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + stream_callback = stream_callback, + ...) + + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Update an existing pet + #' + #' @description + #' Update an existing pet + #' + #' @param pet Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + update_pet = function(pet, data_file = NULL, ...) { + local_var_response <- self$update_pet_with_http_info(pet, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Update an existing pet + #' + #' @description + #' Update an existing pet + #' + #' @param pet Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + update_pet_with_http_info = function(pet, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet`)) { + rlang::abort(message = "Missing required parameter `pet`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet`.")) + } + + + if (!is.null(`pet`)) { + local_var_body <- `pet`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/pet" + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "write:pets read:pets" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json", "application/xml", "multipart/related") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "PUT", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Updates a pet in the store with form data + #' + #' @description + #' Updates a pet in the store with form data + #' + #' @param pet_id ID of pet that needs to be updated + #' @param name (optional) Updated name of the pet + #' @param status (optional) Updated status of the pet + #' @param ... Other optional arguments + #' @return void + #' @export + update_pet_with_form = function(pet_id, name = NULL, status = NULL, ...) { + local_var_response <- self$update_pet_with_form_with_http_info(pet_id, name, status, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Updates a pet in the store with form data + #' + #' @description + #' Updates a pet in the store with form data + #' + #' @param pet_id ID of pet that needs to be updated + #' @param name (optional) Updated name of the pet + #' @param status (optional) Updated status of the pet + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + update_pet_with_form_with_http_info = function(pet_id, name = NULL, status = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + + + form_params["name"] <- `name` + form_params["status"] <- `status` + local_var_url_path <- "/pet/{petId}" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/x-www-form-urlencoded") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' uploads an image + #' + #' @description + #' uploads an image + #' + #' @param pet_id ID of pet to update + #' @param additional_metadata (optional) Additional data to pass to server + #' @param file (optional) file to upload + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return ModelApiResponse + #' @export + upload_file = function(pet_id, additional_metadata = NULL, file = NULL, data_file = NULL, ...) { + local_var_response <- self$upload_file_with_http_info(pet_id, additional_metadata, file, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' uploads an image + #' + #' @description + #' uploads an image + #' + #' @param pet_id ID of pet to update + #' @param additional_metadata (optional) Additional data to pass to server + #' @param file (optional) file to upload + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (ModelApiResponse) with additional information such as HTTP status code, headers + #' @export + upload_file_with_http_info = function(pet_id, additional_metadata = NULL, file = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`pet_id`)) { + rlang::abort(message = "Missing required parameter `pet_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `pet_id`.")) + } + + + + + form_params["additionalMetadata"] <- `additional_metadata` + file_params["file"] <- curl::form_file(`file`) + local_var_url_path <- "/pet/{petId}/uploadImage" + if (!missing(`pet_id`)) { + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) + } + + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "write:pets read:pets" + + # The Accept request HTTP header + local_var_accepts <- list("application/json") + + # The Content-Type representation header + local_var_content_types <- list("multipart/form-data") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "ModelApiResponse", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2/R/pig.R b/samples/client/petstore/R-httr2/R/pig.R new file mode 100644 index 0000000000..6cb6b568ab --- /dev/null +++ b/samples/client/petstore/R-httr2/R/pig.R @@ -0,0 +1,200 @@ +#' @docType class +#' @title Pig +#' +#' @description Pig Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Pig <- R6::R6Class( + "Pig", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("BasquePig", "DanishPig"), + #' Initialize a new Pig. + #' + #' @description + #' Initialize a new Pig. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "BasquePig", "DanishPig" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "BasquePig") { + self$actual_instance <- instance + self$actual_type <- "BasquePig" + } else if (get(class(instance)[[1]], pos = -1)$classname == "DanishPig") { + self$actual_instance <- instance + self$actual_type <- "DanishPig" + } else { + stop(paste("Failed to initialize Pig with oneOf schemas BasquePig, DanishPig. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of Pig. + #' + #' @description + #' Deserialize JSON string into an instance of Pig. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of Pig. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of Pig. + #' + #' @description + #' Deserialize JSON string into an instance of Pig. + #' + #' @param input The input JSON. + #' @return An instance of Pig. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + BasquePig_result <- tryCatch({ + BasquePig$public_methods$validateJSON(input) + BasquePig_instance <- BasquePig$new() + instance <- BasquePig_instance$fromJSON(input) + instance_type <- "BasquePig" + matched_schemas <- append(matched_schemas, "BasquePig") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(BasquePig_result["error"])) { + error_messages <- append(error_messages, BasquePig_result["message"]) + } + + DanishPig_result <- tryCatch({ + DanishPig$public_methods$validateJSON(input) + DanishPig_instance <- DanishPig$new() + instance <- DanishPig_instance$fromJSON(input) + instance_type <- "DanishPig" + matched_schemas <- append(matched_schemas, "DanishPig") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(DanishPig_result["error"])) { + error_messages <- append(error_messages, DanishPig_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into Pig with oneOf schemas BasquePig, DanishPig.") + } else { + # no match + stop(paste("No match found when deserializing the payload into Pig with oneOf schemas BasquePig, DanishPig. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize Pig to JSON string. + #' + #' @description + #' Serialize Pig to JSON string. + #' + #' @return JSON string representation of the Pig. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize Pig to JSON. + #' + #' @description + #' Serialize Pig to JSON. + #' + #' @return JSON representation of the Pig. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to Pig. + #' + #' @description + #' Validate the input JSON with respect to Pig and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#Pig$unlock() +# +## Below is an example to define the print fnuction +#Pig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#Pig$lock() + diff --git a/samples/client/petstore/R-httr2/R/special.R b/samples/client/petstore/R-httr2/R/special.R new file mode 100644 index 0000000000..32ced47753 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/special.R @@ -0,0 +1,311 @@ +#' Create a new Special +#' +#' @description +#' Describes the result of uploading an image resource +#' +#' @docType class +#' @title Special +#' @description Special Class +#' @format An \code{R6Class} generator object +#' @field set_test list(character) [optional] +#' @field item_self integer [optional] +#' @field item_private character [optional] +#' @field item_super character [optional] +#' @field 123_number character [optional] +#' @field array[test] character [optional] +#' @field empty_string character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Special <- R6::R6Class( + "Special", + public = list( + `set_test` = NULL, + `item_self` = NULL, + `item_private` = NULL, + `item_super` = NULL, + `123_number` = NULL, + `array[test]` = NULL, + `empty_string` = NULL, + #' Initialize a new Special class. + #' + #' @description + #' Initialize a new Special class. + #' + #' @param set_test set_test + #' @param item_self item_self + #' @param item_private item_private + #' @param item_super item_super + #' @param 123_number 123_number + #' @param array[test] array[test] + #' @param empty_string empty_string + #' @param ... Other optional arguments. + #' @export + initialize = function(`set_test` = NULL, `item_self` = NULL, `item_private` = NULL, `item_super` = NULL, `123_number` = NULL, `array[test]` = NULL, `empty_string` = NULL, ...) { + if (!is.null(`set_test`)) { + stopifnot(is.vector(`set_test`), length(`set_test`) != 0) + sapply(`set_test`, function(x) stopifnot(is.character(x))) + if (!identical(`set_test`, unique(`set_test`))) { + stop("Error! Items in `set_test` are not unique.") + } + self$`set_test` <- `set_test` + } + if (!is.null(`item_self`)) { + stopifnot(is.numeric(`item_self`), length(`item_self`) == 1) + self$`item_self` <- `item_self` + } + if (!is.null(`item_private`)) { + stopifnot(is.character(`item_private`), length(`item_private`) == 1) + self$`item_private` <- `item_private` + } + if (!is.null(`item_super`)) { + stopifnot(is.character(`item_super`), length(`item_super`) == 1) + self$`item_super` <- `item_super` + } + if (!is.null(`123_number`)) { + stopifnot(is.character(`123_number`), length(`123_number`) == 1) + self$`123_number` <- `123_number` + } + if (!is.null(`array[test]`)) { + stopifnot(is.character(`array[test]`), length(`array[test]`) == 1) + self$`array[test]` <- `array[test]` + } + if (!is.null(`empty_string`)) { + stopifnot(is.character(`empty_string`), length(`empty_string`) == 1) + self$`empty_string` <- `empty_string` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Special in JSON format + #' @export + toJSON = function() { + SpecialObject <- list() + if (!is.null(self$`set_test`)) { + SpecialObject[["set_test"]] <- + self$`set_test` + } + if (!is.null(self$`item_self`)) { + SpecialObject[["self"]] <- + self$`item_self` + } + if (!is.null(self$`item_private`)) { + SpecialObject[["private"]] <- + self$`item_private` + } + if (!is.null(self$`item_super`)) { + SpecialObject[["super"]] <- + self$`item_super` + } + if (!is.null(self$`123_number`)) { + SpecialObject[["123_number"]] <- + self$`123_number` + } + if (!is.null(self$`array[test]`)) { + SpecialObject[["array[test]"]] <- + self$`array[test]` + } + if (!is.null(self$`empty_string`)) { + SpecialObject[["empty_string"]] <- + self$`empty_string` + } + SpecialObject + }, + #' Deserialize JSON string into an instance of Special + #' + #' @description + #' Deserialize JSON string into an instance of Special + #' + #' @param input_json the JSON input + #' @return the instance of Special + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`set_test`)) { + self$`set_test` <- ApiClient$new()$deserializeObj(this_object$`set_test`, "set[character]", loadNamespace("petstore")) + if (!identical(self$`set_test`, unique(self$`set_test`))) { + stop("Error! Items in `set_test` are not unique.") + } + } + if (!is.null(this_object$`self`)) { + self$`item_self` <- this_object$`self` + } + if (!is.null(this_object$`private`)) { + self$`item_private` <- this_object$`private` + } + if (!is.null(this_object$`super`)) { + self$`item_super` <- this_object$`super` + } + if (!is.null(this_object$`123_number`)) { + self$`123_number` <- this_object$`123_number` + } + if (!is.null(this_object$`array[test]`)) { + self$`array[test]` <- this_object$`array[test]` + } + if (!is.null(this_object$`empty_string`)) { + self$`empty_string` <- this_object$`empty_string` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Special in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`set_test`)) { + sprintf( + '"set_test": + [%s] + ', + paste(unlist(lapply(self$`set_test`, function(x) paste0('"', x, '"'))), collapse = ",") + ) + }, + if (!is.null(self$`item_self`)) { + sprintf( + '"self": + %d + ', + self$`item_self` + ) + }, + if (!is.null(self$`item_private`)) { + sprintf( + '"private": + "%s" + ', + self$`item_private` + ) + }, + if (!is.null(self$`item_super`)) { + sprintf( + '"super": + "%s" + ', + self$`item_super` + ) + }, + if (!is.null(self$`123_number`)) { + sprintf( + '"123_number": + "%s" + ', + self$`123_number` + ) + }, + if (!is.null(self$`array[test]`)) { + sprintf( + '"array[test]": + "%s" + ', + self$`array[test]` + ) + }, + if (!is.null(self$`empty_string`)) { + sprintf( + '"empty_string": + "%s" + ', + self$`empty_string` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Special + #' + #' @description + #' Deserialize JSON string into an instance of Special + #' + #' @param input_json the JSON input + #' @return the instance of Special + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`set_test` <- ApiClient$new()$deserializeObj(this_object$`set_test`, "set[character]", loadNamespace("petstore")) + if (!identical(self$`set_test`, unique(self$`set_test`))) { + stop("Error! Items in `set_test` are not unique.") + } + self$`item_self` <- this_object$`item_self` + self$`item_private` <- this_object$`item_private` + self$`item_super` <- this_object$`item_super` + self$`123_number` <- this_object$`123_number` + self$`array[test]` <- this_object$`array[test]` + self$`empty_string` <- this_object$`empty_string` + self + }, + #' Validate JSON input with respect to Special + #' + #' @description + #' Validate JSON input with respect to Special and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Special + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Special$unlock() +# +## Below is an example to define the print fnuction +# Special$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Special$lock() + diff --git a/samples/client/petstore/R-httr2/R/store_api.R b/samples/client/petstore/R-httr2/R/store_api.R new file mode 100644 index 0000000000..ef974aa9a5 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/store_api.R @@ -0,0 +1,725 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title Store operations +#' @description StoreApi +#' @format An \code{R6Class} generator object +#' @field api_client Handles the client-server communication. +#' +#' @section Methods: +#' \describe{ +#' \strong{ delete_order } \emph{ Delete purchase order by ID } +#' For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +#' +#' \itemize{ +#' \item \emph{ @param } order_id character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Order not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_inventory } \emph{ Returns pet inventories by status } +#' Returns a map of status codes to quantities +#' +#' \itemize{ +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : map(integer) +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_order_by_id } \emph{ Find purchase order by ID } +#' For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +#' +#' \itemize{ +#' \item \emph{ @param } order_id integer +#' \item \emph{ @returnType } \link{Order} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Order +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Order not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ place_order } \emph{ Place an order for a pet } +#' +#' +#' \itemize{ +#' \item \emph{ @param } order \link{Order} +#' \item \emph{ @returnType } \link{Order} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Order +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid Order +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' } +#' +#' +#' @examples +#' \dontrun{ +#' #################### delete_order #################### +#' +#' library(petstore) +#' var_order_id <- "order_id_example" # character | ID of the order that needs to be deleted +#' +#' #Delete purchase order by ID +#' api_instance <- StoreApi$new() +#' +#' result <- tryCatch( +#' +#' api_instance$delete_order(var_order_id), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `delete_order`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### get_inventory #################### +#' +#' library(petstore) +#' +#' #Returns pet inventories by status +#' api_instance <- StoreApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$get_inventory(data_file = "result.txt"), +#' +#' +#' api_instance$get_inventory(), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_inventory`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### get_order_by_id #################### +#' +#' library(petstore) +#' var_order_id <- 56 # integer | ID of pet that needs to be fetched +#' +#' #Find purchase order by ID +#' api_instance <- StoreApi$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$get_order_by_id(var_order_id, data_file = "result.txt"), +#' +#' +#' api_instance$get_order_by_id(var_order_id), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_order_by_id`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### place_order #################### +#' +#' library(petstore) +#' var_order <- Order$new() # Order | order placed for purchasing the pet +#' +#' #Place an order for a pet +#' api_instance <- StoreApi$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$place_order(var_order, data_file = "result.txt"), +#' +#' +#' api_instance$place_order(var_order), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `place_order`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' } +#' @importFrom R6 R6Class +#' @importFrom base64enc base64encode +#' @importFrom rlang abort +#' @export +StoreApi <- R6::R6Class( + "StoreApi", + public = list( + api_client = NULL, + #' Initialize a new StoreApi. + #' + #' @description + #' Initialize a new StoreApi. + #' + #' @param api_client An instance of API client. + #' @export + initialize = function(api_client) { + if (!missing(api_client)) { + self$api_client <- api_client + } else { + self$api_client <- ApiClient$new() + } + }, + #' Delete purchase order by ID + #' + #' @description + #' Delete purchase order by ID + #' + #' @param order_id ID of the order that needs to be deleted + #' @param ... Other optional arguments + #' @return void + #' @export + delete_order = function(order_id, ...) { + local_var_response <- self$delete_order_with_http_info(order_id, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Delete purchase order by ID + #' + #' @description + #' Delete purchase order by ID + #' + #' @param order_id ID of the order that needs to be deleted + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + delete_order_with_http_info = function(order_id, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`order_id`)) { + rlang::abort(message = "Missing required parameter `order_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `order_id`.")) + } + + + local_var_url_path <- "/store/order/{orderId}" + if (!missing(`order_id`)) { + local_var_url_path <- gsub("\\{orderId\\}", URLencode(as.character(`order_id`), reserved = TRUE), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "DELETE", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Returns pet inventories by status + #' + #' @description + #' Returns pet inventories by status + #' + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return map(integer) + #' @export + get_inventory = function(data_file = NULL, ...) { + local_var_response <- self$get_inventory_with_http_info(data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Returns pet inventories by status + #' + #' @description + #' Returns pet inventories by status + #' + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (map(integer)) with additional information such as HTTP status code, headers + #' @export + get_inventory_with_http_info = function(data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + local_var_url_path <- "/store/inventory" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list("application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "map(integer)", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Find purchase order by ID + #' + #' @description + #' Find purchase order by ID + #' + #' @param order_id ID of pet that needs to be fetched + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Order + #' @export + get_order_by_id = function(order_id, data_file = NULL, ...) { + local_var_response <- self$get_order_by_id_with_http_info(order_id, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Find purchase order by ID + #' + #' @description + #' Find purchase order by ID + #' + #' @param order_id ID of pet that needs to be fetched + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Order) with additional information such as HTTP status code, headers + #' @export + get_order_by_id_with_http_info = function(order_id, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`order_id`)) { + rlang::abort(message = "Missing required parameter `order_id`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `order_id`.")) + } + + if (`order_id` > 5) { + rlang::abort(message = "Invalid value for `order_id` when calling StoreApi$get_order_by_id, must be smaller than or equal to 5.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `order_id` when calling StoreApi$get_order_by_id, must be smaller than or equal to 5.")) + } + if (`order_id` < 1) { + rlang::abort(message = "Invalid value for `order_id` when calling StoreApi$get_order_by_id, must be bigger than or equal to 1.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `order_id` when calling StoreApi$get_order_by_id, must be bigger than or equal to 1.")) + } + + local_var_url_path <- "/store/order/{orderId}" + if (!missing(`order_id`)) { + local_var_url_path <- gsub("\\{orderId\\}", URLencode(as.character(`order_id`), reserved = TRUE), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Order", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Place an order for a pet + #' + #' @description + #' Place an order for a pet + #' + #' @param order order placed for purchasing the pet + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Order + #' @export + place_order = function(order, data_file = NULL, ...) { + local_var_response <- self$place_order_with_http_info(order, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Place an order for a pet + #' + #' @description + #' Place an order for a pet + #' + #' @param order order placed for purchasing the pet + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Order) with additional information such as HTTP status code, headers + #' @export + place_order_with_http_info = function(order, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`order`)) { + rlang::abort(message = "Missing required parameter `order`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `order`.")) + } + + + if (!is.null(`order`)) { + local_var_body <- `order`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/store/order" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Order", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2/R/tag.R b/samples/client/petstore/R-httr2/R/tag.R new file mode 100644 index 0000000000..8db5513301 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/tag.R @@ -0,0 +1,184 @@ +#' Create a new Tag +#' +#' @description +#' A tag for a pet +#' +#' @docType class +#' @title Tag +#' @description Tag Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field name character [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Tag <- R6::R6Class( + "Tag", + public = list( + `id` = NULL, + `name` = NULL, + #' Initialize a new Tag class. + #' + #' @description + #' Initialize a new Tag class. + #' + #' @param id id + #' @param name name + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `name` = NULL, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Tag in JSON format + #' @export + toJSON = function() { + TagObject <- list() + if (!is.null(self$`id`)) { + TagObject[["id"]] <- + self$`id` + } + if (!is.null(self$`name`)) { + TagObject[["name"]] <- + self$`name` + } + TagObject + }, + #' Deserialize JSON string into an instance of Tag + #' + #' @description + #' Deserialize JSON string into an instance of Tag + #' + #' @param input_json the JSON input + #' @return the instance of Tag + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`name`)) { + self$`name` <- this_object$`name` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Tag in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`name`)) { + sprintf( + '"name": + "%s" + ', + self$`name` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Tag + #' + #' @description + #' Deserialize JSON string into an instance of Tag + #' + #' @param input_json the JSON input + #' @return the instance of Tag + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`name` <- this_object$`name` + self + }, + #' Validate JSON input with respect to Tag + #' + #' @description + #' Validate JSON input with respect to Tag and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Tag + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Tag$unlock() +# +## Below is an example to define the print fnuction +# Tag$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Tag$lock() + diff --git a/samples/client/petstore/R-httr2/R/update_pet_request.R b/samples/client/petstore/R-httr2/R/update_pet_request.R new file mode 100644 index 0000000000..1d37555f4b --- /dev/null +++ b/samples/client/petstore/R-httr2/R/update_pet_request.R @@ -0,0 +1,185 @@ +#' Create a new UpdatePetRequest +#' +#' @description +#' UpdatePetRequest Class +#' +#' @docType class +#' @title UpdatePetRequest +#' @description UpdatePetRequest Class +#' @format An \code{R6Class} generator object +#' @field jsonData \link{Pet} [optional] +#' @field binaryDataN2Information data.frame [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +UpdatePetRequest <- R6::R6Class( + "UpdatePetRequest", + public = list( + `jsonData` = NULL, + `binaryDataN2Information` = NULL, + #' Initialize a new UpdatePetRequest class. + #' + #' @description + #' Initialize a new UpdatePetRequest class. + #' + #' @param jsonData jsonData + #' @param binaryDataN2Information binaryDataN2Information + #' @param ... Other optional arguments. + #' @export + initialize = function(`jsonData` = NULL, `binaryDataN2Information` = NULL, ...) { + if (!is.null(`jsonData`)) { + stopifnot(R6::is.R6(`jsonData`)) + self$`jsonData` <- `jsonData` + } + if (!is.null(`binaryDataN2Information`)) { + self$`binaryDataN2Information` <- `binaryDataN2Information` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return UpdatePetRequest in JSON format + #' @export + toJSON = function() { + UpdatePetRequestObject <- list() + if (!is.null(self$`jsonData`)) { + UpdatePetRequestObject[["jsonData"]] <- + self$`jsonData`$toJSON() + } + if (!is.null(self$`binaryDataN2Information`)) { + UpdatePetRequestObject[["binaryDataN2Information"]] <- + self$`binaryDataN2Information` + } + UpdatePetRequestObject + }, + #' Deserialize JSON string into an instance of UpdatePetRequest + #' + #' @description + #' Deserialize JSON string into an instance of UpdatePetRequest + #' + #' @param input_json the JSON input + #' @return the instance of UpdatePetRequest + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`jsonData`)) { + jsondata_object <- Pet$new() + jsondata_object$fromJSON(jsonlite::toJSON(this_object$jsonData, auto_unbox = TRUE, digits = NA)) + self$`jsonData` <- jsondata_object + } + if (!is.null(this_object$`binaryDataN2Information`)) { + self$`binaryDataN2Information` <- this_object$`binaryDataN2Information` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return UpdatePetRequest in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`jsonData`)) { + sprintf( + '"jsonData": + %s + ', + jsonlite::toJSON(self$`jsonData`$toJSON(), auto_unbox = TRUE, digits = NA) + ) + }, + if (!is.null(self$`binaryDataN2Information`)) { + sprintf( + '"binaryDataN2Information": + "%s" + ', + self$`binaryDataN2Information` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of UpdatePetRequest + #' + #' @description + #' Deserialize JSON string into an instance of UpdatePetRequest + #' + #' @param input_json the JSON input + #' @return the instance of UpdatePetRequest + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`jsonData` <- Pet$new()$fromJSON(jsonlite::toJSON(this_object$jsonData, auto_unbox = TRUE, digits = NA)) + self$`binaryDataN2Information` <- this_object$`binaryDataN2Information` + self + }, + #' Validate JSON input with respect to UpdatePetRequest + #' + #' @description + #' Validate JSON input with respect to UpdatePetRequest and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of UpdatePetRequest + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# UpdatePetRequest$unlock() +# +## Below is an example to define the print fnuction +# UpdatePetRequest$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# UpdatePetRequest$lock() + diff --git a/samples/client/petstore/R-httr2/R/user.R b/samples/client/petstore/R-httr2/R/user.R new file mode 100644 index 0000000000..c3db6eb00d --- /dev/null +++ b/samples/client/petstore/R-httr2/R/user.R @@ -0,0 +1,322 @@ +#' Create a new User +#' +#' @description +#' A User who is purchasing from the pet store +#' +#' @docType class +#' @title User +#' @description User Class +#' @format An \code{R6Class} generator object +#' @field id integer [optional] +#' @field username character [optional] +#' @field firstName character [optional] +#' @field lastName character [optional] +#' @field email character [optional] +#' @field password character [optional] +#' @field phone character [optional] +#' @field userStatus User Status integer [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +User <- R6::R6Class( + "User", + public = list( + `id` = NULL, + `username` = NULL, + `firstName` = NULL, + `lastName` = NULL, + `email` = NULL, + `password` = NULL, + `phone` = NULL, + `userStatus` = NULL, + #' Initialize a new User class. + #' + #' @description + #' Initialize a new User class. + #' + #' @param id id + #' @param username username + #' @param firstName firstName + #' @param lastName lastName + #' @param email email + #' @param password password + #' @param phone phone + #' @param userStatus User Status + #' @param ... Other optional arguments. + #' @export + initialize = function(`id` = NULL, `username` = NULL, `firstName` = NULL, `lastName` = NULL, `email` = NULL, `password` = NULL, `phone` = NULL, `userStatus` = NULL, ...) { + if (!is.null(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!is.null(`username`)) { + stopifnot(is.character(`username`), length(`username`) == 1) + self$`username` <- `username` + } + if (!is.null(`firstName`)) { + stopifnot(is.character(`firstName`), length(`firstName`) == 1) + self$`firstName` <- `firstName` + } + if (!is.null(`lastName`)) { + stopifnot(is.character(`lastName`), length(`lastName`) == 1) + self$`lastName` <- `lastName` + } + if (!is.null(`email`)) { + stopifnot(is.character(`email`), length(`email`) == 1) + self$`email` <- `email` + } + if (!is.null(`password`)) { + stopifnot(is.character(`password`), length(`password`) == 1) + self$`password` <- `password` + } + if (!is.null(`phone`)) { + stopifnot(is.character(`phone`), length(`phone`) == 1) + self$`phone` <- `phone` + } + if (!is.null(`userStatus`)) { + stopifnot(is.numeric(`userStatus`), length(`userStatus`) == 1) + self$`userStatus` <- `userStatus` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return User in JSON format + #' @export + toJSON = function() { + UserObject <- list() + if (!is.null(self$`id`)) { + UserObject[["id"]] <- + self$`id` + } + if (!is.null(self$`username`)) { + UserObject[["username"]] <- + self$`username` + } + if (!is.null(self$`firstName`)) { + UserObject[["firstName"]] <- + self$`firstName` + } + if (!is.null(self$`lastName`)) { + UserObject[["lastName"]] <- + self$`lastName` + } + if (!is.null(self$`email`)) { + UserObject[["email"]] <- + self$`email` + } + if (!is.null(self$`password`)) { + UserObject[["password"]] <- + self$`password` + } + if (!is.null(self$`phone`)) { + UserObject[["phone"]] <- + self$`phone` + } + if (!is.null(self$`userStatus`)) { + UserObject[["userStatus"]] <- + self$`userStatus` + } + UserObject + }, + #' Deserialize JSON string into an instance of User + #' + #' @description + #' Deserialize JSON string into an instance of User + #' + #' @param input_json the JSON input + #' @return the instance of User + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`id`)) { + self$`id` <- this_object$`id` + } + if (!is.null(this_object$`username`)) { + self$`username` <- this_object$`username` + } + if (!is.null(this_object$`firstName`)) { + self$`firstName` <- this_object$`firstName` + } + if (!is.null(this_object$`lastName`)) { + self$`lastName` <- this_object$`lastName` + } + if (!is.null(this_object$`email`)) { + self$`email` <- this_object$`email` + } + if (!is.null(this_object$`password`)) { + self$`password` <- this_object$`password` + } + if (!is.null(this_object$`phone`)) { + self$`phone` <- this_object$`phone` + } + if (!is.null(this_object$`userStatus`)) { + self$`userStatus` <- this_object$`userStatus` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return User in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`id`)) { + sprintf( + '"id": + %d + ', + self$`id` + ) + }, + if (!is.null(self$`username`)) { + sprintf( + '"username": + "%s" + ', + self$`username` + ) + }, + if (!is.null(self$`firstName`)) { + sprintf( + '"firstName": + "%s" + ', + self$`firstName` + ) + }, + if (!is.null(self$`lastName`)) { + sprintf( + '"lastName": + "%s" + ', + self$`lastName` + ) + }, + if (!is.null(self$`email`)) { + sprintf( + '"email": + "%s" + ', + self$`email` + ) + }, + if (!is.null(self$`password`)) { + sprintf( + '"password": + "%s" + ', + self$`password` + ) + }, + if (!is.null(self$`phone`)) { + sprintf( + '"phone": + "%s" + ', + self$`phone` + ) + }, + if (!is.null(self$`userStatus`)) { + sprintf( + '"userStatus": + %d + ', + self$`userStatus` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of User + #' + #' @description + #' Deserialize JSON string into an instance of User + #' + #' @param input_json the JSON input + #' @return the instance of User + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`id` <- this_object$`id` + self$`username` <- this_object$`username` + self$`firstName` <- this_object$`firstName` + self$`lastName` <- this_object$`lastName` + self$`email` <- this_object$`email` + self$`password` <- this_object$`password` + self$`phone` <- this_object$`phone` + self$`userStatus` <- this_object$`userStatus` + self + }, + #' Validate JSON input with respect to User + #' + #' @description + #' Validate JSON input with respect to User and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of User + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# User$unlock() +# +## Below is an example to define the print fnuction +# User$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# User$lock() + diff --git a/samples/client/petstore/R-httr2/R/user_api.R b/samples/client/petstore/R-httr2/R/user_api.R new file mode 100644 index 0000000000..379460748f --- /dev/null +++ b/samples/client/petstore/R-httr2/R/user_api.R @@ -0,0 +1,1356 @@ +#' 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. +#' +#' The version of the OpenAPI document: 1.0.0 +#' Generated by: https://openapi-generator.tech +#' +#' @docType class +#' @title User operations +#' @description UserApi +#' @format An \code{R6Class} generator object +#' @field api_client Handles the client-server communication. +#' +#' @section Methods: +#' \describe{ +#' \strong{ create_user } \emph{ Create user } +#' This can only be done by the logged in user. +#' +#' \itemize{ +#' \item \emph{ @param } user \link{User} +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 0 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ create_users_with_array_input } \emph{ Creates list of users with given input array } +#' +#' +#' \itemize{ +#' \item \emph{ @param } user list( \link{User} ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 0 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ create_users_with_list_input } \emph{ Creates list of users with given input array } +#' +#' +#' \itemize{ +#' \item \emph{ @param } user list( \link{User} ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 0 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ delete_user } \emph{ Delete user } +#' This can only be done by the logged in user. +#' +#' \itemize{ +#' \item \emph{ @param } username character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 400 | Invalid username supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | User not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ get_user_by_name } \emph{ Get user by user name } +#' +#' +#' \itemize{ +#' \item \emph{ @param } username character +#' \item \emph{ @returnType } \link{User} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : User +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid username supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | User not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ login_user } \emph{ Logs user into the system } +#' +#' +#' \itemize{ +#' \item \emph{ @param } username character +#' \item \emph{ @param } password character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : character +#' \item response headers : +#' +#' \tabular{ll}{ +#' Set-Cookie \tab Cookie authentication key for use with the `api_key` apiKey authentication. \cr +#' X-Rate-Limit \tab calls per hour allowed by the user \cr +#' X-Expires-After \tab date in UTC when token expires \cr +#' } +#' \item status code : 400 | Invalid username/password supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ logout_user } \emph{ Logs out current logged in user session } +#' +#' +#' \itemize{ +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 0 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ update_user } \emph{ Updated user } +#' This can only be done by the logged in user. +#' +#' \itemize{ +#' \item \emph{ @param } username character +#' \item \emph{ @param } user \link{User} +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 400 | Invalid user supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | User not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' } +#' +#' +#' @examples +#' \dontrun{ +#' #################### create_user #################### +#' +#' library(petstore) +#' var_user <- User$new() # User | Created user object +#' +#' #Create user +#' api_instance <- UserApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$create_user(var_user), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `create_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### create_users_with_array_input #################### +#' +#' library(petstore) +#' var_user <- [User$new()] # array[User] | List of user object +#' +#' #Creates list of users with given input array +#' api_instance <- UserApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$create_users_with_array_input(var_user), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `create_users_with_array_input`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### create_users_with_list_input #################### +#' +#' library(petstore) +#' var_user <- [User$new()] # array[User] | List of user object +#' +#' #Creates list of users with given input array +#' api_instance <- UserApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$create_users_with_list_input(var_user), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `create_users_with_list_input`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### delete_user #################### +#' +#' library(petstore) +#' var_username <- "username_example" # character | The name that needs to be deleted +#' +#' #Delete user +#' api_instance <- UserApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$delete_user(var_username), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `delete_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### get_user_by_name #################### +#' +#' library(petstore) +#' var_username <- "username_example" # character | The name that needs to be fetched. Use user1 for testing. +#' +#' #Get user by user name +#' api_instance <- UserApi$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$get_user_by_name(var_username, data_file = "result.txt"), +#' +#' +#' api_instance$get_user_by_name(var_username), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `get_user_by_name`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### login_user #################### +#' +#' library(petstore) +#' var_username <- "username_example" # character | The user name for login +#' var_password <- "password_example" # character | The password for login in clear text +#' +#' #Logs user into the system +#' api_instance <- UserApi$new() +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$login_user(var_username, var_password, data_file = "result.txt"), +#' +#' +#' api_instance$login_user(var_username, var_password), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `login_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' +#' #################### logout_user #################### +#' +#' library(petstore) +#' +#' #Logs out current logged in user session +#' api_instance <- UserApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$logout_user(), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `logout_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### update_user #################### +#' +#' library(petstore) +#' var_username <- "username_example" # character | name that need to be deleted +#' var_user <- User$new() # User | Updated user object +#' +#' #Updated user +#' api_instance <- UserApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' api_instance$update_user(var_username, var_user), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `update_user`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' } +#' @importFrom R6 R6Class +#' @importFrom base64enc base64encode +#' @importFrom rlang abort +#' @export +UserApi <- R6::R6Class( + "UserApi", + public = list( + api_client = NULL, + #' Initialize a new UserApi. + #' + #' @description + #' Initialize a new UserApi. + #' + #' @param api_client An instance of API client. + #' @export + initialize = function(api_client) { + if (!missing(api_client)) { + self$api_client <- api_client + } else { + self$api_client <- ApiClient$new() + } + }, + #' Create user + #' + #' @description + #' Create user + #' + #' @param user Created user object + #' @param ... Other optional arguments + #' @return void + #' @export + create_user = function(user, ...) { + local_var_response <- self$create_user_with_http_info(user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Create user + #' + #' @description + #' Create user + #' + #' @param user Created user object + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + create_user_with_http_info = function(user, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`user`)) { + rlang::abort(message = "Missing required parameter `user`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `user`.")) + } + + + if (!is.null(`user`)) { + local_var_body <- `user`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/user" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Creates list of users with given input array + #' + #' @description + #' Creates list of users with given input array + #' + #' @param user List of user object + #' @param ... Other optional arguments + #' @return void + #' @export + create_users_with_array_input = function(user, ...) { + local_var_response <- self$create_users_with_array_input_with_http_info(user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Creates list of users with given input array + #' + #' @description + #' Creates list of users with given input array + #' + #' @param user List of user object + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + create_users_with_array_input_with_http_info = function(user, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`user`)) { + rlang::abort(message = "Missing required parameter `user`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `user`.")) + } + + + if (!is.null(`user`)) { + body.items <- paste(unlist(lapply(`user`, function(param) { + param$toJSONString() + })), collapse = ",") + local_var_body <- paste0("[", body.items, "]") + } else { + body <- NULL + } + + local_var_url_path <- "/user/createWithArray" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Creates list of users with given input array + #' + #' @description + #' Creates list of users with given input array + #' + #' @param user List of user object + #' @param ... Other optional arguments + #' @return void + #' @export + create_users_with_list_input = function(user, ...) { + local_var_response <- self$create_users_with_list_input_with_http_info(user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Creates list of users with given input array + #' + #' @description + #' Creates list of users with given input array + #' + #' @param user List of user object + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + create_users_with_list_input_with_http_info = function(user, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`user`)) { + rlang::abort(message = "Missing required parameter `user`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `user`.")) + } + + + if (!is.null(`user`)) { + body.items <- paste(unlist(lapply(`user`, function(param) { + param$toJSONString() + })), collapse = ",") + local_var_body <- paste0("[", body.items, "]") + } else { + body <- NULL + } + + local_var_url_path <- "/user/createWithList" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Delete user + #' + #' @description + #' Delete user + #' + #' @param username The name that needs to be deleted + #' @param ... Other optional arguments + #' @return void + #' @export + delete_user = function(username, ...) { + local_var_response <- self$delete_user_with_http_info(username, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Delete user + #' + #' @description + #' Delete user + #' + #' @param username The name that needs to be deleted + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + delete_user_with_http_info = function(username, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`username`)) { + rlang::abort(message = "Missing required parameter `username`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `username`.")) + } + + + local_var_url_path <- "/user/{username}" + if (!missing(`username`)) { + local_var_url_path <- gsub("\\{username\\}", URLencode(as.character(`username`), reserved = TRUE), local_var_url_path) + } + + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "DELETE", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Get user by user name + #' + #' @description + #' Get user by user name + #' + #' @param username The name that needs to be fetched. Use user1 for testing. + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return User + #' @export + get_user_by_name = function(username, data_file = NULL, ...) { + local_var_response <- self$get_user_by_name_with_http_info(username, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Get user by user name + #' + #' @description + #' Get user by user name + #' + #' @param username The name that needs to be fetched. Use user1 for testing. + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (User) with additional information such as HTTP status code, headers + #' @export + get_user_by_name_with_http_info = function(username, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`username`)) { + rlang::abort(message = "Missing required parameter `username`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `username`.")) + } + + + local_var_url_path <- "/user/{username}" + if (!missing(`username`)) { + local_var_url_path <- gsub("\\{username\\}", URLencode(as.character(`username`), reserved = TRUE), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "User", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Logs user into the system + #' + #' @description + #' Logs user into the system + #' + #' @param username The user name for login + #' @param password The password for login in clear text + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return character + #' @export + login_user = function(username, password, data_file = NULL, ...) { + local_var_response <- self$login_user_with_http_info(username, password, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Logs user into the system + #' + #' @description + #' Logs user into the system + #' + #' @param username The user name for login + #' @param password The password for login in clear text + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (character) with additional information such as HTTP status code, headers + #' @export + login_user_with_http_info = function(username, password, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`username`)) { + rlang::abort(message = "Missing required parameter `username`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `username`.")) + } + + if (missing(`password`)) { + rlang::abort(message = "Missing required parameter `password`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `password`.")) + } + + if (!str_detect(`username`, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")) { + rlang::abort(message = "Invalid value for `username` when calling UserApi$login_user, must conform to the pattern ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `username` when calling UserApi$login_user, must conform to the pattern ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$.")) + } + + + query_params[["username"]] <- `username` + + query_params[["password"]] <- `password` + + local_var_url_path <- "/user/login" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "character", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Logs out current logged in user session + #' + #' @description + #' Logs out current logged in user session + #' + #' @param ... Other optional arguments + #' @return void + #' @export + logout_user = function(...) { + local_var_response <- self$logout_user_with_http_info(...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Logs out current logged in user session + #' + #' @description + #' Logs out current logged in user session + #' + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + logout_user_with_http_info = function(...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + local_var_url_path <- "/user/logout" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Updated user + #' + #' @description + #' Updated user + #' + #' @param username name that need to be deleted + #' @param user Updated user object + #' @param ... Other optional arguments + #' @return void + #' @export + update_user = function(username, user, ...) { + local_var_response <- self$update_user_with_http_info(username, user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Updated user + #' + #' @description + #' Updated user + #' + #' @param username name that need to be deleted + #' @param user Updated user object + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + update_user_with_http_info = function(username, user, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`username`)) { + rlang::abort(message = "Missing required parameter `username`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `username`.")) + } + + if (missing(`user`)) { + rlang::abort(message = "Missing required parameter `user`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `user`.")) + } + + + + if (!is.null(`user`)) { + local_var_body <- `user`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/user/{username}" + if (!missing(`username`)) { + local_var_url_path <- gsub("\\{username\\}", URLencode(as.character(`username`), reserved = TRUE), local_var_url_path) + } + + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "PUT", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + } + ) +) diff --git a/samples/client/petstore/R-httr2/R/whale.R b/samples/client/petstore/R-httr2/R/whale.R new file mode 100644 index 0000000000..51a3f0b69f --- /dev/null +++ b/samples/client/petstore/R-httr2/R/whale.R @@ -0,0 +1,223 @@ +#' Create a new Whale +#' +#' @description +#' Whale Class +#' +#' @docType class +#' @title Whale +#' @description Whale Class +#' @format An \code{R6Class} generator object +#' @field hasBaleen character [optional] +#' @field hasTeeth character [optional] +#' @field className character +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Whale <- R6::R6Class( + "Whale", + public = list( + `hasBaleen` = NULL, + `hasTeeth` = NULL, + `className` = NULL, + #' Initialize a new Whale class. + #' + #' @description + #' Initialize a new Whale class. + #' + #' @param className className + #' @param hasBaleen hasBaleen + #' @param hasTeeth hasTeeth + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `hasBaleen` = NULL, `hasTeeth` = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`hasBaleen`)) { + stopifnot(is.logical(`hasBaleen`), length(`hasBaleen`) == 1) + self$`hasBaleen` <- `hasBaleen` + } + if (!is.null(`hasTeeth`)) { + stopifnot(is.logical(`hasTeeth`), length(`hasTeeth`) == 1) + self$`hasTeeth` <- `hasTeeth` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Whale in JSON format + #' @export + toJSON = function() { + WhaleObject <- list() + if (!is.null(self$`hasBaleen`)) { + WhaleObject[["hasBaleen"]] <- + self$`hasBaleen` + } + if (!is.null(self$`hasTeeth`)) { + WhaleObject[["hasTeeth"]] <- + self$`hasTeeth` + } + if (!is.null(self$`className`)) { + WhaleObject[["className"]] <- + self$`className` + } + WhaleObject + }, + #' Deserialize JSON string into an instance of Whale + #' + #' @description + #' Deserialize JSON string into an instance of Whale + #' + #' @param input_json the JSON input + #' @return the instance of Whale + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`hasBaleen`)) { + self$`hasBaleen` <- this_object$`hasBaleen` + } + if (!is.null(this_object$`hasTeeth`)) { + self$`hasTeeth` <- this_object$`hasTeeth` + } + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Whale in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`hasBaleen`)) { + sprintf( + '"hasBaleen": + %s + ', + tolower(self$`hasBaleen`) + ) + }, + if (!is.null(self$`hasTeeth`)) { + sprintf( + '"hasTeeth": + %s + ', + tolower(self$`hasTeeth`) + ) + }, + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Whale + #' + #' @description + #' Deserialize JSON string into an instance of Whale + #' + #' @param input_json the JSON input + #' @return the instance of Whale + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`hasBaleen` <- this_object$`hasBaleen` + self$`hasTeeth` <- this_object$`hasTeeth` + self$`className` <- this_object$`className` + self + }, + #' Validate JSON input with respect to Whale + #' + #' @description + #' Validate JSON input with respect to Whale and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Whale: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Whale + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Whale$unlock() +# +## Below is an example to define the print fnuction +# Whale$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Whale$lock() + diff --git a/samples/client/petstore/R-httr2/R/zebra.R b/samples/client/petstore/R-httr2/R/zebra.R new file mode 100644 index 0000000000..7feafc3745 --- /dev/null +++ b/samples/client/petstore/R-httr2/R/zebra.R @@ -0,0 +1,209 @@ +#' Create a new Zebra +#' +#' @description +#' Zebra Class +#' +#' @docType class +#' @title Zebra +#' @description Zebra Class +#' @format An \code{R6Class} generator object +#' @field type character [optional] +#' @field className character +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Zebra <- R6::R6Class( + "Zebra", + public = list( + `type` = NULL, + `className` = NULL, + #' Initialize a new Zebra class. + #' + #' @description + #' Initialize a new Zebra class. + #' + #' @param className className + #' @param type type + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `type` = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`type`)) { + if (!(`type` %in% c("plains", "mountain", "grevys"))) { + stop(paste("Error! \"", `type`, "\" cannot be assigned to `type`. Must be \"plains\", \"mountain\", \"grevys\".", sep = "")) + } + stopifnot(is.character(`type`), length(`type`) == 1) + self$`type` <- `type` + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Zebra in JSON format + #' @export + toJSON = function() { + ZebraObject <- list() + if (!is.null(self$`type`)) { + ZebraObject[["type"]] <- + self$`type` + } + if (!is.null(self$`className`)) { + ZebraObject[["className"]] <- + self$`className` + } + ZebraObject + }, + #' Deserialize JSON string into an instance of Zebra + #' + #' @description + #' Deserialize JSON string into an instance of Zebra + #' + #' @param input_json the JSON input + #' @return the instance of Zebra + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`type`)) { + if (!is.null(this_object$`type`) && !(this_object$`type` %in% c("plains", "mountain", "grevys"))) { + stop(paste("Error! \"", this_object$`type`, "\" cannot be assigned to `type`. Must be \"plains\", \"mountain\", \"grevys\".", sep = "")) + } + self$`type` <- this_object$`type` + } + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Zebra in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`type`)) { + sprintf( + '"type": + "%s" + ', + self$`type` + ) + }, + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Deserialize JSON string into an instance of Zebra + #' + #' @description + #' Deserialize JSON string into an instance of Zebra + #' + #' @param input_json the JSON input + #' @return the instance of Zebra + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`type`) && !(this_object$`type` %in% c("plains", "mountain", "grevys"))) { + stop(paste("Error! \"", this_object$`type`, "\" cannot be assigned to `type`. Must be \"plains\", \"mountain\", \"grevys\".", sep = "")) + } + self$`type` <- this_object$`type` + self$`className` <- this_object$`className` + self + }, + #' Validate JSON input with respect to Zebra + #' + #' @description + #' Validate JSON input with respect to Zebra and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Zebra: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Zebra + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Zebra$unlock() +# +## Below is an example to define the print fnuction +# Zebra$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Zebra$lock() + diff --git a/samples/client/petstore/R-httr2/README.md b/samples/client/petstore/R-httr2/README.md new file mode 100644 index 0000000000..bb481451cb --- /dev/null +++ b/samples/client/petstore/R-httr2/README.md @@ -0,0 +1,159 @@ +# R API client for petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.RClientCodegen + +## Installation + +### Prerequisites + +Install the dependencies + +```R +install.packages("jsonlite") +install.packages("httr") +install.packages("base64enc") +``` + +### Build the package + +```sh +git clone https://github.com/GIT_USER_ID/GIT_REPO_ID +cd GIT_REPO_ID +R CMD build . +R CMD check petstore_1.0.0.tar.gz --no-manual +R CMD INSTALL --preclean petstore_1.0.0.tar.gz +``` + +### Install the package + +```R +install.packages("petstore") +``` + +To install directly from Github, use `devtools`: +```R +install.packages("devtools") +library(devtools) +install_github("GIT_USER_ID/GIT_REPO_ID") +``` + +To install the package from a local file: +```R +install.packages("petstore_1.0.0.tar.gz", repos = NULL, type = "source") +``` + +### Usage + +```R +library(petstore) +``` + +### Reformat code + +To reformat code using [styler](https://styler.r-lib.org/index.html), please run the following in the R console: + +```R +install.packages("remotes") +remotes::install_github("r-lib/styler@v1.7.0.9003") +library("styler") +style_dir() +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*FakeApi* | [**add_pet_optional**](docs/FakeApi.md#add_pet_optional) | **POST** /fake/test_optional_body_parameter | Add a new pet to the store (optional body) +*FakeApi* | [**fake_data_file**](docs/FakeApi.md#fake_data_file) | **GET** /fake/data_file | test data_file to ensure it's escaped correctly +*FakeApi* | [**fake_path_array**](docs/FakeApi.md#fake_path_array) | **GET** /fake/path_array/{path_array}/testing | test array parameter in path +*FakeApi* | [**fake_regular_expression**](docs/FakeApi.md#fake_regular_expression) | **GET** /fake/regular_expression | test regular expression to ensure no exception +*FakeApi* | [**fake_set_query**](docs/FakeApi.md#fake_set_query) | **GET** /fake/set_query_parameter | test set query parameter +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**get_pet_by_id_streaming**](docs/PetApi.md#get_pet_by_id_streaming) | **GET** /pet/{petId}?streaming | Find pet by ID (streaming) +*PetApi* | [**test_header**](docs/PetApi.md#test_header) | **GET** /pet_header_test | Header test +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [AllofTagApiResponse](docs/AllofTagApiResponse.md) + - [Animal](docs/Animal.md) + - [AnyOfPig](docs/AnyOfPig.md) + - [AnyOfPrimitiveTypeTest](docs/AnyOfPrimitiveTypeTest.md) + - [BasquePig](docs/BasquePig.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [DanishPig](docs/DanishPig.md) + - [Date](docs/Date.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [Mammal](docs/Mammal.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [NestedOneOf](docs/NestedOneOf.md) + - [OneOfPrimitiveTypeTest](docs/OneOfPrimitiveTypeTest.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Pig](docs/Pig.md) + - [Special](docs/Special.md) + - [Tag](docs/Tag.md) + - [UpdatePetRequest](docs/UpdatePetRequest.md) + - [User](docs/User.md) + - [Whale](docs/Whale.md) + - [Zebra](docs/Zebra.md) + + +## Documentation for Authorization + + +### BearerToken + +- **Type**: Bearer authentication + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### http_auth + +- **Type**: HTTP basic authentication + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - `write:pets`: modify pets in your account + - `read:pets`: read your pets + + diff --git a/samples/client/petstore/R-httr2/build_and_test.bash b/samples/client/petstore/R-httr2/build_and_test.bash new file mode 100644 index 0000000000..2079f75da0 --- /dev/null +++ b/samples/client/petstore/R-httr2/build_and_test.bash @@ -0,0 +1,26 @@ +#!/bin/bash + +set -e + +REPO=https://cloud.r-project.org + +export R_LIBS_USER=$HOME/R + +echo "R lib directory: $R_LIBS_USER" + +mkdir $R_LIBS_USER || true + +Rscript -e "install.packages('jsonlite', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('httr', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('testthat', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('R6', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('base64enc', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('rlang', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('rjson', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('devtools', repos='$REPO', lib='$R_LIBS_USER')" + +rm petstore_1.0.0.tar.gz || true + +R CMD build . +R CMD check *tar.gz --no-manual +R CMD install --preclean *tar.gz diff --git a/samples/client/petstore/R-httr2/docs/AllofTagApiResponse.md b/samples/client/petstore/R-httr2/docs/AllofTagApiResponse.md new file mode 100644 index 0000000000..14bcc1e22c --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/AllofTagApiResponse.md @@ -0,0 +1,13 @@ +# petstore::AllofTagApiResponse + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**name** | **character** | | [optional] +**code** | **integer** | | [optional] +**type** | **character** | | [optional] +**message** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/Animal.md b/samples/client/petstore/R-httr2/docs/Animal.md new file mode 100644 index 0000000000..21af972e0f --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Animal.md @@ -0,0 +1,10 @@ +# petstore::Animal + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | [optional] [default to "red"] + + diff --git a/samples/client/petstore/R-httr2/docs/AnyOfPig.md b/samples/client/petstore/R-httr2/docs/AnyOfPig.md new file mode 100644 index 0000000000..296d7c7e33 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/AnyOfPig.md @@ -0,0 +1,11 @@ +# petstore::AnyOfPig + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | +**size** | **integer** | | + + diff --git a/samples/client/petstore/R-httr2/docs/AnyOfPrimitiveTypeTest.md b/samples/client/petstore/R-httr2/docs/AnyOfPrimitiveTypeTest.md new file mode 100644 index 0000000000..0d8ba0e63b --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/AnyOfPrimitiveTypeTest.md @@ -0,0 +1,8 @@ +# petstore::AnyOfPrimitiveTypeTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/R-httr2/docs/BasquePig.md b/samples/client/petstore/R-httr2/docs/BasquePig.md new file mode 100644 index 0000000000..9e00cec58b --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/BasquePig.md @@ -0,0 +1,10 @@ +# petstore::BasquePig + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | + + diff --git a/samples/client/petstore/R-httr2/docs/Cat.md b/samples/client/petstore/R-httr2/docs/Cat.md new file mode 100644 index 0000000000..9a717492c0 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Cat.md @@ -0,0 +1,11 @@ +# petstore::Cat + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | [optional] [default to "red"] +**declawed** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/CatAllOf.md b/samples/client/petstore/R-httr2/docs/CatAllOf.md new file mode 100644 index 0000000000..ab2f71b88e --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/CatAllOf.md @@ -0,0 +1,9 @@ +# petstore::CatAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/Category.md b/samples/client/petstore/R-httr2/docs/Category.md new file mode 100644 index 0000000000..41b20285b8 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Category.md @@ -0,0 +1,11 @@ +# petstore::Category + +A category for a pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**name** | **character** | | [optional] [Pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$] + + diff --git a/samples/client/petstore/R-httr2/docs/DanishPig.md b/samples/client/petstore/R-httr2/docs/DanishPig.md new file mode 100644 index 0000000000..1d6c5bf2ac --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/DanishPig.md @@ -0,0 +1,10 @@ +# petstore::DanishPig + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**size** | **integer** | | + + diff --git a/samples/client/petstore/R-httr2/docs/Date.md b/samples/client/petstore/R-httr2/docs/Date.md new file mode 100644 index 0000000000..ed61f58682 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Date.md @@ -0,0 +1,12 @@ +# petstore::Date + +to test the model name `Date` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**percent_description** | **character** | using % in the description | [optional] +**url_property** | **character** | | + + diff --git a/samples/client/petstore/R-httr2/docs/Dog.md b/samples/client/petstore/R-httr2/docs/Dog.md new file mode 100644 index 0000000000..6893a5e18e --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Dog.md @@ -0,0 +1,11 @@ +# petstore::Dog + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | [optional] [default to "red"] +**breed** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/DogAllOf.md b/samples/client/petstore/R-httr2/docs/DogAllOf.md new file mode 100644 index 0000000000..76783e8800 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/DogAllOf.md @@ -0,0 +1,9 @@ +# petstore::DogAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/FakeApi.md b/samples/client/petstore/R-httr2/docs/FakeApi.md new file mode 100644 index 0000000000..0c5e8a0af9 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/FakeApi.md @@ -0,0 +1,308 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_pet_optional**](FakeApi.md#add_pet_optional) | **POST** /fake/test_optional_body_parameter | Add a new pet to the store (optional body) +[**fake_data_file**](FakeApi.md#fake_data_file) | **GET** /fake/data_file | test data_file to ensure it's escaped correctly +[**fake_path_array**](FakeApi.md#fake_path_array) | **GET** /fake/path_array/{path_array}/testing | test array parameter in path +[**fake_regular_expression**](FakeApi.md#fake_regular_expression) | **GET** /fake/regular_expression | test regular expression to ensure no exception +[**fake_set_query**](FakeApi.md#fake_set_query) | **GET** /fake/set_query_parameter | test set query parameter + + +# **add_pet_optional** +> Pet add_pet_optional(pet = var.pet) + +Add a new pet to the store (optional body) + + + +### Example +```R +library(petstore) + +# Add a new pet to the store (optional body) +# +# prepare function argument(s) +var_pet <- Pet$new("name_example", list("photoUrls_example"), 123, Category$new(123, "name_example"), list(Tag$new(123, "name_example")), "available") # Pet | Pet object that needs to be added to the store (Optional) + +api_instance <- FakeApi$new() +# Configure HTTP basic authorization: http_auth +api_instance$api_client$username <- Sys.getenv("USERNAME") +api_instance$api_client$password <- Sys.getenv("PASSWORD") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$add_pet_optional(pet = var_pet, data_file = "result.txt"), + api_instance$add_pet_optional(pet = var_pet), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `add_pet_optional`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml, multipart/related + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + +# **fake_data_file** +> User fake_data_file(dummy, var_data_file = var.var_data_file) + +test data_file to ensure it's escaped correctly + + + +### Example +```R +library(petstore) + +# test data_file to ensure it's escaped correctly +# +# prepare function argument(s) +var_dummy <- "dummy_example" # character | dummy required parameter +var_var_data_file <- "var_data_file_example" # character | header data file (Optional) + +api_instance <- FakeApi$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$fake_data_file(var_dummy, var_data_file = var_var_data_file, data_file = "result.txt"), + api_instance$fake_data_file(var_dummy, var_data_file = var_var_data_file), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `fake_data_file`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **dummy** | **character**| dummy required parameter | + **var_data_file** | **character**| header data file | [optional] + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **fake_path_array** +> fake_path_array(path_array) + +test array parameter in path + + + +### Example +```R +library(petstore) + +# test array parameter in path +# +# prepare function argument(s) +var_path_array <- list("inner_example") # array[character] | dummy path parameter + +api_instance <- FakeApi$new() +result <- tryCatch( + api_instance$fake_path_array(var_path_array), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `fake_path_array`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **path_array** | list( **character** )| dummy path parameter | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **fake_regular_expression** +> fake_regular_expression(reg_exp_test) + +test regular expression to ensure no exception + + + +### Example +```R +library(petstore) + +# test regular expression to ensure no exception +# +# prepare function argument(s) +var_reg_exp_test <- "reg_exp_test_example" # character | dummy required parameter + +api_instance <- FakeApi$new() +result <- tryCatch( + api_instance$fake_regular_expression(var_reg_exp_test), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `fake_regular_expression`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **reg_exp_test** | **character**| dummy required parameter | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **fake_set_query** +> fake_set_query(set_dummy, array_dummy) + +test set query parameter + + + +### Example +```R +library(petstore) + +# test set query parameter +# +# prepare function argument(s) +var_set_dummy <- list("inner_example") # set[character] | set query +var_array_dummy <- list("inner_example") # array[character] | array query + +api_instance <- FakeApi$new() +result <- tryCatch( + api_instance$fake_set_query(var_set_dummy, var_array_dummy), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `fake_set_query`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **set_dummy** | list( **character** )| set query | + **array_dummy** | list( **character** )| array query | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/R-httr2/docs/Mammal.md b/samples/client/petstore/R-httr2/docs/Mammal.md new file mode 100644 index 0000000000..a2835af3f4 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Mammal.md @@ -0,0 +1,12 @@ +# petstore::Mammal + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**hasBaleen** | **character** | | [optional] +**hasTeeth** | **character** | | [optional] +**className** | **character** | | +**type** | **character** | | [optional] [Enum: [plains, mountain, grevys]] + + diff --git a/samples/client/petstore/R-httr2/docs/ModelApiResponse.md b/samples/client/petstore/R-httr2/docs/ModelApiResponse.md new file mode 100644 index 0000000000..c761ca7d5e --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ +# petstore::ModelApiResponse + +Describes the result of uploading an image resource + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **integer** | | [optional] +**type** | **character** | | [optional] +**message** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/NestedOneOf.md b/samples/client/petstore/R-httr2/docs/NestedOneOf.md new file mode 100644 index 0000000000..ecc2ed8914 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/NestedOneOf.md @@ -0,0 +1,10 @@ +# petstore::NestedOneOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**size** | **integer** | | [optional] +**nested_pig** | [**Pig**](Pig.md) | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/OneOfPrimitiveTypeTest.md b/samples/client/petstore/R-httr2/docs/OneOfPrimitiveTypeTest.md new file mode 100644 index 0000000000..82cf318431 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/OneOfPrimitiveTypeTest.md @@ -0,0 +1,8 @@ +# petstore::OneOfPrimitiveTypeTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/R-httr2/docs/Order.md b/samples/client/petstore/R-httr2/docs/Order.md new file mode 100644 index 0000000000..85860b2fb8 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Order.md @@ -0,0 +1,15 @@ +# petstore::Order + +An order for a pets from the pet store + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**petId** | **integer** | | [optional] +**quantity** | **integer** | | [optional] +**shipDate** | **character** | | [optional] +**status** | **character** | Order Status | [optional] [Enum: [placed, approved, delivered]] +**complete** | **character** | | [optional] [default to FALSE] + + diff --git a/samples/client/petstore/R-httr2/docs/Pet.md b/samples/client/petstore/R-httr2/docs/Pet.md new file mode 100644 index 0000000000..29186b2a14 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Pet.md @@ -0,0 +1,15 @@ +# petstore::Pet + +A pet for sale in the pet store + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **character** | | +**photoUrls** | **array[character]** | | +**tags** | [**array[Tag]**](Tag.md) | | [optional] +**status** | **character** | pet status in the store | [optional] [Enum: [available, pending, sold]] + + diff --git a/samples/client/petstore/R-httr2/docs/PetApi.md b/samples/client/petstore/R-httr2/docs/PetApi.md new file mode 100644 index 0000000000..26936a4b78 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/PetApi.md @@ -0,0 +1,659 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +[**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +[**get_pet_by_id_streaming**](PetApi.md#get_pet_by_id_streaming) | **GET** /pet/{petId}?streaming | Find pet by ID (streaming) +[**test_header**](PetApi.md#test_header) | **GET** /pet_header_test | Header test +[**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image + + +# **add_pet** +> Pet add_pet(pet) + +Add a new pet to the store + + + +### Example +```R +library(petstore) + +# Add a new pet to the store +# +# prepare function argument(s) +var_pet <- Pet$new("name_example", list("photoUrls_example"), 123, Category$new(123, "name_example"), list(Tag$new(123, "name_example")), "available") # Pet | Pet object that needs to be added to the store + +api_instance <- PetApi$new() +# Configure HTTP basic authorization: http_auth +api_instance$api_client$username <- Sys.getenv("USERNAME") +api_instance$api_client$password <- Sys.getenv("PASSWORD") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$add_pet(var_pet, data_file = "result.txt"), + api_instance$add_pet(var_pet), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `add_pet`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml, multipart/related + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + +# **delete_pet** +> delete_pet(pet_id, api_key = var.api_key) + +Deletes a pet + + + +### Example +```R +library(petstore) + +# Deletes a pet +# +# prepare function argument(s) +var_pet_id <- 56 # integer | Pet id to delete +var_api_key <- "api_key_example" # character | (Optional) + +api_instance <- PetApi$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + api_instance$delete_pet(var_pet_id, api_key = var_api_key), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `delete_pet`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| Pet id to delete | + **api_key** | **character**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid pet value | - | + +# **find_pets_by_status** +> array[Pet] find_pets_by_status(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```R +library(petstore) + +# Finds Pets by status +# +# prepare function argument(s) +var_status <- list("available") # array[character] | Status values that need to be considered for filter + +api_instance <- PetApi$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$find_pets_by_status(var_status, data_file = "result.txt"), + api_instance$find_pets_by_status(var_status), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `find_pets_by_status`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | Enum [available, pending, sold] | Status values that need to be considered for filter | + +### Return type + +[**array[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + +# **find_pets_by_tags** +> array[Pet] find_pets_by_tags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```R +library(petstore) + +# Finds Pets by tags +# +# prepare function argument(s) +var_tags <- list("inner_example") # array[character] | Tags to filter by + +api_instance <- PetApi$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$find_pets_by_tags(var_tags, data_file = "result.txt"), + api_instance$find_pets_by_tags(var_tags), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `find_pets_by_tags`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | list( **character** )| Tags to filter by | + +### Return type + +[**array[Pet]**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + +# **get_pet_by_id** +> Pet get_pet_by_id(pet_id) + +Find pet by ID + +Returns a single pet + +### Example +```R +library(petstore) + +# Find pet by ID +# +# prepare function argument(s) +var_pet_id <- 56 # integer | ID of pet to return + +api_instance <- PetApi$new() +# Configure HTTP bearer authorization: BearerToken +api_instance$api_client$bearer_token <- Sys.getenv("BEARER_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$get_pet_by_id(var_pet_id, data_file = "result.txt"), + api_instance$get_pet_by_id(var_pet_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_pet_by_id`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[BearerToken](../README.md#BearerToken) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +# **get_pet_by_id_streaming** +> Pet get_pet_by_id_streaming(pet_id) + +Find pet by ID (streaming) + +Returns a single pet + +### Example +```R +library(petstore) + +# Find pet by ID (streaming) +# +# prepare function argument(s) +var_pet_id <- 56 # integer | ID of pet to return + +api_instance <- PetApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$get_pet_by_id_streaming(var_pet_id, data_file = "result.txt"), + # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. + # api_instance$get_pet_by_id_streaming(var_pet_id, stream_callback = function(x){ print(length(x)) }), + api_instance$get_pet_by_id_streaming(var_pet_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_pet_by_id_streaming`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +# **test_header** +> Pet test_header(header_test_int) + +Header test + +Header test + +### Example +```R +library(petstore) + +# Header test +# +# prepare function argument(s) +var_header_test_int <- 56 # integer | header test int + +api_instance <- PetApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$test_header(var_header_test_int, data_file = "result.txt"), + # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. + # api_instance$test_header(var_header_test_int, stream_callback = function(x){ print(length(x)) }), + api_instance$test_header(var_header_test_int), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `test_header`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **header_test_int** | **integer**| header test int | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +# **update_pet** +> Pet update_pet(pet) + +Update an existing pet + + + +### Example +```R +library(petstore) + +# Update an existing pet +# +# prepare function argument(s) +var_pet <- Pet$new("name_example", list("photoUrls_example"), 123, Category$new(123, "name_example"), list(Tag$new(123, "name_example")), "available") # Pet | Pet object that needs to be added to the store + +api_instance <- PetApi$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$update_pet(var_pet, data_file = "result.txt"), + api_instance$update_pet(var_pet), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `update_pet`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml, multipart/related + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + +# **update_pet_with_form** +> update_pet_with_form(pet_id, name = var.name, status = var.status) + +Updates a pet in the store with form data + + + +### Example +```R +library(petstore) + +# Updates a pet in the store with form data +# +# prepare function argument(s) +var_pet_id <- 56 # integer | ID of pet that needs to be updated +var_name <- "name_example" # character | Updated name of the pet (Optional) +var_status <- "status_example" # character | Updated status of the pet (Optional) + +api_instance <- PetApi$new() +result <- tryCatch( + api_instance$update_pet_with_form(var_pet_id, name = var_name, status = var_status), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `update_pet_with_form`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| ID of pet that needs to be updated | + **name** | **character**| Updated name of the pet | [optional] + **status** | **character**| Updated status of the pet | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + +# **upload_file** +> ModelApiResponse upload_file(pet_id, additional_metadata = var.additional_metadata, file = var.file) + +uploads an image + + + +### Example +```R +library(petstore) + +# uploads an image +# +# prepare function argument(s) +var_pet_id <- 56 # integer | ID of pet to update +var_additional_metadata <- "additional_metadata_example" # character | Additional data to pass to server (Optional) +var_file <- File.new('/path/to/file') # data.frame | file to upload (Optional) + +api_instance <- PetApi$new() +# Configure OAuth2 access token for authorization: petstore_auth +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$upload_file(var_pet_id, additional_metadata = var_additional_metadata, file = var_file, data_file = "result.txt"), + api_instance$upload_file(var_pet_id, additional_metadata = var_additional_metadata, file = var_file), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `upload_file`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| ID of pet to update | + **additional_metadata** | **character**| Additional data to pass to server | [optional] + **file** | **data.frame**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/R-httr2/docs/Pig.md b/samples/client/petstore/R-httr2/docs/Pig.md new file mode 100644 index 0000000000..7906011bd4 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Pig.md @@ -0,0 +1,11 @@ +# petstore::Pig + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**color** | **character** | | +**size** | **integer** | | + + diff --git a/samples/client/petstore/R-httr2/docs/Special.md b/samples/client/petstore/R-httr2/docs/Special.md new file mode 100644 index 0000000000..83c2794ec3 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Special.md @@ -0,0 +1,16 @@ +# petstore::Special + +Describes the result of uploading an image resource + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**set_test** | **set[character]** | | [optional] +**item_self** | **integer** | | [optional] +**item_private** | **character** | | [optional] +**item_super** | **character** | | [optional] +**123_number** | **character** | | [optional] +**array[test]** | **character** | | [optional] +**empty_string** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/StoreApi.md b/samples/client/petstore/R-httr2/docs/StoreApi.md new file mode 100644 index 0000000000..c0453bb361 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/StoreApi.md @@ -0,0 +1,251 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +[**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +[**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet + + +# **delete_order** +> delete_order(order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```R +library(petstore) + +# Delete purchase order by ID +# +# prepare function argument(s) +var_order_id <- "order_id_example" # character | ID of the order that needs to be deleted + +api_instance <- StoreApi$new() +result <- tryCatch( + api_instance$delete_order(var_order_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `delete_order`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **character**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +# **get_inventory** +> map(integer) get_inventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```R +library(petstore) + +# Returns pet inventories by status +# + +api_instance <- StoreApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$get_inventory(data_file = "result.txt"), + api_instance$get_inventory(), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_inventory`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**map(integer)** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **get_order_by_id** +> Order get_order_by_id(order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```R +library(petstore) + +# Find purchase order by ID +# +# prepare function argument(s) +var_order_id <- 56 # integer | ID of pet that needs to be fetched + +api_instance <- StoreApi$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$get_order_by_id(var_order_id, data_file = "result.txt"), + api_instance$get_order_by_id(var_order_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_order_by_id`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **integer**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +# **place_order** +> Order place_order(order) + +Place an order for a pet + + + +### Example +```R +library(petstore) + +# Place an order for a pet +# +# prepare function argument(s) +var_order <- Order$new(123, 123, 123, "shipDate_example", "placed", "complete_example") # Order | order placed for purchasing the pet + +api_instance <- StoreApi$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$place_order(var_order, data_file = "result.txt"), + api_instance$place_order(var_order), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `place_order`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/samples/client/petstore/R-httr2/docs/Tag.md b/samples/client/petstore/R-httr2/docs/Tag.md new file mode 100644 index 0000000000..3cb9bd184d --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Tag.md @@ -0,0 +1,11 @@ +# petstore::Tag + +A tag for a pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**name** | **character** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/UpdatePetRequest.md b/samples/client/petstore/R-httr2/docs/UpdatePetRequest.md new file mode 100644 index 0000000000..619f0b2262 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/UpdatePetRequest.md @@ -0,0 +1,10 @@ +# petstore::UpdatePetRequest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**jsonData** | [**Pet**](Pet.md) | | [optional] +**binaryDataN2Information** | **data.frame** | | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/User.md b/samples/client/petstore/R-httr2/docs/User.md new file mode 100644 index 0000000000..98d0316ea2 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/User.md @@ -0,0 +1,17 @@ +# petstore::User + +A User who is purchasing from the pet store + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **integer** | | [optional] +**username** | **character** | | [optional] +**firstName** | **character** | | [optional] +**lastName** | **character** | | [optional] +**email** | **character** | | [optional] +**password** | **character** | | [optional] +**phone** | **character** | | [optional] +**userStatus** | **integer** | User Status | [optional] + + diff --git a/samples/client/petstore/R-httr2/docs/UserApi.md b/samples/client/petstore/R-httr2/docs/UserApi.md new file mode 100644 index 0000000000..7bb012fd1b --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/UserApi.md @@ -0,0 +1,484 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_user**](UserApi.md#create_user) | **POST** /user | Create user +[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +[**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +[**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +[**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system +[**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +[**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +# **create_user** +> create_user(user) + +Create user + +This can only be done by the logged in user. + +### Example +```R +library(petstore) + +# Create user +# +# prepare function argument(s) +var_user <- User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123) # User | Created user object + +api_instance <- UserApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$create_user(var_user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `create_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +# **create_users_with_array_input** +> create_users_with_array_input(user) + +Creates list of users with given input array + + + +### Example +```R +library(petstore) + +# Creates list of users with given input array +# +# prepare function argument(s) +var_user <- list(User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123)) # array[User] | List of user object + +api_instance <- UserApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$create_users_with_array_input(var_user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `create_users_with_array_input`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | list( [**User**](User.md) )| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +# **create_users_with_list_input** +> create_users_with_list_input(user) + +Creates list of users with given input array + + + +### Example +```R +library(petstore) + +# Creates list of users with given input array +# +# prepare function argument(s) +var_user <- list(User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123)) # array[User] | List of user object + +api_instance <- UserApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$create_users_with_list_input(var_user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `create_users_with_list_input`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | list( [**User**](User.md) )| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +# **delete_user** +> delete_user(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```R +library(petstore) + +# Delete user +# +# prepare function argument(s) +var_username <- "username_example" # character | The name that needs to be deleted + +api_instance <- UserApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$delete_user(var_username), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `delete_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **character**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +# **get_user_by_name** +> User get_user_by_name(username) + +Get user by user name + + + +### Example +```R +library(petstore) + +# Get user by user name +# +# prepare function argument(s) +var_username <- "username_example" # character | The name that needs to be fetched. Use user1 for testing. + +api_instance <- UserApi$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$get_user_by_name(var_username, data_file = "result.txt"), + api_instance$get_user_by_name(var_username), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `get_user_by_name`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **character**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +# **login_user** +> character login_user(username, password) + +Logs user into the system + + + +### Example +```R +library(petstore) + +# Logs user into the system +# +# prepare function argument(s) +var_username <- "username_example" # character | The user name for login +var_password <- "password_example" # character | The password for login in clear text + +api_instance <- UserApi$new() +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$login_user(var_username, var_password, data_file = "result.txt"), + api_instance$login_user(var_username, var_password), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `login_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **character**| The user name for login | + **password** | **character**| The password for login in clear text | + +### Return type + +**character** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
        * X-Rate-Limit - calls per hour allowed by the user
        * X-Expires-After - date in UTC when token expires
        | +| **400** | Invalid username/password supplied | - | + +# **logout_user** +> logout_user() + +Logs out current logged in user session + + + +### Example +```R +library(petstore) + +# Logs out current logged in user session +# + +api_instance <- UserApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$logout_user(), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `logout_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +# **update_user** +> update_user(username, user) + +Updated user + +This can only be done by the logged in user. + +### Example +```R +library(petstore) + +# Updated user +# +# prepare function argument(s) +var_username <- "username_example" # character | name that need to be deleted +var_user <- User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123) # User | Updated user object + +api_instance <- UserApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + api_instance$update_user(var_username, var_user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `update_user`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **character**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/samples/client/petstore/R-httr2/docs/Whale.md b/samples/client/petstore/R-httr2/docs/Whale.md new file mode 100644 index 0000000000..bd0d148686 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Whale.md @@ -0,0 +1,11 @@ +# petstore::Whale + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**hasBaleen** | **character** | | [optional] +**hasTeeth** | **character** | | [optional] +**className** | **character** | | + + diff --git a/samples/client/petstore/R-httr2/docs/Zebra.md b/samples/client/petstore/R-httr2/docs/Zebra.md new file mode 100644 index 0000000000..51b7094126 --- /dev/null +++ b/samples/client/petstore/R-httr2/docs/Zebra.md @@ -0,0 +1,10 @@ +# petstore::Zebra + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | **character** | | [optional] [Enum: [plains, mountain, grevys]] +**className** | **character** | | + + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/git_push.sh b/samples/client/petstore/R-httr2/git_push.sh similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/git_push.sh rename to samples/client/petstore/R-httr2/git_push.sh diff --git a/samples/client/petstore/R-httr2/man/AllofTagApiResponse.Rd b/samples/client/petstore/R-httr2/man/AllofTagApiResponse.Rd new file mode 100644 index 0000000000..eeb058dd7b --- /dev/null +++ b/samples/client/petstore/R-httr2/man/AllofTagApiResponse.Rd @@ -0,0 +1,196 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/allof_tag_api_response.R +\docType{class} +\name{AllofTagApiResponse} +\alias{AllofTagApiResponse} +\title{AllofTagApiResponse} +\format{ +An \code{R6Class} generator object +} +\description{ +AllofTagApiResponse Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{integer [optional]} + +\item{\code{name}}{character [optional]} + +\item{\code{code}}{integer [optional]} + +\item{\code{type}}{character [optional]} + +\item{\code{message}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-AllofTagApiResponse-new}{\code{AllofTagApiResponse$new()}} +\item \href{#method-AllofTagApiResponse-toJSON}{\code{AllofTagApiResponse$toJSON()}} +\item \href{#method-AllofTagApiResponse-fromJSON}{\code{AllofTagApiResponse$fromJSON()}} +\item \href{#method-AllofTagApiResponse-toJSONString}{\code{AllofTagApiResponse$toJSONString()}} +\item \href{#method-AllofTagApiResponse-fromJSONString}{\code{AllofTagApiResponse$fromJSONString()}} +\item \href{#method-AllofTagApiResponse-validateJSON}{\code{AllofTagApiResponse$validateJSON()}} +\item \href{#method-AllofTagApiResponse-toString}{\code{AllofTagApiResponse$toString()}} +\item \href{#method-AllofTagApiResponse-clone}{\code{AllofTagApiResponse$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AllofTagApiResponse-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new AllofTagApiResponse class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AllofTagApiResponse$new( + id = NULL, + name = NULL, + code = NULL, + type = NULL, + message = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{id} + +\item{\code{name}}{name} + +\item{\code{code}}{code} + +\item{\code{type}}{type} + +\item{\code{message}}{message} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AllofTagApiResponse-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AllofTagApiResponse$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +AllofTagApiResponse in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AllofTagApiResponse-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of AllofTagApiResponse +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AllofTagApiResponse$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of AllofTagApiResponse +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AllofTagApiResponse-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AllofTagApiResponse$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +AllofTagApiResponse in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AllofTagApiResponse-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of AllofTagApiResponse +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AllofTagApiResponse$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of AllofTagApiResponse +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AllofTagApiResponse-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to AllofTagApiResponse and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AllofTagApiResponse$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AllofTagApiResponse-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AllofTagApiResponse$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of AllofTagApiResponse +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AllofTagApiResponse-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AllofTagApiResponse$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/Animal.Rd b/samples/client/petstore/R-httr2/man/Animal.Rd new file mode 100644 index 0000000000..36d90e9aed --- /dev/null +++ b/samples/client/petstore/R-httr2/man/Animal.Rd @@ -0,0 +1,177 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/animal.R +\docType{class} +\name{Animal} +\alias{Animal} +\title{Animal} +\format{ +An \code{R6Class} generator object +} +\description{ +Animal Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{character} + +\item{\code{color}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Animal-new}{\code{Animal$new()}} +\item \href{#method-Animal-toJSON}{\code{Animal$toJSON()}} +\item \href{#method-Animal-fromJSON}{\code{Animal$fromJSON()}} +\item \href{#method-Animal-toJSONString}{\code{Animal$toJSONString()}} +\item \href{#method-Animal-fromJSONString}{\code{Animal$fromJSONString()}} +\item \href{#method-Animal-validateJSON}{\code{Animal$validateJSON()}} +\item \href{#method-Animal-toString}{\code{Animal$toString()}} +\item \href{#method-Animal-clone}{\code{Animal$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Animal-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new Animal class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Animal$new(className, color = "red", ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{className} + +\item{\code{color}}{color. Default to 'red'.} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Animal-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Animal$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Animal in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Animal-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of Animal +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Animal$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Animal +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Animal-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Animal$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Animal in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Animal-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of Animal +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Animal$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Animal +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Animal-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to Animal and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Animal$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Animal-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Animal$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of Animal +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Animal-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Animal$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/AnyOfPig.Rd b/samples/client/petstore/R-httr2/man/AnyOfPig.Rd new file mode 100644 index 0000000000..a40bf0c69c --- /dev/null +++ b/samples/client/petstore/R-httr2/man/AnyOfPig.Rd @@ -0,0 +1,156 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/any_of_pig.R +\docType{class} +\name{AnyOfPig} +\alias{AnyOfPig} +\title{AnyOfPig} +\format{ +An \code{R6Class} generator object +} +\description{ +AnyOfPig Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{actual_instance}}{the object stored in this instance.} + +\item{\code{actual_type}}{the type of the object stored in this instance.} + +\item{\code{any_of}}{a list of object types defined in the anyOf schema. +Initialize a new AnyOfPig.} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-AnyOfPig-new}{\code{AnyOfPig$new()}} +\item \href{#method-AnyOfPig-fromJSON}{\code{AnyOfPig$fromJSON()}} +\item \href{#method-AnyOfPig-toJSONString}{\code{AnyOfPig$toJSONString()}} +\item \href{#method-AnyOfPig-toJSON}{\code{AnyOfPig$toJSON()}} +\item \href{#method-AnyOfPig-validateJSON}{\code{AnyOfPig$validateJSON()}} +\item \href{#method-AnyOfPig-toString}{\code{AnyOfPig$toString()}} +\item \href{#method-AnyOfPig-clone}{\code{AnyOfPig$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AnyOfPig-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new AnyOfPig. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AnyOfPig$new(instance = NULL)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{instance}}{an instance of the object defined in the anyOf schemas: "BasquePig", "DanishPig"} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AnyOfPig-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of AnyOfPig. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AnyOfPig$fromJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{The input JSON.} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +An instance of AnyOfPig. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AnyOfPig-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +Serialize AnyOfPig to JSON string. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AnyOfPig$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +JSON string representation of the AnyOfPig. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AnyOfPig-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +Serialize AnyOfPig to JSON. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AnyOfPig$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +JSON representation of the AnyOfPig. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AnyOfPig-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate the input JSON with respect to AnyOfPig and +throw exception if invalid. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AnyOfPig$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{The input JSON.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AnyOfPig-toString}{}}} +\subsection{Method \code{toString()}}{ +Returns the string representation of the instance. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AnyOfPig$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +The string representation of the instance. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AnyOfPig-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{AnyOfPig$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/ApiClient.Rd b/samples/client/petstore/R-httr2/man/ApiClient.Rd new file mode 100644 index 0000000000..decef8c6af --- /dev/null +++ b/samples/client/petstore/R-httr2/man/ApiClient.Rd @@ -0,0 +1,260 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/api_client.R +\docType{class} +\name{ApiClient} +\alias{ApiClient} +\title{ApiClient} +\format{ +An \code{R6Class} generator object +} +\description{ +ApiClient Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech + +ApiClient Class + +Generic API client for OpenAPI client library builds. +OpenAPI generic API client. This client handles the client- +server communication, and is invariant across implementations. Specifics of +the methods and models for each application are generated from the OpenAPI Generator +templates. + +NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +Ref: https://openapi-generator.tech +Do not edit the class manually. +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{base_path}}{Base url} + +\item{\code{user_agent}}{Default user agent} + +\item{\code{default_headers}}{Default headers} + +\item{\code{username}}{Username for HTTP basic authentication} + +\item{\code{password}}{Password for HTTP basic authentication} + +\item{\code{api_keys}}{API keys} + +\item{\code{access_token}}{Access token} + +\item{\code{timeout}}{Default timeout in seconds} + +\item{\code{retry_status_codes}}{vector of status codes to retry} + +\item{\code{max_retry_attempts}}{maximum number of retries for the status codes} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-ApiClient-new}{\code{ApiClient$new()}} +\item \href{#method-ApiClient-CallApi}{\code{ApiClient$CallApi()}} +\item \href{#method-ApiClient-Execute}{\code{ApiClient$Execute()}} +\item \href{#method-ApiClient-deserialize}{\code{ApiClient$deserialize()}} +\item \href{#method-ApiClient-deserializeObj}{\code{ApiClient$deserializeObj()}} +\item \href{#method-ApiClient-clone}{\code{ApiClient$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiClient-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new ApiClient. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiClient$new( + base_path = NULL, + user_agent = NULL, + default_headers = NULL, + username = NULL, + password = NULL, + api_keys = NULL, + access_token = NULL, + timeout = NULL, + retry_status_codes = NULL, + max_retry_attempts = NULL +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{base_path}}{Base path.} + +\item{\code{user_agent}}{User agent.} + +\item{\code{default_headers}}{Default headers.} + +\item{\code{username}}{User name.} + +\item{\code{password}}{Password.} + +\item{\code{api_keys}}{API keys.} + +\item{\code{access_token}}{Access token.} + +\item{\code{timeout}}{Timeout.} + +\item{\code{retry_status_codes}}{Status codes for retry.} + +\item{\code{max_retry_attempts}}{Maxmium number of retry.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiClient-CallApi}{}}} +\subsection{Method \code{CallApi()}}{ +Prepare to make an API call with the retry logic. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiClient$CallApi( + url, + method, + query_params, + header_params, + body, + stream_callback = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{url}}{URL.} + +\item{\code{method}}{HTTP method.} + +\item{\code{query_params}}{The query parameters.} + +\item{\code{header_params}}{The header parameters.} + +\item{\code{body}}{The HTTP request body.} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +HTTP response +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiClient-Execute}{}}} +\subsection{Method \code{Execute()}}{ +Make an API call +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiClient$Execute( + url, + method, + query_params, + header_params, + body, + stream_callback = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{url}}{URL.} + +\item{\code{method}}{HTTP method.} + +\item{\code{query_params}}{The query parameters.} + +\item{\code{header_params}}{The header parameters.} + +\item{\code{body}}{The HTTP request body.} + +\item{\code{stream_callback}}{callback function to process data stream} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +HTTP response +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiClient-deserialize}{}}} +\subsection{Method \code{deserialize()}}{ +Deserialize the content of api response to the given type. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiClient$deserialize(resp, return_type, pkg_env)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{resp}}{Response object.} + +\item{\code{return_type}}{R return type.} + +\item{\code{pkg_env}}{Package environment.} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +Deserialized object. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiClient-deserializeObj}{}}} +\subsection{Method \code{deserializeObj()}}{ +Deserialize the response from jsonlite object based on the given type +by handling complex and nested types by iterating recursively +Example return_types will be like "array[integer]", "map(Pet)", "array[map(Tag)]", etc., +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiClient$deserializeObj(obj, return_type, pkg_env)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{obj}}{Response object.} + +\item{\code{return_type}}{R return type.} + +\item{\code{pkg_env}}{Package environment.} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +Deserialized object. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiClient-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiClient$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/ApiException.Rd b/samples/client/petstore/R-httr2/man/ApiException.Rd new file mode 100644 index 0000000000..94a6f74653 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/ApiException.Rd @@ -0,0 +1,95 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/api_exception.R +\docType{class} +\name{ApiException} +\alias{ApiException} +\title{ApiException} +\format{ +An \code{R6Class} generator object +} +\description{ +ApiException Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{status}}{Status of the ApiException} + +\item{\code{reason}}{Reason of the ApiException} + +\item{\code{body}}{Body of the http response} + +\item{\code{headers}}{Headers of the http response} + +\item{\code{errorObject}}{error object type} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-ApiException-new}{\code{ApiException$new()}} +\item \href{#method-ApiException-toString}{\code{ApiException$toString()}} +\item \href{#method-ApiException-clone}{\code{ApiException$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiException-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new ApiExceptino class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiException$new(status = NULL, reason = NULL, http_response = NULL)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{status}}{HTTP status.} + +\item{\code{reason}}{Reason of the ApiException.} + +\item{\code{http_response}}{HTTP response object.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiException-toString}{}}} +\subsection{Method \code{toString()}}{ +Returns the string format of ApiException. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiException$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +the string format of ApiException. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiException-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiException$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/ApiResponse.Rd b/samples/client/petstore/R-httr2/man/ApiResponse.Rd new file mode 100644 index 0000000000..d6970b6b17 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/ApiResponse.Rd @@ -0,0 +1,73 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/api_response.R +\docType{class} +\name{ApiResponse} +\alias{ApiResponse} +\title{ApiResponse} +\format{ +An \code{R6Class} generator object +} +\description{ +ApiResponse Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{content}}{The deserialized response body.} + +\item{\code{response}}{The raw response from the endpoint.} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-ApiResponse-new}{\code{ApiResponse$new()}} +\item \href{#method-ApiResponse-clone}{\code{ApiResponse$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiResponse-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new ApiResponse class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiResponse$new(content, response)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{content}}{The deserialized response body.} + +\item{\code{response}}{The raw response from the endpoint.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ApiResponse-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ApiResponse$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/BasquePig.Rd b/samples/client/petstore/R-httr2/man/BasquePig.Rd new file mode 100644 index 0000000000..df70384ea5 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/BasquePig.Rd @@ -0,0 +1,177 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/basque_pig.R +\docType{class} +\name{BasquePig} +\alias{BasquePig} +\title{BasquePig} +\format{ +An \code{R6Class} generator object +} +\description{ +BasquePig Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{character} + +\item{\code{color}}{character} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-BasquePig-new}{\code{BasquePig$new()}} +\item \href{#method-BasquePig-toJSON}{\code{BasquePig$toJSON()}} +\item \href{#method-BasquePig-fromJSON}{\code{BasquePig$fromJSON()}} +\item \href{#method-BasquePig-toJSONString}{\code{BasquePig$toJSONString()}} +\item \href{#method-BasquePig-fromJSONString}{\code{BasquePig$fromJSONString()}} +\item \href{#method-BasquePig-validateJSON}{\code{BasquePig$validateJSON()}} +\item \href{#method-BasquePig-toString}{\code{BasquePig$toString()}} +\item \href{#method-BasquePig-clone}{\code{BasquePig$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BasquePig-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new BasquePig class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{BasquePig$new(className, color, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{className} + +\item{\code{color}}{color} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BasquePig-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{BasquePig$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +BasquePig in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BasquePig-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of BasquePig +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{BasquePig$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of BasquePig +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BasquePig-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{BasquePig$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +BasquePig in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BasquePig-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of BasquePig +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{BasquePig$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of BasquePig +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BasquePig-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to BasquePig and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{BasquePig$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BasquePig-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{BasquePig$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of BasquePig +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BasquePig-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{BasquePig$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/Cat.Rd b/samples/client/petstore/R-httr2/man/Cat.Rd new file mode 100644 index 0000000000..00daccf540 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/Cat.Rd @@ -0,0 +1,190 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cat.R +\docType{class} +\name{Cat} +\alias{Cat} +\title{Cat} +\format{ +An \code{R6Class} generator object +} +\description{ +Cat Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Super class}{ +\code{\link[petstore:Animal]{petstore::Animal}} -> \code{Cat} +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{character} + +\item{\code{color}}{character [optional]} + +\item{\code{declawed}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Cat-new}{\code{Cat$new()}} +\item \href{#method-Cat-toJSON}{\code{Cat$toJSON()}} +\item \href{#method-Cat-fromJSON}{\code{Cat$fromJSON()}} +\item \href{#method-Cat-toJSONString}{\code{Cat$toJSONString()}} +\item \href{#method-Cat-fromJSONString}{\code{Cat$fromJSONString()}} +\item \href{#method-Cat-validateJSON}{\code{Cat$validateJSON()}} +\item \href{#method-Cat-toString}{\code{Cat$toString()}} +\item \href{#method-Cat-clone}{\code{Cat$clone()}} +} +} +\if{html}{\out{ +
        Inherited methods +
          +
        +
        +}} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Cat-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new Cat class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Cat$new(className, color = "red", declawed = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{className} + +\item{\code{color}}{color. Default to 'red'.} + +\item{\code{declawed}}{declawed} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Cat-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Cat$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Cat in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Cat-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of Cat +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Cat$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Cat +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Cat-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Cat$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Cat in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Cat-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of Cat +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Cat$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Cat +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Cat-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to Cat and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Cat$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Cat-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Cat$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of Cat +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Cat-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Cat$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/CatAllOf.Rd b/samples/client/petstore/R-httr2/man/CatAllOf.Rd new file mode 100644 index 0000000000..643c338aee --- /dev/null +++ b/samples/client/petstore/R-httr2/man/CatAllOf.Rd @@ -0,0 +1,173 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cat_all_of.R +\docType{class} +\name{CatAllOf} +\alias{CatAllOf} +\title{CatAllOf} +\format{ +An \code{R6Class} generator object +} +\description{ +CatAllOf Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{declawed}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-CatAllOf-new}{\code{CatAllOf$new()}} +\item \href{#method-CatAllOf-toJSON}{\code{CatAllOf$toJSON()}} +\item \href{#method-CatAllOf-fromJSON}{\code{CatAllOf$fromJSON()}} +\item \href{#method-CatAllOf-toJSONString}{\code{CatAllOf$toJSONString()}} +\item \href{#method-CatAllOf-fromJSONString}{\code{CatAllOf$fromJSONString()}} +\item \href{#method-CatAllOf-validateJSON}{\code{CatAllOf$validateJSON()}} +\item \href{#method-CatAllOf-toString}{\code{CatAllOf$toString()}} +\item \href{#method-CatAllOf-clone}{\code{CatAllOf$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-CatAllOf-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new CatAllOf class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{CatAllOf$new(declawed = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{declawed}}{declawed} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-CatAllOf-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{CatAllOf$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +CatAllOf in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-CatAllOf-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of CatAllOf +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{CatAllOf$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of CatAllOf +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-CatAllOf-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{CatAllOf$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +CatAllOf in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-CatAllOf-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of CatAllOf +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{CatAllOf$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of CatAllOf +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-CatAllOf-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to CatAllOf and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{CatAllOf$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-CatAllOf-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{CatAllOf$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of CatAllOf +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-CatAllOf-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{CatAllOf$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/Category.Rd b/samples/client/petstore/R-httr2/man/Category.Rd new file mode 100644 index 0000000000..f009bbc151 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/Category.Rd @@ -0,0 +1,177 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/category.R +\docType{class} +\name{Category} +\alias{Category} +\title{Category} +\format{ +An \code{R6Class} generator object +} +\description{ +Category Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{integer [optional]} + +\item{\code{name}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Category-new}{\code{Category$new()}} +\item \href{#method-Category-toJSON}{\code{Category$toJSON()}} +\item \href{#method-Category-fromJSON}{\code{Category$fromJSON()}} +\item \href{#method-Category-toJSONString}{\code{Category$toJSONString()}} +\item \href{#method-Category-fromJSONString}{\code{Category$fromJSONString()}} +\item \href{#method-Category-validateJSON}{\code{Category$validateJSON()}} +\item \href{#method-Category-toString}{\code{Category$toString()}} +\item \href{#method-Category-clone}{\code{Category$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Category-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new Category class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Category$new(id = NULL, name = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{id} + +\item{\code{name}}{name} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Category-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Category$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Category in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Category-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of Category +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Category$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Category +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Category-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Category$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Category in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Category-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of Category +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Category$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Category +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Category-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to Category and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Category$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Category-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Category$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of Category +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Category-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Category$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/DanishPig.Rd b/samples/client/petstore/R-httr2/man/DanishPig.Rd new file mode 100644 index 0000000000..6d72b38038 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/DanishPig.Rd @@ -0,0 +1,177 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/danish_pig.R +\docType{class} +\name{DanishPig} +\alias{DanishPig} +\title{DanishPig} +\format{ +An \code{R6Class} generator object +} +\description{ +DanishPig Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{character} + +\item{\code{size}}{integer} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-DanishPig-new}{\code{DanishPig$new()}} +\item \href{#method-DanishPig-toJSON}{\code{DanishPig$toJSON()}} +\item \href{#method-DanishPig-fromJSON}{\code{DanishPig$fromJSON()}} +\item \href{#method-DanishPig-toJSONString}{\code{DanishPig$toJSONString()}} +\item \href{#method-DanishPig-fromJSONString}{\code{DanishPig$fromJSONString()}} +\item \href{#method-DanishPig-validateJSON}{\code{DanishPig$validateJSON()}} +\item \href{#method-DanishPig-toString}{\code{DanishPig$toString()}} +\item \href{#method-DanishPig-clone}{\code{DanishPig$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DanishPig-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new DanishPig class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DanishPig$new(className, size, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{className} + +\item{\code{size}}{size} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DanishPig-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DanishPig$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +DanishPig in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DanishPig-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of DanishPig +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DanishPig$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of DanishPig +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DanishPig-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DanishPig$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +DanishPig in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DanishPig-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of DanishPig +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DanishPig$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of DanishPig +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DanishPig-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to DanishPig and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DanishPig$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DanishPig-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DanishPig$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of DanishPig +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DanishPig-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DanishPig$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/Dog.Rd b/samples/client/petstore/R-httr2/man/Dog.Rd new file mode 100644 index 0000000000..cd38a2f8e5 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/Dog.Rd @@ -0,0 +1,190 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/dog.R +\docType{class} +\name{Dog} +\alias{Dog} +\title{Dog} +\format{ +An \code{R6Class} generator object +} +\description{ +Dog Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Super class}{ +\code{\link[petstore:Animal]{petstore::Animal}} -> \code{Dog} +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{character} + +\item{\code{color}}{character [optional]} + +\item{\code{breed}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Dog-new}{\code{Dog$new()}} +\item \href{#method-Dog-toJSON}{\code{Dog$toJSON()}} +\item \href{#method-Dog-fromJSON}{\code{Dog$fromJSON()}} +\item \href{#method-Dog-toJSONString}{\code{Dog$toJSONString()}} +\item \href{#method-Dog-fromJSONString}{\code{Dog$fromJSONString()}} +\item \href{#method-Dog-validateJSON}{\code{Dog$validateJSON()}} +\item \href{#method-Dog-toString}{\code{Dog$toString()}} +\item \href{#method-Dog-clone}{\code{Dog$clone()}} +} +} +\if{html}{\out{ +
        Inherited methods +
          +
        +
        +}} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Dog-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new Dog class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Dog$new(className, color = "red", breed = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{className}}{className} + +\item{\code{color}}{color. Default to 'red'.} + +\item{\code{breed}}{breed} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Dog-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Dog$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Dog in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Dog-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of Dog +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Dog$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Dog +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Dog-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Dog$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Dog in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Dog-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of Dog +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Dog$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Dog +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Dog-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to Dog and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Dog$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Dog-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Dog$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of Dog +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Dog-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Dog$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/DogAllOf.Rd b/samples/client/petstore/R-httr2/man/DogAllOf.Rd new file mode 100644 index 0000000000..bba0063c04 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/DogAllOf.Rd @@ -0,0 +1,173 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/dog_all_of.R +\docType{class} +\name{DogAllOf} +\alias{DogAllOf} +\title{DogAllOf} +\format{ +An \code{R6Class} generator object +} +\description{ +DogAllOf Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{breed}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-DogAllOf-new}{\code{DogAllOf$new()}} +\item \href{#method-DogAllOf-toJSON}{\code{DogAllOf$toJSON()}} +\item \href{#method-DogAllOf-fromJSON}{\code{DogAllOf$fromJSON()}} +\item \href{#method-DogAllOf-toJSONString}{\code{DogAllOf$toJSONString()}} +\item \href{#method-DogAllOf-fromJSONString}{\code{DogAllOf$fromJSONString()}} +\item \href{#method-DogAllOf-validateJSON}{\code{DogAllOf$validateJSON()}} +\item \href{#method-DogAllOf-toString}{\code{DogAllOf$toString()}} +\item \href{#method-DogAllOf-clone}{\code{DogAllOf$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DogAllOf-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new DogAllOf class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DogAllOf$new(breed = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{breed}}{breed} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DogAllOf-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DogAllOf$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +DogAllOf in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DogAllOf-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of DogAllOf +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DogAllOf$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of DogAllOf +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DogAllOf-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DogAllOf$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +DogAllOf in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DogAllOf-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of DogAllOf +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DogAllOf$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of DogAllOf +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DogAllOf-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to DogAllOf and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DogAllOf$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DogAllOf-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DogAllOf$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of DogAllOf +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-DogAllOf-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{DogAllOf$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/FakeApi.Rd b/samples/client/petstore/R-httr2/man/FakeApi.Rd new file mode 100644 index 0000000000..319cd8e4e3 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/FakeApi.Rd @@ -0,0 +1,183 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/fake_api.R +\docType{class} +\name{FakeApi} +\alias{FakeApi} +\title{Fake operations} +\format{ +An \code{R6Class} generator object +} +\description{ +petstore.Fake +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Methods}{ + +\describe{ +\strong{ FakeDataFile } \emph{ test data_file to ensure it's escaped correctly } + + +\itemize{ +\item \emph{ @param } dummy character +\item \emph{ @param } var_data_file character +\item \emph{ @returnType } \link{User} \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : User +\item response headers : + +\tabular{ll}{ +} +} + +} +} + +\examples{ +\dontrun{ +#################### FakeDataFile #################### + +library(petstore) +var.dummy <- 'dummy_example' # character | dummy required parameter +var.var_data_file <- 'var_data_file_example' # character | header data file + +#test data_file to ensure it's escaped correctly +api.instance <- FakeApi$new() + +result <- tryCatch( + api.instance$FakeDataFile(var.dummy, var_data_file=var.var_data_file), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +} +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{api_client}}{Handles the client-server communication.} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-FakeApi-new}{\code{FakeApi$new()}} +\item \href{#method-FakeApi-FakeDataFile}{\code{FakeApi$FakeDataFile()}} +\item \href{#method-FakeApi-FakeDataFileWithHttpInfo}{\code{FakeApi$FakeDataFileWithHttpInfo()}} +\item \href{#method-FakeApi-clone}{\code{FakeApi$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-FakeApi-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new FakeApi. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{FakeApi$new(api_client)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{api_client}}{An instance of API client.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-FakeApi-FakeDataFile}{}}} +\subsection{Method \code{FakeDataFile()}}{ +test data_file to ensure it's escaped correctly +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{FakeApi$FakeDataFile(dummy, var_data_file = NULL, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{dummy}}{dummy required parameter} + +\item{\code{var_data_file}}{(optional) header data file} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +User +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-FakeApi-FakeDataFileWithHttpInfo}{}}} +\subsection{Method \code{FakeDataFileWithHttpInfo()}}{ +test data_file to ensure it's escaped correctly +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{FakeApi$FakeDataFileWithHttpInfo( + dummy, + var_data_file = NULL, + data_file = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{dummy}}{dummy required parameter} + +\item{\code{var_data_file}}{(optional) header data file} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (User) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-FakeApi-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{FakeApi$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/ModelApiResponse.Rd b/samples/client/petstore/R-httr2/man/ModelApiResponse.Rd new file mode 100644 index 0000000000..75d2ac0bfa --- /dev/null +++ b/samples/client/petstore/R-httr2/man/ModelApiResponse.Rd @@ -0,0 +1,181 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/model_api_response.R +\docType{class} +\name{ModelApiResponse} +\alias{ModelApiResponse} +\title{ModelApiResponse} +\format{ +An \code{R6Class} generator object +} +\description{ +ModelApiResponse Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{code}}{integer [optional]} + +\item{\code{type}}{character [optional]} + +\item{\code{message}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-ModelApiResponse-new}{\code{ModelApiResponse$new()}} +\item \href{#method-ModelApiResponse-toJSON}{\code{ModelApiResponse$toJSON()}} +\item \href{#method-ModelApiResponse-fromJSON}{\code{ModelApiResponse$fromJSON()}} +\item \href{#method-ModelApiResponse-toJSONString}{\code{ModelApiResponse$toJSONString()}} +\item \href{#method-ModelApiResponse-fromJSONString}{\code{ModelApiResponse$fromJSONString()}} +\item \href{#method-ModelApiResponse-validateJSON}{\code{ModelApiResponse$validateJSON()}} +\item \href{#method-ModelApiResponse-toString}{\code{ModelApiResponse$toString()}} +\item \href{#method-ModelApiResponse-clone}{\code{ModelApiResponse$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ModelApiResponse-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new ModelApiResponse class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ModelApiResponse$new(code = NULL, type = NULL, message = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{code}}{code} + +\item{\code{type}}{type} + +\item{\code{message}}{message} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ModelApiResponse-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ModelApiResponse$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +ModelApiResponse in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ModelApiResponse-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of ModelApiResponse +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ModelApiResponse$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of ModelApiResponse +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ModelApiResponse-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ModelApiResponse$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +ModelApiResponse in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ModelApiResponse-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of ModelApiResponse +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ModelApiResponse$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of ModelApiResponse +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ModelApiResponse-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to ModelApiResponse and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ModelApiResponse$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ModelApiResponse-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ModelApiResponse$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of ModelApiResponse +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-ModelApiResponse-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{ModelApiResponse$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/NestedOneOf.Rd b/samples/client/petstore/R-httr2/man/NestedOneOf.Rd new file mode 100644 index 0000000000..678c1edd8d --- /dev/null +++ b/samples/client/petstore/R-httr2/man/NestedOneOf.Rd @@ -0,0 +1,177 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/nested_one_of.R +\docType{class} +\name{NestedOneOf} +\alias{NestedOneOf} +\title{NestedOneOf} +\format{ +An \code{R6Class} generator object +} +\description{ +NestedOneOf Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{size}}{integer [optional]} + +\item{\code{nested_pig}}{\link{Pig} [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-NestedOneOf-new}{\code{NestedOneOf$new()}} +\item \href{#method-NestedOneOf-toJSON}{\code{NestedOneOf$toJSON()}} +\item \href{#method-NestedOneOf-fromJSON}{\code{NestedOneOf$fromJSON()}} +\item \href{#method-NestedOneOf-toJSONString}{\code{NestedOneOf$toJSONString()}} +\item \href{#method-NestedOneOf-fromJSONString}{\code{NestedOneOf$fromJSONString()}} +\item \href{#method-NestedOneOf-validateJSON}{\code{NestedOneOf$validateJSON()}} +\item \href{#method-NestedOneOf-toString}{\code{NestedOneOf$toString()}} +\item \href{#method-NestedOneOf-clone}{\code{NestedOneOf$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-NestedOneOf-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new NestedOneOf class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{NestedOneOf$new(size = NULL, nested_pig = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{size}}{size} + +\item{\code{nested_pig}}{nested_pig} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-NestedOneOf-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{NestedOneOf$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +NestedOneOf in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-NestedOneOf-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of NestedOneOf +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{NestedOneOf$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of NestedOneOf +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-NestedOneOf-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{NestedOneOf$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +NestedOneOf in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-NestedOneOf-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of NestedOneOf +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{NestedOneOf$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of NestedOneOf +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-NestedOneOf-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to NestedOneOf and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{NestedOneOf$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-NestedOneOf-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{NestedOneOf$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of NestedOneOf +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-NestedOneOf-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{NestedOneOf$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/Order.Rd b/samples/client/petstore/R-httr2/man/Order.Rd new file mode 100644 index 0000000000..951c51be02 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/Order.Rd @@ -0,0 +1,201 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/order.R +\docType{class} +\name{Order} +\alias{Order} +\title{Order} +\format{ +An \code{R6Class} generator object +} +\description{ +Order Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{integer [optional]} + +\item{\code{petId}}{integer [optional]} + +\item{\code{quantity}}{integer [optional]} + +\item{\code{shipDate}}{character [optional]} + +\item{\code{status}}{character [optional]} + +\item{\code{complete}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Order-new}{\code{Order$new()}} +\item \href{#method-Order-toJSON}{\code{Order$toJSON()}} +\item \href{#method-Order-fromJSON}{\code{Order$fromJSON()}} +\item \href{#method-Order-toJSONString}{\code{Order$toJSONString()}} +\item \href{#method-Order-fromJSONString}{\code{Order$fromJSONString()}} +\item \href{#method-Order-validateJSON}{\code{Order$validateJSON()}} +\item \href{#method-Order-toString}{\code{Order$toString()}} +\item \href{#method-Order-clone}{\code{Order$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Order-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new Order class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Order$new( + id = NULL, + petId = NULL, + quantity = NULL, + shipDate = NULL, + status = NULL, + complete = FALSE, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{id} + +\item{\code{petId}}{petId} + +\item{\code{quantity}}{quantity} + +\item{\code{shipDate}}{shipDate} + +\item{\code{status}}{Order Status} + +\item{\code{complete}}{complete. Default to FALSE.} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Order-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Order$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Order in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Order-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of Order +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Order$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Order +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Order-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Order$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Order in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Order-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of Order +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Order$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Order +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Order-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to Order and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Order$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Order-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Order$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of Order +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Order-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Order$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/Pet.Rd b/samples/client/petstore/R-httr2/man/Pet.Rd new file mode 100644 index 0000000000..73e0a9cc08 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/Pet.Rd @@ -0,0 +1,201 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pet.R +\docType{class} +\name{Pet} +\alias{Pet} +\title{Pet} +\format{ +An \code{R6Class} generator object +} +\description{ +Pet Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{integer [optional]} + +\item{\code{category}}{\link{Category} [optional]} + +\item{\code{name}}{character} + +\item{\code{photoUrls}}{list( character )} + +\item{\code{tags}}{list( \link{Tag} ) [optional]} + +\item{\code{status}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Pet-new}{\code{Pet$new()}} +\item \href{#method-Pet-toJSON}{\code{Pet$toJSON()}} +\item \href{#method-Pet-fromJSON}{\code{Pet$fromJSON()}} +\item \href{#method-Pet-toJSONString}{\code{Pet$toJSONString()}} +\item \href{#method-Pet-fromJSONString}{\code{Pet$fromJSONString()}} +\item \href{#method-Pet-validateJSON}{\code{Pet$validateJSON()}} +\item \href{#method-Pet-toString}{\code{Pet$toString()}} +\item \href{#method-Pet-clone}{\code{Pet$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pet-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new Pet class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pet$new( + name, + photoUrls, + id = NULL, + category = NULL, + tags = NULL, + status = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{name}}{name} + +\item{\code{photoUrls}}{photoUrls} + +\item{\code{id}}{id} + +\item{\code{category}}{category} + +\item{\code{tags}}{tags} + +\item{\code{status}}{pet status in the store} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pet-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pet$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Pet in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pet-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of Pet +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pet$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Pet +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pet-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pet$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Pet in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pet-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of Pet +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pet$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Pet +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pet-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to Pet and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pet$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pet-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pet$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of Pet +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pet-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pet$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/PetApi.Rd b/samples/client/petstore/R-httr2/man/PetApi.Rd new file mode 100644 index 0000000000..bf4827fbde --- /dev/null +++ b/samples/client/petstore/R-httr2/man/PetApi.Rd @@ -0,0 +1,1055 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pet_api.R +\docType{class} +\name{PetApi} +\alias{PetApi} +\title{Pet operations} +\format{ +An \code{R6Class} generator object +} +\description{ +petstore.Pet +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Methods}{ + +\describe{ +\strong{ AddPet } \emph{ Add a new pet to the store } + + +\itemize{ +\item \emph{ @param } pet \link{Pet} +\item \emph{ @returnType } \link{Pet} \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : Pet +\item response headers : + +\tabular{ll}{ +} +\item status code : 405 | Invalid input + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ DeletePet } \emph{ Deletes a pet } + + +\itemize{ +\item \emph{ @param } pet_id integer +\item \emph{ @param } api_key character + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 400 | Invalid pet value + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ FindPetsByStatus } \emph{ Finds Pets by status } +Multiple status values can be provided with comma separated strings + +\itemize{ +\item \emph{ @param } status Enum < [available, pending, sold] > +\item \emph{ @returnType } list( \link{Pet} ) \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : array[Pet] +\item response headers : + +\tabular{ll}{ +} +\item status code : 400 | Invalid status value + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ FindPetsByTags } \emph{ Finds Pets by tags } +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +\itemize{ +\item \emph{ @param } tags list( character ) +\item \emph{ @returnType } list( \link{Pet} ) \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : array[Pet] +\item response headers : + +\tabular{ll}{ +} +\item status code : 400 | Invalid tag value + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ GetPetById } \emph{ Find pet by ID } +Returns a single pet + +\itemize{ +\item \emph{ @param } pet_id integer +\item \emph{ @returnType } \link{Pet} \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : Pet +\item response headers : + +\tabular{ll}{ +} +\item status code : 400 | Invalid ID supplied + + +\item response headers : + +\tabular{ll}{ +} +\item status code : 404 | Pet not found + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ GetPetByIdStreaming } \emph{ Find pet by ID (streaming) } +Returns a single pet + +\itemize{ +\item \emph{ @param } pet_id integer +\item \emph{ @returnType } \link{Pet} \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : Pet +\item response headers : + +\tabular{ll}{ +} +\item status code : 400 | Invalid ID supplied + + +\item response headers : + +\tabular{ll}{ +} +\item status code : 404 | Pet not found + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ UpdatePet } \emph{ Update an existing pet } + + +\itemize{ +\item \emph{ @param } pet \link{Pet} +\item \emph{ @returnType } \link{Pet} \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : Pet +\item response headers : + +\tabular{ll}{ +} +\item status code : 400 | Invalid ID supplied + + +\item response headers : + +\tabular{ll}{ +} +\item status code : 404 | Pet not found + + +\item response headers : + +\tabular{ll}{ +} +\item status code : 405 | Validation exception + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ UpdatePetWithForm } \emph{ Updates a pet in the store with form data } + + +\itemize{ +\item \emph{ @param } pet_id integer +\item \emph{ @param } name character +\item \emph{ @param } status character + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 405 | Invalid input + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ UploadFile } \emph{ uploads an image } + + +\itemize{ +\item \emph{ @param } pet_id integer +\item \emph{ @param } additional_metadata character +\item \emph{ @param } file data.frame +\item \emph{ @returnType } \link{ModelApiResponse} \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : ModelApiResponse +\item response headers : + +\tabular{ll}{ +} +} + +} +} + +\examples{ +\dontrun{ +#################### AddPet #################### + +library(petstore) +var.pet <- Pet$new() # Pet | Pet object that needs to be added to the store + +#Add a new pet to the store +api.instance <- PetApi$new() + +# Configure OAuth2 access token for authorization: petstore_auth +api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; + +result <- tryCatch( + api.instance$AddPet(var.pet), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### DeletePet #################### + +library(petstore) +var.pet_id <- 56 # integer | Pet id to delete +var.api_key <- 'api_key_example' # character | + +#Deletes a pet +api.instance <- PetApi$new() + +# Configure OAuth2 access token for authorization: petstore_auth +api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; + +result <- tryCatch( + api.instance$DeletePet(var.pet_id, api_key=var.api_key), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### FindPetsByStatus #################### + +library(petstore) +var.status <- ['status_example'] # array[character] | Status values that need to be considered for filter + +#Finds Pets by status +api.instance <- PetApi$new() + +# Configure OAuth2 access token for authorization: petstore_auth +api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; + +result <- tryCatch( + api.instance$FindPetsByStatus(var.status), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### FindPetsByTags #################### + +library(petstore) +var.tags <- ['tags_example'] # array[character] | Tags to filter by + +#Finds Pets by tags +api.instance <- PetApi$new() + +# Configure OAuth2 access token for authorization: petstore_auth +api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; + +result <- tryCatch( + api.instance$FindPetsByTags(var.tags), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### GetPetById #################### + +library(petstore) +var.pet_id <- 56 # integer | ID of pet to return + +#Find pet by ID +api.instance <- PetApi$new() + +#Configure API key authorization: api_key +api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; + +result <- tryCatch( + api.instance$GetPetById(var.pet_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### GetPetByIdStreaming #################### + +library(petstore) +var.pet_id <- 56 # integer | ID of pet to return + +#Find pet by ID (streaming) +api.instance <- PetApi$new() + +#Configure API key authorization: api_key +api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; + +result <- tryCatch( + api.instance$GetPetByIdStreaming(var.pet_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### UpdatePet #################### + +library(petstore) +var.pet <- Pet$new() # Pet | Pet object that needs to be added to the store + +#Update an existing pet +api.instance <- PetApi$new() + +# Configure OAuth2 access token for authorization: petstore_auth +api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; + +result <- tryCatch( + api.instance$UpdatePet(var.pet), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### UpdatePetWithForm #################### + +library(petstore) +var.pet_id <- 56 # integer | ID of pet that needs to be updated +var.name <- 'name_example' # character | Updated name of the pet +var.status <- 'status_example' # character | Updated status of the pet + +#Updates a pet in the store with form data +api.instance <- PetApi$new() + +# Configure OAuth2 access token for authorization: petstore_auth +api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; + +result <- tryCatch( + api.instance$UpdatePetWithForm(var.pet_id, name=var.name, status=var.status), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### UploadFile #################### + +library(petstore) +var.pet_id <- 56 # integer | ID of pet to update +var.additional_metadata <- 'additional_metadata_example' # character | Additional data to pass to server +var.file <- File.new('/path/to/file') # data.frame | file to upload + +#uploads an image +api.instance <- PetApi$new() + +# Configure OAuth2 access token for authorization: petstore_auth +api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; + +result <- tryCatch( + api.instance$UploadFile(var.pet_id, additional_metadata=var.additional_metadata, file=var.file), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +} +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{api_client}}{Handles the client-server communication.} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-PetApi-new}{\code{PetApi$new()}} +\item \href{#method-PetApi-AddPet}{\code{PetApi$AddPet()}} +\item \href{#method-PetApi-AddPetWithHttpInfo}{\code{PetApi$AddPetWithHttpInfo()}} +\item \href{#method-PetApi-DeletePet}{\code{PetApi$DeletePet()}} +\item \href{#method-PetApi-DeletePetWithHttpInfo}{\code{PetApi$DeletePetWithHttpInfo()}} +\item \href{#method-PetApi-FindPetsByStatus}{\code{PetApi$FindPetsByStatus()}} +\item \href{#method-PetApi-FindPetsByStatusWithHttpInfo}{\code{PetApi$FindPetsByStatusWithHttpInfo()}} +\item \href{#method-PetApi-FindPetsByTags}{\code{PetApi$FindPetsByTags()}} +\item \href{#method-PetApi-FindPetsByTagsWithHttpInfo}{\code{PetApi$FindPetsByTagsWithHttpInfo()}} +\item \href{#method-PetApi-GetPetById}{\code{PetApi$GetPetById()}} +\item \href{#method-PetApi-GetPetByIdWithHttpInfo}{\code{PetApi$GetPetByIdWithHttpInfo()}} +\item \href{#method-PetApi-GetPetByIdStreaming}{\code{PetApi$GetPetByIdStreaming()}} +\item \href{#method-PetApi-GetPetByIdStreamingWithHttpInfo}{\code{PetApi$GetPetByIdStreamingWithHttpInfo()}} +\item \href{#method-PetApi-UpdatePet}{\code{PetApi$UpdatePet()}} +\item \href{#method-PetApi-UpdatePetWithHttpInfo}{\code{PetApi$UpdatePetWithHttpInfo()}} +\item \href{#method-PetApi-UpdatePetWithForm}{\code{PetApi$UpdatePetWithForm()}} +\item \href{#method-PetApi-UpdatePetWithFormWithHttpInfo}{\code{PetApi$UpdatePetWithFormWithHttpInfo()}} +\item \href{#method-PetApi-UploadFile}{\code{PetApi$UploadFile()}} +\item \href{#method-PetApi-UploadFileWithHttpInfo}{\code{PetApi$UploadFileWithHttpInfo()}} +\item \href{#method-PetApi-clone}{\code{PetApi$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new PetApi. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$new(api_client)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{api_client}}{An instance of API client.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-AddPet}{}}} +\subsection{Method \code{AddPet()}}{ +Add a new pet to the store +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$AddPet(pet, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet}}{Pet object that needs to be added to the store} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +Pet +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-AddPetWithHttpInfo}{}}} +\subsection{Method \code{AddPetWithHttpInfo()}}{ +Add a new pet to the store +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$AddPetWithHttpInfo(pet, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet}}{Pet object that needs to be added to the store} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (Pet) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-DeletePet}{}}} +\subsection{Method \code{DeletePet()}}{ +Deletes a pet +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$DeletePet(pet_id, api_key = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{Pet id to delete} + +\item{\code{api_key}}{(optional)} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +void +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-DeletePetWithHttpInfo}{}}} +\subsection{Method \code{DeletePetWithHttpInfo()}}{ +Deletes a pet +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$DeletePetWithHttpInfo(pet_id, api_key = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{Pet id to delete} + +\item{\code{api_key}}{(optional)} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (void) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-FindPetsByStatus}{}}} +\subsection{Method \code{FindPetsByStatus()}}{ +Finds Pets by status +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$FindPetsByStatus(status, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{status}}{Status values that need to be considered for filter} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +array[Pet] +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-FindPetsByStatusWithHttpInfo}{}}} +\subsection{Method \code{FindPetsByStatusWithHttpInfo()}}{ +Finds Pets by status +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$FindPetsByStatusWithHttpInfo(status, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{status}}{Status values that need to be considered for filter} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (array[Pet]) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-FindPetsByTags}{}}} +\subsection{Method \code{FindPetsByTags()}}{ +Finds Pets by tags +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$FindPetsByTags(tags, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{tags}}{Tags to filter by} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +array[Pet] +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-FindPetsByTagsWithHttpInfo}{}}} +\subsection{Method \code{FindPetsByTagsWithHttpInfo()}}{ +Finds Pets by tags +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$FindPetsByTagsWithHttpInfo(tags, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{tags}}{Tags to filter by} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (array[Pet]) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-GetPetById}{}}} +\subsection{Method \code{GetPetById()}}{ +Find pet by ID +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$GetPetById(pet_id, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{ID of pet to return} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +Pet +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-GetPetByIdWithHttpInfo}{}}} +\subsection{Method \code{GetPetByIdWithHttpInfo()}}{ +Find pet by ID +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$GetPetByIdWithHttpInfo(pet_id, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{ID of pet to return} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (Pet) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-GetPetByIdStreaming}{}}} +\subsection{Method \code{GetPetByIdStreaming()}}{ +Find pet by ID (streaming) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$GetPetByIdStreaming( + pet_id, + stream_callback = NULL, + data_file = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{ID of pet to return} + +\item{\code{stream_callback}}{(optional) callback function to process the data stream} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +Pet +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-GetPetByIdStreamingWithHttpInfo}{}}} +\subsection{Method \code{GetPetByIdStreamingWithHttpInfo()}}{ +Find pet by ID (streaming) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$GetPetByIdStreamingWithHttpInfo( + pet_id, + stream_callback = NULL, + data_file = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{ID of pet to return} + +\item{\code{stream_callback}}{(optional) callback function to process the data stream} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (Pet) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-UpdatePet}{}}} +\subsection{Method \code{UpdatePet()}}{ +Update an existing pet +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$UpdatePet(pet, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet}}{Pet object that needs to be added to the store} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +Pet +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-UpdatePetWithHttpInfo}{}}} +\subsection{Method \code{UpdatePetWithHttpInfo()}}{ +Update an existing pet +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$UpdatePetWithHttpInfo(pet, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet}}{Pet object that needs to be added to the store} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (Pet) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-UpdatePetWithForm}{}}} +\subsection{Method \code{UpdatePetWithForm()}}{ +Updates a pet in the store with form data +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$UpdatePetWithForm(pet_id, name = NULL, status = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{ID of pet that needs to be updated} + +\item{\code{name}}{(optional) Updated name of the pet} + +\item{\code{status}}{(optional) Updated status of the pet} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +void +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-UpdatePetWithFormWithHttpInfo}{}}} +\subsection{Method \code{UpdatePetWithFormWithHttpInfo()}}{ +Updates a pet in the store with form data +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$UpdatePetWithFormWithHttpInfo(pet_id, name = NULL, status = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{ID of pet that needs to be updated} + +\item{\code{name}}{(optional) Updated name of the pet} + +\item{\code{status}}{(optional) Updated status of the pet} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (void) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-UploadFile}{}}} +\subsection{Method \code{UploadFile()}}{ +uploads an image +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$UploadFile( + pet_id, + additional_metadata = NULL, + file = NULL, + data_file = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{ID of pet to update} + +\item{\code{additional_metadata}}{(optional) Additional data to pass to server} + +\item{\code{file}}{(optional) file to upload} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +ModelApiResponse +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-UploadFileWithHttpInfo}{}}} +\subsection{Method \code{UploadFileWithHttpInfo()}}{ +uploads an image +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$UploadFileWithHttpInfo( + pet_id, + additional_metadata = NULL, + file = NULL, + data_file = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{pet_id}}{ID of pet to update} + +\item{\code{additional_metadata}}{(optional) Additional data to pass to server} + +\item{\code{file}}{(optional) file to upload} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (ModelApiResponse) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-PetApi-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{PetApi$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/Pig.Rd b/samples/client/petstore/R-httr2/man/Pig.Rd new file mode 100644 index 0000000000..6006f995a3 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/Pig.Rd @@ -0,0 +1,156 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pig.R +\docType{class} +\name{Pig} +\alias{Pig} +\title{Pig} +\format{ +An \code{R6Class} generator object +} +\description{ +Pig Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{actual_instance}}{the object stored in this instance.} + +\item{\code{actual_type}}{the type of the object stored in this instance.} + +\item{\code{one_of}}{a list of object types defined in the oneOf schema. +Initialize a new Pig.} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Pig-new}{\code{Pig$new()}} +\item \href{#method-Pig-fromJSON}{\code{Pig$fromJSON()}} +\item \href{#method-Pig-toJSONString}{\code{Pig$toJSONString()}} +\item \href{#method-Pig-toJSON}{\code{Pig$toJSON()}} +\item \href{#method-Pig-validateJSON}{\code{Pig$validateJSON()}} +\item \href{#method-Pig-toString}{\code{Pig$toString()}} +\item \href{#method-Pig-clone}{\code{Pig$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pig-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new Pig. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pig$new(instance = NULL)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{instance}}{an instance of the object defined in the oneOf schemas: "BasquePig", "DanishPig"} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pig-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of Pig. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pig$fromJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{The input JSON.} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +An instance of Pig. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pig-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +Serialize Pig to JSON string. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pig$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +JSON string representation of the Pig. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pig-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +Serialize Pig to JSON. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pig$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +JSON representation of the Pig. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pig-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate the input JSON with respect to Pig and +throw exception if invalid. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pig$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{The input JSON.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pig-toString}{}}} +\subsection{Method \code{toString()}}{ +Returns the string representation of the instance. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pig$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +The string representation of the instance. +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Pig-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Pig$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/Special.Rd b/samples/client/petstore/R-httr2/man/Special.Rd new file mode 100644 index 0000000000..8c42418b09 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/Special.Rd @@ -0,0 +1,201 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/special.R +\docType{class} +\name{Special} +\alias{Special} +\title{Special} +\format{ +An \code{R6Class} generator object +} +\description{ +Special Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{item_self}}{integer [optional]} + +\item{\code{item_private}}{character [optional]} + +\item{\code{item_super}}{character [optional]} + +\item{\code{123_number}}{character [optional]} + +\item{\code{array[test]}}{character [optional]} + +\item{\code{empty_string}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Special-new}{\code{Special$new()}} +\item \href{#method-Special-toJSON}{\code{Special$toJSON()}} +\item \href{#method-Special-fromJSON}{\code{Special$fromJSON()}} +\item \href{#method-Special-toJSONString}{\code{Special$toJSONString()}} +\item \href{#method-Special-fromJSONString}{\code{Special$fromJSONString()}} +\item \href{#method-Special-validateJSON}{\code{Special$validateJSON()}} +\item \href{#method-Special-toString}{\code{Special$toString()}} +\item \href{#method-Special-clone}{\code{Special$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Special-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new Special class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Special$new( + item_self = NULL, + item_private = NULL, + item_super = NULL, + `123_number` = NULL, + `array[test]` = NULL, + empty_string = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{item_self}}{item_self} + +\item{\code{item_private}}{item_private} + +\item{\code{item_super}}{item_super} + +\item{\code{123_number}}{123_number} + +\item{\code{array[test]}}{array[test]} + +\item{\code{empty_string}}{empty_string} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Special-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Special$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Special in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Special-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of Special +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Special$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Special +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Special-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Special$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Special in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Special-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of Special +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Special$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Special +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Special-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to Special and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Special$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Special-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Special$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of Special +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Special-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Special$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/StoreApi.Rd b/samples/client/petstore/R-httr2/man/StoreApi.Rd new file mode 100644 index 0000000000..2423e1819e --- /dev/null +++ b/samples/client/petstore/R-httr2/man/StoreApi.Rd @@ -0,0 +1,468 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/store_api.R +\docType{class} +\name{StoreApi} +\alias{StoreApi} +\title{Store operations} +\format{ +An \code{R6Class} generator object +} +\description{ +petstore.Store +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Methods}{ + +\describe{ +\strong{ DeleteOrder } \emph{ Delete purchase order by ID } +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +\itemize{ +\item \emph{ @param } order_id character + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 400 | Invalid ID supplied + + +\item response headers : + +\tabular{ll}{ +} +\item status code : 404 | Order not found + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ GetInventory } \emph{ Returns pet inventories by status } +Returns a map of status codes to quantities + +\itemize{ + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : map(integer) +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ GetOrderById } \emph{ Find purchase order by ID } +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +\itemize{ +\item \emph{ @param } order_id integer +\item \emph{ @returnType } \link{Order} \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : Order +\item response headers : + +\tabular{ll}{ +} +\item status code : 400 | Invalid ID supplied + + +\item response headers : + +\tabular{ll}{ +} +\item status code : 404 | Order not found + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ PlaceOrder } \emph{ Place an order for a pet } + + +\itemize{ +\item \emph{ @param } order \link{Order} +\item \emph{ @returnType } \link{Order} \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : Order +\item response headers : + +\tabular{ll}{ +} +\item status code : 400 | Invalid Order + + +\item response headers : + +\tabular{ll}{ +} +} + +} +} + +\examples{ +\dontrun{ +#################### DeleteOrder #################### + +library(petstore) +var.order_id <- 'order_id_example' # character | ID of the order that needs to be deleted + +#Delete purchase order by ID +api.instance <- StoreApi$new() + +result <- tryCatch( + api.instance$DeleteOrder(var.order_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### GetInventory #################### + +library(petstore) + +#Returns pet inventories by status +api.instance <- StoreApi$new() + +#Configure API key authorization: api_key +api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; + +result <- tryCatch( + api.instance$GetInventory(), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### GetOrderById #################### + +library(petstore) +var.order_id <- 56 # integer | ID of pet that needs to be fetched + +#Find purchase order by ID +api.instance <- StoreApi$new() + +result <- tryCatch( + api.instance$GetOrderById(var.order_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### PlaceOrder #################### + +library(petstore) +var.order <- Order$new() # Order | order placed for purchasing the pet + +#Place an order for a pet +api.instance <- StoreApi$new() + +result <- tryCatch( + api.instance$PlaceOrder(var.order), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +} +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{api_client}}{Handles the client-server communication.} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-StoreApi-new}{\code{StoreApi$new()}} +\item \href{#method-StoreApi-DeleteOrder}{\code{StoreApi$DeleteOrder()}} +\item \href{#method-StoreApi-DeleteOrderWithHttpInfo}{\code{StoreApi$DeleteOrderWithHttpInfo()}} +\item \href{#method-StoreApi-GetInventory}{\code{StoreApi$GetInventory()}} +\item \href{#method-StoreApi-GetInventoryWithHttpInfo}{\code{StoreApi$GetInventoryWithHttpInfo()}} +\item \href{#method-StoreApi-GetOrderById}{\code{StoreApi$GetOrderById()}} +\item \href{#method-StoreApi-GetOrderByIdWithHttpInfo}{\code{StoreApi$GetOrderByIdWithHttpInfo()}} +\item \href{#method-StoreApi-PlaceOrder}{\code{StoreApi$PlaceOrder()}} +\item \href{#method-StoreApi-PlaceOrderWithHttpInfo}{\code{StoreApi$PlaceOrderWithHttpInfo()}} +\item \href{#method-StoreApi-clone}{\code{StoreApi$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new StoreApi. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$new(api_client)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{api_client}}{An instance of API client.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-DeleteOrder}{}}} +\subsection{Method \code{DeleteOrder()}}{ +Delete purchase order by ID +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$DeleteOrder(order_id, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{order_id}}{ID of the order that needs to be deleted} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +void +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-DeleteOrderWithHttpInfo}{}}} +\subsection{Method \code{DeleteOrderWithHttpInfo()}}{ +Delete purchase order by ID +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$DeleteOrderWithHttpInfo(order_id, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{order_id}}{ID of the order that needs to be deleted} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (void) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-GetInventory}{}}} +\subsection{Method \code{GetInventory()}}{ +Returns pet inventories by status +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$GetInventory(data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +map(integer) +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-GetInventoryWithHttpInfo}{}}} +\subsection{Method \code{GetInventoryWithHttpInfo()}}{ +Returns pet inventories by status +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$GetInventoryWithHttpInfo(data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (map(integer)) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-GetOrderById}{}}} +\subsection{Method \code{GetOrderById()}}{ +Find purchase order by ID +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$GetOrderById(order_id, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{order_id}}{ID of pet that needs to be fetched} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +Order +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-GetOrderByIdWithHttpInfo}{}}} +\subsection{Method \code{GetOrderByIdWithHttpInfo()}}{ +Find purchase order by ID +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$GetOrderByIdWithHttpInfo(order_id, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{order_id}}{ID of pet that needs to be fetched} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (Order) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-PlaceOrder}{}}} +\subsection{Method \code{PlaceOrder()}}{ +Place an order for a pet +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$PlaceOrder(order, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{order}}{order placed for purchasing the pet} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +Order +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-PlaceOrderWithHttpInfo}{}}} +\subsection{Method \code{PlaceOrderWithHttpInfo()}}{ +Place an order for a pet +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$PlaceOrderWithHttpInfo(order, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{order}}{order placed for purchasing the pet} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (Order) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-StoreApi-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{StoreApi$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/Tag.Rd b/samples/client/petstore/R-httr2/man/Tag.Rd new file mode 100644 index 0000000000..2aea0440ef --- /dev/null +++ b/samples/client/petstore/R-httr2/man/Tag.Rd @@ -0,0 +1,177 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/tag.R +\docType{class} +\name{Tag} +\alias{Tag} +\title{Tag} +\format{ +An \code{R6Class} generator object +} +\description{ +Tag Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{integer [optional]} + +\item{\code{name}}{character [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Tag-new}{\code{Tag$new()}} +\item \href{#method-Tag-toJSON}{\code{Tag$toJSON()}} +\item \href{#method-Tag-fromJSON}{\code{Tag$fromJSON()}} +\item \href{#method-Tag-toJSONString}{\code{Tag$toJSONString()}} +\item \href{#method-Tag-fromJSONString}{\code{Tag$fromJSONString()}} +\item \href{#method-Tag-validateJSON}{\code{Tag$validateJSON()}} +\item \href{#method-Tag-toString}{\code{Tag$toString()}} +\item \href{#method-Tag-clone}{\code{Tag$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Tag-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new Tag class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Tag$new(id = NULL, name = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{id} + +\item{\code{name}}{name} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Tag-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Tag$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Tag in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Tag-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of Tag +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Tag$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Tag +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Tag-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Tag$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +Tag in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Tag-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of Tag +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Tag$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of Tag +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Tag-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to Tag and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Tag$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Tag-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Tag$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of Tag +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Tag-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{Tag$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/UpdatePetRequest.Rd b/samples/client/petstore/R-httr2/man/UpdatePetRequest.Rd new file mode 100644 index 0000000000..8cc115d284 --- /dev/null +++ b/samples/client/petstore/R-httr2/man/UpdatePetRequest.Rd @@ -0,0 +1,177 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/update_pet_request.R +\docType{class} +\name{UpdatePetRequest} +\alias{UpdatePetRequest} +\title{UpdatePetRequest} +\format{ +An \code{R6Class} generator object +} +\description{ +UpdatePetRequest Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{jsonData}}{\link{Pet} [optional]} + +\item{\code{binaryDataN2Information}}{data.frame [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-UpdatePetRequest-new}{\code{UpdatePetRequest$new()}} +\item \href{#method-UpdatePetRequest-toJSON}{\code{UpdatePetRequest$toJSON()}} +\item \href{#method-UpdatePetRequest-fromJSON}{\code{UpdatePetRequest$fromJSON()}} +\item \href{#method-UpdatePetRequest-toJSONString}{\code{UpdatePetRequest$toJSONString()}} +\item \href{#method-UpdatePetRequest-fromJSONString}{\code{UpdatePetRequest$fromJSONString()}} +\item \href{#method-UpdatePetRequest-validateJSON}{\code{UpdatePetRequest$validateJSON()}} +\item \href{#method-UpdatePetRequest-toString}{\code{UpdatePetRequest$toString()}} +\item \href{#method-UpdatePetRequest-clone}{\code{UpdatePetRequest$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UpdatePetRequest-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new UpdatePetRequest class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UpdatePetRequest$new(jsonData = NULL, binaryDataN2Information = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{jsonData}}{jsonData} + +\item{\code{binaryDataN2Information}}{binaryDataN2Information} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UpdatePetRequest-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UpdatePetRequest$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +UpdatePetRequest in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UpdatePetRequest-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of UpdatePetRequest +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UpdatePetRequest$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of UpdatePetRequest +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UpdatePetRequest-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UpdatePetRequest$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +UpdatePetRequest in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UpdatePetRequest-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of UpdatePetRequest +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UpdatePetRequest$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of UpdatePetRequest +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UpdatePetRequest-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to UpdatePetRequest and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UpdatePetRequest$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UpdatePetRequest-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UpdatePetRequest$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of UpdatePetRequest +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UpdatePetRequest-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UpdatePetRequest$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/User.Rd b/samples/client/petstore/R-httr2/man/User.Rd new file mode 100644 index 0000000000..3646b8d8aa --- /dev/null +++ b/samples/client/petstore/R-httr2/man/User.Rd @@ -0,0 +1,211 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/user.R +\docType{class} +\name{User} +\alias{User} +\title{User} +\format{ +An \code{R6Class} generator object +} +\description{ +User Class +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{integer [optional]} + +\item{\code{username}}{character [optional]} + +\item{\code{firstName}}{character [optional]} + +\item{\code{lastName}}{character [optional]} + +\item{\code{email}}{character [optional]} + +\item{\code{password}}{character [optional]} + +\item{\code{phone}}{character [optional]} + +\item{\code{userStatus}}{integer [optional]} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-User-new}{\code{User$new()}} +\item \href{#method-User-toJSON}{\code{User$toJSON()}} +\item \href{#method-User-fromJSON}{\code{User$fromJSON()}} +\item \href{#method-User-toJSONString}{\code{User$toJSONString()}} +\item \href{#method-User-fromJSONString}{\code{User$fromJSONString()}} +\item \href{#method-User-validateJSON}{\code{User$validateJSON()}} +\item \href{#method-User-toString}{\code{User$toString()}} +\item \href{#method-User-clone}{\code{User$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-User-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new User class. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{User$new( + id = NULL, + username = NULL, + firstName = NULL, + lastName = NULL, + email = NULL, + password = NULL, + phone = NULL, + userStatus = NULL, + ... +)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{id}}{id} + +\item{\code{username}}{username} + +\item{\code{firstName}}{firstName} + +\item{\code{lastName}}{lastName} + +\item{\code{email}}{email} + +\item{\code{password}}{password} + +\item{\code{phone}}{phone} + +\item{\code{userStatus}}{User Status} + +\item{\code{...}}{Other optional arguments.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-User-toJSON}{}}} +\subsection{Method \code{toJSON()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{User$toJSON()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +User in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-User-fromJSON}{}}} +\subsection{Method \code{fromJSON()}}{ +Deserialize JSON string into an instance of User +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{User$fromJSON(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of User +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-User-toJSONString}{}}} +\subsection{Method \code{toJSONString()}}{ +To JSON String +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{User$toJSONString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +User in JSON format +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-User-fromJSONString}{}}} +\subsection{Method \code{fromJSONString()}}{ +Deserialize JSON string into an instance of User +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{User$fromJSONString(input_json)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input_json}}{the JSON input} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +the instance of User +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-User-validateJSON}{}}} +\subsection{Method \code{validateJSON()}}{ +Validate JSON input with respect to User and throw an exception if invalid +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{User$validateJSON(input)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{input}}{the JSON input} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-User-toString}{}}} +\subsection{Method \code{toString()}}{ +To string (JSON format) +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{User$toString()}\if{html}{\out{
        }} +} + +\subsection{Returns}{ +String representation of User +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-User-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{User$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/man/UserApi.Rd b/samples/client/petstore/R-httr2/man/UserApi.Rd new file mode 100644 index 0000000000..aa33773d3a --- /dev/null +++ b/samples/client/petstore/R-httr2/man/UserApi.Rd @@ -0,0 +1,842 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/user_api.R +\docType{class} +\name{UserApi} +\alias{UserApi} +\title{User operations} +\format{ +An \code{R6Class} generator object +} +\description{ +petstore.User +} +\details{ +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. + +The version of the OpenAPI document: 1.0.0 +Generated by: https://openapi-generator.tech +} +\section{Methods}{ + +\describe{ +\strong{ CreateUser } \emph{ Create user } +This can only be done by the logged in user. + +\itemize{ +\item \emph{ @param } user \link{User} + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 0 | successful operation + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ CreateUsersWithArrayInput } \emph{ Creates list of users with given input array } + + +\itemize{ +\item \emph{ @param } user list( \link{User} ) + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 0 | successful operation + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ CreateUsersWithListInput } \emph{ Creates list of users with given input array } + + +\itemize{ +\item \emph{ @param } user list( \link{User} ) + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 0 | successful operation + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ DeleteUser } \emph{ Delete user } +This can only be done by the logged in user. + +\itemize{ +\item \emph{ @param } username character + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 400 | Invalid username supplied + + +\item response headers : + +\tabular{ll}{ +} +\item status code : 404 | User not found + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ GetUserByName } \emph{ Get user by user name } + + +\itemize{ +\item \emph{ @param } username character +\item \emph{ @returnType } \link{User} \cr + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : User +\item response headers : + +\tabular{ll}{ +} +\item status code : 400 | Invalid username supplied + + +\item response headers : + +\tabular{ll}{ +} +\item status code : 404 | User not found + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ LoginUser } \emph{ Logs user into the system } + + +\itemize{ +\item \emph{ @param } username character +\item \emph{ @param } password character + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 200 | successful operation + +\item return type : character +\item response headers : + +\tabular{ll}{ +Set-Cookie \tab Cookie authentication key for use with the `api_key` apiKey authentication. \cr +X-Rate-Limit \tab calls per hour allowed by the user \cr +X-Expires-After \tab date in UTC when token expires \cr +} +\item status code : 400 | Invalid username/password supplied + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ LogoutUser } \emph{ Logs out current logged in user session } + + +\itemize{ + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 0 | successful operation + + +\item response headers : + +\tabular{ll}{ +} +} + +\strong{ UpdateUser } \emph{ Updated user } +This can only be done by the logged in user. + +\itemize{ +\item \emph{ @param } username character +\item \emph{ @param } user \link{User} + +\item On encountering errors, an error of subclass ApiException will be thrown. + +\item status code : 400 | Invalid user supplied + + +\item response headers : + +\tabular{ll}{ +} +\item status code : 404 | User not found + + +\item response headers : + +\tabular{ll}{ +} +} + +} +} + +\examples{ +\dontrun{ +#################### CreateUser #################### + +library(petstore) +var.user <- User$new() # User | Created user object + +#Create user +api.instance <- UserApi$new() + +#Configure API key authorization: api_key +api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; + +result <- tryCatch( + api.instance$CreateUser(var.user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### CreateUsersWithArrayInput #################### + +library(petstore) +var.user <- [User$new()] # array[User] | List of user object + +#Creates list of users with given input array +api.instance <- UserApi$new() + +#Configure API key authorization: api_key +api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; + +result <- tryCatch( + api.instance$CreateUsersWithArrayInput(var.user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### CreateUsersWithListInput #################### + +library(petstore) +var.user <- [User$new()] # array[User] | List of user object + +#Creates list of users with given input array +api.instance <- UserApi$new() + +#Configure API key authorization: api_key +api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; + +result <- tryCatch( + api.instance$CreateUsersWithListInput(var.user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### DeleteUser #################### + +library(petstore) +var.username <- 'username_example' # character | The name that needs to be deleted + +#Delete user +api.instance <- UserApi$new() + +#Configure API key authorization: api_key +api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; + +result <- tryCatch( + api.instance$DeleteUser(var.username), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### GetUserByName #################### + +library(petstore) +var.username <- 'username_example' # character | The name that needs to be fetched. Use user1 for testing. + +#Get user by user name +api.instance <- UserApi$new() + +result <- tryCatch( + api.instance$GetUserByName(var.username), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### LoginUser #################### + +library(petstore) +var.username <- 'username_example' # character | The user name for login +var.password <- 'password_example' # character | The password for login in clear text + +#Logs user into the system +api.instance <- UserApi$new() + +result <- tryCatch( + api.instance$LoginUser(var.username, var.password), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# deserialized response object +response.object <- result$content +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### LogoutUser #################### + +library(petstore) + +#Logs out current logged in user session +api.instance <- UserApi$new() + +#Configure API key authorization: api_key +api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; + +result <- tryCatch( + api.instance$LogoutUser(), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +#################### UpdateUser #################### + +library(petstore) +var.username <- 'username_example' # character | name that need to be deleted +var.user <- User$new() # User | Updated user object + +#Updated user +api.instance <- UserApi$new() + +#Configure API key authorization: api_key +api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; + +result <- tryCatch( + api.instance$UpdateUser(var.username, var.user), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { +# response headers +response.headers <- result$response$headers +# response status code +response.status.code <- result$response$status_code +} + + +} +} +\section{Public fields}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{api_client}}{Handles the client-server communication.} +} +\if{html}{\out{
        }} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-UserApi-new}{\code{UserApi$new()}} +\item \href{#method-UserApi-CreateUser}{\code{UserApi$CreateUser()}} +\item \href{#method-UserApi-CreateUserWithHttpInfo}{\code{UserApi$CreateUserWithHttpInfo()}} +\item \href{#method-UserApi-CreateUsersWithArrayInput}{\code{UserApi$CreateUsersWithArrayInput()}} +\item \href{#method-UserApi-CreateUsersWithArrayInputWithHttpInfo}{\code{UserApi$CreateUsersWithArrayInputWithHttpInfo()}} +\item \href{#method-UserApi-CreateUsersWithListInput}{\code{UserApi$CreateUsersWithListInput()}} +\item \href{#method-UserApi-CreateUsersWithListInputWithHttpInfo}{\code{UserApi$CreateUsersWithListInputWithHttpInfo()}} +\item \href{#method-UserApi-DeleteUser}{\code{UserApi$DeleteUser()}} +\item \href{#method-UserApi-DeleteUserWithHttpInfo}{\code{UserApi$DeleteUserWithHttpInfo()}} +\item \href{#method-UserApi-GetUserByName}{\code{UserApi$GetUserByName()}} +\item \href{#method-UserApi-GetUserByNameWithHttpInfo}{\code{UserApi$GetUserByNameWithHttpInfo()}} +\item \href{#method-UserApi-LoginUser}{\code{UserApi$LoginUser()}} +\item \href{#method-UserApi-LoginUserWithHttpInfo}{\code{UserApi$LoginUserWithHttpInfo()}} +\item \href{#method-UserApi-LogoutUser}{\code{UserApi$LogoutUser()}} +\item \href{#method-UserApi-LogoutUserWithHttpInfo}{\code{UserApi$LogoutUserWithHttpInfo()}} +\item \href{#method-UserApi-UpdateUser}{\code{UserApi$UpdateUser()}} +\item \href{#method-UserApi-UpdateUserWithHttpInfo}{\code{UserApi$UpdateUserWithHttpInfo()}} +\item \href{#method-UserApi-clone}{\code{UserApi$clone()}} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-new}{}}} +\subsection{Method \code{new()}}{ +Initialize a new UserApi. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$new(api_client)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{api_client}}{An instance of API client.} +} +\if{html}{\out{
        }} +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-CreateUser}{}}} +\subsection{Method \code{CreateUser()}}{ +Create user +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$CreateUser(user, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{user}}{Created user object} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +void +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-CreateUserWithHttpInfo}{}}} +\subsection{Method \code{CreateUserWithHttpInfo()}}{ +Create user +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$CreateUserWithHttpInfo(user, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{user}}{Created user object} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (void) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-CreateUsersWithArrayInput}{}}} +\subsection{Method \code{CreateUsersWithArrayInput()}}{ +Creates list of users with given input array +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$CreateUsersWithArrayInput(user, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{user}}{List of user object} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +void +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-CreateUsersWithArrayInputWithHttpInfo}{}}} +\subsection{Method \code{CreateUsersWithArrayInputWithHttpInfo()}}{ +Creates list of users with given input array +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$CreateUsersWithArrayInputWithHttpInfo(user, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{user}}{List of user object} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (void) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-CreateUsersWithListInput}{}}} +\subsection{Method \code{CreateUsersWithListInput()}}{ +Creates list of users with given input array +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$CreateUsersWithListInput(user, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{user}}{List of user object} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +void +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-CreateUsersWithListInputWithHttpInfo}{}}} +\subsection{Method \code{CreateUsersWithListInputWithHttpInfo()}}{ +Creates list of users with given input array +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$CreateUsersWithListInputWithHttpInfo(user, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{user}}{List of user object} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (void) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-DeleteUser}{}}} +\subsection{Method \code{DeleteUser()}}{ +Delete user +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$DeleteUser(username, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{username}}{The name that needs to be deleted} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +void +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-DeleteUserWithHttpInfo}{}}} +\subsection{Method \code{DeleteUserWithHttpInfo()}}{ +Delete user +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$DeleteUserWithHttpInfo(username, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{username}}{The name that needs to be deleted} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (void) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-GetUserByName}{}}} +\subsection{Method \code{GetUserByName()}}{ +Get user by user name +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$GetUserByName(username, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{username}}{The name that needs to be fetched. Use user1 for testing.} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +User +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-GetUserByNameWithHttpInfo}{}}} +\subsection{Method \code{GetUserByNameWithHttpInfo()}}{ +Get user by user name +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$GetUserByNameWithHttpInfo(username, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{username}}{The name that needs to be fetched. Use user1 for testing.} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (User) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-LoginUser}{}}} +\subsection{Method \code{LoginUser()}}{ +Logs user into the system +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$LoginUser(username, password, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{username}}{The user name for login} + +\item{\code{password}}{The password for login in clear text} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +character +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-LoginUserWithHttpInfo}{}}} +\subsection{Method \code{LoginUserWithHttpInfo()}}{ +Logs user into the system +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$LoginUserWithHttpInfo(username, password, data_file = NULL, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{username}}{The user name for login} + +\item{\code{password}}{The password for login in clear text} + +\item{\code{data_file}}{(optional) name of the data file to save the result} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (character) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-LogoutUser}{}}} +\subsection{Method \code{LogoutUser()}}{ +Logs out current logged in user session +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$LogoutUser(...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +void +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-LogoutUserWithHttpInfo}{}}} +\subsection{Method \code{LogoutUserWithHttpInfo()}}{ +Logs out current logged in user session +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$LogoutUserWithHttpInfo(...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (void) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-UpdateUser}{}}} +\subsection{Method \code{UpdateUser()}}{ +Updated user +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$UpdateUser(username, user, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{username}}{name that need to be deleted} + +\item{\code{user}}{Updated user object} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +void +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-UpdateUserWithHttpInfo}{}}} +\subsection{Method \code{UpdateUserWithHttpInfo()}}{ +Updated user +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$UpdateUserWithHttpInfo(username, user, ...)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{username}}{name that need to be deleted} + +\item{\code{user}}{Updated user object} + +\item{\code{...}}{Other optional arguments} +} +\if{html}{\out{
        }} +} +\subsection{Returns}{ +API response (void) with additional information such as HTTP status code, headers +} +} +\if{html}{\out{
        }} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-UserApi-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
        }}\preformatted{UserApi$clone(deep = FALSE)}\if{html}{\out{
        }} +} + +\subsection{Arguments}{ +\if{html}{\out{
        }} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
        }} +} +} +} diff --git a/samples/client/petstore/R-httr2/pom.xml b/samples/client/petstore/R-httr2/pom.xml new file mode 100644 index 0000000000..9b460d7724 --- /dev/null +++ b/samples/client/petstore/R-httr2/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + org.openapitools + RHttr2ClientTests + pom + 1.0-SNAPSHOT + R Httr2 Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + nose-test + integration-test + + exec + + + bash + + build_and_test.bash + + + + + + + + diff --git a/samples/client/petstore/R-httr2/test_petstore.R b/samples/client/petstore/R-httr2/test_petstore.R new file mode 100644 index 0000000000..7aa5a16c63 --- /dev/null +++ b/samples/client/petstore/R-httr2/test_petstore.R @@ -0,0 +1,162 @@ + +install.packages("petstore_1.0.0.tar.gz",repos=NULL, type="source") +library(petstore) +library(jsonlite) + +t <- Tag$new() +t$id <- 123 +#t$additional_properties <- c("abc" = 849) +print(t$toJSON()) +print(t$toJSONString()) + +print("done tag") + +t <- OneOfPrimitiveTypeTest$new() + +#t$fromJSONString("[1,2,3]") + + +var_pet <- Pet$new("name_example", list("photoUrls_example"), 56, Category$new(56, "name_example"), list(Tag$new(56, "name_example")), "available") # Pet | Pet object that needs to be added to the store +print(var_pet) +### +####Add a new pet to the store +###api_instance <- PetApi$new() +#### Configure OAuth2 access token for authorization: petstore_auth +###api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +###result <- tryCatch( +### # to save the result into a file, simply add the optional `data_file` parameter, e.g. +### # api_instance$AddPet(var_pet, data_file = "result.txt"), +### api_instance$add_pet(var_pet), +### ApiException = function(ex) ex +### ) +### +###var_pet_id <- 56 # integer | ID of pet to return +### +###pet_response <- api_instance$get_pet_by_id(var_pet_id, data_file = "get_pet_by_id.json") +###response <- read_json("get_pet_by_id.json") +###dput(response) +### +#### test streaming +###api_instance$get_pet_by_id_streaming(var_pet_id, stream_callback = function(x) { print(x) }) + +##Find pet by ID (streaming) +#api_instance <- PetApi$new() +## Configure API key authorization: api_key +#api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#result <- tryCatch( +# # to save the result into a file, simply add the optional `data_file` parameter, e.g. +# # api_instance$GetPetByIdStreaming(var_pet_id, data_file = "result.txt"), +# api_instance$GetPetByIdStreaming(var_pet_id, stream_callback = function(x) { print(x) }), +# ApiException = function(ex) ex +# ) +# In case of error, print the error object +#if (!is.null(result$ApiException)) { +# cat(result$ApiException$toString()) +#} #else { +# # deserialized response object +# response.object <- result$content +# # response headers +# response.headers <- result$response$headers +# # response status code +# response.status.code <- result$response$status_code +#} + +##errorMsg <- "{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}" +###errorMsg <- '{"code": 404, "message": "Not found"}' +##a <- ModelApiResponse$new()$fromJSONString(errorMsg) +##dput(a) +## +##var_pet_id <- 1231256 # integer | ID of pet to return +## +###Find pet by ID +##api_instance <- PetApi$new() +### Configure API key authorization: api_key +##api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +##result <- tryCatch( +## api_instance$GetPetById(var_pet_id), +## ApiException = function(ex) ex +## ) +### In case of error, print the error object +##if(!is.null(result$ApiException)) { +## cat(result$ApiException$toString()) +##} else { +## # deserialized response object +## response.object <- result$content +## # response headers +## response.headers <- result$response$headers +## # response status code +## response.status.code <- result$response$status_code +##} +# +#json2 <- +#'{"name": "pet", "photoUrls" : ["http://a.com", "http://b.com"]}' +# +#jsonlite::minify(json2) +# +#pet_api <- PetApi$new() +#pet_id <- 123321 +#pet <- Pet$new("name_test", +# photoUrls = list("photo_test", "second test"), +# category = Category$new(id = 450, name = "test_cat"), +# id = pet_id, +# tags = list( +# Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown") +# ), +# status = "available" +#) +# +##jsonlite::minify(pet$toJSONString()) +##cat(pet$toJSONString()) +#toString(pet$toString()) +# +##json <- +##'[ +## {"Name" : "Mario", "Age" : 32, "Occupation" : "Plumber"}, +## {"Name" : "Peach", "Age" : 21, "Occupation" : "Princess"}, +## {}, +## {"Name" : "Bowser", "Occupation" : "Koopa"} +##]' +## +## +###Pet$public_methods +###Pet$public_methods$fromJSON(json) +###Pet$public_methods$toJson() +###Pet$public_methods$validateJSON(json2) +###Pet$public_methods$validateJson(json) +###Pet$my_static_method <- function(x) { x + 2} +###Pet$public_methods$my_static_method(1) +## +# basque_pig_json <- +# '{"className2": "BasquePig", "color": "red"}' +## +## danish_pig_json <- +## '{"className2": "DanishPig", "size": 7}' +## +## wrong_json <- +## '[ +## {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"}, +## {}, +## {"Name" : "Ada", "Occupation" : "Engineer"} +## ]' +## +## print("==========") +# pig <- Pig$new() +# basque_pig <- pig$fromJSON(basque_pig_json) +## #print(basque_pig$actual_instance$color) +## #expect_equal(basque_pig$actual_type, "BasquePig") +## pig$fromJSON(danish_pig_json) +## #pig$fromJSON(wrong_json) +## pig$toJSON() +## +## #d <- DanishPig$new() +## #dp <- d$validateJSON(danish_pig_json) +## +## +# +## test nested oneOf +#nested_oneof <- NestedOneOf$new() +#nested_oneof$nested_pig <- pig +#nested_oneof$size <- 15 +# +#cat(nested_oneof$toJSONString()) +# diff --git a/samples/client/petstore/R-httr2/tests/testthat.R b/samples/client/petstore/R-httr2/tests/testthat.R new file mode 100644 index 0000000000..d67bd9cf23 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat.R @@ -0,0 +1,4 @@ +library(testthat) +library(petstore) + +test_check("petstore") diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_allof_tag_api_response.R b/samples/client/petstore/R-httr2/tests/testthat/test_allof_tag_api_response.R new file mode 100644 index 0000000000..90a5d04d3f --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_allof_tag_api_response.R @@ -0,0 +1,41 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test AllofTagApiResponse") + +model_instance <- AllofTagApiResponse$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("name", { + # tests for the property `name` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`name`, "EXPECTED_RESULT") +}) + +test_that("code", { + # tests for the property `code` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`code`, "EXPECTED_RESULT") +}) + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) + +test_that("message", { + # tests for the property `message` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`message`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_animal.R b/samples/client/petstore/R-httr2/tests/testthat/test_animal.R new file mode 100644 index 0000000000..4402cf03c5 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_animal.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Animal") + +model_instance <- Animal$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_any_of_pig.R b/samples/client/petstore/R-httr2/tests/testthat/test_any_of_pig.R new file mode 100644 index 0000000000..8ca3b8e73d --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_any_of_pig.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test AnyOfPig") + +model_instance <- AnyOfPig$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) + +test_that("size", { + # tests for the property `size` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`size`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_any_of_primitive_type_test.R b/samples/client/petstore/R-httr2/tests/testthat/test_any_of_primitive_type_test.R new file mode 100644 index 0000000000..0679cfaf44 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_any_of_primitive_type_test.R @@ -0,0 +1,4 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test AnyOfPrimitiveTypeTest") diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_basque_pig.R b/samples/client/petstore/R-httr2/tests/testthat/test_basque_pig.R new file mode 100644 index 0000000000..400268563d --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_basque_pig.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test BasquePig") + +model_instance <- BasquePig$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_cat.R b/samples/client/petstore/R-httr2/tests/testthat/test_cat.R new file mode 100644 index 0000000000..ab85fe3340 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_cat.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Cat") + +model_instance <- Cat$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) + +test_that("declawed", { + # tests for the property `declawed` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`declawed`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_cat_all_of.R b/samples/client/petstore/R-httr2/tests/testthat/test_cat_all_of.R new file mode 100644 index 0000000000..83ee2fb835 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_cat_all_of.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test CatAllOf") + +model_instance <- CatAllOf$new() + +test_that("declawed", { + # tests for the property `declawed` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`declawed`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_category.R b/samples/client/petstore/R-httr2/tests/testthat/test_category.R new file mode 100644 index 0000000000..c7838edeb6 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_category.R @@ -0,0 +1,21 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Category") + +model.instance <- Category$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("name", { + # tests for the property `name` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`name`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_danish_pig.R b/samples/client/petstore/R-httr2/tests/testthat/test_danish_pig.R new file mode 100644 index 0000000000..a7c2811d89 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_danish_pig.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test DanishPig") + +model_instance <- DanishPig$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("size", { + # tests for the property `size` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`size`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_date.R b/samples/client/petstore/R-httr2/tests/testthat/test_date.R new file mode 100644 index 0000000000..214fd8a352 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_date.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Date") + +model_instance <- Date$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_dog.R b/samples/client/petstore/R-httr2/tests/testthat/test_dog.R new file mode 100644 index 0000000000..9c04cc7806 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_dog.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Dog") + +model_instance <- Dog$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) + +test_that("breed", { + # tests for the property `breed` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`breed`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_dog_all_of.R b/samples/client/petstore/R-httr2/tests/testthat/test_dog_all_of.R new file mode 100644 index 0000000000..6d11847f66 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_dog_all_of.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test DogAllOf") + +model_instance <- DogAllOf$new() + +test_that("breed", { + # tests for the property `breed` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`breed`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_fake_api.R b/samples/client/petstore/R-httr2/tests/testthat/test_fake_api.R new file mode 100644 index 0000000000..7514044ac1 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_fake_api.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test FakeApi") + +api.instance <- FakeApi$new() + +test_that("FakeDataFile", { + # tests for FakeDataFile + # base path: http://petstore.swagger.io/v2 + # test data_file to ensure it's escaped correctly + # + # @param dummy character dummy required parameter + # @param DataFile. character header data file (optional) + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_mammal.R b/samples/client/petstore/R-httr2/tests/testthat/test_mammal.R new file mode 100644 index 0000000000..bc061ea799 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_mammal.R @@ -0,0 +1,34 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Mammal") + +model_instance <- Mammal$new() + +test_that("hasBaleen", { + # tests for the property `hasBaleen` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasBaleen`, "EXPECTED_RESULT") +}) + +test_that("hasTeeth", { + # tests for the property `hasTeeth` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasTeeth`, "EXPECTED_RESULT") +}) + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_model_api_response.R b/samples/client/petstore/R-httr2/tests/testthat/test_model_api_response.R new file mode 100644 index 0000000000..d5dcef5716 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_model_api_response.R @@ -0,0 +1,28 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test ModelApiResponse") + +model.instance <- ModelApiResponse$new() + +test_that("code", { + # tests for the property `code` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`code`, "EXPECTED_RESULT") +}) + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) + +test_that("message", { + # tests for the property `message` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`message`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_nested_one_of.R b/samples/client/petstore/R-httr2/tests/testthat/test_nested_one_of.R new file mode 100644 index 0000000000..940a7fba2a --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_nested_one_of.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test NestedOneOf") + +model_instance <- NestedOneOf$new() + +test_that("size", { + # tests for the property `size` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`size`, "EXPECTED_RESULT") +}) + +test_that("nested_pig", { + # tests for the property `nested_pig` (Pig) + + # uncomment below to test the property + #expect_equal(model.instance$`nested_pig`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_one_of_primitive_type_test.R b/samples/client/petstore/R-httr2/tests/testthat/test_one_of_primitive_type_test.R new file mode 100644 index 0000000000..f9e7158359 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_one_of_primitive_type_test.R @@ -0,0 +1,4 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test OneOfPrimitiveTypeTest") diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_order.R b/samples/client/petstore/R-httr2/tests/testthat/test_order.R new file mode 100644 index 0000000000..33b8752025 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_order.R @@ -0,0 +1,50 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Order") + +model.instance <- Order$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("petId", { + # tests for the property `petId` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`petId`, "EXPECTED_RESULT") +}) + +test_that("quantity", { + # tests for the property `quantity` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`quantity`, "EXPECTED_RESULT") +}) + +test_that("shipDate", { + # tests for the property `shipDate` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`shipDate`, "EXPECTED_RESULT") +}) + +test_that("status", { + # tests for the property `status` (character) + # Order Status + + # uncomment below to test the property + #expect_equal(model.instance$`status`, "EXPECTED_RESULT") +}) + +test_that("complete", { + # tests for the property `complete` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`complete`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_pet.R b/samples/client/petstore/R-httr2/tests/testthat/test_pet.R new file mode 100644 index 0000000000..ac3e4f31dd --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_pet.R @@ -0,0 +1,50 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Pet") + +model.instance <- Pet$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("category", { + # tests for the property `category` (Category) + + # uncomment below to test the property + #expect_equal(model.instance$`category`, "EXPECTED_RESULT") +}) + +test_that("name", { + # tests for the property `name` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`name`, "EXPECTED_RESULT") +}) + +test_that("photoUrls", { + # tests for the property `photoUrls` (array[character]) + + # uncomment below to test the property + #expect_equal(model.instance$`photoUrls`, "EXPECTED_RESULT") +}) + +test_that("tags", { + # tests for the property `tags` (array[Tag]) + + # uncomment below to test the property + #expect_equal(model.instance$`tags`, "EXPECTED_RESULT") +}) + +test_that("status", { + # tests for the property `status` (character) + # pet status in the store + + # uncomment below to test the property + #expect_equal(model.instance$`status`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_pet_api.R b/samples/client/petstore/R-httr2/tests/testthat/test_pet_api.R new file mode 100644 index 0000000000..7fbdd1a70d --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_pet_api.R @@ -0,0 +1,103 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test PetApi") + +api.instance <- PetApi$new() + +test_that("AddPet", { + # tests for AddPet + # base path: http://petstore.swagger.io/v2 + # Add a new pet to the store + # @param body Pet Pet object that needs to be added to the store + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("DeletePet", { + # tests for DeletePet + # base path: http://petstore.swagger.io/v2 + # Deletes a pet + # @param pet.id integer Pet id to delete + # @param api.key character (optional) + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("FindPetsByStatus", { + # tests for FindPetsByStatus + # base path: http://petstore.swagger.io/v2 + # Finds Pets by status + # Multiple status values can be provided with comma separated strings + # @param status array[character] Status values that need to be considered for filter + # @return [array[Pet]] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("FindPetsByTags", { + # tests for FindPetsByTags + # base path: http://petstore.swagger.io/v2 + # Finds Pets by tags + # Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + # @param tags array[character] Tags to filter by + # @return [array[Pet]] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("GetPetById", { + # tests for GetPetById + # base path: http://petstore.swagger.io/v2 + # Find pet by ID + # Returns a single pet + # @param pet.id integer ID of pet to return + # @return [Pet] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("UpdatePet", { + # tests for UpdatePet + # base path: http://petstore.swagger.io/v2 + # Update an existing pet + # @param body Pet Pet object that needs to be added to the store + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("UpdatePetWithForm", { + # tests for UpdatePetWithForm + # base path: http://petstore.swagger.io/v2 + # Updates a pet in the store with form data + # @param pet.id integer ID of pet that needs to be updated + # @param name character Updated name of the pet (optional) + # @param status character Updated status of the pet (optional) + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("UploadFile", { + # tests for UploadFile + # base path: http://petstore.swagger.io/v2 + # uploads an image + # @param pet.id integer ID of pet to update + # @param additional.metadata character Additional data to pass to server (optional) + # @param file data.frame file to upload (optional) + # @return [ModelApiResponse] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_petstore.R b/samples/client/petstore/R-httr2/tests/testthat/test_petstore.R new file mode 100644 index 0000000000..73723ba1d6 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_petstore.R @@ -0,0 +1,400 @@ +context("basic functionality") + +## create a new pet and add to petstore server +pet_api <- PetApi$new() +pet_id <- 123321 +pet <- Pet$new("name_test", + photoUrls = list("photo_test", "second test"), + category = Category$new(id = 450, name = "test_cat"), + id = pet_id, + tags = list( + Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown") + ), + status = "available" +) +pet_api$api_client$username <- "username123" +pet_api$api_client$password <- "password123" +result <- pet_api$add_pet(pet) + +test_that("Test toJSON toJSONString fromJSON fromJSONString", { + # test pet + expect_equal(pet_id, 123321) + expect_equal(pet$toJSONString(), '{"id":123321,"category":{"id":450,"name":"test_cat"},"name":"name_test","photoUrls":["photo_test","second test"],"tags":[{"id":123,"name":"tag_test"},{"id":456,"name":"unknown"}],"status":"available"}') + + # tests for other pet objects + pet0 <- Pet$new() + jsonpet <- pet0$toJSON() + pet2 <- pet0$fromJSON( + jsonlite::toJSON(jsonpet, auto_unbox = TRUE) + ) + expect_equal(pet0, pet2) + jsonpet <- pet0$toJSONString() + pet2 <- pet0$fromJSON( + jsonpet + ) + expect_equal(pet0, pet2) + + jsonpet <- pet0$toJSONString() + pet2 <- pet0$fromJSONString( + jsonpet + ) + expect_equal(pet0, pet2) + + pet1 <- Pet$new("name_test", + list("photo_test", "second test"), + category = Category$new(id = 450, name = "test_cat"), + id = pet_id, + tags = list( + Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown") + ), + status = "available" + ) + jsonpet <- pet1$toJSON() + pet2 <- pet1$fromJSON( + jsonlite::toJSON(jsonpet, auto_unbox = TRUE) + ) + expect_equal(pet1, pet2) + + jsonpet <- pet1$toJSONString() + pet2 <- pet1$fromJSON( + jsonpet + ) + expect_equal(pet1, pet2) + + jsonpet <- pet1$toJSONString() + pet2 <- pet1$fromJSONString( + jsonpet + ) + expect_equal(pet1, pet2) +}) + +test_that("Test Category", { + c1 <- Category$new(id = 450, name = "test_cat") + c2 <- Category$new() + c2$fromJSON(jsonlite::toJSON(c1$toJSON(), auto_unbox = TRUE)) + expect_equal(c1, c2) + c2$fromJSONString(c1$toJSONString()) + expect_equal(c1, c2) +}) + +test_that("get_pet_by_id", { + response <- pet_api$get_pet_by_id(pet_id) + expect_equal(response$id, pet_id) + expect_equal(response$name, "name_test") + expect_equal( + response$photoUrls, + list("photo_test", "second test") + ) + expect_equal(response$status, "available") + expect_equal(response$category, Category$new(id = 450, name = "test_cat")) + + expect_equal(pet$tags, response$tags) + expect_equal( + response$tags, + list(Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown")) + ) +}) + +test_that("update_pet_with_form", { + ## add pet + update_pet_id <- 123999 + update_pet <- Pet$new("name_test", + photoUrls = list("photo_test", "second test"), + category = Category$new(id = 450, name = "test_cat"), + id = update_pet_id, + tags = list( + Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown") + ), + status = "available" + ) + pet_api$api_client$username <- "username123" + pet_api$api_client$password <- "password123" + result <- pet_api$add_pet(update_pet) + + ## update pet with form + pet_api$api_client$oauth_client_id <- "client_id_aaa" + pet_api$api_client$oauth_secret <- "secrete_bbb" + pet_api$api_client$oauth_scopes <- "write:pets read:pets" + update_result <- pet_api$update_pet_with_form(update_pet_id, name = "pet2", status = "sold") + + # get pet + response <- pet_api$get_pet_by_id(update_pet_id) + expect_equal(response$id, update_pet_id) + expect_equal(response$name, "pet2") + expect_equal(response$status, "sold") + expect_equal( + response$photoUrls, + list("photo_test", "second test") + ) + expect_equal(response$category, Category$new(id = 450, name = "test_cat")) + + expect_equal(pet$tags, response$tags) + expect_equal( + response$tags, + list(Tag$new(id = 123, name = "tag_test"), Tag$new(id = 456, name = "unknown")) + ) +}) + +test_that("get_pet_by_id_streaming", { + result <- tryCatch( + pet_api$get_pet_by_id_streaming(pet_id, stream_callback = function(x) { print(x) }), + ApiException = function(ex) ex + ) +}) + +test_that("Test header parameters", { + # test exception + result <- tryCatch(pet_api$test_header(45345), + ApiException = function(ex) ex + ) + + expect_true(!is.null(result)) + expect_true(!is.null(result$ApiException)) + expect_equal(result$ApiException$status, 404) + # test error object `ApiResponse` + #expect_equal(result$ApiException$error_object$toString(), "{\"code\":404,\"type\":\"unknown\",\"message\":\"null for uri: http://pet\n x[1]: store.swagger.io/v2/pet_header_test\"}") + expect_equal(result$ApiException$error_object$code, 404) +}) + + +test_that("Test GetPetById exception", { + # test exception + result <- tryCatch(pet_api$get_pet_by_id(98765), # petId not exist + ApiException = function(ex) ex + ) + + expect_true(!is.null(result)) + expect_true(!is.null(result$ApiException)) + expect_equal(result$ApiException$status, 404) + # test error object `ApiResponse` + expect_equal(result$ApiException$error_object$toString(), "{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}") + expect_equal(result$ApiException$error_object$code, 1) +}) + +test_that("GetPetById with data_file", { + # test to ensure json is saved to the file `get_pet_by_id.json` + pet_response <- pet_api$get_pet_by_id(pet_id, data_file = "get_pet_by_id.json") + response <- read_json("get_pet_by_id.json") + expect_true(!is.null(response)) + expect_equal(response$id, pet_id) + expect_equal(response$name, "name_test") +}) + +test_that("Tests allOf", { + # test allOf without discriminator + a1 <- AllofTagApiResponse$new(id = 450, name = "test_cat", code = 200, type = "test_type", message = "test_message") + + expect_true(!is.null(a1)) + expect_equal(a1$id, 450) + expect_equal(a1$name, "test_cat") +}) + +test_that("Tests allOf with discriminator", { + # test allOf without discriminator + c1 <- Cat$new(className = "cat", color = "red", declawed = TRUE) + + expect_true(!is.null(c1)) + expect_equal(c1$className, "cat") + expect_equal(c1$color, "red") + expect_true(c1$declawed) +}) + +test_that("Tests validateJSON", { + json <- + '{"name": "pet", "photoUrls" : ["http://a.com", "http://b.com"]}' + + json2 <- + '[ + {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"}, + {}, + {"Name" : "Ada", "Occupation" : "Engineer"} + ]' + + # validate `json` and no error throw + Pet$public_methods$validateJSON(json) + + # validate `json2` and should throw an error due to missing required fields + #expect_error(Pet$public_methods$validateJSON(json2), 'The JSON input ` [\n {\"Name\" : \"Tom\", \"Age\" : 32, \"Occupation\" : \"Consultant\"}, \n {},\n {\"Name\" : \"Ada\", \"Occupation\" : \"Engineer\"}\n ] ` is invalid for Pet: the required field `name` is missing.') + +}) + +# test object with special item names: self, private, super +test_that("Tests special item names", { + special_json <- + '{"self": 123, "private": "red", "super": "something"}' + + # test fromJSON + special <- Special$new()$fromJSON(special_json) + expect_equal(special$item_self, 123) + expect_equal(special$item_private, "red") + expect_equal(special$item_super, "something") + + # test toJSONString + expect_true(grepl('"private"', special$toJSONString())) + expect_true(grepl('"self"', special$toJSONString())) + expect_true(grepl('"super"', special$toJSONString())) + expect_equal('{"self":123,"private":"red","super":"something"}', special$toJSONString()) + + # round trip test + s1 <- Special$new()$fromJSONString(special_json) + s2 <- Special$new()$fromJSONString(s1$toJSONString()) + expect_equal(s1, s2) + +}) + +test_that ("Tests validations", { + invalid_pet <- Pet$new() + + expect_false(invalid_pet$isValid()) + + invalid_fields <- invalid_pet$getInvalidFields() + expect_equal(invalid_fields[["name"]], "Non-nullable required field `name` cannot be null.") + expect_equal(invalid_fields[["photoUrls"]], "Non-nullable required field `photoUrls` cannot be null.") + + # fix invalid fields + invalid_pet$name <- "valid pet" + invalid_pet$photoUrls <- list("photo_test", "second test") + + expect_true(invalid_pet$isValid()) + expect_equal(invalid_pet$getInvalidFields(), list()) + +}) + +test_that("Tests oneOf primitive types", { + test <- OneOfPrimitiveTypeTest$new() + test$fromJSONString("\"123abc\"") + expect_equal(test$actual_instance, '123abc') + expect_equal(test$actual_type, 'character') + + test$fromJSONString("456") + expect_equal(test$actual_instance, 456) + expect_equal(test$actual_type, 'integer') + + expect_error(test$fromJSONString("[45,12]"), "No match found when deserializing the payload into OneOfPrimitiveTypeTest with oneOf schemas character, integer. Details: Data type doesn't match. Expected: integer. Actual: list., Data type doesn't match. Expected: character. Actual: list.") # should throw an error +}) + +test_that("Tests anyOf primitive types", { + test <- AnyOfPrimitiveTypeTest$new() + test$fromJSONString("\"123abc\"") + expect_equal(test$actual_instance, '123abc') + expect_equal(test$actual_type, 'character') + + test$fromJSONString("456") + expect_equal(test$actual_instance, 456) + expect_equal(test$actual_type, 'integer') + + expect_error(test$fromJSONString("[45,12]"), "No match found when deserializing the payload into AnyOfPrimitiveTypeTest with oneOf schemas character, integer. Details: Data type doesn't match. Expected: integer. Actual: list., Data type doesn't match. Expected: character. Actual: list.") # should throw an error +}) + +test_that("Tests oneOf", { + basque_pig_json <- + '{"className": "BasquePig", "color": "red"}' + + danish_pig_json <- + '{"className": "DanishPig", "size": 7}' + + wrong_json <- + '[ + {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"}, + {}, + {"Name" : "Ada", "Occupation" : "Engineer"} + ]' + + original_danish_pig <- DanishPig$new()$fromJSON(danish_pig_json) + original_basque_pig <- BasquePig$new()$fromJSON(basque_pig_json) + + # test fromJSON, actual_tpye, actual_instance + pig <- Pig$new() + danish_pig <- pig$fromJSON(danish_pig_json) + pig$validateJSON(basque_pig_json) # validate JSON to ensure its actual_instance, actual_type are not updated + expect_equal(danish_pig$actual_type, "DanishPig") + expect_equal(danish_pig$actual_instance$size, 7) + expect_equal(danish_pig$actual_instance$className, "DanishPig") + + expect_equal(pig$actual_type, "DanishPig") + expect_equal(pig$actual_instance$size, 7) + expect_equal(pig$actual_instance$className, "DanishPig") + + # test toJSON + expect_equal(danish_pig$toJSONString(), original_danish_pig$toJSONString()) + + basque_pig <- pig$fromJSON(basque_pig_json) + expect_equal(basque_pig$actual_type, "BasquePig") + expect_equal(basque_pig$actual_instance$color, "red") + expect_equal(basque_pig$actual_instance$className, "BasquePig") + expect_equal(basque_pig$toJSONString(), original_basque_pig$toJSONString()) + + # test exception when no matche found + expect_error(pig$fromJSON('{}'), 'No match found when deserializing the payload into Pig with oneOf schemas BasquePig, DanishPig. Details: The JSON input ` \\{\\} ` is invalid for BasquePig: the required field `className` is missing\\., The JSON input ` \\{\\} ` is invalid for DanishPig: the required field `className` is missing\\.') + expect_error(pig$validateJSON('{}'), 'No match found when deserializing the payload into Pig with oneOf schemas BasquePig, DanishPig. Details: The JSON input ` \\{\\} ` is invalid for BasquePig: the required field `className` is missing\\., The JSON input ` \\{\\} ` is invalid for DanishPig: the required field `className` is missing\\.') + + # class name test + expect_equal(get(class(basque_pig$actual_instance)[[1]], pos = -1)$classname, "BasquePig") + + # test contructors + pig2 <- Pig$new(instance = basque_pig$actual_instance) + expect_equal(pig2$actual_type, "BasquePig") + expect_equal(pig2$actual_instance$color, "red") + expect_equal(pig2$actual_instance$className, "BasquePig") + expect_equal(pig2$toJSONString(), original_basque_pig$toJSONString()) + + expect_error(Pig$new(instance = basque_pig), 'Failed to initialize Pig with oneOf schemas BasquePig, DanishPig. Provided class name: Pig') + + # test nested oneOf toJSONString + nested_oneof <- NestedOneOf$new() + nested_oneof$nested_pig <- pig + nested_oneof$size <- 15 + expect_equal(nested_oneof$toJSONString(), '{"size":15,"nested_pig":{"className":"BasquePig","color":"red"}}') + + # test fromJSONString with nested oneOf + nested_json_str <- '{"size":15,"nested_pig":{"className":"BasquePig","color":"red"}}' + nested_oneof2 <- NestedOneOf$new()$fromJSONString(nested_json_str) + expect_equal(nested_oneof2$toJSONString(), '{"size":15,"nested_pig":{"className":"BasquePig","color":"red"}}') + + # test toString + expect_equal(as.character(jsonlite::minify(pig$toString())), "{\"actual_instance\":{\"className\":\"BasquePig\",\"color\":\"red\"},\"actual_type\":\"BasquePig\",\"one_of\":\"BasquePig, DanishPig\"}") + expect_equal(as.character(jsonlite::minify(Pig$new()$toString())), "{\"one_of\":\"BasquePig, DanishPig\"}") +}) + +test_that("Tests anyOf", { + basque_pig_json <- + '{"className": "BasquePig", "color": "red"}' + + danish_pig_json <- + '{"className": "DanishPig", "size": 7}' + + wrong_json <- + '[ + {"Name" : "Tom", "Age" : 32, "Occupation" : "Consultant"}, + {}, + {"Name" : "Ada", "Occupation" : "Engineer"} + ]' + + original_danish_pig <- DanishPig$new()$fromJSON(danish_pig_json) + original_basque_pig <- BasquePig$new()$fromJSON(basque_pig_json) + + # test fromJSON, actual_tpye, actual_instance + pig <- AnyOfPig$new() + danish_pig <- pig$fromJSON(danish_pig_json) + expect_equal(danish_pig$actual_type, "DanishPig") + expect_equal(danish_pig$actual_instance$size, 7) + expect_equal(danish_pig$actual_instance$className, "DanishPig") + + expect_equal(pig$actual_type, "DanishPig") + expect_equal(pig$actual_instance$size, 7) + expect_equal(pig$actual_instance$className, "DanishPig") + + # test toJSONString + expect_equal(danish_pig$toJSONString(), original_danish_pig$toJSONString()) + + basque_pig <- pig$fromJSON(basque_pig_json) + expect_equal(basque_pig$actual_type, "BasquePig") + expect_equal(basque_pig$actual_instance$color, "red") + expect_equal(basque_pig$actual_instance$className, "BasquePig") + expect_equal(basque_pig$toJSONString(), original_basque_pig$toJSONString()) + + # test exception when no matche found + expect_error(pig$fromJSON('{}'), 'No match found when deserializing the payload into AnyOfPig with anyOf schemas BasquePig, DanishPig. Details: The JSON input ` \\{\\} ` is invalid for BasquePig: the required field `className` is missing\\., The JSON input ` \\{\\} ` is invalid for DanishPig: the required field `className` is missing\\.') + expect_error(pig$validateJSON('{}'), 'No match found when deserializing the payload into AnyOfPig with anyOf schemas BasquePig, DanishPig. Details: The JSON input ` \\{\\} ` is invalid for BasquePig: the required field `className` is missing\\., The JSON input ` \\{\\} ` is invalid for DanishPig: the required field `className` is missing\\.') + +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_pig.R b/samples/client/petstore/R-httr2/tests/testthat/test_pig.R new file mode 100644 index 0000000000..4846cfbb0f --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_pig.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Pig") + +model_instance <- Pig$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("color", { + # tests for the property `color` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`color`, "EXPECTED_RESULT") +}) + +test_that("size", { + # tests for the property `size` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`size`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_special.R b/samples/client/petstore/R-httr2/tests/testthat/test_special.R new file mode 100644 index 0000000000..c76671b213 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_special.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Special") + +model_instance <- Special$new() + +test_that("self", { + # tests for the property `self` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`self`, "EXPECTED_RESULT") +}) + +test_that("private", { + # tests for the property `private` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`private`, "EXPECTED_RESULT") +}) + +test_that("super", { + # tests for the property `super` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`super`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_store_api.R b/samples/client/petstore/R-httr2/tests/testthat/test_store_api.R new file mode 100644 index 0000000000..1ebb3f82a6 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_store_api.R @@ -0,0 +1,53 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test StoreApi") + +api.instance <- StoreApi$new() + +test_that("DeleteOrder", { + # tests for DeleteOrder + # base path: http://petstore.swagger.io/v2 + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order.id character ID of the order that needs to be deleted + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("GetInventory", { + # tests for GetInventory + # base path: http://petstore.swagger.io/v2 + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @return [map(integer)] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("GetOrderById", { + # tests for GetOrderById + # base path: http://petstore.swagger.io/v2 + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order.id integer ID of pet that needs to be fetched + # @return [Order] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("PlaceOrder", { + # tests for PlaceOrder + # base path: http://petstore.swagger.io/v2 + # Place an order for a pet + # @param body Order order placed for purchasing the pet + # @return [Order] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_tag.R b/samples/client/petstore/R-httr2/tests/testthat/test_tag.R new file mode 100644 index 0000000000..2dd6d369af --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_tag.R @@ -0,0 +1,21 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Tag") + +model.instance <- Tag$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("name", { + # tests for the property `name` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`name`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_update_pet_request.R b/samples/client/petstore/R-httr2/tests/testthat/test_update_pet_request.R new file mode 100644 index 0000000000..b39b2b4d0d --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_update_pet_request.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test UpdatePetRequest") + +model_instance <- UpdatePetRequest$new() + +test_that("jsonData", { + # tests for the property `jsonData` (Pet) + + # uncomment below to test the property + #expect_equal(model.instance$`jsonData`, "EXPECTED_RESULT") +}) + +test_that("binaryDataN2Information", { + # tests for the property `binaryDataN2Information` (data.frame) + + # uncomment below to test the property + #expect_equal(model.instance$`binaryDataN2Information`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_user.R b/samples/client/petstore/R-httr2/tests/testthat/test_user.R new file mode 100644 index 0000000000..9929623b42 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_user.R @@ -0,0 +1,64 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test User") + +model.instance <- User$new() + +test_that("id", { + # tests for the property `id` (integer) + + # uncomment below to test the property + #expect_equal(model.instance$`id`, "EXPECTED_RESULT") +}) + +test_that("username", { + # tests for the property `username` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`username`, "EXPECTED_RESULT") +}) + +test_that("firstName", { + # tests for the property `firstName` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`firstName`, "EXPECTED_RESULT") +}) + +test_that("lastName", { + # tests for the property `lastName` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`lastName`, "EXPECTED_RESULT") +}) + +test_that("email", { + # tests for the property `email` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`email`, "EXPECTED_RESULT") +}) + +test_that("password", { + # tests for the property `password` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`password`, "EXPECTED_RESULT") +}) + +test_that("phone", { + # tests for the property `phone` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`phone`, "EXPECTED_RESULT") +}) + +test_that("userStatus", { + # tests for the property `userStatus` (integer) + # User Status + + # uncomment below to test the property + #expect_equal(model.instance$`userStatus`, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_user_api.R b/samples/client/petstore/R-httr2/tests/testthat/test_user_api.R new file mode 100644 index 0000000000..8b8c3ba384 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_user_api.R @@ -0,0 +1,99 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test UserApi") + +api.instance <- UserApi$new() + +test_that("CreateUser", { + # tests for CreateUser + # base path: http://petstore.swagger.io/v2 + # Create user + # This can only be done by the logged in user. + # @param body User Created user object + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("CreateUsersWithArrayInput", { + # tests for CreateUsersWithArrayInput + # base path: http://petstore.swagger.io/v2 + # Creates list of users with given input array + # @param body array[User] List of user object + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("CreateUsersWithListInput", { + # tests for CreateUsersWithListInput + # base path: http://petstore.swagger.io/v2 + # Creates list of users with given input array + # @param body array[User] List of user object + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("DeleteUser", { + # tests for DeleteUser + # base path: http://petstore.swagger.io/v2 + # Delete user + # This can only be done by the logged in user. + # @param username character The name that needs to be deleted + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("GetUserByName", { + # tests for GetUserByName + # base path: http://petstore.swagger.io/v2 + # Get user by user name + # @param username character The name that needs to be fetched. Use user1 for testing. + # @return [User] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("LoginUser", { + # tests for LoginUser + # base path: http://petstore.swagger.io/v2 + # Logs user into the system + # @param username character The user name for login + # @param password character The password for login in clear text + # @return [character] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("LogoutUser", { + # tests for LogoutUser + # base path: http://petstore.swagger.io/v2 + # Logs out current logged in user session + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + +test_that("UpdateUser", { + # tests for UpdateUser + # base path: http://petstore.swagger.io/v2 + # Updated user + # This can only be done by the logged in user. + # @param username character name that need to be deleted + # @param body User Updated user object + # @return [Void] + + # uncomment below to test the operation + #expect_equal(result, "EXPECTED_RESULT") +}) + diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_whale.R b/samples/client/petstore/R-httr2/tests/testthat/test_whale.R new file mode 100644 index 0000000000..b19c7b9eb3 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_whale.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Whale") + +model_instance <- Whale$new() + +test_that("hasBaleen", { + # tests for the property `hasBaleen` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasBaleen`, "EXPECTED_RESULT") +}) + +test_that("hasTeeth", { + # tests for the property `hasTeeth` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasTeeth`, "EXPECTED_RESULT") +}) + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R-httr2/tests/testthat/test_zebra.R b/samples/client/petstore/R-httr2/tests/testthat/test_zebra.R new file mode 100644 index 0000000000..444da2f8f7 --- /dev/null +++ b/samples/client/petstore/R-httr2/tests/testthat/test_zebra.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Zebra") + +model_instance <- Zebra$new() + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R/.Rbuildignore b/samples/client/petstore/R/.Rbuildignore index b87ca49775..d982e4aa88 100644 --- a/samples/client/petstore/R/.Rbuildignore +++ b/samples/client/petstore/R/.Rbuildignore @@ -11,6 +11,7 @@ ^\.gitignore$ ^\.openapi-generator-ignore$ ^\.travis\.yml$ +^\.lintr$ ^\.github$ ^\.openapi-generator$ ^docs$ diff --git a/samples/client/petstore/R/.openapi-generator/FILES b/samples/client/petstore/R/.openapi-generator/FILES index 7a05f5fdda..d539ea462d 100644 --- a/samples/client/petstore/R/.openapi-generator/FILES +++ b/samples/client/petstore/R/.openapi-generator/FILES @@ -8,6 +8,7 @@ NAMESPACE R/allof_tag_api_response.R R/animal.R R/any_of_pig.R +R/any_of_primitive_type_test.R R/api_client.R R/api_exception.R R/api_response.R @@ -16,11 +17,14 @@ R/cat.R R/cat_all_of.R R/category.R R/danish_pig.R +R/date.R R/dog.R R/dog_all_of.R R/fake_api.R +R/mammal.R R/model_api_response.R R/nested_one_of.R +R/one_of_primitive_type_test.R R/order.R R/pet.R R/pet_api.R @@ -31,20 +35,26 @@ R/tag.R R/update_pet_request.R R/user.R R/user_api.R +R/whale.R +R/zebra.R README.md docs/AllofTagApiResponse.md docs/Animal.md docs/AnyOfPig.md +docs/AnyOfPrimitiveTypeTest.md docs/BasquePig.md docs/Cat.md docs/CatAllOf.md docs/Category.md docs/DanishPig.md +docs/Date.md docs/Dog.md docs/DogAllOf.md docs/FakeApi.md +docs/Mammal.md docs/ModelApiResponse.md docs/NestedOneOf.md +docs/OneOfPrimitiveTypeTest.md docs/Order.md docs/Pet.md docs/PetApi.md @@ -55,5 +65,7 @@ docs/Tag.md docs/UpdatePetRequest.md docs/User.md docs/UserApi.md +docs/Whale.md +docs/Zebra.md git_push.sh tests/testthat.R diff --git a/samples/client/petstore/R/DESCRIPTION b/samples/client/petstore/R/DESCRIPTION index 2afb45624b..ee2ebde912 100644 --- a/samples/client/petstore/R/DESCRIPTION +++ b/samples/client/petstore/R/DESCRIPTION @@ -11,5 +11,5 @@ Encoding: UTF-8 License: Apache License 2.0 LazyData: true Suggests: testthat -Imports: jsonlite, httr, R6, base64enc -RoxygenNote: 7.2.0 +Imports: jsonlite, httr, R6, base64enc, stringr +RoxygenNote: 7.2.1 diff --git a/samples/client/petstore/R/NAMESPACE b/samples/client/petstore/R/NAMESPACE index d8fc867efa..a38534972b 100644 --- a/samples/client/petstore/R/NAMESPACE +++ b/samples/client/petstore/R/NAMESPACE @@ -5,6 +5,8 @@ import(R6) import(jsonlite) import(httr) import(base64enc) +import(stringr) + # Core export(ApiClient) @@ -15,15 +17,19 @@ export(ApiException) export(AllofTagApiResponse) export(Animal) export(AnyOfPig) +export(AnyOfPrimitiveTypeTest) export(BasquePig) export(Cat) export(CatAllOf) export(Category) export(DanishPig) +export(Date) export(Dog) export(DogAllOf) +export(Mammal) export(ModelApiResponse) export(NestedOneOf) +export(OneOfPrimitiveTypeTest) export(Order) export(Pet) export(Pig) @@ -31,6 +37,8 @@ export(Special) export(Tag) export(UpdatePetRequest) export(User) +export(Whale) +export(Zebra) # APIs export(FakeApi) diff --git a/samples/client/petstore/R/R/allof_tag_api_response.R b/samples/client/petstore/R/R/allof_tag_api_response.R index a6722975bf..e485c15e4c 100644 --- a/samples/client/petstore/R/R/allof_tag_api_response.R +++ b/samples/client/petstore/R/R/allof_tag_api_response.R @@ -1,11 +1,8 @@ -#' OpenAPI Petstore +#' Create a new AllofTagApiResponse #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' AllofTagApiResponse Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title AllofTagApiResponse #' @description AllofTagApiResponse Class @@ -15,6 +12,8 @@ #' @field code integer [optional] #' @field type character [optional] #' @field message character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -26,6 +25,8 @@ AllofTagApiResponse <- R6::R6Class( `code` = NULL, `type` = NULL, `message` = NULL, + `_field_list` = c("id", "name", "code", "type", "message"), + `additional_properties` = list(), #' Initialize a new AllofTagApiResponse class. #' #' @description @@ -36,11 +37,10 @@ AllofTagApiResponse <- R6::R6Class( #' @param code code #' @param type type #' @param message message + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `id` = NULL, `name` = NULL, `code` = NULL, `type` = NULL, `message` = NULL, ... - ) { + initialize = function(`id` = NULL, `name` = NULL, `code` = NULL, `type` = NULL, `message` = NULL, additional_properties = NULL, ...) { if (!is.null(`id`)) { stopifnot(is.numeric(`id`), length(`id`) == 1) self$`id` <- `id` @@ -61,6 +61,11 @@ AllofTagApiResponse <- R6::R6Class( stopifnot(is.character(`message`), length(`message`) == 1) self$`message` <- `message` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -91,6 +96,9 @@ AllofTagApiResponse <- R6::R6Class( AllofTagApiResponseObject[["message"]] <- self$`message` } + for (key in names(self$additional_properties)) { + AllofTagApiResponseObject[[key]] <- self$additional_properties[[key]] + } AllofTagApiResponseObject }, @@ -119,6 +127,13 @@ AllofTagApiResponse <- R6::R6Class( if (!is.null(this_object$`message`)) { self$`message` <- this_object$`message` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -172,7 +187,12 @@ AllofTagApiResponse <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of AllofTagApiResponse #' @@ -189,6 +209,13 @@ AllofTagApiResponse <- R6::R6Class( self$`code` <- this_object$`code` self$`type` <- this_object$`type` self$`message` <- this_object$`message` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to AllofTagApiResponse @@ -210,7 +237,50 @@ AllofTagApiResponse <- R6::R6Class( #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +# AllofTagApiResponse$unlock() +# +## Below is an example to define the print fnuction +# AllofTagApiResponse$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# AllofTagApiResponse$lock() diff --git a/samples/client/petstore/R/R/animal.R b/samples/client/petstore/R/R/animal.R index bd8d7deba7..632b160087 100644 --- a/samples/client/petstore/R/R/animal.R +++ b/samples/client/petstore/R/R/animal.R @@ -1,17 +1,16 @@ -#' OpenAPI Petstore +#' Create a new Animal #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' Animal Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title Animal #' @description Animal Class #' @format An \code{R6Class} generator object #' @field className character #' @field color character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -20,6 +19,10 @@ Animal <- R6::R6Class( public = list( `className` = NULL, `color` = NULL, + `_field_list` = c("className", "color"), + `additional_properties` = list(), + `_discriminator_property_name` = 'className', + `_discriminator_mapping_name` = c('Cat' = 'Cat', 'Dog' = 'Dog'), #' Initialize a new Animal class. #' #' @description @@ -27,11 +30,10 @@ Animal <- R6::R6Class( #' #' @param className className #' @param color color. Default to "red". + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `className`, `color` = "red", ... - ) { + initialize = function(`className`, `color` = "red", additional_properties = NULL, ...) { if (!missing(`className`)) { stopifnot(is.character(`className`), length(`className`) == 1) self$`className` <- `className` @@ -40,6 +42,11 @@ Animal <- R6::R6Class( stopifnot(is.character(`color`), length(`color`) == 1) self$`color` <- `color` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -58,6 +65,9 @@ Animal <- R6::R6Class( AnimalObject[["color"]] <- self$`color` } + for (key in names(self$additional_properties)) { + AnimalObject[[key]] <- self$additional_properties[[key]] + } AnimalObject }, @@ -77,6 +87,13 @@ Animal <- R6::R6Class( if (!is.null(this_object$`color`)) { self$`color` <- this_object$`color` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -106,7 +123,12 @@ Animal <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of Animal #' @@ -120,6 +142,13 @@ Animal <- R6::R6Class( this_object <- jsonlite::fromJSON(input_json) self$`className` <- this_object$`className` self$`color` <- this_object$`color` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to Animal @@ -147,7 +176,60 @@ Animal <- R6::R6Class( #' @export toString = function() { self$toJSONString() - } - ) -) + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Animal$unlock() +# +## Below is an example to define the print fnuction +# Animal$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Animal$lock() diff --git a/samples/client/petstore/R/R/any_of_pig.R b/samples/client/petstore/R/R/any_of_pig.R index 955861d965..404b710472 100644 --- a/samples/client/petstore/R/R/any_of_pig.R +++ b/samples/client/petstore/R/R/any_of_pig.R @@ -1,11 +1,3 @@ -#' 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. -#' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title AnyOfPig #' @@ -50,6 +42,18 @@ AnyOfPig <- R6::R6Class( #' #' @description #' Deserialize JSON string into an instance of AnyOfPig. + #' An alias to the method `fromJSON`. + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPig. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of AnyOfPig. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPig. #' #' @param input The input JSON. #' @return An instance of AnyOfPig. @@ -152,7 +156,29 @@ AnyOfPig <- R6::R6Class( ) jsoncontent <- paste(jsoncontent, collapse = ",") as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +#AnyOfPig$unlock() +# +## Below is an example to define the print fnuction +#AnyOfPig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#AnyOfPig$lock() diff --git a/samples/client/petstore/R/R/any_of_primitive_type_test.R b/samples/client/petstore/R/R/any_of_primitive_type_test.R new file mode 100644 index 0000000000..374aa8c605 --- /dev/null +++ b/samples/client/petstore/R/R/any_of_primitive_type_test.R @@ -0,0 +1,202 @@ +#' @docType class +#' @title AnyOfPrimitiveTypeTest +#' +#' @description AnyOfPrimitiveTypeTest Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +AnyOfPrimitiveTypeTest <- R6::R6Class( + "AnyOfPrimitiveTypeTest", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("character", "integer"), + #' Initialize a new AnyOfPrimitiveTypeTest. + #' + #' @description + #' Initialize a new AnyOfPrimitiveTypeTest. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "character", "integer" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "character") { + self$actual_instance <- instance + self$actual_type <- "character" + } else if (get(class(instance)[[1]], pos = -1)$classname == "integer") { + self$actual_instance <- instance + self$actual_type <- "integer" + } else { + stop(paste("Failed to initialize AnyOfPrimitiveTypeTest with oneOf schemas character, integer. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPrimitiveTypeTest. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of AnyOfPrimitiveTypeTest. + #' + #' @param input The input JSON. + #' @return An instance of AnyOfPrimitiveTypeTest. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + integer_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "integer") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "integer", typeof(instance))) + } + instance_type <- "integer" + matched_schemas <- append(matched_schemas, "integer") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(integer_result["error"])) { + error_messages <- append(error_messages, integer_result["message"]) + } + + character_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "character") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "character", typeof(instance))) + } + instance_type <- "character" + matched_schemas <- append(matched_schemas, "character") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(character_result["error"])) { + error_messages <- append(error_messages, character_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into AnyOfPrimitiveTypeTest with oneOf schemas character, integer.") + } else { + # no match + stop(paste("No match found when deserializing the payload into AnyOfPrimitiveTypeTest with oneOf schemas character, integer. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize AnyOfPrimitiveTypeTest to JSON string. + #' + #' @description + #' Serialize AnyOfPrimitiveTypeTest to JSON string. + #' + #' @return JSON string representation of the AnyOfPrimitiveTypeTest. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize AnyOfPrimitiveTypeTest to JSON. + #' + #' @description + #' Serialize AnyOfPrimitiveTypeTest to JSON. + #' + #' @return JSON representation of the AnyOfPrimitiveTypeTest. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to AnyOfPrimitiveTypeTest. + #' + #' @description + #' Validate the input JSON with respect to AnyOfPrimitiveTypeTest and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#AnyOfPrimitiveTypeTest$unlock() +# +## Below is an example to define the print fnuction +#AnyOfPrimitiveTypeTest$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#AnyOfPrimitiveTypeTest$lock() + diff --git a/samples/client/petstore/R/R/api_client.R b/samples/client/petstore/R/R/api_client.R index 568943a6bd..cd0958b02d 100644 --- a/samples/client/petstore/R/R/api_client.R +++ b/samples/client/petstore/R/R/api_client.R @@ -5,7 +5,6 @@ #' The version of the OpenAPI document: 1.0.0 #' Generated by: https://openapi-generator.tech #' - #' ApiClient Class #' #' Generic API client for OpenAPI client library builds. @@ -29,13 +28,21 @@ #' @field password Password for HTTP basic authentication #' @field api_keys API keys #' @field access_token Access token +#' @field oauth_client_id OAuth client ID +#' @field oauth_secret OAuth secret +#' @field oauth_refresh_token OAuth refresh token +#' @field oauth_flow_type OAuth flow type +#' @field oauth_authorization_url Authoriziation URL +#' @field oauth_token_url Token URL +#' @field oauth_pkce Boolean flag to enable PKCE +#' @field bearer_token Bearer token #' @field timeout Default timeout in seconds #' @field retry_status_codes vector of status codes to retry #' @field max_retry_attempts maximum number of retries for the status codes #' @importFrom httr add_headers accept timeout content #' @importFrom rlang abort #' @export -ApiClient <- R6::R6Class( +ApiClient <- R6::R6Class( "ApiClient", public = list( # base path of all requests @@ -52,6 +59,23 @@ ApiClient <- R6::R6Class( api_keys = NULL, # Access token access_token = NULL, + # OAuth2 client ID + oauth_client_id = NULL, + # OAuth2 secret + oauth_secret = NULL, + # OAuth2 refresh token + oauth_refresh_token = NULL, + # OAuth2 + # Flow type + oauth_flow_type = "implicit", + # Authoriziation URL + oauth_authorization_url = "http://petstore.swagger.io/api/oauth/dialog", + # Token URL + oauth_token_url = "", + # Enable PKCE? + oauth_pkce = TRUE, + # Bearer token + bearer_token = NULL, # Time Out (seconds) timeout = NULL, # Vector of status codes to retry @@ -70,6 +94,7 @@ ApiClient <- R6::R6Class( #' @param password Password. #' @param api_keys API keys. #' @param access_token Access token. + #' @param bearer_token Bearer token. #' @param timeout Timeout. #' @param retry_status_codes Status codes for retry. #' @param max_retry_attempts Maxmium number of retry. @@ -77,7 +102,7 @@ ApiClient <- R6::R6Class( initialize = function(base_path = NULL, user_agent = NULL, default_headers = NULL, username = NULL, password = NULL, api_keys = NULL, - access_token = NULL, timeout = NULL, + access_token = NULL, bearer_token = NULL, timeout = NULL, retry_status_codes = NULL, max_retry_attempts = NULL) { if (!is.null(base_path)) { self$base_path <- base_path @@ -99,6 +124,10 @@ ApiClient <- R6::R6Class( self$access_token <- access_token } + if (!is.null(bearer_token)) { + self$bearer_token <- bearer_token + } + if (!is.null(api_keys)) { self$api_keys <- api_keys } else { @@ -130,15 +159,23 @@ ApiClient <- R6::R6Class( #' @param method HTTP method. #' @param query_params The query parameters. #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters for uploading files. + #' @param accepts The list of Accept headers. + #' @param content_types The list of Content-Type headers. #' @param body The HTTP request body. #' @param stream_callback Callback function to process the data stream #' @param ... Other optional arguments. #' @return HTTP response #' @export - CallApi = function(url, method, query_params, header_params, body, stream_callback = NULL, ...) { + CallApi = function(url, method, query_params, header_params, form_params, + file_params, accepts, content_types, + body, stream_callback = NULL, ...) { - resp <- self$Execute(url, method, query_params, header_params, body, stream_callback = stream_callback, ...) - status_code <- httr::status_code(resp) + resp <- self$Execute(url, method, query_params, header_params, + form_params, file_params, + accepts, content_types, + body, stream_callback = stream_callback, ...) if (is.null(self$max_retry_attempts)) { self$max_retry_attempts <- 3 @@ -147,10 +184,11 @@ ApiClient <- R6::R6Class( if (!is.null(self$retry_status_codes)) { for (i in 1 : self$max_retry_attempts) { - if (status_code %in% self$retry_status_codes) { + if (resp$status_code %in% self$retry_status_codes) { Sys.sleep((2 ^ i) + stats::runif(n = 1, min = 0, max = 1)) - resp <- self$Execute(url, method, query_params, header_params, body, stream_callback = stream_callback, ...) - status_code <- httr::status_code(resp) + resp <- self$Execute(url, method, query_params, header_params, + form_params, file_params, accepts, content_types, + body, stream_callback = stream_callback, ...) } else { break } @@ -168,12 +206,19 @@ ApiClient <- R6::R6Class( #' @param method HTTP method. #' @param query_params The query parameters. #' @param header_params The header parameters. + #' @param form_params The form parameters. + #' @param file_params The form parameters for uploading files. + #' @param accepts The list of Accept headers + #' @param content_types The list of Content-Type headers #' @param body The HTTP request body. #' @param stream_callback Callback function to process data stream #' @param ... Other optional arguments. #' @return HTTP response #' @export - Execute = function(url, method, query_params, header_params, body, stream_callback = NULL, ...) { + Execute = function(url, method, query_params, header_params, + form_params, file_params, + accepts, content_types, + body, stream_callback = NULL, ...) { headers <- httr::add_headers(c(header_params, self$default_headers)) http_timeout <- NULL @@ -181,82 +226,99 @@ ApiClient <- R6::R6Class( http_timeout <- httr::timeout(self$timeout) } - if (method == "GET") { - if (typeof(stream_callback) == "closure") { + # set HTTP accept header + accept = self$select_header(accepts) + if (!is.null(accept)) { + headers['Accept'] = accept + } + + # set HTTP content-type header + content_type = self$select_header(content_types) + if (!is.null(content_type)) { + headers['Content-Type'] = content_type + } + + if (typeof(stream_callback) == "closure") { # stream data + if (method == "GET") { httr::GET(url, query = query_params, headers, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::GET(url, query = query_params, headers, http_timeout, - httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "POST") { - if (typeof(stream_callback) == "closure") { + } else if (method == "POST") { httr::POST(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::POST(url, query = query_params, headers, body = body, - httr::content_type("application/json"), http_timeout, - httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "PUT") { - if (typeof(stream_callback) == "closure") { + } else if (method == "PUT") { httr::PUT(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::PUT(url, query = query_params, headers, body = body, - httr::content_type("application/json"), http_timeout, - http_timeout, httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "PATCH") { - if (typeof(stream_callback) == "closure") { + } else if (method == "PATCH") { httr::PATCH(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::PATCH(url, query = query_params, headers, body = body, - httr::content_type("application/json"), http_timeout, - http_timeout, httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "HEAD") { - if (typeof(stream_callback) == "closure") { + } else if (method == "HEAD") { httr::HEAD(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) - } else { - httr::HEAD(url, query = query_params, headers, http_timeout, - http_timeout, httr::user_agent(self$`user_agent`), ...) - } - } else if (method == "DELETE") { - if (typeof(stream_callback) == "closure") { + } else if (method == "DELETE") { httr::DELETE(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), write_stream(stream_callback), ...) } else { - httr::DELETE(url, query = query_params, headers, http_timeout, - http_timeout, httr::user_agent(self$`user_agent`), ...) + err_msg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`." + rlang::abort(message = err_msg, + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, reason = err_msg)) } - } else { - err_msg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`." - rlang::abort(message = err_msg, - .subclass = "ApiException", - ApiException = ApiException$new(status = 0, reason = err_msg)) + } else { # no streaming + if (method == "GET") { + httr_response <- httr::GET(url, query = query_params, headers, http_timeout, + httr::user_agent(self$`user_agent`), ...) + } else if (method == "POST") { + httr_response <- httr::POST(url, query = query_params, headers, body = body, + httr::content_type("application/json"), http_timeout, + httr::user_agent(self$`user_agent`), ...) + } else if (method == "PUT") { + httr_response <- httr::PUT(url, query = query_params, headers, body = body, + httr::content_type("application/json"), http_timeout, + http_timeout, httr::user_agent(self$`user_agent`), ...) + } else if (method == "PATCH") { + httr_response <- httr::PATCH(url, query = query_params, headers, body = body, + httr::content_type("application/json"), http_timeout, + http_timeout, httr::user_agent(self$`user_agent`), ...) + } else if (method == "HEAD") { + httr_response <- httr::HEAD(url, query = query_params, headers, http_timeout, + http_timeout, httr::user_agent(self$`user_agent`), ...) + } else if (method == "DELETE") { + httr_response <- httr::DELETE(url, query = query_params, headers, http_timeout, + http_timeout, httr::user_agent(self$`user_agent`), ...) + } else { + err_msg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`." + rlang::abort(message = err_msg, + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, reason = err_msg)) + } + + # return ApiResponse + api_response <- ApiResponse$new() + api_response$status_code <- httr::status_code(httr_response) + api_response$status_code_desc <- httr::http_status(httr_response)$reason + api_response$response <- httr::content(httr_response, "text", encoding = "UTF-8") + api_response$headers <- httr::headers(httr_response) + + api_response } }, - #' Deserialize the content of api response to the given type. + #' Deserialize the content of API response to the given type. #' #' @description - #' Deserialize the content of api response to the given type. + #' Deserialize the content of API response to the given type. #' - #' @param resp Response object. + #' @param raw_response Raw response. #' @param return_type R return type. #' @param pkg_env Package environment. #' @return Deserialized object. #' @export - deserialize = function(resp, return_type, pkg_env) { - resp_obj <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8")) + deserialize = function(raw_response, return_type, pkg_env) { + resp_obj <- jsonlite::fromJSON(raw_response) self$deserializeObj(resp_obj, return_type, pkg_env) }, - #' Deserialize the response from jsonlite object based on the given type #' #' @description @@ -307,6 +369,20 @@ ApiClient <- R6::R6Class( # To handle model objects which are not array or map containers. Ex:"Pet" return_type <- get(return_type, envir = as.environment(pkg_env)) return_obj <- return_type$new() + # check if discriminator is defined + if (!is.null(return_obj$`_discriminator_property_name`)) { + data_type <- return_obj$`_discriminator_property_name` + # use discriminator mapping if provided + if (!is.null(return_obj$`_discriminator_mapping_name`)) { + data_type <- (return_obj$`_discriminator_mapping_name`)[[obj[[data_type]]]] + } else { + # no mapping provided, use the value directly + data_type <- obj[[data_type]] + } + # create an object of the mapped type (e.g. Cat) + return_type <- get(data_type, envir = as.environment(pkg_env)) + return_obj <- return_type$new() + } return_obj$fromJSON( jsonlite::toJSON(obj, digits = NA, auto_unbox = TRUE) ) @@ -315,6 +391,30 @@ ApiClient <- R6::R6Class( return_obj <- obj } return_obj + }, + #' Return a propery header (for accept or content-type). + #' + #' @description + #' Return a propery header (for accept or content-type). If JSON-related MIME is found, + #' return it. Otherwise, return the first one, if any. + #' + #' @param headers A list of headers + #' @return A header (e.g. 'application/json') + #' @export + select_header = function(headers) { + if (length(headers) == 0) { + return(invisible(NULL)) + } else { + for (header in headers) { + if (str_detect(header, "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")) { + # return JSON-related MIME + return(header) + } + } + + # not json mime type, simply return the first one + return(headers[1]) + } } ) ) diff --git a/samples/client/petstore/R/R/api_exception.R b/samples/client/petstore/R/R/api_exception.R index 41bee0bb20..f31f27858b 100644 --- a/samples/client/petstore/R/R/api_exception.R +++ b/samples/client/petstore/R/R/api_exception.R @@ -5,7 +5,6 @@ #' The version of the OpenAPI document: 1.0.0 #' Generated by: https://openapi-generator.tech #' - #' @docType class #' @title ApiException #' @description ApiException Class @@ -14,7 +13,7 @@ #' @field reason Reason of the ApiException #' @field body Body of the http response #' @field headers Headers of the http response -#' @field errorObject error object type +#' @field error_object error object type #' @export ApiException <- R6::R6Class( "ApiException", @@ -23,7 +22,7 @@ ApiException <- R6::R6Class( reason = NULL, body = NULL, headers = NULL, - errorObject = NULL, + error_object = NULL, #' Initialize a new ApiException class. #' #' @description @@ -36,20 +35,20 @@ ApiException <- R6::R6Class( initialize = function(status = NULL, reason = NULL, http_response = NULL) { if (!is.null(http_response)) { self$status <- http_response$status_code - errorMsg <- toString(content(http_response)) - if (errorMsg == "") { + errorMsg <- http_response$response + if (is.null(errorMsg) || errorMsg == "") { errorMsg <- "Api exception encountered. No details given." } self$body <- errorMsg self$headers <- http_response$headers - self$reason <- httr::http_status(http_response)$reason - self$errorObject <- ModelApiResponse$new()$fromJSONString(content(http_response, "text")) + self$reason <- http_response$http_status_desc + self$error_object <- ModelApiResponse$new()$fromJSONString(http_response$response) } else { self$status <- status self$reason <- reason self$body <- NULL self$headers <- NULL - self$errorObject <- NULL + self$error_object <- NULL } }, #' Returns the string format of ApiException. @@ -73,9 +72,9 @@ ApiException <- R6::R6Class( errorMsg <- paste(errorMsg, "Body : ", "\n", sep = "") errorMsg <- paste(errorMsg, self$body, "\n") } - if (!is.null(self$errorObject)) { + if (!is.null(self$error_object)) { errorMsg <- paste(errorMsg, "Error object : ", "\n", sep = "") - errorMsg <- paste(errorMsg, self$errorObject$toJSONString(), "\n") + errorMsg <- paste(errorMsg, self$error_object$toJSONString(), "\n") } errorMsg } diff --git a/samples/client/petstore/R/R/api_response.R b/samples/client/petstore/R/R/api_response.R index 2362fd4e46..70431ae7e5 100644 --- a/samples/client/petstore/R/R/api_response.R +++ b/samples/client/petstore/R/R/api_response.R @@ -5,19 +5,24 @@ #' The version of the OpenAPI document: 1.0.0 #' Generated by: https://openapi-generator.tech #' - #' @docType class #' @title ApiResponse #' @description ApiResponse Class #' @format An \code{R6Class} generator object #' @field content The deserialized response body. #' @field response The raw response from the endpoint. +#' @field status_code The HTTP response status code. +#' @field status_code_desc The brief descriptoin of the HTTP response status code. +#' @field headers The HTTP response headers. #' @export ApiResponse <- R6::R6Class( "ApiResponse", public = list( content = NULL, response = NULL, + status_code = NULL, + status_code_desc = NULL, + headers = NULL, #' Initialize a new ApiResponse class. #' #' @description @@ -25,10 +30,20 @@ ApiResponse <- R6::R6Class( #' #' @param content The deserialized response body. #' @param response The raw response from the endpoint. + #' @param status_code The HTTP response status code. + #' @param status_code_desc The brief description of the HTTP response status code. + #' @param headers The HTTP response headers. #' @export - initialize = function(content, response) { + initialize = function(content = NULL, + response = NULL, + status_code = NULL, + status_code_desc = NULL, + headers = NULL) { self$content <- content self$response <- response + self$status_code <- status_code + self$status_code_desc <- status_code_desc + self$headers <- headers } ) ) diff --git a/samples/client/petstore/R/R/basque_pig.R b/samples/client/petstore/R/R/basque_pig.R index b948ad4a56..2335bbe37c 100644 --- a/samples/client/petstore/R/R/basque_pig.R +++ b/samples/client/petstore/R/R/basque_pig.R @@ -1,17 +1,16 @@ -#' OpenAPI Petstore +#' Create a new BasquePig #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' BasquePig Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title BasquePig #' @description BasquePig Class #' @format An \code{R6Class} generator object #' @field className character #' @field color character +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -20,6 +19,8 @@ BasquePig <- R6::R6Class( public = list( `className` = NULL, `color` = NULL, + `_field_list` = c("className", "color"), + `additional_properties` = list(), #' Initialize a new BasquePig class. #' #' @description @@ -27,11 +28,10 @@ BasquePig <- R6::R6Class( #' #' @param className className #' @param color color + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `className`, `color`, ... - ) { + initialize = function(`className`, `color`, additional_properties = NULL, ...) { if (!missing(`className`)) { stopifnot(is.character(`className`), length(`className`) == 1) self$`className` <- `className` @@ -40,6 +40,11 @@ BasquePig <- R6::R6Class( stopifnot(is.character(`color`), length(`color`) == 1) self$`color` <- `color` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -58,6 +63,9 @@ BasquePig <- R6::R6Class( BasquePigObject[["color"]] <- self$`color` } + for (key in names(self$additional_properties)) { + BasquePigObject[[key]] <- self$additional_properties[[key]] + } BasquePigObject }, @@ -77,6 +85,13 @@ BasquePig <- R6::R6Class( if (!is.null(this_object$`color`)) { self$`color` <- this_object$`color` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -106,7 +121,12 @@ BasquePig <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of BasquePig #' @@ -120,6 +140,13 @@ BasquePig <- R6::R6Class( this_object <- jsonlite::fromJSON(input_json) self$`className` <- this_object$`className` self$`color` <- this_object$`color` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to BasquePig @@ -153,7 +180,70 @@ BasquePig <- R6::R6Class( #' @export toString = function() { self$toJSONString() - } - ) -) + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + # check if the required `color` is null + if (is.null(self$`color`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + # check if the required `color` is null + if (is.null(self$`color`)) { + invalid_fields["color"] <- "Non-nullable required field `color` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# BasquePig$unlock() +# +## Below is an example to define the print fnuction +# BasquePig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# BasquePig$lock() diff --git a/samples/client/petstore/R/R/cat.R b/samples/client/petstore/R/R/cat.R index 42772a1cac..60d417950b 100644 --- a/samples/client/petstore/R/R/cat.R +++ b/samples/client/petstore/R/R/cat.R @@ -1,11 +1,8 @@ -#' OpenAPI Petstore +#' Create a new Cat #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' Cat Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title Cat #' @description Cat Class @@ -13,6 +10,8 @@ #' @field className character #' @field color character [optional] #' @field declawed character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -23,6 +22,8 @@ Cat <- R6::R6Class( `className` = NULL, `color` = NULL, `declawed` = NULL, + `_field_list` = c("className", "color", "declawed"), + `additional_properties` = list(), #' Initialize a new Cat class. #' #' @description @@ -31,11 +32,10 @@ Cat <- R6::R6Class( #' @param className className #' @param color color. Default to "red". #' @param declawed declawed + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `className`, `color` = "red", `declawed` = NULL, ... - ) { + initialize = function(`className`, `color` = "red", `declawed` = NULL, additional_properties = NULL, ...) { if (!missing(`className`)) { stopifnot(is.character(`className`), length(`className`) == 1) self$`className` <- `className` @@ -48,6 +48,11 @@ Cat <- R6::R6Class( stopifnot(is.logical(`declawed`), length(`declawed`) == 1) self$`declawed` <- `declawed` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -70,6 +75,9 @@ Cat <- R6::R6Class( CatObject[["declawed"]] <- self$`declawed` } + for (key in names(self$additional_properties)) { + CatObject[[key]] <- self$additional_properties[[key]] + } CatObject }, @@ -92,6 +100,13 @@ Cat <- R6::R6Class( if (!is.null(this_object$`declawed`)) { self$`declawed` <- this_object$`declawed` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -129,7 +144,12 @@ Cat <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of Cat #' @@ -144,6 +164,13 @@ Cat <- R6::R6Class( self$`className` <- this_object$`className` self$`color` <- this_object$`color` self$`declawed` <- this_object$`declawed` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to Cat @@ -171,7 +198,60 @@ Cat <- R6::R6Class( #' @export toString = function() { self$toJSONString() - } - ) -) + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Cat$unlock() +# +## Below is an example to define the print fnuction +# Cat$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Cat$lock() diff --git a/samples/client/petstore/R/R/cat_all_of.R b/samples/client/petstore/R/R/cat_all_of.R index 74b0172caf..c3969fc055 100644 --- a/samples/client/petstore/R/R/cat_all_of.R +++ b/samples/client/petstore/R/R/cat_all_of.R @@ -1,16 +1,15 @@ -#' OpenAPI Petstore +#' Create a new CatAllOf #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' CatAllOf Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title CatAllOf #' @description CatAllOf Class #' @format An \code{R6Class} generator object #' @field declawed character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -18,21 +17,27 @@ CatAllOf <- R6::R6Class( "CatAllOf", public = list( `declawed` = NULL, + `_field_list` = c("declawed"), + `additional_properties` = list(), #' Initialize a new CatAllOf class. #' #' @description #' Initialize a new CatAllOf class. #' #' @param declawed declawed + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `declawed` = NULL, ... - ) { + initialize = function(`declawed` = NULL, additional_properties = NULL, ...) { if (!is.null(`declawed`)) { stopifnot(is.logical(`declawed`), length(`declawed`) == 1) self$`declawed` <- `declawed` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -47,6 +52,9 @@ CatAllOf <- R6::R6Class( CatAllOfObject[["declawed"]] <- self$`declawed` } + for (key in names(self$additional_properties)) { + CatAllOfObject[[key]] <- self$additional_properties[[key]] + } CatAllOfObject }, @@ -63,6 +71,13 @@ CatAllOf <- R6::R6Class( if (!is.null(this_object$`declawed`)) { self$`declawed` <- this_object$`declawed` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -84,7 +99,12 @@ CatAllOf <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of CatAllOf #' @@ -97,6 +117,13 @@ CatAllOf <- R6::R6Class( fromJSONString = function(input_json) { this_object <- jsonlite::fromJSON(input_json) self$`declawed` <- this_object$`declawed` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to CatAllOf @@ -118,7 +145,50 @@ CatAllOf <- R6::R6Class( #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +# CatAllOf$unlock() +# +## Below is an example to define the print fnuction +# CatAllOf$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# CatAllOf$lock() diff --git a/samples/client/petstore/R/R/category.R b/samples/client/petstore/R/R/category.R index 39d69c4b73..2de263a568 100644 --- a/samples/client/petstore/R/R/category.R +++ b/samples/client/petstore/R/R/category.R @@ -1,17 +1,16 @@ -#' OpenAPI Petstore +#' Create a new Category #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' A category for a pet #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title Category #' @description Category Class #' @format An \code{R6Class} generator object #' @field id integer [optional] #' @field name character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -20,6 +19,8 @@ Category <- R6::R6Class( public = list( `id` = NULL, `name` = NULL, + `_field_list` = c("id", "name"), + `additional_properties` = list(), #' Initialize a new Category class. #' #' @description @@ -27,11 +28,10 @@ Category <- R6::R6Class( #' #' @param id id #' @param name name + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `id` = NULL, `name` = NULL, ... - ) { + initialize = function(`id` = NULL, `name` = NULL, additional_properties = NULL, ...) { if (!is.null(`id`)) { stopifnot(is.numeric(`id`), length(`id`) == 1) self$`id` <- `id` @@ -40,6 +40,11 @@ Category <- R6::R6Class( stopifnot(is.character(`name`), length(`name`) == 1) self$`name` <- `name` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -58,6 +63,9 @@ Category <- R6::R6Class( CategoryObject[["name"]] <- self$`name` } + for (key in names(self$additional_properties)) { + CategoryObject[[key]] <- self$additional_properties[[key]] + } CategoryObject }, @@ -77,6 +85,13 @@ Category <- R6::R6Class( if (!is.null(this_object$`name`)) { self$`name` <- this_object$`name` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -106,7 +121,12 @@ Category <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of Category #' @@ -120,6 +140,13 @@ Category <- R6::R6Class( this_object <- jsonlite::fromJSON(input_json) self$`id` <- this_object$`id` self$`name` <- this_object$`name` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to Category @@ -141,7 +168,58 @@ Category <- R6::R6Class( #' @export toString = function() { self$toJSONString() - } - ) -) + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + if (!str_detect(self$`name`, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + if (!str_detect(self$`name`, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")) { + invalid_fields["name"] <- "Invalid value for `name`, must conform to the pattern ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Category$unlock() +# +## Below is an example to define the print fnuction +# Category$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Category$lock() diff --git a/samples/client/petstore/R/R/danish_pig.R b/samples/client/petstore/R/R/danish_pig.R index 3c16fc60df..737bfad4b9 100644 --- a/samples/client/petstore/R/R/danish_pig.R +++ b/samples/client/petstore/R/R/danish_pig.R @@ -1,17 +1,16 @@ -#' OpenAPI Petstore +#' Create a new DanishPig #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' DanishPig Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title DanishPig #' @description DanishPig Class #' @format An \code{R6Class} generator object #' @field className character #' @field size integer +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -20,6 +19,8 @@ DanishPig <- R6::R6Class( public = list( `className` = NULL, `size` = NULL, + `_field_list` = c("className", "size"), + `additional_properties` = list(), #' Initialize a new DanishPig class. #' #' @description @@ -27,11 +28,10 @@ DanishPig <- R6::R6Class( #' #' @param className className #' @param size size + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `className`, `size`, ... - ) { + initialize = function(`className`, `size`, additional_properties = NULL, ...) { if (!missing(`className`)) { stopifnot(is.character(`className`), length(`className`) == 1) self$`className` <- `className` @@ -40,6 +40,11 @@ DanishPig <- R6::R6Class( stopifnot(is.numeric(`size`), length(`size`) == 1) self$`size` <- `size` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -58,6 +63,9 @@ DanishPig <- R6::R6Class( DanishPigObject[["size"]] <- self$`size` } + for (key in names(self$additional_properties)) { + DanishPigObject[[key]] <- self$additional_properties[[key]] + } DanishPigObject }, @@ -77,6 +85,13 @@ DanishPig <- R6::R6Class( if (!is.null(this_object$`size`)) { self$`size` <- this_object$`size` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -106,7 +121,12 @@ DanishPig <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of DanishPig #' @@ -120,6 +140,13 @@ DanishPig <- R6::R6Class( this_object <- jsonlite::fromJSON(input_json) self$`className` <- this_object$`className` self$`size` <- this_object$`size` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to DanishPig @@ -153,7 +180,70 @@ DanishPig <- R6::R6Class( #' @export toString = function() { self$toJSONString() - } - ) -) + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + # check if the required `size` is null + if (is.null(self$`size`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + # check if the required `size` is null + if (is.null(self$`size`)) { + invalid_fields["size"] <- "Non-nullable required field `size` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# DanishPig$unlock() +# +## Below is an example to define the print fnuction +# DanishPig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# DanishPig$lock() diff --git a/samples/client/petstore/R/R/date.R b/samples/client/petstore/R/R/date.R new file mode 100644 index 0000000000..a26b7977d4 --- /dev/null +++ b/samples/client/petstore/R/R/date.R @@ -0,0 +1,288 @@ +#' Create a new Date +#' +#' @description +#' to test the model name `Date` +#' +#' @docType class +#' @title Date +#' @description Date Class +#' @format An \code{R6Class} generator object +#' @field className character +#' @field percent_description using \% in the description character [optional] +#' @field url_property character +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Date <- R6::R6Class( + "Date", + public = list( + `className` = NULL, + `percent_description` = NULL, + `url_property` = NULL, + `_field_list` = c("className", "percent_description", "url_property"), + `additional_properties` = list(), + #' Initialize a new Date class. + #' + #' @description + #' Initialize a new Date class. + #' + #' @param className className + #' @param url_property url_property + #' @param percent_description using \% in the description + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `url_property`, `percent_description` = NULL, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!missing(`url_property`)) { + stopifnot(is.character(`url_property`), length(`url_property`) == 1) + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", `url_property`)) + } + self$`url_property` <- `url_property` + } + if (!is.null(`percent_description`)) { + stopifnot(is.character(`percent_description`), length(`percent_description`) == 1) + self$`percent_description` <- `percent_description` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Date in JSON format + #' @export + toJSON = function() { + DateObject <- list() + if (!is.null(self$`className`)) { + DateObject[["className"]] <- + self$`className` + } + if (!is.null(self$`percent_description`)) { + DateObject[["percent_description"]] <- + self$`percent_description` + } + if (!is.null(self$`url_property`)) { + DateObject[["url_property"]] <- + self$`url_property` + } + for (key in names(self$additional_properties)) { + DateObject[[key]] <- self$additional_properties[[key]] + } + + DateObject + }, + #' Deserialize JSON string into an instance of Date + #' + #' @description + #' Deserialize JSON string into an instance of Date + #' + #' @param input_json the JSON input + #' @return the instance of Date + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + if (!is.null(this_object$`percent_description`)) { + self$`percent_description` <- this_object$`percent_description` + } + if (!is.null(this_object$`url_property`)) { + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(this_object$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", this_object$`url_property`)) + } + self$`url_property` <- this_object$`url_property` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Date in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + }, + if (!is.null(self$`percent_description`)) { + sprintf( + '"percent_description": + "%s" + ', + self$`percent_description` + ) + }, + if (!is.null(self$`url_property`)) { + sprintf( + '"url_property": + "%s" + ', + self$`url_property` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Date + #' + #' @description + #' Deserialize JSON string into an instance of Date + #' + #' @param input_json the JSON input + #' @return the instance of Date + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`className` <- this_object$`className` + self$`percent_description` <- this_object$`percent_description` + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(this_object$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", this_object$`url_property`)) + } + self$`url_property` <- this_object$`url_property` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Date + #' + #' @description + #' Validate JSON input with respect to Date and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Date: the required field `className` is missing.")) + } + # check the required field `url_property` + if (!is.null(input_json$`url_property`)) { + stopifnot(is.character(input_json$`url_property`), length(input_json$`url_property`) == 1) + # to validate URL. ref: https://stackoverflow.com/questions/73952024/url-validation-in-r + if (!stringr::str_detect(input_json$`url_property`, "(https?|ftp)://[^ /$.?#].[^\\s]*")) { + stop(paste("Error! Invalid URL:", input_json$`url_property`)) + } + } else { + stop(paste("The JSON input `", input, "` is invalid for Date: the required field `url_property` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Date + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + # check if the required `url_property` is null + if (is.null(self$`url_property`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + # check if the required `url_property` is null + if (is.null(self$`url_property`)) { + invalid_fields["url_property"] <- "Non-nullable required field `url_property` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Date$unlock() +# +## Below is an example to define the print fnuction +# Date$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Date$lock() + diff --git a/samples/client/petstore/R/R/dog.R b/samples/client/petstore/R/R/dog.R index dea850f765..67fb8a315e 100644 --- a/samples/client/petstore/R/R/dog.R +++ b/samples/client/petstore/R/R/dog.R @@ -1,11 +1,8 @@ -#' OpenAPI Petstore +#' Create a new Dog #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' Dog Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title Dog #' @description Dog Class @@ -13,6 +10,8 @@ #' @field className character #' @field color character [optional] #' @field breed character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -23,6 +22,8 @@ Dog <- R6::R6Class( `className` = NULL, `color` = NULL, `breed` = NULL, + `_field_list` = c("className", "color", "breed"), + `additional_properties` = list(), #' Initialize a new Dog class. #' #' @description @@ -31,11 +32,10 @@ Dog <- R6::R6Class( #' @param className className #' @param color color. Default to "red". #' @param breed breed + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `className`, `color` = "red", `breed` = NULL, ... - ) { + initialize = function(`className`, `color` = "red", `breed` = NULL, additional_properties = NULL, ...) { if (!missing(`className`)) { stopifnot(is.character(`className`), length(`className`) == 1) self$`className` <- `className` @@ -48,6 +48,11 @@ Dog <- R6::R6Class( stopifnot(is.character(`breed`), length(`breed`) == 1) self$`breed` <- `breed` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -70,6 +75,9 @@ Dog <- R6::R6Class( DogObject[["breed"]] <- self$`breed` } + for (key in names(self$additional_properties)) { + DogObject[[key]] <- self$additional_properties[[key]] + } DogObject }, @@ -92,6 +100,13 @@ Dog <- R6::R6Class( if (!is.null(this_object$`breed`)) { self$`breed` <- this_object$`breed` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -129,7 +144,12 @@ Dog <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of Dog #' @@ -144,6 +164,13 @@ Dog <- R6::R6Class( self$`className` <- this_object$`className` self$`color` <- this_object$`color` self$`breed` <- this_object$`breed` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to Dog @@ -171,7 +198,60 @@ Dog <- R6::R6Class( #' @export toString = function() { self$toJSONString() - } - ) -) + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Dog$unlock() +# +## Below is an example to define the print fnuction +# Dog$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Dog$lock() diff --git a/samples/client/petstore/R/R/dog_all_of.R b/samples/client/petstore/R/R/dog_all_of.R index 3d721bc4b8..ea44d583d7 100644 --- a/samples/client/petstore/R/R/dog_all_of.R +++ b/samples/client/petstore/R/R/dog_all_of.R @@ -1,16 +1,15 @@ -#' OpenAPI Petstore +#' Create a new DogAllOf #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' DogAllOf Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title DogAllOf #' @description DogAllOf Class #' @format An \code{R6Class} generator object #' @field breed character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -18,21 +17,27 @@ DogAllOf <- R6::R6Class( "DogAllOf", public = list( `breed` = NULL, + `_field_list` = c("breed"), + `additional_properties` = list(), #' Initialize a new DogAllOf class. #' #' @description #' Initialize a new DogAllOf class. #' #' @param breed breed + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `breed` = NULL, ... - ) { + initialize = function(`breed` = NULL, additional_properties = NULL, ...) { if (!is.null(`breed`)) { stopifnot(is.character(`breed`), length(`breed`) == 1) self$`breed` <- `breed` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -47,6 +52,9 @@ DogAllOf <- R6::R6Class( DogAllOfObject[["breed"]] <- self$`breed` } + for (key in names(self$additional_properties)) { + DogAllOfObject[[key]] <- self$additional_properties[[key]] + } DogAllOfObject }, @@ -63,6 +71,13 @@ DogAllOf <- R6::R6Class( if (!is.null(this_object$`breed`)) { self$`breed` <- this_object$`breed` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -84,7 +99,12 @@ DogAllOf <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of DogAllOf #' @@ -97,6 +117,13 @@ DogAllOf <- R6::R6Class( fromJSONString = function(input_json) { this_object <- jsonlite::fromJSON(input_json) self$`breed` <- this_object$`breed` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to DogAllOf @@ -118,7 +145,50 @@ DogAllOf <- R6::R6Class( #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +# DogAllOf$unlock() +# +## Below is an example to define the print fnuction +# DogAllOf$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# DogAllOf$lock() diff --git a/samples/client/petstore/R/R/fake_api.R b/samples/client/petstore/R/R/fake_api.R index d48ae15c56..b20d9bcd7f 100644 --- a/samples/client/petstore/R/R/fake_api.R +++ b/samples/client/petstore/R/R/fake_api.R @@ -5,15 +5,39 @@ #' The version of the OpenAPI document: 1.0.0 #' Generated by: https://openapi-generator.tech #' - #' @docType class #' @title Fake operations -#' @description petstore.Fake +#' @description FakeApi #' @format An \code{R6Class} generator object #' @field api_client Handles the client-server communication. #' #' @section Methods: #' \describe{ +#' \strong{ AddPetOptional } \emph{ Add a new pet to the store (optional body) } +#' +#' +#' \itemize{ +#' \item \emph{ @param } pet \link{Pet} +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 405 | Invalid input +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' #' \strong{ FakeDataFile } \emph{ test data_file to ensure it's escaped correctly } #' #' @@ -26,7 +50,59 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : User +#' \item return type : User +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ FakePathArray } \emph{ test array parameter in path } +#' +#' +#' \itemize{ +#' \item \emph{ @param } path_array list( character ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ FakeRegularExpression } \emph{ test regular expression to ensure no exception } +#' +#' +#' \itemize{ +#' \item \emph{ @param } reg_exp_test character +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ FakeSetQuery } \emph{ test set query parameter } +#' +#' +#' \itemize{ +#' \item \emph{ @param } set_dummy list( character ) +#' \item \emph{ @param } array_dummy list( character ) +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' #' \item response headers : #' #' \tabular{ll}{ @@ -38,32 +114,153 @@ #' #' @examples #' \dontrun{ +#' #################### AddPetOptional #################### +#' +#' library(petstore) +#' var_pet <- Pet$new() # Pet | Pet object that needs to be added to the store +#' +#' #Add a new pet to the store (optional body) +#' api_instance <- FakeApi$new() +#' +#' # Configure HTTP basic authorization: http_auth +#' api_instance$api_client$username <- Sys.getenv("USERNAME") +#' api_instance$api_client$password <- Sys.getenv("PASSWORD") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$AddPetOptional(pet = var_pet, data_file = "result.txt"), +#' +#' +#' api_instance$AddPetOptional(pet = var_pet), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `AddPetOptional`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' #' #################### FakeDataFile #################### #' #' library(petstore) -#' var.dummy <- "dummy_example" # character | dummy required parameter -#' var.var_data_file <- "var_data_file_example" # character | header data file +#' var_dummy <- "dummy_example" # character | dummy required parameter +#' var_var_data_file <- "var_data_file_example" # character | header data file #' #' #test data_file to ensure it's escaped correctly -#' api.instance <- FakeApi$new() +#' api_instance <- FakeApi$new() #' -#'result <- tryCatch( -#' api.instance$FakeDataFile(var.dummy, var_data_file=var.var_data_file), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$FakeDataFile(var_dummy, var_data_file = var_var_data_file, data_file = "result.txt"), +#' +#' +#' api_instance$FakeDataFile(var_dummy, var_data_file = var_var_data_file), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `FakeDataFile`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' +#' #################### FakePathArray #################### +#' +#' library(petstore) +#' var_path_array <- ["path_array_example"] # array[character] | dummy path parameter +#' +#' #test array parameter in path +#' api_instance <- FakeApi$new() +#' +#' result <- tryCatch( +#' +#' api_instance$FakePathArray(var_path_array), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `FakePathArray`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### FakeRegularExpression #################### +#' +#' library(petstore) +#' var_reg_exp_test <- "reg_exp_test_example" # character | dummy required parameter +#' +#' #test regular expression to ensure no exception +#' api_instance <- FakeApi$new() +#' +#' result <- tryCatch( +#' +#' api_instance$FakeRegularExpression(var_reg_exp_test), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `FakeRegularExpression`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' +#' #################### FakeSetQuery #################### +#' +#' library(petstore) +#' var_set_dummy <- ["set_dummy_example"] # set[character] | set query +#' var_array_dummy <- ["array_dummy_example"] # array[character] | array query +#' +#' #test set query parameter +#' api_instance <- FakeApi$new() +#' +#' result <- tryCatch( +#' +#' api_instance$FakeSetQuery(var_set_dummy, var_array_dummy), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `FakeSetQuery`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data +#' +#' #' } #' @importFrom R6 R6Class #' @importFrom base64enc base64encode @@ -87,28 +284,143 @@ FakeApi <- R6::R6Class( self$api_client <- ApiClient$new() } }, + #' Add a new pet to the store (optional body) + #' + #' @description + #' Add a new pet to the store (optional body) + #' + #' @param pet (optional) Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + AddPetOptional = function(pet = NULL, data_file = NULL, ...) { + local_var_response <- self$AddPetOptionalWithHttpInfo(pet, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Add a new pet to the store (optional body) + #' + #' @description + #' Add a new pet to the store (optional body) + #' + #' @param pet (optional) Pet object that needs to be added to the store + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + AddPetOptionalWithHttpInfo = function(pet = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + + if (!is.null(`pet`)) { + local_var_body <- `pet`$toJSONString() + } else { + body <- NULL + } + + local_var_url_path <- "/fake/test_optional_body_parameter" + # HTTP basic auth + if (!is.null(self$api_client$username) || !is.null(self$api_client$password)) { + header_params["Authorization"] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$api_client$username, self$api_client$password, sep = ":")))) + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json", "application/xml", "multipart/related") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "POST", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, #' test data_file to ensure it's escaped correctly #' #' @description #' test data_file to ensure it's escaped correctly #' #' @param dummy dummy required parameter - #' @param var_data_file (optional)header data file + #' @param var_data_file (optional) header data file #' @param data_file (optional) name of the data file to save the result #' @param ... Other optional arguments #' @return User #' @export - FakeDataFile = function(dummy, var_data_file=NULL, data_file = NULL, ...) { - api_response <- self$FakeDataFileWithHttpInfo(dummy, var_data_file, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + FakeDataFile = function(dummy, var_data_file = NULL, data_file = NULL, ...) { + local_var_response <- self$FakeDataFileWithHttpInfo(dummy, var_data_file, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' test data_file to ensure it's escaped correctly @@ -122,10 +434,15 @@ FakeApi <- R6::R6Class( #' @param ... Other optional arguments #' @return API response (User) with additional information such as HTTP status code, headers #' @export - FakeDataFileWithHttpInfo = function(dummy, var_data_file=NULL, data_file = NULL, ...) { + FakeDataFileWithHttpInfo = function(dummy, var_data_file = NULL, data_file = NULL, ...) { args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`dummy`)) { rlang::abort(message = "Missing required parameter `dummy`.", @@ -134,55 +451,406 @@ FakeApi <- R6::R6Class( reason = "Missing required parameter `dummy`.")) } - body <- NULL - url_path <- "/fake/data_file" - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + + header_params["dummy"] <- `dummy` + + header_params["data_file"] <- `var_data_file` + + local_var_url_path <- "/fake/data_file" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "User", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "User", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test array parameter in path + #' + #' @description + #' test array parameter in path + #' + #' @param path_array dummy path parameter + #' @param ... Other optional arguments + #' @return void + #' @export + FakePathArray = function(path_array, ...) { + local_var_response <- self$FakePathArrayWithHttpInfo(path_array, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test array parameter in path + #' + #' @description + #' test array parameter in path + #' + #' @param path_array dummy path parameter + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + FakePathArrayWithHttpInfo = function(path_array, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`path_array`)) { + rlang::abort(message = "Missing required parameter `path_array`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `path_array`.")) + } + + + local_var_url_path <- "/fake/path_array/{path_array}/testing" + if (!missing(`path_array`)) { + local_var_url_path <- gsub("\\{path_array\\}", paste(URLencode(as.character(`path_array`), reserved = TRUE), collapse= ",", sep=""), local_var_url_path) + } + + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test regular expression to ensure no exception + #' + #' @description + #' test regular expression to ensure no exception + #' + #' @param reg_exp_test dummy required parameter + #' @param ... Other optional arguments + #' @return void + #' @export + FakeRegularExpression = function(reg_exp_test, ...) { + local_var_response <- self$FakeRegularExpressionWithHttpInfo(reg_exp_test, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test regular expression to ensure no exception + #' + #' @description + #' test regular expression to ensure no exception + #' + #' @param reg_exp_test dummy required parameter + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + FakeRegularExpressionWithHttpInfo = function(reg_exp_test, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`reg_exp_test`)) { + rlang::abort(message = "Missing required parameter `reg_exp_test`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `reg_exp_test`.")) + } + + if (!str_detect(`reg_exp_test`, "^[A-Za-z0-9_]{1,15}$")) { + rlang::abort(message = "Invalid value for `reg_exp_test` when calling FakeApi$FakeRegularExpression, must conform to the pattern ^[A-Za-z0-9_]{1,15}$.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `reg_exp_test` when calling FakeApi$FakeRegularExpression, must conform to the pattern ^[A-Za-z0-9_]{1,15}$.")) + } + + header_params["reg_exp_test"] <- `reg_exp_test` + + local_var_url_path <- "/fake/regular_expression" + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' test set query parameter + #' + #' @description + #' test set query parameter + #' + #' @param set_dummy set query + #' @param array_dummy array query + #' @param ... Other optional arguments + #' @return void + #' @export + FakeSetQuery = function(set_dummy, array_dummy, ...) { + local_var_response <- self$FakeSetQueryWithHttpInfo(set_dummy, array_dummy, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' test set query parameter + #' + #' @description + #' test set query parameter + #' + #' @param set_dummy set query + #' @param array_dummy array query + #' @param ... Other optional arguments + #' @return API response (void) with additional information such as HTTP status code, headers + #' @export + FakeSetQueryWithHttpInfo = function(set_dummy, array_dummy, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`set_dummy`)) { + rlang::abort(message = "Missing required parameter `set_dummy`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `set_dummy`.")) + } + + if (missing(`array_dummy`)) { + rlang::abort(message = "Missing required parameter `array_dummy`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `array_dummy`.")) + } + + + + # check if items are unique + if (!identical(`set_dummy`, unique(`set_dummy`))) { + rlang::abort(message = "Invalid value for `set_dummy` when calling FakeApi$FakeSetQuery. Items must be unique.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `set_dummy` when calling FakeApi$FakeSetQuery. Items must be unique.")) + } + # explore + for (query_item in `set_dummy`) { + query_params[["set_dummy"]] <- c(query_params[["set_dummy"]], list(`set_dummy` = query_item)) + } + + # explore + for (query_item in `array_dummy`) { + query_params[["array_dummy"]] <- c(query_params[["array_dummy"]], list(`array_dummy` = query_item)) + } + + local_var_url_path <- "/fake/set_query_parameter" + + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + ...) + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." + } + rlang::abort(message = error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } } ) diff --git a/samples/client/petstore/R/R/mammal.R b/samples/client/petstore/R/R/mammal.R new file mode 100644 index 0000000000..4b21d8564c --- /dev/null +++ b/samples/client/petstore/R/R/mammal.R @@ -0,0 +1,200 @@ +#' @docType class +#' @title Mammal +#' +#' @description Mammal Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Mammal <- R6::R6Class( + "Mammal", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("Whale", "Zebra"), + #' Initialize a new Mammal. + #' + #' @description + #' Initialize a new Mammal. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "Whale", "Zebra" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "Whale") { + self$actual_instance <- instance + self$actual_type <- "Whale" + } else if (get(class(instance)[[1]], pos = -1)$classname == "Zebra") { + self$actual_instance <- instance + self$actual_type <- "Zebra" + } else { + stop(paste("Failed to initialize Mammal with oneOf schemas Whale, Zebra. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of Mammal. + #' + #' @description + #' Deserialize JSON string into an instance of Mammal. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of Mammal. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of Mammal. + #' + #' @description + #' Deserialize JSON string into an instance of Mammal. + #' + #' @param input The input JSON. + #' @return An instance of Mammal. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + Whale_result <- tryCatch({ + Whale$public_methods$validateJSON(input) + Whale_instance <- Whale$new() + instance <- Whale_instance$fromJSON(input) + instance_type <- "Whale" + matched_schemas <- append(matched_schemas, "Whale") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(Whale_result["error"])) { + error_messages <- append(error_messages, Whale_result["message"]) + } + + Zebra_result <- tryCatch({ + Zebra$public_methods$validateJSON(input) + Zebra_instance <- Zebra$new() + instance <- Zebra_instance$fromJSON(input) + instance_type <- "Zebra" + matched_schemas <- append(matched_schemas, "Zebra") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(Zebra_result["error"])) { + error_messages <- append(error_messages, Zebra_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into Mammal with oneOf schemas Whale, Zebra.") + } else { + # no match + stop(paste("No match found when deserializing the payload into Mammal with oneOf schemas Whale, Zebra. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize Mammal to JSON string. + #' + #' @description + #' Serialize Mammal to JSON string. + #' + #' @return JSON string representation of the Mammal. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize Mammal to JSON. + #' + #' @description + #' Serialize Mammal to JSON. + #' + #' @return JSON representation of the Mammal. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to Mammal. + #' + #' @description + #' Validate the input JSON with respect to Mammal and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#Mammal$unlock() +# +## Below is an example to define the print fnuction +#Mammal$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#Mammal$lock() + diff --git a/samples/client/petstore/R/R/model_api_response.R b/samples/client/petstore/R/R/model_api_response.R index 1fa1c6ec49..03059bb522 100644 --- a/samples/client/petstore/R/R/model_api_response.R +++ b/samples/client/petstore/R/R/model_api_response.R @@ -1,11 +1,8 @@ -#' OpenAPI Petstore +#' Create a new ModelApiResponse #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' Describes the result of uploading an image resource #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title ModelApiResponse #' @description ModelApiResponse Class @@ -13,6 +10,8 @@ #' @field code integer [optional] #' @field type character [optional] #' @field message character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -22,6 +21,8 @@ ModelApiResponse <- R6::R6Class( `code` = NULL, `type` = NULL, `message` = NULL, + `_field_list` = c("code", "type", "message"), + `additional_properties` = list(), #' Initialize a new ModelApiResponse class. #' #' @description @@ -30,11 +31,10 @@ ModelApiResponse <- R6::R6Class( #' @param code code #' @param type type #' @param message message + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `code` = NULL, `type` = NULL, `message` = NULL, ... - ) { + initialize = function(`code` = NULL, `type` = NULL, `message` = NULL, additional_properties = NULL, ...) { if (!is.null(`code`)) { stopifnot(is.numeric(`code`), length(`code`) == 1) self$`code` <- `code` @@ -47,6 +47,11 @@ ModelApiResponse <- R6::R6Class( stopifnot(is.character(`message`), length(`message`) == 1) self$`message` <- `message` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -69,6 +74,9 @@ ModelApiResponse <- R6::R6Class( ModelApiResponseObject[["message"]] <- self$`message` } + for (key in names(self$additional_properties)) { + ModelApiResponseObject[[key]] <- self$additional_properties[[key]] + } ModelApiResponseObject }, @@ -91,6 +99,13 @@ ModelApiResponse <- R6::R6Class( if (!is.null(this_object$`message`)) { self$`message` <- this_object$`message` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -128,7 +143,12 @@ ModelApiResponse <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of ModelApiResponse #' @@ -143,6 +163,13 @@ ModelApiResponse <- R6::R6Class( self$`code` <- this_object$`code` self$`type` <- this_object$`type` self$`message` <- this_object$`message` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to ModelApiResponse @@ -164,7 +191,50 @@ ModelApiResponse <- R6::R6Class( #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +# ModelApiResponse$unlock() +# +## Below is an example to define the print fnuction +# ModelApiResponse$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# ModelApiResponse$lock() diff --git a/samples/client/petstore/R/R/nested_one_of.R b/samples/client/petstore/R/R/nested_one_of.R index cc9c338774..68b0db6b37 100644 --- a/samples/client/petstore/R/R/nested_one_of.R +++ b/samples/client/petstore/R/R/nested_one_of.R @@ -1,17 +1,16 @@ -#' OpenAPI Petstore +#' Create a new NestedOneOf #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' NestedOneOf Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title NestedOneOf #' @description NestedOneOf Class #' @format An \code{R6Class} generator object #' @field size integer [optional] #' @field nested_pig \link{Pig} [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -20,6 +19,8 @@ NestedOneOf <- R6::R6Class( public = list( `size` = NULL, `nested_pig` = NULL, + `_field_list` = c("size", "nested_pig"), + `additional_properties` = list(), #' Initialize a new NestedOneOf class. #' #' @description @@ -27,11 +28,10 @@ NestedOneOf <- R6::R6Class( #' #' @param size size #' @param nested_pig nested_pig + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `size` = NULL, `nested_pig` = NULL, ... - ) { + initialize = function(`size` = NULL, `nested_pig` = NULL, additional_properties = NULL, ...) { if (!is.null(`size`)) { stopifnot(is.numeric(`size`), length(`size`) == 1) self$`size` <- `size` @@ -40,6 +40,11 @@ NestedOneOf <- R6::R6Class( stopifnot(R6::is.R6(`nested_pig`)) self$`nested_pig` <- `nested_pig` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -58,6 +63,9 @@ NestedOneOf <- R6::R6Class( NestedOneOfObject[["nested_pig"]] <- self$`nested_pig`$toJSON() } + for (key in names(self$additional_properties)) { + NestedOneOfObject[[key]] <- self$additional_properties[[key]] + } NestedOneOfObject }, @@ -79,6 +87,13 @@ NestedOneOf <- R6::R6Class( nested_pig_object$fromJSON(jsonlite::toJSON(this_object$nested_pig, auto_unbox = TRUE, digits = NA)) self$`nested_pig` <- nested_pig_object } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -103,12 +118,17 @@ NestedOneOf <- R6::R6Class( '"nested_pig": %s ', - jsonlite::toJSON(self$`nested_pig`$toJSON(), auto_unbox=TRUE, digits = NA) + jsonlite::toJSON(self$`nested_pig`$toJSON(), auto_unbox = TRUE, digits = NA) ) } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of NestedOneOf #' @@ -122,6 +142,13 @@ NestedOneOf <- R6::R6Class( this_object <- jsonlite::fromJSON(input_json) self$`size` <- this_object$`size` self$`nested_pig` <- Pig$new()$fromJSON(jsonlite::toJSON(this_object$nested_pig, auto_unbox = TRUE, digits = NA)) + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to NestedOneOf @@ -143,7 +170,50 @@ NestedOneOf <- R6::R6Class( #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +# NestedOneOf$unlock() +# +## Below is an example to define the print fnuction +# NestedOneOf$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# NestedOneOf$lock() diff --git a/samples/client/petstore/R/R/one_of_primitive_type_test.R b/samples/client/petstore/R/R/one_of_primitive_type_test.R new file mode 100644 index 0000000000..d558c0eb50 --- /dev/null +++ b/samples/client/petstore/R/R/one_of_primitive_type_test.R @@ -0,0 +1,202 @@ +#' @docType class +#' @title OneOfPrimitiveTypeTest +#' +#' @description OneOfPrimitiveTypeTest Class +#' +#' @format An \code{R6Class} generator object +#' +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +OneOfPrimitiveTypeTest <- R6::R6Class( + "OneOfPrimitiveTypeTest", + public = list( + #' @field actual_instance the object stored in this instance. + actual_instance = NULL, + #' @field actual_type the type of the object stored in this instance. + actual_type = NULL, + #' @field one_of a list of types defined in the oneOf schema. + one_of = list("character", "integer"), + #' Initialize a new OneOfPrimitiveTypeTest. + #' + #' @description + #' Initialize a new OneOfPrimitiveTypeTest. + #' + #' @param instance an instance of the object defined in the oneOf schemas: "character", "integer" + #' @export + initialize = function(instance = NULL) { + if (is.null(instance)) { + # do nothing + } else if (get(class(instance)[[1]], pos = -1)$classname == "character") { + self$actual_instance <- instance + self$actual_type <- "character" + } else if (get(class(instance)[[1]], pos = -1)$classname == "integer") { + self$actual_instance <- instance + self$actual_type <- "integer" + } else { + stop(paste("Failed to initialize OneOfPrimitiveTypeTest with oneOf schemas character, integer. Provided class name: ", + get(class(instance)[[1]], pos = -1)$classname)) + } + }, + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of OneOfPrimitiveTypeTest. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' + #' @description + #' Deserialize JSON string into an instance of OneOfPrimitiveTypeTest. + #' + #' @param input The input JSON. + #' @return An instance of OneOfPrimitiveTypeTest. + #' @export + fromJSON = function(input) { + matched <- 0 # match counter + matched_schemas <- list() #names of matched schemas + error_messages <- list() + instance <- NULL + + integer_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "integer") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "integer", typeof(instance))) + } + instance_type <- "integer" + matched_schemas <- append(matched_schemas, "integer") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(integer_result["error"])) { + error_messages <- append(error_messages, integer_result["message"]) + } + + character_result <- tryCatch({ + instance <- jsonlite::fromJSON(input, simplifyVector = FALSE) + if (typeof(instance) != "character") { + stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "character", typeof(instance))) + } + instance_type <- "character" + matched_schemas <- append(matched_schemas, "character") + matched <- matched + 1 + }, + error = function(err) err + ) + + if (!is.null(character_result["error"])) { + error_messages <- append(error_messages, character_result["message"]) + } + + if (matched == 1) { + # successfully match exactly 1 schema specified in oneOf + self$actual_instance <- instance + self$actual_type <- instance_type + } else if (matched > 1) { + # more than 1 match + stop("Multiple matches found when deserializing the payload into OneOfPrimitiveTypeTest with oneOf schemas character, integer.") + } else { + # no match + stop(paste("No match found when deserializing the payload into OneOfPrimitiveTypeTest with oneOf schemas character, integer. Details: ", + paste(error_messages, collapse = ", "))) + } + + self + }, + #' Serialize OneOfPrimitiveTypeTest to JSON string. + #' + #' @description + #' Serialize OneOfPrimitiveTypeTest to JSON string. + #' + #' @return JSON string representation of the OneOfPrimitiveTypeTest. + #' @export + toJSONString = function() { + if (!is.null(self$actual_instance)) { + as.character(jsonlite::minify(self$actual_instance$toJSONString())) + } else { + NULL + } + }, + #' Serialize OneOfPrimitiveTypeTest to JSON. + #' + #' @description + #' Serialize OneOfPrimitiveTypeTest to JSON. + #' + #' @return JSON representation of the OneOfPrimitiveTypeTest. + #' @export + toJSON = function() { + if (!is.null(self$actual_instance)) { + self$actual_instance$toJSON() + } else { + NULL + } + }, + #' Validate the input JSON with respect to OneOfPrimitiveTypeTest. + #' + #' @description + #' Validate the input JSON with respect to OneOfPrimitiveTypeTest and + #' throw exception if invalid. + #' + #' @param input The input JSON. + #' @export + validateJSON = function(input) { + # backup current values + actual_instance_bak <- self$actual_instance + actual_type_bak <- self$actual_type + + # if it's not valid, an error will be thrown + self$fromJSON(input) + + # no error thrown, restore old values + self$actual_instance <- actual_instance_bak + self$actual_type <- actual_type_bak + }, + #' Returns the string representation of the instance. + #' + #' @description + #' Returns the string representation of the instance. + #' + #' @return The string representation of the instance. + #' @export + toString = function() { + jsoncontent <- c( + sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()), + sprintf('"actual_type": "%s"', self$actual_type), + sprintf('"one_of": "%s"', paste(unlist(self$one_of), collapse = ", ")) + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +#OneOfPrimitiveTypeTest$unlock() +# +## Below is an example to define the print fnuction +#OneOfPrimitiveTypeTest$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#OneOfPrimitiveTypeTest$lock() + diff --git a/samples/client/petstore/R/R/order.R b/samples/client/petstore/R/R/order.R index 29a0fcbf03..6f43799918 100644 --- a/samples/client/petstore/R/R/order.R +++ b/samples/client/petstore/R/R/order.R @@ -1,11 +1,8 @@ -#' OpenAPI Petstore +#' Create a new Order #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' An order for a pets from the pet store #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title Order #' @description Order Class @@ -14,8 +11,10 @@ #' @field petId integer [optional] #' @field quantity integer [optional] #' @field shipDate character [optional] -#' @field status character [optional] +#' @field status Order Status character [optional] #' @field complete character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -28,6 +27,8 @@ Order <- R6::R6Class( `shipDate` = NULL, `status` = NULL, `complete` = NULL, + `_field_list` = c("id", "petId", "quantity", "shipDate", "status", "complete"), + `additional_properties` = list(), #' Initialize a new Order class. #' #' @description @@ -39,11 +40,10 @@ Order <- R6::R6Class( #' @param shipDate shipDate #' @param status Order Status #' @param complete complete. Default to FALSE. + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `id` = NULL, `petId` = NULL, `quantity` = NULL, `shipDate` = NULL, `status` = NULL, `complete` = FALSE, ... - ) { + initialize = function(`id` = NULL, `petId` = NULL, `quantity` = NULL, `shipDate` = NULL, `status` = NULL, `complete` = FALSE, additional_properties = NULL, ...) { if (!is.null(`id`)) { stopifnot(is.numeric(`id`), length(`id`) == 1) self$`id` <- `id` @@ -61,6 +61,9 @@ Order <- R6::R6Class( self$`shipDate` <- `shipDate` } if (!is.null(`status`)) { + if (!(`status` %in% c("placed", "approved", "delivered"))) { + stop(paste("Error! \"", `status`, "\" cannot be assigned to `status`. Must be \"placed\", \"approved\", \"delivered\".", sep = "")) + } stopifnot(is.character(`status`), length(`status`) == 1) self$`status` <- `status` } @@ -68,6 +71,11 @@ Order <- R6::R6Class( stopifnot(is.logical(`complete`), length(`complete`) == 1) self$`complete` <- `complete` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -102,6 +110,9 @@ Order <- R6::R6Class( OrderObject[["complete"]] <- self$`complete` } + for (key in names(self$additional_properties)) { + OrderObject[[key]] <- self$additional_properties[[key]] + } OrderObject }, @@ -128,11 +139,21 @@ Order <- R6::R6Class( self$`shipDate` <- this_object$`shipDate` } if (!is.null(this_object$`status`)) { + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("placed", "approved", "delivered"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"placed\", \"approved\", \"delivered\".", sep = "")) + } self$`status` <- this_object$`status` } if (!is.null(this_object$`complete`)) { self$`complete` <- this_object$`complete` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -194,7 +215,12 @@ Order <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of Order #' @@ -210,8 +236,18 @@ Order <- R6::R6Class( self$`petId` <- this_object$`petId` self$`quantity` <- this_object$`quantity` self$`shipDate` <- this_object$`shipDate` + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("placed", "approved", "delivered"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"placed\", \"approved\", \"delivered\".", sep = "")) + } self$`status` <- this_object$`status` self$`complete` <- this_object$`complete` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to Order @@ -233,7 +269,50 @@ Order <- R6::R6Class( #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +# Order$unlock() +# +## Below is an example to define the print fnuction +# Order$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Order$lock() diff --git a/samples/client/petstore/R/R/pet.R b/samples/client/petstore/R/R/pet.R index 70aa25dd9e..63318448c0 100644 --- a/samples/client/petstore/R/R/pet.R +++ b/samples/client/petstore/R/R/pet.R @@ -1,11 +1,8 @@ -#' OpenAPI Petstore +#' Create a new Pet #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' A pet for sale in the pet store #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title Pet #' @description Pet Class @@ -13,9 +10,11 @@ #' @field id integer [optional] #' @field category \link{Category} [optional] #' @field name character -#' @field photoUrls list( character ) -#' @field tags list( \link{Tag} ) [optional] -#' @field status character [optional] +#' @field photoUrls list(character) +#' @field tags list(\link{Tag}) [optional] +#' @field status pet status in the store character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -28,6 +27,8 @@ Pet <- R6::R6Class( `photoUrls` = NULL, `tags` = NULL, `status` = NULL, + `_field_list` = c("id", "category", "name", "photoUrls", "tags", "status"), + `additional_properties` = list(), #' Initialize a new Pet class. #' #' @description @@ -39,11 +40,10 @@ Pet <- R6::R6Class( #' @param category category #' @param tags tags #' @param status pet status in the store + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `name`, `photoUrls`, `id` = NULL, `category` = NULL, `tags` = NULL, `status` = NULL, ... - ) { + initialize = function(`name`, `photoUrls`, `id` = NULL, `category` = NULL, `tags` = NULL, `status` = NULL, additional_properties = NULL, ...) { if (!missing(`name`)) { stopifnot(is.character(`name`), length(`name`) == 1) self$`name` <- `name` @@ -67,9 +67,17 @@ Pet <- R6::R6Class( self$`tags` <- `tags` } if (!is.null(`status`)) { + if (!(`status` %in% c("available", "pending", "sold"))) { + stop(paste("Error! \"", `status`, "\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".", sep = "")) + } stopifnot(is.character(`status`), length(`status`) == 1) self$`status` <- `status` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -104,6 +112,9 @@ Pet <- R6::R6Class( PetObject[["status"]] <- self$`status` } + for (key in names(self$additional_properties)) { + PetObject[[key]] <- self$additional_properties[[key]] + } PetObject }, @@ -135,8 +146,18 @@ Pet <- R6::R6Class( self$`tags` <- ApiClient$new()$deserializeObj(this_object$`tags`, "array[Tag]", loadNamespace("petstore")) } if (!is.null(this_object$`status`)) { + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("available", "pending", "sold"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".", sep = "")) + } self$`status` <- this_object$`status` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -161,7 +182,7 @@ Pet <- R6::R6Class( '"category": %s ', - jsonlite::toJSON(self$`category`$toJSON(), auto_unbox=TRUE, digits = NA) + jsonlite::toJSON(self$`category`$toJSON(), auto_unbox = TRUE, digits = NA) ) }, if (!is.null(self$`name`)) { @@ -177,7 +198,7 @@ Pet <- R6::R6Class( '"photoUrls": [%s] ', - paste(unlist(lapply(self$`photoUrls`, function(x) paste0('"', x, '"'))), collapse=",") + paste(unlist(lapply(self$`photoUrls`, function(x) paste0('"', x, '"'))), collapse = ",") ) }, if (!is.null(self$`tags`)) { @@ -185,7 +206,7 @@ Pet <- R6::R6Class( '"tags": [%s] ', - paste(sapply(self$`tags`, function(x) jsonlite::toJSON(x$toJSON(), auto_unbox=TRUE, digits = NA)), collapse=",") + paste(sapply(self$`tags`, function(x) jsonlite::toJSON(x$toJSON(), auto_unbox = TRUE, digits = NA)), collapse = ",") ) }, if (!is.null(self$`status`)) { @@ -198,7 +219,12 @@ Pet <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of Pet #' @@ -215,7 +241,17 @@ Pet <- R6::R6Class( self$`name` <- this_object$`name` self$`photoUrls` <- ApiClient$new()$deserializeObj(this_object$`photoUrls`, "array[character]", loadNamespace("petstore")) self$`tags` <- ApiClient$new()$deserializeObj(this_object$`tags`, "array[Tag]", loadNamespace("petstore")) + if (!is.null(this_object$`status`) && !(this_object$`status` %in% c("available", "pending", "sold"))) { + stop(paste("Error! \"", this_object$`status`, "\" cannot be assigned to `status`. Must be \"available\", \"pending\", \"sold\".", sep = "")) + } self$`status` <- this_object$`status` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to Pet @@ -250,7 +286,70 @@ Pet <- R6::R6Class( #' @export toString = function() { self$toJSONString() - } - ) -) + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `name` is null + if (is.null(self$`name`)) { + return(FALSE) + } + + # check if the required `photoUrls` is null + if (is.null(self$`photoUrls`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `name` is null + if (is.null(self$`name`)) { + invalid_fields["name"] <- "Non-nullable required field `name` cannot be null." + } + + # check if the required `photoUrls` is null + if (is.null(self$`photoUrls`)) { + invalid_fields["photoUrls"] <- "Non-nullable required field `photoUrls` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Pet$unlock() +# +## Below is an example to define the print fnuction +# Pet$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Pet$lock() diff --git a/samples/client/petstore/R/R/pet_api.R b/samples/client/petstore/R/R/pet_api.R index 37a27ce940..19f1a04b1f 100644 --- a/samples/client/petstore/R/R/pet_api.R +++ b/samples/client/petstore/R/R/pet_api.R @@ -5,10 +5,9 @@ #' The version of the OpenAPI document: 1.0.0 #' Generated by: https://openapi-generator.tech #' - #' @docType class #' @title Pet operations -#' @description petstore.Pet +#' @description PetApi #' @format An \code{R6Class} generator object #' @field api_client Handles the client-server communication. #' @@ -25,7 +24,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : Pet +#' \item return type : Pet #' \item response headers : #' #' \tabular{ll}{ @@ -68,7 +67,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : array[Pet] +#' \item return type : array[Pet] #' \item response headers : #' #' \tabular{ll}{ @@ -93,7 +92,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : array[Pet] +#' \item return type : array[Pet] #' \item response headers : #' #' \tabular{ll}{ @@ -118,7 +117,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : Pet +#' \item return type : Pet #' \item response headers : #' #' \tabular{ll}{ @@ -150,7 +149,39 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : Pet +#' \item return type : Pet +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 400 | Invalid ID supplied +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' \item status code : 404 | Pet not found +#' +#' +#' \item response headers : +#' +#' \tabular{ll}{ +#' } +#' } +#' +#' \strong{ TestHeader } \emph{ Header test } +#' Header test +#' +#' \itemize{ +#' \item \emph{ @param } header_test_int integer +#' \item \emph{ @returnType } \link{Pet} \cr +#' +#' \item On encountering errors, an error of subclass ApiException will be thrown. +#' +#' \item status code : 200 | successful operation +#' +#' \item return type : Pet #' \item response headers : #' #' \tabular{ll}{ @@ -182,7 +213,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : Pet +#' \item return type : Pet #' \item response headers : #' #' \tabular{ll}{ @@ -242,7 +273,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : ModelApiResponse +#' \item return type : ModelApiResponse #' \item response headers : #' #' \tabular{ll}{ @@ -257,256 +288,353 @@ #' #################### AddPet #################### #' #' library(petstore) -#' var.pet <- Pet$new() # Pet | Pet object that needs to be added to the store +#' var_pet <- Pet$new() # Pet | Pet object that needs to be added to the store #' #' #Add a new pet to the store -#' api.instance <- PetApi$new() +#' api_instance <- PetApi$new() #' -#' # Configure OAuth2 access token for authorization: petstore_auth -#' api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +#' # Configure HTTP basic authorization: http_auth +#' api_instance$api_client$username <- Sys.getenv("USERNAME") +#' api_instance$api_client$password <- Sys.getenv("PASSWORD") #' -#'result <- tryCatch( -#' api.instance$AddPet(var.pet), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$AddPet(var_pet, data_file = "result.txt"), +#' +#' +#' api_instance$AddPet(var_pet), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `AddPet`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' #################### DeletePet #################### #' #' library(petstore) -#' var.pet_id <- 56 # integer | Pet id to delete -#' var.api_key <- "api_key_example" # character | +#' var_pet_id <- 56 # integer | Pet id to delete +#' var_api_key <- "api_key_example" # character | #' #' #Deletes a pet -#' api.instance <- PetApi$new() +#' api_instance <- PetApi$new() #' #' # Configure OAuth2 access token for authorization: petstore_auth -#' api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") #' -#'result <- tryCatch( -#' api.instance$DeletePet(var.pet_id, api_key=var.api_key), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' api_instance$DeletePet(var_pet_id, api_key = var_api_key), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code -#' } +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `DeletePet`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data #' #' #' #################### FindPetsByStatus #################### #' #' library(petstore) -#' var.status <- ["status_example"] # array[character] | Status values that need to be considered for filter +#' var_status <- ["status_example"] # array[character] | Status values that need to be considered for filter #' #' #Finds Pets by status -#' api.instance <- PetApi$new() +#' api_instance <- PetApi$new() #' #' # Configure OAuth2 access token for authorization: petstore_auth -#' api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") #' -#'result <- tryCatch( -#' api.instance$FindPetsByStatus(var.status), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$FindPetsByStatus(var_status, data_file = "result.txt"), +#' +#' +#' api_instance$FindPetsByStatus(var_status), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `FindPetsByStatus`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' #################### FindPetsByTags #################### #' #' library(petstore) -#' var.tags <- ["tags_example"] # array[character] | Tags to filter by +#' var_tags <- ["tags_example"] # array[character] | Tags to filter by #' #' #Finds Pets by tags -#' api.instance <- PetApi$new() +#' api_instance <- PetApi$new() #' -#' # Configure OAuth2 access token for authorization: petstore_auth -#' api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; -#' -#'result <- tryCatch( -#' api.instance$FindPetsByTags(var.tags), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$FindPetsByTags(var_tags, data_file = "result.txt"), +#' +#' +#' api_instance$FindPetsByTags(var_tags), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `FindPetsByTags`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' #################### GetPetById #################### #' #' library(petstore) -#' var.pet_id <- 56 # integer | ID of pet to return +#' var_pet_id <- 56 # integer | ID of pet to return #' #' #Find pet by ID -#' api.instance <- PetApi$new() +#' api_instance <- PetApi$new() #' -#' #Configure API key authorization: api_key -#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#' # Configure HTTP bearer authorization: BearerToken +#' api_instance$api_client$bearer_token <- Sys.getenv("BEARER_TOKEN") #' -#'result <- tryCatch( -#' api.instance$GetPetById(var.pet_id), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$GetPetById(var_pet_id, data_file = "result.txt"), +#' +#' +#' api_instance$GetPetById(var_pet_id), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `GetPetById`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' #################### GetPetByIdStreaming #################### #' #' library(petstore) -#' var.pet_id <- 56 # integer | ID of pet to return +#' var_pet_id <- 56 # integer | ID of pet to return #' #' #Find pet by ID (streaming) -#' api.instance <- PetApi$new() +#' api_instance <- PetApi$new() #' -#' #Configure API key authorization: api_key -#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") #' -#'result <- tryCatch( -#' api.instance$GetPetByIdStreaming(var.pet_id), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$GetPetByIdStreaming(var_pet_id, data_file = "result.txt"), +#' +#' # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. +#' # api_instance$GetPetByIdStreaming(var_pet_id, stream_callback = function(x){ print(length(x)) }), +#' +#' +#' api_instance$GetPetByIdStreaming(var_pet_id), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `GetPetByIdStreaming`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' +#' #################### TestHeader #################### +#' +#' library(petstore) +#' var_header_test_int <- 56 # integer | header test int +#' +#' #Header test +#' api_instance <- PetApi$new() +#' +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +#' +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$TestHeader(var_header_test_int, data_file = "result.txt"), +#' +#' # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. +#' # api_instance$TestHeader(var_header_test_int, stream_callback = function(x){ print(length(x)) }), +#' +#' +#' api_instance$TestHeader(var_header_test_int), +#' ApiException = function(ex) ex +#' ) +#' # In case of error, print the error object +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `TestHeader`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' } else { +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) +#' } +#' +#' +#' #' #################### UpdatePet #################### #' #' library(petstore) -#' var.pet <- Pet$new() # Pet | Pet object that needs to be added to the store +#' var_pet <- Pet$new() # Pet | Pet object that needs to be added to the store #' #' #Update an existing pet -#' api.instance <- PetApi$new() +#' api_instance <- PetApi$new() #' #' # Configure OAuth2 access token for authorization: petstore_auth -#' api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") #' -#'result <- tryCatch( -#' api.instance$UpdatePet(var.pet), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$UpdatePet(var_pet, data_file = "result.txt"), +#' +#' +#' api_instance$UpdatePet(var_pet), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `UpdatePet`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' #################### UpdatePetWithForm #################### #' #' library(petstore) -#' var.pet_id <- 56 # integer | ID of pet that needs to be updated -#' var.name <- "name_example" # character | Updated name of the pet -#' var.status <- "status_example" # character | Updated status of the pet +#' var_pet_id <- 56 # integer | ID of pet that needs to be updated +#' var_name <- "name_example" # character | Updated name of the pet +#' var_status <- "status_example" # character | Updated status of the pet #' #' #Updates a pet in the store with form data -#' api.instance <- PetApi$new() +#' api_instance <- PetApi$new() #' -#' # Configure OAuth2 access token for authorization: petstore_auth -#' api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; -#' -#'result <- tryCatch( -#' api.instance$UpdatePetWithForm(var.pet_id, name=var.name, status=var.status), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' api_instance$UpdatePetWithForm(var_pet_id, name = var_name, status = var_status), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code -#' } +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `UpdatePetWithForm`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data #' #' #' #################### UploadFile #################### #' #' library(petstore) -#' var.pet_id <- 56 # integer | ID of pet to update -#' var.additional_metadata <- "additional_metadata_example" # character | Additional data to pass to server -#' var.file <- File.new('/path/to/file') # data.frame | file to upload +#' var_pet_id <- 56 # integer | ID of pet to update +#' var_additional_metadata <- "additional_metadata_example" # character | Additional data to pass to server +#' var_file <- File.new('/path/to/file') # data.frame | file to upload #' #' #uploads an image -#' api.instance <- PetApi$new() +#' api_instance <- PetApi$new() #' #' # Configure OAuth2 access token for authorization: petstore_auth -#' api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +#' api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") #' -#'result <- tryCatch( -#' api.instance$UploadFile(var.pet_id, additional_metadata=var.additional_metadata, file=var.file), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$UploadFile(var_pet_id, additional_metadata = var_additional_metadata, file = var_file, data_file = "result.txt"), +#' +#' +#' api_instance$UploadFile(var_pet_id, additional_metadata = var_additional_metadata, file = var_file), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `UploadFile`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' } #' @importFrom R6 R6Class #' @importFrom base64enc base64encode @@ -541,16 +669,15 @@ PetApi <- R6::R6Class( #' @return Pet #' @export AddPet = function(pet, data_file = NULL, ...) { - api_response <- self$AddPetWithHttpInfo(pet, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$AddPetWithHttpInfo(pet, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Add a new pet to the store @@ -567,6 +694,11 @@ PetApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`pet`)) { rlang::abort(message = "Missing required parameter `pet`.", @@ -575,62 +707,78 @@ PetApi <- R6::R6Class( reason = "Missing required parameter `pet`.")) } - if (!missing(`pet`)) { - body <- `pet`$toJSONString() + + if (!is.null(`pet`)) { + local_var_body <- `pet`$toJSONString() } else { body <- NULL } - url_path <- "/pet" - # OAuth token - header_params["Authorization"] <- paste("Bearer", self$api_client$access_token, sep = " ") + local_var_url_path <- "/pet" + # HTTP basic auth + if (!is.null(self$api_client$username) || !is.null(self$api_client$password)) { + header_params["Authorization"] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$api_client$username, self$api_client$password, sep = ":")))) + } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json", "application/xml", "multipart/related") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "POST", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "Pet", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Deletes a pet @@ -639,21 +787,20 @@ PetApi <- R6::R6Class( #' Deletes a pet #' #' @param pet_id Pet id to delete - #' @param api_key (optional) + #' @param api_key (optional) No description #' @param ... Other optional arguments #' @return void #' @export - DeletePet = function(pet_id, api_key=NULL, ...) { - api_response <- self$DeletePetWithHttpInfo(pet_id, api_key, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + DeletePet = function(pet_id, api_key = NULL, ...) { + local_var_response <- self$DeletePetWithHttpInfo(pet_id, api_key, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Deletes a pet @@ -662,14 +809,19 @@ PetApi <- R6::R6Class( #' Deletes a pet #' #' @param pet_id Pet id to delete - #' @param api_key (optional) + #' @param api_key (optional) No description #' @param ... Other optional arguments #' @return API response (void) with additional information such as HTTP status code, headers #' @export - DeletePetWithHttpInfo = function(pet_id, api_key=NULL, ...) { + DeletePetWithHttpInfo = function(pet_id, api_key = NULL, ...) { args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`pet_id`)) { rlang::abort(message = "Missing required parameter `pet_id`.", @@ -678,48 +830,65 @@ PetApi <- R6::R6Class( reason = "Missing required parameter `pet_id`.")) } - body <- NULL - url_path <- "/pet/{petId}?streaming" + + + header_params["api_key"] <- `api_key` + + local_var_url_path <- "/pet/{petId}" if (!missing(`pet_id`)) { - url_path <- gsub(paste0("\\{", "petId", "\\}"), URLencode(as.character(`pet_id`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) } - # OAuth token - header_params["Authorization"] <- paste("Bearer", self$api_client$access_token, sep = " ") + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "write:pets read:pets" - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "DELETE", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - ApiResponse$new(NULL, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Finds Pets by status @@ -733,16 +902,15 @@ PetApi <- R6::R6Class( #' @return array[Pet] #' @export FindPetsByStatus = function(status, data_file = NULL, ...) { - api_response <- self$FindPetsByStatusWithHttpInfo(status, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$FindPetsByStatusWithHttpInfo(status, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Finds Pets by status @@ -759,6 +927,11 @@ PetApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`status`)) { rlang::abort(message = "Missing required parameter `status`.", @@ -767,57 +940,83 @@ PetApi <- R6::R6Class( reason = "Missing required parameter `status`.")) } - body <- NULL - url_path <- "/pet/findByStatus" - # OAuth token - header_params["Authorization"] <- paste("Bearer", self$api_client$access_token, sep = " ") - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # explore + for (query_item in `status`) { + # validate enum values + if (!(query_item %in% c("available", "pending", "sold"))) { + rlang::abort(message = "Invalid value for `status` when calling PetApi$FindPetsByStatus. Must be [available, pending, sold].", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `status` when calling PetApi$FindPetsByStatus. Must be [available, pending, sold].")) + } + query_params[["status"]] <- c(query_params[["status"]], list(`status` = query_item)) + } + + local_var_url_path <- "/pet/findByStatus" + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "read:pets" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "array[Pet]", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "array[Pet]", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Finds Pets by tags @@ -831,16 +1030,15 @@ PetApi <- R6::R6Class( #' @return array[Pet] #' @export FindPetsByTags = function(tags, data_file = NULL, ...) { - api_response <- self$FindPetsByTagsWithHttpInfo(tags, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$FindPetsByTagsWithHttpInfo(tags, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Finds Pets by tags @@ -857,6 +1055,11 @@ PetApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`tags`)) { rlang::abort(message = "Missing required parameter `tags`.", @@ -865,57 +1068,71 @@ PetApi <- R6::R6Class( reason = "Missing required parameter `tags`.")) } - body <- NULL - url_path <- "/pet/findByTags" - # OAuth token - header_params["Authorization"] <- paste("Bearer", self$api_client$access_token, sep = " ") - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # no explore + query_params[["tags"]] <- I(paste(lapply(`tags`, URLencode, reserved = TRUE), collapse = ",")) + + local_var_url_path <- "/pet/findByTags" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "array[Pet]", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "array[Pet]", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Find pet by ID @@ -929,16 +1146,15 @@ PetApi <- R6::R6Class( #' @return Pet #' @export GetPetById = function(pet_id, data_file = NULL, ...) { - api_response <- self$GetPetByIdWithHttpInfo(pet_id, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$GetPetByIdWithHttpInfo(pet_id, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Find pet by ID @@ -955,6 +1171,11 @@ PetApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`pet_id`)) { rlang::abort(message = "Missing required parameter `pet_id`.", @@ -963,63 +1184,76 @@ PetApi <- R6::R6Class( reason = "Missing required parameter `pet_id`.")) } - body <- NULL - url_path <- "/pet/{petId}" + + local_var_url_path <- "/pet/{petId}" if (!missing(`pet_id`)) { - url_path <- gsub(paste0("\\{", "petId", "\\}"), URLencode(as.character(`pet_id`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) } - # API key authentication - if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { - header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + # Bearer token + if (!is.null(self$api_client$bearer_token)) { + header_params["Authorization"] <- paste("Bearer", self$api_client$bearer_token, sep = " ") } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "Pet", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Find pet by ID (streaming) @@ -1033,21 +1267,20 @@ PetApi <- R6::R6Class( #' @param ... Other optional arguments #' @return Pet #' @export - GetPetByIdStreaming = function(pet_id, stream_callback=NULL, data_file = NULL, ...) { - api_response <- self$GetPetByIdStreamingWithHttpInfo(pet_id, stream_callback = stream_callback, data_file = data_file, ...) + GetPetByIdStreaming = function(pet_id, stream_callback = NULL, data_file = NULL, ...) { + local_var_response <- self$GetPetByIdStreamingWithHttpInfo(pet_id, stream_callback = stream_callback, data_file = data_file, ...) if (typeof(stream_callback) == "closure") { # return void if streaming is enabled return(invisible(NULL)) } - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Find pet by ID (streaming) @@ -1061,10 +1294,15 @@ PetApi <- R6::R6Class( #' @param ... Other optional arguments #' @return API response (Pet) with additional information such as HTTP status code, headers #' @export - GetPetByIdStreamingWithHttpInfo = function(pet_id, stream_callback=NULL, data_file = NULL, ...) { + GetPetByIdStreamingWithHttpInfo = function(pet_id, stream_callback = NULL, data_file = NULL, ...) { args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`pet_id`)) { rlang::abort(message = "Missing required parameter `pet_id`.", @@ -1073,10 +1311,10 @@ PetApi <- R6::R6Class( reason = "Missing required parameter `pet_id`.")) } - body <- NULL - url_path <- "/pet/{petId}?streaming" + + local_var_url_path <- "/pet/{petId}?streaming" if (!missing(`pet_id`)) { - url_path <- gsub(paste0("\\{", "petId", "\\}"), URLencode(as.character(`pet_id`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) } # API key authentication @@ -1084,11 +1322,23 @@ PetApi <- R6::R6Class( header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, stream_callback = stream_callback, ...) @@ -1096,45 +1346,176 @@ PetApi <- R6::R6Class( return(invisible(NULL)) } - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "Pet", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." + ApiException = ApiException$new(http_response = local_var_resp)) + } + }, + #' Header test + #' + #' @description + #' Header test + #' + #' @param header_test_int header test int + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return Pet + #' @export + TestHeader = function(header_test_int, stream_callback = NULL, data_file = NULL, ...) { + local_var_response <- self$TestHeaderWithHttpInfo(header_test_int, stream_callback = stream_callback, data_file = data_file, ...) + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response + } + }, + #' Header test + #' + #' @description + #' Header test + #' + #' @param header_test_int header test int + #' @param stream_callback (optional) callback function to process the data stream + #' @param data_file (optional) name of the data file to save the result + #' @param ... Other optional arguments + #' @return API response (Pet) with additional information such as HTTP status code, headers + #' @export + TestHeaderWithHttpInfo = function(header_test_int, stream_callback = NULL, data_file = NULL, ...) { + args <- list(...) + query_params <- list() + header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE + + if (missing(`header_test_int`)) { + rlang::abort(message = "Missing required parameter `header_test_int`.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Missing required parameter `header_test_int`.")) + } + + + header_params["header_test_int"] <- `header_test_int` + + local_var_url_path <- "/pet_header_test" + # API key authentication + if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { + header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") + } + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), + method = "GET", + query_params = query_params, + header_params = header_params, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, + stream_callback = stream_callback, + ...) + + if (typeof(stream_callback) == "closure") { # return void if streaming is enabled + return(invisible(NULL)) + } + + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + # save response in a file + if (!is.null(data_file)) { + write(local_var_resp$response, data_file) + } + + deserialized_resp_obj <- tryCatch( + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), + error = function(e) { + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } + ) + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Update an existing pet @@ -1148,16 +1529,15 @@ PetApi <- R6::R6Class( #' @return Pet #' @export UpdatePet = function(pet, data_file = NULL, ...) { - api_response <- self$UpdatePetWithHttpInfo(pet, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$UpdatePetWithHttpInfo(pet, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Update an existing pet @@ -1174,6 +1554,11 @@ PetApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`pet`)) { rlang::abort(message = "Missing required parameter `pet`.", @@ -1182,62 +1567,77 @@ PetApi <- R6::R6Class( reason = "Missing required parameter `pet`.")) } - if (!missing(`pet`)) { - body <- `pet`$toJSONString() + + if (!is.null(`pet`)) { + local_var_body <- `pet`$toJSONString() } else { body <- NULL } - url_path <- "/pet" - # OAuth token - header_params["Authorization"] <- paste("Bearer", self$api_client$access_token, sep = " ") + local_var_url_path <- "/pet" + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "write:pets read:pets" - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json", "application/xml", "multipart/related") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "PUT", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "Pet", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "Pet", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Updates a pet in the store with form data @@ -1246,22 +1646,21 @@ PetApi <- R6::R6Class( #' Updates a pet in the store with form data #' #' @param pet_id ID of pet that needs to be updated - #' @param name (optional)Updated name of the pet - #' @param status (optional)Updated status of the pet + #' @param name (optional) Updated name of the pet + #' @param status (optional) Updated status of the pet #' @param ... Other optional arguments #' @return void #' @export - UpdatePetWithForm = function(pet_id, name=NULL, status=NULL, ...) { - api_response <- self$UpdatePetWithFormWithHttpInfo(pet_id, name, status, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + UpdatePetWithForm = function(pet_id, name = NULL, status = NULL, ...) { + local_var_response <- self$UpdatePetWithFormWithHttpInfo(pet_id, name, status, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Updates a pet in the store with form data @@ -1275,10 +1674,15 @@ PetApi <- R6::R6Class( #' @param ... Other optional arguments #' @return API response (void) with additional information such as HTTP status code, headers #' @export - UpdatePetWithFormWithHttpInfo = function(pet_id, name=NULL, status=NULL, ...) { + UpdatePetWithFormWithHttpInfo = function(pet_id, name = NULL, status = NULL, ...) { args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`pet_id`)) { rlang::abort(message = "Missing required parameter `pet_id`.", @@ -1287,52 +1691,63 @@ PetApi <- R6::R6Class( reason = "Missing required parameter `pet_id`.")) } - body <- list( - "name" = name, - "status" = status - ) - url_path <- "/pet/{petId}?streaming" + + + form_params["name"] <- `name` + form_params["status"] <- `status` + local_var_url_path <- "/pet/{petId}" if (!missing(`pet_id`)) { - url_path <- gsub(paste0("\\{", "petId", "\\}"), URLencode(as.character(`pet_id`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) } - # OAuth token - header_params["Authorization"] <- paste("Bearer", self$api_client$access_token, sep = " ") - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/x-www-form-urlencoded") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "POST", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - ApiResponse$new(NULL, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' uploads an image @@ -1341,23 +1756,22 @@ PetApi <- R6::R6Class( #' uploads an image #' #' @param pet_id ID of pet to update - #' @param additional_metadata (optional)Additional data to pass to server - #' @param file (optional)file to upload + #' @param additional_metadata (optional) Additional data to pass to server + #' @param file (optional) file to upload #' @param data_file (optional) name of the data file to save the result #' @param ... Other optional arguments #' @return ModelApiResponse #' @export - UploadFile = function(pet_id, additional_metadata=NULL, file=NULL, data_file = NULL, ...) { - api_response <- self$UploadFileWithHttpInfo(pet_id, additional_metadata, file, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + UploadFile = function(pet_id, additional_metadata = NULL, file = NULL, data_file = NULL, ...) { + local_var_response <- self$UploadFileWithHttpInfo(pet_id, additional_metadata, file, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' uploads an image @@ -1372,10 +1786,15 @@ PetApi <- R6::R6Class( #' @param ... Other optional arguments #' @return API response (ModelApiResponse) with additional information such as HTTP status code, headers #' @export - UploadFileWithHttpInfo = function(pet_id, additional_metadata=NULL, file=NULL, data_file = NULL, ...) { + UploadFileWithHttpInfo = function(pet_id, additional_metadata = NULL, file = NULL, data_file = NULL, ...) { args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`pet_id`)) { rlang::abort(message = "Missing required parameter `pet_id`.", @@ -1384,65 +1803,79 @@ PetApi <- R6::R6Class( reason = "Missing required parameter `pet_id`.")) } - body <- list( - "additionalMetadata" = additional_metadata, - "file" = httr::upload_file(file) - ) - url_path <- "/pet/{petId}/uploadImage" + + + form_params["additionalMetadata"] <- `additional_metadata` + file_params["file"] <- httr::upload_file(`file`) + local_var_url_path <- "/pet/{petId}/uploadImage" if (!missing(`pet_id`)) { - url_path <- gsub(paste0("\\{", "petId", "\\}"), URLencode(as.character(`pet_id`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{petId\\}", URLencode(as.character(`pet_id`), reserved = TRUE), local_var_url_path) } - # OAuth token - header_params["Authorization"] <- paste("Bearer", self$api_client$access_token, sep = " ") + # OAuth-related settings + is_oauth <- TRUE + oauth_scopes <- "write:pets read:pets" - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list("application/json") + + # The Content-Type representation header + local_var_content_types <- list("multipart/form-data") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "POST", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "ModelApiResponse", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "ModelApiResponse", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } } ) diff --git a/samples/client/petstore/R/R/pig.R b/samples/client/petstore/R/R/pig.R index 8740ff0a1d..6cb6b568ab 100644 --- a/samples/client/petstore/R/R/pig.R +++ b/samples/client/petstore/R/R/pig.R @@ -1,11 +1,3 @@ -#' 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. -#' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title Pig #' @@ -23,7 +15,7 @@ Pig <- R6::R6Class( actual_instance = NULL, #' @field actual_type the type of the object stored in this instance. actual_type = NULL, - #' @field one_of a list of object types defined in the oneOf schema. + #' @field one_of a list of types defined in the oneOf schema. one_of = list("BasquePig", "DanishPig"), #' Initialize a new Pig. #' @@ -50,6 +42,18 @@ Pig <- R6::R6Class( #' #' @description #' Deserialize JSON string into an instance of Pig. + #' An alias to the method `fromJSON` . + #' + #' @param input The input JSON. + #' @return An instance of Pig. + #' @export + fromJSONString = function(input) { + self$fromJSON(input) + }, + #' Deserialize JSON string into an instance of Pig. + #' + #' @description + #' Deserialize JSON string into an instance of Pig. #' #' @param input The input JSON. #' @return An instance of Pig. @@ -168,7 +172,29 @@ Pig <- R6::R6Class( ) jsoncontent <- paste(jsoncontent, collapse = ",") as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = ""))) + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +#Pig$unlock() +# +## Below is an example to define the print fnuction +#Pig$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +#}) +## Uncomment below to lock the class to prevent modifications to the method or field +#Pig$lock() diff --git a/samples/client/petstore/R/R/special.R b/samples/client/petstore/R/R/special.R index 11481199f2..33f06cc6a6 100644 --- a/samples/client/petstore/R/R/special.R +++ b/samples/client/petstore/R/R/special.R @@ -1,49 +1,60 @@ -#' OpenAPI Petstore +#' Create a new Special #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' Describes the result of uploading an image resource #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title Special #' @description Special Class #' @format An \code{R6Class} generator object +#' @field set_test list(character) [optional] #' @field item_self integer [optional] #' @field item_private character [optional] #' @field item_super character [optional] #' @field 123_number character [optional] #' @field array[test] character [optional] #' @field empty_string character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export Special <- R6::R6Class( "Special", public = list( + `set_test` = NULL, `item_self` = NULL, `item_private` = NULL, `item_super` = NULL, `123_number` = NULL, `array[test]` = NULL, `empty_string` = NULL, + `_field_list` = c("set_test", "item_self", "item_private", "item_super", "123_number", "array[test]", "empty_string"), + `additional_properties` = list(), #' Initialize a new Special class. #' #' @description #' Initialize a new Special class. #' + #' @param set_test set_test #' @param item_self item_self #' @param item_private item_private #' @param item_super item_super #' @param 123_number 123_number #' @param array[test] array[test] #' @param empty_string empty_string + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `item_self` = NULL, `item_private` = NULL, `item_super` = NULL, `123_number` = NULL, `array[test]` = NULL, `empty_string` = NULL, ... - ) { + initialize = function(`set_test` = NULL, `item_self` = NULL, `item_private` = NULL, `item_super` = NULL, `123_number` = NULL, `array[test]` = NULL, `empty_string` = NULL, additional_properties = NULL, ...) { + if (!is.null(`set_test`)) { + stopifnot(is.vector(`set_test`), length(`set_test`) != 0) + sapply(`set_test`, function(x) stopifnot(is.character(x))) + if (!identical(`set_test`, unique(`set_test`))) { + stop("Error! Items in `set_test` are not unique.") + } + self$`set_test` <- `set_test` + } if (!is.null(`item_self`)) { stopifnot(is.numeric(`item_self`), length(`item_self`) == 1) self$`item_self` <- `item_self` @@ -68,6 +79,11 @@ Special <- R6::R6Class( stopifnot(is.character(`empty_string`), length(`empty_string`) == 1) self$`empty_string` <- `empty_string` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -78,6 +94,10 @@ Special <- R6::R6Class( #' @export toJSON = function() { SpecialObject <- list() + if (!is.null(self$`set_test`)) { + SpecialObject[["set_test"]] <- + self$`set_test` + } if (!is.null(self$`item_self`)) { SpecialObject[["self"]] <- self$`item_self` @@ -102,6 +122,9 @@ Special <- R6::R6Class( SpecialObject[["empty_string"]] <- self$`empty_string` } + for (key in names(self$additional_properties)) { + SpecialObject[[key]] <- self$additional_properties[[key]] + } SpecialObject }, @@ -115,6 +138,12 @@ Special <- R6::R6Class( #' @export fromJSON = function(input_json) { this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`set_test`)) { + self$`set_test` <- ApiClient$new()$deserializeObj(this_object$`set_test`, "set[character]", loadNamespace("petstore")) + if (!identical(self$`set_test`, unique(self$`set_test`))) { + stop("Error! Items in `set_test` are not unique.") + } + } if (!is.null(this_object$`self`)) { self$`item_self` <- this_object$`self` } @@ -133,6 +162,13 @@ Special <- R6::R6Class( if (!is.null(this_object$`empty_string`)) { self$`empty_string` <- this_object$`empty_string` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -144,6 +180,14 @@ Special <- R6::R6Class( #' @export toJSONString = function() { jsoncontent <- c( + if (!is.null(self$`set_test`)) { + sprintf( + '"set_test": + [%s] + ', + paste(unlist(lapply(self$`set_test`, function(x) paste0('"', x, '"'))), collapse = ",") + ) + }, if (!is.null(self$`item_self`)) { sprintf( '"self": @@ -194,7 +238,12 @@ Special <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of Special #' @@ -206,12 +255,23 @@ Special <- R6::R6Class( #' @export fromJSONString = function(input_json) { this_object <- jsonlite::fromJSON(input_json) + self$`set_test` <- ApiClient$new()$deserializeObj(this_object$`set_test`, "set[character]", loadNamespace("petstore")) + if (!identical(self$`set_test`, unique(self$`set_test`))) { + stop("Error! Items in `set_test` are not unique.") + } self$`item_self` <- this_object$`item_self` self$`item_private` <- this_object$`item_private` self$`item_super` <- this_object$`item_super` self$`123_number` <- this_object$`123_number` self$`array[test]` <- this_object$`array[test]` self$`empty_string` <- this_object$`empty_string` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to Special @@ -233,7 +293,52 @@ Special <- R6::R6Class( #' @export toString = function() { self$toJSONString() - } - ) -) + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Special$unlock() +# +## Below is an example to define the print fnuction +# Special$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Special$lock() diff --git a/samples/client/petstore/R/R/store_api.R b/samples/client/petstore/R/R/store_api.R index 584646fc43..ec9b71aabf 100644 --- a/samples/client/petstore/R/R/store_api.R +++ b/samples/client/petstore/R/R/store_api.R @@ -5,17 +5,16 @@ #' The version of the OpenAPI document: 1.0.0 #' Generated by: https://openapi-generator.tech #' - #' @docType class #' @title Store operations -#' @description petstore.Store +#' @description StoreApi #' @format An \code{R6Class} generator object #' @field api_client Handles the client-server communication. #' #' @section Methods: #' \describe{ #' \strong{ DeleteOrder } \emph{ Delete purchase order by ID } -#' For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +#' For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors #' #' \itemize{ #' \item \emph{ @param } order_id character @@ -47,7 +46,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : map(integer) +#' \item return type : map(integer) #' \item response headers : #' #' \tabular{ll}{ @@ -55,7 +54,7 @@ #' } #' #' \strong{ GetOrderById } \emph{ Find purchase order by ID } -#' For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +#' For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions #' #' \itemize{ #' \item \emph{ @param } order_id integer @@ -65,7 +64,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : Order +#' \item return type : Order #' \item response headers : #' #' \tabular{ll}{ @@ -97,7 +96,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : Order +#' \item return type : Order #' \item response headers : #' #' \tabular{ll}{ @@ -119,24 +118,26 @@ #' #################### DeleteOrder #################### #' #' library(petstore) -#' var.order_id <- "order_id_example" # character | ID of the order that needs to be deleted +#' var_order_id <- "order_id_example" # character | ID of the order that needs to be deleted #' #' #Delete purchase order by ID -#' api.instance <- StoreApi$new() +#' api_instance <- StoreApi$new() #' -#'result <- tryCatch( -#' api.instance$DeleteOrder(var.order_id), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' api_instance$DeleteOrder(var_order_id), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code -#' } +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `DeleteOrder`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data #' #' #' #################### GetInventory #################### @@ -144,78 +145,102 @@ #' library(petstore) #' #' #Returns pet inventories by status -#' api.instance <- StoreApi$new() +#' api_instance <- StoreApi$new() #' -#' #Configure API key authorization: api_key -#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") #' -#'result <- tryCatch( -#' api.instance$GetInventory(), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$GetInventory(data_file = "result.txt"), +#' +#' +#' api_instance$GetInventory(), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `GetInventory`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' #################### GetOrderById #################### #' #' library(petstore) -#' var.order_id <- 56 # integer | ID of pet that needs to be fetched +#' var_order_id <- 56 # integer | ID of pet that needs to be fetched #' #' #Find purchase order by ID -#' api.instance <- StoreApi$new() +#' api_instance <- StoreApi$new() #' -#'result <- tryCatch( -#' api.instance$GetOrderById(var.order_id), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$GetOrderById(var_order_id, data_file = "result.txt"), +#' +#' +#' api_instance$GetOrderById(var_order_id), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `GetOrderById`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' #################### PlaceOrder #################### #' #' library(petstore) -#' var.order <- Order$new() # Order | order placed for purchasing the pet +#' var_order <- Order$new() # Order | order placed for purchasing the pet #' #' #Place an order for a pet -#' api.instance <- StoreApi$new() +#' api_instance <- StoreApi$new() #' -#'result <- tryCatch( -#' api.instance$PlaceOrder(var.order), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$PlaceOrder(var_order, data_file = "result.txt"), +#' +#' +#' api_instance$PlaceOrder(var_order), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `PlaceOrder`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' } #' @importFrom R6 R6Class #' @importFrom base64enc base64encode @@ -249,16 +274,15 @@ StoreApi <- R6::R6Class( #' @return void #' @export DeleteOrder = function(order_id, ...) { - api_response <- self$DeleteOrderWithHttpInfo(order_id, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$DeleteOrderWithHttpInfo(order_id, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Delete purchase order by ID @@ -274,6 +298,11 @@ StoreApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`order_id`)) { rlang::abort(message = "Missing required parameter `order_id`.", @@ -282,46 +311,59 @@ StoreApi <- R6::R6Class( reason = "Missing required parameter `order_id`.")) } - body <- NULL - url_path <- "/store/order/{orderId}" + + local_var_url_path <- "/store/order/{orderId}" if (!missing(`order_id`)) { - url_path <- gsub(paste0("\\{", "orderId", "\\}"), URLencode(as.character(`order_id`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{orderId\\}", URLencode(as.character(`order_id`), reserved = TRUE), local_var_url_path) } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "DELETE", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - ApiResponse$new(NULL, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Returns pet inventories by status @@ -334,16 +376,15 @@ StoreApi <- R6::R6Class( #' @return map(integer) #' @export GetInventory = function(data_file = NULL, ...) { - api_response <- self$GetInventoryWithHttpInfo(data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$GetInventoryWithHttpInfo(data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Returns pet inventories by status @@ -359,60 +400,77 @@ StoreApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE - body <- NULL - url_path <- "/store/inventory" + local_var_url_path <- "/store/inventory" # API key authentication if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list("application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "map(integer)", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "map(integer)", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Find purchase order by ID @@ -426,16 +484,15 @@ StoreApi <- R6::R6Class( #' @return Order #' @export GetOrderById = function(order_id, data_file = NULL, ...) { - api_response <- self$GetOrderByIdWithHttpInfo(order_id, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$GetOrderByIdWithHttpInfo(order_id, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Find purchase order by ID @@ -452,6 +509,11 @@ StoreApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`order_id`)) { rlang::abort(message = "Missing required parameter `order_id`.", @@ -460,59 +522,84 @@ StoreApi <- R6::R6Class( reason = "Missing required parameter `order_id`.")) } - body <- NULL - url_path <- "/store/order/{orderId}" + if (`order_id` > 5) { + rlang::abort(message = "Invalid value for `order_id` when calling StoreApi$GetOrderById, must be smaller than or equal to 5.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `order_id` when calling StoreApi$GetOrderById, must be smaller than or equal to 5.")) + } + if (`order_id` < 1) { + rlang::abort(message = "Invalid value for `order_id` when calling StoreApi$GetOrderById, must be bigger than or equal to 1.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `order_id` when calling StoreApi$GetOrderById, must be bigger than or equal to 1.")) + } + + local_var_url_path <- "/store/order/{orderId}" if (!missing(`order_id`)) { - url_path <- gsub(paste0("\\{", "orderId", "\\}"), URLencode(as.character(`order_id`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{orderId\\}", URLencode(as.character(`order_id`), reserved = TRUE), local_var_url_path) } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "Order", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "Order", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Place an order for a pet @@ -526,16 +613,15 @@ StoreApi <- R6::R6Class( #' @return Order #' @export PlaceOrder = function(order, data_file = NULL, ...) { - api_response <- self$PlaceOrderWithHttpInfo(order, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$PlaceOrderWithHttpInfo(order, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Place an order for a pet @@ -552,6 +638,11 @@ StoreApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`order`)) { rlang::abort(message = "Missing required parameter `order`.", @@ -560,60 +651,74 @@ StoreApi <- R6::R6Class( reason = "Missing required parameter `order`.")) } - if (!missing(`order`)) { - body <- `order`$toJSONString() + + if (!is.null(`order`)) { + local_var_body <- `order`$toJSONString() } else { body <- NULL } - url_path <- "/store/order" + local_var_url_path <- "/store/order" - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "POST", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "Order", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "Order", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } } ) diff --git a/samples/client/petstore/R/R/tag.R b/samples/client/petstore/R/R/tag.R index dc3bd0a41b..bd4aac10e2 100644 --- a/samples/client/petstore/R/R/tag.R +++ b/samples/client/petstore/R/R/tag.R @@ -1,17 +1,16 @@ -#' OpenAPI Petstore +#' Create a new Tag #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' A tag for a pet #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title Tag #' @description Tag Class #' @format An \code{R6Class} generator object #' @field id integer [optional] #' @field name character [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -20,6 +19,8 @@ Tag <- R6::R6Class( public = list( `id` = NULL, `name` = NULL, + `_field_list` = c("id", "name"), + `additional_properties` = list(), #' Initialize a new Tag class. #' #' @description @@ -27,11 +28,10 @@ Tag <- R6::R6Class( #' #' @param id id #' @param name name + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `id` = NULL, `name` = NULL, ... - ) { + initialize = function(`id` = NULL, `name` = NULL, additional_properties = NULL, ...) { if (!is.null(`id`)) { stopifnot(is.numeric(`id`), length(`id`) == 1) self$`id` <- `id` @@ -40,6 +40,11 @@ Tag <- R6::R6Class( stopifnot(is.character(`name`), length(`name`) == 1) self$`name` <- `name` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -58,6 +63,9 @@ Tag <- R6::R6Class( TagObject[["name"]] <- self$`name` } + for (key in names(self$additional_properties)) { + TagObject[[key]] <- self$additional_properties[[key]] + } TagObject }, @@ -77,6 +85,13 @@ Tag <- R6::R6Class( if (!is.null(this_object$`name`)) { self$`name` <- this_object$`name` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -106,7 +121,12 @@ Tag <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of Tag #' @@ -120,6 +140,13 @@ Tag <- R6::R6Class( this_object <- jsonlite::fromJSON(input_json) self$`id` <- this_object$`id` self$`name` <- this_object$`name` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to Tag @@ -141,7 +168,50 @@ Tag <- R6::R6Class( #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +# Tag$unlock() +# +## Below is an example to define the print fnuction +# Tag$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Tag$lock() diff --git a/samples/client/petstore/R/R/update_pet_request.R b/samples/client/petstore/R/R/update_pet_request.R index 0d6f08e88b..bde06df6a8 100644 --- a/samples/client/petstore/R/R/update_pet_request.R +++ b/samples/client/petstore/R/R/update_pet_request.R @@ -1,17 +1,16 @@ -#' OpenAPI Petstore +#' Create a new UpdatePetRequest #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' UpdatePetRequest Class #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title UpdatePetRequest #' @description UpdatePetRequest Class #' @format An \code{R6Class} generator object #' @field jsonData \link{Pet} [optional] #' @field binaryDataN2Information data.frame [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -20,6 +19,8 @@ UpdatePetRequest <- R6::R6Class( public = list( `jsonData` = NULL, `binaryDataN2Information` = NULL, + `_field_list` = c("jsonData", "binaryDataN2Information"), + `additional_properties` = list(), #' Initialize a new UpdatePetRequest class. #' #' @description @@ -27,11 +28,10 @@ UpdatePetRequest <- R6::R6Class( #' #' @param jsonData jsonData #' @param binaryDataN2Information binaryDataN2Information + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `jsonData` = NULL, `binaryDataN2Information` = NULL, ... - ) { + initialize = function(`jsonData` = NULL, `binaryDataN2Information` = NULL, additional_properties = NULL, ...) { if (!is.null(`jsonData`)) { stopifnot(R6::is.R6(`jsonData`)) self$`jsonData` <- `jsonData` @@ -39,6 +39,11 @@ UpdatePetRequest <- R6::R6Class( if (!is.null(`binaryDataN2Information`)) { self$`binaryDataN2Information` <- `binaryDataN2Information` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -57,6 +62,9 @@ UpdatePetRequest <- R6::R6Class( UpdatePetRequestObject[["binaryDataN2Information"]] <- self$`binaryDataN2Information` } + for (key in names(self$additional_properties)) { + UpdatePetRequestObject[[key]] <- self$additional_properties[[key]] + } UpdatePetRequestObject }, @@ -78,6 +86,13 @@ UpdatePetRequest <- R6::R6Class( if (!is.null(this_object$`binaryDataN2Information`)) { self$`binaryDataN2Information` <- this_object$`binaryDataN2Information` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -94,7 +109,7 @@ UpdatePetRequest <- R6::R6Class( '"jsonData": %s ', - jsonlite::toJSON(self$`jsonData`$toJSON(), auto_unbox=TRUE, digits = NA) + jsonlite::toJSON(self$`jsonData`$toJSON(), auto_unbox = TRUE, digits = NA) ) }, if (!is.null(self$`binaryDataN2Information`)) { @@ -107,7 +122,12 @@ UpdatePetRequest <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of UpdatePetRequest #' @@ -121,6 +141,13 @@ UpdatePetRequest <- R6::R6Class( this_object <- jsonlite::fromJSON(input_json) self$`jsonData` <- Pet$new()$fromJSON(jsonlite::toJSON(this_object$jsonData, auto_unbox = TRUE, digits = NA)) self$`binaryDataN2Information` <- this_object$`binaryDataN2Information` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to UpdatePetRequest @@ -142,7 +169,50 @@ UpdatePetRequest <- R6::R6Class( #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +# UpdatePetRequest$unlock() +# +## Below is an example to define the print fnuction +# UpdatePetRequest$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# UpdatePetRequest$lock() diff --git a/samples/client/petstore/R/R/user.R b/samples/client/petstore/R/R/user.R index b13a4e09d9..153aacb3ea 100644 --- a/samples/client/petstore/R/R/user.R +++ b/samples/client/petstore/R/R/user.R @@ -1,11 +1,8 @@ -#' OpenAPI Petstore +#' Create a new User #' -#' This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +#' @description +#' A User who is purchasing from the pet store #' -#' The version of the OpenAPI document: 1.0.0 -#' Generated by: https://openapi-generator.tech -#' - #' @docType class #' @title User #' @description User Class @@ -17,7 +14,9 @@ #' @field email character [optional] #' @field password character [optional] #' @field phone character [optional] -#' @field userStatus integer [optional] +#' @field userStatus User Status integer [optional] +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export @@ -32,6 +31,8 @@ User <- R6::R6Class( `password` = NULL, `phone` = NULL, `userStatus` = NULL, + `_field_list` = c("id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus"), + `additional_properties` = list(), #' Initialize a new User class. #' #' @description @@ -45,11 +46,10 @@ User <- R6::R6Class( #' @param password password #' @param phone phone #' @param userStatus User Status + #' @param additional_properties additonal properties (optional) #' @param ... Other optional arguments. #' @export - initialize = function( - `id` = NULL, `username` = NULL, `firstName` = NULL, `lastName` = NULL, `email` = NULL, `password` = NULL, `phone` = NULL, `userStatus` = NULL, ... - ) { + initialize = function(`id` = NULL, `username` = NULL, `firstName` = NULL, `lastName` = NULL, `email` = NULL, `password` = NULL, `phone` = NULL, `userStatus` = NULL, additional_properties = NULL, ...) { if (!is.null(`id`)) { stopifnot(is.numeric(`id`), length(`id`) == 1) self$`id` <- `id` @@ -82,6 +82,11 @@ User <- R6::R6Class( stopifnot(is.numeric(`userStatus`), length(`userStatus`) == 1) self$`userStatus` <- `userStatus` } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } }, #' To JSON string #' @@ -124,6 +129,9 @@ User <- R6::R6Class( UserObject[["userStatus"]] <- self$`userStatus` } + for (key in names(self$additional_properties)) { + UserObject[[key]] <- self$additional_properties[[key]] + } UserObject }, @@ -161,6 +169,13 @@ User <- R6::R6Class( if (!is.null(this_object$`userStatus`)) { self$`userStatus` <- this_object$`userStatus` } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' To JSON string @@ -238,7 +253,12 @@ User <- R6::R6Class( } ) jsoncontent <- paste(jsoncontent, collapse = ",") - as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) }, #' Deserialize JSON string into an instance of User #' @@ -258,6 +278,13 @@ User <- R6::R6Class( self$`password` <- this_object$`password` self$`phone` <- this_object$`phone` self$`userStatus` <- this_object$`userStatus` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + self }, #' Validate JSON input with respect to User @@ -279,7 +306,50 @@ User <- R6::R6Class( #' @export toString = function() { self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) } - ) + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE ) +## Uncomment below to unlock the class to allow modifications of the method or field +# User$unlock() +# +## Below is an example to define the print fnuction +# User$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# User$lock() diff --git a/samples/client/petstore/R/R/user_api.R b/samples/client/petstore/R/R/user_api.R index 10dead6d87..34e6a7b10b 100644 --- a/samples/client/petstore/R/R/user_api.R +++ b/samples/client/petstore/R/R/user_api.R @@ -5,10 +5,9 @@ #' The version of the OpenAPI document: 1.0.0 #' Generated by: https://openapi-generator.tech #' - #' @docType class #' @title User operations -#' @description petstore.User +#' @description UserApi #' @format An \code{R6Class} generator object #' @field api_client Handles the client-server communication. #' @@ -100,7 +99,7 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : User +#' \item return type : User #' \item response headers : #' #' \tabular{ll}{ @@ -132,11 +131,11 @@ #' #' \item status code : 200 | successful operation #' -#' \item return type : character +#' \item return type : character #' \item response headers : #' #' \tabular{ll}{ -#' Set-Cookie \tab Cookie authentication key for use with the `api_key` apiKey authentication. \cr +#' Set-Cookie \tab Cookie authentication key for use with the `api_key` apiKey authentication. \cr #' X-Rate-Limit \tab calls per hour allowed by the user \cr #' X-Expires-After \tab date in UTC when token expires \cr #' } @@ -198,208 +197,236 @@ #' #################### CreateUser #################### #' #' library(petstore) -#' var.user <- User$new() # User | Created user object +#' var_user <- User$new() # User | Created user object #' #' #Create user -#' api.instance <- UserApi$new() +#' api_instance <- UserApi$new() #' -#' #Configure API key authorization: api_key -#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") #' -#'result <- tryCatch( -#' api.instance$CreateUser(var.user), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' api_instance$CreateUser(var_user), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code -#' } +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `CreateUser`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data #' #' #' #################### CreateUsersWithArrayInput #################### #' #' library(petstore) -#' var.user <- [User$new()] # array[User] | List of user object +#' var_user <- [User$new()] # array[User] | List of user object #' #' #Creates list of users with given input array -#' api.instance <- UserApi$new() +#' api_instance <- UserApi$new() #' -#' #Configure API key authorization: api_key -#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") #' -#'result <- tryCatch( -#' api.instance$CreateUsersWithArrayInput(var.user), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' api_instance$CreateUsersWithArrayInput(var_user), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code -#' } +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `CreateUsersWithArrayInput`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data #' #' #' #################### CreateUsersWithListInput #################### #' #' library(petstore) -#' var.user <- [User$new()] # array[User] | List of user object +#' var_user <- [User$new()] # array[User] | List of user object #' #' #Creates list of users with given input array -#' api.instance <- UserApi$new() +#' api_instance <- UserApi$new() #' -#' #Configure API key authorization: api_key -#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") #' -#'result <- tryCatch( -#' api.instance$CreateUsersWithListInput(var.user), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' api_instance$CreateUsersWithListInput(var_user), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code -#' } +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `CreateUsersWithListInput`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data #' #' #' #################### DeleteUser #################### #' #' library(petstore) -#' var.username <- "username_example" # character | The name that needs to be deleted +#' var_username <- "username_example" # character | The name that needs to be deleted #' #' #Delete user -#' api.instance <- UserApi$new() +#' api_instance <- UserApi$new() #' -#' #Configure API key authorization: api_key -#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") #' -#'result <- tryCatch( -#' api.instance$DeleteUser(var.username), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' api_instance$DeleteUser(var_username), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code -#' } +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `DeleteUser`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data #' #' #' #################### GetUserByName #################### #' #' library(petstore) -#' var.username <- "username_example" # character | The name that needs to be fetched. Use user1 for testing. +#' var_username <- "username_example" # character | The name that needs to be fetched. Use user1 for testing. #' #' #Get user by user name -#' api.instance <- UserApi$new() +#' api_instance <- UserApi$new() #' -#'result <- tryCatch( -#' api.instance$GetUserByName(var.username), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$GetUserByName(var_username, data_file = "result.txt"), +#' +#' +#' api_instance$GetUserByName(var_username), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `GetUserByName`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' #################### LoginUser #################### #' #' library(petstore) -#' var.username <- "username_example" # character | The user name for login -#' var.password <- "password_example" # character | The password for login in clear text +#' var_username <- "username_example" # character | The user name for login +#' var_password <- "password_example" # character | The password for login in clear text #' #' #Logs user into the system -#' api.instance <- UserApi$new() +#' api_instance <- UserApi$new() #' -#'result <- tryCatch( -#' api.instance$LoginUser(var.username, var.password), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' # to save the result into a file, simply add the optional `data_file` parameter, e.g. +#' # api_instance$LoginUser(var_username, var_password, data_file = "result.txt"), +#' +#' +#' api_instance$LoginUser(var_username, var_password), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `LoginUser`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' #' } else { -#' # deserialized response object -#' response.object <- result$content -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code +#' # deserialized response object +#' print("The response is ...") +#' dput(result$toString()) #' } #' #' +#' #' #################### LogoutUser #################### #' #' library(petstore) #' #' #Logs out current logged in user session -#' api.instance <- UserApi$new() +#' api_instance <- UserApi$new() #' -#' #Configure API key authorization: api_key -#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") #' -#'result <- tryCatch( -#' api.instance$LogoutUser(), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' api_instance$LogoutUser(), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code -#' } +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `LogoutUser`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data #' #' #' #################### UpdateUser #################### #' #' library(petstore) -#' var.username <- "username_example" # character | name that need to be deleted -#' var.user <- User$new() # User | Updated user object +#' var_username <- "username_example" # character | name that need to be deleted +#' var_user <- User$new() # User | Updated user object #' #' #Updated user -#' api.instance <- UserApi$new() +#' api_instance <- UserApi$new() #' -#' #Configure API key authorization: api_key -#' api.instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#' # Configure API key authorization: api_key +#' api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") #' -#'result <- tryCatch( -#' api.instance$UpdateUser(var.username, var.user), -#' ApiException = function(ex) ex -#' ) +#' result <- tryCatch( +#' +#' api_instance$UpdateUser(var_username, var_user), +#' ApiException = function(ex) ex +#' ) #' # In case of error, print the error object -#' if(!is.null(result$ApiException)) { -#' cat(result$ApiException$toString()) -#' } else { -#' # response headers -#' response.headers <- result$response$headers -#' # response status code -#' response.status.code <- result$response$status_code -#' } +#' if (!is.null(result$ApiException)) { +#' print("Exception occurs when calling `UpdateUser`:") +#' dput(result$ApiException$toString()) +#' +#' # error object +#' dput(result$ApiException$error_object$toJSONString()) +#' +#' }#' +#' # This endpoint doesn't return data #' #' #' } @@ -435,16 +462,15 @@ UserApi <- R6::R6Class( #' @return void #' @export CreateUser = function(user, ...) { - api_response <- self$CreateUserWithHttpInfo(user, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$CreateUserWithHttpInfo(user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Create user @@ -460,6 +486,11 @@ UserApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`user`)) { rlang::abort(message = "Missing required parameter `user`.", @@ -468,51 +499,65 @@ UserApi <- R6::R6Class( reason = "Missing required parameter `user`.")) } - if (!missing(`user`)) { - body <- `user`$toJSONString() + + if (!is.null(`user`)) { + local_var_body <- `user`$toJSONString() } else { body <- NULL } - url_path <- "/user" + local_var_url_path <- "/user" # API key authentication if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "POST", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - ApiResponse$new(NULL, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Creates list of users with given input array @@ -525,16 +570,15 @@ UserApi <- R6::R6Class( #' @return void #' @export CreateUsersWithArrayInput = function(user, ...) { - api_response <- self$CreateUsersWithArrayInputWithHttpInfo(user, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$CreateUsersWithArrayInputWithHttpInfo(user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Creates list of users with given input array @@ -550,6 +594,11 @@ UserApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`user`)) { rlang::abort(message = "Missing required parameter `user`.", @@ -558,52 +607,68 @@ UserApi <- R6::R6Class( reason = "Missing required parameter `user`.")) } - if (!missing(`user`)) { - body.items = paste(unlist(lapply(user, function(param) {param$toJSONString()})), collapse = ",") - body <- paste0("[", body.items, "]") + + if (!is.null(`user`)) { + body.items <- paste(unlist(lapply(`user`, function(param) { + param$toJSONString() + })), collapse = ",") + local_var_body <- paste0("[", body.items, "]") } else { body <- NULL } - url_path <- "/user/createWithArray" + local_var_url_path <- "/user/createWithArray" # API key authentication if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "POST", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - ApiResponse$new(NULL, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Creates list of users with given input array @@ -616,16 +681,15 @@ UserApi <- R6::R6Class( #' @return void #' @export CreateUsersWithListInput = function(user, ...) { - api_response <- self$CreateUsersWithListInputWithHttpInfo(user, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$CreateUsersWithListInputWithHttpInfo(user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Creates list of users with given input array @@ -641,6 +705,11 @@ UserApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`user`)) { rlang::abort(message = "Missing required parameter `user`.", @@ -649,52 +718,68 @@ UserApi <- R6::R6Class( reason = "Missing required parameter `user`.")) } - if (!missing(`user`)) { - body.items = paste(unlist(lapply(user, function(param) {param$toJSONString()})), collapse = ",") - body <- paste0("[", body.items, "]") + + if (!is.null(`user`)) { + body.items <- paste(unlist(lapply(`user`, function(param) { + param$toJSONString() + })), collapse = ",") + local_var_body <- paste0("[", body.items, "]") } else { body <- NULL } - url_path <- "/user/createWithList" + local_var_url_path <- "/user/createWithList" # API key authentication if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "POST", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - ApiResponse$new(NULL, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Delete user @@ -707,16 +792,15 @@ UserApi <- R6::R6Class( #' @return void #' @export DeleteUser = function(username, ...) { - api_response <- self$DeleteUserWithHttpInfo(username, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$DeleteUserWithHttpInfo(username, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Delete user @@ -732,6 +816,11 @@ UserApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`username`)) { rlang::abort(message = "Missing required parameter `username`.", @@ -740,10 +829,10 @@ UserApi <- R6::R6Class( reason = "Missing required parameter `username`.")) } - body <- NULL - url_path <- "/user/{username}" + + local_var_url_path <- "/user/{username}" if (!missing(`username`)) { - url_path <- gsub(paste0("\\{", "username", "\\}"), URLencode(as.character(`username`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{username\\}", URLencode(as.character(`username`), reserved = TRUE), local_var_url_path) } # API key authentication @@ -751,39 +840,52 @@ UserApi <- R6::R6Class( header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "DELETE", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - ApiResponse$new(NULL, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Get user by user name @@ -797,16 +899,15 @@ UserApi <- R6::R6Class( #' @return User #' @export GetUserByName = function(username, data_file = NULL, ...) { - api_response <- self$GetUserByNameWithHttpInfo(username, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$GetUserByNameWithHttpInfo(username, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Get user by user name @@ -823,6 +924,11 @@ UserApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`username`)) { rlang::abort(message = "Missing required parameter `username`.", @@ -831,59 +937,72 @@ UserApi <- R6::R6Class( reason = "Missing required parameter `username`.")) } - body <- NULL - url_path <- "/user/{username}" + + local_var_url_path <- "/user/{username}" if (!missing(`username`)) { - url_path <- gsub(paste0("\\{", "username", "\\}"), URLencode(as.character(`username`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{username\\}", URLencode(as.character(`username`), reserved = TRUE), local_var_url_path) } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "User", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "User", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Logs user into the system @@ -898,16 +1017,15 @@ UserApi <- R6::R6Class( #' @return character #' @export LoginUser = function(username, password, data_file = NULL, ...) { - api_response <- self$LoginUserWithHttpInfo(username, password, data_file = data_file, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$LoginUserWithHttpInfo(username, password, data_file = data_file, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Logs user into the system @@ -925,6 +1043,11 @@ UserApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`username`)) { rlang::abort(message = "Missing required parameter `username`.", @@ -940,55 +1063,79 @@ UserApi <- R6::R6Class( reason = "Missing required parameter `password`.")) } - body <- NULL - url_path <- "/user/login" + if (!str_detect(`username`, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")) { + rlang::abort(message = "Invalid value for `username` when calling UserApi$LoginUser, must conform to the pattern ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$.", + .subclass = "ApiException", + ApiException = ApiException$new(status = 0, + reason = "Invalid value for `username` when calling UserApi$LoginUser, must conform to the pattern ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$.")) + } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + + query_params[["username"]] <- `username` + + query_params[["password"]] <- `password` + + local_var_url_path <- "/user/login" + + # The Accept request HTTP header + local_var_accepts <- list("application/xml", "application/json") + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { # save response in a file if (!is.null(data_file)) { - write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file) + write(local_var_resp$response, data_file) } deserialized_resp_obj <- tryCatch( - self$api_client$deserialize(resp, "character", loadNamespace("petstore")), + self$api_client$deserialize(local_var_resp$response, "character", loadNamespace("petstore")), error = function(e) { - rlang::abort(message = "Failed to deserialize response", - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + rlang::abort(message = "Failed to deserialize response", + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) } ) - ApiResponse$new(deserialized_resp_obj, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + local_var_resp$content <- deserialized_resp_obj + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Logs out current logged in user session @@ -1000,16 +1147,15 @@ UserApi <- R6::R6Class( #' @return void #' @export LogoutUser = function(...) { - api_response <- self$LogoutUserWithHttpInfo(...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$LogoutUserWithHttpInfo(...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Logs out current logged in user session @@ -1024,47 +1170,64 @@ UserApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE - body <- NULL - url_path <- "/user/logout" + local_var_url_path <- "/user/logout" # API key authentication if ("api_key" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["api_key"]) > 0) { header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list() + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "GET", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - ApiResponse$new(NULL, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } }, #' Updated user @@ -1078,16 +1241,15 @@ UserApi <- R6::R6Class( #' @return void #' @export UpdateUser = function(username, user, ...) { - api_response <- self$UpdateUserWithHttpInfo(username, user, ...) - resp <- api_response$response - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - api_response$content - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - api_response - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - api_response - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - api_response + local_var_response <- self$UpdateUserWithHttpInfo(username, user, ...) + if (local_var_response$status_code >= 200 && local_var_response$status_code <= 299) { + local_var_response$content + } else if (local_var_response$status_code >= 300 && local_var_response$status_code <= 399) { + local_var_response + } else if (local_var_response$status_code >= 400 && local_var_response$status_code <= 499) { + local_var_response + } else if (local_var_response$status_code >= 500 && local_var_response$status_code <= 599) { + local_var_response } }, #' Updated user @@ -1104,6 +1266,11 @@ UserApi <- R6::R6Class( args <- list(...) query_params <- list() header_params <- c() + form_params <- list() + file_params <- list() + local_var_body <- NULL + oauth_scopes <- NULL + is_oauth <- FALSE if (missing(`username`)) { rlang::abort(message = "Missing required parameter `username`.", @@ -1119,15 +1286,17 @@ UserApi <- R6::R6Class( reason = "Missing required parameter `user`.")) } - if (!missing(`user`)) { - body <- `user`$toJSONString() + + + if (!is.null(`user`)) { + local_var_body <- `user`$toJSONString() } else { body <- NULL } - url_path <- "/user/{username}" + local_var_url_path <- "/user/{username}" if (!missing(`username`)) { - url_path <- gsub(paste0("\\{", "username", "\\}"), URLencode(as.character(`username`), reserved = TRUE), url_path) + local_var_url_path <- gsub("\\{username\\}", URLencode(as.character(`username`), reserved = TRUE), local_var_url_path) } # API key authentication @@ -1135,39 +1304,52 @@ UserApi <- R6::R6Class( header_params["api_key"] <- paste(unlist(self$api_client$api_keys["api_key"]), collapse = "") } - resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path), + # The Accept request HTTP header + local_var_accepts <- list() + + # The Content-Type representation header + local_var_content_types <- list("application/json") + + local_var_resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, local_var_url_path), method = "PUT", query_params = query_params, header_params = header_params, - body = body, + form_params = form_params, + file_params = file_params, + accepts = local_var_accepts, + content_types = local_var_content_types, + body = local_var_body, + is_oauth = is_oauth, + oauth_scopes = oauth_scopes, ...) - if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { - ApiResponse$new(NULL, resp) - } else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) { - error_msg <- toString(content(resp)) - if (error_msg == "") { - error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.") + if (local_var_resp$status_code >= 200 && local_var_resp$status_code <= 299) { + local_var_resp$content <- NULL + local_var_resp + } else if (local_var_resp$status_code >= 300 && local_var_resp$status_code <= 399) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- paste("Server returned ", local_var_resp$status_code, " response status code.") + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 400 && local_var_resp$status_code <= 499) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api client exception encountered." + } + rlang::abort(message = local_var_error_msg, + .subclass = "ApiException", + ApiException = ApiException$new(http_response = local_var_resp)) + } else if (local_var_resp$status_code >= 500 && local_var_resp$status_code <= 599) { + local_var_error_msg <- local_var_resp$response + if (local_var_error_msg == "") { + local_var_error_msg <- "Api server exception encountered." } rlang::abort(message = error_msg, .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api client exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) - } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) { - error_msg <- toString(content(resp)) - if(error_msg == "") { - error_msg <- "Api server exception encountered." - } - rlang::abort(message = error_msg, - .subclass = "ApiException", - ApiException = ApiException$new(http_response = resp)) + ApiException = ApiException$new(http_response = local_var_resp)) } } ) diff --git a/samples/client/petstore/R/R/whale.R b/samples/client/petstore/R/R/whale.R new file mode 100644 index 0000000000..936b3a2573 --- /dev/null +++ b/samples/client/petstore/R/R/whale.R @@ -0,0 +1,256 @@ +#' Create a new Whale +#' +#' @description +#' Whale Class +#' +#' @docType class +#' @title Whale +#' @description Whale Class +#' @format An \code{R6Class} generator object +#' @field hasBaleen character [optional] +#' @field hasTeeth character [optional] +#' @field className character +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Whale <- R6::R6Class( + "Whale", + public = list( + `hasBaleen` = NULL, + `hasTeeth` = NULL, + `className` = NULL, + `_field_list` = c("hasBaleen", "hasTeeth", "className"), + `additional_properties` = list(), + #' Initialize a new Whale class. + #' + #' @description + #' Initialize a new Whale class. + #' + #' @param className className + #' @param hasBaleen hasBaleen + #' @param hasTeeth hasTeeth + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `hasBaleen` = NULL, `hasTeeth` = NULL, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`hasBaleen`)) { + stopifnot(is.logical(`hasBaleen`), length(`hasBaleen`) == 1) + self$`hasBaleen` <- `hasBaleen` + } + if (!is.null(`hasTeeth`)) { + stopifnot(is.logical(`hasTeeth`), length(`hasTeeth`) == 1) + self$`hasTeeth` <- `hasTeeth` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Whale in JSON format + #' @export + toJSON = function() { + WhaleObject <- list() + if (!is.null(self$`hasBaleen`)) { + WhaleObject[["hasBaleen"]] <- + self$`hasBaleen` + } + if (!is.null(self$`hasTeeth`)) { + WhaleObject[["hasTeeth"]] <- + self$`hasTeeth` + } + if (!is.null(self$`className`)) { + WhaleObject[["className"]] <- + self$`className` + } + for (key in names(self$additional_properties)) { + WhaleObject[[key]] <- self$additional_properties[[key]] + } + + WhaleObject + }, + #' Deserialize JSON string into an instance of Whale + #' + #' @description + #' Deserialize JSON string into an instance of Whale + #' + #' @param input_json the JSON input + #' @return the instance of Whale + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`hasBaleen`)) { + self$`hasBaleen` <- this_object$`hasBaleen` + } + if (!is.null(this_object$`hasTeeth`)) { + self$`hasTeeth` <- this_object$`hasTeeth` + } + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Whale in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`hasBaleen`)) { + sprintf( + '"hasBaleen": + %s + ', + tolower(self$`hasBaleen`) + ) + }, + if (!is.null(self$`hasTeeth`)) { + sprintf( + '"hasTeeth": + %s + ', + tolower(self$`hasTeeth`) + ) + }, + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Whale + #' + #' @description + #' Deserialize JSON string into an instance of Whale + #' + #' @param input_json the JSON input + #' @return the instance of Whale + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + self$`hasBaleen` <- this_object$`hasBaleen` + self$`hasTeeth` <- this_object$`hasTeeth` + self$`className` <- this_object$`className` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Whale + #' + #' @description + #' Validate JSON input with respect to Whale and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Whale: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Whale + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Whale$unlock() +# +## Below is an example to define the print fnuction +# Whale$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Whale$lock() + diff --git a/samples/client/petstore/R/R/zebra.R b/samples/client/petstore/R/R/zebra.R new file mode 100644 index 0000000000..5c090e84cb --- /dev/null +++ b/samples/client/petstore/R/R/zebra.R @@ -0,0 +1,242 @@ +#' Create a new Zebra +#' +#' @description +#' Zebra Class +#' +#' @docType class +#' @title Zebra +#' @description Zebra Class +#' @format An \code{R6Class} generator object +#' @field type character [optional] +#' @field className character +#' @field _field_list a list of fields list(character) +#' @field additional_properties additional properties list(character) [optional] +#' @importFrom R6 R6Class +#' @importFrom jsonlite fromJSON toJSON +#' @export +Zebra <- R6::R6Class( + "Zebra", + public = list( + `type` = NULL, + `className` = NULL, + `_field_list` = c("type", "className"), + `additional_properties` = list(), + #' Initialize a new Zebra class. + #' + #' @description + #' Initialize a new Zebra class. + #' + #' @param className className + #' @param type type + #' @param additional_properties additonal properties (optional) + #' @param ... Other optional arguments. + #' @export + initialize = function(`className`, `type` = NULL, additional_properties = NULL, ...) { + if (!missing(`className`)) { + stopifnot(is.character(`className`), length(`className`) == 1) + self$`className` <- `className` + } + if (!is.null(`type`)) { + if (!(`type` %in% c("plains", "mountain", "grevys"))) { + stop(paste("Error! \"", `type`, "\" cannot be assigned to `type`. Must be \"plains\", \"mountain\", \"grevys\".", sep = "")) + } + stopifnot(is.character(`type`), length(`type`) == 1) + self$`type` <- `type` + } + if (!is.null(additional_properties)) { + for (key in names(additional_properties)) { + self$additional_properties[[key]] <- additional_properties[[key]] + } + } + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Zebra in JSON format + #' @export + toJSON = function() { + ZebraObject <- list() + if (!is.null(self$`type`)) { + ZebraObject[["type"]] <- + self$`type` + } + if (!is.null(self$`className`)) { + ZebraObject[["className"]] <- + self$`className` + } + for (key in names(self$additional_properties)) { + ZebraObject[[key]] <- self$additional_properties[[key]] + } + + ZebraObject + }, + #' Deserialize JSON string into an instance of Zebra + #' + #' @description + #' Deserialize JSON string into an instance of Zebra + #' + #' @param input_json the JSON input + #' @return the instance of Zebra + #' @export + fromJSON = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`type`)) { + if (!is.null(this_object$`type`) && !(this_object$`type` %in% c("plains", "mountain", "grevys"))) { + stop(paste("Error! \"", this_object$`type`, "\" cannot be assigned to `type`. Must be \"plains\", \"mountain\", \"grevys\".", sep = "")) + } + self$`type` <- this_object$`type` + } + if (!is.null(this_object$`className`)) { + self$`className` <- this_object$`className` + } + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' To JSON string + #' + #' @description + #' To JSON String + #' + #' @return Zebra in JSON format + #' @export + toJSONString = function() { + jsoncontent <- c( + if (!is.null(self$`type`)) { + sprintf( + '"type": + "%s" + ', + self$`type` + ) + }, + if (!is.null(self$`className`)) { + sprintf( + '"className": + "%s" + ', + self$`className` + ) + } + ) + jsoncontent <- paste(jsoncontent, collapse = ",") + json_string <- as.character(jsonlite::minify(paste("{", jsoncontent, "}", sep = ""))) + json_obj <- jsonlite::fromJSON(json_string) + for (key in names(self$additional_properties)) { + json_obj[[key]] <- self$additional_properties[[key]] + } + json_string <- as.character(jsonlite::minify(jsonlite::toJSON(json_obj, auto_unbox = TRUE, digits = NA))) + }, + #' Deserialize JSON string into an instance of Zebra + #' + #' @description + #' Deserialize JSON string into an instance of Zebra + #' + #' @param input_json the JSON input + #' @return the instance of Zebra + #' @export + fromJSONString = function(input_json) { + this_object <- jsonlite::fromJSON(input_json) + if (!is.null(this_object$`type`) && !(this_object$`type` %in% c("plains", "mountain", "grevys"))) { + stop(paste("Error! \"", this_object$`type`, "\" cannot be assigned to `type`. Must be \"plains\", \"mountain\", \"grevys\".", sep = "")) + } + self$`type` <- this_object$`type` + self$`className` <- this_object$`className` + # process additional properties/fields in the payload + for (key in names(this_object)) { + if (!(key %in% self$`_field_list`)) { # json key not in list of fields + self$additional_properties[[key]] <- this_object[[key]] + } + } + + self + }, + #' Validate JSON input with respect to Zebra + #' + #' @description + #' Validate JSON input with respect to Zebra and throw an exception if invalid + #' + #' @param input the JSON input + #' @export + validateJSON = function(input) { + input_json <- jsonlite::fromJSON(input) + # check the required field `className` + if (!is.null(input_json$`className`)) { + stopifnot(is.character(input_json$`className`), length(input_json$`className`) == 1) + } else { + stop(paste("The JSON input `", input, "` is invalid for Zebra: the required field `className` is missing.")) + } + }, + #' To string (JSON format) + #' + #' @description + #' To string (JSON format) + #' + #' @return String representation of Zebra + #' @export + toString = function() { + self$toJSONString() + }, + #' Return true if the values in all fields are valid. + #' + #' @description + #' Return true if the values in all fields are valid. + #' + #' @return true if the values in all fields are valid. + #' @export + isValid = function() { + # check if the required `className` is null + if (is.null(self$`className`)) { + return(FALSE) + } + + TRUE + }, + #' Return a list of invalid fields (if any). + #' + #' @description + #' Return a list of invalid fields (if any). + #' + #' @return A list of invalid fields (if any). + #' @export + getInvalidFields = function() { + invalid_fields <- list() + # check if the required `className` is null + if (is.null(self$`className`)) { + invalid_fields["className"] <- "Non-nullable required field `className` cannot be null." + } + + invalid_fields + }, + #' Print the object + #' + #' @description + #' Print the object + #' + #' @export + print = function() { + print(jsonlite::prettify(self$toJSONString())) + invisible(self) + } + ), + # Lock the class to prevent modifications to the method or field + lock_class = TRUE +) +## Uncomment below to unlock the class to allow modifications of the method or field +# Zebra$unlock() +# +## Below is an example to define the print fnuction +# Zebra$set("public", "print", function(...) { +# print(jsonlite::prettify(self$toJSONString())) +# invisible(self) +# }) +## Uncomment below to lock the class to prevent modifications to the method or field +# Zebra$lock() + diff --git a/samples/client/petstore/R/README.md b/samples/client/petstore/R/README.md index 18c37ed822..263e44af2d 100644 --- a/samples/client/petstore/R/README.md +++ b/samples/client/petstore/R/README.md @@ -55,21 +55,37 @@ install.packages("petstore_1.0.0.tar.gz", repos = NULL, type = "source") library(petstore) ``` +### Reformat code + +To reformat code using [styler](https://styler.r-lib.org/index.html), please run the following in the R console: + +```R +install.packages("remotes") +remotes::install_github("r-lib/styler@v1.7.0.9003") +library("styler") +style_dir() +``` + ## Documentation for API Endpoints All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**AddPetOptional**](docs/FakeApi.md#AddPetOptional) | **POST** /fake/test_optional_body_parameter | Add a new pet to the store (optional body) *FakeApi* | [**FakeDataFile**](docs/FakeApi.md#FakeDataFile) | **GET** /fake/data_file | test data_file to ensure it's escaped correctly +*FakeApi* | [**FakePathArray**](docs/FakeApi.md#FakePathArray) | **GET** /fake/path_array/{path_array}/testing | test array parameter in path +*FakeApi* | [**FakeRegularExpression**](docs/FakeApi.md#FakeRegularExpression) | **GET** /fake/regular_expression | test regular expression to ensure no exception +*FakeApi* | [**FakeSetQuery**](docs/FakeApi.md#FakeSetQuery) | **GET** /fake/set_query_parameter | test set query parameter *PetApi* | [**AddPet**](docs/PetApi.md#AddPet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**DeletePet**](docs/PetApi.md#DeletePet) | **DELETE** /pet/{petId}?streaming | Deletes a pet +*PetApi* | [**DeletePet**](docs/PetApi.md#DeletePet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**FindPetsByStatus**](docs/PetApi.md#FindPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status *PetApi* | [**FindPetsByTags**](docs/PetApi.md#FindPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags *PetApi* | [**GetPetById**](docs/PetApi.md#GetPetById) | **GET** /pet/{petId} | Find pet by ID *PetApi* | [**GetPetByIdStreaming**](docs/PetApi.md#GetPetByIdStreaming) | **GET** /pet/{petId}?streaming | Find pet by ID (streaming) +*PetApi* | [**TestHeader**](docs/PetApi.md#TestHeader) | **GET** /pet_header_test | Header test *PetApi* | [**UpdatePet**](docs/PetApi.md#UpdatePet) | **PUT** /pet | Update an existing pet -*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#UpdatePetWithForm) | **POST** /pet/{petId}?streaming | Updates a pet in the store with form data +*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#UpdatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data *PetApi* | [**UploadFile**](docs/PetApi.md#UploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image *StoreApi* | [**DeleteOrder**](docs/StoreApi.md#DeleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID *StoreApi* | [**GetInventory**](docs/StoreApi.md#GetInventory) | **GET** /store/inventory | Returns pet inventories by status @@ -90,15 +106,19 @@ Class | Method | HTTP request | Description - [AllofTagApiResponse](docs/AllofTagApiResponse.md) - [Animal](docs/Animal.md) - [AnyOfPig](docs/AnyOfPig.md) + - [AnyOfPrimitiveTypeTest](docs/AnyOfPrimitiveTypeTest.md) - [BasquePig](docs/BasquePig.md) - [Cat](docs/Cat.md) - [CatAllOf](docs/CatAllOf.md) - [Category](docs/Category.md) - [DanishPig](docs/DanishPig.md) + - [Date](docs/Date.md) - [Dog](docs/Dog.md) - [DogAllOf](docs/DogAllOf.md) + - [Mammal](docs/Mammal.md) - [ModelApiResponse](docs/ModelApiResponse.md) - [NestedOneOf](docs/NestedOneOf.md) + - [OneOfPrimitiveTypeTest](docs/OneOfPrimitiveTypeTest.md) - [Order](docs/Order.md) - [Pet](docs/Pet.md) - [Pig](docs/Pig.md) @@ -106,29 +126,34 @@ Class | Method | HTTP request | Description - [Tag](docs/Tag.md) - [UpdatePetRequest](docs/UpdatePetRequest.md) - [User](docs/User.md) + - [Whale](docs/Whale.md) + - [Zebra](docs/Zebra.md) ## Documentation for Authorization +### BearerToken + +- **Type**: Bearer authentication + ### api_key - **Type**: API key - **API key parameter name**: api_key - **Location**: HTTP header +### http_auth + +- **Type**: HTTP basic authentication + ### petstore_auth - **Type**: OAuth - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - - write:pets: modify pets in your account - - read:pets: read your pets - - - -## Author - + - `write:pets`: modify pets in your account + - `read:pets`: read your pets diff --git a/samples/client/petstore/R/build_and_test.bash b/samples/client/petstore/R/build_and_test.bash index 2079f75da0..0e7828ec87 100644 --- a/samples/client/petstore/R/build_and_test.bash +++ b/samples/client/petstore/R/build_and_test.bash @@ -18,6 +18,7 @@ Rscript -e "install.packages('base64enc', repos='$REPO', lib='$R_LIBS_USER')" Rscript -e "install.packages('rlang', repos='$REPO', lib='$R_LIBS_USER')" Rscript -e "install.packages('rjson', repos='$REPO', lib='$R_LIBS_USER')" Rscript -e "install.packages('devtools', repos='$REPO', lib='$R_LIBS_USER')" +Rscript -e "install.packages('stringr', repos='$REPO', lib='$R_LIBS_USER')" rm petstore_1.0.0.tar.gz || true diff --git a/samples/client/petstore/R/docs/Animal.md b/samples/client/petstore/R/docs/Animal.md index 5cb0eb8bbf..21af972e0f 100644 --- a/samples/client/petstore/R/docs/Animal.md +++ b/samples/client/petstore/R/docs/Animal.md @@ -5,6 +5,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **character** | | -**color** | **character** | | [optional] [default to "red"] +**color** | **character** | | [optional] [default to "red"] diff --git a/samples/client/petstore/R/docs/AnyOfPrimitiveTypeTest.md b/samples/client/petstore/R/docs/AnyOfPrimitiveTypeTest.md new file mode 100644 index 0000000000..0d8ba0e63b --- /dev/null +++ b/samples/client/petstore/R/docs/AnyOfPrimitiveTypeTest.md @@ -0,0 +1,8 @@ +# petstore::AnyOfPrimitiveTypeTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/R/docs/Cat.md b/samples/client/petstore/R/docs/Cat.md index ba23ea86a3..9a717492c0 100644 --- a/samples/client/petstore/R/docs/Cat.md +++ b/samples/client/petstore/R/docs/Cat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **character** | | -**color** | **character** | | [optional] [default to "red"] +**color** | **character** | | [optional] [default to "red"] **declawed** | **character** | | [optional] diff --git a/samples/client/petstore/R/docs/Category.md b/samples/client/petstore/R/docs/Category.md index 7fa99ae82e..41b20285b8 100644 --- a/samples/client/petstore/R/docs/Category.md +++ b/samples/client/petstore/R/docs/Category.md @@ -6,6 +6,6 @@ A category for a pet Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **integer** | | [optional] -**name** | **character** | | [optional] +**name** | **character** | | [optional] [Pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$] diff --git a/samples/client/petstore/R/docs/Date.md b/samples/client/petstore/R/docs/Date.md new file mode 100644 index 0000000000..ed61f58682 --- /dev/null +++ b/samples/client/petstore/R/docs/Date.md @@ -0,0 +1,12 @@ +# petstore::Date + +to test the model name `Date` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **character** | | +**percent_description** | **character** | using % in the description | [optional] +**url_property** | **character** | | + + diff --git a/samples/client/petstore/R/docs/Dog.md b/samples/client/petstore/R/docs/Dog.md index b2e732df45..6893a5e18e 100644 --- a/samples/client/petstore/R/docs/Dog.md +++ b/samples/client/petstore/R/docs/Dog.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **className** | **character** | | -**color** | **character** | | [optional] [default to "red"] +**color** | **character** | | [optional] [default to "red"] **breed** | **character** | | [optional] diff --git a/samples/client/petstore/R/docs/FakeApi.md b/samples/client/petstore/R/docs/FakeApi.md index 484ca98a1d..4e3f7464f1 100644 --- a/samples/client/petstore/R/docs/FakeApi.md +++ b/samples/client/petstore/R/docs/FakeApi.md @@ -4,9 +4,78 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- +[**AddPetOptional**](FakeApi.md#AddPetOptional) | **POST** /fake/test_optional_body_parameter | Add a new pet to the store (optional body) [**FakeDataFile**](FakeApi.md#FakeDataFile) | **GET** /fake/data_file | test data_file to ensure it's escaped correctly +[**FakePathArray**](FakeApi.md#FakePathArray) | **GET** /fake/path_array/{path_array}/testing | test array parameter in path +[**FakeRegularExpression**](FakeApi.md#FakeRegularExpression) | **GET** /fake/regular_expression | test regular expression to ensure no exception +[**FakeSetQuery**](FakeApi.md#FakeSetQuery) | **GET** /fake/set_query_parameter | test set query parameter +# **AddPetOptional** +> Pet AddPetOptional(pet = var.pet) + +Add a new pet to the store (optional body) + + + +### Example +```R +library(petstore) + +# Add a new pet to the store (optional body) +# +# prepare function argument(s) +var_pet <- Pet$new("name_example", list("photoUrls_example"), 123, Category$new(123, "name_example"), list(Tag$new(123, "name_example")), "available") # Pet | Pet object that needs to be added to the store (Optional) + +api_instance <- FakeApi$new() +# Configure HTTP basic authorization: http_auth +api_instance$api_client$username <- Sys.getenv("USERNAME") +api_instance$api_client$password <- Sys.getenv("PASSWORD") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$AddPetOptional(pet = var_pet, data_file = "result.txt"), + api_instance$AddPetOptional(pet = var_pet), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `AddPetOptional`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml, multipart/related + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + # **FakeDataFile** > User FakeDataFile(dummy, var_data_file = var.var_data_file) @@ -18,10 +87,12 @@ test data_file to ensure it's escaped correctly ```R library(petstore) +# test data_file to ensure it's escaped correctly +# +# prepare function argument(s) var_dummy <- "dummy_example" # character | dummy required parameter -var_var_data_file <- "var_data_file_example" # character | header data file +var_var_data_file <- "var_data_file_example" # character | header data file (Optional) -#test data_file to ensure it's escaped correctly api_instance <- FakeApi$new() result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. @@ -31,15 +102,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `FakeDataFile`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters @@ -67,3 +139,170 @@ No authorization required |-------------|-------------|------------------| | **200** | successful operation | - | +# **FakePathArray** +> FakePathArray(path_array) + +test array parameter in path + + + +### Example +```R +library(petstore) + +# test array parameter in path +# +# prepare function argument(s) +var_path_array <- list("inner_example") # array[character] | dummy path parameter + +api_instance <- FakeApi$new() +result <- tryCatch( + api_instance$FakePathArray(var_path_array), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `FakePathArray`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **path_array** | list( **character** )| dummy path parameter | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **FakeRegularExpression** +> FakeRegularExpression(reg_exp_test) + +test regular expression to ensure no exception + + + +### Example +```R +library(petstore) + +# test regular expression to ensure no exception +# +# prepare function argument(s) +var_reg_exp_test <- "reg_exp_test_example" # character | dummy required parameter + +api_instance <- FakeApi$new() +result <- tryCatch( + api_instance$FakeRegularExpression(var_reg_exp_test), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `FakeRegularExpression`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **reg_exp_test** | **character**| dummy required parameter | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +# **FakeSetQuery** +> FakeSetQuery(set_dummy, array_dummy) + +test set query parameter + + + +### Example +```R +library(petstore) + +# test set query parameter +# +# prepare function argument(s) +var_set_dummy <- list("inner_example") # set[character] | set query +var_array_dummy <- list("inner_example") # array[character] | array query + +api_instance <- FakeApi$new() +result <- tryCatch( + api_instance$FakeSetQuery(var_set_dummy, var_array_dummy), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `FakeSetQuery`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} +# This endpoint doesn't return data +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **set_dummy** | list( **character** )| set query | + **array_dummy** | list( **character** )| array query | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/R/docs/Mammal.md b/samples/client/petstore/R/docs/Mammal.md new file mode 100644 index 0000000000..a2835af3f4 --- /dev/null +++ b/samples/client/petstore/R/docs/Mammal.md @@ -0,0 +1,12 @@ +# petstore::Mammal + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**hasBaleen** | **character** | | [optional] +**hasTeeth** | **character** | | [optional] +**className** | **character** | | +**type** | **character** | | [optional] [Enum: [plains, mountain, grevys]] + + diff --git a/samples/client/petstore/R/docs/OneOfPrimitiveTypeTest.md b/samples/client/petstore/R/docs/OneOfPrimitiveTypeTest.md new file mode 100644 index 0000000000..82cf318431 --- /dev/null +++ b/samples/client/petstore/R/docs/OneOfPrimitiveTypeTest.md @@ -0,0 +1,8 @@ +# petstore::OneOfPrimitiveTypeTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/R/docs/Order.md b/samples/client/petstore/R/docs/Order.md index 2e41a35135..85860b2fb8 100644 --- a/samples/client/petstore/R/docs/Order.md +++ b/samples/client/petstore/R/docs/Order.md @@ -9,7 +9,7 @@ Name | Type | Description | Notes **petId** | **integer** | | [optional] **quantity** | **integer** | | [optional] **shipDate** | **character** | | [optional] -**status** | **character** | Order Status | [optional] -**complete** | **character** | | [optional] [default to FALSE] +**status** | **character** | Order Status | [optional] [Enum: [placed, approved, delivered]] +**complete** | **character** | | [optional] [default to FALSE] diff --git a/samples/client/petstore/R/docs/Pet.md b/samples/client/petstore/R/docs/Pet.md index 63021a8294..29186b2a14 100644 --- a/samples/client/petstore/R/docs/Pet.md +++ b/samples/client/petstore/R/docs/Pet.md @@ -10,6 +10,6 @@ Name | Type | Description | Notes **name** | **character** | | **photoUrls** | **array[character]** | | **tags** | [**array[Tag]**](Tag.md) | | [optional] -**status** | **character** | pet status in the store | [optional] +**status** | **character** | pet status in the store | [optional] [Enum: [available, pending, sold]] diff --git a/samples/client/petstore/R/docs/PetApi.md b/samples/client/petstore/R/docs/PetApi.md index a89cf8fac8..c493fe2da3 100644 --- a/samples/client/petstore/R/docs/PetApi.md +++ b/samples/client/petstore/R/docs/PetApi.md @@ -5,13 +5,14 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**AddPet**](PetApi.md#AddPet) | **POST** /pet | Add a new pet to the store -[**DeletePet**](PetApi.md#DeletePet) | **DELETE** /pet/{petId}?streaming | Deletes a pet +[**DeletePet**](PetApi.md#DeletePet) | **DELETE** /pet/{petId} | Deletes a pet [**FindPetsByStatus**](PetApi.md#FindPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status [**FindPetsByTags**](PetApi.md#FindPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags [**GetPetById**](PetApi.md#GetPetById) | **GET** /pet/{petId} | Find pet by ID [**GetPetByIdStreaming**](PetApi.md#GetPetByIdStreaming) | **GET** /pet/{petId}?streaming | Find pet by ID (streaming) +[**TestHeader**](PetApi.md#TestHeader) | **GET** /pet_header_test | Header test [**UpdatePet**](PetApi.md#UpdatePet) | **PUT** /pet | Update an existing pet -[**UpdatePetWithForm**](PetApi.md#UpdatePetWithForm) | **POST** /pet/{petId}?streaming | Updates a pet in the store with form data +[**UpdatePetWithForm**](PetApi.md#UpdatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data [**UploadFile**](PetApi.md#UploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image @@ -26,12 +27,15 @@ Add a new pet to the store ```R library(petstore) +# Add a new pet to the store +# +# prepare function argument(s) var_pet <- Pet$new("name_example", list("photoUrls_example"), 123, Category$new(123, "name_example"), list(Tag$new(123, "name_example")), "available") # Pet | Pet object that needs to be added to the store -#Add a new pet to the store api_instance <- PetApi$new() -# Configure OAuth2 access token for authorization: petstore_auth -api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +# Configure HTTP basic authorization: http_auth +api_instance$api_client$username <- Sys.getenv("USERNAME") +api_instance$api_client$password <- Sys.getenv("PASSWORD") result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. # api_instance$AddPet(var_pet, data_file = "result.txt"), @@ -40,15 +44,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `AddPet`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters @@ -63,7 +68,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth) +[http_auth](../README.md#http_auth) ### HTTP request headers @@ -87,26 +92,27 @@ Deletes a pet ```R library(petstore) +# Deletes a pet +# +# prepare function argument(s) var_pet_id <- 56 # integer | Pet id to delete -var_api_key <- "api_key_example" # character | +var_api_key <- "api_key_example" # character | (Optional) -#Deletes a pet api_instance <- PetApi$new() # Configure OAuth2 access token for authorization: petstore_auth -api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") result <- tryCatch( api_instance$DeletePet(var_pet_id, api_key = var_api_key), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("Exception occurs when calling `DeletePet`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } +# This endpoint doesn't return data ``` ### Parameters @@ -145,12 +151,14 @@ Multiple status values can be provided with comma separated strings ```R library(petstore) +# Finds Pets by status +# +# prepare function argument(s) var_status <- list("available") # array[character] | Status values that need to be considered for filter -#Finds Pets by status api_instance <- PetApi$new() # Configure OAuth2 access token for authorization: petstore_auth -api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. # api_instance$FindPetsByStatus(var_status, data_file = "result.txt"), @@ -159,15 +167,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `FindPetsByStatus`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters @@ -206,12 +215,12 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ```R library(petstore) +# Finds Pets by tags +# +# prepare function argument(s) var_tags <- list("inner_example") # array[character] | Tags to filter by -#Finds Pets by tags api_instance <- PetApi$new() -# Configure OAuth2 access token for authorization: petstore_auth -api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. # api_instance$FindPetsByTags(var_tags, data_file = "result.txt"), @@ -220,15 +229,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `FindPetsByTags`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters @@ -243,7 +253,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth) +No authorization required ### HTTP request headers @@ -267,12 +277,14 @@ Returns a single pet ```R library(petstore) +# Find pet by ID +# +# prepare function argument(s) var_pet_id <- 56 # integer | ID of pet to return -#Find pet by ID api_instance <- PetApi$new() -# Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +# Configure HTTP bearer authorization: BearerToken +api_instance$api_client$bearer_token <- Sys.getenv("BEARER_TOKEN") result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. # api_instance$GetPetById(var_pet_id, data_file = "result.txt"), @@ -281,15 +293,83 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `GetPetById`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **integer**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[BearerToken](../README.md#BearerToken) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +# **GetPetByIdStreaming** +> Pet GetPetByIdStreaming(pet_id) + +Find pet by ID (streaming) + +Returns a single pet + +### Example +```R +library(petstore) + +# Find pet by ID (streaming) +# +# prepare function argument(s) +var_pet_id <- 56 # integer | ID of pet to return + +api_instance <- PetApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") +result <- tryCatch( + # to save the result into a file, simply add the optional `data_file` parameter, e.g. + # api_instance$GetPetByIdStreaming(var_pet_id, data_file = "result.txt"), + # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. + # api_instance$GetPetByIdStreaming(var_pet_id, stream_callback = function(x){ print(length(x)) }), + api_instance$GetPetByIdStreaming(var_pet_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if (!is.null(result$ApiException)) { + print("Exception occurs when calling `GetPetByIdStreaming`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) +} else { + # deserialized response object + print("The response is ...") + dput(result$toString()) +} + ``` ### Parameters @@ -318,49 +398,52 @@ Name | Type | Description | Notes | **400** | Invalid ID supplied | - | | **404** | Pet not found | - | -# **GetPetByIdStreaming** -> Pet GetPetByIdStreaming(pet_id) +# **TestHeader** +> Pet TestHeader(header_test_int) -Find pet by ID (streaming) +Header test -Returns a single pet +Header test ### Example ```R library(petstore) -var_pet_id <- 56 # integer | ID of pet to return +# Header test +# +# prepare function argument(s) +var_header_test_int <- 56 # integer | header test int -#Find pet by ID (streaming) api_instance <- PetApi$new() # Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. - # api_instance$GetPetByIdStreaming(var_pet_id, data_file = "result.txt"), + # api_instance$TestHeader(var_header_test_int, data_file = "result.txt"), # this endpoint supports data streaming via a callback function using the optional `stream_callback` parameter, e.g. - # api_instance$GetPetByIdStreaming(var_pet_id, stream_callback = function(x){ print(length(x)) }), - api_instance$GetPetByIdStreaming(var_pet_id), + # api_instance$TestHeader(var_header_test_int, stream_callback = function(x){ print(length(x)) }), + api_instance$TestHeader(var_header_test_int), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `TestHeader`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet_id** | **integer**| ID of pet to return | + **header_test_int** | **integer**| header test int | ### Return type @@ -393,12 +476,14 @@ Update an existing pet ```R library(petstore) +# Update an existing pet +# +# prepare function argument(s) var_pet <- Pet$new("name_example", list("photoUrls_example"), 123, Category$new(123, "name_example"), list(Tag$new(123, "name_example")), "available") # Pet | Pet object that needs to be added to the store -#Update an existing pet api_instance <- PetApi$new() # Configure OAuth2 access token for authorization: petstore_auth -api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. # api_instance$UpdatePet(var_pet, data_file = "result.txt"), @@ -407,15 +492,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `UpdatePet`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters @@ -456,27 +542,26 @@ Updates a pet in the store with form data ```R library(petstore) +# Updates a pet in the store with form data +# +# prepare function argument(s) var_pet_id <- 56 # integer | ID of pet that needs to be updated -var_name <- "name_example" # character | Updated name of the pet -var_status <- "status_example" # character | Updated status of the pet +var_name <- "name_example" # character | Updated name of the pet (Optional) +var_status <- "status_example" # character | Updated status of the pet (Optional) -#Updates a pet in the store with form data api_instance <- PetApi$new() -# Configure OAuth2 access token for authorization: petstore_auth -api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; result <- tryCatch( api_instance$UpdatePetWithForm(var_pet_id, name = var_name, status = var_status), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("Exception occurs when calling `UpdatePetWithForm`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } +# This endpoint doesn't return data ``` ### Parameters @@ -493,7 +578,7 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +No authorization required ### HTTP request headers @@ -516,14 +601,16 @@ uploads an image ```R library(petstore) +# uploads an image +# +# prepare function argument(s) var_pet_id <- 56 # integer | ID of pet to update -var_additional_metadata <- "additional_metadata_example" # character | Additional data to pass to server -var_file <- File.new('/path/to/file') # data.frame | file to upload +var_additional_metadata <- "additional_metadata_example" # character | Additional data to pass to server (Optional) +var_file <- File.new('/path/to/file') # data.frame | file to upload (Optional) -#uploads an image api_instance <- PetApi$new() # Configure OAuth2 access token for authorization: petstore_auth -api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +api_instance$api_client$access_token <- Sys.getenv("ACCESS_TOKEN") result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. # api_instance$UploadFile(var_pet_id, additional_metadata = var_additional_metadata, file = var_file, data_file = "result.txt"), @@ -532,15 +619,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `UploadFile`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters diff --git a/samples/client/petstore/R/docs/Special.md b/samples/client/petstore/R/docs/Special.md index 0114a84c8f..83c2794ec3 100644 --- a/samples/client/petstore/R/docs/Special.md +++ b/samples/client/petstore/R/docs/Special.md @@ -5,6 +5,7 @@ Describes the result of uploading an image resource ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**set_test** | **set[character]** | | [optional] **item_self** | **integer** | | [optional] **item_private** | **character** | | [optional] **item_super** | **character** | | [optional] diff --git a/samples/client/petstore/R/docs/StoreApi.md b/samples/client/petstore/R/docs/StoreApi.md index 31343a84ea..b58b49eb76 100644 --- a/samples/client/petstore/R/docs/StoreApi.md +++ b/samples/client/petstore/R/docs/StoreApi.md @@ -21,9 +21,11 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ```R library(petstore) +# Delete purchase order by ID +# +# prepare function argument(s) var_order_id <- "order_id_example" # character | ID of the order that needs to be deleted -#Delete purchase order by ID api_instance <- StoreApi$new() result <- tryCatch( api_instance$DeleteOrder(var_order_id), @@ -31,13 +33,12 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("Exception occurs when calling `DeleteOrder`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } +# This endpoint doesn't return data ``` ### Parameters @@ -76,11 +77,12 @@ Returns a map of status codes to quantities ```R library(petstore) +# Returns pet inventories by status +# -#Returns pet inventories by status api_instance <- StoreApi$new() # Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. # api_instance$GetInventory(data_file = "result.txt"), @@ -89,15 +91,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `GetInventory`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters @@ -132,9 +135,11 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ```R library(petstore) +# Find purchase order by ID +# +# prepare function argument(s) var_order_id <- 56 # integer | ID of pet that needs to be fetched -#Find purchase order by ID api_instance <- StoreApi$new() result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. @@ -144,15 +149,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `GetOrderById`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters @@ -192,9 +198,11 @@ Place an order for a pet ```R library(petstore) +# Place an order for a pet +# +# prepare function argument(s) var_order <- Order$new(123, 123, 123, "shipDate_example", "placed", "complete_example") # Order | order placed for purchasing the pet -#Place an order for a pet api_instance <- StoreApi$new() result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. @@ -204,15 +212,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `PlaceOrder`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters diff --git a/samples/client/petstore/R/docs/UserApi.md b/samples/client/petstore/R/docs/UserApi.md index 3382f734ce..ffc5e09b9e 100644 --- a/samples/client/petstore/R/docs/UserApi.md +++ b/samples/client/petstore/R/docs/UserApi.md @@ -25,25 +25,26 @@ This can only be done by the logged in user. ```R library(petstore) +# Create user +# +# prepare function argument(s) var_user <- User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123) # User | Created user object -#Create user api_instance <- UserApi$new() # Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") result <- tryCatch( api_instance$CreateUser(var_user), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("Exception occurs when calling `CreateUser`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } +# This endpoint doesn't return data ``` ### Parameters @@ -81,25 +82,26 @@ Creates list of users with given input array ```R library(petstore) +# Creates list of users with given input array +# +# prepare function argument(s) var_user <- list(User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123)) # array[User] | List of user object -#Creates list of users with given input array api_instance <- UserApi$new() # Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") result <- tryCatch( api_instance$CreateUsersWithArrayInput(var_user), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("Exception occurs when calling `CreateUsersWithArrayInput`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } +# This endpoint doesn't return data ``` ### Parameters @@ -137,25 +139,26 @@ Creates list of users with given input array ```R library(petstore) +# Creates list of users with given input array +# +# prepare function argument(s) var_user <- list(User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123)) # array[User] | List of user object -#Creates list of users with given input array api_instance <- UserApi$new() # Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") result <- tryCatch( api_instance$CreateUsersWithListInput(var_user), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("Exception occurs when calling `CreateUsersWithListInput`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } +# This endpoint doesn't return data ``` ### Parameters @@ -193,25 +196,26 @@ This can only be done by the logged in user. ```R library(petstore) +# Delete user +# +# prepare function argument(s) var_username <- "username_example" # character | The name that needs to be deleted -#Delete user api_instance <- UserApi$new() # Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") result <- tryCatch( api_instance$DeleteUser(var_username), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("Exception occurs when calling `DeleteUser`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } +# This endpoint doesn't return data ``` ### Parameters @@ -250,9 +254,11 @@ Get user by user name ```R library(petstore) +# Get user by user name +# +# prepare function argument(s) var_username <- "username_example" # character | The name that needs to be fetched. Use user1 for testing. -#Get user by user name api_instance <- UserApi$new() result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. @@ -262,15 +268,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `GetUserByName`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters @@ -310,10 +317,12 @@ Logs user into the system ```R library(petstore) +# Logs user into the system +# +# prepare function argument(s) var_username <- "username_example" # character | The user name for login var_password <- "password_example" # character | The password for login in clear text -#Logs user into the system api_instance <- UserApi$new() result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. @@ -323,15 +332,16 @@ result <- tryCatch( ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) + print("Exception occurs when calling `LoginUser`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } else { # deserialized response object - response.object <- result$content - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("The response is ...") + dput(result$toString()) } + ``` ### Parameters @@ -371,24 +381,24 @@ Logs out current logged in user session ```R library(petstore) +# Logs out current logged in user session +# -#Logs out current logged in user session api_instance <- UserApi$new() # Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") result <- tryCatch( api_instance$LogoutUser(), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("Exception occurs when calling `LogoutUser`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } +# This endpoint doesn't return data ``` ### Parameters @@ -423,26 +433,27 @@ This can only be done by the logged in user. ```R library(petstore) +# Updated user +# +# prepare function argument(s) var_username <- "username_example" # character | name that need to be deleted var_user <- User$new(123, "username_example", "firstName_example", "lastName_example", "email_example", "password_example", "phone_example", 123) # User | Updated user object -#Updated user api_instance <- UserApi$new() # Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +api_instance$api_client$api_keys["api_key"] <- Sys.getenv("API_KEY") result <- tryCatch( api_instance$UpdateUser(var_username, var_user), ApiException = function(ex) ex ) # In case of error, print the error object if (!is.null(result$ApiException)) { - cat(result$ApiException$toString()) -} else { - # response headers - response.headers <- result$response$headers - # response status code - response.status.code <- result$response$status_code + print("Exception occurs when calling `UpdateUser`:") + dput(result$ApiException$toString()) + # error object + dput(result$ApiException$error_object$toJSONString()) } +# This endpoint doesn't return data ``` ### Parameters diff --git a/samples/client/petstore/R/docs/Whale.md b/samples/client/petstore/R/docs/Whale.md new file mode 100644 index 0000000000..bd0d148686 --- /dev/null +++ b/samples/client/petstore/R/docs/Whale.md @@ -0,0 +1,11 @@ +# petstore::Whale + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**hasBaleen** | **character** | | [optional] +**hasTeeth** | **character** | | [optional] +**className** | **character** | | + + diff --git a/samples/client/petstore/R/docs/Zebra.md b/samples/client/petstore/R/docs/Zebra.md new file mode 100644 index 0000000000..51b7094126 --- /dev/null +++ b/samples/client/petstore/R/docs/Zebra.md @@ -0,0 +1,10 @@ +# petstore::Zebra + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | **character** | | [optional] [Enum: [plains, mountain, grevys]] +**className** | **character** | | + + diff --git a/samples/client/petstore/R/test_petstore.R b/samples/client/petstore/R/test_petstore.R index ed6479680e..40b2f35880 100644 --- a/samples/client/petstore/R/test_petstore.R +++ b/samples/client/petstore/R/test_petstore.R @@ -8,6 +8,8 @@ var_pet <- Pet$new("name_example", list("photoUrls_example"), 56, Category$new(5 api_instance <- PetApi$new() # Configure OAuth2 access token for authorization: petstore_auth api_instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN'; +api_instance$api_client$username <- 'username'; +api_instance$api_client$password <- 'password'; result <- tryCatch( # to save the result into a file, simply add the optional `data_file` parameter, e.g. # api_instance$AddPet(var_pet, data_file = "result.txt"), @@ -17,16 +19,18 @@ result <- tryCatch( var_pet_id <- 56 # integer | ID of pet to return -#Find pet by ID (streaming) -api_instance <- PetApi$new() -# Configure API key authorization: api_key -api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; -result <- tryCatch( - # to save the result into a file, simply add the optional `data_file` parameter, e.g. - # api_instance$GetPetByIdStreaming(var_pet_id, data_file = "result.txt"), - api_instance$GetPetByIdStreaming(var_pet_id, stream_callback = function(x) { print(x) }), - ApiException = function(ex) ex - ) +result <- api_instance$FindPetsByStatus("available") +dput(result) +##Find pet by ID (streaming) +#api_instance <- PetApi$new() +## Configure API key authorization: api_key +#api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +#result <- tryCatch( +# # to save the result into a file, simply add the optional `data_file` parameter, e.g. +# # api_instance$GetPetByIdStreaming(var_pet_id, data_file = "result.txt"), +# api_instance$GetPetByIdStreaming(var_pet_id, stream_callback = function(x) { print(x) }), +# ApiException = function(ex) ex +# ) # In case of error, print the error object #if (!is.null(result$ApiException)) { # cat(result$ApiException$toString()) @@ -45,27 +49,28 @@ result <- tryCatch( ##a <- ModelApiResponse$new()$fromJSONString(errorMsg) ##dput(a) ## -##var_pet_id <- 1231256 # integer | ID of pet to return -## -###Find pet by ID -##api_instance <- PetApi$new() -### Configure API key authorization: api_key -##api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; -##result <- tryCatch( -## api_instance$GetPetById(var_pet_id), -## ApiException = function(ex) ex -## ) -### In case of error, print the error object -##if(!is.null(result$ApiException)) { -## cat(result$ApiException$toString()) -##} else { -## # deserialized response object -## response.object <- result$content -## # response headers -## response.headers <- result$response$headers -## # response status code -## response.status.code <- result$response$status_code -##} + +## Test exceptions +var_pet_id <- 1231256 # integer | ID of pet to return +#Find pet by ID +api_instance <- PetApi$new() +# Configure API key authorization: api_key +api_instance$api_client$api_keys['api_key'] <- 'TODO_YOUR_API_KEY'; +result <- tryCatch( + api_instance$GetPetById(var_pet_id), + ApiException = function(ex) ex + ) +# In case of error, print the error object +if(!is.null(result$ApiException)) { + cat(result$ApiException$toString()) +} else { + # deserialized response object + response.object <- result$content + # response headers + response.headers <- result$response$headers + # response status code + response.status.code <- result$response$status_code +} # #json2 <- #'{"name": "pet", "photoUrls" : ["http://a.com", "http://b.com"]}' diff --git a/samples/client/petstore/R/tests/testthat/test_any_of_primitive_type_test.R b/samples/client/petstore/R/tests/testthat/test_any_of_primitive_type_test.R new file mode 100644 index 0000000000..0679cfaf44 --- /dev/null +++ b/samples/client/petstore/R/tests/testthat/test_any_of_primitive_type_test.R @@ -0,0 +1,4 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test AnyOfPrimitiveTypeTest") diff --git a/samples/client/petstore/R/tests/testthat/test_date.R b/samples/client/petstore/R/tests/testthat/test_date.R new file mode 100644 index 0000000000..214fd8a352 --- /dev/null +++ b/samples/client/petstore/R/tests/testthat/test_date.R @@ -0,0 +1,13 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Date") + +model_instance <- Date$new() + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R/tests/testthat/test_mammal.R b/samples/client/petstore/R/tests/testthat/test_mammal.R new file mode 100644 index 0000000000..bc061ea799 --- /dev/null +++ b/samples/client/petstore/R/tests/testthat/test_mammal.R @@ -0,0 +1,34 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Mammal") + +model_instance <- Mammal$new() + +test_that("hasBaleen", { + # tests for the property `hasBaleen` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasBaleen`, "EXPECTED_RESULT") +}) + +test_that("hasTeeth", { + # tests for the property `hasTeeth` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasTeeth`, "EXPECTED_RESULT") +}) + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R/tests/testthat/test_one_of_primitive_type_test.R b/samples/client/petstore/R/tests/testthat/test_one_of_primitive_type_test.R new file mode 100644 index 0000000000..f9e7158359 --- /dev/null +++ b/samples/client/petstore/R/tests/testthat/test_one_of_primitive_type_test.R @@ -0,0 +1,4 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test OneOfPrimitiveTypeTest") diff --git a/samples/client/petstore/R/tests/testthat/test_petstore.R b/samples/client/petstore/R/tests/testthat/test_petstore.R index b59366abe7..4a205dd200 100644 --- a/samples/client/petstore/R/tests/testthat/test_petstore.R +++ b/samples/client/petstore/R/tests/testthat/test_petstore.R @@ -11,13 +11,35 @@ pet <- Pet$new("name_test", ), status = "available" ) + +# no need to set uasername, password and there should be no error +# since the endpoint can support multi auth schema +#pet_api$api_client$username <- "" +#pet_api$api_client$password <- "" result <- pet_api$AddPet(pet) -test_that("AddPet", { +test_that("Test discriminator and mapping", { + d <- '{"breed": "bulldog","color":"white","className":"Dog"}' + dog <- ApiClient$new()$deserialize(d, "Animal", loadNamespace("petstore")) + expect_equal(class(dog)[1], "Dog") + expect_equal(dog$breed, "bulldog") + expect_equal(dog$color, "white") + expect_equal(dog$className, "Dog") +}) + +test_that("Test toJSONString", { expect_equal(pet_id, 123321) expect_equal(pet$toJSONString(), '{"id":123321,"category":{"id":450,"name":"test_cat"},"name":"name_test","photoUrls":["photo_test","second test"],"tags":[{"id":123,"name":"tag_test"},{"id":456,"name":"unknown"}],"status":"available"}') }) +test_that("Test FindPetByStatus", { + pet_api$api_client$oauth_client_id <- "client_id_test" + pet_api$api_client$oauth_secret <- "secret_test" + + result <- pet_api$FindPetsByStatus("available") + expect_equal(result[[1]]$status, "available") +}) + test_that("Test toJSON toJSONString fromJSON fromJSONString", { pet0 <- Pet$new() jsonpet <- pet0$toJSON() @@ -99,18 +121,33 @@ test_that("GetPetByIdStreaming", { ) }) -#test_that("test GetPetById exception", { -# # test exception -# result <- tryCatch(petApi$GetPetById(98765), # petId not exist -# error = function(ex) ex -# ) -# -# expect_true(!is.null(result)) -# #expect_equal(result$toString(),"") -# expect_equal(result, "1") -# #expect_equal(result$ApiException$errorObject$code, 1) -# #expect_equal(response$name, "name_test") -#}) +test_that("Test header parameters", { + # test exception + result <- tryCatch(pet_api$TestHeader(45345), + ApiException = function(ex) ex + ) + + expect_true(!is.null(result)) + expect_true(!is.null(result$ApiException)) + expect_equal(result$ApiException$status, 404) + # test error object `ApiResponse` + #expect_equal(result$ApiException$error_object$toString(), "{\"code\":404,\"type\":\"unknown\",\"message\":\"null for uri: http://pet\n x[1]: store.swagger.io/v2/pet_header_test\"}") + expect_equal(result$ApiException$error_object$code, 404) +}) + +test_that("Test GetPetById exception", { + # test exception + result <- tryCatch(pet_api$GetPetById(98765), # petId not exist + ApiException = function(ex) ex + ) + + expect_true(!is.null(result)) + expect_true(!is.null(result$ApiException)) + expect_equal(result$ApiException$status, 404) + # test error object `ApiResponse` + expect_equal(result$ApiException$error_object$toString(), "{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}") + expect_equal(result$ApiException$error_object$code, 1) +}) test_that("GetPetById with data_file", { # test to ensure json is saved to the file `get_pet_by_id.json` @@ -313,7 +350,3 @@ test_that("Tests anyOf", { # #expect_equal(response$tags, list(Tag$new(123, "tag_test"), Tag$new(456, "unknown"))) #}) -#test_that("updatePetWithForm", { -# response <- pet_api$updatePetWithForm(pet_id, "test", "sold") -# expect_equal(response, "Pet updated") -#}) diff --git a/samples/client/petstore/R/tests/testthat/test_whale.R b/samples/client/petstore/R/tests/testthat/test_whale.R new file mode 100644 index 0000000000..b19c7b9eb3 --- /dev/null +++ b/samples/client/petstore/R/tests/testthat/test_whale.R @@ -0,0 +1,27 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Whale") + +model_instance <- Whale$new() + +test_that("hasBaleen", { + # tests for the property `hasBaleen` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasBaleen`, "EXPECTED_RESULT") +}) + +test_that("hasTeeth", { + # tests for the property `hasTeeth` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`hasTeeth`, "EXPECTED_RESULT") +}) + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/R/tests/testthat/test_zebra.R b/samples/client/petstore/R/tests/testthat/test_zebra.R new file mode 100644 index 0000000000..444da2f8f7 --- /dev/null +++ b/samples/client/petstore/R/tests/testthat/test_zebra.R @@ -0,0 +1,20 @@ +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate + +context("Test Zebra") + +model_instance <- Zebra$new() + +test_that("type", { + # tests for the property `type` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`type`, "EXPECTED_RESULT") +}) + +test_that("className", { + # tests for the property `className` (character) + + # uncomment below to test the property + #expect_equal(model.instance$`className`, "EXPECTED_RESULT") +}) diff --git a/samples/client/petstore/cpp-qt/PetStore/PetStore.pro b/samples/client/petstore/cpp-qt/PetStore/PetStore.pro index 961daeeeff..6ac197536f 100644 --- a/samples/client/petstore/cpp-qt/PetStore/PetStore.pro +++ b/samples/client/petstore/cpp-qt/PetStore/PetStore.pro @@ -6,8 +6,6 @@ QT += core gui testlib network -QT -= gui - TARGET = PetStore CONFIG += console CONFIG -= app_bundle diff --git a/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp index b05c2c1921..6ceed15161 100644 --- a/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp @@ -203,7 +203,7 @@ void PFXHttpRequestWorker::execute(PFXHttpRequestInput *input) { if (input->vars.count() > 0) { bool first = true; isFormData = true; - foreach (QString key, input->vars.keys()) { + for (QString key : input->vars.keys()) { if (!first) { request_content.append("&"); } @@ -234,7 +234,7 @@ void PFXHttpRequestWorker::execute(PFXHttpRequestInput *input) { QString new_line = "\r\n"; // add variables - foreach (QString key, input->vars.keys()) { + for (QString key : input->vars.keys()) { // add boundary request_content.append(boundary_delimiter.toUtf8()); request_content.append(boundary.toUtf8()); @@ -336,7 +336,7 @@ void PFXHttpRequestWorker::execute(PFXHttpRequestInput *input) { request.setSslConfiguration(*PFXHttpRequestWorker::sslDefaultConfiguration); } request.setRawHeader("User-Agent", "OpenAPI-Generator/1.0.0/cpp-qt"); - foreach (QString key, input->headers.keys()) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } + for (QString key : input->headers.keys()) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } if (request_content.size() > 0 && !isFormData && (input->var_layout != MULTIPART)) { if (!input->headers.contains("Content-Type")) { diff --git a/samples/client/petstore/cpp-qt/client/PFXOauth.cpp b/samples/client/petstore/cpp-qt/client/PFXOauth.cpp index f5617124bb..7354a96f6f 100644 --- a/samples/client/petstore/cpp-qt/client/PFXOauth.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXOauth.cpp @@ -327,8 +327,7 @@ void ReplyServer::read() QMap queryParams; - QPair tokenPair; - foreach (tokenPair, tokens) { + for (auto tokenPair : tokens) { QString key = QUrl::fromPercentEncoding(QByteArray().append(tokenPair.first.trimmed().toLatin1())); QString value = QUrl::fromPercentEncoding(QByteArray().append(tokenPair.second.trimmed().toLatin1())); queryParams.insert(key, value); diff --git a/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp b/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp index 5bb15e1620..e1822961fa 100644 --- a/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp @@ -73,7 +73,7 @@ void PFXPetApi::setServerIndex(const QString &operation, int serverIndex) { } void PFXPetApi::setApiKey(const QString &apiKeyName, const QString &apiKey) { - _apiKeys.insert(apiKeyName,apiKey); + _apiKeys.insert(apiKeyName, apiKey); } void PFXPetApi::setBearerToken(const QString &token) { @@ -274,7 +274,7 @@ void PFXPetApi::addPet(const PFXPet &pfx_pet) { _latestWorker = new PFXHttpRequestWorker(this, _manager); _latestWorker->setTimeOut(_timeOut); _latestWorker->setWorkingDirectory(_workingDirectory); - + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::addPetCallback); connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -363,7 +363,7 @@ void PFXPetApi::allPetsCallback(PFXHttpRequestWorker *worker) { QByteArray array(json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonArray jsonArray = doc.array(); - foreach (QJsonValue obj, jsonArray) { + for (QJsonValue obj : jsonArray) { PFXPet val; ::test_namespace::fromJsonValue(val, obj); output.insert(val); @@ -440,7 +440,7 @@ void PFXPetApi::deletePet(const qint64 &pet_id, const ::test_namespace::Optional _latestWorker = new PFXHttpRequestWorker(this, _manager); _latestWorker->setTimeOut(_timeOut); _latestWorker->setWorkingDirectory(_workingDirectory); - + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::deletePetCallback); connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -501,7 +501,7 @@ void PFXPetApi::findPetsByStatus(const QList &status) { queryDelimiter = getParamStyleDelimiter(queryStyle, "status", false); if (status.size() > 0) { if (QString("csv").indexOf("multi") == 0) { - foreach (QString t, status) { + for (QString t : status) { if (fullPath.indexOf("?") > 0) fullPath.append(queryPrefix); else @@ -514,7 +514,7 @@ void PFXPetApi::findPetsByStatus(const QList &status) { else fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); qint32 count = 0; - foreach (QString t, status) { + for (QString t : status) { if (count > 0) { fullPath.append((false)? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter)); } @@ -527,7 +527,7 @@ void PFXPetApi::findPetsByStatus(const QList &status) { else fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); qint32 count = 0; - foreach (QString t, status) { + for (QString t : status) { if (count > 0) { fullPath.append("\t"); } @@ -540,7 +540,7 @@ void PFXPetApi::findPetsByStatus(const QList &status) { else fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); qint32 count = 0; - foreach (QString t, status) { + for (QString t : status) { if (count > 0) { fullPath.append(queryDelimiter); } @@ -553,7 +553,7 @@ void PFXPetApi::findPetsByStatus(const QList &status) { else fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); qint32 count = 0; - foreach (QString t, status) { + for (QString t : status) { if (count > 0) { fullPath.append(queryDelimiter); } @@ -566,7 +566,7 @@ void PFXPetApi::findPetsByStatus(const QList &status) { else fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); qint32 count = 0; - foreach (QString t, status) { + for (QString t : status) { if (count > 0) { fullPath.append(queryDelimiter); } @@ -614,7 +614,7 @@ void PFXPetApi::findPetsByStatus(const QList &status) { _latestWorker = new PFXHttpRequestWorker(this, _manager); _latestWorker->setTimeOut(_timeOut); _latestWorker->setWorkingDirectory(_workingDirectory); - + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByStatusCallback); connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -643,7 +643,7 @@ void PFXPetApi::findPetsByStatusCallback(PFXHttpRequestWorker *worker) { QByteArray array(json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonArray jsonArray = doc.array(); - foreach (QJsonValue obj, jsonArray) { + for (QJsonValue obj : jsonArray) { PFXPet val; ::test_namespace::fromJsonValue(val, obj); output.append(val); @@ -685,7 +685,7 @@ void PFXPetApi::findPetsByTags(const QList &tags) { queryDelimiter = getParamStyleDelimiter(queryStyle, "tags", false); if (tags.size() > 0) { if (QString("csv").indexOf("multi") == 0) { - foreach (QString t, tags) { + for (QString t : tags) { if (fullPath.indexOf("?") > 0) fullPath.append(queryPrefix); else @@ -698,7 +698,7 @@ void PFXPetApi::findPetsByTags(const QList &tags) { else fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); qint32 count = 0; - foreach (QString t, tags) { + for (QString t : tags) { if (count > 0) { fullPath.append((false)? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter)); } @@ -711,7 +711,7 @@ void PFXPetApi::findPetsByTags(const QList &tags) { else fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); qint32 count = 0; - foreach (QString t, tags) { + for (QString t : tags) { if (count > 0) { fullPath.append("\t"); } @@ -724,7 +724,7 @@ void PFXPetApi::findPetsByTags(const QList &tags) { else fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); qint32 count = 0; - foreach (QString t, tags) { + for (QString t : tags) { if (count > 0) { fullPath.append(queryDelimiter); } @@ -737,7 +737,7 @@ void PFXPetApi::findPetsByTags(const QList &tags) { else fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); qint32 count = 0; - foreach (QString t, tags) { + for (QString t : tags) { if (count > 0) { fullPath.append(queryDelimiter); } @@ -750,7 +750,7 @@ void PFXPetApi::findPetsByTags(const QList &tags) { else fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); qint32 count = 0; - foreach (QString t, tags) { + for (QString t : tags) { if (count > 0) { fullPath.append(queryDelimiter); } @@ -798,7 +798,7 @@ void PFXPetApi::findPetsByTags(const QList &tags) { _latestWorker = new PFXHttpRequestWorker(this, _manager); _latestWorker->setTimeOut(_timeOut); _latestWorker->setWorkingDirectory(_workingDirectory); - + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByTagsCallback); connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -827,7 +827,7 @@ void PFXPetApi::findPetsByTagsCallback(PFXHttpRequestWorker *worker) { QByteArray array(json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonArray jsonArray = doc.array(); - foreach (QJsonValue obj, jsonArray) { + for (QJsonValue obj : jsonArray) { PFXPet val; ::test_namespace::fromJsonValue(val, obj); output.append(val); @@ -968,7 +968,7 @@ void PFXPetApi::updatePet(const PFXPet &pfx_pet) { _latestWorker = new PFXHttpRequestWorker(this, _manager); _latestWorker->setTimeOut(_timeOut); _latestWorker->setWorkingDirectory(_workingDirectory); - + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetCallback); connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -1078,7 +1078,7 @@ void PFXPetApi::updatePetWithForm(const qint64 &pet_id, const ::test_namespace:: _latestWorker = new PFXHttpRequestWorker(this, _manager); _latestWorker->setTimeOut(_timeOut); _latestWorker->setWorkingDirectory(_workingDirectory); - + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetWithFormCallback); connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -1188,7 +1188,7 @@ void PFXPetApi::uploadFile(const qint64 &pet_id, const ::test_namespace::Optiona _latestWorker = new PFXHttpRequestWorker(this, _manager); _latestWorker->setTimeOut(_timeOut); _latestWorker->setWorkingDirectory(_workingDirectory); - + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::uploadFileCallback); connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ @@ -1237,8 +1237,8 @@ void PFXPetApi::uploadFileCallback(PFXHttpRequestWorker *worker) { } void PFXPetApi::tokenAvailable(){ - - oauthToken token; + + oauthToken token; switch (_OauthMethod) { case 1: //implicit flow token = _implicitFlow.getToken(_latestScope.join(" ")); @@ -1256,7 +1256,7 @@ void PFXPetApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _authFlow.removeToken(_latestScope.join(" ")); + _authFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -1266,7 +1266,7 @@ void PFXPetApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -1276,7 +1276,7 @@ void PFXPetApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; diff --git a/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.cpp b/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.cpp index 6832b19a93..792128b66f 100644 --- a/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.cpp @@ -59,7 +59,7 @@ void PFXPrimitivesApi::setServerIndex(const QString &operation, int serverIndex) } void PFXPrimitivesApi::setApiKey(const QString &apiKeyName, const QString &apiKey) { - _apiKeys.insert(apiKeyName,apiKey); + _apiKeys.insert(apiKeyName, apiKey); } void PFXPrimitivesApi::setBearerToken(const QString &token) { @@ -319,8 +319,8 @@ void PFXPrimitivesApi::primitivesNumberPutCallback(PFXHttpRequestWorker *worker) } void PFXPrimitivesApi::tokenAvailable(){ - - oauthToken token; + + oauthToken token; switch (_OauthMethod) { case 1: //implicit flow token = _implicitFlow.getToken(_latestScope.join(" ")); @@ -338,7 +338,7 @@ void PFXPrimitivesApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _authFlow.removeToken(_latestScope.join(" ")); + _authFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -348,7 +348,7 @@ void PFXPrimitivesApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -358,7 +358,7 @@ void PFXPrimitivesApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; diff --git a/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp b/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp index 55a6cb040d..77a98da9c7 100644 --- a/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp @@ -63,7 +63,7 @@ void PFXStoreApi::setServerIndex(const QString &operation, int serverIndex) { } void PFXStoreApi::setApiKey(const QString &apiKeyName, const QString &apiKey) { - _apiKeys.insert(apiKeyName,apiKey); + _apiKeys.insert(apiKeyName, apiKey); } void PFXStoreApi::setBearerToken(const QString &token) { @@ -326,7 +326,7 @@ void PFXStoreApi::getInventoryCallback(PFXHttpRequestWorker *worker) { QByteArray array(json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject obj = doc.object(); - foreach (QString key, obj.keys()) { + for (QString key : obj.keys()) { qint32 val; ::test_namespace::fromJsonValue(val, obj[key]); output.insert(key, val); @@ -460,8 +460,8 @@ void PFXStoreApi::placeOrderCallback(PFXHttpRequestWorker *worker) { } void PFXStoreApi::tokenAvailable(){ - - oauthToken token; + + oauthToken token; switch (_OauthMethod) { case 1: //implicit flow token = _implicitFlow.getToken(_latestScope.join(" ")); @@ -479,7 +479,7 @@ void PFXStoreApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _authFlow.removeToken(_latestScope.join(" ")); + _authFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -489,7 +489,7 @@ void PFXStoreApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -499,7 +499,7 @@ void PFXStoreApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; diff --git a/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp b/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp index 420cba72cd..197825fd03 100644 --- a/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp @@ -71,7 +71,7 @@ void PFXUserApi::setServerIndex(const QString &operation, int serverIndex) { } void PFXUserApi::setApiKey(const QString &apiKeyName, const QString &apiKey) { - _apiKeys.insert(apiKeyName,apiKey); + _apiKeys.insert(apiKeyName, apiKey); } void PFXUserApi::setBearerToken(const QString &token) { @@ -705,8 +705,8 @@ void PFXUserApi::updateUserCallback(PFXHttpRequestWorker *worker) { } void PFXUserApi::tokenAvailable(){ - - oauthToken token; + + oauthToken token; switch (_OauthMethod) { case 1: //implicit flow token = _implicitFlow.getToken(_latestScope.join(" ")); @@ -724,7 +724,7 @@ void PFXUserApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _authFlow.removeToken(_latestScope.join(" ")); + _authFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -734,7 +734,7 @@ void PFXUserApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; @@ -744,7 +744,7 @@ void PFXUserApi::tokenAvailable(){ _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); _latestWorker->execute(&_latestInput); }else{ - _credentialFlow.removeToken(_latestScope.join(" ")); + _credentialFlow.removeToken(_latestScope.join(" ")); qDebug() << "Could not retrieve a valid token"; } break; diff --git a/samples/client/petstore/cpp-tiny/lib/service/AbstractService.cpp b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.cpp new file mode 100644 index 0000000000..ac7e992cec --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.cpp @@ -0,0 +1,8 @@ +#include "AbstractService.h" +#include "Arduino.h" + + + +void Tiny::AbstractService::begin(std::string url){ + http.begin(String(url.c_str()), test_root_ca); //HTTPS connection +} diff --git a/samples/client/petstore/cpp-tiny/lib/service/AbstractService.h b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.h new file mode 100644 index 0000000000..07214896d7 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.h @@ -0,0 +1,28 @@ +#ifndef TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +#define TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ + +#include "HTTPClient.h" +#include "Response.h" +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +class AbstractService { +public: +HTTPClient http; +std::string basepath = "https://petstore3.swagger.io/api/v3"; // TODO: change to your url + +void begin(std::string url); + +// Go and comment out a certificate in root.cert, if you get an error here +// Certificate from file +const char* test_root_ca = +#include "../../root.cert" +; + +}; // end class +}// namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ */ diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h index 4c885c815a..277acf200f 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h @@ -18,6 +18,7 @@ #include "Dom/JsonObject.h" #include "HttpRetrySystem.h" #include "Containers/Ticker.h" +#include "Runtime/Launch/Resources/Version.h" namespace OpenAPI { @@ -25,7 +26,13 @@ namespace OpenAPI typedef TSharedRef> JsonWriter; using namespace FHttpRetrySystem; -struct OPENAPI_API HttpRetryManager : public FManager, public FTickerObjectBase +struct OPENAPI_API HttpRetryManager + : public FManager +#if ENGINE_MAJOR_VERSION <= 4 + , public FTickerObjectBase +#else + , public FTSTickerObjectBase +#endif { using FManager::FManager; diff --git a/samples/client/petstore/crystal/.openapi-generator/FILES b/samples/client/petstore/crystal/.openapi-generator/FILES index aa17a1e4b9..ab944b040a 100644 --- a/samples/client/petstore/crystal/.openapi-generator/FILES +++ b/samples/client/petstore/crystal/.openapi-generator/FILES @@ -13,6 +13,7 @@ src/petstore/api_error.cr src/petstore/configuration.cr src/petstore/models/api_response.cr src/petstore/models/category.cr +src/petstore/models/format_test.cr src/petstore/models/order.cr src/petstore/models/pet.cr src/petstore/models/tag.cr diff --git a/samples/client/petstore/crystal/spec/models/format_test_spec.cr b/samples/client/petstore/crystal/spec/models/format_test_spec.cr new file mode 100644 index 0000000000..8801945aec --- /dev/null +++ b/samples/client/petstore/crystal/spec/models/format_test_spec.cr @@ -0,0 +1,122 @@ +# #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. +# +#The version of the OpenAPI document: 1.0.0 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 6.2.1-SNAPSHOT +# + +require "../spec_helper" +require "json" +require "time" + +# Unit tests for Petstore::FormatTest +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::FormatTest do + + describe "test an instance of FormatTest" do + it "should create an instance of FormatTest" do + #instance = Petstore::FormatTest.new + #expect(instance).to be_instance_of(Petstore::FormatTest) + end + end + describe "test attribute 'integer'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'int32'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'int64'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'number'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'float'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'double'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'decimal'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'string'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'byte'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'binary'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'date'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'date_time'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'uuid'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'password'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'pattern_with_digits'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + + describe "test attribute 'pattern_with_digits_and_delimiter'" do + it "should work" do + # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html + end + end + +end diff --git a/samples/client/petstore/crystal/src/petstore/models/api_response.cr b/samples/client/petstore/crystal/src/petstore/models/api_response.cr index 33e05018f8..f0f1fec0cf 100644 --- a/samples/client/petstore/crystal/src/petstore/models/api_response.cr +++ b/samples/client/petstore/crystal/src/petstore/models/api_response.cr @@ -8,6 +8,7 @@ #OpenAPI Generator version: 7.0.0-SNAPSHOT # +require "big" require "json" require "time" diff --git a/samples/client/petstore/crystal/src/petstore/models/category.cr b/samples/client/petstore/crystal/src/petstore/models/category.cr index e32f4b7dfc..4747ac72e4 100644 --- a/samples/client/petstore/crystal/src/petstore/models/category.cr +++ b/samples/client/petstore/crystal/src/petstore/models/category.cr @@ -8,6 +8,7 @@ #OpenAPI Generator version: 7.0.0-SNAPSHOT # +require "big" require "json" require "time" diff --git a/samples/client/petstore/crystal/src/petstore/models/format_test.cr b/samples/client/petstore/crystal/src/petstore/models/format_test.cr new file mode 100644 index 0000000000..1f791829b5 --- /dev/null +++ b/samples/client/petstore/crystal/src/petstore/models/format_test.cr @@ -0,0 +1,439 @@ +# #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. +# +#The version of the OpenAPI document: 1.0.0 +# +#Generated by: https://openapi-generator.tech +#OpenAPI Generator version: 7.0.0-SNAPSHOT +# + +require "big" +require "json" +require "time" + +module Petstore + class FormatTest + include JSON::Serializable + + # Required properties + @[JSON::Field(key: "number", type: Float64, nillable: false, emit_null: false)] + property number : Float64 + + @[JSON::Field(key: "byte", type: String, nillable: false, emit_null: false)] + property byte : String + + @[JSON::Field(key: "date", type: Time, nillable: false, emit_null: false)] + property date : Time + + @[JSON::Field(key: "password", type: String, nillable: false, emit_null: false)] + property password : String + + # Optional properties + @[JSON::Field(key: "integer", type: Int32?, nillable: true, emit_null: false)] + property integer : Int32? + + @[JSON::Field(key: "int32", type: Int32?, nillable: true, emit_null: false)] + property int32 : Int32? + + @[JSON::Field(key: "int64", type: Int64?, nillable: true, emit_null: false)] + property int64 : Int64? + + @[JSON::Field(key: "float", type: Float32?, nillable: true, emit_null: false)] + property float : Float32? + + @[JSON::Field(key: "double", type: Float64?, nillable: true, emit_null: false)] + property double : Float64? + + @[JSON::Field(key: "decimal", type: BigDecimal?, nillable: true, emit_null: false)] + property decimal : BigDecimal? + + @[JSON::Field(key: "string", type: String?, nillable: true, emit_null: false)] + property string : String? + + @[JSON::Field(key: "binary", type: ::File?, nillable: true, emit_null: false)] + property binary : ::File? + + @[JSON::Field(key: "dateTime", type: Time?, nillable: true, emit_null: false)] + property date_time : Time? + + @[JSON::Field(key: "uuid", type: String?, nillable: true, emit_null: false)] + property uuid : String? + + # A string that is a 10 digit number. Can have leading zeros. + @[JSON::Field(key: "pattern_with_digits", type: String?, nillable: true, emit_null: false)] + property pattern_with_digits : String? + + # A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + @[JSON::Field(key: "pattern_with_digits_and_delimiter", type: String?, nillable: true, emit_null: false)] + property pattern_with_digits_and_delimiter : String? + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(@number : Float64, @byte : String, @date : Time, @password : String, @integer : Int32?, @int32 : Int32?, @int64 : Int64?, @float : Float32?, @double : Float64?, @decimal : BigDecimal?, @string : String?, @binary : ::File?, @date_time : Time?, @uuid : String?, @pattern_with_digits : String?, @pattern_with_digits_and_delimiter : String?) + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array(String).new + if !@integer.nil? && @integer > 100 + invalid_properties.push("invalid value for \"integer\", must be smaller than or equal to 100.") + end + + if !@integer.nil? && @integer < 10 + invalid_properties.push("invalid value for \"integer\", must be greater than or equal to 10.") + end + + if !@int32.nil? && @int32 > 200 + invalid_properties.push("invalid value for \"int32\", must be smaller than or equal to 200.") + end + + if !@int32.nil? && @int32 < 20 + invalid_properties.push("invalid value for \"int32\", must be greater than or equal to 20.") + end + + if @number > 543.2 + invalid_properties.push("invalid value for \"number\", must be smaller than or equal to 543.2.") + end + + if @number < 32.1 + invalid_properties.push("invalid value for \"number\", must be greater than or equal to 32.1.") + end + + if !@float.nil? && @float > 987.6 + invalid_properties.push("invalid value for \"float\", must be smaller than or equal to 987.6.") + end + + if !@float.nil? && @float < 54.3 + invalid_properties.push("invalid value for \"float\", must be greater than or equal to 54.3.") + end + + if !@double.nil? && @double > 123.4 + invalid_properties.push("invalid value for \"double\", must be smaller than or equal to 123.4.") + end + + if !@double.nil? && @double < 67.8 + invalid_properties.push("invalid value for \"double\", must be greater than or equal to 67.8.") + end + + pattern = Regexp.new(/[a-z]/i) + if !@string.nil? && @string !~ pattern + invalid_properties.push("invalid value for \"string\", must conform to the pattern #{pattern}.") + end + + if @password.to_s.size > 64 + invalid_properties.push("invalid value for \"password\", the character length must be smaller than or equal to 64.") + end + + if @password.to_s.size < 10 + invalid_properties.push("invalid value for \"password\", the character length must be great than or equal to 10.") + end + + pattern = Regexp.new(/^\d{10}$/) + if !@pattern_with_digits.nil? && @pattern_with_digits !~ pattern + invalid_properties.push("invalid value for \"pattern_with_digits\", must conform to the pattern #{pattern}.") + end + + pattern = Regexp.new(/^image_\d{1,3}$/i) + if !@pattern_with_digits_and_delimiter.nil? && @pattern_with_digits_and_delimiter !~ pattern + invalid_properties.push("invalid value for \"pattern_with_digits_and_delimiter\", must conform to the pattern #{pattern}.") + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if !@integer.nil? && @integer > 100 + return false if !@integer.nil? && @integer < 10 + return false if !@int32.nil? && @int32 > 200 + return false if !@int32.nil? && @int32 < 20 + return false if @number > 543.2 + return false if @number < 32.1 + return false if !@float.nil? && @float > 987.6 + return false if !@float.nil? && @float < 54.3 + return false if !@double.nil? && @double > 123.4 + return false if !@double.nil? && @double < 67.8 + return false if !@string.nil? && @string !~ Regexp.new(/[a-z]/i) + return false if @password.to_s.size > 64 + return false if @password.to_s.size < 10 + return false if !@pattern_with_digits.nil? && @pattern_with_digits !~ Regexp.new(/^\d{10}$/) + return false if !@pattern_with_digits_and_delimiter.nil? && @pattern_with_digits_and_delimiter !~ Regexp.new(/^image_\d{1,3}$/i) + true + end + + # Custom attribute writer method with validation + # @param [Object] integer Value to be assigned + def integer=(integer) + if !integer.nil? && integer > 100 + raise ArgumentError.new("invalid value for \"integer\", must be smaller than or equal to 100.") + end + + if !integer.nil? && integer < 10 + raise ArgumentError.new("invalid value for \"integer\", must be greater than or equal to 10.") + end + + @integer = integer + end + + # Custom attribute writer method with validation + # @param [Object] int32 Value to be assigned + def int32=(int32) + if !int32.nil? && int32 > 200 + raise ArgumentError.new("invalid value for \"int32\", must be smaller than or equal to 200.") + end + + if !int32.nil? && int32 < 20 + raise ArgumentError.new("invalid value for \"int32\", must be greater than or equal to 20.") + end + + @int32 = int32 + end + + # Custom attribute writer method with validation + # @param [Object] number Value to be assigned + def number=(number) + if number > 543.2 + raise ArgumentError.new("invalid value for \"number\", must be smaller than or equal to 543.2.") + end + + if number < 32.1 + raise ArgumentError.new("invalid value for \"number\", must be greater than or equal to 32.1.") + end + + @number = number + end + + # Custom attribute writer method with validation + # @param [Object] float Value to be assigned + def float=(float) + if !float.nil? && float > 987.6 + raise ArgumentError.new("invalid value for \"float\", must be smaller than or equal to 987.6.") + end + + if !float.nil? && float < 54.3 + raise ArgumentError.new("invalid value for \"float\", must be greater than or equal to 54.3.") + end + + @float = float + end + + # Custom attribute writer method with validation + # @param [Object] double Value to be assigned + def double=(double) + if !double.nil? && double > 123.4 + raise ArgumentError.new("invalid value for \"double\", must be smaller than or equal to 123.4.") + end + + if !double.nil? && double < 67.8 + raise ArgumentError.new("invalid value for \"double\", must be greater than or equal to 67.8.") + end + + @double = double + end + + # Custom attribute writer method with validation + # @param [Object] string Value to be assigned + def string=(string) + pattern = Regexp.new(/[a-z]/i) + if !string.nil? && string !~ pattern + raise ArgumentError.new("invalid value for \"string\", must conform to the pattern #{pattern}.") + end + + @string = string + end + + # Custom attribute writer method with validation + # @param [Object] password Value to be assigned + def password=(password) + if password.to_s.size > 64 + raise ArgumentError.new("invalid value for \"password\", the character length must be smaller than or equal to 64.") + end + + if password.to_s.size < 10 + raise ArgumentError.new("invalid value for \"password\", the character length must be great than or equal to 10.") + end + + @password = password + end + + # Custom attribute writer method with validation + # @param [Object] pattern_with_digits Value to be assigned + def pattern_with_digits=(pattern_with_digits) + pattern = Regexp.new(/^\d{10}$/) + if !pattern_with_digits.nil? && pattern_with_digits !~ pattern + raise ArgumentError.new("invalid value for \"pattern_with_digits\", must conform to the pattern #{pattern}.") + end + + @pattern_with_digits = pattern_with_digits + end + + # Custom attribute writer method with validation + # @param [Object] pattern_with_digits_and_delimiter Value to be assigned + def pattern_with_digits_and_delimiter=(pattern_with_digits_and_delimiter) + pattern = Regexp.new(/^image_\d{1,3}$/i) + if !pattern_with_digits_and_delimiter.nil? && pattern_with_digits_and_delimiter !~ pattern + raise ArgumentError.new("invalid value for \"pattern_with_digits_and_delimiter\", must conform to the pattern #{pattern}.") + end + + @pattern_with_digits_and_delimiter = pattern_with_digits_and_delimiter + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.same?(o) + self.class == o.class && + integer == o.integer && + int32 == o.int32 && + int64 == o.int64 && + number == o.number && + float == o.float && + double == o.double && + decimal == o.decimal && + string == o.string && + byte == o.byte && + binary == o.binary && + date == o.date && + date_time == o.date_time && + uuid == o.uuid && + password == o.password && + pattern_with_digits == o.pattern_with_digits && + pattern_with_digits_and_delimiter == o.pattern_with_digits_and_delimiter + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [integer, int32, int64, number, float, double, decimal, string, byte, binary, date, date_time, uuid, password, pattern_with_digits, pattern_with_digits_and_delimiter].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.openapi_types.each_pair do |key, type| + if !attributes[self.class.attribute_map[key]]? && self.class.openapi_nullable.includes?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + ({} of Symbol => String).tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} of Symbol => String + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.includes?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + ({} of Symbol => String).tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/crystal/src/petstore/models/order.cr b/samples/client/petstore/crystal/src/petstore/models/order.cr index 13cbdde806..054e2ce071 100644 --- a/samples/client/petstore/crystal/src/petstore/models/order.cr +++ b/samples/client/petstore/crystal/src/petstore/models/order.cr @@ -8,6 +8,7 @@ #OpenAPI Generator version: 7.0.0-SNAPSHOT # +require "big" require "json" require "time" diff --git a/samples/client/petstore/crystal/src/petstore/models/pet.cr b/samples/client/petstore/crystal/src/petstore/models/pet.cr index facc007e80..49450644ff 100644 --- a/samples/client/petstore/crystal/src/petstore/models/pet.cr +++ b/samples/client/petstore/crystal/src/petstore/models/pet.cr @@ -8,6 +8,7 @@ #OpenAPI Generator version: 7.0.0-SNAPSHOT # +require "big" require "json" require "time" diff --git a/samples/client/petstore/crystal/src/petstore/models/tag.cr b/samples/client/petstore/crystal/src/petstore/models/tag.cr index e1d4c43046..25b06873aa 100644 --- a/samples/client/petstore/crystal/src/petstore/models/tag.cr +++ b/samples/client/petstore/crystal/src/petstore/models/tag.cr @@ -8,6 +8,7 @@ #OpenAPI Generator version: 7.0.0-SNAPSHOT # +require "big" require "json" require "time" diff --git a/samples/client/petstore/crystal/src/petstore/models/user.cr b/samples/client/petstore/crystal/src/petstore/models/user.cr index a77c057c60..be44dac3ed 100644 --- a/samples/client/petstore/crystal/src/petstore/models/user.cr +++ b/samples/client/petstore/crystal/src/petstore/models/user.cr @@ -8,6 +8,7 @@ #OpenAPI Generator version: 7.0.0-SNAPSHOT # +require "big" require "json" require "time" diff --git a/samples/client/petstore/csharp-netcore-functions/docs/ApiResponse.md b/samples/client/petstore/csharp-netcore-functions/docs/ApiResponse.md deleted file mode 100644 index 2bcb247bbd..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/docs/ApiResponse.md +++ /dev/null @@ -1,13 +0,0 @@ -# Org.OpenAPITools.Models.ApiResponse -Describes the result of uploading an image resource - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Code** | **int** | | [optional] -**Type** | **string** | | [optional] -**Message** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore-functions/docs/Category.md b/samples/client/petstore/csharp-netcore-functions/docs/Category.md deleted file mode 100644 index ff6c3ede4b..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/docs/Category.md +++ /dev/null @@ -1,12 +0,0 @@ -# Org.OpenAPITools.Models.Category -A category for a pet - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Id** | **long** | | [optional] -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore-functions/docs/Order.md b/samples/client/petstore/csharp-netcore-functions/docs/Order.md deleted file mode 100644 index 2f13a5b7d6..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/docs/Order.md +++ /dev/null @@ -1,16 +0,0 @@ -# Org.OpenAPITools.Models.Order -An order for a pets from the pet store - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Id** | **long** | | [optional] -**PetId** | **long** | | [optional] -**Quantity** | **int** | | [optional] -**ShipDate** | **DateTime** | | [optional] -**Status** | **string** | Order Status | [optional] -**Complete** | **bool** | | [optional] [default to false] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore-functions/docs/Pet.md b/samples/client/petstore/csharp-netcore-functions/docs/Pet.md deleted file mode 100644 index bb37eb83fd..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/docs/Pet.md +++ /dev/null @@ -1,16 +0,0 @@ -# Org.OpenAPITools.Models.Pet -A pet for sale in the pet store - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Id** | **long** | | [optional] -**Category** | [**Category**](Category.md) | | [optional] -**Name** | **string** | | -**PhotoUrls** | **List<string>** | | -**Tags** | [**List<Tag>**](Tag.md) | | [optional] -**Status** | **string** | pet status in the store | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore-functions/docs/PetApi.md b/samples/client/petstore/csharp-netcore-functions/docs/PetApi.md deleted file mode 100644 index 5251662068..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/docs/PetApi.md +++ /dev/null @@ -1,616 +0,0 @@ -# Org.OpenAPITools.Apis.PetApi - -All URIs are relative to *http://petstore.swagger.io/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**AddPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store -[**DeletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet -[**FindPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status -[**FindPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags -[**GetPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID -[**UpdatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet -[**UpdatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data -[**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image - - - -# **AddPet** -> Pet AddPet (Pet pet) - -Add a new pet to the store - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class AddPetExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure OAuth2 access token for authorization: petstore_auth - config.AccessToken = "YOUR_ACCESS_TOKEN"; - - var apiInstance = new PetApi(config); - var pet = new Pet(); // Pet | Pet object that needs to be added to the store - - try - { - // Add a new pet to the store - Pet result = apiInstance.AddPet(pet); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling PetApi.AddPet: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | - -### Return type - -[**Pet**](Pet.md) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: application/json, application/xml - - **Accept**: application/xml, application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **405** | Invalid input | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **DeletePet** -> void DeletePet (long petId, string apiKey = null) - -Deletes a pet - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class DeletePetExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure OAuth2 access token for authorization: petstore_auth - config.AccessToken = "YOUR_ACCESS_TOKEN"; - - var apiInstance = new PetApi(config); - var petId = 789; // long | Pet id to delete - var apiKey = apiKey_example; // string | (optional) - - try - { - // Deletes a pet - apiInstance.DeletePet(petId, apiKey); - } - catch (ApiException e) - { - Debug.Print("Exception when calling PetApi.DeletePet: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **long**| Pet id to delete | - **apiKey** | **string**| | [optional] - -### Return type - -void (empty response body) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid pet value | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **FindPetsByStatus** -> List<Pet> FindPetsByStatus (List status) - -Finds Pets by status - -Multiple status values can be provided with comma separated strings - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class FindPetsByStatusExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure OAuth2 access token for authorization: petstore_auth - config.AccessToken = "YOUR_ACCESS_TOKEN"; - - var apiInstance = new PetApi(config); - var status = new List(); // List | Status values that need to be considered for filter - - try - { - // Finds Pets by status - List result = apiInstance.FindPetsByStatus(status); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling PetApi.FindPetsByStatus: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **status** | [**List<string>**](string.md)| Status values that need to be considered for filter | - -### Return type - -[**List<Pet>**](Pet.md) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid status value | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **FindPetsByTags** -> List<Pet> FindPetsByTags (List tags) - -Finds Pets by tags - -Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class FindPetsByTagsExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure OAuth2 access token for authorization: petstore_auth - config.AccessToken = "YOUR_ACCESS_TOKEN"; - - var apiInstance = new PetApi(config); - var tags = new List(); // List | Tags to filter by - - try - { - // Finds Pets by tags - List result = apiInstance.FindPetsByTags(tags); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling PetApi.FindPetsByTags: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **tags** | [**List<string>**](string.md)| Tags to filter by | - -### Return type - -[**List<Pet>**](Pet.md) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid tag value | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **GetPetById** -> Pet GetPetById (long petId) - -Find pet by ID - -Returns a single pet - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class GetPetByIdExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure API key authorization: api_key - config.AddApiKey("api_key", "YOUR_API_KEY"); - // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // config.AddApiKeyPrefix("api_key", "Bearer"); - - var apiInstance = new PetApi(config); - var petId = 789; // long | ID of pet to return - - try - { - // Find pet by ID - Pet result = apiInstance.GetPetById(petId); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling PetApi.GetPetById: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **long**| ID of pet to return | - -### Return type - -[**Pet**](Pet.md) - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid ID supplied | - | -| **404** | Pet not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **UpdatePet** -> Pet UpdatePet (Pet pet) - -Update an existing pet - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class UpdatePetExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure OAuth2 access token for authorization: petstore_auth - config.AccessToken = "YOUR_ACCESS_TOKEN"; - - var apiInstance = new PetApi(config); - var pet = new Pet(); // Pet | Pet object that needs to be added to the store - - try - { - // Update an existing pet - Pet result = apiInstance.UpdatePet(pet); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling PetApi.UpdatePet: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | - -### Return type - -[**Pet**](Pet.md) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: application/json, application/xml - - **Accept**: application/xml, application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid ID supplied | - | -| **404** | Pet not found | - | -| **405** | Validation exception | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **UpdatePetWithForm** -> void UpdatePetWithForm (long petId, string name = null, string status = null) - -Updates a pet in the store with form data - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class UpdatePetWithFormExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure OAuth2 access token for authorization: petstore_auth - config.AccessToken = "YOUR_ACCESS_TOKEN"; - - var apiInstance = new PetApi(config); - var petId = 789; // long | ID of pet that needs to be updated - var name = name_example; // string | Updated name of the pet (optional) - var status = status_example; // string | Updated status of the pet (optional) - - try - { - // Updates a pet in the store with form data - apiInstance.UpdatePetWithForm(petId, name, status); - } - catch (ApiException e) - { - Debug.Print("Exception when calling PetApi.UpdatePetWithForm: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **long**| ID of pet that needs to be updated | - **name** | **string**| Updated name of the pet | [optional] - **status** | **string**| Updated status of the pet | [optional] - -### Return type - -void (empty response body) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **405** | Invalid input | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **UploadFile** -> ApiResponse UploadFile (long petId, string additionalMetadata = null, System.IO.Stream file = null) - -uploads an image - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class UploadFileExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure OAuth2 access token for authorization: petstore_auth - config.AccessToken = "YOUR_ACCESS_TOKEN"; - - var apiInstance = new PetApi(config); - var petId = 789; // long | ID of pet to update - var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) - var file = BINARY_DATA_HERE; // System.IO.Stream | file to upload (optional) - - try - { - // uploads an image - ApiResponse result = apiInstance.UploadFile(petId, additionalMetadata, file); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling PetApi.UploadFile: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **long**| ID of pet to update | - **additionalMetadata** | **string**| Additional data to pass to server | [optional] - **file** | **System.IO.Stream****System.IO.Stream**| file to upload | [optional] - -### Return type - -[**ApiResponse**](ApiResponse.md) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - - - **Content-Type**: multipart/form-data - - **Accept**: application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore-functions/docs/StoreApi.md b/samples/client/petstore/csharp-netcore-functions/docs/StoreApi.md deleted file mode 100644 index a1ad605d05..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/docs/StoreApi.md +++ /dev/null @@ -1,298 +0,0 @@ -# Org.OpenAPITools.Apis.StoreApi - -All URIs are relative to *http://petstore.swagger.io/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -[**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status -[**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID -[**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet - - - -# **DeleteOrder** -> void DeleteOrder (string orderId) - -Delete purchase order by ID - -For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class DeleteOrderExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - var apiInstance = new StoreApi(config); - var orderId = orderId_example; // string | ID of the order that needs to be deleted - - try - { - // Delete purchase order by ID - apiInstance.DeleteOrder(orderId); - } - catch (ApiException e) - { - Debug.Print("Exception when calling StoreApi.DeleteOrder: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **orderId** | **string**| ID of the order that needs to be deleted | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid ID supplied | - | -| **404** | Order not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **GetInventory** -> Dictionary<string, int> GetInventory () - -Returns pet inventories by status - -Returns a map of status codes to quantities - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class GetInventoryExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure API key authorization: api_key - config.AddApiKey("api_key", "YOUR_API_KEY"); - // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // config.AddApiKeyPrefix("api_key", "Bearer"); - - var apiInstance = new StoreApi(config); - - try - { - // Returns pet inventories by status - Dictionary result = apiInstance.GetInventory(); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling StoreApi.GetInventory: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters -This endpoint does not need any parameter. - -### Return type - -**Dictionary** - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **GetOrderById** -> Order GetOrderById (long orderId) - -Find purchase order by ID - -For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class GetOrderByIdExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - var apiInstance = new StoreApi(config); - var orderId = 789; // long | ID of pet that needs to be fetched - - try - { - // Find purchase order by ID - Order result = apiInstance.GetOrderById(orderId); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling StoreApi.GetOrderById: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **orderId** | **long**| ID of pet that needs to be fetched | - -### Return type - -[**Order**](Order.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid ID supplied | - | -| **404** | Order not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **PlaceOrder** -> Order PlaceOrder (Order order) - -Place an order for a pet - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class PlaceOrderExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - var apiInstance = new StoreApi(config); - var order = new Order(); // Order | order placed for purchasing the pet - - try - { - // Place an order for a pet - Order result = apiInstance.PlaceOrder(order); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling StoreApi.PlaceOrder: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **order** | [**Order**](Order.md)| order placed for purchasing the pet | - -### Return type - -[**Order**](Order.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/xml, application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid Order | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore-functions/docs/Tag.md b/samples/client/petstore/csharp-netcore-functions/docs/Tag.md deleted file mode 100644 index 97b08989ea..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/docs/Tag.md +++ /dev/null @@ -1,12 +0,0 @@ -# Org.OpenAPITools.Models.Tag -A tag for a pet - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Id** | **long** | | [optional] -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore-functions/docs/User.md b/samples/client/petstore/csharp-netcore-functions/docs/User.md deleted file mode 100644 index d665fa5619..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/docs/User.md +++ /dev/null @@ -1,18 +0,0 @@ -# Org.OpenAPITools.Models.User -A User who is purchasing from the pet store - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Id** | **long** | | [optional] -**Username** | **string** | | [optional] -**FirstName** | **string** | | [optional] -**LastName** | **string** | | [optional] -**Email** | **string** | | [optional] -**Password** | **string** | | [optional] -**Phone** | **string** | | [optional] -**UserStatus** | **int** | User Status | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore-functions/docs/UserApi.md b/samples/client/petstore/csharp-netcore-functions/docs/UserApi.md deleted file mode 100644 index 858ec4e2be..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/docs/UserApi.md +++ /dev/null @@ -1,603 +0,0 @@ -# Org.OpenAPITools.Apis.UserApi - -All URIs are relative to *http://petstore.swagger.io/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**CreateUser**](UserApi.md#createuser) | **POST** /user | Create user -[**CreateUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array -[**CreateUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array -[**DeleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user -[**GetUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name -[**LoginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system -[**LogoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session -[**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user - - - -# **CreateUser** -> void CreateUser (User user) - -Create user - -This can only be done by the logged in user. - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class CreateUserExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure API key authorization: api_key - config.AddApiKey("api_key", "YOUR_API_KEY"); - // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // config.AddApiKeyPrefix("api_key", "Bearer"); - - var apiInstance = new UserApi(config); - var user = new User(); // User | Created user object - - try - { - // Create user - apiInstance.CreateUser(user); - } - catch (ApiException e) - { - Debug.Print("Exception when calling UserApi.CreateUser: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**User**](User.md)| Created user object | - -### Return type - -void (empty response body) - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **CreateUsersWithArrayInput** -> void CreateUsersWithArrayInput (List user) - -Creates list of users with given input array - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class CreateUsersWithArrayInputExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure API key authorization: api_key - config.AddApiKey("api_key", "YOUR_API_KEY"); - // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // config.AddApiKeyPrefix("api_key", "Bearer"); - - var apiInstance = new UserApi(config); - var user = new List(); // List | List of user object - - try - { - // Creates list of users with given input array - apiInstance.CreateUsersWithArrayInput(user); - } - catch (ApiException e) - { - Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInput: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**List<User>**](User.md)| List of user object | - -### Return type - -void (empty response body) - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **CreateUsersWithListInput** -> void CreateUsersWithListInput (List user) - -Creates list of users with given input array - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class CreateUsersWithListInputExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure API key authorization: api_key - config.AddApiKey("api_key", "YOUR_API_KEY"); - // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // config.AddApiKeyPrefix("api_key", "Bearer"); - - var apiInstance = new UserApi(config); - var user = new List(); // List | List of user object - - try - { - // Creates list of users with given input array - apiInstance.CreateUsersWithListInput(user); - } - catch (ApiException e) - { - Debug.Print("Exception when calling UserApi.CreateUsersWithListInput: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**List<User>**](User.md)| List of user object | - -### Return type - -void (empty response body) - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **DeleteUser** -> void DeleteUser (string username) - -Delete user - -This can only be done by the logged in user. - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class DeleteUserExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure API key authorization: api_key - config.AddApiKey("api_key", "YOUR_API_KEY"); - // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // config.AddApiKeyPrefix("api_key", "Bearer"); - - var apiInstance = new UserApi(config); - var username = username_example; // string | The name that needs to be deleted - - try - { - // Delete user - apiInstance.DeleteUser(username); - } - catch (ApiException e) - { - Debug.Print("Exception when calling UserApi.DeleteUser: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **string**| The name that needs to be deleted | - -### Return type - -void (empty response body) - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid username supplied | - | -| **404** | User not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **GetUserByName** -> User GetUserByName (string username) - -Get user by user name - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class GetUserByNameExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - var apiInstance = new UserApi(config); - var username = username_example; // string | The name that needs to be fetched. Use user1 for testing. - - try - { - // Get user by user name - User result = apiInstance.GetUserByName(username); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling UserApi.GetUserByName: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **string**| The name that needs to be fetched. Use user1 for testing. | - -### Return type - -[**User**](User.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid username supplied | - | -| **404** | User not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **LoginUser** -> string LoginUser (string username, string password) - -Logs user into the system - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class LoginUserExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - var apiInstance = new UserApi(config); - var username = username_example; // string | The user name for login - var password = password_example; // string | The password for login in clear text - - try - { - // Logs user into the system - string result = apiInstance.LoginUser(username, password); - Debug.WriteLine(result); - } - catch (ApiException e) - { - Debug.Print("Exception when calling UserApi.LoginUser: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **string**| The user name for login | - **password** | **string**| The password for login in clear text | - -### Return type - -**string** - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
        * X-Rate-Limit - calls per hour allowed by the user
        * X-Expires-After - date in UTC when token expires
        | -| **400** | Invalid username/password supplied | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **LogoutUser** -> void LogoutUser () - -Logs out current logged in user session - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class LogoutUserExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure API key authorization: api_key - config.AddApiKey("api_key", "YOUR_API_KEY"); - // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // config.AddApiKeyPrefix("api_key", "Bearer"); - - var apiInstance = new UserApi(config); - - try - { - // Logs out current logged in user session - apiInstance.LogoutUser(); - } - catch (ApiException e) - { - Debug.Print("Exception when calling UserApi.LogoutUser: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters -This endpoint does not need any parameter. - -### Return type - -void (empty response body) - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -# **UpdateUser** -> void UpdateUser (string username, User user) - -Updated user - -This can only be done by the logged in user. - -### Example -```csharp -using System.Collections.Generic; -using System.Diagnostics; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Client; -using Org.OpenAPITools.Models; - -namespace Example -{ - public class UpdateUserExample - { - public static void Main() - { - Configuration config = new Configuration(); - config.BasePath = "http://petstore.swagger.io/v2"; - // Configure API key authorization: api_key - config.AddApiKey("api_key", "YOUR_API_KEY"); - // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed - // config.AddApiKeyPrefix("api_key", "Bearer"); - - var apiInstance = new UserApi(config); - var username = username_example; // string | name that need to be deleted - var user = new User(); // User | Updated user object - - try - { - // Updated user - apiInstance.UpdateUser(username, user); - } - catch (ApiException e) - { - Debug.Print("Exception when calling UserApi.UpdateUser: " + e.Message ); - Debug.Print("Status Code: "+ e.ErrorCode); - Debug.Print(e.StackTrace); - } - } - } -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **string**| name that need to be deleted | - **user** | [**User**](User.md)| Updated user object | - -### Return type - -void (empty response body) - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid user supplied | - | -| **404** | User not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/UserTests.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/UserTests.cs deleted file mode 100644 index 3f0d780b96..0000000000 --- a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/UserTests.cs +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Models; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing User - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class UserTests : IDisposable - { - // TODO uncomment below to declare an instance variable for User - //private User instance; - - public UserTests() - { - // TODO uncomment below to create an instance of User - //instance = new User(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of User - /// - [Fact] - public void UserInstanceTest() - { - // TODO uncomment below to test "IsType" User - //Assert.IsType(instance); - } - - - /// - /// Test the property 'Id' - /// - [Fact] - public void IdTest() - { - // TODO unit test for the property 'Id' - } - /// - /// Test the property 'Username' - /// - [Fact] - public void UsernameTest() - { - // TODO unit test for the property 'Username' - } - /// - /// Test the property 'FirstName' - /// - [Fact] - public void FirstNameTest() - { - // TODO unit test for the property 'FirstName' - } - /// - /// Test the property 'LastName' - /// - [Fact] - public void LastNameTest() - { - // TODO unit test for the property 'LastName' - } - /// - /// Test the property 'Email' - /// - [Fact] - public void EmailTest() - { - // TODO unit test for the property 'Email' - } - /// - /// Test the property 'Password' - /// - [Fact] - public void PasswordTest() - { - // TODO unit test for the property 'Password' - } - /// - /// Test the property 'Phone' - /// - [Fact] - public void PhoneTest() - { - // TODO unit test for the property 'Phone' - } - /// - /// Test the property 'UserStatus' - /// - [Fact] - public void UserStatusTest() - { - // TODO unit test for the property 'UserStatus' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES index 4636f1cc22..e99cb9be46 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES @@ -98,6 +98,9 @@ src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs +src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs +src/Org.OpenAPITools/Client/Auth/TokenResponse.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumArrays.md index 8881585a4c..62e34f03db 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumArrays.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/InlineResponseDefault.md deleted file mode 100644 index e3d55e133f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/InlineResponseDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/MapTest.md index dc1ebba4e7..516f9d4fd3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/MapTest.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 76a930092b..5d048a005b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Test.Api { // TODO uncomment below to test the method and replace null with proper value //var response = instance.FooGet(); - //Assert.IsType(response); + //Assert.IsType(response); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index 291231a91b..ced34a4faa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a Dog from type Animal - /// - [Fact] - public void DogDeserializeFromAnimalTest() - { - // TODO uncomment below to test deserialize a Dog from type Animal - //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); - } /// /// Test deserialize a Cat from type Animal /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a Cat from type Animal //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } /// /// Test the property 'ClassName' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index 75f4fd8b0e..faa4930944 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a ParentPet from type GrandparentAnimal - /// - [Fact] - public void ParentPetDeserializeFromGrandparentAnimalTest() - { - // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal - //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); - } /// /// Test deserialize a ChildCat from type ParentPet /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a ChildCat from type ParentPet //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } /// /// Test the property 'PetType' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs deleted file mode 100644 index 7731f80c16..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineResponseDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineResponseDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineResponseDefault - //private InlineResponseDefault instance; - - public InlineResponseDefaultTests() - { - // TODO uncomment below to create an instance of InlineResponseDefault - //instance = new InlineResponseDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineResponseDefault - /// - [Fact] - public void InlineResponseDefaultInstanceTest() - { - // TODO uncomment below to test "IsType" InlineResponseDefault - //Assert.IsType(instance); - } - - - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SerializeBasedOnInitialization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SerializeBasedOnInitialization.cs index 68fb2e70f5..ba7b319187 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SerializeBasedOnInitialization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SerializeBasedOnInitialization.cs @@ -1,4 +1,4 @@ -using Org.OpenAPITools.Model; +using Org.OpenAPITools.Model; using System; using System.Collections.Generic; using System.Text; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index e04c8df5fd..95d41fcbd9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs index ff7ce75367..bc5b5556d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs index 421f93ed04..5991b7f0b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 6b66577525..dd74c66d15 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs index 125b0f5cb7..e8439eb125 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api @@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs index 63403e7dcd..e01ed16258 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs index c37a6501c6..8efb827cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs index cd27f08911..b488b996d0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs @@ -24,18 +24,18 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; -using RestSharp.Deserializers; +using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { /// /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// - internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; @@ -81,7 +81,9 @@ namespace Org.OpenAPITools.Client } } - public T Deserialize(IRestResponse response) + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; @@ -93,7 +95,7 @@ namespace Org.OpenAPITools.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(IRestResponse response, Type type) + internal object Deserialize(RestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { @@ -146,15 +148,22 @@ namespace Org.OpenAPITools.Client } } - public string RootElement { get; set; } - public string Namespace { get; set; } - public string DateFormat { get; set; } + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } + + public DataFormat DataFormat => DataFormat.Json; } /// /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), @@ -185,14 +194,14 @@ namespace Org.OpenAPITools.Client /// Allows for extending request processing for generated code. /// /// The RestSharp request object - partial void InterceptRequest(IRestRequest request); + partial void InterceptRequest(RestRequest request); /// /// Allows for extending response processing for generated code. /// /// The RestSharp request object /// The RestSharp response object - partial void InterceptResponse(IRestRequest request, IRestResponse response); + partial void InterceptResponse(RestRequest request, RestResponse response); /// /// Initializes a new instance of the , defaulting to the global configurations' base url. @@ -227,25 +236,25 @@ namespace Org.OpenAPITools.Client switch (method) { case HttpMethod.Get: - other = RestSharpMethod.GET; + other = RestSharpMethod.Get; break; case HttpMethod.Post: - other = RestSharpMethod.POST; + other = RestSharpMethod.Post; break; case HttpMethod.Put: - other = RestSharpMethod.PUT; + other = RestSharpMethod.Put; break; case HttpMethod.Delete: - other = RestSharpMethod.DELETE; + other = RestSharpMethod.Delete; break; case HttpMethod.Head: - other = RestSharpMethod.HEAD; + other = RestSharpMethod.Head; break; case HttpMethod.Options: - other = RestSharpMethod.OPTIONS; + other = RestSharpMethod.Options; break; case HttpMethod.Patch: - other = RestSharpMethod.PATCH; + other = RestSharpMethod.Patch; break; default: throw new ArgumentOutOfRangeException("method", method, null); @@ -276,11 +285,7 @@ namespace Org.OpenAPITools.Client if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); - RestRequest request = new RestRequest(Method(method)) - { - Resource = path, - JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) - }; + RestRequest request = new RestRequest(path, Method(method)); if (options.PathParameters != null) { @@ -375,25 +380,17 @@ namespace Org.OpenAPITools.Client var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); else - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } } } - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - request.AddCookie(cookie.Name, cookie.Value); - } - } - return request; } - private ApiResponse ToApiResponse(IRestResponse response) + private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; string rawContent = response.Content; @@ -412,9 +409,17 @@ namespace Org.OpenAPITools.Client } } + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + if (response.Cookies != null) { - foreach (var responseCookies in response.Cookies) + foreach (var responseCookies in response.Cookies.Cast()) { transformed.Cookies.Add( new Cookie( @@ -432,54 +437,46 @@ namespace Org.OpenAPITools.Client private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else - { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } } - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.Proxy = configuration.Proxy; - } + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); - if (configuration.ClientCertificates != null) + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; @@ -515,6 +512,10 @@ namespace Org.OpenAPITools.Client { response.Data = (T)(object)response.RawBytes; } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } InterceptResponse(req, response); @@ -527,7 +528,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, @@ -556,54 +557,35 @@ namespace Org.OpenAPITools.Client private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); - } - - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) - { - client.Proxy = configuration.Proxy; - } - - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; @@ -644,7 +626,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs new file mode 100644 index 0000000000..8b0ba33499 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs @@ -0,0 +1,95 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : AuthenticatorBase + { + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) : base("") + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// Access token to create a parameter from. + /// An authentication parameter. + protected override async ValueTask GetAuthenticationParameter(string accessToken) + { + var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl) + .UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration)); + + var request = new RestRequest() + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + var response = await client.PostAsync(request); + return $"{response.TokenType} {response.AccessToken}"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs new file mode 100644 index 0000000000..e225740925 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs @@ -0,0 +1,27 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs new file mode 100644 index 0000000000..0a94e17e12 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Client.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs index dcc97c295e..e499a7728e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -120,6 +120,16 @@ namespace Org.OpenAPITools.Client return Convert.ToString(obj, CultureInfo.InvariantCulture); } + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + /// /// Encode string in base64 format. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Configuration.cs index a67ad721ed..9f9385b5e2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Configuration.cs @@ -17,6 +17,8 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Net.Http; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -113,7 +115,7 @@ namespace Org.OpenAPITools.Client public Configuration() { Proxy = null; - UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); BasePath = "http://petstore.swagger.io:80/v2"; DefaultHeaders = new ConcurrentDictionary(); ApiKey = new ConcurrentDictionary(); @@ -361,6 +363,30 @@ namespace Org.OpenAPITools.Client /// The access token. public virtual string AccessToken { get; set; } + /// + /// Gets or sets the token URL for OAuth2 authentication. + /// + /// The OAuth Token URL. + public virtual string OAuthTokenUrl { get; set; } + + /// + /// Gets or sets the client ID for OAuth2 authentication. + /// + /// The OAuth Client ID. + public virtual string OAuthClientId { get; set; } + + /// + /// Gets or sets the client secret for OAuth2 authentication. + /// + /// The OAuth Client Secret. + public virtual string OAuthClientSecret { get; set; } + + /// + /// Gets or sets the flow for OAuth2 authentication. + /// + /// The OAuth Flow. + public virtual OAuthFlow? OAuthFlow { get; set; } + /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// @@ -684,6 +710,10 @@ namespace Org.OpenAPITools.Client Username = second.Username ?? first.Username, Password = second.Password ?? first.Password, AccessToken = second.AccessToken ?? first.AccessToken, + OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl, + OAuthClientId = second.OAuthClientId ?? first.OAuthClientId, + OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret, + OAuthFlow = second.OAuthFlow ?? first.OAuthFlow, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 6a8f9c8dc0..0b3e867d0f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -325,14 +325,18 @@ namespace Org.OpenAPITools.Client /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { - if (!File.Exists(KeyFilePath)) + string keyStr = string.Empty; + if (File.Exists(KeyFilePath)) { - throw new Exception("key file path does not exist."); + keyStr = File.ReadAllText(KeyFilePath); + } + else + { + keyStr = KeyFilePath; } const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; - var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); var ecdsa = ECDsa.Create(); @@ -430,11 +434,15 @@ namespace Org.OpenAPITools.Client bool isPrivateKeyFile = true; byte[] pemkey = null; - if (!File.Exists(pemfile)) + string pemstr = string.Empty; + if (File.Exists(pemfile)) { - throw new Exception("private key file does not exist."); + pemstr = File.ReadAllText(pemfile).Trim(); + } + else + { + pemstr = pemfile; } - string pemstr = File.ReadAllText(pemfile).Trim(); if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) { @@ -725,9 +733,16 @@ namespace Org.OpenAPITools.Client /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { - if (!File.Exists(keyFilePath)) + string[] key = null; + + if (File.Exists(keyFilePath)) { - throw new Exception("Key file path does not exist."); + key = File.ReadAllLines(keyFilePath); + } + else + { + // The ApiKeyFilePath is passed as string + key = new string[] { keyFilePath }; } const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; @@ -737,7 +752,6 @@ namespace Org.OpenAPITools.Client //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; PrivateKeyType keyType; - var key = File.ReadAllLines(keyFilePath); if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) @@ -751,7 +765,7 @@ namespace Org.OpenAPITools.Client } else { - throw new Exception("Either the key is invalid or key is not supported"); + throw new Exception("The key file path does not exist or key is invalid or key is not supported"); } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IReadableConfiguration.cs index b99a151e5b..c9615dc5aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IReadableConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; using System.Net; using System.Security.Cryptography.X509Certificates; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client /// Access token. string AccessToken { get; } + /// + /// Gets the OAuth token URL. + /// + /// OAuth Token URL. + string OAuthTokenUrl { get; } + + /// + /// Gets the OAuth client ID. + /// + /// OAuth Client ID. + string OAuthClientId { get; } + + /// + /// Gets the OAuth client secret. + /// + /// OAuth Client Secret. + string OAuthClientSecret { get; } + + /// + /// Gets the OAuth flow. + /// + /// OAuth Flow. + OAuthFlow? OAuthFlow { get; } + /// /// Gets the API key. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RequestOptions.cs index 3932047e02..4c26cf69b2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client /// public Object Data { get; set; } + /// + /// If request should be authenticated with OAuth. + /// + public bool OAuth { get; set; } + /// /// Constructs a new instance of /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RetryConfiguration.cs index 91bc7cc6d5..7011f69e77 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RetryConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client /// /// Retry policy /// - public static Policy RetryPolicy { get; set; } + public static Policy RetryPolicy { get; set; } /// /// Async retry policy /// - public static AsyncPolicy AsyncRetryPolicy { get; set; } + public static AsyncPolicy AsyncRetryPolicy { get; set; } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs index 0a9b6b337d..6d4cbf3cb8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs @@ -63,7 +63,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get{ return _ClassName;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs index 264577c241..f856ba9072 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Cultivar /// - [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = true)] public string Cultivar { get{ return _Cultivar;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs index 5602630dc8..084e55f92a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs @@ -55,7 +55,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets LengthCm /// - [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = true)] public decimal LengthCm { get{ return _LengthCm;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs index 6cde5d45eb..8262f21f86 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get{ return _ClassName;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs index 6d31d2520a..a9643944cc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs @@ -167,7 +167,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs index ecd7492d5f..dd09bcdc93 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs @@ -88,7 +88,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get{ return _Name;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs index e5f952880e..c7201b1c4a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs @@ -77,14 +77,6 @@ namespace Org.OpenAPITools.Model /// /// Initializes a new instance of the class. /// - [JsonConstructorAttribute] - protected ChildCat() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// /// name. /// petType (default to PetTypeEnum.ChildCat). public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() @@ -211,7 +203,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 8df5f4c0cf..21713f5742 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -65,7 +65,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get{ return _ShapeType;} @@ -89,7 +89,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get{ return _QuadrilateralType;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs index 8f90997e8f..c4b7fbf141 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get{ return _ClassName;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs index 45f65d0d7b..268c386ae2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs @@ -170,7 +170,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs index c799b734cc..e63ee79f3e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -98,33 +98,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets ArrayEnum - /// - - [DataMember(Name = "array_enum", EmitDefaultValue = false)] - public List ArrayEnum - { - get{ return _ArrayEnum;} - set - { - _ArrayEnum = value; - _flagArrayEnum = true; - } - } - private List _ArrayEnum; - private bool _flagArrayEnum; - - /// - /// Returns false as ArrayEnum should not be serialized given that it's read-only. - /// - /// false (boolean) - public bool ShouldSerializeArrayEnum() - { - return _flagArrayEnum; - } /// /// Initializes a new instance of the class. /// @@ -145,6 +118,30 @@ namespace Org.OpenAPITools.Model this.AdditionalProperties = new Dictionary(); } + /// + /// Gets or Sets ArrayEnum + /// + [DataMember(Name = "array_enum", EmitDefaultValue = false)] + public List ArrayEnum + { + get{ return _ArrayEnum;} + set + { + _ArrayEnum = value; + _flagArrayEnum = true; + } + } + private List _ArrayEnum; + private bool _flagArrayEnum; + + /// + /// Returns false as ArrayEnum should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayEnum() + { + return _flagArrayEnum; + } /// /// Gets or Sets additional properties /// @@ -205,7 +202,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs index d1d325588b..6d8fb03b7f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs @@ -115,7 +115,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets EnumStringRequired /// - [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = true)] public EnumStringRequiredEnum EnumStringRequired { get{ return _EnumStringRequired;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 458a320fee..153f0fff2b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -65,7 +65,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get{ return _ShapeType;} @@ -89,7 +89,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get{ return _TriangleType;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs index 6260dacfb0..4787323d3a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs @@ -213,7 +213,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Number /// - [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = true)] public decimal Number { get{ return _Number;} @@ -333,7 +333,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Byte /// - [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = true)] public byte[] Byte { get{ return _Byte;} @@ -382,7 +382,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Date /// [JsonConverter(typeof(OpenAPIDateConverter))] - [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] public DateTime Date { get{ return _Date;} @@ -454,7 +454,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Password /// - [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = true)] public string Password { get{ return _Password;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index a9409a3e18..4b26f24f31 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] public string PetType { get{ return _PetType;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs deleted file mode 100644 index d2532a0f95..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ /dev/null @@ -1,154 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineResponseDefault - /// - [DataContract(Name = "inline_response_default")] - public partial class InlineResponseDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// _string. - public InlineResponseDefault(Foo _string = default(Foo)) - { - this._String = _string; - if (this.String != null) - { - this._flagString = true; - } - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Gets or Sets String - /// - [DataMember(Name = "string", EmitDefaultValue = false)] - public Foo String - { - get{ return _String;} - set - { - _String = value; - _flagString = true; - } - } - private Foo _String; - private bool _flagString; - - /// - /// Returns false as String should not be serialized given that it's read-only. - /// - /// false (boolean) - public bool ShouldSerializeString() - { - return _flagString; - } - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineResponseDefault {\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineResponseDefault).AreEqual; - } - - /// - /// Returns true if InlineResponseDefault instances are equal - /// - /// Instance of InlineResponseDefault to be compared - /// Boolean - public bool Equals(InlineResponseDefault input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index f0dce588f7..d20bedcd92 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get{ return _ShapeType;} @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get{ return _TriangleType;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs index 64bdcf20a3..7e7093e3d0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs @@ -52,33 +52,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets MapOfEnumString - /// - - [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] - public Dictionary MapOfEnumString - { - get{ return _MapOfEnumString;} - set - { - _MapOfEnumString = value; - _flagMapOfEnumString = true; - } - } - private Dictionary _MapOfEnumString; - private bool _flagMapOfEnumString; - - /// - /// Returns false as MapOfEnumString should not be serialized given that it's read-only. - /// - /// false (boolean) - public bool ShouldSerializeMapOfEnumString() - { - return _flagMapOfEnumString; - } /// /// Initializes a new instance of the class. /// @@ -136,6 +109,30 @@ namespace Org.OpenAPITools.Model return _flagMapMapOfString; } /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] + public Dictionary MapOfEnumString + { + get{ return _MapOfEnumString;} + set + { + _MapOfEnumString = value; + _flagMapOfEnumString = true; + } + } + private Dictionary _MapOfEnumString; + private bool _flagMapOfEnumString; + + /// + /// Returns false as MapOfEnumString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMapOfEnumString() + { + return _flagMapOfEnumString; + } + /// /// Gets or Sets DirectMap /// [DataMember(Name = "direct_map", EmitDefaultValue = false)] @@ -248,7 +245,10 @@ namespace Org.OpenAPITools.Model { hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); } - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } if (this.DirectMap != null) { hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs index 1579e494c0..bfda0b0052 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs @@ -59,7 +59,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets _Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public int _Name { get{ return __Name;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs index ac986b555e..49bed67986 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs @@ -135,7 +135,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs index b2d853f7b2..9fea569bb1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs @@ -191,7 +191,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get{ return _Name;} @@ -215,7 +215,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets PhotoUrls /// - [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = true)] public List PhotoUrls { get{ return _PhotoUrls;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index e4aa4fba69..2b8f0a9cd3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get{ return _QuadrilateralType;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 421aeb4bbb..0577d1ddf7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -65,7 +65,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get{ return _ShapeType;} @@ -89,7 +89,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get{ return _TriangleType;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs index 79bbd10fa3..9f5c4295bf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get{ return _ShapeType;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 8ac75f73d9..318daa0c8a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -65,7 +65,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get{ return _ShapeType;} @@ -89,7 +89,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get{ return _QuadrilateralType;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs index 06d4d832a0..d26983a6d9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get{ return _TriangleType;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs index 19a2c468dd..d844993eb2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs @@ -118,7 +118,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get{ return _ClassName;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs index e850753702..615d245b47 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs @@ -116,7 +116,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get{ return _ClassName;} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 5889bffe70..830f64d090 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,11 +21,17 @@ - + - + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumArrays.md index c40bb19edd..2a27962cc5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumArrays.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/InlineResponseDefault.md deleted file mode 100644 index 0c1b0d5bb0..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/InlineResponseDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MapTest.md index 03bcebd3d9..aaee09f787 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/docs/models/MapTest.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 062cf43636..16f60704f2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Test.Api public async Task FooGetAsyncTest() { var response = await _instance.FooGetAsync(); - Assert.IsType(response); + Assert.IsType(response); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index 291231a91b..ced34a4faa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a Dog from type Animal - /// - [Fact] - public void DogDeserializeFromAnimalTest() - { - // TODO uncomment below to test deserialize a Dog from type Animal - //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); - } /// /// Test deserialize a Cat from type Animal /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a Cat from type Animal //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } /// /// Test the property 'ClassName' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index 75f4fd8b0e..faa4930944 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a ParentPet from type GrandparentAnimal - /// - [Fact] - public void ParentPetDeserializeFromGrandparentAnimalTest() - { - // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal - //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); - } /// /// Test deserialize a ChildCat from type ParentPet /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a ChildCat from type ParentPet //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } /// /// Test the property 'PetType' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs deleted file mode 100644 index 7731f80c16..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineResponseDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineResponseDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineResponseDefault - //private InlineResponseDefault instance; - - public InlineResponseDefaultTests() - { - // TODO uncomment below to create an instance of InlineResponseDefault - //instance = new InlineResponseDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineResponseDefault - /// - [Fact] - public void InlineResponseDefaultInstanceTest() - { - // TODO uncomment below to test "IsType" InlineResponseDefault - //Assert.IsType(instance); - } - - - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs index 97e3a3b964..951d98e662 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -36,7 +36,7 @@ namespace Org.OpenAPITools.Model /// /// justSymbol /// arrayEnum - public EnumArrays(JustSymbolEnum? justSymbol = default, List? arrayEnum = default) + public EnumArrays(JustSymbolEnum? justSymbol = default, List? arrayEnum = default) { JustSymbol = justSymbol; ArrayEnum = arrayEnum; @@ -86,12 +86,11 @@ namespace Org.OpenAPITools.Model } - /// /// Gets or Sets ArrayEnum /// [JsonPropertyName("array_enum")] - public List? ArrayEnum { get; set; } + public List? ArrayEnum { get; set; } /// /// Gets or Sets additional properties @@ -144,7 +143,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/InlineResponseDefault.cs deleted file mode 100644 index 7e5ed58fad..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ /dev/null @@ -1,121 +0,0 @@ -// -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - -#nullable enable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.ComponentModel.DataAnnotations; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineResponseDefault - /// - public partial class InlineResponseDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// _string - public InlineResponseDefault(Foo? _string = default) - { - String = _string; - } - - /// - /// Gets or Sets String - /// - [JsonPropertyName("string")] - public Foo? String { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineResponseDefault {\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineResponseDefault).AreEqual; - } - - /// - /// Returns true if InlineResponseDefault instances are equal - /// - /// Instance of InlineResponseDefault to be compared - /// Boolean - public bool Equals(InlineResponseDefault? input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs index 5a01c40395..64a3380a3d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs @@ -38,7 +38,7 @@ namespace Org.OpenAPITools.Model /// mapOfEnumString /// directMap /// indirectMap - public MapTest(Dictionary>? mapMapOfString = default, Dictionary? mapOfEnumString = default, Dictionary? directMap = default, Dictionary? indirectMap = default) + public MapTest(Dictionary>? mapMapOfString = default, Dictionary? mapOfEnumString = default, Dictionary? directMap = default, Dictionary? indirectMap = default) { MapMapOfString = mapMapOfString; MapOfEnumString = mapOfEnumString; @@ -65,19 +65,18 @@ namespace Org.OpenAPITools.Model } - - /// - /// Gets or Sets MapOfEnumString - /// - [JsonPropertyName("map_of_enum_string")] - public Dictionary? MapOfEnumString { get; set; } - /// /// Gets or Sets MapMapOfString /// [JsonPropertyName("map_map_of_string")] public Dictionary>? MapMapOfString { get; set; } + /// + /// Gets or Sets MapOfEnumString + /// + [JsonPropertyName("map_of_enum_string")] + public Dictionary? MapOfEnumString { get; set; } + /// /// Gets or Sets DirectMap /// @@ -146,7 +145,10 @@ namespace Org.OpenAPITools.Model { hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); } - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } if (this.DirectMap != null) { hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 1531b2ee02..63301d3295 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -29,4 +29,10 @@ + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumArrays.md index c40bb19edd..2a27962cc5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/EnumArrays.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/InlineResponseDefault.md deleted file mode 100644 index 0c1b0d5bb0..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/InlineResponseDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MapTest.md index 03bcebd3d9..aaee09f787 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/docs/models/MapTest.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 062cf43636..16f60704f2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Test.Api public async Task FooGetAsyncTest() { var response = await _instance.FooGetAsync(); - Assert.IsType(response); + Assert.IsType(response); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index 291231a91b..ced34a4faa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a Dog from type Animal - /// - [Fact] - public void DogDeserializeFromAnimalTest() - { - // TODO uncomment below to test deserialize a Dog from type Animal - //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); - } /// /// Test deserialize a Cat from type Animal /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a Cat from type Animal //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } /// /// Test the property 'ClassName' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index 75f4fd8b0e..faa4930944 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a ParentPet from type GrandparentAnimal - /// - [Fact] - public void ParentPetDeserializeFromGrandparentAnimalTest() - { - // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal - //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); - } /// /// Test deserialize a ChildCat from type ParentPet /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a ChildCat from type ParentPet //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } /// /// Test the property 'PetType' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs deleted file mode 100644 index 7731f80c16..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineResponseDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineResponseDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineResponseDefault - //private InlineResponseDefault instance; - - public InlineResponseDefaultTests() - { - // TODO uncomment below to create an instance of InlineResponseDefault - //instance = new InlineResponseDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineResponseDefault - /// - [Fact] - public void InlineResponseDefaultInstanceTest() - { - // TODO uncomment below to test "IsType" InlineResponseDefault - //Assert.IsType(instance); - } - - - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs index 95fff02c56..92f07ad2ee 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -34,7 +34,7 @@ namespace Org.OpenAPITools.Model /// /// justSymbol /// arrayEnum - public EnumArrays(JustSymbolEnum justSymbol = default, List arrayEnum = default) + public EnumArrays(JustSymbolEnum justSymbol = default, List arrayEnum = default) { JustSymbol = justSymbol; ArrayEnum = arrayEnum; @@ -84,12 +84,11 @@ namespace Org.OpenAPITools.Model } - /// /// Gets or Sets ArrayEnum /// [JsonPropertyName("array_enum")] - public List ArrayEnum { get; set; } + public List ArrayEnum { get; set; } /// /// Gets or Sets additional properties @@ -142,7 +141,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs deleted file mode 100644 index 4dfd57402f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ /dev/null @@ -1,119 +0,0 @@ -// -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.ComponentModel.DataAnnotations; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineResponseDefault - /// - public partial class InlineResponseDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// _string - public InlineResponseDefault(Foo _string = default) - { - String = _string; - } - - /// - /// Gets or Sets String - /// - [JsonPropertyName("string")] - public Foo String { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineResponseDefault {\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineResponseDefault).AreEqual; - } - - /// - /// Returns true if InlineResponseDefault instances are equal - /// - /// Instance of InlineResponseDefault to be compared - /// Boolean - public bool Equals(InlineResponseDefault input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs index 797a643b7e..2cf624e2af 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs @@ -36,7 +36,7 @@ namespace Org.OpenAPITools.Model /// mapOfEnumString /// directMap /// indirectMap - public MapTest(Dictionary> mapMapOfString = default, Dictionary mapOfEnumString = default, Dictionary directMap = default, Dictionary indirectMap = default) + public MapTest(Dictionary> mapMapOfString = default, Dictionary mapOfEnumString = default, Dictionary directMap = default, Dictionary indirectMap = default) { MapMapOfString = mapMapOfString; MapOfEnumString = mapOfEnumString; @@ -63,19 +63,18 @@ namespace Org.OpenAPITools.Model } - - /// - /// Gets or Sets MapOfEnumString - /// - [JsonPropertyName("map_of_enum_string")] - public Dictionary MapOfEnumString { get; set; } - /// /// Gets or Sets MapMapOfString /// [JsonPropertyName("map_map_of_string")] public Dictionary> MapMapOfString { get; set; } + /// + /// Gets or Sets MapOfEnumString + /// + [JsonPropertyName("map_of_enum_string")] + public Dictionary MapOfEnumString { get; set; } + /// /// Gets or Sets DirectMap /// @@ -144,7 +143,10 @@ namespace Org.OpenAPITools.Model { hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); } - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } if (this.DirectMap != null) { hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index a14df8ce38..20de1a9f24 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -28,4 +28,10 @@ + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumArrays.md index c40bb19edd..2a27962cc5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumArrays.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/InlineResponseDefault.md deleted file mode 100644 index 0c1b0d5bb0..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/InlineResponseDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MapTest.md index 03bcebd3d9..aaee09f787 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/docs/models/MapTest.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 062cf43636..16f60704f2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Test.Api public async Task FooGetAsyncTest() { var response = await _instance.FooGetAsync(); - Assert.IsType(response); + Assert.IsType(response); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index 291231a91b..ced34a4faa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a Dog from type Animal - /// - [Fact] - public void DogDeserializeFromAnimalTest() - { - // TODO uncomment below to test deserialize a Dog from type Animal - //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); - } /// /// Test deserialize a Cat from type Animal /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a Cat from type Animal //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } /// /// Test the property 'ClassName' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index 75f4fd8b0e..faa4930944 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a ParentPet from type GrandparentAnimal - /// - [Fact] - public void ParentPetDeserializeFromGrandparentAnimalTest() - { - // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal - //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); - } /// /// Test deserialize a ChildCat from type ParentPet /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a ChildCat from type ParentPet //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } /// /// Test the property 'PetType' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs deleted file mode 100644 index 7731f80c16..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineResponseDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineResponseDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineResponseDefault - //private InlineResponseDefault instance; - - public InlineResponseDefaultTests() - { - // TODO uncomment below to create an instance of InlineResponseDefault - //instance = new InlineResponseDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineResponseDefault - /// - [Fact] - public void InlineResponseDefaultInstanceTest() - { - // TODO uncomment below to test "IsType" InlineResponseDefault - //Assert.IsType(instance); - } - - - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs index 95fff02c56..92f07ad2ee 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -34,7 +34,7 @@ namespace Org.OpenAPITools.Model /// /// justSymbol /// arrayEnum - public EnumArrays(JustSymbolEnum justSymbol = default, List arrayEnum = default) + public EnumArrays(JustSymbolEnum justSymbol = default, List arrayEnum = default) { JustSymbol = justSymbol; ArrayEnum = arrayEnum; @@ -84,12 +84,11 @@ namespace Org.OpenAPITools.Model } - /// /// Gets or Sets ArrayEnum /// [JsonPropertyName("array_enum")] - public List ArrayEnum { get; set; } + public List ArrayEnum { get; set; } /// /// Gets or Sets additional properties @@ -142,7 +141,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs deleted file mode 100644 index 4dfd57402f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ /dev/null @@ -1,119 +0,0 @@ -// -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.ComponentModel.DataAnnotations; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineResponseDefault - /// - public partial class InlineResponseDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// _string - public InlineResponseDefault(Foo _string = default) - { - String = _string; - } - - /// - /// Gets or Sets String - /// - [JsonPropertyName("string")] - public Foo String { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public Dictionary AdditionalProperties { get; set; } = new Dictionary(); - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineResponseDefault {\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineResponseDefault).AreEqual; - } - - /// - /// Returns true if InlineResponseDefault instances are equal - /// - /// Instance of InlineResponseDefault to be compared - /// Boolean - public bool Equals(InlineResponseDefault input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs index 797a643b7e..2cf624e2af 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs @@ -36,7 +36,7 @@ namespace Org.OpenAPITools.Model /// mapOfEnumString /// directMap /// indirectMap - public MapTest(Dictionary> mapMapOfString = default, Dictionary mapOfEnumString = default, Dictionary directMap = default, Dictionary indirectMap = default) + public MapTest(Dictionary> mapMapOfString = default, Dictionary mapOfEnumString = default, Dictionary directMap = default, Dictionary indirectMap = default) { MapMapOfString = mapMapOfString; MapOfEnumString = mapOfEnumString; @@ -63,19 +63,18 @@ namespace Org.OpenAPITools.Model } - - /// - /// Gets or Sets MapOfEnumString - /// - [JsonPropertyName("map_of_enum_string")] - public Dictionary MapOfEnumString { get; set; } - /// /// Gets or Sets MapMapOfString /// [JsonPropertyName("map_map_of_string")] public Dictionary> MapMapOfString { get; set; } + /// + /// Gets or Sets MapOfEnumString + /// + [JsonPropertyName("map_of_enum_string")] + public Dictionary MapOfEnumString { get; set; } + /// /// Gets or Sets DirectMap /// @@ -144,7 +143,10 @@ namespace Org.OpenAPITools.Model { hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); } - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } if (this.DirectMap != null) { hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 5cbefcd8fb..6fe89418c3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -28,4 +28,10 @@ + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/EnumArrays.md index 8881585a4c..62e34f03db 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/EnumArrays.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/InlineResponseDefault.md deleted file mode 100644 index e3d55e133f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/InlineResponseDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/MapTest.md index dc1ebba4e7..516f9d4fd3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/MapTest.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 6502700031..767537cf40 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Test.Api { // TODO uncomment below to test the method and replace null with proper value //var response = instance.FooGet(); - //Assert.IsType(response); + //Assert.IsType(response); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs index afd0ff25a9..41e1c365c2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -174,7 +174,7 @@ namespace Org.OpenAPITools.Test.Api //long? int64 = null; //float? _float = null; //string _string = null; - //System.IO.Stream binary = null; + //FileParameter binary = null; //DateTime? date = null; //DateTime? dateTime = null; //string password = null; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index 291231a91b..ced34a4faa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a Dog from type Animal - /// - [Fact] - public void DogDeserializeFromAnimalTest() - { - // TODO uncomment below to test deserialize a Dog from type Animal - //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); - } /// /// Test deserialize a Cat from type Animal /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a Cat from type Animal //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } /// /// Test the property 'ClassName' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index e2d84645c6..4f81b845d4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -81,6 +81,14 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'EnumInteger' } /// + /// Test the property 'EnumIntegerOnly' + /// + [Fact] + public void EnumIntegerOnlyTest() + { + // TODO unit test for the property 'EnumIntegerOnly' + } + /// /// Test the property 'EnumNumber' /// [Fact] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index 75f4fd8b0e..faa4930944 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a ParentPet from type GrandparentAnimal - /// - [Fact] - public void ParentPetDeserializeFromGrandparentAnimalTest() - { - // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal - //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); - } /// /// Test deserialize a ChildCat from type ParentPet /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a ChildCat from type ParentPet //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } /// /// Test the property 'PetType' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs deleted file mode 100644 index 7731f80c16..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineResponseDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineResponseDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineResponseDefault - //private InlineResponseDefault instance; - - public InlineResponseDefaultTests() - { - // TODO uncomment below to create an instance of InlineResponseDefault - //instance = new InlineResponseDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineResponseDefault - /// - [Fact] - public void InlineResponseDefaultInstanceTest() - { - // TODO uncomment below to test "IsType" InlineResponseDefault - //Assert.IsType(instance); - } - - - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs index 8a544e417f..24a9e26315 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -57,12 +57,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property '__Client' + /// Test the property '_Client' /// [Fact] - public void __ClientTest() + public void _ClientTest() { - // TODO unit test for the property '__Client' + // TODO unit test for the property '_Client' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs index 57c3f6f9e4..0f0e1ff12a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs @@ -64,6 +64,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'SpecialPropertyName' } + /// + /// Test the property '_SpecialModelName' + /// + [Fact] + public void _SpecialModelNameTest() + { + // TODO unit test for the property '_SpecialModelName' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs index a794d9cdfc..5bf010da66 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs @@ -451,80 +451,97 @@ namespace Org.OpenAPITools.Client IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { + CancellationTokenSource timeoutTokenSource = null; + CancellationTokenSource finalTokenSource = null; var deserializer = new CustomJsonCodec(SerializerSettings, configuration); - var finalToken = cancellationToken; - if (configuration.Timeout > 0) + try { - var tokenSource = new CancellationTokenSource(configuration.Timeout); - finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token; - } - - if (configuration.Proxy != null) - { - if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); - _httpClientHandler.Proxy = configuration.Proxy; - } - - if (configuration.ClientCertificates != null) - { - if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); - _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); - } - - var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; - - if (cookieContainer != null) - { - if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); - foreach (var cookie in cookieContainer) + if (configuration.Timeout > 0) { - _httpClientHandler.CookieContainer.Add(cookie); + timeoutTokenSource = new CancellationTokenSource(configuration.Timeout); + finalTokenSource = CancellationTokenSource.CreateLinkedTokenSource(finalToken, timeoutTokenSource.Token); + finalToken = finalTokenSource.Token; + } + + if (configuration.Proxy != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.Proxy = configuration.Proxy; + } + + if (configuration.ClientCertificates != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); + } + + var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; + + if (cookieContainer != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + foreach (var cookie in cookieContainer) + { + _httpClientHandler.CookieContainer.Add(cookie); + } + } + + InterceptRequest(req); + + HttpResponseMessage response; + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy + .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, finalToken)) + .ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? + policyResult.Result : new HttpResponseMessage() + { + ReasonPhrase = policyResult.FinalException.ToString(), + RequestMessage = req + }; + } + else + { + response = await _httpClient.SendAsync(req, finalToken).ConfigureAwait(false); + } + + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri); + } + + object responseData = await deserializer.Deserialize(response); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + responseData = (T) (object) await response.Content.ReadAsStreamAsync(); + } + + InterceptResponse(req, response); + + return await ToApiResponse(response, responseData, req.RequestUri); + } + finally + { + if (timeoutTokenSource != null) + { + timeoutTokenSource.Dispose(); + } + + if (finalTokenSource != null) + { + finalTokenSource.Dispose(); } } - - InterceptRequest(req); - - HttpResponseMessage response; - if (RetryConfiguration.AsyncRetryPolicy != null) - { - var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy - .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, cancellationToken)) - .ConfigureAwait(false); - response = (policyResult.Outcome == OutcomeType.Successful) ? - policyResult.Result : new HttpResponseMessage() - { - ReasonPhrase = policyResult.FinalException.ToString(), - RequestMessage = req - }; - } - else - { - response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false); - } - - if (!response.IsSuccessStatusCode) - { - return await ToApiResponse(response, default(T), req.RequestUri); - } - - object responseData = await deserializer.Deserialize(response); - - // if the response type is oneOf/anyOf, call FromJSON to deserialize the data - if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) - { - responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); - } - else if (typeof(T).Name == "Stream") // for binary response - { - responseData = (T) (object) await response.Content.ReadAsStreamAsync(); - } - - InterceptResponse(req, response); - - return await ToApiResponse(response, responseData, req.RequestUri); } #region IAsynchronousClient diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs index dcc97c295e..e499a7728e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -120,6 +120,16 @@ namespace Org.OpenAPITools.Client return Convert.ToString(obj, CultureInfo.InvariantCulture); } + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + /// /// Encode string in base64 format. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/Configuration.cs index a67ad721ed..5c01857755 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/Configuration.cs @@ -17,6 +17,7 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Net.Http; namespace Org.OpenAPITools.Client { @@ -113,7 +114,7 @@ namespace Org.OpenAPITools.Client public Configuration() { Proxy = null; - UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); BasePath = "http://petstore.swagger.io:80/v2"; DefaultHeaders = new ConcurrentDictionary(); ApiKey = new ConcurrentDictionary(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 6a8f9c8dc0..0b3e867d0f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -325,14 +325,18 @@ namespace Org.OpenAPITools.Client /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { - if (!File.Exists(KeyFilePath)) + string keyStr = string.Empty; + if (File.Exists(KeyFilePath)) { - throw new Exception("key file path does not exist."); + keyStr = File.ReadAllText(KeyFilePath); + } + else + { + keyStr = KeyFilePath; } const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; - var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); var ecdsa = ECDsa.Create(); @@ -430,11 +434,15 @@ namespace Org.OpenAPITools.Client bool isPrivateKeyFile = true; byte[] pemkey = null; - if (!File.Exists(pemfile)) + string pemstr = string.Empty; + if (File.Exists(pemfile)) { - throw new Exception("private key file does not exist."); + pemstr = File.ReadAllText(pemfile).Trim(); + } + else + { + pemstr = pemfile; } - string pemstr = File.ReadAllText(pemfile).Trim(); if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) { @@ -725,9 +733,16 @@ namespace Org.OpenAPITools.Client /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { - if (!File.Exists(keyFilePath)) + string[] key = null; + + if (File.Exists(keyFilePath)) { - throw new Exception("Key file path does not exist."); + key = File.ReadAllLines(keyFilePath); + } + else + { + // The ApiKeyFilePath is passed as string + key = new string[] { keyFilePath }; } const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; @@ -737,7 +752,6 @@ namespace Org.OpenAPITools.Client //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; PrivateKeyType keyType; - var key = File.ReadAllLines(keyFilePath); if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) @@ -751,7 +765,7 @@ namespace Org.OpenAPITools.Client } else { - throw new Exception("Either the key is invalid or key is not supported"); + throw new Exception("The key file path does not exist or key is invalid or key is not supported"); } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs index 6aef494833..dc511478a5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs @@ -66,7 +66,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs index 0c1a6aad6e..d0a4bdb172 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs @@ -57,7 +57,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Cultivar /// - [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = true)] public string Cultivar { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs index 0bb74117ee..382f8f954f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs @@ -52,7 +52,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets LengthCm /// - [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = true)] public decimal LengthCm { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs index f412b30428..8e890c6878 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs @@ -59,7 +59,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs index a4913aebad..e151f038ad 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs @@ -146,7 +146,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs index b5a4f8a120..7a758fc8b1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs @@ -67,7 +67,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs index 2420d12955..4a7f278731 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs @@ -58,14 +58,6 @@ namespace Org.OpenAPITools.Model /// /// Initializes a new instance of the class. /// - [JsonConstructorAttribute] - protected ChildCat() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// /// name. /// petType (default to PetTypeEnum.ChildCat). public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() @@ -171,7 +163,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index e694ec30fe..2a964cfe40 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -66,13 +66,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs index f894ecd6f2..6449d05896 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs @@ -59,7 +59,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs index 190866102d..1094476027 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs @@ -149,7 +149,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs index 7e5d509dd8..5f374bada4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -79,13 +79,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets ArrayEnum - /// - [DataMember(Name = "array_enum", EmitDefaultValue = false)] - public List ArrayEnum { get; set; } /// /// Initializes a new instance of the class. /// @@ -98,6 +91,12 @@ namespace Org.OpenAPITools.Model this.AdditionalProperties = new Dictionary(); } + /// + /// Gets or Sets ArrayEnum + /// + [DataMember(Name = "array_enum", EmitDefaultValue = false)] + public List ArrayEnum { get; set; } + /// /// Gets or Sets additional properties /// @@ -158,7 +157,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs index a5a0c32d3a..fc83b2c83c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs @@ -95,7 +95,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets EnumStringRequired /// - [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = true)] public EnumStringRequiredEnum EnumStringRequired { get; set; } /// /// Defines EnumInteger diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 94138f9d00..d5fe6f8caa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -66,13 +66,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs index 5ca55acea9..5603e75631 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs @@ -112,7 +112,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Number /// - [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = true)] public decimal Number { get; set; } /// @@ -142,7 +142,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Byte /// - [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = true)] public byte[] Byte { get; set; } /// @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Date /// - [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] [JsonConverter(typeof(OpenAPIDateConverter))] public DateTime Date { get; set; } @@ -173,7 +173,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Password /// - [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = true)] public string Password { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index b5fdfc6ebd..4936fff760 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -63,7 +63,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] public string PetType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs deleted file mode 100644 index 6e0c37e257..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ /dev/null @@ -1,133 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using FileParameter = Org.OpenAPITools.Client.FileParameter; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineResponseDefault - /// - [DataContract(Name = "inline_response_default")] - public partial class InlineResponseDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// _string. - public InlineResponseDefault(Foo _string = default(Foo)) - { - this.String = _string; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Gets or Sets String - /// - [DataMember(Name = "string", EmitDefaultValue = false)] - public Foo String { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineResponseDefault {\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineResponseDefault).AreEqual; - } - - /// - /// Returns true if InlineResponseDefault instances are equal - /// - /// Instance of InlineResponseDefault to be compared - /// Boolean - public bool Equals(InlineResponseDefault input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index d543995430..2028dbe722 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -62,13 +62,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs index 9a7ca84088..9685a3a04d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs @@ -53,13 +53,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets MapOfEnumString - /// - [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] - public Dictionary MapOfEnumString { get; set; } /// /// Initializes a new instance of the class. /// @@ -82,6 +75,12 @@ namespace Org.OpenAPITools.Model [DataMember(Name = "map_map_of_string", EmitDefaultValue = false)] public Dictionary> MapMapOfString { get; set; } + /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] + public Dictionary MapOfEnumString { get; set; } + /// /// Gets or Sets DirectMap /// @@ -159,7 +158,10 @@ namespace Org.OpenAPITools.Model { hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); } - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } if (this.DirectMap != null) { hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs index 47c53759a0..22cd8a4dcc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs @@ -56,7 +56,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets _Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public int _Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs index 423c6e4e40..b717f6edf8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs @@ -136,7 +136,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs index f4875fadc0..7b574d4828 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs @@ -120,13 +120,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// /// Gets or Sets PhotoUrls /// - [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = true)] public List PhotoUrls { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index 1ca6e54bed..649ca6451c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -59,7 +59,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index f02d7bfe63..5cb4a808c8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -66,13 +66,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs index f88d1ff9f3..780b249dbc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -59,7 +59,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 744e079136..051e10685d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -66,13 +66,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs index 60fd3123b5..2c21c7de83 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -59,7 +59,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs index 3963386a7d..a4d2c9e820 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs @@ -75,7 +75,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs index ccf404fb3a..533d9487bb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs @@ -93,7 +93,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 3e1f2e5fe6..a0275e0ac5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,10 +21,16 @@ - + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/FILES index 4636f1cc22..e99cb9be46 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/FILES @@ -98,6 +98,9 @@ src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs +src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs +src/Org.OpenAPITools/Client/Auth/TokenResponse.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/EnumArrays.md index 8881585a4c..62e34f03db 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/EnumArrays.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject.md deleted file mode 100644 index 40e16da1bb..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | Updated name of the pet | [optional] -**Status** | **string** | Updated status of the pet | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject1.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject1.md deleted file mode 100644 index 2e6d226754..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject1.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject1 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**AdditionalMetadata** | **string** | Additional data to pass to server | [optional] -**File** | **System.IO.Stream** | file to upload | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject2.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject2.md deleted file mode 100644 index c02c78f9b2..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject2.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject2 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**EnumFormStringArray** | **List<string>** | Form parameter enum test (string array) | [optional] -**EnumFormString** | **string** | Form parameter enum test (string) | [optional] [default to EnumFormStringEnum.Efg] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject3.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject3.md deleted file mode 100644 index 38b5bf8a5c..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject3.md +++ /dev/null @@ -1,22 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject3 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Integer** | **int** | None | [optional] -**Int32** | **int** | None | [optional] -**Int64** | **long** | None | [optional] -**Number** | **decimal** | None | -**Float** | **float** | None | [optional] -**Double** | **double** | None | -**String** | **string** | None | [optional] -**PatternWithoutDelimiter** | **string** | None | -**Byte** | **byte[]** | None | -**Binary** | **System.IO.Stream** | None | [optional] -**Date** | **DateTime** | None | [optional] -**DateTime** | **DateTime** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] -**Password** | **string** | None | [optional] -**Callback** | **string** | None | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject4.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject4.md deleted file mode 100644 index c8e00663ee..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject4.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject4 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Param** | **string** | field1 | -**Param2** | **string** | field2 | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject5.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject5.md deleted file mode 100644 index a28ff47f2e..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineObject5.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject5 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**AdditionalMetadata** | **string** | Additional data to pass to server | [optional] -**RequiredFile** | **System.IO.Stream** | file to upload | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineResponseDefault.md deleted file mode 100644 index e3d55e133f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/InlineResponseDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/MapTest.md index dc1ebba4e7..516f9d4fd3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/docs/MapTest.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 76a930092b..5d048a005b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Test.Api { // TODO uncomment below to test the method and replace null with proper value //var response = instance.FooGet(); - //Assert.IsType(response); + //Assert.IsType(response); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index 291231a91b..ced34a4faa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a Dog from type Animal - /// - [Fact] - public void DogDeserializeFromAnimalTest() - { - // TODO uncomment below to test deserialize a Dog from type Animal - //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); - } /// /// Test deserialize a Cat from type Animal /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a Cat from type Animal //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } /// /// Test the property 'ClassName' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/CatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/CatTests.cs index 6deb4b1b61..701ba76028 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/CatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/CatTests.cs @@ -51,9 +51,8 @@ namespace Org.OpenAPITools.Test.Model [Fact] public void CatInstanceTest() { - // test to ensure both Cat and Animal (parent) can have "AdditionalProperties", which result in warnings - Cat c = JsonConvert.DeserializeObject("{\"className\":\"cat\",\"bar\":\"from json bar\"}"); - Assert.Equal("from json bar", c.AdditionalProperties["bar"]); + // TODO uncomment below to test "IsType" Cat + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index e2d84645c6..4f81b845d4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -81,6 +81,14 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'EnumInteger' } /// + /// Test the property 'EnumIntegerOnly' + /// + [Fact] + public void EnumIntegerOnlyTest() + { + // TODO unit test for the property 'EnumIntegerOnly' + } + /// /// Test the property 'EnumNumber' /// [Fact] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs index ba2e45a0eb..97332800e9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -105,6 +105,14 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'Double' } /// + /// Test the property 'Decimal' + /// + [Fact] + public void DecimalTest() + { + // TODO unit test for the property 'Decimal' + } + /// /// Test the property 'String' /// [Fact] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index 75f4fd8b0e..faa4930944 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a ParentPet from type GrandparentAnimal - /// - [Fact] - public void ParentPetDeserializeFromGrandparentAnimalTest() - { - // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal - //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); - } /// /// Test deserialize a ChildCat from type ParentPet /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a ChildCat from type ParentPet //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } /// /// Test the property 'PetType' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs deleted file mode 100644 index eaea37f149..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineObject1 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject1Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject1 - //private InlineObject1 instance; - - public InlineObject1Tests() - { - // TODO uncomment below to create an instance of InlineObject1 - //instance = new InlineObject1(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject1 - /// - [Fact] - public void InlineObject1InstanceTest() - { - // TODO uncomment below to test "IsType" InlineObject1 - //Assert.IsType(instance); - } - - - /// - /// Test the property 'AdditionalMetadata' - /// - [Fact] - public void AdditionalMetadataTest() - { - // TODO unit test for the property 'AdditionalMetadata' - } - /// - /// Test the property 'File' - /// - [Fact] - public void FileTest() - { - // TODO unit test for the property 'File' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs deleted file mode 100644 index 4aef8fa056..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineObject2 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject2Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject2 - //private InlineObject2 instance; - - public InlineObject2Tests() - { - // TODO uncomment below to create an instance of InlineObject2 - //instance = new InlineObject2(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject2 - /// - [Fact] - public void InlineObject2InstanceTest() - { - // TODO uncomment below to test "IsType" InlineObject2 - //Assert.IsType(instance); - } - - - /// - /// Test the property 'EnumFormStringArray' - /// - [Fact] - public void EnumFormStringArrayTest() - { - // TODO unit test for the property 'EnumFormStringArray' - } - /// - /// Test the property 'EnumFormString' - /// - [Fact] - public void EnumFormStringTest() - { - // TODO unit test for the property 'EnumFormString' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject3Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject3Tests.cs deleted file mode 100644 index 0f8750d9eb..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject3Tests.cs +++ /dev/null @@ -1,174 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineObject3 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject3Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject3 - //private InlineObject3 instance; - - public InlineObject3Tests() - { - // TODO uncomment below to create an instance of InlineObject3 - //instance = new InlineObject3(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject3 - /// - [Fact] - public void InlineObject3InstanceTest() - { - // TODO uncomment below to test "IsType" InlineObject3 - //Assert.IsType(instance); - } - - - /// - /// Test the property 'Integer' - /// - [Fact] - public void IntegerTest() - { - // TODO unit test for the property 'Integer' - } - /// - /// Test the property 'Int32' - /// - [Fact] - public void Int32Test() - { - // TODO unit test for the property 'Int32' - } - /// - /// Test the property 'Int64' - /// - [Fact] - public void Int64Test() - { - // TODO unit test for the property 'Int64' - } - /// - /// Test the property 'Number' - /// - [Fact] - public void NumberTest() - { - // TODO unit test for the property 'Number' - } - /// - /// Test the property 'Float' - /// - [Fact] - public void FloatTest() - { - // TODO unit test for the property 'Float' - } - /// - /// Test the property 'Double' - /// - [Fact] - public void DoubleTest() - { - // TODO unit test for the property 'Double' - } - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - /// - /// Test the property 'PatternWithoutDelimiter' - /// - [Fact] - public void PatternWithoutDelimiterTest() - { - // TODO unit test for the property 'PatternWithoutDelimiter' - } - /// - /// Test the property 'Byte' - /// - [Fact] - public void ByteTest() - { - // TODO unit test for the property 'Byte' - } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// - /// Test the property 'Date' - /// - [Fact] - public void DateTest() - { - // TODO unit test for the property 'Date' - } - /// - /// Test the property 'DateTime' - /// - [Fact] - public void DateTimeTest() - { - // TODO unit test for the property 'DateTime' - } - /// - /// Test the property 'Password' - /// - [Fact] - public void PasswordTest() - { - // TODO unit test for the property 'Password' - } - /// - /// Test the property 'Callback' - /// - [Fact] - public void CallbackTest() - { - // TODO unit test for the property 'Callback' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject4Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject4Tests.cs deleted file mode 100644 index b2a24a53c2..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject4Tests.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineObject4 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject4Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject4 - //private InlineObject4 instance; - - public InlineObject4Tests() - { - // TODO uncomment below to create an instance of InlineObject4 - //instance = new InlineObject4(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject4 - /// - [Fact] - public void InlineObject4InstanceTest() - { - // TODO uncomment below to test "IsType" InlineObject4 - //Assert.IsType(instance); - } - - - /// - /// Test the property 'Param' - /// - [Fact] - public void ParamTest() - { - // TODO unit test for the property 'Param' - } - /// - /// Test the property 'Param2' - /// - [Fact] - public void Param2Test() - { - // TODO unit test for the property 'Param2' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject5Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject5Tests.cs deleted file mode 100644 index 9036c47159..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObject5Tests.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineObject5 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject5Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject5 - //private InlineObject5 instance; - - public InlineObject5Tests() - { - // TODO uncomment below to create an instance of InlineObject5 - //instance = new InlineObject5(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject5 - /// - [Fact] - public void InlineObject5InstanceTest() - { - // TODO uncomment below to test "IsType" InlineObject5 - //Assert.IsType(instance); - } - - - /// - /// Test the property 'AdditionalMetadata' - /// - [Fact] - public void AdditionalMetadataTest() - { - // TODO unit test for the property 'AdditionalMetadata' - } - /// - /// Test the property 'RequiredFile' - /// - [Fact] - public void RequiredFileTest() - { - // TODO unit test for the property 'RequiredFile' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs deleted file mode 100644 index e466e5820b..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineObject - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObjectTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject - //private InlineObject instance; - - public InlineObjectTests() - { - // TODO uncomment below to create an instance of InlineObject - //instance = new InlineObject(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject - /// - [Fact] - public void InlineObjectInstanceTest() - { - // TODO uncomment below to test "IsType" InlineObject - //Assert.IsType(instance); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - /// - /// Test the property 'Status' - /// - [Fact] - public void StatusTest() - { - // TODO unit test for the property 'Status' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs deleted file mode 100644 index 7731f80c16..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineResponseDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineResponseDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineResponseDefault - //private InlineResponseDefault instance; - - public InlineResponseDefaultTests() - { - // TODO uncomment below to create an instance of InlineResponseDefault - //instance = new InlineResponseDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineResponseDefault - /// - [Fact] - public void InlineResponseDefaultInstanceTest() - { - // TODO uncomment below to test "IsType" InlineResponseDefault - //Assert.IsType(instance); - } - - - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs index 8a544e417f..24a9e26315 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -57,12 +57,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property '__Client' + /// Test the property '_Client' /// [Fact] - public void __ClientTest() + public void _ClientTest() { - // TODO unit test for the property '__Client' + // TODO unit test for the property '_Client' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs index 57c3f6f9e4..0f0e1ff12a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs @@ -64,6 +64,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'SpecialPropertyName' } + /// + /// Test the property '_SpecialModelName' + /// + [Fact] + public void _SpecialModelNameTest() + { + // TODO unit test for the property '_SpecialModelName' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index e04c8df5fd..95d41fcbd9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs index ff7ce75367..bc5b5556d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs index 421f93ed04..5991b7f0b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 6b66577525..dd74c66d15 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs index 125b0f5cb7..e8439eb125 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api @@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs index 63403e7dcd..e01ed16258 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs index c37a6501c6..8efb827cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs index 70ac64f89a..660dcd3a05 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs @@ -25,18 +25,18 @@ using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; -using RestSharp.Deserializers; +using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { /// /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// - internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; @@ -82,7 +82,9 @@ namespace Org.OpenAPITools.Client } } - public T Deserialize(IRestResponse response) + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; @@ -94,7 +96,7 @@ namespace Org.OpenAPITools.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(IRestResponse response, Type type) + internal object Deserialize(RestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { @@ -147,15 +149,22 @@ namespace Org.OpenAPITools.Client } } - public string RootElement { get; set; } - public string Namespace { get; set; } - public string DateFormat { get; set; } + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } + + public DataFormat DataFormat => DataFormat.Json; } /// /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), @@ -186,14 +195,14 @@ namespace Org.OpenAPITools.Client /// Allows for extending request processing for generated code. /// /// The RestSharp request object - partial void InterceptRequest(IRestRequest request); + partial void InterceptRequest(RestRequest request); /// /// Allows for extending response processing for generated code. /// /// The RestSharp request object /// The RestSharp response object - partial void InterceptResponse(IRestRequest request, IRestResponse response); + partial void InterceptResponse(RestRequest request, RestResponse response); /// /// Initializes a new instance of the , defaulting to the global configurations' base url. @@ -228,25 +237,25 @@ namespace Org.OpenAPITools.Client switch (method) { case HttpMethod.Get: - other = RestSharpMethod.GET; + other = RestSharpMethod.Get; break; case HttpMethod.Post: - other = RestSharpMethod.POST; + other = RestSharpMethod.Post; break; case HttpMethod.Put: - other = RestSharpMethod.PUT; + other = RestSharpMethod.Put; break; case HttpMethod.Delete: - other = RestSharpMethod.DELETE; + other = RestSharpMethod.Delete; break; case HttpMethod.Head: - other = RestSharpMethod.HEAD; + other = RestSharpMethod.Head; break; case HttpMethod.Options: - other = RestSharpMethod.OPTIONS; + other = RestSharpMethod.Options; break; case HttpMethod.Patch: - other = RestSharpMethod.PATCH; + other = RestSharpMethod.Patch; break; default: throw new ArgumentOutOfRangeException("method", method, null); @@ -277,11 +286,7 @@ namespace Org.OpenAPITools.Client if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); - RestRequest request = new RestRequest(Method(method)) - { - Resource = path, - JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) - }; + RestRequest request = new RestRequest(path, Method(method)); if (options.PathParameters != null) { @@ -376,25 +381,17 @@ namespace Org.OpenAPITools.Client var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); else - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } } } - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - request.AddCookie(cookie.Name, cookie.Value); - } - } - return request; } - private ApiResponse ToApiResponse(IRestResponse response) + private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; string rawContent = response.Content; @@ -413,9 +410,17 @@ namespace Org.OpenAPITools.Client } } + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + if (response.Cookies != null) { - foreach (var responseCookies in response.Cookies) + foreach (var responseCookies in response.Cookies.Cast()) { transformed.Cookies.Add( new Cookie( @@ -433,54 +438,46 @@ namespace Org.OpenAPITools.Client private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else - { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } } - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.Proxy = configuration.Proxy; - } + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); - if (configuration.ClientCertificates != null) + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; @@ -516,6 +513,10 @@ namespace Org.OpenAPITools.Client { response.Data = (T)(object)response.RawBytes; } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } InterceptResponse(req, response); @@ -528,7 +529,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, @@ -557,54 +558,35 @@ namespace Org.OpenAPITools.Client private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); - } - - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) - { - client.Proxy = configuration.Proxy; - } - - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; @@ -645,7 +627,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs new file mode 100644 index 0000000000..8b0ba33499 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs @@ -0,0 +1,95 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : AuthenticatorBase + { + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) : base("") + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// Access token to create a parameter from. + /// An authentication parameter. + protected override async ValueTask GetAuthenticationParameter(string accessToken) + { + var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl) + .UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration)); + + var request = new RestRequest() + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + var response = await client.PostAsync(request); + return $"{response.TokenType} {response.AccessToken}"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs new file mode 100644 index 0000000000..e225740925 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs @@ -0,0 +1,27 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs new file mode 100644 index 0000000000..0a94e17e12 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Client.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs index dcc97c295e..e499a7728e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -120,6 +120,16 @@ namespace Org.OpenAPITools.Client return Convert.ToString(obj, CultureInfo.InvariantCulture); } + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + /// /// Encode string in base64 format. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Configuration.cs index 56e3a9d13e..526781f42c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Configuration.cs @@ -17,6 +17,8 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Net.Http; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -118,7 +120,7 @@ namespace Org.OpenAPITools.Client public Configuration() { Proxy = null; - UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); BasePath = "http://petstore.swagger.io:80/v2"; DefaultHeaders = new ConcurrentDictionary(); ApiKey = new ConcurrentDictionary(); @@ -366,6 +368,30 @@ namespace Org.OpenAPITools.Client /// The access token. public virtual string AccessToken { get; set; } + /// + /// Gets or sets the token URL for OAuth2 authentication. + /// + /// The OAuth Token URL. + public virtual string OAuthTokenUrl { get; set; } + + /// + /// Gets or sets the client ID for OAuth2 authentication. + /// + /// The OAuth Client ID. + public virtual string OAuthClientId { get; set; } + + /// + /// Gets or sets the client secret for OAuth2 authentication. + /// + /// The OAuth Client Secret. + public virtual string OAuthClientSecret { get; set; } + + /// + /// Gets or sets the flow for OAuth2 authentication. + /// + /// The OAuth Flow. + public virtual OAuthFlow? OAuthFlow { get; set; } + /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// @@ -689,6 +715,10 @@ namespace Org.OpenAPITools.Client Username = second.Username ?? first.Username, Password = second.Password ?? first.Password, AccessToken = second.AccessToken ?? first.AccessToken, + OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl, + OAuthClientId = second.OAuthClientId ?? first.OAuthClientId, + OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret, + OAuthFlow = second.OAuthFlow ?? first.OAuthFlow, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 6a8f9c8dc0..0b3e867d0f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -325,14 +325,18 @@ namespace Org.OpenAPITools.Client /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { - if (!File.Exists(KeyFilePath)) + string keyStr = string.Empty; + if (File.Exists(KeyFilePath)) { - throw new Exception("key file path does not exist."); + keyStr = File.ReadAllText(KeyFilePath); + } + else + { + keyStr = KeyFilePath; } const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; - var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); var ecdsa = ECDsa.Create(); @@ -430,11 +434,15 @@ namespace Org.OpenAPITools.Client bool isPrivateKeyFile = true; byte[] pemkey = null; - if (!File.Exists(pemfile)) + string pemstr = string.Empty; + if (File.Exists(pemfile)) { - throw new Exception("private key file does not exist."); + pemstr = File.ReadAllText(pemfile).Trim(); + } + else + { + pemstr = pemfile; } - string pemstr = File.ReadAllText(pemfile).Trim(); if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) { @@ -725,9 +733,16 @@ namespace Org.OpenAPITools.Client /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { - if (!File.Exists(keyFilePath)) + string[] key = null; + + if (File.Exists(keyFilePath)) { - throw new Exception("Key file path does not exist."); + key = File.ReadAllLines(keyFilePath); + } + else + { + // The ApiKeyFilePath is passed as string + key = new string[] { keyFilePath }; } const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; @@ -737,7 +752,6 @@ namespace Org.OpenAPITools.Client //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; PrivateKeyType keyType; - var key = File.ReadAllLines(keyFilePath); if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) @@ -751,7 +765,7 @@ namespace Org.OpenAPITools.Client } else { - throw new Exception("Either the key is invalid or key is not supported"); + throw new Exception("The key file path does not exist or key is invalid or key is not supported"); } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IReadableConfiguration.cs index b99a151e5b..c9615dc5aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IReadableConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; using System.Net; using System.Security.Cryptography.X509Certificates; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client /// Access token. string AccessToken { get; } + /// + /// Gets the OAuth token URL. + /// + /// OAuth Token URL. + string OAuthTokenUrl { get; } + + /// + /// Gets the OAuth client ID. + /// + /// OAuth Client ID. + string OAuthClientId { get; } + + /// + /// Gets the OAuth client secret. + /// + /// OAuth Client Secret. + string OAuthClientSecret { get; } + + /// + /// Gets the OAuth flow. + /// + /// OAuth Flow. + OAuthFlow? OAuthFlow { get; } + /// /// Gets the API key. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RequestOptions.cs index 3932047e02..4c26cf69b2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client /// public Object Data { get; set; } + /// + /// If request should be authenticated with OAuth. + /// + public bool OAuth { get; set; } + /// /// Constructs a new instance of /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RetryConfiguration.cs index 91bc7cc6d5..7011f69e77 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RetryConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client /// /// Retry policy /// - public static Policy RetryPolicy { get; set; } + public static Policy RetryPolicy { get; set; } /// /// Async retry policy /// - public static AsyncPolicy AsyncRetryPolicy { get; set; } + public static AsyncPolicy AsyncRetryPolicy { get; set; } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Animal.cs index f5150493c8..83397018b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Animal.cs @@ -65,7 +65,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AppleReq.cs index 2c77cf1c41..9e09e2da8c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AppleReq.cs @@ -56,7 +56,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Cultivar /// - [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = true)] public string Cultivar { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BananaReq.cs index fdd36929d1..3edb9a1b6d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BananaReq.cs @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets LengthCm /// - [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = true)] public decimal LengthCm { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BasquePig.cs index e0c780a14b..f65f049cfd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BasquePig.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Cat.cs index 2bc55707da..86ceaeed1a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Cat.cs @@ -145,7 +145,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Category.cs index 35732f998d..94dea2b30b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Category.cs @@ -66,7 +66,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs index 4c60ed776c..2aa81264fa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs @@ -57,14 +57,6 @@ namespace Org.OpenAPITools.Model /// /// Initializes a new instance of the class. /// - [JsonConstructorAttribute] - protected ChildCat() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// /// name. /// petType (default to PetTypeEnum.ChildCat). public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() @@ -170,7 +162,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index dc78561c0d..353ea1d081 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DanishPig.cs index 38628258d1..d86ff21df9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DanishPig.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Dog.cs index 9cd520deaf..786270d1c4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Dog.cs @@ -148,7 +148,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumArrays.cs index 6d7830c0e8..69568d6c87 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -78,13 +78,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets ArrayEnum - /// - [DataMember(Name = "array_enum", EmitDefaultValue = false)] - public List ArrayEnum { get; set; } /// /// Initializes a new instance of the class. /// @@ -97,6 +90,12 @@ namespace Org.OpenAPITools.Model this.AdditionalProperties = new Dictionary(); } + /// + /// Gets or Sets ArrayEnum + /// + [DataMember(Name = "array_enum", EmitDefaultValue = false)] + public List ArrayEnum { get; set; } + /// /// Gets or Sets additional properties /// @@ -157,7 +156,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumTest.cs index 6f3d2272c5..7386cffd37 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumTest.cs @@ -94,7 +94,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets EnumStringRequired /// - [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = true)] public EnumStringRequiredEnum EnumStringRequired { get; set; } /// /// Defines EnumInteger diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 6565b7b6f3..773eba5b0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FormatTest.cs index 4ae624cb61..9d0979b6f7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FormatTest.cs @@ -111,7 +111,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Number /// - [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = true)] public decimal Number { get; set; } /// @@ -141,7 +141,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Byte /// - [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = true)] public byte[] Byte { get; set; } /// @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Date /// - [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] [JsonConverter(typeof(OpenAPIDateConverter))] public DateTime Date { get; set; } @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Password /// - [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = true)] public string Password { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index eddfcf6011..28e7729a17 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] public string PetType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject.cs deleted file mode 100644 index 651f325b64..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject.cs +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject - /// - [DataContract(Name = "inline_object")] - public partial class InlineObject : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// Updated name of the pet. - /// Updated status of the pet. - public InlineObject(string name = default(string), string status = default(string)) - { - this.Name = name; - this.Status = status; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Updated name of the pet - /// - /// Updated name of the pet - [DataMember(Name = "name", EmitDefaultValue = false)] - public string Name { get; set; } - - /// - /// Updated status of the pet - /// - /// Updated status of the pet - [DataMember(Name = "status", EmitDefaultValue = false)] - public string Status { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject {\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject).AreEqual; - } - - /// - /// Returns true if InlineObject instances are equal - /// - /// Instance of InlineObject to be compared - /// Boolean - public bool Equals(InlineObject input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - if (this.Status != null) - hashCode = hashCode * 59 + this.Status.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject1.cs deleted file mode 100644 index 9e96b966e9..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject1.cs +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject1 - /// - [DataContract(Name = "inline_object_1")] - public partial class InlineObject1 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// Additional data to pass to server. - /// file to upload. - public InlineObject1(string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) - { - this.AdditionalMetadata = additionalMetadata; - this.File = file; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Additional data to pass to server - /// - /// Additional data to pass to server - [DataMember(Name = "additionalMetadata", EmitDefaultValue = false)] - public string AdditionalMetadata { get; set; } - - /// - /// file to upload - /// - /// file to upload - [DataMember(Name = "file", EmitDefaultValue = false)] - public System.IO.Stream File { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject1 {\n"); - sb.Append(" AdditionalMetadata: ").Append(AdditionalMetadata).Append("\n"); - sb.Append(" File: ").Append(File).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject1).AreEqual; - } - - /// - /// Returns true if InlineObject1 instances are equal - /// - /// Instance of InlineObject1 to be compared - /// Boolean - public bool Equals(InlineObject1 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.AdditionalMetadata != null) - hashCode = hashCode * 59 + this.AdditionalMetadata.GetHashCode(); - if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject2.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject2.cs deleted file mode 100644 index 0a8a33d11a..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject2.cs +++ /dev/null @@ -1,185 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject2 - /// - [DataContract(Name = "inline_object_2")] - public partial class InlineObject2 : IEquatable, IValidatableObject - { - /// - /// Defines EnumFormStringArray - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumFormStringArrayEnum - { - /// - /// Enum GreaterThan for value: > - /// - [EnumMember(Value = ">")] - GreaterThan = 1, - - /// - /// Enum Dollar for value: $ - /// - [EnumMember(Value = "$")] - Dollar = 2 - - } - - - /// - /// Form parameter enum test (string array) - /// - /// Form parameter enum test (string array) - [DataMember(Name = "enum_form_string_array", EmitDefaultValue = false)] - public List EnumFormStringArray { get; set; } - /// - /// Form parameter enum test (string) - /// - /// Form parameter enum test (string) - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumFormStringEnum - { - /// - /// Enum Abc for value: _abc - /// - [EnumMember(Value = "_abc")] - Abc = 1, - - /// - /// Enum Efg for value: -efg - /// - [EnumMember(Value = "-efg")] - Efg = 2, - - /// - /// Enum Xyz for value: (xyz) - /// - [EnumMember(Value = "(xyz)")] - Xyz = 3 - - } - - /// - /// Form parameter enum test (string) - /// - /// Form parameter enum test (string) - [DataMember(Name = "enum_form_string", EmitDefaultValue = false)] - public EnumFormStringEnum? EnumFormString { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// Form parameter enum test (string array). - /// Form parameter enum test (string) (default to EnumFormStringEnum.Efg). - public InlineObject2(List enumFormStringArray = default(List), EnumFormStringEnum? enumFormString = EnumFormStringEnum.Efg) - { - this.EnumFormStringArray = enumFormStringArray; - this.EnumFormString = enumFormString; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject2 {\n"); - sb.Append(" EnumFormStringArray: ").Append(EnumFormStringArray).Append("\n"); - sb.Append(" EnumFormString: ").Append(EnumFormString).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject2).AreEqual; - } - - /// - /// Returns true if InlineObject2 instances are equal - /// - /// Instance of InlineObject2 to be compared - /// Boolean - public bool Equals(InlineObject2 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - hashCode = hashCode * 59 + this.EnumFormStringArray.GetHashCode(); - hashCode = hashCode * 59 + this.EnumFormString.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject3.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject3.cs deleted file mode 100644 index 7fce7c5559..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject3.cs +++ /dev/null @@ -1,370 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject3 - /// - [DataContract(Name = "inline_object_3")] - public partial class InlineObject3 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject3() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// - /// None. - /// None. - /// None. - /// None (required). - /// None. - /// None (required). - /// None. - /// None (required). - /// None (required). - /// None. - /// None. - /// None (default to "2010-02-01T10:20:10.111110+01:00"). - /// None. - /// None. - public InlineObject3(int integer = default(int), int int32 = default(int), long int64 = default(long), decimal number = default(decimal), float _float = default(float), double _double = default(double), string _string = default(string), string patternWithoutDelimiter = default(string), byte[] _byte = default(byte[]), System.IO.Stream binary = default(System.IO.Stream), DateTime date = default(DateTime), DateTime dateTime = default(DateTime), string password = default(string), string callback = default(string)) - { - this.Number = number; - this.Double = _double; - // to ensure "patternWithoutDelimiter" is required (not null) - this.PatternWithoutDelimiter = patternWithoutDelimiter ?? throw new ArgumentNullException("patternWithoutDelimiter is a required property for InlineObject3 and cannot be null"); - // to ensure "_byte" is required (not null) - this.Byte = _byte ?? throw new ArgumentNullException("_byte is a required property for InlineObject3 and cannot be null"); - this.Integer = integer; - this.Int32 = int32; - this.Int64 = int64; - this.Float = _float; - this.String = _string; - this.Binary = binary; - this.Date = date; - this.DateTime = dateTime; - this.Password = password; - this.Callback = callback; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// None - /// - /// None - [DataMember(Name = "integer", EmitDefaultValue = false)] - public int Integer { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "int32", EmitDefaultValue = false)] - public int Int32 { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "int64", EmitDefaultValue = false)] - public long Int64 { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] - public decimal Number { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "float", EmitDefaultValue = false)] - public float Float { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "double", IsRequired = true, EmitDefaultValue = false)] - public double Double { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "string", EmitDefaultValue = false)] - public string String { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "pattern_without_delimiter", IsRequired = true, EmitDefaultValue = false)] - public string PatternWithoutDelimiter { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] - public byte[] Byte { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "binary", EmitDefaultValue = false)] - public System.IO.Stream Binary { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "date", EmitDefaultValue = false)] - [JsonConverter(typeof(OpenAPIDateConverter))] - public DateTime Date { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "dateTime", EmitDefaultValue = false)] - public DateTime DateTime { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "password", EmitDefaultValue = false)] - public string Password { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "callback", EmitDefaultValue = false)] - public string Callback { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject3 {\n"); - sb.Append(" Integer: ").Append(Integer).Append("\n"); - sb.Append(" Int32: ").Append(Int32).Append("\n"); - sb.Append(" Int64: ").Append(Int64).Append("\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Float: ").Append(Float).Append("\n"); - sb.Append(" Double: ").Append(Double).Append("\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" PatternWithoutDelimiter: ").Append(PatternWithoutDelimiter).Append("\n"); - sb.Append(" Byte: ").Append(Byte).Append("\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); - sb.Append(" Date: ").Append(Date).Append("\n"); - sb.Append(" DateTime: ").Append(DateTime).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); - sb.Append(" Callback: ").Append(Callback).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject3).AreEqual; - } - - /// - /// Returns true if InlineObject3 instances are equal - /// - /// Instance of InlineObject3 to be compared - /// Boolean - public bool Equals(InlineObject3 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - hashCode = hashCode * 59 + this.Integer.GetHashCode(); - hashCode = hashCode * 59 + this.Int32.GetHashCode(); - hashCode = hashCode * 59 + this.Int64.GetHashCode(); - hashCode = hashCode * 59 + this.Number.GetHashCode(); - hashCode = hashCode * 59 + this.Float.GetHashCode(); - hashCode = hashCode * 59 + this.Double.GetHashCode(); - if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); - if (this.PatternWithoutDelimiter != null) - hashCode = hashCode * 59 + this.PatternWithoutDelimiter.GetHashCode(); - if (this.Byte != null) - hashCode = hashCode * 59 + this.Byte.GetHashCode(); - if (this.Binary != null) - hashCode = hashCode * 59 + this.Binary.GetHashCode(); - if (this.Date != null) - hashCode = hashCode * 59 + this.Date.GetHashCode(); - if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); - if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); - if (this.Callback != null) - hashCode = hashCode * 59 + this.Callback.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - // Integer (int) maximum - if(this.Integer > (int)100) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); - } - - // Integer (int) minimum - if(this.Integer < (int)10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); - } - - // Int32 (int) maximum - if(this.Int32 > (int)200) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); - } - - // Int32 (int) minimum - if(this.Int32 < (int)20) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); - } - - // Number (decimal) maximum - if(this.Number > (decimal)543.2) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); - } - - // Number (decimal) minimum - if(this.Number < (decimal)32.1) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); - } - - // Float (float) maximum - if(this.Float > (float)987.6) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); - } - - // Double (double) maximum - if(this.Double > (double)123.4) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); - } - - // Double (double) minimum - if(this.Double < (double)67.8) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); - } - - // String (string) pattern - Regex regexString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (false == regexString.Match(this.String).Success) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for String, must match a pattern of " + regexString, new [] { "String" }); - } - - // PatternWithoutDelimiter (string) pattern - Regex regexPatternWithoutDelimiter = new Regex(@"^[A-Z].*", RegexOptions.CultureInvariant); - if (false == regexPatternWithoutDelimiter.Match(this.PatternWithoutDelimiter).Success) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithoutDelimiter, must match a pattern of " + regexPatternWithoutDelimiter, new [] { "PatternWithoutDelimiter" }); - } - - // Password (string) maxLength - if(this.Password != null && this.Password.Length > 64) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); - } - - // Password (string) minLength - if(this.Password != null && this.Password.Length < 10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); - } - - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject4.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject4.cs deleted file mode 100644 index 72cece1061..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject4.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject4 - /// - [DataContract(Name = "inline_object_4")] - public partial class InlineObject4 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject4() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// - /// field1 (required). - /// field2 (required). - public InlineObject4(string param = default(string), string param2 = default(string)) - { - // to ensure "param" is required (not null) - this.Param = param ?? throw new ArgumentNullException("param is a required property for InlineObject4 and cannot be null"); - // to ensure "param2" is required (not null) - this.Param2 = param2 ?? throw new ArgumentNullException("param2 is a required property for InlineObject4 and cannot be null"); - this.AdditionalProperties = new Dictionary(); - } - - /// - /// field1 - /// - /// field1 - [DataMember(Name = "param", IsRequired = true, EmitDefaultValue = false)] - public string Param { get; set; } - - /// - /// field2 - /// - /// field2 - [DataMember(Name = "param2", IsRequired = true, EmitDefaultValue = false)] - public string Param2 { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject4 {\n"); - sb.Append(" Param: ").Append(Param).Append("\n"); - sb.Append(" Param2: ").Append(Param2).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject4).AreEqual; - } - - /// - /// Returns true if InlineObject4 instances are equal - /// - /// Instance of InlineObject4 to be compared - /// Boolean - public bool Equals(InlineObject4 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.Param != null) - hashCode = hashCode * 59 + this.Param.GetHashCode(); - if (this.Param2 != null) - hashCode = hashCode * 59 + this.Param2.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject5.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject5.cs deleted file mode 100644 index f682f14ef4..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineObject5.cs +++ /dev/null @@ -1,150 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject5 - /// - [DataContract(Name = "inline_object_5")] - public partial class InlineObject5 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject5() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// - /// Additional data to pass to server. - /// file to upload (required). - public InlineObject5(string additionalMetadata = default(string), System.IO.Stream requiredFile = default(System.IO.Stream)) - { - // to ensure "requiredFile" is required (not null) - this.RequiredFile = requiredFile ?? throw new ArgumentNullException("requiredFile is a required property for InlineObject5 and cannot be null"); - this.AdditionalMetadata = additionalMetadata; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Additional data to pass to server - /// - /// Additional data to pass to server - [DataMember(Name = "additionalMetadata", EmitDefaultValue = false)] - public string AdditionalMetadata { get; set; } - - /// - /// file to upload - /// - /// file to upload - [DataMember(Name = "requiredFile", IsRequired = true, EmitDefaultValue = false)] - public System.IO.Stream RequiredFile { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject5 {\n"); - sb.Append(" AdditionalMetadata: ").Append(AdditionalMetadata).Append("\n"); - sb.Append(" RequiredFile: ").Append(RequiredFile).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject5).AreEqual; - } - - /// - /// Returns true if InlineObject5 instances are equal - /// - /// Instance of InlineObject5 to be compared - /// Boolean - public bool Equals(InlineObject5 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.AdditionalMetadata != null) - hashCode = hashCode * 59 + this.AdditionalMetadata.GetHashCode(); - if (this.RequiredFile != null) - hashCode = hashCode * 59 + this.RequiredFile.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineResponseDefault.cs deleted file mode 100644 index ae46f1f009..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineResponseDefault - /// - [DataContract(Name = "inline_response_default")] - public partial class InlineResponseDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// _string. - public InlineResponseDefault(Foo _string = default(Foo)) - { - this.String = _string; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Gets or Sets String - /// - [DataMember(Name = "string", EmitDefaultValue = false)] - public Foo String { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineResponseDefault {\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineResponseDefault).AreEqual; - } - - /// - /// Returns true if InlineResponseDefault instances are equal - /// - /// Instance of InlineResponseDefault to be compared - /// Boolean - public bool Equals(InlineResponseDefault input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 55c607598a..ea18925f87 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -61,13 +61,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MapTest.cs index 8b5a73e773..b2aeedc33c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MapTest.cs @@ -52,13 +52,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets MapOfEnumString - /// - [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] - public Dictionary MapOfEnumString { get; set; } /// /// Initializes a new instance of the class. /// @@ -81,6 +74,12 @@ namespace Org.OpenAPITools.Model [DataMember(Name = "map_map_of_string", EmitDefaultValue = false)] public Dictionary> MapMapOfString { get; set; } + /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] + public Dictionary MapOfEnumString { get; set; } + /// /// Gets or Sets DirectMap /// @@ -158,7 +157,10 @@ namespace Org.OpenAPITools.Model { hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); } - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } if (this.DirectMap != null) { hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs index 0dc21bb656..1d4e760506 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs @@ -55,7 +55,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets _Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public int _Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ParentPet.cs index ac986b555e..49bed67986 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ParentPet.cs @@ -135,7 +135,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pet.cs index 4723827264..0e6f950d7f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pet.cs @@ -119,13 +119,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// /// Gets or Sets PhotoUrls /// - [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = true)] public List PhotoUrls { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index cb2a5dc169..d5be5ea3c9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index e54c584688..236020031e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeInterface.cs index 6225f8888a..c9294b0b4e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index b8fbc0c240..59397bf30f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TriangleInterface.cs index 17571e4514..cdf2bd1f0f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Whale.cs index 10ceda658b..62ae66415f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Whale.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs index aab75e9cd5..8a3c713fe6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs @@ -92,7 +92,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 87e0729d08..a324f24e7e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,11 +21,17 @@ - + - + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.gitignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.gitignore new file mode 100644 index 0000000000..1ee53850b8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator-ignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.openapi-generator-ignore similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator-ignore rename to samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.openapi-generator-ignore diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.openapi-generator/FILES new file mode 100644 index 0000000000..e99cb9be46 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.openapi-generator/FILES @@ -0,0 +1,196 @@ +.gitignore +Org.OpenAPITools.sln +README.md +appveyor.yml +docs/AdditionalPropertiesClass.md +docs/Animal.md +docs/AnotherFakeApi.md +docs/ApiResponse.md +docs/Apple.md +docs/AppleReq.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Banana.md +docs/BananaReq.md +docs/BasquePig.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ChildCat.md +docs/ChildCatAllOf.md +docs/ClassModel.md +docs/ComplexQuadrilateral.md +docs/DanishPig.md +docs/DefaultApi.md +docs/DeprecatedObject.md +docs/Dog.md +docs/DogAllOf.md +docs/Drawing.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/EquilateralTriangle.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/File.md +docs/FileSchemaTestClass.md +docs/Foo.md +docs/FooGetDefaultResponse.md +docs/FormatTest.md +docs/Fruit.md +docs/FruitReq.md +docs/GmFruit.md +docs/GrandparentAnimal.md +docs/HasOnlyReadOnly.md +docs/HealthCheckResult.md +docs/IsoscelesTriangle.md +docs/List.md +docs/Mammal.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelClient.md +docs/Name.md +docs/NullableClass.md +docs/NullableShape.md +docs/NumberOnly.md +docs/ObjectWithDeprecatedFields.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/OuterEnumDefaultValue.md +docs/OuterEnumInteger.md +docs/OuterEnumIntegerDefaultValue.md +docs/ParentPet.md +docs/Pet.md +docs/PetApi.md +docs/Pig.md +docs/PolymorphicProperty.md +docs/Quadrilateral.md +docs/QuadrilateralInterface.md +docs/ReadOnlyFirst.md +docs/Return.md +docs/ScaleneTriangle.md +docs/Shape.md +docs/ShapeInterface.md +docs/ShapeOrNull.md +docs/SimpleQuadrilateral.md +docs/SpecialModelName.md +docs/StoreApi.md +docs/Tag.md +docs/Triangle.md +docs/TriangleInterface.md +docs/User.md +docs/UserApi.md +docs/Whale.md +docs/Zebra.md +git_push.sh +src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools/Api/AnotherFakeApi.cs +src/Org.OpenAPITools/Api/DefaultApi.cs +src/Org.OpenAPITools/Api/FakeApi.cs +src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +src/Org.OpenAPITools/Api/PetApi.cs +src/Org.OpenAPITools/Api/StoreApi.cs +src/Org.OpenAPITools/Api/UserApi.cs +src/Org.OpenAPITools/Client/ApiClient.cs +src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs +src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs +src/Org.OpenAPITools/Client/Auth/TokenResponse.cs +src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/Configuration.cs +src/Org.OpenAPITools/Client/ExceptionFactory.cs +src/Org.OpenAPITools/Client/GlobalConfiguration.cs +src/Org.OpenAPITools/Client/HttpMethod.cs +src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +src/Org.OpenAPITools/Client/IApiAccessor.cs +src/Org.OpenAPITools/Client/IAsynchronousClient.cs +src/Org.OpenAPITools/Client/IReadableConfiguration.cs +src/Org.OpenAPITools/Client/ISynchronousClient.cs +src/Org.OpenAPITools/Client/Multimap.cs +src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs +src/Org.OpenAPITools/Client/RequestOptions.cs +src/Org.OpenAPITools/Client/RetryConfiguration.cs +src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs +src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +src/Org.OpenAPITools/Model/Animal.cs +src/Org.OpenAPITools/Model/ApiResponse.cs +src/Org.OpenAPITools/Model/Apple.cs +src/Org.OpenAPITools/Model/AppleReq.cs +src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +src/Org.OpenAPITools/Model/ArrayTest.cs +src/Org.OpenAPITools/Model/Banana.cs +src/Org.OpenAPITools/Model/BananaReq.cs +src/Org.OpenAPITools/Model/BasquePig.cs +src/Org.OpenAPITools/Model/Capitalization.cs +src/Org.OpenAPITools/Model/Cat.cs +src/Org.OpenAPITools/Model/CatAllOf.cs +src/Org.OpenAPITools/Model/Category.cs +src/Org.OpenAPITools/Model/ChildCat.cs +src/Org.OpenAPITools/Model/ChildCatAllOf.cs +src/Org.OpenAPITools/Model/ClassModel.cs +src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +src/Org.OpenAPITools/Model/DanishPig.cs +src/Org.OpenAPITools/Model/DeprecatedObject.cs +src/Org.OpenAPITools/Model/Dog.cs +src/Org.OpenAPITools/Model/DogAllOf.cs +src/Org.OpenAPITools/Model/Drawing.cs +src/Org.OpenAPITools/Model/EnumArrays.cs +src/Org.OpenAPITools/Model/EnumClass.cs +src/Org.OpenAPITools/Model/EnumTest.cs +src/Org.OpenAPITools/Model/EquilateralTriangle.cs +src/Org.OpenAPITools/Model/File.cs +src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +src/Org.OpenAPITools/Model/Foo.cs +src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs +src/Org.OpenAPITools/Model/FormatTest.cs +src/Org.OpenAPITools/Model/Fruit.cs +src/Org.OpenAPITools/Model/FruitReq.cs +src/Org.OpenAPITools/Model/GmFruit.cs +src/Org.OpenAPITools/Model/GrandparentAnimal.cs +src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +src/Org.OpenAPITools/Model/HealthCheckResult.cs +src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +src/Org.OpenAPITools/Model/List.cs +src/Org.OpenAPITools/Model/Mammal.cs +src/Org.OpenAPITools/Model/MapTest.cs +src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +src/Org.OpenAPITools/Model/Model200Response.cs +src/Org.OpenAPITools/Model/ModelClient.cs +src/Org.OpenAPITools/Model/Name.cs +src/Org.OpenAPITools/Model/NullableClass.cs +src/Org.OpenAPITools/Model/NullableShape.cs +src/Org.OpenAPITools/Model/NumberOnly.cs +src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +src/Org.OpenAPITools/Model/Order.cs +src/Org.OpenAPITools/Model/OuterComposite.cs +src/Org.OpenAPITools/Model/OuterEnum.cs +src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +src/Org.OpenAPITools/Model/OuterEnumInteger.cs +src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +src/Org.OpenAPITools/Model/ParentPet.cs +src/Org.OpenAPITools/Model/Pet.cs +src/Org.OpenAPITools/Model/Pig.cs +src/Org.OpenAPITools/Model/PolymorphicProperty.cs +src/Org.OpenAPITools/Model/Quadrilateral.cs +src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/Return.cs +src/Org.OpenAPITools/Model/ScaleneTriangle.cs +src/Org.OpenAPITools/Model/Shape.cs +src/Org.OpenAPITools/Model/ShapeInterface.cs +src/Org.OpenAPITools/Model/ShapeOrNull.cs +src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +src/Org.OpenAPITools/Model/SpecialModelName.cs +src/Org.OpenAPITools/Model/Tag.cs +src/Org.OpenAPITools/Model/Triangle.cs +src/Org.OpenAPITools/Model/TriangleInterface.cs +src/Org.OpenAPITools/Model/User.cs +src/Org.OpenAPITools/Model/Whale.cs +src/Org.OpenAPITools/Model/Zebra.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/Org.OpenAPITools.sln b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/Org.OpenAPITools.sln new file mode 100644 index 0000000000..5b15451c9d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/Org.OpenAPITools.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{321C8C3F-0156-40C1-AE42-D59761FB9B6C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Test", "src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {321C8C3F-0156-40C1-AE42-D59761FB9B6C}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/README.md new file mode 100644 index 0000000000..b3a20c0c08 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/README.md @@ -0,0 +1,281 @@ +# Org.OpenAPITools - the C# library for the OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen + + +## Frameworks supported + + +## Dependencies + +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.13.0 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.1 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later + +The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: +``` +Install-Package RestSharp +Install-Package Newtonsoft.Json +Install-Package JsonSubTypes +Install-Package System.ComponentModel.Annotations +Install-Package CompareNETObjects +``` + +NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742). +NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406). + + +## Installation +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; +``` + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out Org.OpenAPITools.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + + +## Usage + +To use the API client with a HTTP proxy, setup a `System.Net.WebProxy` +```csharp +Configuration c = new Configuration(); +System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/"); +webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials; +c.Proxy = webProxy; +``` + + +## Getting Started + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class Example + { + public static void Main() + { + + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new AnotherFakeApi(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test special tags + ModelClient result = apiInstance.Call123TestSpecialTags(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling AnotherFakeApi.Call123TestSpecialTags: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**Call123TestSpecialTags**](docs/AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*DefaultApi* | [**FooGet**](docs/DefaultApi.md#fooget) | **GET** /foo | +*FakeApi* | [**FakeHealthGet**](docs/FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +*FakeApi* | [**FakeOuterBooleanSerialize**](docs/FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeApi* | [**FakeOuterCompositeSerialize**](docs/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | +*FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | +*FakeApi* | [**GetArrayOfEnums**](docs/FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +*FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +*FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**TestEnumParameters**](docs/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**TestGroupParameters**](docs/FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**TestInlineAdditionalProperties**](docs/FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**TestJsonFormData**](docs/FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeApi* | [**TestQueryParameterCollectionFormat**](docs/FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-parameters | +*FakeClassnameTags123Api* | [**TestClassname**](docs/FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetApi* | [**UploadFileWithRequiredFile**](docs/PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [Model.AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Model.Animal](docs/Animal.md) + - [Model.ApiResponse](docs/ApiResponse.md) + - [Model.Apple](docs/Apple.md) + - [Model.AppleReq](docs/AppleReq.md) + - [Model.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [Model.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [Model.ArrayTest](docs/ArrayTest.md) + - [Model.Banana](docs/Banana.md) + - [Model.BananaReq](docs/BananaReq.md) + - [Model.BasquePig](docs/BasquePig.md) + - [Model.Capitalization](docs/Capitalization.md) + - [Model.Cat](docs/Cat.md) + - [Model.CatAllOf](docs/CatAllOf.md) + - [Model.Category](docs/Category.md) + - [Model.ChildCat](docs/ChildCat.md) + - [Model.ChildCatAllOf](docs/ChildCatAllOf.md) + - [Model.ClassModel](docs/ClassModel.md) + - [Model.ComplexQuadrilateral](docs/ComplexQuadrilateral.md) + - [Model.DanishPig](docs/DanishPig.md) + - [Model.DeprecatedObject](docs/DeprecatedObject.md) + - [Model.Dog](docs/Dog.md) + - [Model.DogAllOf](docs/DogAllOf.md) + - [Model.Drawing](docs/Drawing.md) + - [Model.EnumArrays](docs/EnumArrays.md) + - [Model.EnumClass](docs/EnumClass.md) + - [Model.EnumTest](docs/EnumTest.md) + - [Model.EquilateralTriangle](docs/EquilateralTriangle.md) + - [Model.File](docs/File.md) + - [Model.FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [Model.Foo](docs/Foo.md) + - [Model.FooGetDefaultResponse](docs/FooGetDefaultResponse.md) + - [Model.FormatTest](docs/FormatTest.md) + - [Model.Fruit](docs/Fruit.md) + - [Model.FruitReq](docs/FruitReq.md) + - [Model.GmFruit](docs/GmFruit.md) + - [Model.GrandparentAnimal](docs/GrandparentAnimal.md) + - [Model.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [Model.HealthCheckResult](docs/HealthCheckResult.md) + - [Model.IsoscelesTriangle](docs/IsoscelesTriangle.md) + - [Model.List](docs/List.md) + - [Model.Mammal](docs/Mammal.md) + - [Model.MapTest](docs/MapTest.md) + - [Model.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model.Model200Response](docs/Model200Response.md) + - [Model.ModelClient](docs/ModelClient.md) + - [Model.Name](docs/Name.md) + - [Model.NullableClass](docs/NullableClass.md) + - [Model.NullableShape](docs/NullableShape.md) + - [Model.NumberOnly](docs/NumberOnly.md) + - [Model.ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [Model.Order](docs/Order.md) + - [Model.OuterComposite](docs/OuterComposite.md) + - [Model.OuterEnum](docs/OuterEnum.md) + - [Model.OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) + - [Model.OuterEnumInteger](docs/OuterEnumInteger.md) + - [Model.OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) + - [Model.ParentPet](docs/ParentPet.md) + - [Model.Pet](docs/Pet.md) + - [Model.Pig](docs/Pig.md) + - [Model.PolymorphicProperty](docs/PolymorphicProperty.md) + - [Model.Quadrilateral](docs/Quadrilateral.md) + - [Model.QuadrilateralInterface](docs/QuadrilateralInterface.md) + - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Model.Return](docs/Return.md) + - [Model.ScaleneTriangle](docs/ScaleneTriangle.md) + - [Model.Shape](docs/Shape.md) + - [Model.ShapeInterface](docs/ShapeInterface.md) + - [Model.ShapeOrNull](docs/ShapeOrNull.md) + - [Model.SimpleQuadrilateral](docs/SimpleQuadrilateral.md) + - [Model.SpecialModelName](docs/SpecialModelName.md) + - [Model.Tag](docs/Tag.md) + - [Model.Triangle](docs/Triangle.md) + - [Model.TriangleInterface](docs/TriangleInterface.md) + - [Model.User](docs/User.md) + - [Model.Whale](docs/Whale.md) + - [Model.Zebra](docs/Zebra.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + +### bearer_test + +- **Type**: Bearer Authentication + + +### http_basic_test + +- **Type**: HTTP basic authentication + + +### http_signature_test + + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/appveyor.yml b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/appveyor.yml new file mode 100644 index 0000000000..f76f63cee5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/appveyor.yml @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\Org.OpenAPITools\Org.OpenAPITools.csproj -o ../../output -c Release --no-build diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/AdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/AdditionalPropertiesClass.md new file mode 100644 index 0000000000..c40cd0f8ac --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/AdditionalPropertiesClass.md @@ -0,0 +1,17 @@ +# Org.OpenAPITools.Model.AdditionalPropertiesClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapProperty** | **Dictionary<string, string>** | | [optional] +**MapOfMapProperty** | **Dictionary<string, Dictionary<string, string>>** | | [optional] +**Anytype1** | **Object** | | [optional] +**MapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] +**MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] +**MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] +**EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] +**MapWithUndeclaredPropertiesString** | **Dictionary<string, string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Animal.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Animal.md new file mode 100644 index 0000000000..f14b7a3ae4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Animal.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Animal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/AnotherFakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/AnotherFakeApi.md new file mode 100644 index 0000000000..0ddc28a119 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/AnotherFakeApi.md @@ -0,0 +1,99 @@ +# Org.OpenAPITools.Api.AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**Call123TestSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags | + + +# **Call123TestSpecialTags** +> ModelClient Call123TestSpecialTags (ModelClient modelClient) + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class Call123TestSpecialTagsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new AnotherFakeApi(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test special tags + ModelClient result = apiInstance.Call123TestSpecialTags(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling AnotherFakeApi.Call123TestSpecialTags: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the Call123TestSpecialTagsWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // To test special tags + ApiResponse response = apiInstance.Call123TestSpecialTagsWithHttpInfo(modelClient); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling AnotherFakeApi.Call123TestSpecialTagsWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **modelClient** | [**ModelClient**](ModelClient.md) | client model | | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ApiResponse.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ApiResponse.md new file mode 100644 index 0000000000..bb723d2baa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.ApiResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Code** | **int** | | [optional] +**Type** | **string** | | [optional] +**Message** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Apple.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Apple.md new file mode 100644 index 0000000000..1f819f8f28 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Apple.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Apple + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Cultivar** | **string** | | [optional] +**Origin** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/AppleReq.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/AppleReq.md new file mode 100644 index 0000000000..005b8f8058 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/AppleReq.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.AppleReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Cultivar** | **string** | | +**Mealy** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 0000000000..4764c0ff80 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ArrayOfArrayOfNumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayArrayNumber** | **List<List<decimal>>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ArrayOfNumberOnly.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ArrayOfNumberOnly.md new file mode 100644 index 0000000000..d93717103b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ArrayOfNumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayNumber** | **List<decimal>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ArrayTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ArrayTest.md new file mode 100644 index 0000000000..d74d11bae7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.ArrayTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayOfString** | **List<string>** | | [optional] +**ArrayArrayOfInteger** | **List<List<long>>** | | [optional] +**ArrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Banana.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Banana.md new file mode 100644 index 0000000000..226952d1ce --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Banana.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Banana + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**LengthCm** | **decimal** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/BananaReq.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/BananaReq.md new file mode 100644 index 0000000000..f99aab99e3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/BananaReq.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.BananaReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**LengthCm** | **decimal** | | +**Sweet** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/BasquePig.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/BasquePig.md new file mode 100644 index 0000000000..681be0bc7e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/BasquePig.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.BasquePig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Capitalization.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Capitalization.md new file mode 100644 index 0000000000..1b1352d918 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Capitalization.md @@ -0,0 +1,15 @@ +# Org.OpenAPITools.Model.Capitalization + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SmallCamel** | **string** | | [optional] +**CapitalCamel** | **string** | | [optional] +**SmallSnake** | **string** | | [optional] +**CapitalSnake** | **string** | | [optional] +**SCAETHFlowPoints** | **string** | | [optional] +**ATT_NAME** | **string** | Name of the pet | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Cat.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Cat.md new file mode 100644 index 0000000000..aa1ac17604 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Cat.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.Cat + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] +**Declawed** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/CatAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/CatAllOf.md new file mode 100644 index 0000000000..6cbaaa14e8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/CatAllOf.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.CatAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Declawed** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Category.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Category.md new file mode 100644 index 0000000000..032a1faeb3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Category.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Category + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Name** | **string** | | [default to "default-name"] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ChildCat.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ChildCat.md new file mode 100644 index 0000000000..072ad05b36 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ChildCat.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ChildCat + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [optional] +**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ChildCatAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ChildCatAllOf.md new file mode 100644 index 0000000000..864d33e80e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ChildCatAllOf.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ChildCatAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [optional] +**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ClassModel.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ClassModel.md new file mode 100644 index 0000000000..f39982657c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ClassModel.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ClassModel +Model for testing model with \"_class\" property + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Class** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ComplexQuadrilateral.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ComplexQuadrilateral.md new file mode 100644 index 0000000000..65a6097ce3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ComplexQuadrilateral.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ComplexQuadrilateral + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DanishPig.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DanishPig.md new file mode 100644 index 0000000000..d9cf6527a3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DanishPig.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.DanishPig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DefaultApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DefaultApi.md new file mode 100644 index 0000000000..3a93305e15 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DefaultApi.md @@ -0,0 +1,90 @@ +# Org.OpenAPITools.Api.DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**FooGet**](DefaultApi.md#fooget) | **GET** /foo | | + + +# **FooGet** +> FooGetDefaultResponse FooGet () + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class FooGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new DefaultApi(config); + + try + { + FooGetDefaultResponse result = apiInstance.FooGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.FooGet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FooGetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FooGetWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.FooGetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**FooGetDefaultResponse**](FooGetDefaultResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | response | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DeprecatedObject.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DeprecatedObject.md new file mode 100644 index 0000000000..bb7824a3d6 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DeprecatedObject.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.DeprecatedObject + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Dog.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Dog.md new file mode 100644 index 0000000000..3aa00144e9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Dog.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.Dog + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] +**Breed** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DogAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DogAllOf.md new file mode 100644 index 0000000000..c1096f2c31 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/DogAllOf.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.DogAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Breed** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Drawing.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Drawing.md new file mode 100644 index 0000000000..6b7122940a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Drawing.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.Drawing + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MainShape** | [**Shape**](Shape.md) | | [optional] +**ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] +**NullableShape** | [**NullableShape**](NullableShape.md) | | [optional] +**Shapes** | [**List<Shape>**](Shape.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EnumArrays.md new file mode 100644 index 0000000000..62e34f03db --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.EnumArrays + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustSymbol** | **string** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EnumClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EnumClass.md new file mode 100644 index 0000000000..38f309437d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EnumClass.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.EnumClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EnumTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EnumTest.md new file mode 100644 index 0000000000..5ce3c4addd --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EnumTest.md @@ -0,0 +1,18 @@ +# Org.OpenAPITools.Model.EnumTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EnumString** | **string** | | [optional] +**EnumStringRequired** | **string** | | +**EnumInteger** | **int** | | [optional] +**EnumIntegerOnly** | **int** | | [optional] +**EnumNumber** | **double** | | [optional] +**OuterEnum** | **OuterEnum** | | [optional] +**OuterEnumInteger** | **OuterEnumInteger** | | [optional] +**OuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**OuterEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EquilateralTriangle.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EquilateralTriangle.md new file mode 100644 index 0000000000..ab06d96ca3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/EquilateralTriangle.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.EquilateralTriangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FakeApi.md new file mode 100644 index 0000000000..46d135e359 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FakeApi.md @@ -0,0 +1,1392 @@ +# Org.OpenAPITools.Api.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**FakeHealthGet**](FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint | +| [**FakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | | +| [**FakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | | +| [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | +| [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | +| [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | +| [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | +| [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | +| [**TestEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 | +| [**TestEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters | +| [**TestGroupParameters**](FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) | +| [**TestInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties | +| [**TestJsonFormData**](FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data | +| [**TestQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-parameters | | + + +# **FakeHealthGet** +> HealthCheckResult FakeHealthGet () + +Health check endpoint + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class FakeHealthGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + + try + { + // Health check endpoint + HealthCheckResult result = apiInstance.FakeHealthGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeHealthGet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeHealthGetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Health check endpoint + ApiResponse response = apiInstance.FakeHealthGetWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeHealthGetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | The instance started successfully | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FakeOuterBooleanSerialize** +> bool FakeOuterBooleanSerialize (bool? body = null) + + + +Test serialization of outer boolean types + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class FakeOuterBooleanSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var body = true; // bool? | Input boolean as post body (optional) + + try + { + bool result = apiInstance.FakeOuterBooleanSerialize(body); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterBooleanSerialize: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeOuterBooleanSerializeWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FakeOuterBooleanSerializeWithHttpInfo(body); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeOuterBooleanSerializeWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **body** | **bool?** | Input boolean as post body | [optional] | + +### Return type + +**bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output boolean | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FakeOuterCompositeSerialize** +> OuterComposite FakeOuterCompositeSerialize (OuterComposite outerComposite = null) + + + +Test serialization of object with outer number type + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class FakeOuterCompositeSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body (optional) + + try + { + OuterComposite result = apiInstance.FakeOuterCompositeSerialize(outerComposite); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterCompositeSerialize: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeOuterCompositeSerializeWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FakeOuterCompositeSerializeWithHttpInfo(outerComposite); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeOuterCompositeSerializeWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **outerComposite** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] | + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output composite | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FakeOuterNumberSerialize** +> decimal FakeOuterNumberSerialize (decimal? body = null) + + + +Test serialization of outer number types + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class FakeOuterNumberSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var body = 8.14D; // decimal? | Input number as post body (optional) + + try + { + decimal result = apiInstance.FakeOuterNumberSerialize(body); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterNumberSerialize: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeOuterNumberSerializeWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FakeOuterNumberSerializeWithHttpInfo(body); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeOuterNumberSerializeWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **body** | **decimal?** | Input number as post body | [optional] | + +### Return type + +**decimal** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output number | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FakeOuterStringSerialize** +> string FakeOuterStringSerialize (string body = null) + + + +Test serialization of outer string types + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class FakeOuterStringSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var body = "body_example"; // string | Input string as post body (optional) + + try + { + string result = apiInstance.FakeOuterStringSerialize(body); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterStringSerialize: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FakeOuterStringSerializeWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.FakeOuterStringSerializeWithHttpInfo(body); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.FakeOuterStringSerializeWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **body** | **string** | Input string as post body | [optional] | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output string | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetArrayOfEnums** +> List<OuterEnum> GetArrayOfEnums () + +Array of Enums + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class GetArrayOfEnumsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + + try + { + // Array of Enums + List result = apiInstance.GetArrayOfEnums(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.GetArrayOfEnums: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetArrayOfEnumsWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Array of Enums + ApiResponse> response = apiInstance.GetArrayOfEnumsWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.GetArrayOfEnumsWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**List<OuterEnum>**](OuterEnum.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Got named array of enums | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestBodyWithFileSchema** +> void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestBodyWithFileSchemaExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | + + try + { + apiInstance.TestBodyWithFileSchema(fileSchemaTestClass); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestBodyWithFileSchema: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestBodyWithFileSchemaWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + apiInstance.TestBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestBodyWithFileSchemaWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestBodyWithQueryParams** +> void TestBodyWithQueryParams (string query, User user) + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestBodyWithQueryParamsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var query = "query_example"; // string | + var user = new User(); // User | + + try + { + apiInstance.TestBodyWithQueryParams(query, user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestBodyWithQueryParams: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestBodyWithQueryParamsWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + apiInstance.TestBodyWithQueryParamsWithHttpInfo(query, user); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestBodyWithQueryParamsWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **query** | **string** | | | +| **user** | [**User**](User.md) | | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestClientModel** +> ModelClient TestClientModel (ModelClient modelClient) + +To test \"client\" model + +To test \"client\" model + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestClientModelExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test \"client\" model + ModelClient result = apiInstance.TestClientModel(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestClientModel: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestClientModelWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // To test \"client\" model + ApiResponse response = apiInstance.TestClientModelWithHttpInfo(modelClient); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestClientModelWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **modelClient** | [**ModelClient**](ModelClient.md) | client model | | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestEndpointParameters** +> void TestEndpointParameters (decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestEndpointParametersExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure HTTP basic authorization: http_basic_test + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + + var apiInstance = new FakeApi(config); + var number = 8.14D; // decimal | None + var _double = 1.2D; // double | None + var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // string | None + var _byte = System.Text.Encoding.ASCII.GetBytes("BYTE_ARRAY_DATA_HERE"); // byte[] | None + var integer = 56; // int? | None (optional) + var int32 = 56; // int? | None (optional) + var int64 = 789L; // long? | None (optional) + var _float = 3.4F; // float? | None (optional) + var _string = "_string_example"; // string | None (optional) + var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | None (optional) + var date = DateTime.Parse("2013-10-20"); // DateTime? | None (optional) + var dateTime = DateTime.Parse(""2010-02-01T10:20:10.111110+01:00""); // DateTime? | None (optional) (default to "2010-02-01T10:20:10.111110+01:00") + var password = "password_example"; // string | None (optional) + var callback = "callback_example"; // string | None (optional) + + try + { + // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestEndpointParameters: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestEndpointParametersWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + apiInstance.TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestEndpointParametersWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **number** | **decimal** | None | | +| **_double** | **double** | None | | +| **patternWithoutDelimiter** | **string** | None | | +| **_byte** | **byte[]** | None | | +| **integer** | **int?** | None | [optional] | +| **int32** | **int?** | None | [optional] | +| **int64** | **long?** | None | [optional] | +| **_float** | **float?** | None | [optional] | +| **_string** | **string** | None | [optional] | +| **binary** | **System.IO.Stream****System.IO.Stream** | None | [optional] | +| **date** | **DateTime?** | None | [optional] | +| **dateTime** | **DateTime?** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] | +| **password** | **string** | None | [optional] | +| **callback** | **string** | None | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestEnumParameters** +> void TestEnumParameters (List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null, List enumFormStringArray = null, string enumFormString = null) + +To test enum parameters + +To test enum parameters + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestEnumParametersExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var enumHeaderStringArray = new List(); // List | Header parameter enum test (string array) (optional) + var enumHeaderString = "_abc"; // string | Header parameter enum test (string) (optional) (default to -efg) + var enumQueryStringArray = new List(); // List | Query parameter enum test (string array) (optional) + var enumQueryString = "_abc"; // string | Query parameter enum test (string) (optional) (default to -efg) + var enumQueryInteger = 1; // int? | Query parameter enum test (double) (optional) + var enumQueryDouble = 1.1D; // double? | Query parameter enum test (double) (optional) + var enumFormStringArray = new List(); // List | Form parameter enum test (string array) (optional) (default to $) + var enumFormString = "_abc"; // string | Form parameter enum test (string) (optional) (default to -efg) + + try + { + // To test enum parameters + apiInstance.TestEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestEnumParameters: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestEnumParametersWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // To test enum parameters + apiInstance.TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestEnumParametersWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **enumHeaderStringArray** | [**List<string>**](string.md) | Header parameter enum test (string array) | [optional] | +| **enumHeaderString** | **string** | Header parameter enum test (string) | [optional] [default to -efg] | +| **enumQueryStringArray** | [**List<string>**](string.md) | Query parameter enum test (string array) | [optional] | +| **enumQueryString** | **string** | Query parameter enum test (string) | [optional] [default to -efg] | +| **enumQueryInteger** | **int?** | Query parameter enum test (double) | [optional] | +| **enumQueryDouble** | **double?** | Query parameter enum test (double) | [optional] | +| **enumFormStringArray** | [**List<string>**](string.md) | Form parameter enum test (string array) | [optional] [default to $] | +| **enumFormString** | **string** | Form parameter enum test (string) | [optional] [default to -efg] | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid request | - | +| **404** | Not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestGroupParameters** +> void TestGroupParameters (int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestGroupParametersExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure Bearer token for authorization: bearer_test + config.AccessToken = "YOUR_BEARER_TOKEN"; + + var apiInstance = new FakeApi(config); + var requiredStringGroup = 56; // int | Required String in group parameters + var requiredBooleanGroup = true; // bool | Required Boolean in group parameters + var requiredInt64Group = 789L; // long | Required Integer in group parameters + var stringGroup = 56; // int? | String in group parameters (optional) + var booleanGroup = true; // bool? | Boolean in group parameters (optional) + var int64Group = 789L; // long? | Integer in group parameters (optional) + + try + { + // Fake endpoint to test group parameters (optional) + apiInstance.TestGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestGroupParameters: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestGroupParametersWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Fake endpoint to test group parameters (optional) + apiInstance.TestGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestGroupParametersWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requiredStringGroup** | **int** | Required String in group parameters | | +| **requiredBooleanGroup** | **bool** | Required Boolean in group parameters | | +| **requiredInt64Group** | **long** | Required Integer in group parameters | | +| **stringGroup** | **int?** | String in group parameters | [optional] | +| **booleanGroup** | **bool?** | Boolean in group parameters | [optional] | +| **int64Group** | **long?** | Integer in group parameters | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Someting wrong | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestInlineAdditionalProperties** +> void TestInlineAdditionalProperties (Dictionary requestBody) + +test inline additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestInlineAdditionalPropertiesExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test inline additionalProperties + apiInstance.TestInlineAdditionalProperties(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestInlineAdditionalProperties: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestInlineAdditionalPropertiesWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test inline additionalProperties + apiInstance.TestInlineAdditionalPropertiesWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestInlineAdditionalPropertiesWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, string>**](string.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestJsonFormData** +> void TestJsonFormData (string param, string param2) + +test json serialization of form data + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestJsonFormDataExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var param = "param_example"; // string | field1 + var param2 = "param2_example"; // string | field2 + + try + { + // test json serialization of form data + apiInstance.TestJsonFormData(param, param2); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestJsonFormData: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestJsonFormDataWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test json serialization of form data + apiInstance.TestJsonFormDataWithHttpInfo(param, param2); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestJsonFormDataWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **param** | **string** | field1 | | +| **param2** | **string** | field2 | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestQueryParameterCollectionFormat** +> void TestQueryParameterCollectionFormat (List pipe, List ioutil, List http, List url, List context) + + + +To test the collection format in query parameters + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestQueryParameterCollectionFormatExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var pipe = new List(); // List | + var ioutil = new List(); // List | + var http = new List(); // List | + var url = new List(); // List | + var context = new List(); // List | + + try + { + apiInstance.TestQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestQueryParameterCollectionFormat: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestQueryParameterCollectionFormatWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + apiInstance.TestQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestQueryParameterCollectionFormatWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **pipe** | [**List<string>**](string.md) | | | +| **ioutil** | [**List<string>**](string.md) | | | +| **http** | [**List<string>**](string.md) | | | +| **url** | [**List<string>**](string.md) | | | +| **context** | [**List<string>**](string.md) | | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FakeClassnameTags123Api.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FakeClassnameTags123Api.md new file mode 100644 index 0000000000..aff9fbdf0e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FakeClassnameTags123Api.md @@ -0,0 +1,104 @@ +# Org.OpenAPITools.Api.FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**TestClassname**](FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case | + + +# **TestClassname** +> ModelClient TestClassname (ModelClient modelClient) + +To test class name in snake case + +To test class name in snake case + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestClassnameExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); + + var apiInstance = new FakeClassnameTags123Api(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test class name in snake case + ModelClient result = apiInstance.TestClassname(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeClassnameTags123Api.TestClassname: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestClassnameWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // To test class name in snake case + ApiResponse response = apiInstance.TestClassnameWithHttpInfo(modelClient); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeClassnameTags123Api.TestClassnameWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **modelClient** | [**ModelClient**](ModelClient.md) | client model | | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/File.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/File.md new file mode 100644 index 0000000000..28959feda0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/File.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.File +Must be named `File` for test. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SourceURI** | **string** | Test capitalization | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FileSchemaTestClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FileSchemaTestClass.md new file mode 100644 index 0000000000..0ce4be56cc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FileSchemaTestClass.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.FileSchemaTestClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**File** | [**File**](File.md) | | [optional] +**Files** | [**List<File>**](File.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Foo.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Foo.md new file mode 100644 index 0000000000..92cf457232 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Foo.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Foo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [default to "bar"] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FooGetDefaultResponse.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FooGetDefaultResponse.md new file mode 100644 index 0000000000..dde9b9729b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FooGetDefaultResponse.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.FooGetDefaultResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**String** | [**Foo**](Foo.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FormatTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FormatTest.md new file mode 100644 index 0000000000..39a70be7ad --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FormatTest.md @@ -0,0 +1,25 @@ +# Org.OpenAPITools.Model.FormatTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Integer** | **int** | | [optional] +**Int32** | **int** | | [optional] +**Int64** | **long** | | [optional] +**Number** | **decimal** | | +**Float** | **float** | | [optional] +**Double** | **double** | | [optional] +**Decimal** | **decimal** | | [optional] +**String** | **string** | | [optional] +**Byte** | **byte[]** | | +**Binary** | **System.IO.Stream** | | [optional] +**Date** | **DateTime** | | +**DateTime** | **DateTime** | | [optional] +**Uuid** | **Guid** | | [optional] +**Password** | **string** | | +**PatternWithDigits** | **string** | A string that is a 10 digit number. Can have leading zeros. | [optional] +**PatternWithDigitsAndDelimiter** | **string** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Fruit.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Fruit.md new file mode 100644 index 0000000000..56b1c9f00a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Fruit.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.Fruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Color** | **string** | | [optional] +**Cultivar** | **string** | | [optional] +**Origin** | **string** | | [optional] +**LengthCm** | **decimal** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FruitReq.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FruitReq.md new file mode 100644 index 0000000000..5db6b0e2d1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/FruitReq.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.FruitReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Cultivar** | **string** | | +**Mealy** | **bool** | | [optional] +**LengthCm** | **decimal** | | +**Sweet** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/GmFruit.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/GmFruit.md new file mode 100644 index 0000000000..2cc2d496e6 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/GmFruit.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.GmFruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Color** | **string** | | [optional] +**Cultivar** | **string** | | [optional] +**Origin** | **string** | | [optional] +**LengthCm** | **decimal** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/GrandparentAnimal.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/GrandparentAnimal.md new file mode 100644 index 0000000000..461ebfe34c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/GrandparentAnimal.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.GrandparentAnimal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**PetType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/HasOnlyReadOnly.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/HasOnlyReadOnly.md new file mode 100644 index 0000000000..64549c18b0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.HasOnlyReadOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [readonly] +**Foo** | **string** | | [optional] [readonly] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/HealthCheckResult.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/HealthCheckResult.md new file mode 100644 index 0000000000..f7d1a7eb68 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/HealthCheckResult.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.HealthCheckResult +Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**NullableMessage** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/IsoscelesTriangle.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/IsoscelesTriangle.md new file mode 100644 index 0000000000..f0eef14fab --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/IsoscelesTriangle.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.IsoscelesTriangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/List.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/List.md new file mode 100644 index 0000000000..2862c7e532 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/List.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.List + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123List** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Mammal.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Mammal.md new file mode 100644 index 0000000000..aab8f4db9c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Mammal.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.Mammal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**HasBaleen** | **bool** | | [optional] +**HasTeeth** | **bool** | | [optional] +**ClassName** | **string** | | +**Type** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/MapTest.md new file mode 100644 index 0000000000..516f9d4fd3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/MapTest.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.MapTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] +**DirectMap** | **Dictionary<string, bool>** | | [optional] +**IndirectMap** | **Dictionary<string, bool>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 0000000000..5f57db957d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.MixedPropertiesAndAdditionalPropertiesClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Uuid** | **Guid** | | [optional] +**DateTime** | **DateTime** | | [optional] +**Map** | [**Dictionary<string, Animal>**](Animal.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Model200Response.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Model200Response.md new file mode 100644 index 0000000000..31f4d86fe4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Model200Response.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.Model200Response +Model for testing model name starting with number + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **int** | | [optional] +**Class** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ModelClient.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ModelClient.md new file mode 100644 index 0000000000..c29a628743 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ModelClient.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ModelClient + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Client** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Name.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Name.md new file mode 100644 index 0000000000..692af702b5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Name.md @@ -0,0 +1,14 @@ +# Org.OpenAPITools.Model.Name +Model for testing model name same as property name + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Name** | **int** | | +**SnakeCase** | **int** | | [optional] [readonly] +**Property** | **string** | | [optional] +**_123Number** | **int** | | [optional] [readonly] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/NullableClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/NullableClass.md new file mode 100644 index 0000000000..7bab4fa20e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/NullableClass.md @@ -0,0 +1,21 @@ +# Org.OpenAPITools.Model.NullableClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**IntegerProp** | **int?** | | [optional] +**NumberProp** | **decimal?** | | [optional] +**BooleanProp** | **bool?** | | [optional] +**StringProp** | **string** | | [optional] +**DateProp** | **DateTime?** | | [optional] +**DatetimeProp** | **DateTime?** | | [optional] +**ArrayNullableProp** | **List<Object>** | | [optional] +**ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayItemsNullable** | **List<Object>** | | [optional] +**ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] +**ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/NullableShape.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/NullableShape.md new file mode 100644 index 0000000000..f8fb004da8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/NullableShape.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.NullableShape +The value may be a shape or the 'null' value. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/NumberOnly.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/NumberOnly.md new file mode 100644 index 0000000000..14a7c0f107 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.NumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustNumber** | **decimal** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ObjectWithDeprecatedFields.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ObjectWithDeprecatedFields.md new file mode 100644 index 0000000000..7a335d446f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ObjectWithDeprecatedFields.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.ObjectWithDeprecatedFields + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Uuid** | **string** | | [optional] +**Id** | **decimal** | | [optional] +**DeprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] +**Bars** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Order.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Order.md new file mode 100644 index 0000000000..66c55c3b47 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Order.md @@ -0,0 +1,15 @@ +# Org.OpenAPITools.Model.Order + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**PetId** | **long** | | [optional] +**Quantity** | **int** | | [optional] +**ShipDate** | **DateTime** | | [optional] +**Status** | **string** | Order Status | [optional] +**Complete** | **bool** | | [optional] [default to false] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterComposite.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterComposite.md new file mode 100644 index 0000000000..eb42bcc1aa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterComposite.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.OuterComposite + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MyNumber** | **decimal** | | [optional] +**MyString** | **string** | | [optional] +**MyBoolean** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnum.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnum.md new file mode 100644 index 0000000000..245765c784 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnum.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.OuterEnum + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnumDefaultValue.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnumDefaultValue.md new file mode 100644 index 0000000000..3ffaa1086a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnumDefaultValue.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.OuterEnumDefaultValue + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnumInteger.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnumInteger.md new file mode 100644 index 0000000000..567858392d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnumInteger.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.OuterEnumInteger + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnumIntegerDefaultValue.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnumIntegerDefaultValue.md new file mode 100644 index 0000000000..35c75a4437 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/OuterEnumIntegerDefaultValue.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.OuterEnumIntegerDefaultValue + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ParentPet.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ParentPet.md new file mode 100644 index 0000000000..0e18ba6d59 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ParentPet.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ParentPet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**PetType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Pet.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Pet.md new file mode 100644 index 0000000000..c7224764e2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Pet.md @@ -0,0 +1,15 @@ +# Org.OpenAPITools.Model.Pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Category** | [**Category**](Category.md) | | [optional] +**Name** | **string** | | +**PhotoUrls** | **List<string>** | | +**Tags** | [**List<Tag>**](Tag.md) | | [optional] +**Status** | **string** | pet status in the store | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/PetApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/PetApi.md new file mode 100644 index 0000000000..1c51cb3d77 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/PetApi.md @@ -0,0 +1,856 @@ +# Org.OpenAPITools.Api.PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**AddPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store | +| [**DeletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**FindPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status | +| [**FindPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**GetPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID | +| [**UpdatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet | +| [**UpdatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image | +| [**UploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) | + + +# **AddPet** +> void AddPet (Pet pet) + +Add a new pet to the store + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class AddPetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Add a new pet to the store + apiInstance.AddPet(pet); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the AddPetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Add a new pet to the store + apiInstance.AddPetWithHttpInfo(pet); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.AddPetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | | + +### Return type + +void (empty response body) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **DeletePet** +> void DeletePet (long petId, string apiKey = null) + +Deletes a pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class DeletePetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789L; // long | Pet id to delete + var apiKey = "apiKey_example"; // string | (optional) + + try + { + // Deletes a pet + apiInstance.DeletePet(petId, apiKey); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.DeletePet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the DeletePetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Deletes a pet + apiInstance.DeletePetWithHttpInfo(petId, apiKey); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.DeletePetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **petId** | **long** | Pet id to delete | | +| **apiKey** | **string** | | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid pet value | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FindPetsByStatus** +> List<Pet> FindPetsByStatus (List status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class FindPetsByStatusExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var status = new List(); // List | Status values that need to be considered for filter + + try + { + // Finds Pets by status + List result = apiInstance.FindPetsByStatus(status); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.FindPetsByStatus: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FindPetsByStatusWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Finds Pets by status + ApiResponse> response = apiInstance.FindPetsByStatusWithHttpInfo(status); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.FindPetsByStatusWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **status** | [**List<string>**](string.md) | Status values that need to be considered for filter | | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FindPetsByTags** +> List<Pet> FindPetsByTags (List tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class FindPetsByTagsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var tags = new List(); // List | Tags to filter by + + try + { + // Finds Pets by tags + List result = apiInstance.FindPetsByTags(tags); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.FindPetsByTags: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the FindPetsByTagsWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Finds Pets by tags + ApiResponse> response = apiInstance.FindPetsByTagsWithHttpInfo(tags); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.FindPetsByTagsWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **tags** | [**List<string>**](string.md) | Tags to filter by | | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetPetById** +> Pet GetPetById (long petId) + +Find pet by ID + +Returns a single pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class GetPetByIdExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new PetApi(config); + var petId = 789L; // long | ID of pet to return + + try + { + // Find pet by ID + Pet result = apiInstance.GetPetById(petId); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.GetPetById: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetPetByIdWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Find pet by ID + ApiResponse response = apiInstance.GetPetByIdWithHttpInfo(petId); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.GetPetByIdWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **petId** | **long** | ID of pet to return | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **UpdatePet** +> void UpdatePet (Pet pet) + +Update an existing pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class UpdatePetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Update an existing pet + apiInstance.UpdatePet(pet); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UpdatePet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UpdatePetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Update an existing pet + apiInstance.UpdatePetWithHttpInfo(pet); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.UpdatePetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | | + +### Return type + +void (empty response body) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **UpdatePetWithForm** +> void UpdatePetWithForm (long petId, string name = null, string status = null) + +Updates a pet in the store with form data + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class UpdatePetWithFormExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789L; // long | ID of pet that needs to be updated + var name = "name_example"; // string | Updated name of the pet (optional) + var status = "status_example"; // string | Updated status of the pet (optional) + + try + { + // Updates a pet in the store with form data + apiInstance.UpdatePetWithForm(petId, name, status); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UpdatePetWithForm: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UpdatePetWithFormWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Updates a pet in the store with form data + apiInstance.UpdatePetWithFormWithHttpInfo(petId, name, status); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.UpdatePetWithFormWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **petId** | **long** | ID of pet that needs to be updated | | +| **name** | **string** | Updated name of the pet | [optional] | +| **status** | **string** | Updated status of the pet | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **UploadFile** +> ApiResponse UploadFile (long petId, string additionalMetadata = null, System.IO.Stream file = null) + +uploads an image + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class UploadFileExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789L; // long | ID of pet to update + var additionalMetadata = "additionalMetadata_example"; // string | Additional data to pass to server (optional) + var file = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | file to upload (optional) + + try + { + // uploads an image + ApiResponse result = apiInstance.UploadFile(petId, additionalMetadata, file); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UploadFile: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UploadFileWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // uploads an image + ApiResponse response = apiInstance.UploadFileWithHttpInfo(petId, additionalMetadata, file); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.UploadFileWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **petId** | **long** | ID of pet to update | | +| **additionalMetadata** | **string** | Additional data to pass to server | [optional] | +| **file** | **System.IO.Stream****System.IO.Stream** | file to upload | [optional] | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **UploadFileWithRequiredFile** +> ApiResponse UploadFileWithRequiredFile (long petId, System.IO.Stream requiredFile, string additionalMetadata = null) + +uploads an image (required) + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class UploadFileWithRequiredFileExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789L; // long | ID of pet to update + var requiredFile = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | file to upload + var additionalMetadata = "additionalMetadata_example"; // string | Additional data to pass to server (optional) + + try + { + // uploads an image (required) + ApiResponse result = apiInstance.UploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UploadFileWithRequiredFile: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UploadFileWithRequiredFileWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // uploads an image (required) + ApiResponse response = apiInstance.UploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling PetApi.UploadFileWithRequiredFileWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **petId** | **long** | ID of pet to update | | +| **requiredFile** | **System.IO.Stream****System.IO.Stream** | file to upload | | +| **additionalMetadata** | **string** | Additional data to pass to server | [optional] | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Pig.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Pig.md new file mode 100644 index 0000000000..6e86d0760d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Pig.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Pig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/PolymorphicProperty.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/PolymorphicProperty.md new file mode 100644 index 0000000000..8262a41c50 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/PolymorphicProperty.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.PolymorphicProperty + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Quadrilateral.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Quadrilateral.md new file mode 100644 index 0000000000..0165ddcc0e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Quadrilateral.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Quadrilateral + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/QuadrilateralInterface.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/QuadrilateralInterface.md new file mode 100644 index 0000000000..6daf340a14 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/QuadrilateralInterface.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.QuadrilateralInterface + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**QuadrilateralType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ReadOnlyFirst.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ReadOnlyFirst.md new file mode 100644 index 0000000000..b3f4a17ea3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ReadOnlyFirst + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [readonly] +**Baz** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Return.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Return.md new file mode 100644 index 0000000000..2c7c97e09d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Return.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Return +Model for testing reserved words + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Return** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ScaleneTriangle.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ScaleneTriangle.md new file mode 100644 index 0000000000..76da8f1de8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ScaleneTriangle.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ScaleneTriangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Shape.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Shape.md new file mode 100644 index 0000000000..9a54628cd4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Shape.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Shape + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ShapeInterface.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ShapeInterface.md new file mode 100644 index 0000000000..57456d6793 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ShapeInterface.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ShapeInterface + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ShapeOrNull.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ShapeOrNull.md new file mode 100644 index 0000000000..cbf61ebe77 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/ShapeOrNull.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.ShapeOrNull +The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/SimpleQuadrilateral.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/SimpleQuadrilateral.md new file mode 100644 index 0000000000..c329495425 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/SimpleQuadrilateral.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.SimpleQuadrilateral + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/SpecialModelName.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/SpecialModelName.md new file mode 100644 index 0000000000..648179799e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/SpecialModelName.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.SpecialModelName + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SpecialPropertyName** | **long** | | [optional] +**_SpecialModelName** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/StoreApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/StoreApi.md new file mode 100644 index 0000000000..95bbe1b2f1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/StoreApi.md @@ -0,0 +1,373 @@ +# Org.OpenAPITools.Api.StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID | +| [**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status | +| [**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID | +| [**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet | + + +# **DeleteOrder** +> void DeleteOrder (string orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class DeleteOrderExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new StoreApi(config); + var orderId = "orderId_example"; // string | ID of the order that needs to be deleted + + try + { + // Delete purchase order by ID + apiInstance.DeleteOrder(orderId); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.DeleteOrder: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the DeleteOrderWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Delete purchase order by ID + apiInstance.DeleteOrderWithHttpInfo(orderId); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling StoreApi.DeleteOrderWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **orderId** | **string** | ID of the order that needs to be deleted | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetInventory** +> Dictionary<string, int> GetInventory () + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class GetInventoryExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new StoreApi(config); + + try + { + // Returns pet inventories by status + Dictionary result = apiInstance.GetInventory(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.GetInventory: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetInventoryWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Returns pet inventories by status + ApiResponse> response = apiInstance.GetInventoryWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling StoreApi.GetInventoryWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +**Dictionary** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetOrderById** +> Order GetOrderById (long orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class GetOrderByIdExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new StoreApi(config); + var orderId = 789L; // long | ID of pet that needs to be fetched + + try + { + // Find purchase order by ID + Order result = apiInstance.GetOrderById(orderId); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.GetOrderById: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetOrderByIdWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Find purchase order by ID + ApiResponse response = apiInstance.GetOrderByIdWithHttpInfo(orderId); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling StoreApi.GetOrderByIdWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **orderId** | **long** | ID of pet that needs to be fetched | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **PlaceOrder** +> Order PlaceOrder (Order order) + +Place an order for a pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class PlaceOrderExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new StoreApi(config); + var order = new Order(); // Order | order placed for purchasing the pet + + try + { + // Place an order for a pet + Order result = apiInstance.PlaceOrder(order); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.PlaceOrder: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the PlaceOrderWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Place an order for a pet + ApiResponse response = apiInstance.PlaceOrderWithHttpInfo(order); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling StoreApi.PlaceOrderWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **order** | [**Order**](Order.md) | order placed for purchasing the pet | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Tag.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Tag.md new file mode 100644 index 0000000000..fdd22eb31f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Tag.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Tag + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Name** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Triangle.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Triangle.md new file mode 100644 index 0000000000..c4d0452b4e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Triangle.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Triangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/TriangleInterface.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/TriangleInterface.md new file mode 100644 index 0000000000..e0d8b5a591 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/TriangleInterface.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.TriangleInterface + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**TriangleType** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/User.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/User.md new file mode 100644 index 0000000000..b0cd4dc042 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/User.md @@ -0,0 +1,21 @@ +# Org.OpenAPITools.Model.User + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Username** | **string** | | [optional] +**FirstName** | **string** | | [optional] +**LastName** | **string** | | [optional] +**Email** | **string** | | [optional] +**Password** | **string** | | [optional] +**Phone** | **string** | | [optional] +**UserStatus** | **int** | User Status | [optional] +**ObjectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] +**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] +**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] +**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/UserApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/UserApi.md new file mode 100644 index 0000000000..a3d461b04c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/UserApi.md @@ -0,0 +1,713 @@ +# Org.OpenAPITools.Api.UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**CreateUser**](UserApi.md#createuser) | **POST** /user | Create user | +| [**CreateUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array | +| [**CreateUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array | +| [**DeleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user | +| [**GetUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name | +| [**LoginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system | +| [**LogoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session | +| [**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user | + + +# **CreateUser** +> void CreateUser (User user) + +Create user + +This can only be done by the logged in user. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class CreateUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new User(); // User | Created user object + + try + { + // Create user + apiInstance.CreateUser(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the CreateUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Create user + apiInstance.CreateUserWithHttpInfo(user); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.CreateUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **user** | [**User**](User.md) | Created user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **CreateUsersWithArrayInput** +> void CreateUsersWithArrayInput (List user) + +Creates list of users with given input array + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class CreateUsersWithArrayInputExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithArrayInput(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInput: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the CreateUsersWithArrayInputWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Creates list of users with given input array + apiInstance.CreateUsersWithArrayInputWithHttpInfo(user); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInputWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **user** | [**List<User>**](User.md) | List of user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **CreateUsersWithListInput** +> void CreateUsersWithListInput (List user) + +Creates list of users with given input array + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class CreateUsersWithListInputExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithListInput(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithListInput: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the CreateUsersWithListInputWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Creates list of users with given input array + apiInstance.CreateUsersWithListInputWithHttpInfo(user); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.CreateUsersWithListInputWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **user** | [**List<User>**](User.md) | List of user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **DeleteUser** +> void DeleteUser (string username) + +Delete user + +This can only be done by the logged in user. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class DeleteUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = "username_example"; // string | The name that needs to be deleted + + try + { + // Delete user + apiInstance.DeleteUser(username); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.DeleteUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the DeleteUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Delete user + apiInstance.DeleteUserWithHttpInfo(username); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.DeleteUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **username** | **string** | The name that needs to be deleted | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetUserByName** +> User GetUserByName (string username) + +Get user by user name + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class GetUserByNameExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = "username_example"; // string | The name that needs to be fetched. Use user1 for testing. + + try + { + // Get user by user name + User result = apiInstance.GetUserByName(username); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.GetUserByName: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the GetUserByNameWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Get user by user name + ApiResponse response = apiInstance.GetUserByNameWithHttpInfo(username); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.GetUserByNameWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **username** | **string** | The name that needs to be fetched. Use user1 for testing. | | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **LoginUser** +> string LoginUser (string username, string password) + +Logs user into the system + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class LoginUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = "username_example"; // string | The user name for login + var password = "password_example"; // string | The password for login in clear text + + try + { + // Logs user into the system + string result = apiInstance.LoginUser(username, password); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.LoginUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the LoginUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Logs user into the system + ApiResponse response = apiInstance.LoginUserWithHttpInfo(username, password); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.LoginUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **username** | **string** | The user name for login | | +| **password** | **string** | The password for login in clear text | | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
        * X-Expires-After - date in UTC when token expires
        | +| **400** | Invalid username/password supplied | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **LogoutUser** +> void LogoutUser () + +Logs out current logged in user session + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class LogoutUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + + try + { + // Logs out current logged in user session + apiInstance.LogoutUser(); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.LogoutUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the LogoutUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Logs out current logged in user session + apiInstance.LogoutUserWithHttpInfo(); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.LogoutUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **UpdateUser** +> void UpdateUser (string username, User user) + +Updated user + +This can only be done by the logged in user. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class UpdateUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = "username_example"; // string | name that need to be deleted + var user = new User(); // User | Updated user object + + try + { + // Updated user + apiInstance.UpdateUser(username, user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.UpdateUser: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the UpdateUserWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Updated user + apiInstance.UpdateUserWithHttpInfo(username, user); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling UserApi.UpdateUserWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **username** | **string** | name that need to be deleted | | +| **user** | [**User**](User.md) | Updated user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Whale.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Whale.md new file mode 100644 index 0000000000..5fc3dc7f85 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Whale.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.Whale + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**HasBaleen** | **bool** | | [optional] +**HasTeeth** | **bool** | | [optional] +**ClassName** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Zebra.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Zebra.md new file mode 100644 index 0000000000..31e686adf0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/docs/Zebra.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Zebra + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Type** | **string** | | [optional] +**ClassName** | **string** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/git_push.sh b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs new file mode 100644 index 0000000000..1d46982928 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using Xunit; + +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; +// uncomment below to import models +//using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing AnotherFakeApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class AnotherFakeApiTests : IDisposable + { + private AnotherFakeApi instance; + + public AnotherFakeApiTests() + { + instance = new AnotherFakeApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AnotherFakeApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' AnotherFakeApi + //Assert.IsType(instance); + } + + /// + /// Test Call123TestSpecialTags + /// + [Fact] + public void Call123TestSpecialTagsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //ModelClient modelClient = null; + //var response = instance.Call123TestSpecialTags(modelClient); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs new file mode 100644 index 0000000000..5d048a005b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -0,0 +1,68 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using Xunit; + +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; +// uncomment below to import models +//using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing DefaultApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class DefaultApiTests : IDisposable + { + private DefaultApi instance; + + public DefaultApiTests() + { + instance = new DefaultApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DefaultApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' DefaultApi + //Assert.IsType(instance); + } + + /// + /// Test FooGet + /// + [Fact] + public void FooGetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.FooGet(); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs new file mode 100644 index 0000000000..994cd46d38 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -0,0 +1,258 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using Xunit; + +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; +// uncomment below to import models +//using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing FakeApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class FakeApiTests : IDisposable + { + private FakeApi instance; + + public FakeApiTests() + { + instance = new FakeApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FakeApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' FakeApi + //Assert.IsType(instance); + } + + /// + /// Test FakeHealthGet + /// + [Fact] + public void FakeHealthGetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.FakeHealthGet(); + //Assert.IsType(response); + } + + /// + /// Test FakeOuterBooleanSerialize + /// + [Fact] + public void FakeOuterBooleanSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //bool? body = null; + //var response = instance.FakeOuterBooleanSerialize(body); + //Assert.IsType(response); + } + + /// + /// Test FakeOuterCompositeSerialize + /// + [Fact] + public void FakeOuterCompositeSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //OuterComposite outerComposite = null; + //var response = instance.FakeOuterCompositeSerialize(outerComposite); + //Assert.IsType(response); + } + + /// + /// Test FakeOuterNumberSerialize + /// + [Fact] + public void FakeOuterNumberSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //decimal? body = null; + //var response = instance.FakeOuterNumberSerialize(body); + //Assert.IsType(response); + } + + /// + /// Test FakeOuterStringSerialize + /// + [Fact] + public void FakeOuterStringSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string body = null; + //var response = instance.FakeOuterStringSerialize(body); + //Assert.IsType(response); + } + + /// + /// Test GetArrayOfEnums + /// + [Fact] + public void GetArrayOfEnumsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.GetArrayOfEnums(); + //Assert.IsType>(response); + } + + /// + /// Test TestBodyWithFileSchema + /// + [Fact] + public void TestBodyWithFileSchemaTest() + { + // TODO uncomment below to test the method and replace null with proper value + //FileSchemaTestClass fileSchemaTestClass = null; + //instance.TestBodyWithFileSchema(fileSchemaTestClass); + } + + /// + /// Test TestBodyWithQueryParams + /// + [Fact] + public void TestBodyWithQueryParamsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string query = null; + //User user = null; + //instance.TestBodyWithQueryParams(query, user); + } + + /// + /// Test TestClientModel + /// + [Fact] + public void TestClientModelTest() + { + // TODO uncomment below to test the method and replace null with proper value + //ModelClient modelClient = null; + //var response = instance.TestClientModel(modelClient); + //Assert.IsType(response); + } + + /// + /// Test TestEndpointParameters + /// + [Fact] + public void TestEndpointParametersTest() + { + // TODO uncomment below to test the method and replace null with proper value + //decimal number = null; + //double _double = null; + //string patternWithoutDelimiter = null; + //byte[] _byte = null; + //int? integer = null; + //int? int32 = null; + //long? int64 = null; + //float? _float = null; + //string _string = null; + //System.IO.Stream binary = null; + //DateTime? date = null; + //DateTime? dateTime = null; + //string password = null; + //string callback = null; + //instance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); + } + + /// + /// Test TestEnumParameters + /// + [Fact] + public void TestEnumParametersTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List enumHeaderStringArray = null; + //string enumHeaderString = null; + //List enumQueryStringArray = null; + //string enumQueryString = null; + //int? enumQueryInteger = null; + //double? enumQueryDouble = null; + //List enumFormStringArray = null; + //string enumFormString = null; + //instance.TestEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } + + /// + /// Test TestGroupParameters + /// + [Fact] + public void TestGroupParametersTest() + { + // TODO uncomment below to test the method and replace null with proper value + //int requiredStringGroup = null; + //bool requiredBooleanGroup = null; + //long requiredInt64Group = null; + //int? stringGroup = null; + //bool? booleanGroup = null; + //long? int64Group = null; + //instance.TestGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /// + /// Test TestInlineAdditionalProperties + /// + [Fact] + public void TestInlineAdditionalPropertiesTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Dictionary requestBody = null; + //instance.TestInlineAdditionalProperties(requestBody); + } + + /// + /// Test TestJsonFormData + /// + [Fact] + public void TestJsonFormDataTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string param = null; + //string param2 = null; + //instance.TestJsonFormData(param, param2); + } + + /// + /// Test TestQueryParameterCollectionFormat + /// + [Fact] + public void TestQueryParameterCollectionFormatTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List pipe = null; + //List ioutil = null; + //List http = null; + //List url = null; + //List context = null; + //instance.TestQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs new file mode 100644 index 0000000000..bbfd4a586e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using Xunit; + +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; +// uncomment below to import models +//using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing FakeClassnameTags123Api + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class FakeClassnameTags123ApiTests : IDisposable + { + private FakeClassnameTags123Api instance; + + public FakeClassnameTags123ApiTests() + { + instance = new FakeClassnameTags123Api(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FakeClassnameTags123Api + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' FakeClassnameTags123Api + //Assert.IsType(instance); + } + + /// + /// Test TestClassname + /// + [Fact] + public void TestClassnameTest() + { + // TODO uncomment below to test the method and replace null with proper value + //ModelClient modelClient = null; + //var response = instance.TestClassname(modelClient); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/PetApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/PetApiTests.cs similarity index 83% rename from samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/PetApiTests.cs rename to samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/PetApiTests.cs index 9ee31e31c3..6738676414 100644 --- a/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/PetApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/PetApiTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -17,9 +17,9 @@ using RestSharp; using Xunit; using Org.OpenAPITools.Client; -using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Api; // uncomment below to import models -//using Org.OpenAPITools.Models; +//using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Test.Api { @@ -62,8 +62,7 @@ namespace Org.OpenAPITools.Test.Api { // TODO uncomment below to test the method and replace null with proper value //Pet pet = null; - //var response = instance.AddPet(pet); - //Assert.IsType(response); + //instance.AddPet(pet); } /// @@ -122,8 +121,7 @@ namespace Org.OpenAPITools.Test.Api { // TODO uncomment below to test the method and replace null with proper value //Pet pet = null; - //var response = instance.UpdatePet(pet); - //Assert.IsType(response); + //instance.UpdatePet(pet); } /// @@ -152,5 +150,19 @@ namespace Org.OpenAPITools.Test.Api //var response = instance.UploadFile(petId, additionalMetadata, file); //Assert.IsType(response); } + + /// + /// Test UploadFileWithRequiredFile + /// + [Fact] + public void UploadFileWithRequiredFileTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //System.IO.Stream requiredFile = null; + //string additionalMetadata = null; + //var response = instance.UploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + //Assert.IsType(response); + } } } diff --git a/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/StoreApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs similarity index 92% rename from samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/StoreApiTests.cs rename to samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs index 59206b2a76..48e9f32748 100644 --- a/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/StoreApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -17,9 +17,9 @@ using RestSharp; using Xunit; using Org.OpenAPITools.Client; -using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Api; // uncomment below to import models -//using Org.OpenAPITools.Models; +//using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Test.Api { diff --git a/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/UserApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/UserApiTests.cs similarity index 94% rename from samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/UserApiTests.cs rename to samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/UserApiTests.cs index 031e222ca0..792db5819a 100644 --- a/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/UserApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Api/UserApiTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -17,9 +17,9 @@ using RestSharp; using Xunit; using Org.OpenAPITools.Client; -using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Api; // uncomment below to import models -//using Org.OpenAPITools.Models; +//using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Test.Api { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs new file mode 100644 index 0000000000..9ab029ed09 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -0,0 +1,126 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing AdditionalPropertiesClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AdditionalPropertiesClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for AdditionalPropertiesClass + //private AdditionalPropertiesClass instance; + + public AdditionalPropertiesClassTests() + { + // TODO uncomment below to create an instance of AdditionalPropertiesClass + //instance = new AdditionalPropertiesClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AdditionalPropertiesClass + /// + [Fact] + public void AdditionalPropertiesClassInstanceTest() + { + // TODO uncomment below to test "IsType" AdditionalPropertiesClass + //Assert.IsType(instance); + } + + + /// + /// Test the property 'MapProperty' + /// + [Fact] + public void MapPropertyTest() + { + // TODO unit test for the property 'MapProperty' + } + /// + /// Test the property 'MapOfMapProperty' + /// + [Fact] + public void MapOfMapPropertyTest() + { + // TODO unit test for the property 'MapOfMapProperty' + } + /// + /// Test the property 'Anytype1' + /// + [Fact] + public void Anytype1Test() + { + // TODO unit test for the property 'Anytype1' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype1' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype1Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype1' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype2' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype2Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype2' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype3' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype3Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3' + } + /// + /// Test the property 'EmptyMap' + /// + [Fact] + public void EmptyMapTest() + { + // TODO unit test for the property 'EmptyMap' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesString' + /// + [Fact] + public void MapWithUndeclaredPropertiesStringTest() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesString' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AnimalTests.cs new file mode 100644 index 0000000000..ced34a4faa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -0,0 +1,96 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Animal + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AnimalTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Animal + //private Animal instance; + + public AnimalTests() + { + // TODO uncomment below to create an instance of Animal + //instance = new Animal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Animal + /// + [Fact] + public void AnimalInstanceTest() + { + // TODO uncomment below to test "IsType" Animal + //Assert.IsType(instance); + } + + /// + /// Test deserialize a Cat from type Animal + /// + [Fact] + public void CatDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Cat from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); + } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/ApiResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs similarity index 90% rename from samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/ApiResponseTests.cs rename to samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs index 8a290fd090..2a2e098e60 100644 --- a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/ApiResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -14,8 +14,8 @@ using System; using System.Linq; using System.IO; using System.Collections.Generic; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Models; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs new file mode 100644 index 0000000000..f945f65936 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing AppleReq + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AppleReqTests : IDisposable + { + // TODO uncomment below to declare an instance variable for AppleReq + //private AppleReq instance; + + public AppleReqTests() + { + // TODO uncomment below to create an instance of AppleReq + //instance = new AppleReq(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AppleReq + /// + [Fact] + public void AppleReqInstanceTest() + { + // TODO uncomment below to test "IsType" AppleReq + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Mealy' + /// + [Fact] + public void MealyTest() + { + // TODO unit test for the property 'Mealy' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AppleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AppleTests.cs new file mode 100644 index 0000000000..468d60184a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/AppleTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Apple + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AppleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Apple + //private Apple instance; + + public AppleTests() + { + // TODO uncomment below to create an instance of Apple + //instance = new Apple(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Apple + /// + [Fact] + public void AppleInstanceTest() + { + // TODO uncomment below to test "IsType" Apple + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Origin' + /// + [Fact] + public void OriginTest() + { + // TODO unit test for the property 'Origin' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs new file mode 100644 index 0000000000..0b259d7d39 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ArrayOfArrayOfNumberOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ArrayOfArrayOfNumberOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ArrayOfArrayOfNumberOnly + //private ArrayOfArrayOfNumberOnly instance; + + public ArrayOfArrayOfNumberOnlyTests() + { + // TODO uncomment below to create an instance of ArrayOfArrayOfNumberOnly + //instance = new ArrayOfArrayOfNumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ArrayOfArrayOfNumberOnly + /// + [Fact] + public void ArrayOfArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" ArrayOfArrayOfNumberOnly + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ArrayArrayNumber' + /// + [Fact] + public void ArrayArrayNumberTest() + { + // TODO unit test for the property 'ArrayArrayNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs new file mode 100644 index 0000000000..27f312ad25 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ArrayOfNumberOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ArrayOfNumberOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ArrayOfNumberOnly + //private ArrayOfNumberOnly instance; + + public ArrayOfNumberOnlyTests() + { + // TODO uncomment below to create an instance of ArrayOfNumberOnly + //instance = new ArrayOfNumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ArrayOfNumberOnly + /// + [Fact] + public void ArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" ArrayOfNumberOnly + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ArrayNumber' + /// + [Fact] + public void ArrayNumberTest() + { + // TODO unit test for the property 'ArrayNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs new file mode 100644 index 0000000000..a433e8c87c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs @@ -0,0 +1,86 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ArrayTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ArrayTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ArrayTest + //private ArrayTest instance; + + public ArrayTestTests() + { + // TODO uncomment below to create an instance of ArrayTest + //instance = new ArrayTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ArrayTest + /// + [Fact] + public void ArrayTestInstanceTest() + { + // TODO uncomment below to test "IsType" ArrayTest + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ArrayOfString' + /// + [Fact] + public void ArrayOfStringTest() + { + // TODO unit test for the property 'ArrayOfString' + } + /// + /// Test the property 'ArrayArrayOfInteger' + /// + [Fact] + public void ArrayArrayOfIntegerTest() + { + // TODO unit test for the property 'ArrayArrayOfInteger' + } + /// + /// Test the property 'ArrayArrayOfModel' + /// + [Fact] + public void ArrayArrayOfModelTest() + { + // TODO unit test for the property 'ArrayArrayOfModel' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs new file mode 100644 index 0000000000..8a6eeb82ee --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing BananaReq + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BananaReqTests : IDisposable + { + // TODO uncomment below to declare an instance variable for BananaReq + //private BananaReq instance; + + public BananaReqTests() + { + // TODO uncomment below to create an instance of BananaReq + //instance = new BananaReq(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of BananaReq + /// + [Fact] + public void BananaReqInstanceTest() + { + // TODO uncomment below to test "IsType" BananaReq + //Assert.IsType(instance); + } + + + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + /// + /// Test the property 'Sweet' + /// + [Fact] + public void SweetTest() + { + // TODO unit test for the property 'Sweet' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/BananaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/BananaTests.cs new file mode 100644 index 0000000000..8d8cc376b0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/BananaTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Banana + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BananaTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Banana + //private Banana instance; + + public BananaTests() + { + // TODO uncomment below to create an instance of Banana + //instance = new Banana(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Banana + /// + [Fact] + public void BananaInstanceTest() + { + // TODO uncomment below to test "IsType" Banana + //Assert.IsType(instance); + } + + + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs new file mode 100644 index 0000000000..3cdccaa759 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing BasquePig + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BasquePigTests : IDisposable + { + // TODO uncomment below to declare an instance variable for BasquePig + //private BasquePig instance; + + public BasquePigTests() + { + // TODO uncomment below to create an instance of BasquePig + //instance = new BasquePig(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of BasquePig + /// + [Fact] + public void BasquePigInstanceTest() + { + // TODO uncomment below to test "IsType" BasquePig + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs new file mode 100644 index 0000000000..185c83666f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs @@ -0,0 +1,110 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Capitalization + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CapitalizationTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Capitalization + //private Capitalization instance; + + public CapitalizationTests() + { + // TODO uncomment below to create an instance of Capitalization + //instance = new Capitalization(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Capitalization + /// + [Fact] + public void CapitalizationInstanceTest() + { + // TODO uncomment below to test "IsType" Capitalization + //Assert.IsType(instance); + } + + + /// + /// Test the property 'SmallCamel' + /// + [Fact] + public void SmallCamelTest() + { + // TODO unit test for the property 'SmallCamel' + } + /// + /// Test the property 'CapitalCamel' + /// + [Fact] + public void CapitalCamelTest() + { + // TODO unit test for the property 'CapitalCamel' + } + /// + /// Test the property 'SmallSnake' + /// + [Fact] + public void SmallSnakeTest() + { + // TODO unit test for the property 'SmallSnake' + } + /// + /// Test the property 'CapitalSnake' + /// + [Fact] + public void CapitalSnakeTest() + { + // TODO unit test for the property 'CapitalSnake' + } + /// + /// Test the property 'SCAETHFlowPoints' + /// + [Fact] + public void SCAETHFlowPointsTest() + { + // TODO unit test for the property 'SCAETHFlowPoints' + } + /// + /// Test the property 'ATT_NAME' + /// + [Fact] + public void ATT_NAMETest() + { + // TODO unit test for the property 'ATT_NAME' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs new file mode 100644 index 0000000000..fb51c28489 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing CatAllOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CatAllOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for CatAllOf + //private CatAllOf instance; + + public CatAllOfTests() + { + // TODO uncomment below to create an instance of CatAllOf + //instance = new CatAllOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of CatAllOf + /// + [Fact] + public void CatAllOfInstanceTest() + { + // TODO uncomment below to test "IsType" CatAllOf + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Declawed' + /// + [Fact] + public void DeclawedTest() + { + // TODO unit test for the property 'Declawed' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CatTests.cs new file mode 100644 index 0000000000..701ba76028 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CatTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Cat + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CatTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Cat + //private Cat instance; + + public CatTests() + { + // TODO uncomment below to create an instance of Cat + //instance = new Cat(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Cat + /// + [Fact] + public void CatInstanceTest() + { + // TODO uncomment below to test "IsType" Cat + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Declawed' + /// + [Fact] + public void DeclawedTest() + { + // TODO unit test for the property 'Declawed' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/CategoryTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CategoryTests.cs similarity index 88% rename from samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/CategoryTests.cs rename to samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CategoryTests.cs index dd395f7d67..6ce48e601e 100644 --- a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/CategoryTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/CategoryTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -14,8 +14,8 @@ using System; using System.Linq; using System.IO; using System.Collections.Generic; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Models; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs new file mode 100644 index 0000000000..49a5393249 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ChildCatAllOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ChildCatAllOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ChildCatAllOf + //private ChildCatAllOf instance; + + public ChildCatAllOfTests() + { + // TODO uncomment below to create an instance of ChildCatAllOf + //instance = new ChildCatAllOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ChildCatAllOf + /// + [Fact] + public void ChildCatAllOfInstanceTest() + { + // TODO uncomment below to test "IsType" ChildCatAllOf + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs new file mode 100644 index 0000000000..68566fd8d5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ChildCat + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ChildCatTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ChildCat + //private ChildCat instance; + + public ChildCatTests() + { + // TODO uncomment below to create an instance of ChildCat + //instance = new ChildCat(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ChildCat + /// + [Fact] + public void ChildCatInstanceTest() + { + // TODO uncomment below to test "IsType" ChildCat + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs new file mode 100644 index 0000000000..d29472e83a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ClassModel + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ClassModelTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ClassModel + //private ClassModel instance; + + public ClassModelTests() + { + // TODO uncomment below to create an instance of ClassModel + //instance = new ClassModel(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ClassModel + /// + [Fact] + public void ClassModelInstanceTest() + { + // TODO uncomment below to test "IsType" ClassModel + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Class' + /// + [Fact] + public void ClassTest() + { + // TODO unit test for the property 'Class' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs new file mode 100644 index 0000000000..b3529280c8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ComplexQuadrilateral + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ComplexQuadrilateralTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ComplexQuadrilateral + //private ComplexQuadrilateral instance; + + public ComplexQuadrilateralTests() + { + // TODO uncomment below to create an instance of ComplexQuadrilateral + //instance = new ComplexQuadrilateral(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ComplexQuadrilateral + /// + [Fact] + public void ComplexQuadrilateralInstanceTest() + { + // TODO uncomment below to test "IsType" ComplexQuadrilateral + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs new file mode 100644 index 0000000000..572d9bffa7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing DanishPig + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DanishPigTests : IDisposable + { + // TODO uncomment below to declare an instance variable for DanishPig + //private DanishPig instance; + + public DanishPigTests() + { + // TODO uncomment below to create an instance of DanishPig + //instance = new DanishPig(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DanishPig + /// + [Fact] + public void DanishPigInstanceTest() + { + // TODO uncomment below to test "IsType" DanishPig + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs new file mode 100644 index 0000000000..1da5f4011c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DeprecatedObjectTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing DeprecatedObject + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DeprecatedObjectTests : IDisposable + { + // TODO uncomment below to declare an instance variable for DeprecatedObject + //private DeprecatedObject instance; + + public DeprecatedObjectTests() + { + // TODO uncomment below to create an instance of DeprecatedObject + //instance = new DeprecatedObject(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DeprecatedObject + /// + [Fact] + public void DeprecatedObjectInstanceTest() + { + // TODO uncomment below to test "IsType" DeprecatedObject + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs new file mode 100644 index 0000000000..b22a444209 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing DogAllOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DogAllOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for DogAllOf + //private DogAllOf instance; + + public DogAllOfTests() + { + // TODO uncomment below to create an instance of DogAllOf + //instance = new DogAllOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DogAllOf + /// + [Fact] + public void DogAllOfInstanceTest() + { + // TODO uncomment below to test "IsType" DogAllOf + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Breed' + /// + [Fact] + public void BreedTest() + { + // TODO unit test for the property 'Breed' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DogTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DogTests.cs new file mode 100644 index 0000000000..992f93a51f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DogTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Dog + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DogTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Dog + //private Dog instance; + + public DogTests() + { + // TODO uncomment below to create an instance of Dog + //instance = new Dog(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Dog + /// + [Fact] + public void DogInstanceTest() + { + // TODO uncomment below to test "IsType" Dog + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Breed' + /// + [Fact] + public void BreedTest() + { + // TODO unit test for the property 'Breed' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DrawingTests.cs new file mode 100644 index 0000000000..0709ad9eeb --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -0,0 +1,94 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Drawing + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DrawingTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Drawing + //private Drawing instance; + + public DrawingTests() + { + // TODO uncomment below to create an instance of Drawing + //instance = new Drawing(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Drawing + /// + [Fact] + public void DrawingInstanceTest() + { + // TODO uncomment below to test "IsType" Drawing + //Assert.IsType(instance); + } + + + /// + /// Test the property 'MainShape' + /// + [Fact] + public void MainShapeTest() + { + // TODO unit test for the property 'MainShape' + } + /// + /// Test the property 'ShapeOrNull' + /// + [Fact] + public void ShapeOrNullTest() + { + // TODO unit test for the property 'ShapeOrNull' + } + /// + /// Test the property 'NullableShape' + /// + [Fact] + public void NullableShapeTest() + { + // TODO unit test for the property 'NullableShape' + } + /// + /// Test the property 'Shapes' + /// + [Fact] + public void ShapesTest() + { + // TODO unit test for the property 'Shapes' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs new file mode 100644 index 0000000000..5779ca2947 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing EnumArrays + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnumArraysTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EnumArrays + //private EnumArrays instance; + + public EnumArraysTests() + { + // TODO uncomment below to create an instance of EnumArrays + //instance = new EnumArrays(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EnumArrays + /// + [Fact] + public void EnumArraysInstanceTest() + { + // TODO uncomment below to test "IsType" EnumArrays + //Assert.IsType(instance); + } + + + /// + /// Test the property 'JustSymbol' + /// + [Fact] + public void JustSymbolTest() + { + // TODO unit test for the property 'JustSymbol' + } + /// + /// Test the property 'ArrayEnum' + /// + [Fact] + public void ArrayEnumTest() + { + // TODO unit test for the property 'ArrayEnum' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs new file mode 100644 index 0000000000..a17738c5cb --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs @@ -0,0 +1,62 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing EnumClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnumClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EnumClass + //private EnumClass instance; + + public EnumClassTests() + { + // TODO uncomment below to create an instance of EnumClass + //instance = new EnumClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EnumClass + /// + [Fact] + public void EnumClassInstanceTest() + { + // TODO uncomment below to test "IsType" EnumClass + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs new file mode 100644 index 0000000000..4f81b845d4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -0,0 +1,134 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing EnumTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnumTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EnumTest + //private EnumTest instance; + + public EnumTestTests() + { + // TODO uncomment below to create an instance of EnumTest + //instance = new EnumTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EnumTest + /// + [Fact] + public void EnumTestInstanceTest() + { + // TODO uncomment below to test "IsType" EnumTest + //Assert.IsType(instance); + } + + + /// + /// Test the property 'EnumString' + /// + [Fact] + public void EnumStringTest() + { + // TODO unit test for the property 'EnumString' + } + /// + /// Test the property 'EnumStringRequired' + /// + [Fact] + public void EnumStringRequiredTest() + { + // TODO unit test for the property 'EnumStringRequired' + } + /// + /// Test the property 'EnumInteger' + /// + [Fact] + public void EnumIntegerTest() + { + // TODO unit test for the property 'EnumInteger' + } + /// + /// Test the property 'EnumIntegerOnly' + /// + [Fact] + public void EnumIntegerOnlyTest() + { + // TODO unit test for the property 'EnumIntegerOnly' + } + /// + /// Test the property 'EnumNumber' + /// + [Fact] + public void EnumNumberTest() + { + // TODO unit test for the property 'EnumNumber' + } + /// + /// Test the property 'OuterEnum' + /// + [Fact] + public void OuterEnumTest() + { + // TODO unit test for the property 'OuterEnum' + } + /// + /// Test the property 'OuterEnumInteger' + /// + [Fact] + public void OuterEnumIntegerTest() + { + // TODO unit test for the property 'OuterEnumInteger' + } + /// + /// Test the property 'OuterEnumDefaultValue' + /// + [Fact] + public void OuterEnumDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumDefaultValue' + } + /// + /// Test the property 'OuterEnumIntegerDefaultValue' + /// + [Fact] + public void OuterEnumIntegerDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumIntegerDefaultValue' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs new file mode 100644 index 0000000000..4663cb667d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing EquilateralTriangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EquilateralTriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EquilateralTriangle + //private EquilateralTriangle instance; + + public EquilateralTriangleTests() + { + // TODO uncomment below to create an instance of EquilateralTriangle + //instance = new EquilateralTriangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EquilateralTriangle + /// + [Fact] + public void EquilateralTriangleInstanceTest() + { + // TODO uncomment below to test "IsType" EquilateralTriangle + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs new file mode 100644 index 0000000000..9f45b4fe89 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing FileSchemaTestClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FileSchemaTestClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FileSchemaTestClass + //private FileSchemaTestClass instance; + + public FileSchemaTestClassTests() + { + // TODO uncomment below to create an instance of FileSchemaTestClass + //instance = new FileSchemaTestClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FileSchemaTestClass + /// + [Fact] + public void FileSchemaTestClassInstanceTest() + { + // TODO uncomment below to test "IsType" FileSchemaTestClass + //Assert.IsType(instance); + } + + + /// + /// Test the property 'File' + /// + [Fact] + public void FileTest() + { + // TODO unit test for the property 'File' + } + /// + /// Test the property 'Files' + /// + [Fact] + public void FilesTest() + { + // TODO unit test for the property 'Files' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FileTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FileTests.cs new file mode 100644 index 0000000000..761bb72a84 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FileTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing File + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FileTests : IDisposable + { + // TODO uncomment below to declare an instance variable for File + //private File instance; + + public FileTests() + { + // TODO uncomment below to create an instance of File + //instance = new File(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of File + /// + [Fact] + public void FileInstanceTest() + { + // TODO uncomment below to test "IsType" File + //Assert.IsType(instance); + } + + + /// + /// Test the property 'SourceURI' + /// + [Fact] + public void SourceURITest() + { + // TODO unit test for the property 'SourceURI' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs new file mode 100644 index 0000000000..0154d52841 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FooGetDefaultResponseTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing FooGetDefaultResponse + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FooGetDefaultResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FooGetDefaultResponse + //private FooGetDefaultResponse instance; + + public FooGetDefaultResponseTests() + { + // TODO uncomment below to create an instance of FooGetDefaultResponse + //instance = new FooGetDefaultResponse(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FooGetDefaultResponse + /// + [Fact] + public void FooGetDefaultResponseInstanceTest() + { + // TODO uncomment below to test "IsType" FooGetDefaultResponse + //Assert.IsType(instance); + } + + + /// + /// Test the property 'String' + /// + [Fact] + public void StringTest() + { + // TODO unit test for the property 'String' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FooTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FooTests.cs new file mode 100644 index 0000000000..0b6ed52edb --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FooTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Foo + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FooTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Foo + //private Foo instance; + + public FooTests() + { + // TODO uncomment below to create an instance of Foo + //instance = new Foo(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Foo + /// + [Fact] + public void FooInstanceTest() + { + // TODO uncomment below to test "IsType" Foo + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Bar' + /// + [Fact] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs new file mode 100644 index 0000000000..97332800e9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -0,0 +1,190 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing FormatTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FormatTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FormatTest + //private FormatTest instance; + + public FormatTestTests() + { + // TODO uncomment below to create an instance of FormatTest + //instance = new FormatTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FormatTest + /// + [Fact] + public void FormatTestInstanceTest() + { + // TODO uncomment below to test "IsType" FormatTest + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Integer' + /// + [Fact] + public void IntegerTest() + { + // TODO unit test for the property 'Integer' + } + /// + /// Test the property 'Int32' + /// + [Fact] + public void Int32Test() + { + // TODO unit test for the property 'Int32' + } + /// + /// Test the property 'Int64' + /// + [Fact] + public void Int64Test() + { + // TODO unit test for the property 'Int64' + } + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + /// + /// Test the property 'Float' + /// + [Fact] + public void FloatTest() + { + // TODO unit test for the property 'Float' + } + /// + /// Test the property 'Double' + /// + [Fact] + public void DoubleTest() + { + // TODO unit test for the property 'Double' + } + /// + /// Test the property 'Decimal' + /// + [Fact] + public void DecimalTest() + { + // TODO unit test for the property 'Decimal' + } + /// + /// Test the property 'String' + /// + [Fact] + public void StringTest() + { + // TODO unit test for the property 'String' + } + /// + /// Test the property 'Byte' + /// + [Fact] + public void ByteTest() + { + // TODO unit test for the property 'Byte' + } + /// + /// Test the property 'Binary' + /// + [Fact] + public void BinaryTest() + { + // TODO unit test for the property 'Binary' + } + /// + /// Test the property 'Date' + /// + [Fact] + public void DateTest() + { + // TODO unit test for the property 'Date' + } + /// + /// Test the property 'DateTime' + /// + [Fact] + public void DateTimeTest() + { + // TODO unit test for the property 'DateTime' + } + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + /// + /// Test the property 'PatternWithDigits' + /// + [Fact] + public void PatternWithDigitsTest() + { + // TODO unit test for the property 'PatternWithDigits' + } + /// + /// Test the property 'PatternWithDigitsAndDelimiter' + /// + [Fact] + public void PatternWithDigitsAndDelimiterTest() + { + // TODO unit test for the property 'PatternWithDigitsAndDelimiter' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs new file mode 100644 index 0000000000..5ea9e3ffc1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs @@ -0,0 +1,94 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing FruitReq + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FruitReqTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FruitReq + //private FruitReq instance; + + public FruitReqTests() + { + // TODO uncomment below to create an instance of FruitReq + //instance = new FruitReq(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FruitReq + /// + [Fact] + public void FruitReqInstanceTest() + { + // TODO uncomment below to test "IsType" FruitReq + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Mealy' + /// + [Fact] + public void MealyTest() + { + // TODO unit test for the property 'Mealy' + } + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + /// + /// Test the property 'Sweet' + /// + [Fact] + public void SweetTest() + { + // TODO unit test for the property 'Sweet' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FruitTests.cs new file mode 100644 index 0000000000..91e069bb42 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/FruitTests.cs @@ -0,0 +1,94 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Fruit + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FruitTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Fruit + //private Fruit instance; + + public FruitTests() + { + // TODO uncomment below to create an instance of Fruit + //instance = new Fruit(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Fruit + /// + [Fact] + public void FruitInstanceTest() + { + // TODO uncomment below to test "IsType" Fruit + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Origin' + /// + [Fact] + public void OriginTest() + { + // TODO unit test for the property 'Origin' + } + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs new file mode 100644 index 0000000000..08fb0e07a1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs @@ -0,0 +1,94 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing GmFruit + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class GmFruitTests : IDisposable + { + // TODO uncomment below to declare an instance variable for GmFruit + //private GmFruit instance; + + public GmFruitTests() + { + // TODO uncomment below to create an instance of GmFruit + //instance = new GmFruit(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of GmFruit + /// + [Fact] + public void GmFruitInstanceTest() + { + // TODO uncomment below to test "IsType" GmFruit + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Origin' + /// + [Fact] + public void OriginTest() + { + // TODO unit test for the property 'Origin' + } + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs new file mode 100644 index 0000000000..faa4930944 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -0,0 +1,88 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing GrandparentAnimal + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class GrandparentAnimalTests : IDisposable + { + // TODO uncomment below to declare an instance variable for GrandparentAnimal + //private GrandparentAnimal instance; + + public GrandparentAnimalTests() + { + // TODO uncomment below to create an instance of GrandparentAnimal + //instance = new GrandparentAnimal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of GrandparentAnimal + /// + [Fact] + public void GrandparentAnimalInstanceTest() + { + // TODO uncomment below to test "IsType" GrandparentAnimal + //Assert.IsType(instance); + } + + /// + /// Test deserialize a ChildCat from type ParentPet + /// + [Fact] + public void ChildCatDeserializeFromParentPetTest() + { + // TODO uncomment below to test deserialize a ChildCat from type ParentPet + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } + + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs new file mode 100644 index 0000000000..651a9f0ce3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing HasOnlyReadOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class HasOnlyReadOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for HasOnlyReadOnly + //private HasOnlyReadOnly instance; + + public HasOnlyReadOnlyTests() + { + // TODO uncomment below to create an instance of HasOnlyReadOnly + //instance = new HasOnlyReadOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of HasOnlyReadOnly + /// + [Fact] + public void HasOnlyReadOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" HasOnlyReadOnly + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Bar' + /// + [Fact] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + /// + /// Test the property 'Foo' + /// + [Fact] + public void FooTest() + { + // TODO unit test for the property 'Foo' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs new file mode 100644 index 0000000000..857190a333 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing HealthCheckResult + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class HealthCheckResultTests : IDisposable + { + // TODO uncomment below to declare an instance variable for HealthCheckResult + //private HealthCheckResult instance; + + public HealthCheckResultTests() + { + // TODO uncomment below to create an instance of HealthCheckResult + //instance = new HealthCheckResult(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of HealthCheckResult + /// + [Fact] + public void HealthCheckResultInstanceTest() + { + // TODO uncomment below to test "IsType" HealthCheckResult + //Assert.IsType(instance); + } + + + /// + /// Test the property 'NullableMessage' + /// + [Fact] + public void NullableMessageTest() + { + // TODO unit test for the property 'NullableMessage' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs new file mode 100644 index 0000000000..755c417cc5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing IsoscelesTriangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class IsoscelesTriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for IsoscelesTriangle + //private IsoscelesTriangle instance; + + public IsoscelesTriangleTests() + { + // TODO uncomment below to create an instance of IsoscelesTriangle + //instance = new IsoscelesTriangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of IsoscelesTriangle + /// + [Fact] + public void IsoscelesTriangleInstanceTest() + { + // TODO uncomment below to test "IsType" IsoscelesTriangle + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ListTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ListTests.cs new file mode 100644 index 0000000000..2ed828d052 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ListTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing List + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ListTests : IDisposable + { + // TODO uncomment below to declare an instance variable for List + //private List instance; + + public ListTests() + { + // TODO uncomment below to create an instance of List + //instance = new List(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of List + /// + [Fact] + public void ListInstanceTest() + { + // TODO uncomment below to test "IsType" List + //Assert.IsType(instance); + } + + + /// + /// Test the property '_123List' + /// + [Fact] + public void _123ListTest() + { + // TODO unit test for the property '_123List' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/MammalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/MammalTests.cs new file mode 100644 index 0000000000..7b46cbf064 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/MammalTests.cs @@ -0,0 +1,94 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Mammal + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class MammalTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Mammal + //private Mammal instance; + + public MammalTests() + { + // TODO uncomment below to create an instance of Mammal + //instance = new Mammal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Mammal + /// + [Fact] + public void MammalInstanceTest() + { + // TODO uncomment below to test "IsType" Mammal + //Assert.IsType(instance); + } + + + /// + /// Test the property 'HasBaleen' + /// + [Fact] + public void HasBaleenTest() + { + // TODO unit test for the property 'HasBaleen' + } + /// + /// Test the property 'HasTeeth' + /// + [Fact] + public void HasTeethTest() + { + // TODO unit test for the property 'HasTeeth' + } + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + /// + /// Test the property 'Type' + /// + [Fact] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/MapTestTests.cs new file mode 100644 index 0000000000..20036e1c90 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/MapTestTests.cs @@ -0,0 +1,94 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing MapTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class MapTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for MapTest + //private MapTest instance; + + public MapTestTests() + { + // TODO uncomment below to create an instance of MapTest + //instance = new MapTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of MapTest + /// + [Fact] + public void MapTestInstanceTest() + { + // TODO uncomment below to test "IsType" MapTest + //Assert.IsType(instance); + } + + + /// + /// Test the property 'MapMapOfString' + /// + [Fact] + public void MapMapOfStringTest() + { + // TODO unit test for the property 'MapMapOfString' + } + /// + /// Test the property 'MapOfEnumString' + /// + [Fact] + public void MapOfEnumStringTest() + { + // TODO unit test for the property 'MapOfEnumString' + } + /// + /// Test the property 'DirectMap' + /// + [Fact] + public void DirectMapTest() + { + // TODO unit test for the property 'DirectMap' + } + /// + /// Test the property 'IndirectMap' + /// + [Fact] + public void IndirectMapTest() + { + // TODO unit test for the property 'IndirectMap' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs new file mode 100644 index 0000000000..f56cd715f4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -0,0 +1,86 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing MixedPropertiesAndAdditionalPropertiesClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class MixedPropertiesAndAdditionalPropertiesClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for MixedPropertiesAndAdditionalPropertiesClass + //private MixedPropertiesAndAdditionalPropertiesClass instance; + + public MixedPropertiesAndAdditionalPropertiesClassTests() + { + // TODO uncomment below to create an instance of MixedPropertiesAndAdditionalPropertiesClass + //instance = new MixedPropertiesAndAdditionalPropertiesClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of MixedPropertiesAndAdditionalPropertiesClass + /// + [Fact] + public void MixedPropertiesAndAdditionalPropertiesClassInstanceTest() + { + // TODO uncomment below to test "IsType" MixedPropertiesAndAdditionalPropertiesClass + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + /// + /// Test the property 'DateTime' + /// + [Fact] + public void DateTimeTest() + { + // TODO unit test for the property 'DateTime' + } + /// + /// Test the property 'Map' + /// + [Fact] + public void MapTest() + { + // TODO unit test for the property 'Map' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs new file mode 100644 index 0000000000..e25478618f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Model200Response + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class Model200ResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Model200Response + //private Model200Response instance; + + public Model200ResponseTests() + { + // TODO uncomment below to create an instance of Model200Response + //instance = new Model200Response(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Model200Response + /// + [Fact] + public void Model200ResponseInstanceTest() + { + // TODO uncomment below to test "IsType" Model200Response + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property 'Class' + /// + [Fact] + public void ClassTest() + { + // TODO unit test for the property 'Class' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs new file mode 100644 index 0000000000..24a9e26315 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ModelClient + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ModelClientTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ModelClient + //private ModelClient instance; + + public ModelClientTests() + { + // TODO uncomment below to create an instance of ModelClient + //instance = new ModelClient(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ModelClient + /// + [Fact] + public void ModelClientInstanceTest() + { + // TODO uncomment below to test "IsType" ModelClient + //Assert.IsType(instance); + } + + + /// + /// Test the property '_Client' + /// + [Fact] + public void _ClientTest() + { + // TODO unit test for the property '_Client' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NameTests.cs new file mode 100644 index 0000000000..c390049e66 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NameTests.cs @@ -0,0 +1,94 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Name + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NameTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Name + //private Name instance; + + public NameTests() + { + // TODO uncomment below to create an instance of Name + //instance = new Name(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Name + /// + [Fact] + public void NameInstanceTest() + { + // TODO uncomment below to test "IsType" Name + //Assert.IsType(instance); + } + + + /// + /// Test the property '_Name' + /// + [Fact] + public void _NameTest() + { + // TODO unit test for the property '_Name' + } + /// + /// Test the property 'SnakeCase' + /// + [Fact] + public void SnakeCaseTest() + { + // TODO unit test for the property 'SnakeCase' + } + /// + /// Test the property 'Property' + /// + [Fact] + public void PropertyTest() + { + // TODO unit test for the property 'Property' + } + /// + /// Test the property '_123Number' + /// + [Fact] + public void _123NumberTest() + { + // TODO unit test for the property '_123Number' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs new file mode 100644 index 0000000000..8f00505612 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -0,0 +1,158 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing NullableClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NullableClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NullableClass + //private NullableClass instance; + + public NullableClassTests() + { + // TODO uncomment below to create an instance of NullableClass + //instance = new NullableClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NullableClass + /// + [Fact] + public void NullableClassInstanceTest() + { + // TODO uncomment below to test "IsType" NullableClass + //Assert.IsType(instance); + } + + + /// + /// Test the property 'IntegerProp' + /// + [Fact] + public void IntegerPropTest() + { + // TODO unit test for the property 'IntegerProp' + } + /// + /// Test the property 'NumberProp' + /// + [Fact] + public void NumberPropTest() + { + // TODO unit test for the property 'NumberProp' + } + /// + /// Test the property 'BooleanProp' + /// + [Fact] + public void BooleanPropTest() + { + // TODO unit test for the property 'BooleanProp' + } + /// + /// Test the property 'StringProp' + /// + [Fact] + public void StringPropTest() + { + // TODO unit test for the property 'StringProp' + } + /// + /// Test the property 'DateProp' + /// + [Fact] + public void DatePropTest() + { + // TODO unit test for the property 'DateProp' + } + /// + /// Test the property 'DatetimeProp' + /// + [Fact] + public void DatetimePropTest() + { + // TODO unit test for the property 'DatetimeProp' + } + /// + /// Test the property 'ArrayNullableProp' + /// + [Fact] + public void ArrayNullablePropTest() + { + // TODO unit test for the property 'ArrayNullableProp' + } + /// + /// Test the property 'ArrayAndItemsNullableProp' + /// + [Fact] + public void ArrayAndItemsNullablePropTest() + { + // TODO unit test for the property 'ArrayAndItemsNullableProp' + } + /// + /// Test the property 'ArrayItemsNullable' + /// + [Fact] + public void ArrayItemsNullableTest() + { + // TODO unit test for the property 'ArrayItemsNullable' + } + /// + /// Test the property 'ObjectNullableProp' + /// + [Fact] + public void ObjectNullablePropTest() + { + // TODO unit test for the property 'ObjectNullableProp' + } + /// + /// Test the property 'ObjectAndItemsNullableProp' + /// + [Fact] + public void ObjectAndItemsNullablePropTest() + { + // TODO unit test for the property 'ObjectAndItemsNullableProp' + } + /// + /// Test the property 'ObjectItemsNullable' + /// + [Fact] + public void ObjectItemsNullableTest() + { + // TODO unit test for the property 'ObjectItemsNullable' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs new file mode 100644 index 0000000000..5662f91d6e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing NullableShape + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NullableShapeTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NullableShape + //private NullableShape instance; + + public NullableShapeTests() + { + // TODO uncomment below to create an instance of NullableShape + //instance = new NullableShape(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NullableShape + /// + [Fact] + public void NullableShapeInstanceTest() + { + // TODO uncomment below to test "IsType" NullableShape + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs new file mode 100644 index 0000000000..3a06cb020b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing NumberOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NumberOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NumberOnly + //private NumberOnly instance; + + public NumberOnlyTests() + { + // TODO uncomment below to create an instance of NumberOnly + //instance = new NumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NumberOnly + /// + [Fact] + public void NumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" NumberOnly + //Assert.IsType(instance); + } + + + /// + /// Test the property 'JustNumber' + /// + [Fact] + public void JustNumberTest() + { + // TODO unit test for the property 'JustNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs new file mode 100644 index 0000000000..82f93fab48 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ObjectWithDeprecatedFieldsTests.cs @@ -0,0 +1,94 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ObjectWithDeprecatedFields + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ObjectWithDeprecatedFieldsTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ObjectWithDeprecatedFields + //private ObjectWithDeprecatedFields instance; + + public ObjectWithDeprecatedFieldsTests() + { + // TODO uncomment below to create an instance of ObjectWithDeprecatedFields + //instance = new ObjectWithDeprecatedFields(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ObjectWithDeprecatedFields + /// + [Fact] + public void ObjectWithDeprecatedFieldsInstanceTest() + { + // TODO uncomment below to test "IsType" ObjectWithDeprecatedFields + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'DeprecatedRef' + /// + [Fact] + public void DeprecatedRefTest() + { + // TODO unit test for the property 'DeprecatedRef' + } + /// + /// Test the property 'Bars' + /// + [Fact] + public void BarsTest() + { + // TODO unit test for the property 'Bars' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/OrderTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OrderTests.cs similarity index 92% rename from samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/OrderTests.cs rename to samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OrderTests.cs index d78afb0066..cf5c561c54 100644 --- a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/OrderTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -14,8 +14,8 @@ using System; using System.Linq; using System.IO; using System.Collections.Generic; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Models; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs new file mode 100644 index 0000000000..2efda0db59 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs @@ -0,0 +1,86 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterComposite + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterCompositeTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterComposite + //private OuterComposite instance; + + public OuterCompositeTests() + { + // TODO uncomment below to create an instance of OuterComposite + //instance = new OuterComposite(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterComposite + /// + [Fact] + public void OuterCompositeInstanceTest() + { + // TODO uncomment below to test "IsType" OuterComposite + //Assert.IsType(instance); + } + + + /// + /// Test the property 'MyNumber' + /// + [Fact] + public void MyNumberTest() + { + // TODO unit test for the property 'MyNumber' + } + /// + /// Test the property 'MyString' + /// + [Fact] + public void MyStringTest() + { + // TODO unit test for the property 'MyString' + } + /// + /// Test the property 'MyBoolean' + /// + [Fact] + public void MyBooleanTest() + { + // TODO unit test for the property 'MyBoolean' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs new file mode 100644 index 0000000000..986fff774c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs @@ -0,0 +1,62 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterEnumDefaultValue + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumDefaultValueTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumDefaultValue + //private OuterEnumDefaultValue instance; + + public OuterEnumDefaultValueTests() + { + // TODO uncomment below to create an instance of OuterEnumDefaultValue + //instance = new OuterEnumDefaultValue(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumDefaultValue + /// + [Fact] + public void OuterEnumDefaultValueInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumDefaultValue + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs new file mode 100644 index 0000000000..015d5dab94 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs @@ -0,0 +1,62 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterEnumIntegerDefaultValue + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumIntegerDefaultValueTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumIntegerDefaultValue + //private OuterEnumIntegerDefaultValue instance; + + public OuterEnumIntegerDefaultValueTests() + { + // TODO uncomment below to create an instance of OuterEnumIntegerDefaultValue + //instance = new OuterEnumIntegerDefaultValue(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumIntegerDefaultValue + /// + [Fact] + public void OuterEnumIntegerDefaultValueInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumIntegerDefaultValue + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs new file mode 100644 index 0000000000..385e899110 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs @@ -0,0 +1,62 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterEnumInteger + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumIntegerTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumInteger + //private OuterEnumInteger instance; + + public OuterEnumIntegerTests() + { + // TODO uncomment below to create an instance of OuterEnumInteger + //instance = new OuterEnumInteger(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumInteger + /// + [Fact] + public void OuterEnumIntegerInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumInteger + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs new file mode 100644 index 0000000000..f47304767b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs @@ -0,0 +1,62 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterEnum + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnum + //private OuterEnum instance; + + public OuterEnumTests() + { + // TODO uncomment below to create an instance of OuterEnum + //instance = new OuterEnum(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnum + /// + [Fact] + public void OuterEnumInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnum + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs new file mode 100644 index 0000000000..1e17568ed3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs @@ -0,0 +1,71 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ParentPet + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ParentPetTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ParentPet + //private ParentPet instance; + + public ParentPetTests() + { + // TODO uncomment below to create an instance of ParentPet + //instance = new ParentPet(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ParentPet + /// + [Fact] + public void ParentPetInstanceTest() + { + // TODO uncomment below to test "IsType" ParentPet + //Assert.IsType(instance); + } + + /// + /// Test deserialize a ChildCat from type ParentPet + /// + [Fact] + public void ChildCatDeserializeFromParentPetTest() + { + // TODO uncomment below to test deserialize a ChildCat from type ParentPet + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } + + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/PetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/PetTests.cs similarity index 92% rename from samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/PetTests.cs rename to samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/PetTests.cs index b444a6448f..154e66f8df 100644 --- a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/PetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -14,8 +14,8 @@ using System; using System.Linq; using System.IO; using System.Collections.Generic; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Models; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/PigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/PigTests.cs new file mode 100644 index 0000000000..55cf218904 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/PigTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Pig + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PigTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Pig + //private Pig instance; + + public PigTests() + { + // TODO uncomment below to create an instance of Pig + //instance = new Pig(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Pig + /// + [Fact] + public void PigInstanceTest() + { + // TODO uncomment below to test "IsType" Pig + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs new file mode 100644 index 0000000000..eff3c6ddc9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/PolymorphicPropertyTests.cs @@ -0,0 +1,62 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing PolymorphicProperty + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PolymorphicPropertyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for PolymorphicProperty + //private PolymorphicProperty instance; + + public PolymorphicPropertyTests() + { + // TODO uncomment below to create an instance of PolymorphicProperty + //instance = new PolymorphicProperty(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of PolymorphicProperty + /// + [Fact] + public void PolymorphicPropertyInstanceTest() + { + // TODO uncomment below to test "IsType" PolymorphicProperty + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs new file mode 100644 index 0000000000..6eef9f4c81 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing QuadrilateralInterface + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class QuadrilateralInterfaceTests : IDisposable + { + // TODO uncomment below to declare an instance variable for QuadrilateralInterface + //private QuadrilateralInterface instance; + + public QuadrilateralInterfaceTests() + { + // TODO uncomment below to create an instance of QuadrilateralInterface + //instance = new QuadrilateralInterface(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of QuadrilateralInterface + /// + [Fact] + public void QuadrilateralInterfaceInstanceTest() + { + // TODO uncomment below to test "IsType" QuadrilateralInterface + //Assert.IsType(instance); + } + + + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs new file mode 100644 index 0000000000..26826681a4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Quadrilateral + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class QuadrilateralTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Quadrilateral + //private Quadrilateral instance; + + public QuadrilateralTests() + { + // TODO uncomment below to create an instance of Quadrilateral + //instance = new Quadrilateral(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Quadrilateral + /// + [Fact] + public void QuadrilateralInstanceTest() + { + // TODO uncomment below to test "IsType" Quadrilateral + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs new file mode 100644 index 0000000000..dc3d0fad54 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ReadOnlyFirst + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ReadOnlyFirstTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ReadOnlyFirst + //private ReadOnlyFirst instance; + + public ReadOnlyFirstTests() + { + // TODO uncomment below to create an instance of ReadOnlyFirst + //instance = new ReadOnlyFirst(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ReadOnlyFirst + /// + [Fact] + public void ReadOnlyFirstInstanceTest() + { + // TODO uncomment below to test "IsType" ReadOnlyFirst + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Bar' + /// + [Fact] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + /// + /// Test the property 'Baz' + /// + [Fact] + public void BazTest() + { + // TODO unit test for the property 'Baz' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ReturnTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ReturnTests.cs new file mode 100644 index 0000000000..c8c1d6510d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ReturnTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Return + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ReturnTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Return + //private Return instance; + + public ReturnTests() + { + // TODO uncomment below to create an instance of Return + //instance = new Return(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Return + /// + [Fact] + public void ReturnInstanceTest() + { + // TODO uncomment below to test "IsType" Return + //Assert.IsType(instance); + } + + + /// + /// Test the property '_Return' + /// + [Fact] + public void _ReturnTest() + { + // TODO unit test for the property '_Return' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs new file mode 100644 index 0000000000..04cb9f1ab6 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ScaleneTriangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ScaleneTriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ScaleneTriangle + //private ScaleneTriangle instance; + + public ScaleneTriangleTests() + { + // TODO uncomment below to create an instance of ScaleneTriangle + //instance = new ScaleneTriangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ScaleneTriangle + /// + [Fact] + public void ScaleneTriangleInstanceTest() + { + // TODO uncomment below to test "IsType" ScaleneTriangle + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs new file mode 100644 index 0000000000..7bd0bc86f9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ShapeInterface + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ShapeInterfaceTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ShapeInterface + //private ShapeInterface instance; + + public ShapeInterfaceTests() + { + // TODO uncomment below to create an instance of ShapeInterface + //instance = new ShapeInterface(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ShapeInterface + /// + [Fact] + public void ShapeInterfaceInstanceTest() + { + // TODO uncomment below to test "IsType" ShapeInterface + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs new file mode 100644 index 0000000000..d0af114157 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ShapeOrNull + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ShapeOrNullTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ShapeOrNull + //private ShapeOrNull instance; + + public ShapeOrNullTests() + { + // TODO uncomment below to create an instance of ShapeOrNull + //instance = new ShapeOrNull(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ShapeOrNull + /// + [Fact] + public void ShapeOrNullInstanceTest() + { + // TODO uncomment below to test "IsType" ShapeOrNull + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ShapeTests.cs new file mode 100644 index 0000000000..b01bd531f8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ShapeTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Shape + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ShapeTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Shape + //private Shape instance; + + public ShapeTests() + { + // TODO uncomment below to create an instance of Shape + //instance = new Shape(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Shape + /// + [Fact] + public void ShapeInstanceTest() + { + // TODO uncomment below to test "IsType" Shape + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs new file mode 100644 index 0000000000..6648e98092 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing SimpleQuadrilateral + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class SimpleQuadrilateralTests : IDisposable + { + // TODO uncomment below to declare an instance variable for SimpleQuadrilateral + //private SimpleQuadrilateral instance; + + public SimpleQuadrilateralTests() + { + // TODO uncomment below to create an instance of SimpleQuadrilateral + //instance = new SimpleQuadrilateral(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of SimpleQuadrilateral + /// + [Fact] + public void SimpleQuadrilateralInstanceTest() + { + // TODO uncomment below to test "IsType" SimpleQuadrilateral + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs new file mode 100644 index 0000000000..0f0e1ff12a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing SpecialModelName + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class SpecialModelNameTests : IDisposable + { + // TODO uncomment below to declare an instance variable for SpecialModelName + //private SpecialModelName instance; + + public SpecialModelNameTests() + { + // TODO uncomment below to create an instance of SpecialModelName + //instance = new SpecialModelName(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of SpecialModelName + /// + [Fact] + public void SpecialModelNameInstanceTest() + { + // TODO uncomment below to test "IsType" SpecialModelName + //Assert.IsType(instance); + } + + + /// + /// Test the property 'SpecialPropertyName' + /// + [Fact] + public void SpecialPropertyNameTest() + { + // TODO unit test for the property 'SpecialPropertyName' + } + /// + /// Test the property '_SpecialModelName' + /// + [Fact] + public void _SpecialModelNameTest() + { + // TODO unit test for the property '_SpecialModelName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/TagTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/TagTests.cs similarity index 88% rename from samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/TagTests.cs rename to samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/TagTests.cs index 141398d038..6d56232d0a 100644 --- a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/TagTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/TagTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -14,8 +14,8 @@ using System; using System.Linq; using System.IO; using System.Collections.Generic; -using Org.OpenAPITools.Apis; -using Org.OpenAPITools.Models; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs new file mode 100644 index 0000000000..fba65470be --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing TriangleInterface + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TriangleInterfaceTests : IDisposable + { + // TODO uncomment below to declare an instance variable for TriangleInterface + //private TriangleInterface instance; + + public TriangleInterfaceTests() + { + // TODO uncomment below to create an instance of TriangleInterface + //instance = new TriangleInterface(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of TriangleInterface + /// + [Fact] + public void TriangleInterfaceInstanceTest() + { + // TODO uncomment below to test "IsType" TriangleInterface + //Assert.IsType(instance); + } + + + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/TriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/TriangleTests.cs new file mode 100644 index 0000000000..bdaab0b479 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/TriangleTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Triangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Triangle + //private Triangle instance; + + public TriangleTests() + { + // TODO uncomment below to create an instance of Triangle + //instance = new Triangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Triangle + /// + [Fact] + public void TriangleInstanceTest() + { + // TODO uncomment below to test "IsType" Triangle + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/UserTests.cs new file mode 100644 index 0000000000..a7b095e4c2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -0,0 +1,158 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing User + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class UserTests : IDisposable + { + // TODO uncomment below to declare an instance variable for User + //private User instance; + + public UserTests() + { + // TODO uncomment below to create an instance of User + //instance = new User(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of User + /// + [Fact] + public void UserInstanceTest() + { + // TODO uncomment below to test "IsType" User + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Username' + /// + [Fact] + public void UsernameTest() + { + // TODO unit test for the property 'Username' + } + /// + /// Test the property 'FirstName' + /// + [Fact] + public void FirstNameTest() + { + // TODO unit test for the property 'FirstName' + } + /// + /// Test the property 'LastName' + /// + [Fact] + public void LastNameTest() + { + // TODO unit test for the property 'LastName' + } + /// + /// Test the property 'Email' + /// + [Fact] + public void EmailTest() + { + // TODO unit test for the property 'Email' + } + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + /// + /// Test the property 'Phone' + /// + [Fact] + public void PhoneTest() + { + // TODO unit test for the property 'Phone' + } + /// + /// Test the property 'UserStatus' + /// + [Fact] + public void UserStatusTest() + { + // TODO unit test for the property 'UserStatus' + } + /// + /// Test the property 'ObjectWithNoDeclaredProps' + /// + [Fact] + public void ObjectWithNoDeclaredPropsTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredProps' + } + /// + /// Test the property 'ObjectWithNoDeclaredPropsNullable' + /// + [Fact] + public void ObjectWithNoDeclaredPropsNullableTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + } + /// + /// Test the property 'AnyTypeProp' + /// + [Fact] + public void AnyTypePropTest() + { + // TODO unit test for the property 'AnyTypeProp' + } + /// + /// Test the property 'AnyTypePropNullable' + /// + [Fact] + public void AnyTypePropNullableTest() + { + // TODO unit test for the property 'AnyTypePropNullable' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/WhaleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/WhaleTests.cs new file mode 100644 index 0000000000..0961079194 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/WhaleTests.cs @@ -0,0 +1,86 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Whale + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class WhaleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Whale + //private Whale instance; + + public WhaleTests() + { + // TODO uncomment below to create an instance of Whale + //instance = new Whale(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Whale + /// + [Fact] + public void WhaleInstanceTest() + { + // TODO uncomment below to test "IsType" Whale + //Assert.IsType(instance); + } + + + /// + /// Test the property 'HasBaleen' + /// + [Fact] + public void HasBaleenTest() + { + // TODO unit test for the property 'HasBaleen' + } + /// + /// Test the property 'HasTeeth' + /// + [Fact] + public void HasTeethTest() + { + // TODO unit test for the property 'HasTeeth' + } + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ZebraTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ZebraTests.cs new file mode 100644 index 0000000000..f44e921314 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/ZebraTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Zebra + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ZebraTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Zebra + //private Zebra instance; + + public ZebraTests() + { + // TODO uncomment below to create an instance of Zebra + //instance = new Zebra(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Zebra + /// + [Fact] + public void ZebraInstanceTest() + { + // TODO uncomment below to test "IsType" Zebra + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Type' + /// + [Fact] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj new file mode 100644 index 0000000000..866b572467 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -0,0 +1,20 @@ + + + + Org.OpenAPITools.Test + Org.OpenAPITools.Test + net48 + false + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/AnotherFakeApi.cs new file mode 100644 index 0000000000..95d41fcbd9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -0,0 +1,354 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Api +{ + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IAnotherFakeApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ModelClient + ModelClient Call123TestSpecialTags(ModelClient modelClient, int operationIndex = 0); + + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ApiResponse of ModelClient + ApiResponse Call123TestSpecialTagsWithHttpInfo(ModelClient modelClient, int operationIndex = 0); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IAnotherFakeApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ModelClient + System.Threading.Tasks.Task Call123TestSpecialTagsAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + System.Threading.Tasks.Task> Call123TestSpecialTagsWithHttpInfoAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IAnotherFakeApi : IAnotherFakeApiSync, IAnotherFakeApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class AnotherFakeApi : IAnotherFakeApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public AnotherFakeApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public AnotherFakeApi(string basePath) + { + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + new Org.OpenAPITools.Client.Configuration { BasePath = basePath } + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public AnotherFakeApi(Org.OpenAPITools.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access. + /// The client interface for asynchronous API access. + /// The configuration object. + public AnotherFakeApi(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + this.AsynchronousClient = asyncClient; + this.Configuration = configuration; + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// The client for accessing this underlying API asynchronously. + /// + public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } + + /// + /// The client for accessing this underlying API synchronously. + /// + public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ModelClient + public ModelClient Call123TestSpecialTags(ModelClient modelClient, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = Call123TestSpecialTagsWithHttpInfo(modelClient); + return localVarResponse.Data; + } + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ApiResponse of ModelClient + public Org.OpenAPITools.Client.ApiResponse Call123TestSpecialTagsWithHttpInfo(ModelClient modelClient, int operationIndex = 0) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = modelClient; + + localVarRequestOptions.Operation = "AnotherFakeApi.Call123TestSpecialTags"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Patch("/another-fake/dummy", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ModelClient + public async System.Threading.Tasks.Task Call123TestSpecialTagsAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await Call123TestSpecialTagsWithHttpInfoAsync(modelClient, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + public async System.Threading.Tasks.Task> Call123TestSpecialTagsWithHttpInfoAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = modelClient; + + localVarRequestOptions.Operation = "AnotherFakeApi.Call123TestSpecialTags"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PatchAsync("/another-fake/dummy", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/DefaultApi.cs new file mode 100644 index 0000000000..bc5b5556d2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -0,0 +1,327 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Api +{ + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// FooGetDefaultResponse + FooGetDefaultResponse FooGet(int operationIndex = 0); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of FooGetDefaultResponse + ApiResponse FooGetWithHttpInfo(int operationIndex = 0); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of FooGetDefaultResponse + System.Threading.Tasks.Task FooGetAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (FooGetDefaultResponse) + System.Threading.Tasks.Task> FooGetWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApi : IDefaultApiSync, IDefaultApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class DefaultApi : IDefaultApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi(string basePath) + { + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + new Org.OpenAPITools.Client.Configuration { BasePath = basePath } + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public DefaultApi(Org.OpenAPITools.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access. + /// The client interface for asynchronous API access. + /// The configuration object. + public DefaultApi(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + this.AsynchronousClient = asyncClient; + this.Configuration = configuration; + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// The client for accessing this underlying API asynchronously. + /// + public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } + + /// + /// The client for accessing this underlying API synchronously. + /// + public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// FooGetDefaultResponse + public FooGetDefaultResponse FooGet(int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FooGetWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of FooGetDefaultResponse + public Org.OpenAPITools.Client.ApiResponse FooGetWithHttpInfo(int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "DefaultApi.FooGet"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get("/foo", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of FooGetDefaultResponse + public async System.Threading.Tasks.Task FooGetAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FooGetWithHttpInfoAsync(operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (FooGetDefaultResponse) + public async System.Threading.Tasks.Task> FooGetWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "DefaultApi.FooGet"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/foo", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs new file mode 100644 index 0000000000..5991b7f0b7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs @@ -0,0 +1,3443 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Api +{ + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// HealthCheckResult + HealthCheckResult FakeHealthGet(int operationIndex = 0); + + /// + /// Health check endpoint + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of HealthCheckResult + ApiResponse FakeHealthGetWithHttpInfo(int operationIndex = 0); + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Index associated with the operation. + /// bool + bool FakeOuterBooleanSerialize(bool? body = default(bool?), int operationIndex = 0); + + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Index associated with the operation. + /// ApiResponse of bool + ApiResponse FakeOuterBooleanSerializeWithHttpInfo(bool? body = default(bool?), int operationIndex = 0); + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Index associated with the operation. + /// OuterComposite + OuterComposite FakeOuterCompositeSerialize(OuterComposite outerComposite = default(OuterComposite), int operationIndex = 0); + + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Index associated with the operation. + /// ApiResponse of OuterComposite + ApiResponse FakeOuterCompositeSerializeWithHttpInfo(OuterComposite outerComposite = default(OuterComposite), int operationIndex = 0); + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Index associated with the operation. + /// decimal + decimal FakeOuterNumberSerialize(decimal? body = default(decimal?), int operationIndex = 0); + + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Index associated with the operation. + /// ApiResponse of decimal + ApiResponse FakeOuterNumberSerializeWithHttpInfo(decimal? body = default(decimal?), int operationIndex = 0); + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Index associated with the operation. + /// string + string FakeOuterStringSerialize(string body = default(string), int operationIndex = 0); + + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Index associated with the operation. + /// ApiResponse of string + ApiResponse FakeOuterStringSerializeWithHttpInfo(string body = default(string), int operationIndex = 0); + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// List<OuterEnum> + List GetArrayOfEnums(int operationIndex = 0); + + /// + /// Array of Enums + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of List<OuterEnum> + ApiResponse> GetArrayOfEnumsWithHttpInfo(int operationIndex = 0); + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Index associated with the operation. + /// + void TestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass, int operationIndex = 0); + + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass fileSchemaTestClass, int operationIndex = 0); + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Index associated with the operation. + /// + void TestBodyWithQueryParams(string query, User user, int operationIndex = 0); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestBodyWithQueryParamsWithHttpInfo(string query, User user, int operationIndex = 0); + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ModelClient + ModelClient TestClientModel(ModelClient modelClient, int operationIndex = 0); + + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ApiResponse of ModelClient + ApiResponse TestClientModelWithHttpInfo(ModelClient modelClient, int operationIndex = 0); + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Index associated with the operation. + /// + void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), int operationIndex = 0); + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), int operationIndex = 0); + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Index associated with the operation. + /// + void TestEnumParameters(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), int operationIndex = 0); + + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestEnumParametersWithHttpInfo(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), int operationIndex = 0); + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Index associated with the operation. + /// + void TestGroupParameters(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), int operationIndex = 0); + + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestGroupParametersWithHttpInfo(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), int operationIndex = 0); + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + void TestInlineAdditionalProperties(Dictionary requestBody, int operationIndex = 0); + + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestInlineAdditionalPropertiesWithHttpInfo(Dictionary requestBody, int operationIndex = 0); + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Index associated with the operation. + /// + void TestJsonFormData(string param, string param2, int operationIndex = 0); + + /// + /// test json serialization of form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestJsonFormDataWithHttpInfo(string param, string param2, int operationIndex = 0); + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Index associated with the operation. + /// + void TestQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context, int operationIndex = 0); + + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context, int operationIndex = 0); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// Health check endpoint + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of HealthCheckResult + System.Threading.Tasks.Task FakeHealthGetAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Health check endpoint + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (HealthCheckResult) + System.Threading.Tasks.Task> FakeHealthGetWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of bool + System.Threading.Tasks.Task FakeOuterBooleanSerializeAsync(bool? body = default(bool?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (bool) + System.Threading.Tasks.Task> FakeOuterBooleanSerializeWithHttpInfoAsync(bool? body = default(bool?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of OuterComposite + System.Threading.Tasks.Task FakeOuterCompositeSerializeAsync(OuterComposite outerComposite = default(OuterComposite), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (OuterComposite) + System.Threading.Tasks.Task> FakeOuterCompositeSerializeWithHttpInfoAsync(OuterComposite outerComposite = default(OuterComposite), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of decimal + System.Threading.Tasks.Task FakeOuterNumberSerializeAsync(decimal? body = default(decimal?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (decimal) + System.Threading.Tasks.Task> FakeOuterNumberSerializeWithHttpInfoAsync(decimal? body = default(decimal?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of string + System.Threading.Tasks.Task FakeOuterStringSerializeAsync(string body = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + System.Threading.Tasks.Task> FakeOuterStringSerializeWithHttpInfoAsync(string body = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Array of Enums + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of List<OuterEnum> + System.Threading.Tasks.Task> GetArrayOfEnumsAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Array of Enums + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<OuterEnum>) + System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestBodyWithFileSchemaWithHttpInfoAsync(FileSchemaTestClass fileSchemaTestClass, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestBodyWithQueryParamsAsync(string query, User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ModelClient + System.Threading.Tasks.Task TestClientModelAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + System.Threading.Tasks.Task> TestClientModelWithHttpInfoAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestEnumParametersAsync(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestInlineAdditionalPropertiesAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestInlineAdditionalPropertiesWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// test json serialization of form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestJsonFormDataAsync(string param, string param2, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test json serialization of form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestJsonFormDataWithHttpInfoAsync(string param, string param2, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestQueryParameterCollectionFormatWithHttpInfoAsync(List pipe, List ioutil, List http, List url, List context, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeApi : IFakeApiSync, IFakeApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class FakeApi : IFakeApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeApi(string basePath) + { + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + new Org.OpenAPITools.Client.Configuration { BasePath = basePath } + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public FakeApi(Org.OpenAPITools.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access. + /// The client interface for asynchronous API access. + /// The configuration object. + public FakeApi(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + this.AsynchronousClient = asyncClient; + this.Configuration = configuration; + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// The client for accessing this underlying API asynchronously. + /// + public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } + + /// + /// The client for accessing this underlying API synchronously. + /// + public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// HealthCheckResult + public HealthCheckResult FakeHealthGet(int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeHealthGetWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of HealthCheckResult + public Org.OpenAPITools.Client.ApiResponse FakeHealthGetWithHttpInfo(int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "FakeApi.FakeHealthGet"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get("/fake/health", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of HealthCheckResult + public async System.Threading.Tasks.Task FakeHealthGetAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeHealthGetWithHttpInfoAsync(operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (HealthCheckResult) + public async System.Threading.Tasks.Task> FakeHealthGetWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "FakeApi.FakeHealthGet"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/health", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Index associated with the operation. + /// bool + public bool FakeOuterBooleanSerialize(bool? body = default(bool?), int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeOuterBooleanSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Index associated with the operation. + /// ApiResponse of bool + public Org.OpenAPITools.Client.ApiResponse FakeOuterBooleanSerializeWithHttpInfo(bool? body = default(bool?), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "*/*" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = body; + + localVarRequestOptions.Operation = "FakeApi.FakeOuterBooleanSerialize"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/outer/boolean", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of bool + public async System.Threading.Tasks.Task FakeOuterBooleanSerializeAsync(bool? body = default(bool?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeOuterBooleanSerializeWithHttpInfoAsync(body, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (bool) + public async System.Threading.Tasks.Task> FakeOuterBooleanSerializeWithHttpInfoAsync(bool? body = default(bool?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "*/*" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = body; + + localVarRequestOptions.Operation = "FakeApi.FakeOuterBooleanSerialize"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/boolean", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Index associated with the operation. + /// OuterComposite + public OuterComposite FakeOuterCompositeSerialize(OuterComposite outerComposite = default(OuterComposite), int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeOuterCompositeSerializeWithHttpInfo(outerComposite); + return localVarResponse.Data; + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Index associated with the operation. + /// ApiResponse of OuterComposite + public Org.OpenAPITools.Client.ApiResponse FakeOuterCompositeSerializeWithHttpInfo(OuterComposite outerComposite = default(OuterComposite), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "*/*" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = outerComposite; + + localVarRequestOptions.Operation = "FakeApi.FakeOuterCompositeSerialize"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/outer/composite", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of OuterComposite + public async System.Threading.Tasks.Task FakeOuterCompositeSerializeAsync(OuterComposite outerComposite = default(OuterComposite), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeOuterCompositeSerializeWithHttpInfoAsync(outerComposite, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (OuterComposite) + public async System.Threading.Tasks.Task> FakeOuterCompositeSerializeWithHttpInfoAsync(OuterComposite outerComposite = default(OuterComposite), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "*/*" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = outerComposite; + + localVarRequestOptions.Operation = "FakeApi.FakeOuterCompositeSerialize"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/composite", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Index associated with the operation. + /// decimal + public decimal FakeOuterNumberSerialize(decimal? body = default(decimal?), int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeOuterNumberSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Index associated with the operation. + /// ApiResponse of decimal + public Org.OpenAPITools.Client.ApiResponse FakeOuterNumberSerializeWithHttpInfo(decimal? body = default(decimal?), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "*/*" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = body; + + localVarRequestOptions.Operation = "FakeApi.FakeOuterNumberSerialize"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/outer/number", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of decimal + public async System.Threading.Tasks.Task FakeOuterNumberSerializeAsync(decimal? body = default(decimal?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeOuterNumberSerializeWithHttpInfoAsync(body, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (decimal) + public async System.Threading.Tasks.Task> FakeOuterNumberSerializeWithHttpInfoAsync(decimal? body = default(decimal?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "*/*" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = body; + + localVarRequestOptions.Operation = "FakeApi.FakeOuterNumberSerialize"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/number", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Index associated with the operation. + /// string + public string FakeOuterStringSerialize(string body = default(string), int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeOuterStringSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Index associated with the operation. + /// ApiResponse of string + public Org.OpenAPITools.Client.ApiResponse FakeOuterStringSerializeWithHttpInfo(string body = default(string), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "*/*" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = body; + + localVarRequestOptions.Operation = "FakeApi.FakeOuterStringSerialize"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/outer/string", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of string + public async System.Threading.Tasks.Task FakeOuterStringSerializeAsync(string body = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeOuterStringSerializeWithHttpInfoAsync(body, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + public async System.Threading.Tasks.Task> FakeOuterStringSerializeWithHttpInfoAsync(string body = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "*/*" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = body; + + localVarRequestOptions.Operation = "FakeApi.FakeOuterStringSerialize"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/string", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// List<OuterEnum> + public List GetArrayOfEnums(int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = GetArrayOfEnumsWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of List<OuterEnum> + public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithHttpInfo(int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "FakeApi.GetArrayOfEnums"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get>("/fake/array-of-enums", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of List<OuterEnum> + public async System.Threading.Tasks.Task> GetArrayOfEnumsAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = await GetArrayOfEnumsWithHttpInfoAsync(operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<OuterEnum>) + public async System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "FakeApi.GetArrayOfEnums"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync>("/fake/array-of-enums", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Index associated with the operation. + /// + public void TestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass, int operationIndex = 0) + { + TestBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); + } + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass fileSchemaTestClass, int operationIndex = 0) + { + // verify the required parameter 'fileSchemaTestClass' is set + if (fileSchemaTestClass == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = fileSchemaTestClass; + + localVarRequestOptions.Operation = "FakeApi.TestBodyWithFileSchema"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Put("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestBodyWithFileSchemaWithHttpInfoAsync(fileSchemaTestClass, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestBodyWithFileSchemaWithHttpInfoAsync(FileSchemaTestClass fileSchemaTestClass, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'fileSchemaTestClass' is set + if (fileSchemaTestClass == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = fileSchemaTestClass; + + localVarRequestOptions.Operation = "FakeApi.TestBodyWithFileSchema"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Index associated with the operation. + /// + public void TestBodyWithQueryParams(string query, User user, int operationIndex = 0) + { + TestBodyWithQueryParamsWithHttpInfo(query, user); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestBodyWithQueryParamsWithHttpInfo(string query, User user, int operationIndex = 0) + { + // verify the required parameter 'query' is set + if (query == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } + + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "FakeApi.TestBodyWithQueryParams"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Put("/fake/body-with-query-params", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestBodyWithQueryParamsAsync(string query, User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestBodyWithQueryParamsWithHttpInfoAsync(query, user, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'query' is set + if (query == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } + + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "FakeApi.TestBodyWithQueryParams"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-query-params", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ModelClient + public ModelClient TestClientModel(ModelClient modelClient, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = TestClientModelWithHttpInfo(modelClient); + return localVarResponse.Data; + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ApiResponse of ModelClient + public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpInfo(ModelClient modelClient, int operationIndex = 0) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = modelClient; + + localVarRequestOptions.Operation = "FakeApi.TestClientModel"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Patch("/fake", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ModelClient + public async System.Threading.Tasks.Task TestClientModelAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await TestClientModelWithHttpInfoAsync(modelClient, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + public async System.Threading.Tasks.Task> TestClientModelWithHttpInfoAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = modelClient; + + localVarRequestOptions.Operation = "FakeApi.TestClientModel"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Index associated with the operation. + /// + public void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), int operationIndex = 0) + { + TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), int operationIndex = 0) + { + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + if (integer != null) + { + localVarRequestOptions.FormParameters.Add("integer", Org.OpenAPITools.Client.ClientUtils.ParameterToString(integer)); // form parameter + } + if (int32 != null) + { + localVarRequestOptions.FormParameters.Add("int32", Org.OpenAPITools.Client.ClientUtils.ParameterToString(int32)); // form parameter + } + if (int64 != null) + { + localVarRequestOptions.FormParameters.Add("int64", Org.OpenAPITools.Client.ClientUtils.ParameterToString(int64)); // form parameter + } + localVarRequestOptions.FormParameters.Add("number", Org.OpenAPITools.Client.ClientUtils.ParameterToString(number)); // form parameter + if (_float != null) + { + localVarRequestOptions.FormParameters.Add("float", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_float)); // form parameter + } + localVarRequestOptions.FormParameters.Add("double", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_double)); // form parameter + if (_string != null) + { + localVarRequestOptions.FormParameters.Add("string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_string)); // form parameter + } + localVarRequestOptions.FormParameters.Add("pattern_without_delimiter", Org.OpenAPITools.Client.ClientUtils.ParameterToString(patternWithoutDelimiter)); // form parameter + localVarRequestOptions.FormParameters.Add("byte", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_byte)); // form parameter + if (binary != null) + { + localVarRequestOptions.FileParameters.Add("binary", binary); + } + if (date != null) + { + localVarRequestOptions.FormParameters.Add("date", Org.OpenAPITools.Client.ClientUtils.ParameterToString(date)); // form parameter + } + if (dateTime != null) + { + localVarRequestOptions.FormParameters.Add("dateTime", Org.OpenAPITools.Client.ClientUtils.ParameterToString(dateTime)); // form parameter + } + if (password != null) + { + localVarRequestOptions.FormParameters.Add("password", Org.OpenAPITools.Client.ClientUtils.ParameterToString(password)); // form parameter + } + if (callback != null) + { + localVarRequestOptions.FormParameters.Add("callback", Org.OpenAPITools.Client.ClientUtils.ParameterToString(callback)); // form parameter + } + + localVarRequestOptions.Operation = "FakeApi.TestEndpointParameters"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_basic_test) required + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + if (integer != null) + { + localVarRequestOptions.FormParameters.Add("integer", Org.OpenAPITools.Client.ClientUtils.ParameterToString(integer)); // form parameter + } + if (int32 != null) + { + localVarRequestOptions.FormParameters.Add("int32", Org.OpenAPITools.Client.ClientUtils.ParameterToString(int32)); // form parameter + } + if (int64 != null) + { + localVarRequestOptions.FormParameters.Add("int64", Org.OpenAPITools.Client.ClientUtils.ParameterToString(int64)); // form parameter + } + localVarRequestOptions.FormParameters.Add("number", Org.OpenAPITools.Client.ClientUtils.ParameterToString(number)); // form parameter + if (_float != null) + { + localVarRequestOptions.FormParameters.Add("float", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_float)); // form parameter + } + localVarRequestOptions.FormParameters.Add("double", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_double)); // form parameter + if (_string != null) + { + localVarRequestOptions.FormParameters.Add("string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_string)); // form parameter + } + localVarRequestOptions.FormParameters.Add("pattern_without_delimiter", Org.OpenAPITools.Client.ClientUtils.ParameterToString(patternWithoutDelimiter)); // form parameter + localVarRequestOptions.FormParameters.Add("byte", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_byte)); // form parameter + if (binary != null) + { + localVarRequestOptions.FileParameters.Add("binary", binary); + } + if (date != null) + { + localVarRequestOptions.FormParameters.Add("date", Org.OpenAPITools.Client.ClientUtils.ParameterToString(date)); // form parameter + } + if (dateTime != null) + { + localVarRequestOptions.FormParameters.Add("dateTime", Org.OpenAPITools.Client.ClientUtils.ParameterToString(dateTime)); // form parameter + } + if (password != null) + { + localVarRequestOptions.FormParameters.Add("password", Org.OpenAPITools.Client.ClientUtils.ParameterToString(password)); // form parameter + } + if (callback != null) + { + localVarRequestOptions.FormParameters.Add("callback", Org.OpenAPITools.Client.ClientUtils.ParameterToString(callback)); // form parameter + } + + localVarRequestOptions.Operation = "FakeApi.TestEndpointParameters"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_basic_test) required + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Index associated with the operation. + /// + public void TestEnumParameters(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), int operationIndex = 0) + { + TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestEnumParametersWithHttpInfo(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + if (enumQueryStringArray != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "enum_query_string_array", enumQueryStringArray)); + } + if (enumQueryString != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_string", enumQueryString)); + } + if (enumQueryInteger != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_integer", enumQueryInteger)); + } + if (enumQueryDouble != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_double", enumQueryDouble)); + } + if (enumHeaderStringArray != null) + { + localVarRequestOptions.HeaderParameters.Add("enum_header_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumHeaderStringArray)); // header parameter + } + if (enumHeaderString != null) + { + localVarRequestOptions.HeaderParameters.Add("enum_header_string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumHeaderString)); // header parameter + } + if (enumFormStringArray != null) + { + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + } + if (enumFormString != null) + { + localVarRequestOptions.FormParameters.Add("enum_form_string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormString)); // form parameter + } + + localVarRequestOptions.Operation = "FakeApi.TestEnumParameters"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get("/fake", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestEnumParametersAsync(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + if (enumQueryStringArray != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "enum_query_string_array", enumQueryStringArray)); + } + if (enumQueryString != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_string", enumQueryString)); + } + if (enumQueryInteger != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_integer", enumQueryInteger)); + } + if (enumQueryDouble != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_double", enumQueryDouble)); + } + if (enumHeaderStringArray != null) + { + localVarRequestOptions.HeaderParameters.Add("enum_header_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumHeaderStringArray)); // header parameter + } + if (enumHeaderString != null) + { + localVarRequestOptions.HeaderParameters.Add("enum_header_string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumHeaderString)); // header parameter + } + if (enumFormStringArray != null) + { + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + } + if (enumFormString != null) + { + localVarRequestOptions.FormParameters.Add("enum_form_string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormString)); // form parameter + } + + localVarRequestOptions.Operation = "FakeApi.TestEnumParameters"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Index associated with the operation. + /// + public void TestGroupParameters(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), int operationIndex = 0) + { + TestGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestGroupParametersWithHttpInfo(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); + if (stringGroup != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "string_group", stringGroup)); + } + if (int64Group != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "int64_group", int64Group)); + } + localVarRequestOptions.HeaderParameters.Add("required_boolean_group", Org.OpenAPITools.Client.ClientUtils.ParameterToString(requiredBooleanGroup)); // header parameter + if (booleanGroup != null) + { + localVarRequestOptions.HeaderParameters.Add("boolean_group", Org.OpenAPITools.Client.ClientUtils.ParameterToString(booleanGroup)); // header parameter + } + + localVarRequestOptions.Operation = "FakeApi.TestGroupParameters"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (bearer_test) required + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Delete("/fake", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestGroupParametersWithHttpInfoAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); + if (stringGroup != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "string_group", stringGroup)); + } + if (int64Group != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "int64_group", int64Group)); + } + localVarRequestOptions.HeaderParameters.Add("required_boolean_group", Org.OpenAPITools.Client.ClientUtils.ParameterToString(requiredBooleanGroup)); // header parameter + if (booleanGroup != null) + { + localVarRequestOptions.HeaderParameters.Add("boolean_group", Org.OpenAPITools.Client.ClientUtils.ParameterToString(booleanGroup)); // header parameter + } + + localVarRequestOptions.Operation = "FakeApi.TestGroupParameters"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (bearer_test) required + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.DeleteAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + public void TestInlineAdditionalProperties(Dictionary requestBody, int operationIndex = 0) + { + TestInlineAdditionalPropertiesWithHttpInfo(requestBody); + } + + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestInlineAdditionalPropertiesWithHttpInfo(Dictionary requestBody, int operationIndex = 0) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestInlineAdditionalProperties"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestInlineAdditionalPropertiesAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestInlineAdditionalPropertiesWithHttpInfoAsync(requestBody, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestInlineAdditionalPropertiesWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestInlineAdditionalProperties"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Index associated with the operation. + /// + public void TestJsonFormData(string param, string param2, int operationIndex = 0) + { + TestJsonFormDataWithHttpInfo(param, param2); + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestJsonFormDataWithHttpInfo(string param, string param2, int operationIndex = 0) + { + // verify the required parameter 'param' is set + if (param == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } + + // verify the required parameter 'param2' is set + if (param2 == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter + localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter + + localVarRequestOptions.Operation = "FakeApi.TestJsonFormData"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get("/fake/jsonFormData", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestJsonFormDataAsync(string param, string param2, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestJsonFormDataWithHttpInfoAsync(param, param2, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestJsonFormDataWithHttpInfoAsync(string param, string param2, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'param' is set + if (param == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } + + // verify the required parameter 'param2' is set + if (param2 == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter + localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter + + localVarRequestOptions.Operation = "FakeApi.TestJsonFormData"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/jsonFormData", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Index associated with the operation. + /// + public void TestQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context, int operationIndex = 0) + { + TestQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context); + } + + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context, int operationIndex = 0) + { + // verify the required parameter 'pipe' is set + if (pipe == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + // verify the required parameter 'ioutil' is set + if (ioutil == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + // verify the required parameter 'http' is set + if (http == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + // verify the required parameter 'url' is set + if (url == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + // verify the required parameter 'context' is set + if (context == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("ssv", "http", http)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "url", url)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "context", context)); + + localVarRequestOptions.Operation = "FakeApi.TestQueryParameterCollectionFormat"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Put("/fake/test-query-parameters", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestQueryParameterCollectionFormatWithHttpInfoAsync(pipe, ioutil, http, url, context, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestQueryParameterCollectionFormatWithHttpInfoAsync(List pipe, List ioutil, List http, List url, List context, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'pipe' is set + if (pipe == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + // verify the required parameter 'ioutil' is set + if (ioutil == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + // verify the required parameter 'http' is set + if (http == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + // verify the required parameter 'url' is set + if (url == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + // verify the required parameter 'context' is set + if (context == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("ssv", "http", http)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "url", url)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "context", context)); + + localVarRequestOptions.Operation = "FakeApi.TestQueryParameterCollectionFormat"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/test-query-parameters", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs new file mode 100644 index 0000000000..dd74c66d15 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -0,0 +1,364 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Api +{ + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeClassnameTags123ApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ModelClient + ModelClient TestClassname(ModelClient modelClient, int operationIndex = 0); + + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ApiResponse of ModelClient + ApiResponse TestClassnameWithHttpInfo(ModelClient modelClient, int operationIndex = 0); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeClassnameTags123ApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ModelClient + System.Threading.Tasks.Task TestClassnameAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + System.Threading.Tasks.Task> TestClassnameWithHttpInfoAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeClassnameTags123Api : IFakeClassnameTags123ApiSync, IFakeClassnameTags123ApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class FakeClassnameTags123Api : IFakeClassnameTags123Api + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeClassnameTags123Api() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeClassnameTags123Api(string basePath) + { + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + new Org.OpenAPITools.Client.Configuration { BasePath = basePath } + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public FakeClassnameTags123Api(Org.OpenAPITools.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access. + /// The client interface for asynchronous API access. + /// The configuration object. + public FakeClassnameTags123Api(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + this.AsynchronousClient = asyncClient; + this.Configuration = configuration; + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// The client for accessing this underlying API asynchronously. + /// + public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } + + /// + /// The client for accessing this underlying API synchronously. + /// + public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// To test class name in snake case To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ModelClient + public ModelClient TestClassname(ModelClient modelClient, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = TestClassnameWithHttpInfo(modelClient); + return localVarResponse.Data; + } + + /// + /// To test class name in snake case To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// ApiResponse of ModelClient + public Org.OpenAPITools.Client.ApiResponse TestClassnameWithHttpInfo(ModelClient modelClient, int operationIndex = 0) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = modelClient; + + localVarRequestOptions.Operation = "FakeClassnameTags123Api.TestClassname"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } + + // make the HTTP request + var localVarResponse = this.Client.Patch("/fake_classname_test", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// To test class name in snake case To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ModelClient + public async System.Threading.Tasks.Task TestClassnameAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await TestClassnameWithHttpInfoAsync(modelClient, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// To test class name in snake case To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + public async System.Threading.Tasks.Task> TestClassnameWithHttpInfoAsync(ModelClient modelClient, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = modelClient; + + localVarRequestOptions.Operation = "FakeClassnameTags123Api.TestClassname"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake_classname_test", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/PetApi.cs new file mode 100644 index 0000000000..e8439eb125 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/PetApi.cs @@ -0,0 +1,2336 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Api +{ + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IPetApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// + void AddPet(Pet pet, int operationIndex = 0); + + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse AddPetWithHttpInfo(Pet pet, int operationIndex = 0); + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Index associated with the operation. + /// + void DeletePet(long petId, string apiKey = default(string), int operationIndex = 0); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse DeletePetWithHttpInfo(long petId, string apiKey = default(string), int operationIndex = 0); + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter (deprecated) + /// Index associated with the operation. + /// List<Pet> + List FindPetsByStatus(List status, int operationIndex = 0); + + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter (deprecated) + /// Index associated with the operation. + /// ApiResponse of List<Pet> + ApiResponse> FindPetsByStatusWithHttpInfo(List status, int operationIndex = 0); + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Index associated with the operation. + /// List<Pet> + [Obsolete] + List FindPetsByTags(List tags, int operationIndex = 0); + + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Index associated with the operation. + /// ApiResponse of List<Pet> + [Obsolete] + ApiResponse> FindPetsByTagsWithHttpInfo(List tags, int operationIndex = 0); + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Index associated with the operation. + /// Pet + Pet GetPetById(long petId, int operationIndex = 0); + + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Index associated with the operation. + /// ApiResponse of Pet + ApiResponse GetPetByIdWithHttpInfo(long petId, int operationIndex = 0); + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// + void UpdatePet(Pet pet, int operationIndex = 0); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse UpdatePetWithHttpInfo(Pet pet, int operationIndex = 0); + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Index associated with the operation. + /// + void UpdatePetWithForm(long petId, string name = default(string), string status = default(string), int operationIndex = 0); + + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse UpdatePetWithFormWithHttpInfo(long petId, string name = default(string), string status = default(string), int operationIndex = 0); + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Index associated with the operation. + /// ApiResponse + ApiResponse UploadFile(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), int operationIndex = 0); + + /// + /// uploads an image + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Index associated with the operation. + /// ApiResponse of ApiResponse + ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), int operationIndex = 0); + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Index associated with the operation. + /// ApiResponse + ApiResponse UploadFileWithRequiredFile(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), int operationIndex = 0); + + /// + /// uploads an image (required) + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Index associated with the operation. + /// ApiResponse of ApiResponse + ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), int operationIndex = 0); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IPetApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task AddPetAsync(Pet pet, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> AddPetWithHttpInfoAsync(Pet pet, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task DeletePetAsync(long petId, string apiKey = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> DeletePetWithHttpInfoAsync(long petId, string apiKey = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter (deprecated) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of List<Pet> + System.Threading.Tasks.Task> FindPetsByStatusAsync(List status, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Finds Pets by status + /// + /// + /// Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter (deprecated) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<Pet>) + System.Threading.Tasks.Task>> FindPetsByStatusWithHttpInfoAsync(List status, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of List<Pet> + [Obsolete] + System.Threading.Tasks.Task> FindPetsByTagsAsync(List tags, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<Pet>) + [Obsolete] + System.Threading.Tasks.Task>> FindPetsByTagsWithHttpInfoAsync(List tags, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Pet + System.Threading.Tasks.Task GetPetByIdAsync(long petId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Pet) + System.Threading.Tasks.Task> GetPetByIdWithHttpInfoAsync(long petId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task UpdatePetAsync(Pet pet, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdatePetWithHttpInfoAsync(Pet pet, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task UpdatePetWithFormAsync(long petId, string name = default(string), string status = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdatePetWithFormWithHttpInfoAsync(long petId, string name = default(string), string status = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// uploads an image + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// uploads an image + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ApiResponse) + System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// uploads an image (required) + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// uploads an image (required) + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ApiResponse) + System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IPetApi : IPetApiSync, IPetApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class PetApi : IPetApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public PetApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PetApi(string basePath) + { + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + new Org.OpenAPITools.Client.Configuration { BasePath = basePath } + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public PetApi(Org.OpenAPITools.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access. + /// The client interface for asynchronous API access. + /// The configuration object. + public PetApi(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + this.AsynchronousClient = asyncClient; + this.Configuration = configuration; + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// The client for accessing this underlying API asynchronously. + /// + public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } + + /// + /// The client for accessing this underlying API synchronously. + /// + public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// + public void AddPet(Pet pet, int operationIndex = 0) + { + AddPetWithHttpInfo(pet); + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse AddPetWithHttpInfo(Pet pet, int operationIndex = 0) + { + // verify the required parameter 'pet' is set + if (pet == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json", + "application/xml" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = pet; + + localVarRequestOptions.Operation = "PetApi.AddPet"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "POST", "/pet", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/pet", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task AddPetAsync(Pet pet, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await AddPetWithHttpInfoAsync(pet, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> AddPetWithHttpInfoAsync(Pet pet, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'pet' is set + if (pet == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json", + "application/xml" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = pet; + + localVarRequestOptions.Operation = "PetApi.AddPet"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "POST", "/pet", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Index associated with the operation. + /// + public void DeletePet(long petId, string apiKey = default(string), int operationIndex = 0) + { + DeletePetWithHttpInfo(petId, apiKey); + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse DeletePetWithHttpInfo(long petId, string apiKey = default(string), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (apiKey != null) + { + localVarRequestOptions.HeaderParameters.Add("api_key", Org.OpenAPITools.Client.ClientUtils.ParameterToString(apiKey)); // header parameter + } + + localVarRequestOptions.Operation = "PetApi.DeletePet"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = this.Client.Delete("/pet/{petId}", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task DeletePetAsync(long petId, string apiKey = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await DeletePetWithHttpInfoAsync(petId, apiKey, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeletePetWithHttpInfoAsync(long petId, string apiKey = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (apiKey != null) + { + localVarRequestOptions.HeaderParameters.Add("api_key", Org.OpenAPITools.Client.ClientUtils.ParameterToString(apiKey)); // header parameter + } + + localVarRequestOptions.Operation = "PetApi.DeletePet"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.DeleteAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter (deprecated) + /// Index associated with the operation. + /// List<Pet> + public List FindPetsByStatus(List status, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = FindPetsByStatusWithHttpInfo(status); + return localVarResponse.Data; + } + + /// + /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter (deprecated) + /// Index associated with the operation. + /// ApiResponse of List<Pet> + public Org.OpenAPITools.Client.ApiResponse> FindPetsByStatusWithHttpInfo(List status, int operationIndex = 0) + { + // verify the required parameter 'status' is set + if (status == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); + + localVarRequestOptions.Operation = "PetApi.FindPetsByStatus"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "GET", "/pet/findByStatus", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = this.Client.Get>("/pet/findByStatus", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter (deprecated) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of List<Pet> + public async System.Threading.Tasks.Task> FindPetsByStatusAsync(List status, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = await FindPetsByStatusWithHttpInfoAsync(status, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Finds Pets by status Multiple status values can be provided with comma separated strings + /// + /// Thrown when fails to make API call + /// Status values that need to be considered for filter (deprecated) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<Pet>) + public async System.Threading.Tasks.Task>> FindPetsByStatusWithHttpInfoAsync(List status, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'status' is set + if (status == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); + + localVarRequestOptions.Operation = "PetApi.FindPetsByStatus"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "GET", "/pet/findByStatus", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Index associated with the operation. + /// List<Pet> + [Obsolete] + public List FindPetsByTags(List tags, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = FindPetsByTagsWithHttpInfo(tags); + return localVarResponse.Data; + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Index associated with the operation. + /// ApiResponse of List<Pet> + [Obsolete] + public Org.OpenAPITools.Client.ApiResponse> FindPetsByTagsWithHttpInfo(List tags, int operationIndex = 0) + { + // verify the required parameter 'tags' is set + if (tags == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); + + localVarRequestOptions.Operation = "PetApi.FindPetsByTags"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "GET", "/pet/findByTags", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = this.Client.Get>("/pet/findByTags", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of List<Pet> + [Obsolete] + public async System.Threading.Tasks.Task> FindPetsByTagsAsync(List tags, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = await FindPetsByTagsWithHttpInfoAsync(tags, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<Pet>) + [Obsolete] + public async System.Threading.Tasks.Task>> FindPetsByTagsWithHttpInfoAsync(List tags, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'tags' is set + if (tags == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); + + localVarRequestOptions.Operation = "PetApi.FindPetsByTags"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "GET", "/pet/findByTags", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Index associated with the operation. + /// Pet + public Pet GetPetById(long petId, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = GetPetByIdWithHttpInfo(petId); + return localVarResponse.Data; + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Index associated with the operation. + /// ApiResponse of Pet + public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petId, int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + + localVarRequestOptions.Operation = "PetApi.GetPetById"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (api_key) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); + } + + // make the HTTP request + var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Pet + public async System.Threading.Tasks.Task GetPetByIdAsync(long petId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await GetPetByIdWithHttpInfoAsync(petId, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Pet) + public async System.Threading.Tasks.Task> GetPetByIdWithHttpInfoAsync(long petId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + + localVarRequestOptions.Operation = "PetApi.GetPetById"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (api_key) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// + public void UpdatePet(Pet pet, int operationIndex = 0) + { + UpdatePetWithHttpInfo(pet); + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet, int operationIndex = 0) + { + // verify the required parameter 'pet' is set + if (pet == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json", + "application/xml" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = pet; + + localVarRequestOptions.Operation = "PetApi.UpdatePet"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "PUT", "/pet", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = this.Client.Put("/pet", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task UpdatePetAsync(Pet pet, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await UpdatePetWithHttpInfoAsync(pet, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdatePetWithHttpInfoAsync(Pet pet, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'pet' is set + if (pet == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json", + "application/xml" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = pet; + + localVarRequestOptions.Operation = "PetApi.UpdatePet"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "PUT", "/pet", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PutAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Index associated with the operation. + /// + public void UpdatePetWithForm(long petId, string name = default(string), string status = default(string), int operationIndex = 0) + { + UpdatePetWithFormWithHttpInfo(petId, name, status); + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse UpdatePetWithFormWithHttpInfo(long petId, string name = default(string), string status = default(string), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (name != null) + { + localVarRequestOptions.FormParameters.Add("name", Org.OpenAPITools.Client.ClientUtils.ParameterToString(name)); // form parameter + } + if (status != null) + { + localVarRequestOptions.FormParameters.Add("status", Org.OpenAPITools.Client.ClientUtils.ParameterToString(status)); // form parameter + } + + localVarRequestOptions.Operation = "PetApi.UpdatePetWithForm"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/pet/{petId}", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task UpdatePetWithFormAsync(long petId, string name = default(string), string status = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await UpdatePetWithFormWithHttpInfoAsync(petId, name, status, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdatePetWithFormWithHttpInfoAsync(long petId, string name = default(string), string status = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (name != null) + { + localVarRequestOptions.FormParameters.Add("name", Org.OpenAPITools.Client.ClientUtils.ParameterToString(name)); // form parameter + } + if (status != null) + { + localVarRequestOptions.FormParameters.Add("status", Org.OpenAPITools.Client.ClientUtils.ParameterToString(status)); // form parameter + } + + localVarRequestOptions.Operation = "PetApi.UpdatePetWithForm"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Index associated with the operation. + /// ApiResponse + public ApiResponse UploadFile(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = UploadFileWithHttpInfo(petId, additionalMetadata, file); + return localVarResponse.Data; + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Index associated with the operation. + /// ApiResponse of ApiResponse + public Org.OpenAPITools.Client.ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "multipart/form-data" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) + { + localVarRequestOptions.FormParameters.Add("additionalMetadata", Org.OpenAPITools.Client.ClientUtils.ParameterToString(additionalMetadata)); // form parameter + } + if (file != null) + { + localVarRequestOptions.FileParameters.Add("file", file); + } + + localVarRequestOptions.Operation = "PetApi.UploadFile"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ApiResponse) + public async System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "multipart/form-data" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) + { + localVarRequestOptions.FormParameters.Add("additionalMetadata", Org.OpenAPITools.Client.ClientUtils.ParameterToString(additionalMetadata)); // form parameter + } + if (file != null) + { + localVarRequestOptions.FileParameters.Add("file", file); + } + + localVarRequestOptions.Operation = "PetApi.UploadFile"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Index associated with the operation. + /// ApiResponse + public ApiResponse UploadFileWithRequiredFile(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = UploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); + return localVarResponse.Data; + } + + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Index associated with the operation. + /// ApiResponse of ApiResponse + public Org.OpenAPITools.Client.ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), int operationIndex = 0) + { + // verify the required parameter 'requiredFile' is set + if (requiredFile == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "multipart/form-data" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) + { + localVarRequestOptions.FormParameters.Add("additionalMetadata", Org.OpenAPITools.Client.ClientUtils.ParameterToString(additionalMetadata)); // form parameter + } + localVarRequestOptions.FileParameters.Add("requiredFile", requiredFile); + + localVarRequestOptions.Operation = "PetApi.UploadFileWithRequiredFile"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ApiResponse) + public async System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requiredFile' is set + if (requiredFile == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "multipart/form-data" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) + { + localVarRequestOptions.FormParameters.Add("additionalMetadata", Org.OpenAPITools.Client.ClientUtils.ParameterToString(additionalMetadata)); // form parameter + } + localVarRequestOptions.FileParameters.Add("requiredFile", requiredFile); + + localVarRequestOptions.Operation = "PetApi.UploadFileWithRequiredFile"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (petstore_auth) required + // oauth required + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/StoreApi.cs new file mode 100644 index 0000000000..e01ed16258 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/StoreApi.cs @@ -0,0 +1,903 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Api +{ + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IStoreApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Index associated with the operation. + /// + void DeleteOrder(string orderId, int operationIndex = 0); + + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse DeleteOrderWithHttpInfo(string orderId, int operationIndex = 0); + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Dictionary<string, int> + Dictionary GetInventory(int operationIndex = 0); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of Dictionary<string, int> + ApiResponse> GetInventoryWithHttpInfo(int operationIndex = 0); + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Index associated with the operation. + /// Order + Order GetOrderById(long orderId, int operationIndex = 0); + + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Index associated with the operation. + /// ApiResponse of Order + ApiResponse GetOrderByIdWithHttpInfo(long orderId, int operationIndex = 0); + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Index associated with the operation. + /// Order + Order PlaceOrder(Order order, int operationIndex = 0); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Index associated with the operation. + /// ApiResponse of Order + ApiResponse PlaceOrderWithHttpInfo(Order order, int operationIndex = 0); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IStoreApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task DeleteOrderAsync(string orderId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> DeleteOrderWithHttpInfoAsync(string orderId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Dictionary<string, int> + System.Threading.Tasks.Task> GetInventoryAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Dictionary<string, int>) + System.Threading.Tasks.Task>> GetInventoryWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Order + System.Threading.Tasks.Task GetOrderByIdAsync(long orderId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Order) + System.Threading.Tasks.Task> GetOrderByIdWithHttpInfoAsync(long orderId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Order + System.Threading.Tasks.Task PlaceOrderAsync(Order order, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Order) + System.Threading.Tasks.Task> PlaceOrderWithHttpInfoAsync(Order order, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IStoreApi : IStoreApiSync, IStoreApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class StoreApi : IStoreApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public StoreApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public StoreApi(string basePath) + { + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + new Org.OpenAPITools.Client.Configuration { BasePath = basePath } + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public StoreApi(Org.OpenAPITools.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access. + /// The client interface for asynchronous API access. + /// The configuration object. + public StoreApi(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + this.AsynchronousClient = asyncClient; + this.Configuration = configuration; + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// The client for accessing this underlying API asynchronously. + /// + public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } + + /// + /// The client for accessing this underlying API synchronously. + /// + public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Index associated with the operation. + /// + public void DeleteOrder(string orderId, int operationIndex = 0) + { + DeleteOrderWithHttpInfo(orderId); + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse DeleteOrderWithHttpInfo(string orderId, int operationIndex = 0) + { + // verify the required parameter 'orderId' is set + if (orderId == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter + + localVarRequestOptions.Operation = "StoreApi.DeleteOrder"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Delete("/store/order/{order_id}", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task DeleteOrderAsync(string orderId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await DeleteOrderWithHttpInfoAsync(orderId, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeleteOrderWithHttpInfoAsync(string orderId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'orderId' is set + if (orderId == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter + + localVarRequestOptions.Operation = "StoreApi.DeleteOrder"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.DeleteAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Dictionary<string, int> + public Dictionary GetInventory(int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = GetInventoryWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of Dictionary<string, int> + public Org.OpenAPITools.Client.ApiResponse> GetInventoryWithHttpInfo(int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "StoreApi.GetInventory"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (api_key) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); + } + + // make the HTTP request + var localVarResponse = this.Client.Get>("/store/inventory", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Dictionary<string, int> + public async System.Threading.Tasks.Task> GetInventoryAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = await GetInventoryWithHttpInfoAsync(operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Dictionary<string, int>) + public async System.Threading.Tasks.Task>> GetInventoryWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "StoreApi.GetInventory"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (api_key) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync>("/store/inventory", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Index associated with the operation. + /// Order + public Order GetOrderById(long orderId, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = GetOrderByIdWithHttpInfo(orderId); + return localVarResponse.Data; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Index associated with the operation. + /// ApiResponse of Order + public Org.OpenAPITools.Client.ApiResponse GetOrderByIdWithHttpInfo(long orderId, int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter + + localVarRequestOptions.Operation = "StoreApi.GetOrderById"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get("/store/order/{order_id}", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Order + public async System.Threading.Tasks.Task GetOrderByIdAsync(long orderId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await GetOrderByIdWithHttpInfoAsync(orderId, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Order) + public async System.Threading.Tasks.Task> GetOrderByIdWithHttpInfoAsync(long orderId, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter + + localVarRequestOptions.Operation = "StoreApi.GetOrderById"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Index associated with the operation. + /// Order + public Order PlaceOrder(Order order, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = PlaceOrderWithHttpInfo(order); + return localVarResponse.Data; + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Index associated with the operation. + /// ApiResponse of Order + public Org.OpenAPITools.Client.ApiResponse PlaceOrderWithHttpInfo(Order order, int operationIndex = 0) + { + // verify the required parameter 'order' is set + if (order == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = order; + + localVarRequestOptions.Operation = "StoreApi.PlaceOrder"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/store/order", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Order + public async System.Threading.Tasks.Task PlaceOrderAsync(Order order, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await PlaceOrderWithHttpInfoAsync(order, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Order) + public async System.Threading.Tasks.Task> PlaceOrderWithHttpInfoAsync(Order order, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'order' is set + if (order == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = order; + + localVarRequestOptions.Operation = "StoreApi.PlaceOrder"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/store/order", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/UserApi.cs new file mode 100644 index 0000000000..8efb827cdc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Api/UserApi.cs @@ -0,0 +1,1691 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Api +{ + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IUserApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Index associated with the operation. + /// + void CreateUser(User user, int operationIndex = 0); + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse CreateUserWithHttpInfo(User user, int operationIndex = 0); + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// + void CreateUsersWithArrayInput(List user, int operationIndex = 0); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse CreateUsersWithArrayInputWithHttpInfo(List user, int operationIndex = 0); + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// + void CreateUsersWithListInput(List user, int operationIndex = 0); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse CreateUsersWithListInputWithHttpInfo(List user, int operationIndex = 0); + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Index associated with the operation. + /// + void DeleteUser(string username, int operationIndex = 0); + + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse DeleteUserWithHttpInfo(string username, int operationIndex = 0); + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Index associated with the operation. + /// User + User GetUserByName(string username, int operationIndex = 0); + + /// + /// Get user by user name + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Index associated with the operation. + /// ApiResponse of User + ApiResponse GetUserByNameWithHttpInfo(string username, int operationIndex = 0); + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Index associated with the operation. + /// string + string LoginUser(string username, string password, int operationIndex = 0); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Index associated with the operation. + /// ApiResponse of string + ApiResponse LoginUserWithHttpInfo(string username, string password, int operationIndex = 0); + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// + void LogoutUser(int operationIndex = 0); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse LogoutUserWithHttpInfo(int operationIndex = 0); + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Index associated with the operation. + /// + void UpdateUser(string username, User user, int operationIndex = 0); + + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse UpdateUserWithHttpInfo(string username, User user, int operationIndex = 0); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IUserApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task CreateUserAsync(User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUserWithHttpInfoAsync(User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task CreateUsersWithArrayInputAsync(List user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUsersWithArrayInputWithHttpInfoAsync(List user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task CreateUsersWithListInputAsync(List user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUsersWithListInputWithHttpInfoAsync(List user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task DeleteUserAsync(string username, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> DeleteUserWithHttpInfoAsync(string username, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Get user by user name + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of User + System.Threading.Tasks.Task GetUserByNameAsync(string username, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Get user by user name + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (User) + System.Threading.Tasks.Task> GetUserByNameWithHttpInfoAsync(string username, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of string + System.Threading.Tasks.Task LoginUserAsync(string username, string password, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + System.Threading.Tasks.Task> LoginUserWithHttpInfoAsync(string username, string password, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task LogoutUserAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> LogoutUserWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task UpdateUserAsync(string username, User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdateUserWithHttpInfoAsync(string username, User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IUserApi : IUserApiSync, IUserApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class UserApi : IUserApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public UserApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public UserApi(string basePath) + { + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + new Org.OpenAPITools.Client.Configuration { BasePath = basePath } + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public UserApi(Org.OpenAPITools.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access. + /// The client interface for asynchronous API access. + /// The configuration object. + public UserApi(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + this.AsynchronousClient = asyncClient; + this.Configuration = configuration; + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// The client for accessing this underlying API asynchronously. + /// + public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } + + /// + /// The client for accessing this underlying API synchronously. + /// + public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Index associated with the operation. + /// + public void CreateUser(User user, int operationIndex = 0) + { + CreateUserWithHttpInfo(user); + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse CreateUserWithHttpInfo(User user, int operationIndex = 0) + { + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "UserApi.CreateUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/user", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task CreateUserAsync(User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await CreateUserWithHttpInfoAsync(user, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUserWithHttpInfoAsync(User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "UserApi.CreateUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/user", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// + public void CreateUsersWithArrayInput(List user, int operationIndex = 0) + { + CreateUsersWithArrayInputWithHttpInfo(user); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse CreateUsersWithArrayInputWithHttpInfo(List user, int operationIndex = 0) + { + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "UserApi.CreateUsersWithArrayInput"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/user/createWithArray", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task CreateUsersWithArrayInputAsync(List user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await CreateUsersWithArrayInputWithHttpInfoAsync(user, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUsersWithArrayInputWithHttpInfoAsync(List user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "UserApi.CreateUsersWithArrayInput"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithArray", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// + public void CreateUsersWithListInput(List user, int operationIndex = 0) + { + CreateUsersWithListInputWithHttpInfo(user); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse CreateUsersWithListInputWithHttpInfo(List user, int operationIndex = 0) + { + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "UserApi.CreateUsersWithListInput"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/user/createWithList", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task CreateUsersWithListInputAsync(List user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await CreateUsersWithListInputWithHttpInfoAsync(user, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUsersWithListInputWithHttpInfoAsync(List user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "UserApi.CreateUsersWithListInput"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithList", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Index associated with the operation. + /// + public void DeleteUser(string username, int operationIndex = 0) + { + DeleteUserWithHttpInfo(username); + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse DeleteUserWithHttpInfo(string username, int operationIndex = 0) + { + // verify the required parameter 'username' is set + if (username == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + + localVarRequestOptions.Operation = "UserApi.DeleteUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Delete("/user/{username}", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task DeleteUserAsync(string username, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await DeleteUserWithHttpInfoAsync(username, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeleteUserWithHttpInfoAsync(string username, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'username' is set + if (username == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + + localVarRequestOptions.Operation = "UserApi.DeleteUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.DeleteAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Index associated with the operation. + /// User + public User GetUserByName(string username, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = GetUserByNameWithHttpInfo(username); + return localVarResponse.Data; + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Index associated with the operation. + /// ApiResponse of User + public Org.OpenAPITools.Client.ApiResponse GetUserByNameWithHttpInfo(string username, int operationIndex = 0) + { + // verify the required parameter 'username' is set + if (username == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + + localVarRequestOptions.Operation = "UserApi.GetUserByName"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get("/user/{username}", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of User + public async System.Threading.Tasks.Task GetUserByNameAsync(string username, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await GetUserByNameWithHttpInfoAsync(username, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (User) + public async System.Threading.Tasks.Task> GetUserByNameWithHttpInfoAsync(string username, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'username' is set + if (username == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + + localVarRequestOptions.Operation = "UserApi.GetUserByName"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Index associated with the operation. + /// string + public string LoginUser(string username, string password, int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = LoginUserWithHttpInfo(username, password); + return localVarResponse.Data; + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Index associated with the operation. + /// ApiResponse of string + public Org.OpenAPITools.Client.ApiResponse LoginUserWithHttpInfo(string username, string password, int operationIndex = 0) + { + // verify the required parameter 'username' is set + if (username == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); + + localVarRequestOptions.Operation = "UserApi.LoginUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get("/user/login", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of string + public async System.Threading.Tasks.Task LoginUserAsync(string username, string password, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await LoginUserWithHttpInfoAsync(username, password, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + public async System.Threading.Tasks.Task> LoginUserWithHttpInfoAsync(string username, string password, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'username' is set + if (username == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); + + localVarRequestOptions.Operation = "UserApi.LoginUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/user/login", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// + public void LogoutUser(int operationIndex = 0) + { + LogoutUserWithHttpInfo(); + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse LogoutUserWithHttpInfo(int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "UserApi.LogoutUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get("/user/logout", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task LogoutUserAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await LogoutUserWithHttpInfoAsync(operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> LogoutUserWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "UserApi.LogoutUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/user/logout", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Index associated with the operation. + /// + public void UpdateUser(string username, User user, int operationIndex = 0) + { + UpdateUserWithHttpInfo(username, user); + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse UpdateUserWithHttpInfo(string username, User user, int operationIndex = 0) + { + // verify the required parameter 'username' is set + if (username == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } + + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "UserApi.UpdateUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Put("/user/{username}", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task UpdateUserAsync(string username, User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await UpdateUserWithHttpInfoAsync(username, user, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdateUserWithHttpInfoAsync(string username, User user, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'username' is set + if (username == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } + + // verify the required parameter 'user' is set + if (user == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + localVarRequestOptions.Data = user; + + localVarRequestOptions.Operation = "UserApi.UpdateUser"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PutAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiClient.cs new file mode 100644 index 0000000000..660dcd3a05 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiClient.cs @@ -0,0 +1,863 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using RestSharp; +using RestSharp.Serializers; +using RestSharpMethod = RestSharp.Method; +using Polly; +using Org.OpenAPITools.Client.Auth; + +namespace Org.OpenAPITools.Client +{ + /// + /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) + { + var result = (T)Deserialize(response, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal object Deserialize(RestResponse response, Type type) + { + if (type == typeof(byte[])) // return byte array + { + return response.RawBytes; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = response.RawBytes; + if (response.Headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in response.Headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(response.Content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + + public DataFormat DataFormat => DataFormat.Json; + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), + /// encapsulating general REST accessor use cases. + /// + public partial class ApiClient : ISynchronousClient, IAsynchronousClient + { + private readonly string _baseUrl; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accommodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(RestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(RestRequest request, RestResponse response); + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + public ApiClient() + { + _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + } + + /// + /// Initializes a new instance of the + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + _baseUrl = basePath; + } + + /// + /// Constructs the RestSharp version of an http method + /// + /// Swagger Client Custom HttpMethod + /// RestSharp's HttpMethod instance. + /// + private RestSharpMethod Method(HttpMethod method) + { + RestSharpMethod other; + switch (method) + { + case HttpMethod.Get: + other = RestSharpMethod.Get; + break; + case HttpMethod.Post: + other = RestSharpMethod.Post; + break; + case HttpMethod.Put: + other = RestSharpMethod.Put; + break; + case HttpMethod.Delete: + other = RestSharpMethod.Delete; + break; + case HttpMethod.Head: + other = RestSharpMethod.Head; + break; + case HttpMethod.Options: + other = RestSharpMethod.Options; + break; + case HttpMethod.Patch: + other = RestSharpMethod.Patch; + break; + default: + throw new ArgumentOutOfRangeException("method", method, null); + } + + return other; + } + + /// + /// Provides all logic for constructing a new RestSharp . + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the RestSharp request. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new RestRequest instance. + /// + private RestRequest NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + RestRequest request = new RestRequest(path, Method(method)); + + if (options.PathParameters != null) + { + foreach (var pathParam in options.PathParameters) + { + request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); + } + } + + if (options.QueryParameters != null) + { + foreach (var queryParam in options.QueryParameters) + { + foreach (var value in queryParam.Value) + { + request.AddQueryParameter(queryParam.Key, value); + } + } + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.AddHeader(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + request.AddHeader(headerParam.Key, value); + } + } + } + + if (options.FormParameters != null) + { + foreach (var formParam in options.FormParameters) + { + request.AddParameter(formParam.Key, formParam.Value); + } + } + + if (options.Data != null) + { + if (options.Data is Stream stream) + { + var contentType = "application/octet-stream"; + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes[0]; + } + + var bytes = ClientUtils.ReadAsBytes(stream); + request.AddParameter(contentType, bytes, ParameterType.RequestBody); + } + else + { + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) + { + request.RequestFormat = DataFormat.Json; + } + else + { + // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. + } + } + else + { + // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. + request.RequestFormat = DataFormat.Json; + } + + request.AddJsonBody(options.Data); + } + } + + if (options.FileParameters != null) + { + foreach (var fileParam in options.FileParameters) + { + foreach (var file in fileParam.Value) + { + var bytes = ClientUtils.ReadAsBytes(file); + var fileStream = file as FileStream; + if (fileStream != null) + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + else + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); + } + } + } + + return request; + } + + private ApiResponse ToApiResponse(RestResponse response) + { + T result = response.Data; + string rawContent = response.Content; + + var transformed = new ApiResponse(response.StatusCode, new Multimap(), result, rawContent) + { + ErrorText = response.ErrorMessage, + Cookies = new List() + }; + + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.Cookies != null) + { + foreach (var responseCookies in response.Cookies.Cast()) + { + transformed.Cookies.Add( + new Cookie( + responseCookies.Name, + responseCookies.Value, + responseCookies.Path, + responseCookies.Domain) + ); + } + } + + return transformed; + } + + private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); + } + + InterceptRequest(req); + + RestResponse response; + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = client.Execute(req); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) + { + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); + } + + InterceptRequest(req); + + RestResponse response; + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(req, cancellationToken).ConfigureAwait(false); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); + } + #endregion IAsynchronousClient + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), options, config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), options, config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), options, config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), options, config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), options, config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), options, config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Patch, path, options, config), options, config); + } + #endregion ISynchronousClient + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiException.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 0000000000..67d9888d6a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiException.cs @@ -0,0 +1,68 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public object ErrorContent { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() { } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + /// HTTP Headers. + public ApiException(int errorCode, string message, object errorContent = null, Multimap headers = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + this.Headers = headers; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiResponse.cs new file mode 100644 index 0000000000..ca2de833a5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -0,0 +1,166 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// The content of this response + /// + Object Content { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + Multimap Headers { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + List Cookies { get; set; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + } + + /// + /// API Response + /// + public class ApiResponse : IApiResponse + { + #region Properties + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + public string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + public List Cookies { get; set; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The data type of + /// + public object Content + { + get { return Data; } + } + + /// + /// The raw content + /// + public string RawContent { get; } + + #endregion Properties + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data, string rawContent) + { + StatusCode = statusCode; + Headers = headers; + Data = data; + RawContent = rawContent; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data) : this(statusCode, headers, data, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null) + { + } + + #endregion Constructors + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs new file mode 100644 index 0000000000..8b0ba33499 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs @@ -0,0 +1,95 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : AuthenticatorBase + { + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) : base("") + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// Access token to create a parameter from. + /// An authentication parameter. + protected override async ValueTask GetAuthenticationParameter(string accessToken) + { + var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl) + .UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration)); + + var request = new RestRequest() + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + var response = await client.PostAsync(request); + return $"{response.TokenType} {response.AccessToken}"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs new file mode 100644 index 0000000000..e225740925 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs @@ -0,0 +1,27 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs new file mode 100644 index 0000000000..0a94e17e12 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Client.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ClientUtils.cs new file mode 100644 index 0000000000..e499a7728e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -0,0 +1,218 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using KellermanSoftware.CompareNetObjects; + +namespace Org.OpenAPITools.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static constructor to initialise compareLogic. + /// + static ClientUtils() + { + compareLogic = new CompareLogic(); + } + + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// Convert params to key/value pairs. + /// Use collectionFormat to properly format lists and collections. + /// + /// The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi + /// Key name. + /// Value object. + /// A multimap of keys with 1..n associated values. + public static Multimap ParameterToMultiMap(string collectionFormat, string name, object value) + { + var parameters = new Multimap(); + + if (value is ICollection collection && collectionFormat == "multi") + { + foreach (var item in collection) + { + parameters.Add(name, ParameterToString(item)); + } + } + else if (value is IDictionary dictionary) + { + if(collectionFormat == "deepObject") { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value)); + } + } + else { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value)); + } + } + } + else + { + parameters.Add(name, ParameterToString(value)); + } + + return parameters; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// An optional configuration instance, providing formatting options used in processing. + /// Formatted string. + public static string ParameterToString(object obj, IReadableConfiguration configuration = null) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) + return string.Join(",", collection.Cast()); + + return Convert.ToString(obj, CultureInfo.InvariantCulture); + } + + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Configuration.cs new file mode 100644 index 0000000000..526781f42c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Configuration.cs @@ -0,0 +1,731 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Net.Http; +using Org.OpenAPITools.Client.Auth; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "1.0.0"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var status = (int)response.StatusCode; + if (status >= 400) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.RawContent), + response.RawContent, response.Headers); + } + if (status == 0) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.ErrorText), response.ErrorText); + } + return null; + }; + + #endregion Static Members + + #region Private Members + + /// + /// Defines the base path of the target API server. + /// Example: http://localhost:3000/v1/ + /// + private string _basePath; + + /// + /// Gets or sets the API key based on the authentication name. + /// This is the key and value comprising the "secret" for accessing an API. + /// + /// The API key. + private IDictionary _apiKey; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + + /// + /// Gets or sets the servers defined in the OpenAPI spec. + /// + /// The servers + private IList> _servers; + + /// + /// Gets or sets the operation servers defined in the OpenAPI spec. + /// + /// The operation servers + private IReadOnlyDictionary>> _operationServers; + + + /// + /// HttpSigning configuration + /// + private HttpSigningConfiguration _HttpSigningConfiguration = null; + #endregion Private Members + + #region Constructors + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration() + { + Proxy = null; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); + BasePath = "http://petstore.swagger.io:80/v2"; + DefaultHeaders = new ConcurrentDictionary(); + ApiKey = new ConcurrentDictionary(); + ApiKeyPrefix = new ConcurrentDictionary(); + Servers = new List>() + { + { + new Dictionary { + {"url", "http://{server}.swagger.io:{port}/v2"}, + {"description", "petstore server"}, + { + "variables", new Dictionary { + { + "server", new Dictionary { + {"description", "No description provided"}, + {"default_value", "petstore"}, + { + "enum_values", new List() { + "petstore", + "qa-petstore", + "dev-petstore" + } + } + } + }, + { + "port", new Dictionary { + {"description", "No description provided"}, + {"default_value", "80"}, + { + "enum_values", new List() { + "80", + "8080" + } + } + } + } + } + } + } + }, + { + new Dictionary { + {"url", "https://localhost:8080/{version}"}, + {"description", "The local server"}, + { + "variables", new Dictionary { + { + "version", new Dictionary { + {"description", "No description provided"}, + {"default_value", "v2"}, + { + "enum_values", new List() { + "v1", + "v2" + } + } + } + } + } + } + } + }, + { + new Dictionary { + {"url", "https://127.0.0.1/no_variable"}, + {"description", "The local server without variables"}, + } + } + }; + OperationServers = new Dictionary>>() + { + { + "PetApi.AddPet", new List> + { + { + new Dictionary + { + {"url", "http://petstore.swagger.io/v2"}, + {"description", "No description provided"} + } + }, + { + new Dictionary + { + {"url", "http://path-server-test.petstore.local/v2"}, + {"description", "No description provided"} + } + }, + } + }, + { + "PetApi.UpdatePet", new List> + { + { + new Dictionary + { + {"url", "http://petstore.swagger.io/v2"}, + {"description", "No description provided"} + } + }, + { + new Dictionary + { + {"url", "http://path-server-test.petstore.local/v2"}, + {"description", "No description provided"} + } + }, + } + }, + }; + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration( + IDictionary defaultHeaders, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "http://petstore.swagger.io:80/v2") : this() + { + if (string.IsNullOrWhiteSpace(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeaders == null) + throw new ArgumentNullException("defaultHeaders"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeaders) + { + DefaultHeaders.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + #endregion Constructors + + #region Properties + + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath { + get { return _basePath; } + set { _basePath = value; } + } + + /// + /// Gets or sets the default header. + /// + [Obsolete("Use DefaultHeaders instead.")] + public virtual IDictionary DefaultHeader + { + get + { + return DefaultHeaders; + } + set + { + DefaultHeaders = value; + } + } + + /// + /// Gets or sets the default headers. + /// + public virtual IDictionary DefaultHeaders { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout { get; set; } + + /// + /// Gets or sets the proxy + /// + /// Proxy. + public virtual WebProxy Proxy { get; set; } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + string apiKeyValue; + ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); + string apiKeyPrefix; + if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) + { + return apiKeyPrefix + " " + apiKeyValue; + } + + return apiKeyValue; + } + + /// + /// Gets or sets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + public X509CertificateCollection ClientCertificates { get; set; } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// This helper property simplifies code generation. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + /// + /// Gets or sets the token URL for OAuth2 authentication. + /// + /// The OAuth Token URL. + public virtual string OAuthTokenUrl { get; set; } + + /// + /// Gets or sets the client ID for OAuth2 authentication. + /// + /// The OAuth Client ID. + public virtual string OAuthClientId { get; set; } + + /// + /// Gets or sets the client secret for OAuth2 authentication. + /// + /// The OAuth Client Secret. + public virtual string OAuthClientSecret { get; set; } + + /// + /// Gets or sets the flow for OAuth2 authentication. + /// + /// The OAuth Flow. + public virtual OAuthFlow? OAuthFlow { get; set; } + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + _tempFolderPath = Path.GetTempPath(); + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + { + _tempFolderPath = value; + } + else + { + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + } + + /// + /// Gets or sets the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// Whatever you set here will be prepended to the value defined in AddApiKey. + /// + /// An example invocation here might be: + /// + /// ApiKeyPrefix["Authorization"] = "Bearer"; + /// + /// … where ApiKey["Authorization"] would then be used to set the value of your bearer token. + /// + /// + /// OAuth2 workflows should set tokens via AccessToken. + /// + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + + /// + /// Gets or sets the servers. + /// + /// The servers. + public virtual IList> Servers + { + get { return _servers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Servers may not be null."); + } + _servers = value; + } + } + + /// + /// Gets or sets the operation servers. + /// + /// The operation servers. + public virtual IReadOnlyDictionary>> OperationServers + { + get { return _operationServers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Operation servers may not be null."); + } + _operationServers = value; + } + } + + /// + /// Returns URL based on server settings without providing values + /// for the variables + /// + /// Array index of the server settings. + /// The server URL. + public string GetServerUrl(int index) + { + return GetServerUrl(Servers, index, null); + } + + /// + /// Returns URL based on server settings. + /// + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + public string GetServerUrl(int index, Dictionary inputVariables) + { + return GetServerUrl(Servers, index, inputVariables); + } + + /// + /// Returns URL based on operation server settings. + /// + /// Operation associated with the request path. + /// Array index of the server settings. + /// The operation server URL. + public string GetOperationServerUrl(string operation, int index) + { + return GetOperationServerUrl(operation, index, null); + } + + /// + /// Returns URL based on operation server settings. + /// + /// Operation associated with the request path. + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The operation server URL. + public string GetOperationServerUrl(string operation, int index, Dictionary inputVariables) + { + if (OperationServers.TryGetValue(operation, out var operationServer)) + { + return GetServerUrl(operationServer, index, inputVariables); + } + + return null; + } + + /// + /// Returns URL based on server settings. + /// + /// Dictionary of server settings. + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + private string GetServerUrl(IList> servers, int index, Dictionary inputVariables) + { + if (index < 0 || index >= servers.Count) + { + throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {servers.Count}."); + } + + if (inputVariables == null) + { + inputVariables = new Dictionary(); + } + + IReadOnlyDictionary server = servers[index]; + string url = (string)server["url"]; + + if (server.ContainsKey("variables")) + { + // go through each variable and assign a value + foreach (KeyValuePair variable in (IReadOnlyDictionary)server["variables"]) + { + + IReadOnlyDictionary serverVariables = (IReadOnlyDictionary)(variable.Value); + + if (inputVariables.ContainsKey(variable.Key)) + { + if (((List)serverVariables["enum_values"]).Contains(inputVariables[variable.Key])) + { + url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]); + } + else + { + throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List)serverVariables["enum_values"]}"); + } + } + else + { + // use default value + url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]); + } + } + } + + return url; + } + + /// + /// Gets and Sets the HttpSigningConfiguration + /// + public HttpSigningConfiguration HttpSigningConfiguration + { + get { return _HttpSigningConfiguration; } + set { _HttpSigningConfiguration = value; } + } + + #endregion Properties + + #region Methods + + /// + /// Returns a string with essential information for debugging. + /// + public static string ToDebugReport() + { + string report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: 1.0.0\n"; + report += " SDK Package Version: 1.0.0\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + + #region Static Members + /// + /// Merge configurations. + /// + /// First configuration. + /// Second configuration. + /// Merged configuration. + public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second) + { + if (second == null) return first ?? GlobalConfiguration.Instance; + + Dictionary apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value; + foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value; + foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value; + + var config = new Configuration + { + ApiKey = apiKey, + ApiKeyPrefix = apiKeyPrefix, + DefaultHeaders = defaultHeaders, + BasePath = second.BasePath ?? first.BasePath, + Timeout = second.Timeout, + Proxy = second.Proxy ?? first.Proxy, + UserAgent = second.UserAgent ?? first.UserAgent, + Username = second.Username ?? first.Username, + Password = second.Password ?? first.Password, + AccessToken = second.AccessToken ?? first.AccessToken, + OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl, + OAuthClientId = second.OAuthClientId ?? first.OAuthClientId, + OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret, + OAuthFlow = second.OAuthFlow ?? first.OAuthFlow, + HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, + TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, + DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, + ClientCertificates = second.ClientCertificates ?? first.ClientCertificates, + }; + return config; + } + #endregion Static Members + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ExceptionFactory.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ExceptionFactory.cs new file mode 100644 index 0000000000..43624dd7c8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ExceptionFactory.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IApiResponse response); +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/GlobalConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/GlobalConfiguration.cs new file mode 100644 index 0000000000..cbee70bca3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/GlobalConfiguration.cs @@ -0,0 +1,67 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// provides a compile-time extension point for globally configuring + /// API Clients. + /// + /// + /// A customized implementation via partial class may reside in another file and may + /// be excluded from automatic generation via a .openapi-generator-ignore file. + /// + public partial class GlobalConfiguration : Configuration + { + #region Private Members + + private static readonly object GlobalConfigSync = new { }; + private static IReadableConfiguration _globalConfiguration; + + #endregion Private Members + + #region Constructors + + /// + private GlobalConfiguration() + { + } + + /// + public GlobalConfiguration(IDictionary defaultHeader, IDictionary apiKey, IDictionary apiKeyPrefix, string basePath = "http://localhost:3000/api") : base(defaultHeader, apiKey, apiKeyPrefix, basePath) + { + } + + static GlobalConfiguration() + { + Instance = new GlobalConfiguration(); + } + + #endregion Constructors + + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static IReadableConfiguration Instance + { + get { return _globalConfiguration; } + set + { + lock (GlobalConfigSync) + { + _globalConfiguration = value; + } + } + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpMethod.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpMethod.cs new file mode 100644 index 0000000000..39cde64b2a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpMethod.cs @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client +{ + /// + /// Http methods supported by swagger + /// + public enum HttpMethod + { + /// HTTP GET request. + Get, + /// HTTP POST request. + Post, + /// HTTP PUT request. + Put, + /// HTTP DELETE request. + Delete, + /// HTTP HEAD request. + Head, + /// HTTP OPTIONS request. + Options, + /// HTTP PATCH request. + Patch + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs new file mode 100644 index 0000000000..0b3e867d0f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -0,0 +1,774 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Web; + +namespace Org.OpenAPITools.Client +{ + /// + /// Class for HttpSigning auth related parameter and methods + /// + public class HttpSigningConfiguration + { + #region + /// + /// Initialize the HashAlgorithm and SigningAlgorithm to default value + /// + public HttpSigningConfiguration() + { + HashAlgorithm = HashAlgorithmName.SHA256; + SigningAlgorithm = "PKCS1-v15"; + } + #endregion + + #region Properties + /// + ///Gets the Api keyId + /// + public string KeyId { get; set; } + + /// + /// Gets the Key file path + /// + public string KeyFilePath { get; set; } + + /// + /// Gets the key pass phrase for password protected key + /// + public SecureString KeyPassPhrase { get; set; } + + /// + /// Gets the HTTP signing header + /// + public List HttpSigningHeader { get; set; } + + /// + /// Gets the hash algorithm sha256 or sha512 + /// + public HashAlgorithmName HashAlgorithm { get; set; } + + /// + /// Gets the signing algorithm + /// + public string SigningAlgorithm { get; set; } + + /// + /// Gets the Signature validity period in seconds + /// + public int SignatureValidityPeriod { get; set; } + + #endregion + + #region enum + private enum PrivateKeyType + { + None = 0, + RSA = 1, + ECDSA = 2, + } + #endregion + + #region Methods + /// + /// Gets the Headers for HttpSigning + /// + /// Base path + /// HTTP method + /// Path + /// Request options + /// Http signed headers + internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) + { + const string HEADER_REQUEST_TARGET = "(request-target)"; + //The time when the HTTP signature expires. The API server should reject HTTP requests + //that have expired. + const string HEADER_EXPIRES = "(expires)"; + //The 'Date' header. + const string HEADER_DATE = "Date"; + //The 'Host' header. + const string HEADER_HOST = "Host"; + //The time when the HTTP signature was generated. + const string HEADER_CREATED = "(created)"; + //When the 'Digest' header is included in the HTTP signature, the client automatically + //computes the digest of the HTTP request body, per RFC 3230. + const string HEADER_DIGEST = "Digest"; + //The 'Authorization' header is automatically generated by the client. It includes + //the list of signed headers and a base64-encoded signature. + const string HEADER_AUTHORIZATION = "Authorization"; + + //Hash table to store singed headers + var HttpSignedRequestHeader = new Dictionary(); + var HttpSignatureHeader = new Dictionary(); + + if (HttpSigningHeader.Count == 0) + { + HttpSigningHeader.Add("(created)"); + } + + if (requestOptions.PathParameters != null) + { + foreach (var pathParam in requestOptions.PathParameters) + { + var tempPath = path.Replace(pathParam.Key, "0"); + path = string.Format(tempPath, pathParam.Value); + } + } + + var httpValues = HttpUtility.ParseQueryString(string.Empty); + foreach (var parameter in requestOptions.QueryParameters) + { +#if (NETCOREAPP) + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key) + "[]", value); + } + } + else + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + } +#else + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(parameter.Key + "[]", value); + } + } + else + { + httpValues.Add(parameter.Key, parameter.Value[0]); + } +#endif + } + var uriBuilder = new UriBuilder(string.Concat(basePath, path)); + uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); + + var dateTime = DateTime.Now; + string Digest = string.Empty; + + //get the body + string requestBody = string.Empty; + if (requestOptions.Data != null) + { + var serializerSettings = new JsonSerializerSettings(); + requestBody = JsonConvert.SerializeObject(requestOptions.Data, serializerSettings); + } + + if (HashAlgorithm == HashAlgorithmName.SHA256) + { + var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody); + Digest = string.Format("SHA-256={0}", Convert.ToBase64String(bodyDigest)); + } + else if (HashAlgorithm == HashAlgorithmName.SHA512) + { + var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody); + Digest = string.Format("SHA-512={0}", Convert.ToBase64String(bodyDigest)); + } + else + { + throw new Exception(string.Format("{0} not supported", HashAlgorithm)); + } + + foreach (var header in HttpSigningHeader) + { + if (header.Equals(HEADER_REQUEST_TARGET)) + { + var targetUrl = string.Format("{0} {1}{2}", method.ToLower(), uriBuilder.Path, uriBuilder.Query); + HttpSignatureHeader.Add(header.ToLower(), targetUrl); + } + else if (header.Equals(HEADER_EXPIRES)) + { + var expireDateTime = dateTime.AddSeconds(SignatureValidityPeriod); + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(expireDateTime).ToString()); + } + else if (header.Equals(HEADER_DATE)) + { + var utcDateTime = dateTime.ToUniversalTime().ToString("r"); + HttpSignatureHeader.Add(header.ToLower(), utcDateTime); + HttpSignedRequestHeader.Add(HEADER_DATE, utcDateTime); + } + else if (header.Equals(HEADER_HOST)) + { + HttpSignatureHeader.Add(header.ToLower(), uriBuilder.Host); + HttpSignedRequestHeader.Add(HEADER_HOST, uriBuilder.Host); + } + else if (header.Equals(HEADER_CREATED)) + { + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(dateTime).ToString()); + } + else if (header.Equals(HEADER_DIGEST)) + { + HttpSignedRequestHeader.Add(HEADER_DIGEST, Digest); + HttpSignatureHeader.Add(header.ToLower(), Digest); + } + else + { + bool isHeaderFound = false; + foreach (var item in requestOptions.HeaderParameters) + { + if (string.Equals(item.Key, header, StringComparison.OrdinalIgnoreCase)) + { + HttpSignatureHeader.Add(header.ToLower(), item.Value.ToString()); + isHeaderFound = true; + break; + } + } + if (!isHeaderFound) + { + throw new Exception(string.Format("Cannot sign HTTP request.Request does not contain the {0} header.",header)); + } + } + + } + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); + var headerValuesList = new List(); + + foreach (var keyVal in HttpSignatureHeader) + { + headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); + } + //Concatenate headers value separated by new line + var headerValuesString = string.Join("\n", headerValuesList); + var signatureStringHash = GetStringHash(HashAlgorithm.ToString(), headerValuesString); + string headerSignatureStr = null; + var keyType = GetKeyType(KeyFilePath); + + if (keyType == PrivateKeyType.RSA) + { + headerSignatureStr = GetRSASignature(signatureStringHash); + } + else if (keyType == PrivateKeyType.ECDSA) + { + headerSignatureStr = GetECDSASignature(signatureStringHash); + } + else + { + throw new Exception(string.Format("Private key type {0} not supported", keyType)); + } + const string cryptographicScheme = "hs2019"; + var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", + KeyId, cryptographicScheme); + + if (HttpSignatureHeader.ContainsKey(HEADER_CREATED)) + { + authorizationHeaderValue += string.Format(",created={0}", HttpSignatureHeader[HEADER_CREATED]); + } + + if (HttpSignatureHeader.ContainsKey(HEADER_EXPIRES)) + { + authorizationHeaderValue += string.Format(",expires={0}", HttpSignatureHeader[HEADER_EXPIRES]); + } + + authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", + headersKeysString, headerSignatureStr); + HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); + return HttpSignedRequestHeader; + } + + private byte[] GetStringHash(string hashName, string stringToBeHashed) + { + var hashAlgorithm = System.Security.Cryptography.HashAlgorithm.Create(hashName); + var bytes = Encoding.UTF8.GetBytes(stringToBeHashed); + var stringHash = hashAlgorithm.ComputeHash(bytes); + return stringHash; + } + + private int GetUnixTime(DateTime date2) + { + DateTime date1 = new DateTime(1970, 01, 01); + TimeSpan timeSpan = date2 - date1; + return (int)timeSpan.TotalSeconds; + } + + private string GetRSASignature(byte[] stringToSign) + { + RSA rsa = GetRSAProviderFromPemFile(KeyFilePath, KeyPassPhrase); + if (SigningAlgorithm == "RSASSA-PSS") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pss); + return Convert.ToBase64String(signedbytes); + } + else if (SigningAlgorithm == "PKCS1-v15") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); + return Convert.ToBase64String(signedbytes); + } + else + { + return string.Empty; + } + } + + /// + /// Gets the ECDSA signature + /// + /// + /// ECDSA signature + private string GetECDSASignature(byte[] dataToSign) + { + string keyStr = string.Empty; + if (File.Exists(KeyFilePath)) + { + keyStr = File.ReadAllText(KeyFilePath); + } + else + { + keyStr = KeyFilePath; + } + + const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; + var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); + var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); + var ecdsa = ECDsa.Create(); + +#if (NETCOREAPP3_0 || NETCOREAPP3_1 || NET5_0) + var byteCount = 0; + if (KeyPassPhrase != null) + { + IntPtr unmanagedString = IntPtr.Zero; + try + { + // convert secure string to byte array + unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(KeyPassPhrase); + ecdsa.ImportEncryptedPkcs8PrivateKey(Encoding.UTF8.GetBytes(Marshal.PtrToStringUni(unmanagedString)), keyBytes, out byteCount); + } + finally + { + if (unmanagedString != IntPtr.Zero) + { + Marshal.ZeroFreeBSTR(unmanagedString); + } + } + } + else + { + ecdsa.ImportPkcs8PrivateKey(keyBytes, out byteCount); + } + var signedBytes = ecdsa.SignHash(dataToSign); + var derBytes = ConvertToECDSAANS1Format(signedBytes); + var signedString = System.Convert.ToBase64String(derBytes); + + return signedString; +#else + throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); +#endif + } + + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + { + var derBytes = new List(); + byte derLength = 68; //default length for ECDSA code signing bit 0x44 + byte rbytesLength = 32; //R length 0x20 + byte sbytesLength = 32; //S length 0x20 + var rBytes = new List(); + var sBytes = new List(); + for (int i = 0; i < 32; i++) + { + rBytes.Add(signedBytes[i]); + } + for (int i = 32; i < 64; i++) + { + sBytes.Add(signedBytes[i]); + } + + if (rBytes[0] > 0x7F) + { + derLength++; + rbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(rBytes); + rBytes.Clear(); + rBytes.Add(0x00); + rBytes.AddRange(tempBytes); + } + + if (sBytes[0] > 0x7F) + { + derLength++; + sbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(sBytes); + sBytes.Clear(); + sBytes.Add(0x00); + sBytes.AddRange(tempBytes); + + } + + derBytes.Add(48); //start of the sequence 0x30 + derBytes.Add(derLength); //total length r length, type and r bytes + + derBytes.Add(2); //tag for integer + derBytes.Add(rbytesLength); //length of r + derBytes.AddRange(rBytes); + + derBytes.Add(2); //tag for integer + derBytes.Add(sbytesLength); //length of s + derBytes.AddRange(sBytes); + return derBytes.ToArray(); + } + + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPhrase = null) + { + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; + bool isPrivateKeyFile = true; + byte[] pemkey = null; + + string pemstr = string.Empty; + if (File.Exists(pemfile)) + { + pemstr = File.ReadAllText(pemfile).Trim(); + } + else + { + pemstr = pemfile; + } + + if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) + { + isPrivateKeyFile = false; + } + + if (isPrivateKeyFile) + { + pemkey = ConvertPrivateKeyToBytes(pemstr, keyPassPhrase); + if (pemkey == null) + { + return null; + } + return DecodeRSAPrivateKey(pemkey); + } + return null; + } + + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPhrase = null) + { + const string pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; + const string pemprivfooter = "-----END RSA PRIVATE KEY-----"; + string pemstr = instr.Trim(); + byte[] binkey; + + if (!pemstr.StartsWith(pemprivheader) || !pemstr.EndsWith(pemprivfooter)) + { + return null; + } + + StringBuilder sb = new StringBuilder(pemstr); + sb.Replace(pemprivheader, ""); + sb.Replace(pemprivfooter, ""); + string pvkstr = sb.ToString().Trim(); + + try + { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key + binkey = Convert.FromBase64String(pvkstr); + return binkey; + } + catch (System.FormatException) + { + StringReader str = new StringReader(pvkstr); + + //-------- read PEM encryption info. lines and extract salt ----- + if (!str.ReadLine().StartsWith("Proc-Type: 4,ENCRYPTED")) + { + return null; + } + string saltline = str.ReadLine(); + if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) + { + return null; + } + string saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + byte[] salt = new byte[saltstr.Length / 2]; + for (int i = 0; i < salt.Length; i++) + salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); + if (str.ReadLine() != "") + { + return null; + } + + //------ remaining b64 data is encrypted RSA key ---- + string encryptedstr = str.ReadToEnd(); + + try + { //should have b64 encrypted RSA key now + binkey = Convert.FromBase64String(encryptedstr); + } + catch (System.FormatException) + { //data is not in base64 format + return null; + } + + byte[] deskey = GetEncryptedKey(salt, keyPassPhrase, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes + if (deskey == null) + { + return null; + } + + //------ Decrypt the encrypted 3des-encrypted RSA private key ------ + byte[] rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV + return rsakey; + } + } + + private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) + { + byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ; + + // --------- Set up stream to decode the asn.1 encoded RSA private key ------ + MemoryStream mem = new MemoryStream(privkey); + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + int elems = 0; + try + { + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + { + binr.ReadByte(); //advance 1 byte + } + else if (twobytes == 0x8230) + { + binr.ReadInt16(); //advance 2 bytes + } + else + { + return null; + } + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) //version number + { + return null; + } + bt = binr.ReadByte(); + if (bt != 0x00) + { + return null; + } + + //------ all private key components are Integer sequences ---- + elems = GetIntegerSize(binr); + bytesModulus = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesE = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesD = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesDP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesDQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesIQ = binr.ReadBytes(elems); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSAParameters RSAparams = new RSAParameters(); + RSAparams.Modulus = bytesModulus; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDP; + RSAparams.DQ = bytesDQ; + RSAparams.InverseQ = bytesIQ; + RSA.ImportParameters(RSAparams); + return RSA; + } + catch (Exception) + { + return null; + } + finally + { + binr.Close(); + } + } + + private int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + byte lowbyte = 0x00; + byte highbyte = 0x00; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) //expect integer + { + return 0; + } + bt = binr.ReadByte(); + + if (bt == 0x81) + { + count = binr.ReadByte(); // data size in next byte + } + else if (bt == 0x82) + { + highbyte = binr.ReadByte(); // data size in next 2 bytes + lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; // we already have the data size + } + while (binr.ReadByte() == 0x00) + { + //remove high order zeros in data + count -= 1; + } + binr.BaseStream.Seek(-1, SeekOrigin.Current); + //last ReadByte wasn't a removed zero, so back up a byte + return count; + } + + private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) + { + IntPtr unmanagedPswd = IntPtr.Zero; + const int HASHLENGTH = 16; //MD5 bytes + byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results + + byte[] psbytes = new byte[secpswd.Length]; + unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); + Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); + Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); + + // --- concatenate salt and pswd bytes into fixed data array --- + byte[] data00 = new byte[psbytes.Length + salt.Length]; + Array.Copy(psbytes, data00, psbytes.Length); //copy the pswd bytes + Array.Copy(salt, 0, data00, psbytes.Length, salt.Length); //concatenate the salt bytes + + // ---- do multi-hashing and concatenate results D1, D2 ... into keymaterial bytes ---- + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] result = null; + byte[] hashtarget = new byte[HASHLENGTH + data00.Length]; //fixed length initial hashtarget + + for (int j = 0; j < miter; j++) + { + // ---- Now hash consecutively for count times ------ + if (j == 0) + { + result = data00; //initialize + } + else + { + Array.Copy(result, hashtarget, result.Length); + Array.Copy(data00, 0, hashtarget, result.Length, data00.Length); + result = hashtarget; + } + + for (int i = 0; i < count; i++) + { + result = md5.ComputeHash(result); + } + Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial + } + byte[] deskey = new byte[24]; + Array.Copy(keymaterial, deskey, deskey.Length); + + Array.Clear(psbytes, 0, psbytes.Length); + Array.Clear(data00, 0, data00.Length); + Array.Clear(result, 0, result.Length); + Array.Clear(hashtarget, 0, hashtarget.Length); + Array.Clear(keymaterial, 0, keymaterial.Length); + return deskey; + } + + private byte[] DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) + { + MemoryStream memst = new MemoryStream(); + TripleDES alg = TripleDES.Create(); + alg.Key = desKey; + alg.IV = IV; + try + { + CryptoStream cs = new CryptoStream(memst, alg.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(cipherData, 0, cipherData.Length); + cs.Close(); + } + catch (Exception) + { + return null; + } + byte[] decryptedData = memst.ToArray(); + return decryptedData; + } + + /// + /// Detect the key type from the pem file. + /// + /// key file path in pem format + /// Private Key Type + private PrivateKeyType GetKeyType(string keyFilePath) + { + string[] key = null; + + if (File.Exists(keyFilePath)) + { + key = File.ReadAllLines(keyFilePath); + } + else + { + // The ApiKeyFilePath is passed as string + key = new string[] { keyFilePath }; + } + + const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + const string ecPrivateKeyFooter = "END EC PRIVATE KEY"; + const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + const string rsaPrivateFooter = "END RSA PRIVATE KEY"; + //var pkcs8Header = "BEGIN PRIVATE KEY"; + //var pkcs8Footer = "END PRIVATE KEY"; + PrivateKeyType keyType; + + if (key[0].Contains(rsaPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) + { + keyType = PrivateKeyType.RSA; + } + else if (key[0].Contains(ecPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + { + keyType = PrivateKeyType.ECDSA; + } + else + { + throw new Exception("The key file path does not exist or key is invalid or key is not supported"); + } + return keyType; + } + #endregion + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/IApiAccessor.cs new file mode 100644 index 0000000000..2bd7641600 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + IReadableConfiguration Configuration { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + string GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/IAsynchronousClient.cs new file mode 100644 index 0000000000..601e86d561 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -0,0 +1,100 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; + +namespace Org.OpenAPITools.Client +{ + /// + /// Contract for Asynchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface IAsynchronousClient + { + /// + /// Executes a non-blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/IReadableConfiguration.cs new file mode 100644 index 0000000000..c9615dc5aa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -0,0 +1,159 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Net; +using System.Security.Cryptography.X509Certificates; +using Org.OpenAPITools.Client.Auth; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a readable-only configuration contract. + /// + public interface IReadableConfiguration + { + /// + /// Gets the access token. + /// + /// Access token. + string AccessToken { get; } + + /// + /// Gets the OAuth token URL. + /// + /// OAuth Token URL. + string OAuthTokenUrl { get; } + + /// + /// Gets the OAuth client ID. + /// + /// OAuth Client ID. + string OAuthClientId { get; } + + /// + /// Gets the OAuth client secret. + /// + /// OAuth Client Secret. + string OAuthClientSecret { get; } + + /// + /// Gets the OAuth flow. + /// + /// OAuth Flow. + OAuthFlow? OAuthFlow { get; } + + /// + /// Gets the API key. + /// + /// API key. + IDictionary ApiKey { get; } + + /// + /// Gets the API key prefix. + /// + /// API key prefix. + IDictionary ApiKeyPrefix { get; } + + /// + /// Gets the base path. + /// + /// Base path. + string BasePath { get; } + + /// + /// Gets the date time format. + /// + /// Date time format. + string DateTimeFormat { get; } + + /// + /// Gets the default header. + /// + /// Default header. + [Obsolete("Use DefaultHeaders instead.")] + IDictionary DefaultHeader { get; } + + /// + /// Gets the default headers. + /// + /// Default headers. + IDictionary DefaultHeaders { get; } + + /// + /// Gets the temp folder path. + /// + /// Temp folder path. + string TempFolderPath { get; } + + /// + /// Gets the HTTP connection timeout (in milliseconds) + /// + /// HTTP connection timeout. + int Timeout { get; } + + /// + /// Gets the proxy. + /// + /// Proxy. + WebProxy Proxy { get; } + + /// + /// Gets the user agent. + /// + /// User agent. + string UserAgent { get; } + + /// + /// Gets the username. + /// + /// Username. + string Username { get; } + + /// + /// Gets the password. + /// + /// Password. + string Password { get; } + + /// + /// Get the servers associated with the operation. + /// + /// Operation servers. + IReadOnlyDictionary>> OperationServers { get; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + + /// + /// Gets the Operation server url at the provided index. + /// + /// Operation server name. + /// Index of the operation server settings. + /// + string GetOperationServerUrl(string operation, int index); + + /// + /// Gets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + X509CertificateCollection ClientCertificates { get; } + + /// + /// Gets the HttpSigning configuration + /// + HttpSigningConfiguration HttpSigningConfiguration { get; } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ISynchronousClient.cs new file mode 100644 index 0000000000..0e0a7fedac --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -0,0 +1,93 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.IO; + +namespace Org.OpenAPITools.Client +{ + /// + /// Contract for Synchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface ISynchronousClient + { + /// + /// Executes a blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Multimap.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Multimap.cs new file mode 100644 index 0000000000..738a64c570 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/Multimap.cs @@ -0,0 +1,295 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A dictionary in which one key has many associated values. + /// + /// The type of the key + /// The type of the value associated with the key. + public class Multimap : IDictionary> + { + #region Private Fields + + private readonly Dictionary> _dictionary; + + #endregion Private Fields + + #region Constructors + + /// + /// Empty Constructor. + /// + public Multimap() + { + _dictionary = new Dictionary>(); + } + + /// + /// Constructor with comparer. + /// + /// + public Multimap(IEqualityComparer comparer) + { + _dictionary = new Dictionary>(comparer); + } + + #endregion Constructors + + #region Enumerators + + /// + /// To get the enumerator. + /// + /// Enumerator + public IEnumerator>> GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + /// + /// To get the enumerator. + /// + /// Enumerator + IEnumerator IEnumerable.GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + #endregion Enumerators + + #region Public Members + /// + /// Add values to Multimap + /// + /// Key value pair + public void Add(KeyValuePair> item) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + + /// + /// Add Multimap to Multimap + /// + /// Multimap + public void Add(Multimap multimap) + { + foreach (var item in multimap) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + + /// + /// Clear Multimap + /// + public void Clear() + { + _dictionary.Clear(); + } + + /// + /// Determines whether Multimap contains the specified item. + /// + /// Key value pair + /// Method needs to be implemented + /// true if the Multimap contains the item; otherwise, false. + public bool Contains(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Copy items of the Multimap to an array, + /// starting at a particular array index. + /// + /// The array that is the destination of the items copied + /// from Multimap. The array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + /// Method needs to be implemented + public void CopyTo(KeyValuePair>[] array, int arrayIndex) + { + throw new NotImplementedException(); + } + + /// + /// Removes the specified item from the Multimap. + /// + /// Key value pair + /// true if the item is successfully removed; otherwise, false. + /// Method needs to be implemented + public bool Remove(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Gets the number of items contained in the Multimap. + /// + public int Count => _dictionary.Count; + + /// + /// Gets a value indicating whether the Multimap is read-only. + /// + public bool IsReadOnly => false; + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add the value to Multimap. + public void Add(TKey key, IList value) + { + if (value != null && value.Count > 0) + { + if (_dictionary.TryGetValue(key, out var list)) + { + foreach (var k in value) list.Add(k); + } + else + { + list = new List(value); + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + } + + /// + /// Determines whether the Multimap contains an item with the specified key. + /// + /// The key to locate in the Multimap. + /// true if the Multimap contains an item with + /// the key; otherwise, false. + public bool ContainsKey(TKey key) + { + return _dictionary.ContainsKey(key); + } + + /// + /// Removes item with the specified key from the Multimap. + /// + /// The key to locate in the Multimap. + /// true if the item is successfully removed; otherwise, false. + public bool Remove(TKey key) + { + return TryRemove(key, out var _); + } + + /// + /// Gets the value associated with the specified key. + /// + /// The key whose value to get. + /// When this method returns, the value associated with the specified key, if the + /// key is found; otherwise, the default value for the type of the value parameter. + /// This parameter is passed uninitialized. + /// true if the object that implements Multimap contains + /// an item with the specified key; otherwise, false. + public bool TryGetValue(TKey key, out IList value) + { + return _dictionary.TryGetValue(key, out value); + } + + /// + /// Gets or sets the item with the specified key. + /// + /// The key of the item to get or set. + /// The value of the specified key. + public IList this[TKey key] + { + get => _dictionary[key]; + set => _dictionary[key] = value; + } + + /// + /// Gets a System.Collections.Generic.ICollection containing the keys of the Multimap. + /// + public ICollection Keys => _dictionary.Keys; + + /// + /// Gets a System.Collections.Generic.ICollection containing the values of the Multimap. + /// + public ICollection> Values => _dictionary.Values; + + /// + /// Copy the items of the Multimap to an System.Array, + /// starting at a particular System.Array index. + /// + /// The one-dimensional System.Array that is the destination of the items copied + /// from Multimap. The System.Array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + public void CopyTo(Array array, int index) + { + ((ICollection)_dictionary).CopyTo(array, index); + } + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add value to Multimap. + public void Add(TKey key, TValue value) + { + if (value != null) + { + if (_dictionary.TryGetValue(key, out var list)) + { + list.Add(value); + } + else + { + list = new List { value }; + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add value to Multimap."); + } + } + } + + #endregion Public Members + + #region Private Members + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryRemove(TKey key, out IList value) + { + _dictionary.TryGetValue(key, out value); + return _dictionary.Remove(key); + } + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryAdd(TKey key, IList value) + { + try + { + _dictionary.Add(key, value); + } + catch (ArgumentException) + { + return false; + } + + return true; + } + #endregion Private Members + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs new file mode 100644 index 0000000000..a5253e5820 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs @@ -0,0 +1,29 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using Newtonsoft.Json.Converters; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/RequestOptions.cs new file mode 100644 index 0000000000..4c26cf69b2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -0,0 +1,89 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Multimap FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Operation associated with the request path. + /// + public string Operation { get; set; } + + /// + /// Index associated with the operation. + /// + public int OperationIndex { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// If request should be authenticated with OAuth. + /// + public bool OAuth { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Multimap(); + Cookies = new List(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/RetryConfiguration.cs new file mode 100644 index 0000000000..7011f69e77 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -0,0 +1,31 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Polly; +using RestSharp; + +namespace Org.OpenAPITools.Client +{ + /// + /// Configuration class to set the polly retry policies to be applied to the requests. + /// + public static class RetryConfiguration + { + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs new file mode 100644 index 0000000000..b3fc4c3c7a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs @@ -0,0 +1,76 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Org.OpenAPITools.Model +{ + /// + /// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification + /// + public abstract partial class AbstractOpenAPISchema + { + /// + /// Custom JSON serializer + /// + static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Error, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Custom JSON serializer for objects with additional properties + /// + static public readonly JsonSerializerSettings AdditionalPropertiesSerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Ignore, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Gets or Sets the actual instance + /// + public abstract Object ActualInstance { get; set; } + + /// + /// Gets or Sets IsNullable to indicate whether the instance is nullable + /// + public bool IsNullable { get; protected set; } + + /// + /// Gets or Sets the schema type, which can be either `oneOf` or `anyOf` + /// + public string SchemaType { get; protected set; } + + /// + /// Converts the instance into JSON string. + /// + public abstract string ToJson(); + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs new file mode 100644 index 0000000000..b3ddad35a0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -0,0 +1,224 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// AdditionalPropertiesClass + /// + [DataContract(Name = "AdditionalPropertiesClass")] + public partial class AdditionalPropertiesClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// mapProperty. + /// mapOfMapProperty. + /// anytype1. + /// mapWithUndeclaredPropertiesAnytype1. + /// mapWithUndeclaredPropertiesAnytype2. + /// mapWithUndeclaredPropertiesAnytype3. + /// an object with no declared properties and no undeclared properties, hence it's an empty map.. + /// mapWithUndeclaredPropertiesString. + public AdditionalPropertiesClass(Dictionary mapProperty = default(Dictionary), Dictionary> mapOfMapProperty = default(Dictionary>), Object anytype1 = default(Object), Object mapWithUndeclaredPropertiesAnytype1 = default(Object), Object mapWithUndeclaredPropertiesAnytype2 = default(Object), Dictionary mapWithUndeclaredPropertiesAnytype3 = default(Dictionary), Object emptyMap = default(Object), Dictionary mapWithUndeclaredPropertiesString = default(Dictionary)) + { + this.MapProperty = mapProperty; + this.MapOfMapProperty = mapOfMapProperty; + this.Anytype1 = anytype1; + this.MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; + this.MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; + this.MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; + this.EmptyMap = emptyMap; + this.MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets MapProperty + /// + [DataMember(Name = "map_property", EmitDefaultValue = false)] + public Dictionary MapProperty { get; set; } + + /// + /// Gets or Sets MapOfMapProperty + /// + [DataMember(Name = "map_of_map_property", EmitDefaultValue = false)] + public Dictionary> MapOfMapProperty { get; set; } + + /// + /// Gets or Sets Anytype1 + /// + [DataMember(Name = "anytype_1", EmitDefaultValue = true)] + public Object Anytype1 { get; set; } + + /// + /// Gets or Sets MapWithUndeclaredPropertiesAnytype1 + /// + [DataMember(Name = "map_with_undeclared_properties_anytype_1", EmitDefaultValue = false)] + public Object MapWithUndeclaredPropertiesAnytype1 { get; set; } + + /// + /// Gets or Sets MapWithUndeclaredPropertiesAnytype2 + /// + [DataMember(Name = "map_with_undeclared_properties_anytype_2", EmitDefaultValue = false)] + public Object MapWithUndeclaredPropertiesAnytype2 { get; set; } + + /// + /// Gets or Sets MapWithUndeclaredPropertiesAnytype3 + /// + [DataMember(Name = "map_with_undeclared_properties_anytype_3", EmitDefaultValue = false)] + public Dictionary MapWithUndeclaredPropertiesAnytype3 { get; set; } + + /// + /// an object with no declared properties and no undeclared properties, hence it's an empty map. + /// + /// an object with no declared properties and no undeclared properties, hence it's an empty map. + [DataMember(Name = "empty_map", EmitDefaultValue = false)] + public Object EmptyMap { get; set; } + + /// + /// Gets or Sets MapWithUndeclaredPropertiesString + /// + [DataMember(Name = "map_with_undeclared_properties_string", EmitDefaultValue = false)] + public Dictionary MapWithUndeclaredPropertiesString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AdditionalPropertiesClass {\n"); + sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); + sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); + sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesAnytype1: ").Append(MapWithUndeclaredPropertiesAnytype1).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesAnytype2: ").Append(MapWithUndeclaredPropertiesAnytype2).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesAnytype3: ").Append(MapWithUndeclaredPropertiesAnytype3).Append("\n"); + sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesString: ").Append(MapWithUndeclaredPropertiesString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesClass).AreEqual; + } + + /// + /// Returns true if AdditionalPropertiesClass instances are equal + /// + /// Instance of AdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(AdditionalPropertiesClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.MapProperty != null) + { + hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); + } + if (this.MapOfMapProperty != null) + { + hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); + } + if (this.Anytype1 != null) + { + hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); + } + if (this.MapWithUndeclaredPropertiesAnytype1 != null) + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + } + if (this.MapWithUndeclaredPropertiesAnytype2 != null) + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + } + if (this.MapWithUndeclaredPropertiesAnytype3 != null) + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + } + if (this.EmptyMap != null) + { + hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); + } + if (this.MapWithUndeclaredPropertiesString != null) + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Animal.cs new file mode 100644 index 0000000000..83397018b7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Animal.cs @@ -0,0 +1,173 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Animal + /// + [DataContract(Name = "Animal")] + [JsonConverter(typeof(JsonSubtypes), "ClassName")] + [JsonSubtypes.KnownSubType(typeof(Cat), "Cat")] + [JsonSubtypes.KnownSubType(typeof(Dog), "Dog")] + public partial class Animal : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Animal() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// className (required). + /// color (default to "red"). + public Animal(string className = default(string), string color = "red") + { + // to ensure "className" is required (not null) + if (className == null) + { + throw new ArgumentNullException("className is a required property for Animal and cannot be null"); + } + this.ClassName = className; + // use default value if no "color" provided + this.Color = color ?? "red"; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] + public string ClassName { get; set; } + + /// + /// Gets or Sets Color + /// + [DataMember(Name = "color", EmitDefaultValue = false)] + public string Color { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Animal {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Animal).AreEqual; + } + + /// + /// Returns true if Animal instances are equal + /// + /// Instance of Animal to be compared + /// Boolean + public bool Equals(Animal input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ClassName != null) + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } + if (this.Color != null) + { + hashCode = (hashCode * 59) + this.Color.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ApiResponse.cs new file mode 100644 index 0000000000..79873f4ddf --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -0,0 +1,155 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ApiResponse + /// + [DataContract(Name = "ApiResponse")] + public partial class ApiResponse : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// code. + /// type. + /// message. + public ApiResponse(int code = default(int), string type = default(string), string message = default(string)) + { + this.Code = code; + this.Type = type; + this.Message = message; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Code + /// + [DataMember(Name = "code", EmitDefaultValue = false)] + public int Code { get; set; } + + /// + /// Gets or Sets Type + /// + [DataMember(Name = "type", EmitDefaultValue = false)] + public string Type { get; set; } + + /// + /// Gets or Sets Message + /// + [DataMember(Name = "message", EmitDefaultValue = false)] + public string Message { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ApiResponse {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ApiResponse).AreEqual; + } + + /// + /// Returns true if ApiResponse instances are equal + /// + /// Instance of ApiResponse to be compared + /// Boolean + public bool Equals(ApiResponse input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.Code.GetHashCode(); + if (this.Type != null) + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } + if (this.Message != null) + { + hashCode = (hashCode * 59) + this.Message.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Apple.cs new file mode 100644 index 0000000000..8b1f87d1aa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Apple.cs @@ -0,0 +1,159 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Apple + /// + [DataContract(Name = "apple")] + public partial class Apple : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// cultivar. + /// origin. + public Apple(string cultivar = default(string), string origin = default(string)) + { + this.Cultivar = cultivar; + this.Origin = origin; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Cultivar + /// + [DataMember(Name = "cultivar", EmitDefaultValue = false)] + public string Cultivar { get; set; } + + /// + /// Gets or Sets Origin + /// + [DataMember(Name = "origin", EmitDefaultValue = false)] + public string Origin { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Apple {\n"); + sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); + sb.Append(" Origin: ").Append(Origin).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Apple).AreEqual; + } + + /// + /// Returns true if Apple instances are equal + /// + /// Instance of Apple to be compared + /// Boolean + public bool Equals(Apple input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Cultivar != null) + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } + if (this.Origin != null) + { + hashCode = (hashCode * 59) + this.Origin.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + // Cultivar (string) pattern + Regex regexCultivar = new Regex(@"^[a-zA-Z\\s]*$", RegexOptions.CultureInvariant); + if (false == regexCultivar.Match(this.Cultivar).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cultivar, must match a pattern of " + regexCultivar, new [] { "Cultivar" }); + } + + // Origin (string) pattern + Regex regexOrigin = new Regex(@"^[A-Z\\s]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regexOrigin.Match(this.Origin).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, must match a pattern of " + regexOrigin, new [] { "Origin" }); + } + + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/AppleReq.cs new file mode 100644 index 0000000000..9e09e2da8c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/AppleReq.cs @@ -0,0 +1,140 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// AppleReq + /// + [DataContract(Name = "appleReq")] + public partial class AppleReq : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected AppleReq() { } + /// + /// Initializes a new instance of the class. + /// + /// cultivar (required). + /// mealy. + public AppleReq(string cultivar = default(string), bool mealy = default(bool)) + { + // to ensure "cultivar" is required (not null) + if (cultivar == null) + { + throw new ArgumentNullException("cultivar is a required property for AppleReq and cannot be null"); + } + this.Cultivar = cultivar; + this.Mealy = mealy; + } + + /// + /// Gets or Sets Cultivar + /// + [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = true)] + public string Cultivar { get; set; } + + /// + /// Gets or Sets Mealy + /// + [DataMember(Name = "mealy", EmitDefaultValue = true)] + public bool Mealy { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class AppleReq {\n"); + sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); + sb.Append(" Mealy: ").Append(Mealy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as AppleReq).AreEqual; + } + + /// + /// Returns true if AppleReq instances are equal + /// + /// Instance of AppleReq to be compared + /// Boolean + public bool Equals(AppleReq input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Cultivar != null) + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs new file mode 100644 index 0000000000..30bf57ef0f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ArrayOfArrayOfNumberOnly + /// + [DataContract(Name = "ArrayOfArrayOfNumberOnly")] + public partial class ArrayOfArrayOfNumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayArrayNumber. + public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber = default(List>)) + { + this.ArrayArrayNumber = arrayArrayNumber; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ArrayArrayNumber + /// + [DataMember(Name = "ArrayArrayNumber", EmitDefaultValue = false)] + public List> ArrayArrayNumber { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ArrayOfArrayOfNumberOnly {\n"); + sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ArrayOfArrayOfNumberOnly).AreEqual; + } + + /// + /// Returns true if ArrayOfArrayOfNumberOnly instances are equal + /// + /// Instance of ArrayOfArrayOfNumberOnly to be compared + /// Boolean + public bool Equals(ArrayOfArrayOfNumberOnly input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ArrayArrayNumber != null) + { + hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs new file mode 100644 index 0000000000..8a215aad13 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ArrayOfNumberOnly + /// + [DataContract(Name = "ArrayOfNumberOnly")] + public partial class ArrayOfNumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayNumber. + public ArrayOfNumberOnly(List arrayNumber = default(List)) + { + this.ArrayNumber = arrayNumber; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ArrayNumber + /// + [DataMember(Name = "ArrayNumber", EmitDefaultValue = false)] + public List ArrayNumber { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ArrayOfNumberOnly {\n"); + sb.Append(" ArrayNumber: ").Append(ArrayNumber).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ArrayOfNumberOnly).AreEqual; + } + + /// + /// Returns true if ArrayOfNumberOnly instances are equal + /// + /// Instance of ArrayOfNumberOnly to be compared + /// Boolean + public bool Equals(ArrayOfNumberOnly input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ArrayNumber != null) + { + hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ArrayTest.cs new file mode 100644 index 0000000000..1a879a1d9c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -0,0 +1,158 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ArrayTest + /// + [DataContract(Name = "ArrayTest")] + public partial class ArrayTest : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayOfString. + /// arrayArrayOfInteger. + /// arrayArrayOfModel. + public ArrayTest(List arrayOfString = default(List), List> arrayArrayOfInteger = default(List>), List> arrayArrayOfModel = default(List>)) + { + this.ArrayOfString = arrayOfString; + this.ArrayArrayOfInteger = arrayArrayOfInteger; + this.ArrayArrayOfModel = arrayArrayOfModel; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ArrayOfString + /// + [DataMember(Name = "array_of_string", EmitDefaultValue = false)] + public List ArrayOfString { get; set; } + + /// + /// Gets or Sets ArrayArrayOfInteger + /// + [DataMember(Name = "array_array_of_integer", EmitDefaultValue = false)] + public List> ArrayArrayOfInteger { get; set; } + + /// + /// Gets or Sets ArrayArrayOfModel + /// + [DataMember(Name = "array_array_of_model", EmitDefaultValue = false)] + public List> ArrayArrayOfModel { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ArrayTest {\n"); + sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); + sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); + sb.Append(" ArrayArrayOfModel: ").Append(ArrayArrayOfModel).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ArrayTest).AreEqual; + } + + /// + /// Returns true if ArrayTest instances are equal + /// + /// Instance of ArrayTest to be compared + /// Boolean + public bool Equals(ArrayTest input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ArrayOfString != null) + { + hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); + } + if (this.ArrayArrayOfInteger != null) + { + hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); + } + if (this.ArrayArrayOfModel != null) + { + hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Banana.cs new file mode 100644 index 0000000000..97939597ed --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Banana.cs @@ -0,0 +1,129 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Banana + /// + [DataContract(Name = "banana")] + public partial class Banana : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// lengthCm. + public Banana(decimal lengthCm = default(decimal)) + { + this.LengthCm = lengthCm; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets LengthCm + /// + [DataMember(Name = "lengthCm", EmitDefaultValue = false)] + public decimal LengthCm { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Banana {\n"); + sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Banana).AreEqual; + } + + /// + /// Returns true if Banana instances are equal + /// + /// Instance of Banana to be compared + /// Boolean + public bool Equals(Banana input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/BananaReq.cs new file mode 100644 index 0000000000..3edb9a1b6d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/BananaReq.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// BananaReq + /// + [DataContract(Name = "bananaReq")] + public partial class BananaReq : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected BananaReq() { } + /// + /// Initializes a new instance of the class. + /// + /// lengthCm (required). + /// sweet. + public BananaReq(decimal lengthCm = default(decimal), bool sweet = default(bool)) + { + this.LengthCm = lengthCm; + this.Sweet = sweet; + } + + /// + /// Gets or Sets LengthCm + /// + [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = true)] + public decimal LengthCm { get; set; } + + /// + /// Gets or Sets Sweet + /// + [DataMember(Name = "sweet", EmitDefaultValue = true)] + public bool Sweet { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BananaReq {\n"); + sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); + sb.Append(" Sweet: ").Append(Sweet).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as BananaReq).AreEqual; + } + + /// + /// Returns true if BananaReq instances are equal + /// + /// Instance of BananaReq to be compared + /// Boolean + public bool Equals(BananaReq input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/BasquePig.cs new file mode 100644 index 0000000000..f65f049cfd --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/BasquePig.cs @@ -0,0 +1,145 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// BasquePig + /// + [DataContract(Name = "BasquePig")] + public partial class BasquePig : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected BasquePig() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// className (required). + public BasquePig(string className = default(string)) + { + // to ensure "className" is required (not null) + if (className == null) + { + throw new ArgumentNullException("className is a required property for BasquePig and cannot be null"); + } + this.ClassName = className; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] + public string ClassName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BasquePig {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as BasquePig).AreEqual; + } + + /// + /// Returns true if BasquePig instances are equal + /// + /// Instance of BasquePig to be compared + /// Boolean + public bool Equals(BasquePig input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ClassName != null) + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Capitalization.cs new file mode 100644 index 0000000000..be68a50a11 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Capitalization.cs @@ -0,0 +1,198 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Capitalization + /// + [DataContract(Name = "Capitalization")] + public partial class Capitalization : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// smallCamel. + /// capitalCamel. + /// smallSnake. + /// capitalSnake. + /// sCAETHFlowPoints. + /// Name of the pet . + public Capitalization(string smallCamel = default(string), string capitalCamel = default(string), string smallSnake = default(string), string capitalSnake = default(string), string sCAETHFlowPoints = default(string), string aTTNAME = default(string)) + { + this.SmallCamel = smallCamel; + this.CapitalCamel = capitalCamel; + this.SmallSnake = smallSnake; + this.CapitalSnake = capitalSnake; + this.SCAETHFlowPoints = sCAETHFlowPoints; + this.ATT_NAME = aTTNAME; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets SmallCamel + /// + [DataMember(Name = "smallCamel", EmitDefaultValue = false)] + public string SmallCamel { get; set; } + + /// + /// Gets or Sets CapitalCamel + /// + [DataMember(Name = "CapitalCamel", EmitDefaultValue = false)] + public string CapitalCamel { get; set; } + + /// + /// Gets or Sets SmallSnake + /// + [DataMember(Name = "small_Snake", EmitDefaultValue = false)] + public string SmallSnake { get; set; } + + /// + /// Gets or Sets CapitalSnake + /// + [DataMember(Name = "Capital_Snake", EmitDefaultValue = false)] + public string CapitalSnake { get; set; } + + /// + /// Gets or Sets SCAETHFlowPoints + /// + [DataMember(Name = "SCA_ETH_Flow_Points", EmitDefaultValue = false)] + public string SCAETHFlowPoints { get; set; } + + /// + /// Name of the pet + /// + /// Name of the pet + [DataMember(Name = "ATT_NAME", EmitDefaultValue = false)] + public string ATT_NAME { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Capitalization {\n"); + sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); + sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); + sb.Append(" SmallSnake: ").Append(SmallSnake).Append("\n"); + sb.Append(" CapitalSnake: ").Append(CapitalSnake).Append("\n"); + sb.Append(" SCAETHFlowPoints: ").Append(SCAETHFlowPoints).Append("\n"); + sb.Append(" ATT_NAME: ").Append(ATT_NAME).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Capitalization).AreEqual; + } + + /// + /// Returns true if Capitalization instances are equal + /// + /// Instance of Capitalization to be compared + /// Boolean + public bool Equals(Capitalization input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.SmallCamel != null) + { + hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); + } + if (this.CapitalCamel != null) + { + hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); + } + if (this.SmallSnake != null) + { + hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); + } + if (this.CapitalSnake != null) + { + hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); + } + if (this.SCAETHFlowPoints != null) + { + hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); + } + if (this.ATT_NAME != null) + { + hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Cat.cs new file mode 100644 index 0000000000..86ceaeed1a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Cat.cs @@ -0,0 +1,156 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Cat + /// + [DataContract(Name = "Cat")] + [JsonConverter(typeof(JsonSubtypes), "ClassName")] + public partial class Cat : Animal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Cat() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// declawed. + /// className (required) (default to "Cat"). + /// color (default to "red"). + public Cat(bool declawed = default(bool), string className = "Cat", string color = "red") : base(className, color) + { + this.Declawed = declawed; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Declawed + /// + [DataMember(Name = "declawed", EmitDefaultValue = true)] + public bool Declawed { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Cat {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" Declawed: ").Append(Declawed).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Cat).AreEqual; + } + + /// + /// Returns true if Cat instances are equal + /// + /// Instance of Cat to be compared + /// Boolean + public bool Equals(Cat input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + foreach (var x in base.BaseValidate(validationContext)) + { + yield return x; + } + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/CatAllOf.cs new file mode 100644 index 0000000000..3a960e9925 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -0,0 +1,129 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// CatAllOf + /// + [DataContract(Name = "Cat_allOf")] + public partial class CatAllOf : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// declawed. + public CatAllOf(bool declawed = default(bool)) + { + this.Declawed = declawed; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Declawed + /// + [DataMember(Name = "declawed", EmitDefaultValue = true)] + public bool Declawed { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CatAllOf {\n"); + sb.Append(" Declawed: ").Append(Declawed).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as CatAllOf).AreEqual; + } + + /// + /// Returns true if CatAllOf instances are equal + /// + /// Instance of CatAllOf to be compared + /// Boolean + public bool Equals(CatAllOf input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Category.cs new file mode 100644 index 0000000000..94dea2b30b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Category.cs @@ -0,0 +1,155 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Category + /// + [DataContract(Name = "Category")] + public partial class Category : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Category() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// id. + /// name (required) (default to "default-name"). + public Category(long id = default(long), string name = "default-name") + { + // to ensure "name" is required (not null) + if (name == null) + { + throw new ArgumentNullException("name is a required property for Category and cannot be null"); + } + this.Name = name; + this.Id = id; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] + public string Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Category {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Category).AreEqual; + } + + /// + /// Returns true if Category instances are equal + /// + /// Instance of Category to be compared + /// Boolean + public bool Equals(Category input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + if (this.Name != null) + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCat.cs new file mode 100644 index 0000000000..2aa81264fa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCat.cs @@ -0,0 +1,173 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ChildCat + /// + [DataContract(Name = "ChildCat")] + [JsonConverter(typeof(JsonSubtypes), "PetType")] + public partial class ChildCat : ParentPet, IEquatable, IValidatableObject + { + /// + /// Defines PetType + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum PetTypeEnum + { + /// + /// Enum ChildCat for value: ChildCat + /// + [EnumMember(Value = "ChildCat")] + ChildCat = 1 + + } + + + /// + /// Gets or Sets PetType + /// + [DataMember(Name = "pet_type", EmitDefaultValue = false)] + public PetTypeEnum? PetType { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// name. + /// petType (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() + { + this.Name = name; + this.PetType = petType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ChildCat {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PetType: ").Append(PetType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ChildCat).AreEqual; + } + + /// + /// Returns true if ChildCat instances are equal + /// + /// Instance of ChildCat to be compared + /// Boolean + public bool Equals(ChildCat input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + if (this.Name != null) + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + foreach (var x in base.BaseValidate(validationContext)) + { + yield return x; + } + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCatAllOf.cs new file mode 100644 index 0000000000..a353ad7ffd --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -0,0 +1,156 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ChildCatAllOf + /// + [DataContract(Name = "ChildCat_allOf")] + public partial class ChildCatAllOf : IEquatable, IValidatableObject + { + /// + /// Defines PetType + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum PetTypeEnum + { + /// + /// Enum ChildCat for value: ChildCat + /// + [EnumMember(Value = "ChildCat")] + ChildCat = 1 + + } + + + /// + /// Gets or Sets PetType + /// + [DataMember(Name = "pet_type", EmitDefaultValue = false)] + public PetTypeEnum? PetType { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// name. + /// petType (default to PetTypeEnum.ChildCat). + public ChildCatAllOf(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) + { + this.Name = name; + this.PetType = petType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ChildCatAllOf {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PetType: ").Append(PetType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ChildCatAllOf).AreEqual; + } + + /// + /// Returns true if ChildCatAllOf instances are equal + /// + /// Instance of ChildCatAllOf to be compared + /// Boolean + public bool Equals(ChildCatAllOf input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Name != null) + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ClassModel.cs new file mode 100644 index 0000000000..7177e9bf0b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ClassModel.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Model for testing model with \"_class\" property + /// + [DataContract(Name = "ClassModel")] + public partial class ClassModel : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _class. + public ClassModel(string _class = default(string)) + { + this.Class = _class; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Class + /// + [DataMember(Name = "_class", EmitDefaultValue = false)] + public string Class { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ClassModel {\n"); + sb.Append(" Class: ").Append(Class).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ClassModel).AreEqual; + } + + /// + /// Returns true if ClassModel instances are equal + /// + /// Instance of ClassModel to be compared + /// Boolean + public bool Equals(ClassModel input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Class != null) + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs new file mode 100644 index 0000000000..353ea1d081 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ComplexQuadrilateral + /// + [DataContract(Name = "ComplexQuadrilateral")] + public partial class ComplexQuadrilateral : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ComplexQuadrilateral() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// quadrilateralType (required). + public ComplexQuadrilateral(string shapeType = default(string), string quadrilateralType = default(string)) + { + // to ensure "shapeType" is required (not null) + if (shapeType == null) + { + throw new ArgumentNullException("shapeType is a required property for ComplexQuadrilateral and cannot be null"); + } + this.ShapeType = shapeType; + // to ensure "quadrilateralType" is required (not null) + if (quadrilateralType == null) + { + throw new ArgumentNullException("quadrilateralType is a required property for ComplexQuadrilateral and cannot be null"); + } + this.QuadrilateralType = quadrilateralType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] + public string ShapeType { get; set; } + + /// + /// Gets or Sets QuadrilateralType + /// + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] + public string QuadrilateralType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ComplexQuadrilateral {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ComplexQuadrilateral).AreEqual; + } + + /// + /// Returns true if ComplexQuadrilateral instances are equal + /// + /// Instance of ComplexQuadrilateral to be compared + /// Boolean + public bool Equals(ComplexQuadrilateral input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ShapeType != null) + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } + if (this.QuadrilateralType != null) + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/DanishPig.cs new file mode 100644 index 0000000000..d86ff21df9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/DanishPig.cs @@ -0,0 +1,145 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// DanishPig + /// + [DataContract(Name = "DanishPig")] + public partial class DanishPig : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected DanishPig() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// className (required). + public DanishPig(string className = default(string)) + { + // to ensure "className" is required (not null) + if (className == null) + { + throw new ArgumentNullException("className is a required property for DanishPig and cannot be null"); + } + this.ClassName = className; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] + public string ClassName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DanishPig {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as DanishPig).AreEqual; + } + + /// + /// Returns true if DanishPig instances are equal + /// + /// Instance of DanishPig to be compared + /// Boolean + public bool Equals(DanishPig input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ClassName != null) + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/DeprecatedObject.cs new file mode 100644 index 0000000000..1928b236bf --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// DeprecatedObject + /// + [DataContract(Name = "DeprecatedObject")] + public partial class DeprecatedObject : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name. + public DeprecatedObject(string name = default(string)) + { + this.Name = name; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeprecatedObject {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as DeprecatedObject).AreEqual; + } + + /// + /// Returns true if DeprecatedObject instances are equal + /// + /// Instance of DeprecatedObject to be compared + /// Boolean + public bool Equals(DeprecatedObject input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Name != null) + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Dog.cs new file mode 100644 index 0000000000..786270d1c4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Dog.cs @@ -0,0 +1,159 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Dog + /// + [DataContract(Name = "Dog")] + [JsonConverter(typeof(JsonSubtypes), "ClassName")] + public partial class Dog : Animal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Dog() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// breed. + /// className (required) (default to "Dog"). + /// color (default to "red"). + public Dog(string breed = default(string), string className = "Dog", string color = "red") : base(className, color) + { + this.Breed = breed; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Breed + /// + [DataMember(Name = "breed", EmitDefaultValue = false)] + public string Breed { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Dog {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" Breed: ").Append(Breed).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Dog).AreEqual; + } + + /// + /// Returns true if Dog instances are equal + /// + /// Instance of Dog to be compared + /// Boolean + public bool Equals(Dog input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + if (this.Breed != null) + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + foreach (var x in base.BaseValidate(validationContext)) + { + yield return x; + } + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/DogAllOf.cs new file mode 100644 index 0000000000..7b026acbf1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// DogAllOf + /// + [DataContract(Name = "Dog_allOf")] + public partial class DogAllOf : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// breed. + public DogAllOf(string breed = default(string)) + { + this.Breed = breed; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Breed + /// + [DataMember(Name = "breed", EmitDefaultValue = false)] + public string Breed { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DogAllOf {\n"); + sb.Append(" Breed: ").Append(Breed).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as DogAllOf).AreEqual; + } + + /// + /// Returns true if DogAllOf instances are equal + /// + /// Instance of DogAllOf to be compared + /// Boolean + public bool Equals(DogAllOf input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Breed != null) + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs new file mode 100644 index 0000000000..d8cd2a70ef --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs @@ -0,0 +1,160 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Drawing + /// + [DataContract(Name = "Drawing")] + public partial class Drawing : Dictionary, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// mainShape. + /// shapeOrNull. + /// nullableShape. + /// shapes. + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + { + this.MainShape = mainShape; + this.ShapeOrNull = shapeOrNull; + this.NullableShape = nullableShape; + this.Shapes = shapes; + } + + /// + /// Gets or Sets MainShape + /// + [DataMember(Name = "mainShape", EmitDefaultValue = false)] + public Shape MainShape { get; set; } + + /// + /// Gets or Sets ShapeOrNull + /// + [DataMember(Name = "shapeOrNull", EmitDefaultValue = false)] + public ShapeOrNull ShapeOrNull { get; set; } + + /// + /// Gets or Sets NullableShape + /// + [DataMember(Name = "nullableShape", EmitDefaultValue = true)] + public NullableShape NullableShape { get; set; } + + /// + /// Gets or Sets Shapes + /// + [DataMember(Name = "shapes", EmitDefaultValue = false)] + public List Shapes { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Drawing {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" MainShape: ").Append(MainShape).Append("\n"); + sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); + sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); + sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Drawing).AreEqual; + } + + /// + /// Returns true if Drawing instances are equal + /// + /// Instance of Drawing to be compared + /// Boolean + public bool Equals(Drawing input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + if (this.MainShape != null) + { + hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); + } + if (this.ShapeOrNull != null) + { + hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); + } + if (this.NullableShape != null) + { + hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); + } + if (this.Shapes != null) + { + hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EnumArrays.cs new file mode 100644 index 0000000000..69568d6c87 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -0,0 +1,182 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// EnumArrays + /// + [DataContract(Name = "EnumArrays")] + public partial class EnumArrays : IEquatable, IValidatableObject + { + /// + /// Defines JustSymbol + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum JustSymbolEnum + { + /// + /// Enum GreaterThanOrEqualTo for value: >= + /// + [EnumMember(Value = ">=")] + GreaterThanOrEqualTo = 1, + + /// + /// Enum Dollar for value: $ + /// + [EnumMember(Value = "$")] + Dollar = 2 + + } + + + /// + /// Gets or Sets JustSymbol + /// + [DataMember(Name = "just_symbol", EmitDefaultValue = false)] + public JustSymbolEnum? JustSymbol { get; set; } + /// + /// Defines ArrayEnum + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum ArrayEnumEnum + { + /// + /// Enum Fish for value: fish + /// + [EnumMember(Value = "fish")] + Fish = 1, + + /// + /// Enum Crab for value: crab + /// + [EnumMember(Value = "crab")] + Crab = 2 + + } + + /// + /// Initializes a new instance of the class. + /// + /// justSymbol. + /// arrayEnum. + public EnumArrays(JustSymbolEnum? justSymbol = default(JustSymbolEnum?), List arrayEnum = default(List)) + { + this.JustSymbol = justSymbol; + this.ArrayEnum = arrayEnum; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ArrayEnum + /// + [DataMember(Name = "array_enum", EmitDefaultValue = false)] + public List ArrayEnum { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EnumArrays {\n"); + sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); + sb.Append(" ArrayEnum: ").Append(ArrayEnum).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as EnumArrays).AreEqual; + } + + /// + /// Returns true if EnumArrays instances are equal + /// + /// Instance of EnumArrays to be compared + /// Boolean + public bool Equals(EnumArrays input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EnumClass.cs new file mode 100644 index 0000000000..48b3d7d0e7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EnumClass.cs @@ -0,0 +1,55 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Defines EnumClass + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumClass + { + /// + /// Enum Abc for value: _abc + /// + [EnumMember(Value = "_abc")] + Abc = 1, + + /// + /// Enum Efg for value: -efg + /// + [EnumMember(Value = "-efg")] + Efg = 2, + + /// + /// Enum Xyz for value: (xyz) + /// + [EnumMember(Value = "(xyz)")] + Xyz = 3 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EnumTest.cs new file mode 100644 index 0000000000..7386cffd37 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EnumTest.cs @@ -0,0 +1,323 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// EnumTest + /// + [DataContract(Name = "Enum_Test")] + public partial class EnumTest : IEquatable, IValidatableObject + { + /// + /// Defines EnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3 + + } + + + /// + /// Gets or Sets EnumString + /// + [DataMember(Name = "enum_string", EmitDefaultValue = false)] + public EnumStringEnum? EnumString { get; set; } + /// + /// Defines EnumStringRequired + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumStringRequiredEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3 + + } + + + /// + /// Gets or Sets EnumStringRequired + /// + [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = true)] + public EnumStringRequiredEnum EnumStringRequired { get; set; } + /// + /// Defines EnumInteger + /// + public enum EnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + + } + + + /// + /// Gets or Sets EnumInteger + /// + [DataMember(Name = "enum_integer", EmitDefaultValue = false)] + public EnumIntegerEnum? EnumInteger { get; set; } + /// + /// Defines EnumIntegerOnly + /// + public enum EnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + + } + + + /// + /// Gets or Sets EnumIntegerOnly + /// + [DataMember(Name = "enum_integer_only", EmitDefaultValue = false)] + public EnumIntegerOnlyEnum? EnumIntegerOnly { get; set; } + /// + /// Defines EnumNumber + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumNumberEnum + { + /// + /// Enum NUMBER_1_DOT_1 for value: 1.1 + /// + [EnumMember(Value = "1.1")] + NUMBER_1_DOT_1 = 1, + + /// + /// Enum NUMBER_MINUS_1_DOT_2 for value: -1.2 + /// + [EnumMember(Value = "-1.2")] + NUMBER_MINUS_1_DOT_2 = 2 + + } + + + /// + /// Gets or Sets EnumNumber + /// + [DataMember(Name = "enum_number", EmitDefaultValue = false)] + public EnumNumberEnum? EnumNumber { get; set; } + + /// + /// Gets or Sets OuterEnum + /// + [DataMember(Name = "outerEnum", EmitDefaultValue = true)] + public OuterEnum? OuterEnum { get; set; } + + /// + /// Gets or Sets OuterEnumInteger + /// + [DataMember(Name = "outerEnumInteger", EmitDefaultValue = false)] + public OuterEnumInteger? OuterEnumInteger { get; set; } + + /// + /// Gets or Sets OuterEnumDefaultValue + /// + [DataMember(Name = "outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? OuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets OuterEnumIntegerDefaultValue + /// + [DataMember(Name = "outerEnumIntegerDefaultValue", EmitDefaultValue = false)] + public OuterEnumIntegerDefaultValue? OuterEnumIntegerDefaultValue { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected EnumTest() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// enumString. + /// enumStringRequired (required). + /// enumInteger. + /// enumIntegerOnly. + /// enumNumber. + /// outerEnum. + /// outerEnumInteger. + /// outerEnumDefaultValue. + /// outerEnumIntegerDefaultValue. + public EnumTest(EnumStringEnum? enumString = default(EnumStringEnum?), EnumStringRequiredEnum enumStringRequired = default(EnumStringRequiredEnum), EnumIntegerEnum? enumInteger = default(EnumIntegerEnum?), EnumIntegerOnlyEnum? enumIntegerOnly = default(EnumIntegerOnlyEnum?), EnumNumberEnum? enumNumber = default(EnumNumberEnum?), OuterEnum? outerEnum = default(OuterEnum?), OuterEnumInteger? outerEnumInteger = default(OuterEnumInteger?), OuterEnumDefaultValue? outerEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue = default(OuterEnumIntegerDefaultValue?)) + { + this.EnumStringRequired = enumStringRequired; + this.EnumString = enumString; + this.EnumInteger = enumInteger; + this.EnumIntegerOnly = enumIntegerOnly; + this.EnumNumber = enumNumber; + this.OuterEnum = outerEnum; + this.OuterEnumInteger = outerEnumInteger; + this.OuterEnumDefaultValue = outerEnumDefaultValue; + this.OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EnumTest {\n"); + sb.Append(" EnumString: ").Append(EnumString).Append("\n"); + sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); + sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); + sb.Append(" EnumIntegerOnly: ").Append(EnumIntegerOnly).Append("\n"); + sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); + sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); + sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).Append("\n"); + sb.Append(" OuterEnumDefaultValue: ").Append(OuterEnumDefaultValue).Append("\n"); + sb.Append(" OuterEnumIntegerDefaultValue: ").Append(OuterEnumIntegerDefaultValue).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as EnumTest).AreEqual; + } + + /// + /// Returns true if EnumTest instances are equal + /// + /// Instance of EnumTest to be compared + /// Boolean + public bool Equals(EnumTest input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumStringRequired.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EquilateralTriangle.cs new file mode 100644 index 0000000000..773eba5b0a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// EquilateralTriangle + /// + [DataContract(Name = "EquilateralTriangle")] + public partial class EquilateralTriangle : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected EquilateralTriangle() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// triangleType (required). + public EquilateralTriangle(string shapeType = default(string), string triangleType = default(string)) + { + // to ensure "shapeType" is required (not null) + if (shapeType == null) + { + throw new ArgumentNullException("shapeType is a required property for EquilateralTriangle and cannot be null"); + } + this.ShapeType = shapeType; + // to ensure "triangleType" is required (not null) + if (triangleType == null) + { + throw new ArgumentNullException("triangleType is a required property for EquilateralTriangle and cannot be null"); + } + this.TriangleType = triangleType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] + public string ShapeType { get; set; } + + /// + /// Gets or Sets TriangleType + /// + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] + public string TriangleType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class EquilateralTriangle {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as EquilateralTriangle).AreEqual; + } + + /// + /// Returns true if EquilateralTriangle instances are equal + /// + /// Instance of EquilateralTriangle to be compared + /// Boolean + public bool Equals(EquilateralTriangle input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ShapeType != null) + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } + if (this.TriangleType != null) + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/File.cs new file mode 100644 index 0000000000..e77d15e06b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/File.cs @@ -0,0 +1,133 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Must be named `File` for test. + /// + [DataContract(Name = "File")] + public partial class File : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Test capitalization. + public File(string sourceURI = default(string)) + { + this.SourceURI = sourceURI; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Test capitalization + /// + /// Test capitalization + [DataMember(Name = "sourceURI", EmitDefaultValue = false)] + public string SourceURI { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class File {\n"); + sb.Append(" SourceURI: ").Append(SourceURI).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as File).AreEqual; + } + + /// + /// Returns true if File instances are equal + /// + /// Instance of File to be compared + /// Boolean + public bool Equals(File input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.SourceURI != null) + { + hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs new file mode 100644 index 0000000000..6808978c49 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -0,0 +1,145 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// FileSchemaTestClass + /// + [DataContract(Name = "FileSchemaTestClass")] + public partial class FileSchemaTestClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// file. + /// files. + public FileSchemaTestClass(File file = default(File), List files = default(List)) + { + this.File = file; + this.Files = files; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets File + /// + [DataMember(Name = "file", EmitDefaultValue = false)] + public File File { get; set; } + + /// + /// Gets or Sets Files + /// + [DataMember(Name = "files", EmitDefaultValue = false)] + public List Files { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FileSchemaTestClass {\n"); + sb.Append(" File: ").Append(File).Append("\n"); + sb.Append(" Files: ").Append(Files).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as FileSchemaTestClass).AreEqual; + } + + /// + /// Returns true if FileSchemaTestClass instances are equal + /// + /// Instance of FileSchemaTestClass to be compared + /// Boolean + public bool Equals(FileSchemaTestClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.File != null) + { + hashCode = (hashCode * 59) + this.File.GetHashCode(); + } + if (this.Files != null) + { + hashCode = (hashCode * 59) + this.Files.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Foo.cs new file mode 100644 index 0000000000..e64aac7b63 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Foo.cs @@ -0,0 +1,133 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Foo + /// + [DataContract(Name = "Foo")] + public partial class Foo : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bar (default to "bar"). + public Foo(string bar = "bar") + { + // use default value if no "bar" provided + this.Bar = bar ?? "bar"; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Bar + /// + [DataMember(Name = "bar", EmitDefaultValue = false)] + public string Bar { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Foo {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Foo).AreEqual; + } + + /// + /// Returns true if Foo instances are equal + /// + /// Instance of Foo to be compared + /// Boolean + public bool Equals(Foo input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Bar != null) + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs new file mode 100644 index 0000000000..259e5e626d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// FooGetDefaultResponse + /// + [DataContract(Name = "_foo_get_default_response")] + public partial class FooGetDefaultResponse : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _string. + public FooGetDefaultResponse(Foo _string = default(Foo)) + { + this.String = _string; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets String + /// + [DataMember(Name = "string", EmitDefaultValue = false)] + public Foo String { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FooGetDefaultResponse {\n"); + sb.Append(" String: ").Append(String).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as FooGetDefaultResponse).AreEqual; + } + + /// + /// Returns true if FooGetDefaultResponse instances are equal + /// + /// Instance of FooGetDefaultResponse to be compared + /// Boolean + public bool Equals(FooGetDefaultResponse input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.String != null) + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FormatTest.cs new file mode 100644 index 0000000000..9d0979b6f7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FormatTest.cs @@ -0,0 +1,420 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// FormatTest + /// + [DataContract(Name = "format_test")] + public partial class FormatTest : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected FormatTest() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// integer. + /// int32. + /// int64. + /// number (required). + /// _float. + /// _double. + /// _decimal. + /// _string. + /// _byte (required). + /// binary. + /// date (required). + /// dateTime. + /// uuid. + /// password (required). + /// A string that is a 10 digit number. Can have leading zeros.. + /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. + public FormatTest(int integer = default(int), int int32 = default(int), long int64 = default(long), decimal number = default(decimal), float _float = default(float), double _double = default(double), decimal _decimal = default(decimal), string _string = default(string), byte[] _byte = default(byte[]), System.IO.Stream binary = default(System.IO.Stream), DateTime date = default(DateTime), DateTime dateTime = default(DateTime), Guid uuid = default(Guid), string password = default(string), string patternWithDigits = default(string), string patternWithDigitsAndDelimiter = default(string)) + { + this.Number = number; + // to ensure "_byte" is required (not null) + if (_byte == null) + { + throw new ArgumentNullException("_byte is a required property for FormatTest and cannot be null"); + } + this.Byte = _byte; + this.Date = date; + // to ensure "password" is required (not null) + if (password == null) + { + throw new ArgumentNullException("password is a required property for FormatTest and cannot be null"); + } + this.Password = password; + this.Integer = integer; + this.Int32 = int32; + this.Int64 = int64; + this.Float = _float; + this.Double = _double; + this.Decimal = _decimal; + this.String = _string; + this.Binary = binary; + this.DateTime = dateTime; + this.Uuid = uuid; + this.PatternWithDigits = patternWithDigits; + this.PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Integer + /// + [DataMember(Name = "integer", EmitDefaultValue = false)] + public int Integer { get; set; } + + /// + /// Gets or Sets Int32 + /// + [DataMember(Name = "int32", EmitDefaultValue = false)] + public int Int32 { get; set; } + + /// + /// Gets or Sets Int64 + /// + [DataMember(Name = "int64", EmitDefaultValue = false)] + public long Int64 { get; set; } + + /// + /// Gets or Sets Number + /// + [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = true)] + public decimal Number { get; set; } + + /// + /// Gets or Sets Float + /// + [DataMember(Name = "float", EmitDefaultValue = false)] + public float Float { get; set; } + + /// + /// Gets or Sets Double + /// + [DataMember(Name = "double", EmitDefaultValue = false)] + public double Double { get; set; } + + /// + /// Gets or Sets Decimal + /// + [DataMember(Name = "decimal", EmitDefaultValue = false)] + public decimal Decimal { get; set; } + + /// + /// Gets or Sets String + /// + [DataMember(Name = "string", EmitDefaultValue = false)] + public string String { get; set; } + + /// + /// Gets or Sets Byte + /// + [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = true)] + public byte[] Byte { get; set; } + + /// + /// Gets or Sets Binary + /// + [DataMember(Name = "binary", EmitDefaultValue = false)] + public System.IO.Stream Binary { get; set; } + + /// + /// Gets or Sets Date + /// + [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime Date { get; set; } + + /// + /// Gets or Sets DateTime + /// + [DataMember(Name = "dateTime", EmitDefaultValue = false)] + public DateTime DateTime { get; set; } + + /// + /// Gets or Sets Uuid + /// + [DataMember(Name = "uuid", EmitDefaultValue = false)] + public Guid Uuid { get; set; } + + /// + /// Gets or Sets Password + /// + [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = true)] + public string Password { get; set; } + + /// + /// A string that is a 10 digit number. Can have leading zeros. + /// + /// A string that is a 10 digit number. Can have leading zeros. + [DataMember(Name = "pattern_with_digits", EmitDefaultValue = false)] + public string PatternWithDigits { get; set; } + + /// + /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + /// + /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + [DataMember(Name = "pattern_with_digits_and_delimiter", EmitDefaultValue = false)] + public string PatternWithDigitsAndDelimiter { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class FormatTest {\n"); + sb.Append(" Integer: ").Append(Integer).Append("\n"); + sb.Append(" Int32: ").Append(Int32).Append("\n"); + sb.Append(" Int64: ").Append(Int64).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Float: ").Append(Float).Append("\n"); + sb.Append(" Double: ").Append(Double).Append("\n"); + sb.Append(" Decimal: ").Append(Decimal).Append("\n"); + sb.Append(" String: ").Append(String).Append("\n"); + sb.Append(" Byte: ").Append(Byte).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); + sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as FormatTest).AreEqual; + } + + /// + /// Returns true if FormatTest instances are equal + /// + /// Instance of FormatTest to be compared + /// Boolean + public bool Equals(FormatTest input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.Integer.GetHashCode(); + hashCode = (hashCode * 59) + this.Int32.GetHashCode(); + hashCode = (hashCode * 59) + this.Int64.GetHashCode(); + hashCode = (hashCode * 59) + this.Number.GetHashCode(); + hashCode = (hashCode * 59) + this.Float.GetHashCode(); + hashCode = (hashCode * 59) + this.Double.GetHashCode(); + hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); + if (this.String != null) + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } + if (this.Byte != null) + { + hashCode = (hashCode * 59) + this.Byte.GetHashCode(); + } + if (this.Binary != null) + { + hashCode = (hashCode * 59) + this.Binary.GetHashCode(); + } + if (this.Date != null) + { + hashCode = (hashCode * 59) + this.Date.GetHashCode(); + } + if (this.DateTime != null) + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } + if (this.Uuid != null) + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } + if (this.Password != null) + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } + if (this.PatternWithDigits != null) + { + hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); + } + if (this.PatternWithDigitsAndDelimiter != null) + { + hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + // Integer (int) maximum + if (this.Integer > (int)100) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); + } + + // Integer (int) minimum + if (this.Integer < (int)10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); + } + + // Int32 (int) maximum + if (this.Int32 > (int)200) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); + } + + // Int32 (int) minimum + if (this.Int32 < (int)20) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); + } + + // Number (decimal) maximum + if (this.Number > (decimal)543.2) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); + } + + // Number (decimal) minimum + if (this.Number < (decimal)32.1) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); + } + + // Float (float) maximum + if (this.Float > (float)987.6) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); + } + + // Float (float) minimum + if (this.Float < (float)54.3) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); + } + + // Double (double) maximum + if (this.Double > (double)123.4) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); + } + + // Double (double) minimum + if (this.Double < (double)67.8) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); + } + + // String (string) pattern + Regex regexString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regexString.Match(this.String).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for String, must match a pattern of " + regexString, new [] { "String" }); + } + + // Password (string) maxLength + if (this.Password != null && this.Password.Length > 64) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); + } + + // Password (string) minLength + if (this.Password != null && this.Password.Length < 10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); + } + + // PatternWithDigits (string) pattern + Regex regexPatternWithDigits = new Regex(@"^\\d{10}$", RegexOptions.CultureInvariant); + if (false == regexPatternWithDigits.Match(this.PatternWithDigits).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigits, must match a pattern of " + regexPatternWithDigits, new [] { "PatternWithDigits" }); + } + + // PatternWithDigitsAndDelimiter (string) pattern + Regex regexPatternWithDigitsAndDelimiter = new Regex(@"^image_\\d{1,3}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiter).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); + } + + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Fruit.cs new file mode 100644 index 0000000000..726b1e8f72 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Fruit.cs @@ -0,0 +1,291 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Fruit + /// + [JsonConverter(typeof(FruitJsonConverter))] + [DataContract(Name = "fruit")] + public partial class Fruit : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Apple. + public Fruit(Apple actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Banana. + public Fruit(Banana actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Apple)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Banana)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Apple, Banana"); + } + } + } + + /// + /// Get the actual instance of `Apple`. If the actual instance is not `Apple`, + /// the InvalidClassException will be thrown + /// + /// An instance of Apple + public Apple GetApple() + { + return (Apple)this.ActualInstance; + } + + /// + /// Get the actual instance of `Banana`. If the actual instance is not `Banana`, + /// the InvalidClassException will be thrown + /// + /// An instance of Banana + public Banana GetBanana() + { + return (Banana)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Fruit {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Fruit.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Fruit + /// + /// JSON string + /// An instance of Fruit + public static Fruit FromJson(string jsonString) + { + Fruit newFruit = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newFruit; + } + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Apple).GetProperty("AdditionalProperties") == null) + { + newFruit = new Fruit(JsonConvert.DeserializeObject(jsonString, Fruit.SerializerSettings)); + } + else + { + newFruit = new Fruit(JsonConvert.DeserializeObject(jsonString, Fruit.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Apple"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Banana).GetProperty("AdditionalProperties") == null) + { + newFruit = new Fruit(JsonConvert.DeserializeObject(jsonString, Fruit.SerializerSettings)); + } + else + { + newFruit = new Fruit(JsonConvert.DeserializeObject(jsonString, Fruit.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Banana"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newFruit; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Fruit).AreEqual; + } + + /// + /// Returns true if Fruit instances are equal + /// + /// Instance of Fruit to be compared + /// Boolean + public bool Equals(Fruit input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Fruit + /// + public class FruitJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Fruit.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FruitReq.cs new file mode 100644 index 0000000000..548da490de --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/FruitReq.cs @@ -0,0 +1,300 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// FruitReq + /// + [JsonConverter(typeof(FruitReqJsonConverter))] + [DataContract(Name = "fruitReq")] + public partial class FruitReq : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + public FruitReq() + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of AppleReq. + public FruitReq(AppleReq actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of BananaReq. + public FruitReq(BananaReq actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(AppleReq)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(BananaReq)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: AppleReq, BananaReq"); + } + } + } + + /// + /// Get the actual instance of `AppleReq`. If the actual instance is not `AppleReq`, + /// the InvalidClassException will be thrown + /// + /// An instance of AppleReq + public AppleReq GetAppleReq() + { + return (AppleReq)this.ActualInstance; + } + + /// + /// Get the actual instance of `BananaReq`. If the actual instance is not `BananaReq`, + /// the InvalidClassException will be thrown + /// + /// An instance of BananaReq + public BananaReq GetBananaReq() + { + return (BananaReq)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class FruitReq {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, FruitReq.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of FruitReq + /// + /// JSON string + /// An instance of FruitReq + public static FruitReq FromJson(string jsonString) + { + FruitReq newFruitReq = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newFruitReq; + } + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(AppleReq).GetProperty("AdditionalProperties") == null) + { + newFruitReq = new FruitReq(JsonConvert.DeserializeObject(jsonString, FruitReq.SerializerSettings)); + } + else + { + newFruitReq = new FruitReq(JsonConvert.DeserializeObject(jsonString, FruitReq.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("AppleReq"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(BananaReq).GetProperty("AdditionalProperties") == null) + { + newFruitReq = new FruitReq(JsonConvert.DeserializeObject(jsonString, FruitReq.SerializerSettings)); + } + else + { + newFruitReq = new FruitReq(JsonConvert.DeserializeObject(jsonString, FruitReq.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("BananaReq"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newFruitReq; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as FruitReq).AreEqual; + } + + /// + /// Returns true if FruitReq instances are equal + /// + /// Instance of FruitReq to be compared + /// Boolean + public bool Equals(FruitReq input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for FruitReq + /// + public class FruitReqJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return FruitReq.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/GmFruit.cs new file mode 100644 index 0000000000..9d97bc6177 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/GmFruit.cs @@ -0,0 +1,264 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// GmFruit + /// + [JsonConverter(typeof(GmFruitJsonConverter))] + [DataContract(Name = "gmFruit")] + public partial class GmFruit : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Apple. + public GmFruit(Apple actualInstance) + { + this.IsNullable = false; + this.SchemaType= "anyOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Banana. + public GmFruit(Banana actualInstance) + { + this.IsNullable = false; + this.SchemaType= "anyOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Apple)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Banana)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Apple, Banana"); + } + } + } + + /// + /// Get the actual instance of `Apple`. If the actual instance is not `Apple`, + /// the InvalidClassException will be thrown + /// + /// An instance of Apple + public Apple GetApple() + { + return (Apple)this.ActualInstance; + } + + /// + /// Get the actual instance of `Banana`. If the actual instance is not `Banana`, + /// the InvalidClassException will be thrown + /// + /// An instance of Banana + public Banana GetBanana() + { + return (Banana)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class GmFruit {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, GmFruit.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of GmFruit + /// + /// JSON string + /// An instance of GmFruit + public static GmFruit FromJson(string jsonString) + { + GmFruit newGmFruit = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newGmFruit; + } + + try + { + newGmFruit = new GmFruit(JsonConvert.DeserializeObject(jsonString, GmFruit.SerializerSettings)); + // deserialization is considered successful at this point if no exception has been thrown. + return newGmFruit; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + } + + try + { + newGmFruit = new GmFruit(JsonConvert.DeserializeObject(jsonString, GmFruit.SerializerSettings)); + // deserialization is considered successful at this point if no exception has been thrown. + return newGmFruit; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + } + + // no match found, throw an exception + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as GmFruit).AreEqual; + } + + /// + /// Returns true if GmFruit instances are equal + /// + /// Instance of GmFruit to be compared + /// Boolean + public bool Equals(GmFruit input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for GmFruit + /// + public class GmFruitJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return GmFruit.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/GrandparentAnimal.cs new file mode 100644 index 0000000000..28e7729a17 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -0,0 +1,159 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// GrandparentAnimal + /// + [DataContract(Name = "GrandparentAnimal")] + [JsonConverter(typeof(JsonSubtypes), "PetType")] + [JsonSubtypes.KnownSubType(typeof(ChildCat), "ChildCat")] + [JsonSubtypes.KnownSubType(typeof(ParentPet), "ParentPet")] + public partial class GrandparentAnimal : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected GrandparentAnimal() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// petType (required). + public GrandparentAnimal(string petType = default(string)) + { + // to ensure "petType" is required (not null) + if (petType == null) + { + throw new ArgumentNullException("petType is a required property for GrandparentAnimal and cannot be null"); + } + this.PetType = petType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets PetType + /// + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] + public string PetType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class GrandparentAnimal {\n"); + sb.Append(" PetType: ").Append(PetType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as GrandparentAnimal).AreEqual; + } + + /// + /// Returns true if GrandparentAnimal instances are equal + /// + /// Instance of GrandparentAnimal to be compared + /// Boolean + public bool Equals(GrandparentAnimal input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.PetType != null) + { + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs new file mode 100644 index 0000000000..52099a7095 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -0,0 +1,158 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// HasOnlyReadOnly + /// + [DataContract(Name = "hasOnlyReadOnly")] + public partial class HasOnlyReadOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + public HasOnlyReadOnly() + { + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Bar + /// + [DataMember(Name = "bar", EmitDefaultValue = false)] + public string Bar { get; private set; } + + /// + /// Returns false as Bar should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBar() + { + return false; + } + /// + /// Gets or Sets Foo + /// + [DataMember(Name = "foo", EmitDefaultValue = false)] + public string Foo { get; private set; } + + /// + /// Returns false as Foo should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeFoo() + { + return false; + } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HasOnlyReadOnly {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" Foo: ").Append(Foo).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as HasOnlyReadOnly).AreEqual; + } + + /// + /// Returns true if HasOnlyReadOnly instances are equal + /// + /// Instance of HasOnlyReadOnly to be compared + /// Boolean + public bool Equals(HasOnlyReadOnly input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Bar != null) + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } + if (this.Foo != null) + { + hashCode = (hashCode * 59) + this.Foo.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/HealthCheckResult.cs new file mode 100644 index 0000000000..e8cbb68e2e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + /// + [DataContract(Name = "HealthCheckResult")] + public partial class HealthCheckResult : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// nullableMessage. + public HealthCheckResult(string nullableMessage = default(string)) + { + this.NullableMessage = nullableMessage; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets NullableMessage + /// + [DataMember(Name = "NullableMessage", EmitDefaultValue = true)] + public string NullableMessage { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HealthCheckResult {\n"); + sb.Append(" NullableMessage: ").Append(NullableMessage).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as HealthCheckResult).AreEqual; + } + + /// + /// Returns true if HealthCheckResult instances are equal + /// + /// Instance of HealthCheckResult to be compared + /// Boolean + public bool Equals(HealthCheckResult input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.NullableMessage != null) + { + hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs new file mode 100644 index 0000000000..ea18925f87 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -0,0 +1,148 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// IsoscelesTriangle + /// + [DataContract(Name = "IsoscelesTriangle")] + public partial class IsoscelesTriangle : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected IsoscelesTriangle() { } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// triangleType (required). + public IsoscelesTriangle(string shapeType = default(string), string triangleType = default(string)) + { + // to ensure "shapeType" is required (not null) + if (shapeType == null) + { + throw new ArgumentNullException("shapeType is a required property for IsoscelesTriangle and cannot be null"); + } + this.ShapeType = shapeType; + // to ensure "triangleType" is required (not null) + if (triangleType == null) + { + throw new ArgumentNullException("triangleType is a required property for IsoscelesTriangle and cannot be null"); + } + this.TriangleType = triangleType; + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] + public string ShapeType { get; set; } + + /// + /// Gets or Sets TriangleType + /// + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] + public string TriangleType { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class IsoscelesTriangle {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as IsoscelesTriangle).AreEqual; + } + + /// + /// Returns true if IsoscelesTriangle instances are equal + /// + /// Instance of IsoscelesTriangle to be compared + /// Boolean + public bool Equals(IsoscelesTriangle input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ShapeType != null) + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } + if (this.TriangleType != null) + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/List.cs new file mode 100644 index 0000000000..00814d1106 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/List.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// List + /// + [DataContract(Name = "List")] + public partial class List : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _123list. + public List(string _123list = default(string)) + { + this._123List = _123list; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets _123List + /// + [DataMember(Name = "123-list", EmitDefaultValue = false)] + public string _123List { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class List {\n"); + sb.Append(" _123List: ").Append(_123List).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as List).AreEqual; + } + + /// + /// Returns true if List instances are equal + /// + /// Instance of List to be compared + /// Boolean + public bool Equals(List input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this._123List != null) + { + hashCode = (hashCode * 59) + this._123List.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Mammal.cs new file mode 100644 index 0000000000..8630f21bba --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Mammal.cs @@ -0,0 +1,364 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Mammal + /// + [JsonConverter(typeof(MammalJsonConverter))] + [DataContract(Name = "mammal")] + public partial class Mammal : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Whale. + public Mammal(Whale actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Zebra. + public Mammal(Zebra actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Pig. + public Mammal(Pig actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Pig)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Whale)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Zebra)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Pig, Whale, Zebra"); + } + } + } + + /// + /// Get the actual instance of `Whale`. If the actual instance is not `Whale`, + /// the InvalidClassException will be thrown + /// + /// An instance of Whale + public Whale GetWhale() + { + return (Whale)this.ActualInstance; + } + + /// + /// Get the actual instance of `Zebra`. If the actual instance is not `Zebra`, + /// the InvalidClassException will be thrown + /// + /// An instance of Zebra + public Zebra GetZebra() + { + return (Zebra)this.ActualInstance; + } + + /// + /// Get the actual instance of `Pig`. If the actual instance is not `Pig`, + /// the InvalidClassException will be thrown + /// + /// An instance of Pig + public Pig GetPig() + { + return (Pig)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Mammal {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Mammal.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Mammal + /// + /// JSON string + /// An instance of Mammal + public static Mammal FromJson(string jsonString) + { + Mammal newMammal = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newMammal; + } + + try + { + var discriminatorObj = JObject.Parse(jsonString)["className"]; + string discriminatorValue = discriminatorObj == null ?string.Empty :discriminatorObj.ToString(); + switch (discriminatorValue) + { + case "Pig": + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + return newMammal; + case "whale": + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + return newMammal; + case "zebra": + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + return newMammal; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); + break; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(string.Format("Failed to parse the json data : `{0}` {1}", jsonString, ex.ToString())); + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Pig).GetProperty("AdditionalProperties") == null) + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.SerializerSettings)); + } + else + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Pig"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Whale).GetProperty("AdditionalProperties") == null) + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.SerializerSettings)); + } + else + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Whale"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Zebra).GetProperty("AdditionalProperties") == null) + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.SerializerSettings)); + } + else + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Zebra"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newMammal; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Mammal).AreEqual; + } + + /// + /// Returns true if Mammal instances are equal + /// + /// Instance of Mammal to be compared + /// Boolean + public bool Equals(Mammal input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Mammal + /// + public class MammalJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Mammal.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/MapTest.cs new file mode 100644 index 0000000000..b2aeedc33c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/MapTest.cs @@ -0,0 +1,191 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// MapTest + /// + [DataContract(Name = "MapTest")] + public partial class MapTest : IEquatable, IValidatableObject + { + /// + /// Defines Inner + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum InnerEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2 + + } + + /// + /// Initializes a new instance of the class. + /// + /// mapMapOfString. + /// mapOfEnumString. + /// directMap. + /// indirectMap. + public MapTest(Dictionary> mapMapOfString = default(Dictionary>), Dictionary mapOfEnumString = default(Dictionary), Dictionary directMap = default(Dictionary), Dictionary indirectMap = default(Dictionary)) + { + this.MapMapOfString = mapMapOfString; + this.MapOfEnumString = mapOfEnumString; + this.DirectMap = directMap; + this.IndirectMap = indirectMap; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets MapMapOfString + /// + [DataMember(Name = "map_map_of_string", EmitDefaultValue = false)] + public Dictionary> MapMapOfString { get; set; } + + /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] + public Dictionary MapOfEnumString { get; set; } + + /// + /// Gets or Sets DirectMap + /// + [DataMember(Name = "direct_map", EmitDefaultValue = false)] + public Dictionary DirectMap { get; set; } + + /// + /// Gets or Sets IndirectMap + /// + [DataMember(Name = "indirect_map", EmitDefaultValue = false)] + public Dictionary IndirectMap { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MapTest {\n"); + sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); + sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); + sb.Append(" DirectMap: ").Append(DirectMap).Append("\n"); + sb.Append(" IndirectMap: ").Append(IndirectMap).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as MapTest).AreEqual; + } + + /// + /// Returns true if MapTest instances are equal + /// + /// Instance of MapTest to be compared + /// Boolean + public bool Equals(MapTest input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.MapMapOfString != null) + { + hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); + } + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } + if (this.DirectMap != null) + { + hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); + } + if (this.IndirectMap != null) + { + hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs new file mode 100644 index 0000000000..3225727af3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -0,0 +1,158 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// MixedPropertiesAndAdditionalPropertiesClass + /// + [DataContract(Name = "MixedPropertiesAndAdditionalPropertiesClass")] + public partial class MixedPropertiesAndAdditionalPropertiesClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// uuid. + /// dateTime. + /// map. + public MixedPropertiesAndAdditionalPropertiesClass(Guid uuid = default(Guid), DateTime dateTime = default(DateTime), Dictionary map = default(Dictionary)) + { + this.Uuid = uuid; + this.DateTime = dateTime; + this.Map = map; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Uuid + /// + [DataMember(Name = "uuid", EmitDefaultValue = false)] + public Guid Uuid { get; set; } + + /// + /// Gets or Sets DateTime + /// + [DataMember(Name = "dateTime", EmitDefaultValue = false)] + public DateTime DateTime { get; set; } + + /// + /// Gets or Sets Map + /// + [DataMember(Name = "map", EmitDefaultValue = false)] + public Dictionary Map { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" Map: ").Append(Map).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as MixedPropertiesAndAdditionalPropertiesClass).AreEqual; + } + + /// + /// Returns true if MixedPropertiesAndAdditionalPropertiesClass instances are equal + /// + /// Instance of MixedPropertiesAndAdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(MixedPropertiesAndAdditionalPropertiesClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Uuid != null) + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } + if (this.DateTime != null) + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } + if (this.Map != null) + { + hashCode = (hashCode * 59) + this.Map.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Model200Response.cs new file mode 100644 index 0000000000..79a49ef91d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Model200Response.cs @@ -0,0 +1,142 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Model for testing model name starting with number + /// + [DataContract(Name = "200_response")] + public partial class Model200Response : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name. + /// _class. + public Model200Response(int name = default(int), string _class = default(string)) + { + this.Name = name; + this.Class = _class; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public int Name { get; set; } + + /// + /// Gets or Sets Class + /// + [DataMember(Name = "class", EmitDefaultValue = false)] + public string Class { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Model200Response {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Class: ").Append(Class).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Model200Response).AreEqual; + } + + /// + /// Returns true if Model200Response instances are equal + /// + /// Instance of Model200Response to be compared + /// Boolean + public bool Equals(Model200Response input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + if (this.Class != null) + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ModelClient.cs new file mode 100644 index 0000000000..1995ec4b16 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ModelClient.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ModelClient + /// + [DataContract(Name = "_Client")] + public partial class ModelClient : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _client. + public ModelClient(string _client = default(string)) + { + this._Client = _client; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets _Client + /// + [DataMember(Name = "client", EmitDefaultValue = false)] + public string _Client { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ModelClient {\n"); + sb.Append(" _Client: ").Append(_Client).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ModelClient).AreEqual; + } + + /// + /// Returns true if ModelClient instances are equal + /// + /// Instance of ModelClient to be compared + /// Boolean + public bool Equals(ModelClient input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this._Client != null) + { + hashCode = (hashCode * 59) + this._Client.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Name.cs new file mode 100644 index 0000000000..1d4e760506 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Name.cs @@ -0,0 +1,182 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Model for testing model name same as property name + /// + [DataContract(Name = "Name")] + public partial class Name : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Name() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// name (required). + /// property. + public Name(int name = default(int), string property = default(string)) + { + this._Name = name; + this.Property = property; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets _Name + /// + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] + public int _Name { get; set; } + + /// + /// Gets or Sets SnakeCase + /// + [DataMember(Name = "snake_case", EmitDefaultValue = false)] + public int SnakeCase { get; private set; } + + /// + /// Returns false as SnakeCase should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeSnakeCase() + { + return false; + } + /// + /// Gets or Sets Property + /// + [DataMember(Name = "property", EmitDefaultValue = false)] + public string Property { get; set; } + + /// + /// Gets or Sets _123Number + /// + [DataMember(Name = "123Number", EmitDefaultValue = false)] + public int _123Number { get; private set; } + + /// + /// Returns false as _123Number should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize_123Number() + { + return false; + } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" _Name: ").Append(_Name).Append("\n"); + sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); + sb.Append(" Property: ").Append(Property).Append("\n"); + sb.Append(" _123Number: ").Append(_123Number).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Name).AreEqual; + } + + /// + /// Returns true if Name instances are equal + /// + /// Instance of Name to be compared + /// Boolean + public bool Equals(Name input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this._Name.GetHashCode(); + hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); + if (this.Property != null) + { + hashCode = (hashCode * 59) + this.Property.GetHashCode(); + } + hashCode = (hashCode * 59) + this._123Number.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs new file mode 100644 index 0000000000..57555c3767 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs @@ -0,0 +1,265 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// NullableClass + /// + [DataContract(Name = "NullableClass")] + public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// integerProp. + /// numberProp. + /// booleanProp. + /// stringProp. + /// dateProp. + /// datetimeProp. + /// arrayNullableProp. + /// arrayAndItemsNullableProp. + /// arrayItemsNullable. + /// objectNullableProp. + /// objectAndItemsNullableProp. + /// objectItemsNullable. + public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) : base() + { + this.IntegerProp = integerProp; + this.NumberProp = numberProp; + this.BooleanProp = booleanProp; + this.StringProp = stringProp; + this.DateProp = dateProp; + this.DatetimeProp = datetimeProp; + this.ArrayNullableProp = arrayNullableProp; + this.ArrayAndItemsNullableProp = arrayAndItemsNullableProp; + this.ArrayItemsNullable = arrayItemsNullable; + this.ObjectNullableProp = objectNullableProp; + this.ObjectAndItemsNullableProp = objectAndItemsNullableProp; + this.ObjectItemsNullable = objectItemsNullable; + } + + /// + /// Gets or Sets IntegerProp + /// + [DataMember(Name = "integer_prop", EmitDefaultValue = true)] + public int? IntegerProp { get; set; } + + /// + /// Gets or Sets NumberProp + /// + [DataMember(Name = "number_prop", EmitDefaultValue = true)] + public decimal? NumberProp { get; set; } + + /// + /// Gets or Sets BooleanProp + /// + [DataMember(Name = "boolean_prop", EmitDefaultValue = true)] + public bool? BooleanProp { get; set; } + + /// + /// Gets or Sets StringProp + /// + [DataMember(Name = "string_prop", EmitDefaultValue = true)] + public string StringProp { get; set; } + + /// + /// Gets or Sets DateProp + /// + [DataMember(Name = "date_prop", EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? DateProp { get; set; } + + /// + /// Gets or Sets DatetimeProp + /// + [DataMember(Name = "datetime_prop", EmitDefaultValue = true)] + public DateTime? DatetimeProp { get; set; } + + /// + /// Gets or Sets ArrayNullableProp + /// + [DataMember(Name = "array_nullable_prop", EmitDefaultValue = true)] + public List ArrayNullableProp { get; set; } + + /// + /// Gets or Sets ArrayAndItemsNullableProp + /// + [DataMember(Name = "array_and_items_nullable_prop", EmitDefaultValue = true)] + public List ArrayAndItemsNullableProp { get; set; } + + /// + /// Gets or Sets ArrayItemsNullable + /// + [DataMember(Name = "array_items_nullable", EmitDefaultValue = false)] + public List ArrayItemsNullable { get; set; } + + /// + /// Gets or Sets ObjectNullableProp + /// + [DataMember(Name = "object_nullable_prop", EmitDefaultValue = true)] + public Dictionary ObjectNullableProp { get; set; } + + /// + /// Gets or Sets ObjectAndItemsNullableProp + /// + [DataMember(Name = "object_and_items_nullable_prop", EmitDefaultValue = true)] + public Dictionary ObjectAndItemsNullableProp { get; set; } + + /// + /// Gets or Sets ObjectItemsNullable + /// + [DataMember(Name = "object_items_nullable", EmitDefaultValue = false)] + public Dictionary ObjectItemsNullable { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NullableClass {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); + sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); + sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); + sb.Append(" StringProp: ").Append(StringProp).Append("\n"); + sb.Append(" DateProp: ").Append(DateProp).Append("\n"); + sb.Append(" DatetimeProp: ").Append(DatetimeProp).Append("\n"); + sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); + sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); + sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); + sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); + sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); + sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as NullableClass).AreEqual; + } + + /// + /// Returns true if NullableClass instances are equal + /// + /// Instance of NullableClass to be compared + /// Boolean + public bool Equals(NullableClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + if (this.IntegerProp != null) + { + hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); + } + if (this.NumberProp != null) + { + hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); + } + if (this.BooleanProp != null) + { + hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); + } + if (this.StringProp != null) + { + hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); + } + if (this.DateProp != null) + { + hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); + } + if (this.DatetimeProp != null) + { + hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); + } + if (this.ArrayNullableProp != null) + { + hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); + } + if (this.ArrayAndItemsNullableProp != null) + { + hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); + } + if (this.ArrayItemsNullable != null) + { + hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); + } + if (this.ObjectNullableProp != null) + { + hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); + } + if (this.ObjectAndItemsNullableProp != null) + { + hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); + } + if (this.ObjectItemsNullable != null) + { + hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableShape.cs new file mode 100644 index 0000000000..01cedb8807 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableShape.cs @@ -0,0 +1,324 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// The value may be a shape or the 'null' value. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. + /// + [JsonConverter(typeof(NullableShapeJsonConverter))] + [DataContract(Name = "NullableShape")] + public partial class NullableShape : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + public NullableShape() + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Triangle. + public NullableShape(Triangle actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Quadrilateral. + public NullableShape(Quadrilateral actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Quadrilateral)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Triangle)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Quadrilateral, Triangle"); + } + } + } + + /// + /// Get the actual instance of `Triangle`. If the actual instance is not `Triangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of Triangle + public Triangle GetTriangle() + { + return (Triangle)this.ActualInstance; + } + + /// + /// Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of Quadrilateral + public Quadrilateral GetQuadrilateral() + { + return (Quadrilateral)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class NullableShape {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, NullableShape.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of NullableShape + /// + /// JSON string + /// An instance of NullableShape + public static NullableShape FromJson(string jsonString) + { + NullableShape newNullableShape = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newNullableShape; + } + + try + { + var discriminatorObj = JObject.Parse(jsonString)["shapeType"]; + string discriminatorValue = discriminatorObj == null ?string.Empty :discriminatorObj.ToString(); + switch (discriminatorValue) + { + case "Quadrilateral": + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); + return newNullableShape; + case "Triangle": + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); + return newNullableShape; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); + break; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(string.Format("Failed to parse the json data : `{0}` {1}", jsonString, ex.ToString())); + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Quadrilateral).GetProperty("AdditionalProperties") == null) + { + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.SerializerSettings)); + } + else + { + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Quadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Triangle).GetProperty("AdditionalProperties") == null) + { + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.SerializerSettings)); + } + else + { + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Triangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newNullableShape; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as NullableShape).AreEqual; + } + + /// + /// Returns true if NullableShape instances are equal + /// + /// Instance of NullableShape to be compared + /// Boolean + public bool Equals(NullableShape input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for NullableShape + /// + public class NullableShapeJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return NullableShape.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NumberOnly.cs new file mode 100644 index 0000000000..0331e1c8db --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -0,0 +1,132 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// NumberOnly + /// + [CLSCompliant(true)] + [ComVisible(true)] + [DataContract(Name = "NumberOnly")] + public partial class NumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// justNumber. + public NumberOnly(decimal justNumber = default(decimal)) + { + this.JustNumber = justNumber; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets JustNumber + /// + [DataMember(Name = "JustNumber", EmitDefaultValue = false)] + public decimal JustNumber { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NumberOnly {\n"); + sb.Append(" JustNumber: ").Append(JustNumber).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as NumberOnly).AreEqual; + } + + /// + /// Returns true if NumberOnly instances are equal + /// + /// Instance of NumberOnly to be compared + /// Boolean + public bool Equals(NumberOnly input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.JustNumber.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs new file mode 100644 index 0000000000..86ea32998f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -0,0 +1,171 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ObjectWithDeprecatedFields + /// + [DataContract(Name = "ObjectWithDeprecatedFields")] + public partial class ObjectWithDeprecatedFields : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// uuid. + /// id. + /// deprecatedRef. + /// bars. + public ObjectWithDeprecatedFields(string uuid = default(string), decimal id = default(decimal), DeprecatedObject deprecatedRef = default(DeprecatedObject), List bars = default(List)) + { + this.Uuid = uuid; + this.Id = id; + this.DeprecatedRef = deprecatedRef; + this.Bars = bars; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Uuid + /// + [DataMember(Name = "uuid", EmitDefaultValue = false)] + public string Uuid { get; set; } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + [Obsolete] + public decimal Id { get; set; } + + /// + /// Gets or Sets DeprecatedRef + /// + [DataMember(Name = "deprecatedRef", EmitDefaultValue = false)] + [Obsolete] + public DeprecatedObject DeprecatedRef { get; set; } + + /// + /// Gets or Sets Bars + /// + [DataMember(Name = "bars", EmitDefaultValue = false)] + [Obsolete] + public List Bars { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ObjectWithDeprecatedFields {\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" DeprecatedRef: ").Append(DeprecatedRef).Append("\n"); + sb.Append(" Bars: ").Append(Bars).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ObjectWithDeprecatedFields).AreEqual; + } + + /// + /// Returns true if ObjectWithDeprecatedFields instances are equal + /// + /// Instance of ObjectWithDeprecatedFields to be compared + /// Boolean + public bool Equals(ObjectWithDeprecatedFields input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Uuid != null) + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + if (this.DeprecatedRef != null) + { + hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); + } + if (this.Bars != null) + { + hashCode = (hashCode * 59) + this.Bars.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Order.cs new file mode 100644 index 0000000000..5c52482e79 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Order.cs @@ -0,0 +1,210 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Order + /// + [DataContract(Name = "Order")] + public partial class Order : IEquatable, IValidatableObject + { + /// + /// Order Status + /// + /// Order Status + [JsonConverter(typeof(StringEnumConverter))] + public enum StatusEnum + { + /// + /// Enum Placed for value: placed + /// + [EnumMember(Value = "placed")] + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + [EnumMember(Value = "approved")] + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + [EnumMember(Value = "delivered")] + Delivered = 3 + + } + + + /// + /// Order Status + /// + /// Order Status + [DataMember(Name = "status", EmitDefaultValue = false)] + public StatusEnum? Status { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// id. + /// petId. + /// quantity. + /// shipDate. + /// Order Status. + /// complete (default to false). + public Order(long id = default(long), long petId = default(long), int quantity = default(int), DateTime shipDate = default(DateTime), StatusEnum? status = default(StatusEnum?), bool complete = false) + { + this.Id = id; + this.PetId = petId; + this.Quantity = quantity; + this.ShipDate = shipDate; + this.Status = status; + this.Complete = complete; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets PetId + /// + [DataMember(Name = "petId", EmitDefaultValue = false)] + public long PetId { get; set; } + + /// + /// Gets or Sets Quantity + /// + [DataMember(Name = "quantity", EmitDefaultValue = false)] + public int Quantity { get; set; } + + /// + /// Gets or Sets ShipDate + /// + [DataMember(Name = "shipDate", EmitDefaultValue = false)] + public DateTime ShipDate { get; set; } + + /// + /// Gets or Sets Complete + /// + [DataMember(Name = "complete", EmitDefaultValue = true)] + public bool Complete { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Order {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PetId: ").Append(PetId).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Order).AreEqual; + } + + /// + /// Returns true if Order instances are equal + /// + /// Instance of Order to be compared + /// Boolean + public bool Equals(Order input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.PetId.GetHashCode(); + hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); + if (this.ShipDate != null) + { + hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + hashCode = (hashCode * 59) + this.Complete.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterComposite.cs new file mode 100644 index 0000000000..3209f6d624 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -0,0 +1,152 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// OuterComposite + /// + [DataContract(Name = "OuterComposite")] + public partial class OuterComposite : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// myNumber. + /// myString. + /// myBoolean. + public OuterComposite(decimal myNumber = default(decimal), string myString = default(string), bool myBoolean = default(bool)) + { + this.MyNumber = myNumber; + this.MyString = myString; + this.MyBoolean = myBoolean; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets MyNumber + /// + [DataMember(Name = "my_number", EmitDefaultValue = false)] + public decimal MyNumber { get; set; } + + /// + /// Gets or Sets MyString + /// + [DataMember(Name = "my_string", EmitDefaultValue = false)] + public string MyString { get; set; } + + /// + /// Gets or Sets MyBoolean + /// + [DataMember(Name = "my_boolean", EmitDefaultValue = true)] + public bool MyBoolean { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OuterComposite {\n"); + sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); + sb.Append(" MyString: ").Append(MyString).Append("\n"); + sb.Append(" MyBoolean: ").Append(MyBoolean).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as OuterComposite).AreEqual; + } + + /// + /// Returns true if OuterComposite instances are equal + /// + /// Instance of OuterComposite to be compared + /// Boolean + public bool Equals(OuterComposite input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.MyNumber.GetHashCode(); + if (this.MyString != null) + { + hashCode = (hashCode * 59) + this.MyString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnum.cs new file mode 100644 index 0000000000..2aa496a2e0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -0,0 +1,55 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Defines OuterEnum + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OuterEnum + { + /// + /// Enum Placed for value: placed + /// + [EnumMember(Value = "placed")] + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + [EnumMember(Value = "approved")] + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + [EnumMember(Value = "delivered")] + Delivered = 3 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs new file mode 100644 index 0000000000..dd79c7010d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -0,0 +1,55 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Defines OuterEnumDefaultValue + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OuterEnumDefaultValue + { + /// + /// Enum Placed for value: placed + /// + [EnumMember(Value = "placed")] + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + [EnumMember(Value = "approved")] + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + [EnumMember(Value = "delivered")] + Delivered = 3 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnumInteger.cs new file mode 100644 index 0000000000..44dc91c700 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Defines OuterEnumInteger + /// + public enum OuterEnumInteger + { + /// + /// Enum NUMBER_0 for value: 0 + /// + NUMBER_0 = 0, + + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs new file mode 100644 index 0000000000..b927507cf9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Defines OuterEnumIntegerDefaultValue + /// + public enum OuterEnumIntegerDefaultValue + { + /// + /// Enum NUMBER_0 for value: 0 + /// + NUMBER_0 = 0, + + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ParentPet.cs new file mode 100644 index 0000000000..49bed67986 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ParentPet.cs @@ -0,0 +1,146 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ParentPet + /// + [DataContract(Name = "ParentPet")] + [JsonConverter(typeof(JsonSubtypes), "PetType")] + [JsonSubtypes.KnownSubType(typeof(ChildCat), "ChildCat")] + public partial class ParentPet : GrandparentAnimal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ParentPet() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// petType (required) (default to "ParentPet"). + public ParentPet(string petType = "ParentPet") : base(petType) + { + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ParentPet {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ParentPet).AreEqual; + } + + /// + /// Returns true if ParentPet instances are equal + /// + /// Instance of ParentPet to be compared + /// Boolean + public bool Equals(ParentPet input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + foreach (var x in base.BaseValidate(validationContext)) + { + yield return x; + } + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Pet.cs new file mode 100644 index 0000000000..0e6f950d7f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Pet.cs @@ -0,0 +1,237 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Pet + /// + [DataContract(Name = "Pet")] + public partial class Pet : IEquatable, IValidatableObject + { + /// + /// pet status in the store + /// + /// pet status in the store + [JsonConverter(typeof(StringEnumConverter))] + public enum StatusEnum + { + /// + /// Enum Available for value: available + /// + [EnumMember(Value = "available")] + Available = 1, + + /// + /// Enum Pending for value: pending + /// + [EnumMember(Value = "pending")] + Pending = 2, + + /// + /// Enum Sold for value: sold + /// + [EnumMember(Value = "sold")] + Sold = 3 + + } + + + /// + /// pet status in the store + /// + /// pet status in the store + [DataMember(Name = "status", EmitDefaultValue = false)] + public StatusEnum? Status { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Pet() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// id. + /// category. + /// name (required). + /// photoUrls (required). + /// tags. + /// pet status in the store. + public Pet(long id = default(long), Category category = default(Category), string name = default(string), List photoUrls = default(List), List tags = default(List), StatusEnum? status = default(StatusEnum?)) + { + // to ensure "name" is required (not null) + if (name == null) + { + throw new ArgumentNullException("name is a required property for Pet and cannot be null"); + } + this.Name = name; + // to ensure "photoUrls" is required (not null) + if (photoUrls == null) + { + throw new ArgumentNullException("photoUrls is a required property for Pet and cannot be null"); + } + this.PhotoUrls = photoUrls; + this.Id = id; + this.Category = category; + this.Tags = tags; + this.Status = status; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets Category + /// + [DataMember(Name = "category", EmitDefaultValue = false)] + public Category Category { get; set; } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = true)] + public List PhotoUrls { get; set; } + + /// + /// Gets or Sets Tags + /// + [DataMember(Name = "tags", EmitDefaultValue = false)] + public List Tags { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Pet {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Tags: ").Append(Tags).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Pet).AreEqual; + } + + /// + /// Returns true if Pet instances are equal + /// + /// Instance of Pet to be compared + /// Boolean + public bool Equals(Pet input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + if (this.Category != null) + { + hashCode = (hashCode * 59) + this.Category.GetHashCode(); + } + if (this.Name != null) + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + if (this.PhotoUrls != null) + { + hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); + } + if (this.Tags != null) + { + hashCode = (hashCode * 59) + this.Tags.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Pig.cs new file mode 100644 index 0000000000..c599574b1c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Pig.cs @@ -0,0 +1,315 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Pig + /// + [JsonConverter(typeof(PigJsonConverter))] + [DataContract(Name = "Pig")] + public partial class Pig : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of BasquePig. + public Pig(BasquePig actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of DanishPig. + public Pig(DanishPig actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(BasquePig)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(DanishPig)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: BasquePig, DanishPig"); + } + } + } + + /// + /// Get the actual instance of `BasquePig`. If the actual instance is not `BasquePig`, + /// the InvalidClassException will be thrown + /// + /// An instance of BasquePig + public BasquePig GetBasquePig() + { + return (BasquePig)this.ActualInstance; + } + + /// + /// Get the actual instance of `DanishPig`. If the actual instance is not `DanishPig`, + /// the InvalidClassException will be thrown + /// + /// An instance of DanishPig + public DanishPig GetDanishPig() + { + return (DanishPig)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Pig {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Pig.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Pig + /// + /// JSON string + /// An instance of Pig + public static Pig FromJson(string jsonString) + { + Pig newPig = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newPig; + } + + try + { + var discriminatorObj = JObject.Parse(jsonString)["className"]; + string discriminatorValue = discriminatorObj == null ?string.Empty :discriminatorObj.ToString(); + switch (discriminatorValue) + { + case "BasquePig": + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); + return newPig; + case "DanishPig": + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); + return newPig; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); + break; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(string.Format("Failed to parse the json data : `{0}` {1}", jsonString, ex.ToString())); + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(BasquePig).GetProperty("AdditionalProperties") == null) + { + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.SerializerSettings)); + } + else + { + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("BasquePig"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(DanishPig).GetProperty("AdditionalProperties") == null) + { + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.SerializerSettings)); + } + else + { + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("DanishPig"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newPig; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Pig).AreEqual; + } + + /// + /// Returns true if Pig instances are equal + /// + /// Instance of Pig to be compared + /// Boolean + public bool Equals(Pig input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Pig + /// + public class PigJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Pig.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/PolymorphicProperty.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/PolymorphicProperty.cs new file mode 100644 index 0000000000..0ce4e18eb2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/PolymorphicProperty.cs @@ -0,0 +1,383 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// PolymorphicProperty + /// + [JsonConverter(typeof(PolymorphicPropertyJsonConverter))] + [DataContract(Name = "PolymorphicProperty")] + public partial class PolymorphicProperty : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of bool. + public PolymorphicProperty(bool actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of string. + public PolymorphicProperty(string actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Object. + public PolymorphicProperty(Object actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of List<string>. + public PolymorphicProperty(List actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(List)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Object)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(bool)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(string)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: List, Object, bool, string"); + } + } + } + + /// + /// Get the actual instance of `bool`. If the actual instance is not `bool`, + /// the InvalidClassException will be thrown + /// + /// An instance of bool + public bool GetBool() + { + return (bool)this.ActualInstance; + } + + /// + /// Get the actual instance of `string`. If the actual instance is not `string`, + /// the InvalidClassException will be thrown + /// + /// An instance of string + public string GetString() + { + return (string)this.ActualInstance; + } + + /// + /// Get the actual instance of `Object`. If the actual instance is not `Object`, + /// the InvalidClassException will be thrown + /// + /// An instance of Object + public Object GetObject() + { + return (Object)this.ActualInstance; + } + + /// + /// Get the actual instance of `List<string>`. If the actual instance is not `List<string>`, + /// the InvalidClassException will be thrown + /// + /// An instance of List<string> + public List GetListString() + { + return (List)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class PolymorphicProperty {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, PolymorphicProperty.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of PolymorphicProperty + /// + /// JSON string + /// An instance of PolymorphicProperty + public static PolymorphicProperty FromJson(string jsonString) + { + PolymorphicProperty newPolymorphicProperty = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newPolymorphicProperty; + } + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(List).GetProperty("AdditionalProperties") == null) + { + newPolymorphicProperty = new PolymorphicProperty(JsonConvert.DeserializeObject>(jsonString, PolymorphicProperty.SerializerSettings)); + } + else + { + newPolymorphicProperty = new PolymorphicProperty(JsonConvert.DeserializeObject>(jsonString, PolymorphicProperty.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("List"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into List: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Object).GetProperty("AdditionalProperties") == null) + { + newPolymorphicProperty = new PolymorphicProperty(JsonConvert.DeserializeObject(jsonString, PolymorphicProperty.SerializerSettings)); + } + else + { + newPolymorphicProperty = new PolymorphicProperty(JsonConvert.DeserializeObject(jsonString, PolymorphicProperty.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Object"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Object: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(bool).GetProperty("AdditionalProperties") == null) + { + newPolymorphicProperty = new PolymorphicProperty(JsonConvert.DeserializeObject(jsonString, PolymorphicProperty.SerializerSettings)); + } + else + { + newPolymorphicProperty = new PolymorphicProperty(JsonConvert.DeserializeObject(jsonString, PolymorphicProperty.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("bool"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into bool: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(string).GetProperty("AdditionalProperties") == null) + { + newPolymorphicProperty = new PolymorphicProperty(JsonConvert.DeserializeObject(jsonString, PolymorphicProperty.SerializerSettings)); + } + else + { + newPolymorphicProperty = new PolymorphicProperty(JsonConvert.DeserializeObject(jsonString, PolymorphicProperty.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("string"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into string: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newPolymorphicProperty; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as PolymorphicProperty).AreEqual; + } + + /// + /// Returns true if PolymorphicProperty instances are equal + /// + /// Instance of PolymorphicProperty to be compared + /// Boolean + public bool Equals(PolymorphicProperty input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for PolymorphicProperty + /// + public class PolymorphicPropertyJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(PolymorphicProperty).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return PolymorphicProperty.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Quadrilateral.cs new file mode 100644 index 0000000000..2e4fc5cb04 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -0,0 +1,315 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Quadrilateral + /// + [JsonConverter(typeof(QuadrilateralJsonConverter))] + [DataContract(Name = "Quadrilateral")] + public partial class Quadrilateral : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of SimpleQuadrilateral. + public Quadrilateral(SimpleQuadrilateral actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of ComplexQuadrilateral. + public Quadrilateral(ComplexQuadrilateral actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(ComplexQuadrilateral)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(SimpleQuadrilateral)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: ComplexQuadrilateral, SimpleQuadrilateral"); + } + } + } + + /// + /// Get the actual instance of `SimpleQuadrilateral`. If the actual instance is not `SimpleQuadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of SimpleQuadrilateral + public SimpleQuadrilateral GetSimpleQuadrilateral() + { + return (SimpleQuadrilateral)this.ActualInstance; + } + + /// + /// Get the actual instance of `ComplexQuadrilateral`. If the actual instance is not `ComplexQuadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of ComplexQuadrilateral + public ComplexQuadrilateral GetComplexQuadrilateral() + { + return (ComplexQuadrilateral)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Quadrilateral {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Quadrilateral.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Quadrilateral + /// + /// JSON string + /// An instance of Quadrilateral + public static Quadrilateral FromJson(string jsonString) + { + Quadrilateral newQuadrilateral = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newQuadrilateral; + } + + try + { + var discriminatorObj = JObject.Parse(jsonString)["quadrilateralType"]; + string discriminatorValue = discriminatorObj == null ?string.Empty :discriminatorObj.ToString(); + switch (discriminatorValue) + { + case "ComplexQuadrilateral": + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); + return newQuadrilateral; + case "SimpleQuadrilateral": + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); + return newQuadrilateral; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); + break; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(string.Format("Failed to parse the json data : `{0}` {1}", jsonString, ex.ToString())); + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(ComplexQuadrilateral).GetProperty("AdditionalProperties") == null) + { + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.SerializerSettings)); + } + else + { + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("ComplexQuadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(SimpleQuadrilateral).GetProperty("AdditionalProperties") == null) + { + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.SerializerSettings)); + } + else + { + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("SimpleQuadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newQuadrilateral; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Quadrilateral).AreEqual; + } + + /// + /// Returns true if Quadrilateral instances are equal + /// + /// Instance of Quadrilateral to be compared + /// Boolean + public bool Equals(Quadrilateral input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Quadrilateral + /// + public class QuadrilateralJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Quadrilateral.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs new file mode 100644 index 0000000000..d5be5ea3c9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -0,0 +1,145 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// QuadrilateralInterface + /// + [DataContract(Name = "QuadrilateralInterface")] + public partial class QuadrilateralInterface : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected QuadrilateralInterface() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// quadrilateralType (required). + public QuadrilateralInterface(string quadrilateralType = default(string)) + { + // to ensure "quadrilateralType" is required (not null) + if (quadrilateralType == null) + { + throw new ArgumentNullException("quadrilateralType is a required property for QuadrilateralInterface and cannot be null"); + } + this.QuadrilateralType = quadrilateralType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets QuadrilateralType + /// + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] + public string QuadrilateralType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class QuadrilateralInterface {\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as QuadrilateralInterface).AreEqual; + } + + /// + /// Returns true if QuadrilateralInterface instances are equal + /// + /// Instance of QuadrilateralInterface to be compared + /// Boolean + public bool Equals(QuadrilateralInterface input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.QuadrilateralType != null) + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs new file mode 100644 index 0000000000..ad59ca8328 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -0,0 +1,151 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ReadOnlyFirst + /// + [DataContract(Name = "ReadOnlyFirst")] + public partial class ReadOnlyFirst : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// baz. + public ReadOnlyFirst(string baz = default(string)) + { + this.Baz = baz; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Bar + /// + [DataMember(Name = "bar", EmitDefaultValue = false)] + public string Bar { get; private set; } + + /// + /// Returns false as Bar should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBar() + { + return false; + } + /// + /// Gets or Sets Baz + /// + [DataMember(Name = "baz", EmitDefaultValue = false)] + public string Baz { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ReadOnlyFirst {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" Baz: ").Append(Baz).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ReadOnlyFirst).AreEqual; + } + + /// + /// Returns true if ReadOnlyFirst instances are equal + /// + /// Instance of ReadOnlyFirst to be compared + /// Boolean + public bool Equals(ReadOnlyFirst input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.Bar != null) + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } + if (this.Baz != null) + { + hashCode = (hashCode * 59) + this.Baz.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Return.cs new file mode 100644 index 0000000000..e702e01570 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Return.cs @@ -0,0 +1,129 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Model for testing reserved words + /// + [DataContract(Name = "Return")] + public partial class Return : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _return. + public Return(int _return = default(int)) + { + this._Return = _return; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets _Return + /// + [DataMember(Name = "return", EmitDefaultValue = false)] + public int _Return { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Return {\n"); + sb.Append(" _Return: ").Append(_Return).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Return).AreEqual; + } + + /// + /// Returns true if Return instances are equal + /// + /// Instance of Return to be compared + /// Boolean + public bool Equals(Return input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this._Return.GetHashCode(); + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ScaleneTriangle.cs new file mode 100644 index 0000000000..236020031e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ScaleneTriangle + /// + [DataContract(Name = "ScaleneTriangle")] + public partial class ScaleneTriangle : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ScaleneTriangle() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// triangleType (required). + public ScaleneTriangle(string shapeType = default(string), string triangleType = default(string)) + { + // to ensure "shapeType" is required (not null) + if (shapeType == null) + { + throw new ArgumentNullException("shapeType is a required property for ScaleneTriangle and cannot be null"); + } + this.ShapeType = shapeType; + // to ensure "triangleType" is required (not null) + if (triangleType == null) + { + throw new ArgumentNullException("triangleType is a required property for ScaleneTriangle and cannot be null"); + } + this.TriangleType = triangleType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] + public string ShapeType { get; set; } + + /// + /// Gets or Sets TriangleType + /// + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] + public string TriangleType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ScaleneTriangle {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ScaleneTriangle).AreEqual; + } + + /// + /// Returns true if ScaleneTriangle instances are equal + /// + /// Instance of ScaleneTriangle to be compared + /// Boolean + public bool Equals(ScaleneTriangle input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ShapeType != null) + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } + if (this.TriangleType != null) + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Shape.cs new file mode 100644 index 0000000000..bc73c0d68a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Shape.cs @@ -0,0 +1,315 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Shape + /// + [JsonConverter(typeof(ShapeJsonConverter))] + [DataContract(Name = "Shape")] + public partial class Shape : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Triangle. + public Shape(Triangle actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Quadrilateral. + public Shape(Quadrilateral actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Quadrilateral)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Triangle)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Quadrilateral, Triangle"); + } + } + } + + /// + /// Get the actual instance of `Triangle`. If the actual instance is not `Triangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of Triangle + public Triangle GetTriangle() + { + return (Triangle)this.ActualInstance; + } + + /// + /// Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of Quadrilateral + public Quadrilateral GetQuadrilateral() + { + return (Quadrilateral)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Shape {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Shape.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Shape + /// + /// JSON string + /// An instance of Shape + public static Shape FromJson(string jsonString) + { + Shape newShape = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newShape; + } + + try + { + var discriminatorObj = JObject.Parse(jsonString)["shapeType"]; + string discriminatorValue = discriminatorObj == null ?string.Empty :discriminatorObj.ToString(); + switch (discriminatorValue) + { + case "Quadrilateral": + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); + return newShape; + case "Triangle": + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); + return newShape; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); + break; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(string.Format("Failed to parse the json data : `{0}` {1}", jsonString, ex.ToString())); + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Quadrilateral).GetProperty("AdditionalProperties") == null) + { + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.SerializerSettings)); + } + else + { + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Quadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Triangle).GetProperty("AdditionalProperties") == null) + { + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.SerializerSettings)); + } + else + { + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Triangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newShape; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Shape).AreEqual; + } + + /// + /// Returns true if Shape instances are equal + /// + /// Instance of Shape to be compared + /// Boolean + public bool Equals(Shape input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Shape + /// + public class ShapeJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Shape.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ShapeInterface.cs new file mode 100644 index 0000000000..c9294b0b4e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -0,0 +1,145 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ShapeInterface + /// + [DataContract(Name = "ShapeInterface")] + public partial class ShapeInterface : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ShapeInterface() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + public ShapeInterface(string shapeType = default(string)) + { + // to ensure "shapeType" is required (not null) + if (shapeType == null) + { + throw new ArgumentNullException("shapeType is a required property for ShapeInterface and cannot be null"); + } + this.ShapeType = shapeType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] + public string ShapeType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ShapeInterface {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ShapeInterface).AreEqual; + } + + /// + /// Returns true if ShapeInterface instances are equal + /// + /// Instance of ShapeInterface to be compared + /// Boolean + public bool Equals(ShapeInterface input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ShapeType != null) + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ShapeOrNull.cs new file mode 100644 index 0000000000..a6d3624c26 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -0,0 +1,324 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + /// + [JsonConverter(typeof(ShapeOrNullJsonConverter))] + [DataContract(Name = "ShapeOrNull")] + public partial class ShapeOrNull : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + public ShapeOrNull() + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Triangle. + public ShapeOrNull(Triangle actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Quadrilateral. + public ShapeOrNull(Quadrilateral actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Quadrilateral)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Triangle)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Quadrilateral, Triangle"); + } + } + } + + /// + /// Get the actual instance of `Triangle`. If the actual instance is not `Triangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of Triangle + public Triangle GetTriangle() + { + return (Triangle)this.ActualInstance; + } + + /// + /// Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of Quadrilateral + public Quadrilateral GetQuadrilateral() + { + return (Quadrilateral)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ShapeOrNull {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, ShapeOrNull.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of ShapeOrNull + /// + /// JSON string + /// An instance of ShapeOrNull + public static ShapeOrNull FromJson(string jsonString) + { + ShapeOrNull newShapeOrNull = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newShapeOrNull; + } + + try + { + var discriminatorObj = JObject.Parse(jsonString)["shapeType"]; + string discriminatorValue = discriminatorObj == null ?string.Empty :discriminatorObj.ToString(); + switch (discriminatorValue) + { + case "Quadrilateral": + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); + return newShapeOrNull; + case "Triangle": + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); + return newShapeOrNull; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); + break; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(string.Format("Failed to parse the json data : `{0}` {1}", jsonString, ex.ToString())); + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Quadrilateral).GetProperty("AdditionalProperties") == null) + { + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.SerializerSettings)); + } + else + { + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Quadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Triangle).GetProperty("AdditionalProperties") == null) + { + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.SerializerSettings)); + } + else + { + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Triangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newShapeOrNull; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ShapeOrNull).AreEqual; + } + + /// + /// Returns true if ShapeOrNull instances are equal + /// + /// Instance of ShapeOrNull to be compared + /// Boolean + public bool Equals(ShapeOrNull input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for ShapeOrNull + /// + public class ShapeOrNullJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return ShapeOrNull.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs new file mode 100644 index 0000000000..59397bf30f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// SimpleQuadrilateral + /// + [DataContract(Name = "SimpleQuadrilateral")] + public partial class SimpleQuadrilateral : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected SimpleQuadrilateral() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// quadrilateralType (required). + public SimpleQuadrilateral(string shapeType = default(string), string quadrilateralType = default(string)) + { + // to ensure "shapeType" is required (not null) + if (shapeType == null) + { + throw new ArgumentNullException("shapeType is a required property for SimpleQuadrilateral and cannot be null"); + } + this.ShapeType = shapeType; + // to ensure "quadrilateralType" is required (not null) + if (quadrilateralType == null) + { + throw new ArgumentNullException("quadrilateralType is a required property for SimpleQuadrilateral and cannot be null"); + } + this.QuadrilateralType = quadrilateralType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] + public string ShapeType { get; set; } + + /// + /// Gets or Sets QuadrilateralType + /// + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] + public string QuadrilateralType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SimpleQuadrilateral {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as SimpleQuadrilateral).AreEqual; + } + + /// + /// Returns true if SimpleQuadrilateral instances are equal + /// + /// Instance of SimpleQuadrilateral to be compared + /// Boolean + public bool Equals(SimpleQuadrilateral input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ShapeType != null) + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } + if (this.QuadrilateralType != null) + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/SpecialModelName.cs new file mode 100644 index 0000000000..7800467822 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -0,0 +1,142 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// SpecialModelName + /// + [DataContract(Name = "_special_model.name_")] + public partial class SpecialModelName : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// specialPropertyName. + /// specialModelName. + public SpecialModelName(long specialPropertyName = default(long), string specialModelName = default(string)) + { + this.SpecialPropertyName = specialPropertyName; + this._SpecialModelName = specialModelName; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets SpecialPropertyName + /// + [DataMember(Name = "$special[property.name]", EmitDefaultValue = false)] + public long SpecialPropertyName { get; set; } + + /// + /// Gets or Sets _SpecialModelName + /// + [DataMember(Name = "_special_model.name_", EmitDefaultValue = false)] + public string _SpecialModelName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class SpecialModelName {\n"); + sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); + sb.Append(" _SpecialModelName: ").Append(_SpecialModelName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as SpecialModelName).AreEqual; + } + + /// + /// Returns true if SpecialModelName instances are equal + /// + /// Instance of SpecialModelName to be compared + /// Boolean + public bool Equals(SpecialModelName input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.SpecialPropertyName.GetHashCode(); + if (this._SpecialModelName != null) + { + hashCode = (hashCode * 59) + this._SpecialModelName.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Tag.cs new file mode 100644 index 0000000000..3df2c02e2c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Tag.cs @@ -0,0 +1,142 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Tag + /// + [DataContract(Name = "Tag")] + public partial class Tag : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id. + /// name. + public Tag(long id = default(long), string name = default(string)) + { + this.Id = id; + this.Name = name; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Tag {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Tag).AreEqual; + } + + /// + /// Returns true if Tag instances are equal + /// + /// Instance of Tag to be compared + /// Boolean + public bool Equals(Tag input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + if (this.Name != null) + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Triangle.cs new file mode 100644 index 0000000000..a68563c154 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Triangle.cs @@ -0,0 +1,364 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Triangle + /// + [JsonConverter(typeof(TriangleJsonConverter))] + [DataContract(Name = "Triangle")] + public partial class Triangle : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of EquilateralTriangle. + public Triangle(EquilateralTriangle actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of IsoscelesTriangle. + public Triangle(IsoscelesTriangle actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of ScaleneTriangle. + public Triangle(ScaleneTriangle actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(EquilateralTriangle)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(IsoscelesTriangle)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(ScaleneTriangle)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle"); + } + } + } + + /// + /// Get the actual instance of `EquilateralTriangle`. If the actual instance is not `EquilateralTriangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of EquilateralTriangle + public EquilateralTriangle GetEquilateralTriangle() + { + return (EquilateralTriangle)this.ActualInstance; + } + + /// + /// Get the actual instance of `IsoscelesTriangle`. If the actual instance is not `IsoscelesTriangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of IsoscelesTriangle + public IsoscelesTriangle GetIsoscelesTriangle() + { + return (IsoscelesTriangle)this.ActualInstance; + } + + /// + /// Get the actual instance of `ScaleneTriangle`. If the actual instance is not `ScaleneTriangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of ScaleneTriangle + public ScaleneTriangle GetScaleneTriangle() + { + return (ScaleneTriangle)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Triangle {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Triangle.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Triangle + /// + /// JSON string + /// An instance of Triangle + public static Triangle FromJson(string jsonString) + { + Triangle newTriangle = null; + + if (string.IsNullOrEmpty(jsonString)) + { + return newTriangle; + } + + try + { + var discriminatorObj = JObject.Parse(jsonString)["triangleType"]; + string discriminatorValue = discriminatorObj == null ?string.Empty :discriminatorObj.ToString(); + switch (discriminatorValue) + { + case "EquilateralTriangle": + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + return newTriangle; + case "IsoscelesTriangle": + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + return newTriangle; + case "ScaleneTriangle": + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + return newTriangle; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); + break; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(string.Format("Failed to parse the json data : `{0}` {1}", jsonString, ex.ToString())); + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(EquilateralTriangle).GetProperty("AdditionalProperties") == null) + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.SerializerSettings)); + } + else + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("EquilateralTriangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(IsoscelesTriangle).GetProperty("AdditionalProperties") == null) + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.SerializerSettings)); + } + else + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("IsoscelesTriangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(ScaleneTriangle).GetProperty("AdditionalProperties") == null) + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.SerializerSettings)); + } + else + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("ScaleneTriangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newTriangle; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Triangle).AreEqual; + } + + /// + /// Returns true if Triangle instances are equal + /// + /// Instance of Triangle to be compared + /// Boolean + public bool Equals(Triangle input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Triangle + /// + public class TriangleJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Triangle.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/TriangleInterface.cs new file mode 100644 index 0000000000..cdf2bd1f0f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -0,0 +1,145 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// TriangleInterface + /// + [DataContract(Name = "TriangleInterface")] + public partial class TriangleInterface : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected TriangleInterface() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// triangleType (required). + public TriangleInterface(string triangleType = default(string)) + { + // to ensure "triangleType" is required (not null) + if (triangleType == null) + { + throw new ArgumentNullException("triangleType is a required property for TriangleInterface and cannot be null"); + } + this.TriangleType = triangleType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets TriangleType + /// + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] + public string TriangleType { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TriangleInterface {\n"); + sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as TriangleInterface).AreEqual; + } + + /// + /// Returns true if TriangleInterface instances are equal + /// + /// Instance of TriangleInterface to be compared + /// Boolean + public bool Equals(TriangleInterface input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.TriangleType != null) + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/User.cs new file mode 100644 index 0000000000..5f2a3020c3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/User.cs @@ -0,0 +1,274 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// User + /// + [DataContract(Name = "User")] + public partial class User : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id. + /// username. + /// firstName. + /// lastName. + /// email. + /// password. + /// phone. + /// User Status. + /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value.. + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value.. + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389. + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values.. + public User(long id = default(long), string username = default(string), string firstName = default(string), string lastName = default(string), string email = default(string), string password = default(string), string phone = default(string), int userStatus = default(int), Object objectWithNoDeclaredProps = default(Object), Object objectWithNoDeclaredPropsNullable = default(Object), Object anyTypeProp = default(Object), Object anyTypePropNullable = default(Object)) + { + this.Id = id; + this.Username = username; + this.FirstName = firstName; + this.LastName = lastName; + this.Email = email; + this.Password = password; + this.Phone = phone; + this.UserStatus = userStatus; + this.ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; + this.ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + this.AnyTypeProp = anyTypeProp; + this.AnyTypePropNullable = anyTypePropNullable; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets Username + /// + [DataMember(Name = "username", EmitDefaultValue = false)] + public string Username { get; set; } + + /// + /// Gets or Sets FirstName + /// + [DataMember(Name = "firstName", EmitDefaultValue = false)] + public string FirstName { get; set; } + + /// + /// Gets or Sets LastName + /// + [DataMember(Name = "lastName", EmitDefaultValue = false)] + public string LastName { get; set; } + + /// + /// Gets or Sets Email + /// + [DataMember(Name = "email", EmitDefaultValue = false)] + public string Email { get; set; } + + /// + /// Gets or Sets Password + /// + [DataMember(Name = "password", EmitDefaultValue = false)] + public string Password { get; set; } + + /// + /// Gets or Sets Phone + /// + [DataMember(Name = "phone", EmitDefaultValue = false)] + public string Phone { get; set; } + + /// + /// User Status + /// + /// User Status + [DataMember(Name = "userStatus", EmitDefaultValue = false)] + public int UserStatus { get; set; } + + /// + /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + /// + /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + [DataMember(Name = "objectWithNoDeclaredProps", EmitDefaultValue = false)] + public Object ObjectWithNoDeclaredProps { get; set; } + + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + [DataMember(Name = "objectWithNoDeclaredPropsNullable", EmitDefaultValue = true)] + public Object ObjectWithNoDeclaredPropsNullable { get; set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + [DataMember(Name = "anyTypeProp", EmitDefaultValue = true)] + public Object AnyTypeProp { get; set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + [DataMember(Name = "anyTypePropNullable", EmitDefaultValue = true)] + public Object AnyTypePropNullable { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class User {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); + sb.Append(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); + sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); + sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); + sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as User).AreEqual; + } + + /// + /// Returns true if User instances are equal + /// + /// Instance of User to be compared + /// Boolean + public bool Equals(User input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + if (this.Username != null) + { + hashCode = (hashCode * 59) + this.Username.GetHashCode(); + } + if (this.FirstName != null) + { + hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); + } + if (this.LastName != null) + { + hashCode = (hashCode * 59) + this.LastName.GetHashCode(); + } + if (this.Email != null) + { + hashCode = (hashCode * 59) + this.Email.GetHashCode(); + } + if (this.Password != null) + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } + if (this.Phone != null) + { + hashCode = (hashCode * 59) + this.Phone.GetHashCode(); + } + hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); + if (this.ObjectWithNoDeclaredProps != null) + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); + } + if (this.ObjectWithNoDeclaredPropsNullable != null) + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + } + if (this.AnyTypeProp != null) + { + hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); + } + if (this.AnyTypePropNullable != null) + { + hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Whale.cs new file mode 100644 index 0000000000..62ae66415f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Whale.cs @@ -0,0 +1,165 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Whale + /// + [DataContract(Name = "whale")] + public partial class Whale : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Whale() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// hasBaleen. + /// hasTeeth. + /// className (required). + public Whale(bool hasBaleen = default(bool), bool hasTeeth = default(bool), string className = default(string)) + { + // to ensure "className" is required (not null) + if (className == null) + { + throw new ArgumentNullException("className is a required property for Whale and cannot be null"); + } + this.ClassName = className; + this.HasBaleen = hasBaleen; + this.HasTeeth = hasTeeth; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets HasBaleen + /// + [DataMember(Name = "hasBaleen", EmitDefaultValue = true)] + public bool HasBaleen { get; set; } + + /// + /// Gets or Sets HasTeeth + /// + [DataMember(Name = "hasTeeth", EmitDefaultValue = true)] + public bool HasTeeth { get; set; } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] + public string ClassName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Whale {\n"); + sb.Append(" HasBaleen: ").Append(HasBaleen).Append("\n"); + sb.Append(" HasTeeth: ").Append(HasTeeth).Append("\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Whale).AreEqual; + } + + /// + /// Returns true if Whale instances are equal + /// + /// Instance of Whale to be compared + /// Boolean + public bool Equals(Whale input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); + hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); + if (this.ClassName != null) + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Zebra.cs new file mode 100644 index 0000000000..8a3c713fe6 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Zebra.cs @@ -0,0 +1,182 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Zebra + /// + [DataContract(Name = "zebra")] + public partial class Zebra : Dictionary, IEquatable, IValidatableObject + { + /// + /// Defines Type + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum TypeEnum + { + /// + /// Enum Plains for value: plains + /// + [EnumMember(Value = "plains")] + Plains = 1, + + /// + /// Enum Mountain for value: mountain + /// + [EnumMember(Value = "mountain")] + Mountain = 2, + + /// + /// Enum Grevys for value: grevys + /// + [EnumMember(Value = "grevys")] + Grevys = 3 + + } + + + /// + /// Gets or Sets Type + /// + [DataMember(Name = "type", EmitDefaultValue = false)] + public TypeEnum? Type { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Zebra() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// type. + /// className (required). + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + { + // to ensure "className" is required (not null) + if (className == null) + { + throw new ArgumentNullException("className is a required property for Zebra and cannot be null"); + } + this.ClassName = className; + this.Type = type; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] + public string ClassName { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Zebra {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Zebra).AreEqual; + } + + /// + /// Returns true if Zebra instances are equal + /// + /// Instance of Zebra to be compared + /// Boolean + public bool Equals(Zebra input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = base.GetHashCode(); + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + if (this.ClassName != null) + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 0000000000..a747d50373 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net48/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,39 @@ + + + + false + net48 + Org.OpenAPITools + Org.OpenAPITools + Library + OpenAPI + OpenAPI + OpenAPI Library + A library generated from a OpenAPI doc + No Copyright + Org.OpenAPITools + 1.0.0 + bin\$(Configuration)\$(TargetFramework)\Org.OpenAPITools.xml + https://github.com/GIT_USER_ID/GIT_REPO_ID.git + git + Minor update + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/FILES index 4636f1cc22..e99cb9be46 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/FILES @@ -98,6 +98,9 @@ src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs +src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs +src/Org.OpenAPITools/Client/Auth/TokenResponse.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/EnumArrays.md index 8881585a4c..62e34f03db 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/EnumArrays.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/InlineResponseDefault.md deleted file mode 100644 index e3d55e133f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/InlineResponseDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/MapTest.md index dc1ebba4e7..516f9d4fd3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/docs/MapTest.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 76a930092b..5d048a005b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Test.Api { // TODO uncomment below to test the method and replace null with proper value //var response = instance.FooGet(); - //Assert.IsType(response); + //Assert.IsType(response); } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs index c1ed54241c..6738676414 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/PetApiTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -62,8 +62,7 @@ namespace Org.OpenAPITools.Test.Api { // TODO uncomment below to test the method and replace null with proper value //Pet pet = null; - //var response = instance.AddPet(pet); - //Assert.IsType(response); + //instance.AddPet(pet); } /// @@ -122,8 +121,7 @@ namespace Org.OpenAPITools.Test.Api { // TODO uncomment below to test the method and replace null with proper value //Pet pet = null; - //var response = instance.UpdatePet(pet); - //Assert.IsType(response); + //instance.UpdatePet(pet); } /// @@ -152,5 +150,19 @@ namespace Org.OpenAPITools.Test.Api //var response = instance.UploadFile(petId, additionalMetadata, file); //Assert.IsType(response); } + + /// + /// Test UploadFileWithRequiredFile + /// + [Fact] + public void UploadFileWithRequiredFileTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //System.IO.Stream requiredFile = null; + //string additionalMetadata = null; + //var response = instance.UploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + //Assert.IsType(response); + } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs index 6c99ad9513..48e9f32748 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs index 3f38396769..792db5819a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Api/UserApiTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index 291231a91b..ced34a4faa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a Dog from type Animal - /// - [Fact] - public void DogDeserializeFromAnimalTest() - { - // TODO uncomment below to test deserialize a Dog from type Animal - //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); - } /// /// Test deserialize a Cat from type Animal /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a Cat from type Animal //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } /// /// Test the property 'ClassName' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs index 54c455c8af..2a2e098e60 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs index 973015d694..6ce48e601e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/CategoryTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index e2d84645c6..4f81b845d4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -81,6 +81,14 @@ namespace Org.OpenAPITools.Test.Model // TODO unit test for the property 'EnumInteger' } /// + /// Test the property 'EnumIntegerOnly' + /// + [Fact] + public void EnumIntegerOnlyTest() + { + // TODO unit test for the property 'EnumIntegerOnly' + } + /// /// Test the property 'EnumNumber' /// [Fact] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index 75f4fd8b0e..faa4930944 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -55,15 +55,6 @@ namespace Org.OpenAPITools.Test.Model //Assert.IsType(instance); } - /// - /// Test deserialize a ParentPet from type GrandparentAnimal - /// - [Fact] - public void ParentPetDeserializeFromGrandparentAnimalTest() - { - // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal - //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); - } /// /// Test deserialize a ChildCat from type ParentPet /// @@ -73,6 +64,15 @@ namespace Org.OpenAPITools.Test.Model // TODO uncomment below to test deserialize a ChildCat from type ParentPet //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } /// /// Test the property 'PetType' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs deleted file mode 100644 index 7731f80c16..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test.Model -{ - /// - /// Class for testing InlineResponseDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineResponseDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineResponseDefault - //private InlineResponseDefault instance; - - public InlineResponseDefaultTests() - { - // TODO uncomment below to create an instance of InlineResponseDefault - //instance = new InlineResponseDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineResponseDefault - /// - [Fact] - public void InlineResponseDefaultInstanceTest() - { - // TODO uncomment below to test "IsType" InlineResponseDefault - //Assert.IsType(instance); - } - - - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs index 8a544e417f..24a9e26315 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -57,12 +57,12 @@ namespace Org.OpenAPITools.Test.Model /// - /// Test the property '__Client' + /// Test the property '_Client' /// [Fact] - public void __ClientTest() + public void _ClientTest() { - // TODO unit test for the property '__Client' + // TODO unit test for the property '_Client' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs index 0cc1e616df..cf5c561c54 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/PetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/PetTests.cs index a296ab12b4..154e66f8df 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs index 57c3f6f9e4..0f0e1ff12a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs @@ -64,6 +64,14 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'SpecialPropertyName' } + /// + /// Test the property '_SpecialModelName' + /// + [Fact] + public void _SpecialModelNameTest() + { + // TODO unit test for the property '_SpecialModelName' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/TagTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/TagTests.cs index d3b4766b10..6d56232d0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/TagTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/TagTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/UserTests.cs index b7019235bf..a7b095e4c2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -1,7 +1,7 @@ /* * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git @@ -120,6 +120,38 @@ namespace Org.OpenAPITools.Test.Model { // TODO unit test for the property 'UserStatus' } + /// + /// Test the property 'ObjectWithNoDeclaredProps' + /// + [Fact] + public void ObjectWithNoDeclaredPropsTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredProps' + } + /// + /// Test the property 'ObjectWithNoDeclaredPropsNullable' + /// + [Fact] + public void ObjectWithNoDeclaredPropsNullableTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + } + /// + /// Test the property 'AnyTypeProp' + /// + [Fact] + public void AnyTypePropTest() + { + // TODO unit test for the property 'AnyTypeProp' + } + /// + /// Test the property 'AnyTypePropNullable' + /// + [Fact] + public void AnyTypePropNullableTest() + { + // TODO unit test for the property 'AnyTypePropNullable' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index e04c8df5fd..95d41fcbd9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs index ff7ce75367..bc5b5556d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs index 421f93ed04..5991b7f0b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 6b66577525..dd74c66d15 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs index 125b0f5cb7..e8439eb125 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api @@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs index 63403e7dcd..e01ed16258 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs index c37a6501c6..8efb827cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs index 70ac64f89a..660dcd3a05 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs @@ -25,18 +25,18 @@ using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; -using RestSharp.Deserializers; +using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { /// /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// - internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; @@ -82,7 +82,9 @@ namespace Org.OpenAPITools.Client } } - public T Deserialize(IRestResponse response) + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; @@ -94,7 +96,7 @@ namespace Org.OpenAPITools.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(IRestResponse response, Type type) + internal object Deserialize(RestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { @@ -147,15 +149,22 @@ namespace Org.OpenAPITools.Client } } - public string RootElement { get; set; } - public string Namespace { get; set; } - public string DateFormat { get; set; } + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } + + public DataFormat DataFormat => DataFormat.Json; } /// /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), @@ -186,14 +195,14 @@ namespace Org.OpenAPITools.Client /// Allows for extending request processing for generated code. /// /// The RestSharp request object - partial void InterceptRequest(IRestRequest request); + partial void InterceptRequest(RestRequest request); /// /// Allows for extending response processing for generated code. /// /// The RestSharp request object /// The RestSharp response object - partial void InterceptResponse(IRestRequest request, IRestResponse response); + partial void InterceptResponse(RestRequest request, RestResponse response); /// /// Initializes a new instance of the , defaulting to the global configurations' base url. @@ -228,25 +237,25 @@ namespace Org.OpenAPITools.Client switch (method) { case HttpMethod.Get: - other = RestSharpMethod.GET; + other = RestSharpMethod.Get; break; case HttpMethod.Post: - other = RestSharpMethod.POST; + other = RestSharpMethod.Post; break; case HttpMethod.Put: - other = RestSharpMethod.PUT; + other = RestSharpMethod.Put; break; case HttpMethod.Delete: - other = RestSharpMethod.DELETE; + other = RestSharpMethod.Delete; break; case HttpMethod.Head: - other = RestSharpMethod.HEAD; + other = RestSharpMethod.Head; break; case HttpMethod.Options: - other = RestSharpMethod.OPTIONS; + other = RestSharpMethod.Options; break; case HttpMethod.Patch: - other = RestSharpMethod.PATCH; + other = RestSharpMethod.Patch; break; default: throw new ArgumentOutOfRangeException("method", method, null); @@ -277,11 +286,7 @@ namespace Org.OpenAPITools.Client if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); - RestRequest request = new RestRequest(Method(method)) - { - Resource = path, - JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) - }; + RestRequest request = new RestRequest(path, Method(method)); if (options.PathParameters != null) { @@ -376,25 +381,17 @@ namespace Org.OpenAPITools.Client var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); else - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } } } - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - request.AddCookie(cookie.Name, cookie.Value); - } - } - return request; } - private ApiResponse ToApiResponse(IRestResponse response) + private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; string rawContent = response.Content; @@ -413,9 +410,17 @@ namespace Org.OpenAPITools.Client } } + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + if (response.Cookies != null) { - foreach (var responseCookies in response.Cookies) + foreach (var responseCookies in response.Cookies.Cast()) { transformed.Cookies.Add( new Cookie( @@ -433,54 +438,46 @@ namespace Org.OpenAPITools.Client private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else - { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } } - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.Proxy = configuration.Proxy; - } + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); - if (configuration.ClientCertificates != null) + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; @@ -516,6 +513,10 @@ namespace Org.OpenAPITools.Client { response.Data = (T)(object)response.RawBytes; } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } InterceptResponse(req, response); @@ -528,7 +529,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, @@ -557,54 +558,35 @@ namespace Org.OpenAPITools.Client private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); - } - - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) - { - client.Proxy = configuration.Proxy; - } - - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; @@ -645,7 +627,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs new file mode 100644 index 0000000000..8b0ba33499 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs @@ -0,0 +1,95 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : AuthenticatorBase + { + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) : base("") + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// Access token to create a parameter from. + /// An authentication parameter. + protected override async ValueTask GetAuthenticationParameter(string accessToken) + { + var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl) + .UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration)); + + var request = new RestRequest() + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + var response = await client.PostAsync(request); + return $"{response.TokenType} {response.AccessToken}"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs new file mode 100644 index 0000000000..e225740925 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs @@ -0,0 +1,27 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs new file mode 100644 index 0000000000..0a94e17e12 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Client.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs index dcc97c295e..e499a7728e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -120,6 +120,16 @@ namespace Org.OpenAPITools.Client return Convert.ToString(obj, CultureInfo.InvariantCulture); } + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + /// /// Encode string in base64 format. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Configuration.cs index 56e3a9d13e..526781f42c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Configuration.cs @@ -17,6 +17,8 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Net.Http; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -118,7 +120,7 @@ namespace Org.OpenAPITools.Client public Configuration() { Proxy = null; - UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); BasePath = "http://petstore.swagger.io:80/v2"; DefaultHeaders = new ConcurrentDictionary(); ApiKey = new ConcurrentDictionary(); @@ -366,6 +368,30 @@ namespace Org.OpenAPITools.Client /// The access token. public virtual string AccessToken { get; set; } + /// + /// Gets or sets the token URL for OAuth2 authentication. + /// + /// The OAuth Token URL. + public virtual string OAuthTokenUrl { get; set; } + + /// + /// Gets or sets the client ID for OAuth2 authentication. + /// + /// The OAuth Client ID. + public virtual string OAuthClientId { get; set; } + + /// + /// Gets or sets the client secret for OAuth2 authentication. + /// + /// The OAuth Client Secret. + public virtual string OAuthClientSecret { get; set; } + + /// + /// Gets or sets the flow for OAuth2 authentication. + /// + /// The OAuth Flow. + public virtual OAuthFlow? OAuthFlow { get; set; } + /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// @@ -689,6 +715,10 @@ namespace Org.OpenAPITools.Client Username = second.Username ?? first.Username, Password = second.Password ?? first.Password, AccessToken = second.AccessToken ?? first.AccessToken, + OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl, + OAuthClientId = second.OAuthClientId ?? first.OAuthClientId, + OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret, + OAuthFlow = second.OAuthFlow ?? first.OAuthFlow, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 6a8f9c8dc0..0b3e867d0f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -325,14 +325,18 @@ namespace Org.OpenAPITools.Client /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { - if (!File.Exists(KeyFilePath)) + string keyStr = string.Empty; + if (File.Exists(KeyFilePath)) { - throw new Exception("key file path does not exist."); + keyStr = File.ReadAllText(KeyFilePath); + } + else + { + keyStr = KeyFilePath; } const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; - var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); var ecdsa = ECDsa.Create(); @@ -430,11 +434,15 @@ namespace Org.OpenAPITools.Client bool isPrivateKeyFile = true; byte[] pemkey = null; - if (!File.Exists(pemfile)) + string pemstr = string.Empty; + if (File.Exists(pemfile)) { - throw new Exception("private key file does not exist."); + pemstr = File.ReadAllText(pemfile).Trim(); + } + else + { + pemstr = pemfile; } - string pemstr = File.ReadAllText(pemfile).Trim(); if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) { @@ -725,9 +733,16 @@ namespace Org.OpenAPITools.Client /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { - if (!File.Exists(keyFilePath)) + string[] key = null; + + if (File.Exists(keyFilePath)) { - throw new Exception("Key file path does not exist."); + key = File.ReadAllLines(keyFilePath); + } + else + { + // The ApiKeyFilePath is passed as string + key = new string[] { keyFilePath }; } const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; @@ -737,7 +752,6 @@ namespace Org.OpenAPITools.Client //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; PrivateKeyType keyType; - var key = File.ReadAllLines(keyFilePath); if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) @@ -751,7 +765,7 @@ namespace Org.OpenAPITools.Client } else { - throw new Exception("Either the key is invalid or key is not supported"); + throw new Exception("The key file path does not exist or key is invalid or key is not supported"); } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IReadableConfiguration.cs index b99a151e5b..c9615dc5aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IReadableConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; using System.Net; using System.Security.Cryptography.X509Certificates; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client /// Access token. string AccessToken { get; } + /// + /// Gets the OAuth token URL. + /// + /// OAuth Token URL. + string OAuthTokenUrl { get; } + + /// + /// Gets the OAuth client ID. + /// + /// OAuth Client ID. + string OAuthClientId { get; } + + /// + /// Gets the OAuth client secret. + /// + /// OAuth Client Secret. + string OAuthClientSecret { get; } + + /// + /// Gets the OAuth flow. + /// + /// OAuth Flow. + OAuthFlow? OAuthFlow { get; } + /// /// Gets the API key. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RequestOptions.cs index 3932047e02..4c26cf69b2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client /// public Object Data { get; set; } + /// + /// If request should be authenticated with OAuth. + /// + public bool OAuth { get; set; } + /// /// Constructs a new instance of /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RetryConfiguration.cs index 91bc7cc6d5..7011f69e77 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RetryConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client /// /// Retry policy /// - public static Policy RetryPolicy { get; set; } + public static Policy RetryPolicy { get; set; } /// /// Async retry policy /// - public static AsyncPolicy AsyncRetryPolicy { get; set; } + public static AsyncPolicy AsyncRetryPolicy { get; set; } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Animal.cs index f5150493c8..83397018b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Animal.cs @@ -65,7 +65,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AppleReq.cs index 2c77cf1c41..9e09e2da8c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AppleReq.cs @@ -56,7 +56,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Cultivar /// - [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = true)] public string Cultivar { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BananaReq.cs index fdd36929d1..3edb9a1b6d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BananaReq.cs @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets LengthCm /// - [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = true)] public decimal LengthCm { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BasquePig.cs index e0c780a14b..f65f049cfd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BasquePig.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Cat.cs index 2bc55707da..86ceaeed1a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Cat.cs @@ -145,7 +145,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Category.cs index 35732f998d..94dea2b30b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Category.cs @@ -66,7 +66,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs index 4c60ed776c..2aa81264fa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs @@ -57,14 +57,6 @@ namespace Org.OpenAPITools.Model /// /// Initializes a new instance of the class. /// - [JsonConstructorAttribute] - protected ChildCat() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// /// name. /// petType (default to PetTypeEnum.ChildCat). public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() @@ -170,7 +162,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index dc78561c0d..353ea1d081 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DanishPig.cs index 38628258d1..d86ff21df9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DanishPig.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Dog.cs index 9cd520deaf..786270d1c4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Dog.cs @@ -148,7 +148,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumArrays.cs index 6d7830c0e8..69568d6c87 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -78,13 +78,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets ArrayEnum - /// - [DataMember(Name = "array_enum", EmitDefaultValue = false)] - public List ArrayEnum { get; set; } /// /// Initializes a new instance of the class. /// @@ -97,6 +90,12 @@ namespace Org.OpenAPITools.Model this.AdditionalProperties = new Dictionary(); } + /// + /// Gets or Sets ArrayEnum + /// + [DataMember(Name = "array_enum", EmitDefaultValue = false)] + public List ArrayEnum { get; set; } + /// /// Gets or Sets additional properties /// @@ -157,7 +156,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumTest.cs index 6f3d2272c5..7386cffd37 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumTest.cs @@ -94,7 +94,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets EnumStringRequired /// - [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = true)] public EnumStringRequiredEnum EnumStringRequired { get; set; } /// /// Defines EnumInteger diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 6565b7b6f3..773eba5b0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs index 4ae624cb61..9d0979b6f7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs @@ -111,7 +111,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Number /// - [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = true)] public decimal Number { get; set; } /// @@ -141,7 +141,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Byte /// - [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = true)] public byte[] Byte { get; set; } /// @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Date /// - [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] [JsonConverter(typeof(OpenAPIDateConverter))] public DateTime Date { get; set; } @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Password /// - [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = true)] public string Password { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index eddfcf6011..28e7729a17 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] public string PetType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs deleted file mode 100644 index ae46f1f009..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineResponseDefault - /// - [DataContract(Name = "inline_response_default")] - public partial class InlineResponseDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// _string. - public InlineResponseDefault(Foo _string = default(Foo)) - { - this.String = _string; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Gets or Sets String - /// - [DataMember(Name = "string", EmitDefaultValue = false)] - public Foo String { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineResponseDefault {\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineResponseDefault).AreEqual; - } - - /// - /// Returns true if InlineResponseDefault instances are equal - /// - /// Instance of InlineResponseDefault to be compared - /// Boolean - public bool Equals(InlineResponseDefault input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 55c607598a..ea18925f87 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -61,13 +61,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MapTest.cs index 8b5a73e773..b2aeedc33c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MapTest.cs @@ -52,13 +52,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets MapOfEnumString - /// - [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] - public Dictionary MapOfEnumString { get; set; } /// /// Initializes a new instance of the class. /// @@ -81,6 +74,12 @@ namespace Org.OpenAPITools.Model [DataMember(Name = "map_map_of_string", EmitDefaultValue = false)] public Dictionary> MapMapOfString { get; set; } + /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] + public Dictionary MapOfEnumString { get; set; } + /// /// Gets or Sets DirectMap /// @@ -158,7 +157,10 @@ namespace Org.OpenAPITools.Model { hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); } - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } if (this.DirectMap != null) { hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs index 0dc21bb656..1d4e760506 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs @@ -55,7 +55,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets _Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public int _Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ParentPet.cs index ac986b555e..49bed67986 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ParentPet.cs @@ -135,7 +135,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pet.cs index 4723827264..0e6f950d7f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pet.cs @@ -119,13 +119,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// /// Gets or Sets PhotoUrls /// - [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = true)] public List PhotoUrls { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index cb2a5dc169..d5be5ea3c9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index e54c584688..236020031e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeInterface.cs index 6225f8888a..c9294b0b4e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index b8fbc0c240..59397bf30f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TriangleInterface.cs index 17571e4514..cdf2bd1f0f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Whale.cs index 10ceda658b..62ae66415f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Whale.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs index aab75e9cd5..8a3c713fe6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs @@ -92,7 +92,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index f5c7bfda9a..eb0213a59a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,11 +21,17 @@ - + - + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/FILES index 274c950fa8..ba71e29dcc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/FILES @@ -97,6 +97,9 @@ src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs +src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs +src/Org.OpenAPITools/Client/Auth/TokenResponse.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesAnyType.md deleted file mode 100644 index 2513b741ba..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesAnyType.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesAnyType -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesArray.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesArray.md deleted file mode 100644 index 39a7c940c2..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesArray.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesArray -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesBoolean.md deleted file mode 100644 index e3b30ac619..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesBoolean.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesBoolean -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesInteger.md deleted file mode 100644 index e40cc1e54e..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesInteger.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesInteger -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesNumber.md deleted file mode 100644 index 91764084c8..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesNumber.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesNumber -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesObject.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesObject.md deleted file mode 100644 index 2fa66f43d6..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesObject.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesObject -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesString.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesString.md deleted file mode 100644 index 008d3d4f33..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AdditionalPropertiesString.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesString -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AnimalFarm.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AnimalFarm.md deleted file mode 100644 index 69c5172580..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/AnimalFarm.md +++ /dev/null @@ -1,8 +0,0 @@ -# Org.OpenAPITools.Model.AnimalFarm -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/BigCat.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/BigCat.md deleted file mode 100644 index 41c336e4ca..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/BigCat.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.BigCat -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Declawed** | **bool** | | [optional] -**Kind** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/BigCatAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/BigCatAllOf.md deleted file mode 100644 index 88a739b7e4..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/BigCatAllOf.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.BigCatAllOf -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Kind** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/EnumArrays.md index 8881585a4c..62e34f03db 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/EnumArrays.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject.md deleted file mode 100644 index 40e16da1bb..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | Updated name of the pet | [optional] -**Status** | **string** | Updated status of the pet | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject1.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject1.md deleted file mode 100644 index 2e6d226754..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject1.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject1 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**AdditionalMetadata** | **string** | Additional data to pass to server | [optional] -**File** | **System.IO.Stream** | file to upload | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject2.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject2.md deleted file mode 100644 index c02c78f9b2..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject2.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject2 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**EnumFormStringArray** | **List<string>** | Form parameter enum test (string array) | [optional] -**EnumFormString** | **string** | Form parameter enum test (string) | [optional] [default to EnumFormStringEnum.Efg] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject3.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject3.md deleted file mode 100644 index 38b5bf8a5c..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject3.md +++ /dev/null @@ -1,22 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject3 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Integer** | **int** | None | [optional] -**Int32** | **int** | None | [optional] -**Int64** | **long** | None | [optional] -**Number** | **decimal** | None | -**Float** | **float** | None | [optional] -**Double** | **double** | None | -**String** | **string** | None | [optional] -**PatternWithoutDelimiter** | **string** | None | -**Byte** | **byte[]** | None | -**Binary** | **System.IO.Stream** | None | [optional] -**Date** | **DateTime** | None | [optional] -**DateTime** | **DateTime** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] -**Password** | **string** | None | [optional] -**Callback** | **string** | None | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject4.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject4.md deleted file mode 100644 index c8e00663ee..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject4.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject4 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Param** | **string** | field1 | -**Param2** | **string** | field2 | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject5.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject5.md deleted file mode 100644 index a28ff47f2e..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineObject5.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject5 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**AdditionalMetadata** | **string** | Additional data to pass to server | [optional] -**RequiredFile** | **System.IO.Stream** | file to upload | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineResponseDefault.md deleted file mode 100644 index e3d55e133f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/InlineResponseDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/MapTest.md index dc1ebba4e7..516f9d4fd3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/MapTest.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/StringBooleanMap.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/StringBooleanMap.md deleted file mode 100644 index 6e7a71368d..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/StringBooleanMap.md +++ /dev/null @@ -1,8 +0,0 @@ -# Org.OpenAPITools.Model.StringBooleanMap -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/TypeHolderDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/TypeHolderDefault.md deleted file mode 100644 index ccf43c723e..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/TypeHolderDefault.md +++ /dev/null @@ -1,13 +0,0 @@ -# Org.OpenAPITools.Model.TypeHolderDefault -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**StringItem** | **string** | | [default to "what"] -**NumberItem** | **decimal** | | -**IntegerItem** | **int** | | -**BoolItem** | **bool** | | [default to true] -**ArrayItem** | **List<int>** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/TypeHolderExample.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/TypeHolderExample.md deleted file mode 100644 index f78185c2aa..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/TypeHolderExample.md +++ /dev/null @@ -1,14 +0,0 @@ -# Org.OpenAPITools.Model.TypeHolderExample -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**StringItem** | **string** | | -**NumberItem** | **decimal** | | -**FloatItem** | **float** | | -**IntegerItem** | **int** | | -**BoolItem** | **bool** | | -**ArrayItem** | **List<int>** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/XmlItem.md b/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/XmlItem.md deleted file mode 100644 index 679fd2c3d1..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/docs/XmlItem.md +++ /dev/null @@ -1,37 +0,0 @@ -# Org.OpenAPITools.Model.XmlItem -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**AttributeString** | **string** | | [optional] -**AttributeNumber** | **decimal** | | [optional] -**AttributeInteger** | **int** | | [optional] -**AttributeBoolean** | **bool** | | [optional] -**WrappedArray** | **List<int>** | | [optional] -**NameString** | **string** | | [optional] -**NameNumber** | **decimal** | | [optional] -**NameInteger** | **int** | | [optional] -**NameBoolean** | **bool** | | [optional] -**NameArray** | **List<int>** | | [optional] -**NameWrappedArray** | **List<int>** | | [optional] -**PrefixString** | **string** | | [optional] -**PrefixNumber** | **decimal** | | [optional] -**PrefixInteger** | **int** | | [optional] -**PrefixBoolean** | **bool** | | [optional] -**PrefixArray** | **List<int>** | | [optional] -**PrefixWrappedArray** | **List<int>** | | [optional] -**NamespaceString** | **string** | | [optional] -**NamespaceNumber** | **decimal** | | [optional] -**NamespaceInteger** | **int** | | [optional] -**NamespaceBoolean** | **bool** | | [optional] -**NamespaceArray** | **List<int>** | | [optional] -**NamespaceWrappedArray** | **List<int>** | | [optional] -**PrefixNsString** | **string** | | [optional] -**PrefixNsNumber** | **decimal** | | [optional] -**PrefixNsInteger** | **int** | | [optional] -**PrefixNsBoolean** | **bool** | | [optional] -**PrefixNsArray** | **List<int>** | | [optional] -**PrefixNsWrappedArray** | **List<int>** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs index 7ca3b32bef..1d46982928 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing AnotherFakeApi @@ -30,26 +30,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the API endpoint. /// - public class AnotherFakeApiTests + public class AnotherFakeApiTests : IDisposable { private AnotherFakeApi instance; public AnotherFakeApiTests() - { + { instance = new AnotherFakeApi(); } + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of AnotherFakeApi /// [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' AnotherFakeApi - //Assert.IsType(typeof(AnotherFakeApi), instance, "instance is a AnotherFakeApi"); + // TODO uncomment below to test 'IsType' AnotherFakeApi + //Assert.IsType(instance); } - /// /// Test Call123TestSpecialTags /// @@ -59,9 +63,7 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //ModelClient modelClient = null; //var response = instance.Call123TestSpecialTags(modelClient); - //Assert.IsType (response, "response is ModelClient"); + //Assert.IsType(response); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 76bc5dfdd6..5d048a005b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing DefaultApi @@ -50,11 +50,10 @@ namespace Org.OpenAPITools.Test [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' DefaultApi - //Assert.IsType(typeof(DefaultApi), instance, "instance is a DefaultApi"); + // TODO uncomment below to test 'IsType' DefaultApi + //Assert.IsType(instance); } - /// /// Test FooGet /// @@ -63,9 +62,7 @@ namespace Org.OpenAPITools.Test { // TODO uncomment below to test the method and replace null with proper value //var response = instance.FooGet(); - //Assert.IsType (response, "response is InlineResponseDefault"); + //Assert.IsType(response); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs index 738f109a20..994cd46d38 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing FakeApi @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the API endpoint. /// - public class FakeApiTests + public class FakeApiTests : IDisposable { private FakeApi instance; @@ -39,17 +39,32 @@ namespace Org.OpenAPITools.Test instance = new FakeApi(); } + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of FakeApi /// [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' FakeApi - //Assert.IsType(typeof(FakeApi), instance, "instance is a FakeApi"); + // TODO uncomment below to test 'IsType' FakeApi + //Assert.IsType(instance); + } + + /// + /// Test FakeHealthGet + /// + [Fact] + public void FakeHealthGetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.FakeHealthGet(); + //Assert.IsType(response); } - /// /// Test FakeOuterBooleanSerialize /// @@ -59,9 +74,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //bool? body = null; //var response = instance.FakeOuterBooleanSerialize(body); - //Assert.IsType (response, "response is bool?"); + //Assert.IsType(response); } - + /// /// Test FakeOuterCompositeSerialize /// @@ -71,9 +86,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //OuterComposite outerComposite = null; //var response = instance.FakeOuterCompositeSerialize(outerComposite); - //Assert.IsType (response, "response is OuterComposite"); + //Assert.IsType(response); } - + /// /// Test FakeOuterNumberSerialize /// @@ -83,9 +98,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //decimal? body = null; //var response = instance.FakeOuterNumberSerialize(body); - //Assert.IsType (response, "response is decimal?"); + //Assert.IsType(response); } - + /// /// Test FakeOuterStringSerialize /// @@ -95,9 +110,20 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //string body = null; //var response = instance.FakeOuterStringSerialize(body); - //Assert.IsType (response, "response is string"); + //Assert.IsType(response); } - + + /// + /// Test GetArrayOfEnums + /// + [Fact] + public void GetArrayOfEnumsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.GetArrayOfEnums(); + //Assert.IsType>(response); + } + /// /// Test TestBodyWithFileSchema /// @@ -107,9 +133,8 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //FileSchemaTestClass fileSchemaTestClass = null; //instance.TestBodyWithFileSchema(fileSchemaTestClass); - } - + /// /// Test TestBodyWithQueryParams /// @@ -120,9 +145,8 @@ namespace Org.OpenAPITools.Test //string query = null; //User user = null; //instance.TestBodyWithQueryParams(query, user); - } - + /// /// Test TestClientModel /// @@ -132,9 +156,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //ModelClient modelClient = null; //var response = instance.TestClientModel(modelClient); - //Assert.IsType (response, "response is ModelClient"); + //Assert.IsType(response); } - + /// /// Test TestEndpointParameters /// @@ -142,8 +166,8 @@ namespace Org.OpenAPITools.Test public void TestEndpointParametersTest() { // TODO uncomment below to test the method and replace null with proper value - //decimal? number = null; - //double? _double = null; + //decimal number = null; + //double _double = null; //string patternWithoutDelimiter = null; //byte[] _byte = null; //int? integer = null; @@ -157,9 +181,8 @@ namespace Org.OpenAPITools.Test //string password = null; //string callback = null; //instance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); - } - + /// /// Test TestEnumParameters /// @@ -176,9 +199,24 @@ namespace Org.OpenAPITools.Test //List enumFormStringArray = null; //string enumFormString = null; //instance.TestEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); - } - + + /// + /// Test TestGroupParameters + /// + [Fact] + public void TestGroupParametersTest() + { + // TODO uncomment below to test the method and replace null with proper value + //int requiredStringGroup = null; + //bool requiredBooleanGroup = null; + //long requiredInt64Group = null; + //int? stringGroup = null; + //bool? booleanGroup = null; + //long? int64Group = null; + //instance.TestGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + /// /// Test TestInlineAdditionalProperties /// @@ -188,9 +226,8 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //Dictionary requestBody = null; //instance.TestInlineAdditionalProperties(requestBody); - } - + /// /// Test TestJsonFormData /// @@ -201,9 +238,21 @@ namespace Org.OpenAPITools.Test //string param = null; //string param2 = null; //instance.TestJsonFormData(param, param2); - } - - } + /// + /// Test TestQueryParameterCollectionFormat + /// + [Fact] + public void TestQueryParameterCollectionFormatTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List pipe = null; + //List ioutil = null; + //List http = null; + //List url = null; + //List context = null; + //instance.TestQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs index e1272d442a..bbfd4a586e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing FakeClassnameTags123Api @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the API endpoint. /// - public class FakeClassnameTags123ApiTests + public class FakeClassnameTags123ApiTests : IDisposable { private FakeClassnameTags123Api instance; @@ -39,17 +39,21 @@ namespace Org.OpenAPITools.Test instance = new FakeClassnameTags123Api(); } + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of FakeClassnameTags123Api /// [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' FakeClassnameTags123Api - //Assert.IsType(typeof(FakeClassnameTags123Api), instance, "instance is a FakeClassnameTags123Api"); + // TODO uncomment below to test 'IsType' FakeClassnameTags123Api + //Assert.IsType(instance); } - /// /// Test TestClassname /// @@ -59,9 +63,7 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //ModelClient modelClient = null; //var response = instance.TestClassname(modelClient); - //Assert.IsType (response, "response is ModelClient"); + //Assert.IsType(response); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs index e748042141..48e9f32748 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing StoreApi @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the API endpoint. /// - public class StoreApiTests + public class StoreApiTests : IDisposable { private StoreApi instance; @@ -39,17 +39,21 @@ namespace Org.OpenAPITools.Test instance = new StoreApi(); } + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of StoreApi /// [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' StoreApi - //Assert.IsType(typeof(StoreApi), instance, "instance is a StoreApi"); + // TODO uncomment below to test 'IsType' StoreApi + //Assert.IsType(instance); } - /// /// Test DeleteOrder /// @@ -59,9 +63,8 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //string orderId = null; //instance.DeleteOrder(orderId); - } - + /// /// Test GetInventory /// @@ -70,9 +73,9 @@ namespace Org.OpenAPITools.Test { // TODO uncomment below to test the method and replace null with proper value //var response = instance.GetInventory(); - //Assert.IsType> (response, "response is Dictionary"); + //Assert.IsType>(response); } - + /// /// Test GetOrderById /// @@ -80,11 +83,11 @@ namespace Org.OpenAPITools.Test public void GetOrderByIdTest() { // TODO uncomment below to test the method and replace null with proper value - //long? orderId = null; + //long orderId = null; //var response = instance.GetOrderById(orderId); - //Assert.IsType (response, "response is Order"); + //Assert.IsType(response); } - + /// /// Test PlaceOrder /// @@ -94,9 +97,7 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //Order order = null; //var response = instance.PlaceOrder(order); - //Assert.IsType (response, "response is Order"); + //Assert.IsType(response); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/UserApiTests.cs index b6ef54ae34..792db5819a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/UserApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Api/UserApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing UserApi @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the API endpoint. /// - public class UserApiTests + public class UserApiTests : IDisposable { private UserApi instance; @@ -39,17 +39,21 @@ namespace Org.OpenAPITools.Test instance = new UserApi(); } + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of UserApi /// [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' UserApi - //Assert.IsType(typeof(UserApi), instance, "instance is a UserApi"); + // TODO uncomment below to test 'IsType' UserApi + //Assert.IsType(instance); } - /// /// Test CreateUser /// @@ -59,9 +63,8 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //User user = null; //instance.CreateUser(user); - } - + /// /// Test CreateUsersWithArrayInput /// @@ -71,9 +74,8 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //List user = null; //instance.CreateUsersWithArrayInput(user); - } - + /// /// Test CreateUsersWithListInput /// @@ -83,9 +85,8 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //List user = null; //instance.CreateUsersWithListInput(user); - } - + /// /// Test DeleteUser /// @@ -95,9 +96,8 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //string username = null; //instance.DeleteUser(username); - } - + /// /// Test GetUserByName /// @@ -107,9 +107,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //string username = null; //var response = instance.GetUserByName(username); - //Assert.IsType (response, "response is User"); + //Assert.IsType(response); } - + /// /// Test LoginUser /// @@ -120,9 +120,9 @@ namespace Org.OpenAPITools.Test //string username = null; //string password = null; //var response = instance.LoginUser(username, password); - //Assert.IsType (response, "response is string"); + //Assert.IsType(response); } - + /// /// Test LogoutUser /// @@ -131,9 +131,8 @@ namespace Org.OpenAPITools.Test { // TODO uncomment below to test the method and replace null with proper value //instance.LogoutUser(); - } - + /// /// Test UpdateUser /// @@ -144,9 +143,6 @@ namespace Org.OpenAPITools.Test //string username = null; //User user = null; //instance.UpdateUser(username, user); - } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/ApiClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/ApiClientTests.cs index 9a001a63e0..4104b13149 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/ApiClientTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/ApiClientTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/ConfigurationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/ConfigurationTests.cs index c3d8c9deae..5dde15c5b6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/ConfigurationTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/ConfigurationTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/JSONComposedSchemaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/JSONComposedSchemaTests.cs index e9478032ec..5972909190 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/JSONComposedSchemaTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/JSONComposedSchemaTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -181,7 +181,7 @@ namespace Org.OpenAPITools.Test EnumTest enumTest = new EnumTest(); enumTest.EnumIntegerOnly = EnumTest.EnumIntegerOnlyEnum.NUMBER_2; enumTest.EnumInteger = EnumTest.EnumIntegerEnum.NUMBER_MINUS_1; - Assert.Equal("{\"enum_integer\":-1,\"enum_integer_only\":2,\"outerEnum\":null}", JsonConvert.SerializeObject(enumTest)); + Assert.Equal("{\"enum_string_required\":0,\"enum_integer\":-1,\"enum_integer_only\":2,\"outerEnum\":null}", JsonConvert.SerializeObject(enumTest)); } } -} +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesAnyTypeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesAnyTypeTests.cs deleted file mode 100644 index 81101896de..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesAnyTypeTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesAnyType - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesAnyTypeTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesAnyType - //private AdditionalPropertiesAnyType instance; - - public AdditionalPropertiesAnyTypeTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesAnyType - //instance = new AdditionalPropertiesAnyType(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesAnyType - /// - [Fact] - public void AdditionalPropertiesAnyTypeInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesAnyType - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesAnyType"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesArrayTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesArrayTests.cs deleted file mode 100644 index 56f5e3fcec..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesArrayTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesArray - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesArrayTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesArray - //private AdditionalPropertiesArray instance; - - public AdditionalPropertiesArrayTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesArray - //instance = new AdditionalPropertiesArray(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesArray - /// - [Fact] - public void AdditionalPropertiesArrayInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesArray - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesArray"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesBooleanTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesBooleanTests.cs deleted file mode 100644 index 04eb195d46..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesBooleanTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesBoolean - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesBooleanTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesBoolean - //private AdditionalPropertiesBoolean instance; - - public AdditionalPropertiesBooleanTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesBoolean - //instance = new AdditionalPropertiesBoolean(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesBoolean - /// - [Fact] - public void AdditionalPropertiesBooleanInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesBoolean - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesBoolean"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs index 9db802aa09..9ab029ed09 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing AdditionalPropertiesClass @@ -30,19 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class AdditionalPropertiesClassTests + public class AdditionalPropertiesClassTests : IDisposable { // TODO uncomment below to declare an instance variable for AdditionalPropertiesClass //private AdditionalPropertiesClass instance; + public AdditionalPropertiesClassTests() + { + // TODO uncomment below to create an instance of AdditionalPropertiesClass + //instance = new AdditionalPropertiesClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of AdditionalPropertiesClass /// [Fact] public void AdditionalPropertiesClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesClass - //Assert.IsType (instance, "variable 'instance' is a AdditionalPropertiesClass"); + // TODO uncomment below to test "IsType" AdditionalPropertiesClass + //Assert.IsType(instance); } @@ -62,6 +72,54 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'MapOfMapProperty' } + /// + /// Test the property 'Anytype1' + /// + [Fact] + public void Anytype1Test() + { + // TODO unit test for the property 'Anytype1' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype1' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype1Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype1' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype2' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype2Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype2' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype3' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype3Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3' + } + /// + /// Test the property 'EmptyMap' + /// + [Fact] + public void EmptyMapTest() + { + // TODO unit test for the property 'EmptyMap' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesString' + /// + [Fact] + public void MapWithUndeclaredPropertiesStringTest() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesString' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesIntegerTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesIntegerTests.cs deleted file mode 100644 index 529caa6c71..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesIntegerTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesInteger - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesIntegerTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesInteger - //private AdditionalPropertiesInteger instance; - - public AdditionalPropertiesIntegerTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesInteger - //instance = new AdditionalPropertiesInteger(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesInteger - /// - [Fact] - public void AdditionalPropertiesIntegerInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesInteger - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesInteger"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesNumberTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesNumberTests.cs deleted file mode 100644 index 43c877754b..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesNumberTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesNumber - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesNumberTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesNumber - //private AdditionalPropertiesNumber instance; - - public AdditionalPropertiesNumberTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesNumber - //instance = new AdditionalPropertiesNumber(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesNumber - /// - [Fact] - public void AdditionalPropertiesNumberInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesNumber - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesNumber"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesObjectTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesObjectTests.cs deleted file mode 100644 index bd441e0665..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesObjectTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesObject - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesObjectTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesObject - //private AdditionalPropertiesObject instance; - - public AdditionalPropertiesObjectTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesObject - //instance = new AdditionalPropertiesObject(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesObject - /// - [Fact] - public void AdditionalPropertiesObjectInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesObject - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesObject"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesStringTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesStringTests.cs deleted file mode 100644 index 441ff5baa8..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesStringTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesString - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesStringTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesString - //private AdditionalPropertiesString instance; - - public AdditionalPropertiesStringTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesString - //instance = new AdditionalPropertiesString(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesString - /// - [Fact] - public void AdditionalPropertiesStringInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesString - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesString"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AnimalFarmTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AnimalFarmTests.cs deleted file mode 100644 index c101b67c92..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AnimalFarmTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AnimalFarm - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AnimalFarmTests - { - /// - /// Test an instance of AnimalFarm - /// - [Fact] - public void AnimalFarmInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AnimalFarm - //Assert.IsType (instance, "variable 'instance' is a AnimalFarm"); - } - - - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index 9b53b47f8e..ced34a4faa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Animal @@ -30,27 +29,32 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class AnimalTests + public class AnimalTests : IDisposable { + // TODO uncomment below to declare an instance variable for Animal + //private Animal instance; + + public AnimalTests() + { + // TODO uncomment below to create an instance of Animal + //instance = new Animal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of Animal /// [Fact] public void AnimalInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Animal - //Assert.IsType (instance, "variable 'instance' is a Animal"); + // TODO uncomment below to test "IsType" Animal + //Assert.IsType(instance); } - /// - /// Test deserialize a Dog from type Animal - /// - [Fact] - public void DogDeserializeFromAnimalTest() - { - // TODO uncomment below to test deserialize a Dog from type Animal - //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); - } /// /// Test deserialize a Cat from type Animal /// @@ -60,6 +64,15 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test deserialize a Cat from type Animal //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } /// /// Test the property 'ClassName' diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs index 53bef990ae..2a2e098e60 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ApiResponse @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class ApiResponseTests + public class ApiResponseTests : IDisposable { + // TODO uncomment below to declare an instance variable for ApiResponse + //private ApiResponse instance; + + public ApiResponseTests() + { + // TODO uncomment below to create an instance of ApiResponse + //instance = new ApiResponse(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of ApiResponse /// [Fact] public void ApiResponseInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ApiResponse - //Assert.IsType (instance, "variable 'instance' is a ApiResponse"); + // TODO uncomment below to test "IsType" ApiResponse + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs index 1e8e0efe11..f945f65936 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing AppleReq @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void AppleReqInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" AppleReq - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AppleReq"); + // TODO uncomment below to test "IsType" AppleReq + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AppleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AppleTests.cs index 69b870d3e2..468d60184a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AppleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/AppleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Apple @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void AppleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Apple - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Apple"); + // TODO uncomment below to test "IsType" Apple + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs index a4d155a0ae..27f312ad25 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ArrayOfNumberOnly @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class ArrayOfNumberOnlyTests + public class ArrayOfNumberOnlyTests : IDisposable { + // TODO uncomment below to declare an instance variable for ArrayOfNumberOnly + //private ArrayOfNumberOnly instance; + + public ArrayOfNumberOnlyTests() + { + // TODO uncomment below to create an instance of ArrayOfNumberOnly + //instance = new ArrayOfNumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of ArrayOfNumberOnly /// [Fact] public void ArrayOfNumberOnlyInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ArrayOfNumberOnly - //Assert.IsType (instance, "variable 'instance' is a ArrayOfNumberOnly"); + // TODO uncomment below to test "IsType" ArrayOfNumberOnly + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs index 73f8886587..a433e8c87c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ArrayTest @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class ArrayTestTests + public class ArrayTestTests : IDisposable { + // TODO uncomment below to declare an instance variable for ArrayTest + //private ArrayTest instance; + + public ArrayTestTests() + { + // TODO uncomment below to create an instance of ArrayTest + //instance = new ArrayTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of ArrayTest /// [Fact] public void ArrayTestInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ArrayTest - //Assert.IsType (instance, "variable 'instance' is a ArrayTest"); + // TODO uncomment below to test "IsType" ArrayTest + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs index 8465dc3803..8a6eeb82ee 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing BananaReq @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void BananaReqInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" BananaReq - //Assert.IsInstanceOfType (instance, "variable 'instance' is a BananaReq"); + // TODO uncomment below to test "IsType" BananaReq + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BananaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BananaTests.cs index 24ac647049..8d8cc376b0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BananaTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BananaTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Banana @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void BananaInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Banana - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Banana"); + // TODO uncomment below to test "IsType" Banana + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs index 561a829029..3cdccaa759 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing BasquePig @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void BasquePigInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" BasquePig - //Assert.IsInstanceOfType (instance, "variable 'instance' is a BasquePig"); + // TODO uncomment below to test "IsType" BasquePig + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BigCatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BigCatAllOfTests.cs deleted file mode 100644 index f1b24c7f8f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BigCatAllOfTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing BigCatAllOf - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class BigCatAllOfTests : IDisposable - { - // TODO uncomment below to declare an instance variable for BigCatAllOf - //private BigCatAllOf instance; - - public BigCatAllOfTests() - { - // TODO uncomment below to create an instance of BigCatAllOf - //instance = new BigCatAllOf(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of BigCatAllOf - /// - [Fact] - public void BigCatAllOfInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" BigCatAllOf - //Assert.IsInstanceOfType (instance, "variable 'instance' is a BigCatAllOf"); - } - - - /// - /// Test the property 'Kind' - /// - [Fact] - public void KindTest() - { - // TODO unit test for the property 'Kind' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BigCatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BigCatTests.cs deleted file mode 100644 index 4bda812119..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/BigCatTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing BigCat - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class BigCatTests : IDisposable - { - // TODO uncomment below to declare an instance variable for BigCat - //private BigCat instance; - - public BigCatTests() - { - // TODO uncomment below to create an instance of BigCat - //instance = new BigCat(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of BigCat - /// - [Fact] - public void BigCatInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" BigCat - //Assert.IsInstanceOfType (instance, "variable 'instance' is a BigCat"); - } - - - /// - /// Test the property 'Kind' - /// - [Fact] - public void KindTest() - { - // TODO unit test for the property 'Kind' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs index ec1d66fc2c..185c83666f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Capitalization @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class CapitalizationTests + public class CapitalizationTests : IDisposable { + // TODO uncomment below to declare an instance variable for Capitalization + //private Capitalization instance; + + public CapitalizationTests() + { + // TODO uncomment below to create an instance of Capitalization + //instance = new Capitalization(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of Capitalization /// [Fact] public void CapitalizationInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Capitalization - //Assert.IsType (instance, "variable 'instance' is a Capitalization"); + // TODO uncomment below to test "IsType" Capitalization + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs index 8362983f18..fb51c28489 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing CatAllOf @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void CatAllOfInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" CatAllOf - //Assert.IsInstanceOfType (instance, "variable 'instance' is a CatAllOf"); + // TODO uncomment below to test "IsType" CatAllOf + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CatTests.cs index 0f021d67e3..701ba76028 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CatTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Cat @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class CatTests + public class CatTests : IDisposable { + // TODO uncomment below to declare an instance variable for Cat + //private Cat instance; + + public CatTests() + { + // TODO uncomment below to create an instance of Cat + //instance = new Cat(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of Cat /// [Fact] public void CatInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Cat - //Assert.IsType (instance, "variable 'instance' is a Cat"); + // TODO uncomment below to test "IsType" Cat + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CategoryTests.cs index 2f59335559..6ce48e601e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CategoryTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/CategoryTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Category @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class CategoryTests + public class CategoryTests : IDisposable { + // TODO uncomment below to declare an instance variable for Category + //private Category instance; + + public CategoryTests() + { + // TODO uncomment below to create an instance of Category + //instance = new Category(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of Category /// [Fact] public void CategoryInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Category - //Assert.IsType (instance, "variable 'instance' is a Category"); + // TODO uncomment below to test "IsType" Category + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs index 2d54632e2f..49a5393249 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ChildCatAllOf @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ChildCatAllOfInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ChildCatAllOf - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ChildCatAllOf"); + // TODO uncomment below to test "IsType" ChildCatAllOf + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs index b9ea749d1d..68566fd8d5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ChildCat @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ChildCatInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ChildCat - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ChildCat"); + // TODO uncomment below to test "IsType" ChildCat + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs index 953fd93f46..d29472e83a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ClassModel @@ -30,8 +29,21 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class ClassModelTests + public class ClassModelTests : IDisposable { + // TODO uncomment below to declare an instance variable for ClassModel + //private ClassModel instance; + + public ClassModelTests() + { + // TODO uncomment below to create an instance of ClassModel + //instance = new ClassModel(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } /// /// Test an instance of ClassModel @@ -39,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ClassModelInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ClassModel - //Assert.IsType (instance, "variable 'instance' is a ClassModel"); + // TODO uncomment below to test "IsType" ClassModel + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs index 1ca093e7d1..b3529280c8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ComplexQuadrilateral @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ComplexQuadrilateralInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ComplexQuadrilateral - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ComplexQuadrilateral"); + // TODO uncomment below to test "IsType" ComplexQuadrilateral + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs index fd7376630f..572d9bffa7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing DanishPig @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void DanishPigInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" DanishPig - //Assert.IsInstanceOfType (instance, "variable 'instance' is a DanishPig"); + // TODO uncomment below to test "IsType" DanishPig + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs index 2b77790674..b22a444209 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing DogAllOf @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void DogAllOfInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" DogAllOf - //Assert.IsInstanceOfType (instance, "variable 'instance' is a DogAllOf"); + // TODO uncomment below to test "IsType" DogAllOf + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DogTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DogTests.cs index 0cd4d9125f..992f93a51f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DogTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DogTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Dog @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class DogTests + public class DogTests : IDisposable { + // TODO uncomment below to declare an instance variable for Dog + //private Dog instance; + + public DogTests() + { + // TODO uncomment below to create an instance of Dog + //instance = new Dog(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of Dog /// [Fact] public void DogInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Dog - //Assert.IsType (instance, "variable 'instance' is a Dog"); + // TODO uncomment below to test "IsType" Dog + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DrawingTests.cs index 8c0c605a5a..0709ad9eeb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DrawingTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Drawing @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void DrawingInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Drawing - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Drawing"); + // TODO uncomment below to test "IsType" Drawing + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs index 20c1eb2712..5779ca2947 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing EnumArrays @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class EnumArraysTests + public class EnumArraysTests : IDisposable { + // TODO uncomment below to declare an instance variable for EnumArrays + //private EnumArrays instance; + + public EnumArraysTests() + { + // TODO uncomment below to create an instance of EnumArrays + //instance = new EnumArrays(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of EnumArrays /// [Fact] public void EnumArraysInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" EnumArrays - //Assert.IsType (instance, "variable 'instance' is a EnumArrays"); + // TODO uncomment below to test "IsType" EnumArrays + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs index cd1fb3a70f..a17738c5cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing EnumClass @@ -30,8 +29,21 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class EnumClassTests + public class EnumClassTests : IDisposable { + // TODO uncomment below to declare an instance variable for EnumClass + //private EnumClass instance; + + public EnumClassTests() + { + // TODO uncomment below to create an instance of EnumClass + //instance = new EnumClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } /// /// Test an instance of EnumClass @@ -39,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void EnumClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" EnumClass - //Assert.IsType (instance, "variable 'instance' is a EnumClass"); + // TODO uncomment below to test "IsType" EnumClass + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index 215bdb2d3d..4f81b845d4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing EnumTest @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class EnumTestTests + public class EnumTestTests : IDisposable { + // TODO uncomment below to declare an instance variable for EnumTest + //private EnumTest instance; + + public EnumTestTests() + { + // TODO uncomment below to create an instance of EnumTest + //instance = new EnumTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of EnumTest /// [Fact] public void EnumTestInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" EnumTest - //Assert.IsType (instance, "variable 'instance' is a EnumTest"); + // TODO uncomment below to test "IsType" EnumTest + //Assert.IsType(instance); } @@ -68,6 +81,14 @@ namespace Org.OpenAPITools.Test // TODO unit test for the property 'EnumInteger' } /// + /// Test the property 'EnumIntegerOnly' + /// + [Fact] + public void EnumIntegerOnlyTest() + { + // TODO unit test for the property 'EnumIntegerOnly' + } + /// /// Test the property 'EnumNumber' /// [Fact] @@ -83,6 +104,30 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'OuterEnum' } + /// + /// Test the property 'OuterEnumInteger' + /// + [Fact] + public void OuterEnumIntegerTest() + { + // TODO unit test for the property 'OuterEnumInteger' + } + /// + /// Test the property 'OuterEnumDefaultValue' + /// + [Fact] + public void OuterEnumDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumDefaultValue' + } + /// + /// Test the property 'OuterEnumIntegerDefaultValue' + /// + [Fact] + public void OuterEnumIntegerDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumIntegerDefaultValue' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs index e3062e1ed4..4663cb667d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing EquilateralTriangle @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void EquilateralTriangleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" EquilateralTriangle - //Assert.IsInstanceOfType (instance, "variable 'instance' is a EquilateralTriangle"); + // TODO uncomment below to test "IsType" EquilateralTriangle + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs index ee350d994e..9f45b4fe89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing FileSchemaTestClass @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class FileSchemaTestClassTests + public class FileSchemaTestClassTests : IDisposable { + // TODO uncomment below to declare an instance variable for FileSchemaTestClass + //private FileSchemaTestClass instance; + + public FileSchemaTestClassTests() + { + // TODO uncomment below to create an instance of FileSchemaTestClass + //instance = new FileSchemaTestClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of FileSchemaTestClass /// [Fact] public void FileSchemaTestClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" FileSchemaTestClass - //Assert.IsType (instance, "variable 'instance' is a FileSchemaTestClass"); + // TODO uncomment below to test "IsType" FileSchemaTestClass + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FileTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FileTests.cs index d4a0d4f1eb..761bb72a84 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FileTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FileTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing File @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class FileTests + public class FileTests : IDisposable { + // TODO uncomment below to declare an instance variable for File + //private File instance; + + public FileTests() + { + // TODO uncomment below to create an instance of File + //instance = new File(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of File /// [Fact] public void FileInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" File - //Assert.IsType (instance, "variable 'instance' is a File"); + // TODO uncomment below to test "IsType" File + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FooTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FooTests.cs index 87c424c85b..0b6ed52edb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FooTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FooTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Foo @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void FooInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Foo - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Foo"); + // TODO uncomment below to test "IsType" Foo + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs index ddde2296c9..97332800e9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing FormatTest @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class FormatTestTests + public class FormatTestTests : IDisposable { + // TODO uncomment below to declare an instance variable for FormatTest + //private FormatTest instance; + + public FormatTestTests() + { + // TODO uncomment below to create an instance of FormatTest + //instance = new FormatTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of FormatTest /// [Fact] public void FormatTestInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" FormatTest - //Assert.IsType (instance, "variable 'instance' is a FormatTest"); + // TODO uncomment below to test "IsType" FormatTest + //Assert.IsType(instance); } @@ -92,6 +105,14 @@ namespace Org.OpenAPITools.Test // TODO unit test for the property 'Double' } /// + /// Test the property 'Decimal' + /// + [Fact] + public void DecimalTest() + { + // TODO unit test for the property 'Decimal' + } + /// /// Test the property 'String' /// [Fact] @@ -147,6 +168,22 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'Password' } + /// + /// Test the property 'PatternWithDigits' + /// + [Fact] + public void PatternWithDigitsTest() + { + // TODO unit test for the property 'PatternWithDigits' + } + /// + /// Test the property 'PatternWithDigitsAndDelimiter' + /// + [Fact] + public void PatternWithDigitsAndDelimiterTest() + { + // TODO unit test for the property 'PatternWithDigitsAndDelimiter' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs index 1a6d408780..5ea9e3ffc1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing FruitReq @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void FruitReqInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" FruitReq - //Assert.IsInstanceOfType (instance, "variable 'instance' is a FruitReq"); + // TODO uncomment below to test "IsType" FruitReq + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FruitTests.cs index b1bc9f600d..91e069bb42 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/FruitTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Fruit @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void FruitInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Fruit - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Fruit"); + // TODO uncomment below to test "IsType" Fruit + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs index a1bba753a5..08fb0e07a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing GmFruit @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void GmFruitInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" GmFruit - //Assert.IsInstanceOfType (instance, "variable 'instance' is a GmFruit"); + // TODO uncomment below to test "IsType" GmFruit + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index fd9552c597..faa4930944 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing GrandparentAnimal @@ -51,19 +51,10 @@ namespace Org.OpenAPITools.Test [Fact] public void GrandparentAnimalInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" GrandparentAnimal - //Assert.IsInstanceOfType (instance, "variable 'instance' is a GrandparentAnimal"); + // TODO uncomment below to test "IsType" GrandparentAnimal + //Assert.IsType(instance); } - /// - /// Test deserialize a ParentPet from type GrandparentAnimal - /// - [Fact] - public void ParentPetDeserializeFromGrandparentAnimalTest() - { - // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal - //Assert.IsInstanceOf(JsonConvert.DeserializeObject(new ParentPet().ToJson())); - } /// /// Test deserialize a ChildCat from type ParentPet /// @@ -71,7 +62,16 @@ namespace Org.OpenAPITools.Test public void ChildCatDeserializeFromParentPetTest() { // TODO uncomment below to test deserialize a ChildCat from type ParentPet - //Assert.IsInstanceOf(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs index ba33b63963..651a9f0ce3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing HasOnlyReadOnly @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class HasOnlyReadOnlyTests + public class HasOnlyReadOnlyTests : IDisposable { + // TODO uncomment below to declare an instance variable for HasOnlyReadOnly + //private HasOnlyReadOnly instance; + + public HasOnlyReadOnlyTests() + { + // TODO uncomment below to create an instance of HasOnlyReadOnly + //instance = new HasOnlyReadOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of HasOnlyReadOnly /// [Fact] public void HasOnlyReadOnlyInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" HasOnlyReadOnly - //Assert.IsType (instance, "variable 'instance' is a HasOnlyReadOnly"); + // TODO uncomment below to test "IsType" HasOnlyReadOnly + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs index d9986a9d83..857190a333 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing HealthCheckResult @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void HealthCheckResultInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" HealthCheckResult - //Assert.IsInstanceOfType (instance, "variable 'instance' is a HealthCheckResult"); + // TODO uncomment below to test "IsType" HealthCheckResult + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs deleted file mode 100644 index d1e0f45aa3..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject1 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject1Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject1 - //private InlineObject1 instance; - - public InlineObject1Tests() - { - // TODO uncomment below to create an instance of InlineObject1 - //instance = new InlineObject1(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject1 - /// - [Fact] - public void InlineObject1InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject1 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject1"); - } - - - /// - /// Test the property 'AdditionalMetadata' - /// - [Fact] - public void AdditionalMetadataTest() - { - // TODO unit test for the property 'AdditionalMetadata' - } - /// - /// Test the property 'File' - /// - [Fact] - public void FileTest() - { - // TODO unit test for the property 'File' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs deleted file mode 100644 index 8e2c754e28..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject2 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject2Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject2 - //private InlineObject2 instance; - - public InlineObject2Tests() - { - // TODO uncomment below to create an instance of InlineObject2 - //instance = new InlineObject2(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject2 - /// - [Fact] - public void InlineObject2InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject2 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject2"); - } - - - /// - /// Test the property 'EnumFormStringArray' - /// - [Fact] - public void EnumFormStringArrayTest() - { - // TODO unit test for the property 'EnumFormStringArray' - } - /// - /// Test the property 'EnumFormString' - /// - [Fact] - public void EnumFormStringTest() - { - // TODO unit test for the property 'EnumFormString' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject3Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject3Tests.cs deleted file mode 100644 index 6f74ebdf63..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject3Tests.cs +++ /dev/null @@ -1,175 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject3 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject3Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject3 - //private InlineObject3 instance; - - public InlineObject3Tests() - { - // TODO uncomment below to create an instance of InlineObject3 - //instance = new InlineObject3(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject3 - /// - [Fact] - public void InlineObject3InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject3 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject3"); - } - - - /// - /// Test the property 'Integer' - /// - [Fact] - public void IntegerTest() - { - // TODO unit test for the property 'Integer' - } - /// - /// Test the property 'Int32' - /// - [Fact] - public void Int32Test() - { - // TODO unit test for the property 'Int32' - } - /// - /// Test the property 'Int64' - /// - [Fact] - public void Int64Test() - { - // TODO unit test for the property 'Int64' - } - /// - /// Test the property 'Number' - /// - [Fact] - public void NumberTest() - { - // TODO unit test for the property 'Number' - } - /// - /// Test the property 'Float' - /// - [Fact] - public void FloatTest() - { - // TODO unit test for the property 'Float' - } - /// - /// Test the property 'Double' - /// - [Fact] - public void DoubleTest() - { - // TODO unit test for the property 'Double' - } - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - /// - /// Test the property 'PatternWithoutDelimiter' - /// - [Fact] - public void PatternWithoutDelimiterTest() - { - // TODO unit test for the property 'PatternWithoutDelimiter' - } - /// - /// Test the property 'Byte' - /// - [Fact] - public void ByteTest() - { - // TODO unit test for the property 'Byte' - } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// - /// Test the property 'Date' - /// - [Fact] - public void DateTest() - { - // TODO unit test for the property 'Date' - } - /// - /// Test the property 'DateTime' - /// - [Fact] - public void DateTimeTest() - { - // TODO unit test for the property 'DateTime' - } - /// - /// Test the property 'Password' - /// - [Fact] - public void PasswordTest() - { - // TODO unit test for the property 'Password' - } - /// - /// Test the property 'Callback' - /// - [Fact] - public void CallbackTest() - { - // TODO unit test for the property 'Callback' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject4Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject4Tests.cs deleted file mode 100644 index c3702936bc..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject4Tests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject4 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject4Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject4 - //private InlineObject4 instance; - - public InlineObject4Tests() - { - // TODO uncomment below to create an instance of InlineObject4 - //instance = new InlineObject4(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject4 - /// - [Fact] - public void InlineObject4InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject4 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject4"); - } - - - /// - /// Test the property 'Param' - /// - [Fact] - public void ParamTest() - { - // TODO unit test for the property 'Param' - } - /// - /// Test the property 'Param2' - /// - [Fact] - public void Param2Test() - { - // TODO unit test for the property 'Param2' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject5Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject5Tests.cs deleted file mode 100644 index d0bb987e46..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObject5Tests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject5 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject5Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject5 - //private InlineObject5 instance; - - public InlineObject5Tests() - { - // TODO uncomment below to create an instance of InlineObject5 - //instance = new InlineObject5(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject5 - /// - [Fact] - public void InlineObject5InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject5 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject5"); - } - - - /// - /// Test the property 'AdditionalMetadata' - /// - [Fact] - public void AdditionalMetadataTest() - { - // TODO unit test for the property 'AdditionalMetadata' - } - /// - /// Test the property 'RequiredFile' - /// - [Fact] - public void RequiredFileTest() - { - // TODO unit test for the property 'RequiredFile' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs deleted file mode 100644 index ec9a5708f2..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObjectTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject - //private InlineObject instance; - - public InlineObjectTests() - { - // TODO uncomment below to create an instance of InlineObject - //instance = new InlineObject(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject - /// - [Fact] - public void InlineObjectInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - /// - /// Test the property 'Status' - /// - [Fact] - public void StatusTest() - { - // TODO unit test for the property 'Status' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs deleted file mode 100644 index 5c20d30a69..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineResponseDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineResponseDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineResponseDefault - //private InlineResponseDefault instance; - - public InlineResponseDefaultTests() - { - // TODO uncomment below to create an instance of InlineResponseDefault - //instance = new InlineResponseDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineResponseDefault - /// - [Fact] - public void InlineResponseDefaultInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineResponseDefault - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineResponseDefault"); - } - - - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs index 00d5d08cc5..755c417cc5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing IsoscelesTriangle @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void IsoscelesTriangleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" IsoscelesTriangle - //Assert.IsInstanceOfType (instance, "variable 'instance' is a IsoscelesTriangle"); + // TODO uncomment below to test "IsType" IsoscelesTriangle + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ListTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ListTests.cs index 121957b0e4..2ed828d052 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ListTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ListTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing List @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class ListTests + public class ListTests : IDisposable { + // TODO uncomment below to declare an instance variable for List + //private List instance; + + public ListTests() + { + // TODO uncomment below to create an instance of List + //instance = new List(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of List /// [Fact] public void ListInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" List - //Assert.IsType (instance, "variable 'instance' is a List"); + // TODO uncomment below to test "IsType" List + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MammalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MammalTests.cs index 76466113c5..7b46cbf064 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MammalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MammalTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Mammal @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void MammalInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Mammal - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Mammal"); + // TODO uncomment below to test "IsType" Mammal + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MapTestTests.cs index 6a63cb9566..20036e1c90 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MapTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MapTestTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing MapTest @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class MapTestTests + public class MapTestTests : IDisposable { + // TODO uncomment below to declare an instance variable for MapTest + //private MapTest instance; + + public MapTestTests() + { + // TODO uncomment below to create an instance of MapTest + //instance = new MapTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of MapTest /// [Fact] public void MapTestInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" MapTest - //Assert.IsType (instance, "variable 'instance' is a MapTest"); + // TODO uncomment below to test "IsType" MapTest + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs index 338537287c..f56cd715f4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing MixedPropertiesAndAdditionalPropertiesClass @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class MixedPropertiesAndAdditionalPropertiesClassTests + public class MixedPropertiesAndAdditionalPropertiesClassTests : IDisposable { + // TODO uncomment below to declare an instance variable for MixedPropertiesAndAdditionalPropertiesClass + //private MixedPropertiesAndAdditionalPropertiesClass instance; + + public MixedPropertiesAndAdditionalPropertiesClassTests() + { + // TODO uncomment below to create an instance of MixedPropertiesAndAdditionalPropertiesClass + //instance = new MixedPropertiesAndAdditionalPropertiesClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of MixedPropertiesAndAdditionalPropertiesClass /// [Fact] public void MixedPropertiesAndAdditionalPropertiesClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" MixedPropertiesAndAdditionalPropertiesClass - //Assert.IsType (instance, "variable 'instance' is a MixedPropertiesAndAdditionalPropertiesClass"); + // TODO uncomment below to test "IsType" MixedPropertiesAndAdditionalPropertiesClass + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs index 6b830deb1a..e25478618f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Model200Response @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class Model200ResponseTests + public class Model200ResponseTests : IDisposable { + // TODO uncomment below to declare an instance variable for Model200Response + //private Model200Response instance; + + public Model200ResponseTests() + { + // TODO uncomment below to create an instance of Model200Response + //instance = new Model200Response(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of Model200Response /// [Fact] public void Model200ResponseInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Model200Response - //Assert.IsType (instance, "variable 'instance' is a Model200Response"); + // TODO uncomment below to test "IsType" Model200Response + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs index a74c816320..24a9e26315 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ModelClient @@ -30,26 +29,40 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class ModelClientTests + public class ModelClientTests : IDisposable { + // TODO uncomment below to declare an instance variable for ModelClient + //private ModelClient instance; + + public ModelClientTests() + { + // TODO uncomment below to create an instance of ModelClient + //instance = new ModelClient(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of ModelClient /// [Fact] public void ModelClientInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ModelClient - //Assert.IsType (instance, "variable 'instance' is a ModelClient"); + // TODO uncomment below to test "IsType" ModelClient + //Assert.IsType(instance); } /// - /// Test the property '__Client' + /// Test the property '_Client' /// [Fact] - public void __ClientTest() + public void _ClientTest() { - // TODO unit test for the property '__Client' + // TODO unit test for the property '_Client' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NameTests.cs index 14812bc593..c390049e66 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NameTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Name @@ -30,8 +29,21 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class NameTests + public class NameTests : IDisposable { + // TODO uncomment below to declare an instance variable for Name + //private Name instance; + + public NameTests() + { + // TODO uncomment below to create an instance of Name + //instance = new Name(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } /// /// Test an instance of Name @@ -39,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void NameInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Name - //Assert.IsType (instance, "variable 'instance' is a Name"); + // TODO uncomment below to test "IsType" Name + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs index d1c6b14343..8f00505612 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing NullableClass @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void NullableClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" NullableClass - //Assert.IsInstanceOfType (instance, "variable 'instance' is a NullableClass"); + // TODO uncomment below to test "IsType" NullableClass + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs index b663af5b6e..5662f91d6e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing NullableShape @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void NullableShapeInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" NullableShape - //Assert.IsInstanceOfType (instance, "variable 'instance' is a NullableShape"); + // TODO uncomment below to test "IsType" NullableShape + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs index 4e6b6674d4..3a06cb020b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing NumberOnly @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class NumberOnlyTests + public class NumberOnlyTests : IDisposable { + // TODO uncomment below to declare an instance variable for NumberOnly + //private NumberOnly instance; + + public NumberOnlyTests() + { + // TODO uncomment below to create an instance of NumberOnly + //instance = new NumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of NumberOnly /// [Fact] public void NumberOnlyInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" NumberOnly - //Assert.IsType (instance, "variable 'instance' is a NumberOnly"); + // TODO uncomment below to test "IsType" NumberOnly + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OrderTests.cs index 52c21c5494..cf5c561c54 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Order @@ -30,8 +29,21 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class OrderTests + public class OrderTests : IDisposable { + // TODO uncomment below to declare an instance variable for Order + //private Order instance; + + public OrderTests() + { + // TODO uncomment below to create an instance of Order + //instance = new Order(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } /// /// Test an instance of Order @@ -39,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OrderInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Order - //Assert.IsType (instance, "variable 'instance' is a Order"); + // TODO uncomment below to test "IsType" Order + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs index 2d95d9b8ef..2efda0db59 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterComposite @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class OuterCompositeTests + public class OuterCompositeTests : IDisposable { + // TODO uncomment below to declare an instance variable for OuterComposite + //private OuterComposite instance; + + public OuterCompositeTests() + { + // TODO uncomment below to create an instance of OuterComposite + //instance = new OuterComposite(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of OuterComposite /// [Fact] public void OuterCompositeInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterComposite - //Assert.IsType (instance, "variable 'instance' is a OuterComposite"); + // TODO uncomment below to test "IsType" OuterComposite + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs index 9c77453021..986fff774c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterEnumDefaultValue @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OuterEnumDefaultValueInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterEnumDefaultValue - //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnumDefaultValue"); + // TODO uncomment below to test "IsType" OuterEnumDefaultValue + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs index d797bc954c..015d5dab94 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterEnumIntegerDefaultValue @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OuterEnumIntegerDefaultValueInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterEnumIntegerDefaultValue - //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnumIntegerDefaultValue"); + // TODO uncomment below to test "IsType" OuterEnumIntegerDefaultValue + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs index acd34b46be..385e899110 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterEnumInteger @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OuterEnumIntegerInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterEnumInteger - //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnumInteger"); + // TODO uncomment below to test "IsType" OuterEnumInteger + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs index 00f93e5e85..f47304767b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterEnum @@ -30,8 +29,21 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class OuterEnumTests + public class OuterEnumTests : IDisposable { + // TODO uncomment below to declare an instance variable for OuterEnum + //private OuterEnum instance; + + public OuterEnumTests() + { + // TODO uncomment below to create an instance of OuterEnum + //instance = new OuterEnum(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } /// /// Test an instance of OuterEnum @@ -39,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OuterEnumInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterEnum - //Assert.IsType (instance, "variable 'instance' is a OuterEnum"); + // TODO uncomment below to test "IsType" OuterEnum + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs index 76db9ecf3a..1e17568ed3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ParentPet @@ -51,10 +51,19 @@ namespace Org.OpenAPITools.Test [Fact] public void ParentPetInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ParentPet - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ParentPet"); + // TODO uncomment below to test "IsType" ParentPet + //Assert.IsType(instance); } + /// + /// Test deserialize a ChildCat from type ParentPet + /// + [Fact] + public void ChildCatDeserializeFromParentPetTest() + { + // TODO uncomment below to test deserialize a ChildCat from type ParentPet + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/PigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/PigTests.cs index 7497d47b78..55cf218904 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/PigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/PigTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Pig @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void PigInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Pig - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Pig"); + // TODO uncomment below to test "IsType" Pig + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs index 09b365a5f1..6eef9f4c81 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing QuadrilateralInterface @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void QuadrilateralInterfaceInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" QuadrilateralInterface - //Assert.IsInstanceOfType (instance, "variable 'instance' is a QuadrilateralInterface"); + // TODO uncomment below to test "IsType" QuadrilateralInterface + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs index fea00bcd6e..26826681a4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Quadrilateral @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void QuadrilateralInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Quadrilateral - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Quadrilateral"); + // TODO uncomment below to test "IsType" Quadrilateral + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs index 3012256085..dc3d0fad54 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ReadOnlyFirst @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class ReadOnlyFirstTests + public class ReadOnlyFirstTests : IDisposable { + // TODO uncomment below to declare an instance variable for ReadOnlyFirst + //private ReadOnlyFirst instance; + + public ReadOnlyFirstTests() + { + // TODO uncomment below to create an instance of ReadOnlyFirst + //instance = new ReadOnlyFirst(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of ReadOnlyFirst /// [Fact] public void ReadOnlyFirstInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ReadOnlyFirst - //Assert.IsType (instance, "variable 'instance' is a ReadOnlyFirst"); + // TODO uncomment below to test "IsType" ReadOnlyFirst + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ReturnTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ReturnTests.cs index ce4d43f26d..c8c1d6510d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ReturnTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ReturnTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Return @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class ReturnTests + public class ReturnTests : IDisposable { + // TODO uncomment below to declare an instance variable for Return + //private Return instance; + + public ReturnTests() + { + // TODO uncomment below to create an instance of Return + //instance = new Return(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of Return /// [Fact] public void ReturnInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Return - //Assert.IsType (instance, "variable 'instance' is a Return"); + // TODO uncomment below to test "IsType" Return + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs index 5170070bf4..04cb9f1ab6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ScaleneTriangle @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ScaleneTriangleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ScaleneTriangle - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ScaleneTriangle"); + // TODO uncomment below to test "IsType" ScaleneTriangle + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs index 4ee56a550d..7bd0bc86f9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ShapeInterface @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ShapeInterfaceInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ShapeInterface - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ShapeInterface"); + // TODO uncomment below to test "IsType" ShapeInterface + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs index eb229415ae..d0af114157 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ShapeOrNull @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ShapeOrNullInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ShapeOrNull - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ShapeOrNull"); + // TODO uncomment below to test "IsType" ShapeOrNull + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeTests.cs index d2c4f92462..b01bd531f8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ShapeTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Shape @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ShapeInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Shape - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Shape"); + // TODO uncomment below to test "IsType" Shape + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs index db78f9c542..6648e98092 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing SimpleQuadrilateral @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void SimpleQuadrilateralInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" SimpleQuadrilateral - //Assert.IsInstanceOfType (instance, "variable 'instance' is a SimpleQuadrilateral"); + // TODO uncomment below to test "IsType" SimpleQuadrilateral + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/StringBooleanMapTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/StringBooleanMapTests.cs deleted file mode 100644 index b26045d414..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/StringBooleanMapTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing StringBooleanMap - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class StringBooleanMapTests - { - /// - /// Test an instance of StringBooleanMap - /// - [Fact] - public void StringBooleanMapInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" StringBooleanMap - //Assert.IsType (instance, "variable 'instance' is a StringBooleanMap"); - } - - - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TagTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TagTests.cs index 07921f122a..6d56232d0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TagTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TagTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Tag @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class TagTests + public class TagTests : IDisposable { + // TODO uncomment below to declare an instance variable for Tag + //private Tag instance; + + public TagTests() + { + // TODO uncomment below to create an instance of Tag + //instance = new Tag(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of Tag /// [Fact] public void TagInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Tag - //Assert.IsType (instance, "variable 'instance' is a Tag"); + // TODO uncomment below to test "IsType" Tag + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs index f75f2a14a6..fba65470be 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing TriangleInterface @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void TriangleInterfaceInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" TriangleInterface - //Assert.IsInstanceOfType (instance, "variable 'instance' is a TriangleInterface"); + // TODO uncomment below to test "IsType" TriangleInterface + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TriangleTests.cs index 2f3f3d284f..bdaab0b479 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TriangleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Triangle @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void TriangleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Triangle - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Triangle"); + // TODO uncomment below to test "IsType" Triangle + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TypeHolderDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TypeHolderDefaultTests.cs deleted file mode 100644 index 9bd2b1afb1..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TypeHolderDefaultTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing TypeHolderDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class TypeHolderDefaultTests - { - /// - /// Test an instance of TypeHolderDefault - /// - [Fact] - public void TypeHolderDefaultInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" TypeHolderDefault - //Assert.IsType (instance, "variable 'instance' is a TypeHolderDefault"); - } - - - /// - /// Test the property 'StringItem' - /// - [Fact] - public void StringItemTest() - { - // TODO unit test for the property 'StringItem' - } - /// - /// Test the property 'NumberItem' - /// - [Fact] - public void NumberItemTest() - { - // TODO unit test for the property 'NumberItem' - } - /// - /// Test the property 'IntegerItem' - /// - [Fact] - public void IntegerItemTest() - { - // TODO unit test for the property 'IntegerItem' - } - /// - /// Test the property 'BoolItem' - /// - [Fact] - public void BoolItemTest() - { - // TODO unit test for the property 'BoolItem' - } - /// - /// Test the property 'ArrayItem' - /// - [Fact] - public void ArrayItemTest() - { - // TODO unit test for the property 'ArrayItem' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TypeHolderExampleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TypeHolderExampleTests.cs deleted file mode 100644 index 7503d7a7d7..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/TypeHolderExampleTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing TypeHolderExample - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class TypeHolderExampleTests - { - /// - /// Test an instance of TypeHolderExample - /// - [Fact] - public void TypeHolderExampleInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" TypeHolderExample - //Assert.IsType (instance, "variable 'instance' is a TypeHolderExample"); - } - - - /// - /// Test the property 'StringItem' - /// - [Fact] - public void StringItemTest() - { - // TODO unit test for the property 'StringItem' - } - /// - /// Test the property 'NumberItem' - /// - [Fact] - public void NumberItemTest() - { - // TODO unit test for the property 'NumberItem' - } - /// - /// Test the property 'IntegerItem' - /// - [Fact] - public void IntegerItemTest() - { - // TODO unit test for the property 'IntegerItem' - } - /// - /// Test the property 'BoolItem' - /// - [Fact] - public void BoolItemTest() - { - // TODO unit test for the property 'BoolItem' - } - /// - /// Test the property 'ArrayItem' - /// - [Fact] - public void ArrayItemTest() - { - // TODO unit test for the property 'ArrayItem' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/UserTests.cs index 6a71925c5c..a7b095e4c2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing User @@ -30,16 +29,30 @@ namespace Org.OpenAPITools.Test /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the model. /// - public class UserTests + public class UserTests : IDisposable { + // TODO uncomment below to declare an instance variable for User + //private User instance; + + public UserTests() + { + // TODO uncomment below to create an instance of User + //instance = new User(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + /// /// Test an instance of User /// [Fact] public void UserInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" User - //Assert.IsType (instance, "variable 'instance' is a User"); + // TODO uncomment below to test "IsType" User + //Assert.IsType(instance); } @@ -107,6 +120,38 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'UserStatus' } + /// + /// Test the property 'ObjectWithNoDeclaredProps' + /// + [Fact] + public void ObjectWithNoDeclaredPropsTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredProps' + } + /// + /// Test the property 'ObjectWithNoDeclaredPropsNullable' + /// + [Fact] + public void ObjectWithNoDeclaredPropsNullableTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + } + /// + /// Test the property 'AnyTypeProp' + /// + [Fact] + public void AnyTypePropTest() + { + // TODO unit test for the property 'AnyTypeProp' + } + /// + /// Test the property 'AnyTypePropNullable' + /// + [Fact] + public void AnyTypePropNullableTest() + { + // TODO unit test for the property 'AnyTypePropNullable' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/WhaleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/WhaleTests.cs index d6d8d009a0..0961079194 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/WhaleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/WhaleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Whale @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void WhaleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Whale - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Whale"); + // TODO uncomment below to test "IsType" Whale + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/XmlItemTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/XmlItemTests.cs deleted file mode 100644 index bdd6c6be6a..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/XmlItemTests.cs +++ /dev/null @@ -1,281 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing XmlItem - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class XmlItemTests - { - /// - /// Test an instance of XmlItem - /// - [Fact] - public void XmlItemInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" XmlItem - //Assert.IsType (instance, "variable 'instance' is a XmlItem"); - } - - - /// - /// Test the property 'AttributeString' - /// - [Fact] - public void AttributeStringTest() - { - // TODO unit test for the property 'AttributeString' - } - /// - /// Test the property 'AttributeNumber' - /// - [Fact] - public void AttributeNumberTest() - { - // TODO unit test for the property 'AttributeNumber' - } - /// - /// Test the property 'AttributeInteger' - /// - [Fact] - public void AttributeIntegerTest() - { - // TODO unit test for the property 'AttributeInteger' - } - /// - /// Test the property 'AttributeBoolean' - /// - [Fact] - public void AttributeBooleanTest() - { - // TODO unit test for the property 'AttributeBoolean' - } - /// - /// Test the property 'WrappedArray' - /// - [Fact] - public void WrappedArrayTest() - { - // TODO unit test for the property 'WrappedArray' - } - /// - /// Test the property 'NameString' - /// - [Fact] - public void NameStringTest() - { - // TODO unit test for the property 'NameString' - } - /// - /// Test the property 'NameNumber' - /// - [Fact] - public void NameNumberTest() - { - // TODO unit test for the property 'NameNumber' - } - /// - /// Test the property 'NameInteger' - /// - [Fact] - public void NameIntegerTest() - { - // TODO unit test for the property 'NameInteger' - } - /// - /// Test the property 'NameBoolean' - /// - [Fact] - public void NameBooleanTest() - { - // TODO unit test for the property 'NameBoolean' - } - /// - /// Test the property 'NameArray' - /// - [Fact] - public void NameArrayTest() - { - // TODO unit test for the property 'NameArray' - } - /// - /// Test the property 'NameWrappedArray' - /// - [Fact] - public void NameWrappedArrayTest() - { - // TODO unit test for the property 'NameWrappedArray' - } - /// - /// Test the property 'PrefixString' - /// - [Fact] - public void PrefixStringTest() - { - // TODO unit test for the property 'PrefixString' - } - /// - /// Test the property 'PrefixNumber' - /// - [Fact] - public void PrefixNumberTest() - { - // TODO unit test for the property 'PrefixNumber' - } - /// - /// Test the property 'PrefixInteger' - /// - [Fact] - public void PrefixIntegerTest() - { - // TODO unit test for the property 'PrefixInteger' - } - /// - /// Test the property 'PrefixBoolean' - /// - [Fact] - public void PrefixBooleanTest() - { - // TODO unit test for the property 'PrefixBoolean' - } - /// - /// Test the property 'PrefixArray' - /// - [Fact] - public void PrefixArrayTest() - { - // TODO unit test for the property 'PrefixArray' - } - /// - /// Test the property 'PrefixWrappedArray' - /// - [Fact] - public void PrefixWrappedArrayTest() - { - // TODO unit test for the property 'PrefixWrappedArray' - } - /// - /// Test the property 'NamespaceString' - /// - [Fact] - public void NamespaceStringTest() - { - // TODO unit test for the property 'NamespaceString' - } - /// - /// Test the property 'NamespaceNumber' - /// - [Fact] - public void NamespaceNumberTest() - { - // TODO unit test for the property 'NamespaceNumber' - } - /// - /// Test the property 'NamespaceInteger' - /// - [Fact] - public void NamespaceIntegerTest() - { - // TODO unit test for the property 'NamespaceInteger' - } - /// - /// Test the property 'NamespaceBoolean' - /// - [Fact] - public void NamespaceBooleanTest() - { - // TODO unit test for the property 'NamespaceBoolean' - } - /// - /// Test the property 'NamespaceArray' - /// - [Fact] - public void NamespaceArrayTest() - { - // TODO unit test for the property 'NamespaceArray' - } - /// - /// Test the property 'NamespaceWrappedArray' - /// - [Fact] - public void NamespaceWrappedArrayTest() - { - // TODO unit test for the property 'NamespaceWrappedArray' - } - /// - /// Test the property 'PrefixNsString' - /// - [Fact] - public void PrefixNsStringTest() - { - // TODO unit test for the property 'PrefixNsString' - } - /// - /// Test the property 'PrefixNsNumber' - /// - [Fact] - public void PrefixNsNumberTest() - { - // TODO unit test for the property 'PrefixNsNumber' - } - /// - /// Test the property 'PrefixNsInteger' - /// - [Fact] - public void PrefixNsIntegerTest() - { - // TODO unit test for the property 'PrefixNsInteger' - } - /// - /// Test the property 'PrefixNsBoolean' - /// - [Fact] - public void PrefixNsBooleanTest() - { - // TODO unit test for the property 'PrefixNsBoolean' - } - /// - /// Test the property 'PrefixNsArray' - /// - [Fact] - public void PrefixNsArrayTest() - { - // TODO unit test for the property 'PrefixNsArray' - } - /// - /// Test the property 'PrefixNsWrappedArray' - /// - [Fact] - public void PrefixNsWrappedArrayTest() - { - // TODO unit test for the property 'PrefixNsWrappedArray' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ZebraTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ZebraTests.cs index 84ebb849aa..f44e921314 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ZebraTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Model/ZebraTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Zebra @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ZebraInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Zebra - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Zebra"); + // TODO uncomment below to test "IsType" Zebra + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 3ebd3e4a84..1f62df0559 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -10,7 +10,7 @@ OpenAPI spec version: 1.0.0 - netcoreapp2.0 + netcoreapp3.1 false diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index e04c8df5fd..95d41fcbd9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs index ff7ce75367..bc5b5556d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs index 421f93ed04..5991b7f0b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 6b66577525..dd74c66d15 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs index 125b0f5cb7..e8439eb125 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api @@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs index 63403e7dcd..e01ed16258 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs index c37a6501c6..8efb827cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs index cd27f08911..b488b996d0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs @@ -24,18 +24,18 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; -using RestSharp.Deserializers; +using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { /// /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// - internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; @@ -81,7 +81,9 @@ namespace Org.OpenAPITools.Client } } - public T Deserialize(IRestResponse response) + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; @@ -93,7 +95,7 @@ namespace Org.OpenAPITools.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(IRestResponse response, Type type) + internal object Deserialize(RestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { @@ -146,15 +148,22 @@ namespace Org.OpenAPITools.Client } } - public string RootElement { get; set; } - public string Namespace { get; set; } - public string DateFormat { get; set; } + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } + + public DataFormat DataFormat => DataFormat.Json; } /// /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), @@ -185,14 +194,14 @@ namespace Org.OpenAPITools.Client /// Allows for extending request processing for generated code. /// /// The RestSharp request object - partial void InterceptRequest(IRestRequest request); + partial void InterceptRequest(RestRequest request); /// /// Allows for extending response processing for generated code. /// /// The RestSharp request object /// The RestSharp response object - partial void InterceptResponse(IRestRequest request, IRestResponse response); + partial void InterceptResponse(RestRequest request, RestResponse response); /// /// Initializes a new instance of the , defaulting to the global configurations' base url. @@ -227,25 +236,25 @@ namespace Org.OpenAPITools.Client switch (method) { case HttpMethod.Get: - other = RestSharpMethod.GET; + other = RestSharpMethod.Get; break; case HttpMethod.Post: - other = RestSharpMethod.POST; + other = RestSharpMethod.Post; break; case HttpMethod.Put: - other = RestSharpMethod.PUT; + other = RestSharpMethod.Put; break; case HttpMethod.Delete: - other = RestSharpMethod.DELETE; + other = RestSharpMethod.Delete; break; case HttpMethod.Head: - other = RestSharpMethod.HEAD; + other = RestSharpMethod.Head; break; case HttpMethod.Options: - other = RestSharpMethod.OPTIONS; + other = RestSharpMethod.Options; break; case HttpMethod.Patch: - other = RestSharpMethod.PATCH; + other = RestSharpMethod.Patch; break; default: throw new ArgumentOutOfRangeException("method", method, null); @@ -276,11 +285,7 @@ namespace Org.OpenAPITools.Client if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); - RestRequest request = new RestRequest(Method(method)) - { - Resource = path, - JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) - }; + RestRequest request = new RestRequest(path, Method(method)); if (options.PathParameters != null) { @@ -375,25 +380,17 @@ namespace Org.OpenAPITools.Client var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); else - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } } } - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - request.AddCookie(cookie.Name, cookie.Value); - } - } - return request; } - private ApiResponse ToApiResponse(IRestResponse response) + private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; string rawContent = response.Content; @@ -412,9 +409,17 @@ namespace Org.OpenAPITools.Client } } + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + if (response.Cookies != null) { - foreach (var responseCookies in response.Cookies) + foreach (var responseCookies in response.Cookies.Cast()) { transformed.Cookies.Add( new Cookie( @@ -432,54 +437,46 @@ namespace Org.OpenAPITools.Client private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else - { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } } - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.Proxy = configuration.Proxy; - } + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); - if (configuration.ClientCertificates != null) + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; @@ -515,6 +512,10 @@ namespace Org.OpenAPITools.Client { response.Data = (T)(object)response.RawBytes; } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } InterceptResponse(req, response); @@ -527,7 +528,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, @@ -556,54 +557,35 @@ namespace Org.OpenAPITools.Client private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); - } - - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) - { - client.Proxy = configuration.Proxy; - } - - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; @@ -644,7 +626,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs new file mode 100644 index 0000000000..8b0ba33499 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs @@ -0,0 +1,95 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : AuthenticatorBase + { + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) : base("") + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// Access token to create a parameter from. + /// An authentication parameter. + protected override async ValueTask GetAuthenticationParameter(string accessToken) + { + var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl) + .UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration)); + + var request = new RestRequest() + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + var response = await client.PostAsync(request); + return $"{response.TokenType} {response.AccessToken}"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs new file mode 100644 index 0000000000..e225740925 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs @@ -0,0 +1,27 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs new file mode 100644 index 0000000000..0a94e17e12 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Client.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs index dcc97c295e..e499a7728e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -120,6 +120,16 @@ namespace Org.OpenAPITools.Client return Convert.ToString(obj, CultureInfo.InvariantCulture); } + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + /// /// Encode string in base64 format. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Configuration.cs index a67ad721ed..9f9385b5e2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Configuration.cs @@ -17,6 +17,8 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Net.Http; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -113,7 +115,7 @@ namespace Org.OpenAPITools.Client public Configuration() { Proxy = null; - UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); BasePath = "http://petstore.swagger.io:80/v2"; DefaultHeaders = new ConcurrentDictionary(); ApiKey = new ConcurrentDictionary(); @@ -361,6 +363,30 @@ namespace Org.OpenAPITools.Client /// The access token. public virtual string AccessToken { get; set; } + /// + /// Gets or sets the token URL for OAuth2 authentication. + /// + /// The OAuth Token URL. + public virtual string OAuthTokenUrl { get; set; } + + /// + /// Gets or sets the client ID for OAuth2 authentication. + /// + /// The OAuth Client ID. + public virtual string OAuthClientId { get; set; } + + /// + /// Gets or sets the client secret for OAuth2 authentication. + /// + /// The OAuth Client Secret. + public virtual string OAuthClientSecret { get; set; } + + /// + /// Gets or sets the flow for OAuth2 authentication. + /// + /// The OAuth Flow. + public virtual OAuthFlow? OAuthFlow { get; set; } + /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// @@ -684,6 +710,10 @@ namespace Org.OpenAPITools.Client Username = second.Username ?? first.Username, Password = second.Password ?? first.Password, AccessToken = second.AccessToken ?? first.AccessToken, + OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl, + OAuthClientId = second.OAuthClientId ?? first.OAuthClientId, + OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret, + OAuthFlow = second.OAuthFlow ?? first.OAuthFlow, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 6a8f9c8dc0..0b3e867d0f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -325,14 +325,18 @@ namespace Org.OpenAPITools.Client /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { - if (!File.Exists(KeyFilePath)) + string keyStr = string.Empty; + if (File.Exists(KeyFilePath)) { - throw new Exception("key file path does not exist."); + keyStr = File.ReadAllText(KeyFilePath); + } + else + { + keyStr = KeyFilePath; } const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; - var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); var ecdsa = ECDsa.Create(); @@ -430,11 +434,15 @@ namespace Org.OpenAPITools.Client bool isPrivateKeyFile = true; byte[] pemkey = null; - if (!File.Exists(pemfile)) + string pemstr = string.Empty; + if (File.Exists(pemfile)) { - throw new Exception("private key file does not exist."); + pemstr = File.ReadAllText(pemfile).Trim(); + } + else + { + pemstr = pemfile; } - string pemstr = File.ReadAllText(pemfile).Trim(); if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) { @@ -725,9 +733,16 @@ namespace Org.OpenAPITools.Client /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { - if (!File.Exists(keyFilePath)) + string[] key = null; + + if (File.Exists(keyFilePath)) { - throw new Exception("Key file path does not exist."); + key = File.ReadAllLines(keyFilePath); + } + else + { + // The ApiKeyFilePath is passed as string + key = new string[] { keyFilePath }; } const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; @@ -737,7 +752,6 @@ namespace Org.OpenAPITools.Client //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; PrivateKeyType keyType; - var key = File.ReadAllLines(keyFilePath); if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) @@ -751,7 +765,7 @@ namespace Org.OpenAPITools.Client } else { - throw new Exception("Either the key is invalid or key is not supported"); + throw new Exception("The key file path does not exist or key is invalid or key is not supported"); } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IReadableConfiguration.cs index b99a151e5b..c9615dc5aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IReadableConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; using System.Net; using System.Security.Cryptography.X509Certificates; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client /// Access token. string AccessToken { get; } + /// + /// Gets the OAuth token URL. + /// + /// OAuth Token URL. + string OAuthTokenUrl { get; } + + /// + /// Gets the OAuth client ID. + /// + /// OAuth Client ID. + string OAuthClientId { get; } + + /// + /// Gets the OAuth client secret. + /// + /// OAuth Client Secret. + string OAuthClientSecret { get; } + + /// + /// Gets the OAuth flow. + /// + /// OAuth Flow. + OAuthFlow? OAuthFlow { get; } + /// /// Gets the API key. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RequestOptions.cs index 3932047e02..4c26cf69b2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client /// public Object Data { get; set; } + /// + /// If request should be authenticated with OAuth. + /// + public bool OAuth { get; set; } + /// /// Constructs a new instance of /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RetryConfiguration.cs index 91bc7cc6d5..7011f69e77 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RetryConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client /// /// Retry policy /// - public static Policy RetryPolicy { get; set; } + public static Policy RetryPolicy { get; set; } /// /// Async retry policy /// - public static AsyncPolicy AsyncRetryPolicy { get; set; } + public static AsyncPolicy AsyncRetryPolicy { get; set; } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Animal.cs index f5150493c8..83397018b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Animal.cs @@ -65,7 +65,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AppleReq.cs index 2c77cf1c41..9e09e2da8c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AppleReq.cs @@ -56,7 +56,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Cultivar /// - [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = true)] public string Cultivar { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BananaReq.cs index fdd36929d1..3edb9a1b6d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BananaReq.cs @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets LengthCm /// - [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = true)] public decimal LengthCm { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BasquePig.cs index e0c780a14b..f65f049cfd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BasquePig.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Cat.cs index 2bc55707da..86ceaeed1a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Cat.cs @@ -145,7 +145,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Category.cs index 35732f998d..94dea2b30b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Category.cs @@ -66,7 +66,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs index 4c60ed776c..2aa81264fa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs @@ -57,14 +57,6 @@ namespace Org.OpenAPITools.Model /// /// Initializes a new instance of the class. /// - [JsonConstructorAttribute] - protected ChildCat() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// /// name. /// petType (default to PetTypeEnum.ChildCat). public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() @@ -170,7 +162,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index dc78561c0d..353ea1d081 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DanishPig.cs index 38628258d1..d86ff21df9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DanishPig.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Dog.cs index 9cd520deaf..786270d1c4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Dog.cs @@ -148,7 +148,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs index 6d7830c0e8..69568d6c87 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -78,13 +78,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets ArrayEnum - /// - [DataMember(Name = "array_enum", EmitDefaultValue = false)] - public List ArrayEnum { get; set; } /// /// Initializes a new instance of the class. /// @@ -97,6 +90,12 @@ namespace Org.OpenAPITools.Model this.AdditionalProperties = new Dictionary(); } + /// + /// Gets or Sets ArrayEnum + /// + [DataMember(Name = "array_enum", EmitDefaultValue = false)] + public List ArrayEnum { get; set; } + /// /// Gets or Sets additional properties /// @@ -157,7 +156,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumTest.cs index 6f3d2272c5..7386cffd37 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumTest.cs @@ -94,7 +94,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets EnumStringRequired /// - [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = true)] public EnumStringRequiredEnum EnumStringRequired { get; set; } /// /// Defines EnumInteger diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 6565b7b6f3..773eba5b0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FormatTest.cs index 4ae624cb61..9d0979b6f7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FormatTest.cs @@ -111,7 +111,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Number /// - [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = true)] public decimal Number { get; set; } /// @@ -141,7 +141,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Byte /// - [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = true)] public byte[] Byte { get; set; } /// @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Date /// - [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] [JsonConverter(typeof(OpenAPIDateConverter))] public DateTime Date { get; set; } @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Password /// - [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = true)] public string Password { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index eddfcf6011..28e7729a17 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] public string PetType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject.cs deleted file mode 100644 index 651f325b64..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject.cs +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject - /// - [DataContract(Name = "inline_object")] - public partial class InlineObject : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// Updated name of the pet. - /// Updated status of the pet. - public InlineObject(string name = default(string), string status = default(string)) - { - this.Name = name; - this.Status = status; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Updated name of the pet - /// - /// Updated name of the pet - [DataMember(Name = "name", EmitDefaultValue = false)] - public string Name { get; set; } - - /// - /// Updated status of the pet - /// - /// Updated status of the pet - [DataMember(Name = "status", EmitDefaultValue = false)] - public string Status { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject {\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject).AreEqual; - } - - /// - /// Returns true if InlineObject instances are equal - /// - /// Instance of InlineObject to be compared - /// Boolean - public bool Equals(InlineObject input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - if (this.Status != null) - hashCode = hashCode * 59 + this.Status.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject1.cs deleted file mode 100644 index 9e96b966e9..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject1.cs +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject1 - /// - [DataContract(Name = "inline_object_1")] - public partial class InlineObject1 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// Additional data to pass to server. - /// file to upload. - public InlineObject1(string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) - { - this.AdditionalMetadata = additionalMetadata; - this.File = file; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Additional data to pass to server - /// - /// Additional data to pass to server - [DataMember(Name = "additionalMetadata", EmitDefaultValue = false)] - public string AdditionalMetadata { get; set; } - - /// - /// file to upload - /// - /// file to upload - [DataMember(Name = "file", EmitDefaultValue = false)] - public System.IO.Stream File { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject1 {\n"); - sb.Append(" AdditionalMetadata: ").Append(AdditionalMetadata).Append("\n"); - sb.Append(" File: ").Append(File).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject1).AreEqual; - } - - /// - /// Returns true if InlineObject1 instances are equal - /// - /// Instance of InlineObject1 to be compared - /// Boolean - public bool Equals(InlineObject1 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.AdditionalMetadata != null) - hashCode = hashCode * 59 + this.AdditionalMetadata.GetHashCode(); - if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject2.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject2.cs deleted file mode 100644 index 0a8a33d11a..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject2.cs +++ /dev/null @@ -1,185 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject2 - /// - [DataContract(Name = "inline_object_2")] - public partial class InlineObject2 : IEquatable, IValidatableObject - { - /// - /// Defines EnumFormStringArray - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumFormStringArrayEnum - { - /// - /// Enum GreaterThan for value: > - /// - [EnumMember(Value = ">")] - GreaterThan = 1, - - /// - /// Enum Dollar for value: $ - /// - [EnumMember(Value = "$")] - Dollar = 2 - - } - - - /// - /// Form parameter enum test (string array) - /// - /// Form parameter enum test (string array) - [DataMember(Name = "enum_form_string_array", EmitDefaultValue = false)] - public List EnumFormStringArray { get; set; } - /// - /// Form parameter enum test (string) - /// - /// Form parameter enum test (string) - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumFormStringEnum - { - /// - /// Enum Abc for value: _abc - /// - [EnumMember(Value = "_abc")] - Abc = 1, - - /// - /// Enum Efg for value: -efg - /// - [EnumMember(Value = "-efg")] - Efg = 2, - - /// - /// Enum Xyz for value: (xyz) - /// - [EnumMember(Value = "(xyz)")] - Xyz = 3 - - } - - /// - /// Form parameter enum test (string) - /// - /// Form parameter enum test (string) - [DataMember(Name = "enum_form_string", EmitDefaultValue = false)] - public EnumFormStringEnum? EnumFormString { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// Form parameter enum test (string array). - /// Form parameter enum test (string) (default to EnumFormStringEnum.Efg). - public InlineObject2(List enumFormStringArray = default(List), EnumFormStringEnum? enumFormString = EnumFormStringEnum.Efg) - { - this.EnumFormStringArray = enumFormStringArray; - this.EnumFormString = enumFormString; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject2 {\n"); - sb.Append(" EnumFormStringArray: ").Append(EnumFormStringArray).Append("\n"); - sb.Append(" EnumFormString: ").Append(EnumFormString).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject2).AreEqual; - } - - /// - /// Returns true if InlineObject2 instances are equal - /// - /// Instance of InlineObject2 to be compared - /// Boolean - public bool Equals(InlineObject2 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - hashCode = hashCode * 59 + this.EnumFormStringArray.GetHashCode(); - hashCode = hashCode * 59 + this.EnumFormString.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject3.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject3.cs deleted file mode 100644 index 7fce7c5559..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject3.cs +++ /dev/null @@ -1,370 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject3 - /// - [DataContract(Name = "inline_object_3")] - public partial class InlineObject3 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject3() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// - /// None. - /// None. - /// None. - /// None (required). - /// None. - /// None (required). - /// None. - /// None (required). - /// None (required). - /// None. - /// None. - /// None (default to "2010-02-01T10:20:10.111110+01:00"). - /// None. - /// None. - public InlineObject3(int integer = default(int), int int32 = default(int), long int64 = default(long), decimal number = default(decimal), float _float = default(float), double _double = default(double), string _string = default(string), string patternWithoutDelimiter = default(string), byte[] _byte = default(byte[]), System.IO.Stream binary = default(System.IO.Stream), DateTime date = default(DateTime), DateTime dateTime = default(DateTime), string password = default(string), string callback = default(string)) - { - this.Number = number; - this.Double = _double; - // to ensure "patternWithoutDelimiter" is required (not null) - this.PatternWithoutDelimiter = patternWithoutDelimiter ?? throw new ArgumentNullException("patternWithoutDelimiter is a required property for InlineObject3 and cannot be null"); - // to ensure "_byte" is required (not null) - this.Byte = _byte ?? throw new ArgumentNullException("_byte is a required property for InlineObject3 and cannot be null"); - this.Integer = integer; - this.Int32 = int32; - this.Int64 = int64; - this.Float = _float; - this.String = _string; - this.Binary = binary; - this.Date = date; - this.DateTime = dateTime; - this.Password = password; - this.Callback = callback; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// None - /// - /// None - [DataMember(Name = "integer", EmitDefaultValue = false)] - public int Integer { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "int32", EmitDefaultValue = false)] - public int Int32 { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "int64", EmitDefaultValue = false)] - public long Int64 { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] - public decimal Number { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "float", EmitDefaultValue = false)] - public float Float { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "double", IsRequired = true, EmitDefaultValue = false)] - public double Double { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "string", EmitDefaultValue = false)] - public string String { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "pattern_without_delimiter", IsRequired = true, EmitDefaultValue = false)] - public string PatternWithoutDelimiter { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] - public byte[] Byte { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "binary", EmitDefaultValue = false)] - public System.IO.Stream Binary { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "date", EmitDefaultValue = false)] - [JsonConverter(typeof(OpenAPIDateConverter))] - public DateTime Date { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "dateTime", EmitDefaultValue = false)] - public DateTime DateTime { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "password", EmitDefaultValue = false)] - public string Password { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "callback", EmitDefaultValue = false)] - public string Callback { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject3 {\n"); - sb.Append(" Integer: ").Append(Integer).Append("\n"); - sb.Append(" Int32: ").Append(Int32).Append("\n"); - sb.Append(" Int64: ").Append(Int64).Append("\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Float: ").Append(Float).Append("\n"); - sb.Append(" Double: ").Append(Double).Append("\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" PatternWithoutDelimiter: ").Append(PatternWithoutDelimiter).Append("\n"); - sb.Append(" Byte: ").Append(Byte).Append("\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); - sb.Append(" Date: ").Append(Date).Append("\n"); - sb.Append(" DateTime: ").Append(DateTime).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); - sb.Append(" Callback: ").Append(Callback).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject3).AreEqual; - } - - /// - /// Returns true if InlineObject3 instances are equal - /// - /// Instance of InlineObject3 to be compared - /// Boolean - public bool Equals(InlineObject3 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - hashCode = hashCode * 59 + this.Integer.GetHashCode(); - hashCode = hashCode * 59 + this.Int32.GetHashCode(); - hashCode = hashCode * 59 + this.Int64.GetHashCode(); - hashCode = hashCode * 59 + this.Number.GetHashCode(); - hashCode = hashCode * 59 + this.Float.GetHashCode(); - hashCode = hashCode * 59 + this.Double.GetHashCode(); - if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); - if (this.PatternWithoutDelimiter != null) - hashCode = hashCode * 59 + this.PatternWithoutDelimiter.GetHashCode(); - if (this.Byte != null) - hashCode = hashCode * 59 + this.Byte.GetHashCode(); - if (this.Binary != null) - hashCode = hashCode * 59 + this.Binary.GetHashCode(); - if (this.Date != null) - hashCode = hashCode * 59 + this.Date.GetHashCode(); - if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); - if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); - if (this.Callback != null) - hashCode = hashCode * 59 + this.Callback.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - // Integer (int) maximum - if(this.Integer > (int)100) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); - } - - // Integer (int) minimum - if(this.Integer < (int)10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); - } - - // Int32 (int) maximum - if(this.Int32 > (int)200) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); - } - - // Int32 (int) minimum - if(this.Int32 < (int)20) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); - } - - // Number (decimal) maximum - if(this.Number > (decimal)543.2) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); - } - - // Number (decimal) minimum - if(this.Number < (decimal)32.1) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); - } - - // Float (float) maximum - if(this.Float > (float)987.6) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); - } - - // Double (double) maximum - if(this.Double > (double)123.4) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); - } - - // Double (double) minimum - if(this.Double < (double)67.8) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); - } - - // String (string) pattern - Regex regexString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (false == regexString.Match(this.String).Success) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for String, must match a pattern of " + regexString, new [] { "String" }); - } - - // PatternWithoutDelimiter (string) pattern - Regex regexPatternWithoutDelimiter = new Regex(@"^[A-Z].*", RegexOptions.CultureInvariant); - if (false == regexPatternWithoutDelimiter.Match(this.PatternWithoutDelimiter).Success) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithoutDelimiter, must match a pattern of " + regexPatternWithoutDelimiter, new [] { "PatternWithoutDelimiter" }); - } - - // Password (string) maxLength - if(this.Password != null && this.Password.Length > 64) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); - } - - // Password (string) minLength - if(this.Password != null && this.Password.Length < 10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); - } - - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject4.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject4.cs deleted file mode 100644 index 72cece1061..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject4.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject4 - /// - [DataContract(Name = "inline_object_4")] - public partial class InlineObject4 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject4() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// - /// field1 (required). - /// field2 (required). - public InlineObject4(string param = default(string), string param2 = default(string)) - { - // to ensure "param" is required (not null) - this.Param = param ?? throw new ArgumentNullException("param is a required property for InlineObject4 and cannot be null"); - // to ensure "param2" is required (not null) - this.Param2 = param2 ?? throw new ArgumentNullException("param2 is a required property for InlineObject4 and cannot be null"); - this.AdditionalProperties = new Dictionary(); - } - - /// - /// field1 - /// - /// field1 - [DataMember(Name = "param", IsRequired = true, EmitDefaultValue = false)] - public string Param { get; set; } - - /// - /// field2 - /// - /// field2 - [DataMember(Name = "param2", IsRequired = true, EmitDefaultValue = false)] - public string Param2 { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject4 {\n"); - sb.Append(" Param: ").Append(Param).Append("\n"); - sb.Append(" Param2: ").Append(Param2).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject4).AreEqual; - } - - /// - /// Returns true if InlineObject4 instances are equal - /// - /// Instance of InlineObject4 to be compared - /// Boolean - public bool Equals(InlineObject4 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.Param != null) - hashCode = hashCode * 59 + this.Param.GetHashCode(); - if (this.Param2 != null) - hashCode = hashCode * 59 + this.Param2.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject5.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject5.cs deleted file mode 100644 index f682f14ef4..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineObject5.cs +++ /dev/null @@ -1,150 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject5 - /// - [DataContract(Name = "inline_object_5")] - public partial class InlineObject5 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject5() - { - this.AdditionalProperties = new Dictionary(); - } - /// - /// Initializes a new instance of the class. - /// - /// Additional data to pass to server. - /// file to upload (required). - public InlineObject5(string additionalMetadata = default(string), System.IO.Stream requiredFile = default(System.IO.Stream)) - { - // to ensure "requiredFile" is required (not null) - this.RequiredFile = requiredFile ?? throw new ArgumentNullException("requiredFile is a required property for InlineObject5 and cannot be null"); - this.AdditionalMetadata = additionalMetadata; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Additional data to pass to server - /// - /// Additional data to pass to server - [DataMember(Name = "additionalMetadata", EmitDefaultValue = false)] - public string AdditionalMetadata { get; set; } - - /// - /// file to upload - /// - /// file to upload - [DataMember(Name = "requiredFile", IsRequired = true, EmitDefaultValue = false)] - public System.IO.Stream RequiredFile { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject5 {\n"); - sb.Append(" AdditionalMetadata: ").Append(AdditionalMetadata).Append("\n"); - sb.Append(" RequiredFile: ").Append(RequiredFile).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject5).AreEqual; - } - - /// - /// Returns true if InlineObject5 instances are equal - /// - /// Instance of InlineObject5 to be compared - /// Boolean - public bool Equals(InlineObject5 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.AdditionalMetadata != null) - hashCode = hashCode * 59 + this.AdditionalMetadata.GetHashCode(); - if (this.RequiredFile != null) - hashCode = hashCode * 59 + this.RequiredFile.GetHashCode(); - if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs deleted file mode 100644 index ae46f1f009..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineResponseDefault - /// - [DataContract(Name = "inline_response_default")] - public partial class InlineResponseDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// _string. - public InlineResponseDefault(Foo _string = default(Foo)) - { - this.String = _string; - this.AdditionalProperties = new Dictionary(); - } - - /// - /// Gets or Sets String - /// - [DataMember(Name = "string", EmitDefaultValue = false)] - public Foo String { get; set; } - - /// - /// Gets or Sets additional properties - /// - [JsonExtensionData] - public IDictionary AdditionalProperties { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineResponseDefault {\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineResponseDefault).AreEqual; - } - - /// - /// Returns true if InlineResponseDefault instances are equal - /// - /// Instance of InlineResponseDefault to be compared - /// Boolean - public bool Equals(InlineResponseDefault input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - if (this.AdditionalProperties != null) - { - hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 55c607598a..ea18925f87 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -61,13 +61,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs index 8b5a73e773..b2aeedc33c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs @@ -52,13 +52,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets MapOfEnumString - /// - [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] - public Dictionary MapOfEnumString { get; set; } /// /// Initializes a new instance of the class. /// @@ -81,6 +74,12 @@ namespace Org.OpenAPITools.Model [DataMember(Name = "map_map_of_string", EmitDefaultValue = false)] public Dictionary> MapMapOfString { get; set; } + /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] + public Dictionary MapOfEnumString { get; set; } + /// /// Gets or Sets DirectMap /// @@ -158,7 +157,10 @@ namespace Org.OpenAPITools.Model { hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); } - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } if (this.DirectMap != null) { hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs index 0dc21bb656..1d4e760506 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs @@ -55,7 +55,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets _Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public int _Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ParentPet.cs index ac986b555e..49bed67986 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ParentPet.cs @@ -135,7 +135,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pet.cs index 4723827264..0e6f950d7f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pet.cs @@ -119,13 +119,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// /// Gets or Sets PhotoUrls /// - [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = true)] public List PhotoUrls { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index cb2a5dc169..d5be5ea3c9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index e54c584688..236020031e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeInterface.cs index 6225f8888a..c9294b0b4e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index b8fbc0c240..59397bf30f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -65,13 +65,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/TriangleInterface.cs index 17571e4514..cdf2bd1f0f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Whale.cs index 10ceda658b..62ae66415f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Whale.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs index aab75e9cd5..8a3c713fe6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs @@ -92,7 +92,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 5889bffe70..830f64d090 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,11 +21,17 @@ - + - + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/FILES index 274c950fa8..ba71e29dcc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/FILES @@ -97,6 +97,9 @@ src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs +src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs +src/Org.OpenAPITools/Client/Auth/TokenResponse.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesAnyType.md deleted file mode 100644 index 2513b741ba..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesAnyType.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesAnyType -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesArray.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesArray.md deleted file mode 100644 index 39a7c940c2..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesArray.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesArray -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesBoolean.md deleted file mode 100644 index e3b30ac619..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesBoolean.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesBoolean -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesInteger.md deleted file mode 100644 index e40cc1e54e..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesInteger.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesInteger -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesNumber.md deleted file mode 100644 index 91764084c8..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesNumber.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesNumber -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesObject.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesObject.md deleted file mode 100644 index 2fa66f43d6..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesObject.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesObject -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesString.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesString.md deleted file mode 100644 index 008d3d4f33..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/AdditionalPropertiesString.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.AdditionalPropertiesString -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/BigCat.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/BigCat.md deleted file mode 100644 index 41c336e4ca..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/BigCat.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.BigCat -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Declawed** | **bool** | | [optional] -**Kind** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/BigCatAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/BigCatAllOf.md deleted file mode 100644 index 88a739b7e4..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/BigCatAllOf.md +++ /dev/null @@ -1,9 +0,0 @@ -# Org.OpenAPITools.Model.BigCatAllOf -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Kind** | **string** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/EnumArrays.md index 8881585a4c..62e34f03db 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/EnumArrays.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/EnumArrays.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject.md deleted file mode 100644 index 40e16da1bb..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Name** | **string** | Updated name of the pet | [optional] -**Status** | **string** | Updated status of the pet | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject1.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject1.md deleted file mode 100644 index 2e6d226754..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject1.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject1 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**AdditionalMetadata** | **string** | Additional data to pass to server | [optional] -**File** | **System.IO.Stream** | file to upload | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject2.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject2.md deleted file mode 100644 index c02c78f9b2..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject2.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject2 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**EnumFormStringArray** | **List<string>** | Form parameter enum test (string array) | [optional] -**EnumFormString** | **string** | Form parameter enum test (string) | [optional] [default to EnumFormStringEnum.Efg] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject3.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject3.md deleted file mode 100644 index 38b5bf8a5c..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject3.md +++ /dev/null @@ -1,22 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject3 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Integer** | **int** | None | [optional] -**Int32** | **int** | None | [optional] -**Int64** | **long** | None | [optional] -**Number** | **decimal** | None | -**Float** | **float** | None | [optional] -**Double** | **double** | None | -**String** | **string** | None | [optional] -**PatternWithoutDelimiter** | **string** | None | -**Byte** | **byte[]** | None | -**Binary** | **System.IO.Stream** | None | [optional] -**Date** | **DateTime** | None | [optional] -**DateTime** | **DateTime** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] -**Password** | **string** | None | [optional] -**Callback** | **string** | None | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject4.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject4.md deleted file mode 100644 index c8e00663ee..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject4.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject4 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**Param** | **string** | field1 | -**Param2** | **string** | field2 | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject5.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject5.md deleted file mode 100644 index a28ff47f2e..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineObject5.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineObject5 -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**AdditionalMetadata** | **string** | Additional data to pass to server | [optional] -**RequiredFile** | **System.IO.Stream** | file to upload | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineResponseDefault.md deleted file mode 100644 index e3d55e133f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/InlineResponseDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# Org.OpenAPITools.Model.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**String** | [**Foo**](Foo.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/MapTest.md index dc1ebba4e7..516f9d4fd3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/MapTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/MapTest.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/TypeHolderDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/TypeHolderDefault.md deleted file mode 100644 index ccf43c723e..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/TypeHolderDefault.md +++ /dev/null @@ -1,13 +0,0 @@ -# Org.OpenAPITools.Model.TypeHolderDefault -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**StringItem** | **string** | | [default to "what"] -**NumberItem** | **decimal** | | -**IntegerItem** | **int** | | -**BoolItem** | **bool** | | [default to true] -**ArrayItem** | **List<int>** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/TypeHolderExample.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/TypeHolderExample.md deleted file mode 100644 index f78185c2aa..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/TypeHolderExample.md +++ /dev/null @@ -1,14 +0,0 @@ -# Org.OpenAPITools.Model.TypeHolderExample -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**StringItem** | **string** | | -**NumberItem** | **decimal** | | -**FloatItem** | **float** | | -**IntegerItem** | **int** | | -**BoolItem** | **bool** | | -**ArrayItem** | **List<int>** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/XmlItem.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/XmlItem.md deleted file mode 100644 index 679fd2c3d1..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/XmlItem.md +++ /dev/null @@ -1,37 +0,0 @@ -# Org.OpenAPITools.Model.XmlItem -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**AttributeString** | **string** | | [optional] -**AttributeNumber** | **decimal** | | [optional] -**AttributeInteger** | **int** | | [optional] -**AttributeBoolean** | **bool** | | [optional] -**WrappedArray** | **List<int>** | | [optional] -**NameString** | **string** | | [optional] -**NameNumber** | **decimal** | | [optional] -**NameInteger** | **int** | | [optional] -**NameBoolean** | **bool** | | [optional] -**NameArray** | **List<int>** | | [optional] -**NameWrappedArray** | **List<int>** | | [optional] -**PrefixString** | **string** | | [optional] -**PrefixNumber** | **decimal** | | [optional] -**PrefixInteger** | **int** | | [optional] -**PrefixBoolean** | **bool** | | [optional] -**PrefixArray** | **List<int>** | | [optional] -**PrefixWrappedArray** | **List<int>** | | [optional] -**NamespaceString** | **string** | | [optional] -**NamespaceNumber** | **decimal** | | [optional] -**NamespaceInteger** | **int** | | [optional] -**NamespaceBoolean** | **bool** | | [optional] -**NamespaceArray** | **List<int>** | | [optional] -**NamespaceWrappedArray** | **List<int>** | | [optional] -**PrefixNsString** | **string** | | [optional] -**PrefixNsNumber** | **decimal** | | [optional] -**PrefixNsInteger** | **int** | | [optional] -**PrefixNsBoolean** | **bool** | | [optional] -**PrefixNsArray** | **List<int>** | | [optional] -**PrefixNsWrappedArray** | **List<int>** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs index 77f35e992a..1d46982928 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing AnotherFakeApi @@ -50,11 +50,10 @@ namespace Org.OpenAPITools.Test [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' AnotherFakeApi - //Assert.IsType(typeof(AnotherFakeApi), instance, "instance is a AnotherFakeApi"); + // TODO uncomment below to test 'IsType' AnotherFakeApi + //Assert.IsType(instance); } - /// /// Test Call123TestSpecialTags /// @@ -62,11 +61,9 @@ namespace Org.OpenAPITools.Test public void Call123TestSpecialTagsTest() { // TODO uncomment below to test the method and replace null with proper value - //ModelClient body = null; - //var response = instance.Call123TestSpecialTags(body); - //Assert.IsType (response, "response is ModelClient"); + //ModelClient modelClient = null; + //var response = instance.Call123TestSpecialTags(modelClient); + //Assert.IsType(response); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs index 76bc5dfdd6..5d048a005b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing DefaultApi @@ -50,11 +50,10 @@ namespace Org.OpenAPITools.Test [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' DefaultApi - //Assert.IsType(typeof(DefaultApi), instance, "instance is a DefaultApi"); + // TODO uncomment below to test 'IsType' DefaultApi + //Assert.IsType(instance); } - /// /// Test FooGet /// @@ -63,9 +62,7 @@ namespace Org.OpenAPITools.Test { // TODO uncomment below to test the method and replace null with proper value //var response = instance.FooGet(); - //Assert.IsType (response, "response is InlineResponseDefault"); + //Assert.IsType(response); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs index 50079e99c2..994cd46d38 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing FakeApi @@ -50,23 +50,21 @@ namespace Org.OpenAPITools.Test [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' FakeApi - //Assert.IsType(typeof(FakeApi), instance, "instance is a FakeApi"); + // TODO uncomment below to test 'IsType' FakeApi + //Assert.IsType(instance); } - /// - /// Test CreateXmlItem + /// Test FakeHealthGet /// [Fact] - public void CreateXmlItemTest() + public void FakeHealthGetTest() { // TODO uncomment below to test the method and replace null with proper value - //XmlItem xmlItem = null; - //instance.CreateXmlItem(xmlItem); - + //var response = instance.FakeHealthGet(); + //Assert.IsType(response); } - + /// /// Test FakeOuterBooleanSerialize /// @@ -76,9 +74,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //bool? body = null; //var response = instance.FakeOuterBooleanSerialize(body); - //Assert.IsType (response, "response is bool"); + //Assert.IsType(response); } - + /// /// Test FakeOuterCompositeSerialize /// @@ -86,11 +84,11 @@ namespace Org.OpenAPITools.Test public void FakeOuterCompositeSerializeTest() { // TODO uncomment below to test the method and replace null with proper value - //OuterComposite body = null; - //var response = instance.FakeOuterCompositeSerialize(body); - //Assert.IsType (response, "response is OuterComposite"); + //OuterComposite outerComposite = null; + //var response = instance.FakeOuterCompositeSerialize(outerComposite); + //Assert.IsType(response); } - + /// /// Test FakeOuterNumberSerialize /// @@ -100,9 +98,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //decimal? body = null; //var response = instance.FakeOuterNumberSerialize(body); - //Assert.IsType (response, "response is decimal"); + //Assert.IsType(response); } - + /// /// Test FakeOuterStringSerialize /// @@ -112,9 +110,20 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //string body = null; //var response = instance.FakeOuterStringSerialize(body); - //Assert.IsType (response, "response is string"); + //Assert.IsType(response); } - + + /// + /// Test GetArrayOfEnums + /// + [Fact] + public void GetArrayOfEnumsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.GetArrayOfEnums(); + //Assert.IsType>(response); + } + /// /// Test TestBodyWithFileSchema /// @@ -122,11 +131,10 @@ namespace Org.OpenAPITools.Test public void TestBodyWithFileSchemaTest() { // TODO uncomment below to test the method and replace null with proper value - //FileSchemaTestClass body = null; - //instance.TestBodyWithFileSchema(body); - + //FileSchemaTestClass fileSchemaTestClass = null; + //instance.TestBodyWithFileSchema(fileSchemaTestClass); } - + /// /// Test TestBodyWithQueryParams /// @@ -135,11 +143,10 @@ namespace Org.OpenAPITools.Test { // TODO uncomment below to test the method and replace null with proper value //string query = null; - //User body = null; - //instance.TestBodyWithQueryParams(query, body); - + //User user = null; + //instance.TestBodyWithQueryParams(query, user); } - + /// /// Test TestClientModel /// @@ -147,11 +154,11 @@ namespace Org.OpenAPITools.Test public void TestClientModelTest() { // TODO uncomment below to test the method and replace null with proper value - //ModelClient body = null; - //var response = instance.TestClientModel(body); - //Assert.IsType (response, "response is ModelClient"); + //ModelClient modelClient = null; + //var response = instance.TestClientModel(modelClient); + //Assert.IsType(response); } - + /// /// Test TestEndpointParameters /// @@ -174,9 +181,8 @@ namespace Org.OpenAPITools.Test //string password = null; //string callback = null; //instance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); - } - + /// /// Test TestEnumParameters /// @@ -193,9 +199,8 @@ namespace Org.OpenAPITools.Test //List enumFormStringArray = null; //string enumFormString = null; //instance.TestEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); - } - + /// /// Test TestGroupParameters /// @@ -210,9 +215,8 @@ namespace Org.OpenAPITools.Test //bool? booleanGroup = null; //long? int64Group = null; //instance.TestGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); - } - + /// /// Test TestInlineAdditionalProperties /// @@ -220,11 +224,10 @@ namespace Org.OpenAPITools.Test public void TestInlineAdditionalPropertiesTest() { // TODO uncomment below to test the method and replace null with proper value - //Dictionary param = null; - //instance.TestInlineAdditionalProperties(param); - + //Dictionary requestBody = null; + //instance.TestInlineAdditionalProperties(requestBody); } - + /// /// Test TestJsonFormData /// @@ -235,9 +238,21 @@ namespace Org.OpenAPITools.Test //string param = null; //string param2 = null; //instance.TestJsonFormData(param, param2); - } - - } + /// + /// Test TestQueryParameterCollectionFormat + /// + [Fact] + public void TestQueryParameterCollectionFormatTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List pipe = null; + //List ioutil = null; + //List http = null; + //List url = null; + //List context = null; + //instance.TestQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + } + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs index 647a66e310..bbfd4a586e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing FakeClassnameTags123Api @@ -50,11 +50,10 @@ namespace Org.OpenAPITools.Test [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' FakeClassnameTags123Api - //Assert.IsType(typeof(FakeClassnameTags123Api), instance, "instance is a FakeClassnameTags123Api"); + // TODO uncomment below to test 'IsType' FakeClassnameTags123Api + //Assert.IsType(instance); } - /// /// Test TestClassname /// @@ -62,11 +61,9 @@ namespace Org.OpenAPITools.Test public void TestClassnameTest() { // TODO uncomment below to test the method and replace null with proper value - //ModelClient body = null; - //var response = instance.TestClassname(body); - //Assert.IsType (response, "response is ModelClient"); + //ModelClient modelClient = null; + //var response = instance.TestClassname(modelClient); + //Assert.IsType(response); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/PetApiTests.cs index bb77b50512..6738676414 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/PetApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/PetApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing PetApi @@ -50,11 +50,10 @@ namespace Org.OpenAPITools.Test [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' PetApi - //Assert.IsType(typeof(PetApi), instance, "instance is a PetApi"); + // TODO uncomment below to test 'IsType' PetApi + //Assert.IsType(instance); } - /// /// Test AddPet /// @@ -62,11 +61,10 @@ namespace Org.OpenAPITools.Test public void AddPetTest() { // TODO uncomment below to test the method and replace null with proper value - //Pet body = null; - //instance.AddPet(body); - + //Pet pet = null; + //instance.AddPet(pet); } - + /// /// Test DeletePet /// @@ -77,9 +75,8 @@ namespace Org.OpenAPITools.Test //long petId = null; //string apiKey = null; //instance.DeletePet(petId, apiKey); - } - + /// /// Test FindPetsByStatus /// @@ -89,9 +86,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //List status = null; //var response = instance.FindPetsByStatus(status); - //Assert.IsType> (response, "response is List"); + //Assert.IsType>(response); } - + /// /// Test FindPetsByTags /// @@ -101,9 +98,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //List tags = null; //var response = instance.FindPetsByTags(tags); - //Assert.IsType> (response, "response is List"); + //Assert.IsType>(response); } - + /// /// Test GetPetById /// @@ -113,9 +110,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //long petId = null; //var response = instance.GetPetById(petId); - //Assert.IsType (response, "response is Pet"); + //Assert.IsType(response); } - + /// /// Test UpdatePet /// @@ -123,11 +120,10 @@ namespace Org.OpenAPITools.Test public void UpdatePetTest() { // TODO uncomment below to test the method and replace null with proper value - //Pet body = null; - //instance.UpdatePet(body); - + //Pet pet = null; + //instance.UpdatePet(pet); } - + /// /// Test UpdatePetWithForm /// @@ -139,9 +135,8 @@ namespace Org.OpenAPITools.Test //string name = null; //string status = null; //instance.UpdatePetWithForm(petId, name, status); - } - + /// /// Test UploadFile /// @@ -153,9 +148,9 @@ namespace Org.OpenAPITools.Test //string additionalMetadata = null; //System.IO.Stream file = null; //var response = instance.UploadFile(petId, additionalMetadata, file); - //Assert.IsType (response, "response is ApiResponse"); + //Assert.IsType(response); } - + /// /// Test UploadFileWithRequiredFile /// @@ -167,9 +162,7 @@ namespace Org.OpenAPITools.Test //System.IO.Stream requiredFile = null; //string additionalMetadata = null; //var response = instance.UploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); - //Assert.IsType (response, "response is ApiResponse"); + //Assert.IsType(response); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs index ac61d7e7c9..48e9f32748 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing StoreApi @@ -50,11 +50,10 @@ namespace Org.OpenAPITools.Test [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' StoreApi - //Assert.IsType(typeof(StoreApi), instance, "instance is a StoreApi"); + // TODO uncomment below to test 'IsType' StoreApi + //Assert.IsType(instance); } - /// /// Test DeleteOrder /// @@ -64,9 +63,8 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //string orderId = null; //instance.DeleteOrder(orderId); - } - + /// /// Test GetInventory /// @@ -75,9 +73,9 @@ namespace Org.OpenAPITools.Test { // TODO uncomment below to test the method and replace null with proper value //var response = instance.GetInventory(); - //Assert.IsType> (response, "response is Dictionary"); + //Assert.IsType>(response); } - + /// /// Test GetOrderById /// @@ -87,9 +85,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //long orderId = null; //var response = instance.GetOrderById(orderId); - //Assert.IsType (response, "response is Order"); + //Assert.IsType(response); } - + /// /// Test PlaceOrder /// @@ -97,11 +95,9 @@ namespace Org.OpenAPITools.Test public void PlaceOrderTest() { // TODO uncomment below to test the method and replace null with proper value - //Order body = null; - //var response = instance.PlaceOrder(body); - //Assert.IsType (response, "response is Order"); + //Order order = null; + //var response = instance.PlaceOrder(order); + //Assert.IsType(response); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/UserApiTests.cs index dfd9e7b340..792db5819a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/UserApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Api/UserApiTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -19,9 +18,10 @@ using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; +// uncomment below to import models +//using Org.OpenAPITools.Model; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Api { /// /// Class for testing UserApi @@ -50,11 +50,10 @@ namespace Org.OpenAPITools.Test [Fact] public void InstanceTest() { - // TODO uncomment below to test 'IsInstanceOfType' UserApi - //Assert.IsType(typeof(UserApi), instance, "instance is a UserApi"); + // TODO uncomment below to test 'IsType' UserApi + //Assert.IsType(instance); } - /// /// Test CreateUser /// @@ -62,11 +61,10 @@ namespace Org.OpenAPITools.Test public void CreateUserTest() { // TODO uncomment below to test the method and replace null with proper value - //User body = null; - //instance.CreateUser(body); - + //User user = null; + //instance.CreateUser(user); } - + /// /// Test CreateUsersWithArrayInput /// @@ -74,11 +72,10 @@ namespace Org.OpenAPITools.Test public void CreateUsersWithArrayInputTest() { // TODO uncomment below to test the method and replace null with proper value - //List body = null; - //instance.CreateUsersWithArrayInput(body); - + //List user = null; + //instance.CreateUsersWithArrayInput(user); } - + /// /// Test CreateUsersWithListInput /// @@ -86,11 +83,10 @@ namespace Org.OpenAPITools.Test public void CreateUsersWithListInputTest() { // TODO uncomment below to test the method and replace null with proper value - //List body = null; - //instance.CreateUsersWithListInput(body); - + //List user = null; + //instance.CreateUsersWithListInput(user); } - + /// /// Test DeleteUser /// @@ -100,9 +96,8 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //string username = null; //instance.DeleteUser(username); - } - + /// /// Test GetUserByName /// @@ -112,9 +107,9 @@ namespace Org.OpenAPITools.Test // TODO uncomment below to test the method and replace null with proper value //string username = null; //var response = instance.GetUserByName(username); - //Assert.IsType (response, "response is User"); + //Assert.IsType(response); } - + /// /// Test LoginUser /// @@ -125,9 +120,9 @@ namespace Org.OpenAPITools.Test //string username = null; //string password = null; //var response = instance.LoginUser(username, password); - //Assert.IsType (response, "response is string"); + //Assert.IsType(response); } - + /// /// Test LogoutUser /// @@ -136,9 +131,8 @@ namespace Org.OpenAPITools.Test { // TODO uncomment below to test the method and replace null with proper value //instance.LogoutUser(); - } - + /// /// Test UpdateUser /// @@ -147,11 +141,8 @@ namespace Org.OpenAPITools.Test { // TODO uncomment below to test the method and replace null with proper value //string username = null; - //User body = null; - //instance.UpdateUser(username, body); - + //User user = null; + //instance.UpdateUser(username, user); } - } - } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesAnyTypeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesAnyTypeTests.cs deleted file mode 100644 index 80e2d42cf5..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesAnyTypeTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesAnyType - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesAnyTypeTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesAnyType - //private AdditionalPropertiesAnyType instance; - - public AdditionalPropertiesAnyTypeTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesAnyType - //instance = new AdditionalPropertiesAnyType(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesAnyType - /// - [Fact] - public void AdditionalPropertiesAnyTypeInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesAnyType - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesAnyType"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesArrayTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesArrayTests.cs deleted file mode 100644 index 21adc82df4..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesArrayTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesArray - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesArrayTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesArray - //private AdditionalPropertiesArray instance; - - public AdditionalPropertiesArrayTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesArray - //instance = new AdditionalPropertiesArray(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesArray - /// - [Fact] - public void AdditionalPropertiesArrayInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesArray - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesArray"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesBooleanTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesBooleanTests.cs deleted file mode 100644 index 61505893ed..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesBooleanTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesBoolean - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesBooleanTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesBoolean - //private AdditionalPropertiesBoolean instance; - - public AdditionalPropertiesBooleanTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesBoolean - //instance = new AdditionalPropertiesBoolean(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesBoolean - /// - [Fact] - public void AdditionalPropertiesBooleanInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesBoolean - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesBoolean"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs index 2c07d9ce2e..9ab029ed09 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing AdditionalPropertiesClass @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void AdditionalPropertiesClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesClass - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesClass"); + // TODO uncomment below to test "IsType" AdditionalPropertiesClass + //Assert.IsType(instance); } @@ -73,6 +72,54 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'MapOfMapProperty' } + /// + /// Test the property 'Anytype1' + /// + [Fact] + public void Anytype1Test() + { + // TODO unit test for the property 'Anytype1' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype1' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype1Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype1' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype2' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype2Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype2' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype3' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype3Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3' + } + /// + /// Test the property 'EmptyMap' + /// + [Fact] + public void EmptyMapTest() + { + // TODO unit test for the property 'EmptyMap' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesString' + /// + [Fact] + public void MapWithUndeclaredPropertiesStringTest() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesString' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesIntegerTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesIntegerTests.cs deleted file mode 100644 index 45de798b24..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesIntegerTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesInteger - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesIntegerTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesInteger - //private AdditionalPropertiesInteger instance; - - public AdditionalPropertiesIntegerTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesInteger - //instance = new AdditionalPropertiesInteger(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesInteger - /// - [Fact] - public void AdditionalPropertiesIntegerInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesInteger - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesInteger"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesNumberTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesNumberTests.cs deleted file mode 100644 index 5a4b8eb3ea..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesNumberTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesNumber - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesNumberTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesNumber - //private AdditionalPropertiesNumber instance; - - public AdditionalPropertiesNumberTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesNumber - //instance = new AdditionalPropertiesNumber(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesNumber - /// - [Fact] - public void AdditionalPropertiesNumberInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesNumber - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesNumber"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesObjectTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesObjectTests.cs deleted file mode 100644 index b4410816ce..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesObjectTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesObject - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesObjectTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesObject - //private AdditionalPropertiesObject instance; - - public AdditionalPropertiesObjectTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesObject - //instance = new AdditionalPropertiesObject(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesObject - /// - [Fact] - public void AdditionalPropertiesObjectInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesObject - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesObject"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesStringTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesStringTests.cs deleted file mode 100644 index 897ddaefc5..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesStringTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing AdditionalPropertiesString - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class AdditionalPropertiesStringTests : IDisposable - { - // TODO uncomment below to declare an instance variable for AdditionalPropertiesString - //private AdditionalPropertiesString instance; - - public AdditionalPropertiesStringTests() - { - // TODO uncomment below to create an instance of AdditionalPropertiesString - //instance = new AdditionalPropertiesString(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of AdditionalPropertiesString - /// - [Fact] - public void AdditionalPropertiesStringInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" AdditionalPropertiesString - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AdditionalPropertiesString"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AnimalTests.cs index a7109a5788..ced34a4faa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Animal @@ -52,19 +51,10 @@ namespace Org.OpenAPITools.Test [Fact] public void AnimalInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Animal - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Animal"); + // TODO uncomment below to test "IsType" Animal + //Assert.IsType(instance); } - /// - /// Test deserialize a Dog from type Animal - /// - [Fact] - public void DogDeserializeFromAnimalTest() - { - // TODO uncomment below to test deserialize a Dog from type Animal - //Assert.IsInstanceOf(JsonConvert.DeserializeObject(new Dog().ToJson())); - } /// /// Test deserialize a Cat from type Animal /// @@ -72,7 +62,16 @@ namespace Org.OpenAPITools.Test public void CatDeserializeFromAnimalTest() { // TODO uncomment below to test deserialize a Cat from type Animal - //Assert.IsInstanceOf(JsonConvert.DeserializeObject(new Cat().ToJson())); + //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); + } + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs index de50416f94..2a2e098e60 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ApiResponse @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ApiResponseInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ApiResponse - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ApiResponse"); + // TODO uncomment below to test "IsType" ApiResponse + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs index 1e8e0efe11..f945f65936 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing AppleReq @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void AppleReqInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" AppleReq - //Assert.IsInstanceOfType (instance, "variable 'instance' is a AppleReq"); + // TODO uncomment below to test "IsType" AppleReq + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AppleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AppleTests.cs index 69b870d3e2..468d60184a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AppleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/AppleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Apple @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void AppleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Apple - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Apple"); + // TODO uncomment below to test "IsType" Apple + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs index 646f03444d..0b259d7d39 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ArrayOfArrayOfNumberOnly @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ArrayOfArrayOfNumberOnlyInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ArrayOfArrayOfNumberOnly - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ArrayOfArrayOfNumberOnly"); + // TODO uncomment below to test "IsType" ArrayOfArrayOfNumberOnly + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs index 3fcab83fc8..27f312ad25 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ArrayOfNumberOnly @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ArrayOfNumberOnlyInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ArrayOfNumberOnly - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ArrayOfNumberOnly"); + // TODO uncomment below to test "IsType" ArrayOfNumberOnly + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs index d14287a525..a433e8c87c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ArrayTest @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ArrayTestInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ArrayTest - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ArrayTest"); + // TODO uncomment below to test "IsType" ArrayTest + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs index 8465dc3803..8a6eeb82ee 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing BananaReq @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void BananaReqInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" BananaReq - //Assert.IsInstanceOfType (instance, "variable 'instance' is a BananaReq"); + // TODO uncomment below to test "IsType" BananaReq + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BananaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BananaTests.cs index 24ac647049..8d8cc376b0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BananaTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BananaTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Banana @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void BananaInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Banana - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Banana"); + // TODO uncomment below to test "IsType" Banana + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs index 561a829029..3cdccaa759 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing BasquePig @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void BasquePigInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" BasquePig - //Assert.IsInstanceOfType (instance, "variable 'instance' is a BasquePig"); + // TODO uncomment below to test "IsType" BasquePig + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BigCatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BigCatAllOfTests.cs deleted file mode 100644 index f1b24c7f8f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BigCatAllOfTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing BigCatAllOf - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class BigCatAllOfTests : IDisposable - { - // TODO uncomment below to declare an instance variable for BigCatAllOf - //private BigCatAllOf instance; - - public BigCatAllOfTests() - { - // TODO uncomment below to create an instance of BigCatAllOf - //instance = new BigCatAllOf(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of BigCatAllOf - /// - [Fact] - public void BigCatAllOfInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" BigCatAllOf - //Assert.IsInstanceOfType (instance, "variable 'instance' is a BigCatAllOf"); - } - - - /// - /// Test the property 'Kind' - /// - [Fact] - public void KindTest() - { - // TODO unit test for the property 'Kind' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BigCatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BigCatTests.cs deleted file mode 100644 index 4bda812119..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/BigCatTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing BigCat - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class BigCatTests : IDisposable - { - // TODO uncomment below to declare an instance variable for BigCat - //private BigCat instance; - - public BigCatTests() - { - // TODO uncomment below to create an instance of BigCat - //instance = new BigCat(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of BigCat - /// - [Fact] - public void BigCatInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" BigCat - //Assert.IsInstanceOfType (instance, "variable 'instance' is a BigCat"); - } - - - /// - /// Test the property 'Kind' - /// - [Fact] - public void KindTest() - { - // TODO unit test for the property 'Kind' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs index 006dbfb657..185c83666f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Capitalization @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void CapitalizationInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Capitalization - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Capitalization"); + // TODO uncomment below to test "IsType" Capitalization + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs index 68b84d01ba..fb51c28489 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing CatAllOf @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void CatAllOfInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" CatAllOf - //Assert.IsInstanceOfType (instance, "variable 'instance' is a CatAllOf"); + // TODO uncomment below to test "IsType" CatAllOf + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CatTests.cs index 466be23b55..701ba76028 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CatTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Cat @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void CatInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Cat - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Cat"); + // TODO uncomment below to test "IsType" Cat + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CategoryTests.cs index b7f7d7a8e9..6ce48e601e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CategoryTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/CategoryTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Category @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void CategoryInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Category - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Category"); + // TODO uncomment below to test "IsType" Category + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs index 99647a66d6..49a5393249 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ChildCatAllOf @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ChildCatAllOfInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ChildCatAllOf - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ChildCatAllOf"); + // TODO uncomment below to test "IsType" ChildCatAllOf + //Assert.IsType(instance); } @@ -64,6 +64,14 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'Name' } + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs index ea933f02e0..68566fd8d5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ChildCat @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ChildCatInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ChildCat - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ChildCat"); + // TODO uncomment below to test "IsType" ChildCat + //Assert.IsType(instance); } @@ -64,6 +64,14 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'Name' } + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs index ee76348d66..d29472e83a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ClassModel @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ClassModelInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ClassModel - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ClassModel"); + // TODO uncomment below to test "IsType" ClassModel + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs index 1ca093e7d1..b3529280c8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ComplexQuadrilateral @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ComplexQuadrilateralInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ComplexQuadrilateral - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ComplexQuadrilateral"); + // TODO uncomment below to test "IsType" ComplexQuadrilateral + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs index fd7376630f..572d9bffa7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing DanishPig @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void DanishPigInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" DanishPig - //Assert.IsInstanceOfType (instance, "variable 'instance' is a DanishPig"); + // TODO uncomment below to test "IsType" DanishPig + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs index 76905852d4..b22a444209 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing DogAllOf @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void DogAllOfInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" DogAllOf - //Assert.IsInstanceOfType (instance, "variable 'instance' is a DogAllOf"); + // TODO uncomment below to test "IsType" DogAllOf + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DogTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DogTests.cs index c3520c9cb5..992f93a51f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DogTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DogTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Dog @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void DogInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Dog - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Dog"); + // TODO uncomment below to test "IsType" Dog + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DrawingTests.cs index 8c0c605a5a..0709ad9eeb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DrawingTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Drawing @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void DrawingInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Drawing - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Drawing"); + // TODO uncomment below to test "IsType" Drawing + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs index a525a8908b..5779ca2947 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing EnumArrays @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void EnumArraysInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" EnumArrays - //Assert.IsInstanceOfType (instance, "variable 'instance' is a EnumArrays"); + // TODO uncomment below to test "IsType" EnumArrays + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs index 14a9b8174e..a17738c5cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing EnumClass @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void EnumClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" EnumClass - //Assert.IsInstanceOfType (instance, "variable 'instance' is a EnumClass"); + // TODO uncomment below to test "IsType" EnumClass + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index 65695bc71f..4f81b845d4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing EnumTest @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void EnumTestInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" EnumTest - //Assert.IsInstanceOfType (instance, "variable 'instance' is a EnumTest"); + // TODO uncomment below to test "IsType" EnumTest + //Assert.IsType(instance); } @@ -82,6 +81,14 @@ namespace Org.OpenAPITools.Test // TODO unit test for the property 'EnumInteger' } /// + /// Test the property 'EnumIntegerOnly' + /// + [Fact] + public void EnumIntegerOnlyTest() + { + // TODO unit test for the property 'EnumIntegerOnly' + } + /// /// Test the property 'EnumNumber' /// [Fact] @@ -97,6 +104,30 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'OuterEnum' } + /// + /// Test the property 'OuterEnumInteger' + /// + [Fact] + public void OuterEnumIntegerTest() + { + // TODO unit test for the property 'OuterEnumInteger' + } + /// + /// Test the property 'OuterEnumDefaultValue' + /// + [Fact] + public void OuterEnumDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumDefaultValue' + } + /// + /// Test the property 'OuterEnumIntegerDefaultValue' + /// + [Fact] + public void OuterEnumIntegerDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumIntegerDefaultValue' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs index e3062e1ed4..4663cb667d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing EquilateralTriangle @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void EquilateralTriangleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" EquilateralTriangle - //Assert.IsInstanceOfType (instance, "variable 'instance' is a EquilateralTriangle"); + // TODO uncomment below to test "IsType" EquilateralTriangle + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs index cc0f3dcefe..9f45b4fe89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing FileSchemaTestClass @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void FileSchemaTestClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" FileSchemaTestClass - //Assert.IsInstanceOfType (instance, "variable 'instance' is a FileSchemaTestClass"); + // TODO uncomment below to test "IsType" FileSchemaTestClass + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FileTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FileTests.cs index ed014dd754..761bb72a84 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FileTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FileTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing File @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void FileInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" File - //Assert.IsInstanceOfType (instance, "variable 'instance' is a File"); + // TODO uncomment below to test "IsType" File + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FooTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FooTests.cs index 87c424c85b..0b6ed52edb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FooTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FooTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Foo @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void FooInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Foo - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Foo"); + // TODO uncomment below to test "IsType" Foo + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs index 169d4277d6..97332800e9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing FormatTest @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void FormatTestInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" FormatTest - //Assert.IsInstanceOfType (instance, "variable 'instance' is a FormatTest"); + // TODO uncomment below to test "IsType" FormatTest + //Assert.IsType(instance); } @@ -106,6 +105,14 @@ namespace Org.OpenAPITools.Test // TODO unit test for the property 'Double' } /// + /// Test the property 'Decimal' + /// + [Fact] + public void DecimalTest() + { + // TODO unit test for the property 'Decimal' + } + /// /// Test the property 'String' /// [Fact] @@ -161,6 +168,22 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'Password' } + /// + /// Test the property 'PatternWithDigits' + /// + [Fact] + public void PatternWithDigitsTest() + { + // TODO unit test for the property 'PatternWithDigits' + } + /// + /// Test the property 'PatternWithDigitsAndDelimiter' + /// + [Fact] + public void PatternWithDigitsAndDelimiterTest() + { + // TODO unit test for the property 'PatternWithDigitsAndDelimiter' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs index 1a6d408780..5ea9e3ffc1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing FruitReq @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void FruitReqInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" FruitReq - //Assert.IsInstanceOfType (instance, "variable 'instance' is a FruitReq"); + // TODO uncomment below to test "IsType" FruitReq + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FruitTests.cs index b1bc9f600d..91e069bb42 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/FruitTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Fruit @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void FruitInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Fruit - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Fruit"); + // TODO uncomment below to test "IsType" Fruit + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs index a1bba753a5..08fb0e07a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing GmFruit @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void GmFruitInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" GmFruit - //Assert.IsInstanceOfType (instance, "variable 'instance' is a GmFruit"); + // TODO uncomment below to test "IsType" GmFruit + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs index fd9552c597..faa4930944 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing GrandparentAnimal @@ -51,19 +51,10 @@ namespace Org.OpenAPITools.Test [Fact] public void GrandparentAnimalInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" GrandparentAnimal - //Assert.IsInstanceOfType (instance, "variable 'instance' is a GrandparentAnimal"); + // TODO uncomment below to test "IsType" GrandparentAnimal + //Assert.IsType(instance); } - /// - /// Test deserialize a ParentPet from type GrandparentAnimal - /// - [Fact] - public void ParentPetDeserializeFromGrandparentAnimalTest() - { - // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal - //Assert.IsInstanceOf(JsonConvert.DeserializeObject(new ParentPet().ToJson())); - } /// /// Test deserialize a ChildCat from type ParentPet /// @@ -71,7 +62,16 @@ namespace Org.OpenAPITools.Test public void ChildCatDeserializeFromParentPetTest() { // TODO uncomment below to test deserialize a ChildCat from type ParentPet - //Assert.IsInstanceOf(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs index 45cf05b3c7..651a9f0ce3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing HasOnlyReadOnly @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void HasOnlyReadOnlyInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" HasOnlyReadOnly - //Assert.IsInstanceOfType (instance, "variable 'instance' is a HasOnlyReadOnly"); + // TODO uncomment below to test "IsType" HasOnlyReadOnly + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs index d9986a9d83..857190a333 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing HealthCheckResult @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void HealthCheckResultInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" HealthCheckResult - //Assert.IsInstanceOfType (instance, "variable 'instance' is a HealthCheckResult"); + // TODO uncomment below to test "IsType" HealthCheckResult + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs deleted file mode 100644 index d1e0f45aa3..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject1Tests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject1 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject1Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject1 - //private InlineObject1 instance; - - public InlineObject1Tests() - { - // TODO uncomment below to create an instance of InlineObject1 - //instance = new InlineObject1(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject1 - /// - [Fact] - public void InlineObject1InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject1 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject1"); - } - - - /// - /// Test the property 'AdditionalMetadata' - /// - [Fact] - public void AdditionalMetadataTest() - { - // TODO unit test for the property 'AdditionalMetadata' - } - /// - /// Test the property 'File' - /// - [Fact] - public void FileTest() - { - // TODO unit test for the property 'File' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs deleted file mode 100644 index 8e2c754e28..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject2Tests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject2 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject2Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject2 - //private InlineObject2 instance; - - public InlineObject2Tests() - { - // TODO uncomment below to create an instance of InlineObject2 - //instance = new InlineObject2(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject2 - /// - [Fact] - public void InlineObject2InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject2 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject2"); - } - - - /// - /// Test the property 'EnumFormStringArray' - /// - [Fact] - public void EnumFormStringArrayTest() - { - // TODO unit test for the property 'EnumFormStringArray' - } - /// - /// Test the property 'EnumFormString' - /// - [Fact] - public void EnumFormStringTest() - { - // TODO unit test for the property 'EnumFormString' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject3Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject3Tests.cs deleted file mode 100644 index 6f74ebdf63..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject3Tests.cs +++ /dev/null @@ -1,175 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject3 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject3Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject3 - //private InlineObject3 instance; - - public InlineObject3Tests() - { - // TODO uncomment below to create an instance of InlineObject3 - //instance = new InlineObject3(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject3 - /// - [Fact] - public void InlineObject3InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject3 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject3"); - } - - - /// - /// Test the property 'Integer' - /// - [Fact] - public void IntegerTest() - { - // TODO unit test for the property 'Integer' - } - /// - /// Test the property 'Int32' - /// - [Fact] - public void Int32Test() - { - // TODO unit test for the property 'Int32' - } - /// - /// Test the property 'Int64' - /// - [Fact] - public void Int64Test() - { - // TODO unit test for the property 'Int64' - } - /// - /// Test the property 'Number' - /// - [Fact] - public void NumberTest() - { - // TODO unit test for the property 'Number' - } - /// - /// Test the property 'Float' - /// - [Fact] - public void FloatTest() - { - // TODO unit test for the property 'Float' - } - /// - /// Test the property 'Double' - /// - [Fact] - public void DoubleTest() - { - // TODO unit test for the property 'Double' - } - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - /// - /// Test the property 'PatternWithoutDelimiter' - /// - [Fact] - public void PatternWithoutDelimiterTest() - { - // TODO unit test for the property 'PatternWithoutDelimiter' - } - /// - /// Test the property 'Byte' - /// - [Fact] - public void ByteTest() - { - // TODO unit test for the property 'Byte' - } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// - /// Test the property 'Date' - /// - [Fact] - public void DateTest() - { - // TODO unit test for the property 'Date' - } - /// - /// Test the property 'DateTime' - /// - [Fact] - public void DateTimeTest() - { - // TODO unit test for the property 'DateTime' - } - /// - /// Test the property 'Password' - /// - [Fact] - public void PasswordTest() - { - // TODO unit test for the property 'Password' - } - /// - /// Test the property 'Callback' - /// - [Fact] - public void CallbackTest() - { - // TODO unit test for the property 'Callback' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject4Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject4Tests.cs deleted file mode 100644 index c3702936bc..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject4Tests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject4 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject4Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject4 - //private InlineObject4 instance; - - public InlineObject4Tests() - { - // TODO uncomment below to create an instance of InlineObject4 - //instance = new InlineObject4(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject4 - /// - [Fact] - public void InlineObject4InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject4 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject4"); - } - - - /// - /// Test the property 'Param' - /// - [Fact] - public void ParamTest() - { - // TODO unit test for the property 'Param' - } - /// - /// Test the property 'Param2' - /// - [Fact] - public void Param2Test() - { - // TODO unit test for the property 'Param2' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject5Tests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject5Tests.cs deleted file mode 100644 index d0bb987e46..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObject5Tests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject5 - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObject5Tests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject5 - //private InlineObject5 instance; - - public InlineObject5Tests() - { - // TODO uncomment below to create an instance of InlineObject5 - //instance = new InlineObject5(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject5 - /// - [Fact] - public void InlineObject5InstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject5 - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject5"); - } - - - /// - /// Test the property 'AdditionalMetadata' - /// - [Fact] - public void AdditionalMetadataTest() - { - // TODO unit test for the property 'AdditionalMetadata' - } - /// - /// Test the property 'RequiredFile' - /// - [Fact] - public void RequiredFileTest() - { - // TODO unit test for the property 'RequiredFile' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs deleted file mode 100644 index ec9a5708f2..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineObjectTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineObject - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineObjectTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineObject - //private InlineObject instance; - - public InlineObjectTests() - { - // TODO uncomment below to create an instance of InlineObject - //instance = new InlineObject(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineObject - /// - [Fact] - public void InlineObjectInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineObject - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineObject"); - } - - - /// - /// Test the property 'Name' - /// - [Fact] - public void NameTest() - { - // TODO unit test for the property 'Name' - } - /// - /// Test the property 'Status' - /// - [Fact] - public void StatusTest() - { - // TODO unit test for the property 'Status' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs deleted file mode 100644 index 5c20d30a69..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing InlineResponseDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class InlineResponseDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for InlineResponseDefault - //private InlineResponseDefault instance; - - public InlineResponseDefaultTests() - { - // TODO uncomment below to create an instance of InlineResponseDefault - //instance = new InlineResponseDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of InlineResponseDefault - /// - [Fact] - public void InlineResponseDefaultInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" InlineResponseDefault - //Assert.IsInstanceOfType (instance, "variable 'instance' is a InlineResponseDefault"); - } - - - /// - /// Test the property 'String' - /// - [Fact] - public void StringTest() - { - // TODO unit test for the property 'String' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs index 00d5d08cc5..755c417cc5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing IsoscelesTriangle @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void IsoscelesTriangleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" IsoscelesTriangle - //Assert.IsInstanceOfType (instance, "variable 'instance' is a IsoscelesTriangle"); + // TODO uncomment below to test "IsType" IsoscelesTriangle + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ListTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ListTests.cs index b779b3b13f..2ed828d052 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ListTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ListTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing List @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ListInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" List - //Assert.IsInstanceOfType (instance, "variable 'instance' is a List"); + // TODO uncomment below to test "IsType" List + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MammalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MammalTests.cs index 76466113c5..7b46cbf064 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MammalTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MammalTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Mammal @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void MammalInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Mammal - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Mammal"); + // TODO uncomment below to test "IsType" Mammal + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MapTestTests.cs index 2b6c365c39..20036e1c90 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MapTestTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MapTestTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing MapTest @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void MapTestInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" MapTest - //Assert.IsInstanceOfType (instance, "variable 'instance' is a MapTest"); + // TODO uncomment below to test "IsType" MapTest + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs index 61cd08e2d8..f56cd715f4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing MixedPropertiesAndAdditionalPropertiesClass @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void MixedPropertiesAndAdditionalPropertiesClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" MixedPropertiesAndAdditionalPropertiesClass - //Assert.IsInstanceOfType (instance, "variable 'instance' is a MixedPropertiesAndAdditionalPropertiesClass"); + // TODO uncomment below to test "IsType" MixedPropertiesAndAdditionalPropertiesClass + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs index 3af4348b64..e25478618f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Model200Response @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void Model200ResponseInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Model200Response - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Model200Response"); + // TODO uncomment below to test "IsType" Model200Response + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs index b4644ef02b..24a9e26315 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ModelClient @@ -52,18 +51,18 @@ namespace Org.OpenAPITools.Test [Fact] public void ModelClientInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ModelClient - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ModelClient"); + // TODO uncomment below to test "IsType" ModelClient + //Assert.IsType(instance); } /// - /// Test the property '__Client' + /// Test the property '_Client' /// [Fact] - public void __ClientTest() + public void _ClientTest() { - // TODO unit test for the property '__Client' + // TODO unit test for the property '_Client' } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NameTests.cs index 940465046c..c390049e66 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NameTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Name @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void NameInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Name - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Name"); + // TODO uncomment below to test "IsType" Name + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs index d1c6b14343..8f00505612 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing NullableClass @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void NullableClassInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" NullableClass - //Assert.IsInstanceOfType (instance, "variable 'instance' is a NullableClass"); + // TODO uncomment below to test "IsType" NullableClass + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs index b663af5b6e..5662f91d6e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing NullableShape @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void NullableShapeInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" NullableShape - //Assert.IsInstanceOfType (instance, "variable 'instance' is a NullableShape"); + // TODO uncomment below to test "IsType" NullableShape + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs index b166001e80..3a06cb020b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing NumberOnly @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void NumberOnlyInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" NumberOnly - //Assert.IsInstanceOfType (instance, "variable 'instance' is a NumberOnly"); + // TODO uncomment below to test "IsType" NumberOnly + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OrderTests.cs index 43e1c8371c..cf5c561c54 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Order @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OrderInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Order - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Order"); + // TODO uncomment below to test "IsType" Order + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs index 0b6b81edeb..2efda0db59 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterComposite @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OuterCompositeInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterComposite - //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterComposite"); + // TODO uncomment below to test "IsType" OuterComposite + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs index 9c77453021..986fff774c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterEnumDefaultValue @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OuterEnumDefaultValueInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterEnumDefaultValue - //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnumDefaultValue"); + // TODO uncomment below to test "IsType" OuterEnumDefaultValue + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs index d797bc954c..015d5dab94 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterEnumIntegerDefaultValue @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OuterEnumIntegerDefaultValueInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterEnumIntegerDefaultValue - //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnumIntegerDefaultValue"); + // TODO uncomment below to test "IsType" OuterEnumIntegerDefaultValue + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs index acd34b46be..385e899110 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterEnumInteger @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OuterEnumIntegerInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterEnumInteger - //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnumInteger"); + // TODO uncomment below to test "IsType" OuterEnumInteger + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs index 6fc33f0d80..f47304767b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing OuterEnum @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void OuterEnumInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" OuterEnum - //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnum"); + // TODO uncomment below to test "IsType" OuterEnum + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs index 76db9ecf3a..1e17568ed3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ParentPet @@ -51,10 +51,19 @@ namespace Org.OpenAPITools.Test [Fact] public void ParentPetInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ParentPet - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ParentPet"); + // TODO uncomment below to test "IsType" ParentPet + //Assert.IsType(instance); } + /// + /// Test deserialize a ChildCat from type ParentPet + /// + [Fact] + public void ChildCatDeserializeFromParentPetTest() + { + // TODO uncomment below to test deserialize a ChildCat from type ParentPet + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/PetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/PetTests.cs index 69ee044f53..154e66f8df 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Pet @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void PetInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Pet - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Pet"); + // TODO uncomment below to test "IsType" Pet + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/PigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/PigTests.cs index 7497d47b78..55cf218904 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/PigTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/PigTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Pig @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void PigInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Pig - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Pig"); + // TODO uncomment below to test "IsType" Pig + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs index 09b365a5f1..6eef9f4c81 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing QuadrilateralInterface @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void QuadrilateralInterfaceInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" QuadrilateralInterface - //Assert.IsInstanceOfType (instance, "variable 'instance' is a QuadrilateralInterface"); + // TODO uncomment below to test "IsType" QuadrilateralInterface + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs index fea00bcd6e..26826681a4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Quadrilateral @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void QuadrilateralInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Quadrilateral - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Quadrilateral"); + // TODO uncomment below to test "IsType" Quadrilateral + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs index eaf0f7cd4d..dc3d0fad54 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ReadOnlyFirst @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ReadOnlyFirstInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ReadOnlyFirst - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ReadOnlyFirst"); + // TODO uncomment below to test "IsType" ReadOnlyFirst + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ReturnTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ReturnTests.cs index cc0784b9b0..c8c1d6510d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ReturnTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ReturnTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Return @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ReturnInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Return - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Return"); + // TODO uncomment below to test "IsType" Return + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs index 5170070bf4..04cb9f1ab6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ScaleneTriangle @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ScaleneTriangleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ScaleneTriangle - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ScaleneTriangle"); + // TODO uncomment below to test "IsType" ScaleneTriangle + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs index 4ee56a550d..7bd0bc86f9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ShapeInterface @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ShapeInterfaceInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ShapeInterface - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ShapeInterface"); + // TODO uncomment below to test "IsType" ShapeInterface + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs index eb229415ae..d0af114157 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing ShapeOrNull @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ShapeOrNullInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" ShapeOrNull - //Assert.IsInstanceOfType (instance, "variable 'instance' is a ShapeOrNull"); + // TODO uncomment below to test "IsType" ShapeOrNull + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeTests.cs index d2c4f92462..b01bd531f8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ShapeTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Shape @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ShapeInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Shape - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Shape"); + // TODO uncomment below to test "IsType" Shape + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs index db78f9c542..6648e98092 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing SimpleQuadrilateral @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void SimpleQuadrilateralInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" SimpleQuadrilateral - //Assert.IsInstanceOfType (instance, "variable 'instance' is a SimpleQuadrilateral"); + // TODO uncomment below to test "IsType" SimpleQuadrilateral + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs index 3c078f18a4..0f0e1ff12a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing SpecialModelName @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void SpecialModelNameInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" SpecialModelName - //Assert.IsInstanceOfType (instance, "variable 'instance' is a SpecialModelName"); + // TODO uncomment below to test "IsType" SpecialModelName + //Assert.IsType(instance); } @@ -65,6 +64,14 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'SpecialPropertyName' } + /// + /// Test the property '_SpecialModelName' + /// + [Fact] + public void _SpecialModelNameTest() + { + // TODO unit test for the property '_SpecialModelName' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TagTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TagTests.cs index f724959535..6d56232d0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TagTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TagTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Tag @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void TagInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Tag - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Tag"); + // TODO uncomment below to test "IsType" Tag + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs index f75f2a14a6..fba65470be 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing TriangleInterface @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void TriangleInterfaceInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" TriangleInterface - //Assert.IsInstanceOfType (instance, "variable 'instance' is a TriangleInterface"); + // TODO uncomment below to test "IsType" TriangleInterface + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TriangleTests.cs index 2f3f3d284f..bdaab0b479 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TriangleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TriangleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Triangle @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void TriangleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Triangle - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Triangle"); + // TODO uncomment below to test "IsType" Triangle + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TypeHolderDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TypeHolderDefaultTests.cs deleted file mode 100644 index 06a678c0ef..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TypeHolderDefaultTests.cs +++ /dev/null @@ -1,103 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing TypeHolderDefault - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class TypeHolderDefaultTests : IDisposable - { - // TODO uncomment below to declare an instance variable for TypeHolderDefault - //private TypeHolderDefault instance; - - public TypeHolderDefaultTests() - { - // TODO uncomment below to create an instance of TypeHolderDefault - //instance = new TypeHolderDefault(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of TypeHolderDefault - /// - [Fact] - public void TypeHolderDefaultInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" TypeHolderDefault - //Assert.IsInstanceOfType (instance, "variable 'instance' is a TypeHolderDefault"); - } - - - /// - /// Test the property 'StringItem' - /// - [Fact] - public void StringItemTest() - { - // TODO unit test for the property 'StringItem' - } - /// - /// Test the property 'NumberItem' - /// - [Fact] - public void NumberItemTest() - { - // TODO unit test for the property 'NumberItem' - } - /// - /// Test the property 'IntegerItem' - /// - [Fact] - public void IntegerItemTest() - { - // TODO unit test for the property 'IntegerItem' - } - /// - /// Test the property 'BoolItem' - /// - [Fact] - public void BoolItemTest() - { - // TODO unit test for the property 'BoolItem' - } - /// - /// Test the property 'ArrayItem' - /// - [Fact] - public void ArrayItemTest() - { - // TODO unit test for the property 'ArrayItem' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TypeHolderExampleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TypeHolderExampleTests.cs deleted file mode 100644 index 0b48fb2c73..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/TypeHolderExampleTests.cs +++ /dev/null @@ -1,103 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing TypeHolderExample - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class TypeHolderExampleTests : IDisposable - { - // TODO uncomment below to declare an instance variable for TypeHolderExample - //private TypeHolderExample instance; - - public TypeHolderExampleTests() - { - // TODO uncomment below to create an instance of TypeHolderExample - //instance = new TypeHolderExample(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of TypeHolderExample - /// - [Fact] - public void TypeHolderExampleInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" TypeHolderExample - //Assert.IsInstanceOfType (instance, "variable 'instance' is a TypeHolderExample"); - } - - - /// - /// Test the property 'StringItem' - /// - [Fact] - public void StringItemTest() - { - // TODO unit test for the property 'StringItem' - } - /// - /// Test the property 'NumberItem' - /// - [Fact] - public void NumberItemTest() - { - // TODO unit test for the property 'NumberItem' - } - /// - /// Test the property 'IntegerItem' - /// - [Fact] - public void IntegerItemTest() - { - // TODO unit test for the property 'IntegerItem' - } - /// - /// Test the property 'BoolItem' - /// - [Fact] - public void BoolItemTest() - { - // TODO unit test for the property 'BoolItem' - } - /// - /// Test the property 'ArrayItem' - /// - [Fact] - public void ArrayItemTest() - { - // TODO unit test for the property 'ArrayItem' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/UserTests.cs index 9a86e5f0fa..a7b095e4c2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -1,10 +1,9 @@ -/* +/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 - * + * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -21,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing User @@ -52,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void UserInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" User - //Assert.IsInstanceOfType (instance, "variable 'instance' is a User"); + // TODO uncomment below to test "IsType" User + //Assert.IsType(instance); } @@ -121,6 +120,38 @@ namespace Org.OpenAPITools.Test { // TODO unit test for the property 'UserStatus' } + /// + /// Test the property 'ObjectWithNoDeclaredProps' + /// + [Fact] + public void ObjectWithNoDeclaredPropsTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredProps' + } + /// + /// Test the property 'ObjectWithNoDeclaredPropsNullable' + /// + [Fact] + public void ObjectWithNoDeclaredPropsNullableTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + } + /// + /// Test the property 'AnyTypeProp' + /// + [Fact] + public void AnyTypePropTest() + { + // TODO unit test for the property 'AnyTypeProp' + } + /// + /// Test the property 'AnyTypePropNullable' + /// + [Fact] + public void AnyTypePropNullableTest() + { + // TODO unit test for the property 'AnyTypePropNullable' + } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/WhaleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/WhaleTests.cs index d6d8d009a0..0961079194 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/WhaleTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/WhaleTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Whale @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void WhaleInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Whale - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Whale"); + // TODO uncomment below to test "IsType" Whale + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/XmlItemTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/XmlItemTests.cs deleted file mode 100644 index 2e14da3de2..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/XmlItemTests.cs +++ /dev/null @@ -1,295 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using Xunit; - -using System; -using System.Linq; -using System.IO; -using System.Collections.Generic; -using Org.OpenAPITools.Api; -using Org.OpenAPITools.Model; -using Org.OpenAPITools.Client; -using System.Reflection; -using Newtonsoft.Json; - -namespace Org.OpenAPITools.Test -{ - /// - /// Class for testing XmlItem - /// - /// - /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). - /// Please update the test case below to test the model. - /// - public class XmlItemTests : IDisposable - { - // TODO uncomment below to declare an instance variable for XmlItem - //private XmlItem instance; - - public XmlItemTests() - { - // TODO uncomment below to create an instance of XmlItem - //instance = new XmlItem(); - } - - public void Dispose() - { - // Cleanup when everything is done. - } - - /// - /// Test an instance of XmlItem - /// - [Fact] - public void XmlItemInstanceTest() - { - // TODO uncomment below to test "IsInstanceOfType" XmlItem - //Assert.IsInstanceOfType (instance, "variable 'instance' is a XmlItem"); - } - - - /// - /// Test the property 'AttributeString' - /// - [Fact] - public void AttributeStringTest() - { - // TODO unit test for the property 'AttributeString' - } - /// - /// Test the property 'AttributeNumber' - /// - [Fact] - public void AttributeNumberTest() - { - // TODO unit test for the property 'AttributeNumber' - } - /// - /// Test the property 'AttributeInteger' - /// - [Fact] - public void AttributeIntegerTest() - { - // TODO unit test for the property 'AttributeInteger' - } - /// - /// Test the property 'AttributeBoolean' - /// - [Fact] - public void AttributeBooleanTest() - { - // TODO unit test for the property 'AttributeBoolean' - } - /// - /// Test the property 'WrappedArray' - /// - [Fact] - public void WrappedArrayTest() - { - // TODO unit test for the property 'WrappedArray' - } - /// - /// Test the property 'NameString' - /// - [Fact] - public void NameStringTest() - { - // TODO unit test for the property 'NameString' - } - /// - /// Test the property 'NameNumber' - /// - [Fact] - public void NameNumberTest() - { - // TODO unit test for the property 'NameNumber' - } - /// - /// Test the property 'NameInteger' - /// - [Fact] - public void NameIntegerTest() - { - // TODO unit test for the property 'NameInteger' - } - /// - /// Test the property 'NameBoolean' - /// - [Fact] - public void NameBooleanTest() - { - // TODO unit test for the property 'NameBoolean' - } - /// - /// Test the property 'NameArray' - /// - [Fact] - public void NameArrayTest() - { - // TODO unit test for the property 'NameArray' - } - /// - /// Test the property 'NameWrappedArray' - /// - [Fact] - public void NameWrappedArrayTest() - { - // TODO unit test for the property 'NameWrappedArray' - } - /// - /// Test the property 'PrefixString' - /// - [Fact] - public void PrefixStringTest() - { - // TODO unit test for the property 'PrefixString' - } - /// - /// Test the property 'PrefixNumber' - /// - [Fact] - public void PrefixNumberTest() - { - // TODO unit test for the property 'PrefixNumber' - } - /// - /// Test the property 'PrefixInteger' - /// - [Fact] - public void PrefixIntegerTest() - { - // TODO unit test for the property 'PrefixInteger' - } - /// - /// Test the property 'PrefixBoolean' - /// - [Fact] - public void PrefixBooleanTest() - { - // TODO unit test for the property 'PrefixBoolean' - } - /// - /// Test the property 'PrefixArray' - /// - [Fact] - public void PrefixArrayTest() - { - // TODO unit test for the property 'PrefixArray' - } - /// - /// Test the property 'PrefixWrappedArray' - /// - [Fact] - public void PrefixWrappedArrayTest() - { - // TODO unit test for the property 'PrefixWrappedArray' - } - /// - /// Test the property 'NamespaceString' - /// - [Fact] - public void NamespaceStringTest() - { - // TODO unit test for the property 'NamespaceString' - } - /// - /// Test the property 'NamespaceNumber' - /// - [Fact] - public void NamespaceNumberTest() - { - // TODO unit test for the property 'NamespaceNumber' - } - /// - /// Test the property 'NamespaceInteger' - /// - [Fact] - public void NamespaceIntegerTest() - { - // TODO unit test for the property 'NamespaceInteger' - } - /// - /// Test the property 'NamespaceBoolean' - /// - [Fact] - public void NamespaceBooleanTest() - { - // TODO unit test for the property 'NamespaceBoolean' - } - /// - /// Test the property 'NamespaceArray' - /// - [Fact] - public void NamespaceArrayTest() - { - // TODO unit test for the property 'NamespaceArray' - } - /// - /// Test the property 'NamespaceWrappedArray' - /// - [Fact] - public void NamespaceWrappedArrayTest() - { - // TODO unit test for the property 'NamespaceWrappedArray' - } - /// - /// Test the property 'PrefixNsString' - /// - [Fact] - public void PrefixNsStringTest() - { - // TODO unit test for the property 'PrefixNsString' - } - /// - /// Test the property 'PrefixNsNumber' - /// - [Fact] - public void PrefixNsNumberTest() - { - // TODO unit test for the property 'PrefixNsNumber' - } - /// - /// Test the property 'PrefixNsInteger' - /// - [Fact] - public void PrefixNsIntegerTest() - { - // TODO unit test for the property 'PrefixNsInteger' - } - /// - /// Test the property 'PrefixNsBoolean' - /// - [Fact] - public void PrefixNsBooleanTest() - { - // TODO unit test for the property 'PrefixNsBoolean' - } - /// - /// Test the property 'PrefixNsArray' - /// - [Fact] - public void PrefixNsArrayTest() - { - // TODO unit test for the property 'PrefixNsArray' - } - /// - /// Test the property 'PrefixNsWrappedArray' - /// - [Fact] - public void PrefixNsWrappedArrayTest() - { - // TODO unit test for the property 'PrefixNsWrappedArray' - } - - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ZebraTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ZebraTests.cs index 84ebb849aa..f44e921314 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ZebraTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/ZebraTests.cs @@ -20,7 +20,7 @@ using Org.OpenAPITools.Client; using System.Reflection; using Newtonsoft.Json; -namespace Org.OpenAPITools.Test +namespace Org.OpenAPITools.Test.Model { /// /// Class for testing Zebra @@ -51,8 +51,8 @@ namespace Org.OpenAPITools.Test [Fact] public void ZebraInstanceTest() { - // TODO uncomment below to test "IsInstanceOfType" Zebra - //Assert.IsInstanceOfType (instance, "variable 'instance' is a Zebra"); + // TODO uncomment below to test "IsType" Zebra + //Assert.IsType(instance); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index e04c8df5fd..95d41fcbd9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs index ff7ce75367..bc5b5556d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs index 421f93ed04..5991b7f0b7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 6b66577525..dd74c66d15 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs index 125b0f5cb7..e8439eb125 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api @@ -674,9 +675,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -769,9 +780,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -844,9 +865,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -921,9 +952,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1015,9 +1056,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1111,9 +1162,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1207,9 +1268,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1305,9 +1376,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1542,9 +1623,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1637,9 +1728,19 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1719,9 +1820,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1803,9 +1914,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1887,9 +2008,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1973,9 +2104,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2061,9 +2202,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -2151,9 +2302,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs index 63403e7dcd..e01ed16258 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs index c37a6501c6..8efb827cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs index 70ac64f89a..660dcd3a05 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -25,18 +25,18 @@ using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; -using RestSharp.Deserializers; +using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { /// /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// - internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; @@ -82,7 +82,9 @@ namespace Org.OpenAPITools.Client } } - public T Deserialize(IRestResponse response) + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; @@ -94,7 +96,7 @@ namespace Org.OpenAPITools.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(IRestResponse response, Type type) + internal object Deserialize(RestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { @@ -147,15 +149,22 @@ namespace Org.OpenAPITools.Client } } - public string RootElement { get; set; } - public string Namespace { get; set; } - public string DateFormat { get; set; } + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } + + public DataFormat DataFormat => DataFormat.Json; } /// /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), @@ -186,14 +195,14 @@ namespace Org.OpenAPITools.Client /// Allows for extending request processing for generated code. /// /// The RestSharp request object - partial void InterceptRequest(IRestRequest request); + partial void InterceptRequest(RestRequest request); /// /// Allows for extending response processing for generated code. /// /// The RestSharp request object /// The RestSharp response object - partial void InterceptResponse(IRestRequest request, IRestResponse response); + partial void InterceptResponse(RestRequest request, RestResponse response); /// /// Initializes a new instance of the , defaulting to the global configurations' base url. @@ -228,25 +237,25 @@ namespace Org.OpenAPITools.Client switch (method) { case HttpMethod.Get: - other = RestSharpMethod.GET; + other = RestSharpMethod.Get; break; case HttpMethod.Post: - other = RestSharpMethod.POST; + other = RestSharpMethod.Post; break; case HttpMethod.Put: - other = RestSharpMethod.PUT; + other = RestSharpMethod.Put; break; case HttpMethod.Delete: - other = RestSharpMethod.DELETE; + other = RestSharpMethod.Delete; break; case HttpMethod.Head: - other = RestSharpMethod.HEAD; + other = RestSharpMethod.Head; break; case HttpMethod.Options: - other = RestSharpMethod.OPTIONS; + other = RestSharpMethod.Options; break; case HttpMethod.Patch: - other = RestSharpMethod.PATCH; + other = RestSharpMethod.Patch; break; default: throw new ArgumentOutOfRangeException("method", method, null); @@ -277,11 +286,7 @@ namespace Org.OpenAPITools.Client if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); - RestRequest request = new RestRequest(Method(method)) - { - Resource = path, - JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) - }; + RestRequest request = new RestRequest(path, Method(method)); if (options.PathParameters != null) { @@ -376,25 +381,17 @@ namespace Org.OpenAPITools.Client var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); else - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } } } - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - request.AddCookie(cookie.Name, cookie.Value); - } - } - return request; } - private ApiResponse ToApiResponse(IRestResponse response) + private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; string rawContent = response.Content; @@ -413,9 +410,17 @@ namespace Org.OpenAPITools.Client } } + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + if (response.Cookies != null) { - foreach (var responseCookies in response.Cookies) + foreach (var responseCookies in response.Cookies.Cast()) { transformed.Cookies.Add( new Cookie( @@ -433,54 +438,46 @@ namespace Org.OpenAPITools.Client private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else - { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } } - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.Proxy = configuration.Proxy; - } + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); - if (configuration.ClientCertificates != null) + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; @@ -516,6 +513,10 @@ namespace Org.OpenAPITools.Client { response.Data = (T)(object)response.RawBytes; } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } InterceptResponse(req, response); @@ -528,7 +529,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, @@ -557,54 +558,35 @@ namespace Org.OpenAPITools.Client private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); - } - - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) - { - client.Proxy = configuration.Proxy; - } - - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; @@ -645,7 +627,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs new file mode 100644 index 0000000000..8b0ba33499 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs @@ -0,0 +1,95 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : AuthenticatorBase + { + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) : base("") + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// Access token to create a parameter from. + /// An authentication parameter. + protected override async ValueTask GetAuthenticationParameter(string accessToken) + { + var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl) + .UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration)); + + var request = new RestRequest() + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + var response = await client.PostAsync(request); + return $"{response.TokenType} {response.AccessToken}"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs new file mode 100644 index 0000000000..e225740925 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs @@ -0,0 +1,27 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs new file mode 100644 index 0000000000..0a94e17e12 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Client.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs index dcc97c295e..e499a7728e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -120,6 +120,16 @@ namespace Org.OpenAPITools.Client return Convert.ToString(obj, CultureInfo.InvariantCulture); } + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + /// /// Encode string in base64 format. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Configuration.cs index 56e3a9d13e..526781f42c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Configuration.cs @@ -17,6 +17,8 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Net.Http; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -118,7 +120,7 @@ namespace Org.OpenAPITools.Client public Configuration() { Proxy = null; - UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); BasePath = "http://petstore.swagger.io:80/v2"; DefaultHeaders = new ConcurrentDictionary(); ApiKey = new ConcurrentDictionary(); @@ -366,6 +368,30 @@ namespace Org.OpenAPITools.Client /// The access token. public virtual string AccessToken { get; set; } + /// + /// Gets or sets the token URL for OAuth2 authentication. + /// + /// The OAuth Token URL. + public virtual string OAuthTokenUrl { get; set; } + + /// + /// Gets or sets the client ID for OAuth2 authentication. + /// + /// The OAuth Client ID. + public virtual string OAuthClientId { get; set; } + + /// + /// Gets or sets the client secret for OAuth2 authentication. + /// + /// The OAuth Client Secret. + public virtual string OAuthClientSecret { get; set; } + + /// + /// Gets or sets the flow for OAuth2 authentication. + /// + /// The OAuth Flow. + public virtual OAuthFlow? OAuthFlow { get; set; } + /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// @@ -689,6 +715,10 @@ namespace Org.OpenAPITools.Client Username = second.Username ?? first.Username, Password = second.Password ?? first.Password, AccessToken = second.AccessToken ?? first.AccessToken, + OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl, + OAuthClientId = second.OAuthClientId ?? first.OAuthClientId, + OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret, + OAuthFlow = second.OAuthFlow ?? first.OAuthFlow, HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 6a8f9c8dc0..0b3e867d0f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -325,14 +325,18 @@ namespace Org.OpenAPITools.Client /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { - if (!File.Exists(KeyFilePath)) + string keyStr = string.Empty; + if (File.Exists(KeyFilePath)) { - throw new Exception("key file path does not exist."); + keyStr = File.ReadAllText(KeyFilePath); + } + else + { + keyStr = KeyFilePath; } const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; - var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); var ecdsa = ECDsa.Create(); @@ -430,11 +434,15 @@ namespace Org.OpenAPITools.Client bool isPrivateKeyFile = true; byte[] pemkey = null; - if (!File.Exists(pemfile)) + string pemstr = string.Empty; + if (File.Exists(pemfile)) { - throw new Exception("private key file does not exist."); + pemstr = File.ReadAllText(pemfile).Trim(); + } + else + { + pemstr = pemfile; } - string pemstr = File.ReadAllText(pemfile).Trim(); if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) { @@ -725,9 +733,16 @@ namespace Org.OpenAPITools.Client /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { - if (!File.Exists(keyFilePath)) + string[] key = null; + + if (File.Exists(keyFilePath)) { - throw new Exception("Key file path does not exist."); + key = File.ReadAllLines(keyFilePath); + } + else + { + // The ApiKeyFilePath is passed as string + key = new string[] { keyFilePath }; } const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; @@ -737,7 +752,6 @@ namespace Org.OpenAPITools.Client //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; PrivateKeyType keyType; - var key = File.ReadAllLines(keyFilePath); if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) @@ -751,7 +765,7 @@ namespace Org.OpenAPITools.Client } else { - throw new Exception("Either the key is invalid or key is not supported"); + throw new Exception("The key file path does not exist or key is invalid or key is not supported"); } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IReadableConfiguration.cs index b99a151e5b..c9615dc5aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IReadableConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; using System.Net; using System.Security.Cryptography.X509Certificates; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client /// Access token. string AccessToken { get; } + /// + /// Gets the OAuth token URL. + /// + /// OAuth Token URL. + string OAuthTokenUrl { get; } + + /// + /// Gets the OAuth client ID. + /// + /// OAuth Client ID. + string OAuthClientId { get; } + + /// + /// Gets the OAuth client secret. + /// + /// OAuth Client Secret. + string OAuthClientSecret { get; } + + /// + /// Gets the OAuth flow. + /// + /// OAuth Flow. + OAuthFlow? OAuthFlow { get; } + /// /// Gets the API key. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RequestOptions.cs index 3932047e02..4c26cf69b2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client /// public Object Data { get; set; } + /// + /// If request should be authenticated with OAuth. + /// + public bool OAuth { get; set; } + /// /// Constructs a new instance of /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RetryConfiguration.cs index 91bc7cc6d5..7011f69e77 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RetryConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client /// /// Retry policy /// - public static Policy RetryPolicy { get; set; } + public static Policy RetryPolicy { get; set; } /// /// Async retry policy /// - public static AsyncPolicy AsyncRetryPolicy { get; set; } + public static AsyncPolicy AsyncRetryPolicy { get; set; } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesAnyType.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesAnyType.cs deleted file mode 100644 index fe9de3aa27..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesAnyType.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// AdditionalPropertiesAnyType - /// - [DataContract] - public partial class AdditionalPropertiesAnyType : Dictionary, IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// name. - public AdditionalPropertiesAnyType(string name = default(string)) : base() - { - this.Name = name; - } - - /// - /// Gets or Sets Name - /// - [DataMember(Name="name", EmitDefaultValue=false)] - public string Name { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class AdditionalPropertiesAnyType {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesAnyType).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesAnyType instances are equal - /// - /// Instance of AdditionalPropertiesAnyType to be compared - /// Boolean - public bool Equals(AdditionalPropertiesAnyType input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = base.GetHashCode(); - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesArray.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesArray.cs deleted file mode 100644 index 46e6973df0..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesArray.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// AdditionalPropertiesArray - /// - [DataContract] - public partial class AdditionalPropertiesArray : Dictionary, IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// name. - public AdditionalPropertiesArray(string name = default(string)) : base() - { - this.Name = name; - } - - /// - /// Gets or Sets Name - /// - [DataMember(Name="name", EmitDefaultValue=false)] - public string Name { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class AdditionalPropertiesArray {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesArray).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesArray instances are equal - /// - /// Instance of AdditionalPropertiesArray to be compared - /// Boolean - public bool Equals(AdditionalPropertiesArray input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = base.GetHashCode(); - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesBoolean.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesBoolean.cs deleted file mode 100644 index e21c5085ce..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesBoolean.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// AdditionalPropertiesBoolean - /// - [DataContract] - public partial class AdditionalPropertiesBoolean : Dictionary, IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// name. - public AdditionalPropertiesBoolean(string name = default(string)) : base() - { - this.Name = name; - } - - /// - /// Gets or Sets Name - /// - [DataMember(Name="name", EmitDefaultValue=false)] - public string Name { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class AdditionalPropertiesBoolean {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesBoolean).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesBoolean instances are equal - /// - /// Instance of AdditionalPropertiesBoolean to be compared - /// Boolean - public bool Equals(AdditionalPropertiesBoolean input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = base.GetHashCode(); - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesInteger.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesInteger.cs deleted file mode 100644 index ceff9d7354..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesInteger.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// AdditionalPropertiesInteger - /// - [DataContract] - public partial class AdditionalPropertiesInteger : Dictionary, IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// name. - public AdditionalPropertiesInteger(string name = default(string)) : base() - { - this.Name = name; - } - - /// - /// Gets or Sets Name - /// - [DataMember(Name="name", EmitDefaultValue=false)] - public string Name { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class AdditionalPropertiesInteger {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesInteger).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesInteger instances are equal - /// - /// Instance of AdditionalPropertiesInteger to be compared - /// Boolean - public bool Equals(AdditionalPropertiesInteger input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = base.GetHashCode(); - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesNumber.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesNumber.cs deleted file mode 100644 index db37cf7ce6..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesNumber.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// AdditionalPropertiesNumber - /// - [DataContract] - public partial class AdditionalPropertiesNumber : Dictionary, IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// name. - public AdditionalPropertiesNumber(string name = default(string)) : base() - { - this.Name = name; - } - - /// - /// Gets or Sets Name - /// - [DataMember(Name="name", EmitDefaultValue=false)] - public string Name { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class AdditionalPropertiesNumber {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesNumber).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesNumber instances are equal - /// - /// Instance of AdditionalPropertiesNumber to be compared - /// Boolean - public bool Equals(AdditionalPropertiesNumber input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = base.GetHashCode(); - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesObject.cs deleted file mode 100644 index ee5b67b2eb..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesObject.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// AdditionalPropertiesObject - /// - [DataContract] - public partial class AdditionalPropertiesObject : Dictionary>, IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// name. - public AdditionalPropertiesObject(string name = default(string)) : base() - { - this.Name = name; - } - - /// - /// Gets or Sets Name - /// - [DataMember(Name="name", EmitDefaultValue=false)] - public string Name { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class AdditionalPropertiesObject {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesObject).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesObject instances are equal - /// - /// Instance of AdditionalPropertiesObject to be compared - /// Boolean - public bool Equals(AdditionalPropertiesObject input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = base.GetHashCode(); - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesString.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesString.cs deleted file mode 100644 index 29dbad58ca..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesString.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// AdditionalPropertiesString - /// - [DataContract] - public partial class AdditionalPropertiesString : Dictionary, IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// name. - public AdditionalPropertiesString(string name = default(string)) : base() - { - this.Name = name; - } - - /// - /// Gets or Sets Name - /// - [DataMember(Name="name", EmitDefaultValue=false)] - public string Name { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class AdditionalPropertiesString {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as AdditionalPropertiesString).AreEqual; - } - - /// - /// Returns true if AdditionalPropertiesString instances are equal - /// - /// Instance of AdditionalPropertiesString to be compared - /// Boolean - public bool Equals(AdditionalPropertiesString input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = base.GetHashCode(); - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Animal.cs index 1a40232b0a..86a7a429b2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Animal.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AppleReq.cs index 2c77cf1c41..9e09e2da8c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AppleReq.cs @@ -56,7 +56,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Cultivar /// - [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = true)] public string Cultivar { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BananaReq.cs index fdd36929d1..3edb9a1b6d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BananaReq.cs @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets LengthCm /// - [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = true)] public decimal LengthCm { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BasquePig.cs index 3be036bde5..2971e12965 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BasquePig.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BigCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BigCat.cs deleted file mode 100644 index 2fd960256c..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BigCat.cs +++ /dev/null @@ -1,158 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// BigCat - /// - [DataContract] - public partial class BigCat : Cat, IEquatable, IValidatableObject - { - /// - /// Defines Kind - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum KindEnum - { - /// - /// Enum Lions for value: lions - /// - [EnumMember(Value = "lions")] - Lions = 1, - - /// - /// Enum Tigers for value: tigers - /// - [EnumMember(Value = "tigers")] - Tigers = 2, - - /// - /// Enum Leopards for value: leopards - /// - [EnumMember(Value = "leopards")] - Leopards = 3, - - /// - /// Enum Jaguars for value: jaguars - /// - [EnumMember(Value = "jaguars")] - Jaguars = 4 - - } - - /// - /// Gets or Sets Kind - /// - [DataMember(Name="kind", EmitDefaultValue=false)] - public KindEnum? Kind { get; set; } - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected BigCat() { } - /// - /// Initializes a new instance of the class. - /// - /// kind. - /// className (required). - /// color (default to "red"). - /// declawed. - public BigCat(KindEnum? kind = default(KindEnum?), string className = default(string), string color = "red", bool declawed = default(bool)) : base(declawed) - { - this.Kind = kind; - } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class BigCat {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); - sb.Append(" Kind: ").Append(Kind).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public override string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as BigCat).AreEqual; - } - - /// - /// Returns true if BigCat instances are equal - /// - /// Instance of BigCat to be compared - /// Boolean - public bool Equals(BigCat input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Kind.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - foreach(var x in BaseValidate(validationContext)) yield return x; - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BigCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BigCatAllOf.cs deleted file mode 100644 index 5244a8f348..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BigCatAllOf.cs +++ /dev/null @@ -1,148 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// BigCatAllOf - /// - [DataContract] - public partial class BigCatAllOf : IEquatable, IValidatableObject - { - /// - /// Defines Kind - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum KindEnum - { - /// - /// Enum Lions for value: lions - /// - [EnumMember(Value = "lions")] - Lions = 1, - - /// - /// Enum Tigers for value: tigers - /// - [EnumMember(Value = "tigers")] - Tigers = 2, - - /// - /// Enum Leopards for value: leopards - /// - [EnumMember(Value = "leopards")] - Leopards = 3, - - /// - /// Enum Jaguars for value: jaguars - /// - [EnumMember(Value = "jaguars")] - Jaguars = 4 - - } - - /// - /// Gets or Sets Kind - /// - [DataMember(Name="kind", EmitDefaultValue=false)] - public KindEnum? Kind { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// kind. - public BigCatAllOf(KindEnum? kind = default(KindEnum?)) - { - this.Kind = kind; - } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class BigCatAllOf {\n"); - sb.Append(" Kind: ").Append(Kind).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as BigCatAllOf).AreEqual; - } - - /// - /// Returns true if BigCatAllOf instances are equal - /// - /// Instance of BigCatAllOf to be compared - /// Boolean - public bool Equals(BigCatAllOf input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - hashCode = hashCode * 59 + this.Kind.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Cat.cs index 87e09bc6a5..c90dc4940d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Cat.cs @@ -130,7 +130,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Category.cs index bb359da38f..1abee7610c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Category.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs index c6c7222d7a..f665258c5c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs @@ -57,11 +57,6 @@ namespace Org.OpenAPITools.Model /// /// Initializes a new instance of the class. /// - [JsonConstructorAttribute] - protected ChildCat() { } - /// - /// Initializes a new instance of the class. - /// /// name. /// petType (default to PetTypeEnum.ChildCat). public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() @@ -155,7 +150,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 87cce8a2f1..25aa645721 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -61,13 +61,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DanishPig.cs index d5ae078551..2f877b7d38 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DanishPig.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Dog.cs index b49df98acb..1d1dd51ee3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Dog.cs @@ -133,7 +133,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumArrays.cs index 89584f4501..59f55d253d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -78,13 +78,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets ArrayEnum - /// - [DataMember(Name = "array_enum", EmitDefaultValue = false)] - public List ArrayEnum { get; set; } /// /// Initializes a new instance of the class. /// @@ -96,6 +89,12 @@ namespace Org.OpenAPITools.Model this.ArrayEnum = arrayEnum; } + /// + /// Gets or Sets ArrayEnum + /// + [DataMember(Name = "array_enum", EmitDefaultValue = false)] + public List ArrayEnum { get; set; } + /// /// Returns the string presentation of the object /// @@ -149,7 +148,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); - hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + if (this.ArrayEnum != null) + { + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumTest.cs index 54937a2fbf..e6b89b9b56 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumTest.cs @@ -94,7 +94,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets EnumStringRequired /// - [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = true)] public EnumStringRequiredEnum EnumStringRequired { get; set; } /// /// Defines EnumInteger diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index bbd3bbdbdf..f17be2330f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -61,13 +61,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs index 551fa85194..62203c6827 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs @@ -107,7 +107,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Number /// - [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = true)] public decimal Number { get; set; } /// @@ -137,7 +137,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Byte /// - [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = true)] public byte[] Byte { get; set; } /// @@ -149,7 +149,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Date /// - [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] [JsonConverter(typeof(OpenAPIDateConverter))] public DateTime Date { get; set; } @@ -168,7 +168,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Password /// - [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = true)] public string Password { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 46971ef73d..46de6e7e45 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] public string PetType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject.cs deleted file mode 100644 index c7a72be0c9..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject - /// - [DataContract(Name = "inline_object")] - public partial class InlineObject : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// Updated name of the pet. - /// Updated status of the pet. - public InlineObject(string name = default(string), string status = default(string)) - { - this.Name = name; - this.Status = status; - } - - /// - /// Updated name of the pet - /// - /// Updated name of the pet - [DataMember(Name = "name", EmitDefaultValue = false)] - public string Name { get; set; } - - /// - /// Updated status of the pet - /// - /// Updated status of the pet - [DataMember(Name = "status", EmitDefaultValue = false)] - public string Status { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject {\n"); - sb.Append(" Name: ").Append(Name).Append("\n"); - sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject).AreEqual; - } - - /// - /// Returns true if InlineObject instances are equal - /// - /// Instance of InlineObject to be compared - /// Boolean - public bool Equals(InlineObject input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - if (this.Status != null) - hashCode = hashCode * 59 + this.Status.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject1.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject1.cs deleted file mode 100644 index e887fa228f..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject1.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject1 - /// - [DataContract(Name = "inline_object_1")] - public partial class InlineObject1 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// Additional data to pass to server. - /// file to upload. - public InlineObject1(string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) - { - this.AdditionalMetadata = additionalMetadata; - this.File = file; - } - - /// - /// Additional data to pass to server - /// - /// Additional data to pass to server - [DataMember(Name = "additionalMetadata", EmitDefaultValue = false)] - public string AdditionalMetadata { get; set; } - - /// - /// file to upload - /// - /// file to upload - [DataMember(Name = "file", EmitDefaultValue = false)] - public System.IO.Stream File { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject1 {\n"); - sb.Append(" AdditionalMetadata: ").Append(AdditionalMetadata).Append("\n"); - sb.Append(" File: ").Append(File).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject1).AreEqual; - } - - /// - /// Returns true if InlineObject1 instances are equal - /// - /// Instance of InlineObject1 to be compared - /// Boolean - public bool Equals(InlineObject1 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.AdditionalMetadata != null) - hashCode = hashCode * 59 + this.AdditionalMetadata.GetHashCode(); - if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject2.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject2.cs deleted file mode 100644 index f0cf3a5071..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject2.cs +++ /dev/null @@ -1,175 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject2 - /// - [DataContract(Name = "inline_object_2")] - public partial class InlineObject2 : IEquatable, IValidatableObject - { - /// - /// Defines EnumFormStringArray - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumFormStringArrayEnum - { - /// - /// Enum GreaterThan for value: > - /// - [EnumMember(Value = ">")] - GreaterThan = 1, - - /// - /// Enum Dollar for value: $ - /// - [EnumMember(Value = "$")] - Dollar = 2 - - } - - - /// - /// Form parameter enum test (string array) - /// - /// Form parameter enum test (string array) - [DataMember(Name = "enum_form_string_array", EmitDefaultValue = false)] - public List EnumFormStringArray { get; set; } - /// - /// Form parameter enum test (string) - /// - /// Form parameter enum test (string) - [JsonConverter(typeof(StringEnumConverter))] - public enum EnumFormStringEnum - { - /// - /// Enum Abc for value: _abc - /// - [EnumMember(Value = "_abc")] - Abc = 1, - - /// - /// Enum Efg for value: -efg - /// - [EnumMember(Value = "-efg")] - Efg = 2, - - /// - /// Enum Xyz for value: (xyz) - /// - [EnumMember(Value = "(xyz)")] - Xyz = 3 - - } - - /// - /// Form parameter enum test (string) - /// - /// Form parameter enum test (string) - [DataMember(Name = "enum_form_string", EmitDefaultValue = false)] - public EnumFormStringEnum? EnumFormString { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// Form parameter enum test (string array). - /// Form parameter enum test (string) (default to EnumFormStringEnum.Efg). - public InlineObject2(List enumFormStringArray = default(List), EnumFormStringEnum? enumFormString = EnumFormStringEnum.Efg) - { - this.EnumFormStringArray = enumFormStringArray; - this.EnumFormString = enumFormString; - } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject2 {\n"); - sb.Append(" EnumFormStringArray: ").Append(EnumFormStringArray).Append("\n"); - sb.Append(" EnumFormString: ").Append(EnumFormString).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject2).AreEqual; - } - - /// - /// Returns true if InlineObject2 instances are equal - /// - /// Instance of InlineObject2 to be compared - /// Boolean - public bool Equals(InlineObject2 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - hashCode = hashCode * 59 + this.EnumFormStringArray.GetHashCode(); - hashCode = hashCode * 59 + this.EnumFormString.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject3.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject3.cs deleted file mode 100644 index 8e94dc8114..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject3.cs +++ /dev/null @@ -1,357 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject3 - /// - [DataContract(Name = "inline_object_3")] - public partial class InlineObject3 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject3() { } - /// - /// Initializes a new instance of the class. - /// - /// None. - /// None. - /// None. - /// None (required). - /// None. - /// None (required). - /// None. - /// None (required). - /// None (required). - /// None. - /// None. - /// None (default to "2010-02-01T10:20:10.111110+01:00"). - /// None. - /// None. - public InlineObject3(int integer = default(int), int int32 = default(int), long int64 = default(long), decimal number = default(decimal), float _float = default(float), double _double = default(double), string _string = default(string), string patternWithoutDelimiter = default(string), byte[] _byte = default(byte[]), System.IO.Stream binary = default(System.IO.Stream), DateTime date = default(DateTime), DateTime dateTime = default(DateTime), string password = default(string), string callback = default(string)) - { - this.Number = number; - this.Double = _double; - // to ensure "patternWithoutDelimiter" is required (not null) - this.PatternWithoutDelimiter = patternWithoutDelimiter ?? throw new ArgumentNullException("patternWithoutDelimiter is a required property for InlineObject3 and cannot be null"); - // to ensure "_byte" is required (not null) - this.Byte = _byte ?? throw new ArgumentNullException("_byte is a required property for InlineObject3 and cannot be null"); - this.Integer = integer; - this.Int32 = int32; - this.Int64 = int64; - this.Float = _float; - this.String = _string; - this.Binary = binary; - this.Date = date; - this.DateTime = dateTime; - this.Password = password; - this.Callback = callback; - } - - /// - /// None - /// - /// None - [DataMember(Name = "integer", EmitDefaultValue = false)] - public int Integer { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "int32", EmitDefaultValue = false)] - public int Int32 { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "int64", EmitDefaultValue = false)] - public long Int64 { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] - public decimal Number { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "float", EmitDefaultValue = false)] - public float Float { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "double", IsRequired = true, EmitDefaultValue = false)] - public double Double { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "string", EmitDefaultValue = false)] - public string String { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "pattern_without_delimiter", IsRequired = true, EmitDefaultValue = false)] - public string PatternWithoutDelimiter { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] - public byte[] Byte { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "binary", EmitDefaultValue = false)] - public System.IO.Stream Binary { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "date", EmitDefaultValue = false)] - [JsonConverter(typeof(OpenAPIDateConverter))] - public DateTime Date { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "dateTime", EmitDefaultValue = false)] - public DateTime DateTime { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "password", EmitDefaultValue = false)] - public string Password { get; set; } - - /// - /// None - /// - /// None - [DataMember(Name = "callback", EmitDefaultValue = false)] - public string Callback { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject3 {\n"); - sb.Append(" Integer: ").Append(Integer).Append("\n"); - sb.Append(" Int32: ").Append(Int32).Append("\n"); - sb.Append(" Int64: ").Append(Int64).Append("\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Float: ").Append(Float).Append("\n"); - sb.Append(" Double: ").Append(Double).Append("\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append(" PatternWithoutDelimiter: ").Append(PatternWithoutDelimiter).Append("\n"); - sb.Append(" Byte: ").Append(Byte).Append("\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); - sb.Append(" Date: ").Append(Date).Append("\n"); - sb.Append(" DateTime: ").Append(DateTime).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); - sb.Append(" Callback: ").Append(Callback).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject3).AreEqual; - } - - /// - /// Returns true if InlineObject3 instances are equal - /// - /// Instance of InlineObject3 to be compared - /// Boolean - public bool Equals(InlineObject3 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - hashCode = hashCode * 59 + this.Integer.GetHashCode(); - hashCode = hashCode * 59 + this.Int32.GetHashCode(); - hashCode = hashCode * 59 + this.Int64.GetHashCode(); - hashCode = hashCode * 59 + this.Number.GetHashCode(); - hashCode = hashCode * 59 + this.Float.GetHashCode(); - hashCode = hashCode * 59 + this.Double.GetHashCode(); - if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); - if (this.PatternWithoutDelimiter != null) - hashCode = hashCode * 59 + this.PatternWithoutDelimiter.GetHashCode(); - if (this.Byte != null) - hashCode = hashCode * 59 + this.Byte.GetHashCode(); - if (this.Binary != null) - hashCode = hashCode * 59 + this.Binary.GetHashCode(); - if (this.Date != null) - hashCode = hashCode * 59 + this.Date.GetHashCode(); - if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); - if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); - if (this.Callback != null) - hashCode = hashCode * 59 + this.Callback.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - // Integer (int) maximum - if(this.Integer > (int)100) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); - } - - // Integer (int) minimum - if(this.Integer < (int)10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); - } - - // Int32 (int) maximum - if(this.Int32 > (int)200) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); - } - - // Int32 (int) minimum - if(this.Int32 < (int)20) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); - } - - // Number (decimal) maximum - if(this.Number > (decimal)543.2) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); - } - - // Number (decimal) minimum - if(this.Number < (decimal)32.1) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); - } - - // Float (float) maximum - if(this.Float > (float)987.6) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); - } - - // Double (double) maximum - if(this.Double > (double)123.4) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); - } - - // Double (double) minimum - if(this.Double < (double)67.8) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); - } - - // String (string) pattern - Regex regexString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (false == regexString.Match(this.String).Success) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for String, must match a pattern of " + regexString, new [] { "String" }); - } - - // PatternWithoutDelimiter (string) pattern - Regex regexPatternWithoutDelimiter = new Regex(@"^[A-Z].*", RegexOptions.CultureInvariant); - if (false == regexPatternWithoutDelimiter.Match(this.PatternWithoutDelimiter).Success) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithoutDelimiter, must match a pattern of " + regexPatternWithoutDelimiter, new [] { "PatternWithoutDelimiter" }); - } - - // Password (string) maxLength - if(this.Password != null && this.Password.Length > 64) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); - } - - // Password (string) minLength - if(this.Password != null && this.Password.Length < 10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); - } - - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject4.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject4.cs deleted file mode 100644 index eef39beea9..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject4.cs +++ /dev/null @@ -1,138 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject4 - /// - [DataContract(Name = "inline_object_4")] - public partial class InlineObject4 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject4() { } - /// - /// Initializes a new instance of the class. - /// - /// field1 (required). - /// field2 (required). - public InlineObject4(string param = default(string), string param2 = default(string)) - { - // to ensure "param" is required (not null) - this.Param = param ?? throw new ArgumentNullException("param is a required property for InlineObject4 and cannot be null"); - // to ensure "param2" is required (not null) - this.Param2 = param2 ?? throw new ArgumentNullException("param2 is a required property for InlineObject4 and cannot be null"); - } - - /// - /// field1 - /// - /// field1 - [DataMember(Name = "param", IsRequired = true, EmitDefaultValue = false)] - public string Param { get; set; } - - /// - /// field2 - /// - /// field2 - [DataMember(Name = "param2", IsRequired = true, EmitDefaultValue = false)] - public string Param2 { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject4 {\n"); - sb.Append(" Param: ").Append(Param).Append("\n"); - sb.Append(" Param2: ").Append(Param2).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject4).AreEqual; - } - - /// - /// Returns true if InlineObject4 instances are equal - /// - /// Instance of InlineObject4 to be compared - /// Boolean - public bool Equals(InlineObject4 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.Param != null) - hashCode = hashCode * 59 + this.Param.GetHashCode(); - if (this.Param2 != null) - hashCode = hashCode * 59 + this.Param2.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject5.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject5.cs deleted file mode 100644 index d88814fa4b..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineObject5.cs +++ /dev/null @@ -1,137 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineObject5 - /// - [DataContract(Name = "inline_object_5")] - public partial class InlineObject5 : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected InlineObject5() { } - /// - /// Initializes a new instance of the class. - /// - /// Additional data to pass to server. - /// file to upload (required). - public InlineObject5(string additionalMetadata = default(string), System.IO.Stream requiredFile = default(System.IO.Stream)) - { - // to ensure "requiredFile" is required (not null) - this.RequiredFile = requiredFile ?? throw new ArgumentNullException("requiredFile is a required property for InlineObject5 and cannot be null"); - this.AdditionalMetadata = additionalMetadata; - } - - /// - /// Additional data to pass to server - /// - /// Additional data to pass to server - [DataMember(Name = "additionalMetadata", EmitDefaultValue = false)] - public string AdditionalMetadata { get; set; } - - /// - /// file to upload - /// - /// file to upload - [DataMember(Name = "requiredFile", IsRequired = true, EmitDefaultValue = false)] - public System.IO.Stream RequiredFile { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class InlineObject5 {\n"); - sb.Append(" AdditionalMetadata: ").Append(AdditionalMetadata).Append("\n"); - sb.Append(" RequiredFile: ").Append(RequiredFile).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineObject5).AreEqual; - } - - /// - /// Returns true if InlineObject5 instances are equal - /// - /// Instance of InlineObject5 to be compared - /// Boolean - public bool Equals(InlineObject5 input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.AdditionalMetadata != null) - hashCode = hashCode * 59 + this.AdditionalMetadata.GetHashCode(); - if (this.RequiredFile != null) - hashCode = hashCode * 59 + this.RequiredFile.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineResponseDefault.cs deleted file mode 100644 index 755f9aebc7..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ /dev/null @@ -1,120 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.IO; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Linq; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// InlineResponseDefault - /// - [DataContract(Name = "inline_response_default")] - public partial class InlineResponseDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// _string. - public InlineResponseDefault(Foo _string = default(Foo)) - { - this.String = _string; - } - - /// - /// Gets or Sets String - /// - [DataMember(Name = "string", EmitDefaultValue = false)] - public Foo String { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("class InlineResponseDefault {\n"); - sb.Append(" String: ").Append(String).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as InlineResponseDefault).AreEqual; - } - - /// - /// Returns true if InlineResponseDefault instances are equal - /// - /// Instance of InlineResponseDefault to be compared - /// Boolean - public bool Equals(InlineResponseDefault input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.String != null) - { - hashCode = (hashCode * 59) + this.String.GetHashCode(); - } - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - public IEnumerable Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 55c607598a..ea18925f87 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -61,13 +61,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MapTest.cs index d947debc81..3c07f00331 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MapTest.cs @@ -52,13 +52,6 @@ namespace Org.OpenAPITools.Model } - - - /// - /// Gets or Sets MapOfEnumString - /// - [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] - public Dictionary MapOfEnumString { get; set; } /// /// Initializes a new instance of the class. /// @@ -80,6 +73,12 @@ namespace Org.OpenAPITools.Model [DataMember(Name = "map_map_of_string", EmitDefaultValue = false)] public Dictionary> MapMapOfString { get; set; } + /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] + public Dictionary MapOfEnumString { get; set; } + /// /// Gets or Sets DirectMap /// @@ -150,7 +149,10 @@ namespace Org.OpenAPITools.Model { hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); } - hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + if (this.MapOfEnumString != null) + { + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); + } if (this.DirectMap != null) { hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs index 560d91db23..a620425b08 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets _Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public int _Name { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ParentPet.cs index c9f4484a5a..06356f5a8f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ParentPet.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach (var x in BaseValidate(validationContext)) + foreach (var x in base.BaseValidate(validationContext)) { yield return x; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pet.cs index dd1651330b..a469a7bcc9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pet.cs @@ -115,13 +115,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// /// Gets or Sets PhotoUrls /// - [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = true)] public List PhotoUrls { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index b01295ccc8..842b87ce4b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 660acca3ff..516766fc2d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -61,13 +61,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeInterface.cs index 61c346de34..c2b7c540ba 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 916bb0972a..00db6ae40f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -61,13 +61,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ShapeType /// - [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = true)] public string ShapeType { get; set; } /// /// Gets or Sets QuadrilateralType /// - [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = true)] public string QuadrilateralType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TriangleInterface.cs index 260ec9b603..0f384e7452 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets TriangleType /// - [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = true)] public string TriangleType { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TypeHolderDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TypeHolderDefault.cs deleted file mode 100644 index c7034a2edd..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TypeHolderDefault.cs +++ /dev/null @@ -1,166 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// TypeHolderDefault - /// - [DataContract] - public partial class TypeHolderDefault : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected TypeHolderDefault() { } - /// - /// Initializes a new instance of the class. - /// - /// stringItem (required) (default to "what"). - /// numberItem (required). - /// integerItem (required). - /// boolItem (required) (default to true). - /// arrayItem (required). - public TypeHolderDefault(string stringItem = "what", decimal numberItem = default(decimal), int integerItem = default(int), bool boolItem = true, List arrayItem = default(List)) - { - // to ensure "stringItem" is required (not null) - this.StringItem = stringItem ?? throw new ArgumentNullException("stringItem is a required property for TypeHolderDefault and cannot be null"); - this.NumberItem = numberItem; - this.IntegerItem = integerItem; - this.BoolItem = boolItem; - // to ensure "arrayItem" is required (not null) - this.ArrayItem = arrayItem ?? throw new ArgumentNullException("arrayItem is a required property for TypeHolderDefault and cannot be null"); - } - - /// - /// Gets or Sets StringItem - /// - [DataMember(Name="string_item", EmitDefaultValue=false)] - public string StringItem { get; set; } - - /// - /// Gets or Sets NumberItem - /// - [DataMember(Name="number_item", EmitDefaultValue=false)] - public decimal NumberItem { get; set; } - - /// - /// Gets or Sets IntegerItem - /// - [DataMember(Name="integer_item", EmitDefaultValue=false)] - public int IntegerItem { get; set; } - - /// - /// Gets or Sets BoolItem - /// - [DataMember(Name="bool_item", EmitDefaultValue=false)] - public bool BoolItem { get; set; } - - /// - /// Gets or Sets ArrayItem - /// - [DataMember(Name="array_item", EmitDefaultValue=false)] - public List ArrayItem { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class TypeHolderDefault {\n"); - sb.Append(" StringItem: ").Append(StringItem).Append("\n"); - sb.Append(" NumberItem: ").Append(NumberItem).Append("\n"); - sb.Append(" IntegerItem: ").Append(IntegerItem).Append("\n"); - sb.Append(" BoolItem: ").Append(BoolItem).Append("\n"); - sb.Append(" ArrayItem: ").Append(ArrayItem).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as TypeHolderDefault).AreEqual; - } - - /// - /// Returns true if TypeHolderDefault instances are equal - /// - /// Instance of TypeHolderDefault to be compared - /// Boolean - public bool Equals(TypeHolderDefault input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.StringItem != null) - hashCode = hashCode * 59 + this.StringItem.GetHashCode(); - hashCode = hashCode * 59 + this.NumberItem.GetHashCode(); - hashCode = hashCode * 59 + this.IntegerItem.GetHashCode(); - hashCode = hashCode * 59 + this.BoolItem.GetHashCode(); - if (this.ArrayItem != null) - hashCode = hashCode * 59 + this.ArrayItem.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TypeHolderExample.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TypeHolderExample.cs deleted file mode 100644 index e69ce97ac7..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TypeHolderExample.cs +++ /dev/null @@ -1,176 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// TypeHolderExample - /// - [DataContract] - public partial class TypeHolderExample : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - [JsonConstructorAttribute] - protected TypeHolderExample() { } - /// - /// Initializes a new instance of the class. - /// - /// stringItem (required). - /// numberItem (required). - /// floatItem (required). - /// integerItem (required). - /// boolItem (required). - /// arrayItem (required). - public TypeHolderExample(string stringItem = default(string), decimal numberItem = default(decimal), float floatItem = default(float), int integerItem = default(int), bool boolItem = default(bool), List arrayItem = default(List)) - { - // to ensure "stringItem" is required (not null) - this.StringItem = stringItem ?? throw new ArgumentNullException("stringItem is a required property for TypeHolderExample and cannot be null"); - this.NumberItem = numberItem; - this.FloatItem = floatItem; - this.IntegerItem = integerItem; - this.BoolItem = boolItem; - // to ensure "arrayItem" is required (not null) - this.ArrayItem = arrayItem ?? throw new ArgumentNullException("arrayItem is a required property for TypeHolderExample and cannot be null"); - } - - /// - /// Gets or Sets StringItem - /// - [DataMember(Name="string_item", EmitDefaultValue=false)] - public string StringItem { get; set; } - - /// - /// Gets or Sets NumberItem - /// - [DataMember(Name="number_item", EmitDefaultValue=false)] - public decimal NumberItem { get; set; } - - /// - /// Gets or Sets FloatItem - /// - [DataMember(Name="float_item", EmitDefaultValue=false)] - public float FloatItem { get; set; } - - /// - /// Gets or Sets IntegerItem - /// - [DataMember(Name="integer_item", EmitDefaultValue=false)] - public int IntegerItem { get; set; } - - /// - /// Gets or Sets BoolItem - /// - [DataMember(Name="bool_item", EmitDefaultValue=false)] - public bool BoolItem { get; set; } - - /// - /// Gets or Sets ArrayItem - /// - [DataMember(Name="array_item", EmitDefaultValue=false)] - public List ArrayItem { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class TypeHolderExample {\n"); - sb.Append(" StringItem: ").Append(StringItem).Append("\n"); - sb.Append(" NumberItem: ").Append(NumberItem).Append("\n"); - sb.Append(" FloatItem: ").Append(FloatItem).Append("\n"); - sb.Append(" IntegerItem: ").Append(IntegerItem).Append("\n"); - sb.Append(" BoolItem: ").Append(BoolItem).Append("\n"); - sb.Append(" ArrayItem: ").Append(ArrayItem).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as TypeHolderExample).AreEqual; - } - - /// - /// Returns true if TypeHolderExample instances are equal - /// - /// Instance of TypeHolderExample to be compared - /// Boolean - public bool Equals(TypeHolderExample input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.StringItem != null) - hashCode = hashCode * 59 + this.StringItem.GetHashCode(); - hashCode = hashCode * 59 + this.NumberItem.GetHashCode(); - hashCode = hashCode * 59 + this.FloatItem.GetHashCode(); - hashCode = hashCode * 59 + this.IntegerItem.GetHashCode(); - hashCode = hashCode * 59 + this.BoolItem.GetHashCode(); - if (this.ArrayItem != null) - hashCode = hashCode * 59 + this.ArrayItem.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Whale.cs index fa418f0c13..b050792c06 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Whale.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/XmlItem.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/XmlItem.cs deleted file mode 100644 index 8f204d8814..0000000000 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/XmlItem.cs +++ /dev/null @@ -1,411 +0,0 @@ -/* - * OpenAPI Petstore - * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://github.com/openapitools/openapi-generator.git - */ - - -using System; -using System.Linq; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.ComponentModel.DataAnnotations; -using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; -using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; - -namespace Org.OpenAPITools.Model -{ - /// - /// XmlItem - /// - [DataContract] - public partial class XmlItem : IEquatable, IValidatableObject - { - /// - /// Initializes a new instance of the class. - /// - /// attributeString. - /// attributeNumber. - /// attributeInteger. - /// attributeBoolean. - /// wrappedArray. - /// nameString. - /// nameNumber. - /// nameInteger. - /// nameBoolean. - /// nameArray. - /// nameWrappedArray. - /// prefixString. - /// prefixNumber. - /// prefixInteger. - /// prefixBoolean. - /// prefixArray. - /// prefixWrappedArray. - /// namespaceString. - /// namespaceNumber. - /// namespaceInteger. - /// namespaceBoolean. - /// namespaceArray. - /// namespaceWrappedArray. - /// prefixNsString. - /// prefixNsNumber. - /// prefixNsInteger. - /// prefixNsBoolean. - /// prefixNsArray. - /// prefixNsWrappedArray. - public XmlItem(string attributeString = default(string), decimal attributeNumber = default(decimal), int attributeInteger = default(int), bool attributeBoolean = default(bool), List wrappedArray = default(List), string nameString = default(string), decimal nameNumber = default(decimal), int nameInteger = default(int), bool nameBoolean = default(bool), List nameArray = default(List), List nameWrappedArray = default(List), string prefixString = default(string), decimal prefixNumber = default(decimal), int prefixInteger = default(int), bool prefixBoolean = default(bool), List prefixArray = default(List), List prefixWrappedArray = default(List), string namespaceString = default(string), decimal namespaceNumber = default(decimal), int namespaceInteger = default(int), bool namespaceBoolean = default(bool), List namespaceArray = default(List), List namespaceWrappedArray = default(List), string prefixNsString = default(string), decimal prefixNsNumber = default(decimal), int prefixNsInteger = default(int), bool prefixNsBoolean = default(bool), List prefixNsArray = default(List), List prefixNsWrappedArray = default(List)) - { - this.AttributeString = attributeString; - this.AttributeNumber = attributeNumber; - this.AttributeInteger = attributeInteger; - this.AttributeBoolean = attributeBoolean; - this.WrappedArray = wrappedArray; - this.NameString = nameString; - this.NameNumber = nameNumber; - this.NameInteger = nameInteger; - this.NameBoolean = nameBoolean; - this.NameArray = nameArray; - this.NameWrappedArray = nameWrappedArray; - this.PrefixString = prefixString; - this.PrefixNumber = prefixNumber; - this.PrefixInteger = prefixInteger; - this.PrefixBoolean = prefixBoolean; - this.PrefixArray = prefixArray; - this.PrefixWrappedArray = prefixWrappedArray; - this.NamespaceString = namespaceString; - this.NamespaceNumber = namespaceNumber; - this.NamespaceInteger = namespaceInteger; - this.NamespaceBoolean = namespaceBoolean; - this.NamespaceArray = namespaceArray; - this.NamespaceWrappedArray = namespaceWrappedArray; - this.PrefixNsString = prefixNsString; - this.PrefixNsNumber = prefixNsNumber; - this.PrefixNsInteger = prefixNsInteger; - this.PrefixNsBoolean = prefixNsBoolean; - this.PrefixNsArray = prefixNsArray; - this.PrefixNsWrappedArray = prefixNsWrappedArray; - } - - /// - /// Gets or Sets AttributeString - /// - [DataMember(Name="attribute_string", EmitDefaultValue=false)] - public string AttributeString { get; set; } - - /// - /// Gets or Sets AttributeNumber - /// - [DataMember(Name="attribute_number", EmitDefaultValue=false)] - public decimal AttributeNumber { get; set; } - - /// - /// Gets or Sets AttributeInteger - /// - [DataMember(Name="attribute_integer", EmitDefaultValue=false)] - public int AttributeInteger { get; set; } - - /// - /// Gets or Sets AttributeBoolean - /// - [DataMember(Name="attribute_boolean", EmitDefaultValue=false)] - public bool AttributeBoolean { get; set; } - - /// - /// Gets or Sets WrappedArray - /// - [DataMember(Name="wrapped_array", EmitDefaultValue=false)] - public List WrappedArray { get; set; } - - /// - /// Gets or Sets NameString - /// - [DataMember(Name="name_string", EmitDefaultValue=false)] - public string NameString { get; set; } - - /// - /// Gets or Sets NameNumber - /// - [DataMember(Name="name_number", EmitDefaultValue=false)] - public decimal NameNumber { get; set; } - - /// - /// Gets or Sets NameInteger - /// - [DataMember(Name="name_integer", EmitDefaultValue=false)] - public int NameInteger { get; set; } - - /// - /// Gets or Sets NameBoolean - /// - [DataMember(Name="name_boolean", EmitDefaultValue=false)] - public bool NameBoolean { get; set; } - - /// - /// Gets or Sets NameArray - /// - [DataMember(Name="name_array", EmitDefaultValue=false)] - public List NameArray { get; set; } - - /// - /// Gets or Sets NameWrappedArray - /// - [DataMember(Name="name_wrapped_array", EmitDefaultValue=false)] - public List NameWrappedArray { get; set; } - - /// - /// Gets or Sets PrefixString - /// - [DataMember(Name="prefix_string", EmitDefaultValue=false)] - public string PrefixString { get; set; } - - /// - /// Gets or Sets PrefixNumber - /// - [DataMember(Name="prefix_number", EmitDefaultValue=false)] - public decimal PrefixNumber { get; set; } - - /// - /// Gets or Sets PrefixInteger - /// - [DataMember(Name="prefix_integer", EmitDefaultValue=false)] - public int PrefixInteger { get; set; } - - /// - /// Gets or Sets PrefixBoolean - /// - [DataMember(Name="prefix_boolean", EmitDefaultValue=false)] - public bool PrefixBoolean { get; set; } - - /// - /// Gets or Sets PrefixArray - /// - [DataMember(Name="prefix_array", EmitDefaultValue=false)] - public List PrefixArray { get; set; } - - /// - /// Gets or Sets PrefixWrappedArray - /// - [DataMember(Name="prefix_wrapped_array", EmitDefaultValue=false)] - public List PrefixWrappedArray { get; set; } - - /// - /// Gets or Sets NamespaceString - /// - [DataMember(Name="namespace_string", EmitDefaultValue=false)] - public string NamespaceString { get; set; } - - /// - /// Gets or Sets NamespaceNumber - /// - [DataMember(Name="namespace_number", EmitDefaultValue=false)] - public decimal NamespaceNumber { get; set; } - - /// - /// Gets or Sets NamespaceInteger - /// - [DataMember(Name="namespace_integer", EmitDefaultValue=false)] - public int NamespaceInteger { get; set; } - - /// - /// Gets or Sets NamespaceBoolean - /// - [DataMember(Name="namespace_boolean", EmitDefaultValue=false)] - public bool NamespaceBoolean { get; set; } - - /// - /// Gets or Sets NamespaceArray - /// - [DataMember(Name="namespace_array", EmitDefaultValue=false)] - public List NamespaceArray { get; set; } - - /// - /// Gets or Sets NamespaceWrappedArray - /// - [DataMember(Name="namespace_wrapped_array", EmitDefaultValue=false)] - public List NamespaceWrappedArray { get; set; } - - /// - /// Gets or Sets PrefixNsString - /// - [DataMember(Name="prefix_ns_string", EmitDefaultValue=false)] - public string PrefixNsString { get; set; } - - /// - /// Gets or Sets PrefixNsNumber - /// - [DataMember(Name="prefix_ns_number", EmitDefaultValue=false)] - public decimal PrefixNsNumber { get; set; } - - /// - /// Gets or Sets PrefixNsInteger - /// - [DataMember(Name="prefix_ns_integer", EmitDefaultValue=false)] - public int PrefixNsInteger { get; set; } - - /// - /// Gets or Sets PrefixNsBoolean - /// - [DataMember(Name="prefix_ns_boolean", EmitDefaultValue=false)] - public bool PrefixNsBoolean { get; set; } - - /// - /// Gets or Sets PrefixNsArray - /// - [DataMember(Name="prefix_ns_array", EmitDefaultValue=false)] - public List PrefixNsArray { get; set; } - - /// - /// Gets or Sets PrefixNsWrappedArray - /// - [DataMember(Name="prefix_ns_wrapped_array", EmitDefaultValue=false)] - public List PrefixNsWrappedArray { get; set; } - - /// - /// Returns the string presentation of the object - /// - /// String presentation of the object - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("class XmlItem {\n"); - sb.Append(" AttributeString: ").Append(AttributeString).Append("\n"); - sb.Append(" AttributeNumber: ").Append(AttributeNumber).Append("\n"); - sb.Append(" AttributeInteger: ").Append(AttributeInteger).Append("\n"); - sb.Append(" AttributeBoolean: ").Append(AttributeBoolean).Append("\n"); - sb.Append(" WrappedArray: ").Append(WrappedArray).Append("\n"); - sb.Append(" NameString: ").Append(NameString).Append("\n"); - sb.Append(" NameNumber: ").Append(NameNumber).Append("\n"); - sb.Append(" NameInteger: ").Append(NameInteger).Append("\n"); - sb.Append(" NameBoolean: ").Append(NameBoolean).Append("\n"); - sb.Append(" NameArray: ").Append(NameArray).Append("\n"); - sb.Append(" NameWrappedArray: ").Append(NameWrappedArray).Append("\n"); - sb.Append(" PrefixString: ").Append(PrefixString).Append("\n"); - sb.Append(" PrefixNumber: ").Append(PrefixNumber).Append("\n"); - sb.Append(" PrefixInteger: ").Append(PrefixInteger).Append("\n"); - sb.Append(" PrefixBoolean: ").Append(PrefixBoolean).Append("\n"); - sb.Append(" PrefixArray: ").Append(PrefixArray).Append("\n"); - sb.Append(" PrefixWrappedArray: ").Append(PrefixWrappedArray).Append("\n"); - sb.Append(" NamespaceString: ").Append(NamespaceString).Append("\n"); - sb.Append(" NamespaceNumber: ").Append(NamespaceNumber).Append("\n"); - sb.Append(" NamespaceInteger: ").Append(NamespaceInteger).Append("\n"); - sb.Append(" NamespaceBoolean: ").Append(NamespaceBoolean).Append("\n"); - sb.Append(" NamespaceArray: ").Append(NamespaceArray).Append("\n"); - sb.Append(" NamespaceWrappedArray: ").Append(NamespaceWrappedArray).Append("\n"); - sb.Append(" PrefixNsString: ").Append(PrefixNsString).Append("\n"); - sb.Append(" PrefixNsNumber: ").Append(PrefixNsNumber).Append("\n"); - sb.Append(" PrefixNsInteger: ").Append(PrefixNsInteger).Append("\n"); - sb.Append(" PrefixNsBoolean: ").Append(PrefixNsBoolean).Append("\n"); - sb.Append(" PrefixNsArray: ").Append(PrefixNsArray).Append("\n"); - sb.Append(" PrefixNsWrappedArray: ").Append(PrefixNsWrappedArray).Append("\n"); - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Returns the JSON string presentation of the object - /// - /// JSON string presentation of the object - public virtual string ToJson() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - - /// - /// Returns true if objects are equal - /// - /// Object to be compared - /// Boolean - public override bool Equals(object input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input as XmlItem).AreEqual; - } - - /// - /// Returns true if XmlItem instances are equal - /// - /// Instance of XmlItem to be compared - /// Boolean - public bool Equals(XmlItem input) - { - return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; - } - - /// - /// Gets the hash code - /// - /// Hash code - public override int GetHashCode() - { - unchecked // Overflow is fine, just wrap - { - int hashCode = 41; - if (this.AttributeString != null) - hashCode = hashCode * 59 + this.AttributeString.GetHashCode(); - hashCode = hashCode * 59 + this.AttributeNumber.GetHashCode(); - hashCode = hashCode * 59 + this.AttributeInteger.GetHashCode(); - hashCode = hashCode * 59 + this.AttributeBoolean.GetHashCode(); - if (this.WrappedArray != null) - hashCode = hashCode * 59 + this.WrappedArray.GetHashCode(); - if (this.NameString != null) - hashCode = hashCode * 59 + this.NameString.GetHashCode(); - hashCode = hashCode * 59 + this.NameNumber.GetHashCode(); - hashCode = hashCode * 59 + this.NameInteger.GetHashCode(); - hashCode = hashCode * 59 + this.NameBoolean.GetHashCode(); - if (this.NameArray != null) - hashCode = hashCode * 59 + this.NameArray.GetHashCode(); - if (this.NameWrappedArray != null) - hashCode = hashCode * 59 + this.NameWrappedArray.GetHashCode(); - if (this.PrefixString != null) - hashCode = hashCode * 59 + this.PrefixString.GetHashCode(); - hashCode = hashCode * 59 + this.PrefixNumber.GetHashCode(); - hashCode = hashCode * 59 + this.PrefixInteger.GetHashCode(); - hashCode = hashCode * 59 + this.PrefixBoolean.GetHashCode(); - if (this.PrefixArray != null) - hashCode = hashCode * 59 + this.PrefixArray.GetHashCode(); - if (this.PrefixWrappedArray != null) - hashCode = hashCode * 59 + this.PrefixWrappedArray.GetHashCode(); - if (this.NamespaceString != null) - hashCode = hashCode * 59 + this.NamespaceString.GetHashCode(); - hashCode = hashCode * 59 + this.NamespaceNumber.GetHashCode(); - hashCode = hashCode * 59 + this.NamespaceInteger.GetHashCode(); - hashCode = hashCode * 59 + this.NamespaceBoolean.GetHashCode(); - if (this.NamespaceArray != null) - hashCode = hashCode * 59 + this.NamespaceArray.GetHashCode(); - if (this.NamespaceWrappedArray != null) - hashCode = hashCode * 59 + this.NamespaceWrappedArray.GetHashCode(); - if (this.PrefixNsString != null) - hashCode = hashCode * 59 + this.PrefixNsString.GetHashCode(); - hashCode = hashCode * 59 + this.PrefixNsNumber.GetHashCode(); - hashCode = hashCode * 59 + this.PrefixNsInteger.GetHashCode(); - hashCode = hashCode * 59 + this.PrefixNsBoolean.GetHashCode(); - if (this.PrefixNsArray != null) - hashCode = hashCode * 59 + this.PrefixNsArray.GetHashCode(); - if (this.PrefixNsWrappedArray != null) - hashCode = hashCode * 59 + this.PrefixNsWrappedArray.GetHashCode(); - return hashCode; - } - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - yield break; - } - } - -} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs index aab75e9cd5..8a3c713fe6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs @@ -92,7 +92,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets ClassName /// - [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = true)] public string ClassName { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Org.OpenAPITools.csproj index a2d989462e..a4d1e50179 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,11 +21,17 @@ - + - + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/FILES index 60d0f82fef..9f81e159fb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/FILES @@ -19,6 +19,9 @@ src/Org.OpenAPITools/Api/UserApi.cs src/Org.OpenAPITools/Client/ApiClient.cs src/Org.OpenAPITools/Client/ApiException.cs src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs +src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs +src/Org.OpenAPITools/Client/Auth/TokenResponse.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs index b872f7a249..2cfaf9e7d4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api @@ -608,9 +609,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -690,9 +701,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -765,9 +786,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -842,9 +873,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -920,9 +961,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1000,9 +1051,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1080,9 +1141,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1162,9 +1233,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1386,9 +1467,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1468,9 +1559,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1550,9 +1651,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1634,9 +1745,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1718,9 +1839,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request @@ -1804,9 +1935,19 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + if (!localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { - localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + else if (!string.IsNullOrEmpty(this.Configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientId) && + !string.IsNullOrEmpty(this.Configuration.OAuthClientSecret) && + this.Configuration.OAuthFlow != null) + { + localVarRequestOptions.OAuth = true; + } } // make the HTTP request diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs index 7cc9c9610a..dd8faec043 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs index 207dda93c6..9f568eb988 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Net; using System.Net.Mime; using Org.OpenAPITools.Client; +using Org.OpenAPITools.Client.Auth; using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Api diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs index 7f930101c9..3d9182b890 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs @@ -24,18 +24,18 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; -using RestSharp.Deserializers; +using RestSharp.Serializers; using RestSharpMethod = RestSharp.Method; using Polly; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { /// /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// - internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; @@ -81,7 +81,9 @@ namespace Org.OpenAPITools.Client } } - public T Deserialize(IRestResponse response) + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; @@ -93,7 +95,7 @@ namespace Org.OpenAPITools.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(IRestResponse response, Type type) + internal object Deserialize(RestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { @@ -146,15 +148,22 @@ namespace Org.OpenAPITools.Client } } - public string RootElement { get; set; } - public string Namespace { get; set; } - public string DateFormat { get; set; } + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.Serializers.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } + + public DataFormat DataFormat => DataFormat.Json; } /// /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), @@ -185,14 +194,14 @@ namespace Org.OpenAPITools.Client /// Allows for extending request processing for generated code. /// /// The RestSharp request object - partial void InterceptRequest(IRestRequest request); + partial void InterceptRequest(RestRequest request); /// /// Allows for extending response processing for generated code. /// /// The RestSharp request object /// The RestSharp response object - partial void InterceptResponse(IRestRequest request, IRestResponse response); + partial void InterceptResponse(RestRequest request, RestResponse response); /// /// Initializes a new instance of the , defaulting to the global configurations' base url. @@ -227,25 +236,25 @@ namespace Org.OpenAPITools.Client switch (method) { case HttpMethod.Get: - other = RestSharpMethod.GET; + other = RestSharpMethod.Get; break; case HttpMethod.Post: - other = RestSharpMethod.POST; + other = RestSharpMethod.Post; break; case HttpMethod.Put: - other = RestSharpMethod.PUT; + other = RestSharpMethod.Put; break; case HttpMethod.Delete: - other = RestSharpMethod.DELETE; + other = RestSharpMethod.Delete; break; case HttpMethod.Head: - other = RestSharpMethod.HEAD; + other = RestSharpMethod.Head; break; case HttpMethod.Options: - other = RestSharpMethod.OPTIONS; + other = RestSharpMethod.Options; break; case HttpMethod.Patch: - other = RestSharpMethod.PATCH; + other = RestSharpMethod.Patch; break; default: throw new ArgumentOutOfRangeException("method", method, null); @@ -276,11 +285,7 @@ namespace Org.OpenAPITools.Client if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); - RestRequest request = new RestRequest(Method(method)) - { - Resource = path, - JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) - }; + RestRequest request = new RestRequest(path, Method(method)); if (options.PathParameters != null) { @@ -375,25 +380,17 @@ namespace Org.OpenAPITools.Client var bytes = ClientUtils.ReadAsBytes(file); var fileStream = file as FileStream; if (fileStream != null) - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); else - request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); } } } - if (options.Cookies != null && options.Cookies.Count > 0) - { - foreach (var cookie in options.Cookies) - { - request.AddCookie(cookie.Name, cookie.Value); - } - } - return request; } - private ApiResponse ToApiResponse(IRestResponse response) + private ApiResponse ToApiResponse(RestResponse response) { T result = response.Data; string rawContent = response.Content; @@ -412,9 +409,17 @@ namespace Org.OpenAPITools.Client } } + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + if (response.Cookies != null) { - foreach (var responseCookies in response.Cookies) + foreach (var responseCookies in response.Cookies.Cast()) { transformed.Cookies.Add( new Cookie( @@ -432,54 +437,46 @@ namespace Org.OpenAPITools.Client private ApiResponse Exec(RestRequest req, RequestOptions options, IReadableConfiguration configuration) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else - { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } } - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.Proxy = configuration.Proxy; - } + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); - if (configuration.ClientCertificates != null) + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; @@ -515,6 +512,10 @@ namespace Org.OpenAPITools.Client { response.Data = (T)(object)response.RawBytes; } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } InterceptResponse(req, response); @@ -527,7 +528,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, @@ -556,54 +557,35 @@ namespace Org.OpenAPITools.Client private async Task> ExecAsync(RestRequest req, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; - RestClient client = new RestClient(baseUrl); - client.ClearHandlers(); - var existingDeserializer = req.JsonSerializer as IDeserializer; - if (existingDeserializer != null) + var clientOptions = new RestClientOptions(baseUrl) { - client.AddHandler("application/json", () => existingDeserializer); - client.AddHandler("text/json", () => existingDeserializer); - client.AddHandler("text/x-json", () => existingDeserializer); - client.AddHandler("text/javascript", () => existingDeserializer); - client.AddHandler("*+json", () => existingDeserializer); - } - else + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent + }; + + RestClient client = new RestClient(clientOptions) + .UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)); + + if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && + !string.IsNullOrEmpty(configuration.OAuthClientId) && + !string.IsNullOrEmpty(configuration.OAuthClientSecret) && + configuration.OAuthFlow != null) { - var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); - client.AddHandler("application/json", () => customDeserializer); - client.AddHandler("text/json", () => customDeserializer); - client.AddHandler("text/x-json", () => customDeserializer); - client.AddHandler("text/javascript", () => customDeserializer); - client.AddHandler("*+json", () => customDeserializer); - } - - var xmlDeserializer = new XmlDeserializer(); - client.AddHandler("application/xml", () => xmlDeserializer); - client.AddHandler("text/xml", () => xmlDeserializer); - client.AddHandler("*+xml", () => xmlDeserializer); - client.AddHandler("*", () => xmlDeserializer); - - client.Timeout = configuration.Timeout; - - if (configuration.Proxy != null) - { - client.Proxy = configuration.Proxy; - } - - if (configuration.UserAgent != null) - { - client.UserAgent = configuration.UserAgent; - } - - if (configuration.ClientCertificates != null) - { - client.ClientCertificates = configuration.ClientCertificates; + client = client.UseAuthenticator(new OAuthAuthenticator( + configuration.OAuthTokenUrl, + configuration.OAuthClientId, + configuration.OAuthClientSecret, + configuration.OAuthFlow, + SerializerSettings, + configuration)); } InterceptRequest(req); - IRestResponse response; + RestResponse response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; @@ -644,7 +626,7 @@ namespace Org.OpenAPITools.Client if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List(); - foreach (var restResponseCookie in response.Cookies) + foreach (var restResponseCookie in response.Cookies.Cast()) { var cookie = new Cookie( restResponseCookie.Name, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs new file mode 100644 index 0000000000..b657ec45f5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Auth/OAuthAuthenticator.cs @@ -0,0 +1,95 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Authenticators; + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// An authenticator for OAuth2 authentication flows + /// + public class OAuthAuthenticator : AuthenticatorBase + { + readonly string _tokenUrl; + readonly string _clientId; + readonly string _clientSecret; + readonly string _grantType; + readonly JsonSerializerSettings _serializerSettings; + readonly IReadableConfiguration _configuration; + + /// + /// Initialize the OAuth2 Authenticator + /// + public OAuthAuthenticator( + string tokenUrl, + string clientId, + string clientSecret, + OAuthFlow? flow, + JsonSerializerSettings serializerSettings, + IReadableConfiguration configuration) : base("") + { + _tokenUrl = tokenUrl; + _clientId = clientId; + _clientSecret = clientSecret; + _serializerSettings = serializerSettings; + _configuration = configuration; + + switch (flow) + { + /*case OAuthFlow.ACCESS_CODE: + _grantType = "authorization_code"; + break; + case OAuthFlow.IMPLICIT: + _grantType = "implicit"; + break; + case OAuthFlow.PASSWORD: + _grantType = "password"; + break;*/ + case OAuthFlow.APPLICATION: + _grantType = "client_credentials"; + break; + default: + break; + } + } + + /// + /// Creates an authentication parameter from an access token. + /// + /// Access token to create a parameter from. + /// An authentication parameter. + protected override async ValueTask GetAuthenticationParameter(string accessToken) + { + var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token; + return new HeaderParameter(KnownHeaders.Authorization, token); + } + + /// + /// Gets the token from the OAuth2 server. + /// + /// An authentication token. + async Task GetToken() + { + var client = new RestClient(_tokenUrl) + .UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration)); + + var request = new RestRequest() + .AddParameter("grant_type", _grantType) + .AddParameter("client_id", _clientId) + .AddParameter("client_secret", _clientSecret); + var response = await client.PostAsync(request); + return $"{response.TokenType} {response.AccessToken}"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs new file mode 100644 index 0000000000..2e1adf9300 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Auth/OAuthFlow.cs @@ -0,0 +1,27 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client.Auth +{ + /// + /// Available flows for OAuth2 authentication + /// + public enum OAuthFlow + { + /// Authorization code flow + ACCESS_CODE, + /// Implicit flow + IMPLICIT, + /// Password flow + PASSWORD, + /// Client credentials flow + APPLICATION + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs new file mode 100644 index 0000000000..21fd27c376 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Auth/TokenResponse.cs @@ -0,0 +1,22 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Client.Auth +{ + class TokenResponse + { + [JsonProperty("token_type")] + public string TokenType { get; set; } + [JsonProperty("access_token")] + public string AccessToken { get; set; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs index 494b55f852..21fe44c8df 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -120,6 +120,16 @@ namespace Org.OpenAPITools.Client return Convert.ToString(obj, CultureInfo.InvariantCulture); } + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + /// /// Encode string in base64 format. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Configuration.cs index f78ad83459..a5cbd551f9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Configuration.cs @@ -17,6 +17,8 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Net.Http; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -108,7 +110,7 @@ namespace Org.OpenAPITools.Client public Configuration() { Proxy = null; - UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); BasePath = "http://petstore.swagger.io/v2"; DefaultHeaders = new ConcurrentDictionary(); ApiKey = new ConcurrentDictionary(); @@ -261,6 +263,30 @@ namespace Org.OpenAPITools.Client /// The access token. public virtual string AccessToken { get; set; } + /// + /// Gets or sets the token URL for OAuth2 authentication. + /// + /// The OAuth Token URL. + public virtual string OAuthTokenUrl { get; set; } + + /// + /// Gets or sets the client ID for OAuth2 authentication. + /// + /// The OAuth Client ID. + public virtual string OAuthClientId { get; set; } + + /// + /// Gets or sets the client secret for OAuth2 authentication. + /// + /// The OAuth Client Secret. + public virtual string OAuthClientSecret { get; set; } + + /// + /// Gets or sets the flow for OAuth2 authentication. + /// + /// The OAuth Flow. + public virtual OAuthFlow? OAuthFlow { get; set; } + /// /// Gets or sets the temporary folder path to store the files downloaded from the server. /// @@ -575,6 +601,10 @@ namespace Org.OpenAPITools.Client Username = second.Username ?? first.Username, Password = second.Password ?? first.Password, AccessToken = second.AccessToken ?? first.AccessToken, + OAuthTokenUrl = second.OAuthTokenUrl ?? first.OAuthTokenUrl, + OAuthClientId = second.OAuthClientId ?? first.OAuthClientId, + OAuthClientSecret = second.OAuthClientSecret ?? first.OAuthClientSecret, + OAuthFlow = second.OAuthFlow ?? first.OAuthFlow, TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, ClientCertificates = second.ClientCertificates ?? first.ClientCertificates, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IReadableConfiguration.cs index ab9e745604..e8d6b0bd39 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IReadableConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; using System.Net; using System.Security.Cryptography.X509Certificates; +using Org.OpenAPITools.Client.Auth; namespace Org.OpenAPITools.Client { @@ -26,6 +27,30 @@ namespace Org.OpenAPITools.Client /// Access token. string AccessToken { get; } + /// + /// Gets the OAuth token URL. + /// + /// OAuth Token URL. + string OAuthTokenUrl { get; } + + /// + /// Gets the OAuth client ID. + /// + /// OAuth Client ID. + string OAuthClientId { get; } + + /// + /// Gets the OAuth client secret. + /// + /// OAuth Client Secret. + string OAuthClientSecret { get; } + + /// + /// Gets the OAuth flow. + /// + /// OAuth Flow. + OAuthFlow? OAuthFlow { get; } + /// /// Gets the API key. /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RequestOptions.cs index a4cca0b5b1..aef6b76e95 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -68,6 +68,11 @@ namespace Org.OpenAPITools.Client /// public Object Data { get; set; } + /// + /// If request should be authenticated with OAuth. + /// + public bool OAuth { get; set; } + /// /// Constructs a new instance of /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RetryConfiguration.cs index 92d8f878ca..f9141a1000 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RetryConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -21,11 +21,11 @@ namespace Org.OpenAPITools.Client /// /// Retry policy /// - public static Policy RetryPolicy { get; set; } + public static Policy RetryPolicy { get; set; } /// /// Async retry policy /// - public static AsyncPolicy AsyncRetryPolicy { get; set; } + public static AsyncPolicy AsyncRetryPolicy { get; set; } } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Pet.cs index 3ebe0c561d..feaf8650e2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Pet.cs @@ -116,13 +116,13 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets Name /// - [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = true)] public string Name { get; set; } /// /// Gets or Sets PhotoUrls /// - [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)] + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = true)] public List PhotoUrls { get; set; } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 5c6f6f4124..5d87b999ec 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,11 +21,17 @@ - + - + + + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient/docs/EnumArrays.md b/samples/client/petstore/csharp/OpenAPIClient/docs/EnumArrays.md index 9d58d25f97..880e2248c9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/docs/EnumArrays.md +++ b/samples/client/petstore/csharp/OpenAPIClient/docs/EnumArrays.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **JustSymbol** | **string** | | [optional] -**ArrayEnum** | **List<string>** | | [optional] +**ArrayEnum** | **List<EnumArrays.ArrayEnumEnum>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) diff --git a/samples/client/petstore/csharp/OpenAPIClient/docs/MapTest.md b/samples/client/petstore/csharp/OpenAPIClient/docs/MapTest.md index 79d499e2cf..654ac32583 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/docs/MapTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient/docs/MapTest.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] -**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**MapOfEnumString** | **Dictionary<string, MapTest.InnerEnum>** | | [optional] **DirectMap** | **Dictionary<string, bool>** | | [optional] **IndirectMap** | **Dictionary<string, bool>** | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/AllOfWithSingleRef.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/AllOfWithSingleRef.cs index dcd135e949..1cce653b43 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/AllOfWithSingleRef.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/AllOfWithSingleRef.cs @@ -33,7 +33,7 @@ namespace Org.OpenAPITools.Model /// /// Gets or Sets SingleRefType /// - [DataMember(Name="SingleRefType", EmitDefaultValue=true)] + [DataMember(Name="SingleRefType", EmitDefaultValue=false)] public SingleRefType? SingleRefType { get; set; } /// /// Initializes a new instance of the class. @@ -42,7 +42,6 @@ namespace Org.OpenAPITools.Model /// singleRefType. public AllOfWithSingleRef(string username = default(string), SingleRefType? singleRefType = default(SingleRefType?)) { - this.SingleRefType = singleRefType; this.Username = username; this.SingleRefType = singleRefType; } diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs index 75c484e6bf..a7d37ba157 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -75,12 +75,6 @@ namespace Org.OpenAPITools.Model } - - /// - /// Gets or Sets ArrayEnum - /// - [DataMember(Name="array_enum", EmitDefaultValue=false)] - public List ArrayEnum { get; set; } /// /// Initializes a new instance of the class. /// @@ -93,6 +87,11 @@ namespace Org.OpenAPITools.Model } + /// + /// Gets or Sets ArrayEnum + /// + [DataMember(Name="array_enum", EmitDefaultValue=false)] + public List ArrayEnum { get; set; } /// /// Returns the string presentation of the object diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs index 7382ac573f..b84ccd0e27 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs @@ -50,12 +50,6 @@ namespace Org.OpenAPITools.Model } - - /// - /// Gets or Sets MapOfEnumString - /// - [DataMember(Name="map_of_enum_string", EmitDefaultValue=false)] - public Dictionary MapOfEnumString { get; set; } /// /// Initializes a new instance of the class. /// @@ -77,6 +71,11 @@ namespace Org.OpenAPITools.Model [DataMember(Name="map_map_of_string", EmitDefaultValue=false)] public Dictionary> MapMapOfString { get; set; } + /// + /// Gets or Sets MapOfEnumString + /// + [DataMember(Name="map_of_enum_string", EmitDefaultValue=false)] + public Dictionary MapOfEnumString { get; set; } /// /// Gets or Sets DirectMap diff --git a/samples/client/petstore/elixir/.gitignore b/samples/client/petstore/elixir/.gitignore index b6012c77a3..5aa3f68181 100644 --- a/samples/client/petstore/elixir/.gitignore +++ b/samples/client/petstore/elixir/.gitignore @@ -18,3 +18,6 @@ erl_crash.dump # Also ignore archive artifacts (built via "mix archive.build"). *.ez + +# Ignore elixir LS +/.elixir_ls diff --git a/samples/client/petstore/elixir/README.md b/samples/client/petstore/elixir/README.md index 42caba912a..898f669267 100644 --- a/samples/client/petstore/elixir/README.md +++ b/samples/client/petstore/elixir/README.md @@ -2,33 +2,46 @@ This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ -### Building +## Building To install the required dependencies and to build the elixir project, run: -``` + +```console mix local.hex --force mix do deps.get, compile ``` ## Installation -If [available in Hex](https://hex.pm/docs/publish), the package can be installed -by adding `openapi_petstore` to your list of dependencies in `mix.exs`: +If [available in Hex][], the package can be installed by adding `openapi_petstore` to +your list of dependencies in `mix.exs`: ```elixir def deps do - [{:openapi_petstore, "~> 0.1.0"}] + [{:openapi_petstore, "~> 1.0.0"}] end ``` -Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) -and published on [HexDocs](https://hexdocs.pm). Once published, the docs can -be found at [https://hexdocs.pm/openapi_petstore](https://hexdocs.pm/openapi_petstore). - +Documentation can be generated with [ExDoc][] and published on [HexDocs][]. Once published, the docs can be found at +[https://hexdocs.pm/openapi_petstore][docs]. ## Configuration -You can override the URL of your server (e.g. if you have a separate development and production server in your configuration files. +You can override the URL of your server (e.g. if you have a separate development and production server in your +configuration files). + ```elixir -config :open_api_petstore, base_url: "http://petstore.swagger.io:80/v2" -``` \ No newline at end of file +config :openapi_petstore, base_url: "http://petstore.swagger.io:80/v2" +``` + +Multiple clients for the same API with different URLs can be created passing different `base_url`s when calling +`OpenapiPetstore.Connection.new/1`: + +```elixir +client = OpenapiPetstore.Connection.new(base_url: "http://petstore.swagger.io:80/v2") +``` + +[exdoc]: https://github.com/elixir-lang/ex_doc +[hexdocs]: https://hexdocs.pm +[available in hex]: https://hex.pm/docs/publish +[docs]: https://hexdocs.pm/openapi_petstore diff --git a/samples/client/petstore/elixir/config/config.exs b/samples/client/petstore/elixir/config/config.exs index 6056f2411d..a6e7708580 100644 --- a/samples/client/petstore/elixir/config/config.exs +++ b/samples/client/petstore/elixir/config/config.exs @@ -7,7 +7,7 @@ # General application configuration import Config -config :open_api_petstore, base_url: "http://petstore.swagger.io:80/v2" +config :openapi_petstore, base_url: "http://petstore.swagger.io:80/v2" # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. diff --git a/samples/client/petstore/elixir/config/runtime.exs b/samples/client/petstore/elixir/config/runtime.exs index a034b2dac4..9fcc3ea00a 100644 --- a/samples/client/petstore/elixir/config/runtime.exs +++ b/samples/client/petstore/elixir/config/runtime.exs @@ -7,6 +7,6 @@ import Config # any compile-time configuration in here, as it won't be applied. # The block below contains prod specific runtime configuration. -if env = System.get_env("OPEN_API_PETSTORE_BASE_URI") do - config :open_api_petstore, base_url: env +if base_url = System.get_env("OPENAPI_PETSTORE_BASE_URI") do + config :openapi_petstore, base_url: base_url end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/another_fake.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/another_fake.ex index 110b399f33..75f9d2df76 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/another_fake.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/another_fake.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Api.AnotherFake do @moduledoc """ @@ -10,31 +9,34 @@ defmodule OpenapiPetstore.Api.AnotherFake do alias OpenapiPetstore.Connection import OpenapiPetstore.RequestBuilder - @doc """ To test special tags To test special tags and operation ID starting with number - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - client (Client): client model - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `client` (Client): client model + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.Client.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.Client.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec call_123_test_special_tags(Tesla.Env.client, OpenapiPetstore.Model.Client.t, keyword()) :: {:ok, OpenapiPetstore.Model.Client.t} | {:error, Tesla.Env.t} def call_123_test_special_tags(connection, client, _opts \\ []) do - %{} - |> method(:patch) - |> url("/another-fake/dummy") - |> add_param(:body, :body, client) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:patch) + |> url("/another-fake/dummy") + |> add_param(:body, :body, client) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.Client{}} + {200, %OpenapiPetstore.Model.Client{}} ]) end end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/default.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/default.ex index 6432938ee0..4aaaf57307 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/default.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/default.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Api.Default do @moduledoc """ @@ -10,27 +9,30 @@ defmodule OpenapiPetstore.Api.Default do alias OpenapiPetstore.Connection import OpenapiPetstore.RequestBuilder - @doc """ - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.FooGetDefaultResponse.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.FooGetDefaultResponse.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec foo_get(Tesla.Env.client, keyword()) :: {:ok, OpenapiPetstore.Model.FooGetDefaultResponse.t} | {:error, Tesla.Env.t} def foo_get(connection, _opts \\ []) do - %{} - |> method(:get) - |> url("/foo") - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/foo") + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { :default, %OpenapiPetstore.Model.FooGetDefaultResponse{}} + {:default, %OpenapiPetstore.Model.FooGetDefaultResponse{}} ]) end end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex index 1d2b32abc9..e6be5c554c 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Api.Fake do @moduledoc """ @@ -10,45 +9,49 @@ defmodule OpenapiPetstore.Api.Fake do alias OpenapiPetstore.Connection import OpenapiPetstore.RequestBuilder - @doc """ Health check endpoint - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.HealthCheckResult.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.HealthCheckResult.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec fake_health_get(Tesla.Env.client, keyword()) :: {:ok, OpenapiPetstore.Model.HealthCheckResult.t} | {:error, Tesla.Env.t} def fake_health_get(connection, _opts \\ []) do - %{} - |> method(:get) - |> url("/fake/health") - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/fake/health") + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.HealthCheckResult{}} + {200, %OpenapiPetstore.Model.HealthCheckResult{}} ]) end @doc """ test http signature authentication - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - pet (Pet): Pet object that needs to be added to the store - - opts (KeywordList): [optional] Optional parameters - - :query1 (String.t): query parameter - - :header1 (String.t): header parameter - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `pet` (Pet): Pet object that needs to be added to the store + - `opts` (keyword): Optional parameters + - `:query_1` (String.t): query parameter + - `:header_1` (String.t): header parameter - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec fake_http_signature_test(Tesla.Env.client, OpenapiPetstore.Model.Pet.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def fake_http_signature_test(connection, pet, opts \\ []) do @@ -56,240 +59,280 @@ defmodule OpenapiPetstore.Api.Fake do :query_1 => :query, :header_1 => :headers } - %{} - |> method(:get) - |> url("/fake/http-signature-test") - |> add_param(:body, :body, pet) - |> add_optional_params(optional_params, opts) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:get) + |> url("/fake/http-signature-test") + |> add_param(:body, :body, pet) + |> add_optional_params(optional_params, opts) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end @doc """ Test serialization of outer boolean types - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - opts (KeywordList): [optional] Optional parameters - - :body (boolean()): Input boolean as post body - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `opts` (keyword): Optional parameters + - `:body` (boolean()): Input boolean as post body - {:ok, boolean()} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, boolean()}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec fake_outer_boolean_serialize(Tesla.Env.client, keyword()) :: {:ok, Boolean.t} | {:error, Tesla.Env.t} def fake_outer_boolean_serialize(connection, opts \\ []) do optional_params = %{ :body => :body } - %{} - |> method(:post) - |> url("/fake/outer/boolean") - |> add_optional_params(optional_params, opts) - |> ensure_body() - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:post) + |> url("/fake/outer/boolean") + |> add_optional_params(optional_params, opts) + |> ensure_body() + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end @doc """ Test serialization of object with outer number type - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - opts (KeywordList): [optional] Optional parameters - - :body (OuterComposite): Input composite as post body - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `opts` (keyword): Optional parameters + - `:body` (OuterComposite): Input composite as post body - {:ok, OpenapiPetstore.Model.OuterComposite.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.OuterComposite.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec fake_outer_composite_serialize(Tesla.Env.client, keyword()) :: {:ok, OpenapiPetstore.Model.OuterComposite.t} | {:error, Tesla.Env.t} def fake_outer_composite_serialize(connection, opts \\ []) do optional_params = %{ :body => :body } - %{} - |> method(:post) - |> url("/fake/outer/composite") - |> add_optional_params(optional_params, opts) - |> ensure_body() - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:post) + |> url("/fake/outer/composite") + |> add_optional_params(optional_params, opts) + |> ensure_body() + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.OuterComposite{}} + {200, %OpenapiPetstore.Model.OuterComposite{}} ]) end @doc """ Test serialization of outer number types - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - opts (KeywordList): [optional] Optional parameters - - :body (float()): Input number as post body - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `opts` (keyword): Optional parameters + - `:body` (float()): Input number as post body - {:ok, float()} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, float()}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec fake_outer_number_serialize(Tesla.Env.client, keyword()) :: {:ok, Float.t} | {:error, Tesla.Env.t} def fake_outer_number_serialize(connection, opts \\ []) do optional_params = %{ :body => :body } - %{} - |> method(:post) - |> url("/fake/outer/number") - |> add_optional_params(optional_params, opts) - |> ensure_body() - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:post) + |> url("/fake/outer/number") + |> add_optional_params(optional_params, opts) + |> ensure_body() + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end @doc """ Test serialization of outer string types - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - opts (KeywordList): [optional] Optional parameters - - :body (String.t): Input string as post body - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `opts` (keyword): Optional parameters + - `:body` (String.t): Input string as post body - {:ok, String.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, String.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec fake_outer_string_serialize(Tesla.Env.client, keyword()) :: {:ok, String.t} | {:error, Tesla.Env.t} def fake_outer_string_serialize(connection, opts \\ []) do optional_params = %{ :body => :body } - %{} - |> method(:post) - |> url("/fake/outer/string") - |> add_optional_params(optional_params, opts) - |> ensure_body() - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:post) + |> url("/fake/outer/string") + |> add_optional_params(optional_params, opts) + |> ensure_body() + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end @doc """ Test serialization of enum (int) properties with examples - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - outer_object_with_enum_property (OuterObjectWithEnumProperty): Input enum (int) as post body - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `outer_object_with_enum_property` (OuterObjectWithEnumProperty): Input enum (int) as post body + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.OuterObjectWithEnumProperty.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.OuterObjectWithEnumProperty.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec fake_property_enum_integer_serialize(Tesla.Env.client, OpenapiPetstore.Model.OuterObjectWithEnumProperty.t, keyword()) :: {:ok, OpenapiPetstore.Model.OuterObjectWithEnumProperty.t} | {:error, Tesla.Env.t} def fake_property_enum_integer_serialize(connection, outer_object_with_enum_property, _opts \\ []) do - %{} - |> method(:post) - |> url("/fake/property/enum-int") - |> add_param(:body, :body, outer_object_with_enum_property) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:post) + |> url("/fake/property/enum-int") + |> add_param(:body, :body, outer_object_with_enum_property) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.OuterObjectWithEnumProperty{}} + {200, %OpenapiPetstore.Model.OuterObjectWithEnumProperty{}} ]) end @doc """ For this test, the body has to be a binary file. - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - body (String.t): image to upload - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `body` (String.t): image to upload + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_body_with_binary(Tesla.Env.client, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def test_body_with_binary(connection, body, _opts \\ []) do - %{} - |> method(:put) - |> url("/fake/body-with-binary") - |> add_param(:body, :body, body) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:put) + |> url("/fake/body-with-binary") + |> add_param(:body, :body, body) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end @doc """ For this test, the body for this request must reference a schema named `File`. - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - file_schema_test_class (FileSchemaTestClass): - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `file_schema_test_class` (FileSchemaTestClass): + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_body_with_file_schema(Tesla.Env.client, OpenapiPetstore.Model.FileSchemaTestClass.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def test_body_with_file_schema(connection, file_schema_test_class, _opts \\ []) do - %{} - |> method(:put) - |> url("/fake/body-with-file-schema") - |> add_param(:body, :body, file_schema_test_class) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:put) + |> url("/fake/body-with-file-schema") + |> add_param(:body, :body, file_schema_test_class) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end @doc """ - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - query (String.t): - - user (User): - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `query` (String.t): + - `user` (User): + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_body_with_query_params(Tesla.Env.client, String.t, OpenapiPetstore.Model.User.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def test_body_with_query_params(connection, query, user, _opts \\ []) do - %{} - |> method(:put) - |> url("/fake/body-with-query-params") - |> add_param(:query, :query, query) - |> add_param(:body, :body, user) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:put) + |> url("/fake/body-with-query-params") + |> add_param(:query, :query, query) + |> add_param(:body, :body, user) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end @@ -297,26 +340,30 @@ defmodule OpenapiPetstore.Api.Fake do To test \"client\" model To test \"client\" model - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - client (Client): client model - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `client` (Client): client model + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.Client.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.Client.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_client_model(Tesla.Env.client, OpenapiPetstore.Model.Client.t, keyword()) :: {:ok, OpenapiPetstore.Model.Client.t} | {:error, Tesla.Env.t} def test_client_model(connection, client, _opts \\ []) do - %{} - |> method(:patch) - |> url("/fake") - |> add_param(:body, :body, client) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:patch) + |> url("/fake") + |> add_param(:body, :body, client) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.Client{}} + {200, %OpenapiPetstore.Model.Client{}} ]) end @@ -324,28 +371,29 @@ defmodule OpenapiPetstore.Api.Fake do Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - number (float()): None - - double (float()): None - - pattern_without_delimiter (String.t): None - - byte (binary()): None - - opts (KeywordList): [optional] Optional parameters - - :integer (integer()): None - - :int32 (integer()): None - - :int64 (integer()): None - - :float (float()): None - - :string (String.t): None - - :binary (String.t): None - - :date (Date.t): None - - :date_time (DateTime.t): None - - :password (String.t): None - - :callback (String.t): None - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `number` (float()): None + - `double` (float()): None + - `pattern_without_delimiter` (String.t): None + - `byte` (binary()): None + - `opts` (keyword): Optional parameters + - `:integer` (integer()): None + - `:int32` (integer()): None + - `:int64` (integer()): None + - `:float` (float()): None + - `:string` (String.t): None + - `:binary` (String.t): None + - `:date` (Date.t): None + - `:dateTime` (DateTime.t): None + - `:password` (String.t): None + - `:callback` (String.t): None - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_endpoint_parameters(Tesla.Env.client, float(), float(), String.t, binary(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def test_endpoint_parameters(connection, number, double, pattern_without_delimiter, byte, opts \\ []) do @@ -361,19 +409,23 @@ defmodule OpenapiPetstore.Api.Fake do :password => :form, :callback => :form } - %{} - |> method(:post) - |> url("/fake") - |> add_param(:form, :number, number) - |> add_param(:form, :double, double) - |> add_param(:form, :pattern_without_delimiter, pattern_without_delimiter) - |> add_param(:form, :byte, byte) - |> add_optional_params(optional_params, opts) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:post) + |> url("/fake") + |> add_param(:form, :number, number) + |> add_param(:form, :double, double) + |> add_param(:form, :pattern_without_delimiter, pattern_without_delimiter) + |> add_param(:form, :byte, byte) + |> add_optional_params(optional_params, opts) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 400, false}, - { 404, false} + {400, false}, + {404, false} ]) end @@ -381,23 +433,24 @@ defmodule OpenapiPetstore.Api.Fake do To test enum parameters To test enum parameters - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - opts (KeywordList): [optional] Optional parameters - - :enum_header_string_array ([String.t]): Header parameter enum test (string array) - - :enum_header_string (String.t): Header parameter enum test (string) - - :enum_query_string_array ([String.t]): Query parameter enum test (string array) - - :enum_query_string (String.t): Query parameter enum test (string) - - :enum_query_integer (integer()): Query parameter enum test (double) - - :enum_query_double (float()): Query parameter enum test (double) - - :enum_query_model_array ([OpenapiPetstore.Model.EnumClass.t]): - - :enum_form_string_array ([String.t]): Form parameter enum test (string array) - - :enum_form_string (String.t): Form parameter enum test (string) - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `opts` (keyword): Optional parameters + - `:enum_header_string_array` ([String.t]): Header parameter enum test (string array) + - `:enum_header_string` (String.t): Header parameter enum test (string) + - `:enum_query_string_array` ([String.t]): Query parameter enum test (string array) + - `:enum_query_string` (String.t): Query parameter enum test (string) + - `:enum_query_integer` (integer()): Query parameter enum test (double) + - `:enum_query_double` (float()): Query parameter enum test (double) + - `:enum_query_model_array` ([OpenapiPetstore.Model.EnumClass.t]): + - `:enum_form_string_array` ([String.t]): Form parameter enum test (string array) + - `:enum_form_string` (String.t): Form parameter enum test (string) - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_enum_parameters(Tesla.Env.client, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def test_enum_parameters(connection, opts \\ []) do @@ -412,15 +465,19 @@ defmodule OpenapiPetstore.Api.Fake do :enum_form_string_array => :form, :enum_form_string => :form } - %{} - |> method(:get) - |> url("/fake") - |> add_optional_params(optional_params, opts) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:get) + |> url("/fake") + |> add_optional_params(optional_params, opts) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 400, false}, - { 404, false} + {400, false}, + {404, false} ]) end @@ -428,20 +485,21 @@ defmodule OpenapiPetstore.Api.Fake do Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - required_string_group (integer()): Required String in group parameters - - required_boolean_group (boolean()): Required Boolean in group parameters - - required_int64_group (integer()): Required Integer in group parameters - - opts (KeywordList): [optional] Optional parameters - - :string_group (integer()): String in group parameters - - :boolean_group (boolean()): Boolean in group parameters - - :int64_group (integer()): Integer in group parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `required_string_group` (integer()): Required String in group parameters + - `required_boolean_group` (boolean()): Required Boolean in group parameters + - `required_int64_group` (integer()): Required Integer in group parameters + - `opts` (keyword): Optional parameters + - `:string_group` (integer()): String in group parameters + - `:boolean_group` (boolean()): Boolean in group parameters + - `:int64_group` (integer()): Integer in group parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_group_parameters(Tesla.Env.client, integer(), boolean(), integer(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def test_group_parameters(connection, required_string_group, required_boolean_group, required_int64_group, opts \\ []) do @@ -450,17 +508,21 @@ defmodule OpenapiPetstore.Api.Fake do :boolean_group => :headers, :int64_group => :query } - %{} - |> method(:delete) - |> url("/fake") - |> add_param(:query, :required_string_group, required_string_group) - |> add_param(:headers, :required_boolean_group, required_boolean_group) - |> add_param(:query, :required_int64_group, required_int64_group) - |> add_optional_params(optional_params, opts) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:delete) + |> url("/fake") + |> add_param(:query, :required_string_group, required_string_group) + |> add_param(:headers, :required_boolean_group, required_boolean_group) + |> add_param(:query, :required_int64_group, required_int64_group) + |> add_optional_params(optional_params, opts) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 400, false} + {400, false} ]) end @@ -468,26 +530,30 @@ defmodule OpenapiPetstore.Api.Fake do test inline additionalProperties - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - request_body (%{optional(String.t) => String.t}): request body - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `request_body` (%{optional(String.t) => String.t}): request body + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_inline_additional_properties(Tesla.Env.client, %{optional(String.t) => String.t}, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def test_inline_additional_properties(connection, request_body, _opts \\ []) do - %{} - |> method(:post) - |> url("/fake/inline-additionalProperties") - |> add_param(:body, :body, request_body) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:post) + |> url("/fake/inline-additionalProperties") + |> add_param(:body, :body, request_body) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end @@ -495,70 +561,79 @@ defmodule OpenapiPetstore.Api.Fake do test json serialization of form data - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - param (String.t): field1 - - param2 (String.t): field2 - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `param` (String.t): field1 + - `param2` (String.t): field2 + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_json_form_data(Tesla.Env.client, String.t, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def test_json_form_data(connection, param, param2, _opts \\ []) do - %{} - |> method(:get) - |> url("/fake/jsonFormData") - |> add_param(:form, :param, param) - |> add_param(:form, :param2, param2) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/fake/jsonFormData") + |> add_param(:form, :param, param) + |> add_param(:form, :param2, param2) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end @doc """ To test the collection format in query parameters - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - pipe ([String.t]): - - ioutil ([String.t]): - - http ([String.t]): - - url ([String.t]): - - context ([String.t]): - - allow_empty (String.t): - - opts (KeywordList): [optional] Optional parameters - - :language (%{optional(String.t) => String.t}): - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `pipe` ([String.t]): + - `ioutil` ([String.t]): + - `http` ([String.t]): + - `url` ([String.t]): + - `context` ([String.t]): + - `allow_empty` (String.t): + - `opts` (keyword): Optional parameters + - `:language` (%{optional(String.t) => String.t}): - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_query_parameter_collection_format(Tesla.Env.client, list(String.t), list(String.t), list(String.t), list(String.t), list(String.t), String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def test_query_parameter_collection_format(connection, pipe, ioutil, http, url, context, allow_empty, opts \\ []) do optional_params = %{ :language => :query } - %{} - |> method(:put) - |> url("/fake/test-query-parameters") - |> add_param(:query, :pipe, pipe) - |> add_param(:query, :ioutil, ioutil) - |> add_param(:query, :http, http) - |> add_param(:query, :url, url) - |> add_param(:query, :context, context) - |> add_param(:query, :allowEmpty, allow_empty) - |> add_optional_params(optional_params, opts) - |> ensure_body() - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:put) + |> url("/fake/test-query-parameters") + |> add_param(:query, :pipe, pipe) + |> add_param(:query, :ioutil, ioutil) + |> add_param(:query, :http, http) + |> add_param(:query, :url, url) + |> add_param(:query, :context, context) + |> add_param(:query, :allowEmpty, allow_empty) + |> add_optional_params(optional_params, opts) + |> ensure_body() + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false} + {200, false} ]) end end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake_classname_tags123.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake_classname_tags123.ex index fd202abac6..7306d63b5a 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake_classname_tags123.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake_classname_tags123.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Api.FakeClassnameTags123 do @moduledoc """ @@ -10,31 +9,34 @@ defmodule OpenapiPetstore.Api.FakeClassnameTags123 do alias OpenapiPetstore.Connection import OpenapiPetstore.RequestBuilder - @doc """ To test class name in snake case To test class name in snake case - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - client (Client): client model - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `client` (Client): client model + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.Client.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.Client.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec test_classname(Tesla.Env.client, OpenapiPetstore.Model.Client.t, keyword()) :: {:ok, OpenapiPetstore.Model.Client.t} | {:error, Tesla.Env.t} def test_classname(connection, client, _opts \\ []) do - %{} - |> method(:patch) - |> url("/fake_classname_test") - |> add_param(:body, :body, client) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:patch) + |> url("/fake_classname_test") + |> add_param(:body, :body, client) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.Client{}} + {200, %OpenapiPetstore.Model.Client{}} ]) end end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/pet.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/pet.ex index acc415d75a..73a04e6da5 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/pet.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/pet.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Api.Pet do @moduledoc """ @@ -10,32 +9,35 @@ defmodule OpenapiPetstore.Api.Pet do alias OpenapiPetstore.Connection import OpenapiPetstore.RequestBuilder - @doc """ Add a new pet to the store - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - pet (Pet): Pet object that needs to be added to the store - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `pet` (Pet): Pet object that needs to be added to the store + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec add_pet(Tesla.Env.client, OpenapiPetstore.Model.Pet.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def add_pet(connection, pet, _opts \\ []) do - %{} - |> method(:post) - |> url("/pet") - |> add_param(:body, :body, pet) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:post) + |> url("/pet") + |> add_param(:body, :body, pet) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false}, - { 405, false} + {200, false}, + {405, false} ]) end @@ -43,31 +45,36 @@ defmodule OpenapiPetstore.Api.Pet do Deletes a pet - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - pet_id (integer()): Pet id to delete - - opts (KeywordList): [optional] Optional parameters - - :api_key (String.t): - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `pet_id` (integer()): Pet id to delete + - `opts` (keyword): Optional parameters + - `:api_key` (String.t): - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec delete_pet(Tesla.Env.client, integer(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def delete_pet(connection, pet_id, opts \\ []) do optional_params = %{ :api_key => :headers } - %{} - |> method(:delete) - |> url("/pet/#{pet_id}") - |> add_optional_params(optional_params, opts) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:delete) + |> url("/pet/#{pet_id}") + |> add_optional_params(optional_params, opts) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false}, - { 400, false} + {200, false}, + {400, false} ]) end @@ -75,27 +82,31 @@ defmodule OpenapiPetstore.Api.Pet do Finds Pets by status Multiple status values can be provided with comma separated strings - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - status ([String.t]): Status values that need to be considered for filter - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `status` ([String.t]): Status values that need to be considered for filter + - `opts` (keyword): Optional parameters - {:ok, [%Pet{}, ...]} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, [%Pet{}, ...]}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec find_pets_by_status(Tesla.Env.client, list(String.t), keyword()) :: {:ok, nil} | {:ok, list(OpenapiPetstore.Model.Pet.t)} | {:error, Tesla.Env.t} def find_pets_by_status(connection, status, _opts \\ []) do - %{} - |> method(:get) - |> url("/pet/findByStatus") - |> add_param(:query, :status, status) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/pet/findByStatus") + |> add_param(:query, :status, status) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, [%OpenapiPetstore.Model.Pet{}]}, - { 400, false} + {200, [%OpenapiPetstore.Model.Pet{}]}, + {400, false} ]) end @@ -103,27 +114,31 @@ defmodule OpenapiPetstore.Api.Pet do Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - tags ([String.t]): Tags to filter by - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `tags` ([String.t]): Tags to filter by + - `opts` (keyword): Optional parameters - {:ok, [%Pet{}, ...]} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, [%Pet{}, ...]}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec find_pets_by_tags(Tesla.Env.client, list(String.t), keyword()) :: {:ok, nil} | {:ok, list(OpenapiPetstore.Model.Pet.t)} | {:error, Tesla.Env.t} def find_pets_by_tags(connection, tags, _opts \\ []) do - %{} - |> method(:get) - |> url("/pet/findByTags") - |> add_param(:query, :tags, tags) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/pet/findByTags") + |> add_param(:query, :tags, tags) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, [%OpenapiPetstore.Model.Pet{}]}, - { 400, false} + {200, [%OpenapiPetstore.Model.Pet{}]}, + {400, false} ]) end @@ -131,27 +146,31 @@ defmodule OpenapiPetstore.Api.Pet do Find pet by ID Returns a single pet - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - pet_id (integer()): ID of pet to return - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `pet_id` (integer()): ID of pet to return + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.Pet.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.Pet.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec get_pet_by_id(Tesla.Env.client, integer(), keyword()) :: {:ok, nil} | {:ok, OpenapiPetstore.Model.Pet.t} | {:error, Tesla.Env.t} def get_pet_by_id(connection, pet_id, _opts \\ []) do - %{} - |> method(:get) - |> url("/pet/#{pet_id}") - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/pet/#{pet_id}") + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.Pet{}}, - { 400, false}, - { 404, false} + {200, %OpenapiPetstore.Model.Pet{}}, + {400, false}, + {404, false} ]) end @@ -159,29 +178,33 @@ defmodule OpenapiPetstore.Api.Pet do Update an existing pet - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - pet (Pet): Pet object that needs to be added to the store - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `pet` (Pet): Pet object that needs to be added to the store + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec update_pet(Tesla.Env.client, OpenapiPetstore.Model.Pet.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def update_pet(connection, pet, _opts \\ []) do - %{} - |> method(:put) - |> url("/pet") - |> add_param(:body, :body, pet) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:put) + |> url("/pet") + |> add_param(:body, :body, pet) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false}, - { 400, false}, - { 404, false}, - { 405, false} + {200, false}, + {400, false}, + {404, false}, + {405, false} ]) end @@ -189,17 +212,18 @@ defmodule OpenapiPetstore.Api.Pet do Updates a pet in the store with form data - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - pet_id (integer()): ID of pet that needs to be updated - - opts (KeywordList): [optional] Optional parameters - - :name (String.t): Updated name of the pet - - :status (String.t): Updated status of the pet - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `pet_id` (integer()): ID of pet that needs to be updated + - `opts` (keyword): Optional parameters + - `:name` (String.t): Updated name of the pet + - `:status` (String.t): Updated status of the pet - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec update_pet_with_form(Tesla.Env.client, integer(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def update_pet_with_form(connection, pet_id, opts \\ []) do @@ -207,16 +231,20 @@ defmodule OpenapiPetstore.Api.Pet do :name => :form, :status => :form } - %{} - |> method(:post) - |> url("/pet/#{pet_id}") - |> add_optional_params(optional_params, opts) - |> ensure_body() - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:post) + |> url("/pet/#{pet_id}") + |> add_optional_params(optional_params, opts) + |> ensure_body() + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false}, - { 405, false} + {200, false}, + {405, false} ]) end @@ -224,17 +252,18 @@ defmodule OpenapiPetstore.Api.Pet do uploads an image - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - pet_id (integer()): ID of pet to update - - opts (KeywordList): [optional] Optional parameters - - :additional_metadata (String.t): Additional data to pass to server - - :file (String.t): file to upload - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `pet_id` (integer()): ID of pet to update + - `opts` (keyword): Optional parameters + - `:additionalMetadata` (String.t): Additional data to pass to server + - `:file` (String.t): file to upload - {:ok, OpenapiPetstore.Model.ApiResponse.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.ApiResponse.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec upload_file(Tesla.Env.client, integer(), keyword()) :: {:ok, OpenapiPetstore.Model.ApiResponse.t} | {:error, Tesla.Env.t} def upload_file(connection, pet_id, opts \\ []) do @@ -242,15 +271,19 @@ defmodule OpenapiPetstore.Api.Pet do :additionalMetadata => :form, :file => :form } - %{} - |> method(:post) - |> url("/pet/#{pet_id}/uploadImage") - |> add_optional_params(optional_params, opts) - |> ensure_body() - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:post) + |> url("/pet/#{pet_id}/uploadImage") + |> add_optional_params(optional_params, opts) + |> ensure_body() + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.ApiResponse{}} + {200, %OpenapiPetstore.Model.ApiResponse{}} ]) end @@ -258,32 +291,37 @@ defmodule OpenapiPetstore.Api.Pet do uploads an image (required) - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - pet_id (integer()): ID of pet to update - - required_file (String.t): file to upload - - opts (KeywordList): [optional] Optional parameters - - :additional_metadata (String.t): Additional data to pass to server - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `pet_id` (integer()): ID of pet to update + - `required_file` (String.t): file to upload + - `opts` (keyword): Optional parameters + - `:additionalMetadata` (String.t): Additional data to pass to server - {:ok, OpenapiPetstore.Model.ApiResponse.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.ApiResponse.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec upload_file_with_required_file(Tesla.Env.client, integer(), String.t, keyword()) :: {:ok, OpenapiPetstore.Model.ApiResponse.t} | {:error, Tesla.Env.t} def upload_file_with_required_file(connection, pet_id, required_file, opts \\ []) do optional_params = %{ :additionalMetadata => :form } - %{} - |> method(:post) - |> url("/fake/#{pet_id}/uploadImageWithRequiredFile") - |> add_param(:file, :requiredFile, required_file) - |> add_optional_params(optional_params, opts) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + + request = + %{} + |> method(:post) + |> url("/fake/#{pet_id}/uploadImageWithRequiredFile") + |> add_param(:file, :requiredFile, required_file) + |> add_optional_params(optional_params, opts) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.ApiResponse{}} + {200, %OpenapiPetstore.Model.ApiResponse{}} ]) end end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/store.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/store.ex index 8487ba44ca..32d5219580 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/store.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/store.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Api.Store do @moduledoc """ @@ -10,31 +9,34 @@ defmodule OpenapiPetstore.Api.Store do alias OpenapiPetstore.Connection import OpenapiPetstore.RequestBuilder - @doc """ Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - order_id (String.t): ID of the order that needs to be deleted - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `order_id` (String.t): ID of the order that needs to be deleted + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec delete_order(Tesla.Env.client, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def delete_order(connection, order_id, _opts \\ []) do - %{} - |> method(:delete) - |> url("/store/order/#{order_id}") - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:delete) + |> url("/store/order/#{order_id}") + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 400, false}, - { 404, false} + {400, false}, + {404, false} ]) end @@ -42,24 +44,28 @@ defmodule OpenapiPetstore.Api.Store do Returns pet inventories by status Returns a map of status codes to quantities - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `opts` (keyword): Optional parameters - {:ok, %{}} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, %{}}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec get_inventory(Tesla.Env.client, keyword()) :: {:ok, map()} | {:error, Tesla.Env.t} def get_inventory(connection, _opts \\ []) do - %{} - |> method(:get) - |> url("/store/inventory") - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/store/inventory") + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %{}} + {200, %{}} ]) end @@ -67,27 +73,31 @@ defmodule OpenapiPetstore.Api.Store do Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - order_id (integer()): ID of pet that needs to be fetched - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `order_id` (integer()): ID of pet that needs to be fetched + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.Order.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.Order.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec get_order_by_id(Tesla.Env.client, integer(), keyword()) :: {:ok, nil} | {:ok, OpenapiPetstore.Model.Order.t} | {:error, Tesla.Env.t} def get_order_by_id(connection, order_id, _opts \\ []) do - %{} - |> method(:get) - |> url("/store/order/#{order_id}") - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/store/order/#{order_id}") + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.Order{}}, - { 400, false}, - { 404, false} + {200, %OpenapiPetstore.Model.Order{}}, + {400, false}, + {404, false} ]) end @@ -95,27 +105,31 @@ defmodule OpenapiPetstore.Api.Store do Place an order for a pet - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - order (Order): order placed for purchasing the pet - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `order` (Order): order placed for purchasing the pet + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.Order.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.Order.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec place_order(Tesla.Env.client, OpenapiPetstore.Model.Order.t, keyword()) :: {:ok, nil} | {:ok, OpenapiPetstore.Model.Order.t} | {:error, Tesla.Env.t} def place_order(connection, order, _opts \\ []) do - %{} - |> method(:post) - |> url("/store/order") - |> add_param(:body, :body, order) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:post) + |> url("/store/order") + |> add_param(:body, :body, order) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.Order{}}, - { 400, false} + {200, %OpenapiPetstore.Model.Order{}}, + {400, false} ]) end end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/user.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/user.ex index ea436c9e40..46a20a5e39 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/user.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/user.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Api.User do @moduledoc """ @@ -10,31 +9,34 @@ defmodule OpenapiPetstore.Api.User do alias OpenapiPetstore.Connection import OpenapiPetstore.RequestBuilder - @doc """ Create user This can only be done by the logged in user. - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - user (User): Created user object - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `user` (User): Created user object + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec create_user(Tesla.Env.client, OpenapiPetstore.Model.User.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def create_user(connection, user, _opts \\ []) do - %{} - |> method(:post) - |> url("/user") - |> add_param(:body, :body, user) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:post) + |> url("/user") + |> add_param(:body, :body, user) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { :default, false} + {:default, false} ]) end @@ -42,26 +44,30 @@ defmodule OpenapiPetstore.Api.User do Creates list of users with given input array - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - user ([OpenapiPetstore.Model.User.t]): List of user object - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `user` ([OpenapiPetstore.Model.User.t]): List of user object + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec create_users_with_array_input(Tesla.Env.client, list(OpenapiPetstore.Model.User.t), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def create_users_with_array_input(connection, user, _opts \\ []) do - %{} - |> method(:post) - |> url("/user/createWithArray") - |> add_param(:body, :body, user) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:post) + |> url("/user/createWithArray") + |> add_param(:body, :body, user) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { :default, false} + {:default, false} ]) end @@ -69,26 +75,30 @@ defmodule OpenapiPetstore.Api.User do Creates list of users with given input array - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - user ([OpenapiPetstore.Model.User.t]): List of user object - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `user` ([OpenapiPetstore.Model.User.t]): List of user object + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec create_users_with_list_input(Tesla.Env.client, list(OpenapiPetstore.Model.User.t), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def create_users_with_list_input(connection, user, _opts \\ []) do - %{} - |> method(:post) - |> url("/user/createWithList") - |> add_param(:body, :body, user) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:post) + |> url("/user/createWithList") + |> add_param(:body, :body, user) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { :default, false} + {:default, false} ]) end @@ -96,26 +106,30 @@ defmodule OpenapiPetstore.Api.User do Delete user This can only be done by the logged in user. - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - username (String.t): The name that needs to be deleted - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `username` (String.t): The name that needs to be deleted + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec delete_user(Tesla.Env.client, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def delete_user(connection, username, _opts \\ []) do - %{} - |> method(:delete) - |> url("/user/#{username}") - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:delete) + |> url("/user/#{username}") + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 400, false}, - { 404, false} + {400, false}, + {404, false} ]) end @@ -123,27 +137,31 @@ defmodule OpenapiPetstore.Api.User do Get user by user name - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - username (String.t): The name that needs to be fetched. Use user1 for testing. - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `username` (String.t): The name that needs to be fetched. Use user1 for testing. + - `opts` (keyword): Optional parameters - {:ok, OpenapiPetstore.Model.User.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, OpenapiPetstore.Model.User.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec get_user_by_name(Tesla.Env.client, String.t, keyword()) :: {:ok, nil} | {:ok, OpenapiPetstore.Model.User.t} | {:error, Tesla.Env.t} def get_user_by_name(connection, username, _opts \\ []) do - %{} - |> method(:get) - |> url("/user/#{username}") - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/user/#{username}") + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, %OpenapiPetstore.Model.User{}}, - { 400, false}, - { 404, false} + {200, %OpenapiPetstore.Model.User{}}, + {400, false}, + {404, false} ]) end @@ -151,29 +169,33 @@ defmodule OpenapiPetstore.Api.User do Logs user into the system - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - username (String.t): The user name for login - - password (String.t): The password for login in clear text - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `username` (String.t): The user name for login + - `password` (String.t): The password for login in clear text + - `opts` (keyword): Optional parameters - {:ok, String.t} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, String.t}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec login_user(Tesla.Env.client, String.t, String.t, keyword()) :: {:ok, nil} | {:ok, String.t} | {:error, Tesla.Env.t} def login_user(connection, username, password, _opts \\ []) do - %{} - |> method(:get) - |> url("/user/login") - |> add_param(:query, :username, username) - |> add_param(:query, :password, password) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/user/login") + |> add_param(:query, :username, username) + |> add_param(:query, :password, password) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 200, false}, - { 400, false} + {200, false}, + {400, false} ]) end @@ -181,24 +203,28 @@ defmodule OpenapiPetstore.Api.User do Logs out current logged in user session - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec logout_user(Tesla.Env.client, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def logout_user(connection, _opts \\ []) do - %{} - |> method(:get) - |> url("/user/logout") - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:get) + |> url("/user/logout") + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { :default, false} + {:default, false} ]) end @@ -206,28 +232,32 @@ defmodule OpenapiPetstore.Api.User do Updated user This can only be done by the logged in user. - ## Parameters + ### Parameters - - connection (OpenapiPetstore.Connection): Connection to server - - username (String.t): name that need to be deleted - - user (User): Updated user object - - opts (KeywordList): [optional] Optional parameters - ## Returns + - `connection` (OpenapiPetstore.Connection): Connection to server + - `username` (String.t): name that need to be deleted + - `user` (User): Updated user object + - `opts` (keyword): Optional parameters - {:ok, nil} on success - {:error, Tesla.Env.t} on failure + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure """ @spec update_user(Tesla.Env.client, String.t, OpenapiPetstore.Model.User.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def update_user(connection, username, user, _opts \\ []) do - %{} - |> method(:put) - |> url("/user/#{username}") - |> add_param(:body, :body, user) - |> Enum.into([]) - |> (&Connection.request(connection, &1)).() + request = + %{} + |> method(:put) + |> url("/user/#{username}") + |> add_param(:body, :body, user) + |> Enum.into([]) + + connection + |> Connection.request(request) |> evaluate_response([ - { 400, false}, - { 404, false} + {400, false}, + {404, false} ]) end end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/connection.ex b/samples/client/petstore/elixir/lib/openapi_petstore/connection.ex index 926fcb5053..656ba020ff 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/connection.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/connection.ex @@ -1,122 +1,238 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Connection do @moduledoc """ Handle Tesla connections for OpenapiPetstore. + + Additional middleware can be set in the compile-time or runtime configuration: + + config :tesla, OpenapiPetstore.Connection, + base_url: "http://petstore.swagger.io:80/v2", + adapter: Tesla.Adapter.Hackney + + The default base URL can also be set as: + + config :openapi_petstore, + :base_url, "http://petstore.swagger.io:80/v2" """ - use Tesla + @default_base_url Application.compile_env( + :openapi_petstore, + :base_url, + "http://petstore.swagger.io:80/v2" + ) - # Add any middleware here (authentication) - plug Tesla.Middleware.BaseUrl, Application.get_env(:open_api_petstore, :base_url, "http://petstore.swagger.io:80/v2") - plug Tesla.Middleware.Headers, [{"user-agent", "Elixir"}] - plug Tesla.Middleware.EncodeJson, engine: Poison - - @doc """ - Configure a client connection using Basic authentication. - - ## Parameters - - - username (String): Username used for authentication - - password (String): Password used for authentication - - # Returns - - Tesla.Env.client - """ - @spec new(String.t, String.t) :: Tesla.Env.client - def new(username, password) do - Tesla.client([ - {Tesla.Middleware.BasicAuth, %{username: username, password: password}} - ]) - end - @doc """ - Configure a client connection using Basic authentication. - - ## Parameters - - - username (String): Username used for authentication - - password (String): Password used for authentication - - # Returns - - Tesla.Env.client - """ - @spec new(String.t, String.t) :: Tesla.Env.client - def new(username, password) do - Tesla.client([ - {Tesla.Middleware.BasicAuth, %{username: username, password: password}} - ]) - end - @doc """ - Configure a client connection using Basic authentication. - - ## Parameters - - - username (String): Username used for authentication - - password (String): Password used for authentication - - # Returns - - Tesla.Env.client - """ - @spec new(String.t, String.t) :: Tesla.Env.client - def new(username, password) do - Tesla.client([ - {Tesla.Middleware.BasicAuth, %{username: username, password: password}} - ]) - end - @scopes [ - "write:pets", # modify pets in your account - "read:pets" # read your pets + @default_scopes [ + # modify pets in your account + "write:pets", + # read your pets + "read:pets" ] + @typedoc """ + An arity-1 function or module/function tuple specification which, given + a list of scopes, obtains an OAuth2 token. + """ + @type token_fetcher :: (scopes :: list(String.t()) -> String.t()) | {module(), atom()} + + @typedoc """ + The list of options that can be passed to new/1. + + - `base_url`: Overrides the base URL on a per-client basis. + - `user_agent`: Overrides the User-Agent header. + - `token`: An OAuth2 token or a token fetcher function. + - `token_scopes`: A list of OAuth2 scope strings for use with a token + fetcher function. + - `username`: A username for basic authentication. + - `password`: A password for basic authentication. + """ + @type options :: [ + {:base_url, String.t()}, + {:user_agent, String.t()}, + {:token, String.t() | token_fetcher}, + {:token_scopes, list(String.t())}, + {:username, String.t() | nil}, + {:password, String.t() | nil}, + ] + + @doc "Forward requests to Tesla." + @spec request(Tesla.Client.t(), [Tesla.option()]) :: Tesla.Env.result() + defdelegate request(client, options), to: Tesla + @doc """ - Configure a client connection using a provided OAuth2 token as a Bearer token + Configure a client with no authentication. - ## Parameters - - - token (String): Bearer token - - ## Returns + ### Returns Tesla.Env.client """ - @spec new(String.t) :: Tesla.Env.client - def new(token) when is_binary(token) do - Tesla.client([ - {Tesla.Middleware.Headers, [{"authorization", "Bearer #{token}"}]} - ]) - end - - @doc """ - Configure a client connection using a function which yields a Bearer token. - - ## Parameters - - - token_fetcher (function arity of 1): Callback which provides an OAuth2 token - given a list of scopes - - ## Returns - - Tesla.Env.client - """ - @spec new(((list(String.t)) -> String.t)) :: Tesla.Env.client - def new(token_fetcher) when is_function(token_fetcher) do - token_fetcher.(@scopes) - |> new - end - @doc """ - Configure an authless client connection - - # Returns - - Tesla.Env.client - """ - @spec new() :: Tesla.Env.client + @spec new() :: Tesla.Env.client() def new do - Tesla.client([]) + Tesla.client(middleware(), adapter()) + end + + @doc """ + Configure a client that may have authentication. + + ### Parameters + + The first parameter *may* be a `token` (a string, a token fetcher class, + or a module/function tuple) or a keyword list of `options`. They are + documented separately, but only *one* of them will be passed. + + - `token`: a String or a function of arity one. This value, or the result + of the function call, will be set as a bearer token in the + `authorization` header. + - `options`: a keyword list of OpenAPIPetstore.Connection.options. + + ### Returns + + Tesla.Env.client + """ + @spec new(String.t() | token_fetcher | options) :: Tesla.Env.client() + def new(token) when is_binary(token) or is_function(token, 1) or is_tuple(token) do + new(token: token) + end + + def new(options) when is_list(options) do + options + |> middleware() + |> Tesla.client(adapter()) + end + + @doc """ + Configure a client using bearer authentication with scopes, or with + username and password for basic authentication. + + ### Parameters + + - `token_or_username`: a String representing a bearer token or a username, + depending on the type of the next parameter, or a function arity one + that returns a bearer token. + - `scopes_or_password`: a list of Strings represenging OAuth2 scopes, or + a single string that is the password for the username provided. + - `options`: a keyword list of OpenAPIPetstore.Connection.options. + + ### Returns + + Tesla.Env.client + """ + @spec new( + token_or_username :: String.t() | token_fetcher, + scopes_or_password :: list(String.t()) | String.t(), + options + ) :: Tesla.Env.client() + + def new(token_or_username, scopes_or_password, options \\ []) + + def new(token, scopes, options) + when (is_binary(token) or is_function(token, 1) or is_tuple(token)) and is_list(scopes) do + options + |> Keyword.merge(token: token, token_scopes: scopes) + |> new() + end + + def new(username, password, options) when is_binary(username) and is_binary(password) do + options + |> Keyword.merge(username: username, password: password) + |> new() + end + + @doc """ + Returns fully configured middleware for passing to Tesla.client/2. + """ + @spec middleware(options) :: [Tesla.Client.middleware()] + def middleware(options \\ []) do + base_url = + Keyword.get( + options, + :base_url, + Application.get_env(:openapi_petstore, :base_url, @default_base_url) + ) + + tesla_options = Application.get_env(:tesla, __MODULE__, []) + middleware = Keyword.get(tesla_options, :middleware, []) + json_engine = Keyword.get(tesla_options, :json, Poison) + + user_agent = + Keyword.get( + options, + :user_agent, + Keyword.get( + tesla_options, + :user_agent, + "openapi-generator - OpenapiPetstore 1.0.0 - elixir" + ) + ) + + username = Keyword.get(options, :username) + password = Keyword.get(options, :password) + middleware = + if username || password do + [{Tesla.Middleware.BasicAuth, %{username: username, password: password}} | middleware] + else + middleware + end + + middleware = + if token = Keyword.get(options, :token) do + scopes = Keyword.get(options, :token_scopes, @default_scopes) + [authorization(token, scopes) | middleware] + else + middleware + end + + [ + {Tesla.Middleware.BaseUrl, base_url}, + {Tesla.Middleware.Headers, [{"user-agent", user_agent}]}, + {Tesla.Middleware.EncodeJson, engine: json_engine} + | middleware + ] + end + + @doc """ + Returns an authentication middleware tuple for a Tesla client that sets + the `authorization` header to the value of the provided bearer token. If + the token is provided as a function of arity one, it will be called with + a list of requested scopes that will obtain an OAuth2 token. + + ### Parameters + + - `token`: a String or a function of arity one. This value, or the result + of the function call, will be set as a bearer token in the + `authorization` header. + + - `scopes`: an optional list of scopes for use with the token fetcher + function. Ignored when `token` is provided as a String. Defaults to + `#{inspect(@default_scopes)}`. + + ### Returns + + `{Tesla.Middleware.Headers, [{"authorization", TOKEN}]}` + """ + @spec authorization(String.t() | token_fetcher, list(String.t())) :: + Tesla.Client.middleware() + def authorization(token, scopes \\ @default_scopes) + + def authorization(token, _scopes) when is_binary(token) do + {Tesla.Middlware.Headers, ["authorization", token]} + end + + def authorization({module, function}, scopes) when is_atom(module) and is_atom(function) do + apply(module, function, [scopes]) + end + + def authorization(token_fetcher, scopes) when is_function(token_fetcher, 1) do + authorization(token_fetcher.(scopes)) + end + + @doc """ + Returns the default adapter for this API. + """ + def adapter do + :tesla + |> Application.get_env(__MODULE__, []) + |> Keyword.get(:adapter, nil) end end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/deserializer.ex b/samples/client/petstore/elixir/lib/openapi_petstore/deserializer.ex index e5e927f1fa..3d41932739 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/deserializer.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/deserializer.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Deserializer do @moduledoc """ @@ -15,24 +14,33 @@ defmodule OpenapiPetstore.Deserializer do model |> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: [struct(mod)]])))) end + def deserialize(model, field, :struct, mod, options) do model |> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: struct(mod)])))) end + def deserialize(model, field, :map, mod, options) do model - |> Map.update!(field, &(Map.new(&1, fn {key, val} -> {key, Poison.Decode.decode(val, Keyword.merge(options, [as: struct(mod)]))} end))) + |> Map.update!( + field, + &Map.new(&1, fn {key, val} -> + {key, Poison.Decode.decode(val, Keyword.merge(options, [as: struct(mod)]))} + end) + ) end + def deserialize(model, field, :date, _, _options) do value = Map.get(model, field) case is_binary(value) do - true -> case DateTime.from_iso8601(value) do - {:ok, datetime, _offset} -> - Map.put(model, field, datetime) - _ -> - model - end - false -> model + true -> + case DateTime.from_iso8601(value) do + {:ok, datetime, _offset} -> Map.put(model, field, datetime) + _ -> model + end + + false -> + model end end end diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/_foo_get_default_response.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/_foo_get_default_response.ex index c48a99b52e..3175497128 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/_foo_get_default_response.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/_foo_get_default_response.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.FooGetDefaultResponse do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/_special_model_name_.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/_special_model_name_.ex index 429129b42a..2aa6e95a31 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/_special_model_name_.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/_special_model_name_.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.SpecialModelName do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/additional_properties_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/additional_properties_class.ex index 722af9396b..6c67590c4e 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/additional_properties_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/additional_properties_class.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.AdditionalPropertiesClass do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex index eaef9cbfcf..3e959bce29 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.AllOfWithSingleRef do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/animal.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/animal.ex index 2457f9dca1..8ee084d843 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/animal.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/animal.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Animal do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/api_response.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/api_response.ex index 5df3e445eb..198a3be273 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/api_response.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/api_response.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.ApiResponse do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_array_of_number_only.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_array_of_number_only.ex index d0312d28ca..6f6d411888 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_array_of_number_only.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_array_of_number_only.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.ArrayOfArrayOfNumberOnly do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_number_only.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_number_only.ex index 770c78e85a..cd02092082 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_number_only.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_number_only.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.ArrayOfNumberOnly do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_test.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_test.ex index 0314a88325..bedaef3fcf 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_test.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_test.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.ArrayTest do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/capitalization.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/capitalization.ex index 23e25dfa36..20e514b7b4 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/capitalization.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/capitalization.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Capitalization do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/cat.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/cat.ex index d3281a7ac1..8994709724 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/cat.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/cat.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Cat do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/cat_all_of.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/cat_all_of.ex index 6935c289a0..c446876ca1 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/cat_all_of.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/cat_all_of.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.CatAllOf do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/category.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/category.ex index 678b66a070..52c8d80034 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/category.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/category.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Category do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/class_model.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/class_model.ex index ba41186048..f3fe3f7759 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/class_model.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/class_model.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.ClassModel do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/client.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/client.ex index 6ef6dddec0..0721d1ad36 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/client.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/client.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Client do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_object.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_object.ex index 0fd11a2a22..a1b3458e38 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_object.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_object.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.DeprecatedObject do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/dog.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/dog.ex index 567f056d8e..c2e250ef44 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/dog.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/dog.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Dog do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/dog_all_of.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/dog_all_of.ex index 5898abad3d..6b66a18889 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/dog_all_of.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/dog_all_of.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.DogAllOf do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_arrays.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_arrays.ex index 28f27eb79d..91d2b46788 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_arrays.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_arrays.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.EnumArrays do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_class.ex index 784588422e..7bd5b6a1c6 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_class.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.EnumClass do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_test.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_test.ex index 1af76bedb3..8d8ea27dcf 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_test.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_test.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.EnumTest do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/file.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/file.ex index 659a4b26ec..44dc48abeb 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/file.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/file.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.File do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/file_schema_test_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/file_schema_test_class.ex index 9edcf4f8a0..509cfb2686 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/file_schema_test_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/file_schema_test_class.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.FileSchemaTestClass do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/foo.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/foo.ex index b25263be9a..b089c09736 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/foo.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/foo.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Foo do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/format_test.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/format_test.ex index 6dafb14d70..637a231cce 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/format_test.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/format_test.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.FormatTest do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/has_only_read_only.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/has_only_read_only.ex index c8bf68f5b2..1a4c39d701 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/has_only_read_only.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/has_only_read_only.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.HasOnlyReadOnly do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/health_check_result.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/health_check_result.ex index 339a5fe876..649a2fb566 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/health_check_result.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/health_check_result.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.HealthCheckResult do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/list.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/list.ex index b37fab3f46..c9ccbe8d08 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/list.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/list.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.List do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/map_test.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/map_test.ex index 6d94cf83c1..5b3b1d9ac4 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/map_test.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/map_test.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.MapTest do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/mixed_properties_and_additional_properties_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/mixed_properties_and_additional_properties_class.ex index a8e4981cd3..bd5426612b 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/mixed_properties_and_additional_properties_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/mixed_properties_and_additional_properties_class.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.MixedPropertiesAndAdditionalPropertiesClass do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/model_200_response.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/model_200_response.ex index 3fbd1067f7..6a473f552f 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/model_200_response.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/model_200_response.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Model200Response do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/name.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/name.ex index 42d93796dd..0a8d36757c 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/name.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/name.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Name do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/nullable_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/nullable_class.ex index 45174fd475..c282a203fa 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/nullable_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/nullable_class.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.NullableClass do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/number_only.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/number_only.ex index 5658d13314..2d48d9ae60 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/number_only.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/number_only.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.NumberOnly do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex index a3f5cc4a53..44e0dd7962 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.ObjectWithDeprecatedFields do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/order.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/order.ex index 0b430ca41c..4f4ea7b3a3 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/order.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/order.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Order do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_composite.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_composite.ex index abacaa6d85..0e09aecba9 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_composite.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_composite.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterComposite do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum.ex index 5e9ce9d276..4bb536a034 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterEnum do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_default_value.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_default_value.ex index 8c890fef50..7368598630 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_default_value.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_default_value.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterEnumDefaultValue do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer.ex index 5130ca77d2..3b6285d01b 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterEnumInteger do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer_default_value.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer_default_value.ex index 33160c1679..3debd284a5 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer_default_value.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer_default_value.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterEnumIntegerDefaultValue do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_object_with_enum_property.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_object_with_enum_property.ex index 23502200bf..8ec0302d3a 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_object_with_enum_property.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_object_with_enum_property.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterObjectWithEnumProperty do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/pet.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/pet.ex index 046e5bee22..34b9f199b0 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/pet.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/pet.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Pet do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/read_only_first.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/read_only_first.ex index 6f36aba467..bc9c1b5a17 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/read_only_first.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/read_only_first.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.ReadOnlyFirst do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/return.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/return.ex index 54b3cbf391..e5a026d8de 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/return.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/return.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Return do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/single_ref_type.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/single_ref_type.ex index d2a17aa740..28b77566b7 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/single_ref_type.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/single_ref_type.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.SingleRefType do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/tag.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/tag.ex index f64ba461a3..83e6e6856d 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/tag.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/tag.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.Tag do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/user.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/user.ex index 368e3f52a3..9213427376 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/user.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/user.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.Model.User do @moduledoc """ diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/request_builder.ex b/samples/client/petstore/elixir/lib/openapi_petstore/request_builder.ex index 2488ab80c7..68c89dfd6e 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/request_builder.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/request_builder.ex @@ -1,6 +1,5 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# https://openapi-generator.tech -# Do not edit the class manually. +# NOTE: This file is auto generated by OpenAPI Generator 7.0.0-SNAPSHOT (https://openapi-generator.tech). +# Do not edit this file manually. defmodule OpenapiPetstore.RequestBuilder do @moduledoc """ @@ -8,113 +7,130 @@ defmodule OpenapiPetstore.RequestBuilder do """ @doc """ - Specify the request method when building a request + Specify the request `method` when building a request. - ## Parameters + Does not override the `method` if one has already been specified. - - request (Map) - Collected request options - - m (atom) - Request method + ### Parameters - ## Returns + - `request` (Map) - Collected request options + - `method` (atom) - Request method + + ### Returns Map """ - @spec method(map(), atom) :: map() - def method(request, m) do - Map.put_new(request, :method, m) + @spec method(map(), atom()) :: map() + def method(request, method) do + Map.put_new(request, :method, method) end @doc """ - Specify the request method when building a request + Specify the request URL when building a request. - ## Parameters + Does not override the `url` if one has already been specified. - - request (Map) - Collected request options - - u (String) - Request URL + ### Parameters - ## Returns + - `request` (Map) - Collected request options + - `url` (String) - Request URL + + ### Returns Map """ - @spec url(map(), String.t) :: map() - def url(request, u) do - Map.put_new(request, :url, u) + @spec url(map(), String.t()) :: map() + def url(request, url) do + Map.put_new(request, :url, url) end @doc """ - Add optional parameters to the request + Add optional parameters to the request. - ## Parameters + ### Parameters - - request (Map) - Collected request options - - definitions (Map) - Map of parameter name to parameter location. - - options (KeywordList) - The provided optional parameters + - `request` (Map) - Collected request options + - `definitions` (Map) - Map of parameter name to parameter location. + - `options` (KeywordList) - The provided optional parameters - ## Returns + ### Returns Map """ - @spec add_optional_params(map(), %{optional(atom) => atom}, keyword()) :: map() + @spec add_optional_params(map(), %{optional(atom) => atom()}, keyword()) :: map() def add_optional_params(request, _, []), do: request + def add_optional_params(request, definitions, [{key, value} | tail]) do case definitions do %{^key => location} -> request |> add_param(location, key, value) |> add_optional_params(definitions, tail) + _ -> add_optional_params(request, definitions, tail) end end @doc """ - Add optional parameters to the request + Add non-optional parameters to the request. - ## Parameters + ### Parameters - - request (Map) - Collected request options - - location (atom) - Where to put the parameter - - key (atom) - The name of the parameter - - value (any) - The value of the parameter + - `request` (Map) - Collected request options + - `location` (atom) - Where to put the parameter + - `key` (atom) - The name of the parameter + - `value` (any) - The value of the parameter - ## Returns + ### Returns Map """ - @spec add_param(map(), atom, atom, any()) :: map() + @spec add_param(map(), atom(), atom(), any()) :: map() def add_param(request, :body, :body, value), do: Map.put(request, :body, value) + def add_param(request, :body, key, value) do request |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0) - |> Map.update!(:body, &(Tesla.Multipart.add_field(&1, key, Poison.encode!(value), headers: [{:"Content-Type", "application/json"}]))) + |> Map.update!(:body, fn multipart -> + Tesla.Multipart.add_field( + multipart, + key, + Poison.encode!(value), + headers: [{:"Content-Type", "application/json"}] + ) + end) end + def add_param(request, :headers, key, value) do - request - |> Tesla.put_header(key, value) + Tesla.put_header(request, key, value) end + def add_param(request, :file, name, path) do request |> Map.put_new_lazy(:body, &Tesla.Multipart.new/0) |> Map.update!(:body, &(Tesla.Multipart.add_file(&1, path, name: name))) end + def add_param(request, :form, name, value) do - request - |> Map.update(:body, %{name => value}, &(Map.put(&1, name, value))) + Map.update(request, :body, %{name => value}, &(Map.put(&1, name, value))) end + def add_param(request, location, key, value) do Map.update(request, location, [{key, value}], &(&1 ++ [{key, value}])) end @doc """ - Due to a bug in httpc, POST, PATCH and PUT requests will fail, if the body is empty + This function ensures that the `body` parameter is always set. - This function will ensure, that the body param is always set + When using Tesla with the `httpc` adapter (the default adapter), there is a + bug where POST, PATCH and PUT requests will fail if the body is empty. - ## Parameters + ### Parameters - - request (Map) - Collected request options + - `request` (Map) - Collected request options - ## Returns + ### Returns Map """ @@ -127,39 +143,44 @@ defmodule OpenapiPetstore.RequestBuilder do Map.put_new(request, :body, "") end + @type status_code :: 100..599 + @type response_mapping :: [{status_code, struct() | false}] + @doc """ - Handle the response for a Tesla request + Evaluate the response from a Tesla request. + Decode the response for a Tesla request. - ## Parameters + ### Parameters - - arg1 (Tesla.Env.t | term) - The response object - - arg2 (:false | struct | [struct]) - The shape of the struct to deserialize into + - `result` (Tesla.Env.result()): The response from Tesla.request/2. + - `mapping` ([{http_status, struct}]): The mapping for status to struct for decoding. - ## Returns + ### Returns - {:ok, struct} on success - {:error, term} on failure + - `{:ok, struct}` or `{:ok, Tesla.Env.t()}` on success + - `{:error, term}` on failure """ - @spec decode(Tesla.Env.t() | term(), false | struct() | [struct()]) :: - {:ok, struct()} | {:ok, Tesla.Env.t()} | {:error, any} - def decode(%Tesla.Env{} = env, false), do: {:ok, env} - def decode(%Tesla.Env{body: body}, struct), do: Poison.decode(body, as: struct) - + @spec evaluate_response(Tesla.Env.result(), response_mapping) :: {:ok, struct()} | Tesla.Env.result() def evaluate_response({:ok, %Tesla.Env{} = env}, mapping) do - resolve_mapping(env, mapping) + resolve_mapping(env, mapping, nil) end def evaluate_response({:error, _} = error, _), do: error - def resolve_mapping(env, mapping, default \\ nil) - - def resolve_mapping(%Tesla.Env{status: status} = env, [{mapping_status, struct} | _], _) + defp resolve_mapping(%Tesla.Env{status: status} = env, [{mapping_status, struct} | _], _) when status == mapping_status do decode(env, struct) end - def resolve_mapping(env, [{:default, struct} | tail], _), do: resolve_mapping(env, tail, struct) - def resolve_mapping(env, [_ | tail], struct), do: resolve_mapping(env, tail, struct) - def resolve_mapping(env, [], nil), do: {:error, env} - def resolve_mapping(env, [], struct), do: decode(env, struct) + defp resolve_mapping(env, [{:default, struct} | tail], _), do: resolve_mapping(env, tail, struct) + + defp resolve_mapping(env, [_ | tail], struct), do: resolve_mapping(env, tail, struct) + + defp resolve_mapping(env, [], nil), do: {:error, env} + + defp resolve_mapping(env, [], struct), do: decode(env, struct) + + defp decode(%Tesla.Env{} = env, false), do: {:ok, env} + + defp decode(%Tesla.Env{body: body}, struct), do: Poison.decode(body, as: struct) end diff --git a/samples/client/petstore/elixir/mix.exs b/samples/client/petstore/elixir/mix.exs index c03b200a50..d7f7fae688 100644 --- a/samples/client/petstore/elixir/mix.exs +++ b/samples/client/petstore/elixir/mix.exs @@ -2,14 +2,16 @@ defmodule OpenapiPetstore.Mixfile do use Mix.Project def project do - [app: :openapi_petstore, - version: "1.0.0", - elixir: "~> 1.10", - build_embedded: Mix.env == :prod, - start_permanent: Mix.env == :prod, - package: package(), - description: "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\", - deps: deps()] + [ + app: :openapi_petstore, + version: "1.0.0", + elixir: "~> 1.10", + build_embedded: Mix.env() == :prod, + start_permanent: Mix.env() == :prod, + package: package(), + description: "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\", + deps: deps() + ] end # Configuration for the OTP application @@ -37,11 +39,10 @@ defmodule OpenapiPetstore.Mixfile do ] end - defp package() do - [ - name: "openapi_petstore", - files: ~w(.formatter.exs config lib mix.exs README* LICENSE*), - licenses: [""] - ] + defp package do + [ + name: "openapi_petstore", + files: ~w(.formatter.exs config lib mix.exs README* LICENSE*), + ] end end diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index 70d0040a3a..e64b064372 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -61,7 +61,7 @@ Each operation can use different server URL defined using `OperationServers` map An operation is uniquely identified by `"{classname}Service.{nickname}"` string. Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. -``` +```golang ctx := context.WithValue(context.Background(), petstore.ContextOperationServerIndices, map[string]int{ "{classname}Service.{nickname}": 2, }) diff --git a/samples/client/petstore/go/go-petstore/api/openapi.yaml b/samples/client/petstore/go/go-petstore/api/openapi.yaml index 0f760ad730..80c1125f22 100644 --- a/samples/client/petstore/go/go-petstore/api/openapi.yaml +++ b/samples/client/petstore/go/go-petstore/api/openapi.yaml @@ -2103,11 +2103,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2118,6 +2120,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/go/go-petstore/test/api_another_fake_test.go b/samples/client/petstore/go/go-petstore/test/api_another_fake_test.go new file mode 100644 index 0000000000..bf60a1c855 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/test/api_another_fake_test.go @@ -0,0 +1,37 @@ +/* +OpenAPI Petstore + +Testing AnotherFakeApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_AnotherFakeApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test AnotherFakeApiService Call123TestSpecialTags", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.AnotherFakeApi.Call123TestSpecialTags(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/client/petstore/go/go-petstore/test/api_fake_classname_tags123_test.go b/samples/client/petstore/go/go-petstore/test/api_fake_classname_tags123_test.go new file mode 100644 index 0000000000..963e4a42da --- /dev/null +++ b/samples/client/petstore/go/go-petstore/test/api_fake_classname_tags123_test.go @@ -0,0 +1,37 @@ +/* +OpenAPI Petstore + +Testing FakeClassnameTags123ApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_FakeClassnameTags123ApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test FakeClassnameTags123ApiService TestClassname", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeClassnameTags123Api.TestClassname(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/client/petstore/go/go-petstore/test/api_fake_test.go b/samples/client/petstore/go/go-petstore/test/api_fake_test.go new file mode 100644 index 0000000000..40e1635c32 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/test/api_fake_test.go @@ -0,0 +1,193 @@ +/* +OpenAPI Petstore + +Testing FakeApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_FakeApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test FakeApiService CreateXmlItem", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.CreateXmlItem(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService FakeOuterBooleanSerialize", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.FakeOuterBooleanSerialize(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService FakeOuterCompositeSerialize", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.FakeOuterCompositeSerialize(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService FakeOuterNumberSerialize", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.FakeOuterNumberSerialize(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService FakeOuterStringSerialize", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.FakeOuterStringSerialize(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestBodyWithFileSchema", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestBodyWithFileSchema(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestBodyWithQueryParams", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestBodyWithQueryParams(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestClientModel", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestClientModel(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestEndpointParameters", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestEndpointParameters(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestEnumParameters", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestEnumParameters(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestGroupParameters", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestGroupParameters(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestInlineAdditionalProperties", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestInlineAdditionalProperties(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestJsonFormData", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestJsonFormData(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestQueryParameterCollectionFormat", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestQueryParameterCollectionFormat(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/client/petstore/go/go-petstore/test/api_pet_test.go b/samples/client/petstore/go/go-petstore/test/api_pet_test.go new file mode 100644 index 0000000000..94d4d0fa7f --- /dev/null +++ b/samples/client/petstore/go/go-petstore/test/api_pet_test.go @@ -0,0 +1,143 @@ +/* +OpenAPI Petstore + +Testing PetApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_PetApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test PetApiService AddPet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetApi.AddPet(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService DeletePet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.DeletePet(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService FindPetsByStatus", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetApi.FindPetsByStatus(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService FindPetsByTags", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetApi.FindPetsByTags(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService GetPetById", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.GetPetById(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService UpdatePet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetApi.UpdatePet(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService UpdatePetWithForm", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.UpdatePetWithForm(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService UploadFile", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.UploadFile(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService UploadFileWithRequiredFile", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.UploadFileWithRequiredFile(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/client/petstore/go/go-petstore/test/api_store_test.go b/samples/client/petstore/go/go-petstore/test/api_store_test.go new file mode 100644 index 0000000000..48c1db2eb5 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/test/api_store_test.go @@ -0,0 +1,77 @@ +/* +OpenAPI Petstore + +Testing StoreApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_StoreApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test StoreApiService DeleteOrder", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var orderId string + + resp, httpRes, err := apiClient.StoreApi.DeleteOrder(context.Background(), orderId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test StoreApiService GetInventory", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.StoreApi.GetInventory(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test StoreApiService GetOrderById", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var orderId int64 + + resp, httpRes, err := apiClient.StoreApi.GetOrderById(context.Background(), orderId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test StoreApiService PlaceOrder", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.StoreApi.PlaceOrder(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/client/petstore/go/go-petstore/test/api_user_test.go b/samples/client/petstore/go/go-petstore/test/api_user_test.go new file mode 100644 index 0000000000..072179b486 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/test/api_user_test.go @@ -0,0 +1,127 @@ +/* +OpenAPI Petstore + +Testing UserApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_UserApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test UserApiService CreateUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.CreateUser(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService CreateUsersWithArrayInput", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.CreateUsersWithArrayInput(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService CreateUsersWithListInput", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.CreateUsersWithListInput(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService DeleteUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var username string + + resp, httpRes, err := apiClient.UserApi.DeleteUser(context.Background(), username).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService GetUserByName", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var username string + + resp, httpRes, err := apiClient.UserApi.GetUserByName(context.Background(), username).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService LoginUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.LoginUser(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService LogoutUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.LogoutUser(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService UpdateUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var username string + + resp, httpRes, err := apiClient.UserApi.UpdateUser(context.Background(), username).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/client/petstore/haskell-http-client/openapi.yaml b/samples/client/petstore/haskell-http-client/openapi.yaml index 0f760ad730..80c1125f22 100644 --- a/samples/client/petstore/haskell-http-client/openapi.yaml +++ b/samples/client/petstore/haskell-http-client/openapi.yaml @@ -2103,11 +2103,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2118,6 +2120,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/.openapi-generator-ignore b/samples/client/petstore/java-helidon-client/mp/.openapi-generator-ignore similarity index 100% rename from samples/client/petstore/rust/hyper/fileResponseTest/.openapi-generator-ignore rename to samples/client/petstore/java-helidon-client/mp/.openapi-generator-ignore diff --git a/samples/client/petstore/java-helidon-client/mp/.openapi-generator/FILES b/samples/client/petstore/java-helidon-client/mp/.openapi-generator/FILES new file mode 100644 index 0000000000..1b046cca4a --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/.openapi-generator/FILES @@ -0,0 +1,116 @@ +README.md +docs/AdditionalPropertiesClass.md +docs/AllOfWithSingleRef.md +docs/Animal.md +docs/AnotherFakeApi.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/DefaultApi.md +docs/DeprecatedObject.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/FileSchemaTestClass.md +docs/Foo.md +docs/FooGetDefaultResponse.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/HealthCheckResult.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelApiResponse.md +docs/ModelFile.md +docs/ModelList.md +docs/ModelReturn.md +docs/Name.md +docs/NullableClass.md +docs/NumberOnly.md +docs/ObjectWithDeprecatedFields.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/OuterEnumDefaultValue.md +docs/OuterEnumInteger.md +docs/OuterEnumIntegerDefaultValue.md +docs/OuterObjectWithEnumProperty.md +docs/Pet.md +docs/PetApi.md +docs/ReadOnlyFirst.md +docs/SingleRefType.md +docs/SpecialModelName.md +docs/StoreApi.md +docs/Tag.md +docs/User.md +docs/UserApi.md +pom.xml +src/main/java/org/openapitools/client/JavaTimeFormatter.java +src/main/java/org/openapitools/client/RFC3339DateFormat.java +src/main/java/org/openapitools/client/api/AnotherFakeApi.java +src/main/java/org/openapitools/client/api/ApiException.java +src/main/java/org/openapitools/client/api/ApiExceptionMapper.java +src/main/java/org/openapitools/client/api/DefaultApi.java +src/main/java/org/openapitools/client/api/FakeApi.java +src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +src/main/java/org/openapitools/client/api/PetApi.java +src/main/java/org/openapitools/client/api/StoreApi.java +src/main/java/org/openapitools/client/api/UserApi.java +src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java +src/main/java/org/openapitools/client/model/Animal.java +src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +src/main/java/org/openapitools/client/model/ArrayTest.java +src/main/java/org/openapitools/client/model/Capitalization.java +src/main/java/org/openapitools/client/model/Cat.java +src/main/java/org/openapitools/client/model/CatAllOf.java +src/main/java/org/openapitools/client/model/Category.java +src/main/java/org/openapitools/client/model/ClassModel.java +src/main/java/org/openapitools/client/model/Client.java +src/main/java/org/openapitools/client/model/DeprecatedObject.java +src/main/java/org/openapitools/client/model/Dog.java +src/main/java/org/openapitools/client/model/DogAllOf.java +src/main/java/org/openapitools/client/model/EnumArrays.java +src/main/java/org/openapitools/client/model/EnumClass.java +src/main/java/org/openapitools/client/model/EnumTest.java +src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +src/main/java/org/openapitools/client/model/Foo.java +src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java +src/main/java/org/openapitools/client/model/FormatTest.java +src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +src/main/java/org/openapitools/client/model/HealthCheckResult.java +src/main/java/org/openapitools/client/model/MapTest.java +src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +src/main/java/org/openapitools/client/model/Model200Response.java +src/main/java/org/openapitools/client/model/ModelApiResponse.java +src/main/java/org/openapitools/client/model/ModelFile.java +src/main/java/org/openapitools/client/model/ModelList.java +src/main/java/org/openapitools/client/model/ModelReturn.java +src/main/java/org/openapitools/client/model/Name.java +src/main/java/org/openapitools/client/model/NullableClass.java +src/main/java/org/openapitools/client/model/NumberOnly.java +src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +src/main/java/org/openapitools/client/model/Order.java +src/main/java/org/openapitools/client/model/OuterComposite.java +src/main/java/org/openapitools/client/model/OuterEnum.java +src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java +src/main/java/org/openapitools/client/model/OuterEnumInteger.java +src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java +src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java +src/main/java/org/openapitools/client/model/Pet.java +src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +src/main/java/org/openapitools/client/model/SingleRefType.java +src/main/java/org/openapitools/client/model/SpecialModelName.java +src/main/java/org/openapitools/client/model/Tag.java +src/main/java/org/openapitools/client/model/User.java diff --git a/samples/client/petstore/java-helidon-client/mp/.openapi-generator/VERSION b/samples/client/petstore/java-helidon-client/mp/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java-helidon-client/mp/README.md b/samples/client/petstore/java-helidon-client/mp/README.md new file mode 100644 index 0000000000..18c68cbe83 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/README.md @@ -0,0 +1,7 @@ +# OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + +## Overview +This project was generated using the Helidon OpenAPI Generator. diff --git a/samples/client/petstore/java-helidon-client/mp/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java-helidon-client/mp/docs/AdditionalPropertiesClass.md new file mode 100644 index 0000000000..fe69a56eeb --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/AdditionalPropertiesClass.md @@ -0,0 +1,14 @@ + + +# AdditionalPropertiesClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**mapProperty** | **Map<String, String>** | | [optional] | +|**mapOfMapProperty** | **Map<String, Map<String, String>>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/AllOfWithSingleRef.md b/samples/client/petstore/java-helidon-client/mp/docs/AllOfWithSingleRef.md new file mode 100644 index 0000000000..0a9e61bc68 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/AllOfWithSingleRef.md @@ -0,0 +1,14 @@ + + +# AllOfWithSingleRef + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**username** | **String** | | [optional] | +|**singleRefType** | [**SingleRefType**](SingleRefType.md) | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Animal.md b/samples/client/petstore/java-helidon-client/mp/docs/Animal.md new file mode 100644 index 0000000000..d9b32f14c8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Animal.md @@ -0,0 +1,14 @@ + + +# Animal + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**className** | **String** | | | +|**color** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/AnotherFakeApi.md b/samples/client/petstore/java-helidon-client/mp/docs/AnotherFakeApi.md new file mode 100644 index 0000000000..86cfd1bdc7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/AnotherFakeApi.md @@ -0,0 +1,44 @@ +# AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**call123testSpecialTags**](AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags | + + + +## call123testSpecialTags + +> Client call123testSpecialTags(client) + +To test special tags + +To test special tags and operation ID starting with number + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **client** | [**Client**](Client.md)| client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java-helidon-client/mp/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 0000000000..0188db3eb1 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,13 @@ + + +# ArrayOfArrayOfNumberOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayArrayNumber** | **List<List<BigDecimal>>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java-helidon-client/mp/docs/ArrayOfNumberOnly.md new file mode 100644 index 0000000000..a5753530aa --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ArrayOfNumberOnly.md @@ -0,0 +1,13 @@ + + +# ArrayOfNumberOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayNumber** | **List<BigDecimal>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ArrayTest.md b/samples/client/petstore/java-helidon-client/mp/docs/ArrayTest.md new file mode 100644 index 0000000000..36077c9df3 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ArrayTest.md @@ -0,0 +1,15 @@ + + +# ArrayTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayOfString** | **List<String>** | | [optional] | +|**arrayArrayOfInteger** | **List<List<Long>>** | | [optional] | +|**arrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Capitalization.md b/samples/client/petstore/java-helidon-client/mp/docs/Capitalization.md new file mode 100644 index 0000000000..82a812711d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Capitalization.md @@ -0,0 +1,18 @@ + + +# Capitalization + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**smallCamel** | **String** | | [optional] | +|**capitalCamel** | **String** | | [optional] | +|**smallSnake** | **String** | | [optional] | +|**capitalSnake** | **String** | | [optional] | +|**scAETHFlowPoints** | **String** | | [optional] | +|**ATT_NAME** | **String** | Name of the pet | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Cat.md b/samples/client/petstore/java-helidon-client/mp/docs/Cat.md new file mode 100644 index 0000000000..390dd519c8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Cat.md @@ -0,0 +1,13 @@ + + +# Cat + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**declawed** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/CatAllOf.md b/samples/client/petstore/java-helidon-client/mp/docs/CatAllOf.md new file mode 100644 index 0000000000..926bc0abd7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/CatAllOf.md @@ -0,0 +1,13 @@ + + +# CatAllOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**declawed** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Category.md b/samples/client/petstore/java-helidon-client/mp/docs/Category.md new file mode 100644 index 0000000000..ab6d1ec334 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Category.md @@ -0,0 +1,14 @@ + + +# Category + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ClassModel.md b/samples/client/petstore/java-helidon-client/mp/docs/ClassModel.md new file mode 100644 index 0000000000..af46dea1f6 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ClassModel.md @@ -0,0 +1,14 @@ + + +# ClassModel + +Model for testing model with \"_class\" property + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**propertyClass** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Client.md b/samples/client/petstore/java-helidon-client/mp/docs/Client.md new file mode 100644 index 0000000000..ef07b4ab8b --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Client.md @@ -0,0 +1,13 @@ + + +# Client + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**client** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/DefaultApi.md b/samples/client/petstore/java-helidon-client/mp/docs/DefaultApi.md new file mode 100644 index 0000000000..d94c3e5f15 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/DefaultApi.md @@ -0,0 +1,39 @@ +# DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**fooGet**](DefaultApi.md#fooGet) | **GET** /foo | | + + + +## fooGet + +> FooGetDefaultResponse fooGet() + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**FooGetDefaultResponse**](FooGetDefaultResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | response | - | + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/DeprecatedObject.md b/samples/client/petstore/java-helidon-client/mp/docs/DeprecatedObject.md new file mode 100644 index 0000000000..48de1d6244 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/DeprecatedObject.md @@ -0,0 +1,13 @@ + + +# DeprecatedObject + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Dog.md b/samples/client/petstore/java-helidon-client/mp/docs/Dog.md new file mode 100644 index 0000000000..972c981c0d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Dog.md @@ -0,0 +1,13 @@ + + +# Dog + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**breed** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/DogAllOf.md b/samples/client/petstore/java-helidon-client/mp/docs/DogAllOf.md new file mode 100644 index 0000000000..d4e4ea0d54 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/DogAllOf.md @@ -0,0 +1,13 @@ + + +# DogAllOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**breed** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/EnumArrays.md b/samples/client/petstore/java-helidon-client/mp/docs/EnumArrays.md new file mode 100644 index 0000000000..b2222d5beb --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/EnumArrays.md @@ -0,0 +1,32 @@ + + +# EnumArrays + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**justSymbol** | [**JustSymbolEnum**](#JustSymbolEnum) | | [optional] | +|**arrayEnum** | [**List<ArrayEnumEnum>**](#List<ArrayEnumEnum>) | | [optional] | + + + +## Enum: JustSymbolEnum + +| Name | Value | +|---- | -----| +| GREATER_THAN_OR_EQUAL_TO | ">=" | +| DOLLAR | "$" | + + + +## Enum: List<ArrayEnumEnum> + +| Name | Value | +|---- | -----| +| FISH | "fish" | +| CRAB | "crab" | + + + diff --git a/samples/openapi3/client/petstore/java/native/docs/EnumClass.md b/samples/client/petstore/java-helidon-client/mp/docs/EnumClass.md similarity index 100% rename from samples/openapi3/client/petstore/java/native/docs/EnumClass.md rename to samples/client/petstore/java-helidon-client/mp/docs/EnumClass.md diff --git a/samples/client/petstore/java-helidon-client/mp/docs/EnumTest.md b/samples/client/petstore/java-helidon-client/mp/docs/EnumTest.md new file mode 100644 index 0000000000..380a2aef0b --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/EnumTest.md @@ -0,0 +1,58 @@ + + +# EnumTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] | +|**enumStringRequired** | [**EnumStringRequiredEnum**](#EnumStringRequiredEnum) | | | +|**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] | +|**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] | +|**outerEnum** | **OuterEnum** | | [optional] | +|**outerEnumInteger** | **OuterEnumInteger** | | [optional] | +|**outerEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] | +|**outerEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] | + + + +## Enum: EnumStringEnum + +| Name | Value | +|---- | -----| +| UPPER | "UPPER" | +| LOWER | "lower" | +| EMPTY | "" | + + + +## Enum: EnumStringRequiredEnum + +| Name | Value | +|---- | -----| +| UPPER | "UPPER" | +| LOWER | "lower" | +| EMPTY | "" | + + + +## Enum: EnumIntegerEnum + +| Name | Value | +|---- | -----| +| NUMBER_1 | 1 | +| NUMBER_MINUS_1 | -1 | + + + +## Enum: EnumNumberEnum + +| Name | Value | +|---- | -----| +| NUMBER_1_DOT_1 | 1.1 | +| NUMBER_MINUS_1_DOT_2 | -1.2 | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/FakeApi.md b/samples/client/petstore/java-helidon-client/mp/docs/FakeApi.md new file mode 100644 index 0000000000..9dfe49d51c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/FakeApi.md @@ -0,0 +1,649 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**fakeHealthGet**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint | +| [**fakeHttpSignatureTest**](FakeApi.md#fakeHttpSignatureTest) | **GET** /fake/http-signature-test | test http signature authentication | +| [**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | | +| [**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | | +| [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | +| [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | +| [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | +| [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | +| [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | +| [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model | +| [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 | +| [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters | +| [**testGroupParameters**](FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) | +| [**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties | +| [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data | +| [**testQueryParameterCollectionFormat**](FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | | + + + +## fakeHealthGet + +> HealthCheckResult fakeHealthGet() + +Health check endpoint + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | The instance started successfully | - | + + +## fakeHttpSignatureTest + +> void fakeHttpSignatureTest(pet, query1, header1) + +test http signature authentication + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | +| **query1** | **String**| query parameter | [optional] | +| **header1** | **String**| header parameter | [optional] | + +### Return type + +[**void**](Void.md) + +### Authorization + +[http_signature_test](../README.md#http_signature_test) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | The instance started successfully | - | + + +## fakeOuterBooleanSerialize + +> Boolean fakeOuterBooleanSerialize(body) + + + +Test serialization of outer boolean types + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **Boolean**| Input boolean as post body | [optional] | + +### Return type + +**Boolean** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output boolean | - | + + +## fakeOuterCompositeSerialize + +> OuterComposite fakeOuterCompositeSerialize(outerComposite) + + + +Test serialization of object with outer number type + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] | + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output composite | - | + + +## fakeOuterNumberSerialize + +> BigDecimal fakeOuterNumberSerialize(body) + + + +Test serialization of outer number types + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **BigDecimal**| Input number as post body | [optional] | + +### Return type + +[**BigDecimal**](BigDecimal.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output number | - | + + +## fakeOuterStringSerialize + +> String fakeOuterStringSerialize(body) + + + +Test serialization of outer string types + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **String**| Input string as post body | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output string | - | + + +## fakePropertyEnumIntegerSerialize + +> OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty) + + + +Test serialization of enum (int) properties with examples + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **outerObjectWithEnumProperty** | [**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md)| Input enum (int) as post body | | + +### Return type + +[**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output enum (int) | - | + + +## testBodyWithBinary + +> void testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **File**| image to upload | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +## testBodyWithFileSchema + +> void testBodyWithFileSchema(fileSchemaTestClass) + + + +For this test, the body for this request must reference a schema named `File`. + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +## testBodyWithQueryParams + +> void testBodyWithQueryParams(query, user) + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **query** | **String**| | | +| **user** | [**User**](User.md)| | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +## testClientModel + +> Client testClientModel(client) + +To test \"client\" model + +To test \"client\" model + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **client** | [**Client**](Client.md)| client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## testEndpointParameters + +> void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **number** | **BigDecimal**| None | | +| **_double** | **Double**| None | | +| **patternWithoutDelimiter** | **String**| None | | +| **_byte** | **byte[]**| None | | +| **integer** | **Integer**| None | [optional] | +| **int32** | **Integer**| None | [optional] | +| **int64** | **Long**| None | [optional] | +| **_float** | **Float**| None | [optional] | +| **string** | **String**| None | [optional] | +| **binary** | **File**| None | [optional] | +| **date** | **LocalDate**| None | [optional] | +| **dateTime** | **OffsetDateTime**| None | [optional] | +| **password** | **String**| None | [optional] | +| **paramCallback** | **String**| None | [optional] | + +### Return type + +[**void**](Void.md) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## testEnumParameters + +> void testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString) + +To test enum parameters + +To test enum parameters + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] | +| **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] | +| **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] | +| **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] | +| **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] [enum: 1, -2] | +| **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] [enum: 1.1, -1.2] | +| **enumQueryModelArray** | [**List<EnumClass>**](EnumClass.md)| | [optional] | +| **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] | +| **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid request | - | +| **404** | Not found | - | + + +## testGroupParameters + +> void testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requiredStringGroup** | **Integer**| Required String in group parameters | | +| **requiredBooleanGroup** | **Boolean**| Required Boolean in group parameters | | +| **requiredInt64Group** | **Long**| Required Integer in group parameters | | +| **stringGroup** | **Integer**| String in group parameters | [optional] | +| **booleanGroup** | **Boolean**| Boolean in group parameters | [optional] | +| **int64Group** | **Long**| Integer in group parameters | [optional] | + +### Return type + +[**void**](Void.md) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Someting wrong | - | + + +## testInlineAdditionalProperties + +> void testInlineAdditionalProperties(requestBody) + +test inline additionalProperties + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, String>**](String.md)| request body | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## testJsonFormData + +> void testJsonFormData(param, param2) + +test json serialization of form data + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **param** | **String**| field1 | | +| **param2** | **String**| field2 | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## testQueryParameterCollectionFormat + +> void testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, allowEmpty, language) + + + +To test the collection format in query parameters + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pipe** | [**List<String>**](String.md)| | | +| **ioutil** | [**List<String>**](String.md)| | | +| **http** | [**List<String>**](String.md)| | | +| **url** | [**List<String>**](String.md)| | | +| **context** | [**List<String>**](String.md)| | | +| **allowEmpty** | **String**| | | +| **language** | [**Map<String, String>**](String.md)| | [optional] | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/FakeClassnameTags123Api.md b/samples/client/petstore/java-helidon-client/mp/docs/FakeClassnameTags123Api.md new file mode 100644 index 0000000000..bcea773b6f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/FakeClassnameTags123Api.md @@ -0,0 +1,44 @@ +# FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testClassname**](FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case | + + + +## testClassname + +> Client testClassname(client) + +To test class name in snake case + +To test class name in snake case + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **client** | [**Client**](Client.md)| client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/FileSchemaTestClass.md b/samples/client/petstore/java-helidon-client/mp/docs/FileSchemaTestClass.md new file mode 100644 index 0000000000..85d1a06366 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/FileSchemaTestClass.md @@ -0,0 +1,14 @@ + + +# FileSchemaTestClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**_file** | [**ModelFile**](ModelFile.md) | | [optional] | +|**files** | [**List<ModelFile>**](ModelFile.md) | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Foo.md b/samples/client/petstore/java-helidon-client/mp/docs/Foo.md new file mode 100644 index 0000000000..6b3f055652 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Foo.md @@ -0,0 +1,13 @@ + + +# Foo + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/FooGetDefaultResponse.md b/samples/client/petstore/java-helidon-client/mp/docs/FooGetDefaultResponse.md new file mode 100644 index 0000000000..ff3d7a3a56 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/FooGetDefaultResponse.md @@ -0,0 +1,13 @@ + + +# FooGetDefaultResponse + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**string** | [**Foo**](Foo.md) | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/FormatTest.md b/samples/client/petstore/java-helidon-client/mp/docs/FormatTest.md new file mode 100644 index 0000000000..01b8c777ae --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/FormatTest.md @@ -0,0 +1,28 @@ + + +# FormatTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**integer** | **Integer** | | [optional] | +|**int32** | **Integer** | | [optional] | +|**int64** | **Long** | | [optional] | +|**number** | **BigDecimal** | | | +|**_float** | **Float** | | [optional] | +|**_double** | **Double** | | [optional] | +|**decimal** | **BigDecimal** | | [optional] | +|**string** | **String** | | [optional] | +|**_byte** | **byte[]** | | | +|**binary** | **File** | | [optional] | +|**date** | **LocalDate** | | | +|**dateTime** | **OffsetDateTime** | | [optional] | +|**uuid** | **UUID** | | [optional] | +|**password** | **String** | | | +|**patternWithDigits** | **String** | A string that is a 10 digit number. Can have leading zeros. | [optional] | +|**patternWithDigitsAndDelimiter** | **String** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/HasOnlyReadOnly.md b/samples/client/petstore/java-helidon-client/mp/docs/HasOnlyReadOnly.md new file mode 100644 index 0000000000..29da5205db --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/HasOnlyReadOnly.md @@ -0,0 +1,14 @@ + + +# HasOnlyReadOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] [readonly] | +|**foo** | **String** | | [optional] [readonly] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/HealthCheckResult.md b/samples/client/petstore/java-helidon-client/mp/docs/HealthCheckResult.md new file mode 100644 index 0000000000..4885e6f1ca --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/HealthCheckResult.md @@ -0,0 +1,14 @@ + + +# HealthCheckResult + +Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**nullableMessage** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/MapTest.md b/samples/client/petstore/java-helidon-client/mp/docs/MapTest.md new file mode 100644 index 0000000000..54380188e1 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/MapTest.md @@ -0,0 +1,25 @@ + + +# MapTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**mapMapOfString** | **Map<String, Map<String, String>>** | | [optional] | +|**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] | +|**directMap** | **Map<String, Boolean>** | | [optional] | +|**indirectMap** | **Map<String, Boolean>** | | [optional] | + + + +## Enum: Map<String, InnerEnum> + +| Name | Value | +|---- | -----| +| UPPER | "UPPER" | +| LOWER | "lower" | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java-helidon-client/mp/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 0000000000..a5ddf0faa6 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,15 @@ + + +# MixedPropertiesAndAdditionalPropertiesClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**uuid** | **UUID** | | [optional] | +|**dateTime** | **OffsetDateTime** | | [optional] | +|**map** | [**Map<String, Animal>**](Animal.md) | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Model200Response.md b/samples/client/petstore/java-helidon-client/mp/docs/Model200Response.md new file mode 100644 index 0000000000..109411580c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Model200Response.md @@ -0,0 +1,15 @@ + + +# Model200Response + +Model for testing model name starting with number + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **Integer** | | [optional] | +|**propertyClass** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ModelApiResponse.md b/samples/client/petstore/java-helidon-client/mp/docs/ModelApiResponse.md new file mode 100644 index 0000000000..e374c2dd2d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ModelApiResponse.md @@ -0,0 +1,15 @@ + + +# ModelApiResponse + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**code** | **Integer** | | [optional] | +|**type** | **String** | | [optional] | +|**message** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ModelFile.md b/samples/client/petstore/java-helidon-client/mp/docs/ModelFile.md new file mode 100644 index 0000000000..adcde984f5 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ModelFile.md @@ -0,0 +1,14 @@ + + +# ModelFile + +Must be named `File` for test. + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**sourceURI** | **String** | Test capitalization | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ModelList.md b/samples/client/petstore/java-helidon-client/mp/docs/ModelList.md new file mode 100644 index 0000000000..f93ab7dde8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ModelList.md @@ -0,0 +1,13 @@ + + +# ModelList + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**_123list** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ModelReturn.md b/samples/client/petstore/java-helidon-client/mp/docs/ModelReturn.md new file mode 100644 index 0000000000..0bd356861e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ModelReturn.md @@ -0,0 +1,14 @@ + + +# ModelReturn + +Model for testing reserved words + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**_return** | **Integer** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Name.md b/samples/client/petstore/java-helidon-client/mp/docs/Name.md new file mode 100644 index 0000000000..c901d94353 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Name.md @@ -0,0 +1,17 @@ + + +# Name + +Model for testing model name same as property name + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **Integer** | | | +|**snakeCase** | **Integer** | | [optional] [readonly] | +|**property** | **String** | | [optional] | +|**_123number** | **Integer** | | [optional] [readonly] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/NullableClass.md b/samples/client/petstore/java-helidon-client/mp/docs/NullableClass.md new file mode 100644 index 0000000000..fa98c5c6d9 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/NullableClass.md @@ -0,0 +1,24 @@ + + +# NullableClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**integerProp** | **Integer** | | [optional] | +|**numberProp** | **BigDecimal** | | [optional] | +|**booleanProp** | **Boolean** | | [optional] | +|**stringProp** | **String** | | [optional] | +|**dateProp** | **LocalDate** | | [optional] | +|**datetimeProp** | **OffsetDateTime** | | [optional] | +|**arrayNullableProp** | **List<Object>** | | [optional] | +|**arrayAndItemsNullableProp** | **List<Object>** | | [optional] | +|**arrayItemsNullable** | **List<Object>** | | [optional] | +|**objectNullableProp** | **Map<String, Object>** | | [optional] | +|**objectAndItemsNullableProp** | **Map<String, Object>** | | [optional] | +|**objectItemsNullable** | **Map<String, Object>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/NumberOnly.md b/samples/client/petstore/java-helidon-client/mp/docs/NumberOnly.md new file mode 100644 index 0000000000..b8ed1a4cfa --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/NumberOnly.md @@ -0,0 +1,13 @@ + + +# NumberOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**justNumber** | **BigDecimal** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ObjectWithDeprecatedFields.md b/samples/client/petstore/java-helidon-client/mp/docs/ObjectWithDeprecatedFields.md new file mode 100644 index 0000000000..f1cf571f4c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ObjectWithDeprecatedFields.md @@ -0,0 +1,16 @@ + + +# ObjectWithDeprecatedFields + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**uuid** | **String** | | [optional] | +|**id** | **BigDecimal** | | [optional] | +|**deprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] | +|**bars** | **List<String>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Order.md b/samples/client/petstore/java-helidon-client/mp/docs/Order.md new file mode 100644 index 0000000000..27af32855c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Order.md @@ -0,0 +1,28 @@ + + +# Order + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**petId** | **Long** | | [optional] | +|**quantity** | **Integer** | | [optional] | +|**shipDate** | **OffsetDateTime** | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] | +|**complete** | **Boolean** | | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| PLACED | "placed" | +| APPROVED | "approved" | +| DELIVERED | "delivered" | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/OuterComposite.md b/samples/client/petstore/java-helidon-client/mp/docs/OuterComposite.md new file mode 100644 index 0000000000..98b56e0763 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/OuterComposite.md @@ -0,0 +1,15 @@ + + +# OuterComposite + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**myNumber** | **BigDecimal** | | [optional] | +|**myString** | **String** | | [optional] | +|**myBoolean** | **Boolean** | | [optional] | + + + diff --git a/samples/openapi3/client/petstore/java/native/docs/OuterEnum.md b/samples/client/petstore/java-helidon-client/mp/docs/OuterEnum.md similarity index 100% rename from samples/openapi3/client/petstore/java/native/docs/OuterEnum.md rename to samples/client/petstore/java-helidon-client/mp/docs/OuterEnum.md diff --git a/samples/openapi3/client/petstore/java/native/docs/OuterEnumDefaultValue.md b/samples/client/petstore/java-helidon-client/mp/docs/OuterEnumDefaultValue.md similarity index 100% rename from samples/openapi3/client/petstore/java/native/docs/OuterEnumDefaultValue.md rename to samples/client/petstore/java-helidon-client/mp/docs/OuterEnumDefaultValue.md diff --git a/samples/openapi3/client/petstore/java/native/docs/OuterEnumInteger.md b/samples/client/petstore/java-helidon-client/mp/docs/OuterEnumInteger.md similarity index 100% rename from samples/openapi3/client/petstore/java/native/docs/OuterEnumInteger.md rename to samples/client/petstore/java-helidon-client/mp/docs/OuterEnumInteger.md diff --git a/samples/openapi3/client/petstore/java/native/docs/OuterEnumIntegerDefaultValue.md b/samples/client/petstore/java-helidon-client/mp/docs/OuterEnumIntegerDefaultValue.md similarity index 100% rename from samples/openapi3/client/petstore/java/native/docs/OuterEnumIntegerDefaultValue.md rename to samples/client/petstore/java-helidon-client/mp/docs/OuterEnumIntegerDefaultValue.md diff --git a/samples/client/petstore/java-helidon-client/mp/docs/OuterObjectWithEnumProperty.md b/samples/client/petstore/java-helidon-client/mp/docs/OuterObjectWithEnumProperty.md new file mode 100644 index 0000000000..0fafaaa271 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/OuterObjectWithEnumProperty.md @@ -0,0 +1,13 @@ + + +# OuterObjectWithEnumProperty + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**value** | **OuterEnumInteger** | | | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Pet.md b/samples/client/petstore/java-helidon-client/mp/docs/Pet.md new file mode 100644 index 0000000000..54af77a9f5 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Pet.md @@ -0,0 +1,28 @@ + + +# Pet + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **Set<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/PetApi.md b/samples/client/petstore/java-helidon-client/mp/docs/PetApi.md new file mode 100644 index 0000000000..2f1e3c02a2 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/PetApi.md @@ -0,0 +1,349 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store | +| [**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status | +| [**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID | +| [**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet | +| [**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image | +| [**uploadFileWithRequiredFile**](PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) | + + + +## addPet + +> void addPet(pet) + +Add a new pet to the store + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +[**void**](Void.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | +| **405** | Invalid input | - | + + +## deletePet + +> void deletePet(petId, apiKey) + +Deletes a pet + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| Pet id to delete | | +| **apiKey** | **String**| | [optional] | + +### Return type + +[**void**](Void.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | +| **400** | Invalid pet value | - | + + +## findPetsByStatus + +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + + +## findPetsByTags + +> Set<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **tags** | [**Set<String>**](String.md)| Tags to filter by | | + +### Return type + +[**Set<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + + +## getPetById + +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to return | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## updatePet + +> void updatePet(pet) + +Update an existing pet + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +[**void**](Void.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + + +## updatePetWithForm + +> void updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet that needs to be updated | | +| **name** | **String**| Updated name of the pet | [optional] | +| **status** | **String**| Updated status of the pet | [optional] | + +### Return type + +[**void**](Void.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | +| **405** | Invalid input | - | + + +## uploadFile + +> ModelApiResponse uploadFile(petId, additionalMetadata, _file) + +uploads an image + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to update | | +| **additionalMetadata** | **String**| Additional data to pass to server | [optional] | +| **_file** | **File**| file to upload | [optional] | + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## uploadFileWithRequiredFile + +> ModelApiResponse uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata) + +uploads an image (required) + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to update | | +| **requiredFile** | **File**| file to upload | | +| **additionalMetadata** | **String**| Additional data to pass to server | [optional] | + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/ReadOnlyFirst.md b/samples/client/petstore/java-helidon-client/mp/docs/ReadOnlyFirst.md new file mode 100644 index 0000000000..ad6af7ee15 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/ReadOnlyFirst.md @@ -0,0 +1,14 @@ + + +# ReadOnlyFirst + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] [readonly] | +|**baz** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/SingleRefType.md b/samples/client/petstore/java-helidon-client/mp/docs/SingleRefType.md new file mode 100644 index 0000000000..cc269bb871 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/SingleRefType.md @@ -0,0 +1,13 @@ + + +# SingleRefType + +## Enum + + +* `ADMIN` (value: `"admin"`) + +* `USER` (value: `"user"`) + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/SpecialModelName.md b/samples/client/petstore/java-helidon-client/mp/docs/SpecialModelName.md new file mode 100644 index 0000000000..4b6a06e362 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/SpecialModelName.md @@ -0,0 +1,13 @@ + + +# SpecialModelName + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**$specialPropertyName** | **Long** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/StoreApi.md b/samples/client/petstore/java-helidon-client/mp/docs/StoreApi.md new file mode 100644 index 0000000000..299fb32656 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/StoreApi.md @@ -0,0 +1,153 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID | +| [**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status | +| [**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID | +| [**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet | + + + +## deleteOrder + +> void deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **orderId** | **String**| ID of the order that needs to be deleted | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## getInventory + +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Map<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## getOrderById + +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **orderId** | **Long**| ID of pet that needs to be fetched | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## placeOrder + +> Order placeOrder(order) + +Place an order for a pet + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **order** | [**Order**](Order.md)| order placed for purchasing the pet | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/Tag.md b/samples/client/petstore/java-helidon-client/mp/docs/Tag.md new file mode 100644 index 0000000000..5088b2dd1c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/Tag.md @@ -0,0 +1,14 @@ + + +# Tag + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/User.md b/samples/client/petstore/java-helidon-client/mp/docs/User.md new file mode 100644 index 0000000000..08813e4b10 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/User.md @@ -0,0 +1,20 @@ + + +# User + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**username** | **String** | | [optional] | +|**firstName** | **String** | | [optional] | +|**lastName** | **String** | | [optional] | +|**email** | **String** | | [optional] | +|**password** | **String** | | [optional] | +|**phone** | **String** | | [optional] | +|**userStatus** | **Integer** | User Status | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/mp/docs/UserApi.md b/samples/client/petstore/java-helidon-client/mp/docs/UserApi.md new file mode 100644 index 0000000000..5f33613cbe --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/docs/UserApi.md @@ -0,0 +1,300 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**createUser**](UserApi.md#createUser) | **POST** /user | Create user | +| [**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array | +| [**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array | +| [**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user | +| [**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name | +| [**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system | +| [**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session | +| [**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user | + + + +## createUser + +> void createUser(user) + +Create user + +This can only be done by the logged in user. + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **user** | [**User**](User.md)| Created user object | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## createUsersWithArrayInput + +> void createUsersWithArrayInput(user) + +Creates list of users with given input array + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **user** | [**List<User>**](User.md)| List of user object | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## createUsersWithListInput + +> void createUsersWithListInput(user) + +Creates list of users with given input array + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **user** | [**List<User>**](User.md)| List of user object | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## deleteUser + +> void deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The name that needs to be deleted | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## getUserByName + +> User getUserByName(username) + +Get user by user name + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The name that needs to be fetched. Use user1 for testing. | | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## loginUser + +> String loginUser(username, password) + +Logs user into the system + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The user name for login | | +| **password** | **String**| The password for login in clear text | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
        * X-Expires-After - date in UTC when token expires
        | +| **400** | Invalid username/password supplied | - | + + +## logoutUser + +> void logoutUser() + +Logs out current logged in user session + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## updateUser + +> void updateUser(username, user) + +Updated user + +This can only be done by the logged in user. + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| name that need to be deleted | | +| **user** | [**User**](User.md)| Updated user object | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/samples/client/petstore/java-helidon-client/mp/pom.xml b/samples/client/petstore/java-helidon-client/mp/pom.xml new file mode 100644 index 0000000000..ccf28c4c1a --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/pom.xml @@ -0,0 +1,78 @@ + + 4.0.0 + org.openapitools + + io.helidon.applications + helidon-mp + 3.0.1 + + + petstore-helidon-client-mp + petstore-helidon-client-mp + 1.0.0 + https://github.com/openapitools/openapi-generator + OpenAPI Java + jar + + + + io.helidon.microprofile.rest-client + helidon-microprofile-rest-client + + + io.helidon.microprofile.config + helidon-microprofile-config + + + org.glassfish.jersey.ext.cdi + jersey-cdi1x + + + jakarta.enterprise + jakarta.enterprise.cdi-api + + + jakarta.json + jakarta.json-api + + + org.glassfish.jersey.media + jersey-media-json-jackson + + + org.openapitools + jackson-databind-nullable + 0.2.2 + + + org.junit.jupiter + junit-jupiter-api + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libs + + + + + org.jboss.jandex + jandex-maven-plugin + + + make-index + + + + + + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/JavaTimeFormatter.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/JavaTimeFormatter.java new file mode 100644 index 0000000000..8a222f5240 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/JavaTimeFormatter.java @@ -0,0 +1,64 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonClientCodegen") +public class JavaTimeFormatter { + + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + /** + * Format the given {@code OffsetDateTime} object into string. + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/RFC3339DateFormat.java new file mode 100644 index 0000000000..dd96c18c0d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -0,0 +1,57 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.text.DecimalFormat; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + this.numberFormat = new DecimalFormat(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return super.clone(); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/AnotherFakeApi.java new file mode 100644 index 0000000000..c2a678cc0f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -0,0 +1,49 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +import org.openapitools.client.model.Client; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +@RegisterRestClient +@RegisterProvider(ApiExceptionMapper.class) +@Path("/another-fake/dummy") +public interface AnotherFakeApi { + + /** + * To test special tags + * To test special tags and operation ID starting with number + */ + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + Client call123testSpecialTags(Client client) throws ApiException, ProcessingException; +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/ApiException.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/ApiException.java new file mode 100644 index 0000000000..c05f1ebf84 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/ApiException.java @@ -0,0 +1,30 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import jakarta.ws.rs.core.Response; + +public class ApiException extends Exception { + private static final long serialVersionUID = 1L; + + private final Response response; + + public ApiException(Response response) { + super("Api response has status code " + response.getStatus()); + this.response = response; + } + + public Response getResponse() { + return this.response; + } +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/ApiExceptionMapper.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/ApiExceptionMapper.java new file mode 100644 index 0000000000..4c425b5669 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/ApiExceptionMapper.java @@ -0,0 +1,33 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.ext.Provider; + +import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper; + +@Provider +public class ApiExceptionMapper implements ResponseExceptionMapper { + + @Override + public boolean handles(int status, MultivaluedMap headers) { + return status >= 400; + } + + @Override + public ApiException toThrowable(Response response) { + return new ApiException(response); + } +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/DefaultApi.java new file mode 100644 index 0000000000..a53eaf73da --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -0,0 +1,44 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +import org.openapitools.client.model.FooGetDefaultResponse; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +@RegisterRestClient +@RegisterProvider(ApiExceptionMapper.class) +@Path("/foo") +public interface DefaultApi { + + @GET + + @Produces({ "application/json" }) + FooGetDefaultResponse fooGet() throws ApiException, ProcessingException; +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeApi.java new file mode 100644 index 0000000000..122edf2255 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeApi.java @@ -0,0 +1,169 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import org.openapitools.client.model.EnumClass; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.HealthCheckResult; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.OuterObjectWithEnumProperty; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.User; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +@RegisterRestClient +@RegisterProvider(ApiExceptionMapper.class) +@Path("/fake") +public interface FakeApi { + + /** + * Health check endpoint + */ + @GET + @Path("/health") + @Produces({ "application/json" }) + HealthCheckResult fakeHealthGet() throws ApiException, ProcessingException; + + /** + * test http signature authentication + */ + @GET + @Path("/http-signature-test") + @Consumes({ "application/json", "application/xml" }) + void fakeHttpSignatureTest(Pet pet, @QueryParam("query_1") String query1, @HeaderParam("header_1") String header1) throws ApiException, ProcessingException; + + @POST + @Path("/outer/boolean") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + Boolean fakeOuterBooleanSerialize(Boolean body) throws ApiException, ProcessingException; + + @POST + @Path("/outer/composite") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + OuterComposite fakeOuterCompositeSerialize(OuterComposite outerComposite) throws ApiException, ProcessingException; + + @POST + @Path("/outer/number") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + BigDecimal fakeOuterNumberSerialize(BigDecimal body) throws ApiException, ProcessingException; + + @POST + @Path("/outer/string") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + String fakeOuterStringSerialize(String body) throws ApiException, ProcessingException; + + @POST + @Path("/property/enum-int") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty) throws ApiException, ProcessingException; + + @PUT + @Path("/body-with-binary") + @Consumes({ "image/png" }) + void testBodyWithBinary(File body) throws ApiException, ProcessingException; + + @PUT + @Path("/body-with-file-schema") + @Consumes({ "application/json" }) + void testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) throws ApiException, ProcessingException; + + @PUT + @Path("/body-with-query-params") + @Consumes({ "application/json" }) + void testBodyWithQueryParams(@QueryParam("query") String query, User user) throws ApiException, ProcessingException; + + /** + * To test \"client\" model + * To test \"client\" model + */ + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + Client testClientModel(Client client) throws ApiException, ProcessingException; + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + */ + @POST + + @Consumes({ "application/x-www-form-urlencoded" }) + void testEndpointParameters(@FormParam("number") BigDecimal number, @FormParam("double") Double _double, @FormParam("pattern_without_delimiter") String patternWithoutDelimiter, @FormParam("byte") byte[] _byte, @FormParam("integer") Integer integer, @FormParam("int32") Integer int32, @FormParam("int64") Long int64, @FormParam("float") Float _float, @FormParam("string") String string, @FormParam("binary") File binary, @FormParam("date") LocalDate date, @FormParam("dateTime") OffsetDateTime dateTime, @FormParam("password") String password, @FormParam("callback") String paramCallback) throws ApiException, ProcessingException; + + /** + * To test enum parameters + * To test enum parameters + */ + @GET + + @Consumes({ "application/x-www-form-urlencoded" }) + void testEnumParameters(@HeaderParam("enum_header_string_array") List enumHeaderStringArray, @HeaderParam("enum_header_string") String enumHeaderString, @QueryParam("enum_query_string_array") List enumQueryStringArray, @QueryParam("enum_query_string") @DefaultValue("-efg") String enumQueryString, @QueryParam("enum_query_integer") Integer enumQueryInteger, @QueryParam("enum_query_double") Double enumQueryDouble, @QueryParam("enum_query_model_array") List enumQueryModelArray, @FormParam("enum_form_string_array") List enumFormStringArray, @FormParam("enum_form_string") String enumFormString) throws ApiException, ProcessingException; + + /** + * Fake endpoint to test group parameters (optional) + * Fake endpoint to test group parameters (optional) + */ + @DELETE + + void testGroupParameters(@QueryParam("required_string_group") Integer requiredStringGroup, @HeaderParam("required_boolean_group") Boolean requiredBooleanGroup, @QueryParam("required_int64_group") Long requiredInt64Group, @QueryParam("string_group") Integer stringGroup, @HeaderParam("boolean_group") Boolean booleanGroup, @QueryParam("int64_group") Long int64Group) throws ApiException, ProcessingException; + + /** + * test inline additionalProperties + * + */ + @POST + @Path("/inline-additionalProperties") + @Consumes({ "application/json" }) + void testInlineAdditionalProperties(Map requestBody) throws ApiException, ProcessingException; + + /** + * test json serialization of form data + * + */ + @GET + @Path("/jsonFormData") + @Consumes({ "application/x-www-form-urlencoded" }) + void testJsonFormData(@FormParam("param") String param, @FormParam("param2") String param2) throws ApiException, ProcessingException; + + @PUT + @Path("/test-query-parameters") + void testQueryParameterCollectionFormat(@QueryParam("pipe") List pipe, @QueryParam("ioutil") List ioutil, @QueryParam("http") List http, @QueryParam("url") List url, @QueryParam("context") List context, @QueryParam("allowEmpty") String allowEmpty, @QueryParam("language") Map language) throws ApiException, ProcessingException; +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java new file mode 100644 index 0000000000..aaeb4a55e4 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -0,0 +1,49 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +import org.openapitools.client.model.Client; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +@RegisterRestClient +@RegisterProvider(ApiExceptionMapper.class) +@Path("/fake_classname_test") +public interface FakeClassnameTags123Api { + + /** + * To test class name in snake case + * To test class name in snake case + */ + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + Client testClassname(Client client) throws ApiException, ProcessingException; +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/PetApi.java new file mode 100644 index 0000000000..0248f2e691 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/PetApi.java @@ -0,0 +1,126 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; +import java.util.Set; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +@RegisterRestClient +@RegisterProvider(ApiExceptionMapper.class) +@Path("") +public interface PetApi { + + /** + * Add a new pet to the store + * + */ + @POST + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + void addPet(Pet pet) throws ApiException, ProcessingException; + + /** + * Deletes a pet + * + */ + @DELETE + @Path("/pet/{petId}") + void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey) throws ApiException, ProcessingException; + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + */ + @GET + @Path("/pet/findByStatus") + @Produces({ "application/xml", "application/json" }) + List findPetsByStatus(@QueryParam("status") List status) throws ApiException, ProcessingException; + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @deprecated + */ + @Deprecated + @GET + @Path("/pet/findByTags") + @Produces({ "application/xml", "application/json" }) + Set findPetsByTags(@QueryParam("tags") Set tags) throws ApiException, ProcessingException; + + /** + * Find pet by ID + * Returns a single pet + */ + @GET + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + Pet getPetById(@PathParam("petId") Long petId) throws ApiException, ProcessingException; + + /** + * Update an existing pet + * + */ + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + void updatePet(Pet pet) throws ApiException, ProcessingException; + + /** + * Updates a pet in the store with form data + * + */ + @POST + @Path("/pet/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + void updatePetWithForm(@PathParam("petId") Long petId, @FormParam("name") String name, @FormParam("status") String status) throws ApiException, ProcessingException; + + /** + * uploads an image + * + */ + @POST + @Path("/pet/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + ModelApiResponse uploadFile(@PathParam("petId") Long petId, @FormParam("additionalMetadata") String additionalMetadata, @FormParam("file") File _file) throws ApiException, ProcessingException; + + /** + * uploads an image (required) + * + */ + @POST + @Path("/fake/{petId}/uploadImageWithRequiredFile") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + ModelApiResponse uploadFileWithRequiredFile(@PathParam("petId") Long petId, @FormParam("requiredFile") File requiredFile, @FormParam("additionalMetadata") String additionalMetadata) throws ApiException, ProcessingException; +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/StoreApi.java new file mode 100644 index 0000000000..ff2dfbfbca --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/StoreApi.java @@ -0,0 +1,75 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +import org.openapitools.client.model.Order; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +@RegisterRestClient +@RegisterProvider(ApiExceptionMapper.class) +@Path("/store") +public interface StoreApi { + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + */ + @DELETE + @Path("/order/{order_id}") + void deleteOrder(@PathParam("order_id") String orderId) throws ApiException, ProcessingException; + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + @GET + @Path("/inventory") + @Produces({ "application/json" }) + Map getInventory() throws ApiException, ProcessingException; + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + */ + @GET + @Path("/order/{order_id}") + @Produces({ "application/xml", "application/json" }) + Order getOrderById(@PathParam("order_id") Long orderId) throws ApiException, ProcessingException; + + /** + * Place an order for a pet + * + */ + @POST + @Path("/order") + @Consumes({ "application/json" }) + @Produces({ "application/xml", "application/json" }) + Order placeOrder(Order order) throws ApiException, ProcessingException; +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/UserApi.java new file mode 100644 index 0000000000..48e64286d8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/UserApi.java @@ -0,0 +1,110 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +import java.time.OffsetDateTime; +import org.openapitools.client.model.User; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +@RegisterRestClient +@RegisterProvider(ApiExceptionMapper.class) +@Path("/user") +public interface UserApi { + + /** + * Create user + * This can only be done by the logged in user. + */ + @POST + + @Consumes({ "application/json" }) + void createUser(User user) throws ApiException, ProcessingException; + + /** + * Creates list of users with given input array + * + */ + @POST + @Path("/createWithArray") + @Consumes({ "application/json" }) + void createUsersWithArrayInput(List user) throws ApiException, ProcessingException; + + /** + * Creates list of users with given input array + * + */ + @POST + @Path("/createWithList") + @Consumes({ "application/json" }) + void createUsersWithListInput(List user) throws ApiException, ProcessingException; + + /** + * Delete user + * This can only be done by the logged in user. + */ + @DELETE + @Path("/{username}") + void deleteUser(@PathParam("username") String username) throws ApiException, ProcessingException; + + /** + * Get user by user name + * + */ + @GET + @Path("/{username}") + @Produces({ "application/xml", "application/json" }) + User getUserByName(@PathParam("username") String username) throws ApiException, ProcessingException; + + /** + * Logs user into the system + * + */ + @GET + @Path("/login") + @Produces({ "application/xml", "application/json" }) + String loginUser(@QueryParam("username") String username, @QueryParam("password") String password) throws ApiException, ProcessingException; + + /** + * Logs out current logged in user session + * + */ + @GET + @Path("/logout") + void logoutUser() throws ApiException, ProcessingException; + + /** + * Updated user + * This can only be done by the logged in user. + */ + @PUT + @Path("/{username}") + @Consumes({ "application/json" }) + void updateUser(@PathParam("username") String username, User user) throws ApiException, ProcessingException; +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java new file mode 100644 index 0000000000..abc3d296fa --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,108 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; + + + + +public class AdditionalPropertiesClass { + + private Map mapProperty = null; + + private Map> mapOfMapProperty = null; + + /** + * Get mapProperty + * @return mapProperty + **/ + public Map getMapProperty() { + return mapProperty; + } + + /** + * Set mapProperty + **/ + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + /** + * Set mapOfMapProperty + **/ + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java new file mode 100644 index 0000000000..cb7b8b0a68 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java @@ -0,0 +1,97 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.SingleRefType; + + + + +public class AllOfWithSingleRef { + + private String username; + + private SingleRefType singleRefType; + + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + + /** + * Set username + **/ + public void setUsername(String username) { + this.username = username; + } + + public AllOfWithSingleRef username(String username) { + this.username = username; + return this; + } + + /** + * Get singleRefType + * @return singleRefType + **/ + public SingleRefType getSingleRefType() { + return singleRefType; + } + + /** + * Set singleRefType + **/ + public void setSingleRefType(SingleRefType singleRefType) { + this.singleRefType = singleRefType; + } + + public AllOfWithSingleRef singleRefType(SingleRefType singleRefType) { + this.singleRefType = singleRefType; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfWithSingleRef {\n"); + + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" singleRefType: ").append(toIndentedString(singleRefType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Animal.java new file mode 100644 index 0000000000..36ecf9c54f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Animal.java @@ -0,0 +1,101 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Cat; +import org.openapitools.client.model.Dog; + + + + +public class Animal { + + private String className; + + private String color = "red"; + + /** + * Get className + * @return className + **/ + public String getClassName() { + return className; + } + + /** + * Set className + **/ + public void setClassName(String className) { + this.className = className; + } + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get color + * @return color + **/ + public String getColor() { + return color; + } + + /** + * Set color + **/ + public void setColor(String color) { + this.color = color; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 0000000000..d451b999d8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,81 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + +public class ArrayOfArrayOfNumberOnly { + + private List> arrayArrayNumber = null; + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + /** + * Set arrayArrayNumber + **/ + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java new file mode 100644 index 0000000000..3b64bf9e87 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,81 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + +public class ArrayOfNumberOnly { + + private List arrayNumber = null; + + /** + * Get arrayNumber + * @return arrayNumber + **/ + public List getArrayNumber() { + return arrayNumber; + } + + /** + * Set arrayNumber + **/ + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ArrayTest.java new file mode 100644 index 0000000000..ab1f6d1791 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -0,0 +1,137 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ReadOnlyFirst; + + + + +public class ArrayTest { + + private List arrayOfString = null; + + private List> arrayArrayOfInteger = null; + + private List> arrayArrayOfModel = null; + + /** + * Get arrayOfString + * @return arrayOfString + **/ + public List getArrayOfString() { + return arrayOfString; + } + + /** + * Set arrayOfString + **/ + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + /** + * Set arrayArrayOfInteger + **/ + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + /** + * Set arrayArrayOfModel + **/ + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Capitalization.java new file mode 100644 index 0000000000..f6d3fde93d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Capitalization.java @@ -0,0 +1,191 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Capitalization { + + private String smallCamel; + + private String capitalCamel; + + private String smallSnake; + + private String capitalSnake; + + private String scAETHFlowPoints; + + /** + * Name of the pet + **/ + private String ATT_NAME; + + /** + * Get smallCamel + * @return smallCamel + **/ + public String getSmallCamel() { + return smallCamel; + } + + /** + * Set smallCamel + **/ + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + public String getCapitalCamel() { + return capitalCamel; + } + + /** + * Set capitalCamel + **/ + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + public String getSmallSnake() { + return smallSnake; + } + + /** + * Set smallSnake + **/ + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + public String getCapitalSnake() { + return capitalSnake; + } + + /** + * Set capitalSnake + **/ + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + /** + * Set scAETHFlowPoints + **/ + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + public String getATTNAME() { + return ATT_NAME; + } + + /** + * Set ATT_NAME + **/ + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Cat.java new file mode 100644 index 0000000000..be9c695456 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Cat.java @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Animal; + + + + +public class Cat extends Animal { + + private Boolean declawed; + + /** + * Get declawed + * @return declawed + **/ + public Boolean getDeclawed() { + return declawed; + } + + /** + * Set declawed + **/ + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/CatAllOf.java new file mode 100644 index 0000000000..2b54aad5ba --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class CatAllOf { + + private Boolean declawed; + + /** + * Get declawed + * @return declawed + **/ + public Boolean getDeclawed() { + return declawed; + } + + /** + * Set declawed + **/ + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + public CatAllOf declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CatAllOf {\n"); + + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Category.java new file mode 100644 index 0000000000..8da9901110 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Category.java @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Category { + + private Long id; + + private String name = "default-name"; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Category name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ClassModel.java new file mode 100644 index 0000000000..de44db959b --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ClassModel.java @@ -0,0 +1,76 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Model for testing model with \"_class\" property + **/ + +public class ClassModel { + + private String propertyClass; + + /** + * Get propertyClass + * @return propertyClass + **/ + public String getPropertyClass() { + return propertyClass; + } + + /** + * Set propertyClass + **/ + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Client.java new file mode 100644 index 0000000000..0ad715df8d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Client.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Client { + + private String client; + + /** + * Get client + * @return client + **/ + public String getClient() { + return client; + } + + /** + * Set client + **/ + public void setClient(String client) { + this.client = client; + } + + public Client client(String client) { + this.client = client; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/DeprecatedObject.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/DeprecatedObject.java new file mode 100644 index 0000000000..aaaed8e7f3 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/DeprecatedObject.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class DeprecatedObject { + + private String name; + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public DeprecatedObject name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeprecatedObject {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Dog.java new file mode 100644 index 0000000000..069dab8392 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Dog.java @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Animal; + + + + +public class Dog extends Animal { + + private String breed; + + /** + * Get breed + * @return breed + **/ + public String getBreed() { + return breed; + } + + /** + * Set breed + **/ + public void setBreed(String breed) { + this.breed = breed; + } + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/DogAllOf.java new file mode 100644 index 0000000000..5dc63ce038 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class DogAllOf { + + private String breed; + + /** + * Get breed + * @return breed + **/ + public String getBreed() { + return breed; + } + + /** + * Set breed + **/ + public void setBreed(String breed) { + this.breed = breed; + } + + public DogAllOf breed(String breed) { + this.breed = breed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DogAllOf {\n"); + + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/EnumArrays.java new file mode 100644 index 0000000000..1a9c48c72c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -0,0 +1,145 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; + + + + +public class EnumArrays { + +public enum JustSymbolEnum { + + GREATER_THAN_OR_EQUAL_TO(String.valueOf(">=")), DOLLAR(String.valueOf("$")); + + String value; + + JustSymbolEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private JustSymbolEnum justSymbol; + +public enum ArrayEnumEnum { + + FISH(String.valueOf("fish")), CRAB(String.valueOf("crab")); + + String value; + + ArrayEnumEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private List arrayEnum = null; + + /** + * Get justSymbol + * @return justSymbol + **/ + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + /** + * Set justSymbol + **/ + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + public List getArrayEnum() { + return arrayEnum; + } + + /** + * Set arrayEnum + **/ + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/EnumClass.java new file mode 100644 index 0000000000..eed52272f7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/EnumClass.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/EnumTest.java new file mode 100644 index 0000000000..e234097abc --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/EnumTest.java @@ -0,0 +1,326 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.OuterEnumDefaultValue; +import org.openapitools.client.model.OuterEnumInteger; +import org.openapitools.client.model.OuterEnumIntegerDefaultValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + + + + +public class EnumTest { + +public enum EnumStringEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); + + String value; + + EnumStringEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private EnumStringEnum enumString; + +public enum EnumStringRequiredEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); + + String value; + + EnumStringRequiredEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private EnumStringRequiredEnum enumStringRequired; + +public enum EnumIntegerEnum { + + NUMBER_1(Integer.valueOf(1)), NUMBER_MINUS_1(Integer.valueOf(-1)); + + Integer value; + + EnumIntegerEnum (Integer v) { + value = v; + } + + public Integer value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private EnumIntegerEnum enumInteger; + +public enum EnumNumberEnum { + + NUMBER_1_DOT_1(Double.valueOf(1.1)), NUMBER_MINUS_1_DOT_2(Double.valueOf(-1.2)); + + Double value; + + EnumNumberEnum (Double v) { + value = v; + } + + public Double value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private EnumNumberEnum enumNumber; + + private OuterEnum outerEnum; + + private OuterEnumInteger outerEnumInteger; + + private OuterEnumDefaultValue outerEnumDefaultValue = OuterEnumDefaultValue.PLACED; + + private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; + + /** + * Get enumString + * @return enumString + **/ + public EnumStringEnum getEnumString() { + return enumString; + } + + /** + * Set enumString + **/ + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumStringRequired + * @return enumStringRequired + **/ + public EnumStringRequiredEnum getEnumStringRequired() { + return enumStringRequired; + } + + /** + * Set enumStringRequired + **/ + public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + } + + public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + /** + * Set enumInteger + **/ + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + /** + * Set enumNumber + **/ + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + public OuterEnum getOuterEnum() { + return outerEnum; + } + + /** + * Set outerEnum + **/ + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnumInteger + * @return outerEnumInteger + **/ + public OuterEnumInteger getOuterEnumInteger() { + return outerEnumInteger; + } + + /** + * Set outerEnumInteger + **/ + public void setOuterEnumInteger(OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + } + + public EnumTest outerEnumInteger(OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + return this; + } + + /** + * Get outerEnumDefaultValue + * @return outerEnumDefaultValue + **/ + public OuterEnumDefaultValue getOuterEnumDefaultValue() { + return outerEnumDefaultValue; + } + + /** + * Set outerEnumDefaultValue + **/ + public void setOuterEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + } + + public EnumTest outerEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + return this; + } + + /** + * Get outerEnumIntegerDefaultValue + * @return outerEnumIntegerDefaultValue + **/ + public OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() { + return outerEnumIntegerDefaultValue; + } + + /** + * Set outerEnumIntegerDefaultValue + **/ + public void setOuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + } + + public EnumTest outerEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumStringRequired: ").append(toIndentedString(enumStringRequired)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append(" outerEnumInteger: ").append(toIndentedString(outerEnumInteger)).append("\n"); + sb.append(" outerEnumDefaultValue: ").append(toIndentedString(outerEnumDefaultValue)).append("\n"); + sb.append(" outerEnumIntegerDefaultValue: ").append(toIndentedString(outerEnumIntegerDefaultValue)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java new file mode 100644 index 0000000000..dd3716a2b1 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -0,0 +1,104 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ModelFile; + + + + +public class FileSchemaTestClass { + + private ModelFile _file; + + private List files = null; + + /** + * Get _file + * @return _file + **/ + public ModelFile getFile() { + return _file; + } + + /** + * Set _file + **/ + public void setFile(ModelFile _file) { + this._file = _file; + } + + public FileSchemaTestClass _file(ModelFile _file) { + this._file = _file; + return this; + } + + /** + * Get files + * @return files + **/ + public List getFiles() { + return files; + } + + /** + * Set files + **/ + public void setFiles(List files) { + this.files = files; + } + + public FileSchemaTestClass files(List files) { + this.files = files; + return this; + } + + public FileSchemaTestClass addFilesItem(ModelFile filesItem) { + this.files.add(filesItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FileSchemaTestClass {\n"); + + sb.append(" _file: ").append(toIndentedString(_file)).append("\n"); + sb.append(" files: ").append(toIndentedString(files)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Foo.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Foo.java new file mode 100644 index 0000000000..fcafaf7682 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Foo.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Foo { + + private String bar = "bar"; + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + /** + * Set bar + **/ + public void setBar(String bar) { + this.bar = bar; + } + + public Foo bar(String bar) { + this.bar = bar; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Foo {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java new file mode 100644 index 0000000000..27971dae91 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Foo; + + + + +public class FooGetDefaultResponse { + + private Foo string; + + /** + * Get string + * @return string + **/ + public Foo getString() { + return string; + } + + /** + * Set string + **/ + public void setString(Foo string) { + this.string = string; + } + + public FooGetDefaultResponse string(Foo string) { + this.string = string; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FooGetDefaultResponse {\n"); + + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FormatTest.java new file mode 100644 index 0000000000..6f6b62d497 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FormatTest.java @@ -0,0 +1,439 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; + + + + +public class FormatTest { + + private Integer integer; + + private Integer int32; + + private Long int64; + + private BigDecimal number; + + private Float _float; + + private Double _double; + + private BigDecimal decimal; + + private String string; + + private byte[] _byte; + + private File binary; + + private LocalDate date; + + private OffsetDateTime dateTime; + + private UUID uuid; + + private String password; + + /** + * A string that is a 10 digit number. Can have leading zeros. + **/ + private String patternWithDigits; + + /** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + **/ + private String patternWithDigitsAndDelimiter; + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + public Integer getInteger() { + return integer; + } + + /** + * Set integer + **/ + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + public Integer getInt32() { + return int32; + } + + /** + * Set int32 + **/ + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + public Long getInt64() { + return int64; + } + + /** + * Set int64 + **/ + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + public BigDecimal getNumber() { + return number; + } + + /** + * Set number + **/ + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + public Float getFloat() { + return _float; + } + + /** + * Set _float + **/ + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + public Double getDouble() { + return _double; + } + + /** + * Set _double + **/ + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get decimal + * @return decimal + **/ + public BigDecimal getDecimal() { + return decimal; + } + + /** + * Set decimal + **/ + public void setDecimal(BigDecimal decimal) { + this.decimal = decimal; + } + + public FormatTest decimal(BigDecimal decimal) { + this.decimal = decimal; + return this; + } + + /** + * Get string + * @return string + **/ + public String getString() { + return string; + } + + /** + * Set string + **/ + public void setString(String string) { + this.string = string; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + public byte[] getByte() { + return _byte; + } + + /** + * Set _byte + **/ + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get binary + * @return binary + **/ + public File getBinary() { + return binary; + } + + /** + * Set binary + **/ + public void setBinary(File binary) { + this.binary = binary; + } + + public FormatTest binary(File binary) { + this.binary = binary; + return this; + } + + /** + * Get date + * @return date + **/ + public LocalDate getDate() { + return date; + } + + /** + * Set date + **/ + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + public OffsetDateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + **/ + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + public UUID getUuid() { + return uuid; + } + + /** + * Set uuid + **/ + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get password + * @return password + **/ + public String getPassword() { + return password; + } + + /** + * Set password + **/ + public void setPassword(String password) { + this.password = password; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * A string that is a 10 digit number. Can have leading zeros. + * @return patternWithDigits + **/ + public String getPatternWithDigits() { + return patternWithDigits; + } + + /** + * Set patternWithDigits + **/ + public void setPatternWithDigits(String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + } + + public FormatTest patternWithDigits(String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + return this; + } + + /** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + * @return patternWithDigitsAndDelimiter + **/ + public String getPatternWithDigitsAndDelimiter() { + return patternWithDigitsAndDelimiter; + } + + /** + * Set patternWithDigitsAndDelimiter + **/ + public void setPatternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + } + + public FormatTest patternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" decimal: ").append(toIndentedString(decimal)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); + sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java new file mode 100644 index 0000000000..72566c02dd --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class HasOnlyReadOnly { + + private String bar; + + private String foo; + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + + /** + * Get foo + * @return foo + **/ + public String getFoo() { + return foo; + } + + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/HealthCheckResult.java new file mode 100644 index 0000000000..48cec9f2da --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -0,0 +1,80 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + + + +/** + * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + **/ + +public class HealthCheckResult { + + private String nullableMessage; + + /** + * Get nullableMessage + * @return nullableMessage + **/ + public String getNullableMessage() { + return nullableMessage; + } + + /** + * Set nullableMessage + **/ + public void setNullableMessage(String nullableMessage) { + this.nullableMessage = nullableMessage; + } + + public HealthCheckResult nullableMessage(String nullableMessage) { + this.nullableMessage = nullableMessage; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HealthCheckResult {\n"); + + sb.append(" nullableMessage: ").append(toIndentedString(nullableMessage)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/MapTest.java new file mode 100644 index 0000000000..ec54a8ae42 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/MapTest.java @@ -0,0 +1,185 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; + + + + +public class MapTest { + + private Map> mapMapOfString = null; + +public enum InnerEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")); + + String value; + + InnerEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private Map mapOfEnumString = null; + + private Map directMap = null; + + private Map indirectMap = null; + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + public Map> getMapMapOfString() { + return mapMapOfString; + } + + /** + * Set mapMapOfString + **/ + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + /** + * Set mapOfEnumString + **/ + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get directMap + * @return directMap + **/ + public Map getDirectMap() { + return directMap; + } + + /** + * Set directMap + **/ + public void setDirectMap(Map directMap) { + this.directMap = directMap; + } + + public MapTest directMap(Map directMap) { + this.directMap = directMap; + return this; + } + + public MapTest putDirectMapItem(String key, Boolean directMapItem) { + this.directMap.put(key, directMapItem); + return this; + } + + /** + * Get indirectMap + * @return indirectMap + **/ + public Map getIndirectMap() { + return indirectMap; + } + + /** + * Set indirectMap + **/ + public void setIndirectMap(Map indirectMap) { + this.indirectMap = indirectMap; + } + + public MapTest indirectMap(Map indirectMap) { + this.indirectMap = indirectMap; + return this; + } + + public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { + this.indirectMap.put(key, indirectMapItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append(" directMap: ").append(toIndentedString(directMap)).append("\n"); + sb.append(" indirectMap: ").append(toIndentedString(indirectMap)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 0000000000..de307d1e28 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,129 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.openapitools.client.model.Animal; + + + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private UUID uuid; + + private OffsetDateTime dateTime; + + private Map map = null; + + /** + * Get uuid + * @return uuid + **/ + public UUID getUuid() { + return uuid; + } + + /** + * Set uuid + **/ + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + public OffsetDateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + **/ + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get map + * @return map + **/ + public Map getMap() { + return map; + } + + /** + * Set map + **/ + public void setMap(Map map) { + this.map = map; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Model200Response.java new file mode 100644 index 0000000000..393f65f83e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Model200Response.java @@ -0,0 +1,99 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Model for testing model name starting with number + **/ + +public class Model200Response { + + private Integer name; + + private String propertyClass; + + /** + * Get name + * @return name + **/ + public Integer getName() { + return name; + } + + /** + * Set name + **/ + public void setName(Integer name) { + this.name = name; + } + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + public String getPropertyClass() { + return propertyClass; + } + + /** + * Set propertyClass + **/ + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelApiResponse.java new file mode 100644 index 0000000000..881fc2677d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -0,0 +1,119 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class ModelApiResponse { + + private Integer code; + + private String type; + + private String message; + + /** + * Get code + * @return code + **/ + public Integer getCode() { + return code; + } + + /** + * Set code + **/ + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get type + * @return type + **/ + public String getType() { + return type; + } + + /** + * Set type + **/ + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get message + * @return message + **/ + public String getMessage() { + return message; + } + + /** + * Set message + **/ + public void setMessage(String message) { + this.message = message; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelFile.java new file mode 100644 index 0000000000..3c1cf785ea --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelFile.java @@ -0,0 +1,79 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Must be named `File` for test. + **/ + +public class ModelFile { + + /** + * Test capitalization + **/ + private String sourceURI; + + /** + * Test capitalization + * @return sourceURI + **/ + public String getSourceURI() { + return sourceURI; + } + + /** + * Set sourceURI + **/ + public void setSourceURI(String sourceURI) { + this.sourceURI = sourceURI; + } + + public ModelFile sourceURI(String sourceURI) { + this.sourceURI = sourceURI; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelFile {\n"); + + sb.append(" sourceURI: ").append(toIndentedString(sourceURI)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelList.java new file mode 100644 index 0000000000..0c2e7ffb39 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelList.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class ModelList { + + private String _123list; + + /** + * Get _123list + * @return _123list + **/ + public String get123list() { + return _123list; + } + + /** + * Set _123list + **/ + public void set123list(String _123list) { + this._123list = _123list; + } + + public ModelList _123list(String _123list) { + this._123list = _123list; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelList {\n"); + + sb.append(" _123list: ").append(toIndentedString(_123list)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelReturn.java new file mode 100644 index 0000000000..7d948f62e2 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -0,0 +1,76 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Model for testing reserved words + **/ + +public class ModelReturn { + + private Integer _return; + + /** + * Get _return + * @return _return + **/ + public Integer getReturn() { + return _return; + } + + /** + * Set _return + **/ + public void setReturn(Integer _return) { + this._return = _return; + } + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Name.java new file mode 100644 index 0000000000..ba07eb9152 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Name.java @@ -0,0 +1,123 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Model for testing model name same as property name + **/ + +public class Name { + + private Integer name; + + private Integer snakeCase; + + private String property; + + private Integer _123number; + + /** + * Get name + * @return name + **/ + public Integer getName() { + return name; + } + + /** + * Set name + **/ + public void setName(Integer name) { + this.name = name; + } + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + public Integer getSnakeCase() { + return snakeCase; + } + + + /** + * Get property + * @return property + **/ + public String getProperty() { + return property; + } + + /** + * Set property + **/ + public void setProperty(String property) { + this.property = property; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get _123number + * @return _123number + **/ + public Integer get123number() { + return _123number; + } + + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123number: ").append(toIndentedString(_123number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/NullableClass.java new file mode 100644 index 0000000000..759832f0dd --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/NullableClass.java @@ -0,0 +1,367 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + + + + +public class NullableClass extends HashMap { + + private Integer integerProp; + + private BigDecimal numberProp; + + private Boolean booleanProp; + + private String stringProp; + + private LocalDate dateProp; + + private OffsetDateTime datetimeProp; + + private List arrayNullableProp = null; + + private List arrayAndItemsNullableProp = null; + + private List arrayItemsNullable = null; + + private Map objectNullableProp = null; + + private Map objectAndItemsNullableProp = null; + + private Map objectItemsNullable = null; + + /** + * Get integerProp + * @return integerProp + **/ + public Integer getIntegerProp() { + return integerProp; + } + + /** + * Set integerProp + **/ + public void setIntegerProp(Integer integerProp) { + this.integerProp = integerProp; + } + + public NullableClass integerProp(Integer integerProp) { + this.integerProp = integerProp; + return this; + } + + /** + * Get numberProp + * @return numberProp + **/ + public BigDecimal getNumberProp() { + return numberProp; + } + + /** + * Set numberProp + **/ + public void setNumberProp(BigDecimal numberProp) { + this.numberProp = numberProp; + } + + public NullableClass numberProp(BigDecimal numberProp) { + this.numberProp = numberProp; + return this; + } + + /** + * Get booleanProp + * @return booleanProp + **/ + public Boolean getBooleanProp() { + return booleanProp; + } + + /** + * Set booleanProp + **/ + public void setBooleanProp(Boolean booleanProp) { + this.booleanProp = booleanProp; + } + + public NullableClass booleanProp(Boolean booleanProp) { + this.booleanProp = booleanProp; + return this; + } + + /** + * Get stringProp + * @return stringProp + **/ + public String getStringProp() { + return stringProp; + } + + /** + * Set stringProp + **/ + public void setStringProp(String stringProp) { + this.stringProp = stringProp; + } + + public NullableClass stringProp(String stringProp) { + this.stringProp = stringProp; + return this; + } + + /** + * Get dateProp + * @return dateProp + **/ + public LocalDate getDateProp() { + return dateProp; + } + + /** + * Set dateProp + **/ + public void setDateProp(LocalDate dateProp) { + this.dateProp = dateProp; + } + + public NullableClass dateProp(LocalDate dateProp) { + this.dateProp = dateProp; + return this; + } + + /** + * Get datetimeProp + * @return datetimeProp + **/ + public OffsetDateTime getDatetimeProp() { + return datetimeProp; + } + + /** + * Set datetimeProp + **/ + public void setDatetimeProp(OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + } + + public NullableClass datetimeProp(OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + return this; + } + + /** + * Get arrayNullableProp + * @return arrayNullableProp + **/ + public List getArrayNullableProp() { + return arrayNullableProp; + } + + /** + * Set arrayNullableProp + **/ + public void setArrayNullableProp(List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + } + + public NullableClass arrayNullableProp(List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + return this; + } + + public NullableClass addArrayNullablePropItem(Object arrayNullablePropItem) { + this.arrayNullableProp.add(arrayNullablePropItem); + return this; + } + + /** + * Get arrayAndItemsNullableProp + * @return arrayAndItemsNullableProp + **/ + public List getArrayAndItemsNullableProp() { + return arrayAndItemsNullableProp; + } + + /** + * Set arrayAndItemsNullableProp + **/ + public void setArrayAndItemsNullableProp(List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + } + + public NullableClass arrayAndItemsNullableProp(List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + return this; + } + + public NullableClass addArrayAndItemsNullablePropItem(Object arrayAndItemsNullablePropItem) { + this.arrayAndItemsNullableProp.add(arrayAndItemsNullablePropItem); + return this; + } + + /** + * Get arrayItemsNullable + * @return arrayItemsNullable + **/ + public List getArrayItemsNullable() { + return arrayItemsNullable; + } + + /** + * Set arrayItemsNullable + **/ + public void setArrayItemsNullable(List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + } + + public NullableClass arrayItemsNullable(List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + return this; + } + + public NullableClass addArrayItemsNullableItem(Object arrayItemsNullableItem) { + this.arrayItemsNullable.add(arrayItemsNullableItem); + return this; + } + + /** + * Get objectNullableProp + * @return objectNullableProp + **/ + public Map getObjectNullableProp() { + return objectNullableProp; + } + + /** + * Set objectNullableProp + **/ + public void setObjectNullableProp(Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + } + + public NullableClass objectNullableProp(Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + return this; + } + + public NullableClass putObjectNullablePropItem(String key, Object objectNullablePropItem) { + this.objectNullableProp.put(key, objectNullablePropItem); + return this; + } + + /** + * Get objectAndItemsNullableProp + * @return objectAndItemsNullableProp + **/ + public Map getObjectAndItemsNullableProp() { + return objectAndItemsNullableProp; + } + + /** + * Set objectAndItemsNullableProp + **/ + public void setObjectAndItemsNullableProp(Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + } + + public NullableClass objectAndItemsNullableProp(Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + return this; + } + + public NullableClass putObjectAndItemsNullablePropItem(String key, Object objectAndItemsNullablePropItem) { + this.objectAndItemsNullableProp.put(key, objectAndItemsNullablePropItem); + return this; + } + + /** + * Get objectItemsNullable + * @return objectItemsNullable + **/ + public Map getObjectItemsNullable() { + return objectItemsNullable; + } + + /** + * Set objectItemsNullable + **/ + public void setObjectItemsNullable(Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + } + + public NullableClass objectItemsNullable(Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + return this; + } + + public NullableClass putObjectItemsNullableItem(String key, Object objectItemsNullableItem) { + this.objectItemsNullable.put(key, objectItemsNullableItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NullableClass {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" integerProp: ").append(toIndentedString(integerProp)).append("\n"); + sb.append(" numberProp: ").append(toIndentedString(numberProp)).append("\n"); + sb.append(" booleanProp: ").append(toIndentedString(booleanProp)).append("\n"); + sb.append(" stringProp: ").append(toIndentedString(stringProp)).append("\n"); + sb.append(" dateProp: ").append(toIndentedString(dateProp)).append("\n"); + sb.append(" datetimeProp: ").append(toIndentedString(datetimeProp)).append("\n"); + sb.append(" arrayNullableProp: ").append(toIndentedString(arrayNullableProp)).append("\n"); + sb.append(" arrayAndItemsNullableProp: ").append(toIndentedString(arrayAndItemsNullableProp)).append("\n"); + sb.append(" arrayItemsNullable: ").append(toIndentedString(arrayItemsNullable)).append("\n"); + sb.append(" objectNullableProp: ").append(toIndentedString(objectNullableProp)).append("\n"); + sb.append(" objectAndItemsNullableProp: ").append(toIndentedString(objectAndItemsNullableProp)).append("\n"); + sb.append(" objectItemsNullable: ").append(toIndentedString(objectItemsNullable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/NumberOnly.java new file mode 100644 index 0000000000..5d493bccf2 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; + + + + +public class NumberOnly { + + private BigDecimal justNumber; + + /** + * Get justNumber + * @return justNumber + **/ + public BigDecimal getJustNumber() { + return justNumber; + } + + /** + * Set justNumber + **/ + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java new file mode 100644 index 0000000000..00c4300075 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -0,0 +1,157 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.DeprecatedObject; + + + + +public class ObjectWithDeprecatedFields { + + private String uuid; + + private BigDecimal id; + + private DeprecatedObject deprecatedRef; + + private List bars = null; + + /** + * Get uuid + * @return uuid + **/ + public String getUuid() { + return uuid; + } + + /** + * Set uuid + **/ + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public ObjectWithDeprecatedFields uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get id + * @return id + * @deprecated + **/ + @Deprecated + public BigDecimal getId() { + return id; + } + + /** + * Set id + **/ + public void setId(BigDecimal id) { + this.id = id; + } + + public ObjectWithDeprecatedFields id(BigDecimal id) { + this.id = id; + return this; + } + + /** + * Get deprecatedRef + * @return deprecatedRef + * @deprecated + **/ + @Deprecated + public DeprecatedObject getDeprecatedRef() { + return deprecatedRef; + } + + /** + * Set deprecatedRef + **/ + public void setDeprecatedRef(DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + } + + public ObjectWithDeprecatedFields deprecatedRef(DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + return this; + } + + /** + * Get bars + * @return bars + * @deprecated + **/ + @Deprecated + public List getBars() { + return bars; + } + + /** + * Set bars + **/ + public void setBars(List bars) { + this.bars = bars; + } + + public ObjectWithDeprecatedFields bars(List bars) { + this.bars = bars; + return this; + } + + public ObjectWithDeprecatedFields addBarsItem(String barsItem) { + this.bars.add(barsItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ObjectWithDeprecatedFields {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" deprecatedRef: ").append(toIndentedString(deprecatedRef)).append("\n"); + sb.append(" bars: ").append(toIndentedString(bars)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Order.java new file mode 100644 index 0000000000..84ce8e3fa1 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Order.java @@ -0,0 +1,213 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; + + + + +public class Order { + + private Long id; + + private Long petId; + + private Integer quantity; + + private OffsetDateTime shipDate; + +public enum StatusEnum { + + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); + + String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + /** + * Order Status + **/ + private StatusEnum status; + + private Boolean complete = false; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get petId + * @return petId + **/ + public Long getPetId() { + return petId; + } + + /** + * Set petId + **/ + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + public Integer getQuantity() { + return quantity; + } + + /** + * Set quantity + **/ + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + public OffsetDateTime getShipDate() { + return shipDate; + } + + /** + * Set shipDate + **/ + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Order Status + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + **/ + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Get complete + * @return complete + **/ + public Boolean getComplete() { + return complete; + } + + /** + * Set complete + **/ + public void setComplete(Boolean complete) { + this.complete = complete; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterComposite.java new file mode 100644 index 0000000000..6ba3d1712d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -0,0 +1,120 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; + + + + +public class OuterComposite { + + private BigDecimal myNumber; + + private String myString; + + private Boolean myBoolean; + + /** + * Get myNumber + * @return myNumber + **/ + public BigDecimal getMyNumber() { + return myNumber; + } + + /** + * Set myNumber + **/ + public void setMyNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + } + + public OuterComposite myNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + return this; + } + + /** + * Get myString + * @return myString + **/ + public String getMyString() { + return myString; + } + + /** + * Set myString + **/ + public void setMyString(String myString) { + this.myString = myString; + } + + public OuterComposite myString(String myString) { + this.myString = myString; + return this; + } + + /** + * Get myBoolean + * @return myBoolean + **/ + public Boolean getMyBoolean() { + return myBoolean; + } + + /** + * Set myBoolean + **/ + public void setMyBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + } + + public OuterComposite myBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterComposite {\n"); + + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); + sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnum.java new file mode 100644 index 0000000000..9fe96db3f6 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnum.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java new file mode 100644 index 0000000000..f5b732f784 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumDefaultValue + */ +public enum OuterEnumDefaultValue { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnumDefaultValue(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumDefaultValue fromValue(String text) { + for (OuterEnumDefaultValue b : OuterEnumDefaultValue.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnumInteger.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnumInteger.java new file mode 100644 index 0000000000..0ca88b32ee --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnumInteger.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumInteger + */ +public enum OuterEnumInteger { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumInteger(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumInteger fromValue(String text) { + for (OuterEnumInteger b : OuterEnumInteger.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java new file mode 100644 index 0000000000..06f9fe6c37 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumIntegerDefaultValue + */ +public enum OuterEnumIntegerDefaultValue { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumIntegerDefaultValue(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumIntegerDefaultValue fromValue(String text) { + for (OuterEnumIntegerDefaultValue b : OuterEnumIntegerDefaultValue.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java new file mode 100644 index 0000000000..b25e8e37ae --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.OuterEnumInteger; + + + + +public class OuterObjectWithEnumProperty { + + private OuterEnumInteger value; + + /** + * Get value + * @return value + **/ + public OuterEnumInteger getValue() { + return value; + } + + /** + * Set value + **/ + public void setValue(OuterEnumInteger value) { + this.value = value; + } + + public OuterObjectWithEnumProperty value(OuterEnumInteger value) { + this.value = value; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterObjectWithEnumProperty {\n"); + + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Pet.java new file mode 100644 index 0000000000..b86299acd2 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Pet.java @@ -0,0 +1,230 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; + + + + +public class Pet { + + private Long id; + + private Category category; + + private String name; + + private Set photoUrls = new LinkedHashSet<>(); + + private List tags = null; + +public enum StatusEnum { + + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); + + String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + /** + * pet status in the store + **/ + private StatusEnum status; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get category + * @return category + **/ + public Category getCategory() { + return category; + } + + /** + * Set category + **/ + public void setCategory(Category category) { + this.category = category; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + public Set getPhotoUrls() { + return photoUrls; + } + + /** + * Set photoUrls + **/ + @JsonDeserialize(as = LinkedHashSet.class) + public void setPhotoUrls(Set photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet photoUrls(Set photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + public List getTags() { + return tags; + } + + /** + * Set tags + **/ + public void setTags(List tags) { + this.tags = tags; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * pet status in the store + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + **/ + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java new file mode 100644 index 0000000000..15344cbf0d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -0,0 +1,85 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class ReadOnlyFirst { + + private String bar; + + private String baz; + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + + /** + * Get baz + * @return baz + **/ + public String getBaz() { + return baz; + } + + /** + * Set baz + **/ + public void setBaz(String baz) { + this.baz = baz; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/SingleRefType.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/SingleRefType.java new file mode 100644 index 0000000000..d46fc6c116 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/SingleRefType.java @@ -0,0 +1,50 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets SingleRefType + */ +public enum SingleRefType { + + ADMIN("admin"), + + USER("user"); + + private String value; + + SingleRefType(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static SingleRefType fromValue(String text) { + for (SingleRefType b : SingleRefType.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/SpecialModelName.java new file mode 100644 index 0000000000..af5166268f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class SpecialModelName { + + private Long $specialPropertyName; + + /** + * Get $specialPropertyName + * @return $specialPropertyName + **/ + public Long get$SpecialPropertyName() { + return $specialPropertyName; + } + + /** + * Set $specialPropertyName + **/ + public void set$SpecialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + } + + public SpecialModelName $specialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" $specialPropertyName: ").append(toIndentedString($specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Tag.java new file mode 100644 index 0000000000..1dee37e393 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/Tag.java @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Tag { + + private Long id; + + private String name; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/User.java new file mode 100644 index 0000000000..c088a4d15d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/User.java @@ -0,0 +1,237 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class User { + + private Long id; + + private String username; + + private String firstName; + + private String lastName; + + private String email; + + private String password; + + private String phone; + + /** + * User Status + **/ + private Integer userStatus; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + + /** + * Set username + **/ + public void setUsername(String username) { + this.username = username; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + public String getFirstName() { + return firstName; + } + + /** + * Set firstName + **/ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + public String getLastName() { + return lastName; + } + + /** + * Set lastName + **/ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get email + * @return email + **/ + public String getEmail() { + return email; + } + + /** + * Set email + **/ + public void setEmail(String email) { + this.email = email; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get password + * @return password + **/ + public String getPassword() { + return password; + } + + /** + * Set password + **/ + public void setPassword(String password) { + this.password = password; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get phone + * @return phone + **/ + public String getPhone() { + return phone; + } + + /** + * Set phone + **/ + public void setPhone(String phone) { + this.phone = phone; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * User Status + * @return userStatus + **/ + public Integer getUserStatus() { + return userStatus; + } + + /** + * Set userStatus + **/ + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java new file mode 100644 index 0000000000..ce1d8264fb --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java @@ -0,0 +1,64 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.Client; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for AnotherFakeApi + */ +public class AnotherFakeApiTest { + + private static AnotherFakeApi client; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() throws MalformedURLException { + client = RestClientBuilder.newBuilder() + .baseUrl(new URL(baseUrl)) + .register(ApiException.class) + .build(AnotherFakeApi.class); + } + + + /** + * To test special tags + * + * To test special tags and operation ID starting with number + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void call123testSpecialTagsTest() throws Exception { + //Client response = client.call123testSpecialTags(client); + //assertNotNull(response); + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/DefaultApiTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/DefaultApiTest.java new file mode 100644 index 0000000000..26e73e5457 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/DefaultApiTest.java @@ -0,0 +1,60 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.FooGetDefaultResponse; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for DefaultApi + */ +public class DefaultApiTest { + + private static DefaultApi client; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() throws MalformedURLException { + client = RestClientBuilder.newBuilder() + .baseUrl(new URL(baseUrl)) + .register(ApiException.class) + .build(DefaultApi.class); + } + + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void fooGetTest() throws Exception { + //FooGetDefaultResponse response = client.fooGet(); + //assertNotNull(response); + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/FakeApiTest.java new file mode 100644 index 0000000000..a953ad7bd8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/FakeApiTest.java @@ -0,0 +1,259 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import org.openapitools.client.model.EnumClass; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.HealthCheckResult; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.OuterObjectWithEnumProperty; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.User; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for FakeApi + */ +public class FakeApiTest { + + private static FakeApi client; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() throws MalformedURLException { + client = RestClientBuilder.newBuilder() + .baseUrl(new URL(baseUrl)) + .register(ApiException.class) + .build(FakeApi.class); + } + + + /** + * Health check endpoint + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeHealthGetTest() throws Exception { + //HealthCheckResult response = client.fakeHealthGet(); + //assertNotNull(response); + } + + /** + * test http signature authentication + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeHttpSignatureTestTest() throws Exception { + //void response = client.fakeHttpSignatureTest(pet, query1, header1); + //assertNotNull(response); + } + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterBooleanSerializeTest() throws Exception { + //Boolean response = client.fakeOuterBooleanSerialize(body); + //assertNotNull(response); + } + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterCompositeSerializeTest() throws Exception { + //OuterComposite response = client.fakeOuterCompositeSerialize(outerComposite); + //assertNotNull(response); + } + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterNumberSerializeTest() throws Exception { + //BigDecimal response = client.fakeOuterNumberSerialize(body); + //assertNotNull(response); + } + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterStringSerializeTest() throws Exception { + //String response = client.fakeOuterStringSerialize(body); + //assertNotNull(response); + } + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakePropertyEnumIntegerSerializeTest() throws Exception { + //OuterObjectWithEnumProperty response = client.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty); + //assertNotNull(response); + } + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBodyWithBinaryTest() throws Exception { + //void response = client.testBodyWithBinary(body); + //assertNotNull(response); + } + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBodyWithFileSchemaTest() throws Exception { + //void response = client.testBodyWithFileSchema(fileSchemaTestClass); + //assertNotNull(response); + } + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBodyWithQueryParamsTest() throws Exception { + //void response = client.testBodyWithQueryParams(query, user); + //assertNotNull(response); + } + + /** + * To test \"client\" model + * + * To test \"client\" model + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testClientModelTest() throws Exception { + //Client response = client.testClientModel(client); + //assertNotNull(response); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws Exception { + //void response = client.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + //assertNotNull(response); + } + + /** + * To test enum parameters + * + * To test enum parameters + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumParametersTest() throws Exception { + //void response = client.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString); + //assertNotNull(response); + } + + /** + * Fake endpoint to test group parameters (optional) + * + * Fake endpoint to test group parameters (optional) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testGroupParametersTest() throws Exception { + //void response = client.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + //assertNotNull(response); + } + + /** + * test inline additionalProperties + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testInlineAdditionalPropertiesTest() throws Exception { + //void response = client.testInlineAdditionalProperties(requestBody); + //assertNotNull(response); + } + + /** + * test json serialization of form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testJsonFormDataTest() throws Exception { + //void response = client.testJsonFormData(param, param2); + //assertNotNull(response); + } + + /** + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryParameterCollectionFormatTest() throws Exception { + //void response = client.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, allowEmpty, language); + //assertNotNull(response); + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java new file mode 100644 index 0000000000..bc5ecc0840 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java @@ -0,0 +1,64 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.Client; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for FakeClassnameTags123Api + */ +public class FakeClassnameTags123ApiTest { + + private static FakeClassnameTags123Api client; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() throws MalformedURLException { + client = RestClientBuilder.newBuilder() + .baseUrl(new URL(baseUrl)) + .register(ApiException.class) + .build(FakeClassnameTags123Api.class); + } + + + /** + * To test class name in snake case + * + * To test class name in snake case + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testClassnameTest() throws Exception { + //Client response = client.testClassname(client); + //assertNotNull(response); + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/PetApiTest.java new file mode 100644 index 0000000000..66959d421f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/PetApiTest.java @@ -0,0 +1,179 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; +import java.util.Set; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for PetApi + */ +public class PetApiTest { + + private static PetApi client; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() throws MalformedURLException { + client = RestClientBuilder.newBuilder() + .baseUrl(new URL(baseUrl)) + .register(ApiException.class) + .build(PetApi.class); + } + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() throws Exception { + //void response = client.addPet(pet); + //assertNotNull(response); + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() throws Exception { + //void response = client.deletePet(petId, apiKey); + //assertNotNull(response); + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() throws Exception { + //List response = client.findPetsByStatus(status); + //assertNotNull(response); + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() throws Exception { + //Set response = client.findPetsByTags(tags); + //assertNotNull(response); + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() throws Exception { + //Pet response = client.getPetById(petId); + //assertNotNull(response); + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() throws Exception { + //void response = client.updatePet(pet); + //assertNotNull(response); + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() throws Exception { + //void response = client.updatePetWithForm(petId, name, status); + //assertNotNull(response); + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() throws Exception { + //ModelApiResponse response = client.uploadFile(petId, additionalMetadata, _file); + //assertNotNull(response); + } + + /** + * uploads an image (required) + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileWithRequiredFileTest() throws Exception { + //ModelApiResponse response = client.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + //assertNotNull(response); + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/StoreApiTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/StoreApiTest.java new file mode 100644 index 0000000000..4331d26aa9 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/StoreApiTest.java @@ -0,0 +1,106 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.Order; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for StoreApi + */ +public class StoreApiTest { + + private static StoreApi client; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() throws MalformedURLException { + client = RestClientBuilder.newBuilder() + .baseUrl(new URL(baseUrl)) + .register(ApiException.class) + .build(StoreApi.class); + } + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() throws Exception { + //void response = client.deleteOrder(orderId); + //assertNotNull(response); + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() throws Exception { + //Map response = client.getInventory(); + //assertNotNull(response); + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() throws Exception { + //Order response = client.getOrderById(orderId); + //assertNotNull(response); + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() throws Exception { + //Order response = client.placeOrder(order); + //assertNotNull(response); + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/UserApiTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/UserApiTest.java new file mode 100644 index 0000000000..dfbfc41d41 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/api/UserApiTest.java @@ -0,0 +1,163 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.time.OffsetDateTime; +import org.openapitools.client.model.User; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for UserApi + */ +public class UserApiTest { + + private static UserApi client; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() throws MalformedURLException { + client = RestClientBuilder.newBuilder() + .baseUrl(new URL(baseUrl)) + .register(ApiException.class) + .build(UserApi.class); + } + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() throws Exception { + //void response = client.createUser(user); + //assertNotNull(response); + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() throws Exception { + //void response = client.createUsersWithArrayInput(user); + //assertNotNull(response); + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() throws Exception { + //void response = client.createUsersWithListInput(user); + //assertNotNull(response); + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() throws Exception { + //void response = client.deleteUser(username); + //assertNotNull(response); + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() throws Exception { + //User response = client.getUserByName(username); + //assertNotNull(response); + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() throws Exception { + //String response = client.loginUser(username, password); + //assertNotNull(response); + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() throws Exception { + //void response = client.logoutUser(); + //assertNotNull(response); + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() throws Exception { + //void response = client.updateUser(username, user); + //assertNotNull(response); + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java new file mode 100644 index 0000000000..008d620d50 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java @@ -0,0 +1,57 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for AdditionalPropertiesClass + */ +public class AdditionalPropertiesClassTest { + private final AdditionalPropertiesClass model = new AdditionalPropertiesClass(); + + /** + * Model tests for AdditionalPropertiesClass + */ + @Test + public void testAdditionalPropertiesClass() { + // TODO: test AdditionalPropertiesClass + } + + /** + * Test the property 'mapProperty' + */ + @Test + public void mapPropertyTest() { + // TODO: test mapProperty + } + + /** + * Test the property 'mapOfMapProperty' + */ + @Test + public void mapOfMapPropertyTest() { + // TODO: test mapOfMapProperty + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/AllOfWithSingleRefTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/AllOfWithSingleRefTest.java new file mode 100644 index 0000000000..ad55c6f2c7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/AllOfWithSingleRefTest.java @@ -0,0 +1,56 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.SingleRefType; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for AllOfWithSingleRef + */ +public class AllOfWithSingleRefTest { + private final AllOfWithSingleRef model = new AllOfWithSingleRef(); + + /** + * Model tests for AllOfWithSingleRef + */ + @Test + public void testAllOfWithSingleRef() { + // TODO: test AllOfWithSingleRef + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'singleRefType' + */ + @Test + public void singleRefTypeTest() { + // TODO: test singleRefType + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/AnimalTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/AnimalTest.java new file mode 100644 index 0000000000..c38a031c2e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/AnimalTest.java @@ -0,0 +1,60 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Cat; +import org.openapitools.client.model.Dog; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Animal + */ +public class AnimalTest { + private final Animal model = new Animal(); + + /** + * Model tests for Animal + */ + @Test + public void testAnimal() { + // TODO: test Animal + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java new file mode 100644 index 0000000000..5a886da823 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java @@ -0,0 +1,50 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayOfArrayOfNumberOnly + */ +public class ArrayOfArrayOfNumberOnlyTest { + private final ArrayOfArrayOfNumberOnly model = new ArrayOfArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfArrayOfNumberOnly + */ + @Test + public void testArrayOfArrayOfNumberOnly() { + // TODO: test ArrayOfArrayOfNumberOnly + } + + /** + * Test the property 'arrayArrayNumber' + */ + @Test + public void arrayArrayNumberTest() { + // TODO: test arrayArrayNumber + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java new file mode 100644 index 0000000000..6b0d615c0e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java @@ -0,0 +1,50 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayOfNumberOnly + */ +public class ArrayOfNumberOnlyTest { + private final ArrayOfNumberOnly model = new ArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfNumberOnly + */ + @Test + public void testArrayOfNumberOnly() { + // TODO: test ArrayOfNumberOnly + } + + /** + * Test the property 'arrayNumber' + */ + @Test + public void arrayNumberTest() { + // TODO: test arrayNumber + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ArrayTestTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ArrayTestTest.java new file mode 100644 index 0000000000..be3f20c9a3 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ArrayTestTest.java @@ -0,0 +1,66 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ReadOnlyFirst; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayTest + */ +public class ArrayTestTest { + private final ArrayTest model = new ArrayTest(); + + /** + * Model tests for ArrayTest + */ + @Test + public void testArrayTest() { + // TODO: test ArrayTest + } + + /** + * Test the property 'arrayOfString' + */ + @Test + public void arrayOfStringTest() { + // TODO: test arrayOfString + } + + /** + * Test the property 'arrayArrayOfInteger' + */ + @Test + public void arrayArrayOfIntegerTest() { + // TODO: test arrayArrayOfInteger + } + + /** + * Test the property 'arrayArrayOfModel' + */ + @Test + public void arrayArrayOfModelTest() { + // TODO: test arrayArrayOfModel + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CapitalizationTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CapitalizationTest.java new file mode 100644 index 0000000000..18e9b9dbf0 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CapitalizationTest.java @@ -0,0 +1,87 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Capitalization + */ +public class CapitalizationTest { + private final Capitalization model = new Capitalization(); + + /** + * Model tests for Capitalization + */ + @Test + public void testCapitalization() { + // TODO: test Capitalization + } + + /** + * Test the property 'smallCamel' + */ + @Test + public void smallCamelTest() { + // TODO: test smallCamel + } + + /** + * Test the property 'capitalCamel' + */ + @Test + public void capitalCamelTest() { + // TODO: test capitalCamel + } + + /** + * Test the property 'smallSnake' + */ + @Test + public void smallSnakeTest() { + // TODO: test smallSnake + } + + /** + * Test the property 'capitalSnake' + */ + @Test + public void capitalSnakeTest() { + // TODO: test capitalSnake + } + + /** + * Test the property 'scAETHFlowPoints' + */ + @Test + public void scAETHFlowPointsTest() { + // TODO: test scAETHFlowPoints + } + + /** + * Test the property 'ATT_NAME' + */ + @Test + public void ATT_NAMETest() { + // TODO: test ATT_NAME + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CatAllOfTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CatAllOfTest.java new file mode 100644 index 0000000000..3772925dd6 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CatAllOfTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for CatAllOf + */ +public class CatAllOfTest { + private final CatAllOf model = new CatAllOf(); + + /** + * Model tests for CatAllOf + */ + @Test + public void testCatAllOf() { + // TODO: test CatAllOf + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CatTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CatTest.java new file mode 100644 index 0000000000..d78fcb6359 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CatTest.java @@ -0,0 +1,67 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Animal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Cat + */ +public class CatTest { + private final Cat model = new Cat(); + + /** + * Model tests for Cat + */ + @Test + public void testCat() { + // TODO: test Cat + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CategoryTest.java new file mode 100644 index 0000000000..12d4b6a644 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/CategoryTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ClassModelTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ClassModelTest.java new file mode 100644 index 0000000000..035b80969f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ClassModelTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ClassModel + */ +public class ClassModelTest { + private final ClassModel model = new ClassModel(); + + /** + * Model tests for ClassModel + */ + @Test + public void testClassModel() { + // TODO: test ClassModel + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ClientTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ClientTest.java new file mode 100644 index 0000000000..9b4899ae22 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ClientTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Client + */ +public class ClientTest { + private final Client model = new Client(); + + /** + * Model tests for Client + */ + @Test + public void testClient() { + // TODO: test Client + } + + /** + * Test the property 'client' + */ + @Test + public void clientTest() { + // TODO: test client + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java new file mode 100644 index 0000000000..54347091cc --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for DeprecatedObject + */ +public class DeprecatedObjectTest { + private final DeprecatedObject model = new DeprecatedObject(); + + /** + * Model tests for DeprecatedObject + */ + @Test + public void testDeprecatedObject() { + // TODO: test DeprecatedObject + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/DogAllOfTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/DogAllOfTest.java new file mode 100644 index 0000000000..16066cd03f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/DogAllOfTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for DogAllOf + */ +public class DogAllOfTest { + private final DogAllOf model = new DogAllOf(); + + /** + * Model tests for DogAllOf + */ + @Test + public void testDogAllOf() { + // TODO: test DogAllOf + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/DogTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/DogTest.java new file mode 100644 index 0000000000..6819c78158 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/DogTest.java @@ -0,0 +1,67 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Animal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Dog + */ +public class DogTest { + private final Dog model = new Dog(); + + /** + * Model tests for Dog + */ + @Test + public void testDog() { + // TODO: test Dog + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/EnumArraysTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/EnumArraysTest.java new file mode 100644 index 0000000000..4d24965872 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/EnumArraysTest.java @@ -0,0 +1,57 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumArrays + */ +public class EnumArraysTest { + private final EnumArrays model = new EnumArrays(); + + /** + * Model tests for EnumArrays + */ + @Test + public void testEnumArrays() { + // TODO: test EnumArrays + } + + /** + * Test the property 'justSymbol' + */ + @Test + public void justSymbolTest() { + // TODO: test justSymbol + } + + /** + * Test the property 'arrayEnum' + */ + @Test + public void arrayEnumTest() { + // TODO: test arrayEnum + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/EnumClassTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/EnumClassTest.java new file mode 100644 index 0000000000..11bf230be7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/EnumClassTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumClass + */ +public class EnumClassTest { + /** + * Model tests for EnumClass + */ + @Test + public void testEnumClass() { + // TODO: test EnumClass + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/EnumTestTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/EnumTestTest.java new file mode 100644 index 0000000000..ec0d37ce36 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/EnumTestTest.java @@ -0,0 +1,111 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.OuterEnumDefaultValue; +import org.openapitools.client.model.OuterEnumInteger; +import org.openapitools.client.model.OuterEnumIntegerDefaultValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumTest + */ +public class EnumTestTest { + private final EnumTest model = new EnumTest(); + + /** + * Model tests for EnumTest + */ + @Test + public void testEnumTest() { + // TODO: test EnumTest + } + + /** + * Test the property 'enumString' + */ + @Test + public void enumStringTest() { + // TODO: test enumString + } + + /** + * Test the property 'enumStringRequired' + */ + @Test + public void enumStringRequiredTest() { + // TODO: test enumStringRequired + } + + /** + * Test the property 'enumInteger' + */ + @Test + public void enumIntegerTest() { + // TODO: test enumInteger + } + + /** + * Test the property 'enumNumber' + */ + @Test + public void enumNumberTest() { + // TODO: test enumNumber + } + + /** + * Test the property 'outerEnum' + */ + @Test + public void outerEnumTest() { + // TODO: test outerEnum + } + + /** + * Test the property 'outerEnumInteger' + */ + @Test + public void outerEnumIntegerTest() { + // TODO: test outerEnumInteger + } + + /** + * Test the property 'outerEnumDefaultValue' + */ + @Test + public void outerEnumDefaultValueTest() { + // TODO: test outerEnumDefaultValue + } + + /** + * Test the property 'outerEnumIntegerDefaultValue' + */ + @Test + public void outerEnumIntegerDefaultValueTest() { + // TODO: test outerEnumIntegerDefaultValue + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java new file mode 100644 index 0000000000..846646eb94 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ModelFile; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FileSchemaTestClass + */ +public class FileSchemaTestClassTest { + private final FileSchemaTestClass model = new FileSchemaTestClass(); + + /** + * Model tests for FileSchemaTestClass + */ + @Test + public void testFileSchemaTestClass() { + // TODO: test FileSchemaTestClass + } + + /** + * Test the property '_file' + */ + @Test + public void _fileTest() { + // TODO: test _file + } + + /** + * Test the property 'files' + */ + @Test + public void filesTest() { + // TODO: test files + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java new file mode 100644 index 0000000000..14639567d8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java @@ -0,0 +1,48 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Foo; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FooGetDefaultResponse + */ +public class FooGetDefaultResponseTest { + private final FooGetDefaultResponse model = new FooGetDefaultResponse(); + + /** + * Model tests for FooGetDefaultResponse + */ + @Test + public void testFooGetDefaultResponse() { + // TODO: test FooGetDefaultResponse + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FooTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FooTest.java new file mode 100644 index 0000000000..6ad35f67e2 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FooTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Foo + */ +public class FooTest { + private final Foo model = new Foo(); + + /** + * Model tests for Foo + */ + @Test + public void testFoo() { + // TODO: test Foo + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FormatTestTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FormatTestTest.java new file mode 100644 index 0000000000..773e76967e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/FormatTestTest.java @@ -0,0 +1,172 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FormatTest + */ +public class FormatTestTest { + private final FormatTest model = new FormatTest(); + + /** + * Model tests for FormatTest + */ + @Test + public void testFormatTest() { + // TODO: test FormatTest + } + + /** + * Test the property 'integer' + */ + @Test + public void integerTest() { + // TODO: test integer + } + + /** + * Test the property 'int32' + */ + @Test + public void int32Test() { + // TODO: test int32 + } + + /** + * Test the property 'int64' + */ + @Test + public void int64Test() { + // TODO: test int64 + } + + /** + * Test the property 'number' + */ + @Test + public void numberTest() { + // TODO: test number + } + + /** + * Test the property '_float' + */ + @Test + public void _floatTest() { + // TODO: test _float + } + + /** + * Test the property '_double' + */ + @Test + public void _doubleTest() { + // TODO: test _double + } + + /** + * Test the property 'decimal' + */ + @Test + public void decimalTest() { + // TODO: test decimal + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + + /** + * Test the property '_byte' + */ + @Test + public void _byteTest() { + // TODO: test _byte + } + + /** + * Test the property 'binary' + */ + @Test + public void binaryTest() { + // TODO: test binary + } + + /** + * Test the property 'date' + */ + @Test + public void dateTest() { + // TODO: test date + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'patternWithDigits' + */ + @Test + public void patternWithDigitsTest() { + // TODO: test patternWithDigits + } + + /** + * Test the property 'patternWithDigitsAndDelimiter' + */ + @Test + public void patternWithDigitsAndDelimiterTest() { + // TODO: test patternWithDigitsAndDelimiter + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java new file mode 100644 index 0000000000..b956d12d74 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for HasOnlyReadOnly + */ +public class HasOnlyReadOnlyTest { + private final HasOnlyReadOnly model = new HasOnlyReadOnly(); + + /** + * Model tests for HasOnlyReadOnly + */ + @Test + public void testHasOnlyReadOnly() { + // TODO: test HasOnlyReadOnly + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'foo' + */ + @Test + public void fooTest() { + // TODO: test foo + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java new file mode 100644 index 0000000000..3267defa3a --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java @@ -0,0 +1,51 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for HealthCheckResult + */ +public class HealthCheckResultTest { + private final HealthCheckResult model = new HealthCheckResult(); + + /** + * Model tests for HealthCheckResult + */ + @Test + public void testHealthCheckResult() { + // TODO: test HealthCheckResult + } + + /** + * Test the property 'nullableMessage' + */ + @Test + public void nullableMessageTest() { + // TODO: test nullableMessage + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/MapTestTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/MapTestTest.java new file mode 100644 index 0000000000..ac308e4008 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/MapTestTest.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for MapTest + */ +public class MapTestTest { + private final MapTest model = new MapTest(); + + /** + * Model tests for MapTest + */ + @Test + public void testMapTest() { + // TODO: test MapTest + } + + /** + * Test the property 'mapMapOfString' + */ + @Test + public void mapMapOfStringTest() { + // TODO: test mapMapOfString + } + + /** + * Test the property 'mapOfEnumString' + */ + @Test + public void mapOfEnumStringTest() { + // TODO: test mapOfEnumString + } + + /** + * Test the property 'directMap' + */ + @Test + public void directMapTest() { + // TODO: test directMap + } + + /** + * Test the property 'indirectMap' + */ + @Test + public void indirectMapTest() { + // TODO: test indirectMap + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java new file mode 100644 index 0000000000..72a7a2a961 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java @@ -0,0 +1,68 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.openapitools.client.model.Animal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ +public class MixedPropertiesAndAdditionalPropertiesClassTest { + private final MixedPropertiesAndAdditionalPropertiesClass model = new MixedPropertiesAndAdditionalPropertiesClass(); + + /** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ + @Test + public void testMixedPropertiesAndAdditionalPropertiesClass() { + // TODO: test MixedPropertiesAndAdditionalPropertiesClass + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'map' + */ + @Test + public void mapTest() { + // TODO: test map + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/Model200ResponseTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/Model200ResponseTest.java new file mode 100644 index 0000000000..79bd883d4c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/Model200ResponseTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Model200Response + */ +public class Model200ResponseTest { + private final Model200Response model = new Model200Response(); + + /** + * Model tests for Model200Response + */ + @Test + public void testModel200Response() { + // TODO: test Model200Response + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java new file mode 100644 index 0000000000..79b915c967 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java @@ -0,0 +1,63 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelFileTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelFileTest.java new file mode 100644 index 0000000000..c10fa3927e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelFileTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelFile + */ +public class ModelFileTest { + private final ModelFile model = new ModelFile(); + + /** + * Model tests for ModelFile + */ + @Test + public void testModelFile() { + // TODO: test ModelFile + } + + /** + * Test the property 'sourceURI' + */ + @Test + public void sourceURITest() { + // TODO: test sourceURI + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelListTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelListTest.java new file mode 100644 index 0000000000..7c09d2e78e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelListTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelList + */ +public class ModelListTest { + private final ModelList model = new ModelList(); + + /** + * Model tests for ModelList + */ + @Test + public void testModelList() { + // TODO: test ModelList + } + + /** + * Test the property '_123list' + */ + @Test + public void _123listTest() { + // TODO: test _123list + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelReturnTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelReturnTest.java new file mode 100644 index 0000000000..8c99cb5220 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ModelReturnTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelReturn + */ +public class ModelReturnTest { + private final ModelReturn model = new ModelReturn(); + + /** + * Model tests for ModelReturn + */ + @Test + public void testModelReturn() { + // TODO: test ModelReturn + } + + /** + * Test the property '_return' + */ + @Test + public void _returnTest() { + // TODO: test _return + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/NameTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/NameTest.java new file mode 100644 index 0000000000..8795299bfa --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/NameTest.java @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Name + */ +public class NameTest { + private final Name model = new Name(); + + /** + * Model tests for Name + */ + @Test + public void testName() { + // TODO: test Name + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'snakeCase' + */ + @Test + public void snakeCaseTest() { + // TODO: test snakeCase + } + + /** + * Test the property 'property' + */ + @Test + public void propertyTest() { + // TODO: test property + } + + /** + * Test the property '_123number' + */ + @Test + public void _123numberTest() { + // TODO: test _123number + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/NullableClassTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/NullableClassTest.java new file mode 100644 index 0000000000..95997f952e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/NullableClassTest.java @@ -0,0 +1,146 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for NullableClass + */ +public class NullableClassTest { + private final NullableClass model = new NullableClass(); + + /** + * Model tests for NullableClass + */ + @Test + public void testNullableClass() { + // TODO: test NullableClass + } + + /** + * Test the property 'integerProp' + */ + @Test + public void integerPropTest() { + // TODO: test integerProp + } + + /** + * Test the property 'numberProp' + */ + @Test + public void numberPropTest() { + // TODO: test numberProp + } + + /** + * Test the property 'booleanProp' + */ + @Test + public void booleanPropTest() { + // TODO: test booleanProp + } + + /** + * Test the property 'stringProp' + */ + @Test + public void stringPropTest() { + // TODO: test stringProp + } + + /** + * Test the property 'dateProp' + */ + @Test + public void datePropTest() { + // TODO: test dateProp + } + + /** + * Test the property 'datetimeProp' + */ + @Test + public void datetimePropTest() { + // TODO: test datetimeProp + } + + /** + * Test the property 'arrayNullableProp' + */ + @Test + public void arrayNullablePropTest() { + // TODO: test arrayNullableProp + } + + /** + * Test the property 'arrayAndItemsNullableProp' + */ + @Test + public void arrayAndItemsNullablePropTest() { + // TODO: test arrayAndItemsNullableProp + } + + /** + * Test the property 'arrayItemsNullable' + */ + @Test + public void arrayItemsNullableTest() { + // TODO: test arrayItemsNullable + } + + /** + * Test the property 'objectNullableProp' + */ + @Test + public void objectNullablePropTest() { + // TODO: test objectNullableProp + } + + /** + * Test the property 'objectAndItemsNullableProp' + */ + @Test + public void objectAndItemsNullablePropTest() { + // TODO: test objectAndItemsNullableProp + } + + /** + * Test the property 'objectItemsNullable' + */ + @Test + public void objectItemsNullableTest() { + // TODO: test objectItemsNullable + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/NumberOnlyTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/NumberOnlyTest.java new file mode 100644 index 0000000000..f1af4caf2e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/NumberOnlyTest.java @@ -0,0 +1,48 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for NumberOnly + */ +public class NumberOnlyTest { + private final NumberOnly model = new NumberOnly(); + + /** + * Model tests for NumberOnly + */ + @Test + public void testNumberOnly() { + // TODO: test NumberOnly + } + + /** + * Test the property 'justNumber' + */ + @Test + public void justNumberTest() { + // TODO: test justNumber + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java new file mode 100644 index 0000000000..14f312e38a --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java @@ -0,0 +1,75 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.DeprecatedObject; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ObjectWithDeprecatedFields + */ +public class ObjectWithDeprecatedFieldsTest { + private final ObjectWithDeprecatedFields model = new ObjectWithDeprecatedFields(); + + /** + * Model tests for ObjectWithDeprecatedFields + */ + @Test + public void testObjectWithDeprecatedFields() { + // TODO: test ObjectWithDeprecatedFields + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'deprecatedRef' + */ + @Test + public void deprecatedRefTest() { + // TODO: test deprecatedRef + } + + /** + * Test the property 'bars' + */ + @Test + public void barsTest() { + // TODO: test bars + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OrderTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OrderTest.java new file mode 100644 index 0000000000..e99bf8d598 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OrderTest.java @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterCompositeTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterCompositeTest.java new file mode 100644 index 0000000000..28b832d5db --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterCompositeTest.java @@ -0,0 +1,64 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterComposite + */ +public class OuterCompositeTest { + private final OuterComposite model = new OuterComposite(); + + /** + * Model tests for OuterComposite + */ + @Test + public void testOuterComposite() { + // TODO: test OuterComposite + } + + /** + * Test the property 'myNumber' + */ + @Test + public void myNumberTest() { + // TODO: test myNumber + } + + /** + * Test the property 'myString' + */ + @Test + public void myStringTest() { + // TODO: test myString + } + + /** + * Test the property 'myBoolean' + */ + @Test + public void myBooleanTest() { + // TODO: test myBoolean + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java new file mode 100644 index 0000000000..75313d6581 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumDefaultValue + */ +public class OuterEnumDefaultValueTest { + /** + * Model tests for OuterEnumDefaultValue + */ + @Test + public void testOuterEnumDefaultValue() { + // TODO: test OuterEnumDefaultValue + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java new file mode 100644 index 0000000000..df4527f0d4 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumIntegerDefaultValue + */ +public class OuterEnumIntegerDefaultValueTest { + /** + * Model tests for OuterEnumIntegerDefaultValue + */ + @Test + public void testOuterEnumIntegerDefaultValue() { + // TODO: test OuterEnumIntegerDefaultValue + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java new file mode 100644 index 0000000000..87c29d2fd7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumInteger + */ +public class OuterEnumIntegerTest { + /** + * Model tests for OuterEnumInteger + */ + @Test + public void testOuterEnumInteger() { + // TODO: test OuterEnumInteger + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumTest.java new file mode 100644 index 0000000000..226fc34f40 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterEnumTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnum + */ +public class OuterEnumTest { + /** + * Model tests for OuterEnum + */ + @Test + public void testOuterEnum() { + // TODO: test OuterEnum + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterObjectWithEnumPropertyTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterObjectWithEnumPropertyTest.java new file mode 100644 index 0000000000..24984008ab --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/OuterObjectWithEnumPropertyTest.java @@ -0,0 +1,48 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.OuterEnumInteger; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterObjectWithEnumProperty + */ +public class OuterObjectWithEnumPropertyTest { + private final OuterObjectWithEnumProperty model = new OuterObjectWithEnumProperty(); + + /** + * Model tests for OuterObjectWithEnumProperty + */ + @Test + public void testOuterObjectWithEnumProperty() { + // TODO: test OuterObjectWithEnumProperty + } + + /** + * Test the property 'value' + */ + @Test + public void valueTest() { + // TODO: test value + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/PetTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/PetTest.java new file mode 100644 index 0000000000..6de3524dcc --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/PetTest.java @@ -0,0 +1,94 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java new file mode 100644 index 0000000000..332a1b116c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ReadOnlyFirst + */ +public class ReadOnlyFirstTest { + private final ReadOnlyFirst model = new ReadOnlyFirst(); + + /** + * Model tests for ReadOnlyFirst + */ + @Test + public void testReadOnlyFirst() { + // TODO: test ReadOnlyFirst + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'baz' + */ + @Test + public void bazTest() { + // TODO: test baz + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/SingleRefTypeTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/SingleRefTypeTest.java new file mode 100644 index 0000000000..82f51f683d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/SingleRefTypeTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for SingleRefType + */ +public class SingleRefTypeTest { + /** + * Model tests for SingleRefType + */ + @Test + public void testSingleRefType() { + // TODO: test SingleRefType + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java new file mode 100644 index 0000000000..e1d4d10b94 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for SpecialModelName + */ +public class SpecialModelNameTest { + private final SpecialModelName model = new SpecialModelName(); + + /** + * Model tests for SpecialModelName + */ + @Test + public void testSpecialModelName() { + // TODO: test SpecialModelName + } + + /** + * Test the property '$specialPropertyName' + */ + @Test + public void $specialPropertyNameTest() { + // TODO: test $specialPropertyName + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/TagTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/TagTest.java new file mode 100644 index 0000000000..ff32e6c114 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/TagTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/UserTest.java b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/UserTest.java new file mode 100644 index 0000000000..32404a5e38 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/mp/src/test/java/org/openapitools/client/model/UserTest.java @@ -0,0 +1,103 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + +} diff --git a/samples/client/petstore/rust/hyper/rust-test/.openapi-generator-ignore b/samples/client/petstore/java-helidon-client/se/.openapi-generator-ignore similarity index 100% rename from samples/client/petstore/rust/hyper/rust-test/.openapi-generator-ignore rename to samples/client/petstore/java-helidon-client/se/.openapi-generator-ignore diff --git a/samples/client/petstore/java-helidon-client/se/.openapi-generator/FILES b/samples/client/petstore/java-helidon-client/se/.openapi-generator/FILES new file mode 100644 index 0000000000..16af74d61d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/.openapi-generator/FILES @@ -0,0 +1,125 @@ +README.md +docs/AdditionalPropertiesClass.md +docs/AllOfWithSingleRef.md +docs/Animal.md +docs/AnotherFakeApi.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/DefaultApi.md +docs/DeprecatedObject.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/FileSchemaTestClass.md +docs/Foo.md +docs/FooGetDefaultResponse.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/HealthCheckResult.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelApiResponse.md +docs/ModelFile.md +docs/ModelList.md +docs/ModelReturn.md +docs/Name.md +docs/NullableClass.md +docs/NumberOnly.md +docs/ObjectWithDeprecatedFields.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/OuterEnumDefaultValue.md +docs/OuterEnumInteger.md +docs/OuterEnumIntegerDefaultValue.md +docs/OuterObjectWithEnumProperty.md +docs/Pet.md +docs/PetApi.md +docs/ReadOnlyFirst.md +docs/SingleRefType.md +docs/SpecialModelName.md +docs/StoreApi.md +docs/Tag.md +docs/User.md +docs/UserApi.md +pom.xml +src/main/java/org/openapitools/client/ApiClient.java +src/main/java/org/openapitools/client/ApiResponse.java +src/main/java/org/openapitools/client/ApiResponseBase.java +src/main/java/org/openapitools/client/Pair.java +src/main/java/org/openapitools/client/RFC3339DateFormat.java +src/main/java/org/openapitools/client/api/AnotherFakeApi.java +src/main/java/org/openapitools/client/api/AnotherFakeApiImpl.java +src/main/java/org/openapitools/client/api/DefaultApi.java +src/main/java/org/openapitools/client/api/DefaultApiImpl.java +src/main/java/org/openapitools/client/api/FakeApi.java +src/main/java/org/openapitools/client/api/FakeApiImpl.java +src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +src/main/java/org/openapitools/client/api/FakeClassnameTags123ApiImpl.java +src/main/java/org/openapitools/client/api/PetApi.java +src/main/java/org/openapitools/client/api/PetApiImpl.java +src/main/java/org/openapitools/client/api/ResponseType.java +src/main/java/org/openapitools/client/api/StoreApi.java +src/main/java/org/openapitools/client/api/StoreApiImpl.java +src/main/java/org/openapitools/client/api/UserApi.java +src/main/java/org/openapitools/client/api/UserApiImpl.java +src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java +src/main/java/org/openapitools/client/model/Animal.java +src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +src/main/java/org/openapitools/client/model/ArrayTest.java +src/main/java/org/openapitools/client/model/Capitalization.java +src/main/java/org/openapitools/client/model/Cat.java +src/main/java/org/openapitools/client/model/CatAllOf.java +src/main/java/org/openapitools/client/model/Category.java +src/main/java/org/openapitools/client/model/ClassModel.java +src/main/java/org/openapitools/client/model/Client.java +src/main/java/org/openapitools/client/model/DeprecatedObject.java +src/main/java/org/openapitools/client/model/Dog.java +src/main/java/org/openapitools/client/model/DogAllOf.java +src/main/java/org/openapitools/client/model/EnumArrays.java +src/main/java/org/openapitools/client/model/EnumClass.java +src/main/java/org/openapitools/client/model/EnumTest.java +src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +src/main/java/org/openapitools/client/model/Foo.java +src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java +src/main/java/org/openapitools/client/model/FormatTest.java +src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +src/main/java/org/openapitools/client/model/HealthCheckResult.java +src/main/java/org/openapitools/client/model/MapTest.java +src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +src/main/java/org/openapitools/client/model/Model200Response.java +src/main/java/org/openapitools/client/model/ModelApiResponse.java +src/main/java/org/openapitools/client/model/ModelFile.java +src/main/java/org/openapitools/client/model/ModelList.java +src/main/java/org/openapitools/client/model/ModelReturn.java +src/main/java/org/openapitools/client/model/Name.java +src/main/java/org/openapitools/client/model/NullableClass.java +src/main/java/org/openapitools/client/model/NumberOnly.java +src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +src/main/java/org/openapitools/client/model/Order.java +src/main/java/org/openapitools/client/model/OuterComposite.java +src/main/java/org/openapitools/client/model/OuterEnum.java +src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java +src/main/java/org/openapitools/client/model/OuterEnumInteger.java +src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java +src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java +src/main/java/org/openapitools/client/model/Pet.java +src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +src/main/java/org/openapitools/client/model/SingleRefType.java +src/main/java/org/openapitools/client/model/SpecialModelName.java +src/main/java/org/openapitools/client/model/Tag.java +src/main/java/org/openapitools/client/model/User.java diff --git a/samples/client/petstore/java-helidon-client/se/.openapi-generator/VERSION b/samples/client/petstore/java-helidon-client/se/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java-helidon-client/se/README.md b/samples/client/petstore/java-helidon-client/se/README.md new file mode 100644 index 0000000000..83180298fc --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/README.md @@ -0,0 +1,24 @@ +# OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + +## Overview +This project was generated using the Helidon OpenAPI Generator. + +The generated classes use the programming model from the Helidon WebClient implementation, primarily the `WebClient` interface and its +`WebClient.Builder` class. Refer to the Helidon WebClient documentation for complete information about them. + +## Using the Generated Classes and Interfaces +The generated `ApiClient` class wraps a `WebClient` instance. Similarly, the `ApiClient.Builder` class wraps the `WebClient.Builder` class. + +The generated `xxxApi` interfaces and `xxxApiImpl` classes make it very simple for your code to send requests (with input parameters) to the remote service which the OpenAPI document describes and to process the response (with output values) from the remote service. + +To use the generated API, your code performs the following steps. + +1. Create an instance of the `ApiClient` using its `Builder`. +2. Create an instance of a `xxxApi` it wants to access, typically by invoking `xxxApiImpl.create(ApiClient)` and passing the `ApiClient` instance just created. +3. Invoke any of the `public` methods on the `xxxApi` instance, passing the input parameters and saving the returned `Single` object. +4. Invoke methods on the returned `Single` to process the response and any output from it. + +Browse the methods and JavaDoc on the generated classes for more information. diff --git a/samples/client/petstore/java-helidon-client/se/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java-helidon-client/se/docs/AdditionalPropertiesClass.md new file mode 100644 index 0000000000..fe69a56eeb --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/AdditionalPropertiesClass.md @@ -0,0 +1,14 @@ + + +# AdditionalPropertiesClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**mapProperty** | **Map<String, String>** | | [optional] | +|**mapOfMapProperty** | **Map<String, Map<String, String>>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/AllOfWithSingleRef.md b/samples/client/petstore/java-helidon-client/se/docs/AllOfWithSingleRef.md new file mode 100644 index 0000000000..0a9e61bc68 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/AllOfWithSingleRef.md @@ -0,0 +1,14 @@ + + +# AllOfWithSingleRef + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**username** | **String** | | [optional] | +|**singleRefType** | [**SingleRefType**](SingleRefType.md) | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Animal.md b/samples/client/petstore/java-helidon-client/se/docs/Animal.md new file mode 100644 index 0000000000..d9b32f14c8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Animal.md @@ -0,0 +1,14 @@ + + +# Animal + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**className** | **String** | | | +|**color** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/AnotherFakeApi.md b/samples/client/petstore/java-helidon-client/se/docs/AnotherFakeApi.md new file mode 100644 index 0000000000..73c966d2d5 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/AnotherFakeApi.md @@ -0,0 +1,75 @@ +# AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**call123testSpecialTags**](AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags | + + + +## call123testSpecialTags + +> Client call123testSpecialTags(client) + +To test special tags + +To test special tags and operation ID starting with number + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AnotherFakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.call123testSpecialTags(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#call123testSpecialTags"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **client** | [**Client**](Client.md)| client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java-helidon-client/se/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 0000000000..0188db3eb1 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,13 @@ + + +# ArrayOfArrayOfNumberOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayArrayNumber** | **List<List<BigDecimal>>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java-helidon-client/se/docs/ArrayOfNumberOnly.md new file mode 100644 index 0000000000..a5753530aa --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ArrayOfNumberOnly.md @@ -0,0 +1,13 @@ + + +# ArrayOfNumberOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayNumber** | **List<BigDecimal>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ArrayTest.md b/samples/client/petstore/java-helidon-client/se/docs/ArrayTest.md new file mode 100644 index 0000000000..36077c9df3 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ArrayTest.md @@ -0,0 +1,15 @@ + + +# ArrayTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayOfString** | **List<String>** | | [optional] | +|**arrayArrayOfInteger** | **List<List<Long>>** | | [optional] | +|**arrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Capitalization.md b/samples/client/petstore/java-helidon-client/se/docs/Capitalization.md new file mode 100644 index 0000000000..82a812711d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Capitalization.md @@ -0,0 +1,18 @@ + + +# Capitalization + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**smallCamel** | **String** | | [optional] | +|**capitalCamel** | **String** | | [optional] | +|**smallSnake** | **String** | | [optional] | +|**capitalSnake** | **String** | | [optional] | +|**scAETHFlowPoints** | **String** | | [optional] | +|**ATT_NAME** | **String** | Name of the pet | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Cat.md b/samples/client/petstore/java-helidon-client/se/docs/Cat.md new file mode 100644 index 0000000000..390dd519c8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Cat.md @@ -0,0 +1,13 @@ + + +# Cat + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**declawed** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/CatAllOf.md b/samples/client/petstore/java-helidon-client/se/docs/CatAllOf.md new file mode 100644 index 0000000000..926bc0abd7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/CatAllOf.md @@ -0,0 +1,13 @@ + + +# CatAllOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**declawed** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Category.md b/samples/client/petstore/java-helidon-client/se/docs/Category.md new file mode 100644 index 0000000000..ab6d1ec334 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Category.md @@ -0,0 +1,14 @@ + + +# Category + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ClassModel.md b/samples/client/petstore/java-helidon-client/se/docs/ClassModel.md new file mode 100644 index 0000000000..af46dea1f6 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ClassModel.md @@ -0,0 +1,14 @@ + + +# ClassModel + +Model for testing model with \"_class\" property + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**propertyClass** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Client.md b/samples/client/petstore/java-helidon-client/se/docs/Client.md new file mode 100644 index 0000000000..ef07b4ab8b --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Client.md @@ -0,0 +1,13 @@ + + +# Client + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**client** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/DefaultApi.md b/samples/client/petstore/java-helidon-client/se/docs/DefaultApi.md new file mode 100644 index 0000000000..2c56e1f90e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/DefaultApi.md @@ -0,0 +1,69 @@ +# DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**fooGet**](DefaultApi.md#fooGet) | **GET** /foo | | + + + +## fooGet + +> FooGetDefaultResponse fooGet() + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + FooGetDefaultResponse result = apiInstance.fooGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#fooGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**FooGetDefaultResponse**](FooGetDefaultResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | response | - | + diff --git a/samples/client/petstore/java-helidon-client/se/docs/DeprecatedObject.md b/samples/client/petstore/java-helidon-client/se/docs/DeprecatedObject.md new file mode 100644 index 0000000000..48de1d6244 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/DeprecatedObject.md @@ -0,0 +1,13 @@ + + +# DeprecatedObject + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Dog.md b/samples/client/petstore/java-helidon-client/se/docs/Dog.md new file mode 100644 index 0000000000..972c981c0d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Dog.md @@ -0,0 +1,13 @@ + + +# Dog + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**breed** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/DogAllOf.md b/samples/client/petstore/java-helidon-client/se/docs/DogAllOf.md new file mode 100644 index 0000000000..d4e4ea0d54 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/DogAllOf.md @@ -0,0 +1,13 @@ + + +# DogAllOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**breed** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/EnumArrays.md b/samples/client/petstore/java-helidon-client/se/docs/EnumArrays.md new file mode 100644 index 0000000000..b2222d5beb --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/EnumArrays.md @@ -0,0 +1,32 @@ + + +# EnumArrays + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**justSymbol** | [**JustSymbolEnum**](#JustSymbolEnum) | | [optional] | +|**arrayEnum** | [**List<ArrayEnumEnum>**](#List<ArrayEnumEnum>) | | [optional] | + + + +## Enum: JustSymbolEnum + +| Name | Value | +|---- | -----| +| GREATER_THAN_OR_EQUAL_TO | ">=" | +| DOLLAR | "$" | + + + +## Enum: List<ArrayEnumEnum> + +| Name | Value | +|---- | -----| +| FISH | "fish" | +| CRAB | "crab" | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/EnumClass.md b/samples/client/petstore/java-helidon-client/se/docs/EnumClass.md new file mode 100644 index 0000000000..b314590a75 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/EnumClass.md @@ -0,0 +1,15 @@ + + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/EnumTest.md b/samples/client/petstore/java-helidon-client/se/docs/EnumTest.md new file mode 100644 index 0000000000..380a2aef0b --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/EnumTest.md @@ -0,0 +1,58 @@ + + +# EnumTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] | +|**enumStringRequired** | [**EnumStringRequiredEnum**](#EnumStringRequiredEnum) | | | +|**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] | +|**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] | +|**outerEnum** | **OuterEnum** | | [optional] | +|**outerEnumInteger** | **OuterEnumInteger** | | [optional] | +|**outerEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] | +|**outerEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] | + + + +## Enum: EnumStringEnum + +| Name | Value | +|---- | -----| +| UPPER | "UPPER" | +| LOWER | "lower" | +| EMPTY | "" | + + + +## Enum: EnumStringRequiredEnum + +| Name | Value | +|---- | -----| +| UPPER | "UPPER" | +| LOWER | "lower" | +| EMPTY | "" | + + + +## Enum: EnumIntegerEnum + +| Name | Value | +|---- | -----| +| NUMBER_1 | 1 | +| NUMBER_MINUS_1 | -1 | + + + +## Enum: EnumNumberEnum + +| Name | Value | +|---- | -----| +| NUMBER_1_DOT_1 | 1.1 | +| NUMBER_MINUS_1_DOT_2 | -1.2 | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/FakeApi.md b/samples/client/petstore/java-helidon-client/se/docs/FakeApi.md new file mode 100644 index 0000000000..1b6b950799 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/FakeApi.md @@ -0,0 +1,1214 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**fakeHealthGet**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint | +| [**fakeHttpSignatureTest**](FakeApi.md#fakeHttpSignatureTest) | **GET** /fake/http-signature-test | test http signature authentication | +| [**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | | +| [**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | | +| [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | +| [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | +| [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | +| [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | +| [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | +| [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model | +| [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 | +| [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters | +| [**testGroupParameters**](FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) | +| [**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties | +| [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data | +| [**testQueryParameterCollectionFormat**](FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | | + + + +## fakeHealthGet + +> HealthCheckResult fakeHealthGet() + +Health check endpoint + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + HealthCheckResult result = apiInstance.fakeHealthGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeHealthGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | The instance started successfully | - | + + +## fakeHttpSignatureTest + +> fakeHttpSignatureTest(pet, query1, header1) + +test http signature authentication + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + + FakeApi apiInstance = new FakeApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + String query1 = "query1_example"; // String | query parameter + String header1 = "header1_example"; // String | header parameter + try { + apiInstance.fakeHttpSignatureTest(pet, query1, header1); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeHttpSignatureTest"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | +| **query1** | **String**| query parameter | [optional] | +| **header1** | **String**| header parameter | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[http_signature_test](../README.md#http_signature_test) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | The instance started successfully | - | + + +## fakeOuterBooleanSerialize + +> Boolean fakeOuterBooleanSerialize(body) + + + +Test serialization of outer boolean types + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Boolean body = true; // Boolean | Input boolean as post body + try { + Boolean result = apiInstance.fakeOuterBooleanSerialize(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterBooleanSerialize"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **Boolean**| Input boolean as post body | [optional] | + +### Return type + +**Boolean** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output boolean | - | + + +## fakeOuterCompositeSerialize + +> OuterComposite fakeOuterCompositeSerialize(outerComposite) + + + +Test serialization of object with outer number type + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + OuterComposite outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body + try { + OuterComposite result = apiInstance.fakeOuterCompositeSerialize(outerComposite); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterCompositeSerialize"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] | + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output composite | - | + + +## fakeOuterNumberSerialize + +> BigDecimal fakeOuterNumberSerialize(body) + + + +Test serialization of outer number types + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + BigDecimal body = new BigDecimal(78); // BigDecimal | Input number as post body + try { + BigDecimal result = apiInstance.fakeOuterNumberSerialize(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterNumberSerialize"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **BigDecimal**| Input number as post body | [optional] | + +### Return type + +[**BigDecimal**](BigDecimal.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output number | - | + + +## fakeOuterStringSerialize + +> String fakeOuterStringSerialize(body) + + + +Test serialization of outer string types + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + String body = "body_example"; // String | Input string as post body + try { + String result = apiInstance.fakeOuterStringSerialize(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterStringSerialize"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **String**| Input string as post body | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output string | - | + + +## fakePropertyEnumIntegerSerialize + +> OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty) + + + +Test serialization of enum (int) properties with examples + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + OuterObjectWithEnumProperty outerObjectWithEnumProperty = new OuterObjectWithEnumProperty(); // OuterObjectWithEnumProperty | Input enum (int) as post body + try { + OuterObjectWithEnumProperty result = apiInstance.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakePropertyEnumIntegerSerialize"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **outerObjectWithEnumProperty** | [**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md)| Input enum (int) as post body | | + +### Return type + +[**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output enum (int) | - | + + +## testBodyWithBinary + +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + File body = new File("/path/to/file"); // File | image to upload + try { + apiInstance.testBodyWithBinary(body); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testBodyWithBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **File**| image to upload | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +## testBodyWithFileSchema + +> testBodyWithFileSchema(fileSchemaTestClass) + + + +For this test, the body for this request must reference a schema named `File`. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + FileSchemaTestClass fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | + try { + apiInstance.testBodyWithFileSchema(fileSchemaTestClass); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testBodyWithFileSchema"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +## testBodyWithQueryParams + +> testBodyWithQueryParams(query, user) + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + String query = "query_example"; // String | + User user = new User(); // User | + try { + apiInstance.testBodyWithQueryParams(query, user); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testBodyWithQueryParams"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **query** | **String**| | | +| **user** | [**User**](User.md)| | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +## testClientModel + +> Client testClientModel(client) + +To test \"client\" model + +To test \"client\" model + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.testClientModel(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testClientModel"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **client** | [**Client**](Client.md)| client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## testEndpointParameters + +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure HTTP basic authorization: http_basic_test + HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); + http_basic_test.setUsername("YOUR USERNAME"); + http_basic_test.setPassword("YOUR PASSWORD"); + + FakeApi apiInstance = new FakeApi(defaultClient); + BigDecimal number = new BigDecimal(78); // BigDecimal | None + Double _double = 3.4D; // Double | None + String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None + byte[] _byte = null; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 56L; // Long | None + Float _float = 3.4F; // Float | None + String string = "string_example"; // String | None + File binary = new File("/path/to/file"); // File | None + LocalDate date = LocalDate.now(); // LocalDate | None + OffsetDateTime dateTime = OffsetDateTime.now(); // OffsetDateTime | None + String password = "password_example"; // String | None + String paramCallback = "paramCallback_example"; // String | None + try { + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **number** | **BigDecimal**| None | | +| **_double** | **Double**| None | | +| **patternWithoutDelimiter** | **String**| None | | +| **_byte** | **byte[]**| None | | +| **integer** | **Integer**| None | [optional] | +| **int32** | **Integer**| None | [optional] | +| **int64** | **Long**| None | [optional] | +| **_float** | **Float**| None | [optional] | +| **string** | **String**| None | [optional] | +| **binary** | **File**| None | [optional] | +| **date** | **LocalDate**| None | [optional] | +| **dateTime** | **OffsetDateTime**| None | [optional] | +| **password** | **String**| None | [optional] | +| **paramCallback** | **String**| None | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## testEnumParameters + +> testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString) + +To test enum parameters + +To test enum parameters + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + List enumHeaderStringArray = Arrays.asList("$"); // List | Header parameter enum test (string array) + String enumHeaderString = "_abc"; // String | Header parameter enum test (string) + List enumQueryStringArray = Arrays.asList("$"); // List | Query parameter enum test (string array) + String enumQueryString = "_abc"; // String | Query parameter enum test (string) + Integer enumQueryInteger = 1; // Integer | Query parameter enum test (double) + Double enumQueryDouble = 1.1D; // Double | Query parameter enum test (double) + List enumQueryModelArray = Arrays.asList(-efg); // List | + List enumFormStringArray = Arrays.asList("$"); // List | Form parameter enum test (string array) + String enumFormString = "_abc"; // String | Form parameter enum test (string) + try { + apiInstance.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumParameters"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] | +| **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] | +| **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] | +| **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] | +| **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] [enum: 1, -2] | +| **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] [enum: 1.1, -1.2] | +| **enumQueryModelArray** | [**List<EnumClass>**](EnumClass.md)| | [optional] | +| **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] | +| **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid request | - | +| **404** | Not found | - | + + +## testGroupParameters + +> testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure HTTP bearer authorization: bearer_test + HttpBearerAuth bearer_test = (HttpBearerAuth) defaultClient.getAuthentication("bearer_test"); + bearer_test.setBearerToken("BEARER TOKEN"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Integer requiredStringGroup = 56; // Integer | Required String in group parameters + Boolean requiredBooleanGroup = true; // Boolean | Required Boolean in group parameters + Long requiredInt64Group = 56L; // Long | Required Integer in group parameters + Integer stringGroup = 56; // Integer | String in group parameters + Boolean booleanGroup = true; // Boolean | Boolean in group parameters + Long int64Group = 56L; // Long | Integer in group parameters + try { + apiInstance.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testGroupParameters"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requiredStringGroup** | **Integer**| Required String in group parameters | | +| **requiredBooleanGroup** | **Boolean**| Required Boolean in group parameters | | +| **requiredInt64Group** | **Long**| Required Integer in group parameters | | +| **stringGroup** | **Integer**| String in group parameters | [optional] | +| **booleanGroup** | **Boolean**| Boolean in group parameters | [optional] | +| **int64Group** | **Long**| Integer in group parameters | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Someting wrong | - | + + +## testInlineAdditionalProperties + +> testInlineAdditionalProperties(requestBody) + +test inline additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = new HashMap(); // Map | request body + try { + apiInstance.testInlineAdditionalProperties(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, String>**](String.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## testJsonFormData + +> testJsonFormData(param, param2) + +test json serialization of form data + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + String param = "param_example"; // String | field1 + String param2 = "param2_example"; // String | field2 + try { + apiInstance.testJsonFormData(param, param2); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testJsonFormData"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **param** | **String**| field1 | | +| **param2** | **String**| field2 | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## testQueryParameterCollectionFormat + +> testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, allowEmpty, language) + + + +To test the collection format in query parameters + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + List pipe = Arrays.asList(); // List | + List ioutil = Arrays.asList(); // List | + List http = Arrays.asList(); // List | + List url = Arrays.asList(); // List | + List context = Arrays.asList(); // List | + String allowEmpty = "allowEmpty_example"; // String | + Map language = new HashMap(); // Map | + try { + apiInstance.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, allowEmpty, language); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testQueryParameterCollectionFormat"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pipe** | [**List<String>**](String.md)| | | +| **ioutil** | [**List<String>**](String.md)| | | +| **http** | [**List<String>**](String.md)| | | +| **url** | [**List<String>**](String.md)| | | +| **context** | [**List<String>**](String.md)| | | +| **allowEmpty** | **String**| | | +| **language** | [**Map<String, String>**](String.md)| | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + diff --git a/samples/client/petstore/java-helidon-client/se/docs/FakeClassnameTags123Api.md b/samples/client/petstore/java-helidon-client/se/docs/FakeClassnameTags123Api.md new file mode 100644 index 0000000000..e4ff70ed90 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/FakeClassnameTags123Api.md @@ -0,0 +1,82 @@ +# FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testClassname**](FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case | + + + +## testClassname + +> Client testClassname(client) + +To test class name in snake case + +To test class name in snake case + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeClassnameTags123Api; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + FakeClassnameTags123Api apiInstance = new FakeClassnameTags123Api(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.testClassname(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeClassnameTags123Api#testClassname"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **client** | [**Client**](Client.md)| client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java-helidon-client/se/docs/FileSchemaTestClass.md b/samples/client/petstore/java-helidon-client/se/docs/FileSchemaTestClass.md new file mode 100644 index 0000000000..85d1a06366 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/FileSchemaTestClass.md @@ -0,0 +1,14 @@ + + +# FileSchemaTestClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**_file** | [**ModelFile**](ModelFile.md) | | [optional] | +|**files** | [**List<ModelFile>**](ModelFile.md) | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Foo.md b/samples/client/petstore/java-helidon-client/se/docs/Foo.md new file mode 100644 index 0000000000..6b3f055652 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Foo.md @@ -0,0 +1,13 @@ + + +# Foo + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/FooGetDefaultResponse.md b/samples/client/petstore/java-helidon-client/se/docs/FooGetDefaultResponse.md new file mode 100644 index 0000000000..ff3d7a3a56 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/FooGetDefaultResponse.md @@ -0,0 +1,13 @@ + + +# FooGetDefaultResponse + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**string** | [**Foo**](Foo.md) | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/FormatTest.md b/samples/client/petstore/java-helidon-client/se/docs/FormatTest.md new file mode 100644 index 0000000000..01b8c777ae --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/FormatTest.md @@ -0,0 +1,28 @@ + + +# FormatTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**integer** | **Integer** | | [optional] | +|**int32** | **Integer** | | [optional] | +|**int64** | **Long** | | [optional] | +|**number** | **BigDecimal** | | | +|**_float** | **Float** | | [optional] | +|**_double** | **Double** | | [optional] | +|**decimal** | **BigDecimal** | | [optional] | +|**string** | **String** | | [optional] | +|**_byte** | **byte[]** | | | +|**binary** | **File** | | [optional] | +|**date** | **LocalDate** | | | +|**dateTime** | **OffsetDateTime** | | [optional] | +|**uuid** | **UUID** | | [optional] | +|**password** | **String** | | | +|**patternWithDigits** | **String** | A string that is a 10 digit number. Can have leading zeros. | [optional] | +|**patternWithDigitsAndDelimiter** | **String** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/HasOnlyReadOnly.md b/samples/client/petstore/java-helidon-client/se/docs/HasOnlyReadOnly.md new file mode 100644 index 0000000000..29da5205db --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/HasOnlyReadOnly.md @@ -0,0 +1,14 @@ + + +# HasOnlyReadOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] [readonly] | +|**foo** | **String** | | [optional] [readonly] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/HealthCheckResult.md b/samples/client/petstore/java-helidon-client/se/docs/HealthCheckResult.md new file mode 100644 index 0000000000..4885e6f1ca --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/HealthCheckResult.md @@ -0,0 +1,14 @@ + + +# HealthCheckResult + +Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**nullableMessage** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/MapTest.md b/samples/client/petstore/java-helidon-client/se/docs/MapTest.md new file mode 100644 index 0000000000..54380188e1 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/MapTest.md @@ -0,0 +1,25 @@ + + +# MapTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**mapMapOfString** | **Map<String, Map<String, String>>** | | [optional] | +|**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] | +|**directMap** | **Map<String, Boolean>** | | [optional] | +|**indirectMap** | **Map<String, Boolean>** | | [optional] | + + + +## Enum: Map<String, InnerEnum> + +| Name | Value | +|---- | -----| +| UPPER | "UPPER" | +| LOWER | "lower" | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java-helidon-client/se/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 0000000000..a5ddf0faa6 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,15 @@ + + +# MixedPropertiesAndAdditionalPropertiesClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**uuid** | **UUID** | | [optional] | +|**dateTime** | **OffsetDateTime** | | [optional] | +|**map** | [**Map<String, Animal>**](Animal.md) | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Model200Response.md b/samples/client/petstore/java-helidon-client/se/docs/Model200Response.md new file mode 100644 index 0000000000..109411580c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Model200Response.md @@ -0,0 +1,15 @@ + + +# Model200Response + +Model for testing model name starting with number + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **Integer** | | [optional] | +|**propertyClass** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ModelApiResponse.md b/samples/client/petstore/java-helidon-client/se/docs/ModelApiResponse.md new file mode 100644 index 0000000000..e374c2dd2d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ModelApiResponse.md @@ -0,0 +1,15 @@ + + +# ModelApiResponse + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**code** | **Integer** | | [optional] | +|**type** | **String** | | [optional] | +|**message** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ModelFile.md b/samples/client/petstore/java-helidon-client/se/docs/ModelFile.md new file mode 100644 index 0000000000..adcde984f5 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ModelFile.md @@ -0,0 +1,14 @@ + + +# ModelFile + +Must be named `File` for test. + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**sourceURI** | **String** | Test capitalization | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ModelList.md b/samples/client/petstore/java-helidon-client/se/docs/ModelList.md new file mode 100644 index 0000000000..f93ab7dde8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ModelList.md @@ -0,0 +1,13 @@ + + +# ModelList + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**_123list** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ModelReturn.md b/samples/client/petstore/java-helidon-client/se/docs/ModelReturn.md new file mode 100644 index 0000000000..0bd356861e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ModelReturn.md @@ -0,0 +1,14 @@ + + +# ModelReturn + +Model for testing reserved words + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**_return** | **Integer** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Name.md b/samples/client/petstore/java-helidon-client/se/docs/Name.md new file mode 100644 index 0000000000..c901d94353 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Name.md @@ -0,0 +1,17 @@ + + +# Name + +Model for testing model name same as property name + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **Integer** | | | +|**snakeCase** | **Integer** | | [optional] [readonly] | +|**property** | **String** | | [optional] | +|**_123number** | **Integer** | | [optional] [readonly] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/NullableClass.md b/samples/client/petstore/java-helidon-client/se/docs/NullableClass.md new file mode 100644 index 0000000000..fa98c5c6d9 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/NullableClass.md @@ -0,0 +1,24 @@ + + +# NullableClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**integerProp** | **Integer** | | [optional] | +|**numberProp** | **BigDecimal** | | [optional] | +|**booleanProp** | **Boolean** | | [optional] | +|**stringProp** | **String** | | [optional] | +|**dateProp** | **LocalDate** | | [optional] | +|**datetimeProp** | **OffsetDateTime** | | [optional] | +|**arrayNullableProp** | **List<Object>** | | [optional] | +|**arrayAndItemsNullableProp** | **List<Object>** | | [optional] | +|**arrayItemsNullable** | **List<Object>** | | [optional] | +|**objectNullableProp** | **Map<String, Object>** | | [optional] | +|**objectAndItemsNullableProp** | **Map<String, Object>** | | [optional] | +|**objectItemsNullable** | **Map<String, Object>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/NumberOnly.md b/samples/client/petstore/java-helidon-client/se/docs/NumberOnly.md new file mode 100644 index 0000000000..b8ed1a4cfa --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/NumberOnly.md @@ -0,0 +1,13 @@ + + +# NumberOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**justNumber** | **BigDecimal** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ObjectWithDeprecatedFields.md b/samples/client/petstore/java-helidon-client/se/docs/ObjectWithDeprecatedFields.md new file mode 100644 index 0000000000..f1cf571f4c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ObjectWithDeprecatedFields.md @@ -0,0 +1,16 @@ + + +# ObjectWithDeprecatedFields + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**uuid** | **String** | | [optional] | +|**id** | **BigDecimal** | | [optional] | +|**deprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] | +|**bars** | **List<String>** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Order.md b/samples/client/petstore/java-helidon-client/se/docs/Order.md new file mode 100644 index 0000000000..27af32855c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Order.md @@ -0,0 +1,28 @@ + + +# Order + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**petId** | **Long** | | [optional] | +|**quantity** | **Integer** | | [optional] | +|**shipDate** | **OffsetDateTime** | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] | +|**complete** | **Boolean** | | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| PLACED | "placed" | +| APPROVED | "approved" | +| DELIVERED | "delivered" | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/OuterComposite.md b/samples/client/petstore/java-helidon-client/se/docs/OuterComposite.md new file mode 100644 index 0000000000..98b56e0763 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/OuterComposite.md @@ -0,0 +1,15 @@ + + +# OuterComposite + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**myNumber** | **BigDecimal** | | [optional] | +|**myString** | **String** | | [optional] | +|**myBoolean** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/OuterEnum.md b/samples/client/petstore/java-helidon-client/se/docs/OuterEnum.md new file mode 100644 index 0000000000..1f9b723eb8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/OuterEnum.md @@ -0,0 +1,15 @@ + + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/OuterEnumDefaultValue.md b/samples/client/petstore/java-helidon-client/se/docs/OuterEnumDefaultValue.md new file mode 100644 index 0000000000..cbc7f4ba54 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/OuterEnumDefaultValue.md @@ -0,0 +1,15 @@ + + +# OuterEnumDefaultValue + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/OuterEnumInteger.md b/samples/client/petstore/java-helidon-client/se/docs/OuterEnumInteger.md new file mode 100644 index 0000000000..f71dea30ad --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/OuterEnumInteger.md @@ -0,0 +1,15 @@ + + +# OuterEnumInteger + +## Enum + + +* `NUMBER_0` (value: `0`) + +* `NUMBER_1` (value: `1`) + +* `NUMBER_2` (value: `2`) + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/OuterEnumIntegerDefaultValue.md b/samples/client/petstore/java-helidon-client/se/docs/OuterEnumIntegerDefaultValue.md new file mode 100644 index 0000000000..99e6389f42 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/OuterEnumIntegerDefaultValue.md @@ -0,0 +1,15 @@ + + +# OuterEnumIntegerDefaultValue + +## Enum + + +* `NUMBER_0` (value: `0`) + +* `NUMBER_1` (value: `1`) + +* `NUMBER_2` (value: `2`) + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/OuterObjectWithEnumProperty.md b/samples/client/petstore/java-helidon-client/se/docs/OuterObjectWithEnumProperty.md new file mode 100644 index 0000000000..0fafaaa271 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/OuterObjectWithEnumProperty.md @@ -0,0 +1,13 @@ + + +# OuterObjectWithEnumProperty + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**value** | **OuterEnumInteger** | | | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Pet.md b/samples/client/petstore/java-helidon-client/se/docs/Pet.md new file mode 100644 index 0000000000..54af77a9f5 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Pet.md @@ -0,0 +1,28 @@ + + +# Pet + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **Set<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/PetApi.md b/samples/client/petstore/java-helidon-client/se/docs/PetApi.md new file mode 100644 index 0000000000..e2515d9bb9 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/PetApi.md @@ -0,0 +1,678 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store | +| [**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status | +| [**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID | +| [**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet | +| [**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image | +| [**uploadFileWithRequiredFile**](PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) | + + + +## addPet + +> addPet(pet) + +Add a new pet to the store + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(pet); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | +| **405** | Invalid input | - | + + +## deletePet + +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | Pet id to delete + String apiKey = "apiKey_example"; // String | + try { + apiInstance.deletePet(petId, apiKey); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| Pet id to delete | | +| **apiKey** | **String**| | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | +| **400** | Invalid pet value | - | + + +## findPetsByStatus + +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List status = Arrays.asList("available"); // List | Status values that need to be considered for filter + try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + + +## findPetsByTags + +> Set<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Set tags = Arrays.asList(); // Set | Tags to filter by + try { + Set result = apiInstance.findPetsByTags(tags); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **tags** | [**Set<String>**](String.md)| Tags to filter by | | + +### Return type + +[**Set<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + + +## getPetById + +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to return + try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to return | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## updatePet + +> updatePet(pet) + +Update an existing pet + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.updatePet(pet); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + + +## updatePetWithForm + +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet that needs to be updated + String name = "name_example"; // String | Updated name of the pet + String status = "status_example"; // String | Updated status of the pet + try { + apiInstance.updatePetWithForm(petId, name, status); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet that needs to be updated | | +| **name** | **String**| Updated name of the pet | [optional] | +| **status** | **String**| Updated status of the pet | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | +| **405** | Invalid input | - | + + +## uploadFile + +> ModelApiResponse uploadFile(petId, additionalMetadata, _file) + +uploads an image + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + File _file = new File("/path/to/file"); // File | file to upload + try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, _file); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to update | | +| **additionalMetadata** | **String**| Additional data to pass to server | [optional] | +| **_file** | **File**| file to upload | [optional] | + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## uploadFileWithRequiredFile + +> ModelApiResponse uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata) + +uploads an image (required) + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + File requiredFile = new File("/path/to/file"); // File | file to upload + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + try { + ModelApiResponse result = apiInstance.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFileWithRequiredFile"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to update | | +| **requiredFile** | **File**| file to upload | | +| **additionalMetadata** | **String**| Additional data to pass to server | [optional] | + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java-helidon-client/se/docs/ReadOnlyFirst.md b/samples/client/petstore/java-helidon-client/se/docs/ReadOnlyFirst.md new file mode 100644 index 0000000000..ad6af7ee15 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/ReadOnlyFirst.md @@ -0,0 +1,14 @@ + + +# ReadOnlyFirst + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] [readonly] | +|**baz** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/SingleRefType.md b/samples/client/petstore/java-helidon-client/se/docs/SingleRefType.md new file mode 100644 index 0000000000..cc269bb871 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/SingleRefType.md @@ -0,0 +1,13 @@ + + +# SingleRefType + +## Enum + + +* `ADMIN` (value: `"admin"`) + +* `USER` (value: `"user"`) + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/SpecialModelName.md b/samples/client/petstore/java-helidon-client/se/docs/SpecialModelName.md new file mode 100644 index 0000000000..4b6a06e362 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/SpecialModelName.md @@ -0,0 +1,13 @@ + + +# SpecialModelName + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**$specialPropertyName** | **Long** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/StoreApi.md b/samples/client/petstore/java-helidon-client/se/docs/StoreApi.md new file mode 100644 index 0000000000..e3b7d7b910 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/StoreApi.md @@ -0,0 +1,282 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID | +| [**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status | +| [**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID | +| [**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet | + + + +## deleteOrder + +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + String orderId = "orderId_example"; // String | ID of the order that needs to be deleted + try { + apiInstance.deleteOrder(orderId); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **orderId** | **String**| ID of the order that needs to be deleted | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## getInventory + +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + StoreApi apiInstance = new StoreApi(defaultClient); + try { + Map result = apiInstance.getInventory(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Map<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## getOrderById + +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of pet that needs to be fetched + try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **orderId** | **Long**| ID of pet that needs to be fetched | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## placeOrder + +> Order placeOrder(order) + +Place an order for a pet + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Order order = new Order(); // Order | order placed for purchasing the pet + try { + Order result = apiInstance.placeOrder(order); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **order** | [**Order**](Order.md)| order placed for purchasing the pet | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/samples/client/petstore/java-helidon-client/se/docs/Tag.md b/samples/client/petstore/java-helidon-client/se/docs/Tag.md new file mode 100644 index 0000000000..5088b2dd1c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/Tag.md @@ -0,0 +1,14 @@ + + +# Tag + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/User.md b/samples/client/petstore/java-helidon-client/se/docs/User.md new file mode 100644 index 0000000000..08813e4b10 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/User.md @@ -0,0 +1,20 @@ + + +# User + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**username** | **String** | | [optional] | +|**firstName** | **String** | | [optional] | +|**lastName** | **String** | | [optional] | +|**email** | **String** | | [optional] | +|**password** | **String** | | [optional] | +|**phone** | **String** | | [optional] | +|**userStatus** | **Integer** | User Status | [optional] | + + + diff --git a/samples/client/petstore/java-helidon-client/se/docs/UserApi.md b/samples/client/petstore/java-helidon-client/se/docs/UserApi.md new file mode 100644 index 0000000000..305fd6e66d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/docs/UserApi.md @@ -0,0 +1,543 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**createUser**](UserApi.md#createUser) | **POST** /user | Create user | +| [**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array | +| [**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array | +| [**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user | +| [**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name | +| [**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system | +| [**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session | +| [**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user | + + + +## createUser + +> createUser(user) + +Create user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + User user = new User(); // User | Created user object + try { + apiInstance.createUser(user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **user** | [**User**](User.md)| Created user object | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithArrayInput + +> createUsersWithArrayInput(user) + +Creates list of users with given input array + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List user = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithArrayInput(user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **user** | [**List<User>**](User.md)| List of user object | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithListInput + +> createUsersWithListInput(user) + +Creates list of users with given input array + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List user = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithListInput(user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **user** | [**List<User>**](User.md)| List of user object | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## deleteUser + +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be deleted + try { + apiInstance.deleteUser(username); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The name that needs to be deleted | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## getUserByName + +> User getUserByName(username) + +Get user by user name + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. + try { + User result = apiInstance.getUserByName(username); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The name that needs to be fetched. Use user1 for testing. | | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## loginUser + +> String loginUser(username, password) + +Logs user into the system + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The user name for login + String password = "password_example"; // String | The password for login in clear text + try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The user name for login | | +| **password** | **String**| The password for login in clear text | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
        * X-Expires-After - date in UTC when token expires
        | +| **400** | Invalid username/password supplied | - | + + +## logoutUser + +> logoutUser() + +Logs out current logged in user session + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + try { + apiInstance.logoutUser(); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## updateUser + +> updateUser(username, user) + +Updated user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | name that need to be deleted + User user = new User(); // User | Updated user object + try { + apiInstance.updateUser(username, user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| name that need to be deleted | | +| **user** | [**User**](User.md)| Updated user object | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/samples/client/petstore/java-helidon-client/se/pom.xml b/samples/client/petstore/java-helidon-client/se/pom.xml new file mode 100644 index 0000000000..6047a12ad4 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/pom.xml @@ -0,0 +1,69 @@ + + 4.0.0 + org.openapitools + + io.helidon.applications + helidon-se + 3.0.1 + + + petstore-helidon-client-se + petstore-helidon-client-se + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + 1.0.0 + jar + + + + io.helidon.webclient + helidon-webclient + + + io.helidon.config + helidon-config + + + jakarta.json + jakarta.json-api + + + io.helidon.media + helidon-media-jackson + + + org.glassfish.jersey.media + jersey-media-json-jackson + + + org.openapitools + jackson-databind-nullable + 0.2.2 + + + org.junit.jupiter + junit-jupiter-api + test + + + org.hamcrest + hamcrest-all + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libs + + + + + + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 0000000000..831df8cb58 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,241 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openapitools.jackson.nullable.JsonNullableModule; + +import io.helidon.config.Config; +import io.helidon.media.jackson.JacksonSupport; +import io.helidon.webclient.WebClient; + +import java.net.URI; +import java.net.URLEncoder; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.StringJoiner; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import static java.nio.charset.StandardCharsets.UTF_8; + +/** + * Configuration and utility class for API clients. + *

        + * Use the {@link ApiClient.Builder} class to prepare and ultimately create the {@code ApiClient} instance. + *

        + */ +public class ApiClient { + + private final WebClient webClient; + + /** + * @return a {@code Builder} for an {@code ApiClient} + */ + public static ApiClient.Builder builder() { + return new Builder(); + } + + /** + * URL encode a string in the UTF-8 encoding. + * + * @param s String to encode. + * @return URL-encoded representation of the input string. + */ + public static String urlEncode(String s) { + return URLEncoder.encode(s, UTF_8); + } + + /** + * Convert a URL query name/value parameter to a list of encoded {@link Pair} + * objects. + * + *

        The value can be null, in which case an empty list is returned.

        + * + * @param name The query name parameter. + * @param value The query value, which may not be a collection but may be + * null. + * @return A singleton list of the {@link Pair} objects representing the input + * parameters, which is encoded for use in a URL. If the value is null, an + * empty list is returned. + */ + public static List parameterToPairs(String name, Object value) { + if (name == null || name.isEmpty() || value == null) { + return Collections.emptyList(); + } + return Collections.singletonList(new Pair(urlEncode(name), urlEncode(valueToString(value)))); + } + + /** + * Convert a URL query name/collection parameter to a list of encoded + * {@link Pair} objects. + * + * @param collectionFormat The swagger collectionFormat string (csv, tsv, etc). + * @param name The query name parameter. + * @param values A collection of values for the given query name, which may be + * null. + * @return A list of {@link Pair} objects representing the input parameters, + * which is encoded for use in a URL. If the values collection is null, an + * empty list is returned. + */ + public static List parameterToPairs( + String collectionFormat, String name, Collection values) { + if (name == null || name.isEmpty() || values == null || values.isEmpty()) { + return Collections.emptyList(); + } + + // get the collection format (default: csv) + String format = collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat; + + // create the params based on the collection format + if ("multi".equals(format)) { + return values.stream() + .map(value -> new Pair(urlEncode(name), urlEncode(valueToString(value)))) + .collect(Collectors.toList()); + } + + String delimiter; + switch(format) { + case "csv": + delimiter = urlEncode(","); + break; + case "ssv": + delimiter = urlEncode(" "); + break; + case "tsv": + delimiter = urlEncode("\t"); + break; + case "pipes": + delimiter = urlEncode("|"); + break; + default: + throw new IllegalArgumentException("Illegal collection format: " + collectionFormat); + } + + StringJoiner joiner = new StringJoiner(delimiter); + for (Object value : values) { + joiner.add(urlEncode(valueToString(value))); + } + + return Collections.singletonList(new Pair(urlEncode(name), joiner.toString())); + } + + private ApiClient(Builder builder) { + webClient = builder.webClientBuilder().build(); + } + + /** + * Get the {@link WebClient} prepared by the builder of this {@code ApiClient}. + * + * @return the WebClient + */ + public WebClient webClient() { + return webClient; + } + + private static String valueToString(Object value) { + if (value == null) { + return ""; + } + if (value instanceof OffsetDateTime) { + return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + return value.toString(); + } + + /** + * Builder for creating a new {@code ApiClient} instance. + * + *

        + * The builder accepts a {@link WebClient.Builder} via the {@code webClientBuilder} method but will provide a default one + * using available configuration (the {@code client} node) and the base URI set in the OpenAPI document. + *

        + */ + public static class Builder { + + private WebClient.Builder webClientBuilder; + private Config clientConfig; + private ObjectMapper objectMapper; + + public ApiClient build() { + return new ApiClient(this); + } + + /** + * Sets the {@code WebClient.Builder} which the {@code ApiClient.Builder} uses. Any previous setting is discarded. + * + * @param webClientBuilder the {@code WebClient.Builder} to be used going forward + * @return the updated builder + */ + public Builder webClientBuilder(WebClient.Builder webClientBuilder) { + this.webClientBuilder = webClientBuilder; + return this; + } + + /** + * Sets the client {@code Config} which the {@code ApiClient.Builder} uses in preparing a default {@code WebClient.Builder}. + * The builder ignores this setting if you provide your own {@code WebClient.Builder} by invoking the + * {@code webClientBuilder} method. + * + * @param clientConfig the {@code Config} node containing client settings + * @return the updated builder + */ + public Builder clientConfig(Config clientConfig) { + this.clientConfig = clientConfig; + return this; + } + + /** + * @return the previously-stored web client builder or, if none, a default one using the provided or defaulted + * client configuration + */ + public WebClient.Builder webClientBuilder() { + if (webClientBuilder == null) { + webClientBuilder = defaultWebClientBuilder(); + } + return webClientBuilder; + } + + /** + * Stores the Jackson {@code ObjectMapper} the builder uses in preparing the {@code WebClient}. + * + * @param objectMapper the Jackson object mapper to use in all API invocations via the built {@code ApiClient} + * @return the updated builder + */ + public Builder objectMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + return this; + } + + private WebClient.Builder defaultWebClientBuilder() { + WebClient.Builder defaultWebClientBuilder = WebClient.builder() + .baseUri("http://petstore.swagger.io:80/v2") + .config(clientConfig()); + defaultWebClientBuilder.addMediaSupport(objectMapper == null + ? JacksonSupport.create() + : JacksonSupport.create(objectMapper)); + return defaultWebClientBuilder; + } + + private Config clientConfig() { + if (clientConfig == null) { + clientConfig = Config.create().get("client"); + } + return clientConfig; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/ApiResponse.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/ApiResponse.java new file mode 100644 index 0000000000..f1e304babe --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/ApiResponse.java @@ -0,0 +1,43 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import java.util.concurrent.ExecutionException; + +import io.helidon.common.GenericType; +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +/** + * Generic-typed response. + * + * Return type for generated API methods. + * + * @param type of the return value from the generated API method + */ +public interface ApiResponse { + + static ApiResponse create(GenericType responseType, Single webClientResponse) { + return new ApiResponseBase<>(responseType, webClientResponse); + } + + /** + * @returns reactive access to the {@link WebClientResponse} describing the response from the server + */ + Single webClientResponse(); + + /** + * @return reactive access to the value returned in the response from the server + */ + Single result() throws ExecutionException, InterruptedException; +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/ApiResponseBase.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/ApiResponseBase.java new file mode 100644 index 0000000000..7653613d4e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/ApiResponseBase.java @@ -0,0 +1,45 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import java.util.concurrent.ExecutionException; + +import io.helidon.common.GenericType; +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +/** + * Implementation of a generic-typed response. + * + * @param type of the return value from the generated API method + */ +class ApiResponseBase implements ApiResponse { + + private final Single webClientResponse; + private final GenericType responseType; + + protected ApiResponseBase(GenericType responseType, Single webClientResponse) { + this.webClientResponse = webClientResponse; + this.responseType = responseType; + } + + @Override + public Single webClientResponse() { + return webClientResponse; + } + + @Override + public Single result() throws ExecutionException, InterruptedException { + return webClientResponse.get().content().as(responseType); + } +} \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/Pair.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/Pair.java similarity index 86% rename from samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/Pair.java rename to samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/Pair.java index e1afb8c039..50dd6b1cd2 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/Pair.java +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/Pair.java @@ -1,4 +1,4 @@ -/* +/** * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * @@ -13,7 +13,6 @@ package org.openapitools.client; -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class Pair { private String name = ""; private String value = ""; @@ -52,10 +51,6 @@ public class Pair { return false; } - if (arg.trim().isEmpty()) { - return false; - } - return true; } } diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/RFC3339DateFormat.java new file mode 100644 index 0000000000..dd96c18c0d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -0,0 +1,57 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.text.DecimalFormat; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + this.numberFormat = new DecimalFormat(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return super.clone(); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/AnotherFakeApi.java new file mode 100644 index 0000000000..f1f0fe1f3d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -0,0 +1,35 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiResponse; +import org.openapitools.client.model.Client; +import java.util.List; +import java.util.Map; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public interface AnotherFakeApi { + + /** + * To test special tags + * To test special tags and operation ID starting with number + * @param client client model (required) + * @return {@code ApiResponse} + */ + ApiResponse call123testSpecialTags(Client client); + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/AnotherFakeApiImpl.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/AnotherFakeApiImpl.java new file mode 100644 index 0000000000..39001e3d1c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/AnotherFakeApiImpl.java @@ -0,0 +1,97 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.util.Objects; +import org.openapitools.client.ApiResponse; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.common.GenericType; +import io.helidon.common.http.MediaType; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.media.common.MediaSupport; + +import io.helidon.media.jackson.JacksonSupport; +import io.helidon.webclient.WebClientRequestBuilder; +import io.helidon.webclient.WebClientResponse; + +import org.openapitools.client.ApiClient; + +import org.openapitools.client.model.Client; +import java.util.List; +import java.util.Map; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public class AnotherFakeApiImpl implements AnotherFakeApi { + + private final ApiClient apiClient; + + protected static final GenericType RESPONSE_TYPE_call123testSpecialTags = ResponseType.create(Client.class); + + /** + * Creates a new instance of AnotherFakeApiImpl initialized with the specified {@link ApiClient}. + * + */ + public static AnotherFakeApiImpl create(ApiClient apiClient) { + return new AnotherFakeApiImpl(apiClient); + } + + protected AnotherFakeApiImpl(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @Override + public ApiResponse call123testSpecialTags(Client client) { + Objects.requireNonNull(client, "Required parameter 'client' not specified"); + WebClientRequestBuilder webClientRequestBuilder = call123testSpecialTagsRequestBuilder(client); + return call123testSpecialTagsSubmit(webClientRequestBuilder, client); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the call123testSpecialTags operation. + * Optional customization point for subclasses. + * + * @param client client model (required) + * @return WebClientRequestBuilder for call123testSpecialTags + */ + protected WebClientRequestBuilder call123testSpecialTagsRequestBuilder(Client client) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("PATCH"); + + webClientRequestBuilder.path("/another-fake/dummy"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the call123testSpecialTags operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param client client model (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse call123testSpecialTagsSubmit(WebClientRequestBuilder webClientRequestBuilder, Client client) { + Single webClientResponse = webClientRequestBuilder.submit(client); + return ApiResponse.create(RESPONSE_TYPE_call123testSpecialTags, webClientResponse); + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/DefaultApi.java new file mode 100644 index 0000000000..75f45b2d88 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -0,0 +1,27 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiResponse; +import org.openapitools.client.model.FooGetDefaultResponse; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public interface DefaultApi { + + ApiResponse fooGet(); + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/DefaultApiImpl.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/DefaultApiImpl.java new file mode 100644 index 0000000000..734cd4f310 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/DefaultApiImpl.java @@ -0,0 +1,91 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.util.Objects; +import org.openapitools.client.ApiResponse; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.common.GenericType; +import io.helidon.common.http.MediaType; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.media.common.MediaSupport; + +import io.helidon.media.jackson.JacksonSupport; +import io.helidon.webclient.WebClientRequestBuilder; +import io.helidon.webclient.WebClientResponse; + +import org.openapitools.client.ApiClient; + +import org.openapitools.client.model.FooGetDefaultResponse; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public class DefaultApiImpl implements DefaultApi { + + private final ApiClient apiClient; + + protected static final GenericType RESPONSE_TYPE_fooGet = ResponseType.create(FooGetDefaultResponse.class); + + /** + * Creates a new instance of DefaultApiImpl initialized with the specified {@link ApiClient}. + * + */ + public static DefaultApiImpl create(ApiClient apiClient) { + return new DefaultApiImpl(apiClient); + } + + protected DefaultApiImpl(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @Override + public ApiResponse fooGet() { + WebClientRequestBuilder webClientRequestBuilder = fooGetRequestBuilder(); + return fooGetSubmit(webClientRequestBuilder); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the fooGet operation. + * Optional customization point for subclasses. + * + * @return WebClientRequestBuilder for fooGet + */ + protected WebClientRequestBuilder fooGetRequestBuilder() { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + webClientRequestBuilder.path("/foo"); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the fooGet operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse fooGetSubmit(WebClientRequestBuilder webClientRequestBuilder) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_fooGet, webClientResponse); + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApi.java new file mode 100644 index 0000000000..01701727d0 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApi.java @@ -0,0 +1,146 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiResponse; +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import org.openapitools.client.model.EnumClass; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.HealthCheckResult; +import java.util.List; +import java.time.LocalDate; +import java.util.Map; +import java.time.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.OuterObjectWithEnumProperty; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.User; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public interface FakeApi { + + /** + * Health check endpoint + * @return {@code ApiResponse} + */ + ApiResponse fakeHealthGet(); + + /** + * test http signature authentication + * @param pet Pet object that needs to be added to the store (required) + * @param query1 query parameter (optional) + * @param header1 header parameter (optional) + * @return {@code ApiResponse} + */ + ApiResponse fakeHttpSignatureTest(Pet pet, String query1, String header1); + + ApiResponse fakeOuterBooleanSerialize(Boolean body); + + ApiResponse fakeOuterCompositeSerialize(OuterComposite outerComposite); + + ApiResponse fakeOuterNumberSerialize(BigDecimal body); + + ApiResponse fakeOuterStringSerialize(String body); + + ApiResponse fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty); + + ApiResponse testBodyWithBinary(File body); + + ApiResponse testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass); + + ApiResponse testBodyWithQueryParams(String query, User user); + + /** + * To test \"client\" model + * To test \"client\" model + * @param client client model (required) + * @return {@code ApiResponse} + */ + ApiResponse testClientModel(Client client); + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @return {@code ApiResponse} + */ + ApiResponse testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback); + + /** + * To test enum parameters + * To test enum parameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param enumQueryModelArray (optional + * @param enumFormStringArray Form parameter enum test (string array) (optional + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @return {@code ApiResponse} + */ + ApiResponse testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumQueryModelArray, List enumFormStringArray, String enumFormString); + + /** + * Fake endpoint to test group parameters (optional) + * Fake endpoint to test group parameters (optional) + * @param requiredStringGroup Required String in group parameters (required) + * @param requiredBooleanGroup Required Boolean in group parameters (required) + * @param requiredInt64Group Required Integer in group parameters (required) + * @param stringGroup String in group parameters (optional) + * @param booleanGroup Boolean in group parameters (optional) + * @param int64Group Integer in group parameters (optional) + * @return {@code ApiResponse} + */ + ApiResponse testGroupParameters(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group); + + /** + * test inline additionalProperties + * + * @param requestBody request body (required) + * @return {@code ApiResponse} + */ + ApiResponse testInlineAdditionalProperties(Map requestBody); + + /** + * test json serialization of form data + * + * @param param field1 (required) + * @param param2 field2 (required) + * @return {@code ApiResponse} + */ + ApiResponse testJsonFormData(String param, String param2); + + ApiResponse testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context, String allowEmpty, Map language); + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApiImpl.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApiImpl.java new file mode 100644 index 0000000000..1b323ac2f8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApiImpl.java @@ -0,0 +1,887 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.util.Objects; +import org.openapitools.client.ApiResponse; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.common.GenericType; +import io.helidon.common.http.MediaType; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.media.common.MediaSupport; + +import io.helidon.media.jackson.JacksonSupport; +import io.helidon.webclient.WebClientRequestBuilder; +import io.helidon.webclient.WebClientResponse; + +import org.openapitools.client.ApiClient; + +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import org.openapitools.client.model.EnumClass; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.HealthCheckResult; +import java.util.List; +import java.time.LocalDate; +import java.util.Map; +import java.time.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.OuterObjectWithEnumProperty; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.User; +import java.util.ArrayList; +import org.openapitools.client.Pair; +import java.util.StringJoiner; +import io.helidon.webclient.WebClientRequestHeaders; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public class FakeApiImpl implements FakeApi { + + private final ApiClient apiClient; + + protected static final GenericType RESPONSE_TYPE_fakeHealthGet = ResponseType.create(HealthCheckResult.class); + protected static final GenericType RESPONSE_TYPE_fakeHttpSignatureTest = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_fakeOuterBooleanSerialize = ResponseType.create(Boolean.class); + protected static final GenericType RESPONSE_TYPE_fakeOuterCompositeSerialize = ResponseType.create(OuterComposite.class); + protected static final GenericType RESPONSE_TYPE_fakeOuterNumberSerialize = ResponseType.create(BigDecimal.class); + protected static final GenericType RESPONSE_TYPE_fakeOuterStringSerialize = ResponseType.create(String.class); + protected static final GenericType RESPONSE_TYPE_fakePropertyEnumIntegerSerialize = ResponseType.create(OuterObjectWithEnumProperty.class); + protected static final GenericType RESPONSE_TYPE_testBodyWithBinary = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_testBodyWithFileSchema = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_testBodyWithQueryParams = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_testClientModel = ResponseType.create(Client.class); + protected static final GenericType RESPONSE_TYPE_testEndpointParameters = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_testEnumParameters = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_testGroupParameters = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_testInlineAdditionalProperties = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_testJsonFormData = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_testQueryParameterCollectionFormat = ResponseType.create(Void.class); + + /** + * Creates a new instance of FakeApiImpl initialized with the specified {@link ApiClient}. + * + */ + public static FakeApiImpl create(ApiClient apiClient) { + return new FakeApiImpl(apiClient); + } + + protected FakeApiImpl(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @Override + public ApiResponse fakeHealthGet() { + WebClientRequestBuilder webClientRequestBuilder = fakeHealthGetRequestBuilder(); + return fakeHealthGetSubmit(webClientRequestBuilder); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the fakeHealthGet operation. + * Optional customization point for subclasses. + * + * @return WebClientRequestBuilder for fakeHealthGet + */ + protected WebClientRequestBuilder fakeHealthGetRequestBuilder() { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + webClientRequestBuilder.path("/fake/health"); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the fakeHealthGet operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse fakeHealthGetSubmit(WebClientRequestBuilder webClientRequestBuilder) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_fakeHealthGet, webClientResponse); + } + + @Override + public ApiResponse fakeHttpSignatureTest(Pet pet, String query1, String header1) { + Objects.requireNonNull(pet, "Required parameter 'pet' not specified"); + WebClientRequestBuilder webClientRequestBuilder = fakeHttpSignatureTestRequestBuilder(pet, query1, header1); + return fakeHttpSignatureTestSubmit(webClientRequestBuilder, pet, query1, header1); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the fakeHttpSignatureTest operation. + * Optional customization point for subclasses. + * + * @param pet Pet object that needs to be added to the store (required) + * @param query1 query parameter (optional) + * @param header1 header parameter (optional) + * @return WebClientRequestBuilder for fakeHttpSignatureTest + */ + protected WebClientRequestBuilder fakeHttpSignatureTestRequestBuilder(Pet pet, String query1, String header1) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + List queryParams = new ArrayList<>(); + queryParams.addAll(ApiClient.parameterToPairs("query_1", query1)); + queryParams.forEach(p -> webClientRequestBuilder.queryParam(p.getName(), p.getValue())); + + WebClientRequestHeaders headers = webClientRequestBuilder.headers(); + if (header1 != null) { + headers.put("header_1", header1); + } + + webClientRequestBuilder.path("/fake/http-signature-test"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the fakeHttpSignatureTest operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param pet Pet object that needs to be added to the store (required) + * @param query1 query parameter (optional) + * @param header1 header parameter (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse fakeHttpSignatureTestSubmit(WebClientRequestBuilder webClientRequestBuilder, Pet pet, String query1, String header1) { + Single webClientResponse = webClientRequestBuilder.submit(pet); + return ApiResponse.create(RESPONSE_TYPE_fakeHttpSignatureTest, webClientResponse); + } + + @Override + public ApiResponse fakeOuterBooleanSerialize(Boolean body) { + WebClientRequestBuilder webClientRequestBuilder = fakeOuterBooleanSerializeRequestBuilder(body); + return fakeOuterBooleanSerializeSubmit(webClientRequestBuilder, body); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the fakeOuterBooleanSerialize operation. + * Optional customization point for subclasses. + * + * @param body Input boolean as post body (optional) + * @return WebClientRequestBuilder for fakeOuterBooleanSerialize + */ + protected WebClientRequestBuilder fakeOuterBooleanSerializeRequestBuilder(Boolean body) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/fake/outer/boolean"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the fakeOuterBooleanSerialize operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param body Input boolean as post body (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse fakeOuterBooleanSerializeSubmit(WebClientRequestBuilder webClientRequestBuilder, Boolean body) { + Single webClientResponse = webClientRequestBuilder.submit(body); + return ApiResponse.create(RESPONSE_TYPE_fakeOuterBooleanSerialize, webClientResponse); + } + + @Override + public ApiResponse fakeOuterCompositeSerialize(OuterComposite outerComposite) { + WebClientRequestBuilder webClientRequestBuilder = fakeOuterCompositeSerializeRequestBuilder(outerComposite); + return fakeOuterCompositeSerializeSubmit(webClientRequestBuilder, outerComposite); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the fakeOuterCompositeSerialize operation. + * Optional customization point for subclasses. + * + * @param outerComposite Input composite as post body (optional) + * @return WebClientRequestBuilder for fakeOuterCompositeSerialize + */ + protected WebClientRequestBuilder fakeOuterCompositeSerializeRequestBuilder(OuterComposite outerComposite) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/fake/outer/composite"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the fakeOuterCompositeSerialize operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param outerComposite Input composite as post body (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse fakeOuterCompositeSerializeSubmit(WebClientRequestBuilder webClientRequestBuilder, OuterComposite outerComposite) { + Single webClientResponse = webClientRequestBuilder.submit(outerComposite); + return ApiResponse.create(RESPONSE_TYPE_fakeOuterCompositeSerialize, webClientResponse); + } + + @Override + public ApiResponse fakeOuterNumberSerialize(BigDecimal body) { + WebClientRequestBuilder webClientRequestBuilder = fakeOuterNumberSerializeRequestBuilder(body); + return fakeOuterNumberSerializeSubmit(webClientRequestBuilder, body); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the fakeOuterNumberSerialize operation. + * Optional customization point for subclasses. + * + * @param body Input number as post body (optional) + * @return WebClientRequestBuilder for fakeOuterNumberSerialize + */ + protected WebClientRequestBuilder fakeOuterNumberSerializeRequestBuilder(BigDecimal body) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/fake/outer/number"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the fakeOuterNumberSerialize operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param body Input number as post body (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse fakeOuterNumberSerializeSubmit(WebClientRequestBuilder webClientRequestBuilder, BigDecimal body) { + Single webClientResponse = webClientRequestBuilder.submit(body); + return ApiResponse.create(RESPONSE_TYPE_fakeOuterNumberSerialize, webClientResponse); + } + + @Override + public ApiResponse fakeOuterStringSerialize(String body) { + WebClientRequestBuilder webClientRequestBuilder = fakeOuterStringSerializeRequestBuilder(body); + return fakeOuterStringSerializeSubmit(webClientRequestBuilder, body); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the fakeOuterStringSerialize operation. + * Optional customization point for subclasses. + * + * @param body Input string as post body (optional) + * @return WebClientRequestBuilder for fakeOuterStringSerialize + */ + protected WebClientRequestBuilder fakeOuterStringSerializeRequestBuilder(String body) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/fake/outer/string"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the fakeOuterStringSerialize operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param body Input string as post body (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse fakeOuterStringSerializeSubmit(WebClientRequestBuilder webClientRequestBuilder, String body) { + Single webClientResponse = webClientRequestBuilder.submit(body); + return ApiResponse.create(RESPONSE_TYPE_fakeOuterStringSerialize, webClientResponse); + } + + @Override + public ApiResponse fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty) { + Objects.requireNonNull(outerObjectWithEnumProperty, "Required parameter 'outerObjectWithEnumProperty' not specified"); + WebClientRequestBuilder webClientRequestBuilder = fakePropertyEnumIntegerSerializeRequestBuilder(outerObjectWithEnumProperty); + return fakePropertyEnumIntegerSerializeSubmit(webClientRequestBuilder, outerObjectWithEnumProperty); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the fakePropertyEnumIntegerSerialize operation. + * Optional customization point for subclasses. + * + * @param outerObjectWithEnumProperty Input enum (int) as post body (required) + * @return WebClientRequestBuilder for fakePropertyEnumIntegerSerialize + */ + protected WebClientRequestBuilder fakePropertyEnumIntegerSerializeRequestBuilder(OuterObjectWithEnumProperty outerObjectWithEnumProperty) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/fake/property/enum-int"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the fakePropertyEnumIntegerSerialize operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param outerObjectWithEnumProperty Input enum (int) as post body (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse fakePropertyEnumIntegerSerializeSubmit(WebClientRequestBuilder webClientRequestBuilder, OuterObjectWithEnumProperty outerObjectWithEnumProperty) { + Single webClientResponse = webClientRequestBuilder.submit(outerObjectWithEnumProperty); + return ApiResponse.create(RESPONSE_TYPE_fakePropertyEnumIntegerSerialize, webClientResponse); + } + + @Override + public ApiResponse testBodyWithBinary(File body) { + Objects.requireNonNull(body, "Required parameter 'body' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testBodyWithBinaryRequestBuilder(body); + return testBodyWithBinarySubmit(webClientRequestBuilder, body); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testBodyWithBinary operation. + * Optional customization point for subclasses. + * + * @param body image to upload (required) + * @return WebClientRequestBuilder for testBodyWithBinary + */ + protected WebClientRequestBuilder testBodyWithBinaryRequestBuilder(File body) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("PUT"); + + webClientRequestBuilder.path("/fake/body-with-binary"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testBodyWithBinary operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param body image to upload (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testBodyWithBinarySubmit(WebClientRequestBuilder webClientRequestBuilder, File body) { + Single webClientResponse = webClientRequestBuilder.submit(body); + return ApiResponse.create(RESPONSE_TYPE_testBodyWithBinary, webClientResponse); + } + + @Override + public ApiResponse testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) { + Objects.requireNonNull(fileSchemaTestClass, "Required parameter 'fileSchemaTestClass' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testBodyWithFileSchemaRequestBuilder(fileSchemaTestClass); + return testBodyWithFileSchemaSubmit(webClientRequestBuilder, fileSchemaTestClass); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testBodyWithFileSchema operation. + * Optional customization point for subclasses. + * + * @param fileSchemaTestClass (required) + * @return WebClientRequestBuilder for testBodyWithFileSchema + */ + protected WebClientRequestBuilder testBodyWithFileSchemaRequestBuilder(FileSchemaTestClass fileSchemaTestClass) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("PUT"); + + webClientRequestBuilder.path("/fake/body-with-file-schema"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testBodyWithFileSchema operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param fileSchemaTestClass (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testBodyWithFileSchemaSubmit(WebClientRequestBuilder webClientRequestBuilder, FileSchemaTestClass fileSchemaTestClass) { + Single webClientResponse = webClientRequestBuilder.submit(fileSchemaTestClass); + return ApiResponse.create(RESPONSE_TYPE_testBodyWithFileSchema, webClientResponse); + } + + @Override + public ApiResponse testBodyWithQueryParams(String query, User user) { + Objects.requireNonNull(query, "Required parameter 'query' not specified"); + Objects.requireNonNull(user, "Required parameter 'user' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testBodyWithQueryParamsRequestBuilder(query, user); + return testBodyWithQueryParamsSubmit(webClientRequestBuilder, query, user); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testBodyWithQueryParams operation. + * Optional customization point for subclasses. + * + * @param query (required) + * @param user (required) + * @return WebClientRequestBuilder for testBodyWithQueryParams + */ + protected WebClientRequestBuilder testBodyWithQueryParamsRequestBuilder(String query, User user) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("PUT"); + + List queryParams = new ArrayList<>(); + queryParams.addAll(ApiClient.parameterToPairs("query", query)); + queryParams.forEach(p -> webClientRequestBuilder.queryParam(p.getName(), p.getValue())); + + webClientRequestBuilder.path("/fake/body-with-query-params"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testBodyWithQueryParams operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param query (required) + * @param user (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testBodyWithQueryParamsSubmit(WebClientRequestBuilder webClientRequestBuilder, String query, User user) { + Single webClientResponse = webClientRequestBuilder.submit(user); + return ApiResponse.create(RESPONSE_TYPE_testBodyWithQueryParams, webClientResponse); + } + + @Override + public ApiResponse testClientModel(Client client) { + Objects.requireNonNull(client, "Required parameter 'client' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testClientModelRequestBuilder(client); + return testClientModelSubmit(webClientRequestBuilder, client); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testClientModel operation. + * Optional customization point for subclasses. + * + * @param client client model (required) + * @return WebClientRequestBuilder for testClientModel + */ + protected WebClientRequestBuilder testClientModelRequestBuilder(Client client) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("PATCH"); + + webClientRequestBuilder.path("/fake"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testClientModel operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param client client model (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testClientModelSubmit(WebClientRequestBuilder webClientRequestBuilder, Client client) { + Single webClientResponse = webClientRequestBuilder.submit(client); + return ApiResponse.create(RESPONSE_TYPE_testClientModel, webClientResponse); + } + + @Override + public ApiResponse testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) { + Objects.requireNonNull(number, "Required parameter 'number' not specified"); + Objects.requireNonNull(_double, "Required parameter '_double' not specified"); + Objects.requireNonNull(patternWithoutDelimiter, "Required parameter 'patternWithoutDelimiter' not specified"); + Objects.requireNonNull(_byte, "Required parameter '_byte' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testEndpointParametersRequestBuilder(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + return testEndpointParametersSubmit(webClientRequestBuilder, number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testEndpointParameters operation. + * Optional customization point for subclasses. + * + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @return WebClientRequestBuilder for testEndpointParameters + */ + protected WebClientRequestBuilder testEndpointParametersRequestBuilder(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/fake"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_FORM_URLENCODED); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testEndpointParameters operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testEndpointParametersSubmit(WebClientRequestBuilder webClientRequestBuilder, BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) { + String formParams = new StringJoiner("&") + .add("integer=" + integer) + .add("int32=" + int32) + .add("int64=" + int64) + .add("number=" + number) + .add("float=" + _float) + .add("double=" + _double) + .add("string=" + string) + .add("pattern_without_delimiter=" + patternWithoutDelimiter) + .add("byte=" + _byte) + .add("binary=" + binary) + .add("date=" + date) + .add("dateTime=" + dateTime) + .add("password=" + password) + .add("callback=" + paramCallback) + .toString(); + Single webClientResponse = webClientRequestBuilder.submit(formParams); + return ApiResponse.create(RESPONSE_TYPE_testEndpointParameters, webClientResponse); + } + + @Override + public ApiResponse testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumQueryModelArray, List enumFormStringArray, String enumFormString) { + WebClientRequestBuilder webClientRequestBuilder = testEnumParametersRequestBuilder(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString); + return testEnumParametersSubmit(webClientRequestBuilder, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testEnumParameters operation. + * Optional customization point for subclasses. + * + * @param enumHeaderStringArray Header parameter enum test (string array) (optional + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param enumQueryModelArray (optional + * @param enumFormStringArray Form parameter enum test (string array) (optional + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @return WebClientRequestBuilder for testEnumParameters + */ + protected WebClientRequestBuilder testEnumParametersRequestBuilder(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumQueryModelArray, List enumFormStringArray, String enumFormString) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + List queryParams = new ArrayList<>(); + queryParams.addAll(ApiClient.parameterToPairs("multi", "enum_query_string_array", enumQueryStringArray)); + queryParams.addAll(ApiClient.parameterToPairs("enum_query_string", enumQueryString)); + queryParams.addAll(ApiClient.parameterToPairs("enum_query_integer", enumQueryInteger)); + queryParams.addAll(ApiClient.parameterToPairs("enum_query_double", enumQueryDouble)); + queryParams.addAll(ApiClient.parameterToPairs("multi", "enum_query_model_array", enumQueryModelArray)); + queryParams.forEach(p -> webClientRequestBuilder.queryParam(p.getName(), p.getValue())); + + WebClientRequestHeaders headers = webClientRequestBuilder.headers(); + if (enumHeaderStringArray != null) { + headers.put("enum_header_string_array", enumHeaderStringArray.toString()); + } + if (enumHeaderString != null) { + headers.put("enum_header_string", enumHeaderString); + } + + webClientRequestBuilder.path("/fake"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_FORM_URLENCODED); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testEnumParameters operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param enumHeaderStringArray Header parameter enum test (string array) (optional + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param enumQueryModelArray (optional + * @param enumFormStringArray Form parameter enum test (string array) (optional + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testEnumParametersSubmit(WebClientRequestBuilder webClientRequestBuilder, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumQueryModelArray, List enumFormStringArray, String enumFormString) { + String formParams = new StringJoiner("&") + .add("enum_form_string_array=" + enumFormStringArray) + .add("enum_form_string=" + enumFormString) + .toString(); + Single webClientResponse = webClientRequestBuilder.submit(formParams); + return ApiResponse.create(RESPONSE_TYPE_testEnumParameters, webClientResponse); + } + + @Override + public ApiResponse testGroupParameters(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) { + Objects.requireNonNull(requiredStringGroup, "Required parameter 'requiredStringGroup' not specified"); + Objects.requireNonNull(requiredBooleanGroup, "Required parameter 'requiredBooleanGroup' not specified"); + Objects.requireNonNull(requiredInt64Group, "Required parameter 'requiredInt64Group' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testGroupParametersRequestBuilder(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + return testGroupParametersSubmit(webClientRequestBuilder, requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testGroupParameters operation. + * Optional customization point for subclasses. + * + * @param requiredStringGroup Required String in group parameters (required) + * @param requiredBooleanGroup Required Boolean in group parameters (required) + * @param requiredInt64Group Required Integer in group parameters (required) + * @param stringGroup String in group parameters (optional) + * @param booleanGroup Boolean in group parameters (optional) + * @param int64Group Integer in group parameters (optional) + * @return WebClientRequestBuilder for testGroupParameters + */ + protected WebClientRequestBuilder testGroupParametersRequestBuilder(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("DELETE"); + + List queryParams = new ArrayList<>(); + queryParams.addAll(ApiClient.parameterToPairs("required_string_group", requiredStringGroup)); + queryParams.addAll(ApiClient.parameterToPairs("required_int64_group", requiredInt64Group)); + queryParams.addAll(ApiClient.parameterToPairs("string_group", stringGroup)); + queryParams.addAll(ApiClient.parameterToPairs("int64_group", int64Group)); + queryParams.forEach(p -> webClientRequestBuilder.queryParam(p.getName(), p.getValue())); + + WebClientRequestHeaders headers = webClientRequestBuilder.headers(); + if (requiredBooleanGroup != null) { + headers.put("required_boolean_group", requiredBooleanGroup.toString()); + } + if (booleanGroup != null) { + headers.put("boolean_group", booleanGroup.toString()); + } + + webClientRequestBuilder.path("/fake"); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testGroupParameters operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param requiredStringGroup Required String in group parameters (required) + * @param requiredBooleanGroup Required Boolean in group parameters (required) + * @param requiredInt64Group Required Integer in group parameters (required) + * @param stringGroup String in group parameters (optional) + * @param booleanGroup Boolean in group parameters (optional) + * @param int64Group Integer in group parameters (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testGroupParametersSubmit(WebClientRequestBuilder webClientRequestBuilder, Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_testGroupParameters, webClientResponse); + } + + @Override + public ApiResponse testInlineAdditionalProperties(Map requestBody) { + Objects.requireNonNull(requestBody, "Required parameter 'requestBody' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testInlineAdditionalPropertiesRequestBuilder(requestBody); + return testInlineAdditionalPropertiesSubmit(webClientRequestBuilder, requestBody); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testInlineAdditionalProperties operation. + * Optional customization point for subclasses. + * + * @param requestBody request body (required) + * @return WebClientRequestBuilder for testInlineAdditionalProperties + */ + protected WebClientRequestBuilder testInlineAdditionalPropertiesRequestBuilder(Map requestBody) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/fake/inline-additionalProperties"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testInlineAdditionalProperties operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param requestBody request body (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testInlineAdditionalPropertiesSubmit(WebClientRequestBuilder webClientRequestBuilder, Map requestBody) { + Single webClientResponse = webClientRequestBuilder.submit(requestBody); + return ApiResponse.create(RESPONSE_TYPE_testInlineAdditionalProperties, webClientResponse); + } + + @Override + public ApiResponse testJsonFormData(String param, String param2) { + Objects.requireNonNull(param, "Required parameter 'param' not specified"); + Objects.requireNonNull(param2, "Required parameter 'param2' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testJsonFormDataRequestBuilder(param, param2); + return testJsonFormDataSubmit(webClientRequestBuilder, param, param2); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testJsonFormData operation. + * Optional customization point for subclasses. + * + * @param param field1 (required) + * @param param2 field2 (required) + * @return WebClientRequestBuilder for testJsonFormData + */ + protected WebClientRequestBuilder testJsonFormDataRequestBuilder(String param, String param2) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + webClientRequestBuilder.path("/fake/jsonFormData"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_FORM_URLENCODED); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testJsonFormData operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param param field1 (required) + * @param param2 field2 (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testJsonFormDataSubmit(WebClientRequestBuilder webClientRequestBuilder, String param, String param2) { + String formParams = new StringJoiner("&") + .add("param=" + param) + .add("param2=" + param2) + .toString(); + Single webClientResponse = webClientRequestBuilder.submit(formParams); + return ApiResponse.create(RESPONSE_TYPE_testJsonFormData, webClientResponse); + } + + @Override + public ApiResponse testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context, String allowEmpty, Map language) { + Objects.requireNonNull(pipe, "Required parameter 'pipe' not specified"); + Objects.requireNonNull(ioutil, "Required parameter 'ioutil' not specified"); + Objects.requireNonNull(http, "Required parameter 'http' not specified"); + Objects.requireNonNull(url, "Required parameter 'url' not specified"); + Objects.requireNonNull(context, "Required parameter 'context' not specified"); + Objects.requireNonNull(allowEmpty, "Required parameter 'allowEmpty' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testQueryParameterCollectionFormatRequestBuilder(pipe, ioutil, http, url, context, allowEmpty, language); + return testQueryParameterCollectionFormatSubmit(webClientRequestBuilder, pipe, ioutil, http, url, context, allowEmpty, language); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testQueryParameterCollectionFormat operation. + * Optional customization point for subclasses. + * + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (required) + * @param allowEmpty (required) + * @param language (optional + * @return WebClientRequestBuilder for testQueryParameterCollectionFormat + */ + protected WebClientRequestBuilder testQueryParameterCollectionFormatRequestBuilder(List pipe, List ioutil, List http, List url, List context, String allowEmpty, Map language) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("PUT"); + + List queryParams = new ArrayList<>(); + queryParams.addAll(ApiClient.parameterToPairs("pipes", "pipe", pipe)); + queryParams.addAll(ApiClient.parameterToPairs("csv", "ioutil", ioutil)); + queryParams.addAll(ApiClient.parameterToPairs("ssv", "http", http)); + queryParams.addAll(ApiClient.parameterToPairs("csv", "url", url)); + queryParams.addAll(ApiClient.parameterToPairs("multi", "context", context)); + queryParams.addAll(ApiClient.parameterToPairs("language", language)); + queryParams.addAll(ApiClient.parameterToPairs("allowEmpty", allowEmpty)); + queryParams.forEach(p -> webClientRequestBuilder.queryParam(p.getName(), p.getValue())); + + webClientRequestBuilder.path("/fake/test-query-parameters"); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testQueryParameterCollectionFormat operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (required) + * @param allowEmpty (required) + * @param language (optional + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testQueryParameterCollectionFormatSubmit(WebClientRequestBuilder webClientRequestBuilder, List pipe, List ioutil, List http, List url, List context, String allowEmpty, Map language) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_testQueryParameterCollectionFormat, webClientResponse); + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java new file mode 100644 index 0000000000..83e7415b6f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -0,0 +1,35 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiResponse; +import org.openapitools.client.model.Client; +import java.util.List; +import java.util.Map; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public interface FakeClassnameTags123Api { + + /** + * To test class name in snake case + * To test class name in snake case + * @param client client model (required) + * @return {@code ApiResponse} + */ + ApiResponse testClassname(Client client); + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeClassnameTags123ApiImpl.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeClassnameTags123ApiImpl.java new file mode 100644 index 0000000000..7af86ce4c5 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeClassnameTags123ApiImpl.java @@ -0,0 +1,97 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.util.Objects; +import org.openapitools.client.ApiResponse; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.common.GenericType; +import io.helidon.common.http.MediaType; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.media.common.MediaSupport; + +import io.helidon.media.jackson.JacksonSupport; +import io.helidon.webclient.WebClientRequestBuilder; +import io.helidon.webclient.WebClientResponse; + +import org.openapitools.client.ApiClient; + +import org.openapitools.client.model.Client; +import java.util.List; +import java.util.Map; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public class FakeClassnameTags123ApiImpl implements FakeClassnameTags123Api { + + private final ApiClient apiClient; + + protected static final GenericType RESPONSE_TYPE_testClassname = ResponseType.create(Client.class); + + /** + * Creates a new instance of FakeClassnameTags123ApiImpl initialized with the specified {@link ApiClient}. + * + */ + public static FakeClassnameTags123ApiImpl create(ApiClient apiClient) { + return new FakeClassnameTags123ApiImpl(apiClient); + } + + protected FakeClassnameTags123ApiImpl(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @Override + public ApiResponse testClassname(Client client) { + Objects.requireNonNull(client, "Required parameter 'client' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testClassnameRequestBuilder(client); + return testClassnameSubmit(webClientRequestBuilder, client); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testClassname operation. + * Optional customization point for subclasses. + * + * @param client client model (required) + * @return WebClientRequestBuilder for testClassname + */ + protected WebClientRequestBuilder testClassnameRequestBuilder(Client client) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("PATCH"); + + webClientRequestBuilder.path("/fake_classname_test"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testClassname operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param client client model (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testClassnameSubmit(WebClientRequestBuilder webClientRequestBuilder, Client client) { + Single webClientResponse = webClientRequestBuilder.submit(client); + return ApiResponse.create(RESPONSE_TYPE_testClassname, webClientResponse); + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/PetApi.java new file mode 100644 index 0000000000..a333b19426 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/PetApi.java @@ -0,0 +1,111 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiResponse; +import java.io.File; +import java.util.List; +import java.util.Map; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; +import java.util.Set; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public interface PetApi { + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store (required) + * @return {@code ApiResponse} + */ + ApiResponse addPet(Pet pet); + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return {@code ApiResponse} + */ + ApiResponse deletePet(Long petId, String apiKey); + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return {@code ApiResponse>} + */ + ApiResponse> findPetsByStatus(List status); + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return {@code ApiResponse>} + * @deprecated + */ + @Deprecated + ApiResponse> findPetsByTags(Set tags); + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return {@code ApiResponse} + */ + ApiResponse getPetById(Long petId); + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store (required) + * @return {@code ApiResponse} + */ + ApiResponse updatePet(Pet pet); + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return {@code ApiResponse} + */ + ApiResponse updatePetWithForm(Long petId, String name, String status); + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (optional) + * @return {@code ApiResponse} + */ + ApiResponse uploadFile(Long petId, String additionalMetadata, File _file); + + /** + * uploads an image (required) + * + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @return {@code ApiResponse} + */ + ApiResponse uploadFileWithRequiredFile(Long petId, File requiredFile, String additionalMetadata); + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/PetApiImpl.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/PetApiImpl.java new file mode 100644 index 0000000000..00cefb142b --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/PetApiImpl.java @@ -0,0 +1,463 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.util.Objects; +import org.openapitools.client.ApiResponse; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.common.GenericType; +import io.helidon.common.http.MediaType; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.media.common.MediaSupport; + +import io.helidon.media.jackson.JacksonSupport; +import io.helidon.webclient.WebClientRequestBuilder; +import io.helidon.webclient.WebClientResponse; + +import org.openapitools.client.ApiClient; + +import java.io.File; +import java.util.List; +import java.util.Map; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; +import java.util.Set; +import java.util.ArrayList; +import org.openapitools.client.Pair; +import java.util.StringJoiner; +import io.helidon.webclient.WebClientRequestHeaders; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public class PetApiImpl implements PetApi { + + private final ApiClient apiClient; + + protected static final GenericType RESPONSE_TYPE_addPet = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_deletePet = ResponseType.create(Void.class); + protected static final GenericType> RESPONSE_TYPE_findPetsByStatus = ResponseType.create(List.class, Pet.class); + protected static final GenericType> RESPONSE_TYPE_findPetsByTags = ResponseType.create(List.class, Pet.class); + protected static final GenericType RESPONSE_TYPE_getPetById = ResponseType.create(Pet.class); + protected static final GenericType RESPONSE_TYPE_updatePet = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_updatePetWithForm = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_uploadFile = ResponseType.create(ModelApiResponse.class); + protected static final GenericType RESPONSE_TYPE_uploadFileWithRequiredFile = ResponseType.create(ModelApiResponse.class); + + /** + * Creates a new instance of PetApiImpl initialized with the specified {@link ApiClient}. + * + */ + public static PetApiImpl create(ApiClient apiClient) { + return new PetApiImpl(apiClient); + } + + protected PetApiImpl(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @Override + public ApiResponse addPet(Pet pet) { + Objects.requireNonNull(pet, "Required parameter 'pet' not specified"); + WebClientRequestBuilder webClientRequestBuilder = addPetRequestBuilder(pet); + return addPetSubmit(webClientRequestBuilder, pet); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the addPet operation. + * Optional customization point for subclasses. + * + * @param pet Pet object that needs to be added to the store (required) + * @return WebClientRequestBuilder for addPet + */ + protected WebClientRequestBuilder addPetRequestBuilder(Pet pet) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/pet"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the addPet operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param pet Pet object that needs to be added to the store (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse addPetSubmit(WebClientRequestBuilder webClientRequestBuilder, Pet pet) { + Single webClientResponse = webClientRequestBuilder.submit(pet); + return ApiResponse.create(RESPONSE_TYPE_addPet, webClientResponse); + } + + @Override + public ApiResponse deletePet(Long petId, String apiKey) { + Objects.requireNonNull(petId, "Required parameter 'petId' not specified"); + WebClientRequestBuilder webClientRequestBuilder = deletePetRequestBuilder(petId, apiKey); + return deletePetSubmit(webClientRequestBuilder, petId, apiKey); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the deletePet operation. + * Optional customization point for subclasses. + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return WebClientRequestBuilder for deletePet + */ + protected WebClientRequestBuilder deletePetRequestBuilder(Long petId, String apiKey) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("DELETE"); + + WebClientRequestHeaders headers = webClientRequestBuilder.headers(); + if (apiKey != null) { + headers.put("api_key", apiKey); + } + + String path = "/pet/{petId}" + .replace("{petId}", ApiClient.urlEncode(petId.toString())); + webClientRequestBuilder.path(path); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the deletePet operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse deletePetSubmit(WebClientRequestBuilder webClientRequestBuilder, Long petId, String apiKey) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_deletePet, webClientResponse); + } + + @Override + public ApiResponse> findPetsByStatus(List status) { + Objects.requireNonNull(status, "Required parameter 'status' not specified"); + WebClientRequestBuilder webClientRequestBuilder = findPetsByStatusRequestBuilder(status); + return findPetsByStatusSubmit(webClientRequestBuilder, status); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the findPetsByStatus operation. + * Optional customization point for subclasses. + * + * @param status Status values that need to be considered for filter (required) + * @return WebClientRequestBuilder for findPetsByStatus + */ + protected WebClientRequestBuilder findPetsByStatusRequestBuilder(List status) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + List queryParams = new ArrayList<>(); + queryParams.addAll(ApiClient.parameterToPairs("csv", "status", status)); + queryParams.forEach(p -> webClientRequestBuilder.queryParam(p.getName(), p.getValue())); + + webClientRequestBuilder.path("/pet/findByStatus"); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the findPetsByStatus operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param status Status values that need to be considered for filter (required) + * @return {@code ApiResponse>} for the submitted request + */ + protected ApiResponse> findPetsByStatusSubmit(WebClientRequestBuilder webClientRequestBuilder, List status) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_findPetsByStatus, webClientResponse); + } + + @Deprecated + @Override + public ApiResponse> findPetsByTags(Set tags) { + Objects.requireNonNull(tags, "Required parameter 'tags' not specified"); + WebClientRequestBuilder webClientRequestBuilder = findPetsByTagsRequestBuilder(tags); + return findPetsByTagsSubmit(webClientRequestBuilder, tags); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the findPetsByTags operation. + * Optional customization point for subclasses. + * + * @param tags Tags to filter by (required) + * @return WebClientRequestBuilder for findPetsByTags + */ + protected WebClientRequestBuilder findPetsByTagsRequestBuilder(Set tags) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + List queryParams = new ArrayList<>(); + queryParams.addAll(ApiClient.parameterToPairs("csv", "tags", tags)); + queryParams.forEach(p -> webClientRequestBuilder.queryParam(p.getName(), p.getValue())); + + webClientRequestBuilder.path("/pet/findByTags"); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the findPetsByTags operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param tags Tags to filter by (required) + * @return {@code ApiResponse>} for the submitted request + */ + protected ApiResponse> findPetsByTagsSubmit(WebClientRequestBuilder webClientRequestBuilder, Set tags) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_findPetsByTags, webClientResponse); + } + + @Override + public ApiResponse getPetById(Long petId) { + Objects.requireNonNull(petId, "Required parameter 'petId' not specified"); + WebClientRequestBuilder webClientRequestBuilder = getPetByIdRequestBuilder(petId); + return getPetByIdSubmit(webClientRequestBuilder, petId); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the getPetById operation. + * Optional customization point for subclasses. + * + * @param petId ID of pet to return (required) + * @return WebClientRequestBuilder for getPetById + */ + protected WebClientRequestBuilder getPetByIdRequestBuilder(Long petId) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + String path = "/pet/{petId}" + .replace("{petId}", ApiClient.urlEncode(petId.toString())); + webClientRequestBuilder.path(path); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the getPetById operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param petId ID of pet to return (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse getPetByIdSubmit(WebClientRequestBuilder webClientRequestBuilder, Long petId) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_getPetById, webClientResponse); + } + + @Override + public ApiResponse updatePet(Pet pet) { + Objects.requireNonNull(pet, "Required parameter 'pet' not specified"); + WebClientRequestBuilder webClientRequestBuilder = updatePetRequestBuilder(pet); + return updatePetSubmit(webClientRequestBuilder, pet); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the updatePet operation. + * Optional customization point for subclasses. + * + * @param pet Pet object that needs to be added to the store (required) + * @return WebClientRequestBuilder for updatePet + */ + protected WebClientRequestBuilder updatePetRequestBuilder(Pet pet) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("PUT"); + + webClientRequestBuilder.path("/pet"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the updatePet operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param pet Pet object that needs to be added to the store (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse updatePetSubmit(WebClientRequestBuilder webClientRequestBuilder, Pet pet) { + Single webClientResponse = webClientRequestBuilder.submit(pet); + return ApiResponse.create(RESPONSE_TYPE_updatePet, webClientResponse); + } + + @Override + public ApiResponse updatePetWithForm(Long petId, String name, String status) { + Objects.requireNonNull(petId, "Required parameter 'petId' not specified"); + WebClientRequestBuilder webClientRequestBuilder = updatePetWithFormRequestBuilder(petId, name, status); + return updatePetWithFormSubmit(webClientRequestBuilder, petId, name, status); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the updatePetWithForm operation. + * Optional customization point for subclasses. + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return WebClientRequestBuilder for updatePetWithForm + */ + protected WebClientRequestBuilder updatePetWithFormRequestBuilder(Long petId, String name, String status) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + String path = "/pet/{petId}" + .replace("{petId}", ApiClient.urlEncode(petId.toString())); + webClientRequestBuilder.path(path); + webClientRequestBuilder.contentType(MediaType.APPLICATION_FORM_URLENCODED); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the updatePetWithForm operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse updatePetWithFormSubmit(WebClientRequestBuilder webClientRequestBuilder, Long petId, String name, String status) { + String formParams = new StringJoiner("&") + .add("name=" + name) + .add("status=" + status) + .toString(); + Single webClientResponse = webClientRequestBuilder.submit(formParams); + return ApiResponse.create(RESPONSE_TYPE_updatePetWithForm, webClientResponse); + } + + @Override + public ApiResponse uploadFile(Long petId, String additionalMetadata, File _file) { + Objects.requireNonNull(petId, "Required parameter 'petId' not specified"); + WebClientRequestBuilder webClientRequestBuilder = uploadFileRequestBuilder(petId, additionalMetadata, _file); + return uploadFileSubmit(webClientRequestBuilder, petId, additionalMetadata, _file); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the uploadFile operation. + * Optional customization point for subclasses. + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (optional) + * @return WebClientRequestBuilder for uploadFile + */ + protected WebClientRequestBuilder uploadFileRequestBuilder(Long petId, String additionalMetadata, File _file) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + String path = "/pet/{petId}/uploadImage" + .replace("{petId}", ApiClient.urlEncode(petId.toString())); + webClientRequestBuilder.path(path); + webClientRequestBuilder.contentType(MediaType.APPLICATION_FORM_URLENCODED); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the uploadFile operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse uploadFileSubmit(WebClientRequestBuilder webClientRequestBuilder, Long petId, String additionalMetadata, File _file) { + String formParams = new StringJoiner("&") + .add("additionalMetadata=" + additionalMetadata) + .add("file=" + _file) + .toString(); + Single webClientResponse = webClientRequestBuilder.submit(formParams); + return ApiResponse.create(RESPONSE_TYPE_uploadFile, webClientResponse); + } + + @Override + public ApiResponse uploadFileWithRequiredFile(Long petId, File requiredFile, String additionalMetadata) { + Objects.requireNonNull(petId, "Required parameter 'petId' not specified"); + Objects.requireNonNull(requiredFile, "Required parameter 'requiredFile' not specified"); + WebClientRequestBuilder webClientRequestBuilder = uploadFileWithRequiredFileRequestBuilder(petId, requiredFile, additionalMetadata); + return uploadFileWithRequiredFileSubmit(webClientRequestBuilder, petId, requiredFile, additionalMetadata); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the uploadFileWithRequiredFile operation. + * Optional customization point for subclasses. + * + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @return WebClientRequestBuilder for uploadFileWithRequiredFile + */ + protected WebClientRequestBuilder uploadFileWithRequiredFileRequestBuilder(Long petId, File requiredFile, String additionalMetadata) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + String path = "/fake/{petId}/uploadImageWithRequiredFile" + .replace("{petId}", ApiClient.urlEncode(petId.toString())); + webClientRequestBuilder.path(path); + webClientRequestBuilder.contentType(MediaType.APPLICATION_FORM_URLENCODED); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the uploadFileWithRequiredFile operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse uploadFileWithRequiredFileSubmit(WebClientRequestBuilder webClientRequestBuilder, Long petId, File requiredFile, String additionalMetadata) { + String formParams = new StringJoiner("&") + .add("additionalMetadata=" + additionalMetadata) + .add("requiredFile=" + requiredFile) + .toString(); + Single webClientResponse = webClientRequestBuilder.submit(formParams); + return ApiResponse.create(RESPONSE_TYPE_uploadFileWithRequiredFile, webClientResponse); + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/ResponseType.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/ResponseType.java new file mode 100644 index 0000000000..74f7f4d9a8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/ResponseType.java @@ -0,0 +1,43 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import io.helidon.common.GenericType; + +class ResponseType { + + static GenericType create(Type rawType, Type... typeParams) { + return typeParams.length == 0 + ? GenericType.create(rawType) + : GenericType.create(new ParameterizedType() { + + @Override + public Type[] getActualTypeArguments() { + return typeParams; + } + + @Override + public Type getRawType() { + return rawType; + } + + @Override + public Type getOwnerType() { + return null; + } + }); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/StoreApi.java new file mode 100644 index 0000000000..b7ad3ea6e8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/StoreApi.java @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiResponse; +import java.util.List; +import java.util.Map; +import org.openapitools.client.model.Order; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public interface StoreApi { + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return {@code ApiResponse} + */ + ApiResponse deleteOrder(String orderId); + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return {@code ApiResponse>} + */ + ApiResponse> getInventory(); + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return {@code ApiResponse} + */ + ApiResponse getOrderById(Long orderId); + + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet (required) + * @return {@code ApiResponse} + */ + ApiResponse placeOrder(Order order); + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/StoreApiImpl.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/StoreApiImpl.java new file mode 100644 index 0000000000..2b039dd7ba --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/StoreApiImpl.java @@ -0,0 +1,212 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.util.Objects; +import org.openapitools.client.ApiResponse; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.common.GenericType; +import io.helidon.common.http.MediaType; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.media.common.MediaSupport; + +import io.helidon.media.jackson.JacksonSupport; +import io.helidon.webclient.WebClientRequestBuilder; +import io.helidon.webclient.WebClientResponse; + +import org.openapitools.client.ApiClient; + +import java.util.List; +import java.util.Map; +import org.openapitools.client.model.Order; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public class StoreApiImpl implements StoreApi { + + private final ApiClient apiClient; + + protected static final GenericType RESPONSE_TYPE_deleteOrder = ResponseType.create(Void.class); + protected static final GenericType> RESPONSE_TYPE_getInventory = ResponseType.create(Map.class, String.class, Integer.class); + protected static final GenericType RESPONSE_TYPE_getOrderById = ResponseType.create(Order.class); + protected static final GenericType RESPONSE_TYPE_placeOrder = ResponseType.create(Order.class); + + /** + * Creates a new instance of StoreApiImpl initialized with the specified {@link ApiClient}. + * + */ + public static StoreApiImpl create(ApiClient apiClient) { + return new StoreApiImpl(apiClient); + } + + protected StoreApiImpl(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @Override + public ApiResponse deleteOrder(String orderId) { + Objects.requireNonNull(orderId, "Required parameter 'orderId' not specified"); + WebClientRequestBuilder webClientRequestBuilder = deleteOrderRequestBuilder(orderId); + return deleteOrderSubmit(webClientRequestBuilder, orderId); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the deleteOrder operation. + * Optional customization point for subclasses. + * + * @param orderId ID of the order that needs to be deleted (required) + * @return WebClientRequestBuilder for deleteOrder + */ + protected WebClientRequestBuilder deleteOrderRequestBuilder(String orderId) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("DELETE"); + + String path = "/store/order/{order_id}" + .replace("{order_id}", ApiClient.urlEncode(orderId)); + webClientRequestBuilder.path(path); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the deleteOrder operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param orderId ID of the order that needs to be deleted (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse deleteOrderSubmit(WebClientRequestBuilder webClientRequestBuilder, String orderId) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_deleteOrder, webClientResponse); + } + + @Override + public ApiResponse> getInventory() { + WebClientRequestBuilder webClientRequestBuilder = getInventoryRequestBuilder(); + return getInventorySubmit(webClientRequestBuilder); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the getInventory operation. + * Optional customization point for subclasses. + * + * @return WebClientRequestBuilder for getInventory + */ + protected WebClientRequestBuilder getInventoryRequestBuilder() { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + webClientRequestBuilder.path("/store/inventory"); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the getInventory operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @return {@code ApiResponse>} for the submitted request + */ + protected ApiResponse> getInventorySubmit(WebClientRequestBuilder webClientRequestBuilder) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_getInventory, webClientResponse); + } + + @Override + public ApiResponse getOrderById(Long orderId) { + Objects.requireNonNull(orderId, "Required parameter 'orderId' not specified"); + WebClientRequestBuilder webClientRequestBuilder = getOrderByIdRequestBuilder(orderId); + return getOrderByIdSubmit(webClientRequestBuilder, orderId); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the getOrderById operation. + * Optional customization point for subclasses. + * + * @param orderId ID of pet that needs to be fetched (required) + * @return WebClientRequestBuilder for getOrderById + */ + protected WebClientRequestBuilder getOrderByIdRequestBuilder(Long orderId) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + String path = "/store/order/{order_id}" + .replace("{order_id}", ApiClient.urlEncode(orderId.toString())); + webClientRequestBuilder.path(path); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the getOrderById operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param orderId ID of pet that needs to be fetched (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse getOrderByIdSubmit(WebClientRequestBuilder webClientRequestBuilder, Long orderId) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_getOrderById, webClientResponse); + } + + @Override + public ApiResponse placeOrder(Order order) { + Objects.requireNonNull(order, "Required parameter 'order' not specified"); + WebClientRequestBuilder webClientRequestBuilder = placeOrderRequestBuilder(order); + return placeOrderSubmit(webClientRequestBuilder, order); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the placeOrder operation. + * Optional customization point for subclasses. + * + * @param order order placed for purchasing the pet (required) + * @return WebClientRequestBuilder for placeOrder + */ + protected WebClientRequestBuilder placeOrderRequestBuilder(Order order) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/store/order"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the placeOrder operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param order order placed for purchasing the pet (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse placeOrderSubmit(WebClientRequestBuilder webClientRequestBuilder, Order order) { + Single webClientResponse = webClientRequestBuilder.submit(order); + return ApiResponse.create(RESPONSE_TYPE_placeOrder, webClientResponse); + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/UserApi.java new file mode 100644 index 0000000000..b8f4c06564 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/UserApi.java @@ -0,0 +1,93 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.ApiResponse; +import java.util.List; +import java.util.Map; +import java.time.OffsetDateTime; +import org.openapitools.client.model.User; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public interface UserApi { + + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object (required) + * @return {@code ApiResponse} + */ + ApiResponse createUser(User user); + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @return {@code ApiResponse} + */ + ApiResponse createUsersWithArrayInput(List user); + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @return {@code ApiResponse} + */ + ApiResponse createUsersWithListInput(List user); + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return {@code ApiResponse} + */ + ApiResponse deleteUser(String username); + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return {@code ApiResponse} + */ + ApiResponse getUserByName(String username); + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return {@code ApiResponse} + */ + ApiResponse loginUser(String username, String password); + + /** + * Logs out current logged in user session + * + * @return {@code ApiResponse} + */ + ApiResponse logoutUser(); + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @return {@code ApiResponse} + */ + ApiResponse updateUser(String username, User user); + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/UserApiImpl.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/UserApiImpl.java new file mode 100644 index 0000000000..0b51b0eb02 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/UserApiImpl.java @@ -0,0 +1,383 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.util.Objects; +import org.openapitools.client.ApiResponse; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.common.GenericType; +import io.helidon.common.http.MediaType; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.media.common.MediaSupport; + +import io.helidon.media.jackson.JacksonSupport; +import io.helidon.webclient.WebClientRequestBuilder; +import io.helidon.webclient.WebClientResponse; + +import org.openapitools.client.ApiClient; + +import java.util.List; +import java.util.Map; +import java.time.OffsetDateTime; +import org.openapitools.client.model.User; +import java.util.ArrayList; +import org.openapitools.client.Pair; + +/** + * OpenAPI Petstore + * + *

        This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + */ +public class UserApiImpl implements UserApi { + + private final ApiClient apiClient; + + protected static final GenericType RESPONSE_TYPE_createUser = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_createUsersWithArrayInput = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_createUsersWithListInput = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_deleteUser = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_getUserByName = ResponseType.create(User.class); + protected static final GenericType RESPONSE_TYPE_loginUser = ResponseType.create(String.class); + protected static final GenericType RESPONSE_TYPE_logoutUser = ResponseType.create(Void.class); + protected static final GenericType RESPONSE_TYPE_updateUser = ResponseType.create(Void.class); + + /** + * Creates a new instance of UserApiImpl initialized with the specified {@link ApiClient}. + * + */ + public static UserApiImpl create(ApiClient apiClient) { + return new UserApiImpl(apiClient); + } + + protected UserApiImpl(ApiClient apiClient) { + this.apiClient = apiClient; + } + + @Override + public ApiResponse createUser(User user) { + Objects.requireNonNull(user, "Required parameter 'user' not specified"); + WebClientRequestBuilder webClientRequestBuilder = createUserRequestBuilder(user); + return createUserSubmit(webClientRequestBuilder, user); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the createUser operation. + * Optional customization point for subclasses. + * + * @param user Created user object (required) + * @return WebClientRequestBuilder for createUser + */ + protected WebClientRequestBuilder createUserRequestBuilder(User user) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/user"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the createUser operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param user Created user object (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse createUserSubmit(WebClientRequestBuilder webClientRequestBuilder, User user) { + Single webClientResponse = webClientRequestBuilder.submit(user); + return ApiResponse.create(RESPONSE_TYPE_createUser, webClientResponse); + } + + @Override + public ApiResponse createUsersWithArrayInput(List user) { + Objects.requireNonNull(user, "Required parameter 'user' not specified"); + WebClientRequestBuilder webClientRequestBuilder = createUsersWithArrayInputRequestBuilder(user); + return createUsersWithArrayInputSubmit(webClientRequestBuilder, user); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the createUsersWithArrayInput operation. + * Optional customization point for subclasses. + * + * @param user List of user object (required) + * @return WebClientRequestBuilder for createUsersWithArrayInput + */ + protected WebClientRequestBuilder createUsersWithArrayInputRequestBuilder(List user) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/user/createWithArray"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the createUsersWithArrayInput operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param user List of user object (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse createUsersWithArrayInputSubmit(WebClientRequestBuilder webClientRequestBuilder, List user) { + Single webClientResponse = webClientRequestBuilder.submit(user); + return ApiResponse.create(RESPONSE_TYPE_createUsersWithArrayInput, webClientResponse); + } + + @Override + public ApiResponse createUsersWithListInput(List user) { + Objects.requireNonNull(user, "Required parameter 'user' not specified"); + WebClientRequestBuilder webClientRequestBuilder = createUsersWithListInputRequestBuilder(user); + return createUsersWithListInputSubmit(webClientRequestBuilder, user); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the createUsersWithListInput operation. + * Optional customization point for subclasses. + * + * @param user List of user object (required) + * @return WebClientRequestBuilder for createUsersWithListInput + */ + protected WebClientRequestBuilder createUsersWithListInputRequestBuilder(List user) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/user/createWithList"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the createUsersWithListInput operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param user List of user object (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse createUsersWithListInputSubmit(WebClientRequestBuilder webClientRequestBuilder, List user) { + Single webClientResponse = webClientRequestBuilder.submit(user); + return ApiResponse.create(RESPONSE_TYPE_createUsersWithListInput, webClientResponse); + } + + @Override + public ApiResponse deleteUser(String username) { + Objects.requireNonNull(username, "Required parameter 'username' not specified"); + WebClientRequestBuilder webClientRequestBuilder = deleteUserRequestBuilder(username); + return deleteUserSubmit(webClientRequestBuilder, username); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the deleteUser operation. + * Optional customization point for subclasses. + * + * @param username The name that needs to be deleted (required) + * @return WebClientRequestBuilder for deleteUser + */ + protected WebClientRequestBuilder deleteUserRequestBuilder(String username) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("DELETE"); + + String path = "/user/{username}" + .replace("{username}", ApiClient.urlEncode(username)); + webClientRequestBuilder.path(path); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the deleteUser operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param username The name that needs to be deleted (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse deleteUserSubmit(WebClientRequestBuilder webClientRequestBuilder, String username) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_deleteUser, webClientResponse); + } + + @Override + public ApiResponse getUserByName(String username) { + Objects.requireNonNull(username, "Required parameter 'username' not specified"); + WebClientRequestBuilder webClientRequestBuilder = getUserByNameRequestBuilder(username); + return getUserByNameSubmit(webClientRequestBuilder, username); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the getUserByName operation. + * Optional customization point for subclasses. + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return WebClientRequestBuilder for getUserByName + */ + protected WebClientRequestBuilder getUserByNameRequestBuilder(String username) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + String path = "/user/{username}" + .replace("{username}", ApiClient.urlEncode(username)); + webClientRequestBuilder.path(path); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the getUserByName operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse getUserByNameSubmit(WebClientRequestBuilder webClientRequestBuilder, String username) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_getUserByName, webClientResponse); + } + + @Override + public ApiResponse loginUser(String username, String password) { + Objects.requireNonNull(username, "Required parameter 'username' not specified"); + Objects.requireNonNull(password, "Required parameter 'password' not specified"); + WebClientRequestBuilder webClientRequestBuilder = loginUserRequestBuilder(username, password); + return loginUserSubmit(webClientRequestBuilder, username, password); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the loginUser operation. + * Optional customization point for subclasses. + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return WebClientRequestBuilder for loginUser + */ + protected WebClientRequestBuilder loginUserRequestBuilder(String username, String password) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + List queryParams = new ArrayList<>(); + queryParams.addAll(ApiClient.parameterToPairs("username", username)); + queryParams.addAll(ApiClient.parameterToPairs("password", password)); + queryParams.forEach(p -> webClientRequestBuilder.queryParam(p.getName(), p.getValue())); + + webClientRequestBuilder.path("/user/login"); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the loginUser operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse loginUserSubmit(WebClientRequestBuilder webClientRequestBuilder, String username, String password) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_loginUser, webClientResponse); + } + + @Override + public ApiResponse logoutUser() { + WebClientRequestBuilder webClientRequestBuilder = logoutUserRequestBuilder(); + return logoutUserSubmit(webClientRequestBuilder); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the logoutUser operation. + * Optional customization point for subclasses. + * + * @return WebClientRequestBuilder for logoutUser + */ + protected WebClientRequestBuilder logoutUserRequestBuilder() { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("GET"); + + webClientRequestBuilder.path("/user/logout"); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the logoutUser operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse logoutUserSubmit(WebClientRequestBuilder webClientRequestBuilder) { + Single webClientResponse = webClientRequestBuilder.submit(); + return ApiResponse.create(RESPONSE_TYPE_logoutUser, webClientResponse); + } + + @Override + public ApiResponse updateUser(String username, User user) { + Objects.requireNonNull(username, "Required parameter 'username' not specified"); + Objects.requireNonNull(user, "Required parameter 'user' not specified"); + WebClientRequestBuilder webClientRequestBuilder = updateUserRequestBuilder(username, user); + return updateUserSubmit(webClientRequestBuilder, username, user); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the updateUser operation. + * Optional customization point for subclasses. + * + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @return WebClientRequestBuilder for updateUser + */ + protected WebClientRequestBuilder updateUserRequestBuilder(String username, User user) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("PUT"); + + String path = "/user/{username}" + .replace("{username}", ApiClient.urlEncode(username)); + webClientRequestBuilder.path(path); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the updateUser operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse updateUserSubmit(WebClientRequestBuilder webClientRequestBuilder, String username, User user) { + Single webClientResponse = webClientRequestBuilder.submit(user); + return ApiResponse.create(RESPONSE_TYPE_updateUser, webClientResponse); + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java new file mode 100644 index 0000000000..abc3d296fa --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,108 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; + + + + +public class AdditionalPropertiesClass { + + private Map mapProperty = null; + + private Map> mapOfMapProperty = null; + + /** + * Get mapProperty + * @return mapProperty + **/ + public Map getMapProperty() { + return mapProperty; + } + + /** + * Set mapProperty + **/ + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + /** + * Set mapOfMapProperty + **/ + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java new file mode 100644 index 0000000000..cb7b8b0a68 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java @@ -0,0 +1,97 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.SingleRefType; + + + + +public class AllOfWithSingleRef { + + private String username; + + private SingleRefType singleRefType; + + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + + /** + * Set username + **/ + public void setUsername(String username) { + this.username = username; + } + + public AllOfWithSingleRef username(String username) { + this.username = username; + return this; + } + + /** + * Get singleRefType + * @return singleRefType + **/ + public SingleRefType getSingleRefType() { + return singleRefType; + } + + /** + * Set singleRefType + **/ + public void setSingleRefType(SingleRefType singleRefType) { + this.singleRefType = singleRefType; + } + + public AllOfWithSingleRef singleRefType(SingleRefType singleRefType) { + this.singleRefType = singleRefType; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfWithSingleRef {\n"); + + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" singleRefType: ").append(toIndentedString(singleRefType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Animal.java new file mode 100644 index 0000000000..36ecf9c54f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Animal.java @@ -0,0 +1,101 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Cat; +import org.openapitools.client.model.Dog; + + + + +public class Animal { + + private String className; + + private String color = "red"; + + /** + * Get className + * @return className + **/ + public String getClassName() { + return className; + } + + /** + * Set className + **/ + public void setClassName(String className) { + this.className = className; + } + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get color + * @return color + **/ + public String getColor() { + return color; + } + + /** + * Set color + **/ + public void setColor(String color) { + this.color = color; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 0000000000..d451b999d8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,81 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + +public class ArrayOfArrayOfNumberOnly { + + private List> arrayArrayNumber = null; + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + /** + * Set arrayArrayNumber + **/ + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java new file mode 100644 index 0000000000..3b64bf9e87 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,81 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + + +public class ArrayOfNumberOnly { + + private List arrayNumber = null; + + /** + * Get arrayNumber + * @return arrayNumber + **/ + public List getArrayNumber() { + return arrayNumber; + } + + /** + * Set arrayNumber + **/ + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ArrayTest.java new file mode 100644 index 0000000000..ab1f6d1791 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -0,0 +1,137 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ReadOnlyFirst; + + + + +public class ArrayTest { + + private List arrayOfString = null; + + private List> arrayArrayOfInteger = null; + + private List> arrayArrayOfModel = null; + + /** + * Get arrayOfString + * @return arrayOfString + **/ + public List getArrayOfString() { + return arrayOfString; + } + + /** + * Set arrayOfString + **/ + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + /** + * Set arrayArrayOfInteger + **/ + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + /** + * Set arrayArrayOfModel + **/ + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Capitalization.java new file mode 100644 index 0000000000..f6d3fde93d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Capitalization.java @@ -0,0 +1,191 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Capitalization { + + private String smallCamel; + + private String capitalCamel; + + private String smallSnake; + + private String capitalSnake; + + private String scAETHFlowPoints; + + /** + * Name of the pet + **/ + private String ATT_NAME; + + /** + * Get smallCamel + * @return smallCamel + **/ + public String getSmallCamel() { + return smallCamel; + } + + /** + * Set smallCamel + **/ + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + public String getCapitalCamel() { + return capitalCamel; + } + + /** + * Set capitalCamel + **/ + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + public String getSmallSnake() { + return smallSnake; + } + + /** + * Set smallSnake + **/ + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + public String getCapitalSnake() { + return capitalSnake; + } + + /** + * Set capitalSnake + **/ + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + /** + * Set scAETHFlowPoints + **/ + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + public String getATTNAME() { + return ATT_NAME; + } + + /** + * Set ATT_NAME + **/ + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Cat.java new file mode 100644 index 0000000000..be9c695456 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Cat.java @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Animal; + + + + +public class Cat extends Animal { + + private Boolean declawed; + + /** + * Get declawed + * @return declawed + **/ + public Boolean getDeclawed() { + return declawed; + } + + /** + * Set declawed + **/ + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/CatAllOf.java new file mode 100644 index 0000000000..2b54aad5ba --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class CatAllOf { + + private Boolean declawed; + + /** + * Get declawed + * @return declawed + **/ + public Boolean getDeclawed() { + return declawed; + } + + /** + * Set declawed + **/ + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + public CatAllOf declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CatAllOf {\n"); + + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Category.java new file mode 100644 index 0000000000..8da9901110 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Category.java @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Category { + + private Long id; + + private String name = "default-name"; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Category name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ClassModel.java new file mode 100644 index 0000000000..de44db959b --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ClassModel.java @@ -0,0 +1,76 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Model for testing model with \"_class\" property + **/ + +public class ClassModel { + + private String propertyClass; + + /** + * Get propertyClass + * @return propertyClass + **/ + public String getPropertyClass() { + return propertyClass; + } + + /** + * Set propertyClass + **/ + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Client.java new file mode 100644 index 0000000000..0ad715df8d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Client.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Client { + + private String client; + + /** + * Get client + * @return client + **/ + public String getClient() { + return client; + } + + /** + * Set client + **/ + public void setClient(String client) { + this.client = client; + } + + public Client client(String client) { + this.client = client; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/DeprecatedObject.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/DeprecatedObject.java new file mode 100644 index 0000000000..aaaed8e7f3 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/DeprecatedObject.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class DeprecatedObject { + + private String name; + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public DeprecatedObject name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeprecatedObject {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Dog.java new file mode 100644 index 0000000000..069dab8392 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Dog.java @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Animal; + + + + +public class Dog extends Animal { + + private String breed; + + /** + * Get breed + * @return breed + **/ + public String getBreed() { + return breed; + } + + /** + * Set breed + **/ + public void setBreed(String breed) { + this.breed = breed; + } + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/DogAllOf.java new file mode 100644 index 0000000000..5dc63ce038 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class DogAllOf { + + private String breed; + + /** + * Get breed + * @return breed + **/ + public String getBreed() { + return breed; + } + + /** + * Set breed + **/ + public void setBreed(String breed) { + this.breed = breed; + } + + public DogAllOf breed(String breed) { + this.breed = breed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DogAllOf {\n"); + + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/EnumArrays.java new file mode 100644 index 0000000000..1a9c48c72c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -0,0 +1,145 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; + + + + +public class EnumArrays { + +public enum JustSymbolEnum { + + GREATER_THAN_OR_EQUAL_TO(String.valueOf(">=")), DOLLAR(String.valueOf("$")); + + String value; + + JustSymbolEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private JustSymbolEnum justSymbol; + +public enum ArrayEnumEnum { + + FISH(String.valueOf("fish")), CRAB(String.valueOf("crab")); + + String value; + + ArrayEnumEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private List arrayEnum = null; + + /** + * Get justSymbol + * @return justSymbol + **/ + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + /** + * Set justSymbol + **/ + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + public List getArrayEnum() { + return arrayEnum; + } + + /** + * Set arrayEnum + **/ + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/EnumClass.java new file mode 100644 index 0000000000..eed52272f7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/EnumClass.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/EnumTest.java new file mode 100644 index 0000000000..e234097abc --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/EnumTest.java @@ -0,0 +1,326 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.OuterEnumDefaultValue; +import org.openapitools.client.model.OuterEnumInteger; +import org.openapitools.client.model.OuterEnumIntegerDefaultValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + + + + +public class EnumTest { + +public enum EnumStringEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); + + String value; + + EnumStringEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private EnumStringEnum enumString; + +public enum EnumStringRequiredEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); + + String value; + + EnumStringRequiredEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private EnumStringRequiredEnum enumStringRequired; + +public enum EnumIntegerEnum { + + NUMBER_1(Integer.valueOf(1)), NUMBER_MINUS_1(Integer.valueOf(-1)); + + Integer value; + + EnumIntegerEnum (Integer v) { + value = v; + } + + public Integer value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private EnumIntegerEnum enumInteger; + +public enum EnumNumberEnum { + + NUMBER_1_DOT_1(Double.valueOf(1.1)), NUMBER_MINUS_1_DOT_2(Double.valueOf(-1.2)); + + Double value; + + EnumNumberEnum (Double v) { + value = v; + } + + public Double value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private EnumNumberEnum enumNumber; + + private OuterEnum outerEnum; + + private OuterEnumInteger outerEnumInteger; + + private OuterEnumDefaultValue outerEnumDefaultValue = OuterEnumDefaultValue.PLACED; + + private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; + + /** + * Get enumString + * @return enumString + **/ + public EnumStringEnum getEnumString() { + return enumString; + } + + /** + * Set enumString + **/ + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumStringRequired + * @return enumStringRequired + **/ + public EnumStringRequiredEnum getEnumStringRequired() { + return enumStringRequired; + } + + /** + * Set enumStringRequired + **/ + public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + } + + public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + /** + * Set enumInteger + **/ + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + /** + * Set enumNumber + **/ + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + public OuterEnum getOuterEnum() { + return outerEnum; + } + + /** + * Set outerEnum + **/ + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnumInteger + * @return outerEnumInteger + **/ + public OuterEnumInteger getOuterEnumInteger() { + return outerEnumInteger; + } + + /** + * Set outerEnumInteger + **/ + public void setOuterEnumInteger(OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + } + + public EnumTest outerEnumInteger(OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + return this; + } + + /** + * Get outerEnumDefaultValue + * @return outerEnumDefaultValue + **/ + public OuterEnumDefaultValue getOuterEnumDefaultValue() { + return outerEnumDefaultValue; + } + + /** + * Set outerEnumDefaultValue + **/ + public void setOuterEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + } + + public EnumTest outerEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + return this; + } + + /** + * Get outerEnumIntegerDefaultValue + * @return outerEnumIntegerDefaultValue + **/ + public OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() { + return outerEnumIntegerDefaultValue; + } + + /** + * Set outerEnumIntegerDefaultValue + **/ + public void setOuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + } + + public EnumTest outerEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumStringRequired: ").append(toIndentedString(enumStringRequired)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append(" outerEnumInteger: ").append(toIndentedString(outerEnumInteger)).append("\n"); + sb.append(" outerEnumDefaultValue: ").append(toIndentedString(outerEnumDefaultValue)).append("\n"); + sb.append(" outerEnumIntegerDefaultValue: ").append(toIndentedString(outerEnumIntegerDefaultValue)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java new file mode 100644 index 0000000000..dd3716a2b1 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -0,0 +1,104 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ModelFile; + + + + +public class FileSchemaTestClass { + + private ModelFile _file; + + private List files = null; + + /** + * Get _file + * @return _file + **/ + public ModelFile getFile() { + return _file; + } + + /** + * Set _file + **/ + public void setFile(ModelFile _file) { + this._file = _file; + } + + public FileSchemaTestClass _file(ModelFile _file) { + this._file = _file; + return this; + } + + /** + * Get files + * @return files + **/ + public List getFiles() { + return files; + } + + /** + * Set files + **/ + public void setFiles(List files) { + this.files = files; + } + + public FileSchemaTestClass files(List files) { + this.files = files; + return this; + } + + public FileSchemaTestClass addFilesItem(ModelFile filesItem) { + this.files.add(filesItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FileSchemaTestClass {\n"); + + sb.append(" _file: ").append(toIndentedString(_file)).append("\n"); + sb.append(" files: ").append(toIndentedString(files)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Foo.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Foo.java new file mode 100644 index 0000000000..fcafaf7682 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Foo.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Foo { + + private String bar = "bar"; + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + /** + * Set bar + **/ + public void setBar(String bar) { + this.bar = bar; + } + + public Foo bar(String bar) { + this.bar = bar; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Foo {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java new file mode 100644 index 0000000000..27971dae91 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Foo; + + + + +public class FooGetDefaultResponse { + + private Foo string; + + /** + * Get string + * @return string + **/ + public Foo getString() { + return string; + } + + /** + * Set string + **/ + public void setString(Foo string) { + this.string = string; + } + + public FooGetDefaultResponse string(Foo string) { + this.string = string; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FooGetDefaultResponse {\n"); + + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FormatTest.java new file mode 100644 index 0000000000..6f6b62d497 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FormatTest.java @@ -0,0 +1,439 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; + + + + +public class FormatTest { + + private Integer integer; + + private Integer int32; + + private Long int64; + + private BigDecimal number; + + private Float _float; + + private Double _double; + + private BigDecimal decimal; + + private String string; + + private byte[] _byte; + + private File binary; + + private LocalDate date; + + private OffsetDateTime dateTime; + + private UUID uuid; + + private String password; + + /** + * A string that is a 10 digit number. Can have leading zeros. + **/ + private String patternWithDigits; + + /** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + **/ + private String patternWithDigitsAndDelimiter; + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + public Integer getInteger() { + return integer; + } + + /** + * Set integer + **/ + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + public Integer getInt32() { + return int32; + } + + /** + * Set int32 + **/ + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + public Long getInt64() { + return int64; + } + + /** + * Set int64 + **/ + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + public BigDecimal getNumber() { + return number; + } + + /** + * Set number + **/ + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + public Float getFloat() { + return _float; + } + + /** + * Set _float + **/ + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + public Double getDouble() { + return _double; + } + + /** + * Set _double + **/ + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get decimal + * @return decimal + **/ + public BigDecimal getDecimal() { + return decimal; + } + + /** + * Set decimal + **/ + public void setDecimal(BigDecimal decimal) { + this.decimal = decimal; + } + + public FormatTest decimal(BigDecimal decimal) { + this.decimal = decimal; + return this; + } + + /** + * Get string + * @return string + **/ + public String getString() { + return string; + } + + /** + * Set string + **/ + public void setString(String string) { + this.string = string; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + public byte[] getByte() { + return _byte; + } + + /** + * Set _byte + **/ + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get binary + * @return binary + **/ + public File getBinary() { + return binary; + } + + /** + * Set binary + **/ + public void setBinary(File binary) { + this.binary = binary; + } + + public FormatTest binary(File binary) { + this.binary = binary; + return this; + } + + /** + * Get date + * @return date + **/ + public LocalDate getDate() { + return date; + } + + /** + * Set date + **/ + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + public OffsetDateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + **/ + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + public UUID getUuid() { + return uuid; + } + + /** + * Set uuid + **/ + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get password + * @return password + **/ + public String getPassword() { + return password; + } + + /** + * Set password + **/ + public void setPassword(String password) { + this.password = password; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * A string that is a 10 digit number. Can have leading zeros. + * @return patternWithDigits + **/ + public String getPatternWithDigits() { + return patternWithDigits; + } + + /** + * Set patternWithDigits + **/ + public void setPatternWithDigits(String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + } + + public FormatTest patternWithDigits(String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + return this; + } + + /** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + * @return patternWithDigitsAndDelimiter + **/ + public String getPatternWithDigitsAndDelimiter() { + return patternWithDigitsAndDelimiter; + } + + /** + * Set patternWithDigitsAndDelimiter + **/ + public void setPatternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + } + + public FormatTest patternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" decimal: ").append(toIndentedString(decimal)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); + sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java new file mode 100644 index 0000000000..72566c02dd --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class HasOnlyReadOnly { + + private String bar; + + private String foo; + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + + /** + * Get foo + * @return foo + **/ + public String getFoo() { + return foo; + } + + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/HealthCheckResult.java new file mode 100644 index 0000000000..48cec9f2da --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -0,0 +1,80 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + + + +/** + * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + **/ + +public class HealthCheckResult { + + private String nullableMessage; + + /** + * Get nullableMessage + * @return nullableMessage + **/ + public String getNullableMessage() { + return nullableMessage; + } + + /** + * Set nullableMessage + **/ + public void setNullableMessage(String nullableMessage) { + this.nullableMessage = nullableMessage; + } + + public HealthCheckResult nullableMessage(String nullableMessage) { + this.nullableMessage = nullableMessage; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HealthCheckResult {\n"); + + sb.append(" nullableMessage: ").append(toIndentedString(nullableMessage)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/MapTest.java new file mode 100644 index 0000000000..ec54a8ae42 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/MapTest.java @@ -0,0 +1,185 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; + + + + +public class MapTest { + + private Map> mapMapOfString = null; + +public enum InnerEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")); + + String value; + + InnerEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + private Map mapOfEnumString = null; + + private Map directMap = null; + + private Map indirectMap = null; + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + public Map> getMapMapOfString() { + return mapMapOfString; + } + + /** + * Set mapMapOfString + **/ + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + /** + * Set mapOfEnumString + **/ + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get directMap + * @return directMap + **/ + public Map getDirectMap() { + return directMap; + } + + /** + * Set directMap + **/ + public void setDirectMap(Map directMap) { + this.directMap = directMap; + } + + public MapTest directMap(Map directMap) { + this.directMap = directMap; + return this; + } + + public MapTest putDirectMapItem(String key, Boolean directMapItem) { + this.directMap.put(key, directMapItem); + return this; + } + + /** + * Get indirectMap + * @return indirectMap + **/ + public Map getIndirectMap() { + return indirectMap; + } + + /** + * Set indirectMap + **/ + public void setIndirectMap(Map indirectMap) { + this.indirectMap = indirectMap; + } + + public MapTest indirectMap(Map indirectMap) { + this.indirectMap = indirectMap; + return this; + } + + public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { + this.indirectMap.put(key, indirectMapItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append(" directMap: ").append(toIndentedString(directMap)).append("\n"); + sb.append(" indirectMap: ").append(toIndentedString(indirectMap)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 0000000000..de307d1e28 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,129 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.openapitools.client.model.Animal; + + + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private UUID uuid; + + private OffsetDateTime dateTime; + + private Map map = null; + + /** + * Get uuid + * @return uuid + **/ + public UUID getUuid() { + return uuid; + } + + /** + * Set uuid + **/ + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + public OffsetDateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + **/ + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get map + * @return map + **/ + public Map getMap() { + return map; + } + + /** + * Set map + **/ + public void setMap(Map map) { + this.map = map; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Model200Response.java new file mode 100644 index 0000000000..393f65f83e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Model200Response.java @@ -0,0 +1,99 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Model for testing model name starting with number + **/ + +public class Model200Response { + + private Integer name; + + private String propertyClass; + + /** + * Get name + * @return name + **/ + public Integer getName() { + return name; + } + + /** + * Set name + **/ + public void setName(Integer name) { + this.name = name; + } + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + public String getPropertyClass() { + return propertyClass; + } + + /** + * Set propertyClass + **/ + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelApiResponse.java new file mode 100644 index 0000000000..881fc2677d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -0,0 +1,119 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class ModelApiResponse { + + private Integer code; + + private String type; + + private String message; + + /** + * Get code + * @return code + **/ + public Integer getCode() { + return code; + } + + /** + * Set code + **/ + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get type + * @return type + **/ + public String getType() { + return type; + } + + /** + * Set type + **/ + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get message + * @return message + **/ + public String getMessage() { + return message; + } + + /** + * Set message + **/ + public void setMessage(String message) { + this.message = message; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelFile.java new file mode 100644 index 0000000000..3c1cf785ea --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelFile.java @@ -0,0 +1,79 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Must be named `File` for test. + **/ + +public class ModelFile { + + /** + * Test capitalization + **/ + private String sourceURI; + + /** + * Test capitalization + * @return sourceURI + **/ + public String getSourceURI() { + return sourceURI; + } + + /** + * Set sourceURI + **/ + public void setSourceURI(String sourceURI) { + this.sourceURI = sourceURI; + } + + public ModelFile sourceURI(String sourceURI) { + this.sourceURI = sourceURI; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelFile {\n"); + + sb.append(" sourceURI: ").append(toIndentedString(sourceURI)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelList.java new file mode 100644 index 0000000000..0c2e7ffb39 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelList.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class ModelList { + + private String _123list; + + /** + * Get _123list + * @return _123list + **/ + public String get123list() { + return _123list; + } + + /** + * Set _123list + **/ + public void set123list(String _123list) { + this._123list = _123list; + } + + public ModelList _123list(String _123list) { + this._123list = _123list; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelList {\n"); + + sb.append(" _123list: ").append(toIndentedString(_123list)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelReturn.java new file mode 100644 index 0000000000..7d948f62e2 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -0,0 +1,76 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Model for testing reserved words + **/ + +public class ModelReturn { + + private Integer _return; + + /** + * Get _return + * @return _return + **/ + public Integer getReturn() { + return _return; + } + + /** + * Set _return + **/ + public void setReturn(Integer _return) { + this._return = _return; + } + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Name.java new file mode 100644 index 0000000000..ba07eb9152 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Name.java @@ -0,0 +1,123 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + +/** + * Model for testing model name same as property name + **/ + +public class Name { + + private Integer name; + + private Integer snakeCase; + + private String property; + + private Integer _123number; + + /** + * Get name + * @return name + **/ + public Integer getName() { + return name; + } + + /** + * Set name + **/ + public void setName(Integer name) { + this.name = name; + } + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + public Integer getSnakeCase() { + return snakeCase; + } + + + /** + * Get property + * @return property + **/ + public String getProperty() { + return property; + } + + /** + * Set property + **/ + public void setProperty(String property) { + this.property = property; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get _123number + * @return _123number + **/ + public Integer get123number() { + return _123number; + } + + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123number: ").append(toIndentedString(_123number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/NullableClass.java new file mode 100644 index 0000000000..759832f0dd --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/NullableClass.java @@ -0,0 +1,367 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + + + + +public class NullableClass extends HashMap { + + private Integer integerProp; + + private BigDecimal numberProp; + + private Boolean booleanProp; + + private String stringProp; + + private LocalDate dateProp; + + private OffsetDateTime datetimeProp; + + private List arrayNullableProp = null; + + private List arrayAndItemsNullableProp = null; + + private List arrayItemsNullable = null; + + private Map objectNullableProp = null; + + private Map objectAndItemsNullableProp = null; + + private Map objectItemsNullable = null; + + /** + * Get integerProp + * @return integerProp + **/ + public Integer getIntegerProp() { + return integerProp; + } + + /** + * Set integerProp + **/ + public void setIntegerProp(Integer integerProp) { + this.integerProp = integerProp; + } + + public NullableClass integerProp(Integer integerProp) { + this.integerProp = integerProp; + return this; + } + + /** + * Get numberProp + * @return numberProp + **/ + public BigDecimal getNumberProp() { + return numberProp; + } + + /** + * Set numberProp + **/ + public void setNumberProp(BigDecimal numberProp) { + this.numberProp = numberProp; + } + + public NullableClass numberProp(BigDecimal numberProp) { + this.numberProp = numberProp; + return this; + } + + /** + * Get booleanProp + * @return booleanProp + **/ + public Boolean getBooleanProp() { + return booleanProp; + } + + /** + * Set booleanProp + **/ + public void setBooleanProp(Boolean booleanProp) { + this.booleanProp = booleanProp; + } + + public NullableClass booleanProp(Boolean booleanProp) { + this.booleanProp = booleanProp; + return this; + } + + /** + * Get stringProp + * @return stringProp + **/ + public String getStringProp() { + return stringProp; + } + + /** + * Set stringProp + **/ + public void setStringProp(String stringProp) { + this.stringProp = stringProp; + } + + public NullableClass stringProp(String stringProp) { + this.stringProp = stringProp; + return this; + } + + /** + * Get dateProp + * @return dateProp + **/ + public LocalDate getDateProp() { + return dateProp; + } + + /** + * Set dateProp + **/ + public void setDateProp(LocalDate dateProp) { + this.dateProp = dateProp; + } + + public NullableClass dateProp(LocalDate dateProp) { + this.dateProp = dateProp; + return this; + } + + /** + * Get datetimeProp + * @return datetimeProp + **/ + public OffsetDateTime getDatetimeProp() { + return datetimeProp; + } + + /** + * Set datetimeProp + **/ + public void setDatetimeProp(OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + } + + public NullableClass datetimeProp(OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + return this; + } + + /** + * Get arrayNullableProp + * @return arrayNullableProp + **/ + public List getArrayNullableProp() { + return arrayNullableProp; + } + + /** + * Set arrayNullableProp + **/ + public void setArrayNullableProp(List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + } + + public NullableClass arrayNullableProp(List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + return this; + } + + public NullableClass addArrayNullablePropItem(Object arrayNullablePropItem) { + this.arrayNullableProp.add(arrayNullablePropItem); + return this; + } + + /** + * Get arrayAndItemsNullableProp + * @return arrayAndItemsNullableProp + **/ + public List getArrayAndItemsNullableProp() { + return arrayAndItemsNullableProp; + } + + /** + * Set arrayAndItemsNullableProp + **/ + public void setArrayAndItemsNullableProp(List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + } + + public NullableClass arrayAndItemsNullableProp(List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + return this; + } + + public NullableClass addArrayAndItemsNullablePropItem(Object arrayAndItemsNullablePropItem) { + this.arrayAndItemsNullableProp.add(arrayAndItemsNullablePropItem); + return this; + } + + /** + * Get arrayItemsNullable + * @return arrayItemsNullable + **/ + public List getArrayItemsNullable() { + return arrayItemsNullable; + } + + /** + * Set arrayItemsNullable + **/ + public void setArrayItemsNullable(List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + } + + public NullableClass arrayItemsNullable(List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + return this; + } + + public NullableClass addArrayItemsNullableItem(Object arrayItemsNullableItem) { + this.arrayItemsNullable.add(arrayItemsNullableItem); + return this; + } + + /** + * Get objectNullableProp + * @return objectNullableProp + **/ + public Map getObjectNullableProp() { + return objectNullableProp; + } + + /** + * Set objectNullableProp + **/ + public void setObjectNullableProp(Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + } + + public NullableClass objectNullableProp(Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + return this; + } + + public NullableClass putObjectNullablePropItem(String key, Object objectNullablePropItem) { + this.objectNullableProp.put(key, objectNullablePropItem); + return this; + } + + /** + * Get objectAndItemsNullableProp + * @return objectAndItemsNullableProp + **/ + public Map getObjectAndItemsNullableProp() { + return objectAndItemsNullableProp; + } + + /** + * Set objectAndItemsNullableProp + **/ + public void setObjectAndItemsNullableProp(Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + } + + public NullableClass objectAndItemsNullableProp(Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + return this; + } + + public NullableClass putObjectAndItemsNullablePropItem(String key, Object objectAndItemsNullablePropItem) { + this.objectAndItemsNullableProp.put(key, objectAndItemsNullablePropItem); + return this; + } + + /** + * Get objectItemsNullable + * @return objectItemsNullable + **/ + public Map getObjectItemsNullable() { + return objectItemsNullable; + } + + /** + * Set objectItemsNullable + **/ + public void setObjectItemsNullable(Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + } + + public NullableClass objectItemsNullable(Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + return this; + } + + public NullableClass putObjectItemsNullableItem(String key, Object objectItemsNullableItem) { + this.objectItemsNullable.put(key, objectItemsNullableItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NullableClass {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" integerProp: ").append(toIndentedString(integerProp)).append("\n"); + sb.append(" numberProp: ").append(toIndentedString(numberProp)).append("\n"); + sb.append(" booleanProp: ").append(toIndentedString(booleanProp)).append("\n"); + sb.append(" stringProp: ").append(toIndentedString(stringProp)).append("\n"); + sb.append(" dateProp: ").append(toIndentedString(dateProp)).append("\n"); + sb.append(" datetimeProp: ").append(toIndentedString(datetimeProp)).append("\n"); + sb.append(" arrayNullableProp: ").append(toIndentedString(arrayNullableProp)).append("\n"); + sb.append(" arrayAndItemsNullableProp: ").append(toIndentedString(arrayAndItemsNullableProp)).append("\n"); + sb.append(" arrayItemsNullable: ").append(toIndentedString(arrayItemsNullable)).append("\n"); + sb.append(" objectNullableProp: ").append(toIndentedString(objectNullableProp)).append("\n"); + sb.append(" objectAndItemsNullableProp: ").append(toIndentedString(objectAndItemsNullableProp)).append("\n"); + sb.append(" objectItemsNullable: ").append(toIndentedString(objectItemsNullable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/NumberOnly.java new file mode 100644 index 0000000000..5d493bccf2 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; + + + + +public class NumberOnly { + + private BigDecimal justNumber; + + /** + * Get justNumber + * @return justNumber + **/ + public BigDecimal getJustNumber() { + return justNumber; + } + + /** + * Set justNumber + **/ + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java new file mode 100644 index 0000000000..00c4300075 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -0,0 +1,157 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.DeprecatedObject; + + + + +public class ObjectWithDeprecatedFields { + + private String uuid; + + private BigDecimal id; + + private DeprecatedObject deprecatedRef; + + private List bars = null; + + /** + * Get uuid + * @return uuid + **/ + public String getUuid() { + return uuid; + } + + /** + * Set uuid + **/ + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public ObjectWithDeprecatedFields uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get id + * @return id + * @deprecated + **/ + @Deprecated + public BigDecimal getId() { + return id; + } + + /** + * Set id + **/ + public void setId(BigDecimal id) { + this.id = id; + } + + public ObjectWithDeprecatedFields id(BigDecimal id) { + this.id = id; + return this; + } + + /** + * Get deprecatedRef + * @return deprecatedRef + * @deprecated + **/ + @Deprecated + public DeprecatedObject getDeprecatedRef() { + return deprecatedRef; + } + + /** + * Set deprecatedRef + **/ + public void setDeprecatedRef(DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + } + + public ObjectWithDeprecatedFields deprecatedRef(DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + return this; + } + + /** + * Get bars + * @return bars + * @deprecated + **/ + @Deprecated + public List getBars() { + return bars; + } + + /** + * Set bars + **/ + public void setBars(List bars) { + this.bars = bars; + } + + public ObjectWithDeprecatedFields bars(List bars) { + this.bars = bars; + return this; + } + + public ObjectWithDeprecatedFields addBarsItem(String barsItem) { + this.bars.add(barsItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ObjectWithDeprecatedFields {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" deprecatedRef: ").append(toIndentedString(deprecatedRef)).append("\n"); + sb.append(" bars: ").append(toIndentedString(bars)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Order.java new file mode 100644 index 0000000000..84ce8e3fa1 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Order.java @@ -0,0 +1,213 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; + + + + +public class Order { + + private Long id; + + private Long petId; + + private Integer quantity; + + private OffsetDateTime shipDate; + +public enum StatusEnum { + + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); + + String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + /** + * Order Status + **/ + private StatusEnum status; + + private Boolean complete = false; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get petId + * @return petId + **/ + public Long getPetId() { + return petId; + } + + /** + * Set petId + **/ + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + public Integer getQuantity() { + return quantity; + } + + /** + * Set quantity + **/ + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + public OffsetDateTime getShipDate() { + return shipDate; + } + + /** + * Set shipDate + **/ + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Order Status + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + **/ + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Get complete + * @return complete + **/ + public Boolean getComplete() { + return complete; + } + + /** + * Set complete + **/ + public void setComplete(Boolean complete) { + this.complete = complete; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterComposite.java new file mode 100644 index 0000000000..6ba3d1712d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -0,0 +1,120 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; + + + + +public class OuterComposite { + + private BigDecimal myNumber; + + private String myString; + + private Boolean myBoolean; + + /** + * Get myNumber + * @return myNumber + **/ + public BigDecimal getMyNumber() { + return myNumber; + } + + /** + * Set myNumber + **/ + public void setMyNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + } + + public OuterComposite myNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + return this; + } + + /** + * Get myString + * @return myString + **/ + public String getMyString() { + return myString; + } + + /** + * Set myString + **/ + public void setMyString(String myString) { + this.myString = myString; + } + + public OuterComposite myString(String myString) { + this.myString = myString; + return this; + } + + /** + * Get myBoolean + * @return myBoolean + **/ + public Boolean getMyBoolean() { + return myBoolean; + } + + /** + * Set myBoolean + **/ + public void setMyBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + } + + public OuterComposite myBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterComposite {\n"); + + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); + sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnum.java new file mode 100644 index 0000000000..9fe96db3f6 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnum.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java new file mode 100644 index 0000000000..f5b732f784 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumDefaultValue + */ +public enum OuterEnumDefaultValue { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnumDefaultValue(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumDefaultValue fromValue(String text) { + for (OuterEnumDefaultValue b : OuterEnumDefaultValue.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnumInteger.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnumInteger.java new file mode 100644 index 0000000000..0ca88b32ee --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnumInteger.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumInteger + */ +public enum OuterEnumInteger { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumInteger(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumInteger fromValue(String text) { + for (OuterEnumInteger b : OuterEnumInteger.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java new file mode 100644 index 0000000000..06f9fe6c37 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java @@ -0,0 +1,52 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumIntegerDefaultValue + */ +public enum OuterEnumIntegerDefaultValue { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumIntegerDefaultValue(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumIntegerDefaultValue fromValue(String text) { + for (OuterEnumIntegerDefaultValue b : OuterEnumIntegerDefaultValue.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java new file mode 100644 index 0000000000..b25e8e37ae --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.OuterEnumInteger; + + + + +public class OuterObjectWithEnumProperty { + + private OuterEnumInteger value; + + /** + * Get value + * @return value + **/ + public OuterEnumInteger getValue() { + return value; + } + + /** + * Set value + **/ + public void setValue(OuterEnumInteger value) { + this.value = value; + } + + public OuterObjectWithEnumProperty value(OuterEnumInteger value) { + this.value = value; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterObjectWithEnumProperty {\n"); + + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Pet.java new file mode 100644 index 0000000000..b86299acd2 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Pet.java @@ -0,0 +1,230 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; + + + + +public class Pet { + + private Long id; + + private Category category; + + private String name; + + private Set photoUrls = new LinkedHashSet<>(); + + private List tags = null; + +public enum StatusEnum { + + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); + + String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + +} + + /** + * pet status in the store + **/ + private StatusEnum status; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get category + * @return category + **/ + public Category getCategory() { + return category; + } + + /** + * Set category + **/ + public void setCategory(Category category) { + this.category = category; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + public Set getPhotoUrls() { + return photoUrls; + } + + /** + * Set photoUrls + **/ + @JsonDeserialize(as = LinkedHashSet.class) + public void setPhotoUrls(Set photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet photoUrls(Set photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + public List getTags() { + return tags; + } + + /** + * Set tags + **/ + public void setTags(List tags) { + this.tags = tags; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * pet status in the store + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + **/ + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java new file mode 100644 index 0000000000..15344cbf0d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -0,0 +1,85 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class ReadOnlyFirst { + + private String bar; + + private String baz; + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + + /** + * Get baz + * @return baz + **/ + public String getBaz() { + return baz; + } + + /** + * Set baz + **/ + public void setBaz(String baz) { + this.baz = baz; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/SingleRefType.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/SingleRefType.java new file mode 100644 index 0000000000..d46fc6c116 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/SingleRefType.java @@ -0,0 +1,50 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets SingleRefType + */ +public enum SingleRefType { + + ADMIN("admin"), + + USER("user"); + + private String value; + + SingleRefType(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static SingleRefType fromValue(String text) { + for (SingleRefType b : SingleRefType.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/SpecialModelName.java new file mode 100644 index 0000000000..af5166268f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class SpecialModelName { + + private Long $specialPropertyName; + + /** + * Get $specialPropertyName + * @return $specialPropertyName + **/ + public Long get$SpecialPropertyName() { + return $specialPropertyName; + } + + /** + * Set $specialPropertyName + **/ + public void set$SpecialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + } + + public SpecialModelName $specialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" $specialPropertyName: ").append(toIndentedString($specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Tag.java new file mode 100644 index 0000000000..1dee37e393 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/Tag.java @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class Tag { + + private Long id; + + private String name; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/User.java new file mode 100644 index 0000000000..c088a4d15d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/User.java @@ -0,0 +1,237 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + + + + +public class User { + + private Long id; + + private String username; + + private String firstName; + + private String lastName; + + private String email; + + private String password; + + private String phone; + + /** + * User Status + **/ + private Integer userStatus; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + + /** + * Set username + **/ + public void setUsername(String username) { + this.username = username; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + public String getFirstName() { + return firstName; + } + + /** + * Set firstName + **/ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + public String getLastName() { + return lastName; + } + + /** + * Set lastName + **/ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get email + * @return email + **/ + public String getEmail() { + return email; + } + + /** + * Set email + **/ + public void setEmail(String email) { + this.email = email; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get password + * @return password + **/ + public String getPassword() { + return password; + } + + /** + * Set password + **/ + public void setPassword(String password) { + this.password = password; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get phone + * @return phone + **/ + public String getPhone() { + return phone; + } + + /** + * Set phone + **/ + public void setPhone(String phone) { + this.phone = phone; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * User Status + * @return userStatus + **/ + public Integer getUserStatus() { + return userStatus; + } + + /** + * Set userStatus + **/ + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java new file mode 100644 index 0000000000..61bad52eda --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.Client; +import java.util.List; +import java.util.Map; + +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiResponse; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * + * OpenAPI Petstore Test + * + * + * API tests for AnotherFakeApi + */ +public class AnotherFakeApiTest { + + private static ApiClient apiClient; + private static AnotherFakeApi api; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() { + apiClient = ApiClient.builder().build(); + api = AnotherFakeApiImpl.create(apiClient); + } + + /** + * To test special tags + * To test special tags and operation ID starting with number + */ + @Test + public void call123testSpecialTagsTest() { + // TODO - assign values to the input arguments. + Client client = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.call123testSpecialTags(client); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/DefaultApiTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/DefaultApiTest.java new file mode 100644 index 0000000000..89d04ef853 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/DefaultApiTest.java @@ -0,0 +1,69 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.FooGetDefaultResponse; + +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiResponse; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * + * OpenAPI Petstore Test + * + * + * API tests for DefaultApi + */ +public class DefaultApiTest { + + private static ApiClient apiClient; + private static DefaultApi api; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() { + apiClient = ApiClient.builder().build(); + api = DefaultApiImpl.create(apiClient); + } + + /** + * + */ + @Test + public void fooGetTest() { + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.fooGet(); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/FakeApiTest.java new file mode 100644 index 0000000000..c4dfd1fcf8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/FakeApiTest.java @@ -0,0 +1,440 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import org.openapitools.client.model.EnumClass; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.HealthCheckResult; +import java.util.List; +import java.time.LocalDate; +import java.util.Map; +import java.time.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.OuterObjectWithEnumProperty; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.User; + +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiResponse; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * + * OpenAPI Petstore Test + * + * + * API tests for FakeApi + */ +public class FakeApiTest { + + private static ApiClient apiClient; + private static FakeApi api; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() { + apiClient = ApiClient.builder().build(); + api = FakeApiImpl.create(apiClient); + } + + /** + * Health check endpoint + */ + @Test + public void fakeHealthGetTest() { + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.fakeHealthGet(); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * test http signature authentication + */ + @Test + public void fakeHttpSignatureTestTest() { + // TODO - assign values to the input arguments. + Pet pet = null; + // TODO - assign values to the input arguments. + String query1 = null; + // TODO - assign values to the input arguments. + String header1 = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.fakeHttpSignatureTest(pet, query1, header1); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * + * Test serialization of outer boolean types + */ + @Test + public void fakeOuterBooleanSerializeTest() { + // TODO - assign values to the input arguments. + Boolean body = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.fakeOuterBooleanSerialize(body); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * + * Test serialization of object with outer number type + */ + @Test + public void fakeOuterCompositeSerializeTest() { + // TODO - assign values to the input arguments. + OuterComposite outerComposite = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.fakeOuterCompositeSerialize(outerComposite); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * + * Test serialization of outer number types + */ + @Test + public void fakeOuterNumberSerializeTest() { + // TODO - assign values to the input arguments. + BigDecimal body = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.fakeOuterNumberSerialize(body); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * + * Test serialization of outer string types + */ + @Test + public void fakeOuterStringSerializeTest() { + // TODO - assign values to the input arguments. + String body = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.fakeOuterStringSerialize(body); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * + * Test serialization of enum (int) properties with examples + */ + @Test + public void fakePropertyEnumIntegerSerializeTest() { + // TODO - assign values to the input arguments. + OuterObjectWithEnumProperty outerObjectWithEnumProperty = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * + * For this test, the body has to be a binary file. + */ + @Test + public void testBodyWithBinaryTest() { + // TODO - assign values to the input arguments. + File body = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testBodyWithBinary(body); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * + * For this test, the body for this request must reference a schema named `File`. + */ + @Test + public void testBodyWithFileSchemaTest() { + // TODO - assign values to the input arguments. + FileSchemaTestClass fileSchemaTestClass = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testBodyWithFileSchema(fileSchemaTestClass); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * + */ + @Test + public void testBodyWithQueryParamsTest() { + // TODO - assign values to the input arguments. + String query = null; + // TODO - assign values to the input arguments. + User user = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testBodyWithQueryParams(query, user); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * To test \"client\" model + * To test \"client\" model + */ + @Test + public void testClientModelTest() { + // TODO - assign values to the input arguments. + Client client = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testClientModel(client); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + */ + @Test + public void testEndpointParametersTest() { + // TODO - assign values to the input arguments. + BigDecimal number = null; + // TODO - assign values to the input arguments. + Double _double = null; + // TODO - assign values to the input arguments. + String patternWithoutDelimiter = null; + // TODO - assign values to the input arguments. + byte[] _byte = null; + // TODO - assign values to the input arguments. + Integer integer = null; + // TODO - assign values to the input arguments. + Integer int32 = null; + // TODO - assign values to the input arguments. + Long int64 = null; + // TODO - assign values to the input arguments. + Float _float = null; + // TODO - assign values to the input arguments. + String string = null; + // TODO - assign values to the input arguments. + File binary = null; + // TODO - assign values to the input arguments. + LocalDate date = null; + // TODO - assign values to the input arguments. + OffsetDateTime dateTime = null; + // TODO - assign values to the input arguments. + String password = null; + // TODO - assign values to the input arguments. + String paramCallback = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * To test enum parameters + * To test enum parameters + */ + @Test + public void testEnumParametersTest() { + // TODO - assign values to the input arguments. + List enumHeaderStringArray = null; + // TODO - assign values to the input arguments. + String enumHeaderString = null; + // TODO - assign values to the input arguments. + List enumQueryStringArray = null; + // TODO - assign values to the input arguments. + String enumQueryString = null; + // TODO - assign values to the input arguments. + Integer enumQueryInteger = null; + // TODO - assign values to the input arguments. + Double enumQueryDouble = null; + // TODO - assign values to the input arguments. + List enumQueryModelArray = null; + // TODO - assign values to the input arguments. + List enumFormStringArray = null; + // TODO - assign values to the input arguments. + String enumFormString = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Fake endpoint to test group parameters (optional) + * Fake endpoint to test group parameters (optional) + */ + @Test + public void testGroupParametersTest() { + // TODO - assign values to the input arguments. + Integer requiredStringGroup = null; + // TODO - assign values to the input arguments. + Boolean requiredBooleanGroup = null; + // TODO - assign values to the input arguments. + Long requiredInt64Group = null; + // TODO - assign values to the input arguments. + Integer stringGroup = null; + // TODO - assign values to the input arguments. + Boolean booleanGroup = null; + // TODO - assign values to the input arguments. + Long int64Group = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * test inline additionalProperties + * + */ + @Test + public void testInlineAdditionalPropertiesTest() { + // TODO - assign values to the input arguments. + Map requestBody = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testInlineAdditionalProperties(requestBody); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * test json serialization of form data + * + */ + @Test + public void testJsonFormDataTest() { + // TODO - assign values to the input arguments. + String param = null; + // TODO - assign values to the input arguments. + String param2 = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testJsonFormData(param, param2); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * + * To test the collection format in query parameters + */ + @Test + public void testQueryParameterCollectionFormatTest() { + // TODO - assign values to the input arguments. + List pipe = null; + // TODO - assign values to the input arguments. + List ioutil = null; + // TODO - assign values to the input arguments. + List http = null; + // TODO - assign values to the input arguments. + List url = null; + // TODO - assign values to the input arguments. + List context = null; + // TODO - assign values to the input arguments. + String allowEmpty = null; + // TODO - assign values to the input arguments. + Map language = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, allowEmpty, language); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java new file mode 100644 index 0000000000..b478b14584 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java @@ -0,0 +1,74 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.Client; +import java.util.List; +import java.util.Map; + +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiResponse; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * + * OpenAPI Petstore Test + * + * + * API tests for FakeClassnameTags123Api + */ +public class FakeClassnameTags123ApiTest { + + private static ApiClient apiClient; + private static FakeClassnameTags123Api api; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() { + apiClient = ApiClient.builder().build(); + api = FakeClassnameTags123ApiImpl.create(apiClient); + } + + /** + * To test class name in snake case + * To test class name in snake case + */ + @Test + public void testClassnameTest() { + // TODO - assign values to the input arguments. + Client client = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.testClassname(client); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/PetApiTest.java new file mode 100644 index 0000000000..070ea88e4b --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/PetApiTest.java @@ -0,0 +1,235 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.io.File; +import java.util.List; +import java.util.Map; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; +import java.util.Set; + +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiResponse; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * + * OpenAPI Petstore Test + * + * + * API tests for PetApi + */ +public class PetApiTest { + + private static ApiClient apiClient; + private static PetApi api; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() { + apiClient = ApiClient.builder().build(); + api = PetApiImpl.create(apiClient); + } + + /** + * Add a new pet to the store + * + */ + @Test + public void addPetTest() { + // TODO - assign values to the input arguments. + Pet pet = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.addPet(pet); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Deletes a pet + * + */ + @Test + public void deletePetTest() { + // TODO - assign values to the input arguments. + Long petId = null; + // TODO - assign values to the input arguments. + String apiKey = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.deletePet(petId, apiKey); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + */ + @Test + public void findPetsByStatusTest() { + // TODO - assign values to the input arguments. + List status = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse> response = api.findPetsByStatus(status); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + */ + @Test + public void findPetsByTagsTest() { + // TODO - assign values to the input arguments. + Set tags = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse> response = api.findPetsByTags(tags); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Find pet by ID + * Returns a single pet + */ + @Test + public void getPetByIdTest() { + // TODO - assign values to the input arguments. + Long petId = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.getPetById(petId); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Update an existing pet + * + */ + @Test + public void updatePetTest() { + // TODO - assign values to the input arguments. + Pet pet = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.updatePet(pet); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + */ + @Test + public void updatePetWithFormTest() { + // TODO - assign values to the input arguments. + Long petId = null; + // TODO - assign values to the input arguments. + String name = null; + // TODO - assign values to the input arguments. + String status = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.updatePetWithForm(petId, name, status); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * uploads an image + * + */ + @Test + public void uploadFileTest() { + // TODO - assign values to the input arguments. + Long petId = null; + // TODO - assign values to the input arguments. + String additionalMetadata = null; + // TODO - assign values to the input arguments. + File _file = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.uploadFile(petId, additionalMetadata, _file); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * uploads an image (required) + * + */ + @Test + public void uploadFileWithRequiredFileTest() { + // TODO - assign values to the input arguments. + Long petId = null; + // TODO - assign values to the input arguments. + File requiredFile = null; + // TODO - assign values to the input arguments. + String additionalMetadata = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/StoreApiTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/StoreApiTest.java new file mode 100644 index 0000000000..352767de98 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/StoreApiTest.java @@ -0,0 +1,126 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.util.List; +import java.util.Map; +import org.openapitools.client.model.Order; + +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiResponse; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * + * OpenAPI Petstore Test + * + * + * API tests for StoreApi + */ +public class StoreApiTest { + + private static ApiClient apiClient; + private static StoreApi api; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() { + apiClient = ApiClient.builder().build(); + api = StoreApiImpl.create(apiClient); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + */ + @Test + public void deleteOrderTest() { + // TODO - assign values to the input arguments. + String orderId = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.deleteOrder(orderId); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + @Test + public void getInventoryTest() { + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse> response = api.getInventory(); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + */ + @Test + public void getOrderByIdTest() { + // TODO - assign values to the input arguments. + Long orderId = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.getOrderById(orderId); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + */ + @Test + public void placeOrderTest() { + // TODO - assign values to the input arguments. + Order order = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.placeOrder(order); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/UserApiTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/UserApiTest.java new file mode 100644 index 0000000000..81fca40222 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/api/UserApiTest.java @@ -0,0 +1,203 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.util.List; +import java.util.Map; +import java.time.OffsetDateTime; +import org.openapitools.client.model.User; + +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiResponse; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.helidon.common.reactive.Single; +import io.helidon.webclient.WebClientResponse; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * + * OpenAPI Petstore Test + * + * + * API tests for UserApi + */ +public class UserApiTest { + + private static ApiClient apiClient; + private static UserApi api; + private static final String baseUrl = "http://localhost:8080"; + + @BeforeAll + public static void setup() { + apiClient = ApiClient.builder().build(); + api = UserApiImpl.create(apiClient); + } + + /** + * Create user + * This can only be done by the logged in user. + */ + @Test + public void createUserTest() { + // TODO - assign values to the input arguments. + User user = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.createUser(user); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + */ + @Test + public void createUsersWithArrayInputTest() { + // TODO - assign values to the input arguments. + List user = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.createUsersWithArrayInput(user); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + */ + @Test + public void createUsersWithListInputTest() { + // TODO - assign values to the input arguments. + List user = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.createUsersWithListInput(user); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Delete user + * This can only be done by the logged in user. + */ + @Test + public void deleteUserTest() { + // TODO - assign values to the input arguments. + String username = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.deleteUser(username); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Get user by user name + * + */ + @Test + public void getUserByNameTest() { + // TODO - assign values to the input arguments. + String username = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.getUserByName(username); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Logs user into the system + * + */ + @Test + public void loginUserTest() { + // TODO - assign values to the input arguments. + String username = null; + // TODO - assign values to the input arguments. + String password = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.loginUser(username, password); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + */ + @Test + public void logoutUserTest() { + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.logoutUser(); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + + /** + * Updated user + * This can only be done by the logged in user. + */ + @Test + public void updateUserTest() { + // TODO - assign values to the input arguments. + String username = null; + // TODO - assign values to the input arguments. + User user = null; + + // TODO - uncomment the following two lines to invoke the service with valid parameters. + //ApiResponse response = api.updateUser(username, user); + //response.webClientResponse().await(); + // TODO - check for appropriate return status + // assertThat("Return status", response.get().status().code(), is(expectedStatus)); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java new file mode 100644 index 0000000000..008d620d50 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java @@ -0,0 +1,57 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for AdditionalPropertiesClass + */ +public class AdditionalPropertiesClassTest { + private final AdditionalPropertiesClass model = new AdditionalPropertiesClass(); + + /** + * Model tests for AdditionalPropertiesClass + */ + @Test + public void testAdditionalPropertiesClass() { + // TODO: test AdditionalPropertiesClass + } + + /** + * Test the property 'mapProperty' + */ + @Test + public void mapPropertyTest() { + // TODO: test mapProperty + } + + /** + * Test the property 'mapOfMapProperty' + */ + @Test + public void mapOfMapPropertyTest() { + // TODO: test mapOfMapProperty + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/AllOfWithSingleRefTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/AllOfWithSingleRefTest.java new file mode 100644 index 0000000000..ad55c6f2c7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/AllOfWithSingleRefTest.java @@ -0,0 +1,56 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.SingleRefType; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for AllOfWithSingleRef + */ +public class AllOfWithSingleRefTest { + private final AllOfWithSingleRef model = new AllOfWithSingleRef(); + + /** + * Model tests for AllOfWithSingleRef + */ + @Test + public void testAllOfWithSingleRef() { + // TODO: test AllOfWithSingleRef + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'singleRefType' + */ + @Test + public void singleRefTypeTest() { + // TODO: test singleRefType + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/AnimalTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/AnimalTest.java new file mode 100644 index 0000000000..c38a031c2e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/AnimalTest.java @@ -0,0 +1,60 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Cat; +import org.openapitools.client.model.Dog; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Animal + */ +public class AnimalTest { + private final Animal model = new Animal(); + + /** + * Model tests for Animal + */ + @Test + public void testAnimal() { + // TODO: test Animal + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java new file mode 100644 index 0000000000..5a886da823 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java @@ -0,0 +1,50 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayOfArrayOfNumberOnly + */ +public class ArrayOfArrayOfNumberOnlyTest { + private final ArrayOfArrayOfNumberOnly model = new ArrayOfArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfArrayOfNumberOnly + */ + @Test + public void testArrayOfArrayOfNumberOnly() { + // TODO: test ArrayOfArrayOfNumberOnly + } + + /** + * Test the property 'arrayArrayNumber' + */ + @Test + public void arrayArrayNumberTest() { + // TODO: test arrayArrayNumber + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java new file mode 100644 index 0000000000..6b0d615c0e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java @@ -0,0 +1,50 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayOfNumberOnly + */ +public class ArrayOfNumberOnlyTest { + private final ArrayOfNumberOnly model = new ArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfNumberOnly + */ + @Test + public void testArrayOfNumberOnly() { + // TODO: test ArrayOfNumberOnly + } + + /** + * Test the property 'arrayNumber' + */ + @Test + public void arrayNumberTest() { + // TODO: test arrayNumber + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ArrayTestTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ArrayTestTest.java new file mode 100644 index 0000000000..be3f20c9a3 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ArrayTestTest.java @@ -0,0 +1,66 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ReadOnlyFirst; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayTest + */ +public class ArrayTestTest { + private final ArrayTest model = new ArrayTest(); + + /** + * Model tests for ArrayTest + */ + @Test + public void testArrayTest() { + // TODO: test ArrayTest + } + + /** + * Test the property 'arrayOfString' + */ + @Test + public void arrayOfStringTest() { + // TODO: test arrayOfString + } + + /** + * Test the property 'arrayArrayOfInteger' + */ + @Test + public void arrayArrayOfIntegerTest() { + // TODO: test arrayArrayOfInteger + } + + /** + * Test the property 'arrayArrayOfModel' + */ + @Test + public void arrayArrayOfModelTest() { + // TODO: test arrayArrayOfModel + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CapitalizationTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CapitalizationTest.java new file mode 100644 index 0000000000..18e9b9dbf0 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CapitalizationTest.java @@ -0,0 +1,87 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Capitalization + */ +public class CapitalizationTest { + private final Capitalization model = new Capitalization(); + + /** + * Model tests for Capitalization + */ + @Test + public void testCapitalization() { + // TODO: test Capitalization + } + + /** + * Test the property 'smallCamel' + */ + @Test + public void smallCamelTest() { + // TODO: test smallCamel + } + + /** + * Test the property 'capitalCamel' + */ + @Test + public void capitalCamelTest() { + // TODO: test capitalCamel + } + + /** + * Test the property 'smallSnake' + */ + @Test + public void smallSnakeTest() { + // TODO: test smallSnake + } + + /** + * Test the property 'capitalSnake' + */ + @Test + public void capitalSnakeTest() { + // TODO: test capitalSnake + } + + /** + * Test the property 'scAETHFlowPoints' + */ + @Test + public void scAETHFlowPointsTest() { + // TODO: test scAETHFlowPoints + } + + /** + * Test the property 'ATT_NAME' + */ + @Test + public void ATT_NAMETest() { + // TODO: test ATT_NAME + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CatAllOfTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CatAllOfTest.java new file mode 100644 index 0000000000..3772925dd6 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CatAllOfTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for CatAllOf + */ +public class CatAllOfTest { + private final CatAllOf model = new CatAllOf(); + + /** + * Model tests for CatAllOf + */ + @Test + public void testCatAllOf() { + // TODO: test CatAllOf + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CatTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CatTest.java new file mode 100644 index 0000000000..d78fcb6359 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CatTest.java @@ -0,0 +1,67 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Animal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Cat + */ +public class CatTest { + private final Cat model = new Cat(); + + /** + * Model tests for Cat + */ + @Test + public void testCat() { + // TODO: test Cat + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CategoryTest.java new file mode 100644 index 0000000000..12d4b6a644 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/CategoryTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ClassModelTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ClassModelTest.java new file mode 100644 index 0000000000..035b80969f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ClassModelTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ClassModel + */ +public class ClassModelTest { + private final ClassModel model = new ClassModel(); + + /** + * Model tests for ClassModel + */ + @Test + public void testClassModel() { + // TODO: test ClassModel + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ClientTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ClientTest.java new file mode 100644 index 0000000000..9b4899ae22 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ClientTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Client + */ +public class ClientTest { + private final Client model = new Client(); + + /** + * Model tests for Client + */ + @Test + public void testClient() { + // TODO: test Client + } + + /** + * Test the property 'client' + */ + @Test + public void clientTest() { + // TODO: test client + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java new file mode 100644 index 0000000000..54347091cc --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for DeprecatedObject + */ +public class DeprecatedObjectTest { + private final DeprecatedObject model = new DeprecatedObject(); + + /** + * Model tests for DeprecatedObject + */ + @Test + public void testDeprecatedObject() { + // TODO: test DeprecatedObject + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/DogAllOfTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/DogAllOfTest.java new file mode 100644 index 0000000000..16066cd03f --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/DogAllOfTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for DogAllOf + */ +public class DogAllOfTest { + private final DogAllOf model = new DogAllOf(); + + /** + * Model tests for DogAllOf + */ + @Test + public void testDogAllOf() { + // TODO: test DogAllOf + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/DogTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/DogTest.java new file mode 100644 index 0000000000..6819c78158 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/DogTest.java @@ -0,0 +1,67 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Animal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Dog + */ +public class DogTest { + private final Dog model = new Dog(); + + /** + * Model tests for Dog + */ + @Test + public void testDog() { + // TODO: test Dog + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/EnumArraysTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/EnumArraysTest.java new file mode 100644 index 0000000000..4d24965872 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/EnumArraysTest.java @@ -0,0 +1,57 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumArrays + */ +public class EnumArraysTest { + private final EnumArrays model = new EnumArrays(); + + /** + * Model tests for EnumArrays + */ + @Test + public void testEnumArrays() { + // TODO: test EnumArrays + } + + /** + * Test the property 'justSymbol' + */ + @Test + public void justSymbolTest() { + // TODO: test justSymbol + } + + /** + * Test the property 'arrayEnum' + */ + @Test + public void arrayEnumTest() { + // TODO: test arrayEnum + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/EnumClassTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/EnumClassTest.java new file mode 100644 index 0000000000..11bf230be7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/EnumClassTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumClass + */ +public class EnumClassTest { + /** + * Model tests for EnumClass + */ + @Test + public void testEnumClass() { + // TODO: test EnumClass + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/EnumTestTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/EnumTestTest.java new file mode 100644 index 0000000000..ec0d37ce36 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/EnumTestTest.java @@ -0,0 +1,111 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.OuterEnumDefaultValue; +import org.openapitools.client.model.OuterEnumInteger; +import org.openapitools.client.model.OuterEnumIntegerDefaultValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumTest + */ +public class EnumTestTest { + private final EnumTest model = new EnumTest(); + + /** + * Model tests for EnumTest + */ + @Test + public void testEnumTest() { + // TODO: test EnumTest + } + + /** + * Test the property 'enumString' + */ + @Test + public void enumStringTest() { + // TODO: test enumString + } + + /** + * Test the property 'enumStringRequired' + */ + @Test + public void enumStringRequiredTest() { + // TODO: test enumStringRequired + } + + /** + * Test the property 'enumInteger' + */ + @Test + public void enumIntegerTest() { + // TODO: test enumInteger + } + + /** + * Test the property 'enumNumber' + */ + @Test + public void enumNumberTest() { + // TODO: test enumNumber + } + + /** + * Test the property 'outerEnum' + */ + @Test + public void outerEnumTest() { + // TODO: test outerEnum + } + + /** + * Test the property 'outerEnumInteger' + */ + @Test + public void outerEnumIntegerTest() { + // TODO: test outerEnumInteger + } + + /** + * Test the property 'outerEnumDefaultValue' + */ + @Test + public void outerEnumDefaultValueTest() { + // TODO: test outerEnumDefaultValue + } + + /** + * Test the property 'outerEnumIntegerDefaultValue' + */ + @Test + public void outerEnumIntegerDefaultValueTest() { + // TODO: test outerEnumIntegerDefaultValue + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java new file mode 100644 index 0000000000..846646eb94 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ModelFile; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FileSchemaTestClass + */ +public class FileSchemaTestClassTest { + private final FileSchemaTestClass model = new FileSchemaTestClass(); + + /** + * Model tests for FileSchemaTestClass + */ + @Test + public void testFileSchemaTestClass() { + // TODO: test FileSchemaTestClass + } + + /** + * Test the property '_file' + */ + @Test + public void _fileTest() { + // TODO: test _file + } + + /** + * Test the property 'files' + */ + @Test + public void filesTest() { + // TODO: test files + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java new file mode 100644 index 0000000000..14639567d8 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java @@ -0,0 +1,48 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.Foo; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FooGetDefaultResponse + */ +public class FooGetDefaultResponseTest { + private final FooGetDefaultResponse model = new FooGetDefaultResponse(); + + /** + * Model tests for FooGetDefaultResponse + */ + @Test + public void testFooGetDefaultResponse() { + // TODO: test FooGetDefaultResponse + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FooTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FooTest.java new file mode 100644 index 0000000000..6ad35f67e2 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FooTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Foo + */ +public class FooTest { + private final Foo model = new Foo(); + + /** + * Model tests for Foo + */ + @Test + public void testFoo() { + // TODO: test Foo + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FormatTestTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FormatTestTest.java new file mode 100644 index 0000000000..773e76967e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/FormatTestTest.java @@ -0,0 +1,172 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FormatTest + */ +public class FormatTestTest { + private final FormatTest model = new FormatTest(); + + /** + * Model tests for FormatTest + */ + @Test + public void testFormatTest() { + // TODO: test FormatTest + } + + /** + * Test the property 'integer' + */ + @Test + public void integerTest() { + // TODO: test integer + } + + /** + * Test the property 'int32' + */ + @Test + public void int32Test() { + // TODO: test int32 + } + + /** + * Test the property 'int64' + */ + @Test + public void int64Test() { + // TODO: test int64 + } + + /** + * Test the property 'number' + */ + @Test + public void numberTest() { + // TODO: test number + } + + /** + * Test the property '_float' + */ + @Test + public void _floatTest() { + // TODO: test _float + } + + /** + * Test the property '_double' + */ + @Test + public void _doubleTest() { + // TODO: test _double + } + + /** + * Test the property 'decimal' + */ + @Test + public void decimalTest() { + // TODO: test decimal + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + + /** + * Test the property '_byte' + */ + @Test + public void _byteTest() { + // TODO: test _byte + } + + /** + * Test the property 'binary' + */ + @Test + public void binaryTest() { + // TODO: test binary + } + + /** + * Test the property 'date' + */ + @Test + public void dateTest() { + // TODO: test date + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'patternWithDigits' + */ + @Test + public void patternWithDigitsTest() { + // TODO: test patternWithDigits + } + + /** + * Test the property 'patternWithDigitsAndDelimiter' + */ + @Test + public void patternWithDigitsAndDelimiterTest() { + // TODO: test patternWithDigitsAndDelimiter + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java new file mode 100644 index 0000000000..b956d12d74 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for HasOnlyReadOnly + */ +public class HasOnlyReadOnlyTest { + private final HasOnlyReadOnly model = new HasOnlyReadOnly(); + + /** + * Model tests for HasOnlyReadOnly + */ + @Test + public void testHasOnlyReadOnly() { + // TODO: test HasOnlyReadOnly + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'foo' + */ + @Test + public void fooTest() { + // TODO: test foo + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java new file mode 100644 index 0000000000..3267defa3a --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java @@ -0,0 +1,51 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for HealthCheckResult + */ +public class HealthCheckResultTest { + private final HealthCheckResult model = new HealthCheckResult(); + + /** + * Model tests for HealthCheckResult + */ + @Test + public void testHealthCheckResult() { + // TODO: test HealthCheckResult + } + + /** + * Test the property 'nullableMessage' + */ + @Test + public void nullableMessageTest() { + // TODO: test nullableMessage + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/MapTestTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/MapTestTest.java new file mode 100644 index 0000000000..ac308e4008 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/MapTestTest.java @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for MapTest + */ +public class MapTestTest { + private final MapTest model = new MapTest(); + + /** + * Model tests for MapTest + */ + @Test + public void testMapTest() { + // TODO: test MapTest + } + + /** + * Test the property 'mapMapOfString' + */ + @Test + public void mapMapOfStringTest() { + // TODO: test mapMapOfString + } + + /** + * Test the property 'mapOfEnumString' + */ + @Test + public void mapOfEnumStringTest() { + // TODO: test mapOfEnumString + } + + /** + * Test the property 'directMap' + */ + @Test + public void directMapTest() { + // TODO: test directMap + } + + /** + * Test the property 'indirectMap' + */ + @Test + public void indirectMapTest() { + // TODO: test indirectMap + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java new file mode 100644 index 0000000000..72a7a2a961 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java @@ -0,0 +1,68 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.openapitools.client.model.Animal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ +public class MixedPropertiesAndAdditionalPropertiesClassTest { + private final MixedPropertiesAndAdditionalPropertiesClass model = new MixedPropertiesAndAdditionalPropertiesClass(); + + /** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ + @Test + public void testMixedPropertiesAndAdditionalPropertiesClass() { + // TODO: test MixedPropertiesAndAdditionalPropertiesClass + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'map' + */ + @Test + public void mapTest() { + // TODO: test map + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/Model200ResponseTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/Model200ResponseTest.java new file mode 100644 index 0000000000..79bd883d4c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/Model200ResponseTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Model200Response + */ +public class Model200ResponseTest { + private final Model200Response model = new Model200Response(); + + /** + * Model tests for Model200Response + */ + @Test + public void testModel200Response() { + // TODO: test Model200Response + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java new file mode 100644 index 0000000000..79b915c967 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java @@ -0,0 +1,63 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelFileTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelFileTest.java new file mode 100644 index 0000000000..c10fa3927e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelFileTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelFile + */ +public class ModelFileTest { + private final ModelFile model = new ModelFile(); + + /** + * Model tests for ModelFile + */ + @Test + public void testModelFile() { + // TODO: test ModelFile + } + + /** + * Test the property 'sourceURI' + */ + @Test + public void sourceURITest() { + // TODO: test sourceURI + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelListTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelListTest.java new file mode 100644 index 0000000000..7c09d2e78e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelListTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelList + */ +public class ModelListTest { + private final ModelList model = new ModelList(); + + /** + * Model tests for ModelList + */ + @Test + public void testModelList() { + // TODO: test ModelList + } + + /** + * Test the property '_123list' + */ + @Test + public void _123listTest() { + // TODO: test _123list + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelReturnTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelReturnTest.java new file mode 100644 index 0000000000..8c99cb5220 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ModelReturnTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelReturn + */ +public class ModelReturnTest { + private final ModelReturn model = new ModelReturn(); + + /** + * Model tests for ModelReturn + */ + @Test + public void testModelReturn() { + // TODO: test ModelReturn + } + + /** + * Test the property '_return' + */ + @Test + public void _returnTest() { + // TODO: test _return + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/NameTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/NameTest.java new file mode 100644 index 0000000000..8795299bfa --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/NameTest.java @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Name + */ +public class NameTest { + private final Name model = new Name(); + + /** + * Model tests for Name + */ + @Test + public void testName() { + // TODO: test Name + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'snakeCase' + */ + @Test + public void snakeCaseTest() { + // TODO: test snakeCase + } + + /** + * Test the property 'property' + */ + @Test + public void propertyTest() { + // TODO: test property + } + + /** + * Test the property '_123number' + */ + @Test + public void _123numberTest() { + // TODO: test _123number + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/NullableClassTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/NullableClassTest.java new file mode 100644 index 0000000000..95997f952e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/NullableClassTest.java @@ -0,0 +1,146 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for NullableClass + */ +public class NullableClassTest { + private final NullableClass model = new NullableClass(); + + /** + * Model tests for NullableClass + */ + @Test + public void testNullableClass() { + // TODO: test NullableClass + } + + /** + * Test the property 'integerProp' + */ + @Test + public void integerPropTest() { + // TODO: test integerProp + } + + /** + * Test the property 'numberProp' + */ + @Test + public void numberPropTest() { + // TODO: test numberProp + } + + /** + * Test the property 'booleanProp' + */ + @Test + public void booleanPropTest() { + // TODO: test booleanProp + } + + /** + * Test the property 'stringProp' + */ + @Test + public void stringPropTest() { + // TODO: test stringProp + } + + /** + * Test the property 'dateProp' + */ + @Test + public void datePropTest() { + // TODO: test dateProp + } + + /** + * Test the property 'datetimeProp' + */ + @Test + public void datetimePropTest() { + // TODO: test datetimeProp + } + + /** + * Test the property 'arrayNullableProp' + */ + @Test + public void arrayNullablePropTest() { + // TODO: test arrayNullableProp + } + + /** + * Test the property 'arrayAndItemsNullableProp' + */ + @Test + public void arrayAndItemsNullablePropTest() { + // TODO: test arrayAndItemsNullableProp + } + + /** + * Test the property 'arrayItemsNullable' + */ + @Test + public void arrayItemsNullableTest() { + // TODO: test arrayItemsNullable + } + + /** + * Test the property 'objectNullableProp' + */ + @Test + public void objectNullablePropTest() { + // TODO: test objectNullableProp + } + + /** + * Test the property 'objectAndItemsNullableProp' + */ + @Test + public void objectAndItemsNullablePropTest() { + // TODO: test objectAndItemsNullableProp + } + + /** + * Test the property 'objectItemsNullable' + */ + @Test + public void objectItemsNullableTest() { + // TODO: test objectItemsNullable + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/NumberOnlyTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/NumberOnlyTest.java new file mode 100644 index 0000000000..f1af4caf2e --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/NumberOnlyTest.java @@ -0,0 +1,48 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for NumberOnly + */ +public class NumberOnlyTest { + private final NumberOnly model = new NumberOnly(); + + /** + * Model tests for NumberOnly + */ + @Test + public void testNumberOnly() { + // TODO: test NumberOnly + } + + /** + * Test the property 'justNumber' + */ + @Test + public void justNumberTest() { + // TODO: test justNumber + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java new file mode 100644 index 0000000000..14f312e38a --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java @@ -0,0 +1,75 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.DeprecatedObject; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ObjectWithDeprecatedFields + */ +public class ObjectWithDeprecatedFieldsTest { + private final ObjectWithDeprecatedFields model = new ObjectWithDeprecatedFields(); + + /** + * Model tests for ObjectWithDeprecatedFields + */ + @Test + public void testObjectWithDeprecatedFields() { + // TODO: test ObjectWithDeprecatedFields + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'deprecatedRef' + */ + @Test + public void deprecatedRefTest() { + // TODO: test deprecatedRef + } + + /** + * Test the property 'bars' + */ + @Test + public void barsTest() { + // TODO: test bars + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OrderTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OrderTest.java new file mode 100644 index 0000000000..e99bf8d598 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OrderTest.java @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterCompositeTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterCompositeTest.java new file mode 100644 index 0000000000..28b832d5db --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterCompositeTest.java @@ -0,0 +1,64 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterComposite + */ +public class OuterCompositeTest { + private final OuterComposite model = new OuterComposite(); + + /** + * Model tests for OuterComposite + */ + @Test + public void testOuterComposite() { + // TODO: test OuterComposite + } + + /** + * Test the property 'myNumber' + */ + @Test + public void myNumberTest() { + // TODO: test myNumber + } + + /** + * Test the property 'myString' + */ + @Test + public void myStringTest() { + // TODO: test myString + } + + /** + * Test the property 'myBoolean' + */ + @Test + public void myBooleanTest() { + // TODO: test myBoolean + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java new file mode 100644 index 0000000000..75313d6581 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumDefaultValue + */ +public class OuterEnumDefaultValueTest { + /** + * Model tests for OuterEnumDefaultValue + */ + @Test + public void testOuterEnumDefaultValue() { + // TODO: test OuterEnumDefaultValue + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java new file mode 100644 index 0000000000..df4527f0d4 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumIntegerDefaultValue + */ +public class OuterEnumIntegerDefaultValueTest { + /** + * Model tests for OuterEnumIntegerDefaultValue + */ + @Test + public void testOuterEnumIntegerDefaultValue() { + // TODO: test OuterEnumIntegerDefaultValue + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java new file mode 100644 index 0000000000..87c29d2fd7 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumInteger + */ +public class OuterEnumIntegerTest { + /** + * Model tests for OuterEnumInteger + */ + @Test + public void testOuterEnumInteger() { + // TODO: test OuterEnumInteger + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumTest.java new file mode 100644 index 0000000000..226fc34f40 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterEnumTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnum + */ +public class OuterEnumTest { + /** + * Model tests for OuterEnum + */ + @Test + public void testOuterEnum() { + // TODO: test OuterEnum + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterObjectWithEnumPropertyTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterObjectWithEnumPropertyTest.java new file mode 100644 index 0000000000..24984008ab --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/OuterObjectWithEnumPropertyTest.java @@ -0,0 +1,48 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.client.model.OuterEnumInteger; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterObjectWithEnumProperty + */ +public class OuterObjectWithEnumPropertyTest { + private final OuterObjectWithEnumProperty model = new OuterObjectWithEnumProperty(); + + /** + * Model tests for OuterObjectWithEnumProperty + */ + @Test + public void testOuterObjectWithEnumProperty() { + // TODO: test OuterObjectWithEnumProperty + } + + /** + * Test the property 'value' + */ + @Test + public void valueTest() { + // TODO: test value + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/PetTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/PetTest.java new file mode 100644 index 0000000000..6de3524dcc --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/PetTest.java @@ -0,0 +1,94 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java new file mode 100644 index 0000000000..332a1b116c --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ReadOnlyFirst + */ +public class ReadOnlyFirstTest { + private final ReadOnlyFirst model = new ReadOnlyFirst(); + + /** + * Model tests for ReadOnlyFirst + */ + @Test + public void testReadOnlyFirst() { + // TODO: test ReadOnlyFirst + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'baz' + */ + @Test + public void bazTest() { + // TODO: test baz + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/SingleRefTypeTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/SingleRefTypeTest.java new file mode 100644 index 0000000000..82f51f683d --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/SingleRefTypeTest.java @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for SingleRefType + */ +public class SingleRefTypeTest { + /** + * Model tests for SingleRefType + */ + @Test + public void testSingleRefType() { + // TODO: test SingleRefType + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java new file mode 100644 index 0000000000..e1d4d10b94 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for SpecialModelName + */ +public class SpecialModelNameTest { + private final SpecialModelName model = new SpecialModelName(); + + /** + * Model tests for SpecialModelName + */ + @Test + public void testSpecialModelName() { + // TODO: test SpecialModelName + } + + /** + * Test the property '$specialPropertyName' + */ + @Test + public void $specialPropertyNameTest() { + // TODO: test $specialPropertyName + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/TagTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/TagTest.java new file mode 100644 index 0000000000..ff32e6c114 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/TagTest.java @@ -0,0 +1,55 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/UserTest.java b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/UserTest.java new file mode 100644 index 0000000000..32404a5e38 --- /dev/null +++ b/samples/client/petstore/java-helidon-client/se/src/test/java/org/openapitools/client/model/UserTest.java @@ -0,0 +1,103 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + +} diff --git a/samples/client/petstore/java/apache-httpclient/api/openapi.yaml b/samples/client/petstore/java/apache-httpclient/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/apache-httpclient/api/openapi.yaml +++ b/samples/client/petstore/java/apache-httpclient/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java index a6e7049085..43308167ad 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java @@ -65,6 +65,7 @@ import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.nio.file.Paths; @@ -707,7 +708,14 @@ public class ApiClient extends JavaTimeFormatter { } else if (value instanceof byte[]) { multiPartBuilder.addBinaryBody(paramEntry.getKey(), (byte[]) value); } else { - multiPartBuilder.addTextBody(paramEntry.getKey(), parameterToString(paramEntry.getValue())); + Charset charset = contentType.getCharset(); + if (charset != null) { + ContentType customContentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset); + multiPartBuilder.addTextBody(paramEntry.getKey(), parameterToString(paramEntry.getValue()), + customContentType); + } else { + multiPartBuilder.addTextBody(paramEntry.getKey(), parameterToString(paramEntry.getValue())); + } } } return multiPartBuilder.build(); @@ -716,11 +724,7 @@ public class ApiClient extends JavaTimeFormatter { for (Entry paramEntry : formParams.entrySet()) { formValues.add(new BasicNameValuePair(paramEntry.getKey(), parameterToString(paramEntry.getValue()))); } - try { - return new UrlEncodedFormEntity(formValues); - } catch (UnsupportedEncodingException e) { - throw new ApiException(e); - } + return new UrlEncodedFormEntity(formValues, contentType.getCharset()); } else { // Handle files with unknown content type if (obj instanceof File) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 957cc2b807..0cbfacebcd 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index e5162ab461..8192afcfd8 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 98ea69f7f4..266eee7e60 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 22fe0a8e0f..b205a2ff70 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -80,7 +80,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 3a87682ab4..d2cb247fe9 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index c6da3609d4..9a15f92689 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index ec6a2360fe..f0e0d637a6 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 3ba318c8ac..f1a56ef222 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Animal.java index be898d61d2..fb3560d3ef 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Animal.java @@ -57,7 +57,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 395b4c4d40..84ecf3c60c 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 81437ecc35..5a740ed59d 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayTest.java index 29e8fde2a2..f649ccdafc 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/BigCat.java index c1685041c0..31311ed0c5 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,7 +85,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/BigCatAllOf.java index fb358abee3..f4390e9b32 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -76,7 +76,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Capitalization.java index 09da87c767..75dab11565 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Cat.java index b5408a8315..7269e26ddd 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Cat.java @@ -50,7 +50,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/CatAllOf.java index 9af537be46..6a40fe1cc2 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -37,7 +37,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Category.java index 9ecb9793f8..95ba07594c 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ClassModel.java index 02a70314cf..c112b0dbfd 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Client.java index c0e1209608..ee1f6eb2b4 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Dog.java index bf9838d6f6..193f040fc5 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Dog.java @@ -46,7 +46,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/DogAllOf.java index 22f41e01ea..d37bc6d62a 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -37,7 +37,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/EnumArrays.java index f5b42b0b87..216f767fef 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -112,7 +112,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/EnumTest.java index 12b3b19a57..6fe3181370 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/EnumTest.java @@ -198,7 +198,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 43c10d8609..ae5247c54e 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FormatTest.java index cef5858fe1..f1aa6b0859 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FormatTest.java @@ -94,7 +94,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index a79abdb993..45c377620b 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -41,7 +41,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/MapTest.java index d50e30db74..3ee0b0ac01 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/MapTest.java @@ -85,7 +85,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 999c32ef2b..9f7331d1d2 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Model200Response.java index a05c698660..18596e30dc 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Model200Response.java @@ -42,7 +42,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 8c90d06494..9ab4b19971 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -45,7 +45,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelFile.java index 8647283641..cc921fbcb0 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelFile.java @@ -38,7 +38,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelList.java index 82abfba9e3..4dd418a4f5 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelList.java @@ -37,7 +37,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelReturn.java index 06fc43f8eb..35a0b1966d 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -38,7 +38,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Name.java index b263b708fe..56bae65fa6 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/NumberOnly.java index 4a268ea06e..fd7c5ed5d1 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Order.java index 4fccc19338..2f838cffbf 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Order.java @@ -94,7 +94,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/OuterComposite.java index 710f350303..324da496f6 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Pet.java index 27121c6969..908d26373e 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Pet.java @@ -100,7 +100,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 1130124051..6860d65e9c 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/SpecialModelName.java index 0d71d05b2e..6d199444c9 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -37,7 +37,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Tag.java index 25e766c40e..2a68d0029a 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index b4e2af9d25..543e5c031d 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -55,7 +55,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/TypeHolderExample.java index e550b7a421..2b40049239 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -59,7 +59,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/User.java index a289c89f5e..fe0c60b880 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/XmlItem.java index f038a2d4b9..597c1b98a9 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/XmlItem.java @@ -151,7 +151,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/feign-no-nullable/api/openapi.yaml b/samples/client/petstore/java/feign-no-nullable/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/feign-no-nullable/api/openapi.yaml +++ b/samples/client/petstore/java/feign-no-nullable/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/auth/OAuth.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/auth/OAuth.java index 921ee0a65c..fe2eb729aa 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/auth/OAuth.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/auth/OAuth.java @@ -77,7 +77,7 @@ public abstract class OAuth implements RequestInterceptor { public synchronized String getAccessToken() { // If first time, get the token - if (expirationTimeSeconds == null || System.currentTimeMillis() >= expirationTimeSeconds) { + if (expirationTimeSeconds == null || System.currentTimeMillis() >= expirationTimeSeconds * MILLIS_PER_SECOND) { updateAccessToken(); } return accessToken; diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 13929e3ca3..7bfaba9c6f 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 92454a75cd..cb8449f941 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -40,7 +40,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index c8c9afbae3..3f12a70c4e 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index bf27e303a9..36816a4e61 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -81,7 +81,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 0fd004f893..4166dfdabd 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index 8c1b5aa090..6c774b7489 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -40,7 +40,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index 7e957c981c..fcf23cae37 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 505a004ae4..3700c25be3 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Animal.java index 1a1de5a9a5..0f16d56d0f 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Animal.java @@ -58,7 +58,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 2cf5c494d2..82f212d06b 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -40,7 +40,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index be1aca1d6d..948829073e 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -40,7 +40,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayTest.java index 8c2c4f676e..34c60bbd6b 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -48,7 +48,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/BigCat.java index 79c9519727..3dd5d093da 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/BigCat.java @@ -86,7 +86,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/BigCatAllOf.java index a9c8ebe58d..08c049e39f 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -77,7 +77,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Capitalization.java index 738b70559c..fa38b83e18 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Capitalization.java @@ -57,7 +57,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Cat.java index bf472e082c..aeba302054 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Cat.java @@ -51,7 +51,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/CatAllOf.java index 31b195fd94..f4819fb0bb 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -38,7 +38,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Category.java index fce1efca6a..f96baeadbd 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Category.java @@ -41,7 +41,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ClassModel.java index b043ba52d3..803a4d8347 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ClassModel.java @@ -38,7 +38,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Client.java index e2a0f312f2..ab483956c7 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Client.java @@ -37,7 +37,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Dog.java index a9c8728549..4fc1d940d2 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Dog.java @@ -47,7 +47,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/DogAllOf.java index e29726d4f9..ae09c5a409 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -38,7 +38,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/EnumArrays.java index b2727221b3..be9aeebee5 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -113,7 +113,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/EnumTest.java index c1eb287075..cb57865672 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/EnumTest.java @@ -199,7 +199,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/File.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/File.java index dd3513af76..d3443ca554 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/File.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/File.java @@ -38,7 +38,7 @@ public class File { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public File() { + public File() { } public File sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 21d41b6f2d..ff032606cf 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -44,7 +44,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass file(File file) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java index 862c1888ca..30d707e353 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java @@ -95,7 +95,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index 010417a790..1ab4b1557a 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -42,7 +42,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/MapTest.java index 38522f2aec..6ac75a7f21 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/MapTest.java @@ -86,7 +86,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 8ac5d5b103..f9ea3fb9fd 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -50,7 +50,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Model200Response.java index fec50d3906..eb1c737b91 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Model200Response.java @@ -43,7 +43,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 2fdb2549c1..f3ee28e8b0 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -46,7 +46,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelList.java index ea6f663582..1fbabc9308 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelList.java @@ -38,7 +38,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelReturn.java index ae6d5867df..749ce16fc9 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -39,7 +39,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Name.java index 16a3d8b0a1..039393c772 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Name.java @@ -50,7 +50,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/NumberOnly.java index 66b80c1b33..9f1bd9f512 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -38,7 +38,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Order.java index d2bd11d92c..4a34907a12 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Order.java @@ -95,7 +95,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/OuterComposite.java index cacdb6dd77..ce56456152 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -46,7 +46,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Pet.java index bdb99b4a94..a36a08dacb 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Pet.java @@ -101,7 +101,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 822b1addd3..765a5905e1 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -41,7 +41,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/SpecialModelName.java index 71c9790203..df892c57d8 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -38,7 +38,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Tag.java index 0daa611523..eeeebd923a 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/Tag.java @@ -41,7 +41,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index f9e5852a9d..f7f308663d 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -56,7 +56,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderExample.java index ec6973375e..8a0c092d5f 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -60,7 +60,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/User.java index 9eebcbe068..11624a3143 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/User.java @@ -65,7 +65,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/XmlItem.java index 249cd62cc8..f29f59916e 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/XmlItem.java @@ -152,7 +152,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/feign/api/openapi.yaml b/samples/client/petstore/java/feign/api/openapi.yaml index ccf94d1ff5..f54c98c7f7 100644 --- a/samples/client/petstore/java/feign/api/openapi.yaml +++ b/samples/client/petstore/java/feign/api/openapi.yaml @@ -98,6 +98,21 @@ paths: servers: - url: http://petstore.swagger.io/v2 - url: http://path-server-test.petstore.local/v2 + - description: test server with variables + url: "http://{server}.swagger.io:{port}/v2" + variables: + server: + default: petstore + description: target server + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" /pet/findByStatus: get: description: Multiple status values can be provided with comma separated strings @@ -2117,11 +2132,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/auth/OAuth.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/auth/OAuth.java index 921ee0a65c..fe2eb729aa 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/auth/OAuth.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/auth/OAuth.java @@ -77,7 +77,7 @@ public abstract class OAuth implements RequestInterceptor { public synchronized String getAccessToken() { // If first time, get the token - if (expirationTimeSeconds == null || System.currentTimeMillis() >= expirationTimeSeconds) { + if (expirationTimeSeconds == null || System.currentTimeMillis() >= expirationTimeSeconds * MILLIS_PER_SECOND) { updateAccessToken(); } return accessToken; diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index dc1cf1c448..ef8a8cf101 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -42,7 +42,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP_OF_MAP_PROPERTY = "map_of_map_property"; private Map> mapOfMapProperty = null; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java index 6bde2cae30..485e451773 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java @@ -23,10 +23,6 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.openapitools.client.model.SingleRefType; -import org.openapitools.jackson.nullable.JsonNullable; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; @@ -43,9 +39,9 @@ public class AllOfWithSingleRef { private String username; public static final String JSON_PROPERTY_SINGLE_REF_TYPE = "SingleRefType"; - private JsonNullable singleRefType = JsonNullable.undefined(); + private SingleRefType singleRefType; - public AllOfWithSingleRef() { + public AllOfWithSingleRef() { } public AllOfWithSingleRef username(String username) { @@ -76,8 +72,8 @@ public class AllOfWithSingleRef { public AllOfWithSingleRef singleRefType(SingleRefType singleRefType) { - this.singleRefType = JsonNullable.of(singleRefType); + this.singleRefType = singleRefType; return this; } @@ -87,26 +83,18 @@ public class AllOfWithSingleRef { **/ @javax.annotation.Nullable @ApiModelProperty(value = "") - @JsonIgnore - - public SingleRefType getSingleRefType() { - return singleRefType.orElse(null); - } - @JsonProperty(JSON_PROPERTY_SINGLE_REF_TYPE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public JsonNullable getSingleRefType_JsonNullable() { + public SingleRefType getSingleRefType() { return singleRefType; } - - @JsonProperty(JSON_PROPERTY_SINGLE_REF_TYPE) - public void setSingleRefType_JsonNullable(JsonNullable singleRefType) { - this.singleRefType = singleRefType; - } + + @JsonProperty(JSON_PROPERTY_SINGLE_REF_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setSingleRefType(SingleRefType singleRefType) { - this.singleRefType = JsonNullable.of(singleRefType); + this.singleRefType = singleRefType; } @@ -120,23 +108,12 @@ public class AllOfWithSingleRef { } AllOfWithSingleRef allOfWithSingleRef = (AllOfWithSingleRef) o; return Objects.equals(this.username, allOfWithSingleRef.username) && - equalsNullable(this.singleRefType, allOfWithSingleRef.singleRefType); - } - - private static boolean equalsNullable(JsonNullable a, JsonNullable b) { - return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + Objects.equals(this.singleRefType, allOfWithSingleRef.singleRefType); } @Override public int hashCode() { - return Objects.hash(username, hashCodeNullable(singleRefType)); - } - - private static int hashCodeNullable(JsonNullable a) { - if (a == null) { - return 1; - } - return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + return Objects.hash(username, singleRefType); } @Override diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Animal.java index 6f1a5d6fd8..2a6e07f644 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Animal.java @@ -55,7 +55,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 395b4c4d40..84ecf3c60c 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 81437ecc35..5a740ed59d 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayTest.java index 29e8fde2a2..f649ccdafc 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Capitalization.java index 09da87c767..75dab11565 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Cat.java index 5b89385b69..d7bcd24a8e 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Cat.java @@ -46,7 +46,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/CatAllOf.java index 8a43bc0fbb..d2b1ff78d2 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -37,7 +37,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Category.java index 9ecb9793f8..95ba07594c 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ClassModel.java index 02a70314cf..c112b0dbfd 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Client.java index c0e1209608..ee1f6eb2b4 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/DeprecatedObject.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/DeprecatedObject.java index 43b0f5f764..c35b4fc5e8 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/DeprecatedObject.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/DeprecatedObject.java @@ -38,7 +38,7 @@ public class DeprecatedObject { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public DeprecatedObject() { + public DeprecatedObject() { } public DeprecatedObject name(String name) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Dog.java index bf9838d6f6..193f040fc5 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Dog.java @@ -46,7 +46,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/DogAllOf.java index 22f41e01ea..d37bc6d62a 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -37,7 +37,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumArrays.java index f5b42b0b87..216f767fef 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -112,7 +112,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumTest.java index a33250dbb6..17a7411cca 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumTest.java @@ -217,7 +217,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM_INTEGER_DEFAULT_VALUE = "outerEnumIntegerDefaultValue"; private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/File.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/File.java index 0455b92774..a5b0a7dfbf 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/File.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/File.java @@ -37,7 +37,7 @@ public class File { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public File() { + public File() { } public File sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 6137dbb628..0bbb290b3f 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass file(File file) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Foo.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Foo.java index fe477338c4..3029990782 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Foo.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Foo.java @@ -36,7 +36,7 @@ public class Foo { public static final String JSON_PROPERTY_BAR = "bar"; private String bar = "bar"; - public Foo() { + public Foo() { } public Foo bar(String bar) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java index 0c2f4bdc6c..d01668ba67 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java @@ -38,7 +38,7 @@ public class FooGetDefaultResponse { public static final String JSON_PROPERTY_STRING = "string"; private Foo string; - public FooGetDefaultResponse() { + public FooGetDefaultResponse() { } public FooGetDefaultResponse string(Foo string) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FormatTest.java index f1ef660aa6..38b3edf010 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FormatTest.java @@ -102,7 +102,7 @@ public class FormatTest { public static final String JSON_PROPERTY_PATTERN_WITH_DIGITS_AND_DELIMITER = "pattern_with_digits_and_delimiter"; private String patternWithDigitsAndDelimiter; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index a79abdb993..45c377620b 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -41,7 +41,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HealthCheckResult.java index 19f2227d84..e6889f1a89 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HealthCheckResult.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -41,7 +41,7 @@ public class HealthCheckResult { public static final String JSON_PROPERTY_NULLABLE_MESSAGE = "NullableMessage"; private JsonNullable nullableMessage = JsonNullable.undefined(); - public HealthCheckResult() { + public HealthCheckResult() { } public HealthCheckResult nullableMessage(String nullableMessage) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/MapTest.java index d50e30db74..3ee0b0ac01 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/MapTest.java @@ -85,7 +85,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 999c32ef2b..9f7331d1d2 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Model200Response.java index a05c698660..18596e30dc 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Model200Response.java @@ -42,7 +42,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 8c90d06494..9ab4b19971 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -45,7 +45,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelList.java index 82abfba9e3..4dd418a4f5 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelList.java @@ -37,7 +37,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelReturn.java index 06fc43f8eb..35a0b1966d 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -38,7 +38,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Name.java index b263b708fe..56bae65fa6 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NullableClass.java index 215add9f0c..3c50057ce7 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NullableClass.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NullableClass.java @@ -91,7 +91,8 @@ public class NullableClass extends HashMap { public static final String JSON_PROPERTY_OBJECT_ITEMS_NULLABLE = "object_items_nullable"; private Map objectItemsNullable = null; - public NullableClass() { + public NullableClass() { + } public NullableClass integerProp(Integer integerProp) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NumberOnly.java index 4a268ea06e..fd7c5ed5d1 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java index 3831a4d330..fc4da32d31 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -52,7 +52,7 @@ public class ObjectWithDeprecatedFields { public static final String JSON_PROPERTY_BARS = "bars"; private List bars = null; - public ObjectWithDeprecatedFields() { + public ObjectWithDeprecatedFields() { } public ObjectWithDeprecatedFields uuid(String uuid) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Order.java index 1e36e84199..3c9176d2be 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Order.java @@ -94,7 +94,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/OuterComposite.java index 4a82ead06c..e422b2a8d8 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java index 1669551078..fd303579d7 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java @@ -37,7 +37,7 @@ public class OuterObjectWithEnumProperty { public static final String JSON_PROPERTY_VALUE = "value"; private OuterEnumInteger value; - public OuterObjectWithEnumProperty() { + public OuterObjectWithEnumProperty() { } public OuterObjectWithEnumProperty value(OuterEnumInteger value) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Pet.java index 27121c6969..908d26373e 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Pet.java @@ -100,7 +100,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 1130124051..6860d65e9c 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/SpecialModelName.java index 95d47212ac..7f2a25923c 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -37,7 +37,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Tag.java index 25e766c40e..2a68d0029a 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/User.java index a289c89f5e..fe0c60b880 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/google-api-client/api/openapi.yaml b/samples/client/petstore/java/google-api-client/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/google-api-client/api/openapi.yaml +++ b/samples/client/petstore/java/google-api-client/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 957cc2b807..0cbfacebcd 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index e5162ab461..8192afcfd8 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 98ea69f7f4..266eee7e60 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 22fe0a8e0f..b205a2ff70 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -80,7 +80,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 3a87682ab4..d2cb247fe9 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index c6da3609d4..9a15f92689 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index ec6a2360fe..f0e0d637a6 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 3ba318c8ac..f1a56ef222 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Animal.java index be898d61d2..fb3560d3ef 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Animal.java @@ -57,7 +57,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 395b4c4d40..84ecf3c60c 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 81437ecc35..5a740ed59d 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayTest.java index 29e8fde2a2..f649ccdafc 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/BigCat.java index c1685041c0..31311ed0c5 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,7 +85,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/BigCatAllOf.java index fb358abee3..f4390e9b32 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -76,7 +76,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Capitalization.java index 09da87c767..75dab11565 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Cat.java index b5408a8315..7269e26ddd 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Cat.java @@ -50,7 +50,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/CatAllOf.java index 9af537be46..6a40fe1cc2 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -37,7 +37,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Category.java index 9ecb9793f8..95ba07594c 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ClassModel.java index 02a70314cf..c112b0dbfd 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Client.java index c0e1209608..ee1f6eb2b4 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Dog.java index bf9838d6f6..193f040fc5 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Dog.java @@ -46,7 +46,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/DogAllOf.java index 22f41e01ea..d37bc6d62a 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -37,7 +37,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/EnumArrays.java index f5b42b0b87..216f767fef 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -112,7 +112,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/EnumTest.java index 12b3b19a57..6fe3181370 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/EnumTest.java @@ -198,7 +198,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 43c10d8609..ae5247c54e 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FormatTest.java index cef5858fe1..f1aa6b0859 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FormatTest.java @@ -94,7 +94,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index a79abdb993..45c377620b 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -41,7 +41,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/MapTest.java index d50e30db74..3ee0b0ac01 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/MapTest.java @@ -85,7 +85,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 999c32ef2b..9f7331d1d2 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Model200Response.java index a05c698660..18596e30dc 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Model200Response.java @@ -42,7 +42,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 8c90d06494..9ab4b19971 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -45,7 +45,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelFile.java index 8647283641..cc921fbcb0 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelFile.java @@ -38,7 +38,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelList.java index 82abfba9e3..4dd418a4f5 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelList.java @@ -37,7 +37,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelReturn.java index 06fc43f8eb..35a0b1966d 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -38,7 +38,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Name.java index b263b708fe..56bae65fa6 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/NumberOnly.java index 4a268ea06e..fd7c5ed5d1 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Order.java index 4fccc19338..2f838cffbf 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Order.java @@ -94,7 +94,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/OuterComposite.java index 710f350303..324da496f6 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Pet.java index 27121c6969..908d26373e 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Pet.java @@ -100,7 +100,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 1130124051..6860d65e9c 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/SpecialModelName.java index 0d71d05b2e..6d199444c9 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -37,7 +37,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Tag.java index 25e766c40e..2a68d0029a 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index b4e2af9d25..543e5c031d 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -55,7 +55,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/TypeHolderExample.java index e550b7a421..2b40049239 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -59,7 +59,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/User.java index a289c89f5e..fe0c60b880 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/XmlItem.java index f038a2d4b9..597c1b98a9 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/XmlItem.java @@ -151,7 +151,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/jersey1/api/openapi.yaml b/samples/client/petstore/java/jersey1/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/jersey1/api/openapi.yaml +++ b/samples/client/petstore/java/jersey1/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 957cc2b807..0cbfacebcd 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index e5162ab461..8192afcfd8 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 98ea69f7f4..266eee7e60 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 22fe0a8e0f..b205a2ff70 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -80,7 +80,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 3a87682ab4..d2cb247fe9 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index c6da3609d4..9a15f92689 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index ec6a2360fe..f0e0d637a6 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 3ba318c8ac..f1a56ef222 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Animal.java index be898d61d2..fb3560d3ef 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Animal.java @@ -57,7 +57,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 395b4c4d40..84ecf3c60c 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 81437ecc35..5a740ed59d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayTest.java index 29e8fde2a2..f649ccdafc 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/BigCat.java index c1685041c0..31311ed0c5 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,7 +85,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/BigCatAllOf.java index fb358abee3..f4390e9b32 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -76,7 +76,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Capitalization.java index 09da87c767..75dab11565 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Cat.java index b5408a8315..7269e26ddd 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Cat.java @@ -50,7 +50,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/CatAllOf.java index 9af537be46..6a40fe1cc2 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -37,7 +37,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Category.java index 9ecb9793f8..95ba07594c 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ClassModel.java index 02a70314cf..c112b0dbfd 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Client.java index c0e1209608..ee1f6eb2b4 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Dog.java index bf9838d6f6..193f040fc5 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Dog.java @@ -46,7 +46,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/DogAllOf.java index 22f41e01ea..d37bc6d62a 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -37,7 +37,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/EnumArrays.java index f5b42b0b87..216f767fef 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -112,7 +112,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/EnumTest.java index 12b3b19a57..6fe3181370 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/EnumTest.java @@ -198,7 +198,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 43c10d8609..ae5247c54e 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/FormatTest.java index cef5858fe1..f1aa6b0859 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/FormatTest.java @@ -94,7 +94,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index a79abdb993..45c377620b 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -41,7 +41,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/MapTest.java index d50e30db74..3ee0b0ac01 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/MapTest.java @@ -85,7 +85,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 999c32ef2b..9f7331d1d2 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Model200Response.java index a05c698660..18596e30dc 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Model200Response.java @@ -42,7 +42,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 8c90d06494..9ab4b19971 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -45,7 +45,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelFile.java index 8647283641..cc921fbcb0 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelFile.java @@ -38,7 +38,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelList.java index 82abfba9e3..4dd418a4f5 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelList.java @@ -37,7 +37,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelReturn.java index 06fc43f8eb..35a0b1966d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -38,7 +38,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Name.java index b263b708fe..56bae65fa6 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/NumberOnly.java index 4a268ea06e..fd7c5ed5d1 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Order.java index 4fccc19338..2f838cffbf 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Order.java @@ -94,7 +94,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/OuterComposite.java index 710f350303..324da496f6 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Pet.java index 27121c6969..908d26373e 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Pet.java @@ -100,7 +100,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 1130124051..6860d65e9c 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/SpecialModelName.java index 0d71d05b2e..6d199444c9 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -37,7 +37,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Tag.java index 25e766c40e..2a68d0029a 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index b4e2af9d25..543e5c031d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -55,7 +55,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/TypeHolderExample.java index e550b7a421..2b40049239 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -59,7 +59,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/User.java index a289c89f5e..fe0c60b880 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/XmlItem.java index f038a2d4b9..597c1b98a9 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/model/XmlItem.java @@ -151,7 +151,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/jersey2-java8-localdatetime/api/openapi.yaml b/samples/client/petstore/java/jersey2-java8-localdatetime/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/jersey2-java8-localdatetime/api/openapi.yaml +++ b/samples/client/petstore/java/jersey2-java8-localdatetime/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/jersey2-java8/api/openapi.yaml b/samples/client/petstore/java/jersey2-java8/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/jersey2-java8/api/openapi.yaml +++ b/samples/client/petstore/java/jersey2-java8/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/jersey3/api/openapi.yaml b/samples/client/petstore/java/jersey3/api/openapi.yaml index 1db8f0a9d1..bd4e3fa22b 100644 --- a/samples/client/petstore/java/jersey3/api/openapi.yaml +++ b/samples/client/petstore/java/jersey3/api/openapi.yaml @@ -2286,11 +2286,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null ChildCat_allOf: properties: name: @@ -2302,6 +2304,7 @@ components: type: string x-enum-as-string: true type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/native-async/api/openapi.yaml b/samples/client/petstore/java/native-async/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/native-async/api/openapi.yaml +++ b/samples/client/petstore/java/native-async/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/native-async/build.gradle b/samples/client/petstore/java/native-async/build.gradle index 60dc3e1e95..d69b1d8078 100644 --- a/samples/client/petstore/java/native-async/build.gradle +++ b/samples/client/petstore/java/native-async/build.gradle @@ -63,7 +63,7 @@ artifacts { ext { swagger_annotations_version = "1.5.22" - jackson_version = "2.13.0" + jackson_version = "2.13.4" jakarta_annotation_version = "1.3.5" junit_version = "4.13.2" } diff --git a/samples/client/petstore/java/native-async/pom.xml b/samples/client/petstore/java/native-async/pom.xml index 1770376556..dcc052abc0 100644 --- a/samples/client/petstore/java/native-async/pom.xml +++ b/samples/client/petstore/java/native-async/pom.xml @@ -214,7 +214,7 @@ 1.5.22 11 11 - 2.13.0 + 2.13.4 0.2.3 1.3.5 4.13.2 diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index 4183097992..4b78e7ac2e 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -13,7 +13,6 @@ package org.openapitools.client.model; -import org.openapitools.client.ApiException; import java.util.Objects; import java.lang.reflect.Type; import java.util.Map; diff --git a/samples/client/petstore/java/native/api/openapi.yaml b/samples/client/petstore/java/native/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/native/api/openapi.yaml +++ b/samples/client/petstore/java/native/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/native/build.gradle b/samples/client/petstore/java/native/build.gradle index 60dc3e1e95..d69b1d8078 100644 --- a/samples/client/petstore/java/native/build.gradle +++ b/samples/client/petstore/java/native/build.gradle @@ -63,7 +63,7 @@ artifacts { ext { swagger_annotations_version = "1.5.22" - jackson_version = "2.13.0" + jackson_version = "2.13.4" jakarta_annotation_version = "1.3.5" junit_version = "4.13.2" } diff --git a/samples/client/petstore/java/native/pom.xml b/samples/client/petstore/java/native/pom.xml index 1770376556..dcc052abc0 100644 --- a/samples/client/petstore/java/native/pom.xml +++ b/samples/client/petstore/java/native/pom.xml @@ -214,7 +214,7 @@ 1.5.22 11 11 - 2.13.0 + 2.13.4 0.2.3 1.3.5 4.13.2 diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index 4183097992..4b78e7ac2e 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -13,7 +13,6 @@ package org.openapitools.client.model; -import org.openapitools.client.ApiException; import java.util.Objects; import java.lang.reflect.Type; import java.util.Map; diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java index e7332008c0..8d71d33a95 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java @@ -982,6 +982,8 @@ public class ApiClient { content = null; } return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create(MediaType.parse(contentType), (String) obj); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 7e27ea5e65..f0821e6d22 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -53,7 +53,7 @@ public class AdditionalPropertiesAnyType { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { } public AdditionalPropertiesAnyType name(String name) { @@ -138,9 +138,7 @@ public class AdditionalPropertiesAnyType { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesAnyType.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesAnyType.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesAnyType is not found in the empty JSON string", AdditionalPropertiesAnyType.openapiRequiredFields.toString())); } } @@ -152,7 +150,7 @@ public class AdditionalPropertiesAnyType { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesAnyType` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 4a5b73a605..598684e426 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -54,7 +54,7 @@ public class AdditionalPropertiesArray { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { } public AdditionalPropertiesArray name(String name) { @@ -139,9 +139,7 @@ public class AdditionalPropertiesArray { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesArray.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesArray.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesArray is not found in the empty JSON string", AdditionalPropertiesArray.openapiRequiredFields.toString())); } } @@ -153,7 +151,7 @@ public class AdditionalPropertiesArray { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesArray` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 070f06150e..c3b5720d76 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -53,7 +53,7 @@ public class AdditionalPropertiesBoolean { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { } public AdditionalPropertiesBoolean name(String name) { @@ -138,9 +138,7 @@ public class AdditionalPropertiesBoolean { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesBoolean.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesBoolean.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesBoolean is not found in the empty JSON string", AdditionalPropertiesBoolean.openapiRequiredFields.toString())); } } @@ -152,7 +150,7 @@ public class AdditionalPropertiesBoolean { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesBoolean` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 02c2ac7821..dd6a62ee0c 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -97,7 +97,7 @@ public class AdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_ANYTYPE3) private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { @@ -506,9 +506,7 @@ public class AdditionalPropertiesClass { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesClass is not found in the empty JSON string", AdditionalPropertiesClass.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index b22e411892..ee165d80b9 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -53,7 +53,7 @@ public class AdditionalPropertiesInteger { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { } public AdditionalPropertiesInteger name(String name) { @@ -138,9 +138,7 @@ public class AdditionalPropertiesInteger { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesInteger.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesInteger.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesInteger is not found in the empty JSON string", AdditionalPropertiesInteger.openapiRequiredFields.toString())); } } @@ -152,7 +150,7 @@ public class AdditionalPropertiesInteger { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesInteger` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index 968eee748c..717fbfada1 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -54,7 +54,7 @@ public class AdditionalPropertiesNumber { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { } public AdditionalPropertiesNumber name(String name) { @@ -139,9 +139,7 @@ public class AdditionalPropertiesNumber { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesNumber.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesNumber.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesNumber is not found in the empty JSON string", AdditionalPropertiesNumber.openapiRequiredFields.toString())); } } @@ -153,7 +151,7 @@ public class AdditionalPropertiesNumber { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesNumber` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index f50e8bd73b..ab3903887b 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -54,7 +54,7 @@ public class AdditionalPropertiesObject { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { } public AdditionalPropertiesObject name(String name) { @@ -139,9 +139,7 @@ public class AdditionalPropertiesObject { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesObject.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesObject.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesObject is not found in the empty JSON string", AdditionalPropertiesObject.openapiRequiredFields.toString())); } } @@ -153,7 +151,7 @@ public class AdditionalPropertiesObject { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesObject` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 2269587439..8e202f0b3c 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -53,7 +53,7 @@ public class AdditionalPropertiesString { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { } public AdditionalPropertiesString name(String name) { @@ -138,9 +138,7 @@ public class AdditionalPropertiesString { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesString.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesString.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesString is not found in the empty JSON string", AdditionalPropertiesString.openapiRequiredFields.toString())); } } @@ -152,7 +150,7 @@ public class AdditionalPropertiesString { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesString` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Animal.java index f49c160b1b..6544aafe65 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Animal.java @@ -60,7 +60,7 @@ public class Animal { @SerializedName(SERIALIZED_NAME_COLOR) private String color = "red"; - public Animal() { + public Animal() { this.className = this.getClass().getSimpleName(); } @@ -173,9 +173,7 @@ public class Animal { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Animal.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Animal.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Animal is not found in the empty JSON string", Animal.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index b2b1a6b246..bb2bc0b8eb 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -56,7 +56,7 @@ public class ArrayOfArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_NUMBER) private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { @@ -149,9 +149,7 @@ public class ArrayOfArrayOfNumberOnly { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfArrayOfNumberOnly is not found in the empty JSON string", ArrayOfArrayOfNumberOnly.openapiRequiredFields.toString())); } } @@ -164,7 +162,7 @@ public class ArrayOfArrayOfNumberOnly { } } // ensure the json data is an array - if (jsonObj.get("ArrayArrayNumber") != null && !jsonObj.get("ArrayArrayNumber").isJsonArray()) { + if (!jsonObj.get("ArrayArrayNumber").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `ArrayArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayArrayNumber").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 6d17c1826d..ead8043228 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -56,7 +56,7 @@ public class ArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_NUMBER) private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { @@ -149,9 +149,7 @@ public class ArrayOfNumberOnly { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfNumberOnly is not found in the empty JSON string", ArrayOfNumberOnly.openapiRequiredFields.toString())); } } @@ -164,7 +162,7 @@ public class ArrayOfNumberOnly { } } // ensure the json data is an array - if (jsonObj.get("ArrayNumber") != null && !jsonObj.get("ArrayNumber").isJsonArray()) { + if (!jsonObj.get("ArrayNumber").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `ArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayNumber").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayTest.java index 51d01d2a38..fcbe151877 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -64,7 +64,7 @@ public class ArrayTest { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { @@ -225,9 +225,7 @@ public class ArrayTest { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayTest is not found in the empty JSON string", ArrayTest.openapiRequiredFields.toString())); } } @@ -240,15 +238,15 @@ public class ArrayTest { } } // ensure the json data is an array - if (jsonObj.get("array_of_string") != null && !jsonObj.get("array_of_string").isJsonArray()) { + if (!jsonObj.get("array_of_string").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_of_string` to be an array in the JSON string but got `%s`", jsonObj.get("array_of_string").toString())); } // ensure the json data is an array - if (jsonObj.get("array_array_of_integer") != null && !jsonObj.get("array_array_of_integer").isJsonArray()) { + if (!jsonObj.get("array_array_of_integer").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_array_of_integer` to be an array in the JSON string but got `%s`", jsonObj.get("array_array_of_integer").toString())); } // ensure the json data is an array - if (jsonObj.get("array_array_of_model") != null && !jsonObj.get("array_array_of_model").isJsonArray()) { + if (!jsonObj.get("array_array_of_model").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_array_of_model` to be an array in the JSON string but got `%s`", jsonObj.get("array_array_of_model").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCat.java index b6a249177e..e1891f7433 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCat.java @@ -105,7 +105,7 @@ public class BigCat extends Cat { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCat() { + public BigCat() { this.className = this.getClass().getSimpleName(); } @@ -197,9 +197,7 @@ public class BigCat extends Cat { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (BigCat.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!BigCat.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in BigCat is not found in the empty JSON string", BigCat.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCatAllOf.java index ba8b6753c1..dfd9b1cfa8 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -104,7 +104,7 @@ public class BigCatAllOf { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { @@ -189,9 +189,7 @@ public class BigCatAllOf { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (BigCatAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!BigCatAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in BigCatAllOf is not found in the empty JSON string", BigCatAllOf.openapiRequiredFields.toString())); } } @@ -203,7 +201,7 @@ public class BigCatAllOf { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `BigCatAllOf` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("kind") != null && !jsonObj.get("kind").isJsonPrimitive()) { + if ((jsonObj.get("kind") != null && !jsonObj.get("kind").isJsonNull()) && !jsonObj.get("kind").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `kind` to be a primitive type in the JSON string but got `%s`", jsonObj.get("kind").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Capitalization.java index 12a0f496eb..a21f9ddcd6 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Capitalization.java @@ -73,7 +73,7 @@ public class Capitalization { @SerializedName(SERIALIZED_NAME_A_T_T_N_A_M_E) private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { @@ -288,9 +288,7 @@ public class Capitalization { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Capitalization.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Capitalization.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Capitalization is not found in the empty JSON string", Capitalization.openapiRequiredFields.toString())); } } @@ -302,22 +300,22 @@ public class Capitalization { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Capitalization` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("smallCamel") != null && !jsonObj.get("smallCamel").isJsonPrimitive()) { + if ((jsonObj.get("smallCamel") != null && !jsonObj.get("smallCamel").isJsonNull()) && !jsonObj.get("smallCamel").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `smallCamel` to be a primitive type in the JSON string but got `%s`", jsonObj.get("smallCamel").toString())); } - if (jsonObj.get("CapitalCamel") != null && !jsonObj.get("CapitalCamel").isJsonPrimitive()) { + if ((jsonObj.get("CapitalCamel") != null && !jsonObj.get("CapitalCamel").isJsonNull()) && !jsonObj.get("CapitalCamel").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `CapitalCamel` to be a primitive type in the JSON string but got `%s`", jsonObj.get("CapitalCamel").toString())); } - if (jsonObj.get("small_Snake") != null && !jsonObj.get("small_Snake").isJsonPrimitive()) { + if ((jsonObj.get("small_Snake") != null && !jsonObj.get("small_Snake").isJsonNull()) && !jsonObj.get("small_Snake").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `small_Snake` to be a primitive type in the JSON string but got `%s`", jsonObj.get("small_Snake").toString())); } - if (jsonObj.get("Capital_Snake") != null && !jsonObj.get("Capital_Snake").isJsonPrimitive()) { + if ((jsonObj.get("Capital_Snake") != null && !jsonObj.get("Capital_Snake").isJsonNull()) && !jsonObj.get("Capital_Snake").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `Capital_Snake` to be a primitive type in the JSON string but got `%s`", jsonObj.get("Capital_Snake").toString())); } - if (jsonObj.get("SCA_ETH_Flow_Points") != null && !jsonObj.get("SCA_ETH_Flow_Points").isJsonPrimitive()) { + if ((jsonObj.get("SCA_ETH_Flow_Points") != null && !jsonObj.get("SCA_ETH_Flow_Points").isJsonNull()) && !jsonObj.get("SCA_ETH_Flow_Points").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `SCA_ETH_Flow_Points` to be a primitive type in the JSON string but got `%s`", jsonObj.get("SCA_ETH_Flow_Points").toString())); } - if (jsonObj.get("ATT_NAME") != null && !jsonObj.get("ATT_NAME").isJsonPrimitive()) { + if ((jsonObj.get("ATT_NAME") != null && !jsonObj.get("ATT_NAME").isJsonNull()) && !jsonObj.get("ATT_NAME").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `ATT_NAME` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ATT_NAME").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Cat.java index 1199be124c..d264d6a7af 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Cat.java @@ -55,7 +55,7 @@ public class Cat extends Animal { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public Cat() { + public Cat() { this.className = this.getClass().getSimpleName(); } @@ -146,9 +146,7 @@ public class Cat extends Animal { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Cat.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Cat.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Cat is not found in the empty JSON string", Cat.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/CatAllOf.java index 8a5201bcfc..f870e77805 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -53,7 +53,7 @@ public class CatAllOf { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { @@ -138,9 +138,7 @@ public class CatAllOf { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (CatAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!CatAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in CatAllOf is not found in the empty JSON string", CatAllOf.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Category.java index b8d5b31d26..c2ccf6ae91 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Category.java @@ -57,7 +57,7 @@ public class Category { @SerializedName(SERIALIZED_NAME_NAME) private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { @@ -169,9 +169,7 @@ public class Category { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Category.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Category.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Category is not found in the empty JSON string", Category.openapiRequiredFields.toString())); } } @@ -190,7 +188,7 @@ public class Category { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if (!jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ClassModel.java index bea305e83a..77e036027c 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ClassModel.java @@ -54,7 +54,7 @@ public class ClassModel { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { @@ -139,9 +139,7 @@ public class ClassModel { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ClassModel.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ClassModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ClassModel is not found in the empty JSON string", ClassModel.openapiRequiredFields.toString())); } } @@ -153,7 +151,7 @@ public class ClassModel { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ClassModel` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("_class") != null && !jsonObj.get("_class").isJsonPrimitive()) { + if ((jsonObj.get("_class") != null && !jsonObj.get("_class").isJsonNull()) && !jsonObj.get("_class").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `_class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("_class").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Client.java index f9e9b104d8..feac9e3039 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Client.java @@ -53,7 +53,7 @@ public class Client { @SerializedName(SERIALIZED_NAME_CLIENT) private String client; - public Client() { + public Client() { } public Client client(String client) { @@ -138,9 +138,7 @@ public class Client { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Client.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Client.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Client is not found in the empty JSON string", Client.openapiRequiredFields.toString())); } } @@ -152,7 +150,7 @@ public class Client { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Client` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("client") != null && !jsonObj.get("client").isJsonPrimitive()) { + if ((jsonObj.get("client") != null && !jsonObj.get("client").isJsonNull()) && !jsonObj.get("client").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `client` to be a primitive type in the JSON string but got `%s`", jsonObj.get("client").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Dog.java index a010c806be..849e96210e 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Dog.java @@ -54,7 +54,7 @@ public class Dog extends Animal { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public Dog() { + public Dog() { this.className = this.getClass().getSimpleName(); } @@ -145,9 +145,7 @@ public class Dog extends Animal { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Dog.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Dog.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Dog is not found in the empty JSON string", Dog.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/DogAllOf.java index a7feaacc9c..a061ea3c44 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -53,7 +53,7 @@ public class DogAllOf { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { @@ -138,9 +138,7 @@ public class DogAllOf { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (DogAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!DogAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in DogAllOf is not found in the empty JSON string", DogAllOf.openapiRequiredFields.toString())); } } @@ -152,7 +150,7 @@ public class DogAllOf { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DogAllOf` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonPrimitive()) { + if ((jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonNull()) && !jsonObj.get("breed").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `breed` to be a primitive type in the JSON string but got `%s`", jsonObj.get("breed").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumArrays.java index f7355cf6ec..31615796fb 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -153,7 +153,7 @@ public class EnumArrays { @SerializedName(SERIALIZED_NAME_ARRAY_ENUM) private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { @@ -272,9 +272,7 @@ public class EnumArrays { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (EnumArrays.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!EnumArrays.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in EnumArrays is not found in the empty JSON string", EnumArrays.openapiRequiredFields.toString())); } } @@ -286,11 +284,11 @@ public class EnumArrays { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `EnumArrays` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonPrimitive()) { + if ((jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) && !jsonObj.get("just_symbol").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `just_symbol` to be a primitive type in the JSON string but got `%s`", jsonObj.get("just_symbol").toString())); } // ensure the json data is an array - if (jsonObj.get("array_enum") != null && !jsonObj.get("array_enum").isJsonArray()) { + if (!jsonObj.get("array_enum").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_enum` to be an array in the JSON string but got `%s`", jsonObj.get("array_enum").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumTest.java index b9d11861df..7d1cf66794 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumTest.java @@ -262,7 +262,7 @@ public class EnumTest { @SerializedName(SERIALIZED_NAME_OUTER_ENUM) private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { @@ -452,9 +452,7 @@ public class EnumTest { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (EnumTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!EnumTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in EnumTest is not found in the empty JSON string", EnumTest.openapiRequiredFields.toString())); } } @@ -473,10 +471,10 @@ public class EnumTest { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonPrimitive()) { + if ((jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) && !jsonObj.get("enum_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string").toString())); } - if (jsonObj.get("enum_string_required") != null && !jsonObj.get("enum_string_required").isJsonPrimitive()) { + if (!jsonObj.get("enum_string_required").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string_required` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string_required").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 6ec83ac69d..4b1c10290b 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -60,7 +60,7 @@ public class FileSchemaTestClass { @SerializedName(SERIALIZED_NAME_FILES) private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { @@ -179,9 +179,7 @@ public class FileSchemaTestClass { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (FileSchemaTestClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!FileSchemaTestClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in FileSchemaTestClass is not found in the empty JSON string", FileSchemaTestClass.openapiRequiredFields.toString())); } } @@ -194,20 +192,22 @@ public class FileSchemaTestClass { } } // validate the optional field `file` - if (jsonObj.getAsJsonObject("file") != null) { + if (jsonObj.get("file") != null && !jsonObj.get("file").isJsonNull()) { ModelFile.validateJsonObject(jsonObj.getAsJsonObject("file")); } - JsonArray jsonArrayfiles = jsonObj.getAsJsonArray("files"); - if (jsonArrayfiles != null) { - // ensure the json data is an array - if (!jsonObj.get("files").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `files` to be an array in the JSON string but got `%s`", jsonObj.get("files").toString())); - } + if (jsonObj.get("files") != null && !jsonObj.get("files").isJsonNull()) { + JsonArray jsonArrayfiles = jsonObj.getAsJsonArray("files"); + if (jsonArrayfiles != null) { + // ensure the json data is an array + if (!jsonObj.get("files").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `files` to be an array in the JSON string but got `%s`", jsonObj.get("files").toString())); + } - // validate the optional field `files` (array) - for (int i = 0; i < jsonArrayfiles.size(); i++) { - ModelFile.validateJsonObject(jsonArrayfiles.get(i).getAsJsonObject()); - }; + // validate the optional field `files` (array) + for (int i = 0; i < jsonArrayfiles.size(); i++) { + ModelFile.validateJsonObject(jsonArrayfiles.get(i).getAsJsonObject()); + }; + } } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FormatTest.java index 2871b5d349..06d9058cdb 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FormatTest.java @@ -110,7 +110,7 @@ public class FormatTest { @SerializedName(SERIALIZED_NAME_BIG_DECIMAL) private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { @@ -547,9 +547,7 @@ public class FormatTest { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (FormatTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!FormatTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in FormatTest is not found in the empty JSON string", FormatTest.openapiRequiredFields.toString())); } } @@ -568,13 +566,13 @@ public class FormatTest { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("string") != null && !jsonObj.get("string").isJsonPrimitive()) { + if ((jsonObj.get("string") != null && !jsonObj.get("string").isJsonNull()) && !jsonObj.get("string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string").toString())); } - if (jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonPrimitive()) { + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); } - if (jsonObj.get("password") != null && !jsonObj.get("password").isJsonPrimitive()) { + if (!jsonObj.get("password").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index 6a2705dfaf..ab2d43afec 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -57,7 +57,7 @@ public class HasOnlyReadOnly { @SerializedName(SERIALIZED_NAME_FOO) private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @@ -160,9 +160,7 @@ public class HasOnlyReadOnly { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (HasOnlyReadOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!HasOnlyReadOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in HasOnlyReadOnly is not found in the empty JSON string", HasOnlyReadOnly.openapiRequiredFields.toString())); } } @@ -174,10 +172,10 @@ public class HasOnlyReadOnly { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `HasOnlyReadOnly` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonPrimitive()) { + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); } - if (jsonObj.get("foo") != null && !jsonObj.get("foo").isJsonPrimitive()) { + if ((jsonObj.get("foo") != null && !jsonObj.get("foo").isJsonNull()) && !jsonObj.get("foo").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `foo` to be a primitive type in the JSON string but got `%s`", jsonObj.get("foo").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MapTest.java index e731774a76..9612c2799a 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MapTest.java @@ -114,7 +114,7 @@ public class MapTest { @SerializedName(SERIALIZED_NAME_INDIRECT_MAP) private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { @@ -309,9 +309,7 @@ public class MapTest { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (MapTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!MapTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in MapTest is not found in the empty JSON string", MapTest.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 286a326781..b8969e5d78 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -66,7 +66,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_MAP) private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { @@ -211,9 +211,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in MixedPropertiesAndAdditionalPropertiesClass is not found in the empty JSON string", MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.toString())); } } @@ -225,7 +223,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MixedPropertiesAndAdditionalPropertiesClass` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonPrimitive()) { + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Model200Response.java index d8a11eac09..62479b4171 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Model200Response.java @@ -58,7 +58,7 @@ public class Model200Response { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { @@ -169,9 +169,7 @@ public class Model200Response { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Model200Response.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Model200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Model200Response is not found in the empty JSON string", Model200Response.openapiRequiredFields.toString())); } } @@ -183,7 +181,7 @@ public class Model200Response { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Model200Response` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("class") != null && !jsonObj.get("class").isJsonPrimitive()) { + if ((jsonObj.get("class") != null && !jsonObj.get("class").isJsonNull()) && !jsonObj.get("class").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("class").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 332723cf37..cecce9bf05 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -61,7 +61,7 @@ public class ModelApiResponse { @SerializedName(SERIALIZED_NAME_MESSAGE) private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { @@ -198,9 +198,7 @@ public class ModelApiResponse { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelApiResponse.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelApiResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelApiResponse is not found in the empty JSON string", ModelApiResponse.openapiRequiredFields.toString())); } } @@ -212,10 +210,10 @@ public class ModelApiResponse { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelApiResponse` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonPrimitive()) { + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); } - if (jsonObj.get("message") != null && !jsonObj.get("message").isJsonPrimitive()) { + if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelFile.java index d73e3b49a3..0271d19ec3 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelFile.java @@ -54,7 +54,7 @@ public class ModelFile { @SerializedName(SERIALIZED_NAME_SOURCE_U_R_I) private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { @@ -139,9 +139,7 @@ public class ModelFile { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelFile.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelFile.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelFile is not found in the empty JSON string", ModelFile.openapiRequiredFields.toString())); } } @@ -153,7 +151,7 @@ public class ModelFile { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelFile` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("sourceURI") != null && !jsonObj.get("sourceURI").isJsonPrimitive()) { + if ((jsonObj.get("sourceURI") != null && !jsonObj.get("sourceURI").isJsonNull()) && !jsonObj.get("sourceURI").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `sourceURI` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sourceURI").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelList.java index c21791d118..ab6232a79b 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelList.java @@ -53,7 +53,7 @@ public class ModelList { @SerializedName(SERIALIZED_NAME_123LIST) private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { @@ -138,9 +138,7 @@ public class ModelList { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelList.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelList.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelList is not found in the empty JSON string", ModelList.openapiRequiredFields.toString())); } } @@ -152,7 +150,7 @@ public class ModelList { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelList` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("123-list") != null && !jsonObj.get("123-list").isJsonPrimitive()) { + if ((jsonObj.get("123-list") != null && !jsonObj.get("123-list").isJsonNull()) && !jsonObj.get("123-list").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `123-list` to be a primitive type in the JSON string but got `%s`", jsonObj.get("123-list").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelReturn.java index ce3ecd43aa..9412d6d092 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -54,7 +54,7 @@ public class ModelReturn { @SerializedName(SERIALIZED_NAME_RETURN) private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { @@ -139,9 +139,7 @@ public class ModelReturn { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelReturn.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelReturn.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelReturn is not found in the empty JSON string", ModelReturn.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Name.java index e253e6e379..2db548e4bd 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Name.java @@ -66,7 +66,7 @@ public class Name { @SerializedName(SERIALIZED_NAME_123NUMBER) private Integer _123number; - public Name() { + public Name() { } @@ -222,9 +222,7 @@ public class Name { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Name.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Name.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Name is not found in the empty JSON string", Name.openapiRequiredFields.toString())); } } @@ -243,7 +241,7 @@ public class Name { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("property") != null && !jsonObj.get("property").isJsonPrimitive()) { + if ((jsonObj.get("property") != null && !jsonObj.get("property").isJsonNull()) && !jsonObj.get("property").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `property` to be a primitive type in the JSON string but got `%s`", jsonObj.get("property").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/NumberOnly.java index 11eb4a9390..6d8fcba7d9 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -54,7 +54,7 @@ public class NumberOnly { @SerializedName(SERIALIZED_NAME_JUST_NUMBER) private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { @@ -139,9 +139,7 @@ public class NumberOnly { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (NumberOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!NumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in NumberOnly is not found in the empty JSON string", NumberOnly.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Order.java index c4f00ec9c7..cdf5744725 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Order.java @@ -123,7 +123,7 @@ public class Order { @SerializedName(SERIALIZED_NAME_COMPLETE) private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { @@ -338,9 +338,7 @@ public class Order { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Order.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Order.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Order is not found in the empty JSON string", Order.openapiRequiredFields.toString())); } } @@ -352,7 +350,7 @@ public class Order { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Order` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonPrimitive()) { + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterComposite.java index acc2fba781..b0f22f9098 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -62,7 +62,7 @@ public class OuterComposite { @SerializedName(SERIALIZED_NAME_MY_BOOLEAN) private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { @@ -199,9 +199,7 @@ public class OuterComposite { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (OuterComposite.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!OuterComposite.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in OuterComposite is not found in the empty JSON string", OuterComposite.openapiRequiredFields.toString())); } } @@ -213,7 +211,7 @@ public class OuterComposite { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `OuterComposite` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("my_string") != null && !jsonObj.get("my_string").isJsonPrimitive()) { + if ((jsonObj.get("my_string") != null && !jsonObj.get("my_string").isJsonNull()) && !jsonObj.get("my_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `my_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("my_string").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Pet.java index b8c3d9b927..0f91e98f35 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Pet.java @@ -128,7 +128,7 @@ public class Pet { @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { @@ -358,9 +358,7 @@ public class Pet { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Pet.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Pet.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Pet is not found in the empty JSON string", Pet.openapiRequiredFields.toString())); } } @@ -380,29 +378,31 @@ public class Pet { } } // validate the optional field `category` - if (jsonObj.getAsJsonObject("category") != null) { + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { Category.validateJsonObject(jsonObj.getAsJsonObject("category")); } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if (!jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } // ensure the json data is an array - if (jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonArray()) { + if ((jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonNull()) && !jsonObj.get("photoUrls").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); } - JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); - if (jsonArraytags != null) { - // ensure the json data is an array - if (!jsonObj.get("tags").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); - } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } - // validate the optional field `tags` (array) - for (int i = 0; i < jsonArraytags.size(); i++) { - Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); - }; + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); + }; + } } - if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonPrimitive()) { + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index b535ed9584..5a8b18873d 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -57,7 +57,7 @@ public class ReadOnlyFirst { @SerializedName(SERIALIZED_NAME_BAZ) private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @@ -167,9 +167,7 @@ public class ReadOnlyFirst { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ReadOnlyFirst.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ReadOnlyFirst.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ReadOnlyFirst is not found in the empty JSON string", ReadOnlyFirst.openapiRequiredFields.toString())); } } @@ -181,10 +179,10 @@ public class ReadOnlyFirst { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ReadOnlyFirst` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonPrimitive()) { + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); } - if (jsonObj.get("baz") != null && !jsonObj.get("baz").isJsonPrimitive()) { + if ((jsonObj.get("baz") != null && !jsonObj.get("baz").isJsonNull()) && !jsonObj.get("baz").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `baz` to be a primitive type in the JSON string but got `%s`", jsonObj.get("baz").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/SpecialModelName.java index 652842a1a5..bdacd2ce18 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -53,7 +53,7 @@ public class SpecialModelName { @SerializedName(SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME) private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { @@ -138,9 +138,7 @@ public class SpecialModelName { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (SpecialModelName.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!SpecialModelName.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in SpecialModelName is not found in the empty JSON string", SpecialModelName.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Tag.java index e22d3eb088..03b119d303 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Tag.java @@ -57,7 +57,7 @@ public class Tag { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { @@ -168,9 +168,7 @@ public class Tag { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Tag.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Tag.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Tag is not found in the empty JSON string", Tag.openapiRequiredFields.toString())); } } @@ -182,7 +180,7 @@ public class Tag { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Tag` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index e91430614d..8966c71367 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -72,7 +72,7 @@ public class TypeHolderDefault { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { @@ -271,9 +271,7 @@ public class TypeHolderDefault { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (TypeHolderDefault.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!TypeHolderDefault.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in TypeHolderDefault is not found in the empty JSON string", TypeHolderDefault.openapiRequiredFields.toString())); } } @@ -292,11 +290,11 @@ public class TypeHolderDefault { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("string_item") != null && !jsonObj.get("string_item").isJsonPrimitive()) { + if (!jsonObj.get("string_item").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `string_item` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string_item").toString())); } // ensure the json data is an array - if (jsonObj.get("array_item") != null && !jsonObj.get("array_item").isJsonArray()) { + if ((jsonObj.get("array_item") != null && !jsonObj.get("array_item").isJsonNull()) && !jsonObj.get("array_item").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_item` to be an array in the JSON string but got `%s`", jsonObj.get("array_item").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderExample.java index c1c3f05b63..5023112e2a 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -76,7 +76,7 @@ public class TypeHolderExample { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { @@ -302,9 +302,7 @@ public class TypeHolderExample { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (TypeHolderExample.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!TypeHolderExample.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in TypeHolderExample is not found in the empty JSON string", TypeHolderExample.openapiRequiredFields.toString())); } } @@ -323,11 +321,11 @@ public class TypeHolderExample { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("string_item") != null && !jsonObj.get("string_item").isJsonPrimitive()) { + if (!jsonObj.get("string_item").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `string_item` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string_item").toString())); } // ensure the json data is an array - if (jsonObj.get("array_item") != null && !jsonObj.get("array_item").isJsonArray()) { + if ((jsonObj.get("array_item") != null && !jsonObj.get("array_item").isJsonNull()) && !jsonObj.get("array_item").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_item` to be an array in the JSON string but got `%s`", jsonObj.get("array_item").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/User.java index 2796498271..d07c822002 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/User.java @@ -81,7 +81,7 @@ public class User { @SerializedName(SERIALIZED_NAME_USER_STATUS) private Integer userStatus; - public User() { + public User() { } public User id(Long id) { @@ -348,9 +348,7 @@ public class User { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (User.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!User.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in User is not found in the empty JSON string", User.openapiRequiredFields.toString())); } } @@ -362,22 +360,22 @@ public class User { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `User` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("username") != null && !jsonObj.get("username").isJsonPrimitive()) { + if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString())); } - if (jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonPrimitive()) { + if ((jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonNull()) && !jsonObj.get("firstName").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `firstName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("firstName").toString())); } - if (jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonPrimitive()) { + if ((jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonNull()) && !jsonObj.get("lastName").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `lastName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("lastName").toString())); } - if (jsonObj.get("email") != null && !jsonObj.get("email").isJsonPrimitive()) { + if ((jsonObj.get("email") != null && !jsonObj.get("email").isJsonNull()) && !jsonObj.get("email").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `email` to be a primitive type in the JSON string but got `%s`", jsonObj.get("email").toString())); } - if (jsonObj.get("password") != null && !jsonObj.get("password").isJsonPrimitive()) { + if ((jsonObj.get("password") != null && !jsonObj.get("password").isJsonNull()) && !jsonObj.get("password").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); } - if (jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonPrimitive()) { + if ((jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonNull()) && !jsonObj.get("phone").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `phone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("phone").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/XmlItem.java index 9a29317b35..c7af7a8dcd 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/XmlItem.java @@ -168,7 +168,7 @@ public class XmlItem { @SerializedName(SERIALIZED_NAME_PREFIX_NS_WRAPPED_ARRAY) private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { @@ -1053,9 +1053,7 @@ public class XmlItem { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (XmlItem.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!XmlItem.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in XmlItem is not found in the empty JSON string", XmlItem.openapiRequiredFields.toString())); } } @@ -1067,55 +1065,55 @@ public class XmlItem { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `XmlItem` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("attribute_string") != null && !jsonObj.get("attribute_string").isJsonPrimitive()) { + if ((jsonObj.get("attribute_string") != null && !jsonObj.get("attribute_string").isJsonNull()) && !jsonObj.get("attribute_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `attribute_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("attribute_string").toString())); } // ensure the json data is an array - if (jsonObj.get("wrapped_array") != null && !jsonObj.get("wrapped_array").isJsonArray()) { + if (!jsonObj.get("wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("wrapped_array").toString())); } - if (jsonObj.get("name_string") != null && !jsonObj.get("name_string").isJsonPrimitive()) { + if ((jsonObj.get("name_string") != null && !jsonObj.get("name_string").isJsonNull()) && !jsonObj.get("name_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name_string").toString())); } // ensure the json data is an array - if (jsonObj.get("name_array") != null && !jsonObj.get("name_array").isJsonArray()) { + if (!jsonObj.get("name_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `name_array` to be an array in the JSON string but got `%s`", jsonObj.get("name_array").toString())); } // ensure the json data is an array - if (jsonObj.get("name_wrapped_array") != null && !jsonObj.get("name_wrapped_array").isJsonArray()) { + if (!jsonObj.get("name_wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `name_wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("name_wrapped_array").toString())); } - if (jsonObj.get("prefix_string") != null && !jsonObj.get("prefix_string").isJsonPrimitive()) { + if ((jsonObj.get("prefix_string") != null && !jsonObj.get("prefix_string").isJsonNull()) && !jsonObj.get("prefix_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("prefix_string").toString())); } // ensure the json data is an array - if (jsonObj.get("prefix_array") != null && !jsonObj.get("prefix_array").isJsonArray()) { + if (!jsonObj.get("prefix_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_array` to be an array in the JSON string but got `%s`", jsonObj.get("prefix_array").toString())); } // ensure the json data is an array - if (jsonObj.get("prefix_wrapped_array") != null && !jsonObj.get("prefix_wrapped_array").isJsonArray()) { + if (!jsonObj.get("prefix_wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("prefix_wrapped_array").toString())); } - if (jsonObj.get("namespace_string") != null && !jsonObj.get("namespace_string").isJsonPrimitive()) { + if ((jsonObj.get("namespace_string") != null && !jsonObj.get("namespace_string").isJsonNull()) && !jsonObj.get("namespace_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `namespace_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("namespace_string").toString())); } // ensure the json data is an array - if (jsonObj.get("namespace_array") != null && !jsonObj.get("namespace_array").isJsonArray()) { + if (!jsonObj.get("namespace_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `namespace_array` to be an array in the JSON string but got `%s`", jsonObj.get("namespace_array").toString())); } // ensure the json data is an array - if (jsonObj.get("namespace_wrapped_array") != null && !jsonObj.get("namespace_wrapped_array").isJsonArray()) { + if (!jsonObj.get("namespace_wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `namespace_wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("namespace_wrapped_array").toString())); } - if (jsonObj.get("prefix_ns_string") != null && !jsonObj.get("prefix_ns_string").isJsonPrimitive()) { + if ((jsonObj.get("prefix_ns_string") != null && !jsonObj.get("prefix_ns_string").isJsonNull()) && !jsonObj.get("prefix_ns_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_ns_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("prefix_ns_string").toString())); } // ensure the json data is an array - if (jsonObj.get("prefix_ns_array") != null && !jsonObj.get("prefix_ns_array").isJsonArray()) { + if (!jsonObj.get("prefix_ns_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_ns_array` to be an array in the JSON string but got `%s`", jsonObj.get("prefix_ns_array").toString())); } // ensure the json data is an array - if (jsonObj.get("prefix_ns_wrapped_array") != null && !jsonObj.get("prefix_ns_wrapped_array").isJsonArray()) { + if (!jsonObj.get("prefix_ns_wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_ns_wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("prefix_ns_wrapped_array").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/resources/openapi/openapi.yaml b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/resources/openapi/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/resources/openapi/openapi.yaml +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/resources/openapi/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/ApiClient.java index 24914b5028..5eaec79750 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/ApiClient.java @@ -977,6 +977,8 @@ public class ApiClient { content = null; } return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create(MediaType.parse(contentType), (String) obj); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Category.java index 073a612483..ed709beb24 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Category.java @@ -58,7 +58,7 @@ public class Category { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public Category() { + public Category() { } public Category id(Long id) { @@ -206,13 +206,11 @@ public class Category { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Category.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Category.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Category is not found in the empty JSON string", Category.openapiRequiredFields.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 2629fe576a..48e893219d 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -62,7 +62,7 @@ public class ModelApiResponse { @SerializedName(SERIALIZED_NAME_MESSAGE) private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { @@ -236,16 +236,14 @@ public class ModelApiResponse { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelApiResponse.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelApiResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelApiResponse is not found in the empty JSON string", ModelApiResponse.openapiRequiredFields.toString())); } } - if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonPrimitive()) { + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); } - if (jsonObj.get("message") != null && !jsonObj.get("message").isJsonPrimitive()) { + if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Order.java index d9eae070d5..5e9f5befa2 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Order.java @@ -124,7 +124,7 @@ public class Order { @SerializedName(SERIALIZED_NAME_COMPLETE) private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { @@ -376,13 +376,11 @@ public class Order { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Order.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Order.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Order is not found in the empty JSON string", Order.openapiRequiredFields.toString())); } } - if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonPrimitive()) { + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Pet.java index 04cc9037b0..e1679b0665 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Pet.java @@ -127,7 +127,7 @@ public class Pet { @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { @@ -396,9 +396,7 @@ public class Pet { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Pet.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Pet.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Pet is not found in the empty JSON string", Pet.openapiRequiredFields.toString())); } } @@ -410,29 +408,31 @@ public class Pet { } } // validate the optional field `category` - if (jsonObj.getAsJsonObject("category") != null) { + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { Category.validateJsonObject(jsonObj.getAsJsonObject("category")); } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if (!jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } // ensure the json data is an array - if (jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonArray()) { + if ((jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonNull()) && !jsonObj.get("photoUrls").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); } - JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); - if (jsonArraytags != null) { - // ensure the json data is an array - if (!jsonObj.get("tags").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); - } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } - // validate the optional field `tags` (array) - for (int i = 0; i < jsonArraytags.size(); i++) { - Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); - }; + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); + }; + } } - if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonPrimitive()) { + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Tag.java index f2986e7354..989a4742d2 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Tag.java @@ -58,7 +58,7 @@ public class Tag { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { @@ -206,13 +206,11 @@ public class Tag { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Tag.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Tag.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Tag is not found in the empty JSON string", Tag.openapiRequiredFields.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/User.java index 1e7e4bec7d..0fc8d804f7 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/User.java @@ -82,7 +82,7 @@ public class User { @SerializedName(SERIALIZED_NAME_USER_STATUS) private Integer userStatus; - public User() { + public User() { } public User id(Long id) { @@ -386,28 +386,26 @@ public class User { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (User.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!User.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in User is not found in the empty JSON string", User.openapiRequiredFields.toString())); } } - if (jsonObj.get("username") != null && !jsonObj.get("username").isJsonPrimitive()) { + if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString())); } - if (jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonPrimitive()) { + if ((jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonNull()) && !jsonObj.get("firstName").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `firstName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("firstName").toString())); } - if (jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonPrimitive()) { + if ((jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonNull()) && !jsonObj.get("lastName").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `lastName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("lastName").toString())); } - if (jsonObj.get("email") != null && !jsonObj.get("email").isJsonPrimitive()) { + if ((jsonObj.get("email") != null && !jsonObj.get("email").isJsonNull()) && !jsonObj.get("email").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `email` to be a primitive type in the JSON string but got `%s`", jsonObj.get("email").toString())); } - if (jsonObj.get("password") != null && !jsonObj.get("password").isJsonPrimitive()) { + if ((jsonObj.get("password") != null && !jsonObj.get("password").isJsonNull()) && !jsonObj.get("password").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); } - if (jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonPrimitive()) { + if ((jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonNull()) && !jsonObj.get("phone").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `phone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("phone").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/api/openapi.yaml b/samples/client/petstore/java/okhttp-gson-parcelableModel/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/api/openapi.yaml +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java index 07792101ff..54e9d332df 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java @@ -983,6 +983,8 @@ public class ApiClient { content = null; } return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create(MediaType.parse(contentType), (String) obj); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index bedcf0a3b3..8d7756779d 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -55,7 +55,7 @@ public class AdditionalPropertiesAnyType implements Parcelable { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { } public AdditionalPropertiesAnyType name(String name) { @@ -161,9 +161,7 @@ public class AdditionalPropertiesAnyType implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesAnyType.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesAnyType.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesAnyType is not found in the empty JSON string", AdditionalPropertiesAnyType.openapiRequiredFields.toString())); } } @@ -175,7 +173,7 @@ public class AdditionalPropertiesAnyType implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesAnyType` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index b637892ac1..b4eaa17498 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -56,7 +56,7 @@ public class AdditionalPropertiesArray implements Parcelable { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { } public AdditionalPropertiesArray name(String name) { @@ -162,9 +162,7 @@ public class AdditionalPropertiesArray implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesArray.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesArray.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesArray is not found in the empty JSON string", AdditionalPropertiesArray.openapiRequiredFields.toString())); } } @@ -176,7 +174,7 @@ public class AdditionalPropertiesArray implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesArray` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index d023dd5956..b1e6978f33 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -55,7 +55,7 @@ public class AdditionalPropertiesBoolean implements Parcelable { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { } public AdditionalPropertiesBoolean name(String name) { @@ -161,9 +161,7 @@ public class AdditionalPropertiesBoolean implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesBoolean.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesBoolean.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesBoolean is not found in the empty JSON string", AdditionalPropertiesBoolean.openapiRequiredFields.toString())); } } @@ -175,7 +173,7 @@ public class AdditionalPropertiesBoolean implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesBoolean` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 99d2423f3a..d801178043 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -99,7 +99,7 @@ public class AdditionalPropertiesClass implements Parcelable { @SerializedName(SERIALIZED_NAME_ANYTYPE3) private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { @@ -549,9 +549,7 @@ public class AdditionalPropertiesClass implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesClass is not found in the empty JSON string", AdditionalPropertiesClass.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index ab186d35b9..590723e883 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -55,7 +55,7 @@ public class AdditionalPropertiesInteger implements Parcelable { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { } public AdditionalPropertiesInteger name(String name) { @@ -161,9 +161,7 @@ public class AdditionalPropertiesInteger implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesInteger.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesInteger.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesInteger is not found in the empty JSON string", AdditionalPropertiesInteger.openapiRequiredFields.toString())); } } @@ -175,7 +173,7 @@ public class AdditionalPropertiesInteger implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesInteger` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index b3bc05c4a4..f505b4ac8c 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -56,7 +56,7 @@ public class AdditionalPropertiesNumber implements Parcelable { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { } public AdditionalPropertiesNumber name(String name) { @@ -162,9 +162,7 @@ public class AdditionalPropertiesNumber implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesNumber.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesNumber.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesNumber is not found in the empty JSON string", AdditionalPropertiesNumber.openapiRequiredFields.toString())); } } @@ -176,7 +174,7 @@ public class AdditionalPropertiesNumber implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesNumber` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index 3f7f012621..84557a8dc1 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -56,7 +56,7 @@ public class AdditionalPropertiesObject implements Parcelable { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { } public AdditionalPropertiesObject name(String name) { @@ -162,9 +162,7 @@ public class AdditionalPropertiesObject implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesObject.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesObject.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesObject is not found in the empty JSON string", AdditionalPropertiesObject.openapiRequiredFields.toString())); } } @@ -176,7 +174,7 @@ public class AdditionalPropertiesObject implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesObject` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 581737f897..a2043e6007 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -55,7 +55,7 @@ public class AdditionalPropertiesString implements Parcelable { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { } public AdditionalPropertiesString name(String name) { @@ -161,9 +161,7 @@ public class AdditionalPropertiesString implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesString.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesString.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesString is not found in the empty JSON string", AdditionalPropertiesString.openapiRequiredFields.toString())); } } @@ -175,7 +173,7 @@ public class AdditionalPropertiesString implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesString` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Animal.java index 511c8520fd..f5664798e1 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Animal.java @@ -62,7 +62,7 @@ public class Animal implements Parcelable { @SerializedName(SERIALIZED_NAME_COLOR) private String color = "red"; - public Animal() { + public Animal() { this.className = this.getClass().getSimpleName(); } @@ -198,9 +198,7 @@ public class Animal implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Animal.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Animal.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Animal is not found in the empty JSON string", Animal.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index f5f17ff974..7e094261c2 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -58,7 +58,7 @@ public class ArrayOfArrayOfNumberOnly implements Parcelable { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_NUMBER) private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { @@ -172,9 +172,7 @@ public class ArrayOfArrayOfNumberOnly implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfArrayOfNumberOnly is not found in the empty JSON string", ArrayOfArrayOfNumberOnly.openapiRequiredFields.toString())); } } @@ -187,7 +185,7 @@ public class ArrayOfArrayOfNumberOnly implements Parcelable { } } // ensure the json data is an array - if (jsonObj.get("ArrayArrayNumber") != null && !jsonObj.get("ArrayArrayNumber").isJsonArray()) { + if (!jsonObj.get("ArrayArrayNumber").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `ArrayArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayArrayNumber").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 307336cb4a..9b1111fdd9 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -58,7 +58,7 @@ public class ArrayOfNumberOnly implements Parcelable { @SerializedName(SERIALIZED_NAME_ARRAY_NUMBER) private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { @@ -172,9 +172,7 @@ public class ArrayOfNumberOnly implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfNumberOnly is not found in the empty JSON string", ArrayOfNumberOnly.openapiRequiredFields.toString())); } } @@ -187,7 +185,7 @@ public class ArrayOfNumberOnly implements Parcelable { } } // ensure the json data is an array - if (jsonObj.get("ArrayNumber") != null && !jsonObj.get("ArrayNumber").isJsonArray()) { + if (!jsonObj.get("ArrayNumber").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `ArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayNumber").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayTest.java index 6cdb80e931..15d2412253 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -66,7 +66,7 @@ public class ArrayTest implements Parcelable { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { @@ -252,9 +252,7 @@ public class ArrayTest implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayTest is not found in the empty JSON string", ArrayTest.openapiRequiredFields.toString())); } } @@ -267,15 +265,15 @@ public class ArrayTest implements Parcelable { } } // ensure the json data is an array - if (jsonObj.get("array_of_string") != null && !jsonObj.get("array_of_string").isJsonArray()) { + if (!jsonObj.get("array_of_string").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_of_string` to be an array in the JSON string but got `%s`", jsonObj.get("array_of_string").toString())); } // ensure the json data is an array - if (jsonObj.get("array_array_of_integer") != null && !jsonObj.get("array_array_of_integer").isJsonArray()) { + if (!jsonObj.get("array_array_of_integer").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_array_of_integer` to be an array in the JSON string but got `%s`", jsonObj.get("array_array_of_integer").toString())); } // ensure the json data is an array - if (jsonObj.get("array_array_of_model") != null && !jsonObj.get("array_array_of_model").isJsonArray()) { + if (!jsonObj.get("array_array_of_model").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_array_of_model` to be an array in the JSON string but got `%s`", jsonObj.get("array_array_of_model").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCat.java index 9ce3c6986c..8852815c3c 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCat.java @@ -107,7 +107,7 @@ public class BigCat extends Cat implements Parcelable { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCat() { + public BigCat() { super(); this.className = this.getClass().getSimpleName(); } @@ -223,9 +223,7 @@ public class BigCat extends Cat implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (BigCat.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!BigCat.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in BigCat is not found in the empty JSON string", BigCat.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCatAllOf.java index 4478471737..42500992c6 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -106,7 +106,7 @@ public class BigCatAllOf implements Parcelable { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { @@ -212,9 +212,7 @@ public class BigCatAllOf implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (BigCatAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!BigCatAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in BigCatAllOf is not found in the empty JSON string", BigCatAllOf.openapiRequiredFields.toString())); } } @@ -226,7 +224,7 @@ public class BigCatAllOf implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `BigCatAllOf` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("kind") != null && !jsonObj.get("kind").isJsonPrimitive()) { + if ((jsonObj.get("kind") != null && !jsonObj.get("kind").isJsonNull()) && !jsonObj.get("kind").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `kind` to be a primitive type in the JSON string but got `%s`", jsonObj.get("kind").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Capitalization.java index 67bc10dd2a..af3f7f2e9c 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Capitalization.java @@ -75,7 +75,7 @@ public class Capitalization implements Parcelable { @SerializedName(SERIALIZED_NAME_A_T_T_N_A_M_E) private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { @@ -321,9 +321,7 @@ public class Capitalization implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Capitalization.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Capitalization.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Capitalization is not found in the empty JSON string", Capitalization.openapiRequiredFields.toString())); } } @@ -335,22 +333,22 @@ public class Capitalization implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Capitalization` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("smallCamel") != null && !jsonObj.get("smallCamel").isJsonPrimitive()) { + if ((jsonObj.get("smallCamel") != null && !jsonObj.get("smallCamel").isJsonNull()) && !jsonObj.get("smallCamel").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `smallCamel` to be a primitive type in the JSON string but got `%s`", jsonObj.get("smallCamel").toString())); } - if (jsonObj.get("CapitalCamel") != null && !jsonObj.get("CapitalCamel").isJsonPrimitive()) { + if ((jsonObj.get("CapitalCamel") != null && !jsonObj.get("CapitalCamel").isJsonNull()) && !jsonObj.get("CapitalCamel").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `CapitalCamel` to be a primitive type in the JSON string but got `%s`", jsonObj.get("CapitalCamel").toString())); } - if (jsonObj.get("small_Snake") != null && !jsonObj.get("small_Snake").isJsonPrimitive()) { + if ((jsonObj.get("small_Snake") != null && !jsonObj.get("small_Snake").isJsonNull()) && !jsonObj.get("small_Snake").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `small_Snake` to be a primitive type in the JSON string but got `%s`", jsonObj.get("small_Snake").toString())); } - if (jsonObj.get("Capital_Snake") != null && !jsonObj.get("Capital_Snake").isJsonPrimitive()) { + if ((jsonObj.get("Capital_Snake") != null && !jsonObj.get("Capital_Snake").isJsonNull()) && !jsonObj.get("Capital_Snake").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `Capital_Snake` to be a primitive type in the JSON string but got `%s`", jsonObj.get("Capital_Snake").toString())); } - if (jsonObj.get("SCA_ETH_Flow_Points") != null && !jsonObj.get("SCA_ETH_Flow_Points").isJsonPrimitive()) { + if ((jsonObj.get("SCA_ETH_Flow_Points") != null && !jsonObj.get("SCA_ETH_Flow_Points").isJsonNull()) && !jsonObj.get("SCA_ETH_Flow_Points").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `SCA_ETH_Flow_Points` to be a primitive type in the JSON string but got `%s`", jsonObj.get("SCA_ETH_Flow_Points").toString())); } - if (jsonObj.get("ATT_NAME") != null && !jsonObj.get("ATT_NAME").isJsonPrimitive()) { + if ((jsonObj.get("ATT_NAME") != null && !jsonObj.get("ATT_NAME").isJsonNull()) && !jsonObj.get("ATT_NAME").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `ATT_NAME` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ATT_NAME").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Cat.java index 45736ae244..076ede1bd8 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Cat.java @@ -57,7 +57,7 @@ public class Cat extends Animal implements Parcelable { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public Cat() { + public Cat() { super(); this.className = this.getClass().getSimpleName(); } @@ -172,9 +172,7 @@ public class Cat extends Animal implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Cat.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Cat.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Cat is not found in the empty JSON string", Cat.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/CatAllOf.java index 0d5ce189ad..3cc84ae9af 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -55,7 +55,7 @@ public class CatAllOf implements Parcelable { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { @@ -161,9 +161,7 @@ public class CatAllOf implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (CatAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!CatAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in CatAllOf is not found in the empty JSON string", CatAllOf.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Category.java index 77ef37b69b..1751bab19f 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Category.java @@ -59,7 +59,7 @@ public class Category implements Parcelable { @SerializedName(SERIALIZED_NAME_NAME) private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { @@ -194,9 +194,7 @@ public class Category implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Category.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Category.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Category is not found in the empty JSON string", Category.openapiRequiredFields.toString())); } } @@ -215,7 +213,7 @@ public class Category implements Parcelable { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if (!jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ClassModel.java index 1140bceb64..4a9de3cac4 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ClassModel.java @@ -56,7 +56,7 @@ public class ClassModel implements Parcelable { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { @@ -162,9 +162,7 @@ public class ClassModel implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ClassModel.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ClassModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ClassModel is not found in the empty JSON string", ClassModel.openapiRequiredFields.toString())); } } @@ -176,7 +174,7 @@ public class ClassModel implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ClassModel` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("_class") != null && !jsonObj.get("_class").isJsonPrimitive()) { + if ((jsonObj.get("_class") != null && !jsonObj.get("_class").isJsonNull()) && !jsonObj.get("_class").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `_class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("_class").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Client.java index 921b7aad85..ed7e83da8e 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Client.java @@ -55,7 +55,7 @@ public class Client implements Parcelable { @SerializedName(SERIALIZED_NAME_CLIENT) private String client; - public Client() { + public Client() { } public Client client(String client) { @@ -161,9 +161,7 @@ public class Client implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Client.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Client.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Client is not found in the empty JSON string", Client.openapiRequiredFields.toString())); } } @@ -175,7 +173,7 @@ public class Client implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Client` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("client") != null && !jsonObj.get("client").isJsonPrimitive()) { + if ((jsonObj.get("client") != null && !jsonObj.get("client").isJsonNull()) && !jsonObj.get("client").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `client` to be a primitive type in the JSON string but got `%s`", jsonObj.get("client").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Dog.java index aac62ab9bc..2d6baf6963 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Dog.java @@ -56,7 +56,7 @@ public class Dog extends Animal implements Parcelable { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public Dog() { + public Dog() { super(); this.className = this.getClass().getSimpleName(); } @@ -171,9 +171,7 @@ public class Dog extends Animal implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Dog.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Dog.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Dog is not found in the empty JSON string", Dog.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/DogAllOf.java index 39d79b9dc7..78709e104f 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -55,7 +55,7 @@ public class DogAllOf implements Parcelable { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { @@ -161,9 +161,7 @@ public class DogAllOf implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (DogAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!DogAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in DogAllOf is not found in the empty JSON string", DogAllOf.openapiRequiredFields.toString())); } } @@ -175,7 +173,7 @@ public class DogAllOf implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DogAllOf` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonPrimitive()) { + if ((jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonNull()) && !jsonObj.get("breed").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `breed` to be a primitive type in the JSON string but got `%s`", jsonObj.get("breed").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumArrays.java index 35cddfff9f..af5771461c 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -155,7 +155,7 @@ public class EnumArrays implements Parcelable { @SerializedName(SERIALIZED_NAME_ARRAY_ENUM) private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { @@ -297,9 +297,7 @@ public class EnumArrays implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (EnumArrays.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!EnumArrays.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in EnumArrays is not found in the empty JSON string", EnumArrays.openapiRequiredFields.toString())); } } @@ -311,11 +309,11 @@ public class EnumArrays implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `EnumArrays` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonPrimitive()) { + if ((jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) && !jsonObj.get("just_symbol").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `just_symbol` to be a primitive type in the JSON string but got `%s`", jsonObj.get("just_symbol").toString())); } // ensure the json data is an array - if (jsonObj.get("array_enum") != null && !jsonObj.get("array_enum").isJsonArray()) { + if (!jsonObj.get("array_enum").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_enum` to be an array in the JSON string but got `%s`", jsonObj.get("array_enum").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumTest.java index 46d9c89ef9..8124606cef 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumTest.java @@ -264,7 +264,7 @@ public class EnumTest implements Parcelable { @SerializedName(SERIALIZED_NAME_OUTER_ENUM) private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { @@ -483,9 +483,7 @@ public class EnumTest implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (EnumTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!EnumTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in EnumTest is not found in the empty JSON string", EnumTest.openapiRequiredFields.toString())); } } @@ -504,10 +502,10 @@ public class EnumTest implements Parcelable { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonPrimitive()) { + if ((jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) && !jsonObj.get("enum_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string").toString())); } - if (jsonObj.get("enum_string_required") != null && !jsonObj.get("enum_string_required").isJsonPrimitive()) { + if (!jsonObj.get("enum_string_required").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string_required` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string_required").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 9ba801b2f7..71b55845f8 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -62,7 +62,7 @@ public class FileSchemaTestClass implements Parcelable { @SerializedName(SERIALIZED_NAME_FILES) private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { @@ -204,9 +204,7 @@ public class FileSchemaTestClass implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (FileSchemaTestClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!FileSchemaTestClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in FileSchemaTestClass is not found in the empty JSON string", FileSchemaTestClass.openapiRequiredFields.toString())); } } @@ -219,20 +217,22 @@ public class FileSchemaTestClass implements Parcelable { } } // validate the optional field `file` - if (jsonObj.getAsJsonObject("file") != null) { + if (jsonObj.get("file") != null && !jsonObj.get("file").isJsonNull()) { ModelFile.validateJsonObject(jsonObj.getAsJsonObject("file")); } - JsonArray jsonArrayfiles = jsonObj.getAsJsonArray("files"); - if (jsonArrayfiles != null) { - // ensure the json data is an array - if (!jsonObj.get("files").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `files` to be an array in the JSON string but got `%s`", jsonObj.get("files").toString())); - } + if (jsonObj.get("files") != null && !jsonObj.get("files").isJsonNull()) { + JsonArray jsonArrayfiles = jsonObj.getAsJsonArray("files"); + if (jsonArrayfiles != null) { + // ensure the json data is an array + if (!jsonObj.get("files").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `files` to be an array in the JSON string but got `%s`", jsonObj.get("files").toString())); + } - // validate the optional field `files` (array) - for (int i = 0; i < jsonArrayfiles.size(); i++) { - ModelFile.validateJsonObject(jsonArrayfiles.get(i).getAsJsonObject()); - }; + // validate the optional field `files` (array) + for (int i = 0; i < jsonArrayfiles.size(); i++) { + ModelFile.validateJsonObject(jsonArrayfiles.get(i).getAsJsonObject()); + }; + } } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FormatTest.java index 0da94612ec..ed3d549350 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FormatTest.java @@ -112,7 +112,7 @@ public class FormatTest implements Parcelable { @SerializedName(SERIALIZED_NAME_BIG_DECIMAL) private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { @@ -596,9 +596,7 @@ public class FormatTest implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (FormatTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!FormatTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in FormatTest is not found in the empty JSON string", FormatTest.openapiRequiredFields.toString())); } } @@ -617,13 +615,13 @@ public class FormatTest implements Parcelable { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("string") != null && !jsonObj.get("string").isJsonPrimitive()) { + if ((jsonObj.get("string") != null && !jsonObj.get("string").isJsonNull()) && !jsonObj.get("string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string").toString())); } - if (jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonPrimitive()) { + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); } - if (jsonObj.get("password") != null && !jsonObj.get("password").isJsonPrimitive()) { + if (!jsonObj.get("password").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index 67380649b7..c6977ace6e 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -59,7 +59,7 @@ public class HasOnlyReadOnly implements Parcelable { @SerializedName(SERIALIZED_NAME_FOO) private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @@ -185,9 +185,7 @@ public class HasOnlyReadOnly implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (HasOnlyReadOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!HasOnlyReadOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in HasOnlyReadOnly is not found in the empty JSON string", HasOnlyReadOnly.openapiRequiredFields.toString())); } } @@ -199,10 +197,10 @@ public class HasOnlyReadOnly implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `HasOnlyReadOnly` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonPrimitive()) { + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); } - if (jsonObj.get("foo") != null && !jsonObj.get("foo").isJsonPrimitive()) { + if ((jsonObj.get("foo") != null && !jsonObj.get("foo").isJsonNull()) && !jsonObj.get("foo").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `foo` to be a primitive type in the JSON string but got `%s`", jsonObj.get("foo").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MapTest.java index c5f5f05e6c..348d37b841 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MapTest.java @@ -116,7 +116,7 @@ public class MapTest implements Parcelable { @SerializedName(SERIALIZED_NAME_INDIRECT_MAP) private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { @@ -338,9 +338,7 @@ public class MapTest implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (MapTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!MapTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in MapTest is not found in the empty JSON string", MapTest.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index bc9dade24d..9402576b34 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -68,7 +68,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Parcelable { @SerializedName(SERIALIZED_NAME_MAP) private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { @@ -238,9 +238,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in MixedPropertiesAndAdditionalPropertiesClass is not found in the empty JSON string", MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.toString())); } } @@ -252,7 +250,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MixedPropertiesAndAdditionalPropertiesClass` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonPrimitive()) { + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Model200Response.java index 67b786bdf4..27b40d32d5 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Model200Response.java @@ -60,7 +60,7 @@ public class Model200Response implements Parcelable { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { @@ -194,9 +194,7 @@ public class Model200Response implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Model200Response.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Model200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Model200Response is not found in the empty JSON string", Model200Response.openapiRequiredFields.toString())); } } @@ -208,7 +206,7 @@ public class Model200Response implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Model200Response` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("class") != null && !jsonObj.get("class").isJsonPrimitive()) { + if ((jsonObj.get("class") != null && !jsonObj.get("class").isJsonNull()) && !jsonObj.get("class").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("class").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 4062f0b6a4..47538e4ef1 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -63,7 +63,7 @@ public class ModelApiResponse implements Parcelable { @SerializedName(SERIALIZED_NAME_MESSAGE) private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { @@ -225,9 +225,7 @@ public class ModelApiResponse implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelApiResponse.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelApiResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelApiResponse is not found in the empty JSON string", ModelApiResponse.openapiRequiredFields.toString())); } } @@ -239,10 +237,10 @@ public class ModelApiResponse implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelApiResponse` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonPrimitive()) { + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); } - if (jsonObj.get("message") != null && !jsonObj.get("message").isJsonPrimitive()) { + if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelFile.java index 6913b2d112..760aabb64b 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelFile.java @@ -56,7 +56,7 @@ public class ModelFile implements Parcelable { @SerializedName(SERIALIZED_NAME_SOURCE_U_R_I) private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { @@ -162,9 +162,7 @@ public class ModelFile implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelFile.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelFile.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelFile is not found in the empty JSON string", ModelFile.openapiRequiredFields.toString())); } } @@ -176,7 +174,7 @@ public class ModelFile implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelFile` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("sourceURI") != null && !jsonObj.get("sourceURI").isJsonPrimitive()) { + if ((jsonObj.get("sourceURI") != null && !jsonObj.get("sourceURI").isJsonNull()) && !jsonObj.get("sourceURI").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `sourceURI` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sourceURI").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelList.java index 9589c26752..3e9aa0ad1c 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelList.java @@ -55,7 +55,7 @@ public class ModelList implements Parcelable { @SerializedName(SERIALIZED_NAME_123LIST) private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { @@ -161,9 +161,7 @@ public class ModelList implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelList.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelList.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelList is not found in the empty JSON string", ModelList.openapiRequiredFields.toString())); } } @@ -175,7 +173,7 @@ public class ModelList implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelList` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("123-list") != null && !jsonObj.get("123-list").isJsonPrimitive()) { + if ((jsonObj.get("123-list") != null && !jsonObj.get("123-list").isJsonNull()) && !jsonObj.get("123-list").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `123-list` to be a primitive type in the JSON string but got `%s`", jsonObj.get("123-list").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelReturn.java index 707eed0c4e..45ca478e7a 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -56,7 +56,7 @@ public class ModelReturn implements Parcelable { @SerializedName(SERIALIZED_NAME_RETURN) private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { @@ -162,9 +162,7 @@ public class ModelReturn implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelReturn.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelReturn.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelReturn is not found in the empty JSON string", ModelReturn.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Name.java index adddb5df74..05c563c3ea 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Name.java @@ -68,7 +68,7 @@ public class Name implements Parcelable { @SerializedName(SERIALIZED_NAME_123NUMBER) private Integer _123number; - public Name() { + public Name() { } @@ -251,9 +251,7 @@ public class Name implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Name.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Name.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Name is not found in the empty JSON string", Name.openapiRequiredFields.toString())); } } @@ -272,7 +270,7 @@ public class Name implements Parcelable { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("property") != null && !jsonObj.get("property").isJsonPrimitive()) { + if ((jsonObj.get("property") != null && !jsonObj.get("property").isJsonNull()) && !jsonObj.get("property").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `property` to be a primitive type in the JSON string but got `%s`", jsonObj.get("property").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/NumberOnly.java index 79b4b985a4..a0281d3527 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -56,7 +56,7 @@ public class NumberOnly implements Parcelable { @SerializedName(SERIALIZED_NAME_JUST_NUMBER) private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { @@ -162,9 +162,7 @@ public class NumberOnly implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (NumberOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!NumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in NumberOnly is not found in the empty JSON string", NumberOnly.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Order.java index fc924b6fc7..f18f79fd9e 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Order.java @@ -125,7 +125,7 @@ public class Order implements Parcelable { @SerializedName(SERIALIZED_NAME_COMPLETE) private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { @@ -371,9 +371,7 @@ public class Order implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Order.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Order.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Order is not found in the empty JSON string", Order.openapiRequiredFields.toString())); } } @@ -385,7 +383,7 @@ public class Order implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Order` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonPrimitive()) { + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterComposite.java index 7bd4b9c277..5199ecbf4e 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -64,7 +64,7 @@ public class OuterComposite implements Parcelable { @SerializedName(SERIALIZED_NAME_MY_BOOLEAN) private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { @@ -226,9 +226,7 @@ public class OuterComposite implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (OuterComposite.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!OuterComposite.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in OuterComposite is not found in the empty JSON string", OuterComposite.openapiRequiredFields.toString())); } } @@ -240,7 +238,7 @@ public class OuterComposite implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `OuterComposite` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("my_string") != null && !jsonObj.get("my_string").isJsonPrimitive()) { + if ((jsonObj.get("my_string") != null && !jsonObj.get("my_string").isJsonNull()) && !jsonObj.get("my_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `my_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("my_string").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Pet.java index 05d4d1cc89..5b88f2f537 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Pet.java @@ -130,7 +130,7 @@ public class Pet implements Parcelable { @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { @@ -391,9 +391,7 @@ public class Pet implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Pet.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Pet.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Pet is not found in the empty JSON string", Pet.openapiRequiredFields.toString())); } } @@ -413,29 +411,31 @@ public class Pet implements Parcelable { } } // validate the optional field `category` - if (jsonObj.getAsJsonObject("category") != null) { + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { Category.validateJsonObject(jsonObj.getAsJsonObject("category")); } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if (!jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } // ensure the json data is an array - if (jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonArray()) { + if ((jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonNull()) && !jsonObj.get("photoUrls").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); } - JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); - if (jsonArraytags != null) { - // ensure the json data is an array - if (!jsonObj.get("tags").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); - } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } - // validate the optional field `tags` (array) - for (int i = 0; i < jsonArraytags.size(); i++) { - Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); - }; + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); + }; + } } - if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonPrimitive()) { + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index da56540465..e326374f69 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -59,7 +59,7 @@ public class ReadOnlyFirst implements Parcelable { @SerializedName(SERIALIZED_NAME_BAZ) private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @@ -192,9 +192,7 @@ public class ReadOnlyFirst implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ReadOnlyFirst.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ReadOnlyFirst.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ReadOnlyFirst is not found in the empty JSON string", ReadOnlyFirst.openapiRequiredFields.toString())); } } @@ -206,10 +204,10 @@ public class ReadOnlyFirst implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ReadOnlyFirst` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonPrimitive()) { + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); } - if (jsonObj.get("baz") != null && !jsonObj.get("baz").isJsonPrimitive()) { + if ((jsonObj.get("baz") != null && !jsonObj.get("baz").isJsonNull()) && !jsonObj.get("baz").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `baz` to be a primitive type in the JSON string but got `%s`", jsonObj.get("baz").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/SpecialModelName.java index 8382046b4b..17e08f6372 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -55,7 +55,7 @@ public class SpecialModelName implements Parcelable { @SerializedName(SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME) private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { @@ -161,9 +161,7 @@ public class SpecialModelName implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (SpecialModelName.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!SpecialModelName.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in SpecialModelName is not found in the empty JSON string", SpecialModelName.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Tag.java index d943f31494..520daa2fde 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Tag.java @@ -59,7 +59,7 @@ public class Tag implements Parcelable { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { @@ -193,9 +193,7 @@ public class Tag implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Tag.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Tag.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Tag is not found in the empty JSON string", Tag.openapiRequiredFields.toString())); } } @@ -207,7 +205,7 @@ public class Tag implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Tag` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index 4039c931e2..b20530e83d 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -74,7 +74,7 @@ public class TypeHolderDefault implements Parcelable { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { @@ -302,9 +302,7 @@ public class TypeHolderDefault implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (TypeHolderDefault.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!TypeHolderDefault.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in TypeHolderDefault is not found in the empty JSON string", TypeHolderDefault.openapiRequiredFields.toString())); } } @@ -323,11 +321,11 @@ public class TypeHolderDefault implements Parcelable { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("string_item") != null && !jsonObj.get("string_item").isJsonPrimitive()) { + if (!jsonObj.get("string_item").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `string_item` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string_item").toString())); } // ensure the json data is an array - if (jsonObj.get("array_item") != null && !jsonObj.get("array_item").isJsonArray()) { + if ((jsonObj.get("array_item") != null && !jsonObj.get("array_item").isJsonNull()) && !jsonObj.get("array_item").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_item` to be an array in the JSON string but got `%s`", jsonObj.get("array_item").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderExample.java index 6bd74b7a74..57c2e37c43 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -78,7 +78,7 @@ public class TypeHolderExample implements Parcelable { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { @@ -335,9 +335,7 @@ public class TypeHolderExample implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (TypeHolderExample.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!TypeHolderExample.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in TypeHolderExample is not found in the empty JSON string", TypeHolderExample.openapiRequiredFields.toString())); } } @@ -356,11 +354,11 @@ public class TypeHolderExample implements Parcelable { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("string_item") != null && !jsonObj.get("string_item").isJsonPrimitive()) { + if (!jsonObj.get("string_item").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `string_item` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string_item").toString())); } // ensure the json data is an array - if (jsonObj.get("array_item") != null && !jsonObj.get("array_item").isJsonArray()) { + if ((jsonObj.get("array_item") != null && !jsonObj.get("array_item").isJsonNull()) && !jsonObj.get("array_item").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_item` to be an array in the JSON string but got `%s`", jsonObj.get("array_item").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/User.java index 2d78752836..41a3c81b01 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/User.java @@ -83,7 +83,7 @@ public class User implements Parcelable { @SerializedName(SERIALIZED_NAME_USER_STATUS) private Integer userStatus; - public User() { + public User() { } public User id(Long id) { @@ -385,9 +385,7 @@ public class User implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (User.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!User.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in User is not found in the empty JSON string", User.openapiRequiredFields.toString())); } } @@ -399,22 +397,22 @@ public class User implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `User` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("username") != null && !jsonObj.get("username").isJsonPrimitive()) { + if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString())); } - if (jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonPrimitive()) { + if ((jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonNull()) && !jsonObj.get("firstName").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `firstName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("firstName").toString())); } - if (jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonPrimitive()) { + if ((jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonNull()) && !jsonObj.get("lastName").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `lastName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("lastName").toString())); } - if (jsonObj.get("email") != null && !jsonObj.get("email").isJsonPrimitive()) { + if ((jsonObj.get("email") != null && !jsonObj.get("email").isJsonNull()) && !jsonObj.get("email").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `email` to be a primitive type in the JSON string but got `%s`", jsonObj.get("email").toString())); } - if (jsonObj.get("password") != null && !jsonObj.get("password").isJsonPrimitive()) { + if ((jsonObj.get("password") != null && !jsonObj.get("password").isJsonNull()) && !jsonObj.get("password").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); } - if (jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonPrimitive()) { + if ((jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonNull()) && !jsonObj.get("phone").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `phone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("phone").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/XmlItem.java index cf3eb5fb5d..218d9ac324 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/XmlItem.java @@ -170,7 +170,7 @@ public class XmlItem implements Parcelable { @SerializedName(SERIALIZED_NAME_PREFIX_NS_WRAPPED_ARRAY) private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { @@ -1132,9 +1132,7 @@ public class XmlItem implements Parcelable { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (XmlItem.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!XmlItem.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in XmlItem is not found in the empty JSON string", XmlItem.openapiRequiredFields.toString())); } } @@ -1146,55 +1144,55 @@ public class XmlItem implements Parcelable { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `XmlItem` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("attribute_string") != null && !jsonObj.get("attribute_string").isJsonPrimitive()) { + if ((jsonObj.get("attribute_string") != null && !jsonObj.get("attribute_string").isJsonNull()) && !jsonObj.get("attribute_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `attribute_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("attribute_string").toString())); } // ensure the json data is an array - if (jsonObj.get("wrapped_array") != null && !jsonObj.get("wrapped_array").isJsonArray()) { + if (!jsonObj.get("wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("wrapped_array").toString())); } - if (jsonObj.get("name_string") != null && !jsonObj.get("name_string").isJsonPrimitive()) { + if ((jsonObj.get("name_string") != null && !jsonObj.get("name_string").isJsonNull()) && !jsonObj.get("name_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name_string").toString())); } // ensure the json data is an array - if (jsonObj.get("name_array") != null && !jsonObj.get("name_array").isJsonArray()) { + if (!jsonObj.get("name_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `name_array` to be an array in the JSON string but got `%s`", jsonObj.get("name_array").toString())); } // ensure the json data is an array - if (jsonObj.get("name_wrapped_array") != null && !jsonObj.get("name_wrapped_array").isJsonArray()) { + if (!jsonObj.get("name_wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `name_wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("name_wrapped_array").toString())); } - if (jsonObj.get("prefix_string") != null && !jsonObj.get("prefix_string").isJsonPrimitive()) { + if ((jsonObj.get("prefix_string") != null && !jsonObj.get("prefix_string").isJsonNull()) && !jsonObj.get("prefix_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("prefix_string").toString())); } // ensure the json data is an array - if (jsonObj.get("prefix_array") != null && !jsonObj.get("prefix_array").isJsonArray()) { + if (!jsonObj.get("prefix_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_array` to be an array in the JSON string but got `%s`", jsonObj.get("prefix_array").toString())); } // ensure the json data is an array - if (jsonObj.get("prefix_wrapped_array") != null && !jsonObj.get("prefix_wrapped_array").isJsonArray()) { + if (!jsonObj.get("prefix_wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("prefix_wrapped_array").toString())); } - if (jsonObj.get("namespace_string") != null && !jsonObj.get("namespace_string").isJsonPrimitive()) { + if ((jsonObj.get("namespace_string") != null && !jsonObj.get("namespace_string").isJsonNull()) && !jsonObj.get("namespace_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `namespace_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("namespace_string").toString())); } // ensure the json data is an array - if (jsonObj.get("namespace_array") != null && !jsonObj.get("namespace_array").isJsonArray()) { + if (!jsonObj.get("namespace_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `namespace_array` to be an array in the JSON string but got `%s`", jsonObj.get("namespace_array").toString())); } // ensure the json data is an array - if (jsonObj.get("namespace_wrapped_array") != null && !jsonObj.get("namespace_wrapped_array").isJsonArray()) { + if (!jsonObj.get("namespace_wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `namespace_wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("namespace_wrapped_array").toString())); } - if (jsonObj.get("prefix_ns_string") != null && !jsonObj.get("prefix_ns_string").isJsonPrimitive()) { + if ((jsonObj.get("prefix_ns_string") != null && !jsonObj.get("prefix_ns_string").isJsonNull()) && !jsonObj.get("prefix_ns_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_ns_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("prefix_ns_string").toString())); } // ensure the json data is an array - if (jsonObj.get("prefix_ns_array") != null && !jsonObj.get("prefix_ns_array").isJsonArray()) { + if (!jsonObj.get("prefix_ns_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_ns_array` to be an array in the JSON string but got `%s`", jsonObj.get("prefix_ns_array").toString())); } // ensure the json data is an array - if (jsonObj.get("prefix_ns_wrapped_array") != null && !jsonObj.get("prefix_ns_wrapped_array").isJsonArray()) { + if (!jsonObj.get("prefix_ns_wrapped_array").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `prefix_ns_wrapped_array` to be an array in the JSON string but got `%s`", jsonObj.get("prefix_ns_wrapped_array").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES index 06aaf5fb56..74fd5c044a 100644 --- a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES +++ b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES @@ -14,6 +14,7 @@ docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfInlineAllOf.md docs/ArrayOfInlineAllOfArrayAllofDogPropertyInner.md docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.md +docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.md docs/ArrayOfNumberOnly.md docs/ArrayTest.md docs/Banana.md @@ -34,6 +35,7 @@ docs/DogAllOf.md docs/Drawing.md docs/EnumArrays.md docs/EnumClass.md +docs/EnumStringDiscriminator.md docs/EnumTest.md docs/EquilateralTriangle.md docs/FakeApi.md @@ -136,6 +138,7 @@ src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.java +src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.java src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java src/main/java/org/openapitools/client/model/ArrayTest.java src/main/java/org/openapitools/client/model/Banana.java @@ -155,6 +158,7 @@ src/main/java/org/openapitools/client/model/DogAllOf.java src/main/java/org/openapitools/client/model/Drawing.java src/main/java/org/openapitools/client/model/EnumArrays.java src/main/java/org/openapitools/client/model/EnumClass.java +src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java src/main/java/org/openapitools/client/model/EnumTest.java src/main/java/org/openapitools/client/model/EquilateralTriangle.java src/main/java/org/openapitools/client/model/FileSchemaTestClass.java diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md index c39f678259..710fdcd645 100644 --- a/samples/client/petstore/java/okhttp-gson/README.md +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -164,6 +164,7 @@ Class | Method | HTTP request | Description - [ArrayOfInlineAllOf](docs/ArrayOfInlineAllOf.md) - [ArrayOfInlineAllOfArrayAllofDogPropertyInner](docs/ArrayOfInlineAllOfArrayAllofDogPropertyInner.md) - [ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf](docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.md) + - [ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1](docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.md) - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [ArrayTest](docs/ArrayTest.md) - [Banana](docs/Banana.md) @@ -183,6 +184,7 @@ Class | Method | HTTP request | Description - [Drawing](docs/Drawing.md) - [EnumArrays](docs/EnumArrays.md) - [EnumClass](docs/EnumClass.md) + - [EnumStringDiscriminator](docs/EnumStringDiscriminator.md) - [EnumTest](docs/EnumTest.md) - [EquilateralTriangle](docs/EquilateralTriangle.md) - [FileSchemaTestClass](docs/FileSchemaTestClass.md) diff --git a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml index d6e01b6804..1ad553c3ad 100644 --- a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml +++ b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml @@ -1496,6 +1496,10 @@ components: example: 72f98069-206d-4f12-9f12-3d1e525a8e84 format: uuid type: string + uuid_with_default: + default: 11111111-206d-4f12-9f12-3d1e525a8e84 + format: uuid + type: string password: format: password maxLength: 64 @@ -2186,6 +2190,20 @@ components: required: - name type: object + EnumStringDiscriminator: + description: An object to test discriminator of enum string + discriminator: + propertyName: enum_str_type + properties: + enum_str_type: + description: enum string type + enum: + - type_a + - type_b + type: string + required: + - enum_str_type + type: object _foo_get_default_response: example: string: @@ -2336,20 +2354,27 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null ArrayOfInlineAllOf_array_allof_dog_property_inner_allOf: + properties: + breed: + type: string + type: object + ArrayOfInlineAllOf_array_allof_dog_property_inner_allOf_1: properties: color: type: string type: object ArrayOfInlineAllOf_array_allof_dog_property_inner: allOf: - - $ref: '#/components/schemas/Dog_allOf' - $ref: '#/components/schemas/ArrayOfInlineAllOf_array_allof_dog_property_inner_allOf' + - $ref: '#/components/schemas/ArrayOfInlineAllOf_array_allof_dog_property_inner_allOf_1' securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/okhttp-gson/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.md b/samples/client/petstore/java/okhttp-gson/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.md index 4ec0e16385..a30fc63ecf 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.md +++ b/samples/client/petstore/java/okhttp-gson/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.md @@ -7,7 +7,7 @@ | Name | Type | Description | Notes | |------------ | ------------- | ------------- | -------------| -|**color** | **String** | | [optional] | +|**breed** | **String** | | [optional] | diff --git a/samples/client/petstore/java/okhttp-gson/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.md b/samples/client/petstore/java/okhttp-gson/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.md new file mode 100644 index 0000000000..fa8c070f53 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.md @@ -0,0 +1,13 @@ + + +# ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**color** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/EnumStringDiscriminator.md b/samples/client/petstore/java/okhttp-gson/docs/EnumStringDiscriminator.md new file mode 100644 index 0000000000..83aebcdb42 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/EnumStringDiscriminator.md @@ -0,0 +1,23 @@ + + +# EnumStringDiscriminator + +An object to test discriminator of enum string + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**enumStrType** | [**EnumStrTypeEnum**](#EnumStrTypeEnum) | enum string type | | + + + +## Enum: EnumStrTypeEnum + +| Name | Value | +|---- | -----| +| A | "type_a" | +| B | "type_b" | + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md b/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md index 01b8c777ae..71790022c1 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FormatTest.md @@ -20,6 +20,7 @@ |**date** | **LocalDate** | | | |**dateTime** | **OffsetDateTime** | | [optional] | |**uuid** | **UUID** | | [optional] | +|**uuidWithDefault** | **UUID** | | [optional] | |**password** | **String** | | | |**patternWithDigits** | **String** | A string that is a 10 digit number. Can have leading zeros. | [optional] | |**patternWithDigitsAndDelimiter** | **String** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] | diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java index 4319311adf..0fcd95584a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java @@ -1002,6 +1002,8 @@ public class ApiClient { content = null; } return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create(MediaType.parse(contentType), (String) obj); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java index 4bd7697b59..00b9ca5ddc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java @@ -86,6 +86,15 @@ public class JSON { return getClassByDiscriminator(classByDiscriminatorValue, getDiscriminatorValue(readElement, "className")); } + }) + .registerTypeSelector(org.openapitools.client.model.EnumStringDiscriminator.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("EnumStringDiscriminator", org.openapitools.client.model.EnumStringDiscriminator.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "enum_str_type")); + } }) .registerTypeSelector(org.openapitools.client.model.GrandparentAnimal.class, new TypeSelector() { @Override @@ -227,6 +236,7 @@ public class JSON { gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfInlineAllOf.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfInlineAllOfArrayAllofDogPropertyInner.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfNumberOnly.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayTest.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Banana.CustomTypeAdapterFactory()); @@ -245,6 +255,7 @@ public class JSON { gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.DogAllOf.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Drawing.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.EnumArrays.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.EnumStringDiscriminator.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.EnumTest.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.EquilateralTriangle.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.FileSchemaTestClass.CustomTypeAdapterFactory()); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 3b97a21418..927b23386e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -84,7 +84,7 @@ public class AdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_STRING) private Map mapWithUndeclaredPropertiesString = null; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapProperty(Map mapProperty) { @@ -431,9 +431,7 @@ public class AdditionalPropertiesClass { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesClass is not found in the empty JSON string", AdditionalPropertiesClass.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Animal.java index 514e9d27cd..e1d94b6362 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Animal.java @@ -59,7 +59,7 @@ public class Animal { @SerializedName(SERIALIZED_NAME_COLOR) private String color = "red"; - public Animal() { + public Animal() { this.className = this.getClass().getSimpleName(); } @@ -209,9 +209,7 @@ public class Animal { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Animal.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Animal.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Animal is not found in the empty JSON string", Animal.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Apple.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Apple.java index 2adf6cbbb6..9183df38a0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Apple.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Apple.java @@ -57,7 +57,7 @@ public class Apple { @SerializedName(SERIALIZED_NAME_ORIGIN) private String origin; - public Apple() { + public Apple() { } public Apple cultivar(String cultivar) { @@ -205,16 +205,14 @@ public class Apple { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Apple.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Apple.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Apple is not found in the empty JSON string", Apple.openapiRequiredFields.toString())); } } - if (jsonObj.get("cultivar") != null && !jsonObj.get("cultivar").isJsonPrimitive()) { + if ((jsonObj.get("cultivar") != null && !jsonObj.get("cultivar").isJsonNull()) && !jsonObj.get("cultivar").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `cultivar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("cultivar").toString())); } - if (jsonObj.get("origin") != null && !jsonObj.get("origin").isJsonPrimitive()) { + if ((jsonObj.get("origin") != null && !jsonObj.get("origin").isJsonNull()) && !jsonObj.get("origin").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `origin` to be a primitive type in the JSON string but got `%s`", jsonObj.get("origin").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AppleReq.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AppleReq.java index 93103ecab9..dd30c95c03 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AppleReq.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AppleReq.java @@ -57,7 +57,7 @@ public class AppleReq { @SerializedName(SERIALIZED_NAME_MEALY) private Boolean mealy; - public AppleReq() { + public AppleReq() { } public AppleReq cultivar(String cultivar) { @@ -169,9 +169,7 @@ public class AppleReq { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (AppleReq.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!AppleReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in AppleReq is not found in the empty JSON string", AppleReq.openapiRequiredFields.toString())); } } @@ -190,7 +188,7 @@ public class AppleReq { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("cultivar") != null && !jsonObj.get("cultivar").isJsonPrimitive()) { + if (!jsonObj.get("cultivar").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `cultivar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("cultivar").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 62462f9486..ca1cf1d387 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -56,7 +56,7 @@ public class ArrayOfArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_NUMBER) private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { @@ -186,14 +186,12 @@ public class ArrayOfArrayOfNumberOnly { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfArrayOfNumberOnly is not found in the empty JSON string", ArrayOfArrayOfNumberOnly.openapiRequiredFields.toString())); } } // ensure the json data is an array - if (jsonObj.get("ArrayArrayNumber") != null && !jsonObj.get("ArrayArrayNumber").isJsonArray()) { + if (!jsonObj.get("ArrayArrayNumber").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `ArrayArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayArrayNumber").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java index 8fc635c590..267f409928 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java @@ -64,7 +64,7 @@ public class ArrayOfInlineAllOf { @SerializedName(SERIALIZED_NAME_ARRAY_ALLOF_DOG_PROPERTY) private List arrayAllofDogProperty = null; - public ArrayOfInlineAllOf() { + public ArrayOfInlineAllOf() { } public ArrayOfInlineAllOf id(Long id) { @@ -247,9 +247,7 @@ public class ArrayOfInlineAllOf { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayOfInlineAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayOfInlineAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfInlineAllOf is not found in the empty JSON string", ArrayOfInlineAllOf.openapiRequiredFields.toString())); } } @@ -260,20 +258,22 @@ public class ArrayOfInlineAllOf { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if (!jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } - JsonArray jsonArrayarrayAllofDogProperty = jsonObj.getAsJsonArray("array_allof_dog_property"); - if (jsonArrayarrayAllofDogProperty != null) { - // ensure the json data is an array - if (!jsonObj.get("array_allof_dog_property").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `array_allof_dog_property` to be an array in the JSON string but got `%s`", jsonObj.get("array_allof_dog_property").toString())); - } + if (jsonObj.get("array_allof_dog_property") != null && !jsonObj.get("array_allof_dog_property").isJsonNull()) { + JsonArray jsonArrayarrayAllofDogProperty = jsonObj.getAsJsonArray("array_allof_dog_property"); + if (jsonArrayarrayAllofDogProperty != null) { + // ensure the json data is an array + if (!jsonObj.get("array_allof_dog_property").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `array_allof_dog_property` to be an array in the JSON string but got `%s`", jsonObj.get("array_allof_dog_property").toString())); + } - // validate the optional field `array_allof_dog_property` (array) - for (int i = 0; i < jsonArrayarrayAllofDogProperty.size(); i++) { - ArrayOfInlineAllOfArrayAllofDogPropertyInner.validateJsonObject(jsonArrayarrayAllofDogProperty.get(i).getAsJsonObject()); - }; + // validate the optional field `array_allof_dog_property` (array) + for (int i = 0; i < jsonArrayarrayAllofDogProperty.size(); i++) { + ArrayOfInlineAllOfArrayAllofDogPropertyInner.validateJsonObject(jsonArrayarrayAllofDogProperty.get(i).getAsJsonObject()); + }; + } } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java index 6e8b66da66..343155380b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java @@ -57,7 +57,7 @@ public class ArrayOfInlineAllOfArrayAllofDogPropertyInner { @SerializedName(SERIALIZED_NAME_COLOR) private String color; - public ArrayOfInlineAllOfArrayAllofDogPropertyInner() { + public ArrayOfInlineAllOfArrayAllofDogPropertyInner() { } public ArrayOfInlineAllOfArrayAllofDogPropertyInner breed(String breed) { @@ -205,16 +205,14 @@ public class ArrayOfInlineAllOfArrayAllofDogPropertyInner { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayOfInlineAllOfArrayAllofDogPropertyInner.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayOfInlineAllOfArrayAllofDogPropertyInner.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfInlineAllOfArrayAllofDogPropertyInner is not found in the empty JSON string", ArrayOfInlineAllOfArrayAllofDogPropertyInner.openapiRequiredFields.toString())); } } - if (jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonPrimitive()) { + if ((jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonNull()) && !jsonObj.get("breed").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `breed` to be a primitive type in the JSON string but got `%s`", jsonObj.get("breed").toString())); } - if (jsonObj.get("color") != null && !jsonObj.get("color").isJsonPrimitive()) { + if ((jsonObj.get("color") != null && !jsonObj.get("color").isJsonNull()) && !jsonObj.get("color").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `color` to be a primitive type in the JSON string but got `%s`", jsonObj.get("color").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.java index e5deb94852..c038228918 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.java @@ -49,33 +49,33 @@ import org.openapitools.client.JSON; */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf { - public static final String SERIALIZED_NAME_COLOR = "color"; - @SerializedName(SERIALIZED_NAME_COLOR) - private String color; + public static final String SERIALIZED_NAME_BREED = "breed"; + @SerializedName(SERIALIZED_NAME_BREED) + private String breed; - public ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf() { + public ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf() { } - public ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf color(String color) { + public ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf breed(String breed) { - this.color = color; + this.breed = breed; return this; } /** - * Get color - * @return color + * Get breed + * @return breed **/ @javax.annotation.Nullable @ApiModelProperty(value = "") - public String getColor() { - return color; + public String getBreed() { + return breed; } - public void setColor(String color) { - this.color = color; + public void setBreed(String breed) { + this.breed = breed; } /** @@ -124,20 +124,20 @@ public class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf { return false; } ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf arrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf = (ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf) o; - return Objects.equals(this.color, arrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.color)&& + return Objects.equals(this.breed, arrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.breed)&& Objects.equals(this.additionalProperties, arrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.additionalProperties); } @Override public int hashCode() { - return Objects.hash(color, additionalProperties); + return Objects.hash(breed, additionalProperties); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf {\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); @@ -161,7 +161,7 @@ public class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf { static { // a set of all properties/fields (JSON key names) openapiFields = new HashSet(); - openapiFields.add("color"); + openapiFields.add("breed"); // a set of required properties/fields (JSON key names) openapiRequiredFields = new HashSet(); @@ -175,14 +175,12 @@ public class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf is not found in the empty JSON string", ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf.openapiRequiredFields.toString())); } } - if (jsonObj.get("color") != null && !jsonObj.get("color").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `color` to be a primitive type in the JSON string but got `%s`", jsonObj.get("color").toString())); + if ((jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonNull()) && !jsonObj.get("breed").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `breed` to be a primitive type in the JSON string but got `%s`", jsonObj.get("breed").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.java new file mode 100644 index 0000000000..ca9607ca9c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.java @@ -0,0 +1,271 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.openapitools.client.JSON; + +/** + * ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 { + public static final String SERIALIZED_NAME_COLOR = "color"; + @SerializedName(SERIALIZED_NAME_COLOR) + private String color; + + public ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1() { + } + + public ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 color(String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getColor() { + return color; + } + + + public void setColor(String color) { + this.color = color; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + */ + public ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 arrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 = (ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1) o; + return Objects.equals(this.color, arrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.color)&& + Objects.equals(this.additionalProperties, arrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(color, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 {\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("color"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 is not found in the empty JSON string", ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.openapiRequiredFields.toString())); + } + } + if ((jsonObj.get("color") != null && !jsonObj.get("color").isJsonNull()) && !jsonObj.get("color").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `color` to be a primitive type in the JSON string but got `%s`", jsonObj.get("color").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additonal properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + // store additional fields in the deserialized instance + ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else { // non-primitive type + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 + * @throws IOException if the JSON string is invalid with respect to ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 + */ + public static ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.class); + } + + /** + * Convert an instance of ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 44f3b1db19..7bdd9ad636 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -56,7 +56,7 @@ public class ArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_NUMBER) private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { @@ -186,14 +186,12 @@ public class ArrayOfNumberOnly { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfNumberOnly is not found in the empty JSON string", ArrayOfNumberOnly.openapiRequiredFields.toString())); } } // ensure the json data is an array - if (jsonObj.get("ArrayNumber") != null && !jsonObj.get("ArrayNumber").isJsonArray()) { + if (!jsonObj.get("ArrayNumber").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `ArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayNumber").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayTest.java index 207dea369b..fa4e62ac1e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -64,7 +64,7 @@ public class ArrayTest { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { @@ -262,22 +262,20 @@ public class ArrayTest { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ArrayTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ArrayTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayTest is not found in the empty JSON string", ArrayTest.openapiRequiredFields.toString())); } } // ensure the json data is an array - if (jsonObj.get("array_of_string") != null && !jsonObj.get("array_of_string").isJsonArray()) { + if (!jsonObj.get("array_of_string").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_of_string` to be an array in the JSON string but got `%s`", jsonObj.get("array_of_string").toString())); } // ensure the json data is an array - if (jsonObj.get("array_array_of_integer") != null && !jsonObj.get("array_array_of_integer").isJsonArray()) { + if (!jsonObj.get("array_array_of_integer").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_array_of_integer` to be an array in the JSON string but got `%s`", jsonObj.get("array_array_of_integer").toString())); } // ensure the json data is an array - if (jsonObj.get("array_array_of_model") != null && !jsonObj.get("array_array_of_model").isJsonArray()) { + if (!jsonObj.get("array_array_of_model").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_array_of_model` to be an array in the JSON string but got `%s`", jsonObj.get("array_array_of_model").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Banana.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Banana.java index 08800366b7..409f56dc5f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Banana.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Banana.java @@ -54,7 +54,7 @@ public class Banana { @SerializedName(SERIALIZED_NAME_LENGTH_CM) private BigDecimal lengthCm; - public Banana() { + public Banana() { } public Banana lengthCm(BigDecimal lengthCm) { @@ -176,9 +176,7 @@ public class Banana { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Banana.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Banana.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Banana is not found in the empty JSON string", Banana.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BananaReq.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BananaReq.java index a34aa12328..877f598954 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BananaReq.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BananaReq.java @@ -58,7 +58,7 @@ public class BananaReq { @SerializedName(SERIALIZED_NAME_SWEET) private Boolean sweet; - public BananaReq() { + public BananaReq() { } public BananaReq lengthCm(BigDecimal lengthCm) { @@ -170,9 +170,7 @@ public class BananaReq { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (BananaReq.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!BananaReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in BananaReq is not found in the empty JSON string", BananaReq.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BasquePig.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BasquePig.java index 7f144c3631..ed5f880e3b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BasquePig.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BasquePig.java @@ -53,7 +53,7 @@ public class BasquePig { @SerializedName(SERIALIZED_NAME_CLASS_NAME) private String className; - public BasquePig() { + public BasquePig() { } public BasquePig className(String className) { @@ -176,9 +176,7 @@ public class BasquePig { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (BasquePig.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!BasquePig.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in BasquePig is not found in the empty JSON string", BasquePig.openapiRequiredFields.toString())); } } @@ -189,7 +187,7 @@ public class BasquePig { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("className") != null && !jsonObj.get("className").isJsonPrimitive()) { + if (!jsonObj.get("className").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Capitalization.java index 6ed0d3d298..a7b48934c3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Capitalization.java @@ -73,7 +73,7 @@ public class Capitalization { @SerializedName(SERIALIZED_NAME_A_T_T_N_A_M_E) private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { @@ -325,28 +325,26 @@ public class Capitalization { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Capitalization.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Capitalization.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Capitalization is not found in the empty JSON string", Capitalization.openapiRequiredFields.toString())); } } - if (jsonObj.get("smallCamel") != null && !jsonObj.get("smallCamel").isJsonPrimitive()) { + if ((jsonObj.get("smallCamel") != null && !jsonObj.get("smallCamel").isJsonNull()) && !jsonObj.get("smallCamel").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `smallCamel` to be a primitive type in the JSON string but got `%s`", jsonObj.get("smallCamel").toString())); } - if (jsonObj.get("CapitalCamel") != null && !jsonObj.get("CapitalCamel").isJsonPrimitive()) { + if ((jsonObj.get("CapitalCamel") != null && !jsonObj.get("CapitalCamel").isJsonNull()) && !jsonObj.get("CapitalCamel").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `CapitalCamel` to be a primitive type in the JSON string but got `%s`", jsonObj.get("CapitalCamel").toString())); } - if (jsonObj.get("small_Snake") != null && !jsonObj.get("small_Snake").isJsonPrimitive()) { + if ((jsonObj.get("small_Snake") != null && !jsonObj.get("small_Snake").isJsonNull()) && !jsonObj.get("small_Snake").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `small_Snake` to be a primitive type in the JSON string but got `%s`", jsonObj.get("small_Snake").toString())); } - if (jsonObj.get("Capital_Snake") != null && !jsonObj.get("Capital_Snake").isJsonPrimitive()) { + if ((jsonObj.get("Capital_Snake") != null && !jsonObj.get("Capital_Snake").isJsonNull()) && !jsonObj.get("Capital_Snake").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `Capital_Snake` to be a primitive type in the JSON string but got `%s`", jsonObj.get("Capital_Snake").toString())); } - if (jsonObj.get("SCA_ETH_Flow_Points") != null && !jsonObj.get("SCA_ETH_Flow_Points").isJsonPrimitive()) { + if ((jsonObj.get("SCA_ETH_Flow_Points") != null && !jsonObj.get("SCA_ETH_Flow_Points").isJsonNull()) && !jsonObj.get("SCA_ETH_Flow_Points").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `SCA_ETH_Flow_Points` to be a primitive type in the JSON string but got `%s`", jsonObj.get("SCA_ETH_Flow_Points").toString())); } - if (jsonObj.get("ATT_NAME") != null && !jsonObj.get("ATT_NAME").isJsonPrimitive()) { + if ((jsonObj.get("ATT_NAME") != null && !jsonObj.get("ATT_NAME").isJsonNull()) && !jsonObj.get("ATT_NAME").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `ATT_NAME` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ATT_NAME").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Cat.java index e1577842b3..a517389ddc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Cat.java @@ -54,7 +54,7 @@ public class Cat extends Animal { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public Cat() { + public Cat() { this.className = this.getClass().getSimpleName(); } @@ -182,9 +182,7 @@ public class Cat extends Animal { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Cat.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Cat.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Cat is not found in the empty JSON string", Cat.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/CatAllOf.java index 7410114217..09ce3c2ef7 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -53,7 +53,7 @@ public class CatAllOf { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { @@ -175,9 +175,7 @@ public class CatAllOf { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (CatAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!CatAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in CatAllOf is not found in the empty JSON string", CatAllOf.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java index ec5e5fcf2d..77d6177207 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java @@ -57,7 +57,7 @@ public class Category { @SerializedName(SERIALIZED_NAME_NAME) private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { @@ -206,9 +206,7 @@ public class Category { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Category.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Category.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Category is not found in the empty JSON string", Category.openapiRequiredFields.toString())); } } @@ -219,7 +217,7 @@ public class Category { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if (!jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ClassModel.java index ad4d551f51..0f8b166129 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ClassModel.java @@ -54,7 +54,7 @@ public class ClassModel { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { @@ -176,13 +176,11 @@ public class ClassModel { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ClassModel.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ClassModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ClassModel is not found in the empty JSON string", ClassModel.openapiRequiredFields.toString())); } } - if (jsonObj.get("_class") != null && !jsonObj.get("_class").isJsonPrimitive()) { + if ((jsonObj.get("_class") != null && !jsonObj.get("_class").isJsonNull()) && !jsonObj.get("_class").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `_class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("_class").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Client.java index 381036120a..a04df3e85f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Client.java @@ -53,7 +53,7 @@ public class Client { @SerializedName(SERIALIZED_NAME_CLIENT) private String client; - public Client() { + public Client() { } public Client client(String client) { @@ -175,13 +175,11 @@ public class Client { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Client.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Client.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Client is not found in the empty JSON string", Client.openapiRequiredFields.toString())); } } - if (jsonObj.get("client") != null && !jsonObj.get("client").isJsonPrimitive()) { + if ((jsonObj.get("client") != null && !jsonObj.get("client").isJsonNull()) && !jsonObj.get("client").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `client` to be a primitive type in the JSON string but got `%s`", jsonObj.get("client").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java index 0c81e3f7d8..a3b2b1cf25 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java @@ -57,7 +57,7 @@ public class ComplexQuadrilateral { @SerializedName(SERIALIZED_NAME_QUADRILATERAL_TYPE) private String quadrilateralType; - public ComplexQuadrilateral() { + public ComplexQuadrilateral() { } public ComplexQuadrilateral shapeType(String shapeType) { @@ -207,9 +207,7 @@ public class ComplexQuadrilateral { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ComplexQuadrilateral.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ComplexQuadrilateral.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ComplexQuadrilateral is not found in the empty JSON string", ComplexQuadrilateral.openapiRequiredFields.toString())); } } @@ -220,10 +218,10 @@ public class ComplexQuadrilateral { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("shapeType") != null && !jsonObj.get("shapeType").isJsonPrimitive()) { + if (!jsonObj.get("shapeType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); } - if (jsonObj.get("quadrilateralType") != null && !jsonObj.get("quadrilateralType").isJsonPrimitive()) { + if (!jsonObj.get("quadrilateralType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `quadrilateralType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("quadrilateralType").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DanishPig.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DanishPig.java index 02c390dcd7..9ec2c05fc6 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DanishPig.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DanishPig.java @@ -53,7 +53,7 @@ public class DanishPig { @SerializedName(SERIALIZED_NAME_CLASS_NAME) private String className; - public DanishPig() { + public DanishPig() { } public DanishPig className(String className) { @@ -176,9 +176,7 @@ public class DanishPig { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (DanishPig.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!DanishPig.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in DanishPig is not found in the empty JSON string", DanishPig.openapiRequiredFields.toString())); } } @@ -189,7 +187,7 @@ public class DanishPig { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("className") != null && !jsonObj.get("className").isJsonPrimitive()) { + if (!jsonObj.get("className").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DeprecatedObject.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DeprecatedObject.java index d1e24af7ff..ef76ed5f9c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DeprecatedObject.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DeprecatedObject.java @@ -55,7 +55,7 @@ public class DeprecatedObject { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public DeprecatedObject() { + public DeprecatedObject() { } public DeprecatedObject name(String name) { @@ -177,13 +177,11 @@ public class DeprecatedObject { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (DeprecatedObject.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!DeprecatedObject.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in DeprecatedObject is not found in the empty JSON string", DeprecatedObject.openapiRequiredFields.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Dog.java index 658a5d4f92..208d3c7494 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Dog.java @@ -54,7 +54,7 @@ public class Dog extends Animal { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public Dog() { + public Dog() { this.className = this.getClass().getSimpleName(); } @@ -182,9 +182,7 @@ public class Dog extends Animal { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Dog.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Dog.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Dog is not found in the empty JSON string", Dog.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DogAllOf.java index a15a3e0929..b38a433b5e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -53,7 +53,7 @@ public class DogAllOf { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { @@ -175,13 +175,11 @@ public class DogAllOf { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (DogAllOf.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!DogAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in DogAllOf is not found in the empty JSON string", DogAllOf.openapiRequiredFields.toString())); } } - if (jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonPrimitive()) { + if ((jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonNull()) && !jsonObj.get("breed").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `breed` to be a primitive type in the JSON string but got `%s`", jsonObj.get("breed").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java index 5318f5afc9..917defa10c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java @@ -72,7 +72,7 @@ public class Drawing { @SerializedName(SERIALIZED_NAME_SHAPES) private List shapes = null; - public Drawing() { + public Drawing() { } public Drawing mainShape(Shape mainShape) { @@ -254,9 +254,7 @@ public class Drawing { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Drawing.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Drawing.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Drawing is not found in the empty JSON string", Drawing.openapiRequiredFields.toString())); } } @@ -269,28 +267,30 @@ public class Drawing { } } // validate the optional field `mainShape` - if (jsonObj.getAsJsonObject("mainShape") != null) { + if (jsonObj.get("mainShape") != null && !jsonObj.get("mainShape").isJsonNull()) { Shape.validateJsonObject(jsonObj.getAsJsonObject("mainShape")); } // validate the optional field `shapeOrNull` - if (jsonObj.getAsJsonObject("shapeOrNull") != null) { + if (jsonObj.get("shapeOrNull") != null && !jsonObj.get("shapeOrNull").isJsonNull()) { ShapeOrNull.validateJsonObject(jsonObj.getAsJsonObject("shapeOrNull")); } // validate the optional field `nullableShape` - if (jsonObj.getAsJsonObject("nullableShape") != null) { + if (jsonObj.get("nullableShape") != null && !jsonObj.get("nullableShape").isJsonNull()) { NullableShape.validateJsonObject(jsonObj.getAsJsonObject("nullableShape")); } - JsonArray jsonArrayshapes = jsonObj.getAsJsonArray("shapes"); - if (jsonArrayshapes != null) { - // ensure the json data is an array - if (!jsonObj.get("shapes").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `shapes` to be an array in the JSON string but got `%s`", jsonObj.get("shapes").toString())); - } + if (jsonObj.get("shapes") != null && !jsonObj.get("shapes").isJsonNull()) { + JsonArray jsonArrayshapes = jsonObj.getAsJsonArray("shapes"); + if (jsonArrayshapes != null) { + // ensure the json data is an array + if (!jsonObj.get("shapes").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `shapes` to be an array in the JSON string but got `%s`", jsonObj.get("shapes").toString())); + } - // validate the optional field `shapes` (array) - for (int i = 0; i < jsonArrayshapes.size(); i++) { - Shape.validateJsonObject(jsonArrayshapes.get(i).getAsJsonObject()); - }; + // validate the optional field `shapes` (array) + for (int i = 0; i < jsonArrayshapes.size(); i++) { + Shape.validateJsonObject(jsonArrayshapes.get(i).getAsJsonObject()); + }; + } } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumArrays.java index 3a705da916..bed4153623 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -153,7 +153,7 @@ public class EnumArrays { @SerializedName(SERIALIZED_NAME_ARRAY_ENUM) private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { @@ -309,17 +309,15 @@ public class EnumArrays { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (EnumArrays.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!EnumArrays.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in EnumArrays is not found in the empty JSON string", EnumArrays.openapiRequiredFields.toString())); } } - if (jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonPrimitive()) { + if ((jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) && !jsonObj.get("just_symbol").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `just_symbol` to be a primitive type in the JSON string but got `%s`", jsonObj.get("just_symbol").toString())); } // ensure the json data is an array - if (jsonObj.get("array_enum") != null && !jsonObj.get("array_enum").isJsonArray()) { + if (!jsonObj.get("array_enum").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_enum` to be an array in the JSON string but got `%s`", jsonObj.get("array_enum").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java new file mode 100644 index 0000000000..1b83263877 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java @@ -0,0 +1,324 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.openapitools.client.JSON; + +/** + * An object to test discriminator of enum string + */ +@ApiModel(description = "An object to test discriminator of enum string") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class EnumStringDiscriminator { + /** + * enum string type + */ + @JsonAdapter(EnumStrTypeEnum.Adapter.class) + public enum EnumStrTypeEnum { + A("type_a"), + + B("type_b"); + + private String value; + + EnumStrTypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStrTypeEnum fromValue(String value) { + for (EnumStrTypeEnum b : EnumStrTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumStrTypeEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumStrTypeEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return EnumStrTypeEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_ENUM_STR_TYPE = "enum_str_type"; + @SerializedName(SERIALIZED_NAME_ENUM_STR_TYPE) + protected EnumStrTypeEnum enumStrType; + + public EnumStringDiscriminator() { + } + + public EnumStringDiscriminator enumStrType(EnumStrTypeEnum enumStrType) { + + this.enumStrType = enumStrType; + return this; + } + + /** + * enum string type + * @return enumStrType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "enum string type") + + public EnumStrTypeEnum getEnumStrType() { + return enumStrType; + } + + + public void setEnumStrType(EnumStrTypeEnum enumStrType) { + this.enumStrType = enumStrType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + */ + public EnumStringDiscriminator putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumStringDiscriminator enumStringDiscriminator = (EnumStringDiscriminator) o; + return Objects.equals(this.enumStrType, enumStringDiscriminator.enumStrType)&& + Objects.equals(this.additionalProperties, enumStringDiscriminator.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(enumStrType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumStringDiscriminator {\n"); + sb.append(" enumStrType: ").append(toIndentedString(enumStrType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("enum_str_type"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("enum_str_type"); + } + + /** + * Validates the JSON Object and throws an exception if issues found + * + * @param jsonObj JSON Object + * @throws IOException if the JSON Object is invalid with respect to EnumStringDiscriminator + */ + public static void validateJsonObject(JsonObject jsonObj) throws IOException { + if (jsonObj == null) { + if (!EnumStringDiscriminator.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null + throw new IllegalArgumentException(String.format("The required field(s) %s in EnumStringDiscriminator is not found in the empty JSON string", EnumStringDiscriminator.openapiRequiredFields.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : EnumStringDiscriminator.openapiRequiredFields) { + if (jsonObj.get(requiredField) == null) { + throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!EnumStringDiscriminator.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'EnumStringDiscriminator' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(EnumStringDiscriminator.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, EnumStringDiscriminator value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additonal properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public EnumStringDiscriminator read(JsonReader in) throws IOException { + JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject(); + validateJsonObject(jsonObj); + // store additional fields in the deserialized instance + EnumStringDiscriminator instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else { // non-primitive type + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of EnumStringDiscriminator given an JSON string + * + * @param jsonString JSON string + * @return An instance of EnumStringDiscriminator + * @throws IOException if the JSON string is invalid with respect to EnumStringDiscriminator + */ + public static EnumStringDiscriminator fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, EnumStringDiscriminator.class); + } + + /** + * Convert an instance of EnumStringDiscriminator to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumTest.java index 0a5892a203..58a4f1dfa6 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumTest.java @@ -329,7 +329,7 @@ public class EnumTest { @SerializedName(SERIALIZED_NAME_OUTER_ENUM_INTEGER_DEFAULT_VALUE) private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { @@ -671,9 +671,7 @@ public class EnumTest { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (EnumTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!EnumTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in EnumTest is not found in the empty JSON string", EnumTest.openapiRequiredFields.toString())); } } @@ -684,10 +682,10 @@ public class EnumTest { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonPrimitive()) { + if ((jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) && !jsonObj.get("enum_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string").toString())); } - if (jsonObj.get("enum_string_required") != null && !jsonObj.get("enum_string_required").isJsonPrimitive()) { + if (!jsonObj.get("enum_string_required").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string_required` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string_required").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EquilateralTriangle.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EquilateralTriangle.java index bc5ded6d31..2812fa4d5a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EquilateralTriangle.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EquilateralTriangle.java @@ -57,7 +57,7 @@ public class EquilateralTriangle { @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) private String triangleType; - public EquilateralTriangle() { + public EquilateralTriangle() { } public EquilateralTriangle shapeType(String shapeType) { @@ -207,9 +207,7 @@ public class EquilateralTriangle { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (EquilateralTriangle.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!EquilateralTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in EquilateralTriangle is not found in the empty JSON string", EquilateralTriangle.openapiRequiredFields.toString())); } } @@ -220,10 +218,10 @@ public class EquilateralTriangle { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("shapeType") != null && !jsonObj.get("shapeType").isJsonPrimitive()) { + if (!jsonObj.get("shapeType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); } - if (jsonObj.get("triangleType") != null && !jsonObj.get("triangleType").isJsonPrimitive()) { + if (!jsonObj.get("triangleType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `triangleType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("triangleType").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 4bfdfe254c..4acf99ff46 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -60,7 +60,7 @@ public class FileSchemaTestClass { @SerializedName(SERIALIZED_NAME_FILES) private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { @@ -216,27 +216,27 @@ public class FileSchemaTestClass { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (FileSchemaTestClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!FileSchemaTestClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in FileSchemaTestClass is not found in the empty JSON string", FileSchemaTestClass.openapiRequiredFields.toString())); } } // validate the optional field `file` - if (jsonObj.getAsJsonObject("file") != null) { + if (jsonObj.get("file") != null && !jsonObj.get("file").isJsonNull()) { ModelFile.validateJsonObject(jsonObj.getAsJsonObject("file")); } - JsonArray jsonArrayfiles = jsonObj.getAsJsonArray("files"); - if (jsonArrayfiles != null) { - // ensure the json data is an array - if (!jsonObj.get("files").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `files` to be an array in the JSON string but got `%s`", jsonObj.get("files").toString())); - } + if (jsonObj.get("files") != null && !jsonObj.get("files").isJsonNull()) { + JsonArray jsonArrayfiles = jsonObj.getAsJsonArray("files"); + if (jsonArrayfiles != null) { + // ensure the json data is an array + if (!jsonObj.get("files").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `files` to be an array in the JSON string but got `%s`", jsonObj.get("files").toString())); + } - // validate the optional field `files` (array) - for (int i = 0; i < jsonArrayfiles.size(); i++) { - ModelFile.validateJsonObject(jsonArrayfiles.get(i).getAsJsonObject()); - }; + // validate the optional field `files` (array) + for (int i = 0; i < jsonArrayfiles.size(); i++) { + ModelFile.validateJsonObject(jsonArrayfiles.get(i).getAsJsonObject()); + }; + } } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Foo.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Foo.java index 4d0a5b1fe7..e45183c138 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Foo.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Foo.java @@ -53,7 +53,7 @@ public class Foo { @SerializedName(SERIALIZED_NAME_BAR) private String bar = "bar"; - public Foo() { + public Foo() { } public Foo bar(String bar) { @@ -175,13 +175,11 @@ public class Foo { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Foo.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Foo.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Foo is not found in the empty JSON string", Foo.openapiRequiredFields.toString())); } } - if (jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonPrimitive()) { + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java index 30333d90f1..69cf96e797 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java @@ -54,7 +54,7 @@ public class FooGetDefaultResponse { @SerializedName(SERIALIZED_NAME_STRING) private Foo string; - public FooGetDefaultResponse() { + public FooGetDefaultResponse() { } public FooGetDefaultResponse string(Foo string) { @@ -176,14 +176,12 @@ public class FooGetDefaultResponse { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (FooGetDefaultResponse.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!FooGetDefaultResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in FooGetDefaultResponse is not found in the empty JSON string", FooGetDefaultResponse.openapiRequiredFields.toString())); } } // validate the optional field `string` - if (jsonObj.getAsJsonObject("string") != null) { + if (jsonObj.get("string") != null && !jsonObj.get("string").isJsonNull()) { Foo.validateJsonObject(jsonObj.getAsJsonObject("string")); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FormatTest.java index 0813672f10..0863d0572c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FormatTest.java @@ -106,6 +106,10 @@ public class FormatTest { @SerializedName(SERIALIZED_NAME_UUID) private UUID uuid; + public static final String SERIALIZED_NAME_UUID_WITH_DEFAULT = "uuid_with_default"; + @SerializedName(SERIALIZED_NAME_UUID_WITH_DEFAULT) + private UUID uuidWithDefault = UUID.fromString("11111111-206d-4f12-9f12-3d1e525a8e84"); + public static final String SERIALIZED_NAME_PASSWORD = "password"; @SerializedName(SERIALIZED_NAME_PASSWORD) private String password; @@ -118,7 +122,7 @@ public class FormatTest { @SerializedName(SERIALIZED_NAME_PATTERN_WITH_DIGITS_AND_DELIMITER) private String patternWithDigitsAndDelimiter; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { @@ -430,6 +434,29 @@ public class FormatTest { } + public FormatTest uuidWithDefault(UUID uuidWithDefault) { + + this.uuidWithDefault = uuidWithDefault; + return this; + } + + /** + * Get uuidWithDefault + * @return uuidWithDefault + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public UUID getUuidWithDefault() { + return uuidWithDefault; + } + + + public void setUuidWithDefault(UUID uuidWithDefault) { + this.uuidWithDefault = uuidWithDefault; + } + + public FormatTest password(String password) { this.password = password; @@ -557,6 +584,7 @@ public class FormatTest { Objects.equals(this.date, formatTest.date) && Objects.equals(this.dateTime, formatTest.dateTime) && Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.uuidWithDefault, formatTest.uuidWithDefault) && Objects.equals(this.password, formatTest.password) && Objects.equals(this.patternWithDigits, formatTest.patternWithDigits) && Objects.equals(this.patternWithDigitsAndDelimiter, formatTest.patternWithDigitsAndDelimiter)&& @@ -565,7 +593,7 @@ public class FormatTest { @Override public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, decimal, string, Arrays.hashCode(_byte), binary, date, dateTime, uuid, password, patternWithDigits, patternWithDigitsAndDelimiter, additionalProperties); + return Objects.hash(integer, int32, int64, number, _float, _double, decimal, string, Arrays.hashCode(_byte), binary, date, dateTime, uuid, uuidWithDefault, password, patternWithDigits, patternWithDigitsAndDelimiter, additionalProperties); } @Override @@ -585,6 +613,7 @@ public class FormatTest { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" uuidWithDefault: ").append(toIndentedString(uuidWithDefault)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); @@ -624,6 +653,7 @@ public class FormatTest { openapiFields.add("date"); openapiFields.add("dateTime"); openapiFields.add("uuid"); + openapiFields.add("uuid_with_default"); openapiFields.add("password"); openapiFields.add("pattern_with_digits"); openapiFields.add("pattern_with_digits_and_delimiter"); @@ -644,9 +674,7 @@ public class FormatTest { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (FormatTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!FormatTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in FormatTest is not found in the empty JSON string", FormatTest.openapiRequiredFields.toString())); } } @@ -657,19 +685,22 @@ public class FormatTest { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("string") != null && !jsonObj.get("string").isJsonPrimitive()) { + if ((jsonObj.get("string") != null && !jsonObj.get("string").isJsonNull()) && !jsonObj.get("string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string").toString())); } - if (jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonPrimitive()) { + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); } - if (jsonObj.get("password") != null && !jsonObj.get("password").isJsonPrimitive()) { + if ((jsonObj.get("uuid_with_default") != null && !jsonObj.get("uuid_with_default").isJsonNull()) && !jsonObj.get("uuid_with_default").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `uuid_with_default` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid_with_default").toString())); + } + if (!jsonObj.get("password").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); } - if (jsonObj.get("pattern_with_digits") != null && !jsonObj.get("pattern_with_digits").isJsonPrimitive()) { + if ((jsonObj.get("pattern_with_digits") != null && !jsonObj.get("pattern_with_digits").isJsonNull()) && !jsonObj.get("pattern_with_digits").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `pattern_with_digits` to be a primitive type in the JSON string but got `%s`", jsonObj.get("pattern_with_digits").toString())); } - if (jsonObj.get("pattern_with_digits_and_delimiter") != null && !jsonObj.get("pattern_with_digits_and_delimiter").isJsonPrimitive()) { + if ((jsonObj.get("pattern_with_digits_and_delimiter") != null && !jsonObj.get("pattern_with_digits_and_delimiter").isJsonNull()) && !jsonObj.get("pattern_with_digits_and_delimiter").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `pattern_with_digits_and_delimiter` to be a primitive type in the JSON string but got `%s`", jsonObj.get("pattern_with_digits_and_delimiter").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/GrandparentAnimal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/GrandparentAnimal.java index faa905c767..a5876f2aa3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/GrandparentAnimal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/GrandparentAnimal.java @@ -54,7 +54,7 @@ public class GrandparentAnimal { @SerializedName(SERIALIZED_NAME_PET_TYPE) protected String petType; - public GrandparentAnimal() { + public GrandparentAnimal() { this.petType = this.getClass().getSimpleName(); } @@ -178,9 +178,7 @@ public class GrandparentAnimal { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (GrandparentAnimal.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!GrandparentAnimal.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in GrandparentAnimal is not found in the empty JSON string", GrandparentAnimal.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index 654a34acbb..0fe00c40c3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -57,7 +57,7 @@ public class HasOnlyReadOnly { @SerializedName(SERIALIZED_NAME_FOO) private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @@ -197,16 +197,14 @@ public class HasOnlyReadOnly { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (HasOnlyReadOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!HasOnlyReadOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in HasOnlyReadOnly is not found in the empty JSON string", HasOnlyReadOnly.openapiRequiredFields.toString())); } } - if (jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonPrimitive()) { + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); } - if (jsonObj.get("foo") != null && !jsonObj.get("foo").isJsonPrimitive()) { + if ((jsonObj.get("foo") != null && !jsonObj.get("foo").isJsonNull()) && !jsonObj.get("foo").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `foo` to be a primitive type in the JSON string but got `%s`", jsonObj.get("foo").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HealthCheckResult.java index 9053adf5a3..75f3d35db2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HealthCheckResult.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -55,7 +55,7 @@ public class HealthCheckResult { @SerializedName(SERIALIZED_NAME_NULLABLE_MESSAGE) private String nullableMessage; - public HealthCheckResult() { + public HealthCheckResult() { } public HealthCheckResult nullableMessage(String nullableMessage) { @@ -188,13 +188,11 @@ public class HealthCheckResult { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (HealthCheckResult.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!HealthCheckResult.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in HealthCheckResult is not found in the empty JSON string", HealthCheckResult.openapiRequiredFields.toString())); } } - if (jsonObj.get("NullableMessage") != null && !jsonObj.get("NullableMessage").isJsonPrimitive()) { + if ((jsonObj.get("NullableMessage") != null && !jsonObj.get("NullableMessage").isJsonNull()) && !jsonObj.get("NullableMessage").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `NullableMessage` to be a primitive type in the JSON string but got `%s`", jsonObj.get("NullableMessage").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java index 8f53ad4cd7..d900a2689c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java @@ -57,7 +57,7 @@ public class IsoscelesTriangle { @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) private String triangleType; - public IsoscelesTriangle() { + public IsoscelesTriangle() { } public IsoscelesTriangle shapeType(String shapeType) { @@ -170,9 +170,7 @@ public class IsoscelesTriangle { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (IsoscelesTriangle.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!IsoscelesTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in IsoscelesTriangle is not found in the empty JSON string", IsoscelesTriangle.openapiRequiredFields.toString())); } } @@ -191,10 +189,10 @@ public class IsoscelesTriangle { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("shapeType") != null && !jsonObj.get("shapeType").isJsonPrimitive()) { + if (!jsonObj.get("shapeType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); } - if (jsonObj.get("triangleType") != null && !jsonObj.get("triangleType").isJsonPrimitive()) { + if (!jsonObj.get("triangleType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `triangleType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("triangleType").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MapTest.java index 33aa426778..8c4ff43c33 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MapTest.java @@ -114,7 +114,7 @@ public class MapTest { @SerializedName(SERIALIZED_NAME_INDIRECT_MAP) private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { @@ -346,9 +346,7 @@ public class MapTest { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (MapTest.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!MapTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in MapTest is not found in the empty JSON string", MapTest.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index c687b90a0c..31c906e162 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -66,7 +66,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_MAP) private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { @@ -248,13 +248,11 @@ public class MixedPropertiesAndAdditionalPropertiesClass { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in MixedPropertiesAndAdditionalPropertiesClass is not found in the empty JSON string", MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.toString())); } } - if (jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonPrimitive()) { + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Model200Response.java index 2a50f1d5dd..7ada25c4a3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Model200Response.java @@ -58,7 +58,7 @@ public class Model200Response { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { @@ -206,13 +206,11 @@ public class Model200Response { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Model200Response.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Model200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Model200Response is not found in the empty JSON string", Model200Response.openapiRequiredFields.toString())); } } - if (jsonObj.get("class") != null && !jsonObj.get("class").isJsonPrimitive()) { + if ((jsonObj.get("class") != null && !jsonObj.get("class").isJsonNull()) && !jsonObj.get("class").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("class").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelApiResponse.java index ceae89017c..fd093ddf00 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -61,7 +61,7 @@ public class ModelApiResponse { @SerializedName(SERIALIZED_NAME_MESSAGE) private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { @@ -235,16 +235,14 @@ public class ModelApiResponse { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelApiResponse.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelApiResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelApiResponse is not found in the empty JSON string", ModelApiResponse.openapiRequiredFields.toString())); } } - if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonPrimitive()) { + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); } - if (jsonObj.get("message") != null && !jsonObj.get("message").isJsonPrimitive()) { + if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelFile.java index 19b8d34165..5dda8fc3e2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelFile.java @@ -54,7 +54,7 @@ public class ModelFile { @SerializedName(SERIALIZED_NAME_SOURCE_U_R_I) private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { @@ -176,13 +176,11 @@ public class ModelFile { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelFile.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelFile.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelFile is not found in the empty JSON string", ModelFile.openapiRequiredFields.toString())); } } - if (jsonObj.get("sourceURI") != null && !jsonObj.get("sourceURI").isJsonPrimitive()) { + if ((jsonObj.get("sourceURI") != null && !jsonObj.get("sourceURI").isJsonNull()) && !jsonObj.get("sourceURI").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `sourceURI` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sourceURI").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelList.java index c11740aa77..764fc3b52e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelList.java @@ -53,7 +53,7 @@ public class ModelList { @SerializedName(SERIALIZED_NAME_123LIST) private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { @@ -175,13 +175,11 @@ public class ModelList { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelList.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelList.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelList is not found in the empty JSON string", ModelList.openapiRequiredFields.toString())); } } - if (jsonObj.get("123-list") != null && !jsonObj.get("123-list").isJsonPrimitive()) { + if ((jsonObj.get("123-list") != null && !jsonObj.get("123-list").isJsonNull()) && !jsonObj.get("123-list").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `123-list` to be a primitive type in the JSON string but got `%s`", jsonObj.get("123-list").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java index 27677e517b..ba7d286b5e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -54,7 +54,7 @@ public class ModelReturn { @SerializedName(SERIALIZED_NAME_RETURN) private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { @@ -176,9 +176,7 @@ public class ModelReturn { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ModelReturn.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ModelReturn.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ModelReturn is not found in the empty JSON string", ModelReturn.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Name.java index b0ff9da609..46625eb384 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Name.java @@ -66,7 +66,7 @@ public class Name { @SerializedName(SERIALIZED_NAME_123NUMBER) private Integer _123number; - public Name() { + public Name() { } @@ -259,9 +259,7 @@ public class Name { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Name.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Name.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Name is not found in the empty JSON string", Name.openapiRequiredFields.toString())); } } @@ -272,7 +270,7 @@ public class Name { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("property") != null && !jsonObj.get("property").isJsonPrimitive()) { + if ((jsonObj.get("property") != null && !jsonObj.get("property").isJsonNull()) && !jsonObj.get("property").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `property` to be a primitive type in the JSON string but got `%s`", jsonObj.get("property").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java index 6c1d46e4f2..cadd5c9bed 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java @@ -105,7 +105,7 @@ public class NullableClass { @SerializedName(SERIALIZED_NAME_OBJECT_ITEMS_NULLABLE) private Map objectItemsNullable = null; - public NullableClass() { + public NullableClass() { } public NullableClass integerProp(Integer integerProp) { @@ -535,9 +535,7 @@ public class NullableClass { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (NullableClass.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!NullableClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in NullableClass is not found in the empty JSON string", NullableClass.openapiRequiredFields.toString())); } } @@ -549,19 +547,19 @@ public class NullableClass { throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `NullableClass` properties. JSON: %s", entry.getKey(), jsonObj.toString())); } } - if (jsonObj.get("string_prop") != null && !jsonObj.get("string_prop").isJsonPrimitive()) { + if ((jsonObj.get("string_prop") != null && !jsonObj.get("string_prop").isJsonNull()) && !jsonObj.get("string_prop").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `string_prop` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string_prop").toString())); } // ensure the json data is an array - if (jsonObj.get("array_nullable_prop") != null && !jsonObj.get("array_nullable_prop").isJsonArray()) { + if (!jsonObj.get("array_nullable_prop").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_nullable_prop` to be an array in the JSON string but got `%s`", jsonObj.get("array_nullable_prop").toString())); } // ensure the json data is an array - if (jsonObj.get("array_and_items_nullable_prop") != null && !jsonObj.get("array_and_items_nullable_prop").isJsonArray()) { + if (!jsonObj.get("array_and_items_nullable_prop").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_and_items_nullable_prop` to be an array in the JSON string but got `%s`", jsonObj.get("array_and_items_nullable_prop").toString())); } // ensure the json data is an array - if (jsonObj.get("array_items_nullable") != null && !jsonObj.get("array_items_nullable").isJsonArray()) { + if (!jsonObj.get("array_items_nullable").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_items_nullable` to be an array in the JSON string but got `%s`", jsonObj.get("array_items_nullable").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberOnly.java index 7dea8b0ecf..76ed0276d9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -54,7 +54,7 @@ public class NumberOnly { @SerializedName(SERIALIZED_NAME_JUST_NUMBER) private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { @@ -176,9 +176,7 @@ public class NumberOnly { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (NumberOnly.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!NumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in NumberOnly is not found in the empty JSON string", NumberOnly.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java index 7454088d2e..81633a463d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -69,7 +69,7 @@ public class ObjectWithDeprecatedFields { @SerializedName(SERIALIZED_NAME_BARS) private List bars = null; - public ObjectWithDeprecatedFields() { + public ObjectWithDeprecatedFields() { } public ObjectWithDeprecatedFields uuid(String uuid) { @@ -283,21 +283,19 @@ public class ObjectWithDeprecatedFields { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ObjectWithDeprecatedFields.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ObjectWithDeprecatedFields.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ObjectWithDeprecatedFields is not found in the empty JSON string", ObjectWithDeprecatedFields.openapiRequiredFields.toString())); } } - if (jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonPrimitive()) { + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); } // validate the optional field `deprecatedRef` - if (jsonObj.getAsJsonObject("deprecatedRef") != null) { + if (jsonObj.get("deprecatedRef") != null && !jsonObj.get("deprecatedRef").isJsonNull()) { DeprecatedObject.validateJsonObject(jsonObj.getAsJsonObject("deprecatedRef")); } // ensure the json data is an array - if (jsonObj.get("bars") != null && !jsonObj.get("bars").isJsonArray()) { + if (!jsonObj.get("bars").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `bars` to be an array in the JSON string but got `%s`", jsonObj.get("bars").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Order.java index a56fa5f28a..da6dc68411 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Order.java @@ -123,7 +123,7 @@ public class Order { @SerializedName(SERIALIZED_NAME_COMPLETE) private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { @@ -375,13 +375,11 @@ public class Order { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Order.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Order.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Order is not found in the empty JSON string", Order.openapiRequiredFields.toString())); } } - if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonPrimitive()) { + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterComposite.java index 011acb3a58..eaf4cbc922 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -62,7 +62,7 @@ public class OuterComposite { @SerializedName(SERIALIZED_NAME_MY_BOOLEAN) private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { @@ -236,13 +236,11 @@ public class OuterComposite { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (OuterComposite.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!OuterComposite.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in OuterComposite is not found in the empty JSON string", OuterComposite.openapiRequiredFields.toString())); } } - if (jsonObj.get("my_string") != null && !jsonObj.get("my_string").isJsonPrimitive()) { + if ((jsonObj.get("my_string") != null && !jsonObj.get("my_string").isJsonNull()) && !jsonObj.get("my_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `my_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("my_string").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ParentPet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ParentPet.java index 25313f8266..cdb27e8560 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ParentPet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ParentPet.java @@ -50,7 +50,7 @@ import org.openapitools.client.JSON; */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class ParentPet extends GrandparentAnimal { - public ParentPet() { + public ParentPet() { this.petType = this.getClass().getSimpleName(); } /** @@ -149,9 +149,7 @@ public class ParentPet extends GrandparentAnimal { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ParentPet.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ParentPet.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ParentPet is not found in the empty JSON string", ParentPet.openapiRequiredFields.toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java index 8078f1b07d..1c506e68a8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java @@ -126,7 +126,7 @@ public class Pet { @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { @@ -393,9 +393,7 @@ public class Pet { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Pet.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Pet.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Pet is not found in the empty JSON string", Pet.openapiRequiredFields.toString())); } } @@ -407,29 +405,31 @@ public class Pet { } } // validate the optional field `category` - if (jsonObj.getAsJsonObject("category") != null) { + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { Category.validateJsonObject(jsonObj.getAsJsonObject("category")); } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if (!jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } // ensure the json data is an array - if (jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonArray()) { + if ((jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonNull()) && !jsonObj.get("photoUrls").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); } - JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); - if (jsonArraytags != null) { - // ensure the json data is an array - if (!jsonObj.get("tags").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); - } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } - // validate the optional field `tags` (array) - for (int i = 0; i < jsonArraytags.size(); i++) { - Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); - }; + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); + }; + } } - if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonPrimitive()) { + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java index 3fde0c9b9c..94f5d943e1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java @@ -126,7 +126,7 @@ public class PetWithRequiredTags { @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status; - public PetWithRequiredTags() { + public PetWithRequiredTags() { } public PetWithRequiredTags id(Long id) { @@ -391,9 +391,7 @@ public class PetWithRequiredTags { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (PetWithRequiredTags.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!PetWithRequiredTags.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in PetWithRequiredTags is not found in the empty JSON string", PetWithRequiredTags.openapiRequiredFields.toString())); } } @@ -405,29 +403,27 @@ public class PetWithRequiredTags { } } // validate the optional field `category` - if (jsonObj.getAsJsonObject("category") != null) { + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { Category.validateJsonObject(jsonObj.getAsJsonObject("category")); } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if (!jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } // ensure the json data is an array - if (jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonArray()) { + if ((jsonObj.get("photoUrls") != null && !jsonObj.get("photoUrls").isJsonNull()) && !jsonObj.get("photoUrls").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); } - JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); - if (jsonArraytags != null) { - // ensure the json data is an array - if (!jsonObj.get("tags").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); - } - - // validate the optional field `tags` (array) - for (int i = 0; i < jsonArraytags.size(); i++) { - Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); - }; + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); } - if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonPrimitive()) { + + JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + // validate the required field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject()); + }; + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java index e2c3d4b33c..887c057b99 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java @@ -53,7 +53,7 @@ public class QuadrilateralInterface { @SerializedName(SERIALIZED_NAME_QUADRILATERAL_TYPE) private String quadrilateralType; - public QuadrilateralInterface() { + public QuadrilateralInterface() { } public QuadrilateralInterface quadrilateralType(String quadrilateralType) { @@ -176,9 +176,7 @@ public class QuadrilateralInterface { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (QuadrilateralInterface.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!QuadrilateralInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in QuadrilateralInterface is not found in the empty JSON string", QuadrilateralInterface.openapiRequiredFields.toString())); } } @@ -189,7 +187,7 @@ public class QuadrilateralInterface { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("quadrilateralType") != null && !jsonObj.get("quadrilateralType").isJsonPrimitive()) { + if (!jsonObj.get("quadrilateralType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `quadrilateralType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("quadrilateralType").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index f5c37a84d4..ab47432067 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -57,7 +57,7 @@ public class ReadOnlyFirst { @SerializedName(SERIALIZED_NAME_BAZ) private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @@ -204,16 +204,14 @@ public class ReadOnlyFirst { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ReadOnlyFirst.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ReadOnlyFirst.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ReadOnlyFirst is not found in the empty JSON string", ReadOnlyFirst.openapiRequiredFields.toString())); } } - if (jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonPrimitive()) { + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); } - if (jsonObj.get("baz") != null && !jsonObj.get("baz").isJsonPrimitive()) { + if ((jsonObj.get("baz") != null && !jsonObj.get("baz").isJsonNull()) && !jsonObj.get("baz").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `baz` to be a primitive type in the JSON string but got `%s`", jsonObj.get("baz").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ScaleneTriangle.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ScaleneTriangle.java index 079d9435e6..9c7d73ef97 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ScaleneTriangle.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ScaleneTriangle.java @@ -57,7 +57,7 @@ public class ScaleneTriangle { @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) private String triangleType; - public ScaleneTriangle() { + public ScaleneTriangle() { } public ScaleneTriangle shapeType(String shapeType) { @@ -207,9 +207,7 @@ public class ScaleneTriangle { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ScaleneTriangle.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ScaleneTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ScaleneTriangle is not found in the empty JSON string", ScaleneTriangle.openapiRequiredFields.toString())); } } @@ -220,10 +218,10 @@ public class ScaleneTriangle { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("shapeType") != null && !jsonObj.get("shapeType").isJsonPrimitive()) { + if (!jsonObj.get("shapeType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); } - if (jsonObj.get("triangleType") != null && !jsonObj.get("triangleType").isJsonPrimitive()) { + if (!jsonObj.get("triangleType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `triangleType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("triangleType").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ShapeInterface.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ShapeInterface.java index 4eba102348..14bfd02fff 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ShapeInterface.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ShapeInterface.java @@ -53,7 +53,7 @@ public class ShapeInterface { @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) private String shapeType; - public ShapeInterface() { + public ShapeInterface() { } public ShapeInterface shapeType(String shapeType) { @@ -176,9 +176,7 @@ public class ShapeInterface { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (ShapeInterface.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!ShapeInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in ShapeInterface is not found in the empty JSON string", ShapeInterface.openapiRequiredFields.toString())); } } @@ -189,7 +187,7 @@ public class ShapeInterface { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("shapeType") != null && !jsonObj.get("shapeType").isJsonPrimitive()) { + if (!jsonObj.get("shapeType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java index ff057da23a..6296f4423f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java @@ -57,7 +57,7 @@ public class SimpleQuadrilateral { @SerializedName(SERIALIZED_NAME_QUADRILATERAL_TYPE) private String quadrilateralType; - public SimpleQuadrilateral() { + public SimpleQuadrilateral() { } public SimpleQuadrilateral shapeType(String shapeType) { @@ -207,9 +207,7 @@ public class SimpleQuadrilateral { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (SimpleQuadrilateral.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!SimpleQuadrilateral.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in SimpleQuadrilateral is not found in the empty JSON string", SimpleQuadrilateral.openapiRequiredFields.toString())); } } @@ -220,10 +218,10 @@ public class SimpleQuadrilateral { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("shapeType") != null && !jsonObj.get("shapeType").isJsonPrimitive()) { + if (!jsonObj.get("shapeType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); } - if (jsonObj.get("quadrilateralType") != null && !jsonObj.get("quadrilateralType").isJsonPrimitive()) { + if (!jsonObj.get("quadrilateralType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `quadrilateralType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("quadrilateralType").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SpecialModelName.java index c9c51593e8..52f467174c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -57,7 +57,7 @@ public class SpecialModelName { @SerializedName(SERIALIZED_NAME_SPECIAL_MODEL_NAME) private String specialModelName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { @@ -205,13 +205,11 @@ public class SpecialModelName { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (SpecialModelName.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!SpecialModelName.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in SpecialModelName is not found in the empty JSON string", SpecialModelName.openapiRequiredFields.toString())); } } - if (jsonObj.get("_special_model.name_") != null && !jsonObj.get("_special_model.name_").isJsonPrimitive()) { + if ((jsonObj.get("_special_model.name_") != null && !jsonObj.get("_special_model.name_").isJsonNull()) && !jsonObj.get("_special_model.name_").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `_special_model.name_` to be a primitive type in the JSON string but got `%s`", jsonObj.get("_special_model.name_").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java index 34a2a5d9d4..64e7edf961 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java @@ -57,7 +57,7 @@ public class Tag { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { @@ -205,13 +205,11 @@ public class Tag { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Tag.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Tag.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Tag is not found in the empty JSON string", Tag.openapiRequiredFields.toString())); } } - if (jsonObj.get("name") != null && !jsonObj.get("name").isJsonPrimitive()) { + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TriangleInterface.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TriangleInterface.java index c4a2b0dfd3..481cc8ff83 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TriangleInterface.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TriangleInterface.java @@ -53,7 +53,7 @@ public class TriangleInterface { @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) private String triangleType; - public TriangleInterface() { + public TriangleInterface() { } public TriangleInterface triangleType(String triangleType) { @@ -176,9 +176,7 @@ public class TriangleInterface { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (TriangleInterface.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!TriangleInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in TriangleInterface is not found in the empty JSON string", TriangleInterface.openapiRequiredFields.toString())); } } @@ -189,7 +187,7 @@ public class TriangleInterface { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("triangleType") != null && !jsonObj.get("triangleType").isJsonPrimitive()) { + if (!jsonObj.get("triangleType").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `triangleType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("triangleType").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/User.java index 8cfe38da4a..cdf8d7b86c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/User.java @@ -98,7 +98,7 @@ public class User { @SerializedName(SERIALIZED_NAME_ANY_TYPE_PROP_NULLABLE) private Object anyTypePropNullable = null; - public User() { + public User() { } public User id(Long id) { @@ -517,28 +517,26 @@ public class User { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (User.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!User.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in User is not found in the empty JSON string", User.openapiRequiredFields.toString())); } } - if (jsonObj.get("username") != null && !jsonObj.get("username").isJsonPrimitive()) { + if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString())); } - if (jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonPrimitive()) { + if ((jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonNull()) && !jsonObj.get("firstName").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `firstName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("firstName").toString())); } - if (jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonPrimitive()) { + if ((jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonNull()) && !jsonObj.get("lastName").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `lastName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("lastName").toString())); } - if (jsonObj.get("email") != null && !jsonObj.get("email").isJsonPrimitive()) { + if ((jsonObj.get("email") != null && !jsonObj.get("email").isJsonNull()) && !jsonObj.get("email").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `email` to be a primitive type in the JSON string but got `%s`", jsonObj.get("email").toString())); } - if (jsonObj.get("password") != null && !jsonObj.get("password").isJsonPrimitive()) { + if ((jsonObj.get("password") != null && !jsonObj.get("password").isJsonNull()) && !jsonObj.get("password").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); } - if (jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonPrimitive()) { + if ((jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonNull()) && !jsonObj.get("phone").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `phone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("phone").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Whale.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Whale.java index 32e54ee066..a2b89819cc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Whale.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Whale.java @@ -61,7 +61,7 @@ public class Whale { @SerializedName(SERIALIZED_NAME_CLASS_NAME) private String className; - public Whale() { + public Whale() { } public Whale hasBaleen(Boolean hasBaleen) { @@ -236,9 +236,7 @@ public class Whale { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Whale.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Whale.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Whale is not found in the empty JSON string", Whale.openapiRequiredFields.toString())); } } @@ -249,7 +247,7 @@ public class Whale { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("className") != null && !jsonObj.get("className").isJsonPrimitive()) { + if (!jsonObj.get("className").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Zebra.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Zebra.java index 788ac740b1..61d7009c60 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Zebra.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Zebra.java @@ -106,7 +106,7 @@ public class Zebra { @SerializedName(SERIALIZED_NAME_CLASS_NAME) private String className; - public Zebra() { + public Zebra() { } public Zebra type(TypeEnum type) { @@ -255,9 +255,7 @@ public class Zebra { */ public static void validateJsonObject(JsonObject jsonObj) throws IOException { if (jsonObj == null) { - if (Zebra.openapiRequiredFields.isEmpty()) { - return; - } else { // has required fields + if (!Zebra.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null throw new IllegalArgumentException(String.format("The required field(s) %s in Zebra is not found in the empty JSON string", Zebra.openapiRequiredFields.toString())); } } @@ -268,10 +266,10 @@ public class Zebra { throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString())); } } - if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonPrimitive()) { + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); } - if (jsonObj.get("className") != null && !jsonObj.get("className").isJsonPrimitive()) { + if (!jsonObj.get("className").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString())); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java index 889ac07190..4c79a25d1f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.*; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import java.io.IOException; @@ -544,6 +545,19 @@ public class JSONTest { } } + + /** + * Test validateJsonObject with null object + */ + @Test + public void testValidateJsonObject() throws Exception { + JsonObject jsonObject = new JsonObject(); + Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Pet.validateJsonObject(jsonObject); + }); + assertEquals(exception.getMessage(), "The required field `photoUrls` is not found in the JSON string: {}"); + } + /** * Test additional properties. */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1Test.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1Test.java new file mode 100644 index 0000000000..427d1c9cde --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1Test.java @@ -0,0 +1,50 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 + */ +public class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1Test { + private final ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 model = new ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1(); + + /** + * Model tests for ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 + */ + @Test + public void testArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1() { + // TODO: test ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java new file mode 100644 index 0000000000..f45d5e5a38 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java @@ -0,0 +1,50 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumStringDiscriminator + */ +public class EnumStringDiscriminatorTest { + private final EnumStringDiscriminator model = new EnumStringDiscriminator(); + + /** + * Model tests for EnumStringDiscriminator + */ + @Test + public void testEnumStringDiscriminator() { + // TODO: test EnumStringDiscriminator + } + + /** + * Test the property 'enumStrType' + */ + @Test + public void enumStrTypeTest() { + // TODO: test enumStrType + } + +} diff --git a/samples/client/petstore/java/rest-assured-jackson/api/openapi.yaml b/samples/client/petstore/java/rest-assured-jackson/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/rest-assured-jackson/api/openapi.yaml +++ b/samples/client/petstore/java/rest-assured-jackson/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index f9a9a3d9f7..5cbbc944ed 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -41,7 +41,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 5042678d91..6aeeab6e23 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -42,7 +42,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 3f14c0556c..59b17b2e39 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -41,7 +41,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 08e66c4a55..6ff7a2ba91 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -83,7 +83,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 2341d7367d..d3632af8fe 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -41,7 +41,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index 5531b90c00..ef73880cce 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -42,7 +42,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index be5b538e53..ff9ebb6ecd 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -41,7 +41,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index e3d50bc073..04ad699e04 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -41,7 +41,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Animal.java index 3b0b60e1fd..1411f6638a 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Animal.java @@ -60,7 +60,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 93c455587f..29daca2645 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -42,7 +42,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 8e87ac5b3d..35a2ccb8fc 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -42,7 +42,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayTest.java index 4cf4c59f7f..f518e99634 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -50,7 +50,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/BigCat.java index 6edb131472..81d23e9ecf 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/BigCat.java @@ -88,7 +88,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/BigCatAllOf.java index 8166257c60..cb76016095 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -79,7 +79,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Capitalization.java index 81024c4b79..d82a736f7c 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Capitalization.java @@ -59,7 +59,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Cat.java index 514efd6246..92bc74064f 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Cat.java @@ -53,7 +53,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/CatAllOf.java index 840565434b..28b9816e66 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -40,7 +40,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Category.java index 65981c4b14..a08abd6cf5 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Category.java @@ -43,7 +43,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ClassModel.java index 69c4acbcdd..f270ccf180 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ClassModel.java @@ -40,7 +40,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Client.java index 187c5aa0f4..1d686ea73e 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Client.java @@ -39,7 +39,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Dog.java index edb3b07653..d916236a93 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Dog.java @@ -49,7 +49,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/DogAllOf.java index 6f512f0f71..8000634eec 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -40,7 +40,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/EnumArrays.java index 15e56c7b19..4ebb826c4a 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -115,7 +115,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/EnumTest.java index f144e900b2..3de82ecb55 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/EnumTest.java @@ -201,7 +201,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 9faa20ad35..9dde20a346 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -46,7 +46,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FormatTest.java index c0cd9d15da..2dcb979b41 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FormatTest.java @@ -97,7 +97,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index eb5c4d964c..b2b8e723ad 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -44,7 +44,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/MapTest.java index 631eb280a2..659ca398f4 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/MapTest.java @@ -88,7 +88,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 2b60fe13b1..c273303322 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -52,7 +52,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Model200Response.java index d0e1dfa83a..71edd3c34b 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Model200Response.java @@ -45,7 +45,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 4ee61b5bab..122291c12c 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -48,7 +48,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelFile.java index 6197afe891..81f6b06526 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelFile.java @@ -41,7 +41,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelList.java index b68373d3d8..6db63dc2f4 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelList.java @@ -40,7 +40,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelReturn.java index 0879834b0b..53889ad0e3 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -41,7 +41,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Name.java index 87c3cae986..95ec5a5b6a 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Name.java @@ -52,7 +52,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/NumberOnly.java index 027c1c3cc6..da67bca1f7 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -40,7 +40,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Order.java index e835998227..0100873954 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Order.java @@ -97,7 +97,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/OuterComposite.java index 8865835c60..274ea3aa37 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -48,7 +48,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Pet.java index 515e741f67..09da789c15 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Pet.java @@ -103,7 +103,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 12743501db..138ac347af 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -43,7 +43,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/SpecialModelName.java index b380bed012..210ef37de1 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -40,7 +40,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Tag.java index a8cefec4a1..2c902675ce 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Tag.java @@ -43,7 +43,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index be4591d3ef..1150d78875 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -58,7 +58,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/TypeHolderExample.java index 619e407341..cda873cd34 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -62,7 +62,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/User.java index 568b1cd119..8a6fff61d9 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/User.java @@ -67,7 +67,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/XmlItem.java index dbf1dc9883..bd23bdd5f6 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/XmlItem.java @@ -154,7 +154,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/rest-assured/api/openapi.yaml b/samples/client/petstore/java/rest-assured/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/rest-assured/api/openapi.yaml +++ b/samples/client/petstore/java/rest-assured/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 6d9fb4b082..c4876c0bf0 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesAnyType extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 2696ab3b28..d4ffbfa0d0 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesArray extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 1101adfc1a..e4d010d057 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesBoolean extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 61d3719165..7ad9aee4ec 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -80,7 +80,7 @@ public class AdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_ANYTYPE3) private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 585b989d1e..1648625276 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesInteger extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index 061cd04d14..278a45a75d 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesNumber extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index 457a011f3e..8d1c6efecd 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesObject extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 6dd39c57cc..dfd38220df 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesString extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Animal.java index d0561d918a..4fa10b5bf9 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Animal.java @@ -43,8 +43,7 @@ public class Animal { @SerializedName(SERIALIZED_NAME_COLOR) private String color = "red"; - public Animal() { - this.className = this.getClass().getSimpleName(); + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index f6b21b232e..e017fefa00 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_NUMBER) private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 794697abc4..054c38b2cc 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_NUMBER) private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayTest.java index cd85842d0e..4ac43365c6 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/BigCat.java index 721093a3f3..d05a1cfecd 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/BigCat.java @@ -88,8 +88,8 @@ public class BigCat extends Cat { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCat() { - this.className = this.getClass().getSimpleName(); + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/BigCatAllOf.java index c4f9e990b3..ada32f6d15 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -87,7 +87,7 @@ public class BigCatAllOf { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Capitalization.java index 95713ca6c4..8163980396 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { @SerializedName(SERIALIZED_NAME_A_T_T_N_A_M_E) private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Cat.java index 5d1cce9024..745bcc9685 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Cat.java @@ -38,8 +38,8 @@ public class Cat extends Animal { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public Cat() { - this.className = this.getClass().getSimpleName(); + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/CatAllOf.java index 8b97e3b2b9..9283a81fc6 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -36,7 +36,7 @@ public class CatAllOf { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Category.java index ba1ed8a254..ba795fff69 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { @SerializedName(SERIALIZED_NAME_NAME) private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ClassModel.java index 50081ae04a..4bde08b8bc 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Client.java index 6ef69ead6e..fcb613b4ef 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { @SerializedName(SERIALIZED_NAME_CLIENT) private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Dog.java index ec383b6773..f729e8beac 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Dog.java @@ -37,8 +37,8 @@ public class Dog extends Animal { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public Dog() { - this.className = this.getClass().getSimpleName(); + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/DogAllOf.java index 5be5691895..fd7bd22452 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -36,7 +36,7 @@ public class DogAllOf { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/EnumArrays.java index 1b3644ddf5..4726f9ccfe 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -136,7 +136,7 @@ public class EnumArrays { @SerializedName(SERIALIZED_NAME_ARRAY_ENUM) private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/EnumTest.java index 7f6f400d06..f07814e10f 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/EnumTest.java @@ -245,7 +245,7 @@ public class EnumTest { @SerializedName(SERIALIZED_NAME_OUTER_ENUM) private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 574c78efbb..2f4865a408 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { @SerializedName(SERIALIZED_NAME_FILES) private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FormatTest.java index 6844e8665a..7dd186d00f 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FormatTest.java @@ -93,7 +93,7 @@ public class FormatTest { @SerializedName(SERIALIZED_NAME_BIG_DECIMAL) private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index 1ef8d3843d..79c326baf7 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -40,7 +40,7 @@ public class HasOnlyReadOnly { @SerializedName(SERIALIZED_NAME_FOO) private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/MapTest.java index 74012df8c5..05aa33ede6 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/MapTest.java @@ -97,7 +97,7 @@ public class MapTest { @SerializedName(SERIALIZED_NAME_INDIRECT_MAP) private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 0e1097e8b8..92da08fc5f 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_MAP) private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Model200Response.java index ddcb13b399..c4d5d1df8c 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Model200Response.java @@ -41,7 +41,7 @@ public class Model200Response { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 4d4eae275e..83cf2ad0d9 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -44,7 +44,7 @@ public class ModelApiResponse { @SerializedName(SERIALIZED_NAME_MESSAGE) private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelFile.java index 44f900da98..c6020d9c93 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelFile.java @@ -37,7 +37,7 @@ public class ModelFile { @SerializedName(SERIALIZED_NAME_SOURCE_U_R_I) private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelList.java index d3a2c81507..0b4d91f469 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelList.java @@ -36,7 +36,7 @@ public class ModelList { @SerializedName(SERIALIZED_NAME_123LIST) private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelReturn.java index 8640d92796..e311a922cc 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -37,7 +37,7 @@ public class ModelReturn { @SerializedName(SERIALIZED_NAME_RETURN) private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Name.java index 2758711e84..fdfea8003d 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { @SerializedName(SERIALIZED_NAME_123NUMBER) private Integer _123number; - public Name() { + public Name() { } diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/NumberOnly.java index 5899f65a5d..f472a1b880 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { @SerializedName(SERIALIZED_NAME_JUST_NUMBER) private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Order.java index 4ad9a1cec5..377eb49de8 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Order.java @@ -106,7 +106,7 @@ public class Order { @SerializedName(SERIALIZED_NAME_COMPLETE) private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/OuterComposite.java index ebf67bacef..30e95730d0 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { @SerializedName(SERIALIZED_NAME_MY_BOOLEAN) private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Pet.java index 254d6823ec..50f4c06248 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Pet.java @@ -111,7 +111,7 @@ public class Pet { @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 969b906135..393046c702 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { @SerializedName(SERIALIZED_NAME_BAZ) private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/SpecialModelName.java index 06b70cadcc..3a93077144 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -36,7 +36,7 @@ public class SpecialModelName { @SerializedName(SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME) private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Tag.java index 15378fc8ad..5fe380ee0c 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index 3fcc932d8e..aa86186e0d 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -55,7 +55,7 @@ public class TypeHolderDefault { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/TypeHolderExample.java index d945f570f5..dcd0277cd5 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -59,7 +59,7 @@ public class TypeHolderExample { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/User.java index 12fb6d2787..b413b4a5e7 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { @SerializedName(SERIALIZED_NAME_USER_STATUS) private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/XmlItem.java index 9a42f393cd..6a09923532 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/XmlItem.java @@ -151,7 +151,7 @@ public class XmlItem { @SerializedName(SERIALIZED_NAME_PREFIX_NS_WRAPPED_ARRAY) private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/resteasy/api/openapi.yaml b/samples/client/petstore/java/resteasy/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/resteasy/api/openapi.yaml +++ b/samples/client/petstore/java/resteasy/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java index 3f1e53a374..aa848d48d5 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java @@ -666,6 +666,38 @@ public class ApiClient extends JavaTimeFormatter { Entity entity = serialize(body, formParams, contentType); + try (Response response = invoke(invocationBuilder, method, entity)) { + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = buildResponseHeaders(response); + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), + message, + buildResponseHeaders(response), + respBody); + } + } + } + + private Response invoke(Invocation.Builder invocationBuilder, String method, Entity entity) throws ApiException { Response response = null; if ("GET".equals(method)) { @@ -688,36 +720,10 @@ public class ApiClient extends JavaTimeFormatter { throw new ApiException(500, "unknown method type " + method); } - statusCode = response.getStatusInfo().getStatusCode(); - responseHeaders = buildResponseHeaders(response); - - if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { - return null; - } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { - if (returnType == null) - return null; - else - return deserialize(response, returnType); - } else { - String message = "error"; - String respBody = null; - if (response.hasEntity()) { - try { - respBody = String.valueOf(response.readEntity(String.class)); - message = respBody; - } catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatus(), - message, - buildResponseHeaders(response), - respBody); - } + return response; } - /** + /** * Build the Client used to make HTTP requests. */ private Client buildHttpClient(boolean debugging) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 957cc2b807..0cbfacebcd 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index e5162ab461..8192afcfd8 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 98ea69f7f4..266eee7e60 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 22fe0a8e0f..b205a2ff70 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -80,7 +80,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 3a87682ab4..d2cb247fe9 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index c6da3609d4..9a15f92689 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index ec6a2360fe..f0e0d637a6 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 3ba318c8ac..f1a56ef222 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Animal.java index be898d61d2..fb3560d3ef 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Animal.java @@ -57,7 +57,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 395b4c4d40..84ecf3c60c 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 81437ecc35..5a740ed59d 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayTest.java index 29e8fde2a2..f649ccdafc 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/BigCat.java index c1685041c0..31311ed0c5 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,7 +85,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/BigCatAllOf.java index fb358abee3..f4390e9b32 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -76,7 +76,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Capitalization.java index 09da87c767..75dab11565 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Cat.java index b5408a8315..7269e26ddd 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Cat.java @@ -50,7 +50,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/CatAllOf.java index 9af537be46..6a40fe1cc2 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -37,7 +37,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Category.java index 9ecb9793f8..95ba07594c 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ClassModel.java index 02a70314cf..c112b0dbfd 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Client.java index c0e1209608..ee1f6eb2b4 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Dog.java index bf9838d6f6..193f040fc5 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Dog.java @@ -46,7 +46,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/DogAllOf.java index 22f41e01ea..d37bc6d62a 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -37,7 +37,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumArrays.java index f5b42b0b87..216f767fef 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -112,7 +112,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumTest.java index 12b3b19a57..6fe3181370 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumTest.java @@ -198,7 +198,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 43c10d8609..ae5247c54e 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FormatTest.java index cef5858fe1..f1aa6b0859 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FormatTest.java @@ -94,7 +94,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index a79abdb993..45c377620b 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -41,7 +41,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MapTest.java index d50e30db74..3ee0b0ac01 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MapTest.java @@ -85,7 +85,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 999c32ef2b..9f7331d1d2 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Model200Response.java index a05c698660..18596e30dc 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Model200Response.java @@ -42,7 +42,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 8c90d06494..9ab4b19971 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -45,7 +45,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelFile.java index 8647283641..cc921fbcb0 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelFile.java @@ -38,7 +38,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelList.java index 82abfba9e3..4dd418a4f5 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelList.java @@ -37,7 +37,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelReturn.java index 06fc43f8eb..35a0b1966d 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -38,7 +38,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Name.java index b263b708fe..56bae65fa6 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/NumberOnly.java index 4a268ea06e..fd7c5ed5d1 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Order.java index 4fccc19338..2f838cffbf 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Order.java @@ -94,7 +94,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/OuterComposite.java index 710f350303..324da496f6 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java index 27121c6969..908d26373e 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java @@ -100,7 +100,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 1130124051..6860d65e9c 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/SpecialModelName.java index 0d71d05b2e..6d199444c9 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -37,7 +37,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Tag.java index 25e766c40e..2a68d0029a 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index b4e2af9d25..543e5c031d 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -55,7 +55,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderExample.java index e550b7a421..2b40049239 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -59,7 +59,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/User.java index a289c89f5e..fe0c60b880 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/XmlItem.java index f038a2d4b9..597c1b98a9 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/XmlItem.java @@ -151,7 +151,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/resttemplate-withXml/api/openapi.yaml b/samples/client/petstore/java/resttemplate-withXml/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/resttemplate-withXml/api/openapi.yaml +++ b/samples/client/petstore/java/resttemplate-withXml/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/resttemplate-withXml/pom.xml b/samples/client/petstore/java/resttemplate-withXml/pom.xml index 97d4d4a21b..405a56e26c 100644 --- a/samples/client/petstore/java/resttemplate-withXml/pom.xml +++ b/samples/client/petstore/java/resttemplate-withXml/pom.xml @@ -250,18 +250,22 @@ ${jackson-databind-nullable-version} - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson-version} - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson-version} - + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson-version} + + + io.github.threeten-jaxb + threeten-jaxb-core + 1.2 + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + jakarta.annotation jakarta.annotation-api @@ -281,8 +285,8 @@ UTF-8 1.5.22 5.3.18 - 2.10.5 - 2.11.4 + 2.12.7 + 2.12.7 0.2.3 1.3.5 1.0.0 diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index a6b4473f8d..c82808d90d 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -28,6 +28,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * AdditionalPropertiesAnyType @@ -44,7 +46,8 @@ public class AdditionalPropertiesAnyType extends HashMap { @XmlElement(name = "name") private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index daeb05b457..c59f2bea3e 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -29,6 +29,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * AdditionalPropertiesArray @@ -45,7 +47,8 @@ public class AdditionalPropertiesArray extends HashMap { @XmlElement(name = "name") private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 7702ad08ce..124751d3e3 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -28,6 +28,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * AdditionalPropertiesBoolean @@ -44,7 +46,8 @@ public class AdditionalPropertiesBoolean extends HashMap { @XmlElement(name = "name") private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 528a69212c..ee697f019f 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -30,6 +30,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * AdditionalPropertiesClass @@ -120,7 +122,7 @@ public class AdditionalPropertiesClass { @XmlElement(name = "anytype_3") private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 35f1354b31..ba86e1ed33 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -28,6 +28,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * AdditionalPropertiesInteger @@ -44,7 +46,8 @@ public class AdditionalPropertiesInteger extends HashMap { @XmlElement(name = "name") private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index 855869f6c4..53657111ae 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -29,6 +29,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * AdditionalPropertiesNumber @@ -45,7 +47,8 @@ public class AdditionalPropertiesNumber extends HashMap { @XmlElement(name = "name") private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index ab334d13d1..3312bee5fc 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -28,6 +28,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * AdditionalPropertiesObject @@ -44,7 +46,8 @@ public class AdditionalPropertiesObject extends HashMap { @XmlElement(name = "name") private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 0213454f77..c6272a34d1 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -28,6 +28,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * AdditionalPropertiesString @@ -44,7 +46,8 @@ public class AdditionalPropertiesString extends HashMap { @XmlElement(name = "name") private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Animal.java index eb4e1af576..439f370537 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Animal.java @@ -32,6 +32,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Animal @@ -64,7 +66,7 @@ public class Animal { @XmlElement(name = "color") private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index ee9eb8dbd4..88cb4f91ca 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -29,6 +29,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * ArrayOfArrayOfNumberOnly @@ -48,7 +50,7 @@ public class ArrayOfArrayOfNumberOnly { @XmlElement(name = "arrayArrayNumber") private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index e70efdd577..5bcdac541f 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -29,6 +29,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * ArrayOfNumberOnly @@ -48,7 +50,7 @@ public class ArrayOfNumberOnly { @XmlElement(name = "arrayNumber") private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayTest.java index c8fe4d1a1f..b9b6546abf 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -29,6 +29,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * ArrayTest @@ -64,7 +66,7 @@ public class ArrayTest { @XmlElement(name = "arrayArrayOfModel") private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/BigCat.java index 82a7e4c772..24353d460e 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/BigCat.java @@ -30,6 +30,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * BigCat @@ -97,7 +99,8 @@ public class BigCat extends Cat { @XmlElement(name = "kind") private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/BigCatAllOf.java index 15a88cc6ae..0b0730f17d 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * BigCatAllOf @@ -88,7 +90,7 @@ public class BigCatAllOf { @XmlElement(name = "kind") private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Capitalization.java index a296d6dc23..309073e8a4 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Capitalization.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Capitalization @@ -67,7 +69,7 @@ public class Capitalization { @XmlElement(name = "ATT_NAME") private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Cat.java index 312f554fc3..abe46d9695 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Cat.java @@ -31,6 +31,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Cat @@ -56,7 +58,8 @@ public class Cat extends Animal { @XmlElement(name = "declawed") private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/CatAllOf.java index bae7e67fe7..145660967d 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * CatAllOf @@ -43,7 +45,7 @@ public class CatAllOf { @XmlElement(name = "declawed") private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Category.java index bd3fdf8094..0a5585ddfe 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Category.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Category @@ -47,7 +49,7 @@ public class Category { @XmlElement(name = "name") private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ClassModel.java index f7377c80c0..6b2a45f29d 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ClassModel.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Model for testing model with \"_class\" property @@ -43,7 +45,7 @@ public class ClassModel { @XmlElement(name = "_class") private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Client.java index 762614cbb9..112268df26 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Client.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Client @@ -42,7 +44,7 @@ public class Client { @XmlElement(name = "client") private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Dog.java index b5f4c7167c..23ebc3b4aa 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Dog.java @@ -30,6 +30,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Dog @@ -52,7 +54,8 @@ public class Dog extends Animal { @XmlElement(name = "breed") private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/DogAllOf.java index da3a0d6210..b7b57541d0 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * DogAllOf @@ -43,7 +45,7 @@ public class DogAllOf { @XmlElement(name = "breed") private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumArrays.java index d102eb00fc..8b0ef2984a 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -28,6 +28,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * EnumArrays @@ -130,7 +132,7 @@ public class EnumArrays { @XmlElement(name = "arrayEnum") private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumClass.java index 5356a732d8..18f9f75446 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumClass.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumClass.java @@ -19,6 +19,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumTest.java index 44a1106b42..3068986f75 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/EnumTest.java @@ -27,6 +27,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * EnumTest @@ -226,7 +228,7 @@ public class EnumTest { @XmlElement(name = "outerEnum") private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 95ea9e88ae..bf3c325a59 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -29,6 +29,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * FileSchemaTestClass @@ -53,7 +55,7 @@ public class FileSchemaTestClass { @XmlElement(name = "files") private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FormatTest.java index 76958400e1..22235663ec 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FormatTest.java @@ -31,6 +31,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * FormatTest @@ -99,6 +101,7 @@ public class FormatTest { public static final String JSON_PROPERTY_DATE_TIME = "dateTime"; @XmlElement(name = "dateTime") + @XmlJavaTypeAdapter(OffsetDateTimeXmlAdapter.class) private OffsetDateTime dateTime; public static final String JSON_PROPERTY_UUID = "uuid"; @@ -113,7 +116,7 @@ public class FormatTest { @XmlElement(name = "BigDecimal") private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index 097f0f784b..853253ce66 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * HasOnlyReadOnly @@ -48,7 +50,7 @@ public class HasOnlyReadOnly { @XmlElement(name = "foo") private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } /** diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/MapTest.java index ff64987430..caf99e9cdd 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/MapTest.java @@ -28,6 +28,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * MapTest @@ -110,7 +112,7 @@ public class MapTest { @XmlElement(name = "inner") private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 9a300fe98f..067dbaae75 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -31,6 +31,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * MixedPropertiesAndAdditionalPropertiesClass @@ -51,6 +53,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_DATE_TIME = "dateTime"; @XmlElement(name = "dateTime") + @XmlJavaTypeAdapter(OffsetDateTimeXmlAdapter.class) private OffsetDateTime dateTime; public static final String JSON_PROPERTY_MAP = "map"; @@ -60,7 +63,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @XmlElement(name = "inner") private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Model200Response.java index 44c6d249fe..e1f1e82a8a 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Model200Response.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Model for testing model name starting with number @@ -49,7 +51,7 @@ public class Model200Response { @XmlElement(name = "class") private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 67fe248692..7ca016e3f1 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * ModelApiResponse @@ -53,7 +55,7 @@ public class ModelApiResponse { @XmlElement(name = "message") private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelFile.java index c87bc91994..5e1e658339 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelFile.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Must be named `File` for test. @@ -44,7 +46,7 @@ public class ModelFile { @XmlElement(name = "sourceURI") private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelList.java index 32aadcded8..4e8b59214f 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelList.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * ModelList @@ -43,7 +45,7 @@ public class ModelList { @XmlElement(name = "123-list") private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelReturn.java index eb1143e807..a6bd5181ca 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Model for testing reserved words @@ -44,7 +46,7 @@ public class ModelReturn { @XmlElement(name = "return") private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Name.java index c47c69fb15..07d349ffe8 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Name.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Model for testing model name same as property name @@ -58,7 +60,7 @@ public class Name { @XmlElement(name = "123Number") private Integer _123number; - public Name() { + public Name() { } public Name name(Integer name) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/NumberOnly.java index 90fe00684b..56b3493c7a 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -27,6 +27,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * NumberOnly @@ -43,7 +45,7 @@ public class NumberOnly { @XmlElement(name = "JustNumber") private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Order.java index ebbc0be053..785731d304 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Order.java @@ -27,6 +27,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Order @@ -58,6 +60,7 @@ public class Order { public static final String JSON_PROPERTY_SHIP_DATE = "shipDate"; @XmlElement(name = "shipDate") + @XmlJavaTypeAdapter(OffsetDateTimeXmlAdapter.class) private OffsetDateTime shipDate; /** @@ -110,7 +113,7 @@ public class Order { @XmlElement(name = "complete") private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/OuterComposite.java index c95caa0854..2076c99237 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -27,6 +27,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * OuterComposite @@ -53,7 +55,7 @@ public class OuterComposite { @XmlElement(name = "my_boolean") private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/OuterEnum.java index f9eb538c60..829a6ff776 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/OuterEnum.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/OuterEnum.java @@ -19,6 +19,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Pet.java index 220ab00320..fb09368d49 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Pet.java @@ -33,6 +33,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Pet @@ -124,7 +126,7 @@ public class Pet { @XmlElement(name = "status") private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 8abba1a8d6..b7ec69a38e 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * ReadOnlyFirst @@ -47,7 +49,7 @@ public class ReadOnlyFirst { @XmlElement(name = "baz") private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } /** diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/SpecialModelName.java index bf584e481a..0ca3654eb8 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * SpecialModelName @@ -43,7 +45,7 @@ public class SpecialModelName { @XmlElement(name = "$special[property.name]") private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Tag.java index b79352b6a7..6346b39d04 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/Tag.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * Tag @@ -47,7 +49,7 @@ public class Tag { @XmlElement(name = "name") private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index f3cae2496a..d88fceeca9 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -29,6 +29,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * TypeHolderDefault @@ -68,7 +70,7 @@ public class TypeHolderDefault { @XmlElement(name = "arrayItem") private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/TypeHolderExample.java index ba08b0e7b4..0b653bc9ca 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -29,6 +29,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * TypeHolderExample @@ -73,7 +75,7 @@ public class TypeHolderExample { @XmlElement(name = "arrayItem") private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/User.java index bfdc061945..b7958fec16 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/User.java @@ -26,6 +26,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * User @@ -77,7 +79,7 @@ public class User { @XmlElement(name = "userStatus") private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/XmlItem.java index 121199ecad..ce485ac6bf 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/XmlItem.java @@ -29,6 +29,8 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.dataformat.xml.annotation.*; import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.*; +import io.github.threetenjaxb.core.*; /** * XmlItem @@ -217,7 +219,7 @@ public class XmlItem { @XmlElementWrapper(namespace="http://f.com/schema", name = "prefix_ns_wrapped_array") private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/resttemplate/api/openapi.yaml b/samples/client/petstore/java/resttemplate/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/resttemplate/api/openapi.yaml +++ b/samples/client/petstore/java/resttemplate/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/resttemplate/pom.xml b/samples/client/petstore/java/resttemplate/pom.xml index 6bad3bcb6a..9401bad784 100644 --- a/samples/client/petstore/java/resttemplate/pom.xml +++ b/samples/client/petstore/java/resttemplate/pom.xml @@ -249,11 +249,11 @@ jackson-databind-nullable ${jackson-databind-nullable-version} - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson-version} - + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + jakarta.annotation jakarta.annotation-api @@ -273,8 +273,8 @@ UTF-8 1.5.22 5.3.18 - 2.10.5 - 2.11.4 + 2.12.7 + 2.12.7 0.2.3 1.3.5 1.0.0 diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 957cc2b807..0cbfacebcd 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index e5162ab461..8192afcfd8 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 98ea69f7f4..266eee7e60 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 22fe0a8e0f..b205a2ff70 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -80,7 +80,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 3a87682ab4..d2cb247fe9 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index c6da3609d4..9a15f92689 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index ec6a2360fe..f0e0d637a6 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 3ba318c8ac..f1a56ef222 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Animal.java index be898d61d2..fb3560d3ef 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Animal.java @@ -57,7 +57,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 395b4c4d40..84ecf3c60c 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 81437ecc35..5a740ed59d 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayTest.java index 29e8fde2a2..f649ccdafc 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/BigCat.java index c1685041c0..31311ed0c5 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,7 +85,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/BigCatAllOf.java index fb358abee3..f4390e9b32 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -76,7 +76,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Capitalization.java index 09da87c767..75dab11565 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Cat.java index b5408a8315..7269e26ddd 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Cat.java @@ -50,7 +50,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/CatAllOf.java index 9af537be46..6a40fe1cc2 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -37,7 +37,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Category.java index 9ecb9793f8..95ba07594c 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ClassModel.java index 02a70314cf..c112b0dbfd 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Client.java index c0e1209608..ee1f6eb2b4 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Dog.java index bf9838d6f6..193f040fc5 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Dog.java @@ -46,7 +46,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/DogAllOf.java index 22f41e01ea..d37bc6d62a 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -37,7 +37,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/EnumArrays.java index f5b42b0b87..216f767fef 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -112,7 +112,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/EnumTest.java index 12b3b19a57..6fe3181370 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/EnumTest.java @@ -198,7 +198,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 43c10d8609..ae5247c54e 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FormatTest.java index cef5858fe1..f1aa6b0859 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FormatTest.java @@ -94,7 +94,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index a79abdb993..45c377620b 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -41,7 +41,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/MapTest.java index d50e30db74..3ee0b0ac01 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/MapTest.java @@ -85,7 +85,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 999c32ef2b..9f7331d1d2 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Model200Response.java index a05c698660..18596e30dc 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Model200Response.java @@ -42,7 +42,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 8c90d06494..9ab4b19971 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -45,7 +45,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelFile.java index 8647283641..cc921fbcb0 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelFile.java @@ -38,7 +38,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelList.java index 82abfba9e3..4dd418a4f5 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelList.java @@ -37,7 +37,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelReturn.java index 06fc43f8eb..35a0b1966d 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -38,7 +38,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Name.java index b263b708fe..56bae65fa6 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/NumberOnly.java index 4a268ea06e..fd7c5ed5d1 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Order.java index 4fccc19338..2f838cffbf 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Order.java @@ -94,7 +94,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/OuterComposite.java index 710f350303..324da496f6 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Pet.java index 27121c6969..908d26373e 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Pet.java @@ -100,7 +100,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 1130124051..6860d65e9c 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/SpecialModelName.java index 0d71d05b2e..6d199444c9 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -37,7 +37,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Tag.java index 25e766c40e..2a68d0029a 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index b4e2af9d25..543e5c031d 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -55,7 +55,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/TypeHolderExample.java index e550b7a421..2b40049239 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -59,7 +59,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/User.java index a289c89f5e..fe0c60b880 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/XmlItem.java index f038a2d4b9..597c1b98a9 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/XmlItem.java @@ -151,7 +151,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/retrofit2-play26/api/openapi.yaml b/samples/client/petstore/java/retrofit2-play26/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/retrofit2-play26/api/openapi.yaml +++ b/samples/client/petstore/java/retrofit2-play26/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 1fb2379e81..776bb88513 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -40,7 +40,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 130f672b1a..813765154f 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -41,7 +41,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 462c0c3d6e..8337ec452b 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -40,7 +40,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 70bc409d8d..4cab2f0c31 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -82,7 +82,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 784bdd22cb..5d99b62f84 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -40,7 +40,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index b501d4495c..a7643a8560 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -41,7 +41,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index 5b98814ffe..428838afbc 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -40,7 +40,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 411b9db6bf..e643e4e29c 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -40,7 +40,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Animal.java index 3baf0b0983..11d4b66410 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Animal.java @@ -59,7 +59,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 555cf4f6dd..b1bb4ed1fe 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -41,7 +41,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 9e76090d30..886614f147 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -41,7 +41,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java index a5b45ae5b9..14d3909c09 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -49,7 +49,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/BigCat.java index d91efb3cc3..402014ad08 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/BigCat.java @@ -87,7 +87,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/BigCatAllOf.java index 2fc2d25b51..cbfa55aee9 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -78,7 +78,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Capitalization.java index 793d7f0cee..3cc33dcb1d 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Capitalization.java @@ -58,7 +58,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Cat.java index 8047e092d5..1c9c811d49 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Cat.java @@ -52,7 +52,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/CatAllOf.java index 1674eae9c1..136a0c3479 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -39,7 +39,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Category.java index d1161eed8b..f51d968508 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Category.java @@ -42,7 +42,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ClassModel.java index c467f79b3f..5b528b4919 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ClassModel.java @@ -39,7 +39,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Client.java index 027622d616..0d3929e337 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Client.java @@ -38,7 +38,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Dog.java index b6814c55b1..f36b4be3f1 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Dog.java @@ -48,7 +48,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/DogAllOf.java index 184f58e1a7..bdbcf6b3af 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -39,7 +39,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumArrays.java index a24ef7f852..8b76bc7134 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -114,7 +114,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumTest.java index 82c14c6a24..e779006e54 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/EnumTest.java @@ -200,7 +200,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 5e98e4ce7d..de9a6a5a5a 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -45,7 +45,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java index b70f44ff63..60b6f6ca70 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java @@ -96,7 +96,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index 7eb4e87ff7..764b5f2d00 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -43,7 +43,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MapTest.java index 7d5ce3d321..9b3bf4fbe4 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MapTest.java @@ -87,7 +87,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 0b25adf454..7854b03d33 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -51,7 +51,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Model200Response.java index 0eae3e4158..3c91863878 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Model200Response.java @@ -44,7 +44,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 1dcde15121..86b85ac56a 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -47,7 +47,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelFile.java index 42060439bf..639548043a 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelFile.java @@ -40,7 +40,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelList.java index 6eb2c78337..d65d4f34aa 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelList.java @@ -39,7 +39,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelReturn.java index 6418b01014..731c547c62 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -40,7 +40,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Name.java index 868bbaeec8..e9f5b31b50 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Name.java @@ -51,7 +51,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/NumberOnly.java index 66b422039b..e9f6b2c94e 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -39,7 +39,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Order.java index 03e9cc9719..c804a69329 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Order.java @@ -96,7 +96,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterComposite.java index 3007e768ff..5276c6c8c6 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -47,7 +47,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java index 22d6c3ec75..9625892244 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java @@ -102,7 +102,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index b196c9adbc..4313d4d2bb 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -42,7 +42,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/SpecialModelName.java index eaeb69cda5..ca41b229f3 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -39,7 +39,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Tag.java index bf8e34e7a3..017cb30311 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Tag.java @@ -42,7 +42,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index d76352b15d..54651462a0 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -57,7 +57,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/TypeHolderExample.java index 2d8afb925b..afa6d0e9a9 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -61,7 +61,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/User.java index b7e85e77bf..2631c0c1d1 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/User.java @@ -66,7 +66,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/XmlItem.java index cdd7061544..31873b6371 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/XmlItem.java @@ -153,7 +153,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/retrofit2/api/openapi.yaml b/samples/client/petstore/java/retrofit2/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/retrofit2/api/openapi.yaml +++ b/samples/client/petstore/java/retrofit2/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 1b5a3cd223..fbe7473d2e 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesAnyType extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 6835e103b6..c084da4df2 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -36,7 +36,8 @@ public class AdditionalPropertiesArray extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 3f2f1b3ba8..ae278ef6fd 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesBoolean extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 36bee14604..3c4a442fa9 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -77,7 +77,7 @@ public class AdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_ANYTYPE3) private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index c90f346b18..5a0562f830 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesInteger extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index b9a1d371fd..292960931b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -36,7 +36,8 @@ public class AdditionalPropertiesNumber extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index a61d030c6c..bbf772c94c 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesObject extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 4745fed665..13c99128e6 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesString extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Animal.java index 24f916d3ad..a48cc8a54f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Animal.java @@ -40,8 +40,7 @@ public class Animal { @SerializedName(SERIALIZED_NAME_COLOR) private String color = "red"; - public Animal() { - this.className = this.getClass().getSimpleName(); + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 6f1d7613af..8e3193a236 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -36,7 +36,7 @@ public class ArrayOfArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_NUMBER) private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index d8ab663ad8..ca384f3c4b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -36,7 +36,7 @@ public class ArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_NUMBER) private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayTest.java index dd8ac4f267..1b3998617a 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -44,7 +44,7 @@ public class ArrayTest { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/BigCat.java index a4e194b964..d0603d0f20 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,8 +85,8 @@ public class BigCat extends Cat { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCat() { - this.className = this.getClass().getSimpleName(); + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/BigCatAllOf.java index 8334448ffd..54e2490e1e 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -84,7 +84,7 @@ public class BigCatAllOf { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Capitalization.java index a99f358698..4a48b25f19 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Capitalization.java @@ -53,7 +53,7 @@ public class Capitalization { @SerializedName(SERIALIZED_NAME_A_T_T_N_A_M_E) private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Cat.java index 06427549ef..e7d693efdb 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Cat.java @@ -35,8 +35,8 @@ public class Cat extends Animal { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public Cat() { - this.className = this.getClass().getSimpleName(); + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/CatAllOf.java index 39c740ffe3..947a132b92 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -33,7 +33,7 @@ public class CatAllOf { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Category.java index 9d7c0e4a1c..74fb50b82f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Category.java @@ -37,7 +37,7 @@ public class Category { @SerializedName(SERIALIZED_NAME_NAME) private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ClassModel.java index eb1d43e00e..ab206751f7 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ClassModel.java @@ -34,7 +34,7 @@ public class ClassModel { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Client.java index 8e5e1694ac..2dd9e90df3 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Client.java @@ -33,7 +33,7 @@ public class Client { @SerializedName(SERIALIZED_NAME_CLIENT) private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Dog.java index 86f8524183..61294befd8 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Dog.java @@ -34,8 +34,8 @@ public class Dog extends Animal { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public Dog() { - this.className = this.getClass().getSimpleName(); + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/DogAllOf.java index b1f42a5f62..c3d273ae47 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -33,7 +33,7 @@ public class DogAllOf { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/EnumArrays.java index 42fd0a61f6..2aacd43537 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -133,7 +133,7 @@ public class EnumArrays { @SerializedName(SERIALIZED_NAME_ARRAY_ENUM) private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/EnumTest.java index 55ddcb829b..8630b96e75 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/EnumTest.java @@ -242,7 +242,7 @@ public class EnumTest { @SerializedName(SERIALIZED_NAME_OUTER_ENUM) private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 61acde71d8..1e00f46c8c 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -40,7 +40,7 @@ public class FileSchemaTestClass { @SerializedName(SERIALIZED_NAME_FILES) private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FormatTest.java index 8f1c8ca978..775f2d19dc 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FormatTest.java @@ -90,7 +90,7 @@ public class FormatTest { @SerializedName(SERIALIZED_NAME_BIG_DECIMAL) private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index b8194dc1df..23259a332c 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -37,7 +37,7 @@ public class HasOnlyReadOnly { @SerializedName(SERIALIZED_NAME_FOO) private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/MapTest.java index a0ed0a782c..1084fa07a8 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/MapTest.java @@ -94,7 +94,7 @@ public class MapTest { @SerializedName(SERIALIZED_NAME_INDIRECT_MAP) private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index ce1edfe85a..afccf3b03d 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -46,7 +46,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_MAP) private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Model200Response.java index 4615091176..f6645fdfd9 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Model200Response.java @@ -38,7 +38,7 @@ public class Model200Response { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 93e9feb5b8..7392a78d91 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -41,7 +41,7 @@ public class ModelApiResponse { @SerializedName(SERIALIZED_NAME_MESSAGE) private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelFile.java index 111a748cef..cfe638a984 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelFile.java @@ -34,7 +34,7 @@ public class ModelFile { @SerializedName(SERIALIZED_NAME_SOURCE_U_R_I) private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelList.java index 2ba46fefd4..194df12419 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelList.java @@ -33,7 +33,7 @@ public class ModelList { @SerializedName(SERIALIZED_NAME_123LIST) private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelReturn.java index 4c0e74f87e..7a66d94525 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -34,7 +34,7 @@ public class ModelReturn { @SerializedName(SERIALIZED_NAME_RETURN) private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Name.java index a0bd099370..35a4908449 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Name.java @@ -46,7 +46,7 @@ public class Name { @SerializedName(SERIALIZED_NAME_123NUMBER) private Integer _123number; - public Name() { + public Name() { } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/NumberOnly.java index 4683086728..f2f603a416 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -34,7 +34,7 @@ public class NumberOnly { @SerializedName(SERIALIZED_NAME_JUST_NUMBER) private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Order.java index 73560da07a..418492d146 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Order.java @@ -103,7 +103,7 @@ public class Order { @SerializedName(SERIALIZED_NAME_COMPLETE) private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/OuterComposite.java index d8c60dcf97..9de8005d7d 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -42,7 +42,7 @@ public class OuterComposite { @SerializedName(SERIALIZED_NAME_MY_BOOLEAN) private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Pet.java index 1664c5658d..bb9b3d215b 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Pet.java @@ -108,7 +108,7 @@ public class Pet { @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index e452bf03a0..97d3f98330 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -37,7 +37,7 @@ public class ReadOnlyFirst { @SerializedName(SERIALIZED_NAME_BAZ) private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/SpecialModelName.java index 271e41f832..d49b88c0c7 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -33,7 +33,7 @@ public class SpecialModelName { @SerializedName(SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME) private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Tag.java index 181b1e6504..65609e24e6 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/Tag.java @@ -37,7 +37,7 @@ public class Tag { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index 2a5f0ab42d..a6667803f3 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -52,7 +52,7 @@ public class TypeHolderDefault { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/TypeHolderExample.java index 69c11bdd46..f8417d8850 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -56,7 +56,7 @@ public class TypeHolderExample { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/User.java index 166fea9628..75f24bb326 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/User.java @@ -61,7 +61,7 @@ public class User { @SerializedName(SERIALIZED_NAME_USER_STATUS) private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/XmlItem.java index d13eb4c220..bcf7dbad97 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/XmlItem.java @@ -148,7 +148,7 @@ public class XmlItem { @SerializedName(SERIALIZED_NAME_PREFIX_NS_WRAPPED_ARRAY) private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/retrofit2rx2/api/openapi.yaml b/samples/client/petstore/java/retrofit2rx2/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/retrofit2rx2/api/openapi.yaml +++ b/samples/client/petstore/java/retrofit2rx2/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 1b5a3cd223..fbe7473d2e 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesAnyType extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 6835e103b6..c084da4df2 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -36,7 +36,8 @@ public class AdditionalPropertiesArray extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 3f2f1b3ba8..ae278ef6fd 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesBoolean extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 36bee14604..3c4a442fa9 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -77,7 +77,7 @@ public class AdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_ANYTYPE3) private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index c90f346b18..5a0562f830 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesInteger extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index b9a1d371fd..292960931b 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -36,7 +36,8 @@ public class AdditionalPropertiesNumber extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index a61d030c6c..bbf772c94c 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesObject extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 4745fed665..13c99128e6 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesString extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Animal.java index 24f916d3ad..a48cc8a54f 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Animal.java @@ -40,8 +40,7 @@ public class Animal { @SerializedName(SERIALIZED_NAME_COLOR) private String color = "red"; - public Animal() { - this.className = this.getClass().getSimpleName(); + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 6f1d7613af..8e3193a236 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -36,7 +36,7 @@ public class ArrayOfArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_NUMBER) private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index d8ab663ad8..ca384f3c4b 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -36,7 +36,7 @@ public class ArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_NUMBER) private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayTest.java index dd8ac4f267..1b3998617a 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -44,7 +44,7 @@ public class ArrayTest { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/BigCat.java index a4e194b964..d0603d0f20 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,8 +85,8 @@ public class BigCat extends Cat { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCat() { - this.className = this.getClass().getSimpleName(); + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/BigCatAllOf.java index 8334448ffd..54e2490e1e 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -84,7 +84,7 @@ public class BigCatAllOf { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Capitalization.java index a99f358698..4a48b25f19 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Capitalization.java @@ -53,7 +53,7 @@ public class Capitalization { @SerializedName(SERIALIZED_NAME_A_T_T_N_A_M_E) private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Cat.java index 06427549ef..e7d693efdb 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Cat.java @@ -35,8 +35,8 @@ public class Cat extends Animal { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public Cat() { - this.className = this.getClass().getSimpleName(); + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/CatAllOf.java index 39c740ffe3..947a132b92 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -33,7 +33,7 @@ public class CatAllOf { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Category.java index 9d7c0e4a1c..74fb50b82f 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Category.java @@ -37,7 +37,7 @@ public class Category { @SerializedName(SERIALIZED_NAME_NAME) private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ClassModel.java index eb1d43e00e..ab206751f7 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ClassModel.java @@ -34,7 +34,7 @@ public class ClassModel { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Client.java index 8e5e1694ac..2dd9e90df3 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Client.java @@ -33,7 +33,7 @@ public class Client { @SerializedName(SERIALIZED_NAME_CLIENT) private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Dog.java index 86f8524183..61294befd8 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Dog.java @@ -34,8 +34,8 @@ public class Dog extends Animal { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public Dog() { - this.className = this.getClass().getSimpleName(); + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/DogAllOf.java index b1f42a5f62..c3d273ae47 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -33,7 +33,7 @@ public class DogAllOf { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/EnumArrays.java index 42fd0a61f6..2aacd43537 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -133,7 +133,7 @@ public class EnumArrays { @SerializedName(SERIALIZED_NAME_ARRAY_ENUM) private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/EnumTest.java index 55ddcb829b..8630b96e75 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/EnumTest.java @@ -242,7 +242,7 @@ public class EnumTest { @SerializedName(SERIALIZED_NAME_OUTER_ENUM) private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 61acde71d8..1e00f46c8c 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -40,7 +40,7 @@ public class FileSchemaTestClass { @SerializedName(SERIALIZED_NAME_FILES) private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FormatTest.java index 8f1c8ca978..775f2d19dc 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FormatTest.java @@ -90,7 +90,7 @@ public class FormatTest { @SerializedName(SERIALIZED_NAME_BIG_DECIMAL) private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index b8194dc1df..23259a332c 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -37,7 +37,7 @@ public class HasOnlyReadOnly { @SerializedName(SERIALIZED_NAME_FOO) private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/MapTest.java index a0ed0a782c..1084fa07a8 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/MapTest.java @@ -94,7 +94,7 @@ public class MapTest { @SerializedName(SERIALIZED_NAME_INDIRECT_MAP) private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index ce1edfe85a..afccf3b03d 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -46,7 +46,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_MAP) private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Model200Response.java index 4615091176..f6645fdfd9 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Model200Response.java @@ -38,7 +38,7 @@ public class Model200Response { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 93e9feb5b8..7392a78d91 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -41,7 +41,7 @@ public class ModelApiResponse { @SerializedName(SERIALIZED_NAME_MESSAGE) private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelFile.java index 111a748cef..cfe638a984 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelFile.java @@ -34,7 +34,7 @@ public class ModelFile { @SerializedName(SERIALIZED_NAME_SOURCE_U_R_I) private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelList.java index 2ba46fefd4..194df12419 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelList.java @@ -33,7 +33,7 @@ public class ModelList { @SerializedName(SERIALIZED_NAME_123LIST) private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelReturn.java index 4c0e74f87e..7a66d94525 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -34,7 +34,7 @@ public class ModelReturn { @SerializedName(SERIALIZED_NAME_RETURN) private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Name.java index a0bd099370..35a4908449 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Name.java @@ -46,7 +46,7 @@ public class Name { @SerializedName(SERIALIZED_NAME_123NUMBER) private Integer _123number; - public Name() { + public Name() { } diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/NumberOnly.java index 4683086728..f2f603a416 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -34,7 +34,7 @@ public class NumberOnly { @SerializedName(SERIALIZED_NAME_JUST_NUMBER) private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Order.java index 73560da07a..418492d146 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Order.java @@ -103,7 +103,7 @@ public class Order { @SerializedName(SERIALIZED_NAME_COMPLETE) private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/OuterComposite.java index d8c60dcf97..9de8005d7d 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -42,7 +42,7 @@ public class OuterComposite { @SerializedName(SERIALIZED_NAME_MY_BOOLEAN) private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Pet.java index 1664c5658d..bb9b3d215b 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Pet.java @@ -108,7 +108,7 @@ public class Pet { @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index e452bf03a0..97d3f98330 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -37,7 +37,7 @@ public class ReadOnlyFirst { @SerializedName(SERIALIZED_NAME_BAZ) private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/SpecialModelName.java index 271e41f832..d49b88c0c7 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -33,7 +33,7 @@ public class SpecialModelName { @SerializedName(SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME) private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Tag.java index 181b1e6504..65609e24e6 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/Tag.java @@ -37,7 +37,7 @@ public class Tag { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index 2a5f0ab42d..a6667803f3 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -52,7 +52,7 @@ public class TypeHolderDefault { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/TypeHolderExample.java index 69c11bdd46..f8417d8850 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -56,7 +56,7 @@ public class TypeHolderExample { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/User.java index 166fea9628..75f24bb326 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/User.java @@ -61,7 +61,7 @@ public class User { @SerializedName(SERIALIZED_NAME_USER_STATUS) private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/XmlItem.java index d13eb4c220..bcf7dbad97 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/XmlItem.java @@ -148,7 +148,7 @@ public class XmlItem { @SerializedName(SERIALIZED_NAME_PREFIX_NS_WRAPPED_ARRAY) private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/retrofit2rx3/api/openapi.yaml b/samples/client/petstore/java/retrofit2rx3/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/retrofit2rx3/api/openapi.yaml +++ b/samples/client/petstore/java/retrofit2rx3/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 1b5a3cd223..fbe7473d2e 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesAnyType extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 6835e103b6..c084da4df2 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -36,7 +36,8 @@ public class AdditionalPropertiesArray extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 3f2f1b3ba8..ae278ef6fd 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesBoolean extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 36bee14604..3c4a442fa9 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -77,7 +77,7 @@ public class AdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_ANYTYPE3) private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index c90f346b18..5a0562f830 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesInteger extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index b9a1d371fd..292960931b 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -36,7 +36,8 @@ public class AdditionalPropertiesNumber extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index a61d030c6c..bbf772c94c 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesObject extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 4745fed665..13c99128e6 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -35,7 +35,8 @@ public class AdditionalPropertiesString extends HashMap { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Animal.java index 24f916d3ad..a48cc8a54f 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Animal.java @@ -40,8 +40,7 @@ public class Animal { @SerializedName(SERIALIZED_NAME_COLOR) private String color = "red"; - public Animal() { - this.className = this.getClass().getSimpleName(); + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 6f1d7613af..8e3193a236 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -36,7 +36,7 @@ public class ArrayOfArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_NUMBER) private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index d8ab663ad8..ca384f3c4b 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -36,7 +36,7 @@ public class ArrayOfNumberOnly { @SerializedName(SERIALIZED_NAME_ARRAY_NUMBER) private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayTest.java index dd8ac4f267..1b3998617a 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -44,7 +44,7 @@ public class ArrayTest { @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/BigCat.java index a4e194b964..d0603d0f20 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,8 +85,8 @@ public class BigCat extends Cat { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCat() { - this.className = this.getClass().getSimpleName(); + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/BigCatAllOf.java index 8334448ffd..54e2490e1e 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -84,7 +84,7 @@ public class BigCatAllOf { @SerializedName(SERIALIZED_NAME_KIND) private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Capitalization.java index a99f358698..4a48b25f19 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Capitalization.java @@ -53,7 +53,7 @@ public class Capitalization { @SerializedName(SERIALIZED_NAME_A_T_T_N_A_M_E) private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Cat.java index 06427549ef..e7d693efdb 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Cat.java @@ -35,8 +35,8 @@ public class Cat extends Animal { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public Cat() { - this.className = this.getClass().getSimpleName(); + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/CatAllOf.java index 39c740ffe3..947a132b92 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -33,7 +33,7 @@ public class CatAllOf { @SerializedName(SERIALIZED_NAME_DECLAWED) private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Category.java index 9d7c0e4a1c..74fb50b82f 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Category.java @@ -37,7 +37,7 @@ public class Category { @SerializedName(SERIALIZED_NAME_NAME) private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ClassModel.java index eb1d43e00e..ab206751f7 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ClassModel.java @@ -34,7 +34,7 @@ public class ClassModel { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Client.java index 8e5e1694ac..2dd9e90df3 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Client.java @@ -33,7 +33,7 @@ public class Client { @SerializedName(SERIALIZED_NAME_CLIENT) private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Dog.java index 86f8524183..61294befd8 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Dog.java @@ -34,8 +34,8 @@ public class Dog extends Animal { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public Dog() { - this.className = this.getClass().getSimpleName(); + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/DogAllOf.java index b1f42a5f62..c3d273ae47 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -33,7 +33,7 @@ public class DogAllOf { @SerializedName(SERIALIZED_NAME_BREED) private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/EnumArrays.java index 42fd0a61f6..2aacd43537 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -133,7 +133,7 @@ public class EnumArrays { @SerializedName(SERIALIZED_NAME_ARRAY_ENUM) private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/EnumTest.java index 55ddcb829b..8630b96e75 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/EnumTest.java @@ -242,7 +242,7 @@ public class EnumTest { @SerializedName(SERIALIZED_NAME_OUTER_ENUM) private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 61acde71d8..1e00f46c8c 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -40,7 +40,7 @@ public class FileSchemaTestClass { @SerializedName(SERIALIZED_NAME_FILES) private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FormatTest.java index 8f1c8ca978..775f2d19dc 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FormatTest.java @@ -90,7 +90,7 @@ public class FormatTest { @SerializedName(SERIALIZED_NAME_BIG_DECIMAL) private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index b8194dc1df..23259a332c 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -37,7 +37,7 @@ public class HasOnlyReadOnly { @SerializedName(SERIALIZED_NAME_FOO) private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/MapTest.java index a0ed0a782c..1084fa07a8 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/MapTest.java @@ -94,7 +94,7 @@ public class MapTest { @SerializedName(SERIALIZED_NAME_INDIRECT_MAP) private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index ce1edfe85a..afccf3b03d 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -46,7 +46,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @SerializedName(SERIALIZED_NAME_MAP) private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Model200Response.java index 4615091176..f6645fdfd9 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Model200Response.java @@ -38,7 +38,7 @@ public class Model200Response { @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 93e9feb5b8..7392a78d91 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -41,7 +41,7 @@ public class ModelApiResponse { @SerializedName(SERIALIZED_NAME_MESSAGE) private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelFile.java index 111a748cef..cfe638a984 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelFile.java @@ -34,7 +34,7 @@ public class ModelFile { @SerializedName(SERIALIZED_NAME_SOURCE_U_R_I) private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelList.java index 2ba46fefd4..194df12419 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelList.java @@ -33,7 +33,7 @@ public class ModelList { @SerializedName(SERIALIZED_NAME_123LIST) private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelReturn.java index 4c0e74f87e..7a66d94525 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -34,7 +34,7 @@ public class ModelReturn { @SerializedName(SERIALIZED_NAME_RETURN) private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Name.java index a0bd099370..35a4908449 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Name.java @@ -46,7 +46,7 @@ public class Name { @SerializedName(SERIALIZED_NAME_123NUMBER) private Integer _123number; - public Name() { + public Name() { } diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/NumberOnly.java index 4683086728..f2f603a416 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -34,7 +34,7 @@ public class NumberOnly { @SerializedName(SERIALIZED_NAME_JUST_NUMBER) private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Order.java index 73560da07a..418492d146 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Order.java @@ -103,7 +103,7 @@ public class Order { @SerializedName(SERIALIZED_NAME_COMPLETE) private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/OuterComposite.java index d8c60dcf97..9de8005d7d 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -42,7 +42,7 @@ public class OuterComposite { @SerializedName(SERIALIZED_NAME_MY_BOOLEAN) private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Pet.java index 1664c5658d..bb9b3d215b 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Pet.java @@ -108,7 +108,7 @@ public class Pet { @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index e452bf03a0..97d3f98330 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -37,7 +37,7 @@ public class ReadOnlyFirst { @SerializedName(SERIALIZED_NAME_BAZ) private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/SpecialModelName.java index 271e41f832..d49b88c0c7 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -33,7 +33,7 @@ public class SpecialModelName { @SerializedName(SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME) private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Tag.java index 181b1e6504..65609e24e6 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/Tag.java @@ -37,7 +37,7 @@ public class Tag { @SerializedName(SERIALIZED_NAME_NAME) private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index 2a5f0ab42d..a6667803f3 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -52,7 +52,7 @@ public class TypeHolderDefault { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/TypeHolderExample.java index 69c11bdd46..f8417d8850 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -56,7 +56,7 @@ public class TypeHolderExample { @SerializedName(SERIALIZED_NAME_ARRAY_ITEM) private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/User.java index 166fea9628..75f24bb326 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/User.java @@ -61,7 +61,7 @@ public class User { @SerializedName(SERIALIZED_NAME_USER_STATUS) private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/XmlItem.java index d13eb4c220..bcf7dbad97 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/XmlItem.java @@ -148,7 +148,7 @@ public class XmlItem { @SerializedName(SERIALIZED_NAME_PREFIX_NS_WRAPPED_ARRAY) private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/vertx-no-nullable/api/openapi.yaml b/samples/client/petstore/java/vertx-no-nullable/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/vertx-no-nullable/api/openapi.yaml +++ b/samples/client/petstore/java/vertx-no-nullable/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 957cc2b807..0cbfacebcd 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index e5162ab461..8192afcfd8 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 98ea69f7f4..266eee7e60 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 22fe0a8e0f..b205a2ff70 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -80,7 +80,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 3a87682ab4..d2cb247fe9 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index c6da3609d4..9a15f92689 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index ec6a2360fe..f0e0d637a6 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 3ba318c8ac..f1a56ef222 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Animal.java index be898d61d2..fb3560d3ef 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Animal.java @@ -57,7 +57,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 395b4c4d40..84ecf3c60c 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 81437ecc35..5a740ed59d 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayTest.java index 29e8fde2a2..f649ccdafc 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/BigCat.java index c1685041c0..31311ed0c5 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,7 +85,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/BigCatAllOf.java index fb358abee3..f4390e9b32 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -76,7 +76,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Capitalization.java index 09da87c767..75dab11565 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Cat.java index b5408a8315..7269e26ddd 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Cat.java @@ -50,7 +50,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/CatAllOf.java index 9af537be46..6a40fe1cc2 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -37,7 +37,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Category.java index 9ecb9793f8..95ba07594c 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ClassModel.java index 02a70314cf..c112b0dbfd 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Client.java index c0e1209608..ee1f6eb2b4 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Dog.java index bf9838d6f6..193f040fc5 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Dog.java @@ -46,7 +46,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/DogAllOf.java index 22f41e01ea..d37bc6d62a 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -37,7 +37,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/EnumArrays.java index f5b42b0b87..216f767fef 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -112,7 +112,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/EnumTest.java index 12b3b19a57..6fe3181370 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/EnumTest.java @@ -198,7 +198,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 43c10d8609..ae5247c54e 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java index 22fc2aa19c..3ae33d5bc8 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java @@ -94,7 +94,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index a79abdb993..45c377620b 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -41,7 +41,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/MapTest.java index d50e30db74..3ee0b0ac01 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/MapTest.java @@ -85,7 +85,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 999c32ef2b..9f7331d1d2 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Model200Response.java index a05c698660..18596e30dc 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Model200Response.java @@ -42,7 +42,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 8c90d06494..9ab4b19971 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -45,7 +45,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelFile.java index 8647283641..cc921fbcb0 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelFile.java @@ -38,7 +38,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelList.java index 82abfba9e3..4dd418a4f5 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelList.java @@ -37,7 +37,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelReturn.java index 06fc43f8eb..35a0b1966d 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -38,7 +38,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Name.java index b263b708fe..56bae65fa6 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/NumberOnly.java index 4a268ea06e..fd7c5ed5d1 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Order.java index 4fccc19338..2f838cffbf 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Order.java @@ -94,7 +94,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/OuterComposite.java index 710f350303..324da496f6 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Pet.java index 27121c6969..908d26373e 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Pet.java @@ -100,7 +100,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 1130124051..6860d65e9c 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/SpecialModelName.java index 0d71d05b2e..6d199444c9 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -37,7 +37,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Tag.java index 25e766c40e..2a68d0029a 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index b4e2af9d25..543e5c031d 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -55,7 +55,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderExample.java index e550b7a421..2b40049239 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -59,7 +59,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/User.java index a289c89f5e..fe0c60b880 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/XmlItem.java index f038a2d4b9..597c1b98a9 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/XmlItem.java @@ -151,7 +151,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/vertx/api/openapi.yaml b/samples/client/petstore/java/vertx/api/openapi.yaml index 3ded94aeaf..151c0e7627 100644 --- a/samples/client/petstore/java/vertx/api/openapi.yaml +++ b/samples/client/petstore/java/vertx/api/openapi.yaml @@ -2164,11 +2164,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2179,6 +2181,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 957cc2b807..0cbfacebcd 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesAnyType extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesAnyType() { + public AdditionalPropertiesAnyType() { + } public AdditionalPropertiesAnyType name(String name) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index e5162ab461..8192afcfd8 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesArray extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesArray() { + public AdditionalPropertiesArray() { + } public AdditionalPropertiesArray name(String name) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 98ea69f7f4..266eee7e60 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesBoolean extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesBoolean() { + public AdditionalPropertiesBoolean() { + } public AdditionalPropertiesBoolean name(String name) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 22fe0a8e0f..b205a2ff70 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -80,7 +80,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_ANYTYPE3 = "anytype_3"; private Object anytype3; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 3a87682ab4..d2cb247fe9 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesInteger extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesInteger() { + public AdditionalPropertiesInteger() { + } public AdditionalPropertiesInteger name(String name) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index c6da3609d4..9a15f92689 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -39,7 +39,8 @@ public class AdditionalPropertiesNumber extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesNumber() { + public AdditionalPropertiesNumber() { + } public AdditionalPropertiesNumber name(String name) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index ec6a2360fe..f0e0d637a6 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesObject extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesObject() { + public AdditionalPropertiesObject() { + } public AdditionalPropertiesObject name(String name) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 3ba318c8ac..f1a56ef222 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -38,7 +38,8 @@ public class AdditionalPropertiesString extends HashMap { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public AdditionalPropertiesString() { + public AdditionalPropertiesString() { + } public AdditionalPropertiesString name(String name) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Animal.java index be898d61d2..fb3560d3ef 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Animal.java @@ -57,7 +57,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 395b4c4d40..84ecf3c60c 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 81437ecc35..5a740ed59d 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayTest.java index 29e8fde2a2..f649ccdafc 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/BigCat.java index c1685041c0..31311ed0c5 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/BigCat.java @@ -85,7 +85,8 @@ public class BigCat extends Cat { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCat() { + public BigCat() { + } public BigCat kind(KindEnum kind) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/BigCatAllOf.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/BigCatAllOf.java index fb358abee3..f4390e9b32 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/BigCatAllOf.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/BigCatAllOf.java @@ -76,7 +76,7 @@ public class BigCatAllOf { public static final String JSON_PROPERTY_KIND = "kind"; private KindEnum kind; - public BigCatAllOf() { + public BigCatAllOf() { } public BigCatAllOf kind(KindEnum kind) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Capitalization.java index 09da87c767..75dab11565 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Cat.java index b5408a8315..7269e26ddd 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Cat.java @@ -50,7 +50,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/CatAllOf.java index 9af537be46..6a40fe1cc2 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -37,7 +37,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Category.java index 9ecb9793f8..95ba07594c 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ClassModel.java index 02a70314cf..c112b0dbfd 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Client.java index c0e1209608..ee1f6eb2b4 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Dog.java index bf9838d6f6..193f040fc5 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Dog.java @@ -46,7 +46,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/DogAllOf.java index 22f41e01ea..d37bc6d62a 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -37,7 +37,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/EnumArrays.java index f5b42b0b87..216f767fef 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -112,7 +112,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/EnumTest.java index 12b3b19a57..6fe3181370 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/EnumTest.java @@ -198,7 +198,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; private OuterEnum outerEnum; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 43c10d8609..ae5247c54e 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FormatTest.java index 22fc2aa19c..3ae33d5bc8 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FormatTest.java @@ -94,7 +94,7 @@ public class FormatTest { public static final String JSON_PROPERTY_BIG_DECIMAL = "BigDecimal"; private BigDecimal bigDecimal; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index a79abdb993..45c377620b 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -41,7 +41,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/MapTest.java index d50e30db74..3ee0b0ac01 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/MapTest.java @@ -85,7 +85,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 999c32ef2b..9f7331d1d2 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Model200Response.java index a05c698660..18596e30dc 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Model200Response.java @@ -42,7 +42,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 8c90d06494..9ab4b19971 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -45,7 +45,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelFile.java index 8647283641..cc921fbcb0 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelFile.java @@ -38,7 +38,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelList.java index 82abfba9e3..4dd418a4f5 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelList.java @@ -37,7 +37,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelReturn.java index 06fc43f8eb..35a0b1966d 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -38,7 +38,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Name.java index b263b708fe..56bae65fa6 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/NumberOnly.java index 4a268ea06e..fd7c5ed5d1 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Order.java index 4fccc19338..2f838cffbf 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Order.java @@ -94,7 +94,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/OuterComposite.java index 710f350303..324da496f6 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Pet.java index 27121c6969..908d26373e 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Pet.java @@ -100,7 +100,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 1130124051..6860d65e9c 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/SpecialModelName.java index 0d71d05b2e..6d199444c9 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -37,7 +37,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Tag.java index 25e766c40e..2a68d0029a 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index b4e2af9d25..543e5c031d 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -55,7 +55,7 @@ public class TypeHolderDefault { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderDefault() { + public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/TypeHolderExample.java index e550b7a421..2b40049239 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -59,7 +59,7 @@ public class TypeHolderExample { public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; private List arrayItem = new ArrayList<>(); - public TypeHolderExample() { + public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/User.java index a289c89f5e..fe0c60b880 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/XmlItem.java index f038a2d4b9..597c1b98a9 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/XmlItem.java @@ -151,7 +151,7 @@ public class XmlItem { public static final String JSON_PROPERTY_PREFIX_NS_WRAPPED_ARRAY = "prefix_ns_wrapped_array"; private List prefixNsWrappedArray = null; - public XmlItem() { + public XmlItem() { } public XmlItem attributeString(String attributeString) { diff --git a/samples/client/petstore/java/webclient-nulable-arrays/build.gradle b/samples/client/petstore/java/webclient-nulable-arrays/build.gradle index df5d3316dc..180ae99a39 100644 --- a/samples/client/petstore/java/webclient-nulable-arrays/build.gradle +++ b/samples/client/petstore/java/webclient-nulable-arrays/build.gradle @@ -114,8 +114,8 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.6.3" spring_boot_version = "2.6.6" - jackson_version = "2.11.4" - jackson_databind_version = "2.11.4" + jackson_version = "2.12.7" + jackson_databind_version = "2.12.7" jackson_databind_nullable_version = "0.2.3" jakarta_annotation_version = "1.3.5" reactor_version = "3.4.3" diff --git a/samples/client/petstore/java/webclient-nulable-arrays/pom.xml b/samples/client/petstore/java/webclient-nulable-arrays/pom.xml index 12bd438445..fbe8f876e7 100644 --- a/samples/client/petstore/java/webclient-nulable-arrays/pom.xml +++ b/samples/client/petstore/java/webclient-nulable-arrays/pom.xml @@ -127,8 +127,8 @@ UTF-8 1.6.3 2.6.6 - 2.11.3 - 2.11.4 + 2.12.7 + 2.12.7 0.2.3 1.3.5 4.13.2 diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/api/DefaultApi.java index 27aa8f5a51..09542762c9 100644 --- a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/api/DefaultApi.java +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -88,8 +88,26 @@ public class DefaultApi { return nullableArrayTestGetRequestCreation().bodyToFlux(localVarReturnType); } + /** + * + * + *

        200 - + * @return ResponseEntity<List<ByteArrayObject>> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono>> nullableArrayTestGetWithHttpInfo() throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return nullableArrayTestGetRequestCreation().toEntityList(localVarReturnType); } + + /** + * + * + *

        200 - + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec nullableArrayTestGetWithResponseSpec() throws WebClientResponseException { + return nullableArrayTestGetRequestCreation(); + } } diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/model/ByteArrayObject.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/model/ByteArrayObject.java index 664f570c7e..a3a2664427 100644 --- a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/model/ByteArrayObject.java +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/model/ByteArrayObject.java @@ -57,7 +57,7 @@ public class ByteArrayObject { public static final String JSON_PROPERTY_INT_FIELD = "intField"; private BigDecimal intField; - public ByteArrayObject() { + public ByteArrayObject() { } public ByteArrayObject nullableArray(byte[] nullableArray) { diff --git a/samples/client/petstore/java/webclient/api/openapi.yaml b/samples/client/petstore/java/webclient/api/openapi.yaml index ccf94d1ff5..f54c98c7f7 100644 --- a/samples/client/petstore/java/webclient/api/openapi.yaml +++ b/samples/client/petstore/java/webclient/api/openapi.yaml @@ -98,6 +98,21 @@ paths: servers: - url: http://petstore.swagger.io/v2 - url: http://path-server-test.petstore.local/v2 + - description: test server with variables + url: "http://{server}.swagger.io:{port}/v2" + variables: + server: + default: petstore + description: target server + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" /pet/findByStatus: get: description: Multiple status values can be provided with comma separated strings @@ -2117,11 +2132,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/webclient/build.gradle b/samples/client/petstore/java/webclient/build.gradle index 5ed93ce970..7d7eb506cd 100644 --- a/samples/client/petstore/java/webclient/build.gradle +++ b/samples/client/petstore/java/webclient/build.gradle @@ -114,8 +114,8 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "1.6.3" spring_boot_version = "2.6.6" - jackson_version = "2.11.4" - jackson_databind_version = "2.11.4" + jackson_version = "2.12.7" + jackson_databind_version = "2.12.7" jackson_databind_nullable_version = "0.2.3" jakarta_annotation_version = "1.3.5" reactor_version = "3.4.3" diff --git a/samples/client/petstore/java/webclient/pom.xml b/samples/client/petstore/java/webclient/pom.xml index cc788c6e7f..cda03fc3ee 100644 --- a/samples/client/petstore/java/webclient/pom.xml +++ b/samples/client/petstore/java/webclient/pom.xml @@ -127,8 +127,8 @@ UTF-8 1.6.3 2.6.6 - 2.11.3 - 2.11.4 + 2.12.7 + 2.12.7 0.2.3 1.3.5 4.13.2 diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 3974c46492..f68bd75357 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -96,8 +96,28 @@ public class AnotherFakeApi { return call123testSpecialTagsRequestCreation(client).bodyToMono(localVarReturnType); } + /** + * To test special tags + * To test special tags and operation ID starting with number + *

        200 - successful operation + * @param client client model + * @return ResponseEntity<Client> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> call123testSpecialTagsWithHttpInfo(Client client) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return call123testSpecialTagsRequestCreation(client).toEntity(localVarReturnType); } + + /** + * To test special tags + * To test special tags and operation ID starting with number + *

        200 - successful operation + * @param client client model + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec call123testSpecialTagsWithResponseSpec(Client client) throws WebClientResponseException { + return call123testSpecialTagsRequestCreation(client); + } } diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/DefaultApi.java index 4579b415e4..70fbac8ecd 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/DefaultApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -88,8 +88,26 @@ public class DefaultApi { return fooGetRequestCreation().bodyToMono(localVarReturnType); } + /** + * + * + *

        0 - response + * @return ResponseEntity<FooGetDefaultResponse> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> fooGetWithHttpInfo() throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return fooGetRequestCreation().toEntity(localVarReturnType); } + + /** + * + * + *

        0 - response + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fooGetWithResponseSpec() throws WebClientResponseException { + return fooGetRequestCreation(); + } } diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeApi.java index cae69eb045..8287c06353 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeApi.java @@ -99,10 +99,28 @@ public class FakeApi { return fakeHealthGetRequestCreation().bodyToMono(localVarReturnType); } + /** + * Health check endpoint + * + *

        200 - The instance started successfully + * @return ResponseEntity<HealthCheckResult> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> fakeHealthGetWithHttpInfo() throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return fakeHealthGetRequestCreation().toEntity(localVarReturnType); } + + /** + * Health check endpoint + * + *

        200 - The instance started successfully + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fakeHealthGetWithResponseSpec() throws WebClientResponseException { + return fakeHealthGetRequestCreation(); + } /** * test http signature authentication * @@ -157,10 +175,33 @@ public class FakeApi { return fakeHttpSignatureTestRequestCreation(pet, query1, header1).bodyToMono(localVarReturnType); } + /** + * test http signature authentication + * + *

        200 - The instance started successfully + * @param pet Pet object that needs to be added to the store + * @param query1 query parameter + * @param header1 header parameter + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> fakeHttpSignatureTestWithHttpInfo(Pet pet, String query1, String header1) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return fakeHttpSignatureTestRequestCreation(pet, query1, header1).toEntity(localVarReturnType); } + + /** + * test http signature authentication + * + *

        200 - The instance started successfully + * @param pet Pet object that needs to be added to the store + * @param query1 query parameter + * @param header1 header parameter + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fakeHttpSignatureTestWithResponseSpec(Pet pet, String query1, String header1) throws WebClientResponseException { + return fakeHttpSignatureTestRequestCreation(pet, query1, header1); + } /** * * Test serialization of outer boolean types @@ -207,10 +248,30 @@ public class FakeApi { return fakeOuterBooleanSerializeRequestCreation(body).bodyToMono(localVarReturnType); } + /** + * + * Test serialization of outer boolean types + *

        200 - Output boolean + * @param body Input boolean as post body + * @return ResponseEntity<Boolean> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> fakeOuterBooleanSerializeWithHttpInfo(Boolean body) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return fakeOuterBooleanSerializeRequestCreation(body).toEntity(localVarReturnType); } + + /** + * + * Test serialization of outer boolean types + *

        200 - Output boolean + * @param body Input boolean as post body + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fakeOuterBooleanSerializeWithResponseSpec(Boolean body) throws WebClientResponseException { + return fakeOuterBooleanSerializeRequestCreation(body); + } /** * * Test serialization of object with outer number type @@ -257,10 +318,30 @@ public class FakeApi { return fakeOuterCompositeSerializeRequestCreation(outerComposite).bodyToMono(localVarReturnType); } + /** + * + * Test serialization of object with outer number type + *

        200 - Output composite + * @param outerComposite Input composite as post body + * @return ResponseEntity<OuterComposite> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> fakeOuterCompositeSerializeWithHttpInfo(OuterComposite outerComposite) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return fakeOuterCompositeSerializeRequestCreation(outerComposite).toEntity(localVarReturnType); } + + /** + * + * Test serialization of object with outer number type + *

        200 - Output composite + * @param outerComposite Input composite as post body + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fakeOuterCompositeSerializeWithResponseSpec(OuterComposite outerComposite) throws WebClientResponseException { + return fakeOuterCompositeSerializeRequestCreation(outerComposite); + } /** * * Test serialization of outer number types @@ -307,10 +388,30 @@ public class FakeApi { return fakeOuterNumberSerializeRequestCreation(body).bodyToMono(localVarReturnType); } + /** + * + * Test serialization of outer number types + *

        200 - Output number + * @param body Input number as post body + * @return ResponseEntity<BigDecimal> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> fakeOuterNumberSerializeWithHttpInfo(BigDecimal body) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return fakeOuterNumberSerializeRequestCreation(body).toEntity(localVarReturnType); } + + /** + * + * Test serialization of outer number types + *

        200 - Output number + * @param body Input number as post body + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fakeOuterNumberSerializeWithResponseSpec(BigDecimal body) throws WebClientResponseException { + return fakeOuterNumberSerializeRequestCreation(body); + } /** * * Test serialization of outer string types @@ -357,10 +458,30 @@ public class FakeApi { return fakeOuterStringSerializeRequestCreation(body).bodyToMono(localVarReturnType); } + /** + * + * Test serialization of outer string types + *

        200 - Output string + * @param body Input string as post body + * @return ResponseEntity<String> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> fakeOuterStringSerializeWithHttpInfo(String body) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return fakeOuterStringSerializeRequestCreation(body).toEntity(localVarReturnType); } + + /** + * + * Test serialization of outer string types + *

        200 - Output string + * @param body Input string as post body + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fakeOuterStringSerializeWithResponseSpec(String body) throws WebClientResponseException { + return fakeOuterStringSerializeRequestCreation(body); + } /** * * Test serialization of enum (int) properties with examples @@ -411,10 +532,30 @@ public class FakeApi { return fakePropertyEnumIntegerSerializeRequestCreation(outerObjectWithEnumProperty).bodyToMono(localVarReturnType); } + /** + * + * Test serialization of enum (int) properties with examples + *

        200 - Output enum (int) + * @param outerObjectWithEnumProperty Input enum (int) as post body + * @return ResponseEntity<OuterObjectWithEnumProperty> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> fakePropertyEnumIntegerSerializeWithHttpInfo(OuterObjectWithEnumProperty outerObjectWithEnumProperty) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return fakePropertyEnumIntegerSerializeRequestCreation(outerObjectWithEnumProperty).toEntity(localVarReturnType); } + + /** + * + * Test serialization of enum (int) properties with examples + *

        200 - Output enum (int) + * @param outerObjectWithEnumProperty Input enum (int) as post body + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fakePropertyEnumIntegerSerializeWithResponseSpec(OuterObjectWithEnumProperty outerObjectWithEnumProperty) throws WebClientResponseException { + return fakePropertyEnumIntegerSerializeRequestCreation(outerObjectWithEnumProperty); + } /** * * For this test, the body has to be a binary file. @@ -461,10 +602,29 @@ public class FakeApi { return testBodyWithBinaryRequestCreation(body).bodyToMono(localVarReturnType); } + /** + * + * For this test, the body has to be a binary file. + *

        200 - Success + * @param body image to upload + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testBodyWithBinaryWithHttpInfo(File body) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testBodyWithBinaryRequestCreation(body).toEntity(localVarReturnType); } + + /** + * + * For this test, the body has to be a binary file. + *

        200 - Success + * @param body image to upload + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testBodyWithBinaryWithResponseSpec(File body) throws WebClientResponseException { + return testBodyWithBinaryRequestCreation(body); + } /** * * For this test, the body for this request must reference a schema named `File`. @@ -511,10 +671,29 @@ public class FakeApi { return testBodyWithFileSchemaRequestCreation(fileSchemaTestClass).bodyToMono(localVarReturnType); } + /** + * + * For this test, the body for this request must reference a schema named `File`. + *

        200 - Success + * @param fileSchemaTestClass The fileSchemaTestClass parameter + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass fileSchemaTestClass) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testBodyWithFileSchemaRequestCreation(fileSchemaTestClass).toEntity(localVarReturnType); } + + /** + * + * For this test, the body for this request must reference a schema named `File`. + *

        200 - Success + * @param fileSchemaTestClass The fileSchemaTestClass parameter + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testBodyWithFileSchemaWithResponseSpec(FileSchemaTestClass fileSchemaTestClass) throws WebClientResponseException { + return testBodyWithFileSchemaRequestCreation(fileSchemaTestClass); + } /** * * @@ -569,10 +748,31 @@ public class FakeApi { return testBodyWithQueryParamsRequestCreation(query, user).bodyToMono(localVarReturnType); } + /** + * + * + *

        200 - Success + * @param query The query parameter + * @param user The user parameter + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testBodyWithQueryParamsWithHttpInfo(String query, User user) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testBodyWithQueryParamsRequestCreation(query, user).toEntity(localVarReturnType); } + + /** + * + * + *

        200 - Success + * @param query The query parameter + * @param user The user parameter + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testBodyWithQueryParamsWithResponseSpec(String query, User user) throws WebClientResponseException { + return testBodyWithQueryParamsRequestCreation(query, user); + } /** * To test \"client\" model * To test \"client\" model @@ -623,10 +823,30 @@ public class FakeApi { return testClientModelRequestCreation(client).bodyToMono(localVarReturnType); } + /** + * To test \"client\" model + * To test \"client\" model + *

        200 - successful operation + * @param client client model + * @return ResponseEntity<Client> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testClientModelWithHttpInfo(Client client) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testClientModelRequestCreation(client).toEntity(localVarReturnType); } + + /** + * To test \"client\" model + * To test \"client\" model + *

        200 - successful operation + * @param client client model + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testClientModelWithResponseSpec(Client client) throws WebClientResponseException { + return testClientModelRequestCreation(client); + } /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -742,10 +962,57 @@ public class FakeApi { return testEndpointParametersRequestCreation(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback).bodyToMono(localVarReturnType); } + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + *

        400 - Invalid username supplied + *

        404 - User not found + * @param number None + * @param _double None + * @param patternWithoutDelimiter None + * @param _byte None + * @param integer None + * @param int32 None + * @param int64 None + * @param _float None + * @param string None + * @param binary None + * @param date None + * @param dateTime None + * @param password None + * @param paramCallback None + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testEndpointParametersRequestCreation(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback).toEntity(localVarReturnType); } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + *

        400 - Invalid username supplied + *

        404 - User not found + * @param number None + * @param _double None + * @param patternWithoutDelimiter None + * @param _byte None + * @param integer None + * @param int32 None + * @param int64 None + * @param _float None + * @param string None + * @param binary None + * @param date None + * @param dateTime None + * @param password None + * @param paramCallback None + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testEndpointParametersWithResponseSpec(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws WebClientResponseException { + return testEndpointParametersRequestCreation(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } /** * To test enum parameters * To test enum parameters @@ -821,10 +1088,47 @@ public class FakeApi { return testEnumParametersRequestCreation(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString).bodyToMono(localVarReturnType); } + /** + * To test enum parameters + * To test enum parameters + *

        400 - Invalid request + *

        404 - Not found + * @param enumHeaderStringArray Header parameter enum test (string array) + * @param enumHeaderString Header parameter enum test (string) + * @param enumQueryStringArray Query parameter enum test (string array) + * @param enumQueryString Query parameter enum test (string) + * @param enumQueryInteger Query parameter enum test (double) + * @param enumQueryDouble Query parameter enum test (double) + * @param enumQueryModelArray The enumQueryModelArray parameter + * @param enumFormStringArray Form parameter enum test (string array) + * @param enumFormString Form parameter enum test (string) + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testEnumParametersWithHttpInfo(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumQueryModelArray, List enumFormStringArray, String enumFormString) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testEnumParametersRequestCreation(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString).toEntity(localVarReturnType); } + + /** + * To test enum parameters + * To test enum parameters + *

        400 - Invalid request + *

        404 - Not found + * @param enumHeaderStringArray Header parameter enum test (string array) + * @param enumHeaderString Header parameter enum test (string) + * @param enumQueryStringArray Query parameter enum test (string array) + * @param enumQueryString Query parameter enum test (string) + * @param enumQueryInteger Query parameter enum test (double) + * @param enumQueryDouble Query parameter enum test (double) + * @param enumQueryModelArray The enumQueryModelArray parameter + * @param enumFormStringArray Form parameter enum test (string array) + * @param enumFormString Form parameter enum test (string) + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testEnumParametersWithResponseSpec(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumQueryModelArray, List enumFormStringArray, String enumFormString) throws WebClientResponseException { + return testEnumParametersRequestCreation(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString); + } /** * Fake endpoint to test group parameters (optional) * Fake endpoint to test group parameters (optional) @@ -896,10 +1200,39 @@ public class FakeApi { return testGroupParametersRequestCreation(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group).bodyToMono(localVarReturnType); } + /** + * Fake endpoint to test group parameters (optional) + * Fake endpoint to test group parameters (optional) + *

        400 - Someting wrong + * @param requiredStringGroup Required String in group parameters + * @param requiredBooleanGroup Required Boolean in group parameters + * @param requiredInt64Group Required Integer in group parameters + * @param stringGroup String in group parameters + * @param booleanGroup Boolean in group parameters + * @param int64Group Integer in group parameters + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testGroupParametersWithHttpInfo(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testGroupParametersRequestCreation(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group).toEntity(localVarReturnType); } + + /** + * Fake endpoint to test group parameters (optional) + * Fake endpoint to test group parameters (optional) + *

        400 - Someting wrong + * @param requiredStringGroup Required String in group parameters + * @param requiredBooleanGroup Required Boolean in group parameters + * @param requiredInt64Group Required Integer in group parameters + * @param stringGroup String in group parameters + * @param booleanGroup Boolean in group parameters + * @param int64Group Integer in group parameters + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testGroupParametersWithResponseSpec(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws WebClientResponseException { + return testGroupParametersRequestCreation(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } /** * test inline additionalProperties * @@ -946,10 +1279,29 @@ public class FakeApi { return testInlineAdditionalPropertiesRequestCreation(requestBody).bodyToMono(localVarReturnType); } + /** + * test inline additionalProperties + * + *

        200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testInlineAdditionalPropertiesWithHttpInfo(Map requestBody) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testInlineAdditionalPropertiesRequestCreation(requestBody).toEntity(localVarReturnType); } + + /** + * test inline additionalProperties + * + *

        200 - successful operation + * @param requestBody request body + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testInlineAdditionalPropertiesWithResponseSpec(Map requestBody) throws WebClientResponseException { + return testInlineAdditionalPropertiesRequestCreation(requestBody); + } /** * test json serialization of form data * @@ -1007,10 +1359,31 @@ public class FakeApi { return testJsonFormDataRequestCreation(param, param2).bodyToMono(localVarReturnType); } + /** + * test json serialization of form data + * + *

        200 - successful operation + * @param param field1 + * @param param2 field2 + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testJsonFormDataWithHttpInfo(String param, String param2) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testJsonFormDataRequestCreation(param, param2).toEntity(localVarReturnType); } + + /** + * test json serialization of form data + * + *

        200 - successful operation + * @param param field1 + * @param param2 field2 + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testJsonFormDataWithResponseSpec(String param, String param2) throws WebClientResponseException { + return testJsonFormDataRequestCreation(param, param2); + } /** * * To test the collection format in query parameters @@ -1095,8 +1468,39 @@ public class FakeApi { return testQueryParameterCollectionFormatRequestCreation(pipe, ioutil, http, url, context, allowEmpty, language).bodyToMono(localVarReturnType); } + /** + * + * To test the collection format in query parameters + *

        200 - Success + * @param pipe The pipe parameter + * @param ioutil The ioutil parameter + * @param http The http parameter + * @param url The url parameter + * @param context The context parameter + * @param allowEmpty The allowEmpty parameter + * @param language The language parameter + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context, String allowEmpty, Map language) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testQueryParameterCollectionFormatRequestCreation(pipe, ioutil, http, url, context, allowEmpty, language).toEntity(localVarReturnType); } + + /** + * + * To test the collection format in query parameters + *

        200 - Success + * @param pipe The pipe parameter + * @param ioutil The ioutil parameter + * @param http The http parameter + * @param url The url parameter + * @param context The context parameter + * @param allowEmpty The allowEmpty parameter + * @param language The language parameter + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testQueryParameterCollectionFormatWithResponseSpec(List pipe, List ioutil, List http, List url, List context, String allowEmpty, Map language) throws WebClientResponseException { + return testQueryParameterCollectionFormatRequestCreation(pipe, ioutil, http, url, context, allowEmpty, language); + } } diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 0ce3faa72f..106994a464 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -96,8 +96,28 @@ public class FakeClassnameTags123Api { return testClassnameRequestCreation(client).bodyToMono(localVarReturnType); } + /** + * To test class name in snake case + * To test class name in snake case + *

        200 - successful operation + * @param client client model + * @return ResponseEntity<Client> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> testClassnameWithHttpInfo(Client client) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return testClassnameRequestCreation(client).toEntity(localVarReturnType); } + + /** + * To test class name in snake case + * To test class name in snake case + *

        200 - successful operation + * @param client client model + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testClassnameWithResponseSpec(Client client) throws WebClientResponseException { + return testClassnameRequestCreation(client); + } } diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/PetApi.java index 2d690b40b8..c5588dff97 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/PetApi.java @@ -97,10 +97,31 @@ public class PetApi { return addPetRequestCreation(pet).bodyToMono(localVarReturnType); } + /** + * Add a new pet to the store + * + *

        200 - Successful operation + *

        405 - Invalid input + * @param pet Pet object that needs to be added to the store + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> addPetWithHttpInfo(Pet pet) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return addPetRequestCreation(pet).toEntity(localVarReturnType); } + + /** + * Add a new pet to the store + * + *

        200 - Successful operation + *

        405 - Invalid input + * @param pet Pet object that needs to be added to the store + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec addPetWithResponseSpec(Pet pet) throws WebClientResponseException { + return addPetRequestCreation(pet); + } /** * Deletes a pet * @@ -153,10 +174,33 @@ public class PetApi { return deletePetRequestCreation(petId, apiKey).bodyToMono(localVarReturnType); } + /** + * Deletes a pet + * + *

        200 - Successful operation + *

        400 - Invalid pet value + * @param petId Pet id to delete + * @param apiKey The apiKey parameter + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> deletePetWithHttpInfo(Long petId, String apiKey) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return deletePetRequestCreation(petId, apiKey).toEntity(localVarReturnType); } + + /** + * Deletes a pet + * + *

        200 - Successful operation + *

        400 - Invalid pet value + * @param petId Pet id to delete + * @param apiKey The apiKey parameter + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deletePetWithResponseSpec(Long petId, String apiKey) throws WebClientResponseException { + return deletePetRequestCreation(petId, apiKey); + } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings @@ -209,10 +253,32 @@ public class PetApi { return findPetsByStatusRequestCreation(status).bodyToFlux(localVarReturnType).collectList().block(); } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

        200 - successful operation + *

        400 - Invalid status value + * @param status Status values that need to be considered for filter + * @return ResponseEntity<List<Pet>> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public ResponseEntity> findPetsByStatusWithHttpInfo(List status) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return findPetsByStatusRequestCreation(status).toEntityList(localVarReturnType).block(); } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

        200 - successful operation + *

        400 - Invalid status value + * @param status Status values that need to be considered for filter + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec findPetsByStatusWithResponseSpec(List status) throws WebClientResponseException { + return findPetsByStatusRequestCreation(status); + } /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -267,10 +333,32 @@ public class PetApi { return findPetsByTagsRequestCreation(tags).bodyToFlux(localVarReturnType).collect(Collectors.toSet()).block(); } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

        200 - successful operation + *

        400 - Invalid tag value + * @param tags Tags to filter by + * @return ResponseEntity<Set<Pet>> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public ResponseEntity> findPetsByTagsWithHttpInfo(Set tags) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return findPetsByTagsRequestCreation(tags).toEntityList(localVarReturnType).block(); } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

        200 - successful operation + *

        400 - Invalid tag value + * @param tags Tags to filter by + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec findPetsByTagsWithResponseSpec(Set tags) throws WebClientResponseException { + return findPetsByTagsRequestCreation(tags); + } /** * Find pet by ID * Returns a single pet @@ -325,10 +413,34 @@ public class PetApi { return getPetByIdRequestCreation(petId).bodyToMono(localVarReturnType).block(); } + /** + * Find pet by ID + * Returns a single pet + *

        200 - successful operation + *

        400 - Invalid ID supplied + *

        404 - Pet not found + * @param petId ID of pet to return + * @return ResponseEntity<Pet> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public ResponseEntity getPetByIdWithHttpInfo(Long petId) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return getPetByIdRequestCreation(petId).toEntity(localVarReturnType).block(); } + + /** + * Find pet by ID + * Returns a single pet + *

        200 - successful operation + *

        400 - Invalid ID supplied + *

        404 - Pet not found + * @param petId ID of pet to return + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getPetByIdWithResponseSpec(Long petId) throws WebClientResponseException { + return getPetByIdRequestCreation(petId); + } /** * Update an existing pet * @@ -381,10 +493,35 @@ public class PetApi { updatePetRequestCreation(pet).bodyToMono(localVarReturnType).block(); } + /** + * Update an existing pet + * + *

        200 - Successful operation + *

        400 - Invalid ID supplied + *

        404 - Pet not found + *

        405 - Validation exception + * @param pet Pet object that needs to be added to the store + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public ResponseEntity updatePetWithHttpInfo(Pet pet) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return updatePetRequestCreation(pet).toEntity(localVarReturnType).block(); } + + /** + * Update an existing pet + * + *

        200 - Successful operation + *

        400 - Invalid ID supplied + *

        404 - Pet not found + *

        405 - Validation exception + * @param pet Pet object that needs to be added to the store + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updatePetWithResponseSpec(Pet pet) throws WebClientResponseException { + return updatePetRequestCreation(pet); + } /** * Updates a pet in the store with form data * @@ -444,10 +581,35 @@ public class PetApi { return updatePetWithFormRequestCreation(petId, name, status).bodyToMono(localVarReturnType); } + /** + * Updates a pet in the store with form data + * + *

        200 - Successful operation + *

        405 - Invalid input + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return updatePetWithFormRequestCreation(petId, name, status).toEntity(localVarReturnType); } + + /** + * Updates a pet in the store with form data + * + *

        200 - Successful operation + *

        405 - Invalid input + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updatePetWithFormWithResponseSpec(Long petId, String name, String status) throws WebClientResponseException { + return updatePetWithFormRequestCreation(petId, name, status); + } /** * uploads an image * @@ -509,10 +671,34 @@ public class PetApi { return uploadFileRequestCreation(petId, additionalMetadata, _file).bodyToMono(localVarReturnType); } + /** + * uploads an image + * + *

        200 - successful operation + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param _file file to upload + * @return ResponseEntity<ModelApiResponse> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File _file) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return uploadFileRequestCreation(petId, additionalMetadata, _file).toEntity(localVarReturnType); } + + /** + * uploads an image + * + *

        200 - successful operation + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param _file file to upload + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec uploadFileWithResponseSpec(Long petId, String additionalMetadata, File _file) throws WebClientResponseException { + return uploadFileRequestCreation(petId, additionalMetadata, _file); + } /** * uploads an image (required) * @@ -578,8 +764,32 @@ public class PetApi { return uploadFileWithRequiredFileRequestCreation(petId, requiredFile, additionalMetadata).bodyToMono(localVarReturnType); } + /** + * uploads an image (required) + * + *

        200 - successful operation + * @param petId ID of pet to update + * @param requiredFile file to upload + * @param additionalMetadata Additional data to pass to server + * @return ResponseEntity<ModelApiResponse> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> uploadFileWithRequiredFileWithHttpInfo(Long petId, File requiredFile, String additionalMetadata) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return uploadFileWithRequiredFileRequestCreation(petId, requiredFile, additionalMetadata).toEntity(localVarReturnType); } + + /** + * uploads an image (required) + * + *

        200 - successful operation + * @param petId ID of pet to update + * @param requiredFile file to upload + * @param additionalMetadata Additional data to pass to server + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec uploadFileWithRequiredFileWithResponseSpec(Long petId, File requiredFile, String additionalMetadata) throws WebClientResponseException { + return uploadFileWithRequiredFileRequestCreation(petId, requiredFile, additionalMetadata); + } } diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/StoreApi.java index 96a429311f..2742695935 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/StoreApi.java @@ -94,10 +94,31 @@ public class StoreApi { return deleteOrderRequestCreation(orderId).bodyToMono(localVarReturnType); } + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + *

        400 - Invalid ID supplied + *

        404 - Order not found + * @param orderId ID of the order that needs to be deleted + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> deleteOrderWithHttpInfo(String orderId) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return deleteOrderRequestCreation(orderId).toEntity(localVarReturnType); } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + *

        400 - Invalid ID supplied + *

        404 - Order not found + * @param orderId ID of the order that needs to be deleted + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteOrderWithResponseSpec(String orderId) throws WebClientResponseException { + return deleteOrderRequestCreation(orderId); + } /** * Returns pet inventories by status * Returns a map of status codes to quantities @@ -140,10 +161,28 @@ public class StoreApi { return getInventoryRequestCreation().bodyToMono(localVarReturnType); } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

        200 - successful operation + * @return ResponseEntity<Map<String, Integer>> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono>> getInventoryWithHttpInfo() throws WebClientResponseException { ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference>() {}; return getInventoryRequestCreation().toEntity(localVarReturnType); } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

        200 - successful operation + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getInventoryWithResponseSpec() throws WebClientResponseException { + return getInventoryRequestCreation(); + } /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -198,10 +237,34 @@ public class StoreApi { return getOrderByIdRequestCreation(orderId).bodyToMono(localVarReturnType); } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + *

        200 - successful operation + *

        400 - Invalid ID supplied + *

        404 - Order not found + * @param orderId ID of pet that needs to be fetched + * @return ResponseEntity<Order> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> getOrderByIdWithHttpInfo(Long orderId) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return getOrderByIdRequestCreation(orderId).toEntity(localVarReturnType); } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + *

        200 - successful operation + *

        400 - Invalid ID supplied + *

        404 - Order not found + * @param orderId ID of pet that needs to be fetched + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getOrderByIdWithResponseSpec(Long orderId) throws WebClientResponseException { + return getOrderByIdRequestCreation(orderId); + } /** * Place an order for a pet * @@ -254,8 +317,30 @@ public class StoreApi { return placeOrderRequestCreation(order).bodyToMono(localVarReturnType); } + /** + * Place an order for a pet + * + *

        200 - successful operation + *

        400 - Invalid Order + * @param order order placed for purchasing the pet + * @return ResponseEntity<Order> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> placeOrderWithHttpInfo(Order order) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return placeOrderRequestCreation(order).toEntity(localVarReturnType); } + + /** + * Place an order for a pet + * + *

        200 - successful operation + *

        400 - Invalid Order + * @param order order placed for purchasing the pet + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec placeOrderWithResponseSpec(Order order) throws WebClientResponseException { + return placeOrderRequestCreation(order); + } } diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/UserApi.java index 70fd7a644c..ad76ef2ea7 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/UserApi.java @@ -93,10 +93,29 @@ public class UserApi { return createUserRequestCreation(user).bodyToMono(localVarReturnType); } + /** + * Create user + * This can only be done by the logged in user. + *

        0 - successful operation + * @param user Created user object + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> createUserWithHttpInfo(User user) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return createUserRequestCreation(user).toEntity(localVarReturnType); } + + /** + * Create user + * This can only be done by the logged in user. + *

        0 - successful operation + * @param user Created user object + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createUserWithResponseSpec(User user) throws WebClientResponseException { + return createUserRequestCreation(user); + } /** * Creates list of users with given input array * @@ -143,10 +162,29 @@ public class UserApi { return createUsersWithArrayInputRequestCreation(user).bodyToMono(localVarReturnType); } + /** + * Creates list of users with given input array + * + *

        0 - successful operation + * @param user List of user object + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> createUsersWithArrayInputWithHttpInfo(List user) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return createUsersWithArrayInputRequestCreation(user).toEntity(localVarReturnType); } + + /** + * Creates list of users with given input array + * + *

        0 - successful operation + * @param user List of user object + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createUsersWithArrayInputWithResponseSpec(List user) throws WebClientResponseException { + return createUsersWithArrayInputRequestCreation(user); + } /** * Creates list of users with given input array * @@ -193,10 +231,29 @@ public class UserApi { return createUsersWithListInputRequestCreation(user).bodyToMono(localVarReturnType); } + /** + * Creates list of users with given input array + * + *

        0 - successful operation + * @param user List of user object + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> createUsersWithListInputWithHttpInfo(List user) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return createUsersWithListInputRequestCreation(user).toEntity(localVarReturnType); } + + /** + * Creates list of users with given input array + * + *

        0 - successful operation + * @param user List of user object + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createUsersWithListInputWithResponseSpec(List user) throws WebClientResponseException { + return createUsersWithListInputRequestCreation(user); + } /** * Delete user * This can only be done by the logged in user. @@ -245,10 +302,31 @@ public class UserApi { return deleteUserRequestCreation(username).bodyToMono(localVarReturnType); } + /** + * Delete user + * This can only be done by the logged in user. + *

        400 - Invalid username supplied + *

        404 - User not found + * @param username The name that needs to be deleted + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> deleteUserWithHttpInfo(String username) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return deleteUserRequestCreation(username).toEntity(localVarReturnType); } + + /** + * Delete user + * This can only be done by the logged in user. + *

        400 - Invalid username supplied + *

        404 - User not found + * @param username The name that needs to be deleted + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteUserWithResponseSpec(String username) throws WebClientResponseException { + return deleteUserRequestCreation(username); + } /** * Get user by user name * @@ -303,10 +381,34 @@ public class UserApi { return getUserByNameRequestCreation(username).bodyToMono(localVarReturnType); } + /** + * Get user by user name + * + *

        200 - successful operation + *

        400 - Invalid username supplied + *

        404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. + * @return ResponseEntity<User> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> getUserByNameWithHttpInfo(String username) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return getUserByNameRequestCreation(username).toEntity(localVarReturnType); } + + /** + * Get user by user name + * + *

        200 - successful operation + *

        400 - Invalid username supplied + *

        404 - User not found + * @param username The name that needs to be fetched. Use user1 for testing. + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getUserByNameWithResponseSpec(String username) throws WebClientResponseException { + return getUserByNameRequestCreation(username); + } /** * Logs user into the system * @@ -366,10 +468,34 @@ public class UserApi { return loginUserRequestCreation(username, password).bodyToMono(localVarReturnType); } + /** + * Logs user into the system + * + *

        200 - successful operation + *

        400 - Invalid username/password supplied + * @param username The user name for login + * @param password The password for login in clear text + * @return ResponseEntity<String> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> loginUserWithHttpInfo(String username, String password) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return loginUserRequestCreation(username, password).toEntity(localVarReturnType); } + + /** + * Logs user into the system + * + *

        200 - successful operation + *

        400 - Invalid username/password supplied + * @param username The user name for login + * @param password The password for login in clear text + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec loginUserWithResponseSpec(String username, String password) throws WebClientResponseException { + return loginUserRequestCreation(username, password); + } /** * Logs out current logged in user session * @@ -408,10 +534,27 @@ public class UserApi { return logoutUserRequestCreation().bodyToMono(localVarReturnType); } + /** + * Logs out current logged in user session + * + *

        0 - successful operation + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> logoutUserWithHttpInfo() throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return logoutUserRequestCreation().toEntity(localVarReturnType); } + + /** + * Logs out current logged in user session + * + *

        0 - successful operation + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec logoutUserWithResponseSpec() throws WebClientResponseException { + return logoutUserRequestCreation(); + } /** * Updated user * This can only be done by the logged in user. @@ -468,8 +611,31 @@ public class UserApi { return updateUserRequestCreation(username, user).bodyToMono(localVarReturnType); } + /** + * Updated user + * This can only be done by the logged in user. + *

        400 - Invalid user supplied + *

        404 - User not found + * @param username name that need to be deleted + * @param user Updated user object + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ public Mono> updateUserWithHttpInfo(String username, User user) throws WebClientResponseException { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return updateUserRequestCreation(username, user).toEntity(localVarReturnType); } + + /** + * Updated user + * This can only be done by the logged in user. + *

        400 - Invalid user supplied + *

        404 - User not found + * @param username name that need to be deleted + * @param user Updated user object + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateUserWithResponseSpec(String username, User user) throws WebClientResponseException { + return updateUserRequestCreation(username, user); + } } diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index dc1cf1c448..ef8a8cf101 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -42,7 +42,7 @@ public class AdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP_OF_MAP_PROPERTY = "map_of_map_property"; private Map> mapOfMapProperty = null; - public AdditionalPropertiesClass() { + public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java index 6bde2cae30..485e451773 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/AllOfWithSingleRef.java @@ -23,10 +23,6 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.openapitools.client.model.SingleRefType; -import org.openapitools.jackson.nullable.JsonNullable; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; @@ -43,9 +39,9 @@ public class AllOfWithSingleRef { private String username; public static final String JSON_PROPERTY_SINGLE_REF_TYPE = "SingleRefType"; - private JsonNullable singleRefType = JsonNullable.undefined(); + private SingleRefType singleRefType; - public AllOfWithSingleRef() { + public AllOfWithSingleRef() { } public AllOfWithSingleRef username(String username) { @@ -76,8 +72,8 @@ public class AllOfWithSingleRef { public AllOfWithSingleRef singleRefType(SingleRefType singleRefType) { - this.singleRefType = JsonNullable.of(singleRefType); + this.singleRefType = singleRefType; return this; } @@ -87,26 +83,18 @@ public class AllOfWithSingleRef { **/ @javax.annotation.Nullable @ApiModelProperty(value = "") - @JsonIgnore - - public SingleRefType getSingleRefType() { - return singleRefType.orElse(null); - } - @JsonProperty(JSON_PROPERTY_SINGLE_REF_TYPE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public JsonNullable getSingleRefType_JsonNullable() { + public SingleRefType getSingleRefType() { return singleRefType; } - - @JsonProperty(JSON_PROPERTY_SINGLE_REF_TYPE) - public void setSingleRefType_JsonNullable(JsonNullable singleRefType) { - this.singleRefType = singleRefType; - } + + @JsonProperty(JSON_PROPERTY_SINGLE_REF_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setSingleRefType(SingleRefType singleRefType) { - this.singleRefType = JsonNullable.of(singleRefType); + this.singleRefType = singleRefType; } @@ -120,23 +108,12 @@ public class AllOfWithSingleRef { } AllOfWithSingleRef allOfWithSingleRef = (AllOfWithSingleRef) o; return Objects.equals(this.username, allOfWithSingleRef.username) && - equalsNullable(this.singleRefType, allOfWithSingleRef.singleRefType); - } - - private static boolean equalsNullable(JsonNullable a, JsonNullable b) { - return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + Objects.equals(this.singleRefType, allOfWithSingleRef.singleRefType); } @Override public int hashCode() { - return Objects.hash(username, hashCodeNullable(singleRefType)); - } - - private static int hashCodeNullable(JsonNullable a) { - if (a == null) { - return 1; - } - return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + return Objects.hash(username, singleRefType); } @Override diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Animal.java index 6f1a5d6fd8..2a6e07f644 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Animal.java @@ -55,7 +55,7 @@ public class Animal { public static final String JSON_PROPERTY_COLOR = "color"; private String color = "red"; - public Animal() { + public Animal() { } public Animal className(String className) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 395b4c4d40..84ecf3c60c 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; private List> arrayArrayNumber = null; - public ArrayOfArrayOfNumberOnly() { + public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 81437ecc35..5a740ed59d 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -39,7 +39,7 @@ public class ArrayOfNumberOnly { public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; private List arrayNumber = null; - public ArrayOfNumberOnly() { + public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayTest.java index 29e8fde2a2..f649ccdafc 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; private List> arrayArrayOfModel = null; - public ArrayTest() { + public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Capitalization.java index 09da87c767..75dab11565 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Capitalization.java @@ -56,7 +56,7 @@ public class Capitalization { public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; private String ATT_NAME; - public Capitalization() { + public Capitalization() { } public Capitalization smallCamel(String smallCamel) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Cat.java index 4aa78333fa..063387e542 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Cat.java @@ -46,7 +46,8 @@ public class Cat extends Animal { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public Cat() { + public Cat() { + } public Cat declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/CatAllOf.java index 9af537be46..6a40fe1cc2 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/CatAllOf.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -37,7 +37,7 @@ public class CatAllOf { public static final String JSON_PROPERTY_DECLAWED = "declawed"; private Boolean declawed; - public CatAllOf() { + public CatAllOf() { } public CatAllOf declawed(Boolean declawed) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Category.java index 9ecb9793f8..95ba07594c 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Category.java @@ -40,7 +40,7 @@ public class Category { public static final String JSON_PROPERTY_NAME = "name"; private String name = "default-name"; - public Category() { + public Category() { } public Category id(Long id) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ClassModel.java index 02a70314cf..c112b0dbfd 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ClassModel.java @@ -37,7 +37,7 @@ public class ClassModel { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; - public ClassModel() { + public ClassModel() { } public ClassModel propertyClass(String propertyClass) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Client.java index c0e1209608..ee1f6eb2b4 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Client.java @@ -36,7 +36,7 @@ public class Client { public static final String JSON_PROPERTY_CLIENT = "client"; private String client; - public Client() { + public Client() { } public Client client(String client) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/DeprecatedObject.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/DeprecatedObject.java index 43b0f5f764..c35b4fc5e8 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/DeprecatedObject.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/DeprecatedObject.java @@ -38,7 +38,7 @@ public class DeprecatedObject { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public DeprecatedObject() { + public DeprecatedObject() { } public DeprecatedObject name(String name) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Dog.java index bf9838d6f6..193f040fc5 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Dog.java @@ -46,7 +46,8 @@ public class Dog extends Animal { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public Dog() { + public Dog() { + } public Dog breed(String breed) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/DogAllOf.java index 22f41e01ea..d37bc6d62a 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/DogAllOf.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -37,7 +37,7 @@ public class DogAllOf { public static final String JSON_PROPERTY_BREED = "breed"; private String breed; - public DogAllOf() { + public DogAllOf() { } public DogAllOf breed(String breed) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumArrays.java index f5b42b0b87..216f767fef 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -112,7 +112,7 @@ public class EnumArrays { public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; private List arrayEnum = null; - public EnumArrays() { + public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumTest.java index a33250dbb6..17a7411cca 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumTest.java @@ -217,7 +217,7 @@ public class EnumTest { public static final String JSON_PROPERTY_OUTER_ENUM_INTEGER_DEFAULT_VALUE = "outerEnumIntegerDefaultValue"; private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; - public EnumTest() { + public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 43c10d8609..ae5247c54e 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; private List files = null; - public FileSchemaTestClass() { + public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Foo.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Foo.java index fe477338c4..3029990782 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Foo.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Foo.java @@ -36,7 +36,7 @@ public class Foo { public static final String JSON_PROPERTY_BAR = "bar"; private String bar = "bar"; - public Foo() { + public Foo() { } public Foo bar(String bar) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java index 0c2f4bdc6c..d01668ba67 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java @@ -38,7 +38,7 @@ public class FooGetDefaultResponse { public static final String JSON_PROPERTY_STRING = "string"; private Foo string; - public FooGetDefaultResponse() { + public FooGetDefaultResponse() { } public FooGetDefaultResponse string(Foo string) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FormatTest.java index f1ef660aa6..38b3edf010 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FormatTest.java @@ -102,7 +102,7 @@ public class FormatTest { public static final String JSON_PROPERTY_PATTERN_WITH_DIGITS_AND_DELIMITER = "pattern_with_digits_and_delimiter"; private String patternWithDigitsAndDelimiter; - public FormatTest() { + public FormatTest() { } public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index a79abdb993..45c377620b 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -41,7 +41,7 @@ public class HasOnlyReadOnly { public static final String JSON_PROPERTY_FOO = "foo"; private String foo; - public HasOnlyReadOnly() { + public HasOnlyReadOnly() { } @JsonCreator diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HealthCheckResult.java index 19f2227d84..e6889f1a89 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HealthCheckResult.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -41,7 +41,7 @@ public class HealthCheckResult { public static final String JSON_PROPERTY_NULLABLE_MESSAGE = "NullableMessage"; private JsonNullable nullableMessage = JsonNullable.undefined(); - public HealthCheckResult() { + public HealthCheckResult() { } public HealthCheckResult nullableMessage(String nullableMessage) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/MapTest.java index d50e30db74..3ee0b0ac01 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/MapTest.java @@ -85,7 +85,7 @@ public class MapTest { public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; private Map indirectMap = null; - public MapTest() { + public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 999c32ef2b..9f7331d1d2 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -49,7 +49,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public static final String JSON_PROPERTY_MAP = "map"; private Map map = null; - public MixedPropertiesAndAdditionalPropertiesClass() { + public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Model200Response.java index a05c698660..18596e30dc 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Model200Response.java @@ -42,7 +42,7 @@ public class Model200Response { public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; private String propertyClass; - public Model200Response() { + public Model200Response() { } public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 8c90d06494..9ab4b19971 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -45,7 +45,7 @@ public class ModelApiResponse { public static final String JSON_PROPERTY_MESSAGE = "message"; private String message; - public ModelApiResponse() { + public ModelApiResponse() { } public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelFile.java index 8647283641..cc921fbcb0 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelFile.java @@ -38,7 +38,7 @@ public class ModelFile { public static final String JSON_PROPERTY_SOURCE_U_R_I = "sourceURI"; private String sourceURI; - public ModelFile() { + public ModelFile() { } public ModelFile sourceURI(String sourceURI) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelList.java index 82abfba9e3..4dd418a4f5 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelList.java @@ -37,7 +37,7 @@ public class ModelList { public static final String JSON_PROPERTY_123LIST = "123-list"; private String _123list; - public ModelList() { + public ModelList() { } public ModelList _123list(String _123list) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelReturn.java index 06fc43f8eb..35a0b1966d 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -38,7 +38,7 @@ public class ModelReturn { public static final String JSON_PROPERTY_RETURN = "return"; private Integer _return; - public ModelReturn() { + public ModelReturn() { } public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Name.java index b263b708fe..56bae65fa6 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Name.java @@ -49,7 +49,7 @@ public class Name { public static final String JSON_PROPERTY_123NUMBER = "123Number"; private Integer _123number; - public Name() { + public Name() { } @JsonCreator diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NullableClass.java index efc2e37167..010a575983 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NullableClass.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NullableClass.java @@ -91,7 +91,8 @@ public class NullableClass extends HashMap { public static final String JSON_PROPERTY_OBJECT_ITEMS_NULLABLE = "object_items_nullable"; private Map objectItemsNullable = null; - public NullableClass() { + public NullableClass() { + } public NullableClass integerProp(Integer integerProp) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NumberOnly.java index 4a268ea06e..fd7c5ed5d1 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -37,7 +37,7 @@ public class NumberOnly { public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; private BigDecimal justNumber; - public NumberOnly() { + public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java index 3831a4d330..fc4da32d31 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -52,7 +52,7 @@ public class ObjectWithDeprecatedFields { public static final String JSON_PROPERTY_BARS = "bars"; private List bars = null; - public ObjectWithDeprecatedFields() { + public ObjectWithDeprecatedFields() { } public ObjectWithDeprecatedFields uuid(String uuid) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Order.java index 4fccc19338..2f838cffbf 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Order.java @@ -94,7 +94,7 @@ public class Order { public static final String JSON_PROPERTY_COMPLETE = "complete"; private Boolean complete = false; - public Order() { + public Order() { } public Order id(Long id) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/OuterComposite.java index 710f350303..324da496f6 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -45,7 +45,7 @@ public class OuterComposite { public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; private Boolean myBoolean; - public OuterComposite() { + public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java index 1669551078..fd303579d7 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/OuterObjectWithEnumProperty.java @@ -37,7 +37,7 @@ public class OuterObjectWithEnumProperty { public static final String JSON_PROPERTY_VALUE = "value"; private OuterEnumInteger value; - public OuterObjectWithEnumProperty() { + public OuterObjectWithEnumProperty() { } public OuterObjectWithEnumProperty value(OuterEnumInteger value) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Pet.java index 27121c6969..908d26373e 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Pet.java @@ -100,7 +100,7 @@ public class Pet { public static final String JSON_PROPERTY_STATUS = "status"; private StatusEnum status; - public Pet() { + public Pet() { } public Pet id(Long id) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index 1130124051..6860d65e9c 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -40,7 +40,7 @@ public class ReadOnlyFirst { public static final String JSON_PROPERTY_BAZ = "baz"; private String baz; - public ReadOnlyFirst() { + public ReadOnlyFirst() { } @JsonCreator diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/SpecialModelName.java index 95d47212ac..7f2a25923c 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -37,7 +37,7 @@ public class SpecialModelName { public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; private Long $specialPropertyName; - public SpecialModelName() { + public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Tag.java index 25e766c40e..2a68d0029a 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/Tag.java @@ -40,7 +40,7 @@ public class Tag { public static final String JSON_PROPERTY_NAME = "name"; private String name; - public Tag() { + public Tag() { } public Tag id(Long id) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/User.java index a289c89f5e..fe0c60b880 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/User.java @@ -64,7 +64,7 @@ public class User { public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; private Integer userStatus; - public User() { + public User() { } public User id(Long id) { diff --git a/samples/client/petstore/javascript-apollo/.babelrc b/samples/client/petstore/javascript-apollo/.babelrc new file mode 100644 index 0000000000..c73df9d50b --- /dev/null +++ b/samples/client/petstore/javascript-apollo/.babelrc @@ -0,0 +1,33 @@ +{ + "presets": [ + "@babel/preset-env" + ], + "plugins": [ + "@babel/plugin-syntax-dynamic-import", + "@babel/plugin-syntax-import-meta", + "@babel/plugin-proposal-class-properties", + "@babel/plugin-proposal-json-strings", + [ + "@babel/plugin-proposal-decorators", + { + "legacy": true + } + ], + "@babel/plugin-proposal-function-sent", + "@babel/plugin-proposal-export-namespace-from", + "@babel/plugin-proposal-numeric-separator", + "@babel/plugin-proposal-throw-expressions", + "@babel/plugin-proposal-export-default-from", + "@babel/plugin-proposal-logical-assignment-operators", + "@babel/plugin-proposal-optional-chaining", + [ + "@babel/plugin-proposal-pipeline-operator", + { + "proposal": "minimal" + } + ], + "@babel/plugin-proposal-nullish-coalescing-operator", + "@babel/plugin-proposal-do-expressions", + "@babel/plugin-proposal-function-bind" + ] +} diff --git a/samples/client/petstore/javascript-apollo/.gitignore b/samples/client/petstore/javascript-apollo/.gitignore new file mode 100644 index 0000000000..6a7d6d8ef6 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/.gitignore @@ -0,0 +1,130 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp +.cache + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* \ No newline at end of file diff --git a/samples/client/petstore/javascript-apollo/.openapi-generator/FILES b/samples/client/petstore/javascript-apollo/.openapi-generator/FILES index 0f0a74bb1a..f83260318a 100644 --- a/samples/client/petstore/javascript-apollo/.openapi-generator/FILES +++ b/samples/client/petstore/javascript-apollo/.openapi-generator/FILES @@ -1,10 +1,62 @@ +.babelrc +.gitignore .travis.yml README.md +docs/AdditionalPropertiesClass.md +docs/Animal.md +docs/AnotherFakeApi.md docs/ApiResponse.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/BasquePig.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/Color.md +docs/DanishPig.md +docs/DefaultApi.md +docs/DeprecatedObject.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/File.md +docs/FileSchemaTestClass.md +docs/Foo.md +docs/FooGetDefaultResponse.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/HealthCheckResult.md +docs/List.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/Name.md +docs/NestedColor.md +docs/NestedOneOf.md +docs/NullableClass.md +docs/NumberOnly.md +docs/ObjectWithDeprecatedFields.md docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/OuterEnumDefaultValue.md +docs/OuterEnumInteger.md +docs/OuterEnumIntegerDefaultValue.md +docs/OuterObjectWithEnumProperty.md docs/Pet.md docs/PetApi.md +docs/Pig.md +docs/ReadOnlyFirst.md +docs/Return.md +docs/SpecialModelName.md docs/StoreApi.md docs/Tag.md docs/User.md @@ -13,13 +65,63 @@ git_push.sh mocha.opts package.json src/ApiClient.js +src/api/AnotherFakeApi.js +src/api/DefaultApi.js +src/api/FakeApi.js +src/api/FakeClassnameTags123Api.js src/api/PetApi.js src/api/StoreApi.js src/api/UserApi.js src/index.js +src/model/AdditionalPropertiesClass.js +src/model/Animal.js src/model/ApiResponse.js +src/model/ArrayOfArrayOfNumberOnly.js +src/model/ArrayOfNumberOnly.js +src/model/ArrayTest.js +src/model/BasquePig.js +src/model/Capitalization.js +src/model/Cat.js +src/model/CatAllOf.js src/model/Category.js +src/model/ClassModel.js +src/model/Client.js +src/model/Color.js +src/model/DanishPig.js +src/model/DeprecatedObject.js +src/model/Dog.js +src/model/DogAllOf.js +src/model/EnumArrays.js +src/model/EnumClass.js +src/model/EnumTest.js +src/model/File.js +src/model/FileSchemaTestClass.js +src/model/Foo.js +src/model/FooGetDefaultResponse.js +src/model/FormatTest.js +src/model/HasOnlyReadOnly.js +src/model/HealthCheckResult.js +src/model/List.js +src/model/MapTest.js +src/model/MixedPropertiesAndAdditionalPropertiesClass.js +src/model/Model200Response.js +src/model/Name.js +src/model/NestedColor.js +src/model/NestedOneOf.js +src/model/NullableClass.js +src/model/NumberOnly.js +src/model/ObjectWithDeprecatedFields.js src/model/Order.js +src/model/OuterComposite.js +src/model/OuterEnum.js +src/model/OuterEnumDefaultValue.js +src/model/OuterEnumInteger.js +src/model/OuterEnumIntegerDefaultValue.js +src/model/OuterObjectWithEnumProperty.js src/model/Pet.js +src/model/Pig.js +src/model/ReadOnlyFirst.js +src/model/Return.js +src/model/SpecialModelName.js src/model/Tag.js src/model/User.js diff --git a/samples/client/petstore/javascript-apollo/.openapi-generator/VERSION b/samples/client/petstore/javascript-apollo/.openapi-generator/VERSION index d99e7162d0..757e674004 100644 --- a/samples/client/petstore/javascript-apollo/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-apollo/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/javascript-apollo/README.md b/samples/client/petstore/javascript-apollo/README.md index 8b83e9a945..a6a90be126 100644 --- a/samples/client/petstore/javascript-apollo/README.md +++ b/samples/client/petstore/javascript-apollo/README.md @@ -1,12 +1,12 @@ # open_api_petstore OpenApiPetstore - JavaScript client for open_api_petstore -This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - API version: 1.0.0 - Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.JavascriptApolloClientCodegen +- Build package: org.openapitools.codegen.languages.JavascriptClientCodegen ## Installation @@ -100,30 +100,46 @@ Please follow the [installation](#installation) instruction and execute the foll ```javascript var OpenApiPetstore = require('open_api_petstore'); -var defaultClient = OpenApiPetstore.ApiClient.instance; -// Configure OAuth2 access token for authorization: petstore_auth -var petstore_auth = defaultClient.authentications['petstore_auth']; -petstore_auth.accessToken = "YOUR ACCESS TOKEN" -var api = new OpenApiPetstore.PetApi() -var body = new OpenApiPetstore.Pet(); // {Pet} Pet object that needs to be added to the store +var api = new OpenApiPetstore.AnotherFakeApi() +var client = new OpenApiPetstore.Client(); // {Client} client model var callback = function(error, data, response) { if (error) { console.error(error); } else { - console.log('API called successfully.'); + console.log('API called successfully. Returned data: ' + data); } }; -api.addPet(body, callback); +api.call123testSpecialTags(client, callback); ``` ## Documentation for API Endpoints -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*OpenApiPetstore.AnotherFakeApi* | [**call123testSpecialTags**](docs/AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags +*OpenApiPetstore.DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooGet) | **GET** /foo | +*OpenApiPetstore.FakeApi* | [**fakeHealthGet**](docs/FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint +*OpenApiPetstore.FakeApi* | [**fakeHttpSignatureTest**](docs/FakeApi.md#fakeHttpSignatureTest) | **GET** /fake/http-signature-test | test http signature authentication +*OpenApiPetstore.FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | +*OpenApiPetstore.FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | +*OpenApiPetstore.FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | +*OpenApiPetstore.FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | +*OpenApiPetstore.FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*OpenApiPetstore.FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | +*OpenApiPetstore.FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | +*OpenApiPetstore.FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | +*OpenApiPetstore.FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model +*OpenApiPetstore.FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*OpenApiPetstore.FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*OpenApiPetstore.FakeApi* | [**testGroupParameters**](docs/FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*OpenApiPetstore.FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*OpenApiPetstore.FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data +*OpenApiPetstore.FakeApi* | [**testQueryParameterCollectionFormat**](docs/FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | +*OpenApiPetstore.FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case *OpenApiPetstore.PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store *OpenApiPetstore.PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet *OpenApiPetstore.PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -132,9 +148,10 @@ Class | Method | HTTP request | Description *OpenApiPetstore.PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet *OpenApiPetstore.PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data *OpenApiPetstore.PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image -*OpenApiPetstore.StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*OpenApiPetstore.PetApi* | [**uploadFileWithRequiredFile**](docs/PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*OpenApiPetstore.StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID *OpenApiPetstore.StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -*OpenApiPetstore.StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*OpenApiPetstore.StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID *OpenApiPetstore.StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet *OpenApiPetstore.UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user *OpenApiPetstore.UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array @@ -148,10 +165,56 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [OpenApiPetstore.AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [OpenApiPetstore.Animal](docs/Animal.md) - [OpenApiPetstore.ApiResponse](docs/ApiResponse.md) + - [OpenApiPetstore.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [OpenApiPetstore.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [OpenApiPetstore.ArrayTest](docs/ArrayTest.md) + - [OpenApiPetstore.BasquePig](docs/BasquePig.md) + - [OpenApiPetstore.Capitalization](docs/Capitalization.md) + - [OpenApiPetstore.Cat](docs/Cat.md) + - [OpenApiPetstore.CatAllOf](docs/CatAllOf.md) - [OpenApiPetstore.Category](docs/Category.md) + - [OpenApiPetstore.ClassModel](docs/ClassModel.md) + - [OpenApiPetstore.Client](docs/Client.md) + - [OpenApiPetstore.Color](docs/Color.md) + - [OpenApiPetstore.DanishPig](docs/DanishPig.md) + - [OpenApiPetstore.DeprecatedObject](docs/DeprecatedObject.md) + - [OpenApiPetstore.Dog](docs/Dog.md) + - [OpenApiPetstore.DogAllOf](docs/DogAllOf.md) + - [OpenApiPetstore.EnumArrays](docs/EnumArrays.md) + - [OpenApiPetstore.EnumClass](docs/EnumClass.md) + - [OpenApiPetstore.EnumTest](docs/EnumTest.md) + - [OpenApiPetstore.File](docs/File.md) + - [OpenApiPetstore.FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [OpenApiPetstore.Foo](docs/Foo.md) + - [OpenApiPetstore.FooGetDefaultResponse](docs/FooGetDefaultResponse.md) + - [OpenApiPetstore.FormatTest](docs/FormatTest.md) + - [OpenApiPetstore.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [OpenApiPetstore.HealthCheckResult](docs/HealthCheckResult.md) + - [OpenApiPetstore.List](docs/List.md) + - [OpenApiPetstore.MapTest](docs/MapTest.md) + - [OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [OpenApiPetstore.Model200Response](docs/Model200Response.md) + - [OpenApiPetstore.Name](docs/Name.md) + - [OpenApiPetstore.NestedColor](docs/NestedColor.md) + - [OpenApiPetstore.NestedOneOf](docs/NestedOneOf.md) + - [OpenApiPetstore.NullableClass](docs/NullableClass.md) + - [OpenApiPetstore.NumberOnly](docs/NumberOnly.md) + - [OpenApiPetstore.ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - [OpenApiPetstore.Order](docs/Order.md) + - [OpenApiPetstore.OuterComposite](docs/OuterComposite.md) + - [OpenApiPetstore.OuterEnum](docs/OuterEnum.md) + - [OpenApiPetstore.OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) + - [OpenApiPetstore.OuterEnumInteger](docs/OuterEnumInteger.md) + - [OpenApiPetstore.OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) + - [OpenApiPetstore.OuterObjectWithEnumProperty](docs/OuterObjectWithEnumProperty.md) - [OpenApiPetstore.Pet](docs/Pet.md) + - [OpenApiPetstore.Pig](docs/Pig.md) + - [OpenApiPetstore.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [OpenApiPetstore.Return](docs/Return.md) + - [OpenApiPetstore.SpecialModelName](docs/SpecialModelName.md) - [OpenApiPetstore.Tag](docs/Tag.md) - [OpenApiPetstore.User](docs/User.md) @@ -169,6 +232,32 @@ Class | Method | HTTP request | Description +### api_key_query + + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + + +### bearer_test + +- **Type**: Bearer authentication (JWT) + + + +### http_basic_test + +- **Type**: HTTP basic authentication + + + +### http_signature_test + + + + ### petstore_auth diff --git a/samples/client/petstore/javascript-apollo/docs/AdditionalPropertiesClass.md b/samples/client/petstore/javascript-apollo/docs/AdditionalPropertiesClass.md new file mode 100644 index 0000000000..c85e85acd9 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/AdditionalPropertiesClass.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.AdditionalPropertiesClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **{String: String}** | | [optional] +**mapOfMapProperty** | **{String: {String: String}}** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Animal.md b/samples/client/petstore/javascript-apollo/docs/Animal.md new file mode 100644 index 0000000000..483c89a1ab --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Animal.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.Animal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] [default to 'red'] + + diff --git a/samples/client/petstore/javascript-apollo/docs/AnotherFakeApi.md b/samples/client/petstore/javascript-apollo/docs/AnotherFakeApi.md new file mode 100644 index 0000000000..ba01bd3e2a --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/AnotherFakeApi.md @@ -0,0 +1,54 @@ +# OpenApiPetstore.AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call123testSpecialTags**](AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags + + + +## call123testSpecialTags + +> Client call123testSpecialTags(client) + +To test special tags + +To test special tags and operation ID starting with number + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.AnotherFakeApi(); +let client = new OpenApiPetstore.Client(); // Client | client model +apiInstance.call123testSpecialTags(client, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + diff --git a/samples/client/petstore/javascript-apollo/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/javascript-apollo/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 0000000000..c321c0985f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.ArrayOfArrayOfNumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | **[[Number]]** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/ArrayOfNumberOnly.md b/samples/client/petstore/javascript-apollo/docs/ArrayOfNumberOnly.md new file mode 100644 index 0000000000..b83e136d97 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/ArrayOfNumberOnly.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.ArrayOfNumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | **[Number]** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/ArrayTest.md b/samples/client/petstore/javascript-apollo/docs/ArrayTest.md new file mode 100644 index 0000000000..711b53a520 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/ArrayTest.md @@ -0,0 +1,11 @@ +# OpenApiPetstore.ArrayTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **[String]** | | [optional] +**arrayArrayOfInteger** | **[[Number]]** | | [optional] +**arrayArrayOfModel** | **[[ReadOnlyFirst]]** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/BasquePig.md b/samples/client/petstore/javascript-apollo/docs/BasquePig.md new file mode 100644 index 0000000000..77d1e74bc7 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/BasquePig.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.BasquePig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | + + diff --git a/samples/client/petstore/javascript-apollo/docs/Capitalization.md b/samples/client/petstore/javascript-apollo/docs/Capitalization.md new file mode 100644 index 0000000000..3bbc5d491f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Capitalization.md @@ -0,0 +1,14 @@ +# OpenApiPetstore.Capitalization + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**sCAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Cat.md b/samples/client/petstore/javascript-apollo/docs/Cat.md new file mode 100644 index 0000000000..652bca4ed0 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Cat.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.Cat + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/CatAllOf.md b/samples/client/petstore/javascript-apollo/docs/CatAllOf.md new file mode 100644 index 0000000000..3b8274c012 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/CatAllOf.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.CatAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Category.md b/samples/client/petstore/javascript-apollo/docs/Category.md index ee7e2ea0df..2de44aa03d 100644 --- a/samples/client/petstore/javascript-apollo/docs/Category.md +++ b/samples/client/petstore/javascript-apollo/docs/Category.md @@ -5,6 +5,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **Number** | | [optional] -**name** | **String** | | [optional] +**name** | **String** | | [default to 'default-name'] diff --git a/samples/client/petstore/javascript-apollo/docs/ClassModel.md b/samples/client/petstore/javascript-apollo/docs/ClassModel.md new file mode 100644 index 0000000000..dd90930dad --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/ClassModel.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.ClassModel + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Client.md b/samples/client/petstore/javascript-apollo/docs/Client.md new file mode 100644 index 0000000000..1164b70431 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Client.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.Client + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Color.md b/samples/client/petstore/javascript-apollo/docs/Color.md new file mode 100644 index 0000000000..5f0e6f0dfb --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Color.md @@ -0,0 +1,8 @@ +# OpenApiPetstore.Color + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/javascript-apollo/docs/DanishPig.md b/samples/client/petstore/javascript-apollo/docs/DanishPig.md new file mode 100644 index 0000000000..7de3e60db3 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/DanishPig.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.DanishPig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**size** | **Number** | | + + diff --git a/samples/client/petstore/javascript-apollo/docs/DefaultApi.md b/samples/client/petstore/javascript-apollo/docs/DefaultApi.md new file mode 100644 index 0000000000..d24a241f95 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/DefaultApi.md @@ -0,0 +1,48 @@ +# OpenApiPetstore.DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fooGet**](DefaultApi.md#fooGet) | **GET** /foo | + + + +## fooGet + +> FooGetDefaultResponse fooGet() + + + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.DefaultApi(); +apiInstance.fooGet((error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**FooGetDefaultResponse**](FooGetDefaultResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + diff --git a/samples/client/petstore/javascript-apollo/docs/DeprecatedObject.md b/samples/client/petstore/javascript-apollo/docs/DeprecatedObject.md new file mode 100644 index 0000000000..77fba12df1 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/DeprecatedObject.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.DeprecatedObject + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Dog.md b/samples/client/petstore/javascript-apollo/docs/Dog.md new file mode 100644 index 0000000000..fd3b9f7c77 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Dog.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.Dog + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/DogAllOf.md b/samples/client/petstore/javascript-apollo/docs/DogAllOf.md new file mode 100644 index 0000000000..8a64029407 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/DogAllOf.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.DogAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/EnumArrays.md b/samples/client/petstore/javascript-apollo/docs/EnumArrays.md new file mode 100644 index 0000000000..4926385b3f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/EnumArrays.md @@ -0,0 +1,32 @@ +# OpenApiPetstore.EnumArrays + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | **String** | | [optional] +**arrayEnum** | **[String]** | | [optional] + + + +## Enum: JustSymbolEnum + + +* `GREATER_THAN_OR_EQUAL_TO` (value: `">="`) + +* `DOLLAR` (value: `"$"`) + + + + + +## Enum: [ArrayEnumEnum] + + +* `fish` (value: `"fish"`) + +* `crab` (value: `"crab"`) + + + + diff --git a/samples/client/petstore/javascript-apollo/docs/EnumClass.md b/samples/client/petstore/javascript-apollo/docs/EnumClass.md new file mode 100644 index 0000000000..cef9bb57a5 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/EnumClass.md @@ -0,0 +1,12 @@ +# OpenApiPetstore.EnumClass + +## Enum + + +* `_abc` (value: `"_abc"`) + +* `-efg` (value: `"-efg"`) + +* `(xyz)` (value: `"(xyz)"`) + + diff --git a/samples/client/petstore/javascript-apollo/docs/EnumTest.md b/samples/client/petstore/javascript-apollo/docs/EnumTest.md new file mode 100644 index 0000000000..b56c3c4cef --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/EnumTest.md @@ -0,0 +1,64 @@ +# OpenApiPetstore.EnumTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | **String** | | [optional] +**enumStringRequired** | **String** | | +**enumInteger** | **Number** | | [optional] +**enumNumber** | **Number** | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] +**outerEnumInteger** | [**OuterEnumInteger**](OuterEnumInteger.md) | | [optional] +**outerEnumDefaultValue** | [**OuterEnumDefaultValue**](OuterEnumDefaultValue.md) | | [optional] +**outerEnumIntegerDefaultValue** | [**OuterEnumIntegerDefaultValue**](OuterEnumIntegerDefaultValue.md) | | [optional] + + + +## Enum: EnumStringEnum + + +* `UPPER` (value: `"UPPER"`) + +* `lower` (value: `"lower"`) + +* `empty` (value: `""`) + + + + + +## Enum: EnumStringRequiredEnum + + +* `UPPER` (value: `"UPPER"`) + +* `lower` (value: `"lower"`) + +* `empty` (value: `""`) + + + + + +## Enum: EnumIntegerEnum + + +* `1` (value: `1`) + +* `-1` (value: `-1`) + + + + + +## Enum: EnumNumberEnum + + +* `1.1` (value: `1.1`) + +* `-1.2` (value: `-1.2`) + + + + diff --git a/samples/client/petstore/javascript-apollo/docs/FakeApi.md b/samples/client/petstore/javascript-apollo/docs/FakeApi.md new file mode 100644 index 0000000000..5b76c0a7f5 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/FakeApi.md @@ -0,0 +1,880 @@ +# OpenApiPetstore.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fakeHealthGet**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint +[**fakeHttpSignatureTest**](FakeApi.md#fakeHttpSignatureTest) | **GET** /fake/http-signature-test | test http signature authentication +[**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | +[**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +[**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | +[**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | +[**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data +[**testQueryParameterCollectionFormat**](FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | + + + +## fakeHealthGet + +> HealthCheckResult fakeHealthGet() + +Health check endpoint + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +apiInstance.fakeHealthGet((error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +## fakeHttpSignatureTest + +> fakeHttpSignatureTest(pet, opts) + +test http signature authentication + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; +let defaultClient = OpenApiPetstore.ApiClient.instance; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let pet = new OpenApiPetstore.Pet(); // Pet | Pet object that needs to be added to the store +let opts = { + 'query1': "query1_example", // String | query parameter + 'header1': "header1_example" // String | header parameter +}; +apiInstance.fakeHttpSignatureTest(pet, opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **query1** | **String**| query parameter | [optional] + **header1** | **String**| header parameter | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[http_signature_test](../README.md#http_signature_test) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +## fakeOuterBooleanSerialize + +> Boolean fakeOuterBooleanSerialize(opts) + + + +Test serialization of outer boolean types + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let opts = { + 'body': true // Boolean | Input boolean as post body +}; +apiInstance.fakeOuterBooleanSerialize(opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Boolean**| Input boolean as post body | [optional] + +### Return type + +**Boolean** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## fakeOuterCompositeSerialize + +> OuterComposite fakeOuterCompositeSerialize(opts) + + + +Test serialization of object with outer number type + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let opts = { + 'outerComposite': new OpenApiPetstore.OuterComposite() // OuterComposite | Input composite as post body +}; +apiInstance.fakeOuterCompositeSerialize(opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## fakeOuterNumberSerialize + +> Number fakeOuterNumberSerialize(opts) + + + +Test serialization of outer number types + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let opts = { + 'body': 3.4 // Number | Input number as post body +}; +apiInstance.fakeOuterNumberSerialize(opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Number**| Input number as post body | [optional] + +### Return type + +**Number** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## fakeOuterStringSerialize + +> String fakeOuterStringSerialize(opts) + + + +Test serialization of outer string types + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let opts = { + 'body': "body_example" // String | Input string as post body +}; +apiInstance.fakeOuterStringSerialize(opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String**| Input string as post body | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## fakePropertyEnumIntegerSerialize + +> OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty) + + + +Test serialization of enum (int) properties with examples + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let outerObjectWithEnumProperty = new OpenApiPetstore.OuterObjectWithEnumProperty(); // OuterObjectWithEnumProperty | Input enum (int) as post body +apiInstance.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **outerObjectWithEnumProperty** | [**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md)| Input enum (int) as post body | + +### Return type + +[**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## testBodyWithBinary + +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let body = "/path/to/file"; // File | image to upload +apiInstance.testBodyWithBinary(body, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **File**| image to upload | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + +## testBodyWithFileSchema + +> testBodyWithFileSchema(fileSchemaTestClass) + + + +For this test, the body for this request must reference a schema named `File`. + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let fileSchemaTestClass = new OpenApiPetstore.FileSchemaTestClass(); // FileSchemaTestClass | +apiInstance.testBodyWithFileSchema(fileSchemaTestClass, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +## testBodyWithQueryParams + +> testBodyWithQueryParams(query, user) + + + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let query = "query_example"; // String | +let user = new OpenApiPetstore.User(); // User | +apiInstance.testBodyWithQueryParams(query, user, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **String**| | + **user** | [**User**](User.md)| | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +## testClientModel + +> Client testClientModel(client) + +To test \"client\" model + +To test \"client\" model + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let client = new OpenApiPetstore.Client(); // Client | client model +apiInstance.testClientModel(client, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +## testEndpointParameters + +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, opts) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; +let defaultClient = OpenApiPetstore.ApiClient.instance; +// Configure HTTP basic authorization: http_basic_test +let http_basic_test = defaultClient.authentications['http_basic_test']; +http_basic_test.username = 'YOUR USERNAME'; +http_basic_test.password = 'YOUR PASSWORD'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let number = 3.4; // Number | None +let _double = 3.4; // Number | None +let patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None +let _byte = null; // Blob | None +let opts = { + 'integer': 56, // Number | None + 'int32': 56, // Number | None + 'int64': 789, // Number | None + '_float': 3.4, // Number | None + 'string': "string_example", // String | None + 'binary': "/path/to/file", // File | None + 'date': new Date("2013-10-20"), // Date | None + 'dateTime': new Date("2013-10-20T19:20:30+01:00"), // Date | None + 'password': "password_example", // String | None + 'callback': "callback_example" // String | None +}; +apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **Number**| None | + **_double** | **Number**| None | + **patternWithoutDelimiter** | **String**| None | + **_byte** | **Blob**| None | + **integer** | **Number**| None | [optional] + **int32** | **Number**| None | [optional] + **int64** | **Number**| None | [optional] + **_float** | **Number**| None | [optional] + **string** | **String**| None | [optional] + **binary** | **File**| None | [optional] + **date** | **Date**| None | [optional] + **dateTime** | **Date**| None | [optional] + **password** | **String**| None | [optional] + **callback** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +## testEnumParameters + +> testEnumParameters(opts) + +To test enum parameters + +To test enum parameters + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let opts = { + 'enumHeaderStringArray': ["'$'"], // [String] | Header parameter enum test (string array) + 'enumHeaderString': "'-efg'", // String | Header parameter enum test (string) + 'enumQueryStringArray': ["'$'"], // [String] | Query parameter enum test (string array) + 'enumQueryString': "'-efg'", // String | Query parameter enum test (string) + 'enumQueryInteger': 56, // Number | Query parameter enum test (double) + 'enumQueryDouble': 3.4, // Number | Query parameter enum test (double) + 'enumQueryModelArray': [new OpenApiPetstore.EnumClass()], // [EnumClass] | + 'enumFormStringArray': ["'$'"], // [String] | Form parameter enum test (string array) + 'enumFormString': "'-efg'" // String | Form parameter enum test (string) +}; +apiInstance.testEnumParameters(opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumHeaderStringArray** | [**[String]**](String.md)| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to '-efg'] + **enumQueryStringArray** | [**[String]**](String.md)| Query parameter enum test (string array) | [optional] + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to '-efg'] + **enumQueryInteger** | **Number**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Number**| Query parameter enum test (double) | [optional] + **enumQueryModelArray** | [**[EnumClass]**](EnumClass.md)| | [optional] + **enumFormStringArray** | [**[String]**](String.md)| Form parameter enum test (string array) | [optional] [default to '$'] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to '-efg'] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +## testGroupParameters + +> testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, opts) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; +let defaultClient = OpenApiPetstore.ApiClient.instance; +// Configure Bearer (JWT) access token for authorization: bearer_test +let bearer_test = defaultClient.authentications['bearer_test']; +bearer_test.accessToken = "YOUR ACCESS TOKEN" + +let apiInstance = new OpenApiPetstore.FakeApi(); +let requiredStringGroup = 56; // Number | Required String in group parameters +let requiredBooleanGroup = true; // Boolean | Required Boolean in group parameters +let requiredInt64Group = 789; // Number | Required Integer in group parameters +let opts = { + 'stringGroup': 56, // Number | String in group parameters + 'booleanGroup': true, // Boolean | Boolean in group parameters + 'int64Group': 789 // Number | Integer in group parameters +}; +apiInstance.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requiredStringGroup** | **Number**| Required String in group parameters | + **requiredBooleanGroup** | **Boolean**| Required Boolean in group parameters | + **requiredInt64Group** | **Number**| Required Integer in group parameters | + **stringGroup** | **Number**| String in group parameters | [optional] + **booleanGroup** | **Boolean**| Boolean in group parameters | [optional] + **int64Group** | **Number**| Integer in group parameters | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## testInlineAdditionalProperties + +> testInlineAdditionalProperties(requestBody) + +test inline additionalProperties + + + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let requestBody = {key: "null"}; // {String: String} | request body +apiInstance.testInlineAdditionalProperties(requestBody, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**{String: String}**](String.md)| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +## testJsonFormData + +> testJsonFormData(param, param2) + +test json serialization of form data + + + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let param = "param_example"; // String | field1 +let param2 = "param2_example"; // String | field2 +apiInstance.testJsonFormData(param, param2, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **String**| field1 | + **param2** | **String**| field2 | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +## testQueryParameterCollectionFormat + +> testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, allowEmpty, opts) + + + +To test the collection format in query parameters + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let pipe = ["null"]; // [String] | +let ioutil = ["null"]; // [String] | +let http = ["null"]; // [String] | +let url = ["null"]; // [String] | +let context = ["null"]; // [String] | +let allowEmpty = "allowEmpty_example"; // String | +let opts = { + 'language': {key: "null"} // {String: String} | +}; +apiInstance.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, allowEmpty, opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pipe** | [**[String]**](String.md)| | + **ioutil** | [**[String]**](String.md)| | + **http** | [**[String]**](String.md)| | + **url** | [**[String]**](String.md)| | + **context** | [**[String]**](String.md)| | + **allowEmpty** | **String**| | + **language** | [**{String: String}**](String.md)| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + diff --git a/samples/client/petstore/javascript-apollo/docs/FakeClassnameTags123Api.md b/samples/client/petstore/javascript-apollo/docs/FakeClassnameTags123Api.md new file mode 100644 index 0000000000..142a911a3c --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/FakeClassnameTags123Api.md @@ -0,0 +1,60 @@ +# OpenApiPetstore.FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClassname**](FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case + + + +## testClassname + +> Client testClassname(client) + +To test class name in snake case + +To test class name in snake case + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; +let defaultClient = OpenApiPetstore.ApiClient.instance; +// Configure API key authorization: api_key_query +let api_key_query = defaultClient.authentications['api_key_query']; +api_key_query.apiKey = 'YOUR API KEY'; +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key_query.apiKeyPrefix = 'Token'; + +let apiInstance = new OpenApiPetstore.FakeClassnameTags123Api(); +let client = new OpenApiPetstore.Client(); // Client | client model +apiInstance.testClassname(client, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + diff --git a/samples/client/petstore/javascript-apollo/docs/File.md b/samples/client/petstore/javascript-apollo/docs/File.md new file mode 100644 index 0000000000..51162c3e0d --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/File.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.File + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**sourceURI** | **String** | Test capitalization | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/FileSchemaTestClass.md b/samples/client/petstore/javascript-apollo/docs/FileSchemaTestClass.md new file mode 100644 index 0000000000..6f28c4976f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/FileSchemaTestClass.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.FileSchemaTestClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**file** | **File** | | [optional] +**files** | **[File]** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Foo.md b/samples/client/petstore/javascript-apollo/docs/Foo.md new file mode 100644 index 0000000000..1e0c9a294c --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Foo.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.Foo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [default to 'bar'] + + diff --git a/samples/client/petstore/javascript-apollo/docs/FooGetDefaultResponse.md b/samples/client/petstore/javascript-apollo/docs/FooGetDefaultResponse.md new file mode 100644 index 0000000000..031b906084 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/FooGetDefaultResponse.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.FooGetDefaultResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**string** | [**Foo**](Foo.md) | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/FormatTest.md b/samples/client/petstore/javascript-apollo/docs/FormatTest.md new file mode 100644 index 0000000000..c1f26210e3 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/FormatTest.md @@ -0,0 +1,24 @@ +# OpenApiPetstore.FormatTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Number** | | [optional] +**int32** | **Number** | | [optional] +**int64** | **Number** | | [optional] +**number** | **Number** | | +**_float** | **Number** | | [optional] +**_double** | **Number** | | [optional] +**decimal** | **Number** | | [optional] +**string** | **String** | | [optional] +**_byte** | **Blob** | | +**binary** | **File** | | [optional] +**date** | **Date** | | +**dateTime** | **Date** | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | +**patternWithDigits** | **String** | A string that is a 10 digit number. Can have leading zeros. | [optional] +**patternWithDigitsAndDelimiter** | **String** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/HasOnlyReadOnly.md b/samples/client/petstore/javascript-apollo/docs/HasOnlyReadOnly.md new file mode 100644 index 0000000000..bfe08a1bae --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/HasOnlyReadOnly.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.HasOnlyReadOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**foo** | **String** | | [optional] [readonly] + + diff --git a/samples/client/petstore/javascript-apollo/docs/HealthCheckResult.md b/samples/client/petstore/javascript-apollo/docs/HealthCheckResult.md new file mode 100644 index 0000000000..bbb74ac6a0 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/HealthCheckResult.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.HealthCheckResult + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**nullableMessage** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/List.md b/samples/client/petstore/javascript-apollo/docs/List.md new file mode 100644 index 0000000000..aaaa082e6a --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/List.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.List + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123list** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/MapTest.md b/samples/client/petstore/javascript-apollo/docs/MapTest.md new file mode 100644 index 0000000000..9399adf753 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/MapTest.md @@ -0,0 +1,23 @@ +# OpenApiPetstore.MapTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | **{String: {String: String}}** | | [optional] +**mapOfEnumString** | **{String: String}** | | [optional] +**directMap** | **{String: Boolean}** | | [optional] +**indirectMap** | **{String: Boolean}** | | [optional] + + + +## Enum: {String: String} + + +* `UPPER` (value: `"UPPER"`) + +* `lower` (value: `"lower"`) + + + + diff --git a/samples/client/petstore/javascript-apollo/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/javascript-apollo/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 0000000000..776d4b3ae0 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | **Date** | | [optional] +**map** | [**{String: Animal}**](Animal.md) | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Model200Response.md b/samples/client/petstore/javascript-apollo/docs/Model200Response.md new file mode 100644 index 0000000000..45f7932a1b --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Model200Response.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.Model200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Number** | | [optional] +**_class** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Name.md b/samples/client/petstore/javascript-apollo/docs/Name.md new file mode 100644 index 0000000000..d9f2fbeb68 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Name.md @@ -0,0 +1,12 @@ +# OpenApiPetstore.Name + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Number** | | +**snakeCase** | **Number** | | [optional] [readonly] +**property** | **String** | | [optional] +**_123number** | **Number** | | [optional] [readonly] + + diff --git a/samples/client/petstore/javascript-apollo/docs/NestedColor.md b/samples/client/petstore/javascript-apollo/docs/NestedColor.md new file mode 100644 index 0000000000..aea6b44494 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/NestedColor.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.NestedColor + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**size** | **Number** | | [optional] +**nested** | [**Color**](Color.md) | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/NestedOneOf.md b/samples/client/petstore/javascript-apollo/docs/NestedOneOf.md new file mode 100644 index 0000000000..b5228e89c7 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/NestedOneOf.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.NestedOneOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**size** | **Number** | | [optional] +**nestedPig** | [**Pig**](Pig.md) | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/NullableClass.md b/samples/client/petstore/javascript-apollo/docs/NullableClass.md new file mode 100644 index 0000000000..3460980270 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/NullableClass.md @@ -0,0 +1,20 @@ +# OpenApiPetstore.NullableClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integerProp** | **Number** | | [optional] +**numberProp** | **Number** | | [optional] +**booleanProp** | **Boolean** | | [optional] +**stringProp** | **String** | | [optional] +**dateProp** | **Date** | | [optional] +**datetimeProp** | **Date** | | [optional] +**arrayNullableProp** | **[Object]** | | [optional] +**arrayAndItemsNullableProp** | **[Object]** | | [optional] +**arrayItemsNullable** | **[Object]** | | [optional] +**objectNullableProp** | **{String: Object}** | | [optional] +**objectAndItemsNullableProp** | **{String: Object}** | | [optional] +**objectItemsNullable** | **{String: Object}** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/NumberOnly.md b/samples/client/petstore/javascript-apollo/docs/NumberOnly.md new file mode 100644 index 0000000000..6524360075 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/NumberOnly.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.NumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | **Number** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/ObjectWithDeprecatedFields.md b/samples/client/petstore/javascript-apollo/docs/ObjectWithDeprecatedFields.md new file mode 100644 index 0000000000..fe6ebba0b6 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/ObjectWithDeprecatedFields.md @@ -0,0 +1,12 @@ +# OpenApiPetstore.ObjectWithDeprecatedFields + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**id** | **Number** | | [optional] +**deprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] +**bars** | **[String]** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/OuterComposite.md b/samples/client/petstore/javascript-apollo/docs/OuterComposite.md new file mode 100644 index 0000000000..aea253a0df --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/OuterComposite.md @@ -0,0 +1,11 @@ +# OpenApiPetstore.OuterComposite + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**myNumber** | **Number** | | [optional] +**myString** | **String** | | [optional] +**myBoolean** | **Boolean** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/OuterEnum.md b/samples/client/petstore/javascript-apollo/docs/OuterEnum.md new file mode 100644 index 0000000000..445d3f4074 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/OuterEnum.md @@ -0,0 +1,12 @@ +# OpenApiPetstore.OuterEnum + +## Enum + + +* `placed` (value: `"placed"`) + +* `approved` (value: `"approved"`) + +* `delivered` (value: `"delivered"`) + + diff --git a/samples/client/petstore/javascript-apollo/docs/OuterEnumDefaultValue.md b/samples/client/petstore/javascript-apollo/docs/OuterEnumDefaultValue.md new file mode 100644 index 0000000000..6da697f636 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/OuterEnumDefaultValue.md @@ -0,0 +1,12 @@ +# OpenApiPetstore.OuterEnumDefaultValue + +## Enum + + +* `placed` (value: `"placed"`) + +* `approved` (value: `"approved"`) + +* `delivered` (value: `"delivered"`) + + diff --git a/samples/client/petstore/javascript-apollo/docs/OuterEnumInteger.md b/samples/client/petstore/javascript-apollo/docs/OuterEnumInteger.md new file mode 100644 index 0000000000..224989a0e6 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/OuterEnumInteger.md @@ -0,0 +1,12 @@ +# OpenApiPetstore.OuterEnumInteger + +## Enum + + +* `0` (value: `0`) + +* `1` (value: `1`) + +* `2` (value: `2`) + + diff --git a/samples/client/petstore/javascript-apollo/docs/OuterEnumIntegerDefaultValue.md b/samples/client/petstore/javascript-apollo/docs/OuterEnumIntegerDefaultValue.md new file mode 100644 index 0000000000..fffd3f8f31 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/OuterEnumIntegerDefaultValue.md @@ -0,0 +1,12 @@ +# OpenApiPetstore.OuterEnumIntegerDefaultValue + +## Enum + + +* `0` (value: `0`) + +* `1` (value: `1`) + +* `2` (value: `2`) + + diff --git a/samples/client/petstore/javascript-apollo/docs/OuterObjectWithEnumProperty.md b/samples/client/petstore/javascript-apollo/docs/OuterObjectWithEnumProperty.md new file mode 100644 index 0000000000..a16331e63a --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/OuterObjectWithEnumProperty.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.OuterObjectWithEnumProperty + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | [**OuterEnumInteger**](OuterEnumInteger.md) | | + + diff --git a/samples/client/petstore/javascript-apollo/docs/PetApi.md b/samples/client/petstore/javascript-apollo/docs/PetApi.md index b08c6a3213..cce0be79c8 100644 --- a/samples/client/petstore/javascript-apollo/docs/PetApi.md +++ b/samples/client/petstore/javascript-apollo/docs/PetApi.md @@ -1,6 +1,6 @@ # OpenApiPetstore.PetApi -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -12,15 +12,18 @@ Method | HTTP request | Description [**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet [**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data [**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**uploadFileWithRequiredFile**](PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) ## addPet -> addPet(body) +> addPet(pet) Add a new pet to the store + + ### Example ```javascript @@ -31,8 +34,8 @@ let petstore_auth = defaultClient.authentications['petstore_auth']; petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; let apiInstance = new OpenApiPetstore.PetApi(); -let body = new OpenApiPetstore.Pet(); // Pet | Pet object that needs to be added to the store -apiInstance.addPet(body, (error, data, response) => { +let pet = new OpenApiPetstore.Pet(); // Pet | Pet object that needs to be added to the store +apiInstance.addPet(pet, (error, data, response) => { if (error) { console.error(error); } else { @@ -46,7 +49,7 @@ apiInstance.addPet(body, (error, data, response) => { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -68,6 +71,8 @@ null (empty response body) Deletes a pet + + ### Example ```javascript @@ -264,10 +269,12 @@ Name | Type | Description | Notes ## updatePet -> updatePet(body) +> updatePet(pet) Update an existing pet + + ### Example ```javascript @@ -278,8 +285,8 @@ let petstore_auth = defaultClient.authentications['petstore_auth']; petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; let apiInstance = new OpenApiPetstore.PetApi(); -let body = new OpenApiPetstore.Pet(); // Pet | Pet object that needs to be added to the store -apiInstance.updatePet(body, (error, data, response) => { +let pet = new OpenApiPetstore.Pet(); // Pet | Pet object that needs to be added to the store +apiInstance.updatePet(pet, (error, data, response) => { if (error) { console.error(error); } else { @@ -293,7 +300,7 @@ apiInstance.updatePet(body, (error, data, response) => { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -315,6 +322,8 @@ null (empty response body) Updates a pet in the store with form data + + ### Example ```javascript @@ -368,6 +377,8 @@ null (empty response body) uploads an image + + ### Example ```javascript @@ -414,3 +425,58 @@ Name | Type | Description | Notes - **Content-Type**: multipart/form-data - **Accept**: application/json + +## uploadFileWithRequiredFile + +> ApiResponse uploadFileWithRequiredFile(petId, requiredFile, opts) + +uploads an image (required) + + + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; +let defaultClient = OpenApiPetstore.ApiClient.instance; +// Configure OAuth2 access token for authorization: petstore_auth +let petstore_auth = defaultClient.authentications['petstore_auth']; +petstore_auth.accessToken = 'YOUR ACCESS TOKEN'; + +let apiInstance = new OpenApiPetstore.PetApi(); +let petId = 789; // Number | ID of pet to update +let requiredFile = "/path/to/file"; // File | file to upload +let opts = { + 'additionalMetadata': "additionalMetadata_example" // String | Additional data to pass to server +}; +apiInstance.uploadFileWithRequiredFile(petId, requiredFile, opts, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Number**| ID of pet to update | + **requiredFile** | **File**| file to upload | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + diff --git a/samples/client/petstore/javascript-apollo/docs/Pig.md b/samples/client/petstore/javascript-apollo/docs/Pig.md new file mode 100644 index 0000000000..a94e1687cc --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Pig.md @@ -0,0 +1,11 @@ +# OpenApiPetstore.Pig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | +**size** | **Number** | | + + diff --git a/samples/client/petstore/javascript-apollo/docs/ReadOnlyFirst.md b/samples/client/petstore/javascript-apollo/docs/ReadOnlyFirst.md new file mode 100644 index 0000000000..eee7a321d4 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/ReadOnlyFirst.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.ReadOnlyFirst + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**baz** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/Return.md b/samples/client/petstore/javascript-apollo/docs/Return.md new file mode 100644 index 0000000000..94b747a28f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/Return.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.Return + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Number** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/SpecialModelName.md b/samples/client/petstore/javascript-apollo/docs/SpecialModelName.md new file mode 100644 index 0000000000..f33678460b --- /dev/null +++ b/samples/client/petstore/javascript-apollo/docs/SpecialModelName.md @@ -0,0 +1,9 @@ +# OpenApiPetstore.SpecialModelName + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Number** | | [optional] + + diff --git a/samples/client/petstore/javascript-apollo/docs/StoreApi.md b/samples/client/petstore/javascript-apollo/docs/StoreApi.md index 35c9f90ca0..b7abc576af 100644 --- a/samples/client/petstore/javascript-apollo/docs/StoreApi.md +++ b/samples/client/petstore/javascript-apollo/docs/StoreApi.md @@ -1,12 +1,12 @@ # OpenApiPetstore.StoreApi -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID [**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID [**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet @@ -150,18 +150,20 @@ No authorization required ## placeOrder -> Order placeOrder(body) +> Order placeOrder(order) Place an order for a pet + + ### Example ```javascript import OpenApiPetstore from 'open_api_petstore'; let apiInstance = new OpenApiPetstore.StoreApi(); -let body = new OpenApiPetstore.Order(); // Order | order placed for purchasing the pet -apiInstance.placeOrder(body, (error, data, response) => { +let order = new OpenApiPetstore.Order(); // Order | order placed for purchasing the pet +apiInstance.placeOrder(order, (error, data, response) => { if (error) { console.error(error); } else { @@ -175,7 +177,7 @@ apiInstance.placeOrder(body, (error, data, response) => { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Order**](Order.md)| order placed for purchasing the pet | + **order** | [**Order**](Order.md)| order placed for purchasing the pet | ### Return type @@ -187,6 +189,6 @@ No authorization required ### HTTP request headers -- **Content-Type**: Not defined +- **Content-Type**: application/json - **Accept**: application/xml, application/json diff --git a/samples/client/petstore/javascript-apollo/docs/UserApi.md b/samples/client/petstore/javascript-apollo/docs/UserApi.md index 01e0bc048d..d3631acbfb 100644 --- a/samples/client/petstore/javascript-apollo/docs/UserApi.md +++ b/samples/client/petstore/javascript-apollo/docs/UserApi.md @@ -1,6 +1,6 @@ # OpenApiPetstore.UserApi -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -17,7 +17,7 @@ Method | HTTP request | Description ## createUser -> createUser(body) +> createUser(user) Create user @@ -29,8 +29,8 @@ This can only be done by the logged in user. import OpenApiPetstore from 'open_api_petstore'; let apiInstance = new OpenApiPetstore.UserApi(); -let body = new OpenApiPetstore.User(); // User | Created user object -apiInstance.createUser(body, (error, data, response) => { +let user = new OpenApiPetstore.User(); // User | Created user object +apiInstance.createUser(user, (error, data, response) => { if (error) { console.error(error); } else { @@ -44,7 +44,7 @@ apiInstance.createUser(body, (error, data, response) => { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**User**](User.md)| Created user object | + **user** | [**User**](User.md)| Created user object | ### Return type @@ -56,24 +56,26 @@ No authorization required ### HTTP request headers -- **Content-Type**: Not defined +- **Content-Type**: application/json - **Accept**: Not defined ## createUsersWithArrayInput -> createUsersWithArrayInput(body) +> createUsersWithArrayInput(user) Creates list of users with given input array + + ### Example ```javascript import OpenApiPetstore from 'open_api_petstore'; let apiInstance = new OpenApiPetstore.UserApi(); -let body = [new OpenApiPetstore.User()]; // [User] | List of user object -apiInstance.createUsersWithArrayInput(body, (error, data, response) => { +let user = [new OpenApiPetstore.User()]; // [User] | List of user object +apiInstance.createUsersWithArrayInput(user, (error, data, response) => { if (error) { console.error(error); } else { @@ -87,7 +89,7 @@ apiInstance.createUsersWithArrayInput(body, (error, data, response) => { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[User]**](User.md)| List of user object | + **user** | [**[User]**](User.md)| List of user object | ### Return type @@ -99,24 +101,26 @@ No authorization required ### HTTP request headers -- **Content-Type**: Not defined +- **Content-Type**: application/json - **Accept**: Not defined ## createUsersWithListInput -> createUsersWithListInput(body) +> createUsersWithListInput(user) Creates list of users with given input array + + ### Example ```javascript import OpenApiPetstore from 'open_api_petstore'; let apiInstance = new OpenApiPetstore.UserApi(); -let body = [new OpenApiPetstore.User()]; // [User] | List of user object -apiInstance.createUsersWithListInput(body, (error, data, response) => { +let user = [new OpenApiPetstore.User()]; // [User] | List of user object +apiInstance.createUsersWithListInput(user, (error, data, response) => { if (error) { console.error(error); } else { @@ -130,7 +134,7 @@ apiInstance.createUsersWithListInput(body, (error, data, response) => { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[User]**](User.md)| List of user object | + **user** | [**[User]**](User.md)| List of user object | ### Return type @@ -142,7 +146,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: Not defined +- **Content-Type**: application/json - **Accept**: Not defined @@ -197,6 +201,8 @@ No authorization required Get user by user name + + ### Example ```javascript @@ -240,6 +246,8 @@ No authorization required Logs user into the system + + ### Example ```javascript @@ -285,6 +293,8 @@ No authorization required Logs out current logged in user session + + ### Example ```javascript @@ -320,7 +330,7 @@ No authorization required ## updateUser -> updateUser(username, body) +> updateUser(username, user) Updated user @@ -333,8 +343,8 @@ import OpenApiPetstore from 'open_api_petstore'; let apiInstance = new OpenApiPetstore.UserApi(); let username = "username_example"; // String | name that need to be deleted -let body = new OpenApiPetstore.User(); // User | Updated user object -apiInstance.updateUser(username, body, (error, data, response) => { +let user = new OpenApiPetstore.User(); // User | Updated user object +apiInstance.updateUser(username, user, (error, data, response) => { if (error) { console.error(error); } else { @@ -349,7 +359,7 @@ apiInstance.updateUser(username, body, (error, data, response) => { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **String**| name that need to be deleted | - **body** | [**User**](User.md)| Updated user object | + **user** | [**User**](User.md)| Updated user object | ### Return type @@ -361,6 +371,6 @@ No authorization required ### HTTP request headers -- **Content-Type**: Not defined +- **Content-Type**: application/json - **Accept**: Not defined diff --git a/samples/client/petstore/javascript-apollo/git_push.sh b/samples/client/petstore/javascript-apollo/git_push.sh index ced3be2b0c..f53a75d4fa 100644 --- a/samples/client/petstore/javascript-apollo/git_push.sh +++ b/samples/client/petstore/javascript-apollo/git_push.sh @@ -1,7 +1,7 @@ #!/bin/sh # ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ # -# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" git_user_id=$1 git_repo_id=$2 @@ -38,14 +38,14 @@ git add . git commit -m "$release_note" # Sets the new remote -git_remote=`git remote` +git_remote=$(git remote) if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git fi fi @@ -55,4 +55,3 @@ git pull origin master # Pushes (Forces) the changes in the local repository up to the remote repository echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" git push origin master 2>&1 | grep -v 'To https' - diff --git a/samples/client/petstore/javascript-apollo/package.json b/samples/client/petstore/javascript-apollo/package.json index 77e6db68c7..2749e38845 100644 --- a/samples/client/petstore/javascript-apollo/package.json +++ b/samples/client/petstore/javascript-apollo/package.json @@ -1,24 +1,47 @@ { "name": "open_api_petstore", "version": "1.0.0", - "description": "This_is_a_sample_server_Petstore_server__For_this_sample_you_can_use_the_api_key_special_key_to_test_the_authorization_filters_", + "description": "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\", "license": "Apache-2.0", - "main": "src/index.js", + "main": "dist/index.js", "scripts": { + "build": "babel src -d dist", + "prepare": "npm run build", "test": "mocha --require @babel/register --recursive" }, "browser": { "fs": false }, "dependencies": { - "apollo-datasource-rest": "^0.7.0" + "@babel/cli": "^7.0.0", + "apollo-datasource-rest": "^3.6.1", + "superagent": "^5.3.0" }, "devDependencies": { + "@babel/core": "^7.0.0", + "@babel/plugin-proposal-class-properties": "^7.0.0", + "@babel/plugin-proposal-decorators": "^7.0.0", + "@babel/plugin-proposal-do-expressions": "^7.0.0", + "@babel/plugin-proposal-export-default-from": "^7.0.0", + "@babel/plugin-proposal-export-namespace-from": "^7.0.0", + "@babel/plugin-proposal-function-bind": "^7.0.0", + "@babel/plugin-proposal-function-sent": "^7.0.0", + "@babel/plugin-proposal-json-strings": "^7.0.0", + "@babel/plugin-proposal-logical-assignment-operators": "^7.0.0", + "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0", + "@babel/plugin-proposal-numeric-separator": "^7.0.0", + "@babel/plugin-proposal-optional-chaining": "^7.0.0", + "@babel/plugin-proposal-pipeline-operator": "^7.0.0", + "@babel/plugin-proposal-throw-expressions": "^7.0.0", + "@babel/plugin-syntax-dynamic-import": "^7.0.0", + "@babel/plugin-syntax-import-meta": "^7.0.0", + "@babel/preset-env": "^7.0.0", + "@babel/register": "^7.0.0", "expect.js": "^0.3.1", - "mocha": "^5.2.0", + "mocha": "^8.0.1", "sinon": "^7.2.0" }, "files": [ - "src" + "dist" ] } diff --git a/samples/client/petstore/javascript-apollo/src/ApiClient.js b/samples/client/petstore/javascript-apollo/src/ApiClient.js index d2d855b712..97d65f916f 100644 --- a/samples/client/petstore/javascript-apollo/src/ApiClient.js +++ b/samples/client/petstore/javascript-apollo/src/ApiClient.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -12,7 +12,7 @@ */ -import RESTDataSource from 'apollo-datasource-rest'; +import { RESTDataSource } from 'apollo-datasource-rest'; /** * @module ApiClient @@ -26,15 +26,25 @@ import RESTDataSource from 'apollo-datasource-rest'; * @class */ export default class ApiClient extends RESTDataSource { - constructor() { + constructor(baseURL = 'http://petstore.swagger.io:80/v2') { super() - + + /** + * The base URL against which to resolve every API call's (relative) path. + * @type {String} + * @default http://petstore.swagger.io:80/v2 + */ + this.baseURL = baseURL.replace(/\/+$/, ''); + /** * The authentication methods to be included for all API calls. * @type {Array.} */ this.authentications = { 'api_key': {type: 'apiKey', 'in': 'header', name: 'api_key'}, + 'api_key_query': {type: 'apiKey', 'in': 'query', name: 'api_key_query'}, + 'bearer_test': {type: 'bearer'}, // JWT + 'http_basic_test': {type: 'basic'}, 'petstore_auth': {type: 'oauth2'} } } @@ -51,7 +61,7 @@ export default class ApiClient extends RESTDataSource { } parametrizePath(path, pathParams) { - return url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { + return path.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { var value; if (pathParams.hasOwnProperty(key)) { value = this.paramToString(pathParams[key]); @@ -174,18 +184,20 @@ export default class ApiClient extends RESTDataSource { async callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, - returnType) { + contentTypes, accepts, returnType, requestInit) { + + var normalizedQueryParams = this.normalizeParams(queryParams); var parameterizedPath = this.parametrizePath(path, pathParams); var fetchOptions = { headers: headerParams, - params: queryParams + params: normalizedQueryParams }; this.applyAuthOptions(fetchOptions, authNames); var body = null; - + if (bodyParam !== null && bodyParam !== undefined) { body = bodyParam; } else if (formParams !== null && formParams !== undefined) { @@ -201,9 +213,9 @@ export default class ApiClient extends RESTDataSource { var httpMethodFn = httpMethod.toLowerCase(); if (httpMethodFn == 'get' || httpMethodFn == 'delete') { - response = await this[httpMethodFn](parameterizedPath, fetchOptions); + response = await this[httpMethodFn](parameterizedPath, normalizedQueryParams, requestInit); } else { - response = await this[httpMethodFn](parameterizedPath, body, fetchOptions) + response = await this[httpMethodFn](parameterizedPath, body, requestInit) } var convertedResponse = ApiClient.convertToType(response, returnType); @@ -232,7 +244,7 @@ export default class ApiClient extends RESTDataSource { case 'Blob': return data; default: - if (type === Object) { + if (typeof type === "object") { // generic object, return directly return data; } else if (typeof type.constructFromObject === 'function') { diff --git a/samples/client/petstore/javascript-apollo/src/api/AnotherFakeApi.js b/samples/client/petstore/javascript-apollo/src/api/AnotherFakeApi.js new file mode 100644 index 0000000000..fda166d2ab --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/api/AnotherFakeApi.js @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + + + +import ApiClient from "../ApiClient"; +import Client from '../model/Client'; + +/** +* AnotherFake service. +* @module api/AnotherFakeApi +* @version 1.0.0 +*/ +export default class AnotherFakeApi extends ApiClient { + + /** + * Constructs a new AnotherFakeApi. + * @alias module:api/AnotherFakeApi + * @class + */ + constructor(baseURL = 'http://petstore.swagger.io:80/v2') { + super(baseURL); + } + + + /** + * To test special tags + * To test special tags and operation ID starting with number + * @param {module:model/Client} client client model + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async call123testSpecialTags(client, requestInit) { + let postBody = client; + // verify the required parameter 'client' is set + if (client === undefined || client === null) { + throw new Error("Missing the required parameter 'client' when calling call123testSpecialTags"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = ['application/json']; + let returnType = Client; + + return this.callApi( + '/another-fake/dummy', 'PATCH', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + +} diff --git a/samples/client/petstore/javascript-apollo/src/api/DefaultApi.js b/samples/client/petstore/javascript-apollo/src/api/DefaultApi.js new file mode 100644 index 0000000000..6ff467614d --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/api/DefaultApi.js @@ -0,0 +1,66 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + + + +import ApiClient from "../ApiClient"; +import FooGetDefaultResponse from '../model/FooGetDefaultResponse'; + +/** +* Default service. +* @module api/DefaultApi +* @version 1.0.0 +*/ +export default class DefaultApi extends ApiClient { + + /** + * Constructs a new DefaultApi. + * @alias module:api/DefaultApi + * @class + */ + constructor(baseURL = 'http://petstore.swagger.io:80/v2') { + super(baseURL); + } + + + /** + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async fooGet(requestInit) { + let postBody = null; + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = []; + let accepts = ['application/json']; + let returnType = FooGetDefaultResponse; + + return this.callApi( + '/foo', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + +} diff --git a/samples/client/petstore/javascript-apollo/src/api/FakeApi.js b/samples/client/petstore/javascript-apollo/src/api/FakeApi.js new file mode 100644 index 0000000000..c29506203b --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/api/FakeApi.js @@ -0,0 +1,762 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + + + +import ApiClient from "../ApiClient"; +import Client from '../model/Client'; +import EnumClass from '../model/EnumClass'; +import FileSchemaTestClass from '../model/FileSchemaTestClass'; +import HealthCheckResult from '../model/HealthCheckResult'; +import OuterComposite from '../model/OuterComposite'; +import OuterObjectWithEnumProperty from '../model/OuterObjectWithEnumProperty'; +import Pet from '../model/Pet'; +import User from '../model/User'; + +/** +* Fake service. +* @module api/FakeApi +* @version 1.0.0 +*/ +export default class FakeApi extends ApiClient { + + /** + * Constructs a new FakeApi. + * @alias module:api/FakeApi + * @class + */ + constructor(baseURL = 'http://petstore.swagger.io:80/v2') { + super(baseURL); + } + + + /** + * Health check endpoint + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async fakeHealthGet(requestInit) { + let postBody = null; + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = []; + let accepts = ['application/json']; + let returnType = HealthCheckResult; + + return this.callApi( + '/fake/health', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * test http signature authentication + * @param {module:model/Pet} pet Pet object that needs to be added to the store + * @param {Object} opts Optional parameters + * @param {String} opts.query1 query parameter + * @param {String} opts.header1 header parameter + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async fakeHttpSignatureTest(pet, opts, requestInit) { + opts = opts || {}; + let postBody = pet; + // verify the required parameter 'pet' is set + if (pet === undefined || pet === null) { + throw new Error("Missing the required parameter 'pet' when calling fakeHttpSignatureTest"); + } + + let pathParams = { + }; + let queryParams = { + 'query_1': opts['query1'] + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + 'header_1': opts['header1'] + }; + let formParams = { + }; + + let authNames = ['http_signature_test']; + let contentTypes = ['application/json', 'application/xml']; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake/http-signature-test', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * Test serialization of outer boolean types + * @param {Object} opts Optional parameters + * @param {Boolean} opts.body Input boolean as post body + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async fakeOuterBooleanSerialize(opts, requestInit) { + opts = opts || {}; + let postBody = opts['body']; + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = ['*/*']; + let returnType = 'Boolean'; + + return this.callApi( + '/fake/outer/boolean', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * Test serialization of object with outer number type + * @param {Object} opts Optional parameters + * @param {module:model/OuterComposite} opts.outerComposite Input composite as post body + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async fakeOuterCompositeSerialize(opts, requestInit) { + opts = opts || {}; + let postBody = opts['outerComposite']; + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = ['*/*']; + let returnType = OuterComposite; + + return this.callApi( + '/fake/outer/composite', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * Test serialization of outer number types + * @param {Object} opts Optional parameters + * @param {Number} opts.body Input number as post body + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async fakeOuterNumberSerialize(opts, requestInit) { + opts = opts || {}; + let postBody = opts['body']; + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = ['*/*']; + let returnType = 'Number'; + + return this.callApi( + '/fake/outer/number', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * Test serialization of outer string types + * @param {Object} opts Optional parameters + * @param {String} opts.body Input string as post body + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async fakeOuterStringSerialize(opts, requestInit) { + opts = opts || {}; + let postBody = opts['body']; + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = ['*/*']; + let returnType = 'String'; + + return this.callApi( + '/fake/outer/string', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * Test serialization of enum (int) properties with examples + * @param {module:model/OuterObjectWithEnumProperty} outerObjectWithEnumProperty Input enum (int) as post body + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty, requestInit) { + let postBody = outerObjectWithEnumProperty; + // verify the required parameter 'outerObjectWithEnumProperty' is set + if (outerObjectWithEnumProperty === undefined || outerObjectWithEnumProperty === null) { + throw new Error("Missing the required parameter 'outerObjectWithEnumProperty' when calling fakePropertyEnumIntegerSerialize"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = ['*/*']; + let returnType = OuterObjectWithEnumProperty; + + return this.callApi( + '/fake/property/enum-int', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * For this test, the body has to be a binary file. + * @param {File} body image to upload + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testBodyWithBinary(body, requestInit) { + let postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling testBodyWithBinary"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['image/png']; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake/body-with-binary', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * For this test, the body for this request must reference a schema named `File`. + * @param {module:model/FileSchemaTestClass} fileSchemaTestClass + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testBodyWithFileSchema(fileSchemaTestClass, requestInit) { + let postBody = fileSchemaTestClass; + // verify the required parameter 'fileSchemaTestClass' is set + if (fileSchemaTestClass === undefined || fileSchemaTestClass === null) { + throw new Error("Missing the required parameter 'fileSchemaTestClass' when calling testBodyWithFileSchema"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake/body-with-file-schema', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * @param {String} query + * @param {module:model/User} user + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testBodyWithQueryParams(query, user, requestInit) { + let postBody = user; + // verify the required parameter 'query' is set + if (query === undefined || query === null) { + throw new Error("Missing the required parameter 'query' when calling testBodyWithQueryParams"); + } + // verify the required parameter 'user' is set + if (user === undefined || user === null) { + throw new Error("Missing the required parameter 'user' when calling testBodyWithQueryParams"); + } + + let pathParams = { + }; + let queryParams = { + 'query': query + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake/body-with-query-params', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param {module:model/Client} client client model + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testClientModel(client, requestInit) { + let postBody = client; + // verify the required parameter 'client' is set + if (client === undefined || client === null) { + throw new Error("Missing the required parameter 'client' when calling testClientModel"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = ['application/json']; + let returnType = Client; + + return this.callApi( + '/fake', 'PATCH', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param {Number} number None + * @param {Number} _double None + * @param {String} patternWithoutDelimiter None + * @param {Blob} _byte None + * @param {Object} opts Optional parameters + * @param {Number} opts.integer None + * @param {Number} opts.int32 None + * @param {Number} opts.int64 None + * @param {Number} opts._float None + * @param {String} opts.string None + * @param {File} opts.binary None + * @param {Date} opts.date None + * @param {Date} opts.dateTime None + * @param {String} opts.password None + * @param {String} opts.callback None + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, opts, requestInit) { + opts = opts || {}; + let postBody = null; + // verify the required parameter 'number' is set + if (number === undefined || number === null) { + throw new Error("Missing the required parameter 'number' when calling testEndpointParameters"); + } + // verify the required parameter '_double' is set + if (_double === undefined || _double === null) { + throw new Error("Missing the required parameter '_double' when calling testEndpointParameters"); + } + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter === undefined || patternWithoutDelimiter === null) { + throw new Error("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); + } + // verify the required parameter '_byte' is set + if (_byte === undefined || _byte === null) { + throw new Error("Missing the required parameter '_byte' when calling testEndpointParameters"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + 'integer': opts['integer'], + 'int32': opts['int32'], + 'int64': opts['int64'], + 'number': number, + 'float': opts['_float'], + 'double': _double, + 'string': opts['string'], + 'pattern_without_delimiter': patternWithoutDelimiter, + 'byte': _byte, + 'binary': opts['binary'], + 'date': opts['date'], + 'dateTime': opts['dateTime'], + 'password': opts['password'], + 'callback': opts['callback'] + }; + + let authNames = ['http_basic_test']; + let contentTypes = ['application/x-www-form-urlencoded']; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * To test enum parameters + * To test enum parameters + * @param {Object} opts Optional parameters + * @param {Array.} opts.enumHeaderStringArray Header parameter enum test (string array) + * @param {module:model/String} opts.enumHeaderString Header parameter enum test (string) (default to '-efg') + * @param {Array.} opts.enumQueryStringArray Query parameter enum test (string array) + * @param {module:model/String} opts.enumQueryString Query parameter enum test (string) (default to '-efg') + * @param {module:model/Number} opts.enumQueryInteger Query parameter enum test (double) + * @param {module:model/Number} opts.enumQueryDouble Query parameter enum test (double) + * @param {Array.} opts.enumQueryModelArray + * @param {Array.} opts.enumFormStringArray Form parameter enum test (string array) (default to '$') + * @param {module:model/String} opts.enumFormString Form parameter enum test (string) (default to '-efg') + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testEnumParameters(opts, requestInit) { + opts = opts || {}; + let postBody = null; + + let pathParams = { + }; + let queryParams = { + 'enum_query_string_array': this.buildCollectionParam(opts['enumQueryStringArray'], 'multi'), + 'enum_query_string': opts['enumQueryString'], + 'enum_query_integer': opts['enumQueryInteger'], + 'enum_query_double': opts['enumQueryDouble'], + 'enum_query_model_array': this.buildCollectionParam(opts['enumQueryModelArray'], 'multi') + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + 'enum_header_string_array': opts['enumHeaderStringArray'], + 'enum_header_string': opts['enumHeaderString'] + }; + let formParams = { + 'enum_form_string_array': this.buildCollectionParam(opts['enumFormStringArray'], 'csv'), + 'enum_form_string': opts['enumFormString'] + }; + + let authNames = []; + let contentTypes = ['application/x-www-form-urlencoded']; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * Fake endpoint to test group parameters (optional) + * Fake endpoint to test group parameters (optional) + * @param {Number} requiredStringGroup Required String in group parameters + * @param {Boolean} requiredBooleanGroup Required Boolean in group parameters + * @param {Number} requiredInt64Group Required Integer in group parameters + * @param {Object} opts Optional parameters + * @param {Number} opts.stringGroup String in group parameters + * @param {Boolean} opts.booleanGroup Boolean in group parameters + * @param {Number} opts.int64Group Integer in group parameters + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, opts, requestInit) { + opts = opts || {}; + let postBody = null; + // verify the required parameter 'requiredStringGroup' is set + if (requiredStringGroup === undefined || requiredStringGroup === null) { + throw new Error("Missing the required parameter 'requiredStringGroup' when calling testGroupParameters"); + } + // verify the required parameter 'requiredBooleanGroup' is set + if (requiredBooleanGroup === undefined || requiredBooleanGroup === null) { + throw new Error("Missing the required parameter 'requiredBooleanGroup' when calling testGroupParameters"); + } + // verify the required parameter 'requiredInt64Group' is set + if (requiredInt64Group === undefined || requiredInt64Group === null) { + throw new Error("Missing the required parameter 'requiredInt64Group' when calling testGroupParameters"); + } + + let pathParams = { + }; + let queryParams = { + 'required_string_group': requiredStringGroup, + 'required_int64_group': requiredInt64Group, + 'string_group': opts['stringGroup'], + 'int64_group': opts['int64Group'] + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + 'required_boolean_group': requiredBooleanGroup, + 'boolean_group': opts['booleanGroup'] + }; + let formParams = { + }; + + let authNames = ['bearer_test']; + let contentTypes = []; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake', 'DELETE', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * test inline additionalProperties + * + * @param {Object.} requestBody request body + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testInlineAdditionalProperties(requestBody, requestInit) { + let postBody = requestBody; + // verify the required parameter 'requestBody' is set + if (requestBody === undefined || requestBody === null) { + throw new Error("Missing the required parameter 'requestBody' when calling testInlineAdditionalProperties"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake/inline-additionalProperties', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * test json serialization of form data + * + * @param {String} param field1 + * @param {String} param2 field2 + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testJsonFormData(param, param2, requestInit) { + let postBody = null; + // verify the required parameter 'param' is set + if (param === undefined || param === null) { + throw new Error("Missing the required parameter 'param' when calling testJsonFormData"); + } + // verify the required parameter 'param2' is set + if (param2 === undefined || param2 === null) { + throw new Error("Missing the required parameter 'param2' when calling testJsonFormData"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + 'param': param, + 'param2': param2 + }; + + let authNames = []; + let contentTypes = ['application/x-www-form-urlencoded']; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake/jsonFormData', 'GET', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * To test the collection format in query parameters + * @param {Array.} pipe + * @param {Array.} ioutil + * @param {Array.} http + * @param {Array.} url + * @param {Array.} context + * @param {String} allowEmpty + * @param {Object} opts Optional parameters + * @param {Object.} opts.language + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, allowEmpty, opts, requestInit) { + opts = opts || {}; + let postBody = null; + // verify the required parameter 'pipe' is set + if (pipe === undefined || pipe === null) { + throw new Error("Missing the required parameter 'pipe' when calling testQueryParameterCollectionFormat"); + } + // verify the required parameter 'ioutil' is set + if (ioutil === undefined || ioutil === null) { + throw new Error("Missing the required parameter 'ioutil' when calling testQueryParameterCollectionFormat"); + } + // verify the required parameter 'http' is set + if (http === undefined || http === null) { + throw new Error("Missing the required parameter 'http' when calling testQueryParameterCollectionFormat"); + } + // verify the required parameter 'url' is set + if (url === undefined || url === null) { + throw new Error("Missing the required parameter 'url' when calling testQueryParameterCollectionFormat"); + } + // verify the required parameter 'context' is set + if (context === undefined || context === null) { + throw new Error("Missing the required parameter 'context' when calling testQueryParameterCollectionFormat"); + } + // verify the required parameter 'allowEmpty' is set + if (allowEmpty === undefined || allowEmpty === null) { + throw new Error("Missing the required parameter 'allowEmpty' when calling testQueryParameterCollectionFormat"); + } + + let pathParams = { + }; + let queryParams = { + 'pipe': this.buildCollectionParam(pipe, 'pipes'), + 'ioutil': this.buildCollectionParam(ioutil, 'csv'), + 'http': this.buildCollectionParam(http, 'ssv'), + 'url': this.buildCollectionParam(url, 'csv'), + 'context': this.buildCollectionParam(context, 'multi'), + 'language': opts['language'], + 'allowEmpty': allowEmpty + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = []; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake/test-query-parameters', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + +} diff --git a/samples/client/petstore/javascript-apollo/src/api/FakeClassnameTags123Api.js b/samples/client/petstore/javascript-apollo/src/api/FakeClassnameTags123Api.js new file mode 100644 index 0000000000..f8bb2acbe2 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/api/FakeClassnameTags123Api.js @@ -0,0 +1,73 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + + + +import ApiClient from "../ApiClient"; +import Client from '../model/Client'; + +/** +* FakeClassnameTags123 service. +* @module api/FakeClassnameTags123Api +* @version 1.0.0 +*/ +export default class FakeClassnameTags123Api extends ApiClient { + + /** + * Constructs a new FakeClassnameTags123Api. + * @alias module:api/FakeClassnameTags123Api + * @class + */ + constructor(baseURL = 'http://petstore.swagger.io:80/v2') { + super(baseURL); + } + + + /** + * To test class name in snake case + * To test class name in snake case + * @param {module:model/Client} client client model + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testClassname(client, requestInit) { + let postBody = client; + // verify the required parameter 'client' is set + if (client === undefined || client === null) { + throw new Error("Missing the required parameter 'client' when calling testClassname"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = ['api_key_query']; + let contentTypes = ['application/json']; + let accepts = ['application/json']; + let returnType = Client; + + return this.callApi( + '/fake_classname_test', 'PATCH', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + +} diff --git a/samples/client/petstore/javascript-apollo/src/api/PetApi.js b/samples/client/petstore/javascript-apollo/src/api/PetApi.js index 916a6f72fd..d1e65785eb 100644 --- a/samples/client/petstore/javascript-apollo/src/api/PetApi.js +++ b/samples/client/petstore/javascript-apollo/src/api/PetApi.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -29,22 +29,24 @@ export default class PetApi extends ApiClient { * @alias module:api/PetApi * @class */ - constructor() { - super(); - this.baseURL = null; + constructor(baseURL = 'http://petstore.swagger.io:80/v2') { + super(baseURL); } /** * Add a new pet to the store - * @param {Pet} body Pet object that needs to be added to the store + * + * @param {module:model/Pet} pet Pet object that needs to be added to the store + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async addPet(body) { - let postBody = body; - // verify the required parameter 'body' is set - if (body === undefined || body === null) { - throw new Error("Missing the required parameter 'body' when calling addPet"); + async addPet(pet, opts, requestInit) { + opts = opts || {}; + let postBody = pet; + // verify the required parameter 'pet' is set + if (pet === undefined || pet === null) { + throw new Error("Missing the required parameter 'pet' when calling addPet"); } let pathParams = { @@ -52,6 +54,7 @@ export default class PetApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -60,22 +63,33 @@ export default class PetApi extends ApiClient { let contentTypes = ['application/json', 'application/xml']; let accepts = []; let returnType = null; + let basePaths = ['http://petstore.swagger.io/v2', 'http://path-server-test.petstore.local/v2']; + let basePath = basePaths[0]; // by default use the first one in "servers" defined in OpenAPI + if (typeof opts['_base_path_index'] !== 'undefined') { + if (opts['_base_path_index'] >= basePaths.length || opts['_base_path_index'] < 0) { + throw new Error("Invalid index " + opts['_base_path_index'] + " when selecting the host settings. Must be less than " + basePaths.length); + } + basePath = basePaths[opts['_base_path_index']]; + } + return this.callApi( '/pet', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Deletes a pet + * * @param {Number} petId Pet id to delete * @param {Object} opts Optional parameters * @param {String} opts.apiKey + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async deletePet(petId, opts) { + async deletePet(petId, opts, requestInit) { opts = opts || {}; let postBody = null; // verify the required parameter 'petId' is set @@ -89,6 +103,7 @@ export default class PetApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', 'api_key': opts['apiKey'] }; let formParams = { @@ -102,17 +117,18 @@ export default class PetApi extends ApiClient { return this.callApi( '/pet/{petId}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings - * @param {Array.} status Status values that need to be considered for filter - * @return {Promise>} + * @param {Array.} status Status values that need to be considered for filter + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise>} */ - async findPetsByStatus(status) { + async findPetsByStatus(status, requestInit) { let postBody = null; // verify the required parameter 'status' is set if (status === undefined || status === null) { @@ -125,6 +141,7 @@ export default class PetApi extends ApiClient { 'status': this.buildCollectionParam(status, 'csv') }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -137,7 +154,7 @@ export default class PetApi extends ApiClient { return this.callApi( '/pet/findByStatus', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } @@ -145,9 +162,10 @@ export default class PetApi extends ApiClient { * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param {Array.} tags Tags to filter by - * @return {Promise>} + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise>} */ - async findPetsByTags(tags) { + async findPetsByTags(tags, requestInit) { let postBody = null; // verify the required parameter 'tags' is set if (tags === undefined || tags === null) { @@ -160,6 +178,7 @@ export default class PetApi extends ApiClient { 'tags': this.buildCollectionParam(tags, 'csv') }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -172,7 +191,7 @@ export default class PetApi extends ApiClient { return this.callApi( '/pet/findByTags', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } @@ -180,9 +199,10 @@ export default class PetApi extends ApiClient { * Find pet by ID * Returns a single pet * @param {Number} petId ID of pet to return - * @return {Promise} + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} */ - async getPetById(petId) { + async getPetById(petId, requestInit) { let postBody = null; // verify the required parameter 'petId' is set if (petId === undefined || petId === null) { @@ -195,6 +215,7 @@ export default class PetApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -207,20 +228,23 @@ export default class PetApi extends ApiClient { return this.callApi( '/pet/{petId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Update an existing pet - * @param {Pet} body Pet object that needs to be added to the store + * + * @param {module:model/Pet} pet Pet object that needs to be added to the store + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async updatePet(body) { - let postBody = body; - // verify the required parameter 'body' is set - if (body === undefined || body === null) { - throw new Error("Missing the required parameter 'body' when calling updatePet"); + async updatePet(pet, opts, requestInit) { + opts = opts || {}; + let postBody = pet; + // verify the required parameter 'pet' is set + if (pet === undefined || pet === null) { + throw new Error("Missing the required parameter 'pet' when calling updatePet"); } let pathParams = { @@ -228,6 +252,7 @@ export default class PetApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -236,23 +261,34 @@ export default class PetApi extends ApiClient { let contentTypes = ['application/json', 'application/xml']; let accepts = []; let returnType = null; + let basePaths = ['http://petstore.swagger.io/v2', 'http://path-server-test.petstore.local/v2']; + let basePath = basePaths[0]; // by default use the first one in "servers" defined in OpenAPI + if (typeof opts['_base_path_index'] !== 'undefined') { + if (opts['_base_path_index'] >= basePaths.length || opts['_base_path_index'] < 0) { + throw new Error("Invalid index " + opts['_base_path_index'] + " when selecting the host settings. Must be less than " + basePaths.length); + } + basePath = basePaths[opts['_base_path_index']]; + } + return this.callApi( '/pet', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Updates a pet in the store with form data + * * @param {Number} petId ID of pet that needs to be updated * @param {Object} opts Optional parameters * @param {String} opts.name Updated name of the pet * @param {String} opts.status Updated status of the pet + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async updatePetWithForm(petId, opts) { + async updatePetWithForm(petId, opts, requestInit) { opts = opts || {}; let postBody = null; // verify the required parameter 'petId' is set @@ -266,6 +302,7 @@ export default class PetApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { 'name': opts['name'], @@ -280,19 +317,21 @@ export default class PetApi extends ApiClient { return this.callApi( '/pet/{petId}', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * uploads an image + * * @param {Number} petId ID of pet to update * @param {Object} opts Optional parameters * @param {String} opts.additionalMetadata Additional data to pass to server * @param {File} opts.file file to upload - * @return {Promise} + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} */ - async uploadFile(petId, opts) { + async uploadFile(petId, opts, requestInit) { opts = opts || {}; let postBody = null; // verify the required parameter 'petId' is set @@ -306,6 +345,7 @@ export default class PetApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { 'additionalMetadata': opts['additionalMetadata'], @@ -320,7 +360,54 @@ export default class PetApi extends ApiClient { return this.callApi( '/pet/{petId}/uploadImage', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit + ); + } + + /** + * uploads an image (required) + * + * @param {Number} petId ID of pet to update + * @param {File} requiredFile file to upload + * @param {Object} opts Optional parameters + * @param {String} opts.additionalMetadata Additional data to pass to server + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async uploadFileWithRequiredFile(petId, requiredFile, opts, requestInit) { + opts = opts || {}; + let postBody = null; + // verify the required parameter 'petId' is set + if (petId === undefined || petId === null) { + throw new Error("Missing the required parameter 'petId' when calling uploadFileWithRequiredFile"); + } + // verify the required parameter 'requiredFile' is set + if (requiredFile === undefined || requiredFile === null) { + throw new Error("Missing the required parameter 'requiredFile' when calling uploadFileWithRequiredFile"); + } + + let pathParams = { + 'petId': petId + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + 'additionalMetadata': opts['additionalMetadata'], + 'requiredFile': requiredFile + }; + + let authNames = ['petstore_auth']; + let contentTypes = ['multipart/form-data']; + let accepts = ['application/json']; + let returnType = ApiResponse; + + return this.callApi( + '/fake/{petId}/uploadImageWithRequiredFile', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit ); } diff --git a/samples/client/petstore/javascript-apollo/src/api/StoreApi.js b/samples/client/petstore/javascript-apollo/src/api/StoreApi.js index f39c063e6c..96c269f27a 100644 --- a/samples/client/petstore/javascript-apollo/src/api/StoreApi.js +++ b/samples/client/petstore/javascript-apollo/src/api/StoreApi.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -28,9 +28,8 @@ export default class StoreApi extends ApiClient { * @alias module:api/StoreApi * @class */ - constructor() { - super(); - this.baseURL = null; + constructor(baseURL = 'http://petstore.swagger.io:80/v2') { + super(baseURL); } @@ -38,9 +37,10 @@ export default class StoreApi extends ApiClient { * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param {String} orderId ID of the order that needs to be deleted + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async deleteOrder(orderId) { + async deleteOrder(orderId, requestInit) { let postBody = null; // verify the required parameter 'orderId' is set if (orderId === undefined || orderId === null) { @@ -48,11 +48,12 @@ export default class StoreApi extends ApiClient { } let pathParams = { - 'orderId': orderId + 'order_id': orderId }; let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -63,18 +64,19 @@ export default class StoreApi extends ApiClient { let returnType = null; return this.callApi( - '/store/order/{orderId}', 'DELETE', + '/store/order/{order_id}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Returns pet inventories by status * Returns a map of status codes to quantities + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise>} */ - async getInventory() { + async getInventory(requestInit) { let postBody = null; let pathParams = { @@ -82,6 +84,7 @@ export default class StoreApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -94,7 +97,7 @@ export default class StoreApi extends ApiClient { return this.callApi( '/store/inventory', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } @@ -102,9 +105,10 @@ export default class StoreApi extends ApiClient { * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param {Number} orderId ID of pet that needs to be fetched - * @return {Promise} + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} */ - async getOrderById(orderId) { + async getOrderById(orderId, requestInit) { let postBody = null; // verify the required parameter 'orderId' is set if (orderId === undefined || orderId === null) { @@ -112,11 +116,12 @@ export default class StoreApi extends ApiClient { } let pathParams = { - 'orderId': orderId + 'order_id': orderId }; let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -127,22 +132,24 @@ export default class StoreApi extends ApiClient { let returnType = Order; return this.callApi( - '/store/order/{orderId}', 'GET', + '/store/order/{order_id}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Place an order for a pet - * @param {Order} body order placed for purchasing the pet - * @return {Promise} + * + * @param {module:model/Order} order order placed for purchasing the pet + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} */ - async placeOrder(body) { - let postBody = body; - // verify the required parameter 'body' is set - if (body === undefined || body === null) { - throw new Error("Missing the required parameter 'body' when calling placeOrder"); + async placeOrder(order, requestInit) { + let postBody = order; + // verify the required parameter 'order' is set + if (order === undefined || order === null) { + throw new Error("Missing the required parameter 'order' when calling placeOrder"); } let pathParams = { @@ -150,19 +157,20 @@ export default class StoreApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; let authNames = []; - let contentTypes = []; + let contentTypes = ['application/json']; let accepts = ['application/xml', 'application/json']; let returnType = Order; return this.callApi( '/store/order', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } diff --git a/samples/client/petstore/javascript-apollo/src/api/UserApi.js b/samples/client/petstore/javascript-apollo/src/api/UserApi.js index 9d8c47b9e0..36071c4a78 100644 --- a/samples/client/petstore/javascript-apollo/src/api/UserApi.js +++ b/samples/client/petstore/javascript-apollo/src/api/UserApi.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -28,23 +28,23 @@ export default class UserApi extends ApiClient { * @alias module:api/UserApi * @class */ - constructor() { - super(); - this.baseURL = null; + constructor(baseURL = 'http://petstore.swagger.io:80/v2') { + super(baseURL); } /** * Create user * This can only be done by the logged in user. - * @param {User} body Created user object + * @param {module:model/User} user Created user object + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async createUser(body) { - let postBody = body; - // verify the required parameter 'body' is set - if (body === undefined || body === null) { - throw new Error("Missing the required parameter 'body' when calling createUser"); + async createUser(user, requestInit) { + let postBody = user; + // verify the required parameter 'user' is set + if (user === undefined || user === null) { + throw new Error("Missing the required parameter 'user' when calling createUser"); } let pathParams = { @@ -52,32 +52,35 @@ export default class UserApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; let authNames = []; - let contentTypes = []; + let contentTypes = ['application/json']; let accepts = []; let returnType = null; return this.callApi( '/user', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Creates list of users with given input array - * @param {Array.} body List of user object + * + * @param {Array.} user List of user object + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async createUsersWithArrayInput(body) { - let postBody = body; - // verify the required parameter 'body' is set - if (body === undefined || body === null) { - throw new Error("Missing the required parameter 'body' when calling createUsersWithArrayInput"); + async createUsersWithArrayInput(user, requestInit) { + let postBody = user; + // verify the required parameter 'user' is set + if (user === undefined || user === null) { + throw new Error("Missing the required parameter 'user' when calling createUsersWithArrayInput"); } let pathParams = { @@ -85,32 +88,35 @@ export default class UserApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; let authNames = []; - let contentTypes = []; + let contentTypes = ['application/json']; let accepts = []; let returnType = null; return this.callApi( '/user/createWithArray', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Creates list of users with given input array - * @param {Array.} body List of user object + * + * @param {Array.} user List of user object + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async createUsersWithListInput(body) { - let postBody = body; - // verify the required parameter 'body' is set - if (body === undefined || body === null) { - throw new Error("Missing the required parameter 'body' when calling createUsersWithListInput"); + async createUsersWithListInput(user, requestInit) { + let postBody = user; + // verify the required parameter 'user' is set + if (user === undefined || user === null) { + throw new Error("Missing the required parameter 'user' when calling createUsersWithListInput"); } let pathParams = { @@ -118,19 +124,20 @@ export default class UserApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; let authNames = []; - let contentTypes = []; + let contentTypes = ['application/json']; let accepts = []; let returnType = null; return this.callApi( '/user/createWithList', 'POST', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } @@ -138,9 +145,10 @@ export default class UserApi extends ApiClient { * Delete user * This can only be done by the logged in user. * @param {String} username The name that needs to be deleted + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async deleteUser(username) { + async deleteUser(username, requestInit) { let postBody = null; // verify the required parameter 'username' is set if (username === undefined || username === null) { @@ -153,6 +161,7 @@ export default class UserApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -165,16 +174,18 @@ export default class UserApi extends ApiClient { return this.callApi( '/user/{username}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Get user by user name + * * @param {String} username The name that needs to be fetched. Use user1 for testing. - * @return {Promise} + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} */ - async getUserByName(username) { + async getUserByName(username, requestInit) { let postBody = null; // verify the required parameter 'username' is set if (username === undefined || username === null) { @@ -187,6 +198,7 @@ export default class UserApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -199,17 +211,19 @@ export default class UserApi extends ApiClient { return this.callApi( '/user/{username}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Logs user into the system + * * @param {String} username The user name for login * @param {String} password The password for login in clear text + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async loginUser(username, password) { + async loginUser(username, password, requestInit) { let postBody = null; // verify the required parameter 'username' is set if (username === undefined || username === null) { @@ -227,6 +241,7 @@ export default class UserApi extends ApiClient { 'password': password }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -239,15 +254,17 @@ export default class UserApi extends ApiClient { return this.callApi( '/user/login', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } /** * Logs out current logged in user session + * + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async logoutUser() { + async logoutUser(requestInit) { let postBody = null; let pathParams = { @@ -255,6 +272,7 @@ export default class UserApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; @@ -267,7 +285,7 @@ export default class UserApi extends ApiClient { return this.callApi( '/user/logout', 'GET', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } @@ -275,18 +293,19 @@ export default class UserApi extends ApiClient { * Updated user * This can only be done by the logged in user. * @param {String} username name that need to be deleted - * @param {User} body Updated user object + * @param {module:model/User} user Updated user object + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} * @return {Promise} */ - async updateUser(username, body) { - let postBody = body; + async updateUser(username, user, requestInit) { + let postBody = user; // verify the required parameter 'username' is set if (username === undefined || username === null) { throw new Error("Missing the required parameter 'username' when calling updateUser"); } - // verify the required parameter 'body' is set - if (body === undefined || body === null) { - throw new Error("Missing the required parameter 'body' when calling updateUser"); + // verify the required parameter 'user' is set + if (user === undefined || user === null) { + throw new Error("Missing the required parameter 'user' when calling updateUser"); } let pathParams = { @@ -295,19 +314,20 @@ export default class UserApi extends ApiClient { let queryParams = { }; let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', }; let formParams = { }; let authNames = []; - let contentTypes = []; + let contentTypes = ['application/json']; let accepts = []; let returnType = null; return this.callApi( '/user/{username}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, - authNames, contentTypes, accepts, returnType + authNames, contentTypes, accepts, returnType, requestInit ); } diff --git a/samples/client/petstore/javascript-apollo/src/index.js b/samples/client/petstore/javascript-apollo/src/index.js index 71e74a18ac..a95a17ec1b 100644 --- a/samples/client/petstore/javascript-apollo/src/index.js +++ b/samples/client/petstore/javascript-apollo/src/index.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -13,19 +13,69 @@ import ApiClient from './ApiClient'; +import AdditionalPropertiesClass from './model/AdditionalPropertiesClass'; +import Animal from './model/Animal'; import ApiResponse from './model/ApiResponse'; +import ArrayOfArrayOfNumberOnly from './model/ArrayOfArrayOfNumberOnly'; +import ArrayOfNumberOnly from './model/ArrayOfNumberOnly'; +import ArrayTest from './model/ArrayTest'; +import BasquePig from './model/BasquePig'; +import Capitalization from './model/Capitalization'; +import Cat from './model/Cat'; +import CatAllOf from './model/CatAllOf'; import Category from './model/Category'; +import ClassModel from './model/ClassModel'; +import Client from './model/Client'; +import Color from './model/Color'; +import DanishPig from './model/DanishPig'; +import DeprecatedObject from './model/DeprecatedObject'; +import Dog from './model/Dog'; +import DogAllOf from './model/DogAllOf'; +import EnumArrays from './model/EnumArrays'; +import EnumClass from './model/EnumClass'; +import EnumTest from './model/EnumTest'; +import File from './model/File'; +import FileSchemaTestClass from './model/FileSchemaTestClass'; +import Foo from './model/Foo'; +import FooGetDefaultResponse from './model/FooGetDefaultResponse'; +import FormatTest from './model/FormatTest'; +import HasOnlyReadOnly from './model/HasOnlyReadOnly'; +import HealthCheckResult from './model/HealthCheckResult'; +import List from './model/List'; +import MapTest from './model/MapTest'; +import MixedPropertiesAndAdditionalPropertiesClass from './model/MixedPropertiesAndAdditionalPropertiesClass'; +import Model200Response from './model/Model200Response'; +import Name from './model/Name'; +import NestedColor from './model/NestedColor'; +import NestedOneOf from './model/NestedOneOf'; +import NullableClass from './model/NullableClass'; +import NumberOnly from './model/NumberOnly'; +import ObjectWithDeprecatedFields from './model/ObjectWithDeprecatedFields'; import Order from './model/Order'; +import OuterComposite from './model/OuterComposite'; +import OuterEnum from './model/OuterEnum'; +import OuterEnumDefaultValue from './model/OuterEnumDefaultValue'; +import OuterEnumInteger from './model/OuterEnumInteger'; +import OuterEnumIntegerDefaultValue from './model/OuterEnumIntegerDefaultValue'; +import OuterObjectWithEnumProperty from './model/OuterObjectWithEnumProperty'; import Pet from './model/Pet'; +import Pig from './model/Pig'; +import ReadOnlyFirst from './model/ReadOnlyFirst'; +import Return from './model/Return'; +import SpecialModelName from './model/SpecialModelName'; import Tag from './model/Tag'; import User from './model/User'; +import AnotherFakeApi from './api/AnotherFakeApi'; +import DefaultApi from './api/DefaultApi'; +import FakeApi from './api/FakeApi'; +import FakeClassnameTags123Api from './api/FakeClassnameTags123Api'; import PetApi from './api/PetApi'; import StoreApi from './api/StoreApi'; import UserApi from './api/UserApi'; /** -* This_is_a_sample_server_Petstore_server__For_this_sample_you_can_use_the_api_key_special_key_to_test_the_authorization_filters_.
        +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\.
        * The index module provides access to constructors for all the classes which comprise the public API. *

        * An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: @@ -62,30 +112,306 @@ export { */ ApiClient, + /** + * The AdditionalPropertiesClass model constructor. + * @property {module:model/AdditionalPropertiesClass} + */ + AdditionalPropertiesClass, + + /** + * The Animal model constructor. + * @property {module:model/Animal} + */ + Animal, + /** * The ApiResponse model constructor. * @property {module:model/ApiResponse} */ ApiResponse, + /** + * The ArrayOfArrayOfNumberOnly model constructor. + * @property {module:model/ArrayOfArrayOfNumberOnly} + */ + ArrayOfArrayOfNumberOnly, + + /** + * The ArrayOfNumberOnly model constructor. + * @property {module:model/ArrayOfNumberOnly} + */ + ArrayOfNumberOnly, + + /** + * The ArrayTest model constructor. + * @property {module:model/ArrayTest} + */ + ArrayTest, + + /** + * The BasquePig model constructor. + * @property {module:model/BasquePig} + */ + BasquePig, + + /** + * The Capitalization model constructor. + * @property {module:model/Capitalization} + */ + Capitalization, + + /** + * The Cat model constructor. + * @property {module:model/Cat} + */ + Cat, + + /** + * The CatAllOf model constructor. + * @property {module:model/CatAllOf} + */ + CatAllOf, + /** * The Category model constructor. * @property {module:model/Category} */ Category, + /** + * The ClassModel model constructor. + * @property {module:model/ClassModel} + */ + ClassModel, + + /** + * The Client model constructor. + * @property {module:model/Client} + */ + Client, + + /** + * The Color model constructor. + * @property {module:model/Color} + */ + Color, + + /** + * The DanishPig model constructor. + * @property {module:model/DanishPig} + */ + DanishPig, + + /** + * The DeprecatedObject model constructor. + * @property {module:model/DeprecatedObject} + */ + DeprecatedObject, + + /** + * The Dog model constructor. + * @property {module:model/Dog} + */ + Dog, + + /** + * The DogAllOf model constructor. + * @property {module:model/DogAllOf} + */ + DogAllOf, + + /** + * The EnumArrays model constructor. + * @property {module:model/EnumArrays} + */ + EnumArrays, + + /** + * The EnumClass model constructor. + * @property {module:model/EnumClass} + */ + EnumClass, + + /** + * The EnumTest model constructor. + * @property {module:model/EnumTest} + */ + EnumTest, + + /** + * The File model constructor. + * @property {module:model/File} + */ + File, + + /** + * The FileSchemaTestClass model constructor. + * @property {module:model/FileSchemaTestClass} + */ + FileSchemaTestClass, + + /** + * The Foo model constructor. + * @property {module:model/Foo} + */ + Foo, + + /** + * The FooGetDefaultResponse model constructor. + * @property {module:model/FooGetDefaultResponse} + */ + FooGetDefaultResponse, + + /** + * The FormatTest model constructor. + * @property {module:model/FormatTest} + */ + FormatTest, + + /** + * The HasOnlyReadOnly model constructor. + * @property {module:model/HasOnlyReadOnly} + */ + HasOnlyReadOnly, + + /** + * The HealthCheckResult model constructor. + * @property {module:model/HealthCheckResult} + */ + HealthCheckResult, + + /** + * The List model constructor. + * @property {module:model/List} + */ + List, + + /** + * The MapTest model constructor. + * @property {module:model/MapTest} + */ + MapTest, + + /** + * The MixedPropertiesAndAdditionalPropertiesClass model constructor. + * @property {module:model/MixedPropertiesAndAdditionalPropertiesClass} + */ + MixedPropertiesAndAdditionalPropertiesClass, + + /** + * The Model200Response model constructor. + * @property {module:model/Model200Response} + */ + Model200Response, + + /** + * The Name model constructor. + * @property {module:model/Name} + */ + Name, + + /** + * The NestedColor model constructor. + * @property {module:model/NestedColor} + */ + NestedColor, + + /** + * The NestedOneOf model constructor. + * @property {module:model/NestedOneOf} + */ + NestedOneOf, + + /** + * The NullableClass model constructor. + * @property {module:model/NullableClass} + */ + NullableClass, + + /** + * The NumberOnly model constructor. + * @property {module:model/NumberOnly} + */ + NumberOnly, + + /** + * The ObjectWithDeprecatedFields model constructor. + * @property {module:model/ObjectWithDeprecatedFields} + */ + ObjectWithDeprecatedFields, + /** * The Order model constructor. * @property {module:model/Order} */ Order, + /** + * The OuterComposite model constructor. + * @property {module:model/OuterComposite} + */ + OuterComposite, + + /** + * The OuterEnum model constructor. + * @property {module:model/OuterEnum} + */ + OuterEnum, + + /** + * The OuterEnumDefaultValue model constructor. + * @property {module:model/OuterEnumDefaultValue} + */ + OuterEnumDefaultValue, + + /** + * The OuterEnumInteger model constructor. + * @property {module:model/OuterEnumInteger} + */ + OuterEnumInteger, + + /** + * The OuterEnumIntegerDefaultValue model constructor. + * @property {module:model/OuterEnumIntegerDefaultValue} + */ + OuterEnumIntegerDefaultValue, + + /** + * The OuterObjectWithEnumProperty model constructor. + * @property {module:model/OuterObjectWithEnumProperty} + */ + OuterObjectWithEnumProperty, + /** * The Pet model constructor. * @property {module:model/Pet} */ Pet, + /** + * The Pig model constructor. + * @property {module:model/Pig} + */ + Pig, + + /** + * The ReadOnlyFirst model constructor. + * @property {module:model/ReadOnlyFirst} + */ + ReadOnlyFirst, + + /** + * The Return model constructor. + * @property {module:model/Return} + */ + Return, + + /** + * The SpecialModelName model constructor. + * @property {module:model/SpecialModelName} + */ + SpecialModelName, + /** * The Tag model constructor. * @property {module:model/Tag} @@ -98,6 +424,30 @@ export { */ User, + /** + * The AnotherFakeApi service constructor. + * @property {module:api/AnotherFakeApi} + */ + AnotherFakeApi, + + /** + * The DefaultApi service constructor. + * @property {module:api/DefaultApi} + */ + DefaultApi, + + /** + * The FakeApi service constructor. + * @property {module:api/FakeApi} + */ + FakeApi, + + /** + * The FakeClassnameTags123Api service constructor. + * @property {module:api/FakeClassnameTags123Api} + */ + FakeClassnameTags123Api, + /** * The PetApi service constructor. * @property {module:api/PetApi} diff --git a/samples/client/petstore/javascript-apollo/src/model/AdditionalPropertiesClass.js b/samples/client/petstore/javascript-apollo/src/model/AdditionalPropertiesClass.js new file mode 100644 index 0000000000..3849c00c59 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/AdditionalPropertiesClass.js @@ -0,0 +1,91 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The AdditionalPropertiesClass model module. + * @module model/AdditionalPropertiesClass + * @version 1.0.0 + */ +class AdditionalPropertiesClass { + /** + * Constructs a new AdditionalPropertiesClass. + * @alias module:model/AdditionalPropertiesClass + */ + constructor() { + + AdditionalPropertiesClass.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a AdditionalPropertiesClass from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/AdditionalPropertiesClass} obj Optional instance to populate. + * @return {module:model/AdditionalPropertiesClass} The populated AdditionalPropertiesClass instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new AdditionalPropertiesClass(); + + if (data.hasOwnProperty('map_property')) { + obj['map_property'] = ApiClient.convertToType(data['map_property'], {'String': 'String'}); + } + if (data.hasOwnProperty('map_of_map_property')) { + obj['map_of_map_property'] = ApiClient.convertToType(data['map_of_map_property'], {'String': {'String': 'String'}}); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to AdditionalPropertiesClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to AdditionalPropertiesClass. + */ + static validateJSON(data) { + + return true; + } + + +} + + + +/** + * @member {Object.} map_property + */ +AdditionalPropertiesClass.prototype['map_property'] = undefined; + +/** + * @member {Object.>} map_of_map_property + */ +AdditionalPropertiesClass.prototype['map_of_map_property'] = undefined; + + + + + + +export default AdditionalPropertiesClass; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Animal.js b/samples/client/petstore/javascript-apollo/src/model/Animal.js new file mode 100644 index 0000000000..27c6975b59 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Animal.js @@ -0,0 +1,108 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Animal model module. + * @module model/Animal + * @version 1.0.0 + */ +class Animal { + /** + * Constructs a new Animal. + * @alias module:model/Animal + * @param className {String} + */ + constructor(className) { + + Animal.initialize(this, className); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, className) { + obj['className'] = className; + } + + /** + * Constructs a Animal from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Animal} obj Optional instance to populate. + * @return {module:model/Animal} The populated Animal instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new Animal(); + + if (data.hasOwnProperty('className')) { + obj['className'] = ApiClient.convertToType(data['className'], 'String'); + } + if (data.hasOwnProperty('color')) { + obj['color'] = ApiClient.convertToType(data['color'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to Animal. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Animal. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Animal.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['className'] && !(typeof data['className'] === 'string' || data['className'] instanceof String)) { + throw new Error("Expected the field `className` to be a primitive type in the JSON string but got " + data['className']); + } + // ensure the json data is a string + if (data['color'] && !(typeof data['color'] === 'string' || data['color'] instanceof String)) { + throw new Error("Expected the field `color` to be a primitive type in the JSON string but got " + data['color']); + } + + return true; + } + + +} + +Animal.RequiredProperties = ["className"]; + +/** + * @member {String} className + */ +Animal.prototype['className'] = undefined; + +/** + * @member {String} color + * @default 'red' + */ +Animal.prototype['color'] = 'red'; + + + + + + +export default Animal; + diff --git a/samples/client/petstore/javascript-apollo/src/model/ApiResponse.js b/samples/client/petstore/javascript-apollo/src/model/ApiResponse.js index 751a48aced..6db561122f 100644 --- a/samples/client/petstore/javascript-apollo/src/model/ApiResponse.js +++ b/samples/client/petstore/javascript-apollo/src/model/ApiResponse.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -19,27 +19,8 @@ import ApiClient from '../ApiClient'; * @version 1.0.0 */ class ApiResponse { - /** - * @member {Number} code - * @type {Number} - */ - code; - /** - * @member {String} type - * @type {String} - */ - type; - /** - * @member {String} message - * @type {String} - */ - message; - - - /** * Constructs a new ApiResponse. - * Describes the result of uploading an image resource * @alias module:model/ApiResponse */ constructor() { @@ -78,9 +59,49 @@ class ApiResponse { } return obj; } + + /** + * Validates the JSON data with respect to ApiResponse. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ApiResponse. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['type'] && !(typeof data['type'] === 'string' || data['type'] instanceof String)) { + throw new Error("Expected the field `type` to be a primitive type in the JSON string but got " + data['type']); + } + // ensure the json data is a string + if (data['message'] && !(typeof data['message'] === 'string' || data['message'] instanceof String)) { + throw new Error("Expected the field `message` to be a primitive type in the JSON string but got " + data['message']); + } + + return true; + } + + } +/** + * @member {Number} code + */ +ApiResponse.prototype['code'] = undefined; + +/** + * @member {String} type + */ +ApiResponse.prototype['type'] = undefined; + +/** + * @member {String} message + */ +ApiResponse.prototype['message'] = undefined; + + + + + + export default ApiResponse; diff --git a/samples/client/petstore/javascript-apollo/src/model/ArrayOfArrayOfNumberOnly.js b/samples/client/petstore/javascript-apollo/src/model/ArrayOfArrayOfNumberOnly.js new file mode 100644 index 0000000000..461c6b5b35 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/ArrayOfArrayOfNumberOnly.js @@ -0,0 +1,87 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The ArrayOfArrayOfNumberOnly model module. + * @module model/ArrayOfArrayOfNumberOnly + * @version 1.0.0 + */ +class ArrayOfArrayOfNumberOnly { + /** + * Constructs a new ArrayOfArrayOfNumberOnly. + * @alias module:model/ArrayOfArrayOfNumberOnly + */ + constructor() { + + ArrayOfArrayOfNumberOnly.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a ArrayOfArrayOfNumberOnly from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ArrayOfArrayOfNumberOnly} obj Optional instance to populate. + * @return {module:model/ArrayOfArrayOfNumberOnly} The populated ArrayOfArrayOfNumberOnly instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new ArrayOfArrayOfNumberOnly(); + + if (data.hasOwnProperty('ArrayArrayNumber')) { + obj['ArrayArrayNumber'] = ApiClient.convertToType(data['ArrayArrayNumber'], [['Number']]); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to ArrayOfArrayOfNumberOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ArrayOfArrayOfNumberOnly. + */ + static validateJSON(data) { + // ensure the json data is an array + if (!Array.isArray(data['ArrayArrayNumber'])) { + throw new Error("Expected the field `ArrayArrayNumber` to be an array in the JSON data but got " + data['ArrayArrayNumber']); + } + + return true; + } + + +} + + + +/** + * @member {Array.>} ArrayArrayNumber + */ +ArrayOfArrayOfNumberOnly.prototype['ArrayArrayNumber'] = undefined; + + + + + + +export default ArrayOfArrayOfNumberOnly; + diff --git a/samples/client/petstore/javascript-apollo/src/model/ArrayOfNumberOnly.js b/samples/client/petstore/javascript-apollo/src/model/ArrayOfNumberOnly.js new file mode 100644 index 0000000000..4c2513c107 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/ArrayOfNumberOnly.js @@ -0,0 +1,87 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The ArrayOfNumberOnly model module. + * @module model/ArrayOfNumberOnly + * @version 1.0.0 + */ +class ArrayOfNumberOnly { + /** + * Constructs a new ArrayOfNumberOnly. + * @alias module:model/ArrayOfNumberOnly + */ + constructor() { + + ArrayOfNumberOnly.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a ArrayOfNumberOnly from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ArrayOfNumberOnly} obj Optional instance to populate. + * @return {module:model/ArrayOfNumberOnly} The populated ArrayOfNumberOnly instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new ArrayOfNumberOnly(); + + if (data.hasOwnProperty('ArrayNumber')) { + obj['ArrayNumber'] = ApiClient.convertToType(data['ArrayNumber'], ['Number']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to ArrayOfNumberOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ArrayOfNumberOnly. + */ + static validateJSON(data) { + // ensure the json data is an array + if (!Array.isArray(data['ArrayNumber'])) { + throw new Error("Expected the field `ArrayNumber` to be an array in the JSON data but got " + data['ArrayNumber']); + } + + return true; + } + + +} + + + +/** + * @member {Array.} ArrayNumber + */ +ArrayOfNumberOnly.prototype['ArrayNumber'] = undefined; + + + + + + +export default ArrayOfNumberOnly; + diff --git a/samples/client/petstore/javascript-apollo/src/model/ArrayTest.js b/samples/client/petstore/javascript-apollo/src/model/ArrayTest.js new file mode 100644 index 0000000000..3fc3c9b7f9 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/ArrayTest.js @@ -0,0 +1,112 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import ReadOnlyFirst from './ReadOnlyFirst'; + +/** + * The ArrayTest model module. + * @module model/ArrayTest + * @version 1.0.0 + */ +class ArrayTest { + /** + * Constructs a new ArrayTest. + * @alias module:model/ArrayTest + */ + constructor() { + + ArrayTest.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a ArrayTest from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ArrayTest} obj Optional instance to populate. + * @return {module:model/ArrayTest} The populated ArrayTest instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new ArrayTest(); + + if (data.hasOwnProperty('array_of_string')) { + obj['array_of_string'] = ApiClient.convertToType(data['array_of_string'], ['String']); + } + if (data.hasOwnProperty('array_array_of_integer')) { + obj['array_array_of_integer'] = ApiClient.convertToType(data['array_array_of_integer'], [['Number']]); + } + if (data.hasOwnProperty('array_array_of_model')) { + obj['array_array_of_model'] = ApiClient.convertToType(data['array_array_of_model'], [[ReadOnlyFirst]]); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to ArrayTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ArrayTest. + */ + static validateJSON(data) { + // ensure the json data is an array + if (!Array.isArray(data['array_of_string'])) { + throw new Error("Expected the field `array_of_string` to be an array in the JSON data but got " + data['array_of_string']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_array_of_integer'])) { + throw new Error("Expected the field `array_array_of_integer` to be an array in the JSON data but got " + data['array_array_of_integer']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_array_of_model'])) { + throw new Error("Expected the field `array_array_of_model` to be an array in the JSON data but got " + data['array_array_of_model']); + } + + return true; + } + + +} + + + +/** + * @member {Array.} array_of_string + */ +ArrayTest.prototype['array_of_string'] = undefined; + +/** + * @member {Array.>} array_array_of_integer + */ +ArrayTest.prototype['array_array_of_integer'] = undefined; + +/** + * @member {Array.>} array_array_of_model + */ +ArrayTest.prototype['array_array_of_model'] = undefined; + + + + + + +export default ArrayTest; + diff --git a/samples/client/petstore/javascript-apollo/src/model/BasquePig.js b/samples/client/petstore/javascript-apollo/src/model/BasquePig.js new file mode 100644 index 0000000000..dc26c47c4f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/BasquePig.js @@ -0,0 +1,109 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The BasquePig model module. + * @module model/BasquePig + * @version 1.0.0 + */ +class BasquePig { + /** + * Constructs a new BasquePig. + * @alias module:model/BasquePig + * @param className {String} + * @param color {String} + */ + constructor(className, color) { + + BasquePig.initialize(this, className, color); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, className, color) { + obj['className'] = className; + obj['color'] = color; + } + + /** + * Constructs a BasquePig from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/BasquePig} obj Optional instance to populate. + * @return {module:model/BasquePig} The populated BasquePig instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new BasquePig(); + + if (data.hasOwnProperty('className')) { + obj['className'] = ApiClient.convertToType(data['className'], 'String'); + } + if (data.hasOwnProperty('color')) { + obj['color'] = ApiClient.convertToType(data['color'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to BasquePig. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to BasquePig. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of BasquePig.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['className'] && !(typeof data['className'] === 'string' || data['className'] instanceof String)) { + throw new Error("Expected the field `className` to be a primitive type in the JSON string but got " + data['className']); + } + // ensure the json data is a string + if (data['color'] && !(typeof data['color'] === 'string' || data['color'] instanceof String)) { + throw new Error("Expected the field `color` to be a primitive type in the JSON string but got " + data['color']); + } + + return true; + } + + +} + +BasquePig.RequiredProperties = ["className", "color"]; + +/** + * @member {String} className + */ +BasquePig.prototype['className'] = undefined; + +/** + * @member {String} color + */ +BasquePig.prototype['color'] = undefined; + + + + + + +export default BasquePig; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Capitalization.js b/samples/client/petstore/javascript-apollo/src/model/Capitalization.js new file mode 100644 index 0000000000..cf4ef4348a --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Capitalization.js @@ -0,0 +1,148 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Capitalization model module. + * @module model/Capitalization + * @version 1.0.0 + */ +class Capitalization { + /** + * Constructs a new Capitalization. + * @alias module:model/Capitalization + */ + constructor() { + + Capitalization.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a Capitalization from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Capitalization} obj Optional instance to populate. + * @return {module:model/Capitalization} The populated Capitalization instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new Capitalization(); + + if (data.hasOwnProperty('smallCamel')) { + obj['smallCamel'] = ApiClient.convertToType(data['smallCamel'], 'String'); + } + if (data.hasOwnProperty('CapitalCamel')) { + obj['CapitalCamel'] = ApiClient.convertToType(data['CapitalCamel'], 'String'); + } + if (data.hasOwnProperty('small_Snake')) { + obj['small_Snake'] = ApiClient.convertToType(data['small_Snake'], 'String'); + } + if (data.hasOwnProperty('Capital_Snake')) { + obj['Capital_Snake'] = ApiClient.convertToType(data['Capital_Snake'], 'String'); + } + if (data.hasOwnProperty('SCA_ETH_Flow_Points')) { + obj['SCA_ETH_Flow_Points'] = ApiClient.convertToType(data['SCA_ETH_Flow_Points'], 'String'); + } + if (data.hasOwnProperty('ATT_NAME')) { + obj['ATT_NAME'] = ApiClient.convertToType(data['ATT_NAME'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to Capitalization. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Capitalization. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['smallCamel'] && !(typeof data['smallCamel'] === 'string' || data['smallCamel'] instanceof String)) { + throw new Error("Expected the field `smallCamel` to be a primitive type in the JSON string but got " + data['smallCamel']); + } + // ensure the json data is a string + if (data['CapitalCamel'] && !(typeof data['CapitalCamel'] === 'string' || data['CapitalCamel'] instanceof String)) { + throw new Error("Expected the field `CapitalCamel` to be a primitive type in the JSON string but got " + data['CapitalCamel']); + } + // ensure the json data is a string + if (data['small_Snake'] && !(typeof data['small_Snake'] === 'string' || data['small_Snake'] instanceof String)) { + throw new Error("Expected the field `small_Snake` to be a primitive type in the JSON string but got " + data['small_Snake']); + } + // ensure the json data is a string + if (data['Capital_Snake'] && !(typeof data['Capital_Snake'] === 'string' || data['Capital_Snake'] instanceof String)) { + throw new Error("Expected the field `Capital_Snake` to be a primitive type in the JSON string but got " + data['Capital_Snake']); + } + // ensure the json data is a string + if (data['SCA_ETH_Flow_Points'] && !(typeof data['SCA_ETH_Flow_Points'] === 'string' || data['SCA_ETH_Flow_Points'] instanceof String)) { + throw new Error("Expected the field `SCA_ETH_Flow_Points` to be a primitive type in the JSON string but got " + data['SCA_ETH_Flow_Points']); + } + // ensure the json data is a string + if (data['ATT_NAME'] && !(typeof data['ATT_NAME'] === 'string' || data['ATT_NAME'] instanceof String)) { + throw new Error("Expected the field `ATT_NAME` to be a primitive type in the JSON string but got " + data['ATT_NAME']); + } + + return true; + } + + +} + + + +/** + * @member {String} smallCamel + */ +Capitalization.prototype['smallCamel'] = undefined; + +/** + * @member {String} CapitalCamel + */ +Capitalization.prototype['CapitalCamel'] = undefined; + +/** + * @member {String} small_Snake + */ +Capitalization.prototype['small_Snake'] = undefined; + +/** + * @member {String} Capital_Snake + */ +Capitalization.prototype['Capital_Snake'] = undefined; + +/** + * @member {String} SCA_ETH_Flow_Points + */ +Capitalization.prototype['SCA_ETH_Flow_Points'] = undefined; + +/** + * Name of the pet + * @member {String} ATT_NAME + */ +Capitalization.prototype['ATT_NAME'] = undefined; + + + + + + +export default Capitalization; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Cat.js b/samples/client/petstore/javascript-apollo/src/model/Cat.js new file mode 100644 index 0000000000..203a652cfc --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Cat.js @@ -0,0 +1,113 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Animal from './Animal'; +import CatAllOf from './CatAllOf'; + +/** + * The Cat model module. + * @module model/Cat + * @version 1.0.0 + */ +class Cat { + /** + * Constructs a new Cat. + * @alias module:model/Cat + * @extends module:model/Animal + * @implements module:model/Animal + * @implements module:model/CatAllOf + * @param className {String} + */ + constructor(className) { + Animal.initialize(this, className);CatAllOf.initialize(this); + Cat.initialize(this, className); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, className) { + } + + /** + * Constructs a Cat from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Cat} obj Optional instance to populate. + * @return {module:model/Cat} The populated Cat instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new Cat(); + Animal.constructFromObject(data, obj); + Animal.constructFromObject(data, obj); + CatAllOf.constructFromObject(data, obj); + + if (data.hasOwnProperty('declawed')) { + obj['declawed'] = ApiClient.convertToType(data['declawed'], 'Boolean'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to Cat. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Cat. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Cat.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + + return true; + } + + +} + +Cat.RequiredProperties = ["className"]; + +/** + * @member {Boolean} declawed + */ +Cat.prototype['declawed'] = undefined; + + +// Implement Animal interface: +/** + * @member {String} className + */ +Animal.prototype['className'] = undefined; +/** + * @member {String} color + * @default 'red' + */ +Animal.prototype['color'] = 'red'; +// Implement CatAllOf interface: +/** + * @member {Boolean} declawed + */ +CatAllOf.prototype['declawed'] = undefined; + + + + +export default Cat; + diff --git a/samples/client/petstore/javascript-apollo/src/model/CatAllOf.js b/samples/client/petstore/javascript-apollo/src/model/CatAllOf.js new file mode 100644 index 0000000000..8c0d5bfbbd --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/CatAllOf.js @@ -0,0 +1,83 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The CatAllOf model module. + * @module model/CatAllOf + * @version 1.0.0 + */ +class CatAllOf { + /** + * Constructs a new CatAllOf. + * @alias module:model/CatAllOf + */ + constructor() { + + CatAllOf.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a CatAllOf from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/CatAllOf} obj Optional instance to populate. + * @return {module:model/CatAllOf} The populated CatAllOf instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new CatAllOf(); + + if (data.hasOwnProperty('declawed')) { + obj['declawed'] = ApiClient.convertToType(data['declawed'], 'Boolean'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to CatAllOf. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to CatAllOf. + */ + static validateJSON(data) { + + return true; + } + + +} + + + +/** + * @member {Boolean} declawed + */ +CatAllOf.prototype['declawed'] = undefined; + + + + + + +export default CatAllOf; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Category.js b/samples/client/petstore/javascript-apollo/src/model/Category.js index 9ab10c3a0a..fc304998f4 100644 --- a/samples/client/petstore/javascript-apollo/src/model/Category.js +++ b/samples/client/petstore/javascript-apollo/src/model/Category.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -19,27 +19,14 @@ import ApiClient from '../ApiClient'; * @version 1.0.0 */ class Category { - /** - * @member {Number} id - * @type {Number} - */ - id; - /** - * @member {String} name - * @type {String} - */ - name; - - - /** * Constructs a new Category. - * A category for a pet * @alias module:model/Category + * @param name {String} */ - constructor() { + constructor(name) { - Category.initialize(this); + Category.initialize(this, name); } /** @@ -47,7 +34,8 @@ class Category { * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ - static initialize(obj) { + static initialize(obj, name) { + obj['name'] = name || 'default-name'; } /** @@ -70,8 +58,46 @@ class Category { } return obj; } + + /** + * Validates the JSON data with respect to Category. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Category. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Category.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + + return true; + } + + } +Category.RequiredProperties = ["name"]; + +/** + * @member {Number} id + */ +Category.prototype['id'] = undefined; + +/** + * @member {String} name + * @default 'default-name' + */ +Category.prototype['name'] = 'default-name'; + + + + export default Category; diff --git a/samples/client/petstore/javascript-apollo/src/model/ClassModel.js b/samples/client/petstore/javascript-apollo/src/model/ClassModel.js new file mode 100644 index 0000000000..ba614443eb --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/ClassModel.js @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The ClassModel model module. + * @module model/ClassModel + * @version 1.0.0 + */ +class ClassModel { + /** + * Constructs a new ClassModel. + * Model for testing model with \"_class\" property + * @alias module:model/ClassModel + */ + constructor() { + + ClassModel.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a ClassModel from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ClassModel} obj Optional instance to populate. + * @return {module:model/ClassModel} The populated ClassModel instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new ClassModel(); + + if (data.hasOwnProperty('_class')) { + obj['_class'] = ApiClient.convertToType(data['_class'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to ClassModel. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ClassModel. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['_class'] && !(typeof data['_class'] === 'string' || data['_class'] instanceof String)) { + throw new Error("Expected the field `_class` to be a primitive type in the JSON string but got " + data['_class']); + } + + return true; + } + + +} + + + +/** + * @member {String} _class + */ +ClassModel.prototype['_class'] = undefined; + + + + + + +export default ClassModel; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Client.js b/samples/client/petstore/javascript-apollo/src/model/Client.js new file mode 100644 index 0000000000..4089ff37ee --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Client.js @@ -0,0 +1,87 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Client model module. + * @module model/Client + * @version 1.0.0 + */ +class Client { + /** + * Constructs a new Client. + * @alias module:model/Client + */ + constructor() { + + Client.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a Client from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Client} obj Optional instance to populate. + * @return {module:model/Client} The populated Client instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new Client(); + + if (data.hasOwnProperty('client')) { + obj['client'] = ApiClient.convertToType(data['client'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to Client. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Client. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['client'] && !(typeof data['client'] === 'string' || data['client'] instanceof String)) { + throw new Error("Expected the field `client` to be a primitive type in the JSON string but got " + data['client']); + } + + return true; + } + + +} + + + +/** + * @member {String} client + */ +Client.prototype['client'] = undefined; + + + + + + +export default Client; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Color.js b/samples/client/petstore/javascript-apollo/src/model/Color.js new file mode 100644 index 0000000000..b071fff068 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Color.js @@ -0,0 +1,164 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Color model module. + * @module model/Color + * @version 1.0.0 + */ +class Color { + /** + * Constructs a new Color. + * RGB array, RGBA array, or hex string. + * @alias module:model/Color + * @param {(module:model/String|module:model/[Number])} instance The actual instance to initialize Color. + */ + constructor(instance = null) { + if (instance === null) { + this.actualInstance = null; + return; + } + var match = 0; + var errorMessages = []; + // RGB three element array with values 0-255. + try { + // validate array data type + if (!Array.isArray(instance)) { + throw new Error("Invalid data type. Expecting array. Input: " + instance); + } + if (instance.length > 3 || instance.length < 3) { + throw new Error("Invalid array size. Minimim: 3. Maximum: 3. Input: " + instance); + } + // validate array of integer + for (const item of instance) { + if (!(typeof item === 'number' && item % 1 === 0)) { + throw new Error("Invalid array items. Must be integer. Input: " + instance); + } + if (item > 255 || item < 0) { + throw new Error("Invalid integer value in an array items. Max.: 255. Min.: 0. Input: " + instance); + } + } + this.actualInstance = instance; + match++; + } catch(err) { + // json data failed to deserialize into [Number] + errorMessages.push("Failed to construct [Number]: " + err) + } + + // RGBA four element array with values 0-255. + try { + // validate array data type + if (!Array.isArray(instance)) { + throw new Error("Invalid data type. Expecting array. Input: " + instance); + } + if (instance.length > 4 || instance.length < 4) { + throw new Error("Invalid array size. Minimim: 4. Maximum: 4. Input: " + instance); + } + // validate array of integer + for (const item of instance) { + if (!(typeof item === 'number' && item % 1 === 0)) { + throw new Error("Invalid array items. Must be integer. Input: " + instance); + } + if (item > 255 || item < 0) { + throw new Error("Invalid integer value in an array items. Max.: 255. Min.: 0. Input: " + instance); + } + } + this.actualInstance = instance; + match++; + } catch(err) { + // json data failed to deserialize into [Number] + errorMessages.push("Failed to construct [Number]: " + err) + } + + // Hex color string, such as #00FF00. + try { + // validate array of string + if (!(typeof instance === 'string')) { + throw new Error("Invalid input. Must be string. Input: " + JSON.stringify(instance)); + } + if (!/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(instance)) { + throw new Error("Invalid string value in an array items. Must conform to /^#(?:[0-9a-fA-F]{3}){1,2}$/. Input: " + JSON.stringify(instance)); + } + if (instance.length > 7 && instance.length < 7) { + throw new Error("Invalid string value in an array items. Max. length: 7. Min. length: 7. Input: " + JSON.stringify(instance)); + } + this.actualInstance = instance; + match++; + } catch(err) { + // json data failed to deserialize into String + errorMessages.push("Failed to construct String: " + err) + } + + if (match > 1) { + throw new Error("Multiple matches found constructing `Color` with oneOf schemas String, [Number]. Input: " + JSON.stringify(instance)); + } else if (match === 0) { + this.actualInstance = null; // clear the actual instance in case there are multiple matches + throw new Error("No match found constructing `Color` with oneOf schemas String, [Number]. Details: " + + errorMessages.join(", ")); + } else { // only 1 match + // the input is valid + } + } + + /** + * Constructs a Color from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Color} obj Optional instance to populate. + * @return {module:model/Color} The populated Color instance. + */ + static constructFromObject(data, obj) { + return new Color(data); + } + + /** + * Gets the actaul instance, which can be String, [Number]. + * @return {(module:model/String|module:model/[Number])} The actual instance. + */ + getActualInstance() { + return this.actualInstance; + } + + /** + * Sets the actaul instance, which can be String, [Number]. + * @param {(module:model/String|module:model/[Number])} obj The actual instance. + */ + setActualInstance(obj) { + this.actualInstance = Color.constructFromObject(obj).getActualInstance(); + } + + /** + * Returns the JSON representation of the actual intance. + * @return {string} + */ + toJSON = function(){ + return this.getActualInstance(); + } + + /** + * Create an instance of Color from a JSON string. + * @param {string} json_string JSON string. + * @return {module:model/Color} An instance of Color. + */ + static fromJSON = function(json_string){ + return Color.constructFromObject(JSON.parse(json_string)); + } +} + + +Color.OneOf = ["String", "[Number]"]; + +export default Color; + diff --git a/samples/client/petstore/javascript-apollo/src/model/DanishPig.js b/samples/client/petstore/javascript-apollo/src/model/DanishPig.js new file mode 100644 index 0000000000..4023e9d637 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/DanishPig.js @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The DanishPig model module. + * @module model/DanishPig + * @version 1.0.0 + */ +class DanishPig { + /** + * Constructs a new DanishPig. + * @alias module:model/DanishPig + * @param className {String} + * @param size {Number} + */ + constructor(className, size) { + + DanishPig.initialize(this, className, size); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, className, size) { + obj['className'] = className; + obj['size'] = size; + } + + /** + * Constructs a DanishPig from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/DanishPig} obj Optional instance to populate. + * @return {module:model/DanishPig} The populated DanishPig instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new DanishPig(); + + if (data.hasOwnProperty('className')) { + obj['className'] = ApiClient.convertToType(data['className'], 'String'); + } + if (data.hasOwnProperty('size')) { + obj['size'] = ApiClient.convertToType(data['size'], 'Number'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to DanishPig. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to DanishPig. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of DanishPig.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['className'] && !(typeof data['className'] === 'string' || data['className'] instanceof String)) { + throw new Error("Expected the field `className` to be a primitive type in the JSON string but got " + data['className']); + } + + return true; + } + + +} + +DanishPig.RequiredProperties = ["className", "size"]; + +/** + * @member {String} className + */ +DanishPig.prototype['className'] = undefined; + +/** + * @member {Number} size + */ +DanishPig.prototype['size'] = undefined; + + + + + + +export default DanishPig; + diff --git a/samples/client/petstore/javascript-apollo/src/model/DeprecatedObject.js b/samples/client/petstore/javascript-apollo/src/model/DeprecatedObject.js new file mode 100644 index 0000000000..d7c874345f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/DeprecatedObject.js @@ -0,0 +1,87 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The DeprecatedObject model module. + * @module model/DeprecatedObject + * @version 1.0.0 + */ +class DeprecatedObject { + /** + * Constructs a new DeprecatedObject. + * @alias module:model/DeprecatedObject + */ + constructor() { + + DeprecatedObject.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a DeprecatedObject from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/DeprecatedObject} obj Optional instance to populate. + * @return {module:model/DeprecatedObject} The populated DeprecatedObject instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new DeprecatedObject(); + + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to DeprecatedObject. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to DeprecatedObject. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + + return true; + } + + +} + + + +/** + * @member {String} name + */ +DeprecatedObject.prototype['name'] = undefined; + + + + + + +export default DeprecatedObject; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Dog.js b/samples/client/petstore/javascript-apollo/src/model/Dog.js new file mode 100644 index 0000000000..dd3f1ebb50 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Dog.js @@ -0,0 +1,117 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Animal from './Animal'; +import DogAllOf from './DogAllOf'; + +/** + * The Dog model module. + * @module model/Dog + * @version 1.0.0 + */ +class Dog { + /** + * Constructs a new Dog. + * @alias module:model/Dog + * @extends module:model/Animal + * @implements module:model/Animal + * @implements module:model/DogAllOf + * @param className {String} + */ + constructor(className) { + Animal.initialize(this, className);DogAllOf.initialize(this); + Dog.initialize(this, className); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, className) { + } + + /** + * Constructs a Dog from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Dog} obj Optional instance to populate. + * @return {module:model/Dog} The populated Dog instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new Dog(); + Animal.constructFromObject(data, obj); + Animal.constructFromObject(data, obj); + DogAllOf.constructFromObject(data, obj); + + if (data.hasOwnProperty('breed')) { + obj['breed'] = ApiClient.convertToType(data['breed'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to Dog. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Dog. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Dog.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['breed'] && !(typeof data['breed'] === 'string' || data['breed'] instanceof String)) { + throw new Error("Expected the field `breed` to be a primitive type in the JSON string but got " + data['breed']); + } + + return true; + } + + +} + +Dog.RequiredProperties = ["className"]; + +/** + * @member {String} breed + */ +Dog.prototype['breed'] = undefined; + + +// Implement Animal interface: +/** + * @member {String} className + */ +Animal.prototype['className'] = undefined; +/** + * @member {String} color + * @default 'red' + */ +Animal.prototype['color'] = 'red'; +// Implement DogAllOf interface: +/** + * @member {String} breed + */ +DogAllOf.prototype['breed'] = undefined; + + + + +export default Dog; + diff --git a/samples/client/petstore/javascript-apollo/src/model/DogAllOf.js b/samples/client/petstore/javascript-apollo/src/model/DogAllOf.js new file mode 100644 index 0000000000..beb42db2ec --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/DogAllOf.js @@ -0,0 +1,87 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The DogAllOf model module. + * @module model/DogAllOf + * @version 1.0.0 + */ +class DogAllOf { + /** + * Constructs a new DogAllOf. + * @alias module:model/DogAllOf + */ + constructor() { + + DogAllOf.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a DogAllOf from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/DogAllOf} obj Optional instance to populate. + * @return {module:model/DogAllOf} The populated DogAllOf instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new DogAllOf(); + + if (data.hasOwnProperty('breed')) { + obj['breed'] = ApiClient.convertToType(data['breed'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to DogAllOf. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to DogAllOf. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['breed'] && !(typeof data['breed'] === 'string' || data['breed'] instanceof String)) { + throw new Error("Expected the field `breed` to be a primitive type in the JSON string but got " + data['breed']); + } + + return true; + } + + +} + + + +/** + * @member {String} breed + */ +DogAllOf.prototype['breed'] = undefined; + + + + + + +export default DogAllOf; + diff --git a/samples/client/petstore/javascript-apollo/src/model/EnumArrays.js b/samples/client/petstore/javascript-apollo/src/model/EnumArrays.js new file mode 100644 index 0000000000..2289689e34 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/EnumArrays.js @@ -0,0 +1,141 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The EnumArrays model module. + * @module model/EnumArrays + * @version 1.0.0 + */ +class EnumArrays { + /** + * Constructs a new EnumArrays. + * @alias module:model/EnumArrays + */ + constructor() { + + EnumArrays.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a EnumArrays from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/EnumArrays} obj Optional instance to populate. + * @return {module:model/EnumArrays} The populated EnumArrays instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new EnumArrays(); + + if (data.hasOwnProperty('just_symbol')) { + obj['just_symbol'] = ApiClient.convertToType(data['just_symbol'], 'String'); + } + if (data.hasOwnProperty('array_enum')) { + obj['array_enum'] = ApiClient.convertToType(data['array_enum'], ['String']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to EnumArrays. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to EnumArrays. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['just_symbol'] && !(typeof data['just_symbol'] === 'string' || data['just_symbol'] instanceof String)) { + throw new Error("Expected the field `just_symbol` to be a primitive type in the JSON string but got " + data['just_symbol']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_enum'])) { + throw new Error("Expected the field `array_enum` to be an array in the JSON data but got " + data['array_enum']); + } + + return true; + } + + +} + + + +/** + * @member {module:model/EnumArrays.JustSymbolEnum} just_symbol + */ +EnumArrays.prototype['just_symbol'] = undefined; + +/** + * @member {Array.} array_enum + */ +EnumArrays.prototype['array_enum'] = undefined; + + + + + +/** + * Allowed values for the just_symbol property. + * @enum {String} + * @readonly + */ +EnumArrays['JustSymbolEnum'] = { + + /** + * value: ">=" + * @const + */ + "GREATER_THAN_OR_EQUAL_TO": ">=", + + /** + * value: "$" + * @const + */ + "DOLLAR": "$" +}; + + +/** + * Allowed values for the arrayEnum property. + * @enum {String} + * @readonly + */ +EnumArrays['ArrayEnumEnum'] = { + + /** + * value: "fish" + * @const + */ + "fish": "fish", + + /** + * value: "crab" + * @const + */ + "crab": "crab" +}; + + + +export default EnumArrays; + diff --git a/samples/client/petstore/javascript-apollo/src/model/EnumClass.js b/samples/client/petstore/javascript-apollo/src/model/EnumClass.js new file mode 100644 index 0000000000..f0888e52d5 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/EnumClass.js @@ -0,0 +1,53 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +/** +* Enum class EnumClass. +* @enum {} +* @readonly +*/ +export default class EnumClass { + + /** + * value: "_abc" + * @const + */ + "_abc" = "_abc"; + + + /** + * value: "-efg" + * @const + */ + "-efg" = "-efg"; + + + /** + * value: "(xyz)" + * @const + */ + "(xyz)" = "(xyz)"; + + + + /** + * Returns a EnumClass enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {module:model/EnumClass} The enum EnumClass value. + */ + static constructFromObject(object) { + return object; + } +} + diff --git a/samples/client/petstore/javascript-apollo/src/model/EnumTest.js b/samples/client/petstore/javascript-apollo/src/model/EnumTest.js new file mode 100644 index 0000000000..b1556a0613 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/EnumTest.js @@ -0,0 +1,255 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import OuterEnum from './OuterEnum'; +import OuterEnumDefaultValue from './OuterEnumDefaultValue'; +import OuterEnumInteger from './OuterEnumInteger'; +import OuterEnumIntegerDefaultValue from './OuterEnumIntegerDefaultValue'; + +/** + * The EnumTest model module. + * @module model/EnumTest + * @version 1.0.0 + */ +class EnumTest { + /** + * Constructs a new EnumTest. + * @alias module:model/EnumTest + * @param enumStringRequired {module:model/EnumTest.EnumStringRequiredEnum} + */ + constructor(enumStringRequired) { + + EnumTest.initialize(this, enumStringRequired); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, enumStringRequired) { + obj['enum_string_required'] = enumStringRequired; + } + + /** + * Constructs a EnumTest from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/EnumTest} obj Optional instance to populate. + * @return {module:model/EnumTest} The populated EnumTest instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new EnumTest(); + + if (data.hasOwnProperty('enum_string')) { + obj['enum_string'] = ApiClient.convertToType(data['enum_string'], 'String'); + } + if (data.hasOwnProperty('enum_string_required')) { + obj['enum_string_required'] = ApiClient.convertToType(data['enum_string_required'], 'String'); + } + if (data.hasOwnProperty('enum_integer')) { + obj['enum_integer'] = ApiClient.convertToType(data['enum_integer'], 'Number'); + } + if (data.hasOwnProperty('enum_number')) { + obj['enum_number'] = ApiClient.convertToType(data['enum_number'], 'Number'); + } + if (data.hasOwnProperty('outerEnum')) { + obj['outerEnum'] = OuterEnum.constructFromObject(data['outerEnum']); + } + if (data.hasOwnProperty('outerEnumInteger')) { + obj['outerEnumInteger'] = OuterEnumInteger.constructFromObject(data['outerEnumInteger']); + } + if (data.hasOwnProperty('outerEnumDefaultValue')) { + obj['outerEnumDefaultValue'] = OuterEnumDefaultValue.constructFromObject(data['outerEnumDefaultValue']); + } + if (data.hasOwnProperty('outerEnumIntegerDefaultValue')) { + obj['outerEnumIntegerDefaultValue'] = OuterEnumIntegerDefaultValue.constructFromObject(data['outerEnumIntegerDefaultValue']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to EnumTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to EnumTest. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of EnumTest.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['enum_string'] && !(typeof data['enum_string'] === 'string' || data['enum_string'] instanceof String)) { + throw new Error("Expected the field `enum_string` to be a primitive type in the JSON string but got " + data['enum_string']); + } + // ensure the json data is a string + if (data['enum_string_required'] && !(typeof data['enum_string_required'] === 'string' || data['enum_string_required'] instanceof String)) { + throw new Error("Expected the field `enum_string_required` to be a primitive type in the JSON string but got " + data['enum_string_required']); + } + + return true; + } + + +} + +EnumTest.RequiredProperties = ["enum_string_required"]; + +/** + * @member {module:model/EnumTest.EnumStringEnum} enum_string + */ +EnumTest.prototype['enum_string'] = undefined; + +/** + * @member {module:model/EnumTest.EnumStringRequiredEnum} enum_string_required + */ +EnumTest.prototype['enum_string_required'] = undefined; + +/** + * @member {module:model/EnumTest.EnumIntegerEnum} enum_integer + */ +EnumTest.prototype['enum_integer'] = undefined; + +/** + * @member {module:model/EnumTest.EnumNumberEnum} enum_number + */ +EnumTest.prototype['enum_number'] = undefined; + +/** + * @member {module:model/OuterEnum} outerEnum + */ +EnumTest.prototype['outerEnum'] = undefined; + +/** + * @member {module:model/OuterEnumInteger} outerEnumInteger + */ +EnumTest.prototype['outerEnumInteger'] = undefined; + +/** + * @member {module:model/OuterEnumDefaultValue} outerEnumDefaultValue + */ +EnumTest.prototype['outerEnumDefaultValue'] = undefined; + +/** + * @member {module:model/OuterEnumIntegerDefaultValue} outerEnumIntegerDefaultValue + */ +EnumTest.prototype['outerEnumIntegerDefaultValue'] = undefined; + + + + + +/** + * Allowed values for the enum_string property. + * @enum {String} + * @readonly + */ +EnumTest['EnumStringEnum'] = { + + /** + * value: "UPPER" + * @const + */ + "UPPER": "UPPER", + + /** + * value: "lower" + * @const + */ + "lower": "lower", + + /** + * value: "" + * @const + */ + "empty": "" +}; + + +/** + * Allowed values for the enum_string_required property. + * @enum {String} + * @readonly + */ +EnumTest['EnumStringRequiredEnum'] = { + + /** + * value: "UPPER" + * @const + */ + "UPPER": "UPPER", + + /** + * value: "lower" + * @const + */ + "lower": "lower", + + /** + * value: "" + * @const + */ + "empty": "" +}; + + +/** + * Allowed values for the enum_integer property. + * @enum {Number} + * @readonly + */ +EnumTest['EnumIntegerEnum'] = { + + /** + * value: 1 + * @const + */ + "1": 1, + + /** + * value: -1 + * @const + */ + "-1": -1 +}; + + +/** + * Allowed values for the enum_number property. + * @enum {Number} + * @readonly + */ +EnumTest['EnumNumberEnum'] = { + + /** + * value: 1.1 + * @const + */ + "1.1": 1.1, + + /** + * value: -1.2 + * @const + */ + "-1.2": -1.2 +}; + + + +export default EnumTest; + diff --git a/samples/client/petstore/javascript-apollo/src/model/File.js b/samples/client/petstore/javascript-apollo/src/model/File.js new file mode 100644 index 0000000000..5f5c9547a1 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/File.js @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The File model module. + * @module model/File + * @version 1.0.0 + */ +class File { + /** + * Constructs a new File. + * Must be named `File` for test. + * @alias module:model/File + */ + constructor() { + + File.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a File from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/File} obj Optional instance to populate. + * @return {module:model/File} The populated File instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new File(); + + if (data.hasOwnProperty('sourceURI')) { + obj['sourceURI'] = ApiClient.convertToType(data['sourceURI'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to File. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to File. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['sourceURI'] && !(typeof data['sourceURI'] === 'string' || data['sourceURI'] instanceof String)) { + throw new Error("Expected the field `sourceURI` to be a primitive type in the JSON string but got " + data['sourceURI']); + } + + return true; + } + + +} + + + +/** + * Test capitalization + * @member {String} sourceURI + */ +File.prototype['sourceURI'] = undefined; + + + + + + +export default File; + diff --git a/samples/client/petstore/javascript-apollo/src/model/FileSchemaTestClass.js b/samples/client/petstore/javascript-apollo/src/model/FileSchemaTestClass.js new file mode 100644 index 0000000000..8174d56245 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/FileSchemaTestClass.js @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The FileSchemaTestClass model module. + * @module model/FileSchemaTestClass + * @version 1.0.0 + */ +class FileSchemaTestClass { + /** + * Constructs a new FileSchemaTestClass. + * @alias module:model/FileSchemaTestClass + */ + constructor() { + + FileSchemaTestClass.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a FileSchemaTestClass from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/FileSchemaTestClass} obj Optional instance to populate. + * @return {module:model/FileSchemaTestClass} The populated FileSchemaTestClass instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new FileSchemaTestClass(); + + if (data.hasOwnProperty('file')) { + obj['file'] = File.constructFromObject(data['file']); + } + if (data.hasOwnProperty('files')) { + obj['files'] = ApiClient.convertToType(data['files'], [File]); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to FileSchemaTestClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to FileSchemaTestClass. + */ + static validateJSON(data) { + // validate the optional field `file` + if (data['file']) { // data not null + File.validateJSON(data['file']); + } + if (data['files']) { // data not null + // ensure the json data is an array + if (!Array.isArray(data['files'])) { + throw new Error("Expected the field `files` to be an array in the JSON data but got " + data['files']); + } + // validate the optional field `files` (array) + for (const item of data['files']) { + File.validateJsonObject(item); + }; + } + + return true; + } + + +} + + + +/** + * @member {File} file + */ +FileSchemaTestClass.prototype['file'] = undefined; + +/** + * @member {Array.} files + */ +FileSchemaTestClass.prototype['files'] = undefined; + + + + + + +export default FileSchemaTestClass; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Foo.js b/samples/client/petstore/javascript-apollo/src/model/Foo.js new file mode 100644 index 0000000000..3fc7819f99 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Foo.js @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Foo model module. + * @module model/Foo + * @version 1.0.0 + */ +class Foo { + /** + * Constructs a new Foo. + * @alias module:model/Foo + */ + constructor() { + + Foo.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a Foo from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Foo} obj Optional instance to populate. + * @return {module:model/Foo} The populated Foo instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new Foo(); + + if (data.hasOwnProperty('bar')) { + obj['bar'] = ApiClient.convertToType(data['bar'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to Foo. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Foo. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['bar'] && !(typeof data['bar'] === 'string' || data['bar'] instanceof String)) { + throw new Error("Expected the field `bar` to be a primitive type in the JSON string but got " + data['bar']); + } + + return true; + } + + +} + + + +/** + * @member {String} bar + * @default 'bar' + */ +Foo.prototype['bar'] = 'bar'; + + + + + + +export default Foo; + diff --git a/samples/client/petstore/javascript-apollo/src/model/FooGetDefaultResponse.js b/samples/client/petstore/javascript-apollo/src/model/FooGetDefaultResponse.js new file mode 100644 index 0000000000..b11d885937 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/FooGetDefaultResponse.js @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Foo from './Foo'; + +/** + * The FooGetDefaultResponse model module. + * @module model/FooGetDefaultResponse + * @version 1.0.0 + */ +class FooGetDefaultResponse { + /** + * Constructs a new FooGetDefaultResponse. + * @alias module:model/FooGetDefaultResponse + */ + constructor() { + + FooGetDefaultResponse.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a FooGetDefaultResponse from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/FooGetDefaultResponse} obj Optional instance to populate. + * @return {module:model/FooGetDefaultResponse} The populated FooGetDefaultResponse instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new FooGetDefaultResponse(); + + if (data.hasOwnProperty('string')) { + obj['string'] = Foo.constructFromObject(data['string']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to FooGetDefaultResponse. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to FooGetDefaultResponse. + */ + static validateJSON(data) { + // validate the optional field `string` + if (data['string']) { // data not null + Foo.validateJSON(data['string']); + } + + return true; + } + + +} + + + +/** + * @member {module:model/Foo} string + */ +FooGetDefaultResponse.prototype['string'] = undefined; + + + + + + +export default FooGetDefaultResponse; + diff --git a/samples/client/petstore/javascript-apollo/src/model/FormatTest.js b/samples/client/petstore/javascript-apollo/src/model/FormatTest.js new file mode 100644 index 0000000000..65a34a7ff0 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/FormatTest.js @@ -0,0 +1,239 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The FormatTest model module. + * @module model/FormatTest + * @version 1.0.0 + */ +class FormatTest { + /** + * Constructs a new FormatTest. + * @alias module:model/FormatTest + * @param number {Number} + * @param _byte {Blob} + * @param date {Date} + * @param password {String} + */ + constructor(number, _byte, date, password) { + + FormatTest.initialize(this, number, _byte, date, password); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, number, _byte, date, password) { + obj['number'] = number; + obj['byte'] = _byte; + obj['date'] = date; + obj['password'] = password; + } + + /** + * Constructs a FormatTest from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/FormatTest} obj Optional instance to populate. + * @return {module:model/FormatTest} The populated FormatTest instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new FormatTest(); + + if (data.hasOwnProperty('integer')) { + obj['integer'] = ApiClient.convertToType(data['integer'], 'Number'); + } + if (data.hasOwnProperty('int32')) { + obj['int32'] = ApiClient.convertToType(data['int32'], 'Number'); + } + if (data.hasOwnProperty('int64')) { + obj['int64'] = ApiClient.convertToType(data['int64'], 'Number'); + } + if (data.hasOwnProperty('number')) { + obj['number'] = ApiClient.convertToType(data['number'], 'Number'); + } + if (data.hasOwnProperty('float')) { + obj['float'] = ApiClient.convertToType(data['float'], 'Number'); + } + if (data.hasOwnProperty('double')) { + obj['double'] = ApiClient.convertToType(data['double'], 'Number'); + } + if (data.hasOwnProperty('decimal')) { + obj['decimal'] = ApiClient.convertToType(data['decimal'], 'Number'); + } + if (data.hasOwnProperty('string')) { + obj['string'] = ApiClient.convertToType(data['string'], 'String'); + } + if (data.hasOwnProperty('byte')) { + obj['byte'] = ApiClient.convertToType(data['byte'], 'Blob'); + } + if (data.hasOwnProperty('binary')) { + obj['binary'] = ApiClient.convertToType(data['binary'], File); + } + if (data.hasOwnProperty('date')) { + obj['date'] = ApiClient.convertToType(data['date'], 'Date'); + } + if (data.hasOwnProperty('dateTime')) { + obj['dateTime'] = ApiClient.convertToType(data['dateTime'], 'Date'); + } + if (data.hasOwnProperty('uuid')) { + obj['uuid'] = ApiClient.convertToType(data['uuid'], 'String'); + } + if (data.hasOwnProperty('password')) { + obj['password'] = ApiClient.convertToType(data['password'], 'String'); + } + if (data.hasOwnProperty('pattern_with_digits')) { + obj['pattern_with_digits'] = ApiClient.convertToType(data['pattern_with_digits'], 'String'); + } + if (data.hasOwnProperty('pattern_with_digits_and_delimiter')) { + obj['pattern_with_digits_and_delimiter'] = ApiClient.convertToType(data['pattern_with_digits_and_delimiter'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to FormatTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to FormatTest. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of FormatTest.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['string'] && !(typeof data['string'] === 'string' || data['string'] instanceof String)) { + throw new Error("Expected the field `string` to be a primitive type in the JSON string but got " + data['string']); + } + // ensure the json data is a string + if (data['uuid'] && !(typeof data['uuid'] === 'string' || data['uuid'] instanceof String)) { + throw new Error("Expected the field `uuid` to be a primitive type in the JSON string but got " + data['uuid']); + } + // ensure the json data is a string + if (data['password'] && !(typeof data['password'] === 'string' || data['password'] instanceof String)) { + throw new Error("Expected the field `password` to be a primitive type in the JSON string but got " + data['password']); + } + // ensure the json data is a string + if (data['pattern_with_digits'] && !(typeof data['pattern_with_digits'] === 'string' || data['pattern_with_digits'] instanceof String)) { + throw new Error("Expected the field `pattern_with_digits` to be a primitive type in the JSON string but got " + data['pattern_with_digits']); + } + // ensure the json data is a string + if (data['pattern_with_digits_and_delimiter'] && !(typeof data['pattern_with_digits_and_delimiter'] === 'string' || data['pattern_with_digits_and_delimiter'] instanceof String)) { + throw new Error("Expected the field `pattern_with_digits_and_delimiter` to be a primitive type in the JSON string but got " + data['pattern_with_digits_and_delimiter']); + } + + return true; + } + + +} + +FormatTest.RequiredProperties = ["number", "byte", "date", "password"]; + +/** + * @member {Number} integer + */ +FormatTest.prototype['integer'] = undefined; + +/** + * @member {Number} int32 + */ +FormatTest.prototype['int32'] = undefined; + +/** + * @member {Number} int64 + */ +FormatTest.prototype['int64'] = undefined; + +/** + * @member {Number} number + */ +FormatTest.prototype['number'] = undefined; + +/** + * @member {Number} float + */ +FormatTest.prototype['float'] = undefined; + +/** + * @member {Number} double + */ +FormatTest.prototype['double'] = undefined; + +/** + * @member {Number} decimal + */ +FormatTest.prototype['decimal'] = undefined; + +/** + * @member {String} string + */ +FormatTest.prototype['string'] = undefined; + +/** + * @member {Blob} byte + */ +FormatTest.prototype['byte'] = undefined; + +/** + * @member {File} binary + */ +FormatTest.prototype['binary'] = undefined; + +/** + * @member {Date} date + */ +FormatTest.prototype['date'] = undefined; + +/** + * @member {Date} dateTime + */ +FormatTest.prototype['dateTime'] = undefined; + +/** + * @member {String} uuid + */ +FormatTest.prototype['uuid'] = undefined; + +/** + * @member {String} password + */ +FormatTest.prototype['password'] = undefined; + +/** + * A string that is a 10 digit number. Can have leading zeros. + * @member {String} pattern_with_digits + */ +FormatTest.prototype['pattern_with_digits'] = undefined; + +/** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + * @member {String} pattern_with_digits_and_delimiter + */ +FormatTest.prototype['pattern_with_digits_and_delimiter'] = undefined; + + + + + + +export default FormatTest; + diff --git a/samples/client/petstore/javascript-apollo/src/model/HasOnlyReadOnly.js b/samples/client/petstore/javascript-apollo/src/model/HasOnlyReadOnly.js new file mode 100644 index 0000000000..90943b87ae --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/HasOnlyReadOnly.js @@ -0,0 +1,99 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The HasOnlyReadOnly model module. + * @module model/HasOnlyReadOnly + * @version 1.0.0 + */ +class HasOnlyReadOnly { + /** + * Constructs a new HasOnlyReadOnly. + * @alias module:model/HasOnlyReadOnly + */ + constructor() { + + HasOnlyReadOnly.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a HasOnlyReadOnly from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/HasOnlyReadOnly} obj Optional instance to populate. + * @return {module:model/HasOnlyReadOnly} The populated HasOnlyReadOnly instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new HasOnlyReadOnly(); + + if (data.hasOwnProperty('bar')) { + obj['bar'] = ApiClient.convertToType(data['bar'], 'String'); + } + if (data.hasOwnProperty('foo')) { + obj['foo'] = ApiClient.convertToType(data['foo'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to HasOnlyReadOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to HasOnlyReadOnly. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['bar'] && !(typeof data['bar'] === 'string' || data['bar'] instanceof String)) { + throw new Error("Expected the field `bar` to be a primitive type in the JSON string but got " + data['bar']); + } + // ensure the json data is a string + if (data['foo'] && !(typeof data['foo'] === 'string' || data['foo'] instanceof String)) { + throw new Error("Expected the field `foo` to be a primitive type in the JSON string but got " + data['foo']); + } + + return true; + } + + +} + + + +/** + * @member {String} bar + */ +HasOnlyReadOnly.prototype['bar'] = undefined; + +/** + * @member {String} foo + */ +HasOnlyReadOnly.prototype['foo'] = undefined; + + + + + + +export default HasOnlyReadOnly; + diff --git a/samples/client/petstore/javascript-apollo/src/model/HealthCheckResult.js b/samples/client/petstore/javascript-apollo/src/model/HealthCheckResult.js new file mode 100644 index 0000000000..112fd77842 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/HealthCheckResult.js @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The HealthCheckResult model module. + * @module model/HealthCheckResult + * @version 1.0.0 + */ +class HealthCheckResult { + /** + * Constructs a new HealthCheckResult. + * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + * @alias module:model/HealthCheckResult + */ + constructor() { + + HealthCheckResult.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a HealthCheckResult from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/HealthCheckResult} obj Optional instance to populate. + * @return {module:model/HealthCheckResult} The populated HealthCheckResult instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new HealthCheckResult(); + + if (data.hasOwnProperty('NullableMessage')) { + obj['NullableMessage'] = ApiClient.convertToType(data['NullableMessage'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to HealthCheckResult. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to HealthCheckResult. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['NullableMessage'] && !(typeof data['NullableMessage'] === 'string' || data['NullableMessage'] instanceof String)) { + throw new Error("Expected the field `NullableMessage` to be a primitive type in the JSON string but got " + data['NullableMessage']); + } + + return true; + } + + +} + + + +/** + * @member {String} NullableMessage + */ +HealthCheckResult.prototype['NullableMessage'] = undefined; + + + + + + +export default HealthCheckResult; + diff --git a/samples/client/petstore/javascript-apollo/src/model/List.js b/samples/client/petstore/javascript-apollo/src/model/List.js new file mode 100644 index 0000000000..ca916761c0 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/List.js @@ -0,0 +1,87 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The List model module. + * @module model/List + * @version 1.0.0 + */ +class List { + /** + * Constructs a new List. + * @alias module:model/List + */ + constructor() { + + List.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a List from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/List} obj Optional instance to populate. + * @return {module:model/List} The populated List instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new List(); + + if (data.hasOwnProperty('123-list')) { + obj['123-list'] = ApiClient.convertToType(data['123-list'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to List. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to List. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['123-list'] && !(typeof data['123-list'] === 'string' || data['123-list'] instanceof String)) { + throw new Error("Expected the field `123-list` to be a primitive type in the JSON string but got " + data['123-list']); + } + + return true; + } + + +} + + + +/** + * @member {String} 123-list + */ +List.prototype['123-list'] = undefined; + + + + + + +export default List; + diff --git a/samples/client/petstore/javascript-apollo/src/model/MapTest.js b/samples/client/petstore/javascript-apollo/src/model/MapTest.js new file mode 100644 index 0000000000..478e2347fa --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/MapTest.js @@ -0,0 +1,128 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The MapTest model module. + * @module model/MapTest + * @version 1.0.0 + */ +class MapTest { + /** + * Constructs a new MapTest. + * @alias module:model/MapTest + */ + constructor() { + + MapTest.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a MapTest from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/MapTest} obj Optional instance to populate. + * @return {module:model/MapTest} The populated MapTest instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new MapTest(); + + if (data.hasOwnProperty('map_map_of_string')) { + obj['map_map_of_string'] = ApiClient.convertToType(data['map_map_of_string'], {'String': {'String': 'String'}}); + } + if (data.hasOwnProperty('map_of_enum_string')) { + obj['map_of_enum_string'] = ApiClient.convertToType(data['map_of_enum_string'], {'String': 'String'}); + } + if (data.hasOwnProperty('direct_map')) { + obj['direct_map'] = ApiClient.convertToType(data['direct_map'], {'String': 'Boolean'}); + } + if (data.hasOwnProperty('indirect_map')) { + obj['indirect_map'] = ApiClient.convertToType(data['indirect_map'], {'String': 'Boolean'}); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to MapTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to MapTest. + */ + static validateJSON(data) { + + return true; + } + + +} + + + +/** + * @member {Object.>} map_map_of_string + */ +MapTest.prototype['map_map_of_string'] = undefined; + +/** + * @member {Object.} map_of_enum_string + */ +MapTest.prototype['map_of_enum_string'] = undefined; + +/** + * @member {Object.} direct_map + */ +MapTest.prototype['direct_map'] = undefined; + +/** + * @member {Object.} indirect_map + */ +MapTest.prototype['indirect_map'] = undefined; + + + + + +/** + * Allowed values for the inner property. + * @enum {String} + * @readonly + */ +MapTest['InnerEnum'] = { + + /** + * value: "UPPER" + * @const + */ + "UPPER": "UPPER", + + /** + * value: "lower" + * @const + */ + "lower": "lower" +}; + + + +export default MapTest; + diff --git a/samples/client/petstore/javascript-apollo/src/model/MixedPropertiesAndAdditionalPropertiesClass.js b/samples/client/petstore/javascript-apollo/src/model/MixedPropertiesAndAdditionalPropertiesClass.js new file mode 100644 index 0000000000..8131fa3620 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/MixedPropertiesAndAdditionalPropertiesClass.js @@ -0,0 +1,104 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Animal from './Animal'; + +/** + * The MixedPropertiesAndAdditionalPropertiesClass model module. + * @module model/MixedPropertiesAndAdditionalPropertiesClass + * @version 1.0.0 + */ +class MixedPropertiesAndAdditionalPropertiesClass { + /** + * Constructs a new MixedPropertiesAndAdditionalPropertiesClass. + * @alias module:model/MixedPropertiesAndAdditionalPropertiesClass + */ + constructor() { + + MixedPropertiesAndAdditionalPropertiesClass.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a MixedPropertiesAndAdditionalPropertiesClass from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/MixedPropertiesAndAdditionalPropertiesClass} obj Optional instance to populate. + * @return {module:model/MixedPropertiesAndAdditionalPropertiesClass} The populated MixedPropertiesAndAdditionalPropertiesClass instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new MixedPropertiesAndAdditionalPropertiesClass(); + + if (data.hasOwnProperty('uuid')) { + obj['uuid'] = ApiClient.convertToType(data['uuid'], 'String'); + } + if (data.hasOwnProperty('dateTime')) { + obj['dateTime'] = ApiClient.convertToType(data['dateTime'], 'Date'); + } + if (data.hasOwnProperty('map')) { + obj['map'] = ApiClient.convertToType(data['map'], {'String': Animal}); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to MixedPropertiesAndAdditionalPropertiesClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to MixedPropertiesAndAdditionalPropertiesClass. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['uuid'] && !(typeof data['uuid'] === 'string' || data['uuid'] instanceof String)) { + throw new Error("Expected the field `uuid` to be a primitive type in the JSON string but got " + data['uuid']); + } + + return true; + } + + +} + + + +/** + * @member {String} uuid + */ +MixedPropertiesAndAdditionalPropertiesClass.prototype['uuid'] = undefined; + +/** + * @member {Date} dateTime + */ +MixedPropertiesAndAdditionalPropertiesClass.prototype['dateTime'] = undefined; + +/** + * @member {Object.} map + */ +MixedPropertiesAndAdditionalPropertiesClass.prototype['map'] = undefined; + + + + + + +export default MixedPropertiesAndAdditionalPropertiesClass; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Model200Response.js b/samples/client/petstore/javascript-apollo/src/model/Model200Response.js new file mode 100644 index 0000000000..604683735f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Model200Response.js @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Model200Response model module. + * @module model/Model200Response + * @version 1.0.0 + */ +class Model200Response { + /** + * Constructs a new Model200Response. + * Model for testing model name starting with number + * @alias module:model/Model200Response + */ + constructor() { + + Model200Response.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a Model200Response from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Model200Response} obj Optional instance to populate. + * @return {module:model/Model200Response} The populated Model200Response instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new Model200Response(); + + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'Number'); + } + if (data.hasOwnProperty('class')) { + obj['class'] = ApiClient.convertToType(data['class'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to Model200Response. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Model200Response. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['class'] && !(typeof data['class'] === 'string' || data['class'] instanceof String)) { + throw new Error("Expected the field `class` to be a primitive type in the JSON string but got " + data['class']); + } + + return true; + } + + +} + + + +/** + * @member {Number} name + */ +Model200Response.prototype['name'] = undefined; + +/** + * @member {String} class + */ +Model200Response.prototype['class'] = undefined; + + + + + + +export default Model200Response; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Name.js b/samples/client/petstore/javascript-apollo/src/model/Name.js new file mode 100644 index 0000000000..978fbaa7ef --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Name.js @@ -0,0 +1,120 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Name model module. + * @module model/Name + * @version 1.0.0 + */ +class Name { + /** + * Constructs a new Name. + * Model for testing model name same as property name + * @alias module:model/Name + * @param name {Number} + */ + constructor(name) { + + Name.initialize(this, name); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, name) { + obj['name'] = name; + } + + /** + * Constructs a Name from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Name} obj Optional instance to populate. + * @return {module:model/Name} The populated Name instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new Name(); + + if (data.hasOwnProperty('name')) { + obj['name'] = ApiClient.convertToType(data['name'], 'Number'); + } + if (data.hasOwnProperty('snake_case')) { + obj['snake_case'] = ApiClient.convertToType(data['snake_case'], 'Number'); + } + if (data.hasOwnProperty('property')) { + obj['property'] = ApiClient.convertToType(data['property'], 'String'); + } + if (data.hasOwnProperty('123Number')) { + obj['123Number'] = ApiClient.convertToType(data['123Number'], 'Number'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to Name. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Name. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Name.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['property'] && !(typeof data['property'] === 'string' || data['property'] instanceof String)) { + throw new Error("Expected the field `property` to be a primitive type in the JSON string but got " + data['property']); + } + + return true; + } + + +} + +Name.RequiredProperties = ["name"]; + +/** + * @member {Number} name + */ +Name.prototype['name'] = undefined; + +/** + * @member {Number} snake_case + */ +Name.prototype['snake_case'] = undefined; + +/** + * @member {String} property + */ +Name.prototype['property'] = undefined; + +/** + * @member {Number} 123Number + */ +Name.prototype['123Number'] = undefined; + + + + + + +export default Name; + diff --git a/samples/client/petstore/javascript-apollo/src/model/NestedColor.js b/samples/client/petstore/javascript-apollo/src/model/NestedColor.js new file mode 100644 index 0000000000..5b61146903 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/NestedColor.js @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Color from './Color'; + +/** + * The NestedColor model module. + * @module model/NestedColor + * @version 1.0.0 + */ +class NestedColor { + /** + * Constructs a new NestedColor. + * @alias module:model/NestedColor + */ + constructor() { + + NestedColor.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a NestedColor from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/NestedColor} obj Optional instance to populate. + * @return {module:model/NestedColor} The populated NestedColor instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new NestedColor(); + + if (data.hasOwnProperty('size')) { + obj['size'] = ApiClient.convertToType(data['size'], 'Number'); + } + if (data.hasOwnProperty('nested')) { + obj['nested'] = Color.constructFromObject(data['nested']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to NestedColor. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NestedColor. + */ + static validateJSON(data) { + // validate the optional field `nested` + if (data['nested']) { // data not null + Color.validateJSON(data['nested']); + } + + return true; + } + + +} + + + +/** + * @member {Number} size + */ +NestedColor.prototype['size'] = undefined; + +/** + * @member {module:model/Color} nested + */ +NestedColor.prototype['nested'] = undefined; + + + + + + +export default NestedColor; + diff --git a/samples/client/petstore/javascript-apollo/src/model/NestedOneOf.js b/samples/client/petstore/javascript-apollo/src/model/NestedOneOf.js new file mode 100644 index 0000000000..3ea6ed798b --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/NestedOneOf.js @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Pig from './Pig'; + +/** + * The NestedOneOf model module. + * @module model/NestedOneOf + * @version 1.0.0 + */ +class NestedOneOf { + /** + * Constructs a new NestedOneOf. + * @alias module:model/NestedOneOf + */ + constructor() { + + NestedOneOf.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a NestedOneOf from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/NestedOneOf} obj Optional instance to populate. + * @return {module:model/NestedOneOf} The populated NestedOneOf instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new NestedOneOf(); + + if (data.hasOwnProperty('size')) { + obj['size'] = ApiClient.convertToType(data['size'], 'Number'); + } + if (data.hasOwnProperty('nested_pig')) { + obj['nested_pig'] = Pig.constructFromObject(data['nested_pig']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to NestedOneOf. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NestedOneOf. + */ + static validateJSON(data) { + // validate the optional field `nested_pig` + if (data['nested_pig']) { // data not null + Pig.validateJSON(data['nested_pig']); + } + + return true; + } + + +} + + + +/** + * @member {Number} size + */ +NestedOneOf.prototype['size'] = undefined; + +/** + * @member {module:model/Pig} nested_pig + */ +NestedOneOf.prototype['nested_pig'] = undefined; + + + + + + +export default NestedOneOf; + diff --git a/samples/client/petstore/javascript-apollo/src/model/NullableClass.js b/samples/client/petstore/javascript-apollo/src/model/NullableClass.js new file mode 100644 index 0000000000..33dd77a182 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/NullableClass.js @@ -0,0 +1,191 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The NullableClass model module. + * @module model/NullableClass + * @version 1.0.0 + */ +class NullableClass { + /** + * Constructs a new NullableClass. + * @alias module:model/NullableClass + * @extends Object + */ + constructor() { + + NullableClass.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a NullableClass from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/NullableClass} obj Optional instance to populate. + * @return {module:model/NullableClass} The populated NullableClass instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new NullableClass(); + + ApiClient.constructFromObject(data, obj, 'Object'); + + + if (data.hasOwnProperty('integer_prop')) { + obj['integer_prop'] = ApiClient.convertToType(data['integer_prop'], 'Number'); + } + if (data.hasOwnProperty('number_prop')) { + obj['number_prop'] = ApiClient.convertToType(data['number_prop'], 'Number'); + } + if (data.hasOwnProperty('boolean_prop')) { + obj['boolean_prop'] = ApiClient.convertToType(data['boolean_prop'], 'Boolean'); + } + if (data.hasOwnProperty('string_prop')) { + obj['string_prop'] = ApiClient.convertToType(data['string_prop'], 'String'); + } + if (data.hasOwnProperty('date_prop')) { + obj['date_prop'] = ApiClient.convertToType(data['date_prop'], 'Date'); + } + if (data.hasOwnProperty('datetime_prop')) { + obj['datetime_prop'] = ApiClient.convertToType(data['datetime_prop'], 'Date'); + } + if (data.hasOwnProperty('array_nullable_prop')) { + obj['array_nullable_prop'] = ApiClient.convertToType(data['array_nullable_prop'], [Object]); + } + if (data.hasOwnProperty('array_and_items_nullable_prop')) { + obj['array_and_items_nullable_prop'] = ApiClient.convertToType(data['array_and_items_nullable_prop'], [Object]); + } + if (data.hasOwnProperty('array_items_nullable')) { + obj['array_items_nullable'] = ApiClient.convertToType(data['array_items_nullable'], [Object]); + } + if (data.hasOwnProperty('object_nullable_prop')) { + obj['object_nullable_prop'] = ApiClient.convertToType(data['object_nullable_prop'], {'String': Object}); + } + if (data.hasOwnProperty('object_and_items_nullable_prop')) { + obj['object_and_items_nullable_prop'] = ApiClient.convertToType(data['object_and_items_nullable_prop'], {'String': Object}); + } + if (data.hasOwnProperty('object_items_nullable')) { + obj['object_items_nullable'] = ApiClient.convertToType(data['object_items_nullable'], {'String': Object}); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to NullableClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NullableClass. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['string_prop'] && !(typeof data['string_prop'] === 'string' || data['string_prop'] instanceof String)) { + throw new Error("Expected the field `string_prop` to be a primitive type in the JSON string but got " + data['string_prop']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_nullable_prop'])) { + throw new Error("Expected the field `array_nullable_prop` to be an array in the JSON data but got " + data['array_nullable_prop']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_and_items_nullable_prop'])) { + throw new Error("Expected the field `array_and_items_nullable_prop` to be an array in the JSON data but got " + data['array_and_items_nullable_prop']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_items_nullable'])) { + throw new Error("Expected the field `array_items_nullable` to be an array in the JSON data but got " + data['array_items_nullable']); + } + + return true; + } + + +} + + + +/** + * @member {Number} integer_prop + */ +NullableClass.prototype['integer_prop'] = undefined; + +/** + * @member {Number} number_prop + */ +NullableClass.prototype['number_prop'] = undefined; + +/** + * @member {Boolean} boolean_prop + */ +NullableClass.prototype['boolean_prop'] = undefined; + +/** + * @member {String} string_prop + */ +NullableClass.prototype['string_prop'] = undefined; + +/** + * @member {Date} date_prop + */ +NullableClass.prototype['date_prop'] = undefined; + +/** + * @member {Date} datetime_prop + */ +NullableClass.prototype['datetime_prop'] = undefined; + +/** + * @member {Array.} array_nullable_prop + */ +NullableClass.prototype['array_nullable_prop'] = undefined; + +/** + * @member {Array.} array_and_items_nullable_prop + */ +NullableClass.prototype['array_and_items_nullable_prop'] = undefined; + +/** + * @member {Array.} array_items_nullable + */ +NullableClass.prototype['array_items_nullable'] = undefined; + +/** + * @member {Object.} object_nullable_prop + */ +NullableClass.prototype['object_nullable_prop'] = undefined; + +/** + * @member {Object.} object_and_items_nullable_prop + */ +NullableClass.prototype['object_and_items_nullable_prop'] = undefined; + +/** + * @member {Object.} object_items_nullable + */ +NullableClass.prototype['object_items_nullable'] = undefined; + + + + + + +export default NullableClass; + diff --git a/samples/client/petstore/javascript-apollo/src/model/NumberOnly.js b/samples/client/petstore/javascript-apollo/src/model/NumberOnly.js new file mode 100644 index 0000000000..deb4f2961f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/NumberOnly.js @@ -0,0 +1,83 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The NumberOnly model module. + * @module model/NumberOnly + * @version 1.0.0 + */ +class NumberOnly { + /** + * Constructs a new NumberOnly. + * @alias module:model/NumberOnly + */ + constructor() { + + NumberOnly.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a NumberOnly from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/NumberOnly} obj Optional instance to populate. + * @return {module:model/NumberOnly} The populated NumberOnly instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new NumberOnly(); + + if (data.hasOwnProperty('JustNumber')) { + obj['JustNumber'] = ApiClient.convertToType(data['JustNumber'], 'Number'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to NumberOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NumberOnly. + */ + static validateJSON(data) { + + return true; + } + + +} + + + +/** + * @member {Number} JustNumber + */ +NumberOnly.prototype['JustNumber'] = undefined; + + + + + + +export default NumberOnly; + diff --git a/samples/client/petstore/javascript-apollo/src/model/ObjectWithDeprecatedFields.js b/samples/client/petstore/javascript-apollo/src/model/ObjectWithDeprecatedFields.js new file mode 100644 index 0000000000..29e80fd266 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/ObjectWithDeprecatedFields.js @@ -0,0 +1,120 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import DeprecatedObject from './DeprecatedObject'; + +/** + * The ObjectWithDeprecatedFields model module. + * @module model/ObjectWithDeprecatedFields + * @version 1.0.0 + */ +class ObjectWithDeprecatedFields { + /** + * Constructs a new ObjectWithDeprecatedFields. + * @alias module:model/ObjectWithDeprecatedFields + */ + constructor() { + + ObjectWithDeprecatedFields.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a ObjectWithDeprecatedFields from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ObjectWithDeprecatedFields} obj Optional instance to populate. + * @return {module:model/ObjectWithDeprecatedFields} The populated ObjectWithDeprecatedFields instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new ObjectWithDeprecatedFields(); + + if (data.hasOwnProperty('uuid')) { + obj['uuid'] = ApiClient.convertToType(data['uuid'], 'String'); + } + if (data.hasOwnProperty('id')) { + obj['id'] = ApiClient.convertToType(data['id'], 'Number'); + } + if (data.hasOwnProperty('deprecatedRef')) { + obj['deprecatedRef'] = DeprecatedObject.constructFromObject(data['deprecatedRef']); + } + if (data.hasOwnProperty('bars')) { + obj['bars'] = ApiClient.convertToType(data['bars'], ['String']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to ObjectWithDeprecatedFields. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ObjectWithDeprecatedFields. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['uuid'] && !(typeof data['uuid'] === 'string' || data['uuid'] instanceof String)) { + throw new Error("Expected the field `uuid` to be a primitive type in the JSON string but got " + data['uuid']); + } + // validate the optional field `deprecatedRef` + if (data['deprecatedRef']) { // data not null + DeprecatedObject.validateJSON(data['deprecatedRef']); + } + // ensure the json data is an array + if (!Array.isArray(data['bars'])) { + throw new Error("Expected the field `bars` to be an array in the JSON data but got " + data['bars']); + } + + return true; + } + + +} + + + +/** + * @member {String} uuid + */ +ObjectWithDeprecatedFields.prototype['uuid'] = undefined; + +/** + * @member {Number} id + */ +ObjectWithDeprecatedFields.prototype['id'] = undefined; + +/** + * @member {module:model/DeprecatedObject} deprecatedRef + */ +ObjectWithDeprecatedFields.prototype['deprecatedRef'] = undefined; + +/** + * @member {Array.} bars + */ +ObjectWithDeprecatedFields.prototype['bars'] = undefined; + + + + + + +export default ObjectWithDeprecatedFields; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Order.js b/samples/client/petstore/javascript-apollo/src/model/Order.js index 98d7ec7abe..ad586f185d 100644 --- a/samples/client/petstore/javascript-apollo/src/model/Order.js +++ b/samples/client/petstore/javascript-apollo/src/model/Order.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -19,43 +19,8 @@ import ApiClient from '../ApiClient'; * @version 1.0.0 */ class Order { - /** - * @member {Number} id - * @type {Number} - */ - id; - /** - * @member {Number} petId - * @type {Number} - */ - petId; - /** - * @member {Number} quantity - * @type {Number} - */ - quantity; - /** - * @member {Date} shipDate - * @type {Date} - */ - shipDate; - /** - * @member {Order.StatusEnum} status - * @type {Order.StatusEnum} - */ - status; - /** - * @member {Boolean} complete - * @type {Boolean} - * @default false - */ - complete = false; - - - /** * Constructs a new Order. - * An order for a pets from the pet store * @alias module:model/Order */ constructor() { @@ -103,9 +68,62 @@ class Order { } return obj; } + + /** + * Validates the JSON data with respect to Order. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Order. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['status'] && !(typeof data['status'] === 'string' || data['status'] instanceof String)) { + throw new Error("Expected the field `status` to be a primitive type in the JSON string but got " + data['status']); + } + + return true; + } + + } + +/** + * @member {Number} id + */ +Order.prototype['id'] = undefined; + +/** + * @member {Number} petId + */ +Order.prototype['petId'] = undefined; + +/** + * @member {Number} quantity + */ +Order.prototype['quantity'] = undefined; + +/** + * @member {Date} shipDate + */ +Order.prototype['shipDate'] = undefined; + +/** + * Order Status + * @member {module:model/Order.StatusEnum} status + */ +Order.prototype['status'] = undefined; + +/** + * @member {Boolean} complete + * @default false + */ +Order.prototype['complete'] = false; + + + + + /** * Allowed values for the status property. * @enum {String} diff --git a/samples/client/petstore/javascript-apollo/src/model/OuterComposite.js b/samples/client/petstore/javascript-apollo/src/model/OuterComposite.js new file mode 100644 index 0000000000..1c6a3c9a85 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/OuterComposite.js @@ -0,0 +1,103 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The OuterComposite model module. + * @module model/OuterComposite + * @version 1.0.0 + */ +class OuterComposite { + /** + * Constructs a new OuterComposite. + * @alias module:model/OuterComposite + */ + constructor() { + + OuterComposite.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a OuterComposite from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/OuterComposite} obj Optional instance to populate. + * @return {module:model/OuterComposite} The populated OuterComposite instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new OuterComposite(); + + if (data.hasOwnProperty('my_number')) { + obj['my_number'] = ApiClient.convertToType(data['my_number'], 'Number'); + } + if (data.hasOwnProperty('my_string')) { + obj['my_string'] = ApiClient.convertToType(data['my_string'], 'String'); + } + if (data.hasOwnProperty('my_boolean')) { + obj['my_boolean'] = ApiClient.convertToType(data['my_boolean'], 'Boolean'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to OuterComposite. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to OuterComposite. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['my_string'] && !(typeof data['my_string'] === 'string' || data['my_string'] instanceof String)) { + throw new Error("Expected the field `my_string` to be a primitive type in the JSON string but got " + data['my_string']); + } + + return true; + } + + +} + + + +/** + * @member {Number} my_number + */ +OuterComposite.prototype['my_number'] = undefined; + +/** + * @member {String} my_string + */ +OuterComposite.prototype['my_string'] = undefined; + +/** + * @member {Boolean} my_boolean + */ +OuterComposite.prototype['my_boolean'] = undefined; + + + + + + +export default OuterComposite; + diff --git a/samples/client/petstore/javascript-apollo/src/model/OuterEnum.js b/samples/client/petstore/javascript-apollo/src/model/OuterEnum.js new file mode 100644 index 0000000000..12fdff9802 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/OuterEnum.js @@ -0,0 +1,53 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +/** +* Enum class OuterEnum. +* @enum {} +* @readonly +*/ +export default class OuterEnum { + + /** + * value: "placed" + * @const + */ + "placed" = "placed"; + + + /** + * value: "approved" + * @const + */ + "approved" = "approved"; + + + /** + * value: "delivered" + * @const + */ + "delivered" = "delivered"; + + + + /** + * Returns a OuterEnum enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {module:model/OuterEnum} The enum OuterEnum value. + */ + static constructFromObject(object) { + return object; + } +} + diff --git a/samples/client/petstore/javascript-apollo/src/model/OuterEnumDefaultValue.js b/samples/client/petstore/javascript-apollo/src/model/OuterEnumDefaultValue.js new file mode 100644 index 0000000000..a65b1dd0a6 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/OuterEnumDefaultValue.js @@ -0,0 +1,53 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +/** +* Enum class OuterEnumDefaultValue. +* @enum {} +* @readonly +*/ +export default class OuterEnumDefaultValue { + + /** + * value: "placed" + * @const + */ + "placed" = "placed"; + + + /** + * value: "approved" + * @const + */ + "approved" = "approved"; + + + /** + * value: "delivered" + * @const + */ + "delivered" = "delivered"; + + + + /** + * Returns a OuterEnumDefaultValue enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {module:model/OuterEnumDefaultValue} The enum OuterEnumDefaultValue value. + */ + static constructFromObject(object) { + return object; + } +} + diff --git a/samples/client/petstore/javascript-apollo/src/model/OuterEnumInteger.js b/samples/client/petstore/javascript-apollo/src/model/OuterEnumInteger.js new file mode 100644 index 0000000000..b6fc29568a --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/OuterEnumInteger.js @@ -0,0 +1,53 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +/** +* Enum class OuterEnumInteger. +* @enum {} +* @readonly +*/ +export default class OuterEnumInteger { + + /** + * value: 0 + * @const + */ + "0" = 0; + + + /** + * value: 1 + * @const + */ + "1" = 1; + + + /** + * value: 2 + * @const + */ + "2" = 2; + + + + /** + * Returns a OuterEnumInteger enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {module:model/OuterEnumInteger} The enum OuterEnumInteger value. + */ + static constructFromObject(object) { + return object; + } +} + diff --git a/samples/client/petstore/javascript-apollo/src/model/OuterEnumIntegerDefaultValue.js b/samples/client/petstore/javascript-apollo/src/model/OuterEnumIntegerDefaultValue.js new file mode 100644 index 0000000000..86a9d6b946 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/OuterEnumIntegerDefaultValue.js @@ -0,0 +1,53 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +/** +* Enum class OuterEnumIntegerDefaultValue. +* @enum {} +* @readonly +*/ +export default class OuterEnumIntegerDefaultValue { + + /** + * value: 0 + * @const + */ + "0" = 0; + + + /** + * value: 1 + * @const + */ + "1" = 1; + + + /** + * value: 2 + * @const + */ + "2" = 2; + + + + /** + * Returns a OuterEnumIntegerDefaultValue enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {module:model/OuterEnumIntegerDefaultValue} The enum OuterEnumIntegerDefaultValue value. + */ + static constructFromObject(object) { + return object; + } +} + diff --git a/samples/client/petstore/javascript-apollo/src/model/OuterObjectWithEnumProperty.js b/samples/client/petstore/javascript-apollo/src/model/OuterObjectWithEnumProperty.js new file mode 100644 index 0000000000..b9ead482af --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/OuterObjectWithEnumProperty.js @@ -0,0 +1,92 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import OuterEnumInteger from './OuterEnumInteger'; + +/** + * The OuterObjectWithEnumProperty model module. + * @module model/OuterObjectWithEnumProperty + * @version 1.0.0 + */ +class OuterObjectWithEnumProperty { + /** + * Constructs a new OuterObjectWithEnumProperty. + * @alias module:model/OuterObjectWithEnumProperty + * @param value {module:model/OuterEnumInteger} + */ + constructor(value) { + + OuterObjectWithEnumProperty.initialize(this, value); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, value) { + obj['value'] = value; + } + + /** + * Constructs a OuterObjectWithEnumProperty from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/OuterObjectWithEnumProperty} obj Optional instance to populate. + * @return {module:model/OuterObjectWithEnumProperty} The populated OuterObjectWithEnumProperty instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new OuterObjectWithEnumProperty(); + + if (data.hasOwnProperty('value')) { + obj['value'] = OuterEnumInteger.constructFromObject(data['value']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to OuterObjectWithEnumProperty. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to OuterObjectWithEnumProperty. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of OuterObjectWithEnumProperty.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + + return true; + } + + +} + +OuterObjectWithEnumProperty.RequiredProperties = ["value"]; + +/** + * @member {module:model/OuterEnumInteger} value + */ +OuterObjectWithEnumProperty.prototype['value'] = undefined; + + + + + + +export default OuterObjectWithEnumProperty; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Pet.js b/samples/client/petstore/javascript-apollo/src/model/Pet.js index 3bf2f9eef9..cc5239c6a1 100644 --- a/samples/client/petstore/javascript-apollo/src/model/Pet.js +++ b/samples/client/petstore/javascript-apollo/src/model/Pet.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -21,55 +21,11 @@ import Tag from './Tag'; * @version 1.0.0 */ class Pet { - /** - * @member {Number} id - * @type {Number} - */ - id; - /** - * @member {Category} category - * @type {Category} - */ - category; - /** - * @member {String} name - * @type {String} - */ - name; - /** - * @member {Array.} photoUrls - * @type {Array.} - */ - photoUrls; - /** - * @member {Array.} tags - * @type {Array.} - */ - tags; - /** - * @member {Pet.StatusEnum} status - * @type {Pet.StatusEnum} - */ - status; - - - /** * Constructs a new Pet. - * A pet for sale in the pet store * @alias module:model/Pet * @param name {String} - * @param photoUrls {Array.} + * @param photoUrls {Array.} */ constructor(name, photoUrls) { @@ -118,8 +74,88 @@ class Pet { } return obj; } + + /** + * Validates the JSON data with respect to Pet. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Pet. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Pet.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // validate the optional field `category` + if (data['category']) { // data not null + Category.validateJSON(data['category']); + } + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + // ensure the json data is an array + if (!Array.isArray(data['photoUrls'])) { + throw new Error("Expected the field `photoUrls` to be an array in the JSON data but got " + data['photoUrls']); + } + if (data['tags']) { // data not null + // ensure the json data is an array + if (!Array.isArray(data['tags'])) { + throw new Error("Expected the field `tags` to be an array in the JSON data but got " + data['tags']); + } + // validate the optional field `tags` (array) + for (const item of data['tags']) { + Tag.validateJsonObject(item); + }; + } + // ensure the json data is a string + if (data['status'] && !(typeof data['status'] === 'string' || data['status'] instanceof String)) { + throw new Error("Expected the field `status` to be a primitive type in the JSON string but got " + data['status']); + } + + return true; + } + + } +Pet.RequiredProperties = ["name", "photoUrls"]; + +/** + * @member {Number} id + */ +Pet.prototype['id'] = undefined; + +/** + * @member {module:model/Category} category + */ +Pet.prototype['category'] = undefined; + +/** + * @member {String} name + */ +Pet.prototype['name'] = undefined; + +/** + * @member {Array.} photoUrls + */ +Pet.prototype['photoUrls'] = undefined; + +/** + * @member {Array.} tags + */ +Pet.prototype['tags'] = undefined; + +/** + * pet status in the store + * @member {module:model/Pet.StatusEnum} status + */ +Pet.prototype['status'] = undefined; + + + + /** * Allowed values for the status property. diff --git a/samples/client/petstore/javascript-apollo/src/model/Pig.js b/samples/client/petstore/javascript-apollo/src/model/Pig.js new file mode 100644 index 0000000000..da6cdc0765 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Pig.js @@ -0,0 +1,143 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import BasquePig from './BasquePig'; +import DanishPig from './DanishPig'; + +/** + * The Pig model module. + * @module model/Pig + * @version 1.0.0 + */ +class Pig { + /** + * Constructs a new Pig. + * @alias module:model/Pig + * @param {(module:model/BasquePig|module:model/DanishPig)} instance The actual instance to initialize Pig. + */ + constructor(instance = null) { + if (instance === null) { + this.actualInstance = null; + return; + } + var match = 0; + var errorMessages = []; + try { + if (typeof instance === "BasquePig") { + this.actualInstance = instance; + } else { + // plain JS object + // validate the object + BasquePig.validateJSON(instance); // throw an exception if no match + // create BasquePig from JS object + this.actualInstance = BasquePig.constructFromObject(instance); + } + match++; + } catch(err) { + // json data failed to deserialize into BasquePig + errorMessages.push("Failed to construct BasquePig: " + err) + } + + try { + if (typeof instance === "DanishPig") { + this.actualInstance = instance; + } else { + // plain JS object + // validate the object + DanishPig.validateJSON(instance); // throw an exception if no match + // create DanishPig from JS object + this.actualInstance = DanishPig.constructFromObject(instance); + } + match++; + } catch(err) { + // json data failed to deserialize into DanishPig + errorMessages.push("Failed to construct DanishPig: " + err) + } + + if (match > 1) { + throw new Error("Multiple matches found constructing `Pig` with oneOf schemas BasquePig, DanishPig. Input: " + JSON.stringify(instance)); + } else if (match === 0) { + this.actualInstance = null; // clear the actual instance in case there are multiple matches + throw new Error("No match found constructing `Pig` with oneOf schemas BasquePig, DanishPig. Details: " + + errorMessages.join(", ")); + } else { // only 1 match + // the input is valid + } + } + + /** + * Constructs a Pig from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Pig} obj Optional instance to populate. + * @return {module:model/Pig} The populated Pig instance. + */ + static constructFromObject(data, obj) { + return new Pig(data); + } + + /** + * Gets the actaul instance, which can be BasquePig, DanishPig. + * @return {(module:model/BasquePig|module:model/DanishPig)} The actual instance. + */ + getActualInstance() { + return this.actualInstance; + } + + /** + * Sets the actaul instance, which can be BasquePig, DanishPig. + * @param {(module:model/BasquePig|module:model/DanishPig)} obj The actual instance. + */ + setActualInstance(obj) { + this.actualInstance = Pig.constructFromObject(obj).getActualInstance(); + } + + /** + * Returns the JSON representation of the actual intance. + * @return {string} + */ + toJSON = function(){ + return this.getActualInstance(); + } + + /** + * Create an instance of Pig from a JSON string. + * @param {string} json_string JSON string. + * @return {module:model/Pig} An instance of Pig. + */ + static fromJSON = function(json_string){ + return Pig.constructFromObject(JSON.parse(json_string)); + } +} + +/** + * @member {String} className + */ +Pig.prototype['className'] = undefined; + +/** + * @member {String} color + */ +Pig.prototype['color'] = undefined; + +/** + * @member {Number} size + */ +Pig.prototype['size'] = undefined; + + +Pig.OneOf = ["BasquePig", "DanishPig"]; + +export default Pig; + diff --git a/samples/client/petstore/javascript-apollo/src/model/ReadOnlyFirst.js b/samples/client/petstore/javascript-apollo/src/model/ReadOnlyFirst.js new file mode 100644 index 0000000000..b0fa7628f1 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/ReadOnlyFirst.js @@ -0,0 +1,99 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The ReadOnlyFirst model module. + * @module model/ReadOnlyFirst + * @version 1.0.0 + */ +class ReadOnlyFirst { + /** + * Constructs a new ReadOnlyFirst. + * @alias module:model/ReadOnlyFirst + */ + constructor() { + + ReadOnlyFirst.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a ReadOnlyFirst from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ReadOnlyFirst} obj Optional instance to populate. + * @return {module:model/ReadOnlyFirst} The populated ReadOnlyFirst instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new ReadOnlyFirst(); + + if (data.hasOwnProperty('bar')) { + obj['bar'] = ApiClient.convertToType(data['bar'], 'String'); + } + if (data.hasOwnProperty('baz')) { + obj['baz'] = ApiClient.convertToType(data['baz'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to ReadOnlyFirst. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ReadOnlyFirst. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['bar'] && !(typeof data['bar'] === 'string' || data['bar'] instanceof String)) { + throw new Error("Expected the field `bar` to be a primitive type in the JSON string but got " + data['bar']); + } + // ensure the json data is a string + if (data['baz'] && !(typeof data['baz'] === 'string' || data['baz'] instanceof String)) { + throw new Error("Expected the field `baz` to be a primitive type in the JSON string but got " + data['baz']); + } + + return true; + } + + +} + + + +/** + * @member {String} bar + */ +ReadOnlyFirst.prototype['bar'] = undefined; + +/** + * @member {String} baz + */ +ReadOnlyFirst.prototype['baz'] = undefined; + + + + + + +export default ReadOnlyFirst; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Return.js b/samples/client/petstore/javascript-apollo/src/model/Return.js new file mode 100644 index 0000000000..616574b5fc --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/Return.js @@ -0,0 +1,84 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Return model module. + * @module model/Return + * @version 1.0.0 + */ +class Return { + /** + * Constructs a new Return. + * Model for testing reserved words + * @alias module:model/Return + */ + constructor() { + + Return.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a Return from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Return} obj Optional instance to populate. + * @return {module:model/Return} The populated Return instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new Return(); + + if (data.hasOwnProperty('return')) { + obj['return'] = ApiClient.convertToType(data['return'], 'Number'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to Return. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Return. + */ + static validateJSON(data) { + + return true; + } + + +} + + + +/** + * @member {Number} return + */ +Return.prototype['return'] = undefined; + + + + + + +export default Return; + diff --git a/samples/client/petstore/javascript-apollo/src/model/SpecialModelName.js b/samples/client/petstore/javascript-apollo/src/model/SpecialModelName.js new file mode 100644 index 0000000000..b9ece72292 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/src/model/SpecialModelName.js @@ -0,0 +1,83 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The SpecialModelName model module. + * @module model/SpecialModelName + * @version 1.0.0 + */ +class SpecialModelName { + /** + * Constructs a new SpecialModelName. + * @alias module:model/SpecialModelName + */ + constructor() { + + SpecialModelName.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a SpecialModelName from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/SpecialModelName} obj Optional instance to populate. + * @return {module:model/SpecialModelName} The populated SpecialModelName instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new SpecialModelName(); + + if (data.hasOwnProperty('$special[property.name]')) { + obj['$special[property.name]'] = ApiClient.convertToType(data['$special[property.name]'], 'Number'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to SpecialModelName. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to SpecialModelName. + */ + static validateJSON(data) { + + return true; + } + + +} + + + +/** + * @member {Number} $special[property.name] + */ +SpecialModelName.prototype['$special[property.name]'] = undefined; + + + + + + +export default SpecialModelName; + diff --git a/samples/client/petstore/javascript-apollo/src/model/Tag.js b/samples/client/petstore/javascript-apollo/src/model/Tag.js index 5034feec6f..c24706b827 100644 --- a/samples/client/petstore/javascript-apollo/src/model/Tag.js +++ b/samples/client/petstore/javascript-apollo/src/model/Tag.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -19,22 +19,8 @@ import ApiClient from '../ApiClient'; * @version 1.0.0 */ class Tag { - /** - * @member {Number} id - * @type {Number} - */ - id; - /** - * @member {String} name - * @type {String} - */ - name; - - - /** * Constructs a new Tag. - * A tag for a pet * @alias module:model/Tag */ constructor() { @@ -70,9 +56,40 @@ class Tag { } return obj; } + + /** + * Validates the JSON data with respect to Tag. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Tag. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + + return true; + } + + } +/** + * @member {Number} id + */ +Tag.prototype['id'] = undefined; + +/** + * @member {String} name + */ +Tag.prototype['name'] = undefined; + + + + + + export default Tag; diff --git a/samples/client/petstore/javascript-apollo/src/model/User.js b/samples/client/petstore/javascript-apollo/src/model/User.js index 8c3d21f0ed..145851f479 100644 --- a/samples/client/petstore/javascript-apollo/src/model/User.js +++ b/samples/client/petstore/javascript-apollo/src/model/User.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -19,52 +19,8 @@ import ApiClient from '../ApiClient'; * @version 1.0.0 */ class User { - /** - * @member {Number} id - * @type {Number} - */ - id; - /** - * @member {String} username - * @type {String} - */ - username; - /** - * @member {String} firstName - * @type {String} - */ - firstName; - /** - * @member {String} lastName - * @type {String} - */ - lastName; - /** - * @member {String} email - * @type {String} - */ - email; - /** - * @member {String} password - * @type {String} - */ - password; - /** - * @member {String} phone - * @type {String} - */ - phone; - /** - * @member {Number} userStatus - * @type {Number} - */ - userStatus; - - - /** * Constructs a new User. - * A User who is purchasing from the pet store * @alias module:model/User */ constructor() { @@ -118,9 +74,91 @@ class User { } return obj; } + + /** + * Validates the JSON data with respect to User. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to User. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['username'] && !(typeof data['username'] === 'string' || data['username'] instanceof String)) { + throw new Error("Expected the field `username` to be a primitive type in the JSON string but got " + data['username']); + } + // ensure the json data is a string + if (data['firstName'] && !(typeof data['firstName'] === 'string' || data['firstName'] instanceof String)) { + throw new Error("Expected the field `firstName` to be a primitive type in the JSON string but got " + data['firstName']); + } + // ensure the json data is a string + if (data['lastName'] && !(typeof data['lastName'] === 'string' || data['lastName'] instanceof String)) { + throw new Error("Expected the field `lastName` to be a primitive type in the JSON string but got " + data['lastName']); + } + // ensure the json data is a string + if (data['email'] && !(typeof data['email'] === 'string' || data['email'] instanceof String)) { + throw new Error("Expected the field `email` to be a primitive type in the JSON string but got " + data['email']); + } + // ensure the json data is a string + if (data['password'] && !(typeof data['password'] === 'string' || data['password'] instanceof String)) { + throw new Error("Expected the field `password` to be a primitive type in the JSON string but got " + data['password']); + } + // ensure the json data is a string + if (data['phone'] && !(typeof data['phone'] === 'string' || data['phone'] instanceof String)) { + throw new Error("Expected the field `phone` to be a primitive type in the JSON string but got " + data['phone']); + } + + return true; + } + + } +/** + * @member {Number} id + */ +User.prototype['id'] = undefined; + +/** + * @member {String} username + */ +User.prototype['username'] = undefined; + +/** + * @member {String} firstName + */ +User.prototype['firstName'] = undefined; + +/** + * @member {String} lastName + */ +User.prototype['lastName'] = undefined; + +/** + * @member {String} email + */ +User.prototype['email'] = undefined; + +/** + * @member {String} password + */ +User.prototype['password'] = undefined; + +/** + * @member {String} phone + */ +User.prototype['phone'] = undefined; + +/** + * User Status + * @member {Number} userStatus + */ +User.prototype['userStatus'] = undefined; + + + + + + export default User; diff --git a/samples/client/petstore/javascript-apollo/test/api/AnotherFakeApi.spec.js b/samples/client/petstore/javascript-apollo/test/api/AnotherFakeApi.spec.js new file mode 100644 index 0000000000..3212de6605 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/api/AnotherFakeApi.spec.js @@ -0,0 +1,63 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.AnotherFakeApi(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('AnotherFakeApi', function() { + describe('call123testSpecialTags', function() { + it('should call call123testSpecialTags successfully', function(done) { + //uncomment below and update the code to test call123testSpecialTags + //instance.call123testSpecialTags(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/api/DefaultApi.spec.js b/samples/client/petstore/javascript-apollo/test/api/DefaultApi.spec.js new file mode 100644 index 0000000000..34ef8d5c2e --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/api/DefaultApi.spec.js @@ -0,0 +1,63 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.DefaultApi(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('DefaultApi', function() { + describe('fooGet', function() { + it('should call fooGet successfully', function(done) { + //uncomment below and update the code to test fooGet + //instance.fooGet(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/api/FakeApi.spec.js b/samples/client/petstore/javascript-apollo/test/api/FakeApi.spec.js new file mode 100644 index 0000000000..9ecfa421cb --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/api/FakeApi.spec.js @@ -0,0 +1,223 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.FakeApi(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('FakeApi', function() { + describe('fakeHealthGet', function() { + it('should call fakeHealthGet successfully', function(done) { + //uncomment below and update the code to test fakeHealthGet + //instance.fakeHealthGet(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('fakeHttpSignatureTest', function() { + it('should call fakeHttpSignatureTest successfully', function(done) { + //uncomment below and update the code to test fakeHttpSignatureTest + //instance.fakeHttpSignatureTest(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('fakeOuterBooleanSerialize', function() { + it('should call fakeOuterBooleanSerialize successfully', function(done) { + //uncomment below and update the code to test fakeOuterBooleanSerialize + //instance.fakeOuterBooleanSerialize(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('fakeOuterCompositeSerialize', function() { + it('should call fakeOuterCompositeSerialize successfully', function(done) { + //uncomment below and update the code to test fakeOuterCompositeSerialize + //instance.fakeOuterCompositeSerialize(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('fakeOuterNumberSerialize', function() { + it('should call fakeOuterNumberSerialize successfully', function(done) { + //uncomment below and update the code to test fakeOuterNumberSerialize + //instance.fakeOuterNumberSerialize(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('fakeOuterStringSerialize', function() { + it('should call fakeOuterStringSerialize successfully', function(done) { + //uncomment below and update the code to test fakeOuterStringSerialize + //instance.fakeOuterStringSerialize(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('fakePropertyEnumIntegerSerialize', function() { + it('should call fakePropertyEnumIntegerSerialize successfully', function(done) { + //uncomment below and update the code to test fakePropertyEnumIntegerSerialize + //instance.fakePropertyEnumIntegerSerialize(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testBodyWithBinary', function() { + it('should call testBodyWithBinary successfully', function(done) { + //uncomment below and update the code to test testBodyWithBinary + //instance.testBodyWithBinary(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testBodyWithFileSchema', function() { + it('should call testBodyWithFileSchema successfully', function(done) { + //uncomment below and update the code to test testBodyWithFileSchema + //instance.testBodyWithFileSchema(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testBodyWithQueryParams', function() { + it('should call testBodyWithQueryParams successfully', function(done) { + //uncomment below and update the code to test testBodyWithQueryParams + //instance.testBodyWithQueryParams(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testClientModel', function() { + it('should call testClientModel successfully', function(done) { + //uncomment below and update the code to test testClientModel + //instance.testClientModel(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testEndpointParameters', function() { + it('should call testEndpointParameters successfully', function(done) { + //uncomment below and update the code to test testEndpointParameters + //instance.testEndpointParameters(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testEnumParameters', function() { + it('should call testEnumParameters successfully', function(done) { + //uncomment below and update the code to test testEnumParameters + //instance.testEnumParameters(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testGroupParameters', function() { + it('should call testGroupParameters successfully', function(done) { + //uncomment below and update the code to test testGroupParameters + //instance.testGroupParameters(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testInlineAdditionalProperties', function() { + it('should call testInlineAdditionalProperties successfully', function(done) { + //uncomment below and update the code to test testInlineAdditionalProperties + //instance.testInlineAdditionalProperties(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testJsonFormData', function() { + it('should call testJsonFormData successfully', function(done) { + //uncomment below and update the code to test testJsonFormData + //instance.testJsonFormData(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testQueryParameterCollectionFormat', function() { + it('should call testQueryParameterCollectionFormat successfully', function(done) { + //uncomment below and update the code to test testQueryParameterCollectionFormat + //instance.testQueryParameterCollectionFormat(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/api/FakeClassnameTags123Api.spec.js b/samples/client/petstore/javascript-apollo/test/api/FakeClassnameTags123Api.spec.js new file mode 100644 index 0000000000..ebe401b08d --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/api/FakeClassnameTags123Api.spec.js @@ -0,0 +1,63 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.FakeClassnameTags123Api(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('FakeClassnameTags123Api', function() { + describe('testClassname', function() { + it('should call testClassname successfully', function(done) { + //uncomment below and update the code to test testClassname + //instance.testClassname(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/api/PetApi.spec.js b/samples/client/petstore/javascript-apollo/test/api/PetApi.spec.js index c6fb54c625..16591a407d 100644 --- a/samples/client/petstore/javascript-apollo/test/api/PetApi.spec.js +++ b/samples/client/petstore/javascript-apollo/test/api/PetApi.spec.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -11,34 +11,43 @@ * */ -// CommonJS-like environments that support module.exports, like Node. -factory(require('expect.js'), require(process.cwd()+'/src/index')); +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; -'use strict'; + var instance; -var instance; + beforeEach(function() { + instance = new OpenApiPetstore.PetApi(); + }); -beforeEach(function() { - instance = new OpenApiPetstore.PetApi(); -}); + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } -var getProperty = function(object, getter, property) { - // Use getter method if present; otherwise, get the property directly. - if (typeof object[getter] === 'function') - return object[getter](); - else - return object[property]; -} + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } -var setProperty = function(object, setter, property, value) { - // Use setter method if present; otherwise, set the property directly. - if (typeof object[setter] === 'function') - object[setter](value); - else - object[property] = value; -} - -describe('PetApi', function() { + describe('PetApi', function() { describe('addPet', function() { it('should call addPet successfully', function(done) { //uncomment below and update the code to test addPet @@ -119,4 +128,16 @@ describe('PetApi', function() { done(); }); }); -}); \ No newline at end of file + describe('uploadFileWithRequiredFile', function() { + it('should call uploadFileWithRequiredFile successfully', function(done) { + //uncomment below and update the code to test uploadFileWithRequiredFile + //instance.uploadFileWithRequiredFile(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/api/StoreApi.spec.js b/samples/client/petstore/javascript-apollo/test/api/StoreApi.spec.js index 02b07e6b14..2ad9823032 100644 --- a/samples/client/petstore/javascript-apollo/test/api/StoreApi.spec.js +++ b/samples/client/petstore/javascript-apollo/test/api/StoreApi.spec.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -11,34 +11,43 @@ * */ -// CommonJS-like environments that support module.exports, like Node. -factory(require('expect.js'), require(process.cwd()+'/src/index')); +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; -'use strict'; + var instance; -var instance; + beforeEach(function() { + instance = new OpenApiPetstore.StoreApi(); + }); -beforeEach(function() { - instance = new OpenApiPetstore.StoreApi(); -}); + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } -var getProperty = function(object, getter, property) { - // Use getter method if present; otherwise, get the property directly. - if (typeof object[getter] === 'function') - return object[getter](); - else - return object[property]; -} + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } -var setProperty = function(object, setter, property, value) { - // Use setter method if present; otherwise, set the property directly. - if (typeof object[setter] === 'function') - object[setter](value); - else - object[property] = value; -} - -describe('StoreApi', function() { + describe('StoreApi', function() { describe('deleteOrder', function() { it('should call deleteOrder successfully', function(done) { //uncomment below and update the code to test deleteOrder @@ -79,4 +88,6 @@ describe('StoreApi', function() { done(); }); }); -}); \ No newline at end of file + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/api/UserApi.spec.js b/samples/client/petstore/javascript-apollo/test/api/UserApi.spec.js index 0fd8669f38..feab9370b1 100644 --- a/samples/client/petstore/javascript-apollo/test/api/UserApi.spec.js +++ b/samples/client/petstore/javascript-apollo/test/api/UserApi.spec.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -11,34 +11,43 @@ * */ -// CommonJS-like environments that support module.exports, like Node. -factory(require('expect.js'), require(process.cwd()+'/src/index')); +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; -'use strict'; + var instance; -var instance; + beforeEach(function() { + instance = new OpenApiPetstore.UserApi(); + }); -beforeEach(function() { - instance = new OpenApiPetstore.UserApi(); -}); + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } -var getProperty = function(object, getter, property) { - // Use getter method if present; otherwise, get the property directly. - if (typeof object[getter] === 'function') - return object[getter](); - else - return object[property]; -} + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } -var setProperty = function(object, setter, property, value) { - // Use setter method if present; otherwise, set the property directly. - if (typeof object[setter] === 'function') - object[setter](value); - else - object[property] = value; -} - -describe('UserApi', function() { + describe('UserApi', function() { describe('createUser', function() { it('should call createUser successfully', function(done) { //uncomment below and update the code to test createUser @@ -119,4 +128,6 @@ describe('UserApi', function() { done(); }); }); -}); \ No newline at end of file + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/AdditionalPropertiesClass.spec.js b/samples/client/petstore/javascript-apollo/test/model/AdditionalPropertiesClass.spec.js new file mode 100644 index 0000000000..4086c3a614 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/AdditionalPropertiesClass.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.AdditionalPropertiesClass(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('AdditionalPropertiesClass', function() { + it('should create an instance of AdditionalPropertiesClass', function() { + // uncomment below and update the code to test AdditionalPropertiesClass + //var instance = new OpenApiPetstore.AdditionalPropertiesClass(); + //expect(instance).to.be.a(OpenApiPetstore.AdditionalPropertiesClass); + }); + + it('should have the property mapProperty (base name: "map_property")', function() { + // uncomment below and update the code to test the property mapProperty + //var instance = new OpenApiPetstore.AdditionalPropertiesClass(); + //expect(instance).to.be(); + }); + + it('should have the property mapOfMapProperty (base name: "map_of_map_property")', function() { + // uncomment below and update the code to test the property mapOfMapProperty + //var instance = new OpenApiPetstore.AdditionalPropertiesClass(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Animal.spec.js b/samples/client/petstore/javascript-apollo/test/model/Animal.spec.js new file mode 100644 index 0000000000..1fedba274c --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Animal.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Animal(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Animal', function() { + it('should create an instance of Animal', function() { + // uncomment below and update the code to test Animal + //var instance = new OpenApiPetstore.Animal(); + //expect(instance).to.be.a(OpenApiPetstore.Animal); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.Animal(); + //expect(instance).to.be(); + }); + + it('should have the property color (base name: "color")', function() { + // uncomment below and update the code to test the property color + //var instance = new OpenApiPetstore.Animal(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/ApiResponse.spec.js b/samples/client/petstore/javascript-apollo/test/model/ApiResponse.spec.js index a3b74c77ee..47716b7a52 100644 --- a/samples/client/petstore/javascript-apollo/test/model/ApiResponse.spec.js +++ b/samples/client/petstore/javascript-apollo/test/model/ApiResponse.spec.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -50,25 +50,25 @@ describe('ApiResponse', function() { it('should create an instance of ApiResponse', function() { // uncomment below and update the code to test ApiResponse - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be.a(OpenApiPetstore.ApiResponse); }); it('should have the property code (base name: "code")', function() { // uncomment below and update the code to test the property code - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be(); }); it('should have the property type (base name: "type")', function() { // uncomment below and update the code to test the property type - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be(); }); it('should have the property message (base name: "message")', function() { // uncomment below and update the code to test the property message - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-apollo/test/model/ArrayOfArrayOfNumberOnly.spec.js b/samples/client/petstore/javascript-apollo/test/model/ArrayOfArrayOfNumberOnly.spec.js new file mode 100644 index 0000000000..4bdd2cd2cb --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/ArrayOfArrayOfNumberOnly.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('ArrayOfArrayOfNumberOnly', function() { + it('should create an instance of ArrayOfArrayOfNumberOnly', function() { + // uncomment below and update the code to test ArrayOfArrayOfNumberOnly + //var instance = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); + //expect(instance).to.be.a(OpenApiPetstore.ArrayOfArrayOfNumberOnly); + }); + + it('should have the property arrayArrayNumber (base name: "ArrayArrayNumber")', function() { + // uncomment below and update the code to test the property arrayArrayNumber + //var instance = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/ArrayOfNumberOnly.spec.js b/samples/client/petstore/javascript-apollo/test/model/ArrayOfNumberOnly.spec.js new file mode 100644 index 0000000000..a44c1a7ea1 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/ArrayOfNumberOnly.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.ArrayOfNumberOnly(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('ArrayOfNumberOnly', function() { + it('should create an instance of ArrayOfNumberOnly', function() { + // uncomment below and update the code to test ArrayOfNumberOnly + //var instance = new OpenApiPetstore.ArrayOfNumberOnly(); + //expect(instance).to.be.a(OpenApiPetstore.ArrayOfNumberOnly); + }); + + it('should have the property arrayNumber (base name: "ArrayNumber")', function() { + // uncomment below and update the code to test the property arrayNumber + //var instance = new OpenApiPetstore.ArrayOfNumberOnly(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/ArrayTest.spec.js b/samples/client/petstore/javascript-apollo/test/model/ArrayTest.spec.js new file mode 100644 index 0000000000..a6bbf95e21 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/ArrayTest.spec.js @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.ArrayTest(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('ArrayTest', function() { + it('should create an instance of ArrayTest', function() { + // uncomment below and update the code to test ArrayTest + //var instance = new OpenApiPetstore.ArrayTest(); + //expect(instance).to.be.a(OpenApiPetstore.ArrayTest); + }); + + it('should have the property arrayOfString (base name: "array_of_string")', function() { + // uncomment below and update the code to test the property arrayOfString + //var instance = new OpenApiPetstore.ArrayTest(); + //expect(instance).to.be(); + }); + + it('should have the property arrayArrayOfInteger (base name: "array_array_of_integer")', function() { + // uncomment below and update the code to test the property arrayArrayOfInteger + //var instance = new OpenApiPetstore.ArrayTest(); + //expect(instance).to.be(); + }); + + it('should have the property arrayArrayOfModel (base name: "array_array_of_model")', function() { + // uncomment below and update the code to test the property arrayArrayOfModel + //var instance = new OpenApiPetstore.ArrayTest(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/BasquePig.spec.js b/samples/client/petstore/javascript-apollo/test/model/BasquePig.spec.js new file mode 100644 index 0000000000..da5196fc09 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/BasquePig.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.BasquePig(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('BasquePig', function() { + it('should create an instance of BasquePig', function() { + // uncomment below and update the code to test BasquePig + //var instance = new OpenApiPetstore.BasquePig(); + //expect(instance).to.be.a(OpenApiPetstore.BasquePig); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.BasquePig(); + //expect(instance).to.be(); + }); + + it('should have the property color (base name: "color")', function() { + // uncomment below and update the code to test the property color + //var instance = new OpenApiPetstore.BasquePig(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Capitalization.spec.js b/samples/client/petstore/javascript-apollo/test/model/Capitalization.spec.js new file mode 100644 index 0000000000..8f14fd583d --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Capitalization.spec.js @@ -0,0 +1,95 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Capitalization(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Capitalization', function() { + it('should create an instance of Capitalization', function() { + // uncomment below and update the code to test Capitalization + //var instance = new OpenApiPetstore.Capitalization(); + //expect(instance).to.be.a(OpenApiPetstore.Capitalization); + }); + + it('should have the property smallCamel (base name: "smallCamel")', function() { + // uncomment below and update the code to test the property smallCamel + //var instance = new OpenApiPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalCamel (base name: "CapitalCamel")', function() { + // uncomment below and update the code to test the property capitalCamel + //var instance = new OpenApiPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property smallSnake (base name: "small_Snake")', function() { + // uncomment below and update the code to test the property smallSnake + //var instance = new OpenApiPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalSnake (base name: "Capital_Snake")', function() { + // uncomment below and update the code to test the property capitalSnake + //var instance = new OpenApiPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property sCAETHFlowPoints (base name: "SCA_ETH_Flow_Points")', function() { + // uncomment below and update the code to test the property sCAETHFlowPoints + //var instance = new OpenApiPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property ATT_NAME (base name: "ATT_NAME")', function() { + // uncomment below and update the code to test the property ATT_NAME + //var instance = new OpenApiPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Cat.spec.js b/samples/client/petstore/javascript-apollo/test/model/Cat.spec.js new file mode 100644 index 0000000000..a0c3551cbc --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Cat.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Cat(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Cat', function() { + it('should create an instance of Cat', function() { + // uncomment below and update the code to test Cat + //var instance = new OpenApiPetstore.Cat(); + //expect(instance).to.be.a(OpenApiPetstore.Cat); + }); + + it('should have the property declawed (base name: "declawed")', function() { + // uncomment below and update the code to test the property declawed + //var instance = new OpenApiPetstore.Cat(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/CatAllOf.spec.js b/samples/client/petstore/javascript-apollo/test/model/CatAllOf.spec.js new file mode 100644 index 0000000000..7e9f50eadd --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/CatAllOf.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.CatAllOf(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('CatAllOf', function() { + it('should create an instance of CatAllOf', function() { + // uncomment below and update the code to test CatAllOf + //var instance = new OpenApiPetstore.CatAllOf(); + //expect(instance).to.be.a(OpenApiPetstore.CatAllOf); + }); + + it('should have the property declawed (base name: "declawed")', function() { + // uncomment below and update the code to test the property declawed + //var instance = new OpenApiPetstore.CatAllOf(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Category.spec.js b/samples/client/petstore/javascript-apollo/test/model/Category.spec.js index e044cfcc3c..c0e132b026 100644 --- a/samples/client/petstore/javascript-apollo/test/model/Category.spec.js +++ b/samples/client/petstore/javascript-apollo/test/model/Category.spec.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -50,19 +50,19 @@ describe('Category', function() { it('should create an instance of Category', function() { // uncomment below and update the code to test Category - //var instane = new OpenApiPetstore.Category(); + //var instance = new OpenApiPetstore.Category(); //expect(instance).to.be.a(OpenApiPetstore.Category); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Category(); + //var instance = new OpenApiPetstore.Category(); //expect(instance).to.be(); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Category(); + //var instance = new OpenApiPetstore.Category(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-apollo/test/model/ClassModel.spec.js b/samples/client/petstore/javascript-apollo/test/model/ClassModel.spec.js new file mode 100644 index 0000000000..975308a1ce --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/ClassModel.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.ClassModel(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('ClassModel', function() { + it('should create an instance of ClassModel', function() { + // uncomment below and update the code to test ClassModel + //var instance = new OpenApiPetstore.ClassModel(); + //expect(instance).to.be.a(OpenApiPetstore.ClassModel); + }); + + it('should have the property _class (base name: "_class")', function() { + // uncomment below and update the code to test the property _class + //var instance = new OpenApiPetstore.ClassModel(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Client.spec.js b/samples/client/petstore/javascript-apollo/test/model/Client.spec.js new file mode 100644 index 0000000000..c96ccac7e3 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Client.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Client(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Client', function() { + it('should create an instance of Client', function() { + // uncomment below and update the code to test Client + //var instance = new OpenApiPetstore.Client(); + //expect(instance).to.be.a(OpenApiPetstore.Client); + }); + + it('should have the property client (base name: "client")', function() { + // uncomment below and update the code to test the property client + //var instance = new OpenApiPetstore.Client(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Color.spec.js b/samples/client/petstore/javascript-apollo/test/model/Color.spec.js new file mode 100644 index 0000000000..c079e6e511 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Color.spec.js @@ -0,0 +1,59 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Color(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Color', function() { + it('should create an instance of Color', function() { + // uncomment below and update the code to test Color + //var instance = new OpenApiPetstore.Color(); + //expect(instance).to.be.a(OpenApiPetstore.Color); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/DanishPig.spec.js b/samples/client/petstore/javascript-apollo/test/model/DanishPig.spec.js new file mode 100644 index 0000000000..f227291846 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/DanishPig.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.DanishPig(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('DanishPig', function() { + it('should create an instance of DanishPig', function() { + // uncomment below and update the code to test DanishPig + //var instance = new OpenApiPetstore.DanishPig(); + //expect(instance).to.be.a(OpenApiPetstore.DanishPig); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.DanishPig(); + //expect(instance).to.be(); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.DanishPig(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/DeprecatedObject.spec.js b/samples/client/petstore/javascript-apollo/test/model/DeprecatedObject.spec.js new file mode 100644 index 0000000000..072245e26f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/DeprecatedObject.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.DeprecatedObject(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('DeprecatedObject', function() { + it('should create an instance of DeprecatedObject', function() { + // uncomment below and update the code to test DeprecatedObject + //var instance = new OpenApiPetstore.DeprecatedObject(); + //expect(instance).to.be.a(OpenApiPetstore.DeprecatedObject); + }); + + it('should have the property name (base name: "name")', function() { + // uncomment below and update the code to test the property name + //var instance = new OpenApiPetstore.DeprecatedObject(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Dog.spec.js b/samples/client/petstore/javascript-apollo/test/model/Dog.spec.js new file mode 100644 index 0000000000..709cbfa9fd --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Dog.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Dog(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Dog', function() { + it('should create an instance of Dog', function() { + // uncomment below and update the code to test Dog + //var instance = new OpenApiPetstore.Dog(); + //expect(instance).to.be.a(OpenApiPetstore.Dog); + }); + + it('should have the property breed (base name: "breed")', function() { + // uncomment below and update the code to test the property breed + //var instance = new OpenApiPetstore.Dog(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/DogAllOf.spec.js b/samples/client/petstore/javascript-apollo/test/model/DogAllOf.spec.js new file mode 100644 index 0000000000..0bb726203a --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/DogAllOf.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.DogAllOf(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('DogAllOf', function() { + it('should create an instance of DogAllOf', function() { + // uncomment below and update the code to test DogAllOf + //var instance = new OpenApiPetstore.DogAllOf(); + //expect(instance).to.be.a(OpenApiPetstore.DogAllOf); + }); + + it('should have the property breed (base name: "breed")', function() { + // uncomment below and update the code to test the property breed + //var instance = new OpenApiPetstore.DogAllOf(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/EnumArrays.spec.js b/samples/client/petstore/javascript-apollo/test/model/EnumArrays.spec.js new file mode 100644 index 0000000000..bda0e3bcf4 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/EnumArrays.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.EnumArrays(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('EnumArrays', function() { + it('should create an instance of EnumArrays', function() { + // uncomment below and update the code to test EnumArrays + //var instance = new OpenApiPetstore.EnumArrays(); + //expect(instance).to.be.a(OpenApiPetstore.EnumArrays); + }); + + it('should have the property justSymbol (base name: "just_symbol")', function() { + // uncomment below and update the code to test the property justSymbol + //var instance = new OpenApiPetstore.EnumArrays(); + //expect(instance).to.be(); + }); + + it('should have the property arrayEnum (base name: "array_enum")', function() { + // uncomment below and update the code to test the property arrayEnum + //var instance = new OpenApiPetstore.EnumArrays(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/EnumClass.spec.js b/samples/client/petstore/javascript-apollo/test/model/EnumClass.spec.js new file mode 100644 index 0000000000..31924e83d5 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/EnumClass.spec.js @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('EnumClass', function() { + it('should create an instance of EnumClass', function() { + // uncomment below and update the code to test EnumClass + //var instance = new OpenApiPetstore.EnumClass(); + //expect(instance).to.be.a(OpenApiPetstore.EnumClass); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/EnumTest.spec.js b/samples/client/petstore/javascript-apollo/test/model/EnumTest.spec.js new file mode 100644 index 0000000000..ee14bc9b9d --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/EnumTest.spec.js @@ -0,0 +1,107 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.EnumTest(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('EnumTest', function() { + it('should create an instance of EnumTest', function() { + // uncomment below and update the code to test EnumTest + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be.a(OpenApiPetstore.EnumTest); + }); + + it('should have the property enumString (base name: "enum_string")', function() { + // uncomment below and update the code to test the property enumString + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property enumStringRequired (base name: "enum_string_required")', function() { + // uncomment below and update the code to test the property enumStringRequired + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property enumInteger (base name: "enum_integer")', function() { + // uncomment below and update the code to test the property enumInteger + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property enumNumber (base name: "enum_number")', function() { + // uncomment below and update the code to test the property enumNumber + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property outerEnum (base name: "outerEnum")', function() { + // uncomment below and update the code to test the property outerEnum + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property outerEnumInteger (base name: "outerEnumInteger")', function() { + // uncomment below and update the code to test the property outerEnumInteger + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property outerEnumDefaultValue (base name: "outerEnumDefaultValue")', function() { + // uncomment below and update the code to test the property outerEnumDefaultValue + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property outerEnumIntegerDefaultValue (base name: "outerEnumIntegerDefaultValue")', function() { + // uncomment below and update the code to test the property outerEnumIntegerDefaultValue + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/File.spec.js b/samples/client/petstore/javascript-apollo/test/model/File.spec.js new file mode 100644 index 0000000000..ac6fbb3de7 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/File.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.File(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('File', function() { + it('should create an instance of File', function() { + // uncomment below and update the code to test File + //var instance = new OpenApiPetstore.File(); + //expect(instance).to.be.a(OpenApiPetstore.File); + }); + + it('should have the property sourceURI (base name: "sourceURI")', function() { + // uncomment below and update the code to test the property sourceURI + //var instance = new OpenApiPetstore.File(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/FileSchemaTestClass.spec.js b/samples/client/petstore/javascript-apollo/test/model/FileSchemaTestClass.spec.js new file mode 100644 index 0000000000..2f00908972 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/FileSchemaTestClass.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.FileSchemaTestClass(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('FileSchemaTestClass', function() { + it('should create an instance of FileSchemaTestClass', function() { + // uncomment below and update the code to test FileSchemaTestClass + //var instance = new OpenApiPetstore.FileSchemaTestClass(); + //expect(instance).to.be.a(OpenApiPetstore.FileSchemaTestClass); + }); + + it('should have the property file (base name: "file")', function() { + // uncomment below and update the code to test the property file + //var instance = new OpenApiPetstore.FileSchemaTestClass(); + //expect(instance).to.be(); + }); + + it('should have the property files (base name: "files")', function() { + // uncomment below and update the code to test the property files + //var instance = new OpenApiPetstore.FileSchemaTestClass(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Foo.spec.js b/samples/client/petstore/javascript-apollo/test/model/Foo.spec.js new file mode 100644 index 0000000000..81491fc42c --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Foo.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Foo(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Foo', function() { + it('should create an instance of Foo', function() { + // uncomment below and update the code to test Foo + //var instance = new OpenApiPetstore.Foo(); + //expect(instance).to.be.a(OpenApiPetstore.Foo); + }); + + it('should have the property bar (base name: "bar")', function() { + // uncomment below and update the code to test the property bar + //var instance = new OpenApiPetstore.Foo(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/FooGetDefaultResponse.spec.js b/samples/client/petstore/javascript-apollo/test/model/FooGetDefaultResponse.spec.js new file mode 100644 index 0000000000..64c3067380 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/FooGetDefaultResponse.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.FooGetDefaultResponse(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('FooGetDefaultResponse', function() { + it('should create an instance of FooGetDefaultResponse', function() { + // uncomment below and update the code to test FooGetDefaultResponse + //var instance = new OpenApiPetstore.FooGetDefaultResponse(); + //expect(instance).to.be.a(OpenApiPetstore.FooGetDefaultResponse); + }); + + it('should have the property string (base name: "string")', function() { + // uncomment below and update the code to test the property string + //var instance = new OpenApiPetstore.FooGetDefaultResponse(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/FormatTest.spec.js b/samples/client/petstore/javascript-apollo/test/model/FormatTest.spec.js new file mode 100644 index 0000000000..6506a39d85 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/FormatTest.spec.js @@ -0,0 +1,155 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.FormatTest(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('FormatTest', function() { + it('should create an instance of FormatTest', function() { + // uncomment below and update the code to test FormatTest + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be.a(OpenApiPetstore.FormatTest); + }); + + it('should have the property integer (base name: "integer")', function() { + // uncomment below and update the code to test the property integer + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property int32 (base name: "int32")', function() { + // uncomment below and update the code to test the property int32 + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property int64 (base name: "int64")', function() { + // uncomment below and update the code to test the property int64 + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property number (base name: "number")', function() { + // uncomment below and update the code to test the property number + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property _float (base name: "float")', function() { + // uncomment below and update the code to test the property _float + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property _double (base name: "double")', function() { + // uncomment below and update the code to test the property _double + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property decimal (base name: "decimal")', function() { + // uncomment below and update the code to test the property decimal + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property string (base name: "string")', function() { + // uncomment below and update the code to test the property string + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property _byte (base name: "byte")', function() { + // uncomment below and update the code to test the property _byte + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property binary (base name: "binary")', function() { + // uncomment below and update the code to test the property binary + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property date (base name: "date")', function() { + // uncomment below and update the code to test the property date + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property dateTime (base name: "dateTime")', function() { + // uncomment below and update the code to test the property dateTime + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property uuid (base name: "uuid")', function() { + // uncomment below and update the code to test the property uuid + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property password (base name: "password")', function() { + // uncomment below and update the code to test the property password + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property patternWithDigits (base name: "pattern_with_digits")', function() { + // uncomment below and update the code to test the property patternWithDigits + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property patternWithDigitsAndDelimiter (base name: "pattern_with_digits_and_delimiter")', function() { + // uncomment below and update the code to test the property patternWithDigitsAndDelimiter + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/HasOnlyReadOnly.spec.js b/samples/client/petstore/javascript-apollo/test/model/HasOnlyReadOnly.spec.js new file mode 100644 index 0000000000..e9ba0be44f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/HasOnlyReadOnly.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.HasOnlyReadOnly(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('HasOnlyReadOnly', function() { + it('should create an instance of HasOnlyReadOnly', function() { + // uncomment below and update the code to test HasOnlyReadOnly + //var instance = new OpenApiPetstore.HasOnlyReadOnly(); + //expect(instance).to.be.a(OpenApiPetstore.HasOnlyReadOnly); + }); + + it('should have the property bar (base name: "bar")', function() { + // uncomment below and update the code to test the property bar + //var instance = new OpenApiPetstore.HasOnlyReadOnly(); + //expect(instance).to.be(); + }); + + it('should have the property foo (base name: "foo")', function() { + // uncomment below and update the code to test the property foo + //var instance = new OpenApiPetstore.HasOnlyReadOnly(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/HealthCheckResult.spec.js b/samples/client/petstore/javascript-apollo/test/model/HealthCheckResult.spec.js new file mode 100644 index 0000000000..25d9ecd929 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/HealthCheckResult.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.HealthCheckResult(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('HealthCheckResult', function() { + it('should create an instance of HealthCheckResult', function() { + // uncomment below and update the code to test HealthCheckResult + //var instance = new OpenApiPetstore.HealthCheckResult(); + //expect(instance).to.be.a(OpenApiPetstore.HealthCheckResult); + }); + + it('should have the property nullableMessage (base name: "NullableMessage")', function() { + // uncomment below and update the code to test the property nullableMessage + //var instance = new OpenApiPetstore.HealthCheckResult(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/List.spec.js b/samples/client/petstore/javascript-apollo/test/model/List.spec.js new file mode 100644 index 0000000000..675aa82c18 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/List.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.List(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('List', function() { + it('should create an instance of List', function() { + // uncomment below and update the code to test List + //var instance = new OpenApiPetstore.List(); + //expect(instance).to.be.a(OpenApiPetstore.List); + }); + + it('should have the property _123list (base name: "123-list")', function() { + // uncomment below and update the code to test the property _123list + //var instance = new OpenApiPetstore.List(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/MapTest.spec.js b/samples/client/petstore/javascript-apollo/test/model/MapTest.spec.js new file mode 100644 index 0000000000..4e7dabcc21 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/MapTest.spec.js @@ -0,0 +1,83 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.MapTest(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('MapTest', function() { + it('should create an instance of MapTest', function() { + // uncomment below and update the code to test MapTest + //var instance = new OpenApiPetstore.MapTest(); + //expect(instance).to.be.a(OpenApiPetstore.MapTest); + }); + + it('should have the property mapMapOfString (base name: "map_map_of_string")', function() { + // uncomment below and update the code to test the property mapMapOfString + //var instance = new OpenApiPetstore.MapTest(); + //expect(instance).to.be(); + }); + + it('should have the property mapOfEnumString (base name: "map_of_enum_string")', function() { + // uncomment below and update the code to test the property mapOfEnumString + //var instance = new OpenApiPetstore.MapTest(); + //expect(instance).to.be(); + }); + + it('should have the property directMap (base name: "direct_map")', function() { + // uncomment below and update the code to test the property directMap + //var instance = new OpenApiPetstore.MapTest(); + //expect(instance).to.be(); + }); + + it('should have the property indirectMap (base name: "indirect_map")', function() { + // uncomment below and update the code to test the property indirectMap + //var instance = new OpenApiPetstore.MapTest(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js b/samples/client/petstore/javascript-apollo/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js new file mode 100644 index 0000000000..2e72316a90 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('MixedPropertiesAndAdditionalPropertiesClass', function() { + it('should create an instance of MixedPropertiesAndAdditionalPropertiesClass', function() { + // uncomment below and update the code to test MixedPropertiesAndAdditionalPropertiesClass + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //expect(instance).to.be.a(OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass); + }); + + it('should have the property uuid (base name: "uuid")', function() { + // uncomment below and update the code to test the property uuid + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //expect(instance).to.be(); + }); + + it('should have the property dateTime (base name: "dateTime")', function() { + // uncomment below and update the code to test the property dateTime + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //expect(instance).to.be(); + }); + + it('should have the property map (base name: "map")', function() { + // uncomment below and update the code to test the property map + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Model200Response.spec.js b/samples/client/petstore/javascript-apollo/test/model/Model200Response.spec.js new file mode 100644 index 0000000000..7cd4da5e51 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Model200Response.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Model200Response(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Model200Response', function() { + it('should create an instance of Model200Response', function() { + // uncomment below and update the code to test Model200Response + //var instance = new OpenApiPetstore.Model200Response(); + //expect(instance).to.be.a(OpenApiPetstore.Model200Response); + }); + + it('should have the property name (base name: "name")', function() { + // uncomment below and update the code to test the property name + //var instance = new OpenApiPetstore.Model200Response(); + //expect(instance).to.be(); + }); + + it('should have the property _class (base name: "class")', function() { + // uncomment below and update the code to test the property _class + //var instance = new OpenApiPetstore.Model200Response(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Name.spec.js b/samples/client/petstore/javascript-apollo/test/model/Name.spec.js new file mode 100644 index 0000000000..a88057711f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Name.spec.js @@ -0,0 +1,83 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Name(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Name', function() { + it('should create an instance of Name', function() { + // uncomment below and update the code to test Name + //var instance = new OpenApiPetstore.Name(); + //expect(instance).to.be.a(OpenApiPetstore.Name); + }); + + it('should have the property name (base name: "name")', function() { + // uncomment below and update the code to test the property name + //var instance = new OpenApiPetstore.Name(); + //expect(instance).to.be(); + }); + + it('should have the property snakeCase (base name: "snake_case")', function() { + // uncomment below and update the code to test the property snakeCase + //var instance = new OpenApiPetstore.Name(); + //expect(instance).to.be(); + }); + + it('should have the property property (base name: "property")', function() { + // uncomment below and update the code to test the property property + //var instance = new OpenApiPetstore.Name(); + //expect(instance).to.be(); + }); + + it('should have the property _123number (base name: "123Number")', function() { + // uncomment below and update the code to test the property _123number + //var instance = new OpenApiPetstore.Name(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/NestedColor.spec.js b/samples/client/petstore/javascript-apollo/test/model/NestedColor.spec.js new file mode 100644 index 0000000000..00a5813236 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/NestedColor.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.NestedColor(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('NestedColor', function() { + it('should create an instance of NestedColor', function() { + // uncomment below and update the code to test NestedColor + //var instance = new OpenApiPetstore.NestedColor(); + //expect(instance).to.be.a(OpenApiPetstore.NestedColor); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.NestedColor(); + //expect(instance).to.be(); + }); + + it('should have the property nested (base name: "nested")', function() { + // uncomment below and update the code to test the property nested + //var instance = new OpenApiPetstore.NestedColor(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/NestedOneOf.spec.js b/samples/client/petstore/javascript-apollo/test/model/NestedOneOf.spec.js new file mode 100644 index 0000000000..5a54e7fbb0 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/NestedOneOf.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.NestedOneOf(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('NestedOneOf', function() { + it('should create an instance of NestedOneOf', function() { + // uncomment below and update the code to test NestedOneOf + //var instance = new OpenApiPetstore.NestedOneOf(); + //expect(instance).to.be.a(OpenApiPetstore.NestedOneOf); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.NestedOneOf(); + //expect(instance).to.be(); + }); + + it('should have the property nestedPig (base name: "nested_pig")', function() { + // uncomment below and update the code to test the property nestedPig + //var instance = new OpenApiPetstore.NestedOneOf(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/NullableClass.spec.js b/samples/client/petstore/javascript-apollo/test/model/NullableClass.spec.js new file mode 100644 index 0000000000..602a172777 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/NullableClass.spec.js @@ -0,0 +1,131 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.NullableClass(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('NullableClass', function() { + it('should create an instance of NullableClass', function() { + // uncomment below and update the code to test NullableClass + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be.a(OpenApiPetstore.NullableClass); + }); + + it('should have the property integerProp (base name: "integer_prop")', function() { + // uncomment below and update the code to test the property integerProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property numberProp (base name: "number_prop")', function() { + // uncomment below and update the code to test the property numberProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property booleanProp (base name: "boolean_prop")', function() { + // uncomment below and update the code to test the property booleanProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property stringProp (base name: "string_prop")', function() { + // uncomment below and update the code to test the property stringProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property dateProp (base name: "date_prop")', function() { + // uncomment below and update the code to test the property dateProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property datetimeProp (base name: "datetime_prop")', function() { + // uncomment below and update the code to test the property datetimeProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property arrayNullableProp (base name: "array_nullable_prop")', function() { + // uncomment below and update the code to test the property arrayNullableProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property arrayAndItemsNullableProp (base name: "array_and_items_nullable_prop")', function() { + // uncomment below and update the code to test the property arrayAndItemsNullableProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property arrayItemsNullable (base name: "array_items_nullable")', function() { + // uncomment below and update the code to test the property arrayItemsNullable + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property objectNullableProp (base name: "object_nullable_prop")', function() { + // uncomment below and update the code to test the property objectNullableProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property objectAndItemsNullableProp (base name: "object_and_items_nullable_prop")', function() { + // uncomment below and update the code to test the property objectAndItemsNullableProp + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + it('should have the property objectItemsNullable (base name: "object_items_nullable")', function() { + // uncomment below and update the code to test the property objectItemsNullable + //var instance = new OpenApiPetstore.NullableClass(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/NumberOnly.spec.js b/samples/client/petstore/javascript-apollo/test/model/NumberOnly.spec.js new file mode 100644 index 0000000000..a39e26134e --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/NumberOnly.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.NumberOnly(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('NumberOnly', function() { + it('should create an instance of NumberOnly', function() { + // uncomment below and update the code to test NumberOnly + //var instance = new OpenApiPetstore.NumberOnly(); + //expect(instance).to.be.a(OpenApiPetstore.NumberOnly); + }); + + it('should have the property justNumber (base name: "JustNumber")', function() { + // uncomment below and update the code to test the property justNumber + //var instance = new OpenApiPetstore.NumberOnly(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/ObjectWithDeprecatedFields.spec.js b/samples/client/petstore/javascript-apollo/test/model/ObjectWithDeprecatedFields.spec.js new file mode 100644 index 0000000000..b190adcca3 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/ObjectWithDeprecatedFields.spec.js @@ -0,0 +1,83 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.ObjectWithDeprecatedFields(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('ObjectWithDeprecatedFields', function() { + it('should create an instance of ObjectWithDeprecatedFields', function() { + // uncomment below and update the code to test ObjectWithDeprecatedFields + //var instance = new OpenApiPetstore.ObjectWithDeprecatedFields(); + //expect(instance).to.be.a(OpenApiPetstore.ObjectWithDeprecatedFields); + }); + + it('should have the property uuid (base name: "uuid")', function() { + // uncomment below and update the code to test the property uuid + //var instance = new OpenApiPetstore.ObjectWithDeprecatedFields(); + //expect(instance).to.be(); + }); + + it('should have the property id (base name: "id")', function() { + // uncomment below and update the code to test the property id + //var instance = new OpenApiPetstore.ObjectWithDeprecatedFields(); + //expect(instance).to.be(); + }); + + it('should have the property deprecatedRef (base name: "deprecatedRef")', function() { + // uncomment below and update the code to test the property deprecatedRef + //var instance = new OpenApiPetstore.ObjectWithDeprecatedFields(); + //expect(instance).to.be(); + }); + + it('should have the property bars (base name: "bars")', function() { + // uncomment below and update the code to test the property bars + //var instance = new OpenApiPetstore.ObjectWithDeprecatedFields(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Order.spec.js b/samples/client/petstore/javascript-apollo/test/model/Order.spec.js index 15908bf24c..88564e2bc6 100644 --- a/samples/client/petstore/javascript-apollo/test/model/Order.spec.js +++ b/samples/client/petstore/javascript-apollo/test/model/Order.spec.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -50,43 +50,43 @@ describe('Order', function() { it('should create an instance of Order', function() { // uncomment below and update the code to test Order - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be.a(OpenApiPetstore.Order); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property petId (base name: "petId")', function() { // uncomment below and update the code to test the property petId - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property quantity (base name: "quantity")', function() { // uncomment below and update the code to test the property quantity - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property shipDate (base name: "shipDate")', function() { // uncomment below and update the code to test the property shipDate - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property status (base name: "status")', function() { // uncomment below and update the code to test the property status - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property complete (base name: "complete")', function() { // uncomment below and update the code to test the property complete - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-apollo/test/model/OuterComposite.spec.js b/samples/client/petstore/javascript-apollo/test/model/OuterComposite.spec.js new file mode 100644 index 0000000000..1ef9599b2d --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/OuterComposite.spec.js @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.OuterComposite(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('OuterComposite', function() { + it('should create an instance of OuterComposite', function() { + // uncomment below and update the code to test OuterComposite + //var instance = new OpenApiPetstore.OuterComposite(); + //expect(instance).to.be.a(OpenApiPetstore.OuterComposite); + }); + + it('should have the property myNumber (base name: "my_number")', function() { + // uncomment below and update the code to test the property myNumber + //var instance = new OpenApiPetstore.OuterComposite(); + //expect(instance).to.be(); + }); + + it('should have the property myString (base name: "my_string")', function() { + // uncomment below and update the code to test the property myString + //var instance = new OpenApiPetstore.OuterComposite(); + //expect(instance).to.be(); + }); + + it('should have the property myBoolean (base name: "my_boolean")', function() { + // uncomment below and update the code to test the property myBoolean + //var instance = new OpenApiPetstore.OuterComposite(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/OuterEnum.spec.js b/samples/client/petstore/javascript-apollo/test/model/OuterEnum.spec.js new file mode 100644 index 0000000000..16e8d61479 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/OuterEnum.spec.js @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('OuterEnum', function() { + it('should create an instance of OuterEnum', function() { + // uncomment below and update the code to test OuterEnum + //var instance = new OpenApiPetstore.OuterEnum(); + //expect(instance).to.be.a(OpenApiPetstore.OuterEnum); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/OuterEnumDefaultValue.spec.js b/samples/client/petstore/javascript-apollo/test/model/OuterEnumDefaultValue.spec.js new file mode 100644 index 0000000000..213f8de637 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/OuterEnumDefaultValue.spec.js @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('OuterEnumDefaultValue', function() { + it('should create an instance of OuterEnumDefaultValue', function() { + // uncomment below and update the code to test OuterEnumDefaultValue + //var instance = new OpenApiPetstore.OuterEnumDefaultValue(); + //expect(instance).to.be.a(OpenApiPetstore.OuterEnumDefaultValue); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/OuterEnumInteger.spec.js b/samples/client/petstore/javascript-apollo/test/model/OuterEnumInteger.spec.js new file mode 100644 index 0000000000..50c8b78c5f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/OuterEnumInteger.spec.js @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('OuterEnumInteger', function() { + it('should create an instance of OuterEnumInteger', function() { + // uncomment below and update the code to test OuterEnumInteger + //var instance = new OpenApiPetstore.OuterEnumInteger(); + //expect(instance).to.be.a(OpenApiPetstore.OuterEnumInteger); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/OuterEnumIntegerDefaultValue.spec.js b/samples/client/petstore/javascript-apollo/test/model/OuterEnumIntegerDefaultValue.spec.js new file mode 100644 index 0000000000..af3dab3119 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/OuterEnumIntegerDefaultValue.spec.js @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('OuterEnumIntegerDefaultValue', function() { + it('should create an instance of OuterEnumIntegerDefaultValue', function() { + // uncomment below and update the code to test OuterEnumIntegerDefaultValue + //var instance = new OpenApiPetstore.OuterEnumIntegerDefaultValue(); + //expect(instance).to.be.a(OpenApiPetstore.OuterEnumIntegerDefaultValue); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/OuterObjectWithEnumProperty.spec.js b/samples/client/petstore/javascript-apollo/test/model/OuterObjectWithEnumProperty.spec.js new file mode 100644 index 0000000000..9f7afbfd39 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/OuterObjectWithEnumProperty.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.OuterObjectWithEnumProperty(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('OuterObjectWithEnumProperty', function() { + it('should create an instance of OuterObjectWithEnumProperty', function() { + // uncomment below and update the code to test OuterObjectWithEnumProperty + //var instance = new OpenApiPetstore.OuterObjectWithEnumProperty(); + //expect(instance).to.be.a(OpenApiPetstore.OuterObjectWithEnumProperty); + }); + + it('should have the property value (base name: "value")', function() { + // uncomment below and update the code to test the property value + //var instance = new OpenApiPetstore.OuterObjectWithEnumProperty(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Pet.spec.js b/samples/client/petstore/javascript-apollo/test/model/Pet.spec.js index 5b21642808..7b2f4cf121 100644 --- a/samples/client/petstore/javascript-apollo/test/model/Pet.spec.js +++ b/samples/client/petstore/javascript-apollo/test/model/Pet.spec.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -50,43 +50,43 @@ describe('Pet', function() { it('should create an instance of Pet', function() { // uncomment below and update the code to test Pet - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be.a(OpenApiPetstore.Pet); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property category (base name: "category")', function() { // uncomment below and update the code to test the property category - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property photoUrls (base name: "photoUrls")', function() { // uncomment below and update the code to test the property photoUrls - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property tags (base name: "tags")', function() { // uncomment below and update the code to test the property tags - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property status (base name: "status")', function() { // uncomment below and update the code to test the property status - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-apollo/test/model/Pig.spec.js b/samples/client/petstore/javascript-apollo/test/model/Pig.spec.js new file mode 100644 index 0000000000..994a590578 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Pig.spec.js @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Pig(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Pig', function() { + it('should create an instance of Pig', function() { + // uncomment below and update the code to test Pig + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be.a(OpenApiPetstore.Pig); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be(); + }); + + it('should have the property color (base name: "color")', function() { + // uncomment below and update the code to test the property color + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be(); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/ReadOnlyFirst.spec.js b/samples/client/petstore/javascript-apollo/test/model/ReadOnlyFirst.spec.js new file mode 100644 index 0000000000..a9be118d2f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/ReadOnlyFirst.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.ReadOnlyFirst(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('ReadOnlyFirst', function() { + it('should create an instance of ReadOnlyFirst', function() { + // uncomment below and update the code to test ReadOnlyFirst + //var instance = new OpenApiPetstore.ReadOnlyFirst(); + //expect(instance).to.be.a(OpenApiPetstore.ReadOnlyFirst); + }); + + it('should have the property bar (base name: "bar")', function() { + // uncomment below and update the code to test the property bar + //var instance = new OpenApiPetstore.ReadOnlyFirst(); + //expect(instance).to.be(); + }); + + it('should have the property baz (base name: "baz")', function() { + // uncomment below and update the code to test the property baz + //var instance = new OpenApiPetstore.ReadOnlyFirst(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Return.spec.js b/samples/client/petstore/javascript-apollo/test/model/Return.spec.js new file mode 100644 index 0000000000..75aae37c74 --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/Return.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Return(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Return', function() { + it('should create an instance of Return', function() { + // uncomment below and update the code to test Return + //var instance = new OpenApiPetstore.Return(); + //expect(instance).to.be.a(OpenApiPetstore.Return); + }); + + it('should have the property _return (base name: "return")', function() { + // uncomment below and update the code to test the property _return + //var instance = new OpenApiPetstore.Return(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/SpecialModelName.spec.js b/samples/client/petstore/javascript-apollo/test/model/SpecialModelName.spec.js new file mode 100644 index 0000000000..8b6e95c76f --- /dev/null +++ b/samples/client/petstore/javascript-apollo/test/model/SpecialModelName.spec.js @@ -0,0 +1,65 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.SpecialModelName(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('SpecialModelName', function() { + it('should create an instance of SpecialModelName', function() { + // uncomment below and update the code to test SpecialModelName + //var instance = new OpenApiPetstore.SpecialModelName(); + //expect(instance).to.be.a(OpenApiPetstore.SpecialModelName); + }); + + it('should have the property specialPropertyName (base name: "$special[property.name]")', function() { + // uncomment below and update the code to test the property specialPropertyName + //var instance = new OpenApiPetstore.SpecialModelName(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-apollo/test/model/Tag.spec.js b/samples/client/petstore/javascript-apollo/test/model/Tag.spec.js index 2a4de4f117..7832664c4f 100644 --- a/samples/client/petstore/javascript-apollo/test/model/Tag.spec.js +++ b/samples/client/petstore/javascript-apollo/test/model/Tag.spec.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -50,19 +50,19 @@ describe('Tag', function() { it('should create an instance of Tag', function() { // uncomment below and update the code to test Tag - //var instane = new OpenApiPetstore.Tag(); + //var instance = new OpenApiPetstore.Tag(); //expect(instance).to.be.a(OpenApiPetstore.Tag); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Tag(); + //var instance = new OpenApiPetstore.Tag(); //expect(instance).to.be(); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Tag(); + //var instance = new OpenApiPetstore.Tag(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-apollo/test/model/User.spec.js b/samples/client/petstore/javascript-apollo/test/model/User.spec.js index b089f3f38f..44d541dc64 100644 --- a/samples/client/petstore/javascript-apollo/test/model/User.spec.js +++ b/samples/client/petstore/javascript-apollo/test/model/User.spec.js @@ -1,6 +1,6 @@ /** * 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. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * @@ -50,55 +50,55 @@ describe('User', function() { it('should create an instance of User', function() { // uncomment below and update the code to test User - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be.a(OpenApiPetstore.User); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property username (base name: "username")', function() { // uncomment below and update the code to test the property username - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property firstName (base name: "firstName")', function() { // uncomment below and update the code to test the property firstName - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property lastName (base name: "lastName")', function() { // uncomment below and update the code to test the property lastName - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property email (base name: "email")', function() { // uncomment below and update the code to test the property email - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property password (base name: "password")', function() { // uncomment below and update the code to test the property password - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property phone (base name: "phone")', function() { // uncomment below and update the code to test the property phone - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property userStatus (base name: "userStatus")', function() { // uncomment below and update the code to test the property userStatus - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/.gitignore b/samples/client/petstore/javascript-es6/.gitignore index e920c16718..6a7d6d8ef6 100644 --- a/samples/client/petstore/javascript-es6/.gitignore +++ b/samples/client/petstore/javascript-es6/.gitignore @@ -2,32 +2,129 @@ logs *.log npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed +*.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage +*.lcov -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt +# Bower dependency directory (https://bower.io/) +bower_components + # node-waf configuration .lock-wscript -# Compiled binary addons (http://nodejs.org/api/addons.html) +# Compiled binary addons (https://nodejs.org/api/addons.html) build/Release -# Dependency directory -node_modules +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo # Optional npm cache directory .npm +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + # Optional REPL history .node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp +.cache + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* \ No newline at end of file diff --git a/samples/client/petstore/javascript-es6/.openapi-generator-ignore b/samples/client/petstore/javascript-es6/.openapi-generator-ignore index c5fa491b4c..7484ee590a 100644 --- a/samples/client/petstore/javascript-es6/.openapi-generator-ignore +++ b/samples/client/petstore/javascript-es6/.openapi-generator-ignore @@ -1,11 +1,11 @@ -# Swagger Codegen Ignore -# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen +# 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 Swagger Codgen to ignore just this file by uncommenting the following line: +# 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 (*): diff --git a/samples/client/petstore/javascript-es6/.openapi-generator/FILES b/samples/client/petstore/javascript-es6/.openapi-generator/FILES index 0440bb2716..f83260318a 100644 --- a/samples/client/petstore/javascript-es6/.openapi-generator/FILES +++ b/samples/client/petstore/javascript-es6/.openapi-generator/FILES @@ -9,12 +9,15 @@ docs/ApiResponse.md docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfNumberOnly.md docs/ArrayTest.md +docs/BasquePig.md docs/Capitalization.md docs/Cat.md docs/CatAllOf.md docs/Category.md docs/ClassModel.md docs/Client.md +docs/Color.md +docs/DanishPig.md docs/DefaultApi.md docs/DeprecatedObject.md docs/Dog.md @@ -36,6 +39,8 @@ docs/MapTest.md docs/MixedPropertiesAndAdditionalPropertiesClass.md docs/Model200Response.md docs/Name.md +docs/NestedColor.md +docs/NestedOneOf.md docs/NullableClass.md docs/NumberOnly.md docs/ObjectWithDeprecatedFields.md @@ -48,6 +53,7 @@ docs/OuterEnumIntegerDefaultValue.md docs/OuterObjectWithEnumProperty.md docs/Pet.md docs/PetApi.md +docs/Pig.md docs/ReadOnlyFirst.md docs/Return.md docs/SpecialModelName.md @@ -73,12 +79,15 @@ src/model/ApiResponse.js src/model/ArrayOfArrayOfNumberOnly.js src/model/ArrayOfNumberOnly.js src/model/ArrayTest.js +src/model/BasquePig.js src/model/Capitalization.js src/model/Cat.js src/model/CatAllOf.js src/model/Category.js src/model/ClassModel.js src/model/Client.js +src/model/Color.js +src/model/DanishPig.js src/model/DeprecatedObject.js src/model/Dog.js src/model/DogAllOf.js @@ -97,6 +106,8 @@ src/model/MapTest.js src/model/MixedPropertiesAndAdditionalPropertiesClass.js src/model/Model200Response.js src/model/Name.js +src/model/NestedColor.js +src/model/NestedOneOf.js src/model/NullableClass.js src/model/NumberOnly.js src/model/ObjectWithDeprecatedFields.js @@ -108,6 +119,7 @@ src/model/OuterEnumInteger.js src/model/OuterEnumIntegerDefaultValue.js src/model/OuterObjectWithEnumProperty.js src/model/Pet.js +src/model/Pig.js src/model/ReadOnlyFirst.js src/model/Return.js src/model/SpecialModelName.js diff --git a/samples/client/petstore/javascript-es6/README.md b/samples/client/petstore/javascript-es6/README.md index 2f7325ceeb..a6a90be126 100644 --- a/samples/client/petstore/javascript-es6/README.md +++ b/samples/client/petstore/javascript-es6/README.md @@ -171,12 +171,15 @@ Class | Method | HTTP request | Description - [OpenApiPetstore.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [OpenApiPetstore.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [OpenApiPetstore.ArrayTest](docs/ArrayTest.md) + - [OpenApiPetstore.BasquePig](docs/BasquePig.md) - [OpenApiPetstore.Capitalization](docs/Capitalization.md) - [OpenApiPetstore.Cat](docs/Cat.md) - [OpenApiPetstore.CatAllOf](docs/CatAllOf.md) - [OpenApiPetstore.Category](docs/Category.md) - [OpenApiPetstore.ClassModel](docs/ClassModel.md) - [OpenApiPetstore.Client](docs/Client.md) + - [OpenApiPetstore.Color](docs/Color.md) + - [OpenApiPetstore.DanishPig](docs/DanishPig.md) - [OpenApiPetstore.DeprecatedObject](docs/DeprecatedObject.md) - [OpenApiPetstore.Dog](docs/Dog.md) - [OpenApiPetstore.DogAllOf](docs/DogAllOf.md) @@ -195,6 +198,8 @@ Class | Method | HTTP request | Description - [OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [OpenApiPetstore.Model200Response](docs/Model200Response.md) - [OpenApiPetstore.Name](docs/Name.md) + - [OpenApiPetstore.NestedColor](docs/NestedColor.md) + - [OpenApiPetstore.NestedOneOf](docs/NestedOneOf.md) - [OpenApiPetstore.NullableClass](docs/NullableClass.md) - [OpenApiPetstore.NumberOnly](docs/NumberOnly.md) - [OpenApiPetstore.ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) @@ -206,6 +211,7 @@ Class | Method | HTTP request | Description - [OpenApiPetstore.OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) - [OpenApiPetstore.OuterObjectWithEnumProperty](docs/OuterObjectWithEnumProperty.md) - [OpenApiPetstore.Pet](docs/Pet.md) + - [OpenApiPetstore.Pig](docs/Pig.md) - [OpenApiPetstore.ReadOnlyFirst](docs/ReadOnlyFirst.md) - [OpenApiPetstore.Return](docs/Return.md) - [OpenApiPetstore.SpecialModelName](docs/SpecialModelName.md) diff --git a/samples/client/petstore/javascript-es6/docs/AnimalFarm.md b/samples/client/petstore/javascript-es6/docs/AnimalFarm.md deleted file mode 100644 index ab153513ca..0000000000 --- a/samples/client/petstore/javascript-es6/docs/AnimalFarm.md +++ /dev/null @@ -1,7 +0,0 @@ -# OpenApiPetstore.AnimalFarm - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - diff --git a/samples/client/petstore/javascript-es6/docs/BasquePig.md b/samples/client/petstore/javascript-es6/docs/BasquePig.md new file mode 100644 index 0000000000..77d1e74bc7 --- /dev/null +++ b/samples/client/petstore/javascript-es6/docs/BasquePig.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.BasquePig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | + + diff --git a/samples/client/petstore/javascript-es6/docs/Color.md b/samples/client/petstore/javascript-es6/docs/Color.md new file mode 100644 index 0000000000..5f0e6f0dfb --- /dev/null +++ b/samples/client/petstore/javascript-es6/docs/Color.md @@ -0,0 +1,8 @@ +# OpenApiPetstore.Color + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/javascript-es6/docs/DanishPig.md b/samples/client/petstore/javascript-es6/docs/DanishPig.md new file mode 100644 index 0000000000..7de3e60db3 --- /dev/null +++ b/samples/client/petstore/javascript-es6/docs/DanishPig.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.DanishPig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**size** | **Number** | | + + diff --git a/samples/client/petstore/javascript-es6/docs/Fake_classname_tags123Api.md b/samples/client/petstore/javascript-es6/docs/Fake_classname_tags123Api.md deleted file mode 100644 index dfe4d0735f..0000000000 --- a/samples/client/petstore/javascript-es6/docs/Fake_classname_tags123Api.md +++ /dev/null @@ -1,59 +0,0 @@ -# SwaggerPetstore.Fake_classname_tags123Api - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**testClassname**](Fake_classname_tags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case - - - -# **testClassname** -> Client testClassname(body) - -To test class name in snake case - -### Example -```javascript -import SwaggerPetstore from 'swagger_petstore'; -let defaultClient = SwaggerPetstore.ApiClient.instance; - -// Configure API key authorization: api_key_query -let api_key_query = defaultClient.authentications['api_key_query']; -api_key_query.apiKey = 'YOUR API KEY'; -// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) -//api_key_query.apiKeyPrefix = 'Token'; - -let apiInstance = new SwaggerPetstore.Fake_classname_tags123Api(); - -let body = new SwaggerPetstore.Client(); // Client | client model - - -apiInstance.testClassname(body, (error, data, response) => { - if (error) { - console.error(error); - } else { - console.log('API called successfully. Returned data: ' + data); - } -}); -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | - -### Return type - -[**Client**](Client.md) - -### Authorization - -[api_key_query](../README.md#api_key_query) - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - diff --git a/samples/client/petstore/javascript-es6/docs/InlineObject.md b/samples/client/petstore/javascript-es6/docs/InlineObject.md deleted file mode 100644 index 529c032d7a..0000000000 --- a/samples/client/petstore/javascript-es6/docs/InlineObject.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.InlineObject - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | Updated name of the pet | [optional] -**status** | **String** | Updated status of the pet | [optional] - - diff --git a/samples/client/petstore/javascript-es6/docs/InlineObject1.md b/samples/client/petstore/javascript-es6/docs/InlineObject1.md deleted file mode 100644 index bd2fcd57a2..0000000000 --- a/samples/client/petstore/javascript-es6/docs/InlineObject1.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.InlineObject1 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**file** | **File** | file to upload | [optional] - - diff --git a/samples/client/petstore/javascript-es6/docs/InlineObject2.md b/samples/client/petstore/javascript-es6/docs/InlineObject2.md deleted file mode 100644 index 7d703a9086..0000000000 --- a/samples/client/petstore/javascript-es6/docs/InlineObject2.md +++ /dev/null @@ -1,34 +0,0 @@ -# OpenApiPetstore.InlineObject2 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enumFormStringArray** | **[String]** | Form parameter enum test (string array) | [optional] -**enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to '-efg'] - - - -## Enum: [EnumFormStringArrayEnum] - - -* `GREATER_THAN` (value: `">"`) - -* `DOLLAR` (value: `"$"`) - - - - - -## Enum: EnumFormStringEnum - - -* `_abc` (value: `"_abc"`) - -* `-efg` (value: `"-efg"`) - -* `(xyz)` (value: `"(xyz)"`) - - - - diff --git a/samples/client/petstore/javascript-es6/docs/InlineObject3.md b/samples/client/petstore/javascript-es6/docs/InlineObject3.md deleted file mode 100644 index ec8980b728..0000000000 --- a/samples/client/petstore/javascript-es6/docs/InlineObject3.md +++ /dev/null @@ -1,22 +0,0 @@ -# OpenApiPetstore.InlineObject3 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | **Number** | None | [optional] -**int32** | **Number** | None | [optional] -**int64** | **Number** | None | [optional] -**_number** | **Number** | None | -**_float** | **Number** | None | [optional] -**_double** | **Number** | None | -**_string** | **String** | None | [optional] -**patternWithoutDelimiter** | **String** | None | -**_byte** | **Blob** | None | -**binary** | **File** | None | [optional] -**_date** | **Date** | None | [optional] -**dateTime** | **Date** | None | [optional] -**password** | **String** | None | [optional] -**callback** | **String** | None | [optional] - - diff --git a/samples/client/petstore/javascript-es6/docs/InlineObject4.md b/samples/client/petstore/javascript-es6/docs/InlineObject4.md deleted file mode 100644 index 07ce4b0cac..0000000000 --- a/samples/client/petstore/javascript-es6/docs/InlineObject4.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.InlineObject4 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**param** | **String** | field1 | -**param2** | **String** | field2 | - - diff --git a/samples/client/petstore/javascript-es6/docs/InlineObject5.md b/samples/client/petstore/javascript-es6/docs/InlineObject5.md deleted file mode 100644 index 16547e7f52..0000000000 --- a/samples/client/petstore/javascript-es6/docs/InlineObject5.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.InlineObject5 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**requiredFile** | **File** | file to upload | - - diff --git a/samples/client/petstore/javascript-es6/docs/InlineResponseDefault.md b/samples/client/petstore/javascript-es6/docs/InlineResponseDefault.md deleted file mode 100644 index 3bd01f8f7d..0000000000 --- a/samples/client/petstore/javascript-es6/docs/InlineResponseDefault.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**string** | [**Foo**](Foo.md) | | [optional] - - diff --git a/samples/client/petstore/javascript-es6/docs/ModelReturn.md b/samples/client/petstore/javascript-es6/docs/ModelReturn.md deleted file mode 100644 index c93601692f..0000000000 --- a/samples/client/petstore/javascript-es6/docs/ModelReturn.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.ModelReturn - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**_return** | **Number** | | [optional] - - diff --git a/samples/client/petstore/javascript-es6/docs/NestedColor.md b/samples/client/petstore/javascript-es6/docs/NestedColor.md new file mode 100644 index 0000000000..aea6b44494 --- /dev/null +++ b/samples/client/petstore/javascript-es6/docs/NestedColor.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.NestedColor + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**size** | **Number** | | [optional] +**nested** | [**Color**](Color.md) | | [optional] + + diff --git a/samples/client/petstore/javascript-es6/docs/NestedOneOf.md b/samples/client/petstore/javascript-es6/docs/NestedOneOf.md new file mode 100644 index 0000000000..b5228e89c7 --- /dev/null +++ b/samples/client/petstore/javascript-es6/docs/NestedOneOf.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.NestedOneOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**size** | **Number** | | [optional] +**nestedPig** | [**Pig**](Pig.md) | | [optional] + + diff --git a/samples/client/petstore/javascript-es6/docs/OuterBoolean.md b/samples/client/petstore/javascript-es6/docs/OuterBoolean.md deleted file mode 100644 index 61ea0d5661..0000000000 --- a/samples/client/petstore/javascript-es6/docs/OuterBoolean.md +++ /dev/null @@ -1,7 +0,0 @@ -# SwaggerPetstore.OuterBoolean - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - diff --git a/samples/client/petstore/javascript-es6/docs/OuterNumber.md b/samples/client/petstore/javascript-es6/docs/OuterNumber.md deleted file mode 100644 index efbbfa8353..0000000000 --- a/samples/client/petstore/javascript-es6/docs/OuterNumber.md +++ /dev/null @@ -1,7 +0,0 @@ -# SwaggerPetstore.OuterNumber - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - diff --git a/samples/client/petstore/javascript-es6/docs/OuterString.md b/samples/client/petstore/javascript-es6/docs/OuterString.md deleted file mode 100644 index 22eba5351a..0000000000 --- a/samples/client/petstore/javascript-es6/docs/OuterString.md +++ /dev/null @@ -1,7 +0,0 @@ -# SwaggerPetstore.OuterString - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - diff --git a/samples/client/petstore/javascript-es6/docs/Pig.md b/samples/client/petstore/javascript-es6/docs/Pig.md new file mode 100644 index 0000000000..a94e1687cc --- /dev/null +++ b/samples/client/petstore/javascript-es6/docs/Pig.md @@ -0,0 +1,11 @@ +# OpenApiPetstore.Pig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | +**size** | **Number** | | + + diff --git a/samples/client/petstore/javascript-es6/docs/SingleRefType.md b/samples/client/petstore/javascript-es6/docs/SingleRefType.md deleted file mode 100644 index 6a7ac770c2..0000000000 --- a/samples/client/petstore/javascript-es6/docs/SingleRefType.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.SingleRefType - -## Enum - - -* `admin` (value: `"admin"`) - -* `user` (value: `"user"`) - - diff --git a/samples/client/petstore/javascript-es6/docs/StringBooleanMap.md b/samples/client/petstore/javascript-es6/docs/StringBooleanMap.md deleted file mode 100644 index 195a7d5767..0000000000 --- a/samples/client/petstore/javascript-es6/docs/StringBooleanMap.md +++ /dev/null @@ -1,7 +0,0 @@ -# OpenApiPetstore.StringBooleanMap - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - diff --git a/samples/client/petstore/javascript-es6/docs/TypeHolderDefault.md b/samples/client/petstore/javascript-es6/docs/TypeHolderDefault.md deleted file mode 100644 index e726bb0535..0000000000 --- a/samples/client/petstore/javascript-es6/docs/TypeHolderDefault.md +++ /dev/null @@ -1,12 +0,0 @@ -# OpenApiPetstore.TypeHolderDefault - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**stringItem** | **String** | | [default to 'what'] -**numberItem** | **Number** | | -**integerItem** | **Number** | | -**boolItem** | **Boolean** | | [default to true] -**arrayItem** | **[Number]** | | - - diff --git a/samples/client/petstore/javascript-es6/docs/TypeHolderExample.md b/samples/client/petstore/javascript-es6/docs/TypeHolderExample.md deleted file mode 100644 index 925271cb6c..0000000000 --- a/samples/client/petstore/javascript-es6/docs/TypeHolderExample.md +++ /dev/null @@ -1,12 +0,0 @@ -# OpenApiPetstore.TypeHolderExample - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**stringItem** | **String** | | -**numberItem** | **Number** | | -**integerItem** | **Number** | | -**boolItem** | **Boolean** | | -**arrayItem** | **[Number]** | | - - diff --git a/samples/client/petstore/javascript-es6/package.json b/samples/client/petstore/javascript-es6/package.json index dfa8bf720f..e457ebe7e0 100644 --- a/samples/client/petstore/javascript-es6/package.json +++ b/samples/client/petstore/javascript-es6/package.json @@ -1,7 +1,7 @@ { "name": "open_api_petstore", "version": "1.0.0", - "description": "This_spec_is_mainly_for_testing_Petstore_server_and_contains_fake_endpoints_models__Please_do_not_use_this_for_any_other_purpose__Special_characters___", + "description": "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\", "license": "Apache-2.0", "main": "dist/index.js", "scripts": { diff --git a/samples/client/petstore/javascript-es6/src/index.js b/samples/client/petstore/javascript-es6/src/index.js index a75a817c26..a95a17ec1b 100644 --- a/samples/client/petstore/javascript-es6/src/index.js +++ b/samples/client/petstore/javascript-es6/src/index.js @@ -19,12 +19,15 @@ import ApiResponse from './model/ApiResponse'; import ArrayOfArrayOfNumberOnly from './model/ArrayOfArrayOfNumberOnly'; import ArrayOfNumberOnly from './model/ArrayOfNumberOnly'; import ArrayTest from './model/ArrayTest'; +import BasquePig from './model/BasquePig'; import Capitalization from './model/Capitalization'; import Cat from './model/Cat'; import CatAllOf from './model/CatAllOf'; import Category from './model/Category'; import ClassModel from './model/ClassModel'; import Client from './model/Client'; +import Color from './model/Color'; +import DanishPig from './model/DanishPig'; import DeprecatedObject from './model/DeprecatedObject'; import Dog from './model/Dog'; import DogAllOf from './model/DogAllOf'; @@ -43,6 +46,8 @@ import MapTest from './model/MapTest'; import MixedPropertiesAndAdditionalPropertiesClass from './model/MixedPropertiesAndAdditionalPropertiesClass'; import Model200Response from './model/Model200Response'; import Name from './model/Name'; +import NestedColor from './model/NestedColor'; +import NestedOneOf from './model/NestedOneOf'; import NullableClass from './model/NullableClass'; import NumberOnly from './model/NumberOnly'; import ObjectWithDeprecatedFields from './model/ObjectWithDeprecatedFields'; @@ -54,6 +59,7 @@ import OuterEnumInteger from './model/OuterEnumInteger'; import OuterEnumIntegerDefaultValue from './model/OuterEnumIntegerDefaultValue'; import OuterObjectWithEnumProperty from './model/OuterObjectWithEnumProperty'; import Pet from './model/Pet'; +import Pig from './model/Pig'; import ReadOnlyFirst from './model/ReadOnlyFirst'; import Return from './model/Return'; import SpecialModelName from './model/SpecialModelName'; @@ -69,7 +75,7 @@ import UserApi from './api/UserApi'; /** -* This_spec_is_mainly_for_testing_Petstore_server_and_contains_fake_endpoints_models__Please_do_not_use_this_for_any_other_purpose__Special_characters___.
        +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\.
        * The index module provides access to constructors for all the classes which comprise the public API. *

        * An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: @@ -142,6 +148,12 @@ export { */ ArrayTest, + /** + * The BasquePig model constructor. + * @property {module:model/BasquePig} + */ + BasquePig, + /** * The Capitalization model constructor. * @property {module:model/Capitalization} @@ -178,6 +190,18 @@ export { */ Client, + /** + * The Color model constructor. + * @property {module:model/Color} + */ + Color, + + /** + * The DanishPig model constructor. + * @property {module:model/DanishPig} + */ + DanishPig, + /** * The DeprecatedObject model constructor. * @property {module:model/DeprecatedObject} @@ -286,6 +310,18 @@ export { */ Name, + /** + * The NestedColor model constructor. + * @property {module:model/NestedColor} + */ + NestedColor, + + /** + * The NestedOneOf model constructor. + * @property {module:model/NestedOneOf} + */ + NestedOneOf, + /** * The NullableClass model constructor. * @property {module:model/NullableClass} @@ -352,6 +388,12 @@ export { */ Pet, + /** + * The Pig model constructor. + * @property {module:model/Pig} + */ + Pig, + /** * The ReadOnlyFirst model constructor. * @property {module:model/ReadOnlyFirst} diff --git a/samples/client/petstore/javascript-es6/src/model/AdditionalPropertiesClass.js b/samples/client/petstore/javascript-es6/src/model/AdditionalPropertiesClass.js index d6d83cca28..3849c00c59 100644 --- a/samples/client/petstore/javascript-es6/src/model/AdditionalPropertiesClass.js +++ b/samples/client/petstore/javascript-es6/src/model/AdditionalPropertiesClass.js @@ -57,9 +57,21 @@ class AdditionalPropertiesClass { return obj; } + /** + * Validates the JSON data with respect to AdditionalPropertiesClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to AdditionalPropertiesClass. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Object.} map_property */ diff --git a/samples/client/petstore/javascript-es6/src/model/Animal.js b/samples/client/petstore/javascript-es6/src/model/Animal.js index 7cb9017160..27c6975b59 100644 --- a/samples/client/petstore/javascript-es6/src/model/Animal.js +++ b/samples/client/petstore/javascript-es6/src/model/Animal.js @@ -59,9 +59,35 @@ class Animal { return obj; } + /** + * Validates the JSON data with respect to Animal. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Animal. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Animal.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['className'] && !(typeof data['className'] === 'string' || data['className'] instanceof String)) { + throw new Error("Expected the field `className` to be a primitive type in the JSON string but got " + data['className']); + } + // ensure the json data is a string + if (data['color'] && !(typeof data['color'] === 'string' || data['color'] instanceof String)) { + throw new Error("Expected the field `color` to be a primitive type in the JSON string but got " + data['color']); + } + + return true; + } + } +Animal.RequiredProperties = ["className"]; + /** * @member {String} className */ diff --git a/samples/client/petstore/javascript-es6/src/model/AnimalFarm.js b/samples/client/petstore/javascript-es6/src/model/AnimalFarm.js deleted file mode 100644 index 3b9cc01f03..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/AnimalFarm.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; -import Animal from './Animal'; - -/** - * The AnimalFarm model module. - * @module model/AnimalFarm - * @version 1.0.0 - */ -class AnimalFarm extends Array { - /** - * Constructs a new AnimalFarm. - * @alias module:model/AnimalFarm - * @extends Array - */ - constructor() { - super(); - - - AnimalFarm.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a AnimalFarm from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/AnimalFarm} obj Optional instance to populate. - * @return {module:model/AnimalFarm} The populated AnimalFarm instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new AnimalFarm(); - - ApiClient.constructFromObject(data, obj, 'Animal'); - - - } - return obj; - } - - -} - - - - - - -export default AnimalFarm; - diff --git a/samples/client/petstore/javascript-es6/src/model/ApiResponse.js b/samples/client/petstore/javascript-es6/src/model/ApiResponse.js index f5af17fdf8..6db561122f 100644 --- a/samples/client/petstore/javascript-es6/src/model/ApiResponse.js +++ b/samples/client/petstore/javascript-es6/src/model/ApiResponse.js @@ -60,9 +60,29 @@ class ApiResponse { return obj; } + /** + * Validates the JSON data with respect to ApiResponse. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ApiResponse. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['type'] && !(typeof data['type'] === 'string' || data['type'] instanceof String)) { + throw new Error("Expected the field `type` to be a primitive type in the JSON string but got " + data['type']); + } + // ensure the json data is a string + if (data['message'] && !(typeof data['message'] === 'string' || data['message'] instanceof String)) { + throw new Error("Expected the field `message` to be a primitive type in the JSON string but got " + data['message']); + } + + return true; + } + } + + /** * @member {Number} code */ diff --git a/samples/client/petstore/javascript-es6/src/model/ArrayOfArrayOfNumberOnly.js b/samples/client/petstore/javascript-es6/src/model/ArrayOfArrayOfNumberOnly.js index eadd7db414..461c6b5b35 100644 --- a/samples/client/petstore/javascript-es6/src/model/ArrayOfArrayOfNumberOnly.js +++ b/samples/client/petstore/javascript-es6/src/model/ArrayOfArrayOfNumberOnly.js @@ -54,9 +54,25 @@ class ArrayOfArrayOfNumberOnly { return obj; } + /** + * Validates the JSON data with respect to ArrayOfArrayOfNumberOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ArrayOfArrayOfNumberOnly. + */ + static validateJSON(data) { + // ensure the json data is an array + if (!Array.isArray(data['ArrayArrayNumber'])) { + throw new Error("Expected the field `ArrayArrayNumber` to be an array in the JSON data but got " + data['ArrayArrayNumber']); + } + + return true; + } + } + + /** * @member {Array.>} ArrayArrayNumber */ diff --git a/samples/client/petstore/javascript-es6/src/model/ArrayOfNumberOnly.js b/samples/client/petstore/javascript-es6/src/model/ArrayOfNumberOnly.js index 1145a62630..4c2513c107 100644 --- a/samples/client/petstore/javascript-es6/src/model/ArrayOfNumberOnly.js +++ b/samples/client/petstore/javascript-es6/src/model/ArrayOfNumberOnly.js @@ -54,9 +54,25 @@ class ArrayOfNumberOnly { return obj; } + /** + * Validates the JSON data with respect to ArrayOfNumberOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ArrayOfNumberOnly. + */ + static validateJSON(data) { + // ensure the json data is an array + if (!Array.isArray(data['ArrayNumber'])) { + throw new Error("Expected the field `ArrayNumber` to be an array in the JSON data but got " + data['ArrayNumber']); + } + + return true; + } + } + + /** * @member {Array.} ArrayNumber */ diff --git a/samples/client/petstore/javascript-es6/src/model/ArrayTest.js b/samples/client/petstore/javascript-es6/src/model/ArrayTest.js index 18bc925308..3fc3c9b7f9 100644 --- a/samples/client/petstore/javascript-es6/src/model/ArrayTest.js +++ b/samples/client/petstore/javascript-es6/src/model/ArrayTest.js @@ -61,9 +61,33 @@ class ArrayTest { return obj; } + /** + * Validates the JSON data with respect to ArrayTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ArrayTest. + */ + static validateJSON(data) { + // ensure the json data is an array + if (!Array.isArray(data['array_of_string'])) { + throw new Error("Expected the field `array_of_string` to be an array in the JSON data but got " + data['array_of_string']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_array_of_integer'])) { + throw new Error("Expected the field `array_array_of_integer` to be an array in the JSON data but got " + data['array_array_of_integer']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_array_of_model'])) { + throw new Error("Expected the field `array_array_of_model` to be an array in the JSON data but got " + data['array_array_of_model']); + } + + return true; + } + } + + /** * @member {Array.} array_of_string */ diff --git a/samples/client/petstore/javascript-es6/src/model/BasquePig.js b/samples/client/petstore/javascript-es6/src/model/BasquePig.js new file mode 100644 index 0000000000..dc26c47c4f --- /dev/null +++ b/samples/client/petstore/javascript-es6/src/model/BasquePig.js @@ -0,0 +1,109 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The BasquePig model module. + * @module model/BasquePig + * @version 1.0.0 + */ +class BasquePig { + /** + * Constructs a new BasquePig. + * @alias module:model/BasquePig + * @param className {String} + * @param color {String} + */ + constructor(className, color) { + + BasquePig.initialize(this, className, color); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, className, color) { + obj['className'] = className; + obj['color'] = color; + } + + /** + * Constructs a BasquePig from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/BasquePig} obj Optional instance to populate. + * @return {module:model/BasquePig} The populated BasquePig instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new BasquePig(); + + if (data.hasOwnProperty('className')) { + obj['className'] = ApiClient.convertToType(data['className'], 'String'); + } + if (data.hasOwnProperty('color')) { + obj['color'] = ApiClient.convertToType(data['color'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to BasquePig. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to BasquePig. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of BasquePig.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['className'] && !(typeof data['className'] === 'string' || data['className'] instanceof String)) { + throw new Error("Expected the field `className` to be a primitive type in the JSON string but got " + data['className']); + } + // ensure the json data is a string + if (data['color'] && !(typeof data['color'] === 'string' || data['color'] instanceof String)) { + throw new Error("Expected the field `color` to be a primitive type in the JSON string but got " + data['color']); + } + + return true; + } + + +} + +BasquePig.RequiredProperties = ["className", "color"]; + +/** + * @member {String} className + */ +BasquePig.prototype['className'] = undefined; + +/** + * @member {String} color + */ +BasquePig.prototype['color'] = undefined; + + + + + + +export default BasquePig; + diff --git a/samples/client/petstore/javascript-es6/src/model/Capitalization.js b/samples/client/petstore/javascript-es6/src/model/Capitalization.js index 63b14361fe..cf4ef4348a 100644 --- a/samples/client/petstore/javascript-es6/src/model/Capitalization.js +++ b/samples/client/petstore/javascript-es6/src/model/Capitalization.js @@ -69,9 +69,45 @@ class Capitalization { return obj; } + /** + * Validates the JSON data with respect to Capitalization. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Capitalization. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['smallCamel'] && !(typeof data['smallCamel'] === 'string' || data['smallCamel'] instanceof String)) { + throw new Error("Expected the field `smallCamel` to be a primitive type in the JSON string but got " + data['smallCamel']); + } + // ensure the json data is a string + if (data['CapitalCamel'] && !(typeof data['CapitalCamel'] === 'string' || data['CapitalCamel'] instanceof String)) { + throw new Error("Expected the field `CapitalCamel` to be a primitive type in the JSON string but got " + data['CapitalCamel']); + } + // ensure the json data is a string + if (data['small_Snake'] && !(typeof data['small_Snake'] === 'string' || data['small_Snake'] instanceof String)) { + throw new Error("Expected the field `small_Snake` to be a primitive type in the JSON string but got " + data['small_Snake']); + } + // ensure the json data is a string + if (data['Capital_Snake'] && !(typeof data['Capital_Snake'] === 'string' || data['Capital_Snake'] instanceof String)) { + throw new Error("Expected the field `Capital_Snake` to be a primitive type in the JSON string but got " + data['Capital_Snake']); + } + // ensure the json data is a string + if (data['SCA_ETH_Flow_Points'] && !(typeof data['SCA_ETH_Flow_Points'] === 'string' || data['SCA_ETH_Flow_Points'] instanceof String)) { + throw new Error("Expected the field `SCA_ETH_Flow_Points` to be a primitive type in the JSON string but got " + data['SCA_ETH_Flow_Points']); + } + // ensure the json data is a string + if (data['ATT_NAME'] && !(typeof data['ATT_NAME'] === 'string' || data['ATT_NAME'] instanceof String)) { + throw new Error("Expected the field `ATT_NAME` to be a primitive type in the JSON string but got " + data['ATT_NAME']); + } + + return true; + } + } + + /** * @member {String} smallCamel */ diff --git a/samples/client/petstore/javascript-es6/src/model/Cat.js b/samples/client/petstore/javascript-es6/src/model/Cat.js index d18ce94e70..203a652cfc 100644 --- a/samples/client/petstore/javascript-es6/src/model/Cat.js +++ b/samples/client/petstore/javascript-es6/src/model/Cat.js @@ -63,9 +63,27 @@ class Cat { return obj; } + /** + * Validates the JSON data with respect to Cat. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Cat. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Cat.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + + return true; + } + } +Cat.RequiredProperties = ["className"]; + /** * @member {Boolean} declawed */ diff --git a/samples/client/petstore/javascript-es6/src/model/CatAllOf.js b/samples/client/petstore/javascript-es6/src/model/CatAllOf.js index c71ea7129b..8c0d5bfbbd 100644 --- a/samples/client/petstore/javascript-es6/src/model/CatAllOf.js +++ b/samples/client/petstore/javascript-es6/src/model/CatAllOf.js @@ -54,9 +54,21 @@ class CatAllOf { return obj; } + /** + * Validates the JSON data with respect to CatAllOf. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to CatAllOf. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Boolean} declawed */ diff --git a/samples/client/petstore/javascript-es6/src/model/Category.js b/samples/client/petstore/javascript-es6/src/model/Category.js index 557e8e1862..fc304998f4 100644 --- a/samples/client/petstore/javascript-es6/src/model/Category.js +++ b/samples/client/petstore/javascript-es6/src/model/Category.js @@ -59,9 +59,31 @@ class Category { return obj; } + /** + * Validates the JSON data with respect to Category. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Category. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Category.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + + return true; + } + } +Category.RequiredProperties = ["name"]; + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-es6/src/model/ClassModel.js b/samples/client/petstore/javascript-es6/src/model/ClassModel.js index ee1f141777..ba614443eb 100644 --- a/samples/client/petstore/javascript-es6/src/model/ClassModel.js +++ b/samples/client/petstore/javascript-es6/src/model/ClassModel.js @@ -55,9 +55,25 @@ class ClassModel { return obj; } + /** + * Validates the JSON data with respect to ClassModel. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ClassModel. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['_class'] && !(typeof data['_class'] === 'string' || data['_class'] instanceof String)) { + throw new Error("Expected the field `_class` to be a primitive type in the JSON string but got " + data['_class']); + } + + return true; + } + } + + /** * @member {String} _class */ diff --git a/samples/client/petstore/javascript-es6/src/model/Client.js b/samples/client/petstore/javascript-es6/src/model/Client.js index 8521c85043..4089ff37ee 100644 --- a/samples/client/petstore/javascript-es6/src/model/Client.js +++ b/samples/client/petstore/javascript-es6/src/model/Client.js @@ -54,9 +54,25 @@ class Client { return obj; } + /** + * Validates the JSON data with respect to Client. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Client. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['client'] && !(typeof data['client'] === 'string' || data['client'] instanceof String)) { + throw new Error("Expected the field `client` to be a primitive type in the JSON string but got " + data['client']); + } + + return true; + } + } + + /** * @member {String} client */ diff --git a/samples/client/petstore/javascript-es6/src/model/Color.js b/samples/client/petstore/javascript-es6/src/model/Color.js new file mode 100644 index 0000000000..b071fff068 --- /dev/null +++ b/samples/client/petstore/javascript-es6/src/model/Color.js @@ -0,0 +1,164 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Color model module. + * @module model/Color + * @version 1.0.0 + */ +class Color { + /** + * Constructs a new Color. + * RGB array, RGBA array, or hex string. + * @alias module:model/Color + * @param {(module:model/String|module:model/[Number])} instance The actual instance to initialize Color. + */ + constructor(instance = null) { + if (instance === null) { + this.actualInstance = null; + return; + } + var match = 0; + var errorMessages = []; + // RGB three element array with values 0-255. + try { + // validate array data type + if (!Array.isArray(instance)) { + throw new Error("Invalid data type. Expecting array. Input: " + instance); + } + if (instance.length > 3 || instance.length < 3) { + throw new Error("Invalid array size. Minimim: 3. Maximum: 3. Input: " + instance); + } + // validate array of integer + for (const item of instance) { + if (!(typeof item === 'number' && item % 1 === 0)) { + throw new Error("Invalid array items. Must be integer. Input: " + instance); + } + if (item > 255 || item < 0) { + throw new Error("Invalid integer value in an array items. Max.: 255. Min.: 0. Input: " + instance); + } + } + this.actualInstance = instance; + match++; + } catch(err) { + // json data failed to deserialize into [Number] + errorMessages.push("Failed to construct [Number]: " + err) + } + + // RGBA four element array with values 0-255. + try { + // validate array data type + if (!Array.isArray(instance)) { + throw new Error("Invalid data type. Expecting array. Input: " + instance); + } + if (instance.length > 4 || instance.length < 4) { + throw new Error("Invalid array size. Minimim: 4. Maximum: 4. Input: " + instance); + } + // validate array of integer + for (const item of instance) { + if (!(typeof item === 'number' && item % 1 === 0)) { + throw new Error("Invalid array items. Must be integer. Input: " + instance); + } + if (item > 255 || item < 0) { + throw new Error("Invalid integer value in an array items. Max.: 255. Min.: 0. Input: " + instance); + } + } + this.actualInstance = instance; + match++; + } catch(err) { + // json data failed to deserialize into [Number] + errorMessages.push("Failed to construct [Number]: " + err) + } + + // Hex color string, such as #00FF00. + try { + // validate array of string + if (!(typeof instance === 'string')) { + throw new Error("Invalid input. Must be string. Input: " + JSON.stringify(instance)); + } + if (!/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(instance)) { + throw new Error("Invalid string value in an array items. Must conform to /^#(?:[0-9a-fA-F]{3}){1,2}$/. Input: " + JSON.stringify(instance)); + } + if (instance.length > 7 && instance.length < 7) { + throw new Error("Invalid string value in an array items. Max. length: 7. Min. length: 7. Input: " + JSON.stringify(instance)); + } + this.actualInstance = instance; + match++; + } catch(err) { + // json data failed to deserialize into String + errorMessages.push("Failed to construct String: " + err) + } + + if (match > 1) { + throw new Error("Multiple matches found constructing `Color` with oneOf schemas String, [Number]. Input: " + JSON.stringify(instance)); + } else if (match === 0) { + this.actualInstance = null; // clear the actual instance in case there are multiple matches + throw new Error("No match found constructing `Color` with oneOf schemas String, [Number]. Details: " + + errorMessages.join(", ")); + } else { // only 1 match + // the input is valid + } + } + + /** + * Constructs a Color from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Color} obj Optional instance to populate. + * @return {module:model/Color} The populated Color instance. + */ + static constructFromObject(data, obj) { + return new Color(data); + } + + /** + * Gets the actaul instance, which can be String, [Number]. + * @return {(module:model/String|module:model/[Number])} The actual instance. + */ + getActualInstance() { + return this.actualInstance; + } + + /** + * Sets the actaul instance, which can be String, [Number]. + * @param {(module:model/String|module:model/[Number])} obj The actual instance. + */ + setActualInstance(obj) { + this.actualInstance = Color.constructFromObject(obj).getActualInstance(); + } + + /** + * Returns the JSON representation of the actual intance. + * @return {string} + */ + toJSON = function(){ + return this.getActualInstance(); + } + + /** + * Create an instance of Color from a JSON string. + * @param {string} json_string JSON string. + * @return {module:model/Color} An instance of Color. + */ + static fromJSON = function(json_string){ + return Color.constructFromObject(JSON.parse(json_string)); + } +} + + +Color.OneOf = ["String", "[Number]"]; + +export default Color; + diff --git a/samples/client/petstore/javascript-es6/src/model/DanishPig.js b/samples/client/petstore/javascript-es6/src/model/DanishPig.js new file mode 100644 index 0000000000..4023e9d637 --- /dev/null +++ b/samples/client/petstore/javascript-es6/src/model/DanishPig.js @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The DanishPig model module. + * @module model/DanishPig + * @version 1.0.0 + */ +class DanishPig { + /** + * Constructs a new DanishPig. + * @alias module:model/DanishPig + * @param className {String} + * @param size {Number} + */ + constructor(className, size) { + + DanishPig.initialize(this, className, size); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, className, size) { + obj['className'] = className; + obj['size'] = size; + } + + /** + * Constructs a DanishPig from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/DanishPig} obj Optional instance to populate. + * @return {module:model/DanishPig} The populated DanishPig instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new DanishPig(); + + if (data.hasOwnProperty('className')) { + obj['className'] = ApiClient.convertToType(data['className'], 'String'); + } + if (data.hasOwnProperty('size')) { + obj['size'] = ApiClient.convertToType(data['size'], 'Number'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to DanishPig. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to DanishPig. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of DanishPig.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['className'] && !(typeof data['className'] === 'string' || data['className'] instanceof String)) { + throw new Error("Expected the field `className` to be a primitive type in the JSON string but got " + data['className']); + } + + return true; + } + + +} + +DanishPig.RequiredProperties = ["className", "size"]; + +/** + * @member {String} className + */ +DanishPig.prototype['className'] = undefined; + +/** + * @member {Number} size + */ +DanishPig.prototype['size'] = undefined; + + + + + + +export default DanishPig; + diff --git a/samples/client/petstore/javascript-es6/src/model/DeprecatedObject.js b/samples/client/petstore/javascript-es6/src/model/DeprecatedObject.js index c3298d5020..d7c874345f 100644 --- a/samples/client/petstore/javascript-es6/src/model/DeprecatedObject.js +++ b/samples/client/petstore/javascript-es6/src/model/DeprecatedObject.js @@ -54,9 +54,25 @@ class DeprecatedObject { return obj; } + /** + * Validates the JSON data with respect to DeprecatedObject. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to DeprecatedObject. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + + return true; + } + } + + /** * @member {String} name */ diff --git a/samples/client/petstore/javascript-es6/src/model/Dog.js b/samples/client/petstore/javascript-es6/src/model/Dog.js index b101feecd3..dd3f1ebb50 100644 --- a/samples/client/petstore/javascript-es6/src/model/Dog.js +++ b/samples/client/petstore/javascript-es6/src/model/Dog.js @@ -63,9 +63,31 @@ class Dog { return obj; } + /** + * Validates the JSON data with respect to Dog. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Dog. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Dog.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['breed'] && !(typeof data['breed'] === 'string' || data['breed'] instanceof String)) { + throw new Error("Expected the field `breed` to be a primitive type in the JSON string but got " + data['breed']); + } + + return true; + } + } +Dog.RequiredProperties = ["className"]; + /** * @member {String} breed */ diff --git a/samples/client/petstore/javascript-es6/src/model/DogAllOf.js b/samples/client/petstore/javascript-es6/src/model/DogAllOf.js index 58ecede612..beb42db2ec 100644 --- a/samples/client/petstore/javascript-es6/src/model/DogAllOf.js +++ b/samples/client/petstore/javascript-es6/src/model/DogAllOf.js @@ -54,9 +54,25 @@ class DogAllOf { return obj; } + /** + * Validates the JSON data with respect to DogAllOf. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to DogAllOf. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['breed'] && !(typeof data['breed'] === 'string' || data['breed'] instanceof String)) { + throw new Error("Expected the field `breed` to be a primitive type in the JSON string but got " + data['breed']); + } + + return true; + } + } + + /** * @member {String} breed */ diff --git a/samples/client/petstore/javascript-es6/src/model/EnumArrays.js b/samples/client/petstore/javascript-es6/src/model/EnumArrays.js index 7fe64e3111..2289689e34 100644 --- a/samples/client/petstore/javascript-es6/src/model/EnumArrays.js +++ b/samples/client/petstore/javascript-es6/src/model/EnumArrays.js @@ -57,9 +57,29 @@ class EnumArrays { return obj; } + /** + * Validates the JSON data with respect to EnumArrays. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to EnumArrays. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['just_symbol'] && !(typeof data['just_symbol'] === 'string' || data['just_symbol'] instanceof String)) { + throw new Error("Expected the field `just_symbol` to be a primitive type in the JSON string but got " + data['just_symbol']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_enum'])) { + throw new Error("Expected the field `array_enum` to be an array in the JSON data but got " + data['array_enum']); + } + + return true; + } + } + + /** * @member {module:model/EnumArrays.JustSymbolEnum} just_symbol */ diff --git a/samples/client/petstore/javascript-es6/src/model/EnumTest.js b/samples/client/petstore/javascript-es6/src/model/EnumTest.js index dc684b7c26..b1556a0613 100644 --- a/samples/client/petstore/javascript-es6/src/model/EnumTest.js +++ b/samples/client/petstore/javascript-es6/src/model/EnumTest.js @@ -81,9 +81,35 @@ class EnumTest { return obj; } + /** + * Validates the JSON data with respect to EnumTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to EnumTest. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of EnumTest.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['enum_string'] && !(typeof data['enum_string'] === 'string' || data['enum_string'] instanceof String)) { + throw new Error("Expected the field `enum_string` to be a primitive type in the JSON string but got " + data['enum_string']); + } + // ensure the json data is a string + if (data['enum_string_required'] && !(typeof data['enum_string_required'] === 'string' || data['enum_string_required'] instanceof String)) { + throw new Error("Expected the field `enum_string_required` to be a primitive type in the JSON string but got " + data['enum_string_required']); + } + + return true; + } + } +EnumTest.RequiredProperties = ["enum_string_required"]; + /** * @member {module:model/EnumTest.EnumStringEnum} enum_string */ diff --git a/samples/client/petstore/javascript-es6/src/model/File.js b/samples/client/petstore/javascript-es6/src/model/File.js index 12b51b87d8..5f5c9547a1 100644 --- a/samples/client/petstore/javascript-es6/src/model/File.js +++ b/samples/client/petstore/javascript-es6/src/model/File.js @@ -55,9 +55,25 @@ class File { return obj; } + /** + * Validates the JSON data with respect to File. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to File. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['sourceURI'] && !(typeof data['sourceURI'] === 'string' || data['sourceURI'] instanceof String)) { + throw new Error("Expected the field `sourceURI` to be a primitive type in the JSON string but got " + data['sourceURI']); + } + + return true; + } + } + + /** * Test capitalization * @member {String} sourceURI diff --git a/samples/client/petstore/javascript-es6/src/model/FileSchemaTestClass.js b/samples/client/petstore/javascript-es6/src/model/FileSchemaTestClass.js index b6fe9e90ec..8174d56245 100644 --- a/samples/client/petstore/javascript-es6/src/model/FileSchemaTestClass.js +++ b/samples/client/petstore/javascript-es6/src/model/FileSchemaTestClass.js @@ -57,9 +57,35 @@ class FileSchemaTestClass { return obj; } + /** + * Validates the JSON data with respect to FileSchemaTestClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to FileSchemaTestClass. + */ + static validateJSON(data) { + // validate the optional field `file` + if (data['file']) { // data not null + File.validateJSON(data['file']); + } + if (data['files']) { // data not null + // ensure the json data is an array + if (!Array.isArray(data['files'])) { + throw new Error("Expected the field `files` to be an array in the JSON data but got " + data['files']); + } + // validate the optional field `files` (array) + for (const item of data['files']) { + File.validateJsonObject(item); + }; + } + + return true; + } + } + + /** * @member {File} file */ diff --git a/samples/client/petstore/javascript-es6/src/model/Foo.js b/samples/client/petstore/javascript-es6/src/model/Foo.js index 3e4477b805..3fc7819f99 100644 --- a/samples/client/petstore/javascript-es6/src/model/Foo.js +++ b/samples/client/petstore/javascript-es6/src/model/Foo.js @@ -54,9 +54,25 @@ class Foo { return obj; } + /** + * Validates the JSON data with respect to Foo. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Foo. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['bar'] && !(typeof data['bar'] === 'string' || data['bar'] instanceof String)) { + throw new Error("Expected the field `bar` to be a primitive type in the JSON string but got " + data['bar']); + } + + return true; + } + } + + /** * @member {String} bar * @default 'bar' diff --git a/samples/client/petstore/javascript-es6/src/model/FooGetDefaultResponse.js b/samples/client/petstore/javascript-es6/src/model/FooGetDefaultResponse.js index ab3558a041..b11d885937 100644 --- a/samples/client/petstore/javascript-es6/src/model/FooGetDefaultResponse.js +++ b/samples/client/petstore/javascript-es6/src/model/FooGetDefaultResponse.js @@ -55,9 +55,25 @@ class FooGetDefaultResponse { return obj; } + /** + * Validates the JSON data with respect to FooGetDefaultResponse. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to FooGetDefaultResponse. + */ + static validateJSON(data) { + // validate the optional field `string` + if (data['string']) { // data not null + Foo.validateJSON(data['string']); + } + + return true; + } + } + + /** * @member {module:model/Foo} string */ diff --git a/samples/client/petstore/javascript-es6/src/model/FormatTest.js b/samples/client/petstore/javascript-es6/src/model/FormatTest.js index 00ee3533d0..65a34a7ff0 100644 --- a/samples/client/petstore/javascript-es6/src/model/FormatTest.js +++ b/samples/client/petstore/javascript-es6/src/model/FormatTest.js @@ -107,9 +107,47 @@ class FormatTest { return obj; } + /** + * Validates the JSON data with respect to FormatTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to FormatTest. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of FormatTest.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['string'] && !(typeof data['string'] === 'string' || data['string'] instanceof String)) { + throw new Error("Expected the field `string` to be a primitive type in the JSON string but got " + data['string']); + } + // ensure the json data is a string + if (data['uuid'] && !(typeof data['uuid'] === 'string' || data['uuid'] instanceof String)) { + throw new Error("Expected the field `uuid` to be a primitive type in the JSON string but got " + data['uuid']); + } + // ensure the json data is a string + if (data['password'] && !(typeof data['password'] === 'string' || data['password'] instanceof String)) { + throw new Error("Expected the field `password` to be a primitive type in the JSON string but got " + data['password']); + } + // ensure the json data is a string + if (data['pattern_with_digits'] && !(typeof data['pattern_with_digits'] === 'string' || data['pattern_with_digits'] instanceof String)) { + throw new Error("Expected the field `pattern_with_digits` to be a primitive type in the JSON string but got " + data['pattern_with_digits']); + } + // ensure the json data is a string + if (data['pattern_with_digits_and_delimiter'] && !(typeof data['pattern_with_digits_and_delimiter'] === 'string' || data['pattern_with_digits_and_delimiter'] instanceof String)) { + throw new Error("Expected the field `pattern_with_digits_and_delimiter` to be a primitive type in the JSON string but got " + data['pattern_with_digits_and_delimiter']); + } + + return true; + } + } +FormatTest.RequiredProperties = ["number", "byte", "date", "password"]; + /** * @member {Number} integer */ diff --git a/samples/client/petstore/javascript-es6/src/model/HasOnlyReadOnly.js b/samples/client/petstore/javascript-es6/src/model/HasOnlyReadOnly.js index 57c9173723..90943b87ae 100644 --- a/samples/client/petstore/javascript-es6/src/model/HasOnlyReadOnly.js +++ b/samples/client/petstore/javascript-es6/src/model/HasOnlyReadOnly.js @@ -57,9 +57,29 @@ class HasOnlyReadOnly { return obj; } + /** + * Validates the JSON data with respect to HasOnlyReadOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to HasOnlyReadOnly. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['bar'] && !(typeof data['bar'] === 'string' || data['bar'] instanceof String)) { + throw new Error("Expected the field `bar` to be a primitive type in the JSON string but got " + data['bar']); + } + // ensure the json data is a string + if (data['foo'] && !(typeof data['foo'] === 'string' || data['foo'] instanceof String)) { + throw new Error("Expected the field `foo` to be a primitive type in the JSON string but got " + data['foo']); + } + + return true; + } + } + + /** * @member {String} bar */ diff --git a/samples/client/petstore/javascript-es6/src/model/HealthCheckResult.js b/samples/client/petstore/javascript-es6/src/model/HealthCheckResult.js index 2dd62c2a26..112fd77842 100644 --- a/samples/client/petstore/javascript-es6/src/model/HealthCheckResult.js +++ b/samples/client/petstore/javascript-es6/src/model/HealthCheckResult.js @@ -55,9 +55,25 @@ class HealthCheckResult { return obj; } + /** + * Validates the JSON data with respect to HealthCheckResult. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to HealthCheckResult. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['NullableMessage'] && !(typeof data['NullableMessage'] === 'string' || data['NullableMessage'] instanceof String)) { + throw new Error("Expected the field `NullableMessage` to be a primitive type in the JSON string but got " + data['NullableMessage']); + } + + return true; + } + } + + /** * @member {String} NullableMessage */ diff --git a/samples/client/petstore/javascript-es6/src/model/InlineObject.js b/samples/client/petstore/javascript-es6/src/model/InlineObject.js deleted file mode 100644 index 6815bc809c..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/InlineObject.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject model module. - * @module model/InlineObject - * @version 1.0.0 - */ -class InlineObject { - /** - * Constructs a new InlineObject. - * @alias module:model/InlineObject - */ - constructor() { - - InlineObject.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a InlineObject from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject} obj Optional instance to populate. - * @return {module:model/InlineObject} The populated InlineObject instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject(); - - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - if (data.hasOwnProperty('status')) { - obj['status'] = ApiClient.convertToType(data['status'], 'String'); - } - } - return obj; - } - - -} - -/** - * Updated name of the pet - * @member {String} name - */ -InlineObject.prototype['name'] = undefined; - -/** - * Updated status of the pet - * @member {String} status - */ -InlineObject.prototype['status'] = undefined; - - - - - - -export default InlineObject; - diff --git a/samples/client/petstore/javascript-es6/src/model/InlineObject1.js b/samples/client/petstore/javascript-es6/src/model/InlineObject1.js deleted file mode 100644 index 947877256f..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/InlineObject1.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject1 model module. - * @module model/InlineObject1 - * @version 1.0.0 - */ -class InlineObject1 { - /** - * Constructs a new InlineObject1. - * @alias module:model/InlineObject1 - */ - constructor() { - - InlineObject1.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a InlineObject1 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject1} obj Optional instance to populate. - * @return {module:model/InlineObject1} The populated InlineObject1 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject1(); - - if (data.hasOwnProperty('additionalMetadata')) { - obj['additionalMetadata'] = ApiClient.convertToType(data['additionalMetadata'], 'String'); - } - if (data.hasOwnProperty('file')) { - obj['file'] = ApiClient.convertToType(data['file'], File); - } - } - return obj; - } - - -} - -/** - * Additional data to pass to server - * @member {String} additionalMetadata - */ -InlineObject1.prototype['additionalMetadata'] = undefined; - -/** - * file to upload - * @member {File} file - */ -InlineObject1.prototype['file'] = undefined; - - - - - - -export default InlineObject1; - diff --git a/samples/client/petstore/javascript-es6/src/model/InlineObject2.js b/samples/client/petstore/javascript-es6/src/model/InlineObject2.js deleted file mode 100644 index e6ed904456..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/InlineObject2.js +++ /dev/null @@ -1,130 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject2 model module. - * @module model/InlineObject2 - * @version 1.0.0 - */ -class InlineObject2 { - /** - * Constructs a new InlineObject2. - * @alias module:model/InlineObject2 - */ - constructor() { - - InlineObject2.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a InlineObject2 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject2} obj Optional instance to populate. - * @return {module:model/InlineObject2} The populated InlineObject2 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject2(); - - if (data.hasOwnProperty('enum_form_string_array')) { - obj['enum_form_string_array'] = ApiClient.convertToType(data['enum_form_string_array'], ['String']); - } - if (data.hasOwnProperty('enum_form_string')) { - obj['enum_form_string'] = ApiClient.convertToType(data['enum_form_string'], 'String'); - } - } - return obj; - } - - -} - -/** - * Form parameter enum test (string array) - * @member {Array.} enum_form_string_array - */ -InlineObject2.prototype['enum_form_string_array'] = undefined; - -/** - * Form parameter enum test (string) - * @member {module:model/InlineObject2.EnumFormStringEnum} enum_form_string - * @default '-efg' - */ -InlineObject2.prototype['enum_form_string'] = '-efg'; - - - - - -/** - * Allowed values for the enumFormStringArray property. - * @enum {String} - * @readonly - */ -InlineObject2['EnumFormStringArrayEnum'] = { - - /** - * value: ">" - * @const - */ - "GREATER_THAN": ">", - - /** - * value: "$" - * @const - */ - "DOLLAR": "$" -}; - - -/** - * Allowed values for the enum_form_string property. - * @enum {String} - * @readonly - */ -InlineObject2['EnumFormStringEnum'] = { - - /** - * value: "_abc" - * @const - */ - "_abc": "_abc", - - /** - * value: "-efg" - * @const - */ - "-efg": "-efg", - - /** - * value: "(xyz)" - * @const - */ - "(xyz)": "(xyz)" -}; - - - -export default InlineObject2; - diff --git a/samples/client/petstore/javascript-es6/src/model/InlineObject3.js b/samples/client/petstore/javascript-es6/src/model/InlineObject3.js deleted file mode 100644 index 6a14f67109..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/InlineObject3.js +++ /dev/null @@ -1,197 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject3 model module. - * @module model/InlineObject3 - * @version 1.0.0 - */ -class InlineObject3 { - /** - * Constructs a new InlineObject3. - * @alias module:model/InlineObject3 - * @param _number {Number} None - * @param _double {Number} None - * @param patternWithoutDelimiter {String} None - * @param _byte {Blob} None - */ - constructor(_number, _double, patternWithoutDelimiter, _byte) { - - InlineObject3.initialize(this, _number, _double, patternWithoutDelimiter, _byte); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, _number, _double, patternWithoutDelimiter, _byte) { - obj['number'] = _number; - obj['double'] = _double; - obj['pattern_without_delimiter'] = patternWithoutDelimiter; - obj['byte'] = _byte; - } - - /** - * Constructs a InlineObject3 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject3} obj Optional instance to populate. - * @return {module:model/InlineObject3} The populated InlineObject3 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject3(); - - if (data.hasOwnProperty('integer')) { - obj['integer'] = ApiClient.convertToType(data['integer'], 'Number'); - } - if (data.hasOwnProperty('int32')) { - obj['int32'] = ApiClient.convertToType(data['int32'], 'Number'); - } - if (data.hasOwnProperty('int64')) { - obj['int64'] = ApiClient.convertToType(data['int64'], 'Number'); - } - if (data.hasOwnProperty('number')) { - obj['number'] = ApiClient.convertToType(data['number'], 'Number'); - } - if (data.hasOwnProperty('float')) { - obj['float'] = ApiClient.convertToType(data['float'], 'Number'); - } - if (data.hasOwnProperty('double')) { - obj['double'] = ApiClient.convertToType(data['double'], 'Number'); - } - if (data.hasOwnProperty('string')) { - obj['string'] = ApiClient.convertToType(data['string'], 'String'); - } - if (data.hasOwnProperty('pattern_without_delimiter')) { - obj['pattern_without_delimiter'] = ApiClient.convertToType(data['pattern_without_delimiter'], 'String'); - } - if (data.hasOwnProperty('byte')) { - obj['byte'] = ApiClient.convertToType(data['byte'], 'Blob'); - } - if (data.hasOwnProperty('binary')) { - obj['binary'] = ApiClient.convertToType(data['binary'], File); - } - if (data.hasOwnProperty('date')) { - obj['date'] = ApiClient.convertToType(data['date'], 'Date'); - } - if (data.hasOwnProperty('dateTime')) { - obj['dateTime'] = ApiClient.convertToType(data['dateTime'], 'Date'); - } - if (data.hasOwnProperty('password')) { - obj['password'] = ApiClient.convertToType(data['password'], 'String'); - } - if (data.hasOwnProperty('callback')) { - obj['callback'] = ApiClient.convertToType(data['callback'], 'String'); - } - } - return obj; - } - - -} - -/** - * None - * @member {Number} integer - */ -InlineObject3.prototype['integer'] = undefined; - -/** - * None - * @member {Number} int32 - */ -InlineObject3.prototype['int32'] = undefined; - -/** - * None - * @member {Number} int64 - */ -InlineObject3.prototype['int64'] = undefined; - -/** - * None - * @member {Number} number - */ -InlineObject3.prototype['number'] = undefined; - -/** - * None - * @member {Number} float - */ -InlineObject3.prototype['float'] = undefined; - -/** - * None - * @member {Number} double - */ -InlineObject3.prototype['double'] = undefined; - -/** - * None - * @member {String} string - */ -InlineObject3.prototype['string'] = undefined; - -/** - * None - * @member {String} pattern_without_delimiter - */ -InlineObject3.prototype['pattern_without_delimiter'] = undefined; - -/** - * None - * @member {Blob} byte - */ -InlineObject3.prototype['byte'] = undefined; - -/** - * None - * @member {File} binary - */ -InlineObject3.prototype['binary'] = undefined; - -/** - * None - * @member {Date} date - */ -InlineObject3.prototype['date'] = undefined; - -/** - * None - * @member {Date} dateTime - */ -InlineObject3.prototype['dateTime'] = undefined; - -/** - * None - * @member {String} password - */ -InlineObject3.prototype['password'] = undefined; - -/** - * None - * @member {String} callback - */ -InlineObject3.prototype['callback'] = undefined; - - - - - - -export default InlineObject3; - diff --git a/samples/client/petstore/javascript-es6/src/model/InlineObject4.js b/samples/client/petstore/javascript-es6/src/model/InlineObject4.js deleted file mode 100644 index 9d5d5715c6..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/InlineObject4.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject4 model module. - * @module model/InlineObject4 - * @version 1.0.0 - */ -class InlineObject4 { - /** - * Constructs a new InlineObject4. - * @alias module:model/InlineObject4 - * @param param {String} field1 - * @param param2 {String} field2 - */ - constructor(param, param2) { - - InlineObject4.initialize(this, param, param2); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, param, param2) { - obj['param'] = param; - obj['param2'] = param2; - } - - /** - * Constructs a InlineObject4 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject4} obj Optional instance to populate. - * @return {module:model/InlineObject4} The populated InlineObject4 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject4(); - - if (data.hasOwnProperty('param')) { - obj['param'] = ApiClient.convertToType(data['param'], 'String'); - } - if (data.hasOwnProperty('param2')) { - obj['param2'] = ApiClient.convertToType(data['param2'], 'String'); - } - } - return obj; - } - - -} - -/** - * field1 - * @member {String} param - */ -InlineObject4.prototype['param'] = undefined; - -/** - * field2 - * @member {String} param2 - */ -InlineObject4.prototype['param2'] = undefined; - - - - - - -export default InlineObject4; - diff --git a/samples/client/petstore/javascript-es6/src/model/InlineObject5.js b/samples/client/petstore/javascript-es6/src/model/InlineObject5.js deleted file mode 100644 index 1969e9b2ef..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/InlineObject5.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject5 model module. - * @module model/InlineObject5 - * @version 1.0.0 - */ -class InlineObject5 { - /** - * Constructs a new InlineObject5. - * @alias module:model/InlineObject5 - * @param requiredFile {File} file to upload - */ - constructor(requiredFile) { - - InlineObject5.initialize(this, requiredFile); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, requiredFile) { - obj['requiredFile'] = requiredFile; - } - - /** - * Constructs a InlineObject5 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject5} obj Optional instance to populate. - * @return {module:model/InlineObject5} The populated InlineObject5 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject5(); - - if (data.hasOwnProperty('additionalMetadata')) { - obj['additionalMetadata'] = ApiClient.convertToType(data['additionalMetadata'], 'String'); - } - if (data.hasOwnProperty('requiredFile')) { - obj['requiredFile'] = ApiClient.convertToType(data['requiredFile'], File); - } - } - return obj; - } - - -} - -/** - * Additional data to pass to server - * @member {String} additionalMetadata - */ -InlineObject5.prototype['additionalMetadata'] = undefined; - -/** - * file to upload - * @member {File} requiredFile - */ -InlineObject5.prototype['requiredFile'] = undefined; - - - - - - -export default InlineObject5; - diff --git a/samples/client/petstore/javascript-es6/src/model/InlineResponseDefault.js b/samples/client/petstore/javascript-es6/src/model/InlineResponseDefault.js deleted file mode 100644 index 2f66d888ec..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/InlineResponseDefault.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; -import Foo from './Foo'; - -/** - * The InlineResponseDefault model module. - * @module model/InlineResponseDefault - * @version 1.0.0 - */ -class InlineResponseDefault { - /** - * Constructs a new InlineResponseDefault. - * @alias module:model/InlineResponseDefault - */ - constructor() { - - InlineResponseDefault.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a InlineResponseDefault from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineResponseDefault} obj Optional instance to populate. - * @return {module:model/InlineResponseDefault} The populated InlineResponseDefault instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineResponseDefault(); - - if (data.hasOwnProperty('string')) { - obj['string'] = Foo.constructFromObject(data['string']); - } - } - return obj; - } - - -} - -/** - * @member {module:model/Foo} string - */ -InlineResponseDefault.prototype['string'] = undefined; - - - - - - -export default InlineResponseDefault; - diff --git a/samples/client/petstore/javascript-es6/src/model/List.js b/samples/client/petstore/javascript-es6/src/model/List.js index 18d6a25849..ca916761c0 100644 --- a/samples/client/petstore/javascript-es6/src/model/List.js +++ b/samples/client/petstore/javascript-es6/src/model/List.js @@ -54,9 +54,25 @@ class List { return obj; } + /** + * Validates the JSON data with respect to List. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to List. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['123-list'] && !(typeof data['123-list'] === 'string' || data['123-list'] instanceof String)) { + throw new Error("Expected the field `123-list` to be a primitive type in the JSON string but got " + data['123-list']); + } + + return true; + } + } + + /** * @member {String} 123-list */ diff --git a/samples/client/petstore/javascript-es6/src/model/MapTest.js b/samples/client/petstore/javascript-es6/src/model/MapTest.js index 3113ad56bd..478e2347fa 100644 --- a/samples/client/petstore/javascript-es6/src/model/MapTest.js +++ b/samples/client/petstore/javascript-es6/src/model/MapTest.js @@ -63,9 +63,21 @@ class MapTest { return obj; } + /** + * Validates the JSON data with respect to MapTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to MapTest. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Object.>} map_map_of_string */ diff --git a/samples/client/petstore/javascript-es6/src/model/MixedPropertiesAndAdditionalPropertiesClass.js b/samples/client/petstore/javascript-es6/src/model/MixedPropertiesAndAdditionalPropertiesClass.js index 7cd9ca844f..8131fa3620 100644 --- a/samples/client/petstore/javascript-es6/src/model/MixedPropertiesAndAdditionalPropertiesClass.js +++ b/samples/client/petstore/javascript-es6/src/model/MixedPropertiesAndAdditionalPropertiesClass.js @@ -61,9 +61,25 @@ class MixedPropertiesAndAdditionalPropertiesClass { return obj; } + /** + * Validates the JSON data with respect to MixedPropertiesAndAdditionalPropertiesClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to MixedPropertiesAndAdditionalPropertiesClass. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['uuid'] && !(typeof data['uuid'] === 'string' || data['uuid'] instanceof String)) { + throw new Error("Expected the field `uuid` to be a primitive type in the JSON string but got " + data['uuid']); + } + + return true; + } + } + + /** * @member {String} uuid */ diff --git a/samples/client/petstore/javascript-es6/src/model/Model200Response.js b/samples/client/petstore/javascript-es6/src/model/Model200Response.js index 88daaba2eb..604683735f 100644 --- a/samples/client/petstore/javascript-es6/src/model/Model200Response.js +++ b/samples/client/petstore/javascript-es6/src/model/Model200Response.js @@ -58,9 +58,25 @@ class Model200Response { return obj; } + /** + * Validates the JSON data with respect to Model200Response. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Model200Response. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['class'] && !(typeof data['class'] === 'string' || data['class'] instanceof String)) { + throw new Error("Expected the field `class` to be a primitive type in the JSON string but got " + data['class']); + } + + return true; + } + } + + /** * @member {Number} name */ diff --git a/samples/client/petstore/javascript-es6/src/model/ModelReturn.js b/samples/client/petstore/javascript-es6/src/model/ModelReturn.js deleted file mode 100644 index bdfe578288..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/ModelReturn.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The ModelReturn model module. - * @module model/ModelReturn - * @version 1.0.0 - */ -class ModelReturn { - /** - * Constructs a new ModelReturn. - * Model for testing reserved words - * @alias module:model/ModelReturn - */ - constructor() { - - ModelReturn.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a ModelReturn from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/ModelReturn} obj Optional instance to populate. - * @return {module:model/ModelReturn} The populated ModelReturn instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new ModelReturn(); - - if (data.hasOwnProperty('return')) { - obj['return'] = ApiClient.convertToType(data['return'], 'Number'); - } - } - return obj; - } - - -} - -/** - * @member {Number} return - */ -ModelReturn.prototype['return'] = undefined; - - - - - - -export default ModelReturn; - diff --git a/samples/client/petstore/javascript-es6/src/model/Name.js b/samples/client/petstore/javascript-es6/src/model/Name.js index 740d4bad15..978fbaa7ef 100644 --- a/samples/client/petstore/javascript-es6/src/model/Name.js +++ b/samples/client/petstore/javascript-es6/src/model/Name.js @@ -66,9 +66,31 @@ class Name { return obj; } + /** + * Validates the JSON data with respect to Name. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Name. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Name.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['property'] && !(typeof data['property'] === 'string' || data['property'] instanceof String)) { + throw new Error("Expected the field `property` to be a primitive type in the JSON string but got " + data['property']); + } + + return true; + } + } +Name.RequiredProperties = ["name"]; + /** * @member {Number} name */ diff --git a/samples/client/petstore/javascript-es6/src/model/NestedColor.js b/samples/client/petstore/javascript-es6/src/model/NestedColor.js new file mode 100644 index 0000000000..5b61146903 --- /dev/null +++ b/samples/client/petstore/javascript-es6/src/model/NestedColor.js @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Color from './Color'; + +/** + * The NestedColor model module. + * @module model/NestedColor + * @version 1.0.0 + */ +class NestedColor { + /** + * Constructs a new NestedColor. + * @alias module:model/NestedColor + */ + constructor() { + + NestedColor.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a NestedColor from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/NestedColor} obj Optional instance to populate. + * @return {module:model/NestedColor} The populated NestedColor instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new NestedColor(); + + if (data.hasOwnProperty('size')) { + obj['size'] = ApiClient.convertToType(data['size'], 'Number'); + } + if (data.hasOwnProperty('nested')) { + obj['nested'] = Color.constructFromObject(data['nested']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to NestedColor. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NestedColor. + */ + static validateJSON(data) { + // validate the optional field `nested` + if (data['nested']) { // data not null + Color.validateJSON(data['nested']); + } + + return true; + } + + +} + + + +/** + * @member {Number} size + */ +NestedColor.prototype['size'] = undefined; + +/** + * @member {module:model/Color} nested + */ +NestedColor.prototype['nested'] = undefined; + + + + + + +export default NestedColor; + diff --git a/samples/client/petstore/javascript-es6/src/model/NestedOneOf.js b/samples/client/petstore/javascript-es6/src/model/NestedOneOf.js new file mode 100644 index 0000000000..3ea6ed798b --- /dev/null +++ b/samples/client/petstore/javascript-es6/src/model/NestedOneOf.js @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Pig from './Pig'; + +/** + * The NestedOneOf model module. + * @module model/NestedOneOf + * @version 1.0.0 + */ +class NestedOneOf { + /** + * Constructs a new NestedOneOf. + * @alias module:model/NestedOneOf + */ + constructor() { + + NestedOneOf.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a NestedOneOf from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/NestedOneOf} obj Optional instance to populate. + * @return {module:model/NestedOneOf} The populated NestedOneOf instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new NestedOneOf(); + + if (data.hasOwnProperty('size')) { + obj['size'] = ApiClient.convertToType(data['size'], 'Number'); + } + if (data.hasOwnProperty('nested_pig')) { + obj['nested_pig'] = Pig.constructFromObject(data['nested_pig']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to NestedOneOf. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NestedOneOf. + */ + static validateJSON(data) { + // validate the optional field `nested_pig` + if (data['nested_pig']) { // data not null + Pig.validateJSON(data['nested_pig']); + } + + return true; + } + + +} + + + +/** + * @member {Number} size + */ +NestedOneOf.prototype['size'] = undefined; + +/** + * @member {module:model/Pig} nested_pig + */ +NestedOneOf.prototype['nested_pig'] = undefined; + + + + + + +export default NestedOneOf; + diff --git a/samples/client/petstore/javascript-es6/src/model/NullableClass.js b/samples/client/petstore/javascript-es6/src/model/NullableClass.js index 12a0f2509b..33dd77a182 100644 --- a/samples/client/petstore/javascript-es6/src/model/NullableClass.js +++ b/samples/client/petstore/javascript-es6/src/model/NullableClass.js @@ -91,9 +91,37 @@ class NullableClass { return obj; } + /** + * Validates the JSON data with respect to NullableClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NullableClass. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['string_prop'] && !(typeof data['string_prop'] === 'string' || data['string_prop'] instanceof String)) { + throw new Error("Expected the field `string_prop` to be a primitive type in the JSON string but got " + data['string_prop']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_nullable_prop'])) { + throw new Error("Expected the field `array_nullable_prop` to be an array in the JSON data but got " + data['array_nullable_prop']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_and_items_nullable_prop'])) { + throw new Error("Expected the field `array_and_items_nullable_prop` to be an array in the JSON data but got " + data['array_and_items_nullable_prop']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_items_nullable'])) { + throw new Error("Expected the field `array_items_nullable` to be an array in the JSON data but got " + data['array_items_nullable']); + } + + return true; + } + } + + /** * @member {Number} integer_prop */ diff --git a/samples/client/petstore/javascript-es6/src/model/NumberOnly.js b/samples/client/petstore/javascript-es6/src/model/NumberOnly.js index 449e08bd9a..deb4f2961f 100644 --- a/samples/client/petstore/javascript-es6/src/model/NumberOnly.js +++ b/samples/client/petstore/javascript-es6/src/model/NumberOnly.js @@ -54,9 +54,21 @@ class NumberOnly { return obj; } + /** + * Validates the JSON data with respect to NumberOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NumberOnly. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Number} JustNumber */ diff --git a/samples/client/petstore/javascript-es6/src/model/ObjectWithDeprecatedFields.js b/samples/client/petstore/javascript-es6/src/model/ObjectWithDeprecatedFields.js index a3d0d40094..29e80fd266 100644 --- a/samples/client/petstore/javascript-es6/src/model/ObjectWithDeprecatedFields.js +++ b/samples/client/petstore/javascript-es6/src/model/ObjectWithDeprecatedFields.js @@ -64,9 +64,33 @@ class ObjectWithDeprecatedFields { return obj; } + /** + * Validates the JSON data with respect to ObjectWithDeprecatedFields. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ObjectWithDeprecatedFields. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['uuid'] && !(typeof data['uuid'] === 'string' || data['uuid'] instanceof String)) { + throw new Error("Expected the field `uuid` to be a primitive type in the JSON string but got " + data['uuid']); + } + // validate the optional field `deprecatedRef` + if (data['deprecatedRef']) { // data not null + DeprecatedObject.validateJSON(data['deprecatedRef']); + } + // ensure the json data is an array + if (!Array.isArray(data['bars'])) { + throw new Error("Expected the field `bars` to be an array in the JSON data but got " + data['bars']); + } + + return true; + } + } + + /** * @member {String} uuid */ diff --git a/samples/client/petstore/javascript-es6/src/model/Order.js b/samples/client/petstore/javascript-es6/src/model/Order.js index 1d28748e82..ad586f185d 100644 --- a/samples/client/petstore/javascript-es6/src/model/Order.js +++ b/samples/client/petstore/javascript-es6/src/model/Order.js @@ -69,9 +69,25 @@ class Order { return obj; } + /** + * Validates the JSON data with respect to Order. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Order. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['status'] && !(typeof data['status'] === 'string' || data['status'] instanceof String)) { + throw new Error("Expected the field `status` to be a primitive type in the JSON string but got " + data['status']); + } + + return true; + } + } + + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-es6/src/model/OuterComposite.js b/samples/client/petstore/javascript-es6/src/model/OuterComposite.js index cc4ed6c172..1c6a3c9a85 100644 --- a/samples/client/petstore/javascript-es6/src/model/OuterComposite.js +++ b/samples/client/petstore/javascript-es6/src/model/OuterComposite.js @@ -60,9 +60,25 @@ class OuterComposite { return obj; } + /** + * Validates the JSON data with respect to OuterComposite. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to OuterComposite. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['my_string'] && !(typeof data['my_string'] === 'string' || data['my_string'] instanceof String)) { + throw new Error("Expected the field `my_string` to be a primitive type in the JSON string but got " + data['my_string']); + } + + return true; + } + } + + /** * @member {Number} my_number */ diff --git a/samples/client/petstore/javascript-es6/src/model/OuterObjectWithEnumProperty.js b/samples/client/petstore/javascript-es6/src/model/OuterObjectWithEnumProperty.js index d2ef0e0437..b9ead482af 100644 --- a/samples/client/petstore/javascript-es6/src/model/OuterObjectWithEnumProperty.js +++ b/samples/client/petstore/javascript-es6/src/model/OuterObjectWithEnumProperty.js @@ -57,9 +57,27 @@ class OuterObjectWithEnumProperty { return obj; } + /** + * Validates the JSON data with respect to OuterObjectWithEnumProperty. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to OuterObjectWithEnumProperty. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of OuterObjectWithEnumProperty.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + + return true; + } + } +OuterObjectWithEnumProperty.RequiredProperties = ["value"]; + /** * @member {module:model/OuterEnumInteger} value */ diff --git a/samples/client/petstore/javascript-es6/src/model/Pet.js b/samples/client/petstore/javascript-es6/src/model/Pet.js index b88e5d869f..cc5239c6a1 100644 --- a/samples/client/petstore/javascript-es6/src/model/Pet.js +++ b/samples/client/petstore/javascript-es6/src/model/Pet.js @@ -75,9 +75,53 @@ class Pet { return obj; } + /** + * Validates the JSON data with respect to Pet. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Pet. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Pet.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // validate the optional field `category` + if (data['category']) { // data not null + Category.validateJSON(data['category']); + } + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + // ensure the json data is an array + if (!Array.isArray(data['photoUrls'])) { + throw new Error("Expected the field `photoUrls` to be an array in the JSON data but got " + data['photoUrls']); + } + if (data['tags']) { // data not null + // ensure the json data is an array + if (!Array.isArray(data['tags'])) { + throw new Error("Expected the field `tags` to be an array in the JSON data but got " + data['tags']); + } + // validate the optional field `tags` (array) + for (const item of data['tags']) { + Tag.validateJsonObject(item); + }; + } + // ensure the json data is a string + if (data['status'] && !(typeof data['status'] === 'string' || data['status'] instanceof String)) { + throw new Error("Expected the field `status` to be a primitive type in the JSON string but got " + data['status']); + } + + return true; + } + } +Pet.RequiredProperties = ["name", "photoUrls"]; + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-es6/src/model/Pig.js b/samples/client/petstore/javascript-es6/src/model/Pig.js new file mode 100644 index 0000000000..da6cdc0765 --- /dev/null +++ b/samples/client/petstore/javascript-es6/src/model/Pig.js @@ -0,0 +1,143 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import BasquePig from './BasquePig'; +import DanishPig from './DanishPig'; + +/** + * The Pig model module. + * @module model/Pig + * @version 1.0.0 + */ +class Pig { + /** + * Constructs a new Pig. + * @alias module:model/Pig + * @param {(module:model/BasquePig|module:model/DanishPig)} instance The actual instance to initialize Pig. + */ + constructor(instance = null) { + if (instance === null) { + this.actualInstance = null; + return; + } + var match = 0; + var errorMessages = []; + try { + if (typeof instance === "BasquePig") { + this.actualInstance = instance; + } else { + // plain JS object + // validate the object + BasquePig.validateJSON(instance); // throw an exception if no match + // create BasquePig from JS object + this.actualInstance = BasquePig.constructFromObject(instance); + } + match++; + } catch(err) { + // json data failed to deserialize into BasquePig + errorMessages.push("Failed to construct BasquePig: " + err) + } + + try { + if (typeof instance === "DanishPig") { + this.actualInstance = instance; + } else { + // plain JS object + // validate the object + DanishPig.validateJSON(instance); // throw an exception if no match + // create DanishPig from JS object + this.actualInstance = DanishPig.constructFromObject(instance); + } + match++; + } catch(err) { + // json data failed to deserialize into DanishPig + errorMessages.push("Failed to construct DanishPig: " + err) + } + + if (match > 1) { + throw new Error("Multiple matches found constructing `Pig` with oneOf schemas BasquePig, DanishPig. Input: " + JSON.stringify(instance)); + } else if (match === 0) { + this.actualInstance = null; // clear the actual instance in case there are multiple matches + throw new Error("No match found constructing `Pig` with oneOf schemas BasquePig, DanishPig. Details: " + + errorMessages.join(", ")); + } else { // only 1 match + // the input is valid + } + } + + /** + * Constructs a Pig from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Pig} obj Optional instance to populate. + * @return {module:model/Pig} The populated Pig instance. + */ + static constructFromObject(data, obj) { + return new Pig(data); + } + + /** + * Gets the actaul instance, which can be BasquePig, DanishPig. + * @return {(module:model/BasquePig|module:model/DanishPig)} The actual instance. + */ + getActualInstance() { + return this.actualInstance; + } + + /** + * Sets the actaul instance, which can be BasquePig, DanishPig. + * @param {(module:model/BasquePig|module:model/DanishPig)} obj The actual instance. + */ + setActualInstance(obj) { + this.actualInstance = Pig.constructFromObject(obj).getActualInstance(); + } + + /** + * Returns the JSON representation of the actual intance. + * @return {string} + */ + toJSON = function(){ + return this.getActualInstance(); + } + + /** + * Create an instance of Pig from a JSON string. + * @param {string} json_string JSON string. + * @return {module:model/Pig} An instance of Pig. + */ + static fromJSON = function(json_string){ + return Pig.constructFromObject(JSON.parse(json_string)); + } +} + +/** + * @member {String} className + */ +Pig.prototype['className'] = undefined; + +/** + * @member {String} color + */ +Pig.prototype['color'] = undefined; + +/** + * @member {Number} size + */ +Pig.prototype['size'] = undefined; + + +Pig.OneOf = ["BasquePig", "DanishPig"]; + +export default Pig; + diff --git a/samples/client/petstore/javascript-es6/src/model/ReadOnlyFirst.js b/samples/client/petstore/javascript-es6/src/model/ReadOnlyFirst.js index 8e2a39cf2a..b0fa7628f1 100644 --- a/samples/client/petstore/javascript-es6/src/model/ReadOnlyFirst.js +++ b/samples/client/petstore/javascript-es6/src/model/ReadOnlyFirst.js @@ -57,9 +57,29 @@ class ReadOnlyFirst { return obj; } + /** + * Validates the JSON data with respect to ReadOnlyFirst. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ReadOnlyFirst. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['bar'] && !(typeof data['bar'] === 'string' || data['bar'] instanceof String)) { + throw new Error("Expected the field `bar` to be a primitive type in the JSON string but got " + data['bar']); + } + // ensure the json data is a string + if (data['baz'] && !(typeof data['baz'] === 'string' || data['baz'] instanceof String)) { + throw new Error("Expected the field `baz` to be a primitive type in the JSON string but got " + data['baz']); + } + + return true; + } + } + + /** * @member {String} bar */ diff --git a/samples/client/petstore/javascript-es6/src/model/Return.js b/samples/client/petstore/javascript-es6/src/model/Return.js index 304ebb46f0..616574b5fc 100644 --- a/samples/client/petstore/javascript-es6/src/model/Return.js +++ b/samples/client/petstore/javascript-es6/src/model/Return.js @@ -55,9 +55,21 @@ class Return { return obj; } + /** + * Validates the JSON data with respect to Return. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Return. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Number} return */ diff --git a/samples/client/petstore/javascript-es6/src/model/SingleRefType.js b/samples/client/petstore/javascript-es6/src/model/SingleRefType.js deleted file mode 100644 index 999a69e288..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/SingleRefType.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; -/** -* Enum class SingleRefType. -* @enum {} -* @readonly -*/ -export default class SingleRefType { - - /** - * value: "admin" - * @const - */ - "admin" = "admin"; - - - /** - * value: "user" - * @const - */ - "user" = "user"; - - - - /** - * Returns a SingleRefType enum value from a Javascript object name. - * @param {Object} data The plain JavaScript object containing the name of the enum value. - * @return {module:model/SingleRefType} The enum SingleRefType value. - */ - static constructFromObject(object) { - return object; - } -} - diff --git a/samples/client/petstore/javascript-es6/src/model/SpecialModelName.js b/samples/client/petstore/javascript-es6/src/model/SpecialModelName.js index 45ba7d7ea0..b9ece72292 100644 --- a/samples/client/petstore/javascript-es6/src/model/SpecialModelName.js +++ b/samples/client/petstore/javascript-es6/src/model/SpecialModelName.js @@ -54,9 +54,21 @@ class SpecialModelName { return obj; } + /** + * Validates the JSON data with respect to SpecialModelName. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to SpecialModelName. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Number} $special[property.name] */ diff --git a/samples/client/petstore/javascript-es6/src/model/StringBooleanMap.js b/samples/client/petstore/javascript-es6/src/model/StringBooleanMap.js deleted file mode 100644 index 30172b33f7..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/StringBooleanMap.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The StringBooleanMap model module. - * @module model/StringBooleanMap - * @version 1.0.0 - */ -class StringBooleanMap { - /** - * Constructs a new StringBooleanMap. - * @alias module:model/StringBooleanMap - * @extends Object - */ - constructor() { - - StringBooleanMap.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a StringBooleanMap from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/StringBooleanMap} obj Optional instance to populate. - * @return {module:model/StringBooleanMap} The populated StringBooleanMap instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new StringBooleanMap(); - - ApiClient.constructFromObject(data, obj, 'Boolean'); - - - } - return obj; - } - - -} - - - - - - -export default StringBooleanMap; - diff --git a/samples/client/petstore/javascript-es6/src/model/Tag.js b/samples/client/petstore/javascript-es6/src/model/Tag.js index 3330530c0c..c24706b827 100644 --- a/samples/client/petstore/javascript-es6/src/model/Tag.js +++ b/samples/client/petstore/javascript-es6/src/model/Tag.js @@ -57,9 +57,25 @@ class Tag { return obj; } + /** + * Validates the JSON data with respect to Tag. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Tag. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + + return true; + } + } + + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-es6/src/model/TypeHolderDefault.js b/samples/client/petstore/javascript-es6/src/model/TypeHolderDefault.js deleted file mode 100644 index 819ef864a5..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/TypeHolderDefault.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The TypeHolderDefault model module. - * @module model/TypeHolderDefault - * @version 1.0.0 - */ -class TypeHolderDefault { - /** - * Constructs a new TypeHolderDefault. - * @alias module:model/TypeHolderDefault - * @param stringItem {String} - * @param numberItem {Number} - * @param integerItem {Number} - * @param boolItem {Boolean} - * @param arrayItem {Array.} - */ - constructor(stringItem, numberItem, integerItem, boolItem, arrayItem) { - - TypeHolderDefault.initialize(this, stringItem, numberItem, integerItem, boolItem, arrayItem); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, stringItem, numberItem, integerItem, boolItem, arrayItem) { - obj['string_item'] = stringItem; - obj['number_item'] = numberItem; - obj['integer_item'] = integerItem; - obj['bool_item'] = boolItem; - obj['array_item'] = arrayItem; - } - - /** - * Constructs a TypeHolderDefault from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/TypeHolderDefault} obj Optional instance to populate. - * @return {module:model/TypeHolderDefault} The populated TypeHolderDefault instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new TypeHolderDefault(); - - if (data.hasOwnProperty('string_item')) { - obj['string_item'] = ApiClient.convertToType(data['string_item'], 'String'); - } - if (data.hasOwnProperty('number_item')) { - obj['number_item'] = ApiClient.convertToType(data['number_item'], 'Number'); - } - if (data.hasOwnProperty('integer_item')) { - obj['integer_item'] = ApiClient.convertToType(data['integer_item'], 'Number'); - } - if (data.hasOwnProperty('bool_item')) { - obj['bool_item'] = ApiClient.convertToType(data['bool_item'], 'Boolean'); - } - if (data.hasOwnProperty('array_item')) { - obj['array_item'] = ApiClient.convertToType(data['array_item'], ['Number']); - } - } - return obj; - } - - -} - -/** - * @member {String} string_item - * @default 'what' - */ -TypeHolderDefault.prototype['string_item'] = 'what'; - -/** - * @member {Number} number_item - */ -TypeHolderDefault.prototype['number_item'] = undefined; - -/** - * @member {Number} integer_item - */ -TypeHolderDefault.prototype['integer_item'] = undefined; - -/** - * @member {Boolean} bool_item - * @default true - */ -TypeHolderDefault.prototype['bool_item'] = true; - -/** - * @member {Array.} array_item - */ -TypeHolderDefault.prototype['array_item'] = undefined; - - - - - - -export default TypeHolderDefault; - diff --git a/samples/client/petstore/javascript-es6/src/model/TypeHolderExample.js b/samples/client/petstore/javascript-es6/src/model/TypeHolderExample.js deleted file mode 100644 index 3eeced5696..0000000000 --- a/samples/client/petstore/javascript-es6/src/model/TypeHolderExample.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The TypeHolderExample model module. - * @module model/TypeHolderExample - * @version 1.0.0 - */ -class TypeHolderExample { - /** - * Constructs a new TypeHolderExample. - * @alias module:model/TypeHolderExample - * @param stringItem {String} - * @param numberItem {Number} - * @param integerItem {Number} - * @param boolItem {Boolean} - * @param arrayItem {Array.} - */ - constructor(stringItem, numberItem, integerItem, boolItem, arrayItem) { - - TypeHolderExample.initialize(this, stringItem, numberItem, integerItem, boolItem, arrayItem); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, stringItem, numberItem, integerItem, boolItem, arrayItem) { - obj['string_item'] = stringItem; - obj['number_item'] = numberItem; - obj['integer_item'] = integerItem; - obj['bool_item'] = boolItem; - obj['array_item'] = arrayItem; - } - - /** - * Constructs a TypeHolderExample from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/TypeHolderExample} obj Optional instance to populate. - * @return {module:model/TypeHolderExample} The populated TypeHolderExample instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new TypeHolderExample(); - - if (data.hasOwnProperty('string_item')) { - obj['string_item'] = ApiClient.convertToType(data['string_item'], 'String'); - } - if (data.hasOwnProperty('number_item')) { - obj['number_item'] = ApiClient.convertToType(data['number_item'], 'Number'); - } - if (data.hasOwnProperty('integer_item')) { - obj['integer_item'] = ApiClient.convertToType(data['integer_item'], 'Number'); - } - if (data.hasOwnProperty('bool_item')) { - obj['bool_item'] = ApiClient.convertToType(data['bool_item'], 'Boolean'); - } - if (data.hasOwnProperty('array_item')) { - obj['array_item'] = ApiClient.convertToType(data['array_item'], ['Number']); - } - } - return obj; - } - - -} - -/** - * @member {String} string_item - */ -TypeHolderExample.prototype['string_item'] = undefined; - -/** - * @member {Number} number_item - */ -TypeHolderExample.prototype['number_item'] = undefined; - -/** - * @member {Number} integer_item - */ -TypeHolderExample.prototype['integer_item'] = undefined; - -/** - * @member {Boolean} bool_item - */ -TypeHolderExample.prototype['bool_item'] = undefined; - -/** - * @member {Array.} array_item - */ -TypeHolderExample.prototype['array_item'] = undefined; - - - - - - -export default TypeHolderExample; - diff --git a/samples/client/petstore/javascript-es6/src/model/User.js b/samples/client/petstore/javascript-es6/src/model/User.js index 473bf7c78b..145851f479 100644 --- a/samples/client/petstore/javascript-es6/src/model/User.js +++ b/samples/client/petstore/javascript-es6/src/model/User.js @@ -75,9 +75,45 @@ class User { return obj; } + /** + * Validates the JSON data with respect to User. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to User. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['username'] && !(typeof data['username'] === 'string' || data['username'] instanceof String)) { + throw new Error("Expected the field `username` to be a primitive type in the JSON string but got " + data['username']); + } + // ensure the json data is a string + if (data['firstName'] && !(typeof data['firstName'] === 'string' || data['firstName'] instanceof String)) { + throw new Error("Expected the field `firstName` to be a primitive type in the JSON string but got " + data['firstName']); + } + // ensure the json data is a string + if (data['lastName'] && !(typeof data['lastName'] === 'string' || data['lastName'] instanceof String)) { + throw new Error("Expected the field `lastName` to be a primitive type in the JSON string but got " + data['lastName']); + } + // ensure the json data is a string + if (data['email'] && !(typeof data['email'] === 'string' || data['email'] instanceof String)) { + throw new Error("Expected the field `email` to be a primitive type in the JSON string but got " + data['email']); + } + // ensure the json data is a string + if (data['password'] && !(typeof data['password'] === 'string' || data['password'] instanceof String)) { + throw new Error("Expected the field `password` to be a primitive type in the JSON string but got " + data['password']); + } + // ensure the json data is a string + if (data['phone'] && !(typeof data['phone'] === 'string' || data['phone'] instanceof String)) { + throw new Error("Expected the field `phone` to be a primitive type in the JSON string but got " + data['phone']); + } + + return true; + } + } + + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-es6/test/PetstoreTest.js b/samples/client/petstore/javascript-es6/test/PetstoreTest.js new file mode 100644 index 0000000000..dfa424b5ae --- /dev/null +++ b/samples/client/petstore/javascript-es6/test/PetstoreTest.js @@ -0,0 +1,285 @@ +if (typeof module === 'object' && module.exports) { + var expect = require('expect.js'); + var OpenAPIPetstore = require('../src/index'); + var sinon = require('sinon'); +} + +var apiClient = OpenAPIPetstore.ApiClient.instance; + +var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; +} + +var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; +} + +describe('Petstore', function() { + describe('models', function() { + it('should serialize oneOf models correctly', function() { + var pig = new OpenAPIPetstore.Pig(); + expect(JSON.stringify(pig)).to.be('null'); + + // set basque big as the payload + var bpig = new OpenAPIPetstore.BasquePig(); + setProperty(bpig, "setClassName", "className", "BasquePig"); + setProperty(bpig, "setColor", "color", "red"); + expect(JSON.stringify(bpig)).to.be('{"className":"BasquePig","color":"red"}'); + + pig.setActualInstance(bpig); + expect(JSON.stringify(pig)).to.be('{"className":"BasquePig","color":"red"}'); + + }); + + it('should serialize nested oneOf models correctly', function() { + var nested_one_of = new OpenAPIPetstore.NestedOneOf(); + setProperty(nested_one_of, "setSize", "size", 28); + expect(JSON.stringify(nested_one_of)).to.be('{"size":28}'); + + // set nested oneOf `Pig` + var pig = new OpenAPIPetstore.Pig(); + // set basque big as the payload + var bpig = new OpenAPIPetstore.BasquePig(); + setProperty(bpig, "setClassName", "className", "BasquePig"); + setProperty(bpig, "setColor", "color", "red"); + pig.setActualInstance(bpig); + setProperty(nested_one_of, "setNestedPig", "nested_pig", pig); + + expect(JSON.stringify(nested_one_of)).to.be('{"size":28,"nested_pig":{"className":"BasquePig","color":"red"}}'); + }); + + it('should run BasquePig constructFromObject correctly', function() { + var bpig_json = '{"className":"BasquePig","color":"red"}'; + var bpig = OpenAPIPetstore.BasquePig.constructFromObject(JSON.parse(bpig_json), null); + expect(JSON.stringify(bpig)).to.be('{"className":"BasquePig","color":"red"}'); + + OpenAPIPetstore.BasquePig.validateJSON(JSON.parse(bpig_json)); // should not throw error + }); + + it('should throw error from Pet.validateJSON', function() { + var bpig_json = '{"className":"BasquePig","color":"red"}'; + try { + OpenAPIPetstore.Pet.validateJSON(JSON.parse(bpig_json)); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('The required field `name` is not found in the JSON data: {"className":"BasquePig","color":"red"}')); + } + }); + + it('should run Pig new correctly', function() { + var bpig = OpenAPIPetstore.BasquePig.constructFromObject(JSON.parse('{"className":"BasquePig","color":"red"}')); + var pig = new OpenAPIPetstore.Pig(bpig); + expect(JSON.stringify(pig)).to.be('{"className":"BasquePig","color":"red"}'); + }); + + it('should run Pig constructFromObject correctly', function() { + var bpig = '{"className":"BasquePig","color":"red"}'; + var pig = OpenAPIPetstore.Pig.constructFromObject(JSON.parse(bpig)); + expect(JSON.stringify(pig)).to.be('{"className":"BasquePig","color":"red"}'); + }); + + it('should throw an error when running Pig constructFromObject with incorrect data', function() { + try { + var bpig = '[1,2,3]'; + var pig = OpenAPIPetstore.Pig.constructFromObject(JSON.parse(bpig)); + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing `Pig` with oneOf schemas BasquePig, DanishPig. Details: Failed to construct BasquePig: Error: The required field `className` is not found in the JSON data: [1,2,3], Failed to construct DanishPig: Error: The required field `className` is not found in the JSON data: [1,2,3]')); + } + }); + + it('should deserialize simple models correctly', function() { + var tag_json = '{"id":1,"name":"tag_name"}'; + var tag_result = OpenAPIPetstore.ApiClient.convertToType(tag_json, OpenAPIPetstore.Tag); + expect(tag_result).to.be.a(OpenAPIPetstore.Tag); + //expect(tag_result.id).to.be(1); + //expect(JSON.stringify(tag_result)).to.be(tag_json); + }); + it('should run Color constructFromObject correctly from array', function() { + // construct from RgbColor + let array_integer = [0,128,255]; + let color = OpenAPIPetstore.Color.constructFromObject(array_integer, null); + expect(color).to.be.a(OpenAPIPetstore.Color); + expect(color.getActualInstance()).to.be.eql(array_integer); + }); + + it('should throw an error when running Color constructFromObject with invalid array', function() { + // construct from RgbColor + let array_integer = [0,128,9255]; + try { + let color = OpenAPIPetstore.Color.constructFromObject(array_integer, null); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing `Color` with oneOf schemas String, [Number]. Details: Failed to construct [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: 0,128,9255, Failed to construct [Number]: Error: Invalid array size. Minimim: 4. Maximum: 4. Data: 0,128,9255, Failed to construct String: Error: Invalid data. Must be string. Data: [0,128,9255]')); + } + }); + + it('should run Color new correctly', function() { + // valid hex color + var input = "#00FF00"; + var color = new OpenAPIPetstore.Color(input); + expect(color.getActualInstance()).to.be(input); + + // valid RgbColor + input = [0,128,255]; + color = new OpenAPIPetstore.Color(input); + expect(color.getActualInstance()).to.be(input); + + // valid RgbaColor + input = [0,128,200,255]; + color = new OpenAPIPetstore.Color(input); + expect(color.getActualInstance()).to.be(input); + }); + + it('should run Color constructFromObject correctly', function() { + // valid hex color + var json = '"#00FF00"'; + var color = OpenAPIPetstore.Color.constructFromObject(JSON.parse(json), null); + expect(JSON.stringify(color)).to.be(json); + + // valid RgbColor + json = '[0,128,255]'; + color = OpenAPIPetstore.Color.constructFromObject(JSON.parse(json), null); + expect(JSON.stringify(color)).to.be(json); + + // valid RgbaColor + json = '[0,128,200,255]'; + color = OpenAPIPetstore.Color.constructFromObject(JSON.parse(json), null); + expect(JSON.stringify(color)).to.be(json); + }); + + it('should thrown an error when running Color new with invalid data', function() { + // invalid hex color + try { + let input = "#00FF00ZZZZ"; + new OpenAPIPetstore.Color(input); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid data type. Expecting array. Data: #00FF00ZZZZ, Failed to desserialize JSON data into [Number]: Error: Invalid data type. Expecting array. Data: #00FF00ZZZZ, Failed to desserialize JSON data into String: Error: Invalid string value in an array items. Must conform to /^#(?:[0-9a-fA-F]{3}){1,2}$/. Data: "#00FF00ZZZZ"')); + } + + // invalid RgbColor <0 + try { + let input = [-1,128,255]; + new OpenAPIPetstore.Color(input); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: -1,128,255, Failed to desserialize JSON data into [Number]: Error: Invalid array size. Minimim: 4. Maximum: 4. Data: -1,128,255, Failed to desserialize JSON data into String: Error: Invalid data. Must be string. Data: [-1,128,255]')); + } + + // invalid RgbColor >255 + try { + let input = [1,128,256]; + new OpenAPIPetstore.Color(input); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: 1,128,256, Failed to desserialize JSON data into [Number]: Error: Invalid array size. Minimim: 4. Maximum: 4. Data: 1,128,256, Failed to desserialize JSON data into String: Error: Invalid data. Must be string. Data: [1,128,256]')); + } + + // invalid RgbaColor <0 + try { + let input = [-1,1,128,255]; + new OpenAPIPetstore.Color(input); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid array size. Minimim: 3. Maximum: 3. Data: -1,1,128,255, Failed to desserialize JSON data into [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: -1,1,128,255, Failed to desserialize JSON data into String: Error: Invalid data. Must be string. Data: [-1,1,128,255]')); + } + + // invalid RgbaColor >255 + try { + let input = [1,11,128,256]; + new OpenAPIPetstore.Color(input); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('[Error: No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid array size. Minimim: 3. Maximum: 3. Data: 1,11,128,256, Failed to desserialize JSON data into [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: 1,11,128,256, Failed to desserialize JSON data into String: Error: Invalid data. Must be string. Data: [1,11,128,256]')); + } + }); + + + it('should thrown an error when running Color constructFromObject with invalid data', function() { + // invalid hex color + try { + let json = '"#00FF00ZZZZ"'; + OpenAPIPetstore.Color.constructFromObject(JSON.parse(json), null); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid data type. Expecting array. Data: #00FF00ZZZZ, Failed to desserialize JSON data into [Number]: Error: Invalid data type. Expecting array. Data: #00FF00ZZZZ, Failed to desserialize JSON data into String: Error: Invalid string value in an array items. Must conform to /^#(?:[0-9a-fA-F]{3}){1,2}$/. Data: "#00FF00ZZZZ"')); + } + + // invalid RgbColor <0 + try { + let json = '[-1,128,255]'; + OpenAPIPetstore.Color.constructFromObject(JSON.parse(json), null); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: -1,128,255, Failed to desserialize JSON data into [Number]: Error: Invalid array size. Minimim: 4. Maximum: 4. Data: -1,128,255, Failed to desserialize JSON data into String: Error: Invalid data. Must be string. Data: [-1,128,255]')); + } + + // invalid RgbColor >255 + try { + let json = '[1,128,256]'; + OpenAPIPetstore.Color.constructFromObject(JSON.parse(json), null); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: 1,128,256, Failed to desserialize JSON data into [Number]: Error: Invalid array size. Minimim: 4. Maximum: 4. Data: 1,128,256, Failed to desserialize JSON data into String: Error: Invalid data. Must be string. Data: [1,128,256]')); + } + + // invalid RgbaColor <0 + try { + let json = '[-1,1,128,255]'; + OpenAPIPetstore.Color.constructFromObject(JSON.parse(json), null); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid array size. Minimim: 3. Maximum: 3. Data: -1,1,128,255, Failed to desserialize JSON data into [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: -1,1,128,255, Failed to desserialize JSON data into String: Error: Invalid data. Must be string. Data: [-1,1,128,255]')); + } + + // invalid RgbaColor >255 + try { + let json = '[1,11,128,256]'; + OpenAPIPetstore.Color.constructFromObject(JSON.parse(json), null); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('[Error: No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid array size. Minimim: 3. Maximum: 3. Data: 1,11,128,256, Failed to desserialize JSON data into [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: 1,11,128,256, Failed to desserialize JSON data into String: Error: Invalid data. Must be string. Data: [1,11,128,256]')); + } + }); + + it('should test fromJSON in oneOf models', function() { + // invalid RgbaColor >255 + try { + let json = '[1,11,128,256]'; + OpenAPIPetstore.Color.fromJSON(json); + expect(true).to.be(false); // this line should not run if the error is thrown correctly + } catch (err) { + expect(err).to.be.eql(new Error('[Error: No match found constructing Color with oneOf schemas String, [Number]. Details: Failed to desserialize JSON data into [Number]: Error: Invalid array size. Minimim: 3. Maximum: 3. Data: 1,11,128,256, Failed to desserialize JSON data into [Number]: Error: Invalid integer value in an array items. Max.: 255. Min.: 0. Data: 1,11,128,256, Failed to desserialize JSON data into String: Error: Invalid data. Must be string. Data: [1,11,128,256]')); + } + + // valid RgbColor + let json = '[0,128,255]'; + let color = OpenAPIPetstore.Color.fromJSON(json); + expect(JSON.stringify(color)).to.be(json); + }); + + it('should deserialize NestedColor with nested oneOf model color correctly', function() { + var json = '{"nested":"#00FF00","size":256}' + var result = OpenAPIPetstore.ApiClient.convertToType(JSON.parse(json), OpenAPIPetstore.NestedColor); + expect(result).to.be.a(OpenAPIPetstore.NestedColor); + expect(JSON.stringify(result)).to.be('{"size":256,"nested":"#00FF00"}'); + }); + + it('should deserialize NestedOneOf with nested oneOf model correctly', function() { + var nested_one_of_json = '{"size":28,"nested_pig":{"className":"BasquePig","color":"red"}}' + var result = OpenAPIPetstore.ApiClient.convertToType(JSON.parse(nested_one_of_json), OpenAPIPetstore.NestedOneOf); + expect(result).to.be.a(OpenAPIPetstore.NestedOneOf); + expect(JSON.stringify(result)).to.be(nested_one_of_json); + }); + + }); +}); + diff --git a/samples/client/petstore/javascript-es6/test/api/AnotherFakeApi.spec.js b/samples/client/petstore/javascript-es6/test/api/AnotherFakeApi.spec.js index 7508407842..3212de6605 100644 --- a/samples/client/petstore/javascript-es6/test/api/AnotherFakeApi.spec.js +++ b/samples/client/petstore/javascript-es6/test/api/AnotherFakeApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -48,10 +48,10 @@ } describe('AnotherFakeApi', function() { - describe('testSpecialTags', function() { - it('should call testSpecialTags successfully', function(done) { - //uncomment below and update the code to test testSpecialTags - //instance.testSpecialTags(function(error) { + describe('call123testSpecialTags', function() { + it('should call call123testSpecialTags successfully', function(done) { + //uncomment below and update the code to test call123testSpecialTags + //instance.call123testSpecialTags(function(error) { // if (error) throw error; //expect().to.be(); //}); diff --git a/samples/client/petstore/javascript-es6/test/api/DefaultApi.spec.js b/samples/client/petstore/javascript-es6/test/api/DefaultApi.spec.js index 5d37f0a2e1..34ef8d5c2e 100644 --- a/samples/client/petstore/javascript-es6/test/api/DefaultApi.spec.js +++ b/samples/client/petstore/javascript-es6/test/api/DefaultApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); diff --git a/samples/client/petstore/javascript-es6/test/api/FakeApi.spec.js b/samples/client/petstore/javascript-es6/test/api/FakeApi.spec.js index 7931dbdd6c..9ecfa421cb 100644 --- a/samples/client/petstore/javascript-es6/test/api/FakeApi.spec.js +++ b/samples/client/petstore/javascript-es6/test/api/FakeApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -48,6 +48,26 @@ } describe('FakeApi', function() { + describe('fakeHealthGet', function() { + it('should call fakeHealthGet successfully', function(done) { + //uncomment below and update the code to test fakeHealthGet + //instance.fakeHealthGet(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('fakeHttpSignatureTest', function() { + it('should call fakeHttpSignatureTest successfully', function(done) { + //uncomment below and update the code to test fakeHttpSignatureTest + //instance.fakeHttpSignatureTest(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); describe('fakeOuterBooleanSerialize', function() { it('should call fakeOuterBooleanSerialize successfully', function(done) { //uncomment below and update the code to test fakeOuterBooleanSerialize @@ -88,6 +108,36 @@ done(); }); }); + describe('fakePropertyEnumIntegerSerialize', function() { + it('should call fakePropertyEnumIntegerSerialize successfully', function(done) { + //uncomment below and update the code to test fakePropertyEnumIntegerSerialize + //instance.fakePropertyEnumIntegerSerialize(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testBodyWithBinary', function() { + it('should call testBodyWithBinary successfully', function(done) { + //uncomment below and update the code to test testBodyWithBinary + //instance.testBodyWithBinary(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testBodyWithFileSchema', function() { + it('should call testBodyWithFileSchema successfully', function(done) { + //uncomment below and update the code to test testBodyWithFileSchema + //instance.testBodyWithFileSchema(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); describe('testBodyWithQueryParams', function() { it('should call testBodyWithQueryParams successfully', function(done) { //uncomment below and update the code to test testBodyWithQueryParams @@ -128,6 +178,16 @@ done(); }); }); + describe('testGroupParameters', function() { + it('should call testGroupParameters successfully', function(done) { + //uncomment below and update the code to test testGroupParameters + //instance.testGroupParameters(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); describe('testInlineAdditionalProperties', function() { it('should call testInlineAdditionalProperties successfully', function(done) { //uncomment below and update the code to test testInlineAdditionalProperties @@ -148,6 +208,16 @@ done(); }); }); + describe('testQueryParameterCollectionFormat', function() { + it('should call testQueryParameterCollectionFormat successfully', function(done) { + //uncomment below and update the code to test testQueryParameterCollectionFormat + //instance.testQueryParameterCollectionFormat(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); }); })); diff --git a/samples/client/petstore/javascript-es6/test/api/FakeClassnameTags123Api.spec.js b/samples/client/petstore/javascript-es6/test/api/FakeClassnameTags123Api.spec.js index a9f0780a18..ebe401b08d 100644 --- a/samples/client/petstore/javascript-es6/test/api/FakeClassnameTags123Api.spec.js +++ b/samples/client/petstore/javascript-es6/test/api/FakeClassnameTags123Api.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); diff --git a/samples/client/petstore/javascript-es6/test/api/PetApi.spec.js b/samples/client/petstore/javascript-es6/test/api/PetApi.spec.js index 49dcc06058..e21aa53f7d 100644 --- a/samples/client/petstore/javascript-es6/test/api/PetApi.spec.js +++ b/samples/client/petstore/javascript-es6/test/api/PetApi.spec.js @@ -26,6 +26,7 @@ 'use strict'; var api_instance; + var id = 129038120; beforeEach(function() { api_instance = new OpenApiPetstore.PetApi(); @@ -48,7 +49,6 @@ } var createRandomPet = function() { - var id = new Date().getTime(); var pet = new OpenApiPetstore.Pet(); setProperty(pet, "setId", "id", id); setProperty(pet, "setName", "name", "pet" + id); @@ -81,6 +81,13 @@ expect(response.get('Content-Type')).to.be('application/json'); expect(fetched).to.be.a(OpenApiPetstore.Pet); + expect(JSON.stringify(fetched)).to.be('{"name":"pet129038120","photoUrls":["http://foo.bar.com/1","http://foo.bar.com/2"],"id":129038120,"category":{"name":"category129038120","id":129038120},"tags":[],"status":"available"}'); + + // test ApiClient.convertToType + var tag_result = OpenApiPetstore.ApiClient.convertToType(JSON.stringify(fetched), OpenApiPetstore.Pet); + expect(tag_result).to.be.a(OpenApiPetstore.Pet); + + // test returned object `Pet` expect(fetched.id).to.be(pet.id); expect(getProperty(fetched, "getPhotoUrls", "photoUrls")) .to.eql(getProperty(pet, "getPhotoUrls", "photoUrls")); diff --git a/samples/client/petstore/javascript-es6/test/api/StoreApi.spec.js b/samples/client/petstore/javascript-es6/test/api/StoreApi.spec.js index cd542e15f5..2ad9823032 100644 --- a/samples/client/petstore/javascript-es6/test/api/StoreApi.spec.js +++ b/samples/client/petstore/javascript-es6/test/api/StoreApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); diff --git a/samples/client/petstore/javascript-es6/test/api/UserApi.spec.js b/samples/client/petstore/javascript-es6/test/api/UserApi.spec.js index c5ba7e4e4b..feab9370b1 100644 --- a/samples/client/petstore/javascript-es6/test/api/UserApi.spec.js +++ b/samples/client/petstore/javascript-es6/test/api/UserApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); diff --git a/samples/client/petstore/javascript-es6/test/model/AdditionalPropertiesClass.spec.js b/samples/client/petstore/javascript-es6/test/model/AdditionalPropertiesClass.spec.js index 4c472d5ac5..4086c3a614 100644 --- a/samples/client/petstore/javascript-es6/test/model/AdditionalPropertiesClass.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/AdditionalPropertiesClass.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,19 @@ describe('AdditionalPropertiesClass', function() { it('should create an instance of AdditionalPropertiesClass', function() { // uncomment below and update the code to test AdditionalPropertiesClass - //var instane = new OpenApiPetstore.AdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.AdditionalPropertiesClass(); //expect(instance).to.be.a(OpenApiPetstore.AdditionalPropertiesClass); }); it('should have the property mapProperty (base name: "map_property")', function() { // uncomment below and update the code to test the property mapProperty - //var instane = new OpenApiPetstore.AdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.AdditionalPropertiesClass(); //expect(instance).to.be(); }); it('should have the property mapOfMapProperty (base name: "map_of_map_property")', function() { // uncomment below and update the code to test the property mapOfMapProperty - //var instane = new OpenApiPetstore.AdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.AdditionalPropertiesClass(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Animal.spec.js b/samples/client/petstore/javascript-es6/test/model/Animal.spec.js index dbe9ef41d1..1fedba274c 100644 --- a/samples/client/petstore/javascript-es6/test/model/Animal.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Animal.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,19 @@ describe('Animal', function() { it('should create an instance of Animal', function() { // uncomment below and update the code to test Animal - //var instane = new OpenApiPetstore.Animal(); + //var instance = new OpenApiPetstore.Animal(); //expect(instance).to.be.a(OpenApiPetstore.Animal); }); it('should have the property className (base name: "className")', function() { // uncomment below and update the code to test the property className - //var instane = new OpenApiPetstore.Animal(); + //var instance = new OpenApiPetstore.Animal(); //expect(instance).to.be(); }); it('should have the property color (base name: "color")', function() { // uncomment below and update the code to test the property color - //var instane = new OpenApiPetstore.Animal(); + //var instance = new OpenApiPetstore.Animal(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/ApiResponse.spec.js b/samples/client/petstore/javascript-es6/test/model/ApiResponse.spec.js index 1165094a73..47716b7a52 100644 --- a/samples/client/petstore/javascript-es6/test/model/ApiResponse.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/ApiResponse.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,25 +50,25 @@ describe('ApiResponse', function() { it('should create an instance of ApiResponse', function() { // uncomment below and update the code to test ApiResponse - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be.a(OpenApiPetstore.ApiResponse); }); it('should have the property code (base name: "code")', function() { // uncomment below and update the code to test the property code - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be(); }); it('should have the property type (base name: "type")', function() { // uncomment below and update the code to test the property type - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be(); }); it('should have the property message (base name: "message")', function() { // uncomment below and update the code to test the property message - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/ArrayOfArrayOfNumberOnly.spec.js b/samples/client/petstore/javascript-es6/test/model/ArrayOfArrayOfNumberOnly.spec.js index f30c53f5ed..4bdd2cd2cb 100644 --- a/samples/client/petstore/javascript-es6/test/model/ArrayOfArrayOfNumberOnly.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/ArrayOfArrayOfNumberOnly.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('ArrayOfArrayOfNumberOnly', function() { it('should create an instance of ArrayOfArrayOfNumberOnly', function() { // uncomment below and update the code to test ArrayOfArrayOfNumberOnly - //var instane = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); + //var instance = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); //expect(instance).to.be.a(OpenApiPetstore.ArrayOfArrayOfNumberOnly); }); it('should have the property arrayArrayNumber (base name: "ArrayArrayNumber")', function() { // uncomment below and update the code to test the property arrayArrayNumber - //var instane = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); + //var instance = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/ArrayOfNumberOnly.spec.js b/samples/client/petstore/javascript-es6/test/model/ArrayOfNumberOnly.spec.js index 6c2bc8807d..a44c1a7ea1 100644 --- a/samples/client/petstore/javascript-es6/test/model/ArrayOfNumberOnly.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/ArrayOfNumberOnly.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('ArrayOfNumberOnly', function() { it('should create an instance of ArrayOfNumberOnly', function() { // uncomment below and update the code to test ArrayOfNumberOnly - //var instane = new OpenApiPetstore.ArrayOfNumberOnly(); + //var instance = new OpenApiPetstore.ArrayOfNumberOnly(); //expect(instance).to.be.a(OpenApiPetstore.ArrayOfNumberOnly); }); it('should have the property arrayNumber (base name: "ArrayNumber")', function() { // uncomment below and update the code to test the property arrayNumber - //var instane = new OpenApiPetstore.ArrayOfNumberOnly(); + //var instance = new OpenApiPetstore.ArrayOfNumberOnly(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/ArrayTest.spec.js b/samples/client/petstore/javascript-es6/test/model/ArrayTest.spec.js index ab9294b159..a6bbf95e21 100644 --- a/samples/client/petstore/javascript-es6/test/model/ArrayTest.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/ArrayTest.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,25 +50,25 @@ describe('ArrayTest', function() { it('should create an instance of ArrayTest', function() { // uncomment below and update the code to test ArrayTest - //var instane = new OpenApiPetstore.ArrayTest(); + //var instance = new OpenApiPetstore.ArrayTest(); //expect(instance).to.be.a(OpenApiPetstore.ArrayTest); }); it('should have the property arrayOfString (base name: "array_of_string")', function() { // uncomment below and update the code to test the property arrayOfString - //var instane = new OpenApiPetstore.ArrayTest(); + //var instance = new OpenApiPetstore.ArrayTest(); //expect(instance).to.be(); }); it('should have the property arrayArrayOfInteger (base name: "array_array_of_integer")', function() { // uncomment below and update the code to test the property arrayArrayOfInteger - //var instane = new OpenApiPetstore.ArrayTest(); + //var instance = new OpenApiPetstore.ArrayTest(); //expect(instance).to.be(); }); it('should have the property arrayArrayOfModel (base name: "array_array_of_model")', function() { // uncomment below and update the code to test the property arrayArrayOfModel - //var instane = new OpenApiPetstore.ArrayTest(); + //var instance = new OpenApiPetstore.ArrayTest(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/BasquePig.spec.js b/samples/client/petstore/javascript-es6/test/model/BasquePig.spec.js new file mode 100644 index 0000000000..da5196fc09 --- /dev/null +++ b/samples/client/petstore/javascript-es6/test/model/BasquePig.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.BasquePig(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('BasquePig', function() { + it('should create an instance of BasquePig', function() { + // uncomment below and update the code to test BasquePig + //var instance = new OpenApiPetstore.BasquePig(); + //expect(instance).to.be.a(OpenApiPetstore.BasquePig); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.BasquePig(); + //expect(instance).to.be(); + }); + + it('should have the property color (base name: "color")', function() { + // uncomment below and update the code to test the property color + //var instance = new OpenApiPetstore.BasquePig(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-es6/test/model/Capitalization.spec.js b/samples/client/petstore/javascript-es6/test/model/Capitalization.spec.js index 8be47e3e13..8f14fd583d 100644 --- a/samples/client/petstore/javascript-es6/test/model/Capitalization.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Capitalization.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,43 +50,43 @@ describe('Capitalization', function() { it('should create an instance of Capitalization', function() { // uncomment below and update the code to test Capitalization - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be.a(OpenApiPetstore.Capitalization); }); it('should have the property smallCamel (base name: "smallCamel")', function() { // uncomment below and update the code to test the property smallCamel - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property capitalCamel (base name: "CapitalCamel")', function() { // uncomment below and update the code to test the property capitalCamel - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property smallSnake (base name: "small_Snake")', function() { // uncomment below and update the code to test the property smallSnake - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property capitalSnake (base name: "Capital_Snake")', function() { // uncomment below and update the code to test the property capitalSnake - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property sCAETHFlowPoints (base name: "SCA_ETH_Flow_Points")', function() { // uncomment below and update the code to test the property sCAETHFlowPoints - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property ATT_NAME (base name: "ATT_NAME")', function() { // uncomment below and update the code to test the property ATT_NAME - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Cat.spec.js b/samples/client/petstore/javascript-es6/test/model/Cat.spec.js index 99b7496450..a0c3551cbc 100644 --- a/samples/client/petstore/javascript-es6/test/model/Cat.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Cat.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('Cat', function() { it('should create an instance of Cat', function() { // uncomment below and update the code to test Cat - //var instane = new OpenApiPetstore.Cat(); + //var instance = new OpenApiPetstore.Cat(); //expect(instance).to.be.a(OpenApiPetstore.Cat); }); it('should have the property declawed (base name: "declawed")', function() { // uncomment below and update the code to test the property declawed - //var instane = new OpenApiPetstore.Cat(); + //var instance = new OpenApiPetstore.Cat(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/CatAllOf.spec.js b/samples/client/petstore/javascript-es6/test/model/CatAllOf.spec.js index be4cf8b972..7e9f50eadd 100644 --- a/samples/client/petstore/javascript-es6/test/model/CatAllOf.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/CatAllOf.spec.js @@ -50,13 +50,13 @@ describe('CatAllOf', function() { it('should create an instance of CatAllOf', function() { // uncomment below and update the code to test CatAllOf - //var instane = new OpenApiPetstore.CatAllOf(); + //var instance = new OpenApiPetstore.CatAllOf(); //expect(instance).to.be.a(OpenApiPetstore.CatAllOf); }); it('should have the property declawed (base name: "declawed")', function() { // uncomment below and update the code to test the property declawed - //var instane = new OpenApiPetstore.CatAllOf(); + //var instance = new OpenApiPetstore.CatAllOf(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Category.spec.js b/samples/client/petstore/javascript-es6/test/model/Category.spec.js index 2a02a9e470..c0e132b026 100644 --- a/samples/client/petstore/javascript-es6/test/model/Category.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Category.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,19 @@ describe('Category', function() { it('should create an instance of Category', function() { // uncomment below and update the code to test Category - //var instane = new OpenApiPetstore.Category(); + //var instance = new OpenApiPetstore.Category(); //expect(instance).to.be.a(OpenApiPetstore.Category); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Category(); + //var instance = new OpenApiPetstore.Category(); //expect(instance).to.be(); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Category(); + //var instance = new OpenApiPetstore.Category(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/ClassModel.spec.js b/samples/client/petstore/javascript-es6/test/model/ClassModel.spec.js index d87a995d19..975308a1ce 100644 --- a/samples/client/petstore/javascript-es6/test/model/ClassModel.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/ClassModel.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('ClassModel', function() { it('should create an instance of ClassModel', function() { // uncomment below and update the code to test ClassModel - //var instane = new OpenApiPetstore.ClassModel(); + //var instance = new OpenApiPetstore.ClassModel(); //expect(instance).to.be.a(OpenApiPetstore.ClassModel); }); it('should have the property _class (base name: "_class")', function() { // uncomment below and update the code to test the property _class - //var instane = new OpenApiPetstore.ClassModel(); + //var instance = new OpenApiPetstore.ClassModel(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Client.spec.js b/samples/client/petstore/javascript-es6/test/model/Client.spec.js index 182ad62443..c96ccac7e3 100644 --- a/samples/client/petstore/javascript-es6/test/model/Client.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Client.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('Client', function() { it('should create an instance of Client', function() { // uncomment below and update the code to test Client - //var instane = new OpenApiPetstore.Client(); + //var instance = new OpenApiPetstore.Client(); //expect(instance).to.be.a(OpenApiPetstore.Client); }); it('should have the property client (base name: "client")', function() { // uncomment below and update the code to test the property client - //var instane = new OpenApiPetstore.Client(); + //var instance = new OpenApiPetstore.Client(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Color.spec.js b/samples/client/petstore/javascript-es6/test/model/Color.spec.js new file mode 100644 index 0000000000..f203fe44d2 --- /dev/null +++ b/samples/client/petstore/javascript-es6/test/model/Color.spec.js @@ -0,0 +1,59 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + //instance = new OpenApiPetstore.Color('#00FF00'); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Color', function() { + it('should create an instance of Color', function() { + // uncomment below and update the code to test Color + //var instance = new OpenApiPetstore.Color(); + //expect(instance).to.be.a(OpenApiPetstore.Color); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-es6/test/model/DanishPig.spec.js b/samples/client/petstore/javascript-es6/test/model/DanishPig.spec.js new file mode 100644 index 0000000000..f227291846 --- /dev/null +++ b/samples/client/petstore/javascript-es6/test/model/DanishPig.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.DanishPig(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('DanishPig', function() { + it('should create an instance of DanishPig', function() { + // uncomment below and update the code to test DanishPig + //var instance = new OpenApiPetstore.DanishPig(); + //expect(instance).to.be.a(OpenApiPetstore.DanishPig); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.DanishPig(); + //expect(instance).to.be(); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.DanishPig(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-es6/test/model/DeprecatedObject.spec.js b/samples/client/petstore/javascript-es6/test/model/DeprecatedObject.spec.js index 2273f70a0f..072245e26f 100644 --- a/samples/client/petstore/javascript-es6/test/model/DeprecatedObject.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/DeprecatedObject.spec.js @@ -50,7 +50,7 @@ describe('DeprecatedObject', function() { it('should create an instance of DeprecatedObject', function() { // uncomment below and update the code to test DeprecatedObject - //var instane = new OpenApiPetstore.DeprecatedObject(); + //var instance = new OpenApiPetstore.DeprecatedObject(); //expect(instance).to.be.a(OpenApiPetstore.DeprecatedObject); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Dog.spec.js b/samples/client/petstore/javascript-es6/test/model/Dog.spec.js index 13d1584d01..709cbfa9fd 100644 --- a/samples/client/petstore/javascript-es6/test/model/Dog.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Dog.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('Dog', function() { it('should create an instance of Dog', function() { // uncomment below and update the code to test Dog - //var instane = new OpenApiPetstore.Dog(); + //var instance = new OpenApiPetstore.Dog(); //expect(instance).to.be.a(OpenApiPetstore.Dog); }); it('should have the property breed (base name: "breed")', function() { // uncomment below and update the code to test the property breed - //var instane = new OpenApiPetstore.Dog(); + //var instance = new OpenApiPetstore.Dog(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/DogAllOf.spec.js b/samples/client/petstore/javascript-es6/test/model/DogAllOf.spec.js index 767e3b0071..0bb726203a 100644 --- a/samples/client/petstore/javascript-es6/test/model/DogAllOf.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/DogAllOf.spec.js @@ -50,13 +50,13 @@ describe('DogAllOf', function() { it('should create an instance of DogAllOf', function() { // uncomment below and update the code to test DogAllOf - //var instane = new OpenApiPetstore.DogAllOf(); + //var instance = new OpenApiPetstore.DogAllOf(); //expect(instance).to.be.a(OpenApiPetstore.DogAllOf); }); it('should have the property breed (base name: "breed")', function() { // uncomment below and update the code to test the property breed - //var instane = new OpenApiPetstore.DogAllOf(); + //var instance = new OpenApiPetstore.DogAllOf(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/EnumArrays.spec.js b/samples/client/petstore/javascript-es6/test/model/EnumArrays.spec.js index dae8d83d7f..bda0e3bcf4 100644 --- a/samples/client/petstore/javascript-es6/test/model/EnumArrays.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/EnumArrays.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,19 @@ describe('EnumArrays', function() { it('should create an instance of EnumArrays', function() { // uncomment below and update the code to test EnumArrays - //var instane = new OpenApiPetstore.EnumArrays(); + //var instance = new OpenApiPetstore.EnumArrays(); //expect(instance).to.be.a(OpenApiPetstore.EnumArrays); }); it('should have the property justSymbol (base name: "just_symbol")', function() { // uncomment below and update the code to test the property justSymbol - //var instane = new OpenApiPetstore.EnumArrays(); + //var instance = new OpenApiPetstore.EnumArrays(); //expect(instance).to.be(); }); it('should have the property arrayEnum (base name: "array_enum")', function() { // uncomment below and update the code to test the property arrayEnum - //var instane = new OpenApiPetstore.EnumArrays(); + //var instance = new OpenApiPetstore.EnumArrays(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/EnumClass.spec.js b/samples/client/petstore/javascript-es6/test/model/EnumClass.spec.js index eb5a111791..31924e83d5 100644 --- a/samples/client/petstore/javascript-es6/test/model/EnumClass.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/EnumClass.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -49,7 +49,7 @@ describe('EnumClass', function() { it('should create an instance of EnumClass', function() { // uncomment below and update the code to test EnumClass - //var instane = new OpenApiPetstore.EnumClass(); + //var instance = new OpenApiPetstore.EnumClass(); //expect(instance).to.be.a(OpenApiPetstore.EnumClass); }); diff --git a/samples/client/petstore/javascript-es6/test/model/EnumTest.spec.js b/samples/client/petstore/javascript-es6/test/model/EnumTest.spec.js index 6d7c2519e6..ee14bc9b9d 100644 --- a/samples/client/petstore/javascript-es6/test/model/EnumTest.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/EnumTest.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,37 +50,55 @@ describe('EnumTest', function() { it('should create an instance of EnumTest', function() { // uncomment below and update the code to test EnumTest - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be.a(OpenApiPetstore.EnumTest); }); it('should have the property enumString (base name: "enum_string")', function() { // uncomment below and update the code to test the property enumString - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property enumStringRequired (base name: "enum_string_required")', function() { // uncomment below and update the code to test the property enumStringRequired - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property enumInteger (base name: "enum_integer")', function() { // uncomment below and update the code to test the property enumInteger - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property enumNumber (base name: "enum_number")', function() { // uncomment below and update the code to test the property enumNumber - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property outerEnum (base name: "outerEnum")', function() { // uncomment below and update the code to test the property outerEnum - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property outerEnumInteger (base name: "outerEnumInteger")', function() { + // uncomment below and update the code to test the property outerEnumInteger + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property outerEnumDefaultValue (base name: "outerEnumDefaultValue")', function() { + // uncomment below and update the code to test the property outerEnumDefaultValue + //var instance = new OpenApiPetstore.EnumTest(); + //expect(instance).to.be(); + }); + + it('should have the property outerEnumIntegerDefaultValue (base name: "outerEnumIntegerDefaultValue")', function() { + // uncomment below and update the code to test the property outerEnumIntegerDefaultValue + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/File.spec.js b/samples/client/petstore/javascript-es6/test/model/File.spec.js index 10666dc53c..ac6fbb3de7 100644 --- a/samples/client/petstore/javascript-es6/test/model/File.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/File.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('File', function() { it('should create an instance of File', function() { // uncomment below and update the code to test File - //var instane = new OpenApiPetstore.File(); + //var instance = new OpenApiPetstore.File(); //expect(instance).to.be.a(OpenApiPetstore.File); }); it('should have the property sourceURI (base name: "sourceURI")', function() { // uncomment below and update the code to test the property sourceURI - //var instane = new OpenApiPetstore.File(); + //var instance = new OpenApiPetstore.File(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/FileSchemaTestClass.spec.js b/samples/client/petstore/javascript-es6/test/model/FileSchemaTestClass.spec.js index d6e49689d2..2f00908972 100644 --- a/samples/client/petstore/javascript-es6/test/model/FileSchemaTestClass.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/FileSchemaTestClass.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,19 @@ describe('FileSchemaTestClass', function() { it('should create an instance of FileSchemaTestClass', function() { // uncomment below and update the code to test FileSchemaTestClass - //var instane = new OpenApiPetstore.FileSchemaTestClass(); + //var instance = new OpenApiPetstore.FileSchemaTestClass(); //expect(instance).to.be.a(OpenApiPetstore.FileSchemaTestClass); }); it('should have the property file (base name: "file")', function() { // uncomment below and update the code to test the property file - //var instane = new OpenApiPetstore.FileSchemaTestClass(); + //var instance = new OpenApiPetstore.FileSchemaTestClass(); //expect(instance).to.be(); }); it('should have the property files (base name: "files")', function() { // uncomment below and update the code to test the property files - //var instane = new OpenApiPetstore.FileSchemaTestClass(); + //var instance = new OpenApiPetstore.FileSchemaTestClass(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Foo.spec.js b/samples/client/petstore/javascript-es6/test/model/Foo.spec.js index 19023af6f1..81491fc42c 100644 --- a/samples/client/petstore/javascript-es6/test/model/Foo.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Foo.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('Foo', function() { it('should create an instance of Foo', function() { // uncomment below and update the code to test Foo - //var instane = new OpenApiPetstore.Foo(); + //var instance = new OpenApiPetstore.Foo(); //expect(instance).to.be.a(OpenApiPetstore.Foo); }); it('should have the property bar (base name: "bar")', function() { // uncomment below and update the code to test the property bar - //var instane = new OpenApiPetstore.Foo(); + //var instance = new OpenApiPetstore.Foo(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/FormatTest.spec.js b/samples/client/petstore/javascript-es6/test/model/FormatTest.spec.js index 2e61e4f8ed..6506a39d85 100644 --- a/samples/client/petstore/javascript-es6/test/model/FormatTest.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/FormatTest.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,85 +50,103 @@ describe('FormatTest', function() { it('should create an instance of FormatTest', function() { // uncomment below and update the code to test FormatTest - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be.a(OpenApiPetstore.FormatTest); }); it('should have the property integer (base name: "integer")', function() { // uncomment below and update the code to test the property integer - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property int32 (base name: "int32")', function() { // uncomment below and update the code to test the property int32 - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property int64 (base name: "int64")', function() { // uncomment below and update the code to test the property int64 - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); - it('should have the property _number (base name: "number")', function() { - // uncomment below and update the code to test the property _number - //var instane = new OpenApiPetstore.FormatTest(); + it('should have the property number (base name: "number")', function() { + // uncomment below and update the code to test the property number + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property _float (base name: "float")', function() { // uncomment below and update the code to test the property _float - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property _double (base name: "double")', function() { // uncomment below and update the code to test the property _double - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); - it('should have the property _string (base name: "string")', function() { - // uncomment below and update the code to test the property _string - //var instane = new OpenApiPetstore.FormatTest(); + it('should have the property decimal (base name: "decimal")', function() { + // uncomment below and update the code to test the property decimal + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property string (base name: "string")', function() { + // uncomment below and update the code to test the property string + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property _byte (base name: "byte")', function() { // uncomment below and update the code to test the property _byte - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property binary (base name: "binary")', function() { // uncomment below and update the code to test the property binary - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); - it('should have the property _date (base name: "date")', function() { - // uncomment below and update the code to test the property _date - //var instane = new OpenApiPetstore.FormatTest(); + it('should have the property date (base name: "date")', function() { + // uncomment below and update the code to test the property date + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property dateTime (base name: "dateTime")', function() { // uncomment below and update the code to test the property dateTime - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property uuid (base name: "uuid")', function() { // uncomment below and update the code to test the property uuid - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property password (base name: "password")', function() { // uncomment below and update the code to test the property password - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property patternWithDigits (base name: "pattern_with_digits")', function() { + // uncomment below and update the code to test the property patternWithDigits + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property patternWithDigitsAndDelimiter (base name: "pattern_with_digits_and_delimiter")', function() { + // uncomment below and update the code to test the property patternWithDigitsAndDelimiter + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/HasOnlyReadOnly.spec.js b/samples/client/petstore/javascript-es6/test/model/HasOnlyReadOnly.spec.js index 409e06ad82..e9ba0be44f 100644 --- a/samples/client/petstore/javascript-es6/test/model/HasOnlyReadOnly.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/HasOnlyReadOnly.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,19 @@ describe('HasOnlyReadOnly', function() { it('should create an instance of HasOnlyReadOnly', function() { // uncomment below and update the code to test HasOnlyReadOnly - //var instane = new OpenApiPetstore.HasOnlyReadOnly(); + //var instance = new OpenApiPetstore.HasOnlyReadOnly(); //expect(instance).to.be.a(OpenApiPetstore.HasOnlyReadOnly); }); it('should have the property bar (base name: "bar")', function() { // uncomment below and update the code to test the property bar - //var instane = new OpenApiPetstore.HasOnlyReadOnly(); + //var instance = new OpenApiPetstore.HasOnlyReadOnly(); //expect(instance).to.be(); }); it('should have the property foo (base name: "foo")', function() { // uncomment below and update the code to test the property foo - //var instane = new OpenApiPetstore.HasOnlyReadOnly(); + //var instance = new OpenApiPetstore.HasOnlyReadOnly(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/HealthCheckResult.spec.js b/samples/client/petstore/javascript-es6/test/model/HealthCheckResult.spec.js index fec4b172d8..25d9ecd929 100644 --- a/samples/client/petstore/javascript-es6/test/model/HealthCheckResult.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/HealthCheckResult.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('HealthCheckResult', function() { it('should create an instance of HealthCheckResult', function() { // uncomment below and update the code to test HealthCheckResult - //var instane = new OpenApiPetstore.HealthCheckResult(); + //var instance = new OpenApiPetstore.HealthCheckResult(); //expect(instance).to.be.a(OpenApiPetstore.HealthCheckResult); }); it('should have the property nullableMessage (base name: "NullableMessage")', function() { // uncomment below and update the code to test the property nullableMessage - //var instane = new OpenApiPetstore.HealthCheckResult(); + //var instance = new OpenApiPetstore.HealthCheckResult(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/List.spec.js b/samples/client/petstore/javascript-es6/test/model/List.spec.js index e3a8574d9a..675aa82c18 100644 --- a/samples/client/petstore/javascript-es6/test/model/List.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/List.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('List', function() { it('should create an instance of List', function() { // uncomment below and update the code to test List - //var instane = new OpenApiPetstore.List(); + //var instance = new OpenApiPetstore.List(); //expect(instance).to.be.a(OpenApiPetstore.List); }); it('should have the property _123list (base name: "123-list")', function() { // uncomment below and update the code to test the property _123list - //var instane = new OpenApiPetstore.List(); + //var instance = new OpenApiPetstore.List(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/MapTest.spec.js b/samples/client/petstore/javascript-es6/test/model/MapTest.spec.js index da009beec4..4e7dabcc21 100644 --- a/samples/client/petstore/javascript-es6/test/model/MapTest.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/MapTest.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,31 @@ describe('MapTest', function() { it('should create an instance of MapTest', function() { // uncomment below and update the code to test MapTest - //var instane = new OpenApiPetstore.MapTest(); + //var instance = new OpenApiPetstore.MapTest(); //expect(instance).to.be.a(OpenApiPetstore.MapTest); }); it('should have the property mapMapOfString (base name: "map_map_of_string")', function() { // uncomment below and update the code to test the property mapMapOfString - //var instane = new OpenApiPetstore.MapTest(); + //var instance = new OpenApiPetstore.MapTest(); //expect(instance).to.be(); }); it('should have the property mapOfEnumString (base name: "map_of_enum_string")', function() { // uncomment below and update the code to test the property mapOfEnumString - //var instane = new OpenApiPetstore.MapTest(); + //var instance = new OpenApiPetstore.MapTest(); + //expect(instance).to.be(); + }); + + it('should have the property directMap (base name: "direct_map")', function() { + // uncomment below and update the code to test the property directMap + //var instance = new OpenApiPetstore.MapTest(); + //expect(instance).to.be(); + }); + + it('should have the property indirectMap (base name: "indirect_map")', function() { + // uncomment below and update the code to test the property indirectMap + //var instance = new OpenApiPetstore.MapTest(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js b/samples/client/petstore/javascript-es6/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js index c9174f5615..2e72316a90 100644 --- a/samples/client/petstore/javascript-es6/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,25 +50,25 @@ describe('MixedPropertiesAndAdditionalPropertiesClass', function() { it('should create an instance of MixedPropertiesAndAdditionalPropertiesClass', function() { // uncomment below and update the code to test MixedPropertiesAndAdditionalPropertiesClass - //var instane = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); //expect(instance).to.be.a(OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass); }); it('should have the property uuid (base name: "uuid")', function() { // uncomment below and update the code to test the property uuid - //var instane = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); //expect(instance).to.be(); }); it('should have the property dateTime (base name: "dateTime")', function() { // uncomment below and update the code to test the property dateTime - //var instane = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); //expect(instance).to.be(); }); it('should have the property map (base name: "map")', function() { // uncomment below and update the code to test the property map - //var instane = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Model200Response.spec.js b/samples/client/petstore/javascript-es6/test/model/Model200Response.spec.js index 13f768e973..7cd4da5e51 100644 --- a/samples/client/petstore/javascript-es6/test/model/Model200Response.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Model200Response.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,19 @@ describe('Model200Response', function() { it('should create an instance of Model200Response', function() { // uncomment below and update the code to test Model200Response - //var instane = new OpenApiPetstore.Model200Response(); + //var instance = new OpenApiPetstore.Model200Response(); //expect(instance).to.be.a(OpenApiPetstore.Model200Response); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Model200Response(); + //var instance = new OpenApiPetstore.Model200Response(); //expect(instance).to.be(); }); it('should have the property _class (base name: "class")', function() { // uncomment below and update the code to test the property _class - //var instane = new OpenApiPetstore.Model200Response(); + //var instance = new OpenApiPetstore.Model200Response(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Name.spec.js b/samples/client/petstore/javascript-es6/test/model/Name.spec.js index 3726b8867b..a88057711f 100644 --- a/samples/client/petstore/javascript-es6/test/model/Name.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Name.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,31 +50,31 @@ describe('Name', function() { it('should create an instance of Name', function() { // uncomment below and update the code to test Name - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be.a(OpenApiPetstore.Name); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be(); }); it('should have the property snakeCase (base name: "snake_case")', function() { // uncomment below and update the code to test the property snakeCase - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be(); }); it('should have the property property (base name: "property")', function() { // uncomment below and update the code to test the property property - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be(); }); it('should have the property _123number (base name: "123Number")', function() { // uncomment below and update the code to test the property _123number - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/NestedColor.spec.js b/samples/client/petstore/javascript-es6/test/model/NestedColor.spec.js new file mode 100644 index 0000000000..00a5813236 --- /dev/null +++ b/samples/client/petstore/javascript-es6/test/model/NestedColor.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.NestedColor(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('NestedColor', function() { + it('should create an instance of NestedColor', function() { + // uncomment below and update the code to test NestedColor + //var instance = new OpenApiPetstore.NestedColor(); + //expect(instance).to.be.a(OpenApiPetstore.NestedColor); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.NestedColor(); + //expect(instance).to.be(); + }); + + it('should have the property nested (base name: "nested")', function() { + // uncomment below and update the code to test the property nested + //var instance = new OpenApiPetstore.NestedColor(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-es6/test/model/NestedOneOf.spec.js b/samples/client/petstore/javascript-es6/test/model/NestedOneOf.spec.js new file mode 100644 index 0000000000..5a54e7fbb0 --- /dev/null +++ b/samples/client/petstore/javascript-es6/test/model/NestedOneOf.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.NestedOneOf(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('NestedOneOf', function() { + it('should create an instance of NestedOneOf', function() { + // uncomment below and update the code to test NestedOneOf + //var instance = new OpenApiPetstore.NestedOneOf(); + //expect(instance).to.be.a(OpenApiPetstore.NestedOneOf); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.NestedOneOf(); + //expect(instance).to.be(); + }); + + it('should have the property nestedPig (base name: "nested_pig")', function() { + // uncomment below and update the code to test the property nestedPig + //var instance = new OpenApiPetstore.NestedOneOf(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-es6/test/model/NullableClass.spec.js b/samples/client/petstore/javascript-es6/test/model/NullableClass.spec.js index 89cd2821d4..602a172777 100644 --- a/samples/client/petstore/javascript-es6/test/model/NullableClass.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/NullableClass.spec.js @@ -50,79 +50,79 @@ describe('NullableClass', function() { it('should create an instance of NullableClass', function() { // uncomment below and update the code to test NullableClass - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be.a(OpenApiPetstore.NullableClass); }); it('should have the property integerProp (base name: "integer_prop")', function() { // uncomment below and update the code to test the property integerProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property numberProp (base name: "number_prop")', function() { // uncomment below and update the code to test the property numberProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property booleanProp (base name: "boolean_prop")', function() { // uncomment below and update the code to test the property booleanProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property stringProp (base name: "string_prop")', function() { // uncomment below and update the code to test the property stringProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property dateProp (base name: "date_prop")', function() { // uncomment below and update the code to test the property dateProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property datetimeProp (base name: "datetime_prop")', function() { // uncomment below and update the code to test the property datetimeProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property arrayNullableProp (base name: "array_nullable_prop")', function() { // uncomment below and update the code to test the property arrayNullableProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property arrayAndItemsNullableProp (base name: "array_and_items_nullable_prop")', function() { // uncomment below and update the code to test the property arrayAndItemsNullableProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property arrayItemsNullable (base name: "array_items_nullable")', function() { // uncomment below and update the code to test the property arrayItemsNullable - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property objectNullableProp (base name: "object_nullable_prop")', function() { // uncomment below and update the code to test the property objectNullableProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property objectAndItemsNullableProp (base name: "object_and_items_nullable_prop")', function() { // uncomment below and update the code to test the property objectAndItemsNullableProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property objectItemsNullable (base name: "object_items_nullable")', function() { // uncomment below and update the code to test the property objectItemsNullable - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/NumberOnly.spec.js b/samples/client/petstore/javascript-es6/test/model/NumberOnly.spec.js index 2261973c9a..a39e26134e 100644 --- a/samples/client/petstore/javascript-es6/test/model/NumberOnly.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/NumberOnly.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('NumberOnly', function() { it('should create an instance of NumberOnly', function() { // uncomment below and update the code to test NumberOnly - //var instane = new OpenApiPetstore.NumberOnly(); + //var instance = new OpenApiPetstore.NumberOnly(); //expect(instance).to.be.a(OpenApiPetstore.NumberOnly); }); it('should have the property justNumber (base name: "JustNumber")', function() { // uncomment below and update the code to test the property justNumber - //var instane = new OpenApiPetstore.NumberOnly(); + //var instance = new OpenApiPetstore.NumberOnly(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/ObjectWithDeprecatedFields.spec.js b/samples/client/petstore/javascript-es6/test/model/ObjectWithDeprecatedFields.spec.js index 11a78dce68..b190adcca3 100644 --- a/samples/client/petstore/javascript-es6/test/model/ObjectWithDeprecatedFields.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/ObjectWithDeprecatedFields.spec.js @@ -50,7 +50,7 @@ describe('ObjectWithDeprecatedFields', function() { it('should create an instance of ObjectWithDeprecatedFields', function() { // uncomment below and update the code to test ObjectWithDeprecatedFields - //var instane = new OpenApiPetstore.ObjectWithDeprecatedFields(); + //var instance = new OpenApiPetstore.ObjectWithDeprecatedFields(); //expect(instance).to.be.a(OpenApiPetstore.ObjectWithDeprecatedFields); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Order.spec.js b/samples/client/petstore/javascript-es6/test/model/Order.spec.js index 536d217cc5..88564e2bc6 100644 --- a/samples/client/petstore/javascript-es6/test/model/Order.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Order.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,43 +50,43 @@ describe('Order', function() { it('should create an instance of Order', function() { // uncomment below and update the code to test Order - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be.a(OpenApiPetstore.Order); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property petId (base name: "petId")', function() { // uncomment below and update the code to test the property petId - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property quantity (base name: "quantity")', function() { // uncomment below and update the code to test the property quantity - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property shipDate (base name: "shipDate")', function() { // uncomment below and update the code to test the property shipDate - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property status (base name: "status")', function() { // uncomment below and update the code to test the property status - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property complete (base name: "complete")', function() { // uncomment below and update the code to test the property complete - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/OuterComposite.spec.js b/samples/client/petstore/javascript-es6/test/model/OuterComposite.spec.js index 3309d61942..1ef9599b2d 100644 --- a/samples/client/petstore/javascript-es6/test/model/OuterComposite.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/OuterComposite.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,25 +50,25 @@ describe('OuterComposite', function() { it('should create an instance of OuterComposite', function() { // uncomment below and update the code to test OuterComposite - //var instane = new OpenApiPetstore.OuterComposite(); + //var instance = new OpenApiPetstore.OuterComposite(); //expect(instance).to.be.a(OpenApiPetstore.OuterComposite); }); it('should have the property myNumber (base name: "my_number")', function() { // uncomment below and update the code to test the property myNumber - //var instane = new OpenApiPetstore.OuterComposite(); + //var instance = new OpenApiPetstore.OuterComposite(); //expect(instance).to.be(); }); it('should have the property myString (base name: "my_string")', function() { // uncomment below and update the code to test the property myString - //var instane = new OpenApiPetstore.OuterComposite(); + //var instance = new OpenApiPetstore.OuterComposite(); //expect(instance).to.be(); }); it('should have the property myBoolean (base name: "my_boolean")', function() { // uncomment below and update the code to test the property myBoolean - //var instane = new OpenApiPetstore.OuterComposite(); + //var instance = new OpenApiPetstore.OuterComposite(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/OuterEnum.spec.js b/samples/client/petstore/javascript-es6/test/model/OuterEnum.spec.js index fa51fa90cb..16e8d61479 100644 --- a/samples/client/petstore/javascript-es6/test/model/OuterEnum.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/OuterEnum.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -49,7 +49,7 @@ describe('OuterEnum', function() { it('should create an instance of OuterEnum', function() { // uncomment below and update the code to test OuterEnum - //var instane = new OpenApiPetstore.OuterEnum(); + //var instance = new OpenApiPetstore.OuterEnum(); //expect(instance).to.be.a(OpenApiPetstore.OuterEnum); }); diff --git a/samples/client/petstore/javascript-es6/test/model/OuterEnumDefaultValue.spec.js b/samples/client/petstore/javascript-es6/test/model/OuterEnumDefaultValue.spec.js index 7358f731e7..213f8de637 100644 --- a/samples/client/petstore/javascript-es6/test/model/OuterEnumDefaultValue.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/OuterEnumDefaultValue.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -49,7 +49,7 @@ describe('OuterEnumDefaultValue', function() { it('should create an instance of OuterEnumDefaultValue', function() { // uncomment below and update the code to test OuterEnumDefaultValue - //var instane = new OpenApiPetstore.OuterEnumDefaultValue(); + //var instance = new OpenApiPetstore.OuterEnumDefaultValue(); //expect(instance).to.be.a(OpenApiPetstore.OuterEnumDefaultValue); }); diff --git a/samples/client/petstore/javascript-es6/test/model/OuterEnumInteger.spec.js b/samples/client/petstore/javascript-es6/test/model/OuterEnumInteger.spec.js index d7d09b16ea..50c8b78c5f 100644 --- a/samples/client/petstore/javascript-es6/test/model/OuterEnumInteger.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/OuterEnumInteger.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -49,7 +49,7 @@ describe('OuterEnumInteger', function() { it('should create an instance of OuterEnumInteger', function() { // uncomment below and update the code to test OuterEnumInteger - //var instane = new OpenApiPetstore.OuterEnumInteger(); + //var instance = new OpenApiPetstore.OuterEnumInteger(); //expect(instance).to.be.a(OpenApiPetstore.OuterEnumInteger); }); diff --git a/samples/client/petstore/javascript-es6/test/model/OuterEnumIntegerDefaultValue.spec.js b/samples/client/petstore/javascript-es6/test/model/OuterEnumIntegerDefaultValue.spec.js index 0b9e2f7933..af3dab3119 100644 --- a/samples/client/petstore/javascript-es6/test/model/OuterEnumIntegerDefaultValue.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/OuterEnumIntegerDefaultValue.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -49,7 +49,7 @@ describe('OuterEnumIntegerDefaultValue', function() { it('should create an instance of OuterEnumIntegerDefaultValue', function() { // uncomment below and update the code to test OuterEnumIntegerDefaultValue - //var instane = new OpenApiPetstore.OuterEnumIntegerDefaultValue(); + //var instance = new OpenApiPetstore.OuterEnumIntegerDefaultValue(); //expect(instance).to.be.a(OpenApiPetstore.OuterEnumIntegerDefaultValue); }); diff --git a/samples/client/petstore/javascript-es6/test/model/OuterObjectWithEnumProperty.spec.js b/samples/client/petstore/javascript-es6/test/model/OuterObjectWithEnumProperty.spec.js index ea94c61358..9f7afbfd39 100644 --- a/samples/client/petstore/javascript-es6/test/model/OuterObjectWithEnumProperty.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/OuterObjectWithEnumProperty.spec.js @@ -50,7 +50,7 @@ describe('OuterObjectWithEnumProperty', function() { it('should create an instance of OuterObjectWithEnumProperty', function() { // uncomment below and update the code to test OuterObjectWithEnumProperty - //var instane = new OpenApiPetstore.OuterObjectWithEnumProperty(); + //var instance = new OpenApiPetstore.OuterObjectWithEnumProperty(); //expect(instance).to.be.a(OpenApiPetstore.OuterObjectWithEnumProperty); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Pet.spec.js b/samples/client/petstore/javascript-es6/test/model/Pet.spec.js index f8ce9b93a3..7b2f4cf121 100644 --- a/samples/client/petstore/javascript-es6/test/model/Pet.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Pet.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,43 +50,43 @@ describe('Pet', function() { it('should create an instance of Pet', function() { // uncomment below and update the code to test Pet - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be.a(OpenApiPetstore.Pet); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property category (base name: "category")', function() { // uncomment below and update the code to test the property category - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property photoUrls (base name: "photoUrls")', function() { // uncomment below and update the code to test the property photoUrls - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property tags (base name: "tags")', function() { // uncomment below and update the code to test the property tags - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property status (base name: "status")', function() { // uncomment below and update the code to test the property status - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Pig.spec.js b/samples/client/petstore/javascript-es6/test/model/Pig.spec.js new file mode 100644 index 0000000000..994a590578 --- /dev/null +++ b/samples/client/petstore/javascript-es6/test/model/Pig.spec.js @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Pig(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Pig', function() { + it('should create an instance of Pig', function() { + // uncomment below and update the code to test Pig + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be.a(OpenApiPetstore.Pig); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be(); + }); + + it('should have the property color (base name: "color")', function() { + // uncomment below and update the code to test the property color + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be(); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-es6/test/model/ReadOnlyFirst.spec.js b/samples/client/petstore/javascript-es6/test/model/ReadOnlyFirst.spec.js index 5bc5cb3a70..a9be118d2f 100644 --- a/samples/client/petstore/javascript-es6/test/model/ReadOnlyFirst.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/ReadOnlyFirst.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,19 @@ describe('ReadOnlyFirst', function() { it('should create an instance of ReadOnlyFirst', function() { // uncomment below and update the code to test ReadOnlyFirst - //var instane = new OpenApiPetstore.ReadOnlyFirst(); + //var instance = new OpenApiPetstore.ReadOnlyFirst(); //expect(instance).to.be.a(OpenApiPetstore.ReadOnlyFirst); }); it('should have the property bar (base name: "bar")', function() { // uncomment below and update the code to test the property bar - //var instane = new OpenApiPetstore.ReadOnlyFirst(); + //var instance = new OpenApiPetstore.ReadOnlyFirst(); //expect(instance).to.be(); }); it('should have the property baz (base name: "baz")', function() { // uncomment below and update the code to test the property baz - //var instane = new OpenApiPetstore.ReadOnlyFirst(); + //var instance = new OpenApiPetstore.ReadOnlyFirst(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Return.spec.js b/samples/client/petstore/javascript-es6/test/model/Return.spec.js index 94aa449c27..75aae37c74 100644 --- a/samples/client/petstore/javascript-es6/test/model/Return.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Return.spec.js @@ -50,7 +50,7 @@ describe('Return', function() { it('should create an instance of Return', function() { // uncomment below and update the code to test Return - //var instane = new OpenApiPetstore.Return(); + //var instance = new OpenApiPetstore.Return(); //expect(instance).to.be.a(OpenApiPetstore.Return); }); diff --git a/samples/client/petstore/javascript-es6/test/model/SingleRefType.spec.js b/samples/client/petstore/javascript-es6/test/model/SingleRefType.spec.js deleted file mode 100644 index c0bbb3c018..0000000000 --- a/samples/client/petstore/javascript-es6/test/model/SingleRefType.spec.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -(function(root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. - define(['expect.js', process.cwd()+'/src/index'], factory); - } else if (typeof module === 'object' && module.exports) { - // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require(process.cwd()+'/src/index')); - } else { - // Browser globals (root is window) - factory(root.expect, root.OpenApiPetstore); - } -}(this, function(expect, OpenApiPetstore) { - 'use strict'; - - var instance; - - beforeEach(function() { - }); - - var getProperty = function(object, getter, property) { - // Use getter method if present; otherwise, get the property directly. - if (typeof object[getter] === 'function') - return object[getter](); - else - return object[property]; - } - - var setProperty = function(object, setter, property, value) { - // Use setter method if present; otherwise, set the property directly. - if (typeof object[setter] === 'function') - object[setter](value); - else - object[property] = value; - } - - describe('SingleRefType', function() { - it('should create an instance of SingleRefType', function() { - // uncomment below and update the code to test SingleRefType - //var instance = new OpenApiPetstore.SingleRefType(); - //expect(instance).to.be.a(OpenApiPetstore.SingleRefType); - }); - - }); - -})); diff --git a/samples/client/petstore/javascript-es6/test/model/SpecialModelName.spec.js b/samples/client/petstore/javascript-es6/test/model/SpecialModelName.spec.js index f459d2e0cd..8b6e95c76f 100644 --- a/samples/client/petstore/javascript-es6/test/model/SpecialModelName.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/SpecialModelName.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,13 +50,13 @@ describe('SpecialModelName', function() { it('should create an instance of SpecialModelName', function() { // uncomment below and update the code to test SpecialModelName - //var instane = new OpenApiPetstore.SpecialModelName(); + //var instance = new OpenApiPetstore.SpecialModelName(); //expect(instance).to.be.a(OpenApiPetstore.SpecialModelName); }); it('should have the property specialPropertyName (base name: "$special[property.name]")', function() { // uncomment below and update the code to test the property specialPropertyName - //var instane = new OpenApiPetstore.SpecialModelName(); + //var instance = new OpenApiPetstore.SpecialModelName(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/Tag.spec.js b/samples/client/petstore/javascript-es6/test/model/Tag.spec.js index 2213b06d50..7832664c4f 100644 --- a/samples/client/petstore/javascript-es6/test/model/Tag.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/Tag.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,19 +50,19 @@ describe('Tag', function() { it('should create an instance of Tag', function() { // uncomment below and update the code to test Tag - //var instane = new OpenApiPetstore.Tag(); + //var instance = new OpenApiPetstore.Tag(); //expect(instance).to.be.a(OpenApiPetstore.Tag); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Tag(); + //var instance = new OpenApiPetstore.Tag(); //expect(instance).to.be(); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Tag(); + //var instance = new OpenApiPetstore.Tag(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-es6/test/model/User.spec.js b/samples/client/petstore/javascript-es6/test/model/User.spec.js index f0cd8819ec..44d541dc64 100644 --- a/samples/client/petstore/javascript-es6/test/model/User.spec.js +++ b/samples/client/petstore/javascript-es6/test/model/User.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -14,10 +14,10 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. - define(['expect.js', '../../src/index'], factory); + define(['expect.js', process.cwd()+'/src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require('../../src/index')); + factory(require('expect.js'), require(process.cwd()+'/src/index')); } else { // Browser globals (root is window) factory(root.expect, root.OpenApiPetstore); @@ -50,55 +50,55 @@ describe('User', function() { it('should create an instance of User', function() { // uncomment below and update the code to test User - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be.a(OpenApiPetstore.User); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property username (base name: "username")', function() { // uncomment below and update the code to test the property username - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property firstName (base name: "firstName")', function() { // uncomment below and update the code to test the property firstName - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property lastName (base name: "lastName")', function() { // uncomment below and update the code to test the property lastName - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property email (base name: "email")', function() { // uncomment below and update the code to test the property email - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property password (base name: "password")', function() { // uncomment below and update the code to test the property password - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property phone (base name: "phone")', function() { // uncomment below and update the code to test the property phone - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property userStatus (base name: "userStatus")', function() { // uncomment below and update the code to test the property userStatus - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/.gitignore b/samples/client/petstore/javascript-promise-es6/.gitignore index e920c16718..6a7d6d8ef6 100644 --- a/samples/client/petstore/javascript-promise-es6/.gitignore +++ b/samples/client/petstore/javascript-promise-es6/.gitignore @@ -2,32 +2,129 @@ logs *.log npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed +*.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage +*.lcov -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt +# Bower dependency directory (https://bower.io/) +bower_components + # node-waf configuration .lock-wscript -# Compiled binary addons (http://nodejs.org/api/addons.html) +# Compiled binary addons (https://nodejs.org/api/addons.html) build/Release -# Dependency directory -node_modules +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo # Optional npm cache directory .npm +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + # Optional REPL history .node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp +.cache + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* \ No newline at end of file diff --git a/samples/client/petstore/javascript-promise-es6/.openapi-generator-ignore b/samples/client/petstore/javascript-promise-es6/.openapi-generator-ignore index e9f5c30fed..7484ee590a 100644 --- a/samples/client/petstore/javascript-promise-es6/.openapi-generator-ignore +++ b/samples/client/petstore/javascript-promise-es6/.openapi-generator-ignore @@ -1,11 +1,11 @@ -# Swagger Codegen Ignore -# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen +# 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 Swagger Codgen to ignore just this file by uncommenting the following line: +# 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 (*): @@ -21,4 +21,3 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md -# diff --git a/samples/client/petstore/javascript-promise-es6/.openapi-generator/FILES b/samples/client/petstore/javascript-promise-es6/.openapi-generator/FILES index 0440bb2716..f83260318a 100644 --- a/samples/client/petstore/javascript-promise-es6/.openapi-generator/FILES +++ b/samples/client/petstore/javascript-promise-es6/.openapi-generator/FILES @@ -9,12 +9,15 @@ docs/ApiResponse.md docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfNumberOnly.md docs/ArrayTest.md +docs/BasquePig.md docs/Capitalization.md docs/Cat.md docs/CatAllOf.md docs/Category.md docs/ClassModel.md docs/Client.md +docs/Color.md +docs/DanishPig.md docs/DefaultApi.md docs/DeprecatedObject.md docs/Dog.md @@ -36,6 +39,8 @@ docs/MapTest.md docs/MixedPropertiesAndAdditionalPropertiesClass.md docs/Model200Response.md docs/Name.md +docs/NestedColor.md +docs/NestedOneOf.md docs/NullableClass.md docs/NumberOnly.md docs/ObjectWithDeprecatedFields.md @@ -48,6 +53,7 @@ docs/OuterEnumIntegerDefaultValue.md docs/OuterObjectWithEnumProperty.md docs/Pet.md docs/PetApi.md +docs/Pig.md docs/ReadOnlyFirst.md docs/Return.md docs/SpecialModelName.md @@ -73,12 +79,15 @@ src/model/ApiResponse.js src/model/ArrayOfArrayOfNumberOnly.js src/model/ArrayOfNumberOnly.js src/model/ArrayTest.js +src/model/BasquePig.js src/model/Capitalization.js src/model/Cat.js src/model/CatAllOf.js src/model/Category.js src/model/ClassModel.js src/model/Client.js +src/model/Color.js +src/model/DanishPig.js src/model/DeprecatedObject.js src/model/Dog.js src/model/DogAllOf.js @@ -97,6 +106,8 @@ src/model/MapTest.js src/model/MixedPropertiesAndAdditionalPropertiesClass.js src/model/Model200Response.js src/model/Name.js +src/model/NestedColor.js +src/model/NestedOneOf.js src/model/NullableClass.js src/model/NumberOnly.js src/model/ObjectWithDeprecatedFields.js @@ -108,6 +119,7 @@ src/model/OuterEnumInteger.js src/model/OuterEnumIntegerDefaultValue.js src/model/OuterObjectWithEnumProperty.js src/model/Pet.js +src/model/Pig.js src/model/ReadOnlyFirst.js src/model/Return.js src/model/SpecialModelName.js diff --git a/samples/client/petstore/javascript-promise-es6/README.md b/samples/client/petstore/javascript-promise-es6/README.md index a968da472d..47a8d3c345 100644 --- a/samples/client/petstore/javascript-promise-es6/README.md +++ b/samples/client/petstore/javascript-promise-es6/README.md @@ -169,12 +169,15 @@ Class | Method | HTTP request | Description - [OpenApiPetstore.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [OpenApiPetstore.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [OpenApiPetstore.ArrayTest](docs/ArrayTest.md) + - [OpenApiPetstore.BasquePig](docs/BasquePig.md) - [OpenApiPetstore.Capitalization](docs/Capitalization.md) - [OpenApiPetstore.Cat](docs/Cat.md) - [OpenApiPetstore.CatAllOf](docs/CatAllOf.md) - [OpenApiPetstore.Category](docs/Category.md) - [OpenApiPetstore.ClassModel](docs/ClassModel.md) - [OpenApiPetstore.Client](docs/Client.md) + - [OpenApiPetstore.Color](docs/Color.md) + - [OpenApiPetstore.DanishPig](docs/DanishPig.md) - [OpenApiPetstore.DeprecatedObject](docs/DeprecatedObject.md) - [OpenApiPetstore.Dog](docs/Dog.md) - [OpenApiPetstore.DogAllOf](docs/DogAllOf.md) @@ -193,6 +196,8 @@ Class | Method | HTTP request | Description - [OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [OpenApiPetstore.Model200Response](docs/Model200Response.md) - [OpenApiPetstore.Name](docs/Name.md) + - [OpenApiPetstore.NestedColor](docs/NestedColor.md) + - [OpenApiPetstore.NestedOneOf](docs/NestedOneOf.md) - [OpenApiPetstore.NullableClass](docs/NullableClass.md) - [OpenApiPetstore.NumberOnly](docs/NumberOnly.md) - [OpenApiPetstore.ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) @@ -204,6 +209,7 @@ Class | Method | HTTP request | Description - [OpenApiPetstore.OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) - [OpenApiPetstore.OuterObjectWithEnumProperty](docs/OuterObjectWithEnumProperty.md) - [OpenApiPetstore.Pet](docs/Pet.md) + - [OpenApiPetstore.Pig](docs/Pig.md) - [OpenApiPetstore.ReadOnlyFirst](docs/ReadOnlyFirst.md) - [OpenApiPetstore.Return](docs/Return.md) - [OpenApiPetstore.SpecialModelName](docs/SpecialModelName.md) diff --git a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesAnyType.md deleted file mode 100644 index 4b14f26ad1..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesAnyType.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.AdditionalPropertiesAnyType - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesArray.md b/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesArray.md deleted file mode 100644 index b99e8820d2..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesArray.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.AdditionalPropertiesArray - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesBoolean.md deleted file mode 100644 index db3f089ce9..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesBoolean.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.AdditionalPropertiesBoolean - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesInteger.md deleted file mode 100644 index be98887371..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesInteger.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.AdditionalPropertiesInteger - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesNumber.md deleted file mode 100644 index 6f4273d6eb..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesNumber.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.AdditionalPropertiesNumber - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesObject.md b/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesObject.md deleted file mode 100644 index 58a9278418..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesObject.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.AdditionalPropertiesObject - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesString.md b/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesString.md deleted file mode 100644 index ee6ad171ee..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/AdditionalPropertiesString.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.AdditionalPropertiesString - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/BasquePig.md b/samples/client/petstore/javascript-promise-es6/docs/BasquePig.md new file mode 100644 index 0000000000..77d1e74bc7 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/docs/BasquePig.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.BasquePig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | + + diff --git a/samples/client/petstore/javascript-promise-es6/docs/BigCat.md b/samples/client/petstore/javascript-promise-es6/docs/BigCat.md deleted file mode 100644 index bbd79b2ba1..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/BigCat.md +++ /dev/null @@ -1,24 +0,0 @@ -# OpenApiPetstore.BigCat - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**kind** | **String** | | [optional] - - - -## Enum: KindEnum - - -* `lions` (value: `"lions"`) - -* `tigers` (value: `"tigers"`) - -* `leopards` (value: `"leopards"`) - -* `jaguars` (value: `"jaguars"`) - - - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/BigCatAllOf.md b/samples/client/petstore/javascript-promise-es6/docs/BigCatAllOf.md deleted file mode 100644 index c5e83bfdae..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/BigCatAllOf.md +++ /dev/null @@ -1,24 +0,0 @@ -# OpenApiPetstore.BigCatAllOf - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**kind** | **String** | | [optional] - - - -## Enum: KindEnum - - -* `lions` (value: `"lions"`) - -* `tigers` (value: `"tigers"`) - -* `leopards` (value: `"leopards"`) - -* `jaguars` (value: `"jaguars"`) - - - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/Color.md b/samples/client/petstore/javascript-promise-es6/docs/Color.md new file mode 100644 index 0000000000..5f0e6f0dfb --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/docs/Color.md @@ -0,0 +1,8 @@ +# OpenApiPetstore.Color + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/javascript-promise-es6/docs/DanishPig.md b/samples/client/petstore/javascript-promise-es6/docs/DanishPig.md new file mode 100644 index 0000000000..7de3e60db3 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/docs/DanishPig.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.DanishPig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**size** | **Number** | | + + diff --git a/samples/client/petstore/javascript-promise-es6/docs/InlineObject.md b/samples/client/petstore/javascript-promise-es6/docs/InlineObject.md deleted file mode 100644 index 529c032d7a..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/InlineObject.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.InlineObject - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | Updated name of the pet | [optional] -**status** | **String** | Updated status of the pet | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/InlineObject1.md b/samples/client/petstore/javascript-promise-es6/docs/InlineObject1.md deleted file mode 100644 index bd2fcd57a2..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/InlineObject1.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.InlineObject1 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**file** | **File** | file to upload | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/InlineObject2.md b/samples/client/petstore/javascript-promise-es6/docs/InlineObject2.md deleted file mode 100644 index 7d703a9086..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/InlineObject2.md +++ /dev/null @@ -1,34 +0,0 @@ -# OpenApiPetstore.InlineObject2 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enumFormStringArray** | **[String]** | Form parameter enum test (string array) | [optional] -**enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to '-efg'] - - - -## Enum: [EnumFormStringArrayEnum] - - -* `GREATER_THAN` (value: `">"`) - -* `DOLLAR` (value: `"$"`) - - - - - -## Enum: EnumFormStringEnum - - -* `_abc` (value: `"_abc"`) - -* `-efg` (value: `"-efg"`) - -* `(xyz)` (value: `"(xyz)"`) - - - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/InlineObject3.md b/samples/client/petstore/javascript-promise-es6/docs/InlineObject3.md deleted file mode 100644 index ec8980b728..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/InlineObject3.md +++ /dev/null @@ -1,22 +0,0 @@ -# OpenApiPetstore.InlineObject3 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | **Number** | None | [optional] -**int32** | **Number** | None | [optional] -**int64** | **Number** | None | [optional] -**_number** | **Number** | None | -**_float** | **Number** | None | [optional] -**_double** | **Number** | None | -**_string** | **String** | None | [optional] -**patternWithoutDelimiter** | **String** | None | -**_byte** | **Blob** | None | -**binary** | **File** | None | [optional] -**_date** | **Date** | None | [optional] -**dateTime** | **Date** | None | [optional] -**password** | **String** | None | [optional] -**callback** | **String** | None | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/InlineObject4.md b/samples/client/petstore/javascript-promise-es6/docs/InlineObject4.md deleted file mode 100644 index 07ce4b0cac..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/InlineObject4.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.InlineObject4 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**param** | **String** | field1 | -**param2** | **String** | field2 | - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/InlineObject5.md b/samples/client/petstore/javascript-promise-es6/docs/InlineObject5.md deleted file mode 100644 index 16547e7f52..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/InlineObject5.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.InlineObject5 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**requiredFile** | **File** | file to upload | - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/InlineResponseDefault.md b/samples/client/petstore/javascript-promise-es6/docs/InlineResponseDefault.md deleted file mode 100644 index 3bd01f8f7d..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/InlineResponseDefault.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.InlineResponseDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**string** | [**Foo**](Foo.md) | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/ModelReturn.md b/samples/client/petstore/javascript-promise-es6/docs/ModelReturn.md deleted file mode 100644 index c93601692f..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/ModelReturn.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenApiPetstore.ModelReturn - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**_return** | **Number** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/NestedColor.md b/samples/client/petstore/javascript-promise-es6/docs/NestedColor.md new file mode 100644 index 0000000000..aea6b44494 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/docs/NestedColor.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.NestedColor + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**size** | **Number** | | [optional] +**nested** | [**Color**](Color.md) | | [optional] + + diff --git a/samples/client/petstore/javascript-promise-es6/docs/NestedOneOf.md b/samples/client/petstore/javascript-promise-es6/docs/NestedOneOf.md new file mode 100644 index 0000000000..b5228e89c7 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/docs/NestedOneOf.md @@ -0,0 +1,10 @@ +# OpenApiPetstore.NestedOneOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**size** | **Number** | | [optional] +**nestedPig** | [**Pig**](Pig.md) | | [optional] + + diff --git a/samples/client/petstore/javascript-promise-es6/docs/Pig.md b/samples/client/petstore/javascript-promise-es6/docs/Pig.md new file mode 100644 index 0000000000..a94e1687cc --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/docs/Pig.md @@ -0,0 +1,11 @@ +# OpenApiPetstore.Pig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | +**size** | **Number** | | + + diff --git a/samples/client/petstore/javascript-promise-es6/docs/SingleRefType.md b/samples/client/petstore/javascript-promise-es6/docs/SingleRefType.md deleted file mode 100644 index 6a7ac770c2..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/SingleRefType.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenApiPetstore.SingleRefType - -## Enum - - -* `admin` (value: `"admin"`) - -* `user` (value: `"user"`) - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/TypeHolderDefault.md b/samples/client/petstore/javascript-promise-es6/docs/TypeHolderDefault.md deleted file mode 100644 index 3342b50076..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/TypeHolderDefault.md +++ /dev/null @@ -1,13 +0,0 @@ -# OpenApiPetstore.TypeHolderDefault - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**stringItem** | **String** | | [default to 'what'] -**numberItem** | **Number** | | -**integerItem** | **Number** | | -**boolItem** | **Boolean** | | [default to true] -**arrayItem** | **[Number]** | | - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/TypeHolderExample.md b/samples/client/petstore/javascript-promise-es6/docs/TypeHolderExample.md deleted file mode 100644 index 44ba1e3aef..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/TypeHolderExample.md +++ /dev/null @@ -1,14 +0,0 @@ -# OpenApiPetstore.TypeHolderExample - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**stringItem** | **String** | | -**numberItem** | **Number** | | -**floatItem** | **Number** | | -**integerItem** | **Number** | | -**boolItem** | **Boolean** | | -**arrayItem** | **[Number]** | | - - diff --git a/samples/client/petstore/javascript-promise-es6/docs/XmlItem.md b/samples/client/petstore/javascript-promise-es6/docs/XmlItem.md deleted file mode 100644 index 8711fac408..0000000000 --- a/samples/client/petstore/javascript-promise-es6/docs/XmlItem.md +++ /dev/null @@ -1,37 +0,0 @@ -# OpenApiPetstore.XmlItem - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**attributeString** | **String** | | [optional] -**attributeNumber** | **Number** | | [optional] -**attributeInteger** | **Number** | | [optional] -**attributeBoolean** | **Boolean** | | [optional] -**wrappedArray** | **[Number]** | | [optional] -**nameString** | **String** | | [optional] -**nameNumber** | **Number** | | [optional] -**nameInteger** | **Number** | | [optional] -**nameBoolean** | **Boolean** | | [optional] -**nameArray** | **[Number]** | | [optional] -**nameWrappedArray** | **[Number]** | | [optional] -**prefixString** | **String** | | [optional] -**prefixNumber** | **Number** | | [optional] -**prefixInteger** | **Number** | | [optional] -**prefixBoolean** | **Boolean** | | [optional] -**prefixArray** | **[Number]** | | [optional] -**prefixWrappedArray** | **[Number]** | | [optional] -**namespaceString** | **String** | | [optional] -**namespaceNumber** | **Number** | | [optional] -**namespaceInteger** | **Number** | | [optional] -**namespaceBoolean** | **Boolean** | | [optional] -**namespaceArray** | **[Number]** | | [optional] -**namespaceWrappedArray** | **[Number]** | | [optional] -**prefixNsString** | **String** | | [optional] -**prefixNsNumber** | **Number** | | [optional] -**prefixNsInteger** | **Number** | | [optional] -**prefixNsBoolean** | **Boolean** | | [optional] -**prefixNsArray** | **[Number]** | | [optional] -**prefixNsWrappedArray** | **[Number]** | | [optional] - - diff --git a/samples/client/petstore/javascript-promise-es6/package.json b/samples/client/petstore/javascript-promise-es6/package.json index dfa8bf720f..e457ebe7e0 100644 --- a/samples/client/petstore/javascript-promise-es6/package.json +++ b/samples/client/petstore/javascript-promise-es6/package.json @@ -1,7 +1,7 @@ { "name": "open_api_petstore", "version": "1.0.0", - "description": "This_spec_is_mainly_for_testing_Petstore_server_and_contains_fake_endpoints_models__Please_do_not_use_this_for_any_other_purpose__Special_characters___", + "description": "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\", "license": "Apache-2.0", "main": "dist/index.js", "scripts": { diff --git a/samples/client/petstore/javascript-promise-es6/src/index.js b/samples/client/petstore/javascript-promise-es6/src/index.js index a75a817c26..a95a17ec1b 100644 --- a/samples/client/petstore/javascript-promise-es6/src/index.js +++ b/samples/client/petstore/javascript-promise-es6/src/index.js @@ -19,12 +19,15 @@ import ApiResponse from './model/ApiResponse'; import ArrayOfArrayOfNumberOnly from './model/ArrayOfArrayOfNumberOnly'; import ArrayOfNumberOnly from './model/ArrayOfNumberOnly'; import ArrayTest from './model/ArrayTest'; +import BasquePig from './model/BasquePig'; import Capitalization from './model/Capitalization'; import Cat from './model/Cat'; import CatAllOf from './model/CatAllOf'; import Category from './model/Category'; import ClassModel from './model/ClassModel'; import Client from './model/Client'; +import Color from './model/Color'; +import DanishPig from './model/DanishPig'; import DeprecatedObject from './model/DeprecatedObject'; import Dog from './model/Dog'; import DogAllOf from './model/DogAllOf'; @@ -43,6 +46,8 @@ import MapTest from './model/MapTest'; import MixedPropertiesAndAdditionalPropertiesClass from './model/MixedPropertiesAndAdditionalPropertiesClass'; import Model200Response from './model/Model200Response'; import Name from './model/Name'; +import NestedColor from './model/NestedColor'; +import NestedOneOf from './model/NestedOneOf'; import NullableClass from './model/NullableClass'; import NumberOnly from './model/NumberOnly'; import ObjectWithDeprecatedFields from './model/ObjectWithDeprecatedFields'; @@ -54,6 +59,7 @@ import OuterEnumInteger from './model/OuterEnumInteger'; import OuterEnumIntegerDefaultValue from './model/OuterEnumIntegerDefaultValue'; import OuterObjectWithEnumProperty from './model/OuterObjectWithEnumProperty'; import Pet from './model/Pet'; +import Pig from './model/Pig'; import ReadOnlyFirst from './model/ReadOnlyFirst'; import Return from './model/Return'; import SpecialModelName from './model/SpecialModelName'; @@ -69,7 +75,7 @@ import UserApi from './api/UserApi'; /** -* This_spec_is_mainly_for_testing_Petstore_server_and_contains_fake_endpoints_models__Please_do_not_use_this_for_any_other_purpose__Special_characters___.
        +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\.
        * The index module provides access to constructors for all the classes which comprise the public API. *

        * An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: @@ -142,6 +148,12 @@ export { */ ArrayTest, + /** + * The BasquePig model constructor. + * @property {module:model/BasquePig} + */ + BasquePig, + /** * The Capitalization model constructor. * @property {module:model/Capitalization} @@ -178,6 +190,18 @@ export { */ Client, + /** + * The Color model constructor. + * @property {module:model/Color} + */ + Color, + + /** + * The DanishPig model constructor. + * @property {module:model/DanishPig} + */ + DanishPig, + /** * The DeprecatedObject model constructor. * @property {module:model/DeprecatedObject} @@ -286,6 +310,18 @@ export { */ Name, + /** + * The NestedColor model constructor. + * @property {module:model/NestedColor} + */ + NestedColor, + + /** + * The NestedOneOf model constructor. + * @property {module:model/NestedOneOf} + */ + NestedOneOf, + /** * The NullableClass model constructor. * @property {module:model/NullableClass} @@ -352,6 +388,12 @@ export { */ Pet, + /** + * The Pig model constructor. + * @property {module:model/Pig} + */ + Pig, + /** * The ReadOnlyFirst model constructor. * @property {module:model/ReadOnlyFirst} diff --git a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesAnyType.js b/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesAnyType.js deleted file mode 100644 index b836b0e93c..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesAnyType.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The AdditionalPropertiesAnyType model module. - * @module model/AdditionalPropertiesAnyType - * @version 1.0.0 - */ -class AdditionalPropertiesAnyType { - /** - * Constructs a new AdditionalPropertiesAnyType. - * @alias module:model/AdditionalPropertiesAnyType - * @extends Object - */ - constructor() { - - AdditionalPropertiesAnyType.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a AdditionalPropertiesAnyType from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/AdditionalPropertiesAnyType} obj Optional instance to populate. - * @return {module:model/AdditionalPropertiesAnyType} The populated AdditionalPropertiesAnyType instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new AdditionalPropertiesAnyType(); - - ApiClient.constructFromObject(data, obj, 'Object'); - - - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - } - return obj; - } - - -} - -/** - * @member {String} name - */ -AdditionalPropertiesAnyType.prototype['name'] = undefined; - - - - - - -export default AdditionalPropertiesAnyType; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesArray.js b/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesArray.js deleted file mode 100644 index d630c2f5b7..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesArray.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The AdditionalPropertiesArray model module. - * @module model/AdditionalPropertiesArray - * @version 1.0.0 - */ -class AdditionalPropertiesArray { - /** - * Constructs a new AdditionalPropertiesArray. - * @alias module:model/AdditionalPropertiesArray - * @extends Object - */ - constructor() { - - AdditionalPropertiesArray.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a AdditionalPropertiesArray from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/AdditionalPropertiesArray} obj Optional instance to populate. - * @return {module:model/AdditionalPropertiesArray} The populated AdditionalPropertiesArray instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new AdditionalPropertiesArray(); - - ApiClient.constructFromObject(data, obj, 'Array'); - - - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - } - return obj; - } - - -} - -/** - * @member {String} name - */ -AdditionalPropertiesArray.prototype['name'] = undefined; - - - - - - -export default AdditionalPropertiesArray; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesBoolean.js b/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesBoolean.js deleted file mode 100644 index 57001bb1ff..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesBoolean.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The AdditionalPropertiesBoolean model module. - * @module model/AdditionalPropertiesBoolean - * @version 1.0.0 - */ -class AdditionalPropertiesBoolean { - /** - * Constructs a new AdditionalPropertiesBoolean. - * @alias module:model/AdditionalPropertiesBoolean - * @extends Object - */ - constructor() { - - AdditionalPropertiesBoolean.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a AdditionalPropertiesBoolean from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/AdditionalPropertiesBoolean} obj Optional instance to populate. - * @return {module:model/AdditionalPropertiesBoolean} The populated AdditionalPropertiesBoolean instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new AdditionalPropertiesBoolean(); - - ApiClient.constructFromObject(data, obj, 'Boolean'); - - - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - } - return obj; - } - - -} - -/** - * @member {String} name - */ -AdditionalPropertiesBoolean.prototype['name'] = undefined; - - - - - - -export default AdditionalPropertiesBoolean; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesClass.js b/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesClass.js index d6d83cca28..3849c00c59 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesClass.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesClass.js @@ -57,9 +57,21 @@ class AdditionalPropertiesClass { return obj; } + /** + * Validates the JSON data with respect to AdditionalPropertiesClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to AdditionalPropertiesClass. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Object.} map_property */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesInteger.js b/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesInteger.js deleted file mode 100644 index 6e68ed7ac8..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesInteger.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The AdditionalPropertiesInteger model module. - * @module model/AdditionalPropertiesInteger - * @version 1.0.0 - */ -class AdditionalPropertiesInteger { - /** - * Constructs a new AdditionalPropertiesInteger. - * @alias module:model/AdditionalPropertiesInteger - * @extends Object - */ - constructor() { - - AdditionalPropertiesInteger.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a AdditionalPropertiesInteger from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/AdditionalPropertiesInteger} obj Optional instance to populate. - * @return {module:model/AdditionalPropertiesInteger} The populated AdditionalPropertiesInteger instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new AdditionalPropertiesInteger(); - - ApiClient.constructFromObject(data, obj, 'Number'); - - - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - } - return obj; - } - - -} - -/** - * @member {String} name - */ -AdditionalPropertiesInteger.prototype['name'] = undefined; - - - - - - -export default AdditionalPropertiesInteger; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesNumber.js b/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesNumber.js deleted file mode 100644 index 4acb6986f2..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesNumber.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The AdditionalPropertiesNumber model module. - * @module model/AdditionalPropertiesNumber - * @version 1.0.0 - */ -class AdditionalPropertiesNumber { - /** - * Constructs a new AdditionalPropertiesNumber. - * @alias module:model/AdditionalPropertiesNumber - * @extends Object - */ - constructor() { - - AdditionalPropertiesNumber.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a AdditionalPropertiesNumber from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/AdditionalPropertiesNumber} obj Optional instance to populate. - * @return {module:model/AdditionalPropertiesNumber} The populated AdditionalPropertiesNumber instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new AdditionalPropertiesNumber(); - - ApiClient.constructFromObject(data, obj, 'Number'); - - - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - } - return obj; - } - - -} - -/** - * @member {String} name - */ -AdditionalPropertiesNumber.prototype['name'] = undefined; - - - - - - -export default AdditionalPropertiesNumber; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesObject.js b/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesObject.js deleted file mode 100644 index 14796a296a..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesObject.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The AdditionalPropertiesObject model module. - * @module model/AdditionalPropertiesObject - * @version 1.0.0 - */ -class AdditionalPropertiesObject { - /** - * Constructs a new AdditionalPropertiesObject. - * @alias module:model/AdditionalPropertiesObject - * @extends Object - */ - constructor() { - - AdditionalPropertiesObject.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a AdditionalPropertiesObject from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/AdditionalPropertiesObject} obj Optional instance to populate. - * @return {module:model/AdditionalPropertiesObject} The populated AdditionalPropertiesObject instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new AdditionalPropertiesObject(); - - ApiClient.constructFromObject(data, obj, 'Object'); - - - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - } - return obj; - } - - -} - -/** - * @member {String} name - */ -AdditionalPropertiesObject.prototype['name'] = undefined; - - - - - - -export default AdditionalPropertiesObject; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesString.js b/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesString.js deleted file mode 100644 index f5792a66c5..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/AdditionalPropertiesString.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The AdditionalPropertiesString model module. - * @module model/AdditionalPropertiesString - * @version 1.0.0 - */ -class AdditionalPropertiesString { - /** - * Constructs a new AdditionalPropertiesString. - * @alias module:model/AdditionalPropertiesString - * @extends Object - */ - constructor() { - - AdditionalPropertiesString.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a AdditionalPropertiesString from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/AdditionalPropertiesString} obj Optional instance to populate. - * @return {module:model/AdditionalPropertiesString} The populated AdditionalPropertiesString instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new AdditionalPropertiesString(); - - ApiClient.constructFromObject(data, obj, 'String'); - - - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - } - return obj; - } - - -} - -/** - * @member {String} name - */ -AdditionalPropertiesString.prototype['name'] = undefined; - - - - - - -export default AdditionalPropertiesString; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Animal.js b/samples/client/petstore/javascript-promise-es6/src/model/Animal.js index 7cb9017160..27c6975b59 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Animal.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Animal.js @@ -59,9 +59,35 @@ class Animal { return obj; } + /** + * Validates the JSON data with respect to Animal. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Animal. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Animal.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['className'] && !(typeof data['className'] === 'string' || data['className'] instanceof String)) { + throw new Error("Expected the field `className` to be a primitive type in the JSON string but got " + data['className']); + } + // ensure the json data is a string + if (data['color'] && !(typeof data['color'] === 'string' || data['color'] instanceof String)) { + throw new Error("Expected the field `color` to be a primitive type in the JSON string but got " + data['color']); + } + + return true; + } + } +Animal.RequiredProperties = ["className"]; + /** * @member {String} className */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/ApiResponse.js b/samples/client/petstore/javascript-promise-es6/src/model/ApiResponse.js index f5af17fdf8..6db561122f 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/ApiResponse.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/ApiResponse.js @@ -60,9 +60,29 @@ class ApiResponse { return obj; } + /** + * Validates the JSON data with respect to ApiResponse. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ApiResponse. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['type'] && !(typeof data['type'] === 'string' || data['type'] instanceof String)) { + throw new Error("Expected the field `type` to be a primitive type in the JSON string but got " + data['type']); + } + // ensure the json data is a string + if (data['message'] && !(typeof data['message'] === 'string' || data['message'] instanceof String)) { + throw new Error("Expected the field `message` to be a primitive type in the JSON string but got " + data['message']); + } + + return true; + } + } + + /** * @member {Number} code */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/ArrayOfArrayOfNumberOnly.js b/samples/client/petstore/javascript-promise-es6/src/model/ArrayOfArrayOfNumberOnly.js index eadd7db414..461c6b5b35 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/ArrayOfArrayOfNumberOnly.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/ArrayOfArrayOfNumberOnly.js @@ -54,9 +54,25 @@ class ArrayOfArrayOfNumberOnly { return obj; } + /** + * Validates the JSON data with respect to ArrayOfArrayOfNumberOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ArrayOfArrayOfNumberOnly. + */ + static validateJSON(data) { + // ensure the json data is an array + if (!Array.isArray(data['ArrayArrayNumber'])) { + throw new Error("Expected the field `ArrayArrayNumber` to be an array in the JSON data but got " + data['ArrayArrayNumber']); + } + + return true; + } + } + + /** * @member {Array.>} ArrayArrayNumber */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/ArrayOfNumberOnly.js b/samples/client/petstore/javascript-promise-es6/src/model/ArrayOfNumberOnly.js index 1145a62630..4c2513c107 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/ArrayOfNumberOnly.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/ArrayOfNumberOnly.js @@ -54,9 +54,25 @@ class ArrayOfNumberOnly { return obj; } + /** + * Validates the JSON data with respect to ArrayOfNumberOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ArrayOfNumberOnly. + */ + static validateJSON(data) { + // ensure the json data is an array + if (!Array.isArray(data['ArrayNumber'])) { + throw new Error("Expected the field `ArrayNumber` to be an array in the JSON data but got " + data['ArrayNumber']); + } + + return true; + } + } + + /** * @member {Array.} ArrayNumber */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/ArrayTest.js b/samples/client/petstore/javascript-promise-es6/src/model/ArrayTest.js index 18bc925308..3fc3c9b7f9 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/ArrayTest.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/ArrayTest.js @@ -61,9 +61,33 @@ class ArrayTest { return obj; } + /** + * Validates the JSON data with respect to ArrayTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ArrayTest. + */ + static validateJSON(data) { + // ensure the json data is an array + if (!Array.isArray(data['array_of_string'])) { + throw new Error("Expected the field `array_of_string` to be an array in the JSON data but got " + data['array_of_string']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_array_of_integer'])) { + throw new Error("Expected the field `array_array_of_integer` to be an array in the JSON data but got " + data['array_array_of_integer']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_array_of_model'])) { + throw new Error("Expected the field `array_array_of_model` to be an array in the JSON data but got " + data['array_array_of_model']); + } + + return true; + } + } + + /** * @member {Array.} array_of_string */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/BasquePig.js b/samples/client/petstore/javascript-promise-es6/src/model/BasquePig.js new file mode 100644 index 0000000000..dc26c47c4f --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/src/model/BasquePig.js @@ -0,0 +1,109 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The BasquePig model module. + * @module model/BasquePig + * @version 1.0.0 + */ +class BasquePig { + /** + * Constructs a new BasquePig. + * @alias module:model/BasquePig + * @param className {String} + * @param color {String} + */ + constructor(className, color) { + + BasquePig.initialize(this, className, color); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, className, color) { + obj['className'] = className; + obj['color'] = color; + } + + /** + * Constructs a BasquePig from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/BasquePig} obj Optional instance to populate. + * @return {module:model/BasquePig} The populated BasquePig instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new BasquePig(); + + if (data.hasOwnProperty('className')) { + obj['className'] = ApiClient.convertToType(data['className'], 'String'); + } + if (data.hasOwnProperty('color')) { + obj['color'] = ApiClient.convertToType(data['color'], 'String'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to BasquePig. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to BasquePig. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of BasquePig.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['className'] && !(typeof data['className'] === 'string' || data['className'] instanceof String)) { + throw new Error("Expected the field `className` to be a primitive type in the JSON string but got " + data['className']); + } + // ensure the json data is a string + if (data['color'] && !(typeof data['color'] === 'string' || data['color'] instanceof String)) { + throw new Error("Expected the field `color` to be a primitive type in the JSON string but got " + data['color']); + } + + return true; + } + + +} + +BasquePig.RequiredProperties = ["className", "color"]; + +/** + * @member {String} className + */ +BasquePig.prototype['className'] = undefined; + +/** + * @member {String} color + */ +BasquePig.prototype['color'] = undefined; + + + + + + +export default BasquePig; + diff --git a/samples/client/petstore/javascript-promise-es6/src/model/BigCat.js b/samples/client/petstore/javascript-promise-es6/src/model/BigCat.js deleted file mode 100644 index 764e45d31d..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/BigCat.js +++ /dev/null @@ -1,132 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; -import BigCatAllOf from './BigCatAllOf'; -import Cat from './Cat'; - -/** - * The BigCat model module. - * @module model/BigCat - * @version 1.0.0 - */ -class BigCat { - /** - * Constructs a new BigCat. - * @alias module:model/BigCat - * @extends module:model/Cat - * @implements module:model/Cat - * @implements module:model/BigCatAllOf - * @param className {String} - */ - constructor(className) { - Cat.initialize(this, className);BigCatAllOf.initialize(this); - BigCat.initialize(this, className); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, className) { - } - - /** - * Constructs a BigCat from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/BigCat} obj Optional instance to populate. - * @return {module:model/BigCat} The populated BigCat instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new BigCat(); - Cat.constructFromObject(data, obj); - Cat.constructFromObject(data, obj); - BigCatAllOf.constructFromObject(data, obj); - - if (data.hasOwnProperty('kind')) { - obj['kind'] = ApiClient.convertToType(data['kind'], 'String'); - } - } - return obj; - } - - -} - -/** - * @member {module:model/BigCat.KindEnum} kind - */ -BigCat.prototype['kind'] = undefined; - - -// Implement Cat interface: -/** - * @member {String} className - */ -Cat.prototype['className'] = undefined; -/** - * @member {String} color - * @default 'red' - */ -Cat.prototype['color'] = 'red'; -/** - * @member {Boolean} declawed - */ -Cat.prototype['declawed'] = undefined; -// Implement BigCatAllOf interface: -/** - * @member {module:model/BigCatAllOf.KindEnum} kind - */ -BigCatAllOf.prototype['kind'] = undefined; - - - -/** - * Allowed values for the kind property. - * @enum {String} - * @readonly - */ -BigCat['KindEnum'] = { - - /** - * value: "lions" - * @const - */ - "lions": "lions", - - /** - * value: "tigers" - * @const - */ - "tigers": "tigers", - - /** - * value: "leopards" - * @const - */ - "leopards": "leopards", - - /** - * value: "jaguars" - * @const - */ - "jaguars": "jaguars" -}; - - - -export default BigCat; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/BigCatAllOf.js b/samples/client/petstore/javascript-promise-es6/src/model/BigCatAllOf.js deleted file mode 100644 index 1b79f1a284..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/BigCatAllOf.js +++ /dev/null @@ -1,104 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The BigCatAllOf model module. - * @module model/BigCatAllOf - * @version 1.0.0 - */ -class BigCatAllOf { - /** - * Constructs a new BigCatAllOf. - * @alias module:model/BigCatAllOf - */ - constructor() { - - BigCatAllOf.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a BigCatAllOf from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/BigCatAllOf} obj Optional instance to populate. - * @return {module:model/BigCatAllOf} The populated BigCatAllOf instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new BigCatAllOf(); - - if (data.hasOwnProperty('kind')) { - obj['kind'] = ApiClient.convertToType(data['kind'], 'String'); - } - } - return obj; - } - - -} - -/** - * @member {module:model/BigCatAllOf.KindEnum} kind - */ -BigCatAllOf.prototype['kind'] = undefined; - - - - - -/** - * Allowed values for the kind property. - * @enum {String} - * @readonly - */ -BigCatAllOf['KindEnum'] = { - - /** - * value: "lions" - * @const - */ - "lions": "lions", - - /** - * value: "tigers" - * @const - */ - "tigers": "tigers", - - /** - * value: "leopards" - * @const - */ - "leopards": "leopards", - - /** - * value: "jaguars" - * @const - */ - "jaguars": "jaguars" -}; - - - -export default BigCatAllOf; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Capitalization.js b/samples/client/petstore/javascript-promise-es6/src/model/Capitalization.js index 63b14361fe..cf4ef4348a 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Capitalization.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Capitalization.js @@ -69,9 +69,45 @@ class Capitalization { return obj; } + /** + * Validates the JSON data with respect to Capitalization. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Capitalization. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['smallCamel'] && !(typeof data['smallCamel'] === 'string' || data['smallCamel'] instanceof String)) { + throw new Error("Expected the field `smallCamel` to be a primitive type in the JSON string but got " + data['smallCamel']); + } + // ensure the json data is a string + if (data['CapitalCamel'] && !(typeof data['CapitalCamel'] === 'string' || data['CapitalCamel'] instanceof String)) { + throw new Error("Expected the field `CapitalCamel` to be a primitive type in the JSON string but got " + data['CapitalCamel']); + } + // ensure the json data is a string + if (data['small_Snake'] && !(typeof data['small_Snake'] === 'string' || data['small_Snake'] instanceof String)) { + throw new Error("Expected the field `small_Snake` to be a primitive type in the JSON string but got " + data['small_Snake']); + } + // ensure the json data is a string + if (data['Capital_Snake'] && !(typeof data['Capital_Snake'] === 'string' || data['Capital_Snake'] instanceof String)) { + throw new Error("Expected the field `Capital_Snake` to be a primitive type in the JSON string but got " + data['Capital_Snake']); + } + // ensure the json data is a string + if (data['SCA_ETH_Flow_Points'] && !(typeof data['SCA_ETH_Flow_Points'] === 'string' || data['SCA_ETH_Flow_Points'] instanceof String)) { + throw new Error("Expected the field `SCA_ETH_Flow_Points` to be a primitive type in the JSON string but got " + data['SCA_ETH_Flow_Points']); + } + // ensure the json data is a string + if (data['ATT_NAME'] && !(typeof data['ATT_NAME'] === 'string' || data['ATT_NAME'] instanceof String)) { + throw new Error("Expected the field `ATT_NAME` to be a primitive type in the JSON string but got " + data['ATT_NAME']); + } + + return true; + } + } + + /** * @member {String} smallCamel */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Cat.js b/samples/client/petstore/javascript-promise-es6/src/model/Cat.js index d18ce94e70..203a652cfc 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Cat.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Cat.js @@ -63,9 +63,27 @@ class Cat { return obj; } + /** + * Validates the JSON data with respect to Cat. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Cat. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Cat.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + + return true; + } + } +Cat.RequiredProperties = ["className"]; + /** * @member {Boolean} declawed */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/CatAllOf.js b/samples/client/petstore/javascript-promise-es6/src/model/CatAllOf.js index c71ea7129b..8c0d5bfbbd 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/CatAllOf.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/CatAllOf.js @@ -54,9 +54,21 @@ class CatAllOf { return obj; } + /** + * Validates the JSON data with respect to CatAllOf. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to CatAllOf. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Boolean} declawed */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Category.js b/samples/client/petstore/javascript-promise-es6/src/model/Category.js index 557e8e1862..fc304998f4 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Category.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Category.js @@ -59,9 +59,31 @@ class Category { return obj; } + /** + * Validates the JSON data with respect to Category. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Category. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Category.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + + return true; + } + } +Category.RequiredProperties = ["name"]; + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/ClassModel.js b/samples/client/petstore/javascript-promise-es6/src/model/ClassModel.js index ee1f141777..ba614443eb 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/ClassModel.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/ClassModel.js @@ -55,9 +55,25 @@ class ClassModel { return obj; } + /** + * Validates the JSON data with respect to ClassModel. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ClassModel. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['_class'] && !(typeof data['_class'] === 'string' || data['_class'] instanceof String)) { + throw new Error("Expected the field `_class` to be a primitive type in the JSON string but got " + data['_class']); + } + + return true; + } + } + + /** * @member {String} _class */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Client.js b/samples/client/petstore/javascript-promise-es6/src/model/Client.js index 8521c85043..4089ff37ee 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Client.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Client.js @@ -54,9 +54,25 @@ class Client { return obj; } + /** + * Validates the JSON data with respect to Client. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Client. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['client'] && !(typeof data['client'] === 'string' || data['client'] instanceof String)) { + throw new Error("Expected the field `client` to be a primitive type in the JSON string but got " + data['client']); + } + + return true; + } + } + + /** * @member {String} client */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Color.js b/samples/client/petstore/javascript-promise-es6/src/model/Color.js new file mode 100644 index 0000000000..b071fff068 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/src/model/Color.js @@ -0,0 +1,164 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The Color model module. + * @module model/Color + * @version 1.0.0 + */ +class Color { + /** + * Constructs a new Color. + * RGB array, RGBA array, or hex string. + * @alias module:model/Color + * @param {(module:model/String|module:model/[Number])} instance The actual instance to initialize Color. + */ + constructor(instance = null) { + if (instance === null) { + this.actualInstance = null; + return; + } + var match = 0; + var errorMessages = []; + // RGB three element array with values 0-255. + try { + // validate array data type + if (!Array.isArray(instance)) { + throw new Error("Invalid data type. Expecting array. Input: " + instance); + } + if (instance.length > 3 || instance.length < 3) { + throw new Error("Invalid array size. Minimim: 3. Maximum: 3. Input: " + instance); + } + // validate array of integer + for (const item of instance) { + if (!(typeof item === 'number' && item % 1 === 0)) { + throw new Error("Invalid array items. Must be integer. Input: " + instance); + } + if (item > 255 || item < 0) { + throw new Error("Invalid integer value in an array items. Max.: 255. Min.: 0. Input: " + instance); + } + } + this.actualInstance = instance; + match++; + } catch(err) { + // json data failed to deserialize into [Number] + errorMessages.push("Failed to construct [Number]: " + err) + } + + // RGBA four element array with values 0-255. + try { + // validate array data type + if (!Array.isArray(instance)) { + throw new Error("Invalid data type. Expecting array. Input: " + instance); + } + if (instance.length > 4 || instance.length < 4) { + throw new Error("Invalid array size. Minimim: 4. Maximum: 4. Input: " + instance); + } + // validate array of integer + for (const item of instance) { + if (!(typeof item === 'number' && item % 1 === 0)) { + throw new Error("Invalid array items. Must be integer. Input: " + instance); + } + if (item > 255 || item < 0) { + throw new Error("Invalid integer value in an array items. Max.: 255. Min.: 0. Input: " + instance); + } + } + this.actualInstance = instance; + match++; + } catch(err) { + // json data failed to deserialize into [Number] + errorMessages.push("Failed to construct [Number]: " + err) + } + + // Hex color string, such as #00FF00. + try { + // validate array of string + if (!(typeof instance === 'string')) { + throw new Error("Invalid input. Must be string. Input: " + JSON.stringify(instance)); + } + if (!/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(instance)) { + throw new Error("Invalid string value in an array items. Must conform to /^#(?:[0-9a-fA-F]{3}){1,2}$/. Input: " + JSON.stringify(instance)); + } + if (instance.length > 7 && instance.length < 7) { + throw new Error("Invalid string value in an array items. Max. length: 7. Min. length: 7. Input: " + JSON.stringify(instance)); + } + this.actualInstance = instance; + match++; + } catch(err) { + // json data failed to deserialize into String + errorMessages.push("Failed to construct String: " + err) + } + + if (match > 1) { + throw new Error("Multiple matches found constructing `Color` with oneOf schemas String, [Number]. Input: " + JSON.stringify(instance)); + } else if (match === 0) { + this.actualInstance = null; // clear the actual instance in case there are multiple matches + throw new Error("No match found constructing `Color` with oneOf schemas String, [Number]. Details: " + + errorMessages.join(", ")); + } else { // only 1 match + // the input is valid + } + } + + /** + * Constructs a Color from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Color} obj Optional instance to populate. + * @return {module:model/Color} The populated Color instance. + */ + static constructFromObject(data, obj) { + return new Color(data); + } + + /** + * Gets the actaul instance, which can be String, [Number]. + * @return {(module:model/String|module:model/[Number])} The actual instance. + */ + getActualInstance() { + return this.actualInstance; + } + + /** + * Sets the actaul instance, which can be String, [Number]. + * @param {(module:model/String|module:model/[Number])} obj The actual instance. + */ + setActualInstance(obj) { + this.actualInstance = Color.constructFromObject(obj).getActualInstance(); + } + + /** + * Returns the JSON representation of the actual intance. + * @return {string} + */ + toJSON = function(){ + return this.getActualInstance(); + } + + /** + * Create an instance of Color from a JSON string. + * @param {string} json_string JSON string. + * @return {module:model/Color} An instance of Color. + */ + static fromJSON = function(json_string){ + return Color.constructFromObject(JSON.parse(json_string)); + } +} + + +Color.OneOf = ["String", "[Number]"]; + +export default Color; + diff --git a/samples/client/petstore/javascript-promise-es6/src/model/DanishPig.js b/samples/client/petstore/javascript-promise-es6/src/model/DanishPig.js new file mode 100644 index 0000000000..4023e9d637 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/src/model/DanishPig.js @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; + +/** + * The DanishPig model module. + * @module model/DanishPig + * @version 1.0.0 + */ +class DanishPig { + /** + * Constructs a new DanishPig. + * @alias module:model/DanishPig + * @param className {String} + * @param size {Number} + */ + constructor(className, size) { + + DanishPig.initialize(this, className, size); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj, className, size) { + obj['className'] = className; + obj['size'] = size; + } + + /** + * Constructs a DanishPig from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/DanishPig} obj Optional instance to populate. + * @return {module:model/DanishPig} The populated DanishPig instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new DanishPig(); + + if (data.hasOwnProperty('className')) { + obj['className'] = ApiClient.convertToType(data['className'], 'String'); + } + if (data.hasOwnProperty('size')) { + obj['size'] = ApiClient.convertToType(data['size'], 'Number'); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to DanishPig. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to DanishPig. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of DanishPig.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['className'] && !(typeof data['className'] === 'string' || data['className'] instanceof String)) { + throw new Error("Expected the field `className` to be a primitive type in the JSON string but got " + data['className']); + } + + return true; + } + + +} + +DanishPig.RequiredProperties = ["className", "size"]; + +/** + * @member {String} className + */ +DanishPig.prototype['className'] = undefined; + +/** + * @member {Number} size + */ +DanishPig.prototype['size'] = undefined; + + + + + + +export default DanishPig; + diff --git a/samples/client/petstore/javascript-promise-es6/src/model/DeprecatedObject.js b/samples/client/petstore/javascript-promise-es6/src/model/DeprecatedObject.js index c3298d5020..d7c874345f 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/DeprecatedObject.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/DeprecatedObject.js @@ -54,9 +54,25 @@ class DeprecatedObject { return obj; } + /** + * Validates the JSON data with respect to DeprecatedObject. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to DeprecatedObject. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + + return true; + } + } + + /** * @member {String} name */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Dog.js b/samples/client/petstore/javascript-promise-es6/src/model/Dog.js index b101feecd3..dd3f1ebb50 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Dog.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Dog.js @@ -63,9 +63,31 @@ class Dog { return obj; } + /** + * Validates the JSON data with respect to Dog. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Dog. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Dog.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['breed'] && !(typeof data['breed'] === 'string' || data['breed'] instanceof String)) { + throw new Error("Expected the field `breed` to be a primitive type in the JSON string but got " + data['breed']); + } + + return true; + } + } +Dog.RequiredProperties = ["className"]; + /** * @member {String} breed */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/DogAllOf.js b/samples/client/petstore/javascript-promise-es6/src/model/DogAllOf.js index 58ecede612..beb42db2ec 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/DogAllOf.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/DogAllOf.js @@ -54,9 +54,25 @@ class DogAllOf { return obj; } + /** + * Validates the JSON data with respect to DogAllOf. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to DogAllOf. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['breed'] && !(typeof data['breed'] === 'string' || data['breed'] instanceof String)) { + throw new Error("Expected the field `breed` to be a primitive type in the JSON string but got " + data['breed']); + } + + return true; + } + } + + /** * @member {String} breed */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/EnumArrays.js b/samples/client/petstore/javascript-promise-es6/src/model/EnumArrays.js index 7fe64e3111..2289689e34 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/EnumArrays.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/EnumArrays.js @@ -57,9 +57,29 @@ class EnumArrays { return obj; } + /** + * Validates the JSON data with respect to EnumArrays. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to EnumArrays. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['just_symbol'] && !(typeof data['just_symbol'] === 'string' || data['just_symbol'] instanceof String)) { + throw new Error("Expected the field `just_symbol` to be a primitive type in the JSON string but got " + data['just_symbol']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_enum'])) { + throw new Error("Expected the field `array_enum` to be an array in the JSON data but got " + data['array_enum']); + } + + return true; + } + } + + /** * @member {module:model/EnumArrays.JustSymbolEnum} just_symbol */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/EnumTest.js b/samples/client/petstore/javascript-promise-es6/src/model/EnumTest.js index dc684b7c26..b1556a0613 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/EnumTest.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/EnumTest.js @@ -81,9 +81,35 @@ class EnumTest { return obj; } + /** + * Validates the JSON data with respect to EnumTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to EnumTest. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of EnumTest.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['enum_string'] && !(typeof data['enum_string'] === 'string' || data['enum_string'] instanceof String)) { + throw new Error("Expected the field `enum_string` to be a primitive type in the JSON string but got " + data['enum_string']); + } + // ensure the json data is a string + if (data['enum_string_required'] && !(typeof data['enum_string_required'] === 'string' || data['enum_string_required'] instanceof String)) { + throw new Error("Expected the field `enum_string_required` to be a primitive type in the JSON string but got " + data['enum_string_required']); + } + + return true; + } + } +EnumTest.RequiredProperties = ["enum_string_required"]; + /** * @member {module:model/EnumTest.EnumStringEnum} enum_string */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/File.js b/samples/client/petstore/javascript-promise-es6/src/model/File.js index 12b51b87d8..5f5c9547a1 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/File.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/File.js @@ -55,9 +55,25 @@ class File { return obj; } + /** + * Validates the JSON data with respect to File. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to File. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['sourceURI'] && !(typeof data['sourceURI'] === 'string' || data['sourceURI'] instanceof String)) { + throw new Error("Expected the field `sourceURI` to be a primitive type in the JSON string but got " + data['sourceURI']); + } + + return true; + } + } + + /** * Test capitalization * @member {String} sourceURI diff --git a/samples/client/petstore/javascript-promise-es6/src/model/FileSchemaTestClass.js b/samples/client/petstore/javascript-promise-es6/src/model/FileSchemaTestClass.js index b6fe9e90ec..8174d56245 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/FileSchemaTestClass.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/FileSchemaTestClass.js @@ -57,9 +57,35 @@ class FileSchemaTestClass { return obj; } + /** + * Validates the JSON data with respect to FileSchemaTestClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to FileSchemaTestClass. + */ + static validateJSON(data) { + // validate the optional field `file` + if (data['file']) { // data not null + File.validateJSON(data['file']); + } + if (data['files']) { // data not null + // ensure the json data is an array + if (!Array.isArray(data['files'])) { + throw new Error("Expected the field `files` to be an array in the JSON data but got " + data['files']); + } + // validate the optional field `files` (array) + for (const item of data['files']) { + File.validateJsonObject(item); + }; + } + + return true; + } + } + + /** * @member {File} file */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Foo.js b/samples/client/petstore/javascript-promise-es6/src/model/Foo.js index 3e4477b805..3fc7819f99 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Foo.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Foo.js @@ -54,9 +54,25 @@ class Foo { return obj; } + /** + * Validates the JSON data with respect to Foo. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Foo. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['bar'] && !(typeof data['bar'] === 'string' || data['bar'] instanceof String)) { + throw new Error("Expected the field `bar` to be a primitive type in the JSON string but got " + data['bar']); + } + + return true; + } + } + + /** * @member {String} bar * @default 'bar' diff --git a/samples/client/petstore/javascript-promise-es6/src/model/FooGetDefaultResponse.js b/samples/client/petstore/javascript-promise-es6/src/model/FooGetDefaultResponse.js index ab3558a041..b11d885937 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/FooGetDefaultResponse.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/FooGetDefaultResponse.js @@ -55,9 +55,25 @@ class FooGetDefaultResponse { return obj; } + /** + * Validates the JSON data with respect to FooGetDefaultResponse. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to FooGetDefaultResponse. + */ + static validateJSON(data) { + // validate the optional field `string` + if (data['string']) { // data not null + Foo.validateJSON(data['string']); + } + + return true; + } + } + + /** * @member {module:model/Foo} string */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/FormatTest.js b/samples/client/petstore/javascript-promise-es6/src/model/FormatTest.js index 00ee3533d0..65a34a7ff0 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/FormatTest.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/FormatTest.js @@ -107,9 +107,47 @@ class FormatTest { return obj; } + /** + * Validates the JSON data with respect to FormatTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to FormatTest. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of FormatTest.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['string'] && !(typeof data['string'] === 'string' || data['string'] instanceof String)) { + throw new Error("Expected the field `string` to be a primitive type in the JSON string but got " + data['string']); + } + // ensure the json data is a string + if (data['uuid'] && !(typeof data['uuid'] === 'string' || data['uuid'] instanceof String)) { + throw new Error("Expected the field `uuid` to be a primitive type in the JSON string but got " + data['uuid']); + } + // ensure the json data is a string + if (data['password'] && !(typeof data['password'] === 'string' || data['password'] instanceof String)) { + throw new Error("Expected the field `password` to be a primitive type in the JSON string but got " + data['password']); + } + // ensure the json data is a string + if (data['pattern_with_digits'] && !(typeof data['pattern_with_digits'] === 'string' || data['pattern_with_digits'] instanceof String)) { + throw new Error("Expected the field `pattern_with_digits` to be a primitive type in the JSON string but got " + data['pattern_with_digits']); + } + // ensure the json data is a string + if (data['pattern_with_digits_and_delimiter'] && !(typeof data['pattern_with_digits_and_delimiter'] === 'string' || data['pattern_with_digits_and_delimiter'] instanceof String)) { + throw new Error("Expected the field `pattern_with_digits_and_delimiter` to be a primitive type in the JSON string but got " + data['pattern_with_digits_and_delimiter']); + } + + return true; + } + } +FormatTest.RequiredProperties = ["number", "byte", "date", "password"]; + /** * @member {Number} integer */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/HasOnlyReadOnly.js b/samples/client/petstore/javascript-promise-es6/src/model/HasOnlyReadOnly.js index 57c9173723..90943b87ae 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/HasOnlyReadOnly.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/HasOnlyReadOnly.js @@ -57,9 +57,29 @@ class HasOnlyReadOnly { return obj; } + /** + * Validates the JSON data with respect to HasOnlyReadOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to HasOnlyReadOnly. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['bar'] && !(typeof data['bar'] === 'string' || data['bar'] instanceof String)) { + throw new Error("Expected the field `bar` to be a primitive type in the JSON string but got " + data['bar']); + } + // ensure the json data is a string + if (data['foo'] && !(typeof data['foo'] === 'string' || data['foo'] instanceof String)) { + throw new Error("Expected the field `foo` to be a primitive type in the JSON string but got " + data['foo']); + } + + return true; + } + } + + /** * @member {String} bar */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/HealthCheckResult.js b/samples/client/petstore/javascript-promise-es6/src/model/HealthCheckResult.js index 2dd62c2a26..112fd77842 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/HealthCheckResult.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/HealthCheckResult.js @@ -55,9 +55,25 @@ class HealthCheckResult { return obj; } + /** + * Validates the JSON data with respect to HealthCheckResult. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to HealthCheckResult. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['NullableMessage'] && !(typeof data['NullableMessage'] === 'string' || data['NullableMessage'] instanceof String)) { + throw new Error("Expected the field `NullableMessage` to be a primitive type in the JSON string but got " + data['NullableMessage']); + } + + return true; + } + } + + /** * @member {String} NullableMessage */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject.js b/samples/client/petstore/javascript-promise-es6/src/model/InlineObject.js deleted file mode 100644 index 6815bc809c..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject model module. - * @module model/InlineObject - * @version 1.0.0 - */ -class InlineObject { - /** - * Constructs a new InlineObject. - * @alias module:model/InlineObject - */ - constructor() { - - InlineObject.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a InlineObject from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject} obj Optional instance to populate. - * @return {module:model/InlineObject} The populated InlineObject instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject(); - - if (data.hasOwnProperty('name')) { - obj['name'] = ApiClient.convertToType(data['name'], 'String'); - } - if (data.hasOwnProperty('status')) { - obj['status'] = ApiClient.convertToType(data['status'], 'String'); - } - } - return obj; - } - - -} - -/** - * Updated name of the pet - * @member {String} name - */ -InlineObject.prototype['name'] = undefined; - -/** - * Updated status of the pet - * @member {String} status - */ -InlineObject.prototype['status'] = undefined; - - - - - - -export default InlineObject; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject1.js b/samples/client/petstore/javascript-promise-es6/src/model/InlineObject1.js deleted file mode 100644 index 947877256f..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject1.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject1 model module. - * @module model/InlineObject1 - * @version 1.0.0 - */ -class InlineObject1 { - /** - * Constructs a new InlineObject1. - * @alias module:model/InlineObject1 - */ - constructor() { - - InlineObject1.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a InlineObject1 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject1} obj Optional instance to populate. - * @return {module:model/InlineObject1} The populated InlineObject1 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject1(); - - if (data.hasOwnProperty('additionalMetadata')) { - obj['additionalMetadata'] = ApiClient.convertToType(data['additionalMetadata'], 'String'); - } - if (data.hasOwnProperty('file')) { - obj['file'] = ApiClient.convertToType(data['file'], File); - } - } - return obj; - } - - -} - -/** - * Additional data to pass to server - * @member {String} additionalMetadata - */ -InlineObject1.prototype['additionalMetadata'] = undefined; - -/** - * file to upload - * @member {File} file - */ -InlineObject1.prototype['file'] = undefined; - - - - - - -export default InlineObject1; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject2.js b/samples/client/petstore/javascript-promise-es6/src/model/InlineObject2.js deleted file mode 100644 index e6ed904456..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject2.js +++ /dev/null @@ -1,130 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject2 model module. - * @module model/InlineObject2 - * @version 1.0.0 - */ -class InlineObject2 { - /** - * Constructs a new InlineObject2. - * @alias module:model/InlineObject2 - */ - constructor() { - - InlineObject2.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a InlineObject2 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject2} obj Optional instance to populate. - * @return {module:model/InlineObject2} The populated InlineObject2 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject2(); - - if (data.hasOwnProperty('enum_form_string_array')) { - obj['enum_form_string_array'] = ApiClient.convertToType(data['enum_form_string_array'], ['String']); - } - if (data.hasOwnProperty('enum_form_string')) { - obj['enum_form_string'] = ApiClient.convertToType(data['enum_form_string'], 'String'); - } - } - return obj; - } - - -} - -/** - * Form parameter enum test (string array) - * @member {Array.} enum_form_string_array - */ -InlineObject2.prototype['enum_form_string_array'] = undefined; - -/** - * Form parameter enum test (string) - * @member {module:model/InlineObject2.EnumFormStringEnum} enum_form_string - * @default '-efg' - */ -InlineObject2.prototype['enum_form_string'] = '-efg'; - - - - - -/** - * Allowed values for the enumFormStringArray property. - * @enum {String} - * @readonly - */ -InlineObject2['EnumFormStringArrayEnum'] = { - - /** - * value: ">" - * @const - */ - "GREATER_THAN": ">", - - /** - * value: "$" - * @const - */ - "DOLLAR": "$" -}; - - -/** - * Allowed values for the enum_form_string property. - * @enum {String} - * @readonly - */ -InlineObject2['EnumFormStringEnum'] = { - - /** - * value: "_abc" - * @const - */ - "_abc": "_abc", - - /** - * value: "-efg" - * @const - */ - "-efg": "-efg", - - /** - * value: "(xyz)" - * @const - */ - "(xyz)": "(xyz)" -}; - - - -export default InlineObject2; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject3.js b/samples/client/petstore/javascript-promise-es6/src/model/InlineObject3.js deleted file mode 100644 index 6a14f67109..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject3.js +++ /dev/null @@ -1,197 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject3 model module. - * @module model/InlineObject3 - * @version 1.0.0 - */ -class InlineObject3 { - /** - * Constructs a new InlineObject3. - * @alias module:model/InlineObject3 - * @param _number {Number} None - * @param _double {Number} None - * @param patternWithoutDelimiter {String} None - * @param _byte {Blob} None - */ - constructor(_number, _double, patternWithoutDelimiter, _byte) { - - InlineObject3.initialize(this, _number, _double, patternWithoutDelimiter, _byte); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, _number, _double, patternWithoutDelimiter, _byte) { - obj['number'] = _number; - obj['double'] = _double; - obj['pattern_without_delimiter'] = patternWithoutDelimiter; - obj['byte'] = _byte; - } - - /** - * Constructs a InlineObject3 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject3} obj Optional instance to populate. - * @return {module:model/InlineObject3} The populated InlineObject3 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject3(); - - if (data.hasOwnProperty('integer')) { - obj['integer'] = ApiClient.convertToType(data['integer'], 'Number'); - } - if (data.hasOwnProperty('int32')) { - obj['int32'] = ApiClient.convertToType(data['int32'], 'Number'); - } - if (data.hasOwnProperty('int64')) { - obj['int64'] = ApiClient.convertToType(data['int64'], 'Number'); - } - if (data.hasOwnProperty('number')) { - obj['number'] = ApiClient.convertToType(data['number'], 'Number'); - } - if (data.hasOwnProperty('float')) { - obj['float'] = ApiClient.convertToType(data['float'], 'Number'); - } - if (data.hasOwnProperty('double')) { - obj['double'] = ApiClient.convertToType(data['double'], 'Number'); - } - if (data.hasOwnProperty('string')) { - obj['string'] = ApiClient.convertToType(data['string'], 'String'); - } - if (data.hasOwnProperty('pattern_without_delimiter')) { - obj['pattern_without_delimiter'] = ApiClient.convertToType(data['pattern_without_delimiter'], 'String'); - } - if (data.hasOwnProperty('byte')) { - obj['byte'] = ApiClient.convertToType(data['byte'], 'Blob'); - } - if (data.hasOwnProperty('binary')) { - obj['binary'] = ApiClient.convertToType(data['binary'], File); - } - if (data.hasOwnProperty('date')) { - obj['date'] = ApiClient.convertToType(data['date'], 'Date'); - } - if (data.hasOwnProperty('dateTime')) { - obj['dateTime'] = ApiClient.convertToType(data['dateTime'], 'Date'); - } - if (data.hasOwnProperty('password')) { - obj['password'] = ApiClient.convertToType(data['password'], 'String'); - } - if (data.hasOwnProperty('callback')) { - obj['callback'] = ApiClient.convertToType(data['callback'], 'String'); - } - } - return obj; - } - - -} - -/** - * None - * @member {Number} integer - */ -InlineObject3.prototype['integer'] = undefined; - -/** - * None - * @member {Number} int32 - */ -InlineObject3.prototype['int32'] = undefined; - -/** - * None - * @member {Number} int64 - */ -InlineObject3.prototype['int64'] = undefined; - -/** - * None - * @member {Number} number - */ -InlineObject3.prototype['number'] = undefined; - -/** - * None - * @member {Number} float - */ -InlineObject3.prototype['float'] = undefined; - -/** - * None - * @member {Number} double - */ -InlineObject3.prototype['double'] = undefined; - -/** - * None - * @member {String} string - */ -InlineObject3.prototype['string'] = undefined; - -/** - * None - * @member {String} pattern_without_delimiter - */ -InlineObject3.prototype['pattern_without_delimiter'] = undefined; - -/** - * None - * @member {Blob} byte - */ -InlineObject3.prototype['byte'] = undefined; - -/** - * None - * @member {File} binary - */ -InlineObject3.prototype['binary'] = undefined; - -/** - * None - * @member {Date} date - */ -InlineObject3.prototype['date'] = undefined; - -/** - * None - * @member {Date} dateTime - */ -InlineObject3.prototype['dateTime'] = undefined; - -/** - * None - * @member {String} password - */ -InlineObject3.prototype['password'] = undefined; - -/** - * None - * @member {String} callback - */ -InlineObject3.prototype['callback'] = undefined; - - - - - - -export default InlineObject3; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject4.js b/samples/client/petstore/javascript-promise-es6/src/model/InlineObject4.js deleted file mode 100644 index 9d5d5715c6..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject4.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject4 model module. - * @module model/InlineObject4 - * @version 1.0.0 - */ -class InlineObject4 { - /** - * Constructs a new InlineObject4. - * @alias module:model/InlineObject4 - * @param param {String} field1 - * @param param2 {String} field2 - */ - constructor(param, param2) { - - InlineObject4.initialize(this, param, param2); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, param, param2) { - obj['param'] = param; - obj['param2'] = param2; - } - - /** - * Constructs a InlineObject4 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject4} obj Optional instance to populate. - * @return {module:model/InlineObject4} The populated InlineObject4 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject4(); - - if (data.hasOwnProperty('param')) { - obj['param'] = ApiClient.convertToType(data['param'], 'String'); - } - if (data.hasOwnProperty('param2')) { - obj['param2'] = ApiClient.convertToType(data['param2'], 'String'); - } - } - return obj; - } - - -} - -/** - * field1 - * @member {String} param - */ -InlineObject4.prototype['param'] = undefined; - -/** - * field2 - * @member {String} param2 - */ -InlineObject4.prototype['param2'] = undefined; - - - - - - -export default InlineObject4; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject5.js b/samples/client/petstore/javascript-promise-es6/src/model/InlineObject5.js deleted file mode 100644 index 1969e9b2ef..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/InlineObject5.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The InlineObject5 model module. - * @module model/InlineObject5 - * @version 1.0.0 - */ -class InlineObject5 { - /** - * Constructs a new InlineObject5. - * @alias module:model/InlineObject5 - * @param requiredFile {File} file to upload - */ - constructor(requiredFile) { - - InlineObject5.initialize(this, requiredFile); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, requiredFile) { - obj['requiredFile'] = requiredFile; - } - - /** - * Constructs a InlineObject5 from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineObject5} obj Optional instance to populate. - * @return {module:model/InlineObject5} The populated InlineObject5 instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineObject5(); - - if (data.hasOwnProperty('additionalMetadata')) { - obj['additionalMetadata'] = ApiClient.convertToType(data['additionalMetadata'], 'String'); - } - if (data.hasOwnProperty('requiredFile')) { - obj['requiredFile'] = ApiClient.convertToType(data['requiredFile'], File); - } - } - return obj; - } - - -} - -/** - * Additional data to pass to server - * @member {String} additionalMetadata - */ -InlineObject5.prototype['additionalMetadata'] = undefined; - -/** - * file to upload - * @member {File} requiredFile - */ -InlineObject5.prototype['requiredFile'] = undefined; - - - - - - -export default InlineObject5; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/InlineResponseDefault.js b/samples/client/petstore/javascript-promise-es6/src/model/InlineResponseDefault.js deleted file mode 100644 index 2f66d888ec..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/InlineResponseDefault.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; -import Foo from './Foo'; - -/** - * The InlineResponseDefault model module. - * @module model/InlineResponseDefault - * @version 1.0.0 - */ -class InlineResponseDefault { - /** - * Constructs a new InlineResponseDefault. - * @alias module:model/InlineResponseDefault - */ - constructor() { - - InlineResponseDefault.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a InlineResponseDefault from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/InlineResponseDefault} obj Optional instance to populate. - * @return {module:model/InlineResponseDefault} The populated InlineResponseDefault instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new InlineResponseDefault(); - - if (data.hasOwnProperty('string')) { - obj['string'] = Foo.constructFromObject(data['string']); - } - } - return obj; - } - - -} - -/** - * @member {module:model/Foo} string - */ -InlineResponseDefault.prototype['string'] = undefined; - - - - - - -export default InlineResponseDefault; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/List.js b/samples/client/petstore/javascript-promise-es6/src/model/List.js index 18d6a25849..ca916761c0 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/List.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/List.js @@ -54,9 +54,25 @@ class List { return obj; } + /** + * Validates the JSON data with respect to List. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to List. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['123-list'] && !(typeof data['123-list'] === 'string' || data['123-list'] instanceof String)) { + throw new Error("Expected the field `123-list` to be a primitive type in the JSON string but got " + data['123-list']); + } + + return true; + } + } + + /** * @member {String} 123-list */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/MapTest.js b/samples/client/petstore/javascript-promise-es6/src/model/MapTest.js index 3113ad56bd..478e2347fa 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/MapTest.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/MapTest.js @@ -63,9 +63,21 @@ class MapTest { return obj; } + /** + * Validates the JSON data with respect to MapTest. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to MapTest. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Object.>} map_map_of_string */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/MixedPropertiesAndAdditionalPropertiesClass.js b/samples/client/petstore/javascript-promise-es6/src/model/MixedPropertiesAndAdditionalPropertiesClass.js index 7cd9ca844f..8131fa3620 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/MixedPropertiesAndAdditionalPropertiesClass.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/MixedPropertiesAndAdditionalPropertiesClass.js @@ -61,9 +61,25 @@ class MixedPropertiesAndAdditionalPropertiesClass { return obj; } + /** + * Validates the JSON data with respect to MixedPropertiesAndAdditionalPropertiesClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to MixedPropertiesAndAdditionalPropertiesClass. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['uuid'] && !(typeof data['uuid'] === 'string' || data['uuid'] instanceof String)) { + throw new Error("Expected the field `uuid` to be a primitive type in the JSON string but got " + data['uuid']); + } + + return true; + } + } + + /** * @member {String} uuid */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Model200Response.js b/samples/client/petstore/javascript-promise-es6/src/model/Model200Response.js index 88daaba2eb..604683735f 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Model200Response.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Model200Response.js @@ -58,9 +58,25 @@ class Model200Response { return obj; } + /** + * Validates the JSON data with respect to Model200Response. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Model200Response. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['class'] && !(typeof data['class'] === 'string' || data['class'] instanceof String)) { + throw new Error("Expected the field `class` to be a primitive type in the JSON string but got " + data['class']); + } + + return true; + } + } + + /** * @member {Number} name */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Name.js b/samples/client/petstore/javascript-promise-es6/src/model/Name.js index 740d4bad15..978fbaa7ef 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Name.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Name.js @@ -66,9 +66,31 @@ class Name { return obj; } + /** + * Validates the JSON data with respect to Name. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Name. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Name.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // ensure the json data is a string + if (data['property'] && !(typeof data['property'] === 'string' || data['property'] instanceof String)) { + throw new Error("Expected the field `property` to be a primitive type in the JSON string but got " + data['property']); + } + + return true; + } + } +Name.RequiredProperties = ["name"]; + /** * @member {Number} name */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/NestedColor.js b/samples/client/petstore/javascript-promise-es6/src/model/NestedColor.js new file mode 100644 index 0000000000..5b61146903 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/src/model/NestedColor.js @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Color from './Color'; + +/** + * The NestedColor model module. + * @module model/NestedColor + * @version 1.0.0 + */ +class NestedColor { + /** + * Constructs a new NestedColor. + * @alias module:model/NestedColor + */ + constructor() { + + NestedColor.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a NestedColor from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/NestedColor} obj Optional instance to populate. + * @return {module:model/NestedColor} The populated NestedColor instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new NestedColor(); + + if (data.hasOwnProperty('size')) { + obj['size'] = ApiClient.convertToType(data['size'], 'Number'); + } + if (data.hasOwnProperty('nested')) { + obj['nested'] = Color.constructFromObject(data['nested']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to NestedColor. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NestedColor. + */ + static validateJSON(data) { + // validate the optional field `nested` + if (data['nested']) { // data not null + Color.validateJSON(data['nested']); + } + + return true; + } + + +} + + + +/** + * @member {Number} size + */ +NestedColor.prototype['size'] = undefined; + +/** + * @member {module:model/Color} nested + */ +NestedColor.prototype['nested'] = undefined; + + + + + + +export default NestedColor; + diff --git a/samples/client/petstore/javascript-promise-es6/src/model/NestedOneOf.js b/samples/client/petstore/javascript-promise-es6/src/model/NestedOneOf.js new file mode 100644 index 0000000000..3ea6ed798b --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/src/model/NestedOneOf.js @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import Pig from './Pig'; + +/** + * The NestedOneOf model module. + * @module model/NestedOneOf + * @version 1.0.0 + */ +class NestedOneOf { + /** + * Constructs a new NestedOneOf. + * @alias module:model/NestedOneOf + */ + constructor() { + + NestedOneOf.initialize(this); + } + + /** + * Initializes the fields of this object. + * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). + * Only for internal use. + */ + static initialize(obj) { + } + + /** + * Constructs a NestedOneOf from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/NestedOneOf} obj Optional instance to populate. + * @return {module:model/NestedOneOf} The populated NestedOneOf instance. + */ + static constructFromObject(data, obj) { + if (data) { + obj = obj || new NestedOneOf(); + + if (data.hasOwnProperty('size')) { + obj['size'] = ApiClient.convertToType(data['size'], 'Number'); + } + if (data.hasOwnProperty('nested_pig')) { + obj['nested_pig'] = Pig.constructFromObject(data['nested_pig']); + } + } + return obj; + } + + /** + * Validates the JSON data with respect to NestedOneOf. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NestedOneOf. + */ + static validateJSON(data) { + // validate the optional field `nested_pig` + if (data['nested_pig']) { // data not null + Pig.validateJSON(data['nested_pig']); + } + + return true; + } + + +} + + + +/** + * @member {Number} size + */ +NestedOneOf.prototype['size'] = undefined; + +/** + * @member {module:model/Pig} nested_pig + */ +NestedOneOf.prototype['nested_pig'] = undefined; + + + + + + +export default NestedOneOf; + diff --git a/samples/client/petstore/javascript-promise-es6/src/model/NullableClass.js b/samples/client/petstore/javascript-promise-es6/src/model/NullableClass.js index 12a0f2509b..33dd77a182 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/NullableClass.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/NullableClass.js @@ -91,9 +91,37 @@ class NullableClass { return obj; } + /** + * Validates the JSON data with respect to NullableClass. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NullableClass. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['string_prop'] && !(typeof data['string_prop'] === 'string' || data['string_prop'] instanceof String)) { + throw new Error("Expected the field `string_prop` to be a primitive type in the JSON string but got " + data['string_prop']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_nullable_prop'])) { + throw new Error("Expected the field `array_nullable_prop` to be an array in the JSON data but got " + data['array_nullable_prop']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_and_items_nullable_prop'])) { + throw new Error("Expected the field `array_and_items_nullable_prop` to be an array in the JSON data but got " + data['array_and_items_nullable_prop']); + } + // ensure the json data is an array + if (!Array.isArray(data['array_items_nullable'])) { + throw new Error("Expected the field `array_items_nullable` to be an array in the JSON data but got " + data['array_items_nullable']); + } + + return true; + } + } + + /** * @member {Number} integer_prop */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/NumberOnly.js b/samples/client/petstore/javascript-promise-es6/src/model/NumberOnly.js index 449e08bd9a..deb4f2961f 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/NumberOnly.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/NumberOnly.js @@ -54,9 +54,21 @@ class NumberOnly { return obj; } + /** + * Validates the JSON data with respect to NumberOnly. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to NumberOnly. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Number} JustNumber */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/ObjectWithDeprecatedFields.js b/samples/client/petstore/javascript-promise-es6/src/model/ObjectWithDeprecatedFields.js index a3d0d40094..29e80fd266 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/ObjectWithDeprecatedFields.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/ObjectWithDeprecatedFields.js @@ -64,9 +64,33 @@ class ObjectWithDeprecatedFields { return obj; } + /** + * Validates the JSON data with respect to ObjectWithDeprecatedFields. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ObjectWithDeprecatedFields. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['uuid'] && !(typeof data['uuid'] === 'string' || data['uuid'] instanceof String)) { + throw new Error("Expected the field `uuid` to be a primitive type in the JSON string but got " + data['uuid']); + } + // validate the optional field `deprecatedRef` + if (data['deprecatedRef']) { // data not null + DeprecatedObject.validateJSON(data['deprecatedRef']); + } + // ensure the json data is an array + if (!Array.isArray(data['bars'])) { + throw new Error("Expected the field `bars` to be an array in the JSON data but got " + data['bars']); + } + + return true; + } + } + + /** * @member {String} uuid */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Order.js b/samples/client/petstore/javascript-promise-es6/src/model/Order.js index 1d28748e82..ad586f185d 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Order.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Order.js @@ -69,9 +69,25 @@ class Order { return obj; } + /** + * Validates the JSON data with respect to Order. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Order. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['status'] && !(typeof data['status'] === 'string' || data['status'] instanceof String)) { + throw new Error("Expected the field `status` to be a primitive type in the JSON string but got " + data['status']); + } + + return true; + } + } + + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/OuterComposite.js b/samples/client/petstore/javascript-promise-es6/src/model/OuterComposite.js index cc4ed6c172..1c6a3c9a85 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/OuterComposite.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/OuterComposite.js @@ -60,9 +60,25 @@ class OuterComposite { return obj; } + /** + * Validates the JSON data with respect to OuterComposite. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to OuterComposite. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['my_string'] && !(typeof data['my_string'] === 'string' || data['my_string'] instanceof String)) { + throw new Error("Expected the field `my_string` to be a primitive type in the JSON string but got " + data['my_string']); + } + + return true; + } + } + + /** * @member {Number} my_number */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/OuterObjectWithEnumProperty.js b/samples/client/petstore/javascript-promise-es6/src/model/OuterObjectWithEnumProperty.js index d2ef0e0437..b9ead482af 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/OuterObjectWithEnumProperty.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/OuterObjectWithEnumProperty.js @@ -57,9 +57,27 @@ class OuterObjectWithEnumProperty { return obj; } + /** + * Validates the JSON data with respect to OuterObjectWithEnumProperty. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to OuterObjectWithEnumProperty. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of OuterObjectWithEnumProperty.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + + return true; + } + } +OuterObjectWithEnumProperty.RequiredProperties = ["value"]; + /** * @member {module:model/OuterEnumInteger} value */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Pet.js b/samples/client/petstore/javascript-promise-es6/src/model/Pet.js index b88e5d869f..cc5239c6a1 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Pet.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Pet.js @@ -75,9 +75,53 @@ class Pet { return obj; } + /** + * Validates the JSON data with respect to Pet. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Pet. + */ + static validateJSON(data) { + // check to make sure all required properties are present in the JSON string + for (const property of Pet.RequiredProperties) { + if (!data[property]) { + throw new Error("The required field `" + property + "` is not found in the JSON data: " + JSON.stringify(data)); + } + } + // validate the optional field `category` + if (data['category']) { // data not null + Category.validateJSON(data['category']); + } + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + // ensure the json data is an array + if (!Array.isArray(data['photoUrls'])) { + throw new Error("Expected the field `photoUrls` to be an array in the JSON data but got " + data['photoUrls']); + } + if (data['tags']) { // data not null + // ensure the json data is an array + if (!Array.isArray(data['tags'])) { + throw new Error("Expected the field `tags` to be an array in the JSON data but got " + data['tags']); + } + // validate the optional field `tags` (array) + for (const item of data['tags']) { + Tag.validateJsonObject(item); + }; + } + // ensure the json data is a string + if (data['status'] && !(typeof data['status'] === 'string' || data['status'] instanceof String)) { + throw new Error("Expected the field `status` to be a primitive type in the JSON string but got " + data['status']); + } + + return true; + } + } +Pet.RequiredProperties = ["name", "photoUrls"]; + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Pig.js b/samples/client/petstore/javascript-promise-es6/src/model/Pig.js new file mode 100644 index 0000000000..da6cdc0765 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/src/model/Pig.js @@ -0,0 +1,143 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +import ApiClient from '../ApiClient'; +import BasquePig from './BasquePig'; +import DanishPig from './DanishPig'; + +/** + * The Pig model module. + * @module model/Pig + * @version 1.0.0 + */ +class Pig { + /** + * Constructs a new Pig. + * @alias module:model/Pig + * @param {(module:model/BasquePig|module:model/DanishPig)} instance The actual instance to initialize Pig. + */ + constructor(instance = null) { + if (instance === null) { + this.actualInstance = null; + return; + } + var match = 0; + var errorMessages = []; + try { + if (typeof instance === "BasquePig") { + this.actualInstance = instance; + } else { + // plain JS object + // validate the object + BasquePig.validateJSON(instance); // throw an exception if no match + // create BasquePig from JS object + this.actualInstance = BasquePig.constructFromObject(instance); + } + match++; + } catch(err) { + // json data failed to deserialize into BasquePig + errorMessages.push("Failed to construct BasquePig: " + err) + } + + try { + if (typeof instance === "DanishPig") { + this.actualInstance = instance; + } else { + // plain JS object + // validate the object + DanishPig.validateJSON(instance); // throw an exception if no match + // create DanishPig from JS object + this.actualInstance = DanishPig.constructFromObject(instance); + } + match++; + } catch(err) { + // json data failed to deserialize into DanishPig + errorMessages.push("Failed to construct DanishPig: " + err) + } + + if (match > 1) { + throw new Error("Multiple matches found constructing `Pig` with oneOf schemas BasquePig, DanishPig. Input: " + JSON.stringify(instance)); + } else if (match === 0) { + this.actualInstance = null; // clear the actual instance in case there are multiple matches + throw new Error("No match found constructing `Pig` with oneOf schemas BasquePig, DanishPig. Details: " + + errorMessages.join(", ")); + } else { // only 1 match + // the input is valid + } + } + + /** + * Constructs a Pig from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Pig} obj Optional instance to populate. + * @return {module:model/Pig} The populated Pig instance. + */ + static constructFromObject(data, obj) { + return new Pig(data); + } + + /** + * Gets the actaul instance, which can be BasquePig, DanishPig. + * @return {(module:model/BasquePig|module:model/DanishPig)} The actual instance. + */ + getActualInstance() { + return this.actualInstance; + } + + /** + * Sets the actaul instance, which can be BasquePig, DanishPig. + * @param {(module:model/BasquePig|module:model/DanishPig)} obj The actual instance. + */ + setActualInstance(obj) { + this.actualInstance = Pig.constructFromObject(obj).getActualInstance(); + } + + /** + * Returns the JSON representation of the actual intance. + * @return {string} + */ + toJSON = function(){ + return this.getActualInstance(); + } + + /** + * Create an instance of Pig from a JSON string. + * @param {string} json_string JSON string. + * @return {module:model/Pig} An instance of Pig. + */ + static fromJSON = function(json_string){ + return Pig.constructFromObject(JSON.parse(json_string)); + } +} + +/** + * @member {String} className + */ +Pig.prototype['className'] = undefined; + +/** + * @member {String} color + */ +Pig.prototype['color'] = undefined; + +/** + * @member {Number} size + */ +Pig.prototype['size'] = undefined; + + +Pig.OneOf = ["BasquePig", "DanishPig"]; + +export default Pig; + diff --git a/samples/client/petstore/javascript-promise-es6/src/model/ReadOnlyFirst.js b/samples/client/petstore/javascript-promise-es6/src/model/ReadOnlyFirst.js index 8e2a39cf2a..b0fa7628f1 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/ReadOnlyFirst.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/ReadOnlyFirst.js @@ -57,9 +57,29 @@ class ReadOnlyFirst { return obj; } + /** + * Validates the JSON data with respect to ReadOnlyFirst. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to ReadOnlyFirst. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['bar'] && !(typeof data['bar'] === 'string' || data['bar'] instanceof String)) { + throw new Error("Expected the field `bar` to be a primitive type in the JSON string but got " + data['bar']); + } + // ensure the json data is a string + if (data['baz'] && !(typeof data['baz'] === 'string' || data['baz'] instanceof String)) { + throw new Error("Expected the field `baz` to be a primitive type in the JSON string but got " + data['baz']); + } + + return true; + } + } + + /** * @member {String} bar */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Return.js b/samples/client/petstore/javascript-promise-es6/src/model/Return.js index 304ebb46f0..616574b5fc 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Return.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Return.js @@ -55,9 +55,21 @@ class Return { return obj; } + /** + * Validates the JSON data with respect to Return. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Return. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Number} return */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/SingleRefType.js b/samples/client/petstore/javascript-promise-es6/src/model/SingleRefType.js deleted file mode 100644 index 999a69e288..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/SingleRefType.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; -/** -* Enum class SingleRefType. -* @enum {} -* @readonly -*/ -export default class SingleRefType { - - /** - * value: "admin" - * @const - */ - "admin" = "admin"; - - - /** - * value: "user" - * @const - */ - "user" = "user"; - - - - /** - * Returns a SingleRefType enum value from a Javascript object name. - * @param {Object} data The plain JavaScript object containing the name of the enum value. - * @return {module:model/SingleRefType} The enum SingleRefType value. - */ - static constructFromObject(object) { - return object; - } -} - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/SpecialModelName.js b/samples/client/petstore/javascript-promise-es6/src/model/SpecialModelName.js index 45ba7d7ea0..b9ece72292 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/SpecialModelName.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/SpecialModelName.js @@ -54,9 +54,21 @@ class SpecialModelName { return obj; } + /** + * Validates the JSON data with respect to SpecialModelName. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to SpecialModelName. + */ + static validateJSON(data) { + + return true; + } + } + + /** * @member {Number} $special[property.name] */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/Tag.js b/samples/client/petstore/javascript-promise-es6/src/model/Tag.js index 3330530c0c..c24706b827 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/Tag.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/Tag.js @@ -57,9 +57,25 @@ class Tag { return obj; } + /** + * Validates the JSON data with respect to Tag. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to Tag. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['name'] && !(typeof data['name'] === 'string' || data['name'] instanceof String)) { + throw new Error("Expected the field `name` to be a primitive type in the JSON string but got " + data['name']); + } + + return true; + } + } + + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/TypeHolderDefault.js b/samples/client/petstore/javascript-promise-es6/src/model/TypeHolderDefault.js deleted file mode 100644 index 4ca66c6407..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/TypeHolderDefault.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The TypeHolderDefault model module. - * @module model/TypeHolderDefault - * @version 1.0.0 - */ -class TypeHolderDefault { - /** - * Constructs a new TypeHolderDefault. - * @alias module:model/TypeHolderDefault - * @param stringItem {String} - * @param numberItem {Number} - * @param integerItem {Number} - * @param boolItem {Boolean} - * @param arrayItem {Array.} - */ - constructor(stringItem, numberItem, integerItem, boolItem, arrayItem) { - - TypeHolderDefault.initialize(this, stringItem, numberItem, integerItem, boolItem, arrayItem); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, stringItem, numberItem, integerItem, boolItem, arrayItem) { - obj['string_item'] = stringItem; - obj['number_item'] = numberItem; - obj['integer_item'] = integerItem; - obj['bool_item'] = boolItem; - obj['array_item'] = arrayItem; - } - - /** - * Constructs a TypeHolderDefault from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/TypeHolderDefault} obj Optional instance to populate. - * @return {module:model/TypeHolderDefault} The populated TypeHolderDefault instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new TypeHolderDefault(); - - if (data.hasOwnProperty('string_item')) { - obj['string_item'] = ApiClient.convertToType(data['string_item'], 'String'); - } - if (data.hasOwnProperty('number_item')) { - obj['number_item'] = ApiClient.convertToType(data['number_item'], 'Number'); - } - if (data.hasOwnProperty('integer_item')) { - obj['integer_item'] = ApiClient.convertToType(data['integer_item'], 'Number'); - } - if (data.hasOwnProperty('bool_item')) { - obj['bool_item'] = ApiClient.convertToType(data['bool_item'], 'Boolean'); - } - if (data.hasOwnProperty('array_item')) { - obj['array_item'] = ApiClient.convertToType(data['array_item'], ['Number']); - } - } - return obj; - } - - -} - -/** - * @member {String} string_item - * @default 'what' - */ -TypeHolderDefault.prototype['string_item'] = 'what'; - -/** - * @member {Number} number_item - */ -TypeHolderDefault.prototype['number_item'] = undefined; - -/** - * @member {Number} integer_item - */ -TypeHolderDefault.prototype['integer_item'] = undefined; - -/** - * @member {Boolean} bool_item - * @default true - */ -TypeHolderDefault.prototype['bool_item'] = true; - -/** - * @member {Array.} array_item - */ -TypeHolderDefault.prototype['array_item'] = undefined; - - - - - - -export default TypeHolderDefault; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/TypeHolderExample.js b/samples/client/petstore/javascript-promise-es6/src/model/TypeHolderExample.js deleted file mode 100644 index fa969870f8..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/TypeHolderExample.js +++ /dev/null @@ -1,123 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The TypeHolderExample model module. - * @module model/TypeHolderExample - * @version 1.0.0 - */ -class TypeHolderExample { - /** - * Constructs a new TypeHolderExample. - * @alias module:model/TypeHolderExample - * @param stringItem {String} - * @param numberItem {Number} - * @param floatItem {Number} - * @param integerItem {Number} - * @param boolItem {Boolean} - * @param arrayItem {Array.} - */ - constructor(stringItem, numberItem, floatItem, integerItem, boolItem, arrayItem) { - - TypeHolderExample.initialize(this, stringItem, numberItem, floatItem, integerItem, boolItem, arrayItem); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj, stringItem, numberItem, floatItem, integerItem, boolItem, arrayItem) { - obj['string_item'] = stringItem; - obj['number_item'] = numberItem; - obj['float_item'] = floatItem; - obj['integer_item'] = integerItem; - obj['bool_item'] = boolItem; - obj['array_item'] = arrayItem; - } - - /** - * Constructs a TypeHolderExample from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/TypeHolderExample} obj Optional instance to populate. - * @return {module:model/TypeHolderExample} The populated TypeHolderExample instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new TypeHolderExample(); - - if (data.hasOwnProperty('string_item')) { - obj['string_item'] = ApiClient.convertToType(data['string_item'], 'String'); - } - if (data.hasOwnProperty('number_item')) { - obj['number_item'] = ApiClient.convertToType(data['number_item'], 'Number'); - } - if (data.hasOwnProperty('float_item')) { - obj['float_item'] = ApiClient.convertToType(data['float_item'], 'Number'); - } - if (data.hasOwnProperty('integer_item')) { - obj['integer_item'] = ApiClient.convertToType(data['integer_item'], 'Number'); - } - if (data.hasOwnProperty('bool_item')) { - obj['bool_item'] = ApiClient.convertToType(data['bool_item'], 'Boolean'); - } - if (data.hasOwnProperty('array_item')) { - obj['array_item'] = ApiClient.convertToType(data['array_item'], ['Number']); - } - } - return obj; - } - - -} - -/** - * @member {String} string_item - */ -TypeHolderExample.prototype['string_item'] = undefined; - -/** - * @member {Number} number_item - */ -TypeHolderExample.prototype['number_item'] = undefined; - -/** - * @member {Number} float_item - */ -TypeHolderExample.prototype['float_item'] = undefined; - -/** - * @member {Number} integer_item - */ -TypeHolderExample.prototype['integer_item'] = undefined; - -/** - * @member {Boolean} bool_item - */ -TypeHolderExample.prototype['bool_item'] = undefined; - -/** - * @member {Array.} array_item - */ -TypeHolderExample.prototype['array_item'] = undefined; - - - - - - -export default TypeHolderExample; - diff --git a/samples/client/petstore/javascript-promise-es6/src/model/User.js b/samples/client/petstore/javascript-promise-es6/src/model/User.js index 473bf7c78b..145851f479 100644 --- a/samples/client/petstore/javascript-promise-es6/src/model/User.js +++ b/samples/client/petstore/javascript-promise-es6/src/model/User.js @@ -75,9 +75,45 @@ class User { return obj; } + /** + * Validates the JSON data with respect to User. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @return {boolean} to indicate whether the JSON data is valid with respect to User. + */ + static validateJSON(data) { + // ensure the json data is a string + if (data['username'] && !(typeof data['username'] === 'string' || data['username'] instanceof String)) { + throw new Error("Expected the field `username` to be a primitive type in the JSON string but got " + data['username']); + } + // ensure the json data is a string + if (data['firstName'] && !(typeof data['firstName'] === 'string' || data['firstName'] instanceof String)) { + throw new Error("Expected the field `firstName` to be a primitive type in the JSON string but got " + data['firstName']); + } + // ensure the json data is a string + if (data['lastName'] && !(typeof data['lastName'] === 'string' || data['lastName'] instanceof String)) { + throw new Error("Expected the field `lastName` to be a primitive type in the JSON string but got " + data['lastName']); + } + // ensure the json data is a string + if (data['email'] && !(typeof data['email'] === 'string' || data['email'] instanceof String)) { + throw new Error("Expected the field `email` to be a primitive type in the JSON string but got " + data['email']); + } + // ensure the json data is a string + if (data['password'] && !(typeof data['password'] === 'string' || data['password'] instanceof String)) { + throw new Error("Expected the field `password` to be a primitive type in the JSON string but got " + data['password']); + } + // ensure the json data is a string + if (data['phone'] && !(typeof data['phone'] === 'string' || data['phone'] instanceof String)) { + throw new Error("Expected the field `phone` to be a primitive type in the JSON string but got " + data['phone']); + } + + return true; + } + } + + /** * @member {Number} id */ diff --git a/samples/client/petstore/javascript-promise-es6/src/model/XmlItem.js b/samples/client/petstore/javascript-promise-es6/src/model/XmlItem.js deleted file mode 100644 index 7510c480b2..0000000000 --- a/samples/client/petstore/javascript-promise-es6/src/model/XmlItem.js +++ /dev/null @@ -1,295 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -import ApiClient from '../ApiClient'; - -/** - * The XmlItem model module. - * @module model/XmlItem - * @version 1.0.0 - */ -class XmlItem { - /** - * Constructs a new XmlItem. - * @alias module:model/XmlItem - */ - constructor() { - - XmlItem.initialize(this); - } - - /** - * Initializes the fields of this object. - * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). - * Only for internal use. - */ - static initialize(obj) { - } - - /** - * Constructs a XmlItem from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/XmlItem} obj Optional instance to populate. - * @return {module:model/XmlItem} The populated XmlItem instance. - */ - static constructFromObject(data, obj) { - if (data) { - obj = obj || new XmlItem(); - - if (data.hasOwnProperty('attribute_string')) { - obj['attribute_string'] = ApiClient.convertToType(data['attribute_string'], 'String'); - } - if (data.hasOwnProperty('attribute_number')) { - obj['attribute_number'] = ApiClient.convertToType(data['attribute_number'], 'Number'); - } - if (data.hasOwnProperty('attribute_integer')) { - obj['attribute_integer'] = ApiClient.convertToType(data['attribute_integer'], 'Number'); - } - if (data.hasOwnProperty('attribute_boolean')) { - obj['attribute_boolean'] = ApiClient.convertToType(data['attribute_boolean'], 'Boolean'); - } - if (data.hasOwnProperty('wrapped_array')) { - obj['wrapped_array'] = ApiClient.convertToType(data['wrapped_array'], ['Number']); - } - if (data.hasOwnProperty('name_string')) { - obj['name_string'] = ApiClient.convertToType(data['name_string'], 'String'); - } - if (data.hasOwnProperty('name_number')) { - obj['name_number'] = ApiClient.convertToType(data['name_number'], 'Number'); - } - if (data.hasOwnProperty('name_integer')) { - obj['name_integer'] = ApiClient.convertToType(data['name_integer'], 'Number'); - } - if (data.hasOwnProperty('name_boolean')) { - obj['name_boolean'] = ApiClient.convertToType(data['name_boolean'], 'Boolean'); - } - if (data.hasOwnProperty('name_array')) { - obj['name_array'] = ApiClient.convertToType(data['name_array'], ['Number']); - } - if (data.hasOwnProperty('name_wrapped_array')) { - obj['name_wrapped_array'] = ApiClient.convertToType(data['name_wrapped_array'], ['Number']); - } - if (data.hasOwnProperty('prefix_string')) { - obj['prefix_string'] = ApiClient.convertToType(data['prefix_string'], 'String'); - } - if (data.hasOwnProperty('prefix_number')) { - obj['prefix_number'] = ApiClient.convertToType(data['prefix_number'], 'Number'); - } - if (data.hasOwnProperty('prefix_integer')) { - obj['prefix_integer'] = ApiClient.convertToType(data['prefix_integer'], 'Number'); - } - if (data.hasOwnProperty('prefix_boolean')) { - obj['prefix_boolean'] = ApiClient.convertToType(data['prefix_boolean'], 'Boolean'); - } - if (data.hasOwnProperty('prefix_array')) { - obj['prefix_array'] = ApiClient.convertToType(data['prefix_array'], ['Number']); - } - if (data.hasOwnProperty('prefix_wrapped_array')) { - obj['prefix_wrapped_array'] = ApiClient.convertToType(data['prefix_wrapped_array'], ['Number']); - } - if (data.hasOwnProperty('namespace_string')) { - obj['namespace_string'] = ApiClient.convertToType(data['namespace_string'], 'String'); - } - if (data.hasOwnProperty('namespace_number')) { - obj['namespace_number'] = ApiClient.convertToType(data['namespace_number'], 'Number'); - } - if (data.hasOwnProperty('namespace_integer')) { - obj['namespace_integer'] = ApiClient.convertToType(data['namespace_integer'], 'Number'); - } - if (data.hasOwnProperty('namespace_boolean')) { - obj['namespace_boolean'] = ApiClient.convertToType(data['namespace_boolean'], 'Boolean'); - } - if (data.hasOwnProperty('namespace_array')) { - obj['namespace_array'] = ApiClient.convertToType(data['namespace_array'], ['Number']); - } - if (data.hasOwnProperty('namespace_wrapped_array')) { - obj['namespace_wrapped_array'] = ApiClient.convertToType(data['namespace_wrapped_array'], ['Number']); - } - if (data.hasOwnProperty('prefix_ns_string')) { - obj['prefix_ns_string'] = ApiClient.convertToType(data['prefix_ns_string'], 'String'); - } - if (data.hasOwnProperty('prefix_ns_number')) { - obj['prefix_ns_number'] = ApiClient.convertToType(data['prefix_ns_number'], 'Number'); - } - if (data.hasOwnProperty('prefix_ns_integer')) { - obj['prefix_ns_integer'] = ApiClient.convertToType(data['prefix_ns_integer'], 'Number'); - } - if (data.hasOwnProperty('prefix_ns_boolean')) { - obj['prefix_ns_boolean'] = ApiClient.convertToType(data['prefix_ns_boolean'], 'Boolean'); - } - if (data.hasOwnProperty('prefix_ns_array')) { - obj['prefix_ns_array'] = ApiClient.convertToType(data['prefix_ns_array'], ['Number']); - } - if (data.hasOwnProperty('prefix_ns_wrapped_array')) { - obj['prefix_ns_wrapped_array'] = ApiClient.convertToType(data['prefix_ns_wrapped_array'], ['Number']); - } - } - return obj; - } - - -} - -/** - * @member {String} attribute_string - */ -XmlItem.prototype['attribute_string'] = undefined; - -/** - * @member {Number} attribute_number - */ -XmlItem.prototype['attribute_number'] = undefined; - -/** - * @member {Number} attribute_integer - */ -XmlItem.prototype['attribute_integer'] = undefined; - -/** - * @member {Boolean} attribute_boolean - */ -XmlItem.prototype['attribute_boolean'] = undefined; - -/** - * @member {Array.} wrapped_array - */ -XmlItem.prototype['wrapped_array'] = undefined; - -/** - * @member {String} name_string - */ -XmlItem.prototype['name_string'] = undefined; - -/** - * @member {Number} name_number - */ -XmlItem.prototype['name_number'] = undefined; - -/** - * @member {Number} name_integer - */ -XmlItem.prototype['name_integer'] = undefined; - -/** - * @member {Boolean} name_boolean - */ -XmlItem.prototype['name_boolean'] = undefined; - -/** - * @member {Array.} name_array - */ -XmlItem.prototype['name_array'] = undefined; - -/** - * @member {Array.} name_wrapped_array - */ -XmlItem.prototype['name_wrapped_array'] = undefined; - -/** - * @member {String} prefix_string - */ -XmlItem.prototype['prefix_string'] = undefined; - -/** - * @member {Number} prefix_number - */ -XmlItem.prototype['prefix_number'] = undefined; - -/** - * @member {Number} prefix_integer - */ -XmlItem.prototype['prefix_integer'] = undefined; - -/** - * @member {Boolean} prefix_boolean - */ -XmlItem.prototype['prefix_boolean'] = undefined; - -/** - * @member {Array.} prefix_array - */ -XmlItem.prototype['prefix_array'] = undefined; - -/** - * @member {Array.} prefix_wrapped_array - */ -XmlItem.prototype['prefix_wrapped_array'] = undefined; - -/** - * @member {String} namespace_string - */ -XmlItem.prototype['namespace_string'] = undefined; - -/** - * @member {Number} namespace_number - */ -XmlItem.prototype['namespace_number'] = undefined; - -/** - * @member {Number} namespace_integer - */ -XmlItem.prototype['namespace_integer'] = undefined; - -/** - * @member {Boolean} namespace_boolean - */ -XmlItem.prototype['namespace_boolean'] = undefined; - -/** - * @member {Array.} namespace_array - */ -XmlItem.prototype['namespace_array'] = undefined; - -/** - * @member {Array.} namespace_wrapped_array - */ -XmlItem.prototype['namespace_wrapped_array'] = undefined; - -/** - * @member {String} prefix_ns_string - */ -XmlItem.prototype['prefix_ns_string'] = undefined; - -/** - * @member {Number} prefix_ns_number - */ -XmlItem.prototype['prefix_ns_number'] = undefined; - -/** - * @member {Number} prefix_ns_integer - */ -XmlItem.prototype['prefix_ns_integer'] = undefined; - -/** - * @member {Boolean} prefix_ns_boolean - */ -XmlItem.prototype['prefix_ns_boolean'] = undefined; - -/** - * @member {Array.} prefix_ns_array - */ -XmlItem.prototype['prefix_ns_array'] = undefined; - -/** - * @member {Array.} prefix_ns_wrapped_array - */ -XmlItem.prototype['prefix_ns_wrapped_array'] = undefined; - - - - - - -export default XmlItem; - diff --git a/samples/client/petstore/javascript-promise-es6/test/api/AnotherFakeApi.spec.js b/samples/client/petstore/javascript-promise-es6/test/api/AnotherFakeApi.spec.js index cc0edc79ac..3212de6605 100644 --- a/samples/client/petstore/javascript-promise-es6/test/api/AnotherFakeApi.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/api/AnotherFakeApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/client/petstore/javascript-promise-es6/test/api/FakeApi.spec.js b/samples/client/petstore/javascript-promise-es6/test/api/FakeApi.spec.js index 1f0d2e140f..9ecfa421cb 100644 --- a/samples/client/petstore/javascript-promise-es6/test/api/FakeApi.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/api/FakeApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -48,10 +48,20 @@ } describe('FakeApi', function() { - describe('createXmlItem', function() { - it('should call createXmlItem successfully', function(done) { - //uncomment below and update the code to test createXmlItem - //instance.createXmlItem(function(error) { + describe('fakeHealthGet', function() { + it('should call fakeHealthGet successfully', function(done) { + //uncomment below and update the code to test fakeHealthGet + //instance.fakeHealthGet(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('fakeHttpSignatureTest', function() { + it('should call fakeHttpSignatureTest successfully', function(done) { + //uncomment below and update the code to test fakeHttpSignatureTest + //instance.fakeHttpSignatureTest(function(error) { // if (error) throw error; //expect().to.be(); //}); @@ -98,6 +108,26 @@ done(); }); }); + describe('fakePropertyEnumIntegerSerialize', function() { + it('should call fakePropertyEnumIntegerSerialize successfully', function(done) { + //uncomment below and update the code to test fakePropertyEnumIntegerSerialize + //instance.fakePropertyEnumIntegerSerialize(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); + describe('testBodyWithBinary', function() { + it('should call testBodyWithBinary successfully', function(done) { + //uncomment below and update the code to test testBodyWithBinary + //instance.testBodyWithBinary(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); describe('testBodyWithFileSchema', function() { it('should call testBodyWithFileSchema successfully', function(done) { //uncomment below and update the code to test testBodyWithFileSchema @@ -178,6 +208,16 @@ done(); }); }); + describe('testQueryParameterCollectionFormat', function() { + it('should call testQueryParameterCollectionFormat successfully', function(done) { + //uncomment below and update the code to test testQueryParameterCollectionFormat + //instance.testQueryParameterCollectionFormat(function(error) { + // if (error) throw error; + //expect().to.be(); + //}); + done(); + }); + }); }); })); diff --git a/samples/client/petstore/javascript-promise-es6/test/api/FakeClassnameTags123Api.spec.js b/samples/client/petstore/javascript-promise-es6/test/api/FakeClassnameTags123Api.spec.js index c9b8c836f8..ebe401b08d 100644 --- a/samples/client/petstore/javascript-promise-es6/test/api/FakeClassnameTags123Api.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/api/FakeClassnameTags123Api.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/client/petstore/javascript-promise-es6/test/api/PetApi.spec.js b/samples/client/petstore/javascript-promise-es6/test/api/PetApi.spec.js index 1818900165..16591a407d 100644 --- a/samples/client/petstore/javascript-promise-es6/test/api/PetApi.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/api/PetApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/client/petstore/javascript-promise-es6/test/api/StoreApi.spec.js b/samples/client/petstore/javascript-promise-es6/test/api/StoreApi.spec.js index 86b7758157..2ad9823032 100644 --- a/samples/client/petstore/javascript-promise-es6/test/api/StoreApi.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/api/StoreApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/client/petstore/javascript-promise-es6/test/api/UserApi.spec.js b/samples/client/petstore/javascript-promise-es6/test/api/UserApi.spec.js index 891f2dc475..feab9370b1 100644 --- a/samples/client/petstore/javascript-promise-es6/test/api/UserApi.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/api/UserApi.spec.js @@ -2,7 +2,7 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/client/petstore/javascript-promise-es6/test/model/AdditionalPropertiesClass.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/AdditionalPropertiesClass.spec.js index d316c448dd..4086c3a614 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/AdditionalPropertiesClass.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/AdditionalPropertiesClass.spec.js @@ -50,19 +50,19 @@ describe('AdditionalPropertiesClass', function() { it('should create an instance of AdditionalPropertiesClass', function() { // uncomment below and update the code to test AdditionalPropertiesClass - //var instane = new OpenApiPetstore.AdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.AdditionalPropertiesClass(); //expect(instance).to.be.a(OpenApiPetstore.AdditionalPropertiesClass); }); it('should have the property mapProperty (base name: "map_property")', function() { // uncomment below and update the code to test the property mapProperty - //var instane = new OpenApiPetstore.AdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.AdditionalPropertiesClass(); //expect(instance).to.be(); }); it('should have the property mapOfMapProperty (base name: "map_of_map_property")', function() { // uncomment below and update the code to test the property mapOfMapProperty - //var instane = new OpenApiPetstore.AdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.AdditionalPropertiesClass(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Animal.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Animal.spec.js index cc729e13ba..1fedba274c 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Animal.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Animal.spec.js @@ -50,19 +50,19 @@ describe('Animal', function() { it('should create an instance of Animal', function() { // uncomment below and update the code to test Animal - //var instane = new OpenApiPetstore.Animal(); + //var instance = new OpenApiPetstore.Animal(); //expect(instance).to.be.a(OpenApiPetstore.Animal); }); it('should have the property className (base name: "className")', function() { // uncomment below and update the code to test the property className - //var instane = new OpenApiPetstore.Animal(); + //var instance = new OpenApiPetstore.Animal(); //expect(instance).to.be(); }); it('should have the property color (base name: "color")', function() { // uncomment below and update the code to test the property color - //var instane = new OpenApiPetstore.Animal(); + //var instance = new OpenApiPetstore.Animal(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/ApiResponse.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/ApiResponse.spec.js index e9da1c3974..47716b7a52 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/ApiResponse.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/ApiResponse.spec.js @@ -50,25 +50,25 @@ describe('ApiResponse', function() { it('should create an instance of ApiResponse', function() { // uncomment below and update the code to test ApiResponse - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be.a(OpenApiPetstore.ApiResponse); }); it('should have the property code (base name: "code")', function() { // uncomment below and update the code to test the property code - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be(); }); it('should have the property type (base name: "type")', function() { // uncomment below and update the code to test the property type - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be(); }); it('should have the property message (base name: "message")', function() { // uncomment below and update the code to test the property message - //var instane = new OpenApiPetstore.ApiResponse(); + //var instance = new OpenApiPetstore.ApiResponse(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/ArrayOfArrayOfNumberOnly.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/ArrayOfArrayOfNumberOnly.spec.js index 8c1cdf356f..4bdd2cd2cb 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/ArrayOfArrayOfNumberOnly.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/ArrayOfArrayOfNumberOnly.spec.js @@ -50,13 +50,13 @@ describe('ArrayOfArrayOfNumberOnly', function() { it('should create an instance of ArrayOfArrayOfNumberOnly', function() { // uncomment below and update the code to test ArrayOfArrayOfNumberOnly - //var instane = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); + //var instance = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); //expect(instance).to.be.a(OpenApiPetstore.ArrayOfArrayOfNumberOnly); }); it('should have the property arrayArrayNumber (base name: "ArrayArrayNumber")', function() { // uncomment below and update the code to test the property arrayArrayNumber - //var instane = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); + //var instance = new OpenApiPetstore.ArrayOfArrayOfNumberOnly(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/ArrayOfNumberOnly.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/ArrayOfNumberOnly.spec.js index 70dc490e45..a44c1a7ea1 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/ArrayOfNumberOnly.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/ArrayOfNumberOnly.spec.js @@ -50,13 +50,13 @@ describe('ArrayOfNumberOnly', function() { it('should create an instance of ArrayOfNumberOnly', function() { // uncomment below and update the code to test ArrayOfNumberOnly - //var instane = new OpenApiPetstore.ArrayOfNumberOnly(); + //var instance = new OpenApiPetstore.ArrayOfNumberOnly(); //expect(instance).to.be.a(OpenApiPetstore.ArrayOfNumberOnly); }); it('should have the property arrayNumber (base name: "ArrayNumber")', function() { // uncomment below and update the code to test the property arrayNumber - //var instane = new OpenApiPetstore.ArrayOfNumberOnly(); + //var instance = new OpenApiPetstore.ArrayOfNumberOnly(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/ArrayTest.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/ArrayTest.spec.js index 3df2ea0d57..a6bbf95e21 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/ArrayTest.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/ArrayTest.spec.js @@ -50,25 +50,25 @@ describe('ArrayTest', function() { it('should create an instance of ArrayTest', function() { // uncomment below and update the code to test ArrayTest - //var instane = new OpenApiPetstore.ArrayTest(); + //var instance = new OpenApiPetstore.ArrayTest(); //expect(instance).to.be.a(OpenApiPetstore.ArrayTest); }); it('should have the property arrayOfString (base name: "array_of_string")', function() { // uncomment below and update the code to test the property arrayOfString - //var instane = new OpenApiPetstore.ArrayTest(); + //var instance = new OpenApiPetstore.ArrayTest(); //expect(instance).to.be(); }); it('should have the property arrayArrayOfInteger (base name: "array_array_of_integer")', function() { // uncomment below and update the code to test the property arrayArrayOfInteger - //var instane = new OpenApiPetstore.ArrayTest(); + //var instance = new OpenApiPetstore.ArrayTest(); //expect(instance).to.be(); }); it('should have the property arrayArrayOfModel (base name: "array_array_of_model")', function() { // uncomment below and update the code to test the property arrayArrayOfModel - //var instane = new OpenApiPetstore.ArrayTest(); + //var instance = new OpenApiPetstore.ArrayTest(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/BasquePig.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/BasquePig.spec.js new file mode 100644 index 0000000000..da5196fc09 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/test/model/BasquePig.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.BasquePig(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('BasquePig', function() { + it('should create an instance of BasquePig', function() { + // uncomment below and update the code to test BasquePig + //var instance = new OpenApiPetstore.BasquePig(); + //expect(instance).to.be.a(OpenApiPetstore.BasquePig); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.BasquePig(); + //expect(instance).to.be(); + }); + + it('should have the property color (base name: "color")', function() { + // uncomment below and update the code to test the property color + //var instance = new OpenApiPetstore.BasquePig(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Capitalization.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Capitalization.spec.js index dcb9d6d182..8f14fd583d 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Capitalization.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Capitalization.spec.js @@ -50,43 +50,43 @@ describe('Capitalization', function() { it('should create an instance of Capitalization', function() { // uncomment below and update the code to test Capitalization - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be.a(OpenApiPetstore.Capitalization); }); it('should have the property smallCamel (base name: "smallCamel")', function() { // uncomment below and update the code to test the property smallCamel - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property capitalCamel (base name: "CapitalCamel")', function() { // uncomment below and update the code to test the property capitalCamel - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property smallSnake (base name: "small_Snake")', function() { // uncomment below and update the code to test the property smallSnake - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property capitalSnake (base name: "Capital_Snake")', function() { // uncomment below and update the code to test the property capitalSnake - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property sCAETHFlowPoints (base name: "SCA_ETH_Flow_Points")', function() { // uncomment below and update the code to test the property sCAETHFlowPoints - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); it('should have the property ATT_NAME (base name: "ATT_NAME")', function() { // uncomment below and update the code to test the property ATT_NAME - //var instane = new OpenApiPetstore.Capitalization(); + //var instance = new OpenApiPetstore.Capitalization(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Cat.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Cat.spec.js index 1b7182a130..a0c3551cbc 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Cat.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Cat.spec.js @@ -50,13 +50,13 @@ describe('Cat', function() { it('should create an instance of Cat', function() { // uncomment below and update the code to test Cat - //var instane = new OpenApiPetstore.Cat(); + //var instance = new OpenApiPetstore.Cat(); //expect(instance).to.be.a(OpenApiPetstore.Cat); }); it('should have the property declawed (base name: "declawed")', function() { // uncomment below and update the code to test the property declawed - //var instane = new OpenApiPetstore.Cat(); + //var instance = new OpenApiPetstore.Cat(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/CatAllOf.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/CatAllOf.spec.js index be4cf8b972..7e9f50eadd 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/CatAllOf.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/CatAllOf.spec.js @@ -50,13 +50,13 @@ describe('CatAllOf', function() { it('should create an instance of CatAllOf', function() { // uncomment below and update the code to test CatAllOf - //var instane = new OpenApiPetstore.CatAllOf(); + //var instance = new OpenApiPetstore.CatAllOf(); //expect(instance).to.be.a(OpenApiPetstore.CatAllOf); }); it('should have the property declawed (base name: "declawed")', function() { // uncomment below and update the code to test the property declawed - //var instane = new OpenApiPetstore.CatAllOf(); + //var instance = new OpenApiPetstore.CatAllOf(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Category.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Category.spec.js index e0a992aa51..c0e132b026 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Category.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Category.spec.js @@ -50,19 +50,19 @@ describe('Category', function() { it('should create an instance of Category', function() { // uncomment below and update the code to test Category - //var instane = new OpenApiPetstore.Category(); + //var instance = new OpenApiPetstore.Category(); //expect(instance).to.be.a(OpenApiPetstore.Category); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Category(); + //var instance = new OpenApiPetstore.Category(); //expect(instance).to.be(); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Category(); + //var instance = new OpenApiPetstore.Category(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/ClassModel.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/ClassModel.spec.js index 0f2d200d0b..975308a1ce 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/ClassModel.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/ClassModel.spec.js @@ -50,13 +50,13 @@ describe('ClassModel', function() { it('should create an instance of ClassModel', function() { // uncomment below and update the code to test ClassModel - //var instane = new OpenApiPetstore.ClassModel(); + //var instance = new OpenApiPetstore.ClassModel(); //expect(instance).to.be.a(OpenApiPetstore.ClassModel); }); it('should have the property _class (base name: "_class")', function() { // uncomment below and update the code to test the property _class - //var instane = new OpenApiPetstore.ClassModel(); + //var instance = new OpenApiPetstore.ClassModel(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Client.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Client.spec.js index 49a4400987..c96ccac7e3 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Client.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Client.spec.js @@ -50,13 +50,13 @@ describe('Client', function() { it('should create an instance of Client', function() { // uncomment below and update the code to test Client - //var instane = new OpenApiPetstore.Client(); + //var instance = new OpenApiPetstore.Client(); //expect(instance).to.be.a(OpenApiPetstore.Client); }); it('should have the property client (base name: "client")', function() { // uncomment below and update the code to test the property client - //var instane = new OpenApiPetstore.Client(); + //var instance = new OpenApiPetstore.Client(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Color.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Color.spec.js new file mode 100644 index 0000000000..c079e6e511 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/test/model/Color.spec.js @@ -0,0 +1,59 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Color(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Color', function() { + it('should create an instance of Color', function() { + // uncomment below and update the code to test Color + //var instance = new OpenApiPetstore.Color(); + //expect(instance).to.be.a(OpenApiPetstore.Color); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/DanishPig.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/DanishPig.spec.js new file mode 100644 index 0000000000..f227291846 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/test/model/DanishPig.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.DanishPig(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('DanishPig', function() { + it('should create an instance of DanishPig', function() { + // uncomment below and update the code to test DanishPig + //var instance = new OpenApiPetstore.DanishPig(); + //expect(instance).to.be.a(OpenApiPetstore.DanishPig); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.DanishPig(); + //expect(instance).to.be(); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.DanishPig(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/DeprecatedObject.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/DeprecatedObject.spec.js index 2273f70a0f..072245e26f 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/DeprecatedObject.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/DeprecatedObject.spec.js @@ -50,7 +50,7 @@ describe('DeprecatedObject', function() { it('should create an instance of DeprecatedObject', function() { // uncomment below and update the code to test DeprecatedObject - //var instane = new OpenApiPetstore.DeprecatedObject(); + //var instance = new OpenApiPetstore.DeprecatedObject(); //expect(instance).to.be.a(OpenApiPetstore.DeprecatedObject); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Dog.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Dog.spec.js index eb919428d2..709cbfa9fd 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Dog.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Dog.spec.js @@ -50,13 +50,13 @@ describe('Dog', function() { it('should create an instance of Dog', function() { // uncomment below and update the code to test Dog - //var instane = new OpenApiPetstore.Dog(); + //var instance = new OpenApiPetstore.Dog(); //expect(instance).to.be.a(OpenApiPetstore.Dog); }); it('should have the property breed (base name: "breed")', function() { // uncomment below and update the code to test the property breed - //var instane = new OpenApiPetstore.Dog(); + //var instance = new OpenApiPetstore.Dog(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/DogAllOf.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/DogAllOf.spec.js index 767e3b0071..0bb726203a 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/DogAllOf.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/DogAllOf.spec.js @@ -50,13 +50,13 @@ describe('DogAllOf', function() { it('should create an instance of DogAllOf', function() { // uncomment below and update the code to test DogAllOf - //var instane = new OpenApiPetstore.DogAllOf(); + //var instance = new OpenApiPetstore.DogAllOf(); //expect(instance).to.be.a(OpenApiPetstore.DogAllOf); }); it('should have the property breed (base name: "breed")', function() { // uncomment below and update the code to test the property breed - //var instane = new OpenApiPetstore.DogAllOf(); + //var instance = new OpenApiPetstore.DogAllOf(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/EnumArrays.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/EnumArrays.spec.js index d176bddbaf..bda0e3bcf4 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/EnumArrays.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/EnumArrays.spec.js @@ -50,19 +50,19 @@ describe('EnumArrays', function() { it('should create an instance of EnumArrays', function() { // uncomment below and update the code to test EnumArrays - //var instane = new OpenApiPetstore.EnumArrays(); + //var instance = new OpenApiPetstore.EnumArrays(); //expect(instance).to.be.a(OpenApiPetstore.EnumArrays); }); it('should have the property justSymbol (base name: "just_symbol")', function() { // uncomment below and update the code to test the property justSymbol - //var instane = new OpenApiPetstore.EnumArrays(); + //var instance = new OpenApiPetstore.EnumArrays(); //expect(instance).to.be(); }); it('should have the property arrayEnum (base name: "array_enum")', function() { // uncomment below and update the code to test the property arrayEnum - //var instane = new OpenApiPetstore.EnumArrays(); + //var instance = new OpenApiPetstore.EnumArrays(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/EnumClass.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/EnumClass.spec.js index 92ceee37ad..31924e83d5 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/EnumClass.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/EnumClass.spec.js @@ -49,7 +49,7 @@ describe('EnumClass', function() { it('should create an instance of EnumClass', function() { // uncomment below and update the code to test EnumClass - //var instane = new OpenApiPetstore.EnumClass(); + //var instance = new OpenApiPetstore.EnumClass(); //expect(instance).to.be.a(OpenApiPetstore.EnumClass); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/EnumTest.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/EnumTest.spec.js index fdfd70a772..ee14bc9b9d 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/EnumTest.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/EnumTest.spec.js @@ -50,55 +50,55 @@ describe('EnumTest', function() { it('should create an instance of EnumTest', function() { // uncomment below and update the code to test EnumTest - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be.a(OpenApiPetstore.EnumTest); }); it('should have the property enumString (base name: "enum_string")', function() { // uncomment below and update the code to test the property enumString - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property enumStringRequired (base name: "enum_string_required")', function() { // uncomment below and update the code to test the property enumStringRequired - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property enumInteger (base name: "enum_integer")', function() { // uncomment below and update the code to test the property enumInteger - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property enumNumber (base name: "enum_number")', function() { // uncomment below and update the code to test the property enumNumber - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property outerEnum (base name: "outerEnum")', function() { // uncomment below and update the code to test the property outerEnum - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property outerEnumInteger (base name: "outerEnumInteger")', function() { // uncomment below and update the code to test the property outerEnumInteger - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property outerEnumDefaultValue (base name: "outerEnumDefaultValue")', function() { // uncomment below and update the code to test the property outerEnumDefaultValue - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); it('should have the property outerEnumIntegerDefaultValue (base name: "outerEnumIntegerDefaultValue")', function() { // uncomment below and update the code to test the property outerEnumIntegerDefaultValue - //var instane = new OpenApiPetstore.EnumTest(); + //var instance = new OpenApiPetstore.EnumTest(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/File.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/File.spec.js index 4be82b5b48..ac6fbb3de7 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/File.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/File.spec.js @@ -50,13 +50,13 @@ describe('File', function() { it('should create an instance of File', function() { // uncomment below and update the code to test File - //var instane = new OpenApiPetstore.File(); + //var instance = new OpenApiPetstore.File(); //expect(instance).to.be.a(OpenApiPetstore.File); }); it('should have the property sourceURI (base name: "sourceURI")', function() { // uncomment below and update the code to test the property sourceURI - //var instane = new OpenApiPetstore.File(); + //var instance = new OpenApiPetstore.File(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/FileSchemaTestClass.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/FileSchemaTestClass.spec.js index 31c80909bf..2f00908972 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/FileSchemaTestClass.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/FileSchemaTestClass.spec.js @@ -50,19 +50,19 @@ describe('FileSchemaTestClass', function() { it('should create an instance of FileSchemaTestClass', function() { // uncomment below and update the code to test FileSchemaTestClass - //var instane = new OpenApiPetstore.FileSchemaTestClass(); + //var instance = new OpenApiPetstore.FileSchemaTestClass(); //expect(instance).to.be.a(OpenApiPetstore.FileSchemaTestClass); }); it('should have the property file (base name: "file")', function() { // uncomment below and update the code to test the property file - //var instane = new OpenApiPetstore.FileSchemaTestClass(); + //var instance = new OpenApiPetstore.FileSchemaTestClass(); //expect(instance).to.be(); }); it('should have the property files (base name: "files")', function() { // uncomment below and update the code to test the property files - //var instane = new OpenApiPetstore.FileSchemaTestClass(); + //var instance = new OpenApiPetstore.FileSchemaTestClass(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Foo.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Foo.spec.js index 7460803792..81491fc42c 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Foo.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Foo.spec.js @@ -50,13 +50,13 @@ describe('Foo', function() { it('should create an instance of Foo', function() { // uncomment below and update the code to test Foo - //var instane = new OpenApiPetstore.Foo(); + //var instance = new OpenApiPetstore.Foo(); //expect(instance).to.be.a(OpenApiPetstore.Foo); }); it('should have the property bar (base name: "bar")', function() { // uncomment below and update the code to test the property bar - //var instane = new OpenApiPetstore.Foo(); + //var instance = new OpenApiPetstore.Foo(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/FormatTest.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/FormatTest.spec.js index cdff66632d..6506a39d85 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/FormatTest.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/FormatTest.spec.js @@ -50,97 +50,103 @@ describe('FormatTest', function() { it('should create an instance of FormatTest', function() { // uncomment below and update the code to test FormatTest - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be.a(OpenApiPetstore.FormatTest); }); it('should have the property integer (base name: "integer")', function() { // uncomment below and update the code to test the property integer - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property int32 (base name: "int32")', function() { // uncomment below and update the code to test the property int32 - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property int64 (base name: "int64")', function() { // uncomment below and update the code to test the property int64 - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); - it('should have the property _number (base name: "number")', function() { - // uncomment below and update the code to test the property _number - //var instane = new OpenApiPetstore.FormatTest(); + it('should have the property number (base name: "number")', function() { + // uncomment below and update the code to test the property number + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property _float (base name: "float")', function() { // uncomment below and update the code to test the property _float - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property _double (base name: "double")', function() { // uncomment below and update the code to test the property _double - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); - it('should have the property _string (base name: "string")', function() { - // uncomment below and update the code to test the property _string - //var instane = new OpenApiPetstore.FormatTest(); + it('should have the property decimal (base name: "decimal")', function() { + // uncomment below and update the code to test the property decimal + //var instance = new OpenApiPetstore.FormatTest(); + //expect(instance).to.be(); + }); + + it('should have the property string (base name: "string")', function() { + // uncomment below and update the code to test the property string + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property _byte (base name: "byte")', function() { // uncomment below and update the code to test the property _byte - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property binary (base name: "binary")', function() { // uncomment below and update the code to test the property binary - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); - it('should have the property _date (base name: "date")', function() { - // uncomment below and update the code to test the property _date - //var instane = new OpenApiPetstore.FormatTest(); + it('should have the property date (base name: "date")', function() { + // uncomment below and update the code to test the property date + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property dateTime (base name: "dateTime")', function() { // uncomment below and update the code to test the property dateTime - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property uuid (base name: "uuid")', function() { // uncomment below and update the code to test the property uuid - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property password (base name: "password")', function() { // uncomment below and update the code to test the property password - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property patternWithDigits (base name: "pattern_with_digits")', function() { // uncomment below and update the code to test the property patternWithDigits - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); it('should have the property patternWithDigitsAndDelimiter (base name: "pattern_with_digits_and_delimiter")', function() { // uncomment below and update the code to test the property patternWithDigitsAndDelimiter - //var instane = new OpenApiPetstore.FormatTest(); + //var instance = new OpenApiPetstore.FormatTest(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/HasOnlyReadOnly.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/HasOnlyReadOnly.spec.js index 05235ef7b5..e9ba0be44f 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/HasOnlyReadOnly.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/HasOnlyReadOnly.spec.js @@ -50,19 +50,19 @@ describe('HasOnlyReadOnly', function() { it('should create an instance of HasOnlyReadOnly', function() { // uncomment below and update the code to test HasOnlyReadOnly - //var instane = new OpenApiPetstore.HasOnlyReadOnly(); + //var instance = new OpenApiPetstore.HasOnlyReadOnly(); //expect(instance).to.be.a(OpenApiPetstore.HasOnlyReadOnly); }); it('should have the property bar (base name: "bar")', function() { // uncomment below and update the code to test the property bar - //var instane = new OpenApiPetstore.HasOnlyReadOnly(); + //var instance = new OpenApiPetstore.HasOnlyReadOnly(); //expect(instance).to.be(); }); it('should have the property foo (base name: "foo")', function() { // uncomment below and update the code to test the property foo - //var instane = new OpenApiPetstore.HasOnlyReadOnly(); + //var instance = new OpenApiPetstore.HasOnlyReadOnly(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/HealthCheckResult.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/HealthCheckResult.spec.js index 7399370b14..25d9ecd929 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/HealthCheckResult.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/HealthCheckResult.spec.js @@ -50,13 +50,13 @@ describe('HealthCheckResult', function() { it('should create an instance of HealthCheckResult', function() { // uncomment below and update the code to test HealthCheckResult - //var instane = new OpenApiPetstore.HealthCheckResult(); + //var instance = new OpenApiPetstore.HealthCheckResult(); //expect(instance).to.be.a(OpenApiPetstore.HealthCheckResult); }); it('should have the property nullableMessage (base name: "NullableMessage")', function() { // uncomment below and update the code to test the property nullableMessage - //var instane = new OpenApiPetstore.HealthCheckResult(); + //var instance = new OpenApiPetstore.HealthCheckResult(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/List.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/List.spec.js index 7609a9420d..675aa82c18 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/List.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/List.spec.js @@ -50,13 +50,13 @@ describe('List', function() { it('should create an instance of List', function() { // uncomment below and update the code to test List - //var instane = new OpenApiPetstore.List(); + //var instance = new OpenApiPetstore.List(); //expect(instance).to.be.a(OpenApiPetstore.List); }); it('should have the property _123list (base name: "123-list")', function() { // uncomment below and update the code to test the property _123list - //var instane = new OpenApiPetstore.List(); + //var instance = new OpenApiPetstore.List(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/MapTest.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/MapTest.spec.js index 9b1016b7cc..4e7dabcc21 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/MapTest.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/MapTest.spec.js @@ -50,31 +50,31 @@ describe('MapTest', function() { it('should create an instance of MapTest', function() { // uncomment below and update the code to test MapTest - //var instane = new OpenApiPetstore.MapTest(); + //var instance = new OpenApiPetstore.MapTest(); //expect(instance).to.be.a(OpenApiPetstore.MapTest); }); it('should have the property mapMapOfString (base name: "map_map_of_string")', function() { // uncomment below and update the code to test the property mapMapOfString - //var instane = new OpenApiPetstore.MapTest(); + //var instance = new OpenApiPetstore.MapTest(); //expect(instance).to.be(); }); it('should have the property mapOfEnumString (base name: "map_of_enum_string")', function() { // uncomment below and update the code to test the property mapOfEnumString - //var instane = new OpenApiPetstore.MapTest(); + //var instance = new OpenApiPetstore.MapTest(); //expect(instance).to.be(); }); it('should have the property directMap (base name: "direct_map")', function() { // uncomment below and update the code to test the property directMap - //var instane = new OpenApiPetstore.MapTest(); + //var instance = new OpenApiPetstore.MapTest(); //expect(instance).to.be(); }); it('should have the property indirectMap (base name: "indirect_map")', function() { // uncomment below and update the code to test the property indirectMap - //var instane = new OpenApiPetstore.MapTest(); + //var instance = new OpenApiPetstore.MapTest(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js index 60243bf389..2e72316a90 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/MixedPropertiesAndAdditionalPropertiesClass.spec.js @@ -50,25 +50,25 @@ describe('MixedPropertiesAndAdditionalPropertiesClass', function() { it('should create an instance of MixedPropertiesAndAdditionalPropertiesClass', function() { // uncomment below and update the code to test MixedPropertiesAndAdditionalPropertiesClass - //var instane = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); //expect(instance).to.be.a(OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass); }); it('should have the property uuid (base name: "uuid")', function() { // uncomment below and update the code to test the property uuid - //var instane = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); //expect(instance).to.be(); }); it('should have the property dateTime (base name: "dateTime")', function() { // uncomment below and update the code to test the property dateTime - //var instane = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); //expect(instance).to.be(); }); it('should have the property map (base name: "map")', function() { // uncomment below and update the code to test the property map - //var instane = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); + //var instance = new OpenApiPetstore.MixedPropertiesAndAdditionalPropertiesClass(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Model200Response.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Model200Response.spec.js index f966a55a5b..7cd4da5e51 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Model200Response.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Model200Response.spec.js @@ -50,19 +50,19 @@ describe('Model200Response', function() { it('should create an instance of Model200Response', function() { // uncomment below and update the code to test Model200Response - //var instane = new OpenApiPetstore.Model200Response(); + //var instance = new OpenApiPetstore.Model200Response(); //expect(instance).to.be.a(OpenApiPetstore.Model200Response); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Model200Response(); + //var instance = new OpenApiPetstore.Model200Response(); //expect(instance).to.be(); }); it('should have the property _class (base name: "class")', function() { // uncomment below and update the code to test the property _class - //var instane = new OpenApiPetstore.Model200Response(); + //var instance = new OpenApiPetstore.Model200Response(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Name.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Name.spec.js index feed4e8f29..a88057711f 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Name.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Name.spec.js @@ -50,31 +50,31 @@ describe('Name', function() { it('should create an instance of Name', function() { // uncomment below and update the code to test Name - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be.a(OpenApiPetstore.Name); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be(); }); it('should have the property snakeCase (base name: "snake_case")', function() { // uncomment below and update the code to test the property snakeCase - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be(); }); it('should have the property property (base name: "property")', function() { // uncomment below and update the code to test the property property - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be(); }); it('should have the property _123number (base name: "123Number")', function() { // uncomment below and update the code to test the property _123number - //var instane = new OpenApiPetstore.Name(); + //var instance = new OpenApiPetstore.Name(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/NestedColor.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/NestedColor.spec.js new file mode 100644 index 0000000000..00a5813236 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/test/model/NestedColor.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.NestedColor(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('NestedColor', function() { + it('should create an instance of NestedColor', function() { + // uncomment below and update the code to test NestedColor + //var instance = new OpenApiPetstore.NestedColor(); + //expect(instance).to.be.a(OpenApiPetstore.NestedColor); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.NestedColor(); + //expect(instance).to.be(); + }); + + it('should have the property nested (base name: "nested")', function() { + // uncomment below and update the code to test the property nested + //var instance = new OpenApiPetstore.NestedColor(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/NestedOneOf.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/NestedOneOf.spec.js new file mode 100644 index 0000000000..5a54e7fbb0 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/test/model/NestedOneOf.spec.js @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.NestedOneOf(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('NestedOneOf', function() { + it('should create an instance of NestedOneOf', function() { + // uncomment below and update the code to test NestedOneOf + //var instance = new OpenApiPetstore.NestedOneOf(); + //expect(instance).to.be.a(OpenApiPetstore.NestedOneOf); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.NestedOneOf(); + //expect(instance).to.be(); + }); + + it('should have the property nestedPig (base name: "nested_pig")', function() { + // uncomment below and update the code to test the property nestedPig + //var instance = new OpenApiPetstore.NestedOneOf(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/NullableClass.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/NullableClass.spec.js index 89cd2821d4..602a172777 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/NullableClass.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/NullableClass.spec.js @@ -50,79 +50,79 @@ describe('NullableClass', function() { it('should create an instance of NullableClass', function() { // uncomment below and update the code to test NullableClass - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be.a(OpenApiPetstore.NullableClass); }); it('should have the property integerProp (base name: "integer_prop")', function() { // uncomment below and update the code to test the property integerProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property numberProp (base name: "number_prop")', function() { // uncomment below and update the code to test the property numberProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property booleanProp (base name: "boolean_prop")', function() { // uncomment below and update the code to test the property booleanProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property stringProp (base name: "string_prop")', function() { // uncomment below and update the code to test the property stringProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property dateProp (base name: "date_prop")', function() { // uncomment below and update the code to test the property dateProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property datetimeProp (base name: "datetime_prop")', function() { // uncomment below and update the code to test the property datetimeProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property arrayNullableProp (base name: "array_nullable_prop")', function() { // uncomment below and update the code to test the property arrayNullableProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property arrayAndItemsNullableProp (base name: "array_and_items_nullable_prop")', function() { // uncomment below and update the code to test the property arrayAndItemsNullableProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property arrayItemsNullable (base name: "array_items_nullable")', function() { // uncomment below and update the code to test the property arrayItemsNullable - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property objectNullableProp (base name: "object_nullable_prop")', function() { // uncomment below and update the code to test the property objectNullableProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property objectAndItemsNullableProp (base name: "object_and_items_nullable_prop")', function() { // uncomment below and update the code to test the property objectAndItemsNullableProp - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); it('should have the property objectItemsNullable (base name: "object_items_nullable")', function() { // uncomment below and update the code to test the property objectItemsNullable - //var instane = new OpenApiPetstore.NullableClass(); + //var instance = new OpenApiPetstore.NullableClass(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/NumberOnly.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/NumberOnly.spec.js index cbbd3d6124..a39e26134e 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/NumberOnly.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/NumberOnly.spec.js @@ -50,13 +50,13 @@ describe('NumberOnly', function() { it('should create an instance of NumberOnly', function() { // uncomment below and update the code to test NumberOnly - //var instane = new OpenApiPetstore.NumberOnly(); + //var instance = new OpenApiPetstore.NumberOnly(); //expect(instance).to.be.a(OpenApiPetstore.NumberOnly); }); it('should have the property justNumber (base name: "JustNumber")', function() { // uncomment below and update the code to test the property justNumber - //var instane = new OpenApiPetstore.NumberOnly(); + //var instance = new OpenApiPetstore.NumberOnly(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/ObjectWithDeprecatedFields.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/ObjectWithDeprecatedFields.spec.js index 11a78dce68..b190adcca3 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/ObjectWithDeprecatedFields.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/ObjectWithDeprecatedFields.spec.js @@ -50,7 +50,7 @@ describe('ObjectWithDeprecatedFields', function() { it('should create an instance of ObjectWithDeprecatedFields', function() { // uncomment below and update the code to test ObjectWithDeprecatedFields - //var instane = new OpenApiPetstore.ObjectWithDeprecatedFields(); + //var instance = new OpenApiPetstore.ObjectWithDeprecatedFields(); //expect(instance).to.be.a(OpenApiPetstore.ObjectWithDeprecatedFields); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Order.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Order.spec.js index b3e2b5a471..88564e2bc6 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Order.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Order.spec.js @@ -50,43 +50,43 @@ describe('Order', function() { it('should create an instance of Order', function() { // uncomment below and update the code to test Order - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be.a(OpenApiPetstore.Order); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property petId (base name: "petId")', function() { // uncomment below and update the code to test the property petId - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property quantity (base name: "quantity")', function() { // uncomment below and update the code to test the property quantity - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property shipDate (base name: "shipDate")', function() { // uncomment below and update the code to test the property shipDate - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property status (base name: "status")', function() { // uncomment below and update the code to test the property status - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); it('should have the property complete (base name: "complete")', function() { // uncomment below and update the code to test the property complete - //var instane = new OpenApiPetstore.Order(); + //var instance = new OpenApiPetstore.Order(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/OuterComposite.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/OuterComposite.spec.js index 7f772d8c37..1ef9599b2d 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/OuterComposite.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/OuterComposite.spec.js @@ -50,25 +50,25 @@ describe('OuterComposite', function() { it('should create an instance of OuterComposite', function() { // uncomment below and update the code to test OuterComposite - //var instane = new OpenApiPetstore.OuterComposite(); + //var instance = new OpenApiPetstore.OuterComposite(); //expect(instance).to.be.a(OpenApiPetstore.OuterComposite); }); it('should have the property myNumber (base name: "my_number")', function() { // uncomment below and update the code to test the property myNumber - //var instane = new OpenApiPetstore.OuterComposite(); + //var instance = new OpenApiPetstore.OuterComposite(); //expect(instance).to.be(); }); it('should have the property myString (base name: "my_string")', function() { // uncomment below and update the code to test the property myString - //var instane = new OpenApiPetstore.OuterComposite(); + //var instance = new OpenApiPetstore.OuterComposite(); //expect(instance).to.be(); }); it('should have the property myBoolean (base name: "my_boolean")', function() { // uncomment below and update the code to test the property myBoolean - //var instane = new OpenApiPetstore.OuterComposite(); + //var instance = new OpenApiPetstore.OuterComposite(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/OuterEnum.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/OuterEnum.spec.js index f5ec4089cc..16e8d61479 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/OuterEnum.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/OuterEnum.spec.js @@ -49,7 +49,7 @@ describe('OuterEnum', function() { it('should create an instance of OuterEnum', function() { // uncomment below and update the code to test OuterEnum - //var instane = new OpenApiPetstore.OuterEnum(); + //var instance = new OpenApiPetstore.OuterEnum(); //expect(instance).to.be.a(OpenApiPetstore.OuterEnum); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumDefaultValue.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumDefaultValue.spec.js index 9da972203e..213f8de637 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumDefaultValue.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumDefaultValue.spec.js @@ -49,7 +49,7 @@ describe('OuterEnumDefaultValue', function() { it('should create an instance of OuterEnumDefaultValue', function() { // uncomment below and update the code to test OuterEnumDefaultValue - //var instane = new OpenApiPetstore.OuterEnumDefaultValue(); + //var instance = new OpenApiPetstore.OuterEnumDefaultValue(); //expect(instance).to.be.a(OpenApiPetstore.OuterEnumDefaultValue); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumInteger.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumInteger.spec.js index 196da96a8d..50c8b78c5f 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumInteger.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumInteger.spec.js @@ -49,7 +49,7 @@ describe('OuterEnumInteger', function() { it('should create an instance of OuterEnumInteger', function() { // uncomment below and update the code to test OuterEnumInteger - //var instane = new OpenApiPetstore.OuterEnumInteger(); + //var instance = new OpenApiPetstore.OuterEnumInteger(); //expect(instance).to.be.a(OpenApiPetstore.OuterEnumInteger); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumIntegerDefaultValue.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumIntegerDefaultValue.spec.js index 24829ac612..af3dab3119 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumIntegerDefaultValue.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/OuterEnumIntegerDefaultValue.spec.js @@ -49,7 +49,7 @@ describe('OuterEnumIntegerDefaultValue', function() { it('should create an instance of OuterEnumIntegerDefaultValue', function() { // uncomment below and update the code to test OuterEnumIntegerDefaultValue - //var instane = new OpenApiPetstore.OuterEnumIntegerDefaultValue(); + //var instance = new OpenApiPetstore.OuterEnumIntegerDefaultValue(); //expect(instance).to.be.a(OpenApiPetstore.OuterEnumIntegerDefaultValue); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/OuterObjectWithEnumProperty.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/OuterObjectWithEnumProperty.spec.js index ea94c61358..9f7afbfd39 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/OuterObjectWithEnumProperty.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/OuterObjectWithEnumProperty.spec.js @@ -50,7 +50,7 @@ describe('OuterObjectWithEnumProperty', function() { it('should create an instance of OuterObjectWithEnumProperty', function() { // uncomment below and update the code to test OuterObjectWithEnumProperty - //var instane = new OpenApiPetstore.OuterObjectWithEnumProperty(); + //var instance = new OpenApiPetstore.OuterObjectWithEnumProperty(); //expect(instance).to.be.a(OpenApiPetstore.OuterObjectWithEnumProperty); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Pet.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Pet.spec.js index f33470481f..7b2f4cf121 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Pet.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Pet.spec.js @@ -50,43 +50,43 @@ describe('Pet', function() { it('should create an instance of Pet', function() { // uncomment below and update the code to test Pet - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be.a(OpenApiPetstore.Pet); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property category (base name: "category")', function() { // uncomment below and update the code to test the property category - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property photoUrls (base name: "photoUrls")', function() { // uncomment below and update the code to test the property photoUrls - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property tags (base name: "tags")', function() { // uncomment below and update the code to test the property tags - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); it('should have the property status (base name: "status")', function() { // uncomment below and update the code to test the property status - //var instane = new OpenApiPetstore.Pet(); + //var instance = new OpenApiPetstore.Pet(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Pig.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Pig.spec.js new file mode 100644 index 0000000000..994a590578 --- /dev/null +++ b/samples/client/petstore/javascript-promise-es6/test/model/Pig.spec.js @@ -0,0 +1,77 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', process.cwd()+'/src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require(process.cwd()+'/src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.OpenApiPetstore); + } +}(this, function(expect, OpenApiPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new OpenApiPetstore.Pig(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Pig', function() { + it('should create an instance of Pig', function() { + // uncomment below and update the code to test Pig + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be.a(OpenApiPetstore.Pig); + }); + + it('should have the property className (base name: "className")', function() { + // uncomment below and update the code to test the property className + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be(); + }); + + it('should have the property color (base name: "color")', function() { + // uncomment below and update the code to test the property color + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be(); + }); + + it('should have the property size (base name: "size")', function() { + // uncomment below and update the code to test the property size + //var instance = new OpenApiPetstore.Pig(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/ReadOnlyFirst.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/ReadOnlyFirst.spec.js index 7584840104..a9be118d2f 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/ReadOnlyFirst.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/ReadOnlyFirst.spec.js @@ -50,19 +50,19 @@ describe('ReadOnlyFirst', function() { it('should create an instance of ReadOnlyFirst', function() { // uncomment below and update the code to test ReadOnlyFirst - //var instane = new OpenApiPetstore.ReadOnlyFirst(); + //var instance = new OpenApiPetstore.ReadOnlyFirst(); //expect(instance).to.be.a(OpenApiPetstore.ReadOnlyFirst); }); it('should have the property bar (base name: "bar")', function() { // uncomment below and update the code to test the property bar - //var instane = new OpenApiPetstore.ReadOnlyFirst(); + //var instance = new OpenApiPetstore.ReadOnlyFirst(); //expect(instance).to.be(); }); it('should have the property baz (base name: "baz")', function() { // uncomment below and update the code to test the property baz - //var instane = new OpenApiPetstore.ReadOnlyFirst(); + //var instance = new OpenApiPetstore.ReadOnlyFirst(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Return.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Return.spec.js index 94aa449c27..75aae37c74 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Return.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Return.spec.js @@ -50,7 +50,7 @@ describe('Return', function() { it('should create an instance of Return', function() { // uncomment below and update the code to test Return - //var instane = new OpenApiPetstore.Return(); + //var instance = new OpenApiPetstore.Return(); //expect(instance).to.be.a(OpenApiPetstore.Return); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/SingleRefType.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/SingleRefType.spec.js deleted file mode 100644 index c0bbb3c018..0000000000 --- a/samples/client/petstore/javascript-promise-es6/test/model/SingleRefType.spec.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - * - */ - -(function(root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. - define(['expect.js', process.cwd()+'/src/index'], factory); - } else if (typeof module === 'object' && module.exports) { - // CommonJS-like environments that support module.exports, like Node. - factory(require('expect.js'), require(process.cwd()+'/src/index')); - } else { - // Browser globals (root is window) - factory(root.expect, root.OpenApiPetstore); - } -}(this, function(expect, OpenApiPetstore) { - 'use strict'; - - var instance; - - beforeEach(function() { - }); - - var getProperty = function(object, getter, property) { - // Use getter method if present; otherwise, get the property directly. - if (typeof object[getter] === 'function') - return object[getter](); - else - return object[property]; - } - - var setProperty = function(object, setter, property, value) { - // Use setter method if present; otherwise, set the property directly. - if (typeof object[setter] === 'function') - object[setter](value); - else - object[property] = value; - } - - describe('SingleRefType', function() { - it('should create an instance of SingleRefType', function() { - // uncomment below and update the code to test SingleRefType - //var instance = new OpenApiPetstore.SingleRefType(); - //expect(instance).to.be.a(OpenApiPetstore.SingleRefType); - }); - - }); - -})); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/SpecialModelName.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/SpecialModelName.spec.js index 7cd283fa54..8b6e95c76f 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/SpecialModelName.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/SpecialModelName.spec.js @@ -50,13 +50,13 @@ describe('SpecialModelName', function() { it('should create an instance of SpecialModelName', function() { // uncomment below and update the code to test SpecialModelName - //var instane = new OpenApiPetstore.SpecialModelName(); + //var instance = new OpenApiPetstore.SpecialModelName(); //expect(instance).to.be.a(OpenApiPetstore.SpecialModelName); }); it('should have the property specialPropertyName (base name: "$special[property.name]")', function() { // uncomment below and update the code to test the property specialPropertyName - //var instane = new OpenApiPetstore.SpecialModelName(); + //var instance = new OpenApiPetstore.SpecialModelName(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/Tag.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/Tag.spec.js index 749022dc38..7832664c4f 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/Tag.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/Tag.spec.js @@ -50,19 +50,19 @@ describe('Tag', function() { it('should create an instance of Tag', function() { // uncomment below and update the code to test Tag - //var instane = new OpenApiPetstore.Tag(); + //var instance = new OpenApiPetstore.Tag(); //expect(instance).to.be.a(OpenApiPetstore.Tag); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.Tag(); + //var instance = new OpenApiPetstore.Tag(); //expect(instance).to.be(); }); it('should have the property name (base name: "name")', function() { // uncomment below and update the code to test the property name - //var instane = new OpenApiPetstore.Tag(); + //var instance = new OpenApiPetstore.Tag(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript-promise-es6/test/model/User.spec.js b/samples/client/petstore/javascript-promise-es6/test/model/User.spec.js index fb24f42d1a..44d541dc64 100644 --- a/samples/client/petstore/javascript-promise-es6/test/model/User.spec.js +++ b/samples/client/petstore/javascript-promise-es6/test/model/User.spec.js @@ -50,55 +50,55 @@ describe('User', function() { it('should create an instance of User', function() { // uncomment below and update the code to test User - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be.a(OpenApiPetstore.User); }); it('should have the property id (base name: "id")', function() { // uncomment below and update the code to test the property id - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property username (base name: "username")', function() { // uncomment below and update the code to test the property username - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property firstName (base name: "firstName")', function() { // uncomment below and update the code to test the property firstName - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property lastName (base name: "lastName")', function() { // uncomment below and update the code to test the property lastName - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property email (base name: "email")', function() { // uncomment below and update the code to test the property email - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property password (base name: "password")', function() { // uncomment below and update the code to test the property password - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property phone (base name: "phone")', function() { // uncomment below and update the code to test the property phone - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); it('should have the property userStatus (base name: "userStatus")', function() { // uncomment below and update the code to test the property userStatus - //var instane = new OpenApiPetstore.User(); + //var instance = new OpenApiPetstore.User(); //expect(instance).to.be(); }); diff --git a/samples/client/petstore/javascript/package-lock.json b/samples/client/petstore/javascript/package-lock.json deleted file mode 100644 index ffa052e5d0..0000000000 --- a/samples/client/petstore/javascript/package-lock.json +++ /dev/null @@ -1,364 +0,0 @@ -{ - "name": "open_api_petstore", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "asynckit": { - "version": "0.4.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" - }, - "combined-stream": { - "version": "1.0.6", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/combined-stream/-/combined-stream-1.0.6.tgz", - "integrity": "sha1-cj599ugBrFYTETp+RFqbactjKBg=", - "requires": { - "delayed-stream": "~1.0.0" - } - }, - "commander": { - "version": "2.3.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/commander/-/commander-2.3.0.tgz", - "integrity": "sha1-/UMOiJgy7DU7ms0d4hfBHLPu+HM=", - "dev": true - }, - "component-emitter": { - "version": "1.2.1", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/component-emitter/-/component-emitter-1.2.1.tgz", - "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=" - }, - "cookiejar": { - "version": "2.1.2", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/cookiejar/-/cookiejar-2.1.2.tgz", - "integrity": "sha1-3YojVTB1L5iPmghE8/xYnjERElw=" - }, - "core-util-is": { - "version": "1.0.2", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" - }, - "debug": { - "version": "3.1.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/debug/-/debug-3.1.0.tgz", - "integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=", - "requires": { - "ms": "2.0.0" - } - }, - "delayed-stream": { - "version": "1.0.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" - }, - "diff": { - "version": "1.4.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/diff/-/diff-1.4.0.tgz", - "integrity": "sha1-fyjS657nsVqX79ic5j3P2qPMur8=", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.2", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/escape-string-regexp/-/escape-string-regexp-1.0.2.tgz", - "integrity": "sha1-Tbwv5nTnGUnK8/smlc5/LcHZqNE=", - "dev": true - }, - "expect.js": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/expect.js/-/expect.js-0.3.1.tgz", - "integrity": "sha1-sKWaDS7/VDdUTr8M6qYBWEHQm1s=", - "dev": true - }, - "extend": { - "version": "3.0.2", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/extend/-/extend-3.0.2.tgz", - "integrity": "sha1-+LETa0Bx+9jrFAr/hYsQGewpFfo=" - }, - "form-data": { - "version": "2.3.2", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/form-data/-/form-data-2.3.2.tgz", - "integrity": "sha1-SXBJi+YEwgwAXU9cI67NIda0kJk=", - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "1.0.6", - "mime-types": "^2.1.12" - } - }, - "formatio": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/formatio/-/formatio-1.1.1.tgz", - "integrity": "sha1-XtPM1jZVEJc4NGXZlhmRAOhhYek=", - "dev": true, - "requires": { - "samsam": "~1.1" - } - }, - "formidable": { - "version": "1.2.1", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/formidable/-/formidable-1.2.1.tgz", - "integrity": "sha1-cPt8oCkO5v+WEJBBX0s989IIJlk=" - }, - "glob": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-3.2.3.tgz", - "integrity": "sha1-4xPusknHr/qlxHUoaw4RW1mDlGc=", - "dev": true, - "requires": { - "graceful-fs": "~2.0.0", - "inherits": "2", - "minimatch": "~0.2.11" - } - }, - "graceful-fs": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-2.0.3.tgz", - "integrity": "sha1-fNLNsiiko/Nule+mzBQt59GhNtA=", - "dev": true - }, - "growl": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/growl/-/growl-1.8.1.tgz", - "integrity": "sha1-Sy3sjZB+k9szZiTc7AGDUC+MlCg=", - "dev": true - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" - }, - "isarray": { - "version": "1.0.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - }, - "jade": { - "version": "0.26.3", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/jade/-/jade-0.26.3.tgz", - "integrity": "sha1-jxDXl32NefL2/4YqgbBRPMslaGw=", - "dev": true, - "requires": { - "commander": "0.6.1", - "mkdirp": "0.3.0" - }, - "dependencies": { - "commander": { - "version": "0.6.1", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/commander/-/commander-0.6.1.tgz", - "integrity": "sha1-+mihT2qUXVTbvlDYzbMyDp47GgY=", - "dev": true - }, - "mkdirp": { - "version": "0.3.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/mkdirp/-/mkdirp-0.3.0.tgz", - "integrity": "sha1-G79asbqCevI1dRQ0kEJkVfSB/h4=", - "dev": true - } - } - }, - "lolex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/lolex/-/lolex-1.3.2.tgz", - "integrity": "sha1-fD2mL/yzDw9agKJWbKJORdigHzE=", - "dev": true - }, - "lru-cache": { - "version": "2.7.3", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/lru-cache/-/lru-cache-2.7.3.tgz", - "integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI=", - "dev": true - }, - "methods": { - "version": "1.1.2", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/methods/-/methods-1.1.2.tgz", - "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" - }, - "mime": { - "version": "1.6.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/mime/-/mime-1.6.0.tgz", - "integrity": "sha1-Ms2eXGRVO9WNGaVor0Uqz/BJgbE=" - }, - "mime-db": { - "version": "1.35.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/mime-db/-/mime-db-1.35.0.tgz", - "integrity": "sha1-BWnWV0ZkkSg3CWY603mpm5DZq0c=" - }, - "mime-types": { - "version": "2.1.19", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/mime-types/-/mime-types-2.1.19.tgz", - "integrity": "sha1-ceRkU3p++BwV8tudl+kT/A/2BvA=", - "requires": { - "mime-db": "~1.35.0" - } - }, - "minimatch": { - "version": "0.2.14", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/minimatch/-/minimatch-0.2.14.tgz", - "integrity": "sha1-x054BXT2PG+aCQ6Q775u9TpqdWo=", - "dev": true, - "requires": { - "lru-cache": "2", - "sigmund": "~1.0.0" - } - }, - "minimist": { - "version": "0.0.8", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", - "dev": true - }, - "mkdirp": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz", - "integrity": "sha1-HXMHam35hs2TROFecfzAWkyavxI=", - "dev": true, - "requires": { - "minimist": "0.0.8" - } - }, - "mocha": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-2.3.4.tgz", - "integrity": "sha1-himm+wRPLSJapLgaKuLQAWmesmY=", - "dev": true, - "requires": { - "commander": "2.3.0", - "debug": "2.2.0", - "diff": "1.4.0", - "escape-string-regexp": "1.0.2", - "glob": "3.2.3", - "growl": "1.8.1", - "jade": "0.26.3", - "mkdirp": "0.5.0", - "supports-color": "1.2.0" - }, - "dependencies": { - "debug": { - "version": "2.2.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/debug/-/debug-2.2.0.tgz", - "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", - "dev": true, - "requires": { - "ms": "0.7.1" - } - }, - "ms": { - "version": "0.7.1", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/ms/-/ms-0.7.1.tgz", - "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", - "dev": true - } - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" - }, - "process-nextick-args": { - "version": "2.0.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/process-nextick-args/-/process-nextick-args-2.0.0.tgz", - "integrity": "sha1-o31zL0JxtKsa0HDTVQjoKQeI/6o=" - }, - "qs": { - "version": "6.5.2", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/qs/-/qs-6.5.2.tgz", - "integrity": "sha1-yzroBuh0BERYTvFUzo7pjUA/PjY=" - }, - "readable-stream": { - "version": "2.3.6", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/readable-stream/-/readable-stream-2.3.6.tgz", - "integrity": "sha1-sRwn2IuP8fvgcGQ8+UsMea4bCq8=", - "requires": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "safe-buffer": { - "version": "5.1.2", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha1-mR7GnSluAxN0fVm9/St0XDX4go0=" - }, - "samsam": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/samsam/-/samsam-1.1.2.tgz", - "integrity": "sha1-vsEf3IOp/aBjQBIQ5AF2wwJNFWc=", - "dev": true - }, - "sigmund": { - "version": "1.0.1", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/sigmund/-/sigmund-1.0.1.tgz", - "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=", - "dev": true - }, - "sinon": { - "version": "1.17.3", - "resolved": "https://registry.npmjs.org/sinon/-/sinon-1.17.3.tgz", - "integrity": "sha1-RNZLx0jQI4gARsFUPO/Oo0xH0X4=", - "dev": true, - "requires": { - "formatio": "1.1.1", - "lolex": "1.3.2", - "samsam": "1.1.2", - "util": ">=0.10.3 <1" - } - }, - "string_decoder": { - "version": "1.1.1", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha1-nPFhG6YmhdcDCunkujQUnDrwP8g=", - "requires": { - "safe-buffer": "~5.1.0" - } - }, - "superagent": { - "version": "3.7.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/superagent/-/superagent-3.7.0.tgz", - "integrity": "sha1-vVi/3iy8UwWtucy7bay6GECGKdY=", - "requires": { - "component-emitter": "^1.2.0", - "cookiejar": "^2.1.0", - "debug": "^3.1.0", - "extend": "^3.0.0", - "form-data": "^2.3.1", - "formidable": "^1.1.1", - "methods": "^1.1.1", - "mime": "^1.4.1", - "qs": "^6.5.1", - "readable-stream": "^2.0.5" - } - }, - "supports-color": { - "version": "1.2.0", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/supports-color/-/supports-color-1.2.0.tgz", - "integrity": "sha1-/x7R5hFp0Gs88tWI4YixjYhH4X4=", - "dev": true - }, - "util": { - "version": "0.10.3", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/util/-/util-0.10.3.tgz", - "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", - "dev": true, - "requires": { - "inherits": "2.0.1" - }, - "dependencies": { - "inherits": { - "version": "2.0.1", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/inherits/-/inherits-2.0.1.tgz", - "integrity": "sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE=", - "dev": true - } - } - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://artifactory.sri.com/artifactory/api/npm/Sunflower-NPM-all/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" - } - } -} diff --git a/samples/client/petstore/kotlin-allOff-discriminator/README.md b/samples/client/petstore/kotlin-allOff-discriminator/README.md index a0dbb4c5fe..6b1ed0fb32 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/README.md +++ b/samples/client/petstore/kotlin-allOff-discriminator/README.md @@ -1,5 +1,15 @@ # org.openapitools.client - Kotlin client library for Example +An example + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 0.1 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen +For more information, please visit [https://example.org](https://example.org) + ## Requires * Kotlin 1.4.30 @@ -50,3 +60,8 @@ Class | Method | HTTP request | Description ## Documentation for Authorization All endpoints do not require authorization. + + +## Author + +contact@example.org diff --git a/samples/client/petstore/kotlin-allOff-discriminator/build.gradle b/samples/client/petstore/kotlin-allOff-discriminator/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/build.gradle +++ b/samples/client/petstore/kotlin-allOff-discriminator/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/apis/BirdApi.kt b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/apis/BirdApi.kt index eaed334ee1..84f087c90b 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/apis/BirdApi.kt +++ b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/apis/BirdApi.kt @@ -1,14 +1,9 @@ /** - * Example - * - * An example - * - * The version of the OpenAPI document: 0.1 - * Contact: contact@example.org * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Bird @@ -112,11 +108,14 @@ class BirdApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/v1/bird/{id}".replace("{"+"id"+"}", id.toString()), + path = "/v1/bird/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index bfd00ac6a2..757080d7ed 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -145,7 +148,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -155,7 +158,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -163,16 +166,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/Animal.kt b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/Animal.kt index 5a78f2d42d..df2cbb2bfa 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/Animal.kt +++ b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/Animal.kt @@ -1,14 +1,9 @@ /** - * Example - * - * An example - * - * The version of the OpenAPI document: 0.1 - * Contact: contact@example.org * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/Bird.kt b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/Bird.kt index 5606016ecd..9cf419d67c 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/Bird.kt +++ b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/Bird.kt @@ -1,14 +1,9 @@ /** - * Example - * - * An example - * - * The version of the OpenAPI document: 0.1 - * Contact: contact@example.org * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/BirdAllOf.kt b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/BirdAllOf.kt index d40a792707..dd4054e903 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/BirdAllOf.kt +++ b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/models/BirdAllOf.kt @@ -1,14 +1,9 @@ /** - * Example - * - * An example - * - * The version of the OpenAPI document: 0.1 - * Contact: contact@example.org * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/README.md b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/README.md index 833e3ab254..be47543f96 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/README.md +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Demo +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/build.gradle b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/build.gradle index b19a3b3873..e48744c81e 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/build.gradle +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" implementation "com.squareup.okhttp3:okhttp:3.12.13" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index 50854f326b..f25a3c0953 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import com.squareup.moshi.Json @@ -108,11 +104,14 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient return RequestConfig( method = RequestMethod.GET, - path = "/{ids}".replace("{"+"ids"+"}", ids.joinToString(",")), + path = "/{ids}".replace("{"+"ids"+"}", encodeURIComponent(ids.joinToString(","))), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments()[0] } diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 6db8e7c74f..90aff17076 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -65,6 +65,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> RequestBody.create(MediaType.parse(mediaType ?: guessContentTypeFromFile(content)), content) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -72,22 +73,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(Headers.of(headers), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = MediaType.parse(guessContentTypeFromFile(part.body)) + addPart( + Headers.of(partHeaders), + RequestBody.create(fileMediaType, part.body) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + Headers.of(partHeaders), + RequestBody.create(null, parameterToString(part.body)) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> RequestBody.create(MediaType.parse(mediaType ?: guessContentTypeFromFile(content)), content) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -143,7 +146,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -153,7 +156,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -161,16 +164,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/README.md b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/README.md index 833e3ab254..be47543f96 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/README.md +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Demo +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/build.gradle b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/build.gradle +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index 50854f326b..9e3ae5ca5a 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import com.squareup.moshi.Json @@ -108,11 +104,14 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient return RequestConfig( method = RequestMethod.GET, - path = "/{ids}".replace("{"+"ids"+"}", ids.joinToString(",")), + path = "/{ids}".replace("{"+"ids"+"}", encodeURIComponent(ids.joinToString(","))), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index bfd00ac6a2..757080d7ed 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -145,7 +148,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -155,7 +158,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -163,16 +166,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/README.md b/samples/client/petstore/kotlin-array-simple-string-multiplatform/README.md index f89fa40280..a0768dda37 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/README.md +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Demo +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.5.10 diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-array-simple-string-multiplatform/build.gradle.kts index 2380844aa9..219d79917c 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/build.gradle.kts @@ -8,10 +8,10 @@ plugins { group = "org.openapitools" version = "1.0.0" -val kotlin_version = "1.6.0" -val coroutines_version = "1.5.2" -val serialization_version = "1.3.0" -val ktor_version = "1.6.4" +val kotlin_version = "1.6.10" +val coroutines_version = "1.6.3" +val serialization_version = "1.3.3" +val ktor_version = "2.0.3" repositories { mavenCentral() @@ -30,9 +30,11 @@ kotlin { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") + api("io.ktor:ktor-client-core:$ktor_version") - api("io.ktor:ktor-client-json:$ktor_version") api("io.ktor:ktor-client-serialization:$ktor_version") + api("io.ktor:ktor-client-content-negotiation:$ktor_version") + api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") } } diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonTest/kotlin/util/Coroutine.kt index 110762d355..4db267d629 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/iosTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/iosTest/kotlin/util/Coroutine.kt index 51f9803de3..e967e3993c 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/iosTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/iosTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt index 51f9803de3..e967e3993c 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index d79299bb11..dd9cdca33e 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -25,7 +20,6 @@ import org.openapitools.client.infrastructure.* import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json import io.ktor.http.ParametersBuilder import kotlinx.serialization.* diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 77dc28c814..fd07e4229d 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -3,43 +3,31 @@ package org.openapitools.client.infrastructure import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.JsonFeature -import io.ktor.client.features.json.JsonSerializer -import io.ktor.client.features.json.serializer.KotlinxSerializer +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.serialization.kotlinx.json.* import io.ktor.client.request.* import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse -import io.ktor.client.utils.EmptyContent import io.ktor.http.* -import io.ktor.http.content.OutgoingContent import io.ktor.http.content.PartData import kotlin.Unit import kotlinx.serialization.json.Json -import org.openapitools.client.apis.* -import org.openapitools.client.models.* import org.openapitools.client.auth.* open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - private val json: Json + private val jsonBlock: Json ) { - private val serializer: JsonSerializer by lazy { - KotlinxSerializer(json).ignoreOutgoingContent() - } - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { { - // Hold a reference to the serializer to avoid freezing the entire ApiClient instance - // when the JsonFeature is configured. - val serializerReference = serializer - it.install(JsonFeature) { serializer = serializerReference } + it.install(ContentNegotiation) { json(jsonBlock) } httpClientConfig?.invoke(it) } } @@ -52,7 +40,11 @@ open class ApiClient( companion object { const val BASE_URL = "http://localhost" - val JSON_DEFAULT = Json { ignoreUnknownKeys = true } + val JSON_DEFAULT = Json { + ignoreUnknownKeys = true + prettyPrint = true + isLenient = true + } protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) } @@ -132,18 +124,13 @@ open class ApiClient( return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) } - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } - ?: ContentType.Application.Json) - return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) - else request(requestConfig, authNames = authNames) - } + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.request { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -156,7 +143,7 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - this.body = body + this.setBody(body) } } @@ -182,14 +169,4 @@ open class ApiClient( RequestMethod.POST -> HttpMethod.Post RequestMethod.OPTIONS -> HttpMethod.Options } -} - -// https://github.com/ktorio/ktor/issues/851 -private fun JsonSerializer.ignoreOutgoingContent() = IgnoreOutgoingContentJsonSerializer(this) - -private class IgnoreOutgoingContentJsonSerializer(private val delegate: JsonSerializer) : JsonSerializer by delegate { - override fun write(data: Any): OutgoingContent { - if (data is OutgoingContent) return data - return delegate.write(data) - } -} +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt index 7d30ce18fc..0ff8578738 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -14,7 +14,7 @@ private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it private fun Int.toBase64(): Char = BASE64_ALPHABET[this] private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() -internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { writeStringUtf8(dropLastWhile { it == BASE64_PAD }) }.decodeBase64Bytes().readBytes() +internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { dropLastWhile { it == BASE64_PAD } }.decodeBase64Bytes().readBytes() /** * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt index 61e55bc5b1..4285d605ea 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -1,9 +1,9 @@ package org.openapitools.client.infrastructure -import io.ktor.client.call.TypeInfo -import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { val status: Int = response.status.value @@ -29,11 +29,11 @@ interface BodyProvider { class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { @Suppress("UNCHECKED_CAST") override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.receive(type) as T + response.call.body(type) as T @Suppress("UNCHECKED_CAST") override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.receive(type) as V + response.call.body(type) as V } class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/README.md b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/README.md index 49943bfb2c..5e3b917974 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/README.md +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Demo +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.5.10 diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/build.gradle.kts index 2380844aa9..219d79917c 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/build.gradle.kts @@ -8,10 +8,10 @@ plugins { group = "org.openapitools" version = "1.0.0" -val kotlin_version = "1.6.0" -val coroutines_version = "1.5.2" -val serialization_version = "1.3.0" -val ktor_version = "1.6.4" +val kotlin_version = "1.6.10" +val coroutines_version = "1.6.3" +val serialization_version = "1.3.3" +val ktor_version = "2.0.3" repositories { mavenCentral() @@ -30,9 +30,11 @@ kotlin { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") + api("io.ktor:ktor-client-core:$ktor_version") - api("io.ktor:ktor-client-json:$ktor_version") api("io.ktor:ktor-client-serialization:$ktor_version") + api("io.ktor:ktor-client-content-negotiation:$ktor_version") + api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") } } diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonTest/kotlin/util/Coroutine.kt index 110762d355..4db267d629 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/iosTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/iosTest/kotlin/util/Coroutine.kt index 51f9803de3..e967e3993c 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/iosTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/iosTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt index 51f9803de3..e967e3993c 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index 8daf437915..5b62d07e6c 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -26,7 +21,6 @@ import org.openapitools.client.infrastructure.* import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json import io.ktor.http.ParametersBuilder import kotlinx.serialization.* diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 77dc28c814..fd07e4229d 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -3,43 +3,31 @@ package org.openapitools.client.infrastructure import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.JsonFeature -import io.ktor.client.features.json.JsonSerializer -import io.ktor.client.features.json.serializer.KotlinxSerializer +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.serialization.kotlinx.json.* import io.ktor.client.request.* import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse -import io.ktor.client.utils.EmptyContent import io.ktor.http.* -import io.ktor.http.content.OutgoingContent import io.ktor.http.content.PartData import kotlin.Unit import kotlinx.serialization.json.Json -import org.openapitools.client.apis.* -import org.openapitools.client.models.* import org.openapitools.client.auth.* open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - private val json: Json + private val jsonBlock: Json ) { - private val serializer: JsonSerializer by lazy { - KotlinxSerializer(json).ignoreOutgoingContent() - } - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { { - // Hold a reference to the serializer to avoid freezing the entire ApiClient instance - // when the JsonFeature is configured. - val serializerReference = serializer - it.install(JsonFeature) { serializer = serializerReference } + it.install(ContentNegotiation) { json(jsonBlock) } httpClientConfig?.invoke(it) } } @@ -52,7 +40,11 @@ open class ApiClient( companion object { const val BASE_URL = "http://localhost" - val JSON_DEFAULT = Json { ignoreUnknownKeys = true } + val JSON_DEFAULT = Json { + ignoreUnknownKeys = true + prettyPrint = true + isLenient = true + } protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) } @@ -132,18 +124,13 @@ open class ApiClient( return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) } - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } - ?: ContentType.Application.Json) - return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) - else request(requestConfig, authNames = authNames) - } + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.request { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -156,7 +143,7 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - this.body = body + this.setBody(body) } } @@ -182,14 +169,4 @@ open class ApiClient( RequestMethod.POST -> HttpMethod.Post RequestMethod.OPTIONS -> HttpMethod.Options } -} - -// https://github.com/ktorio/ktor/issues/851 -private fun JsonSerializer.ignoreOutgoingContent() = IgnoreOutgoingContentJsonSerializer(this) - -private class IgnoreOutgoingContentJsonSerializer(private val delegate: JsonSerializer) : JsonSerializer by delegate { - override fun write(data: Any): OutgoingContent { - if (data is OutgoingContent) return data - return delegate.write(data) - } -} +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt index 7d30ce18fc..0ff8578738 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -14,7 +14,7 @@ private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it private fun Int.toBase64(): Char = BASE64_ALPHABET[this] private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() -internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { writeStringUtf8(dropLastWhile { it == BASE64_PAD }) }.decodeBase64Bytes().readBytes() +internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { dropLastWhile { it == BASE64_PAD } }.decodeBase64Bytes().readBytes() /** * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt index 61e55bc5b1..4285d605ea 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -1,9 +1,9 @@ package org.openapitools.client.infrastructure -import io.ktor.client.call.TypeInfo -import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { val status: Int = response.status.value @@ -29,11 +29,11 @@ interface BodyProvider { class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { @Suppress("UNCHECKED_CAST") override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.receive(type) as T + response.call.body(type) as T @Suppress("UNCHECKED_CAST") override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.receive(type) as V + response.call.body(type) as V } class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt index 3d57bf158a..d2a5502173 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/README.md b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/README.md index 5928098211..e1589aead6 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/README.md +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Demo +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/build.gradle b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/build.gradle +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index a9d705e857..c1323d49b0 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Apa @@ -117,4 +113,7 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index bfd00ac6a2..757080d7ed 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -145,7 +148,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -155,7 +158,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -163,16 +166,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/models/Apa.kt index 574811c7f1..ca2a4a45df 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/models/Apa.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/models/Apa.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/README.md b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/README.md index f575aaf50c..96bddb2ac9 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/README.md +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Demo +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/build.gradle b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/build.gradle index b19a3b3873..e48744c81e 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/build.gradle +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" implementation "com.squareup.okhttp3:okhttp:3.12.13" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/docs/DefaultApi.md b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/docs/DefaultApi.md index 97d95ded4d..beff84ea66 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/docs/DefaultApi.md +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/docs/DefaultApi.md @@ -9,7 +9,7 @@ Method | HTTP request | Description # **test** -> test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3) +> test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3, fn4) Tests default values @@ -50,8 +50,9 @@ val fn0 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn1 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn2 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn3 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | +val fn4 : kotlin.collections.List = // kotlin.collections.List | try { - apiInstance.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3) + apiInstance.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3, fn4) } catch (e: ClientException) { println("4xx response calling DefaultApi#test") e.printStackTrace() @@ -93,6 +94,7 @@ Name | Type | Description | Notes **fn1** | **java.math.BigDecimal**| | [default to 71.0] **fn2** | **java.math.BigDecimal**| | [optional] **fn3** | **java.math.BigDecimal**| | + **fn4** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| | ### Return type diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index 3e00596068..e5342a3c2f 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import com.squareup.moshi.Json @@ -79,6 +75,7 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient * @param fn1 (default to 71.0) * @param fn2 (optional) * @param fn3 + * @param fn4 * @return void * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception @@ -87,8 +84,8 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient * @throws ServerException If the API returns a server error response */ @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) - fun test(pi0: kotlin.Int = 10, pi1: kotlin.Int, pn0: java.math.BigDecimal = java.math.BigDecimal("10.0"), pn1: java.math.BigDecimal, qi0: kotlin.Int? = 10, qi1: kotlin.Int = 71, qi2: kotlin.Int? = null, qi3: kotlin.Int, qn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), qn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), qn2: java.math.BigDecimal? = null, qn3: java.math.BigDecimal, hi0: kotlin.Int? = 10, hi1: kotlin.Int = 71, hi2: kotlin.Int? = null, hi3: kotlin.Int, hn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), hn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), hn2: java.math.BigDecimal? = null, hn3: java.math.BigDecimal, fi0: kotlin.Int? = 10, fi1: kotlin.Int = 71, fi2: kotlin.Int? = null, fi3: kotlin.Int, fn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), fn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), fn2: java.math.BigDecimal? = null, fn3: java.math.BigDecimal) : Unit { - val localVarResponse = testWithHttpInfo(pi0 = pi0, pi1 = pi1, pn0 = pn0, pn1 = pn1, qi0 = qi0, qi1 = qi1, qi2 = qi2, qi3 = qi3, qn0 = qn0, qn1 = qn1, qn2 = qn2, qn3 = qn3, hi0 = hi0, hi1 = hi1, hi2 = hi2, hi3 = hi3, hn0 = hn0, hn1 = hn1, hn2 = hn2, hn3 = hn3, fi0 = fi0, fi1 = fi1, fi2 = fi2, fi3 = fi3, fn0 = fn0, fn1 = fn1, fn2 = fn2, fn3 = fn3) + fun test(pi0: kotlin.Int = 10, pi1: kotlin.Int, pn0: java.math.BigDecimal = java.math.BigDecimal("10.0"), pn1: java.math.BigDecimal, qi0: kotlin.Int? = 10, qi1: kotlin.Int = 71, qi2: kotlin.Int? = null, qi3: kotlin.Int, qn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), qn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), qn2: java.math.BigDecimal? = null, qn3: java.math.BigDecimal, hi0: kotlin.Int? = 10, hi1: kotlin.Int = 71, hi2: kotlin.Int? = null, hi3: kotlin.Int, hn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), hn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), hn2: java.math.BigDecimal? = null, hn3: java.math.BigDecimal, fi0: kotlin.Int? = 10, fi1: kotlin.Int = 71, fi2: kotlin.Int? = null, fi3: kotlin.Int, fn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), fn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), fn2: java.math.BigDecimal? = null, fn3: java.math.BigDecimal, fn4: kotlin.collections.List) : Unit { + val localVarResponse = testWithHttpInfo(pi0 = pi0, pi1 = pi1, pn0 = pn0, pn1 = pn1, qi0 = qi0, qi1 = qi1, qi2 = qi2, qi3 = qi3, qn0 = qn0, qn1 = qn1, qn2 = qn2, qn3 = qn3, hi0 = hi0, hi1 = hi1, hi2 = hi2, hi3 = hi3, hn0 = hn0, hn1 = hn1, hn2 = hn2, hn3 = hn3, fi0 = fi0, fi1 = fi1, fi2 = fi2, fi3 = fi3, fn0 = fn0, fn1 = fn1, fn2 = fn2, fn3 = fn3, fn4 = fn4) return when (localVarResponse.responseType) { ResponseType.Success -> Unit @@ -136,13 +133,14 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient * @param fn1 (default to 71.0) * @param fn2 (optional) * @param fn3 + * @param fn4 * @return ApiResponse * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Throws(IllegalStateException::class, IOException::class) - fun testWithHttpInfo(pi0: kotlin.Int, pi1: kotlin.Int, pn0: java.math.BigDecimal, pn1: java.math.BigDecimal, qi0: kotlin.Int?, qi1: kotlin.Int, qi2: kotlin.Int?, qi3: kotlin.Int, qn0: java.math.BigDecimal?, qn1: java.math.BigDecimal, qn2: java.math.BigDecimal?, qn3: java.math.BigDecimal, hi0: kotlin.Int?, hi1: kotlin.Int, hi2: kotlin.Int?, hi3: kotlin.Int, hn0: java.math.BigDecimal?, hn1: java.math.BigDecimal, hn2: java.math.BigDecimal?, hn3: java.math.BigDecimal, fi0: kotlin.Int?, fi1: kotlin.Int, fi2: kotlin.Int?, fi3: kotlin.Int, fn0: java.math.BigDecimal?, fn1: java.math.BigDecimal, fn2: java.math.BigDecimal?, fn3: java.math.BigDecimal) : ApiResponse { - val localVariableConfig = testRequestConfig(pi0 = pi0, pi1 = pi1, pn0 = pn0, pn1 = pn1, qi0 = qi0, qi1 = qi1, qi2 = qi2, qi3 = qi3, qn0 = qn0, qn1 = qn1, qn2 = qn2, qn3 = qn3, hi0 = hi0, hi1 = hi1, hi2 = hi2, hi3 = hi3, hn0 = hn0, hn1 = hn1, hn2 = hn2, hn3 = hn3, fi0 = fi0, fi1 = fi1, fi2 = fi2, fi3 = fi3, fn0 = fn0, fn1 = fn1, fn2 = fn2, fn3 = fn3) + fun testWithHttpInfo(pi0: kotlin.Int, pi1: kotlin.Int, pn0: java.math.BigDecimal, pn1: java.math.BigDecimal, qi0: kotlin.Int?, qi1: kotlin.Int, qi2: kotlin.Int?, qi3: kotlin.Int, qn0: java.math.BigDecimal?, qn1: java.math.BigDecimal, qn2: java.math.BigDecimal?, qn3: java.math.BigDecimal, hi0: kotlin.Int?, hi1: kotlin.Int, hi2: kotlin.Int?, hi3: kotlin.Int, hn0: java.math.BigDecimal?, hn1: java.math.BigDecimal, hn2: java.math.BigDecimal?, hn3: java.math.BigDecimal, fi0: kotlin.Int?, fi1: kotlin.Int, fi2: kotlin.Int?, fi3: kotlin.Int, fn0: java.math.BigDecimal?, fn1: java.math.BigDecimal, fn2: java.math.BigDecimal?, fn3: java.math.BigDecimal, fn4: kotlin.collections.List) : ApiResponse { + val localVariableConfig = testRequestConfig(pi0 = pi0, pi1 = pi1, pn0 = pn0, pn1 = pn1, qi0 = qi0, qi1 = qi1, qi2 = qi2, qi3 = qi3, qn0 = qn0, qn1 = qn1, qn2 = qn2, qn3 = qn3, hi0 = hi0, hi1 = hi1, hi2 = hi2, hi3 = hi3, hn0 = hn0, hn1 = hn1, hn2 = hn2, hn3 = hn3, fi0 = fi0, fi1 = fi1, fi2 = fi2, fi3 = fi3, fn0 = fn0, fn1 = fn1, fn2 = fn2, fn3 = fn3, fn4 = fn4) return request>, Unit>( localVariableConfig @@ -180,9 +178,10 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient * @param fn1 (default to 71.0) * @param fn2 (optional) * @param fn3 + * @param fn4 * @return RequestConfig */ - fun testRequestConfig(pi0: kotlin.Int, pi1: kotlin.Int, pn0: java.math.BigDecimal, pn1: java.math.BigDecimal, qi0: kotlin.Int?, qi1: kotlin.Int, qi2: kotlin.Int?, qi3: kotlin.Int, qn0: java.math.BigDecimal?, qn1: java.math.BigDecimal, qn2: java.math.BigDecimal?, qn3: java.math.BigDecimal, hi0: kotlin.Int?, hi1: kotlin.Int, hi2: kotlin.Int?, hi3: kotlin.Int, hn0: java.math.BigDecimal?, hn1: java.math.BigDecimal, hn2: java.math.BigDecimal?, hn3: java.math.BigDecimal, fi0: kotlin.Int?, fi1: kotlin.Int, fi2: kotlin.Int?, fi3: kotlin.Int, fn0: java.math.BigDecimal?, fn1: java.math.BigDecimal, fn2: java.math.BigDecimal?, fn3: java.math.BigDecimal) : RequestConfig>> { + fun testRequestConfig(pi0: kotlin.Int, pi1: kotlin.Int, pn0: java.math.BigDecimal, pn1: java.math.BigDecimal, qi0: kotlin.Int?, qi1: kotlin.Int, qi2: kotlin.Int?, qi3: kotlin.Int, qn0: java.math.BigDecimal?, qn1: java.math.BigDecimal, qn2: java.math.BigDecimal?, qn3: java.math.BigDecimal, hi0: kotlin.Int?, hi1: kotlin.Int, hi2: kotlin.Int?, hi3: kotlin.Int, hn0: java.math.BigDecimal?, hn1: java.math.BigDecimal, hn2: java.math.BigDecimal?, hn3: java.math.BigDecimal, fi0: kotlin.Int?, fi1: kotlin.Int, fi2: kotlin.Int?, fi3: kotlin.Int, fn0: java.math.BigDecimal?, fn1: java.math.BigDecimal, fn2: java.math.BigDecimal?, fn3: java.math.BigDecimal, fn4: kotlin.collections.List) : RequestConfig>> { val localVariableBody = mapOf( "fi0" to PartConfig(body = fi0, headers = mutableMapOf()), "fi1" to PartConfig(body = fi1, headers = mutableMapOf()), @@ -191,7 +190,8 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient "fn0" to PartConfig(body = fn0, headers = mutableMapOf()), "fn1" to PartConfig(body = fn1, headers = mutableMapOf()), "fn2" to PartConfig(body = fn2, headers = mutableMapOf()), - "fn3" to PartConfig(body = fn3, headers = mutableMapOf()),) + "fn3" to PartConfig(body = fn3, headers = mutableMapOf()), + "fn4" to PartConfig(body = fn4, headers = mutableMapOf()),) val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { if (qi0 != null) { @@ -223,11 +223,14 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient return RequestConfig( method = RequestMethod.POST, - path = "/test".replace("{"+"pi0"+"}", pi0.toString()).replace("{"+"pi1"+"}", pi1.toString()).replace("{"+"pn0"+"}", pn0.toString()).replace("{"+"pn1"+"}", pn1.toString()), + path = "/test".replace("{"+"pi0"+"}", encodeURIComponent(pi0.toString())).replace("{"+"pi1"+"}", encodeURIComponent(pi1.toString())).replace("{"+"pn0"+"}", encodeURIComponent(pn0.toString())).replace("{"+"pn1"+"}", encodeURIComponent(pn1.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments()[0] } diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 6db8e7c74f..90aff17076 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -65,6 +65,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> RequestBody.create(MediaType.parse(mediaType ?: guessContentTypeFromFile(content)), content) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -72,22 +73,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(Headers.of(headers), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = MediaType.parse(guessContentTypeFromFile(part.body)) + addPart( + Headers.of(partHeaders), + RequestBody.create(fileMediaType, part.body) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + Headers.of(partHeaders), + RequestBody.create(null, parameterToString(part.body)) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> RequestBody.create(MediaType.parse(mediaType ?: guessContentTypeFromFile(content)), content) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -143,7 +146,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -153,7 +156,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -161,16 +164,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/models/Apa.kt index cb23ff967a..4455c9a2ae 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/models/Apa.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/models/Apa.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/README.md b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/README.md index f575aaf50c..96bddb2ac9 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/README.md +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Demo +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/build.gradle b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/build.gradle +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/docs/DefaultApi.md b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/docs/DefaultApi.md index 97d95ded4d..beff84ea66 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/docs/DefaultApi.md +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/docs/DefaultApi.md @@ -9,7 +9,7 @@ Method | HTTP request | Description # **test** -> test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3) +> test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3, fn4) Tests default values @@ -50,8 +50,9 @@ val fn0 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn1 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn2 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn3 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | +val fn4 : kotlin.collections.List = // kotlin.collections.List | try { - apiInstance.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3) + apiInstance.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3, fn4) } catch (e: ClientException) { println("4xx response calling DefaultApi#test") e.printStackTrace() @@ -93,6 +94,7 @@ Name | Type | Description | Notes **fn1** | **java.math.BigDecimal**| | [default to 71.0] **fn2** | **java.math.BigDecimal**| | [optional] **fn3** | **java.math.BigDecimal**| | + **fn4** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| | ### Return type diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index 3e00596068..bf0058dc6c 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import com.squareup.moshi.Json @@ -79,6 +75,7 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient * @param fn1 (default to 71.0) * @param fn2 (optional) * @param fn3 + * @param fn4 * @return void * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception @@ -87,8 +84,8 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient * @throws ServerException If the API returns a server error response */ @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) - fun test(pi0: kotlin.Int = 10, pi1: kotlin.Int, pn0: java.math.BigDecimal = java.math.BigDecimal("10.0"), pn1: java.math.BigDecimal, qi0: kotlin.Int? = 10, qi1: kotlin.Int = 71, qi2: kotlin.Int? = null, qi3: kotlin.Int, qn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), qn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), qn2: java.math.BigDecimal? = null, qn3: java.math.BigDecimal, hi0: kotlin.Int? = 10, hi1: kotlin.Int = 71, hi2: kotlin.Int? = null, hi3: kotlin.Int, hn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), hn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), hn2: java.math.BigDecimal? = null, hn3: java.math.BigDecimal, fi0: kotlin.Int? = 10, fi1: kotlin.Int = 71, fi2: kotlin.Int? = null, fi3: kotlin.Int, fn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), fn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), fn2: java.math.BigDecimal? = null, fn3: java.math.BigDecimal) : Unit { - val localVarResponse = testWithHttpInfo(pi0 = pi0, pi1 = pi1, pn0 = pn0, pn1 = pn1, qi0 = qi0, qi1 = qi1, qi2 = qi2, qi3 = qi3, qn0 = qn0, qn1 = qn1, qn2 = qn2, qn3 = qn3, hi0 = hi0, hi1 = hi1, hi2 = hi2, hi3 = hi3, hn0 = hn0, hn1 = hn1, hn2 = hn2, hn3 = hn3, fi0 = fi0, fi1 = fi1, fi2 = fi2, fi3 = fi3, fn0 = fn0, fn1 = fn1, fn2 = fn2, fn3 = fn3) + fun test(pi0: kotlin.Int = 10, pi1: kotlin.Int, pn0: java.math.BigDecimal = java.math.BigDecimal("10.0"), pn1: java.math.BigDecimal, qi0: kotlin.Int? = 10, qi1: kotlin.Int = 71, qi2: kotlin.Int? = null, qi3: kotlin.Int, qn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), qn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), qn2: java.math.BigDecimal? = null, qn3: java.math.BigDecimal, hi0: kotlin.Int? = 10, hi1: kotlin.Int = 71, hi2: kotlin.Int? = null, hi3: kotlin.Int, hn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), hn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), hn2: java.math.BigDecimal? = null, hn3: java.math.BigDecimal, fi0: kotlin.Int? = 10, fi1: kotlin.Int = 71, fi2: kotlin.Int? = null, fi3: kotlin.Int, fn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), fn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), fn2: java.math.BigDecimal? = null, fn3: java.math.BigDecimal, fn4: kotlin.collections.List) : Unit { + val localVarResponse = testWithHttpInfo(pi0 = pi0, pi1 = pi1, pn0 = pn0, pn1 = pn1, qi0 = qi0, qi1 = qi1, qi2 = qi2, qi3 = qi3, qn0 = qn0, qn1 = qn1, qn2 = qn2, qn3 = qn3, hi0 = hi0, hi1 = hi1, hi2 = hi2, hi3 = hi3, hn0 = hn0, hn1 = hn1, hn2 = hn2, hn3 = hn3, fi0 = fi0, fi1 = fi1, fi2 = fi2, fi3 = fi3, fn0 = fn0, fn1 = fn1, fn2 = fn2, fn3 = fn3, fn4 = fn4) return when (localVarResponse.responseType) { ResponseType.Success -> Unit @@ -136,13 +133,14 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient * @param fn1 (default to 71.0) * @param fn2 (optional) * @param fn3 + * @param fn4 * @return ApiResponse * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Throws(IllegalStateException::class, IOException::class) - fun testWithHttpInfo(pi0: kotlin.Int, pi1: kotlin.Int, pn0: java.math.BigDecimal, pn1: java.math.BigDecimal, qi0: kotlin.Int?, qi1: kotlin.Int, qi2: kotlin.Int?, qi3: kotlin.Int, qn0: java.math.BigDecimal?, qn1: java.math.BigDecimal, qn2: java.math.BigDecimal?, qn3: java.math.BigDecimal, hi0: kotlin.Int?, hi1: kotlin.Int, hi2: kotlin.Int?, hi3: kotlin.Int, hn0: java.math.BigDecimal?, hn1: java.math.BigDecimal, hn2: java.math.BigDecimal?, hn3: java.math.BigDecimal, fi0: kotlin.Int?, fi1: kotlin.Int, fi2: kotlin.Int?, fi3: kotlin.Int, fn0: java.math.BigDecimal?, fn1: java.math.BigDecimal, fn2: java.math.BigDecimal?, fn3: java.math.BigDecimal) : ApiResponse { - val localVariableConfig = testRequestConfig(pi0 = pi0, pi1 = pi1, pn0 = pn0, pn1 = pn1, qi0 = qi0, qi1 = qi1, qi2 = qi2, qi3 = qi3, qn0 = qn0, qn1 = qn1, qn2 = qn2, qn3 = qn3, hi0 = hi0, hi1 = hi1, hi2 = hi2, hi3 = hi3, hn0 = hn0, hn1 = hn1, hn2 = hn2, hn3 = hn3, fi0 = fi0, fi1 = fi1, fi2 = fi2, fi3 = fi3, fn0 = fn0, fn1 = fn1, fn2 = fn2, fn3 = fn3) + fun testWithHttpInfo(pi0: kotlin.Int, pi1: kotlin.Int, pn0: java.math.BigDecimal, pn1: java.math.BigDecimal, qi0: kotlin.Int?, qi1: kotlin.Int, qi2: kotlin.Int?, qi3: kotlin.Int, qn0: java.math.BigDecimal?, qn1: java.math.BigDecimal, qn2: java.math.BigDecimal?, qn3: java.math.BigDecimal, hi0: kotlin.Int?, hi1: kotlin.Int, hi2: kotlin.Int?, hi3: kotlin.Int, hn0: java.math.BigDecimal?, hn1: java.math.BigDecimal, hn2: java.math.BigDecimal?, hn3: java.math.BigDecimal, fi0: kotlin.Int?, fi1: kotlin.Int, fi2: kotlin.Int?, fi3: kotlin.Int, fn0: java.math.BigDecimal?, fn1: java.math.BigDecimal, fn2: java.math.BigDecimal?, fn3: java.math.BigDecimal, fn4: kotlin.collections.List) : ApiResponse { + val localVariableConfig = testRequestConfig(pi0 = pi0, pi1 = pi1, pn0 = pn0, pn1 = pn1, qi0 = qi0, qi1 = qi1, qi2 = qi2, qi3 = qi3, qn0 = qn0, qn1 = qn1, qn2 = qn2, qn3 = qn3, hi0 = hi0, hi1 = hi1, hi2 = hi2, hi3 = hi3, hn0 = hn0, hn1 = hn1, hn2 = hn2, hn3 = hn3, fi0 = fi0, fi1 = fi1, fi2 = fi2, fi3 = fi3, fn0 = fn0, fn1 = fn1, fn2 = fn2, fn3 = fn3, fn4 = fn4) return request>, Unit>( localVariableConfig @@ -180,9 +178,10 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient * @param fn1 (default to 71.0) * @param fn2 (optional) * @param fn3 + * @param fn4 * @return RequestConfig */ - fun testRequestConfig(pi0: kotlin.Int, pi1: kotlin.Int, pn0: java.math.BigDecimal, pn1: java.math.BigDecimal, qi0: kotlin.Int?, qi1: kotlin.Int, qi2: kotlin.Int?, qi3: kotlin.Int, qn0: java.math.BigDecimal?, qn1: java.math.BigDecimal, qn2: java.math.BigDecimal?, qn3: java.math.BigDecimal, hi0: kotlin.Int?, hi1: kotlin.Int, hi2: kotlin.Int?, hi3: kotlin.Int, hn0: java.math.BigDecimal?, hn1: java.math.BigDecimal, hn2: java.math.BigDecimal?, hn3: java.math.BigDecimal, fi0: kotlin.Int?, fi1: kotlin.Int, fi2: kotlin.Int?, fi3: kotlin.Int, fn0: java.math.BigDecimal?, fn1: java.math.BigDecimal, fn2: java.math.BigDecimal?, fn3: java.math.BigDecimal) : RequestConfig>> { + fun testRequestConfig(pi0: kotlin.Int, pi1: kotlin.Int, pn0: java.math.BigDecimal, pn1: java.math.BigDecimal, qi0: kotlin.Int?, qi1: kotlin.Int, qi2: kotlin.Int?, qi3: kotlin.Int, qn0: java.math.BigDecimal?, qn1: java.math.BigDecimal, qn2: java.math.BigDecimal?, qn3: java.math.BigDecimal, hi0: kotlin.Int?, hi1: kotlin.Int, hi2: kotlin.Int?, hi3: kotlin.Int, hn0: java.math.BigDecimal?, hn1: java.math.BigDecimal, hn2: java.math.BigDecimal?, hn3: java.math.BigDecimal, fi0: kotlin.Int?, fi1: kotlin.Int, fi2: kotlin.Int?, fi3: kotlin.Int, fn0: java.math.BigDecimal?, fn1: java.math.BigDecimal, fn2: java.math.BigDecimal?, fn3: java.math.BigDecimal, fn4: kotlin.collections.List) : RequestConfig>> { val localVariableBody = mapOf( "fi0" to PartConfig(body = fi0, headers = mutableMapOf()), "fi1" to PartConfig(body = fi1, headers = mutableMapOf()), @@ -191,7 +190,8 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient "fn0" to PartConfig(body = fn0, headers = mutableMapOf()), "fn1" to PartConfig(body = fn1, headers = mutableMapOf()), "fn2" to PartConfig(body = fn2, headers = mutableMapOf()), - "fn3" to PartConfig(body = fn3, headers = mutableMapOf()),) + "fn3" to PartConfig(body = fn3, headers = mutableMapOf()), + "fn4" to PartConfig(body = fn4, headers = mutableMapOf()),) val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { if (qi0 != null) { @@ -223,11 +223,14 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient return RequestConfig( method = RequestMethod.POST, - path = "/test".replace("{"+"pi0"+"}", pi0.toString()).replace("{"+"pi1"+"}", pi1.toString()).replace("{"+"pn0"+"}", pn0.toString()).replace("{"+"pn1"+"}", pn1.toString()), + path = "/test".replace("{"+"pi0"+"}", encodeURIComponent(pi0.toString())).replace("{"+"pi1"+"}", encodeURIComponent(pi1.toString())).replace("{"+"pn0"+"}", encodeURIComponent(pn0.toString())).replace("{"+"pn1"+"}", encodeURIComponent(pn1.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index bfd00ac6a2..757080d7ed 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -145,7 +148,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -155,7 +158,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -163,16 +166,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/models/Apa.kt index cb23ff967a..4455c9a2ae 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/models/Apa.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/models/Apa.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/README.md b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/README.md index 09cab44ee7..904786dd56 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/README.md +++ b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Demo +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/build.gradle b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/build.gradle index e094b70441..07cd4614b2 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/build.gradle +++ b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' ext.retrofitVersion = '2.9.0' repositories { @@ -31,9 +31,9 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:logging-interceptor:4.10.0" implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion" implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" diff --git a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/docs/DefaultApi.md b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/docs/DefaultApi.md index fccc2be060..25c9faaddb 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/docs/DefaultApi.md +++ b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/docs/DefaultApi.md @@ -49,8 +49,9 @@ val fn0 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn1 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn2 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn3 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | +val fn4 : kotlin.collections.List = // kotlin.collections.List | -webService.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3) +webService.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3, fn4) ``` ### Parameters @@ -85,6 +86,7 @@ Name | Type | Description | Notes **fn1** | **java.math.BigDecimal**| | [default to 71.0] **fn2** | **java.math.BigDecimal**| | [optional] **fn3** | **java.math.BigDecimal**| | + **fn4** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| | ### Return type diff --git a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index edfc3a526a..99801bdf65 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -4,6 +4,7 @@ import org.openapitools.client.infrastructure.CollectionFormats.* import retrofit2.http.* import retrofit2.Call import okhttp3.RequestBody +import com.squareup.moshi.Json interface DefaultApi { @@ -41,10 +42,11 @@ interface DefaultApi { * @param fn1 (default to 71.0) * @param fn2 (optional) * @param fn3 + * @param fn4 * @return [Call]<[Unit]> */ @Multipart @POST("test") - fun test(@Path("pi0") pi0: kotlin.Int = 10, @Path("pi1") pi1: kotlin.Int, @Path("pn0") pn0: java.math.BigDecimal = java.math.BigDecimal("10.0"), @Path("pn1") pn1: java.math.BigDecimal, @Query("qi0") qi0: kotlin.Int? = 10, @Query("qi1") qi1: kotlin.Int = 71, @Query("qi2") qi2: kotlin.Int? = null, @Query("qi3") qi3: kotlin.Int, @Query("qn0") qn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), @Query("qn1") qn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), @Query("qn2") qn2: java.math.BigDecimal? = null, @Query("qn3") qn3: java.math.BigDecimal, @Header("hi0") hi0: kotlin.Int? = 10, @Header("hi1") hi1: kotlin.Int = 71, @Header("hi2") hi2: kotlin.Int? = null, @Header("hi3") hi3: kotlin.Int, @Header("hn0") hn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), @Header("hn1") hn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), @Header("hn2") hn2: java.math.BigDecimal? = null, @Header("hn3") hn3: java.math.BigDecimal, @Part("fi0") fi0: kotlin.Int? = 10, @Part("fi1") fi1: kotlin.Int = 71, @Part("fi2") fi2: kotlin.Int? = null, @Part("fi3") fi3: kotlin.Int, @Part("fn0") fn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), @Part("fn1") fn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), @Part("fn2") fn2: java.math.BigDecimal? = null, @Part("fn3") fn3: java.math.BigDecimal): Call + fun test(@Path("pi0") pi0: kotlin.Int = 10, @Path("pi1") pi1: kotlin.Int, @Path("pn0") pn0: java.math.BigDecimal = java.math.BigDecimal("10.0"), @Path("pn1") pn1: java.math.BigDecimal, @Query("qi0") qi0: kotlin.Int? = 10, @Query("qi1") qi1: kotlin.Int = 71, @Query("qi2") qi2: kotlin.Int? = null, @Query("qi3") qi3: kotlin.Int, @Query("qn0") qn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), @Query("qn1") qn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), @Query("qn2") qn2: java.math.BigDecimal? = null, @Query("qn3") qn3: java.math.BigDecimal, @Header("hi0") hi0: kotlin.Int? = 10, @Header("hi1") hi1: kotlin.Int = 71, @Header("hi2") hi2: kotlin.Int? = null, @Header("hi3") hi3: kotlin.Int, @Header("hn0") hn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), @Header("hn1") hn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), @Header("hn2") hn2: java.math.BigDecimal? = null, @Header("hn3") hn3: java.math.BigDecimal, @Part("fi0") fi0: kotlin.Int? = 10, @Part("fi1") fi1: kotlin.Int = 71, @Part("fi2") fi2: kotlin.Int? = null, @Part("fi3") fi3: kotlin.Int, @Part("fn0") fn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), @Part("fn1") fn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), @Part("fn2") fn2: java.math.BigDecimal? = null, @Part("fn3") fn3: java.math.BigDecimal, @Part("fn4") fn4: kotlin.collections.List): Call } diff --git a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/models/Apa.kt index cb23ff967a..4455c9a2ae 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/models/Apa.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/src/main/kotlin/org/openapitools/client/models/Apa.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/docs/DefaultApi.md b/samples/client/petstore/kotlin-default-values-jvm-volley/docs/DefaultApi.md index f85a38f6f7..a7e3b0bc67 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-volley/docs/DefaultApi.md +++ b/samples/client/petstore/kotlin-default-values-jvm-volley/docs/DefaultApi.md @@ -49,8 +49,9 @@ val fn0 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn1 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn2 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | val fn3 : java.math.BigDecimal = 8.14 // java.math.BigDecimal | +val fn4 : kotlin.collections.List = // kotlin.collections.List | -webService.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3) +webService.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3, fn4) ``` ### Parameters @@ -85,6 +86,7 @@ Name | Type | Description | Notes **fn1** | **java.math.BigDecimal**| | [default to 71.0] **fn2** | **java.math.BigDecimal**| | [optional] **fn3** | **java.math.BigDecimal**| | + **fn4** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| | ### Return type diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index 2952353438..13725dca9f 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -63,9 +63,10 @@ class DefaultApi ( * @param fn1 (default to 71.0) * @param fn2 (optional) * @param fn3 + * @param fn4 * @return void */ - suspend fun test(pi0: kotlin.Int = 10, pi1: kotlin.Int, pn0: java.math.BigDecimal = java.math.BigDecimal("10.0"), pn1: java.math.BigDecimal, qi0: kotlin.Int? = 10, qi1: kotlin.Int = 71, qi2: kotlin.Int? = null, qi3: kotlin.Int, qn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), qn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), qn2: java.math.BigDecimal? = null, qn3: java.math.BigDecimal, hi0: kotlin.Int? = 10, hi1: kotlin.Int = 71, hi2: kotlin.Int? = null, hi3: kotlin.Int, hn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), hn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), hn2: java.math.BigDecimal? = null, hn3: java.math.BigDecimal, fi0: kotlin.Int? = 10, fi1: kotlin.Int = 71, fi2: kotlin.Int? = null, fi3: kotlin.Int, fn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), fn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), fn2: java.math.BigDecimal? = null, fn3: java.math.BigDecimal): Unit { + suspend fun test(pi0: kotlin.Int = 10, pi1: kotlin.Int, pn0: java.math.BigDecimal = java.math.BigDecimal("10.0"), pn1: java.math.BigDecimal, qi0: kotlin.Int? = 10, qi1: kotlin.Int = 71, qi2: kotlin.Int? = null, qi3: kotlin.Int, qn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), qn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), qn2: java.math.BigDecimal? = null, qn3: java.math.BigDecimal, hi0: kotlin.Int? = 10, hi1: kotlin.Int = 71, hi2: kotlin.Int? = null, hi3: kotlin.Int, hn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), hn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), hn2: java.math.BigDecimal? = null, hn3: java.math.BigDecimal, fi0: kotlin.Int? = 10, fi1: kotlin.Int = 71, fi2: kotlin.Int? = null, fi3: kotlin.Int, fn0: java.math.BigDecimal? = java.math.BigDecimal("10.0"), fn1: java.math.BigDecimal = java.math.BigDecimal("71.0"), fn2: java.math.BigDecimal? = null, fn3: java.math.BigDecimal, fn4: kotlin.collections.List): Unit { val body: Any? = null val contentTypes : Array = arrayOf("multipart/form-data") @@ -87,7 +88,8 @@ class DefaultApi ( "fn0" to IRequestFactory.parameterToString(fn0), "fn1" to IRequestFactory.parameterToString(fn1), "fn2" to IRequestFactory.parameterToString(fn2), - "fn3" to IRequestFactory.parameterToString(fn3) + "fn3" to IRequestFactory.parameterToString(fn3), + "fn4" to IRequestFactory.parameterToString(fn4) ) diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ITransformForStorage.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ITransformForStorage.kt index 973d1e9a32..d6383bf618 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ITransformForStorage.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/infrastructure/ITransformForStorage.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/Apa.kt index 1dee53e8eb..2e89541e50 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/Apa.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/Apa.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/room/ApaRoomModel.kt b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/room/ApaRoomModel.kt index b1ef4e8629..6af93efc58 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/room/ApaRoomModel.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-volley/src/main/kotlin/org/openapitools/client/models/room/ApaRoomModel.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/README.md b/samples/client/petstore/kotlin-default-values-multiplatform/README.md index a52e0a04a8..7bd76d9827 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/README.md +++ b/samples/client/petstore/kotlin-default-values-multiplatform/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Demo +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.5.10 diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-default-values-multiplatform/build.gradle.kts index 2380844aa9..219d79917c 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-default-values-multiplatform/build.gradle.kts @@ -8,10 +8,10 @@ plugins { group = "org.openapitools" version = "1.0.0" -val kotlin_version = "1.6.0" -val coroutines_version = "1.5.2" -val serialization_version = "1.3.0" -val ktor_version = "1.6.4" +val kotlin_version = "1.6.10" +val coroutines_version = "1.6.3" +val serialization_version = "1.3.3" +val ktor_version = "2.0.3" repositories { mavenCentral() @@ -30,9 +30,11 @@ kotlin { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") + api("io.ktor:ktor-client-core:$ktor_version") - api("io.ktor:ktor-client-json:$ktor_version") api("io.ktor:ktor-client-serialization:$ktor_version") + api("io.ktor:ktor-client-content-negotiation:$ktor_version") + api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") } } diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/docs/DefaultApi.md b/samples/client/petstore/kotlin-default-values-multiplatform/docs/DefaultApi.md index b299facd16..d163784e16 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/docs/DefaultApi.md +++ b/samples/client/petstore/kotlin-default-values-multiplatform/docs/DefaultApi.md @@ -9,7 +9,7 @@ Method | HTTP request | Description # **test** -> test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3) +> test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3, fn4) Tests default values @@ -50,8 +50,9 @@ val fn0 : kotlin.Double = 8.14 // kotlin.Double | val fn1 : kotlin.Double = 8.14 // kotlin.Double | val fn2 : kotlin.Double = 8.14 // kotlin.Double | val fn3 : kotlin.Double = 8.14 // kotlin.Double | +val fn4 : kotlin.collections.List = // kotlin.collections.List | try { - apiInstance.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3) + apiInstance.test(pi0, pi1, pn0, pn1, qi0, qi1, qi2, qi3, qn0, qn1, qn2, qn3, hi0, hi1, hi2, hi3, hn0, hn1, hn2, hn3, fi0, fi1, fi2, fi3, fn0, fn1, fn2, fn3, fn4) } catch (e: ClientException) { println("4xx response calling DefaultApi#test") e.printStackTrace() @@ -93,6 +94,7 @@ Name | Type | Description | Notes **fn1** | **kotlin.Double**| | [default to 71.0] **fn2** | **kotlin.Double**| | [optional] **fn3** | **kotlin.Double**| | + **fn4** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| | ### Return type diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonTest/kotlin/util/Coroutine.kt index 110762d355..4db267d629 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/iosTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/iosTest/kotlin/util/Coroutine.kt index 51f9803de3..e967e3993c 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/iosTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/iosTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt index 51f9803de3..e967e3993c 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index 6f47869c5a..d6be280d46 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -25,7 +20,6 @@ import org.openapitools.client.infrastructure.* import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json import io.ktor.http.ParametersBuilder import kotlinx.serialization.* @@ -70,9 +64,10 @@ open class DefaultApi( * @param fn1 (default to 71.0) * @param fn2 (optional) * @param fn3 + * @param fn4 * @return void */ - open suspend fun test(pi0: kotlin.Int = 10, pi1: kotlin.Int, pn0: kotlin.Double = 10.0.toDouble(), pn1: kotlin.Double, qi0: kotlin.Int? = 10, qi1: kotlin.Int = 71, qi2: kotlin.Int? = null, qi3: kotlin.Int, qn0: kotlin.Double? = 10.0.toDouble(), qn1: kotlin.Double = 71.0.toDouble(), qn2: kotlin.Double? = null, qn3: kotlin.Double, hi0: kotlin.Int? = 10, hi1: kotlin.Int = 71, hi2: kotlin.Int? = null, hi3: kotlin.Int, hn0: kotlin.Double? = 10.0.toDouble(), hn1: kotlin.Double = 71.0.toDouble(), hn2: kotlin.Double? = null, hn3: kotlin.Double, fi0: kotlin.Int? = 10, fi1: kotlin.Int = 71, fi2: kotlin.Int? = null, fi3: kotlin.Int, fn0: kotlin.Double? = 10.0.toDouble(), fn1: kotlin.Double = 71.0.toDouble(), fn2: kotlin.Double? = null, fn3: kotlin.Double): HttpResponse { + open suspend fun test(pi0: kotlin.Int = 10, pi1: kotlin.Int, pn0: kotlin.Double = 10.0.toDouble(), pn1: kotlin.Double, qi0: kotlin.Int? = 10, qi1: kotlin.Int = 71, qi2: kotlin.Int? = null, qi3: kotlin.Int, qn0: kotlin.Double? = 10.0.toDouble(), qn1: kotlin.Double = 71.0.toDouble(), qn2: kotlin.Double? = null, qn3: kotlin.Double, hi0: kotlin.Int? = 10, hi1: kotlin.Int = 71, hi2: kotlin.Int? = null, hi3: kotlin.Int, hn0: kotlin.Double? = 10.0.toDouble(), hn1: kotlin.Double = 71.0.toDouble(), hn2: kotlin.Double? = null, hn3: kotlin.Double, fi0: kotlin.Int? = 10, fi1: kotlin.Int = 71, fi2: kotlin.Int? = null, fi3: kotlin.Int, fn0: kotlin.Double? = 10.0.toDouble(), fn1: kotlin.Double = 71.0.toDouble(), fn2: kotlin.Double? = null, fn3: kotlin.Double, fn4: kotlin.collections.List): HttpResponse { val localVariableAuthNames = listOf() @@ -86,6 +81,7 @@ open class DefaultApi( fn1?.apply { append("fn1", fn1) } fn2?.apply { append("fn2", fn2) } fn3?.apply { append("fn3", fn3) } + fn4?.apply { append("fn4", fn4) } } val localVariableQuery = mutableMapOf>() diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 77dc28c814..fd07e4229d 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -3,43 +3,31 @@ package org.openapitools.client.infrastructure import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.JsonFeature -import io.ktor.client.features.json.JsonSerializer -import io.ktor.client.features.json.serializer.KotlinxSerializer +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.serialization.kotlinx.json.* import io.ktor.client.request.* import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse -import io.ktor.client.utils.EmptyContent import io.ktor.http.* -import io.ktor.http.content.OutgoingContent import io.ktor.http.content.PartData import kotlin.Unit import kotlinx.serialization.json.Json -import org.openapitools.client.apis.* -import org.openapitools.client.models.* import org.openapitools.client.auth.* open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - private val json: Json + private val jsonBlock: Json ) { - private val serializer: JsonSerializer by lazy { - KotlinxSerializer(json).ignoreOutgoingContent() - } - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { { - // Hold a reference to the serializer to avoid freezing the entire ApiClient instance - // when the JsonFeature is configured. - val serializerReference = serializer - it.install(JsonFeature) { serializer = serializerReference } + it.install(ContentNegotiation) { json(jsonBlock) } httpClientConfig?.invoke(it) } } @@ -52,7 +40,11 @@ open class ApiClient( companion object { const val BASE_URL = "http://localhost" - val JSON_DEFAULT = Json { ignoreUnknownKeys = true } + val JSON_DEFAULT = Json { + ignoreUnknownKeys = true + prettyPrint = true + isLenient = true + } protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) } @@ -132,18 +124,13 @@ open class ApiClient( return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) } - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } - ?: ContentType.Application.Json) - return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) - else request(requestConfig, authNames = authNames) - } + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.request { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -156,7 +143,7 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - this.body = body + this.setBody(body) } } @@ -182,14 +169,4 @@ open class ApiClient( RequestMethod.POST -> HttpMethod.Post RequestMethod.OPTIONS -> HttpMethod.Options } -} - -// https://github.com/ktorio/ktor/issues/851 -private fun JsonSerializer.ignoreOutgoingContent() = IgnoreOutgoingContentJsonSerializer(this) - -private class IgnoreOutgoingContentJsonSerializer(private val delegate: JsonSerializer) : JsonSerializer by delegate { - override fun write(data: Any): OutgoingContent { - if (data is OutgoingContent) return data - return delegate.write(data) - } -} +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt index 7d30ce18fc..0ff8578738 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -14,7 +14,7 @@ private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it private fun Int.toBase64(): Char = BASE64_ALPHABET[this] private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() -internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { writeStringUtf8(dropLastWhile { it == BASE64_PAD }) }.decodeBase64Bytes().readBytes() +internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { dropLastWhile { it == BASE64_PAD } }.decodeBase64Bytes().readBytes() /** * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt index 61e55bc5b1..4285d605ea 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -1,9 +1,9 @@ package org.openapitools.client.infrastructure -import io.ktor.client.call.TypeInfo -import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { val status: Int = response.status.value @@ -29,11 +29,11 @@ interface BodyProvider { class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { @Suppress("UNCHECKED_CAST") override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.receive(type) as T + response.call.body(type) as T @Suppress("UNCHECKED_CAST") override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.receive(type) as V + response.call.body(type) as V } class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt index 83fddb0070..d09beda60f 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/main/kotlin/org/openapitools/client/models/Apa.kt @@ -1,14 +1,9 @@ /** - * Demo - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-default-values-numbers/docs/ModelWithPropertyHavingDefault.md b/samples/client/petstore/kotlin-default-values-numbers/docs/ModelWithPropertyHavingDefault.md new file mode 100644 index 0000000000..0d41a58b19 --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-numbers/docs/ModelWithPropertyHavingDefault.md @@ -0,0 +1,17 @@ + +# ModelWithPropertyHavingDefault + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyInt** | **kotlin.Int** | | [optional] +**propertyLong** | **kotlin.Long** | | [optional] +**propertyFloat1** | **kotlin.Float** | | [optional] +**propertyFloat2** | **kotlin.Float** | | [optional] +**propertyFloat3** | **kotlin.Float** | | [optional] +**propertyDouble1** | **kotlin.Double** | | [optional] +**propertyDouble2** | **kotlin.Double** | | [optional] +**propertyDouble3** | **kotlin.Double** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-default-values-numbers/src/main/kotlin/org/openapitools/client/models/ModelWithPropertyHavingDefault.kt b/samples/client/petstore/kotlin-default-values-numbers/src/main/kotlin/org/openapitools/client/models/ModelWithPropertyHavingDefault.kt new file mode 100644 index 0000000000..5bba4b2acd --- /dev/null +++ b/samples/client/petstore/kotlin-default-values-numbers/src/main/kotlin/org/openapitools/client/models/ModelWithPropertyHavingDefault.kt @@ -0,0 +1,61 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param propertyInt + * @param propertyLong + * @param propertyFloat1 + * @param propertyFloat2 + * @param propertyFloat3 + * @param propertyDouble1 + * @param propertyDouble2 + * @param propertyDouble3 + */ + +data class ModelWithPropertyHavingDefault ( + + @SerializedName("propertyInt") + val propertyInt: kotlin.Int? = 0, + + @SerializedName("propertyLong") + val propertyLong: kotlin.Long? = 0L, + + @SerializedName("propertyFloat1") + val propertyFloat1: kotlin.Float? = 0f, + + @SerializedName("propertyFloat2") + val propertyFloat2: kotlin.Float? = 0.0f, + + @SerializedName("propertyFloat3") + val propertyFloat3: kotlin.Float? = 0.01f, + + @SerializedName("propertyDouble1") + val propertyDouble1: kotlin.Double? = 0.0, + + @SerializedName("propertyDouble2") + val propertyDouble2: kotlin.Double? = 0.0, + + @SerializedName("propertyDouble3") + val propertyDouble3: kotlin.Double? = 0.01 + +) + diff --git a/samples/client/petstore/kotlin-enum-default-value/README.md b/samples/client/petstore/kotlin-enum-default-value/README.md index 57d63266ef..df4685a202 100644 --- a/samples/client/petstore/kotlin-enum-default-value/README.md +++ b/samples/client/petstore/kotlin-enum-default-value/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for Issue 10591 Enum default value +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: latest +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-enum-default-value/build.gradle b/samples/client/petstore/kotlin-enum-default-value/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin-enum-default-value/build.gradle +++ b/samples/client/petstore/kotlin-enum-default-value/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index 28d8935251..e70279d32c 100644 --- a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -1,14 +1,9 @@ /** - * Issue 10591 Enum default value - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: latest - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelWithEnumPropertyHavingDefault @@ -116,4 +112,7 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index bfd00ac6a2..757080d7ed 100644 --- a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -145,7 +148,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -155,7 +158,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -163,16 +166,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/models/ModelWithEnumPropertyHavingDefault.kt b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/models/ModelWithEnumPropertyHavingDefault.kt index 16982beb88..6dc3db67b0 100644 --- a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/models/ModelWithEnumPropertyHavingDefault.kt +++ b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/models/ModelWithEnumPropertyHavingDefault.kt @@ -1,14 +1,9 @@ /** - * Issue 10591 Enum default value - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: latest - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-gson/README.md b/samples/client/petstore/kotlin-gson/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-gson/README.md +++ b/samples/client/petstore/kotlin-gson/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-gson/build.gradle b/samples/client/petstore/kotlin-gson/build.gradle index 5cad8581cb..205e3365af 100644 --- a/samples/client/petstore/kotlin-gson/build.gradle +++ b/samples/client/petstore/kotlin-gson/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -29,7 +29,7 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - implementation "com.google.code.gson:gson:2.8.7" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.google.code.gson:gson:2.9.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 63bbe32b4f..242cfabd72 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index f9fc75b285..ab07574dd3 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index df52c3c9b3..5a3088e0f2 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 17485b2c88..e983cd91a2 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -163,7 +166,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -173,7 +176,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -181,16 +184,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Category.kt index f9b43a4a71..50fff2dafc 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 773c82f431..f52e01cb0d 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Order.kt index b27ec5ecc1..8774e79d5c 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt index 7bcec4de92..1e11a67331 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Tag.kt index dbf125cb0b..e9443d15a4 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/User.kt index 631e09ec6b..6ee2fca147 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES b/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES index 34bf95b7ef..22d4e4fcce 100644 --- a/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES @@ -20,7 +20,6 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt diff --git a/samples/client/petstore/kotlin-jackson/README.md b/samples/client/petstore/kotlin-jackson/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-jackson/README.md +++ b/samples/client/petstore/kotlin-jackson/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-jackson/build.gradle b/samples/client/petstore/kotlin-jackson/build.gradle index 5cbe1fb014..e4d25c073c 100644 --- a/samples/client/petstore/kotlin-jackson/build.gradle +++ b/samples/client/petstore/kotlin-jackson/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.3" - implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.3" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.13.3" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.3" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index fd8229183a..2308fddead 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 404bb6024c..2e214e45f3 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 2d24c96c09..c7847514b1 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 5040c47697..18950f7e72 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -163,7 +166,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -173,7 +176,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -181,16 +184,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt index 6deb64d4d3..5f02a113b8 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index be6fc87dff..3ef775bc66 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt index 71200c0bbe..75055dc657 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt index bae9497a17..c7f0d70984 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt index cb7be4de18..591bb4230b 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/User.kt index 64042f583b..c079f8f167 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES index ab27444a31..4ed261ac1a 100644 --- a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES @@ -13,6 +13,7 @@ gradle/wrapper/gradle-wrapper.jar gradle/wrapper/gradle-wrapper.properties gradlew gradlew.bat +proguard-rules.pro settings.gradle src/main/kotlin/org/openapitools/client/apis/PetApi.kt src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -20,9 +21,11 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt +src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt -src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -32,7 +35,9 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/Category.kt src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt diff --git a/samples/client/petstore/kotlin-json-request-string/README.md b/samples/client/petstore/kotlin-json-request-string/README.md index 56bfbfeeb9..eb18a4c21d 100644 --- a/samples/client/petstore/kotlin-json-request-string/README.md +++ b/samples/client/petstore/kotlin-json-request-string/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-json-request-string/build.gradle b/samples/client/petstore/kotlin-json-request-string/build.gradle index 614bd17172..f495c77a74 100644 --- a/samples/client/petstore/kotlin-json-request-string/build.gradle +++ b/samples/client/petstore/kotlin-json-request-string/build.gradle @@ -2,23 +2,25 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" } } apply plugin: 'kotlin' apply plugin: 'kotlin-parcelize' +apply plugin: 'kotlinx-serialization' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,9 +32,13 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.3" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } + +tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { + kotlinOptions { + freeCompilerArgs += "-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi" + } +} diff --git a/samples/client/petstore/kotlin-json-request-string/proguard-rules.pro b/samples/client/petstore/kotlin-json-request-string/proguard-rules.pro new file mode 100644 index 0000000000..7c7b08bf38 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/proguard-rules.pro @@ -0,0 +1,11 @@ +-keepattributes *Annotation*, InnerClasses +-dontnote kotlinx.serialization.AnnotationsKt # core serialization annotations + +# kotlinx-serialization-json specific. Add this if you have java.lang.NoClassDefFoundError kotlinx.serialization.json.JsonObjectSerializer +-keepclassmembers class kotlinx.serialization.json.** { *** Companion; } +-keepclasseswithmembers class kotlinx.serialization.json.** { kotlinx.serialization.KSerializer serializer(...); } + +# project specific. +-keep,includedescriptorclasses class org.openapitools.client.models.**$$serializer { *; } +-keepclassmembers class org.openapitools.client.models.** { *** Companion; } +-keepclasseswithmembers class org.openapitools.client.models.** { kotlinx.serialization.KSerializer serializer(...); } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 4ae59dbd26..381b2f8f18 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,11 +17,13 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet -import com.squareup.moshi.Json +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.openapitools.client.infrastructure.ApiClient import org.openapitools.client.infrastructure.ApiResponse @@ -182,7 +179,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -405,7 +402,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -548,7 +545,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -626,11 +623,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index d192191c85..34e2b717f8 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,10 +17,12 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order -import com.squareup.moshi.Json +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.openapitools.client.infrastructure.ApiClient import org.openapitools.client.infrastructure.ApiResponse @@ -109,7 +106,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +243,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +320,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 327a69c8e7..e7f3e993e7 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,10 +17,12 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User -import com.squareup.moshi.Json +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.openapitools.client.infrastructure.ApiClient import org.openapitools.client.infrastructure.ApiResponse @@ -310,7 +307,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +377,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +588,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 804c66706c..e33a5625ae 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -28,7 +28,8 @@ import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime import java.util.Locale -import com.squareup.moshi.adapter +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.encodeToString open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { @@ -69,6 +70,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -76,22 +78,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -105,7 +109,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie if (content == null) { EMPTY_REQUEST } else { - Serializer.moshi.adapter(T::class.java).toJson(content) + Serializer.kotlinxSerializationJson.encodeToString(content) .toRequestBody((mediaType ?: JsonMediaType).toMediaTypeOrNull()) } mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.") @@ -113,7 +117,6 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.") } - @OptIn(ExperimentalStdlibApi::class) protected inline fun responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? { if(body == null) { return null @@ -140,7 +143,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } return when { mediaType==null || (mediaType.startsWith("application/") && mediaType.endsWith("json")) -> - Serializer.moshi.adapter().fromJson(bodyContent) + Serializer.kotlinxSerializationJson.decodeFromString(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } @@ -169,7 +172,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -179,7 +182,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -187,16 +190,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt new file mode 100644 index 0000000000..80611e349b --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt @@ -0,0 +1,21 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor +import java.util.concurrent.atomic.AtomicBoolean + +@Serializer(forClass = AtomicBoolean::class) +object AtomicBooleanAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: AtomicBoolean) { + encoder.encodeBoolean(value.get()) + } + + override fun deserialize(decoder: Decoder): AtomicBoolean = AtomicBoolean(decoder.decodeBoolean()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicBoolean", PrimitiveKind.BOOLEAN) +} diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt new file mode 100644 index 0000000000..8a5a8bafc7 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt @@ -0,0 +1,21 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor +import java.util.concurrent.atomic.AtomicInteger + +@Serializer(forClass = AtomicInteger::class) +object AtomicIntegerAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: AtomicInteger) { + encoder.encodeInt(value.get()) + } + + override fun deserialize(decoder: Decoder): AtomicInteger = AtomicInteger(decoder.decodeInt()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicInteger", PrimitiveKind.INT) +} diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt new file mode 100644 index 0000000000..5842c49088 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt @@ -0,0 +1,21 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor +import java.util.concurrent.atomic.AtomicLong + +@Serializer(forClass = AtomicLong::class) +object AtomicLongAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: AtomicLong) { + encoder.encodeLong(value.get()) + } + + override fun deserialize(decoder: Decoder): AtomicLong = AtomicLong(decoder.decodeLong()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicLong", PrimitiveKind.LONG) +} diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..94cbcb573a 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -1,17 +1,17 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.math.BigDecimal -class BigDecimalAdapter { - @ToJson - fun toJson(value: BigDecimal): String { - return value.toPlainString() - } - - @FromJson - fun fromJson(value: String): BigDecimal { - return BigDecimal(value) - } -} \ No newline at end of file +@Serializer(forClass = BigDecimal::class) +object BigDecimalAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING) + override fun deserialize(decoder: Decoder): BigDecimal = BigDecimal(decoder.decodeString()) + override fun serialize(encoder: Encoder, value: BigDecimal) = encoder.encodeString(value.toPlainString()) +} diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..8f0544aa2b 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -1,17 +1,22 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.math.BigInteger -class BigIntegerAdapter { - @ToJson - fun toJson(value: BigInteger): String { - return value.toString() +@Serializer(forClass = BigInteger::class) +object BigIntegerAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigInteger", PrimitiveKind.STRING) + override fun deserialize(decoder: Decoder): BigInteger { + return BigInteger(decoder.decodeString()) } - @FromJson - fun fromJson(value: String): BigInteger { - return BigInteger(value) + override fun serialize(encoder: Encoder, value: BigInteger) { + encoder.encodeString(value.toString()) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt deleted file mode 100644 index ff5e2a81ee..0000000000 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt +++ /dev/null @@ -1,12 +0,0 @@ -package org.openapitools.client.infrastructure - -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson - -class ByteArrayAdapter { - @ToJson - fun toJson(data: ByteArray): String = String(data) - - @FromJson - fun fromJson(data: String): ByteArray = data.toByteArray() -} diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt index b2e1654479..f7c632d696 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -1,19 +1,24 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.time.LocalDate import java.time.format.DateTimeFormatter -class LocalDateAdapter { - @ToJson - fun toJson(value: LocalDate): String { - return DateTimeFormatter.ISO_LOCAL_DATE.format(value) +@Serializer(forClass = LocalDate::class) +object LocalDateAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDate", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: LocalDate) { + encoder.encodeString(DateTimeFormatter.ISO_LOCAL_DATE.format(value)) } - @FromJson - fun fromJson(value: String): LocalDate { - return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) + override fun deserialize(decoder: Decoder): LocalDate { + return LocalDate.parse(decoder.decodeString(), DateTimeFormatter.ISO_LOCAL_DATE) } - } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt index e082db9481..88bd140113 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -1,19 +1,24 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.time.LocalDateTime import java.time.format.DateTimeFormatter -class LocalDateTimeAdapter { - @ToJson - fun toJson(value: LocalDateTime): String { - return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) +@Serializer(forClass = LocalDateTime::class) +object LocalDateTimeAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDateTime", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: LocalDateTime) { + encoder.encodeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value)) } - @FromJson - fun fromJson(value: String): LocalDateTime { - return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) + override fun deserialize(decoder: Decoder): LocalDateTime { + return LocalDateTime.parse(decoder.decodeString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME) } - } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt index 87437871a3..e0fe9e3b53 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -1,19 +1,24 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.time.OffsetDateTime import java.time.format.DateTimeFormatter -class OffsetDateTimeAdapter { - @ToJson - fun toJson(value: OffsetDateTime): String { - return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) +@Serializer(forClass = OffsetDateTime::class) +object OffsetDateTimeAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("OffsetDateTime", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: OffsetDateTime) { + encoder.encodeString(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value)) } - @FromJson - fun fromJson(value: String): OffsetDateTime { - return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + override fun deserialize(decoder: Decoder): OffsetDateTime { + return OffsetDateTime.parse(decoder.decodeString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME) } - } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index e22592e47d..82473d228a 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,23 +1,52 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.Moshi -import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +import java.math.BigDecimal +import java.math.BigInteger +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.OffsetDateTime +import java.util.UUID +import kotlinx.serialization.json.Json +import kotlinx.serialization.modules.SerializersModule +import java.net.URI +import java.net.URL +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong object Serializer { + @Deprecated("Use Serializer.kotlinxSerializationAdapters instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationAdapters")) @JvmStatic - val moshiBuilder: Moshi.Builder = Moshi.Builder() - .add(OffsetDateTimeAdapter()) - .add(LocalDateTimeAdapter()) - .add(LocalDateAdapter()) - .add(UUIDAdapter()) - .add(ByteArrayAdapter()) - .add(URIAdapter()) - .add(KotlinJsonAdapterFactory()) - .add(BigDecimalAdapter()) - .add(BigIntegerAdapter()) + val kotlinSerializationAdapters: SerializersModule + get() { return kotlinxSerializationAdapters } @JvmStatic - val moshi: Moshi by lazy { - moshiBuilder.build() + val kotlinxSerializationAdapters = SerializersModule { + contextual(BigDecimal::class, BigDecimalAdapter) + contextual(BigInteger::class, BigIntegerAdapter) + contextual(LocalDate::class, LocalDateAdapter) + contextual(LocalDateTime::class, LocalDateTimeAdapter) + contextual(OffsetDateTime::class, OffsetDateTimeAdapter) + contextual(UUID::class, UUIDAdapter) + contextual(AtomicInteger::class, AtomicIntegerAdapter) + contextual(AtomicLong::class, AtomicLongAdapter) + contextual(AtomicBoolean::class, AtomicBooleanAdapter) + contextual(URI::class, URIAdapter) + contextual(URL::class, URLAdapter) + contextual(StringBuilder::class, StringBuilderAdapter) + } + + @Deprecated("Use Serializer.kotlinxSerializationJson instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationJson")) + @JvmStatic + val jvmJson: Json + get() { return kotlinxSerializationJson } + + @JvmStatic + val kotlinxSerializationJson: Json by lazy { + Json { + serializersModule = kotlinxSerializationAdapters + ignoreUnknownKeys = true + isLenient = true + } } } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt new file mode 100644 index 0000000000..7a15749f06 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt @@ -0,0 +1,20 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor + +@Serializer(forClass = StringBuilder::class) +object StringBuilderAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: StringBuilder) { + encoder.encodeString(value.toString()) + } + + override fun deserialize(decoder: Decoder): StringBuilder = StringBuilder(decoder.decodeString()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("StringBuilder", PrimitiveKind.STRING) +} diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt index 927522757d..0856c99813 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -1,13 +1,21 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.net.URI -class URIAdapter { - @ToJson - fun toJson(uri: URI) = uri.toString() +@Serializer(forClass = URI::class) +object URIAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: URI) { + encoder.encodeString(value.toASCIIString()) + } - @FromJson - fun fromJson(s: String): URI = URI.create(s) + override fun deserialize(decoder: Decoder): URI = URI(decoder.decodeString()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URI", PrimitiveKind.STRING) } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt new file mode 100644 index 0000000000..0dead7a73f --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt @@ -0,0 +1,21 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor +import java.net.URL + +@Serializer(forClass = URL::class) +object URLAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: URL) { + encoder.encodeString(value.toExternalForm()) + } + + override fun deserialize(decoder: Decoder): URL = URL(decoder.decodeString()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URL", PrimitiveKind.STRING) +} diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index 7ccf7dc25d..fbae87c1a6 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -1,13 +1,23 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.util.UUID -class UUIDAdapter { - @ToJson - fun toJson(uuid: UUID) = uuid.toString() +@Serializer(forClass = UUID::class) +object UUIDAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING) - @FromJson - fun fromJson(s: String): UUID = UUID.fromString(s) + override fun serialize(encoder: Encoder, value: UUID) { + encoder.encodeString(value.toString()) + } + + override fun deserialize(decoder: Decoder): UUID { + return UUID.fromString(decoder.decodeString()) + } } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt index 51c35a061e..6a0d0a49a7 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -21,7 +16,14 @@ package org.openapitools.client.models -import com.squareup.moshi.Json +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder import android.os.Parcelable import kotlinx.parcelize.Parcelize @@ -32,13 +34,13 @@ import kotlinx.parcelize.Parcelize * @param name */ @Parcelize - +@Serializable data class Category ( - @Json(name = "id") + @SerialName(value = "id") val id: kotlin.Long? = null, - @Json(name = "name") + @SerialName(value = "name") val name: kotlin.String? = null ) : Parcelable diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 61b35faee8..196cda362e 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -21,7 +16,14 @@ package org.openapitools.client.models -import com.squareup.moshi.Json +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder import android.os.Parcelable import kotlinx.parcelize.Parcelize @@ -33,16 +35,16 @@ import kotlinx.parcelize.Parcelize * @param message */ @Parcelize - +@Serializable data class ModelApiResponse ( - @Json(name = "code") + @SerialName(value = "code") val code: kotlin.Int? = null, - @Json(name = "type") + @SerialName(value = "type") val type: kotlin.String? = null, - @Json(name = "message") + @SerialName(value = "message") val message: kotlin.String? = null ) : Parcelable diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt index e2bfdd701d..6910263b8c 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -21,7 +16,14 @@ package org.openapitools.client.models -import com.squareup.moshi.Json +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder import android.os.Parcelable import kotlinx.parcelize.Parcelize @@ -36,26 +38,26 @@ import kotlinx.parcelize.Parcelize * @param complete */ @Parcelize - +@Serializable data class Order ( - @Json(name = "id") + @SerialName(value = "id") val id: kotlin.Long? = null, - @Json(name = "petId") + @SerialName(value = "petId") val petId: kotlin.Long? = null, - @Json(name = "quantity") + @SerialName(value = "quantity") val quantity: kotlin.Int? = null, - @Json(name = "shipDate") + @Contextual @SerialName(value = "shipDate") val shipDate: java.time.OffsetDateTime? = null, /* Order Status */ - @Json(name = "status") + @SerialName(value = "status") val status: Order.Status? = null, - @Json(name = "complete") + @SerialName(value = "complete") val complete: kotlin.Boolean? = false ) : Parcelable { @@ -63,12 +65,29 @@ data class Order ( /** * Order Status * - * Values: placed,approved,delivered + * Values: placed,approved,delivered,unknownDefaultOpenApi */ + @Serializable(with = OrderSerializer::class) enum class Status(val value: kotlin.String) { - @Json(name = "placed") placed("placed"), - @Json(name = "approved") approved("approved"), - @Json(name = "delivered") delivered("delivered"); + @SerialName(value = "placed") placed("placed"), + @SerialName(value = "approved") approved("approved"), + @SerialName(value = "delivered") delivered("delivered"), + @SerialName(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + } + + @Serializer(forClass = Status::class) + internal object StatusSerializer : KSerializer { + override val descriptor = kotlin.String.serializer().descriptor + + override fun deserialize(decoder: Decoder): Status { + val value = decoder.decodeSerializableValue(kotlin.String.serializer()) + return Status.values().firstOrNull { it.value == value } + ?: Status.unknownDefaultOpenApi + } + + override fun serialize(encoder: Encoder, value: Status) { + encoder.encodeSerializableValue(kotlin.String.serializer(), value.value) + } } } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt index 6ff38c8e0d..8922075ac9 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -23,7 +18,14 @@ package org.openapitools.client.models import org.openapitools.client.models.Category import org.openapitools.client.models.Tag -import com.squareup.moshi.Json +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder import android.os.Parcelable import kotlinx.parcelize.Parcelize @@ -38,26 +40,26 @@ import kotlinx.parcelize.Parcelize * @param status pet status in the store */ @Parcelize - +@Serializable data class Pet ( - @Json(name = "name") + @SerialName(value = "name") val name: kotlin.String, - @Json(name = "photoUrls") + @SerialName(value = "photoUrls") val photoUrls: kotlin.collections.List, - @Json(name = "id") + @SerialName(value = "id") val id: kotlin.Long? = null, - @Json(name = "category") + @SerialName(value = "category") val category: Category? = null, - @Json(name = "tags") + @SerialName(value = "tags") val tags: kotlin.collections.List? = null, /* pet status in the store */ - @Json(name = "status") + @SerialName(value = "status") val status: Pet.Status? = null ) : Parcelable { @@ -65,12 +67,29 @@ data class Pet ( /** * pet status in the store * - * Values: available,pending,sold + * Values: available,pending,sold,unknownDefaultOpenApi */ + @Serializable(with = PetSerializer::class) enum class Status(val value: kotlin.String) { - @Json(name = "available") available("available"), - @Json(name = "pending") pending("pending"), - @Json(name = "sold") sold("sold"); + @SerialName(value = "available") available("available"), + @SerialName(value = "pending") pending("pending"), + @SerialName(value = "sold") sold("sold"), + @SerialName(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + } + + @Serializer(forClass = Status::class) + internal object StatusSerializer : KSerializer { + override val descriptor = kotlin.String.serializer().descriptor + + override fun deserialize(decoder: Decoder): Status { + val value = decoder.decodeSerializableValue(kotlin.String.serializer()) + return Status.values().firstOrNull { it.value == value } + ?: Status.unknownDefaultOpenApi + } + + override fun serialize(encoder: Encoder, value: Status) { + encoder.encodeSerializableValue(kotlin.String.serializer(), value.value) + } } } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt index 18421bb3ac..34beab9831 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -21,7 +16,14 @@ package org.openapitools.client.models -import com.squareup.moshi.Json +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder import android.os.Parcelable import kotlinx.parcelize.Parcelize @@ -32,13 +34,13 @@ import kotlinx.parcelize.Parcelize * @param name */ @Parcelize - +@Serializable data class Tag ( - @Json(name = "id") + @SerialName(value = "id") val id: kotlin.Long? = null, - @Json(name = "name") + @SerialName(value = "name") val name: kotlin.String? = null ) : Parcelable diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt index 22889800c0..3b2b060502 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -21,7 +16,14 @@ package org.openapitools.client.models -import com.squareup.moshi.Json +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder import android.os.Parcelable import kotlinx.parcelize.Parcelize @@ -38,32 +40,32 @@ import kotlinx.parcelize.Parcelize * @param userStatus User Status */ @Parcelize - +@Serializable data class User ( - @Json(name = "id") + @SerialName(value = "id") val id: kotlin.Long? = null, - @Json(name = "username") + @SerialName(value = "username") val username: kotlin.String? = null, - @Json(name = "firstName") + @SerialName(value = "firstName") val firstName: kotlin.String? = null, - @Json(name = "lastName") + @SerialName(value = "lastName") val lastName: kotlin.String? = null, - @Json(name = "email") + @SerialName(value = "email") val email: kotlin.String? = null, - @Json(name = "password") + @SerialName(value = "password") val password: kotlin.String? = null, - @Json(name = "phone") + @SerialName(value = "phone") val phone: kotlin.String? = null, /* User Status */ - @Json(name = "userStatus") + @SerialName(value = "userStatus") val userStatus: kotlin.Int? = null ) : Parcelable diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/README.md b/samples/client/petstore/kotlin-jvm-ktor-gson/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/README.md +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/build.gradle b/samples/client/petstore/kotlin-jvm-ktor-gson/build.gradle index 70cfaf2c98..0c3e6b64c9 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/build.gradle +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/build.gradle @@ -2,13 +2,13 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' - ext.ktor_version = '1.6.7' + ext.kotlin_version = '1.6.10' + ext.ktor_version = '2.0.3' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,10 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - implementation "com.google.code.gson:gson:2.8.7" + implementation "com.google.code.gson:gson:2.9.0" implementation "io.ktor:ktor-client-core:$ktor_version" + implementation "io.ktor:ktor-client-content-negotiation:$ktor_version" + implementation "io.ktor:ktor-serialization-gson:$ktor_version" implementation "io.ktor:ktor-client-gson:$ktor_version" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 16778dcd2a..6469b50b46 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -28,15 +23,16 @@ import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.http.ParametersBuilder - import com.google.gson.Gson +import com.google.gson.GsonBuilder +import java.text.DateFormat open class PetApi( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: Gson = ApiClient.JSON_DEFAULT, - ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, json) { + jsonBlock: GsonBuilder.() -> Unit = ApiClient.JSON_DEFAULT, + ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonBlock) { /** * Add a new pet to the store diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 4d6c90ef30..8360878da1 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -27,15 +22,16 @@ import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.http.ParametersBuilder - import com.google.gson.Gson +import com.google.gson.GsonBuilder +import java.text.DateFormat open class StoreApi( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: Gson = ApiClient.JSON_DEFAULT, - ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, json) { + jsonBlock: GsonBuilder.() -> Unit = ApiClient.JSON_DEFAULT, + ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonBlock) { /** * Delete purchase order by ID diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index df39222326..b28ac18547 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -27,15 +22,16 @@ import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.http.ParametersBuilder - import com.google.gson.Gson +import com.google.gson.GsonBuilder +import java.text.DateFormat open class UserApi( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: Gson = ApiClient.JSON_DEFAULT, - ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, json) { + jsonBlock: GsonBuilder.() -> Unit = ApiClient.JSON_DEFAULT, + ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonBlock) { /** * Create user diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 8a23111a84..5d6fc3af68 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,45 +1,47 @@ package org.openapitools.client.infrastructure + import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.JsonFeature -import io.ktor.client.features.json.JsonSerializer -import io.ktor.client.request.* +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter +import io.ktor.client.request.request +import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse -import io.ktor.client.utils.EmptyContent -import io.ktor.http.* -import io.ktor.http.content.ByteArrayContent -import io.ktor.http.content.OutgoingContent +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpMethod +import io.ktor.http.Parameters +import io.ktor.http.URLBuilder import io.ktor.http.content.PartData -import kotlin.Unit - -import com.google.gson.Gson -import java.nio.charset.StandardCharsets - +import io.ktor.http.encodeURLQueryComponent +import io.ktor.http.encodedPath +import io.ktor.http.takeFrom +import io.ktor.serialization.gson.* +import com.google.gson.GsonBuilder +import java.text.DateFormat +import org.openapitools.client.auth.ApiKeyAuth +import org.openapitools.client.auth.Authentication +import org.openapitools.client.auth.HttpBasicAuth +import org.openapitools.client.auth.HttpBearerAuth +import org.openapitools.client.auth.OAuth import org.openapitools.client.auth.* open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: Gson, + jsonBlock: GsonBuilder.() -> Unit = JSON_DEFAULT, ) { - private val serializer: JsonSerializer by lazy { - JsonSerializerImpl(json) - } - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { { - // Hold a reference to the serializer to avoid freezing the entire ApiClient instance - // when the JsonFeature is configured. - val serializerReference = serializer - it.install(JsonFeature) { serializer = serializerReference } + it.install(ContentNegotiation) { + gson { jsonBlock() } + } httpClientConfig?.invoke(it) } } @@ -55,9 +57,12 @@ open class ApiClient( } companion object { - const val BASE_URL = "http://petstore.swagger.io/v2" - val JSON_DEFAULT = Gson() - protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) + const val BASE_URL = "http://petstore.swagger.io/v2" + val JSON_DEFAULT : GsonBuilder.() -> Unit = { + setDateFormat(DateFormat.LONG) + setPrettyPrinting() + } + protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) } /** @@ -66,7 +71,7 @@ open class ApiClient( * @param username Username */ fun setUsername(username: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? ?: throw Exception("No HTTP basic authentication configured") auth.username = username } @@ -77,7 +82,7 @@ open class ApiClient( * @param password Password */ fun setPassword(password: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? ?: throw Exception("No HTTP basic authentication configured") auth.password = password } @@ -89,7 +94,7 @@ open class ApiClient( * @param paramName The name of the API key parameter, or null or set the first key. */ fun setApiKey(apiKey: String, paramName: String? = null) { - val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? + val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? ?: throw Exception("No API key authentication configured") auth.apiKey = apiKey } @@ -101,7 +106,7 @@ open class ApiClient( * @param paramName The name of the API key parameter, or null or set the first key. */ fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) { - val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? + val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? ?: throw Exception("No API key authentication configured") auth.apiKeyPrefix = apiKeyPrefix } @@ -112,7 +117,7 @@ open class ApiClient( * @param accessToken Access token */ fun setAccessToken(accessToken: String) { - val auth = authentications?.values?.firstOrNull { it is OAuth } as OAuth? + val auth = authentications.values.firstOrNull { it is OAuth } as OAuth? ?: throw Exception("No OAuth2 authentication configured") auth.accessToken = accessToken } @@ -123,7 +128,7 @@ open class ApiClient( * @param bearerToken The bearer token. */ fun setBearerToken(bearerToken: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? + val auth = authentications.values.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? ?: throw Exception("No Bearer authentication configured") auth.bearerToken = bearerToken } @@ -136,18 +141,13 @@ open class ApiClient( return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) } - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } - ?: ContentType.Application.Json) - return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) - else request(requestConfig, authNames = authNames) - } + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.request { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -160,8 +160,7 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - this.body = body - + setBody(body) } } @@ -187,10 +186,3 @@ open class ApiClient( RequestMethod.OPTIONS -> HttpMethod.Options } } - -private class JsonSerializerImpl(private val gson: Gson) : JsonSerializer { - override fun write(data: Any, contentType: ContentType): OutgoingContent = - ByteArrayContent(gson.toJson(data).toByteArray(StandardCharsets.UTF_8), contentType) -} - - diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt index 61e55bc5b1..4285d605ea 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -1,9 +1,9 @@ package org.openapitools.client.infrastructure -import io.ktor.client.call.TypeInfo -import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { val status: Int = response.status.value @@ -29,11 +29,11 @@ interface BodyProvider { class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { @Suppress("UNCHECKED_CAST") override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.receive(type) as T + response.call.body(type) as T @Suppress("UNCHECKED_CAST") override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.receive(type) as V + response.call.body(type) as V } class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Category.kt index f9b43a4a71..50fff2dafc 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 773c82f431..f52e01cb0d 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Order.kt index 7f91c458f9..5d9240bc46 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt index 8b9a0d0d14..2a7be8be76 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Tag.kt index dbf125cb0b..e9443d15a4 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/User.kt index 631e09ec6b..6ee2fca147 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/README.md b/samples/client/petstore/kotlin-jvm-ktor-jackson/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/README.md +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/build.gradle b/samples/client/petstore/kotlin-jvm-ktor-jackson/build.gradle index a9de22fdf1..febcd440b1 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/build.gradle +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/build.gradle @@ -2,13 +2,13 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' - ext.ktor_version = '1.6.7' + ext.kotlin_version = '1.6.10' + ext.ktor_version = '2.0.3' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -31,9 +31,11 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.3" - implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.3" + implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.13.3" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.3" implementation "io.ktor:ktor-client-core:$ktor_version" + implementation "io.ktor:ktor-client-content-negotiation:$ktor_version" implementation "io.ktor:ktor-client-jackson:$ktor_version" + implementation "io.ktor:ktor-serialization-jackson:$ktor_version" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index f1ae54f274..88a8d0e448 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -28,15 +23,14 @@ import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.http.ParametersBuilder - import com.fasterxml.jackson.databind.ObjectMapper open class PetApi( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: ObjectMapper = ApiClient.JSON_DEFAULT, - ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, json) { + jsonBlock: ObjectMapper.() -> Unit = ApiClient.JSON_DEFAULT, + ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonBlock) { /** * Add a new pet to the store diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 17f13b366c..f6dd67c8b0 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -27,15 +22,14 @@ import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.http.ParametersBuilder - import com.fasterxml.jackson.databind.ObjectMapper open class StoreApi( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: ObjectMapper = ApiClient.JSON_DEFAULT, - ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, json) { + jsonBlock: ObjectMapper.() -> Unit = ApiClient.JSON_DEFAULT, + ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonBlock) { /** * Delete purchase order by ID diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index b65926f5fc..f1c146e27c 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -27,15 +22,14 @@ import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.http.ParametersBuilder - import com.fasterxml.jackson.databind.ObjectMapper open class UserApi( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: ObjectMapper = ApiClient.JSON_DEFAULT, - ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, json) { + jsonBlock: ObjectMapper.() -> Unit = ApiClient.JSON_DEFAULT, + ) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonBlock) { /** * Create user diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index f492c6e881..e21bccb906 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,44 +1,51 @@ package org.openapitools.client.infrastructure + import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.JsonFeature -import io.ktor.client.features.json.JsonSerializer -import io.ktor.client.request.* +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter +import io.ktor.client.request.request +import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse -import io.ktor.client.utils.EmptyContent -import io.ktor.http.* -import io.ktor.http.content.ByteArrayContent -import io.ktor.http.content.OutgoingContent +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpMethod +import io.ktor.http.Parameters +import io.ktor.http.URLBuilder import io.ktor.http.content.PartData -import kotlin.Unit - +import io.ktor.http.encodeURLQueryComponent +import io.ktor.http.encodedPath +import io.ktor.http.takeFrom +import io.ktor.serialization.jackson.* +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.databind.ObjectMapper - +import com.fasterxml.jackson.databind.SerializationFeature +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule +import com.fasterxml.jackson.core.util.DefaultIndenter +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter +import org.openapitools.client.auth.ApiKeyAuth +import org.openapitools.client.auth.Authentication +import org.openapitools.client.auth.HttpBasicAuth +import org.openapitools.client.auth.HttpBearerAuth +import org.openapitools.client.auth.OAuth import org.openapitools.client.auth.* open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - json: ObjectMapper, + jsonBlock: ObjectMapper.() -> Unit = JSON_DEFAULT, ) { - private val serializer: JsonSerializer by lazy { - JsonSerializerImpl(json) - } - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { { - // Hold a reference to the serializer to avoid freezing the entire ApiClient instance - // when the JsonFeature is configured. - val serializerReference = serializer - it.install(JsonFeature) { serializer = serializerReference } + it.install(ContentNegotiation) { + jackson { jsonBlock() } + } httpClientConfig?.invoke(it) } } @@ -54,9 +61,16 @@ open class ApiClient( } companion object { - const val BASE_URL = "http://petstore.swagger.io/v2" - val JSON_DEFAULT = ObjectMapper() - protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) + const val BASE_URL = "http://petstore.swagger.io/v2" + val JSON_DEFAULT: ObjectMapper.() -> Unit = { + configure(SerializationFeature.INDENT_OUTPUT, true) + setDefaultPrettyPrinter(DefaultPrettyPrinter().apply { + indentArraysWith(DefaultPrettyPrinter.FixedSpaceIndenter.instance) + indentObjectsWith(DefaultIndenter(" ", "\n")) + }) + registerModule(JavaTimeModule()) + } + protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) } /** @@ -65,7 +79,7 @@ open class ApiClient( * @param username Username */ fun setUsername(username: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? ?: throw Exception("No HTTP basic authentication configured") auth.username = username } @@ -76,7 +90,7 @@ open class ApiClient( * @param password Password */ fun setPassword(password: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? ?: throw Exception("No HTTP basic authentication configured") auth.password = password } @@ -88,7 +102,7 @@ open class ApiClient( * @param paramName The name of the API key parameter, or null or set the first key. */ fun setApiKey(apiKey: String, paramName: String? = null) { - val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? + val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? ?: throw Exception("No API key authentication configured") auth.apiKey = apiKey } @@ -100,7 +114,7 @@ open class ApiClient( * @param paramName The name of the API key parameter, or null or set the first key. */ fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) { - val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? + val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? ?: throw Exception("No API key authentication configured") auth.apiKeyPrefix = apiKeyPrefix } @@ -111,7 +125,7 @@ open class ApiClient( * @param accessToken Access token */ fun setAccessToken(accessToken: String) { - val auth = authentications?.values?.firstOrNull { it is OAuth } as OAuth? + val auth = authentications.values.firstOrNull { it is OAuth } as OAuth? ?: throw Exception("No OAuth2 authentication configured") auth.accessToken = accessToken } @@ -122,7 +136,7 @@ open class ApiClient( * @param bearerToken The bearer token. */ fun setBearerToken(bearerToken: String) { - val auth = authentications?.values?.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? + val auth = authentications.values.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? ?: throw Exception("No Bearer authentication configured") auth.bearerToken = bearerToken } @@ -135,18 +149,13 @@ open class ApiClient( return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) } - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } - ?: ContentType.Application.Json) - return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) - else request(requestConfig, authNames = authNames) - } + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.request { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -159,8 +168,7 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - this.body = body - + setBody(body) } } @@ -186,10 +194,3 @@ open class ApiClient( RequestMethod.OPTIONS -> HttpMethod.Options } } - - - -private class JsonSerializerImpl(private val objectMapper: ObjectMapper) : JsonSerializer { - override fun write(data: Any, contentType: ContentType): OutgoingContent = - ByteArrayContent(objectMapper.writeValueAsBytes(data), contentType) -} diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt index 61e55bc5b1..4285d605ea 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -1,9 +1,9 @@ package org.openapitools.client.infrastructure -import io.ktor.client.call.TypeInfo -import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { val status: Int = response.status.value @@ -29,11 +29,11 @@ interface BodyProvider { class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { @Suppress("UNCHECKED_CAST") override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.receive(type) as T + response.call.body(type) as T @Suppress("UNCHECKED_CAST") override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.receive(type) as V + response.call.body(type) as V } class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt index 6deb64d4d3..5f02a113b8 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index be6fc87dff..3ef775bc66 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt index 0b2a583f5d..fbb813a47e 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt index 3aa3afac36..e1e53044dd 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt index cb7be4de18..591bb4230b 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/User.kt index 64042f583b..c079f8f167 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/README.md b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/README.md +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle index 70d79ab693..410fce57b4 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -29,8 +29,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1" - implementation "com.google.code.gson:gson:2.8.7" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.3" + implementation "com.google.code.gson:gson:2.9.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 81fdbed46a..eecb37205f 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -184,7 +180,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -414,7 +410,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -557,7 +553,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -635,11 +631,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 51255cd2a5..4bc01ba927 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -111,7 +107,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -248,7 +244,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -325,4 +321,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 834bbe6f81..0df9761bc9 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -312,7 +308,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -382,7 +378,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -593,11 +589,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index cacd2b743b..d7c20c5f81 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -71,6 +71,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -78,22 +79,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -166,7 +169,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -176,7 +179,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -184,16 +187,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Category.kt index c2c611fdbe..efdde72015 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 16e2038ba9..70862a29ee 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Order.kt index 36871a90e4..49274482e4 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Pet.kt index e5732a1f24..2abf3d44e9 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Tag.kt index f39d14831a..30a782898d 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/User.kt index 6f5e04a7bc..336d9f4f98 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ITransformForStorage.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ITransformForStorage.kt index 21e96af43d..d6383bf618 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ITransformForStorage.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/infrastructure/ITransformForStorage.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Category.kt index 8bd167529e..c1dcccb58b 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/ModelApiResponse.kt index 9f81f502ed..625e71c9d8 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Order.kt index cb48557cd2..a2e6db7f0f 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Pet.kt index 83edfb9c4f..0399733505 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Tag.kt index 03dcdbbaf0..206ba2eb22 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/User.kt index c35a2df394..a0d3ee5372 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/CategoryRoomModel.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/CategoryRoomModel.kt index 896589516a..dd20e53b07 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/CategoryRoomModel.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/CategoryRoomModel.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/ModelApiResponseRoomModel.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/ModelApiResponseRoomModel.kt index 87c2114349..904313c485 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/ModelApiResponseRoomModel.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/ModelApiResponseRoomModel.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/OrderRoomModel.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/OrderRoomModel.kt index 5367a0e354..4291614f24 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/OrderRoomModel.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/OrderRoomModel.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/PetRoomModel.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/PetRoomModel.kt index 81296bb2f9..2bfb6cf64a 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/PetRoomModel.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/PetRoomModel.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/TagRoomModel.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/TagRoomModel.kt index 42f255a11f..228a464d2b 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/TagRoomModel.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/TagRoomModel.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/UserRoomModel.kt b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/UserRoomModel.kt index f0c067fc19..20fb81c2e8 100644 --- a/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/UserRoomModel.kt +++ b/samples/client/petstore/kotlin-jvm-volley/src/main/java/org/openapitools/client/models/room/UserRoomModel.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-modelMutable/README.md b/samples/client/petstore/kotlin-modelMutable/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-modelMutable/README.md +++ b/samples/client/petstore/kotlin-modelMutable/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-modelMutable/build.gradle b/samples/client/petstore/kotlin-modelMutable/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin-modelMutable/build.gradle +++ b/samples/client/petstore/kotlin-modelMutable/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index bc6cf14b7e..58787a00f5 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 2fc4f74b3d..20bc7f914c 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index c75da6a2b4..652c44082b 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 4ad22a02df..fd43ff24fe 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -164,7 +167,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -174,7 +177,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -182,16 +185,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Category.kt index d523c462f5..a1bee507cc 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 217f50ea51..7869a81585 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Order.kt index 8a909313ac..75d6dc52fa 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Pet.kt index 680acc7c0f..9bace47c42 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Tag.kt index fb38d26671..d52e127012 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/User.kt index 983c8f75f3..5c87172568 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-moshi-codegen/README.md b/samples/client/petstore/kotlin-moshi-codegen/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/README.md +++ b/samples/client/petstore/kotlin-moshi-codegen/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-moshi-codegen/build.gradle b/samples/client/petstore/kotlin-moshi-codegen/build.gradle index 7e8fe4d903..1f5a719c9d 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/build.gradle +++ b/samples/client/petstore/kotlin-moshi-codegen/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,9 +30,9 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - implementation "com.squareup.moshi:moshi:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + kapt "com.squareup.moshi:moshi-kotlin-codegen:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index e0d26a4ae3..9b1451613f 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index d192191c85..ca473d06df 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 327a69c8e7..720713cafe 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 4ad22a02df..fd43ff24fe 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -164,7 +167,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -174,7 +177,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -182,16 +185,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Category.kt index 60e6efed3b..3d1ca0a7f2 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 1921982e78..0fbbf5e5e0 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Order.kt index 1cb16202c6..b2d33f85be 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Pet.kt index 3da7fac874..f7f118762e 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Tag.kt index c64e4efbed..b62aca125b 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/User.kt index 59c0398042..709983e041 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-multiplatform/README.md b/samples/client/petstore/kotlin-multiplatform/README.md index 0e965d57d6..923b987751 100644 --- a/samples/client/petstore/kotlin-multiplatform/README.md +++ b/samples/client/petstore/kotlin-multiplatform/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.5.10 diff --git a/samples/client/petstore/kotlin-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts index 2380844aa9..219d79917c 100644 --- a/samples/client/petstore/kotlin-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts @@ -8,10 +8,10 @@ plugins { group = "org.openapitools" version = "1.0.0" -val kotlin_version = "1.6.0" -val coroutines_version = "1.5.2" -val serialization_version = "1.3.0" -val ktor_version = "1.6.4" +val kotlin_version = "1.6.10" +val coroutines_version = "1.6.3" +val serialization_version = "1.3.3" +val ktor_version = "2.0.3" repositories { mavenCentral() @@ -30,9 +30,11 @@ kotlin { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") + api("io.ktor:ktor-client-core:$ktor_version") - api("io.ktor:ktor-client-json:$ktor_version") api("io.ktor:ktor-client-serialization:$ktor_version") + api("io.ktor:ktor-client-content-negotiation:$ktor_version") + api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") } } diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt index 5bfd90fd04..86948b0d6c 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -27,7 +22,6 @@ import org.openapitools.client.infrastructure.* import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json import io.ktor.http.ParametersBuilder import kotlinx.serialization.* diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt index 1e3de76952..c335f9512e 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -26,7 +21,6 @@ import org.openapitools.client.infrastructure.* import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json import io.ktor.http.ParametersBuilder import kotlinx.serialization.* diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt index f1c1dc2e5f..53fee9660b 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -26,7 +21,6 @@ import org.openapitools.client.infrastructure.* import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json import io.ktor.http.ParametersBuilder import kotlinx.serialization.* diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index a6ec2640af..dc66073419 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -3,43 +3,31 @@ package org.openapitools.client.infrastructure import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine -import io.ktor.client.features.json.JsonFeature -import io.ktor.client.features.json.JsonSerializer -import io.ktor.client.features.json.serializer.KotlinxSerializer +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.serialization.kotlinx.json.* import io.ktor.client.request.* import io.ktor.client.request.forms.FormDataContent import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse -import io.ktor.client.utils.EmptyContent import io.ktor.http.* -import io.ktor.http.content.OutgoingContent import io.ktor.http.content.PartData import kotlin.Unit import kotlinx.serialization.json.Json -import org.openapitools.client.apis.* -import org.openapitools.client.models.* import org.openapitools.client.auth.* open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, - private val json: Json + private val jsonBlock: Json ) { - private val serializer: JsonSerializer by lazy { - KotlinxSerializer(json).ignoreOutgoingContent() - } - private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { { - // Hold a reference to the serializer to avoid freezing the entire ApiClient instance - // when the JsonFeature is configured. - val serializerReference = serializer - it.install(JsonFeature) { serializer = serializerReference } + it.install(ContentNegotiation) { json(jsonBlock) } httpClientConfig?.invoke(it) } } @@ -56,7 +44,11 @@ open class ApiClient( companion object { const val BASE_URL = "http://petstore.swagger.io/v2" - val JSON_DEFAULT = Json { ignoreUnknownKeys = true } + val JSON_DEFAULT = Json { + ignoreUnknownKeys = true + prettyPrint = true + isLenient = true + } protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) } @@ -136,18 +128,13 @@ open class ApiClient( return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) } - protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { - val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } - ?: ContentType.Application.Json) - return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) - else request(requestConfig, authNames = authNames) - } + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.request { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -160,7 +147,7 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) - this.body = body + this.setBody(body) } } @@ -186,14 +173,4 @@ open class ApiClient( RequestMethod.POST -> HttpMethod.Post RequestMethod.OPTIONS -> HttpMethod.Options } -} - -// https://github.com/ktorio/ktor/issues/851 -private fun JsonSerializer.ignoreOutgoingContent() = IgnoreOutgoingContentJsonSerializer(this) - -private class IgnoreOutgoingContentJsonSerializer(private val delegate: JsonSerializer) : JsonSerializer by delegate { - override fun write(data: Any): OutgoingContent { - if (data is OutgoingContent) return data - return delegate.write(data) - } -} +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt index 7d30ce18fc..0ff8578738 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -14,7 +14,7 @@ private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it private fun Int.toBase64(): Char = BASE64_ALPHABET[this] private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() -internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { writeStringUtf8(dropLastWhile { it == BASE64_PAD }) }.decodeBase64Bytes().readBytes() +internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { dropLastWhile { it == BASE64_PAD } }.decodeBase64Bytes().readBytes() /** * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt index 61e55bc5b1..4285d605ea 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -1,9 +1,9 @@ package org.openapitools.client.infrastructure -import io.ktor.client.call.TypeInfo -import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { val status: Int = response.status.value @@ -29,11 +29,11 @@ interface BodyProvider { class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { @Suppress("UNCHECKED_CAST") override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = - response.call.receive(type) as T + response.call.body(type) as T @Suppress("UNCHECKED_CAST") override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = - response.call.receive(type) as V + response.call.body(type) as V } class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Category.kt index a13ef95df0..cadfa02396 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 614529156e..babd717df4 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Order.kt index 80db3efc71..1fb838bc80 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt index acc9ed19e3..e9768bd013 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt index fa092c9656..d7edf1d61e 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/User.kt index 5c5b18c0d0..346113de5d 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-multiplatform/src/commonTest/kotlin/util/Coroutine.kt index d7f388f67d..4db267d629 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-multiplatform/src/iosTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-multiplatform/src/iosTest/kotlin/util/Coroutine.kt index 2ddea12d6a..e967e3993c 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/iosTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/iosTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt index 2ddea12d6a..e967e3993c 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/jvmTest/kotlin/util/Coroutine.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nonpublic/README.md b/samples/client/petstore/kotlin-nonpublic/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-nonpublic/README.md +++ b/samples/client/petstore/kotlin-nonpublic/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-nonpublic/build.gradle b/samples/client/petstore/kotlin-nonpublic/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin-nonpublic/build.gradle +++ b/samples/client/petstore/kotlin-nonpublic/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index ca615c5e8e..72a5ce749c 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpC return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpC return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpC return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpC return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index fef010230c..c99fd97c6e 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHtt return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHtt return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHtt ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 03ef7baa87..6fbc4bbfb9 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttp return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttp return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttp return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 61ba8e3041..be98a7761b 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ internal open class ApiClient(val baseUrl: String, val client: OkHttpClient = de protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ internal open class ApiClient(val baseUrl: String, val client: OkHttpClient = de // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -164,7 +167,7 @@ internal open class ApiClient(val baseUrl: String, val client: OkHttpClient = de updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -174,7 +177,7 @@ internal open class ApiClient(val baseUrl: String, val client: OkHttpClient = de }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -182,16 +185,16 @@ internal open class ApiClient(val baseUrl: String, val client: OkHttpClient = de } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index 8aa11ef985..d38e504e91 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ internal class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index fbd0beed7f..21f6e90951 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ internal class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Category.kt index 9de433b75e..e6743cfe80 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 43947587cf..14658f3824 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Order.kt index 1e71385a5c..7e42b1669c 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Pet.kt index 88ce520dd5..fd644dee52 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Tag.kt index 5e75097481..c553371102 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/User.kt index fa92a880d3..7cf9457405 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nullable/README.md b/samples/client/petstore/kotlin-nullable/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-nullable/README.md +++ b/samples/client/petstore/kotlin-nullable/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-nullable/build.gradle b/samples/client/petstore/kotlin-nullable/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin-nullable/build.gradle +++ b/samples/client/petstore/kotlin-nullable/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index aeb395cf87..2c440b44b8 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index cf9f7f99e4..4ecada339c 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 2c46e94f7f..0730e30aa4 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 4ad22a02df..fd43ff24fe 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -164,7 +167,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -174,7 +177,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -182,16 +185,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Category.kt index f458d178e3..7be2ec5ed2 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 5f584a05ac..109f5f8ad9 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Order.kt index 049b45ab9e..959bb76bc5 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Pet.kt index 0ad65abf40..8e8fa881d3 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Tag.kt index ded73dc723..41d984658a 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/User.kt index 03d55050eb..92e10c741e 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-okhttp3/README.md b/samples/client/petstore/kotlin-okhttp3/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-okhttp3/README.md +++ b/samples/client/petstore/kotlin-okhttp3/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-okhttp3/build.gradle b/samples/client/petstore/kotlin-okhttp3/build.gradle index b19a3b3873..e48744c81e 100644 --- a/samples/client/petstore/kotlin-okhttp3/build.gradle +++ b/samples/client/petstore/kotlin-okhttp3/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" implementation "com.squareup.okhttp3:okhttp:3.12.13" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 3e28ded0d9..1460cd1d97 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments()[0] } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index d192191c85..a99b9d3da2 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments()[0] } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 327a69c8e7..d35e1a9c4f 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments()[0] } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 9fcf138505..d87c7b3885 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -65,6 +65,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> RequestBody.create(MediaType.parse(mediaType ?: guessContentTypeFromFile(content)), content) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -72,22 +73,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(Headers.of(headers), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = MediaType.parse(guessContentTypeFromFile(part.body)) + addPart( + Headers.of(partHeaders), + RequestBody.create(fileMediaType, part.body) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + Headers.of(partHeaders), + RequestBody.create(null, parameterToString(part.body)) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> RequestBody.create(MediaType.parse(mediaType ?: guessContentTypeFromFile(content)), content) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -162,7 +165,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -172,7 +175,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -180,16 +183,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Category.kt index 94a40441cb..36beb0e657 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 15c64ef38a..d9540485eb 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Order.kt index 7195f33669..bde4a0e9ac 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Pet.kt index 801bd2a822..ceaf28a742 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Tag.kt index fcd3c28dcd..2086c90cfb 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/User.kt index ab10e1ddfd..4ea236d7ca 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/FILES b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/FILES index fd9029f088..e301c7cd1b 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/FILES @@ -28,7 +28,6 @@ src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt -src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/README.md b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/README.md index 8fb632221c..1bd530b899 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/README.md +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle index 60257e3160..e94a5d0130 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' ext.retrofitVersion = '2.9.0' repositories { @@ -32,9 +32,9 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1" + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.3" implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" - implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "com.squareup.okhttp3:logging-interceptor:4.10.0" implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/proguard-rules.pro b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/proguard-rules.pro index 31c893c43e..7c7b08bf38 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/proguard-rules.pro +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/proguard-rules.pro @@ -8,4 +8,4 @@ # project specific. -keep,includedescriptorclasses class org.openapitools.client.models.**$$serializer { *; } -keepclassmembers class org.openapitools.client.models.** { *** Companion; } --keepclasseswithmembers class org.openapitools.client.models.** { kotlinx.serialization.KSerializer serializer(...); } \ No newline at end of file +-keepclasseswithmembers class org.openapitools.client.models.** { kotlinx.serialization.KSerializer serializer(...); } diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index ababf9327f..78fe8530b2 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -4,6 +4,8 @@ import org.openapitools.client.infrastructure.CollectionFormats.* import retrofit2.http.* import retrofit2.Call import okhttp3.RequestBody +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -36,6 +38,16 @@ interface PetApi { @DELETE("pet/{petId}") fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Call + + /** + * enum for parameter status + */ + enum class Status_findPetsByStatus(val value: kotlin.String) { + @SerialName(value = "available") AVAILABLE("available"), + @SerialName(value = "pending") PENDING("pending"), + @SerialName(value = "sold") SOLD("sold") + } + /** * Finds Pets by status * Multiple status values can be provided with comma separated strings diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 7736ddef1f..393e0c10e3 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -4,6 +4,8 @@ import org.openapitools.client.infrastructure.CollectionFormats.* import retrofit2.http.* import retrofit2.Call import okhttp3.RequestBody +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.openapitools.client.models.Order diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index fdfa2a2641..d15b2c115e 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -4,6 +4,8 @@ import org.openapitools.client.infrastructure.CollectionFormats.* import retrofit2.http.* import retrofit2.Call import okhttp3.RequestBody +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.openapitools.client.models.User diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index ed22d5d071..2cc80d4840 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -16,7 +16,7 @@ import retrofit2.Converter import retrofit2.converter.scalars.ScalarsConverterFactory import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory -import org.openapitools.client.infrastructure.Serializer.jvmJson +import org.openapitools.client.infrastructure.Serializer.kotlinxSerializationJson import okhttp3.MediaType.Companion.toMediaType class ApiClient( @@ -32,7 +32,7 @@ class ApiClient( Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(ScalarsConverterFactory.create()) - .addConverterFactory(jvmJson.asConverterFactory("application/json".toMediaType())) + .addConverterFactory(kotlinxSerializationJson.asConverterFactory("application/json".toMediaType())) .apply { if (converterFactory != null) { addConverterFactory(converterFactory) diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt index f49da4b817..80611e349b 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt @@ -18,4 +18,4 @@ object AtomicBooleanAdapter : KSerializer { override fun deserialize(decoder: Decoder): AtomicBoolean = AtomicBoolean(decoder.decodeBoolean()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicBoolean", PrimitiveKind.BOOLEAN) -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt index d2c8182ac7..8a5a8bafc7 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt @@ -18,4 +18,4 @@ object AtomicIntegerAdapter : KSerializer { override fun deserialize(decoder: Decoder): AtomicInteger = AtomicInteger(decoder.decodeInt()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicInteger", PrimitiveKind.INT) -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt index bda455a88d..5842c49088 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt @@ -18,4 +18,4 @@ object AtomicLongAdapter : KSerializer { override fun deserialize(decoder: Decoder): AtomicLong = AtomicLong(decoder.decodeLong()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicLong", PrimitiveKind.LONG) -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index f0bedb18ea..94cbcb573a 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ object BigDecimalAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): BigDecimal = BigDecimal(decoder.decodeString()) override fun serialize(encoder: Encoder, value: BigDecimal) = encoder.encodeString(value.toPlainString()) -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index ca8cc56f06..8f0544aa2b 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -19,4 +19,4 @@ object BigIntegerAdapter : KSerializer { override fun serialize(encoder: Encoder, value: BigInteger) { encoder.encodeString(value.toString()) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt deleted file mode 100644 index fff39c7ac2..0000000000 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt +++ /dev/null @@ -1,3 +0,0 @@ -package org.openapitools.client.infrastructure - - diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index bbb1363803..82473d228a 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -15,8 +15,13 @@ import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong object Serializer { + @Deprecated("Use Serializer.kotlinxSerializationAdapters instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationAdapters")) @JvmStatic - val kotlinSerializationAdapters = SerializersModule { + val kotlinSerializationAdapters: SerializersModule + get() { return kotlinxSerializationAdapters } + + @JvmStatic + val kotlinxSerializationAdapters = SerializersModule { contextual(BigDecimal::class, BigDecimalAdapter) contextual(BigInteger::class, BigIntegerAdapter) contextual(LocalDate::class, LocalDateAdapter) @@ -31,6 +36,17 @@ object Serializer { contextual(StringBuilder::class, StringBuilderAdapter) } + @Deprecated("Use Serializer.kotlinxSerializationJson instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationJson")) @JvmStatic - val jvmJson: Json by lazy { Json { serializersModule = kotlinSerializationAdapters } } + val jvmJson: Json + get() { return kotlinxSerializationJson } + + @JvmStatic + val kotlinxSerializationJson: Json by lazy { + Json { + serializersModule = kotlinxSerializationAdapters + ignoreUnknownKeys = true + isLenient = true + } + } } diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt index 90610d4978..7a15749f06 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt @@ -17,4 +17,4 @@ object StringBuilderAdapter : KSerializer { override fun deserialize(decoder: Decoder): StringBuilder = StringBuilder(decoder.decodeString()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("StringBuilder", PrimitiveKind.STRING) -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt index 2df3308b76..0dead7a73f 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt @@ -18,4 +18,4 @@ object URLAdapter : KSerializer { override fun deserialize(decoder: Decoder): URL = URL(decoder.decodeString()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URL", PrimitiveKind.STRING) -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Category.kt index 6a45df20b8..d76243ae68 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index c898dbd152..3a1cb58e82 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Order.kt index 433a01d242..52a7d8b473 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Pet.kt index a3c43c02c9..b0564bd04c 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Tag.kt index 29286beda5..b38f0f9adc 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/User.kt index 0615309741..0b84f270fb 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/README.md b/samples/client/petstore/kotlin-retrofit2-rx3/README.md index 8fb632221c..1bd530b899 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/README.md +++ b/samples/client/petstore/kotlin-retrofit2-rx3/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle b/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle index 0d9707eb2d..8d3c9dd1bd 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle +++ b/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' ext.retrofitVersion = '2.9.0' ext.rxJava3Version = '3.0.12' @@ -32,10 +32,10 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" - implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "com.squareup.okhttp3:logging-interceptor:4.10.0" implementation "io.reactivex.rxjava3:rxjava:$rxJava3Version" implementation "com.squareup.retrofit2:adapter-rxjava3:2.9.0" implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 8149c9c078..ef86ac4da3 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -5,6 +5,7 @@ import retrofit2.http.* import okhttp3.RequestBody import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.core.Completable +import com.squareup.moshi.Json import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -37,6 +38,16 @@ interface PetApi { @DELETE("pet/{petId}") fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Completable + + /** + * enum for parameter status + */ + enum class Status_findPetsByStatus(val value: kotlin.String) { + @Json(name = "available") available("available"), + @Json(name = "pending") pending("pending"), + @Json(name = "sold") sold("sold") + } + /** * Finds Pets by status * Multiple status values can be provided with comma separated strings diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 7946510c56..b24d72895e 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -5,6 +5,7 @@ import retrofit2.http.* import okhttp3.RequestBody import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.core.Completable +import com.squareup.moshi.Json import org.openapitools.client.models.Order diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 55aeb36bbd..8f074fb34a 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -5,6 +5,7 @@ import retrofit2.http.* import okhttp3.RequestBody import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.core.Completable +import com.squareup.moshi.Json import org.openapitools.client.models.User diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Category.kt index 94a40441cb..36beb0e657 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 15c64ef38a..d9540485eb 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Order.kt index 1c87feb697..d1de6588ca 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Pet.kt index fb28ee9222..b1d4ea6bf0 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Tag.kt index fcd3c28dcd..2086c90cfb 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/User.kt index ab10e1ddfd..4ea236d7ca 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2/README.md b/samples/client/petstore/kotlin-retrofit2/README.md index 8fb632221c..1bd530b899 100644 --- a/samples/client/petstore/kotlin-retrofit2/README.md +++ b/samples/client/petstore/kotlin-retrofit2/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-retrofit2/build.gradle b/samples/client/petstore/kotlin-retrofit2/build.gradle index 32e67f975a..2c2228d9d6 100644 --- a/samples/client/petstore/kotlin-retrofit2/build.gradle +++ b/samples/client/petstore/kotlin-retrofit2/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' ext.retrofitVersion = '2.9.0' repositories { @@ -31,10 +31,10 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" - implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "com.squareup.okhttp3:logging-interceptor:4.10.0" implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion" implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index ababf9327f..ebedf6a416 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -4,6 +4,7 @@ import org.openapitools.client.infrastructure.CollectionFormats.* import retrofit2.http.* import retrofit2.Call import okhttp3.RequestBody +import com.squareup.moshi.Json import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -36,6 +37,16 @@ interface PetApi { @DELETE("pet/{petId}") fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Call + + /** + * enum for parameter status + */ + enum class Status_findPetsByStatus(val value: kotlin.String) { + @Json(name = "available") available("available"), + @Json(name = "pending") pending("pending"), + @Json(name = "sold") sold("sold") + } + /** * Finds Pets by status * Multiple status values can be provided with comma separated strings diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 7736ddef1f..5a3c2f7ccb 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -4,6 +4,7 @@ import org.openapitools.client.infrastructure.CollectionFormats.* import retrofit2.http.* import retrofit2.Call import okhttp3.RequestBody +import com.squareup.moshi.Json import org.openapitools.client.models.Order diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index fdfa2a2641..f4139bfa9c 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -4,6 +4,7 @@ import org.openapitools.client.infrastructure.CollectionFormats.* import retrofit2.http.* import retrofit2.Call import okhttp3.RequestBody +import com.squareup.moshi.Json import org.openapitools.client.models.User diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Category.kt index 94a40441cb..36beb0e657 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 15c64ef38a..d9540485eb 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Order.kt index 1c87feb697..d1de6588ca 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Pet.kt index fb28ee9222..b1d4ea6bf0 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Tag.kt index fcd3c28dcd..2086c90cfb 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/User.kt index ab10e1ddfd..4ea236d7ca 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-string/README.md b/samples/client/petstore/kotlin-string/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-string/README.md +++ b/samples/client/petstore/kotlin-string/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-string/build.gradle b/samples/client/petstore/kotlin-string/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin-string/build.gradle +++ b/samples/client/petstore/kotlin-string/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index bf195c9af2..672d8b295d 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index d192191c85..ca473d06df 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 327a69c8e7..720713cafe 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 4ad22a02df..fd43ff24fe 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -164,7 +167,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -174,7 +177,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -182,16 +185,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Category.kt index f458d178e3..7be2ec5ed2 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 5f584a05ac..109f5f8ad9 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Order.kt index 3527c1ea84..a8d20ae5db 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Pet.kt index 51546bc6ee..9db9ee6739 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Tag.kt index ded73dc723..41d984658a 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/User.kt index 03d55050eb..92e10c741e 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-threetenbp/README.md b/samples/client/petstore/kotlin-threetenbp/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin-threetenbp/README.md +++ b/samples/client/petstore/kotlin-threetenbp/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-threetenbp/build.gradle b/samples/client/petstore/kotlin-threetenbp/build.gradle index 39e3e41164..e27847c2f3 100644 --- a/samples/client/petstore/kotlin-threetenbp/build.gradle +++ b/samples/client/petstore/kotlin-threetenbp/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,9 +30,9 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" implementation "org.threeten:threetenbp:1.5.1" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index e0d26a4ae3..9b1451613f 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index d192191c85..ca473d06df 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 327a69c8e7..720713cafe 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 3d6b7ccb79..69b4dcef60 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -164,7 +167,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -174,7 +177,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -182,16 +185,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Category.kt index 94a40441cb..36beb0e657 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 15c64ef38a..d9540485eb 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Order.kt index 988ec7c78d..fece9ea4f6 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Pet.kt index fb28ee9222..b1d4ea6bf0 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Tag.kt index fcd3c28dcd..2086c90cfb 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/User.kt index ab10e1ddfd..4ea236d7ca 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES index 9a212390c6..9139e88c88 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES @@ -6,14 +6,17 @@ gradle/wrapper/gradle-wrapper.jar gradle/wrapper/gradle-wrapper.properties gradlew gradlew.bat +proguard-rules.pro settings.gradle src/main/kotlin/org/openapitools/client/apis/EnumApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt +src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt -src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -23,6 +26,8 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/PetEnum.kt diff --git a/samples/client/petstore/kotlin-uppercase-enum/README.md b/samples/client/petstore/kotlin-uppercase-enum/README.md index 0c118c5bf7..9b3bfe4e89 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/README.md +++ b/samples/client/petstore/kotlin-uppercase-enum/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for OpenAPI Petstore +Test for issue 4062 + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin-uppercase-enum/build.gradle b/samples/client/petstore/kotlin-uppercase-enum/build.gradle index 3de8b45b13..1df0362d6c 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/build.gradle +++ b/samples/client/petstore/kotlin-uppercase-enum/build.gradle @@ -2,22 +2,24 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" } } apply plugin: 'kotlin' +apply plugin: 'kotlinx-serialization' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -29,9 +31,13 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.3" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } + +tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { + kotlinOptions { + freeCompilerArgs += "-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi" + } +} diff --git a/samples/client/petstore/kotlin-uppercase-enum/docs/PetEnum.md b/samples/client/petstore/kotlin-uppercase-enum/docs/PetEnum.md index d970c3dd86..cab9c95f78 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/docs/PetEnum.md +++ b/samples/client/petstore/kotlin-uppercase-enum/docs/PetEnum.md @@ -8,5 +8,7 @@ * `MY_SECOND_VALUE` (value: `"MY_SECOND_VALUE"`) + * `UNKNOWN_DEFAULT_OPEN_API` (value: `"unknown_default_open_api"`) + diff --git a/samples/client/petstore/kotlin-uppercase-enum/proguard-rules.pro b/samples/client/petstore/kotlin-uppercase-enum/proguard-rules.pro new file mode 100644 index 0000000000..7c7b08bf38 --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/proguard-rules.pro @@ -0,0 +1,11 @@ +-keepattributes *Annotation*, InnerClasses +-dontnote kotlinx.serialization.AnnotationsKt # core serialization annotations + +# kotlinx-serialization-json specific. Add this if you have java.lang.NoClassDefFoundError kotlinx.serialization.json.JsonObjectSerializer +-keepclassmembers class kotlinx.serialization.json.** { *** Companion; } +-keepclasseswithmembers class kotlinx.serialization.json.** { kotlinx.serialization.KSerializer serializer(...); } + +# project specific. +-keep,includedescriptorclasses class org.openapitools.client.models.**$$serializer { *; } +-keepclassmembers class org.openapitools.client.models.** { *** Companion; } +-keepclasseswithmembers class org.openapitools.client.models.** { kotlinx.serialization.KSerializer serializer(...); } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt index 7f1765943b..3e4079f632 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt @@ -1,14 +1,9 @@ /** - * OpenAPI Petstore - * - * Test for issue 4062 - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,10 +17,12 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.PetEnum -import com.squareup.moshi.Json +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.openapitools.client.infrastructure.ApiClient import org.openapitools.client.infrastructure.ApiResponse @@ -116,4 +113,7 @@ class EnumApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index bfd00ac6a2..ca3a9037de 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -27,7 +27,8 @@ import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime import java.util.Locale -import com.squareup.moshi.adapter +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.encodeToString open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { @@ -68,6 +69,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +77,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -104,7 +108,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie if (content == null) { EMPTY_REQUEST } else { - Serializer.moshi.adapter(T::class.java).toJson(content) + Serializer.kotlinxSerializationJson.encodeToString(content) .toRequestBody((mediaType ?: JsonMediaType).toMediaTypeOrNull()) } mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.") @@ -112,7 +116,6 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.") } - @OptIn(ExperimentalStdlibApi::class) protected inline fun responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? { if(body == null) { return null @@ -135,7 +138,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } return when { mediaType==null || (mediaType.startsWith("application/") && mediaType.endsWith("json")) -> - Serializer.moshi.adapter().fromJson(bodyContent) + Serializer.kotlinxSerializationJson.decodeFromString(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } @@ -145,7 +148,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -155,7 +158,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -163,16 +166,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -237,6 +240,6 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie formatter. It also easily allows to provide a simple way to define a custom date format pattern inside a gson/moshi adapter. */ - return Serializer.moshi.adapter(T::class.java).toJson(value).replace("\"", "") + return Serializer.kotlinxSerializationJson.encodeToString(value).replace("\"", "") } } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt new file mode 100644 index 0000000000..80611e349b --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/AtomicBooleanAdapter.kt @@ -0,0 +1,21 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor +import java.util.concurrent.atomic.AtomicBoolean + +@Serializer(forClass = AtomicBoolean::class) +object AtomicBooleanAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: AtomicBoolean) { + encoder.encodeBoolean(value.get()) + } + + override fun deserialize(decoder: Decoder): AtomicBoolean = AtomicBoolean(decoder.decodeBoolean()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicBoolean", PrimitiveKind.BOOLEAN) +} diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt new file mode 100644 index 0000000000..8a5a8bafc7 --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/AtomicIntegerAdapter.kt @@ -0,0 +1,21 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor +import java.util.concurrent.atomic.AtomicInteger + +@Serializer(forClass = AtomicInteger::class) +object AtomicIntegerAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: AtomicInteger) { + encoder.encodeInt(value.get()) + } + + override fun deserialize(decoder: Decoder): AtomicInteger = AtomicInteger(decoder.decodeInt()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicInteger", PrimitiveKind.INT) +} diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt new file mode 100644 index 0000000000..5842c49088 --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/AtomicLongAdapter.kt @@ -0,0 +1,21 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor +import java.util.concurrent.atomic.AtomicLong + +@Serializer(forClass = AtomicLong::class) +object AtomicLongAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: AtomicLong) { + encoder.encodeLong(value.get()) + } + + override fun deserialize(decoder: Decoder): AtomicLong = AtomicLong(decoder.decodeLong()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("AtomicLong", PrimitiveKind.LONG) +} diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..94cbcb573a 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -1,17 +1,17 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.math.BigDecimal -class BigDecimalAdapter { - @ToJson - fun toJson(value: BigDecimal): String { - return value.toPlainString() - } - - @FromJson - fun fromJson(value: String): BigDecimal { - return BigDecimal(value) - } -} \ No newline at end of file +@Serializer(forClass = BigDecimal::class) +object BigDecimalAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING) + override fun deserialize(decoder: Decoder): BigDecimal = BigDecimal(decoder.decodeString()) + override fun serialize(encoder: Encoder, value: BigDecimal) = encoder.encodeString(value.toPlainString()) +} diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..8f0544aa2b 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -1,17 +1,22 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.math.BigInteger -class BigIntegerAdapter { - @ToJson - fun toJson(value: BigInteger): String { - return value.toString() +@Serializer(forClass = BigInteger::class) +object BigIntegerAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigInteger", PrimitiveKind.STRING) + override fun deserialize(decoder: Decoder): BigInteger { + return BigInteger(decoder.decodeString()) } - @FromJson - fun fromJson(value: String): BigInteger { - return BigInteger(value) + override fun serialize(encoder: Encoder, value: BigInteger) { + encoder.encodeString(value.toString()) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt deleted file mode 100644 index ff5e2a81ee..0000000000 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt +++ /dev/null @@ -1,12 +0,0 @@ -package org.openapitools.client.infrastructure - -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson - -class ByteArrayAdapter { - @ToJson - fun toJson(data: ByteArray): String = String(data) - - @FromJson - fun fromJson(data: String): ByteArray = data.toByteArray() -} diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt index b2e1654479..f7c632d696 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -1,19 +1,24 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.time.LocalDate import java.time.format.DateTimeFormatter -class LocalDateAdapter { - @ToJson - fun toJson(value: LocalDate): String { - return DateTimeFormatter.ISO_LOCAL_DATE.format(value) +@Serializer(forClass = LocalDate::class) +object LocalDateAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDate", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: LocalDate) { + encoder.encodeString(DateTimeFormatter.ISO_LOCAL_DATE.format(value)) } - @FromJson - fun fromJson(value: String): LocalDate { - return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) + override fun deserialize(decoder: Decoder): LocalDate { + return LocalDate.parse(decoder.decodeString(), DateTimeFormatter.ISO_LOCAL_DATE) } - } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt index e082db9481..88bd140113 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -1,19 +1,24 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.time.LocalDateTime import java.time.format.DateTimeFormatter -class LocalDateTimeAdapter { - @ToJson - fun toJson(value: LocalDateTime): String { - return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) +@Serializer(forClass = LocalDateTime::class) +object LocalDateTimeAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDateTime", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: LocalDateTime) { + encoder.encodeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value)) } - @FromJson - fun fromJson(value: String): LocalDateTime { - return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) + override fun deserialize(decoder: Decoder): LocalDateTime { + return LocalDateTime.parse(decoder.decodeString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME) } - } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt index 87437871a3..e0fe9e3b53 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -1,19 +1,24 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.time.OffsetDateTime import java.time.format.DateTimeFormatter -class OffsetDateTimeAdapter { - @ToJson - fun toJson(value: OffsetDateTime): String { - return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) +@Serializer(forClass = OffsetDateTime::class) +object OffsetDateTimeAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("OffsetDateTime", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: OffsetDateTime) { + encoder.encodeString(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value)) } - @FromJson - fun fromJson(value: String): OffsetDateTime { - return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + override fun deserialize(decoder: Decoder): OffsetDateTime { + return OffsetDateTime.parse(decoder.decodeString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME) } - } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index e22592e47d..82473d228a 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,23 +1,52 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.Moshi -import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +import java.math.BigDecimal +import java.math.BigInteger +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.OffsetDateTime +import java.util.UUID +import kotlinx.serialization.json.Json +import kotlinx.serialization.modules.SerializersModule +import java.net.URI +import java.net.URL +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong object Serializer { + @Deprecated("Use Serializer.kotlinxSerializationAdapters instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationAdapters")) @JvmStatic - val moshiBuilder: Moshi.Builder = Moshi.Builder() - .add(OffsetDateTimeAdapter()) - .add(LocalDateTimeAdapter()) - .add(LocalDateAdapter()) - .add(UUIDAdapter()) - .add(ByteArrayAdapter()) - .add(URIAdapter()) - .add(KotlinJsonAdapterFactory()) - .add(BigDecimalAdapter()) - .add(BigIntegerAdapter()) + val kotlinSerializationAdapters: SerializersModule + get() { return kotlinxSerializationAdapters } @JvmStatic - val moshi: Moshi by lazy { - moshiBuilder.build() + val kotlinxSerializationAdapters = SerializersModule { + contextual(BigDecimal::class, BigDecimalAdapter) + contextual(BigInteger::class, BigIntegerAdapter) + contextual(LocalDate::class, LocalDateAdapter) + contextual(LocalDateTime::class, LocalDateTimeAdapter) + contextual(OffsetDateTime::class, OffsetDateTimeAdapter) + contextual(UUID::class, UUIDAdapter) + contextual(AtomicInteger::class, AtomicIntegerAdapter) + contextual(AtomicLong::class, AtomicLongAdapter) + contextual(AtomicBoolean::class, AtomicBooleanAdapter) + contextual(URI::class, URIAdapter) + contextual(URL::class, URLAdapter) + contextual(StringBuilder::class, StringBuilderAdapter) + } + + @Deprecated("Use Serializer.kotlinxSerializationJson instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationJson")) + @JvmStatic + val jvmJson: Json + get() { return kotlinxSerializationJson } + + @JvmStatic + val kotlinxSerializationJson: Json by lazy { + Json { + serializersModule = kotlinxSerializationAdapters + ignoreUnknownKeys = true + isLenient = true + } } } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt new file mode 100644 index 0000000000..7a15749f06 --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/StringBuilderAdapter.kt @@ -0,0 +1,20 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor + +@Serializer(forClass = StringBuilder::class) +object StringBuilderAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: StringBuilder) { + encoder.encodeString(value.toString()) + } + + override fun deserialize(decoder: Decoder): StringBuilder = StringBuilder(decoder.decodeString()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("StringBuilder", PrimitiveKind.STRING) +} diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt index 927522757d..0856c99813 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -1,13 +1,21 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.net.URI -class URIAdapter { - @ToJson - fun toJson(uri: URI) = uri.toString() +@Serializer(forClass = URI::class) +object URIAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: URI) { + encoder.encodeString(value.toASCIIString()) + } - @FromJson - fun fromJson(s: String): URI = URI.create(s) + override fun deserialize(decoder: Decoder): URI = URI(decoder.decodeString()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URI", PrimitiveKind.STRING) } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt new file mode 100644 index 0000000000..0dead7a73f --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt @@ -0,0 +1,21 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor +import java.net.URL + +@Serializer(forClass = URL::class) +object URLAdapter : KSerializer { + override fun serialize(encoder: Encoder, value: URL) { + encoder.encodeString(value.toExternalForm()) + } + + override fun deserialize(decoder: Decoder): URL = URL(decoder.decodeString()) + + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URL", PrimitiveKind.STRING) +} diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index 7ccf7dc25d..fbae87c1a6 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -1,13 +1,23 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.ToJson +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.SerialDescriptor import java.util.UUID -class UUIDAdapter { - @ToJson - fun toJson(uuid: UUID) = uuid.toString() +@Serializer(forClass = UUID::class) +object UUIDAdapter : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING) - @FromJson - fun fromJson(s: String): UUID = UUID.fromString(s) + override fun serialize(encoder: Encoder, value: UUID) { + encoder.encodeString(value.toString()) + } + + override fun deserialize(decoder: Decoder): UUID { + return UUID.fromString(decoder.decodeString()) + } } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt index 4d9fa1abd6..a4aa4c2f57 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt @@ -1,14 +1,9 @@ /** - * OpenAPI Petstore - * - * Test for issue 4062 - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -21,21 +16,30 @@ package org.openapitools.client.models -import com.squareup.moshi.Json +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder /** * An enum with complex-ish naming * - * Values: MY_FIRST_VALUE,MY_SECOND_VALUE + * Values: MY_FIRST_VALUE,MY_SECOND_VALUE,UNKNOWN_DEFAULT_OPEN_API */ - +@Serializable(with = PetEnumSerializer::class) enum class PetEnum(val value: kotlin.String) { - @Json(name = "myFirstValue") + @SerialName(value = "myFirstValue") MY_FIRST_VALUE("myFirstValue"), - @Json(name = "MY_SECOND_VALUE") - MY_SECOND_VALUE("MY_SECOND_VALUE"); + @SerialName(value = "MY_SECOND_VALUE") + MY_SECOND_VALUE("MY_SECOND_VALUE"), + + @SerialName(value = "unknown_default_open_api") + UNKNOWN_DEFAULT_OPEN_API("unknown_default_open_api"); /** * Override toString() to avoid using the enum variable name as the value, and instead use @@ -64,3 +68,18 @@ enum class PetEnum(val value: kotlin.String) { } } +@Serializer(forClass = PetEnum::class) +internal object PetEnumSerializer : KSerializer { + override val descriptor = kotlin.String.serializer().descriptor + + override fun deserialize(decoder: Decoder): PetEnum { + val value = decoder.decodeSerializableValue(kotlin.String.serializer()) + return PetEnum.values().firstOrNull { it.value == value } + ?: PetEnum.UNKNOWN_DEFAULT_OPEN_API + } + + override fun serialize(encoder: Encoder, value: PetEnum) { + encoder.encodeSerializableValue(kotlin.String.serializer(), value.value) + } +} + diff --git a/samples/client/petstore/kotlin/README.md b/samples/client/petstore/kotlin/README.md index 5ecae07a7a..e8336e9f36 100644 --- a/samples/client/petstore/kotlin/README.md +++ b/samples/client/petstore/kotlin/README.md @@ -1,5 +1,14 @@ # org.openapitools.client - Kotlin client library for 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. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + ## Requires * Kotlin 1.4.30 diff --git a/samples/client/petstore/kotlin/build.gradle b/samples/client/petstore/kotlin/build.gradle index 3de8b45b13..527140cfc8 100644 --- a/samples/client/petstore/kotlin/build.gradle +++ b/samples/client/petstore/kotlin/build.gradle @@ -2,12 +2,12 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '6.8.3' + gradleVersion = '7.5' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.5.10' + ext.kotlin_version = '1.6.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,8 +30,8 @@ test { dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - implementation "com.squareup.moshi:moshi-kotlin:1.12.0" - implementation "com.squareup.moshi:moshi-adapters:1.12.0" - implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "com.squareup.moshi:moshi-kotlin:1.13.0" + implementation "com.squareup.moshi:moshi-adapters:1.13.0" + implementation "com.squareup.okhttp3:okhttp:4.10.0" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index e0d26a4ae3..9b1451613f 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -182,7 +178,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -412,7 +408,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -555,7 +551,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -633,11 +629,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", petId.toString()), + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index d192191c85..ca473d06df 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.Order @@ -109,7 +105,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -246,7 +242,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", orderId.toString()), + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -323,4 +319,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 327a69c8e7..720713cafe 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( @@ -22,6 +17,7 @@ package org.openapitools.client.apis import java.io.IOException import okhttp3.OkHttpClient +import okhttp3.HttpUrl import org.openapitools.client.models.User @@ -310,7 +306,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -380,7 +376,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody @@ -591,11 +587,14 @@ class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", username.toString()), + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) } + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 4ad22a02df..fd43ff24fe 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -68,6 +68,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -75,22 +76,24 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie // content's type *must* be Map> @Suppress("UNCHECKED_CAST") (content as Map>).forEach { (name, part) -> - val contentType = part.headers.remove("Content-Type") - val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) - bodies.forEach { body -> - val headers = part.headers.toMutableMap() + - ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") - addPart(headers.toHeaders(), - requestSingleBody(body, contentType)) + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) } } }.build() - else -> requestSingleBody(content, mediaType) - } - - protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = - when { - content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { // content's type *must* be Map> @@ -164,7 +167,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie updateAuthParams(requestConfig) val url = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) + .addEncodedPathSegments(requestConfig.path.trimStart('/')) .apply { requestConfig.query.forEach { query -> query.value.forEach { queryValue -> @@ -174,7 +177,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie }.build() // take content-type/accept from spec or set to default (application/json) if not defined - if (requestConfig.headers[ContentType].isNullOrEmpty()) { + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { requestConfig.headers[ContentType] = JsonMediaType } if (requestConfig.headers[Accept].isNullOrEmpty()) { @@ -182,16 +185,16 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie } val headers = requestConfig.headers - if(headers[ContentType].isNullOrEmpty()) { - throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") - } - - if(headers[Accept].isNullOrEmpty()) { + if (headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) + } else { + null + } val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index fb2c972cf8..064b57fc6b 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -14,4 +14,4 @@ class BigDecimalAdapter { fun fromJson(value: String): BigDecimal { return BigDecimal(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index 4b6963110c..7df6057b45 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -14,4 +14,4 @@ class BigIntegerAdapter { fun fromJson(value: String): BigInteger { return BigInteger(value) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Category.kt index f458d178e3..7be2ec5ed2 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 5f584a05ac..109f5f8ad9 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt index 049b45ab9e..959bb76bc5 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt index 0ad65abf40..8e8fa881d3 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Tag.kt index ded73dc723..41d984658a 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/User.kt index 03d55050eb..92e10c741e 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/models/User.kt @@ -1,14 +1,9 @@ /** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. + * */ @file:Suppress( diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/ApiClient.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/ApiClient.pm index 3319a2c92a..0aa1201423 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/ApiClient.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/ApiClient.pm @@ -256,10 +256,12 @@ sub deserialize } elsif (grep /^$class$/, ('DATE_TIME', 'DATE')) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ($class eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($class eq 'object') { return $data; } elsif (grep /^$class$/, ('int', 'float', 'double')) { + return undef unless defined $data; return $data + 0; } elsif ($class eq 'bool') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/AdditionalPropertiesClass.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/AdditionalPropertiesClass.pm index 5c2e9307fa..fe3e6e9bf8 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/AdditionalPropertiesClass.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/AdditionalPropertiesClass.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/AllOfWithSingleRef.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/AllOfWithSingleRef.pm index 0a57730d25..b032d5c460 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/AllOfWithSingleRef.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/AllOfWithSingleRef.pm @@ -131,21 +131,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -196,8 +200,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Animal.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Animal.pm index a757b284e3..610421d0af 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Animal.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Animal.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ApiResponse.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ApiResponse.pm index 3000b9d6d5..ad8dd55099 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ApiResponse.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ApiResponse.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayOfArrayOfNumberOnly.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayOfArrayOfNumberOnly.pm index 4fdc48339a..8d5200bafb 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayOfArrayOfNumberOnly.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayOfArrayOfNumberOnly.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayOfNumberOnly.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayOfNumberOnly.pm index 0b57da9f12..1248abfb95 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayOfNumberOnly.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayOfNumberOnly.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayTest.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayTest.pm index afe2349c04..bd080ca518 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayTest.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ArrayTest.pm @@ -131,21 +131,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -196,8 +200,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Capitalization.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Capitalization.pm index f42063375c..a7e92a6bbd 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Capitalization.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Capitalization.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Cat.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Cat.pm index cde97e8881..dfaa6adbb8 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Cat.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Cat.pm @@ -140,21 +140,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -208,8 +212,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/CatAllOf.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/CatAllOf.pm index 311f549abc..35c42cd049 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/CatAllOf.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/CatAllOf.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Category.pm index f10dd9a33a..3d6dfcc8b7 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Category.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ClassModel.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ClassModel.pm index 2223cd047b..e980490b08 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ClassModel.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ClassModel.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Client.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Client.pm index dd092c9635..2dd2ef0445 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Client.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Client.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/DeprecatedObject.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/DeprecatedObject.pm index a38312f064..590c2782fa 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/DeprecatedObject.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/DeprecatedObject.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Dog.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Dog.pm index 96ba8329f5..42559cbc14 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Dog.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Dog.pm @@ -140,21 +140,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -208,8 +212,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/DogAllOf.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/DogAllOf.pm index 7215d703f4..f75f7f4106 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/DogAllOf.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/DogAllOf.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumArrays.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumArrays.pm index eeaa2820f8..76b8491df2 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumArrays.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumArrays.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumClass.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumClass.pm index 7f1c21376a..c9f89c7f9b 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumClass.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumClass.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumTest.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumTest.pm index 7365ea1180..a6c47f94ad 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumTest.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/EnumTest.pm @@ -134,21 +134,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -199,8 +203,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/File.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/File.pm index 3635691c47..eed979a03a 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/File.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/File.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FileSchemaTestClass.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FileSchemaTestClass.pm index 83abbe603a..51a3e8c563 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FileSchemaTestClass.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FileSchemaTestClass.pm @@ -131,21 +131,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -196,8 +200,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm index 9d2fddd95c..455bc1d495 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FooGetDefaultResponse.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FooGetDefaultResponse.pm index d67c0207c8..ff23c2e1f1 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FooGetDefaultResponse.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FooGetDefaultResponse.pm @@ -131,21 +131,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -196,8 +200,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FormatTest.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FormatTest.pm index d0ad7e619f..667b31ba9c 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FormatTest.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/FormatTest.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/HasOnlyReadOnly.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/HasOnlyReadOnly.pm index cfea73981d..39d0391e75 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/HasOnlyReadOnly.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/HasOnlyReadOnly.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/HealthCheckResult.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/HealthCheckResult.pm index 6899aeb011..8d95f20444 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/HealthCheckResult.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/HealthCheckResult.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/List.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/List.pm index 6c993449c5..c7b5da6e28 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/List.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/List.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/MapTest.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/MapTest.pm index 0065986549..23f774ba88 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/MapTest.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/MapTest.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm index b39798d87e..94dd3db9c7 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/MixedPropertiesAndAdditionalPropertiesClass.pm @@ -131,21 +131,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -196,8 +200,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Model200Response.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Model200Response.pm index 8dd6bbecc4..4cd7e3ce5d 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Model200Response.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Model200Response.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ModelReturn.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ModelReturn.pm index 19170e5806..fc7ab101d0 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ModelReturn.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ModelReturn.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Name.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Name.pm index fe693fb563..3a028d3558 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Name.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Name.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/NullableClass.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/NullableClass.pm index e83d3d247e..88ef76300d 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/NullableClass.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/NullableClass.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/NumberOnly.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/NumberOnly.pm index 285b49d5f2..a9183ffc6a 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/NumberOnly.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/NumberOnly.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ObjectWithDeprecatedFields.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ObjectWithDeprecatedFields.pm index 52fddf1b0e..ce18bf6cb6 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ObjectWithDeprecatedFields.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ObjectWithDeprecatedFields.pm @@ -131,21 +131,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -196,8 +200,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Order.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Order.pm index 546fa99bd5..73168f90b7 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Order.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterComposite.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterComposite.pm index bd556a015a..cc57dd4149 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterComposite.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterComposite.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnum.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnum.pm index dcaf89b59b..9d430abd72 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnum.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnum.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumDefaultValue.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumDefaultValue.pm index de637b622c..014481ffc7 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumDefaultValue.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumDefaultValue.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumInteger.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumInteger.pm index 8ea3c91dba..78eb9b0d6f 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumInteger.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumInteger.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumIntegerDefaultValue.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumIntegerDefaultValue.pm index 4e2d7f322d..929d7d1e82 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumIntegerDefaultValue.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterEnumIntegerDefaultValue.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterObjectWithEnumProperty.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterObjectWithEnumProperty.pm index aa593caa74..e714d6f1f5 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterObjectWithEnumProperty.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/OuterObjectWithEnumProperty.pm @@ -131,21 +131,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -196,8 +200,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Pet.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Pet.pm index 4d8e35e755..cb9ffa59e7 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Pet.pm @@ -132,21 +132,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -197,8 +201,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ReadOnlyFirst.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ReadOnlyFirst.pm index f3eaa616cb..59e15a1cb5 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ReadOnlyFirst.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/ReadOnlyFirst.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/SingleRefType.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/SingleRefType.pm index 6840aa6a3c..66f108a0d7 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/SingleRefType.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/SingleRefType.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/SpecialModelName.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/SpecialModelName.pm index a392080eef..b09955a26f 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/SpecialModelName.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/SpecialModelName.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Tag.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Tag.pm index a1aa0ab405..35466afbc4 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Tag.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/User.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/User.pm index 5f750981a4..788dc12142 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/User.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/User.pm @@ -130,21 +130,25 @@ sub _to_json_primitives { if ( grep( /^$type$/, ('int', 'double'))) { # https://metacpan.org/pod/JSON#simple-scalars # numify it, ensuring it will be dumped as a number + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { # https://metacpan.org/pod/JSON#simple-scalars # stringified + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { # https://metacpan.org/pod/JSON#JSON::true,-JSON::false,-JSON::null return $data ? \1 : \0; } elsif ($type eq 'DATE') { + return undef unless defined $data; if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Eymd($optional_separator),-$dt-%3Emdy(...),-$dt-%3Edmy(...) return $data->ymd; } return $data .q(); } elsif ($type eq 'DATE_TIME') { + return undef unless defined $data; # the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z if (ref($data) eq 'DateTime') { # https://metacpan.org/pod/DateTime#$dt-%3Erfc3339 @@ -195,8 +199,10 @@ sub _deserialize { if (grep( /^$type$/ , ('DATE_TIME', 'DATE'))) { return DateTime->from_epoch(epoch => str2time($data)); } elsif ( grep( /^$type$/, ('int', 'double'))) { + return undef unless defined $data; return $data + 0; } elsif ($type eq 'string') { + return undef unless defined $data; return $data . q(); } elsif ($type eq 'boolean') { return !!$data; diff --git a/samples/client/petstore/perl/test.pl b/samples/client/petstore/perl/test.pl index 3f00dc9fb6..665412d7bb 100755 --- a/samples/client/petstore/perl/test.pl +++ b/samples/client/petstore/perl/test.pl @@ -61,7 +61,7 @@ print "\nupload_file:" additional_metadata => 'testabc', file => './test.pl' ); -print "\nadd_pet:" . Dumper $api->add_pet( body => $pet ); +print "\nadd_pet:" . Dumper $api->add_pet( pet => $pet ); print "\nget_pet_by_id:" . Dumper $api->get_pet_by_id( pet_id => $pet_id ); print "\nupdate_pet_with_form:" . Dumper $api->update_pet_with_form( diff --git a/samples/client/petstore/perl/tests/02_store_api.t b/samples/client/petstore/perl/tests/02_store_api.t index 188471ec3e..76f397c83a 100644 --- a/samples/client/petstore/perl/tests/02_store_api.t +++ b/samples/client/petstore/perl/tests/02_store_api.t @@ -1,4 +1,4 @@ -use Test::More tests => 56; +use Test::More tests => 57; use Test::Exception; use lib 'lib'; @@ -184,4 +184,11 @@ my $pet_object_to_json = JSON->new->convert_blessed->encode($pet_object); like $pet_object_to_json, qr/\"id\":123/, '$pet_object->tags->[0]->id'; like $pet_object_to_json, qr/\"name\":\"1000\"/, '$pet_object->tags->[0]->name'; like $pet_object_to_json, qr/\"id\":456/, '$pet_object->tags->[1]->id'; -like $pet_object_to_json, qr/\"name\":\"test2\"/, '$pet_object->tags->[1]->name'; \ No newline at end of file +like $pet_object_to_json, qr/\"name\":\"test2\"/, '$pet_object->tags->[1]->name'; + +my %undef_test_order_data = ( + id => undef, + status => undef, +); +my $undef_test_order = WWW::OpenAPIClient::Object::Order->new->from_hash(\%undef_test_order_data); +lives_ok { JSON->new->convert_blessed->encode($undef_test_order) }; diff --git a/samples/client/petstore/perl/tests/05_long_module_name.t b/samples/client/petstore/perl/tests/05_long_module_name.t index c3e457c470..2be4ecbca0 100644 --- a/samples/client/petstore/perl/tests/05_long_module_name.t +++ b/samples/client/petstore/perl/tests/05_long_module_name.t @@ -9,7 +9,7 @@ if (! -d 'deep_module_test/lib' ) { plan skip_all => 'bin/perl-petstore.sh needs to be run first'; } else { - plan tests => 38; + plan tests => 37; } use_ok('Something::Deep::PetApi'); @@ -18,19 +18,19 @@ use_ok('Something::Deep::Object::Pet'); use_ok('Something::Deep::Object::Tag'); use_ok('Something::Deep::Object::Category'); -my $api_client = Something::Deep::ApiClient->instance('base_url' => 'http://testing'); -my $pet_api = Something::Deep::PetApi->new('api_client' => $api_client); -is $pet_api->{api_client}->{base_url}, 'http://testing', 'get the proper base URL from api client'; +my $api_client = Something::Deep::ApiClient->new('base_url' => 'http://testing'); +my $pet_api = Something::Deep::PetApi->new($api_client); +is $pet_api->{api_client}->{config}->{base_url}, 'http://testing', 'get the proper base URL from api client'; my $api = Something::Deep::PetApi->new(); -is $api->{api_client}->{base_url}, 'http://testing', 'we still get the original base URL from api client, because it\'s a singleton'; +is $api->{api_client}->{config}->{base_url}, 'http://petstore.swagger.io:80/v2', 'we still get the original base URL from api client, because it\'s a singleton'; # reset the base_url - no direct access because an application shouldn't be changing # its base URL halfway through -$api->{api_client}->{base_url} = 'http://petstore.swagger.io/v2'; +$api->{api_client}->{config}->{base_url} = 'http://petstore.swagger.io/v2'; -is $api->{api_client}->{base_url}, 'http://petstore.swagger.io/v2', 'get the default base URL from api client'; +is $api->{api_client}->{config}->{base_url}, 'http://petstore.swagger.io/v2', 'get the default base URL from api client'; # test select_header_content_type is $api->{api_client}->select_header_content_type('application/xml', 'Application/JSON'), 'application/json', 'get the proper content type application/json but not application/xml'; @@ -61,7 +61,7 @@ is $pet_hash->{category}->{name}, 'perl', 'get the proper category name'; is $pet_hash->{tags}[0]->{name}, 'just kidding', 'get the proper tag name'; is $pet_hash->{tags}[0]->{id}, '11', 'get the proper tag id'; -my $add_pet = $api->add_pet(pet => $pet); +my $add_pet = $api->add_pet(body => $pet); my $get_pet = $api->get_pet_by_id(pet_id => $pet_id); my $get_pet_hash = $get_pet->to_hash; @@ -82,8 +82,8 @@ is $update_pet_with_form, undef, 'get the null response from update_pet_wth_form my $get_pet_after_update = $api->get_pet_by_id(pet_id => $pet_id); is $get_pet_after_update->{status}, 'sold', 'get the updated status after update_pet_with_form'; -my $upload_pet = $api->upload_file(pet_id => $pet_id, additional_metadata => 'testabc', file => 'test.pl'); -is $upload_pet, undef, 'get the null response from upload_pet'; +# my $upload_pet = $api->upload_file(pet_id => $pet_id, additional_metadata => 'testabc', file => 'test.pl'); +# is $upload_pet, undef, 'get the null response from upload_pet'; my $delete_pet = $api->delete_pet(pet_id => $pet_id); is $delete_pet, undef, 'get the null response from delete_pet'; diff --git a/samples/client/petstore/perl/tests/06_inheritance.t b/samples/client/petstore/perl/tests/06_inheritance.t index 94f2eee748..cdf089ea64 100644 --- a/samples/client/petstore/perl/tests/06_inheritance.t +++ b/samples/client/petstore/perl/tests/06_inheritance.t @@ -1,4 +1,4 @@ -use Test::More tests => 37; +use Test::More tests => 6; use Test::Exception; use lib 'lib'; diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/AnotherFakeApi.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/AnotherFakeApi.md index 20ee44a4bf..ef6fa331bd 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/AnotherFakeApi.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/AnotherFakeApi.md @@ -1,10 +1,10 @@ # OpenAPI\Client\AnotherFakeApi -All URIs are relative to http://petstore.swagger.io:80/v2. +All URIs are relative to http://petstore.swagger.io:80/v2, except if the operation defines another base path. -Method | HTTP request | Description -------------- | ------------- | ------------- -[**call123TestSpecialTags()**](AnotherFakeApi.md#call123TestSpecialTags) | **PATCH** /another-fake/dummy | To test special tags +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**call123TestSpecialTags()**](AnotherFakeApi.md#call123TestSpecialTags) | **PATCH** /another-fake/dummy | To test special tags | ## `call123TestSpecialTags()` @@ -42,9 +42,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**\OpenAPI\Client\Model\Client**](../Model/Client.md)| client model | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **client** | [**\OpenAPI\Client\Model\Client**](../Model/Client.md)| client model | | ### Return type diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/DefaultApi.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/DefaultApi.md index 6de004c507..d603956cfa 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/DefaultApi.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/DefaultApi.md @@ -1,10 +1,10 @@ # OpenAPI\Client\DefaultApi -All URIs are relative to http://petstore.swagger.io:80/v2. +All URIs are relative to http://petstore.swagger.io:80/v2, except if the operation defines another base path. -Method | HTTP request | Description -------------- | ------------- | ------------- -[**fooGet()**](DefaultApi.md#fooGet) | **GET** /foo | +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**fooGet()**](DefaultApi.md#fooGet) | **GET** /foo | | ## `fooGet()` diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md index d511a482a1..69af2914b9 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md @@ -1,26 +1,26 @@ # OpenAPI\Client\FakeApi -All URIs are relative to http://petstore.swagger.io:80/v2. +All URIs are relative to http://petstore.swagger.io:80/v2, except if the operation defines another base path. -Method | HTTP request | Description -------------- | ------------- | ------------- -[**fakeHealthGet()**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint -[**fakeHttpSignatureTest()**](FakeApi.md#fakeHttpSignatureTest) | **GET** /fake/http-signature-test | test http signature authentication -[**fakeOuterBooleanSerialize()**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | -[**fakeOuterCompositeSerialize()**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | -[**fakeOuterNumberSerialize()**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | -[**fakeOuterStringSerialize()**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | -[**fakePropertyEnumIntegerSerialize()**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | -[**testBodyWithBinary()**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | -[**testBodyWithFileSchema()**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | -[**testBodyWithQueryParams()**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | -[**testClientModel()**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model -[**testEndpointParameters()**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumParameters()**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters -[**testGroupParameters()**](FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -[**testInlineAdditionalProperties()**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -[**testJsonFormData()**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data -[**testQueryParameterCollectionFormat()**](FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**fakeHealthGet()**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint | +| [**fakeHttpSignatureTest()**](FakeApi.md#fakeHttpSignatureTest) | **GET** /fake/http-signature-test | test http signature authentication | +| [**fakeOuterBooleanSerialize()**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | | +| [**fakeOuterCompositeSerialize()**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | | +| [**fakeOuterNumberSerialize()**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | +| [**fakeOuterStringSerialize()**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | +| [**fakePropertyEnumIntegerSerialize()**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testBodyWithBinary()**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | +| [**testBodyWithFileSchema()**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | +| [**testBodyWithQueryParams()**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | +| [**testClientModel()**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model | +| [**testEndpointParameters()**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 | +| [**testEnumParameters()**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters | +| [**testGroupParameters()**](FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) | +| [**testInlineAdditionalProperties()**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties | +| [**testJsonFormData()**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data | +| [**testQueryParameterCollectionFormat()**](FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | | ## `fakeHealthGet()` @@ -110,11 +110,11 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet** | [**\OpenAPI\Client\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | - **query_1** | **string**| query parameter | [optional] - **header_1** | **string**| header parameter | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet** | [**\OpenAPI\Client\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | | +| **query_1** | **string**| query parameter | [optional] | +| **header_1** | **string**| header parameter | [optional] | ### Return type @@ -168,9 +168,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **bool**| Input boolean as post body | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | **bool**| Input boolean as post body | [optional] | ### Return type @@ -224,9 +224,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **outer_composite** | [**\OpenAPI\Client\Model\OuterComposite**](../Model/OuterComposite.md)| Input composite as post body | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **outer_composite** | [**\OpenAPI\Client\Model\OuterComposite**](../Model/OuterComposite.md)| Input composite as post body | [optional] | ### Return type @@ -280,9 +280,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **float**| Input number as post body | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | **float**| Input number as post body | [optional] | ### Return type @@ -336,9 +336,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **string**| Input string as post body | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | **string**| Input string as post body | [optional] | ### Return type @@ -392,9 +392,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **outer_object_with_enum_property** | [**\OpenAPI\Client\Model\OuterObjectWithEnumProperty**](../Model/OuterObjectWithEnumProperty.md)| Input enum (int) as post body | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **outer_object_with_enum_property** | [**\OpenAPI\Client\Model\OuterObjectWithEnumProperty**](../Model/OuterObjectWithEnumProperty.md)| Input enum (int) as post body | | ### Return type @@ -447,9 +447,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **\SplFileObject****\SplFileObject**| image to upload | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | **\SplFileObject****\SplFileObject**| image to upload | | ### Return type @@ -502,9 +502,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **file_schema_test_class** | [**\OpenAPI\Client\Model\FileSchemaTestClass**](../Model/FileSchemaTestClass.md)| | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **file_schema_test_class** | [**\OpenAPI\Client\Model\FileSchemaTestClass**](../Model/FileSchemaTestClass.md)| | | ### Return type @@ -556,10 +556,10 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **query** | **string**| | - **user** | [**\OpenAPI\Client\Model\User**](../Model/User.md)| | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **query** | **string**| | | +| **user** | [**\OpenAPI\Client\Model\User**](../Model/User.md)| | | ### Return type @@ -613,9 +613,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**\OpenAPI\Client\Model\Client**](../Model/Client.md)| client model | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **client** | [**\OpenAPI\Client\Model\Client**](../Model/Client.md)| client model | | ### Return type @@ -664,7 +664,7 @@ $apiInstance = new OpenAPI\Client\Api\FakeApi( $config ); $number = 3.4; // float | None -$double = 3.4; // double | None +$double = 3.4; // float | None $pattern_without_delimiter = 'pattern_without_delimiter_example'; // string | None $byte = 'byte_example'; // string | None $integer = 56; // int | None @@ -687,22 +687,22 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **number** | **float**| None | - **double** | **double**| None | - **pattern_without_delimiter** | **string**| None | - **byte** | **string**| None | - **integer** | **int**| None | [optional] - **int32** | **int**| None | [optional] - **int64** | **int**| None | [optional] - **float** | **float**| None | [optional] - **string** | **string**| None | [optional] - **binary** | **\SplFileObject****\SplFileObject**| None | [optional] - **date** | **\DateTime**| None | [optional] - **date_time** | **\DateTime**| None | [optional] - **password** | **string**| None | [optional] - **callback** | **string**| None | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **number** | **float**| None | | +| **double** | **float**| None | | +| **pattern_without_delimiter** | **string**| None | | +| **byte** | **string**| None | | +| **integer** | **int**| None | [optional] | +| **int32** | **int**| None | [optional] | +| **int64** | **int**| None | [optional] | +| **float** | **float**| None | [optional] | +| **string** | **string**| None | [optional] | +| **binary** | **\SplFileObject****\SplFileObject**| None | [optional] | +| **date** | **\DateTime**| None | [optional] | +| **date_time** | **\DateTime**| None | [optional] | +| **password** | **string**| None | [optional] | +| **callback** | **string**| None | [optional] | ### Return type @@ -749,7 +749,7 @@ $enum_header_string = '-efg'; // string | Header parameter enum test (string) $enum_query_string_array = array('enum_query_string_array_example'); // string[] | Query parameter enum test (string array) $enum_query_string = '-efg'; // string | Query parameter enum test (string) $enum_query_integer = 56; // int | Query parameter enum test (double) -$enum_query_double = 3.4; // double | Query parameter enum test (double) +$enum_query_double = 3.4; // float | Query parameter enum test (double) $enum_query_model_array = array(new \OpenAPI\Client\Model\\OpenAPI\Client\Model\EnumClass()); // \OpenAPI\Client\Model\EnumClass[] $enum_form_string_array = array('$'); // string[] | Form parameter enum test (string array) $enum_form_string = '-efg'; // string | Form parameter enum test (string) @@ -763,17 +763,17 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **enum_header_string_array** | [**string[]**](../Model/string.md)| Header parameter enum test (string array) | [optional] - **enum_header_string** | **string**| Header parameter enum test (string) | [optional] [default to '-efg'] - **enum_query_string_array** | [**string[]**](../Model/string.md)| Query parameter enum test (string array) | [optional] - **enum_query_string** | **string**| Query parameter enum test (string) | [optional] [default to '-efg'] - **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] - **enum_query_double** | **double**| Query parameter enum test (double) | [optional] - **enum_query_model_array** | [**\OpenAPI\Client\Model\EnumClass[]**](../Model/\OpenAPI\Client\Model\EnumClass.md)| | [optional] - **enum_form_string_array** | [**string[]**](../Model/string.md)| Form parameter enum test (string array) | [optional] [default to '$'] - **enum_form_string** | **string**| Form parameter enum test (string) | [optional] [default to '-efg'] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **enum_header_string_array** | [**string[]**](../Model/string.md)| Header parameter enum test (string array) | [optional] | +| **enum_header_string** | **string**| Header parameter enum test (string) | [optional] [default to '-efg'] | +| **enum_query_string_array** | [**string[]**](../Model/string.md)| Query parameter enum test (string array) | [optional] | +| **enum_query_string** | **string**| Query parameter enum test (string) | [optional] [default to '-efg'] | +| **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] | +| **enum_query_double** | **float**| Query parameter enum test (double) | [optional] | +| **enum_query_model_array** | [**\OpenAPI\Client\Model\EnumClass[]**](../Model/\OpenAPI\Client\Model\EnumClass.md)| | [optional] | +| **enum_form_string_array** | [**string[]**](../Model/string.md)| Form parameter enum test (string array) | [optional] [default to '$'] | +| **enum_form_string** | **string**| Form parameter enum test (string) | [optional] [default to '-efg'] | ### Return type @@ -819,12 +819,15 @@ $apiInstance = new OpenAPI\Client\Api\FakeApi( new GuzzleHttp\Client(), $config ); -$associate_array['required_string_group'] = 56; // int | Required String in group parameters -$associate_array['required_boolean_group'] = True; // bool | Required Boolean in group parameters -$associate_array['required_int64_group'] = 56; // int | Required Integer in group parameters -$associate_array['string_group'] = 56; // int | String in group parameters -$associate_array['boolean_group'] = True; // bool | Boolean in group parameters -$associate_array['int64_group'] = 56; // int | Integer in group parameters + +$associative_array = [ + 'required_string_group' => 56, // int | Required String in group parameters + 'required_boolean_group' => True, // bool | Required Boolean in group parameters + 'required_int64_group' => 56, // int | Required Integer in group parameters + 'string_group' => 56, // int | String in group parameters + 'boolean_group' => True, // bool | Boolean in group parameters + 'int64_group' => 56, // int | Integer in group parameters +]; try { $apiInstance->testGroupParameters($associate_array); @@ -835,16 +838,16 @@ try { ### Parameters -Note: the input parameter is an associative array with the keys listed as the parameter name below. +Note: the input parameter is an associative array with the keys listed as the parameter names below. -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **required_string_group** | **int**| Required String in group parameters | - **required_boolean_group** | **bool**| Required Boolean in group parameters | - **required_int64_group** | **int**| Required Integer in group parameters | - **string_group** | **int**| String in group parameters | [optional] - **boolean_group** | **bool**| Boolean in group parameters | [optional] - **int64_group** | **int**| Integer in group parameters | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **required_string_group** | **int**| Required String in group parameters | | +| **required_boolean_group** | **bool**| Required Boolean in group parameters | | +| **required_int64_group** | **int**| Required Integer in group parameters | | +| **string_group** | **int**| String in group parameters | [optional] | +| **boolean_group** | **bool**| Boolean in group parameters | [optional] | +| **int64_group** | **int**| Integer in group parameters | [optional] | ### Return type @@ -897,9 +900,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **request_body** | [**array**](../Model/string.md)| request body | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **request_body** | [**array**](../Model/string.md)| request body | | ### Return type @@ -953,10 +956,10 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **param** | **string**| field1 | - **param2** | **string**| field2 | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **param** | **string**| field1 | | +| **param2** | **string**| field2 | | ### Return type @@ -1015,15 +1018,15 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pipe** | [**string[]**](../Model/string.md)| | - **ioutil** | [**string[]**](../Model/string.md)| | - **http** | [**string[]**](../Model/string.md)| | - **url** | [**string[]**](../Model/string.md)| | - **context** | [**string[]**](../Model/string.md)| | - **allow_empty** | **string**| | - **language** | [**array**](../Model/string.md)| | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pipe** | [**string[]**](../Model/string.md)| | | +| **ioutil** | [**string[]**](../Model/string.md)| | | +| **http** | [**string[]**](../Model/string.md)| | | +| **url** | [**string[]**](../Model/string.md)| | | +| **context** | [**string[]**](../Model/string.md)| | | +| **allow_empty** | **string**| | | +| **language** | [**array**](../Model/string.md)| | [optional] | ### Return type diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeClassnameTags123Api.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeClassnameTags123Api.md index 58088ff9de..7519d7924b 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeClassnameTags123Api.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeClassnameTags123Api.md @@ -1,10 +1,10 @@ # OpenAPI\Client\FakeClassnameTags123Api -All URIs are relative to http://petstore.swagger.io:80/v2. +All URIs are relative to http://petstore.swagger.io:80/v2, except if the operation defines another base path. -Method | HTTP request | Description -------------- | ------------- | ------------- -[**testClassname()**](FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**testClassname()**](FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case | ## `testClassname()` @@ -48,9 +48,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**\OpenAPI\Client\Model\Client**](../Model/Client.md)| client model | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **client** | [**\OpenAPI\Client\Model\Client**](../Model/Client.md)| client model | | ### Return type diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/PetApi.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/PetApi.md index eb814406b5..527942413c 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/PetApi.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/PetApi.md @@ -1,18 +1,18 @@ # OpenAPI\Client\PetApi -All URIs are relative to http://petstore.swagger.io:80/v2. +All URIs are relative to http://petstore.swagger.io:80/v2, except if the operation defines another base path. -Method | HTTP request | Description -------------- | ------------- | ------------- -[**addPet()**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -[**deletePet()**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet -[**findPetsByStatus()**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status -[**findPetsByTags()**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags -[**getPetById()**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID -[**updatePet()**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet -[**updatePetWithForm()**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data -[**uploadFile()**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image -[**uploadFileWithRequiredFile()**](PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**addPet()**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store | +| [**deletePet()**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**findPetsByStatus()**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status | +| [**findPetsByTags()**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**getPetById()**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID | +| [**updatePet()**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet | +| [**updatePetWithForm()**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**uploadFile()**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image | +| [**uploadFileWithRequiredFile()**](PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) | ## `addPet()` @@ -20,6 +20,21 @@ Method | HTTP request | Description ```php addPet($pet) ``` +### URI(s): +- http://petstore.swagger.io/v2 - http://path-server-test.petstore.local/v2 - http://{server}.swagger.io:{port}/v2 test server with variables + - Variables: + - server: target server + - Allowed values: + - petstore + - qa-petstore + - dev-petstore + - Default value: petstore + + - port: No description provided + - Allowed values: + - 80 + - 8080 + - Default value: 80 Add a new pet to the store @@ -44,8 +59,12 @@ $apiInstance = new OpenAPI\Client\Api\PetApi( ); $pet = new \OpenAPI\Client\Model\Pet(); // \OpenAPI\Client\Model\Pet | Pet object that needs to be added to the store +$hostIndex = 0; +$variables = [ +]; + try { - $apiInstance->addPet($pet); + $apiInstance->addPet($pet, $hostIndex, $variables); } catch (Exception $e) { echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), PHP_EOL; } @@ -53,9 +72,13 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet** | [**\OpenAPI\Client\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet** | [**\OpenAPI\Client\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | | +| hostIndex | null|int | Host index. Defaults to null. If null, then the library will use $this->hostIndex instead | [optional] | +| variables | array | Associative array of variables to pass to the host. Defaults to empty array. | [optional] | + + ### Return type @@ -113,10 +136,10 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| Pet id to delete | - **api_key** | **string**| | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet_id** | **int**| Pet id to delete | | +| **api_key** | **string**| | [optional] | ### Return type @@ -174,9 +197,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **status** | [**string[]**](../Model/string.md)| Status values that need to be considered for filter | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **status** | [**string[]**](../Model/string.md)| Status values that need to be considered for filter | | ### Return type @@ -234,9 +257,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **tags** | [**string[]**](../Model/string.md)| Tags to filter by | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **tags** | [**string[]**](../Model/string.md)| Tags to filter by | | ### Return type @@ -296,9 +319,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet to return | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet_id** | **int**| ID of pet to return | | ### Return type @@ -322,6 +345,21 @@ Name | Type | Description | Notes ```php updatePet($pet) ``` +### URI(s): +- http://petstore.swagger.io/v2 - http://path-server-test.petstore.local/v2 - http://{server}.swagger.io:{port}/v2 test server with variables + - Variables: + - server: target server + - Allowed values: + - petstore + - qa-petstore + - dev-petstore + - Default value: petstore + + - port: No description provided + - Allowed values: + - 80 + - 8080 + - Default value: 80 Update an existing pet @@ -346,8 +384,12 @@ $apiInstance = new OpenAPI\Client\Api\PetApi( ); $pet = new \OpenAPI\Client\Model\Pet(); // \OpenAPI\Client\Model\Pet | Pet object that needs to be added to the store +$hostIndex = 0; +$variables = [ +]; + try { - $apiInstance->updatePet($pet); + $apiInstance->updatePet($pet, $hostIndex, $variables); } catch (Exception $e) { echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), PHP_EOL; } @@ -355,9 +397,13 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet** | [**\OpenAPI\Client\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet** | [**\OpenAPI\Client\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | | +| hostIndex | null|int | Host index. Defaults to null. If null, then the library will use $this->hostIndex instead | [optional] | +| variables | array | Associative array of variables to pass to the host. Defaults to empty array. | [optional] | + + ### Return type @@ -416,11 +462,11 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet that needs to be updated | - **name** | **string**| Updated name of the pet | [optional] - **status** | **string**| Updated status of the pet | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet_id** | **int**| ID of pet that needs to be updated | | +| **name** | **string**| Updated name of the pet | [optional] | +| **status** | **string**| Updated status of the pet | [optional] | ### Return type @@ -480,11 +526,11 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet to update | - **additional_metadata** | **string**| Additional data to pass to server | [optional] - **file** | **\SplFileObject****\SplFileObject**| file to upload | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet_id** | **int**| ID of pet to update | | +| **additional_metadata** | **string**| Additional data to pass to server | [optional] | +| **file** | **\SplFileObject****\SplFileObject**| file to upload | [optional] | ### Return type @@ -544,11 +590,11 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet_id** | **int**| ID of pet to update | - **required_file** | **\SplFileObject****\SplFileObject**| file to upload | - **additional_metadata** | **string**| Additional data to pass to server | [optional] +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet_id** | **int**| ID of pet to update | | +| **required_file** | **\SplFileObject****\SplFileObject**| file to upload | | +| **additional_metadata** | **string**| Additional data to pass to server | [optional] | ### Return type diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/StoreApi.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/StoreApi.md index f863861fe7..9e88ae63e3 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/StoreApi.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/StoreApi.md @@ -1,13 +1,13 @@ # OpenAPI\Client\StoreApi -All URIs are relative to http://petstore.swagger.io:80/v2. +All URIs are relative to http://petstore.swagger.io:80/v2, except if the operation defines another base path. -Method | HTTP request | Description -------------- | ------------- | ------------- -[**deleteOrder()**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -[**getInventory()**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -[**getOrderById()**](StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID -[**placeOrder()**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**deleteOrder()**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID | +| [**getInventory()**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status | +| [**getOrderById()**](StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID | +| [**placeOrder()**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet | ## `deleteOrder()` @@ -44,9 +44,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **order_id** | **string**| ID of the order that needs to be deleted | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **order_id** | **string**| ID of the order that needs to be deleted | | ### Return type @@ -159,9 +159,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **order_id** | **int**| ID of pet that needs to be fetched | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **order_id** | **int**| ID of pet that needs to be fetched | | ### Return type @@ -215,9 +215,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **order** | [**\OpenAPI\Client\Model\Order**](../Model/Order.md)| order placed for purchasing the pet | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **order** | [**\OpenAPI\Client\Model\Order**](../Model/Order.md)| order placed for purchasing the pet | | ### Return type diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/UserApi.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/UserApi.md index d821635f87..c5ff23c66a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/UserApi.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/UserApi.md @@ -1,17 +1,17 @@ # OpenAPI\Client\UserApi -All URIs are relative to http://petstore.swagger.io:80/v2. +All URIs are relative to http://petstore.swagger.io:80/v2, except if the operation defines another base path. -Method | HTTP request | Description -------------- | ------------- | ------------- -[**createUser()**](UserApi.md#createUser) | **POST** /user | Create user -[**createUsersWithArrayInput()**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array -[**createUsersWithListInput()**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array -[**deleteUser()**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user -[**getUserByName()**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name -[**loginUser()**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system -[**logoutUser()**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session -[**updateUser()**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**createUser()**](UserApi.md#createUser) | **POST** /user | Create user | +| [**createUsersWithArrayInput()**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array | +| [**createUsersWithListInput()**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array | +| [**deleteUser()**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user | +| [**getUserByName()**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name | +| [**loginUser()**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system | +| [**logoutUser()**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session | +| [**updateUser()**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user | ## `createUser()` @@ -48,9 +48,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**\OpenAPI\Client\Model\User**](../Model/User.md)| Created user object | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **user** | [**\OpenAPI\Client\Model\User**](../Model/User.md)| Created user object | | ### Return type @@ -103,9 +103,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**\OpenAPI\Client\Model\User[]**](../Model/User.md)| List of user object | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **user** | [**\OpenAPI\Client\Model\User[]**](../Model/User.md)| List of user object | | ### Return type @@ -158,9 +158,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**\OpenAPI\Client\Model\User[]**](../Model/User.md)| List of user object | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **user** | [**\OpenAPI\Client\Model\User[]**](../Model/User.md)| List of user object | | ### Return type @@ -213,9 +213,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **string**| The name that needs to be deleted | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **username** | **string**| The name that needs to be deleted | | ### Return type @@ -269,9 +269,9 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **string**| The name that needs to be fetched. Use user1 for testing. | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **username** | **string**| The name that needs to be fetched. Use user1 for testing. | | ### Return type @@ -326,10 +326,10 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **string**| The user name for login | - **password** | **string**| The password for login in clear text | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **username** | **string**| The user name for login | | +| **password** | **string**| The password for login in clear text | | ### Return type @@ -435,10 +435,10 @@ try { ### Parameters -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **string**| name that need to be deleted | - **user** | [**\OpenAPI\Client\Model\User**](../Model/User.md)| Updated user object | +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **username** | **string**| name that need to be deleted | | +| **user** | [**\OpenAPI\Client\Model\User**](../Model/User.md)| Updated user object | | ### Return type diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Model/EnumTest.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Model/EnumTest.md index 28781e6a38..d2e02570c5 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Model/EnumTest.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Model/EnumTest.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **enum_string** | **string** | | [optional] **enum_string_required** | **string** | | **enum_integer** | **int** | | [optional] -**enum_number** | **double** | | [optional] +**enum_number** | **float** | | [optional] **outer_enum** | [**\OpenAPI\Client\Model\OuterEnum**](OuterEnum.md) | | [optional] **outer_enum_integer** | [**\OpenAPI\Client\Model\OuterEnumInteger**](OuterEnumInteger.md) | | [optional] **outer_enum_default_value** | [**\OpenAPI\Client\Model\OuterEnumDefaultValue**](OuterEnumDefaultValue.md) | | [optional] diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Model/FormatTest.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Model/FormatTest.md index 2ce2f9dcb8..81f6387a2e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Model/FormatTest.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Model/FormatTest.md @@ -9,7 +9,7 @@ Name | Type | Description | Notes **int64** | **int** | | [optional] **number** | **float** | | **float** | **float** | | [optional] -**double** | **double** | | [optional] +**double** | **float** | | [optional] **decimal** | **float** | | [optional] **string** | **string** | | [optional] **byte** | **string** | | diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php index 489581742d..4915ba3731 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php @@ -183,6 +183,7 @@ class AnotherFakeApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -198,6 +199,7 @@ class AnotherFakeApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = '\OpenAPI\Client\Model\Client'; @@ -218,6 +220,7 @@ class AnotherFakeApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -226,6 +229,7 @@ class AnotherFakeApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -312,6 +316,7 @@ class AnotherFakeApi */ public function call123TestSpecialTagsRequest($client) { + // verify the required parameter 'client' is set if ($client === null || (is_array($client) && count($client) === 0)) { throw new \InvalidArgumentException( @@ -384,10 +389,11 @@ class AnotherFakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'PATCH', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php index ed947bb648..167f7d8409 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php @@ -177,6 +177,7 @@ class DefaultApi } switch($statusCode) { + default: if ('\OpenAPI\Client\Model\FooGetDefaultResponse' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -192,6 +193,7 @@ class DefaultApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = '\OpenAPI\Client\Model\FooGetDefaultResponse'; @@ -212,6 +214,7 @@ class DefaultApi } catch (ApiException $e) { switch ($e->getCode()) { + default: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -220,6 +223,7 @@ class DefaultApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -359,10 +363,11 @@ class DefaultApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php index 71f6a83d4d..dee80e00fd 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php @@ -181,6 +181,7 @@ class FakeApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\HealthCheckResult' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -196,6 +197,7 @@ class FakeApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = '\OpenAPI\Client\Model\HealthCheckResult'; @@ -216,6 +218,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -224,6 +227,7 @@ class FakeApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -367,10 +371,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -450,6 +455,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -529,6 +535,7 @@ class FakeApi */ public function fakeHttpSignatureTestRequest($pet, $query_1 = null, $header_1 = null) { + // verify the required parameter 'pet' is set if ($pet === null || (is_array($pet) && count($pet) === 0)) { throw new \InvalidArgumentException( @@ -536,6 +543,8 @@ class FakeApi ); } + + $resourcePath = '/fake/http-signature-test'; $formParams = []; $queryParams = []; @@ -614,10 +623,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -687,6 +697,7 @@ class FakeApi } switch($statusCode) { + case 200: if ('bool' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -702,6 +713,7 @@ class FakeApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = 'bool'; @@ -722,6 +734,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -730,6 +743,7 @@ class FakeApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -813,6 +827,7 @@ class FakeApi public function fakeOuterBooleanSerializeRequest($body = null) { + $resourcePath = '/fake/outer/boolean'; $formParams = []; $queryParams = []; @@ -878,10 +893,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -951,6 +967,7 @@ class FakeApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\OuterComposite' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -966,6 +983,7 @@ class FakeApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = '\OpenAPI\Client\Model\OuterComposite'; @@ -986,6 +1004,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -994,6 +1013,7 @@ class FakeApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -1077,6 +1097,7 @@ class FakeApi public function fakeOuterCompositeSerializeRequest($outer_composite = null) { + $resourcePath = '/fake/outer/composite'; $formParams = []; $queryParams = []; @@ -1142,10 +1163,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -1215,6 +1237,7 @@ class FakeApi } switch($statusCode) { + case 200: if ('float' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -1230,6 +1253,7 @@ class FakeApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = 'float'; @@ -1250,6 +1274,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -1258,6 +1283,7 @@ class FakeApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -1341,6 +1367,7 @@ class FakeApi public function fakeOuterNumberSerializeRequest($body = null) { + $resourcePath = '/fake/outer/number'; $formParams = []; $queryParams = []; @@ -1406,10 +1433,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -1479,6 +1507,7 @@ class FakeApi } switch($statusCode) { + case 200: if ('string' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -1494,6 +1523,7 @@ class FakeApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = 'string'; @@ -1514,6 +1544,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -1522,6 +1553,7 @@ class FakeApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -1605,6 +1637,7 @@ class FakeApi public function fakeOuterStringSerializeRequest($body = null) { + $resourcePath = '/fake/outer/string'; $formParams = []; $queryParams = []; @@ -1670,10 +1703,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -1743,6 +1777,7 @@ class FakeApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\OuterObjectWithEnumProperty' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -1758,6 +1793,7 @@ class FakeApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = '\OpenAPI\Client\Model\OuterObjectWithEnumProperty'; @@ -1778,6 +1814,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -1786,6 +1823,7 @@ class FakeApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -1868,6 +1906,7 @@ class FakeApi */ public function fakePropertyEnumIntegerSerializeRequest($outer_object_with_enum_property) { + // verify the required parameter 'outer_object_with_enum_property' is set if ($outer_object_with_enum_property === null || (is_array($outer_object_with_enum_property) && count($outer_object_with_enum_property) === 0)) { throw new \InvalidArgumentException( @@ -1940,10 +1979,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -2015,6 +2055,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -2084,6 +2125,7 @@ class FakeApi */ public function testBodyWithBinaryRequest($body) { + // verify the required parameter 'body' is set if ($body === null || (is_array($body) && count($body) === 0)) { throw new \InvalidArgumentException( @@ -2156,10 +2198,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'PUT', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -2231,6 +2274,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -2300,6 +2344,7 @@ class FakeApi */ public function testBodyWithFileSchemaRequest($file_schema_test_class) { + // verify the required parameter 'file_schema_test_class' is set if ($file_schema_test_class === null || (is_array($file_schema_test_class) && count($file_schema_test_class) === 0)) { throw new \InvalidArgumentException( @@ -2372,10 +2417,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'PUT', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -2449,6 +2495,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -2521,12 +2568,14 @@ class FakeApi */ public function testBodyWithQueryParamsRequest($query, $user) { + // verify the required parameter 'query' is set if ($query === null || (is_array($query) && count($query) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $query when calling testBodyWithQueryParams' ); } + // verify the required parameter 'user' is set if ($user === null || (is_array($user) && count($user) === 0)) { throw new \InvalidArgumentException( @@ -2608,10 +2657,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'PUT', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -2685,6 +2735,7 @@ class FakeApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -2700,6 +2751,7 @@ class FakeApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = '\OpenAPI\Client\Model\Client'; @@ -2720,6 +2772,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -2728,6 +2781,7 @@ class FakeApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -2814,6 +2868,7 @@ class FakeApi */ public function testClientModelRequest($client) { + // verify the required parameter 'client' is set if ($client === null || (is_array($client) && count($client) === 0)) { throw new \InvalidArgumentException( @@ -2886,10 +2941,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'PATCH', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -2901,7 +2957,7 @@ class FakeApi * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * @param float $number None (required) - * @param double $double None (required) + * @param float $double None (required) * @param string $pattern_without_delimiter None (required) * @param string $byte None (required) * @param int $integer None (optional) @@ -2930,7 +2986,7 @@ class FakeApi * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * @param float $number None (required) - * @param double $double None (required) + * @param float $double None (required) * @param string $pattern_without_delimiter None (required) * @param string $byte None (required) * @param int $integer None (optional) @@ -2991,6 +3047,8 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + + } throw $e; } @@ -3002,7 +3060,7 @@ class FakeApi * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * @param float $number None (required) - * @param double $double None (required) + * @param float $double None (required) * @param string $pattern_without_delimiter None (required) * @param string $byte None (required) * @param int $integer None (optional) @@ -3035,7 +3093,7 @@ class FakeApi * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * @param float $number None (required) - * @param double $double None (required) + * @param float $double None (required) * @param string $pattern_without_delimiter None (required) * @param string $byte None (required) * @param int $integer None (optional) @@ -3084,7 +3142,7 @@ class FakeApi * Create request for operation 'testEndpointParameters' * * @param float $number None (required) - * @param double $double None (required) + * @param float $double None (required) * @param string $pattern_without_delimiter None (required) * @param string $byte None (required) * @param int $integer None (optional) @@ -3103,6 +3161,7 @@ class FakeApi */ public function testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) { + // verify the required parameter 'number' is set if ($number === null || (is_array($number) && count($number) === 0)) { throw new \InvalidArgumentException( @@ -3116,6 +3175,7 @@ class FakeApi throw new \InvalidArgumentException('invalid value for "$number" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 32.1.'); } + // verify the required parameter 'double' is set if ($double === null || (is_array($double) && count($double) === 0)) { throw new \InvalidArgumentException( @@ -3129,6 +3189,7 @@ class FakeApi throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 67.8.'); } + // verify the required parameter 'pattern_without_delimiter' is set if ($pattern_without_delimiter === null || (is_array($pattern_without_delimiter) && count($pattern_without_delimiter) === 0)) { throw new \InvalidArgumentException( @@ -3139,12 +3200,14 @@ class FakeApi throw new \InvalidArgumentException("invalid value for \"pattern_without_delimiter\" when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z].*/."); } + // verify the required parameter 'byte' is set if ($byte === null || (is_array($byte) && count($byte) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $byte when calling testEndpointParameters' ); } + if ($integer !== null && $integer > 100) { throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 100.'); } @@ -3152,6 +3215,7 @@ class FakeApi throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); } + if ($int32 !== null && $int32 > 200) { throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 200.'); } @@ -3159,14 +3223,21 @@ class FakeApi throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 20.'); } + + if ($float !== null && $float > 987.6) { throw new \InvalidArgumentException('invalid value for "$float" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 987.6.'); } + if ($string !== null && !preg_match("/[a-z]/i", $string)) { throw new \InvalidArgumentException("invalid value for \"string\" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i."); } + + + + if ($password !== null && strlen($password) > 64) { throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 64.'); } @@ -3175,6 +3246,7 @@ class FakeApi } + $resourcePath = '/fake'; $formParams = []; $queryParams = []; @@ -3302,10 +3374,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -3321,7 +3394,7 @@ class FakeApi * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param float $enum_query_double Query parameter enum test (double) (optional) * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array enum_query_model_array (optional) * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') @@ -3345,7 +3418,7 @@ class FakeApi * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param float $enum_query_double Query parameter enum test (double) (optional) * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array (optional) * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') @@ -3397,6 +3470,8 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + + } throw $e; } @@ -3412,7 +3487,7 @@ class FakeApi * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param float $enum_query_double Query parameter enum test (double) (optional) * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array (optional) * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') @@ -3440,7 +3515,7 @@ class FakeApi * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param float $enum_query_double Query parameter enum test (double) (optional) * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array (optional) * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') @@ -3484,7 +3559,7 @@ class FakeApi * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param double $enum_query_double Query parameter enum test (double) (optional) + * @param float $enum_query_double Query parameter enum test (double) (optional) * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array (optional) * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') @@ -3495,6 +3570,15 @@ class FakeApi public function testEnumParametersRequest($enum_header_string_array = null, $enum_header_string = '-efg', $enum_query_string_array = null, $enum_query_string = '-efg', $enum_query_integer = null, $enum_query_double = null, $enum_query_model_array = null, $enum_form_string_array = '$', $enum_form_string = '-efg') { + + + + + + + + + $resourcePath = '/fake'; $formParams = []; $queryParams = []; @@ -3618,10 +3702,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -3711,6 +3796,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -3819,12 +3905,14 @@ class FakeApi 'Missing the required parameter $required_string_group when calling testGroupParameters' ); } + // verify the required parameter 'required_boolean_group' is set if ($required_boolean_group === null || (is_array($required_boolean_group) && count($required_boolean_group) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $required_boolean_group when calling testGroupParameters' ); } + // verify the required parameter 'required_int64_group' is set if ($required_int64_group === null || (is_array($required_int64_group) && count($required_int64_group) === 0)) { throw new \InvalidArgumentException( @@ -3832,6 +3920,9 @@ class FakeApi ); } + + + $resourcePath = '/fake'; $formParams = []; $queryParams = []; @@ -3939,10 +4030,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'DELETE', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -4018,6 +4110,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -4091,6 +4184,7 @@ class FakeApi */ public function testInlineAdditionalPropertiesRequest($request_body) { + // verify the required parameter 'request_body' is set if ($request_body === null || (is_array($request_body) && count($request_body) === 0)) { throw new \InvalidArgumentException( @@ -4163,10 +4257,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -4244,6 +4339,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -4320,12 +4416,14 @@ class FakeApi */ public function testJsonFormDataRequest($param, $param2) { + // verify the required parameter 'param' is set if ($param === null || (is_array($param) && count($param) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $param when calling testJsonFormData' ); } + // verify the required parameter 'param2' is set if ($param2 === null || (is_array($param2) && count($param2) === 0)) { throw new \InvalidArgumentException( @@ -4400,10 +4498,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -4487,6 +4586,7 @@ class FakeApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -4574,36 +4674,42 @@ class FakeApi */ public function testQueryParameterCollectionFormatRequest($pipe, $ioutil, $http, $url, $context, $allow_empty, $language = null) { + // verify the required parameter 'pipe' is set if ($pipe === null || (is_array($pipe) && count($pipe) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $pipe when calling testQueryParameterCollectionFormat' ); } + // verify the required parameter 'ioutil' is set if ($ioutil === null || (is_array($ioutil) && count($ioutil) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $ioutil when calling testQueryParameterCollectionFormat' ); } + // verify the required parameter 'http' is set if ($http === null || (is_array($http) && count($http) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $http when calling testQueryParameterCollectionFormat' ); } + // verify the required parameter 'url' is set if ($url === null || (is_array($url) && count($url) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $url when calling testQueryParameterCollectionFormat' ); } + // verify the required parameter 'context' is set if ($context === null || (is_array($context) && count($context) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $context when calling testQueryParameterCollectionFormat' ); } + // verify the required parameter 'allow_empty' is set if ($allow_empty === null || (is_array($allow_empty) && count($allow_empty) === 0)) { throw new \InvalidArgumentException( @@ -4611,6 +4717,7 @@ class FakeApi ); } + $resourcePath = '/fake/test-query-parameters'; $formParams = []; $queryParams = []; @@ -4733,10 +4840,11 @@ class FakeApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'PUT', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php index c7ba40377b..95575c2f4a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php @@ -183,6 +183,7 @@ class FakeClassnameTags123Api } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -198,6 +199,7 @@ class FakeClassnameTags123Api $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = '\OpenAPI\Client\Model\Client'; @@ -218,6 +220,7 @@ class FakeClassnameTags123Api } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -226,6 +229,7 @@ class FakeClassnameTags123Api ); $e->setResponseObject($data); break; + } throw $e; } @@ -312,6 +316,7 @@ class FakeClassnameTags123Api */ public function testClassnameRequest($client) { + // verify the required parameter 'client' is set if ($client === null || (is_array($client) && count($client) === 0)) { throw new \InvalidArgumentException( @@ -389,10 +394,11 @@ class FakeClassnameTags123Api $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'PATCH', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php index db32afa7fa..68350c3498 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php @@ -120,19 +120,33 @@ class PetApi * * Add a new pet to the store * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \OpenAPI\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return void */ - public function addPet($pet) + public function addPet($pet, ?int $hostIndex = null, array $variables = []) { - $this->addPetWithHttpInfo($pet); + $this->addPetWithHttpInfo($pet, $hostIndex, $variables); } /** @@ -140,19 +154,33 @@ class PetApi * * Add a new pet to the store * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \OpenAPI\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ - public function addPetWithHttpInfo($pet) + public function addPetWithHttpInfo($pet, ?int $hostIndex = null, array $variables = []) { - $request = $this->addPetRequest($pet); + $request = $this->addPetRequest($pet, $hostIndex, $variables); try { $options = $this->createHttpClientOption(); @@ -193,6 +221,8 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { + + } throw $e; } @@ -203,18 +233,32 @@ class PetApi * * Add a new pet to the store * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ - public function addPetAsync($pet) + public function addPetAsync($pet, ?int $hostIndex = null, array $variables = []) { - return $this->addPetAsyncWithHttpInfo($pet) + return $this->addPetAsyncWithHttpInfo($pet, $hostIndex, $variables) ->then( function ($response) { return $response[0]; @@ -227,19 +271,33 @@ class PetApi * * Add a new pet to the store * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ - public function addPetAsyncWithHttpInfo($pet) + public function addPetAsyncWithHttpInfo($pet, ?int $hostIndex = null, array $variables = []) { $returnType = ''; - $request = $this->addPetRequest($pet); + $request = $this->addPetRequest($pet, $hostIndex, $variables); return $this->client ->sendAsync($request, $this->createHttpClientOption()) @@ -267,17 +325,32 @@ class PetApi /** * Create request for operation 'addPet' * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ - public function addPetRequest($pet) + public function addPetRequest($pet, ?int $hostIndex = null, array $variables = []) { + // verify the required parameter 'pet' is set if ($pet === null || (is_array($pet) && count($pet) === 0)) { throw new \InvalidArgumentException( @@ -354,12 +427,17 @@ class PetApi $headers ); - $operationHosts = ["http://petstore.swagger.io/v2", "http://path-server-test.petstore.local/v2"]; - if ($this->hostIndex < 0 || $this->hostIndex >= sizeof($operationHosts)) { - throw new \InvalidArgumentException("Invalid index {$this->hostIndex} when selecting the host. Must be less than ".sizeof($operationHosts)); + # Preserve the original behavior of server indexing. + if ($hostIndex === null) { + $hostIndex = $this->hostIndex; } - $operationHost = $operationHosts[$this->hostIndex]; + $hostSettings = $this->getHostSettingsForaddPet(); + + if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { + throw new \InvalidArgumentException("Invalid index {$hostIndex} when selecting the host. Must be less than ".count($hostSettings)); + } + $operationHost = Configuration::getHostString($hostSettings, $hostIndex, $variables); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', @@ -369,6 +447,48 @@ class PetApi ); } + /** + * Returns an array of host settings for Operation addPet + * + * @return array an array of host settings + */ + protected function getHostSettingsForaddPet(): array + { + return [ + [ + "url" => "http://petstore.swagger.io/v2", + "description" => "No description provided", + ], + [ + "url" => "http://path-server-test.petstore.local/v2", + "description" => "No description provided", + ], + [ + "url" => "http://{server}.swagger.io:{port}/v2", + "description" => "test server with variables", + "variables" => [ + "server" => [ + "description" => "target server", + "default_value" => "petstore", + "enum_values" => [ + "petstore", + "qa-petstore", + "dev-petstore", + ] + ], + "port" => [ + "description" => "No description provided", + "default_value" => "80", + "enum_values" => [ + "80", + "8080", + ] + ] + ] + ] + ]; + } + /** * Operation deletePet * @@ -441,6 +561,8 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { + + } throw $e; } @@ -517,6 +639,7 @@ class PetApi */ public function deletePetRequest($pet_id, $api_key = null) { + // verify the required parameter 'pet_id' is set if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { throw new \InvalidArgumentException( @@ -524,6 +647,7 @@ class PetApi ); } + $resourcePath = '/pet/{petId}'; $formParams = []; $queryParams = []; @@ -599,10 +723,11 @@ class PetApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'DELETE', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -676,6 +801,7 @@ class PetApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\Pet[]' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -691,6 +817,8 @@ class PetApi $response->getStatusCode(), $response->getHeaders() ]; + + } $returnType = '\OpenAPI\Client\Model\Pet[]'; @@ -711,6 +839,7 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -719,6 +848,8 @@ class PetApi ); $e->setResponseObject($data); break; + + } throw $e; } @@ -805,6 +936,7 @@ class PetApi */ public function findPetsByStatusRequest($status) { + // verify the required parameter 'status' is set if ($status === null || (is_array($status) && count($status) === 0)) { throw new \InvalidArgumentException( @@ -884,10 +1016,11 @@ class PetApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -963,6 +1096,7 @@ class PetApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\Pet[]' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -978,6 +1112,8 @@ class PetApi $response->getStatusCode(), $response->getHeaders() ]; + + } $returnType = '\OpenAPI\Client\Model\Pet[]'; @@ -998,6 +1134,7 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -1006,6 +1143,8 @@ class PetApi ); $e->setResponseObject($data); break; + + } throw $e; } @@ -1095,6 +1234,7 @@ class PetApi */ public function findPetsByTagsRequest($tags) { + // verify the required parameter 'tags' is set if ($tags === null || (is_array($tags) && count($tags) === 0)) { throw new \InvalidArgumentException( @@ -1175,10 +1315,11 @@ class PetApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -1252,6 +1393,7 @@ class PetApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\Pet' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -1267,6 +1409,9 @@ class PetApi $response->getStatusCode(), $response->getHeaders() ]; + + + } $returnType = '\OpenAPI\Client\Model\Pet'; @@ -1287,6 +1432,7 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -1295,6 +1441,9 @@ class PetApi ); $e->setResponseObject($data); break; + + + } throw $e; } @@ -1381,6 +1530,7 @@ class PetApi */ public function getPetByIdRequest($pet_id) { + // verify the required parameter 'pet_id' is set if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { throw new \InvalidArgumentException( @@ -1460,10 +1610,11 @@ class PetApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -1474,19 +1625,33 @@ class PetApi * * Update an existing pet * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \OpenAPI\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return void */ - public function updatePet($pet) + public function updatePet($pet, ?int $hostIndex = null, array $variables = []) { - $this->updatePetWithHttpInfo($pet); + $this->updatePetWithHttpInfo($pet, $hostIndex, $variables); } /** @@ -1494,19 +1659,33 @@ class PetApi * * Update an existing pet * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \OpenAPI\Client\ApiException on non-2xx response * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ - public function updatePetWithHttpInfo($pet) + public function updatePetWithHttpInfo($pet, ?int $hostIndex = null, array $variables = []) { - $request = $this->updatePetRequest($pet); + $request = $this->updatePetRequest($pet, $hostIndex, $variables); try { $options = $this->createHttpClientOption(); @@ -1547,6 +1726,10 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { + + + + } throw $e; } @@ -1557,18 +1740,32 @@ class PetApi * * Update an existing pet * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ - public function updatePetAsync($pet) + public function updatePetAsync($pet, ?int $hostIndex = null, array $variables = []) { - return $this->updatePetAsyncWithHttpInfo($pet) + return $this->updatePetAsyncWithHttpInfo($pet, $hostIndex, $variables) ->then( function ($response) { return $response[0]; @@ -1581,19 +1778,33 @@ class PetApi * * Update an existing pet * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \InvalidArgumentException * @return \GuzzleHttp\Promise\PromiseInterface */ - public function updatePetAsyncWithHttpInfo($pet) + public function updatePetAsyncWithHttpInfo($pet, ?int $hostIndex = null, array $variables = []) { $returnType = ''; - $request = $this->updatePetRequest($pet); + $request = $this->updatePetRequest($pet, $hostIndex, $variables); return $this->client ->sendAsync($request, $this->createHttpClientOption()) @@ -1621,17 +1832,32 @@ class PetApi /** * Create request for operation 'updatePet' * - * This operation contains host(s) defined in the OpenAP spec. Use 'hostIndex' to select the host. + * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. + * if needed, use the 'variables' parameter to pass variables to the host. * URL: http://petstore.swagger.io/v2 * URL: http://path-server-test.petstore.local/v2 + * URL: http://{server}.swagger.io:{port}/v2 + * Variables: + * - server: target server + * Allowed values: + * - petstore + * - qa-petstore + * - dev-petstore + * - port: No description provided + * Allowed values: + * - 80 + * - 8080 * * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) + * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead + * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * * @throws \InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ - public function updatePetRequest($pet) + public function updatePetRequest($pet, ?int $hostIndex = null, array $variables = []) { + // verify the required parameter 'pet' is set if ($pet === null || (is_array($pet) && count($pet) === 0)) { throw new \InvalidArgumentException( @@ -1708,12 +1934,17 @@ class PetApi $headers ); - $operationHosts = ["http://petstore.swagger.io/v2", "http://path-server-test.petstore.local/v2"]; - if ($this->hostIndex < 0 || $this->hostIndex >= sizeof($operationHosts)) { - throw new \InvalidArgumentException("Invalid index {$this->hostIndex} when selecting the host. Must be less than ".sizeof($operationHosts)); + # Preserve the original behavior of server indexing. + if ($hostIndex === null) { + $hostIndex = $this->hostIndex; } - $operationHost = $operationHosts[$this->hostIndex]; + $hostSettings = $this->getHostSettingsForupdatePet(); + + if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { + throw new \InvalidArgumentException("Invalid index {$hostIndex} when selecting the host. Must be less than ".count($hostSettings)); + } + $operationHost = Configuration::getHostString($hostSettings, $hostIndex, $variables); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'PUT', @@ -1723,6 +1954,48 @@ class PetApi ); } + /** + * Returns an array of host settings for Operation updatePet + * + * @return array an array of host settings + */ + protected function getHostSettingsForupdatePet(): array + { + return [ + [ + "url" => "http://petstore.swagger.io/v2", + "description" => "No description provided", + ], + [ + "url" => "http://path-server-test.petstore.local/v2", + "description" => "No description provided", + ], + [ + "url" => "http://{server}.swagger.io:{port}/v2", + "description" => "test server with variables", + "variables" => [ + "server" => [ + "description" => "target server", + "default_value" => "petstore", + "enum_values" => [ + "petstore", + "qa-petstore", + "dev-petstore", + ] + ], + "port" => [ + "description" => "No description provided", + "default_value" => "80", + "enum_values" => [ + "80", + "8080", + ] + ] + ] + ] + ]; + } + /** * Operation updatePetWithForm * @@ -1797,6 +2070,8 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { + + } throw $e; } @@ -1876,6 +2151,7 @@ class PetApi */ public function updatePetWithFormRequest($pet_id, $name = null, $status = null) { + // verify the required parameter 'pet_id' is set if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { throw new \InvalidArgumentException( @@ -1883,6 +2159,8 @@ class PetApi ); } + + $resourcePath = '/pet/{petId}'; $formParams = []; $queryParams = []; @@ -1962,10 +2240,11 @@ class PetApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -2043,6 +2322,7 @@ class PetApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\ApiResponse' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -2058,6 +2338,7 @@ class PetApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = '\OpenAPI\Client\Model\ApiResponse'; @@ -2078,6 +2359,7 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -2086,6 +2368,7 @@ class PetApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -2178,6 +2461,7 @@ class PetApi */ public function uploadFileRequest($pet_id, $additional_metadata = null, $file = null) { + // verify the required parameter 'pet_id' is set if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { throw new \InvalidArgumentException( @@ -2185,6 +2469,8 @@ class PetApi ); } + + $resourcePath = '/pet/{petId}/uploadImage'; $formParams = []; $queryParams = []; @@ -2272,10 +2558,11 @@ class PetApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -2353,6 +2640,7 @@ class PetApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\ApiResponse' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -2368,6 +2656,7 @@ class PetApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = '\OpenAPI\Client\Model\ApiResponse'; @@ -2388,6 +2677,7 @@ class PetApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -2396,6 +2686,7 @@ class PetApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -2488,12 +2779,14 @@ class PetApi */ public function uploadFileWithRequiredFileRequest($pet_id, $required_file, $additional_metadata = null) { + // verify the required parameter 'pet_id' is set if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $pet_id when calling uploadFileWithRequiredFile' ); } + // verify the required parameter 'required_file' is set if ($required_file === null || (is_array($required_file) && count($required_file) === 0)) { throw new \InvalidArgumentException( @@ -2501,6 +2794,7 @@ class PetApi ); } + $resourcePath = '/fake/{petId}/uploadImageWithRequiredFile'; $formParams = []; $queryParams = []; @@ -2588,10 +2882,11 @@ class PetApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php index 99a04bfa47..69b96af3a9 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php @@ -185,6 +185,8 @@ class StoreApi } catch (ApiException $e) { switch ($e->getCode()) { + + } throw $e; } @@ -258,6 +260,7 @@ class StoreApi */ public function deleteOrderRequest($order_id) { + // verify the required parameter 'order_id' is set if ($order_id === null || (is_array($order_id) && count($order_id) === 0)) { throw new \InvalidArgumentException( @@ -332,10 +335,11 @@ class StoreApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'DELETE', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -407,12 +411,13 @@ class StoreApi } switch($statusCode) { + case 200: if ('array' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer } else { $content = (string) $response->getBody(); - if ('array<string,int>' !== 'string') { + if ('array' !== 'string') { $content = json_decode($content); } } @@ -422,6 +427,7 @@ class StoreApi $response->getStatusCode(), $response->getHeaders() ]; + } $returnType = 'array'; @@ -442,6 +448,7 @@ class StoreApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -450,6 +457,7 @@ class StoreApi ); $e->setResponseObject($data); break; + } throw $e; } @@ -598,10 +606,11 @@ class StoreApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -675,6 +684,7 @@ class StoreApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\Order' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -690,6 +700,9 @@ class StoreApi $response->getStatusCode(), $response->getHeaders() ]; + + + } $returnType = '\OpenAPI\Client\Model\Order'; @@ -710,6 +723,7 @@ class StoreApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -718,6 +732,9 @@ class StoreApi ); $e->setResponseObject($data); break; + + + } throw $e; } @@ -804,6 +821,7 @@ class StoreApi */ public function getOrderByIdRequest($order_id) { + // verify the required parameter 'order_id' is set if ($order_id === null || (is_array($order_id) && count($order_id) === 0)) { throw new \InvalidArgumentException( @@ -885,10 +903,11 @@ class StoreApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -962,6 +981,7 @@ class StoreApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\Order' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -977,6 +997,8 @@ class StoreApi $response->getStatusCode(), $response->getHeaders() ]; + + } $returnType = '\OpenAPI\Client\Model\Order'; @@ -997,6 +1019,7 @@ class StoreApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -1005,6 +1028,8 @@ class StoreApi ); $e->setResponseObject($data); break; + + } throw $e; } @@ -1091,6 +1116,7 @@ class StoreApi */ public function placeOrderRequest($order) { + // verify the required parameter 'order' is set if ($order === null || (is_array($order) && count($order) === 0)) { throw new \InvalidArgumentException( @@ -1163,10 +1189,11 @@ class StoreApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php index c3a3e5d26f..e8f6689b59 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php @@ -185,6 +185,7 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -258,6 +259,7 @@ class UserApi */ public function createUserRequest($user) { + // verify the required parameter 'user' is set if ($user === null || (is_array($user) && count($user) === 0)) { throw new \InvalidArgumentException( @@ -330,10 +332,11 @@ class UserApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -409,6 +412,7 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -482,6 +486,7 @@ class UserApi */ public function createUsersWithArrayInputRequest($user) { + // verify the required parameter 'user' is set if ($user === null || (is_array($user) && count($user) === 0)) { throw new \InvalidArgumentException( @@ -554,10 +559,11 @@ class UserApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -633,6 +639,7 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -706,6 +713,7 @@ class UserApi */ public function createUsersWithListInputRequest($user) { + // verify the required parameter 'user' is set if ($user === null || (is_array($user) && count($user) === 0)) { throw new \InvalidArgumentException( @@ -778,10 +786,11 @@ class UserApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'POST', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -857,6 +866,8 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { + + } throw $e; } @@ -930,6 +941,7 @@ class UserApi */ public function deleteUserRequest($username) { + // verify the required parameter 'username' is set if ($username === null || (is_array($username) && count($username) === 0)) { throw new \InvalidArgumentException( @@ -1004,10 +1016,11 @@ class UserApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'DELETE', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -1081,6 +1094,7 @@ class UserApi } switch($statusCode) { + case 200: if ('\OpenAPI\Client\Model\User' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -1096,6 +1110,9 @@ class UserApi $response->getStatusCode(), $response->getHeaders() ]; + + + } $returnType = '\OpenAPI\Client\Model\User'; @@ -1116,6 +1133,7 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -1124,6 +1142,9 @@ class UserApi ); $e->setResponseObject($data); break; + + + } throw $e; } @@ -1210,6 +1231,7 @@ class UserApi */ public function getUserByNameRequest($username) { + // verify the required parameter 'username' is set if ($username === null || (is_array($username) && count($username) === 0)) { throw new \InvalidArgumentException( @@ -1284,10 +1306,11 @@ class UserApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -1363,6 +1386,7 @@ class UserApi } switch($statusCode) { + case 200: if ('string' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer @@ -1378,6 +1402,8 @@ class UserApi $response->getStatusCode(), $response->getHeaders() ]; + + } $returnType = 'string'; @@ -1398,6 +1424,7 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { + case 200: $data = ObjectSerializer::deserialize( $e->getResponseBody(), @@ -1406,6 +1433,8 @@ class UserApi ); $e->setResponseObject($data); break; + + } throw $e; } @@ -1495,12 +1524,14 @@ class UserApi */ public function loginUserRequest($username, $password) { + // verify the required parameter 'username' is set if ($username === null || (is_array($username) && count($username) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $username when calling loginUser' ); } + // verify the required parameter 'password' is set if ($password === null || (is_array($password) && count($password) === 0)) { throw new \InvalidArgumentException( @@ -1585,10 +1616,11 @@ class UserApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -1662,6 +1694,7 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { + } throw $e; } @@ -1792,10 +1825,11 @@ class UserApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); @@ -1873,6 +1907,8 @@ class UserApi } catch (ApiException $e) { switch ($e->getCode()) { + + } throw $e; } @@ -1949,12 +1985,14 @@ class UserApi */ public function updateUserRequest($username, $user) { + // verify the required parameter 'username' is set if ($username === null || (is_array($username) && count($username) === 0)) { throw new \InvalidArgumentException( 'Missing the required parameter $username when calling updateUser' ); } + // verify the required parameter 'user' is set if ($user === null || (is_array($user) && count($user) === 0)) { throw new \InvalidArgumentException( @@ -2035,10 +2073,11 @@ class UserApi $headers ); + $operationHost = $this->config->getHost(); $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'PUT', - $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php index f33c394db7..afa867f44e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php @@ -516,32 +516,31 @@ class Configuration } /** - * Returns URL based on the index and variables - * - * @param int $index index of the host settings - * @param array|null $variables hash of variable and the corresponding value (optional) - * @return string URL based on host settings - */ - public function getHostFromSettings($index, $variables = null) + * Returns URL based on host settings, index and variables + * + * @param array $hostSettings array of host settings, generated from getHostSettings() or equivalent from the API clients + * @param int $hostIndex index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public static function getHostString(array $hostsSettings, $hostIndex, array $variables = null) { if (null === $variables) { $variables = []; } - $hosts = $this->getHostSettings(); - // check array index out of bound - if ($index < 0 || $index >= sizeof($hosts)) { - throw new \InvalidArgumentException("Invalid index $index when selecting the host. Must be less than ".sizeof($hosts)); + if ($hostIndex < 0 || $hostIndex >= count($hostsSettings)) { + throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostsSettings)); } - $host = $hosts[$index]; + $host = $hostsSettings[$hostIndex]; $url = $host["url"]; // go through variable and assign a value foreach ($host["variables"] ?? [] as $name => $variable) { if (array_key_exists($name, $variables)) { // check to see if it's in the variables provided by the user - if (in_array($variables[$name], $variable["enum_values"], true)) { // check to see if the value is in the enum + if (!isset($variable['enum_values']) || in_array($variables[$name], $variable["enum_values"], true)) { // check to see if the value is in the enum $url = str_replace("{".$name."}", $variables[$name], $url); } else { throw new \InvalidArgumentException("The variable `$name` in the host URL has invalid value ".$variables[$name].". Must be ".join(',', $variable["enum_values"])."."); @@ -554,4 +553,16 @@ class Configuration return $url; } + + /** + * Returns URL based on the index and variables + * + * @param int $index index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public function getHostFromSettings($index, $variables = null) + { + return self::getHostString($this->getHostSettings(), $index, $variables); + } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php index f7c5f4aebf..b541468e4c 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php @@ -130,6 +130,16 @@ class AdditionalPropertiesClass implements ModelInterface, ArrayAccess, \JsonSer return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php index 796c382166..71fd035afc 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php @@ -80,7 +80,7 @@ class AllOfWithSingleRef implements ModelInterface, ArrayAccess, \JsonSerializab */ protected static array $openAPINullables = [ 'username' => false, - 'single_ref_type' => true + 'single_ref_type' => false ]; /** @@ -130,6 +130,16 @@ class AllOfWithSingleRef implements ModelInterface, ArrayAccess, \JsonSerializab return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * @@ -336,14 +346,7 @@ class AllOfWithSingleRef implements ModelInterface, ArrayAccess, \JsonSerializab { if (is_null($single_ref_type)) { - array_push($this->openAPINullablesSetToNull, 'single_ref_type'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('single_ref_type', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } + throw new \InvalidArgumentException('non-nullable single_ref_type cannot be null'); } $this->container['single_ref_type'] = $single_ref_type; diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php index 589c3fbc1a..293e2014e0 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php @@ -130,6 +130,16 @@ class Animal implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php index 96596b51c0..b7e545ec52 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php @@ -133,6 +133,16 @@ class ApiResponse implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php index 039424f8c2..79c45b8bb5 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -127,6 +127,16 @@ class ArrayOfArrayOfNumberOnly implements ModelInterface, ArrayAccess, \JsonSeri return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php index 9e8c7826ce..a05f69244c 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php @@ -127,6 +127,16 @@ class ArrayOfNumberOnly implements ModelInterface, ArrayAccess, \JsonSerializabl return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php index 0c6cd79575..f69413fd44 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php @@ -133,6 +133,16 @@ class ArrayTest implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php index 8250f3c658..d963aac7dd 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php @@ -142,6 +142,16 @@ class Capitalization implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php index fe84f0ecdb..b2c9b094e8 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php @@ -125,6 +125,16 @@ class Cat extends Animal return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php index 6ecfa9b1e5..a2241bc428 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php @@ -127,6 +127,16 @@ class CatAllOf implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php index 1dd97411a6..66ffaa9016 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php @@ -130,6 +130,16 @@ class Category implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php index e5c974d9fa..6c413543fe 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php @@ -128,6 +128,16 @@ class ClassModel implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php index 57418d784f..7393d8cf12 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php @@ -127,6 +127,16 @@ class Client implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DeprecatedObject.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DeprecatedObject.php index 22308c5a60..ace7be3042 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DeprecatedObject.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DeprecatedObject.php @@ -127,6 +127,16 @@ class DeprecatedObject implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php index b5a1b725dd..2471b0d81d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php @@ -125,6 +125,16 @@ class Dog extends Animal return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php index c8cc0ed3da..984b6f83a0 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php @@ -127,6 +127,16 @@ class DogAllOf implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php index d54be74e58..f967706f66 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php @@ -130,6 +130,16 @@ class EnumArrays implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php index 9613483682..593b60eddb 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php @@ -60,7 +60,7 @@ class EnumTest implements ModelInterface, ArrayAccess, \JsonSerializable 'enum_string' => 'string', 'enum_string_required' => 'string', 'enum_integer' => 'int', - 'enum_number' => 'double', + 'enum_number' => 'float', 'outer_enum' => '\OpenAPI\Client\Model\OuterEnum', 'outer_enum_integer' => '\OpenAPI\Client\Model\OuterEnumInteger', 'outer_enum_default_value' => '\OpenAPI\Client\Model\OuterEnumDefaultValue', @@ -148,6 +148,16 @@ class EnumTest implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * @@ -551,7 +561,7 @@ class EnumTest implements ModelInterface, ArrayAccess, \JsonSerializable /** * Gets enum_number * - * @return double|null + * @return float|null */ public function getEnumNumber() { @@ -561,7 +571,7 @@ class EnumTest implements ModelInterface, ArrayAccess, \JsonSerializable /** * Sets enum_number * - * @param double|null $enum_number enum_number + * @param float|null $enum_number enum_number * * @return self */ diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php index ccc4ae03b7..2271d772ea 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php @@ -128,6 +128,16 @@ class File implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php index de310394cf..036ccf89b1 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php @@ -130,6 +130,16 @@ class FileSchemaTestClass implements ModelInterface, ArrayAccess, \JsonSerializa return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php index 71c500a86b..65c74825c4 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php @@ -127,6 +127,16 @@ class Foo implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php index 2457ff018c..9e199eda35 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php @@ -127,6 +127,16 @@ class FooGetDefaultResponse implements ModelInterface, ArrayAccess, \JsonSeriali return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php index 28d23d0620..42d9ec950f 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php @@ -62,7 +62,7 @@ class FormatTest implements ModelInterface, ArrayAccess, \JsonSerializable 'int64' => 'int', 'number' => 'float', 'float' => 'float', - 'double' => 'double', + 'double' => 'float', 'decimal' => 'float', 'string' => 'string', 'byte' => 'string', @@ -172,6 +172,16 @@ class FormatTest implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * @@ -636,7 +646,7 @@ class FormatTest implements ModelInterface, ArrayAccess, \JsonSerializable /** * Gets double * - * @return double|null + * @return float|null */ public function getDouble() { @@ -646,7 +656,7 @@ class FormatTest implements ModelInterface, ArrayAccess, \JsonSerializable /** * Sets double * - * @param double|null $double double + * @param float|null $double double * * @return self */ diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php index 067071d158..5ef1a1b78c 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php @@ -130,6 +130,16 @@ class HasOnlyReadOnly implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php index 29db696f29..53fc4e5660 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php @@ -128,6 +128,16 @@ class HealthCheckResult implements ModelInterface, ArrayAccess, \JsonSerializabl return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php deleted file mode 100644 index cdc77c805e..0000000000 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php +++ /dev/null @@ -1,320 +0,0 @@ - - */ -class InlineResponseDefault implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'inline_response_default'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'string' => '\OpenAPI\Client\Model\Foo' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'string' => null - ]; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @return array - */ - public static function openAPITypes() - { - return self::$openAPITypes; - } - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @return array - */ - public static function openAPIFormats() - { - return self::$openAPIFormats; - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'string' => 'string' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'string' => 'setString' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'string' => 'getString' - ]; - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @return array - */ - public static function attributeMap() - { - return self::$attributeMap; - } - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @return array - */ - public static function setters() - { - return self::$setters; - } - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @return array - */ - public static function getters() - { - return self::$getters; - } - - /** - * The original name of the model. - * - * @return string - */ - public function getModelName() - { - return self::$openAPIModelName; - } - - - /** - * Associative array for storing property values - * - * @var mixed[] - */ - protected $container = []; - - /** - * Constructor - * - * @param mixed[] $data Associated array of property values - * initializing the model - */ - public function __construct(array $data = null) - { - $this->container['string'] = $data['string'] ?? null; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - return $invalidProperties; - } - - /** - * Validate all the properties in the model - * return true if all passed - * - * @return bool True if all properties are valid - */ - public function valid() - { - return count($this->listInvalidProperties()) === 0; - } - - - /** - * Gets string - * - * @return \OpenAPI\Client\Model\Foo|null - */ - public function getString() - { - return $this->container['string']; - } - - /** - * Sets string - * - * @param \OpenAPI\Client\Model\Foo|null $string string - * - * @return self - */ - public function setString($string) - { - $this->container['string'] = $string; - - return $this; - } - /** - * Returns true if offset exists. False otherwise. - * - * @param integer $offset Offset - * - * @return boolean - */ - public function offsetExists($offset): bool - { - return isset($this->container[$offset]); - } - - /** - * Gets offset. - * - * @param integer $offset Offset - * - * @return mixed|null - */ - #[\ReturnTypeWillChange] - public function offsetGet($offset) - { - return $this->container[$offset] ?? null; - } - - /** - * Sets value based on offset. - * - * @param int|null $offset Offset - * @param mixed $value Value to be set - * - * @return void - */ - public function offsetSet($offset, $value): void - { - if (is_null($offset)) { - $this->container[] = $value; - } else { - $this->container[$offset] = $value; - } - } - - /** - * Unsets offset. - * - * @param integer $offset Offset - * - * @return void - */ - public function offsetUnset($offset): void - { - unset($this->container[$offset]); - } - - /** - * Serializes the object to a value that can be serialized natively by json_encode(). - * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php - * - * @return mixed Returns data which can be serialized by json_encode(), which is a value - * of any type other than a resource. - */ - #[\ReturnTypeWillChange] - public function jsonSerialize() - { - return ObjectSerializer::sanitizeForSerialization($this); - } - - /** - * Gets the string presentation of the object - * - * @return string - */ - public function __toString() - { - return json_encode( - ObjectSerializer::sanitizeForSerialization($this), - JSON_PRETTY_PRINT - ); - } - - /** - * Gets a header-safe presentation of the object - * - * @return string - */ - public function toHeaderValue() - { - return json_encode(ObjectSerializer::sanitizeForSerialization($this)); - } -} - - diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php index 03505bfaf7..c544544639 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php @@ -136,6 +136,16 @@ class MapTest implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index c629eac4c8..e717d540f8 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -133,6 +133,16 @@ class MixedPropertiesAndAdditionalPropertiesClass implements ModelInterface, Arr return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php index 1b3d8d99b3..88ebb9430b 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php @@ -131,6 +131,16 @@ class Model200Response implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php index 3e9289d08d..f42dd8faf7 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php @@ -127,6 +127,16 @@ class ModelList implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php index 3995465196..ca8b3c445f 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php @@ -128,6 +128,16 @@ class ModelReturn implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php index 81b2fcfe54..5ab1bdf33e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php @@ -137,6 +137,16 @@ class Name implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php index 44a21977e6..66ce61a327 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php @@ -160,6 +160,16 @@ class NullableClass implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php index 00b8ad554c..d1312b1413 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php @@ -127,6 +127,16 @@ class NumberOnly implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php index 0ff899b8e5..8e45274308 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php @@ -136,6 +136,16 @@ class ObjectWithDeprecatedFields implements ModelInterface, ArrayAccess, \JsonSe return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php index 09ef1515d9..bf51536616 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php @@ -142,6 +142,16 @@ class Order implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php index 1233ca75e8..c1dcc513a2 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php @@ -133,6 +133,16 @@ class OuterComposite implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php index b2bcfc278a..b5a879f34e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php @@ -127,6 +127,16 @@ class OuterObjectWithEnumProperty implements ModelInterface, ArrayAccess, \JsonS return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php index 18569e3ff9..a8dd4688ca 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php @@ -142,6 +142,16 @@ class Pet implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php index 2baad5b913..5e111a8864 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php @@ -130,6 +130,16 @@ class ReadOnlyFirst implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php index bf00f21403..f2d7ed0566 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php @@ -127,6 +127,16 @@ class SpecialModelName implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php index 3594c8ecf0..d15d979708 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php @@ -130,6 +130,16 @@ class Tag implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php index 1c45b0eb3b..f64f39237d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php @@ -148,6 +148,16 @@ class User implements ModelInterface, ArrayAccess, \JsonSerializable return $this->openAPINullablesSetToNull; } + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + /** * Checks if a property is nullable * diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php index cda20489c2..0ed14361db 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php @@ -87,7 +87,7 @@ class ObjectSerializer foreach ($data::openAPITypes() as $property => $openAPIType) { $getter = $data::getters()[$property]; $value = $data->$getter(); - if ($value !== null && !in_array($openAPIType, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + if ($value !== null && !in_array($openAPIType, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { $callable = [$openAPIType, 'getAllowableEnumValues']; if (is_callable($callable)) { /** array $callable */ @@ -189,6 +189,11 @@ class ObjectSerializer } } + # Handle DateTime objects in query + if($openApiType === "\\DateTime" && $value instanceof \DateTime) { + return ["{$paramName}" => $value->format(self::$dateTimeFormat)]; + } + $query = []; $value = (in_array($openApiType, ['object', 'array'], true)) ? (array)$value : $value; @@ -441,7 +446,7 @@ class ObjectSerializer } /** @psalm-suppress ParadoxicalCondition */ - if (in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + if (in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { settype($data, $class); return $data; } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Api/AnotherFakeApiTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Api/AnotherFakeApiTest.php index e27cb94acc..6cee518588 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Api/AnotherFakeApiTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Api/AnotherFakeApiTest.php @@ -1,7 +1,7 @@ markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Api/DefaultApiTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Api/DefaultApiTest.php index cc8d162dad..44ca443399 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Api/DefaultApiTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Api/DefaultApiTest.php @@ -1,7 +1,7 @@ markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Api/FakeApiTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Api/FakeApiTest.php index fbd7182acd..953145478b 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Api/FakeApiTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Api/FakeApiTest.php @@ -1,7 +1,7 @@ markTestIncomplete('Not implemented'); } /** @@ -90,6 +91,8 @@ class FakeApiTest extends TestCase */ public function testFakeHttpSignatureTest() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -100,6 +103,8 @@ class FakeApiTest extends TestCase */ public function testFakeOuterBooleanSerialize() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -110,6 +115,8 @@ class FakeApiTest extends TestCase */ public function testFakeOuterCompositeSerialize() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -120,6 +127,8 @@ class FakeApiTest extends TestCase */ public function testFakeOuterNumberSerialize() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -130,6 +139,32 @@ class FakeApiTest extends TestCase */ public function testFakeOuterStringSerialize() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } + + /** + * Test case for fakePropertyEnumIntegerSerialize + * + * . + * + */ + public function testFakePropertyEnumIntegerSerialize() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } + + /** + * Test case for testBodyWithBinary + * + * . + * + */ + public function testTestBodyWithBinary() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -140,6 +175,8 @@ class FakeApiTest extends TestCase */ public function testTestBodyWithFileSchema() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -150,6 +187,8 @@ class FakeApiTest extends TestCase */ public function testTestBodyWithQueryParams() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -160,6 +199,8 @@ class FakeApiTest extends TestCase */ public function testTestClientModel() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -170,6 +211,8 @@ class FakeApiTest extends TestCase */ public function testTestEndpointParameters() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -180,6 +223,8 @@ class FakeApiTest extends TestCase */ public function testTestEnumParameters() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -190,6 +235,8 @@ class FakeApiTest extends TestCase */ public function testTestGroupParameters() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -200,6 +247,8 @@ class FakeApiTest extends TestCase */ public function testTestInlineAdditionalProperties() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -210,6 +259,8 @@ class FakeApiTest extends TestCase */ public function testTestJsonFormData() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -220,5 +271,7 @@ class FakeApiTest extends TestCase */ public function testTestQueryParameterCollectionFormat() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Api/FakeClassnameTags123ApiTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Api/FakeClassnameTags123ApiTest.php index da81da6bb3..6ea65e4d6e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Api/FakeClassnameTags123ApiTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Api/FakeClassnameTags123ApiTest.php @@ -1,7 +1,7 @@ markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Api/PetApiTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Api/PetApiTest.php index eb4cdb92bf..06d61a51b7 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Api/PetApiTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Api/PetApiTest.php @@ -1,7 +1,7 @@ markTestIncomplete('Not implemented'); } /** @@ -90,6 +91,8 @@ class PetApiTest extends TestCase */ public function testDeletePet() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -100,6 +103,8 @@ class PetApiTest extends TestCase */ public function testFindPetsByStatus() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -110,6 +115,8 @@ class PetApiTest extends TestCase */ public function testFindPetsByTags() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -120,6 +127,8 @@ class PetApiTest extends TestCase */ public function testGetPetById() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -130,6 +139,8 @@ class PetApiTest extends TestCase */ public function testUpdatePet() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -140,6 +151,8 @@ class PetApiTest extends TestCase */ public function testUpdatePetWithForm() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -150,6 +163,8 @@ class PetApiTest extends TestCase */ public function testUploadFile() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -160,5 +175,7 @@ class PetApiTest extends TestCase */ public function testUploadFileWithRequiredFile() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Api/StoreApiTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Api/StoreApiTest.php index 2259f61d7a..cf2e8b9d1e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Api/StoreApiTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Api/StoreApiTest.php @@ -1,7 +1,7 @@ markTestIncomplete('Not implemented'); } /** @@ -90,6 +91,8 @@ class StoreApiTest extends TestCase */ public function testGetInventory() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -100,6 +103,8 @@ class StoreApiTest extends TestCase */ public function testGetOrderById() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -110,5 +115,7 @@ class StoreApiTest extends TestCase */ public function testPlaceOrder() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Api/UserApiTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Api/UserApiTest.php index ede511de41..43c14fe848 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Api/UserApiTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Api/UserApiTest.php @@ -1,7 +1,7 @@ markTestIncomplete('Not implemented'); } /** @@ -90,6 +91,8 @@ class UserApiTest extends TestCase */ public function testCreateUsersWithArrayInput() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -100,6 +103,8 @@ class UserApiTest extends TestCase */ public function testCreateUsersWithListInput() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -110,6 +115,8 @@ class UserApiTest extends TestCase */ public function testDeleteUser() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -120,6 +127,8 @@ class UserApiTest extends TestCase */ public function testGetUserByName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -130,6 +139,8 @@ class UserApiTest extends TestCase */ public function testLoginUser() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -140,6 +151,8 @@ class UserApiTest extends TestCase */ public function testLogoutUser() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -150,5 +163,7 @@ class UserApiTest extends TestCase */ public function testUpdateUser() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/AdditionalPropertiesAnyTypeTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/AdditionalPropertiesAnyTypeTest.php deleted file mode 100644 index c818b85c9f..0000000000 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/AdditionalPropertiesAnyTypeTest.php +++ /dev/null @@ -1,87 +0,0 @@ -markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class AdditionalPropertiesClassTest extends TestCase */ public function testPropertyMapProperty() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,5 +93,7 @@ class AdditionalPropertiesClassTest extends TestCase */ public function testPropertyMapOfMapProperty() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/AdditionalPropertiesIntegerTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/AdditionalPropertiesIntegerTest.php deleted file mode 100644 index a8effc0606..0000000000 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/AdditionalPropertiesIntegerTest.php +++ /dev/null @@ -1,87 +0,0 @@ -markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class AnimalTest extends TestCase */ public function testPropertyClassName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,5 +93,7 @@ class AnimalTest extends TestCase */ public function testPropertyColor() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ApiResponseTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ApiResponseTest.php index 21e716d187..71ffed8161 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ApiResponseTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ApiResponseTest.php @@ -2,7 +2,7 @@ /** * ApiResponseTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class ApiResponseTest extends TestCase */ public function testApiResponse() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class ApiResponseTest extends TestCase */ public function testPropertyCode() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class ApiResponseTest extends TestCase */ public function testPropertyType() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,5 +102,7 @@ class ApiResponseTest extends TestCase */ public function testPropertyMessage() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php index edb49953d1..ff497f4ee5 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayOfArrayOfNumberOnlyTest.php @@ -2,7 +2,7 @@ /** * ArrayOfArrayOfNumberOnlyTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class ArrayOfArrayOfNumberOnlyTest extends TestCase */ public function testArrayOfArrayOfNumberOnly() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class ArrayOfArrayOfNumberOnlyTest extends TestCase */ public function testPropertyArrayArrayNumber() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayOfNumberOnlyTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayOfNumberOnlyTest.php index 4b2059689c..244c3ba6c1 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayOfNumberOnlyTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayOfNumberOnlyTest.php @@ -2,7 +2,7 @@ /** * ArrayOfNumberOnlyTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class ArrayOfNumberOnlyTest extends TestCase */ public function testArrayOfNumberOnly() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class ArrayOfNumberOnlyTest extends TestCase */ public function testPropertyArrayNumber() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayTestTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayTestTest.php index 498ba99a1e..ced0c66807 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayTestTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ArrayTestTest.php @@ -2,7 +2,7 @@ /** * ArrayTestTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class ArrayTestTest extends TestCase */ public function testArrayTest() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class ArrayTestTest extends TestCase */ public function testPropertyArrayOfString() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class ArrayTestTest extends TestCase */ public function testPropertyArrayArrayOfInteger() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,5 +102,7 @@ class ArrayTestTest extends TestCase */ public function testPropertyArrayArrayOfModel() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/BigCatAllOfTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/BigCatAllOfTest.php deleted file mode 100644 index af0dad92c1..0000000000 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/BigCatAllOfTest.php +++ /dev/null @@ -1,87 +0,0 @@ -markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class CapitalizationTest extends TestCase */ public function testPropertySmallCamel() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class CapitalizationTest extends TestCase */ public function testPropertyCapitalCamel() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,6 +102,8 @@ class CapitalizationTest extends TestCase */ public function testPropertySmallSnake() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -104,6 +111,8 @@ class CapitalizationTest extends TestCase */ public function testPropertyCapitalSnake() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -111,6 +120,8 @@ class CapitalizationTest extends TestCase */ public function testPropertyScaEthFlowPoints() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -118,5 +129,7 @@ class CapitalizationTest extends TestCase */ public function testPropertyAttName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/CatAllOfTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/CatAllOfTest.php index 17db0e9005..469a2cbe3e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/CatAllOfTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/CatAllOfTest.php @@ -2,7 +2,7 @@ /** * CatAllOfTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class CatAllOfTest extends TestCase */ public function testCatAllOf() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class CatAllOfTest extends TestCase */ public function testPropertyDeclawed() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/CatTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/CatTest.php index c0f8d54589..000182efc6 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/CatTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/CatTest.php @@ -2,7 +2,7 @@ /** * CatTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class CatTest extends TestCase */ public function testCat() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class CatTest extends TestCase */ public function testPropertyDeclawed() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/CategoryTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/CategoryTest.php index 116dc3a242..1ae2588a26 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/CategoryTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/CategoryTest.php @@ -2,7 +2,7 @@ /** * CategoryTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class CategoryTest extends TestCase */ public function testCategory() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class CategoryTest extends TestCase */ public function testPropertyId() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,5 +93,7 @@ class CategoryTest extends TestCase */ public function testPropertyName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ClassModelTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ClassModelTest.php index 661706de45..9258531c89 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ClassModelTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ClassModelTest.php @@ -2,7 +2,7 @@ /** * ClassModelTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class ClassModelTest extends TestCase */ public function testClassModel() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class ClassModelTest extends TestCase */ public function testPropertyClass() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ClientTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ClientTest.php index b68aedcc37..a975446ae4 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ClientTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ClientTest.php @@ -2,7 +2,7 @@ /** * ClientTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class ClientTest extends TestCase */ public function testClient() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class ClientTest extends TestCase */ public function testPropertyClient() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/DeprecatedObjectTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/DeprecatedObjectTest.php index a32076925f..e958e25861 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/DeprecatedObjectTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/DeprecatedObjectTest.php @@ -2,7 +2,7 @@ /** * DeprecatedObjectTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.2.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/DogAllOfTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/DogAllOfTest.php index cd22f758c9..efd7ae0ec4 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/DogAllOfTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/DogAllOfTest.php @@ -2,7 +2,7 @@ /** * DogAllOfTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class DogAllOfTest extends TestCase */ public function testDogAllOf() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class DogAllOfTest extends TestCase */ public function testPropertyBreed() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/DogTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/DogTest.php index 5618d4907a..154ec07823 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/DogTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/DogTest.php @@ -2,7 +2,7 @@ /** * DogTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class DogTest extends TestCase */ public function testDog() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class DogTest extends TestCase */ public function testPropertyBreed() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumArraysTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumArraysTest.php index b49ea71c29..144730c7f1 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumArraysTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumArraysTest.php @@ -2,7 +2,7 @@ /** * EnumArraysTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class EnumArraysTest extends TestCase */ public function testEnumArrays() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class EnumArraysTest extends TestCase */ public function testPropertyJustSymbol() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,5 +93,7 @@ class EnumArraysTest extends TestCase */ public function testPropertyArrayEnum() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumClassTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumClassTest.php index a2ef8ea3e2..10b045d0ef 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumClassTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumClassTest.php @@ -2,7 +2,7 @@ /** * EnumClassTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,5 +75,7 @@ class EnumClassTest extends TestCase */ public function testEnumClass() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumTestTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumTestTest.php index 479fc3e598..5df99d7540 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumTestTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/EnumTestTest.php @@ -2,7 +2,7 @@ /** * EnumTestTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class EnumTestTest extends TestCase */ public function testEnumTest() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class EnumTestTest extends TestCase */ public function testPropertyEnumString() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class EnumTestTest extends TestCase */ public function testPropertyEnumStringRequired() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,6 +102,8 @@ class EnumTestTest extends TestCase */ public function testPropertyEnumInteger() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -104,6 +111,8 @@ class EnumTestTest extends TestCase */ public function testPropertyEnumNumber() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -111,6 +120,8 @@ class EnumTestTest extends TestCase */ public function testPropertyOuterEnum() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -118,6 +129,8 @@ class EnumTestTest extends TestCase */ public function testPropertyOuterEnumInteger() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -125,6 +138,8 @@ class EnumTestTest extends TestCase */ public function testPropertyOuterEnumDefaultValue() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -132,5 +147,7 @@ class EnumTestTest extends TestCase */ public function testPropertyOuterEnumIntegerDefaultValue() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FileSchemaTestClassTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FileSchemaTestClassTest.php index aec72c1602..8a0e5a8356 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FileSchemaTestClassTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FileSchemaTestClassTest.php @@ -2,7 +2,7 @@ /** * FileSchemaTestClassTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class FileSchemaTestClassTest extends TestCase */ public function testFileSchemaTestClass() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class FileSchemaTestClassTest extends TestCase */ public function testPropertyFile() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,5 +93,7 @@ class FileSchemaTestClassTest extends TestCase */ public function testPropertyFiles() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FileTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FileTest.php index dc76d50a16..6c7460efbc 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FileTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FileTest.php @@ -2,7 +2,7 @@ /** * FileTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class FileTest extends TestCase */ public function testFile() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class FileTest extends TestCase */ public function testPropertySourceUri() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FooGetDefaultResponseTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FooGetDefaultResponseTest.php index b7e0e6e21f..ec9536c8a6 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FooGetDefaultResponseTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FooGetDefaultResponseTest.php @@ -2,7 +2,7 @@ /** * FooGetDefaultResponseTest * - * PHP version 7.3 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 6.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FooTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FooTest.php index 2626d017d6..f357e06727 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FooTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FooTest.php @@ -2,7 +2,7 @@ /** * FooTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class FooTest extends TestCase */ public function testFoo() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class FooTest extends TestCase */ public function testPropertyBar() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FormatTestTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FormatTestTest.php index 5514496b67..7d43c0d165 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/FormatTestTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/FormatTestTest.php @@ -2,7 +2,7 @@ /** * FormatTestTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class FormatTestTest extends TestCase */ public function testFormatTest() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class FormatTestTest extends TestCase */ public function testPropertyInteger() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class FormatTestTest extends TestCase */ public function testPropertyInt32() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,6 +102,8 @@ class FormatTestTest extends TestCase */ public function testPropertyInt64() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -104,6 +111,8 @@ class FormatTestTest extends TestCase */ public function testPropertyNumber() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -111,6 +120,8 @@ class FormatTestTest extends TestCase */ public function testPropertyFloat() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -118,6 +129,17 @@ class FormatTestTest extends TestCase */ public function testPropertyDouble() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "decimal" + */ + public function testPropertyDecimal() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -125,6 +147,8 @@ class FormatTestTest extends TestCase */ public function testPropertyString() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -132,6 +156,8 @@ class FormatTestTest extends TestCase */ public function testPropertyByte() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -139,6 +165,8 @@ class FormatTestTest extends TestCase */ public function testPropertyBinary() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -146,6 +174,8 @@ class FormatTestTest extends TestCase */ public function testPropertyDate() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -153,6 +183,8 @@ class FormatTestTest extends TestCase */ public function testPropertyDateTime() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -160,6 +192,8 @@ class FormatTestTest extends TestCase */ public function testPropertyUuid() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -167,6 +201,8 @@ class FormatTestTest extends TestCase */ public function testPropertyPassword() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -174,6 +210,8 @@ class FormatTestTest extends TestCase */ public function testPropertyPatternWithDigits() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -181,5 +219,7 @@ class FormatTestTest extends TestCase */ public function testPropertyPatternWithDigitsAndDelimiter() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/HasOnlyReadOnlyTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/HasOnlyReadOnlyTest.php index 0782a49d64..42f3977270 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/HasOnlyReadOnlyTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/HasOnlyReadOnlyTest.php @@ -2,7 +2,7 @@ /** * HasOnlyReadOnlyTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class HasOnlyReadOnlyTest extends TestCase */ public function testHasOnlyReadOnly() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class HasOnlyReadOnlyTest extends TestCase */ public function testPropertyBar() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,5 +93,7 @@ class HasOnlyReadOnlyTest extends TestCase */ public function testPropertyFoo() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/HealthCheckResultTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/HealthCheckResultTest.php index 44b75f893a..55ae06c184 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/HealthCheckResultTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/HealthCheckResultTest.php @@ -2,7 +2,7 @@ /** * HealthCheckResultTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class HealthCheckResultTest extends TestCase */ public function testHealthCheckResult() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class HealthCheckResultTest extends TestCase */ public function testPropertyNullableMessage() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/InlineObject1Test.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/InlineObject1Test.php deleted file mode 100644 index 805c82a0da..0000000000 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/InlineObject1Test.php +++ /dev/null @@ -1,94 +0,0 @@ -markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class MapTestTest extends TestCase */ public function testPropertyMapMapOfString() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class MapTestTest extends TestCase */ public function testPropertyMapOfEnumString() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,6 +102,8 @@ class MapTestTest extends TestCase */ public function testPropertyDirectMap() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -104,5 +111,7 @@ class MapTestTest extends TestCase */ public function testPropertyIndirectMap() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php index 73dd17f1a6..842e1271c3 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php @@ -2,7 +2,7 @@ /** * MixedPropertiesAndAdditionalPropertiesClassTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class MixedPropertiesAndAdditionalPropertiesClassTest extends TestCase */ public function testMixedPropertiesAndAdditionalPropertiesClass() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class MixedPropertiesAndAdditionalPropertiesClassTest extends TestCase */ public function testPropertyUuid() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class MixedPropertiesAndAdditionalPropertiesClassTest extends TestCase */ public function testPropertyDateTime() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,5 +102,7 @@ class MixedPropertiesAndAdditionalPropertiesClassTest extends TestCase */ public function testPropertyMap() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/Model200ResponseTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/Model200ResponseTest.php index 625b13c5c3..d6d5f0c62a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/Model200ResponseTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/Model200ResponseTest.php @@ -2,7 +2,7 @@ /** * Model200ResponseTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class Model200ResponseTest extends TestCase */ public function testModel200Response() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class Model200ResponseTest extends TestCase */ public function testPropertyName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,5 +93,7 @@ class Model200ResponseTest extends TestCase */ public function testPropertyClass() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ModelListTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ModelListTest.php index 8c8eb959f9..fed517cfe1 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ModelListTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ModelListTest.php @@ -2,7 +2,7 @@ /** * ModelListTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class ModelListTest extends TestCase */ public function testModelList() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class ModelListTest extends TestCase */ public function testProperty123List() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ModelReturnTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ModelReturnTest.php index a8169b7d75..aa50dc1e13 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ModelReturnTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ModelReturnTest.php @@ -2,7 +2,7 @@ /** * ModelReturnTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class ModelReturnTest extends TestCase */ public function testModelReturn() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class ModelReturnTest extends TestCase */ public function testPropertyReturn() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/NameTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/NameTest.php index 1a2af802b2..857c84bae0 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/NameTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/NameTest.php @@ -2,7 +2,7 @@ /** * NameTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class NameTest extends TestCase */ public function testName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class NameTest extends TestCase */ public function testPropertyName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class NameTest extends TestCase */ public function testPropertySnakeCase() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,6 +102,8 @@ class NameTest extends TestCase */ public function testPropertyProperty() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -104,5 +111,7 @@ class NameTest extends TestCase */ public function testProperty123Number() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/NullableClassTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/NullableClassTest.php index 32bc5a67fa..0f6a26a1a2 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/NullableClassTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/NullableClassTest.php @@ -2,7 +2,7 @@ /** * NullableClassTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class NullableClassTest extends TestCase */ public function testNullableClass() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class NullableClassTest extends TestCase */ public function testPropertyIntegerProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class NullableClassTest extends TestCase */ public function testPropertyNumberProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,6 +102,8 @@ class NullableClassTest extends TestCase */ public function testPropertyBooleanProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -104,6 +111,8 @@ class NullableClassTest extends TestCase */ public function testPropertyStringProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -111,6 +120,8 @@ class NullableClassTest extends TestCase */ public function testPropertyDateProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -118,6 +129,8 @@ class NullableClassTest extends TestCase */ public function testPropertyDatetimeProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -125,6 +138,8 @@ class NullableClassTest extends TestCase */ public function testPropertyArrayNullableProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -132,6 +147,8 @@ class NullableClassTest extends TestCase */ public function testPropertyArrayAndItemsNullableProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -139,6 +156,8 @@ class NullableClassTest extends TestCase */ public function testPropertyArrayItemsNullable() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -146,6 +165,8 @@ class NullableClassTest extends TestCase */ public function testPropertyObjectNullableProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -153,6 +174,8 @@ class NullableClassTest extends TestCase */ public function testPropertyObjectAndItemsNullableProp() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -160,5 +183,7 @@ class NullableClassTest extends TestCase */ public function testPropertyObjectItemsNullable() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/NumberOnlyTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/NumberOnlyTest.php index 1cfc708181..44a972197d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/NumberOnlyTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/NumberOnlyTest.php @@ -2,7 +2,7 @@ /** * NumberOnlyTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class NumberOnlyTest extends TestCase */ public function testNumberOnly() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class NumberOnlyTest extends TestCase */ public function testPropertyJustNumber() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ObjectWithDeprecatedFieldsTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ObjectWithDeprecatedFieldsTest.php index 2dde49a682..d890e8e7c7 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ObjectWithDeprecatedFieldsTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ObjectWithDeprecatedFieldsTest.php @@ -2,7 +2,7 @@ /** * ObjectWithDeprecatedFieldsTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.2.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OrderTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OrderTest.php index 836503bd76..deee179082 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OrderTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OrderTest.php @@ -2,7 +2,7 @@ /** * OrderTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class OrderTest extends TestCase */ public function testOrder() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class OrderTest extends TestCase */ public function testPropertyId() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class OrderTest extends TestCase */ public function testPropertyPetId() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,6 +102,8 @@ class OrderTest extends TestCase */ public function testPropertyQuantity() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -104,6 +111,8 @@ class OrderTest extends TestCase */ public function testPropertyShipDate() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -111,6 +120,8 @@ class OrderTest extends TestCase */ public function testPropertyStatus() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -118,5 +129,7 @@ class OrderTest extends TestCase */ public function testPropertyComplete() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterCompositeTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterCompositeTest.php index 135abe5783..fe406c33f9 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterCompositeTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterCompositeTest.php @@ -2,7 +2,7 @@ /** * OuterCompositeTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class OuterCompositeTest extends TestCase */ public function testOuterComposite() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class OuterCompositeTest extends TestCase */ public function testPropertyMyNumber() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class OuterCompositeTest extends TestCase */ public function testPropertyMyString() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,5 +102,7 @@ class OuterCompositeTest extends TestCase */ public function testPropertyMyBoolean() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumDefaultValueTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumDefaultValueTest.php index 42de969dc3..7e4008ee3e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumDefaultValueTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumDefaultValueTest.php @@ -2,7 +2,7 @@ /** * OuterEnumDefaultValueTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,5 +75,7 @@ class OuterEnumDefaultValueTest extends TestCase */ public function testOuterEnumDefaultValue() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumIntegerDefaultValueTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumIntegerDefaultValueTest.php index cb423e0452..4749175262 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumIntegerDefaultValueTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumIntegerDefaultValueTest.php @@ -2,7 +2,7 @@ /** * OuterEnumIntegerDefaultValueTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,5 +75,7 @@ class OuterEnumIntegerDefaultValueTest extends TestCase */ public function testOuterEnumIntegerDefaultValue() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumIntegerTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumIntegerTest.php index f6a6c33bea..9e5d201f95 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumIntegerTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumIntegerTest.php @@ -2,7 +2,7 @@ /** * OuterEnumIntegerTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,5 +75,7 @@ class OuterEnumIntegerTest extends TestCase */ public function testOuterEnumInteger() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumTest.php index 37875f308b..fd0e951580 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterEnumTest.php @@ -2,7 +2,7 @@ /** * OuterEnumTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,5 +75,7 @@ class OuterEnumTest extends TestCase */ public function testOuterEnum() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterObjectWithEnumPropertyTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterObjectWithEnumPropertyTest.php index 9b186f93f6..e00c4a1781 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterObjectWithEnumPropertyTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/OuterObjectWithEnumPropertyTest.php @@ -2,7 +2,7 @@ /** * OuterObjectWithEnumPropertyTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/PetTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/PetTest.php index c096b6cfec..f19f26d014 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/PetTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/PetTest.php @@ -2,7 +2,7 @@ /** * PetTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class PetTest extends TestCase */ public function testPet() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class PetTest extends TestCase */ public function testPropertyId() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class PetTest extends TestCase */ public function testPropertyCategory() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,6 +102,8 @@ class PetTest extends TestCase */ public function testPropertyName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -104,6 +111,8 @@ class PetTest extends TestCase */ public function testPropertyPhotoUrls() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -111,6 +120,8 @@ class PetTest extends TestCase */ public function testPropertyTags() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -118,5 +129,7 @@ class PetTest extends TestCase */ public function testPropertyStatus() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ReadOnlyFirstTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ReadOnlyFirstTest.php index 3cdf837b8f..e9ca89bc41 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/ReadOnlyFirstTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/ReadOnlyFirstTest.php @@ -2,7 +2,7 @@ /** * ReadOnlyFirstTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class ReadOnlyFirstTest extends TestCase */ public function testReadOnlyFirst() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class ReadOnlyFirstTest extends TestCase */ public function testPropertyBar() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,5 +93,7 @@ class ReadOnlyFirstTest extends TestCase */ public function testPropertyBaz() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/SingleRefTypeTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/SingleRefTypeTest.php index 721ac183ec..6d2b5953da 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/SingleRefTypeTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/SingleRefTypeTest.php @@ -2,7 +2,7 @@ /** * SingleRefTypeTest * - * PHP version 7.3 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 6.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/SpecialModelNameTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/SpecialModelNameTest.php index 04c7034330..589e5af215 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/SpecialModelNameTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/SpecialModelNameTest.php @@ -2,7 +2,7 @@ /** * SpecialModelNameTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class SpecialModelNameTest extends TestCase */ public function testSpecialModelName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,5 +84,7 @@ class SpecialModelNameTest extends TestCase */ public function testPropertySpecialPropertyName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/TagTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/TagTest.php index d3b2e92598..74baa57984 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/TagTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/test/Model/TagTest.php @@ -2,7 +2,7 @@ /** * TagTest * - * PHP version 7.2 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -16,9 +16,8 @@ * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 - * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.0.0-SNAPSHOT + * OpenAPI Generator version: 6.1.0-SNAPSHOT */ /** @@ -27,7 +26,7 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Client; +namespace OpenAPI\Client\Test\Model; use PHPUnit\Framework\TestCase; @@ -76,6 +75,8 @@ class TagTest extends TestCase */ public function testTag() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class TagTest extends TestCase */ public function testPropertyId() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,5 +93,7 @@ class TagTest extends TestCase */ public function testPropertyName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/TypeHolderDefaultTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/TypeHolderDefaultTest.php deleted file mode 100644 index 75ea9e66f5..0000000000 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/TypeHolderDefaultTest.php +++ /dev/null @@ -1,115 +0,0 @@ -markTestIncomplete('Not implemented'); } /** @@ -83,6 +84,8 @@ class UserTest extends TestCase */ public function testPropertyId() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -90,6 +93,8 @@ class UserTest extends TestCase */ public function testPropertyUsername() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -97,6 +102,8 @@ class UserTest extends TestCase */ public function testPropertyFirstName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -104,6 +111,8 @@ class UserTest extends TestCase */ public function testPropertyLastName() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -111,6 +120,8 @@ class UserTest extends TestCase */ public function testPropertyEmail() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -118,6 +129,8 @@ class UserTest extends TestCase */ public function testPropertyPassword() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -125,6 +138,8 @@ class UserTest extends TestCase */ public function testPropertyPhone() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } /** @@ -132,5 +147,7 @@ class UserTest extends TestCase */ public function testPropertyUserStatus() { + // TODO: implement + $this->markTestIncomplete('Not implemented'); } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/test/Model/XmlItemTest.php b/samples/client/petstore/php/OpenAPIClient-php/test/Model/XmlItemTest.php deleted file mode 100644 index 4dc01deb48..0000000000 --- a/samples/client/petstore/php/OpenAPIClient-php/test/Model/XmlItemTest.php +++ /dev/null @@ -1,283 +0,0 @@ -setName(1); + $this->assertEquals(1, $name->getName(), 'Non-nullable property can be set and retains its value'); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('non-nullable name cannot be null'); + + $name->setName(null); + } + + public function testNullableobject(): void + { + $nullable = new NullableClass(); + + $nullable->setIntegerProp(null); + $this->assertNull($nullable->getIntegerProp(), 'Nullable property can be set to null retains its value'); + + $nullable->setIntegerProp(1); + $this->assertEquals(1, $nullable->getIntegerProp(), 'Nullable property can be set and retains its value'); + } +} \ No newline at end of file diff --git a/samples/client/petstore/php/OpenAPIClient-php/tests/ObjectSerializerTest.php b/samples/client/petstore/php/OpenAPIClient-php/tests/ObjectSerializerTest.php index 78eab44058..8743611a52 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/tests/ObjectSerializerTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/tests/ObjectSerializerTest.php @@ -2,44 +2,53 @@ namespace OpenAPI\Client; +use DateTime; use GuzzleHttp\Psr7\Utils; +use OpenAPI\Client\Model\Pet; +use OpenAPI\Client\Model\Tag; use PHPUnit\Framework\TestCase; +use SplFileObject; -// test object serializer +/** + * class ObjectSerializerTest + * + * @package OpenAPI\Client + */ class ObjectSerializerTest extends TestCase { - // test sanitizeFilename - public function testSanitizeFilename() + /** + * Test sanitizeFilename + * + * @covers ObjectSerializer::sanitizeFilename + */ + public function testSanitizeFilename(): void { - // initialize the API client - $s = new ObjectSerializer(); - - $this->assertSame("sun.gif", $s->sanitizeFilename("sun.gif")); - $this->assertSame("sun.gif", $s->sanitizeFilename("../sun.gif")); - $this->assertSame("sun.gif", $s->sanitizeFilename("/var/tmp/sun.gif")); - $this->assertSame("sun.gif", $s->sanitizeFilename("./sun.gif")); + $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("sun.gif")); + $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("../sun.gif")); + $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("/var/tmp/sun.gif")); + $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("./sun.gif")); - $this->assertSame("sun", $s->sanitizeFilename("sun")); - $this->assertSame("sun.gif", $s->sanitizeFilename("..\sun.gif")); - $this->assertSame("sun.gif", $s->sanitizeFilename("\var\tmp\sun.gif")); - $this->assertSame("sun.gif", $s->sanitizeFilename("c:\var\tmp\sun.gif")); - $this->assertSame("sun.gif", $s->sanitizeFilename(".\sun.gif")); + $this->assertSame("sun", ObjectSerializer::sanitizeFilename("sun")); + $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("..\sun.gif")); + $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("\var\tmp\sun.gif")); + $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("c:\var\tmp\sun.gif")); + $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename(".\sun.gif")); } /** * Test SplFileObject class deserialization. * * @see https://github.com/OpenAPITools/openapi-generator/pull/11184 - * @covers ObjectSerializer::serialize + * @covers ObjectSerializer::deserialize * @dataProvider provideFileStreams */ public function testDeserializeFile($stream, ?array $httpHeaders = null, ?string $expectedFilename = null): void { $s = new ObjectSerializer(); - /** @var \SplFileObject */ - $file = $s->deserialize($stream, '\SplFileObject', $httpHeaders); - $this->assertInstanceOf(\SplFileObject::class, $file); + /** @var SplFileObject $file */ + $file = ObjectSerializer::deserialize($stream, '\SplFileObject', $httpHeaders); + $this->assertInstanceOf(SplFileObject::class, $file); if (is_string($expectedFilename)) { $this->assertEquals($expectedFilename, $file->getFilename()); @@ -48,7 +57,11 @@ class ObjectSerializerTest extends TestCase } } - public function provideFileStreams() + /** + * File Streams Provider + * @return array[] + */ + public function provideFileStreams(): array { return [ 'File stream without headers' => [ @@ -90,9 +103,14 @@ class ObjectSerializerTest extends TestCase public function testDateTimeParseSecondAccuracy(string $timestamp, string $expected): void { $dateTime = ObjectSerializer::deserialize($timestamp, '\DateTime'); - $this->assertEquals(new \DateTime($expected), $dateTime); + $this->assertEquals(new DateTime($expected), $dateTime); } + /** + * Timestamps provider + * + * @return string[][] + */ public function provideTimestamps(): array { return [ @@ -149,6 +167,11 @@ class ObjectSerializerTest extends TestCase $this->assertEquals($expected, $query); } + /** + * Query params provider + * + * @return array[] + */ public function provideQueryParams(): array { $array = ['blue', 'black', 'brown']; @@ -304,6 +327,15 @@ class ObjectSerializerTest extends TestCase true, 'filter%5Bor%5D%5B0%5D%5Bname%5D=John&filter%5Bor%5D%5B1%5D%5Bemail%5D=john%40doe.com' ], + 'form DateTime object, explode on, required true' => [ + new DateTime('2021-10-06T20:17:16'), 'dateTime', '\DateTime', 'form', true, true, 'dateTime=2021-10-06T20%3A17%3A16%2B00%3A00', + ], + 'form null DateTime object, explode on, required true' => [ + null, 'dateTime', '\DateTime', 'form', true, true, 'dateTime=', + ], + 'form null DateTime object, explode on, required false' => [ + null, 'dateTime', '\DateTime', 'form', true, false, '', + ], ]; } @@ -321,6 +353,11 @@ class ObjectSerializerTest extends TestCase $this->assertEquals($expected, $result); } + /** + * Deep Objects provider + * + * @return array + */ public function provideDeepObjects(): array { return [ @@ -360,6 +397,11 @@ class ObjectSerializerTest extends TestCase $this->assertSame($expected, $result); } + /** + * toString() input provider + * + * @return array + */ public function provideToStringInput(): array { return [ @@ -384,11 +426,12 @@ class ObjectSerializerTest extends TestCase 'expected' => 'some string', ], 'a date' => [ - 'input' => new \DateTime('14-04-2022'), + 'input' => new DateTime('14-04-2022'), 'expected' => '2022-04-14T00:00:00+00:00', ], ]; } + /** * @covers ObjectSerializer::toQueryValue * @dataProvider provideQueryParamsWithStringBooleanFormatForQueryString @@ -412,6 +455,11 @@ class ObjectSerializerTest extends TestCase $this->assertEquals($expected, $query); } + /** + * Query Params with string boolean format provider + * + * @return array[] + */ public function provideQueryParamsWithStringBooleanFormatForQueryString(): array { return [ @@ -431,4 +479,33 @@ class ObjectSerializerTest extends TestCase ], ]; } + + /** + * Test array to class deserialization. + * + * @covers ObjectSerializer::deserialize + * + * @see https://github.com/OpenAPITools/openapi-generator/pull/12849#issuecomment-1186130098 + */ + public function testArrayGivenAsObjectForDeserialize(): void + { + $data = [ + 'name' => 'Pet Name', + 'status' => Pet::STATUS_AVAILABLE, + 'tags' => [ + ['name' => 'Tag Name'], + ] + ]; + + /** @var Pet $pet */ + $pet = ObjectSerializer::deserialize($data, Pet::class); + $this->assertEquals('Pet Name', $pet->getName()); + $this->assertEquals(Pet::STATUS_AVAILABLE, $pet->getStatus()); + + $tags = $pet->getTags(); + $this->assertIsArray($tags); + + $tag = $tags[0]; + $this->assertInstanceOf(Tag::class, $tag); + } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/tests/ServerVariablesInOperationTest.php b/samples/client/petstore/php/OpenAPIClient-php/tests/ServerVariablesInOperationTest.php new file mode 100644 index 0000000000..208ae7ed32 --- /dev/null +++ b/samples/client/petstore/php/OpenAPIClient-php/tests/ServerVariablesInOperationTest.php @@ -0,0 +1,58 @@ +fakeHttpClient = new FakeHttpClient(); + $this->api = new Api\PetApi($this->fakeHttpClient); + $this->pet = new Model\Pet(); + } + + public function testServerVariablesInOperation(): void + { + # Test default values (if no variables are set) + $this->api->addPet($this->pet, 2); + $request = $this->fakeHttpClient->getLastRequest(); + + $this->assertEquals('petstore.swagger.io', $request->getUri()->getHost(), 'Server variable set to default value.'); + + # Test variables substitution + $this->api->addPet($this->pet, 2, [ 'server' => 'qa-petstore', 'port' => '8080']); + $request = $this->fakeHttpClient->getLastRequest(); + + $this->assertEquals('qa-petstore.swagger.io', $request->getUri()->getHost(), 'Server set to "qa-petstore"'); + $this->assertEquals(8080, $request->getUri()->getPort(), 'Port set to 8080'); + } + + public function testLegacyServerChoiceInOperation(): void + { + # Test legacy behavior (set server using api->setHostIndex() + $this->api->setHostIndex(1); + $this->api->addPet($this->pet); + $request = $this->fakeHttpClient->getLastRequest(); + + $this->assertEquals('path-server-test.petstore.local', $request->getUri()->getHost(), 'Server set using legacy behavior'); + } + + public function testInvalidVariableValueInOperation(): void + { + $this->expectException(InvalidArgumentException::class); + $this->api->addPet($this->pet, 2,['server' => 'invalid-value']); + } +} diff --git a/samples/client/petstore/python/.gitignore b/samples/client/petstore/python-prior/.gitignore similarity index 100% rename from samples/client/petstore/python/.gitignore rename to samples/client/petstore/python-prior/.gitignore diff --git a/samples/client/petstore/python/.gitlab-ci.yml b/samples/client/petstore/python-prior/.gitlab-ci.yml similarity index 100% rename from samples/client/petstore/python/.gitlab-ci.yml rename to samples/client/petstore/python-prior/.gitlab-ci.yml diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/.openapi-generator-ignore b/samples/client/petstore/python-prior/.openapi-generator-ignore similarity index 100% rename from samples/client/petstore/rust/reqwest/fileResponseTest/.openapi-generator-ignore rename to samples/client/petstore/python-prior/.openapi-generator-ignore diff --git a/samples/client/petstore/python/.openapi-generator/FILES b/samples/client/petstore/python-prior/.openapi-generator/FILES similarity index 100% rename from samples/client/petstore/python/.openapi-generator/FILES rename to samples/client/petstore/python-prior/.openapi-generator/FILES diff --git a/samples/client/petstore/python-prior/.openapi-generator/VERSION b/samples/client/petstore/python-prior/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/python-prior/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python/.travis.yml b/samples/client/petstore/python-prior/.travis.yml similarity index 100% rename from samples/client/petstore/python/.travis.yml rename to samples/client/petstore/python-prior/.travis.yml diff --git a/samples/client/petstore/python/Makefile b/samples/client/petstore/python-prior/Makefile similarity index 100% rename from samples/client/petstore/python/Makefile rename to samples/client/petstore/python-prior/Makefile diff --git a/samples/client/petstore/python-prior/README.md b/samples/client/petstore/python-prior/README.md new file mode 100644 index 0000000000..eb14e3a2d7 --- /dev/null +++ b/samples/client/petstore/python-prior/README.md @@ -0,0 +1,254 @@ +# petstore-api +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonPriorClientCodegen + +## Requirements. + +Python >=3.6 + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: +```python +import petstore_api +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import petstore_api +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python + +import time +import petstore_api +from pprint import pprint +from petstore_api.api import another_fake_api +from petstore_api.model.client import Client +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = another_fake_api.AnotherFakeApi(api_client) + body = Client( + client="client_example", + ) # Client | client model + + try: + # To test special tags + api_response = api_instance.call_123_test_special_tags(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +*FakeApi* | [**array_model**](docs/FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | +*FakeApi* | [**boolean**](docs/FakeApi.md#boolean) | **POST** /fake/refs/boolean | +*FakeApi* | [**create_xml_item**](docs/FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem +*FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | +*FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +*FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | +*FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | +*FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | +*FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | +*FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**test_endpoint_enums_length_one**](docs/FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | +*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetApi* | [**upload_file_with_required_file**](docs/PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) + - [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) + - [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) + - [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) + - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) + - [AdditionalPropertiesString](docs/AdditionalPropertiesString.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ApiResponse](docs/ApiResponse.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [Child](docs/Child.md) + - [ChildAllOf](docs/ChildAllOf.md) + - [ChildCat](docs/ChildCat.md) + - [ChildCatAllOf](docs/ChildCatAllOf.md) + - [ChildDog](docs/ChildDog.md) + - [ChildDogAllOf](docs/ChildDogAllOf.md) + - [ChildLizard](docs/ChildLizard.md) + - [ChildLizardAllOf](docs/ChildLizardAllOf.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [File](docs/File.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [FormatTest](docs/FormatTest.md) + - [Grandparent](docs/Grandparent.md) + - [GrandparentAnimal](docs/GrandparentAnimal.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelReturn](docs/ModelReturn.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [NumberWithValidations](docs/NumberWithValidations.md) + - [ObjectModelWithRefProps](docs/ObjectModelWithRefProps.md) + - [Order](docs/Order.md) + - [Parent](docs/Parent.md) + - [ParentAllOf](docs/ParentAllOf.md) + - [ParentPet](docs/ParentPet.md) + - [Pet](docs/Pet.md) + - [Player](docs/Player.md) + - [Polygon](docs/Polygon.md) + - [PolygonAllOf](docs/PolygonAllOf.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Shape](docs/Shape.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Square](docs/Square.md) + - [SquareAllOf](docs/SquareAllOf.md) + - [StringBooleanMap](docs/StringBooleanMap.md) + - [StringEnum](docs/StringEnum.md) + - [Tag](docs/Tag.md) + - [Triangle](docs/Triangle.md) + - [TriangleAllOf](docs/TriangleAllOf.md) + - [TypeHolderDefault](docs/TypeHolderDefault.md) + - [TypeHolderExample](docs/TypeHolderExample.md) + - [User](docs/User.md) + - [XmlItem](docs/XmlItem.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + +## http_basic_test + +- **Type**: HTTP basic authentication + + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + + +## Author + + + + +## Notes for Large OpenAPI documents +If the OpenAPI document is large, imports in petstore_api.apis and petstore_api.models may fail with a +RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: + +Solution 1: +Use specific imports for apis and models like: +- `from petstore_api.api.default_api import DefaultApi` +- `from petstore_api.model.pet import Pet` + +Solution 2: +Before importing the package, adjust the maximum recursion limit as shown below: +``` +import sys +sys.setrecursionlimit(1500) +import petstore_api +from petstore_api.apis import * +from petstore_api.models import * +``` + diff --git a/samples/client/petstore/python/dev-requirements.txt b/samples/client/petstore/python-prior/dev-requirements.txt similarity index 100% rename from samples/client/petstore/python/dev-requirements.txt rename to samples/client/petstore/python-prior/dev-requirements.txt diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/python-prior/docs/AdditionalPropertiesAnyType.md similarity index 100% rename from samples/client/petstore/python/docs/AdditionalPropertiesAnyType.md rename to samples/client/petstore/python-prior/docs/AdditionalPropertiesAnyType.md diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesArray.md b/samples/client/petstore/python-prior/docs/AdditionalPropertiesArray.md similarity index 100% rename from samples/client/petstore/python/docs/AdditionalPropertiesArray.md rename to samples/client/petstore/python-prior/docs/AdditionalPropertiesArray.md diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/python-prior/docs/AdditionalPropertiesBoolean.md similarity index 100% rename from samples/client/petstore/python/docs/AdditionalPropertiesBoolean.md rename to samples/client/petstore/python-prior/docs/AdditionalPropertiesBoolean.md diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesClass.md b/samples/client/petstore/python-prior/docs/AdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/python/docs/AdditionalPropertiesClass.md rename to samples/client/petstore/python-prior/docs/AdditionalPropertiesClass.md diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/python-prior/docs/AdditionalPropertiesInteger.md similarity index 100% rename from samples/client/petstore/python/docs/AdditionalPropertiesInteger.md rename to samples/client/petstore/python-prior/docs/AdditionalPropertiesInteger.md diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/python-prior/docs/AdditionalPropertiesNumber.md similarity index 100% rename from samples/client/petstore/python/docs/AdditionalPropertiesNumber.md rename to samples/client/petstore/python-prior/docs/AdditionalPropertiesNumber.md diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesObject.md b/samples/client/petstore/python-prior/docs/AdditionalPropertiesObject.md similarity index 100% rename from samples/client/petstore/python/docs/AdditionalPropertiesObject.md rename to samples/client/petstore/python-prior/docs/AdditionalPropertiesObject.md diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesString.md b/samples/client/petstore/python-prior/docs/AdditionalPropertiesString.md similarity index 100% rename from samples/client/petstore/python/docs/AdditionalPropertiesString.md rename to samples/client/petstore/python-prior/docs/AdditionalPropertiesString.md diff --git a/samples/client/petstore/python/docs/Animal.md b/samples/client/petstore/python-prior/docs/Animal.md similarity index 100% rename from samples/client/petstore/python/docs/Animal.md rename to samples/client/petstore/python-prior/docs/Animal.md diff --git a/samples/client/petstore/python/docs/AnimalFarm.md b/samples/client/petstore/python-prior/docs/AnimalFarm.md similarity index 100% rename from samples/client/petstore/python/docs/AnimalFarm.md rename to samples/client/petstore/python-prior/docs/AnimalFarm.md diff --git a/samples/client/petstore/python/docs/AnotherFakeApi.md b/samples/client/petstore/python-prior/docs/AnotherFakeApi.md similarity index 100% rename from samples/client/petstore/python/docs/AnotherFakeApi.md rename to samples/client/petstore/python-prior/docs/AnotherFakeApi.md diff --git a/samples/client/petstore/python/docs/ApiResponse.md b/samples/client/petstore/python-prior/docs/ApiResponse.md similarity index 100% rename from samples/client/petstore/python/docs/ApiResponse.md rename to samples/client/petstore/python-prior/docs/ApiResponse.md diff --git a/samples/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/python-prior/docs/ArrayOfArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md rename to samples/client/petstore/python-prior/docs/ArrayOfArrayOfNumberOnly.md diff --git a/samples/client/petstore/python/docs/ArrayOfNumberOnly.md b/samples/client/petstore/python-prior/docs/ArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/python/docs/ArrayOfNumberOnly.md rename to samples/client/petstore/python-prior/docs/ArrayOfNumberOnly.md diff --git a/samples/client/petstore/python/docs/ArrayTest.md b/samples/client/petstore/python-prior/docs/ArrayTest.md similarity index 100% rename from samples/client/petstore/python/docs/ArrayTest.md rename to samples/client/petstore/python-prior/docs/ArrayTest.md diff --git a/samples/client/petstore/python/docs/Capitalization.md b/samples/client/petstore/python-prior/docs/Capitalization.md similarity index 100% rename from samples/client/petstore/python/docs/Capitalization.md rename to samples/client/petstore/python-prior/docs/Capitalization.md diff --git a/samples/client/petstore/python/docs/Cat.md b/samples/client/petstore/python-prior/docs/Cat.md similarity index 100% rename from samples/client/petstore/python/docs/Cat.md rename to samples/client/petstore/python-prior/docs/Cat.md diff --git a/samples/client/petstore/python/docs/CatAllOf.md b/samples/client/petstore/python-prior/docs/CatAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/CatAllOf.md rename to samples/client/petstore/python-prior/docs/CatAllOf.md diff --git a/samples/client/petstore/python/docs/Category.md b/samples/client/petstore/python-prior/docs/Category.md similarity index 100% rename from samples/client/petstore/python/docs/Category.md rename to samples/client/petstore/python-prior/docs/Category.md diff --git a/samples/client/petstore/python/docs/Child.md b/samples/client/petstore/python-prior/docs/Child.md similarity index 100% rename from samples/client/petstore/python/docs/Child.md rename to samples/client/petstore/python-prior/docs/Child.md diff --git a/samples/client/petstore/python/docs/ChildAllOf.md b/samples/client/petstore/python-prior/docs/ChildAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/ChildAllOf.md rename to samples/client/petstore/python-prior/docs/ChildAllOf.md diff --git a/samples/client/petstore/python/docs/ChildCat.md b/samples/client/petstore/python-prior/docs/ChildCat.md similarity index 100% rename from samples/client/petstore/python/docs/ChildCat.md rename to samples/client/petstore/python-prior/docs/ChildCat.md diff --git a/samples/client/petstore/python/docs/ChildCatAllOf.md b/samples/client/petstore/python-prior/docs/ChildCatAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/ChildCatAllOf.md rename to samples/client/petstore/python-prior/docs/ChildCatAllOf.md diff --git a/samples/client/petstore/python/docs/ChildDog.md b/samples/client/petstore/python-prior/docs/ChildDog.md similarity index 100% rename from samples/client/petstore/python/docs/ChildDog.md rename to samples/client/petstore/python-prior/docs/ChildDog.md diff --git a/samples/client/petstore/python/docs/ChildDogAllOf.md b/samples/client/petstore/python-prior/docs/ChildDogAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/ChildDogAllOf.md rename to samples/client/petstore/python-prior/docs/ChildDogAllOf.md diff --git a/samples/client/petstore/python/docs/ChildLizard.md b/samples/client/petstore/python-prior/docs/ChildLizard.md similarity index 100% rename from samples/client/petstore/python/docs/ChildLizard.md rename to samples/client/petstore/python-prior/docs/ChildLizard.md diff --git a/samples/client/petstore/python/docs/ChildLizardAllOf.md b/samples/client/petstore/python-prior/docs/ChildLizardAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/ChildLizardAllOf.md rename to samples/client/petstore/python-prior/docs/ChildLizardAllOf.md diff --git a/samples/client/petstore/python/docs/ClassModel.md b/samples/client/petstore/python-prior/docs/ClassModel.md similarity index 100% rename from samples/client/petstore/python/docs/ClassModel.md rename to samples/client/petstore/python-prior/docs/ClassModel.md diff --git a/samples/client/petstore/python/docs/Client.md b/samples/client/petstore/python-prior/docs/Client.md similarity index 100% rename from samples/client/petstore/python/docs/Client.md rename to samples/client/petstore/python-prior/docs/Client.md diff --git a/samples/client/petstore/python/docs/Dog.md b/samples/client/petstore/python-prior/docs/Dog.md similarity index 100% rename from samples/client/petstore/python/docs/Dog.md rename to samples/client/petstore/python-prior/docs/Dog.md diff --git a/samples/client/petstore/python/docs/DogAllOf.md b/samples/client/petstore/python-prior/docs/DogAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/DogAllOf.md rename to samples/client/petstore/python-prior/docs/DogAllOf.md diff --git a/samples/client/petstore/python/docs/EnumArrays.md b/samples/client/petstore/python-prior/docs/EnumArrays.md similarity index 100% rename from samples/client/petstore/python/docs/EnumArrays.md rename to samples/client/petstore/python-prior/docs/EnumArrays.md diff --git a/samples/client/petstore/python/docs/EnumClass.md b/samples/client/petstore/python-prior/docs/EnumClass.md similarity index 100% rename from samples/client/petstore/python/docs/EnumClass.md rename to samples/client/petstore/python-prior/docs/EnumClass.md diff --git a/samples/client/petstore/python/docs/EnumTest.md b/samples/client/petstore/python-prior/docs/EnumTest.md similarity index 100% rename from samples/client/petstore/python/docs/EnumTest.md rename to samples/client/petstore/python-prior/docs/EnumTest.md diff --git a/samples/client/petstore/python-prior/docs/FakeApi.md b/samples/client/petstore/python-prior/docs/FakeApi.md new file mode 100644 index 0000000000..7c12e3bd18 --- /dev/null +++ b/samples/client/petstore/python-prior/docs/FakeApi.md @@ -0,0 +1,1239 @@ +# petstore_api.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**array_model**](FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | +[**boolean**](FakeApi.md#boolean) | **POST** /fake/refs/boolean | +[**create_xml_item**](FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem +[**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | +[**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +[**string**](FakeApi.md#string) | **POST** /fake/refs/string | +[**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | +[**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | +[**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | +[**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model +[**test_endpoint_enums_length_one**](FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | +[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +[**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data + + +# **array_model** +> AnimalFarm array_model() + + + +Test serialization of ArrayModel + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.animal_farm import AnimalFarm +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = AnimalFarm([ + Animal(), + ]) # AnimalFarm | Input model (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.array_model(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->array_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**AnimalFarm**](AnimalFarm.md)| Input model | [optional] + +### Return type + +[**AnimalFarm**](AnimalFarm.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output model | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **boolean** +> bool boolean() + + + +Test serialization of outer boolean types + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = True # bool | Input boolean as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.boolean(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->boolean: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **bool**| Input boolean as post body | [optional] + +### Return type + +**bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output boolean | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_xml_item** +> create_xml_item(xml_item) + +creates an XmlItem + +this route creates an XmlItem + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.xml_item import XmlItem +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + xml_item = XmlItem( + attribute_string="string", + attribute_number=1.234, + attribute_integer=-2, + attribute_boolean=True, + wrapped_array=[ + 1, + ], + name_string="string", + name_number=1.234, + name_integer=-2, + name_boolean=True, + name_array=[ + 1, + ], + name_wrapped_array=[ + 1, + ], + prefix_string="string", + prefix_number=1.234, + prefix_integer=-2, + prefix_boolean=True, + prefix_array=[ + 1, + ], + prefix_wrapped_array=[ + 1, + ], + namespace_string="string", + namespace_number=1.234, + namespace_integer=-2, + namespace_boolean=True, + namespace_array=[ + 1, + ], + namespace_wrapped_array=[ + 1, + ], + prefix_ns_string="string", + prefix_ns_number=1.234, + prefix_ns_integer=-2, + prefix_ns_boolean=True, + prefix_ns_array=[ + 1, + ], + prefix_ns_wrapped_array=[ + 1, + ], + ) # XmlItem | XmlItem Body + + # example passing only required values which don't have defaults set + try: + # creates an XmlItem + api_instance.create_xml_item(xml_item) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->create_xml_item: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **xml_item** | [**XmlItem**](XmlItem.md)| XmlItem Body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml, application/xml; charset=utf-8, application/xml; charset=utf-16, text/xml, text/xml; charset=utf-8, text/xml; charset=utf-16 + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **number_with_validations** +> NumberWithValidations number_with_validations() + + + +Test serialization of outer number types + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.number_with_validations import NumberWithValidations +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = NumberWithValidations(1E+1) # NumberWithValidations | Input number as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.number_with_validations(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->number_with_validations: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**NumberWithValidations**](NumberWithValidations.md)| Input number as post body | [optional] + +### Return type + +[**NumberWithValidations**](NumberWithValidations.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output number | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **object_model_with_ref_props** +> ObjectModelWithRefProps object_model_with_ref_props() + + + +Test serialization of object with $refed properties + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = ObjectModelWithRefProps( + my_number=NumberWithValidations(1E+1), + my_string="my_string_example", + my_boolean=True, + ) # ObjectModelWithRefProps | Input model (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.object_model_with_ref_props(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**ObjectModelWithRefProps**](ObjectModelWithRefProps.md)| Input model | [optional] + +### Return type + +[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output model | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **string** +> str string() + + + +Test serialization of outer string types + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = "body_example" # str | Input string as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.string(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **str**| Input string as post body | [optional] + +### Return type + +**str** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output string | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **string_enum** +> StringEnum string_enum() + + + +Test serialization of outer enum + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.string_enum import StringEnum +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = StringEnum("placed") # StringEnum | Input enum (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.string_enum(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string_enum: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**StringEnum**](StringEnum.md)| Input enum | [optional] + +### Return type + +[**StringEnum**](StringEnum.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output enum | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_with_file_schema** +> test_body_with_file_schema(body) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.file_schema_test_class import FileSchemaTestClass +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = FileSchemaTestClass( + file=File( + source_uri="source_uri_example", + ), + files=[ + File( + source_uri="source_uri_example", + ), + ], + ) # FileSchemaTestClass | + + # example passing only required values which don't have defaults set + try: + api_instance.test_body_with_file_schema(body) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_body_with_file_schema: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_with_query_params** +> test_body_with_query_params(query, body) + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + query = "query_example" # str | + body = User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + ) # User | + + # example passing only required values which don't have defaults set + try: + api_instance.test_body_with_query_params(query, body) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_body_with_query_params: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **str**| | + **body** | [**User**](User.md)| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_client_model** +> Client test_client_model(body) + +To test \"client\" model + +To test \"client\" model + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.client import Client +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = Client( + client="client_example", + ) # Client | client model + + # example passing only required values which don't have defaults set + try: + # To test \"client\" model + api_response = api_instance.test_client_model(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_client_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_endpoint_enums_length_one** +> test_endpoint_enums_length_one() + + + +This route has required values with enums of 1 + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + try: + api_instance.test_endpoint_enums_length_one() + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_enums_length_one: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query_integer** | **int**| | defaults to 3 + **query_string** | **str**| | defaults to "brillig" + **path_string** | **str**| | defaults to "hello" + **path_integer** | **int**| | defaults to 34 + **header_number** | **float**| | defaults to 1.234 + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_endpoint_parameters** +> test_endpoint_parameters(number, double, pattern_without_delimiter, byte) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example + +* Basic Authentication (http_basic_test): + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure HTTP basic authorization: http_basic_test +configuration = petstore_api.Configuration( + username = 'YOUR_USERNAME', + password = 'YOUR_PASSWORD' +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + number = 32.1 # float | None + double = 67.8 # float | None + pattern_without_delimiter = "AUR,rZ#UM/?R,Fp^l6$ARjbhJk C>" # str | None + byte = 'YQ==' # str | None + integer = 10 # int | None (optional) + int32 = 20 # int | None (optional) + int64 = 1 # int | None (optional) + float = 3.14 # float | None (optional) + string = "A" # str | None (optional) + binary = open('/path/to/file', 'rb') # file_type | None (optional) + date = dateutil_parser('1970-01-01').date() # date | None (optional) + date_time = dateutil_parser('1970-01-01T00:00:00.00Z') # datetime | None (optional) + password = "password_example" # str | None (optional) + param_callback = "param_callback_example" # str | None (optional) + + # example passing only required values which don't have defaults set + try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **float**| None | + **double** | **float**| None | + **pattern_without_delimiter** | **str**| None | + **byte** | **str**| None | + **integer** | **int**| None | [optional] + **int32** | **int**| None | [optional] + **int64** | **int**| None | [optional] + **float** | **float**| None | [optional] + **string** | **str**| None | [optional] + **binary** | **file_type**| None | [optional] + **date** | **date**| None | [optional] + **date_time** | **datetime**| None | [optional] + **password** | **str**| None | [optional] + **param_callback** | **str**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid username supplied | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_enum_parameters** +> test_enum_parameters() + +To test enum parameters + +To test enum parameters + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + enum_header_string_array = [ + "$", + ] # [str] | Header parameter enum test (string array) (optional) + enum_header_string = "-efg" # str | Header parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + enum_query_string_array = [ + "$", + ] # [str] | Query parameter enum test (string array) (optional) + enum_query_string = "-efg" # str | Query parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + enum_query_integer = 1 # int | Query parameter enum test (double) (optional) + enum_query_double = 1.1 # float | Query parameter enum test (double) (optional) + enum_form_string_array = [ + "$", + ] # [str] | Form parameter enum test (string array) (optional) if omitted the server will use the default value of "$" + enum_form_string = "-efg" # str | Form parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + + # example passing only required values which don't have defaults set + # and optional values + try: + # To test enum parameters + api_instance.test_enum_parameters(enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double, enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enum_header_string_array** | **[str]**| Header parameter enum test (string array) | [optional] + **enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + **enum_query_string_array** | **[str]**| Query parameter enum test (string array) | [optional] + **enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] + **enum_query_double** | **float**| Query parameter enum test (double) | [optional] + **enum_form_string_array** | **[str]**| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of "$" + **enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid request | - | +**404** | Not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_group_parameters** +> test_group_parameters(required_string_group, required_boolean_group, required_int64_group) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + required_string_group = 1 # int | Required String in group parameters + required_boolean_group = True # bool | Required Boolean in group parameters + required_int64_group = 1 # int | Required Integer in group parameters + string_group = 1 # int | String in group parameters (optional) + boolean_group = True # bool | Boolean in group parameters (optional) + int64_group = 1 # int | Integer in group parameters (optional) + + # example passing only required values which don't have defaults set + try: + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **required_string_group** | **int**| Required String in group parameters | + **required_boolean_group** | **bool**| Required Boolean in group parameters | + **required_int64_group** | **int**| Required Integer in group parameters | + **string_group** | **int**| String in group parameters | [optional] + **boolean_group** | **bool**| Boolean in group parameters | [optional] + **int64_group** | **int**| Integer in group parameters | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Someting wrong | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_inline_additional_properties** +> test_inline_additional_properties(param) + +test inline additionalProperties + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + param = { + "key": "key_example", + } # {str: (str,)} | request body + + # example passing only required values which don't have defaults set + try: + # test inline additionalProperties + api_instance.test_inline_additional_properties(param) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **{str: (str,)}**| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_json_form_data** +> test_json_form_data(param, param2) + +test json serialization of form data + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + param = "param_example" # str | field1 + param2 = "param2_example" # str | field2 + + # example passing only required values which don't have defaults set + try: + # test json serialization of form data + api_instance.test_json_form_data(param, param2) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_json_form_data: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **str**| field1 | + **param2** | **str**| field2 | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python/docs/FakeClassnameTags123Api.md b/samples/client/petstore/python-prior/docs/FakeClassnameTags123Api.md similarity index 100% rename from samples/client/petstore/python/docs/FakeClassnameTags123Api.md rename to samples/client/petstore/python-prior/docs/FakeClassnameTags123Api.md diff --git a/samples/client/petstore/python/docs/File.md b/samples/client/petstore/python-prior/docs/File.md similarity index 100% rename from samples/client/petstore/python/docs/File.md rename to samples/client/petstore/python-prior/docs/File.md diff --git a/samples/client/petstore/python/docs/FileSchemaTestClass.md b/samples/client/petstore/python-prior/docs/FileSchemaTestClass.md similarity index 100% rename from samples/client/petstore/python/docs/FileSchemaTestClass.md rename to samples/client/petstore/python-prior/docs/FileSchemaTestClass.md diff --git a/samples/client/petstore/python/docs/FormatTest.md b/samples/client/petstore/python-prior/docs/FormatTest.md similarity index 100% rename from samples/client/petstore/python/docs/FormatTest.md rename to samples/client/petstore/python-prior/docs/FormatTest.md diff --git a/samples/client/petstore/python/docs/Grandparent.md b/samples/client/petstore/python-prior/docs/Grandparent.md similarity index 100% rename from samples/client/petstore/python/docs/Grandparent.md rename to samples/client/petstore/python-prior/docs/Grandparent.md diff --git a/samples/client/petstore/python/docs/GrandparentAnimal.md b/samples/client/petstore/python-prior/docs/GrandparentAnimal.md similarity index 100% rename from samples/client/petstore/python/docs/GrandparentAnimal.md rename to samples/client/petstore/python-prior/docs/GrandparentAnimal.md diff --git a/samples/client/petstore/python/docs/HasOnlyReadOnly.md b/samples/client/petstore/python-prior/docs/HasOnlyReadOnly.md similarity index 100% rename from samples/client/petstore/python/docs/HasOnlyReadOnly.md rename to samples/client/petstore/python-prior/docs/HasOnlyReadOnly.md diff --git a/samples/client/petstore/python/docs/List.md b/samples/client/petstore/python-prior/docs/List.md similarity index 100% rename from samples/client/petstore/python/docs/List.md rename to samples/client/petstore/python-prior/docs/List.md diff --git a/samples/client/petstore/python/docs/MapTest.md b/samples/client/petstore/python-prior/docs/MapTest.md similarity index 100% rename from samples/client/petstore/python/docs/MapTest.md rename to samples/client/petstore/python-prior/docs/MapTest.md diff --git a/samples/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/python-prior/docs/MixedPropertiesAndAdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md rename to samples/client/petstore/python-prior/docs/MixedPropertiesAndAdditionalPropertiesClass.md diff --git a/samples/client/petstore/python/docs/Model200Response.md b/samples/client/petstore/python-prior/docs/Model200Response.md similarity index 100% rename from samples/client/petstore/python/docs/Model200Response.md rename to samples/client/petstore/python-prior/docs/Model200Response.md diff --git a/samples/client/petstore/python/docs/ModelReturn.md b/samples/client/petstore/python-prior/docs/ModelReturn.md similarity index 100% rename from samples/client/petstore/python/docs/ModelReturn.md rename to samples/client/petstore/python-prior/docs/ModelReturn.md diff --git a/samples/client/petstore/python/docs/Model_200Response.md b/samples/client/petstore/python-prior/docs/Model_200Response.md similarity index 100% rename from samples/client/petstore/python/docs/Model_200Response.md rename to samples/client/petstore/python-prior/docs/Model_200Response.md diff --git a/samples/client/petstore/python/docs/Model_Return.md b/samples/client/petstore/python-prior/docs/Model_Return.md similarity index 100% rename from samples/client/petstore/python/docs/Model_Return.md rename to samples/client/petstore/python-prior/docs/Model_Return.md diff --git a/samples/client/petstore/python/docs/Name.md b/samples/client/petstore/python-prior/docs/Name.md similarity index 100% rename from samples/client/petstore/python/docs/Name.md rename to samples/client/petstore/python-prior/docs/Name.md diff --git a/samples/client/petstore/python/docs/NumberOnly.md b/samples/client/petstore/python-prior/docs/NumberOnly.md similarity index 100% rename from samples/client/petstore/python/docs/NumberOnly.md rename to samples/client/petstore/python-prior/docs/NumberOnly.md diff --git a/samples/client/petstore/python/docs/NumberWithValidations.md b/samples/client/petstore/python-prior/docs/NumberWithValidations.md similarity index 100% rename from samples/client/petstore/python/docs/NumberWithValidations.md rename to samples/client/petstore/python-prior/docs/NumberWithValidations.md diff --git a/samples/client/petstore/python/docs/ObjectModelWithRefProps.md b/samples/client/petstore/python-prior/docs/ObjectModelWithRefProps.md similarity index 100% rename from samples/client/petstore/python/docs/ObjectModelWithRefProps.md rename to samples/client/petstore/python-prior/docs/ObjectModelWithRefProps.md diff --git a/samples/client/petstore/python/docs/Order.md b/samples/client/petstore/python-prior/docs/Order.md similarity index 100% rename from samples/client/petstore/python/docs/Order.md rename to samples/client/petstore/python-prior/docs/Order.md diff --git a/samples/client/petstore/python/docs/Parent.md b/samples/client/petstore/python-prior/docs/Parent.md similarity index 100% rename from samples/client/petstore/python/docs/Parent.md rename to samples/client/petstore/python-prior/docs/Parent.md diff --git a/samples/client/petstore/python/docs/ParentAllOf.md b/samples/client/petstore/python-prior/docs/ParentAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/ParentAllOf.md rename to samples/client/petstore/python-prior/docs/ParentAllOf.md diff --git a/samples/client/petstore/python/docs/ParentPet.md b/samples/client/petstore/python-prior/docs/ParentPet.md similarity index 100% rename from samples/client/petstore/python/docs/ParentPet.md rename to samples/client/petstore/python-prior/docs/ParentPet.md diff --git a/samples/client/petstore/python/docs/Pet.md b/samples/client/petstore/python-prior/docs/Pet.md similarity index 100% rename from samples/client/petstore/python/docs/Pet.md rename to samples/client/petstore/python-prior/docs/Pet.md diff --git a/samples/client/petstore/python/docs/PetApi.md b/samples/client/petstore/python-prior/docs/PetApi.md similarity index 100% rename from samples/client/petstore/python/docs/PetApi.md rename to samples/client/petstore/python-prior/docs/PetApi.md diff --git a/samples/client/petstore/python/docs/Player.md b/samples/client/petstore/python-prior/docs/Player.md similarity index 100% rename from samples/client/petstore/python/docs/Player.md rename to samples/client/petstore/python-prior/docs/Player.md diff --git a/samples/client/petstore/python/docs/Polygon.md b/samples/client/petstore/python-prior/docs/Polygon.md similarity index 100% rename from samples/client/petstore/python/docs/Polygon.md rename to samples/client/petstore/python-prior/docs/Polygon.md diff --git a/samples/client/petstore/python/docs/PolygonAllOf.md b/samples/client/petstore/python-prior/docs/PolygonAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/PolygonAllOf.md rename to samples/client/petstore/python-prior/docs/PolygonAllOf.md diff --git a/samples/client/petstore/python/docs/ReadOnlyFirst.md b/samples/client/petstore/python-prior/docs/ReadOnlyFirst.md similarity index 100% rename from samples/client/petstore/python/docs/ReadOnlyFirst.md rename to samples/client/petstore/python-prior/docs/ReadOnlyFirst.md diff --git a/samples/client/petstore/python/docs/Shape.md b/samples/client/petstore/python-prior/docs/Shape.md similarity index 100% rename from samples/client/petstore/python/docs/Shape.md rename to samples/client/petstore/python-prior/docs/Shape.md diff --git a/samples/client/petstore/python/docs/SpecialModelName.md b/samples/client/petstore/python-prior/docs/SpecialModelName.md similarity index 100% rename from samples/client/petstore/python/docs/SpecialModelName.md rename to samples/client/petstore/python-prior/docs/SpecialModelName.md diff --git a/samples/client/petstore/python/docs/Square.md b/samples/client/petstore/python-prior/docs/Square.md similarity index 100% rename from samples/client/petstore/python/docs/Square.md rename to samples/client/petstore/python-prior/docs/Square.md diff --git a/samples/client/petstore/python/docs/SquareAllOf.md b/samples/client/petstore/python-prior/docs/SquareAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/SquareAllOf.md rename to samples/client/petstore/python-prior/docs/SquareAllOf.md diff --git a/samples/client/petstore/python/docs/StoreApi.md b/samples/client/petstore/python-prior/docs/StoreApi.md similarity index 100% rename from samples/client/petstore/python/docs/StoreApi.md rename to samples/client/petstore/python-prior/docs/StoreApi.md diff --git a/samples/client/petstore/python/docs/StringBooleanMap.md b/samples/client/petstore/python-prior/docs/StringBooleanMap.md similarity index 100% rename from samples/client/petstore/python/docs/StringBooleanMap.md rename to samples/client/petstore/python-prior/docs/StringBooleanMap.md diff --git a/samples/client/petstore/python/docs/StringEnum.md b/samples/client/petstore/python-prior/docs/StringEnum.md similarity index 100% rename from samples/client/petstore/python/docs/StringEnum.md rename to samples/client/petstore/python-prior/docs/StringEnum.md diff --git a/samples/client/petstore/python/docs/Tag.md b/samples/client/petstore/python-prior/docs/Tag.md similarity index 100% rename from samples/client/petstore/python/docs/Tag.md rename to samples/client/petstore/python-prior/docs/Tag.md diff --git a/samples/client/petstore/python/docs/Triangle.md b/samples/client/petstore/python-prior/docs/Triangle.md similarity index 100% rename from samples/client/petstore/python/docs/Triangle.md rename to samples/client/petstore/python-prior/docs/Triangle.md diff --git a/samples/client/petstore/python/docs/TriangleAllOf.md b/samples/client/petstore/python-prior/docs/TriangleAllOf.md similarity index 100% rename from samples/client/petstore/python/docs/TriangleAllOf.md rename to samples/client/petstore/python-prior/docs/TriangleAllOf.md diff --git a/samples/client/petstore/python/docs/TypeHolderDefault.md b/samples/client/petstore/python-prior/docs/TypeHolderDefault.md similarity index 100% rename from samples/client/petstore/python/docs/TypeHolderDefault.md rename to samples/client/petstore/python-prior/docs/TypeHolderDefault.md diff --git a/samples/client/petstore/python/docs/TypeHolderExample.md b/samples/client/petstore/python-prior/docs/TypeHolderExample.md similarity index 100% rename from samples/client/petstore/python/docs/TypeHolderExample.md rename to samples/client/petstore/python-prior/docs/TypeHolderExample.md diff --git a/samples/client/petstore/python/docs/User.md b/samples/client/petstore/python-prior/docs/User.md similarity index 100% rename from samples/client/petstore/python/docs/User.md rename to samples/client/petstore/python-prior/docs/User.md diff --git a/samples/client/petstore/python/docs/UserApi.md b/samples/client/petstore/python-prior/docs/UserApi.md similarity index 100% rename from samples/client/petstore/python/docs/UserApi.md rename to samples/client/petstore/python-prior/docs/UserApi.md diff --git a/samples/client/petstore/python/docs/XmlItem.md b/samples/client/petstore/python-prior/docs/XmlItem.md similarity index 100% rename from samples/client/petstore/python/docs/XmlItem.md rename to samples/client/petstore/python-prior/docs/XmlItem.md diff --git a/samples/client/petstore/python-prior/git_push.sh b/samples/client/petstore/python-prior/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/client/petstore/python-prior/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/python/petstore_api/__init__.py b/samples/client/petstore/python-prior/petstore_api/__init__.py similarity index 100% rename from samples/client/petstore/python/petstore_api/__init__.py rename to samples/client/petstore/python-prior/petstore_api/__init__.py diff --git a/samples/client/petstore/python/petstore_api/api/__init__.py b/samples/client/petstore/python-prior/petstore_api/api/__init__.py similarity index 100% rename from samples/client/petstore/python/petstore_api/api/__init__.py rename to samples/client/petstore/python-prior/petstore_api/api/__init__.py diff --git a/samples/client/petstore/python/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-prior/petstore_api/api/another_fake_api.py similarity index 100% rename from samples/client/petstore/python/petstore_api/api/another_fake_api.py rename to samples/client/petstore/python-prior/petstore_api/api/another_fake_api.py diff --git a/samples/client/petstore/python/petstore_api/api/fake_api.py b/samples/client/petstore/python-prior/petstore_api/api/fake_api.py similarity index 100% rename from samples/client/petstore/python/petstore_api/api/fake_api.py rename to samples/client/petstore/python-prior/petstore_api/api/fake_api.py diff --git a/samples/client/petstore/python/petstore_api/api/fake_classname_tags123_api.py b/samples/client/petstore/python-prior/petstore_api/api/fake_classname_tags123_api.py similarity index 100% rename from samples/client/petstore/python/petstore_api/api/fake_classname_tags123_api.py rename to samples/client/petstore/python-prior/petstore_api/api/fake_classname_tags123_api.py diff --git a/samples/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-prior/petstore_api/api/fake_classname_tags_123_api.py similarity index 100% rename from samples/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py rename to samples/client/petstore/python-prior/petstore_api/api/fake_classname_tags_123_api.py diff --git a/samples/client/petstore/python/petstore_api/api/pet_api.py b/samples/client/petstore/python-prior/petstore_api/api/pet_api.py similarity index 100% rename from samples/client/petstore/python/petstore_api/api/pet_api.py rename to samples/client/petstore/python-prior/petstore_api/api/pet_api.py diff --git a/samples/client/petstore/python/petstore_api/api/store_api.py b/samples/client/petstore/python-prior/petstore_api/api/store_api.py similarity index 100% rename from samples/client/petstore/python/petstore_api/api/store_api.py rename to samples/client/petstore/python-prior/petstore_api/api/store_api.py diff --git a/samples/client/petstore/python/petstore_api/api/user_api.py b/samples/client/petstore/python-prior/petstore_api/api/user_api.py similarity index 100% rename from samples/client/petstore/python/petstore_api/api/user_api.py rename to samples/client/petstore/python-prior/petstore_api/api/user_api.py diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python-prior/petstore_api/api_client.py similarity index 100% rename from samples/client/petstore/python/petstore_api/api_client.py rename to samples/client/petstore/python-prior/petstore_api/api_client.py diff --git a/samples/client/petstore/python/petstore_api/apis/__init__.py b/samples/client/petstore/python-prior/petstore_api/apis/__init__.py similarity index 100% rename from samples/client/petstore/python/petstore_api/apis/__init__.py rename to samples/client/petstore/python-prior/petstore_api/apis/__init__.py diff --git a/samples/client/petstore/python/petstore_api/configuration.py b/samples/client/petstore/python-prior/petstore_api/configuration.py similarity index 100% rename from samples/client/petstore/python/petstore_api/configuration.py rename to samples/client/petstore/python-prior/petstore_api/configuration.py diff --git a/samples/client/petstore/python/petstore_api/exceptions.py b/samples/client/petstore/python-prior/petstore_api/exceptions.py similarity index 100% rename from samples/client/petstore/python/petstore_api/exceptions.py rename to samples/client/petstore/python-prior/petstore_api/exceptions.py diff --git a/samples/client/petstore/python/petstore_api/model/__init__.py b/samples/client/petstore/python-prior/petstore_api/model/__init__.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/__init__.py rename to samples/client/petstore/python-prior/petstore_api/model/__init__.py diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py b/samples/client/petstore/python-prior/petstore_api/model/additional_properties_any_type.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py rename to samples/client/petstore/python-prior/petstore_api/model/additional_properties_any_type.py diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_array.py b/samples/client/petstore/python-prior/petstore_api/model/additional_properties_array.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/additional_properties_array.py rename to samples/client/petstore/python-prior/petstore_api/model/additional_properties_array.py diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py b/samples/client/petstore/python-prior/petstore_api/model/additional_properties_boolean.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py rename to samples/client/petstore/python-prior/petstore_api/model/additional_properties_boolean.py diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_class.py b/samples/client/petstore/python-prior/petstore_api/model/additional_properties_class.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/additional_properties_class.py rename to samples/client/petstore/python-prior/petstore_api/model/additional_properties_class.py diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py b/samples/client/petstore/python-prior/petstore_api/model/additional_properties_integer.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/additional_properties_integer.py rename to samples/client/petstore/python-prior/petstore_api/model/additional_properties_integer.py diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_number.py b/samples/client/petstore/python-prior/petstore_api/model/additional_properties_number.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/additional_properties_number.py rename to samples/client/petstore/python-prior/petstore_api/model/additional_properties_number.py diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_object.py b/samples/client/petstore/python-prior/petstore_api/model/additional_properties_object.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/additional_properties_object.py rename to samples/client/petstore/python-prior/petstore_api/model/additional_properties_object.py diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_string.py b/samples/client/petstore/python-prior/petstore_api/model/additional_properties_string.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/additional_properties_string.py rename to samples/client/petstore/python-prior/petstore_api/model/additional_properties_string.py diff --git a/samples/client/petstore/python/petstore_api/model/animal.py b/samples/client/petstore/python-prior/petstore_api/model/animal.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/animal.py rename to samples/client/petstore/python-prior/petstore_api/model/animal.py diff --git a/samples/client/petstore/python/petstore_api/model/animal_farm.py b/samples/client/petstore/python-prior/petstore_api/model/animal_farm.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/animal_farm.py rename to samples/client/petstore/python-prior/petstore_api/model/animal_farm.py diff --git a/samples/client/petstore/python/petstore_api/model/api_response.py b/samples/client/petstore/python-prior/petstore_api/model/api_response.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/api_response.py rename to samples/client/petstore/python-prior/petstore_api/model/api_response.py diff --git a/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py b/samples/client/petstore/python-prior/petstore_api/model/array_of_array_of_number_only.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py rename to samples/client/petstore/python-prior/petstore_api/model/array_of_array_of_number_only.py diff --git a/samples/client/petstore/python/petstore_api/model/array_of_number_only.py b/samples/client/petstore/python-prior/petstore_api/model/array_of_number_only.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/array_of_number_only.py rename to samples/client/petstore/python-prior/petstore_api/model/array_of_number_only.py diff --git a/samples/client/petstore/python/petstore_api/model/array_test.py b/samples/client/petstore/python-prior/petstore_api/model/array_test.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/array_test.py rename to samples/client/petstore/python-prior/petstore_api/model/array_test.py diff --git a/samples/client/petstore/python/petstore_api/model/capitalization.py b/samples/client/petstore/python-prior/petstore_api/model/capitalization.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/capitalization.py rename to samples/client/petstore/python-prior/petstore_api/model/capitalization.py diff --git a/samples/client/petstore/python/petstore_api/model/cat.py b/samples/client/petstore/python-prior/petstore_api/model/cat.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/cat.py rename to samples/client/petstore/python-prior/petstore_api/model/cat.py diff --git a/samples/client/petstore/python/petstore_api/model/cat_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/cat_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/cat_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/cat_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/category.py b/samples/client/petstore/python-prior/petstore_api/model/category.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/category.py rename to samples/client/petstore/python-prior/petstore_api/model/category.py diff --git a/samples/client/petstore/python/petstore_api/model/child.py b/samples/client/petstore/python-prior/petstore_api/model/child.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/child.py rename to samples/client/petstore/python-prior/petstore_api/model/child.py diff --git a/samples/client/petstore/python/petstore_api/model/child_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/child_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/child_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/child_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/child_cat.py b/samples/client/petstore/python-prior/petstore_api/model/child_cat.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/child_cat.py rename to samples/client/petstore/python-prior/petstore_api/model/child_cat.py diff --git a/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/child_cat_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/child_cat_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/child_cat_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/child_dog.py b/samples/client/petstore/python-prior/petstore_api/model/child_dog.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/child_dog.py rename to samples/client/petstore/python-prior/petstore_api/model/child_dog.py diff --git a/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/child_dog_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/child_dog_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/child_dog_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/child_lizard.py b/samples/client/petstore/python-prior/petstore_api/model/child_lizard.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/child_lizard.py rename to samples/client/petstore/python-prior/petstore_api/model/child_lizard.py diff --git a/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/child_lizard_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/child_lizard_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/class_model.py b/samples/client/petstore/python-prior/petstore_api/model/class_model.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/class_model.py rename to samples/client/petstore/python-prior/petstore_api/model/class_model.py diff --git a/samples/client/petstore/python/petstore_api/model/client.py b/samples/client/petstore/python-prior/petstore_api/model/client.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/client.py rename to samples/client/petstore/python-prior/petstore_api/model/client.py diff --git a/samples/client/petstore/python/petstore_api/model/dog.py b/samples/client/petstore/python-prior/petstore_api/model/dog.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/dog.py rename to samples/client/petstore/python-prior/petstore_api/model/dog.py diff --git a/samples/client/petstore/python/petstore_api/model/dog_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/dog_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/dog_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/dog_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/enum_arrays.py b/samples/client/petstore/python-prior/petstore_api/model/enum_arrays.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/enum_arrays.py rename to samples/client/petstore/python-prior/petstore_api/model/enum_arrays.py diff --git a/samples/client/petstore/python/petstore_api/model/enum_class.py b/samples/client/petstore/python-prior/petstore_api/model/enum_class.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/enum_class.py rename to samples/client/petstore/python-prior/petstore_api/model/enum_class.py diff --git a/samples/client/petstore/python/petstore_api/model/enum_test.py b/samples/client/petstore/python-prior/petstore_api/model/enum_test.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/enum_test.py rename to samples/client/petstore/python-prior/petstore_api/model/enum_test.py diff --git a/samples/client/petstore/python/petstore_api/model/file.py b/samples/client/petstore/python-prior/petstore_api/model/file.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/file.py rename to samples/client/petstore/python-prior/petstore_api/model/file.py diff --git a/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py b/samples/client/petstore/python-prior/petstore_api/model/file_schema_test_class.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/file_schema_test_class.py rename to samples/client/petstore/python-prior/petstore_api/model/file_schema_test_class.py diff --git a/samples/client/petstore/python/petstore_api/model/format_test.py b/samples/client/petstore/python-prior/petstore_api/model/format_test.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/format_test.py rename to samples/client/petstore/python-prior/petstore_api/model/format_test.py diff --git a/samples/client/petstore/python/petstore_api/model/grandparent.py b/samples/client/petstore/python-prior/petstore_api/model/grandparent.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/grandparent.py rename to samples/client/petstore/python-prior/petstore_api/model/grandparent.py diff --git a/samples/client/petstore/python/petstore_api/model/grandparent_animal.py b/samples/client/petstore/python-prior/petstore_api/model/grandparent_animal.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/grandparent_animal.py rename to samples/client/petstore/python-prior/petstore_api/model/grandparent_animal.py diff --git a/samples/client/petstore/python/petstore_api/model/has_only_read_only.py b/samples/client/petstore/python-prior/petstore_api/model/has_only_read_only.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/has_only_read_only.py rename to samples/client/petstore/python-prior/petstore_api/model/has_only_read_only.py diff --git a/samples/client/petstore/python/petstore_api/model/list.py b/samples/client/petstore/python-prior/petstore_api/model/list.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/list.py rename to samples/client/petstore/python-prior/petstore_api/model/list.py diff --git a/samples/client/petstore/python/petstore_api/model/map_test.py b/samples/client/petstore/python-prior/petstore_api/model/map_test.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/map_test.py rename to samples/client/petstore/python-prior/petstore_api/model/map_test.py diff --git a/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-prior/petstore_api/model/mixed_properties_and_additional_properties_class.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py rename to samples/client/petstore/python-prior/petstore_api/model/mixed_properties_and_additional_properties_class.py diff --git a/samples/client/petstore/python/petstore_api/model/model200_response.py b/samples/client/petstore/python-prior/petstore_api/model/model200_response.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/model200_response.py rename to samples/client/petstore/python-prior/petstore_api/model/model200_response.py diff --git a/samples/client/petstore/python/petstore_api/model/model_200_response.py b/samples/client/petstore/python-prior/petstore_api/model/model_200_response.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/model_200_response.py rename to samples/client/petstore/python-prior/petstore_api/model/model_200_response.py diff --git a/samples/client/petstore/python/petstore_api/model/model_return.py b/samples/client/petstore/python-prior/petstore_api/model/model_return.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/model_return.py rename to samples/client/petstore/python-prior/petstore_api/model/model_return.py diff --git a/samples/client/petstore/python/petstore_api/model/name.py b/samples/client/petstore/python-prior/petstore_api/model/name.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/name.py rename to samples/client/petstore/python-prior/petstore_api/model/name.py diff --git a/samples/client/petstore/python/petstore_api/model/number_only.py b/samples/client/petstore/python-prior/petstore_api/model/number_only.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/number_only.py rename to samples/client/petstore/python-prior/petstore_api/model/number_only.py diff --git a/samples/client/petstore/python/petstore_api/model/number_with_validations.py b/samples/client/petstore/python-prior/petstore_api/model/number_with_validations.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/number_with_validations.py rename to samples/client/petstore/python-prior/petstore_api/model/number_with_validations.py diff --git a/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py b/samples/client/petstore/python-prior/petstore_api/model/object_model_with_ref_props.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py rename to samples/client/petstore/python-prior/petstore_api/model/object_model_with_ref_props.py diff --git a/samples/client/petstore/python/petstore_api/model/order.py b/samples/client/petstore/python-prior/petstore_api/model/order.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/order.py rename to samples/client/petstore/python-prior/petstore_api/model/order.py diff --git a/samples/client/petstore/python/petstore_api/model/parent.py b/samples/client/petstore/python-prior/petstore_api/model/parent.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/parent.py rename to samples/client/petstore/python-prior/petstore_api/model/parent.py diff --git a/samples/client/petstore/python/petstore_api/model/parent_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/parent_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/parent_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/parent_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/parent_pet.py b/samples/client/petstore/python-prior/petstore_api/model/parent_pet.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/parent_pet.py rename to samples/client/petstore/python-prior/petstore_api/model/parent_pet.py diff --git a/samples/client/petstore/python/petstore_api/model/pet.py b/samples/client/petstore/python-prior/petstore_api/model/pet.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/pet.py rename to samples/client/petstore/python-prior/petstore_api/model/pet.py diff --git a/samples/client/petstore/python/petstore_api/model/player.py b/samples/client/petstore/python-prior/petstore_api/model/player.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/player.py rename to samples/client/petstore/python-prior/petstore_api/model/player.py diff --git a/samples/client/petstore/python/petstore_api/model/polygon.py b/samples/client/petstore/python-prior/petstore_api/model/polygon.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/polygon.py rename to samples/client/petstore/python-prior/petstore_api/model/polygon.py diff --git a/samples/client/petstore/python/petstore_api/model/polygon_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/polygon_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/polygon_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/polygon_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/read_only_first.py b/samples/client/petstore/python-prior/petstore_api/model/read_only_first.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/read_only_first.py rename to samples/client/petstore/python-prior/petstore_api/model/read_only_first.py diff --git a/samples/client/petstore/python/petstore_api/model/shape.py b/samples/client/petstore/python-prior/petstore_api/model/shape.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/shape.py rename to samples/client/petstore/python-prior/petstore_api/model/shape.py diff --git a/samples/client/petstore/python/petstore_api/model/special_model_name.py b/samples/client/petstore/python-prior/petstore_api/model/special_model_name.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/special_model_name.py rename to samples/client/petstore/python-prior/petstore_api/model/special_model_name.py diff --git a/samples/client/petstore/python/petstore_api/model/square.py b/samples/client/petstore/python-prior/petstore_api/model/square.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/square.py rename to samples/client/petstore/python-prior/petstore_api/model/square.py diff --git a/samples/client/petstore/python/petstore_api/model/square_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/square_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/square_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/square_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/string_boolean_map.py b/samples/client/petstore/python-prior/petstore_api/model/string_boolean_map.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/string_boolean_map.py rename to samples/client/petstore/python-prior/petstore_api/model/string_boolean_map.py diff --git a/samples/client/petstore/python/petstore_api/model/string_enum.py b/samples/client/petstore/python-prior/petstore_api/model/string_enum.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/string_enum.py rename to samples/client/petstore/python-prior/petstore_api/model/string_enum.py diff --git a/samples/client/petstore/python/petstore_api/model/tag.py b/samples/client/petstore/python-prior/petstore_api/model/tag.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/tag.py rename to samples/client/petstore/python-prior/petstore_api/model/tag.py diff --git a/samples/client/petstore/python/petstore_api/model/triangle.py b/samples/client/petstore/python-prior/petstore_api/model/triangle.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/triangle.py rename to samples/client/petstore/python-prior/petstore_api/model/triangle.py diff --git a/samples/client/petstore/python/petstore_api/model/triangle_all_of.py b/samples/client/petstore/python-prior/petstore_api/model/triangle_all_of.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/triangle_all_of.py rename to samples/client/petstore/python-prior/petstore_api/model/triangle_all_of.py diff --git a/samples/client/petstore/python/petstore_api/model/type_holder_default.py b/samples/client/petstore/python-prior/petstore_api/model/type_holder_default.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/type_holder_default.py rename to samples/client/petstore/python-prior/petstore_api/model/type_holder_default.py diff --git a/samples/client/petstore/python/petstore_api/model/type_holder_example.py b/samples/client/petstore/python-prior/petstore_api/model/type_holder_example.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/type_holder_example.py rename to samples/client/petstore/python-prior/petstore_api/model/type_holder_example.py diff --git a/samples/client/petstore/python/petstore_api/model/user.py b/samples/client/petstore/python-prior/petstore_api/model/user.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/user.py rename to samples/client/petstore/python-prior/petstore_api/model/user.py diff --git a/samples/client/petstore/python/petstore_api/model/xml_item.py b/samples/client/petstore/python-prior/petstore_api/model/xml_item.py similarity index 100% rename from samples/client/petstore/python/petstore_api/model/xml_item.py rename to samples/client/petstore/python-prior/petstore_api/model/xml_item.py diff --git a/samples/client/petstore/python-prior/petstore_api/model_utils.py b/samples/client/petstore/python-prior/petstore_api/model_utils.py new file mode 100644 index 0000000000..ab2d0087df --- /dev/null +++ b/samples/client/petstore/python-prior/petstore_api/model_utils.py @@ -0,0 +1,2058 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from datetime import date, datetime # noqa: F401 +from copy import deepcopy +import inspect +import io +import os +import pprint +import re +import tempfile +import uuid + +from dateutil.parser import parse + +from petstore_api.exceptions import ( + ApiKeyError, + ApiAttributeError, + ApiTypeError, + ApiValueError, +) + +none_type = type(None) +file_type = io.IOBase + + +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python( + kwargs, _self if isinstance( + _self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + +class cached_property(object): + # this caches the result of the function call for fn with no inputs + # use this as a decorator on function methods that you want converted + # into cached properties + result_key = '_results' + + def __init__(self, fn): + self._fn = fn + + def __get__(self, instance, cls=None): + if self.result_key in vars(self): + return vars(self)[self.result_key] + else: + result = self._fn() + setattr(self, self.result_key, result) + return result + + +PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) + + +def allows_single_value_input(cls): + """ + This function returns True if the input composed schema model or any + descendant model allows a value only input + This is true for cases where oneOf contains items like: + oneOf: + - float + - NumberWithValidation + - StringEnum + - ArrayModel + - null + TODO: lru_cache this + """ + if ( + issubclass(cls, ModelSimple) or + cls in PRIMITIVE_TYPES + ): + return True + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return False + return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) + return False + + +def composed_model_input_classes(cls): + """ + This function returns a list of the possible models that can be accepted as + inputs. + TODO: lru_cache this + """ + if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: + return [cls] + elif issubclass(cls, ModelNormal): + if cls.discriminator is None: + return [cls] + else: + return get_discriminated_classes(cls) + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return [] + if cls.discriminator is None: + input_classes = [] + for c in cls._composed_schemas['oneOf']: + input_classes.extend(composed_model_input_classes(c)) + return input_classes + else: + return get_discriminated_classes(cls) + return [] + + +class OpenApiModel(object): + """The base class for all OpenAPIModels""" + + def set_attribute(self, name, value): + # this is only used to set properties on self + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + + if name in self.openapi_types: + required_types_mixed = self.openapi_types[name] + elif self.additional_properties_type is None: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + path_to_item + ) + elif self.additional_properties_type is not None: + required_types_mixed = self.additional_properties_type + + if get_simple_class(name) != str: + error_msg = type_error_message( + var_name=name, + var_value=name, + valid_classes=(str,), + key_type=True + ) + raise ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=(str,), + key_type=True + ) + + if self._check_type: + value = validate_and_convert_types( + value, required_types_mixed, path_to_item, self._spec_property_naming, + self._check_type, configuration=self._configuration) + if (name,) in self.allowed_values: + check_allowed_values( + self.allowed_values, + (name,), + value + ) + if (name,) in self.validations: + check_validations( + self.validations, + (name,), + value, + self._configuration + ) + self.__dict__['_data_store'][name] = value + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other + + def __setattr__(self, attr, value): + """set the value of an attribute using dot notation: `instance.attr = val`""" + self[attr] = value + + def __getattr__(self, attr): + """get the value of an attribute using dot notation: `instance.attr`""" + return self.__getitem__(attr) + + def __copy__(self): + cls = self.__class__ + if self.get("_spec_property_naming", False): + return cls._new_from_openapi_data(**self.__dict__) + else: + return cls.__new__(cls, **self.__dict__) + + def __deepcopy__(self, memo): + cls = self.__class__ + + if self.get("_spec_property_naming", False): + new_inst = cls._new_from_openapi_data() + else: + new_inst = cls.__new__(cls, **self.__dict__) + + for k, v in self.__dict__.items(): + setattr(new_inst, k, deepcopy(v, memo)) + return new_inst + + + def __new__(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return super(OpenApiModel, cls).__new__(cls) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return super(OpenApiModel, cls).__new__(cls) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = super(OpenApiModel, cls).__new__(cls) + self_inst.__init__(*args, **kwargs) + + if kwargs.get("_spec_property_naming", False): + # when true, implies new is from deserialization + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + else: + new_inst = new_cls.__new__(new_cls, *args, **kwargs) + new_inst.__init__(*args, **kwargs) + + return new_inst + + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + +class ModelSimple(OpenApiModel): + """the parent class of models whose type != object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_str(self): + """Returns the string representation of the model""" + return str(self.value) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + this_val = self._data_store['value'] + that_val = other._data_store['value'] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + return vals_equal + + +class ModelNormal(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +class ModelComposed(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi and have oneOf/allOf/anyOf + + When one sets a property we use var_name_to_model_instances to store the value in + the correct class instances + run any type checking + validation code. + When one gets a property we use var_name_to_model_instances to get the value + from the correct class instances. + This allows multiple composed schemas to contain the same property with additive + constraints on the value. + + _composed_schemas (dict) stores the anyOf/allOf/oneOf classes + key (str): allOf/oneOf/anyOf + value (list): the classes in the XOf definition. + Note: none_type can be included when the openapi document version >= 3.1.0 + _composed_instances (list): stores a list of instances of the composed schemas + defined in _composed_schemas. When properties are accessed in the self instance, + they are returned from the self._data_store or the data stores in the instances + in self._composed_schemas + _var_name_to_model_instances (dict): maps between a variable name on self and + the composed instances (self included) which contain that data + key (str): property name + value (list): list of class instances, self or instances in _composed_instances + which contain the value that the key is referring to. + """ + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None + + __unset_attribute_value__ = object() + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + # get the attribute from the correct instance + model_instances = self._var_name_to_model_instances.get(name) + values = [] + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + v = model_instance._data_store[name] + if v not in values: + values.append(v) + len_values = len(values) + if len_values == 0: + return default + elif len_values == 1: + return values[0] + elif len_values > 1: + raise ApiValueError( + "Values stored for property {0} in {1} differ when looking " + "at self and self's composed instances. All values must be " + "the same".format(name, type(self).__name__), + [e for e in [self._path_to_item, name] if e] + ) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + value = self.get(name, self.__unset_attribute_value__) + if value is self.__unset_attribute_value__: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + return value + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + + if name in self.required_properties: + return name in self.__dict__ + + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + return True + + return False + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +COERCION_INDEX_BY_TYPE = { + ModelComposed: 0, + ModelNormal: 1, + ModelSimple: 2, + none_type: 3, # The type of 'None'. + list: 4, + dict: 5, + float: 6, + int: 7, + bool: 8, + datetime: 9, + date: 10, + str: 11, + file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. +} + +# these are used to limit what type conversions we try to do +# when we have a valid type already and we want to try converting +# to another type +UPCONVERSION_TYPE_PAIRS = ( + (str, datetime), + (str, date), + # A float may be serialized as an integer, e.g. '3' is a valid serialized float. + (int, float), + (list, ModelComposed), + (dict, ModelComposed), + (str, ModelComposed), + (int, ModelComposed), + (float, ModelComposed), + (list, ModelComposed), + (list, ModelNormal), + (dict, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), +) + +COERCIBLE_TYPE_PAIRS = { + False: ( # client instantiation of a model with client data + # (dict, ModelComposed), + # (list, ModelComposed), + # (dict, ModelNormal), + # (list, ModelNormal), + # (str, ModelSimple), + # (int, ModelSimple), + # (float, ModelSimple), + # (list, ModelSimple), + # (str, int), + # (str, float), + # (str, datetime), + # (str, date), + # (int, str), + # (float, str), + ), + True: ( # server -> client data + (dict, ModelComposed), + (list, ModelComposed), + (dict, ModelNormal), + (list, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), + # (str, int), + # (str, float), + (str, datetime), + (str, date), + # (int, str), + # (float, str), + (str, file_type) + ), +} + + +def get_simple_class(input_value): + """Returns an input_value's simple class that we will use for type checking + Python2: + float and int will return int, where int is the python3 int backport + str and unicode will return str, where str is the python3 str backport + Note: float and int ARE both instances of int backport + Note: str_py2 and unicode_py2 are NOT both instances of str backport + + Args: + input_value (class/class_instance): the item for which we will return + the simple class + """ + if isinstance(input_value, type): + # input_value is a class + return input_value + elif isinstance(input_value, tuple): + return tuple + elif isinstance(input_value, list): + return list + elif isinstance(input_value, dict): + return dict + elif isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, file_type): + return file_type + elif isinstance(input_value, bool): + # this must be higher than the int check because + # isinstance(True, int) == True + return bool + elif isinstance(input_value, int): + return int + elif isinstance(input_value, datetime): + # this must be higher than the date check because + # isinstance(datetime_instance, date) == True + return datetime + elif isinstance(input_value, date): + return date + elif isinstance(input_value, str): + return str + return type(input_value) + + +def check_allowed_values(allowed_values, input_variable_path, input_values): + """Raises an exception if the input_values are not allowed + + Args: + allowed_values (dict): the allowed_values dict + input_variable_path (tuple): the path to the input variable + input_values (list/str/int/float/date/datetime): the values that we + are checking to see if they are in allowed_values + """ + these_allowed_values = list(allowed_values[input_variable_path].values()) + if (isinstance(input_values, list) + and not set(input_values).issubset( + set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values) - set(these_allowed_values))), + raise ApiValueError( + "Invalid values for `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (isinstance(input_values, dict) + and not set( + input_values.keys()).issubset(set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values.keys()) - set(these_allowed_values))) + raise ApiValueError( + "Invalid keys in `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (not isinstance(input_values, (list, dict)) + and input_values not in these_allowed_values): + raise ApiValueError( + "Invalid value for `%s` (%s), must be one of %s" % + ( + input_variable_path[0], + input_values, + these_allowed_values + ) + ) + + +def is_json_validation_enabled(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + +def check_validations( + validations, input_variable_path, input_values, + configuration=None): + """Raises an exception if the input_values are invalid + + Args: + validations (dict): the validation dictionary. + input_variable_path (tuple): the path to the input variable. + input_values (list/str/int/float/date/datetime): the values that we + are checking. + configuration (Configuration): the configuration class. + """ + + if input_values is None: + return + + current_validations = validations[input_variable_path] + if (is_json_validation_enabled('multipleOf', configuration) and + 'multiple_of' in current_validations and + isinstance(input_values, (int, float)) and + not (float(input_values) / current_validations['multiple_of']).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + raise ApiValueError( + "Invalid value for `%s`, value must be a multiple of " + "`%s`" % ( + input_variable_path[0], + current_validations['multiple_of'] + ) + ) + + if (is_json_validation_enabled('maxLength', configuration) and + 'max_length' in current_validations and + len(input_values) > current_validations['max_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['max_length'] + ) + ) + + if (is_json_validation_enabled('minLength', configuration) and + 'min_length' in current_validations and + len(input_values) < current_validations['min_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be greater than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['min_length'] + ) + ) + + if (is_json_validation_enabled('maxItems', configuration) and + 'max_items' in current_validations and + len(input_values) > current_validations['max_items']): + raise ApiValueError( + "Invalid value for `%s`, number of items must be less than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['max_items'] + ) + ) + + if (is_json_validation_enabled('minItems', configuration) and + 'min_items' in current_validations and + len(input_values) < current_validations['min_items']): + raise ValueError( + "Invalid value for `%s`, number of items must be greater than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['min_items'] + ) + ) + + items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', + 'inclusive_minimum') + if (any(item in current_validations for item in items)): + if isinstance(input_values, list): + max_val = max(input_values) + min_val = min(input_values) + elif isinstance(input_values, dict): + max_val = max(input_values.values()) + min_val = min(input_values.values()) + else: + max_val = input_values + min_val = input_values + + if (is_json_validation_enabled('exclusiveMaximum', configuration) and + 'exclusive_maximum' in current_validations and + max_val >= current_validations['exclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than `%s`" % ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('maximum', configuration) and + 'inclusive_maximum' in current_validations and + max_val > current_validations['inclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['inclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('exclusiveMinimum', configuration) and + 'exclusive_minimum' in current_validations and + min_val <= current_validations['exclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than `%s`" % + ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('minimum', configuration) and + 'inclusive_minimum' in current_validations and + min_val < current_validations['inclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than or equal " + "to `%s`" % ( + input_variable_path[0], + current_validations['inclusive_minimum'] + ) + ) + flags = current_validations.get('regex', {}).get('flags', 0) + if (is_json_validation_enabled('pattern', configuration) and + 'regex' in current_validations and + not re.search(current_validations['regex']['pattern'], + input_values, flags=flags)): + err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( + input_variable_path[0], + current_validations['regex']['pattern'] + ) + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + err_msg = r"%s with flags=`%s`" % (err_msg, flags) + raise ApiValueError(err_msg) + + +def order_response_types(required_types): + """Returns the required types sorted in coercion order + + Args: + required_types (list/tuple): collection of classes or instance of + list or dict with class information inside it. + + Returns: + (list): coercion order sorted collection of classes or instance + of list or dict with class information inside it. + """ + + def index_getter(class_or_instance): + if isinstance(class_or_instance, list): + return COERCION_INDEX_BY_TYPE[list] + elif isinstance(class_or_instance, dict): + return COERCION_INDEX_BY_TYPE[dict] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelComposed)): + return COERCION_INDEX_BY_TYPE[ModelComposed] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelNormal)): + return COERCION_INDEX_BY_TYPE[ModelNormal] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelSimple)): + return COERCION_INDEX_BY_TYPE[ModelSimple] + elif class_or_instance in COERCION_INDEX_BY_TYPE: + return COERCION_INDEX_BY_TYPE[class_or_instance] + raise ApiValueError("Unsupported type: %s" % class_or_instance) + + sorted_types = sorted( + required_types, + key=lambda class_or_instance: index_getter(class_or_instance) + ) + return sorted_types + + +def remove_uncoercible(required_types_classes, current_item, spec_property_naming, + must_convert=True): + """Only keeps the type conversions that are possible + + Args: + required_types_classes (tuple): tuple of classes that are required + these should be ordered by COERCION_INDEX_BY_TYPE + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + current_item (any): the current item (input data) to be converted + + Keyword Args: + must_convert (bool): if True the item to convert is of the wrong + type and we want a big list of coercibles + if False, we want a limited list of coercibles + + Returns: + (list): the remaining coercible required types, classes only + """ + current_type_simple = get_simple_class(current_item) + + results_classes = [] + for required_type_class in required_types_classes: + # convert our models to OpenApiModel + required_type_class_simplified = required_type_class + if isinstance(required_type_class_simplified, type): + if issubclass(required_type_class_simplified, ModelComposed): + required_type_class_simplified = ModelComposed + elif issubclass(required_type_class_simplified, ModelNormal): + required_type_class_simplified = ModelNormal + elif issubclass(required_type_class_simplified, ModelSimple): + required_type_class_simplified = ModelSimple + + if required_type_class_simplified == current_type_simple: + # don't consider converting to one's own class + continue + + class_pair = (current_type_simple, required_type_class_simplified) + if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: + results_classes.append(required_type_class) + elif class_pair in UPCONVERSION_TYPE_PAIRS: + results_classes.append(required_type_class) + return results_classes + + +def get_discriminated_classes(cls): + """ + Returns all the classes that a discriminator converts to + TODO: lru_cache this + """ + possible_classes = [] + key = list(cls.discriminator.keys())[0] + if is_type_nullable(cls): + possible_classes.append(cls) + for discr_cls in cls.discriminator[key].values(): + if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: + possible_classes.extend(get_discriminated_classes(discr_cls)) + else: + possible_classes.append(discr_cls) + return possible_classes + + +def get_possible_classes(cls, from_server_context): + # TODO: lru_cache this + possible_classes = [cls] + if from_server_context: + return possible_classes + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + possible_classes = [] + possible_classes.extend(get_discriminated_classes(cls)) + elif issubclass(cls, ModelComposed): + possible_classes.extend(composed_model_input_classes(cls)) + return possible_classes + + +def get_required_type_classes(required_types_mixed, spec_property_naming): + """Converts the tuple required_types into a tuple and a dict described + below + + Args: + required_types_mixed (tuple/list): will contain either classes or + instance of list or dict + spec_property_naming (bool): if True these values came from the + server, and we use the data types in our endpoints. + If False, we are client side and we need to include + oneOf and discriminator classes inside the data types in our endpoints + + Returns: + (valid_classes, dict_valid_class_to_child_types_mixed): + valid_classes (tuple): the valid classes that the current item + should be + dict_valid_class_to_child_types_mixed (dict): + valid_class (class): this is the key + child_types_mixed (list/dict/tuple): describes the valid child + types + """ + valid_classes = [] + child_req_types_by_current_type = {} + for required_type in required_types_mixed: + if isinstance(required_type, list): + valid_classes.append(list) + child_req_types_by_current_type[list] = required_type + elif isinstance(required_type, tuple): + valid_classes.append(tuple) + child_req_types_by_current_type[tuple] = required_type + elif isinstance(required_type, dict): + valid_classes.append(dict) + child_req_types_by_current_type[dict] = required_type[str] + else: + valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) + return tuple(valid_classes), child_req_types_by_current_type + + +def change_keys_js_to_python(input_dict, model_class): + """ + Converts from javascript_key keys in the input_dict to python_keys in + the output dict using the mapping in model_class. + If the input_dict contains a key which does not declared in the model_class, + the key is added to the output dict as is. The assumption is the model_class + may have undeclared properties (additionalProperties attribute in the OAS + document). + """ + + if getattr(model_class, 'attribute_map', None) is None: + return input_dict + output_dict = {} + reversed_attr_map = {value: key for key, value in + model_class.attribute_map.items()} + for javascript_key, value in input_dict.items(): + python_key = reversed_attr_map.get(javascript_key) + if python_key is None: + # if the key is unknown, it is in error or it is an + # additionalProperties variable + python_key = javascript_key + output_dict[python_key] = value + return output_dict + + +def get_type_error(var_value, path_to_item, valid_classes, key_type=False): + error_msg = type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type + ) + + +def deserialize_primitive(data, klass, path_to_item): + """Deserializes string to primitive type. + + :param data: str/int/float + :param klass: str/class the class to convert to + + :return: int, float, str, bool, date, datetime + """ + additional_message = "" + try: + if klass in {datetime, date}: + additional_message = ( + "If you need your parameter to have a fallback " + "string value, please set its type as `type: {}` in your " + "spec. That allows the value to be any type. " + ) + if klass == datetime: + if len(data) < 8: + raise ValueError("This is not a datetime") + # The string should be in iso8601 datetime format. + parsed_datetime = parse(data) + date_only = ( + parsed_datetime.hour == 0 and + parsed_datetime.minute == 0 and + parsed_datetime.second == 0 and + parsed_datetime.tzinfo is None and + 8 <= len(data) <= 10 + ) + if date_only: + raise ValueError("This is a date, not a datetime") + return parsed_datetime + elif klass == date: + if len(data) < 8: + raise ValueError("This is not a date") + return parse(data).date() + else: + converted_value = klass(data) + if isinstance(data, str) and klass == float: + if str(converted_value) != data: + # '7' -> 7.0 -> '7.0' != '7' + raise ValueError('This is not a float') + return converted_value + except (OverflowError, ValueError) as ex: + # parse can raise OverflowError + raise ApiValueError( + "{0}Failed to parse {1} as {2}".format( + additional_message, repr(data), klass.__name__ + ), + path_to_item=path_to_item + ) from ex + + +def get_discriminator_class(model_class, + discr_name, + discr_value, cls_visited): + """Returns the child class specified by the discriminator. + + Args: + model_class (OpenApiModel): the model class. + discr_name (string): the name of the discriminator property. + discr_value (any): the discriminator value. + cls_visited (list): list of model classes that have been visited. + Used to determine the discriminator class without + visiting circular references indefinitely. + + Returns: + used_model_class (class/None): the chosen child class that will be used + to deserialize the data, for example dog.Dog. + If a class is not found, None is returned. + """ + + if model_class in cls_visited: + # The class has already been visited and no suitable class was found. + return None + cls_visited.append(model_class) + used_model_class = None + if discr_name in model_class.discriminator: + class_name_to_discr_class = model_class.discriminator[discr_name] + used_model_class = class_name_to_discr_class.get(discr_value) + if used_model_class is None: + # We didn't find a discriminated class in class_name_to_discr_class. + # So look in the ancestor or descendant discriminators + # The discriminator mapping may exist in a descendant (anyOf, oneOf) + # or ancestor (allOf). + # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat + # hierarchy, the discriminator mappings may be defined at any level + # in the hierarchy. + # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig + # if we try to make BasquePig from mammal, we need to travel through + # the oneOf descendant discriminators to find BasquePig + descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ + model_class._composed_schemas.get('anyOf', ()) + ancestor_classes = model_class._composed_schemas.get('allOf', ()) + possible_classes = descendant_classes + ancestor_classes + for cls in possible_classes: + # Check if the schema has inherited discriminators. + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + used_model_class = get_discriminator_class( + cls, discr_name, discr_value, cls_visited) + if used_model_class is not None: + return used_model_class + return used_model_class + + +def deserialize_model(model_data, model_class, path_to_item, check_type, + configuration, spec_property_naming): + """Deserializes model_data to model instance. + + Args: + model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model + model_class (OpenApiModel): the model class + path_to_item (list): path to the model in the received data + check_type (bool): whether to check the data tupe for the values in + the model + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + + Returns: + model instance + + Raise: + ApiTypeError + ApiValueError + ApiKeyError + """ + + kw_args = dict(_check_type=check_type, + _path_to_item=path_to_item, + _configuration=configuration, + _spec_property_naming=spec_property_naming) + + if issubclass(model_class, ModelSimple): + return model_class._new_from_openapi_data(model_data, **kw_args) + elif isinstance(model_data, list): + return model_class._new_from_openapi_data(*model_data, **kw_args) + if isinstance(model_data, dict): + kw_args.update(model_data) + return model_class._new_from_openapi_data(**kw_args) + elif isinstance(model_data, PRIMITIVE_TYPES): + return model_class._new_from_openapi_data(model_data, **kw_args) + + +def deserialize_file(response_data, configuration, content_disposition=None): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + Args: + param response_data (str): the file data to write + configuration (Configuration): the instance to use to convert files + + Keyword Args: + content_disposition (str): the value of the Content-Disposition + header + + Returns: + (file_type): the deserialized file which is open + The user is responsible for closing and reading the file + """ + fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition, + flags=re.I) + if filename is not None: + filename = filename.group(1) + else: + filename = "default_" + str(uuid.uuid4()) + + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + if isinstance(response_data, str): + # change str to bytes so we can write it + response_data = response_data.encode('utf-8') + f.write(response_data) + + f = open(path, "rb") + return f + + +def attempt_convert_item(input_value, valid_classes, path_to_item, + configuration, spec_property_naming, key_type=False, + must_convert=False, check_type=True): + """ + Args: + input_value (any): the data to convert + valid_classes (any): the classes that are valid + path_to_item (list): the path to the item to convert + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + key_type (bool): if True we need to convert a key type (not supported) + must_convert (bool): if True we must convert + check_type (bool): if True we check the type or the returned data in + ModelComposed/ModelNormal/ModelSimple instances + + Returns: + instance (any) the fixed item + + Raises: + ApiTypeError + ApiValueError + ApiKeyError + """ + valid_classes_ordered = order_response_types(valid_classes) + valid_classes_coercible = remove_uncoercible( + valid_classes_ordered, input_value, spec_property_naming) + if not valid_classes_coercible or key_type: + # we do not handle keytype errors, json will take care + # of this for us + if configuration is None or not configuration.discard_unknown_keys: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=key_type) + for valid_class in valid_classes_coercible: + try: + if issubclass(valid_class, OpenApiModel): + return deserialize_model(input_value, valid_class, + path_to_item, check_type, + configuration, spec_property_naming) + elif valid_class == file_type: + return deserialize_file(input_value, configuration) + return deserialize_primitive(input_value, valid_class, + path_to_item) + except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: + if must_convert: + raise conversion_exc + # if we have conversion errors when must_convert == False + # we ignore the exception and move on to the next class + continue + # we were unable to convert, must_convert == False + return input_value + + +def is_type_nullable(input_type): + """ + Returns true if None is an allowed value for the specified input_type. + + A type is nullable if at least one of the following conditions is true: + 1. The OAS 'nullable' attribute has been specified, + 1. The type is the 'null' type, + 1. The type is a anyOf/oneOf composed schema, and a child schema is + the 'null' type. + Args: + input_type (type): the class of the input_value that we are + checking + Returns: + bool + """ + if input_type is none_type: + return True + if issubclass(input_type, OpenApiModel) and input_type._nullable: + return True + if issubclass(input_type, ModelComposed): + # If oneOf/anyOf, check if the 'null' type is one of the allowed types. + for t in input_type._composed_schemas.get('oneOf', ()): + if is_type_nullable(t): + return True + for t in input_type._composed_schemas.get('anyOf', ()): + if is_type_nullable(t): + return True + return False + + +def is_valid_type(input_class_simple, valid_classes): + """ + Args: + input_class_simple (class): the class of the input_value that we are + checking + valid_classes (tuple): the valid classes that the current item + should be + Returns: + bool + """ + if issubclass(input_class_simple, OpenApiModel) and \ + valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,): + return True + valid_type = input_class_simple in valid_classes + if not valid_type and ( + issubclass(input_class_simple, OpenApiModel) or + input_class_simple is none_type): + for valid_class in valid_classes: + if input_class_simple is none_type and is_type_nullable(valid_class): + # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. + return True + if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): + continue + discr_propertyname_py = list(valid_class.discriminator.keys())[0] + discriminator_classes = ( + valid_class.discriminator[discr_propertyname_py].values() + ) + valid_type = is_valid_type(input_class_simple, discriminator_classes) + if valid_type: + return True + return valid_type + + +def validate_and_convert_types(input_value, required_types_mixed, path_to_item, + spec_property_naming, _check_type, configuration=None): + """Raises a TypeError is there is a problem, otherwise returns value + + Args: + input_value (any): the data to validate/convert + required_types_mixed (list/dict/tuple): A list of + valid classes, or a list tuples of valid classes, or a dict where + the value is a tuple of value classes + path_to_item: (list) the path to the data being validated + this stores a list of keys or indices to get to the data being + validated + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + _check_type: (boolean) if true, type will be checked and conversion + will be attempted. + configuration: (Configuration): the configuration class to use + when converting file_type items. + If passed, conversion will be attempted when possible + If not passed, no conversions will be attempted and + exceptions will be raised + + Returns: + the correctly typed value + + Raises: + ApiTypeError + """ + results = get_required_type_classes(required_types_mixed, spec_property_naming) + valid_classes, child_req_types_by_current_type = results + + input_class_simple = get_simple_class(input_value) + valid_type = is_valid_type(input_class_simple, valid_classes) + if not valid_type: + if (configuration + or (input_class_simple == dict + and dict not in valid_classes)): + # if input_value is not valid_type try to convert it + converted_instance = attempt_convert_item( + input_value, + valid_classes, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=True, + check_type=_check_type + ) + return converted_instance + else: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=False) + + # input_value's type is in valid_classes + if len(valid_classes) > 1 and configuration: + # there are valid classes which are not the current class + valid_classes_coercible = remove_uncoercible( + valid_classes, input_value, spec_property_naming, must_convert=False) + if valid_classes_coercible: + converted_instance = attempt_convert_item( + input_value, + valid_classes_coercible, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=False, + check_type=_check_type + ) + return converted_instance + + if child_req_types_by_current_type == {}: + # all types are of the required types and there are no more inner + # variables left to look at + return input_value + inner_required_types = child_req_types_by_current_type.get( + type(input_value) + ) + if inner_required_types is None: + # for this type, there are not more inner variables left to look at + return input_value + if isinstance(input_value, list): + if input_value == []: + # allow an empty list + return input_value + for index, inner_value in enumerate(input_value): + inner_path = list(path_to_item) + inner_path.append(index) + input_value[index] = validate_and_convert_types( + inner_value, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + elif isinstance(input_value, dict): + if input_value == {}: + # allow an empty dict + return input_value + for inner_key, inner_val in input_value.items(): + inner_path = list(path_to_item) + inner_path.append(inner_key) + if get_simple_class(inner_key) != str: + raise get_type_error(inner_key, inner_path, valid_classes, + key_type=True) + input_value[inner_key] = validate_and_convert_types( + inner_val, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + return input_value + + +def model_to_dict(model_instance, serialize=True): + """Returns the model properties as a dict + + Args: + model_instance (one of your model instances): the model instance that + will be converted to a dict. + + Keyword Args: + serialize (bool): if True, the keys in the dict will be values from + attribute_map + """ + result = {} + + def extract_item(item): return ( + item[0], model_to_dict( + item[1], serialize=serialize)) if hasattr( + item[1], '_data_store') else item + + model_instances = [model_instance] + if model_instance._composed_schemas: + model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} + for model_instance in model_instances: + for attr, value in model_instance._data_store.items(): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) + if isinstance(value, list): + if not value: + # empty list or None + result[attr] = value + else: + res = [] + for v in value: + if isinstance(v, PRIMITIVE_TYPES) or v is None: + res.append(v) + elif isinstance(v, ModelSimple): + res.append(v.value) + elif isinstance(v, dict): + res.append(dict(map( + extract_item, + v.items() + ))) + else: + res.append(model_to_dict(v, serialize=serialize)) + result[attr] = res + elif isinstance(value, dict): + result[attr] = dict(map( + extract_item, + value.items() + )) + elif isinstance(value, ModelSimple): + result[attr] = value.value + elif hasattr(value, '_data_store'): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] + + return result + + +def type_error_message(var_value=None, var_name=None, valid_classes=None, + key_type=None): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + """ + key_or_value = 'value' + if key_type: + key_or_value = 'key' + valid_classes_phrase = get_valid_classes_phrase(valid_classes) + msg = ( + "Invalid type for variable '{0}'. Required {1} type {2} and " + "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + ) + return msg + + +def get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed + """ + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return 'is {0}'.format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas['allOf']: + + try: + if constant_args.get('_spec_property_naming'): + allof_instance = allof_class._from_openapi_data(**model_args, **constant_args) + else: + allof_instance = allof_class(**model_args, **constant_args) + composed_instances.append(allof_instance) + except Exception as ex: + raise ApiValueError( + "Invalid inputs given to generate an instance of '%s'. The " + "input data was invalid for the allOf schema '%s' in the composed " + "schema '%s'. Error=%s" % ( + allof_class.__name__, + allof_class.__name__, + self.__class__.__name__, + str(ex) + ) + ) from ex + return composed_instances + + +def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): + """ + Find the oneOf schema that matches the input data (e.g. payload). + If exactly one schema matches the input data, an instance of that schema + is returned. + If zero or more than one schema match the input data, an exception is raised. + In OAS 3.x, the payload MUST, by validation, match exactly one of the + schemas described by oneOf. + + Args: + cls: the class we are handling + model_kwargs (dict): var_name to var_value + The input data, e.g. the payload that must match a oneOf schema + in the OpenAPI document. + constant_kwargs (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Kwargs: + model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): + the value to assign to a primitive class or ModelSimple class + Notes: + - this is only passed in when oneOf includes types which are not object + - None is used to suppress handling of model_arg, nullable models are handled in __new__ + + Returns + oneof_instance (instance) + """ + if len(cls._composed_schemas['oneOf']) == 0: + return None + + oneof_instances = [] + # Iterate over each oneOf schema and determine if the input data + # matches the oneOf schemas. + for oneof_class in cls._composed_schemas['oneOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if oneof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + single_value_input = allows_single_value_input(oneof_class) + + try: + if not single_value_input: + if constant_kwargs.get('_spec_property_naming'): + oneof_instance = oneof_class._from_openapi_data( + **model_kwargs, **constant_kwargs) + else: + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) + else: + if issubclass(oneof_class, ModelSimple): + if constant_kwargs.get('_spec_property_naming'): + oneof_instance = oneof_class._from_openapi_data( + model_arg, **constant_kwargs) + else: + oneof_instance = oneof_class(model_arg, **constant_kwargs) + elif oneof_class in PRIMITIVE_TYPES: + oneof_instance = validate_and_convert_types( + model_arg, + (oneof_class,), + constant_kwargs['_path_to_item'], + constant_kwargs['_spec_property_naming'], + constant_kwargs['_check_type'], + configuration=constant_kwargs['_configuration'] + ) + oneof_instances.append(oneof_instance) + except Exception: + pass + if len(oneof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None " + "of the oneOf schemas matched the input data." % + cls.__name__ + ) + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf schemas matched the inputs, but a max of one is allowed." % + cls.__name__ + ) + return oneof_instances[0] + + +def get_anyof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + The input data, e.g. the payload that must match at least one + anyOf child schema in the OpenAPI document. + constant_args (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Returns + anyof_instances (list) + """ + anyof_instances = [] + if len(self._composed_schemas['anyOf']) == 0: + return anyof_instances + + for anyof_class in self._composed_schemas['anyOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if anyof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + try: + if constant_args.get('_spec_property_naming'): + anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args) + else: + anyof_instance = anyof_class(**model_args, **constant_args) + anyof_instances.append(anyof_instance) + except Exception: + pass + if len(anyof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None of the " + "anyOf schemas matched the inputs." % + self.__class__.__name__ + ) + return anyof_instances + + +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names + # before __init__ was called + for instance in composed_instances: + if instance.__class__ in self._composed_schemas['allOf']: + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + else: + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args + + +def validate_get_composed_info(constant_args, model_args, self): + """ + For composed schemas, generate schema instances for + all schemas in the oneOf/anyOf/allOf definition. If additional + properties are allowed, also assign those properties on + all matched schemas that contain additionalProperties. + Openapi schemas are python classes. + + Exceptions are raised if: + - 0 or > 1 oneOf schema matches the model_args input data + - no anyOf schema matches the model_args input data + - any of the allOf schemas do not match the model_args input data + + Args: + constant_args (dict): these are the args that every model requires + model_args (dict): these are the required and optional spec args that + were passed in to make this model + self (class): the class that we are instantiating + This class contains self._composed_schemas + + Returns: + composed_info (list): length three + composed_instances (list): the composed instances which are not + self + var_name_to_model_instances (dict): a dict going from var_name + to the model_instance which holds that var_name + the model_instance may be self or an instance of one of the + classes in self.composed_instances() + additional_properties_model_instances (list): a list of the + model instances which have the property + additional_properties_type. This list can include self + """ + # create composed_instances + composed_instances = [] + allof_instances = get_allof_instances(self, model_args, constant_args) + composed_instances.extend(allof_instances) + oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) + if oneof_instance is not None: + composed_instances.append(oneof_instance) + anyof_instances = get_anyof_instances(self, model_args, constant_args) + composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] + + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) + + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + list( + filter( + lambda x: prop_name in x.openapi_types, composed_instances)) + + return [ + composed_instances, + var_name_to_model_instances, + additional_properties_model_instances, + discarded_args + ] diff --git a/samples/client/petstore/python/petstore_api/models/__init__.py b/samples/client/petstore/python-prior/petstore_api/models/__init__.py similarity index 100% rename from samples/client/petstore/python/petstore_api/models/__init__.py rename to samples/client/petstore/python-prior/petstore_api/models/__init__.py diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python-prior/petstore_api/rest.py similarity index 100% rename from samples/client/petstore/python/petstore_api/rest.py rename to samples/client/petstore/python-prior/petstore_api/rest.py diff --git a/samples/client/petstore/python/pom.xml b/samples/client/petstore/python-prior/pom.xml similarity index 100% rename from samples/client/petstore/python/pom.xml rename to samples/client/petstore/python-prior/pom.xml diff --git a/samples/client/petstore/python/requirements.txt b/samples/client/petstore/python-prior/requirements.txt similarity index 100% rename from samples/client/petstore/python/requirements.txt rename to samples/client/petstore/python-prior/requirements.txt diff --git a/samples/client/petstore/python/setup.cfg b/samples/client/petstore/python-prior/setup.cfg similarity index 100% rename from samples/client/petstore/python/setup.cfg rename to samples/client/petstore/python-prior/setup.cfg diff --git a/samples/client/petstore/python/setup.py b/samples/client/petstore/python-prior/setup.py similarity index 100% rename from samples/client/petstore/python/setup.py rename to samples/client/petstore/python-prior/setup.py diff --git a/samples/client/petstore/python/test-requirements.txt b/samples/client/petstore/python-prior/test-requirements.txt similarity index 100% rename from samples/client/petstore/python/test-requirements.txt rename to samples/client/petstore/python-prior/test-requirements.txt diff --git a/samples/client/petstore/python/test/__init__.py b/samples/client/petstore/python-prior/test/__init__.py similarity index 100% rename from samples/client/petstore/python/test/__init__.py rename to samples/client/petstore/python-prior/test/__init__.py diff --git a/samples/client/petstore/python/test/test_additional_properties_any_type.py b/samples/client/petstore/python-prior/test/test_additional_properties_any_type.py similarity index 100% rename from samples/client/petstore/python/test/test_additional_properties_any_type.py rename to samples/client/petstore/python-prior/test/test_additional_properties_any_type.py diff --git a/samples/client/petstore/python/test/test_additional_properties_array.py b/samples/client/petstore/python-prior/test/test_additional_properties_array.py similarity index 100% rename from samples/client/petstore/python/test/test_additional_properties_array.py rename to samples/client/petstore/python-prior/test/test_additional_properties_array.py diff --git a/samples/client/petstore/python/test/test_additional_properties_boolean.py b/samples/client/petstore/python-prior/test/test_additional_properties_boolean.py similarity index 100% rename from samples/client/petstore/python/test/test_additional_properties_boolean.py rename to samples/client/petstore/python-prior/test/test_additional_properties_boolean.py diff --git a/samples/client/petstore/python/test/test_additional_properties_class.py b/samples/client/petstore/python-prior/test/test_additional_properties_class.py similarity index 100% rename from samples/client/petstore/python/test/test_additional_properties_class.py rename to samples/client/petstore/python-prior/test/test_additional_properties_class.py diff --git a/samples/client/petstore/python/test/test_additional_properties_integer.py b/samples/client/petstore/python-prior/test/test_additional_properties_integer.py similarity index 100% rename from samples/client/petstore/python/test/test_additional_properties_integer.py rename to samples/client/petstore/python-prior/test/test_additional_properties_integer.py diff --git a/samples/client/petstore/python/test/test_additional_properties_number.py b/samples/client/petstore/python-prior/test/test_additional_properties_number.py similarity index 100% rename from samples/client/petstore/python/test/test_additional_properties_number.py rename to samples/client/petstore/python-prior/test/test_additional_properties_number.py diff --git a/samples/client/petstore/python/test/test_additional_properties_object.py b/samples/client/petstore/python-prior/test/test_additional_properties_object.py similarity index 100% rename from samples/client/petstore/python/test/test_additional_properties_object.py rename to samples/client/petstore/python-prior/test/test_additional_properties_object.py diff --git a/samples/client/petstore/python/test/test_additional_properties_string.py b/samples/client/petstore/python-prior/test/test_additional_properties_string.py similarity index 100% rename from samples/client/petstore/python/test/test_additional_properties_string.py rename to samples/client/petstore/python-prior/test/test_additional_properties_string.py diff --git a/samples/client/petstore/python/test/test_animal.py b/samples/client/petstore/python-prior/test/test_animal.py similarity index 100% rename from samples/client/petstore/python/test/test_animal.py rename to samples/client/petstore/python-prior/test/test_animal.py diff --git a/samples/client/petstore/python/test/test_animal_farm.py b/samples/client/petstore/python-prior/test/test_animal_farm.py similarity index 100% rename from samples/client/petstore/python/test/test_animal_farm.py rename to samples/client/petstore/python-prior/test/test_animal_farm.py diff --git a/samples/client/petstore/python/test/test_another_fake_api.py b/samples/client/petstore/python-prior/test/test_another_fake_api.py similarity index 100% rename from samples/client/petstore/python/test/test_another_fake_api.py rename to samples/client/petstore/python-prior/test/test_another_fake_api.py diff --git a/samples/client/petstore/python/test/test_api_response.py b/samples/client/petstore/python-prior/test/test_api_response.py similarity index 100% rename from samples/client/petstore/python/test/test_api_response.py rename to samples/client/petstore/python-prior/test/test_api_response.py diff --git a/samples/client/petstore/python/test/test_array_of_array_of_number_only.py b/samples/client/petstore/python-prior/test/test_array_of_array_of_number_only.py similarity index 100% rename from samples/client/petstore/python/test/test_array_of_array_of_number_only.py rename to samples/client/petstore/python-prior/test/test_array_of_array_of_number_only.py diff --git a/samples/client/petstore/python/test/test_array_of_number_only.py b/samples/client/petstore/python-prior/test/test_array_of_number_only.py similarity index 100% rename from samples/client/petstore/python/test/test_array_of_number_only.py rename to samples/client/petstore/python-prior/test/test_array_of_number_only.py diff --git a/samples/client/petstore/python/test/test_array_test.py b/samples/client/petstore/python-prior/test/test_array_test.py similarity index 100% rename from samples/client/petstore/python/test/test_array_test.py rename to samples/client/petstore/python-prior/test/test_array_test.py diff --git a/samples/client/petstore/python/test/test_capitalization.py b/samples/client/petstore/python-prior/test/test_capitalization.py similarity index 100% rename from samples/client/petstore/python/test/test_capitalization.py rename to samples/client/petstore/python-prior/test/test_capitalization.py diff --git a/samples/client/petstore/python/test/test_cat.py b/samples/client/petstore/python-prior/test/test_cat.py similarity index 100% rename from samples/client/petstore/python/test/test_cat.py rename to samples/client/petstore/python-prior/test/test_cat.py diff --git a/samples/client/petstore/python/test/test_cat_all_of.py b/samples/client/petstore/python-prior/test/test_cat_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_cat_all_of.py rename to samples/client/petstore/python-prior/test/test_cat_all_of.py diff --git a/samples/client/petstore/python/test/test_category.py b/samples/client/petstore/python-prior/test/test_category.py similarity index 100% rename from samples/client/petstore/python/test/test_category.py rename to samples/client/petstore/python-prior/test/test_category.py diff --git a/samples/client/petstore/python/test/test_child.py b/samples/client/petstore/python-prior/test/test_child.py similarity index 100% rename from samples/client/petstore/python/test/test_child.py rename to samples/client/petstore/python-prior/test/test_child.py diff --git a/samples/client/petstore/python/test/test_child_all_of.py b/samples/client/petstore/python-prior/test/test_child_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_child_all_of.py rename to samples/client/petstore/python-prior/test/test_child_all_of.py diff --git a/samples/client/petstore/python/test/test_child_cat.py b/samples/client/petstore/python-prior/test/test_child_cat.py similarity index 100% rename from samples/client/petstore/python/test/test_child_cat.py rename to samples/client/petstore/python-prior/test/test_child_cat.py diff --git a/samples/client/petstore/python/test/test_child_cat_all_of.py b/samples/client/petstore/python-prior/test/test_child_cat_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_child_cat_all_of.py rename to samples/client/petstore/python-prior/test/test_child_cat_all_of.py diff --git a/samples/client/petstore/python/test/test_child_dog.py b/samples/client/petstore/python-prior/test/test_child_dog.py similarity index 100% rename from samples/client/petstore/python/test/test_child_dog.py rename to samples/client/petstore/python-prior/test/test_child_dog.py diff --git a/samples/client/petstore/python/test/test_child_dog_all_of.py b/samples/client/petstore/python-prior/test/test_child_dog_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_child_dog_all_of.py rename to samples/client/petstore/python-prior/test/test_child_dog_all_of.py diff --git a/samples/client/petstore/python/test/test_child_lizard.py b/samples/client/petstore/python-prior/test/test_child_lizard.py similarity index 100% rename from samples/client/petstore/python/test/test_child_lizard.py rename to samples/client/petstore/python-prior/test/test_child_lizard.py diff --git a/samples/client/petstore/python/test/test_child_lizard_all_of.py b/samples/client/petstore/python-prior/test/test_child_lizard_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_child_lizard_all_of.py rename to samples/client/petstore/python-prior/test/test_child_lizard_all_of.py diff --git a/samples/client/petstore/python/test/test_class_model.py b/samples/client/petstore/python-prior/test/test_class_model.py similarity index 100% rename from samples/client/petstore/python/test/test_class_model.py rename to samples/client/petstore/python-prior/test/test_class_model.py diff --git a/samples/client/petstore/python/test/test_client.py b/samples/client/petstore/python-prior/test/test_client.py similarity index 100% rename from samples/client/petstore/python/test/test_client.py rename to samples/client/petstore/python-prior/test/test_client.py diff --git a/samples/client/petstore/python/test/test_dog.py b/samples/client/petstore/python-prior/test/test_dog.py similarity index 100% rename from samples/client/petstore/python/test/test_dog.py rename to samples/client/petstore/python-prior/test/test_dog.py diff --git a/samples/client/petstore/python/test/test_dog_all_of.py b/samples/client/petstore/python-prior/test/test_dog_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_dog_all_of.py rename to samples/client/petstore/python-prior/test/test_dog_all_of.py diff --git a/samples/client/petstore/python/test/test_enum_arrays.py b/samples/client/petstore/python-prior/test/test_enum_arrays.py similarity index 100% rename from samples/client/petstore/python/test/test_enum_arrays.py rename to samples/client/petstore/python-prior/test/test_enum_arrays.py diff --git a/samples/client/petstore/python/test/test_enum_class.py b/samples/client/petstore/python-prior/test/test_enum_class.py similarity index 100% rename from samples/client/petstore/python/test/test_enum_class.py rename to samples/client/petstore/python-prior/test/test_enum_class.py diff --git a/samples/client/petstore/python/test/test_enum_test.py b/samples/client/petstore/python-prior/test/test_enum_test.py similarity index 100% rename from samples/client/petstore/python/test/test_enum_test.py rename to samples/client/petstore/python-prior/test/test_enum_test.py diff --git a/samples/client/petstore/python/test/test_fake_api.py b/samples/client/petstore/python-prior/test/test_fake_api.py similarity index 100% rename from samples/client/petstore/python/test/test_fake_api.py rename to samples/client/petstore/python-prior/test/test_fake_api.py diff --git a/samples/client/petstore/python/test/test_fake_classname_tags123_api.py b/samples/client/petstore/python-prior/test/test_fake_classname_tags123_api.py similarity index 100% rename from samples/client/petstore/python/test/test_fake_classname_tags123_api.py rename to samples/client/petstore/python-prior/test/test_fake_classname_tags123_api.py diff --git a/samples/client/petstore/python/test/test_fake_classname_tags_123_api.py b/samples/client/petstore/python-prior/test/test_fake_classname_tags_123_api.py similarity index 100% rename from samples/client/petstore/python/test/test_fake_classname_tags_123_api.py rename to samples/client/petstore/python-prior/test/test_fake_classname_tags_123_api.py diff --git a/samples/client/petstore/python/test/test_file.py b/samples/client/petstore/python-prior/test/test_file.py similarity index 100% rename from samples/client/petstore/python/test/test_file.py rename to samples/client/petstore/python-prior/test/test_file.py diff --git a/samples/client/petstore/python/test/test_file_schema_test_class.py b/samples/client/petstore/python-prior/test/test_file_schema_test_class.py similarity index 100% rename from samples/client/petstore/python/test/test_file_schema_test_class.py rename to samples/client/petstore/python-prior/test/test_file_schema_test_class.py diff --git a/samples/client/petstore/python/test/test_format_test.py b/samples/client/petstore/python-prior/test/test_format_test.py similarity index 100% rename from samples/client/petstore/python/test/test_format_test.py rename to samples/client/petstore/python-prior/test/test_format_test.py diff --git a/samples/client/petstore/python/test/test_grandparent.py b/samples/client/petstore/python-prior/test/test_grandparent.py similarity index 100% rename from samples/client/petstore/python/test/test_grandparent.py rename to samples/client/petstore/python-prior/test/test_grandparent.py diff --git a/samples/client/petstore/python/test/test_grandparent_animal.py b/samples/client/petstore/python-prior/test/test_grandparent_animal.py similarity index 100% rename from samples/client/petstore/python/test/test_grandparent_animal.py rename to samples/client/petstore/python-prior/test/test_grandparent_animal.py diff --git a/samples/client/petstore/python/test/test_has_only_read_only.py b/samples/client/petstore/python-prior/test/test_has_only_read_only.py similarity index 100% rename from samples/client/petstore/python/test/test_has_only_read_only.py rename to samples/client/petstore/python-prior/test/test_has_only_read_only.py diff --git a/samples/client/petstore/python/test/test_list.py b/samples/client/petstore/python-prior/test/test_list.py similarity index 100% rename from samples/client/petstore/python/test/test_list.py rename to samples/client/petstore/python-prior/test/test_list.py diff --git a/samples/client/petstore/python/test/test_map_test.py b/samples/client/petstore/python-prior/test/test_map_test.py similarity index 100% rename from samples/client/petstore/python/test/test_map_test.py rename to samples/client/petstore/python-prior/test/test_map_test.py diff --git a/samples/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-prior/test/test_mixed_properties_and_additional_properties_class.py similarity index 100% rename from samples/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py rename to samples/client/petstore/python-prior/test/test_mixed_properties_and_additional_properties_class.py diff --git a/samples/client/petstore/python/test/test_model200_response.py b/samples/client/petstore/python-prior/test/test_model200_response.py similarity index 100% rename from samples/client/petstore/python/test/test_model200_response.py rename to samples/client/petstore/python-prior/test/test_model200_response.py diff --git a/samples/client/petstore/python/test/test_model_200_response.py b/samples/client/petstore/python-prior/test/test_model_200_response.py similarity index 100% rename from samples/client/petstore/python/test/test_model_200_response.py rename to samples/client/petstore/python-prior/test/test_model_200_response.py diff --git a/samples/client/petstore/python/test/test_model_return.py b/samples/client/petstore/python-prior/test/test_model_return.py similarity index 100% rename from samples/client/petstore/python/test/test_model_return.py rename to samples/client/petstore/python-prior/test/test_model_return.py diff --git a/samples/client/petstore/python/test/test_name.py b/samples/client/petstore/python-prior/test/test_name.py similarity index 100% rename from samples/client/petstore/python/test/test_name.py rename to samples/client/petstore/python-prior/test/test_name.py diff --git a/samples/client/petstore/python/test/test_number_only.py b/samples/client/petstore/python-prior/test/test_number_only.py similarity index 100% rename from samples/client/petstore/python/test/test_number_only.py rename to samples/client/petstore/python-prior/test/test_number_only.py diff --git a/samples/client/petstore/python/test/test_number_with_validations.py b/samples/client/petstore/python-prior/test/test_number_with_validations.py similarity index 100% rename from samples/client/petstore/python/test/test_number_with_validations.py rename to samples/client/petstore/python-prior/test/test_number_with_validations.py diff --git a/samples/client/petstore/python/test/test_object_model_with_ref_props.py b/samples/client/petstore/python-prior/test/test_object_model_with_ref_props.py similarity index 100% rename from samples/client/petstore/python/test/test_object_model_with_ref_props.py rename to samples/client/petstore/python-prior/test/test_object_model_with_ref_props.py diff --git a/samples/client/petstore/python/test/test_order.py b/samples/client/petstore/python-prior/test/test_order.py similarity index 100% rename from samples/client/petstore/python/test/test_order.py rename to samples/client/petstore/python-prior/test/test_order.py diff --git a/samples/client/petstore/python/test/test_parent.py b/samples/client/petstore/python-prior/test/test_parent.py similarity index 100% rename from samples/client/petstore/python/test/test_parent.py rename to samples/client/petstore/python-prior/test/test_parent.py diff --git a/samples/client/petstore/python/test/test_parent_all_of.py b/samples/client/petstore/python-prior/test/test_parent_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_parent_all_of.py rename to samples/client/petstore/python-prior/test/test_parent_all_of.py diff --git a/samples/client/petstore/python/test/test_parent_pet.py b/samples/client/petstore/python-prior/test/test_parent_pet.py similarity index 100% rename from samples/client/petstore/python/test/test_parent_pet.py rename to samples/client/petstore/python-prior/test/test_parent_pet.py diff --git a/samples/client/petstore/python/test/test_pet.py b/samples/client/petstore/python-prior/test/test_pet.py similarity index 100% rename from samples/client/petstore/python/test/test_pet.py rename to samples/client/petstore/python-prior/test/test_pet.py diff --git a/samples/client/petstore/python/test/test_pet_api.py b/samples/client/petstore/python-prior/test/test_pet_api.py similarity index 100% rename from samples/client/petstore/python/test/test_pet_api.py rename to samples/client/petstore/python-prior/test/test_pet_api.py diff --git a/samples/client/petstore/python/test/test_player.py b/samples/client/petstore/python-prior/test/test_player.py similarity index 100% rename from samples/client/petstore/python/test/test_player.py rename to samples/client/petstore/python-prior/test/test_player.py diff --git a/samples/client/petstore/python/test/test_polygon.py b/samples/client/petstore/python-prior/test/test_polygon.py similarity index 100% rename from samples/client/petstore/python/test/test_polygon.py rename to samples/client/petstore/python-prior/test/test_polygon.py diff --git a/samples/client/petstore/python/test/test_polygon_all_of.py b/samples/client/petstore/python-prior/test/test_polygon_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_polygon_all_of.py rename to samples/client/petstore/python-prior/test/test_polygon_all_of.py diff --git a/samples/client/petstore/python/test/test_read_only_first.py b/samples/client/petstore/python-prior/test/test_read_only_first.py similarity index 100% rename from samples/client/petstore/python/test/test_read_only_first.py rename to samples/client/petstore/python-prior/test/test_read_only_first.py diff --git a/samples/client/petstore/python/test/test_shape.py b/samples/client/petstore/python-prior/test/test_shape.py similarity index 100% rename from samples/client/petstore/python/test/test_shape.py rename to samples/client/petstore/python-prior/test/test_shape.py diff --git a/samples/client/petstore/python/test/test_special_model_name.py b/samples/client/petstore/python-prior/test/test_special_model_name.py similarity index 100% rename from samples/client/petstore/python/test/test_special_model_name.py rename to samples/client/petstore/python-prior/test/test_special_model_name.py diff --git a/samples/client/petstore/python/test/test_square.py b/samples/client/petstore/python-prior/test/test_square.py similarity index 100% rename from samples/client/petstore/python/test/test_square.py rename to samples/client/petstore/python-prior/test/test_square.py diff --git a/samples/client/petstore/python/test/test_square_all_of.py b/samples/client/petstore/python-prior/test/test_square_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_square_all_of.py rename to samples/client/petstore/python-prior/test/test_square_all_of.py diff --git a/samples/client/petstore/python/test/test_store_api.py b/samples/client/petstore/python-prior/test/test_store_api.py similarity index 100% rename from samples/client/petstore/python/test/test_store_api.py rename to samples/client/petstore/python-prior/test/test_store_api.py diff --git a/samples/client/petstore/python/test/test_string_boolean_map.py b/samples/client/petstore/python-prior/test/test_string_boolean_map.py similarity index 100% rename from samples/client/petstore/python/test/test_string_boolean_map.py rename to samples/client/petstore/python-prior/test/test_string_boolean_map.py diff --git a/samples/client/petstore/python/test/test_string_enum.py b/samples/client/petstore/python-prior/test/test_string_enum.py similarity index 100% rename from samples/client/petstore/python/test/test_string_enum.py rename to samples/client/petstore/python-prior/test/test_string_enum.py diff --git a/samples/client/petstore/python/test/test_tag.py b/samples/client/petstore/python-prior/test/test_tag.py similarity index 100% rename from samples/client/petstore/python/test/test_tag.py rename to samples/client/petstore/python-prior/test/test_tag.py diff --git a/samples/client/petstore/python/test/test_triangle.py b/samples/client/petstore/python-prior/test/test_triangle.py similarity index 100% rename from samples/client/petstore/python/test/test_triangle.py rename to samples/client/petstore/python-prior/test/test_triangle.py diff --git a/samples/client/petstore/python/test/test_triangle_all_of.py b/samples/client/petstore/python-prior/test/test_triangle_all_of.py similarity index 100% rename from samples/client/petstore/python/test/test_triangle_all_of.py rename to samples/client/petstore/python-prior/test/test_triangle_all_of.py diff --git a/samples/client/petstore/python/test/test_type_holder_default.py b/samples/client/petstore/python-prior/test/test_type_holder_default.py similarity index 100% rename from samples/client/petstore/python/test/test_type_holder_default.py rename to samples/client/petstore/python-prior/test/test_type_holder_default.py diff --git a/samples/client/petstore/python/test/test_type_holder_example.py b/samples/client/petstore/python-prior/test/test_type_holder_example.py similarity index 100% rename from samples/client/petstore/python/test/test_type_holder_example.py rename to samples/client/petstore/python-prior/test/test_type_holder_example.py diff --git a/samples/client/petstore/python/test/test_user.py b/samples/client/petstore/python-prior/test/test_user.py similarity index 100% rename from samples/client/petstore/python/test/test_user.py rename to samples/client/petstore/python-prior/test/test_user.py diff --git a/samples/client/petstore/python/test/test_user_api.py b/samples/client/petstore/python-prior/test/test_user_api.py similarity index 100% rename from samples/client/petstore/python/test/test_user_api.py rename to samples/client/petstore/python-prior/test/test_user_api.py diff --git a/samples/client/petstore/python/test/test_xml_item.py b/samples/client/petstore/python-prior/test/test_xml_item.py similarity index 100% rename from samples/client/petstore/python/test/test_xml_item.py rename to samples/client/petstore/python-prior/test/test_xml_item.py diff --git a/samples/client/petstore/python/test_python.sh b/samples/client/petstore/python-prior/test_python.sh similarity index 100% rename from samples/client/petstore/python/test_python.sh rename to samples/client/petstore/python-prior/test_python.sh diff --git a/samples/client/petstore/python/testfiles/1px_pic1.png b/samples/client/petstore/python-prior/testfiles/1px_pic1.png similarity index 100% rename from samples/client/petstore/python/testfiles/1px_pic1.png rename to samples/client/petstore/python-prior/testfiles/1px_pic1.png diff --git a/samples/client/petstore/python/testfiles/1px_pic2.png b/samples/client/petstore/python-prior/testfiles/1px_pic2.png similarity index 100% rename from samples/client/petstore/python/testfiles/1px_pic2.png rename to samples/client/petstore/python-prior/testfiles/1px_pic2.png diff --git a/samples/client/petstore/python/testfiles/foo.png b/samples/client/petstore/python-prior/testfiles/foo.png similarity index 100% rename from samples/client/petstore/python/testfiles/foo.png rename to samples/client/petstore/python-prior/testfiles/foo.png diff --git a/samples/client/petstore/python/tests/__init__.py b/samples/client/petstore/python-prior/tests/__init__.py similarity index 100% rename from samples/client/petstore/python/tests/__init__.py rename to samples/client/petstore/python-prior/tests/__init__.py diff --git a/samples/client/petstore/python/tests/test_api_client.py b/samples/client/petstore/python-prior/tests/test_api_client.py similarity index 100% rename from samples/client/petstore/python/tests/test_api_client.py rename to samples/client/petstore/python-prior/tests/test_api_client.py diff --git a/samples/client/petstore/python/tests/test_api_exception.py b/samples/client/petstore/python-prior/tests/test_api_exception.py similarity index 100% rename from samples/client/petstore/python/tests/test_api_exception.py rename to samples/client/petstore/python-prior/tests/test_api_exception.py diff --git a/samples/client/petstore/python/tests/test_deserialization.py b/samples/client/petstore/python-prior/tests/test_deserialization.py similarity index 100% rename from samples/client/petstore/python/tests/test_deserialization.py rename to samples/client/petstore/python-prior/tests/test_deserialization.py diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python-prior/tests/test_pet_api.py similarity index 100% rename from samples/client/petstore/python/tests/test_pet_api.py rename to samples/client/petstore/python-prior/tests/test_pet_api.py diff --git a/samples/client/petstore/python/tests/test_serialization.py b/samples/client/petstore/python-prior/tests/test_serialization.py similarity index 100% rename from samples/client/petstore/python/tests/test_serialization.py rename to samples/client/petstore/python-prior/tests/test_serialization.py diff --git a/samples/client/petstore/python/tests/test_store_api.py b/samples/client/petstore/python-prior/tests/test_store_api.py similarity index 100% rename from samples/client/petstore/python/tests/test_store_api.py rename to samples/client/petstore/python-prior/tests/test_store_api.py diff --git a/samples/client/petstore/python/tests/util.py b/samples/client/petstore/python-prior/tests/util.py similarity index 100% rename from samples/client/petstore/python/tests/util.py rename to samples/client/petstore/python-prior/tests/util.py diff --git a/samples/client/petstore/python/tox.ini b/samples/client/petstore/python-prior/tox.ini similarity index 100% rename from samples/client/petstore/python/tox.ini rename to samples/client/petstore/python-prior/tox.ini diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitignore b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.gitignore similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitignore rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.gitignore diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitlab-ci.yml b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.gitlab-ci.yml similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitlab-ci.yml rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.gitlab-ci.yml diff --git a/samples/client/petstore/rust/reqwest/rust-test/.openapi-generator-ignore b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.openapi-generator-ignore similarity index 100% rename from samples/client/petstore/rust/reqwest/rust-test/.openapi-generator-ignore rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.openapi-generator-ignore diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/FILES b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/FILES similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/FILES rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/FILES diff --git a/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.travis.yml b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.travis.yml similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.travis.yml rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/.travis.yml diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/Makefile b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/Makefile similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/Makefile rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/Makefile diff --git a/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/README.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/README.md new file mode 100644 index 0000000000..eb14e3a2d7 --- /dev/null +++ b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/README.md @@ -0,0 +1,254 @@ +# petstore-api +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonPriorClientCodegen + +## Requirements. + +Python >=3.6 + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: +```python +import petstore_api +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import petstore_api +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python + +import time +import petstore_api +from pprint import pprint +from petstore_api.api import another_fake_api +from petstore_api.model.client import Client +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = another_fake_api.AnotherFakeApi(api_client) + body = Client( + client="client_example", + ) # Client | client model + + try: + # To test special tags + api_response = api_instance.call_123_test_special_tags(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +*FakeApi* | [**array_model**](docs/FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | +*FakeApi* | [**boolean**](docs/FakeApi.md#boolean) | **POST** /fake/refs/boolean | +*FakeApi* | [**create_xml_item**](docs/FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem +*FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | +*FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +*FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | +*FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | +*FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | +*FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | +*FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**test_endpoint_enums_length_one**](docs/FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | +*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetApi* | [**upload_file_with_required_file**](docs/PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) + - [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) + - [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) + - [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) + - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) + - [AdditionalPropertiesString](docs/AdditionalPropertiesString.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ApiResponse](docs/ApiResponse.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [Child](docs/Child.md) + - [ChildAllOf](docs/ChildAllOf.md) + - [ChildCat](docs/ChildCat.md) + - [ChildCatAllOf](docs/ChildCatAllOf.md) + - [ChildDog](docs/ChildDog.md) + - [ChildDogAllOf](docs/ChildDogAllOf.md) + - [ChildLizard](docs/ChildLizard.md) + - [ChildLizardAllOf](docs/ChildLizardAllOf.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [File](docs/File.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [FormatTest](docs/FormatTest.md) + - [Grandparent](docs/Grandparent.md) + - [GrandparentAnimal](docs/GrandparentAnimal.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelReturn](docs/ModelReturn.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [NumberWithValidations](docs/NumberWithValidations.md) + - [ObjectModelWithRefProps](docs/ObjectModelWithRefProps.md) + - [Order](docs/Order.md) + - [Parent](docs/Parent.md) + - [ParentAllOf](docs/ParentAllOf.md) + - [ParentPet](docs/ParentPet.md) + - [Pet](docs/Pet.md) + - [Player](docs/Player.md) + - [Polygon](docs/Polygon.md) + - [PolygonAllOf](docs/PolygonAllOf.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Shape](docs/Shape.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Square](docs/Square.md) + - [SquareAllOf](docs/SquareAllOf.md) + - [StringBooleanMap](docs/StringBooleanMap.md) + - [StringEnum](docs/StringEnum.md) + - [Tag](docs/Tag.md) + - [Triangle](docs/Triangle.md) + - [TriangleAllOf](docs/TriangleAllOf.md) + - [TypeHolderDefault](docs/TypeHolderDefault.md) + - [TypeHolderExample](docs/TypeHolderExample.md) + - [User](docs/User.md) + - [XmlItem](docs/XmlItem.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + +## http_basic_test + +- **Type**: HTTP basic authentication + + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + + +## Author + + + + +## Notes for Large OpenAPI documents +If the OpenAPI document is large, imports in petstore_api.apis and petstore_api.models may fail with a +RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: + +Solution 1: +Use specific imports for apis and models like: +- `from petstore_api.api.default_api import DefaultApi` +- `from petstore_api.model.pet import Pet` + +Solution 2: +Before importing the package, adjust the maximum recursion limit as shown below: +``` +import sys +sys.setrecursionlimit(1500) +import petstore_api +from petstore_api.apis import * +from petstore_api.models import * +``` + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/dev-requirements.txt b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/dev-requirements.txt similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/dev-requirements.txt rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/dev-requirements.txt diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesAnyType.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesAnyType.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesAnyType.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesArray.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesArray.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesArray.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesArray.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesBoolean.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesBoolean.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesBoolean.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesClass.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesClass.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesClass.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesInteger.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesInteger.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesInteger.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesNumber.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesNumber.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesNumber.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesObject.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesObject.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesObject.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesObject.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesString.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesString.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesString.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesString.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Animal.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Animal.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Animal.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Animal.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnimalFarm.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AnimalFarm.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnimalFarm.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AnimalFarm.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnotherFakeApi.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AnotherFakeApi.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnotherFakeApi.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/AnotherFakeApi.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ApiResponse.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ApiResponse.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ApiResponse.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ApiResponse.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfArrayOfNumberOnly.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfArrayOfNumberOnly.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfNumberOnly.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfNumberOnly.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfNumberOnly.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayTest.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ArrayTest.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayTest.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ArrayTest.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Capitalization.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Capitalization.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Capitalization.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Capitalization.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Cat.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Cat.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Cat.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Cat.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/CatAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/CatAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/CatAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/CatAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Category.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Category.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Category.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Category.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Child.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Child.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Child.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Child.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCat.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildCat.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCat.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildCat.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCatAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildCatAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCatAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildCatAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDog.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildDog.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDog.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildDog.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDogAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildDogAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDogAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildDogAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizard.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizard.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizard.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizard.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizardAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizardAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizardAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizardAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ClassModel.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ClassModel.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ClassModel.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ClassModel.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Client.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Client.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Client.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Client.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Dog.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Dog.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Dog.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Dog.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/DogAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/DogAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/DogAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/DogAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumArrays.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/EnumArrays.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumArrays.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/EnumArrays.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumClass.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/EnumClass.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumClass.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/EnumClass.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumTest.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/EnumTest.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumTest.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/EnumTest.md diff --git a/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/FakeApi.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/FakeApi.md new file mode 100644 index 0000000000..7c12e3bd18 --- /dev/null +++ b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/FakeApi.md @@ -0,0 +1,1239 @@ +# petstore_api.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**array_model**](FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | +[**boolean**](FakeApi.md#boolean) | **POST** /fake/refs/boolean | +[**create_xml_item**](FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem +[**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | +[**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +[**string**](FakeApi.md#string) | **POST** /fake/refs/string | +[**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | +[**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | +[**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | +[**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model +[**test_endpoint_enums_length_one**](FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | +[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +[**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data + + +# **array_model** +> AnimalFarm array_model() + + + +Test serialization of ArrayModel + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.animal_farm import AnimalFarm +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = AnimalFarm([ + Animal(), + ]) # AnimalFarm | Input model (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.array_model(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->array_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**AnimalFarm**](AnimalFarm.md)| Input model | [optional] + +### Return type + +[**AnimalFarm**](AnimalFarm.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output model | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **boolean** +> bool boolean() + + + +Test serialization of outer boolean types + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = True # bool | Input boolean as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.boolean(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->boolean: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **bool**| Input boolean as post body | [optional] + +### Return type + +**bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output boolean | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_xml_item** +> create_xml_item(xml_item) + +creates an XmlItem + +this route creates an XmlItem + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.xml_item import XmlItem +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + xml_item = XmlItem( + attribute_string="string", + attribute_number=1.234, + attribute_integer=-2, + attribute_boolean=True, + wrapped_array=[ + 1, + ], + name_string="string", + name_number=1.234, + name_integer=-2, + name_boolean=True, + name_array=[ + 1, + ], + name_wrapped_array=[ + 1, + ], + prefix_string="string", + prefix_number=1.234, + prefix_integer=-2, + prefix_boolean=True, + prefix_array=[ + 1, + ], + prefix_wrapped_array=[ + 1, + ], + namespace_string="string", + namespace_number=1.234, + namespace_integer=-2, + namespace_boolean=True, + namespace_array=[ + 1, + ], + namespace_wrapped_array=[ + 1, + ], + prefix_ns_string="string", + prefix_ns_number=1.234, + prefix_ns_integer=-2, + prefix_ns_boolean=True, + prefix_ns_array=[ + 1, + ], + prefix_ns_wrapped_array=[ + 1, + ], + ) # XmlItem | XmlItem Body + + # example passing only required values which don't have defaults set + try: + # creates an XmlItem + api_instance.create_xml_item(xml_item) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->create_xml_item: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **xml_item** | [**XmlItem**](XmlItem.md)| XmlItem Body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml, application/xml; charset=utf-8, application/xml; charset=utf-16, text/xml, text/xml; charset=utf-8, text/xml; charset=utf-16 + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **number_with_validations** +> NumberWithValidations number_with_validations() + + + +Test serialization of outer number types + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.number_with_validations import NumberWithValidations +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = NumberWithValidations(1E+1) # NumberWithValidations | Input number as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.number_with_validations(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->number_with_validations: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**NumberWithValidations**](NumberWithValidations.md)| Input number as post body | [optional] + +### Return type + +[**NumberWithValidations**](NumberWithValidations.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output number | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **object_model_with_ref_props** +> ObjectModelWithRefProps object_model_with_ref_props() + + + +Test serialization of object with $refed properties + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = ObjectModelWithRefProps( + my_number=NumberWithValidations(1E+1), + my_string="my_string_example", + my_boolean=True, + ) # ObjectModelWithRefProps | Input model (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.object_model_with_ref_props(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**ObjectModelWithRefProps**](ObjectModelWithRefProps.md)| Input model | [optional] + +### Return type + +[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output model | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **string** +> str string() + + + +Test serialization of outer string types + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = "body_example" # str | Input string as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.string(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **str**| Input string as post body | [optional] + +### Return type + +**str** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output string | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **string_enum** +> StringEnum string_enum() + + + +Test serialization of outer enum + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.string_enum import StringEnum +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = StringEnum("placed") # StringEnum | Input enum (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.string_enum(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string_enum: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**StringEnum**](StringEnum.md)| Input enum | [optional] + +### Return type + +[**StringEnum**](StringEnum.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output enum | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_with_file_schema** +> test_body_with_file_schema(body) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.file_schema_test_class import FileSchemaTestClass +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = FileSchemaTestClass( + file=File( + source_uri="source_uri_example", + ), + files=[ + File( + source_uri="source_uri_example", + ), + ], + ) # FileSchemaTestClass | + + # example passing only required values which don't have defaults set + try: + api_instance.test_body_with_file_schema(body) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_body_with_file_schema: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_with_query_params** +> test_body_with_query_params(query, body) + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + query = "query_example" # str | + body = User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + ) # User | + + # example passing only required values which don't have defaults set + try: + api_instance.test_body_with_query_params(query, body) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_body_with_query_params: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **str**| | + **body** | [**User**](User.md)| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_client_model** +> Client test_client_model(body) + +To test \"client\" model + +To test \"client\" model + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.client import Client +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = Client( + client="client_example", + ) # Client | client model + + # example passing only required values which don't have defaults set + try: + # To test \"client\" model + api_response = api_instance.test_client_model(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_client_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_endpoint_enums_length_one** +> test_endpoint_enums_length_one() + + + +This route has required values with enums of 1 + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + try: + api_instance.test_endpoint_enums_length_one() + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_enums_length_one: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query_integer** | **int**| | defaults to 3 + **query_string** | **str**| | defaults to "brillig" + **path_string** | **str**| | defaults to "hello" + **path_integer** | **int**| | defaults to 34 + **header_number** | **float**| | defaults to 1.234 + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_endpoint_parameters** +> test_endpoint_parameters(number, double, pattern_without_delimiter, byte) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example + +* Basic Authentication (http_basic_test): + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure HTTP basic authorization: http_basic_test +configuration = petstore_api.Configuration( + username = 'YOUR_USERNAME', + password = 'YOUR_PASSWORD' +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + number = 32.1 # float | None + double = 67.8 # float | None + pattern_without_delimiter = "AUR,rZ#UM/?R,Fp^l6$ARjbhJk C>" # str | None + byte = 'YQ==' # str | None + integer = 10 # int | None (optional) + int32 = 20 # int | None (optional) + int64 = 1 # int | None (optional) + float = 3.14 # float | None (optional) + string = "A" # str | None (optional) + binary = open('/path/to/file', 'rb') # file_type | None (optional) + date = dateutil_parser('1970-01-01').date() # date | None (optional) + date_time = dateutil_parser('1970-01-01T00:00:00.00Z') # datetime | None (optional) + password = "password_example" # str | None (optional) + param_callback = "param_callback_example" # str | None (optional) + + # example passing only required values which don't have defaults set + try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **float**| None | + **double** | **float**| None | + **pattern_without_delimiter** | **str**| None | + **byte** | **str**| None | + **integer** | **int**| None | [optional] + **int32** | **int**| None | [optional] + **int64** | **int**| None | [optional] + **float** | **float**| None | [optional] + **string** | **str**| None | [optional] + **binary** | **file_type**| None | [optional] + **date** | **date**| None | [optional] + **date_time** | **datetime**| None | [optional] + **password** | **str**| None | [optional] + **param_callback** | **str**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid username supplied | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_enum_parameters** +> test_enum_parameters() + +To test enum parameters + +To test enum parameters + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + enum_header_string_array = [ + "$", + ] # [str] | Header parameter enum test (string array) (optional) + enum_header_string = "-efg" # str | Header parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + enum_query_string_array = [ + "$", + ] # [str] | Query parameter enum test (string array) (optional) + enum_query_string = "-efg" # str | Query parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + enum_query_integer = 1 # int | Query parameter enum test (double) (optional) + enum_query_double = 1.1 # float | Query parameter enum test (double) (optional) + enum_form_string_array = [ + "$", + ] # [str] | Form parameter enum test (string array) (optional) if omitted the server will use the default value of "$" + enum_form_string = "-efg" # str | Form parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + + # example passing only required values which don't have defaults set + # and optional values + try: + # To test enum parameters + api_instance.test_enum_parameters(enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double, enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enum_header_string_array** | **[str]**| Header parameter enum test (string array) | [optional] + **enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + **enum_query_string_array** | **[str]**| Query parameter enum test (string array) | [optional] + **enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] + **enum_query_double** | **float**| Query parameter enum test (double) | [optional] + **enum_form_string_array** | **[str]**| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of "$" + **enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid request | - | +**404** | Not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_group_parameters** +> test_group_parameters(required_string_group, required_boolean_group, required_int64_group) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + required_string_group = 1 # int | Required String in group parameters + required_boolean_group = True # bool | Required Boolean in group parameters + required_int64_group = 1 # int | Required Integer in group parameters + string_group = 1 # int | String in group parameters (optional) + boolean_group = True # bool | Boolean in group parameters (optional) + int64_group = 1 # int | Integer in group parameters (optional) + + # example passing only required values which don't have defaults set + try: + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **required_string_group** | **int**| Required String in group parameters | + **required_boolean_group** | **bool**| Required Boolean in group parameters | + **required_int64_group** | **int**| Required Integer in group parameters | + **string_group** | **int**| String in group parameters | [optional] + **boolean_group** | **bool**| Boolean in group parameters | [optional] + **int64_group** | **int**| Integer in group parameters | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Someting wrong | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_inline_additional_properties** +> test_inline_additional_properties(param) + +test inline additionalProperties + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + param = { + "key": "key_example", + } # {str: (str,)} | request body + + # example passing only required values which don't have defaults set + try: + # test inline additionalProperties + api_instance.test_inline_additional_properties(param) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **{str: (str,)}**| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_json_form_data** +> test_json_form_data(param, param2) + +test json serialization of form data + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + param = "param_example" # str | field1 + param2 = "param2_example" # str | field2 + + # example passing only required values which don't have defaults set + try: + # test json serialization of form data + api_instance.test_json_form_data(param, param2) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_json_form_data: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **str**| field1 | + **param2** | **str**| field2 | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeClassnameTags123Api.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/FakeClassnameTags123Api.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeClassnameTags123Api.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/FakeClassnameTags123Api.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/File.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/File.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/File.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/File.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FileSchemaTestClass.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/FileSchemaTestClass.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FileSchemaTestClass.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/FileSchemaTestClass.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FormatTest.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/FormatTest.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FormatTest.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/FormatTest.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Grandparent.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Grandparent.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Grandparent.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Grandparent.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/GrandparentAnimal.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/GrandparentAnimal.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/GrandparentAnimal.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/GrandparentAnimal.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/HasOnlyReadOnly.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/HasOnlyReadOnly.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/HasOnlyReadOnly.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/HasOnlyReadOnly.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/List.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/List.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/List.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/List.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MapTest.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/MapTest.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MapTest.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/MapTest.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/MixedPropertiesAndAdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MixedPropertiesAndAdditionalPropertiesClass.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/MixedPropertiesAndAdditionalPropertiesClass.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Model200Response.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Model200Response.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Model200Response.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Model200Response.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ModelReturn.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ModelReturn.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ModelReturn.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ModelReturn.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Model_200Response.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Model_200Response.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Model_200Response.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Model_200Response.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Model_Return.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Model_Return.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Model_Return.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Model_Return.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Name.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Name.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Name.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Name.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberOnly.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/NumberOnly.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberOnly.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/NumberOnly.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberWithValidations.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/NumberWithValidations.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberWithValidations.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/NumberWithValidations.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ObjectModelWithRefProps.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ObjectModelWithRefProps.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ObjectModelWithRefProps.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ObjectModelWithRefProps.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Order.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Order.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Order.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Order.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Parent.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Parent.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Parent.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Parent.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ParentAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ParentAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentPet.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ParentPet.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentPet.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ParentPet.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Pet.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Pet.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Pet.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Pet.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/PetApi.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/PetApi.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/PetApi.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/PetApi.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Player.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Player.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Player.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Player.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Polygon.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Polygon.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Polygon.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Polygon.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/PolygonAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/PolygonAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/PolygonAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/PolygonAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ReadOnlyFirst.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ReadOnlyFirst.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ReadOnlyFirst.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/ReadOnlyFirst.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Shape.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Shape.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Shape.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Shape.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/SpecialModelName.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/SpecialModelName.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/SpecialModelName.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/SpecialModelName.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Square.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Square.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Square.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Square.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/SquareAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/SquareAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/SquareAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/SquareAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StoreApi.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/StoreApi.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StoreApi.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/StoreApi.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringBooleanMap.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/StringBooleanMap.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringBooleanMap.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/StringBooleanMap.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringEnum.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/StringEnum.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringEnum.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/StringEnum.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Tag.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Tag.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Tag.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Tag.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Triangle.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Triangle.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Triangle.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/Triangle.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TriangleAllOf.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/TriangleAllOf.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TriangleAllOf.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/TriangleAllOf.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderDefault.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderDefault.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderDefault.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderDefault.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderExample.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderExample.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderExample.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderExample.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/User.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/User.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/User.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/User.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/UserApi.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/UserApi.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/UserApi.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/UserApi.md diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/XmlItem.md b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/XmlItem.md similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/XmlItem.md rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/docs/XmlItem.md diff --git a/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/git_push.sh b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/__init__.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/__init__.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/__init__.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/__init__.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/__init__.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/__init__.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/__init__.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/__init__.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags123_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags123_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags123_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags123_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/apis/__init__.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/apis/__init__.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/apis/__init__.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/apis/__init__.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/configuration.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/configuration.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/configuration.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/configuration.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/exceptions.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/exceptions.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/exceptions.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/exceptions.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/__init__.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/__init__.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/__init__.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/__init__.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_200_response.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_200_response.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_200_response.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_200_response.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/polygon.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/polygon.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/polygon.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/polygon.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/polygon_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/polygon_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/polygon_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/polygon_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/shape.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/shape.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/shape.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/shape.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/square.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/square.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/square.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/square.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/square_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/square_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/square_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/square_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/triangle.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/triangle.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/triangle.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/triangle.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/triangle_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/triangle_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/triangle_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/triangle_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py diff --git a/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py new file mode 100644 index 0000000000..ab2d0087df --- /dev/null +++ b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py @@ -0,0 +1,2058 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from datetime import date, datetime # noqa: F401 +from copy import deepcopy +import inspect +import io +import os +import pprint +import re +import tempfile +import uuid + +from dateutil.parser import parse + +from petstore_api.exceptions import ( + ApiKeyError, + ApiAttributeError, + ApiTypeError, + ApiValueError, +) + +none_type = type(None) +file_type = io.IOBase + + +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python( + kwargs, _self if isinstance( + _self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + +class cached_property(object): + # this caches the result of the function call for fn with no inputs + # use this as a decorator on function methods that you want converted + # into cached properties + result_key = '_results' + + def __init__(self, fn): + self._fn = fn + + def __get__(self, instance, cls=None): + if self.result_key in vars(self): + return vars(self)[self.result_key] + else: + result = self._fn() + setattr(self, self.result_key, result) + return result + + +PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) + + +def allows_single_value_input(cls): + """ + This function returns True if the input composed schema model or any + descendant model allows a value only input + This is true for cases where oneOf contains items like: + oneOf: + - float + - NumberWithValidation + - StringEnum + - ArrayModel + - null + TODO: lru_cache this + """ + if ( + issubclass(cls, ModelSimple) or + cls in PRIMITIVE_TYPES + ): + return True + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return False + return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) + return False + + +def composed_model_input_classes(cls): + """ + This function returns a list of the possible models that can be accepted as + inputs. + TODO: lru_cache this + """ + if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: + return [cls] + elif issubclass(cls, ModelNormal): + if cls.discriminator is None: + return [cls] + else: + return get_discriminated_classes(cls) + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return [] + if cls.discriminator is None: + input_classes = [] + for c in cls._composed_schemas['oneOf']: + input_classes.extend(composed_model_input_classes(c)) + return input_classes + else: + return get_discriminated_classes(cls) + return [] + + +class OpenApiModel(object): + """The base class for all OpenAPIModels""" + + def set_attribute(self, name, value): + # this is only used to set properties on self + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + + if name in self.openapi_types: + required_types_mixed = self.openapi_types[name] + elif self.additional_properties_type is None: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + path_to_item + ) + elif self.additional_properties_type is not None: + required_types_mixed = self.additional_properties_type + + if get_simple_class(name) != str: + error_msg = type_error_message( + var_name=name, + var_value=name, + valid_classes=(str,), + key_type=True + ) + raise ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=(str,), + key_type=True + ) + + if self._check_type: + value = validate_and_convert_types( + value, required_types_mixed, path_to_item, self._spec_property_naming, + self._check_type, configuration=self._configuration) + if (name,) in self.allowed_values: + check_allowed_values( + self.allowed_values, + (name,), + value + ) + if (name,) in self.validations: + check_validations( + self.validations, + (name,), + value, + self._configuration + ) + self.__dict__['_data_store'][name] = value + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other + + def __setattr__(self, attr, value): + """set the value of an attribute using dot notation: `instance.attr = val`""" + self[attr] = value + + def __getattr__(self, attr): + """get the value of an attribute using dot notation: `instance.attr`""" + return self.__getitem__(attr) + + def __copy__(self): + cls = self.__class__ + if self.get("_spec_property_naming", False): + return cls._new_from_openapi_data(**self.__dict__) + else: + return cls.__new__(cls, **self.__dict__) + + def __deepcopy__(self, memo): + cls = self.__class__ + + if self.get("_spec_property_naming", False): + new_inst = cls._new_from_openapi_data() + else: + new_inst = cls.__new__(cls, **self.__dict__) + + for k, v in self.__dict__.items(): + setattr(new_inst, k, deepcopy(v, memo)) + return new_inst + + + def __new__(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return super(OpenApiModel, cls).__new__(cls) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return super(OpenApiModel, cls).__new__(cls) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = super(OpenApiModel, cls).__new__(cls) + self_inst.__init__(*args, **kwargs) + + if kwargs.get("_spec_property_naming", False): + # when true, implies new is from deserialization + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + else: + new_inst = new_cls.__new__(new_cls, *args, **kwargs) + new_inst.__init__(*args, **kwargs) + + return new_inst + + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + +class ModelSimple(OpenApiModel): + """the parent class of models whose type != object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_str(self): + """Returns the string representation of the model""" + return str(self.value) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + this_val = self._data_store['value'] + that_val = other._data_store['value'] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + return vals_equal + + +class ModelNormal(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +class ModelComposed(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi and have oneOf/allOf/anyOf + + When one sets a property we use var_name_to_model_instances to store the value in + the correct class instances + run any type checking + validation code. + When one gets a property we use var_name_to_model_instances to get the value + from the correct class instances. + This allows multiple composed schemas to contain the same property with additive + constraints on the value. + + _composed_schemas (dict) stores the anyOf/allOf/oneOf classes + key (str): allOf/oneOf/anyOf + value (list): the classes in the XOf definition. + Note: none_type can be included when the openapi document version >= 3.1.0 + _composed_instances (list): stores a list of instances of the composed schemas + defined in _composed_schemas. When properties are accessed in the self instance, + they are returned from the self._data_store or the data stores in the instances + in self._composed_schemas + _var_name_to_model_instances (dict): maps between a variable name on self and + the composed instances (self included) which contain that data + key (str): property name + value (list): list of class instances, self or instances in _composed_instances + which contain the value that the key is referring to. + """ + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None + + __unset_attribute_value__ = object() + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + # get the attribute from the correct instance + model_instances = self._var_name_to_model_instances.get(name) + values = [] + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + v = model_instance._data_store[name] + if v not in values: + values.append(v) + len_values = len(values) + if len_values == 0: + return default + elif len_values == 1: + return values[0] + elif len_values > 1: + raise ApiValueError( + "Values stored for property {0} in {1} differ when looking " + "at self and self's composed instances. All values must be " + "the same".format(name, type(self).__name__), + [e for e in [self._path_to_item, name] if e] + ) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + value = self.get(name, self.__unset_attribute_value__) + if value is self.__unset_attribute_value__: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + return value + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + + if name in self.required_properties: + return name in self.__dict__ + + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + return True + + return False + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +COERCION_INDEX_BY_TYPE = { + ModelComposed: 0, + ModelNormal: 1, + ModelSimple: 2, + none_type: 3, # The type of 'None'. + list: 4, + dict: 5, + float: 6, + int: 7, + bool: 8, + datetime: 9, + date: 10, + str: 11, + file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. +} + +# these are used to limit what type conversions we try to do +# when we have a valid type already and we want to try converting +# to another type +UPCONVERSION_TYPE_PAIRS = ( + (str, datetime), + (str, date), + # A float may be serialized as an integer, e.g. '3' is a valid serialized float. + (int, float), + (list, ModelComposed), + (dict, ModelComposed), + (str, ModelComposed), + (int, ModelComposed), + (float, ModelComposed), + (list, ModelComposed), + (list, ModelNormal), + (dict, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), +) + +COERCIBLE_TYPE_PAIRS = { + False: ( # client instantiation of a model with client data + # (dict, ModelComposed), + # (list, ModelComposed), + # (dict, ModelNormal), + # (list, ModelNormal), + # (str, ModelSimple), + # (int, ModelSimple), + # (float, ModelSimple), + # (list, ModelSimple), + # (str, int), + # (str, float), + # (str, datetime), + # (str, date), + # (int, str), + # (float, str), + ), + True: ( # server -> client data + (dict, ModelComposed), + (list, ModelComposed), + (dict, ModelNormal), + (list, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), + # (str, int), + # (str, float), + (str, datetime), + (str, date), + # (int, str), + # (float, str), + (str, file_type) + ), +} + + +def get_simple_class(input_value): + """Returns an input_value's simple class that we will use for type checking + Python2: + float and int will return int, where int is the python3 int backport + str and unicode will return str, where str is the python3 str backport + Note: float and int ARE both instances of int backport + Note: str_py2 and unicode_py2 are NOT both instances of str backport + + Args: + input_value (class/class_instance): the item for which we will return + the simple class + """ + if isinstance(input_value, type): + # input_value is a class + return input_value + elif isinstance(input_value, tuple): + return tuple + elif isinstance(input_value, list): + return list + elif isinstance(input_value, dict): + return dict + elif isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, file_type): + return file_type + elif isinstance(input_value, bool): + # this must be higher than the int check because + # isinstance(True, int) == True + return bool + elif isinstance(input_value, int): + return int + elif isinstance(input_value, datetime): + # this must be higher than the date check because + # isinstance(datetime_instance, date) == True + return datetime + elif isinstance(input_value, date): + return date + elif isinstance(input_value, str): + return str + return type(input_value) + + +def check_allowed_values(allowed_values, input_variable_path, input_values): + """Raises an exception if the input_values are not allowed + + Args: + allowed_values (dict): the allowed_values dict + input_variable_path (tuple): the path to the input variable + input_values (list/str/int/float/date/datetime): the values that we + are checking to see if they are in allowed_values + """ + these_allowed_values = list(allowed_values[input_variable_path].values()) + if (isinstance(input_values, list) + and not set(input_values).issubset( + set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values) - set(these_allowed_values))), + raise ApiValueError( + "Invalid values for `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (isinstance(input_values, dict) + and not set( + input_values.keys()).issubset(set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values.keys()) - set(these_allowed_values))) + raise ApiValueError( + "Invalid keys in `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (not isinstance(input_values, (list, dict)) + and input_values not in these_allowed_values): + raise ApiValueError( + "Invalid value for `%s` (%s), must be one of %s" % + ( + input_variable_path[0], + input_values, + these_allowed_values + ) + ) + + +def is_json_validation_enabled(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + +def check_validations( + validations, input_variable_path, input_values, + configuration=None): + """Raises an exception if the input_values are invalid + + Args: + validations (dict): the validation dictionary. + input_variable_path (tuple): the path to the input variable. + input_values (list/str/int/float/date/datetime): the values that we + are checking. + configuration (Configuration): the configuration class. + """ + + if input_values is None: + return + + current_validations = validations[input_variable_path] + if (is_json_validation_enabled('multipleOf', configuration) and + 'multiple_of' in current_validations and + isinstance(input_values, (int, float)) and + not (float(input_values) / current_validations['multiple_of']).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + raise ApiValueError( + "Invalid value for `%s`, value must be a multiple of " + "`%s`" % ( + input_variable_path[0], + current_validations['multiple_of'] + ) + ) + + if (is_json_validation_enabled('maxLength', configuration) and + 'max_length' in current_validations and + len(input_values) > current_validations['max_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['max_length'] + ) + ) + + if (is_json_validation_enabled('minLength', configuration) and + 'min_length' in current_validations and + len(input_values) < current_validations['min_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be greater than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['min_length'] + ) + ) + + if (is_json_validation_enabled('maxItems', configuration) and + 'max_items' in current_validations and + len(input_values) > current_validations['max_items']): + raise ApiValueError( + "Invalid value for `%s`, number of items must be less than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['max_items'] + ) + ) + + if (is_json_validation_enabled('minItems', configuration) and + 'min_items' in current_validations and + len(input_values) < current_validations['min_items']): + raise ValueError( + "Invalid value for `%s`, number of items must be greater than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['min_items'] + ) + ) + + items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', + 'inclusive_minimum') + if (any(item in current_validations for item in items)): + if isinstance(input_values, list): + max_val = max(input_values) + min_val = min(input_values) + elif isinstance(input_values, dict): + max_val = max(input_values.values()) + min_val = min(input_values.values()) + else: + max_val = input_values + min_val = input_values + + if (is_json_validation_enabled('exclusiveMaximum', configuration) and + 'exclusive_maximum' in current_validations and + max_val >= current_validations['exclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than `%s`" % ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('maximum', configuration) and + 'inclusive_maximum' in current_validations and + max_val > current_validations['inclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['inclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('exclusiveMinimum', configuration) and + 'exclusive_minimum' in current_validations and + min_val <= current_validations['exclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than `%s`" % + ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('minimum', configuration) and + 'inclusive_minimum' in current_validations and + min_val < current_validations['inclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than or equal " + "to `%s`" % ( + input_variable_path[0], + current_validations['inclusive_minimum'] + ) + ) + flags = current_validations.get('regex', {}).get('flags', 0) + if (is_json_validation_enabled('pattern', configuration) and + 'regex' in current_validations and + not re.search(current_validations['regex']['pattern'], + input_values, flags=flags)): + err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( + input_variable_path[0], + current_validations['regex']['pattern'] + ) + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + err_msg = r"%s with flags=`%s`" % (err_msg, flags) + raise ApiValueError(err_msg) + + +def order_response_types(required_types): + """Returns the required types sorted in coercion order + + Args: + required_types (list/tuple): collection of classes or instance of + list or dict with class information inside it. + + Returns: + (list): coercion order sorted collection of classes or instance + of list or dict with class information inside it. + """ + + def index_getter(class_or_instance): + if isinstance(class_or_instance, list): + return COERCION_INDEX_BY_TYPE[list] + elif isinstance(class_or_instance, dict): + return COERCION_INDEX_BY_TYPE[dict] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelComposed)): + return COERCION_INDEX_BY_TYPE[ModelComposed] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelNormal)): + return COERCION_INDEX_BY_TYPE[ModelNormal] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelSimple)): + return COERCION_INDEX_BY_TYPE[ModelSimple] + elif class_or_instance in COERCION_INDEX_BY_TYPE: + return COERCION_INDEX_BY_TYPE[class_or_instance] + raise ApiValueError("Unsupported type: %s" % class_or_instance) + + sorted_types = sorted( + required_types, + key=lambda class_or_instance: index_getter(class_or_instance) + ) + return sorted_types + + +def remove_uncoercible(required_types_classes, current_item, spec_property_naming, + must_convert=True): + """Only keeps the type conversions that are possible + + Args: + required_types_classes (tuple): tuple of classes that are required + these should be ordered by COERCION_INDEX_BY_TYPE + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + current_item (any): the current item (input data) to be converted + + Keyword Args: + must_convert (bool): if True the item to convert is of the wrong + type and we want a big list of coercibles + if False, we want a limited list of coercibles + + Returns: + (list): the remaining coercible required types, classes only + """ + current_type_simple = get_simple_class(current_item) + + results_classes = [] + for required_type_class in required_types_classes: + # convert our models to OpenApiModel + required_type_class_simplified = required_type_class + if isinstance(required_type_class_simplified, type): + if issubclass(required_type_class_simplified, ModelComposed): + required_type_class_simplified = ModelComposed + elif issubclass(required_type_class_simplified, ModelNormal): + required_type_class_simplified = ModelNormal + elif issubclass(required_type_class_simplified, ModelSimple): + required_type_class_simplified = ModelSimple + + if required_type_class_simplified == current_type_simple: + # don't consider converting to one's own class + continue + + class_pair = (current_type_simple, required_type_class_simplified) + if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: + results_classes.append(required_type_class) + elif class_pair in UPCONVERSION_TYPE_PAIRS: + results_classes.append(required_type_class) + return results_classes + + +def get_discriminated_classes(cls): + """ + Returns all the classes that a discriminator converts to + TODO: lru_cache this + """ + possible_classes = [] + key = list(cls.discriminator.keys())[0] + if is_type_nullable(cls): + possible_classes.append(cls) + for discr_cls in cls.discriminator[key].values(): + if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: + possible_classes.extend(get_discriminated_classes(discr_cls)) + else: + possible_classes.append(discr_cls) + return possible_classes + + +def get_possible_classes(cls, from_server_context): + # TODO: lru_cache this + possible_classes = [cls] + if from_server_context: + return possible_classes + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + possible_classes = [] + possible_classes.extend(get_discriminated_classes(cls)) + elif issubclass(cls, ModelComposed): + possible_classes.extend(composed_model_input_classes(cls)) + return possible_classes + + +def get_required_type_classes(required_types_mixed, spec_property_naming): + """Converts the tuple required_types into a tuple and a dict described + below + + Args: + required_types_mixed (tuple/list): will contain either classes or + instance of list or dict + spec_property_naming (bool): if True these values came from the + server, and we use the data types in our endpoints. + If False, we are client side and we need to include + oneOf and discriminator classes inside the data types in our endpoints + + Returns: + (valid_classes, dict_valid_class_to_child_types_mixed): + valid_classes (tuple): the valid classes that the current item + should be + dict_valid_class_to_child_types_mixed (dict): + valid_class (class): this is the key + child_types_mixed (list/dict/tuple): describes the valid child + types + """ + valid_classes = [] + child_req_types_by_current_type = {} + for required_type in required_types_mixed: + if isinstance(required_type, list): + valid_classes.append(list) + child_req_types_by_current_type[list] = required_type + elif isinstance(required_type, tuple): + valid_classes.append(tuple) + child_req_types_by_current_type[tuple] = required_type + elif isinstance(required_type, dict): + valid_classes.append(dict) + child_req_types_by_current_type[dict] = required_type[str] + else: + valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) + return tuple(valid_classes), child_req_types_by_current_type + + +def change_keys_js_to_python(input_dict, model_class): + """ + Converts from javascript_key keys in the input_dict to python_keys in + the output dict using the mapping in model_class. + If the input_dict contains a key which does not declared in the model_class, + the key is added to the output dict as is. The assumption is the model_class + may have undeclared properties (additionalProperties attribute in the OAS + document). + """ + + if getattr(model_class, 'attribute_map', None) is None: + return input_dict + output_dict = {} + reversed_attr_map = {value: key for key, value in + model_class.attribute_map.items()} + for javascript_key, value in input_dict.items(): + python_key = reversed_attr_map.get(javascript_key) + if python_key is None: + # if the key is unknown, it is in error or it is an + # additionalProperties variable + python_key = javascript_key + output_dict[python_key] = value + return output_dict + + +def get_type_error(var_value, path_to_item, valid_classes, key_type=False): + error_msg = type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type + ) + + +def deserialize_primitive(data, klass, path_to_item): + """Deserializes string to primitive type. + + :param data: str/int/float + :param klass: str/class the class to convert to + + :return: int, float, str, bool, date, datetime + """ + additional_message = "" + try: + if klass in {datetime, date}: + additional_message = ( + "If you need your parameter to have a fallback " + "string value, please set its type as `type: {}` in your " + "spec. That allows the value to be any type. " + ) + if klass == datetime: + if len(data) < 8: + raise ValueError("This is not a datetime") + # The string should be in iso8601 datetime format. + parsed_datetime = parse(data) + date_only = ( + parsed_datetime.hour == 0 and + parsed_datetime.minute == 0 and + parsed_datetime.second == 0 and + parsed_datetime.tzinfo is None and + 8 <= len(data) <= 10 + ) + if date_only: + raise ValueError("This is a date, not a datetime") + return parsed_datetime + elif klass == date: + if len(data) < 8: + raise ValueError("This is not a date") + return parse(data).date() + else: + converted_value = klass(data) + if isinstance(data, str) and klass == float: + if str(converted_value) != data: + # '7' -> 7.0 -> '7.0' != '7' + raise ValueError('This is not a float') + return converted_value + except (OverflowError, ValueError) as ex: + # parse can raise OverflowError + raise ApiValueError( + "{0}Failed to parse {1} as {2}".format( + additional_message, repr(data), klass.__name__ + ), + path_to_item=path_to_item + ) from ex + + +def get_discriminator_class(model_class, + discr_name, + discr_value, cls_visited): + """Returns the child class specified by the discriminator. + + Args: + model_class (OpenApiModel): the model class. + discr_name (string): the name of the discriminator property. + discr_value (any): the discriminator value. + cls_visited (list): list of model classes that have been visited. + Used to determine the discriminator class without + visiting circular references indefinitely. + + Returns: + used_model_class (class/None): the chosen child class that will be used + to deserialize the data, for example dog.Dog. + If a class is not found, None is returned. + """ + + if model_class in cls_visited: + # The class has already been visited and no suitable class was found. + return None + cls_visited.append(model_class) + used_model_class = None + if discr_name in model_class.discriminator: + class_name_to_discr_class = model_class.discriminator[discr_name] + used_model_class = class_name_to_discr_class.get(discr_value) + if used_model_class is None: + # We didn't find a discriminated class in class_name_to_discr_class. + # So look in the ancestor or descendant discriminators + # The discriminator mapping may exist in a descendant (anyOf, oneOf) + # or ancestor (allOf). + # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat + # hierarchy, the discriminator mappings may be defined at any level + # in the hierarchy. + # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig + # if we try to make BasquePig from mammal, we need to travel through + # the oneOf descendant discriminators to find BasquePig + descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ + model_class._composed_schemas.get('anyOf', ()) + ancestor_classes = model_class._composed_schemas.get('allOf', ()) + possible_classes = descendant_classes + ancestor_classes + for cls in possible_classes: + # Check if the schema has inherited discriminators. + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + used_model_class = get_discriminator_class( + cls, discr_name, discr_value, cls_visited) + if used_model_class is not None: + return used_model_class + return used_model_class + + +def deserialize_model(model_data, model_class, path_to_item, check_type, + configuration, spec_property_naming): + """Deserializes model_data to model instance. + + Args: + model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model + model_class (OpenApiModel): the model class + path_to_item (list): path to the model in the received data + check_type (bool): whether to check the data tupe for the values in + the model + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + + Returns: + model instance + + Raise: + ApiTypeError + ApiValueError + ApiKeyError + """ + + kw_args = dict(_check_type=check_type, + _path_to_item=path_to_item, + _configuration=configuration, + _spec_property_naming=spec_property_naming) + + if issubclass(model_class, ModelSimple): + return model_class._new_from_openapi_data(model_data, **kw_args) + elif isinstance(model_data, list): + return model_class._new_from_openapi_data(*model_data, **kw_args) + if isinstance(model_data, dict): + kw_args.update(model_data) + return model_class._new_from_openapi_data(**kw_args) + elif isinstance(model_data, PRIMITIVE_TYPES): + return model_class._new_from_openapi_data(model_data, **kw_args) + + +def deserialize_file(response_data, configuration, content_disposition=None): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + Args: + param response_data (str): the file data to write + configuration (Configuration): the instance to use to convert files + + Keyword Args: + content_disposition (str): the value of the Content-Disposition + header + + Returns: + (file_type): the deserialized file which is open + The user is responsible for closing and reading the file + """ + fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition, + flags=re.I) + if filename is not None: + filename = filename.group(1) + else: + filename = "default_" + str(uuid.uuid4()) + + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + if isinstance(response_data, str): + # change str to bytes so we can write it + response_data = response_data.encode('utf-8') + f.write(response_data) + + f = open(path, "rb") + return f + + +def attempt_convert_item(input_value, valid_classes, path_to_item, + configuration, spec_property_naming, key_type=False, + must_convert=False, check_type=True): + """ + Args: + input_value (any): the data to convert + valid_classes (any): the classes that are valid + path_to_item (list): the path to the item to convert + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + key_type (bool): if True we need to convert a key type (not supported) + must_convert (bool): if True we must convert + check_type (bool): if True we check the type or the returned data in + ModelComposed/ModelNormal/ModelSimple instances + + Returns: + instance (any) the fixed item + + Raises: + ApiTypeError + ApiValueError + ApiKeyError + """ + valid_classes_ordered = order_response_types(valid_classes) + valid_classes_coercible = remove_uncoercible( + valid_classes_ordered, input_value, spec_property_naming) + if not valid_classes_coercible or key_type: + # we do not handle keytype errors, json will take care + # of this for us + if configuration is None or not configuration.discard_unknown_keys: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=key_type) + for valid_class in valid_classes_coercible: + try: + if issubclass(valid_class, OpenApiModel): + return deserialize_model(input_value, valid_class, + path_to_item, check_type, + configuration, spec_property_naming) + elif valid_class == file_type: + return deserialize_file(input_value, configuration) + return deserialize_primitive(input_value, valid_class, + path_to_item) + except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: + if must_convert: + raise conversion_exc + # if we have conversion errors when must_convert == False + # we ignore the exception and move on to the next class + continue + # we were unable to convert, must_convert == False + return input_value + + +def is_type_nullable(input_type): + """ + Returns true if None is an allowed value for the specified input_type. + + A type is nullable if at least one of the following conditions is true: + 1. The OAS 'nullable' attribute has been specified, + 1. The type is the 'null' type, + 1. The type is a anyOf/oneOf composed schema, and a child schema is + the 'null' type. + Args: + input_type (type): the class of the input_value that we are + checking + Returns: + bool + """ + if input_type is none_type: + return True + if issubclass(input_type, OpenApiModel) and input_type._nullable: + return True + if issubclass(input_type, ModelComposed): + # If oneOf/anyOf, check if the 'null' type is one of the allowed types. + for t in input_type._composed_schemas.get('oneOf', ()): + if is_type_nullable(t): + return True + for t in input_type._composed_schemas.get('anyOf', ()): + if is_type_nullable(t): + return True + return False + + +def is_valid_type(input_class_simple, valid_classes): + """ + Args: + input_class_simple (class): the class of the input_value that we are + checking + valid_classes (tuple): the valid classes that the current item + should be + Returns: + bool + """ + if issubclass(input_class_simple, OpenApiModel) and \ + valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,): + return True + valid_type = input_class_simple in valid_classes + if not valid_type and ( + issubclass(input_class_simple, OpenApiModel) or + input_class_simple is none_type): + for valid_class in valid_classes: + if input_class_simple is none_type and is_type_nullable(valid_class): + # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. + return True + if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): + continue + discr_propertyname_py = list(valid_class.discriminator.keys())[0] + discriminator_classes = ( + valid_class.discriminator[discr_propertyname_py].values() + ) + valid_type = is_valid_type(input_class_simple, discriminator_classes) + if valid_type: + return True + return valid_type + + +def validate_and_convert_types(input_value, required_types_mixed, path_to_item, + spec_property_naming, _check_type, configuration=None): + """Raises a TypeError is there is a problem, otherwise returns value + + Args: + input_value (any): the data to validate/convert + required_types_mixed (list/dict/tuple): A list of + valid classes, or a list tuples of valid classes, or a dict where + the value is a tuple of value classes + path_to_item: (list) the path to the data being validated + this stores a list of keys or indices to get to the data being + validated + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + _check_type: (boolean) if true, type will be checked and conversion + will be attempted. + configuration: (Configuration): the configuration class to use + when converting file_type items. + If passed, conversion will be attempted when possible + If not passed, no conversions will be attempted and + exceptions will be raised + + Returns: + the correctly typed value + + Raises: + ApiTypeError + """ + results = get_required_type_classes(required_types_mixed, spec_property_naming) + valid_classes, child_req_types_by_current_type = results + + input_class_simple = get_simple_class(input_value) + valid_type = is_valid_type(input_class_simple, valid_classes) + if not valid_type: + if (configuration + or (input_class_simple == dict + and dict not in valid_classes)): + # if input_value is not valid_type try to convert it + converted_instance = attempt_convert_item( + input_value, + valid_classes, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=True, + check_type=_check_type + ) + return converted_instance + else: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=False) + + # input_value's type is in valid_classes + if len(valid_classes) > 1 and configuration: + # there are valid classes which are not the current class + valid_classes_coercible = remove_uncoercible( + valid_classes, input_value, spec_property_naming, must_convert=False) + if valid_classes_coercible: + converted_instance = attempt_convert_item( + input_value, + valid_classes_coercible, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=False, + check_type=_check_type + ) + return converted_instance + + if child_req_types_by_current_type == {}: + # all types are of the required types and there are no more inner + # variables left to look at + return input_value + inner_required_types = child_req_types_by_current_type.get( + type(input_value) + ) + if inner_required_types is None: + # for this type, there are not more inner variables left to look at + return input_value + if isinstance(input_value, list): + if input_value == []: + # allow an empty list + return input_value + for index, inner_value in enumerate(input_value): + inner_path = list(path_to_item) + inner_path.append(index) + input_value[index] = validate_and_convert_types( + inner_value, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + elif isinstance(input_value, dict): + if input_value == {}: + # allow an empty dict + return input_value + for inner_key, inner_val in input_value.items(): + inner_path = list(path_to_item) + inner_path.append(inner_key) + if get_simple_class(inner_key) != str: + raise get_type_error(inner_key, inner_path, valid_classes, + key_type=True) + input_value[inner_key] = validate_and_convert_types( + inner_val, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + return input_value + + +def model_to_dict(model_instance, serialize=True): + """Returns the model properties as a dict + + Args: + model_instance (one of your model instances): the model instance that + will be converted to a dict. + + Keyword Args: + serialize (bool): if True, the keys in the dict will be values from + attribute_map + """ + result = {} + + def extract_item(item): return ( + item[0], model_to_dict( + item[1], serialize=serialize)) if hasattr( + item[1], '_data_store') else item + + model_instances = [model_instance] + if model_instance._composed_schemas: + model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} + for model_instance in model_instances: + for attr, value in model_instance._data_store.items(): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) + if isinstance(value, list): + if not value: + # empty list or None + result[attr] = value + else: + res = [] + for v in value: + if isinstance(v, PRIMITIVE_TYPES) or v is None: + res.append(v) + elif isinstance(v, ModelSimple): + res.append(v.value) + elif isinstance(v, dict): + res.append(dict(map( + extract_item, + v.items() + ))) + else: + res.append(model_to_dict(v, serialize=serialize)) + result[attr] = res + elif isinstance(value, dict): + result[attr] = dict(map( + extract_item, + value.items() + )) + elif isinstance(value, ModelSimple): + result[attr] = value.value + elif hasattr(value, '_data_store'): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] + + return result + + +def type_error_message(var_value=None, var_name=None, valid_classes=None, + key_type=None): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + """ + key_or_value = 'value' + if key_type: + key_or_value = 'key' + valid_classes_phrase = get_valid_classes_phrase(valid_classes) + msg = ( + "Invalid type for variable '{0}'. Required {1} type {2} and " + "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + ) + return msg + + +def get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed + """ + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return 'is {0}'.format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas['allOf']: + + try: + if constant_args.get('_spec_property_naming'): + allof_instance = allof_class._from_openapi_data(**model_args, **constant_args) + else: + allof_instance = allof_class(**model_args, **constant_args) + composed_instances.append(allof_instance) + except Exception as ex: + raise ApiValueError( + "Invalid inputs given to generate an instance of '%s'. The " + "input data was invalid for the allOf schema '%s' in the composed " + "schema '%s'. Error=%s" % ( + allof_class.__name__, + allof_class.__name__, + self.__class__.__name__, + str(ex) + ) + ) from ex + return composed_instances + + +def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): + """ + Find the oneOf schema that matches the input data (e.g. payload). + If exactly one schema matches the input data, an instance of that schema + is returned. + If zero or more than one schema match the input data, an exception is raised. + In OAS 3.x, the payload MUST, by validation, match exactly one of the + schemas described by oneOf. + + Args: + cls: the class we are handling + model_kwargs (dict): var_name to var_value + The input data, e.g. the payload that must match a oneOf schema + in the OpenAPI document. + constant_kwargs (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Kwargs: + model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): + the value to assign to a primitive class or ModelSimple class + Notes: + - this is only passed in when oneOf includes types which are not object + - None is used to suppress handling of model_arg, nullable models are handled in __new__ + + Returns + oneof_instance (instance) + """ + if len(cls._composed_schemas['oneOf']) == 0: + return None + + oneof_instances = [] + # Iterate over each oneOf schema and determine if the input data + # matches the oneOf schemas. + for oneof_class in cls._composed_schemas['oneOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if oneof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + single_value_input = allows_single_value_input(oneof_class) + + try: + if not single_value_input: + if constant_kwargs.get('_spec_property_naming'): + oneof_instance = oneof_class._from_openapi_data( + **model_kwargs, **constant_kwargs) + else: + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) + else: + if issubclass(oneof_class, ModelSimple): + if constant_kwargs.get('_spec_property_naming'): + oneof_instance = oneof_class._from_openapi_data( + model_arg, **constant_kwargs) + else: + oneof_instance = oneof_class(model_arg, **constant_kwargs) + elif oneof_class in PRIMITIVE_TYPES: + oneof_instance = validate_and_convert_types( + model_arg, + (oneof_class,), + constant_kwargs['_path_to_item'], + constant_kwargs['_spec_property_naming'], + constant_kwargs['_check_type'], + configuration=constant_kwargs['_configuration'] + ) + oneof_instances.append(oneof_instance) + except Exception: + pass + if len(oneof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None " + "of the oneOf schemas matched the input data." % + cls.__name__ + ) + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf schemas matched the inputs, but a max of one is allowed." % + cls.__name__ + ) + return oneof_instances[0] + + +def get_anyof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + The input data, e.g. the payload that must match at least one + anyOf child schema in the OpenAPI document. + constant_args (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Returns + anyof_instances (list) + """ + anyof_instances = [] + if len(self._composed_schemas['anyOf']) == 0: + return anyof_instances + + for anyof_class in self._composed_schemas['anyOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if anyof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + try: + if constant_args.get('_spec_property_naming'): + anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args) + else: + anyof_instance = anyof_class(**model_args, **constant_args) + anyof_instances.append(anyof_instance) + except Exception: + pass + if len(anyof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None of the " + "anyOf schemas matched the inputs." % + self.__class__.__name__ + ) + return anyof_instances + + +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names + # before __init__ was called + for instance in composed_instances: + if instance.__class__ in self._composed_schemas['allOf']: + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + else: + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args + + +def validate_get_composed_info(constant_args, model_args, self): + """ + For composed schemas, generate schema instances for + all schemas in the oneOf/anyOf/allOf definition. If additional + properties are allowed, also assign those properties on + all matched schemas that contain additionalProperties. + Openapi schemas are python classes. + + Exceptions are raised if: + - 0 or > 1 oneOf schema matches the model_args input data + - no anyOf schema matches the model_args input data + - any of the allOf schemas do not match the model_args input data + + Args: + constant_args (dict): these are the args that every model requires + model_args (dict): these are the required and optional spec args that + were passed in to make this model + self (class): the class that we are instantiating + This class contains self._composed_schemas + + Returns: + composed_info (list): length three + composed_instances (list): the composed instances which are not + self + var_name_to_model_instances (dict): a dict going from var_name + to the model_instance which holds that var_name + the model_instance may be self or an instance of one of the + classes in self.composed_instances() + additional_properties_model_instances (list): a list of the + model instances which have the property + additional_properties_type. This list can include self + """ + # create composed_instances + composed_instances = [] + allof_instances = get_allof_instances(self, model_args, constant_args) + composed_instances.extend(allof_instances) + oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) + if oneof_instance is not None: + composed_instances.append(oneof_instance) + anyof_instances = get_anyof_instances(self, model_args, constant_args) + composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] + + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) + + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + list( + filter( + lambda x: prop_name in x.openapi_types, composed_instances)) + + return [ + composed_instances, + var_name_to_model_instances, + additional_properties_model_instances, + discarded_args + ] diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/models/__init__.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/models/__init__.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/models/__init__.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/models/__init__.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/pom.xml b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/pom.xml similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/pom.xml rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/pom.xml diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/requirements.txt b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/requirements.txt similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/requirements.txt rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/requirements.txt diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.cfg b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/setup.cfg similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.cfg rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/setup.cfg diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/setup.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/setup.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test-requirements.txt b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test-requirements.txt similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test-requirements.txt rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test-requirements.txt diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/__init__.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/__init__.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/__init__.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/__init__.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_any_type.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_any_type.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_any_type.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_any_type.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_array.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_array.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_array.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_array.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_boolean.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_boolean.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_boolean.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_boolean.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_class.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_class.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_class.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_class.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_integer.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_integer.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_integer.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_integer.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_number.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_number.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_number.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_number.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_object.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_object.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_object.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_object.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_string.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_string.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_string.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_string.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_animal.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_animal.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal_farm.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_animal_farm.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal_farm.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_animal_farm.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_another_fake_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_another_fake_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_another_fake_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_another_fake_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_api_response.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_api_response.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_api_response.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_api_response.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_array_of_number_only.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_array_of_number_only.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_array_of_number_only.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_array_of_number_only.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_number_only.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_number_only.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_number_only.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_number_only.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_test.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_array_test.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_test.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_array_test.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_capitalization.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_capitalization.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_capitalization.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_capitalization.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_cat.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_cat.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_cat_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_cat_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_category.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_category.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_category.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_category.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_class_model.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_class_model.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_class_model.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_class_model.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_client.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_client.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_client.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_client.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_dog.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_dog.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_dog_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_dog_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_arrays.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_enum_arrays.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_arrays.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_enum_arrays.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_class.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_enum_class.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_class.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_enum_class.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_test.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_enum_test.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_test.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_enum_test.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_fake_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_fake_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags123_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags123_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags123_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags123_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags_123_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags_123_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags_123_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags_123_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_file.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_file.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file_schema_test_class.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_file_schema_test_class.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file_schema_test_class.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_file_schema_test_class.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_format_test.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_format_test.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_format_test.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_format_test.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent_animal.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent_animal.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent_animal.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent_animal.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_has_only_read_only.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_has_only_read_only.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_has_only_read_only.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_has_only_read_only.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_list.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_list.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_list.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_list.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_map_test.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_map_test.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_map_test.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_map_test.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_mixed_properties_and_additional_properties_class.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_mixed_properties_and_additional_properties_class.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_mixed_properties_and_additional_properties_class.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model200_response.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_model200_response.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model200_response.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_model200_response.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model_200_response.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_model_200_response.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model_200_response.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_model_200_response.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model_return.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_model_return.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model_return.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_model_return.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_name.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_name.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_name.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_name.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_only.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_number_only.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_only.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_number_only.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_with_validations.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_number_with_validations.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_with_validations.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_number_with_validations.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_object_model_with_ref_props.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_object_model_with_ref_props.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_object_model_with_ref_props.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_object_model_with_ref_props.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_order.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_order.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_order.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_order.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_parent.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_parent.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_parent_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_parent_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_pet.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_parent_pet.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_pet.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_parent_pet.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_pet.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_pet.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_pet_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_pet_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_player.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_player.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_player.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_player.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_polygon.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_polygon.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_polygon.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_polygon.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_polygon_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_polygon_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_polygon_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_polygon_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_read_only_first.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_read_only_first.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_read_only_first.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_read_only_first.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_shape.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_shape.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_shape.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_shape.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_special_model_name.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_special_model_name.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_special_model_name.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_special_model_name.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_square.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_square.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_square.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_square.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_square_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_square_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_square_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_square_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_store_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_store_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_store_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_store_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_boolean_map.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_string_boolean_map.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_boolean_map.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_string_boolean_map.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_enum.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_string_enum.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_enum.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_string_enum.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_tag.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_tag.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_tag.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_tag.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_triangle.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_triangle.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_triangle.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_triangle.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_triangle_all_of.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_triangle_all_of.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_triangle_all_of.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_triangle_all_of.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_default.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_default.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_default.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_default.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_example.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_example.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_example.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_example.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_user.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_user.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_user_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_user_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_xml_item.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_xml_item.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_xml_item.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test/test_xml_item.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test_python.sh b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test_python.sh similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test_python.sh rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/test_python.sh diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic1.png b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic1.png similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic1.png rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic1.png diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic2.png b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic2.png similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic2.png rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic2.png diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/foo.png b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/testfiles/foo.png similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/foo.png rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/testfiles/foo.png diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/__init__.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/__init__.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/__init__.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/__init__.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_client.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_api_client.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_client.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_api_client.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_exception.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_api_exception.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_exception.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_api_exception.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_deserialization.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_deserialization.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_deserialization.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_deserialization.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_pet_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_pet_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_pet_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_pet_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_serialization.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_serialization.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_serialization.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_serialization.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_store_api.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_store_api.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_store_api.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/test_store_api.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/util.py b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/util.py similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/util.py rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tests/util.py diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tox.ini b/samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tox.ini similarity index 100% rename from samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tox.ini rename to samples/client/petstore/python-prior_disallowAdditionalPropertiesIfNotPresent/tox.ini diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md deleted file mode 100644 index 4b34d32b61..0000000000 --- a/samples/client/petstore/python/README.md +++ /dev/null @@ -1,254 +0,0 @@ -# petstore-api -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - -This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: 1.0.0 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.PythonClientCodegen - -## Requirements. - -Python >=3.6 - -## Installation & Usage -### pip install - -If the python package is hosted on a repository, you can install directly using: - -```sh -pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git -``` -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) - -Then import the package: -```python -import petstore_api -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: -```python -import petstore_api -``` - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```python - -import time -import petstore_api -from pprint import pprint -from petstore_api.api import another_fake_api -from petstore_api.model.client import Client -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = another_fake_api.AnotherFakeApi(api_client) - body = Client( - client="client_example", - ) # Client | client model - - try: - # To test special tags - api_response = api_instance.call_123_test_special_tags(body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags -*FakeApi* | [**array_model**](docs/FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | -*FakeApi* | [**boolean**](docs/FakeApi.md#boolean) | **POST** /fake/refs/boolean | -*FakeApi* | [**create_xml_item**](docs/FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem -*FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | -*FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | -*FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | -*FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | -*FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | -*FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | -*FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model -*FakeApi* | [**test_endpoint_enums_length_one**](docs/FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | -*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -*FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data -*FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case -*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet -*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image -*PetApi* | [**upload_file_with_required_file**](docs/PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet -*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user -*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user -*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name -*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system -*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user - - -## Documentation For Models - - - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) - - [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) - - [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) - - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - - [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) - - [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) - - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) - - [AdditionalPropertiesString](docs/AdditionalPropertiesString.md) - - [Animal](docs/Animal.md) - - [AnimalFarm](docs/AnimalFarm.md) - - [ApiResponse](docs/ApiResponse.md) - - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - - [ArrayTest](docs/ArrayTest.md) - - [Capitalization](docs/Capitalization.md) - - [Cat](docs/Cat.md) - - [CatAllOf](docs/CatAllOf.md) - - [Category](docs/Category.md) - - [Child](docs/Child.md) - - [ChildAllOf](docs/ChildAllOf.md) - - [ChildCat](docs/ChildCat.md) - - [ChildCatAllOf](docs/ChildCatAllOf.md) - - [ChildDog](docs/ChildDog.md) - - [ChildDogAllOf](docs/ChildDogAllOf.md) - - [ChildLizard](docs/ChildLizard.md) - - [ChildLizardAllOf](docs/ChildLizardAllOf.md) - - [ClassModel](docs/ClassModel.md) - - [Client](docs/Client.md) - - [Dog](docs/Dog.md) - - [DogAllOf](docs/DogAllOf.md) - - [EnumArrays](docs/EnumArrays.md) - - [EnumClass](docs/EnumClass.md) - - [EnumTest](docs/EnumTest.md) - - [File](docs/File.md) - - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - - [FormatTest](docs/FormatTest.md) - - [Grandparent](docs/Grandparent.md) - - [GrandparentAnimal](docs/GrandparentAnimal.md) - - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - - [List](docs/List.md) - - [MapTest](docs/MapTest.md) - - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - - [Model200Response](docs/Model200Response.md) - - [ModelReturn](docs/ModelReturn.md) - - [Name](docs/Name.md) - - [NumberOnly](docs/NumberOnly.md) - - [NumberWithValidations](docs/NumberWithValidations.md) - - [ObjectModelWithRefProps](docs/ObjectModelWithRefProps.md) - - [Order](docs/Order.md) - - [Parent](docs/Parent.md) - - [ParentAllOf](docs/ParentAllOf.md) - - [ParentPet](docs/ParentPet.md) - - [Pet](docs/Pet.md) - - [Player](docs/Player.md) - - [Polygon](docs/Polygon.md) - - [PolygonAllOf](docs/PolygonAllOf.md) - - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - - [Shape](docs/Shape.md) - - [SpecialModelName](docs/SpecialModelName.md) - - [Square](docs/Square.md) - - [SquareAllOf](docs/SquareAllOf.md) - - [StringBooleanMap](docs/StringBooleanMap.md) - - [StringEnum](docs/StringEnum.md) - - [Tag](docs/Tag.md) - - [Triangle](docs/Triangle.md) - - [TriangleAllOf](docs/TriangleAllOf.md) - - [TypeHolderDefault](docs/TypeHolderDefault.md) - - [TypeHolderExample](docs/TypeHolderExample.md) - - [User](docs/User.md) - - [XmlItem](docs/XmlItem.md) - - -## Documentation For Authorization - - -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - - -## api_key_query - -- **Type**: API key -- **API key parameter name**: api_key_query -- **Location**: URL query string - - -## http_basic_test - -- **Type**: HTTP basic authentication - - -## petstore_auth - -- **Type**: OAuth -- **Flow**: implicit -- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog -- **Scopes**: - - **write:pets**: modify pets in your account - - **read:pets**: read your pets - - -## Author - - - - -## Notes for Large OpenAPI documents -If the OpenAPI document is large, imports in petstore_api.apis and petstore_api.models may fail with a -RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: - -Solution 1: -Use specific imports for apis and models like: -- `from petstore_api.api.default_api import DefaultApi` -- `from petstore_api.model.pet import Pet` - -Solution 2: -Before importing the package, adjust the maximum recursion limit as shown below: -``` -import sys -sys.setrecursionlimit(1500) -import petstore_api -from petstore_api.apis import * -from petstore_api.models import * -``` - diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md deleted file mode 100644 index c52fe144ab..0000000000 --- a/samples/client/petstore/python/docs/FakeApi.md +++ /dev/null @@ -1,1239 +0,0 @@ -# petstore_api.FakeApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**array_model**](FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | -[**boolean**](FakeApi.md#boolean) | **POST** /fake/refs/boolean | -[**create_xml_item**](FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem -[**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | -[**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | -[**string**](FakeApi.md#string) | **POST** /fake/refs/string | -[**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | -[**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | -[**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | -[**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model -[**test_endpoint_enums_length_one**](FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | -[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -[**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -[**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data - - -# **array_model** -> AnimalFarm array_model() - - - -Test serialization of ArrayModel - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.animal_farm import AnimalFarm -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = AnimalFarm([ - Animal(), - ]) # AnimalFarm | Input model (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.array_model(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->array_model: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**AnimalFarm**](AnimalFarm.md)| Input model | [optional] - -### Return type - -[**AnimalFarm**](AnimalFarm.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output model | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **boolean** -> bool boolean() - - - -Test serialization of outer boolean types - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = True # bool | Input boolean as post body (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.boolean(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->boolean: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **bool**| Input boolean as post body | [optional] - -### Return type - -**bool** - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output boolean | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_xml_item** -> create_xml_item(xml_item) - -creates an XmlItem - -this route creates an XmlItem - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.xml_item import XmlItem -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - xml_item = XmlItem( - attribute_string="string", - attribute_number=1.234, - attribute_integer=-2, - attribute_boolean=True, - wrapped_array=[ - 1, - ], - name_string="string", - name_number=1.234, - name_integer=-2, - name_boolean=True, - name_array=[ - 1, - ], - name_wrapped_array=[ - 1, - ], - prefix_string="string", - prefix_number=1.234, - prefix_integer=-2, - prefix_boolean=True, - prefix_array=[ - 1, - ], - prefix_wrapped_array=[ - 1, - ], - namespace_string="string", - namespace_number=1.234, - namespace_integer=-2, - namespace_boolean=True, - namespace_array=[ - 1, - ], - namespace_wrapped_array=[ - 1, - ], - prefix_ns_string="string", - prefix_ns_number=1.234, - prefix_ns_integer=-2, - prefix_ns_boolean=True, - prefix_ns_array=[ - 1, - ], - prefix_ns_wrapped_array=[ - 1, - ], - ) # XmlItem | XmlItem Body - - # example passing only required values which don't have defaults set - try: - # creates an XmlItem - api_instance.create_xml_item(xml_item) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->create_xml_item: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **xml_item** | [**XmlItem**](XmlItem.md)| XmlItem Body | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/xml, application/xml; charset=utf-8, application/xml; charset=utf-16, text/xml, text/xml; charset=utf-8, text/xml; charset=utf-16 - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **number_with_validations** -> NumberWithValidations number_with_validations() - - - -Test serialization of outer number types - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.number_with_validations import NumberWithValidations -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = NumberWithValidations(1E+1) # NumberWithValidations | Input number as post body (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.number_with_validations(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->number_with_validations: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**NumberWithValidations**](NumberWithValidations.md)| Input number as post body | [optional] - -### Return type - -[**NumberWithValidations**](NumberWithValidations.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output number | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **object_model_with_ref_props** -> ObjectModelWithRefProps object_model_with_ref_props() - - - -Test serialization of object with $refed properties - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = ObjectModelWithRefProps( - my_number=NumberWithValidations(1E+1), - my_string="my_string_example", - my_boolean=True, - ) # ObjectModelWithRefProps | Input model (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.object_model_with_ref_props(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**ObjectModelWithRefProps**](ObjectModelWithRefProps.md)| Input model | [optional] - -### Return type - -[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output model | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **string** -> str string() - - - -Test serialization of outer string types - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = "body_example" # str | Input string as post body (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.string(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->string: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **str**| Input string as post body | [optional] - -### Return type - -**str** - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output string | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **string_enum** -> StringEnum string_enum() - - - -Test serialization of outer enum - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.string_enum import StringEnum -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = StringEnum("placed") # StringEnum | Input enum (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.string_enum(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->string_enum: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**StringEnum**](StringEnum.md)| Input enum | [optional] - -### Return type - -[**StringEnum**](StringEnum.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output enum | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_body_with_file_schema** -> test_body_with_file_schema(body) - - - -For this test, the body for this request much reference a schema named `File`. - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.file_schema_test_class import FileSchemaTestClass -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = FileSchemaTestClass( - file=File( - source_uri="source_uri_example", - ), - files=[ - File( - source_uri="source_uri_example", - ), - ], - ) # FileSchemaTestClass | - - # example passing only required values which don't have defaults set - try: - api_instance.test_body_with_file_schema(body) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_body_with_file_schema: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_body_with_query_params** -> test_body_with_query_params(query, body) - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.user import User -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - query = "query_example" # str | - body = User( - id=1, - username="username_example", - first_name="first_name_example", - last_name="last_name_example", - email="email_example", - password="password_example", - phone="phone_example", - user_status=1, - ) # User | - - # example passing only required values which don't have defaults set - try: - api_instance.test_body_with_query_params(query, body) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_body_with_query_params: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **query** | **str**| | - **body** | [**User**](User.md)| | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_client_model** -> Client test_client_model(body) - -To test \"client\" model - -To test \"client\" model - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.client import Client -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = Client( - client="client_example", - ) # Client | client model - - # example passing only required values which don't have defaults set - try: - # To test \"client\" model - api_response = api_instance.test_client_model(body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_client_model: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | - -### Return type - -[**Client**](Client.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_endpoint_enums_length_one** -> test_endpoint_enums_length_one() - - - -This route has required values with enums of 1 - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - try: - api_instance.test_endpoint_enums_length_one() - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_endpoint_enums_length_one: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **query_integer** | **int**| | defaults to 3 - **query_string** | **str**| | defaults to "brillig" - **path_string** | **str**| | defaults to "hello" - **path_integer** | **int**| | defaults to 34 - **header_number** | **float**| | defaults to 1.234 - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_endpoint_parameters** -> test_endpoint_parameters(number, double, pattern_without_delimiter, byte) - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -### Example - -* Basic Authentication (http_basic_test): - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure HTTP basic authorization: http_basic_test -configuration = petstore_api.Configuration( - username = 'YOUR_USERNAME', - password = 'YOUR_PASSWORD' -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - number = 32.1 # float | None - double = 67.8 # float | None - pattern_without_delimiter = "Aj" # str | None - byte = 'YQ==' # str | None - integer = 10 # int | None (optional) - int32 = 20 # int | None (optional) - int64 = 1 # int | None (optional) - float = 3.14 # float | None (optional) - string = "A" # str | None (optional) - binary = open('/path/to/file', 'rb') # file_type | None (optional) - date = dateutil_parser('1970-01-01').date() # date | None (optional) - date_time = dateutil_parser('1970-01-01T00:00:00.00Z') # datetime | None (optional) - password = "password_example" # str | None (optional) - param_callback = "param_callback_example" # str | None (optional) - - # example passing only required values which don't have defaults set - try: - # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) - - # example passing only required values which don't have defaults set - # and optional values - try: - # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **number** | **float**| None | - **double** | **float**| None | - **pattern_without_delimiter** | **str**| None | - **byte** | **str**| None | - **integer** | **int**| None | [optional] - **int32** | **int**| None | [optional] - **int64** | **int**| None | [optional] - **float** | **float**| None | [optional] - **string** | **str**| None | [optional] - **binary** | **file_type**| None | [optional] - **date** | **date**| None | [optional] - **date_time** | **datetime**| None | [optional] - **password** | **str**| None | [optional] - **param_callback** | **str**| None | [optional] - -### Return type - -void (empty response body) - -### Authorization - -[http_basic_test](../README.md#http_basic_test) - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**400** | Invalid username supplied | - | -**404** | User not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_enum_parameters** -> test_enum_parameters() - -To test enum parameters - -To test enum parameters - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - enum_header_string_array = [ - "$", - ] # [str] | Header parameter enum test (string array) (optional) - enum_header_string = "-efg" # str | Header parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" - enum_query_string_array = [ - "$", - ] # [str] | Query parameter enum test (string array) (optional) - enum_query_string = "-efg" # str | Query parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" - enum_query_integer = 1 # int | Query parameter enum test (double) (optional) - enum_query_double = 1.1 # float | Query parameter enum test (double) (optional) - enum_form_string_array = [ - "$", - ] # [str] | Form parameter enum test (string array) (optional) if omitted the server will use the default value of "$" - enum_form_string = "-efg" # str | Form parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" - - # example passing only required values which don't have defaults set - # and optional values - try: - # To test enum parameters - api_instance.test_enum_parameters(enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double, enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **enum_header_string_array** | **[str]**| Header parameter enum test (string array) | [optional] - **enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" - **enum_query_string_array** | **[str]**| Query parameter enum test (string array) | [optional] - **enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" - **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] - **enum_query_double** | **float**| Query parameter enum test (double) | [optional] - **enum_form_string_array** | **[str]**| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of "$" - **enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**400** | Invalid request | - | -**404** | Not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_group_parameters** -> test_group_parameters(required_string_group, required_boolean_group, required_int64_group) - -Fake endpoint to test group parameters (optional) - -Fake endpoint to test group parameters (optional) - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - required_string_group = 1 # int | Required String in group parameters - required_boolean_group = True # bool | Required Boolean in group parameters - required_int64_group = 1 # int | Required Integer in group parameters - string_group = 1 # int | String in group parameters (optional) - boolean_group = True # bool | Boolean in group parameters (optional) - int64_group = 1 # int | Integer in group parameters (optional) - - # example passing only required values which don't have defaults set - try: - # Fake endpoint to test group parameters (optional) - api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) - - # example passing only required values which don't have defaults set - # and optional values - try: - # Fake endpoint to test group parameters (optional) - api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **required_string_group** | **int**| Required String in group parameters | - **required_boolean_group** | **bool**| Required Boolean in group parameters | - **required_int64_group** | **int**| Required Integer in group parameters | - **string_group** | **int**| String in group parameters | [optional] - **boolean_group** | **bool**| Boolean in group parameters | [optional] - **int64_group** | **int**| Integer in group parameters | [optional] - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**400** | Someting wrong | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_inline_additional_properties** -> test_inline_additional_properties(param) - -test inline additionalProperties - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - param = { - "key": "key_example", - } # {str: (str,)} | request body - - # example passing only required values which don't have defaults set - try: - # test inline additionalProperties - api_instance.test_inline_additional_properties(param) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **param** | **{str: (str,)}**| request body | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_json_form_data** -> test_json_form_data(param, param2) - -test json serialization of form data - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - param = "param_example" # str | field1 - param2 = "param2_example" # str | field2 - - # example passing only required values which don't have defaults set - try: - # test json serialization of form data - api_instance.test_json_form_data(param, param2) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_json_form_data: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **param** | **str**| field1 | - **param2** | **str**| field2 | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/python/petstore_api/model_utils.py b/samples/client/petstore/python/petstore_api/model_utils.py deleted file mode 100644 index 933ceec6fa..0000000000 --- a/samples/client/petstore/python/petstore_api/model_utils.py +++ /dev/null @@ -1,2058 +0,0 @@ -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from datetime import date, datetime # noqa: F401 -from copy import deepcopy -import inspect -import io -import os -import pprint -import re -import tempfile -import uuid - -from dateutil.parser import parse - -from petstore_api.exceptions import ( - ApiKeyError, - ApiAttributeError, - ApiTypeError, - ApiValueError, -) - -none_type = type(None) -file_type = io.IOBase - - -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python( - kwargs, _self if isinstance( - _self, type) else _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - -class cached_property(object): - # this caches the result of the function call for fn with no inputs - # use this as a decorator on function methods that you want converted - # into cached properties - result_key = '_results' - - def __init__(self, fn): - self._fn = fn - - def __get__(self, instance, cls=None): - if self.result_key in vars(self): - return vars(self)[self.result_key] - else: - result = self._fn() - setattr(self, self.result_key, result) - return result - - -PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) - - -def allows_single_value_input(cls): - """ - This function returns True if the input composed schema model or any - descendant model allows a value only input - This is true for cases where oneOf contains items like: - oneOf: - - float - - NumberWithValidation - - StringEnum - - ArrayModel - - null - TODO: lru_cache this - """ - if ( - issubclass(cls, ModelSimple) or - cls in PRIMITIVE_TYPES - ): - return True - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas['oneOf']: - return False - return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) - return False - - -def composed_model_input_classes(cls): - """ - This function returns a list of the possible models that can be accepted as - inputs. - TODO: lru_cache this - """ - if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: - return [cls] - elif issubclass(cls, ModelNormal): - if cls.discriminator is None: - return [cls] - else: - return get_discriminated_classes(cls) - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas['oneOf']: - return [] - if cls.discriminator is None: - input_classes = [] - for c in cls._composed_schemas['oneOf']: - input_classes.extend(composed_model_input_classes(c)) - return input_classes - else: - return get_discriminated_classes(cls) - return [] - - -class OpenApiModel(object): - """The base class for all OpenAPIModels""" - - def set_attribute(self, name, value): - # this is only used to set properties on self - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._spec_property_naming, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value, - self._configuration - ) - self.__dict__['_data_store'][name] = value - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other - - def __setattr__(self, attr, value): - """set the value of an attribute using dot notation: `instance.attr = val`""" - self[attr] = value - - def __getattr__(self, attr): - """get the value of an attribute using dot notation: `instance.attr`""" - return self.__getitem__(attr) - - def __copy__(self): - cls = self.__class__ - if self.get("_spec_property_naming", False): - return cls._new_from_openapi_data(**self.__dict__) - else: - return cls.__new__(cls, **self.__dict__) - - def __deepcopy__(self, memo): - cls = self.__class__ - - if self.get("_spec_property_naming", False): - new_inst = cls._new_from_openapi_data() - else: - new_inst = cls.__new__(cls) - - for k, v in self.__dict__.items(): - setattr(new_inst, k, deepcopy(v, memo)) - return new_inst - - - def __new__(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get('_visited_composed_classes', ()) - if ( - cls.discriminator is None or - cls in visited_composed_classes - ): - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: If Animal has a discriminator - # petType and we pass in "Dog", and the class Dog - # allOf includes Animal, we move through Animal - # once using the discriminator, and pick Dog. - # Then in the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return super(OpenApiModel, cls).__new__(cls) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % - (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class( - cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get('_path_to_item', ()) - disc_prop_value = kwargs.get( - discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % - (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return super(OpenApiModel, cls).__new__(cls) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = ( - cls._composed_schemas.get('oneOf', ()) + - cls._composed_schemas.get('anyOf', ())) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get('allOf') and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = super(OpenApiModel, cls).__new__(cls) - self_inst.__init__(*args, **kwargs) - - if kwargs.get("_spec_property_naming", False): - # when true, implies new is from deserialization - new_inst = new_cls._new_from_openapi_data(*args, **kwargs) - else: - new_inst = new_cls.__new__(new_cls, *args, **kwargs) - new_inst.__init__(*args, **kwargs) - - return new_inst - - @classmethod - @convert_js_args_to_python_args - def _new_from_openapi_data(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get('_visited_composed_classes', ()) - if ( - cls.discriminator is None or - cls in visited_composed_classes - ): - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: If Animal has a discriminator - # petType and we pass in "Dog", and the class Dog - # allOf includes Animal, we move through Animal - # once using the discriminator, and pick Dog. - # Then in the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return cls._from_openapi_data(*args, **kwargs) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % - (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class( - cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get('_path_to_item', ()) - disc_prop_value = kwargs.get( - discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % - (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return cls._from_openapi_data(*args, **kwargs) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = ( - cls._composed_schemas.get('oneOf', ()) + - cls._composed_schemas.get('anyOf', ())) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get('allOf') and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = cls._from_openapi_data(*args, **kwargs) - - new_inst = new_cls._new_from_openapi_data(*args, **kwargs) - return new_inst - - -class ModelSimple(OpenApiModel): - """the parent class of models whose type != object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__['_data_store'].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__['_data_store'] - - def to_str(self): - """Returns the string representation of the model""" - return str(self.value) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - this_val = self._data_store['value'] - that_val = other._data_store['value'] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - return vals_equal - - -class ModelNormal(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__['_data_store'].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__['_data_store'] - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -class ModelComposed(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi and have oneOf/allOf/anyOf - - When one sets a property we use var_name_to_model_instances to store the value in - the correct class instances + run any type checking + validation code. - When one gets a property we use var_name_to_model_instances to get the value - from the correct class instances. - This allows multiple composed schemas to contain the same property with additive - constraints on the value. - - _composed_schemas (dict) stores the anyOf/allOf/oneOf classes - key (str): allOf/oneOf/anyOf - value (list): the classes in the XOf definition. - Note: none_type can be included when the openapi document version >= 3.1.0 - _composed_instances (list): stores a list of instances of the composed schemas - defined in _composed_schemas. When properties are accessed in the self instance, - they are returned from the self._data_store or the data stores in the instances - in self._composed_schemas - _var_name_to_model_instances (dict): maps between a variable name on self and - the composed instances (self included) which contain that data - key (str): property name - value (list): list of class instances, self or instances in _composed_instances - which contain the value that the key is referring to. - """ - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - """ - Use cases: - 1. additional_properties_type is None (additionalProperties == False in spec) - Check for property presence in self.openapi_types - if not present then throw an error - if present set in self, set attribute - always set on composed schemas - 2. additional_properties_type exists - set attribute on self - always set on composed schemas - """ - if self.additional_properties_type is None: - """ - For an attribute to exist on a composed schema it must: - - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND - - fulfill schema_requirements in each oneOf/anyOf/allOf schemas - - schema_requirements: - For an attribute to exist on a schema it must: - - be present in properties at the schema OR - - have additionalProperties unset (defaults additionalProperties = any type) OR - - have additionalProperties set - """ - if name not in self.openapi_types: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - # attribute must be set on self and composed instances - self.set_attribute(name, value) - for model_instance in self._composed_instances: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] - return None - - __unset_attribute_value__ = object() - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get(name) - values = [] - # A composed model stores self and child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. - # Any property must exist in self and all model instances - # The value stored in all model instances must be the same - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - v = model_instance._data_store[name] - if v not in values: - values.append(v) - len_values = len(values) - if len_values == 0: - return default - elif len_values == 1: - return values[0] - elif len_values > 1: - raise ApiValueError( - "Values stored for property {0} in {1} differ when looking " - "at self and self's composed instances. All values must be " - "the same".format(name, type(self).__name__), - [e for e in [self._path_to_item, name] if e] - ) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - value = self.get(name, self.__unset_attribute_value__) - if value is self.__unset_attribute_value__: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - return value - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - - if name in self.required_properties: - return name in self.__dict__ - - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) - - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - return True - - return False - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -COERCION_INDEX_BY_TYPE = { - ModelComposed: 0, - ModelNormal: 1, - ModelSimple: 2, - none_type: 3, # The type of 'None'. - list: 4, - dict: 5, - float: 6, - int: 7, - bool: 8, - datetime: 9, - date: 10, - str: 11, - file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. -} - -# these are used to limit what type conversions we try to do -# when we have a valid type already and we want to try converting -# to another type -UPCONVERSION_TYPE_PAIRS = ( - (str, datetime), - (str, date), - # A float may be serialized as an integer, e.g. '3' is a valid serialized float. - (int, float), - (list, ModelComposed), - (dict, ModelComposed), - (str, ModelComposed), - (int, ModelComposed), - (float, ModelComposed), - (list, ModelComposed), - (list, ModelNormal), - (dict, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), -) - -COERCIBLE_TYPE_PAIRS = { - False: ( # client instantiation of a model with client data - # (dict, ModelComposed), - # (list, ModelComposed), - # (dict, ModelNormal), - # (list, ModelNormal), - # (str, ModelSimple), - # (int, ModelSimple), - # (float, ModelSimple), - # (list, ModelSimple), - # (str, int), - # (str, float), - # (str, datetime), - # (str, date), - # (int, str), - # (float, str), - ), - True: ( # server -> client data - (dict, ModelComposed), - (list, ModelComposed), - (dict, ModelNormal), - (list, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), - # (str, int), - # (str, float), - (str, datetime), - (str, date), - # (int, str), - # (float, str), - (str, file_type) - ), -} - - -def get_simple_class(input_value): - """Returns an input_value's simple class that we will use for type checking - Python2: - float and int will return int, where int is the python3 int backport - str and unicode will return str, where str is the python3 str backport - Note: float and int ARE both instances of int backport - Note: str_py2 and unicode_py2 are NOT both instances of str backport - - Args: - input_value (class/class_instance): the item for which we will return - the simple class - """ - if isinstance(input_value, type): - # input_value is a class - return input_value - elif isinstance(input_value, tuple): - return tuple - elif isinstance(input_value, list): - return list - elif isinstance(input_value, dict): - return dict - elif isinstance(input_value, none_type): - return none_type - elif isinstance(input_value, file_type): - return file_type - elif isinstance(input_value, bool): - # this must be higher than the int check because - # isinstance(True, int) == True - return bool - elif isinstance(input_value, int): - return int - elif isinstance(input_value, datetime): - # this must be higher than the date check because - # isinstance(datetime_instance, date) == True - return datetime - elif isinstance(input_value, date): - return date - elif isinstance(input_value, str): - return str - return type(input_value) - - -def check_allowed_values(allowed_values, input_variable_path, input_values): - """Raises an exception if the input_values are not allowed - - Args: - allowed_values (dict): the allowed_values dict - input_variable_path (tuple): the path to the input variable - input_values (list/str/int/float/date/datetime): the values that we - are checking to see if they are in allowed_values - """ - these_allowed_values = list(allowed_values[input_variable_path].values()) - if (isinstance(input_values, list) - and not set(input_values).issubset( - set(these_allowed_values))): - invalid_values = ", ".join( - map(str, set(input_values) - set(these_allowed_values))), - raise ApiValueError( - "Invalid values for `%s` [%s], must be a subset of [%s]" % - ( - input_variable_path[0], - invalid_values, - ", ".join(map(str, these_allowed_values)) - ) - ) - elif (isinstance(input_values, dict) - and not set( - input_values.keys()).issubset(set(these_allowed_values))): - invalid_values = ", ".join( - map(str, set(input_values.keys()) - set(these_allowed_values))) - raise ApiValueError( - "Invalid keys in `%s` [%s], must be a subset of [%s]" % - ( - input_variable_path[0], - invalid_values, - ", ".join(map(str, these_allowed_values)) - ) - ) - elif (not isinstance(input_values, (list, dict)) - and input_values not in these_allowed_values): - raise ApiValueError( - "Invalid value for `%s` (%s), must be one of %s" % - ( - input_variable_path[0], - input_values, - these_allowed_values - ) - ) - - -def is_json_validation_enabled(schema_keyword, configuration=None): - """Returns true if JSON schema validation is enabled for the specified - validation keyword. This can be used to skip JSON schema structural validation - as requested in the configuration. - - Args: - schema_keyword (string): the name of a JSON schema validation keyword. - configuration (Configuration): the configuration class. - """ - - return (configuration is None or - not hasattr(configuration, '_disabled_client_side_validations') or - schema_keyword not in configuration._disabled_client_side_validations) - - -def check_validations( - validations, input_variable_path, input_values, - configuration=None): - """Raises an exception if the input_values are invalid - - Args: - validations (dict): the validation dictionary. - input_variable_path (tuple): the path to the input variable. - input_values (list/str/int/float/date/datetime): the values that we - are checking. - configuration (Configuration): the configuration class. - """ - - if input_values is None: - return - - current_validations = validations[input_variable_path] - if (is_json_validation_enabled('multipleOf', configuration) and - 'multiple_of' in current_validations and - isinstance(input_values, (int, float)) and - not (float(input_values) / current_validations['multiple_of']).is_integer()): - # Note 'multipleOf' will be as good as the floating point arithmetic. - raise ApiValueError( - "Invalid value for `%s`, value must be a multiple of " - "`%s`" % ( - input_variable_path[0], - current_validations['multiple_of'] - ) - ) - - if (is_json_validation_enabled('maxLength', configuration) and - 'max_length' in current_validations and - len(input_values) > current_validations['max_length']): - raise ApiValueError( - "Invalid value for `%s`, length must be less than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['max_length'] - ) - ) - - if (is_json_validation_enabled('minLength', configuration) and - 'min_length' in current_validations and - len(input_values) < current_validations['min_length']): - raise ApiValueError( - "Invalid value for `%s`, length must be greater than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['min_length'] - ) - ) - - if (is_json_validation_enabled('maxItems', configuration) and - 'max_items' in current_validations and - len(input_values) > current_validations['max_items']): - raise ApiValueError( - "Invalid value for `%s`, number of items must be less than or " - "equal to `%s`" % ( - input_variable_path[0], - current_validations['max_items'] - ) - ) - - if (is_json_validation_enabled('minItems', configuration) and - 'min_items' in current_validations and - len(input_values) < current_validations['min_items']): - raise ValueError( - "Invalid value for `%s`, number of items must be greater than or " - "equal to `%s`" % ( - input_variable_path[0], - current_validations['min_items'] - ) - ) - - items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', - 'inclusive_minimum') - if (any(item in current_validations for item in items)): - if isinstance(input_values, list): - max_val = max(input_values) - min_val = min(input_values) - elif isinstance(input_values, dict): - max_val = max(input_values.values()) - min_val = min(input_values.values()) - else: - max_val = input_values - min_val = input_values - - if (is_json_validation_enabled('exclusiveMaximum', configuration) and - 'exclusive_maximum' in current_validations and - max_val >= current_validations['exclusive_maximum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than `%s`" % ( - input_variable_path[0], - current_validations['exclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('maximum', configuration) and - 'inclusive_maximum' in current_validations and - max_val > current_validations['inclusive_maximum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['inclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('exclusiveMinimum', configuration) and - 'exclusive_minimum' in current_validations and - min_val <= current_validations['exclusive_minimum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than `%s`" % - ( - input_variable_path[0], - current_validations['exclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('minimum', configuration) and - 'inclusive_minimum' in current_validations and - min_val < current_validations['inclusive_minimum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than or equal " - "to `%s`" % ( - input_variable_path[0], - current_validations['inclusive_minimum'] - ) - ) - flags = current_validations.get('regex', {}).get('flags', 0) - if (is_json_validation_enabled('pattern', configuration) and - 'regex' in current_validations and - not re.search(current_validations['regex']['pattern'], - input_values, flags=flags)): - err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( - input_variable_path[0], - current_validations['regex']['pattern'] - ) - if flags != 0: - # Don't print the regex flags if the flags are not - # specified in the OAS document. - err_msg = r"%s with flags=`%s`" % (err_msg, flags) - raise ApiValueError(err_msg) - - -def order_response_types(required_types): - """Returns the required types sorted in coercion order - - Args: - required_types (list/tuple): collection of classes or instance of - list or dict with class information inside it. - - Returns: - (list): coercion order sorted collection of classes or instance - of list or dict with class information inside it. - """ - - def index_getter(class_or_instance): - if isinstance(class_or_instance, list): - return COERCION_INDEX_BY_TYPE[list] - elif isinstance(class_or_instance, dict): - return COERCION_INDEX_BY_TYPE[dict] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelComposed)): - return COERCION_INDEX_BY_TYPE[ModelComposed] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelNormal)): - return COERCION_INDEX_BY_TYPE[ModelNormal] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelSimple)): - return COERCION_INDEX_BY_TYPE[ModelSimple] - elif class_or_instance in COERCION_INDEX_BY_TYPE: - return COERCION_INDEX_BY_TYPE[class_or_instance] - raise ApiValueError("Unsupported type: %s" % class_or_instance) - - sorted_types = sorted( - required_types, - key=lambda class_or_instance: index_getter(class_or_instance) - ) - return sorted_types - - -def remove_uncoercible(required_types_classes, current_item, spec_property_naming, - must_convert=True): - """Only keeps the type conversions that are possible - - Args: - required_types_classes (tuple): tuple of classes that are required - these should be ordered by COERCION_INDEX_BY_TYPE - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - current_item (any): the current item (input data) to be converted - - Keyword Args: - must_convert (bool): if True the item to convert is of the wrong - type and we want a big list of coercibles - if False, we want a limited list of coercibles - - Returns: - (list): the remaining coercible required types, classes only - """ - current_type_simple = get_simple_class(current_item) - - results_classes = [] - for required_type_class in required_types_classes: - # convert our models to OpenApiModel - required_type_class_simplified = required_type_class - if isinstance(required_type_class_simplified, type): - if issubclass(required_type_class_simplified, ModelComposed): - required_type_class_simplified = ModelComposed - elif issubclass(required_type_class_simplified, ModelNormal): - required_type_class_simplified = ModelNormal - elif issubclass(required_type_class_simplified, ModelSimple): - required_type_class_simplified = ModelSimple - - if required_type_class_simplified == current_type_simple: - # don't consider converting to one's own class - continue - - class_pair = (current_type_simple, required_type_class_simplified) - if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: - results_classes.append(required_type_class) - elif class_pair in UPCONVERSION_TYPE_PAIRS: - results_classes.append(required_type_class) - return results_classes - - -def get_discriminated_classes(cls): - """ - Returns all the classes that a discriminator converts to - TODO: lru_cache this - """ - possible_classes = [] - key = list(cls.discriminator.keys())[0] - if is_type_nullable(cls): - possible_classes.append(cls) - for discr_cls in cls.discriminator[key].values(): - if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: - possible_classes.extend(get_discriminated_classes(discr_cls)) - else: - possible_classes.append(discr_cls) - return possible_classes - - -def get_possible_classes(cls, from_server_context): - # TODO: lru_cache this - possible_classes = [cls] - if from_server_context: - return possible_classes - if hasattr(cls, 'discriminator') and cls.discriminator is not None: - possible_classes = [] - possible_classes.extend(get_discriminated_classes(cls)) - elif issubclass(cls, ModelComposed): - possible_classes.extend(composed_model_input_classes(cls)) - return possible_classes - - -def get_required_type_classes(required_types_mixed, spec_property_naming): - """Converts the tuple required_types into a tuple and a dict described - below - - Args: - required_types_mixed (tuple/list): will contain either classes or - instance of list or dict - spec_property_naming (bool): if True these values came from the - server, and we use the data types in our endpoints. - If False, we are client side and we need to include - oneOf and discriminator classes inside the data types in our endpoints - - Returns: - (valid_classes, dict_valid_class_to_child_types_mixed): - valid_classes (tuple): the valid classes that the current item - should be - dict_valid_class_to_child_types_mixed (dict): - valid_class (class): this is the key - child_types_mixed (list/dict/tuple): describes the valid child - types - """ - valid_classes = [] - child_req_types_by_current_type = {} - for required_type in required_types_mixed: - if isinstance(required_type, list): - valid_classes.append(list) - child_req_types_by_current_type[list] = required_type - elif isinstance(required_type, tuple): - valid_classes.append(tuple) - child_req_types_by_current_type[tuple] = required_type - elif isinstance(required_type, dict): - valid_classes.append(dict) - child_req_types_by_current_type[dict] = required_type[str] - else: - valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) - return tuple(valid_classes), child_req_types_by_current_type - - -def change_keys_js_to_python(input_dict, model_class): - """ - Converts from javascript_key keys in the input_dict to python_keys in - the output dict using the mapping in model_class. - If the input_dict contains a key which does not declared in the model_class, - the key is added to the output dict as is. The assumption is the model_class - may have undeclared properties (additionalProperties attribute in the OAS - document). - """ - - if getattr(model_class, 'attribute_map', None) is None: - return input_dict - output_dict = {} - reversed_attr_map = {value: key for key, value in - model_class.attribute_map.items()} - for javascript_key, value in input_dict.items(): - python_key = reversed_attr_map.get(javascript_key) - if python_key is None: - # if the key is unknown, it is in error or it is an - # additionalProperties variable - python_key = javascript_key - output_dict[python_key] = value - return output_dict - - -def get_type_error(var_value, path_to_item, valid_classes, key_type=False): - error_msg = type_error_message( - var_name=path_to_item[-1], - var_value=var_value, - valid_classes=valid_classes, - key_type=key_type - ) - return ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=valid_classes, - key_type=key_type - ) - - -def deserialize_primitive(data, klass, path_to_item): - """Deserializes string to primitive type. - - :param data: str/int/float - :param klass: str/class the class to convert to - - :return: int, float, str, bool, date, datetime - """ - additional_message = "" - try: - if klass in {datetime, date}: - additional_message = ( - "If you need your parameter to have a fallback " - "string value, please set its type as `type: {}` in your " - "spec. That allows the value to be any type. " - ) - if klass == datetime: - if len(data) < 8: - raise ValueError("This is not a datetime") - # The string should be in iso8601 datetime format. - parsed_datetime = parse(data) - date_only = ( - parsed_datetime.hour == 0 and - parsed_datetime.minute == 0 and - parsed_datetime.second == 0 and - parsed_datetime.tzinfo is None and - 8 <= len(data) <= 10 - ) - if date_only: - raise ValueError("This is a date, not a datetime") - return parsed_datetime - elif klass == date: - if len(data) < 8: - raise ValueError("This is not a date") - return parse(data).date() - else: - converted_value = klass(data) - if isinstance(data, str) and klass == float: - if str(converted_value) != data: - # '7' -> 7.0 -> '7.0' != '7' - raise ValueError('This is not a float') - return converted_value - except (OverflowError, ValueError) as ex: - # parse can raise OverflowError - raise ApiValueError( - "{0}Failed to parse {1} as {2}".format( - additional_message, repr(data), klass.__name__ - ), - path_to_item=path_to_item - ) from ex - - -def get_discriminator_class(model_class, - discr_name, - discr_value, cls_visited): - """Returns the child class specified by the discriminator. - - Args: - model_class (OpenApiModel): the model class. - discr_name (string): the name of the discriminator property. - discr_value (any): the discriminator value. - cls_visited (list): list of model classes that have been visited. - Used to determine the discriminator class without - visiting circular references indefinitely. - - Returns: - used_model_class (class/None): the chosen child class that will be used - to deserialize the data, for example dog.Dog. - If a class is not found, None is returned. - """ - - if model_class in cls_visited: - # The class has already been visited and no suitable class was found. - return None - cls_visited.append(model_class) - used_model_class = None - if discr_name in model_class.discriminator: - class_name_to_discr_class = model_class.discriminator[discr_name] - used_model_class = class_name_to_discr_class.get(discr_value) - if used_model_class is None: - # We didn't find a discriminated class in class_name_to_discr_class. - # So look in the ancestor or descendant discriminators - # The discriminator mapping may exist in a descendant (anyOf, oneOf) - # or ancestor (allOf). - # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat - # hierarchy, the discriminator mappings may be defined at any level - # in the hierarchy. - # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig - # if we try to make BasquePig from mammal, we need to travel through - # the oneOf descendant discriminators to find BasquePig - descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ - model_class._composed_schemas.get('anyOf', ()) - ancestor_classes = model_class._composed_schemas.get('allOf', ()) - possible_classes = descendant_classes + ancestor_classes - for cls in possible_classes: - # Check if the schema has inherited discriminators. - if hasattr(cls, 'discriminator') and cls.discriminator is not None: - used_model_class = get_discriminator_class( - cls, discr_name, discr_value, cls_visited) - if used_model_class is not None: - return used_model_class - return used_model_class - - -def deserialize_model(model_data, model_class, path_to_item, check_type, - configuration, spec_property_naming): - """Deserializes model_data to model instance. - - Args: - model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model - model_class (OpenApiModel): the model class - path_to_item (list): path to the model in the received data - check_type (bool): whether to check the data tupe for the values in - the model - configuration (Configuration): the instance to use to convert files - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - - Returns: - model instance - - Raise: - ApiTypeError - ApiValueError - ApiKeyError - """ - - kw_args = dict(_check_type=check_type, - _path_to_item=path_to_item, - _configuration=configuration, - _spec_property_naming=spec_property_naming) - - if issubclass(model_class, ModelSimple): - return model_class._new_from_openapi_data(model_data, **kw_args) - elif isinstance(model_data, list): - return model_class._new_from_openapi_data(*model_data, **kw_args) - if isinstance(model_data, dict): - kw_args.update(model_data) - return model_class._new_from_openapi_data(**kw_args) - elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class._new_from_openapi_data(model_data, **kw_args) - - -def deserialize_file(response_data, configuration, content_disposition=None): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - Args: - param response_data (str): the file data to write - configuration (Configuration): the instance to use to convert files - - Keyword Args: - content_disposition (str): the value of the Content-Disposition - header - - Returns: - (file_type): the deserialized file which is open - The user is responsible for closing and reading the file - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition, - flags=re.I) - if filename is not None: - filename = filename.group(1) - else: - filename = "default_" + str(uuid.uuid4()) - - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - if isinstance(response_data, str): - # change str to bytes so we can write it - response_data = response_data.encode('utf-8') - f.write(response_data) - - f = open(path, "rb") - return f - - -def attempt_convert_item(input_value, valid_classes, path_to_item, - configuration, spec_property_naming, key_type=False, - must_convert=False, check_type=True): - """ - Args: - input_value (any): the data to convert - valid_classes (any): the classes that are valid - path_to_item (list): the path to the item to convert - configuration (Configuration): the instance to use to convert files - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - key_type (bool): if True we need to convert a key type (not supported) - must_convert (bool): if True we must convert - check_type (bool): if True we check the type or the returned data in - ModelComposed/ModelNormal/ModelSimple instances - - Returns: - instance (any) the fixed item - - Raises: - ApiTypeError - ApiValueError - ApiKeyError - """ - valid_classes_ordered = order_response_types(valid_classes) - valid_classes_coercible = remove_uncoercible( - valid_classes_ordered, input_value, spec_property_naming) - if not valid_classes_coercible or key_type: - # we do not handle keytype errors, json will take care - # of this for us - if configuration is None or not configuration.discard_unknown_keys: - raise get_type_error(input_value, path_to_item, valid_classes, - key_type=key_type) - for valid_class in valid_classes_coercible: - try: - if issubclass(valid_class, OpenApiModel): - return deserialize_model(input_value, valid_class, - path_to_item, check_type, - configuration, spec_property_naming) - elif valid_class == file_type: - return deserialize_file(input_value, configuration) - return deserialize_primitive(input_value, valid_class, - path_to_item) - except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: - if must_convert: - raise conversion_exc - # if we have conversion errors when must_convert == False - # we ignore the exception and move on to the next class - continue - # we were unable to convert, must_convert == False - return input_value - - -def is_type_nullable(input_type): - """ - Returns true if None is an allowed value for the specified input_type. - - A type is nullable if at least one of the following conditions is true: - 1. The OAS 'nullable' attribute has been specified, - 1. The type is the 'null' type, - 1. The type is a anyOf/oneOf composed schema, and a child schema is - the 'null' type. - Args: - input_type (type): the class of the input_value that we are - checking - Returns: - bool - """ - if input_type is none_type: - return True - if issubclass(input_type, OpenApiModel) and input_type._nullable: - return True - if issubclass(input_type, ModelComposed): - # If oneOf/anyOf, check if the 'null' type is one of the allowed types. - for t in input_type._composed_schemas.get('oneOf', ()): - if is_type_nullable(t): - return True - for t in input_type._composed_schemas.get('anyOf', ()): - if is_type_nullable(t): - return True - return False - - -def is_valid_type(input_class_simple, valid_classes): - """ - Args: - input_class_simple (class): the class of the input_value that we are - checking - valid_classes (tuple): the valid classes that the current item - should be - Returns: - bool - """ - if issubclass(input_class_simple, OpenApiModel) and \ - valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,): - return True - valid_type = input_class_simple in valid_classes - if not valid_type and ( - issubclass(input_class_simple, OpenApiModel) or - input_class_simple is none_type): - for valid_class in valid_classes: - if input_class_simple is none_type and is_type_nullable(valid_class): - # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. - return True - if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): - continue - discr_propertyname_py = list(valid_class.discriminator.keys())[0] - discriminator_classes = ( - valid_class.discriminator[discr_propertyname_py].values() - ) - valid_type = is_valid_type(input_class_simple, discriminator_classes) - if valid_type: - return True - return valid_type - - -def validate_and_convert_types(input_value, required_types_mixed, path_to_item, - spec_property_naming, _check_type, configuration=None): - """Raises a TypeError is there is a problem, otherwise returns value - - Args: - input_value (any): the data to validate/convert - required_types_mixed (list/dict/tuple): A list of - valid classes, or a list tuples of valid classes, or a dict where - the value is a tuple of value classes - path_to_item: (list) the path to the data being validated - this stores a list of keys or indices to get to the data being - validated - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - _check_type: (boolean) if true, type will be checked and conversion - will be attempted. - configuration: (Configuration): the configuration class to use - when converting file_type items. - If passed, conversion will be attempted when possible - If not passed, no conversions will be attempted and - exceptions will be raised - - Returns: - the correctly typed value - - Raises: - ApiTypeError - """ - results = get_required_type_classes(required_types_mixed, spec_property_naming) - valid_classes, child_req_types_by_current_type = results - - input_class_simple = get_simple_class(input_value) - valid_type = is_valid_type(input_class_simple, valid_classes) - if not valid_type: - if (configuration - or (input_class_simple == dict - and dict not in valid_classes)): - # if input_value is not valid_type try to convert it - converted_instance = attempt_convert_item( - input_value, - valid_classes, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=True, - check_type=_check_type - ) - return converted_instance - else: - raise get_type_error(input_value, path_to_item, valid_classes, - key_type=False) - - # input_value's type is in valid_classes - if len(valid_classes) > 1 and configuration: - # there are valid classes which are not the current class - valid_classes_coercible = remove_uncoercible( - valid_classes, input_value, spec_property_naming, must_convert=False) - if valid_classes_coercible: - converted_instance = attempt_convert_item( - input_value, - valid_classes_coercible, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=False, - check_type=_check_type - ) - return converted_instance - - if child_req_types_by_current_type == {}: - # all types are of the required types and there are no more inner - # variables left to look at - return input_value - inner_required_types = child_req_types_by_current_type.get( - type(input_value) - ) - if inner_required_types is None: - # for this type, there are not more inner variables left to look at - return input_value - if isinstance(input_value, list): - if input_value == []: - # allow an empty list - return input_value - for index, inner_value in enumerate(input_value): - inner_path = list(path_to_item) - inner_path.append(index) - input_value[index] = validate_and_convert_types( - inner_value, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration - ) - elif isinstance(input_value, dict): - if input_value == {}: - # allow an empty dict - return input_value - for inner_key, inner_val in input_value.items(): - inner_path = list(path_to_item) - inner_path.append(inner_key) - if get_simple_class(inner_key) != str: - raise get_type_error(inner_key, inner_path, valid_classes, - key_type=True) - input_value[inner_key] = validate_and_convert_types( - inner_val, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration - ) - return input_value - - -def model_to_dict(model_instance, serialize=True): - """Returns the model properties as a dict - - Args: - model_instance (one of your model instances): the model instance that - will be converted to a dict. - - Keyword Args: - serialize (bool): if True, the keys in the dict will be values from - attribute_map - """ - result = {} - - def extract_item(item): return ( - item[0], model_to_dict( - item[1], serialize=serialize)) if hasattr( - item[1], '_data_store') else item - - model_instances = [model_instance] - if model_instance._composed_schemas: - model_instances.extend(model_instance._composed_instances) - seen_json_attribute_names = set() - used_fallback_python_attribute_names = set() - py_to_json_map = {} - for model_instance in model_instances: - for attr, value in model_instance._data_store.items(): - if serialize: - # we use get here because additional property key names do not - # exist in attribute_map - try: - attr = model_instance.attribute_map[attr] - py_to_json_map.update(model_instance.attribute_map) - seen_json_attribute_names.add(attr) - except KeyError: - used_fallback_python_attribute_names.add(attr) - if isinstance(value, list): - if not value: - # empty list or None - result[attr] = value - else: - res = [] - for v in value: - if isinstance(v, PRIMITIVE_TYPES) or v is None: - res.append(v) - elif isinstance(v, ModelSimple): - res.append(v.value) - elif isinstance(v, dict): - res.append(dict(map( - extract_item, - v.items() - ))) - else: - res.append(model_to_dict(v, serialize=serialize)) - result[attr] = res - elif isinstance(value, dict): - result[attr] = dict(map( - extract_item, - value.items() - )) - elif isinstance(value, ModelSimple): - result[attr] = value.value - elif hasattr(value, '_data_store'): - result[attr] = model_to_dict(value, serialize=serialize) - else: - result[attr] = value - if serialize: - for python_key in used_fallback_python_attribute_names: - json_key = py_to_json_map.get(python_key) - if json_key is None: - continue - if python_key == json_key: - continue - json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names - if json_key_assigned_no_need_for_python_key: - del result[python_key] - - return result - - -def type_error_message(var_value=None, var_name=None, valid_classes=None, - key_type=None): - """ - Keyword Args: - var_value (any): the variable which has the type_error - var_name (str): the name of the variable which has the typ error - valid_classes (tuple): the accepted classes for current_item's - value - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - """ - key_or_value = 'value' - if key_type: - key_or_value = 'key' - valid_classes_phrase = get_valid_classes_phrase(valid_classes) - msg = ( - "Invalid type for variable '{0}'. Required {1} type {2} and " - "passed type was {3}".format( - var_name, - key_or_value, - valid_classes_phrase, - type(var_value).__name__, - ) - ) - return msg - - -def get_valid_classes_phrase(input_classes): - """Returns a string phrase describing what types are allowed - """ - all_classes = list(input_classes) - all_classes = sorted(all_classes, key=lambda cls: cls.__name__) - all_class_names = [cls.__name__ for cls in all_classes] - if len(all_class_names) == 1: - return 'is {0}'.format(all_class_names[0]) - return "is one of [{0}]".format(", ".join(all_class_names)) - - -def get_allof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - used to make instances - constant_args (dict): - metadata arguments: - _check_type - _path_to_item - _spec_property_naming - _configuration - _visited_composed_classes - - Returns - composed_instances (list) - """ - composed_instances = [] - for allof_class in self._composed_schemas['allOf']: - - try: - if constant_args.get('_spec_property_naming'): - allof_instance = allof_class._from_openapi_data(**model_args, **constant_args) - else: - allof_instance = allof_class(**model_args, **constant_args) - composed_instances.append(allof_instance) - except Exception as ex: - raise ApiValueError( - "Invalid inputs given to generate an instance of '%s'. The " - "input data was invalid for the allOf schema '%s' in the composed " - "schema '%s'. Error=%s" % ( - allof_class.__name__, - allof_class.__name__, - self.__class__.__name__, - str(ex) - ) - ) from ex - return composed_instances - - -def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): - """ - Find the oneOf schema that matches the input data (e.g. payload). - If exactly one schema matches the input data, an instance of that schema - is returned. - If zero or more than one schema match the input data, an exception is raised. - In OAS 3.x, the payload MUST, by validation, match exactly one of the - schemas described by oneOf. - - Args: - cls: the class we are handling - model_kwargs (dict): var_name to var_value - The input data, e.g. the payload that must match a oneOf schema - in the OpenAPI document. - constant_kwargs (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Kwargs: - model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): - the value to assign to a primitive class or ModelSimple class - Notes: - - this is only passed in when oneOf includes types which are not object - - None is used to suppress handling of model_arg, nullable models are handled in __new__ - - Returns - oneof_instance (instance) - """ - if len(cls._composed_schemas['oneOf']) == 0: - return None - - oneof_instances = [] - # Iterate over each oneOf schema and determine if the input data - # matches the oneOf schemas. - for oneof_class in cls._composed_schemas['oneOf']: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if oneof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - single_value_input = allows_single_value_input(oneof_class) - - try: - if not single_value_input: - if constant_kwargs.get('_spec_property_naming'): - oneof_instance = oneof_class._from_openapi_data( - **model_kwargs, **constant_kwargs) - else: - oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) - else: - if issubclass(oneof_class, ModelSimple): - if constant_kwargs.get('_spec_property_naming'): - oneof_instance = oneof_class._from_openapi_data( - model_arg, **constant_kwargs) - else: - oneof_instance = oneof_class(model_arg, **constant_kwargs) - elif oneof_class in PRIMITIVE_TYPES: - oneof_instance = validate_and_convert_types( - model_arg, - (oneof_class,), - constant_kwargs['_path_to_item'], - constant_kwargs['_spec_property_naming'], - constant_kwargs['_check_type'], - configuration=constant_kwargs['_configuration'] - ) - oneof_instances.append(oneof_instance) - except Exception: - pass - if len(oneof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None " - "of the oneOf schemas matched the input data." % - cls.__name__ - ) - elif len(oneof_instances) > 1: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. Multiple " - "oneOf schemas matched the inputs, but a max of one is allowed." % - cls.__name__ - ) - return oneof_instances[0] - - -def get_anyof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - The input data, e.g. the payload that must match at least one - anyOf child schema in the OpenAPI document. - constant_args (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Returns - anyof_instances (list) - """ - anyof_instances = [] - if len(self._composed_schemas['anyOf']) == 0: - return anyof_instances - - for anyof_class in self._composed_schemas['anyOf']: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if anyof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - try: - if constant_args.get('_spec_property_naming'): - anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args) - else: - anyof_instance = anyof_class(**model_args, **constant_args) - anyof_instances.append(anyof_instance) - except Exception: - pass - if len(anyof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None of the " - "anyOf schemas matched the inputs." % - self.__class__.__name__ - ) - return anyof_instances - - -def get_discarded_args(self, composed_instances, model_args): - """ - Gathers the args that were discarded by configuration.discard_unknown_keys - """ - model_arg_keys = model_args.keys() - discarded_args = set() - # arguments passed to self were already converted to python names - # before __init__ was called - for instance in composed_instances: - if instance.__class__ in self._composed_schemas['allOf']: - try: - keys = instance.to_dict().keys() - discarded_keys = model_args - keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - else: - try: - all_keys = set(model_to_dict(instance, serialize=False).keys()) - js_keys = model_to_dict(instance, serialize=True).keys() - all_keys.update(js_keys) - discarded_keys = model_arg_keys - all_keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - return discarded_args - - -def validate_get_composed_info(constant_args, model_args, self): - """ - For composed schemas, generate schema instances for - all schemas in the oneOf/anyOf/allOf definition. If additional - properties are allowed, also assign those properties on - all matched schemas that contain additionalProperties. - Openapi schemas are python classes. - - Exceptions are raised if: - - 0 or > 1 oneOf schema matches the model_args input data - - no anyOf schema matches the model_args input data - - any of the allOf schemas do not match the model_args input data - - Args: - constant_args (dict): these are the args that every model requires - model_args (dict): these are the required and optional spec args that - were passed in to make this model - self (class): the class that we are instantiating - This class contains self._composed_schemas - - Returns: - composed_info (list): length three - composed_instances (list): the composed instances which are not - self - var_name_to_model_instances (dict): a dict going from var_name - to the model_instance which holds that var_name - the model_instance may be self or an instance of one of the - classes in self.composed_instances() - additional_properties_model_instances (list): a list of the - model instances which have the property - additional_properties_type. This list can include self - """ - # create composed_instances - composed_instances = [] - allof_instances = get_allof_instances(self, model_args, constant_args) - composed_instances.extend(allof_instances) - oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) - if oneof_instance is not None: - composed_instances.append(oneof_instance) - anyof_instances = get_anyof_instances(self, model_args, constant_args) - composed_instances.extend(anyof_instances) - """ - set additional_properties_model_instances - additional properties must be evaluated at the schema level - so self's additional properties are most important - If self is a composed schema with: - - no properties defined in self - - additionalProperties: False - Then for object payloads every property is an additional property - and they are not allowed, so only empty dict is allowed - - Properties must be set on all matching schemas - so when a property is assigned toa composed instance, it must be set on all - composed instances regardless of additionalProperties presence - keeping it to prevent breaking changes in v5.0.1 - TODO remove cls._additional_properties_model_instances in 6.0.0 - """ - additional_properties_model_instances = [] - if self.additional_properties_type is not None: - additional_properties_model_instances = [self] - - """ - no need to set properties on self in here, they will be set in __init__ - By here all composed schema oneOf/anyOf/allOf instances have their properties set using - model_args - """ - discarded_args = get_discarded_args(self, composed_instances, model_args) - - # map variable names to composed_instances - var_name_to_model_instances = {} - for prop_name in model_args: - if prop_name not in discarded_args: - var_name_to_model_instances[prop_name] = [self] + list( - filter( - lambda x: prop_name in x.openapi_types, composed_instances)) - - return [ - composed_instances, - var_name_to_model_instances, - additional_properties_model_instances, - discarded_args - ] diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/README.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/README.md deleted file mode 100644 index 4b34d32b61..0000000000 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/README.md +++ /dev/null @@ -1,254 +0,0 @@ -# petstore-api -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - -This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: 1.0.0 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.PythonClientCodegen - -## Requirements. - -Python >=3.6 - -## Installation & Usage -### pip install - -If the python package is hosted on a repository, you can install directly using: - -```sh -pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git -``` -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) - -Then import the package: -```python -import petstore_api -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: -```python -import petstore_api -``` - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```python - -import time -import petstore_api -from pprint import pprint -from petstore_api.api import another_fake_api -from petstore_api.model.client import Client -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = another_fake_api.AnotherFakeApi(api_client) - body = Client( - client="client_example", - ) # Client | client model - - try: - # To test special tags - api_response = api_instance.call_123_test_special_tags(body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags -*FakeApi* | [**array_model**](docs/FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | -*FakeApi* | [**boolean**](docs/FakeApi.md#boolean) | **POST** /fake/refs/boolean | -*FakeApi* | [**create_xml_item**](docs/FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem -*FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | -*FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | -*FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | -*FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | -*FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | -*FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | -*FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model -*FakeApi* | [**test_endpoint_enums_length_one**](docs/FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | -*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -*FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data -*FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case -*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet -*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image -*PetApi* | [**upload_file_with_required_file**](docs/PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet -*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user -*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user -*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name -*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system -*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user - - -## Documentation For Models - - - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) - - [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) - - [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) - - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - - [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) - - [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) - - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) - - [AdditionalPropertiesString](docs/AdditionalPropertiesString.md) - - [Animal](docs/Animal.md) - - [AnimalFarm](docs/AnimalFarm.md) - - [ApiResponse](docs/ApiResponse.md) - - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - - [ArrayTest](docs/ArrayTest.md) - - [Capitalization](docs/Capitalization.md) - - [Cat](docs/Cat.md) - - [CatAllOf](docs/CatAllOf.md) - - [Category](docs/Category.md) - - [Child](docs/Child.md) - - [ChildAllOf](docs/ChildAllOf.md) - - [ChildCat](docs/ChildCat.md) - - [ChildCatAllOf](docs/ChildCatAllOf.md) - - [ChildDog](docs/ChildDog.md) - - [ChildDogAllOf](docs/ChildDogAllOf.md) - - [ChildLizard](docs/ChildLizard.md) - - [ChildLizardAllOf](docs/ChildLizardAllOf.md) - - [ClassModel](docs/ClassModel.md) - - [Client](docs/Client.md) - - [Dog](docs/Dog.md) - - [DogAllOf](docs/DogAllOf.md) - - [EnumArrays](docs/EnumArrays.md) - - [EnumClass](docs/EnumClass.md) - - [EnumTest](docs/EnumTest.md) - - [File](docs/File.md) - - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - - [FormatTest](docs/FormatTest.md) - - [Grandparent](docs/Grandparent.md) - - [GrandparentAnimal](docs/GrandparentAnimal.md) - - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - - [List](docs/List.md) - - [MapTest](docs/MapTest.md) - - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - - [Model200Response](docs/Model200Response.md) - - [ModelReturn](docs/ModelReturn.md) - - [Name](docs/Name.md) - - [NumberOnly](docs/NumberOnly.md) - - [NumberWithValidations](docs/NumberWithValidations.md) - - [ObjectModelWithRefProps](docs/ObjectModelWithRefProps.md) - - [Order](docs/Order.md) - - [Parent](docs/Parent.md) - - [ParentAllOf](docs/ParentAllOf.md) - - [ParentPet](docs/ParentPet.md) - - [Pet](docs/Pet.md) - - [Player](docs/Player.md) - - [Polygon](docs/Polygon.md) - - [PolygonAllOf](docs/PolygonAllOf.md) - - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - - [Shape](docs/Shape.md) - - [SpecialModelName](docs/SpecialModelName.md) - - [Square](docs/Square.md) - - [SquareAllOf](docs/SquareAllOf.md) - - [StringBooleanMap](docs/StringBooleanMap.md) - - [StringEnum](docs/StringEnum.md) - - [Tag](docs/Tag.md) - - [Triangle](docs/Triangle.md) - - [TriangleAllOf](docs/TriangleAllOf.md) - - [TypeHolderDefault](docs/TypeHolderDefault.md) - - [TypeHolderExample](docs/TypeHolderExample.md) - - [User](docs/User.md) - - [XmlItem](docs/XmlItem.md) - - -## Documentation For Authorization - - -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - - -## api_key_query - -- **Type**: API key -- **API key parameter name**: api_key_query -- **Location**: URL query string - - -## http_basic_test - -- **Type**: HTTP basic authentication - - -## petstore_auth - -- **Type**: OAuth -- **Flow**: implicit -- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog -- **Scopes**: - - **write:pets**: modify pets in your account - - **read:pets**: read your pets - - -## Author - - - - -## Notes for Large OpenAPI documents -If the OpenAPI document is large, imports in petstore_api.apis and petstore_api.models may fail with a -RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: - -Solution 1: -Use specific imports for apis and models like: -- `from petstore_api.api.default_api import DefaultApi` -- `from petstore_api.model.pet import Pet` - -Solution 2: -Before importing the package, adjust the maximum recursion limit as shown below: -``` -import sys -sys.setrecursionlimit(1500) -import petstore_api -from petstore_api.apis import * -from petstore_api.models import * -``` - diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeApi.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeApi.md deleted file mode 100644 index c52fe144ab..0000000000 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeApi.md +++ /dev/null @@ -1,1239 +0,0 @@ -# petstore_api.FakeApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**array_model**](FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | -[**boolean**](FakeApi.md#boolean) | **POST** /fake/refs/boolean | -[**create_xml_item**](FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem -[**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | -[**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | -[**string**](FakeApi.md#string) | **POST** /fake/refs/string | -[**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | -[**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | -[**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | -[**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model -[**test_endpoint_enums_length_one**](FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | -[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -[**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -[**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data - - -# **array_model** -> AnimalFarm array_model() - - - -Test serialization of ArrayModel - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.animal_farm import AnimalFarm -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = AnimalFarm([ - Animal(), - ]) # AnimalFarm | Input model (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.array_model(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->array_model: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**AnimalFarm**](AnimalFarm.md)| Input model | [optional] - -### Return type - -[**AnimalFarm**](AnimalFarm.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output model | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **boolean** -> bool boolean() - - - -Test serialization of outer boolean types - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = True # bool | Input boolean as post body (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.boolean(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->boolean: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **bool**| Input boolean as post body | [optional] - -### Return type - -**bool** - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output boolean | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_xml_item** -> create_xml_item(xml_item) - -creates an XmlItem - -this route creates an XmlItem - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.xml_item import XmlItem -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - xml_item = XmlItem( - attribute_string="string", - attribute_number=1.234, - attribute_integer=-2, - attribute_boolean=True, - wrapped_array=[ - 1, - ], - name_string="string", - name_number=1.234, - name_integer=-2, - name_boolean=True, - name_array=[ - 1, - ], - name_wrapped_array=[ - 1, - ], - prefix_string="string", - prefix_number=1.234, - prefix_integer=-2, - prefix_boolean=True, - prefix_array=[ - 1, - ], - prefix_wrapped_array=[ - 1, - ], - namespace_string="string", - namespace_number=1.234, - namespace_integer=-2, - namespace_boolean=True, - namespace_array=[ - 1, - ], - namespace_wrapped_array=[ - 1, - ], - prefix_ns_string="string", - prefix_ns_number=1.234, - prefix_ns_integer=-2, - prefix_ns_boolean=True, - prefix_ns_array=[ - 1, - ], - prefix_ns_wrapped_array=[ - 1, - ], - ) # XmlItem | XmlItem Body - - # example passing only required values which don't have defaults set - try: - # creates an XmlItem - api_instance.create_xml_item(xml_item) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->create_xml_item: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **xml_item** | [**XmlItem**](XmlItem.md)| XmlItem Body | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/xml, application/xml; charset=utf-8, application/xml; charset=utf-16, text/xml, text/xml; charset=utf-8, text/xml; charset=utf-16 - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **number_with_validations** -> NumberWithValidations number_with_validations() - - - -Test serialization of outer number types - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.number_with_validations import NumberWithValidations -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = NumberWithValidations(1E+1) # NumberWithValidations | Input number as post body (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.number_with_validations(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->number_with_validations: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**NumberWithValidations**](NumberWithValidations.md)| Input number as post body | [optional] - -### Return type - -[**NumberWithValidations**](NumberWithValidations.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output number | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **object_model_with_ref_props** -> ObjectModelWithRefProps object_model_with_ref_props() - - - -Test serialization of object with $refed properties - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = ObjectModelWithRefProps( - my_number=NumberWithValidations(1E+1), - my_string="my_string_example", - my_boolean=True, - ) # ObjectModelWithRefProps | Input model (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.object_model_with_ref_props(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**ObjectModelWithRefProps**](ObjectModelWithRefProps.md)| Input model | [optional] - -### Return type - -[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output model | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **string** -> str string() - - - -Test serialization of outer string types - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = "body_example" # str | Input string as post body (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.string(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->string: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **str**| Input string as post body | [optional] - -### Return type - -**str** - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output string | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **string_enum** -> StringEnum string_enum() - - - -Test serialization of outer enum - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.string_enum import StringEnum -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = StringEnum("placed") # StringEnum | Input enum (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.string_enum(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->string_enum: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**StringEnum**](StringEnum.md)| Input enum | [optional] - -### Return type - -[**StringEnum**](StringEnum.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: */* - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output enum | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_body_with_file_schema** -> test_body_with_file_schema(body) - - - -For this test, the body for this request much reference a schema named `File`. - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.file_schema_test_class import FileSchemaTestClass -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = FileSchemaTestClass( - file=File( - source_uri="source_uri_example", - ), - files=[ - File( - source_uri="source_uri_example", - ), - ], - ) # FileSchemaTestClass | - - # example passing only required values which don't have defaults set - try: - api_instance.test_body_with_file_schema(body) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_body_with_file_schema: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_body_with_query_params** -> test_body_with_query_params(query, body) - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.user import User -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - query = "query_example" # str | - body = User( - id=1, - username="username_example", - first_name="first_name_example", - last_name="last_name_example", - email="email_example", - password="password_example", - phone="phone_example", - user_status=1, - ) # User | - - # example passing only required values which don't have defaults set - try: - api_instance.test_body_with_query_params(query, body) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_body_with_query_params: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **query** | **str**| | - **body** | [**User**](User.md)| | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_client_model** -> Client test_client_model(body) - -To test \"client\" model - -To test \"client\" model - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.client import Client -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = Client( - client="client_example", - ) # Client | client model - - # example passing only required values which don't have defaults set - try: - # To test \"client\" model - api_response = api_instance.test_client_model(body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_client_model: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | - -### Return type - -[**Client**](Client.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_endpoint_enums_length_one** -> test_endpoint_enums_length_one() - - - -This route has required values with enums of 1 - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - try: - api_instance.test_endpoint_enums_length_one() - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_endpoint_enums_length_one: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **query_integer** | **int**| | defaults to 3 - **query_string** | **str**| | defaults to "brillig" - **path_string** | **str**| | defaults to "hello" - **path_integer** | **int**| | defaults to 34 - **header_number** | **float**| | defaults to 1.234 - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_endpoint_parameters** -> test_endpoint_parameters(number, double, pattern_without_delimiter, byte) - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -### Example - -* Basic Authentication (http_basic_test): - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure HTTP basic authorization: http_basic_test -configuration = petstore_api.Configuration( - username = 'YOUR_USERNAME', - password = 'YOUR_PASSWORD' -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - number = 32.1 # float | None - double = 67.8 # float | None - pattern_without_delimiter = "Aj" # str | None - byte = 'YQ==' # str | None - integer = 10 # int | None (optional) - int32 = 20 # int | None (optional) - int64 = 1 # int | None (optional) - float = 3.14 # float | None (optional) - string = "A" # str | None (optional) - binary = open('/path/to/file', 'rb') # file_type | None (optional) - date = dateutil_parser('1970-01-01').date() # date | None (optional) - date_time = dateutil_parser('1970-01-01T00:00:00.00Z') # datetime | None (optional) - password = "password_example" # str | None (optional) - param_callback = "param_callback_example" # str | None (optional) - - # example passing only required values which don't have defaults set - try: - # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) - - # example passing only required values which don't have defaults set - # and optional values - try: - # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **number** | **float**| None | - **double** | **float**| None | - **pattern_without_delimiter** | **str**| None | - **byte** | **str**| None | - **integer** | **int**| None | [optional] - **int32** | **int**| None | [optional] - **int64** | **int**| None | [optional] - **float** | **float**| None | [optional] - **string** | **str**| None | [optional] - **binary** | **file_type**| None | [optional] - **date** | **date**| None | [optional] - **date_time** | **datetime**| None | [optional] - **password** | **str**| None | [optional] - **param_callback** | **str**| None | [optional] - -### Return type - -void (empty response body) - -### Authorization - -[http_basic_test](../README.md#http_basic_test) - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**400** | Invalid username supplied | - | -**404** | User not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_enum_parameters** -> test_enum_parameters() - -To test enum parameters - -To test enum parameters - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - enum_header_string_array = [ - "$", - ] # [str] | Header parameter enum test (string array) (optional) - enum_header_string = "-efg" # str | Header parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" - enum_query_string_array = [ - "$", - ] # [str] | Query parameter enum test (string array) (optional) - enum_query_string = "-efg" # str | Query parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" - enum_query_integer = 1 # int | Query parameter enum test (double) (optional) - enum_query_double = 1.1 # float | Query parameter enum test (double) (optional) - enum_form_string_array = [ - "$", - ] # [str] | Form parameter enum test (string array) (optional) if omitted the server will use the default value of "$" - enum_form_string = "-efg" # str | Form parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" - - # example passing only required values which don't have defaults set - # and optional values - try: - # To test enum parameters - api_instance.test_enum_parameters(enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double, enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **enum_header_string_array** | **[str]**| Header parameter enum test (string array) | [optional] - **enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" - **enum_query_string_array** | **[str]**| Query parameter enum test (string array) | [optional] - **enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" - **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] - **enum_query_double** | **float**| Query parameter enum test (double) | [optional] - **enum_form_string_array** | **[str]**| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of "$" - **enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**400** | Invalid request | - | -**404** | Not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_group_parameters** -> test_group_parameters(required_string_group, required_boolean_group, required_int64_group) - -Fake endpoint to test group parameters (optional) - -Fake endpoint to test group parameters (optional) - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - required_string_group = 1 # int | Required String in group parameters - required_boolean_group = True # bool | Required Boolean in group parameters - required_int64_group = 1 # int | Required Integer in group parameters - string_group = 1 # int | String in group parameters (optional) - boolean_group = True # bool | Boolean in group parameters (optional) - int64_group = 1 # int | Integer in group parameters (optional) - - # example passing only required values which don't have defaults set - try: - # Fake endpoint to test group parameters (optional) - api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) - - # example passing only required values which don't have defaults set - # and optional values - try: - # Fake endpoint to test group parameters (optional) - api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **required_string_group** | **int**| Required String in group parameters | - **required_boolean_group** | **bool**| Required Boolean in group parameters | - **required_int64_group** | **int**| Required Integer in group parameters | - **string_group** | **int**| String in group parameters | [optional] - **boolean_group** | **bool**| Boolean in group parameters | [optional] - **int64_group** | **int**| Integer in group parameters | [optional] - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**400** | Someting wrong | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_inline_additional_properties** -> test_inline_additional_properties(param) - -test inline additionalProperties - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - param = { - "key": "key_example", - } # {str: (str,)} | request body - - # example passing only required values which don't have defaults set - try: - # test inline additionalProperties - api_instance.test_inline_additional_properties(param) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **param** | **{str: (str,)}**| request body | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_json_form_data** -> test_json_form_data(param, param2) - -test json serialization of form data - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - param = "param_example" # str | field1 - param2 = "param2_example" # str | field2 - - # example passing only required values which don't have defaults set - try: - # test json serialization of form data - api_instance.test_json_form_data(param, param2) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_json_form_data: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **param** | **str**| field1 | - **param2** | **str**| field2 | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py deleted file mode 100644 index 933ceec6fa..0000000000 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py +++ /dev/null @@ -1,2058 +0,0 @@ -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from datetime import date, datetime # noqa: F401 -from copy import deepcopy -import inspect -import io -import os -import pprint -import re -import tempfile -import uuid - -from dateutil.parser import parse - -from petstore_api.exceptions import ( - ApiKeyError, - ApiAttributeError, - ApiTypeError, - ApiValueError, -) - -none_type = type(None) -file_type = io.IOBase - - -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python( - kwargs, _self if isinstance( - _self, type) else _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - -class cached_property(object): - # this caches the result of the function call for fn with no inputs - # use this as a decorator on function methods that you want converted - # into cached properties - result_key = '_results' - - def __init__(self, fn): - self._fn = fn - - def __get__(self, instance, cls=None): - if self.result_key in vars(self): - return vars(self)[self.result_key] - else: - result = self._fn() - setattr(self, self.result_key, result) - return result - - -PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) - - -def allows_single_value_input(cls): - """ - This function returns True if the input composed schema model or any - descendant model allows a value only input - This is true for cases where oneOf contains items like: - oneOf: - - float - - NumberWithValidation - - StringEnum - - ArrayModel - - null - TODO: lru_cache this - """ - if ( - issubclass(cls, ModelSimple) or - cls in PRIMITIVE_TYPES - ): - return True - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas['oneOf']: - return False - return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) - return False - - -def composed_model_input_classes(cls): - """ - This function returns a list of the possible models that can be accepted as - inputs. - TODO: lru_cache this - """ - if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: - return [cls] - elif issubclass(cls, ModelNormal): - if cls.discriminator is None: - return [cls] - else: - return get_discriminated_classes(cls) - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas['oneOf']: - return [] - if cls.discriminator is None: - input_classes = [] - for c in cls._composed_schemas['oneOf']: - input_classes.extend(composed_model_input_classes(c)) - return input_classes - else: - return get_discriminated_classes(cls) - return [] - - -class OpenApiModel(object): - """The base class for all OpenAPIModels""" - - def set_attribute(self, name, value): - # this is only used to set properties on self - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._spec_property_naming, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value, - self._configuration - ) - self.__dict__['_data_store'][name] = value - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other - - def __setattr__(self, attr, value): - """set the value of an attribute using dot notation: `instance.attr = val`""" - self[attr] = value - - def __getattr__(self, attr): - """get the value of an attribute using dot notation: `instance.attr`""" - return self.__getitem__(attr) - - def __copy__(self): - cls = self.__class__ - if self.get("_spec_property_naming", False): - return cls._new_from_openapi_data(**self.__dict__) - else: - return cls.__new__(cls, **self.__dict__) - - def __deepcopy__(self, memo): - cls = self.__class__ - - if self.get("_spec_property_naming", False): - new_inst = cls._new_from_openapi_data() - else: - new_inst = cls.__new__(cls) - - for k, v in self.__dict__.items(): - setattr(new_inst, k, deepcopy(v, memo)) - return new_inst - - - def __new__(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get('_visited_composed_classes', ()) - if ( - cls.discriminator is None or - cls in visited_composed_classes - ): - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: If Animal has a discriminator - # petType and we pass in "Dog", and the class Dog - # allOf includes Animal, we move through Animal - # once using the discriminator, and pick Dog. - # Then in the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return super(OpenApiModel, cls).__new__(cls) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % - (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class( - cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get('_path_to_item', ()) - disc_prop_value = kwargs.get( - discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % - (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return super(OpenApiModel, cls).__new__(cls) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = ( - cls._composed_schemas.get('oneOf', ()) + - cls._composed_schemas.get('anyOf', ())) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get('allOf') and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = super(OpenApiModel, cls).__new__(cls) - self_inst.__init__(*args, **kwargs) - - if kwargs.get("_spec_property_naming", False): - # when true, implies new is from deserialization - new_inst = new_cls._new_from_openapi_data(*args, **kwargs) - else: - new_inst = new_cls.__new__(new_cls, *args, **kwargs) - new_inst.__init__(*args, **kwargs) - - return new_inst - - @classmethod - @convert_js_args_to_python_args - def _new_from_openapi_data(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get('_visited_composed_classes', ()) - if ( - cls.discriminator is None or - cls in visited_composed_classes - ): - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: If Animal has a discriminator - # petType and we pass in "Dog", and the class Dog - # allOf includes Animal, we move through Animal - # once using the discriminator, and pick Dog. - # Then in the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return cls._from_openapi_data(*args, **kwargs) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % - (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class( - cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get('_path_to_item', ()) - disc_prop_value = kwargs.get( - discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % - (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return cls._from_openapi_data(*args, **kwargs) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = ( - cls._composed_schemas.get('oneOf', ()) + - cls._composed_schemas.get('anyOf', ())) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get('allOf') and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = cls._from_openapi_data(*args, **kwargs) - - new_inst = new_cls._new_from_openapi_data(*args, **kwargs) - return new_inst - - -class ModelSimple(OpenApiModel): - """the parent class of models whose type != object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__['_data_store'].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__['_data_store'] - - def to_str(self): - """Returns the string representation of the model""" - return str(self.value) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - this_val = self._data_store['value'] - that_val = other._data_store['value'] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - return vals_equal - - -class ModelNormal(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__['_data_store'].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__['_data_store'] - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -class ModelComposed(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi and have oneOf/allOf/anyOf - - When one sets a property we use var_name_to_model_instances to store the value in - the correct class instances + run any type checking + validation code. - When one gets a property we use var_name_to_model_instances to get the value - from the correct class instances. - This allows multiple composed schemas to contain the same property with additive - constraints on the value. - - _composed_schemas (dict) stores the anyOf/allOf/oneOf classes - key (str): allOf/oneOf/anyOf - value (list): the classes in the XOf definition. - Note: none_type can be included when the openapi document version >= 3.1.0 - _composed_instances (list): stores a list of instances of the composed schemas - defined in _composed_schemas. When properties are accessed in the self instance, - they are returned from the self._data_store or the data stores in the instances - in self._composed_schemas - _var_name_to_model_instances (dict): maps between a variable name on self and - the composed instances (self included) which contain that data - key (str): property name - value (list): list of class instances, self or instances in _composed_instances - which contain the value that the key is referring to. - """ - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - """ - Use cases: - 1. additional_properties_type is None (additionalProperties == False in spec) - Check for property presence in self.openapi_types - if not present then throw an error - if present set in self, set attribute - always set on composed schemas - 2. additional_properties_type exists - set attribute on self - always set on composed schemas - """ - if self.additional_properties_type is None: - """ - For an attribute to exist on a composed schema it must: - - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND - - fulfill schema_requirements in each oneOf/anyOf/allOf schemas - - schema_requirements: - For an attribute to exist on a schema it must: - - be present in properties at the schema OR - - have additionalProperties unset (defaults additionalProperties = any type) OR - - have additionalProperties set - """ - if name not in self.openapi_types: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - # attribute must be set on self and composed instances - self.set_attribute(name, value) - for model_instance in self._composed_instances: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] - return None - - __unset_attribute_value__ = object() - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get(name) - values = [] - # A composed model stores self and child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. - # Any property must exist in self and all model instances - # The value stored in all model instances must be the same - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - v = model_instance._data_store[name] - if v not in values: - values.append(v) - len_values = len(values) - if len_values == 0: - return default - elif len_values == 1: - return values[0] - elif len_values > 1: - raise ApiValueError( - "Values stored for property {0} in {1} differ when looking " - "at self and self's composed instances. All values must be " - "the same".format(name, type(self).__name__), - [e for e in [self._path_to_item, name] if e] - ) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - value = self.get(name, self.__unset_attribute_value__) - if value is self.__unset_attribute_value__: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - return value - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - - if name in self.required_properties: - return name in self.__dict__ - - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) - - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - return True - - return False - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -COERCION_INDEX_BY_TYPE = { - ModelComposed: 0, - ModelNormal: 1, - ModelSimple: 2, - none_type: 3, # The type of 'None'. - list: 4, - dict: 5, - float: 6, - int: 7, - bool: 8, - datetime: 9, - date: 10, - str: 11, - file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. -} - -# these are used to limit what type conversions we try to do -# when we have a valid type already and we want to try converting -# to another type -UPCONVERSION_TYPE_PAIRS = ( - (str, datetime), - (str, date), - # A float may be serialized as an integer, e.g. '3' is a valid serialized float. - (int, float), - (list, ModelComposed), - (dict, ModelComposed), - (str, ModelComposed), - (int, ModelComposed), - (float, ModelComposed), - (list, ModelComposed), - (list, ModelNormal), - (dict, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), -) - -COERCIBLE_TYPE_PAIRS = { - False: ( # client instantiation of a model with client data - # (dict, ModelComposed), - # (list, ModelComposed), - # (dict, ModelNormal), - # (list, ModelNormal), - # (str, ModelSimple), - # (int, ModelSimple), - # (float, ModelSimple), - # (list, ModelSimple), - # (str, int), - # (str, float), - # (str, datetime), - # (str, date), - # (int, str), - # (float, str), - ), - True: ( # server -> client data - (dict, ModelComposed), - (list, ModelComposed), - (dict, ModelNormal), - (list, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), - # (str, int), - # (str, float), - (str, datetime), - (str, date), - # (int, str), - # (float, str), - (str, file_type) - ), -} - - -def get_simple_class(input_value): - """Returns an input_value's simple class that we will use for type checking - Python2: - float and int will return int, where int is the python3 int backport - str and unicode will return str, where str is the python3 str backport - Note: float and int ARE both instances of int backport - Note: str_py2 and unicode_py2 are NOT both instances of str backport - - Args: - input_value (class/class_instance): the item for which we will return - the simple class - """ - if isinstance(input_value, type): - # input_value is a class - return input_value - elif isinstance(input_value, tuple): - return tuple - elif isinstance(input_value, list): - return list - elif isinstance(input_value, dict): - return dict - elif isinstance(input_value, none_type): - return none_type - elif isinstance(input_value, file_type): - return file_type - elif isinstance(input_value, bool): - # this must be higher than the int check because - # isinstance(True, int) == True - return bool - elif isinstance(input_value, int): - return int - elif isinstance(input_value, datetime): - # this must be higher than the date check because - # isinstance(datetime_instance, date) == True - return datetime - elif isinstance(input_value, date): - return date - elif isinstance(input_value, str): - return str - return type(input_value) - - -def check_allowed_values(allowed_values, input_variable_path, input_values): - """Raises an exception if the input_values are not allowed - - Args: - allowed_values (dict): the allowed_values dict - input_variable_path (tuple): the path to the input variable - input_values (list/str/int/float/date/datetime): the values that we - are checking to see if they are in allowed_values - """ - these_allowed_values = list(allowed_values[input_variable_path].values()) - if (isinstance(input_values, list) - and not set(input_values).issubset( - set(these_allowed_values))): - invalid_values = ", ".join( - map(str, set(input_values) - set(these_allowed_values))), - raise ApiValueError( - "Invalid values for `%s` [%s], must be a subset of [%s]" % - ( - input_variable_path[0], - invalid_values, - ", ".join(map(str, these_allowed_values)) - ) - ) - elif (isinstance(input_values, dict) - and not set( - input_values.keys()).issubset(set(these_allowed_values))): - invalid_values = ", ".join( - map(str, set(input_values.keys()) - set(these_allowed_values))) - raise ApiValueError( - "Invalid keys in `%s` [%s], must be a subset of [%s]" % - ( - input_variable_path[0], - invalid_values, - ", ".join(map(str, these_allowed_values)) - ) - ) - elif (not isinstance(input_values, (list, dict)) - and input_values not in these_allowed_values): - raise ApiValueError( - "Invalid value for `%s` (%s), must be one of %s" % - ( - input_variable_path[0], - input_values, - these_allowed_values - ) - ) - - -def is_json_validation_enabled(schema_keyword, configuration=None): - """Returns true if JSON schema validation is enabled for the specified - validation keyword. This can be used to skip JSON schema structural validation - as requested in the configuration. - - Args: - schema_keyword (string): the name of a JSON schema validation keyword. - configuration (Configuration): the configuration class. - """ - - return (configuration is None or - not hasattr(configuration, '_disabled_client_side_validations') or - schema_keyword not in configuration._disabled_client_side_validations) - - -def check_validations( - validations, input_variable_path, input_values, - configuration=None): - """Raises an exception if the input_values are invalid - - Args: - validations (dict): the validation dictionary. - input_variable_path (tuple): the path to the input variable. - input_values (list/str/int/float/date/datetime): the values that we - are checking. - configuration (Configuration): the configuration class. - """ - - if input_values is None: - return - - current_validations = validations[input_variable_path] - if (is_json_validation_enabled('multipleOf', configuration) and - 'multiple_of' in current_validations and - isinstance(input_values, (int, float)) and - not (float(input_values) / current_validations['multiple_of']).is_integer()): - # Note 'multipleOf' will be as good as the floating point arithmetic. - raise ApiValueError( - "Invalid value for `%s`, value must be a multiple of " - "`%s`" % ( - input_variable_path[0], - current_validations['multiple_of'] - ) - ) - - if (is_json_validation_enabled('maxLength', configuration) and - 'max_length' in current_validations and - len(input_values) > current_validations['max_length']): - raise ApiValueError( - "Invalid value for `%s`, length must be less than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['max_length'] - ) - ) - - if (is_json_validation_enabled('minLength', configuration) and - 'min_length' in current_validations and - len(input_values) < current_validations['min_length']): - raise ApiValueError( - "Invalid value for `%s`, length must be greater than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['min_length'] - ) - ) - - if (is_json_validation_enabled('maxItems', configuration) and - 'max_items' in current_validations and - len(input_values) > current_validations['max_items']): - raise ApiValueError( - "Invalid value for `%s`, number of items must be less than or " - "equal to `%s`" % ( - input_variable_path[0], - current_validations['max_items'] - ) - ) - - if (is_json_validation_enabled('minItems', configuration) and - 'min_items' in current_validations and - len(input_values) < current_validations['min_items']): - raise ValueError( - "Invalid value for `%s`, number of items must be greater than or " - "equal to `%s`" % ( - input_variable_path[0], - current_validations['min_items'] - ) - ) - - items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', - 'inclusive_minimum') - if (any(item in current_validations for item in items)): - if isinstance(input_values, list): - max_val = max(input_values) - min_val = min(input_values) - elif isinstance(input_values, dict): - max_val = max(input_values.values()) - min_val = min(input_values.values()) - else: - max_val = input_values - min_val = input_values - - if (is_json_validation_enabled('exclusiveMaximum', configuration) and - 'exclusive_maximum' in current_validations and - max_val >= current_validations['exclusive_maximum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than `%s`" % ( - input_variable_path[0], - current_validations['exclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('maximum', configuration) and - 'inclusive_maximum' in current_validations and - max_val > current_validations['inclusive_maximum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['inclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('exclusiveMinimum', configuration) and - 'exclusive_minimum' in current_validations and - min_val <= current_validations['exclusive_minimum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than `%s`" % - ( - input_variable_path[0], - current_validations['exclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('minimum', configuration) and - 'inclusive_minimum' in current_validations and - min_val < current_validations['inclusive_minimum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than or equal " - "to `%s`" % ( - input_variable_path[0], - current_validations['inclusive_minimum'] - ) - ) - flags = current_validations.get('regex', {}).get('flags', 0) - if (is_json_validation_enabled('pattern', configuration) and - 'regex' in current_validations and - not re.search(current_validations['regex']['pattern'], - input_values, flags=flags)): - err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( - input_variable_path[0], - current_validations['regex']['pattern'] - ) - if flags != 0: - # Don't print the regex flags if the flags are not - # specified in the OAS document. - err_msg = r"%s with flags=`%s`" % (err_msg, flags) - raise ApiValueError(err_msg) - - -def order_response_types(required_types): - """Returns the required types sorted in coercion order - - Args: - required_types (list/tuple): collection of classes or instance of - list or dict with class information inside it. - - Returns: - (list): coercion order sorted collection of classes or instance - of list or dict with class information inside it. - """ - - def index_getter(class_or_instance): - if isinstance(class_or_instance, list): - return COERCION_INDEX_BY_TYPE[list] - elif isinstance(class_or_instance, dict): - return COERCION_INDEX_BY_TYPE[dict] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelComposed)): - return COERCION_INDEX_BY_TYPE[ModelComposed] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelNormal)): - return COERCION_INDEX_BY_TYPE[ModelNormal] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelSimple)): - return COERCION_INDEX_BY_TYPE[ModelSimple] - elif class_or_instance in COERCION_INDEX_BY_TYPE: - return COERCION_INDEX_BY_TYPE[class_or_instance] - raise ApiValueError("Unsupported type: %s" % class_or_instance) - - sorted_types = sorted( - required_types, - key=lambda class_or_instance: index_getter(class_or_instance) - ) - return sorted_types - - -def remove_uncoercible(required_types_classes, current_item, spec_property_naming, - must_convert=True): - """Only keeps the type conversions that are possible - - Args: - required_types_classes (tuple): tuple of classes that are required - these should be ordered by COERCION_INDEX_BY_TYPE - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - current_item (any): the current item (input data) to be converted - - Keyword Args: - must_convert (bool): if True the item to convert is of the wrong - type and we want a big list of coercibles - if False, we want a limited list of coercibles - - Returns: - (list): the remaining coercible required types, classes only - """ - current_type_simple = get_simple_class(current_item) - - results_classes = [] - for required_type_class in required_types_classes: - # convert our models to OpenApiModel - required_type_class_simplified = required_type_class - if isinstance(required_type_class_simplified, type): - if issubclass(required_type_class_simplified, ModelComposed): - required_type_class_simplified = ModelComposed - elif issubclass(required_type_class_simplified, ModelNormal): - required_type_class_simplified = ModelNormal - elif issubclass(required_type_class_simplified, ModelSimple): - required_type_class_simplified = ModelSimple - - if required_type_class_simplified == current_type_simple: - # don't consider converting to one's own class - continue - - class_pair = (current_type_simple, required_type_class_simplified) - if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: - results_classes.append(required_type_class) - elif class_pair in UPCONVERSION_TYPE_PAIRS: - results_classes.append(required_type_class) - return results_classes - - -def get_discriminated_classes(cls): - """ - Returns all the classes that a discriminator converts to - TODO: lru_cache this - """ - possible_classes = [] - key = list(cls.discriminator.keys())[0] - if is_type_nullable(cls): - possible_classes.append(cls) - for discr_cls in cls.discriminator[key].values(): - if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: - possible_classes.extend(get_discriminated_classes(discr_cls)) - else: - possible_classes.append(discr_cls) - return possible_classes - - -def get_possible_classes(cls, from_server_context): - # TODO: lru_cache this - possible_classes = [cls] - if from_server_context: - return possible_classes - if hasattr(cls, 'discriminator') and cls.discriminator is not None: - possible_classes = [] - possible_classes.extend(get_discriminated_classes(cls)) - elif issubclass(cls, ModelComposed): - possible_classes.extend(composed_model_input_classes(cls)) - return possible_classes - - -def get_required_type_classes(required_types_mixed, spec_property_naming): - """Converts the tuple required_types into a tuple and a dict described - below - - Args: - required_types_mixed (tuple/list): will contain either classes or - instance of list or dict - spec_property_naming (bool): if True these values came from the - server, and we use the data types in our endpoints. - If False, we are client side and we need to include - oneOf and discriminator classes inside the data types in our endpoints - - Returns: - (valid_classes, dict_valid_class_to_child_types_mixed): - valid_classes (tuple): the valid classes that the current item - should be - dict_valid_class_to_child_types_mixed (dict): - valid_class (class): this is the key - child_types_mixed (list/dict/tuple): describes the valid child - types - """ - valid_classes = [] - child_req_types_by_current_type = {} - for required_type in required_types_mixed: - if isinstance(required_type, list): - valid_classes.append(list) - child_req_types_by_current_type[list] = required_type - elif isinstance(required_type, tuple): - valid_classes.append(tuple) - child_req_types_by_current_type[tuple] = required_type - elif isinstance(required_type, dict): - valid_classes.append(dict) - child_req_types_by_current_type[dict] = required_type[str] - else: - valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) - return tuple(valid_classes), child_req_types_by_current_type - - -def change_keys_js_to_python(input_dict, model_class): - """ - Converts from javascript_key keys in the input_dict to python_keys in - the output dict using the mapping in model_class. - If the input_dict contains a key which does not declared in the model_class, - the key is added to the output dict as is. The assumption is the model_class - may have undeclared properties (additionalProperties attribute in the OAS - document). - """ - - if getattr(model_class, 'attribute_map', None) is None: - return input_dict - output_dict = {} - reversed_attr_map = {value: key for key, value in - model_class.attribute_map.items()} - for javascript_key, value in input_dict.items(): - python_key = reversed_attr_map.get(javascript_key) - if python_key is None: - # if the key is unknown, it is in error or it is an - # additionalProperties variable - python_key = javascript_key - output_dict[python_key] = value - return output_dict - - -def get_type_error(var_value, path_to_item, valid_classes, key_type=False): - error_msg = type_error_message( - var_name=path_to_item[-1], - var_value=var_value, - valid_classes=valid_classes, - key_type=key_type - ) - return ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=valid_classes, - key_type=key_type - ) - - -def deserialize_primitive(data, klass, path_to_item): - """Deserializes string to primitive type. - - :param data: str/int/float - :param klass: str/class the class to convert to - - :return: int, float, str, bool, date, datetime - """ - additional_message = "" - try: - if klass in {datetime, date}: - additional_message = ( - "If you need your parameter to have a fallback " - "string value, please set its type as `type: {}` in your " - "spec. That allows the value to be any type. " - ) - if klass == datetime: - if len(data) < 8: - raise ValueError("This is not a datetime") - # The string should be in iso8601 datetime format. - parsed_datetime = parse(data) - date_only = ( - parsed_datetime.hour == 0 and - parsed_datetime.minute == 0 and - parsed_datetime.second == 0 and - parsed_datetime.tzinfo is None and - 8 <= len(data) <= 10 - ) - if date_only: - raise ValueError("This is a date, not a datetime") - return parsed_datetime - elif klass == date: - if len(data) < 8: - raise ValueError("This is not a date") - return parse(data).date() - else: - converted_value = klass(data) - if isinstance(data, str) and klass == float: - if str(converted_value) != data: - # '7' -> 7.0 -> '7.0' != '7' - raise ValueError('This is not a float') - return converted_value - except (OverflowError, ValueError) as ex: - # parse can raise OverflowError - raise ApiValueError( - "{0}Failed to parse {1} as {2}".format( - additional_message, repr(data), klass.__name__ - ), - path_to_item=path_to_item - ) from ex - - -def get_discriminator_class(model_class, - discr_name, - discr_value, cls_visited): - """Returns the child class specified by the discriminator. - - Args: - model_class (OpenApiModel): the model class. - discr_name (string): the name of the discriminator property. - discr_value (any): the discriminator value. - cls_visited (list): list of model classes that have been visited. - Used to determine the discriminator class without - visiting circular references indefinitely. - - Returns: - used_model_class (class/None): the chosen child class that will be used - to deserialize the data, for example dog.Dog. - If a class is not found, None is returned. - """ - - if model_class in cls_visited: - # The class has already been visited and no suitable class was found. - return None - cls_visited.append(model_class) - used_model_class = None - if discr_name in model_class.discriminator: - class_name_to_discr_class = model_class.discriminator[discr_name] - used_model_class = class_name_to_discr_class.get(discr_value) - if used_model_class is None: - # We didn't find a discriminated class in class_name_to_discr_class. - # So look in the ancestor or descendant discriminators - # The discriminator mapping may exist in a descendant (anyOf, oneOf) - # or ancestor (allOf). - # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat - # hierarchy, the discriminator mappings may be defined at any level - # in the hierarchy. - # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig - # if we try to make BasquePig from mammal, we need to travel through - # the oneOf descendant discriminators to find BasquePig - descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ - model_class._composed_schemas.get('anyOf', ()) - ancestor_classes = model_class._composed_schemas.get('allOf', ()) - possible_classes = descendant_classes + ancestor_classes - for cls in possible_classes: - # Check if the schema has inherited discriminators. - if hasattr(cls, 'discriminator') and cls.discriminator is not None: - used_model_class = get_discriminator_class( - cls, discr_name, discr_value, cls_visited) - if used_model_class is not None: - return used_model_class - return used_model_class - - -def deserialize_model(model_data, model_class, path_to_item, check_type, - configuration, spec_property_naming): - """Deserializes model_data to model instance. - - Args: - model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model - model_class (OpenApiModel): the model class - path_to_item (list): path to the model in the received data - check_type (bool): whether to check the data tupe for the values in - the model - configuration (Configuration): the instance to use to convert files - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - - Returns: - model instance - - Raise: - ApiTypeError - ApiValueError - ApiKeyError - """ - - kw_args = dict(_check_type=check_type, - _path_to_item=path_to_item, - _configuration=configuration, - _spec_property_naming=spec_property_naming) - - if issubclass(model_class, ModelSimple): - return model_class._new_from_openapi_data(model_data, **kw_args) - elif isinstance(model_data, list): - return model_class._new_from_openapi_data(*model_data, **kw_args) - if isinstance(model_data, dict): - kw_args.update(model_data) - return model_class._new_from_openapi_data(**kw_args) - elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class._new_from_openapi_data(model_data, **kw_args) - - -def deserialize_file(response_data, configuration, content_disposition=None): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - Args: - param response_data (str): the file data to write - configuration (Configuration): the instance to use to convert files - - Keyword Args: - content_disposition (str): the value of the Content-Disposition - header - - Returns: - (file_type): the deserialized file which is open - The user is responsible for closing and reading the file - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition, - flags=re.I) - if filename is not None: - filename = filename.group(1) - else: - filename = "default_" + str(uuid.uuid4()) - - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - if isinstance(response_data, str): - # change str to bytes so we can write it - response_data = response_data.encode('utf-8') - f.write(response_data) - - f = open(path, "rb") - return f - - -def attempt_convert_item(input_value, valid_classes, path_to_item, - configuration, spec_property_naming, key_type=False, - must_convert=False, check_type=True): - """ - Args: - input_value (any): the data to convert - valid_classes (any): the classes that are valid - path_to_item (list): the path to the item to convert - configuration (Configuration): the instance to use to convert files - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - key_type (bool): if True we need to convert a key type (not supported) - must_convert (bool): if True we must convert - check_type (bool): if True we check the type or the returned data in - ModelComposed/ModelNormal/ModelSimple instances - - Returns: - instance (any) the fixed item - - Raises: - ApiTypeError - ApiValueError - ApiKeyError - """ - valid_classes_ordered = order_response_types(valid_classes) - valid_classes_coercible = remove_uncoercible( - valid_classes_ordered, input_value, spec_property_naming) - if not valid_classes_coercible or key_type: - # we do not handle keytype errors, json will take care - # of this for us - if configuration is None or not configuration.discard_unknown_keys: - raise get_type_error(input_value, path_to_item, valid_classes, - key_type=key_type) - for valid_class in valid_classes_coercible: - try: - if issubclass(valid_class, OpenApiModel): - return deserialize_model(input_value, valid_class, - path_to_item, check_type, - configuration, spec_property_naming) - elif valid_class == file_type: - return deserialize_file(input_value, configuration) - return deserialize_primitive(input_value, valid_class, - path_to_item) - except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: - if must_convert: - raise conversion_exc - # if we have conversion errors when must_convert == False - # we ignore the exception and move on to the next class - continue - # we were unable to convert, must_convert == False - return input_value - - -def is_type_nullable(input_type): - """ - Returns true if None is an allowed value for the specified input_type. - - A type is nullable if at least one of the following conditions is true: - 1. The OAS 'nullable' attribute has been specified, - 1. The type is the 'null' type, - 1. The type is a anyOf/oneOf composed schema, and a child schema is - the 'null' type. - Args: - input_type (type): the class of the input_value that we are - checking - Returns: - bool - """ - if input_type is none_type: - return True - if issubclass(input_type, OpenApiModel) and input_type._nullable: - return True - if issubclass(input_type, ModelComposed): - # If oneOf/anyOf, check if the 'null' type is one of the allowed types. - for t in input_type._composed_schemas.get('oneOf', ()): - if is_type_nullable(t): - return True - for t in input_type._composed_schemas.get('anyOf', ()): - if is_type_nullable(t): - return True - return False - - -def is_valid_type(input_class_simple, valid_classes): - """ - Args: - input_class_simple (class): the class of the input_value that we are - checking - valid_classes (tuple): the valid classes that the current item - should be - Returns: - bool - """ - if issubclass(input_class_simple, OpenApiModel) and \ - valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,): - return True - valid_type = input_class_simple in valid_classes - if not valid_type and ( - issubclass(input_class_simple, OpenApiModel) or - input_class_simple is none_type): - for valid_class in valid_classes: - if input_class_simple is none_type and is_type_nullable(valid_class): - # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. - return True - if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): - continue - discr_propertyname_py = list(valid_class.discriminator.keys())[0] - discriminator_classes = ( - valid_class.discriminator[discr_propertyname_py].values() - ) - valid_type = is_valid_type(input_class_simple, discriminator_classes) - if valid_type: - return True - return valid_type - - -def validate_and_convert_types(input_value, required_types_mixed, path_to_item, - spec_property_naming, _check_type, configuration=None): - """Raises a TypeError is there is a problem, otherwise returns value - - Args: - input_value (any): the data to validate/convert - required_types_mixed (list/dict/tuple): A list of - valid classes, or a list tuples of valid classes, or a dict where - the value is a tuple of value classes - path_to_item: (list) the path to the data being validated - this stores a list of keys or indices to get to the data being - validated - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - _check_type: (boolean) if true, type will be checked and conversion - will be attempted. - configuration: (Configuration): the configuration class to use - when converting file_type items. - If passed, conversion will be attempted when possible - If not passed, no conversions will be attempted and - exceptions will be raised - - Returns: - the correctly typed value - - Raises: - ApiTypeError - """ - results = get_required_type_classes(required_types_mixed, spec_property_naming) - valid_classes, child_req_types_by_current_type = results - - input_class_simple = get_simple_class(input_value) - valid_type = is_valid_type(input_class_simple, valid_classes) - if not valid_type: - if (configuration - or (input_class_simple == dict - and dict not in valid_classes)): - # if input_value is not valid_type try to convert it - converted_instance = attempt_convert_item( - input_value, - valid_classes, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=True, - check_type=_check_type - ) - return converted_instance - else: - raise get_type_error(input_value, path_to_item, valid_classes, - key_type=False) - - # input_value's type is in valid_classes - if len(valid_classes) > 1 and configuration: - # there are valid classes which are not the current class - valid_classes_coercible = remove_uncoercible( - valid_classes, input_value, spec_property_naming, must_convert=False) - if valid_classes_coercible: - converted_instance = attempt_convert_item( - input_value, - valid_classes_coercible, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=False, - check_type=_check_type - ) - return converted_instance - - if child_req_types_by_current_type == {}: - # all types are of the required types and there are no more inner - # variables left to look at - return input_value - inner_required_types = child_req_types_by_current_type.get( - type(input_value) - ) - if inner_required_types is None: - # for this type, there are not more inner variables left to look at - return input_value - if isinstance(input_value, list): - if input_value == []: - # allow an empty list - return input_value - for index, inner_value in enumerate(input_value): - inner_path = list(path_to_item) - inner_path.append(index) - input_value[index] = validate_and_convert_types( - inner_value, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration - ) - elif isinstance(input_value, dict): - if input_value == {}: - # allow an empty dict - return input_value - for inner_key, inner_val in input_value.items(): - inner_path = list(path_to_item) - inner_path.append(inner_key) - if get_simple_class(inner_key) != str: - raise get_type_error(inner_key, inner_path, valid_classes, - key_type=True) - input_value[inner_key] = validate_and_convert_types( - inner_val, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration - ) - return input_value - - -def model_to_dict(model_instance, serialize=True): - """Returns the model properties as a dict - - Args: - model_instance (one of your model instances): the model instance that - will be converted to a dict. - - Keyword Args: - serialize (bool): if True, the keys in the dict will be values from - attribute_map - """ - result = {} - - def extract_item(item): return ( - item[0], model_to_dict( - item[1], serialize=serialize)) if hasattr( - item[1], '_data_store') else item - - model_instances = [model_instance] - if model_instance._composed_schemas: - model_instances.extend(model_instance._composed_instances) - seen_json_attribute_names = set() - used_fallback_python_attribute_names = set() - py_to_json_map = {} - for model_instance in model_instances: - for attr, value in model_instance._data_store.items(): - if serialize: - # we use get here because additional property key names do not - # exist in attribute_map - try: - attr = model_instance.attribute_map[attr] - py_to_json_map.update(model_instance.attribute_map) - seen_json_attribute_names.add(attr) - except KeyError: - used_fallback_python_attribute_names.add(attr) - if isinstance(value, list): - if not value: - # empty list or None - result[attr] = value - else: - res = [] - for v in value: - if isinstance(v, PRIMITIVE_TYPES) or v is None: - res.append(v) - elif isinstance(v, ModelSimple): - res.append(v.value) - elif isinstance(v, dict): - res.append(dict(map( - extract_item, - v.items() - ))) - else: - res.append(model_to_dict(v, serialize=serialize)) - result[attr] = res - elif isinstance(value, dict): - result[attr] = dict(map( - extract_item, - value.items() - )) - elif isinstance(value, ModelSimple): - result[attr] = value.value - elif hasattr(value, '_data_store'): - result[attr] = model_to_dict(value, serialize=serialize) - else: - result[attr] = value - if serialize: - for python_key in used_fallback_python_attribute_names: - json_key = py_to_json_map.get(python_key) - if json_key is None: - continue - if python_key == json_key: - continue - json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names - if json_key_assigned_no_need_for_python_key: - del result[python_key] - - return result - - -def type_error_message(var_value=None, var_name=None, valid_classes=None, - key_type=None): - """ - Keyword Args: - var_value (any): the variable which has the type_error - var_name (str): the name of the variable which has the typ error - valid_classes (tuple): the accepted classes for current_item's - value - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - """ - key_or_value = 'value' - if key_type: - key_or_value = 'key' - valid_classes_phrase = get_valid_classes_phrase(valid_classes) - msg = ( - "Invalid type for variable '{0}'. Required {1} type {2} and " - "passed type was {3}".format( - var_name, - key_or_value, - valid_classes_phrase, - type(var_value).__name__, - ) - ) - return msg - - -def get_valid_classes_phrase(input_classes): - """Returns a string phrase describing what types are allowed - """ - all_classes = list(input_classes) - all_classes = sorted(all_classes, key=lambda cls: cls.__name__) - all_class_names = [cls.__name__ for cls in all_classes] - if len(all_class_names) == 1: - return 'is {0}'.format(all_class_names[0]) - return "is one of [{0}]".format(", ".join(all_class_names)) - - -def get_allof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - used to make instances - constant_args (dict): - metadata arguments: - _check_type - _path_to_item - _spec_property_naming - _configuration - _visited_composed_classes - - Returns - composed_instances (list) - """ - composed_instances = [] - for allof_class in self._composed_schemas['allOf']: - - try: - if constant_args.get('_spec_property_naming'): - allof_instance = allof_class._from_openapi_data(**model_args, **constant_args) - else: - allof_instance = allof_class(**model_args, **constant_args) - composed_instances.append(allof_instance) - except Exception as ex: - raise ApiValueError( - "Invalid inputs given to generate an instance of '%s'. The " - "input data was invalid for the allOf schema '%s' in the composed " - "schema '%s'. Error=%s" % ( - allof_class.__name__, - allof_class.__name__, - self.__class__.__name__, - str(ex) - ) - ) from ex - return composed_instances - - -def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): - """ - Find the oneOf schema that matches the input data (e.g. payload). - If exactly one schema matches the input data, an instance of that schema - is returned. - If zero or more than one schema match the input data, an exception is raised. - In OAS 3.x, the payload MUST, by validation, match exactly one of the - schemas described by oneOf. - - Args: - cls: the class we are handling - model_kwargs (dict): var_name to var_value - The input data, e.g. the payload that must match a oneOf schema - in the OpenAPI document. - constant_kwargs (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Kwargs: - model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): - the value to assign to a primitive class or ModelSimple class - Notes: - - this is only passed in when oneOf includes types which are not object - - None is used to suppress handling of model_arg, nullable models are handled in __new__ - - Returns - oneof_instance (instance) - """ - if len(cls._composed_schemas['oneOf']) == 0: - return None - - oneof_instances = [] - # Iterate over each oneOf schema and determine if the input data - # matches the oneOf schemas. - for oneof_class in cls._composed_schemas['oneOf']: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if oneof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - single_value_input = allows_single_value_input(oneof_class) - - try: - if not single_value_input: - if constant_kwargs.get('_spec_property_naming'): - oneof_instance = oneof_class._from_openapi_data( - **model_kwargs, **constant_kwargs) - else: - oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) - else: - if issubclass(oneof_class, ModelSimple): - if constant_kwargs.get('_spec_property_naming'): - oneof_instance = oneof_class._from_openapi_data( - model_arg, **constant_kwargs) - else: - oneof_instance = oneof_class(model_arg, **constant_kwargs) - elif oneof_class in PRIMITIVE_TYPES: - oneof_instance = validate_and_convert_types( - model_arg, - (oneof_class,), - constant_kwargs['_path_to_item'], - constant_kwargs['_spec_property_naming'], - constant_kwargs['_check_type'], - configuration=constant_kwargs['_configuration'] - ) - oneof_instances.append(oneof_instance) - except Exception: - pass - if len(oneof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None " - "of the oneOf schemas matched the input data." % - cls.__name__ - ) - elif len(oneof_instances) > 1: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. Multiple " - "oneOf schemas matched the inputs, but a max of one is allowed." % - cls.__name__ - ) - return oneof_instances[0] - - -def get_anyof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - The input data, e.g. the payload that must match at least one - anyOf child schema in the OpenAPI document. - constant_args (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Returns - anyof_instances (list) - """ - anyof_instances = [] - if len(self._composed_schemas['anyOf']) == 0: - return anyof_instances - - for anyof_class in self._composed_schemas['anyOf']: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if anyof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - try: - if constant_args.get('_spec_property_naming'): - anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args) - else: - anyof_instance = anyof_class(**model_args, **constant_args) - anyof_instances.append(anyof_instance) - except Exception: - pass - if len(anyof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None of the " - "anyOf schemas matched the inputs." % - self.__class__.__name__ - ) - return anyof_instances - - -def get_discarded_args(self, composed_instances, model_args): - """ - Gathers the args that were discarded by configuration.discard_unknown_keys - """ - model_arg_keys = model_args.keys() - discarded_args = set() - # arguments passed to self were already converted to python names - # before __init__ was called - for instance in composed_instances: - if instance.__class__ in self._composed_schemas['allOf']: - try: - keys = instance.to_dict().keys() - discarded_keys = model_args - keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - else: - try: - all_keys = set(model_to_dict(instance, serialize=False).keys()) - js_keys = model_to_dict(instance, serialize=True).keys() - all_keys.update(js_keys) - discarded_keys = model_arg_keys - all_keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - return discarded_args - - -def validate_get_composed_info(constant_args, model_args, self): - """ - For composed schemas, generate schema instances for - all schemas in the oneOf/anyOf/allOf definition. If additional - properties are allowed, also assign those properties on - all matched schemas that contain additionalProperties. - Openapi schemas are python classes. - - Exceptions are raised if: - - 0 or > 1 oneOf schema matches the model_args input data - - no anyOf schema matches the model_args input data - - any of the allOf schemas do not match the model_args input data - - Args: - constant_args (dict): these are the args that every model requires - model_args (dict): these are the required and optional spec args that - were passed in to make this model - self (class): the class that we are instantiating - This class contains self._composed_schemas - - Returns: - composed_info (list): length three - composed_instances (list): the composed instances which are not - self - var_name_to_model_instances (dict): a dict going from var_name - to the model_instance which holds that var_name - the model_instance may be self or an instance of one of the - classes in self.composed_instances() - additional_properties_model_instances (list): a list of the - model instances which have the property - additional_properties_type. This list can include self - """ - # create composed_instances - composed_instances = [] - allof_instances = get_allof_instances(self, model_args, constant_args) - composed_instances.extend(allof_instances) - oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) - if oneof_instance is not None: - composed_instances.append(oneof_instance) - anyof_instances = get_anyof_instances(self, model_args, constant_args) - composed_instances.extend(anyof_instances) - """ - set additional_properties_model_instances - additional properties must be evaluated at the schema level - so self's additional properties are most important - If self is a composed schema with: - - no properties defined in self - - additionalProperties: False - Then for object payloads every property is an additional property - and they are not allowed, so only empty dict is allowed - - Properties must be set on all matching schemas - so when a property is assigned toa composed instance, it must be set on all - composed instances regardless of additionalProperties presence - keeping it to prevent breaking changes in v5.0.1 - TODO remove cls._additional_properties_model_instances in 6.0.0 - """ - additional_properties_model_instances = [] - if self.additional_properties_type is not None: - additional_properties_model_instances = [self] - - """ - no need to set properties on self in here, they will be set in __init__ - By here all composed schema oneOf/anyOf/allOf instances have their properties set using - model_args - """ - discarded_args = get_discarded_args(self, composed_instances, model_args) - - # map variable names to composed_instances - var_name_to_model_instances = {} - for prop_name in model_args: - if prop_name not in discarded_args: - var_name_to_model_instances[prop_name] = [self] + list( - filter( - lambda x: prop_name in x.openapi_types, composed_instances)) - - return [ - composed_instances, - var_name_to_model_instances, - additional_properties_model_instances, - discarded_args - ] diff --git a/samples/client/petstore/ruby-autoload/.gitignore b/samples/client/petstore/ruby-autoload/.gitignore new file mode 100644 index 0000000000..05a17cb8f0 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/.gitignore @@ -0,0 +1,39 @@ +# Generated by: https://openapi-generator.tech +# + +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# Gemfile.lock +# .ruby-version +# .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc diff --git a/samples/client/petstore/ruby-autoload/.gitlab-ci.yml b/samples/client/petstore/ruby-autoload/.gitlab-ci.yml new file mode 100644 index 0000000000..3d57c5b30c --- /dev/null +++ b/samples/client/petstore/ruby-autoload/.gitlab-ci.yml @@ -0,0 +1,26 @@ +.ruby: &ruby + variables: + LANG: "C.UTF-8" + before_script: + - ruby -v + - bundle config set --local deployment true + - bundle install -j $(nproc) + parallel: + matrix: + - RUBY_VERSION: ['2.3', '2.4', '2.5', '2.6', '2.7', '3.0'] + image: "ruby:$RUBY_VERSION" + cache: + paths: + - vendor/ruby + key: 'ruby-$RUBY_VERSION' + +gem: + extends: .ruby + script: + - bundle exec rspec + - bundle exec rake build + - bundle exec rake install + artifacts: + paths: + - pkg/*.gem + diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/.openapi-generator-ignore b/samples/client/petstore/ruby-autoload/.openapi-generator-ignore similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/.openapi-generator-ignore rename to samples/client/petstore/ruby-autoload/.openapi-generator-ignore diff --git a/samples/client/petstore/ruby-autoload/.openapi-generator/FILES b/samples/client/petstore/ruby-autoload/.openapi-generator/FILES new file mode 100644 index 0000000000..9335129107 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/.openapi-generator/FILES @@ -0,0 +1,128 @@ +.gitignore +.gitlab-ci.yml +.rspec +.rubocop.yml +.travis.yml +Gemfile +README.md +Rakefile +docs/AdditionalPropertiesClass.md +docs/AllOfWithSingleRef.md +docs/Animal.md +docs/AnotherFakeApi.md +docs/ApiResponse.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/DefaultApi.md +docs/DeprecatedObject.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/File.md +docs/FileSchemaTestClass.md +docs/Foo.md +docs/FooGetDefaultResponse.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/HealthCheckResult.md +docs/List.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelReturn.md +docs/Name.md +docs/NullableClass.md +docs/NumberOnly.md +docs/ObjectWithDeprecatedFields.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/OuterEnumDefaultValue.md +docs/OuterEnumInteger.md +docs/OuterEnumIntegerDefaultValue.md +docs/OuterObjectWithEnumProperty.md +docs/Pet.md +docs/PetApi.md +docs/ReadOnlyFirst.md +docs/SingleRefType.md +docs/SpecialModelName.md +docs/StoreApi.md +docs/Tag.md +docs/User.md +docs/UserApi.md +git_push.sh +lib/petstore.rb +lib/petstore/api/another_fake_api.rb +lib/petstore/api/default_api.rb +lib/petstore/api/fake_api.rb +lib/petstore/api/fake_classname_tags123_api.rb +lib/petstore/api/pet_api.rb +lib/petstore/api/store_api.rb +lib/petstore/api/user_api.rb +lib/petstore/api_client.rb +lib/petstore/api_error.rb +lib/petstore/configuration.rb +lib/petstore/models/additional_properties_class.rb +lib/petstore/models/all_of_with_single_ref.rb +lib/petstore/models/animal.rb +lib/petstore/models/api_response.rb +lib/petstore/models/array_of_array_of_number_only.rb +lib/petstore/models/array_of_number_only.rb +lib/petstore/models/array_test.rb +lib/petstore/models/capitalization.rb +lib/petstore/models/cat.rb +lib/petstore/models/cat_all_of.rb +lib/petstore/models/category.rb +lib/petstore/models/class_model.rb +lib/petstore/models/client.rb +lib/petstore/models/deprecated_object.rb +lib/petstore/models/dog.rb +lib/petstore/models/dog_all_of.rb +lib/petstore/models/enum_arrays.rb +lib/petstore/models/enum_class.rb +lib/petstore/models/enum_test.rb +lib/petstore/models/file.rb +lib/petstore/models/file_schema_test_class.rb +lib/petstore/models/foo.rb +lib/petstore/models/foo_get_default_response.rb +lib/petstore/models/format_test.rb +lib/petstore/models/has_only_read_only.rb +lib/petstore/models/health_check_result.rb +lib/petstore/models/list.rb +lib/petstore/models/map_test.rb +lib/petstore/models/mixed_properties_and_additional_properties_class.rb +lib/petstore/models/model200_response.rb +lib/petstore/models/model_return.rb +lib/petstore/models/name.rb +lib/petstore/models/nullable_class.rb +lib/petstore/models/number_only.rb +lib/petstore/models/object_with_deprecated_fields.rb +lib/petstore/models/order.rb +lib/petstore/models/outer_composite.rb +lib/petstore/models/outer_enum.rb +lib/petstore/models/outer_enum_default_value.rb +lib/petstore/models/outer_enum_integer.rb +lib/petstore/models/outer_enum_integer_default_value.rb +lib/petstore/models/outer_object_with_enum_property.rb +lib/petstore/models/pet.rb +lib/petstore/models/read_only_first.rb +lib/petstore/models/single_ref_type.rb +lib/petstore/models/special_model_name.rb +lib/petstore/models/tag.rb +lib/petstore/models/user.rb +lib/petstore/version.rb +petstore.gemspec +spec/api_client_spec.rb +spec/configuration_spec.rb +spec/spec_helper.rb diff --git a/samples/client/petstore/ruby-autoload/.openapi-generator/VERSION b/samples/client/petstore/ruby-autoload/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/ruby-autoload/.rspec b/samples/client/petstore/ruby-autoload/.rspec new file mode 100644 index 0000000000..83e16f8044 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/.rspec @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/samples/client/petstore/ruby-autoload/.rubocop.yml b/samples/client/petstore/ruby-autoload/.rubocop.yml new file mode 100644 index 0000000000..d32b2b1cda --- /dev/null +++ b/samples/client/petstore/ruby-autoload/.rubocop.yml @@ -0,0 +1,148 @@ +# This file is based on https://github.com/rails/rails/blob/master/.rubocop.yml (MIT license) +# Automatically generated by OpenAPI Generator (https://openapi-generator.tech) +AllCops: + TargetRubyVersion: 2.4 + # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop + # to ignore them, so only the ones explicitly set in this file are enabled. + DisabledByDefault: true + Exclude: + - '**/templates/**/*' + - '**/vendor/**/*' + - 'actionpack/lib/action_dispatch/journey/parser.rb' + +# Prefer &&/|| over and/or. +Style/AndOr: + Enabled: true + +# Align `when` with `case`. +Layout/CaseIndentation: + Enabled: true + +# Align comments with method definitions. +Layout/CommentIndentation: + Enabled: true + +Layout/ElseAlignment: + Enabled: true + +Layout/EmptyLineAfterMagicComment: + Enabled: true + +# In a regular class definition, no empty lines around the body. +Layout/EmptyLinesAroundClassBody: + Enabled: true + +# In a regular method definition, no empty lines around the body. +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +# In a regular module definition, no empty lines around the body. +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Layout/FirstArgumentIndentation: + Enabled: true + +# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. +Style/HashSyntax: + Enabled: false + +# Method definitions after `private` or `protected` isolated calls need one +# extra level of indentation. +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: indented_internal_methods + +# Two spaces, no tabs (for indentation). +Layout/IndentationWidth: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Style/DefWithParentheses: + Enabled: true + +# Defining a method with parameters needs parentheses. +Style/MethodDefParentheses: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: false + EnforcedStyle: always + +# Use `foo {}` not `foo{}`. +Layout/SpaceBeforeBlockBraces: + Enabled: true + +# Use `foo { bar }` not `foo {bar}`. +Layout/SpaceInsideBlockBraces: + Enabled: true + +# Use `{ a: 1 }` not `{a:1}`. +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +# Check quotes usage according to lint rule below. +#Style/StringLiterals: +# Enabled: true +# EnforcedStyle: single_quotes + +# Detect hard tabs, no hard tabs. +Layout/IndentationStyle: + Enabled: true + +# Blank lines should not have any spaces. +Layout/TrailingEmptyLines: + Enabled: true + +# No trailing whitespace. +Layout/TrailingWhitespace: + Enabled: false + +# Use quotes for string literals when they are enough. +Style/RedundantPercentQ: + Enabled: true + +# Align `end` with the matching keyword or starting expression except for +# assignments, where it should be aligned with the LHS. +Layout/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: variable + AutoCorrect: true + +# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. +Lint/RequireParentheses: + Enabled: true + +Style/RedundantReturn: + Enabled: true + AllowMultipleReturnValues: true + +Style/Semicolon: + Enabled: true + AllowAsExpressionSeparator: true diff --git a/samples/client/petstore/ruby-autoload/.travis.yml b/samples/client/petstore/ruby-autoload/.travis.yml new file mode 100644 index 0000000000..09210fc037 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/.travis.yml @@ -0,0 +1,14 @@ +language: ruby +cache: bundler +rvm: + - 2.3 + - 2.4 + - 2.5 + - 2.6 + - 2.7 + - 3.0 +script: + - bundle install --path vendor/bundle + - bundle exec rspec + - gem build petstore.gemspec + - gem install ./petstore-1.0.0.gem diff --git a/samples/client/petstore/ruby-autoload/Gemfile b/samples/client/petstore/ruby-autoload/Gemfile new file mode 100644 index 0000000000..c2e3127cdc --- /dev/null +++ b/samples/client/petstore/ruby-autoload/Gemfile @@ -0,0 +1,9 @@ +source 'https://rubygems.org' + +gemspec + +group :development, :test do + gem 'rake', '~> 13.0.1' + gem 'pry-byebug' + gem 'rubocop', '~> 0.66.0' +end diff --git a/samples/client/petstore/ruby-autoload/README.md b/samples/client/petstore/ruby-autoload/README.md new file mode 100644 index 0000000000..bd15c2fd79 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/README.md @@ -0,0 +1,210 @@ +# petstore + +Petstore - the Ruby gem for the OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +This SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.RubyClientCodegen + +## Installation + +### Build a gem + +To build the Ruby code into a gem: + +```shell +gem build petstore.gemspec +``` + +Then either install the gem locally: + +```shell +gem install ./petstore-1.0.0.gem +``` + +(for development, run `gem install --dev ./petstore-1.0.0.gem` to install the development dependencies) + +or publish the gem to a gem hosting service, e.g. [RubyGems](https://rubygems.org/). + +Finally add this to the Gemfile: + + gem 'petstore', '~> 1.0.0' + +### Install from Git + +If the Ruby gem is hosted at a git repository: https://github.com/GIT_USER_ID/GIT_REPO_ID, then add the following in the Gemfile: + + gem 'petstore', :git => 'https://github.com/GIT_USER_ID/GIT_REPO_ID.git' + +### Include the Ruby code directly + +Include the Ruby code directly using `-I` as follows: + +```shell +ruby -Ilib script.rb +``` + +## Getting Started + +Please follow the [installation](#installation) procedure and then run the following code: + +```ruby +# Load the gem +require 'petstore' + +api_instance = Petstore::AnotherFakeApi.new +client = Petstore::Client.new # Client | client model + +begin + #To test special tags + result = api_instance.call_123_test_special_tags(client) + p result +rescue Petstore::ApiError => e + puts "Exception when calling AnotherFakeApi->call_123_test_special_tags: #{e}" +end + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*Petstore::AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +*Petstore::DefaultApi* | [**foo_get**](docs/DefaultApi.md#foo_get) | **GET** /foo | +*Petstore::FakeApi* | [**fake_health_get**](docs/FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint +*Petstore::FakeApi* | [**fake_http_signature_test**](docs/FakeApi.md#fake_http_signature_test) | **GET** /fake/http-signature-test | test http signature authentication +*Petstore::FakeApi* | [**fake_outer_boolean_serialize**](docs/FakeApi.md#fake_outer_boolean_serialize) | **POST** /fake/outer/boolean | +*Petstore::FakeApi* | [**fake_outer_composite_serialize**](docs/FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite | +*Petstore::FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | +*Petstore::FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | +*Petstore::FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*Petstore::FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | +*Petstore::FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | +*Petstore::FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | +*Petstore::FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model +*Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*Petstore::FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*Petstore::FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*Petstore::FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*Petstore::FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data +*Petstore::FakeApi* | [**test_query_parameter_collection_format**](docs/FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | +*Petstore::FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case +*Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*Petstore::PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +*Petstore::PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +*Petstore::PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*Petstore::PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*Petstore::PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*Petstore::PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*Petstore::PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*Petstore::PetApi* | [**upload_file_with_required_file**](docs/PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*Petstore::StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*Petstore::StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*Petstore::StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID +*Petstore::StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*Petstore::UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*Petstore::UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*Petstore::UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*Petstore::UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*Petstore::UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*Petstore::UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*Petstore::UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*Petstore::UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [Petstore::AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Petstore::AllOfWithSingleRef](docs/AllOfWithSingleRef.md) + - [Petstore::Animal](docs/Animal.md) + - [Petstore::ApiResponse](docs/ApiResponse.md) + - [Petstore::ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [Petstore::ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [Petstore::ArrayTest](docs/ArrayTest.md) + - [Petstore::Capitalization](docs/Capitalization.md) + - [Petstore::Cat](docs/Cat.md) + - [Petstore::CatAllOf](docs/CatAllOf.md) + - [Petstore::Category](docs/Category.md) + - [Petstore::ClassModel](docs/ClassModel.md) + - [Petstore::Client](docs/Client.md) + - [Petstore::DeprecatedObject](docs/DeprecatedObject.md) + - [Petstore::Dog](docs/Dog.md) + - [Petstore::DogAllOf](docs/DogAllOf.md) + - [Petstore::EnumArrays](docs/EnumArrays.md) + - [Petstore::EnumClass](docs/EnumClass.md) + - [Petstore::EnumTest](docs/EnumTest.md) + - [Petstore::File](docs/File.md) + - [Petstore::FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [Petstore::Foo](docs/Foo.md) + - [Petstore::FooGetDefaultResponse](docs/FooGetDefaultResponse.md) + - [Petstore::FormatTest](docs/FormatTest.md) + - [Petstore::HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [Petstore::HealthCheckResult](docs/HealthCheckResult.md) + - [Petstore::List](docs/List.md) + - [Petstore::MapTest](docs/MapTest.md) + - [Petstore::MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Petstore::Model200Response](docs/Model200Response.md) + - [Petstore::ModelReturn](docs/ModelReturn.md) + - [Petstore::Name](docs/Name.md) + - [Petstore::NullableClass](docs/NullableClass.md) + - [Petstore::NumberOnly](docs/NumberOnly.md) + - [Petstore::ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [Petstore::Order](docs/Order.md) + - [Petstore::OuterComposite](docs/OuterComposite.md) + - [Petstore::OuterEnum](docs/OuterEnum.md) + - [Petstore::OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) + - [Petstore::OuterEnumInteger](docs/OuterEnumInteger.md) + - [Petstore::OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) + - [Petstore::OuterObjectWithEnumProperty](docs/OuterObjectWithEnumProperty.md) + - [Petstore::Pet](docs/Pet.md) + - [Petstore::ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Petstore::SingleRefType](docs/SingleRefType.md) + - [Petstore::SpecialModelName](docs/SpecialModelName.md) + - [Petstore::Tag](docs/Tag.md) + - [Petstore::User](docs/User.md) + + +## Documentation for Authorization + + +### api_key + + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### api_key_query + + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + +### bearer_test + +- **Type**: Bearer authentication (JWT) + +### http_basic_test + +- **Type**: HTTP basic authentication + +### http_signature_test + + +### petstore_auth + + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/client/petstore/ruby-autoload/Rakefile b/samples/client/petstore/ruby-autoload/Rakefile new file mode 100644 index 0000000000..c72ca30d45 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/Rakefile @@ -0,0 +1,10 @@ +require "bundler/gem_tasks" + +begin + require 'rspec/core/rake_task' + + RSpec::Core::RakeTask.new(:spec) + task default: :spec +rescue LoadError + # no rspec available +end diff --git a/samples/client/petstore/ruby-autoload/docs/AdditionalPropertiesClass.md b/samples/client/petstore/ruby-autoload/docs/AdditionalPropertiesClass.md new file mode 100644 index 0000000000..4e1cdc869f --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/AdditionalPropertiesClass.md @@ -0,0 +1,20 @@ +# Petstore::AdditionalPropertiesClass + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **map_property** | **Hash<String, String>** | | [optional] | +| **map_of_map_property** | **Hash<String, Hash<String, String>>** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::AdditionalPropertiesClass.new( + map_property: null, + map_of_map_property: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/AllOfWithSingleRef.md b/samples/client/petstore/ruby-autoload/docs/AllOfWithSingleRef.md new file mode 100644 index 0000000000..3c14ac91c4 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/AllOfWithSingleRef.md @@ -0,0 +1,20 @@ +# Petstore::AllOfWithSingleRef + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **username** | **String** | | [optional] | +| **single_ref_type** | [**SingleRefType**](SingleRefType.md) | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::AllOfWithSingleRef.new( + username: null, + single_ref_type: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Animal.md b/samples/client/petstore/ruby-autoload/docs/Animal.md new file mode 100644 index 0000000000..286ce80cb2 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Animal.md @@ -0,0 +1,20 @@ +# Petstore::Animal + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **class_name** | **String** | | | +| **color** | **String** | | [optional][default to 'red'] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Animal.new( + class_name: null, + color: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/AnotherFakeApi.md b/samples/client/petstore/ruby-autoload/docs/AnotherFakeApi.md new file mode 100644 index 0000000000..52f3f5a72e --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/AnotherFakeApi.md @@ -0,0 +1,72 @@ +# Petstore::AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**call_123_test_special_tags**](AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags | + + +## call_123_test_special_tags + +> call_123_test_special_tags(client) + +To test special tags + +To test special tags and operation ID starting with number + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::AnotherFakeApi.new +client = Petstore::Client.new # Client | client model + +begin + # To test special tags + result = api_instance.call_123_test_special_tags(client) + p result +rescue Petstore::ApiError => e + puts "Error when calling AnotherFakeApi->call_123_test_special_tags: #{e}" +end +``` + +#### Using the call_123_test_special_tags_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> call_123_test_special_tags_with_http_info(client) + +```ruby +begin + # To test special tags + data, status_code, headers = api_instance.call_123_test_special_tags_with_http_info(client) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling AnotherFakeApi->call_123_test_special_tags_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **client** | [**Client**](Client.md) | client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + diff --git a/samples/client/petstore/ruby-autoload/docs/ApiResponse.md b/samples/client/petstore/ruby-autoload/docs/ApiResponse.md new file mode 100644 index 0000000000..be28c4fbb5 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/ApiResponse.md @@ -0,0 +1,22 @@ +# Petstore::ApiResponse + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **code** | **Integer** | | [optional] | +| **type** | **String** | | [optional] | +| **message** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::ApiResponse.new( + code: null, + type: null, + message: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/ruby-autoload/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 0000000000..eb5b3f43bc --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,18 @@ +# Petstore::ArrayOfArrayOfNumberOnly + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **array_array_number** | **Array<Array<Float>>** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::ArrayOfArrayOfNumberOnly.new( + array_array_number: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/ArrayOfNumberOnly.md b/samples/client/petstore/ruby-autoload/docs/ArrayOfNumberOnly.md new file mode 100644 index 0000000000..18b6c0f690 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/ArrayOfNumberOnly.md @@ -0,0 +1,18 @@ +# Petstore::ArrayOfNumberOnly + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **array_number** | **Array<Float>** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::ArrayOfNumberOnly.new( + array_number: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/ArrayTest.md b/samples/client/petstore/ruby-autoload/docs/ArrayTest.md new file mode 100644 index 0000000000..8ee02d169e --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/ArrayTest.md @@ -0,0 +1,22 @@ +# Petstore::ArrayTest + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **array_of_string** | **Array<String>** | | [optional] | +| **array_array_of_integer** | **Array<Array<Integer>>** | | [optional] | +| **array_array_of_model** | **Array<Array<ReadOnlyFirst>>** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::ArrayTest.new( + array_of_string: null, + array_array_of_integer: null, + array_array_of_model: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Capitalization.md b/samples/client/petstore/ruby-autoload/docs/Capitalization.md new file mode 100644 index 0000000000..a34377e797 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Capitalization.md @@ -0,0 +1,28 @@ +# Petstore::Capitalization + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **small_camel** | **String** | | [optional] | +| **capital_camel** | **String** | | [optional] | +| **small_snake** | **String** | | [optional] | +| **capital_snake** | **String** | | [optional] | +| **sca_eth_flow_points** | **String** | | [optional] | +| **att_name** | **String** | Name of the pet | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Capitalization.new( + small_camel: null, + capital_camel: null, + small_snake: null, + capital_snake: null, + sca_eth_flow_points: null, + att_name: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Cat.md b/samples/client/petstore/ruby-autoload/docs/Cat.md new file mode 100644 index 0000000000..67168c7766 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Cat.md @@ -0,0 +1,18 @@ +# Petstore::Cat + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **declawed** | **Boolean** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Cat.new( + declawed: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/CatAllOf.md b/samples/client/petstore/ruby-autoload/docs/CatAllOf.md new file mode 100644 index 0000000000..8d91ec5d6e --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/CatAllOf.md @@ -0,0 +1,18 @@ +# Petstore::CatAllOf + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **declawed** | **Boolean** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::CatAllOf.new( + declawed: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Category.md b/samples/client/petstore/ruby-autoload/docs/Category.md new file mode 100644 index 0000000000..f92706fd24 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Category.md @@ -0,0 +1,20 @@ +# Petstore::Category + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [default to 'default-name'] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Category.new( + id: null, + name: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/ClassModel.md b/samples/client/petstore/ruby-autoload/docs/ClassModel.md new file mode 100644 index 0000000000..e88b4c0c7b --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/ClassModel.md @@ -0,0 +1,18 @@ +# Petstore::ClassModel + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **_class** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::ClassModel.new( + _class: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Client.md b/samples/client/petstore/ruby-autoload/docs/Client.md new file mode 100644 index 0000000000..17778a6b0f --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Client.md @@ -0,0 +1,18 @@ +# Petstore::Client + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **client** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Client.new( + client: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/DefaultApi.md b/samples/client/petstore/ruby-autoload/docs/DefaultApi.md new file mode 100644 index 0000000000..86925bb7c8 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/DefaultApi.md @@ -0,0 +1,67 @@ +# Petstore::DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**foo_get**](DefaultApi.md#foo_get) | **GET** /foo | | + + +## foo_get + +> foo_get + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::DefaultApi.new + +begin + + result = api_instance.foo_get + p result +rescue Petstore::ApiError => e + puts "Error when calling DefaultApi->foo_get: #{e}" +end +``` + +#### Using the foo_get_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> foo_get_with_http_info + +```ruby +begin + + data, status_code, headers = api_instance.foo_get_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling DefaultApi->foo_get_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**FooGetDefaultResponse**](FooGetDefaultResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + diff --git a/samples/client/petstore/ruby-autoload/docs/DeprecatedObject.md b/samples/client/petstore/ruby-autoload/docs/DeprecatedObject.md new file mode 100644 index 0000000000..143be46c41 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/DeprecatedObject.md @@ -0,0 +1,18 @@ +# Petstore::DeprecatedObject + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **name** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::DeprecatedObject.new( + name: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Dog.md b/samples/client/petstore/ruby-autoload/docs/Dog.md new file mode 100644 index 0000000000..2649c58c00 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Dog.md @@ -0,0 +1,18 @@ +# Petstore::Dog + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **breed** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Dog.new( + breed: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/DogAllOf.md b/samples/client/petstore/ruby-autoload/docs/DogAllOf.md new file mode 100644 index 0000000000..e0e7a831d0 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/DogAllOf.md @@ -0,0 +1,18 @@ +# Petstore::DogAllOf + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **breed** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::DogAllOf.new( + breed: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/EnumArrays.md b/samples/client/petstore/ruby-autoload/docs/EnumArrays.md new file mode 100644 index 0000000000..cd3d076ad9 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/EnumArrays.md @@ -0,0 +1,20 @@ +# Petstore::EnumArrays + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **just_symbol** | **String** | | [optional] | +| **array_enum** | **Array<String>** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::EnumArrays.new( + just_symbol: null, + array_enum: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/EnumClass.md b/samples/client/petstore/ruby-autoload/docs/EnumClass.md new file mode 100644 index 0000000000..099e6e47ec --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/EnumClass.md @@ -0,0 +1,15 @@ +# Petstore::EnumClass + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::EnumClass.new() +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/EnumTest.md b/samples/client/petstore/ruby-autoload/docs/EnumTest.md new file mode 100644 index 0000000000..fad21de8ae --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/EnumTest.md @@ -0,0 +1,32 @@ +# Petstore::EnumTest + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **enum_string** | **String** | | [optional] | +| **enum_string_required** | **String** | | | +| **enum_integer** | **Integer** | | [optional] | +| **enum_number** | **Float** | | [optional] | +| **outer_enum** | [**OuterEnum**](OuterEnum.md) | | [optional] | +| **outer_enum_integer** | [**OuterEnumInteger**](OuterEnumInteger.md) | | [optional] | +| **outer_enum_default_value** | [**OuterEnumDefaultValue**](OuterEnumDefaultValue.md) | | [optional][default to 'placed'] | +| **outer_enum_integer_default_value** | [**OuterEnumIntegerDefaultValue**](OuterEnumIntegerDefaultValue.md) | | [optional][default to OuterEnumIntegerDefaultValue::N0] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::EnumTest.new( + enum_string: null, + enum_string_required: null, + enum_integer: null, + enum_number: null, + outer_enum: null, + outer_enum_integer: null, + outer_enum_default_value: null, + outer_enum_integer_default_value: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/FakeApi.md b/samples/client/petstore/ruby-autoload/docs/FakeApi.md new file mode 100644 index 0000000000..71fc522caf --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/FakeApi.md @@ -0,0 +1,1197 @@ +# Petstore::FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**fake_health_get**](FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint | +| [**fake_http_signature_test**](FakeApi.md#fake_http_signature_test) | **GET** /fake/http-signature-test | test http signature authentication | +| [**fake_outer_boolean_serialize**](FakeApi.md#fake_outer_boolean_serialize) | **POST** /fake/outer/boolean | | +| [**fake_outer_composite_serialize**](FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite | | +| [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | | +| [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | | +| [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | | +| [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | | +| [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | | +| [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | | +| [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model | +| [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 | +| [**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters | +| [**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) | +| [**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties | +| [**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data | +| [**test_query_parameter_collection_format**](FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | | + + +## fake_health_get + +> fake_health_get + +Health check endpoint + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new + +begin + # Health check endpoint + result = api_instance.fake_health_get + p result +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_health_get: #{e}" +end +``` + +#### Using the fake_health_get_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> fake_health_get_with_http_info + +```ruby +begin + # Health check endpoint + data, status_code, headers = api_instance.fake_health_get_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_health_get_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +## fake_http_signature_test + +> fake_http_signature_test(pet, opts) + +test http signature authentication + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| +end + +api_instance = Petstore::FakeApi.new +pet = Petstore::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store +opts = { + query_1: 'query_1_example', # String | query parameter + header_1: 'header_1_example' # String | header parameter +} + +begin + # test http signature authentication + api_instance.fake_http_signature_test(pet, opts) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_http_signature_test: #{e}" +end +``` + +#### Using the fake_http_signature_test_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> fake_http_signature_test_with_http_info(pet, opts) + +```ruby +begin + # test http signature authentication + data, status_code, headers = api_instance.fake_http_signature_test_with_http_info(pet, opts) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_http_signature_test_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | | +| **query_1** | **String** | query parameter | [optional] | +| **header_1** | **String** | header parameter | [optional] | + +### Return type + +nil (empty response body) + +### Authorization + +[http_signature_test](../README.md#http_signature_test) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +## fake_outer_boolean_serialize + +> Boolean fake_outer_boolean_serialize(opts) + + + +Test serialization of outer boolean types + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +opts = { + body: true # Boolean | Input boolean as post body +} + +begin + + result = api_instance.fake_outer_boolean_serialize(opts) + p result +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_outer_boolean_serialize: #{e}" +end +``` + +#### Using the fake_outer_boolean_serialize_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> fake_outer_boolean_serialize_with_http_info(opts) + +```ruby +begin + + data, status_code, headers = api_instance.fake_outer_boolean_serialize_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => Boolean +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_outer_boolean_serialize_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **Boolean** | Input boolean as post body | [optional] | + +### Return type + +**Boolean** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## fake_outer_composite_serialize + +> fake_outer_composite_serialize(opts) + + + +Test serialization of object with outer number type + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +opts = { + outer_composite: Petstore::OuterComposite.new # OuterComposite | Input composite as post body +} + +begin + + result = api_instance.fake_outer_composite_serialize(opts) + p result +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_outer_composite_serialize: #{e}" +end +``` + +#### Using the fake_outer_composite_serialize_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> fake_outer_composite_serialize_with_http_info(opts) + +```ruby +begin + + data, status_code, headers = api_instance.fake_outer_composite_serialize_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_outer_composite_serialize_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **outer_composite** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] | + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## fake_outer_number_serialize + +> Float fake_outer_number_serialize(opts) + + + +Test serialization of outer number types + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +opts = { + body: 8.14 # Float | Input number as post body +} + +begin + + result = api_instance.fake_outer_number_serialize(opts) + p result +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_outer_number_serialize: #{e}" +end +``` + +#### Using the fake_outer_number_serialize_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> fake_outer_number_serialize_with_http_info(opts) + +```ruby +begin + + data, status_code, headers = api_instance.fake_outer_number_serialize_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => Float +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_outer_number_serialize_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **Float** | Input number as post body | [optional] | + +### Return type + +**Float** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## fake_outer_string_serialize + +> String fake_outer_string_serialize(opts) + + + +Test serialization of outer string types + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +opts = { + body: 'body_example' # String | Input string as post body +} + +begin + + result = api_instance.fake_outer_string_serialize(opts) + p result +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_outer_string_serialize: #{e}" +end +``` + +#### Using the fake_outer_string_serialize_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> fake_outer_string_serialize_with_http_info(opts) + +```ruby +begin + + data, status_code, headers = api_instance.fake_outer_string_serialize_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_outer_string_serialize_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **String** | Input string as post body | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## fake_property_enum_integer_serialize + +> fake_property_enum_integer_serialize(outer_object_with_enum_property) + + + +Test serialization of enum (int) properties with examples + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +outer_object_with_enum_property = Petstore::OuterObjectWithEnumProperty.new({value: Petstore::OuterEnumInteger::N0}) # OuterObjectWithEnumProperty | Input enum (int) as post body + +begin + + result = api_instance.fake_property_enum_integer_serialize(outer_object_with_enum_property) + p result +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_property_enum_integer_serialize: #{e}" +end +``` + +#### Using the fake_property_enum_integer_serialize_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> fake_property_enum_integer_serialize_with_http_info(outer_object_with_enum_property) + +```ruby +begin + + data, status_code, headers = api_instance.fake_property_enum_integer_serialize_with_http_info(outer_object_with_enum_property) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->fake_property_enum_integer_serialize_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **outer_object_with_enum_property** | [**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md) | Input enum (int) as post body | | + +### Return type + +[**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: */* + + +## test_body_with_binary + +> test_body_with_binary(body) + + + +For this test, the body has to be a binary file. + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +body = File.new('/path/to/some/file') # File | image to upload + +begin + + api_instance.test_body_with_binary(body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary: #{e}" +end +``` + +#### Using the test_body_with_binary_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_body_with_binary_with_http_info(body) + +```ruby +begin + + data, status_code, headers = api_instance.test_body_with_binary_with_http_info(body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **File** | image to upload | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + +## test_body_with_file_schema + +> test_body_with_file_schema(file_schema_test_class) + + + +For this test, the body for this request must reference a schema named `File`. + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +file_schema_test_class = Petstore::FileSchemaTestClass.new # FileSchemaTestClass | + +begin + + api_instance.test_body_with_file_schema(file_schema_test_class) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_file_schema: #{e}" +end +``` + +#### Using the test_body_with_file_schema_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_body_with_file_schema_with_http_info(file_schema_test_class) + +```ruby +begin + + data, status_code, headers = api_instance.test_body_with_file_schema_with_http_info(file_schema_test_class) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_file_schema_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **file_schema_test_class** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +## test_body_with_query_params + +> test_body_with_query_params(query, user) + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +query = 'query_example' # String | +user = Petstore::User.new # User | + +begin + + api_instance.test_body_with_query_params(query, user) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_query_params: #{e}" +end +``` + +#### Using the test_body_with_query_params_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_body_with_query_params_with_http_info(query, user) + +```ruby +begin + + data, status_code, headers = api_instance.test_body_with_query_params_with_http_info(query, user) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_query_params_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query** | **String** | | | +| **user** | [**User**](User.md) | | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +## test_client_model + +> test_client_model(client) + +To test \"client\" model + +To test \"client\" model + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +client = Petstore::Client.new # Client | client model + +begin + # To test \"client\" model + result = api_instance.test_client_model(client) + p result +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_client_model: #{e}" +end +``` + +#### Using the test_client_model_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> test_client_model_with_http_info(client) + +```ruby +begin + # To test \"client\" model + data, status_code, headers = api_instance.test_client_model_with_http_info(client) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_client_model_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **client** | [**Client**](Client.md) | client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +## test_endpoint_parameters + +> test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure HTTP basic authorization: http_basic_test + config.username = 'YOUR USERNAME' + config.password = 'YOUR PASSWORD' +end + +api_instance = Petstore::FakeApi.new +number = 8.14 # Float | None +double = 1.2 # Float | None +pattern_without_delimiter = 'pattern_without_delimiter_example' # String | None +byte = 'BYTE_ARRAY_DATA_HERE' # String | None +opts = { + integer: 56, # Integer | None + int32: 56, # Integer | None + int64: 789, # Integer | None + float: 3.4, # Float | None + string: 'string_example', # String | None + binary: File.new('/path/to/some/file'), # File | None + date: Date.parse('2013-10-20'), # Date | None + date_time: Time.parse('2013-10-20T19:20:30+01:00'), # Time | None + password: 'password_example', # String | None + callback: 'callback_example' # String | None +} + +begin + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_endpoint_parameters: #{e}" +end +``` + +#### Using the test_endpoint_parameters_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts) + +```ruby +begin + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + data, status_code, headers = api_instance.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_endpoint_parameters_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **number** | **Float** | None | | +| **double** | **Float** | None | | +| **pattern_without_delimiter** | **String** | None | | +| **byte** | **String** | None | | +| **integer** | **Integer** | None | [optional] | +| **int32** | **Integer** | None | [optional] | +| **int64** | **Integer** | None | [optional] | +| **float** | **Float** | None | [optional] | +| **string** | **String** | None | [optional] | +| **binary** | **File** | None | [optional] | +| **date** | **Date** | None | [optional] | +| **date_time** | **Time** | None | [optional] | +| **password** | **String** | None | [optional] | +| **callback** | **String** | None | [optional] | + +### Return type + +nil (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +## test_enum_parameters + +> test_enum_parameters(opts) + +To test enum parameters + +To test enum parameters + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +opts = { + enum_header_string_array: ['>'], # Array | Header parameter enum test (string array) + enum_header_string: '_abc', # String | Header parameter enum test (string) + enum_query_string_array: ['>'], # Array | Query parameter enum test (string array) + enum_query_string: '_abc', # String | Query parameter enum test (string) + enum_query_integer: 1, # Integer | Query parameter enum test (double) + enum_query_double: 1.1, # Float | Query parameter enum test (double) + enum_query_model_array: [Petstore::EnumClass::ABC], # Array | + enum_form_string_array: ['>'], # Array | Form parameter enum test (string array) + enum_form_string: '_abc' # String | Form parameter enum test (string) +} + +begin + # To test enum parameters + api_instance.test_enum_parameters(opts) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_enum_parameters: #{e}" +end +``` + +#### Using the test_enum_parameters_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_enum_parameters_with_http_info(opts) + +```ruby +begin + # To test enum parameters + data, status_code, headers = api_instance.test_enum_parameters_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_enum_parameters_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **enum_header_string_array** | [**Array<String>**](String.md) | Header parameter enum test (string array) | [optional] | +| **enum_header_string** | **String** | Header parameter enum test (string) | [optional][default to '-efg'] | +| **enum_query_string_array** | [**Array<String>**](String.md) | Query parameter enum test (string array) | [optional] | +| **enum_query_string** | **String** | Query parameter enum test (string) | [optional][default to '-efg'] | +| **enum_query_integer** | **Integer** | Query parameter enum test (double) | [optional] | +| **enum_query_double** | **Float** | Query parameter enum test (double) | [optional] | +| **enum_query_model_array** | [**Array<EnumClass>**](EnumClass.md) | | [optional] | +| **enum_form_string_array** | [**Array<String>**](String.md) | Form parameter enum test (string array) | [optional][default to '$'] | +| **enum_form_string** | **String** | Form parameter enum test (string) | [optional][default to '-efg'] | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +## test_group_parameters + +> test_group_parameters(opts) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure Bearer authorization (JWT): bearer_test + config.access_token = 'YOUR_BEARER_TOKEN' +end + +api_instance = Petstore::FakeApi.new +opts = { + required_string_group: 56, # Integer | Required String in group parameters (required) + required_boolean_group: true, # Boolean | Required Boolean in group parameters (required) + required_int64_group: 789, # Integer | Required Integer in group parameters (required) + string_group: 56, # Integer | String in group parameters + boolean_group: true, # Boolean | Boolean in group parameters + int64_group: 789, # Integer | Integer in group parameters +} + +begin + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(opts) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_group_parameters: #{e}" +end +``` + +#### Using the test_group_parameters_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_group_parameters_with_http_info(opts) + +```ruby +begin + # Fake endpoint to test group parameters (optional) + data, status_code, headers = api_instance.test_group_parameters_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_group_parameters_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **required_string_group** | **Integer** | Required String in group parameters | | +| **required_boolean_group** | **Boolean** | Required Boolean in group parameters | | +| **required_int64_group** | **Integer** | Required Integer in group parameters | | +| **string_group** | **Integer** | String in group parameters | [optional] | +| **boolean_group** | **Boolean** | Boolean in group parameters | [optional] | +| **int64_group** | **Integer** | Integer in group parameters | [optional] | + +### Return type + +nil (empty response body) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## test_inline_additional_properties + +> test_inline_additional_properties(request_body) + +test inline additionalProperties + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +request_body = { key: 'inner_example'} # Hash | request body + +begin + # test inline additionalProperties + api_instance.test_inline_additional_properties(request_body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_inline_additional_properties: #{e}" +end +``` + +#### Using the test_inline_additional_properties_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_inline_additional_properties_with_http_info(request_body) + +```ruby +begin + # test inline additionalProperties + data, status_code, headers = api_instance.test_inline_additional_properties_with_http_info(request_body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_inline_additional_properties_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **request_body** | [**Hash<String, String>**](String.md) | request body | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +## test_json_form_data + +> test_json_form_data(param, param2) + +test json serialization of form data + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +param = 'param_example' # String | field1 +param2 = 'param2_example' # String | field2 + +begin + # test json serialization of form data + api_instance.test_json_form_data(param, param2) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_json_form_data: #{e}" +end +``` + +#### Using the test_json_form_data_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_json_form_data_with_http_info(param, param2) + +```ruby +begin + # test json serialization of form data + data, status_code, headers = api_instance.test_json_form_data_with_http_info(param, param2) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_json_form_data_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **param** | **String** | field1 | | +| **param2** | **String** | field2 | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +## test_query_parameter_collection_format + +> test_query_parameter_collection_format(pipe, ioutil, http, url, context, allow_empty, opts) + + + +To test the collection format in query parameters + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +pipe = ['inner_example'] # Array | +ioutil = ['inner_example'] # Array | +http = ['inner_example'] # Array | +url = ['inner_example'] # Array | +context = ['inner_example'] # Array | +allow_empty = 'allow_empty_example' # String | +opts = { + language: { key: 'inner_example'} # Hash | +} + +begin + + api_instance.test_query_parameter_collection_format(pipe, ioutil, http, url, context, allow_empty, opts) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_query_parameter_collection_format: #{e}" +end +``` + +#### Using the test_query_parameter_collection_format_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_query_parameter_collection_format_with_http_info(pipe, ioutil, http, url, context, allow_empty, opts) + +```ruby +begin + + data, status_code, headers = api_instance.test_query_parameter_collection_format_with_http_info(pipe, ioutil, http, url, context, allow_empty, opts) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_query_parameter_collection_format_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pipe** | [**Array<String>**](String.md) | | | +| **ioutil** | [**Array<String>**](String.md) | | | +| **http** | [**Array<String>**](String.md) | | | +| **url** | [**Array<String>**](String.md) | | | +| **context** | [**Array<String>**](String.md) | | | +| **allow_empty** | **String** | | | +| **language** | [**Hash<String, String>**](String.md) | | [optional] | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + diff --git a/samples/client/petstore/ruby-autoload/docs/FakeClassnameTags123Api.md b/samples/client/petstore/ruby-autoload/docs/FakeClassnameTags123Api.md new file mode 100644 index 0000000000..32d3ff8ebd --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/FakeClassnameTags123Api.md @@ -0,0 +1,79 @@ +# Petstore::FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_classname**](FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case | + + +## test_classname + +> test_classname(client) + +To test class name in snake case + +To test class name in snake case + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: api_key_query + config.api_key['api_key_query'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key_query'] = 'Bearer' +end + +api_instance = Petstore::FakeClassnameTags123Api.new +client = Petstore::Client.new # Client | client model + +begin + # To test class name in snake case + result = api_instance.test_classname(client) + p result +rescue Petstore::ApiError => e + puts "Error when calling FakeClassnameTags123Api->test_classname: #{e}" +end +``` + +#### Using the test_classname_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> test_classname_with_http_info(client) + +```ruby +begin + # To test class name in snake case + data, status_code, headers = api_instance.test_classname_with_http_info(client) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling FakeClassnameTags123Api->test_classname_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **client** | [**Client**](Client.md) | client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + diff --git a/samples/client/petstore/ruby-autoload/docs/File.md b/samples/client/petstore/ruby-autoload/docs/File.md new file mode 100644 index 0000000000..5cbc129790 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/File.md @@ -0,0 +1,18 @@ +# Petstore::File + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **source_uri** | **String** | Test capitalization | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::File.new( + source_uri: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/FileSchemaTestClass.md b/samples/client/petstore/ruby-autoload/docs/FileSchemaTestClass.md new file mode 100644 index 0000000000..d9dbef2348 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/FileSchemaTestClass.md @@ -0,0 +1,20 @@ +# Petstore::FileSchemaTestClass + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **file** | **File** | | [optional] | +| **files** | **Array<File>** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::FileSchemaTestClass.new( + file: null, + files: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Foo.md b/samples/client/petstore/ruby-autoload/docs/Foo.md new file mode 100644 index 0000000000..3a826f6ae7 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Foo.md @@ -0,0 +1,18 @@ +# Petstore::Foo + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **bar** | **String** | | [optional][default to 'bar'] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Foo.new( + bar: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/FooGetDefaultResponse.md b/samples/client/petstore/ruby-autoload/docs/FooGetDefaultResponse.md new file mode 100644 index 0000000000..915e059d92 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/FooGetDefaultResponse.md @@ -0,0 +1,18 @@ +# Petstore::FooGetDefaultResponse + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **string** | [**Foo**](Foo.md) | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::FooGetDefaultResponse.new( + string: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/FormatTest.md b/samples/client/petstore/ruby-autoload/docs/FormatTest.md new file mode 100644 index 0000000000..a790ce4483 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/FormatTest.md @@ -0,0 +1,48 @@ +# Petstore::FormatTest + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **integer** | **Integer** | | [optional] | +| **int32** | **Integer** | | [optional] | +| **int64** | **Integer** | | [optional] | +| **number** | **Float** | | | +| **float** | **Float** | | [optional] | +| **double** | **Float** | | [optional] | +| **decimal** | **Float** | | [optional] | +| **string** | **String** | | [optional] | +| **byte** | **String** | | | +| **binary** | **File** | | [optional] | +| **date** | **Date** | | | +| **date_time** | **Time** | | [optional] | +| **uuid** | **String** | | [optional] | +| **password** | **String** | | | +| **pattern_with_digits** | **String** | A string that is a 10 digit number. Can have leading zeros. | [optional] | +| **pattern_with_digits_and_delimiter** | **String** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::FormatTest.new( + integer: null, + int32: null, + int64: null, + number: null, + float: null, + double: null, + decimal: null, + string: null, + byte: null, + binary: null, + date: null, + date_time: null, + uuid: 72f98069-206d-4f12-9f12-3d1e525a8e84, + password: null, + pattern_with_digits: null, + pattern_with_digits_and_delimiter: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/HasOnlyReadOnly.md b/samples/client/petstore/ruby-autoload/docs/HasOnlyReadOnly.md new file mode 100644 index 0000000000..6d8dbfd0ad --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/HasOnlyReadOnly.md @@ -0,0 +1,20 @@ +# Petstore::HasOnlyReadOnly + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **bar** | **String** | | [optional][readonly] | +| **foo** | **String** | | [optional][readonly] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::HasOnlyReadOnly.new( + bar: null, + foo: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/HealthCheckResult.md b/samples/client/petstore/ruby-autoload/docs/HealthCheckResult.md new file mode 100644 index 0000000000..5695ceb488 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/HealthCheckResult.md @@ -0,0 +1,18 @@ +# Petstore::HealthCheckResult + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **nullable_message** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::HealthCheckResult.new( + nullable_message: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/List.md b/samples/client/petstore/ruby-autoload/docs/List.md new file mode 100644 index 0000000000..42467415e7 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/List.md @@ -0,0 +1,18 @@ +# Petstore::List + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **_123_list** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::List.new( + _123_list: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/MapTest.md b/samples/client/petstore/ruby-autoload/docs/MapTest.md new file mode 100644 index 0000000000..58bc132724 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/MapTest.md @@ -0,0 +1,24 @@ +# Petstore::MapTest + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **map_map_of_string** | **Hash<String, Hash<String, String>>** | | [optional] | +| **map_of_enum_string** | **Hash<String, String>** | | [optional] | +| **direct_map** | **Hash<String, Boolean>** | | [optional] | +| **indirect_map** | **Hash<String, Boolean>** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::MapTest.new( + map_map_of_string: null, + map_of_enum_string: null, + direct_map: null, + indirect_map: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/ruby-autoload/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 0000000000..c7d57c85dd --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,22 @@ +# Petstore::MixedPropertiesAndAdditionalPropertiesClass + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **uuid** | **String** | | [optional] | +| **date_time** | **Time** | | [optional] | +| **map** | [**Hash<String, Animal>**](Animal.md) | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::MixedPropertiesAndAdditionalPropertiesClass.new( + uuid: null, + date_time: null, + map: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Model200Response.md b/samples/client/petstore/ruby-autoload/docs/Model200Response.md new file mode 100644 index 0000000000..2eee7ded75 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Model200Response.md @@ -0,0 +1,20 @@ +# Petstore::Model200Response + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **name** | **Integer** | | [optional] | +| **_class** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Model200Response.new( + name: null, + _class: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/ModelReturn.md b/samples/client/petstore/ruby-autoload/docs/ModelReturn.md new file mode 100644 index 0000000000..bbcb5307f4 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/ModelReturn.md @@ -0,0 +1,18 @@ +# Petstore::ModelReturn + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **_return** | **Integer** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::ModelReturn.new( + _return: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Name.md b/samples/client/petstore/ruby-autoload/docs/Name.md new file mode 100644 index 0000000000..9ff05587cb --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Name.md @@ -0,0 +1,24 @@ +# Petstore::Name + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **name** | **Integer** | | | +| **snake_case** | **Integer** | | [optional][readonly] | +| **property** | **String** | | [optional] | +| **_123_number** | **Integer** | | [optional][readonly] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Name.new( + name: null, + snake_case: null, + property: null, + _123_number: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/NullableClass.md b/samples/client/petstore/ruby-autoload/docs/NullableClass.md new file mode 100644 index 0000000000..761bfd8073 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/NullableClass.md @@ -0,0 +1,40 @@ +# Petstore::NullableClass + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **integer_prop** | **Integer** | | [optional] | +| **number_prop** | **Float** | | [optional] | +| **boolean_prop** | **Boolean** | | [optional] | +| **string_prop** | **String** | | [optional] | +| **date_prop** | **Date** | | [optional] | +| **datetime_prop** | **Time** | | [optional] | +| **array_nullable_prop** | **Array<Object>** | | [optional] | +| **array_and_items_nullable_prop** | **Array<Object>** | | [optional] | +| **array_items_nullable** | **Array<Object>** | | [optional] | +| **object_nullable_prop** | **Hash<String, Object>** | | [optional] | +| **object_and_items_nullable_prop** | **Hash<String, Object>** | | [optional] | +| **object_items_nullable** | **Hash<String, Object>** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::NullableClass.new( + integer_prop: null, + number_prop: null, + boolean_prop: null, + string_prop: null, + date_prop: null, + datetime_prop: null, + array_nullable_prop: null, + array_and_items_nullable_prop: null, + array_items_nullable: null, + object_nullable_prop: null, + object_and_items_nullable_prop: null, + object_items_nullable: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/NumberOnly.md b/samples/client/petstore/ruby-autoload/docs/NumberOnly.md new file mode 100644 index 0000000000..540e736c8a --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/NumberOnly.md @@ -0,0 +1,18 @@ +# Petstore::NumberOnly + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **just_number** | **Float** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::NumberOnly.new( + just_number: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/ObjectWithDeprecatedFields.md b/samples/client/petstore/ruby-autoload/docs/ObjectWithDeprecatedFields.md new file mode 100644 index 0000000000..6658759209 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/ObjectWithDeprecatedFields.md @@ -0,0 +1,24 @@ +# Petstore::ObjectWithDeprecatedFields + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **uuid** | **String** | | [optional] | +| **id** | **Float** | | [optional] | +| **deprecated_ref** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] | +| **bars** | **Array<String>** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::ObjectWithDeprecatedFields.new( + uuid: null, + id: null, + deprecated_ref: null, + bars: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Order.md b/samples/client/petstore/ruby-autoload/docs/Order.md new file mode 100644 index 0000000000..a3fd551380 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Order.md @@ -0,0 +1,28 @@ +# Petstore::Order + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **pet_id** | **Integer** | | [optional] | +| **quantity** | **Integer** | | [optional] | +| **ship_date** | **Time** | | [optional] | +| **status** | **String** | Order Status | [optional] | +| **complete** | **Boolean** | | [optional][default to false] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Order.new( + id: null, + pet_id: null, + quantity: null, + ship_date: null, + status: null, + complete: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/OuterComposite.md b/samples/client/petstore/ruby-autoload/docs/OuterComposite.md new file mode 100644 index 0000000000..03f9386e5f --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/OuterComposite.md @@ -0,0 +1,22 @@ +# Petstore::OuterComposite + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **my_number** | **Float** | | [optional] | +| **my_string** | **String** | | [optional] | +| **my_boolean** | **Boolean** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::OuterComposite.new( + my_number: null, + my_string: null, + my_boolean: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/OuterEnum.md b/samples/client/petstore/ruby-autoload/docs/OuterEnum.md new file mode 100644 index 0000000000..9c81b44ae7 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/OuterEnum.md @@ -0,0 +1,15 @@ +# Petstore::OuterEnum + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::OuterEnum.new() +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/OuterEnumDefaultValue.md b/samples/client/petstore/ruby-autoload/docs/OuterEnumDefaultValue.md new file mode 100644 index 0000000000..be1f48a846 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/OuterEnumDefaultValue.md @@ -0,0 +1,15 @@ +# Petstore::OuterEnumDefaultValue + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::OuterEnumDefaultValue.new() +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/OuterEnumInteger.md b/samples/client/petstore/ruby-autoload/docs/OuterEnumInteger.md new file mode 100644 index 0000000000..80f46c1e0d --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/OuterEnumInteger.md @@ -0,0 +1,15 @@ +# Petstore::OuterEnumInteger + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::OuterEnumInteger.new() +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/OuterEnumIntegerDefaultValue.md b/samples/client/petstore/ruby-autoload/docs/OuterEnumIntegerDefaultValue.md new file mode 100644 index 0000000000..38fbfd638a --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/OuterEnumIntegerDefaultValue.md @@ -0,0 +1,15 @@ +# Petstore::OuterEnumIntegerDefaultValue + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::OuterEnumIntegerDefaultValue.new() +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/OuterObjectWithEnumProperty.md b/samples/client/petstore/ruby-autoload/docs/OuterObjectWithEnumProperty.md new file mode 100644 index 0000000000..dfd9de4596 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/OuterObjectWithEnumProperty.md @@ -0,0 +1,18 @@ +# Petstore::OuterObjectWithEnumProperty + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **value** | [**OuterEnumInteger**](OuterEnumInteger.md) | | | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::OuterObjectWithEnumProperty.new( + value: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/Pet.md b/samples/client/petstore/ruby-autoload/docs/Pet.md new file mode 100644 index 0000000000..13f34d7d16 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Pet.md @@ -0,0 +1,28 @@ +# Petstore::Pet + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **category** | [**Category**](Category.md) | | [optional] | +| **name** | **String** | | | +| **photo_urls** | **Array<String>** | | | +| **tags** | [**Array<Tag>**](Tag.md) | | [optional] | +| **status** | **String** | pet status in the store | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Pet.new( + id: null, + category: null, + name: doggie, + photo_urls: null, + tags: null, + status: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/PetApi.md b/samples/client/petstore/ruby-autoload/docs/PetApi.md new file mode 100644 index 0000000000..b28334ae2c --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/PetApi.md @@ -0,0 +1,657 @@ +# Petstore::PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store | +| [**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status | +| [**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID | +| [**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet | +| [**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image | +| [**upload_file_with_required_file**](PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) | + + +## add_pet + +> add_pet(pet) + +Add a new pet to the store + + + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new +pet = Petstore::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store + +begin + # Add a new pet to the store + api_instance.add_pet(pet) +rescue Petstore::ApiError => e + puts "Error when calling PetApi->add_pet: #{e}" +end +``` + +#### Using the add_pet_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> add_pet_with_http_info(pet) + +```ruby +begin + # Add a new pet to the store + data, status_code, headers = api_instance.add_pet_with_http_info(pet) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling PetApi->add_pet_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | | + +### Return type + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +## delete_pet + +> delete_pet(pet_id, opts) + +Deletes a pet + + + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new +pet_id = 789 # Integer | Pet id to delete +opts = { + api_key: 'api_key_example' # String | +} + +begin + # Deletes a pet + api_instance.delete_pet(pet_id, opts) +rescue Petstore::ApiError => e + puts "Error when calling PetApi->delete_pet: #{e}" +end +``` + +#### Using the delete_pet_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> delete_pet_with_http_info(pet_id, opts) + +```ruby +begin + # Deletes a pet + data, status_code, headers = api_instance.delete_pet_with_http_info(pet_id, opts) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling PetApi->delete_pet_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet_id** | **Integer** | Pet id to delete | | +| **api_key** | **String** | | [optional] | + +### Return type + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## find_pets_by_status + +> > find_pets_by_status(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new +status = ['available'] # Array | Status values that need to be considered for filter + +begin + # Finds Pets by status + result = api_instance.find_pets_by_status(status) + p result +rescue Petstore::ApiError => e + puts "Error when calling PetApi->find_pets_by_status: #{e}" +end +``` + +#### Using the find_pets_by_status_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> >, Integer, Hash)> find_pets_by_status_with_http_info(status) + +```ruby +begin + # Finds Pets by status + data, status_code, headers = api_instance.find_pets_by_status_with_http_info(status) + p status_code # => 2xx + p headers # => { ... } + p data # => > +rescue Petstore::ApiError => e + puts "Error when calling PetApi->find_pets_by_status_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **status** | [**Array<String>**](String.md) | Status values that need to be considered for filter | | + +### Return type + +[**Array<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## find_pets_by_tags + +> > find_pets_by_tags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new +tags = ['inner_example'] # Array | Tags to filter by + +begin + # Finds Pets by tags + result = api_instance.find_pets_by_tags(tags) + p result +rescue Petstore::ApiError => e + puts "Error when calling PetApi->find_pets_by_tags: #{e}" +end +``` + +#### Using the find_pets_by_tags_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> >, Integer, Hash)> find_pets_by_tags_with_http_info(tags) + +```ruby +begin + # Finds Pets by tags + data, status_code, headers = api_instance.find_pets_by_tags_with_http_info(tags) + p status_code # => 2xx + p headers # => { ... } + p data # => > +rescue Petstore::ApiError => e + puts "Error when calling PetApi->find_pets_by_tags_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **tags** | [**Array<String>**](String.md) | Tags to filter by | | + +### Return type + +[**Array<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## get_pet_by_id + +> get_pet_by_id(pet_id) + +Find pet by ID + +Returns a single pet + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key'] = 'Bearer' +end + +api_instance = Petstore::PetApi.new +pet_id = 789 # Integer | ID of pet to return + +begin + # Find pet by ID + result = api_instance.get_pet_by_id(pet_id) + p result +rescue Petstore::ApiError => e + puts "Error when calling PetApi->get_pet_by_id: #{e}" +end +``` + +#### Using the get_pet_by_id_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> get_pet_by_id_with_http_info(pet_id) + +```ruby +begin + # Find pet by ID + data, status_code, headers = api_instance.get_pet_by_id_with_http_info(pet_id) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling PetApi->get_pet_by_id_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet_id** | **Integer** | ID of pet to return | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## update_pet + +> update_pet(pet) + +Update an existing pet + + + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new +pet = Petstore::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store + +begin + # Update an existing pet + api_instance.update_pet(pet) +rescue Petstore::ApiError => e + puts "Error when calling PetApi->update_pet: #{e}" +end +``` + +#### Using the update_pet_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> update_pet_with_http_info(pet) + +```ruby +begin + # Update an existing pet + data, status_code, headers = api_instance.update_pet_with_http_info(pet) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling PetApi->update_pet_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | | + +### Return type + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +## update_pet_with_form + +> update_pet_with_form(pet_id, opts) + +Updates a pet in the store with form data + + + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new +pet_id = 789 # Integer | ID of pet that needs to be updated +opts = { + name: 'name_example', # String | Updated name of the pet + status: 'status_example' # String | Updated status of the pet +} + +begin + # Updates a pet in the store with form data + api_instance.update_pet_with_form(pet_id, opts) +rescue Petstore::ApiError => e + puts "Error when calling PetApi->update_pet_with_form: #{e}" +end +``` + +#### Using the update_pet_with_form_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> update_pet_with_form_with_http_info(pet_id, opts) + +```ruby +begin + # Updates a pet in the store with form data + data, status_code, headers = api_instance.update_pet_with_form_with_http_info(pet_id, opts) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling PetApi->update_pet_with_form_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet_id** | **Integer** | ID of pet that needs to be updated | | +| **name** | **String** | Updated name of the pet | [optional] | +| **status** | **String** | Updated status of the pet | [optional] | + +### Return type + +nil (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +## upload_file + +> upload_file(pet_id, opts) + +uploads an image + + + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new +pet_id = 789 # Integer | ID of pet to update +opts = { + additional_metadata: 'additional_metadata_example', # String | Additional data to pass to server + file: File.new('/path/to/some/file') # File | file to upload +} + +begin + # uploads an image + result = api_instance.upload_file(pet_id, opts) + p result +rescue Petstore::ApiError => e + puts "Error when calling PetApi->upload_file: #{e}" +end +``` + +#### Using the upload_file_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> upload_file_with_http_info(pet_id, opts) + +```ruby +begin + # uploads an image + data, status_code, headers = api_instance.upload_file_with_http_info(pet_id, opts) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling PetApi->upload_file_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet_id** | **Integer** | ID of pet to update | | +| **additional_metadata** | **String** | Additional data to pass to server | [optional] | +| **file** | **File** | file to upload | [optional] | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + + +## upload_file_with_required_file + +> upload_file_with_required_file(pet_id, required_file, opts) + +uploads an image (required) + + + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure OAuth2 access token for authorization: petstore_auth + config.access_token = 'YOUR ACCESS TOKEN' +end + +api_instance = Petstore::PetApi.new +pet_id = 789 # Integer | ID of pet to update +required_file = File.new('/path/to/some/file') # File | file to upload +opts = { + additional_metadata: 'additional_metadata_example' # String | Additional data to pass to server +} + +begin + # uploads an image (required) + result = api_instance.upload_file_with_required_file(pet_id, required_file, opts) + p result +rescue Petstore::ApiError => e + puts "Error when calling PetApi->upload_file_with_required_file: #{e}" +end +``` + +#### Using the upload_file_with_required_file_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> upload_file_with_required_file_with_http_info(pet_id, required_file, opts) + +```ruby +begin + # uploads an image (required) + data, status_code, headers = api_instance.upload_file_with_required_file_with_http_info(pet_id, required_file, opts) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling PetApi->upload_file_with_required_file_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet_id** | **Integer** | ID of pet to update | | +| **required_file** | **File** | file to upload | | +| **additional_metadata** | **String** | Additional data to pass to server | [optional] | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + diff --git a/samples/client/petstore/ruby-autoload/docs/ReadOnlyFirst.md b/samples/client/petstore/ruby-autoload/docs/ReadOnlyFirst.md new file mode 100644 index 0000000000..bed355e261 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/ReadOnlyFirst.md @@ -0,0 +1,20 @@ +# Petstore::ReadOnlyFirst + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **bar** | **String** | | [optional][readonly] | +| **baz** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::ReadOnlyFirst.new( + bar: null, + baz: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/SingleRefType.md b/samples/client/petstore/ruby-autoload/docs/SingleRefType.md new file mode 100644 index 0000000000..1f997e7bf8 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/SingleRefType.md @@ -0,0 +1,15 @@ +# Petstore::SingleRefType + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::SingleRefType.new() +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/SpecialModelName.md b/samples/client/petstore/ruby-autoload/docs/SpecialModelName.md new file mode 100644 index 0000000000..6a5169191d --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/SpecialModelName.md @@ -0,0 +1,18 @@ +# Petstore::SpecialModelName + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **special_property_name** | **Integer** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::SpecialModelName.new( + special_property_name: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/StoreApi.md b/samples/client/petstore/ruby-autoload/docs/StoreApi.md new file mode 100644 index 0000000000..0bccca0bec --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/StoreApi.md @@ -0,0 +1,270 @@ +# Petstore::StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID | +| [**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status | +| [**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID | +| [**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet | + + +## delete_order + +> delete_order(order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::StoreApi.new +order_id = 'order_id_example' # String | ID of the order that needs to be deleted + +begin + # Delete purchase order by ID + api_instance.delete_order(order_id) +rescue Petstore::ApiError => e + puts "Error when calling StoreApi->delete_order: #{e}" +end +``` + +#### Using the delete_order_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> delete_order_with_http_info(order_id) + +```ruby +begin + # Delete purchase order by ID + data, status_code, headers = api_instance.delete_order_with_http_info(order_id) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling StoreApi->delete_order_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **order_id** | **String** | ID of the order that needs to be deleted | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## get_inventory + +> Hash<String, Integer> get_inventory + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Examples + +```ruby +require 'time' +require 'petstore' +# setup authorization +Petstore.configure do |config| + # Configure API key authorization: api_key + config.api_key['api_key'] = 'YOUR API KEY' + # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) + # config.api_key_prefix['api_key'] = 'Bearer' +end + +api_instance = Petstore::StoreApi.new + +begin + # Returns pet inventories by status + result = api_instance.get_inventory + p result +rescue Petstore::ApiError => e + puts "Error when calling StoreApi->get_inventory: #{e}" +end +``` + +#### Using the get_inventory_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> get_inventory_with_http_info + +```ruby +begin + # Returns pet inventories by status + data, status_code, headers = api_instance.get_inventory_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => Hash<String, Integer> +rescue Petstore::ApiError => e + puts "Error when calling StoreApi->get_inventory_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Hash<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +## get_order_by_id + +> get_order_by_id(order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::StoreApi.new +order_id = 789 # Integer | ID of pet that needs to be fetched + +begin + # Find purchase order by ID + result = api_instance.get_order_by_id(order_id) + p result +rescue Petstore::ApiError => e + puts "Error when calling StoreApi->get_order_by_id: #{e}" +end +``` + +#### Using the get_order_by_id_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> get_order_by_id_with_http_info(order_id) + +```ruby +begin + # Find purchase order by ID + data, status_code, headers = api_instance.get_order_by_id_with_http_info(order_id) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling StoreApi->get_order_by_id_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **order_id** | **Integer** | ID of pet that needs to be fetched | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## place_order + +> place_order(order) + +Place an order for a pet + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::StoreApi.new +order = Petstore::Order.new # Order | order placed for purchasing the pet + +begin + # Place an order for a pet + result = api_instance.place_order(order) + p result +rescue Petstore::ApiError => e + puts "Error when calling StoreApi->place_order: #{e}" +end +``` + +#### Using the place_order_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> place_order_with_http_info(order) + +```ruby +begin + # Place an order for a pet + data, status_code, headers = api_instance.place_order_with_http_info(order) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling StoreApi->place_order_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **order** | [**Order**](Order.md) | order placed for purchasing the pet | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/ruby-autoload/docs/Tag.md b/samples/client/petstore/ruby-autoload/docs/Tag.md new file mode 100644 index 0000000000..f29ee058b0 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/Tag.md @@ -0,0 +1,20 @@ +# Petstore::Tag + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Tag.new( + id: null, + name: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/User.md b/samples/client/petstore/ruby-autoload/docs/User.md new file mode 100644 index 0000000000..1dab27adba --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/User.md @@ -0,0 +1,32 @@ +# Petstore::User + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **username** | **String** | | [optional] | +| **first_name** | **String** | | [optional] | +| **last_name** | **String** | | [optional] | +| **email** | **String** | | [optional] | +| **password** | **String** | | [optional] | +| **phone** | **String** | | [optional] | +| **user_status** | **Integer** | User Status | [optional] | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::User.new( + id: null, + username: null, + first_name: null, + last_name: null, + email: null, + password: null, + phone: null, + user_status: null +) +``` + diff --git a/samples/client/petstore/ruby-autoload/docs/UserApi.md b/samples/client/petstore/ruby-autoload/docs/UserApi.md new file mode 100644 index 0000000000..348f5f9c42 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/docs/UserApi.md @@ -0,0 +1,522 @@ +# Petstore::UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**create_user**](UserApi.md#create_user) | **POST** /user | Create user | +| [**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array | +| [**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array | +| [**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user | +| [**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name | +| [**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system | +| [**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session | +| [**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user | + + +## create_user + +> create_user(user) + +Create user + +This can only be done by the logged in user. + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::UserApi.new +user = Petstore::User.new # User | Created user object + +begin + # Create user + api_instance.create_user(user) +rescue Petstore::ApiError => e + puts "Error when calling UserApi->create_user: #{e}" +end +``` + +#### Using the create_user_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> create_user_with_http_info(user) + +```ruby +begin + # Create user + data, status_code, headers = api_instance.create_user_with_http_info(user) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling UserApi->create_user_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **user** | [**User**](User.md) | Created user object | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +## create_users_with_array_input + +> create_users_with_array_input(user) + +Creates list of users with given input array + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::UserApi.new +user = [Petstore::User.new] # Array | List of user object + +begin + # Creates list of users with given input array + api_instance.create_users_with_array_input(user) +rescue Petstore::ApiError => e + puts "Error when calling UserApi->create_users_with_array_input: #{e}" +end +``` + +#### Using the create_users_with_array_input_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> create_users_with_array_input_with_http_info(user) + +```ruby +begin + # Creates list of users with given input array + data, status_code, headers = api_instance.create_users_with_array_input_with_http_info(user) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling UserApi->create_users_with_array_input_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **user** | [**Array<User>**](User.md) | List of user object | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +## create_users_with_list_input + +> create_users_with_list_input(user) + +Creates list of users with given input array + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::UserApi.new +user = [Petstore::User.new] # Array | List of user object + +begin + # Creates list of users with given input array + api_instance.create_users_with_list_input(user) +rescue Petstore::ApiError => e + puts "Error when calling UserApi->create_users_with_list_input: #{e}" +end +``` + +#### Using the create_users_with_list_input_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> create_users_with_list_input_with_http_info(user) + +```ruby +begin + # Creates list of users with given input array + data, status_code, headers = api_instance.create_users_with_list_input_with_http_info(user) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling UserApi->create_users_with_list_input_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **user** | [**Array<User>**](User.md) | List of user object | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +## delete_user + +> delete_user(username) + +Delete user + +This can only be done by the logged in user. + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::UserApi.new +username = 'username_example' # String | The name that needs to be deleted + +begin + # Delete user + api_instance.delete_user(username) +rescue Petstore::ApiError => e + puts "Error when calling UserApi->delete_user: #{e}" +end +``` + +#### Using the delete_user_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> delete_user_with_http_info(username) + +```ruby +begin + # Delete user + data, status_code, headers = api_instance.delete_user_with_http_info(username) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling UserApi->delete_user_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **username** | **String** | The name that needs to be deleted | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## get_user_by_name + +> get_user_by_name(username) + +Get user by user name + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::UserApi.new +username = 'username_example' # String | The name that needs to be fetched. Use user1 for testing. + +begin + # Get user by user name + result = api_instance.get_user_by_name(username) + p result +rescue Petstore::ApiError => e + puts "Error when calling UserApi->get_user_by_name: #{e}" +end +``` + +#### Using the get_user_by_name_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> get_user_by_name_with_http_info(username) + +```ruby +begin + # Get user by user name + data, status_code, headers = api_instance.get_user_by_name_with_http_info(username) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue Petstore::ApiError => e + puts "Error when calling UserApi->get_user_by_name_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **username** | **String** | The name that needs to be fetched. Use user1 for testing. | | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## login_user + +> String login_user(username, password) + +Logs user into the system + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::UserApi.new +username = 'username_example' # String | The user name for login +password = 'password_example' # String | The password for login in clear text + +begin + # Logs user into the system + result = api_instance.login_user(username, password) + p result +rescue Petstore::ApiError => e + puts "Error when calling UserApi->login_user: #{e}" +end +``` + +#### Using the login_user_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> login_user_with_http_info(username, password) + +```ruby +begin + # Logs user into the system + data, status_code, headers = api_instance.login_user_with_http_info(username, password) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue Petstore::ApiError => e + puts "Error when calling UserApi->login_user_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **username** | **String** | The user name for login | | +| **password** | **String** | The password for login in clear text | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## logout_user + +> logout_user + +Logs out current logged in user session + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::UserApi.new + +begin + # Logs out current logged in user session + api_instance.logout_user +rescue Petstore::ApiError => e + puts "Error when calling UserApi->logout_user: #{e}" +end +``` + +#### Using the logout_user_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> logout_user_with_http_info + +```ruby +begin + # Logs out current logged in user session + data, status_code, headers = api_instance.logout_user_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling UserApi->logout_user_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## update_user + +> update_user(username, user) + +Updated user + +This can only be done by the logged in user. + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::UserApi.new +username = 'username_example' # String | name that need to be deleted +user = Petstore::User.new # User | Updated user object + +begin + # Updated user + api_instance.update_user(username, user) +rescue Petstore::ApiError => e + puts "Error when calling UserApi->update_user: #{e}" +end +``` + +#### Using the update_user_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> update_user_with_http_info(username, user) + +```ruby +begin + # Updated user + data, status_code, headers = api_instance.update_user_with_http_info(username, user) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling UserApi->update_user_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **username** | **String** | name that need to be deleted | | +| **user** | [**User**](User.md) | Updated user object | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + diff --git a/samples/client/petstore/ruby-autoload/git_push.sh b/samples/client/petstore/ruby-autoload/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/client/petstore/ruby-autoload/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/ruby-autoload/lib/petstore.rb b/samples/client/petstore/ruby-autoload/lib/petstore.rb new file mode 100644 index 0000000000..a9e4c3bc9c --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore.rb @@ -0,0 +1,94 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +# Common files +require 'petstore/api_client' +require 'petstore/api_error' +require 'petstore/version' +require 'petstore/configuration' + +# Models +Petstore.autoload :AdditionalPropertiesClass, 'petstore/models/additional_properties_class' +Petstore.autoload :AllOfWithSingleRef, 'petstore/models/all_of_with_single_ref' +Petstore.autoload :Animal, 'petstore/models/animal' +Petstore.autoload :ApiResponse, 'petstore/models/api_response' +Petstore.autoload :ArrayOfArrayOfNumberOnly, 'petstore/models/array_of_array_of_number_only' +Petstore.autoload :ArrayOfNumberOnly, 'petstore/models/array_of_number_only' +Petstore.autoload :ArrayTest, 'petstore/models/array_test' +Petstore.autoload :Capitalization, 'petstore/models/capitalization' +Petstore.autoload :Cat, 'petstore/models/cat' +Petstore.autoload :CatAllOf, 'petstore/models/cat_all_of' +Petstore.autoload :Category, 'petstore/models/category' +Petstore.autoload :ClassModel, 'petstore/models/class_model' +Petstore.autoload :Client, 'petstore/models/client' +Petstore.autoload :DeprecatedObject, 'petstore/models/deprecated_object' +Petstore.autoload :Dog, 'petstore/models/dog' +Petstore.autoload :DogAllOf, 'petstore/models/dog_all_of' +Petstore.autoload :EnumArrays, 'petstore/models/enum_arrays' +Petstore.autoload :EnumClass, 'petstore/models/enum_class' +Petstore.autoload :EnumTest, 'petstore/models/enum_test' +Petstore.autoload :File, 'petstore/models/file' +Petstore.autoload :FileSchemaTestClass, 'petstore/models/file_schema_test_class' +Petstore.autoload :Foo, 'petstore/models/foo' +Petstore.autoload :FooGetDefaultResponse, 'petstore/models/foo_get_default_response' +Petstore.autoload :FormatTest, 'petstore/models/format_test' +Petstore.autoload :HasOnlyReadOnly, 'petstore/models/has_only_read_only' +Petstore.autoload :HealthCheckResult, 'petstore/models/health_check_result' +Petstore.autoload :List, 'petstore/models/list' +Petstore.autoload :MapTest, 'petstore/models/map_test' +Petstore.autoload :MixedPropertiesAndAdditionalPropertiesClass, 'petstore/models/mixed_properties_and_additional_properties_class' +Petstore.autoload :Model200Response, 'petstore/models/model200_response' +Petstore.autoload :ModelReturn, 'petstore/models/model_return' +Petstore.autoload :Name, 'petstore/models/name' +Petstore.autoload :NullableClass, 'petstore/models/nullable_class' +Petstore.autoload :NumberOnly, 'petstore/models/number_only' +Petstore.autoload :ObjectWithDeprecatedFields, 'petstore/models/object_with_deprecated_fields' +Petstore.autoload :Order, 'petstore/models/order' +Petstore.autoload :OuterComposite, 'petstore/models/outer_composite' +Petstore.autoload :OuterEnum, 'petstore/models/outer_enum' +Petstore.autoload :OuterEnumDefaultValue, 'petstore/models/outer_enum_default_value' +Petstore.autoload :OuterEnumInteger, 'petstore/models/outer_enum_integer' +Petstore.autoload :OuterEnumIntegerDefaultValue, 'petstore/models/outer_enum_integer_default_value' +Petstore.autoload :OuterObjectWithEnumProperty, 'petstore/models/outer_object_with_enum_property' +Petstore.autoload :Pet, 'petstore/models/pet' +Petstore.autoload :ReadOnlyFirst, 'petstore/models/read_only_first' +Petstore.autoload :SingleRefType, 'petstore/models/single_ref_type' +Petstore.autoload :SpecialModelName, 'petstore/models/special_model_name' +Petstore.autoload :Tag, 'petstore/models/tag' +Petstore.autoload :User, 'petstore/models/user' + +# APIs +Petstore.autoload :AnotherFakeApi, 'petstore/api/another_fake_api' +Petstore.autoload :DefaultApi, 'petstore/api/default_api' +Petstore.autoload :FakeApi, 'petstore/api/fake_api' +Petstore.autoload :FakeClassnameTags123Api, 'petstore/api/fake_classname_tags123_api' +Petstore.autoload :PetApi, 'petstore/api/pet_api' +Petstore.autoload :StoreApi, 'petstore/api/store_api' +Petstore.autoload :UserApi, 'petstore/api/user_api' + +module Petstore + class << self + # Customize default settings for the SDK using block. + # Petstore.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. + def configure + if block_given? + yield(Configuration.default) + else + Configuration.default + end + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/another_fake_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/another_fake_api.rb new file mode 100644 index 0000000000..c79cd13c2c --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/another_fake_api.rb @@ -0,0 +1,90 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'cgi' + +module Petstore + class AnotherFakeApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # To test special tags + # To test special tags and operation ID starting with number + # @param client [Client] client model + # @param [Hash] opts the optional parameters + # @return [Client] + def call_123_test_special_tags(client, opts = {}) + data, _status_code, _headers = call_123_test_special_tags_with_http_info(client, opts) + data + end + + # To test special tags + # To test special tags and operation ID starting with number + # @param client [Client] client model + # @param [Hash] opts the optional parameters + # @return [Array<(Client, Integer, Hash)>] Client data, response status code and response headers + def call_123_test_special_tags_with_http_info(client, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: AnotherFakeApi.call_123_test_special_tags ...' + end + # verify the required parameter 'client' is set + if @api_client.config.client_side_validation && client.nil? + fail ArgumentError, "Missing the required parameter 'client' when calling AnotherFakeApi.call_123_test_special_tags" + end + # resource path + local_var_path = '/another-fake/dummy' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(client) + + # return_type + return_type = opts[:debug_return_type] || 'Client' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"AnotherFakeApi.call_123_test_special_tags", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: AnotherFakeApi#call_123_test_special_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/default_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/default_api.rb new file mode 100644 index 0000000000..f69fd6ccd6 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/default_api.rb @@ -0,0 +1,75 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'cgi' + +module Petstore + class DefaultApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # @param [Hash] opts the optional parameters + # @return [FooGetDefaultResponse] + def foo_get(opts = {}) + data, _status_code, _headers = foo_get_with_http_info(opts) + data + end + + # @param [Hash] opts the optional parameters + # @return [Array<(FooGetDefaultResponse, Integer, Hash)>] FooGetDefaultResponse data, response status code and response headers + def foo_get_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: DefaultApi.foo_get ...' + end + # resource path + local_var_path = '/foo' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'FooGetDefaultResponse' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"DefaultApi.foo_get", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: DefaultApi#foo_get\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_api.rb new file mode 100644 index 0000000000..196bfc63bf --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_api.rb @@ -0,0 +1,1340 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'cgi' + +module Petstore + class FakeApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Health check endpoint + # @param [Hash] opts the optional parameters + # @return [HealthCheckResult] + def fake_health_get(opts = {}) + data, _status_code, _headers = fake_health_get_with_http_info(opts) + data + end + + # Health check endpoint + # @param [Hash] opts the optional parameters + # @return [Array<(HealthCheckResult, Integer, Hash)>] HealthCheckResult data, response status code and response headers + def fake_health_get_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.fake_health_get ...' + end + # resource path + local_var_path = '/fake/health' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'HealthCheckResult' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.fake_health_get", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#fake_health_get\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # test http signature authentication + # @param pet [Pet] Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @option opts [String] :query_1 query parameter + # @option opts [String] :header_1 header parameter + # @return [nil] + def fake_http_signature_test(pet, opts = {}) + fake_http_signature_test_with_http_info(pet, opts) + nil + end + + # test http signature authentication + # @param pet [Pet] Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @option opts [String] :query_1 query parameter + # @option opts [String] :header_1 header parameter + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def fake_http_signature_test_with_http_info(pet, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.fake_http_signature_test ...' + end + # verify the required parameter 'pet' is set + if @api_client.config.client_side_validation && pet.nil? + fail ArgumentError, "Missing the required parameter 'pet' when calling FakeApi.fake_http_signature_test" + end + # resource path + local_var_path = '/fake/http-signature-test' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_1'] = opts[:'query_1'] if !opts[:'query_1'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json', 'application/xml']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + header_params[:'header_1'] = opts[:'header_1'] if !opts[:'header_1'].nil? + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(pet) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || ['http_signature_test'] + + new_options = opts.merge( + :operation => :"FakeApi.fake_http_signature_test", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#fake_http_signature_test\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test serialization of outer boolean types + # @param [Hash] opts the optional parameters + # @option opts [Boolean] :body Input boolean as post body + # @return [Boolean] + def fake_outer_boolean_serialize(opts = {}) + data, _status_code, _headers = fake_outer_boolean_serialize_with_http_info(opts) + data + end + + # Test serialization of outer boolean types + # @param [Hash] opts the optional parameters + # @option opts [Boolean] :body Input boolean as post body + # @return [Array<(Boolean, Integer, Hash)>] Boolean data, response status code and response headers + def fake_outer_boolean_serialize_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.fake_outer_boolean_serialize ...' + end + # resource path + local_var_path = '/fake/outer/boolean' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['*/*']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'body']) + + # return_type + return_type = opts[:debug_return_type] || 'Boolean' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.fake_outer_boolean_serialize", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#fake_outer_boolean_serialize\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test serialization of object with outer number type + # @param [Hash] opts the optional parameters + # @option opts [OuterComposite] :outer_composite Input composite as post body + # @return [OuterComposite] + def fake_outer_composite_serialize(opts = {}) + data, _status_code, _headers = fake_outer_composite_serialize_with_http_info(opts) + data + end + + # Test serialization of object with outer number type + # @param [Hash] opts the optional parameters + # @option opts [OuterComposite] :outer_composite Input composite as post body + # @return [Array<(OuterComposite, Integer, Hash)>] OuterComposite data, response status code and response headers + def fake_outer_composite_serialize_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.fake_outer_composite_serialize ...' + end + # resource path + local_var_path = '/fake/outer/composite' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['*/*']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'outer_composite']) + + # return_type + return_type = opts[:debug_return_type] || 'OuterComposite' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.fake_outer_composite_serialize", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#fake_outer_composite_serialize\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test serialization of outer number types + # @param [Hash] opts the optional parameters + # @option opts [Float] :body Input number as post body + # @return [Float] + def fake_outer_number_serialize(opts = {}) + data, _status_code, _headers = fake_outer_number_serialize_with_http_info(opts) + data + end + + # Test serialization of outer number types + # @param [Hash] opts the optional parameters + # @option opts [Float] :body Input number as post body + # @return [Array<(Float, Integer, Hash)>] Float data, response status code and response headers + def fake_outer_number_serialize_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.fake_outer_number_serialize ...' + end + # resource path + local_var_path = '/fake/outer/number' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['*/*']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'body']) + + # return_type + return_type = opts[:debug_return_type] || 'Float' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.fake_outer_number_serialize", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#fake_outer_number_serialize\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test serialization of outer string types + # @param [Hash] opts the optional parameters + # @option opts [String] :body Input string as post body + # @return [String] + def fake_outer_string_serialize(opts = {}) + data, _status_code, _headers = fake_outer_string_serialize_with_http_info(opts) + data + end + + # Test serialization of outer string types + # @param [Hash] opts the optional parameters + # @option opts [String] :body Input string as post body + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def fake_outer_string_serialize_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.fake_outer_string_serialize ...' + end + # resource path + local_var_path = '/fake/outer/string' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['*/*']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'body']) + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.fake_outer_string_serialize", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#fake_outer_string_serialize\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test serialization of enum (int) properties with examples + # @param outer_object_with_enum_property [OuterObjectWithEnumProperty] Input enum (int) as post body + # @param [Hash] opts the optional parameters + # @return [OuterObjectWithEnumProperty] + def fake_property_enum_integer_serialize(outer_object_with_enum_property, opts = {}) + data, _status_code, _headers = fake_property_enum_integer_serialize_with_http_info(outer_object_with_enum_property, opts) + data + end + + # Test serialization of enum (int) properties with examples + # @param outer_object_with_enum_property [OuterObjectWithEnumProperty] Input enum (int) as post body + # @param [Hash] opts the optional parameters + # @return [Array<(OuterObjectWithEnumProperty, Integer, Hash)>] OuterObjectWithEnumProperty data, response status code and response headers + def fake_property_enum_integer_serialize_with_http_info(outer_object_with_enum_property, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.fake_property_enum_integer_serialize ...' + end + # verify the required parameter 'outer_object_with_enum_property' is set + if @api_client.config.client_side_validation && outer_object_with_enum_property.nil? + fail ArgumentError, "Missing the required parameter 'outer_object_with_enum_property' when calling FakeApi.fake_property_enum_integer_serialize" + end + # resource path + local_var_path = '/fake/property/enum-int' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['*/*']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(outer_object_with_enum_property) + + # return_type + return_type = opts[:debug_return_type] || 'OuterObjectWithEnumProperty' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.fake_property_enum_integer_serialize", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#fake_property_enum_integer_serialize\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [nil] + def test_body_with_binary(body, opts = {}) + test_body_with_binary_with_http_info(body, opts) + nil + end + + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_body_with_binary_with_http_info(body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_body_with_binary ...' + end + # resource path + local_var_path = '/fake/body-with-binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['image/png']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_body_with_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_body_with_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # For this test, the body for this request must reference a schema named `File`. + # @param file_schema_test_class [FileSchemaTestClass] + # @param [Hash] opts the optional parameters + # @return [nil] + def test_body_with_file_schema(file_schema_test_class, opts = {}) + test_body_with_file_schema_with_http_info(file_schema_test_class, opts) + nil + end + + # For this test, the body for this request must reference a schema named `File`. + # @param file_schema_test_class [FileSchemaTestClass] + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_body_with_file_schema_with_http_info(file_schema_test_class, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_body_with_file_schema ...' + end + # verify the required parameter 'file_schema_test_class' is set + if @api_client.config.client_side_validation && file_schema_test_class.nil? + fail ArgumentError, "Missing the required parameter 'file_schema_test_class' when calling FakeApi.test_body_with_file_schema" + end + # resource path + local_var_path = '/fake/body-with-file-schema' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(file_schema_test_class) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_body_with_file_schema", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_body_with_file_schema\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # @param query [String] + # @param user [User] + # @param [Hash] opts the optional parameters + # @return [nil] + def test_body_with_query_params(query, user, opts = {}) + test_body_with_query_params_with_http_info(query, user, opts) + nil + end + + # @param query [String] + # @param user [User] + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_body_with_query_params_with_http_info(query, user, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_body_with_query_params ...' + end + # verify the required parameter 'query' is set + if @api_client.config.client_side_validation && query.nil? + fail ArgumentError, "Missing the required parameter 'query' when calling FakeApi.test_body_with_query_params" + end + # verify the required parameter 'user' is set + if @api_client.config.client_side_validation && user.nil? + fail ArgumentError, "Missing the required parameter 'user' when calling FakeApi.test_body_with_query_params" + end + # resource path + local_var_path = '/fake/body-with-query-params' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query'] = query + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(user) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_body_with_query_params", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_body_with_query_params\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # To test \"client\" model + # To test \"client\" model + # @param client [Client] client model + # @param [Hash] opts the optional parameters + # @return [Client] + def test_client_model(client, opts = {}) + data, _status_code, _headers = test_client_model_with_http_info(client, opts) + data + end + + # To test \"client\" model + # To test \"client\" model + # @param client [Client] client model + # @param [Hash] opts the optional parameters + # @return [Array<(Client, Integer, Hash)>] Client data, response status code and response headers + def test_client_model_with_http_info(client, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_client_model ...' + end + # verify the required parameter 'client' is set + if @api_client.config.client_side_validation && client.nil? + fail ArgumentError, "Missing the required parameter 'client' when calling FakeApi.test_client_model" + end + # resource path + local_var_path = '/fake' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(client) + + # return_type + return_type = opts[:debug_return_type] || 'Client' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_client_model", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_client_model\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # @param number [Float] None + # @param double [Float] None + # @param pattern_without_delimiter [String] None + # @param byte [String] None + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer None + # @option opts [Integer] :int32 None + # @option opts [Integer] :int64 None + # @option opts [Float] :float None + # @option opts [String] :string None + # @option opts [File] :binary None + # @option opts [Date] :date None + # @option opts [Time] :date_time None + # @option opts [String] :password None + # @option opts [String] :callback None + # @return [nil] + def test_endpoint_parameters(number, double, pattern_without_delimiter, byte, opts = {}) + test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts) + nil + end + + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # @param number [Float] None + # @param double [Float] None + # @param pattern_without_delimiter [String] None + # @param byte [String] None + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer None + # @option opts [Integer] :int32 None + # @option opts [Integer] :int64 None + # @option opts [Float] :float None + # @option opts [String] :string None + # @option opts [File] :binary None + # @option opts [Date] :date None + # @option opts [Time] :date_time None + # @option opts [String] :password None + # @option opts [String] :callback None + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_endpoint_parameters ...' + end + # verify the required parameter 'number' is set + if @api_client.config.client_side_validation && number.nil? + fail ArgumentError, "Missing the required parameter 'number' when calling FakeApi.test_endpoint_parameters" + end + if @api_client.config.client_side_validation && number > 543.2 + fail ArgumentError, 'invalid value for "number" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 543.2.' + end + + if @api_client.config.client_side_validation && number < 32.1 + fail ArgumentError, 'invalid value for "number" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 32.1.' + end + + # verify the required parameter 'double' is set + if @api_client.config.client_side_validation && double.nil? + fail ArgumentError, "Missing the required parameter 'double' when calling FakeApi.test_endpoint_parameters" + end + if @api_client.config.client_side_validation && double > 123.4 + fail ArgumentError, 'invalid value for "double" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 123.4.' + end + + if @api_client.config.client_side_validation && double < 67.8 + fail ArgumentError, 'invalid value for "double" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 67.8.' + end + + # verify the required parameter 'pattern_without_delimiter' is set + if @api_client.config.client_side_validation && pattern_without_delimiter.nil? + fail ArgumentError, "Missing the required parameter 'pattern_without_delimiter' when calling FakeApi.test_endpoint_parameters" + end + pattern = Regexp.new(/^[A-Z].*/) + if @api_client.config.client_side_validation && pattern_without_delimiter !~ pattern + fail ArgumentError, "invalid value for 'pattern_without_delimiter' when calling FakeApi.test_endpoint_parameters, must conform to the pattern #{pattern}." + end + + # verify the required parameter 'byte' is set + if @api_client.config.client_side_validation && byte.nil? + fail ArgumentError, "Missing the required parameter 'byte' when calling FakeApi.test_endpoint_parameters" + end + if @api_client.config.client_side_validation && !opts[:'integer'].nil? && opts[:'integer'] > 100 + fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 100.' + end + + if @api_client.config.client_side_validation && !opts[:'integer'].nil? && opts[:'integer'] < 10 + fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 10.' + end + + if @api_client.config.client_side_validation && !opts[:'int32'].nil? && opts[:'int32'] > 200 + fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 200.' + end + + if @api_client.config.client_side_validation && !opts[:'int32'].nil? && opts[:'int32'] < 20 + fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 20.' + end + + if @api_client.config.client_side_validation && !opts[:'float'].nil? && opts[:'float'] > 987.6 + fail ArgumentError, 'invalid value for "opts[:"float"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 987.6.' + end + + pattern = Regexp.new(/[a-z]/i) + if @api_client.config.client_side_validation && !opts[:'string'].nil? && opts[:'string'] !~ pattern + fail ArgumentError, "invalid value for 'opts[:\"string\"]' when calling FakeApi.test_endpoint_parameters, must conform to the pattern #{pattern}." + end + + if @api_client.config.client_side_validation && !opts[:'password'].nil? && opts[:'password'].to_s.length > 64 + fail ArgumentError, 'invalid value for "opts[:"password"]" when calling FakeApi.test_endpoint_parameters, the character length must be smaller than or equal to 64.' + end + + if @api_client.config.client_side_validation && !opts[:'password'].nil? && opts[:'password'].to_s.length < 10 + fail ArgumentError, 'invalid value for "opts[:"password"]" when calling FakeApi.test_endpoint_parameters, the character length must be great than or equal to 10.' + end + + # resource path + local_var_path = '/fake' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['number'] = number + form_params['double'] = double + form_params['pattern_without_delimiter'] = pattern_without_delimiter + form_params['byte'] = byte + form_params['integer'] = opts[:'integer'] if !opts[:'integer'].nil? + form_params['int32'] = opts[:'int32'] if !opts[:'int32'].nil? + form_params['int64'] = opts[:'int64'] if !opts[:'int64'].nil? + form_params['float'] = opts[:'float'] if !opts[:'float'].nil? + form_params['string'] = opts[:'string'] if !opts[:'string'].nil? + form_params['binary'] = opts[:'binary'] if !opts[:'binary'].nil? + form_params['date'] = opts[:'date'] if !opts[:'date'].nil? + form_params['dateTime'] = opts[:'date_time'] if !opts[:'date_time'].nil? + form_params['password'] = opts[:'password'] if !opts[:'password'].nil? + form_params['callback'] = opts[:'callback'] if !opts[:'callback'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || ['http_basic_test'] + + new_options = opts.merge( + :operation => :"FakeApi.test_endpoint_parameters", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_endpoint_parameters\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # To test enum parameters + # To test enum parameters + # @param [Hash] opts the optional parameters + # @option opts [Array] :enum_header_string_array Header parameter enum test (string array) + # @option opts [String] :enum_header_string Header parameter enum test (string) (default to '-efg') + # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) + # @option opts [String] :enum_query_string Query parameter enum test (string) (default to '-efg') + # @option opts [Integer] :enum_query_integer Query parameter enum test (double) + # @option opts [Float] :enum_query_double Query parameter enum test (double) + # @option opts [Array] :enum_query_model_array + # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) (default to '$') + # @option opts [String] :enum_form_string Form parameter enum test (string) (default to '-efg') + # @return [nil] + def test_enum_parameters(opts = {}) + test_enum_parameters_with_http_info(opts) + nil + end + + # To test enum parameters + # To test enum parameters + # @param [Hash] opts the optional parameters + # @option opts [Array] :enum_header_string_array Header parameter enum test (string array) + # @option opts [String] :enum_header_string Header parameter enum test (string) (default to '-efg') + # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) + # @option opts [String] :enum_query_string Query parameter enum test (string) (default to '-efg') + # @option opts [Integer] :enum_query_integer Query parameter enum test (double) + # @option opts [Float] :enum_query_double Query parameter enum test (double) + # @option opts [Array] :enum_query_model_array + # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) (default to '$') + # @option opts [String] :enum_form_string Form parameter enum test (string) (default to '-efg') + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_enum_parameters_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_enum_parameters ...' + end + allowable_values = [">", "$"] + if @api_client.config.client_side_validation && opts[:'enum_header_string_array'] && !opts[:'enum_header_string_array'].all? { |item| allowable_values.include?(item) } + fail ArgumentError, "invalid value for \"enum_header_string_array\", must include one of #{allowable_values}" + end + allowable_values = ["_abc", "-efg", "(xyz)"] + if @api_client.config.client_side_validation && opts[:'enum_header_string'] && !allowable_values.include?(opts[:'enum_header_string']) + fail ArgumentError, "invalid value for \"enum_header_string\", must be one of #{allowable_values}" + end + allowable_values = [">", "$"] + if @api_client.config.client_side_validation && opts[:'enum_query_string_array'] && !opts[:'enum_query_string_array'].all? { |item| allowable_values.include?(item) } + fail ArgumentError, "invalid value for \"enum_query_string_array\", must include one of #{allowable_values}" + end + allowable_values = ["_abc", "-efg", "(xyz)"] + if @api_client.config.client_side_validation && opts[:'enum_query_string'] && !allowable_values.include?(opts[:'enum_query_string']) + fail ArgumentError, "invalid value for \"enum_query_string\", must be one of #{allowable_values}" + end + allowable_values = [1, -2] + if @api_client.config.client_side_validation && opts[:'enum_query_integer'] && !allowable_values.include?(opts[:'enum_query_integer']) + fail ArgumentError, "invalid value for \"enum_query_integer\", must be one of #{allowable_values}" + end + allowable_values = [1.1, -1.2] + if @api_client.config.client_side_validation && opts[:'enum_query_double'] && !allowable_values.include?(opts[:'enum_query_double']) + fail ArgumentError, "invalid value for \"enum_query_double\", must be one of #{allowable_values}" + end + allowable_values = [">", "$"] + if @api_client.config.client_side_validation && opts[:'enum_form_string_array'] && !opts[:'enum_form_string_array'].all? { |item| allowable_values.include?(item) } + fail ArgumentError, "invalid value for \"enum_form_string_array\", must include one of #{allowable_values}" + end + allowable_values = ["_abc", "-efg", "(xyz)"] + if @api_client.config.client_side_validation && opts[:'enum_form_string'] && !allowable_values.include?(opts[:'enum_form_string']) + fail ArgumentError, "invalid value for \"enum_form_string\", must be one of #{allowable_values}" + end + # resource path + local_var_path = '/fake' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'enum_query_string_array'] = @api_client.build_collection_param(opts[:'enum_query_string_array'], :multi) if !opts[:'enum_query_string_array'].nil? + query_params[:'enum_query_string'] = opts[:'enum_query_string'] if !opts[:'enum_query_string'].nil? + query_params[:'enum_query_integer'] = opts[:'enum_query_integer'] if !opts[:'enum_query_integer'].nil? + query_params[:'enum_query_double'] = opts[:'enum_query_double'] if !opts[:'enum_query_double'].nil? + query_params[:'enum_query_model_array'] = @api_client.build_collection_param(opts[:'enum_query_model_array'], :multi) if !opts[:'enum_query_model_array'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + header_params[:'enum_header_string_array'] = @api_client.build_collection_param(opts[:'enum_header_string_array'], :csv) if !opts[:'enum_header_string_array'].nil? + header_params[:'enum_header_string'] = opts[:'enum_header_string'] if !opts[:'enum_header_string'].nil? + + # form parameters + form_params = opts[:form_params] || {} + form_params['enum_form_string_array'] = @api_client.build_collection_param(opts[:'enum_form_string_array'], :csv) if !opts[:'enum_form_string_array'].nil? + form_params['enum_form_string'] = opts[:'enum_form_string'] if !opts[:'enum_form_string'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_enum_parameters", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_enum_parameters\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Fake endpoint to test group parameters (optional) + # Fake endpoint to test group parameters (optional) + # @param [Hash] opts the parameters + # @option opts [Integer] :required_string_group Required String in group parameters (required) + # @option opts [Boolean] :required_boolean_group Required Boolean in group parameters (required) + # @option opts [Integer] :required_int64_group Required Integer in group parameters (required) + # @option opts [Integer] :string_group String in group parameters + # @option opts [Boolean] :boolean_group Boolean in group parameters + # @option opts [Integer] :int64_group Integer in group parameters + # @return [nil] + def test_group_parameters(opts = {}) + test_group_parameters_with_http_info(opts) + nil + end + + # Fake endpoint to test group parameters (optional) + # Fake endpoint to test group parameters (optional) + # @param [Hash] opts the parameters + # @option opts [Integer] :required_string_group Required String in group parameters (required) + # @option opts [Boolean] :required_boolean_group Required Boolean in group parameters (required) + # @option opts [Integer] :required_int64_group Required Integer in group parameters (required) + # @option opts [Integer] :string_group String in group parameters + # @option opts [Boolean] :boolean_group Boolean in group parameters + # @option opts [Integer] :int64_group Integer in group parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_group_parameters_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_group_parameters ...' + end + # unbox the parameters from the hash + required_string_group = opts[:'required_string_group'] + required_boolean_group = opts[:'required_boolean_group'] + required_int64_group = opts[:'required_int64_group'] + # verify the required parameter 'required_string_group' is set + if @api_client.config.client_side_validation && required_string_group.nil? + fail ArgumentError, "Missing the required parameter 'required_string_group' when calling FakeApi.test_group_parameters" + end + # verify the required parameter 'required_boolean_group' is set + if @api_client.config.client_side_validation && required_boolean_group.nil? + fail ArgumentError, "Missing the required parameter 'required_boolean_group' when calling FakeApi.test_group_parameters" + end + # verify the required parameter 'required_int64_group' is set + if @api_client.config.client_side_validation && required_int64_group.nil? + fail ArgumentError, "Missing the required parameter 'required_int64_group' when calling FakeApi.test_group_parameters" + end + # resource path + local_var_path = '/fake' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'required_string_group'] = required_string_group + query_params[:'required_int64_group'] = required_int64_group + query_params[:'string_group'] = opts[:'string_group'] if !opts[:'string_group'].nil? + query_params[:'int64_group'] = opts[:'int64_group'] if !opts[:'int64_group'].nil? + + # header parameters + header_params = opts[:header_params] || {} + header_params[:'required_boolean_group'] = required_boolean_group + header_params[:'boolean_group'] = opts[:'boolean_group'] if !opts[:'boolean_group'].nil? + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || ['bearer_test'] + + new_options = opts.merge( + :operation => :"FakeApi.test_group_parameters", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_group_parameters\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # test inline additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [nil] + def test_inline_additional_properties(request_body, opts = {}) + test_inline_additional_properties_with_http_info(request_body, opts) + nil + end + + # test inline additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_inline_additional_properties_with_http_info(request_body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_inline_additional_properties ...' + end + # verify the required parameter 'request_body' is set + if @api_client.config.client_side_validation && request_body.nil? + fail ArgumentError, "Missing the required parameter 'request_body' when calling FakeApi.test_inline_additional_properties" + end + # resource path + local_var_path = '/fake/inline-additionalProperties' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(request_body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_inline_additional_properties", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_inline_additional_properties\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # test json serialization of form data + # + # @param param [String] field1 + # @param param2 [String] field2 + # @param [Hash] opts the optional parameters + # @return [nil] + def test_json_form_data(param, param2, opts = {}) + test_json_form_data_with_http_info(param, param2, opts) + nil + end + + # test json serialization of form data + # + # @param param [String] field1 + # @param param2 [String] field2 + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_json_form_data_with_http_info(param, param2, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_json_form_data ...' + end + # verify the required parameter 'param' is set + if @api_client.config.client_side_validation && param.nil? + fail ArgumentError, "Missing the required parameter 'param' when calling FakeApi.test_json_form_data" + end + # verify the required parameter 'param2' is set + if @api_client.config.client_side_validation && param2.nil? + fail ArgumentError, "Missing the required parameter 'param2' when calling FakeApi.test_json_form_data" + end + # resource path + local_var_path = '/fake/jsonFormData' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['param'] = param + form_params['param2'] = param2 + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_json_form_data", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_json_form_data\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # To test the collection format in query parameters + # @param pipe [Array] + # @param ioutil [Array] + # @param http [Array] + # @param url [Array] + # @param context [Array] + # @param allow_empty [String] + # @param [Hash] opts the optional parameters + # @option opts [Hash] :language + # @return [nil] + def test_query_parameter_collection_format(pipe, ioutil, http, url, context, allow_empty, opts = {}) + test_query_parameter_collection_format_with_http_info(pipe, ioutil, http, url, context, allow_empty, opts) + nil + end + + # To test the collection format in query parameters + # @param pipe [Array] + # @param ioutil [Array] + # @param http [Array] + # @param url [Array] + # @param context [Array] + # @param allow_empty [String] + # @param [Hash] opts the optional parameters + # @option opts [Hash] :language + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_query_parameter_collection_format_with_http_info(pipe, ioutil, http, url, context, allow_empty, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_query_parameter_collection_format ...' + end + # verify the required parameter 'pipe' is set + if @api_client.config.client_side_validation && pipe.nil? + fail ArgumentError, "Missing the required parameter 'pipe' when calling FakeApi.test_query_parameter_collection_format" + end + # verify the required parameter 'ioutil' is set + if @api_client.config.client_side_validation && ioutil.nil? + fail ArgumentError, "Missing the required parameter 'ioutil' when calling FakeApi.test_query_parameter_collection_format" + end + # verify the required parameter 'http' is set + if @api_client.config.client_side_validation && http.nil? + fail ArgumentError, "Missing the required parameter 'http' when calling FakeApi.test_query_parameter_collection_format" + end + # verify the required parameter 'url' is set + if @api_client.config.client_side_validation && url.nil? + fail ArgumentError, "Missing the required parameter 'url' when calling FakeApi.test_query_parameter_collection_format" + end + # verify the required parameter 'context' is set + if @api_client.config.client_side_validation && context.nil? + fail ArgumentError, "Missing the required parameter 'context' when calling FakeApi.test_query_parameter_collection_format" + end + # verify the required parameter 'allow_empty' is set + if @api_client.config.client_side_validation && allow_empty.nil? + fail ArgumentError, "Missing the required parameter 'allow_empty' when calling FakeApi.test_query_parameter_collection_format" + end + # resource path + local_var_path = '/fake/test-query-parameters' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'pipe'] = @api_client.build_collection_param(pipe, :pipes) + query_params[:'ioutil'] = @api_client.build_collection_param(ioutil, :csv) + query_params[:'http'] = @api_client.build_collection_param(http, :ssv) + query_params[:'url'] = @api_client.build_collection_param(url, :csv) + query_params[:'context'] = @api_client.build_collection_param(context, :multi) + query_params[:'allowEmpty'] = allow_empty + query_params[:'language'] = opts[:'language'] if !opts[:'language'].nil? + + # header parameters + header_params = opts[:header_params] || {} + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_query_parameter_collection_format", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_query_parameter_collection_format\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_classname_tags123_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_classname_tags123_api.rb new file mode 100644 index 0000000000..c4a81cc33b --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_classname_tags123_api.rb @@ -0,0 +1,90 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'cgi' + +module Petstore + class FakeClassnameTags123Api + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # To test class name in snake case + # To test class name in snake case + # @param client [Client] client model + # @param [Hash] opts the optional parameters + # @return [Client] + def test_classname(client, opts = {}) + data, _status_code, _headers = test_classname_with_http_info(client, opts) + data + end + + # To test class name in snake case + # To test class name in snake case + # @param client [Client] client model + # @param [Hash] opts the optional parameters + # @return [Array<(Client, Integer, Hash)>] Client data, response status code and response headers + def test_classname_with_http_info(client, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeClassnameTags123Api.test_classname ...' + end + # verify the required parameter 'client' is set + if @api_client.config.client_side_validation && client.nil? + fail ArgumentError, "Missing the required parameter 'client' when calling FakeClassnameTags123Api.test_classname" + end + # resource path + local_var_path = '/fake_classname_test' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(client) + + # return_type + return_type = opts[:debug_return_type] || 'Client' + + # auth_names + auth_names = opts[:debug_auth_names] || ['api_key_query'] + + new_options = opts.merge( + :operation => :"FakeClassnameTags123Api.test_classname", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeClassnameTags123Api#test_classname\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/pet_api.rb new file mode 100644 index 0000000000..9095893694 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/pet_api.rb @@ -0,0 +1,633 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'cgi' + +module Petstore + class PetApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Add a new pet to the store + # + # @param pet [Pet] Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @return [nil] + def add_pet(pet, opts = {}) + add_pet_with_http_info(pet, opts) + nil + end + + # Add a new pet to the store + # + # @param pet [Pet] Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def add_pet_with_http_info(pet, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PetApi.add_pet ...' + end + # verify the required parameter 'pet' is set + if @api_client.config.client_side_validation && pet.nil? + fail ArgumentError, "Missing the required parameter 'pet' when calling PetApi.add_pet" + end + # resource path + local_var_path = '/pet' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json', 'application/xml']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(pet) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || ['petstore_auth'] + + new_options = opts.merge( + :operation => :"PetApi.add_pet", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#add_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Deletes a pet + # + # @param pet_id [Integer] Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [String] :api_key + # @return [nil] + def delete_pet(pet_id, opts = {}) + delete_pet_with_http_info(pet_id, opts) + nil + end + + # Deletes a pet + # + # @param pet_id [Integer] Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [String] :api_key + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def delete_pet_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PetApi.delete_pet ...' + end + # verify the required parameter 'pet_id' is set + if @api_client.config.client_side_validation && pet_id.nil? + fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.delete_pet" + end + # resource path + local_var_path = '/pet/{petId}'.sub('{' + 'petId' + '}', CGI.escape(pet_id.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + header_params[:'api_key'] = opts[:'api_key'] if !opts[:'api_key'].nil? + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || ['petstore_auth'] + + new_options = opts.merge( + :operation => :"PetApi.delete_pet", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#delete_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Finds Pets by status + # Multiple status values can be provided with comma separated strings + # @param status [Array] Status values that need to be considered for filter + # @param [Hash] opts the optional parameters + # @return [Array] + def find_pets_by_status(status, opts = {}) + data, _status_code, _headers = find_pets_by_status_with_http_info(status, opts) + data + end + + # Finds Pets by status + # Multiple status values can be provided with comma separated strings + # @param status [Array] Status values that need to be considered for filter + # @param [Hash] opts the optional parameters + # @return [Array<(Array, Integer, Hash)>] Array data, response status code and response headers + def find_pets_by_status_with_http_info(status, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PetApi.find_pets_by_status ...' + end + # verify the required parameter 'status' is set + if @api_client.config.client_side_validation && status.nil? + fail ArgumentError, "Missing the required parameter 'status' when calling PetApi.find_pets_by_status" + end + # resource path + local_var_path = '/pet/findByStatus' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'status'] = @api_client.build_collection_param(status, :csv) + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Array' + + # auth_names + auth_names = opts[:debug_auth_names] || ['petstore_auth'] + + new_options = opts.merge( + :operation => :"PetApi.find_pets_by_status", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#find_pets_by_status\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Finds Pets by tags + # Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + # @param tags [Array] Tags to filter by + # @param [Hash] opts the optional parameters + # @return [Array] + def find_pets_by_tags(tags, opts = {}) + data, _status_code, _headers = find_pets_by_tags_with_http_info(tags, opts) + data + end + + # Finds Pets by tags + # Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + # @param tags [Array] Tags to filter by + # @param [Hash] opts the optional parameters + # @return [Array<(Array, Integer, Hash)>] Array data, response status code and response headers + def find_pets_by_tags_with_http_info(tags, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PetApi.find_pets_by_tags ...' + end + # verify the required parameter 'tags' is set + if @api_client.config.client_side_validation && tags.nil? + fail ArgumentError, "Missing the required parameter 'tags' when calling PetApi.find_pets_by_tags" + end + # resource path + local_var_path = '/pet/findByTags' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'tags'] = @api_client.build_collection_param(tags, :csv) + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Array' + + # auth_names + auth_names = opts[:debug_auth_names] || ['petstore_auth'] + + new_options = opts.merge( + :operation => :"PetApi.find_pets_by_tags", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#find_pets_by_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Find pet by ID + # Returns a single pet + # @param pet_id [Integer] ID of pet to return + # @param [Hash] opts the optional parameters + # @return [Pet] + def get_pet_by_id(pet_id, opts = {}) + data, _status_code, _headers = get_pet_by_id_with_http_info(pet_id, opts) + data + end + + # Find pet by ID + # Returns a single pet + # @param pet_id [Integer] ID of pet to return + # @param [Hash] opts the optional parameters + # @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers + def get_pet_by_id_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PetApi.get_pet_by_id ...' + end + # verify the required parameter 'pet_id' is set + if @api_client.config.client_side_validation && pet_id.nil? + fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.get_pet_by_id" + end + # resource path + local_var_path = '/pet/{petId}'.sub('{' + 'petId' + '}', CGI.escape(pet_id.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Pet' + + # auth_names + auth_names = opts[:debug_auth_names] || ['api_key'] + + new_options = opts.merge( + :operation => :"PetApi.get_pet_by_id", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#get_pet_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Update an existing pet + # + # @param pet [Pet] Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @return [nil] + def update_pet(pet, opts = {}) + update_pet_with_http_info(pet, opts) + nil + end + + # Update an existing pet + # + # @param pet [Pet] Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def update_pet_with_http_info(pet, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PetApi.update_pet ...' + end + # verify the required parameter 'pet' is set + if @api_client.config.client_side_validation && pet.nil? + fail ArgumentError, "Missing the required parameter 'pet' when calling PetApi.update_pet" + end + # resource path + local_var_path = '/pet' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json', 'application/xml']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(pet) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || ['petstore_auth'] + + new_options = opts.merge( + :operation => :"PetApi.update_pet", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#update_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Updates a pet in the store with form data + # + # @param pet_id [Integer] ID of pet that needs to be updated + # @param [Hash] opts the optional parameters + # @option opts [String] :name Updated name of the pet + # @option opts [String] :status Updated status of the pet + # @return [nil] + def update_pet_with_form(pet_id, opts = {}) + update_pet_with_form_with_http_info(pet_id, opts) + nil + end + + # Updates a pet in the store with form data + # + # @param pet_id [Integer] ID of pet that needs to be updated + # @param [Hash] opts the optional parameters + # @option opts [String] :name Updated name of the pet + # @option opts [String] :status Updated status of the pet + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def update_pet_with_form_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PetApi.update_pet_with_form ...' + end + # verify the required parameter 'pet_id' is set + if @api_client.config.client_side_validation && pet_id.nil? + fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.update_pet_with_form" + end + # resource path + local_var_path = '/pet/{petId}'.sub('{' + 'petId' + '}', CGI.escape(pet_id.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['name'] = opts[:'name'] if !opts[:'name'].nil? + form_params['status'] = opts[:'status'] if !opts[:'status'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || ['petstore_auth'] + + new_options = opts.merge( + :operation => :"PetApi.update_pet_with_form", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#update_pet_with_form\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # uploads an image + # + # @param pet_id [Integer] ID of pet to update + # @param [Hash] opts the optional parameters + # @option opts [String] :additional_metadata Additional data to pass to server + # @option opts [File] :file file to upload + # @return [ApiResponse] + def upload_file(pet_id, opts = {}) + data, _status_code, _headers = upload_file_with_http_info(pet_id, opts) + data + end + + # uploads an image + # + # @param pet_id [Integer] ID of pet to update + # @param [Hash] opts the optional parameters + # @option opts [String] :additional_metadata Additional data to pass to server + # @option opts [File] :file file to upload + # @return [Array<(ApiResponse, Integer, Hash)>] ApiResponse data, response status code and response headers + def upload_file_with_http_info(pet_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PetApi.upload_file ...' + end + # verify the required parameter 'pet_id' is set + if @api_client.config.client_side_validation && pet_id.nil? + fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.upload_file" + end + # resource path + local_var_path = '/pet/{petId}/uploadImage'.sub('{' + 'petId' + '}', CGI.escape(pet_id.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['multipart/form-data']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['additionalMetadata'] = opts[:'additional_metadata'] if !opts[:'additional_metadata'].nil? + form_params['file'] = opts[:'file'] if !opts[:'file'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'ApiResponse' + + # auth_names + auth_names = opts[:debug_auth_names] || ['petstore_auth'] + + new_options = opts.merge( + :operation => :"PetApi.upload_file", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#upload_file\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # uploads an image (required) + # + # @param pet_id [Integer] ID of pet to update + # @param required_file [File] file to upload + # @param [Hash] opts the optional parameters + # @option opts [String] :additional_metadata Additional data to pass to server + # @return [ApiResponse] + def upload_file_with_required_file(pet_id, required_file, opts = {}) + data, _status_code, _headers = upload_file_with_required_file_with_http_info(pet_id, required_file, opts) + data + end + + # uploads an image (required) + # + # @param pet_id [Integer] ID of pet to update + # @param required_file [File] file to upload + # @param [Hash] opts the optional parameters + # @option opts [String] :additional_metadata Additional data to pass to server + # @return [Array<(ApiResponse, Integer, Hash)>] ApiResponse data, response status code and response headers + def upload_file_with_required_file_with_http_info(pet_id, required_file, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PetApi.upload_file_with_required_file ...' + end + # verify the required parameter 'pet_id' is set + if @api_client.config.client_side_validation && pet_id.nil? + fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.upload_file_with_required_file" + end + # verify the required parameter 'required_file' is set + if @api_client.config.client_side_validation && required_file.nil? + fail ArgumentError, "Missing the required parameter 'required_file' when calling PetApi.upload_file_with_required_file" + end + # resource path + local_var_path = '/fake/{petId}/uploadImageWithRequiredFile'.sub('{' + 'petId' + '}', CGI.escape(pet_id.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['multipart/form-data']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['requiredFile'] = required_file + form_params['additionalMetadata'] = opts[:'additional_metadata'] if !opts[:'additional_metadata'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'ApiResponse' + + # auth_names + auth_names = opts[:debug_auth_names] || ['petstore_auth'] + + new_options = opts.merge( + :operation => :"PetApi.upload_file_with_required_file", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PetApi#upload_file_with_required_file\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/store_api.rb new file mode 100644 index 0000000000..687557a4a4 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/store_api.rb @@ -0,0 +1,279 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'cgi' + +module Petstore + class StoreApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order_id [String] ID of the order that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [nil] + def delete_order(order_id, opts = {}) + delete_order_with_http_info(order_id, opts) + nil + end + + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order_id [String] ID of the order that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def delete_order_with_http_info(order_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: StoreApi.delete_order ...' + end + # verify the required parameter 'order_id' is set + if @api_client.config.client_side_validation && order_id.nil? + fail ArgumentError, "Missing the required parameter 'order_id' when calling StoreApi.delete_order" + end + # resource path + local_var_path = '/store/order/{order_id}'.sub('{' + 'order_id' + '}', CGI.escape(order_id.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"StoreApi.delete_order", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#delete_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return [Hash] + def get_inventory(opts = {}) + data, _status_code, _headers = get_inventory_with_http_info(opts) + data + end + + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return [Array<(Hash, Integer, Hash)>] Hash data, response status code and response headers + def get_inventory_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: StoreApi.get_inventory ...' + end + # resource path + local_var_path = '/store/inventory' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Hash' + + # auth_names + auth_names = opts[:debug_auth_names] || ['api_key'] + + new_options = opts.merge( + :operation => :"StoreApi.get_inventory", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#get_inventory\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id [Integer] ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [Order] + def get_order_by_id(order_id, opts = {}) + data, _status_code, _headers = get_order_by_id_with_http_info(order_id, opts) + data + end + + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id [Integer] ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [Array<(Order, Integer, Hash)>] Order data, response status code and response headers + def get_order_by_id_with_http_info(order_id, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: StoreApi.get_order_by_id ...' + end + # verify the required parameter 'order_id' is set + if @api_client.config.client_side_validation && order_id.nil? + fail ArgumentError, "Missing the required parameter 'order_id' when calling StoreApi.get_order_by_id" + end + if @api_client.config.client_side_validation && order_id > 5 + fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be smaller than or equal to 5.' + end + + if @api_client.config.client_side_validation && order_id < 1 + fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be greater than or equal to 1.' + end + + # resource path + local_var_path = '/store/order/{order_id}'.sub('{' + 'order_id' + '}', CGI.escape(order_id.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'Order' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"StoreApi.get_order_by_id", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#get_order_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Place an order for a pet + # + # @param order [Order] order placed for purchasing the pet + # @param [Hash] opts the optional parameters + # @return [Order] + def place_order(order, opts = {}) + data, _status_code, _headers = place_order_with_http_info(order, opts) + data + end + + # Place an order for a pet + # + # @param order [Order] order placed for purchasing the pet + # @param [Hash] opts the optional parameters + # @return [Array<(Order, Integer, Hash)>] Order data, response status code and response headers + def place_order_with_http_info(order, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: StoreApi.place_order ...' + end + # verify the required parameter 'order' is set + if @api_client.config.client_side_validation && order.nil? + fail ArgumentError, "Missing the required parameter 'order' when calling StoreApi.place_order" + end + # resource path + local_var_path = '/store/order' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(order) + + # return_type + return_type = opts[:debug_return_type] || 'Order' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"StoreApi.place_order", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: StoreApi#place_order\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/user_api.rb new file mode 100644 index 0000000000..17bda2dbaa --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/user_api.rb @@ -0,0 +1,542 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'cgi' + +module Petstore + class UserApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Create user + # This can only be done by the logged in user. + # @param user [User] Created user object + # @param [Hash] opts the optional parameters + # @return [nil] + def create_user(user, opts = {}) + create_user_with_http_info(user, opts) + nil + end + + # Create user + # This can only be done by the logged in user. + # @param user [User] Created user object + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def create_user_with_http_info(user, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UserApi.create_user ...' + end + # verify the required parameter 'user' is set + if @api_client.config.client_side_validation && user.nil? + fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.create_user" + end + # resource path + local_var_path = '/user' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(user) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"UserApi.create_user", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#create_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Creates list of users with given input array + # + # @param user [Array] List of user object + # @param [Hash] opts the optional parameters + # @return [nil] + def create_users_with_array_input(user, opts = {}) + create_users_with_array_input_with_http_info(user, opts) + nil + end + + # Creates list of users with given input array + # + # @param user [Array] List of user object + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def create_users_with_array_input_with_http_info(user, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UserApi.create_users_with_array_input ...' + end + # verify the required parameter 'user' is set + if @api_client.config.client_side_validation && user.nil? + fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.create_users_with_array_input" + end + # resource path + local_var_path = '/user/createWithArray' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(user) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"UserApi.create_users_with_array_input", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#create_users_with_array_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Creates list of users with given input array + # + # @param user [Array] List of user object + # @param [Hash] opts the optional parameters + # @return [nil] + def create_users_with_list_input(user, opts = {}) + create_users_with_list_input_with_http_info(user, opts) + nil + end + + # Creates list of users with given input array + # + # @param user [Array] List of user object + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def create_users_with_list_input_with_http_info(user, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UserApi.create_users_with_list_input ...' + end + # verify the required parameter 'user' is set + if @api_client.config.client_side_validation && user.nil? + fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.create_users_with_list_input" + end + # resource path + local_var_path = '/user/createWithList' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(user) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"UserApi.create_users_with_list_input", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#create_users_with_list_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Delete user + # This can only be done by the logged in user. + # @param username [String] The name that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [nil] + def delete_user(username, opts = {}) + delete_user_with_http_info(username, opts) + nil + end + + # Delete user + # This can only be done by the logged in user. + # @param username [String] The name that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def delete_user_with_http_info(username, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UserApi.delete_user ...' + end + # verify the required parameter 'username' is set + if @api_client.config.client_side_validation && username.nil? + fail ArgumentError, "Missing the required parameter 'username' when calling UserApi.delete_user" + end + # resource path + local_var_path = '/user/{username}'.sub('{' + 'username' + '}', CGI.escape(username.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"UserApi.delete_user", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#delete_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Get user by user name + # + # @param username [String] The name that needs to be fetched. Use user1 for testing. + # @param [Hash] opts the optional parameters + # @return [User] + def get_user_by_name(username, opts = {}) + data, _status_code, _headers = get_user_by_name_with_http_info(username, opts) + data + end + + # Get user by user name + # + # @param username [String] The name that needs to be fetched. Use user1 for testing. + # @param [Hash] opts the optional parameters + # @return [Array<(User, Integer, Hash)>] User data, response status code and response headers + def get_user_by_name_with_http_info(username, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UserApi.get_user_by_name ...' + end + # verify the required parameter 'username' is set + if @api_client.config.client_side_validation && username.nil? + fail ArgumentError, "Missing the required parameter 'username' when calling UserApi.get_user_by_name" + end + # resource path + local_var_path = '/user/{username}'.sub('{' + 'username' + '}', CGI.escape(username.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'User' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"UserApi.get_user_by_name", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#get_user_by_name\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Logs user into the system + # + # @param username [String] The user name for login + # @param password [String] The password for login in clear text + # @param [Hash] opts the optional parameters + # @return [String] + def login_user(username, password, opts = {}) + data, _status_code, _headers = login_user_with_http_info(username, password, opts) + data + end + + # Logs user into the system + # + # @param username [String] The user name for login + # @param password [String] The password for login in clear text + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def login_user_with_http_info(username, password, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UserApi.login_user ...' + end + # verify the required parameter 'username' is set + if @api_client.config.client_side_validation && username.nil? + fail ArgumentError, "Missing the required parameter 'username' when calling UserApi.login_user" + end + # verify the required parameter 'password' is set + if @api_client.config.client_side_validation && password.nil? + fail ArgumentError, "Missing the required parameter 'password' when calling UserApi.login_user" + end + # resource path + local_var_path = '/user/login' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'username'] = username + query_params[:'password'] = password + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"UserApi.login_user", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#login_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Logs out current logged in user session + # + # @param [Hash] opts the optional parameters + # @return [nil] + def logout_user(opts = {}) + logout_user_with_http_info(opts) + nil + end + + # Logs out current logged in user session + # + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def logout_user_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UserApi.logout_user ...' + end + # resource path + local_var_path = '/user/logout' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"UserApi.logout_user", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#logout_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Updated user + # This can only be done by the logged in user. + # @param username [String] name that need to be deleted + # @param user [User] Updated user object + # @param [Hash] opts the optional parameters + # @return [nil] + def update_user(username, user, opts = {}) + update_user_with_http_info(username, user, opts) + nil + end + + # Updated user + # This can only be done by the logged in user. + # @param username [String] name that need to be deleted + # @param user [User] Updated user object + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def update_user_with_http_info(username, user, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: UserApi.update_user ...' + end + # verify the required parameter 'username' is set + if @api_client.config.client_side_validation && username.nil? + fail ArgumentError, "Missing the required parameter 'username' when calling UserApi.update_user" + end + # verify the required parameter 'user' is set + if @api_client.config.client_side_validation && user.nil? + fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.update_user" + end + # resource path + local_var_path = '/user/{username}'.sub('{' + 'username' + '}', CGI.escape(username.to_s).gsub('%2F', '/')) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(user) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"UserApi.update_user", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: UserApi#update_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api_client.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api_client.rb new file mode 100644 index 0000000000..64aec67082 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api_client.rb @@ -0,0 +1,392 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'json' +require 'logger' +require 'tempfile' +require 'time' +require 'typhoeus' + +module Petstore + class ApiClient + # The Configuration object holding settings to be used in the API client. + attr_accessor :config + + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers + + # Initializes the ApiClient + # @option config [Configuration] Configuration for initializing the object, default to Configuration.default + def initialize(config = Configuration.default) + @config = config + @user_agent = "OpenAPI-Generator/#{VERSION}/ruby" + @default_headers = { + 'Content-Type' => 'application/json', + 'User-Agent' => @user_agent + } + end + + def self.default + @@default ||= ApiClient.new + end + + # Call an API with given options. + # + # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. + def call_api(http_method, path, opts = {}) + request = build_request(http_method, path, opts) + response = request.run + + if @config.debugging + @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + if response.timed_out? + fail ApiError.new('Connection timed out') + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(:code => 0, + :message => response.return_message) + else + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end + end + + if opts[:return_type] + data = deserialize(response, opts[:return_type]) + else + data = nil + end + return data, response.code, response.headers + end + + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request + def build_request(http_method, path, opts = {}) + url = build_request_url(path, opts) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {}) + query_params = opts[:query_params] || {} + form_params = opts[:form_params] || {} + follow_location = opts[:follow_location] || true + + update_params_for_auth! header_params, query_params, opts[:auth_names] + + # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false) + _verify_ssl_host = @config.verify_ssl_host ? 2 : 0 + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :params_encoding => @config.params_encoding, + :timeout => @config.timeout, + :ssl_verifypeer => @config.verify_ssl, + :ssl_verifyhost => _verify_ssl_host, + :sslcert => @config.cert_file, + :sslkey => @config.key_file, + :verbose => @config.debugging, + :followlocation => follow_location + } + + # set custom cert, if provided + req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update :body => req_body + if @config.debugging + @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + + request = Typhoeus::Request.new(url, req_opts) + download_file(request) if opts[:return_type] == 'File' + request + end + + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string + def build_request_body(header_params, form_params, body) + # http form + if header_params['Content-Type'] == 'application/x-www-form-urlencoded' || + header_params['Content-Type'] == 'multipart/form-data' + data = {} + form_params.each do |key, value| + case value + when ::File, ::Array, nil + # let typhoeus handle File, Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + data + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # The response body is written to the file in chunks in order to handle files which + # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby + # process can use. + # + # @see Configuration#temp_folder_path + def download_file(request) + tempfile = nil + encoding = nil + request.on_headers do |response| + content_disposition = response.headers['Content-Disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = response.body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + @tempfile = tempfile + end + request.on_body do |chunk| + chunk.force_encoding(encoding) + tempfile.write(chunk) + end + request.on_complete do |response| + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + end + end + end + + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + # */* + # @param [String] mime MIME + # @return [Boolean] True if the MIME is application/json + def json_mime?(mime) + (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? + end + + # Deserialize the response to the given return type. + # + # @param [Response] response HTTP response + # @param [String] return_type some examples: "User", "Array", "Hash" + def deserialize(response, return_type) + body = response.body + + # handle file downloading - return the File instance processed in request callbacks + # note that response body is empty when the file is written in chunks in request on_body callback + return @tempfile if return_type == 'File' + + return nil if body.nil? || body.empty? + + # return response body directly for String return type + return body if return_type == 'String' + + # ensuring a default content type + content_type = response.headers['Content-Type'] || 'application/json' + + fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type) + + begin + data = JSON.parse("[#{body}]", :symbolize_names => true)[0] + rescue JSON::ParserError => e + if %w(String Date Time).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + # @param [Object] data Data to be converted + # @param [String] return_type Return type + # @return [Mixed] Data in a particular type + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when 'String' + data.to_s + when 'Integer' + data.to_i + when 'Float' + data.to_f + when 'Boolean' + data == true + when 'Time' + # parse date time (expecting ISO 8601 format) + Time.parse data + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object (usually a Hash), return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map { |item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each { |k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(return_type) + klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data) + end + end + + # Sanitize filename by removing path. + # e.g. ../../sun.gif becomes sun.gif + # + # @param [String] filename the filename to be sanitized + # @return [String] the sanitized filename + def sanitize_filename(filename) + filename.gsub(/.*[\/\\]/, '') + end + + def build_request_url(path, opts = {}) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, '/') + @config.base_url(opts[:operation]) + path + end + + # Update header and query params based on authentication settings. + # + # @param [Hash] header_params Header parameters + # @param [Hash] query_params Query parameters + # @param [String] auth_names Authentication scheme name + def update_params_for_auth!(header_params, query_params, auth_names) + Array(auth_names).each do |auth_name| + auth_setting = @config.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] + when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] + else fail ArgumentError, 'Authentication token must be in `query` or `header`' + end + end + end + + # Sets user agent in HTTP header + # + # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0) + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent + end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) + return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + json_accept || accepts.join(',') + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + # return nil by default + return if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + json_content_type || content_types.first + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return model if model.nil? || model.is_a?(String) + local_body = nil + if model.is_a?(Array) + local_body = model.map { |m| object_to_hash(m) } + else + local_body = object_to_hash(model) + end + local_body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + + # Build parameter value according to the given collection format. + # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi + def build_collection_param(param, collection_format) + case collection_format + when :csv + param.join(',') + when :ssv + param.join(' ') + when :tsv + param.join("\t") + when :pipes + param.join('|') + when :multi + # return the array directly as typhoeus will handle it as expected + param + else + fail "unknown collection format: #{collection_format.inspect}" + end + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api_error.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api_error.rb new file mode 100644 index 0000000000..ec622a5fc1 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api_error.rb @@ -0,0 +1,57 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +module Petstore + class ApiError < StandardError + attr_reader :code, :response_headers, :response_body + + # Usage examples: + # ApiError.new + # ApiError.new("message") + # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") + # ApiError.new(:code => 404, :message => "Not Found") + def initialize(arg = nil) + if arg.is_a? Hash + if arg.key?(:message) || arg.key?('message') + super(arg[:message] || arg['message']) + else + super arg + end + + arg.each do |k, v| + instance_variable_set "@#{k}", v + end + else + super arg + end + end + + # Override to_s to display a friendly error message + def to_s + message + end + + def message + if @message.nil? + msg = "Error message: the server returns an error" + else + msg = @message + end + + msg += "\nHTTP status code: #{code}" if code + msg += "\nResponse headers: #{response_headers}" if response_headers + msg += "\nResponse body: #{response_body}" if response_body + + msg + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/configuration.rb b/samples/client/petstore/ruby-autoload/lib/petstore/configuration.rb new file mode 100644 index 0000000000..144fb92cb9 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/configuration.rb @@ -0,0 +1,411 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +module Petstore + class Configuration + # Defines url scheme + attr_accessor :scheme + + # Defines url host + attr_accessor :host + + # Defines url base path + attr_accessor :base_path + + # Define server configuration index + attr_accessor :server_index + + # Define server operation configuration index + attr_accessor :server_operation_index + + # Default server variables + attr_accessor :server_variables + + # Default server operation variables + attr_accessor :server_operation_variables + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Defines the access token (Bearer) used with OAuth2. + attr_accessor :access_token + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # The time limit for HTTP request in seconds. + # Default to 0 (never times out). + attr_accessor :timeout + + # Set this to false to skip client side validation in the operation. + # Default to true. + # @return [true, false] + attr_accessor :client_side_validation + + ### TLS/SSL setting + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl_host + + ### TLS/SSL setting + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + ### TLS/SSL setting + # Client certificate file (for client certificate) + attr_accessor :cert_file + + ### TLS/SSL setting + # Client private key file (for client certificate) + attr_accessor :key_file + + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + attr_accessor :params_encoding + + + attr_accessor :inject_format + + attr_accessor :force_ending_format + + def initialize + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @server_index = 0 + @server_operation_index = {} + @server_variables = {} + @server_operation_variables = {} + @api_key = {} + @api_key_prefix = {} + @client_side_validation = true + @verify_ssl = true + @verify_ssl_host = true + @cert_file = nil + @key_file = nil + @timeout = 0 + @params_encoding = nil + @debugging = false + @inject_format = false + @force_ending_format = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + yield(self) if block_given? + end + + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, '') + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, '').split('/').first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, '/') + @base_path = '' if @base_path == '/' + end + + # Returns base URL for specified operation based on server settings + def base_url(operation = nil) + index = server_operation_index.fetch(operation, server_index) + return "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') if index == nil + + server_url(index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation]) + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{key}" + else + key + end + end + + # Gets Basic Auth token string + def basic_auth_token + 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + { + 'api_key' => + { + type: 'api_key', + in: 'header', + key: 'api_key', + value: api_key_with_prefix('api_key') + }, + 'api_key_query' => + { + type: 'api_key', + in: 'query', + key: 'api_key_query', + value: api_key_with_prefix('api_key_query') + }, + 'bearer_test' => + { + type: 'bearer', + in: 'header', + format: 'JWT', + key: 'Authorization', + value: "Bearer #{access_token}" + }, + 'http_basic_test' => + { + type: 'basic', + in: 'header', + key: 'Authorization', + value: basic_auth_token + }, + 'petstore_auth' => + { + type: 'oauth2', + in: 'header', + key: 'Authorization', + value: "Bearer #{access_token}" + }, + } + end + + # Returns an array of Server setting + def server_settings + [ + { + url: "http://{server}.swagger.io:{port}/v2", + description: "petstore server", + variables: { + server: { + description: "No description provided", + default_value: "petstore", + enum_values: [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + port: { + description: "No description provided", + default_value: "80", + enum_values: [ + "80", + "8080" + ] + } + } + }, + { + url: "https://localhost:8080/{version}", + description: "The local server", + variables: { + version: { + description: "No description provided", + default_value: "v2", + enum_values: [ + "v1", + "v2" + ] + } + } + }, + { + url: "https://127.0.0.1/no_varaible", + description: "The local server without variables", + } + ] + end + + def operation_server_settings + { + "PetApi.add_pet": [ + { + url: "http://petstore.swagger.io/v2", + description: "No description provided", + }, + { + url: "http://path-server-test.petstore.local/v2", + description: "No description provided", + }, + { + url: "http://{server}.swagger.io:{port}/v2", + description: "test server with variables", + variables: { + server: { + description: "target server", + default_value: "petstore", + enum_values: [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + port: { + description: "No description provided", + default_value: "80", + enum_values: [ + "80", + "8080" + ] + } + } + } + ], + "PetApi.update_pet": [ + { + url: "http://petstore.swagger.io/v2", + description: "No description provided", + }, + { + url: "http://path-server-test.petstore.local/v2", + description: "No description provided", + }, + { + url: "http://{server}.swagger.io:{port}/v2", + description: "test server with variables", + variables: { + server: { + description: "target server", + default_value: "petstore", + enum_values: [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + port: { + description: "No description provided", + default_value: "80", + enum_values: [ + "80", + "8080" + ] + } + } + } + ], + } + end + + # Returns URL based on server settings + # + # @param index array index of the server settings + # @param variables hash of variable and the corresponding value + def server_url(index, variables = {}, servers = nil) + servers = server_settings if servers == nil + + # check array index out of bound + if (index < 0 || index >= servers.size) + fail ArgumentError, "Invalid index #{index} when selecting the server. Must be less than #{servers.size}" + end + + server = servers[index] + url = server[:url] + + return url unless server.key? :variables + + # go through variable and assign a value + server[:variables].each do |name, variable| + if variables.key?(name) + if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name])) + url.gsub! "{" + name.to_s + "}", variables[name] + else + fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}." + end + else + # use default value + url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value] + end + end + + url + end + + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/additional_properties_class.rb new file mode 100644 index 0000000000..09b4aa0f17 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/additional_properties_class.rb @@ -0,0 +1,232 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class AdditionalPropertiesClass + attr_accessor :map_property + + attr_accessor :map_of_map_property + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'map_property' => :'map_property', + :'map_of_map_property' => :'map_of_map_property' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'map_property' => :'Hash', + :'map_of_map_property' => :'Hash>' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::AdditionalPropertiesClass` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::AdditionalPropertiesClass`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'map_property') + if (value = attributes[:'map_property']).is_a?(Hash) + self.map_property = value + end + end + + if attributes.key?(:'map_of_map_property') + if (value = attributes[:'map_of_map_property']).is_a?(Hash) + self.map_of_map_property = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + map_property == o.map_property && + map_of_map_property == o.map_of_map_property + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [map_property, map_of_map_property].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/all_of_with_single_ref.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/all_of_with_single_ref.rb new file mode 100644 index 0000000000..c7e611e2f5 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/all_of_with_single_ref.rb @@ -0,0 +1,228 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class AllOfWithSingleRef + attr_accessor :username + + attr_accessor :single_ref_type + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'username' => :'username', + :'single_ref_type' => :'SingleRefType' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'username' => :'String', + :'single_ref_type' => :'SingleRefType' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::AllOfWithSingleRef` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::AllOfWithSingleRef`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'username') + self.username = attributes[:'username'] + end + + if attributes.key?(:'single_ref_type') + self.single_ref_type = attributes[:'single_ref_type'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + username == o.username && + single_ref_type == o.single_ref_type + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [username, single_ref_type].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/animal.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/animal.rb new file mode 100644 index 0000000000..14b080b796 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/animal.rb @@ -0,0 +1,240 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Animal + attr_accessor :class_name + + attr_accessor :color + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'class_name' => :'className', + :'color' => :'color' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'class_name' => :'String', + :'color' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # discriminator's property name in OpenAPI v3 + def self.openapi_discriminator_name + :'class_name' + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Animal` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Animal`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'class_name') + self.class_name = attributes[:'class_name'] + end + + if attributes.key?(:'color') + self.color = attributes[:'color'] + else + self.color = 'red' + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if @class_name.nil? + invalid_properties.push('invalid value for "class_name", class_name cannot be nil.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if @class_name.nil? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + class_name == o.class_name && + color == o.color + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [class_name, color].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/api_response.rb new file mode 100644 index 0000000000..afe92b54ed --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/api_response.rb @@ -0,0 +1,237 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class ApiResponse + attr_accessor :code + + attr_accessor :type + + attr_accessor :message + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'code' => :'code', + :'type' => :'type', + :'message' => :'message' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'code' => :'Integer', + :'type' => :'String', + :'message' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::ApiResponse` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::ApiResponse`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'code') + self.code = attributes[:'code'] + end + + if attributes.key?(:'type') + self.type = attributes[:'type'] + end + + if attributes.key?(:'message') + self.message = attributes[:'message'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + code == o.code && + type == o.type && + message == o.message + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [code, type, message].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_array_of_number_only.rb new file mode 100644 index 0000000000..452252dcc8 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_array_of_number_only.rb @@ -0,0 +1,221 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class ArrayOfArrayOfNumberOnly + attr_accessor :array_array_number + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'array_array_number' => :'ArrayArrayNumber' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'array_array_number' => :'Array>' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::ArrayOfArrayOfNumberOnly` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::ArrayOfArrayOfNumberOnly`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'array_array_number') + if (value = attributes[:'array_array_number']).is_a?(Array) + self.array_array_number = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + array_array_number == o.array_array_number + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [array_array_number].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_number_only.rb new file mode 100644 index 0000000000..bcbd551ea3 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_number_only.rb @@ -0,0 +1,221 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class ArrayOfNumberOnly + attr_accessor :array_number + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'array_number' => :'ArrayNumber' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'array_number' => :'Array' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::ArrayOfNumberOnly` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::ArrayOfNumberOnly`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'array_number') + if (value = attributes[:'array_number']).is_a?(Array) + self.array_number = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + array_number == o.array_number + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [array_number].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_test.rb new file mode 100644 index 0000000000..28f1f358b2 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_test.rb @@ -0,0 +1,267 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class ArrayTest + attr_accessor :array_of_string + + attr_accessor :array_array_of_integer + + attr_accessor :array_array_of_model + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'array_of_string' => :'array_of_string', + :'array_array_of_integer' => :'array_array_of_integer', + :'array_array_of_model' => :'array_array_of_model' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'array_of_string' => :'Array', + :'array_array_of_integer' => :'Array>', + :'array_array_of_model' => :'Array>' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::ArrayTest` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::ArrayTest`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'array_of_string') + if (value = attributes[:'array_of_string']).is_a?(Array) + self.array_of_string = value + end + end + + if attributes.key?(:'array_array_of_integer') + if (value = attributes[:'array_array_of_integer']).is_a?(Array) + self.array_array_of_integer = value + end + end + + if attributes.key?(:'array_array_of_model') + if (value = attributes[:'array_array_of_model']).is_a?(Array) + self.array_array_of_model = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if !@array_of_string.nil? && @array_of_string.length > 3 + invalid_properties.push('invalid value for "array_of_string", number of items must be less than or equal to 3.') + end + + if !@array_of_string.nil? && @array_of_string.length < 0 + invalid_properties.push('invalid value for "array_of_string", number of items must be greater than or equal to 0.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if !@array_of_string.nil? && @array_of_string.length > 3 + return false if !@array_of_string.nil? && @array_of_string.length < 0 + true + end + + # Custom attribute writer method with validation + # @param [Object] array_of_string Value to be assigned + def array_of_string=(array_of_string) + if !array_of_string.nil? && array_of_string.length > 3 + fail ArgumentError, 'invalid value for "array_of_string", number of items must be less than or equal to 3.' + end + + if !array_of_string.nil? && array_of_string.length < 0 + fail ArgumentError, 'invalid value for "array_of_string", number of items must be greater than or equal to 0.' + end + + @array_of_string = array_of_string + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + array_of_string == o.array_of_string && + array_array_of_integer == o.array_array_of_integer && + array_array_of_model == o.array_array_of_model + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [array_of_string, array_array_of_integer, array_array_of_model].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/capitalization.rb new file mode 100644 index 0000000000..a55b870914 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/capitalization.rb @@ -0,0 +1,265 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Capitalization + attr_accessor :small_camel + + attr_accessor :capital_camel + + attr_accessor :small_snake + + attr_accessor :capital_snake + + attr_accessor :sca_eth_flow_points + + # Name of the pet + attr_accessor :att_name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'small_camel' => :'smallCamel', + :'capital_camel' => :'CapitalCamel', + :'small_snake' => :'small_Snake', + :'capital_snake' => :'Capital_Snake', + :'sca_eth_flow_points' => :'SCA_ETH_Flow_Points', + :'att_name' => :'ATT_NAME' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'small_camel' => :'String', + :'capital_camel' => :'String', + :'small_snake' => :'String', + :'capital_snake' => :'String', + :'sca_eth_flow_points' => :'String', + :'att_name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Capitalization` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Capitalization`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'small_camel') + self.small_camel = attributes[:'small_camel'] + end + + if attributes.key?(:'capital_camel') + self.capital_camel = attributes[:'capital_camel'] + end + + if attributes.key?(:'small_snake') + self.small_snake = attributes[:'small_snake'] + end + + if attributes.key?(:'capital_snake') + self.capital_snake = attributes[:'capital_snake'] + end + + if attributes.key?(:'sca_eth_flow_points') + self.sca_eth_flow_points = attributes[:'sca_eth_flow_points'] + end + + if attributes.key?(:'att_name') + self.att_name = attributes[:'att_name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + small_camel == o.small_camel && + capital_camel == o.capital_camel && + small_snake == o.small_snake && + capital_snake == o.capital_snake && + sca_eth_flow_points == o.sca_eth_flow_points && + att_name == o.att_name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [small_camel, capital_camel, small_snake, capital_snake, sca_eth_flow_points, att_name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/cat.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/cat.rb new file mode 100644 index 0000000000..6052061367 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/cat.rb @@ -0,0 +1,231 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Cat < Animal + attr_accessor :declawed + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'declawed' => :'declawed' + } + end + + # Returns all the JSON keys this model knows about, including the ones defined in its parent(s) + def self.acceptable_attributes + attribute_map.values.concat(superclass.acceptable_attributes) + end + + # Attribute type mapping. + def self.openapi_types + { + :'declawed' => :'Boolean' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # List of class defined in allOf (OpenAPI v3) + def self.openapi_all_of + [ + :'Animal', + :'CatAllOf' + ] + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Cat` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Cat`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + # call parent's initialize + super(attributes) + + if attributes.key?(:'declawed') + self.declawed = attributes[:'declawed'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = super + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true && super + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + declawed == o.declawed && super(o) + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [declawed].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + super(attributes) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = super + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/cat_all_of.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/cat_all_of.rb new file mode 100644 index 0000000000..5b3371e65e --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/cat_all_of.rb @@ -0,0 +1,219 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class CatAllOf + attr_accessor :declawed + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'declawed' => :'declawed' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'declawed' => :'Boolean' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::CatAllOf` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::CatAllOf`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'declawed') + self.declawed = attributes[:'declawed'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + declawed == o.declawed + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [declawed].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/category.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/category.rb new file mode 100644 index 0000000000..e38a0e24a1 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/category.rb @@ -0,0 +1,235 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Category + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'name' => :'name' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Category` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Category`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + else + self.name = 'default-name' + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if @name.nil? + invalid_properties.push('invalid value for "name", name cannot be nil.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if @name.nil? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/class_model.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/class_model.rb new file mode 100644 index 0000000000..5a1ea761ff --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/class_model.rb @@ -0,0 +1,220 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + # Model for testing model with \"_class\" property + class ClassModel + attr_accessor :_class + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'_class' => :'_class' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'_class' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::ClassModel` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::ClassModel`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'_class') + self._class = attributes[:'_class'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + _class == o._class + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [_class].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/client.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/client.rb new file mode 100644 index 0000000000..28bcda26da --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/client.rb @@ -0,0 +1,219 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Client + attr_accessor :client + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'client' => :'client' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'client' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Client` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Client`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'client') + self.client = attributes[:'client'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + client == o.client + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [client].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/deprecated_object.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/deprecated_object.rb new file mode 100644 index 0000000000..5cd8b8856a --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/deprecated_object.rb @@ -0,0 +1,219 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class DeprecatedObject + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'name' => :'name' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::DeprecatedObject` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::DeprecatedObject`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/dog.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/dog.rb new file mode 100644 index 0000000000..29172f20ec --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/dog.rb @@ -0,0 +1,231 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Dog < Animal + attr_accessor :breed + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'breed' => :'breed' + } + end + + # Returns all the JSON keys this model knows about, including the ones defined in its parent(s) + def self.acceptable_attributes + attribute_map.values.concat(superclass.acceptable_attributes) + end + + # Attribute type mapping. + def self.openapi_types + { + :'breed' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # List of class defined in allOf (OpenAPI v3) + def self.openapi_all_of + [ + :'Animal', + :'DogAllOf' + ] + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Dog` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Dog`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + # call parent's initialize + super(attributes) + + if attributes.key?(:'breed') + self.breed = attributes[:'breed'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = super + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true && super + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + breed == o.breed && super(o) + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [breed].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + super(attributes) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = super + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/dog_all_of.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/dog_all_of.rb new file mode 100644 index 0000000000..f653092097 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/dog_all_of.rb @@ -0,0 +1,219 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class DogAllOf + attr_accessor :breed + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'breed' => :'breed' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'breed' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::DogAllOf` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::DogAllOf`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'breed') + self.breed = attributes[:'breed'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + breed == o.breed + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [breed].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_arrays.rb new file mode 100644 index 0000000000..c42e545e08 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_arrays.rb @@ -0,0 +1,264 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class EnumArrays + attr_accessor :just_symbol + + attr_accessor :array_enum + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'just_symbol' => :'just_symbol', + :'array_enum' => :'array_enum' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'just_symbol' => :'String', + :'array_enum' => :'Array' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::EnumArrays` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::EnumArrays`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'just_symbol') + self.just_symbol = attributes[:'just_symbol'] + end + + if attributes.key?(:'array_enum') + if (value = attributes[:'array_enum']).is_a?(Array) + self.array_enum = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + just_symbol_validator = EnumAttributeValidator.new('String', [">=", "$"]) + return false unless just_symbol_validator.valid?(@just_symbol) + true + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] just_symbol Object to be assigned + def just_symbol=(just_symbol) + validator = EnumAttributeValidator.new('String', [">=", "$"]) + unless validator.valid?(just_symbol) + fail ArgumentError, "invalid value for \"just_symbol\", must be one of #{validator.allowable_values}." + end + @just_symbol = just_symbol + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + just_symbol == o.just_symbol && + array_enum == o.array_enum + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [just_symbol, array_enum].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_class.rb new file mode 100644 index 0000000000..b2cd88d076 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_class.rb @@ -0,0 +1,41 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class EnumClass + ABC = "_abc".freeze + EFG = "-efg".freeze + XYZ = "(xyz)".freeze + + def self.all_vars + @all_vars ||= [ABC, EFG, XYZ].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if EnumClass.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #EnumClass" + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_test.rb new file mode 100644 index 0000000000..58c55ed401 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_test.rb @@ -0,0 +1,362 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class EnumTest + attr_accessor :enum_string + + attr_accessor :enum_string_required + + attr_accessor :enum_integer + + attr_accessor :enum_number + + attr_accessor :outer_enum + + attr_accessor :outer_enum_integer + + attr_accessor :outer_enum_default_value + + attr_accessor :outer_enum_integer_default_value + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'enum_string' => :'enum_string', + :'enum_string_required' => :'enum_string_required', + :'enum_integer' => :'enum_integer', + :'enum_number' => :'enum_number', + :'outer_enum' => :'outerEnum', + :'outer_enum_integer' => :'outerEnumInteger', + :'outer_enum_default_value' => :'outerEnumDefaultValue', + :'outer_enum_integer_default_value' => :'outerEnumIntegerDefaultValue' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'enum_string' => :'String', + :'enum_string_required' => :'String', + :'enum_integer' => :'Integer', + :'enum_number' => :'Float', + :'outer_enum' => :'OuterEnum', + :'outer_enum_integer' => :'OuterEnumInteger', + :'outer_enum_default_value' => :'OuterEnumDefaultValue', + :'outer_enum_integer_default_value' => :'OuterEnumIntegerDefaultValue' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + :'outer_enum', + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::EnumTest` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::EnumTest`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'enum_string') + self.enum_string = attributes[:'enum_string'] + end + + if attributes.key?(:'enum_string_required') + self.enum_string_required = attributes[:'enum_string_required'] + end + + if attributes.key?(:'enum_integer') + self.enum_integer = attributes[:'enum_integer'] + end + + if attributes.key?(:'enum_number') + self.enum_number = attributes[:'enum_number'] + end + + if attributes.key?(:'outer_enum') + self.outer_enum = attributes[:'outer_enum'] + end + + if attributes.key?(:'outer_enum_integer') + self.outer_enum_integer = attributes[:'outer_enum_integer'] + end + + if attributes.key?(:'outer_enum_default_value') + self.outer_enum_default_value = attributes[:'outer_enum_default_value'] + else + self.outer_enum_default_value = 'placed' + end + + if attributes.key?(:'outer_enum_integer_default_value') + self.outer_enum_integer_default_value = attributes[:'outer_enum_integer_default_value'] + else + self.outer_enum_integer_default_value = OuterEnumIntegerDefaultValue::N0 + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if @enum_string_required.nil? + invalid_properties.push('invalid value for "enum_string_required", enum_string_required cannot be nil.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + enum_string_validator = EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) + return false unless enum_string_validator.valid?(@enum_string) + return false if @enum_string_required.nil? + enum_string_required_validator = EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) + return false unless enum_string_required_validator.valid?(@enum_string_required) + enum_integer_validator = EnumAttributeValidator.new('Integer', [1, -1]) + return false unless enum_integer_validator.valid?(@enum_integer) + enum_number_validator = EnumAttributeValidator.new('Float', [1.1, -1.2]) + return false unless enum_number_validator.valid?(@enum_number) + true + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_string Object to be assigned + def enum_string=(enum_string) + validator = EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) + unless validator.valid?(enum_string) + fail ArgumentError, "invalid value for \"enum_string\", must be one of #{validator.allowable_values}." + end + @enum_string = enum_string + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_string_required Object to be assigned + def enum_string_required=(enum_string_required) + validator = EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) + unless validator.valid?(enum_string_required) + fail ArgumentError, "invalid value for \"enum_string_required\", must be one of #{validator.allowable_values}." + end + @enum_string_required = enum_string_required + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_integer Object to be assigned + def enum_integer=(enum_integer) + validator = EnumAttributeValidator.new('Integer', [1, -1]) + unless validator.valid?(enum_integer) + fail ArgumentError, "invalid value for \"enum_integer\", must be one of #{validator.allowable_values}." + end + @enum_integer = enum_integer + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_number Object to be assigned + def enum_number=(enum_number) + validator = EnumAttributeValidator.new('Float', [1.1, -1.2]) + unless validator.valid?(enum_number) + fail ArgumentError, "invalid value for \"enum_number\", must be one of #{validator.allowable_values}." + end + @enum_number = enum_number + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + enum_string == o.enum_string && + enum_string_required == o.enum_string_required && + enum_integer == o.enum_integer && + enum_number == o.enum_number && + outer_enum == o.outer_enum && + outer_enum_integer == o.outer_enum_integer && + outer_enum_default_value == o.outer_enum_default_value && + outer_enum_integer_default_value == o.outer_enum_integer_default_value + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [enum_string, enum_string_required, enum_integer, enum_number, outer_enum, outer_enum_integer, outer_enum_default_value, outer_enum_integer_default_value].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/file.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/file.rb new file mode 100644 index 0000000000..44bd87ec04 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/file.rb @@ -0,0 +1,221 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + # Must be named `File` for test. + class File + # Test capitalization + attr_accessor :source_uri + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'source_uri' => :'sourceURI' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'source_uri' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::File` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::File`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'source_uri') + self.source_uri = attributes[:'source_uri'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + source_uri == o.source_uri + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [source_uri].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/file_schema_test_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/file_schema_test_class.rb new file mode 100644 index 0000000000..7c7b3d8a32 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/file_schema_test_class.rb @@ -0,0 +1,230 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class FileSchemaTestClass + attr_accessor :file + + attr_accessor :files + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'file' => :'file', + :'files' => :'files' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'file' => :'File', + :'files' => :'Array' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::FileSchemaTestClass` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::FileSchemaTestClass`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'file') + self.file = attributes[:'file'] + end + + if attributes.key?(:'files') + if (value = attributes[:'files']).is_a?(Array) + self.files = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + file == o.file && + files == o.files + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [file, files].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/foo.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/foo.rb new file mode 100644 index 0000000000..e6b03f67ee --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/foo.rb @@ -0,0 +1,221 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Foo + attr_accessor :bar + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'bar' => :'bar' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'bar' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Foo` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Foo`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'bar') + self.bar = attributes[:'bar'] + else + self.bar = 'bar' + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + bar == o.bar + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [bar].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/foo_get_default_response.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/foo_get_default_response.rb new file mode 100644 index 0000000000..c32e9f721c --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/foo_get_default_response.rb @@ -0,0 +1,219 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class FooGetDefaultResponse + attr_accessor :string + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'string' => :'string' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'string' => :'Foo' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::FooGetDefaultResponse` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::FooGetDefaultResponse`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'string') + self.string = attributes[:'string'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + string == o.string + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [string].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/format_test.rb new file mode 100644 index 0000000000..5d7bd35a97 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/format_test.rb @@ -0,0 +1,579 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class FormatTest + attr_accessor :integer + + attr_accessor :int32 + + attr_accessor :int64 + + attr_accessor :number + + attr_accessor :float + + attr_accessor :double + + attr_accessor :decimal + + attr_accessor :string + + attr_accessor :byte + + attr_accessor :binary + + attr_accessor :date + + attr_accessor :date_time + + attr_accessor :uuid + + attr_accessor :password + + # A string that is a 10 digit number. Can have leading zeros. + attr_accessor :pattern_with_digits + + # A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + attr_accessor :pattern_with_digits_and_delimiter + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'integer' => :'integer', + :'int32' => :'int32', + :'int64' => :'int64', + :'number' => :'number', + :'float' => :'float', + :'double' => :'double', + :'decimal' => :'decimal', + :'string' => :'string', + :'byte' => :'byte', + :'binary' => :'binary', + :'date' => :'date', + :'date_time' => :'dateTime', + :'uuid' => :'uuid', + :'password' => :'password', + :'pattern_with_digits' => :'pattern_with_digits', + :'pattern_with_digits_and_delimiter' => :'pattern_with_digits_and_delimiter' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'integer' => :'Integer', + :'int32' => :'Integer', + :'int64' => :'Integer', + :'number' => :'Float', + :'float' => :'Float', + :'double' => :'Float', + :'decimal' => :'Float', + :'string' => :'String', + :'byte' => :'String', + :'binary' => :'File', + :'date' => :'Date', + :'date_time' => :'Time', + :'uuid' => :'String', + :'password' => :'String', + :'pattern_with_digits' => :'String', + :'pattern_with_digits_and_delimiter' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::FormatTest` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::FormatTest`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'integer') + self.integer = attributes[:'integer'] + end + + if attributes.key?(:'int32') + self.int32 = attributes[:'int32'] + end + + if attributes.key?(:'int64') + self.int64 = attributes[:'int64'] + end + + if attributes.key?(:'number') + self.number = attributes[:'number'] + end + + if attributes.key?(:'float') + self.float = attributes[:'float'] + end + + if attributes.key?(:'double') + self.double = attributes[:'double'] + end + + if attributes.key?(:'decimal') + self.decimal = attributes[:'decimal'] + end + + if attributes.key?(:'string') + self.string = attributes[:'string'] + end + + if attributes.key?(:'byte') + self.byte = attributes[:'byte'] + end + + if attributes.key?(:'binary') + self.binary = attributes[:'binary'] + end + + if attributes.key?(:'date') + self.date = attributes[:'date'] + end + + if attributes.key?(:'date_time') + self.date_time = attributes[:'date_time'] + end + + if attributes.key?(:'uuid') + self.uuid = attributes[:'uuid'] + end + + if attributes.key?(:'password') + self.password = attributes[:'password'] + end + + if attributes.key?(:'pattern_with_digits') + self.pattern_with_digits = attributes[:'pattern_with_digits'] + end + + if attributes.key?(:'pattern_with_digits_and_delimiter') + self.pattern_with_digits_and_delimiter = attributes[:'pattern_with_digits_and_delimiter'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if !@integer.nil? && @integer > 100 + invalid_properties.push('invalid value for "integer", must be smaller than or equal to 100.') + end + + if !@integer.nil? && @integer < 10 + invalid_properties.push('invalid value for "integer", must be greater than or equal to 10.') + end + + if !@int32.nil? && @int32 > 200 + invalid_properties.push('invalid value for "int32", must be smaller than or equal to 200.') + end + + if !@int32.nil? && @int32 < 20 + invalid_properties.push('invalid value for "int32", must be greater than or equal to 20.') + end + + if @number.nil? + invalid_properties.push('invalid value for "number", number cannot be nil.') + end + + if @number > 543.2 + invalid_properties.push('invalid value for "number", must be smaller than or equal to 543.2.') + end + + if @number < 32.1 + invalid_properties.push('invalid value for "number", must be greater than or equal to 32.1.') + end + + if !@float.nil? && @float > 987.6 + invalid_properties.push('invalid value for "float", must be smaller than or equal to 987.6.') + end + + if !@float.nil? && @float < 54.3 + invalid_properties.push('invalid value for "float", must be greater than or equal to 54.3.') + end + + if !@double.nil? && @double > 123.4 + invalid_properties.push('invalid value for "double", must be smaller than or equal to 123.4.') + end + + if !@double.nil? && @double < 67.8 + invalid_properties.push('invalid value for "double", must be greater than or equal to 67.8.') + end + + pattern = Regexp.new(/[a-z]/i) + if !@string.nil? && @string !~ pattern + invalid_properties.push("invalid value for \"string\", must conform to the pattern #{pattern}.") + end + + if @byte.nil? + invalid_properties.push('invalid value for "byte", byte cannot be nil.') + end + + if @date.nil? + invalid_properties.push('invalid value for "date", date cannot be nil.') + end + + if @password.nil? + invalid_properties.push('invalid value for "password", password cannot be nil.') + end + + if @password.to_s.length > 64 + invalid_properties.push('invalid value for "password", the character length must be smaller than or equal to 64.') + end + + if @password.to_s.length < 10 + invalid_properties.push('invalid value for "password", the character length must be great than or equal to 10.') + end + + pattern = Regexp.new(/^\d{10}$/) + if !@pattern_with_digits.nil? && @pattern_with_digits !~ pattern + invalid_properties.push("invalid value for \"pattern_with_digits\", must conform to the pattern #{pattern}.") + end + + pattern = Regexp.new(/^image_\d{1,3}$/i) + if !@pattern_with_digits_and_delimiter.nil? && @pattern_with_digits_and_delimiter !~ pattern + invalid_properties.push("invalid value for \"pattern_with_digits_and_delimiter\", must conform to the pattern #{pattern}.") + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if !@integer.nil? && @integer > 100 + return false if !@integer.nil? && @integer < 10 + return false if !@int32.nil? && @int32 > 200 + return false if !@int32.nil? && @int32 < 20 + return false if @number.nil? + return false if @number > 543.2 + return false if @number < 32.1 + return false if !@float.nil? && @float > 987.6 + return false if !@float.nil? && @float < 54.3 + return false if !@double.nil? && @double > 123.4 + return false if !@double.nil? && @double < 67.8 + return false if !@string.nil? && @string !~ Regexp.new(/[a-z]/i) + return false if @byte.nil? + return false if @date.nil? + return false if @password.nil? + return false if @password.to_s.length > 64 + return false if @password.to_s.length < 10 + return false if !@pattern_with_digits.nil? && @pattern_with_digits !~ Regexp.new(/^\d{10}$/) + return false if !@pattern_with_digits_and_delimiter.nil? && @pattern_with_digits_and_delimiter !~ Regexp.new(/^image_\d{1,3}$/i) + true + end + + # Custom attribute writer method with validation + # @param [Object] integer Value to be assigned + def integer=(integer) + if !integer.nil? && integer > 100 + fail ArgumentError, 'invalid value for "integer", must be smaller than or equal to 100.' + end + + if !integer.nil? && integer < 10 + fail ArgumentError, 'invalid value for "integer", must be greater than or equal to 10.' + end + + @integer = integer + end + + # Custom attribute writer method with validation + # @param [Object] int32 Value to be assigned + def int32=(int32) + if !int32.nil? && int32 > 200 + fail ArgumentError, 'invalid value for "int32", must be smaller than or equal to 200.' + end + + if !int32.nil? && int32 < 20 + fail ArgumentError, 'invalid value for "int32", must be greater than or equal to 20.' + end + + @int32 = int32 + end + + # Custom attribute writer method with validation + # @param [Object] number Value to be assigned + def number=(number) + if number.nil? + fail ArgumentError, 'number cannot be nil' + end + + if number > 543.2 + fail ArgumentError, 'invalid value for "number", must be smaller than or equal to 543.2.' + end + + if number < 32.1 + fail ArgumentError, 'invalid value for "number", must be greater than or equal to 32.1.' + end + + @number = number + end + + # Custom attribute writer method with validation + # @param [Object] float Value to be assigned + def float=(float) + if !float.nil? && float > 987.6 + fail ArgumentError, 'invalid value for "float", must be smaller than or equal to 987.6.' + end + + if !float.nil? && float < 54.3 + fail ArgumentError, 'invalid value for "float", must be greater than or equal to 54.3.' + end + + @float = float + end + + # Custom attribute writer method with validation + # @param [Object] double Value to be assigned + def double=(double) + if !double.nil? && double > 123.4 + fail ArgumentError, 'invalid value for "double", must be smaller than or equal to 123.4.' + end + + if !double.nil? && double < 67.8 + fail ArgumentError, 'invalid value for "double", must be greater than or equal to 67.8.' + end + + @double = double + end + + # Custom attribute writer method with validation + # @param [Object] string Value to be assigned + def string=(string) + pattern = Regexp.new(/[a-z]/i) + if !string.nil? && string !~ pattern + fail ArgumentError, "invalid value for \"string\", must conform to the pattern #{pattern}." + end + + @string = string + end + + # Custom attribute writer method with validation + # @param [Object] password Value to be assigned + def password=(password) + if password.nil? + fail ArgumentError, 'password cannot be nil' + end + + if password.to_s.length > 64 + fail ArgumentError, 'invalid value for "password", the character length must be smaller than or equal to 64.' + end + + if password.to_s.length < 10 + fail ArgumentError, 'invalid value for "password", the character length must be great than or equal to 10.' + end + + @password = password + end + + # Custom attribute writer method with validation + # @param [Object] pattern_with_digits Value to be assigned + def pattern_with_digits=(pattern_with_digits) + pattern = Regexp.new(/^\d{10}$/) + if !pattern_with_digits.nil? && pattern_with_digits !~ pattern + fail ArgumentError, "invalid value for \"pattern_with_digits\", must conform to the pattern #{pattern}." + end + + @pattern_with_digits = pattern_with_digits + end + + # Custom attribute writer method with validation + # @param [Object] pattern_with_digits_and_delimiter Value to be assigned + def pattern_with_digits_and_delimiter=(pattern_with_digits_and_delimiter) + pattern = Regexp.new(/^image_\d{1,3}$/i) + if !pattern_with_digits_and_delimiter.nil? && pattern_with_digits_and_delimiter !~ pattern + fail ArgumentError, "invalid value for \"pattern_with_digits_and_delimiter\", must conform to the pattern #{pattern}." + end + + @pattern_with_digits_and_delimiter = pattern_with_digits_and_delimiter + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + integer == o.integer && + int32 == o.int32 && + int64 == o.int64 && + number == o.number && + float == o.float && + double == o.double && + decimal == o.decimal && + string == o.string && + byte == o.byte && + binary == o.binary && + date == o.date && + date_time == o.date_time && + uuid == o.uuid && + password == o.password && + pattern_with_digits == o.pattern_with_digits && + pattern_with_digits_and_delimiter == o.pattern_with_digits_and_delimiter + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [integer, int32, int64, number, float, double, decimal, string, byte, binary, date, date_time, uuid, password, pattern_with_digits, pattern_with_digits_and_delimiter].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/has_only_read_only.rb new file mode 100644 index 0000000000..df54b67cf9 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/has_only_read_only.rb @@ -0,0 +1,228 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class HasOnlyReadOnly + attr_accessor :bar + + attr_accessor :foo + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'bar' => :'bar', + :'foo' => :'foo' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'bar' => :'String', + :'foo' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::HasOnlyReadOnly` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::HasOnlyReadOnly`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'bar') + self.bar = attributes[:'bar'] + end + + if attributes.key?(:'foo') + self.foo = attributes[:'foo'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + bar == o.bar && + foo == o.foo + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [bar, foo].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/health_check_result.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/health_check_result.rb new file mode 100644 index 0000000000..12845874f8 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/health_check_result.rb @@ -0,0 +1,221 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + # Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + class HealthCheckResult + attr_accessor :nullable_message + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'nullable_message' => :'NullableMessage' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'nullable_message' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + :'nullable_message' + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::HealthCheckResult` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::HealthCheckResult`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'nullable_message') + self.nullable_message = attributes[:'nullable_message'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + nullable_message == o.nullable_message + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [nullable_message].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/list.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/list.rb new file mode 100644 index 0000000000..32065095d9 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/list.rb @@ -0,0 +1,219 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class List + attr_accessor :_123_list + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'_123_list' => :'123-list' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'_123_list' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::List` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::List`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'_123_list') + self._123_list = attributes[:'_123_list'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + _123_list == o._123_list + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [_123_list].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/map_test.rb new file mode 100644 index 0000000000..181c1c991a --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/map_test.rb @@ -0,0 +1,276 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class MapTest + attr_accessor :map_map_of_string + + attr_accessor :map_of_enum_string + + attr_accessor :direct_map + + attr_accessor :indirect_map + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'map_map_of_string' => :'map_map_of_string', + :'map_of_enum_string' => :'map_of_enum_string', + :'direct_map' => :'direct_map', + :'indirect_map' => :'indirect_map' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'map_map_of_string' => :'Hash>', + :'map_of_enum_string' => :'Hash', + :'direct_map' => :'Hash', + :'indirect_map' => :'Hash' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::MapTest` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::MapTest`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'map_map_of_string') + if (value = attributes[:'map_map_of_string']).is_a?(Hash) + self.map_map_of_string = value + end + end + + if attributes.key?(:'map_of_enum_string') + if (value = attributes[:'map_of_enum_string']).is_a?(Hash) + self.map_of_enum_string = value + end + end + + if attributes.key?(:'direct_map') + if (value = attributes[:'direct_map']).is_a?(Hash) + self.direct_map = value + end + end + + if attributes.key?(:'indirect_map') + if (value = attributes[:'indirect_map']).is_a?(Hash) + self.indirect_map = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + map_map_of_string == o.map_map_of_string && + map_of_enum_string == o.map_of_enum_string && + direct_map == o.direct_map && + indirect_map == o.indirect_map + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [map_map_of_string, map_of_enum_string, direct_map, indirect_map].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/mixed_properties_and_additional_properties_class.rb new file mode 100644 index 0000000000..93a1c6c4d7 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -0,0 +1,239 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class MixedPropertiesAndAdditionalPropertiesClass + attr_accessor :uuid + + attr_accessor :date_time + + attr_accessor :map + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'uuid' => :'uuid', + :'date_time' => :'dateTime', + :'map' => :'map' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'uuid' => :'String', + :'date_time' => :'Time', + :'map' => :'Hash' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::MixedPropertiesAndAdditionalPropertiesClass` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::MixedPropertiesAndAdditionalPropertiesClass`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'uuid') + self.uuid = attributes[:'uuid'] + end + + if attributes.key?(:'date_time') + self.date_time = attributes[:'date_time'] + end + + if attributes.key?(:'map') + if (value = attributes[:'map']).is_a?(Hash) + self.map = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + uuid == o.uuid && + date_time == o.date_time && + map == o.map + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [uuid, date_time, map].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/model200_response.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/model200_response.rb new file mode 100644 index 0000000000..9dd11b88dc --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/model200_response.rb @@ -0,0 +1,229 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + # Model for testing model name starting with number + class Model200Response + attr_accessor :name + + attr_accessor :_class + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'name' => :'name', + :'_class' => :'class' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'name' => :'Integer', + :'_class' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Model200Response` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Model200Response`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + + if attributes.key?(:'_class') + self._class = attributes[:'_class'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + name == o.name && + _class == o._class + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [name, _class].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/model_return.rb new file mode 100644 index 0000000000..1543f71d5d --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/model_return.rb @@ -0,0 +1,220 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + # Model for testing reserved words + class ModelReturn + attr_accessor :_return + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'_return' => :'return' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'_return' => :'Integer' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::ModelReturn` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::ModelReturn`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'_return') + self._return = attributes[:'_return'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + _return == o._return + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [_return].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/name.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/name.rb new file mode 100644 index 0000000000..e0f4d00c0b --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/name.rb @@ -0,0 +1,252 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + # Model for testing model name same as property name + class Name + attr_accessor :name + + attr_accessor :snake_case + + attr_accessor :property + + attr_accessor :_123_number + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'name' => :'name', + :'snake_case' => :'snake_case', + :'property' => :'property', + :'_123_number' => :'123Number' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'name' => :'Integer', + :'snake_case' => :'Integer', + :'property' => :'String', + :'_123_number' => :'Integer' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Name` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Name`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + + if attributes.key?(:'snake_case') + self.snake_case = attributes[:'snake_case'] + end + + if attributes.key?(:'property') + self.property = attributes[:'property'] + end + + if attributes.key?(:'_123_number') + self._123_number = attributes[:'_123_number'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if @name.nil? + invalid_properties.push('invalid value for "name", name cannot be nil.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if @name.nil? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + name == o.name && + snake_case == o.snake_case && + property == o.property && + _123_number == o._123_number + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [name, snake_case, property, _123_number].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/nullable_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/nullable_class.rb new file mode 100644 index 0000000000..cc768c1a03 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/nullable_class.rb @@ -0,0 +1,340 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class NullableClass + attr_accessor :integer_prop + + attr_accessor :number_prop + + attr_accessor :boolean_prop + + attr_accessor :string_prop + + attr_accessor :date_prop + + attr_accessor :datetime_prop + + attr_accessor :array_nullable_prop + + attr_accessor :array_and_items_nullable_prop + + attr_accessor :array_items_nullable + + attr_accessor :object_nullable_prop + + attr_accessor :object_and_items_nullable_prop + + attr_accessor :object_items_nullable + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'integer_prop' => :'integer_prop', + :'number_prop' => :'number_prop', + :'boolean_prop' => :'boolean_prop', + :'string_prop' => :'string_prop', + :'date_prop' => :'date_prop', + :'datetime_prop' => :'datetime_prop', + :'array_nullable_prop' => :'array_nullable_prop', + :'array_and_items_nullable_prop' => :'array_and_items_nullable_prop', + :'array_items_nullable' => :'array_items_nullable', + :'object_nullable_prop' => :'object_nullable_prop', + :'object_and_items_nullable_prop' => :'object_and_items_nullable_prop', + :'object_items_nullable' => :'object_items_nullable' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'integer_prop' => :'Integer', + :'number_prop' => :'Float', + :'boolean_prop' => :'Boolean', + :'string_prop' => :'String', + :'date_prop' => :'Date', + :'datetime_prop' => :'Time', + :'array_nullable_prop' => :'Array', + :'array_and_items_nullable_prop' => :'Array', + :'array_items_nullable' => :'Array', + :'object_nullable_prop' => :'Hash', + :'object_and_items_nullable_prop' => :'Hash', + :'object_items_nullable' => :'Hash' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + :'integer_prop', + :'number_prop', + :'boolean_prop', + :'string_prop', + :'date_prop', + :'datetime_prop', + :'array_nullable_prop', + :'array_and_items_nullable_prop', + :'object_nullable_prop', + :'object_and_items_nullable_prop', + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::NullableClass` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::NullableClass`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'integer_prop') + self.integer_prop = attributes[:'integer_prop'] + end + + if attributes.key?(:'number_prop') + self.number_prop = attributes[:'number_prop'] + end + + if attributes.key?(:'boolean_prop') + self.boolean_prop = attributes[:'boolean_prop'] + end + + if attributes.key?(:'string_prop') + self.string_prop = attributes[:'string_prop'] + end + + if attributes.key?(:'date_prop') + self.date_prop = attributes[:'date_prop'] + end + + if attributes.key?(:'datetime_prop') + self.datetime_prop = attributes[:'datetime_prop'] + end + + if attributes.key?(:'array_nullable_prop') + if (value = attributes[:'array_nullable_prop']).is_a?(Array) + self.array_nullable_prop = value + end + end + + if attributes.key?(:'array_and_items_nullable_prop') + if (value = attributes[:'array_and_items_nullable_prop']).is_a?(Array) + self.array_and_items_nullable_prop = value + end + end + + if attributes.key?(:'array_items_nullable') + if (value = attributes[:'array_items_nullable']).is_a?(Array) + self.array_items_nullable = value + end + end + + if attributes.key?(:'object_nullable_prop') + if (value = attributes[:'object_nullable_prop']).is_a?(Hash) + self.object_nullable_prop = value + end + end + + if attributes.key?(:'object_and_items_nullable_prop') + if (value = attributes[:'object_and_items_nullable_prop']).is_a?(Hash) + self.object_and_items_nullable_prop = value + end + end + + if attributes.key?(:'object_items_nullable') + if (value = attributes[:'object_items_nullable']).is_a?(Hash) + self.object_items_nullable = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + integer_prop == o.integer_prop && + number_prop == o.number_prop && + boolean_prop == o.boolean_prop && + string_prop == o.string_prop && + date_prop == o.date_prop && + datetime_prop == o.datetime_prop && + array_nullable_prop == o.array_nullable_prop && + array_and_items_nullable_prop == o.array_and_items_nullable_prop && + array_items_nullable == o.array_items_nullable && + object_nullable_prop == o.object_nullable_prop && + object_and_items_nullable_prop == o.object_and_items_nullable_prop && + object_items_nullable == o.object_items_nullable + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [integer_prop, number_prop, boolean_prop, string_prop, date_prop, datetime_prop, array_nullable_prop, array_and_items_nullable_prop, array_items_nullable, object_nullable_prop, object_and_items_nullable_prop, object_items_nullable].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/number_only.rb new file mode 100644 index 0000000000..b04314c703 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/number_only.rb @@ -0,0 +1,219 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class NumberOnly + attr_accessor :just_number + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'just_number' => :'JustNumber' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'just_number' => :'Float' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::NumberOnly` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::NumberOnly`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'just_number') + self.just_number = attributes[:'just_number'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + just_number == o.just_number + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [just_number].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/object_with_deprecated_fields.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/object_with_deprecated_fields.rb new file mode 100644 index 0000000000..8f511458c6 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/object_with_deprecated_fields.rb @@ -0,0 +1,248 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class ObjectWithDeprecatedFields + attr_accessor :uuid + + attr_accessor :id + + attr_accessor :deprecated_ref + + attr_accessor :bars + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'uuid' => :'uuid', + :'id' => :'id', + :'deprecated_ref' => :'deprecatedRef', + :'bars' => :'bars' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'uuid' => :'String', + :'id' => :'Float', + :'deprecated_ref' => :'DeprecatedObject', + :'bars' => :'Array' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::ObjectWithDeprecatedFields` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::ObjectWithDeprecatedFields`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'uuid') + self.uuid = attributes[:'uuid'] + end + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'deprecated_ref') + self.deprecated_ref = attributes[:'deprecated_ref'] + end + + if attributes.key?(:'bars') + if (value = attributes[:'bars']).is_a?(Array) + self.bars = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + uuid == o.uuid && + id == o.id && + deprecated_ref == o.deprecated_ref && + bars == o.bars + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [uuid, id, deprecated_ref, bars].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/order.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/order.rb new file mode 100644 index 0000000000..9ab55bee61 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/order.rb @@ -0,0 +1,301 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Order + attr_accessor :id + + attr_accessor :pet_id + + attr_accessor :quantity + + attr_accessor :ship_date + + # Order Status + attr_accessor :status + + attr_accessor :complete + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'pet_id' => :'petId', + :'quantity' => :'quantity', + :'ship_date' => :'shipDate', + :'status' => :'status', + :'complete' => :'complete' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'pet_id' => :'Integer', + :'quantity' => :'Integer', + :'ship_date' => :'Time', + :'status' => :'String', + :'complete' => :'Boolean' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Order` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Order`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'pet_id') + self.pet_id = attributes[:'pet_id'] + end + + if attributes.key?(:'quantity') + self.quantity = attributes[:'quantity'] + end + + if attributes.key?(:'ship_date') + self.ship_date = attributes[:'ship_date'] + end + + if attributes.key?(:'status') + self.status = attributes[:'status'] + end + + if attributes.key?(:'complete') + self.complete = attributes[:'complete'] + else + self.complete = false + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + status_validator = EnumAttributeValidator.new('String', ["placed", "approved", "delivered"]) + return false unless status_validator.valid?(@status) + true + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] status Object to be assigned + def status=(status) + validator = EnumAttributeValidator.new('String', ["placed", "approved", "delivered"]) + unless validator.valid?(status) + fail ArgumentError, "invalid value for \"status\", must be one of #{validator.allowable_values}." + end + @status = status + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + pet_id == o.pet_id && + quantity == o.quantity && + ship_date == o.ship_date && + status == o.status && + complete == o.complete + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, pet_id, quantity, ship_date, status, complete].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_composite.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_composite.rb new file mode 100644 index 0000000000..ba83c2a500 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_composite.rb @@ -0,0 +1,237 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class OuterComposite + attr_accessor :my_number + + attr_accessor :my_string + + attr_accessor :my_boolean + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'my_number' => :'my_number', + :'my_string' => :'my_string', + :'my_boolean' => :'my_boolean' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'my_number' => :'Float', + :'my_string' => :'String', + :'my_boolean' => :'Boolean' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::OuterComposite` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::OuterComposite`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'my_number') + self.my_number = attributes[:'my_number'] + end + + if attributes.key?(:'my_string') + self.my_string = attributes[:'my_string'] + end + + if attributes.key?(:'my_boolean') + self.my_boolean = attributes[:'my_boolean'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + my_number == o.my_number && + my_string == o.my_string && + my_boolean == o.my_boolean + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [my_number, my_string, my_boolean].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum.rb new file mode 100644 index 0000000000..cc0b78284c --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum.rb @@ -0,0 +1,41 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class OuterEnum + PLACED = "placed".freeze + APPROVED = "approved".freeze + DELIVERED = "delivered".freeze + + def self.all_vars + @all_vars ||= [PLACED, APPROVED, DELIVERED].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if OuterEnum.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnum" + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_default_value.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_default_value.rb new file mode 100644 index 0000000000..d4353f2972 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_default_value.rb @@ -0,0 +1,41 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class OuterEnumDefaultValue + PLACED = "placed".freeze + APPROVED = "approved".freeze + DELIVERED = "delivered".freeze + + def self.all_vars + @all_vars ||= [PLACED, APPROVED, DELIVERED].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if OuterEnumDefaultValue.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnumDefaultValue" + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer.rb new file mode 100644 index 0000000000..f5e5de7107 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer.rb @@ -0,0 +1,41 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class OuterEnumInteger + N0 = 0.freeze + N1 = 1.freeze + N2 = 2.freeze + + def self.all_vars + @all_vars ||= [N0, N1, N2].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if OuterEnumInteger.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnumInteger" + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer_default_value.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer_default_value.rb new file mode 100644 index 0000000000..388b00014e --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer_default_value.rb @@ -0,0 +1,41 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class OuterEnumIntegerDefaultValue + N0 = 0.freeze + N1 = 1.freeze + N2 = 2.freeze + + def self.all_vars + @all_vars ||= [N0, N1, N2].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if OuterEnumIntegerDefaultValue.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnumIntegerDefaultValue" + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_object_with_enum_property.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_object_with_enum_property.rb new file mode 100644 index 0000000000..650432f95d --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_object_with_enum_property.rb @@ -0,0 +1,224 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class OuterObjectWithEnumProperty + attr_accessor :value + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'value' => :'value' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'value' => :'OuterEnumInteger' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::OuterObjectWithEnumProperty` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::OuterObjectWithEnumProperty`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'value') + self.value = attributes[:'value'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if @value.nil? + invalid_properties.push('invalid value for "value", value cannot be nil.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if @value.nil? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + value == o.value + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [value].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/pet.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/pet.rb new file mode 100644 index 0000000000..78934ccb03 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/pet.rb @@ -0,0 +1,323 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Pet + attr_accessor :id + + attr_accessor :category + + attr_accessor :name + + attr_accessor :photo_urls + + attr_accessor :tags + + # pet status in the store + attr_accessor :status + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'category' => :'category', + :'name' => :'name', + :'photo_urls' => :'photoUrls', + :'tags' => :'tags', + :'status' => :'status' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'category' => :'Category', + :'name' => :'String', + :'photo_urls' => :'Array', + :'tags' => :'Array', + :'status' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Pet` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Pet`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'category') + self.category = attributes[:'category'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + + if attributes.key?(:'photo_urls') + if (value = attributes[:'photo_urls']).is_a?(Array) + self.photo_urls = value + end + end + + if attributes.key?(:'tags') + if (value = attributes[:'tags']).is_a?(Array) + self.tags = value + end + end + + if attributes.key?(:'status') + self.status = attributes[:'status'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + if @name.nil? + invalid_properties.push('invalid value for "name", name cannot be nil.') + end + + if @photo_urls.nil? + invalid_properties.push('invalid value for "photo_urls", photo_urls cannot be nil.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return false if @name.nil? + return false if @photo_urls.nil? + status_validator = EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + return false unless status_validator.valid?(@status) + true + end + + # Custom attribute writer method with validation + # @param [Object] photo_urls Value to be assigned + def photo_urls=(photo_urls) + if photo_urls.nil? + fail ArgumentError, 'photo_urls cannot be nil' + end + + @photo_urls = photo_urls + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] status Object to be assigned + def status=(status) + validator = EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + unless validator.valid?(status) + fail ArgumentError, "invalid value for \"status\", must be one of #{validator.allowable_values}." + end + @status = status + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + category == o.category && + name == o.name && + photo_urls == o.photo_urls && + tags == o.tags && + status == o.status + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, category, name, photo_urls, tags, status].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/read_only_first.rb new file mode 100644 index 0000000000..8afb713ede --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/read_only_first.rb @@ -0,0 +1,228 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class ReadOnlyFirst + attr_accessor :bar + + attr_accessor :baz + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'bar' => :'bar', + :'baz' => :'baz' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'bar' => :'String', + :'baz' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::ReadOnlyFirst` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::ReadOnlyFirst`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'bar') + self.bar = attributes[:'bar'] + end + + if attributes.key?(:'baz') + self.baz = attributes[:'baz'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + bar == o.bar && + baz == o.baz + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [bar, baz].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/single_ref_type.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/single_ref_type.rb new file mode 100644 index 0000000000..746e50cbec --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/single_ref_type.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class SingleRefType + ADMIN = "admin".freeze + USER = "user".freeze + + def self.all_vars + @all_vars ||= [ADMIN, USER].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if SingleRefType.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #SingleRefType" + end + end +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/special_model_name.rb new file mode 100644 index 0000000000..d1a049eec3 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/special_model_name.rb @@ -0,0 +1,219 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class SpecialModelName + attr_accessor :special_property_name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'special_property_name' => :'$special[property.name]' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'special_property_name' => :'Integer' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::SpecialModelName` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::SpecialModelName`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'special_property_name') + self.special_property_name = attributes[:'special_property_name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + special_property_name == o.special_property_name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [special_property_name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/tag.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/tag.rb new file mode 100644 index 0000000000..894e4c24ac --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/tag.rb @@ -0,0 +1,228 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Tag + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'name' => :'name' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::Tag` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::Tag`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/user.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/user.rb new file mode 100644 index 0000000000..e34d1381ea --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/user.rb @@ -0,0 +1,283 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class User + attr_accessor :id + + attr_accessor :username + + attr_accessor :first_name + + attr_accessor :last_name + + attr_accessor :email + + attr_accessor :password + + attr_accessor :phone + + # User Status + attr_accessor :user_status + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'username' => :'username', + :'first_name' => :'firstName', + :'last_name' => :'lastName', + :'email' => :'email', + :'password' => :'password', + :'phone' => :'phone', + :'user_status' => :'userStatus' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'username' => :'String', + :'first_name' => :'String', + :'last_name' => :'String', + :'email' => :'String', + :'password' => :'String', + :'phone' => :'String', + :'user_status' => :'Integer' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::User` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::User`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'username') + self.username = attributes[:'username'] + end + + if attributes.key?(:'first_name') + self.first_name = attributes[:'first_name'] + end + + if attributes.key?(:'last_name') + self.last_name = attributes[:'last_name'] + end + + if attributes.key?(:'email') + self.email = attributes[:'email'] + end + + if attributes.key?(:'password') + self.password = attributes[:'password'] + end + + if attributes.key?(:'phone') + self.phone = attributes[:'phone'] + end + + if attributes.key?(:'user_status') + self.user_status = attributes[:'user_status'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + username == o.username && + first_name == o.first_name && + last_name == o.last_name && + email == o.email && + password == o.password && + phone == o.phone && + user_status == o.user_status + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, username, first_name, last_name, email, password, phone, user_status].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + new.build_from_hash(attributes) + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + self.class.openapi_types.each_pair do |key, type| + if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) + self.send("#{key}=", nil) + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = Petstore.const_get(type) + klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/version.rb b/samples/client/petstore/ruby-autoload/lib/petstore/version.rb new file mode 100644 index 0000000000..c7ded788d0 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/lib/petstore/version.rb @@ -0,0 +1,15 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +module Petstore + VERSION = '1.0.0' +end diff --git a/samples/client/petstore/ruby-autoload/petstore.gemspec b/samples/client/petstore/ruby-autoload/petstore.gemspec new file mode 100644 index 0000000000..5106da6e09 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/petstore.gemspec @@ -0,0 +1,38 @@ +# -*- encoding: utf-8 -*- + +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +$:.push File.expand_path("../lib", __FILE__) +require "petstore/version" + +Gem::Specification.new do |s| + s.name = "petstore" + s.version = Petstore::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["OpenAPI-Generator"] + s.email = [""] + s.homepage = "https://openapi-generator.tech" + s.summary = "OpenAPI Petstore Ruby Gem" + s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" + s.license = "Unlicense" + s.required_ruby_version = ">= 2.4" + + s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' + + s.add_development_dependency 'rspec', '~> 3.6', '>= 3.6.0' + + s.files = `find *`.split("\n").uniq.sort.select { |f| !f.empty? } + s.test_files = `find spec/*`.split("\n") + s.executables = [] + s.require_paths = ["lib"] +end diff --git a/samples/client/petstore/ruby-autoload/pom.xml b/samples/client/petstore/ruby-autoload/pom.xml new file mode 100644 index 0000000000..222c9e18df --- /dev/null +++ b/samples/client/petstore/ruby-autoload/pom.xml @@ -0,0 +1,62 @@ + + 4.0.0 + org.openapitools + RubyAutoloadClientTests + pom + 1.0-SNAPSHOT + Ruby Autoload Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bundle-install + pre-integration-test + + exec + + + bundle + + install + --path + vendor/bundle + + + + + bundle-test + integration-test + + exec + + + bundle + + exec + rspec + + + + + + + + diff --git a/samples/client/petstore/ruby-autoload/spec/api/another_fake_api_spec.rb b/samples/client/petstore/ruby-autoload/spec/api/another_fake_api_spec.rb new file mode 100644 index 0000000000..523b4b9fc4 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/api/another_fake_api_spec.rb @@ -0,0 +1,47 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for Petstore::AnotherFakeApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'AnotherFakeApi' do + before do + # run before each test + @api_instance = Petstore::AnotherFakeApi.new + end + + after do + # run after each test + end + + describe 'test an instance of AnotherFakeApi' do + it 'should create an instance of AnotherFakeApi' do + expect(@api_instance).to be_instance_of(Petstore::AnotherFakeApi) + end + end + + # unit tests for call_123_test_special_tags + # To test special tags + # To test special tags and operation ID starting with number + # @param client client model + # @param [Hash] opts the optional parameters + # @return [Client] + describe 'call_123_test_special_tags test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/api/default_api_spec.rb b/samples/client/petstore/ruby-autoload/spec/api/default_api_spec.rb new file mode 100644 index 0000000000..4c860076c0 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/api/default_api_spec.rb @@ -0,0 +1,44 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for Petstore::DefaultApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'DefaultApi' do + before do + # run before each test + @api_instance = Petstore::DefaultApi.new + end + + after do + # run after each test + end + + describe 'test an instance of DefaultApi' do + it 'should create an instance of DefaultApi' do + expect(@api_instance).to be_instance_of(Petstore::DefaultApi) + end + end + + # unit tests for foo_get + # @param [Hash] opts the optional parameters + # @return [FooGetDefaultResponse] + describe 'foo_get test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/api/fake_api_spec.rb b/samples/client/petstore/ruby-autoload/spec/api/fake_api_spec.rb new file mode 100644 index 0000000000..dc56a801e6 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/api/fake_api_spec.rb @@ -0,0 +1,262 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for Petstore::FakeApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'FakeApi' do + before do + # run before each test + @api_instance = Petstore::FakeApi.new + end + + after do + # run after each test + end + + describe 'test an instance of FakeApi' do + it 'should create an instance of FakeApi' do + expect(@api_instance).to be_instance_of(Petstore::FakeApi) + end + end + + # unit tests for fake_health_get + # Health check endpoint + # @param [Hash] opts the optional parameters + # @return [HealthCheckResult] + describe 'fake_health_get test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for fake_http_signature_test + # test http signature authentication + # @param pet Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @option opts [String] :query_1 query parameter + # @option opts [String] :header_1 header parameter + # @return [nil] + describe 'fake_http_signature_test test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for fake_outer_boolean_serialize + # Test serialization of outer boolean types + # @param [Hash] opts the optional parameters + # @option opts [Boolean] :body Input boolean as post body + # @return [Boolean] + describe 'fake_outer_boolean_serialize test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for fake_outer_composite_serialize + # Test serialization of object with outer number type + # @param [Hash] opts the optional parameters + # @option opts [OuterComposite] :outer_composite Input composite as post body + # @return [OuterComposite] + describe 'fake_outer_composite_serialize test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for fake_outer_number_serialize + # Test serialization of outer number types + # @param [Hash] opts the optional parameters + # @option opts [Float] :body Input number as post body + # @return [Float] + describe 'fake_outer_number_serialize test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for fake_outer_string_serialize + # Test serialization of outer string types + # @param [Hash] opts the optional parameters + # @option opts [String] :body Input string as post body + # @return [String] + describe 'fake_outer_string_serialize test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for fake_property_enum_integer_serialize + # Test serialization of enum (int) properties with examples + # @param outer_object_with_enum_property Input enum (int) as post body + # @param [Hash] opts the optional parameters + # @return [OuterObjectWithEnumProperty] + describe 'fake_property_enum_integer_serialize test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_body_with_binary + # For this test, the body has to be a binary file. + # @param body image to upload + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'test_body_with_binary test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_body_with_file_schema + # For this test, the body for this request must reference a schema named `File`. + # @param file_schema_test_class + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'test_body_with_file_schema test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_body_with_query_params + # @param query + # @param user + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'test_body_with_query_params test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_client_model + # To test \"client\" model + # To test \"client\" model + # @param client client model + # @param [Hash] opts the optional parameters + # @return [Client] + describe 'test_client_model test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_endpoint_parameters + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # @param number None + # @param double None + # @param pattern_without_delimiter None + # @param byte None + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer None + # @option opts [Integer] :int32 None + # @option opts [Integer] :int64 None + # @option opts [Float] :float None + # @option opts [String] :string None + # @option opts [File] :binary None + # @option opts [Date] :date None + # @option opts [Time] :date_time None + # @option opts [String] :password None + # @option opts [String] :callback None + # @return [nil] + describe 'test_endpoint_parameters test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_enum_parameters + # To test enum parameters + # To test enum parameters + # @param [Hash] opts the optional parameters + # @option opts [Array] :enum_header_string_array Header parameter enum test (string array) + # @option opts [String] :enum_header_string Header parameter enum test (string) + # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) + # @option opts [String] :enum_query_string Query parameter enum test (string) + # @option opts [Integer] :enum_query_integer Query parameter enum test (double) + # @option opts [Float] :enum_query_double Query parameter enum test (double) + # @option opts [Array] :enum_query_model_array + # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) + # @option opts [String] :enum_form_string Form parameter enum test (string) + # @return [nil] + describe 'test_enum_parameters test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_group_parameters + # Fake endpoint to test group parameters (optional) + # Fake endpoint to test group parameters (optional) + # @param required_string_group Required String in group parameters + # @param required_boolean_group Required Boolean in group parameters + # @param required_int64_group Required Integer in group parameters + # @param [Hash] opts the optional parameters + # @option opts [Integer] :string_group String in group parameters + # @option opts [Boolean] :boolean_group Boolean in group parameters + # @option opts [Integer] :int64_group Integer in group parameters + # @return [nil] + describe 'test_group_parameters test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_inline_additional_properties + # test inline additionalProperties + # + # @param request_body request body + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'test_inline_additional_properties test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_json_form_data + # test json serialization of form data + # + # @param param field1 + # @param param2 field2 + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'test_json_form_data test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for test_query_parameter_collection_format + # To test the collection format in query parameters + # @param pipe + # @param ioutil + # @param http + # @param url + # @param context + # @param allow_empty + # @param [Hash] opts the optional parameters + # @option opts [Hash] :language + # @return [nil] + describe 'test_query_parameter_collection_format test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/api/fake_classname_tags123_api_spec.rb b/samples/client/petstore/ruby-autoload/spec/api/fake_classname_tags123_api_spec.rb new file mode 100644 index 0000000000..1f0665451e --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/api/fake_classname_tags123_api_spec.rb @@ -0,0 +1,47 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for Petstore::FakeClassnameTags123Api +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'FakeClassnameTags123Api' do + before do + # run before each test + @api_instance = Petstore::FakeClassnameTags123Api.new + end + + after do + # run after each test + end + + describe 'test an instance of FakeClassnameTags123Api' do + it 'should create an instance of FakeClassnameTags123Api' do + expect(@api_instance).to be_instance_of(Petstore::FakeClassnameTags123Api) + end + end + + # unit tests for test_classname + # To test class name in snake case + # To test class name in snake case + # @param client client model + # @param [Hash] opts the optional parameters + # @return [Client] + describe 'test_classname test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/api/pet_api_spec.rb b/samples/client/petstore/ruby-autoload/spec/api/pet_api_spec.rb new file mode 100644 index 0000000000..b474770871 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/api/pet_api_spec.rb @@ -0,0 +1,150 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for Petstore::PetApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'PetApi' do + before do + # run before each test + @api_instance = Petstore::PetApi.new + end + + after do + # run after each test + end + + describe 'test an instance of PetApi' do + it 'should create an instance of PetApi' do + expect(@api_instance).to be_instance_of(Petstore::PetApi) + end + end + + # unit tests for add_pet + # Add a new pet to the store + # + # @param pet Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'add_pet test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for delete_pet + # Deletes a pet + # + # @param pet_id Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [String] :api_key + # @return [nil] + describe 'delete_pet test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for find_pets_by_status + # Finds Pets by status + # Multiple status values can be provided with comma separated strings + # @param status Status values that need to be considered for filter + # @param [Hash] opts the optional parameters + # @return [Array] + describe 'find_pets_by_status test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for find_pets_by_tags + # Finds Pets by tags + # Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + # @param tags Tags to filter by + # @param [Hash] opts the optional parameters + # @return [Array] + describe 'find_pets_by_tags test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for get_pet_by_id + # Find pet by ID + # Returns a single pet + # @param pet_id ID of pet to return + # @param [Hash] opts the optional parameters + # @return [Pet] + describe 'get_pet_by_id test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for update_pet + # Update an existing pet + # + # @param pet Pet object that needs to be added to the store + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'update_pet test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for update_pet_with_form + # Updates a pet in the store with form data + # + # @param pet_id ID of pet that needs to be updated + # @param [Hash] opts the optional parameters + # @option opts [String] :name Updated name of the pet + # @option opts [String] :status Updated status of the pet + # @return [nil] + describe 'update_pet_with_form test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for upload_file + # uploads an image + # + # @param pet_id ID of pet to update + # @param [Hash] opts the optional parameters + # @option opts [String] :additional_metadata Additional data to pass to server + # @option opts [File] :file file to upload + # @return [ApiResponse] + describe 'upload_file test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for upload_file_with_required_file + # uploads an image (required) + # + # @param pet_id ID of pet to update + # @param required_file file to upload + # @param [Hash] opts the optional parameters + # @option opts [String] :additional_metadata Additional data to pass to server + # @return [ApiResponse] + describe 'upload_file_with_required_file test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/api/store_api_spec.rb b/samples/client/petstore/ruby-autoload/spec/api/store_api_spec.rb new file mode 100644 index 0000000000..165cc7a2b9 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/api/store_api_spec.rb @@ -0,0 +1,82 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for Petstore::StoreApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'StoreApi' do + before do + # run before each test + @api_instance = Petstore::StoreApi.new + end + + after do + # run after each test + end + + describe 'test an instance of StoreApi' do + it 'should create an instance of StoreApi' do + expect(@api_instance).to be_instance_of(Petstore::StoreApi) + end + end + + # unit tests for delete_order + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order_id ID of the order that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'delete_order test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for get_inventory + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return [Hash] + describe 'get_inventory test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for get_order_by_id + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return [Order] + describe 'get_order_by_id test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for place_order + # Place an order for a pet + # + # @param order order placed for purchasing the pet + # @param [Hash] opts the optional parameters + # @return [Order] + describe 'place_order test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/api/user_api_spec.rb b/samples/client/petstore/ruby-autoload/spec/api/user_api_spec.rb new file mode 100644 index 0000000000..e3eae5db7d --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/api/user_api_spec.rb @@ -0,0 +1,132 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for Petstore::UserApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'UserApi' do + before do + # run before each test + @api_instance = Petstore::UserApi.new + end + + after do + # run after each test + end + + describe 'test an instance of UserApi' do + it 'should create an instance of UserApi' do + expect(@api_instance).to be_instance_of(Petstore::UserApi) + end + end + + # unit tests for create_user + # Create user + # This can only be done by the logged in user. + # @param user Created user object + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'create_user test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for create_users_with_array_input + # Creates list of users with given input array + # + # @param user List of user object + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'create_users_with_array_input test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for create_users_with_list_input + # Creates list of users with given input array + # + # @param user List of user object + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'create_users_with_list_input test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for delete_user + # Delete user + # This can only be done by the logged in user. + # @param username The name that needs to be deleted + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'delete_user test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for get_user_by_name + # Get user by user name + # + # @param username The name that needs to be fetched. Use user1 for testing. + # @param [Hash] opts the optional parameters + # @return [User] + describe 'get_user_by_name test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for login_user + # Logs user into the system + # + # @param username The user name for login + # @param password The password for login in clear text + # @param [Hash] opts the optional parameters + # @return [String] + describe 'login_user test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for logout_user + # Logs out current logged in user session + # + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'logout_user test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + # unit tests for update_user + # Updated user + # This can only be done by the logged in user. + # @param username name that need to be deleted + # @param user Updated user object + # @param [Hash] opts the optional parameters + # @return [nil] + describe 'update_user test' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/api_client_spec.rb b/samples/client/petstore/ruby-autoload/spec/api_client_spec.rb new file mode 100644 index 0000000000..7dce33ae2e --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/api_client_spec.rb @@ -0,0 +1,226 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'spec_helper' + +describe Petstore::ApiClient do + context 'initialization' do + context 'URL stuff' do + context 'host' do + it 'removes http from host' do + Petstore.configure { |c| c.host = 'http://example.com' } + expect(Petstore::Configuration.default.host).to eq('example.com') + end + + it 'removes https from host' do + Petstore.configure { |c| c.host = 'https://wookiee.com' } + expect(Petstore::ApiClient.default.config.host).to eq('wookiee.com') + end + + it 'removes trailing path from host' do + Petstore.configure { |c| c.host = 'hobo.com/v4' } + expect(Petstore::Configuration.default.host).to eq('hobo.com') + end + end + + context 'base_path' do + it "prepends a slash to base_path" do + Petstore.configure { |c| c.base_path = 'v4/dog' } + expect(Petstore::Configuration.default.base_path).to eq('/v4/dog') + end + + it "doesn't prepend a slash if one is already there" do + Petstore.configure { |c| c.base_path = '/v4/dog' } + expect(Petstore::Configuration.default.base_path).to eq('/v4/dog') + end + + it "ends up as a blank string if nil" do + Petstore.configure { |c| c.base_path = nil } + expect(Petstore::Configuration.default.base_path).to eq('') + end + end + end + end + + describe 'params_encoding in #build_request' do + let(:config) { Petstore::Configuration.new } + let(:api_client) { Petstore::ApiClient.new(config) } + + it 'defaults to nil' do + expect(Petstore::Configuration.default.params_encoding).to eq(nil) + expect(config.params_encoding).to eq(nil) + + request = api_client.build_request(:get, '/test') + expect(request.options[:params_encoding]).to eq(nil) + end + + it 'can be customized' do + config.params_encoding = :multi + request = api_client.build_request(:get, '/test') + expect(request.options[:params_encoding]).to eq(:multi) + end + end + + describe 'timeout in #build_request' do + let(:config) { Petstore::Configuration.new } + let(:api_client) { Petstore::ApiClient.new(config) } + + it 'defaults to 0' do + expect(Petstore::Configuration.default.timeout).to eq(0) + expect(config.timeout).to eq(0) + + request = api_client.build_request(:get, '/test') + expect(request.options[:timeout]).to eq(0) + end + + it 'can be customized' do + config.timeout = 100 + request = api_client.build_request(:get, '/test') + expect(request.options[:timeout]).to eq(100) + end + end + + describe '#deserialize' do + it "handles Array" do + api_client = Petstore::ApiClient.new + headers = { 'Content-Type' => 'application/json' } + response = double('response', headers: headers, body: '[12, 34]') + data = api_client.deserialize(response, 'Array') + expect(data).to be_instance_of(Array) + expect(data).to eq([12, 34]) + end + + it 'handles Array>' do + api_client = Petstore::ApiClient.new + headers = { 'Content-Type' => 'application/json' } + response = double('response', headers: headers, body: '[[12, 34], [56]]') + data = api_client.deserialize(response, 'Array>') + expect(data).to be_instance_of(Array) + expect(data).to eq([[12, 34], [56]]) + end + + it 'handles Hash' do + api_client = Petstore::ApiClient.new + headers = { 'Content-Type' => 'application/json' } + response = double('response', headers: headers, body: '{"message": "Hello"}') + data = api_client.deserialize(response, 'Hash') + expect(data).to be_instance_of(Hash) + expect(data).to eq(:message => 'Hello') + end + end + + describe "#object_to_hash" do + it 'ignores nils and includes empty arrays' do + # uncomment below to test object_to_hash for model + # api_client = Petstore::ApiClient.new + # _model = Petstore::ModelName.new + # update the model attribute below + # _model.id = 1 + # update the expected value (hash) below + # expected = {id: 1, name: '', tags: []} + # expect(api_client.object_to_hash(_model)).to eq(expected) + end + end + + describe '#build_collection_param' do + let(:param) { ['aa', 'bb', 'cc'] } + let(:api_client) { Petstore::ApiClient.new } + + it 'works for csv' do + expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc') + end + + it 'works for ssv' do + expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc') + end + + it 'works for tsv' do + expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc") + end + + it 'works for pipes' do + expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc') + end + + it 'works for multi' do + expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc']) + end + + it 'fails for invalid collection format' do + expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') + end + end + + describe '#json_mime?' do + let(:api_client) { Petstore::ApiClient.new } + + it 'works' do + expect(api_client.json_mime?(nil)).to eq false + expect(api_client.json_mime?('')).to eq false + + expect(api_client.json_mime?('application/json')).to eq true + expect(api_client.json_mime?('application/json; charset=UTF8')).to eq true + expect(api_client.json_mime?('APPLICATION/JSON')).to eq true + + expect(api_client.json_mime?('application/xml')).to eq false + expect(api_client.json_mime?('text/plain')).to eq false + expect(api_client.json_mime?('application/jsonp')).to eq false + end + end + + describe '#select_header_accept' do + let(:api_client) { Petstore::ApiClient.new } + + it 'works' do + expect(api_client.select_header_accept(nil)).to be_nil + expect(api_client.select_header_accept([])).to be_nil + + expect(api_client.select_header_accept(['application/json'])).to eq('application/json') + expect(api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_accept(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') + + expect(api_client.select_header_accept(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_accept(['text/html', 'application/xml'])).to eq('text/html,application/xml') + end + end + + describe '#select_header_content_type' do + let(:api_client) { Petstore::ApiClient.new } + + it 'works' do + expect(api_client.select_header_content_type(nil)).to be_nil + expect(api_client.select_header_content_type([])).to be_nil + + expect(api_client.select_header_content_type(['application/json'])).to eq('application/json') + expect(api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') + expect(api_client.select_header_content_type(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') + expect(api_client.select_header_content_type(['application/xml'])).to eq('application/xml') + expect(api_client.select_header_content_type(['text/plain', 'application/xml'])).to eq('text/plain') + end + end + + describe '#sanitize_filename' do + let(:api_client) { Petstore::ApiClient.new } + + it 'works' do + expect(api_client.sanitize_filename('sun')).to eq('sun') + expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('/var/tmp/sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('./sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('..\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('c:\var\tmp\sun.gif')).to eq('sun.gif') + expect(api_client.sanitize_filename('.\sun.gif')).to eq('sun.gif') + end + end +end diff --git a/samples/client/petstore/ruby-autoload/spec/configuration_spec.rb b/samples/client/petstore/ruby-autoload/spec/configuration_spec.rb new file mode 100644 index 0000000000..59363666a1 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/configuration_spec.rb @@ -0,0 +1,42 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +require 'spec_helper' + +describe Petstore::Configuration do + let(:config) { Petstore::Configuration.default } + + before(:each) do + # uncomment below to setup host and base_path + # require 'URI' + # uri = URI.parse("http://petstore.swagger.io:80/v2") + # Petstore.configure do |c| + # c.host = uri.host + # c.base_path = uri.path + # end + end + + describe '#base_url' do + it 'should have the default value' do + # uncomment below to test default value of the base path + # expect(config.base_url).to eq("http://petstore.swagger.io:80/v2") + end + + it 'should remove trailing slashes' do + [nil, '', '/', '//'].each do |base_path| + config.base_path = base_path + # uncomment below to test trailing slashes + # expect(config.base_url).to eq("http://petstore.swagger.io:80/v2") + end + end + end +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/additional_properties_class_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/additional_properties_class_spec.rb new file mode 100644 index 0000000000..0daa268698 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/additional_properties_class_spec.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::AdditionalPropertiesClass +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::AdditionalPropertiesClass do + let(:instance) { Petstore::AdditionalPropertiesClass.new } + + describe 'test an instance of AdditionalPropertiesClass' do + it 'should create an instance of AdditionalPropertiesClass' do + expect(instance).to be_instance_of(Petstore::AdditionalPropertiesClass) + end + end + describe 'test attribute "map_property"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "map_of_map_property"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/all_of_with_single_ref_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/all_of_with_single_ref_spec.rb new file mode 100644 index 0000000000..3b52a10b6a --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/all_of_with_single_ref_spec.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::AllOfWithSingleRef +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::AllOfWithSingleRef do + let(:instance) { Petstore::AllOfWithSingleRef.new } + + describe 'test an instance of AllOfWithSingleRef' do + it 'should create an instance of AllOfWithSingleRef' do + expect(instance).to be_instance_of(Petstore::AllOfWithSingleRef) + end + end + describe 'test attribute "username"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "single_ref_type"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/animal_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/animal_spec.rb new file mode 100644 index 0000000000..ef60372f48 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/animal_spec.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Animal +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Animal do + let(:instance) { Petstore::Animal.new } + + describe 'test an instance of Animal' do + it 'should create an instance of Animal' do + expect(instance).to be_instance_of(Petstore::Animal) + end + end + describe 'test attribute "class_name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "color"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/api_response_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/api_response_spec.rb new file mode 100644 index 0000000000..3b9a30ae8a --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/api_response_spec.rb @@ -0,0 +1,46 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ApiResponse +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::ApiResponse do + let(:instance) { Petstore::ApiResponse.new } + + describe 'test an instance of ApiResponse' do + it 'should create an instance of ApiResponse' do + expect(instance).to be_instance_of(Petstore::ApiResponse) + end + end + describe 'test attribute "code"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "type"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "message"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/array_of_array_of_number_only_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/array_of_array_of_number_only_spec.rb new file mode 100644 index 0000000000..c99f7a21ca --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/array_of_array_of_number_only_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ArrayOfArrayOfNumberOnly +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::ArrayOfArrayOfNumberOnly do + let(:instance) { Petstore::ArrayOfArrayOfNumberOnly.new } + + describe 'test an instance of ArrayOfArrayOfNumberOnly' do + it 'should create an instance of ArrayOfArrayOfNumberOnly' do + expect(instance).to be_instance_of(Petstore::ArrayOfArrayOfNumberOnly) + end + end + describe 'test attribute "array_array_number"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/array_of_number_only_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/array_of_number_only_spec.rb new file mode 100644 index 0000000000..cbc701d20d --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/array_of_number_only_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ArrayOfNumberOnly +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::ArrayOfNumberOnly do + let(:instance) { Petstore::ArrayOfNumberOnly.new } + + describe 'test an instance of ArrayOfNumberOnly' do + it 'should create an instance of ArrayOfNumberOnly' do + expect(instance).to be_instance_of(Petstore::ArrayOfNumberOnly) + end + end + describe 'test attribute "array_number"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/array_test_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/array_test_spec.rb new file mode 100644 index 0000000000..adfd4d8fb4 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/array_test_spec.rb @@ -0,0 +1,46 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ArrayTest +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::ArrayTest do + let(:instance) { Petstore::ArrayTest.new } + + describe 'test an instance of ArrayTest' do + it 'should create an instance of ArrayTest' do + expect(instance).to be_instance_of(Petstore::ArrayTest) + end + end + describe 'test attribute "array_of_string"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "array_array_of_integer"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "array_array_of_model"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/capitalization_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/capitalization_spec.rb new file mode 100644 index 0000000000..d3ff44c566 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/capitalization_spec.rb @@ -0,0 +1,64 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Capitalization +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Capitalization do + let(:instance) { Petstore::Capitalization.new } + + describe 'test an instance of Capitalization' do + it 'should create an instance of Capitalization' do + expect(instance).to be_instance_of(Petstore::Capitalization) + end + end + describe 'test attribute "small_camel"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "capital_camel"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "small_snake"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "capital_snake"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "sca_eth_flow_points"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "att_name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/cat_all_of_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/cat_all_of_spec.rb new file mode 100644 index 0000000000..a073f30b28 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/cat_all_of_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::CatAllOf +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::CatAllOf do + let(:instance) { Petstore::CatAllOf.new } + + describe 'test an instance of CatAllOf' do + it 'should create an instance of CatAllOf' do + expect(instance).to be_instance_of(Petstore::CatAllOf) + end + end + describe 'test attribute "declawed"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/cat_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/cat_spec.rb new file mode 100644 index 0000000000..6a51da1376 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/cat_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Cat +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Cat do + let(:instance) { Petstore::Cat.new } + + describe 'test an instance of Cat' do + it 'should create an instance of Cat' do + expect(instance).to be_instance_of(Petstore::Cat) + end + end + describe 'test attribute "declawed"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/category_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/category_spec.rb new file mode 100644 index 0000000000..3016883fe2 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/category_spec.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Category +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Category do + let(:instance) { Petstore::Category.new } + + describe 'test an instance of Category' do + it 'should create an instance of Category' do + expect(instance).to be_instance_of(Petstore::Category) + end + end + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/class_model_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/class_model_spec.rb new file mode 100644 index 0000000000..1f8377d284 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/class_model_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ClassModel +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::ClassModel do + let(:instance) { Petstore::ClassModel.new } + + describe 'test an instance of ClassModel' do + it 'should create an instance of ClassModel' do + expect(instance).to be_instance_of(Petstore::ClassModel) + end + end + describe 'test attribute "_class"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/client_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/client_spec.rb new file mode 100644 index 0000000000..f16856f240 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/client_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Client +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Client do + let(:instance) { Petstore::Client.new } + + describe 'test an instance of Client' do + it 'should create an instance of Client' do + expect(instance).to be_instance_of(Petstore::Client) + end + end + describe 'test attribute "client"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/deprecated_object_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/deprecated_object_spec.rb new file mode 100644 index 0000000000..27fba88874 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/deprecated_object_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::DeprecatedObject +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::DeprecatedObject do + let(:instance) { Petstore::DeprecatedObject.new } + + describe 'test an instance of DeprecatedObject' do + it 'should create an instance of DeprecatedObject' do + expect(instance).to be_instance_of(Petstore::DeprecatedObject) + end + end + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/dog_all_of_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/dog_all_of_spec.rb new file mode 100644 index 0000000000..f4324654b5 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/dog_all_of_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::DogAllOf +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::DogAllOf do + let(:instance) { Petstore::DogAllOf.new } + + describe 'test an instance of DogAllOf' do + it 'should create an instance of DogAllOf' do + expect(instance).to be_instance_of(Petstore::DogAllOf) + end + end + describe 'test attribute "breed"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/dog_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/dog_spec.rb new file mode 100644 index 0000000000..9c335f7cc2 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/dog_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Dog +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Dog do + let(:instance) { Petstore::Dog.new } + + describe 'test an instance of Dog' do + it 'should create an instance of Dog' do + expect(instance).to be_instance_of(Petstore::Dog) + end + end + describe 'test attribute "breed"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/enum_arrays_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/enum_arrays_spec.rb new file mode 100644 index 0000000000..77dfa19702 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/enum_arrays_spec.rb @@ -0,0 +1,48 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::EnumArrays +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::EnumArrays do + let(:instance) { Petstore::EnumArrays.new } + + describe 'test an instance of EnumArrays' do + it 'should create an instance of EnumArrays' do + expect(instance).to be_instance_of(Petstore::EnumArrays) + end + end + describe 'test attribute "just_symbol"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', [">=", "$"]) + # validator.allowable_values.each do |value| + # expect { instance.just_symbol = value }.not_to raise_error + # end + end + end + + describe 'test attribute "array_enum"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Array', ["fish", "crab"]) + # validator.allowable_values.each do |value| + # expect { instance.array_enum = value }.not_to raise_error + # end + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/enum_class_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/enum_class_spec.rb new file mode 100644 index 0000000000..0cdc3dc890 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/enum_class_spec.rb @@ -0,0 +1,28 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::EnumClass +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::EnumClass do + let(:instance) { Petstore::EnumClass.new } + + describe 'test an instance of EnumClass' do + it 'should create an instance of EnumClass' do + expect(instance).to be_instance_of(Petstore::EnumClass) + end + end +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/enum_test_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/enum_test_spec.rb new file mode 100644 index 0000000000..67553e59b3 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/enum_test_spec.rb @@ -0,0 +1,92 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::EnumTest +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::EnumTest do + let(:instance) { Petstore::EnumTest.new } + + describe 'test an instance of EnumTest' do + it 'should create an instance of EnumTest' do + expect(instance).to be_instance_of(Petstore::EnumTest) + end + end + describe 'test attribute "enum_string"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) + # validator.allowable_values.each do |value| + # expect { instance.enum_string = value }.not_to raise_error + # end + end + end + + describe 'test attribute "enum_string_required"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) + # validator.allowable_values.each do |value| + # expect { instance.enum_string_required = value }.not_to raise_error + # end + end + end + + describe 'test attribute "enum_integer"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Integer', [1, -1]) + # validator.allowable_values.each do |value| + # expect { instance.enum_integer = value }.not_to raise_error + # end + end + end + + describe 'test attribute "enum_number"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Float', [1.1, -1.2]) + # validator.allowable_values.each do |value| + # expect { instance.enum_number = value }.not_to raise_error + # end + end + end + + describe 'test attribute "outer_enum"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "outer_enum_integer"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "outer_enum_default_value"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "outer_enum_integer_default_value"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/file_schema_test_class_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/file_schema_test_class_spec.rb new file mode 100644 index 0000000000..c8a0f8800a --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/file_schema_test_class_spec.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::FileSchemaTestClass +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::FileSchemaTestClass do + let(:instance) { Petstore::FileSchemaTestClass.new } + + describe 'test an instance of FileSchemaTestClass' do + it 'should create an instance of FileSchemaTestClass' do + expect(instance).to be_instance_of(Petstore::FileSchemaTestClass) + end + end + describe 'test attribute "file"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "files"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/file_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/file_spec.rb new file mode 100644 index 0000000000..688c38eb44 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/file_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::File +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::File do + let(:instance) { Petstore::File.new } + + describe 'test an instance of File' do + it 'should create an instance of File' do + expect(instance).to be_instance_of(Petstore::File) + end + end + describe 'test attribute "source_uri"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/foo_get_default_response_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/foo_get_default_response_spec.rb new file mode 100644 index 0000000000..b5b0355778 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/foo_get_default_response_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::FooGetDefaultResponse +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::FooGetDefaultResponse do + let(:instance) { Petstore::FooGetDefaultResponse.new } + + describe 'test an instance of FooGetDefaultResponse' do + it 'should create an instance of FooGetDefaultResponse' do + expect(instance).to be_instance_of(Petstore::FooGetDefaultResponse) + end + end + describe 'test attribute "string"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/foo_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/foo_spec.rb new file mode 100644 index 0000000000..c2b4a79654 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/foo_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Foo +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Foo do + let(:instance) { Petstore::Foo.new } + + describe 'test an instance of Foo' do + it 'should create an instance of Foo' do + expect(instance).to be_instance_of(Petstore::Foo) + end + end + describe 'test attribute "bar"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/format_test_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/format_test_spec.rb new file mode 100644 index 0000000000..cebdbafff3 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/format_test_spec.rb @@ -0,0 +1,124 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::FormatTest +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::FormatTest do + let(:instance) { Petstore::FormatTest.new } + + describe 'test an instance of FormatTest' do + it 'should create an instance of FormatTest' do + expect(instance).to be_instance_of(Petstore::FormatTest) + end + end + describe 'test attribute "integer"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "int32"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "int64"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "number"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "float"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "double"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "decimal"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "string"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "byte"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "binary"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "date"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "date_time"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "uuid"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "password"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "pattern_with_digits"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "pattern_with_digits_and_delimiter"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/has_only_read_only_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/has_only_read_only_spec.rb new file mode 100644 index 0000000000..eb5e2feb64 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/has_only_read_only_spec.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::HasOnlyReadOnly +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::HasOnlyReadOnly do + let(:instance) { Petstore::HasOnlyReadOnly.new } + + describe 'test an instance of HasOnlyReadOnly' do + it 'should create an instance of HasOnlyReadOnly' do + expect(instance).to be_instance_of(Petstore::HasOnlyReadOnly) + end + end + describe 'test attribute "bar"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "foo"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/health_check_result_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/health_check_result_spec.rb new file mode 100644 index 0000000000..7b8436db22 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/health_check_result_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::HealthCheckResult +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::HealthCheckResult do + let(:instance) { Petstore::HealthCheckResult.new } + + describe 'test an instance of HealthCheckResult' do + it 'should create an instance of HealthCheckResult' do + expect(instance).to be_instance_of(Petstore::HealthCheckResult) + end + end + describe 'test attribute "nullable_message"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/list_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/list_spec.rb new file mode 100644 index 0000000000..3571c832e2 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/list_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::List +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::List do + let(:instance) { Petstore::List.new } + + describe 'test an instance of List' do + it 'should create an instance of List' do + expect(instance).to be_instance_of(Petstore::List) + end + end + describe 'test attribute "_123_list"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/map_test_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/map_test_spec.rb new file mode 100644 index 0000000000..e4b2bcc242 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/map_test_spec.rb @@ -0,0 +1,56 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::MapTest +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::MapTest do + let(:instance) { Petstore::MapTest.new } + + describe 'test an instance of MapTest' do + it 'should create an instance of MapTest' do + expect(instance).to be_instance_of(Petstore::MapTest) + end + end + describe 'test attribute "map_map_of_string"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "map_of_enum_string"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Hash', ["UPPER", "lower"]) + # validator.allowable_values.each do |value| + # expect { instance.map_of_enum_string = value }.not_to raise_error + # end + end + end + + describe 'test attribute "direct_map"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "indirect_map"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/mixed_properties_and_additional_properties_class_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/mixed_properties_and_additional_properties_class_spec.rb new file mode 100644 index 0000000000..2bf4ef5f9d --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/mixed_properties_and_additional_properties_class_spec.rb @@ -0,0 +1,46 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::MixedPropertiesAndAdditionalPropertiesClass +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::MixedPropertiesAndAdditionalPropertiesClass do + let(:instance) { Petstore::MixedPropertiesAndAdditionalPropertiesClass.new } + + describe 'test an instance of MixedPropertiesAndAdditionalPropertiesClass' do + it 'should create an instance of MixedPropertiesAndAdditionalPropertiesClass' do + expect(instance).to be_instance_of(Petstore::MixedPropertiesAndAdditionalPropertiesClass) + end + end + describe 'test attribute "uuid"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "date_time"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "map"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/model200_response_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/model200_response_spec.rb new file mode 100644 index 0000000000..7c9a78a286 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/model200_response_spec.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Model200Response +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Model200Response do + let(:instance) { Petstore::Model200Response.new } + + describe 'test an instance of Model200Response' do + it 'should create an instance of Model200Response' do + expect(instance).to be_instance_of(Petstore::Model200Response) + end + end + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "_class"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/model_return_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/model_return_spec.rb new file mode 100644 index 0000000000..7cd06ed692 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/model_return_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ModelReturn +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::ModelReturn do + let(:instance) { Petstore::ModelReturn.new } + + describe 'test an instance of ModelReturn' do + it 'should create an instance of ModelReturn' do + expect(instance).to be_instance_of(Petstore::ModelReturn) + end + end + describe 'test attribute "_return"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/name_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/name_spec.rb new file mode 100644 index 0000000000..946443e979 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/name_spec.rb @@ -0,0 +1,52 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Name +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Name do + let(:instance) { Petstore::Name.new } + + describe 'test an instance of Name' do + it 'should create an instance of Name' do + expect(instance).to be_instance_of(Petstore::Name) + end + end + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "snake_case"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "property"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "_123_number"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/nullable_class_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/nullable_class_spec.rb new file mode 100644 index 0000000000..8c0d004a66 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/nullable_class_spec.rb @@ -0,0 +1,100 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::NullableClass +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::NullableClass do + let(:instance) { Petstore::NullableClass.new } + + describe 'test an instance of NullableClass' do + it 'should create an instance of NullableClass' do + expect(instance).to be_instance_of(Petstore::NullableClass) + end + end + describe 'test attribute "integer_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "number_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "boolean_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "string_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "date_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "datetime_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "array_nullable_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "array_and_items_nullable_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "array_items_nullable"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "object_nullable_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "object_and_items_nullable_prop"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "object_items_nullable"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/number_only_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/number_only_spec.rb new file mode 100644 index 0000000000..f4354dd575 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/number_only_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::NumberOnly +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::NumberOnly do + let(:instance) { Petstore::NumberOnly.new } + + describe 'test an instance of NumberOnly' do + it 'should create an instance of NumberOnly' do + expect(instance).to be_instance_of(Petstore::NumberOnly) + end + end + describe 'test attribute "just_number"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/object_with_deprecated_fields_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/object_with_deprecated_fields_spec.rb new file mode 100644 index 0000000000..ffd1a0ae4c --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/object_with_deprecated_fields_spec.rb @@ -0,0 +1,52 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ObjectWithDeprecatedFields +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::ObjectWithDeprecatedFields do + let(:instance) { Petstore::ObjectWithDeprecatedFields.new } + + describe 'test an instance of ObjectWithDeprecatedFields' do + it 'should create an instance of ObjectWithDeprecatedFields' do + expect(instance).to be_instance_of(Petstore::ObjectWithDeprecatedFields) + end + end + describe 'test attribute "uuid"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "deprecated_ref"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "bars"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/order_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/order_spec.rb new file mode 100644 index 0000000000..99084704e4 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/order_spec.rb @@ -0,0 +1,68 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Order +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Order do + let(:instance) { Petstore::Order.new } + + describe 'test an instance of Order' do + it 'should create an instance of Order' do + expect(instance).to be_instance_of(Petstore::Order) + end + end + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "pet_id"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "quantity"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "ship_date"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "status"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["placed", "approved", "delivered"]) + # validator.allowable_values.each do |value| + # expect { instance.status = value }.not_to raise_error + # end + end + end + + describe 'test attribute "complete"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/outer_composite_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/outer_composite_spec.rb new file mode 100644 index 0000000000..766ca57e63 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/outer_composite_spec.rb @@ -0,0 +1,46 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::OuterComposite +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::OuterComposite do + let(:instance) { Petstore::OuterComposite.new } + + describe 'test an instance of OuterComposite' do + it 'should create an instance of OuterComposite' do + expect(instance).to be_instance_of(Petstore::OuterComposite) + end + end + describe 'test attribute "my_number"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "my_string"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "my_boolean"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/outer_enum_default_value_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/outer_enum_default_value_spec.rb new file mode 100644 index 0000000000..4b48a9f6a6 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/outer_enum_default_value_spec.rb @@ -0,0 +1,28 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::OuterEnumDefaultValue +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::OuterEnumDefaultValue do + let(:instance) { Petstore::OuterEnumDefaultValue.new } + + describe 'test an instance of OuterEnumDefaultValue' do + it 'should create an instance of OuterEnumDefaultValue' do + expect(instance).to be_instance_of(Petstore::OuterEnumDefaultValue) + end + end +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/outer_enum_integer_default_value_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/outer_enum_integer_default_value_spec.rb new file mode 100644 index 0000000000..1ae3778145 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/outer_enum_integer_default_value_spec.rb @@ -0,0 +1,28 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::OuterEnumIntegerDefaultValue +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::OuterEnumIntegerDefaultValue do + let(:instance) { Petstore::OuterEnumIntegerDefaultValue.new } + + describe 'test an instance of OuterEnumIntegerDefaultValue' do + it 'should create an instance of OuterEnumIntegerDefaultValue' do + expect(instance).to be_instance_of(Petstore::OuterEnumIntegerDefaultValue) + end + end +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/outer_enum_integer_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/outer_enum_integer_spec.rb new file mode 100644 index 0000000000..11c0c903ce --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/outer_enum_integer_spec.rb @@ -0,0 +1,28 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::OuterEnumInteger +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::OuterEnumInteger do + let(:instance) { Petstore::OuterEnumInteger.new } + + describe 'test an instance of OuterEnumInteger' do + it 'should create an instance of OuterEnumInteger' do + expect(instance).to be_instance_of(Petstore::OuterEnumInteger) + end + end +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/outer_enum_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/outer_enum_spec.rb new file mode 100644 index 0000000000..ef02b0f406 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/outer_enum_spec.rb @@ -0,0 +1,28 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::OuterEnum +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::OuterEnum do + let(:instance) { Petstore::OuterEnum.new } + + describe 'test an instance of OuterEnum' do + it 'should create an instance of OuterEnum' do + expect(instance).to be_instance_of(Petstore::OuterEnum) + end + end +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/outer_object_with_enum_property_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/outer_object_with_enum_property_spec.rb new file mode 100644 index 0000000000..0f88c5a547 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/outer_object_with_enum_property_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::OuterObjectWithEnumProperty +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::OuterObjectWithEnumProperty do + let(:instance) { Petstore::OuterObjectWithEnumProperty.new } + + describe 'test an instance of OuterObjectWithEnumProperty' do + it 'should create an instance of OuterObjectWithEnumProperty' do + expect(instance).to be_instance_of(Petstore::OuterObjectWithEnumProperty) + end + end + describe 'test attribute "value"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/pet_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/pet_spec.rb new file mode 100644 index 0000000000..fb948ec3ec --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/pet_spec.rb @@ -0,0 +1,68 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Pet +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Pet do + let(:instance) { Petstore::Pet.new } + + describe 'test an instance of Pet' do + it 'should create an instance of Pet' do + expect(instance).to be_instance_of(Petstore::Pet) + end + end + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "category"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "photo_urls"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "tags"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "status"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + # validator.allowable_values.each do |value| + # expect { instance.status = value }.not_to raise_error + # end + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/read_only_first_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/read_only_first_spec.rb new file mode 100644 index 0000000000..657a2b695a --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/read_only_first_spec.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ReadOnlyFirst +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::ReadOnlyFirst do + let(:instance) { Petstore::ReadOnlyFirst.new } + + describe 'test an instance of ReadOnlyFirst' do + it 'should create an instance of ReadOnlyFirst' do + expect(instance).to be_instance_of(Petstore::ReadOnlyFirst) + end + end + describe 'test attribute "bar"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "baz"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/single_ref_type_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/single_ref_type_spec.rb new file mode 100644 index 0000000000..7cf871f27e --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/single_ref_type_spec.rb @@ -0,0 +1,28 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::SingleRefType +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::SingleRefType do + let(:instance) { Petstore::SingleRefType.new } + + describe 'test an instance of SingleRefType' do + it 'should create an instance of SingleRefType' do + expect(instance).to be_instance_of(Petstore::SingleRefType) + end + end +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/special_model_name_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/special_model_name_spec.rb new file mode 100644 index 0000000000..38542aef0e --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/special_model_name_spec.rb @@ -0,0 +1,34 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::SpecialModelName +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::SpecialModelName do + let(:instance) { Petstore::SpecialModelName.new } + + describe 'test an instance of SpecialModelName' do + it 'should create an instance of SpecialModelName' do + expect(instance).to be_instance_of(Petstore::SpecialModelName) + end + end + describe 'test attribute "special_property_name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/tag_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/tag_spec.rb new file mode 100644 index 0000000000..c73c1fbab1 --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/tag_spec.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Tag +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Tag do + let(:instance) { Petstore::Tag.new } + + describe 'test an instance of Tag' do + it 'should create an instance of Tag' do + expect(instance).to be_instance_of(Petstore::Tag) + end + end + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/models/user_spec.rb b/samples/client/petstore/ruby-autoload/spec/models/user_spec.rb new file mode 100644 index 0000000000..8eb9cd582a --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/models/user_spec.rb @@ -0,0 +1,76 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 6.1.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::User +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::User do + let(:instance) { Petstore::User.new } + + describe 'test an instance of User' do + it 'should create an instance of User' do + expect(instance).to be_instance_of(Petstore::User) + end + end + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "username"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "first_name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "last_name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "email"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "password"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "phone"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "user_status"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end diff --git a/samples/client/petstore/ruby-autoload/spec/spec_helper.rb b/samples/client/petstore/ruby-autoload/spec/spec_helper.rb new file mode 100644 index 0000000000..c070b6f2ac --- /dev/null +++ b/samples/client/petstore/ruby-autoload/spec/spec_helper.rb @@ -0,0 +1,111 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.0.0-SNAPSHOT + +=end + +# load the gem +require 'petstore' + +# The following was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# The `.rspec` file also contains a few flags that are not defaults but that +# users commonly want. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # These two settings work together to allow you to limit a spec run + # to individual examples or groups you care about by tagging them with + # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # get run. + config.filter_run :focus + config.run_all_when_everything_filtered = true + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = 'doc' + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb index eb187b6932..99b13cdeec 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb @@ -112,7 +112,6 @@ module Petstore # Overload default options only if provided request.options.params_encoder = config.params_encoder if config.params_encoder request.options.timeout = config.timeout if config.timeout - request.options.verbose = config.debugging if config.debugging request.url url request.params = query_params @@ -136,7 +135,7 @@ module Petstore case value when ::File, ::Tempfile # TODO hardcode to application/octet-stream, need better way to detect content type - data[key] = Faraday::UploadIO.new(value.path, 'application/octet-stream', value.path) + data[key] = Faraday::FilePart.new(value.path, 'application/octet-stream', value.path) when ::Array, nil # let Faraday handle Array and nil parameters data[key] = value diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb index 13e4a0693a..b213974658 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb @@ -153,9 +153,7 @@ module Petstore @ssl_ca_file = nil @ssl_client_cert = nil @ssl_client_key = nil - @middlewares = [] - @request_middlewares = [] - @response_middlewares = [] + @middlewares = Hash.new { |h, k| h[k] = [] } @timeout = 60 # return data as binary instead of file @return_binary_data = false @@ -317,6 +315,29 @@ module Petstore { url: "http://path-server-test.petstore.local/v2", description: "No description provided", + }, + { + url: "http://{server}.swagger.io:{port}/v2", + description: "test server with variables", + variables: { + server: { + description: "target server", + default_value: "petstore", + enum_values: [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + port: { + description: "No description provided", + default_value: "80", + enum_values: [ + "80", + "8080" + ] + } + } } ], "PetApi.update_pet": [ @@ -327,6 +348,29 @@ module Petstore { url: "http://path-server-test.petstore.local/v2", description: "No description provided", + }, + { + url: "http://{server}.swagger.io:{port}/v2", + description: "test server with variables", + variables: { + server: { + description: "target server", + default_value: "petstore", + enum_values: [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + port: { + description: "No description provided", + default_value: "80", + enum_values: [ + "80", + "8080" + ] + } + } } ], } @@ -368,31 +412,56 @@ module Petstore # Adds middleware to the stack def use(*middleware) - @middlewares << middleware + set_faraday_middleware(:use, *middleware) end # Adds request middleware to the stack def request(*middleware) - @request_middlewares << middleware + set_faraday_middleware(:request, *middleware) end # Adds response middleware to the stack def response(*middleware) - @response_middlewares << middleware + set_faraday_middleware(:response, *middleware) end + # Adds Faraday middleware setting information to the stack + # + # @example Use the `set_faraday_middleware` method to set middleware information + # config.set_faraday_middleware(:request, :retry, max: 3, methods: [:get, :post], retry_statuses: [503]) + # config.set_faraday_middleware(:response, :logger, nil, { bodies: true, log_level: :debug }) + # config.set_faraday_middleware(:use, Faraday::HttpCache, store: Rails.cache, shared_cache: false) + # config.set_faraday_middleware(:insert, 0, FaradayMiddleware::FollowRedirects, { standards_compliant: true, limit: 1 }) + # config.set_faraday_middleware(:swap, 0, Faraday::Response::Logger) + # config.set_faraday_middleware(:delete, Faraday::Multipart::Middleware) + # + # @see https://github.com/lostisland/faraday/blob/v2.3.0/lib/faraday/rack_builder.rb#L92-L143 + def set_faraday_middleware(operation, key, *args, &block) + unless [:request, :response, :use, :insert, :insert_before, :insert_after, :swap, :delete].include?(operation) + fail ArgumentError, "Invalid faraday middleware operation #{operation}. Must be" \ + " :request, :response, :use, :insert, :insert_before, :insert_after, :swap or :delete." + end + + @middlewares[operation] << [key, args, block] + end + ruby2_keywords(:set_faraday_middleware) if respond_to?(:ruby2_keywords, true) + # Set up middleware on the connection def configure_middleware(connection) - @middlewares.each do |middleware| - connection.use(*middleware) + return if @middlewares.empty? + + [:request, :response, :use, :insert, :insert_before, :insert_after, :swap].each do |operation| + next unless @middlewares.key?(operation) + + @middlewares[operation].each do |key, args, block| + connection.builder.send(operation, key, *args, &block) + end end - @request_middlewares.each do |middleware| - connection.request(*middleware) - end - - @response_middlewares.each do |middleware| - connection.response(*middleware) + if @middlewares.key?(:delete) + @middlewares[:delete].each do |key, _args, _block| + connection.builder.delete(key) + end end end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/all_of_with_single_ref.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/all_of_with_single_ref.rb index 563ba8781f..c7e611e2f5 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/all_of_with_single_ref.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/all_of_with_single_ref.rb @@ -43,7 +43,6 @@ module Petstore # List of attributes with nullable: true def self.openapi_nullable Set.new([ - :'single_ref_type' ]) end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb index 29e705d3e1..b2cd88d076 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb @@ -19,6 +19,10 @@ module Petstore EFG = "-efg".freeze XYZ = "(xyz)".freeze + def self.all_vars + @all_vars ||= [ABC, EFG, XYZ].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = EnumClass.constants.select { |c| EnumClass::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #EnumClass" if constantValues.empty? - value + return value if EnumClass.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #EnumClass" end end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb index fc0ec6d49f..cc0b78284c 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb @@ -19,6 +19,10 @@ module Petstore APPROVED = "approved".freeze DELIVERED = "delivered".freeze + def self.all_vars + @all_vars ||= [PLACED, APPROVED, DELIVERED].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = OuterEnum.constants.select { |c| OuterEnum::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #OuterEnum" if constantValues.empty? - value + return value if OuterEnum.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnum" end end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb index 2853bad341..d4353f2972 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb @@ -19,6 +19,10 @@ module Petstore APPROVED = "approved".freeze DELIVERED = "delivered".freeze + def self.all_vars + @all_vars ||= [PLACED, APPROVED, DELIVERED].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = OuterEnumDefaultValue.constants.select { |c| OuterEnumDefaultValue::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #OuterEnumDefaultValue" if constantValues.empty? - value + return value if OuterEnumDefaultValue.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnumDefaultValue" end end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb index 97f8330bb8..f5e5de7107 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb @@ -19,6 +19,10 @@ module Petstore N1 = 1.freeze N2 = 2.freeze + def self.all_vars + @all_vars ||= [N0, N1, N2].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = OuterEnumInteger.constants.select { |c| OuterEnumInteger::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #OuterEnumInteger" if constantValues.empty? - value + return value if OuterEnumInteger.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnumInteger" end end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb index aa76b0c4eb..388b00014e 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb @@ -19,6 +19,10 @@ module Petstore N1 = 1.freeze N2 = 2.freeze + def self.all_vars + @all_vars ||= [N0, N1, N2].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = OuterEnumIntegerDefaultValue.constants.select { |c| OuterEnumIntegerDefaultValue::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #OuterEnumIntegerDefaultValue" if constantValues.empty? - value + return value if OuterEnumIntegerDefaultValue.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnumIntegerDefaultValue" end end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/single_ref_type.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/single_ref_type.rb index 86117408c8..746e50cbec 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/single_ref_type.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/single_ref_type.rb @@ -18,6 +18,10 @@ module Petstore ADMIN = "admin".freeze USER = "user".freeze + def self.all_vars + @all_vars ||= [ADMIN, USER].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -29,9 +33,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = SingleRefType.constants.select { |c| SingleRefType::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #SingleRefType" if constantValues.empty? - value + return value if SingleRefType.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #SingleRefType" end end end diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index f31dffc1ab..144fb92cb9 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -312,6 +312,29 @@ module Petstore { url: "http://path-server-test.petstore.local/v2", description: "No description provided", + }, + { + url: "http://{server}.swagger.io:{port}/v2", + description: "test server with variables", + variables: { + server: { + description: "target server", + default_value: "petstore", + enum_values: [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + port: { + description: "No description provided", + default_value: "80", + enum_values: [ + "80", + "8080" + ] + } + } } ], "PetApi.update_pet": [ @@ -322,6 +345,29 @@ module Petstore { url: "http://path-server-test.petstore.local/v2", description: "No description provided", + }, + { + url: "http://{server}.swagger.io:{port}/v2", + description: "test server with variables", + variables: { + server: { + description: "target server", + default_value: "petstore", + enum_values: [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + port: { + description: "No description provided", + default_value: "80", + enum_values: [ + "80", + "8080" + ] + } + } } ], } diff --git a/samples/client/petstore/ruby/lib/petstore/models/all_of_with_single_ref.rb b/samples/client/petstore/ruby/lib/petstore/models/all_of_with_single_ref.rb index 563ba8781f..c7e611e2f5 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/all_of_with_single_ref.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/all_of_with_single_ref.rb @@ -43,7 +43,6 @@ module Petstore # List of attributes with nullable: true def self.openapi_nullable Set.new([ - :'single_ref_type' ]) end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb index 29e705d3e1..b2cd88d076 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb @@ -19,6 +19,10 @@ module Petstore EFG = "-efg".freeze XYZ = "(xyz)".freeze + def self.all_vars + @all_vars ||= [ABC, EFG, XYZ].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = EnumClass.constants.select { |c| EnumClass::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #EnumClass" if constantValues.empty? - value + return value if EnumClass.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #EnumClass" end end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb index fc0ec6d49f..cc0b78284c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb @@ -19,6 +19,10 @@ module Petstore APPROVED = "approved".freeze DELIVERED = "delivered".freeze + def self.all_vars + @all_vars ||= [PLACED, APPROVED, DELIVERED].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = OuterEnum.constants.select { |c| OuterEnum::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #OuterEnum" if constantValues.empty? - value + return value if OuterEnum.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnum" end end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb index 2853bad341..d4353f2972 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb @@ -19,6 +19,10 @@ module Petstore APPROVED = "approved".freeze DELIVERED = "delivered".freeze + def self.all_vars + @all_vars ||= [PLACED, APPROVED, DELIVERED].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = OuterEnumDefaultValue.constants.select { |c| OuterEnumDefaultValue::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #OuterEnumDefaultValue" if constantValues.empty? - value + return value if OuterEnumDefaultValue.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnumDefaultValue" end end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb index 97f8330bb8..f5e5de7107 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb @@ -19,6 +19,10 @@ module Petstore N1 = 1.freeze N2 = 2.freeze + def self.all_vars + @all_vars ||= [N0, N1, N2].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = OuterEnumInteger.constants.select { |c| OuterEnumInteger::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #OuterEnumInteger" if constantValues.empty? - value + return value if OuterEnumInteger.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnumInteger" end end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb index aa76b0c4eb..388b00014e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb @@ -19,6 +19,10 @@ module Petstore N1 = 1.freeze N2 = 2.freeze + def self.all_vars + @all_vars ||= [N0, N1, N2].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -30,9 +34,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = OuterEnumIntegerDefaultValue.constants.select { |c| OuterEnumIntegerDefaultValue::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #OuterEnumIntegerDefaultValue" if constantValues.empty? - value + return value if OuterEnumIntegerDefaultValue.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #OuterEnumIntegerDefaultValue" end end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/single_ref_type.rb b/samples/client/petstore/ruby/lib/petstore/models/single_ref_type.rb index 86117408c8..746e50cbec 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/single_ref_type.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/single_ref_type.rb @@ -18,6 +18,10 @@ module Petstore ADMIN = "admin".freeze USER = "user".freeze + def self.all_vars + @all_vars ||= [ADMIN, USER].freeze + end + # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -29,9 +33,8 @@ module Petstore # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = SingleRefType.constants.select { |c| SingleRefType::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #SingleRefType" if constantValues.empty? - value + return value if SingleRefType.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #SingleRefType" end end end diff --git a/samples/client/petstore/rust/.openapi-generator/VERSION b/samples/client/petstore/rust/.openapi-generator/VERSION deleted file mode 100644 index 479c313e87..0000000000 --- a/samples/client/petstore/rust/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -4.0.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/docs/InlineObject.md b/samples/client/petstore/rust/docs/InlineObject.md deleted file mode 100644 index bfe33a4efb..0000000000 --- a/samples/client/petstore/rust/docs/InlineObject.md +++ /dev/null @@ -1,12 +0,0 @@ -# InlineObject - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | Updated name of the pet | [optional] -**status** | **String** | Updated status of the pet | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/client/petstore/rust/docs/InlineObject1.md b/samples/client/petstore/rust/docs/InlineObject1.md deleted file mode 100644 index 930d10cdcb..0000000000 --- a/samples/client/petstore/rust/docs/InlineObject1.md +++ /dev/null @@ -1,12 +0,0 @@ -# InlineObject1 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additional_metadata** | **String** | Additional data to pass to server | [optional] -**file** | [***std::path::PathBuf**](std::path::PathBuf.md) | file to upload | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/.gitignore b/samples/client/petstore/rust/hyper/fileResponseTest/.gitignore deleted file mode 100644 index 6aa106405a..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/target/ -**/*.rs.bk -Cargo.lock diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/.openapi-generator/FILES b/samples/client/petstore/rust/hyper/fileResponseTest/.openapi-generator/FILES deleted file mode 100644 index d85f759b59..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/.openapi-generator/FILES +++ /dev/null @@ -1,13 +0,0 @@ -.gitignore -.travis.yml -Cargo.toml -README.md -docs/DefaultApi.md -git_push.sh -src/apis/client.rs -src/apis/configuration.rs -src/apis/default_api.rs -src/apis/mod.rs -src/apis/request.rs -src/lib.rs -src/models/mod.rs diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/.openapi-generator/VERSION b/samples/client/petstore/rust/hyper/fileResponseTest/.openapi-generator/VERSION deleted file mode 100644 index d99e7162d0..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/.travis.yml b/samples/client/petstore/rust/hyper/fileResponseTest/.travis.yml deleted file mode 100644 index 22761ba7ee..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: rust diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/Cargo.toml b/samples/client/petstore/rust/hyper/fileResponseTest/Cargo.toml deleted file mode 100644 index 808f425995..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "fileResponseTest-hyper" -version = "1.0.0" -authors = ["OpenAPI Generator team and contributors"] -edition = "2018" - -[dependencies] -serde = "^1.0" -serde_derive = "^1.0" -serde_json = "^1.0" -url = "1.5" -hyper = "~0.11" -serde_yaml = "0.7" -base64 = "~0.7.0" -futures = "0.1.23" - -[dev-dependencies] -tokio-core = "*" diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/README.md b/samples/client/petstore/rust/hyper/fileResponseTest/README.md deleted file mode 100644 index 1cb8e0b83f..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# Rust API client for fileResponseTest-hyper - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -## Overview - -This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. - -- API version: 1.0.0 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.RustClientCodegen - -## Installation - -Put the package under your project folder and add the following to `Cargo.toml` under `[dependencies]`: - -``` - openapi = { path = "./generated" } -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://localhost/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*DefaultApi* | [**fileresponsetest**](docs/DefaultApi.md#fileresponsetest) | **Get** /tests/fileResponse | - - -## Documentation For Models - - - -To get access to the crate's generated documentation, use: - -``` -cargo doc --open -``` - -## Author - - - diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/docs/DefaultApi.md b/samples/client/petstore/rust/hyper/fileResponseTest/docs/DefaultApi.md deleted file mode 100644 index 6e8157cf0e..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/docs/DefaultApi.md +++ /dev/null @@ -1,34 +0,0 @@ -# \DefaultApi - -All URIs are relative to *http://localhost/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**fileresponsetest**](DefaultApi.md#fileresponsetest) | **Get** /tests/fileResponse | - - - -## fileresponsetest - -> std::path::PathBuf fileresponsetest() - - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -[**std::path::PathBuf**](std::path::PathBuf.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/octet-stream - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/client.rs b/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/client.rs deleted file mode 100644 index 4976ba81c6..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/client.rs +++ /dev/null @@ -1,23 +0,0 @@ -use std::rc::Rc; - -use hyper; -use super::configuration::Configuration; - -pub struct APIClient { - default_api: Box, -} - -impl APIClient { - pub fn new(configuration: Configuration) -> APIClient { - let rc = Rc::new(configuration); - - APIClient { - default_api: Box::new(crate::apis::DefaultApiClient::new(rc.clone())), - } - } - - pub fn default_api(&self) -> &dyn crate::apis::DefaultApi{ - self.default_api.as_ref() - } - -} diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/configuration.rs b/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/configuration.rs deleted file mode 100644 index 6a3d69dddd..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/configuration.rs +++ /dev/null @@ -1,41 +0,0 @@ -/* - * File Response Test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -use hyper; - -pub struct Configuration { - pub base_path: String, - pub user_agent: Option, - pub client: hyper::client::Client, - pub basic_auth: Option, - pub oauth_access_token: Option, - pub api_key: Option, - // TODO: take an oauth2 token source, similar to the go one -} - -pub type BasicAuth = (String, Option); - -pub struct ApiKey { - pub prefix: Option, - pub key: String, -} - -impl Configuration { - pub fn new(client: hyper::client::Client) -> Configuration { - Configuration { - base_path: "http://localhost/v2".to_owned(), - user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), - client: client, - basic_auth: None, - oauth_access_token: None, - api_key: None, - } - } -} diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/default_api.rs b/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/default_api.rs deleted file mode 100644 index fb52b3cc52..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/default_api.rs +++ /dev/null @@ -1,47 +0,0 @@ -/* - * File Response Test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -use std::rc::Rc; -use std::borrow::Borrow; -#[allow(unused_imports)] -use std::option::Option; - -use hyper; -use serde_json; -use futures::Future; - -use super::{Error, configuration}; -use super::request as __internal_request; - -pub struct DefaultApiClient { - configuration: Rc>, -} - -impl DefaultApiClient { - pub fn new(configuration: Rc>) -> DefaultApiClient { - DefaultApiClient { - configuration, - } - } -} - -pub trait DefaultApi { - fn fileresponsetest(&self, ) -> Box>>; -} - -implDefaultApi for DefaultApiClient { - fn fileresponsetest(&self, ) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/tests/fileResponse".to_string()) - ; - - req.execute(self.configuration.borrow()) - } - -} diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/mod.rs b/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/mod.rs deleted file mode 100644 index cb13d23efc..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/mod.rs +++ /dev/null @@ -1,58 +0,0 @@ -use hyper; -use serde; -use serde_json; - -#[derive(Debug)] -pub enum Error { - UriError(hyper::error::UriError), - Hyper(hyper::Error), - Serde(serde_json::Error), - ApiError(ApiError), -} - -#[derive(Debug)] -pub struct ApiError { - pub code: hyper::StatusCode, - pub content: Option, -} - -impl<'de, T> From<(hyper::StatusCode, &'de [u8])> for Error - where T: serde::Deserialize<'de> { - fn from(e: (hyper::StatusCode, &'de [u8])) -> Self { - if e.1.len() == 0 { - return Error::ApiError(ApiError{ - code: e.0, - content: None, - }); - } - match serde_json::from_slice::(e.1) { - Ok(t) => Error::ApiError(ApiError{ - code: e.0, - content: Some(t), - }), - Err(e) => { - Error::from(e) - } - } - } -} - -impl From for Error { - fn from(e: hyper::Error) -> Self { - return Error::Hyper(e) - } -} - -impl From for Error { - fn from(e: serde_json::Error) -> Self { - return Error::Serde(e) - } -} - -mod request; - -mod default_api; -pub use self::default_api::{ DefaultApi, DefaultApiClient }; - -pub mod configuration; -pub mod client; diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/request.rs b/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/request.rs deleted file mode 100644 index f97b527719..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/src/apis/request.rs +++ /dev/null @@ -1,239 +0,0 @@ -use std::borrow::Cow; -use std::collections::HashMap; - -use super::{configuration, Error}; -use futures; -use futures::{Future, Stream}; -use hyper; -use hyper::header::UserAgent; -use serde; -use serde_json; - -pub(crate) struct ApiKey { - pub in_header: bool, - pub in_query: bool, - pub param_name: String, -} - -impl ApiKey { - fn key(&self, prefix: &Option, key: &str) -> String { - match prefix { - None => key.to_owned(), - Some(ref prefix) => format!("{} {}", prefix, key), - } - } -} - -#[allow(dead_code)] -pub(crate) enum Auth { - None, - ApiKey(ApiKey), - Basic, - Oauth, -} - -pub(crate) struct Request { - auth: Auth, - method: hyper::Method, - path: String, - query_params: HashMap, - no_return_type: bool, - path_params: HashMap, - form_params: HashMap, - header_params: HashMap, - // TODO: multiple body params are possible technically, but not supported here. - serialized_body: Option, -} - -impl Request { - pub fn new(method: hyper::Method, path: String) -> Self { - Request { - auth: Auth::None, - method: method, - path: path, - query_params: HashMap::new(), - path_params: HashMap::new(), - form_params: HashMap::new(), - header_params: HashMap::new(), - serialized_body: None, - no_return_type: false, - } - } - - pub fn with_body_param(mut self, param: T) -> Self { - self.serialized_body = Some(serde_json::to_string(¶m).unwrap()); - self - } - - pub fn with_header_param(mut self, basename: String, param: String) -> Self { - self.header_params.insert(basename, param); - self - } - - pub fn with_query_param(mut self, basename: String, param: String) -> Self { - self.query_params.insert(basename, param); - self - } - - pub fn with_path_param(mut self, basename: String, param: String) -> Self { - self.path_params.insert(basename, param); - self - } - - pub fn with_form_param(mut self, basename: String, param: String) -> Self { - self.form_params.insert(basename, param); - self - } - - pub fn returns_nothing(mut self) -> Self { - self.no_return_type = true; - self - } - - pub fn with_auth(mut self, auth: Auth) -> Self { - self.auth = auth; - self - } - - pub fn execute<'a, C, U>( - self, - conf: &configuration::Configuration, - ) -> Box> + 'a> - where - C: hyper::client::Connect, - U: Sized + 'a, - for<'de> U: serde::Deserialize<'de>, - { - let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned()); - // raw_headers is for headers we don't know the proper type of (e.g. custom api key - // headers); headers is for ones we do know the type of. - let mut raw_headers = HashMap::new(); - let mut headers: hyper::header::Headers = hyper::header::Headers::new(); - - let mut path = self.path; - for (k, v) in self.path_params { - // replace {id} with the value of the id path param - path = path.replace(&format!("{{{}}}", k), &v); - } - - for (k, v) in self.header_params { - raw_headers.insert(k, v); - } - - for (key, val) in self.query_params { - query_string.append_pair(&key, &val); - } - - match self.auth { - Auth::ApiKey(apikey) => { - if let Some(ref key) = conf.api_key { - let val = apikey.key(&key.prefix, &key.key); - if apikey.in_query { - query_string.append_pair(&apikey.param_name, &val); - } - if apikey.in_header { - raw_headers.insert(apikey.param_name, val); - } - } - } - Auth::Basic => { - if let Some(ref auth_conf) = conf.basic_auth { - let auth = hyper::header::Authorization(hyper::header::Basic { - username: auth_conf.0.to_owned(), - password: auth_conf.1.to_owned(), - }); - headers.set(auth); - } - } - Auth::Oauth => { - if let Some(ref token) = conf.oauth_access_token { - let auth = hyper::header::Authorization(hyper::header::Bearer { - token: token.to_owned(), - }); - headers.set(auth); - } - } - Auth::None => {} - } - - let mut uri_str = format!("{}{}", conf.base_path, path); - - let query_string_str = query_string.finish(); - if query_string_str != "" { - uri_str += "?"; - uri_str += &query_string_str; - } - let uri: hyper::Uri = match uri_str.parse() { - Err(e) => { - return Box::new(futures::future::err(Error::UriError(e))); - } - Ok(u) => u, - }; - - let mut req = hyper::Request::new(self.method, uri); - { - let req_headers = req.headers_mut(); - if let Some(ref user_agent) = conf.user_agent { - req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone()))); - } - - req_headers.extend(headers.iter()); - - for (key, val) in raw_headers { - req_headers.set_raw(key, val); - } - } - - if self.form_params.len() > 0 { - req.headers_mut().set(hyper::header::ContentType::form_url_encoded()); - let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned()); - for (k, v) in self.form_params { - enc.append_pair(&k, &v); - } - req.set_body(enc.finish()); - } - - if let Some(body) = self.serialized_body { - req.headers_mut().set(hyper::header::ContentType::json()); - req.headers_mut() - .set(hyper::header::ContentLength(body.len() as u64)); - req.set_body(body); - } - - let no_ret_type = self.no_return_type; - let res = conf.client - .request(req) - .map_err(|e| Error::from(e)) - .and_then(|resp| { - let status = resp.status(); - resp.body() - .concat2() - .and_then(move |body| Ok((status, body))) - .map_err(|e| Error::from(e)) - }) - .and_then(|(status, body)| { - if status.is_success() { - Ok(body) - } else { - Err(Error::from((status, &*body))) - } - }); - Box::new( - res - .and_then(move |body| { - let parsed: Result = if no_ret_type { - // This is a hack; if there's no_ret_type, U is (), but serde_json gives an - // error when deserializing "" into (), so deserialize 'null' into it - // instead. - // An alternate option would be to require U: Default, and then return - // U::default() here instead since () implements that, but then we'd - // need to impl default for all models. - serde_json::from_str("null") - } else { - serde_json::from_slice(&body) - }; - parsed.map_err(|e| Error::from(e)) - }) - ) - } -} diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/src/lib.rs b/samples/client/petstore/rust/hyper/fileResponseTest/src/lib.rs deleted file mode 100644 index a76d822525..0000000000 --- a/samples/client/petstore/rust/hyper/fileResponseTest/src/lib.rs +++ /dev/null @@ -1,11 +0,0 @@ -#[macro_use] -extern crate serde_derive; - -extern crate serde; -extern crate serde_json; -extern crate url; -extern crate hyper; -extern crate futures; - -pub mod apis; -pub mod models; diff --git a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/FILES b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/FILES index 5345a60cd9..6ebb4efdd0 100644 --- a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/FILES +++ b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/FILES @@ -2,15 +2,20 @@ .travis.yml Cargo.toml README.md +docs/ActionContainer.md docs/ApiResponse.md +docs/Baz.md docs/Category.md docs/FakeApi.md docs/Order.md docs/Pet.md docs/PetApi.md docs/PropertyTest.md +docs/Return.md docs/StoreApi.md docs/Tag.md +docs/TestingApi.md +docs/TypeTesting.md docs/User.md docs/UserApi.md git_push.sh @@ -21,13 +26,18 @@ src/apis/mod.rs src/apis/pet_api.rs src/apis/request.rs src/apis/store_api.rs +src/apis/testing_api.rs src/apis/user_api.rs src/lib.rs +src/models/action_container.rs src/models/api_response.rs +src/models/baz.rs src/models/category.rs src/models/mod.rs +src/models/model_return.rs src/models/order.rs src/models/pet.rs src/models/property_test.rs src/models/tag.rs +src/models/type_testing.rs src/models/user.rs diff --git a/samples/client/petstore/rust/hyper/petstore/README.md b/samples/client/petstore/rust/hyper/petstore/README.md index 2fe69e24cc..29c034e6f6 100644 --- a/samples/client/petstore/rust/hyper/petstore/README.md +++ b/samples/client/petstore/rust/hyper/petstore/README.md @@ -38,6 +38,8 @@ Class | Method | HTTP request | Description *StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **Get** /store/inventory | Returns pet inventories by status *StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **Get** /store/order/{orderId} | Find purchase order by ID *StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **Post** /store/order | Place an order for a pet +*TestingApi* | [**tests_file_response_get**](docs/TestingApi.md#tests_file_response_get) | **Get** /tests/fileResponse | Returns an image file +*TestingApi* | [**tests_type_testing_get**](docs/TestingApi.md#tests_type_testing_get) | **Get** /tests/typeTesting | Route to test the TypeTesting schema *UserApi* | [**create_user**](docs/UserApi.md#create_user) | **Post** /user | Create user *UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **Post** /user/createWithArray | Creates list of users with given input array *UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **Post** /user/createWithList | Creates list of users with given input array @@ -50,12 +52,16 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [ActionContainer](docs/ActionContainer.md) - [ApiResponse](docs/ApiResponse.md) + - [Baz](docs/Baz.md) - [Category](docs/Category.md) - [Order](docs/Order.md) - [Pet](docs/Pet.md) - [PropertyTest](docs/PropertyTest.md) + - [Return](docs/Return.md) - [Tag](docs/Tag.md) + - [TypeTesting](docs/TypeTesting.md) - [User](docs/User.md) diff --git a/samples/client/petstore/rust/hyper/petstore/docs/ActionContainer.md b/samples/client/petstore/rust/hyper/petstore/docs/ActionContainer.md new file mode 100644 index 0000000000..8490ec5d82 --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/docs/ActionContainer.md @@ -0,0 +1,11 @@ +# ActionContainer + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**action** | [**crate::models::Baz**](Baz.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/hyper/petstore/docs/ApiResponse.md b/samples/client/petstore/rust/hyper/petstore/docs/ApiResponse.md index 97128a87d9..b5125ba685 100644 --- a/samples/client/petstore/rust/hyper/petstore/docs/ApiResponse.md +++ b/samples/client/petstore/rust/hyper/petstore/docs/ApiResponse.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | Option<**i32**> | | [optional] -**_type** | Option<**String**> | | [optional] +**r#type** | Option<**String**> | | [optional] **message** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/rust/hyper/petstore/docs/Baz.md b/samples/client/petstore/rust/hyper/petstore/docs/Baz.md new file mode 100644 index 0000000000..68c84b1b1b --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/docs/Baz.md @@ -0,0 +1,10 @@ +# Baz + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/hyper/petstore/docs/DefaultApi.md b/samples/client/petstore/rust/hyper/petstore/docs/DefaultApi.md new file mode 100644 index 0000000000..54af229525 --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/docs/DefaultApi.md @@ -0,0 +1,60 @@ +# \DefaultApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**tests_file_response_get**](DefaultApi.md#tests_file_response_get) | **Get** /tests/fileResponse | Returns an image file +[**tests_type_testing_get**](DefaultApi.md#tests_type_testing_get) | **Get** /tests/typeTesting | Route to test the TypeTesting schema + + + +## tests_file_response_get + +> std::path::PathBuf tests_file_response_get() +Returns an image file + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**std::path::PathBuf**](std::path::PathBuf.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/jpeg + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## tests_type_testing_get + +> crate::models::TypeTesting tests_type_testing_get() +Route to test the TypeTesting schema + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**crate::models::TypeTesting**](TypeTesting.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/rust/hyper/petstore/docs/Return.md b/samples/client/petstore/rust/hyper/petstore/docs/Return.md new file mode 100644 index 0000000000..04710a019d --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/docs/Return.md @@ -0,0 +1,13 @@ +# Return + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#match** | Option<**i32**> | | [optional] +**r#async** | Option<**bool**> | | [optional] +**param_super** | Option<**bool**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/hyper/petstore/docs/TestingApi.md b/samples/client/petstore/rust/hyper/petstore/docs/TestingApi.md new file mode 100644 index 0000000000..9f72e78530 --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/docs/TestingApi.md @@ -0,0 +1,60 @@ +# \TestingApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**tests_file_response_get**](TestingApi.md#tests_file_response_get) | **Get** /tests/fileResponse | Returns an image file +[**tests_type_testing_get**](TestingApi.md#tests_type_testing_get) | **Get** /tests/typeTesting | Route to test the TypeTesting schema + + + +## tests_file_response_get + +> std::path::PathBuf tests_file_response_get() +Returns an image file + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**std::path::PathBuf**](std::path::PathBuf.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/jpeg + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## tests_type_testing_get + +> crate::models::TypeTesting tests_type_testing_get() +Route to test the TypeTesting schema + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**crate::models::TypeTesting**](TypeTesting.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/rust/hyper/petstore/docs/TypeTesting.md b/samples/client/petstore/rust/hyper/petstore/docs/TypeTesting.md new file mode 100644 index 0000000000..6beca6dbac --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/docs/TypeTesting.md @@ -0,0 +1,17 @@ +# TypeTesting + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**int32** | **i32** | | +**int64** | **i64** | | +**float** | **f32** | | +**double** | **f64** | | +**string** | **String** | | +**boolean** | **bool** | | +**uuid** | [**uuid::Uuid**](uuid::Uuid.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/client.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/client.rs index e209050c59..c38f01cdc5 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/client.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/client.rs @@ -7,6 +7,7 @@ pub struct APIClient { fake_api: Box, pet_api: Box, store_api: Box, + testing_api: Box, user_api: Box, } @@ -19,6 +20,7 @@ impl APIClient { fake_api: Box::new(crate::apis::FakeApiClient::new(rc.clone())), pet_api: Box::new(crate::apis::PetApiClient::new(rc.clone())), store_api: Box::new(crate::apis::StoreApiClient::new(rc.clone())), + testing_api: Box::new(crate::apis::TestingApiClient::new(rc.clone())), user_api: Box::new(crate::apis::UserApiClient::new(rc.clone())), } } @@ -35,6 +37,10 @@ impl APIClient { self.store_api.as_ref() } + pub fn testing_api(&self) -> &dyn crate::apis::TestingApi{ + self.testing_api.as_ref() + } + pub fn user_api(&self) -> &dyn crate::apis::UserApi{ self.user_api.as_ref() } diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/mod.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/mod.rs index e2ccc5d6a3..2abfb5a4e6 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/mod.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/mod.rs @@ -53,6 +53,8 @@ mod pet_api; pub use self::pet_api::{ PetApi, PetApiClient }; mod store_api; pub use self::store_api::{ StoreApi, StoreApiClient }; +mod testing_api; +pub use self::testing_api::{ TestingApi, TestingApiClient }; mod user_api; pub use self::user_api::{ UserApi, UserApiClient }; diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/testing_api.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/testing_api.rs new file mode 100644 index 0000000000..fd521555b7 --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/testing_api.rs @@ -0,0 +1,60 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +use std::rc::Rc; +use std::borrow::Borrow; +use std::pin::Pin; +#[allow(unused_imports)] +use std::option::Option; + +use hyper; +use futures::Future; + +use super::{Error, configuration}; +use super::request as __internal_request; + +pub struct TestingApiClient + where C: Clone + std::marker::Send + Sync + 'static { + configuration: Rc>, +} + +impl TestingApiClient + where C: Clone + std::marker::Send + Sync { + pub fn new(configuration: Rc>) -> TestingApiClient { + TestingApiClient { + configuration, + } + } +} + +pub trait TestingApi { + fn tests_file_response_get(&self, ) -> Pin>>>; + fn tests_type_testing_get(&self, ) -> Pin>>>; +} + +implTestingApi for TestingApiClient + where C: Clone + std::marker::Send + Sync { + #[allow(unused_mut)] + fn tests_file_response_get(&self, ) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/tests/fileResponse".to_string()) + ; + + req.execute(self.configuration.borrow()) + } + + #[allow(unused_mut)] + fn tests_type_testing_get(&self, ) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/tests/typeTesting".to_string()) + ; + + req.execute(self.configuration.borrow()) + } + +} diff --git a/samples/client/petstore/rust/hyper/petstore/src/models/action_container.rs b/samples/client/petstore/rust/hyper/petstore/src/models/action_container.rs new file mode 100644 index 0000000000..32d925eed3 --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/src/models/action_container.rs @@ -0,0 +1,28 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct ActionContainer { + #[serde(rename = "action")] + pub action: Box, +} + +impl ActionContainer { + pub fn new(action: crate::models::Baz) -> ActionContainer { + ActionContainer { + action: Box::new(action), + } + } +} + + diff --git a/samples/client/petstore/rust/hyper/petstore/src/models/api_response.rs b/samples/client/petstore/rust/hyper/petstore/src/models/api_response.rs index eff3b44e36..3ec5b4ae30 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/models/api_response.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/models/api_response.rs @@ -17,7 +17,7 @@ pub struct ApiResponse { #[serde(rename = "code", skip_serializing_if = "Option::is_none")] pub code: Option, #[serde(rename = "type", skip_serializing_if = "Option::is_none")] - pub _type: Option, + pub r#type: Option, #[serde(rename = "message", skip_serializing_if = "Option::is_none")] pub message: Option, } @@ -27,7 +27,7 @@ impl ApiResponse { pub fn new() -> ApiResponse { ApiResponse { code: None, - _type: None, + r#type: None, message: None, } } diff --git a/samples/client/petstore/rust/hyper/petstore/src/models/baz.rs b/samples/client/petstore/rust/hyper/petstore/src/models/baz.rs new file mode 100644 index 0000000000..94f8c5aa6a --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/src/models/baz.rs @@ -0,0 +1,43 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Baz : Test handling of empty variants + +/// Test handling of empty variants +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Baz { + #[serde(rename = "A")] + A, + #[serde(rename = "B")] + B, + #[serde(rename = "")] + Empty, + +} + +impl ToString for Baz { + fn to_string(&self) -> String { + match self { + Self::A => String::from("A"), + Self::B => String::from("B"), + Self::Empty => String::from(""), + } + } +} + +impl Default for Baz { + fn default() -> Baz { + Self::A + } +} + + + + diff --git a/samples/client/petstore/rust/hyper/petstore/src/models/mod.rs b/samples/client/petstore/rust/hyper/petstore/src/models/mod.rs index 37334443da..af4630c6a2 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/models/mod.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/models/mod.rs @@ -1,5 +1,9 @@ +pub mod action_container; +pub use self::action_container::ActionContainer; pub mod api_response; pub use self::api_response::ApiResponse; +pub mod baz; +pub use self::baz::Baz; pub mod category; pub use self::category::Category; pub mod order; @@ -8,7 +12,11 @@ pub mod pet; pub use self::pet::Pet; pub mod property_test; pub use self::property_test::PropertyTest; +pub mod model_return; +pub use self::model_return::Return; pub mod tag; pub use self::tag::Tag; +pub mod type_testing; +pub use self::type_testing::TypeTesting; pub mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/hyper/petstore/src/models/model_return.rs b/samples/client/petstore/rust/hyper/petstore/src/models/model_return.rs new file mode 100644 index 0000000000..5deb3e5ee1 --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/src/models/model_return.rs @@ -0,0 +1,36 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Return : Test using keywords + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Return { + #[serde(rename = "match", skip_serializing_if = "Option::is_none")] + pub r#match: Option, + #[serde(rename = "async", skip_serializing_if = "Option::is_none")] + pub r#async: Option, + #[serde(rename = "super", skip_serializing_if = "Option::is_none")] + pub param_super: Option, +} + +impl Return { + /// Test using keywords + pub fn new() -> Return { + Return { + r#match: None, + r#async: None, + param_super: None, + } + } +} + + diff --git a/samples/client/petstore/rust/hyper/petstore/src/models/type_testing.rs b/samples/client/petstore/rust/hyper/petstore/src/models/type_testing.rs new file mode 100644 index 0000000000..dda67915df --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/src/models/type_testing.rs @@ -0,0 +1,48 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// TypeTesting : Test handling of different field data types + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TypeTesting { + #[serde(rename = "int32")] + pub int32: i32, + #[serde(rename = "int64")] + pub int64: i64, + #[serde(rename = "float")] + pub float: f32, + #[serde(rename = "double")] + pub double: f64, + #[serde(rename = "string")] + pub string: String, + #[serde(rename = "boolean")] + pub boolean: bool, + #[serde(rename = "uuid")] + pub uuid: uuid::Uuid, +} + +impl TypeTesting { + /// Test handling of different field data types + pub fn new(int32: i32, int64: i64, float: f32, double: f64, string: String, boolean: bool, uuid: uuid::Uuid) -> TypeTesting { + TypeTesting { + int32, + int64, + float, + double, + string, + boolean, + uuid, + } + } +} + + diff --git a/samples/client/petstore/rust/hyper/rust-test/.gitignore b/samples/client/petstore/rust/hyper/rust-test/.gitignore deleted file mode 100644 index 6aa106405a..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/target/ -**/*.rs.bk -Cargo.lock diff --git a/samples/client/petstore/rust/hyper/rust-test/.openapi-generator/FILES b/samples/client/petstore/rust/hyper/rust-test/.openapi-generator/FILES deleted file mode 100644 index 22f11c2df5..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/.openapi-generator/FILES +++ /dev/null @@ -1,15 +0,0 @@ -.gitignore -.travis.yml -Cargo.toml -README.md -docs/DefaultApi.md -docs/TypeTesting.md -git_push.sh -src/apis/client.rs -src/apis/configuration.rs -src/apis/default_api.rs -src/apis/mod.rs -src/apis/request.rs -src/lib.rs -src/models/mod.rs -src/models/type_testing.rs diff --git a/samples/client/petstore/rust/hyper/rust-test/.openapi-generator/VERSION b/samples/client/petstore/rust/hyper/rust-test/.openapi-generator/VERSION deleted file mode 100644 index d99e7162d0..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/hyper/rust-test/.travis.yml b/samples/client/petstore/rust/hyper/rust-test/.travis.yml deleted file mode 100644 index 22761ba7ee..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: rust diff --git a/samples/client/petstore/rust/hyper/rust-test/Cargo.toml b/samples/client/petstore/rust/hyper/rust-test/Cargo.toml deleted file mode 100644 index 4a39ba0c5f..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "rust-test-hyper" -version = "1.0.0" -authors = ["OpenAPI Generator team and contributors"] -edition = "2018" - -[dependencies] -serde = "^1.0" -serde_derive = "^1.0" -serde_json = "^1.0" -url = "1.5" -hyper = "~0.11" -serde_yaml = "0.7" -base64 = "~0.7.0" -futures = "0.1.23" - -[dev-dependencies] -tokio-core = "*" diff --git a/samples/client/petstore/rust/hyper/rust-test/README.md b/samples/client/petstore/rust/hyper/rust-test/README.md deleted file mode 100644 index 1383eecfd3..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# Rust API client for rust-test-hyper - -Special testing for the Rust client generator - -## Overview - -This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. - -- API version: 1.0.7 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.RustClientCodegen - -## Installation - -Put the package under your project folder and add the following to `Cargo.toml` under `[dependencies]`: - -``` - openapi = { path = "./generated" } -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://localhost* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*DefaultApi* | [**dummy_get**](docs/DefaultApi.md#dummy_get) | **Get** /dummy | A dummy endpoint to make the spec valid. - - -## Documentation For Models - - - [TypeTesting](docs/TypeTesting.md) - - -To get access to the crate's generated documentation, use: - -``` -cargo doc --open -``` - -## Author - - - diff --git a/samples/client/petstore/rust/hyper/rust-test/docs/DefaultApi.md b/samples/client/petstore/rust/hyper/rust-test/docs/DefaultApi.md deleted file mode 100644 index caf4632183..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/docs/DefaultApi.md +++ /dev/null @@ -1,34 +0,0 @@ -# \DefaultApi - -All URIs are relative to *http://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**dummy_get**](DefaultApi.md#dummy_get) | **Get** /dummy | A dummy endpoint to make the spec valid. - - - -## dummy_get - -> dummy_get() -A dummy endpoint to make the spec valid. - -### Parameters - -This endpoint does not need any parameter. - -### Return type - - (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/rust/hyper/rust-test/docs/TypeTesting.md b/samples/client/petstore/rust/hyper/rust-test/docs/TypeTesting.md deleted file mode 100644 index 7b05cee280..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/docs/TypeTesting.md +++ /dev/null @@ -1,16 +0,0 @@ -# TypeTesting - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | Option<**i32**> | | [optional] -**long** | Option<**i64**> | | [optional] -**number** | Option<**f32**> | | [optional] -**float** | Option<**f32**> | | [optional] -**double** | Option<**f64**> | | [optional] -**uuid** | Option<**String**> | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/client/petstore/rust/hyper/rust-test/git_push.sh b/samples/client/petstore/rust/hyper/rust-test/git_push.sh deleted file mode 100644 index ced3be2b0c..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/git_push.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - diff --git a/samples/client/petstore/rust/hyper/rust-test/src/apis/client.rs b/samples/client/petstore/rust/hyper/rust-test/src/apis/client.rs deleted file mode 100644 index 4976ba81c6..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/src/apis/client.rs +++ /dev/null @@ -1,23 +0,0 @@ -use std::rc::Rc; - -use hyper; -use super::configuration::Configuration; - -pub struct APIClient { - default_api: Box, -} - -impl APIClient { - pub fn new(configuration: Configuration) -> APIClient { - let rc = Rc::new(configuration); - - APIClient { - default_api: Box::new(crate::apis::DefaultApiClient::new(rc.clone())), - } - } - - pub fn default_api(&self) -> &dyn crate::apis::DefaultApi{ - self.default_api.as_ref() - } - -} diff --git a/samples/client/petstore/rust/hyper/rust-test/src/apis/configuration.rs b/samples/client/petstore/rust/hyper/rust-test/src/apis/configuration.rs deleted file mode 100644 index 79762a1437..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/src/apis/configuration.rs +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Rust client test spec - * - * Special testing for the Rust client generator - * - * The version of the OpenAPI document: 1.0.7 - * - * Generated by: https://openapi-generator.tech - */ - -use hyper; - -pub struct Configuration { - pub base_path: String, - pub user_agent: Option, - pub client: hyper::client::Client, - pub basic_auth: Option, - pub oauth_access_token: Option, - pub api_key: Option, - // TODO: take an oauth2 token source, similar to the go one -} - -pub type BasicAuth = (String, Option); - -pub struct ApiKey { - pub prefix: Option, - pub key: String, -} - -impl Configuration { - pub fn new(client: hyper::client::Client) -> Configuration { - Configuration { - base_path: "http://localhost".to_owned(), - user_agent: Some("OpenAPI-Generator/1.0.7/rust".to_owned()), - client: client, - basic_auth: None, - oauth_access_token: None, - api_key: None, - } - } -} diff --git a/samples/client/petstore/rust/hyper/rust-test/src/apis/default_api.rs b/samples/client/petstore/rust/hyper/rust-test/src/apis/default_api.rs deleted file mode 100644 index 5ebb6a09dd..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/src/apis/default_api.rs +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Rust client test spec - * - * Special testing for the Rust client generator - * - * The version of the OpenAPI document: 1.0.7 - * - * Generated by: https://openapi-generator.tech - */ - -use std::rc::Rc; -use std::borrow::Borrow; -#[allow(unused_imports)] -use std::option::Option; - -use hyper; -use serde_json; -use futures::Future; - -use super::{Error, configuration}; -use super::request as __internal_request; - -pub struct DefaultApiClient { - configuration: Rc>, -} - -impl DefaultApiClient { - pub fn new(configuration: Rc>) -> DefaultApiClient { - DefaultApiClient { - configuration, - } - } -} - -pub trait DefaultApi { - fn dummy_get(&self, ) -> Box>>; -} - -implDefaultApi for DefaultApiClient { - fn dummy_get(&self, ) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/dummy".to_string()) - ; - req = req.returns_nothing(); - - req.execute(self.configuration.borrow()) - } - -} diff --git a/samples/client/petstore/rust/hyper/rust-test/src/apis/mod.rs b/samples/client/petstore/rust/hyper/rust-test/src/apis/mod.rs deleted file mode 100644 index cb13d23efc..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/src/apis/mod.rs +++ /dev/null @@ -1,58 +0,0 @@ -use hyper; -use serde; -use serde_json; - -#[derive(Debug)] -pub enum Error { - UriError(hyper::error::UriError), - Hyper(hyper::Error), - Serde(serde_json::Error), - ApiError(ApiError), -} - -#[derive(Debug)] -pub struct ApiError { - pub code: hyper::StatusCode, - pub content: Option, -} - -impl<'de, T> From<(hyper::StatusCode, &'de [u8])> for Error - where T: serde::Deserialize<'de> { - fn from(e: (hyper::StatusCode, &'de [u8])) -> Self { - if e.1.len() == 0 { - return Error::ApiError(ApiError{ - code: e.0, - content: None, - }); - } - match serde_json::from_slice::(e.1) { - Ok(t) => Error::ApiError(ApiError{ - code: e.0, - content: Some(t), - }), - Err(e) => { - Error::from(e) - } - } - } -} - -impl From for Error { - fn from(e: hyper::Error) -> Self { - return Error::Hyper(e) - } -} - -impl From for Error { - fn from(e: serde_json::Error) -> Self { - return Error::Serde(e) - } -} - -mod request; - -mod default_api; -pub use self::default_api::{ DefaultApi, DefaultApiClient }; - -pub mod configuration; -pub mod client; diff --git a/samples/client/petstore/rust/hyper/rust-test/src/apis/request.rs b/samples/client/petstore/rust/hyper/rust-test/src/apis/request.rs deleted file mode 100644 index f97b527719..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/src/apis/request.rs +++ /dev/null @@ -1,239 +0,0 @@ -use std::borrow::Cow; -use std::collections::HashMap; - -use super::{configuration, Error}; -use futures; -use futures::{Future, Stream}; -use hyper; -use hyper::header::UserAgent; -use serde; -use serde_json; - -pub(crate) struct ApiKey { - pub in_header: bool, - pub in_query: bool, - pub param_name: String, -} - -impl ApiKey { - fn key(&self, prefix: &Option, key: &str) -> String { - match prefix { - None => key.to_owned(), - Some(ref prefix) => format!("{} {}", prefix, key), - } - } -} - -#[allow(dead_code)] -pub(crate) enum Auth { - None, - ApiKey(ApiKey), - Basic, - Oauth, -} - -pub(crate) struct Request { - auth: Auth, - method: hyper::Method, - path: String, - query_params: HashMap, - no_return_type: bool, - path_params: HashMap, - form_params: HashMap, - header_params: HashMap, - // TODO: multiple body params are possible technically, but not supported here. - serialized_body: Option, -} - -impl Request { - pub fn new(method: hyper::Method, path: String) -> Self { - Request { - auth: Auth::None, - method: method, - path: path, - query_params: HashMap::new(), - path_params: HashMap::new(), - form_params: HashMap::new(), - header_params: HashMap::new(), - serialized_body: None, - no_return_type: false, - } - } - - pub fn with_body_param(mut self, param: T) -> Self { - self.serialized_body = Some(serde_json::to_string(¶m).unwrap()); - self - } - - pub fn with_header_param(mut self, basename: String, param: String) -> Self { - self.header_params.insert(basename, param); - self - } - - pub fn with_query_param(mut self, basename: String, param: String) -> Self { - self.query_params.insert(basename, param); - self - } - - pub fn with_path_param(mut self, basename: String, param: String) -> Self { - self.path_params.insert(basename, param); - self - } - - pub fn with_form_param(mut self, basename: String, param: String) -> Self { - self.form_params.insert(basename, param); - self - } - - pub fn returns_nothing(mut self) -> Self { - self.no_return_type = true; - self - } - - pub fn with_auth(mut self, auth: Auth) -> Self { - self.auth = auth; - self - } - - pub fn execute<'a, C, U>( - self, - conf: &configuration::Configuration, - ) -> Box> + 'a> - where - C: hyper::client::Connect, - U: Sized + 'a, - for<'de> U: serde::Deserialize<'de>, - { - let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned()); - // raw_headers is for headers we don't know the proper type of (e.g. custom api key - // headers); headers is for ones we do know the type of. - let mut raw_headers = HashMap::new(); - let mut headers: hyper::header::Headers = hyper::header::Headers::new(); - - let mut path = self.path; - for (k, v) in self.path_params { - // replace {id} with the value of the id path param - path = path.replace(&format!("{{{}}}", k), &v); - } - - for (k, v) in self.header_params { - raw_headers.insert(k, v); - } - - for (key, val) in self.query_params { - query_string.append_pair(&key, &val); - } - - match self.auth { - Auth::ApiKey(apikey) => { - if let Some(ref key) = conf.api_key { - let val = apikey.key(&key.prefix, &key.key); - if apikey.in_query { - query_string.append_pair(&apikey.param_name, &val); - } - if apikey.in_header { - raw_headers.insert(apikey.param_name, val); - } - } - } - Auth::Basic => { - if let Some(ref auth_conf) = conf.basic_auth { - let auth = hyper::header::Authorization(hyper::header::Basic { - username: auth_conf.0.to_owned(), - password: auth_conf.1.to_owned(), - }); - headers.set(auth); - } - } - Auth::Oauth => { - if let Some(ref token) = conf.oauth_access_token { - let auth = hyper::header::Authorization(hyper::header::Bearer { - token: token.to_owned(), - }); - headers.set(auth); - } - } - Auth::None => {} - } - - let mut uri_str = format!("{}{}", conf.base_path, path); - - let query_string_str = query_string.finish(); - if query_string_str != "" { - uri_str += "?"; - uri_str += &query_string_str; - } - let uri: hyper::Uri = match uri_str.parse() { - Err(e) => { - return Box::new(futures::future::err(Error::UriError(e))); - } - Ok(u) => u, - }; - - let mut req = hyper::Request::new(self.method, uri); - { - let req_headers = req.headers_mut(); - if let Some(ref user_agent) = conf.user_agent { - req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone()))); - } - - req_headers.extend(headers.iter()); - - for (key, val) in raw_headers { - req_headers.set_raw(key, val); - } - } - - if self.form_params.len() > 0 { - req.headers_mut().set(hyper::header::ContentType::form_url_encoded()); - let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned()); - for (k, v) in self.form_params { - enc.append_pair(&k, &v); - } - req.set_body(enc.finish()); - } - - if let Some(body) = self.serialized_body { - req.headers_mut().set(hyper::header::ContentType::json()); - req.headers_mut() - .set(hyper::header::ContentLength(body.len() as u64)); - req.set_body(body); - } - - let no_ret_type = self.no_return_type; - let res = conf.client - .request(req) - .map_err(|e| Error::from(e)) - .and_then(|resp| { - let status = resp.status(); - resp.body() - .concat2() - .and_then(move |body| Ok((status, body))) - .map_err(|e| Error::from(e)) - }) - .and_then(|(status, body)| { - if status.is_success() { - Ok(body) - } else { - Err(Error::from((status, &*body))) - } - }); - Box::new( - res - .and_then(move |body| { - let parsed: Result = if no_ret_type { - // This is a hack; if there's no_ret_type, U is (), but serde_json gives an - // error when deserializing "" into (), so deserialize 'null' into it - // instead. - // An alternate option would be to require U: Default, and then return - // U::default() here instead since () implements that, but then we'd - // need to impl default for all models. - serde_json::from_str("null") - } else { - serde_json::from_slice(&body) - }; - parsed.map_err(|e| Error::from(e)) - }) - ) - } -} diff --git a/samples/client/petstore/rust/hyper/rust-test/src/lib.rs b/samples/client/petstore/rust/hyper/rust-test/src/lib.rs deleted file mode 100644 index a76d822525..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/src/lib.rs +++ /dev/null @@ -1,11 +0,0 @@ -#[macro_use] -extern crate serde_derive; - -extern crate serde; -extern crate serde_json; -extern crate url; -extern crate hyper; -extern crate futures; - -pub mod apis; -pub mod models; diff --git a/samples/client/petstore/rust/hyper/rust-test/src/models/mod.rs b/samples/client/petstore/rust/hyper/rust-test/src/models/mod.rs deleted file mode 100644 index 97887b5798..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/src/models/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod type_testing; -pub use self::type_testing::TypeTesting; diff --git a/samples/client/petstore/rust/hyper/rust-test/src/models/type_testing.rs b/samples/client/petstore/rust/hyper/rust-test/src/models/type_testing.rs deleted file mode 100644 index 530d1d1365..0000000000 --- a/samples/client/petstore/rust/hyper/rust-test/src/models/type_testing.rs +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Rust client test spec - * - * Special testing for the Rust client generator - * - * The version of the OpenAPI document: 1.0.7 - * - * Generated by: https://openapi-generator.tech - */ - -/// TypeTesting : Test handling of differing types (see \\#3463) - - - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct TypeTesting { - #[serde(rename = "integer", skip_serializing_if = "Option::is_none")] - pub integer: Option, - #[serde(rename = "long", skip_serializing_if = "Option::is_none")] - pub long: Option, - #[serde(rename = "number", skip_serializing_if = "Option::is_none")] - pub number: Option, - #[serde(rename = "float", skip_serializing_if = "Option::is_none")] - pub float: Option, - #[serde(rename = "double", skip_serializing_if = "Option::is_none")] - pub double: Option, - #[serde(rename = "uuid", skip_serializing_if = "Option::is_none")] - pub uuid: Option, -} - -impl TypeTesting { - /// Test handling of differing types (see \\#3463) - pub fn new() -> TypeTesting { - TypeTesting { - integer: None, - long: None, - number: None, - float: None, - double: None, - uuid: None, - } - } -} - - diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/.gitignore b/samples/client/petstore/rust/reqwest/fileResponseTest/.gitignore deleted file mode 100644 index 6aa106405a..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/target/ -**/*.rs.bk -Cargo.lock diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/.openapi-generator/FILES b/samples/client/petstore/rust/reqwest/fileResponseTest/.openapi-generator/FILES deleted file mode 100644 index 20457f1a6d..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/.openapi-generator/FILES +++ /dev/null @@ -1,11 +0,0 @@ -.gitignore -.travis.yml -Cargo.toml -README.md -docs/DefaultApi.md -git_push.sh -src/apis/configuration.rs -src/apis/default_api.rs -src/apis/mod.rs -src/lib.rs -src/models/mod.rs diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/fileResponseTest/.openapi-generator/VERSION deleted file mode 100644 index d99e7162d0..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/.travis.yml b/samples/client/petstore/rust/reqwest/fileResponseTest/.travis.yml deleted file mode 100644 index 22761ba7ee..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: rust diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/Cargo.toml b/samples/client/petstore/rust/reqwest/fileResponseTest/Cargo.toml deleted file mode 100644 index 67a7558679..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "fileResponseTest-reqwest" -version = "1.0.0" -authors = ["OpenAPI Generator team and contributors"] -edition = "2018" - -[dependencies] -serde = "^1.0" -serde_derive = "^1.0" -serde_json = "^1.0" -url = "1.5" -reqwest = "~0.9" - -[dev-dependencies] diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/README.md b/samples/client/petstore/rust/reqwest/fileResponseTest/README.md deleted file mode 100644 index 8bf849adb6..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# Rust API client for fileResponseTest-reqwest - -No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - -## Overview - -This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. - -- API version: 1.0.0 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.RustClientCodegen - -## Installation - -Put the package under your project folder and add the following to `Cargo.toml` under `[dependencies]`: - -``` - openapi = { path = "./generated" } -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://localhost/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*DefaultApi* | [**fileresponsetest**](docs/DefaultApi.md#fileresponsetest) | **get** /tests/fileResponse | - - -## Documentation For Models - - - -To get access to the crate's generated documentation, use: - -``` -cargo doc --open -``` - -## Author - - - diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/docs/DefaultApi.md b/samples/client/petstore/rust/reqwest/fileResponseTest/docs/DefaultApi.md deleted file mode 100644 index 0b0273e434..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/docs/DefaultApi.md +++ /dev/null @@ -1,34 +0,0 @@ -# \DefaultApi - -All URIs are relative to *http://localhost/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**fileresponsetest**](DefaultApi.md#fileresponsetest) | **get** /tests/fileResponse | - - - -## fileresponsetest - -> std::path::PathBuf fileresponsetest() - - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -[**std::path::PathBuf**](std::path::PathBuf.md) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/octet-stream - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/git_push.sh b/samples/client/petstore/rust/reqwest/fileResponseTest/git_push.sh deleted file mode 100644 index ced3be2b0c..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/git_push.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/client.rs b/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/client.rs deleted file mode 100644 index b10fef0b55..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/client.rs +++ /dev/null @@ -1,22 +0,0 @@ -use std::rc::Rc; - -use super::configuration::Configuration; - -pub struct APIClient { - default_api: Box, -} - -impl APIClient { - pub fn new(configuration: Configuration) -> APIClient { - let rc = Rc::new(configuration); - - APIClient { - default_api: Box::new(crate::apis::default_api::DefaultApiClient::new(rc.clone())), - } - } - - pub fn default_api(&self) -> &dyn crate::apis::default_api::DefaultApi{ - self.default_api.as_ref() - } - -} diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/configuration.rs b/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/configuration.rs deleted file mode 100644 index 107d558aa4..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/configuration.rs +++ /dev/null @@ -1,50 +0,0 @@ -/* - * File Response Test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - - -use reqwest; - -pub struct Configuration { - pub base_path: String, - pub user_agent: Option, - pub client: reqwest::Client, - pub basic_auth: Option, - pub oauth_access_token: Option, - pub bearer_access_token: Option, - pub api_key: Option, - // TODO: take an oauth2 token source, similar to the go one -} - -pub type BasicAuth = (String, Option); - -pub struct ApiKey { - pub prefix: Option, - pub key: String, -} - -impl Configuration { - pub fn new() -> Configuration { - Configuration::default() - } -} - -impl Default for Configuration { - fn default() -> Self { - Configuration { - base_path: "http://localhost/v2".to_owned(), - user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), - client: reqwest::Client::new(), - basic_auth: None, - oauth_access_token: None, - bearer_access_token: None, - api_key: None, - } - } -} diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/default_api.rs b/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/default_api.rs deleted file mode 100644 index 1dad859d20..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/default_api.rs +++ /dev/null @@ -1,51 +0,0 @@ -/* - * File Response Test - * - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - - -use reqwest; - -use crate::apis::ResponseContent; -use super::{Error, configuration}; - - -/// struct for typed errors of method `fileresponsetest` -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum FileresponsetestError { - UnknownValue(serde_json::Value), -} - - -pub fn fileresponsetest(configuration: &configuration::Configuration, ) -> Result> { - - let client = &configuration.client; - - let uri_str = format!("{}/tests/fileResponse", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); - - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); - } - - let req = req_builder.build()?; - let mut resp = client.execute(req)?; - - let status = resp.status(); - let content = resp.text()?; - - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) - } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) - } -} - diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/mod.rs b/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/mod.rs deleted file mode 100644 index aeab00a7bc..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/src/apis/mod.rs +++ /dev/null @@ -1,43 +0,0 @@ -use reqwest; -use serde_json; - -#[derive(Debug, Clone)] -pub struct ResponseContent { - pub status: reqwest::StatusCode, - pub content: String, - pub entity: Option, -} - -#[derive(Debug)] -pub enum Error { - Reqwest(reqwest::Error), - Serde(serde_json::Error), - Io(std::io::Error), - ResponseError(ResponseContent), -} - -impl From for Error { - fn from(e: reqwest::Error) -> Self { - Error::Reqwest(e) - } -} - -impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Serde(e) - } -} - -impl From for Error { - fn from(e: std::io::Error) -> Self { - Error::Io(e) - } -} - -pub fn urlencode>(s: T) -> String { - ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() -} - -pub mod default_api; - -pub mod configuration; diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/src/lib.rs b/samples/client/petstore/rust/reqwest/fileResponseTest/src/lib.rs deleted file mode 100644 index c1dd666f79..0000000000 --- a/samples/client/petstore/rust/reqwest/fileResponseTest/src/lib.rs +++ /dev/null @@ -1,10 +0,0 @@ -#[macro_use] -extern crate serde_derive; - -extern crate serde; -extern crate serde_json; -extern crate url; -extern crate reqwest; - -pub mod apis; -pub mod models; diff --git a/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/FILES b/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/FILES index 611ac7b6dd..6a0f473de4 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/FILES +++ b/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/FILES @@ -2,26 +2,40 @@ .travis.yml Cargo.toml README.md +docs/ActionContainer.md docs/ApiResponse.md +docs/Baz.md docs/Category.md +docs/FakeApi.md docs/Order.md docs/Pet.md docs/PetApi.md +docs/PropertyTest.md +docs/Return.md docs/StoreApi.md docs/Tag.md +docs/TestingApi.md +docs/TypeTesting.md docs/User.md docs/UserApi.md git_push.sh src/apis/configuration.rs +src/apis/fake_api.rs src/apis/mod.rs src/apis/pet_api.rs src/apis/store_api.rs +src/apis/testing_api.rs src/apis/user_api.rs src/lib.rs +src/models/action_container.rs src/models/api_response.rs +src/models/baz.rs src/models/category.rs src/models/mod.rs +src/models/model_return.rs src/models/order.rs src/models/pet.rs +src/models/property_test.rs src/models/tag.rs +src/models/type_testing.rs src/models/user.rs diff --git a/samples/client/petstore/rust/reqwest/petstore-async/README.md b/samples/client/petstore/rust/reqwest/petstore-async/README.md index a26b68bd33..e17c4105c1 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/README.md +++ b/samples/client/petstore/rust/reqwest/petstore-async/README.md @@ -25,6 +25,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**test_nullable_required_param**](docs/FakeApi.md#test_nullable_required_param) | **GET** /fake/user/{username} | To test nullable required parameters *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -37,6 +38,8 @@ Class | Method | HTTP request | Description *StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status *StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID *StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*TestingApi* | [**tests_file_response_get**](docs/TestingApi.md#tests_file_response_get) | **GET** /tests/fileResponse | Returns an image file +*TestingApi* | [**tests_type_testing_get**](docs/TestingApi.md#tests_type_testing_get) | **GET** /tests/typeTesting | Route to test the TypeTesting schema *UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user *UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array *UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array @@ -49,11 +52,16 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [ActionContainer](docs/ActionContainer.md) - [ApiResponse](docs/ApiResponse.md) + - [Baz](docs/Baz.md) - [Category](docs/Category.md) - [Order](docs/Order.md) - [Pet](docs/Pet.md) + - [PropertyTest](docs/PropertyTest.md) + - [Return](docs/Return.md) - [Tag](docs/Tag.md) + - [TypeTesting](docs/TypeTesting.md) - [User](docs/User.md) diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/ActionContainer.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/ActionContainer.md new file mode 100644 index 0000000000..8490ec5d82 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/ActionContainer.md @@ -0,0 +1,11 @@ +# ActionContainer + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**action** | [**crate::models::Baz**](Baz.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/ApiResponse.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/ApiResponse.md index 97128a87d9..b5125ba685 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/docs/ApiResponse.md +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/ApiResponse.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | Option<**i32**> | | [optional] -**_type** | Option<**String**> | | [optional] +**r#type** | Option<**String**> | | [optional] **message** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/Baz.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/Baz.md new file mode 100644 index 0000000000..68c84b1b1b --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/Baz.md @@ -0,0 +1,10 @@ +# Baz + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/FakeApi.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/FakeApi.md new file mode 100644 index 0000000000..55bf612aa2 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/FakeApi.md @@ -0,0 +1,41 @@ +# \FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**test_nullable_required_param**](FakeApi.md#test_nullable_required_param) | **GET** /fake/user/{username} | To test nullable required parameters + + + +## test_nullable_required_param + +> test_nullable_required_param(username, dummy_required_nullable_param, uppercase) +To test nullable required parameters + + + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**username** | **String** | The name that needs to be fetched. Use user1 for testing. | [required] | +**dummy_required_nullable_param** | Option<**String**> | To test nullable required parameters | [required] | +**uppercase** | Option<**String**> | To test parameter names in upper case | | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/PropertyTest.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/PropertyTest.md new file mode 100644 index 0000000000..3f36c163de --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/PropertyTest.md @@ -0,0 +1,11 @@ +# PropertyTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | Option<[**uuid::Uuid**](uuid::Uuid.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/Return.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/Return.md new file mode 100644 index 0000000000..04710a019d --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/Return.md @@ -0,0 +1,13 @@ +# Return + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#match** | Option<**i32**> | | [optional] +**r#async** | Option<**bool**> | | [optional] +**param_super** | Option<**bool**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/TestingApi.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/TestingApi.md new file mode 100644 index 0000000000..ca0c06e06a --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/TestingApi.md @@ -0,0 +1,60 @@ +# \TestingApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**tests_file_response_get**](TestingApi.md#tests_file_response_get) | **GET** /tests/fileResponse | Returns an image file +[**tests_type_testing_get**](TestingApi.md#tests_type_testing_get) | **GET** /tests/typeTesting | Route to test the TypeTesting schema + + + +## tests_file_response_get + +> std::path::PathBuf tests_file_response_get() +Returns an image file + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**std::path::PathBuf**](std::path::PathBuf.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/jpeg + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## tests_type_testing_get + +> crate::models::TypeTesting tests_type_testing_get() +Route to test the TypeTesting schema + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**crate::models::TypeTesting**](TypeTesting.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/TypeTesting.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/TypeTesting.md new file mode 100644 index 0000000000..6beca6dbac --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/TypeTesting.md @@ -0,0 +1,17 @@ +# TypeTesting + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**int32** | **i32** | | +**int64** | **i64** | | +**float** | **f32** | | +**double** | **f64** | | +**string** | **String** | | +**boolean** | **bool** | | +**uuid** | [**uuid::Uuid**](uuid::Uuid.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/fake_api.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/fake_api.rs new file mode 100644 index 0000000000..d457ee3888 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/fake_api.rs @@ -0,0 +1,89 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; + +use crate::apis::ResponseContent; +use super::{Error, configuration}; + +/// struct for passing parameters to the method [`test_nullable_required_param`] +#[derive(Clone, Debug, Default)] +pub struct TestNullableRequiredParamParams { + /// The name that needs to be fetched. Use user1 for testing. + pub username: String, + /// To test nullable required parameters + pub dummy_required_nullable_param: Option, + /// To test parameter names in upper case + pub uppercase: Option +} + + +/// struct for typed successes of method [`test_nullable_required_param`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestNullableRequiredParamSuccess { + Status200(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`test_nullable_required_param`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestNullableRequiredParamError { + Status400(), + Status404(), + UnknownValue(serde_json::Value), +} + + +/// +pub async fn test_nullable_required_param(configuration: &configuration::Configuration, params: TestNullableRequiredParamParams) -> Result, Error> { + let local_var_configuration = configuration; + + // unbox the parameters + let username = params.username; + let dummy_required_nullable_param = params.dummy_required_nullable_param; + let uppercase = params.uppercase; + + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/fake/user/{username}", local_var_configuration.base_path, username=crate::apis::urlencode(username)); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + match dummy_required_nullable_param { + Some(local_var_param_value) => { local_var_req_builder = local_var_req_builder.header("dummy_required_nullable_param", local_var_param_value.to_string()); }, + None => { local_var_req_builder = local_var_req_builder.header("dummy_required_nullable_param", ""); }, + } + if let Some(local_var_param_value) = uppercase { + local_var_req_builder = local_var_req_builder.header("UPPERCASE", local_var_param_value.to_string()); + } + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) + } +} + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/mod.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/mod.rs index c24f345edf..34085cdedf 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/mod.rs @@ -61,8 +61,10 @@ pub fn urlencode>(s: T) -> String { ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() } +pub mod fake_api; pub mod pet_api; pub mod store_api; +pub mod testing_api; pub mod user_api; pub mod configuration; diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/testing_api.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/testing_api.rs new file mode 100644 index 0000000000..98f2fa1562 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/testing_api.rs @@ -0,0 +1,112 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; + +use crate::apis::ResponseContent; +use super::{Error, configuration}; + + +/// struct for typed successes of method [`tests_file_response_get`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestsFileResponseGetSuccess { + Status200(std::path::PathBuf), + UnknownValue(serde_json::Value), +} + +/// struct for typed successes of method [`tests_type_testing_get`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestsTypeTestingGetSuccess { + Status200(crate::models::TypeTesting), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`tests_file_response_get`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestsFileResponseGetError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`tests_type_testing_get`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestsTypeTestingGetError { + UnknownValue(serde_json::Value), +} + + +pub async fn tests_file_response_get(configuration: &configuration::Configuration) -> Result, Error> { + let local_var_configuration = configuration; + + // unbox the parameters + + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/tests/fileResponse", local_var_configuration.base_path); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn tests_type_testing_get(configuration: &configuration::Configuration) -> Result, Error> { + let local_var_configuration = configuration; + + // unbox the parameters + + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/tests/typeTesting", local_var_configuration.base_path); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) + } +} + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/models/action_container.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/models/action_container.rs new file mode 100644 index 0000000000..32d925eed3 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/models/action_container.rs @@ -0,0 +1,28 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct ActionContainer { + #[serde(rename = "action")] + pub action: Box, +} + +impl ActionContainer { + pub fn new(action: crate::models::Baz) -> ActionContainer { + ActionContainer { + action: Box::new(action), + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/models/api_response.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/models/api_response.rs index eff3b44e36..3ec5b4ae30 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/models/api_response.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/models/api_response.rs @@ -17,7 +17,7 @@ pub struct ApiResponse { #[serde(rename = "code", skip_serializing_if = "Option::is_none")] pub code: Option, #[serde(rename = "type", skip_serializing_if = "Option::is_none")] - pub _type: Option, + pub r#type: Option, #[serde(rename = "message", skip_serializing_if = "Option::is_none")] pub message: Option, } @@ -27,7 +27,7 @@ impl ApiResponse { pub fn new() -> ApiResponse { ApiResponse { code: None, - _type: None, + r#type: None, message: None, } } diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/models/baz.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/models/baz.rs new file mode 100644 index 0000000000..94f8c5aa6a --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/models/baz.rs @@ -0,0 +1,43 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Baz : Test handling of empty variants + +/// Test handling of empty variants +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Baz { + #[serde(rename = "A")] + A, + #[serde(rename = "B")] + B, + #[serde(rename = "")] + Empty, + +} + +impl ToString for Baz { + fn to_string(&self) -> String { + match self { + Self::A => String::from("A"), + Self::B => String::from("B"), + Self::Empty => String::from(""), + } + } +} + +impl Default for Baz { + fn default() -> Baz { + Self::A + } +} + + + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/models/mod.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/models/mod.rs index 1baf2f7528..af4630c6a2 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/models/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/models/mod.rs @@ -1,12 +1,22 @@ +pub mod action_container; +pub use self::action_container::ActionContainer; pub mod api_response; pub use self::api_response::ApiResponse; +pub mod baz; +pub use self::baz::Baz; pub mod category; pub use self::category::Category; pub mod order; pub use self::order::Order; pub mod pet; pub use self::pet::Pet; +pub mod property_test; +pub use self::property_test::PropertyTest; +pub mod model_return; +pub use self::model_return::Return; pub mod tag; pub use self::tag::Tag; +pub mod type_testing; +pub use self::type_testing::TypeTesting; pub mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/models/model_return.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/models/model_return.rs new file mode 100644 index 0000000000..5deb3e5ee1 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/models/model_return.rs @@ -0,0 +1,36 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Return : Test using keywords + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Return { + #[serde(rename = "match", skip_serializing_if = "Option::is_none")] + pub r#match: Option, + #[serde(rename = "async", skip_serializing_if = "Option::is_none")] + pub r#async: Option, + #[serde(rename = "super", skip_serializing_if = "Option::is_none")] + pub param_super: Option, +} + +impl Return { + /// Test using keywords + pub fn new() -> Return { + Return { + r#match: None, + r#async: None, + param_super: None, + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/models/property_test.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/models/property_test.rs new file mode 100644 index 0000000000..1c3c4f3f3f --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/models/property_test.rs @@ -0,0 +1,30 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// PropertyTest : A model to test various formats, e.g. UUID + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct PropertyTest { + #[serde(rename = "uuid", skip_serializing_if = "Option::is_none")] + pub uuid: Option, +} + +impl PropertyTest { + /// A model to test various formats, e.g. UUID + pub fn new() -> PropertyTest { + PropertyTest { + uuid: None, + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/models/type_testing.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/models/type_testing.rs new file mode 100644 index 0000000000..dda67915df --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/models/type_testing.rs @@ -0,0 +1,48 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// TypeTesting : Test handling of different field data types + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TypeTesting { + #[serde(rename = "int32")] + pub int32: i32, + #[serde(rename = "int64")] + pub int64: i64, + #[serde(rename = "float")] + pub float: f32, + #[serde(rename = "double")] + pub double: f64, + #[serde(rename = "string")] + pub string: String, + #[serde(rename = "boolean")] + pub boolean: bool, + #[serde(rename = "uuid")] + pub uuid: uuid::Uuid, +} + +impl TypeTesting { + /// Test handling of different field data types + pub fn new(int32: i32, int64: i64, float: f32, double: f64, string: String, boolean: bool, uuid: uuid::Uuid) -> TypeTesting { + TypeTesting { + int32, + int64, + float, + double, + string, + boolean, + uuid, + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/tests/pet_tests.rs b/samples/client/petstore/rust/reqwest/petstore-async/tests/pet_tests.rs index bf4cb42e86..8d9d2576f9 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/tests/pet_tests.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/tests/pet_tests.rs @@ -17,7 +17,7 @@ fn test_pet() { new_pet.id = Option::Some(8787); let new_pet_params = petstore_reqwest_async::apis::pet_api::AddPetParams { - body: new_pet, + pet: new_pet, }; // add pet @@ -28,7 +28,7 @@ fn test_pet() { }; // get pet - let pet_result = petstore_reqwest_async::apis::pet_api::get_pet_by_id(&config, get_pet_params); + let _pet_result = petstore_reqwest_async::apis::pet_api::get_pet_by_id(&config, get_pet_params); // TODO Testing async functions requires some additionnal testing crates. } diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/FILES b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/FILES index 611ac7b6dd..6a0f473de4 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/FILES +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/FILES @@ -2,26 +2,40 @@ .travis.yml Cargo.toml README.md +docs/ActionContainer.md docs/ApiResponse.md +docs/Baz.md docs/Category.md +docs/FakeApi.md docs/Order.md docs/Pet.md docs/PetApi.md +docs/PropertyTest.md +docs/Return.md docs/StoreApi.md docs/Tag.md +docs/TestingApi.md +docs/TypeTesting.md docs/User.md docs/UserApi.md git_push.sh src/apis/configuration.rs +src/apis/fake_api.rs src/apis/mod.rs src/apis/pet_api.rs src/apis/store_api.rs +src/apis/testing_api.rs src/apis/user_api.rs src/lib.rs +src/models/action_container.rs src/models/api_response.rs +src/models/baz.rs src/models/category.rs src/models/mod.rs +src/models/model_return.rs src/models/order.rs src/models/pet.rs +src/models/property_test.rs src/models/tag.rs +src/models/type_testing.rs src/models/user.rs diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/Cargo.toml b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/Cargo.toml index bdc29cf694..112dcce90d 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/Cargo.toml +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/Cargo.toml @@ -10,9 +10,9 @@ serde_derive = "^1.0" serde_json = "^1.0" url = "^2.2" uuid = { version = "^1.0", features = ["serde"] } -reqwest = "~0.9" aws-sigv4 = "0.3.0" http = "0.2.5" secrecy = "0.8.0" +reqwest = "~0.9" [dev-dependencies] diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/README.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/README.md index c3f36db353..8520ca9d80 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/README.md +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/README.md @@ -25,6 +25,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**test_nullable_required_param**](docs/FakeApi.md#test_nullable_required_param) | **GET** /fake/user/{username} | To test nullable required parameters *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -37,6 +38,8 @@ Class | Method | HTTP request | Description *StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status *StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID *StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*TestingApi* | [**tests_file_response_get**](docs/TestingApi.md#tests_file_response_get) | **GET** /tests/fileResponse | Returns an image file +*TestingApi* | [**tests_type_testing_get**](docs/TestingApi.md#tests_type_testing_get) | **GET** /tests/typeTesting | Route to test the TypeTesting schema *UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user *UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array *UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array @@ -49,11 +52,16 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [ActionContainer](docs/ActionContainer.md) - [ApiResponse](docs/ApiResponse.md) + - [Baz](docs/Baz.md) - [Category](docs/Category.md) - [Order](docs/Order.md) - [Pet](docs/Pet.md) + - [PropertyTest](docs/PropertyTest.md) + - [Return](docs/Return.md) - [Tag](docs/Tag.md) + - [TypeTesting](docs/TypeTesting.md) - [User](docs/User.md) diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/ActionContainer.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/ActionContainer.md new file mode 100644 index 0000000000..8490ec5d82 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/ActionContainer.md @@ -0,0 +1,11 @@ +# ActionContainer + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**action** | [**crate::models::Baz**](Baz.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/ApiResponse.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/ApiResponse.md index 97128a87d9..b5125ba685 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/ApiResponse.md +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/ApiResponse.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | Option<**i32**> | | [optional] -**_type** | Option<**String**> | | [optional] +**r#type** | Option<**String**> | | [optional] **message** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/Baz.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/Baz.md new file mode 100644 index 0000000000..68c84b1b1b --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/Baz.md @@ -0,0 +1,10 @@ +# Baz + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/FakeApi.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/FakeApi.md new file mode 100644 index 0000000000..55bf612aa2 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/FakeApi.md @@ -0,0 +1,41 @@ +# \FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**test_nullable_required_param**](FakeApi.md#test_nullable_required_param) | **GET** /fake/user/{username} | To test nullable required parameters + + + +## test_nullable_required_param + +> test_nullable_required_param(username, dummy_required_nullable_param, uppercase) +To test nullable required parameters + + + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**username** | **String** | The name that needs to be fetched. Use user1 for testing. | [required] | +**dummy_required_nullable_param** | Option<**String**> | To test nullable required parameters | [required] | +**uppercase** | Option<**String**> | To test parameter names in upper case | | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/PropertyTest.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/PropertyTest.md new file mode 100644 index 0000000000..3f36c163de --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/PropertyTest.md @@ -0,0 +1,11 @@ +# PropertyTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | Option<[**uuid::Uuid**](uuid::Uuid.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/Return.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/Return.md new file mode 100644 index 0000000000..04710a019d --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/Return.md @@ -0,0 +1,13 @@ +# Return + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#match** | Option<**i32**> | | [optional] +**r#async** | Option<**bool**> | | [optional] +**param_super** | Option<**bool**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/TestingApi.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/TestingApi.md new file mode 100644 index 0000000000..ca0c06e06a --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/TestingApi.md @@ -0,0 +1,60 @@ +# \TestingApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**tests_file_response_get**](TestingApi.md#tests_file_response_get) | **GET** /tests/fileResponse | Returns an image file +[**tests_type_testing_get**](TestingApi.md#tests_type_testing_get) | **GET** /tests/typeTesting | Route to test the TypeTesting schema + + + +## tests_file_response_get + +> std::path::PathBuf tests_file_response_get() +Returns an image file + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**std::path::PathBuf**](std::path::PathBuf.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/jpeg + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## tests_type_testing_get + +> crate::models::TypeTesting tests_type_testing_get() +Route to test the TypeTesting schema + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**crate::models::TypeTesting**](TypeTesting.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/TypeTesting.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/TypeTesting.md new file mode 100644 index 0000000000..6beca6dbac --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/TypeTesting.md @@ -0,0 +1,17 @@ +# TypeTesting + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**int32** | **i32** | | +**int64** | **i64** | | +**float** | **f32** | | +**double** | **f64** | | +**string** | **String** | | +**boolean** | **bool** | | +**uuid** | [**uuid::Uuid**](uuid::Uuid.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/fake_api.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/fake_api.rs new file mode 100644 index 0000000000..13d9b7f851 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/fake_api.rs @@ -0,0 +1,62 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; + +use crate::apis::ResponseContent; +use super::{Error, configuration}; + + +/// struct for typed errors of method [`test_nullable_required_param`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestNullableRequiredParamError { + Status400(), + Status404(), + UnknownValue(serde_json::Value), +} + + +/// +pub fn test_nullable_required_param(configuration: &configuration::Configuration, username: &str, dummy_required_nullable_param: Option<&str>, uppercase: Option<&str>) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/fake/user/{username}", local_var_configuration.base_path, username=crate::apis::urlencode(username)); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + match dummy_required_nullable_param { + Some(local_var_param_value) => { local_var_req_builder = local_var_req_builder.header("dummy_required_nullable_param", local_var_param_value.to_string()); }, + None => { local_var_req_builder = local_var_req_builder.header("dummy_required_nullable_param", ""); }, + } + if let Some(local_var_param_value) = uppercase { + local_var_req_builder = local_var_req_builder.header("UPPERCASE", local_var_param_value.to_string()); + } + + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) + } +} + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/mod.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/mod.rs index caa4d7eb62..32344f36b0 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/mod.rs @@ -65,8 +65,10 @@ pub fn urlencode>(s: T) -> String { ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() } +pub mod fake_api; pub mod pet_api; pub mod store_api; +pub mod testing_api; pub mod user_api; pub mod configuration; diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/testing_api.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/testing_api.rs new file mode 100644 index 0000000000..fb84a57345 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/testing_api.rs @@ -0,0 +1,86 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; + +use crate::apis::ResponseContent; +use super::{Error, configuration}; + + +/// struct for typed errors of method [`tests_file_response_get`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestsFileResponseGetError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`tests_type_testing_get`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestsTypeTestingGetError { + UnknownValue(serde_json::Value), +} + + +pub fn tests_file_response_get(configuration: &configuration::Configuration, ) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/tests/fileResponse", local_var_configuration.base_path); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub fn tests_type_testing_get(configuration: &configuration::Configuration, ) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/tests/typeTesting", local_var_configuration.base_path); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) + } +} + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/action_container.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/action_container.rs new file mode 100644 index 0000000000..32d925eed3 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/action_container.rs @@ -0,0 +1,28 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct ActionContainer { + #[serde(rename = "action")] + pub action: Box, +} + +impl ActionContainer { + pub fn new(action: crate::models::Baz) -> ActionContainer { + ActionContainer { + action: Box::new(action), + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/api_response.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/api_response.rs index eff3b44e36..3ec5b4ae30 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/api_response.rs +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/api_response.rs @@ -17,7 +17,7 @@ pub struct ApiResponse { #[serde(rename = "code", skip_serializing_if = "Option::is_none")] pub code: Option, #[serde(rename = "type", skip_serializing_if = "Option::is_none")] - pub _type: Option, + pub r#type: Option, #[serde(rename = "message", skip_serializing_if = "Option::is_none")] pub message: Option, } @@ -27,7 +27,7 @@ impl ApiResponse { pub fn new() -> ApiResponse { ApiResponse { code: None, - _type: None, + r#type: None, message: None, } } diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/baz.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/baz.rs new file mode 100644 index 0000000000..94f8c5aa6a --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/baz.rs @@ -0,0 +1,43 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Baz : Test handling of empty variants + +/// Test handling of empty variants +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Baz { + #[serde(rename = "A")] + A, + #[serde(rename = "B")] + B, + #[serde(rename = "")] + Empty, + +} + +impl ToString for Baz { + fn to_string(&self) -> String { + match self { + Self::A => String::from("A"), + Self::B => String::from("B"), + Self::Empty => String::from(""), + } + } +} + +impl Default for Baz { + fn default() -> Baz { + Self::A + } +} + + + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/mod.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/mod.rs index 1baf2f7528..af4630c6a2 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/mod.rs @@ -1,12 +1,22 @@ +pub mod action_container; +pub use self::action_container::ActionContainer; pub mod api_response; pub use self::api_response::ApiResponse; +pub mod baz; +pub use self::baz::Baz; pub mod category; pub use self::category::Category; pub mod order; pub use self::order::Order; pub mod pet; pub use self::pet::Pet; +pub mod property_test; +pub use self::property_test::PropertyTest; +pub mod model_return; +pub use self::model_return::Return; pub mod tag; pub use self::tag::Tag; +pub mod type_testing; +pub use self::type_testing::TypeTesting; pub mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/model_return.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/model_return.rs new file mode 100644 index 0000000000..5deb3e5ee1 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/model_return.rs @@ -0,0 +1,36 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Return : Test using keywords + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Return { + #[serde(rename = "match", skip_serializing_if = "Option::is_none")] + pub r#match: Option, + #[serde(rename = "async", skip_serializing_if = "Option::is_none")] + pub r#async: Option, + #[serde(rename = "super", skip_serializing_if = "Option::is_none")] + pub param_super: Option, +} + +impl Return { + /// Test using keywords + pub fn new() -> Return { + Return { + r#match: None, + r#async: None, + param_super: None, + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/property_test.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/property_test.rs new file mode 100644 index 0000000000..1c3c4f3f3f --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/property_test.rs @@ -0,0 +1,30 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// PropertyTest : A model to test various formats, e.g. UUID + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct PropertyTest { + #[serde(rename = "uuid", skip_serializing_if = "Option::is_none")] + pub uuid: Option, +} + +impl PropertyTest { + /// A model to test various formats, e.g. UUID + pub fn new() -> PropertyTest { + PropertyTest { + uuid: None, + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/type_testing.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/type_testing.rs new file mode 100644 index 0000000000..dda67915df --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/type_testing.rs @@ -0,0 +1,48 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// TypeTesting : Test handling of different field data types + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TypeTesting { + #[serde(rename = "int32")] + pub int32: i32, + #[serde(rename = "int64")] + pub int64: i64, + #[serde(rename = "float")] + pub float: f32, + #[serde(rename = "double")] + pub double: f64, + #[serde(rename = "string")] + pub string: String, + #[serde(rename = "boolean")] + pub boolean: bool, + #[serde(rename = "uuid")] + pub uuid: uuid::Uuid, +} + +impl TypeTesting { + /// Test handling of different field data types + pub fn new(int32: i32, int64: i64, float: f32, double: f64, string: String, boolean: bool, uuid: uuid::Uuid) -> TypeTesting { + TypeTesting { + int32, + int64, + float, + double, + string, + boolean, + uuid, + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/FILES b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/FILES index 75bd989a45..6a0f473de4 100644 --- a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/FILES +++ b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/FILES @@ -2,15 +2,20 @@ .travis.yml Cargo.toml README.md +docs/ActionContainer.md docs/ApiResponse.md +docs/Baz.md docs/Category.md docs/FakeApi.md docs/Order.md docs/Pet.md docs/PetApi.md docs/PropertyTest.md +docs/Return.md docs/StoreApi.md docs/Tag.md +docs/TestingApi.md +docs/TypeTesting.md docs/User.md docs/UserApi.md git_push.sh @@ -19,13 +24,18 @@ src/apis/fake_api.rs src/apis/mod.rs src/apis/pet_api.rs src/apis/store_api.rs +src/apis/testing_api.rs src/apis/user_api.rs src/lib.rs +src/models/action_container.rs src/models/api_response.rs +src/models/baz.rs src/models/category.rs src/models/mod.rs +src/models/model_return.rs src/models/order.rs src/models/pet.rs src/models/property_test.rs src/models/tag.rs +src/models/type_testing.rs src/models/user.rs diff --git a/samples/client/petstore/rust/reqwest/petstore/README.md b/samples/client/petstore/rust/reqwest/petstore/README.md index af68b013a2..962cac9c97 100644 --- a/samples/client/petstore/rust/reqwest/petstore/README.md +++ b/samples/client/petstore/rust/reqwest/petstore/README.md @@ -38,6 +38,8 @@ Class | Method | HTTP request | Description *StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status *StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID *StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*TestingApi* | [**tests_file_response_get**](docs/TestingApi.md#tests_file_response_get) | **GET** /tests/fileResponse | Returns an image file +*TestingApi* | [**tests_type_testing_get**](docs/TestingApi.md#tests_type_testing_get) | **GET** /tests/typeTesting | Route to test the TypeTesting schema *UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user *UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array *UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array @@ -50,12 +52,16 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [ActionContainer](docs/ActionContainer.md) - [ApiResponse](docs/ApiResponse.md) + - [Baz](docs/Baz.md) - [Category](docs/Category.md) - [Order](docs/Order.md) - [Pet](docs/Pet.md) - [PropertyTest](docs/PropertyTest.md) + - [Return](docs/Return.md) - [Tag](docs/Tag.md) + - [TypeTesting](docs/TypeTesting.md) - [User](docs/User.md) diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/ActionContainer.md b/samples/client/petstore/rust/reqwest/petstore/docs/ActionContainer.md new file mode 100644 index 0000000000..8490ec5d82 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/docs/ActionContainer.md @@ -0,0 +1,11 @@ +# ActionContainer + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**action** | [**crate::models::Baz**](Baz.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/ApiResponse.md b/samples/client/petstore/rust/reqwest/petstore/docs/ApiResponse.md index 97128a87d9..b5125ba685 100644 --- a/samples/client/petstore/rust/reqwest/petstore/docs/ApiResponse.md +++ b/samples/client/petstore/rust/reqwest/petstore/docs/ApiResponse.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | Option<**i32**> | | [optional] -**_type** | Option<**String**> | | [optional] +**r#type** | Option<**String**> | | [optional] **message** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/Baz.md b/samples/client/petstore/rust/reqwest/petstore/docs/Baz.md new file mode 100644 index 0000000000..68c84b1b1b --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/docs/Baz.md @@ -0,0 +1,10 @@ +# Baz + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/DefaultApi.md b/samples/client/petstore/rust/reqwest/petstore/docs/DefaultApi.md new file mode 100644 index 0000000000..86b9c86e7c --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/docs/DefaultApi.md @@ -0,0 +1,60 @@ +# \DefaultApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**tests_file_response_get**](DefaultApi.md#tests_file_response_get) | **GET** /tests/fileResponse | Returns an image file +[**tests_type_testing_get**](DefaultApi.md#tests_type_testing_get) | **GET** /tests/typeTesting | Route to test the TypeTesting schema + + + +## tests_file_response_get + +> std::path::PathBuf tests_file_response_get() +Returns an image file + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**std::path::PathBuf**](std::path::PathBuf.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/jpeg + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## tests_type_testing_get + +> crate::models::TypeTesting tests_type_testing_get() +Route to test the TypeTesting schema + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**crate::models::TypeTesting**](TypeTesting.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/Return.md b/samples/client/petstore/rust/reqwest/petstore/docs/Return.md new file mode 100644 index 0000000000..04710a019d --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/docs/Return.md @@ -0,0 +1,13 @@ +# Return + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#match** | Option<**i32**> | | [optional] +**r#async** | Option<**bool**> | | [optional] +**param_super** | Option<**bool**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/TestingApi.md b/samples/client/petstore/rust/reqwest/petstore/docs/TestingApi.md new file mode 100644 index 0000000000..ca0c06e06a --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/docs/TestingApi.md @@ -0,0 +1,60 @@ +# \TestingApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**tests_file_response_get**](TestingApi.md#tests_file_response_get) | **GET** /tests/fileResponse | Returns an image file +[**tests_type_testing_get**](TestingApi.md#tests_type_testing_get) | **GET** /tests/typeTesting | Route to test the TypeTesting schema + + + +## tests_file_response_get + +> std::path::PathBuf tests_file_response_get() +Returns an image file + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**std::path::PathBuf**](std::path::PathBuf.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/jpeg + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## tests_type_testing_get + +> crate::models::TypeTesting tests_type_testing_get() +Route to test the TypeTesting schema + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**crate::models::TypeTesting**](TypeTesting.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/TypeTesting.md b/samples/client/petstore/rust/reqwest/petstore/docs/TypeTesting.md new file mode 100644 index 0000000000..6beca6dbac --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/docs/TypeTesting.md @@ -0,0 +1,17 @@ +# TypeTesting + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**int32** | **i32** | | +**int64** | **i64** | | +**float** | **f32** | | +**double** | **f64** | | +**string** | **String** | | +**boolean** | **bool** | | +**uuid** | [**uuid::Uuid**](uuid::Uuid.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore/src/apis/mod.rs b/samples/client/petstore/rust/reqwest/petstore/src/apis/mod.rs index 353447f625..34085cdedf 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/apis/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/apis/mod.rs @@ -64,6 +64,7 @@ pub fn urlencode>(s: T) -> String { pub mod fake_api; pub mod pet_api; pub mod store_api; +pub mod testing_api; pub mod user_api; pub mod configuration; diff --git a/samples/client/petstore/rust/reqwest/petstore/src/apis/testing_api.rs b/samples/client/petstore/rust/reqwest/petstore/src/apis/testing_api.rs new file mode 100644 index 0000000000..fb84a57345 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/src/apis/testing_api.rs @@ -0,0 +1,86 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; + +use crate::apis::ResponseContent; +use super::{Error, configuration}; + + +/// struct for typed errors of method [`tests_file_response_get`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestsFileResponseGetError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`tests_type_testing_get`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TestsTypeTestingGetError { + UnknownValue(serde_json::Value), +} + + +pub fn tests_file_response_get(configuration: &configuration::Configuration, ) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/tests/fileResponse", local_var_configuration.base_path); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub fn tests_type_testing_get(configuration: &configuration::Configuration, ) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/tests/typeTesting", local_var_configuration.base_path); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) + } +} + diff --git a/samples/client/petstore/rust/reqwest/petstore/src/models/action_container.rs b/samples/client/petstore/rust/reqwest/petstore/src/models/action_container.rs new file mode 100644 index 0000000000..32d925eed3 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/src/models/action_container.rs @@ -0,0 +1,28 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct ActionContainer { + #[serde(rename = "action")] + pub action: Box, +} + +impl ActionContainer { + pub fn new(action: crate::models::Baz) -> ActionContainer { + ActionContainer { + action: Box::new(action), + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore/src/models/api_response.rs b/samples/client/petstore/rust/reqwest/petstore/src/models/api_response.rs index eff3b44e36..3ec5b4ae30 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/models/api_response.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/models/api_response.rs @@ -17,7 +17,7 @@ pub struct ApiResponse { #[serde(rename = "code", skip_serializing_if = "Option::is_none")] pub code: Option, #[serde(rename = "type", skip_serializing_if = "Option::is_none")] - pub _type: Option, + pub r#type: Option, #[serde(rename = "message", skip_serializing_if = "Option::is_none")] pub message: Option, } @@ -27,7 +27,7 @@ impl ApiResponse { pub fn new() -> ApiResponse { ApiResponse { code: None, - _type: None, + r#type: None, message: None, } } diff --git a/samples/client/petstore/rust/reqwest/petstore/src/models/baz.rs b/samples/client/petstore/rust/reqwest/petstore/src/models/baz.rs new file mode 100644 index 0000000000..94f8c5aa6a --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/src/models/baz.rs @@ -0,0 +1,43 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Baz : Test handling of empty variants + +/// Test handling of empty variants +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Baz { + #[serde(rename = "A")] + A, + #[serde(rename = "B")] + B, + #[serde(rename = "")] + Empty, + +} + +impl ToString for Baz { + fn to_string(&self) -> String { + match self { + Self::A => String::from("A"), + Self::B => String::from("B"), + Self::Empty => String::from(""), + } + } +} + +impl Default for Baz { + fn default() -> Baz { + Self::A + } +} + + + + diff --git a/samples/client/petstore/rust/reqwest/petstore/src/models/mod.rs b/samples/client/petstore/rust/reqwest/petstore/src/models/mod.rs index 37334443da..af4630c6a2 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/models/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/models/mod.rs @@ -1,5 +1,9 @@ +pub mod action_container; +pub use self::action_container::ActionContainer; pub mod api_response; pub use self::api_response::ApiResponse; +pub mod baz; +pub use self::baz::Baz; pub mod category; pub use self::category::Category; pub mod order; @@ -8,7 +12,11 @@ pub mod pet; pub use self::pet::Pet; pub mod property_test; pub use self::property_test::PropertyTest; +pub mod model_return; +pub use self::model_return::Return; pub mod tag; pub use self::tag::Tag; +pub mod type_testing; +pub use self::type_testing::TypeTesting; pub mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/reqwest/petstore/src/models/model_return.rs b/samples/client/petstore/rust/reqwest/petstore/src/models/model_return.rs new file mode 100644 index 0000000000..5deb3e5ee1 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/src/models/model_return.rs @@ -0,0 +1,36 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// Return : Test using keywords + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Return { + #[serde(rename = "match", skip_serializing_if = "Option::is_none")] + pub r#match: Option, + #[serde(rename = "async", skip_serializing_if = "Option::is_none")] + pub r#async: Option, + #[serde(rename = "super", skip_serializing_if = "Option::is_none")] + pub param_super: Option, +} + +impl Return { + /// Test using keywords + pub fn new() -> Return { + Return { + r#match: None, + r#async: None, + param_super: None, + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore/src/models/type_testing.rs b/samples/client/petstore/rust/reqwest/petstore/src/models/type_testing.rs new file mode 100644 index 0000000000..dda67915df --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/src/models/type_testing.rs @@ -0,0 +1,48 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// TypeTesting : Test handling of different field data types + + + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TypeTesting { + #[serde(rename = "int32")] + pub int32: i32, + #[serde(rename = "int64")] + pub int64: i64, + #[serde(rename = "float")] + pub float: f32, + #[serde(rename = "double")] + pub double: f64, + #[serde(rename = "string")] + pub string: String, + #[serde(rename = "boolean")] + pub boolean: bool, + #[serde(rename = "uuid")] + pub uuid: uuid::Uuid, +} + +impl TypeTesting { + /// Test handling of different field data types + pub fn new(int32: i32, int64: i64, float: f32, double: f64, string: String, boolean: bool, uuid: uuid::Uuid) -> TypeTesting { + TypeTesting { + int32, + int64, + float, + double, + string, + boolean, + uuid, + } + } +} + + diff --git a/samples/client/petstore/rust/reqwest/petstore/tests/type_testing.rs b/samples/client/petstore/rust/reqwest/petstore/tests/type_testing.rs new file mode 100644 index 0000000000..e89187b170 --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/tests/type_testing.rs @@ -0,0 +1,19 @@ +extern crate petstore_reqwest; + +use petstore_reqwest::models::TypeTesting; + +#[test] +fn test_types() { + let tt = TypeTesting::default(); + assert_eq!(type_of(tt.int32), "i32"); + assert_eq!(type_of(tt.int64), "i64"); + assert_eq!(type_of(tt.float), "f32"); + assert_eq!(type_of(tt.double), "f64"); + assert_eq!(type_of(tt.string), "alloc::string::String"); + assert_eq!(type_of(tt.boolean), "bool"); + assert_eq!(type_of(tt.uuid), "uuid::Uuid"); +} + +fn type_of(_: T) -> &'static str { + std::any::type_name::() +} diff --git a/samples/client/petstore/rust/reqwest/rust-test/.gitignore b/samples/client/petstore/rust/reqwest/rust-test/.gitignore deleted file mode 100644 index 6aa106405a..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/target/ -**/*.rs.bk -Cargo.lock diff --git a/samples/client/petstore/rust/reqwest/rust-test/.openapi-generator/FILES b/samples/client/petstore/rust/reqwest/rust-test/.openapi-generator/FILES deleted file mode 100644 index 419360c647..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/.openapi-generator/FILES +++ /dev/null @@ -1,13 +0,0 @@ -.gitignore -.travis.yml -Cargo.toml -README.md -docs/DefaultApi.md -docs/TypeTesting.md -git_push.sh -src/apis/configuration.rs -src/apis/default_api.rs -src/apis/mod.rs -src/lib.rs -src/models/mod.rs -src/models/type_testing.rs diff --git a/samples/client/petstore/rust/reqwest/rust-test/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/rust-test/.openapi-generator/VERSION deleted file mode 100644 index d99e7162d0..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/rust-test/.travis.yml b/samples/client/petstore/rust/reqwest/rust-test/.travis.yml deleted file mode 100644 index 22761ba7ee..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: rust diff --git a/samples/client/petstore/rust/reqwest/rust-test/Cargo.toml b/samples/client/petstore/rust/reqwest/rust-test/Cargo.toml deleted file mode 100644 index 1c36153fd7..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "rust-test-reqwest" -version = "1.0.0" -authors = ["OpenAPI Generator team and contributors"] -edition = "2018" - -[dependencies] -serde = "^1.0" -serde_derive = "^1.0" -serde_json = "^1.0" -url = "1.5" -reqwest = "~0.9" - -[dev-dependencies] diff --git a/samples/client/petstore/rust/reqwest/rust-test/README.md b/samples/client/petstore/rust/reqwest/rust-test/README.md deleted file mode 100644 index 097d18b77d..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# Rust API client for rust-test-reqwest - -Special testing for the Rust client generator - -## Overview - -This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. - -- API version: 1.0.7 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.RustClientCodegen - -## Installation - -Put the package under your project folder and add the following to `Cargo.toml` under `[dependencies]`: - -``` - openapi = { path = "./generated" } -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://localhost* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*DefaultApi* | [**dummy_get**](docs/DefaultApi.md#dummy_get) | **get** /dummy | A dummy endpoint to make the spec valid. - - -## Documentation For Models - - - [TypeTesting](docs/TypeTesting.md) - - -To get access to the crate's generated documentation, use: - -``` -cargo doc --open -``` - -## Author - - - diff --git a/samples/client/petstore/rust/reqwest/rust-test/docs/DefaultApi.md b/samples/client/petstore/rust/reqwest/rust-test/docs/DefaultApi.md deleted file mode 100644 index ea01d010f0..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/docs/DefaultApi.md +++ /dev/null @@ -1,34 +0,0 @@ -# \DefaultApi - -All URIs are relative to *http://localhost* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**dummy_get**](DefaultApi.md#dummy_get) | **get** /dummy | A dummy endpoint to make the spec valid. - - - -## dummy_get - -> dummy_get() -A dummy endpoint to make the spec valid. - -### Parameters - -This endpoint does not need any parameter. - -### Return type - - (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/client/petstore/rust/reqwest/rust-test/docs/TypeTesting.md b/samples/client/petstore/rust/reqwest/rust-test/docs/TypeTesting.md deleted file mode 100644 index 7b05cee280..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/docs/TypeTesting.md +++ /dev/null @@ -1,16 +0,0 @@ -# TypeTesting - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | Option<**i32**> | | [optional] -**long** | Option<**i64**> | | [optional] -**number** | Option<**f32**> | | [optional] -**float** | Option<**f32**> | | [optional] -**double** | Option<**f64**> | | [optional] -**uuid** | Option<**String**> | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/client/petstore/rust/reqwest/rust-test/git_push.sh b/samples/client/petstore/rust/reqwest/rust-test/git_push.sh deleted file mode 100644 index ced3be2b0c..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/git_push.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - diff --git a/samples/client/petstore/rust/reqwest/rust-test/src/apis/client.rs b/samples/client/petstore/rust/reqwest/rust-test/src/apis/client.rs deleted file mode 100644 index b10fef0b55..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/src/apis/client.rs +++ /dev/null @@ -1,22 +0,0 @@ -use std::rc::Rc; - -use super::configuration::Configuration; - -pub struct APIClient { - default_api: Box, -} - -impl APIClient { - pub fn new(configuration: Configuration) -> APIClient { - let rc = Rc::new(configuration); - - APIClient { - default_api: Box::new(crate::apis::default_api::DefaultApiClient::new(rc.clone())), - } - } - - pub fn default_api(&self) -> &dyn crate::apis::default_api::DefaultApi{ - self.default_api.as_ref() - } - -} diff --git a/samples/client/petstore/rust/reqwest/rust-test/src/apis/configuration.rs b/samples/client/petstore/rust/reqwest/rust-test/src/apis/configuration.rs deleted file mode 100644 index 6aa6915560..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/src/apis/configuration.rs +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Rust client test spec - * - * Special testing for the Rust client generator - * - * The version of the OpenAPI document: 1.0.7 - * - * Generated by: https://openapi-generator.tech - */ - - -use reqwest; - -pub struct Configuration { - pub base_path: String, - pub user_agent: Option, - pub client: reqwest::Client, - pub basic_auth: Option, - pub oauth_access_token: Option, - pub bearer_access_token: Option, - pub api_key: Option, - // TODO: take an oauth2 token source, similar to the go one -} - -pub type BasicAuth = (String, Option); - -pub struct ApiKey { - pub prefix: Option, - pub key: String, -} - -impl Configuration { - pub fn new() -> Configuration { - Configuration::default() - } -} - -impl Default for Configuration { - fn default() -> Self { - Configuration { - base_path: "http://localhost".to_owned(), - user_agent: Some("OpenAPI-Generator/1.0.7/rust".to_owned()), - client: reqwest::Client::new(), - basic_auth: None, - oauth_access_token: None, - bearer_access_token: None, - api_key: None, - } - } -} diff --git a/samples/client/petstore/rust/reqwest/rust-test/src/apis/default_api.rs b/samples/client/petstore/rust/reqwest/rust-test/src/apis/default_api.rs deleted file mode 100644 index 098078bea8..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/src/apis/default_api.rs +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Rust client test spec - * - * Special testing for the Rust client generator - * - * The version of the OpenAPI document: 1.0.7 - * - * Generated by: https://openapi-generator.tech - */ - - -use reqwest; - -use crate::apis::ResponseContent; -use super::{Error, configuration}; - - -/// struct for typed errors of method `dummy_get` -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum DummyGetError { - UnknownValue(serde_json::Value), -} - - -pub fn dummy_get(configuration: &configuration::Configuration, ) -> Result<(), Error> { - - let client = &configuration.client; - - let uri_str = format!("{}/dummy", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); - - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); - } - - let req = req_builder.build()?; - let mut resp = client.execute(req)?; - - let status = resp.status(); - let content = resp.text()?; - - if status.is_success() { - Ok(()) - } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) - } -} - diff --git a/samples/client/petstore/rust/reqwest/rust-test/src/apis/mod.rs b/samples/client/petstore/rust/reqwest/rust-test/src/apis/mod.rs deleted file mode 100644 index aeab00a7bc..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/src/apis/mod.rs +++ /dev/null @@ -1,43 +0,0 @@ -use reqwest; -use serde_json; - -#[derive(Debug, Clone)] -pub struct ResponseContent { - pub status: reqwest::StatusCode, - pub content: String, - pub entity: Option, -} - -#[derive(Debug)] -pub enum Error { - Reqwest(reqwest::Error), - Serde(serde_json::Error), - Io(std::io::Error), - ResponseError(ResponseContent), -} - -impl From for Error { - fn from(e: reqwest::Error) -> Self { - Error::Reqwest(e) - } -} - -impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Serde(e) - } -} - -impl From for Error { - fn from(e: std::io::Error) -> Self { - Error::Io(e) - } -} - -pub fn urlencode>(s: T) -> String { - ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() -} - -pub mod default_api; - -pub mod configuration; diff --git a/samples/client/petstore/rust/reqwest/rust-test/src/lib.rs b/samples/client/petstore/rust/reqwest/rust-test/src/lib.rs deleted file mode 100644 index c1dd666f79..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/src/lib.rs +++ /dev/null @@ -1,10 +0,0 @@ -#[macro_use] -extern crate serde_derive; - -extern crate serde; -extern crate serde_json; -extern crate url; -extern crate reqwest; - -pub mod apis; -pub mod models; diff --git a/samples/client/petstore/rust/reqwest/rust-test/src/models/mod.rs b/samples/client/petstore/rust/reqwest/rust-test/src/models/mod.rs deleted file mode 100644 index 97887b5798..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/src/models/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod type_testing; -pub use self::type_testing::TypeTesting; diff --git a/samples/client/petstore/rust/reqwest/rust-test/src/models/type_testing.rs b/samples/client/petstore/rust/reqwest/rust-test/src/models/type_testing.rs deleted file mode 100644 index 530d1d1365..0000000000 --- a/samples/client/petstore/rust/reqwest/rust-test/src/models/type_testing.rs +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Rust client test spec - * - * Special testing for the Rust client generator - * - * The version of the OpenAPI document: 1.0.7 - * - * Generated by: https://openapi-generator.tech - */ - -/// TypeTesting : Test handling of differing types (see \\#3463) - - - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct TypeTesting { - #[serde(rename = "integer", skip_serializing_if = "Option::is_none")] - pub integer: Option, - #[serde(rename = "long", skip_serializing_if = "Option::is_none")] - pub long: Option, - #[serde(rename = "number", skip_serializing_if = "Option::is_none")] - pub number: Option, - #[serde(rename = "float", skip_serializing_if = "Option::is_none")] - pub float: Option, - #[serde(rename = "double", skip_serializing_if = "Option::is_none")] - pub double: Option, - #[serde(rename = "uuid", skip_serializing_if = "Option::is_none")] - pub uuid: Option, -} - -impl TypeTesting { - /// Test handling of differing types (see \\#3463) - pub fn new() -> TypeTesting { - TypeTesting { - integer: None, - long: None, - number: None, - float: None, - double: None, - uuid: None, - } - } -} - - diff --git a/samples/client/petstore/rust/src/models/inline_object.rs b/samples/client/petstore/rust/src/models/inline_object.rs deleted file mode 100644 index b1444810dc..0000000000 --- a/samples/client/petstore/rust/src/models/inline_object.rs +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - - - -#[derive(Debug, PartialEq, Serialize, Deserialize)] -pub struct InlineObject { - /// Updated name of the pet - #[serde(rename = "name", skip_serializing_if = "Option::is_none")] - pub name: Option, - /// Updated status of the pet - #[serde(rename = "status", skip_serializing_if = "Option::is_none")] - pub status: Option, -} - -impl InlineObject { - pub fn new() -> InlineObject { - InlineObject { - name: None, - status: None, - } - } -} - - diff --git a/samples/client/petstore/rust/src/models/inline_object_1.rs b/samples/client/petstore/rust/src/models/inline_object_1.rs deleted file mode 100644 index ee4c1b78ae..0000000000 --- a/samples/client/petstore/rust/src/models/inline_object_1.rs +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - - - -#[derive(Debug, PartialEq, Serialize, Deserialize)] -pub struct InlineObject1 { - /// Additional data to pass to server - #[serde(rename = "additionalMetadata", skip_serializing_if = "Option::is_none")] - pub additional_metadata: Option, - /// file to upload - #[serde(rename = "file", skip_serializing_if = "Option::is_none")] - pub file: Option, -} - -impl InlineObject1 { - pub fn new() -> InlineObject1 { - InlineObject1 { - additional_metadata: None, - file: None, - } - } -} - - diff --git a/samples/client/petstore/scala-sttp/.openapi-generator/FILES b/samples/client/petstore/scala-sttp/.openapi-generator/FILES index 93bed4b07d..dae7253b83 100644 --- a/samples/client/petstore/scala-sttp/.openapi-generator/FILES +++ b/samples/client/petstore/scala-sttp/.openapi-generator/FILES @@ -9,6 +9,7 @@ src/main/scala/org/openapitools/client/core/DateSerializers.scala src/main/scala/org/openapitools/client/core/JsonSupport.scala src/main/scala/org/openapitools/client/model/ApiResponse.scala src/main/scala/org/openapitools/client/model/Category.scala +src/main/scala/org/openapitools/client/model/EnumTest.scala src/main/scala/org/openapitools/client/model/Order.scala src/main/scala/org/openapitools/client/model/Pet.scala src/main/scala/org/openapitools/client/model/Tag.scala diff --git a/samples/client/petstore/scala-sttp/README.md b/samples/client/petstore/scala-sttp/README.md index 678cf67799..ea6aa409dc 100644 --- a/samples/client/petstore/scala-sttp/README.md +++ b/samples/client/petstore/scala-sttp/README.md @@ -91,6 +91,7 @@ Class | Method | HTTP request | Description - [ApiResponse](ApiResponse.md) - [Category](Category.md) + - [EnumTest](EnumTest.md) - [Order](Order.md) - [Pet](Pet.md) - [Tag](Tag.md) diff --git a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala index 3f6ad7782e..e4897aa241 100644 --- a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala +++ b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala @@ -35,7 +35,7 @@ class PetApi(baseUrl: String) { * @param pet Pet object that needs to be added to the store */ def addPet(pet: Pet -): Request[Either[ResponseException[String, Exception], Pet], Nothing] = +): Request[Either[ResponseException[String, Exception], Pet], Any] = basicRequest .method(Method.POST, uri"$baseUrl/pet") .contentType("application/json") @@ -52,7 +52,7 @@ class PetApi(baseUrl: String) { * @param apiKey */ def deletePet(petId: Long, apiKey: Option[String] = None -): Request[Either[ResponseException[String, Exception], Unit], Nothing] = +): Request[Either[ResponseException[String, Exception], Unit], Any] = basicRequest .method(Method.DELETE, uri"$baseUrl/pet/${petId}") .contentType("application/json") @@ -69,7 +69,7 @@ class PetApi(baseUrl: String) { * @param status Status values that need to be considered for filter */ def findPetsByStatus(status: Seq[String] -): Request[Either[ResponseException[String, Exception], Seq[Pet]], Nothing] = +): Request[Either[ResponseException[String, Exception], Seq[Pet]], Any] = basicRequest .method(Method.GET, uri"$baseUrl/pet/findByStatus?status=${ status }") .contentType("application/json") @@ -85,7 +85,7 @@ class PetApi(baseUrl: String) { * @param tags Tags to filter by */ def findPetsByTags(tags: Seq[String] -): Request[Either[ResponseException[String, Exception], Seq[Pet]], Nothing] = +): Request[Either[ResponseException[String, Exception], Seq[Pet]], Any] = basicRequest .method(Method.GET, uri"$baseUrl/pet/findByTags?tags=${ tags }") .contentType("application/json") @@ -105,7 +105,7 @@ class PetApi(baseUrl: String) { * @param petId ID of pet to return */ def getPetById(apiKey: String)(petId: Long -): Request[Either[ResponseException[String, Exception], Pet], Nothing] = +): Request[Either[ResponseException[String, Exception], Pet], Any] = basicRequest .method(Method.GET, uri"$baseUrl/pet/${petId}") .contentType("application/json") @@ -124,7 +124,7 @@ class PetApi(baseUrl: String) { * @param pet Pet object that needs to be added to the store */ def updatePet(pet: Pet -): Request[Either[ResponseException[String, Exception], Pet], Nothing] = +): Request[Either[ResponseException[String, Exception], Pet], Any] = basicRequest .method(Method.PUT, uri"$baseUrl/pet") .contentType("application/json") @@ -142,7 +142,7 @@ class PetApi(baseUrl: String) { * @param status Updated status of the pet */ def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None -): Request[Either[ResponseException[String, Exception], Unit], Nothing] = +): Request[Either[ResponseException[String, Exception], Unit], Any] = basicRequest .method(Method.POST, uri"$baseUrl/pet/${petId}") .contentType("application/x-www-form-urlencoded") @@ -163,7 +163,7 @@ class PetApi(baseUrl: String) { * @param file file to upload */ def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None -): Request[Either[ResponseException[String, Exception], ApiResponse], Nothing] = +): Request[Either[ResponseException[String, Exception], ApiResponse], Any] = basicRequest .method(Method.POST, uri"$baseUrl/pet/${petId}/uploadImage") .contentType("multipart/form-data") diff --git a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/StoreApi.scala b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/StoreApi.scala index d98fb71e18..e4db9be33b 100644 --- a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/StoreApi.scala +++ b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/StoreApi.scala @@ -33,7 +33,7 @@ class StoreApi(baseUrl: String) { * @param orderId ID of the order that needs to be deleted */ def deleteOrder(orderId: String -): Request[Either[ResponseException[String, Exception], Unit], Nothing] = +): Request[Either[ResponseException[String, Exception], Unit], Any] = basicRequest .method(Method.DELETE, uri"$baseUrl/store/order/${orderId}") .contentType("application/json") @@ -49,7 +49,7 @@ class StoreApi(baseUrl: String) { * api_key (apiKey) */ def getInventory(apiKey: String)( -): Request[Either[ResponseException[String, Exception], Map[String, Int]], Nothing] = +): Request[Either[ResponseException[String, Exception], Map[String, Int]], Any] = basicRequest .method(Method.GET, uri"$baseUrl/store/inventory") .contentType("application/json") @@ -67,7 +67,7 @@ class StoreApi(baseUrl: String) { * @param orderId ID of pet that needs to be fetched */ def getOrderById(orderId: Long -): Request[Either[ResponseException[String, Exception], Order], Nothing] = +): Request[Either[ResponseException[String, Exception], Order], Any] = basicRequest .method(Method.GET, uri"$baseUrl/store/order/${orderId}") .contentType("application/json") @@ -83,7 +83,7 @@ class StoreApi(baseUrl: String) { * @param order order placed for purchasing the pet */ def placeOrder(order: Order -): Request[Either[ResponseException[String, Exception], Order], Nothing] = +): Request[Either[ResponseException[String, Exception], Order], Any] = basicRequest .method(Method.POST, uri"$baseUrl/store/order") .contentType("application/json") diff --git a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/UserApi.scala b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/UserApi.scala index ee236f92f5..6f035512fc 100644 --- a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/UserApi.scala +++ b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/UserApi.scala @@ -36,13 +36,13 @@ class UserApi(baseUrl: String) { * @param user Created user object */ def createUser(apiKey: String)(user: User -): Request[Either[ResponseException[String, Exception], Unit], Nothing] = +): Request[Either[Either[String, String], Unit], Any] = basicRequest .method(Method.POST, uri"$baseUrl/user") .contentType("application/json") .header("api_key", apiKey) .body(user) - .response(asJson[Unit]) + .response(asEither(asString, ignore)) /** * @@ -56,13 +56,13 @@ class UserApi(baseUrl: String) { * @param user List of user object */ def createUsersWithArrayInput(apiKey: String)(user: Seq[User] -): Request[Either[ResponseException[String, Exception], Unit], Nothing] = +): Request[Either[Either[String, String], Unit], Any] = basicRequest .method(Method.POST, uri"$baseUrl/user/createWithArray") .contentType("application/json") .header("api_key", apiKey) .body(user) - .response(asJson[Unit]) + .response(asEither(asString, ignore)) /** * @@ -76,13 +76,13 @@ class UserApi(baseUrl: String) { * @param user List of user object */ def createUsersWithListInput(apiKey: String)(user: Seq[User] -): Request[Either[ResponseException[String, Exception], Unit], Nothing] = +): Request[Either[Either[String, String], Unit], Any] = basicRequest .method(Method.POST, uri"$baseUrl/user/createWithList") .contentType("application/json") .header("api_key", apiKey) .body(user) - .response(asJson[Unit]) + .response(asEither(asString, ignore)) /** * This can only be done by the logged in user. @@ -97,7 +97,7 @@ class UserApi(baseUrl: String) { * @param username The name that needs to be deleted */ def deleteUser(apiKey: String)(username: String -): Request[Either[ResponseException[String, Exception], Unit], Nothing] = +): Request[Either[ResponseException[String, Exception], Unit], Any] = basicRequest .method(Method.DELETE, uri"$baseUrl/user/${username}") .contentType("application/json") @@ -115,7 +115,7 @@ class UserApi(baseUrl: String) { * @param username The name that needs to be fetched. Use user1 for testing. */ def getUserByName(username: String -): Request[Either[ResponseException[String, Exception], User], Nothing] = +): Request[Either[ResponseException[String, Exception], User], Any] = basicRequest .method(Method.GET, uri"$baseUrl/user/${username}") .contentType("application/json") @@ -136,7 +136,7 @@ class UserApi(baseUrl: String) { * @param password The password for login in clear text */ def loginUser(username: String, password: String -): Request[Either[ResponseException[String, Exception], String], Nothing] = +): Request[Either[ResponseException[String, Exception], String], Any] = basicRequest .method(Method.GET, uri"$baseUrl/user/login?username=${ username }&password=${ password }") .contentType("application/json") @@ -152,12 +152,12 @@ class UserApi(baseUrl: String) { * api_key (apiKey) */ def logoutUser(apiKey: String)( -): Request[Either[ResponseException[String, Exception], Unit], Nothing] = +): Request[Either[Either[String, String], Unit], Any] = basicRequest .method(Method.GET, uri"$baseUrl/user/logout") .contentType("application/json") .header("api_key", apiKey) - .response(asJson[Unit]) + .response(asEither(asString, ignore)) /** * This can only be done by the logged in user. @@ -173,7 +173,7 @@ class UserApi(baseUrl: String) { * @param user Updated user object */ def updateUser(apiKey: String)(username: String, user: User -): Request[Either[ResponseException[String, Exception], Unit], Nothing] = +): Request[Either[ResponseException[String, Exception], Unit], Any] = basicRequest .method(Method.PUT, uri"$baseUrl/user/${username}") .contentType("application/json") diff --git a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/EnumTest.scala b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/EnumTest.scala new file mode 100644 index 0000000000..96fad75f85 --- /dev/null +++ b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/EnumTest.scala @@ -0,0 +1,38 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + + +case class EnumTest( + emails: Option[Seq[String]] = None, + search: Option[EnumTestEnums.Search] = None, + sortBy: Option[Seq[EnumTestEnums.SortBy]] = None +) + +object EnumTestEnums { + + type Search = Search.Value + type SortBy = SortBy.Value + object Search extends Enumeration { + val FirstName = Value("first_name") + val LastName = Value("last_name") + val Email = Value("email") + val FullName = Value("full_name") + } + + object SortBy extends Enumeration { + val FirstName = Value("first_name") + val LastName = Value("last_name") + val Email = Value("email") + } + +} diff --git a/samples/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java b/samples/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java index ed6da0f64b..8b6751f003 100644 --- a/samples/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java +++ b/samples/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "Default", description = "the Default API") +@RequestMapping("${openapi.apiDocumentation.base-path:}") public interface DefaultApi { /** @@ -53,7 +54,7 @@ public interface DefaultApi { ResponseEntity get( @ApiParam(value = "A date path parameter", required = true, defaultValue = "1972-01-01") @PathVariable("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date, @NotNull @ApiParam(value = "A date-time query parameter", required = true, defaultValue = "1973-12-19T03:39:57-08:00") @Valid @RequestParam(value = "dateTime", required = true, defaultValue = "1973-12-19T03:39:57-08:00") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime dateTime, - @ApiParam(value = "A date header parameter", required = true, defaultValue = "1974-01-01") @RequestHeader(value = "X-Order-Date", required = true, defaultValue = "1974-01-01") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate xOrderDate, + @NotNull @ApiParam(value = "A date header parameter", required = true, defaultValue = "1974-01-01") @RequestHeader(value = "X-Order-Date", required = true, defaultValue = "1974-01-01") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate xOrderDate, @ApiParam(value = "A date cookie parameter", defaultValue = "1975-01-01") @CookieValue(name = "loginDate", required = false, defaultValue = "1975-01-01") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate loginDate ); diff --git a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/PetApiClient.java b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/PetApiClient.java index ed3b67c359..f80fe4ddc6 100644 --- a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/PetApiClient.java +++ b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/PetApiClient.java @@ -3,6 +3,6 @@ package org.openapitools.api; import org.springframework.cloud.openfeign.FeignClient; import org.openapitools.configuration.ClientConfiguration; -@FeignClient(name="${pet.name:pet}", configuration = ClientConfiguration.class) +@FeignClient(name="${pet.name:pet}", url="${pet.url:http://petstore.swagger.io/v2}", configuration = ClientConfiguration.class) public interface PetApiClient extends PetApi { } diff --git a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/StoreApiClient.java b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/StoreApiClient.java index b49ab7583f..71d613a871 100644 --- a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/StoreApiClient.java +++ b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/StoreApiClient.java @@ -3,6 +3,6 @@ package org.openapitools.api; import org.springframework.cloud.openfeign.FeignClient; import org.openapitools.configuration.ClientConfiguration; -@FeignClient(name="${store.name:store}", configuration = ClientConfiguration.class) +@FeignClient(name="${store.name:store}", url="${store.url:http://petstore.swagger.io/v2}", configuration = ClientConfiguration.class) public interface StoreApiClient extends StoreApi { } diff --git a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/UserApiClient.java b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/UserApiClient.java index ecbe88a3b9..1db4598108 100644 --- a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/UserApiClient.java +++ b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/UserApiClient.java @@ -3,6 +3,6 @@ package org.openapitools.api; import org.springframework.cloud.openfeign.FeignClient; import org.openapitools.configuration.ClientConfiguration; -@FeignClient(name="${user.name:user}", configuration = ClientConfiguration.class) +@FeignClient(name="${user.name:user}", url="${user.url:http://petstore.swagger.io/v2}", configuration = ClientConfiguration.class) public interface UserApiClient extends UserApi { } diff --git a/samples/client/petstore/spring-stubs/.openapi-generator/FILES b/samples/client/petstore/spring-stubs/.openapi-generator/FILES index 8783779323..718ebc8e8c 100644 --- a/samples/client/petstore/spring-stubs/.openapi-generator/FILES +++ b/samples/client/petstore/spring-stubs/.openapi-generator/FILES @@ -1,3 +1,4 @@ +.openapi-generator-ignore README.md pom.xml src/main/java/org/openapitools/api/ApiUtil.java diff --git a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java index 28ea66ff7d..0e831f5b79 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java index 8d8168a147..570816e0ba 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java index 950357107c..32f54a60f0 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/FILES index 5a7c78dd6a..f1bd751eb1 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec @@ -57,6 +58,7 @@ PetstoreClient/Classes/OpenAPIs/Models/Tag.swift PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift PetstoreClient/Classes/OpenAPIs/Models/User.swift +PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift README.md diff --git a/samples/client/petstore/swift5/alamofireLibrary/.swiftformat b/samples/client/petstore/swift5/alamofireLibrary/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/alamofireLibrary/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index 4222b4cbae..7bb346ea9a 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,15 +28,17 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5e179af64e..44e76f4550 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -53,6 +53,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index d980142c6a..1dff5ad6a2 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -51,7 +51,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -93,7 +93,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -135,7 +135,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -177,7 +177,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -219,7 +219,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -254,7 +254,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -265,7 +265,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -309,7 +309,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -333,7 +333,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: OpenAPIDateWithoutTime? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask { return testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result in switch result { case .success: @@ -367,7 +367,7 @@ open class FakeAPI { - parameter callback: (form) None (optional) - returns: RequestBuilder */ - open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { + open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: OpenAPIDateWithoutTime? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ @@ -400,7 +400,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -523,10 +523,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -539,7 +539,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -585,10 +585,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -600,7 +600,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -643,7 +643,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -694,6 +694,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 34e8c9c7f2..e4290335f9 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -56,6 +56,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 254930e777..93671ed852 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -34,6 +34,9 @@ open class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -55,7 +58,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -106,7 +109,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -154,7 +157,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -165,7 +168,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -206,7 +209,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -217,7 +220,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -267,7 +270,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -313,7 +316,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -372,7 +375,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -431,7 +434,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -490,6 +493,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index c111e83013..c8416218db 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -56,7 +56,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -101,7 +101,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -148,7 +148,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -191,6 +191,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 5e01a4a7c3..5072c1f1da 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -53,7 +53,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -96,7 +96,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -139,7 +139,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -186,7 +186,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -232,7 +232,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -270,8 +270,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -282,7 +282,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -323,7 +323,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -372,6 +372,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index 3b9580adfb..bc4759a803 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -21,8 +21,8 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { private var managerStore = SynchronizedDictionary() open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -103,21 +103,25 @@ open class AlamofireRequestBuilder: RequestBuilder { let upload = manager.upload(multipartFormData: { mpForm in for (k, v) in self.parameters! { - switch v { - case let fileURL as URL: - if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { - mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) - } else { - mpForm.append(fileURL, withName: k) + for v in (v as? Array ?? [v]) { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } else { + mpForm.append(fileURL, withName: k) + } + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + case let data as Data: + mpForm.append(data, withName: k) + case let uuid as UUID: + mpForm.append(uuid.uuidString.data(using: String.Encoding.utf8)!, withName: k) + default: + fatalError("Unprocessable value \(v) with key \(k)") } - case let string as String: - mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) - case let number as NSNumber: - mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) - case let data as Data: - mpForm.append(data, withName: k) - default: - fatalError("Unprocessable value \(v) with key \(k)") } } }, to: URLString, method: xMethod, headers: nil) @@ -161,11 +165,13 @@ open class AlamofireRequestBuilder: RequestBuilder { managerStore[managerId] = nil } - let validatedRequest = request.validate() + let validatedRequest = request.validate(statusCode: Configuration.successfulStatusCodeRange) switch T.self { case is Void.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { voidResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { voidResponse in cleanupRequest() switch voidResponse.result { @@ -253,11 +259,13 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild managerStore[managerId] = nil } - let validatedRequest = request.validate() + let validatedRequest = request.validate(statusCode: Configuration.successfulStatusCodeRange) switch T.self { case is String.Type: - validatedRequest.responseString(queue: apiResponseQueue, completionHandler: { stringResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.stringResponseSerializer, + completionHandler: { stringResponse in cleanupRequest() switch stringResponse.result { @@ -269,7 +277,9 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild }) case is URL.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { dataResponse in cleanupRequest() do { @@ -315,7 +325,9 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild return }) case is Void.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { voidResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { voidResponse in cleanupRequest() switch voidResponse.result { @@ -327,7 +339,9 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild }) case is Data.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { dataResponse in cleanupRequest() switch dataResponse.result { @@ -339,7 +353,9 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild }) default: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { dataResponse in cleanupRequest() if case let .failure(error) = dataResponse.result { diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..def40552f7 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -5,6 +5,7 @@ // import Foundation +import Alamofire open class Configuration { @@ -12,4 +13,32 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 + /// ResponseSerializer that will be used by the generator for `Data` responses + /// + /// If unchanged, Alamofires default `DataResponseSerializer` will be used. + public static var dataResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(DataResponseSerializer()) + /// ResponseSerializer that will be used by the generator for `String` responses + /// + /// If unchanged, Alamofires default `StringResponseSerializer` will be used. + public static var stringResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(StringResponseSerializer()) } + +/// Type-erased ResponseSerializer +/// +/// This is needed in order to use `ResponseSerializer` as a Type in `Configuration`. Obsolete with `any` keyword in Swift >= 5.7 +public struct AnyResponseSerializer: ResponseSerializer { + + let _serialize: (URLRequest?, HTTPURLResponse?, Data?, Error?) throws -> T + + public init(_ delegatee: V) where V.SerializedObject == T { + _serialize = delegatee.serialize + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T { + try _serialize(request, response, data, error) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index f950dbd27f..28189fb486 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -107,13 +107,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var request: Request? internal func set(request: Request) { + lock.lock() + defer { lock.unlock() } self.request = request } public func cancel() { + lock.lock() + defer { lock.unlock() } request?.cancel() request = nil } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 0a32995548..4986408b7c 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -21,12 +21,12 @@ public struct FormatTest: Codable, JSONEncodable, Hashable { public var string: String? public var byte: Data public var binary: URL? - public var date: Date + public var date: OpenAPIDateWithoutTime public var dateTime: Date? public var uuid: UUID? public var password: String - public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { + public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: OpenAPIDateWithoutTime, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { self.integer = integer self.int32 = int32 self.int64 = int64 diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift new file mode 100644 index 0000000000..93d52871dd --- /dev/null +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift @@ -0,0 +1,69 @@ +// OpenAPIDateWithoutTime.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +/// Represents a date without time information (e.g. a birthday) for transmission from and to a REST API +/// +/// This type is used as a representation for openapi specs `date` format which does not contain +/// time information as opposed to the `date-time` format. Although it internally uses `Date` for +/// (de-)serialization as well the generator needs to be able to distinguish between the two formats. +/// - note: As `Date` is agnostic to timezones (and calendars), timezone information is needed to be able to add +/// an appropriate padding in order to transform to GMT+0 which is the assumed timezone in ISO 8601. +/// When decoding, GMT+0 can be assumed (again: ISO8601) so there is no padding necessary and wrappedDate +/// can be used safely. +public struct OpenAPIDateWithoutTime: Codable, Hashable, Equatable { + public let wrappedDate: Date + public let timezone: TimeZone + + public enum CodingKeys: CodingKey, CaseIterable { + case wrappedDate + case timezone + } + + /// On decoding ISO8601 timezone is assumed + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + self.wrappedDate = try container.decode(Date.self) + self.timezone = OpenISO8601DateFormatter.withoutTime.timeZone + } + + /// Convenience Initializer which is useful when dealing with optionals a lot like e.g. in API mappers + public init?(wrappedDate: Date?, timezone: TimeZone = .current) { + guard let wrappedDate = wrappedDate else { + return nil + } + + self.init(wrappedDate: wrappedDate, timezone: timezone) + } + + /// Designated Initializer for `OpenAPIDateWithoutTime` + /// + /// Since usually `Date`s without time components - as e.g. birthdays - are created Calendar- and timezone-aware + // it is important to also provide a timezone so that the generator is able to normalize the supplied Date to ISO8601 (GMT+0) + public init(wrappedDate: Date, timezone: TimeZone) { + self.wrappedDate = wrappedDate + self.timezone = timezone + } + + /// Only the wrappedDate is encoded normalized to GMT+0 with an offset derived from the supplied Timezone + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(OpenISO8601DateFormatter.withoutTime.string(from: normalizedWrappedDate())) + } + + /// Normalizes the wrappedDate to GMT+0 according to the supplied timezone + fileprivate func normalizedWrappedDate() -> Date { + return wrappedDate.addingTimeInterval( + Double(timezone.secondsFromGMT(for: wrappedDate))) + } +} + +extension OpenAPIDateWithoutTime: JSONEncodable { + func encodeToJSON() -> Any { + return OpenISO8601DateFormatter.withoutTime.string(from: self.normalizedWrappedDate()) + } +} \ No newline at end of file diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift index 49f2e3210a..16a1dcd842 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift @@ -22,21 +22,29 @@ class BearerRequestBuilderFactory: RequestBuilderFactory { class BearerRequestBuilder: AlamofireRequestBuilder { override func createAlamofireSession(interceptor: RequestInterceptor? = nil) -> Session { - let bearerTokenHandler = BearerTokenHandler() + if self.requiresAuthentication { - let alamofireSession = super.createAlamofireSession(interceptor: bearerTokenHandler) - - return alamofireSession + let bearerTokenHandler = BearerTokenHandler() + let alamofireSession = super.createAlamofireSession(interceptor: bearerTokenHandler) + + return alamofireSession + } else { + return super.createAlamofireSession(interceptor: nil) + } } } class BearerDecodableRequestBuilder: AlamofireDecodableRequestBuilder { override func createAlamofireSession(interceptor: RequestInterceptor? = nil) -> Session { - let bearerTokenHandler = BearerTokenHandler() - - let alamofireSession = super.createAlamofireSession(interceptor: bearerTokenHandler) - - return alamofireSession + if self.requiresAuthentication { + + let bearerTokenHandler = BearerTokenHandler() + let alamofireSession = super.createAlamofireSession(interceptor: bearerTokenHandler) + + return alamofireSession + } else { + return super.createAlamofireSession(interceptor: nil) + } } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md index 69b1faa2b9..1d64d2d2c4 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md @@ -364,7 +364,7 @@ No authorization required # **testEndpointParameters** ```swift - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: OpenAPIDateWithoutTime? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -386,7 +386,7 @@ let int64 = 987 // Int64 | None (optional) let float = 987 // Float | None (optional) let string = "string_example" // String | None (optional) let binary = URL(string: "https://example.com")! // URL | None (optional) -let date = Date() // Date | None (optional) +let date = 987 // OpenAPIDateWithoutTime | None (optional) let dateTime = Date() // Date | None (optional) let password = "password_example" // String | None (optional) let callback = "callback_example" // String | None (optional) @@ -418,7 +418,7 @@ Name | Type | Description | Notes **float** | **Float** | None | [optional] **string** | **String** | None | [optional] **binary** | **URL** | None | [optional] - **date** | **Date** | None | [optional] + **date** | **OpenAPIDateWithoutTime** | None | [optional] **dateTime** | **Date** | None | [optional] **password** | **String** | None | [optional] **callback** | **String** | None | [optional] diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/FormatTest.md b/samples/client/petstore/swift5/alamofireLibrary/docs/FormatTest.md index f74d94f6c4..590974734b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/FormatTest.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/FormatTest.md @@ -12,7 +12,7 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **byte** | **Data** | | **binary** | **URL** | | [optional] -**date** | **Date** | | +**date** | **OpenAPIDateWithoutTime** | | **dateTime** | **Date** | | [optional] **uuid** | **UUID** | | [optional] **password** | **String** | | diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md index 7dc73a9890..786640dabb 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/asyncAwaitLibrary/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/.swiftformat b/samples/client/petstore/swift5/asyncAwaitLibrary/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5a78f471fa..367592cea4 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -20,7 +20,8 @@ open class AnotherFakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func call123testSpecialTags(body: Client) async throws -> Client { - var requestTask: RequestTask? + let requestBuilder = call123testSpecialTagsWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -29,7 +30,7 @@ open class AnotherFakeAPI { return } - requestTask = call123testSpecialTagsWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -38,8 +39,8 @@ open class AnotherFakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -65,6 +66,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index e953c1a269..3e34a66f7d 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -19,7 +19,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func fakeOuterBooleanSerialize(body: Bool? = nil) async throws -> Bool { - var requestTask: RequestTask? + let requestBuilder = fakeOuterBooleanSerializeWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -28,7 +29,7 @@ open class FakeAPI { return } - requestTask = fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -37,8 +38,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -63,7 +64,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -73,7 +74,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil) async throws -> OuterComposite { - var requestTask: RequestTask? + let requestBuilder = fakeOuterCompositeSerializeWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -82,7 +84,7 @@ open class FakeAPI { return } - requestTask = fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -91,8 +93,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -117,7 +119,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -127,7 +129,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func fakeOuterNumberSerialize(body: Double? = nil) async throws -> Double { - var requestTask: RequestTask? + let requestBuilder = fakeOuterNumberSerializeWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -136,7 +139,7 @@ open class FakeAPI { return } - requestTask = fakeOuterNumberSerializeWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -145,8 +148,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -171,7 +174,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -181,7 +184,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func fakeOuterStringSerialize(body: String? = nil) async throws -> String { - var requestTask: RequestTask? + let requestBuilder = fakeOuterStringSerializeWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -190,7 +194,7 @@ open class FakeAPI { return } - requestTask = fakeOuterStringSerializeWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -199,8 +203,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -225,7 +229,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -235,7 +239,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func testBodyWithFileSchema(body: FileSchemaTestClass) async throws { - var requestTask: RequestTask? + let requestBuilder = testBodyWithFileSchemaWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -244,7 +249,7 @@ open class FakeAPI { return } - requestTask = testBodyWithFileSchemaWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -253,8 +258,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -279,7 +284,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -290,7 +295,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func testBodyWithQueryParams(query: String, body: User) async throws { - var requestTask: RequestTask? + let requestBuilder = testBodyWithQueryParamsWithRequestBuilder(query: query, body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -299,7 +305,7 @@ open class FakeAPI { return } - requestTask = testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -308,8 +314,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -326,7 +332,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -337,7 +343,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -348,7 +354,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func testClientModel(body: Client) async throws -> Client { - var requestTask: RequestTask? + let requestBuilder = testClientModelWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -357,7 +364,7 @@ open class FakeAPI { return } - requestTask = testClientModelWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -366,8 +373,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -393,7 +400,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -417,7 +424,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) async throws { - var requestTask: RequestTask? + let requestBuilder = testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -426,7 +434,7 @@ open class FakeAPI { return } - requestTask = testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -435,8 +443,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -496,7 +504,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -581,7 +589,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) async throws { - var requestTask: RequestTask? + let requestBuilder = testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -590,7 +599,7 @@ open class FakeAPI { return } - requestTask = testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -599,8 +608,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -631,10 +640,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -647,7 +656,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -663,7 +672,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) async throws { - var requestTask: RequestTask? + let requestBuilder = testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -672,7 +682,7 @@ open class FakeAPI { return } - requestTask = testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -681,8 +691,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -705,10 +715,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -720,7 +730,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -731,7 +741,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func testInlineAdditionalProperties(param: [String: String]) async throws { - var requestTask: RequestTask? + let requestBuilder = testInlineAdditionalPropertiesWithRequestBuilder(param: param) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -740,7 +751,7 @@ open class FakeAPI { return } - requestTask = testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -749,8 +760,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -775,7 +786,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -787,7 +798,8 @@ open class FakeAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func testJsonFormData(param: String, param2: String) async throws { - var requestTask: RequestTask? + let requestBuilder = testJsonFormDataWithRequestBuilder(param: param, param2: param2) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -796,7 +808,7 @@ open class FakeAPI { return } - requestTask = testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -805,8 +817,8 @@ open class FakeAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -838,6 +850,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index c533eaa980..d6a2f24469 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -20,7 +20,8 @@ open class FakeClassnameTags123API { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func testClassname(body: Client) async throws -> Client { - var requestTask: RequestTask? + let requestBuilder = testClassnameWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -29,7 +30,7 @@ open class FakeClassnameTags123API { return } - requestTask = testClassnameWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -38,8 +39,8 @@ open class FakeClassnameTags123API { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -68,6 +69,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index f033e47594..9c86f63bd8 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -20,7 +20,8 @@ open class PetAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func addPet(body: Pet) async throws { - var requestTask: RequestTask? + let requestBuilder = addPetWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -29,7 +30,7 @@ open class PetAPI { return } - requestTask = addPetWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -38,14 +39,17 @@ open class PetAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -67,7 +71,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -79,7 +83,8 @@ open class PetAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func deletePet(petId: Int64, apiKey: String? = nil) async throws { - var requestTask: RequestTask? + let requestBuilder = deletePetWithRequestBuilder(petId: petId, apiKey: apiKey) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -88,7 +93,7 @@ open class PetAPI { return } - requestTask = deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -97,8 +102,8 @@ open class PetAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -130,7 +135,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -150,7 +155,8 @@ open class PetAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func findPetsByStatus(status: [Status_findPetsByStatus]) async throws -> [Pet] { - var requestTask: RequestTask? + let requestBuilder = findPetsByStatusWithRequestBuilder(status: status) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -159,7 +165,7 @@ open class PetAPI { return } - requestTask = findPetsByStatusWithRequestBuilder(status: status).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -168,8 +174,8 @@ open class PetAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -190,7 +196,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -201,7 +207,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -213,7 +219,8 @@ open class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func findPetsByTags(tags: [String]) async throws -> [Pet] { - var requestTask: RequestTask? + let requestBuilder = findPetsByTagsWithRequestBuilder(tags: tags) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -222,7 +229,7 @@ open class PetAPI { return } - requestTask = findPetsByTagsWithRequestBuilder(tags: tags).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -231,8 +238,8 @@ open class PetAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -254,7 +261,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -265,7 +272,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -276,7 +283,8 @@ open class PetAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func getPetById(petId: Int64) async throws -> Pet { - var requestTask: RequestTask? + let requestBuilder = getPetByIdWithRequestBuilder(petId: petId) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -285,7 +293,7 @@ open class PetAPI { return } - requestTask = getPetByIdWithRequestBuilder(petId: petId).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -294,8 +302,8 @@ open class PetAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -327,7 +335,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -338,7 +346,8 @@ open class PetAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func updatePet(body: Pet) async throws { - var requestTask: RequestTask? + let requestBuilder = updatePetWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -347,7 +356,7 @@ open class PetAPI { return } - requestTask = updatePetWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -356,8 +365,8 @@ open class PetAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -385,7 +394,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -398,7 +407,8 @@ open class PetAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil) async throws { - var requestTask: RequestTask? + let requestBuilder = updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -407,7 +417,7 @@ open class PetAPI { return } - requestTask = updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -416,8 +426,8 @@ open class PetAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -456,7 +466,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -469,7 +479,8 @@ open class PetAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) async throws -> ApiResponse { - var requestTask: RequestTask? + let requestBuilder = uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -478,7 +489,7 @@ open class PetAPI { return } - requestTask = uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -487,8 +498,8 @@ open class PetAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -527,7 +538,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -540,7 +551,8 @@ open class PetAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) async throws -> ApiResponse { - var requestTask: RequestTask? + let requestBuilder = uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -549,7 +561,7 @@ open class PetAPI { return } - requestTask = uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -558,8 +570,8 @@ open class PetAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -598,6 +610,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index bc76c7a2d7..503083b5df 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -20,7 +20,8 @@ open class StoreAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func deleteOrder(orderId: String) async throws { - var requestTask: RequestTask? + let requestBuilder = deleteOrderWithRequestBuilder(orderId: orderId) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -29,7 +30,7 @@ open class StoreAPI { return } - requestTask = deleteOrderWithRequestBuilder(orderId: orderId).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -38,8 +39,8 @@ open class StoreAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -68,7 +69,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -78,7 +79,8 @@ open class StoreAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func getInventory() async throws -> [String: Int] { - var requestTask: RequestTask? + let requestBuilder = getInventoryWithRequestBuilder() + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -87,7 +89,7 @@ open class StoreAPI { return } - requestTask = getInventoryWithRequestBuilder().execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -96,8 +98,8 @@ open class StoreAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -125,7 +127,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -136,7 +138,8 @@ open class StoreAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func getOrderById(orderId: Int64) async throws -> Order { - var requestTask: RequestTask? + let requestBuilder = getOrderByIdWithRequestBuilder(orderId: orderId) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -145,7 +148,7 @@ open class StoreAPI { return } - requestTask = getOrderByIdWithRequestBuilder(orderId: orderId).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -154,8 +157,8 @@ open class StoreAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -184,7 +187,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -195,7 +198,8 @@ open class StoreAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func placeOrder(body: Order) async throws -> Order { - var requestTask: RequestTask? + let requestBuilder = placeOrderWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -204,7 +208,7 @@ open class StoreAPI { return } - requestTask = placeOrderWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -213,8 +217,8 @@ open class StoreAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -239,6 +243,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 0a2dab3d82..19c707b3ee 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -20,7 +20,8 @@ open class UserAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func createUser(body: User) async throws { - var requestTask: RequestTask? + let requestBuilder = createUserWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -29,7 +30,7 @@ open class UserAPI { return } - requestTask = createUserWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -38,8 +39,8 @@ open class UserAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -65,7 +66,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -76,7 +77,8 @@ open class UserAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func createUsersWithArrayInput(body: [User]) async throws { - var requestTask: RequestTask? + let requestBuilder = createUsersWithArrayInputWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -85,7 +87,7 @@ open class UserAPI { return } - requestTask = createUsersWithArrayInputWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -94,8 +96,8 @@ open class UserAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -120,7 +122,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -131,7 +133,8 @@ open class UserAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func createUsersWithListInput(body: [User]) async throws { - var requestTask: RequestTask? + let requestBuilder = createUsersWithListInputWithRequestBuilder(body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -140,7 +143,7 @@ open class UserAPI { return } - requestTask = createUsersWithListInputWithRequestBuilder(body: body).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -149,8 +152,8 @@ open class UserAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -175,7 +178,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -186,7 +189,8 @@ open class UserAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func deleteUser(username: String) async throws { - var requestTask: RequestTask? + let requestBuilder = deleteUserWithRequestBuilder(username: username) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -195,7 +199,7 @@ open class UserAPI { return } - requestTask = deleteUserWithRequestBuilder(username: username).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -204,8 +208,8 @@ open class UserAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -234,7 +238,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -245,7 +249,8 @@ open class UserAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func getUserByName(username: String) async throws -> User { - var requestTask: RequestTask? + let requestBuilder = getUserByNameWithRequestBuilder(username: username) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -254,7 +259,7 @@ open class UserAPI { return } - requestTask = getUserByNameWithRequestBuilder(username: username).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -263,8 +268,8 @@ open class UserAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -292,7 +297,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -304,7 +309,8 @@ open class UserAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func loginUser(username: String, password: String) async throws -> String { - var requestTask: RequestTask? + let requestBuilder = loginUserWithRequestBuilder(username: username, password: password) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -313,7 +319,7 @@ open class UserAPI { return } - requestTask = loginUserWithRequestBuilder(username: username, password: password).execute { result in + requestBuilder.execute { result in switch result { case let .success(response): continuation.resume(returning: response.body) @@ -322,8 +328,8 @@ open class UserAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -342,8 +348,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -354,7 +360,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -364,7 +370,8 @@ open class UserAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func logoutUser() async throws { - var requestTask: RequestTask? + let requestBuilder = logoutUserWithRequestBuilder() + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -373,7 +380,7 @@ open class UserAPI { return } - requestTask = logoutUserWithRequestBuilder().execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -382,8 +389,8 @@ open class UserAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -407,7 +414,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -419,7 +426,8 @@ open class UserAPI { */ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) open class func updateUser(username: String, body: User) async throws { - var requestTask: RequestTask? + let requestBuilder = updateUserWithRequestBuilder(username: username, body: body) + let requestTask = requestBuilder.requestTask return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in @@ -428,7 +436,7 @@ open class UserAPI { return } - requestTask = updateUserWithRequestBuilder(username: username, body: body).execute { result in + requestBuilder.execute { result in switch result { case .success: continuation.resume(returning: ()) @@ -437,8 +445,8 @@ open class UserAPI { } } } - } onCancel: { [requestTask] in - requestTask?.cancel() + } onCancel: { + requestTask.cancel() } } @@ -468,6 +476,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..eb916234ab 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -105,14 +105,19 @@ open class Response { } } -public final class RequestTask { +public final class RequestTask: @unchecked Sendable { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md index 7dc73a9890..786640dabb 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/combineLibrary/.swiftformat b/samples/client/petstore/swift5/combineLibrary/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/combineLibrary/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 892be60e14..f77dd2e72f 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -64,6 +64,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 6920a9c53b..66cd804674 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -62,7 +62,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -112,7 +112,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -162,7 +162,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -212,7 +212,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -262,7 +262,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -305,7 +305,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -316,7 +316,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -368,7 +368,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -467,7 +467,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -598,10 +598,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -614,7 +614,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -668,10 +668,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -683,7 +683,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -734,7 +734,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -793,6 +793,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index adf4f16985..a918464fd5 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -67,6 +67,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index a6d43fb28c..a9033a06cc 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -45,6 +45,9 @@ open class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -66,7 +69,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -125,7 +128,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -181,7 +184,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -192,7 +195,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -241,7 +244,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -252,7 +255,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -310,7 +313,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -364,7 +367,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -431,7 +434,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -498,7 +501,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -565,6 +568,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 8d26a9f6ce..0b1e198919 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -67,7 +67,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -120,7 +120,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -175,7 +175,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -226,6 +226,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 82bd26b3f0..8401cc9f26 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -64,7 +64,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -115,7 +115,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -166,7 +166,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -221,7 +221,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -275,7 +275,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -321,8 +321,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -333,7 +333,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -382,7 +382,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -439,6 +439,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md index 7dc73a9890..786640dabb 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/default/.openapi-generator/FILES b/samples/client/petstore/swift5/default/.openapi-generator/FILES index 205dadc060..0cdf0c7c7c 100644 --- a/samples/client/petstore/swift5/default/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/default/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/default/.swiftformat b/samples/client/petstore/swift5/default/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/default/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5e179af64e..44e76f4550 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -53,6 +53,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 78c64f76f1..f28ddd9d12 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -53,7 +53,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -95,7 +95,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -137,7 +137,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -179,7 +179,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -221,7 +221,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -263,7 +263,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -298,7 +298,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -309,7 +309,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -353,7 +353,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -444,7 +444,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -567,10 +567,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -583,7 +583,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -629,10 +629,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -644,7 +644,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -687,7 +687,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -738,7 +738,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -780,11 +780,11 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "pipe": pipe.encodeToJSON(), - "ioutil": ioutil.encodeToJSON(), - "http": http.encodeToJSON(), - "url": url.encodeToJSON(), - "context": context.encodeToJSON(), + "pipe": (wrappedValue: pipe.encodeToJSON(), isExplode: false), + "ioutil": (wrappedValue: ioutil.encodeToJSON(), isExplode: false), + "http": (wrappedValue: http.encodeToJSON(), isExplode: false), + "url": (wrappedValue: url.encodeToJSON(), isExplode: false), + "context": (wrappedValue: context.encodeToJSON(), isExplode: true), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -795,6 +795,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 34e8c9c7f2..e4290335f9 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -56,6 +56,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 6d37af7299..ea6d473539 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -55,7 +55,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -106,7 +106,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -154,7 +154,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -165,7 +165,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -206,7 +206,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -217,7 +217,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -267,7 +267,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -313,7 +313,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -372,7 +372,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -431,7 +431,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -490,6 +490,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index c111e83013..c8416218db 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -56,7 +56,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -101,7 +101,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -148,7 +148,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -191,6 +191,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 5e01a4a7c3..5072c1f1da 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -53,7 +53,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -96,7 +96,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -139,7 +139,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -186,7 +186,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -232,7 +232,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -270,8 +270,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -282,7 +282,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -323,7 +323,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -372,6 +372,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/deprecated/.openapi-generator/FILES b/samples/client/petstore/swift5/deprecated/.openapi-generator/FILES index b78ea60c11..f0c4496c59 100644 --- a/samples/client/petstore/swift5/deprecated/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/deprecated/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/deprecated/.swiftformat b/samples/client/petstore/swift5/deprecated/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/deprecated/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift index 79ef8ff207..b0fe3685df 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 9b2fd4b47b..ebd4e6d887 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -56,7 +56,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -108,7 +108,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -156,7 +156,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -167,7 +167,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -208,7 +208,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -219,7 +219,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -269,7 +269,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -316,7 +316,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -376,7 +376,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -436,6 +436,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 4c713d2d67..01e80e98e2 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -56,7 +56,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -101,7 +101,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -148,7 +148,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -192,6 +192,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 8b8706bbde..644fe10642 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -56,7 +56,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -103,7 +103,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -150,7 +150,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -200,7 +200,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -247,7 +247,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -286,8 +286,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: true), + "password": (wrappedValue: password.encodeToJSON(), isExplode: true), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -298,7 +298,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -343,7 +343,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -395,6 +395,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/frozenEnums/.swiftformat b/samples/client/petstore/swift5/frozenEnums/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5e179af64e..44e76f4550 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -53,6 +53,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index eac6aeb1a3..102ea93f6d 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -51,7 +51,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -93,7 +93,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -135,7 +135,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -177,7 +177,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -219,7 +219,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -254,7 +254,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -265,7 +265,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -309,7 +309,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -400,7 +400,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -523,10 +523,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -539,7 +539,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -585,10 +585,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -600,7 +600,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -643,7 +643,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -694,6 +694,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 34e8c9c7f2..e4290335f9 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -56,6 +56,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 1fc238359a..054422bbe3 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -34,6 +34,9 @@ open class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -55,7 +58,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -106,7 +109,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -154,7 +157,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -165,7 +168,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -206,7 +209,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -217,7 +220,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -267,7 +270,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -313,7 +316,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -372,7 +375,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -431,7 +434,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -490,6 +493,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index c111e83013..c8416218db 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -56,7 +56,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -101,7 +101,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -148,7 +148,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -191,6 +191,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 5e01a4a7c3..5072c1f1da 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -53,7 +53,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -96,7 +96,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -139,7 +139,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -186,7 +186,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -232,7 +232,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -270,8 +270,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -282,7 +282,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -323,7 +323,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -372,6 +372,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/frozenEnums/docs/PetAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/PetAPI.md index 37226f18b8..7db99cf837 100644 --- a/samples/client/petstore/swift5/frozenEnums/docs/PetAPI.md +++ b/samples/client/petstore/swift5/frozenEnums/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/FILES b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/nonPublicApi/.swiftformat b/samples/client/petstore/swift5/nonPublicApi/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/nonPublicApi/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 83d36bb643..2ca9a6df1c 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ internal struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + internal static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded internal static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ internal struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift index 2dc59ba173..353a183b43 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ internal class RequestBuilder { internal let method: String internal let URLString: String internal let requestTask: RequestTask = RequestTask() + internal let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. internal var onProgressReady: ((Progress) -> Void)? - required internal init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required internal init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index fee5f2b8cc..df848839c9 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -53,6 +53,6 @@ internal class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 344309b20b..62aec8ada0 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -51,7 +51,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -93,7 +93,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -135,7 +135,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -177,7 +177,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -219,7 +219,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -254,7 +254,7 @@ internal class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -265,7 +265,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -309,7 +309,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -400,7 +400,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -523,10 +523,10 @@ internal class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -539,7 +539,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -585,10 +585,10 @@ internal class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -600,7 +600,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -643,7 +643,7 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -694,6 +694,6 @@ internal class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index ff9d932c5a..cab978d6be 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -56,6 +56,6 @@ internal class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 84428b2b76..143d7aa284 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -34,6 +34,9 @@ internal class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -55,7 +58,7 @@ internal class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -106,7 +109,7 @@ internal class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -154,7 +157,7 @@ internal class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -165,7 +168,7 @@ internal class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -206,7 +209,7 @@ internal class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -217,7 +220,7 @@ internal class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -267,7 +270,7 @@ internal class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -313,7 +316,7 @@ internal class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -372,7 +375,7 @@ internal class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -431,7 +434,7 @@ internal class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -490,6 +493,6 @@ internal class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 226802df83..78f99758e6 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -56,7 +56,7 @@ internal class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -101,7 +101,7 @@ internal class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -148,7 +148,7 @@ internal class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -191,6 +191,6 @@ internal class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 352cb794c3..6852a37500 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -53,7 +53,7 @@ internal class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -96,7 +96,7 @@ internal class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -139,7 +139,7 @@ internal class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -186,7 +186,7 @@ internal class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -232,7 +232,7 @@ internal class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -270,8 +270,8 @@ internal class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -282,7 +282,7 @@ internal class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -323,7 +323,7 @@ internal class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -372,6 +372,6 @@ internal class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 5be96e4e20..84d878ff6c 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ internal class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") internal static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + internal static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift index c7e2df56bc..5a4a360a0a 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + internal mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + internal mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + internal func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + internal func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift index 356d9c7454..9e20efc58f 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -18,7 +18,7 @@ extension CaseIterableDefaultsLast { /// Initializes an enum such that if a known raw value is found, then it is decoded. /// Otherwise the last case is used. /// - Parameter decoder: A decoder. - public init(from decoder: Decoder) throws { + internal init(from decoder: Decoder) throws { if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { self = value } else if let lastValue = Self.allCases.last { @@ -106,13 +106,18 @@ internal class Response { } internal final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } internal func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index cc04b4e3a4..ff0d9d08eb 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ internal class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ internal class OpenISO8601DateFormatter: DateFormatter { override internal func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 2502c1043e..e6ea6da1b1 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ internal class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") internal var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required internal init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required internal init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ internal class URLSessionDecodableRequestBuilder: URLSessionReques default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md b/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md index a9e13c339c..8635a4c340 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/FILES b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/objcCompatible/.swiftformat b/samples/client/petstore/swift5/objcCompatible/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/objcCompatible/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index c8199c1635..094cc27e47 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -53,6 +53,6 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 3211e37fe6..92b34cf1d2 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -51,7 +51,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -93,7 +93,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -135,7 +135,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -177,7 +177,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -219,7 +219,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -254,7 +254,7 @@ import AnyCodable var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -265,7 +265,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -309,7 +309,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -400,7 +400,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -523,10 +523,10 @@ import AnyCodable var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -539,7 +539,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -585,10 +585,10 @@ import AnyCodable var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -600,7 +600,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -643,7 +643,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -694,6 +694,6 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 897771399d..4767b66872 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -56,6 +56,6 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 851cba5071..06cdfc06cc 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -34,6 +34,9 @@ import AnyCodable /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -55,7 +58,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -106,7 +109,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -154,7 +157,7 @@ import AnyCodable var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -165,7 +168,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -206,7 +209,7 @@ import AnyCodable var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -217,7 +220,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -267,7 +270,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -313,7 +316,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -372,7 +375,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -431,7 +434,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -490,6 +493,6 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 333059bb10..770d143f0a 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -56,7 +56,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -101,7 +101,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -148,7 +148,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -191,6 +191,6 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 6a9da2b760..f3b848022c 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -53,7 +53,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -96,7 +96,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -139,7 +139,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -186,7 +186,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -232,7 +232,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -270,8 +270,8 @@ import AnyCodable var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -282,7 +282,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -323,7 +323,7 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -372,6 +372,6 @@ import AnyCodable let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md b/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md index 5e6bccd7ea..571bcd0fbc 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/oneOf/.openapi-generator/FILES b/samples/client/petstore/swift5/oneOf/.openapi-generator/FILES index 421958ec1d..2aca55297b 100644 --- a/samples/client/petstore/swift5/oneOf/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/oneOf/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/oneOf/.swiftformat b/samples/client/petstore/swift5/oneOf/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift index 96e432a19d..513c1222ad 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift index f17b96cd1f..b99ae9d542 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift @@ -48,6 +48,6 @@ open class DefaultAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/promisekitLibrary/.swiftformat b/samples/client/petstore/swift5/promisekitLibrary/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/promisekitLibrary/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index a020ab9180..89126346df 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -54,6 +54,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 76a588d0ac..02bfa1c5f9 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -52,7 +52,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -94,7 +94,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -136,7 +136,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -178,7 +178,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -220,7 +220,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -255,7 +255,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -266,7 +266,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -310,7 +310,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -401,7 +401,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -524,10 +524,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -540,7 +540,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -586,10 +586,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -601,7 +601,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -644,7 +644,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -695,6 +695,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index ca711ec135..1c03b338da 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -57,6 +57,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index cdfddd43e6..51ed84dfc8 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -35,6 +35,9 @@ open class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -56,7 +59,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -107,7 +110,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -155,7 +158,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -166,7 +169,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -207,7 +210,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -218,7 +221,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -268,7 +271,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -314,7 +317,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -373,7 +376,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -432,7 +435,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -491,6 +494,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index b2ca6da2b7..7cd506b1f7 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -57,7 +57,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -102,7 +102,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -149,7 +149,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -192,6 +192,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 4d631e267a..611917e6ad 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -54,7 +54,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -97,7 +97,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -140,7 +140,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -187,7 +187,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -233,7 +233,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -271,8 +271,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -283,7 +283,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -324,7 +324,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -373,6 +373,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index af90bc2ac5..09e71835ef 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -146,6 +146,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -185,11 +196,33 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md index 41d27fed4e..419776868a 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md @@ -51,7 +51,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/FILES b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/readonlyProperties/.swiftformat b/samples/client/petstore/swift5/readonlyProperties/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/readonlyProperties/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5e179af64e..44e76f4550 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -53,6 +53,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index d980142c6a..6113837af7 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -51,7 +51,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -93,7 +93,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -135,7 +135,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -177,7 +177,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -219,7 +219,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -254,7 +254,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -265,7 +265,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -309,7 +309,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -400,7 +400,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -523,10 +523,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -539,7 +539,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -585,10 +585,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -600,7 +600,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -643,7 +643,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -694,6 +694,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 34e8c9c7f2..e4290335f9 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -56,6 +56,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 254930e777..93671ed852 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -34,6 +34,9 @@ open class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -55,7 +58,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -106,7 +109,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -154,7 +157,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -165,7 +168,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -206,7 +209,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -217,7 +220,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -267,7 +270,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -313,7 +316,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -372,7 +375,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -431,7 +434,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -490,6 +493,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index c111e83013..c8416218db 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -56,7 +56,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -101,7 +101,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -148,7 +148,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -191,6 +191,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 5e01a4a7c3..5072c1f1da 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -53,7 +53,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -96,7 +96,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -139,7 +139,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -186,7 +186,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -232,7 +232,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -270,8 +270,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -282,7 +282,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -323,7 +323,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -372,6 +372,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md b/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md index 7dc73a9890..786640dabb 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/resultLibrary/.swiftformat b/samples/client/petstore/swift5/resultLibrary/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/resultLibrary/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index c684ae4fad..e7026326ee 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -20,17 +20,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 2c96460870..9bed93b838 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -53,6 +53,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index e347440638..4b15d4cfd8 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -51,7 +51,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -93,7 +93,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -135,7 +135,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -177,7 +177,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -219,7 +219,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -254,7 +254,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -265,7 +265,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -309,7 +309,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -400,7 +400,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -523,10 +523,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -539,7 +539,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -585,10 +585,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -600,7 +600,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -643,7 +643,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -694,6 +694,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index bc8e16a86d..43d5e65232 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -56,6 +56,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index d88ad67da7..f685b49335 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -34,6 +34,9 @@ open class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -55,7 +58,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -106,7 +109,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -154,7 +157,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -165,7 +168,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -206,7 +209,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -217,7 +220,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -267,7 +270,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -313,7 +316,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -372,7 +375,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -431,7 +434,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -490,6 +493,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 766f89065f..70d00552d8 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -56,7 +56,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -101,7 +101,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -148,7 +148,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -191,6 +191,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 0a40144f75..2b7a261443 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -53,7 +53,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -96,7 +96,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -139,7 +139,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -186,7 +186,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -232,7 +232,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -270,8 +270,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -282,7 +282,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -323,7 +323,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -372,6 +372,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md index 7dc73a9890..786640dabb 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/rxswiftLibrary/.swiftformat b/samples/client/petstore/swift5/rxswiftLibrary/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/rxswiftLibrary/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 336e8a19e3..d68645423d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -60,6 +60,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index e27e0b6c2d..e23c89811b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -58,7 +58,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -106,7 +106,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -154,7 +154,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -202,7 +202,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -250,7 +250,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -291,7 +291,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -302,7 +302,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -352,7 +352,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -449,7 +449,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -578,10 +578,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -594,7 +594,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -646,10 +646,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -661,7 +661,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -710,7 +710,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -767,6 +767,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index bd7da53d60..d9f0549dbd 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -63,6 +63,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index a1fa17f78b..2426be2a77 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -41,6 +41,9 @@ open class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -62,7 +65,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -119,7 +122,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -173,7 +176,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -184,7 +187,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -231,7 +234,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -242,7 +245,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -298,7 +301,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -350,7 +353,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -415,7 +418,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -480,7 +483,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -545,6 +548,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 283b7332c5..fb827f8458 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -63,7 +63,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -114,7 +114,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -167,7 +167,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -216,6 +216,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index c0be612ac9..9ab47031b6 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -60,7 +60,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -109,7 +109,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -158,7 +158,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -211,7 +211,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -263,7 +263,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -307,8 +307,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -319,7 +319,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -366,7 +366,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -421,6 +421,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index f7d0efdcb7..f82084988d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -102,6 +102,6 @@ extension JSONEncodable where Self: Encodable { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md index 9f9a42ca4f..c376190fb6 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md @@ -44,7 +44,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/FILES index 27a85ba47e..6ae7cd0f2e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.swiftformat b/samples/client/petstore/swift5/urlsessionLibrary/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift index 20dfa6d14c..4632a8c2dc 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift @@ -56,7 +56,7 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift index f336d4b552..d03476d2f4 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift @@ -54,7 +54,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -96,7 +96,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -138,7 +138,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -180,7 +180,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -222,7 +222,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -257,7 +257,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -268,7 +268,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -312,7 +312,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -403,7 +403,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -526,10 +526,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -542,7 +542,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -588,10 +588,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -603,7 +603,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -646,7 +646,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -697,7 +697,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift index e1608abb40..249596866e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift @@ -59,7 +59,7 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift index 551edaf0db..1d2a16db1d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift @@ -37,6 +37,9 @@ open class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -58,7 +61,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -109,7 +112,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -157,7 +160,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -168,7 +171,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -209,7 +212,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -220,7 +223,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -270,7 +273,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -316,7 +319,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -375,7 +378,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -434,7 +437,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -493,7 +496,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift index 052761d676..1d449dbbb7 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift @@ -59,7 +59,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -104,7 +104,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -151,7 +151,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -194,7 +194,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift index 242239a1a9..77dc9bfdbd 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift @@ -56,7 +56,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -99,7 +99,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -142,7 +142,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -189,7 +189,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -235,7 +235,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -273,8 +273,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -285,7 +285,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -326,7 +326,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -375,7 +375,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift index c5224b89eb..399495722c 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift @@ -16,6 +16,10 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift index b1f37b4ea8..527e3e8464 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient/BearerDecodableRequestBuilder.swift @@ -20,10 +20,18 @@ class BearerRequestBuilderFactory: RequestBuilderFactory { } class BearerRequestBuilder: URLSessionRequestBuilder { + @discardableResult override func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (Result, ErrorResponse>) -> Void) -> RequestTask { + + guard self.requiresAuthentication else { + return super.execute(apiResponseQueue, completion) + } + // Before making the request, we can validate if we have a bearer token to be able to make a request - BearerTokenHandler.refreshTokenIfDoesntExist { + BearerTokenHandler.refreshTokenIfDoesntExist { token in + + self.addHeaders(["Authorization": "Bearer \(token)"]) // Here we make the request super.execute(apiResponseQueue) { result in @@ -43,10 +51,12 @@ class BearerRequestBuilder: URLSessionRequestBuilder { data: data, response: response, error: error - ) { wasTokenRefreshed in + ) { (wasTokenRefreshed, newToken) in - if wasTokenRefreshed { + if wasTokenRefreshed, let newToken = newToken { + // If the token was refreshed, it's because it was a 401 error, so we refreshed the token, and we are going to retry the request by calling self.execute() + self.addHeaders(["Authorization": "Bearer \(newToken)"]) self.execute(apiResponseQueue, completion) } else { // If the token was not refreshed, it's because it was not a 401 error, so we send the response to the completion block @@ -67,10 +77,18 @@ class BearerRequestBuilder: URLSessionRequestBuilder { } class BearerDecodableRequestBuilder: URLSessionDecodableRequestBuilder { + @discardableResult override func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (Result, ErrorResponse>) -> Void) -> RequestTask { + + guard self.requiresAuthentication else { + return super.execute(apiResponseQueue, completion) + } + // Before making the request, we can validate if we have a bearer token to be able to make a request - BearerTokenHandler.refreshTokenIfDoesntExist { + BearerTokenHandler.refreshTokenIfDoesntExist { token in + + self.addHeaders(["Authorization": "Bearer \(token)"]) // Here we make the request super.execute(apiResponseQueue) { result in @@ -90,10 +108,12 @@ class BearerDecodableRequestBuilder: URLSessionDecodableRequestBui data: data, response: response, error: error - ) { wasTokenRefreshed in + ) { (wasTokenRefreshed, newToken) in - if wasTokenRefreshed { + if wasTokenRefreshed, let newToken = newToken { + // If the token was refreshed, it's because it was a 401 error, so we refreshed the token, and we are going to retry the request by calling self.execute() + self.addHeaders(["Authorization": "Bearer \(newToken)"]) self.execute(apiResponseQueue, completion) } else { // If the token was not refreshed, it's because it was not a 401 error, so we send the response to the completion block @@ -116,33 +136,32 @@ class BearerDecodableRequestBuilder: URLSessionDecodableRequestBui class BearerTokenHandler { private static var bearerToken: String? = nil - static func refreshTokenIfDoesntExist(completionHandler: @escaping () -> Void) { - if bearerToken != nil { - completionHandler() + static func refreshTokenIfDoesntExist(completionHandler: @escaping (String) -> Void) { + if let bearerToken = bearerToken { + completionHandler(bearerToken) } else { - startRefreshingToken { - completionHandler() + startRefreshingToken { token in + completionHandler(token) } } } - static func refreshTokenIfUnauthorizedRequestResponse(data: Data?, response: URLResponse?, error: Error?, completionHandler: @escaping (Bool) -> Void) { + static func refreshTokenIfUnauthorizedRequestResponse(data: Data?, response: URLResponse?, error: Error?, completionHandler: @escaping (Bool, String?) -> Void) { if let response = response as? HTTPURLResponse, response.statusCode == 401 { - startRefreshingToken { - completionHandler(true) + startRefreshingToken { token in + completionHandler(true, token) } } else { - completionHandler(false) + completionHandler(false, nil) } } - private static func startRefreshingToken(completionHandler: @escaping () -> Void) { + private static func startRefreshingToken(completionHandler: @escaping (String) -> Void) { // Get a bearer token let dummyBearerToken = "..." bearerToken = dummyBearerToken - PetstoreClientAPI.customHeaders["Authorization"] = "Bearer \(dummyBearerToken)" - completionHandler() + completionHandler(dummyBearerToken) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md index 7dc73a9890..786640dabb 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/FILES index ec27ad4b38..ce00501a1a 100644 --- a/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Package.swift README.md Sources/PetstoreClient/APIs.swift @@ -60,6 +61,7 @@ Sources/PetstoreClient/Models/TypeHolderDefault.swift Sources/PetstoreClient/Models/TypeHolderExample.swift Sources/PetstoreClient/Models/User.swift Sources/PetstoreClient/Models/XmlItem.swift +Sources/PetstoreClient/OpenISO8601DateFormatter.swift docs/AdditionalPropertiesAnyType.md docs/AdditionalPropertiesArray.md docs/AdditionalPropertiesBoolean.md diff --git a/samples/client/petstore/swift5/vaporLibrary/.swiftformat b/samples/client/petstore/swift5/vaporLibrary/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Extensions.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Extensions.swift index 85e9a859c3..b1777b8b35 100644 --- a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Extensions.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Extensions.swift @@ -55,6 +55,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -94,6 +105,28 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension UUID: Content { } diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift new file mode 100644 index 0000000000..cc3288805f --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift @@ -0,0 +1,56 @@ +// +// OpenISO8601DateFormatter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +// https://stackoverflow.com/a/50281094/976628 +public class OpenISO8601DateFormatter: DateFormatter { + static let withoutSeconds: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + return formatter + }() + + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + + private func setup() { + calendar = Calendar(identifier: .iso8601) + locale = Locale(identifier: "en_US_POSIX") + timeZone = TimeZone(secondsFromGMT: 0) + dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + } + + override init() { + super.init() + setup() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + override public func date(from string: String) -> Date? { + if let result = super.date(from: string) { + return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result + } + + return OpenISO8601DateFormatter.withoutTime.date(from: string) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/FILES b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/FILES index c81943baf2..d9454003ce 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/FILES @@ -1,4 +1,5 @@ .gitignore +.swiftformat Cartfile Package.swift PetstoreClient.podspec diff --git a/samples/client/petstore/swift5/x-swift-hashable/.swiftformat b/samples/client/petstore/swift5/x-swift-hashable/.swiftformat new file mode 100644 index 0000000000..9300725280 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 049b7f655f..ce35f8dbc7 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -62,6 +62,41 @@ public struct APIHelper { return source } + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into seperate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { @@ -73,6 +108,7 @@ public struct APIHelper { .forEach { value in result.append(URLQueryItem(name: item.key, value: value)) } + } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift index 485585212d..8f74ebeeb7 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -28,17 +28,19 @@ open class RequestBuilder { public let method: String public let URLString: String public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool /// Optional block to obtain a reference to the request's progress instance when available. /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. /// If you need to get the request's progress in older OS versions, please use Alamofire http client. public var onProgressReady: ((Progress) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.headers = headers + self.requiresAuthentication = requiresAuthentication addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5e179af64e..44e76f4550 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -53,6 +53,6 @@ open class AnotherFakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index d980142c6a..6113837af7 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -51,7 +51,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -93,7 +93,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -135,7 +135,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -177,7 +177,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -219,7 +219,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -254,7 +254,7 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "query": query.encodeToJSON(), + "query": (wrappedValue: query.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -265,7 +265,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -309,7 +309,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -400,7 +400,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -523,10 +523,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), - "enum_query_string": enumQueryString?.encodeToJSON(), - "enum_query_integer": enumQueryInteger?.encodeToJSON(), - "enum_query_double": enumQueryDouble?.encodeToJSON(), + "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false), + "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false), + "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false), + "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -539,7 +539,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -585,10 +585,10 @@ open class FakeAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "required_string_group": requiredStringGroup.encodeToJSON(), - "required_int64_group": requiredInt64Group.encodeToJSON(), - "string_group": stringGroup?.encodeToJSON(), - "int64_group": int64Group?.encodeToJSON(), + "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false), + "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false), + "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false), + "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -600,7 +600,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -643,7 +643,7 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -694,6 +694,6 @@ open class FakeAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 34e8c9c7f2..e4290335f9 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -56,6 +56,6 @@ open class FakeClassnameTags123API { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 254930e777..93671ed852 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -34,6 +34,9 @@ open class PetAPI { /** Add a new pet to the store - POST /pet + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query - OAuth: - type: oauth2 - name: petstore_auth @@ -55,7 +58,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -106,7 +109,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -154,7 +157,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "status": status.encodeToJSON(), + "status": (wrappedValue: status.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -165,7 +168,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -206,7 +209,7 @@ open class PetAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "tags": tags.encodeToJSON(), + "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -217,7 +220,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -267,7 +270,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -313,7 +316,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -372,7 +375,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -431,7 +434,7 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -490,6 +493,6 @@ open class PetAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index c111e83013..c8416218db 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -56,7 +56,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -101,7 +101,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } /** @@ -148,7 +148,7 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -191,6 +191,6 @@ open class StoreAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 5e01a4a7c3..5072c1f1da 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -53,7 +53,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -96,7 +96,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -139,7 +139,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -186,7 +186,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -232,7 +232,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -270,8 +270,8 @@ open class UserAPI { var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ - "username": username.encodeToJSON(), - "password": password.encodeToJSON(), + "username": (wrappedValue: username.encodeToJSON(), isExplode: false), + "password": (wrappedValue: password.encodeToJSON(), isExplode: false), ]) let localVariableNillableHeaders: [String: Any?] = [ @@ -282,7 +282,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -323,7 +323,7 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } /** @@ -372,6 +372,6 @@ open class UserAPI { let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() - return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 8fb0533188..03789f4b49 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -12,4 +12,8 @@ open class Configuration { // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 0b17438a7c..dd0b27c48d 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -145,6 +145,17 @@ extension KeyedEncodingContainerProtocol { } } + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + var mutableValue = value + let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) + try encode(stringValue, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } } extension KeyedDecodingContainerProtocol { @@ -184,10 +195,32 @@ extension KeyedDecodingContainerProtocol { return map } + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + } extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return (200 ..< 300).contains(statusCode) + return Configuration.successfulStatusCodeRange.contains(statusCode) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift index 21aad0cf64..50cd5bff5f 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -106,13 +106,18 @@ open class Response { } public final class RequestTask { + private var lock = NSRecursiveLock() private var task: URLSessionTask? internal func set(task: URLSessionTask) { + lock.lock() + defer { lock.unlock() } self.task = task } public func cancel() { + lock.lock() + defer { lock.unlock() } task?.cancel() task = nil } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift index e06208074c..cc3288805f 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -18,6 +18,15 @@ public class OpenISO8601DateFormatter: DateFormatter { return formatter }() + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + private func setup() { calendar = Calendar(identifier: .iso8601) locale = Locale(identifier: "en_US_POSIX") @@ -38,7 +47,10 @@ public class OpenISO8601DateFormatter: DateFormatter { override public func date(from string: String) -> Date? { if let result = super.date(from: string) { return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result } - return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + + return OpenISO8601DateFormatter.withoutTime.date(from: string) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index a12e0bb402..f259b240e6 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -55,8 +55,8 @@ open class URLSessionRequestBuilder: RequestBuilder { @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? - required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { - super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) } /** @@ -353,8 +353,8 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui default: guard let data = data, !data.isEmpty else { - if T.self is ExpressibleByNilLiteral.Type { - completion(.success(Response(response: httpResponse, body: Optional.none as! T))) + if let E = T.self as? ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: E.init(nilLiteral: ()) as! T))) } else { completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) } @@ -455,49 +455,62 @@ private class FormDataEncoding: ParameterEncoding { urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") for (key, value) in parameters { - switch value { - case let fileURL as URL: + for value in (value as? Array ?? [value]) { + switch value { + case let fileURL as URL: - urlRequest = try configureFileUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - fileURL: fileURL - ) + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) - case let string as String: + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let data as Data: - if let data = string.data(using: .utf8) { urlRequest = configureDataUploadRequest( urlRequest: urlRequest, boundary: boundary, name: key, data: data ) + + case let uuid as UUID: + + if let data = uuid.uuidString.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") } - - case let number as NSNumber: - - if let data = number.stringValue.data(using: .utf8) { - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - } - - case let data as Data: - - urlRequest = configureDataUploadRequest( - urlRequest: urlRequest, - boundary: boundary, - name: key, - data: data - ) - - default: - fatalError("Unprocessable value \(value) with key \(key)") } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md index 7dc73a9890..786640dabb 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md @@ -54,7 +54,7 @@ Void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[api_key_query](../README.md#api_key_query), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/.openapi-generator/FILES index e646d434ee..6cf24d465b 100644 --- a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/.openapi-generator/FILES @@ -11,4 +11,5 @@ model/apple.ts model/fruit.ts model/grape.ts model/models.ts +param.ts variables.ts diff --git a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/README.md b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/README.md index f2e5a1c1ee..de16f95a8b 100644 --- a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/README.md +++ b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/README.md @@ -201,3 +201,26 @@ import { environment } from '../environments/environment'; }) export class AppModule { } ``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/api/default.service.ts b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/api/default.service.ts index 5a2e821d72..bd0f78c6e0 100644 --- a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/api/default.service.ts +++ b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/api/default.service.ts @@ -37,11 +37,15 @@ export class DefaultService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -127,7 +131,8 @@ export class DefaultService { } } - return this.httpClient.get(`${this.configuration.basePath}/`, + let localVarPath = `/`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -188,10 +193,11 @@ export class DefaultService { } } - return this.httpClient.put(`${this.configuration.basePath}/`, - body, + let localVarPath = `/`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/configuration.ts index 4ca3546927..d38a4c153f 100644 --- a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/configuration.ts @@ -1,4 +1,5 @@ import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; export interface ConfigurationParameters { /** @@ -13,7 +14,18 @@ export interface ConfigurationParameters { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -35,7 +47,18 @@ export class Configuration { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -51,6 +74,12 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } if (configurationParameters.credentials) { this.credentials = configurationParameters.credentials; } @@ -118,4 +147,20 @@ export class Configuration { ? value() : value; } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/index.ts b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/index.ts index c312b70fa3..104dd3d21e 100644 --- a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/index.ts +++ b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/param.ts b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/.openapi-generator/FILES index 7f8ebffb30..6e213a61aa 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/.openapi-generator/FILES @@ -16,4 +16,5 @@ model/order.ts model/pet.ts model/tag.ts model/user.ts +param.ts variables.ts diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/README.md b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/README.md index f2e5a1c1ee..de16f95a8b 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/README.md +++ b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/README.md @@ -201,3 +201,26 @@ import { environment } from '../environments/environment'; }) export class AppModule { } ``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/pet.service.ts index 12cd04a284..b59d02e26a 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/pet.service.ts @@ -39,11 +39,15 @@ export class PetService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -163,10 +167,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet`, - body, + let localVarPath = `/pet`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -231,7 +236,8 @@ export class PetService { } } - return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -261,7 +267,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (status) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - status.join(COLLECTION_FORMATS['csv']), 'status'); + [...status].join(COLLECTION_FORMATS['csv']), 'status'); } let localVarHeaders = this.defaultHeaders; @@ -303,7 +309,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + let localVarPath = `/pet/findByStatus`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -335,7 +342,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (tags) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - tags.join(COLLECTION_FORMATS['csv']), 'tags'); + [...tags].join(COLLECTION_FORMATS['csv']), 'tags'); } let localVarHeaders = this.defaultHeaders; @@ -377,7 +384,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + let localVarPath = `/pet/findByTags`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -444,7 +452,8 @@ export class PetService { } } - return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -517,10 +526,11 @@ export class PetService { } } - return this.httpClient.put(`${this.configuration.basePath}/pet`, - body, + let localVarPath = `/pet`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -605,10 +615,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -697,10 +708,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/store.service.ts index 8b504109f7..6160c6b7c2 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/store.service.ts @@ -37,11 +37,15 @@ export class StoreService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -132,7 +136,8 @@ export class StoreService { } } - return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -193,7 +198,8 @@ export class StoreService { } } - return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + let localVarPath = `/store/inventory`; + return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -252,7 +258,8 @@ export class StoreService { } } - return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -318,10 +325,11 @@ export class StoreService { } } - return this.httpClient.post(`${this.configuration.basePath}/store/order`, - body, + let localVarPath = `/store/order`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/user.service.ts index a8d7621ee3..ad578c0420 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/api/user.service.ts @@ -37,11 +37,15 @@ export class UserService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -140,10 +144,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user`, - body, + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -205,10 +210,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, - body, + let localVarPath = `/user/createWithArray`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -270,10 +276,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, - body, + let localVarPath = `/user/createWithList`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -328,7 +335,8 @@ export class UserService { } } - return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -386,7 +394,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -458,7 +467,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/login`, + let localVarPath = `/user/login`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -511,7 +521,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + let localVarPath = `/user/logout`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -580,10 +591,11 @@ export class UserService { } } - return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, - body, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/configuration.ts index 6fc0f80d97..5ea92c82cb 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/configuration.ts @@ -1,4 +1,5 @@ import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; export interface ConfigurationParameters { /** @@ -13,7 +14,18 @@ export interface ConfigurationParameters { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -35,7 +47,18 @@ export class Configuration { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -51,6 +74,12 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } if (configurationParameters.credentials) { this.credentials = configurationParameters.credentials; } @@ -138,4 +167,20 @@ export class Configuration { ? value() : value; } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/index.ts b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/index.ts index c312b70fa3..104dd3d21e 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/index.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/param.ts b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/.openapi-generator/FILES index 7f8ebffb30..6e213a61aa 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/.openapi-generator/FILES @@ -16,4 +16,5 @@ model/order.ts model/pet.ts model/tag.ts model/user.ts +param.ts variables.ts diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/README.md b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/README.md index f2e5a1c1ee..de16f95a8b 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/README.md +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/README.md @@ -201,3 +201,26 @@ import { environment } from '../environments/environment'; }) export class AppModule { } ``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/pet.service.ts index c5dcda6a5f..7a51c36ce9 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/pet.service.ts @@ -39,11 +39,15 @@ export class PetService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -163,10 +167,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet`, - body, + let localVarPath = `/pet`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -231,7 +236,8 @@ export class PetService { } } - return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -261,7 +267,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (status) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - status.join(COLLECTION_FORMATS['csv']), 'status'); + [...status].join(COLLECTION_FORMATS['csv']), 'status'); } let localVarHeaders = this.defaultHeaders; @@ -303,7 +309,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + let localVarPath = `/pet/findByStatus`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -335,7 +342,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (tags) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - tags.join(COLLECTION_FORMATS['csv']), 'tags'); + [...tags].join(COLLECTION_FORMATS['csv']), 'tags'); } let localVarHeaders = this.defaultHeaders; @@ -377,7 +384,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + let localVarPath = `/pet/findByTags`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -444,7 +452,8 @@ export class PetService { } } - return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -517,10 +526,11 @@ export class PetService { } } - return this.httpClient.put(`${this.configuration.basePath}/pet`, - body, + let localVarPath = `/pet`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -605,10 +615,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -697,10 +708,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/store.service.ts index 00a9cce5de..374f8f02e7 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/store.service.ts @@ -37,11 +37,15 @@ export class StoreService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -132,7 +136,8 @@ export class StoreService { } } - return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -193,7 +198,8 @@ export class StoreService { } } - return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + let localVarPath = `/store/inventory`; + return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -252,7 +258,8 @@ export class StoreService { } } - return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -318,10 +325,11 @@ export class StoreService { } } - return this.httpClient.post(`${this.configuration.basePath}/store/order`, - body, + let localVarPath = `/store/order`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/user.service.ts index 444e25c12e..f193dd635e 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/api/user.service.ts @@ -37,11 +37,15 @@ export class UserService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -140,10 +144,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user`, - body, + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -205,10 +210,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, - body, + let localVarPath = `/user/createWithArray`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -270,10 +276,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, - body, + let localVarPath = `/user/createWithList`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -328,7 +335,8 @@ export class UserService { } } - return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -386,7 +394,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -458,7 +467,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/login`, + let localVarPath = `/user/login`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -511,7 +521,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + let localVarPath = `/user/logout`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -580,10 +591,11 @@ export class UserService { } } - return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, - body, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/configuration.ts index 6fc0f80d97..5ea92c82cb 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/configuration.ts @@ -1,4 +1,5 @@ import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; export interface ConfigurationParameters { /** @@ -13,7 +14,18 @@ export interface ConfigurationParameters { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -35,7 +47,18 @@ export class Configuration { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -51,6 +74,12 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } if (configurationParameters.credentials) { this.credentials = configurationParameters.credentials; } @@ -138,4 +167,20 @@ export class Configuration { ? value() : value; } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/index.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/index.ts index c312b70fa3..104dd3d21e 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/index.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/param.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/.openapi-generator/FILES index 5db7bd7636..572424259e 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/.openapi-generator/FILES @@ -18,5 +18,6 @@ model/tag.ts model/user.ts ng-package.json package.json +param.ts tsconfig.json variables.ts diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/README.md b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/README.md index 000c51d694..4cd59003db 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/README.md +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/README.md @@ -201,3 +201,26 @@ import { environment } from '../environments/environment'; }) export class AppModule { } ``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/pet.service.ts index c5dcda6a5f..7a51c36ce9 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/pet.service.ts @@ -39,11 +39,15 @@ export class PetService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -163,10 +167,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet`, - body, + let localVarPath = `/pet`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -231,7 +236,8 @@ export class PetService { } } - return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -261,7 +267,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (status) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - status.join(COLLECTION_FORMATS['csv']), 'status'); + [...status].join(COLLECTION_FORMATS['csv']), 'status'); } let localVarHeaders = this.defaultHeaders; @@ -303,7 +309,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + let localVarPath = `/pet/findByStatus`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -335,7 +342,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (tags) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - tags.join(COLLECTION_FORMATS['csv']), 'tags'); + [...tags].join(COLLECTION_FORMATS['csv']), 'tags'); } let localVarHeaders = this.defaultHeaders; @@ -377,7 +384,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + let localVarPath = `/pet/findByTags`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -444,7 +452,8 @@ export class PetService { } } - return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -517,10 +526,11 @@ export class PetService { } } - return this.httpClient.put(`${this.configuration.basePath}/pet`, - body, + let localVarPath = `/pet`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -605,10 +615,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -697,10 +708,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/store.service.ts index 00a9cce5de..374f8f02e7 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/store.service.ts @@ -37,11 +37,15 @@ export class StoreService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -132,7 +136,8 @@ export class StoreService { } } - return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -193,7 +198,8 @@ export class StoreService { } } - return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + let localVarPath = `/store/inventory`; + return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -252,7 +258,8 @@ export class StoreService { } } - return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -318,10 +325,11 @@ export class StoreService { } } - return this.httpClient.post(`${this.configuration.basePath}/store/order`, - body, + let localVarPath = `/store/order`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/user.service.ts index 444e25c12e..f193dd635e 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/api/user.service.ts @@ -37,11 +37,15 @@ export class UserService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -140,10 +144,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user`, - body, + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -205,10 +210,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, - body, + let localVarPath = `/user/createWithArray`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -270,10 +276,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, - body, + let localVarPath = `/user/createWithList`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -328,7 +335,8 @@ export class UserService { } } - return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -386,7 +394,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -458,7 +467,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/login`, + let localVarPath = `/user/login`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -511,7 +521,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + let localVarPath = `/user/logout`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -580,10 +591,11 @@ export class UserService { } } - return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, - body, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/configuration.ts index 6fc0f80d97..5ea92c82cb 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/configuration.ts @@ -1,4 +1,5 @@ import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; export interface ConfigurationParameters { /** @@ -13,7 +14,18 @@ export interface ConfigurationParameters { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -35,7 +47,18 @@ export class Configuration { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -51,6 +74,12 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } if (configurationParameters.credentials) { this.credentials = configurationParameters.credentials; } @@ -138,4 +167,20 @@ export class Configuration { ? value() : value; } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/index.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/index.ts index c312b70fa3..104dd3d21e 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/index.ts +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/param.ts b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/.openapi-generator/FILES index e646d434ee..6cf24d465b 100644 --- a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/.openapi-generator/FILES @@ -11,4 +11,5 @@ model/apple.ts model/fruit.ts model/grape.ts model/models.ts +param.ts variables.ts diff --git a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/README.md b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/README.md index f2e5a1c1ee..de16f95a8b 100644 --- a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/README.md +++ b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/README.md @@ -201,3 +201,26 @@ import { environment } from '../environments/environment'; }) export class AppModule { } ``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/api/default.service.ts b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/api/default.service.ts index 5a2e821d72..bd0f78c6e0 100644 --- a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/api/default.service.ts +++ b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/api/default.service.ts @@ -37,11 +37,15 @@ export class DefaultService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -127,7 +131,8 @@ export class DefaultService { } } - return this.httpClient.get(`${this.configuration.basePath}/`, + let localVarPath = `/`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -188,10 +193,11 @@ export class DefaultService { } } - return this.httpClient.put(`${this.configuration.basePath}/`, - body, + let localVarPath = `/`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/configuration.ts index 4ca3546927..d38a4c153f 100644 --- a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/configuration.ts @@ -1,4 +1,5 @@ import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; export interface ConfigurationParameters { /** @@ -13,7 +14,18 @@ export interface ConfigurationParameters { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -35,7 +47,18 @@ export class Configuration { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -51,6 +74,12 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } if (configurationParameters.credentials) { this.credentials = configurationParameters.credentials; } @@ -118,4 +147,20 @@ export class Configuration { ? value() : value; } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/index.ts b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/index.ts index c312b70fa3..104dd3d21e 100644 --- a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/index.ts +++ b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/param.ts b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/.openapi-generator/FILES index 7f8ebffb30..6e213a61aa 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/.openapi-generator/FILES @@ -16,4 +16,5 @@ model/order.ts model/pet.ts model/tag.ts model/user.ts +param.ts variables.ts diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/README.md b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/README.md index f2e5a1c1ee..de16f95a8b 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/README.md +++ b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/README.md @@ -201,3 +201,26 @@ import { environment } from '../environments/environment'; }) export class AppModule { } ``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/pet.service.ts index 12cd04a284..b59d02e26a 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/pet.service.ts @@ -39,11 +39,15 @@ export class PetService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -163,10 +167,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet`, - body, + let localVarPath = `/pet`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -231,7 +236,8 @@ export class PetService { } } - return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -261,7 +267,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (status) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - status.join(COLLECTION_FORMATS['csv']), 'status'); + [...status].join(COLLECTION_FORMATS['csv']), 'status'); } let localVarHeaders = this.defaultHeaders; @@ -303,7 +309,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + let localVarPath = `/pet/findByStatus`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -335,7 +342,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (tags) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - tags.join(COLLECTION_FORMATS['csv']), 'tags'); + [...tags].join(COLLECTION_FORMATS['csv']), 'tags'); } let localVarHeaders = this.defaultHeaders; @@ -377,7 +384,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + let localVarPath = `/pet/findByTags`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -444,7 +452,8 @@ export class PetService { } } - return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -517,10 +526,11 @@ export class PetService { } } - return this.httpClient.put(`${this.configuration.basePath}/pet`, - body, + let localVarPath = `/pet`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -605,10 +615,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -697,10 +708,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/store.service.ts index 8b504109f7..6160c6b7c2 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/store.service.ts @@ -37,11 +37,15 @@ export class StoreService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -132,7 +136,8 @@ export class StoreService { } } - return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -193,7 +198,8 @@ export class StoreService { } } - return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + let localVarPath = `/store/inventory`; + return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -252,7 +258,8 @@ export class StoreService { } } - return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -318,10 +325,11 @@ export class StoreService { } } - return this.httpClient.post(`${this.configuration.basePath}/store/order`, - body, + let localVarPath = `/store/order`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/user.service.ts index a8d7621ee3..ad578c0420 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/api/user.service.ts @@ -37,11 +37,15 @@ export class UserService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -140,10 +144,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user`, - body, + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -205,10 +210,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, - body, + let localVarPath = `/user/createWithArray`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -270,10 +276,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, - body, + let localVarPath = `/user/createWithList`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -328,7 +335,8 @@ export class UserService { } } - return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -386,7 +394,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -458,7 +467,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/login`, + let localVarPath = `/user/login`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -511,7 +521,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + let localVarPath = `/user/logout`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -580,10 +591,11 @@ export class UserService { } } - return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, - body, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: body, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/configuration.ts index 6fc0f80d97..5ea92c82cb 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/configuration.ts @@ -1,4 +1,5 @@ import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; export interface ConfigurationParameters { /** @@ -13,7 +14,18 @@ export interface ConfigurationParameters { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -35,7 +47,18 @@ export class Configuration { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -51,6 +74,12 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } if (configurationParameters.credentials) { this.credentials = configurationParameters.credentials; } @@ -138,4 +167,20 @@ export class Configuration { ? value() : value; } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/index.ts b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/index.ts index c312b70fa3..104dd3d21e 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/index.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/param.ts b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES index 7f8ebffb30..6e213a61aa 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES @@ -16,4 +16,5 @@ model/order.ts model/pet.ts model/tag.ts model/user.ts +param.ts variables.ts diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md index f2e5a1c1ee..de16f95a8b 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md @@ -201,3 +201,26 @@ import { environment } from '../environments/environment'; }) export class AppModule { } ``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts index af8f8e65ca..c27a2e8f8e 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts @@ -39,11 +39,15 @@ export class PetService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -166,10 +170,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet`, - pet, + let localVarPath = `/pet`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: pet, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -235,7 +240,8 @@ export class PetService { } } - return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -265,7 +271,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (status) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - status.join(COLLECTION_FORMATS['csv']), 'status'); + [...status].join(COLLECTION_FORMATS['csv']), 'status'); } let localVarHeaders = this.defaultHeaders; @@ -307,7 +313,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + let localVarPath = `/pet/findByStatus`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -339,7 +346,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (tags) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - tags.join(COLLECTION_FORMATS['csv']), 'tags'); + [...tags].join(COLLECTION_FORMATS['csv']), 'tags'); } let localVarHeaders = this.defaultHeaders; @@ -381,7 +388,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + let localVarPath = `/pet/findByTags`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -448,7 +456,8 @@ export class PetService { } } - return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -524,10 +533,11 @@ export class PetService { } } - return this.httpClient.put(`${this.configuration.basePath}/pet`, - pet, + let localVarPath = `/pet`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: pet, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -613,10 +623,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -706,10 +717,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts index cc32a52fc4..2aa584617f 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts @@ -37,11 +37,15 @@ export class StoreService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -132,7 +136,8 @@ export class StoreService { } } - return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -193,7 +198,8 @@ export class StoreService { } } - return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + let localVarPath = `/store/inventory`; + return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -252,7 +258,8 @@ export class StoreService { } } - return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -320,10 +327,11 @@ export class StoreService { } } - return this.httpClient.post(`${this.configuration.basePath}/store/order`, - order, + let localVarPath = `/store/order`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: order, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts index 070ed1221d..62cbf7b6e8 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts @@ -37,11 +37,15 @@ export class UserService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -148,10 +152,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user`, - user, + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: user, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -222,10 +227,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, - user, + let localVarPath = `/user/createWithArray`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: user, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -296,10 +302,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, - user, + let localVarPath = `/user/createWithList`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: user, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -361,7 +368,8 @@ export class UserService { } } - return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -420,7 +428,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -493,7 +502,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/login`, + let localVarPath = `/user/login`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -554,7 +564,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + let localVarPath = `/user/logout`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -631,10 +642,11 @@ export class UserService { } } - return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, - user, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: user, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts index 6fc0f80d97..5ea92c82cb 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts @@ -1,4 +1,5 @@ import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; export interface ConfigurationParameters { /** @@ -13,7 +14,18 @@ export interface ConfigurationParameters { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -35,7 +47,18 @@ export class Configuration { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -51,6 +74,12 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } if (configurationParameters.credentials) { this.credentials = configurationParameters.credentials; } @@ -138,4 +167,20 @@ export class Configuration { ? value() : value; } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts index c312b70fa3..104dd3d21e 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/param.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES index 5db7bd7636..572424259e 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES @@ -18,5 +18,6 @@ model/tag.ts model/user.ts ng-package.json package.json +param.ts tsconfig.json variables.ts diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md index 000c51d694..4cd59003db 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md @@ -201,3 +201,26 @@ import { environment } from '../environments/environment'; }) export class AppModule { } ``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts index af8f8e65ca..c27a2e8f8e 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts @@ -39,11 +39,15 @@ export class PetService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -166,10 +170,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet`, - pet, + let localVarPath = `/pet`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: pet, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -235,7 +240,8 @@ export class PetService { } } - return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -265,7 +271,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (status) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - status.join(COLLECTION_FORMATS['csv']), 'status'); + [...status].join(COLLECTION_FORMATS['csv']), 'status'); } let localVarHeaders = this.defaultHeaders; @@ -307,7 +313,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + let localVarPath = `/pet/findByStatus`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -339,7 +346,7 @@ export class PetService { let localVarQueryParameters = new HttpParams({encoder: this.encoder}); if (tags) { localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, - tags.join(COLLECTION_FORMATS['csv']), 'tags'); + [...tags].join(COLLECTION_FORMATS['csv']), 'tags'); } let localVarHeaders = this.defaultHeaders; @@ -381,7 +388,8 @@ export class PetService { } } - return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + let localVarPath = `/pet/findByTags`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -448,7 +456,8 @@ export class PetService { } } - return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -524,10 +533,11 @@ export class PetService { } } - return this.httpClient.put(`${this.configuration.basePath}/pet`, - pet, + let localVarPath = `/pet`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: pet, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -613,10 +623,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -706,10 +717,11 @@ export class PetService { } } - return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, - localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts index cc32a52fc4..2aa584617f 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts @@ -37,11 +37,15 @@ export class StoreService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -132,7 +136,8 @@ export class StoreService { } } - return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -193,7 +198,8 @@ export class StoreService { } } - return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + let localVarPath = `/store/inventory`; + return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -252,7 +258,8 @@ export class StoreService { } } - return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -320,10 +327,11 @@ export class StoreService { } } - return this.httpClient.post(`${this.configuration.basePath}/store/order`, - order, + let localVarPath = `/store/order`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: order, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts index 070ed1221d..62cbf7b6e8 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts @@ -37,11 +37,15 @@ export class UserService { public configuration = new Configuration(); public encoder: HttpParameterCodec; - constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; } if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + if (typeof basePath !== 'string') { basePath = this.basePath; } @@ -148,10 +152,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user`, - user, + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: user, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -222,10 +227,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, - user, + let localVarPath = `/user/createWithArray`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: user, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -296,10 +302,11 @@ export class UserService { } } - return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, - user, + let localVarPath = `/user/createWithList`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: user, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, @@ -361,7 +368,8 @@ export class UserService { } } - return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -420,7 +428,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -493,7 +502,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/login`, + let localVarPath = `/user/login`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -554,7 +564,8 @@ export class UserService { } } - return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + let localVarPath = `/user/logout`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, responseType: responseType_, @@ -631,10 +642,11 @@ export class UserService { } } - return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, - user, + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, { context: localVarHttpContext, + body: user, responseType: responseType_, withCredentials: this.configuration.withCredentials, headers: localVarHeaders, diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts index 6fc0f80d97..5ea92c82cb 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts @@ -1,4 +1,5 @@ import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; export interface ConfigurationParameters { /** @@ -13,7 +14,18 @@ export interface ConfigurationParameters { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -35,7 +47,18 @@ export class Configuration { accessToken?: string | (() => string); basePath?: string; withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; /** * The keys are the names in the securitySchemes section of the OpenAPI * document. They should map to the value used for authentication @@ -51,6 +74,12 @@ export class Configuration { this.basePath = configurationParameters.basePath; this.withCredentials = configurationParameters.withCredentials; this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } if (configurationParameters.credentials) { this.credentials = configurationParameters.credentials; } @@ -138,4 +167,20 @@ export class Configuration { ? value() : value; } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } } diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts index c312b70fa3..104dd3d21e 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts @@ -2,4 +2,5 @@ export * from './api/api'; export * from './model/models'; export * from './variables'; export * from './configuration'; -export * from './api.module'; \ No newline at end of file +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/param.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/.gitignore b/samples/client/petstore/typescript-angular-v14-provided-in-root/.gitignore new file mode 100644 index 0000000000..f05cc0eff3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/.gitignore @@ -0,0 +1,41 @@ +# See http://help.github.com/ignore-files/ for more about ignoring files. + +# compiled output +/dist +/tmp +/out-tsc + +# dependencies +/node_modules + +# IDEs and editors +/.idea +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# IDE - VSCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +# misc +/.sass-cache +/connect.lock +/coverage +/libpeerconnection.log +npm-debug.log +yarn-error.log +testem.log +/typings + +# System Files +.DS_Store +Thumbs.db + +.angular diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/angular.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/angular.json new file mode 100644 index 0000000000..899df27278 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/angular.json @@ -0,0 +1,111 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "newProjectRoot": "tests", + "projects": { + "test-default": { + "root": "tests/default", + "sourceRoot": "tests/default/src", + "projectType": "application", + "prefix": "app", + "schematics": {}, + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:browser", + "options": { + "aot": true, + "outputPath": "tests/default/dist", + "index": "tests/default/src/index.html", + "main": "tests/default/src/main.ts", + "polyfills": "tests/default/src/polyfills.ts", + "tsConfig": "tests/default/src/tsconfig.app.json", + "assets": [ + "tests/default/src/favicon.ico", + "tests/default/src/assets" + ], + "styles": [ + "tests/default/src/styles.css" + ], + "scripts": [] + }, + "configurations": { + "production": { + "budgets": [ + { + "type": "anyComponentStyle", + "maximumWarning": "6kb" + } + ], + "fileReplacements": [ + { + "replace": "tests/default/src/environments/environment.ts", + "with": "tests/default/src/environments/environment.prod.ts" + } + ], + "optimization": true, + "outputHashing": "all", + "sourceMap": false, + "namedChunks": false, + "aot": true, + "extractLicenses": true, + "vendorChunk": false, + "buildOptimizer": true + }, + "development": {} + }, + "defaultConfiguration": "production" + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + }, + "configurations": { + "production": { + "browserTarget": "test-default:build:production" + }, + "development": { + "browserTarget": "test-default:build:development" + } + }, + "defaultConfiguration": "development" + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "browserTarget": "test-default:build" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "main": "tests/default/src/test.ts", + "polyfills": "tests/default/src/polyfills.ts", + "tsConfig": "tests/default/src/tsconfig.spec.json", + "karmaConfig": "tests/default/src/karma.conf.js", + "styles": [ + "tests/default/src/styles.css" + ], + "scripts": [], + "assets": [ + "tests/default/src/favicon.ico", + "tests/default/src/assets" + ] + } + }, + "lint": { + "builder": "@angular-devkit/build-angular:tslint", + "options": { + "tsConfig": [ + "tests/default/src/tsconfig.app.json", + "tests/default/src/tsconfig.spec.json" + ], + "exclude": [ + "**/node_modules/**" + ] + } + } + } + } + }, + "defaultProject": "test-default" +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.gitignore b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.gitignore new file mode 100644 index 0000000000..149b576547 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator-ignore b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator-ignore similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator-ignore rename to samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator-ignore diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/FILES new file mode 100644 index 0000000000..6e213a61aa --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/FILES @@ -0,0 +1,20 @@ +.gitignore +README.md +api.module.ts +api/api.ts +api/pet.service.ts +api/store.service.ts +api/user.service.ts +configuration.ts +encoder.ts +git_push.sh +index.ts +model/apiResponse.ts +model/category.ts +model/models.ts +model/order.ts +model/pet.ts +model/tag.ts +model/user.ts +param.ts +variables.ts diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/README.md b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/README.md new file mode 100644 index 0000000000..de16f95a8b --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/README.md @@ -0,0 +1,226 @@ +## @ + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @ --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from ''; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from ''; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from ''; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from ''; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from ''; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from ''; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from ''; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api.module.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api.module.ts new file mode 100644 index 0000000000..2afb8f64e9 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api.module.ts @@ -0,0 +1,33 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/api.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/api.ts new file mode 100644 index 0000000000..8e44b64083 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/pet.service.ts new file mode 100644 index 0000000000..c27a2e8f8e --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/pet.service.ts @@ -0,0 +1,734 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { ApiResponse } from '../model/apiResponse'; +// @ts-ignore +import { Pet } from '../model/pet'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class PetService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public addPet(pet: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public addPet(pet: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public addPet(pet: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public addPet(pet: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (pet === null || pet === undefined) { + throw new Error('Required parameter pet was null or undefined when calling addPet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: pet, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + let localVarHeaders = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + localVarHeaders = localVarHeaders.set('api_key', String(apiKey)); + } + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (status) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + [...status].join(COLLECTION_FORMATS['csv']), 'status'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/findByStatus`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + * @deprecated + */ + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (tags) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + [...tags].join(COLLECTION_FORMATS['csv']), 'tags'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/findByTags`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePet(pet: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public updatePet(pet: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public updatePet(pet: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public updatePet(pet: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (pet === null || pet === undefined) { + throw new Error('Required parameter pet was null or undefined when calling updatePet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: pet, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (name !== undefined) { + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; + } + if (status !== undefined) { + localVarFormParams = localVarFormParams.append('status', status) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (additionalMetadata !== undefined) { + localVarFormParams = localVarFormParams.append('additionalMetadata', additionalMetadata) as any || localVarFormParams; + } + if (file !== undefined) { + localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/store.service.ts new file mode 100644 index 0000000000..2aa584617f --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/store.service.ts @@ -0,0 +1,344 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { Order } from '../model/order'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class StoreService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/inventory`; + return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public placeOrder(order: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public placeOrder(order: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(order: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(order: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (order === null || order === undefined) { + throw new Error('Required parameter order was null or undefined when calling placeOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/order`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: order, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/user.service.ts new file mode 100644 index 0000000000..62cbf7b6e8 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/api/user.service.ts @@ -0,0 +1,659 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { User } from '../model/user'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class UserService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUser(user: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUser(user: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(user: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(user: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: user, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithArrayInput(user: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithArrayInput(user: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(user: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(user: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUsersWithArrayInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/createWithArray`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: user, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithListInput(user: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithListInput(user: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(user: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(user: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUsersWithListInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/createWithList`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: user, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (username !== undefined && username !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + username, 'username'); + } + if (password !== undefined && password !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + password, 'password'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/login`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs out current logged in user session + * + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/logout`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param user Updated user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateUser(username: string, user: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updateUser(username: string, user: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, user: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, user: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling updateUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: user, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/configuration.ts new file mode 100644 index 0000000000..5ea92c82cb --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/configuration.ts @@ -0,0 +1,186 @@ +import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + + // init default api_key credential + if (!this.credentials['api_key']) { + this.credentials['api_key'] = () => { + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } + }; + } + + // init default petstore_auth credential + if (!this.credentials['petstore_auth']) { + this.credentials['petstore_auth'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/encoder.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/encoder.ts new file mode 100644 index 0000000000..138c4d5cf2 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/git_push.sh b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/index.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/index.ts new file mode 100644 index 0000000000..104dd3d21e --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/index.ts @@ -0,0 +1,6 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/apiResponse.ts new file mode 100644 index 0000000000..682ba47892 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/apiResponse.ts @@ -0,0 +1,22 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/category.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/category.ts new file mode 100644 index 0000000000..b988b6827a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/category.ts @@ -0,0 +1,21 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/models.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/models.ts new file mode 100644 index 0000000000..8607c5dabd --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/order.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/order.ts new file mode 100644 index 0000000000..a29bebe490 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/order.ts @@ -0,0 +1,37 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: string; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/pet.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/pet.ts new file mode 100644 index 0000000000..e0404395f9 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/pet.ts @@ -0,0 +1,39 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/tag.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/tag.ts new file mode 100644 index 0000000000..b6ff210e8d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/tag.ts @@ -0,0 +1,21 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/user.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/user.ts new file mode 100644 index 0000000000..fce5100530 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/model/user.ts @@ -0,0 +1,30 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/param.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/variables.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/variables.ts new file mode 100644 index 0000000000..6fe58549f3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/.gitignore b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/.gitignore new file mode 100644 index 0000000000..149b576547 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/README.md b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/README.md new file mode 100644 index 0000000000..000c51d694 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/README.md @@ -0,0 +1,203 @@ +## @openapitools/typescript-angular-petstore@1.0.0 + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @openapitools/typescript-angular-petstore@1.0.0 --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link @openapitools/typescript-angular-petstore +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from '@openapitools/typescript-angular-petstore'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from '@openapitools/typescript-angular-petstore'; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from '@openapitools/typescript-angular-petstore'; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from '@openapitools/typescript-angular-petstore'; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from '@openapitools/typescript-angular-petstore'; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from '@openapitools/typescript-angular-petstore'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from '@openapitools/typescript-angular-petstore'; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api.module.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api.module.ts new file mode 100644 index 0000000000..2afb8f64e9 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api.module.ts @@ -0,0 +1,33 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/api.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/api.ts new file mode 100644 index 0000000000..8e44b64083 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/pet.service.ts new file mode 100644 index 0000000000..af8f8e65ca --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/pet.service.ts @@ -0,0 +1,722 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { ApiResponse } from '../model/apiResponse'; +// @ts-ignore +import { Pet } from '../model/pet'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class PetService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public addPet(pet: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public addPet(pet: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public addPet(pet: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public addPet(pet: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (pet === null || pet === undefined) { + throw new Error('Required parameter pet was null or undefined when calling addPet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.post(`${this.configuration.basePath}/pet`, + pet, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + let localVarHeaders = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + localVarHeaders = localVarHeaders.set('api_key', String(apiKey)); + } + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (status) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + status.join(COLLECTION_FORMATS['csv']), 'status'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + * @deprecated + */ + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (tags) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + tags.join(COLLECTION_FORMATS['csv']), 'tags'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePet(pet: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public updatePet(pet: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public updatePet(pet: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public updatePet(pet: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (pet === null || pet === undefined) { + throw new Error('Required parameter pet was null or undefined when calling updatePet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.put(`${this.configuration.basePath}/pet`, + pet, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (name !== undefined) { + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; + } + if (status !== undefined) { + localVarFormParams = localVarFormParams.append('status', status) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (additionalMetadata !== undefined) { + localVarFormParams = localVarFormParams.append('additionalMetadata', additionalMetadata) as any || localVarFormParams; + } + if (file !== undefined) { + localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/store.service.ts new file mode 100644 index 0000000000..cc32a52fc4 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/store.service.ts @@ -0,0 +1,336 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { Order } from '../model/order'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class StoreService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public placeOrder(order: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public placeOrder(order: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(order: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(order: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (order === null || order === undefined) { + throw new Error('Required parameter order was null or undefined when calling placeOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.post(`${this.configuration.basePath}/store/order`, + order, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/user.service.ts new file mode 100644 index 0000000000..070ed1221d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/api/user.service.ts @@ -0,0 +1,647 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { User } from '../model/user'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class UserService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUser(user: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUser(user: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(user: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(user: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.post(`${this.configuration.basePath}/user`, + user, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithArrayInput(user: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithArrayInput(user: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(user: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(user: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUsersWithArrayInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, + user, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithListInput(user: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithListInput(user: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(user: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(user: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUsersWithListInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, + user, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (username !== undefined && username !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + username, 'username'); + } + if (password !== undefined && password !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + password, 'password'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.get(`${this.configuration.basePath}/user/login`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs out current logged in user session + * + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param user Updated user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateUser(username: string, user: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updateUser(username: string, user: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, user: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, user: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling updateUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + user, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/configuration.ts new file mode 100644 index 0000000000..6fc0f80d97 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/configuration.ts @@ -0,0 +1,141 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + + // init default api_key credential + if (!this.credentials['api_key']) { + this.credentials['api_key'] = () => { + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } + }; + } + + // init default petstore_auth credential + if (!this.credentials['petstore_auth']) { + this.credentials['petstore_auth'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/encoder.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/encoder.ts new file mode 100644 index 0000000000..138c4d5cf2 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/git_push.sh b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/index.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/index.ts new file mode 100644 index 0000000000..c312b70fa3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/index.ts @@ -0,0 +1,5 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/apiResponse.ts new file mode 100644 index 0000000000..682ba47892 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/apiResponse.ts @@ -0,0 +1,22 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/category.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/category.ts new file mode 100644 index 0000000000..b988b6827a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/category.ts @@ -0,0 +1,21 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/models.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/models.ts new file mode 100644 index 0000000000..8607c5dabd --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/order.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/order.ts new file mode 100644 index 0000000000..a29bebe490 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/order.ts @@ -0,0 +1,37 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: string; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/pet.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/pet.ts new file mode 100644 index 0000000000..e0404395f9 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/pet.ts @@ -0,0 +1,39 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/tag.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/tag.ts new file mode 100644 index 0000000000..b6ff210e8d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/tag.ts @@ -0,0 +1,21 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/user.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/user.ts new file mode 100644 index 0000000000..fce5100530 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/model/user.ts @@ -0,0 +1,30 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/ng-package.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/ng-package.json new file mode 100644 index 0000000000..3b17900dc9 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/ng-package.json @@ -0,0 +1,6 @@ +{ + "$schema": "./node_modules/ng-packagr/ng-package.schema.json", + "lib": { + "entryFile": "index.ts" + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/package.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/package.json new file mode 100644 index 0000000000..4bf112ce3b --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/package.json @@ -0,0 +1,38 @@ +{ + "name": "@openapitools/typescript-angular-petstore", + "version": "1.0.0", + "description": "OpenAPI client for @openapitools/typescript-angular-petstore", + "author": "OpenAPI-Generator Contributors", + "repository": { + "type": "git", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + }, + "keywords": [ + "openapi-client", + "openapi-generator" + ], + "license": "Unlicense", + "scripts": { + "build": "ng-packagr -p ng-package.json" + }, + "peerDependencies": { + "@angular/core": "^14.0.5", + "rxjs": "^7.5.5" + }, + "devDependencies": { + "@angular/common": "^14.0.5", + "@angular/compiler": "^14.0.5", + "@angular/compiler-cli": "^14.0.5", + "@angular/core": "^14.0.5", + "@angular/platform-browser": "^14.0.5", + "ng-packagr": "^14.0.2", + "reflect-metadata": "^0.1.3", + "rxjs": "^7.5.5", + "tsickle": "^0.46.3", + "typescript": ">=4.6.0 <=4.8.0", + "zone.js": "^0.11.5" + }, + "publishConfig": { + "registry": "https://skimdb.npmjs.com/registry" + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/tsconfig.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/tsconfig.json new file mode 100644 index 0000000000..fd2abf8a2a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es6", + "module": "es6", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/variables.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/variables.ts new file mode 100644 index 0000000000..6fe58549f3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/with-npm/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/package-lock.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/package-lock.json new file mode 100644 index 0000000000..59eebec86f --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/package-lock.json @@ -0,0 +1,20981 @@ +{ + "name": "typescript-angular-v13-unit-tests", + "version": "0.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "typescript-angular-v13-unit-tests", + "version": "0.0.0", + "dependencies": { + "@angular/animations": "^13.3.4", + "@angular/common": "^13.3.4", + "@angular/compiler": "^13.3.4", + "@angular/core": "^13.3.4", + "@angular/forms": "^13.3.4", + "@angular/platform-browser": "^13.3.4", + "@angular/platform-browser-dynamic": "^13.3.4", + "@angular/router": "^13.3.4", + "core-js": "^2.5.4", + "rxjs": "^6.6.7", + "tslib": "^2.0.0", + "zone.js": "~0.11.5" + }, + "devDependencies": { + "@angular-devkit/build-angular": "^13.3.3", + "@angular/cli": "^13.3.3", + "@angular/compiler-cli": "^13.3.4", + "@angular/language-service": "^13.3.4", + "@types/jasmine": "~3.6.0", + "@types/jasminewd2": "~2.0.3", + "@types/node": "^12.11.1", + "codelyzer": "^6.0.0", + "jasmine-core": "~3.8.0", + "jasmine-spec-reporter": "~5.0.0", + "karma": "~6.3.4", + "karma-chrome-launcher": "~3.1.0", + "karma-coverage-istanbul-reporter": "~3.0.2", + "karma-jasmine": "~4.0.0", + "karma-jasmine-html-reporter": "^1.7.0", + "ts-node": "~7.0.0", + "tslint": "~6.1.0", + "typescript": "^4.6.3" + } + }, + "node_modules/@ampproject/remapping": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-1.1.1.tgz", + "integrity": "sha512-YVAcA4DKLOj296CF5SrQ8cYiMRiUGc2sqFpLxsDGWE34suHqhGP/5yMsDHKsrh8hs8I5TiRVXNwKPWQpX3iGjw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "sourcemap-codec": "1.4.8" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@angular-devkit/architect": { + "version": "0.1303.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/architect/-/architect-0.1303.3.tgz", + "integrity": "sha512-WRVVBCzLlMqRZVhZXGASHzNJK/OCAvl/DTGhlLuJDIjF7lVGnXHjtwNM8ilYZq949OnC3fly5Z61TfhbN/OHCg==", + "dev": true, + "dependencies": { + "@angular-devkit/core": "13.3.3", + "rxjs": "6.6.7" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular-devkit/build-angular": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/build-angular/-/build-angular-13.3.3.tgz", + "integrity": "sha512-iEpNF3tF+9Gw+qQKL63fPFHIvWokJdrgVU4GzENQ5QeL8zk8iYTEbH3jWogq5tWy5+VmNP/mKkasq9i78lRiYw==", + "dev": true, + "dependencies": { + "@ampproject/remapping": "1.1.1", + "@angular-devkit/architect": "0.1303.3", + "@angular-devkit/build-webpack": "0.1303.3", + "@angular-devkit/core": "13.3.3", + "@babel/core": "7.16.12", + "@babel/generator": "7.16.8", + "@babel/helper-annotate-as-pure": "7.16.7", + "@babel/plugin-proposal-async-generator-functions": "7.16.8", + "@babel/plugin-transform-async-to-generator": "7.16.8", + "@babel/plugin-transform-runtime": "7.16.10", + "@babel/preset-env": "7.16.11", + "@babel/runtime": "7.16.7", + "@babel/template": "7.16.7", + "@discoveryjs/json-ext": "0.5.6", + "@ngtools/webpack": "13.3.3", + "ansi-colors": "4.1.1", + "babel-loader": "8.2.3", + "babel-plugin-istanbul": "6.1.1", + "browserslist": "^4.9.1", + "cacache": "15.3.0", + "circular-dependency-plugin": "5.2.2", + "copy-webpack-plugin": "10.2.1", + "core-js": "3.20.3", + "critters": "0.0.16", + "css-loader": "6.5.1", + "esbuild-wasm": "0.14.22", + "glob": "7.2.0", + "https-proxy-agent": "5.0.0", + "inquirer": "8.2.0", + "jsonc-parser": "3.0.0", + "karma-source-map-support": "1.4.0", + "less": "4.1.2", + "less-loader": "10.2.0", + "license-webpack-plugin": "4.0.2", + "loader-utils": "3.2.0", + "mini-css-extract-plugin": "2.5.3", + "minimatch": "3.0.5", + "open": "8.4.0", + "ora": "5.4.1", + "parse5-html-rewriting-stream": "6.0.1", + "piscina": "3.2.0", + "postcss": "8.4.5", + "postcss-import": "14.0.2", + "postcss-loader": "6.2.1", + "postcss-preset-env": "7.2.3", + "regenerator-runtime": "0.13.9", + "resolve-url-loader": "5.0.0", + "rxjs": "6.6.7", + "sass": "1.49.9", + "sass-loader": "12.4.0", + "semver": "7.3.5", + "source-map-loader": "3.0.1", + "source-map-support": "0.5.21", + "stylus": "0.56.0", + "stylus-loader": "6.2.0", + "terser": "5.11.0", + "text-table": "0.2.0", + "tree-kill": "1.2.2", + "tslib": "2.3.1", + "webpack": "5.70.0", + "webpack-dev-middleware": "5.3.0", + "webpack-dev-server": "4.7.3", + "webpack-merge": "5.8.0", + "webpack-subresource-integrity": "5.1.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + }, + "optionalDependencies": { + "esbuild": "0.14.22" + }, + "peerDependencies": { + "@angular/compiler-cli": "^13.0.0 || ^13.3.0-rc.0", + "@angular/localize": "^13.0.0 || ^13.3.0-rc.0", + "@angular/service-worker": "^13.0.0 || ^13.3.0-rc.0", + "karma": "^6.3.0", + "ng-packagr": "^13.0.0", + "protractor": "^7.0.0", + "tailwindcss": "^2.0.0 || ^3.0.0", + "typescript": ">=4.4.3 <4.7" + }, + "peerDependenciesMeta": { + "@angular/localize": { + "optional": true + }, + "@angular/service-worker": { + "optional": true + }, + "karma": { + "optional": true + }, + "ng-packagr": { + "optional": true + }, + "protractor": { + "optional": true + }, + "tailwindcss": { + "optional": true + } + } + }, + "node_modules/@angular-devkit/build-angular/node_modules/core-js": { + "version": "3.20.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.20.3.tgz", + "integrity": "sha512-vVl8j8ph6tRS3B8qir40H7yw7voy17xL0piAjlbBUsH7WIfzoedL/ZOr1OV9FyZQLWXsayOJyV4tnRyXR85/ag==", + "dev": true, + "hasInstallScript": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/@angular-devkit/build-angular/node_modules/semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@angular-devkit/build-webpack": { + "version": "0.1303.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/build-webpack/-/build-webpack-0.1303.3.tgz", + "integrity": "sha512-v/z/YgwrAzYn1LfN9OHNxqcThyyg4LLx28hmHzDs5gyDShAK189y34EoT9uQ+lCyQrPVhP7UKACCxCdSwOEJiA==", + "dev": true, + "dependencies": { + "@angular-devkit/architect": "0.1303.3", + "rxjs": "6.6.7" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + }, + "peerDependencies": { + "webpack": "^5.30.0", + "webpack-dev-server": "^4.0.0" + } + }, + "node_modules/@angular-devkit/core": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-13.3.3.tgz", + "integrity": "sha512-lfQwY9LuVRwcNVzGmyPcwOpb3CAobP4T+c3joR1LLIPS5lzcM0oeCE2bon9N52Ktn4Q/pH98dVtjWL+jSrUADw==", + "dev": true, + "dependencies": { + "ajv": "8.9.0", + "ajv-formats": "2.1.1", + "fast-json-stable-stringify": "2.1.0", + "magic-string": "0.25.7", + "rxjs": "6.6.7", + "source-map": "0.7.3" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + }, + "peerDependencies": { + "chokidar": "^3.5.2" + }, + "peerDependenciesMeta": { + "chokidar": { + "optional": true + } + } + }, + "node_modules/@angular-devkit/core/node_modules/ajv": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.9.0.tgz", + "integrity": "sha512-qOKJyNj/h+OWx7s5DePL6Zu1KeM9jPZhwBqs+7DzP6bGOvqzVCSf0xueYmVuaC/oQ/VtS2zLMLHdQFbkka+XDQ==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@angular-devkit/core/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/@angular-devkit/schematics": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-13.3.3.tgz", + "integrity": "sha512-S8UNlw6IoR/kxBYbiwesuA7oJGSnFkD6bJwVLhpHdT6Sqrz2/IrjHcNgTJRAvhsOKIbfDtMtXRzl/PUdWEfgyw==", + "dev": true, + "dependencies": { + "@angular-devkit/core": "13.3.3", + "jsonc-parser": "3.0.0", + "magic-string": "0.25.7", + "ora": "5.4.1", + "rxjs": "6.6.7" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular/animations": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/animations/-/animations-13.3.4.tgz", + "integrity": "sha512-cXjjbzYR2hda9BDAu0teJUVbbA03jJTK53vIYnDLIAvN20YRPo9LqINxpUlbAzH6hE8v5xF2LLnAXcaQROVpIw==", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + }, + "peerDependencies": { + "@angular/core": "13.3.4" + } + }, + "node_modules/@angular/cli": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@angular/cli/-/cli-13.3.3.tgz", + "integrity": "sha512-a+nnzFP1FfnypXpAhrHbIBaJcxzegWLZUvVzJQwt6P2z60IoHdvTVmyNbY89qI0LE1SrAokEUO1zW3Yjmu7fUw==", + "dev": true, + "hasInstallScript": true, + "dependencies": { + "@angular-devkit/architect": "0.1303.3", + "@angular-devkit/core": "13.3.3", + "@angular-devkit/schematics": "13.3.3", + "@schematics/angular": "13.3.3", + "@yarnpkg/lockfile": "1.1.0", + "ansi-colors": "4.1.1", + "debug": "4.3.3", + "ini": "2.0.0", + "inquirer": "8.2.0", + "jsonc-parser": "3.0.0", + "npm-package-arg": "8.1.5", + "npm-pick-manifest": "6.1.1", + "open": "8.4.0", + "ora": "5.4.1", + "pacote": "12.0.3", + "resolve": "1.22.0", + "semver": "7.3.5", + "symbol-observable": "4.0.0", + "uuid": "8.3.2" + }, + "bin": { + "ng": "bin/ng.js" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular/cli/node_modules/semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@angular/common": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/common/-/common-13.3.4.tgz", + "integrity": "sha512-vPZuUGWMXz6r30obBqH+iIG4Feq4YEK/4wUks7PEYGke8MXFPYsNKuHMhKCgYEhabD/4Mo4GEp3i18/3Kk72Mw==", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + }, + "peerDependencies": { + "@angular/core": "13.3.4", + "rxjs": "^6.5.3 || ^7.4.0" + } + }, + "node_modules/@angular/compiler": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-13.3.4.tgz", + "integrity": "sha512-Yf1Dv2BVytjmv5Nnv05hUciUOH/UpKgXG1Ql5XwQG/qGV4eEs33PJBtGsUJTPuddxfRm72JMsbZcoRjVADqbcw==", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + } + }, + "node_modules/@angular/compiler-cli": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-13.3.4.tgz", + "integrity": "sha512-wCnt2YOS5EiwWCEv8oCqIfiwUtifs+COhcYH6fpmf/3X9w1yKO1ZMA+OsFQ0IVS4d0YYavm5DTPQ2ep2c0sF5w==", + "dev": true, + "dependencies": { + "@babel/core": "^7.17.2", + "chokidar": "^3.0.0", + "convert-source-map": "^1.5.1", + "dependency-graph": "^0.11.0", + "magic-string": "^0.26.0", + "reflect-metadata": "^0.1.2", + "semver": "^7.0.0", + "sourcemap-codec": "^1.4.8", + "tslib": "^2.3.0", + "yargs": "^17.2.1" + }, + "bin": { + "ng-xi18n": "bundles/src/bin/ng_xi18n.js", + "ngc": "bundles/src/bin/ngc.js", + "ngcc": "bundles/ngcc/main-ngcc.js" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + }, + "peerDependencies": { + "@angular/compiler": "13.3.4", + "typescript": ">=4.4.2 <4.7" + } + }, + "node_modules/@angular/compiler-cli/node_modules/@ampproject/remapping": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.1.2.tgz", + "integrity": "sha512-hoyByceqwKirw7w3Z7gnIIZC3Wx3J484Y3L/cMpXFbr7d9ZQj2mODrirNzcJa+SM3UlpWXYvKV4RlRpFXlWgXg==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@angular/compiler-cli/node_modules/@babel/core": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.17.9.tgz", + "integrity": "sha512-5ug+SfZCpDAkVp9SFIZAzlW18rlzsOcJGaetCjkySnrXXDUw9AR8cDUm1iByTmdWM6yxX6/zycaV76w3YTF2gw==", + "dev": true, + "dependencies": { + "@ampproject/remapping": "^2.1.0", + "@babel/code-frame": "^7.16.7", + "@babel/generator": "^7.17.9", + "@babel/helper-compilation-targets": "^7.17.7", + "@babel/helper-module-transforms": "^7.17.7", + "@babel/helpers": "^7.17.9", + "@babel/parser": "^7.17.9", + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.17.9", + "@babel/types": "^7.17.0", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.1", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@angular/compiler-cli/node_modules/@babel/core/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@angular/compiler-cli/node_modules/@babel/generator": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.17.9.tgz", + "integrity": "sha512-rAdDousTwxbIxbz5I7GEQ3lUip+xVCXooZNbsydCWs3xA7ZsYOv+CFRdzGxRX78BmQHu9B1Eso59AOZQOJDEdQ==", + "dev": true, + "dependencies": { + "@babel/types": "^7.17.0", + "jsesc": "^2.5.1", + "source-map": "^0.5.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@angular/compiler-cli/node_modules/magic-string": { + "version": "0.26.1", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.26.1.tgz", + "integrity": "sha512-ndThHmvgtieXe8J/VGPjG+Apu7v7ItcD5mhEIvOscWjPF/ccOiLxHaSuCAS2G+3x4GKsAbT8u7zdyamupui8Tg==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.8" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@angular/compiler-cli/node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/@angular/compiler-cli/node_modules/yargs": { + "version": "17.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.4.1.tgz", + "integrity": "sha512-WSZD9jgobAg3ZKuCQZSa3g9QOJeCCqLoLAykiWgmXnDo9EPnn4RPf5qVTtzgOx66o6/oqhcA5tHtJXpG8pMt3g==", + "dev": true, + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@angular/compiler-cli/node_modules/yargs-parser": { + "version": "21.0.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.0.1.tgz", + "integrity": "sha512-9BK1jFpLzJROCI5TzwZL/TU4gqjK5xiHV/RfWLOahrjAko/e4DJkRDZQXfvqAsiZzzYhgAzbgz6lg48jcm4GLg==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/@angular/core": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/core/-/core-13.3.4.tgz", + "integrity": "sha512-PqPwx9oaV0Bh0m0fdI2jtXUC6s04jfD4vyzB4sjEuRI9pRUnZ6M5hZ5Vn/KJVZyt411MevbJfqzUVf0W+GDZew==", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + }, + "peerDependencies": { + "rxjs": "^6.5.3 || ^7.4.0", + "zone.js": "~0.11.4" + } + }, + "node_modules/@angular/forms": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/forms/-/forms-13.3.4.tgz", + "integrity": "sha512-QHyUXOKYITysaJJ4VnmBacE69oz0rw4G7Y2lhPb2V3a1XsWeO61SZEeGMfAWo7sLoDvi2MCEWNEhl1du4dK14A==", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + }, + "peerDependencies": { + "@angular/common": "13.3.4", + "@angular/core": "13.3.4", + "@angular/platform-browser": "13.3.4", + "rxjs": "^6.5.3 || ^7.4.0" + } + }, + "node_modules/@angular/language-service": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/language-service/-/language-service-13.3.4.tgz", + "integrity": "sha512-9k2q9TJaTG2QgIDNLUVOPCdzYRXLOw4aKiHTeMeIJOw4Zhp2dV7I4oX/aC/a1AN86JIO6m5nujeVf4SkK95WSw==", + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + } + }, + "node_modules/@angular/platform-browser": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-13.3.4.tgz", + "integrity": "sha512-IjBOkjrIVIbbZCDQJRdel0FSDcExSLDgMxcCSQ6pKa6oR/t59BJpSpOhB1W9nRwLtvMmGYkS/oyLFsKk65UoYA==", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + }, + "peerDependencies": { + "@angular/animations": "13.3.4", + "@angular/common": "13.3.4", + "@angular/core": "13.3.4" + }, + "peerDependenciesMeta": { + "@angular/animations": { + "optional": true + } + } + }, + "node_modules/@angular/platform-browser-dynamic": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/platform-browser-dynamic/-/platform-browser-dynamic-13.3.4.tgz", + "integrity": "sha512-UApjgrL6B3QTdSYoCOPzMvFDmSewAHrLpreLYEmADutMWkD0ZcTPux4MJp8awT4P3l6wKzBeGJIKLlk8zsXmGQ==", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + }, + "peerDependencies": { + "@angular/common": "13.3.4", + "@angular/compiler": "13.3.4", + "@angular/core": "13.3.4", + "@angular/platform-browser": "13.3.4" + } + }, + "node_modules/@angular/router": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/router/-/router-13.3.4.tgz", + "integrity": "sha512-UuMAjWHoFKF8b9gFOiqL7fpVXjIr89BtxVES3yXReVq/IZJz9gWup6lYK3KMja+F8HZB8LBUMYgtqjS9iyLV/Q==", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0" + }, + "peerDependencies": { + "@angular/common": "13.3.4", + "@angular/core": "13.3.4", + "@angular/platform-browser": "13.3.4", + "rxjs": "^6.5.3 || ^7.4.0" + } + }, + "node_modules/@assemblyscript/loader": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@assemblyscript/loader/-/loader-0.10.1.tgz", + "integrity": "sha512-H71nDOOL8Y7kWRLqf6Sums+01Q5msqBW2KhDUTemh1tvY04eSkSXrK0uj/4mmY0Xr16/3zyZmsrxN7CKuRbNRg==", + "dev": true + }, + "node_modules/@babel/code-frame": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.7.tgz", + "integrity": "sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg==", + "dev": true, + "dependencies": { + "@babel/highlight": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.17.7.tgz", + "integrity": "sha512-p8pdE6j0a29TNGebNm7NzYZWB3xVZJBZ7XGs42uAKzQo8VQ3F0By/cQCtUEABwIqw5zo6WA4NbmxsfzADzMKnQ==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.16.12", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.16.12.tgz", + "integrity": "sha512-dK5PtG1uiN2ikk++5OzSYsitZKny4wOCD0nrO4TqnW4BVBTQ2NGS3NgilvT/TEyxTST7LNyWV/T4tXDoD3fOgg==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.16.7", + "@babel/generator": "^7.16.8", + "@babel/helper-compilation-targets": "^7.16.7", + "@babel/helper-module-transforms": "^7.16.7", + "@babel/helpers": "^7.16.7", + "@babel/parser": "^7.16.12", + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.16.10", + "@babel/types": "^7.16.8", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.1.2", + "semver": "^6.3.0", + "source-map": "^0.5.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/core/node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/@babel/generator": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.16.8.tgz", + "integrity": "sha512-1ojZwE9+lOXzcWdWmO6TbUzDfqLD39CmEhN8+2cX9XkDo5yW1OpgfejfliysR2AWLpMamTiOiAp/mtroaymhpw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.16.8", + "jsesc": "^2.5.1", + "source-map": "^0.5.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/generator/node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.16.7.tgz", + "integrity": "sha512-s6t2w/IPQVTAET1HitoowRGXooX8mCgtuP5195wD/QJPV6wYjpujCGF7JuMODVX2ZAJOf1GT6DT9MHEZvLOFSw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-builder-binary-assignment-operator-visitor": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.16.7.tgz", + "integrity": "sha512-C6FdbRaxYjwVu/geKW4ZeQ0Q31AftgRcdSnZ5/jsH6BzCJbtvXvhpfkbkThYSuutZA7nCXpPR6AD9zd1dprMkA==", + "dev": true, + "dependencies": { + "@babel/helper-explode-assignable-expression": "^7.16.7", + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.17.7.tgz", + "integrity": "sha512-UFzlz2jjd8kroj0hmCFV5zr+tQPi1dpC2cRsDV/3IEW8bJfCPrPpmcSN6ZS8RqIq4LXcmpipCQFPddyFA5Yc7w==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.17.7", + "@babel/helper-validator-option": "^7.16.7", + "browserslist": "^4.17.5", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-create-class-features-plugin": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.17.9.tgz", + "integrity": "sha512-kUjip3gruz6AJKOq5i3nC6CoCEEF/oHH3cp6tOZhB+IyyyPyW0g1Gfsxn3mkk6S08pIA2y8GQh609v9G/5sHVQ==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-function-name": "^7.17.9", + "@babel/helper-member-expression-to-functions": "^7.17.7", + "@babel/helper-optimise-call-expression": "^7.16.7", + "@babel/helper-replace-supers": "^7.16.7", + "@babel/helper-split-export-declaration": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-create-regexp-features-plugin": { + "version": "7.17.0", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.17.0.tgz", + "integrity": "sha512-awO2So99wG6KnlE+TPs6rn83gCz5WlEePJDTnLEqbchMVrBeAujURVphRdigsk094VhvZehFoNOihSlcBjwsXA==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "regexpu-core": "^5.0.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-define-polyfill-provider": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.3.1.tgz", + "integrity": "sha512-J9hGMpJQmtWmj46B3kBHmL38UhJGhYX7eqkcq+2gsstyYt341HmPeWspihX43yVRA0mS+8GGk2Gckc7bY/HCmA==", + "dev": true, + "dependencies": { + "@babel/helper-compilation-targets": "^7.13.0", + "@babel/helper-module-imports": "^7.12.13", + "@babel/helper-plugin-utils": "^7.13.0", + "@babel/traverse": "^7.13.0", + "debug": "^4.1.1", + "lodash.debounce": "^4.0.8", + "resolve": "^1.14.2", + "semver": "^6.1.2" + }, + "peerDependencies": { + "@babel/core": "^7.4.0-0" + } + }, + "node_modules/@babel/helper-define-polyfill-provider/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-environment-visitor": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.16.7.tgz", + "integrity": "sha512-SLLb0AAn6PkUeAfKJCCOl9e1R53pQlGAfc4y4XuMRZfqeMYLE0dM1LMhqbGAlGQY0lfw5/ohoYWAe9V1yibRag==", + "dev": true, + "dependencies": { + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-explode-assignable-expression": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.16.7.tgz", + "integrity": "sha512-KyUenhWMC8VrxzkGP0Jizjo4/Zx+1nNZhgocs+gLzyZyB8SHidhoq9KK/8Ato4anhwsivfkBLftky7gvzbZMtQ==", + "dev": true, + "dependencies": { + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-function-name": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.17.9.tgz", + "integrity": "sha512-7cRisGlVtiVqZ0MW0/yFB4atgpGLWEHUVYnb448hZK4x+vih0YO5UoS11XIYtZYqHd0dIPMdUSv8q5K4LdMnIg==", + "dev": true, + "dependencies": { + "@babel/template": "^7.16.7", + "@babel/types": "^7.17.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-hoist-variables": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.16.7.tgz", + "integrity": "sha512-m04d/0Op34H5v7pbZw6pSKP7weA6lsMvfiIAMeIvkY/R4xQtBSMFEigu9QTZ2qB/9l22vsxtM8a+Q8CzD255fg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-member-expression-to-functions": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.17.7.tgz", + "integrity": "sha512-thxXgnQ8qQ11W2wVUObIqDL4p148VMxkt5T/qpN5k2fboRyzFGFmKsTGViquyM5QHKUy48OZoca8kw4ajaDPyw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.17.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.16.7.tgz", + "integrity": "sha512-LVtS6TqjJHFc+nYeITRo6VLXve70xmq7wPhWTqDJusJEgGmkAACWwMiTNrvfoQo6hEhFwAIixNkvB0jPXDL8Wg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.17.7.tgz", + "integrity": "sha512-VmZD99F3gNTYB7fJRDTi+u6l/zxY0BE6OIxPSU7a50s6ZUQkHwSDmV92FfM+oCG0pZRVojGYhkR8I0OGeCVREw==", + "dev": true, + "dependencies": { + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-module-imports": "^7.16.7", + "@babel/helper-simple-access": "^7.17.7", + "@babel/helper-split-export-declaration": "^7.16.7", + "@babel/helper-validator-identifier": "^7.16.7", + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.17.3", + "@babel/types": "^7.17.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-optimise-call-expression": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.16.7.tgz", + "integrity": "sha512-EtgBhg7rd/JcnpZFXpBy0ze1YRfdm7BnBX4uKMBd3ixa3RGAE002JZB66FJyNH7g0F38U05pXmA5P8cBh7z+1w==", + "dev": true, + "dependencies": { + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.16.7.tgz", + "integrity": "sha512-Qg3Nk7ZxpgMrsox6HreY1ZNKdBq7K72tDSliA6dCl5f007jR4ne8iD5UzuNnCJH2xBf2BEEVGr+/OL6Gdp7RxA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-remap-async-to-generator": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.16.8.tgz", + "integrity": "sha512-fm0gH7Flb8H51LqJHy3HJ3wnE1+qtYR2A99K06ahwrawLdOFsCEWjZOrYricXJHoPSudNKxrMBUPEIPxiIIvBw==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "@babel/helper-wrap-function": "^7.16.8", + "@babel/types": "^7.16.8" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-replace-supers": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.16.7.tgz", + "integrity": "sha512-y9vsWilTNaVnVh6xiJfABzsNpgDPKev9HnAgz6Gb1p6UUwf9NepdlsV7VXGCftJM+jqD5f7JIEubcpLjZj5dBw==", + "dev": true, + "dependencies": { + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-member-expression-to-functions": "^7.16.7", + "@babel/helper-optimise-call-expression": "^7.16.7", + "@babel/traverse": "^7.16.7", + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-simple-access": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.17.7.tgz", + "integrity": "sha512-txyMCGroZ96i+Pxr3Je3lzEJjqwaRC9buMUgtomcrLe5Nd0+fk1h0LLA+ixUF5OW7AhHuQ7Es1WcQJZmZsz2XA==", + "dev": true, + "dependencies": { + "@babel/types": "^7.17.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-skip-transparent-expression-wrappers": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.16.0.tgz", + "integrity": "sha512-+il1gTy0oHwUsBQZyJvukbB4vPMdcYBrFHa0Uc4AizLxbq6BOYC51Rv4tWocX9BLBDLZ4kc6qUFpQ6HRgL+3zw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.16.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-split-export-declaration": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.16.7.tgz", + "integrity": "sha512-xbWoy/PFoxSWazIToT9Sif+jJTlrMcndIsaOKvTA6u7QEo7ilkRZpjew18/W3c7nm8fXdUDXh02VXTbZ0pGDNw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.16.7.tgz", + "integrity": "sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.16.7.tgz", + "integrity": "sha512-TRtenOuRUVo9oIQGPC5G9DgK4743cdxvtOw0weQNpZXaS16SCBi5MNjZF8vba3ETURjZpTbVn7Vvcf2eAwFozQ==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-wrap-function": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.16.8.tgz", + "integrity": "sha512-8RpyRVIAW1RcDDGTA+GpPAwV22wXCfKOoM9bet6TLkGIFTkRQSkH1nMQ5Yet4MpoXe1ZwHPVtNasc2w0uZMqnw==", + "dev": true, + "dependencies": { + "@babel/helper-function-name": "^7.16.7", + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.16.8", + "@babel/types": "^7.16.8" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.17.9.tgz", + "integrity": "sha512-cPCt915ShDWUEzEp3+UNRktO2n6v49l5RSnG9M5pS24hA+2FAc5si+Pn1i4VVbQQ+jh+bIZhPFQOJOzbrOYY1Q==", + "dev": true, + "dependencies": { + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.17.9", + "@babel/types": "^7.17.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.10.tgz", + "integrity": "sha512-5FnTQLSLswEj6IkgVw5KusNUUFY9ZGqe/TRFnP/BKYHYgfh7tc+C7mwiy95/yNP7Dh9x580Vv8r7u7ZfTBFxdw==", + "dev": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.16.7", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.17.9.tgz", + "integrity": "sha512-vqUSBLP8dQHFPdPi9bc5GK9vRkYHJ49fsZdtoJ8EQ8ibpwk5rPKfvNIwChB0KVXcIjcepEBBd2VHC5r9Gy8ueg==", + "dev": true, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.16.7.tgz", + "integrity": "sha512-anv/DObl7waiGEnC24O9zqL0pSuI9hljihqiDuFHC8d7/bjr/4RLGPWuc8rYOff/QPzbEPSkzG8wGG9aDuhHRg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-7.16.7.tgz", + "integrity": "sha512-di8vUHRdf+4aJ7ltXhaDbPoszdkh59AQtJM5soLsuHpQJdFQZOA4uGj0V2u/CZ8bJ/u8ULDL5yq6FO/bCXnKHw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.16.0", + "@babel/plugin-proposal-optional-chaining": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.13.0" + } + }, + "node_modules/@babel/plugin-proposal-async-generator-functions": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.16.8.tgz", + "integrity": "sha512-71YHIvMuiuqWJQkebWJtdhQTfd4Q4mF76q2IX37uZPkG9+olBxsX+rH1vkhFto4UeJZ9dPY2s+mDvhDm1u2BGQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-remap-async-to-generator": "^7.16.8", + "@babel/plugin-syntax-async-generators": "^7.8.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-class-properties": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.16.7.tgz", + "integrity": "sha512-IobU0Xme31ewjYOShSIqd/ZGM/r/cuOz2z0MDbNrhF5FW+ZVgi0f2lyeoj9KFPDOAqsYxmLWZte1WOwlvY9aww==", + "dev": true, + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-class-static-block": { + "version": "7.17.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-class-static-block/-/plugin-proposal-class-static-block-7.17.6.tgz", + "integrity": "sha512-X/tididvL2zbs7jZCeeRJ8167U/+Ac135AM6jCAx6gYXDUviZV5Ku9UDvWS2NCuWlFjIRXklYhwo6HhAC7ETnA==", + "dev": true, + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.17.6", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-class-static-block": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.12.0" + } + }, + "node_modules/@babel/plugin-proposal-dynamic-import": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-dynamic-import/-/plugin-proposal-dynamic-import-7.16.7.tgz", + "integrity": "sha512-I8SW9Ho3/8DRSdmDdH3gORdyUuYnk1m4cMxUAdu5oy4n3OfN8flDEH+d60iG7dUfi0KkYwSvoalHzzdRzpWHTg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-dynamic-import": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-export-namespace-from": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-export-namespace-from/-/plugin-proposal-export-namespace-from-7.16.7.tgz", + "integrity": "sha512-ZxdtqDXLRGBL64ocZcs7ovt71L3jhC1RGSyR996svrCi3PYqHNkb3SwPJCs8RIzD86s+WPpt2S73+EHCGO+NUA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-export-namespace-from": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-json-strings": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.16.7.tgz", + "integrity": "sha512-lNZ3EEggsGY78JavgbHsK9u5P3pQaW7k4axlgFLYkMd7UBsiNahCITShLjNQschPyjtO6dADrL24757IdhBrsQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-json-strings": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-logical-assignment-operators": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-logical-assignment-operators/-/plugin-proposal-logical-assignment-operators-7.16.7.tgz", + "integrity": "sha512-K3XzyZJGQCr00+EtYtrDjmwX7o7PLK6U9bi1nCwkQioRFVUv6dJoxbQjtWVtP+bCPy82bONBKG8NPyQ4+i6yjg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-nullish-coalescing-operator": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.16.7.tgz", + "integrity": "sha512-aUOrYU3EVtjf62jQrCj63pYZ7k6vns2h/DQvHPWGmsJRYzWXZ6/AsfgpiRy6XiuIDADhJzP2Q9MwSMKauBQ+UQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-numeric-separator": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-numeric-separator/-/plugin-proposal-numeric-separator-7.16.7.tgz", + "integrity": "sha512-vQgPMknOIgiuVqbokToyXbkY/OmmjAzr/0lhSIbG/KmnzXPGwW/AdhdKpi+O4X/VkWiWjnkKOBiqJrTaC98VKw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-numeric-separator": "^7.10.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-object-rest-spread": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.17.3.tgz", + "integrity": "sha512-yuL5iQA/TbZn+RGAfxQXfi7CNLmKi1f8zInn4IgobuCWcAb7i+zj4TYzQ9l8cEzVyJ89PDGuqxK1xZpUDISesw==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.17.0", + "@babel/helper-compilation-targets": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-transform-parameters": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-optional-catch-binding": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.16.7.tgz", + "integrity": "sha512-eMOH/L4OvWSZAE1VkHbr1vckLG1WUcHGJSLqqQwl2GaUqG6QjddvrOaTUMNYiv77H5IKPMZ9U9P7EaHwvAShfA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-optional-chaining": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.16.7.tgz", + "integrity": "sha512-eC3xy+ZrUcBtP7x+sq62Q/HYd674pPTb/77XZMb5wbDPGWIdUbSr4Agr052+zaUPSb+gGRnjxXfKFvx5iMJ+DA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.16.0", + "@babel/plugin-syntax-optional-chaining": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-private-methods": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-methods/-/plugin-proposal-private-methods-7.16.11.tgz", + "integrity": "sha512-F/2uAkPlXDr8+BHpZvo19w3hLFKge+k75XUprE6jaqKxjGkSYcK+4c+bup5PdW/7W/Rpjwql7FTVEDW+fRAQsw==", + "dev": true, + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.16.10", + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-private-property-in-object": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.16.7.tgz", + "integrity": "sha512-rMQkjcOFbm+ufe3bTZLyOfsOUOxyvLXZJCTARhJr+8UMSoZmqTe1K1BgkFcrW37rAchWg57yI69ORxiWvUINuQ==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "@babel/helper-create-class-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-proposal-unicode-property-regex": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-unicode-property-regex/-/plugin-proposal-unicode-property-regex-7.16.7.tgz", + "integrity": "sha512-QRK0YI/40VLhNVGIjRNAAQkEHws0cswSdFFjpFyt943YmJIU1da9uW63Iu6NFV6CxTZW5eTDCrwZUstBWgp/Rg==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-static-block": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", + "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-dynamic-import": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz", + "integrity": "sha512-5gdGbFon+PszYzqs83S3E5mpi7/y/8M9eC90MRTZfduQOYW76ig6SOSPNe41IG5LoP3FGBn2N0RjVDSQiS94kQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-export-namespace-from": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-export-namespace-from/-/plugin-syntax-export-namespace-from-7.8.3.tgz", + "integrity": "sha512-MXf5laXo6c1IbEbegDmzGPwGNTsHZmEy6QGznu5Sh2UCWvueywb2ee+CCE4zQiZstxU9BMoQO9i6zUFSY0Kj0Q==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.3" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-private-property-in-object": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", + "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-arrow-functions": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.16.7.tgz", + "integrity": "sha512-9ffkFFMbvzTvv+7dTp/66xvZAWASuPD5Tl9LK3Z9vhOmANo6j94rik+5YMBt4CwHVMWLWpMsriIc2zsa3WW3xQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-async-to-generator": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.16.8.tgz", + "integrity": "sha512-MtmUmTJQHCnyJVrScNzNlofQJ3dLFuobYn3mwOTKHnSCMtbNsqvF71GQmJfFjdrXSsAA7iysFmYWw4bXZ20hOg==", + "dev": true, + "dependencies": { + "@babel/helper-module-imports": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-remap-async-to-generator": "^7.16.8" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoped-functions": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.16.7.tgz", + "integrity": "sha512-JUuzlzmF40Z9cXyytcbZEZKckgrQzChbQJw/5PuEHYeqzCsvebDx0K0jWnIIVcmmDOAVctCgnYs0pMcrYj2zJg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoping": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.16.7.tgz", + "integrity": "sha512-ObZev2nxVAYA4bhyusELdo9hb3H+A56bxH3FZMbEImZFiEDYVHXQSJ1hQKFlDnlt8G9bBrCZ5ZpURZUrV4G5qQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-classes": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.16.7.tgz", + "integrity": "sha512-WY7og38SFAGYRe64BrjKf8OrE6ulEHtr5jEYaZMwox9KebgqPi67Zqz8K53EKk1fFEJgm96r32rkKZ3qA2nCWQ==", + "dev": true, + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-function-name": "^7.16.7", + "@babel/helper-optimise-call-expression": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-replace-supers": "^7.16.7", + "@babel/helper-split-export-declaration": "^7.16.7", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-computed-properties": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.16.7.tgz", + "integrity": "sha512-gN72G9bcmenVILj//sv1zLNaPyYcOzUho2lIJBMh/iakJ9ygCo/hEF9cpGb61SCMEDxbbyBoVQxrt+bWKu5KGw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-destructuring": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.17.7.tgz", + "integrity": "sha512-XVh0r5yq9sLR4vZ6eVZe8FKfIcSgaTBxVBRSYokRj2qksf6QerYnTxz9/GTuKTH/n/HwLP7t6gtlybHetJ/6hQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-dotall-regex": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.16.7.tgz", + "integrity": "sha512-Lyttaao2SjZF6Pf4vk1dVKv8YypMpomAbygW+mU5cYP3S5cWTfCJjG8xV6CFdzGFlfWK81IjL9viiTvpb6G7gQ==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-duplicate-keys": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.16.7.tgz", + "integrity": "sha512-03DvpbRfvWIXyK0/6QiR1KMTWeT6OcQ7tbhjrXyFS02kjuX/mu5Bvnh5SDSWHxyawit2g5aWhKwI86EE7GUnTw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-exponentiation-operator": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.16.7.tgz", + "integrity": "sha512-8UYLSlyLgRixQvlYH3J2ekXFHDFLQutdy7FfFAMm3CPZ6q9wHCwnUyiXpQCe3gVVnQlHc5nsuiEVziteRNTXEA==", + "dev": true, + "dependencies": { + "@babel/helper-builder-binary-assignment-operator-visitor": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-for-of": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.16.7.tgz", + "integrity": "sha512-/QZm9W92Ptpw7sjI9Nx1mbcsWz33+l8kuMIQnDwgQBG5s3fAfQvkRjQ7NqXhtNcKOnPkdICmUHyCaWW06HCsqg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-function-name": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.16.7.tgz", + "integrity": "sha512-SU/C68YVwTRxqWj5kgsbKINakGag0KTgq9f2iZEXdStoAbOzLHEBRYzImmA6yFo8YZhJVflvXmIHUO7GWHmxxA==", + "dev": true, + "dependencies": { + "@babel/helper-compilation-targets": "^7.16.7", + "@babel/helper-function-name": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-literals": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.16.7.tgz", + "integrity": "sha512-6tH8RTpTWI0s2sV6uq3e/C9wPo4PTqqZps4uF0kzQ9/xPLFQtipynvmT1g/dOfEJ+0EQsHhkQ/zyRId8J2b8zQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-member-expression-literals": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.16.7.tgz", + "integrity": "sha512-mBruRMbktKQwbxaJof32LT9KLy2f3gH+27a5XSuXo6h7R3vqltl0PgZ80C8ZMKw98Bf8bqt6BEVi3svOh2PzMw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-amd": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.16.7.tgz", + "integrity": "sha512-KaaEtgBL7FKYwjJ/teH63oAmE3lP34N3kshz8mm4VMAw7U3PxjVwwUmxEFksbgsNUaO3wId9R2AVQYSEGRa2+g==", + "dev": true, + "dependencies": { + "@babel/helper-module-transforms": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "babel-plugin-dynamic-import-node": "^2.3.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-commonjs": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.17.9.tgz", + "integrity": "sha512-2TBFd/r2I6VlYn0YRTz2JdazS+FoUuQ2rIFHoAxtyP/0G3D82SBLaRq9rnUkpqlLg03Byfl/+M32mpxjO6KaPw==", + "dev": true, + "dependencies": { + "@babel/helper-module-transforms": "^7.17.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-simple-access": "^7.17.7", + "babel-plugin-dynamic-import-node": "^2.3.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-systemjs": { + "version": "7.17.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.17.8.tgz", + "integrity": "sha512-39reIkMTUVagzgA5x88zDYXPCMT6lcaRKs1+S9K6NKBPErbgO/w/kP8GlNQTC87b412ZTlmNgr3k2JrWgHH+Bw==", + "dev": true, + "dependencies": { + "@babel/helper-hoist-variables": "^7.16.7", + "@babel/helper-module-transforms": "^7.17.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-validator-identifier": "^7.16.7", + "babel-plugin-dynamic-import-node": "^2.3.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-umd": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.16.7.tgz", + "integrity": "sha512-EMh7uolsC8O4xhudF2F6wedbSHm1HHZ0C6aJ7K67zcDNidMzVcxWdGr+htW9n21klm+bOn+Rx4CBsAntZd3rEQ==", + "dev": true, + "dependencies": { + "@babel/helper-module-transforms": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.16.8.tgz", + "integrity": "sha512-j3Jw+n5PvpmhRR+mrgIh04puSANCk/T/UA3m3P1MjJkhlK906+ApHhDIqBQDdOgL/r1UYpz4GNclTXxyZrYGSw==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-new-target": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.16.7.tgz", + "integrity": "sha512-xiLDzWNMfKoGOpc6t3U+etCE2yRnn3SM09BXqWPIZOBpL2gvVrBWUKnsJx0K/ADi5F5YC5f8APFfWrz25TdlGg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-object-super": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.16.7.tgz", + "integrity": "sha512-14J1feiQVWaGvRxj2WjyMuXS2jsBkgB3MdSN5HuC2G5nRspa5RK9COcs82Pwy5BuGcjb+fYaUj94mYcOj7rCvw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-replace-supers": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-parameters": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.16.7.tgz", + "integrity": "sha512-AT3MufQ7zZEhU2hwOA11axBnExW0Lszu4RL/tAlUJBuNoRak+wehQW8h6KcXOcgjY42fHtDxswuMhMjFEuv/aw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-property-literals": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.16.7.tgz", + "integrity": "sha512-z4FGr9NMGdoIl1RqavCqGG+ZuYjfZ/hkCIeuH6Do7tXmSm0ls11nYVSJqFEUOSJbDab5wC6lRE/w6YjVcr6Hqw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-regenerator": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.17.9.tgz", + "integrity": "sha512-Lc2TfbxR1HOyn/c6b4Y/b6NHoTb67n/IoWLxTu4kC7h4KQnWlhCq2S8Tx0t2SVvv5Uu87Hs+6JEJ5kt2tYGylQ==", + "dev": true, + "dependencies": { + "regenerator-transform": "^0.15.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-reserved-words": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.16.7.tgz", + "integrity": "sha512-KQzzDnZ9hWQBjwi5lpY5v9shmm6IVG0U9pB18zvMu2i4H90xpT4gmqwPYsn8rObiadYe2M0gmgsiOIF5A/2rtg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-runtime": { + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.16.10.tgz", + "integrity": "sha512-9nwTiqETv2G7xI4RvXHNfpGdr8pAA+Q/YtN3yLK7OoK7n9OibVm/xymJ838a9A6E/IciOLPj82lZk0fW6O4O7w==", + "dev": true, + "dependencies": { + "@babel/helper-module-imports": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "babel-plugin-polyfill-corejs2": "^0.3.0", + "babel-plugin-polyfill-corejs3": "^0.5.0", + "babel-plugin-polyfill-regenerator": "^0.3.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-runtime/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/plugin-transform-shorthand-properties": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.16.7.tgz", + "integrity": "sha512-hah2+FEnoRoATdIb05IOXf+4GzXYTq75TVhIn1PewihbpyrNWUt2JbudKQOETWw6QpLe+AIUpJ5MVLYTQbeeUg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-spread": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.16.7.tgz", + "integrity": "sha512-+pjJpgAngb53L0iaA5gU/1MLXJIfXcYepLgXB3esVRf4fqmj8f2cxM3/FKaHsZms08hFQJkFccEWuIpm429TXg==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.16.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-sticky-regex": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.16.7.tgz", + "integrity": "sha512-NJa0Bd/87QV5NZZzTuZG5BPJjLYadeSZ9fO6oOUoL4iQx+9EEuw/eEM92SrsT19Yc2jgB1u1hsjqDtH02c3Drw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-template-literals": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.16.7.tgz", + "integrity": "sha512-VwbkDDUeenlIjmfNeDX/V0aWrQH2QiVyJtwymVQSzItFDTpxfyJh3EVaQiS0rIN/CqbLGr0VcGmuwyTdZtdIsA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typeof-symbol": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.16.7.tgz", + "integrity": "sha512-p2rOixCKRJzpg9JB4gjnG4gjWkWa89ZoYUnl9snJ1cWIcTH/hvxZqfO+WjG6T8DRBpctEol5jw1O5rA8gkCokQ==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-escapes": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.16.7.tgz", + "integrity": "sha512-TAV5IGahIz3yZ9/Hfv35TV2xEm+kaBDaZQCn2S/hG9/CZ0DktxJv9eKfPc7yYCvOYR4JGx1h8C+jcSOvgaaI/Q==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-regex": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.16.7.tgz", + "integrity": "sha512-oC5tYYKw56HO75KZVLQ+R/Nl3Hro9kf8iG0hXoaHP7tjAyCpvqBiSNe6vGrZni1Z6MggmUOC6A7VP7AVmw225Q==", + "dev": true, + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/preset-env": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.16.11.tgz", + "integrity": "sha512-qcmWG8R7ZW6WBRPZK//y+E3Cli151B20W1Rv7ln27vuPaXU/8TKms6jFdiJtF7UDTxcrb7mZd88tAeK9LjdT8g==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.16.8", + "@babel/helper-compilation-targets": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-validator-option": "^7.16.7", + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.16.7", + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.16.7", + "@babel/plugin-proposal-async-generator-functions": "^7.16.8", + "@babel/plugin-proposal-class-properties": "^7.16.7", + "@babel/plugin-proposal-class-static-block": "^7.16.7", + "@babel/plugin-proposal-dynamic-import": "^7.16.7", + "@babel/plugin-proposal-export-namespace-from": "^7.16.7", + "@babel/plugin-proposal-json-strings": "^7.16.7", + "@babel/plugin-proposal-logical-assignment-operators": "^7.16.7", + "@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.7", + "@babel/plugin-proposal-numeric-separator": "^7.16.7", + "@babel/plugin-proposal-object-rest-spread": "^7.16.7", + "@babel/plugin-proposal-optional-catch-binding": "^7.16.7", + "@babel/plugin-proposal-optional-chaining": "^7.16.7", + "@babel/plugin-proposal-private-methods": "^7.16.11", + "@babel/plugin-proposal-private-property-in-object": "^7.16.7", + "@babel/plugin-proposal-unicode-property-regex": "^7.16.7", + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-dynamic-import": "^7.8.3", + "@babel/plugin-syntax-export-namespace-from": "^7.8.3", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5", + "@babel/plugin-transform-arrow-functions": "^7.16.7", + "@babel/plugin-transform-async-to-generator": "^7.16.8", + "@babel/plugin-transform-block-scoped-functions": "^7.16.7", + "@babel/plugin-transform-block-scoping": "^7.16.7", + "@babel/plugin-transform-classes": "^7.16.7", + "@babel/plugin-transform-computed-properties": "^7.16.7", + "@babel/plugin-transform-destructuring": "^7.16.7", + "@babel/plugin-transform-dotall-regex": "^7.16.7", + "@babel/plugin-transform-duplicate-keys": "^7.16.7", + "@babel/plugin-transform-exponentiation-operator": "^7.16.7", + "@babel/plugin-transform-for-of": "^7.16.7", + "@babel/plugin-transform-function-name": "^7.16.7", + "@babel/plugin-transform-literals": "^7.16.7", + "@babel/plugin-transform-member-expression-literals": "^7.16.7", + "@babel/plugin-transform-modules-amd": "^7.16.7", + "@babel/plugin-transform-modules-commonjs": "^7.16.8", + "@babel/plugin-transform-modules-systemjs": "^7.16.7", + "@babel/plugin-transform-modules-umd": "^7.16.7", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.16.8", + "@babel/plugin-transform-new-target": "^7.16.7", + "@babel/plugin-transform-object-super": "^7.16.7", + "@babel/plugin-transform-parameters": "^7.16.7", + "@babel/plugin-transform-property-literals": "^7.16.7", + "@babel/plugin-transform-regenerator": "^7.16.7", + "@babel/plugin-transform-reserved-words": "^7.16.7", + "@babel/plugin-transform-shorthand-properties": "^7.16.7", + "@babel/plugin-transform-spread": "^7.16.7", + "@babel/plugin-transform-sticky-regex": "^7.16.7", + "@babel/plugin-transform-template-literals": "^7.16.7", + "@babel/plugin-transform-typeof-symbol": "^7.16.7", + "@babel/plugin-transform-unicode-escapes": "^7.16.7", + "@babel/plugin-transform-unicode-regex": "^7.16.7", + "@babel/preset-modules": "^0.1.5", + "@babel/types": "^7.16.8", + "babel-plugin-polyfill-corejs2": "^0.3.0", + "babel-plugin-polyfill-corejs3": "^0.5.0", + "babel-plugin-polyfill-regenerator": "^0.3.0", + "core-js-compat": "^3.20.2", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/preset-env/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/preset-modules": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.5.tgz", + "integrity": "sha512-A57th6YRG7oR3cq/yt/Y84MvGgE0eJG2F1JLhKuyG+jFxEgrd/HAMJatiFtmOiZurz+0DkrvbheCLaV5f2JfjA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/plugin-proposal-unicode-property-regex": "^7.4.4", + "@babel/plugin-transform-dotall-regex": "^7.4.4", + "@babel/types": "^7.4.4", + "esutils": "^2.0.2" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.16.7.tgz", + "integrity": "sha512-9E9FJowqAsytyOY6LG+1KuueckRL+aQW+mKvXRXnuFGyRAyepJPmEo9vgMfXUA6O9u3IeEdv9MAkppFcaQwogQ==", + "dev": true, + "dependencies": { + "regenerator-runtime": "^0.13.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.16.7.tgz", + "integrity": "sha512-I8j/x8kHUrbYRTUxXrrMbfCa7jxkE7tZre39x3kjr9hvI82cK1FfqLygotcWN5kdPGWcLdWMHpSBavse5tWw3w==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.16.7", + "@babel/parser": "^7.16.7", + "@babel/types": "^7.16.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.17.9.tgz", + "integrity": "sha512-PQO8sDIJ8SIwipTPiR71kJQCKQYB5NGImbOviK8K+kg5xkNSYXLBupuX9QhatFowrsvo9Hj8WgArg3W7ijNAQw==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.16.7", + "@babel/generator": "^7.17.9", + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-function-name": "^7.17.9", + "@babel/helper-hoist-variables": "^7.16.7", + "@babel/helper-split-export-declaration": "^7.16.7", + "@babel/parser": "^7.17.9", + "@babel/types": "^7.17.0", + "debug": "^4.1.0", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse/node_modules/@babel/generator": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.17.9.tgz", + "integrity": "sha512-rAdDousTwxbIxbz5I7GEQ3lUip+xVCXooZNbsydCWs3xA7ZsYOv+CFRdzGxRX78BmQHu9B1Eso59AOZQOJDEdQ==", + "dev": true, + "dependencies": { + "@babel/types": "^7.17.0", + "jsesc": "^2.5.1", + "source-map": "^0.5.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse/node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/@babel/types": { + "version": "7.17.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.17.0.tgz", + "integrity": "sha512-TmKSNO4D5rzhL5bjWFcVHHLETzfQ/AmbKpKPOSjlP0WoHZ6L911fgoOKY4Alp/emzG4cHJdyN49zpgkbXFEHHw==", + "dev": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.16.7", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@colors/colors": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", + "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", + "dev": true, + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/@csstools/postcss-progressive-custom-properties": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@csstools/postcss-progressive-custom-properties/-/postcss-progressive-custom-properties-1.3.0.tgz", + "integrity": "sha512-ASA9W1aIy5ygskZYuWams4BzafD12ULvSypmaLJT2jvQ8G0M3I8PRQhC0h7mG0Z3LI05+agZjqSR9+K9yaQQjA==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.3" + } + }, + "node_modules/@discoveryjs/json-ext": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.5.6.tgz", + "integrity": "sha512-ws57AidsDvREKrZKYffXddNkyaF14iHNHm8VQnZH6t99E8gczjNN0GpvcGny0imC80yQ0tHz1xVUKk/KFQSUyA==", + "dev": true, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@gar/promisify": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.3.tgz", + "integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==", + "dev": true + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.0.6.tgz", + "integrity": "sha512-R7xHtBSNm+9SyvpJkdQl+qrM3Hm2fea3Ef197M3mUug+v+yR+Rhfbs7PBtcBUVnIWJ4JcAdjvij+c8hXS9p5aw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.11", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.11.tgz", + "integrity": "sha512-Fg32GrJo61m+VqYSdRSjRXMjQ06j8YIYfcTqndLYVAaHmroZHLJZCydsWBOTDqXS2v+mjxohBWEMfg97GXmYQg==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@ngtools/webpack": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@ngtools/webpack/-/webpack-13.3.3.tgz", + "integrity": "sha512-O6EzafKfFuvI3Ju941u7ANs0mT7YDdChbVRhVECCPWOTm3Klr73js3bnCDzaJlxZNjzlG/KeUu5ghrhbMrHjSw==", + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + }, + "peerDependencies": { + "@angular/compiler-cli": "^13.0.0", + "typescript": ">=4.4.3 <4.7", + "webpack": "^5.30.0" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@npmcli/fs": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-1.1.1.tgz", + "integrity": "sha512-8KG5RD0GVP4ydEzRn/I4BNDuxDtqVbOdm8675T49OIG/NGhaK0pjPX7ZcDlvKYbA+ulvVK3ztfcF4uBdOxuJbQ==", + "dev": true, + "dependencies": { + "@gar/promisify": "^1.0.1", + "semver": "^7.3.5" + } + }, + "node_modules/@npmcli/git": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-2.1.0.tgz", + "integrity": "sha512-/hBFX/QG1b+N7PZBFs0bi+evgRZcK9nWBxQKZkGoXUT5hJSwl5c4d7y8/hm+NQZRPhQ67RzFaj5UM9YeyKoryw==", + "dev": true, + "dependencies": { + "@npmcli/promise-spawn": "^1.3.2", + "lru-cache": "^6.0.0", + "mkdirp": "^1.0.4", + "npm-pick-manifest": "^6.1.1", + "promise-inflight": "^1.0.1", + "promise-retry": "^2.0.1", + "semver": "^7.3.5", + "which": "^2.0.2" + } + }, + "node_modules/@npmcli/git/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@npmcli/installed-package-contents": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-1.0.7.tgz", + "integrity": "sha512-9rufe0wnJusCQoLpV9ZPKIVP55itrM5BxOXs10DmdbRfgWtHy1LDyskbwRnBghuB0PrF7pNPOqREVtpz4HqzKw==", + "dev": true, + "dependencies": { + "npm-bundled": "^1.1.1", + "npm-normalize-package-bin": "^1.0.1" + }, + "bin": { + "installed-package-contents": "index.js" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/@npmcli/move-file": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@npmcli/move-file/-/move-file-1.1.2.tgz", + "integrity": "sha512-1SUf/Cg2GzGDyaf15aR9St9TWlb+XvbZXWpDx8YKs7MLzMH/BCeopv+y9vzrzgkfykCGuWOlSu3mZhj2+FQcrg==", + "dev": true, + "dependencies": { + "mkdirp": "^1.0.4", + "rimraf": "^3.0.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@npmcli/node-gyp": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@npmcli/node-gyp/-/node-gyp-1.0.3.tgz", + "integrity": "sha512-fnkhw+fmX65kiLqk6E3BFLXNC26rUhK90zVwe2yncPliVT/Qos3xjhTLE59Df8KnPlcwIERXKVlU1bXoUQ+liA==", + "dev": true + }, + "node_modules/@npmcli/promise-spawn": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-1.3.2.tgz", + "integrity": "sha512-QyAGYo/Fbj4MXeGdJcFzZ+FkDkomfRBrPM+9QYJSg+PxgAUL+LU3FneQk37rKR2/zjqkCV1BLHccX98wRXG3Sg==", + "dev": true, + "dependencies": { + "infer-owner": "^1.0.4" + } + }, + "node_modules/@npmcli/run-script": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-2.0.0.tgz", + "integrity": "sha512-fSan/Pu11xS/TdaTpTB0MRn9guwGU8dye+x56mEVgBEd/QsybBbYcAL0phPXi8SGWFEChkQd6M9qL4y6VOpFig==", + "dev": true, + "dependencies": { + "@npmcli/node-gyp": "^1.0.2", + "@npmcli/promise-spawn": "^1.3.2", + "node-gyp": "^8.2.0", + "read-package-json-fast": "^2.0.1" + } + }, + "node_modules/@schematics/angular": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-13.3.3.tgz", + "integrity": "sha512-kX5ghVCmWHcMN+g0pUaFuIJzwrXsVnK4bfid8DckU4EEtfFSv3UA5I1QNJRgpCPxTPhNEAk+3ePN8nzDSjdU+w==", + "dev": true, + "dependencies": { + "@angular-devkit/core": "13.3.3", + "@angular-devkit/schematics": "13.3.3", + "jsonc-parser": "3.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.15.0 || >=16.10.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@socket.io/base64-arraybuffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@socket.io/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz", + "integrity": "sha512-dOlCBKnDw4iShaIsH/bxujKTM18+2TOAsYz+KSc11Am38H4q5Xw8Bbz97ZYdrVNM+um3p7w86Bvvmcn9q+5+eQ==", + "dev": true, + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/@tootallnate/once": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", + "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==", + "dev": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.2.tgz", + "integrity": "sha512-ALYone6pm6QmwZoAgeyNksccT9Q4AWZQ6PvfwR37GT6r6FWUPguq6sUmNGSMV2Wr761oQoBxwGGa6DR5o1DC9g==", + "dev": true, + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/bonjour": { + "version": "3.5.10", + "resolved": "https://registry.npmjs.org/@types/bonjour/-/bonjour-3.5.10.tgz", + "integrity": "sha512-p7ienRMiS41Nu2/igbJxxLDWrSZ0WxM8UQgCeO9KhoVF7cOVFkrKsiDr1EsJIla8vV3oEEjGcz11jc5yimhzZw==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/component-emitter": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/@types/component-emitter/-/component-emitter-1.2.11.tgz", + "integrity": "sha512-SRXjM+tfsSlA9VuG8hGO2nft2p8zjXCK1VcC6N4NXbBbYbSia9kzCChYQajIjzIqOOOuh5Ock6MmV2oux4jDZQ==", + "dev": true + }, + "node_modules/@types/connect": { + "version": "3.4.35", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.35.tgz", + "integrity": "sha512-cdeYyv4KWoEgpBISTxWvqYsVy444DOqehiF3fM3ne10AmJ62RSyNkUnxMJXHQWRQQX2eR94m5y1IZyDwBjV9FQ==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/connect-history-api-fallback": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/connect-history-api-fallback/-/connect-history-api-fallback-1.3.5.tgz", + "integrity": "sha512-h8QJa8xSb1WD4fpKBDcATDNGXghFj6/3GRWG6dhmRcu0RX1Ubasur2Uvx5aeEwlf0MwblEC2bMzzMQntxnw/Cw==", + "dev": true, + "dependencies": { + "@types/express-serve-static-core": "*", + "@types/node": "*" + } + }, + "node_modules/@types/cookie": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz", + "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==", + "dev": true + }, + "node_modules/@types/cors": { + "version": "2.8.12", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.12.tgz", + "integrity": "sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==", + "dev": true + }, + "node_modules/@types/eslint": { + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.1.tgz", + "integrity": "sha512-GE44+DNEyxxh2Kc6ro/VkIj+9ma0pO0bwv9+uHSyBrikYOHr8zYcdPvnBOp1aw8s+CjRvuSx7CyWqRrNFQ59mA==", + "dev": true, + "dependencies": { + "@types/estree": "*", + "@types/json-schema": "*" + } + }, + "node_modules/@types/eslint-scope": { + "version": "3.7.3", + "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.3.tgz", + "integrity": "sha512-PB3ldyrcnAicT35TWPs5IcwKD8S333HMaa2VVv4+wdvebJkjWuW/xESoB8IwRcog8HYVYamb1g/R31Qv5Bx03g==", + "dev": true, + "dependencies": { + "@types/eslint": "*", + "@types/estree": "*" + } + }, + "node_modules/@types/estree": { + "version": "0.0.51", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.51.tgz", + "integrity": "sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ==", + "dev": true + }, + "node_modules/@types/express": { + "version": "4.17.13", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.13.tgz", + "integrity": "sha512-6bSZTPaTIACxn48l50SR+axgrqm6qXFIxrdAKaG6PaJk3+zuUr35hBlgT7vOmJcum+OEaIBLtHV/qloEAFITeA==", + "dev": true, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.18", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.17.28", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.17.28.tgz", + "integrity": "sha512-P1BJAEAW3E2DJUlkgq4tOL3RyMunoWXqbSCygWo5ZIWTjUgN1YnaXWW4VWl/oc8vs/XoYibEGBKP0uZyF4AHig==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*" + } + }, + "node_modules/@types/http-proxy": { + "version": "1.17.8", + "resolved": "https://registry.npmjs.org/@types/http-proxy/-/http-proxy-1.17.8.tgz", + "integrity": "sha512-5kPLG5BKpWYkw/LVOGWpiq3nEVqxiN32rTgI53Sk12/xHFQ2rG3ehI9IO+O3W2QoKeyB92dJkoka8SUm6BX1pA==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/jasmine": { + "version": "3.6.11", + "resolved": "https://registry.npmjs.org/@types/jasmine/-/jasmine-3.6.11.tgz", + "integrity": "sha512-S6pvzQDvMZHrkBz2Mcn/8Du7cpr76PlRJBAoHnSDNbulULsH5dp0Gns+WRyNX5LHejz/ljxK4/vIHK/caHt6SQ==", + "dev": true + }, + "node_modules/@types/jasminewd2": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/@types/jasminewd2/-/jasminewd2-2.0.10.tgz", + "integrity": "sha512-J7mDz7ovjwjc+Y9rR9rY53hFWKATcIkrr9DwQWmOas4/pnIPJTXawnzjwpHm3RSxz/e3ZVUvQ7cRbd5UQLo10g==", + "dev": true, + "dependencies": { + "@types/jasmine": "*" + } + }, + "node_modules/@types/json-schema": { + "version": "7.0.9", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz", + "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==", + "dev": true + }, + "node_modules/@types/mime": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.2.tgz", + "integrity": "sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw==", + "dev": true + }, + "node_modules/@types/node": { + "version": "12.20.46", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.20.46.tgz", + "integrity": "sha512-cPjLXj8d6anFPzFvOPxS3fvly3Shm5nTfl6g8X5smexixbuGUf7hfr21J5tX9JW+UPStp/5P5R8qrKL5IyVJ+A==", + "dev": true + }, + "node_modules/@types/parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==", + "dev": true + }, + "node_modules/@types/qs": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.7.tgz", + "integrity": "sha512-FGa1F62FT09qcrueBA6qYTrJPVDzah9a+493+o2PCXsesWHIn27G98TsSMs3WPNbZIEj4+VJf6saSFpvD+3Zsw==", + "dev": true + }, + "node_modules/@types/range-parser": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.4.tgz", + "integrity": "sha512-EEhsLsD6UsDM1yFhAvy0Cjr6VwmpMWqFBCb9w07wVugF7w9nfajxLuVmngTIpgS6svCnm6Vaw+MZhoDCKnOfsw==", + "dev": true + }, + "node_modules/@types/retry": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.1.tgz", + "integrity": "sha512-xoDlM2S4ortawSWORYqsdU+2rxdh4LRW9ytc3zmT37RIKQh6IHyKwwtKhKis9ah8ol07DCkZxPt8BBvPjC6v4g==", + "dev": true + }, + "node_modules/@types/serve-index": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@types/serve-index/-/serve-index-1.9.1.tgz", + "integrity": "sha512-d/Hs3nWDxNL2xAczmOVZNj92YZCS6RGxfBPjKzuu/XirCgXdpKEb88dYNbrYGint6IVWLNP+yonwVAuRC0T2Dg==", + "dev": true, + "dependencies": { + "@types/express": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.13.10", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.13.10.tgz", + "integrity": "sha512-nCkHGI4w7ZgAdNkrEu0bv+4xNV/XDqW+DydknebMOQwkpDGx8G+HTlj7R7ABI8i8nKxVw0wtKPi1D+lPOkh4YQ==", + "dev": true, + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/sockjs": { + "version": "0.3.33", + "resolved": "https://registry.npmjs.org/@types/sockjs/-/sockjs-0.3.33.tgz", + "integrity": "sha512-f0KEEe05NvUnat+boPTZ0dgaLZ4SfSouXUgv5noUiefG2ajgKjmETo9ZJyuqsl7dfl2aHlLJUiki6B4ZYldiiw==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/ws": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.3.tgz", + "integrity": "sha512-6YOoWjruKj1uLf3INHH7D3qTXwFfEsg1kf3c0uDdSBJwfa/llkwIjrAGV7j7mVgGNbzTQ3HiHKKDXl6bJPD97w==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.1.tgz", + "integrity": "sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw==", + "dev": true, + "dependencies": { + "@webassemblyjs/helper-numbers": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz", + "integrity": "sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz", + "integrity": "sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz", + "integrity": "sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz", + "integrity": "sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ==", + "dev": true, + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.11.1", + "@webassemblyjs/helper-api-error": "1.11.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz", + "integrity": "sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q==", + "dev": true + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz", + "integrity": "sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz", + "integrity": "sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ==", + "dev": true, + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.1.tgz", + "integrity": "sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw==", + "dev": true, + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.1.tgz", + "integrity": "sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ==", + "dev": true + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz", + "integrity": "sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/helper-wasm-section": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1", + "@webassemblyjs/wasm-opt": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1", + "@webassemblyjs/wast-printer": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz", + "integrity": "sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/ieee754": "1.11.1", + "@webassemblyjs/leb128": "1.11.1", + "@webassemblyjs/utf8": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz", + "integrity": "sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz", + "integrity": "sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-api-error": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/ieee754": "1.11.1", + "@webassemblyjs/leb128": "1.11.1", + "@webassemblyjs/utf8": "1.11.1" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz", + "integrity": "sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg==", + "dev": true, + "dependencies": { + "@webassemblyjs/ast": "1.11.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true + }, + "node_modules/@yarnpkg/lockfile": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", + "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", + "dev": true + }, + "node_modules/abab": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", + "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", + "dev": true + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "dev": true + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dev": true, + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.7.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.1.tgz", + "integrity": "sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-assertions": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz", + "integrity": "sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw==", + "dev": true, + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/adjust-sourcemap-loader": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/adjust-sourcemap-loader/-/adjust-sourcemap-loader-4.0.0.tgz", + "integrity": "sha512-OXwN5b9pCUXNQHJpwwD2qP40byEmSgzj8B4ydSN0uMNYWiFmJ6x6KwUllMmfk8Rwu/HJDFR7U8ubsWBoN0Xp0A==", + "dev": true, + "dependencies": { + "loader-utils": "^2.0.0", + "regex-parser": "^2.2.11" + }, + "engines": { + "node": ">=8.9" + } + }, + "node_modules/adjust-sourcemap-loader/node_modules/loader-utils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.2.tgz", + "integrity": "sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A==", + "dev": true, + "dependencies": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^2.1.2" + }, + "engines": { + "node": ">=8.9.0" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/agentkeepalive": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.2.1.tgz", + "integrity": "sha512-Zn4cw2NEqd+9fiSVWMscnjyQ1a8Yfoc5oBajLeo5w+YBHgDUcEBY2hS4YpTz6iN5f/2zQiktcuM6tS8x1p9dpA==", + "dev": true, + "dependencies": { + "debug": "^4.1.0", + "depd": "^1.1.2", + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/aggregate-error": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "dev": true, + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "dev": true, + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-formats/node_modules/ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "dev": true, + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/ansi-colors": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", + "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-html-community": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/ansi-html-community/-/ansi-html-community-0.0.8.tgz", + "integrity": "sha512-1APHAyr3+PCamwNw3bXCPp4HFLONZt/yIH0sZp0/469KWNTEy+qN5jQ3GVX6DMZ1UXAi34yVwtTeaG/HpBuuzw==", + "dev": true, + "engines": [ + "node >= 0.8.0" + ], + "bin": { + "ansi-html": "bin/ansi-html" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/anymatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", + "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/app-root-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/app-root-path/-/app-root-path-3.0.0.tgz", + "integrity": "sha512-qMcx+Gy2UZynHjOHOIXPNvpf+9cjvk3cWrBBK7zg4gH9+clobJRb9NGzcT7mQTcV/6Gm/1WelUtqxVXnNlrwcw==", + "dev": true, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==", + "dev": true + }, + "node_modules/are-we-there-yet": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-3.0.0.tgz", + "integrity": "sha512-0GWpv50YSOcLXaN6/FAKY3vfRbllXWV2xvfA/oKJF8pzFhWXPV+yjhJXDBbjscDYowv7Yw1A3uigpzn5iEGTyw==", + "dev": true, + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/argparse/node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "node_modules/aria-query": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-3.0.0.tgz", + "integrity": "sha1-ZbP8wcoRVajJrmTW7uKX8V1RM8w=", + "dev": true, + "dependencies": { + "ast-types-flow": "0.0.7", + "commander": "^2.11.0" + } + }, + "node_modules/array-flatten": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-2.1.2.tgz", + "integrity": "sha512-hNfzcOV8W4NdualtqBFPyVO+54DSJuZGY9qT4pRroB6S9e3iiido2ISIC5h9R2sPJ8H3FHCIiEnsv1lPXO3KtQ==", + "dev": true + }, + "node_modules/array-union": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-3.0.1.tgz", + "integrity": "sha512-1OvF9IbWwaeiM9VhzYXVQacMibxpXOMYVNIvMtKRyX9SImBXpKcFr8XvFDeEslCyuH/t6KRt7HEO94AlP8Iatw==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ast-types-flow": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.7.tgz", + "integrity": "sha1-9wtzXGvKGlycItmCw+Oef+ujva0=", + "dev": true + }, + "node_modules/async": { + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", + "integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==", + "dev": true, + "dependencies": { + "lodash": "^4.17.14" + } + }, + "node_modules/atob": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", + "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", + "dev": true, + "bin": { + "atob": "bin/atob.js" + }, + "engines": { + "node": ">= 4.5.0" + } + }, + "node_modules/autoprefixer": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.5.tgz", + "integrity": "sha512-Fvd8yCoA7lNX/OUllvS+aS1I7WRBclGXsepbvT8ZaPgrH24rgXpZzF0/6Hh3ZEkwg+0AES/Osd196VZmYoEFtw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + } + ], + "dependencies": { + "browserslist": "^4.20.2", + "caniuse-lite": "^1.0.30001332", + "fraction.js": "^4.2.0", + "normalize-range": "^0.1.2", + "picocolors": "^1.0.0", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/axobject-query": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-2.0.2.tgz", + "integrity": "sha512-MCeek8ZH7hKyO1rWUbKNQBbl4l2eY0ntk7OGi+q0RlafrCnfPxC06WZA+uebCfmYp4mNU9jRBP1AhGyf8+W3ww==", + "dev": true, + "dependencies": { + "ast-types-flow": "0.0.7" + } + }, + "node_modules/babel-loader": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.2.3.tgz", + "integrity": "sha512-n4Zeta8NC3QAsuyiizu0GkmRcQ6clkV9WFUnUf1iXP//IeSKbWjofW3UHyZVwlOB4y039YQKefawyTn64Zwbuw==", + "dev": true, + "dependencies": { + "find-cache-dir": "^3.3.1", + "loader-utils": "^1.4.0", + "make-dir": "^3.1.0", + "schema-utils": "^2.6.5" + }, + "engines": { + "node": ">= 8.9" + }, + "peerDependencies": { + "@babel/core": "^7.0.0", + "webpack": ">=2" + } + }, + "node_modules/babel-loader/node_modules/json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/babel-loader/node_modules/loader-utils": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz", + "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==", + "dev": true, + "dependencies": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^1.0.1" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/babel-plugin-dynamic-import-node": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.3.tgz", + "integrity": "sha512-jZVI+s9Zg3IqA/kdi0i6UDCybUI3aSBLnglhYbSSjKlV7yF1F/5LWv8MakQmvYpnbJDS6fcBL2KzHSxNCMtWSQ==", + "dev": true, + "dependencies": { + "object.assign": "^4.1.0" + } + }, + "node_modules/babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-polyfill-corejs2": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.3.1.tgz", + "integrity": "sha512-v7/T6EQcNfVLfcN2X8Lulb7DjprieyLWJK/zOWH5DUYcAgex9sP3h25Q+DLsX9TloXe3y1O8l2q2Jv9q8UVB9w==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.13.11", + "@babel/helper-define-polyfill-provider": "^0.3.1", + "semver": "^6.1.1" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/babel-plugin-polyfill-corejs2/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/babel-plugin-polyfill-corejs3": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.5.2.tgz", + "integrity": "sha512-G3uJih0XWiID451fpeFaYGVuxHEjzKTHtc9uGFEjR6hHrvNzeS/PX+LLLcetJcytsB5m4j+K3o/EpXJNb/5IEQ==", + "dev": true, + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.3.1", + "core-js-compat": "^3.21.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/babel-plugin-polyfill-regenerator": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.3.1.tgz", + "integrity": "sha512-Y2B06tvgHYt1x0yz17jGkGeeMr5FeKUu+ASJ+N6nB5lQ8Dapfg42i0OVrf8PNGJ3zKL4A23snMi1IRwrqqND7A==", + "dev": true, + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.3.1" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", + "dev": true, + "engines": { + "node": "^4.5.0 || >= 5.9" + } + }, + "node_modules/batch": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz", + "integrity": "sha1-3DQxT05nkxgJP8dgJyUl+UvyXBY=", + "dev": true + }, + "node_modules/big.js": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", + "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", + "dev": true, + "engines": { + "node": "*" + } + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/body-parser": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.0.tgz", + "integrity": "sha512-DfJ+q6EPcGKZD1QWUjSpqp+Q7bDQTsQIF4zfUAtZ6qk+H/3/QRhg9CEp39ss+/T2vw0+HaidC0ecJj/DRLIaKg==", + "dev": true, + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.10.3", + "raw-body": "2.5.1", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/body-parser/node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/bonjour": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/bonjour/-/bonjour-3.5.0.tgz", + "integrity": "sha1-jokKGD2O6aI5OzhExpGkK897yfU=", + "dev": true, + "dependencies": { + "array-flatten": "^2.1.0", + "deep-equal": "^1.0.1", + "dns-equal": "^1.0.0", + "dns-txt": "^2.0.2", + "multicast-dns": "^6.0.1", + "multicast-dns-service-types": "^1.1.0" + } + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=", + "dev": true + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.20.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.20.3.tgz", + "integrity": "sha512-NBhymBQl1zM0Y5dQT/O+xiLP9/rzOIQdKM/eMJBAq7yBgaB6krIYLGejrwVYnSHZdqjscB1SPuAjHwxjvN6Wdg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], + "dependencies": { + "caniuse-lite": "^1.0.30001332", + "electron-to-chromium": "^1.4.118", + "escalade": "^3.1.1", + "node-releases": "^2.0.3", + "picocolors": "^1.0.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "node_modules/buffer-indexof": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-indexof/-/buffer-indexof-1.1.1.tgz", + "integrity": "sha512-4/rOEg86jivtPTeOUUT61jJO1Ya1TrR/OkqCSZDyq84WJh3LuuiphBYJN+fm5xufIk4XAFcEwte/8WzC8If/1g==", + "dev": true + }, + "node_modules/builtin-modules": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", + "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/builtins": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/builtins/-/builtins-1.0.3.tgz", + "integrity": "sha1-y5T662HIaWRR2zZTThQi+U8K7og=", + "dev": true + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cacache": { + "version": "15.3.0", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-15.3.0.tgz", + "integrity": "sha512-VVdYzXEn+cnbXpFgWs5hTT7OScegHVmLhJIR8Ufqk3iFD6A6j5iSX1KuBTfNEv4tdJWE2PzA6IVFtcLC7fN9wQ==", + "dev": true, + "dependencies": { + "@npmcli/fs": "^1.0.0", + "@npmcli/move-file": "^1.0.1", + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "glob": "^7.1.4", + "infer-owner": "^1.0.4", + "lru-cache": "^6.0.0", + "minipass": "^3.1.1", + "minipass-collect": "^1.0.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.2", + "mkdirp": "^1.0.3", + "p-map": "^4.0.0", + "promise-inflight": "^1.0.1", + "rimraf": "^3.0.2", + "ssri": "^8.0.1", + "tar": "^6.0.2", + "unique-filename": "^1.1.1" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001332", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001332.tgz", + "integrity": "sha512-10T30NYOEQtN6C11YGg411yebhvpnC6Z102+B95eAsN0oB6KUs01ivE8u+G6FMIRtIrVlYXhL+LUwQ3/hXwDWw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + } + ] + }, + "node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/chrome-trace-event": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz", + "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", + "dev": true, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/circular-dependency-plugin": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/circular-dependency-plugin/-/circular-dependency-plugin-5.2.2.tgz", + "integrity": "sha512-g38K9Cm5WRwlaH6g03B9OEz/0qRizI+2I7n+Gz+L5DxXJAPAiWQvwlYNm1V1jkdpUv95bOe/ASm2vfi/G560jQ==", + "dev": true, + "engines": { + "node": ">=6.0.0" + }, + "peerDependencies": { + "webpack": ">=4.0.1" + } + }, + "node_modules/clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-spinners": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.6.1.tgz", + "integrity": "sha512-x/5fWmGMnbKQAaNwN+UZlV79qBLM9JFnJuJ03gIi5whrob0xV0ofNVHy9DhwGdsMJQc2OKv0oGmLzvaqvAVv+g==", + "dev": true, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-width": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", + "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "dev": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dev": true, + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", + "dev": true, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/clone-deep": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz", + "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", + "dev": true, + "dependencies": { + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.2", + "shallow-clone": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/codelyzer": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/codelyzer/-/codelyzer-6.0.2.tgz", + "integrity": "sha512-v3+E0Ucu2xWJMOJ2fA/q9pDT/hlxHftHGPUay1/1cTgyPV5JTHFdO9hqo837Sx2s9vKBMTt5gO+lhF95PO6J+g==", + "dev": true, + "dependencies": { + "@angular/compiler": "9.0.0", + "@angular/core": "9.0.0", + "app-root-path": "^3.0.0", + "aria-query": "^3.0.0", + "axobject-query": "2.0.2", + "css-selector-tokenizer": "^0.7.1", + "cssauron": "^1.4.0", + "damerau-levenshtein": "^1.0.4", + "rxjs": "^6.5.3", + "semver-dsl": "^1.0.1", + "source-map": "^0.5.7", + "sprintf-js": "^1.1.2", + "tslib": "^1.10.0", + "zone.js": "~0.10.3" + }, + "peerDependencies": { + "@angular/compiler": ">=2.3.1 <13.0.0 || ^12.0.0-next || ^12.1.0-next || ^12.2.0-next", + "@angular/core": ">=2.3.1 <13.0.0 || ^12.0.0-next || ^12.1.0-next || ^12.2.0-next", + "tslint": "^5.0.0 || ^6.0.0" + } + }, + "node_modules/codelyzer/node_modules/@angular/compiler": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-9.0.0.tgz", + "integrity": "sha512-ctjwuntPfZZT2mNj2NDIVu51t9cvbhl/16epc5xEwyzyDt76pX9UgwvY+MbXrf/C/FWwdtmNtfP698BKI+9leQ==", + "dev": true, + "peerDependencies": { + "tslib": "^1.10.0" + } + }, + "node_modules/codelyzer/node_modules/@angular/core": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@angular/core/-/core-9.0.0.tgz", + "integrity": "sha512-6Pxgsrf0qF9iFFqmIcWmjJGkkCaCm6V5QNnxMy2KloO3SDq6QuMVRbN9RtC8Urmo25LP+eZ6ZgYqFYpdD8Hd9w==", + "dev": true, + "peerDependencies": { + "rxjs": "^6.5.3", + "tslib": "^1.10.0", + "zone.js": "~0.10.2" + } + }, + "node_modules/codelyzer/node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/codelyzer/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, + "node_modules/codelyzer/node_modules/zone.js": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.10.3.tgz", + "integrity": "sha512-LXVLVEq0NNOqK/fLJo3d0kfzd4sxwn2/h67/02pjCjfKDxgx1i9QqpvtHD8CrBnSSwMw5+dy11O7FRX5mkO7Cg==", + "dev": true + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "dev": true, + "bin": { + "color-support": "bin.js" + } + }, + "node_modules/colorette": { + "version": "2.0.16", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.16.tgz", + "integrity": "sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==", + "dev": true + }, + "node_modules/colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "dev": true, + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, + "node_modules/component-emitter": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", + "dev": true + }, + "node_modules/compressible": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", + "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", + "dev": true, + "dependencies": { + "mime-db": ">= 1.43.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/compression": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.4.tgz", + "integrity": "sha512-jaSIDzP9pZVS4ZfQ+TzvtiWhdpFhE2RDHz8QJkpX9SIpLq88VueF5jJw6t+6CUQcAoA6t+x89MLrWAqpfDE8iQ==", + "dev": true, + "dependencies": { + "accepts": "~1.3.5", + "bytes": "3.0.0", + "compressible": "~2.0.16", + "debug": "2.6.9", + "on-headers": "~1.0.2", + "safe-buffer": "5.1.2", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/compression/node_modules/bytes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", + "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/compression/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/compression/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "node_modules/connect": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/connect/-/connect-3.7.0.tgz", + "integrity": "sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==", + "dev": true, + "dependencies": { + "debug": "2.6.9", + "finalhandler": "1.1.2", + "parseurl": "~1.3.3", + "utils-merge": "1.0.1" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/connect-history-api-fallback": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/connect-history-api-fallback/-/connect-history-api-fallback-1.6.0.tgz", + "integrity": "sha512-e54B99q/OUoH64zYYRf3HBP5z24G38h5D3qXu23JGRoigpX5Ss4r9ZnDk3g0Z8uQC2x2lPaJ+UlWBc1ZWBWdLg==", + "dev": true, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/connect/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/connect/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", + "dev": true + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dev": true, + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-disposition/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/convert-source-map": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.8.0.tgz", + "integrity": "sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==", + "dev": true, + "dependencies": { + "safe-buffer": "~5.1.1" + } + }, + "node_modules/cookie": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", + "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=", + "dev": true + }, + "node_modules/copy-anything": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-2.0.6.tgz", + "integrity": "sha512-1j20GZTsvKNkc4BY3NpMOM8tt///wY3FpIzozTOFO2ffuZcV61nojHXVKIy3WM+7ADCy5FVhdZYHYDdgTU0yJw==", + "dev": true, + "dependencies": { + "is-what": "^3.14.1" + }, + "funding": { + "url": "https://github.com/sponsors/mesqueeb" + } + }, + "node_modules/copy-webpack-plugin": { + "version": "10.2.1", + "resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-10.2.1.tgz", + "integrity": "sha512-nr81NhCAIpAWXGCK5thrKmfCQ6GDY0L5RN0U+BnIn/7Us55+UCex5ANNsNKmIVtDRnk0Ecf+/kzp9SUVrrBMLg==", + "dev": true, + "dependencies": { + "fast-glob": "^3.2.7", + "glob-parent": "^6.0.1", + "globby": "^12.0.2", + "normalize-path": "^3.0.0", + "schema-utils": "^4.0.0", + "serialize-javascript": "^6.0.0" + }, + "engines": { + "node": ">= 12.20.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + } + }, + "node_modules/copy-webpack-plugin/node_modules/ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/copy-webpack-plugin/node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/copy-webpack-plugin/node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/copy-webpack-plugin/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/copy-webpack-plugin/node_modules/schema-utils": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.0.0.tgz", + "integrity": "sha512-1edyXKgh6XnJsJSQ8mKWXnN/BVaIbFMLpouRUrXgVq7WYne5kw3MW7UPhO44uRXQSIpTSXoJbmrR2X0w9kUTyg==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.8.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.0.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/core-js": { + "version": "2.6.12", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.12.tgz", + "integrity": "sha512-Kb2wC0fvsWfQrgk8HU5lW6U/Lcs8+9aaYcy4ZFc6DDlo4nZ7n70dEgE5rtR0oG6ufKDUnrwfWL1mXR5ljDatrQ==", + "deprecated": "core-js@<3.4 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js.", + "hasInstallScript": true + }, + "node_modules/core-js-compat": { + "version": "3.22.2", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.22.2.tgz", + "integrity": "sha512-Fns9lU06ZJ07pdfmPMu7OnkIKGPKDzXKIiuGlSvHHapwqMUF2QnnsWwtueFZtSyZEilP0o6iUeHQwpn7LxtLUw==", + "dev": true, + "dependencies": { + "browserslist": "^4.20.2", + "semver": "7.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/core-js-compat/node_modules/semver": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.0.0.tgz", + "integrity": "sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dev": true, + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cosmiconfig": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.1.tgz", + "integrity": "sha512-a1YWNUV2HwGimB7dU2s1wUMurNKjpx60HxBB6xUM8Re+2s1g1IIfJvFR0/iCF+XHdE0GMTKTuLR32UQff4TEyQ==", + "dev": true, + "dependencies": { + "@types/parse-json": "^4.0.0", + "import-fresh": "^3.2.1", + "parse-json": "^5.0.0", + "path-type": "^4.0.0", + "yaml": "^1.10.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/critters": { + "version": "0.0.16", + "resolved": "https://registry.npmjs.org/critters/-/critters-0.0.16.tgz", + "integrity": "sha512-JwjgmO6i3y6RWtLYmXwO5jMd+maZt8Tnfu7VVISmEWyQqfLpB8soBswf8/2bu6SBXxtKA68Al3c+qIG1ApT68A==", + "dev": true, + "dependencies": { + "chalk": "^4.1.0", + "css-select": "^4.2.0", + "parse5": "^6.0.1", + "parse5-htmlparser2-tree-adapter": "^6.0.1", + "postcss": "^8.3.7", + "pretty-bytes": "^5.3.0" + } + }, + "node_modules/critters/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/critters/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/critters/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/critters/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/critters/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/critters/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cross-spawn/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/css": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/css/-/css-3.0.0.tgz", + "integrity": "sha512-DG9pFfwOrzc+hawpmqX/dHYHJG+Bsdb0klhyi1sDneOgGOXy9wQIC8hzyVp1e4NRYDBdxcylvywPkkXCHAzTyQ==", + "dev": true, + "dependencies": { + "inherits": "^2.0.4", + "source-map": "^0.6.1", + "source-map-resolve": "^0.6.0" + } + }, + "node_modules/css-blank-pseudo": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/css-blank-pseudo/-/css-blank-pseudo-3.0.3.tgz", + "integrity": "sha512-VS90XWtsHGqoM0t4KpH053c4ehxZ2E6HtGI7x68YFV0pTo/QmkV/YFA+NnlvK8guxZVNWGQhVNJGC39Q8XF4OQ==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.9" + }, + "bin": { + "css-blank-pseudo": "dist/cli.cjs" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/css-has-pseudo": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/css-has-pseudo/-/css-has-pseudo-3.0.4.tgz", + "integrity": "sha512-Vse0xpR1K9MNlp2j5w1pgWIJtm1a8qS0JwS9goFYcImjlHEmywP9VUF05aGBXzGpDJF86QXk4L0ypBmwPhGArw==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.9" + }, + "bin": { + "css-has-pseudo": "dist/cli.cjs" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/css-loader": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-6.5.1.tgz", + "integrity": "sha512-gEy2w9AnJNnD9Kuo4XAP9VflW/ujKoS9c/syO+uWMlm5igc7LysKzPXaDoR2vroROkSwsTS2tGr1yGGEbZOYZQ==", + "dev": true, + "dependencies": { + "icss-utils": "^5.1.0", + "postcss": "^8.2.15", + "postcss-modules-extract-imports": "^3.0.0", + "postcss-modules-local-by-default": "^4.0.0", + "postcss-modules-scope": "^3.0.0", + "postcss-modules-values": "^4.0.0", + "postcss-value-parser": "^4.1.0", + "semver": "^7.3.5" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + } + }, + "node_modules/css-prefers-color-scheme": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/css-prefers-color-scheme/-/css-prefers-color-scheme-6.0.3.tgz", + "integrity": "sha512-4BqMbZksRkJQx2zAjrokiGMd07RqOa2IxIrrN10lyBe9xhn9DEvjUK79J6jkeiv9D9hQFXKb6g1jwU62jziJZA==", + "dev": true, + "bin": { + "css-prefers-color-scheme": "dist/cli.cjs" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/css-select": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-4.3.0.tgz", + "integrity": "sha512-wPpOYtnsVontu2mODhA19JrqWxNsfdatRKd64kmpRbQgh1KtItko5sTnEpPdpSaJszTOhEMlF/RPz28qj4HqhQ==", + "dev": true, + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.0.1", + "domhandler": "^4.3.1", + "domutils": "^2.8.0", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-selector-tokenizer": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/css-selector-tokenizer/-/css-selector-tokenizer-0.7.3.tgz", + "integrity": "sha512-jWQv3oCEL5kMErj4wRnK/OPoBi0D+P1FR2cDCKYPaMeD2eW3/mttav8HT4hT1CKopiJI/psEULjkClhvJo4Lvg==", + "dev": true, + "dependencies": { + "cssesc": "^3.0.0", + "fastparse": "^1.1.2" + } + }, + "node_modules/css-what": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", + "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==", + "dev": true, + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/cssauron": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/cssauron/-/cssauron-1.4.0.tgz", + "integrity": "sha1-pmAt/34EqDBtwNuaVR6S6LVmKtg=", + "dev": true, + "dependencies": { + "through": "X.X.X" + } + }, + "node_modules/cssdb": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cssdb/-/cssdb-5.1.0.tgz", + "integrity": "sha512-/vqjXhv1x9eGkE/zO6o8ZOI7dgdZbLVLUGyVRbPgk6YipXbW87YzUCcO+Jrmi5bwJlAH6oD+MNeZyRgXea1GZw==", + "dev": true + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/custom-event": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz", + "integrity": "sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU=", + "dev": true + }, + "node_modules/damerau-levenshtein": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", + "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==", + "dev": true + }, + "node_modules/date-format": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/date-format/-/date-format-4.0.3.tgz", + "integrity": "sha512-7P3FyqDcfeznLZp2b+OMitV9Sz2lUnsT87WaTat9nVwqsBkTzPG3lPLNwW3en6F4pHUiWzr6vb8CLhjdK9bcxQ==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/debug": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/deep-equal": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.1.1.tgz", + "integrity": "sha512-yd9c5AdiqVcR+JjcwUQb9DkhJc8ngNr0MahEBGvDiJw8puWab2yZlh+nkasOnZP+EGTAP6rRp2JzJhJZzvNF8g==", + "dev": true, + "dependencies": { + "is-arguments": "^1.0.4", + "is-date-object": "^1.0.1", + "is-regex": "^1.0.4", + "object-is": "^1.0.1", + "object-keys": "^1.1.1", + "regexp.prototype.flags": "^1.2.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/default-gateway": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/default-gateway/-/default-gateway-6.0.3.tgz", + "integrity": "sha512-fwSOJsbbNzZ/CUFpqFBqYfYNLj1NbMPm8MMCIzHjC83iSJRBEGmDUxU+WP661BaBQImeC2yHwXtz+P/O9o+XEg==", + "dev": true, + "dependencies": { + "execa": "^5.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/defaults": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", + "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "dev": true, + "dependencies": { + "clone": "^1.0.2" + } + }, + "node_modules/define-lazy-prop": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", + "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/define-properties": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.4.tgz", + "integrity": "sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA==", + "dev": true, + "dependencies": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/del": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/del/-/del-6.0.0.tgz", + "integrity": "sha512-1shh9DQ23L16oXSZKB2JxpL7iMy2E0S9d517ptA1P8iw0alkPtQcrKH7ru31rYtKwF499HkTu+DRzq3TCKDFRQ==", + "dev": true, + "dependencies": { + "globby": "^11.0.1", + "graceful-fs": "^4.2.4", + "is-glob": "^4.0.1", + "is-path-cwd": "^2.2.0", + "is-path-inside": "^3.0.2", + "p-map": "^4.0.0", + "rimraf": "^3.0.2", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/del/node_modules/array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/del/node_modules/globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/del/node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", + "dev": true + }, + "node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/dependency-graph": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/dependency-graph/-/dependency-graph-0.11.0.tgz", + "integrity": "sha512-JeMq7fEshyepOWDfcfHK06N3MhyPhz++vtqWhMT5O9A3K42rdsEDpfdVqjaqaAhsw6a+ZqeDvQVtD0hFHQWrzg==", + "dev": true, + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "dev": true, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==", + "dev": true + }, + "node_modules/di": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz", + "integrity": "sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw=", + "dev": true + }, + "node_modules/diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/dns-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/dns-equal/-/dns-equal-1.0.0.tgz", + "integrity": "sha1-s55/HabrCnW6nBcySzR1PEfgZU0=", + "dev": true + }, + "node_modules/dns-packet": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-1.3.4.tgz", + "integrity": "sha512-BQ6F4vycLXBvdrJZ6S3gZewt6rcrks9KBgM9vrhW+knGRqc8uEdT7fuCwloc7nny5xNoMJ17HGH0R/6fpo8ECA==", + "dev": true, + "dependencies": { + "ip": "^1.1.0", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/dns-txt": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/dns-txt/-/dns-txt-2.0.2.tgz", + "integrity": "sha1-uR2Ab10nGI5Ks+fRB9iBocxGQrY=", + "dev": true, + "dependencies": { + "buffer-indexof": "^1.0.0" + } + }, + "node_modules/dom-serialize": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/dom-serialize/-/dom-serialize-2.2.1.tgz", + "integrity": "sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs=", + "dev": true, + "dependencies": { + "custom-event": "~1.0.0", + "ent": "~2.2.0", + "extend": "^3.0.0", + "void-elements": "^2.0.0" + } + }, + "node_modules/dom-serializer": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz", + "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==", + "dev": true, + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.2.0", + "entities": "^2.0.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ] + }, + "node_modules/domhandler": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz", + "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==", + "dev": true, + "dependencies": { + "domelementtype": "^2.2.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz", + "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==", + "dev": true, + "dependencies": { + "dom-serializer": "^1.0.1", + "domelementtype": "^2.2.0", + "domhandler": "^4.2.0" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", + "dev": true + }, + "node_modules/electron-to-chromium": { + "version": "1.4.122", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.122.tgz", + "integrity": "sha512-VuLNxTIt8sBWIT2sd186xPd18Y8KcK8myLd9nMdSJOYZwFUxxbLVmX/T1VX+qqaytRlrYYQv39myxJdXtu7Ysw==", + "dev": true + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/emojis-list": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz", + "integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/encoding": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", + "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", + "dev": true, + "optional": true, + "dependencies": { + "iconv-lite": "^0.6.2" + } + }, + "node_modules/encoding/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "optional": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/engine.io": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.1.3.tgz", + "integrity": "sha512-rqs60YwkvWTLLnfazqgZqLa/aKo+9cueVfEi/dZ8PyGyaf8TLOxj++4QMIgeG3Gn0AhrWiFXvghsoY9L9h25GA==", + "dev": true, + "dependencies": { + "@types/cookie": "^0.4.1", + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "accepts": "~1.3.4", + "base64id": "2.0.0", + "cookie": "~0.4.1", + "cors": "~2.8.5", + "debug": "~4.3.1", + "engine.io-parser": "~5.0.3", + "ws": "~8.2.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.3.tgz", + "integrity": "sha512-BtQxwF27XUNnSafQLvDi0dQ8s3i6VgzSoQMJacpIcGNrlUdfHSKbgm3jmjCVvQluGzqwujQMPAoMai3oYSTurg==", + "dev": true, + "dependencies": { + "@socket.io/base64-arraybuffer": "~1.0.2" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.9.3.tgz", + "integrity": "sha512-Bq9VSor+kjvW3f9/MiiR4eE3XYgOl7/rS8lnSxbRbF3kS0B2r+Y9w5krBWxZgDxASVZbdYrn5wT4j/Wb0J9qow==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/ent": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz", + "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=", + "dev": true + }, + "node_modules/entities": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", + "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", + "dev": true, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/err-code": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz", + "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==", + "dev": true + }, + "node_modules/errno": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.8.tgz", + "integrity": "sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==", + "dev": true, + "optional": true, + "dependencies": { + "prr": "~1.0.1" + }, + "bin": { + "errno": "cli.js" + } + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-module-lexer": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-0.9.3.tgz", + "integrity": "sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ==", + "dev": true + }, + "node_modules/esbuild": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.14.22.tgz", + "integrity": "sha512-CjFCFGgYtbFOPrwZNJf7wsuzesx8kqwAffOlbYcFDLFuUtP8xloK1GH+Ai13Qr0RZQf9tE7LMTHJ2iVGJ1SKZA==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "esbuild-android-arm64": "0.14.22", + "esbuild-darwin-64": "0.14.22", + "esbuild-darwin-arm64": "0.14.22", + "esbuild-freebsd-64": "0.14.22", + "esbuild-freebsd-arm64": "0.14.22", + "esbuild-linux-32": "0.14.22", + "esbuild-linux-64": "0.14.22", + "esbuild-linux-arm": "0.14.22", + "esbuild-linux-arm64": "0.14.22", + "esbuild-linux-mips64le": "0.14.22", + "esbuild-linux-ppc64le": "0.14.22", + "esbuild-linux-riscv64": "0.14.22", + "esbuild-linux-s390x": "0.14.22", + "esbuild-netbsd-64": "0.14.22", + "esbuild-openbsd-64": "0.14.22", + "esbuild-sunos-64": "0.14.22", + "esbuild-windows-32": "0.14.22", + "esbuild-windows-64": "0.14.22", + "esbuild-windows-arm64": "0.14.22" + } + }, + "node_modules/esbuild-android-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.14.22.tgz", + "integrity": "sha512-k1Uu4uC4UOFgrnTj2zuj75EswFSEBK+H6lT70/DdS4mTAOfs2ECv2I9ZYvr3w0WL0T4YItzJdK7fPNxcPw6YmQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-darwin-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.14.22.tgz", + "integrity": "sha512-d8Ceuo6Vw6HM3fW218FB6jTY6O3r2WNcTAU0SGsBkXZ3k8SDoRLd3Nrc//EqzdgYnzDNMNtrWegK2Qsss4THhw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-darwin-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.14.22.tgz", + "integrity": "sha512-YAt9Tj3SkIUkswuzHxkaNlT9+sg0xvzDvE75LlBo4DI++ogSgSmKNR6B4eUhU5EUUepVXcXdRIdqMq9ppeRqfw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-freebsd-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.14.22.tgz", + "integrity": "sha512-ek1HUv7fkXMy87Qm2G4IRohN+Qux4IcnrDBPZGXNN33KAL0pEJJzdTv0hB/42+DCYWylSrSKxk3KUXfqXOoH4A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-freebsd-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.14.22.tgz", + "integrity": "sha512-zPh9SzjRvr9FwsouNYTqgqFlsMIW07O8mNXulGeQx6O5ApgGUBZBgtzSlBQXkHi18WjrosYfsvp5nzOKiWzkjQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-32": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.14.22.tgz", + "integrity": "sha512-SnpveoE4nzjb9t2hqCIzzTWBM0RzcCINDMBB67H6OXIuDa4KqFqaIgmTchNA9pJKOVLVIKd5FYxNiJStli21qg==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.22.tgz", + "integrity": "sha512-Zcl9Wg7gKhOWWNqAjygyqzB+fJa19glgl2JG7GtuxHyL1uEnWlpSMytTLMqtfbmRykIHdab797IOZeKwk5g0zg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-arm": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.14.22.tgz", + "integrity": "sha512-soPDdbpt/C0XvOOK45p4EFt8HbH5g+0uHs5nUKjHVExfgR7du734kEkXR/mE5zmjrlymk5AA79I0VIvj90WZ4g==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.14.22.tgz", + "integrity": "sha512-8q/FRBJtV5IHnQChO3LHh/Jf7KLrxJ/RCTGdBvlVZhBde+dk3/qS9fFsUy+rs3dEi49aAsyVitTwlKw1SUFm+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-mips64le": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.14.22.tgz", + "integrity": "sha512-SiNDfuRXhGh1JQLLA9JPprBgPVFOsGuQ0yDfSPTNxztmVJd8W2mX++c4FfLpAwxuJe183mLuKf7qKCHQs5ZnBQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-ppc64le": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.14.22.tgz", + "integrity": "sha512-6t/GI9I+3o1EFm2AyN9+TsjdgWCpg2nwniEhjm2qJWtJyJ5VzTXGUU3alCO3evopu8G0hN2Bu1Jhz2YmZD0kng==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-riscv64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.14.22.tgz", + "integrity": "sha512-AyJHipZKe88sc+tp5layovquw5cvz45QXw5SaDgAq2M911wLHiCvDtf/07oDx8eweCyzYzG5Y39Ih568amMTCQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-s390x": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.14.22.tgz", + "integrity": "sha512-Sz1NjZewTIXSblQDZWEFZYjOK6p8tV6hrshYdXZ0NHTjWE+lwxpOpWeElUGtEmiPcMT71FiuA9ODplqzzSxkzw==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-netbsd-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.14.22.tgz", + "integrity": "sha512-TBbCtx+k32xydImsHxvFgsOCuFqCTGIxhzRNbgSL1Z2CKhzxwT92kQMhxort9N/fZM2CkRCPPs5wzQSamtzEHA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-openbsd-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.14.22.tgz", + "integrity": "sha512-vK912As725haT313ANZZZN+0EysEEQXWC/+YE4rQvOQzLuxAQc2tjbzlAFREx3C8+uMuZj/q7E5gyVB7TzpcTA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-sunos-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.14.22.tgz", + "integrity": "sha512-/mbJdXTW7MTcsPhtfDsDyPEOju9EOABvCjeUU2OJ7fWpX/Em/H3WYDa86tzLUbcVg++BScQDzqV/7RYw5XNY0g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-wasm": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-wasm/-/esbuild-wasm-0.14.22.tgz", + "integrity": "sha512-FOSAM29GN1fWusw0oLMv6JYhoheDIh5+atC72TkJKfIUMID6yISlicoQSd9gsNSFsNBvABvtE2jR4JB1j4FkFw==", + "dev": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-windows-32": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.14.22.tgz", + "integrity": "sha512-1vRIkuvPTjeSVK3diVrnMLSbkuE36jxA+8zGLUOrT4bb7E/JZvDRhvtbWXWaveUc/7LbhaNFhHNvfPuSw2QOQg==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-windows-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.14.22.tgz", + "integrity": "sha512-AxjIDcOmx17vr31C5hp20HIwz1MymtMjKqX4qL6whPj0dT9lwxPexmLj6G1CpR3vFhui6m75EnBEe4QL82SYqw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-windows-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.14.22.tgz", + "integrity": "sha512-5wvQ+39tHmRhNpu2Fx04l7QfeK3mQ9tKzDqqGR8n/4WUxsFxnVLfDRBGirIfk4AfWlxk60kqirlODPoT5LqMUg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "dev": true + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventemitter-asyncresource": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/eventemitter-asyncresource/-/eventemitter-asyncresource-1.0.0.tgz", + "integrity": "sha512-39F7TBIV0G7gTelxwbEqnwhp90eqCPON1k0NwNfwhgKn4Co4ybUbj2pECcXT0B3ztRKZ7Pw1JujUUgmQJHcVAQ==", + "dev": true + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "dev": true + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/express": { + "version": "4.18.0", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.0.tgz", + "integrity": "sha512-EJEXxiTQJS3lIPrU1AE2vRuT7X7E+0KBbpm5GSoK524yl0K8X+er8zS2P14E64eqsVNoWbMCT7MpmQ+ErAhgRg==", + "dev": true, + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.0", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.5.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.10.3", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/express/node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=", + "dev": true + }, + "node_modules/express/node_modules/cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/express/node_modules/finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "dev": true, + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/express/node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/express/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/express/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "node_modules/fast-glob": { + "version": "3.2.11", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.11.tgz", + "integrity": "sha512-xrO3+1bxSo3ZVHAnqzyuewYT6aMFHRAd4Kcs92MAonjwQZLsK9d0SF1IyQ3k5PoirxTW0Oe/RqFgMQ6TcNE5Ew==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "node_modules/fastparse": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.2.tgz", + "integrity": "sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ==", + "dev": true + }, + "node_modules/fastq": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.13.0.tgz", + "integrity": "sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==", + "dev": true, + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "dev": true, + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "dependencies": { + "escape-string-regexp": "^1.0.5" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", + "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "dev": true, + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "statuses": "~1.5.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/find-cache-dir": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz", + "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", + "dev": true, + "dependencies": { + "commondir": "^1.0.1", + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/avajs/find-cache-dir?sponsor=1" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/flatted": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.5.tgz", + "integrity": "sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==", + "dev": true + }, + "node_modules/follow-redirects": { + "version": "1.14.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz", + "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fraction.js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.2.0.tgz", + "integrity": "sha512-MhLuK+2gUcnZe8ZHlaaINnQLl0xRIGRfcGk2yl8xoQAfHrSsL3rYu6FCmBdkdbhc9EPlwyGHewaRsvwRMJtAlA==", + "dev": true, + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://www.patreon.com/infusion" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dev": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-monkey": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-1.0.3.tgz", + "integrity": "sha512-cybjIfiiE+pTWicSCLFHSrXZ6EilF30oh91FDP9S2B051prEa7QWfrVTQm10/dDpswBDXZugPa1Ogu8Yh+HV0Q==", + "dev": true + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gauge": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-4.0.4.tgz", + "integrity": "sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg==", + "dev": true, + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.3", + "console-control-strings": "^1.1.0", + "has-unicode": "^2.0.1", + "signal-exit": "^3.0.7", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.5" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", + "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true + }, + "node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/globby": { + "version": "12.2.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-12.2.0.tgz", + "integrity": "sha512-wiSuFQLZ+urS9x2gGPl1H5drc5twabmm4m2gTR27XDFyjUHJUNsS8o/2aKyIF6IoBaR630atdher0XJ5g6OMmA==", + "dev": true, + "dependencies": { + "array-union": "^3.0.1", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.7", + "ignore": "^5.1.9", + "merge2": "^1.4.1", + "slash": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.9", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", + "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", + "dev": true + }, + "node_modules/handle-thing": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-2.0.1.tgz", + "integrity": "sha512-9Qn4yBxelxoh2Ow62nP+Ka/kMnOXRi8BXnRaUwezLNhqelnN49xKz4F/dPP8OYLxLxq6JDtZb2i9XznUQbNPTg==", + "dev": true + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", + "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.1.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "dev": true, + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", + "dev": true + }, + "node_modules/hdr-histogram-js": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/hdr-histogram-js/-/hdr-histogram-js-2.0.3.tgz", + "integrity": "sha512-Hkn78wwzWHNCp2uarhzQ2SGFLU3JY8SBDDd3TAABK4fc30wm+MuPOrg5QVFVfkKOQd6Bfz3ukJEI+q9sXEkK1g==", + "dev": true, + "dependencies": { + "@assemblyscript/loader": "^0.10.1", + "base64-js": "^1.2.0", + "pako": "^1.0.3" + } + }, + "node_modules/hdr-histogram-percentiles-obj": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hdr-histogram-percentiles-obj/-/hdr-histogram-percentiles-obj-3.0.0.tgz", + "integrity": "sha512-7kIufnBqdsBGcSZLPJwqHT3yhk1QTsSlFsVD3kx5ixH/AlgBs9yM1q6DPhXZ8f8gtdqgh7N7/5btRLpQsS2gHw==", + "dev": true + }, + "node_modules/hosted-git-info": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", + "integrity": "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/hpack.js": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/hpack.js/-/hpack.js-2.1.6.tgz", + "integrity": "sha1-h3dMCUnlE/QuhFdbPEVoH63ioLI=", + "dev": true, + "dependencies": { + "inherits": "^2.0.1", + "obuf": "^1.0.0", + "readable-stream": "^2.0.1", + "wbuf": "^1.1.0" + } + }, + "node_modules/hpack.js/node_modules/readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/hpack.js/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/html-entities": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.3.3.tgz", + "integrity": "sha512-DV5Ln36z34NNTDgnz0EWGBLZENelNAtkiFA4kyNOG2tDI6Mz1uSWiq1wAKdyjnJwyDiDO7Fa2SO1CTxPXL8VxA==", + "dev": true + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true + }, + "node_modules/http-cache-semantics": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz", + "integrity": "sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==", + "dev": true + }, + "node_modules/http-deceiver": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz", + "integrity": "sha1-+nFolEq5pRnTN8sL7HKE3D5yPYc=", + "dev": true + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dev": true, + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-errors/node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-errors/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-parser-js": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.6.tgz", + "integrity": "sha512-vDlkRPDJn93swjcjqMSaGSPABbIarsr1TLAui/gLDXzV5VsJNdXNzMYDyNBLQkjWQCJ1uizu8T2oDMhmGt0PRA==", + "dev": true + }, + "node_modules/http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "dev": true, + "dependencies": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-proxy-agent": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", + "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", + "dev": true, + "dependencies": { + "@tootallnate/once": "1", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/http-proxy-middleware": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.6.tgz", + "integrity": "sha512-ya/UeJ6HVBYxrgYotAZo1KvPWlgB48kUJLDePFeneHsVujFaW5WNj2NgWCAE//B1Dl02BIfYlpNgBy8Kf8Rjmw==", + "dev": true, + "dependencies": { + "@types/http-proxy": "^1.17.8", + "http-proxy": "^1.18.1", + "is-glob": "^4.0.1", + "is-plain-obj": "^3.0.0", + "micromatch": "^4.0.2" + }, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "@types/express": "^4.17.13" + }, + "peerDependenciesMeta": { + "@types/express": { + "optional": true + } + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", + "integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", + "dev": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true, + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha1-xG4xWaKT9riW2ikxbYtv6Lt5u+0=", + "dev": true, + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/icss-utils": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-5.1.0.tgz", + "integrity": "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==", + "dev": true, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/ignore": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.0.tgz", + "integrity": "sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/ignore-walk": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-4.0.1.tgz", + "integrity": "sha512-rzDQLaW4jQbh2YrOFlJdCtX8qgJTehFRYiUB2r1osqTeDzV/3+Jh8fz1oAPzUThf3iku8Ds4IDqawI5d8mUiQw==", + "dev": true, + "dependencies": { + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/image-size": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-0.5.5.tgz", + "integrity": "sha1-Cd/Uq50g4p6xw+gLiZA3jfnjy5w=", + "dev": true, + "optional": true, + "bin": { + "image-size": "bin/image-size.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/immutable": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/immutable/-/immutable-4.0.0.tgz", + "integrity": "sha512-zIE9hX70qew5qTUjSS7wi1iwj/l7+m54KWU247nhM3v806UdGj1yDndXj+IOYxxtW9zyLI+xqFNZjTuDaLUqFw==", + "dev": true + }, + "node_modules/import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "dev": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-fresh/node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true, + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/infer-owner": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz", + "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==", + "dev": true + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "node_modules/ini": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-2.0.0.tgz", + "integrity": "sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/inquirer": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.0.tgz", + "integrity": "sha512-0crLweprevJ02tTuA6ThpoAERAGyVILC4sS74uib58Xf/zSr1/ZWtmm7D5CI+bSQEaA04f0K7idaHpQbSWgiVQ==", + "dev": true, + "dependencies": { + "ansi-escapes": "^4.2.1", + "chalk": "^4.1.1", + "cli-cursor": "^3.1.0", + "cli-width": "^3.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.21", + "mute-stream": "0.0.8", + "ora": "^5.4.1", + "run-async": "^2.4.0", + "rxjs": "^7.2.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/inquirer/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/inquirer/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/inquirer/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/inquirer/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/inquirer/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/rxjs": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.5.5.tgz", + "integrity": "sha512-sy+H0pQofO95VDmFLzyaw9xNJU4KTRSwQIGM6+iG3SypAtCiLDzpeG8sJrNCWn2Up9km+KhkvTdbkrdy+yzZdw==", + "dev": true, + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/inquirer/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ip": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/ip/-/ip-1.1.5.tgz", + "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=", + "dev": true + }, + "node_modules/ipaddr.js": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.0.1.tgz", + "integrity": "sha512-1qTgH9NG+IIJ4yfKs2e6Pp1bZg8wbDbKHT21HrLIeYBTRLgMYKnMTPAuI3Lcs61nfx5h1xlXnbJtH1kX5/d/ng==", + "dev": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/is-arguments": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.1.tgz", + "integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-interactive": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-lambda": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-lambda/-/is-lambda-1.0.1.tgz", + "integrity": "sha1-PZh3iZ5qU+/AFgUEzeFfgubwYdU=", + "dev": true + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-path-cwd": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-2.2.0.tgz", + "integrity": "sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-plain-obj": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-3.0.0.tgz", + "integrity": "sha512-gwsOE28k+23GP1B6vFl1oVh/WOzmawBrKwo5Ev6wMKzPkaXaCDIQKzLnvsA42DRlbVTWorkgTKIviAKCWkfUwA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-what": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/is-what/-/is-what-3.14.1.tgz", + "integrity": "sha512-sNxgpk9793nzSs7bA6JQJGeIuRBQhAaNGG77kzYQgMkrID+lS6SlK07K5LaptscDlSaIgH+GPFzf+d75FVxozA==", + "dev": true + }, + "node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "node_modules/isbinaryfile": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.8.tgz", + "integrity": "sha512-53h6XFniq77YdW+spoRrebh0mnmTxRPTlcuIArO57lmMdq4uBKFKaeTjnb92oYWrSn/LVL+LT+Hap2tFQj8V+w==", + "dev": true, + "engines": { + "node": ">= 8.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/gjtorikian/" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "node_modules/isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-instrument": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.0.tgz", + "integrity": "sha512-6Lthe1hqXHBNsqvgDzGO6l03XNeu3CrG4RqQ1KM9+l5+jNGpEJfIELx1NS3SEHmJQA8np/u+E4EPRKRiu6m19A==", + "dev": true, + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-instrument/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", + "dev": true, + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.6.tgz", + "integrity": "sha512-R47KzMtDJH6X4/YW9XTx+jrLnZnscW4VpNN+1PViSYTejLVPWv7oov+Duf8YQSPyVRUvueQqz1TcsC6mooZTXw==", + "dev": true, + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^2.0.5", + "make-dir": "^2.1.0", + "rimraf": "^2.6.3", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/istanbul-lib-coverage": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz", + "integrity": "sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "dependencies": { + "pify": "^4.0.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/istanbul-reports": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.4.tgz", + "integrity": "sha512-r1/DshN4KSE7xWEknZLLLLDn5CJybV3nw01VTkp6D5jzLuELlcbudfj/eSQFvrKsJuTVCGnePO7ho82Nw9zzfw==", + "dev": true, + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jasmine-core": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-3.8.0.tgz", + "integrity": "sha512-zl0nZWDrmbCiKns0NcjkFGYkVTGCPUgoHypTaj+G2AzaWus7QGoXARSlYsSle2VRpSdfJmM+hzmFKzQNhF2kHg==", + "dev": true + }, + "node_modules/jasmine-spec-reporter": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/jasmine-spec-reporter/-/jasmine-spec-reporter-5.0.2.tgz", + "integrity": "sha512-6gP1LbVgJ+d7PKksQBc2H0oDGNRQI3gKUsWlswKaQ2fif9X5gzhQcgM5+kiJGCQVurOG09jqNhk7payggyp5+g==", + "dev": true, + "dependencies": { + "colors": "1.4.0" + } + }, + "node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/jest-worker/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "node_modules/json5": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", + "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", + "dev": true, + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonc-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.0.0.tgz", + "integrity": "sha512-fQzRfAbIBnR0IQvftw9FJveWiHp72Fg20giDrHz6TdfB12UH/uue0D3hm57UB5KgAVuniLMCaS8P1IMj9NR7cA==", + "dev": true + }, + "node_modules/jsonparse": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", + "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=", + "dev": true, + "engines": [ + "node >= 0.2.0" + ] + }, + "node_modules/karma": { + "version": "6.3.17", + "resolved": "https://registry.npmjs.org/karma/-/karma-6.3.17.tgz", + "integrity": "sha512-2TfjHwrRExC8yHoWlPBULyaLwAFmXmxQrcuFImt/JsAsSZu1uOWTZ1ZsWjqQtWpHLiatJOHL5jFjXSJIgCd01g==", + "dev": true, + "dependencies": { + "@colors/colors": "1.5.0", + "body-parser": "^1.19.0", + "braces": "^3.0.2", + "chokidar": "^3.5.1", + "connect": "^3.7.0", + "di": "^0.0.1", + "dom-serialize": "^2.2.1", + "glob": "^7.1.7", + "graceful-fs": "^4.2.6", + "http-proxy": "^1.18.1", + "isbinaryfile": "^4.0.8", + "lodash": "^4.17.21", + "log4js": "^6.4.1", + "mime": "^2.5.2", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.5", + "qjobs": "^1.2.0", + "range-parser": "^1.2.1", + "rimraf": "^3.0.2", + "socket.io": "^4.2.0", + "source-map": "^0.6.1", + "tmp": "^0.2.1", + "ua-parser-js": "^0.7.30", + "yargs": "^16.1.1" + }, + "bin": { + "karma": "bin/karma" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/karma-chrome-launcher": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/karma-chrome-launcher/-/karma-chrome-launcher-3.1.0.tgz", + "integrity": "sha512-3dPs/n7vgz1rxxtynpzZTvb9y/GIaW8xjAwcIGttLbycqoFtI7yo1NGnQi6oFTherRE+GIhCAHZC4vEqWGhNvg==", + "dev": true, + "dependencies": { + "which": "^1.2.1" + } + }, + "node_modules/karma-coverage-istanbul-reporter": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/karma-coverage-istanbul-reporter/-/karma-coverage-istanbul-reporter-3.0.3.tgz", + "integrity": "sha512-wE4VFhG/QZv2Y4CdAYWDbMmcAHeS926ZIji4z+FkB2aF/EposRb6DP6G5ncT/wXhqUfAb/d7kZrNKPonbvsATw==", + "dev": true, + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^3.0.6", + "istanbul-reports": "^3.0.2", + "minimatch": "^3.0.4" + }, + "funding": { + "url": "https://github.com/sponsors/mattlewis92" + } + }, + "node_modules/karma-jasmine": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/karma-jasmine/-/karma-jasmine-4.0.1.tgz", + "integrity": "sha512-h8XDAhTiZjJKzfkoO1laMH+zfNlra+dEQHUAjpn5JV1zCPtOIVWGQjLBrqhnzQa/hrU2XrZwSyBa6XjEBzfXzw==", + "dev": true, + "dependencies": { + "jasmine-core": "^3.6.0" + }, + "engines": { + "node": ">= 10" + }, + "peerDependencies": { + "karma": "*" + } + }, + "node_modules/karma-jasmine-html-reporter": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/karma-jasmine-html-reporter/-/karma-jasmine-html-reporter-1.7.0.tgz", + "integrity": "sha512-pzum1TL7j90DTE86eFt48/s12hqwQuiD+e5aXx2Dc9wDEn2LfGq6RoAxEZZjFiN0RDSCOnosEKRZWxbQ+iMpQQ==", + "dev": true, + "peerDependencies": { + "jasmine-core": ">=3.8", + "karma": ">=0.9", + "karma-jasmine": ">=1.1" + } + }, + "node_modules/karma-source-map-support": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/karma-source-map-support/-/karma-source-map-support-1.4.0.tgz", + "integrity": "sha512-RsBECncGO17KAoJCYXjv+ckIz+Ii9NCi+9enk+rq6XC81ezYkb4/RHE6CTXdA7IOJqoF3wcaLfVG0CPmE5ca6A==", + "dev": true, + "dependencies": { + "source-map-support": "^0.5.5" + } + }, + "node_modules/karma/node_modules/mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "dev": true, + "dependencies": { + "minimist": "^1.2.5" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/karma/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/karma/node_modules/tmp": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz", + "integrity": "sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ==", + "dev": true, + "dependencies": { + "rimraf": "^3.0.0" + }, + "engines": { + "node": ">=8.17.0" + } + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/klona": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/klona/-/klona-2.0.5.tgz", + "integrity": "sha512-pJiBpiXMbt7dkzXe8Ghj/u4FfXOOa98fPW+bihOJ4SjnoijweJrNThJfd3ifXpXhREjpoF2mZVH1GfS9LV3kHQ==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/less": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/less/-/less-4.1.2.tgz", + "integrity": "sha512-EoQp/Et7OSOVu0aJknJOtlXZsnr8XE8KwuzTHOLeVSEx8pVWUICc8Q0VYRHgzyjX78nMEyC/oztWFbgyhtNfDA==", + "dev": true, + "dependencies": { + "copy-anything": "^2.0.1", + "parse-node-version": "^1.0.1", + "tslib": "^2.3.0" + }, + "bin": { + "lessc": "bin/lessc" + }, + "engines": { + "node": ">=6" + }, + "optionalDependencies": { + "errno": "^0.1.1", + "graceful-fs": "^4.1.2", + "image-size": "~0.5.0", + "make-dir": "^2.1.0", + "mime": "^1.4.1", + "needle": "^2.5.2", + "source-map": "~0.6.0" + } + }, + "node_modules/less-loader": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/less-loader/-/less-loader-10.2.0.tgz", + "integrity": "sha512-AV5KHWvCezW27GT90WATaDnfXBv99llDbtaj4bshq6DvAihMdNjaPDcUMa6EXKLRF+P2opFenJp89BXg91XLYg==", + "dev": true, + "dependencies": { + "klona": "^2.0.4" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "less": "^3.5.0 || ^4.0.0", + "webpack": "^5.0.0" + } + }, + "node_modules/less/node_modules/make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "optional": true, + "dependencies": { + "pify": "^4.0.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/less/node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true, + "optional": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/less/node_modules/pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true, + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/less/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "optional": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/less/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/license-webpack-plugin": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/license-webpack-plugin/-/license-webpack-plugin-4.0.2.tgz", + "integrity": "sha512-771TFWFD70G1wLTC4oU2Cw4qvtmNrIw+wRvBtn+okgHl7slJVi7zfNcdmqDL72BojM30VNJ2UHylr1o77U37Jw==", + "dev": true, + "dependencies": { + "webpack-sources": "^3.0.0" + }, + "peerDependenciesMeta": { + "webpack": { + "optional": true + }, + "webpack-sources": { + "optional": true + } + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true + }, + "node_modules/loader-runner": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", + "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", + "dev": true, + "engines": { + "node": ">=6.11.5" + } + }, + "node_modules/loader-utils": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-3.2.0.tgz", + "integrity": "sha512-HVl9ZqccQihZ7JM85dco1MvO9G+ONvxoGa9rkhzFsneGLKSUg1gJf9bWzhRhcvm2qChhWpebQhP44qxjKIUCaQ==", + "dev": true, + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true + }, + "node_modules/lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168=", + "dev": true + }, + "node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dev": true, + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-symbols/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/log-symbols/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/log-symbols/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/log-symbols/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/log-symbols/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/log-symbols/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/log4js": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/log4js/-/log4js-6.4.1.tgz", + "integrity": "sha512-iUiYnXqAmNKiIZ1XSAitQ4TmNs8CdZYTAWINARF3LjnsLN8tY5m0vRwd6uuWj/yNY0YHxeZodnbmxKFUOM2rMg==", + "dev": true, + "dependencies": { + "date-format": "^4.0.3", + "debug": "^4.3.3", + "flatted": "^3.2.4", + "rfdc": "^1.3.0", + "streamroller": "^3.0.2" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/magic-string": { + "version": "0.25.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz", + "integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.4" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, + "node_modules/make-fetch-happen": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-9.1.0.tgz", + "integrity": "sha512-+zopwDy7DNknmwPQplem5lAZX/eCOzSvSNNcSKm5eVwTkOBzoktEfXsa9L23J/GIRhxRsaxzkPEhrJEpE2F4Gg==", + "dev": true, + "dependencies": { + "agentkeepalive": "^4.1.3", + "cacache": "^15.2.0", + "http-cache-semantics": "^4.1.0", + "http-proxy-agent": "^4.0.1", + "https-proxy-agent": "^5.0.0", + "is-lambda": "^1.0.1", + "lru-cache": "^6.0.0", + "minipass": "^3.1.3", + "minipass-collect": "^1.0.2", + "minipass-fetch": "^1.3.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.2", + "promise-retry": "^2.0.1", + "socks-proxy-agent": "^6.0.0", + "ssri": "^8.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memfs": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/memfs/-/memfs-3.4.1.tgz", + "integrity": "sha512-1c9VPVvW5P7I85c35zAdEr1TD5+F11IToIHIlrVIcflfnzPkJa0ZoYEoEdYDP8KgPFoSZ/opDrUsAoZWym3mtw==", + "dev": true, + "dependencies": { + "fs-monkey": "1.0.3" + }, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", + "dev": true + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "dependencies": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "dev": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz", + "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.34", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz", + "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==", + "dev": true, + "dependencies": { + "mime-db": "1.51.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/mini-css-extract-plugin": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.5.3.tgz", + "integrity": "sha512-YseMB8cs8U/KCaAGQoqYmfUuhhGW0a9p9XvWXrxVOkE3/IiISTLw4ALNt7JR5B2eYauFM+PQGSbXMDmVbR7Tfw==", + "dev": true, + "dependencies": { + "schema-utils": "^4.0.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + } + }, + "node_modules/mini-css-extract-plugin/node_modules/ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/mini-css-extract-plugin/node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/mini-css-extract-plugin/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/mini-css-extract-plugin/node_modules/schema-utils": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.0.0.tgz", + "integrity": "sha512-1edyXKgh6XnJsJSQ8mKWXnN/BVaIbFMLpouRUrXgVq7WYne5kw3MW7UPhO44uRXQSIpTSXoJbmrR2X0w9kUTyg==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.8.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.0.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true + }, + "node_modules/minimatch": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.5.tgz", + "integrity": "sha512-tUpxzX0VAzJHjLu0xUfFv1gwVp9ba3IOuRAVH2EGuRW8a5emA2FlACLqiT/lDVtS1W+TGNwqz3sWaNyLgDJWuw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", + "dev": true + }, + "node_modules/minipass": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.1.6.tgz", + "integrity": "sha512-rty5kpw9/z8SX9dmxblFA6edItUmwJgMeYDZRrwlIVN27i8gysGbznJwUggw2V/FVqFSDdWy040ZPS811DYAqQ==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-collect": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-1.0.2.tgz", + "integrity": "sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA==", + "dev": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-fetch": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-1.4.1.tgz", + "integrity": "sha512-CGH1eblLq26Y15+Azk7ey4xh0J/XfJfrCox5LDJiKqI2Q2iwOLOKrlmIaODiSQS8d18jalF6y2K2ePUm0CmShw==", + "dev": true, + "dependencies": { + "minipass": "^3.1.0", + "minipass-sized": "^1.0.3", + "minizlib": "^2.0.0" + }, + "engines": { + "node": ">=8" + }, + "optionalDependencies": { + "encoding": "^0.1.12" + } + }, + "node_modules/minipass-flush": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz", + "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==", + "dev": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-json-stream": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minipass-json-stream/-/minipass-json-stream-1.0.1.tgz", + "integrity": "sha512-ODqY18UZt/I8k+b7rl2AENgbWE8IDYam+undIJONvigAz8KR5GWblsFTEfQs0WODsjbSXWlm+JHEv8Gr6Tfdbg==", + "dev": true, + "dependencies": { + "jsonparse": "^1.3.1", + "minipass": "^3.0.0" + } + }, + "node_modules/minipass-pipeline": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", + "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", + "dev": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-sized": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz", + "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==", + "dev": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dev": true, + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true, + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/multicast-dns": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-6.2.3.tgz", + "integrity": "sha512-ji6J5enbMyGRHIAkAOu3WdV8nggqviKCEKtXcOqfphZZtQrmHKycfynJ2V7eVPUA4NhJ6V7Wf4TmGbTwKE9B6g==", + "dev": true, + "dependencies": { + "dns-packet": "^1.3.1", + "thunky": "^1.0.2" + }, + "bin": { + "multicast-dns": "cli.js" + } + }, + "node_modules/multicast-dns-service-types": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz", + "integrity": "sha1-iZ8R2WhuXgXLkbNdXw5jt3PPyQE=", + "dev": true + }, + "node_modules/mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true + }, + "node_modules/nanoid": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.1.tgz", + "integrity": "sha512-n6Vs/3KGyxPQd6uO0eH4Bv0ojGSUvuLlIHtC3Y0kEO23YRge8H9x1GCzLn28YX0H66pMkxuaeESFq4tKISKwdw==", + "dev": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/needle": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/needle/-/needle-2.9.1.tgz", + "integrity": "sha512-6R9fqJ5Zcmf+uYaFgdIHmLwNldn5HbK8L5ybn7Uz+ylX/rnOsSp1AHcvQSrCaFN+qNM1wpymHqD7mVasEOlHGQ==", + "dev": true, + "optional": true, + "dependencies": { + "debug": "^3.2.6", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + }, + "bin": { + "needle": "bin/needle" + }, + "engines": { + "node": ">= 4.4.x" + } + }, + "node_modules/needle/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "optional": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "dev": true + }, + "node_modules/nice-napi": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/nice-napi/-/nice-napi-1.0.2.tgz", + "integrity": "sha512-px/KnJAJZf5RuBGcfD+Sp2pAKq0ytz8j+1NehvgIGFkvtvFrDM3T8E4x/JJODXK9WZow8RRGrbA9QQ3hs+pDhA==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "!win32" + ], + "dependencies": { + "node-addon-api": "^3.0.0", + "node-gyp-build": "^4.2.2" + } + }, + "node_modules/node-addon-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz", + "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==", + "dev": true, + "optional": true + }, + "node_modules/node-forge": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz", + "integrity": "sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==", + "dev": true, + "engines": { + "node": ">= 6.13.0" + } + }, + "node_modules/node-gyp": { + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-8.4.1.tgz", + "integrity": "sha512-olTJRgUtAb/hOXG0E93wZDs5YiJlgbXxTwQAFHyNlRsXQnYzUaF2aGgujZbw+hR8aF4ZG/rST57bWMWD16jr9w==", + "dev": true, + "dependencies": { + "env-paths": "^2.2.0", + "glob": "^7.1.4", + "graceful-fs": "^4.2.6", + "make-fetch-happen": "^9.1.0", + "nopt": "^5.0.0", + "npmlog": "^6.0.0", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.2", + "which": "^2.0.2" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": ">= 10.12.0" + } + }, + "node_modules/node-gyp-build": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.4.0.tgz", + "integrity": "sha512-amJnQCcgtRVw9SvoebO3BKGESClrfXGCUTX9hSn1OuGQTQBOZmVd0Z0OlecpuRksKvbsUqALE8jls/ErClAPuQ==", + "dev": true, + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/node-gyp/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/node-releases": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.3.tgz", + "integrity": "sha512-maHFz6OLqYxz+VQyCAtA3PTX4UP/53pa05fyDNc9CwjvJ0yEh6+xBwKsgCxMNhS8taUKBFYxfuiaD9U/55iFaw==", + "dev": true + }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "dev": true, + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/normalize-range": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", + "integrity": "sha1-LRDAa9/TEuqXd2laTShDlFa3WUI=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-bundled": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-1.1.2.tgz", + "integrity": "sha512-x5DHup0SuyQcmL3s7Rx/YQ8sbw/Hzg0rj48eN0dV7hf5cmQq5PXIeioroH3raV1QC1yh3uTYuMThvEQF3iKgGQ==", + "dev": true, + "dependencies": { + "npm-normalize-package-bin": "^1.0.1" + } + }, + "node_modules/npm-install-checks": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-4.0.0.tgz", + "integrity": "sha512-09OmyDkNLYwqKPOnbI8exiOZU2GVVmQp7tgez2BPi5OZC8M82elDAps7sxC4l//uSUtotWqoEIDwjRvWH4qz8w==", + "dev": true, + "dependencies": { + "semver": "^7.1.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/npm-normalize-package-bin": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-1.0.1.tgz", + "integrity": "sha512-EPfafl6JL5/rU+ot6P3gRSCpPDW5VmIzX959Ob1+ySFUuuYHWHekXpwdUZcKP5C+DS4GEtdJluwBjnsNDl+fSA==", + "dev": true + }, + "node_modules/npm-package-arg": { + "version": "8.1.5", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-8.1.5.tgz", + "integrity": "sha512-LhgZrg0n0VgvzVdSm1oiZworPbTxYHUJCgtsJW8mGvlDpxTM1vSJc3m5QZeUkhAHIzbz3VCHd/R4osi1L1Tg/Q==", + "dev": true, + "dependencies": { + "hosted-git-info": "^4.0.1", + "semver": "^7.3.4", + "validate-npm-package-name": "^3.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/npm-packlist": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-3.0.0.tgz", + "integrity": "sha512-L/cbzmutAwII5glUcf2DBRNY/d0TFd4e/FnaZigJV6JD85RHZXJFGwCndjMWiiViiWSsWt3tiOLpI3ByTnIdFQ==", + "dev": true, + "dependencies": { + "glob": "^7.1.6", + "ignore-walk": "^4.0.1", + "npm-bundled": "^1.1.1", + "npm-normalize-package-bin": "^1.0.1" + }, + "bin": { + "npm-packlist": "bin/index.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/npm-pick-manifest": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-6.1.1.tgz", + "integrity": "sha512-dBsdBtORT84S8V8UTad1WlUyKIY9iMsAmqxHbLdeEeBNMLQDlDWWra3wYUx9EBEIiG/YwAy0XyNHDd2goAsfuA==", + "dev": true, + "dependencies": { + "npm-install-checks": "^4.0.0", + "npm-normalize-package-bin": "^1.0.1", + "npm-package-arg": "^8.1.2", + "semver": "^7.3.4" + } + }, + "node_modules/npm-registry-fetch": { + "version": "12.0.2", + "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-12.0.2.tgz", + "integrity": "sha512-Df5QT3RaJnXYuOwtXBXS9BWs+tHH2olvkCLh6jcR/b/u3DvPMlp3J0TvvYwplPKxHMOwfg287PYih9QqaVFoKA==", + "dev": true, + "dependencies": { + "make-fetch-happen": "^10.0.1", + "minipass": "^3.1.6", + "minipass-fetch": "^1.4.1", + "minipass-json-stream": "^1.0.1", + "minizlib": "^2.1.2", + "npm-package-arg": "^8.1.5" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16" + } + }, + "node_modules/npm-registry-fetch/node_modules/@npmcli/fs": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-2.1.0.tgz", + "integrity": "sha512-DmfBvNXGaetMxj9LTp8NAN9vEidXURrf5ZTslQzEAi/6GbW+4yjaLFQc6Tue5cpZ9Frlk4OBo/Snf1Bh/S7qTQ==", + "dev": true, + "dependencies": { + "@gar/promisify": "^1.1.3", + "semver": "^7.3.5" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/npm-registry-fetch/node_modules/@npmcli/move-file": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/move-file/-/move-file-2.0.0.tgz", + "integrity": "sha512-UR6D5f4KEGWJV6BGPH3Qb2EtgH+t+1XQ1Tt85c7qicN6cezzuHPdZwwAxqZr4JLtnQu0LZsTza/5gmNmSl8XLg==", + "dev": true, + "dependencies": { + "mkdirp": "^1.0.4", + "rimraf": "^3.0.2" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/npm-registry-fetch/node_modules/@tootallnate/once": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", + "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", + "dev": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/npm-registry-fetch/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/npm-registry-fetch/node_modules/cacache": { + "version": "16.0.6", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-16.0.6.tgz", + "integrity": "sha512-9a/MLxGaw3LEGes0HaPez2RgZWDV6X0jrgChsuxfEh8xoDoYGxaGrkMe7Dlyjrb655tA/b8fX0qlUg6Ii5MBvw==", + "dev": true, + "dependencies": { + "@npmcli/fs": "^2.1.0", + "@npmcli/move-file": "^2.0.0", + "chownr": "^2.0.0", + "fs-minipass": "^2.1.0", + "glob": "^8.0.1", + "infer-owner": "^1.0.4", + "lru-cache": "^7.7.1", + "minipass": "^3.1.6", + "minipass-collect": "^1.0.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "mkdirp": "^1.0.4", + "p-map": "^4.0.0", + "promise-inflight": "^1.0.1", + "rimraf": "^3.0.2", + "ssri": "^9.0.0", + "tar": "^6.1.11", + "unique-filename": "^1.1.1" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/npm-registry-fetch/node_modules/glob": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/glob/-/glob-8.0.1.tgz", + "integrity": "sha512-cF7FYZZ47YzmCu7dDy50xSRRfO3ErRfrXuLZcNIuyiJEco0XSrGtuilG19L5xp3NcwTx7Gn+X6Tv3fmsUPTbow==", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^5.0.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm-registry-fetch/node_modules/http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "dev": true, + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/npm-registry-fetch/node_modules/lru-cache": { + "version": "7.8.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.8.1.tgz", + "integrity": "sha512-E1v547OCgJvbvevfjgK9sNKIVXO96NnsTsFPBlg4ZxjhsJSODoH9lk8Bm0OxvHNm6Vm5Yqkl/1fErDxhYL8Skg==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/npm-registry-fetch/node_modules/make-fetch-happen": { + "version": "10.1.2", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-10.1.2.tgz", + "integrity": "sha512-GWMGiZsKVeJACQGJ1P3Z+iNec7pLsU6YW1q11eaPn3RR8nRXHppFWfP7Eu0//55JK3hSjrAQRl8sDa5uXpq1Ew==", + "dev": true, + "dependencies": { + "agentkeepalive": "^4.2.1", + "cacache": "^16.0.2", + "http-cache-semantics": "^4.1.0", + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "is-lambda": "^1.0.1", + "lru-cache": "^7.7.1", + "minipass": "^3.1.6", + "minipass-collect": "^1.0.2", + "minipass-fetch": "^2.0.3", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.3", + "promise-retry": "^2.0.1", + "socks-proxy-agent": "^6.1.1", + "ssri": "^9.0.0" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/npm-registry-fetch/node_modules/make-fetch-happen/node_modules/minipass-fetch": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-2.1.0.tgz", + "integrity": "sha512-H9U4UVBGXEyyWJnqYDCLp1PwD8XIkJ4akNHp1aGVI+2Ym7wQMlxDKi4IB4JbmyU+pl9pEs/cVrK6cOuvmbK4Sg==", + "dev": true, + "dependencies": { + "minipass": "^3.1.6", + "minipass-sized": "^1.0.3", + "minizlib": "^2.1.2" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + }, + "optionalDependencies": { + "encoding": "^0.1.13" + } + }, + "node_modules/npm-registry-fetch/node_modules/minimatch": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz", + "integrity": "sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/npm-registry-fetch/node_modules/ssri": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-9.0.0.tgz", + "integrity": "sha512-Y1Z6J8UYnexKFN1R/hxUaYoY2LVdKEzziPmVAFKiKX8fiwvCJTVzn/xYE9TEWod5OVyNfIHHuVfIEuBClL/uJQ==", + "dev": true, + "dependencies": { + "minipass": "^3.1.1" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npmlog": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-6.0.2.tgz", + "integrity": "sha512-/vBvz5Jfr9dT/aFWd0FIRf+T/Q2WBsLENygUaFUqstqsycmZAP/t5BvFJTK0viFmSUxiUKTUplWy5vt+rvKIxg==", + "dev": true, + "dependencies": { + "are-we-there-yet": "^3.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^4.0.3", + "set-blocking": "^2.0.0" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/nth-check": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.0.1.tgz", + "integrity": "sha512-it1vE95zF6dTT9lBsYbxvqh0Soy4SPowchj0UBGj/V6cTPnXXtQOPUbhZ6CmGzAD/rW22LQK6E96pcdJXk4A4w==", + "dev": true, + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.0.tgz", + "integrity": "sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obuf": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", + "integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==", + "dev": true + }, + "node_modules/on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dev": true, + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/open": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/open/-/open-8.4.0.tgz", + "integrity": "sha512-XgFPPM+B28FtCCgSb9I+s9szOC1vZRSwgWsRUA5ylIxRTgKozqjOCrVOqGsYABPYK5qnfqClxZTFBa8PKt2v6Q==", + "dev": true, + "dependencies": { + "define-lazy-prop": "^2.0.0", + "is-docker": "^2.1.1", + "is-wsl": "^2.2.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", + "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "dev": true, + "dependencies": { + "bl": "^4.1.0", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.5.0", + "is-interactive": "^1.0.0", + "is-unicode-supported": "^0.1.0", + "log-symbols": "^4.1.0", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ora/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ora/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/ora/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/ora/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ora/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-locate/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-map": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", + "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", + "dev": true, + "dependencies": { + "aggregate-error": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-retry": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.1.tgz", + "integrity": "sha512-e2xXGNhZOZ0lfgR9kL34iGlU8N/KO0xZnQxVEwdeOvpqNDQfdnxIYizvWtK8RglUa3bGqI8g0R/BdfzLMxRkiA==", + "dev": true, + "dependencies": { + "@types/retry": "^0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-retry/node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/pacote": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/pacote/-/pacote-12.0.3.tgz", + "integrity": "sha512-CdYEl03JDrRO3x18uHjBYA9TyoW8gy+ThVcypcDkxPtKlw76e4ejhYB6i9lJ+/cebbjpqPW/CijjqxwDTts8Ow==", + "dev": true, + "dependencies": { + "@npmcli/git": "^2.1.0", + "@npmcli/installed-package-contents": "^1.0.6", + "@npmcli/promise-spawn": "^1.2.0", + "@npmcli/run-script": "^2.0.0", + "cacache": "^15.0.5", + "chownr": "^2.0.0", + "fs-minipass": "^2.1.0", + "infer-owner": "^1.0.4", + "minipass": "^3.1.3", + "mkdirp": "^1.0.3", + "npm-package-arg": "^8.0.1", + "npm-packlist": "^3.0.0", + "npm-pick-manifest": "^6.0.0", + "npm-registry-fetch": "^12.0.0", + "promise-retry": "^2.0.1", + "read-package-json-fast": "^2.0.1", + "rimraf": "^3.0.2", + "ssri": "^8.0.1", + "tar": "^6.1.0" + }, + "bin": { + "pacote": "lib/bin.js" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16" + } + }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "dev": true + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-node-version": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parse-node-version/-/parse-node-version-1.0.1.tgz", + "integrity": "sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA==", + "dev": true, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/parse5": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", + "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", + "dev": true + }, + "node_modules/parse5-html-rewriting-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5-html-rewriting-stream/-/parse5-html-rewriting-stream-6.0.1.tgz", + "integrity": "sha512-vwLQzynJVEfUlURxgnf51yAJDQTtVpNyGD8tKi2Za7m+akukNHxCcUQMAa/mUGLhCeicFdpy7Tlvj8ZNKadprg==", + "dev": true, + "dependencies": { + "parse5": "^6.0.1", + "parse5-sax-parser": "^6.0.1" + } + }, + "node_modules/parse5-htmlparser2-tree-adapter": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-6.0.1.tgz", + "integrity": "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA==", + "dev": true, + "dependencies": { + "parse5": "^6.0.1" + } + }, + "node_modules/parse5-sax-parser": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5-sax-parser/-/parse5-sax-parser-6.0.1.tgz", + "integrity": "sha512-kXX+5S81lgESA0LsDuGjAlBybImAChYRMT+/uKCEXFBFOeEhS52qUCydGhU3qLRD8D9DVjaUo821WK7DM4iCeg==", + "dev": true, + "dependencies": { + "parse5": "^6.0.1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=", + "dev": true + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/piscina": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/piscina/-/piscina-3.2.0.tgz", + "integrity": "sha512-yn/jMdHRw+q2ZJhFhyqsmANcbF6V2QwmD84c6xRau+QpQOmtrBCoRGdvTfeuFDYXB5W2m6MfLkjkvQa9lUSmIA==", + "dev": true, + "dependencies": { + "eventemitter-asyncresource": "^1.0.0", + "hdr-histogram-js": "^2.0.1", + "hdr-histogram-percentiles-obj": "^3.0.0" + }, + "optionalDependencies": { + "nice-napi": "^1.0.2" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/portfinder": { + "version": "1.0.28", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.28.tgz", + "integrity": "sha512-Se+2isanIcEqf2XMHjyUKskczxbPH7dQnlMjXX6+dybayyHvAf/TCgyMRlzf/B6QDhAEFOGes0pzRo3by4AbMA==", + "dev": true, + "dependencies": { + "async": "^2.6.2", + "debug": "^3.1.1", + "mkdirp": "^0.5.5" + }, + "engines": { + "node": ">= 0.12.0" + } + }, + "node_modules/portfinder/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/portfinder/node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/postcss": { + "version": "8.4.5", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.5.tgz", + "integrity": "sha512-jBDboWM8qpaqwkMwItqTQTiFikhs/67OYVvblFFTM7MrZjt6yMKd6r2kgXizEbTTljacm4NldIlZnhbjr84QYg==", + "dev": true, + "dependencies": { + "nanoid": "^3.1.30", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + } + }, + "node_modules/postcss-attribute-case-insensitive": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/postcss-attribute-case-insensitive/-/postcss-attribute-case-insensitive-5.0.0.tgz", + "integrity": "sha512-b4g9eagFGq9T5SWX4+USfVyjIb3liPnjhHHRMP7FMB2kFVpYyfEscV0wP3eaXhKlcHKUut8lt5BGoeylWA/dBQ==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.2" + }, + "peerDependencies": { + "postcss": "^8.0.2" + } + }, + "node_modules/postcss-color-functional-notation": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/postcss-color-functional-notation/-/postcss-color-functional-notation-4.2.2.tgz", + "integrity": "sha512-DXVtwUhIk4f49KK5EGuEdgx4Gnyj6+t2jBSEmxvpIK9QI40tWrpS2Pua8Q7iIZWBrki2QOaeUdEaLPPa91K0RQ==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-color-hex-alpha": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/postcss-color-hex-alpha/-/postcss-color-hex-alpha-8.0.3.tgz", + "integrity": "sha512-fESawWJCrBV035DcbKRPAVmy21LpoyiXdPTuHUfWJ14ZRjY7Y7PA6P4g8z6LQGYhU1WAxkTxjIjurXzoe68Glw==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-color-rebeccapurple": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/postcss-color-rebeccapurple/-/postcss-color-rebeccapurple-7.0.2.tgz", + "integrity": "sha512-SFc3MaocHaQ6k3oZaFwH8io6MdypkUtEy/eXzXEB1vEQlO3S3oDc/FSZA8AsS04Z25RirQhlDlHLh3dn7XewWw==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.3" + } + }, + "node_modules/postcss-custom-media": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/postcss-custom-media/-/postcss-custom-media-8.0.0.tgz", + "integrity": "sha512-FvO2GzMUaTN0t1fBULDeIvxr5IvbDXcIatt6pnJghc736nqNgsGao5NT+5+WVLAQiTt6Cb3YUms0jiPaXhL//g==", + "dev": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-custom-properties": { + "version": "12.1.7", + "resolved": "https://registry.npmjs.org/postcss-custom-properties/-/postcss-custom-properties-12.1.7.tgz", + "integrity": "sha512-N/hYP5gSoFhaqxi2DPCmvto/ZcRDVjE3T1LiAMzc/bg53hvhcHOLpXOHb526LzBBp5ZlAUhkuot/bfpmpgStJg==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-custom-selectors": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/postcss-custom-selectors/-/postcss-custom-selectors-6.0.0.tgz", + "integrity": "sha512-/1iyBhz/W8jUepjGyu7V1OPcGbc636snN1yXEQCinb6Bwt7KxsiU7/bLQlp8GwAXzCh7cobBU5odNn/2zQWR8Q==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.4" + }, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "postcss": "^8.1.2" + } + }, + "node_modules/postcss-dir-pseudo-class": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/postcss-dir-pseudo-class/-/postcss-dir-pseudo-class-6.0.4.tgz", + "integrity": "sha512-I8epwGy5ftdzNWEYok9VjW9whC4xnelAtbajGv4adql4FIF09rnrxnA9Y8xSHN47y7gqFIv10C5+ImsLeJpKBw==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.9" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-double-position-gradients": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/postcss-double-position-gradients/-/postcss-double-position-gradients-3.1.1.tgz", + "integrity": "sha512-jM+CGkTs4FcG53sMPjrrGE0rIvLDdCrqMzgDC5fLI7JHDO7o6QG8C5TQBtExb13hdBdoH9C2QVbG4jo2y9lErQ==", + "dev": true, + "dependencies": { + "@csstools/postcss-progressive-custom-properties": "^1.1.0", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-env-function": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/postcss-env-function/-/postcss-env-function-4.0.6.tgz", + "integrity": "sha512-kpA6FsLra+NqcFnL81TnsU+Z7orGtDTxcOhl6pwXeEq1yFPpRMkCDpHhrz8CFQDr/Wfm0jLiNQ1OsGGPjlqPwA==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-focus-visible": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/postcss-focus-visible/-/postcss-focus-visible-6.0.4.tgz", + "integrity": "sha512-QcKuUU/dgNsstIK6HELFRT5Y3lbrMLEOwG+A4s5cA+fx3A3y/JTq3X9LaOj3OC3ALH0XqyrgQIgey/MIZ8Wczw==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.9" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-focus-within": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/postcss-focus-within/-/postcss-focus-within-5.0.4.tgz", + "integrity": "sha512-vvjDN++C0mu8jz4af5d52CB184ogg/sSxAFS+oUJQq2SuCe7T5U2iIsVJtsCp2d6R4j0jr5+q3rPkBVZkXD9fQ==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.9" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-font-variant": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/postcss-font-variant/-/postcss-font-variant-5.0.0.tgz", + "integrity": "sha512-1fmkBaCALD72CK2a9i468mA/+tr9/1cBxRRMXOUaZqO43oWPR5imcyPjXwuv7PXbCid4ndlP5zWhidQVVa3hmA==", + "dev": true, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-gap-properties": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/postcss-gap-properties/-/postcss-gap-properties-3.0.3.tgz", + "integrity": "sha512-rPPZRLPmEKgLk/KlXMqRaNkYTUpE7YC+bOIQFN5xcu1Vp11Y4faIXv6/Jpft6FMnl6YRxZqDZG0qQOW80stzxQ==", + "dev": true, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-image-set-function": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/postcss-image-set-function/-/postcss-image-set-function-4.0.6.tgz", + "integrity": "sha512-KfdC6vg53GC+vPd2+HYzsZ6obmPqOk6HY09kttU19+Gj1nC3S3XBVEXDHxkhxTohgZqzbUb94bKXvKDnYWBm/A==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-import": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-14.0.2.tgz", + "integrity": "sha512-BJ2pVK4KhUyMcqjuKs9RijV5tatNzNa73e/32aBVE/ejYPe37iH+6vAu9WvqUkB5OAYgLHzbSvzHnorybJCm9g==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-initial": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/postcss-initial/-/postcss-initial-4.0.1.tgz", + "integrity": "sha512-0ueD7rPqX8Pn1xJIjay0AZeIuDoF+V+VvMt/uOnn+4ezUKhZM/NokDeP6DwMNyIoYByuN/94IQnt5FEkaN59xQ==", + "dev": true, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-lab-function": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-lab-function/-/postcss-lab-function-4.2.0.tgz", + "integrity": "sha512-Zb1EO9DGYfa3CP8LhINHCcTTCTLI+R3t7AX2mKsDzdgVQ/GkCpHOTgOr6HBHslP7XDdVbqgHW5vvRPMdVANQ8w==", + "dev": true, + "dependencies": { + "@csstools/postcss-progressive-custom-properties": "^1.1.0", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-loader": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/postcss-loader/-/postcss-loader-6.2.1.tgz", + "integrity": "sha512-WbbYpmAaKcux/P66bZ40bpWsBucjx/TTgVVzRZ9yUO8yQfVBlameJ0ZGVaPfH64hNSBh63a+ICP5nqOpBA0w+Q==", + "dev": true, + "dependencies": { + "cosmiconfig": "^7.0.0", + "klona": "^2.0.5", + "semver": "^7.3.5" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "postcss": "^7.0.0 || ^8.0.1", + "webpack": "^5.0.0" + } + }, + "node_modules/postcss-logical": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/postcss-logical/-/postcss-logical-5.0.4.tgz", + "integrity": "sha512-RHXxplCeLh9VjinvMrZONq7im4wjWGlRJAqmAVLXyZaXwfDWP73/oq4NdIp+OZwhQUMj0zjqDfM5Fj7qby+B4g==", + "dev": true, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-media-minmax": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/postcss-media-minmax/-/postcss-media-minmax-5.0.0.tgz", + "integrity": "sha512-yDUvFf9QdFZTuCUg0g0uNSHVlJ5X1lSzDZjPSFaiCWvjgsvu8vEVxtahPrLMinIDEEGnx6cBe6iqdx5YWz08wQ==", + "dev": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-extract-imports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.0.0.tgz", + "integrity": "sha512-bdHleFnP3kZ4NYDhuGlVK+CMrQ/pqUm8bx/oGL93K6gVwiclvX5x0n76fYMKuIGKzlABOy13zsvqjb0f92TEXw==", + "dev": true, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-local-by-default": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.0.0.tgz", + "integrity": "sha512-sT7ihtmGSF9yhm6ggikHdV0hlziDTX7oFoXtuVWeDd3hHObNkcHRo9V3yg7vCAY7cONyxJC/XXCmmiHHcvX7bQ==", + "dev": true, + "dependencies": { + "icss-utils": "^5.0.0", + "postcss-selector-parser": "^6.0.2", + "postcss-value-parser": "^4.1.0" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-scope": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-3.0.0.tgz", + "integrity": "sha512-hncihwFA2yPath8oZ15PZqvWGkWf+XUfQgUGamS4LqoP1anQLOsOJw0vr7J7IwLpoY9fatA2qiGUGmuZL0Iqlg==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.4" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-values": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz", + "integrity": "sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ==", + "dev": true, + "dependencies": { + "icss-utils": "^5.0.0" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-nesting": { + "version": "10.1.4", + "resolved": "https://registry.npmjs.org/postcss-nesting/-/postcss-nesting-10.1.4.tgz", + "integrity": "sha512-2ixdQ59ik/Gt1+oPHiI1kHdwEI8lLKEmui9B1nl6163ANLC+GewQn7fXMxJF2JSb4i2MKL96GU8fIiQztK4TTA==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.10" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-overflow-shorthand": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/postcss-overflow-shorthand/-/postcss-overflow-shorthand-3.0.3.tgz", + "integrity": "sha512-CxZwoWup9KXzQeeIxtgOciQ00tDtnylYIlJBBODqkgS/PU2jISuWOL/mYLHmZb9ZhZiCaNKsCRiLp22dZUtNsg==", + "dev": true, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-page-break": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/postcss-page-break/-/postcss-page-break-3.0.4.tgz", + "integrity": "sha512-1JGu8oCjVXLa9q9rFTo4MbeeA5FMe00/9C7lN4va606Rdb+HkxXtXsmEDrIraQ11fGz/WvKWa8gMuCKkrXpTsQ==", + "dev": true, + "peerDependencies": { + "postcss": "^8" + } + }, + "node_modules/postcss-place": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/postcss-place/-/postcss-place-7.0.4.tgz", + "integrity": "sha512-MrgKeiiu5OC/TETQO45kV3npRjOFxEHthsqGtkh3I1rPbZSbXGD/lZVi9j13cYh+NA8PIAPyk6sGjT9QbRyvSg==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-preset-env": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/postcss-preset-env/-/postcss-preset-env-7.2.3.tgz", + "integrity": "sha512-Ok0DhLfwrcNGrBn8sNdy1uZqWRk/9FId0GiQ39W4ILop5GHtjJs8bu1MY9isPwHInpVEPWjb4CEcEaSbBLpfwA==", + "dev": true, + "dependencies": { + "autoprefixer": "^10.4.2", + "browserslist": "^4.19.1", + "caniuse-lite": "^1.0.30001299", + "css-blank-pseudo": "^3.0.2", + "css-has-pseudo": "^3.0.3", + "css-prefers-color-scheme": "^6.0.2", + "cssdb": "^5.0.0", + "postcss-attribute-case-insensitive": "^5.0.0", + "postcss-color-functional-notation": "^4.2.1", + "postcss-color-hex-alpha": "^8.0.2", + "postcss-color-rebeccapurple": "^7.0.2", + "postcss-custom-media": "^8.0.0", + "postcss-custom-properties": "^12.1.2", + "postcss-custom-selectors": "^6.0.0", + "postcss-dir-pseudo-class": "^6.0.3", + "postcss-double-position-gradients": "^3.0.4", + "postcss-env-function": "^4.0.4", + "postcss-focus-visible": "^6.0.3", + "postcss-focus-within": "^5.0.3", + "postcss-font-variant": "^5.0.0", + "postcss-gap-properties": "^3.0.2", + "postcss-image-set-function": "^4.0.4", + "postcss-initial": "^4.0.1", + "postcss-lab-function": "^4.0.3", + "postcss-logical": "^5.0.3", + "postcss-media-minmax": "^5.0.0", + "postcss-nesting": "^10.1.2", + "postcss-overflow-shorthand": "^3.0.2", + "postcss-page-break": "^3.0.4", + "postcss-place": "^7.0.3", + "postcss-pseudo-class-any-link": "^7.0.2", + "postcss-replace-overflow-wrap": "^4.0.0", + "postcss-selector-not": "^5.0.0" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-pseudo-class-any-link": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/postcss-pseudo-class-any-link/-/postcss-pseudo-class-any-link-7.1.2.tgz", + "integrity": "sha512-76XzEQv3g+Vgnz3tmqh3pqQyRojkcJ+pjaePsyhcyf164p9aZsu3t+NWxkZYbcHLK1ju5Qmalti2jPI5IWCe5w==", + "dev": true, + "dependencies": { + "postcss-selector-parser": "^6.0.10" + }, + "engines": { + "node": "^12 || ^14 || >=16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/postcss-replace-overflow-wrap": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/postcss-replace-overflow-wrap/-/postcss-replace-overflow-wrap-4.0.0.tgz", + "integrity": "sha512-KmF7SBPphT4gPPcKZc7aDkweHiKEEO8cla/GjcBK+ckKxiZslIu3C4GCRW3DNfL0o7yW7kMQu9xlZ1kXRXLXtw==", + "dev": true, + "peerDependencies": { + "postcss": "^8.0.3" + } + }, + "node_modules/postcss-selector-not": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/postcss-selector-not/-/postcss-selector-not-5.0.0.tgz", + "integrity": "sha512-/2K3A4TCP9orP4TNS7u3tGdRFVKqz/E6pX3aGnriPG0jU78of8wsUcqE4QAhWEU0d+WnMSF93Ah3F//vUtK+iQ==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.0.10", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", + "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==", + "dev": true, + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true + }, + "node_modules/pretty-bytes": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-5.6.0.tgz", + "integrity": "sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg==", + "dev": true, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true + }, + "node_modules/promise-inflight": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", + "integrity": "sha1-mEcocL8igTL8vdhoEputEsPAKeM=", + "dev": true + }, + "node_modules/promise-retry": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz", + "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==", + "dev": true, + "dependencies": { + "err-code": "^2.0.2", + "retry": "^0.12.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dev": true, + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-addr/node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", + "dev": true, + "optional": true + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/qjobs": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/qjobs/-/qjobs-1.2.0.tgz", + "integrity": "sha512-8YOJEHtxpySA3fFDyCRxA+UUV+fA+rTWnuWvylOK/NCjhY+b4ocCtmu8TtsWb+mYeU+GCHf/S66KZF/AsteKHg==", + "dev": true, + "engines": { + "node": ">=0.9" + } + }, + "node_modules/qs": { + "version": "6.10.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.10.3.tgz", + "integrity": "sha512-wr7M2E0OFRfIfJZjKGieI8lBKb7fRCH4Fv5KNPEs7gJ8jadvotdsS08PzOKR7opXhZ/Xkjtt3WF9g38drmyRqQ==", + "dev": true, + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", + "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "dev": true, + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha1-5mTvMRYRZsl1HNvo28+GtftY93Q=", + "dev": true, + "dependencies": { + "pify": "^2.3.0" + } + }, + "node_modules/read-package-json-fast": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/read-package-json-fast/-/read-package-json-fast-2.0.3.tgz", + "integrity": "sha512-W/BKtbL+dUjTuRL2vziuYhp76s5HZ9qQhd/dKfWIZveD0O40453QNyZhC0e63lqZrAQ4jiOapVoeJ7JrszenQQ==", + "dev": true, + "dependencies": { + "json-parse-even-better-errors": "^2.3.0", + "npm-normalize-package-bin": "^1.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/reflect-metadata": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", + "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==", + "dev": true + }, + "node_modules/regenerate": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz", + "integrity": "sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A==", + "dev": true + }, + "node_modules/regenerate-unicode-properties": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.0.1.tgz", + "integrity": "sha512-vn5DU6yg6h8hP/2OkQo3K7uVILvY4iu0oI4t3HFa81UPkhGJwkRwM10JEc3upjdhHjs/k8GJY1sRBhk5sr69Bw==", + "dev": true, + "dependencies": { + "regenerate": "^1.4.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.9", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==", + "dev": true + }, + "node_modules/regenerator-transform": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.15.0.tgz", + "integrity": "sha512-LsrGtPmbYg19bcPHwdtmXwbW+TqNvtY4riE3P83foeHRroMbH6/2ddFBfab3t7kbzc7v7p4wbkIecHImqt0QNg==", + "dev": true, + "dependencies": { + "@babel/runtime": "^7.8.4" + } + }, + "node_modules/regex-parser": { + "version": "2.2.11", + "resolved": "https://registry.npmjs.org/regex-parser/-/regex-parser-2.2.11.tgz", + "integrity": "sha512-jbD/FT0+9MBU2XAZluI7w2OBs1RBi6p9M83nkoZayQXXU9e8Robt69FcZc7wU4eJD/YFTjn1JdCk3rbMJajz8Q==", + "dev": true + }, + "node_modules/regexp.prototype.flags": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.4.3.tgz", + "integrity": "sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "functions-have-names": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexpu-core": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-5.0.1.tgz", + "integrity": "sha512-CriEZlrKK9VJw/xQGJpQM5rY88BtuL8DM+AEwvcThHilbxiTAy8vq4iJnd2tqq8wLmjbGZzP7ZcKFjbGkmEFrw==", + "dev": true, + "dependencies": { + "regenerate": "^1.4.2", + "regenerate-unicode-properties": "^10.0.1", + "regjsgen": "^0.6.0", + "regjsparser": "^0.8.2", + "unicode-match-property-ecmascript": "^2.0.0", + "unicode-match-property-value-ecmascript": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/regjsgen": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.6.0.tgz", + "integrity": "sha512-ozE883Uigtqj3bx7OhL1KNbCzGyW2NQZPl6Hs09WTvCuZD5sTI4JY58bkbQWa/Y9hxIsvJ3M8Nbf7j54IqeZbA==", + "dev": true + }, + "node_modules/regjsparser": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.8.4.tgz", + "integrity": "sha512-J3LABycON/VNEu3abOviqGHuB/LOtOQj8SKmfP9anY5GfAVw/SPjwzSjxGjbZXIxbGfqTHtJw58C2Li/WkStmA==", + "dev": true, + "dependencies": { + "jsesc": "~0.5.0" + }, + "bin": { + "regjsparser": "bin/parser" + } + }, + "node_modules/regjsparser/node_modules/jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", + "dev": true + }, + "node_modules/resolve": { + "version": "1.22.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.0.tgz", + "integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.8.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-url-loader": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-url-loader/-/resolve-url-loader-5.0.0.tgz", + "integrity": "sha512-uZtduh8/8srhBoMx//5bwqjQ+rfYOUq8zC9NrMUGtjBiGTtFJM42s58/36+hTqeqINcnYe08Nj3LkK9lW4N8Xg==", + "dev": true, + "dependencies": { + "adjust-sourcemap-loader": "^4.0.0", + "convert-source-map": "^1.7.0", + "loader-utils": "^2.0.0", + "postcss": "^8.2.14", + "source-map": "0.6.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/resolve-url-loader/node_modules/loader-utils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.2.tgz", + "integrity": "sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A==", + "dev": true, + "dependencies": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^2.1.2" + }, + "engines": { + "node": ">=8.9.0" + } + }, + "node_modules/resolve-url-loader/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha1-G0KmJmoh8HQh0bC1S33BZ7AcATs=", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "dev": true, + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rfdc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.0.tgz", + "integrity": "sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA==", + "dev": true + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/rxjs": { + "version": "6.6.7", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", + "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", + "dependencies": { + "tslib": "^1.9.0" + }, + "engines": { + "npm": ">=2.0.0" + } + }, + "node_modules/rxjs/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==" + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "node_modules/sass": { + "version": "1.49.9", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.49.9.tgz", + "integrity": "sha512-YlYWkkHP9fbwaFRZQRXgDi3mXZShslVmmo+FVK3kHLUELHHEYrCmL1x6IUjC7wLS6VuJSAFXRQS/DxdsC4xL1A==", + "dev": true, + "dependencies": { + "chokidar": ">=3.0.0 <4.0.0", + "immutable": "^4.0.0", + "source-map-js": ">=0.6.2 <2.0.0" + }, + "bin": { + "sass": "sass.js" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/sass-loader": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-12.4.0.tgz", + "integrity": "sha512-7xN+8khDIzym1oL9XyS6zP6Ges+Bo2B2xbPrjdMHEYyV3AQYhd/wXeru++3ODHF0zMjYmVadblSKrPrjEkL8mg==", + "dev": true, + "dependencies": { + "klona": "^2.0.4", + "neo-async": "^2.6.2" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "fibers": ">= 3.1.0", + "node-sass": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0", + "sass": "^1.3.0", + "webpack": "^5.0.0" + }, + "peerDependenciesMeta": { + "fibers": { + "optional": true + }, + "node-sass": { + "optional": true + }, + "sass": { + "optional": true + } + } + }, + "node_modules/sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", + "dev": true + }, + "node_modules/schema-utils": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-2.7.1.tgz", + "integrity": "sha512-SHiNtMOUGWBQJwzISiVYKu82GiV4QYGePp3odlY1tuKO7gPtphAT5R/py0fA6xtbgLL/RvtJZnU9b8s0F1q0Xg==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.5", + "ajv": "^6.12.4", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 8.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/select-hose": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", + "integrity": "sha1-Yl2GWPhlr0Psliv8N2o3NZpJlMo=", + "dev": true + }, + "node_modules/selfsigned": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-2.0.1.tgz", + "integrity": "sha512-LmME957M1zOsUhG+67rAjKfiWFox3SBxE/yymatMZsAx+oMrJ0YQ8AToOnyCm7xbeg2ep37IHLxdu0o2MavQOQ==", + "dev": true, + "dependencies": { + "node-forge": "^1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver": { + "version": "7.3.7", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", + "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver-dsl": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/semver-dsl/-/semver-dsl-1.0.1.tgz", + "integrity": "sha1-02eN5VVeimH2Ke7QJTZq5fJzQKA=", + "dev": true, + "dependencies": { + "semver": "^5.3.0" + } + }, + "node_modules/semver-dsl/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/send": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "dev": true, + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/send/node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/send/node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz", + "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", + "dev": true, + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/serve-index": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz", + "integrity": "sha1-03aNabHn2C5c4FD/9bRTvqEqkjk=", + "dev": true, + "dependencies": { + "accepts": "~1.3.4", + "batch": "0.6.1", + "debug": "2.6.9", + "escape-html": "~1.0.3", + "http-errors": "~1.6.2", + "mime-types": "~2.1.17", + "parseurl": "~1.3.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/serve-index/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/serve-index/node_modules/http-errors": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", + "integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=", + "dev": true, + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/serve-index/node_modules/inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "node_modules/serve-index/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "node_modules/serve-index/node_modules/setprototypeof": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", + "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "dev": true + }, + "node_modules/serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "dev": true, + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", + "dev": true + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true + }, + "node_modules/shallow-clone": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", + "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", + "dev": true, + "dependencies": { + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dev": true, + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "node_modules/slash": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-4.0.0.tgz", + "integrity": "sha512-3dOsAHXXUkQTpOYcoAxLIorMTp4gIQr5IW3iVb7A7lFIp0VHhnynm9izx6TssdrIcVIESAlVjtnO2K8bg+Coew==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "dev": true, + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socket.io": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.4.1.tgz", + "integrity": "sha512-s04vrBswdQBUmuWJuuNTmXUVJhP0cVky8bBDhdkf8y0Ptsu7fKU2LuLbts9g+pdmAdyMMn8F/9Mf1/wbtUN0fg==", + "dev": true, + "dependencies": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "debug": "~4.3.2", + "engine.io": "~6.1.0", + "socket.io-adapter": "~2.3.3", + "socket.io-parser": "~4.0.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-adapter": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.3.3.tgz", + "integrity": "sha512-Qd/iwn3VskrpNO60BeRyCyr8ZWw9CPZyitW4AQwmRZ8zCiyDiL+znRnWX6tDHXnWn1sJrM1+b6Mn6wEDJJ4aYQ==", + "dev": true + }, + "node_modules/socket.io-parser": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.0.4.tgz", + "integrity": "sha512-t+b0SS+IxG7Rxzda2EVvyBZbvFPBCjJoyHuE0P//7OAsN23GItzDRdWa6ALxZI/8R5ygK7jAR6t028/z+7295g==", + "dev": true, + "dependencies": { + "@types/component-emitter": "^1.2.10", + "component-emitter": "~1.3.0", + "debug": "~4.3.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/sockjs": { + "version": "0.3.24", + "resolved": "https://registry.npmjs.org/sockjs/-/sockjs-0.3.24.tgz", + "integrity": "sha512-GJgLTZ7vYb/JtPSSZ10hsOYIvEYsjbNU+zPdIHcUaWVNUEPivzxku31865sSSud0Da0W4lEeOPlmw93zLQchuQ==", + "dev": true, + "dependencies": { + "faye-websocket": "^0.11.3", + "uuid": "^8.3.2", + "websocket-driver": "^0.7.4" + } + }, + "node_modules/socks": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.6.2.tgz", + "integrity": "sha512-zDZhHhZRY9PxRruRMR7kMhnf3I8hDs4S3f9RecfnGxvcBHQcKcIH/oUcEWffsfl1XxdYlA7nnlGbbTvPz9D8gA==", + "dev": true, + "dependencies": { + "ip": "^1.1.5", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.13.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-6.2.0.tgz", + "integrity": "sha512-wWqJhjb32Q6GsrUqzuFkukxb/zzide5quXYcMVpIjxalDBBYy2nqKCFQ/9+Ie4dvOYSQdOk3hUlZSdzZOd3zMQ==", + "dev": true, + "dependencies": { + "agent-base": "^6.0.2", + "debug": "^4.3.3", + "socks": "^2.6.2" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/source-map": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-loader": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/source-map-loader/-/source-map-loader-3.0.1.tgz", + "integrity": "sha512-Vp1UsfyPvgujKQzi4pyDiTOnE3E4H+yHvkVRN3c/9PJmQS4CQJExvcDvaX/D+RV+xQben9HJ56jMJS3CgUeWyA==", + "dev": true, + "dependencies": { + "abab": "^2.0.5", + "iconv-lite": "^0.6.3", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + } + }, + "node_modules/source-map-loader/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-resolve": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.6.0.tgz", + "integrity": "sha512-KXBr9d/fO/bWo97NXsPIAW1bFSBOuCnjbNTBMO7N59hsv5i9yzRDfcYwwt0l04+VqnKC+EwzvJZIP/qkuMgR/w==", + "deprecated": "See https://github.com/lydell/source-map-resolve#deprecated", + "dev": true, + "dependencies": { + "atob": "^2.1.2", + "decode-uri-component": "^0.2.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "dev": true + }, + "node_modules/spdy": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/spdy/-/spdy-4.0.2.tgz", + "integrity": "sha512-r46gZQZQV+Kl9oItvl1JZZqJKGr+oEkB08A6BzkiR7593/7IbtuncXHd2YoYeTsG4157ZssMu9KYvUHLcjcDoA==", + "dev": true, + "dependencies": { + "debug": "^4.1.0", + "handle-thing": "^2.0.0", + "http-deceiver": "^1.2.7", + "select-hose": "^2.0.0", + "spdy-transport": "^3.0.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/spdy-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdy-transport/-/spdy-transport-3.0.0.tgz", + "integrity": "sha512-hsLVFE5SjA6TCisWeJXFKniGGOpBgMLmerfO2aCyCU5s7nJ/rpAepqmFifv/GCbSbueEeAJJnmSQ2rKC/g8Fcw==", + "dev": true, + "dependencies": { + "debug": "^4.1.0", + "detect-node": "^2.0.4", + "hpack.js": "^2.1.6", + "obuf": "^1.1.2", + "readable-stream": "^3.0.6", + "wbuf": "^1.7.3" + } + }, + "node_modules/sprintf-js": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.2.tgz", + "integrity": "sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug==", + "dev": true + }, + "node_modules/ssri": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-8.0.1.tgz", + "integrity": "sha512-97qShzy1AiyxvPNIkLWoGua7xoQzzPjQ0HAH4B0rWKo7SZ6USuPcrUiAFrws0UH8RrbWmgq3LMTObhPIHbbBeQ==", + "dev": true, + "dependencies": { + "minipass": "^3.1.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/streamroller": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/streamroller/-/streamroller-3.0.2.tgz", + "integrity": "sha512-ur6y5S5dopOaRXBuRIZ1u6GC5bcEXHRZKgfBjfCglMhmIf+roVCECjvkEYzNQOXIN2/JPnkMPW/8B3CZoKaEPA==", + "dev": true, + "dependencies": { + "date-format": "^4.0.3", + "debug": "^4.1.1", + "fs-extra": "^10.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/streamroller/node_modules/fs-extra": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.0.1.tgz", + "integrity": "sha512-NbdoVMZso2Lsrn/QwLXOy6rm0ufY2zEOKCDzJR/0kBsb0E6qed0P3iYK+Ath3BfvXEeu4JhEtXLgILx5psUfag==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/streamroller/node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/streamroller/node_modules/universalify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==", + "dev": true, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/stylus": { + "version": "0.56.0", + "resolved": "https://registry.npmjs.org/stylus/-/stylus-0.56.0.tgz", + "integrity": "sha512-Ev3fOb4bUElwWu4F9P9WjnnaSpc8XB9OFHSFZSKMFL1CE1oM+oFXWEgAqPmmZIyhBihuqIQlFsVTypiiS9RxeA==", + "dev": true, + "dependencies": { + "css": "^3.0.0", + "debug": "^4.3.2", + "glob": "^7.1.6", + "safer-buffer": "^2.1.2", + "sax": "~1.2.4", + "source-map": "^0.7.3" + }, + "bin": { + "stylus": "bin/stylus" + }, + "engines": { + "node": "*" + } + }, + "node_modules/stylus-loader": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/stylus-loader/-/stylus-loader-6.2.0.tgz", + "integrity": "sha512-5dsDc7qVQGRoc6pvCL20eYgRUxepZ9FpeK28XhdXaIPP6kXr6nI1zAAKFQgP5OBkOfKaURp4WUpJzspg1f01Gg==", + "dev": true, + "dependencies": { + "fast-glob": "^3.2.7", + "klona": "^2.0.4", + "normalize-path": "^3.0.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "stylus": ">=0.52.4", + "webpack": "^5.0.0" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/symbol-observable": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-4.0.0.tgz", + "integrity": "sha512-b19dMThMV4HVFynSAM1++gBHAbk2Tc/osgLIBZMKsyqh34jb2e8Os7T6ZW/Bt3pJFdBTd2JwAnAAEQV7rSNvcQ==", + "dev": true, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/tapable": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", + "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/tar": { + "version": "6.1.11", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.11.tgz", + "integrity": "sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA==", + "dev": true, + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^3.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/terser": { + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.11.0.tgz", + "integrity": "sha512-uCA9DLanzzWSsN1UirKwylhhRz3aKPInlfmpGfw8VN6jHsAtu8HJtIpeeHHK23rxnE/cDc+yvmq5wqkIC6Kn0A==", + "dev": true, + "dependencies": { + "acorn": "^8.5.0", + "commander": "^2.20.0", + "source-map": "~0.7.2", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser-webpack-plugin": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.1.4.tgz", + "integrity": "sha512-C2WkFwstHDhVEmsmlCxrXUtVklS+Ir1A7twrYzrDrQQOIMOaVAYykaoo/Aq1K0QRkMoY2hhvDQY1cm4jnIMFwA==", + "dev": true, + "dependencies": { + "jest-worker": "^27.0.2", + "p-limit": "^3.1.0", + "schema-utils": "^3.0.0", + "serialize-javascript": "^6.0.0", + "source-map": "^0.6.1", + "terser": "^5.7.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + } + }, + "node_modules/terser-webpack-plugin/node_modules/schema-utils": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.1.1.tgz", + "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/terser-webpack-plugin/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, + "node_modules/thunky": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", + "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==", + "dev": true + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-node": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-7.0.1.tgz", + "integrity": "sha512-BVwVbPJRspzNh2yfslyT1PSbl5uIk03EZlb493RKHN4qej/D06n1cEhjlOJG69oFsE7OT8XjpTUcYf6pKTLMhw==", + "dev": true, + "dependencies": { + "arrify": "^1.0.0", + "buffer-from": "^1.1.0", + "diff": "^3.1.0", + "make-error": "^1.1.1", + "minimist": "^1.2.0", + "mkdirp": "^0.5.1", + "source-map-support": "^0.5.6", + "yn": "^2.0.0" + }, + "bin": { + "ts-node": "dist/bin.js" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/ts-node/node_modules/mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "dev": true, + "dependencies": { + "minimist": "^1.2.5" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/tslib": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" + }, + "node_modules/tslint": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-6.1.3.tgz", + "integrity": "sha512-IbR4nkT96EQOvKE2PW/djGz8iGNeJ4rF2mBfiYaR/nvUWYKJhLwimoJKgjIFEIDibBtOevj7BqCRL4oHeWWUCg==", + "deprecated": "TSLint has been deprecated in favor of ESLint. Please see https://github.com/palantir/tslint/issues/4534 for more information.", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.0.0", + "builtin-modules": "^1.1.1", + "chalk": "^2.3.0", + "commander": "^2.12.1", + "diff": "^4.0.1", + "glob": "^7.1.1", + "js-yaml": "^3.13.1", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.3", + "resolve": "^1.3.2", + "semver": "^5.3.0", + "tslib": "^1.13.0", + "tsutils": "^2.29.0" + }, + "bin": { + "tslint": "bin/tslint" + }, + "engines": { + "node": ">=4.8.0" + }, + "peerDependencies": { + "typescript": ">=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >=3.0.0-dev || >= 3.1.0-dev || >= 3.2.0-dev || >= 4.0.0-dev" + } + }, + "node_modules/tslint/node_modules/diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/tslint/node_modules/mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "dev": true, + "dependencies": { + "minimist": "^1.2.5" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/tslint/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/tslint/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, + "node_modules/tslint/node_modules/tsutils": { + "version": "2.29.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz", + "integrity": "sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==", + "dev": true, + "dependencies": { + "tslib": "^1.8.1" + }, + "peerDependencies": { + "typescript": ">=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >= 3.0.0-dev || >= 3.1.0-dev" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dev": true, + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typed-assert": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/typed-assert/-/typed-assert-1.0.9.tgz", + "integrity": "sha512-KNNZtayBCtmnNmbo5mG47p1XsCyrx6iVqomjcZnec/1Y5GGARaxPs6r49RnSPeUP3YjNYiU9sQHAtY4BBvnZwg==", + "dev": true + }, + "node_modules/typescript": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.6.3.tgz", + "integrity": "sha512-yNIatDa5iaofVozS/uQJEl3JRWLKKGJKh6Yaiv0GLGSuhpFJe7P3SbHZ8/yjAHRQwKRoA6YZqlfjXWmVzoVSMw==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/ua-parser-js": { + "version": "0.7.31", + "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.31.tgz", + "integrity": "sha512-qLK/Xe9E2uzmYI3qLeOmI0tEOt+TBBQyUIAh4aAgU05FVYzeZrKUdkAZfBNVGRaHVgV0TDkdEngJSw/SyQchkQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/ua-parser-js" + }, + { + "type": "paypal", + "url": "https://paypal.me/faisalman" + } + ], + "engines": { + "node": "*" + } + }, + "node_modules/unicode-canonical-property-names-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.0.tgz", + "integrity": "sha512-yY5PpDlfVIU5+y/BSCxAJRBIS1Zc2dDG3Ujq+sR0U+JjUevW2JhocOF+soROYDSaAezOzOKuyyixhD6mBknSmQ==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-match-property-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-2.0.0.tgz", + "integrity": "sha512-5kaZCrbp5mmbz5ulBkDkbY0SsPOjKqVS35VpL9ulMPfSl0J0Xsm+9Evphv9CoIZFwre7aJoa94AY6seMKGVN5Q==", + "dev": true, + "dependencies": { + "unicode-canonical-property-names-ecmascript": "^2.0.0", + "unicode-property-aliases-ecmascript": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-match-property-value-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-2.0.0.tgz", + "integrity": "sha512-7Yhkc0Ye+t4PNYzOGKedDhXbYIBe1XEQYQxOPyhcXNMJ0WCABqqj6ckydd6pWRZTHV4GuCPKdBAUiMc60tsKVw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-property-aliases-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-2.0.0.tgz", + "integrity": "sha512-5Zfuy9q/DFr4tfO7ZPeVXb1aPoeQSdeFMLpYuFebehDAhbuevLs5yxSZmIFN1tP5F9Wl4IpJrYojg85/zgyZHQ==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/unique-filename": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", + "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", + "dev": true, + "dependencies": { + "unique-slug": "^2.0.0" + } + }, + "node_modules/unique-slug": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.2.tgz", + "integrity": "sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==", + "dev": true, + "dependencies": { + "imurmurhash": "^0.1.4" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "dev": true, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/validate-npm-package-name": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-3.0.0.tgz", + "integrity": "sha1-X6kS2B630MdK/BQN5zF/DKffQ34=", + "dev": true, + "dependencies": { + "builtins": "^1.0.3" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/void-elements": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz", + "integrity": "sha1-wGavtYK7HLQSjWDqkjkulNXp2+w=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.3.1.tgz", + "integrity": "sha512-x0t0JuydIo8qCNctdDrn1OzH/qDzk2+rdCOC3YzumZ42fiMqmQ7T3xQurykYMhYfHaPHTp4ZxAx2NfUo1K6QaA==", + "dev": true, + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/wbuf": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/wbuf/-/wbuf-1.7.3.tgz", + "integrity": "sha512-O84QOnr0icsbFGLS0O3bI5FswxzRr8/gHwWkDlQFskhSPryQXvrTMxjxGP4+iWYoauLoBvfDpkrOauZ+0iZpDA==", + "dev": true, + "dependencies": { + "minimalistic-assert": "^1.0.0" + } + }, + "node_modules/wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g=", + "dev": true, + "dependencies": { + "defaults": "^1.0.3" + } + }, + "node_modules/webpack": { + "version": "5.70.0", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.70.0.tgz", + "integrity": "sha512-ZMWWy8CeuTTjCxbeaQI21xSswseF2oNOwc70QSKNePvmxE7XW36i7vpBMYZFAUHPwQiEbNGCEYIOOlyRbdGmxw==", + "dev": true, + "dependencies": { + "@types/eslint-scope": "^3.7.3", + "@types/estree": "^0.0.51", + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/wasm-edit": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1", + "acorn": "^8.4.1", + "acorn-import-assertions": "^1.7.6", + "browserslist": "^4.14.5", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.9.2", + "es-module-lexer": "^0.9.0", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.9", + "json-parse-better-errors": "^1.0.2", + "loader-runner": "^4.2.0", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^3.1.0", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.1.3", + "watchpack": "^2.3.1", + "webpack-sources": "^3.2.3" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-dev-middleware": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-5.3.0.tgz", + "integrity": "sha512-MouJz+rXAm9B1OTOYaJnn6rtD/lWZPy2ufQCH3BPs8Rloh/Du6Jze4p7AeLYHkVi0giJnYLaSGDC7S+GM9arhg==", + "dev": true, + "dependencies": { + "colorette": "^2.0.10", + "memfs": "^3.2.2", + "mime-types": "^2.1.31", + "range-parser": "^1.2.1", + "schema-utils": "^4.0.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^4.0.0 || ^5.0.0" + } + }, + "node_modules/webpack-dev-middleware/node_modules/ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/webpack-dev-middleware/node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/webpack-dev-middleware/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/webpack-dev-middleware/node_modules/schema-utils": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.0.0.tgz", + "integrity": "sha512-1edyXKgh6XnJsJSQ8mKWXnN/BVaIbFMLpouRUrXgVq7WYne5kw3MW7UPhO44uRXQSIpTSXoJbmrR2X0w9kUTyg==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.8.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.0.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/webpack-dev-server": { + "version": "4.7.3", + "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-4.7.3.tgz", + "integrity": "sha512-mlxq2AsIw2ag016nixkzUkdyOE8ST2GTy34uKSABp1c4nhjZvH90D5ZRR+UOLSsG4Z3TFahAi72a3ymRtfRm+Q==", + "dev": true, + "dependencies": { + "@types/bonjour": "^3.5.9", + "@types/connect-history-api-fallback": "^1.3.5", + "@types/serve-index": "^1.9.1", + "@types/sockjs": "^0.3.33", + "@types/ws": "^8.2.2", + "ansi-html-community": "^0.0.8", + "bonjour": "^3.5.0", + "chokidar": "^3.5.2", + "colorette": "^2.0.10", + "compression": "^1.7.4", + "connect-history-api-fallback": "^1.6.0", + "default-gateway": "^6.0.3", + "del": "^6.0.0", + "express": "^4.17.1", + "graceful-fs": "^4.2.6", + "html-entities": "^2.3.2", + "http-proxy-middleware": "^2.0.0", + "ipaddr.js": "^2.0.1", + "open": "^8.0.9", + "p-retry": "^4.5.0", + "portfinder": "^1.0.28", + "schema-utils": "^4.0.0", + "selfsigned": "^2.0.0", + "serve-index": "^1.9.1", + "sockjs": "^0.3.21", + "spdy": "^4.0.2", + "strip-ansi": "^7.0.0", + "webpack-dev-middleware": "^5.3.0", + "ws": "^8.1.0" + }, + "bin": { + "webpack-dev-server": "bin/webpack-dev-server.js" + }, + "engines": { + "node": ">= 12.13.0" + }, + "peerDependencies": { + "webpack": "^4.37.0 || ^5.0.0" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-dev-server/node_modules/ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/webpack-dev-server/node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/webpack-dev-server/node_modules/ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/webpack-dev-server/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/webpack-dev-server/node_modules/schema-utils": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.0.0.tgz", + "integrity": "sha512-1edyXKgh6XnJsJSQ8mKWXnN/BVaIbFMLpouRUrXgVq7WYne5kw3MW7UPhO44uRXQSIpTSXoJbmrR2X0w9kUTyg==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.8.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.0.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/webpack-dev-server/node_modules/strip-ansi": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.0.1.tgz", + "integrity": "sha512-cXNxvT8dFNRVfhVME3JAe98mkXDYN2O1l7jmcwMnOslDeESg1rF/OZMtK0nRAhiari1unG5cD4jG3rapUAkLbw==", + "dev": true, + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/webpack-merge": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.8.0.tgz", + "integrity": "sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q==", + "dev": true, + "dependencies": { + "clone-deep": "^4.0.1", + "wildcard": "^2.0.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/webpack-sources": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz", + "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==", + "dev": true, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack-subresource-integrity": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/webpack-subresource-integrity/-/webpack-subresource-integrity-5.1.0.tgz", + "integrity": "sha512-sacXoX+xd8r4WKsy9MvH/q/vBtEHr86cpImXwyg74pFIpERKt6FmB8cXpeuh0ZLgclOlHI4Wcll7+R5L02xk9Q==", + "dev": true, + "dependencies": { + "typed-assert": "^1.0.8" + }, + "engines": { + "node": ">= 12" + }, + "peerDependencies": { + "html-webpack-plugin": ">= 5.0.0-beta.1 < 6", + "webpack": "^5.12.0" + }, + "peerDependenciesMeta": { + "html-webpack-plugin": { + "optional": true + } + } + }, + "node_modules/webpack/node_modules/schema-utils": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.1.1.tgz", + "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "dev": true, + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "dev": true, + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/wildcard": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.0.tgz", + "integrity": "sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw==", + "dev": true + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/wrap-ansi/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "node_modules/ws": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", + "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "dev": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, + "node_modules/yaml": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", + "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", + "dev": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dev": true, + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yn": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/yn/-/yn-2.0.0.tgz", + "integrity": "sha1-5a2ryKz0CPY4X8dklWhMiOavaJo=", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zone.js": { + "version": "0.11.5", + "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.11.5.tgz", + "integrity": "sha512-D1/7VxEuQ7xk6z/kAROe4SUbd9CzxY4zOwVGnGHerd/SgLIVU5f4esDzQUsOCeArn933BZfWMKydH7l7dPEp0g==", + "dependencies": { + "tslib": "^2.3.0" + } + } + }, + "dependencies": { + "@ampproject/remapping": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-1.1.1.tgz", + "integrity": "sha512-YVAcA4DKLOj296CF5SrQ8cYiMRiUGc2sqFpLxsDGWE34suHqhGP/5yMsDHKsrh8hs8I5TiRVXNwKPWQpX3iGjw==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "^3.0.3", + "sourcemap-codec": "1.4.8" + } + }, + "@angular-devkit/architect": { + "version": "0.1303.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/architect/-/architect-0.1303.3.tgz", + "integrity": "sha512-WRVVBCzLlMqRZVhZXGASHzNJK/OCAvl/DTGhlLuJDIjF7lVGnXHjtwNM8ilYZq949OnC3fly5Z61TfhbN/OHCg==", + "dev": true, + "requires": { + "@angular-devkit/core": "13.3.3", + "rxjs": "6.6.7" + } + }, + "@angular-devkit/build-angular": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/build-angular/-/build-angular-13.3.3.tgz", + "integrity": "sha512-iEpNF3tF+9Gw+qQKL63fPFHIvWokJdrgVU4GzENQ5QeL8zk8iYTEbH3jWogq5tWy5+VmNP/mKkasq9i78lRiYw==", + "dev": true, + "requires": { + "@ampproject/remapping": "1.1.1", + "@angular-devkit/architect": "0.1303.3", + "@angular-devkit/build-webpack": "0.1303.3", + "@angular-devkit/core": "13.3.3", + "@babel/core": "7.16.12", + "@babel/generator": "7.16.8", + "@babel/helper-annotate-as-pure": "7.16.7", + "@babel/plugin-proposal-async-generator-functions": "7.16.8", + "@babel/plugin-transform-async-to-generator": "7.16.8", + "@babel/plugin-transform-runtime": "7.16.10", + "@babel/preset-env": "7.16.11", + "@babel/runtime": "7.16.7", + "@babel/template": "7.16.7", + "@discoveryjs/json-ext": "0.5.6", + "@ngtools/webpack": "13.3.3", + "ansi-colors": "4.1.1", + "babel-loader": "8.2.3", + "babel-plugin-istanbul": "6.1.1", + "browserslist": "^4.9.1", + "cacache": "15.3.0", + "circular-dependency-plugin": "5.2.2", + "copy-webpack-plugin": "10.2.1", + "core-js": "3.20.3", + "critters": "0.0.16", + "css-loader": "6.5.1", + "esbuild": "0.14.22", + "esbuild-wasm": "0.14.22", + "glob": "7.2.0", + "https-proxy-agent": "5.0.0", + "inquirer": "8.2.0", + "jsonc-parser": "3.0.0", + "karma-source-map-support": "1.4.0", + "less": "4.1.2", + "less-loader": "10.2.0", + "license-webpack-plugin": "4.0.2", + "loader-utils": "3.2.0", + "mini-css-extract-plugin": "2.5.3", + "minimatch": "3.0.5", + "open": "8.4.0", + "ora": "5.4.1", + "parse5-html-rewriting-stream": "6.0.1", + "piscina": "3.2.0", + "postcss": "8.4.5", + "postcss-import": "14.0.2", + "postcss-loader": "6.2.1", + "postcss-preset-env": "7.2.3", + "regenerator-runtime": "0.13.9", + "resolve-url-loader": "5.0.0", + "rxjs": "6.6.7", + "sass": "1.49.9", + "sass-loader": "12.4.0", + "semver": "7.3.5", + "source-map-loader": "3.0.1", + "source-map-support": "0.5.21", + "stylus": "0.56.0", + "stylus-loader": "6.2.0", + "terser": "5.11.0", + "text-table": "0.2.0", + "tree-kill": "1.2.2", + "tslib": "2.3.1", + "webpack": "5.70.0", + "webpack-dev-middleware": "5.3.0", + "webpack-dev-server": "4.7.3", + "webpack-merge": "5.8.0", + "webpack-subresource-integrity": "5.1.0" + }, + "dependencies": { + "core-js": { + "version": "3.20.3", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.20.3.tgz", + "integrity": "sha512-vVl8j8ph6tRS3B8qir40H7yw7voy17xL0piAjlbBUsH7WIfzoedL/ZOr1OV9FyZQLWXsayOJyV4tnRyXR85/ag==", + "dev": true + }, + "semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dev": true, + "requires": { + "lru-cache": "^6.0.0" + } + } + } + }, + "@angular-devkit/build-webpack": { + "version": "0.1303.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/build-webpack/-/build-webpack-0.1303.3.tgz", + "integrity": "sha512-v/z/YgwrAzYn1LfN9OHNxqcThyyg4LLx28hmHzDs5gyDShAK189y34EoT9uQ+lCyQrPVhP7UKACCxCdSwOEJiA==", + "dev": true, + "requires": { + "@angular-devkit/architect": "0.1303.3", + "rxjs": "6.6.7" + } + }, + "@angular-devkit/core": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-13.3.3.tgz", + "integrity": "sha512-lfQwY9LuVRwcNVzGmyPcwOpb3CAobP4T+c3joR1LLIPS5lzcM0oeCE2bon9N52Ktn4Q/pH98dVtjWL+jSrUADw==", + "dev": true, + "requires": { + "ajv": "8.9.0", + "ajv-formats": "2.1.1", + "fast-json-stable-stringify": "2.1.0", + "magic-string": "0.25.7", + "rxjs": "6.6.7", + "source-map": "0.7.3" + }, + "dependencies": { + "ajv": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.9.0.tgz", + "integrity": "sha512-qOKJyNj/h+OWx7s5DePL6Zu1KeM9jPZhwBqs+7DzP6bGOvqzVCSf0xueYmVuaC/oQ/VtS2zLMLHdQFbkka+XDQ==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + } + }, + "json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + } + } + }, + "@angular-devkit/schematics": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-13.3.3.tgz", + "integrity": "sha512-S8UNlw6IoR/kxBYbiwesuA7oJGSnFkD6bJwVLhpHdT6Sqrz2/IrjHcNgTJRAvhsOKIbfDtMtXRzl/PUdWEfgyw==", + "dev": true, + "requires": { + "@angular-devkit/core": "13.3.3", + "jsonc-parser": "3.0.0", + "magic-string": "0.25.7", + "ora": "5.4.1", + "rxjs": "6.6.7" + } + }, + "@angular/animations": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/animations/-/animations-13.3.4.tgz", + "integrity": "sha512-cXjjbzYR2hda9BDAu0teJUVbbA03jJTK53vIYnDLIAvN20YRPo9LqINxpUlbAzH6hE8v5xF2LLnAXcaQROVpIw==", + "requires": { + "tslib": "^2.3.0" + } + }, + "@angular/cli": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@angular/cli/-/cli-13.3.3.tgz", + "integrity": "sha512-a+nnzFP1FfnypXpAhrHbIBaJcxzegWLZUvVzJQwt6P2z60IoHdvTVmyNbY89qI0LE1SrAokEUO1zW3Yjmu7fUw==", + "dev": true, + "requires": { + "@angular-devkit/architect": "0.1303.3", + "@angular-devkit/core": "13.3.3", + "@angular-devkit/schematics": "13.3.3", + "@schematics/angular": "13.3.3", + "@yarnpkg/lockfile": "1.1.0", + "ansi-colors": "4.1.1", + "debug": "4.3.3", + "ini": "2.0.0", + "inquirer": "8.2.0", + "jsonc-parser": "3.0.0", + "npm-package-arg": "8.1.5", + "npm-pick-manifest": "6.1.1", + "open": "8.4.0", + "ora": "5.4.1", + "pacote": "12.0.3", + "resolve": "1.22.0", + "semver": "7.3.5", + "symbol-observable": "4.0.0", + "uuid": "8.3.2" + }, + "dependencies": { + "semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dev": true, + "requires": { + "lru-cache": "^6.0.0" + } + } + } + }, + "@angular/common": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/common/-/common-13.3.4.tgz", + "integrity": "sha512-vPZuUGWMXz6r30obBqH+iIG4Feq4YEK/4wUks7PEYGke8MXFPYsNKuHMhKCgYEhabD/4Mo4GEp3i18/3Kk72Mw==", + "requires": { + "tslib": "^2.3.0" + } + }, + "@angular/compiler": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-13.3.4.tgz", + "integrity": "sha512-Yf1Dv2BVytjmv5Nnv05hUciUOH/UpKgXG1Ql5XwQG/qGV4eEs33PJBtGsUJTPuddxfRm72JMsbZcoRjVADqbcw==", + "requires": { + "tslib": "^2.3.0" + } + }, + "@angular/compiler-cli": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-13.3.4.tgz", + "integrity": "sha512-wCnt2YOS5EiwWCEv8oCqIfiwUtifs+COhcYH6fpmf/3X9w1yKO1ZMA+OsFQ0IVS4d0YYavm5DTPQ2ep2c0sF5w==", + "dev": true, + "requires": { + "@babel/core": "^7.17.2", + "chokidar": "^3.0.0", + "convert-source-map": "^1.5.1", + "dependency-graph": "^0.11.0", + "magic-string": "^0.26.0", + "reflect-metadata": "^0.1.2", + "semver": "^7.0.0", + "sourcemap-codec": "^1.4.8", + "tslib": "^2.3.0", + "yargs": "^17.2.1" + }, + "dependencies": { + "@ampproject/remapping": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.1.2.tgz", + "integrity": "sha512-hoyByceqwKirw7w3Z7gnIIZC3Wx3J484Y3L/cMpXFbr7d9ZQj2mODrirNzcJa+SM3UlpWXYvKV4RlRpFXlWgXg==", + "dev": true, + "requires": { + "@jridgewell/trace-mapping": "^0.3.0" + } + }, + "@babel/core": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.17.9.tgz", + "integrity": "sha512-5ug+SfZCpDAkVp9SFIZAzlW18rlzsOcJGaetCjkySnrXXDUw9AR8cDUm1iByTmdWM6yxX6/zycaV76w3YTF2gw==", + "dev": true, + "requires": { + "@ampproject/remapping": "^2.1.0", + "@babel/code-frame": "^7.16.7", + "@babel/generator": "^7.17.9", + "@babel/helper-compilation-targets": "^7.17.7", + "@babel/helper-module-transforms": "^7.17.7", + "@babel/helpers": "^7.17.9", + "@babel/parser": "^7.17.9", + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.17.9", + "@babel/types": "^7.17.0", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.1", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "@babel/generator": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.17.9.tgz", + "integrity": "sha512-rAdDousTwxbIxbz5I7GEQ3lUip+xVCXooZNbsydCWs3xA7ZsYOv+CFRdzGxRX78BmQHu9B1Eso59AOZQOJDEdQ==", + "dev": true, + "requires": { + "@babel/types": "^7.17.0", + "jsesc": "^2.5.1", + "source-map": "^0.5.0" + } + }, + "magic-string": { + "version": "0.26.1", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.26.1.tgz", + "integrity": "sha512-ndThHmvgtieXe8J/VGPjG+Apu7v7ItcD5mhEIvOscWjPF/ccOiLxHaSuCAS2G+3x4GKsAbT8u7zdyamupui8Tg==", + "dev": true, + "requires": { + "sourcemap-codec": "^1.4.8" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "yargs": { + "version": "17.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.4.1.tgz", + "integrity": "sha512-WSZD9jgobAg3ZKuCQZSa3g9QOJeCCqLoLAykiWgmXnDo9EPnn4RPf5qVTtzgOx66o6/oqhcA5tHtJXpG8pMt3g==", + "dev": true, + "requires": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.0.0" + } + }, + "yargs-parser": { + "version": "21.0.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.0.1.tgz", + "integrity": "sha512-9BK1jFpLzJROCI5TzwZL/TU4gqjK5xiHV/RfWLOahrjAko/e4DJkRDZQXfvqAsiZzzYhgAzbgz6lg48jcm4GLg==", + "dev": true + } + } + }, + "@angular/core": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/core/-/core-13.3.4.tgz", + "integrity": "sha512-PqPwx9oaV0Bh0m0fdI2jtXUC6s04jfD4vyzB4sjEuRI9pRUnZ6M5hZ5Vn/KJVZyt411MevbJfqzUVf0W+GDZew==", + "requires": { + "tslib": "^2.3.0" + } + }, + "@angular/forms": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/forms/-/forms-13.3.4.tgz", + "integrity": "sha512-QHyUXOKYITysaJJ4VnmBacE69oz0rw4G7Y2lhPb2V3a1XsWeO61SZEeGMfAWo7sLoDvi2MCEWNEhl1du4dK14A==", + "requires": { + "tslib": "^2.3.0" + } + }, + "@angular/language-service": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/language-service/-/language-service-13.3.4.tgz", + "integrity": "sha512-9k2q9TJaTG2QgIDNLUVOPCdzYRXLOw4aKiHTeMeIJOw4Zhp2dV7I4oX/aC/a1AN86JIO6m5nujeVf4SkK95WSw==", + "dev": true + }, + "@angular/platform-browser": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-13.3.4.tgz", + "integrity": "sha512-IjBOkjrIVIbbZCDQJRdel0FSDcExSLDgMxcCSQ6pKa6oR/t59BJpSpOhB1W9nRwLtvMmGYkS/oyLFsKk65UoYA==", + "requires": { + "tslib": "^2.3.0" + } + }, + "@angular/platform-browser-dynamic": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/platform-browser-dynamic/-/platform-browser-dynamic-13.3.4.tgz", + "integrity": "sha512-UApjgrL6B3QTdSYoCOPzMvFDmSewAHrLpreLYEmADutMWkD0ZcTPux4MJp8awT4P3l6wKzBeGJIKLlk8zsXmGQ==", + "requires": { + "tslib": "^2.3.0" + } + }, + "@angular/router": { + "version": "13.3.4", + "resolved": "https://registry.npmjs.org/@angular/router/-/router-13.3.4.tgz", + "integrity": "sha512-UuMAjWHoFKF8b9gFOiqL7fpVXjIr89BtxVES3yXReVq/IZJz9gWup6lYK3KMja+F8HZB8LBUMYgtqjS9iyLV/Q==", + "requires": { + "tslib": "^2.3.0" + } + }, + "@assemblyscript/loader": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@assemblyscript/loader/-/loader-0.10.1.tgz", + "integrity": "sha512-H71nDOOL8Y7kWRLqf6Sums+01Q5msqBW2KhDUTemh1tvY04eSkSXrK0uj/4mmY0Xr16/3zyZmsrxN7CKuRbNRg==", + "dev": true + }, + "@babel/code-frame": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.7.tgz", + "integrity": "sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg==", + "dev": true, + "requires": { + "@babel/highlight": "^7.16.7" + } + }, + "@babel/compat-data": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.17.7.tgz", + "integrity": "sha512-p8pdE6j0a29TNGebNm7NzYZWB3xVZJBZ7XGs42uAKzQo8VQ3F0By/cQCtUEABwIqw5zo6WA4NbmxsfzADzMKnQ==", + "dev": true + }, + "@babel/core": { + "version": "7.16.12", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.16.12.tgz", + "integrity": "sha512-dK5PtG1uiN2ikk++5OzSYsitZKny4wOCD0nrO4TqnW4BVBTQ2NGS3NgilvT/TEyxTST7LNyWV/T4tXDoD3fOgg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.16.7", + "@babel/generator": "^7.16.8", + "@babel/helper-compilation-targets": "^7.16.7", + "@babel/helper-module-transforms": "^7.16.7", + "@babel/helpers": "^7.16.7", + "@babel/parser": "^7.16.12", + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.16.10", + "@babel/types": "^7.16.8", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.1.2", + "semver": "^6.3.0", + "source-map": "^0.5.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "@babel/generator": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.16.8.tgz", + "integrity": "sha512-1ojZwE9+lOXzcWdWmO6TbUzDfqLD39CmEhN8+2cX9XkDo5yW1OpgfejfliysR2AWLpMamTiOiAp/mtroaymhpw==", + "dev": true, + "requires": { + "@babel/types": "^7.16.8", + "jsesc": "^2.5.1", + "source-map": "^0.5.0" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "@babel/helper-annotate-as-pure": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.16.7.tgz", + "integrity": "sha512-s6t2w/IPQVTAET1HitoowRGXooX8mCgtuP5195wD/QJPV6wYjpujCGF7JuMODVX2ZAJOf1GT6DT9MHEZvLOFSw==", + "dev": true, + "requires": { + "@babel/types": "^7.16.7" + } + }, + "@babel/helper-builder-binary-assignment-operator-visitor": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.16.7.tgz", + "integrity": "sha512-C6FdbRaxYjwVu/geKW4ZeQ0Q31AftgRcdSnZ5/jsH6BzCJbtvXvhpfkbkThYSuutZA7nCXpPR6AD9zd1dprMkA==", + "dev": true, + "requires": { + "@babel/helper-explode-assignable-expression": "^7.16.7", + "@babel/types": "^7.16.7" + } + }, + "@babel/helper-compilation-targets": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.17.7.tgz", + "integrity": "sha512-UFzlz2jjd8kroj0hmCFV5zr+tQPi1dpC2cRsDV/3IEW8bJfCPrPpmcSN6ZS8RqIq4LXcmpipCQFPddyFA5Yc7w==", + "dev": true, + "requires": { + "@babel/compat-data": "^7.17.7", + "@babel/helper-validator-option": "^7.16.7", + "browserslist": "^4.17.5", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "@babel/helper-create-class-features-plugin": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.17.9.tgz", + "integrity": "sha512-kUjip3gruz6AJKOq5i3nC6CoCEEF/oHH3cp6tOZhB+IyyyPyW0g1Gfsxn3mkk6S08pIA2y8GQh609v9G/5sHVQ==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-function-name": "^7.17.9", + "@babel/helper-member-expression-to-functions": "^7.17.7", + "@babel/helper-optimise-call-expression": "^7.16.7", + "@babel/helper-replace-supers": "^7.16.7", + "@babel/helper-split-export-declaration": "^7.16.7" + } + }, + "@babel/helper-create-regexp-features-plugin": { + "version": "7.17.0", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.17.0.tgz", + "integrity": "sha512-awO2So99wG6KnlE+TPs6rn83gCz5WlEePJDTnLEqbchMVrBeAujURVphRdigsk094VhvZehFoNOihSlcBjwsXA==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "regexpu-core": "^5.0.1" + } + }, + "@babel/helper-define-polyfill-provider": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.3.1.tgz", + "integrity": "sha512-J9hGMpJQmtWmj46B3kBHmL38UhJGhYX7eqkcq+2gsstyYt341HmPeWspihX43yVRA0mS+8GGk2Gckc7bY/HCmA==", + "dev": true, + "requires": { + "@babel/helper-compilation-targets": "^7.13.0", + "@babel/helper-module-imports": "^7.12.13", + "@babel/helper-plugin-utils": "^7.13.0", + "@babel/traverse": "^7.13.0", + "debug": "^4.1.1", + "lodash.debounce": "^4.0.8", + "resolve": "^1.14.2", + "semver": "^6.1.2" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "@babel/helper-environment-visitor": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.16.7.tgz", + "integrity": "sha512-SLLb0AAn6PkUeAfKJCCOl9e1R53pQlGAfc4y4XuMRZfqeMYLE0dM1LMhqbGAlGQY0lfw5/ohoYWAe9V1yibRag==", + "dev": true, + "requires": { + "@babel/types": "^7.16.7" + } + }, + "@babel/helper-explode-assignable-expression": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.16.7.tgz", + "integrity": "sha512-KyUenhWMC8VrxzkGP0Jizjo4/Zx+1nNZhgocs+gLzyZyB8SHidhoq9KK/8Ato4anhwsivfkBLftky7gvzbZMtQ==", + "dev": true, + "requires": { + "@babel/types": "^7.16.7" + } + }, + "@babel/helper-function-name": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.17.9.tgz", + "integrity": "sha512-7cRisGlVtiVqZ0MW0/yFB4atgpGLWEHUVYnb448hZK4x+vih0YO5UoS11XIYtZYqHd0dIPMdUSv8q5K4LdMnIg==", + "dev": true, + "requires": { + "@babel/template": "^7.16.7", + "@babel/types": "^7.17.0" + } + }, + "@babel/helper-hoist-variables": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.16.7.tgz", + "integrity": "sha512-m04d/0Op34H5v7pbZw6pSKP7weA6lsMvfiIAMeIvkY/R4xQtBSMFEigu9QTZ2qB/9l22vsxtM8a+Q8CzD255fg==", + "dev": true, + "requires": { + "@babel/types": "^7.16.7" + } + }, + "@babel/helper-member-expression-to-functions": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.17.7.tgz", + "integrity": "sha512-thxXgnQ8qQ11W2wVUObIqDL4p148VMxkt5T/qpN5k2fboRyzFGFmKsTGViquyM5QHKUy48OZoca8kw4ajaDPyw==", + "dev": true, + "requires": { + "@babel/types": "^7.17.0" + } + }, + "@babel/helper-module-imports": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.16.7.tgz", + "integrity": "sha512-LVtS6TqjJHFc+nYeITRo6VLXve70xmq7wPhWTqDJusJEgGmkAACWwMiTNrvfoQo6hEhFwAIixNkvB0jPXDL8Wg==", + "dev": true, + "requires": { + "@babel/types": "^7.16.7" + } + }, + "@babel/helper-module-transforms": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.17.7.tgz", + "integrity": "sha512-VmZD99F3gNTYB7fJRDTi+u6l/zxY0BE6OIxPSU7a50s6ZUQkHwSDmV92FfM+oCG0pZRVojGYhkR8I0OGeCVREw==", + "dev": true, + "requires": { + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-module-imports": "^7.16.7", + "@babel/helper-simple-access": "^7.17.7", + "@babel/helper-split-export-declaration": "^7.16.7", + "@babel/helper-validator-identifier": "^7.16.7", + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.17.3", + "@babel/types": "^7.17.0" + } + }, + "@babel/helper-optimise-call-expression": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.16.7.tgz", + "integrity": "sha512-EtgBhg7rd/JcnpZFXpBy0ze1YRfdm7BnBX4uKMBd3ixa3RGAE002JZB66FJyNH7g0F38U05pXmA5P8cBh7z+1w==", + "dev": true, + "requires": { + "@babel/types": "^7.16.7" + } + }, + "@babel/helper-plugin-utils": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.16.7.tgz", + "integrity": "sha512-Qg3Nk7ZxpgMrsox6HreY1ZNKdBq7K72tDSliA6dCl5f007jR4ne8iD5UzuNnCJH2xBf2BEEVGr+/OL6Gdp7RxA==", + "dev": true + }, + "@babel/helper-remap-async-to-generator": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.16.8.tgz", + "integrity": "sha512-fm0gH7Flb8H51LqJHy3HJ3wnE1+qtYR2A99K06ahwrawLdOFsCEWjZOrYricXJHoPSudNKxrMBUPEIPxiIIvBw==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "@babel/helper-wrap-function": "^7.16.8", + "@babel/types": "^7.16.8" + } + }, + "@babel/helper-replace-supers": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.16.7.tgz", + "integrity": "sha512-y9vsWilTNaVnVh6xiJfABzsNpgDPKev9HnAgz6Gb1p6UUwf9NepdlsV7VXGCftJM+jqD5f7JIEubcpLjZj5dBw==", + "dev": true, + "requires": { + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-member-expression-to-functions": "^7.16.7", + "@babel/helper-optimise-call-expression": "^7.16.7", + "@babel/traverse": "^7.16.7", + "@babel/types": "^7.16.7" + } + }, + "@babel/helper-simple-access": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.17.7.tgz", + "integrity": "sha512-txyMCGroZ96i+Pxr3Je3lzEJjqwaRC9buMUgtomcrLe5Nd0+fk1h0LLA+ixUF5OW7AhHuQ7Es1WcQJZmZsz2XA==", + "dev": true, + "requires": { + "@babel/types": "^7.17.0" + } + }, + "@babel/helper-skip-transparent-expression-wrappers": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.16.0.tgz", + "integrity": "sha512-+il1gTy0oHwUsBQZyJvukbB4vPMdcYBrFHa0Uc4AizLxbq6BOYC51Rv4tWocX9BLBDLZ4kc6qUFpQ6HRgL+3zw==", + "dev": true, + "requires": { + "@babel/types": "^7.16.0" + } + }, + "@babel/helper-split-export-declaration": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.16.7.tgz", + "integrity": "sha512-xbWoy/PFoxSWazIToT9Sif+jJTlrMcndIsaOKvTA6u7QEo7ilkRZpjew18/W3c7nm8fXdUDXh02VXTbZ0pGDNw==", + "dev": true, + "requires": { + "@babel/types": "^7.16.7" + } + }, + "@babel/helper-validator-identifier": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.16.7.tgz", + "integrity": "sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw==", + "dev": true + }, + "@babel/helper-validator-option": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.16.7.tgz", + "integrity": "sha512-TRtenOuRUVo9oIQGPC5G9DgK4743cdxvtOw0weQNpZXaS16SCBi5MNjZF8vba3ETURjZpTbVn7Vvcf2eAwFozQ==", + "dev": true + }, + "@babel/helper-wrap-function": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.16.8.tgz", + "integrity": "sha512-8RpyRVIAW1RcDDGTA+GpPAwV22wXCfKOoM9bet6TLkGIFTkRQSkH1nMQ5Yet4MpoXe1ZwHPVtNasc2w0uZMqnw==", + "dev": true, + "requires": { + "@babel/helper-function-name": "^7.16.7", + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.16.8", + "@babel/types": "^7.16.8" + } + }, + "@babel/helpers": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.17.9.tgz", + "integrity": "sha512-cPCt915ShDWUEzEp3+UNRktO2n6v49l5RSnG9M5pS24hA+2FAc5si+Pn1i4VVbQQ+jh+bIZhPFQOJOzbrOYY1Q==", + "dev": true, + "requires": { + "@babel/template": "^7.16.7", + "@babel/traverse": "^7.17.9", + "@babel/types": "^7.17.0" + } + }, + "@babel/highlight": { + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.10.tgz", + "integrity": "sha512-5FnTQLSLswEj6IkgVw5KusNUUFY9ZGqe/TRFnP/BKYHYgfh7tc+C7mwiy95/yNP7Dh9x580Vv8r7u7ZfTBFxdw==", + "dev": true, + "requires": { + "@babel/helper-validator-identifier": "^7.16.7", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + } + }, + "@babel/parser": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.17.9.tgz", + "integrity": "sha512-vqUSBLP8dQHFPdPi9bc5GK9vRkYHJ49fsZdtoJ8EQ8ibpwk5rPKfvNIwChB0KVXcIjcepEBBd2VHC5r9Gy8ueg==", + "dev": true + }, + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.16.7.tgz", + "integrity": "sha512-anv/DObl7waiGEnC24O9zqL0pSuI9hljihqiDuFHC8d7/bjr/4RLGPWuc8rYOff/QPzbEPSkzG8wGG9aDuhHRg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-7.16.7.tgz", + "integrity": "sha512-di8vUHRdf+4aJ7ltXhaDbPoszdkh59AQtJM5soLsuHpQJdFQZOA4uGj0V2u/CZ8bJ/u8ULDL5yq6FO/bCXnKHw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.16.0", + "@babel/plugin-proposal-optional-chaining": "^7.16.7" + } + }, + "@babel/plugin-proposal-async-generator-functions": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.16.8.tgz", + "integrity": "sha512-71YHIvMuiuqWJQkebWJtdhQTfd4Q4mF76q2IX37uZPkG9+olBxsX+rH1vkhFto4UeJZ9dPY2s+mDvhDm1u2BGQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-remap-async-to-generator": "^7.16.8", + "@babel/plugin-syntax-async-generators": "^7.8.4" + } + }, + "@babel/plugin-proposal-class-properties": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.16.7.tgz", + "integrity": "sha512-IobU0Xme31ewjYOShSIqd/ZGM/r/cuOz2z0MDbNrhF5FW+ZVgi0f2lyeoj9KFPDOAqsYxmLWZte1WOwlvY9aww==", + "dev": true, + "requires": { + "@babel/helper-create-class-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-proposal-class-static-block": { + "version": "7.17.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-class-static-block/-/plugin-proposal-class-static-block-7.17.6.tgz", + "integrity": "sha512-X/tididvL2zbs7jZCeeRJ8167U/+Ac135AM6jCAx6gYXDUviZV5Ku9UDvWS2NCuWlFjIRXklYhwo6HhAC7ETnA==", + "dev": true, + "requires": { + "@babel/helper-create-class-features-plugin": "^7.17.6", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-class-static-block": "^7.14.5" + } + }, + "@babel/plugin-proposal-dynamic-import": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-dynamic-import/-/plugin-proposal-dynamic-import-7.16.7.tgz", + "integrity": "sha512-I8SW9Ho3/8DRSdmDdH3gORdyUuYnk1m4cMxUAdu5oy4n3OfN8flDEH+d60iG7dUfi0KkYwSvoalHzzdRzpWHTg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-dynamic-import": "^7.8.3" + } + }, + "@babel/plugin-proposal-export-namespace-from": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-export-namespace-from/-/plugin-proposal-export-namespace-from-7.16.7.tgz", + "integrity": "sha512-ZxdtqDXLRGBL64ocZcs7ovt71L3jhC1RGSyR996svrCi3PYqHNkb3SwPJCs8RIzD86s+WPpt2S73+EHCGO+NUA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-export-namespace-from": "^7.8.3" + } + }, + "@babel/plugin-proposal-json-strings": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.16.7.tgz", + "integrity": "sha512-lNZ3EEggsGY78JavgbHsK9u5P3pQaW7k4axlgFLYkMd7UBsiNahCITShLjNQschPyjtO6dADrL24757IdhBrsQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-json-strings": "^7.8.3" + } + }, + "@babel/plugin-proposal-logical-assignment-operators": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-logical-assignment-operators/-/plugin-proposal-logical-assignment-operators-7.16.7.tgz", + "integrity": "sha512-K3XzyZJGQCr00+EtYtrDjmwX7o7PLK6U9bi1nCwkQioRFVUv6dJoxbQjtWVtP+bCPy82bONBKG8NPyQ4+i6yjg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4" + } + }, + "@babel/plugin-proposal-nullish-coalescing-operator": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.16.7.tgz", + "integrity": "sha512-aUOrYU3EVtjf62jQrCj63pYZ7k6vns2h/DQvHPWGmsJRYzWXZ6/AsfgpiRy6XiuIDADhJzP2Q9MwSMKauBQ+UQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3" + } + }, + "@babel/plugin-proposal-numeric-separator": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-numeric-separator/-/plugin-proposal-numeric-separator-7.16.7.tgz", + "integrity": "sha512-vQgPMknOIgiuVqbokToyXbkY/OmmjAzr/0lhSIbG/KmnzXPGwW/AdhdKpi+O4X/VkWiWjnkKOBiqJrTaC98VKw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-numeric-separator": "^7.10.4" + } + }, + "@babel/plugin-proposal-object-rest-spread": { + "version": "7.17.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.17.3.tgz", + "integrity": "sha512-yuL5iQA/TbZn+RGAfxQXfi7CNLmKi1f8zInn4IgobuCWcAb7i+zj4TYzQ9l8cEzVyJ89PDGuqxK1xZpUDISesw==", + "dev": true, + "requires": { + "@babel/compat-data": "^7.17.0", + "@babel/helper-compilation-targets": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-transform-parameters": "^7.16.7" + } + }, + "@babel/plugin-proposal-optional-catch-binding": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.16.7.tgz", + "integrity": "sha512-eMOH/L4OvWSZAE1VkHbr1vckLG1WUcHGJSLqqQwl2GaUqG6QjddvrOaTUMNYiv77H5IKPMZ9U9P7EaHwvAShfA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3" + } + }, + "@babel/plugin-proposal-optional-chaining": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.16.7.tgz", + "integrity": "sha512-eC3xy+ZrUcBtP7x+sq62Q/HYd674pPTb/77XZMb5wbDPGWIdUbSr4Agr052+zaUPSb+gGRnjxXfKFvx5iMJ+DA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.16.0", + "@babel/plugin-syntax-optional-chaining": "^7.8.3" + } + }, + "@babel/plugin-proposal-private-methods": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-methods/-/plugin-proposal-private-methods-7.16.11.tgz", + "integrity": "sha512-F/2uAkPlXDr8+BHpZvo19w3hLFKge+k75XUprE6jaqKxjGkSYcK+4c+bup5PdW/7W/Rpjwql7FTVEDW+fRAQsw==", + "dev": true, + "requires": { + "@babel/helper-create-class-features-plugin": "^7.16.10", + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-proposal-private-property-in-object": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.16.7.tgz", + "integrity": "sha512-rMQkjcOFbm+ufe3bTZLyOfsOUOxyvLXZJCTARhJr+8UMSoZmqTe1K1BgkFcrW37rAchWg57yI69ORxiWvUINuQ==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "@babel/helper-create-class-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5" + } + }, + "@babel/plugin-proposal-unicode-property-regex": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-unicode-property-regex/-/plugin-proposal-unicode-property-regex-7.16.7.tgz", + "integrity": "sha512-QRK0YI/40VLhNVGIjRNAAQkEHws0cswSdFFjpFyt943YmJIU1da9uW63Iu6NFV6CxTZW5eTDCrwZUstBWgp/Rg==", + "dev": true, + "requires": { + "@babel/helper-create-regexp-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.12.13" + } + }, + "@babel/plugin-syntax-class-static-block": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", + "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.14.5" + } + }, + "@babel/plugin-syntax-dynamic-import": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz", + "integrity": "sha512-5gdGbFon+PszYzqs83S3E5mpi7/y/8M9eC90MRTZfduQOYW76ig6SOSPNe41IG5LoP3FGBn2N0RjVDSQiS94kQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-export-namespace-from": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-export-namespace-from/-/plugin-syntax-export-namespace-from-7.8.3.tgz", + "integrity": "sha512-MXf5laXo6c1IbEbegDmzGPwGNTsHZmEy6QGznu5Sh2UCWvueywb2ee+CCE4zQiZstxU9BMoQO9i6zUFSY0Kj0Q==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.3" + } + }, + "@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" + } + }, + "@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.10.4" + } + }, + "@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.8.0" + } + }, + "@babel/plugin-syntax-private-property-in-object": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", + "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.14.5" + } + }, + "@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.14.5" + } + }, + "@babel/plugin-transform-arrow-functions": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.16.7.tgz", + "integrity": "sha512-9ffkFFMbvzTvv+7dTp/66xvZAWASuPD5Tl9LK3Z9vhOmANo6j94rik+5YMBt4CwHVMWLWpMsriIc2zsa3WW3xQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-async-to-generator": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.16.8.tgz", + "integrity": "sha512-MtmUmTJQHCnyJVrScNzNlofQJ3dLFuobYn3mwOTKHnSCMtbNsqvF71GQmJfFjdrXSsAA7iysFmYWw4bXZ20hOg==", + "dev": true, + "requires": { + "@babel/helper-module-imports": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-remap-async-to-generator": "^7.16.8" + } + }, + "@babel/plugin-transform-block-scoped-functions": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.16.7.tgz", + "integrity": "sha512-JUuzlzmF40Z9cXyytcbZEZKckgrQzChbQJw/5PuEHYeqzCsvebDx0K0jWnIIVcmmDOAVctCgnYs0pMcrYj2zJg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-block-scoping": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.16.7.tgz", + "integrity": "sha512-ObZev2nxVAYA4bhyusELdo9hb3H+A56bxH3FZMbEImZFiEDYVHXQSJ1hQKFlDnlt8G9bBrCZ5ZpURZUrV4G5qQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-classes": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.16.7.tgz", + "integrity": "sha512-WY7og38SFAGYRe64BrjKf8OrE6ulEHtr5jEYaZMwox9KebgqPi67Zqz8K53EKk1fFEJgm96r32rkKZ3qA2nCWQ==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.16.7", + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-function-name": "^7.16.7", + "@babel/helper-optimise-call-expression": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-replace-supers": "^7.16.7", + "@babel/helper-split-export-declaration": "^7.16.7", + "globals": "^11.1.0" + } + }, + "@babel/plugin-transform-computed-properties": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.16.7.tgz", + "integrity": "sha512-gN72G9bcmenVILj//sv1zLNaPyYcOzUho2lIJBMh/iakJ9ygCo/hEF9cpGb61SCMEDxbbyBoVQxrt+bWKu5KGw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-destructuring": { + "version": "7.17.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.17.7.tgz", + "integrity": "sha512-XVh0r5yq9sLR4vZ6eVZe8FKfIcSgaTBxVBRSYokRj2qksf6QerYnTxz9/GTuKTH/n/HwLP7t6gtlybHetJ/6hQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-dotall-regex": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.16.7.tgz", + "integrity": "sha512-Lyttaao2SjZF6Pf4vk1dVKv8YypMpomAbygW+mU5cYP3S5cWTfCJjG8xV6CFdzGFlfWK81IjL9viiTvpb6G7gQ==", + "dev": true, + "requires": { + "@babel/helper-create-regexp-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-duplicate-keys": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.16.7.tgz", + "integrity": "sha512-03DvpbRfvWIXyK0/6QiR1KMTWeT6OcQ7tbhjrXyFS02kjuX/mu5Bvnh5SDSWHxyawit2g5aWhKwI86EE7GUnTw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-exponentiation-operator": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.16.7.tgz", + "integrity": "sha512-8UYLSlyLgRixQvlYH3J2ekXFHDFLQutdy7FfFAMm3CPZ6q9wHCwnUyiXpQCe3gVVnQlHc5nsuiEVziteRNTXEA==", + "dev": true, + "requires": { + "@babel/helper-builder-binary-assignment-operator-visitor": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-for-of": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.16.7.tgz", + "integrity": "sha512-/QZm9W92Ptpw7sjI9Nx1mbcsWz33+l8kuMIQnDwgQBG5s3fAfQvkRjQ7NqXhtNcKOnPkdICmUHyCaWW06HCsqg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-function-name": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.16.7.tgz", + "integrity": "sha512-SU/C68YVwTRxqWj5kgsbKINakGag0KTgq9f2iZEXdStoAbOzLHEBRYzImmA6yFo8YZhJVflvXmIHUO7GWHmxxA==", + "dev": true, + "requires": { + "@babel/helper-compilation-targets": "^7.16.7", + "@babel/helper-function-name": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-literals": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.16.7.tgz", + "integrity": "sha512-6tH8RTpTWI0s2sV6uq3e/C9wPo4PTqqZps4uF0kzQ9/xPLFQtipynvmT1g/dOfEJ+0EQsHhkQ/zyRId8J2b8zQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-member-expression-literals": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.16.7.tgz", + "integrity": "sha512-mBruRMbktKQwbxaJof32LT9KLy2f3gH+27a5XSuXo6h7R3vqltl0PgZ80C8ZMKw98Bf8bqt6BEVi3svOh2PzMw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-modules-amd": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.16.7.tgz", + "integrity": "sha512-KaaEtgBL7FKYwjJ/teH63oAmE3lP34N3kshz8mm4VMAw7U3PxjVwwUmxEFksbgsNUaO3wId9R2AVQYSEGRa2+g==", + "dev": true, + "requires": { + "@babel/helper-module-transforms": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "babel-plugin-dynamic-import-node": "^2.3.3" + } + }, + "@babel/plugin-transform-modules-commonjs": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.17.9.tgz", + "integrity": "sha512-2TBFd/r2I6VlYn0YRTz2JdazS+FoUuQ2rIFHoAxtyP/0G3D82SBLaRq9rnUkpqlLg03Byfl/+M32mpxjO6KaPw==", + "dev": true, + "requires": { + "@babel/helper-module-transforms": "^7.17.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-simple-access": "^7.17.7", + "babel-plugin-dynamic-import-node": "^2.3.3" + } + }, + "@babel/plugin-transform-modules-systemjs": { + "version": "7.17.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.17.8.tgz", + "integrity": "sha512-39reIkMTUVagzgA5x88zDYXPCMT6lcaRKs1+S9K6NKBPErbgO/w/kP8GlNQTC87b412ZTlmNgr3k2JrWgHH+Bw==", + "dev": true, + "requires": { + "@babel/helper-hoist-variables": "^7.16.7", + "@babel/helper-module-transforms": "^7.17.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-validator-identifier": "^7.16.7", + "babel-plugin-dynamic-import-node": "^2.3.3" + } + }, + "@babel/plugin-transform-modules-umd": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.16.7.tgz", + "integrity": "sha512-EMh7uolsC8O4xhudF2F6wedbSHm1HHZ0C6aJ7K67zcDNidMzVcxWdGr+htW9n21klm+bOn+Rx4CBsAntZd3rEQ==", + "dev": true, + "requires": { + "@babel/helper-module-transforms": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-named-capturing-groups-regex": { + "version": "7.16.8", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.16.8.tgz", + "integrity": "sha512-j3Jw+n5PvpmhRR+mrgIh04puSANCk/T/UA3m3P1MjJkhlK906+ApHhDIqBQDdOgL/r1UYpz4GNclTXxyZrYGSw==", + "dev": true, + "requires": { + "@babel/helper-create-regexp-features-plugin": "^7.16.7" + } + }, + "@babel/plugin-transform-new-target": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.16.7.tgz", + "integrity": "sha512-xiLDzWNMfKoGOpc6t3U+etCE2yRnn3SM09BXqWPIZOBpL2gvVrBWUKnsJx0K/ADi5F5YC5f8APFfWrz25TdlGg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-object-super": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.16.7.tgz", + "integrity": "sha512-14J1feiQVWaGvRxj2WjyMuXS2jsBkgB3MdSN5HuC2G5nRspa5RK9COcs82Pwy5BuGcjb+fYaUj94mYcOj7rCvw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-replace-supers": "^7.16.7" + } + }, + "@babel/plugin-transform-parameters": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.16.7.tgz", + "integrity": "sha512-AT3MufQ7zZEhU2hwOA11axBnExW0Lszu4RL/tAlUJBuNoRak+wehQW8h6KcXOcgjY42fHtDxswuMhMjFEuv/aw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-property-literals": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.16.7.tgz", + "integrity": "sha512-z4FGr9NMGdoIl1RqavCqGG+ZuYjfZ/hkCIeuH6Do7tXmSm0ls11nYVSJqFEUOSJbDab5wC6lRE/w6YjVcr6Hqw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-regenerator": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.17.9.tgz", + "integrity": "sha512-Lc2TfbxR1HOyn/c6b4Y/b6NHoTb67n/IoWLxTu4kC7h4KQnWlhCq2S8Tx0t2SVvv5Uu87Hs+6JEJ5kt2tYGylQ==", + "dev": true, + "requires": { + "regenerator-transform": "^0.15.0" + } + }, + "@babel/plugin-transform-reserved-words": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.16.7.tgz", + "integrity": "sha512-KQzzDnZ9hWQBjwi5lpY5v9shmm6IVG0U9pB18zvMu2i4H90xpT4gmqwPYsn8rObiadYe2M0gmgsiOIF5A/2rtg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-runtime": { + "version": "7.16.10", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.16.10.tgz", + "integrity": "sha512-9nwTiqETv2G7xI4RvXHNfpGdr8pAA+Q/YtN3yLK7OoK7n9OibVm/xymJ838a9A6E/IciOLPj82lZk0fW6O4O7w==", + "dev": true, + "requires": { + "@babel/helper-module-imports": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "babel-plugin-polyfill-corejs2": "^0.3.0", + "babel-plugin-polyfill-corejs3": "^0.5.0", + "babel-plugin-polyfill-regenerator": "^0.3.0", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "@babel/plugin-transform-shorthand-properties": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.16.7.tgz", + "integrity": "sha512-hah2+FEnoRoATdIb05IOXf+4GzXYTq75TVhIn1PewihbpyrNWUt2JbudKQOETWw6QpLe+AIUpJ5MVLYTQbeeUg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-spread": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.16.7.tgz", + "integrity": "sha512-+pjJpgAngb53L0iaA5gU/1MLXJIfXcYepLgXB3esVRf4fqmj8f2cxM3/FKaHsZms08hFQJkFccEWuIpm429TXg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.16.0" + } + }, + "@babel/plugin-transform-sticky-regex": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.16.7.tgz", + "integrity": "sha512-NJa0Bd/87QV5NZZzTuZG5BPJjLYadeSZ9fO6oOUoL4iQx+9EEuw/eEM92SrsT19Yc2jgB1u1hsjqDtH02c3Drw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-template-literals": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.16.7.tgz", + "integrity": "sha512-VwbkDDUeenlIjmfNeDX/V0aWrQH2QiVyJtwymVQSzItFDTpxfyJh3EVaQiS0rIN/CqbLGr0VcGmuwyTdZtdIsA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-typeof-symbol": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.16.7.tgz", + "integrity": "sha512-p2rOixCKRJzpg9JB4gjnG4gjWkWa89ZoYUnl9snJ1cWIcTH/hvxZqfO+WjG6T8DRBpctEol5jw1O5rA8gkCokQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-unicode-escapes": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.16.7.tgz", + "integrity": "sha512-TAV5IGahIz3yZ9/Hfv35TV2xEm+kaBDaZQCn2S/hG9/CZ0DktxJv9eKfPc7yYCvOYR4JGx1h8C+jcSOvgaaI/Q==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/plugin-transform-unicode-regex": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.16.7.tgz", + "integrity": "sha512-oC5tYYKw56HO75KZVLQ+R/Nl3Hro9kf8iG0hXoaHP7tjAyCpvqBiSNe6vGrZni1Z6MggmUOC6A7VP7AVmw225Q==", + "dev": true, + "requires": { + "@babel/helper-create-regexp-features-plugin": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7" + } + }, + "@babel/preset-env": { + "version": "7.16.11", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.16.11.tgz", + "integrity": "sha512-qcmWG8R7ZW6WBRPZK//y+E3Cli151B20W1Rv7ln27vuPaXU/8TKms6jFdiJtF7UDTxcrb7mZd88tAeK9LjdT8g==", + "dev": true, + "requires": { + "@babel/compat-data": "^7.16.8", + "@babel/helper-compilation-targets": "^7.16.7", + "@babel/helper-plugin-utils": "^7.16.7", + "@babel/helper-validator-option": "^7.16.7", + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.16.7", + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.16.7", + "@babel/plugin-proposal-async-generator-functions": "^7.16.8", + "@babel/plugin-proposal-class-properties": "^7.16.7", + "@babel/plugin-proposal-class-static-block": "^7.16.7", + "@babel/plugin-proposal-dynamic-import": "^7.16.7", + "@babel/plugin-proposal-export-namespace-from": "^7.16.7", + "@babel/plugin-proposal-json-strings": "^7.16.7", + "@babel/plugin-proposal-logical-assignment-operators": "^7.16.7", + "@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.7", + "@babel/plugin-proposal-numeric-separator": "^7.16.7", + "@babel/plugin-proposal-object-rest-spread": "^7.16.7", + "@babel/plugin-proposal-optional-catch-binding": "^7.16.7", + "@babel/plugin-proposal-optional-chaining": "^7.16.7", + "@babel/plugin-proposal-private-methods": "^7.16.11", + "@babel/plugin-proposal-private-property-in-object": "^7.16.7", + "@babel/plugin-proposal-unicode-property-regex": "^7.16.7", + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-dynamic-import": "^7.8.3", + "@babel/plugin-syntax-export-namespace-from": "^7.8.3", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5", + "@babel/plugin-transform-arrow-functions": "^7.16.7", + "@babel/plugin-transform-async-to-generator": "^7.16.8", + "@babel/plugin-transform-block-scoped-functions": "^7.16.7", + "@babel/plugin-transform-block-scoping": "^7.16.7", + "@babel/plugin-transform-classes": "^7.16.7", + "@babel/plugin-transform-computed-properties": "^7.16.7", + "@babel/plugin-transform-destructuring": "^7.16.7", + "@babel/plugin-transform-dotall-regex": "^7.16.7", + "@babel/plugin-transform-duplicate-keys": "^7.16.7", + "@babel/plugin-transform-exponentiation-operator": "^7.16.7", + "@babel/plugin-transform-for-of": "^7.16.7", + "@babel/plugin-transform-function-name": "^7.16.7", + "@babel/plugin-transform-literals": "^7.16.7", + "@babel/plugin-transform-member-expression-literals": "^7.16.7", + "@babel/plugin-transform-modules-amd": "^7.16.7", + "@babel/plugin-transform-modules-commonjs": "^7.16.8", + "@babel/plugin-transform-modules-systemjs": "^7.16.7", + "@babel/plugin-transform-modules-umd": "^7.16.7", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.16.8", + "@babel/plugin-transform-new-target": "^7.16.7", + "@babel/plugin-transform-object-super": "^7.16.7", + "@babel/plugin-transform-parameters": "^7.16.7", + "@babel/plugin-transform-property-literals": "^7.16.7", + "@babel/plugin-transform-regenerator": "^7.16.7", + "@babel/plugin-transform-reserved-words": "^7.16.7", + "@babel/plugin-transform-shorthand-properties": "^7.16.7", + "@babel/plugin-transform-spread": "^7.16.7", + "@babel/plugin-transform-sticky-regex": "^7.16.7", + "@babel/plugin-transform-template-literals": "^7.16.7", + "@babel/plugin-transform-typeof-symbol": "^7.16.7", + "@babel/plugin-transform-unicode-escapes": "^7.16.7", + "@babel/plugin-transform-unicode-regex": "^7.16.7", + "@babel/preset-modules": "^0.1.5", + "@babel/types": "^7.16.8", + "babel-plugin-polyfill-corejs2": "^0.3.0", + "babel-plugin-polyfill-corejs3": "^0.5.0", + "babel-plugin-polyfill-regenerator": "^0.3.0", + "core-js-compat": "^3.20.2", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "@babel/preset-modules": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.5.tgz", + "integrity": "sha512-A57th6YRG7oR3cq/yt/Y84MvGgE0eJG2F1JLhKuyG+jFxEgrd/HAMJatiFtmOiZurz+0DkrvbheCLaV5f2JfjA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/plugin-proposal-unicode-property-regex": "^7.4.4", + "@babel/plugin-transform-dotall-regex": "^7.4.4", + "@babel/types": "^7.4.4", + "esutils": "^2.0.2" + } + }, + "@babel/runtime": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.16.7.tgz", + "integrity": "sha512-9E9FJowqAsytyOY6LG+1KuueckRL+aQW+mKvXRXnuFGyRAyepJPmEo9vgMfXUA6O9u3IeEdv9MAkppFcaQwogQ==", + "dev": true, + "requires": { + "regenerator-runtime": "^0.13.4" + } + }, + "@babel/template": { + "version": "7.16.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.16.7.tgz", + "integrity": "sha512-I8j/x8kHUrbYRTUxXrrMbfCa7jxkE7tZre39x3kjr9hvI82cK1FfqLygotcWN5kdPGWcLdWMHpSBavse5tWw3w==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.16.7", + "@babel/parser": "^7.16.7", + "@babel/types": "^7.16.7" + } + }, + "@babel/traverse": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.17.9.tgz", + "integrity": "sha512-PQO8sDIJ8SIwipTPiR71kJQCKQYB5NGImbOviK8K+kg5xkNSYXLBupuX9QhatFowrsvo9Hj8WgArg3W7ijNAQw==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.16.7", + "@babel/generator": "^7.17.9", + "@babel/helper-environment-visitor": "^7.16.7", + "@babel/helper-function-name": "^7.17.9", + "@babel/helper-hoist-variables": "^7.16.7", + "@babel/helper-split-export-declaration": "^7.16.7", + "@babel/parser": "^7.17.9", + "@babel/types": "^7.17.0", + "debug": "^4.1.0", + "globals": "^11.1.0" + }, + "dependencies": { + "@babel/generator": { + "version": "7.17.9", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.17.9.tgz", + "integrity": "sha512-rAdDousTwxbIxbz5I7GEQ3lUip+xVCXooZNbsydCWs3xA7ZsYOv+CFRdzGxRX78BmQHu9B1Eso59AOZQOJDEdQ==", + "dev": true, + "requires": { + "@babel/types": "^7.17.0", + "jsesc": "^2.5.1", + "source-map": "^0.5.0" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "@babel/types": { + "version": "7.17.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.17.0.tgz", + "integrity": "sha512-TmKSNO4D5rzhL5bjWFcVHHLETzfQ/AmbKpKPOSjlP0WoHZ6L911fgoOKY4Alp/emzG4cHJdyN49zpgkbXFEHHw==", + "dev": true, + "requires": { + "@babel/helper-validator-identifier": "^7.16.7", + "to-fast-properties": "^2.0.0" + } + }, + "@colors/colors": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", + "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", + "dev": true + }, + "@csstools/postcss-progressive-custom-properties": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@csstools/postcss-progressive-custom-properties/-/postcss-progressive-custom-properties-1.3.0.tgz", + "integrity": "sha512-ASA9W1aIy5ygskZYuWams4BzafD12ULvSypmaLJT2jvQ8G0M3I8PRQhC0h7mG0Z3LI05+agZjqSR9+K9yaQQjA==", + "dev": true, + "requires": { + "postcss-value-parser": "^4.2.0" + } + }, + "@discoveryjs/json-ext": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.5.6.tgz", + "integrity": "sha512-ws57AidsDvREKrZKYffXddNkyaF14iHNHm8VQnZH6t99E8gczjNN0GpvcGny0imC80yQ0tHz1xVUKk/KFQSUyA==", + "dev": true + }, + "@gar/promisify": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.3.tgz", + "integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==", + "dev": true + }, + "@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "requires": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + } + }, + "@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true + }, + "@jridgewell/resolve-uri": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.0.6.tgz", + "integrity": "sha512-R7xHtBSNm+9SyvpJkdQl+qrM3Hm2fea3Ef197M3mUug+v+yR+Rhfbs7PBtcBUVnIWJ4JcAdjvij+c8hXS9p5aw==", + "dev": true + }, + "@jridgewell/sourcemap-codec": { + "version": "1.4.11", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.11.tgz", + "integrity": "sha512-Fg32GrJo61m+VqYSdRSjRXMjQ06j8YIYfcTqndLYVAaHmroZHLJZCydsWBOTDqXS2v+mjxohBWEMfg97GXmYQg==", + "dev": true + }, + "@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "requires": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "@ngtools/webpack": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@ngtools/webpack/-/webpack-13.3.3.tgz", + "integrity": "sha512-O6EzafKfFuvI3Ju941u7ANs0mT7YDdChbVRhVECCPWOTm3Klr73js3bnCDzaJlxZNjzlG/KeUu5ghrhbMrHjSw==", + "dev": true, + "requires": {} + }, + "@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "requires": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + } + }, + "@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true + }, + "@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "requires": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + } + }, + "@npmcli/fs": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-1.1.1.tgz", + "integrity": "sha512-8KG5RD0GVP4ydEzRn/I4BNDuxDtqVbOdm8675T49OIG/NGhaK0pjPX7ZcDlvKYbA+ulvVK3ztfcF4uBdOxuJbQ==", + "dev": true, + "requires": { + "@gar/promisify": "^1.0.1", + "semver": "^7.3.5" + } + }, + "@npmcli/git": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-2.1.0.tgz", + "integrity": "sha512-/hBFX/QG1b+N7PZBFs0bi+evgRZcK9nWBxQKZkGoXUT5hJSwl5c4d7y8/hm+NQZRPhQ67RzFaj5UM9YeyKoryw==", + "dev": true, + "requires": { + "@npmcli/promise-spawn": "^1.3.2", + "lru-cache": "^6.0.0", + "mkdirp": "^1.0.4", + "npm-pick-manifest": "^6.1.1", + "promise-inflight": "^1.0.1", + "promise-retry": "^2.0.1", + "semver": "^7.3.5", + "which": "^2.0.2" + }, + "dependencies": { + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "@npmcli/installed-package-contents": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-1.0.7.tgz", + "integrity": "sha512-9rufe0wnJusCQoLpV9ZPKIVP55itrM5BxOXs10DmdbRfgWtHy1LDyskbwRnBghuB0PrF7pNPOqREVtpz4HqzKw==", + "dev": true, + "requires": { + "npm-bundled": "^1.1.1", + "npm-normalize-package-bin": "^1.0.1" + } + }, + "@npmcli/move-file": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@npmcli/move-file/-/move-file-1.1.2.tgz", + "integrity": "sha512-1SUf/Cg2GzGDyaf15aR9St9TWlb+XvbZXWpDx8YKs7MLzMH/BCeopv+y9vzrzgkfykCGuWOlSu3mZhj2+FQcrg==", + "dev": true, + "requires": { + "mkdirp": "^1.0.4", + "rimraf": "^3.0.2" + } + }, + "@npmcli/node-gyp": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@npmcli/node-gyp/-/node-gyp-1.0.3.tgz", + "integrity": "sha512-fnkhw+fmX65kiLqk6E3BFLXNC26rUhK90zVwe2yncPliVT/Qos3xjhTLE59Df8KnPlcwIERXKVlU1bXoUQ+liA==", + "dev": true + }, + "@npmcli/promise-spawn": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-1.3.2.tgz", + "integrity": "sha512-QyAGYo/Fbj4MXeGdJcFzZ+FkDkomfRBrPM+9QYJSg+PxgAUL+LU3FneQk37rKR2/zjqkCV1BLHccX98wRXG3Sg==", + "dev": true, + "requires": { + "infer-owner": "^1.0.4" + } + }, + "@npmcli/run-script": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-2.0.0.tgz", + "integrity": "sha512-fSan/Pu11xS/TdaTpTB0MRn9guwGU8dye+x56mEVgBEd/QsybBbYcAL0phPXi8SGWFEChkQd6M9qL4y6VOpFig==", + "dev": true, + "requires": { + "@npmcli/node-gyp": "^1.0.2", + "@npmcli/promise-spawn": "^1.3.2", + "node-gyp": "^8.2.0", + "read-package-json-fast": "^2.0.1" + } + }, + "@schematics/angular": { + "version": "13.3.3", + "resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-13.3.3.tgz", + "integrity": "sha512-kX5ghVCmWHcMN+g0pUaFuIJzwrXsVnK4bfid8DckU4EEtfFSv3UA5I1QNJRgpCPxTPhNEAk+3ePN8nzDSjdU+w==", + "dev": true, + "requires": { + "@angular-devkit/core": "13.3.3", + "@angular-devkit/schematics": "13.3.3", + "jsonc-parser": "3.0.0" + } + }, + "@socket.io/base64-arraybuffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@socket.io/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz", + "integrity": "sha512-dOlCBKnDw4iShaIsH/bxujKTM18+2TOAsYz+KSc11Am38H4q5Xw8Bbz97ZYdrVNM+um3p7w86Bvvmcn9q+5+eQ==", + "dev": true + }, + "@tootallnate/once": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", + "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==", + "dev": true + }, + "@types/body-parser": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.2.tgz", + "integrity": "sha512-ALYone6pm6QmwZoAgeyNksccT9Q4AWZQ6PvfwR37GT6r6FWUPguq6sUmNGSMV2Wr761oQoBxwGGa6DR5o1DC9g==", + "dev": true, + "requires": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "@types/bonjour": { + "version": "3.5.10", + "resolved": "https://registry.npmjs.org/@types/bonjour/-/bonjour-3.5.10.tgz", + "integrity": "sha512-p7ienRMiS41Nu2/igbJxxLDWrSZ0WxM8UQgCeO9KhoVF7cOVFkrKsiDr1EsJIla8vV3oEEjGcz11jc5yimhzZw==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/component-emitter": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/@types/component-emitter/-/component-emitter-1.2.11.tgz", + "integrity": "sha512-SRXjM+tfsSlA9VuG8hGO2nft2p8zjXCK1VcC6N4NXbBbYbSia9kzCChYQajIjzIqOOOuh5Ock6MmV2oux4jDZQ==", + "dev": true + }, + "@types/connect": { + "version": "3.4.35", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.35.tgz", + "integrity": "sha512-cdeYyv4KWoEgpBISTxWvqYsVy444DOqehiF3fM3ne10AmJ62RSyNkUnxMJXHQWRQQX2eR94m5y1IZyDwBjV9FQ==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/connect-history-api-fallback": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/connect-history-api-fallback/-/connect-history-api-fallback-1.3.5.tgz", + "integrity": "sha512-h8QJa8xSb1WD4fpKBDcATDNGXghFj6/3GRWG6dhmRcu0RX1Ubasur2Uvx5aeEwlf0MwblEC2bMzzMQntxnw/Cw==", + "dev": true, + "requires": { + "@types/express-serve-static-core": "*", + "@types/node": "*" + } + }, + "@types/cookie": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.1.tgz", + "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==", + "dev": true + }, + "@types/cors": { + "version": "2.8.12", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.12.tgz", + "integrity": "sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==", + "dev": true + }, + "@types/eslint": { + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.1.tgz", + "integrity": "sha512-GE44+DNEyxxh2Kc6ro/VkIj+9ma0pO0bwv9+uHSyBrikYOHr8zYcdPvnBOp1aw8s+CjRvuSx7CyWqRrNFQ59mA==", + "dev": true, + "requires": { + "@types/estree": "*", + "@types/json-schema": "*" + } + }, + "@types/eslint-scope": { + "version": "3.7.3", + "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.3.tgz", + "integrity": "sha512-PB3ldyrcnAicT35TWPs5IcwKD8S333HMaa2VVv4+wdvebJkjWuW/xESoB8IwRcog8HYVYamb1g/R31Qv5Bx03g==", + "dev": true, + "requires": { + "@types/eslint": "*", + "@types/estree": "*" + } + }, + "@types/estree": { + "version": "0.0.51", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.51.tgz", + "integrity": "sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ==", + "dev": true + }, + "@types/express": { + "version": "4.17.13", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.13.tgz", + "integrity": "sha512-6bSZTPaTIACxn48l50SR+axgrqm6qXFIxrdAKaG6PaJk3+zuUr35hBlgT7vOmJcum+OEaIBLtHV/qloEAFITeA==", + "dev": true, + "requires": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.18", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "@types/express-serve-static-core": { + "version": "4.17.28", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.17.28.tgz", + "integrity": "sha512-P1BJAEAW3E2DJUlkgq4tOL3RyMunoWXqbSCygWo5ZIWTjUgN1YnaXWW4VWl/oc8vs/XoYibEGBKP0uZyF4AHig==", + "dev": true, + "requires": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*" + } + }, + "@types/http-proxy": { + "version": "1.17.8", + "resolved": "https://registry.npmjs.org/@types/http-proxy/-/http-proxy-1.17.8.tgz", + "integrity": "sha512-5kPLG5BKpWYkw/LVOGWpiq3nEVqxiN32rTgI53Sk12/xHFQ2rG3ehI9IO+O3W2QoKeyB92dJkoka8SUm6BX1pA==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/jasmine": { + "version": "3.6.11", + "resolved": "https://registry.npmjs.org/@types/jasmine/-/jasmine-3.6.11.tgz", + "integrity": "sha512-S6pvzQDvMZHrkBz2Mcn/8Du7cpr76PlRJBAoHnSDNbulULsH5dp0Gns+WRyNX5LHejz/ljxK4/vIHK/caHt6SQ==", + "dev": true + }, + "@types/jasminewd2": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/@types/jasminewd2/-/jasminewd2-2.0.10.tgz", + "integrity": "sha512-J7mDz7ovjwjc+Y9rR9rY53hFWKATcIkrr9DwQWmOas4/pnIPJTXawnzjwpHm3RSxz/e3ZVUvQ7cRbd5UQLo10g==", + "dev": true, + "requires": { + "@types/jasmine": "*" + } + }, + "@types/json-schema": { + "version": "7.0.9", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz", + "integrity": "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==", + "dev": true + }, + "@types/mime": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.2.tgz", + "integrity": "sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw==", + "dev": true + }, + "@types/node": { + "version": "12.20.46", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.20.46.tgz", + "integrity": "sha512-cPjLXj8d6anFPzFvOPxS3fvly3Shm5nTfl6g8X5smexixbuGUf7hfr21J5tX9JW+UPStp/5P5R8qrKL5IyVJ+A==", + "dev": true + }, + "@types/parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==", + "dev": true + }, + "@types/qs": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.7.tgz", + "integrity": "sha512-FGa1F62FT09qcrueBA6qYTrJPVDzah9a+493+o2PCXsesWHIn27G98TsSMs3WPNbZIEj4+VJf6saSFpvD+3Zsw==", + "dev": true + }, + "@types/range-parser": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.4.tgz", + "integrity": "sha512-EEhsLsD6UsDM1yFhAvy0Cjr6VwmpMWqFBCb9w07wVugF7w9nfajxLuVmngTIpgS6svCnm6Vaw+MZhoDCKnOfsw==", + "dev": true + }, + "@types/retry": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.1.tgz", + "integrity": "sha512-xoDlM2S4ortawSWORYqsdU+2rxdh4LRW9ytc3zmT37RIKQh6IHyKwwtKhKis9ah8ol07DCkZxPt8BBvPjC6v4g==", + "dev": true + }, + "@types/serve-index": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@types/serve-index/-/serve-index-1.9.1.tgz", + "integrity": "sha512-d/Hs3nWDxNL2xAczmOVZNj92YZCS6RGxfBPjKzuu/XirCgXdpKEb88dYNbrYGint6IVWLNP+yonwVAuRC0T2Dg==", + "dev": true, + "requires": { + "@types/express": "*" + } + }, + "@types/serve-static": { + "version": "1.13.10", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.13.10.tgz", + "integrity": "sha512-nCkHGI4w7ZgAdNkrEu0bv+4xNV/XDqW+DydknebMOQwkpDGx8G+HTlj7R7ABI8i8nKxVw0wtKPi1D+lPOkh4YQ==", + "dev": true, + "requires": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "@types/sockjs": { + "version": "0.3.33", + "resolved": "https://registry.npmjs.org/@types/sockjs/-/sockjs-0.3.33.tgz", + "integrity": "sha512-f0KEEe05NvUnat+boPTZ0dgaLZ4SfSouXUgv5noUiefG2ajgKjmETo9ZJyuqsl7dfl2aHlLJUiki6B4ZYldiiw==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/ws": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.3.tgz", + "integrity": "sha512-6YOoWjruKj1uLf3INHH7D3qTXwFfEsg1kf3c0uDdSBJwfa/llkwIjrAGV7j7mVgGNbzTQ3HiHKKDXl6bJPD97w==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@webassemblyjs/ast": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.1.tgz", + "integrity": "sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw==", + "dev": true, + "requires": { + "@webassemblyjs/helper-numbers": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1" + } + }, + "@webassemblyjs/floating-point-hex-parser": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz", + "integrity": "sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ==", + "dev": true + }, + "@webassemblyjs/helper-api-error": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz", + "integrity": "sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg==", + "dev": true + }, + "@webassemblyjs/helper-buffer": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz", + "integrity": "sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA==", + "dev": true + }, + "@webassemblyjs/helper-numbers": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz", + "integrity": "sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ==", + "dev": true, + "requires": { + "@webassemblyjs/floating-point-hex-parser": "1.11.1", + "@webassemblyjs/helper-api-error": "1.11.1", + "@xtuc/long": "4.2.2" + } + }, + "@webassemblyjs/helper-wasm-bytecode": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz", + "integrity": "sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q==", + "dev": true + }, + "@webassemblyjs/helper-wasm-section": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz", + "integrity": "sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1" + } + }, + "@webassemblyjs/ieee754": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz", + "integrity": "sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ==", + "dev": true, + "requires": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "@webassemblyjs/leb128": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.1.tgz", + "integrity": "sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw==", + "dev": true, + "requires": { + "@xtuc/long": "4.2.2" + } + }, + "@webassemblyjs/utf8": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.1.tgz", + "integrity": "sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ==", + "dev": true + }, + "@webassemblyjs/wasm-edit": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz", + "integrity": "sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/helper-wasm-section": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1", + "@webassemblyjs/wasm-opt": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1", + "@webassemblyjs/wast-printer": "1.11.1" + } + }, + "@webassemblyjs/wasm-gen": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz", + "integrity": "sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/ieee754": "1.11.1", + "@webassemblyjs/leb128": "1.11.1", + "@webassemblyjs/utf8": "1.11.1" + } + }, + "@webassemblyjs/wasm-opt": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz", + "integrity": "sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-buffer": "1.11.1", + "@webassemblyjs/wasm-gen": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1" + } + }, + "@webassemblyjs/wasm-parser": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz", + "integrity": "sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/helper-api-error": "1.11.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.1", + "@webassemblyjs/ieee754": "1.11.1", + "@webassemblyjs/leb128": "1.11.1", + "@webassemblyjs/utf8": "1.11.1" + } + }, + "@webassemblyjs/wast-printer": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz", + "integrity": "sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.11.1", + "@xtuc/long": "4.2.2" + } + }, + "@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true + }, + "@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true + }, + "@yarnpkg/lockfile": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", + "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", + "dev": true + }, + "abab": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", + "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", + "dev": true + }, + "abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "dev": true + }, + "accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dev": true, + "requires": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + } + }, + "acorn": { + "version": "8.7.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.1.tgz", + "integrity": "sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A==", + "dev": true + }, + "acorn-import-assertions": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz", + "integrity": "sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw==", + "dev": true, + "requires": {} + }, + "adjust-sourcemap-loader": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/adjust-sourcemap-loader/-/adjust-sourcemap-loader-4.0.0.tgz", + "integrity": "sha512-OXwN5b9pCUXNQHJpwwD2qP40byEmSgzj8B4ydSN0uMNYWiFmJ6x6KwUllMmfk8Rwu/HJDFR7U8ubsWBoN0Xp0A==", + "dev": true, + "requires": { + "loader-utils": "^2.0.0", + "regex-parser": "^2.2.11" + }, + "dependencies": { + "loader-utils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.2.tgz", + "integrity": "sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A==", + "dev": true, + "requires": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^2.1.2" + } + } + } + }, + "agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, + "requires": { + "debug": "4" + } + }, + "agentkeepalive": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.2.1.tgz", + "integrity": "sha512-Zn4cw2NEqd+9fiSVWMscnjyQ1a8Yfoc5oBajLeo5w+YBHgDUcEBY2hS4YpTz6iN5f/2zQiktcuM6tS8x1p9dpA==", + "dev": true, + "requires": { + "debug": "^4.1.0", + "depd": "^1.1.2", + "humanize-ms": "^1.2.1" + } + }, + "aggregate-error": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "dev": true, + "requires": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + } + }, + "ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ajv-formats": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "dev": true, + "requires": { + "ajv": "^8.0.0" + }, + "dependencies": { + "ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + } + }, + "json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + } + } + }, + "ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "dev": true, + "requires": {} + }, + "ansi-colors": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", + "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", + "dev": true + }, + "ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "requires": { + "type-fest": "^0.21.3" + } + }, + "ansi-html-community": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/ansi-html-community/-/ansi-html-community-0.0.8.tgz", + "integrity": "sha512-1APHAyr3+PCamwNw3bXCPp4HFLONZt/yIH0sZp0/469KWNTEy+qN5jQ3GVX6DMZ1UXAi34yVwtTeaG/HpBuuzw==", + "dev": true + }, + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "anymatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", + "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", + "dev": true, + "requires": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + } + }, + "app-root-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/app-root-path/-/app-root-path-3.0.0.tgz", + "integrity": "sha512-qMcx+Gy2UZynHjOHOIXPNvpf+9cjvk3cWrBBK7zg4gH9+clobJRb9NGzcT7mQTcV/6Gm/1WelUtqxVXnNlrwcw==", + "dev": true + }, + "aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==", + "dev": true + }, + "are-we-there-yet": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-3.0.0.tgz", + "integrity": "sha512-0GWpv50YSOcLXaN6/FAKY3vfRbllXWV2xvfA/oKJF8pzFhWXPV+yjhJXDBbjscDYowv7Yw1A3uigpzn5iEGTyw==", + "dev": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + } + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + }, + "dependencies": { + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + } + } + }, + "aria-query": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-3.0.0.tgz", + "integrity": "sha1-ZbP8wcoRVajJrmTW7uKX8V1RM8w=", + "dev": true, + "requires": { + "ast-types-flow": "0.0.7", + "commander": "^2.11.0" + } + }, + "array-flatten": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-2.1.2.tgz", + "integrity": "sha512-hNfzcOV8W4NdualtqBFPyVO+54DSJuZGY9qT4pRroB6S9e3iiido2ISIC5h9R2sPJ8H3FHCIiEnsv1lPXO3KtQ==", + "dev": true + }, + "array-union": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-3.0.1.tgz", + "integrity": "sha512-1OvF9IbWwaeiM9VhzYXVQacMibxpXOMYVNIvMtKRyX9SImBXpKcFr8XvFDeEslCyuH/t6KRt7HEO94AlP8Iatw==", + "dev": true + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true + }, + "ast-types-flow": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.7.tgz", + "integrity": "sha1-9wtzXGvKGlycItmCw+Oef+ujva0=", + "dev": true + }, + "async": { + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", + "integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==", + "dev": true, + "requires": { + "lodash": "^4.17.14" + } + }, + "atob": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", + "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", + "dev": true + }, + "autoprefixer": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.5.tgz", + "integrity": "sha512-Fvd8yCoA7lNX/OUllvS+aS1I7WRBclGXsepbvT8ZaPgrH24rgXpZzF0/6Hh3ZEkwg+0AES/Osd196VZmYoEFtw==", + "dev": true, + "requires": { + "browserslist": "^4.20.2", + "caniuse-lite": "^1.0.30001332", + "fraction.js": "^4.2.0", + "normalize-range": "^0.1.2", + "picocolors": "^1.0.0", + "postcss-value-parser": "^4.2.0" + } + }, + "axobject-query": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-2.0.2.tgz", + "integrity": "sha512-MCeek8ZH7hKyO1rWUbKNQBbl4l2eY0ntk7OGi+q0RlafrCnfPxC06WZA+uebCfmYp4mNU9jRBP1AhGyf8+W3ww==", + "dev": true, + "requires": { + "ast-types-flow": "0.0.7" + } + }, + "babel-loader": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.2.3.tgz", + "integrity": "sha512-n4Zeta8NC3QAsuyiizu0GkmRcQ6clkV9WFUnUf1iXP//IeSKbWjofW3UHyZVwlOB4y039YQKefawyTn64Zwbuw==", + "dev": true, + "requires": { + "find-cache-dir": "^3.3.1", + "loader-utils": "^1.4.0", + "make-dir": "^3.1.0", + "schema-utils": "^2.6.5" + }, + "dependencies": { + "json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + }, + "loader-utils": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz", + "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==", + "dev": true, + "requires": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^1.0.1" + } + } + } + }, + "babel-plugin-dynamic-import-node": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.3.tgz", + "integrity": "sha512-jZVI+s9Zg3IqA/kdi0i6UDCybUI3aSBLnglhYbSSjKlV7yF1F/5LWv8MakQmvYpnbJDS6fcBL2KzHSxNCMtWSQ==", + "dev": true, + "requires": { + "object.assign": "^4.1.0" + } + }, + "babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + } + }, + "babel-plugin-polyfill-corejs2": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.3.1.tgz", + "integrity": "sha512-v7/T6EQcNfVLfcN2X8Lulb7DjprieyLWJK/zOWH5DUYcAgex9sP3h25Q+DLsX9TloXe3y1O8l2q2Jv9q8UVB9w==", + "dev": true, + "requires": { + "@babel/compat-data": "^7.13.11", + "@babel/helper-define-polyfill-provider": "^0.3.1", + "semver": "^6.1.1" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "babel-plugin-polyfill-corejs3": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.5.2.tgz", + "integrity": "sha512-G3uJih0XWiID451fpeFaYGVuxHEjzKTHtc9uGFEjR6hHrvNzeS/PX+LLLcetJcytsB5m4j+K3o/EpXJNb/5IEQ==", + "dev": true, + "requires": { + "@babel/helper-define-polyfill-provider": "^0.3.1", + "core-js-compat": "^3.21.0" + } + }, + "babel-plugin-polyfill-regenerator": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.3.1.tgz", + "integrity": "sha512-Y2B06tvgHYt1x0yz17jGkGeeMr5FeKUu+ASJ+N6nB5lQ8Dapfg42i0OVrf8PNGJ3zKL4A23snMi1IRwrqqND7A==", + "dev": true, + "requires": { + "@babel/helper-define-polyfill-provider": "^0.3.1" + } + }, + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true + }, + "base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", + "dev": true + }, + "batch": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz", + "integrity": "sha1-3DQxT05nkxgJP8dgJyUl+UvyXBY=", + "dev": true + }, + "big.js": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", + "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", + "dev": true + }, + "binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "dev": true + }, + "bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, + "requires": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "body-parser": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.0.tgz", + "integrity": "sha512-DfJ+q6EPcGKZD1QWUjSpqp+Q7bDQTsQIF4zfUAtZ6qk+H/3/QRhg9CEp39ss+/T2vw0+HaidC0ecJj/DRLIaKg==", + "dev": true, + "requires": { + "bytes": "3.1.2", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.10.3", + "raw-body": "2.5.1", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } + } + } + }, + "bonjour": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/bonjour/-/bonjour-3.5.0.tgz", + "integrity": "sha1-jokKGD2O6aI5OzhExpGkK897yfU=", + "dev": true, + "requires": { + "array-flatten": "^2.1.0", + "deep-equal": "^1.0.1", + "dns-equal": "^1.0.0", + "dns-txt": "^2.0.2", + "multicast-dns": "^6.0.1", + "multicast-dns-service-types": "^1.1.0" + } + }, + "boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "requires": { + "fill-range": "^7.0.1" + } + }, + "browserslist": { + "version": "4.20.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.20.3.tgz", + "integrity": "sha512-NBhymBQl1zM0Y5dQT/O+xiLP9/rzOIQdKM/eMJBAq7yBgaB6krIYLGejrwVYnSHZdqjscB1SPuAjHwxjvN6Wdg==", + "dev": true, + "requires": { + "caniuse-lite": "^1.0.30001332", + "electron-to-chromium": "^1.4.118", + "escalade": "^3.1.1", + "node-releases": "^2.0.3", + "picocolors": "^1.0.0" + } + }, + "buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "requires": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "buffer-indexof": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-indexof/-/buffer-indexof-1.1.1.tgz", + "integrity": "sha512-4/rOEg86jivtPTeOUUT61jJO1Ya1TrR/OkqCSZDyq84WJh3LuuiphBYJN+fm5xufIk4XAFcEwte/8WzC8If/1g==", + "dev": true + }, + "builtin-modules": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", + "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", + "dev": true + }, + "builtins": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/builtins/-/builtins-1.0.3.tgz", + "integrity": "sha1-y5T662HIaWRR2zZTThQi+U8K7og=", + "dev": true + }, + "bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "dev": true + }, + "cacache": { + "version": "15.3.0", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-15.3.0.tgz", + "integrity": "sha512-VVdYzXEn+cnbXpFgWs5hTT7OScegHVmLhJIR8Ufqk3iFD6A6j5iSX1KuBTfNEv4tdJWE2PzA6IVFtcLC7fN9wQ==", + "dev": true, + "requires": { + "@npmcli/fs": "^1.0.0", + "@npmcli/move-file": "^1.0.1", + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "glob": "^7.1.4", + "infer-owner": "^1.0.4", + "lru-cache": "^6.0.0", + "minipass": "^3.1.1", + "minipass-collect": "^1.0.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.2", + "mkdirp": "^1.0.3", + "p-map": "^4.0.0", + "promise-inflight": "^1.0.1", + "rimraf": "^3.0.2", + "ssri": "^8.0.1", + "tar": "^6.0.2", + "unique-filename": "^1.1.1" + } + }, + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true + }, + "camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true + }, + "caniuse-lite": { + "version": "1.0.30001332", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001332.tgz", + "integrity": "sha512-10T30NYOEQtN6C11YGg411yebhvpnC6Z102+B95eAsN0oB6KUs01ivE8u+G6FMIRtIrVlYXhL+LUwQ3/hXwDWw==", + "dev": true + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, + "chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "dev": true, + "requires": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "fsevents": "~2.3.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + } + }, + "chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "dev": true + }, + "chrome-trace-event": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz", + "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", + "dev": true + }, + "circular-dependency-plugin": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/circular-dependency-plugin/-/circular-dependency-plugin-5.2.2.tgz", + "integrity": "sha512-g38K9Cm5WRwlaH6g03B9OEz/0qRizI+2I7n+Gz+L5DxXJAPAiWQvwlYNm1V1jkdpUv95bOe/ASm2vfi/G560jQ==", + "dev": true, + "requires": {} + }, + "clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "dev": true + }, + "cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "requires": { + "restore-cursor": "^3.1.0" + } + }, + "cli-spinners": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.6.1.tgz", + "integrity": "sha512-x/5fWmGMnbKQAaNwN+UZlV79qBLM9JFnJuJ03gIi5whrob0xV0ofNVHy9DhwGdsMJQc2OKv0oGmLzvaqvAVv+g==", + "dev": true + }, + "cli-width": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", + "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "dev": true + }, + "cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dev": true, + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", + "dev": true + }, + "clone-deep": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz", + "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.2", + "shallow-clone": "^3.0.0" + } + }, + "codelyzer": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/codelyzer/-/codelyzer-6.0.2.tgz", + "integrity": "sha512-v3+E0Ucu2xWJMOJ2fA/q9pDT/hlxHftHGPUay1/1cTgyPV5JTHFdO9hqo837Sx2s9vKBMTt5gO+lhF95PO6J+g==", + "dev": true, + "requires": { + "@angular/compiler": "9.0.0", + "@angular/core": "9.0.0", + "app-root-path": "^3.0.0", + "aria-query": "^3.0.0", + "axobject-query": "2.0.2", + "css-selector-tokenizer": "^0.7.1", + "cssauron": "^1.4.0", + "damerau-levenshtein": "^1.0.4", + "rxjs": "^6.5.3", + "semver-dsl": "^1.0.1", + "source-map": "^0.5.7", + "sprintf-js": "^1.1.2", + "tslib": "^1.10.0", + "zone.js": "~0.10.3" + }, + "dependencies": { + "@angular/compiler": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-9.0.0.tgz", + "integrity": "sha512-ctjwuntPfZZT2mNj2NDIVu51t9cvbhl/16epc5xEwyzyDt76pX9UgwvY+MbXrf/C/FWwdtmNtfP698BKI+9leQ==", + "dev": true, + "requires": {} + }, + "@angular/core": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@angular/core/-/core-9.0.0.tgz", + "integrity": "sha512-6Pxgsrf0qF9iFFqmIcWmjJGkkCaCm6V5QNnxMy2KloO3SDq6QuMVRbN9RtC8Urmo25LP+eZ6ZgYqFYpdD8Hd9w==", + "dev": true, + "requires": {} + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, + "zone.js": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.10.3.tgz", + "integrity": "sha512-LXVLVEq0NNOqK/fLJo3d0kfzd4sxwn2/h67/02pjCjfKDxgx1i9QqpvtHD8CrBnSSwMw5+dy11O7FRX5mkO7Cg==", + "dev": true + } + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "dev": true + }, + "colorette": { + "version": "2.0.16", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.16.tgz", + "integrity": "sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==", + "dev": true + }, + "colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "dev": true + }, + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, + "component-emitter": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", + "dev": true + }, + "compressible": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", + "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", + "dev": true, + "requires": { + "mime-db": ">= 1.43.0 < 2" + } + }, + "compression": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.4.tgz", + "integrity": "sha512-jaSIDzP9pZVS4ZfQ+TzvtiWhdpFhE2RDHz8QJkpX9SIpLq88VueF5jJw6t+6CUQcAoA6t+x89MLrWAqpfDE8iQ==", + "dev": true, + "requires": { + "accepts": "~1.3.5", + "bytes": "3.0.0", + "compressible": "~2.0.16", + "debug": "2.6.9", + "on-headers": "~1.0.2", + "safe-buffer": "5.1.2", + "vary": "~1.1.2" + }, + "dependencies": { + "bytes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", + "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "connect": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/connect/-/connect-3.7.0.tgz", + "integrity": "sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==", + "dev": true, + "requires": { + "debug": "2.6.9", + "finalhandler": "1.1.2", + "parseurl": "~1.3.3", + "utils-merge": "1.0.1" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } + } + }, + "connect-history-api-fallback": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/connect-history-api-fallback/-/connect-history-api-fallback-1.6.0.tgz", + "integrity": "sha512-e54B99q/OUoH64zYYRf3HBP5z24G38h5D3qXu23JGRoigpX5Ss4r9ZnDk3g0Z8uQC2x2lPaJ+UlWBc1ZWBWdLg==", + "dev": true + }, + "console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", + "dev": true + }, + "content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dev": true, + "requires": { + "safe-buffer": "5.2.1" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true + } + } + }, + "content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "dev": true + }, + "convert-source-map": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.8.0.tgz", + "integrity": "sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.1" + } + }, + "cookie": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", + "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==", + "dev": true + }, + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=", + "dev": true + }, + "copy-anything": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-2.0.6.tgz", + "integrity": "sha512-1j20GZTsvKNkc4BY3NpMOM8tt///wY3FpIzozTOFO2ffuZcV61nojHXVKIy3WM+7ADCy5FVhdZYHYDdgTU0yJw==", + "dev": true, + "requires": { + "is-what": "^3.14.1" + } + }, + "copy-webpack-plugin": { + "version": "10.2.1", + "resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-10.2.1.tgz", + "integrity": "sha512-nr81NhCAIpAWXGCK5thrKmfCQ6GDY0L5RN0U+BnIn/7Us55+UCex5ANNsNKmIVtDRnk0Ecf+/kzp9SUVrrBMLg==", + "dev": true, + "requires": { + "fast-glob": "^3.2.7", + "glob-parent": "^6.0.1", + "globby": "^12.0.2", + "normalize-path": "^3.0.0", + "schema-utils": "^4.0.0", + "serialize-javascript": "^6.0.0" + }, + "dependencies": { + "ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + } + }, + "ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.3" + } + }, + "glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "requires": { + "is-glob": "^4.0.3" + } + }, + "json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "schema-utils": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.0.0.tgz", + "integrity": "sha512-1edyXKgh6XnJsJSQ8mKWXnN/BVaIbFMLpouRUrXgVq7WYne5kw3MW7UPhO44uRXQSIpTSXoJbmrR2X0w9kUTyg==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.8.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.0.0" + } + } + } + }, + "core-js": { + "version": "2.6.12", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.12.tgz", + "integrity": "sha512-Kb2wC0fvsWfQrgk8HU5lW6U/Lcs8+9aaYcy4ZFc6DDlo4nZ7n70dEgE5rtR0oG6ufKDUnrwfWL1mXR5ljDatrQ==" + }, + "core-js-compat": { + "version": "3.22.2", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.22.2.tgz", + "integrity": "sha512-Fns9lU06ZJ07pdfmPMu7OnkIKGPKDzXKIiuGlSvHHapwqMUF2QnnsWwtueFZtSyZEilP0o6iUeHQwpn7LxtLUw==", + "dev": true, + "requires": { + "browserslist": "^4.20.2", + "semver": "7.0.0" + }, + "dependencies": { + "semver": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.0.0.tgz", + "integrity": "sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A==", + "dev": true + } + } + }, + "core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true + }, + "cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dev": true, + "requires": { + "object-assign": "^4", + "vary": "^1" + } + }, + "cosmiconfig": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.1.tgz", + "integrity": "sha512-a1YWNUV2HwGimB7dU2s1wUMurNKjpx60HxBB6xUM8Re+2s1g1IIfJvFR0/iCF+XHdE0GMTKTuLR32UQff4TEyQ==", + "dev": true, + "requires": { + "@types/parse-json": "^4.0.0", + "import-fresh": "^3.2.1", + "parse-json": "^5.0.0", + "path-type": "^4.0.0", + "yaml": "^1.10.0" + } + }, + "critters": { + "version": "0.0.16", + "resolved": "https://registry.npmjs.org/critters/-/critters-0.0.16.tgz", + "integrity": "sha512-JwjgmO6i3y6RWtLYmXwO5jMd+maZt8Tnfu7VVISmEWyQqfLpB8soBswf8/2bu6SBXxtKA68Al3c+qIG1ApT68A==", + "dev": true, + "requires": { + "chalk": "^4.1.0", + "css-select": "^4.2.0", + "parse5": "^6.0.1", + "parse5-htmlparser2-tree-adapter": "^6.0.1", + "postcss": "^8.3.7", + "pretty-bytes": "^5.3.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "dependencies": { + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "css": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/css/-/css-3.0.0.tgz", + "integrity": "sha512-DG9pFfwOrzc+hawpmqX/dHYHJG+Bsdb0klhyi1sDneOgGOXy9wQIC8hzyVp1e4NRYDBdxcylvywPkkXCHAzTyQ==", + "dev": true, + "requires": { + "inherits": "^2.0.4", + "source-map": "^0.6.1", + "source-map-resolve": "^0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "css-blank-pseudo": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/css-blank-pseudo/-/css-blank-pseudo-3.0.3.tgz", + "integrity": "sha512-VS90XWtsHGqoM0t4KpH053c4ehxZ2E6HtGI7x68YFV0pTo/QmkV/YFA+NnlvK8guxZVNWGQhVNJGC39Q8XF4OQ==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.9" + } + }, + "css-has-pseudo": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/css-has-pseudo/-/css-has-pseudo-3.0.4.tgz", + "integrity": "sha512-Vse0xpR1K9MNlp2j5w1pgWIJtm1a8qS0JwS9goFYcImjlHEmywP9VUF05aGBXzGpDJF86QXk4L0ypBmwPhGArw==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.9" + } + }, + "css-loader": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-6.5.1.tgz", + "integrity": "sha512-gEy2w9AnJNnD9Kuo4XAP9VflW/ujKoS9c/syO+uWMlm5igc7LysKzPXaDoR2vroROkSwsTS2tGr1yGGEbZOYZQ==", + "dev": true, + "requires": { + "icss-utils": "^5.1.0", + "postcss": "^8.2.15", + "postcss-modules-extract-imports": "^3.0.0", + "postcss-modules-local-by-default": "^4.0.0", + "postcss-modules-scope": "^3.0.0", + "postcss-modules-values": "^4.0.0", + "postcss-value-parser": "^4.1.0", + "semver": "^7.3.5" + } + }, + "css-prefers-color-scheme": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/css-prefers-color-scheme/-/css-prefers-color-scheme-6.0.3.tgz", + "integrity": "sha512-4BqMbZksRkJQx2zAjrokiGMd07RqOa2IxIrrN10lyBe9xhn9DEvjUK79J6jkeiv9D9hQFXKb6g1jwU62jziJZA==", + "dev": true, + "requires": {} + }, + "css-select": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-4.3.0.tgz", + "integrity": "sha512-wPpOYtnsVontu2mODhA19JrqWxNsfdatRKd64kmpRbQgh1KtItko5sTnEpPdpSaJszTOhEMlF/RPz28qj4HqhQ==", + "dev": true, + "requires": { + "boolbase": "^1.0.0", + "css-what": "^6.0.1", + "domhandler": "^4.3.1", + "domutils": "^2.8.0", + "nth-check": "^2.0.1" + } + }, + "css-selector-tokenizer": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/css-selector-tokenizer/-/css-selector-tokenizer-0.7.3.tgz", + "integrity": "sha512-jWQv3oCEL5kMErj4wRnK/OPoBi0D+P1FR2cDCKYPaMeD2eW3/mttav8HT4hT1CKopiJI/psEULjkClhvJo4Lvg==", + "dev": true, + "requires": { + "cssesc": "^3.0.0", + "fastparse": "^1.1.2" + } + }, + "css-what": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", + "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==", + "dev": true + }, + "cssauron": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/cssauron/-/cssauron-1.4.0.tgz", + "integrity": "sha1-pmAt/34EqDBtwNuaVR6S6LVmKtg=", + "dev": true, + "requires": { + "through": "X.X.X" + } + }, + "cssdb": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cssdb/-/cssdb-5.1.0.tgz", + "integrity": "sha512-/vqjXhv1x9eGkE/zO6o8ZOI7dgdZbLVLUGyVRbPgk6YipXbW87YzUCcO+Jrmi5bwJlAH6oD+MNeZyRgXea1GZw==", + "dev": true + }, + "cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true + }, + "custom-event": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz", + "integrity": "sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU=", + "dev": true + }, + "damerau-levenshtein": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", + "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==", + "dev": true + }, + "date-format": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/date-format/-/date-format-4.0.3.tgz", + "integrity": "sha512-7P3FyqDcfeznLZp2b+OMitV9Sz2lUnsT87WaTat9nVwqsBkTzPG3lPLNwW3en6F4pHUiWzr6vb8CLhjdK9bcxQ==", + "dev": true + }, + "debug": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", + "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", + "dev": true, + "requires": { + "ms": "2.1.2" + } + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true + }, + "deep-equal": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.1.1.tgz", + "integrity": "sha512-yd9c5AdiqVcR+JjcwUQb9DkhJc8ngNr0MahEBGvDiJw8puWab2yZlh+nkasOnZP+EGTAP6rRp2JzJhJZzvNF8g==", + "dev": true, + "requires": { + "is-arguments": "^1.0.4", + "is-date-object": "^1.0.1", + "is-regex": "^1.0.4", + "object-is": "^1.0.1", + "object-keys": "^1.1.1", + "regexp.prototype.flags": "^1.2.0" + } + }, + "default-gateway": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/default-gateway/-/default-gateway-6.0.3.tgz", + "integrity": "sha512-fwSOJsbbNzZ/CUFpqFBqYfYNLj1NbMPm8MMCIzHjC83iSJRBEGmDUxU+WP661BaBQImeC2yHwXtz+P/O9o+XEg==", + "dev": true, + "requires": { + "execa": "^5.0.0" + } + }, + "defaults": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", + "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "dev": true, + "requires": { + "clone": "^1.0.2" + } + }, + "define-lazy-prop": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", + "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==", + "dev": true + }, + "define-properties": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.4.tgz", + "integrity": "sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA==", + "dev": true, + "requires": { + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + } + }, + "del": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/del/-/del-6.0.0.tgz", + "integrity": "sha512-1shh9DQ23L16oXSZKB2JxpL7iMy2E0S9d517ptA1P8iw0alkPtQcrKH7ru31rYtKwF499HkTu+DRzq3TCKDFRQ==", + "dev": true, + "requires": { + "globby": "^11.0.1", + "graceful-fs": "^4.2.4", + "is-glob": "^4.0.1", + "is-path-cwd": "^2.2.0", + "is-path-inside": "^3.0.2", + "p-map": "^4.0.0", + "rimraf": "^3.0.2", + "slash": "^3.0.0" + }, + "dependencies": { + "array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true + }, + "globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, + "requires": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + } + }, + "slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true + } + } + }, + "delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", + "dev": true + }, + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "dev": true + }, + "dependency-graph": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/dependency-graph/-/dependency-graph-0.11.0.tgz", + "integrity": "sha512-JeMq7fEshyepOWDfcfHK06N3MhyPhz++vtqWhMT5O9A3K42rdsEDpfdVqjaqaAhsw6a+ZqeDvQVtD0hFHQWrzg==", + "dev": true + }, + "destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "dev": true + }, + "detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==", + "dev": true + }, + "di": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz", + "integrity": "sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw=", + "dev": true + }, + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true + }, + "dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "requires": { + "path-type": "^4.0.0" + } + }, + "dns-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/dns-equal/-/dns-equal-1.0.0.tgz", + "integrity": "sha1-s55/HabrCnW6nBcySzR1PEfgZU0=", + "dev": true + }, + "dns-packet": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-1.3.4.tgz", + "integrity": "sha512-BQ6F4vycLXBvdrJZ6S3gZewt6rcrks9KBgM9vrhW+knGRqc8uEdT7fuCwloc7nny5xNoMJ17HGH0R/6fpo8ECA==", + "dev": true, + "requires": { + "ip": "^1.1.0", + "safe-buffer": "^5.0.1" + } + }, + "dns-txt": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/dns-txt/-/dns-txt-2.0.2.tgz", + "integrity": "sha1-uR2Ab10nGI5Ks+fRB9iBocxGQrY=", + "dev": true, + "requires": { + "buffer-indexof": "^1.0.0" + } + }, + "dom-serialize": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/dom-serialize/-/dom-serialize-2.2.1.tgz", + "integrity": "sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs=", + "dev": true, + "requires": { + "custom-event": "~1.0.0", + "ent": "~2.2.0", + "extend": "^3.0.0", + "void-elements": "^2.0.0" + } + }, + "dom-serializer": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz", + "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==", + "dev": true, + "requires": { + "domelementtype": "^2.0.1", + "domhandler": "^4.2.0", + "entities": "^2.0.0" + } + }, + "domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true + }, + "domhandler": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz", + "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==", + "dev": true, + "requires": { + "domelementtype": "^2.2.0" + } + }, + "domutils": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz", + "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==", + "dev": true, + "requires": { + "dom-serializer": "^1.0.1", + "domelementtype": "^2.2.0", + "domhandler": "^4.2.0" + } + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", + "dev": true + }, + "electron-to-chromium": { + "version": "1.4.122", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.122.tgz", + "integrity": "sha512-VuLNxTIt8sBWIT2sd186xPd18Y8KcK8myLd9nMdSJOYZwFUxxbLVmX/T1VX+qqaytRlrYYQv39myxJdXtu7Ysw==", + "dev": true + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "emojis-list": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz", + "integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==", + "dev": true + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "dev": true + }, + "encoding": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", + "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", + "dev": true, + "optional": true, + "requires": { + "iconv-lite": "^0.6.2" + }, + "dependencies": { + "iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "optional": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + } + } + } + }, + "engine.io": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.1.3.tgz", + "integrity": "sha512-rqs60YwkvWTLLnfazqgZqLa/aKo+9cueVfEi/dZ8PyGyaf8TLOxj++4QMIgeG3Gn0AhrWiFXvghsoY9L9h25GA==", + "dev": true, + "requires": { + "@types/cookie": "^0.4.1", + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "accepts": "~1.3.4", + "base64id": "2.0.0", + "cookie": "~0.4.1", + "cors": "~2.8.5", + "debug": "~4.3.1", + "engine.io-parser": "~5.0.3", + "ws": "~8.2.3" + } + }, + "engine.io-parser": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.3.tgz", + "integrity": "sha512-BtQxwF27XUNnSafQLvDi0dQ8s3i6VgzSoQMJacpIcGNrlUdfHSKbgm3jmjCVvQluGzqwujQMPAoMai3oYSTurg==", + "dev": true, + "requires": { + "@socket.io/base64-arraybuffer": "~1.0.2" + } + }, + "enhanced-resolve": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.9.3.tgz", + "integrity": "sha512-Bq9VSor+kjvW3f9/MiiR4eE3XYgOl7/rS8lnSxbRbF3kS0B2r+Y9w5krBWxZgDxASVZbdYrn5wT4j/Wb0J9qow==", + "dev": true, + "requires": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + } + }, + "ent": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz", + "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=", + "dev": true + }, + "entities": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", + "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", + "dev": true + }, + "env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true + }, + "err-code": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz", + "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==", + "dev": true + }, + "errno": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.8.tgz", + "integrity": "sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==", + "dev": true, + "optional": true, + "requires": { + "prr": "~1.0.1" + } + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "es-module-lexer": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-0.9.3.tgz", + "integrity": "sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ==", + "dev": true + }, + "esbuild": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.14.22.tgz", + "integrity": "sha512-CjFCFGgYtbFOPrwZNJf7wsuzesx8kqwAffOlbYcFDLFuUtP8xloK1GH+Ai13Qr0RZQf9tE7LMTHJ2iVGJ1SKZA==", + "dev": true, + "optional": true, + "requires": { + "esbuild-android-arm64": "0.14.22", + "esbuild-darwin-64": "0.14.22", + "esbuild-darwin-arm64": "0.14.22", + "esbuild-freebsd-64": "0.14.22", + "esbuild-freebsd-arm64": "0.14.22", + "esbuild-linux-32": "0.14.22", + "esbuild-linux-64": "0.14.22", + "esbuild-linux-arm": "0.14.22", + "esbuild-linux-arm64": "0.14.22", + "esbuild-linux-mips64le": "0.14.22", + "esbuild-linux-ppc64le": "0.14.22", + "esbuild-linux-riscv64": "0.14.22", + "esbuild-linux-s390x": "0.14.22", + "esbuild-netbsd-64": "0.14.22", + "esbuild-openbsd-64": "0.14.22", + "esbuild-sunos-64": "0.14.22", + "esbuild-windows-32": "0.14.22", + "esbuild-windows-64": "0.14.22", + "esbuild-windows-arm64": "0.14.22" + } + }, + "esbuild-android-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.14.22.tgz", + "integrity": "sha512-k1Uu4uC4UOFgrnTj2zuj75EswFSEBK+H6lT70/DdS4mTAOfs2ECv2I9ZYvr3w0WL0T4YItzJdK7fPNxcPw6YmQ==", + "dev": true, + "optional": true + }, + "esbuild-darwin-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.14.22.tgz", + "integrity": "sha512-d8Ceuo6Vw6HM3fW218FB6jTY6O3r2WNcTAU0SGsBkXZ3k8SDoRLd3Nrc//EqzdgYnzDNMNtrWegK2Qsss4THhw==", + "dev": true, + "optional": true + }, + "esbuild-darwin-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.14.22.tgz", + "integrity": "sha512-YAt9Tj3SkIUkswuzHxkaNlT9+sg0xvzDvE75LlBo4DI++ogSgSmKNR6B4eUhU5EUUepVXcXdRIdqMq9ppeRqfw==", + "dev": true, + "optional": true + }, + "esbuild-freebsd-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.14.22.tgz", + "integrity": "sha512-ek1HUv7fkXMy87Qm2G4IRohN+Qux4IcnrDBPZGXNN33KAL0pEJJzdTv0hB/42+DCYWylSrSKxk3KUXfqXOoH4A==", + "dev": true, + "optional": true + }, + "esbuild-freebsd-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.14.22.tgz", + "integrity": "sha512-zPh9SzjRvr9FwsouNYTqgqFlsMIW07O8mNXulGeQx6O5ApgGUBZBgtzSlBQXkHi18WjrosYfsvp5nzOKiWzkjQ==", + "dev": true, + "optional": true + }, + "esbuild-linux-32": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.14.22.tgz", + "integrity": "sha512-SnpveoE4nzjb9t2hqCIzzTWBM0RzcCINDMBB67H6OXIuDa4KqFqaIgmTchNA9pJKOVLVIKd5FYxNiJStli21qg==", + "dev": true, + "optional": true + }, + "esbuild-linux-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.22.tgz", + "integrity": "sha512-Zcl9Wg7gKhOWWNqAjygyqzB+fJa19glgl2JG7GtuxHyL1uEnWlpSMytTLMqtfbmRykIHdab797IOZeKwk5g0zg==", + "dev": true, + "optional": true + }, + "esbuild-linux-arm": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.14.22.tgz", + "integrity": "sha512-soPDdbpt/C0XvOOK45p4EFt8HbH5g+0uHs5nUKjHVExfgR7du734kEkXR/mE5zmjrlymk5AA79I0VIvj90WZ4g==", + "dev": true, + "optional": true + }, + "esbuild-linux-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.14.22.tgz", + "integrity": "sha512-8q/FRBJtV5IHnQChO3LHh/Jf7KLrxJ/RCTGdBvlVZhBde+dk3/qS9fFsUy+rs3dEi49aAsyVitTwlKw1SUFm+A==", + "dev": true, + "optional": true + }, + "esbuild-linux-mips64le": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.14.22.tgz", + "integrity": "sha512-SiNDfuRXhGh1JQLLA9JPprBgPVFOsGuQ0yDfSPTNxztmVJd8W2mX++c4FfLpAwxuJe183mLuKf7qKCHQs5ZnBQ==", + "dev": true, + "optional": true + }, + "esbuild-linux-ppc64le": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.14.22.tgz", + "integrity": "sha512-6t/GI9I+3o1EFm2AyN9+TsjdgWCpg2nwniEhjm2qJWtJyJ5VzTXGUU3alCO3evopu8G0hN2Bu1Jhz2YmZD0kng==", + "dev": true, + "optional": true + }, + "esbuild-linux-riscv64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.14.22.tgz", + "integrity": "sha512-AyJHipZKe88sc+tp5layovquw5cvz45QXw5SaDgAq2M911wLHiCvDtf/07oDx8eweCyzYzG5Y39Ih568amMTCQ==", + "dev": true, + "optional": true + }, + "esbuild-linux-s390x": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.14.22.tgz", + "integrity": "sha512-Sz1NjZewTIXSblQDZWEFZYjOK6p8tV6hrshYdXZ0NHTjWE+lwxpOpWeElUGtEmiPcMT71FiuA9ODplqzzSxkzw==", + "dev": true, + "optional": true + }, + "esbuild-netbsd-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.14.22.tgz", + "integrity": "sha512-TBbCtx+k32xydImsHxvFgsOCuFqCTGIxhzRNbgSL1Z2CKhzxwT92kQMhxort9N/fZM2CkRCPPs5wzQSamtzEHA==", + "dev": true, + "optional": true + }, + "esbuild-openbsd-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.14.22.tgz", + "integrity": "sha512-vK912As725haT313ANZZZN+0EysEEQXWC/+YE4rQvOQzLuxAQc2tjbzlAFREx3C8+uMuZj/q7E5gyVB7TzpcTA==", + "dev": true, + "optional": true + }, + "esbuild-sunos-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.14.22.tgz", + "integrity": "sha512-/mbJdXTW7MTcsPhtfDsDyPEOju9EOABvCjeUU2OJ7fWpX/Em/H3WYDa86tzLUbcVg++BScQDzqV/7RYw5XNY0g==", + "dev": true, + "optional": true + }, + "esbuild-wasm": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-wasm/-/esbuild-wasm-0.14.22.tgz", + "integrity": "sha512-FOSAM29GN1fWusw0oLMv6JYhoheDIh5+atC72TkJKfIUMID6yISlicoQSd9gsNSFsNBvABvtE2jR4JB1j4FkFw==", + "dev": true + }, + "esbuild-windows-32": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.14.22.tgz", + "integrity": "sha512-1vRIkuvPTjeSVK3diVrnMLSbkuE36jxA+8zGLUOrT4bb7E/JZvDRhvtbWXWaveUc/7LbhaNFhHNvfPuSw2QOQg==", + "dev": true, + "optional": true + }, + "esbuild-windows-64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.14.22.tgz", + "integrity": "sha512-AxjIDcOmx17vr31C5hp20HIwz1MymtMjKqX4qL6whPj0dT9lwxPexmLj6G1CpR3vFhui6m75EnBEe4QL82SYqw==", + "dev": true, + "optional": true + }, + "esbuild-windows-arm64": { + "version": "0.14.22", + "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.14.22.tgz", + "integrity": "sha512-5wvQ+39tHmRhNpu2Fx04l7QfeK3mQ9tKzDqqGR8n/4WUxsFxnVLfDRBGirIfk4AfWlxk60kqirlODPoT5LqMUg==", + "dev": true, + "optional": true + }, + "escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "requires": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + } + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + }, + "esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "requires": { + "estraverse": "^5.2.0" + }, + "dependencies": { + "estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true + } + } + }, + "estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true + }, + "esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true + }, + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "dev": true + }, + "eventemitter-asyncresource": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/eventemitter-asyncresource/-/eventemitter-asyncresource-1.0.0.tgz", + "integrity": "sha512-39F7TBIV0G7gTelxwbEqnwhp90eqCPON1k0NwNfwhgKn4Co4ybUbj2pECcXT0B3ztRKZ7Pw1JujUUgmQJHcVAQ==", + "dev": true + }, + "eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "dev": true + }, + "events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true + }, + "execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + } + }, + "express": { + "version": "4.18.0", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.0.tgz", + "integrity": "sha512-EJEXxiTQJS3lIPrU1AE2vRuT7X7E+0KBbpm5GSoK524yl0K8X+er8zS2P14E64eqsVNoWbMCT7MpmQ+ErAhgRg==", + "dev": true, + "requires": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.0", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.5.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.10.3", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "dependencies": { + "array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=", + "dev": true + }, + "cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "dev": true + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true + }, + "finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "dev": true, + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true + }, + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "dev": true + } + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true + }, + "external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "requires": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + } + }, + "fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "fast-glob": { + "version": "3.2.11", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.11.tgz", + "integrity": "sha512-xrO3+1bxSo3ZVHAnqzyuewYT6aMFHRAd4Kcs92MAonjwQZLsK9d0SF1IyQ3k5PoirxTW0Oe/RqFgMQ6TcNE5Ew==", + "dev": true, + "requires": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + } + }, + "fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "fastparse": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.2.tgz", + "integrity": "sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ==", + "dev": true + }, + "fastq": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.13.0.tgz", + "integrity": "sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==", + "dev": true, + "requires": { + "reusify": "^1.0.4" + } + }, + "faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "dev": true, + "requires": { + "websocket-driver": ">=0.5.1" + } + }, + "figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "finalhandler": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", + "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "dev": true, + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "statuses": "~1.5.0", + "unpipe": "~1.0.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } + } + }, + "find-cache-dir": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz", + "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" + } + }, + "find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "requires": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + } + }, + "flatted": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.5.tgz", + "integrity": "sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==", + "dev": true + }, + "follow-redirects": { + "version": "1.14.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz", + "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==", + "dev": true + }, + "forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true + }, + "fraction.js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.2.0.tgz", + "integrity": "sha512-MhLuK+2gUcnZe8ZHlaaINnQLl0xRIGRfcGk2yl8xoQAfHrSsL3rYu6FCmBdkdbhc9EPlwyGHewaRsvwRMJtAlA==", + "dev": true + }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "dev": true + }, + "fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dev": true, + "requires": { + "minipass": "^3.0.0" + } + }, + "fs-monkey": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-1.0.3.tgz", + "integrity": "sha512-cybjIfiiE+pTWicSCLFHSrXZ6EilF30oh91FDP9S2B051prEa7QWfrVTQm10/dDpswBDXZugPa1Ogu8Yh+HV0Q==", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "optional": true + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true + }, + "gauge": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-4.0.4.tgz", + "integrity": "sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg==", + "dev": true, + "requires": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.3", + "console-control-strings": "^1.1.0", + "has-unicode": "^2.0.1", + "signal-exit": "^3.0.7", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.5" + } + }, + "gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true + }, + "get-intrinsic": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", + "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1" + } + }, + "get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true + }, + "get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true + }, + "glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "requires": { + "is-glob": "^4.0.1" + } + }, + "glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true + }, + "globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true + }, + "globby": { + "version": "12.2.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-12.2.0.tgz", + "integrity": "sha512-wiSuFQLZ+urS9x2gGPl1H5drc5twabmm4m2gTR27XDFyjUHJUNsS8o/2aKyIF6IoBaR630atdher0XJ5g6OMmA==", + "dev": true, + "requires": { + "array-union": "^3.0.1", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.7", + "ignore": "^5.1.9", + "merge2": "^1.4.1", + "slash": "^4.0.0" + } + }, + "graceful-fs": { + "version": "4.2.9", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", + "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", + "dev": true + }, + "handle-thing": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-2.0.1.tgz", + "integrity": "sha512-9Qn4yBxelxoh2Ow62nP+Ka/kMnOXRi8BXnRaUwezLNhqelnN49xKz4F/dPP8OYLxLxq6JDtZb2i9XznUQbNPTg==", + "dev": true + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "has-property-descriptors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", + "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", + "dev": true, + "requires": { + "get-intrinsic": "^1.1.1" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "dev": true + }, + "has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "dev": true, + "requires": { + "has-symbols": "^1.0.2" + } + }, + "has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", + "dev": true + }, + "hdr-histogram-js": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/hdr-histogram-js/-/hdr-histogram-js-2.0.3.tgz", + "integrity": "sha512-Hkn78wwzWHNCp2uarhzQ2SGFLU3JY8SBDDd3TAABK4fc30wm+MuPOrg5QVFVfkKOQd6Bfz3ukJEI+q9sXEkK1g==", + "dev": true, + "requires": { + "@assemblyscript/loader": "^0.10.1", + "base64-js": "^1.2.0", + "pako": "^1.0.3" + } + }, + "hdr-histogram-percentiles-obj": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hdr-histogram-percentiles-obj/-/hdr-histogram-percentiles-obj-3.0.0.tgz", + "integrity": "sha512-7kIufnBqdsBGcSZLPJwqHT3yhk1QTsSlFsVD3kx5ixH/AlgBs9yM1q6DPhXZ8f8gtdqgh7N7/5btRLpQsS2gHw==", + "dev": true + }, + "hosted-git-info": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", + "integrity": "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==", + "dev": true, + "requires": { + "lru-cache": "^6.0.0" + } + }, + "hpack.js": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/hpack.js/-/hpack.js-2.1.6.tgz", + "integrity": "sha1-h3dMCUnlE/QuhFdbPEVoH63ioLI=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "obuf": "^1.0.0", + "readable-stream": "^2.0.1", + "wbuf": "^1.1.0" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "html-entities": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.3.3.tgz", + "integrity": "sha512-DV5Ln36z34NNTDgnz0EWGBLZENelNAtkiFA4kyNOG2tDI6Mz1uSWiq1wAKdyjnJwyDiDO7Fa2SO1CTxPXL8VxA==", + "dev": true + }, + "html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true + }, + "http-cache-semantics": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz", + "integrity": "sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==", + "dev": true + }, + "http-deceiver": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz", + "integrity": "sha1-+nFolEq5pRnTN8sL7HKE3D5yPYc=", + "dev": true + }, + "http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dev": true, + "requires": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "dependencies": { + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true + }, + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "dev": true + } + } + }, + "http-parser-js": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.6.tgz", + "integrity": "sha512-vDlkRPDJn93swjcjqMSaGSPABbIarsr1TLAui/gLDXzV5VsJNdXNzMYDyNBLQkjWQCJ1uizu8T2oDMhmGt0PRA==", + "dev": true + }, + "http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "dev": true, + "requires": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + } + }, + "http-proxy-agent": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", + "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", + "dev": true, + "requires": { + "@tootallnate/once": "1", + "agent-base": "6", + "debug": "4" + } + }, + "http-proxy-middleware": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.6.tgz", + "integrity": "sha512-ya/UeJ6HVBYxrgYotAZo1KvPWlgB48kUJLDePFeneHsVujFaW5WNj2NgWCAE//B1Dl02BIfYlpNgBy8Kf8Rjmw==", + "dev": true, + "requires": { + "@types/http-proxy": "^1.17.8", + "http-proxy": "^1.18.1", + "is-glob": "^4.0.1", + "is-plain-obj": "^3.0.0", + "micromatch": "^4.0.2" + } + }, + "https-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", + "integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", + "dev": true, + "requires": { + "agent-base": "6", + "debug": "4" + } + }, + "human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true + }, + "humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha1-xG4xWaKT9riW2ikxbYtv6Lt5u+0=", + "dev": true, + "requires": { + "ms": "^2.0.0" + } + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "icss-utils": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-5.1.0.tgz", + "integrity": "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==", + "dev": true, + "requires": {} + }, + "ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true + }, + "ignore": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.0.tgz", + "integrity": "sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ==", + "dev": true + }, + "ignore-walk": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-4.0.1.tgz", + "integrity": "sha512-rzDQLaW4jQbh2YrOFlJdCtX8qgJTehFRYiUB2r1osqTeDzV/3+Jh8fz1oAPzUThf3iku8Ds4IDqawI5d8mUiQw==", + "dev": true, + "requires": { + "minimatch": "^3.0.4" + } + }, + "image-size": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-0.5.5.tgz", + "integrity": "sha1-Cd/Uq50g4p6xw+gLiZA3jfnjy5w=", + "dev": true, + "optional": true + }, + "immutable": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/immutable/-/immutable-4.0.0.tgz", + "integrity": "sha512-zIE9hX70qew5qTUjSS7wi1iwj/l7+m54KWU247nhM3v806UdGj1yDndXj+IOYxxtW9zyLI+xqFNZjTuDaLUqFw==", + "dev": true + }, + "import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "dev": true, + "requires": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "dependencies": { + "resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true + } + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true + }, + "infer-owner": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz", + "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "ini": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-2.0.0.tgz", + "integrity": "sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==", + "dev": true + }, + "inquirer": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.0.tgz", + "integrity": "sha512-0crLweprevJ02tTuA6ThpoAERAGyVILC4sS74uib58Xf/zSr1/ZWtmm7D5CI+bSQEaA04f0K7idaHpQbSWgiVQ==", + "dev": true, + "requires": { + "ansi-escapes": "^4.2.1", + "chalk": "^4.1.1", + "cli-cursor": "^3.1.0", + "cli-width": "^3.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.21", + "mute-stream": "0.0.8", + "ora": "^5.4.1", + "run-async": "^2.4.0", + "rxjs": "^7.2.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "rxjs": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.5.5.tgz", + "integrity": "sha512-sy+H0pQofO95VDmFLzyaw9xNJU4KTRSwQIGM6+iG3SypAtCiLDzpeG8sJrNCWn2Up9km+KhkvTdbkrdy+yzZdw==", + "dev": true, + "requires": { + "tslib": "^2.1.0" + } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "ip": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/ip/-/ip-1.1.5.tgz", + "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=", + "dev": true + }, + "ipaddr.js": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.0.1.tgz", + "integrity": "sha512-1qTgH9NG+IIJ4yfKs2e6Pp1bZg8wbDbKHT21HrLIeYBTRLgMYKnMTPAuI3Lcs61nfx5h1xlXnbJtH1kX5/d/ng==", + "dev": true + }, + "is-arguments": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "requires": { + "binary-extensions": "^2.0.0" + } + }, + "is-core-module": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.1.tgz", + "integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, + "is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dev": true, + "requires": { + "has-tostringtag": "^1.0.0" + } + }, + "is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-interactive": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "dev": true + }, + "is-lambda": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-lambda/-/is-lambda-1.0.1.tgz", + "integrity": "sha1-PZh3iZ5qU+/AFgUEzeFfgubwYdU=", + "dev": true + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true + }, + "is-path-cwd": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-2.2.0.tgz", + "integrity": "sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ==", + "dev": true + }, + "is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true + }, + "is-plain-obj": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-3.0.0.tgz", + "integrity": "sha512-gwsOE28k+23GP1B6vFl1oVh/WOzmawBrKwo5Ev6wMKzPkaXaCDIQKzLnvsA42DRlbVTWorkgTKIviAKCWkfUwA==", + "dev": true + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + } + }, + "is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true + }, + "is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "dev": true + }, + "is-what": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/is-what/-/is-what-3.14.1.tgz", + "integrity": "sha512-sNxgpk9793nzSs7bA6JQJGeIuRBQhAaNGG77kzYQgMkrID+lS6SlK07K5LaptscDlSaIgH+GPFzf+d75FVxozA==", + "dev": true + }, + "is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "requires": { + "is-docker": "^2.0.0" + } + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isbinaryfile": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.8.tgz", + "integrity": "sha512-53h6XFniq77YdW+spoRrebh0mnmTxRPTlcuIArO57lmMdq4uBKFKaeTjnb92oYWrSn/LVL+LT+Hap2tFQj8V+w==", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "dev": true + }, + "istanbul-lib-instrument": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.0.tgz", + "integrity": "sha512-6Lthe1hqXHBNsqvgDzGO6l03XNeu3CrG4RqQ1KM9+l5+jNGpEJfIELx1NS3SEHmJQA8np/u+E4EPRKRiu6m19A==", + "dev": true, + "requires": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" + }, + "dependencies": { + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "istanbul-lib-source-maps": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.6.tgz", + "integrity": "sha512-R47KzMtDJH6X4/YW9XTx+jrLnZnscW4VpNN+1PViSYTejLVPWv7oov+Duf8YQSPyVRUvueQqz1TcsC6mooZTXw==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^2.0.5", + "make-dir": "^2.1.0", + "rimraf": "^2.6.3", + "source-map": "^0.6.1" + }, + "dependencies": { + "istanbul-lib-coverage": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz", + "integrity": "sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA==", + "dev": true + }, + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } + }, + "pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true + }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "istanbul-reports": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.4.tgz", + "integrity": "sha512-r1/DshN4KSE7xWEknZLLLLDn5CJybV3nw01VTkp6D5jzLuELlcbudfj/eSQFvrKsJuTVCGnePO7ho82Nw9zzfw==", + "dev": true, + "requires": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + } + }, + "jasmine-core": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-3.8.0.tgz", + "integrity": "sha512-zl0nZWDrmbCiKns0NcjkFGYkVTGCPUgoHypTaj+G2AzaWus7QGoXARSlYsSle2VRpSdfJmM+hzmFKzQNhF2kHg==", + "dev": true + }, + "jasmine-spec-reporter": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/jasmine-spec-reporter/-/jasmine-spec-reporter-5.0.2.tgz", + "integrity": "sha512-6gP1LbVgJ+d7PKksQBc2H0oDGNRQI3gKUsWlswKaQ2fif9X5gzhQcgM5+kiJGCQVurOG09jqNhk7payggyp5+g==", + "dev": true, + "requires": { + "colors": "1.4.0" + } + }, + "jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "requires": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "dependencies": { + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true + }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, + "json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "json5": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", + "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", + "dev": true + }, + "jsonc-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.0.0.tgz", + "integrity": "sha512-fQzRfAbIBnR0IQvftw9FJveWiHp72Fg20giDrHz6TdfB12UH/uue0D3hm57UB5KgAVuniLMCaS8P1IMj9NR7cA==", + "dev": true + }, + "jsonparse": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", + "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=", + "dev": true + }, + "karma": { + "version": "6.3.17", + "resolved": "https://registry.npmjs.org/karma/-/karma-6.3.17.tgz", + "integrity": "sha512-2TfjHwrRExC8yHoWlPBULyaLwAFmXmxQrcuFImt/JsAsSZu1uOWTZ1ZsWjqQtWpHLiatJOHL5jFjXSJIgCd01g==", + "dev": true, + "requires": { + "@colors/colors": "1.5.0", + "body-parser": "^1.19.0", + "braces": "^3.0.2", + "chokidar": "^3.5.1", + "connect": "^3.7.0", + "di": "^0.0.1", + "dom-serialize": "^2.2.1", + "glob": "^7.1.7", + "graceful-fs": "^4.2.6", + "http-proxy": "^1.18.1", + "isbinaryfile": "^4.0.8", + "lodash": "^4.17.21", + "log4js": "^6.4.1", + "mime": "^2.5.2", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.5", + "qjobs": "^1.2.0", + "range-parser": "^1.2.1", + "rimraf": "^3.0.2", + "socket.io": "^4.2.0", + "source-map": "^0.6.1", + "tmp": "^0.2.1", + "ua-parser-js": "^0.7.30", + "yargs": "^16.1.1" + }, + "dependencies": { + "mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "dev": true, + "requires": { + "minimist": "^1.2.5" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "tmp": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz", + "integrity": "sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ==", + "dev": true, + "requires": { + "rimraf": "^3.0.0" + } + } + } + }, + "karma-chrome-launcher": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/karma-chrome-launcher/-/karma-chrome-launcher-3.1.0.tgz", + "integrity": "sha512-3dPs/n7vgz1rxxtynpzZTvb9y/GIaW8xjAwcIGttLbycqoFtI7yo1NGnQi6oFTherRE+GIhCAHZC4vEqWGhNvg==", + "dev": true, + "requires": { + "which": "^1.2.1" + } + }, + "karma-coverage-istanbul-reporter": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/karma-coverage-istanbul-reporter/-/karma-coverage-istanbul-reporter-3.0.3.tgz", + "integrity": "sha512-wE4VFhG/QZv2Y4CdAYWDbMmcAHeS926ZIji4z+FkB2aF/EposRb6DP6G5ncT/wXhqUfAb/d7kZrNKPonbvsATw==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^3.0.6", + "istanbul-reports": "^3.0.2", + "minimatch": "^3.0.4" + } + }, + "karma-jasmine": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/karma-jasmine/-/karma-jasmine-4.0.1.tgz", + "integrity": "sha512-h8XDAhTiZjJKzfkoO1laMH+zfNlra+dEQHUAjpn5JV1zCPtOIVWGQjLBrqhnzQa/hrU2XrZwSyBa6XjEBzfXzw==", + "dev": true, + "requires": { + "jasmine-core": "^3.6.0" + } + }, + "karma-jasmine-html-reporter": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/karma-jasmine-html-reporter/-/karma-jasmine-html-reporter-1.7.0.tgz", + "integrity": "sha512-pzum1TL7j90DTE86eFt48/s12hqwQuiD+e5aXx2Dc9wDEn2LfGq6RoAxEZZjFiN0RDSCOnosEKRZWxbQ+iMpQQ==", + "dev": true, + "requires": {} + }, + "karma-source-map-support": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/karma-source-map-support/-/karma-source-map-support-1.4.0.tgz", + "integrity": "sha512-RsBECncGO17KAoJCYXjv+ckIz+Ii9NCi+9enk+rq6XC81ezYkb4/RHE6CTXdA7IOJqoF3wcaLfVG0CPmE5ca6A==", + "dev": true, + "requires": { + "source-map-support": "^0.5.5" + } + }, + "kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true + }, + "klona": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/klona/-/klona-2.0.5.tgz", + "integrity": "sha512-pJiBpiXMbt7dkzXe8Ghj/u4FfXOOa98fPW+bihOJ4SjnoijweJrNThJfd3ifXpXhREjpoF2mZVH1GfS9LV3kHQ==", + "dev": true + }, + "less": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/less/-/less-4.1.2.tgz", + "integrity": "sha512-EoQp/Et7OSOVu0aJknJOtlXZsnr8XE8KwuzTHOLeVSEx8pVWUICc8Q0VYRHgzyjX78nMEyC/oztWFbgyhtNfDA==", + "dev": true, + "requires": { + "copy-anything": "^2.0.1", + "errno": "^0.1.1", + "graceful-fs": "^4.1.2", + "image-size": "~0.5.0", + "make-dir": "^2.1.0", + "mime": "^1.4.1", + "needle": "^2.5.2", + "parse-node-version": "^1.0.1", + "source-map": "~0.6.0", + "tslib": "^2.3.0" + }, + "dependencies": { + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "optional": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true, + "optional": true + }, + "pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true, + "optional": true + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true, + "optional": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true + } + } + }, + "less-loader": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/less-loader/-/less-loader-10.2.0.tgz", + "integrity": "sha512-AV5KHWvCezW27GT90WATaDnfXBv99llDbtaj4bshq6DvAihMdNjaPDcUMa6EXKLRF+P2opFenJp89BXg91XLYg==", + "dev": true, + "requires": { + "klona": "^2.0.4" + } + }, + "license-webpack-plugin": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/license-webpack-plugin/-/license-webpack-plugin-4.0.2.tgz", + "integrity": "sha512-771TFWFD70G1wLTC4oU2Cw4qvtmNrIw+wRvBtn+okgHl7slJVi7zfNcdmqDL72BojM30VNJ2UHylr1o77U37Jw==", + "dev": true, + "requires": { + "webpack-sources": "^3.0.0" + } + }, + "lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true + }, + "loader-runner": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", + "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", + "dev": true + }, + "loader-utils": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-3.2.0.tgz", + "integrity": "sha512-HVl9ZqccQihZ7JM85dco1MvO9G+ONvxoGa9rkhzFsneGLKSUg1gJf9bWzhRhcvm2qChhWpebQhP44qxjKIUCaQ==", + "dev": true + }, + "locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "requires": { + "p-locate": "^4.1.0" + } + }, + "lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true + }, + "lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168=", + "dev": true + }, + "log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dev": true, + "requires": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "log4js": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/log4js/-/log4js-6.4.1.tgz", + "integrity": "sha512-iUiYnXqAmNKiIZ1XSAitQ4TmNs8CdZYTAWINARF3LjnsLN8tY5m0vRwd6uuWj/yNY0YHxeZodnbmxKFUOM2rMg==", + "dev": true, + "requires": { + "date-format": "^4.0.3", + "debug": "^4.3.3", + "flatted": "^3.2.4", + "rfdc": "^1.3.0", + "streamroller": "^3.0.2" + } + }, + "lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "requires": { + "yallist": "^4.0.0" + } + }, + "magic-string": { + "version": "0.25.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz", + "integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==", + "dev": true, + "requires": { + "sourcemap-codec": "^1.4.4" + } + }, + "make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "requires": { + "semver": "^6.0.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, + "make-fetch-happen": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-9.1.0.tgz", + "integrity": "sha512-+zopwDy7DNknmwPQplem5lAZX/eCOzSvSNNcSKm5eVwTkOBzoktEfXsa9L23J/GIRhxRsaxzkPEhrJEpE2F4Gg==", + "dev": true, + "requires": { + "agentkeepalive": "^4.1.3", + "cacache": "^15.2.0", + "http-cache-semantics": "^4.1.0", + "http-proxy-agent": "^4.0.1", + "https-proxy-agent": "^5.0.0", + "is-lambda": "^1.0.1", + "lru-cache": "^6.0.0", + "minipass": "^3.1.3", + "minipass-collect": "^1.0.2", + "minipass-fetch": "^1.3.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.2", + "promise-retry": "^2.0.1", + "socks-proxy-agent": "^6.0.0", + "ssri": "^8.0.0" + } + }, + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "dev": true + }, + "memfs": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/memfs/-/memfs-3.4.1.tgz", + "integrity": "sha512-1c9VPVvW5P7I85c35zAdEr1TD5+F11IToIHIlrVIcflfnzPkJa0ZoYEoEdYDP8KgPFoSZ/opDrUsAoZWym3mtw==", + "dev": true, + "requires": { + "fs-monkey": "1.0.3" + } + }, + "merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", + "dev": true + }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", + "dev": true + }, + "micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "requires": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + } + }, + "mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "dev": true + }, + "mime-db": { + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz", + "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==", + "dev": true + }, + "mime-types": { + "version": "2.1.34", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz", + "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==", + "dev": true, + "requires": { + "mime-db": "1.51.0" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true + }, + "mini-css-extract-plugin": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.5.3.tgz", + "integrity": "sha512-YseMB8cs8U/KCaAGQoqYmfUuhhGW0a9p9XvWXrxVOkE3/IiISTLw4ALNt7JR5B2eYauFM+PQGSbXMDmVbR7Tfw==", + "dev": true, + "requires": { + "schema-utils": "^4.0.0" + }, + "dependencies": { + "ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + } + }, + "ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.3" + } + }, + "json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "schema-utils": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.0.0.tgz", + "integrity": "sha512-1edyXKgh6XnJsJSQ8mKWXnN/BVaIbFMLpouRUrXgVq7WYne5kw3MW7UPhO44uRXQSIpTSXoJbmrR2X0w9kUTyg==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.8.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.0.0" + } + } + } + }, + "minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true + }, + "minimatch": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.5.tgz", + "integrity": "sha512-tUpxzX0VAzJHjLu0xUfFv1gwVp9ba3IOuRAVH2EGuRW8a5emA2FlACLqiT/lDVtS1W+TGNwqz3sWaNyLgDJWuw==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", + "dev": true + }, + "minipass": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.1.6.tgz", + "integrity": "sha512-rty5kpw9/z8SX9dmxblFA6edItUmwJgMeYDZRrwlIVN27i8gysGbznJwUggw2V/FVqFSDdWy040ZPS811DYAqQ==", + "dev": true, + "requires": { + "yallist": "^4.0.0" + } + }, + "minipass-collect": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-1.0.2.tgz", + "integrity": "sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA==", + "dev": true, + "requires": { + "minipass": "^3.0.0" + } + }, + "minipass-fetch": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-1.4.1.tgz", + "integrity": "sha512-CGH1eblLq26Y15+Azk7ey4xh0J/XfJfrCox5LDJiKqI2Q2iwOLOKrlmIaODiSQS8d18jalF6y2K2ePUm0CmShw==", + "dev": true, + "requires": { + "encoding": "^0.1.12", + "minipass": "^3.1.0", + "minipass-sized": "^1.0.3", + "minizlib": "^2.0.0" + } + }, + "minipass-flush": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz", + "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==", + "dev": true, + "requires": { + "minipass": "^3.0.0" + } + }, + "minipass-json-stream": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minipass-json-stream/-/minipass-json-stream-1.0.1.tgz", + "integrity": "sha512-ODqY18UZt/I8k+b7rl2AENgbWE8IDYam+undIJONvigAz8KR5GWblsFTEfQs0WODsjbSXWlm+JHEv8Gr6Tfdbg==", + "dev": true, + "requires": { + "jsonparse": "^1.3.1", + "minipass": "^3.0.0" + } + }, + "minipass-pipeline": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", + "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", + "dev": true, + "requires": { + "minipass": "^3.0.0" + } + }, + "minipass-sized": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz", + "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==", + "dev": true, + "requires": { + "minipass": "^3.0.0" + } + }, + "minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dev": true, + "requires": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + } + }, + "mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "multicast-dns": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-6.2.3.tgz", + "integrity": "sha512-ji6J5enbMyGRHIAkAOu3WdV8nggqviKCEKtXcOqfphZZtQrmHKycfynJ2V7eVPUA4NhJ6V7Wf4TmGbTwKE9B6g==", + "dev": true, + "requires": { + "dns-packet": "^1.3.1", + "thunky": "^1.0.2" + } + }, + "multicast-dns-service-types": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz", + "integrity": "sha1-iZ8R2WhuXgXLkbNdXw5jt3PPyQE=", + "dev": true + }, + "mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true + }, + "nanoid": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.1.tgz", + "integrity": "sha512-n6Vs/3KGyxPQd6uO0eH4Bv0ojGSUvuLlIHtC3Y0kEO23YRge8H9x1GCzLn28YX0H66pMkxuaeESFq4tKISKwdw==", + "dev": true + }, + "needle": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/needle/-/needle-2.9.1.tgz", + "integrity": "sha512-6R9fqJ5Zcmf+uYaFgdIHmLwNldn5HbK8L5ybn7Uz+ylX/rnOsSp1AHcvQSrCaFN+qNM1wpymHqD7mVasEOlHGQ==", + "dev": true, + "optional": true, + "requires": { + "debug": "^3.2.6", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + }, + "dependencies": { + "debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "optional": true, + "requires": { + "ms": "^2.1.1" + } + } + } + }, + "negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "dev": true + }, + "neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "dev": true + }, + "nice-napi": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/nice-napi/-/nice-napi-1.0.2.tgz", + "integrity": "sha512-px/KnJAJZf5RuBGcfD+Sp2pAKq0ytz8j+1NehvgIGFkvtvFrDM3T8E4x/JJODXK9WZow8RRGrbA9QQ3hs+pDhA==", + "dev": true, + "optional": true, + "requires": { + "node-addon-api": "^3.0.0", + "node-gyp-build": "^4.2.2" + } + }, + "node-addon-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz", + "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==", + "dev": true, + "optional": true + }, + "node-forge": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz", + "integrity": "sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==", + "dev": true + }, + "node-gyp": { + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-8.4.1.tgz", + "integrity": "sha512-olTJRgUtAb/hOXG0E93wZDs5YiJlgbXxTwQAFHyNlRsXQnYzUaF2aGgujZbw+hR8aF4ZG/rST57bWMWD16jr9w==", + "dev": true, + "requires": { + "env-paths": "^2.2.0", + "glob": "^7.1.4", + "graceful-fs": "^4.2.6", + "make-fetch-happen": "^9.1.0", + "nopt": "^5.0.0", + "npmlog": "^6.0.0", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.2", + "which": "^2.0.2" + }, + "dependencies": { + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "node-gyp-build": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.4.0.tgz", + "integrity": "sha512-amJnQCcgtRVw9SvoebO3BKGESClrfXGCUTX9hSn1OuGQTQBOZmVd0Z0OlecpuRksKvbsUqALE8jls/ErClAPuQ==", + "dev": true, + "optional": true + }, + "node-releases": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.3.tgz", + "integrity": "sha512-maHFz6OLqYxz+VQyCAtA3PTX4UP/53pa05fyDNc9CwjvJ0yEh6+xBwKsgCxMNhS8taUKBFYxfuiaD9U/55iFaw==", + "dev": true + }, + "nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "dev": true, + "requires": { + "abbrev": "1" + } + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + }, + "normalize-range": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", + "integrity": "sha1-LRDAa9/TEuqXd2laTShDlFa3WUI=", + "dev": true + }, + "npm-bundled": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-1.1.2.tgz", + "integrity": "sha512-x5DHup0SuyQcmL3s7Rx/YQ8sbw/Hzg0rj48eN0dV7hf5cmQq5PXIeioroH3raV1QC1yh3uTYuMThvEQF3iKgGQ==", + "dev": true, + "requires": { + "npm-normalize-package-bin": "^1.0.1" + } + }, + "npm-install-checks": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-4.0.0.tgz", + "integrity": "sha512-09OmyDkNLYwqKPOnbI8exiOZU2GVVmQp7tgez2BPi5OZC8M82elDAps7sxC4l//uSUtotWqoEIDwjRvWH4qz8w==", + "dev": true, + "requires": { + "semver": "^7.1.1" + } + }, + "npm-normalize-package-bin": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-1.0.1.tgz", + "integrity": "sha512-EPfafl6JL5/rU+ot6P3gRSCpPDW5VmIzX959Ob1+ySFUuuYHWHekXpwdUZcKP5C+DS4GEtdJluwBjnsNDl+fSA==", + "dev": true + }, + "npm-package-arg": { + "version": "8.1.5", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-8.1.5.tgz", + "integrity": "sha512-LhgZrg0n0VgvzVdSm1oiZworPbTxYHUJCgtsJW8mGvlDpxTM1vSJc3m5QZeUkhAHIzbz3VCHd/R4osi1L1Tg/Q==", + "dev": true, + "requires": { + "hosted-git-info": "^4.0.1", + "semver": "^7.3.4", + "validate-npm-package-name": "^3.0.0" + } + }, + "npm-packlist": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-3.0.0.tgz", + "integrity": "sha512-L/cbzmutAwII5glUcf2DBRNY/d0TFd4e/FnaZigJV6JD85RHZXJFGwCndjMWiiViiWSsWt3tiOLpI3ByTnIdFQ==", + "dev": true, + "requires": { + "glob": "^7.1.6", + "ignore-walk": "^4.0.1", + "npm-bundled": "^1.1.1", + "npm-normalize-package-bin": "^1.0.1" + } + }, + "npm-pick-manifest": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-6.1.1.tgz", + "integrity": "sha512-dBsdBtORT84S8V8UTad1WlUyKIY9iMsAmqxHbLdeEeBNMLQDlDWWra3wYUx9EBEIiG/YwAy0XyNHDd2goAsfuA==", + "dev": true, + "requires": { + "npm-install-checks": "^4.0.0", + "npm-normalize-package-bin": "^1.0.1", + "npm-package-arg": "^8.1.2", + "semver": "^7.3.4" + } + }, + "npm-registry-fetch": { + "version": "12.0.2", + "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-12.0.2.tgz", + "integrity": "sha512-Df5QT3RaJnXYuOwtXBXS9BWs+tHH2olvkCLh6jcR/b/u3DvPMlp3J0TvvYwplPKxHMOwfg287PYih9QqaVFoKA==", + "dev": true, + "requires": { + "make-fetch-happen": "^10.0.1", + "minipass": "^3.1.6", + "minipass-fetch": "^1.4.1", + "minipass-json-stream": "^1.0.1", + "minizlib": "^2.1.2", + "npm-package-arg": "^8.1.5" + }, + "dependencies": { + "@npmcli/fs": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-2.1.0.tgz", + "integrity": "sha512-DmfBvNXGaetMxj9LTp8NAN9vEidXURrf5ZTslQzEAi/6GbW+4yjaLFQc6Tue5cpZ9Frlk4OBo/Snf1Bh/S7qTQ==", + "dev": true, + "requires": { + "@gar/promisify": "^1.1.3", + "semver": "^7.3.5" + } + }, + "@npmcli/move-file": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/move-file/-/move-file-2.0.0.tgz", + "integrity": "sha512-UR6D5f4KEGWJV6BGPH3Qb2EtgH+t+1XQ1Tt85c7qicN6cezzuHPdZwwAxqZr4JLtnQu0LZsTza/5gmNmSl8XLg==", + "dev": true, + "requires": { + "mkdirp": "^1.0.4", + "rimraf": "^3.0.2" + } + }, + "@tootallnate/once": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", + "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", + "dev": true + }, + "brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0" + } + }, + "cacache": { + "version": "16.0.6", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-16.0.6.tgz", + "integrity": "sha512-9a/MLxGaw3LEGes0HaPez2RgZWDV6X0jrgChsuxfEh8xoDoYGxaGrkMe7Dlyjrb655tA/b8fX0qlUg6Ii5MBvw==", + "dev": true, + "requires": { + "@npmcli/fs": "^2.1.0", + "@npmcli/move-file": "^2.0.0", + "chownr": "^2.0.0", + "fs-minipass": "^2.1.0", + "glob": "^8.0.1", + "infer-owner": "^1.0.4", + "lru-cache": "^7.7.1", + "minipass": "^3.1.6", + "minipass-collect": "^1.0.2", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "mkdirp": "^1.0.4", + "p-map": "^4.0.0", + "promise-inflight": "^1.0.1", + "rimraf": "^3.0.2", + "ssri": "^9.0.0", + "tar": "^6.1.11", + "unique-filename": "^1.1.1" + } + }, + "glob": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/glob/-/glob-8.0.1.tgz", + "integrity": "sha512-cF7FYZZ47YzmCu7dDy50xSRRfO3ErRfrXuLZcNIuyiJEco0XSrGtuilG19L5xp3NcwTx7Gn+X6Tv3fmsUPTbow==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^5.0.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "dev": true, + "requires": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + } + }, + "lru-cache": { + "version": "7.8.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.8.1.tgz", + "integrity": "sha512-E1v547OCgJvbvevfjgK9sNKIVXO96NnsTsFPBlg4ZxjhsJSODoH9lk8Bm0OxvHNm6Vm5Yqkl/1fErDxhYL8Skg==", + "dev": true + }, + "make-fetch-happen": { + "version": "10.1.2", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-10.1.2.tgz", + "integrity": "sha512-GWMGiZsKVeJACQGJ1P3Z+iNec7pLsU6YW1q11eaPn3RR8nRXHppFWfP7Eu0//55JK3hSjrAQRl8sDa5uXpq1Ew==", + "dev": true, + "requires": { + "agentkeepalive": "^4.2.1", + "cacache": "^16.0.2", + "http-cache-semantics": "^4.1.0", + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "is-lambda": "^1.0.1", + "lru-cache": "^7.7.1", + "minipass": "^3.1.6", + "minipass-collect": "^1.0.2", + "minipass-fetch": "^2.0.3", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.3", + "promise-retry": "^2.0.1", + "socks-proxy-agent": "^6.1.1", + "ssri": "^9.0.0" + }, + "dependencies": { + "minipass-fetch": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-2.1.0.tgz", + "integrity": "sha512-H9U4UVBGXEyyWJnqYDCLp1PwD8XIkJ4akNHp1aGVI+2Ym7wQMlxDKi4IB4JbmyU+pl9pEs/cVrK6cOuvmbK4Sg==", + "dev": true, + "requires": { + "encoding": "^0.1.13", + "minipass": "^3.1.6", + "minipass-sized": "^1.0.3", + "minizlib": "^2.1.2" + } + } + } + }, + "minimatch": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz", + "integrity": "sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==", + "dev": true, + "requires": { + "brace-expansion": "^2.0.1" + } + }, + "ssri": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-9.0.0.tgz", + "integrity": "sha512-Y1Z6J8UYnexKFN1R/hxUaYoY2LVdKEzziPmVAFKiKX8fiwvCJTVzn/xYE9TEWod5OVyNfIHHuVfIEuBClL/uJQ==", + "dev": true, + "requires": { + "minipass": "^3.1.1" + } + } + } + }, + "npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "requires": { + "path-key": "^3.0.0" + } + }, + "npmlog": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-6.0.2.tgz", + "integrity": "sha512-/vBvz5Jfr9dT/aFWd0FIRf+T/Q2WBsLENygUaFUqstqsycmZAP/t5BvFJTK0viFmSUxiUKTUplWy5vt+rvKIxg==", + "dev": true, + "requires": { + "are-we-there-yet": "^3.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^4.0.3", + "set-blocking": "^2.0.0" + } + }, + "nth-check": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.0.1.tgz", + "integrity": "sha512-it1vE95zF6dTT9lBsYbxvqh0Soy4SPowchj0UBGj/V6cTPnXXtQOPUbhZ6CmGzAD/rW22LQK6E96pcdJXk4A4w==", + "dev": true, + "requires": { + "boolbase": "^1.0.0" + } + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true + }, + "object-inspect": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.0.tgz", + "integrity": "sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g==", + "dev": true + }, + "object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, + "object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + }, + "obuf": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", + "integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==", + "dev": true + }, + "on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } + }, + "on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "open": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/open/-/open-8.4.0.tgz", + "integrity": "sha512-XgFPPM+B28FtCCgSb9I+s9szOC1vZRSwgWsRUA5ylIxRTgKozqjOCrVOqGsYABPYK5qnfqClxZTFBa8PKt2v6Q==", + "dev": true, + "requires": { + "define-lazy-prop": "^2.0.0", + "is-docker": "^2.1.1", + "is-wsl": "^2.2.0" + } + }, + "ora": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", + "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "dev": true, + "requires": { + "bl": "^4.1.0", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.5.0", + "is-interactive": "^1.0.0", + "is-unicode-supported": "^0.1.0", + "log-symbols": "^4.1.0", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true + }, + "p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "requires": { + "yocto-queue": "^0.1.0" + } + }, + "p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "requires": { + "p-limit": "^2.2.0" + }, + "dependencies": { + "p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + } + } + }, + "p-map": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", + "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", + "dev": true, + "requires": { + "aggregate-error": "^3.0.0" + } + }, + "p-retry": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.1.tgz", + "integrity": "sha512-e2xXGNhZOZ0lfgR9kL34iGlU8N/KO0xZnQxVEwdeOvpqNDQfdnxIYizvWtK8RglUa3bGqI8g0R/BdfzLMxRkiA==", + "dev": true, + "requires": { + "@types/retry": "^0.12.0", + "retry": "^0.13.1" + }, + "dependencies": { + "retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "dev": true + } + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "pacote": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/pacote/-/pacote-12.0.3.tgz", + "integrity": "sha512-CdYEl03JDrRO3x18uHjBYA9TyoW8gy+ThVcypcDkxPtKlw76e4ejhYB6i9lJ+/cebbjpqPW/CijjqxwDTts8Ow==", + "dev": true, + "requires": { + "@npmcli/git": "^2.1.0", + "@npmcli/installed-package-contents": "^1.0.6", + "@npmcli/promise-spawn": "^1.2.0", + "@npmcli/run-script": "^2.0.0", + "cacache": "^15.0.5", + "chownr": "^2.0.0", + "fs-minipass": "^2.1.0", + "infer-owner": "^1.0.4", + "minipass": "^3.1.3", + "mkdirp": "^1.0.3", + "npm-package-arg": "^8.0.1", + "npm-packlist": "^3.0.0", + "npm-pick-manifest": "^6.0.0", + "npm-registry-fetch": "^12.0.0", + "promise-retry": "^2.0.1", + "read-package-json-fast": "^2.0.1", + "rimraf": "^3.0.2", + "ssri": "^8.0.1", + "tar": "^6.1.0" + } + }, + "pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "dev": true + }, + "parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "requires": { + "callsites": "^3.0.0" + } + }, + "parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + } + }, + "parse-node-version": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parse-node-version/-/parse-node-version-1.0.1.tgz", + "integrity": "sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA==", + "dev": true + }, + "parse5": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", + "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==", + "dev": true + }, + "parse5-html-rewriting-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5-html-rewriting-stream/-/parse5-html-rewriting-stream-6.0.1.tgz", + "integrity": "sha512-vwLQzynJVEfUlURxgnf51yAJDQTtVpNyGD8tKi2Za7m+akukNHxCcUQMAa/mUGLhCeicFdpy7Tlvj8ZNKadprg==", + "dev": true, + "requires": { + "parse5": "^6.0.1", + "parse5-sax-parser": "^6.0.1" + } + }, + "parse5-htmlparser2-tree-adapter": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-6.0.1.tgz", + "integrity": "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA==", + "dev": true, + "requires": { + "parse5": "^6.0.1" + } + }, + "parse5-sax-parser": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5-sax-parser/-/parse5-sax-parser-6.0.1.tgz", + "integrity": "sha512-kXX+5S81lgESA0LsDuGjAlBybImAChYRMT+/uKCEXFBFOeEhS52qUCydGhU3qLRD8D9DVjaUo821WK7DM4iCeg==", + "dev": true, + "requires": { + "parse5": "^6.0.1" + } + }, + "parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true + }, + "path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=", + "dev": true + }, + "path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true + }, + "picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "dev": true + }, + "picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true + }, + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + }, + "piscina": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/piscina/-/piscina-3.2.0.tgz", + "integrity": "sha512-yn/jMdHRw+q2ZJhFhyqsmANcbF6V2QwmD84c6xRau+QpQOmtrBCoRGdvTfeuFDYXB5W2m6MfLkjkvQa9lUSmIA==", + "dev": true, + "requires": { + "eventemitter-asyncresource": "^1.0.0", + "hdr-histogram-js": "^2.0.1", + "hdr-histogram-percentiles-obj": "^3.0.0", + "nice-napi": "^1.0.2" + } + }, + "pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "requires": { + "find-up": "^4.0.0" + } + }, + "portfinder": { + "version": "1.0.28", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.28.tgz", + "integrity": "sha512-Se+2isanIcEqf2XMHjyUKskczxbPH7dQnlMjXX6+dybayyHvAf/TCgyMRlzf/B6QDhAEFOGes0pzRo3by4AbMA==", + "dev": true, + "requires": { + "async": "^2.6.2", + "debug": "^3.1.1", + "mkdirp": "^0.5.5" + }, + "dependencies": { + "debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "requires": { + "minimist": "^1.2.6" + } + } + } + }, + "postcss": { + "version": "8.4.5", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.5.tgz", + "integrity": "sha512-jBDboWM8qpaqwkMwItqTQTiFikhs/67OYVvblFFTM7MrZjt6yMKd6r2kgXizEbTTljacm4NldIlZnhbjr84QYg==", + "dev": true, + "requires": { + "nanoid": "^3.1.30", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.1" + } + }, + "postcss-attribute-case-insensitive": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/postcss-attribute-case-insensitive/-/postcss-attribute-case-insensitive-5.0.0.tgz", + "integrity": "sha512-b4g9eagFGq9T5SWX4+USfVyjIb3liPnjhHHRMP7FMB2kFVpYyfEscV0wP3eaXhKlcHKUut8lt5BGoeylWA/dBQ==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.2" + } + }, + "postcss-color-functional-notation": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/postcss-color-functional-notation/-/postcss-color-functional-notation-4.2.2.tgz", + "integrity": "sha512-DXVtwUhIk4f49KK5EGuEdgx4Gnyj6+t2jBSEmxvpIK9QI40tWrpS2Pua8Q7iIZWBrki2QOaeUdEaLPPa91K0RQ==", + "dev": true, + "requires": { + "postcss-value-parser": "^4.2.0" + } + }, + "postcss-color-hex-alpha": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/postcss-color-hex-alpha/-/postcss-color-hex-alpha-8.0.3.tgz", + "integrity": "sha512-fESawWJCrBV035DcbKRPAVmy21LpoyiXdPTuHUfWJ14ZRjY7Y7PA6P4g8z6LQGYhU1WAxkTxjIjurXzoe68Glw==", + "dev": true, + "requires": { + "postcss-value-parser": "^4.2.0" + } + }, + "postcss-color-rebeccapurple": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/postcss-color-rebeccapurple/-/postcss-color-rebeccapurple-7.0.2.tgz", + "integrity": "sha512-SFc3MaocHaQ6k3oZaFwH8io6MdypkUtEy/eXzXEB1vEQlO3S3oDc/FSZA8AsS04Z25RirQhlDlHLh3dn7XewWw==", + "dev": true, + "requires": { + "postcss-value-parser": "^4.2.0" + } + }, + "postcss-custom-media": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/postcss-custom-media/-/postcss-custom-media-8.0.0.tgz", + "integrity": "sha512-FvO2GzMUaTN0t1fBULDeIvxr5IvbDXcIatt6pnJghc736nqNgsGao5NT+5+WVLAQiTt6Cb3YUms0jiPaXhL//g==", + "dev": true, + "requires": {} + }, + "postcss-custom-properties": { + "version": "12.1.7", + "resolved": "https://registry.npmjs.org/postcss-custom-properties/-/postcss-custom-properties-12.1.7.tgz", + "integrity": "sha512-N/hYP5gSoFhaqxi2DPCmvto/ZcRDVjE3T1LiAMzc/bg53hvhcHOLpXOHb526LzBBp5ZlAUhkuot/bfpmpgStJg==", + "dev": true, + "requires": { + "postcss-value-parser": "^4.2.0" + } + }, + "postcss-custom-selectors": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/postcss-custom-selectors/-/postcss-custom-selectors-6.0.0.tgz", + "integrity": "sha512-/1iyBhz/W8jUepjGyu7V1OPcGbc636snN1yXEQCinb6Bwt7KxsiU7/bLQlp8GwAXzCh7cobBU5odNn/2zQWR8Q==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.4" + } + }, + "postcss-dir-pseudo-class": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/postcss-dir-pseudo-class/-/postcss-dir-pseudo-class-6.0.4.tgz", + "integrity": "sha512-I8epwGy5ftdzNWEYok9VjW9whC4xnelAtbajGv4adql4FIF09rnrxnA9Y8xSHN47y7gqFIv10C5+ImsLeJpKBw==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.9" + } + }, + "postcss-double-position-gradients": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/postcss-double-position-gradients/-/postcss-double-position-gradients-3.1.1.tgz", + "integrity": "sha512-jM+CGkTs4FcG53sMPjrrGE0rIvLDdCrqMzgDC5fLI7JHDO7o6QG8C5TQBtExb13hdBdoH9C2QVbG4jo2y9lErQ==", + "dev": true, + "requires": { + "@csstools/postcss-progressive-custom-properties": "^1.1.0", + "postcss-value-parser": "^4.2.0" + } + }, + "postcss-env-function": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/postcss-env-function/-/postcss-env-function-4.0.6.tgz", + "integrity": "sha512-kpA6FsLra+NqcFnL81TnsU+Z7orGtDTxcOhl6pwXeEq1yFPpRMkCDpHhrz8CFQDr/Wfm0jLiNQ1OsGGPjlqPwA==", + "dev": true, + "requires": { + "postcss-value-parser": "^4.2.0" + } + }, + "postcss-focus-visible": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/postcss-focus-visible/-/postcss-focus-visible-6.0.4.tgz", + "integrity": "sha512-QcKuUU/dgNsstIK6HELFRT5Y3lbrMLEOwG+A4s5cA+fx3A3y/JTq3X9LaOj3OC3ALH0XqyrgQIgey/MIZ8Wczw==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.9" + } + }, + "postcss-focus-within": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/postcss-focus-within/-/postcss-focus-within-5.0.4.tgz", + "integrity": "sha512-vvjDN++C0mu8jz4af5d52CB184ogg/sSxAFS+oUJQq2SuCe7T5U2iIsVJtsCp2d6R4j0jr5+q3rPkBVZkXD9fQ==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.9" + } + }, + "postcss-font-variant": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/postcss-font-variant/-/postcss-font-variant-5.0.0.tgz", + "integrity": "sha512-1fmkBaCALD72CK2a9i468mA/+tr9/1cBxRRMXOUaZqO43oWPR5imcyPjXwuv7PXbCid4ndlP5zWhidQVVa3hmA==", + "dev": true, + "requires": {} + }, + "postcss-gap-properties": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/postcss-gap-properties/-/postcss-gap-properties-3.0.3.tgz", + "integrity": "sha512-rPPZRLPmEKgLk/KlXMqRaNkYTUpE7YC+bOIQFN5xcu1Vp11Y4faIXv6/Jpft6FMnl6YRxZqDZG0qQOW80stzxQ==", + "dev": true, + "requires": {} + }, + "postcss-image-set-function": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/postcss-image-set-function/-/postcss-image-set-function-4.0.6.tgz", + "integrity": "sha512-KfdC6vg53GC+vPd2+HYzsZ6obmPqOk6HY09kttU19+Gj1nC3S3XBVEXDHxkhxTohgZqzbUb94bKXvKDnYWBm/A==", + "dev": true, + "requires": { + "postcss-value-parser": "^4.2.0" + } + }, + "postcss-import": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-14.0.2.tgz", + "integrity": "sha512-BJ2pVK4KhUyMcqjuKs9RijV5tatNzNa73e/32aBVE/ejYPe37iH+6vAu9WvqUkB5OAYgLHzbSvzHnorybJCm9g==", + "dev": true, + "requires": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + } + }, + "postcss-initial": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/postcss-initial/-/postcss-initial-4.0.1.tgz", + "integrity": "sha512-0ueD7rPqX8Pn1xJIjay0AZeIuDoF+V+VvMt/uOnn+4ezUKhZM/NokDeP6DwMNyIoYByuN/94IQnt5FEkaN59xQ==", + "dev": true, + "requires": {} + }, + "postcss-lab-function": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-lab-function/-/postcss-lab-function-4.2.0.tgz", + "integrity": "sha512-Zb1EO9DGYfa3CP8LhINHCcTTCTLI+R3t7AX2mKsDzdgVQ/GkCpHOTgOr6HBHslP7XDdVbqgHW5vvRPMdVANQ8w==", + "dev": true, + "requires": { + "@csstools/postcss-progressive-custom-properties": "^1.1.0", + "postcss-value-parser": "^4.2.0" + } + }, + "postcss-loader": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/postcss-loader/-/postcss-loader-6.2.1.tgz", + "integrity": "sha512-WbbYpmAaKcux/P66bZ40bpWsBucjx/TTgVVzRZ9yUO8yQfVBlameJ0ZGVaPfH64hNSBh63a+ICP5nqOpBA0w+Q==", + "dev": true, + "requires": { + "cosmiconfig": "^7.0.0", + "klona": "^2.0.5", + "semver": "^7.3.5" + } + }, + "postcss-logical": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/postcss-logical/-/postcss-logical-5.0.4.tgz", + "integrity": "sha512-RHXxplCeLh9VjinvMrZONq7im4wjWGlRJAqmAVLXyZaXwfDWP73/oq4NdIp+OZwhQUMj0zjqDfM5Fj7qby+B4g==", + "dev": true, + "requires": {} + }, + "postcss-media-minmax": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/postcss-media-minmax/-/postcss-media-minmax-5.0.0.tgz", + "integrity": "sha512-yDUvFf9QdFZTuCUg0g0uNSHVlJ5X1lSzDZjPSFaiCWvjgsvu8vEVxtahPrLMinIDEEGnx6cBe6iqdx5YWz08wQ==", + "dev": true, + "requires": {} + }, + "postcss-modules-extract-imports": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.0.0.tgz", + "integrity": "sha512-bdHleFnP3kZ4NYDhuGlVK+CMrQ/pqUm8bx/oGL93K6gVwiclvX5x0n76fYMKuIGKzlABOy13zsvqjb0f92TEXw==", + "dev": true, + "requires": {} + }, + "postcss-modules-local-by-default": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.0.0.tgz", + "integrity": "sha512-sT7ihtmGSF9yhm6ggikHdV0hlziDTX7oFoXtuVWeDd3hHObNkcHRo9V3yg7vCAY7cONyxJC/XXCmmiHHcvX7bQ==", + "dev": true, + "requires": { + "icss-utils": "^5.0.0", + "postcss-selector-parser": "^6.0.2", + "postcss-value-parser": "^4.1.0" + } + }, + "postcss-modules-scope": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-3.0.0.tgz", + "integrity": "sha512-hncihwFA2yPath8oZ15PZqvWGkWf+XUfQgUGamS4LqoP1anQLOsOJw0vr7J7IwLpoY9fatA2qiGUGmuZL0Iqlg==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.4" + } + }, + "postcss-modules-values": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz", + "integrity": "sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ==", + "dev": true, + "requires": { + "icss-utils": "^5.0.0" + } + }, + "postcss-nesting": { + "version": "10.1.4", + "resolved": "https://registry.npmjs.org/postcss-nesting/-/postcss-nesting-10.1.4.tgz", + "integrity": "sha512-2ixdQ59ik/Gt1+oPHiI1kHdwEI8lLKEmui9B1nl6163ANLC+GewQn7fXMxJF2JSb4i2MKL96GU8fIiQztK4TTA==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.10" + } + }, + "postcss-overflow-shorthand": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/postcss-overflow-shorthand/-/postcss-overflow-shorthand-3.0.3.tgz", + "integrity": "sha512-CxZwoWup9KXzQeeIxtgOciQ00tDtnylYIlJBBODqkgS/PU2jISuWOL/mYLHmZb9ZhZiCaNKsCRiLp22dZUtNsg==", + "dev": true, + "requires": {} + }, + "postcss-page-break": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/postcss-page-break/-/postcss-page-break-3.0.4.tgz", + "integrity": "sha512-1JGu8oCjVXLa9q9rFTo4MbeeA5FMe00/9C7lN4va606Rdb+HkxXtXsmEDrIraQ11fGz/WvKWa8gMuCKkrXpTsQ==", + "dev": true, + "requires": {} + }, + "postcss-place": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/postcss-place/-/postcss-place-7.0.4.tgz", + "integrity": "sha512-MrgKeiiu5OC/TETQO45kV3npRjOFxEHthsqGtkh3I1rPbZSbXGD/lZVi9j13cYh+NA8PIAPyk6sGjT9QbRyvSg==", + "dev": true, + "requires": { + "postcss-value-parser": "^4.2.0" + } + }, + "postcss-preset-env": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/postcss-preset-env/-/postcss-preset-env-7.2.3.tgz", + "integrity": "sha512-Ok0DhLfwrcNGrBn8sNdy1uZqWRk/9FId0GiQ39W4ILop5GHtjJs8bu1MY9isPwHInpVEPWjb4CEcEaSbBLpfwA==", + "dev": true, + "requires": { + "autoprefixer": "^10.4.2", + "browserslist": "^4.19.1", + "caniuse-lite": "^1.0.30001299", + "css-blank-pseudo": "^3.0.2", + "css-has-pseudo": "^3.0.3", + "css-prefers-color-scheme": "^6.0.2", + "cssdb": "^5.0.0", + "postcss-attribute-case-insensitive": "^5.0.0", + "postcss-color-functional-notation": "^4.2.1", + "postcss-color-hex-alpha": "^8.0.2", + "postcss-color-rebeccapurple": "^7.0.2", + "postcss-custom-media": "^8.0.0", + "postcss-custom-properties": "^12.1.2", + "postcss-custom-selectors": "^6.0.0", + "postcss-dir-pseudo-class": "^6.0.3", + "postcss-double-position-gradients": "^3.0.4", + "postcss-env-function": "^4.0.4", + "postcss-focus-visible": "^6.0.3", + "postcss-focus-within": "^5.0.3", + "postcss-font-variant": "^5.0.0", + "postcss-gap-properties": "^3.0.2", + "postcss-image-set-function": "^4.0.4", + "postcss-initial": "^4.0.1", + "postcss-lab-function": "^4.0.3", + "postcss-logical": "^5.0.3", + "postcss-media-minmax": "^5.0.0", + "postcss-nesting": "^10.1.2", + "postcss-overflow-shorthand": "^3.0.2", + "postcss-page-break": "^3.0.4", + "postcss-place": "^7.0.3", + "postcss-pseudo-class-any-link": "^7.0.2", + "postcss-replace-overflow-wrap": "^4.0.0", + "postcss-selector-not": "^5.0.0" + } + }, + "postcss-pseudo-class-any-link": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/postcss-pseudo-class-any-link/-/postcss-pseudo-class-any-link-7.1.2.tgz", + "integrity": "sha512-76XzEQv3g+Vgnz3tmqh3pqQyRojkcJ+pjaePsyhcyf164p9aZsu3t+NWxkZYbcHLK1ju5Qmalti2jPI5IWCe5w==", + "dev": true, + "requires": { + "postcss-selector-parser": "^6.0.10" + } + }, + "postcss-replace-overflow-wrap": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/postcss-replace-overflow-wrap/-/postcss-replace-overflow-wrap-4.0.0.tgz", + "integrity": "sha512-KmF7SBPphT4gPPcKZc7aDkweHiKEEO8cla/GjcBK+ckKxiZslIu3C4GCRW3DNfL0o7yW7kMQu9xlZ1kXRXLXtw==", + "dev": true, + "requires": {} + }, + "postcss-selector-not": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/postcss-selector-not/-/postcss-selector-not-5.0.0.tgz", + "integrity": "sha512-/2K3A4TCP9orP4TNS7u3tGdRFVKqz/E6pX3aGnriPG0jU78of8wsUcqE4QAhWEU0d+WnMSF93Ah3F//vUtK+iQ==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0" + } + }, + "postcss-selector-parser": { + "version": "6.0.10", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", + "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==", + "dev": true, + "requires": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + } + }, + "postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true + }, + "pretty-bytes": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-5.6.0.tgz", + "integrity": "sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg==", + "dev": true + }, + "process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true + }, + "promise-inflight": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", + "integrity": "sha1-mEcocL8igTL8vdhoEputEsPAKeM=", + "dev": true + }, + "promise-retry": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz", + "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==", + "dev": true, + "requires": { + "err-code": "^2.0.2", + "retry": "^0.12.0" + } + }, + "proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dev": true, + "requires": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "dependencies": { + "ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true + } + } + }, + "prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", + "dev": true, + "optional": true + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true + }, + "qjobs": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/qjobs/-/qjobs-1.2.0.tgz", + "integrity": "sha512-8YOJEHtxpySA3fFDyCRxA+UUV+fA+rTWnuWvylOK/NCjhY+b4ocCtmu8TtsWb+mYeU+GCHf/S66KZF/AsteKHg==", + "dev": true + }, + "qs": { + "version": "6.10.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.10.3.tgz", + "integrity": "sha512-wr7M2E0OFRfIfJZjKGieI8lBKb7fRCH4Fv5KNPEs7gJ8jadvotdsS08PzOKR7opXhZ/Xkjtt3WF9g38drmyRqQ==", + "dev": true, + "requires": { + "side-channel": "^1.0.4" + } + }, + "queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true + }, + "randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "requires": { + "safe-buffer": "^5.1.0" + } + }, + "range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "dev": true + }, + "raw-body": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", + "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "dev": true, + "requires": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + } + }, + "read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha1-5mTvMRYRZsl1HNvo28+GtftY93Q=", + "dev": true, + "requires": { + "pify": "^2.3.0" + } + }, + "read-package-json-fast": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/read-package-json-fast/-/read-package-json-fast-2.0.3.tgz", + "integrity": "sha512-W/BKtbL+dUjTuRL2vziuYhp76s5HZ9qQhd/dKfWIZveD0O40453QNyZhC0e63lqZrAQ4jiOapVoeJ7JrszenQQ==", + "dev": true, + "requires": { + "json-parse-even-better-errors": "^2.3.0", + "npm-normalize-package-bin": "^1.0.1" + } + }, + "readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "dev": true, + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, + "readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "requires": { + "picomatch": "^2.2.1" + } + }, + "reflect-metadata": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", + "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==", + "dev": true + }, + "regenerate": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz", + "integrity": "sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A==", + "dev": true + }, + "regenerate-unicode-properties": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.0.1.tgz", + "integrity": "sha512-vn5DU6yg6h8hP/2OkQo3K7uVILvY4iu0oI4t3HFa81UPkhGJwkRwM10JEc3upjdhHjs/k8GJY1sRBhk5sr69Bw==", + "dev": true, + "requires": { + "regenerate": "^1.4.2" + } + }, + "regenerator-runtime": { + "version": "0.13.9", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==", + "dev": true + }, + "regenerator-transform": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.15.0.tgz", + "integrity": "sha512-LsrGtPmbYg19bcPHwdtmXwbW+TqNvtY4riE3P83foeHRroMbH6/2ddFBfab3t7kbzc7v7p4wbkIecHImqt0QNg==", + "dev": true, + "requires": { + "@babel/runtime": "^7.8.4" + } + }, + "regex-parser": { + "version": "2.2.11", + "resolved": "https://registry.npmjs.org/regex-parser/-/regex-parser-2.2.11.tgz", + "integrity": "sha512-jbD/FT0+9MBU2XAZluI7w2OBs1RBi6p9M83nkoZayQXXU9e8Robt69FcZc7wU4eJD/YFTjn1JdCk3rbMJajz8Q==", + "dev": true + }, + "regexp.prototype.flags": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.4.3.tgz", + "integrity": "sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3", + "functions-have-names": "^1.2.2" + } + }, + "regexpu-core": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-5.0.1.tgz", + "integrity": "sha512-CriEZlrKK9VJw/xQGJpQM5rY88BtuL8DM+AEwvcThHilbxiTAy8vq4iJnd2tqq8wLmjbGZzP7ZcKFjbGkmEFrw==", + "dev": true, + "requires": { + "regenerate": "^1.4.2", + "regenerate-unicode-properties": "^10.0.1", + "regjsgen": "^0.6.0", + "regjsparser": "^0.8.2", + "unicode-match-property-ecmascript": "^2.0.0", + "unicode-match-property-value-ecmascript": "^2.0.0" + } + }, + "regjsgen": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.6.0.tgz", + "integrity": "sha512-ozE883Uigtqj3bx7OhL1KNbCzGyW2NQZPl6Hs09WTvCuZD5sTI4JY58bkbQWa/Y9hxIsvJ3M8Nbf7j54IqeZbA==", + "dev": true + }, + "regjsparser": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.8.4.tgz", + "integrity": "sha512-J3LABycON/VNEu3abOviqGHuB/LOtOQj8SKmfP9anY5GfAVw/SPjwzSjxGjbZXIxbGfqTHtJw58C2Li/WkStmA==", + "dev": true, + "requires": { + "jsesc": "~0.5.0" + }, + "dependencies": { + "jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", + "dev": true + } + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "dev": true + }, + "require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true + }, + "requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", + "dev": true + }, + "resolve": { + "version": "1.22.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.0.tgz", + "integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==", + "dev": true, + "requires": { + "is-core-module": "^2.8.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + } + }, + "resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true + }, + "resolve-url-loader": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-url-loader/-/resolve-url-loader-5.0.0.tgz", + "integrity": "sha512-uZtduh8/8srhBoMx//5bwqjQ+rfYOUq8zC9NrMUGtjBiGTtFJM42s58/36+hTqeqINcnYe08Nj3LkK9lW4N8Xg==", + "dev": true, + "requires": { + "adjust-sourcemap-loader": "^4.0.0", + "convert-source-map": "^1.7.0", + "loader-utils": "^2.0.0", + "postcss": "^8.2.14", + "source-map": "0.6.1" + }, + "dependencies": { + "loader-utils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.2.tgz", + "integrity": "sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A==", + "dev": true, + "requires": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^2.1.2" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "requires": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + } + }, + "retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha1-G0KmJmoh8HQh0bC1S33BZ7AcATs=", + "dev": true + }, + "reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "dev": true + }, + "rfdc": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.0.tgz", + "integrity": "sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA==", + "dev": true + }, + "rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true + }, + "run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "requires": { + "queue-microtask": "^1.2.2" + } + }, + "rxjs": { + "version": "6.6.7", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", + "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", + "requires": { + "tslib": "^1.9.0" + }, + "dependencies": { + "tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==" + } + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "sass": { + "version": "1.49.9", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.49.9.tgz", + "integrity": "sha512-YlYWkkHP9fbwaFRZQRXgDi3mXZShslVmmo+FVK3kHLUELHHEYrCmL1x6IUjC7wLS6VuJSAFXRQS/DxdsC4xL1A==", + "dev": true, + "requires": { + "chokidar": ">=3.0.0 <4.0.0", + "immutable": "^4.0.0", + "source-map-js": ">=0.6.2 <2.0.0" + } + }, + "sass-loader": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-12.4.0.tgz", + "integrity": "sha512-7xN+8khDIzym1oL9XyS6zP6Ges+Bo2B2xbPrjdMHEYyV3AQYhd/wXeru++3ODHF0zMjYmVadblSKrPrjEkL8mg==", + "dev": true, + "requires": { + "klona": "^2.0.4", + "neo-async": "^2.6.2" + } + }, + "sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", + "dev": true + }, + "schema-utils": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-2.7.1.tgz", + "integrity": "sha512-SHiNtMOUGWBQJwzISiVYKu82GiV4QYGePp3odlY1tuKO7gPtphAT5R/py0fA6xtbgLL/RvtJZnU9b8s0F1q0Xg==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.5", + "ajv": "^6.12.4", + "ajv-keywords": "^3.5.2" + } + }, + "select-hose": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", + "integrity": "sha1-Yl2GWPhlr0Psliv8N2o3NZpJlMo=", + "dev": true + }, + "selfsigned": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-2.0.1.tgz", + "integrity": "sha512-LmME957M1zOsUhG+67rAjKfiWFox3SBxE/yymatMZsAx+oMrJ0YQ8AToOnyCm7xbeg2ep37IHLxdu0o2MavQOQ==", + "dev": true, + "requires": { + "node-forge": "^1" + } + }, + "semver": { + "version": "7.3.7", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", + "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", + "dev": true, + "requires": { + "lru-cache": "^6.0.0" + } + }, + "semver-dsl": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/semver-dsl/-/semver-dsl-1.0.1.tgz", + "integrity": "sha1-02eN5VVeimH2Ke7QJTZq5fJzQKA=", + "dev": true, + "requires": { + "semver": "^5.3.0" + }, + "dependencies": { + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true + } + } + }, + "send": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "dev": true, + "requires": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } + } + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true + }, + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } + }, + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "dev": true + } + } + }, + "serialize-javascript": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz", + "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", + "dev": true, + "requires": { + "randombytes": "^2.1.0" + } + }, + "serve-index": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz", + "integrity": "sha1-03aNabHn2C5c4FD/9bRTvqEqkjk=", + "dev": true, + "requires": { + "accepts": "~1.3.4", + "batch": "0.6.1", + "debug": "2.6.9", + "escape-html": "~1.0.3", + "http-errors": "~1.6.2", + "mime-types": "~2.1.17", + "parseurl": "~1.3.2" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "http-errors": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", + "integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=", + "dev": true, + "requires": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "setprototypeof": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", + "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "dev": true + } + } + }, + "serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "dev": true, + "requires": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + } + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", + "dev": true + }, + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true + }, + "shallow-clone": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", + "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", + "dev": true, + "requires": { + "kind-of": "^6.0.2" + } + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + } + }, + "signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true + }, + "slash": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-4.0.0.tgz", + "integrity": "sha512-3dOsAHXXUkQTpOYcoAxLIorMTp4gIQr5IW3iVb7A7lFIp0VHhnynm9izx6TssdrIcVIESAlVjtnO2K8bg+Coew==", + "dev": true + }, + "smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "dev": true + }, + "socket.io": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.4.1.tgz", + "integrity": "sha512-s04vrBswdQBUmuWJuuNTmXUVJhP0cVky8bBDhdkf8y0Ptsu7fKU2LuLbts9g+pdmAdyMMn8F/9Mf1/wbtUN0fg==", + "dev": true, + "requires": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "debug": "~4.3.2", + "engine.io": "~6.1.0", + "socket.io-adapter": "~2.3.3", + "socket.io-parser": "~4.0.4" + } + }, + "socket.io-adapter": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.3.3.tgz", + "integrity": "sha512-Qd/iwn3VskrpNO60BeRyCyr8ZWw9CPZyitW4AQwmRZ8zCiyDiL+znRnWX6tDHXnWn1sJrM1+b6Mn6wEDJJ4aYQ==", + "dev": true + }, + "socket.io-parser": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.0.4.tgz", + "integrity": "sha512-t+b0SS+IxG7Rxzda2EVvyBZbvFPBCjJoyHuE0P//7OAsN23GItzDRdWa6ALxZI/8R5ygK7jAR6t028/z+7295g==", + "dev": true, + "requires": { + "@types/component-emitter": "^1.2.10", + "component-emitter": "~1.3.0", + "debug": "~4.3.1" + } + }, + "sockjs": { + "version": "0.3.24", + "resolved": "https://registry.npmjs.org/sockjs/-/sockjs-0.3.24.tgz", + "integrity": "sha512-GJgLTZ7vYb/JtPSSZ10hsOYIvEYsjbNU+zPdIHcUaWVNUEPivzxku31865sSSud0Da0W4lEeOPlmw93zLQchuQ==", + "dev": true, + "requires": { + "faye-websocket": "^0.11.3", + "uuid": "^8.3.2", + "websocket-driver": "^0.7.4" + } + }, + "socks": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.6.2.tgz", + "integrity": "sha512-zDZhHhZRY9PxRruRMR7kMhnf3I8hDs4S3f9RecfnGxvcBHQcKcIH/oUcEWffsfl1XxdYlA7nnlGbbTvPz9D8gA==", + "dev": true, + "requires": { + "ip": "^1.1.5", + "smart-buffer": "^4.2.0" + } + }, + "socks-proxy-agent": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-6.2.0.tgz", + "integrity": "sha512-wWqJhjb32Q6GsrUqzuFkukxb/zzide5quXYcMVpIjxalDBBYy2nqKCFQ/9+Ie4dvOYSQdOk3hUlZSdzZOd3zMQ==", + "dev": true, + "requires": { + "agent-base": "^6.0.2", + "debug": "^4.3.3", + "socks": "^2.6.2" + } + }, + "source-map": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true + }, + "source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "dev": true + }, + "source-map-loader": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/source-map-loader/-/source-map-loader-3.0.1.tgz", + "integrity": "sha512-Vp1UsfyPvgujKQzi4pyDiTOnE3E4H+yHvkVRN3c/9PJmQS4CQJExvcDvaX/D+RV+xQben9HJ56jMJS3CgUeWyA==", + "dev": true, + "requires": { + "abab": "^2.0.5", + "iconv-lite": "^0.6.3", + "source-map-js": "^1.0.1" + }, + "dependencies": { + "iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + } + } + } + }, + "source-map-resolve": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.6.0.tgz", + "integrity": "sha512-KXBr9d/fO/bWo97NXsPIAW1bFSBOuCnjbNTBMO7N59hsv5i9yzRDfcYwwt0l04+VqnKC+EwzvJZIP/qkuMgR/w==", + "dev": true, + "requires": { + "atob": "^2.1.2", + "decode-uri-component": "^0.2.0" + } + }, + "source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "dev": true + }, + "spdy": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/spdy/-/spdy-4.0.2.tgz", + "integrity": "sha512-r46gZQZQV+Kl9oItvl1JZZqJKGr+oEkB08A6BzkiR7593/7IbtuncXHd2YoYeTsG4157ZssMu9KYvUHLcjcDoA==", + "dev": true, + "requires": { + "debug": "^4.1.0", + "handle-thing": "^2.0.0", + "http-deceiver": "^1.2.7", + "select-hose": "^2.0.0", + "spdy-transport": "^3.0.0" + } + }, + "spdy-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdy-transport/-/spdy-transport-3.0.0.tgz", + "integrity": "sha512-hsLVFE5SjA6TCisWeJXFKniGGOpBgMLmerfO2aCyCU5s7nJ/rpAepqmFifv/GCbSbueEeAJJnmSQ2rKC/g8Fcw==", + "dev": true, + "requires": { + "debug": "^4.1.0", + "detect-node": "^2.0.4", + "hpack.js": "^2.1.6", + "obuf": "^1.1.2", + "readable-stream": "^3.0.6", + "wbuf": "^1.7.3" + } + }, + "sprintf-js": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.2.tgz", + "integrity": "sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug==", + "dev": true + }, + "ssri": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-8.0.1.tgz", + "integrity": "sha512-97qShzy1AiyxvPNIkLWoGua7xoQzzPjQ0HAH4B0rWKo7SZ6USuPcrUiAFrws0UH8RrbWmgq3LMTObhPIHbbBeQ==", + "dev": true, + "requires": { + "minipass": "^3.1.1" + } + }, + "statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "dev": true + }, + "streamroller": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/streamroller/-/streamroller-3.0.2.tgz", + "integrity": "sha512-ur6y5S5dopOaRXBuRIZ1u6GC5bcEXHRZKgfBjfCglMhmIf+roVCECjvkEYzNQOXIN2/JPnkMPW/8B3CZoKaEPA==", + "dev": true, + "requires": { + "date-format": "^4.0.3", + "debug": "^4.1.1", + "fs-extra": "^10.0.0" + }, + "dependencies": { + "fs-extra": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.0.1.tgz", + "integrity": "sha512-NbdoVMZso2Lsrn/QwLXOy6rm0ufY2zEOKCDzJR/0kBsb0E6qed0P3iYK+Ath3BfvXEeu4JhEtXLgILx5psUfag==", + "dev": true, + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + } + }, + "jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.6", + "universalify": "^2.0.0" + } + }, + "universalify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==", + "dev": true + } + } + }, + "string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "requires": { + "safe-buffer": "~5.2.0" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true + } + } + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.1" + } + }, + "strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true + }, + "stylus": { + "version": "0.56.0", + "resolved": "https://registry.npmjs.org/stylus/-/stylus-0.56.0.tgz", + "integrity": "sha512-Ev3fOb4bUElwWu4F9P9WjnnaSpc8XB9OFHSFZSKMFL1CE1oM+oFXWEgAqPmmZIyhBihuqIQlFsVTypiiS9RxeA==", + "dev": true, + "requires": { + "css": "^3.0.0", + "debug": "^4.3.2", + "glob": "^7.1.6", + "safer-buffer": "^2.1.2", + "sax": "~1.2.4", + "source-map": "^0.7.3" + } + }, + "stylus-loader": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/stylus-loader/-/stylus-loader-6.2.0.tgz", + "integrity": "sha512-5dsDc7qVQGRoc6pvCL20eYgRUxepZ9FpeK28XhdXaIPP6kXr6nI1zAAKFQgP5OBkOfKaURp4WUpJzspg1f01Gg==", + "dev": true, + "requires": { + "fast-glob": "^3.2.7", + "klona": "^2.0.4", + "normalize-path": "^3.0.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true + }, + "symbol-observable": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-4.0.0.tgz", + "integrity": "sha512-b19dMThMV4HVFynSAM1++gBHAbk2Tc/osgLIBZMKsyqh34jb2e8Os7T6ZW/Bt3pJFdBTd2JwAnAAEQV7rSNvcQ==", + "dev": true + }, + "tapable": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", + "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", + "dev": true + }, + "tar": { + "version": "6.1.11", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.11.tgz", + "integrity": "sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA==", + "dev": true, + "requires": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^3.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + } + }, + "terser": { + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.11.0.tgz", + "integrity": "sha512-uCA9DLanzzWSsN1UirKwylhhRz3aKPInlfmpGfw8VN6jHsAtu8HJtIpeeHHK23rxnE/cDc+yvmq5wqkIC6Kn0A==", + "dev": true, + "requires": { + "acorn": "^8.5.0", + "commander": "^2.20.0", + "source-map": "~0.7.2", + "source-map-support": "~0.5.20" + } + }, + "terser-webpack-plugin": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.1.4.tgz", + "integrity": "sha512-C2WkFwstHDhVEmsmlCxrXUtVklS+Ir1A7twrYzrDrQQOIMOaVAYykaoo/Aq1K0QRkMoY2hhvDQY1cm4jnIMFwA==", + "dev": true, + "requires": { + "jest-worker": "^27.0.2", + "p-limit": "^3.1.0", + "schema-utils": "^3.0.0", + "serialize-javascript": "^6.0.0", + "source-map": "^0.6.1", + "terser": "^5.7.0" + }, + "dependencies": { + "schema-utils": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.1.1.tgz", + "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "requires": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + } + }, + "text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, + "thunky": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", + "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==", + "dev": true + }, + "tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.2" + } + }, + "to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "dev": true + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "requires": { + "is-number": "^7.0.0" + } + }, + "toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true + }, + "tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true + }, + "ts-node": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-7.0.1.tgz", + "integrity": "sha512-BVwVbPJRspzNh2yfslyT1PSbl5uIk03EZlb493RKHN4qej/D06n1cEhjlOJG69oFsE7OT8XjpTUcYf6pKTLMhw==", + "dev": true, + "requires": { + "arrify": "^1.0.0", + "buffer-from": "^1.1.0", + "diff": "^3.1.0", + "make-error": "^1.1.1", + "minimist": "^1.2.0", + "mkdirp": "^0.5.1", + "source-map-support": "^0.5.6", + "yn": "^2.0.0" + }, + "dependencies": { + "mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "dev": true, + "requires": { + "minimist": "^1.2.5" + } + } + } + }, + "tslib": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" + }, + "tslint": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-6.1.3.tgz", + "integrity": "sha512-IbR4nkT96EQOvKE2PW/djGz8iGNeJ4rF2mBfiYaR/nvUWYKJhLwimoJKgjIFEIDibBtOevj7BqCRL4oHeWWUCg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "builtin-modules": "^1.1.1", + "chalk": "^2.3.0", + "commander": "^2.12.1", + "diff": "^4.0.1", + "glob": "^7.1.1", + "js-yaml": "^3.13.1", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.3", + "resolve": "^1.3.2", + "semver": "^5.3.0", + "tslib": "^1.13.0", + "tsutils": "^2.29.0" + }, + "dependencies": { + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true + }, + "mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "dev": true, + "requires": { + "minimist": "^1.2.5" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "dev": true + }, + "tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "dev": true + }, + "tsutils": { + "version": "2.29.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz", + "integrity": "sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==", + "dev": true, + "requires": { + "tslib": "^1.8.1" + } + } + } + }, + "type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true + }, + "type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dev": true, + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + } + }, + "typed-assert": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/typed-assert/-/typed-assert-1.0.9.tgz", + "integrity": "sha512-KNNZtayBCtmnNmbo5mG47p1XsCyrx6iVqomjcZnec/1Y5GGARaxPs6r49RnSPeUP3YjNYiU9sQHAtY4BBvnZwg==", + "dev": true + }, + "typescript": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.6.3.tgz", + "integrity": "sha512-yNIatDa5iaofVozS/uQJEl3JRWLKKGJKh6Yaiv0GLGSuhpFJe7P3SbHZ8/yjAHRQwKRoA6YZqlfjXWmVzoVSMw==", + "dev": true + }, + "ua-parser-js": { + "version": "0.7.31", + "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.31.tgz", + "integrity": "sha512-qLK/Xe9E2uzmYI3qLeOmI0tEOt+TBBQyUIAh4aAgU05FVYzeZrKUdkAZfBNVGRaHVgV0TDkdEngJSw/SyQchkQ==", + "dev": true + }, + "unicode-canonical-property-names-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.0.tgz", + "integrity": "sha512-yY5PpDlfVIU5+y/BSCxAJRBIS1Zc2dDG3Ujq+sR0U+JjUevW2JhocOF+soROYDSaAezOzOKuyyixhD6mBknSmQ==", + "dev": true + }, + "unicode-match-property-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-2.0.0.tgz", + "integrity": "sha512-5kaZCrbp5mmbz5ulBkDkbY0SsPOjKqVS35VpL9ulMPfSl0J0Xsm+9Evphv9CoIZFwre7aJoa94AY6seMKGVN5Q==", + "dev": true, + "requires": { + "unicode-canonical-property-names-ecmascript": "^2.0.0", + "unicode-property-aliases-ecmascript": "^2.0.0" + } + }, + "unicode-match-property-value-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-2.0.0.tgz", + "integrity": "sha512-7Yhkc0Ye+t4PNYzOGKedDhXbYIBe1XEQYQxOPyhcXNMJ0WCABqqj6ckydd6pWRZTHV4GuCPKdBAUiMc60tsKVw==", + "dev": true + }, + "unicode-property-aliases-ecmascript": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-2.0.0.tgz", + "integrity": "sha512-5Zfuy9q/DFr4tfO7ZPeVXb1aPoeQSdeFMLpYuFebehDAhbuevLs5yxSZmIFN1tP5F9Wl4IpJrYojg85/zgyZHQ==", + "dev": true + }, + "unique-filename": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", + "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", + "dev": true, + "requires": { + "unique-slug": "^2.0.0" + } + }, + "unique-slug": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.2.tgz", + "integrity": "sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==", + "dev": true, + "requires": { + "imurmurhash": "^0.1.4" + } + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", + "dev": true + }, + "uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "dev": true + }, + "uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true + }, + "validate-npm-package-name": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-3.0.0.tgz", + "integrity": "sha1-X6kS2B630MdK/BQN5zF/DKffQ34=", + "dev": true, + "requires": { + "builtins": "^1.0.3" + } + }, + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "dev": true + }, + "void-elements": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz", + "integrity": "sha1-wGavtYK7HLQSjWDqkjkulNXp2+w=", + "dev": true + }, + "watchpack": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.3.1.tgz", + "integrity": "sha512-x0t0JuydIo8qCNctdDrn1OzH/qDzk2+rdCOC3YzumZ42fiMqmQ7T3xQurykYMhYfHaPHTp4ZxAx2NfUo1K6QaA==", + "dev": true, + "requires": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + } + }, + "wbuf": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/wbuf/-/wbuf-1.7.3.tgz", + "integrity": "sha512-O84QOnr0icsbFGLS0O3bI5FswxzRr8/gHwWkDlQFskhSPryQXvrTMxjxGP4+iWYoauLoBvfDpkrOauZ+0iZpDA==", + "dev": true, + "requires": { + "minimalistic-assert": "^1.0.0" + } + }, + "wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g=", + "dev": true, + "requires": { + "defaults": "^1.0.3" + } + }, + "webpack": { + "version": "5.70.0", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.70.0.tgz", + "integrity": "sha512-ZMWWy8CeuTTjCxbeaQI21xSswseF2oNOwc70QSKNePvmxE7XW36i7vpBMYZFAUHPwQiEbNGCEYIOOlyRbdGmxw==", + "dev": true, + "requires": { + "@types/eslint-scope": "^3.7.3", + "@types/estree": "^0.0.51", + "@webassemblyjs/ast": "1.11.1", + "@webassemblyjs/wasm-edit": "1.11.1", + "@webassemblyjs/wasm-parser": "1.11.1", + "acorn": "^8.4.1", + "acorn-import-assertions": "^1.7.6", + "browserslist": "^4.14.5", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.9.2", + "es-module-lexer": "^0.9.0", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.9", + "json-parse-better-errors": "^1.0.2", + "loader-runner": "^4.2.0", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^3.1.0", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.1.3", + "watchpack": "^2.3.1", + "webpack-sources": "^3.2.3" + }, + "dependencies": { + "schema-utils": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.1.1.tgz", + "integrity": "sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + } + } + } + }, + "webpack-dev-middleware": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-5.3.0.tgz", + "integrity": "sha512-MouJz+rXAm9B1OTOYaJnn6rtD/lWZPy2ufQCH3BPs8Rloh/Du6Jze4p7AeLYHkVi0giJnYLaSGDC7S+GM9arhg==", + "dev": true, + "requires": { + "colorette": "^2.0.10", + "memfs": "^3.2.2", + "mime-types": "^2.1.31", + "range-parser": "^1.2.1", + "schema-utils": "^4.0.0" + }, + "dependencies": { + "ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + } + }, + "ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.3" + } + }, + "json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "schema-utils": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.0.0.tgz", + "integrity": "sha512-1edyXKgh6XnJsJSQ8mKWXnN/BVaIbFMLpouRUrXgVq7WYne5kw3MW7UPhO44uRXQSIpTSXoJbmrR2X0w9kUTyg==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.8.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.0.0" + } + } + } + }, + "webpack-dev-server": { + "version": "4.7.3", + "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-4.7.3.tgz", + "integrity": "sha512-mlxq2AsIw2ag016nixkzUkdyOE8ST2GTy34uKSABp1c4nhjZvH90D5ZRR+UOLSsG4Z3TFahAi72a3ymRtfRm+Q==", + "dev": true, + "requires": { + "@types/bonjour": "^3.5.9", + "@types/connect-history-api-fallback": "^1.3.5", + "@types/serve-index": "^1.9.1", + "@types/sockjs": "^0.3.33", + "@types/ws": "^8.2.2", + "ansi-html-community": "^0.0.8", + "bonjour": "^3.5.0", + "chokidar": "^3.5.2", + "colorette": "^2.0.10", + "compression": "^1.7.4", + "connect-history-api-fallback": "^1.6.0", + "default-gateway": "^6.0.3", + "del": "^6.0.0", + "express": "^4.17.1", + "graceful-fs": "^4.2.6", + "html-entities": "^2.3.2", + "http-proxy-middleware": "^2.0.0", + "ipaddr.js": "^2.0.1", + "open": "^8.0.9", + "p-retry": "^4.5.0", + "portfinder": "^1.0.28", + "schema-utils": "^4.0.0", + "selfsigned": "^2.0.0", + "serve-index": "^1.9.1", + "sockjs": "^0.3.21", + "spdy": "^4.0.2", + "strip-ansi": "^7.0.0", + "webpack-dev-middleware": "^5.3.0", + "ws": "^8.1.0" + }, + "dependencies": { + "ajv": { + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", + "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + } + }, + "ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.3" + } + }, + "ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", + "dev": true + }, + "json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "schema-utils": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.0.0.tgz", + "integrity": "sha512-1edyXKgh6XnJsJSQ8mKWXnN/BVaIbFMLpouRUrXgVq7WYne5kw3MW7UPhO44uRXQSIpTSXoJbmrR2X0w9kUTyg==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.8.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.0.0" + } + }, + "strip-ansi": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.0.1.tgz", + "integrity": "sha512-cXNxvT8dFNRVfhVME3JAe98mkXDYN2O1l7jmcwMnOslDeESg1rF/OZMtK0nRAhiari1unG5cD4jG3rapUAkLbw==", + "dev": true, + "requires": { + "ansi-regex": "^6.0.1" + } + } + } + }, + "webpack-merge": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-5.8.0.tgz", + "integrity": "sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q==", + "dev": true, + "requires": { + "clone-deep": "^4.0.1", + "wildcard": "^2.0.0" + } + }, + "webpack-sources": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz", + "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==", + "dev": true + }, + "webpack-subresource-integrity": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/webpack-subresource-integrity/-/webpack-subresource-integrity-5.1.0.tgz", + "integrity": "sha512-sacXoX+xd8r4WKsy9MvH/q/vBtEHr86cpImXwyg74pFIpERKt6FmB8cXpeuh0ZLgclOlHI4Wcll7+R5L02xk9Q==", + "dev": true, + "requires": { + "typed-assert": "^1.0.8" + } + }, + "websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "dev": true, + "requires": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + } + }, + "websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "dev": true + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "dev": true, + "requires": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "wildcard": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.0.tgz", + "integrity": "sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw==", + "dev": true + }, + "wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "ws": { + "version": "8.2.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", + "integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", + "dev": true, + "requires": {} + }, + "y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true + }, + "yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, + "yaml": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", + "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", + "dev": true + }, + "yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dev": true, + "requires": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + } + }, + "yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "dev": true + }, + "yn": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/yn/-/yn-2.0.0.tgz", + "integrity": "sha1-5a2ryKz0CPY4X8dklWhMiOavaJo=", + "dev": true + }, + "yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true + }, + "zone.js": { + "version": "0.11.5", + "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.11.5.tgz", + "integrity": "sha512-D1/7VxEuQ7xk6z/kAROe4SUbd9CzxY4zOwVGnGHerd/SgLIVU5f4esDzQUsOCeArn933BZfWMKydH7l7dPEp0g==", + "requires": { + "tslib": "^2.3.0" + } + } + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/package.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/package.json new file mode 100644 index 0000000000..d8238b7b59 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/package.json @@ -0,0 +1,47 @@ +{ + "name": "typescript-angular-v13-unit-tests", + "version": "0.0.0", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build", + "test": "ng test", + "lint": "ng lint", + "update": "ng update" + }, + "private": true, + "dependencies": { + "@angular/animations": "^13.3.4", + "@angular/common": "^13.3.4", + "@angular/compiler": "^13.3.4", + "@angular/core": "^13.3.4", + "@angular/forms": "^13.3.4", + "@angular/platform-browser": "^13.3.4", + "@angular/platform-browser-dynamic": "^13.3.4", + "@angular/router": "^13.3.4", + "core-js": "^2.5.4", + "rxjs": "^6.6.7", + "tslib": "^2.0.0", + "zone.js": "~0.11.5" + }, + "devDependencies": { + "@angular-devkit/build-angular": "^13.3.3", + "@angular/cli": "^13.3.3", + "@angular/compiler-cli": "^13.3.4", + "@angular/language-service": "^13.3.4", + "@types/jasmine": "~3.6.0", + "@types/jasminewd2": "~2.0.3", + "@types/node": "^12.11.1", + "codelyzer": "^6.0.0", + "jasmine-core": "~3.8.0", + "jasmine-spec-reporter": "~5.0.0", + "karma": "~6.3.4", + "karma-chrome-launcher": "~3.1.0", + "karma-coverage-istanbul-reporter": "~3.0.2", + "karma-jasmine": "~4.0.0", + "karma-jasmine-html-reporter": "^1.7.0", + "ts-node": "~7.0.0", + "tslint": "~6.1.0", + "typescript": "^4.6.3" + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/pom.xml b/samples/client/petstore/typescript-angular-v14-provided-in-root/pom.xml new file mode 100644 index 0000000000..7d263dea81 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/pom.xml @@ -0,0 +1,140 @@ + + 4.0.0 + org.openapitools + typescript-angular-v14-provided-in-root-tests + pom + 1.0-SNAPSHOT + + Typescript-Angular v14 Petstore Client + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + + withnpmm-npm-install + pre-integration-test + + exec + + + npm + builds/with-npm + + --legacy-peer-deps + install + + + + + + withnpmm-npm-run-build + pre-integration-test + + exec + + + npm + builds/with-npm + + run + build + + + + + + + + + + org.apache.maven.plugins + maven-clean-plugin + 3.1.0 + + + + clean-typescript-angular-v14-test-outputs + + clean + + post-integration-test + + true + + + builds/with-npm + false + false + + dist/** + node_modules/** + package-lock.json + + + + + + + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + npm-install + pre-integration-test + + exec + + + npm + + install + + + + + npm-test + integration-test + + exec + + + npm + + test + -- + --progress=false + --no-watch + --browsers + ChromeHeadless + + + + + + + + diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/src/models/mod.rs b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.css similarity index 100% rename from samples/client/petstore/rust/hyper/fileResponseTest/src/models/mod.rs rename to samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.css diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.html b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.html new file mode 100644 index 0000000000..b843d662b6 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.html @@ -0,0 +1,44 @@ +
        +

        + Welcome to {{ title }}! +

        +
        +
        +

        Pet API

        + + + + + + + +
        +
        +

        Pet

        +
        +

        Name: {{ pet.name }}

        +

        ID: {{ pet.id }}

        +
        + +
        +
        +

        Store API

        + +
        +
        +

        Store

        +
          +
        • {{item.key}}: {{item.number}}
        • +
        + +
        diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.spec.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.spec.ts new file mode 100644 index 0000000000..6ddcad3f19 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.spec.ts @@ -0,0 +1,94 @@ +import { TestBed, waitForAsync } from '@angular/core/testing'; +import { HttpClientModule } from '@angular/common/http'; +import { + ApiModule, + Configuration, + ConfigurationParameters, + PetService, + StoreService, + UserService, +} from '@swagger/typescript-angular-petstore'; +import { AppComponent } from './app.component'; +import {fakePetstoreBackendProviders} from "../test/fakeBackend"; + +describe('AppComponent', () => { + + const apiConfigurationParams: ConfigurationParameters = { + // add configuration params here + apiKeys: { api_key: 'foobar' }, + }; + + const apiConfig = new Configuration(apiConfigurationParams); + + const getApiConfig: () => Configuration = () => { + return apiConfig; + }; + + + beforeEach(waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientModule, + ApiModule.forRoot(getApiConfig), + ], + providers: [ + PetService, + StoreService, + UserService, + ...fakePetstoreBackendProviders, + ], + declarations: [ + AppComponent, + ], + }).compileComponents(); + })); + + it('should create the app', waitForAsync(() => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); + })); + + it('should render title in a h1 tag', waitForAsync(() => { + const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); + const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain('Welcome to Typescript Angular v11 (provided in root)!'); + })); + + describe(`constructor()`, () => { + it(`should have a petService provided`, () => { + const petService = TestBed.inject(PetService); + expect(petService).toBeTruthy(); + }); + + it(`should have a storeService provided`, () => { + const storeService = TestBed.inject(StoreService); + expect(storeService).toBeTruthy(); + }); + + it(`should have a userService provided`, () => { + const userService = TestBed.inject(UserService); + expect(userService).toBeTruthy(); + }); + }); + + describe('addPet()', () => { + it(`should add a new pet`, () => { + const fixture = TestBed.createComponent(AppComponent); + const instance = fixture.componentInstance; + const petService = TestBed.inject(PetService); + + spyOn(petService, 'addPet').and.callThrough(); + + fixture.detectChanges(); + instance.addPet(); + + expect(petService.addPet).toHaveBeenCalledWith({ + name: `pet`, + photoUrls: [] + }); + }); + }); + +}); diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.ts new file mode 100644 index 0000000000..44ef8c4be0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.component.ts @@ -0,0 +1,71 @@ +import { Component } from '@angular/core'; +import { + PetService, + StoreService, + UserService, + Pet +} from '@swagger/typescript-angular-petstore'; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'] +}) +export class AppComponent { + title = 'Typescript Angular v11 (provided in root)'; + pet: Pet; + store: { key: string, number: number }[]; + + constructor(private petService: PetService, + private storeService: StoreService, + private userService: UserService, + ) { + this.pet = { + name: `pet`, + photoUrls: [] + }; + } + + public addPet() { + this.petService.addPet(this.pet) + .subscribe((result) => { + this.pet = result; + } + ); + } + + public getPetByID() { + this.petService.getPetById(this.pet.id) + .subscribe((result) => { + this.pet = result; + } + ); + } + + public updatePet() { + this.petService.updatePet(this.pet) + .subscribe((result) => { + this.pet = result; + } + ); + } + + public deletePet() { + this.petService.deletePet(this.pet.id) + .subscribe((result) => { + this.pet = result; + } + ); + } + + public getStoreInventory() { + this.storeService.getInventory() + .subscribe((result) => { + this.store = []; + for(let item in result) { + const number = result[item]; + this.store.push({ key: item, number: number}); + } + }) + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.module.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.module.ts new file mode 100644 index 0000000000..33239063d6 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/app/app.module.ts @@ -0,0 +1,36 @@ +import { BrowserModule } from '@angular/platform-browser'; +import { NgModule } from '@angular/core'; +import { HttpClientModule } from '@angular/common/http'; +import { + ApiModule, + Configuration, + ConfigurationParameters +} from '@swagger/typescript-angular-petstore' + +import { AppComponent } from './app.component'; + +export const apiConfigurationParams: ConfigurationParameters = { + apiKeys: { api_key: "foobar" } +}; + +export const apiConfig = new Configuration(apiConfigurationParams); + +export function getApiConfig() { + return apiConfig; +} + +@NgModule({ + declarations: [ + AppComponent, + ], + imports: [ + BrowserModule, + HttpClientModule, + ApiModule.forRoot(getApiConfig), + ], + providers: [ + ], + bootstrap: [AppComponent] +}) +export class AppModule { } + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/environments/environment.prod.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/environments/environment.prod.ts new file mode 100644 index 0000000000..3612073bc3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/environments/environment.prod.ts @@ -0,0 +1,3 @@ +export const environment = { + production: true +}; diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/environments/environment.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/environments/environment.ts new file mode 100644 index 0000000000..012182efa3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/environments/environment.ts @@ -0,0 +1,15 @@ +// This file can be replaced during build by using the `fileReplacements` array. +// `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`. +// The list of file replacements can be found in `angular.json`. + +export const environment = { + production: false +}; + +/* + * In development mode, to ignore zone related error stack frames such as + * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can + * import the following file, but please comment it out in production mode + * because it will have performance impact when throw error + */ +// import 'zone.js/dist/zone-error'; // Included with Angular CLI. diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/favicon.ico b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/favicon.ico new file mode 100644 index 0000000000..8081c7ceaf Binary files /dev/null and b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/favicon.ico differ diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/index.html b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/index.html new file mode 100644 index 0000000000..0d92535c76 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/index.html @@ -0,0 +1,14 @@ + + + + + Cli + + + + + + + + + diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/karma.conf.js b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/karma.conf.js new file mode 100644 index 0000000000..4a9730b9b6 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/karma.conf.js @@ -0,0 +1,31 @@ +// Karma configuration file, see link for more information +// https://karma-runner.github.io/1.0/config/configuration-file.html + +module.exports = function (config) { + config.set({ + basePath: '', + frameworks: ['jasmine', '@angular-devkit/build-angular'], + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-jasmine-html-reporter'), + require('karma-coverage-istanbul-reporter'), + require('@angular-devkit/build-angular/plugins/karma') + ], + client: { + clearContext: false // leave Jasmine Spec Runner output visible in browser + }, + coverageIstanbulReporter: { + dir: require('path').join(__dirname, '../coverage'), + reports: ['html', 'lcovonly'], + fixWebpackSourcePaths: true + }, + reporters: ['progress', 'kjhtml'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome'], + singleRun: false + }); +}; diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/main.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/main.ts new file mode 100644 index 0000000000..91ec6da5f0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/main.ts @@ -0,0 +1,12 @@ +import { enableProdMode } from '@angular/core'; +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; + +import { AppModule } from './app/app.module'; +import { environment } from './environments/environment'; + +if (environment.production) { + enableProdMode(); +} + +platformBrowserDynamic().bootstrapModule(AppModule) + .catch(err => console.log(err)); diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/polyfills.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/polyfills.ts new file mode 100644 index 0000000000..aa665d6b87 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/polyfills.ts @@ -0,0 +1,63 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.io/guide/browser-support + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** IE10 and IE11 requires the following for NgClass support on SVG elements */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. + +/** + * Web Animations `@angular/platform-browser/animations` + * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. + * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). + */ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + +/** + * By default, zone.js will patch all possible macroTask and DomEvents + * user can disable parts of macroTask/DomEvents patch by setting following flags + * because those flags need to be set before `zone.js` being loaded, and webpack + * will put import in the top of bundle, so user need to create a separate file + * in this directory (for example: zone-flags.ts), and put the following flags + * into that file, and then add the following code before importing zone.js. + * import './zone-flags.ts'; + * + * The flags allowed in zone-flags.ts are listed here. + * + * The following flags will work for all browsers. + * + * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame + * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick + * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames + * + * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js + * with the following flag, it will bypass `zone.js` patch for IE/Edge + * + * (window as any).__Zone_enable_cross_context_check = true; + * + */ + +/*************************************************************************************************** + * Zone JS is required by default for Angular itself. + */ +import 'zone.js/dist/zone'; // Included with Angular CLI. + + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/styles.css b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/styles.css new file mode 100644 index 0000000000..90d4ee0072 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/styles.css @@ -0,0 +1 @@ +/* You can add global styles to this file, and also import other style files */ diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test.ts new file mode 100644 index 0000000000..16317897b1 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test.ts @@ -0,0 +1,20 @@ +// This file is required by karma.conf.js and loads recursively all the .spec and framework files + +import 'zone.js/dist/zone-testing'; +import { getTestBed } from '@angular/core/testing'; +import { + BrowserDynamicTestingModule, + platformBrowserDynamicTesting +} from '@angular/platform-browser-dynamic/testing'; + +declare const require: any; + +// First, initialize the Angular testing environment. +getTestBed().initTestEnvironment( + BrowserDynamicTestingModule, + platformBrowserDynamicTesting() +); +// Then we find all the tests. +const context = require.context('./', true, /\.spec\.ts$/); +// And load the modules. +context.keys().map(context); diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/api.spec.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/api.spec.ts new file mode 100644 index 0000000000..225414c0d5 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/api.spec.ts @@ -0,0 +1,152 @@ +import { TestBed, waitForAsync } from '@angular/core/testing'; +import {HttpClientModule} from '@angular/common/http'; +import { + ApiModule, + Configuration, + ConfigurationParameters, + PetService, + StoreService, + UserService, + Pet, + User, +} from '@swagger/typescript-angular-petstore'; +import {fakePetstoreBackendProviders} from "./fakeBackend"; +import {switchMap} from "rxjs/operators"; + + +describe(`API (functionality)`, () => { + + const getUser: () => User = () => { + const time = Date.now(); + return { + username: `user-${time}`, + } + }; + + const getPet: () => Pet = () => { + const time = Date.now(); + return { + name: `pet-${time}`, + photoUrls: [], + } + }; + + const newPet: Pet = getPet(); + + const newUser: User = getUser(); + + const apiConfigurationParams: ConfigurationParameters = { + // add configuration params here + apiKeys: { api_key: 'foobar' } + }; + + const apiConfig = new Configuration(apiConfigurationParams); + + const getApiConfig = () => { + return apiConfig; + }; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientModule, + ApiModule.forRoot(getApiConfig) + ], + providers: [ + PetService, + StoreService, + UserService, + ...fakePetstoreBackendProviders, + ] + }); + }); + + describe(`PetService`, () => { + it(`should be provided`, () => { + const petService = TestBed.inject(PetService); + expect(petService).toBeTruthy(); + }); + + it(`should add a pet`, waitForAsync(() => { + const petService = TestBed.inject(PetService); + + return petService.addPet(newPet).subscribe( + (result) => { + expect(result.id).toBeGreaterThan(0); + expect(result.name).toBe(newPet.name); + }, + ); + })); + + it(`should get the pet data by id`, waitForAsync(() => { + const petService = TestBed.inject(PetService); + return petService.addPet(newPet).pipe( + switchMap((addedPet: Pet) => petService.getPetById(addedPet.id)) + ).subscribe( + result => { + return expect(result.name).toBe(newPet.name); + }, + ); + })); + + it(`should update the pet name by pet object`, waitForAsync(() => { + const petService = TestBed.inject(PetService); + + + return petService.addPet(newPet).pipe( + switchMap((addedPet: Pet) => petService.updatePet({ + ...addedPet, + name: 'something else' + })) + ).subscribe( + result => expect(result.name).toBe('something else'), + error => fail(`expected a result, not the error: ${error.message}`), + ); + })); + + it(`should delete the pet`, waitForAsync(() => { + const petService = TestBed.inject(PetService); + + return petService.addPet(newPet).pipe( + switchMap((addedPet: Pet) => petService.deletePet(addedPet.id, undefined, 'response')), + ).subscribe( + result => expect(result.status).toEqual(200), + ); + })); + + }); + + describe(`StoreService`, () => { + it(`should be provided`, () => { + const storeService = TestBed.inject(StoreService); + expect(storeService).toBeTruthy(); + }); + + it(`should get the inventory`, waitForAsync(() => { + const storeService = TestBed.inject(StoreService); + + return storeService.getInventory().subscribe( + result => expect(result.mega).toBe(42), + error => fail(`expected a result, not the error: ${error.message}`), + ); + + })); + + }); + + describe(`UserService`, () => { + it(`should be provided`, () => { + const userService = TestBed.inject(UserService); + expect(userService).toBeTruthy(); + }); + + it(`should create the user`, waitForAsync(() => { + const userService = TestBed.inject(UserService); + + return userService.createUser(newUser, 'response').subscribe( + result => expect(result.status).toEqual(200), + ); + })); + + }); +}); diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/basePath.spec.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/basePath.spec.ts new file mode 100644 index 0000000000..c6357cc16f --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/basePath.spec.ts @@ -0,0 +1,63 @@ +import { TestBed, waitForAsync } from '@angular/core/testing'; +import { HttpClient } from '@angular/common/http'; +import { HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; +import { + ApiModule, + PetService, + Pet, +} from '@swagger/typescript-angular-petstore'; +import {BASE_PATH} from "../../../../builds/default/variables"; + +describe(`API (basePath)`, () => { + let httpClient: HttpClient; + let httpTestingController: HttpTestingController; + + const pet: Pet = { + name: `pet`, + photoUrls: [] + }; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientTestingModule , + ApiModule, + ], + providers: [ + PetService, + { provide: BASE_PATH, useValue: '//test'} + ] + }); + + // Inject the http service and test controller for each test + httpClient = TestBed.inject(HttpClient); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + // After every test, assert that there are no more pending requests. + httpTestingController.verify(); + }); + + describe(`PetService`, () => { + it(`should be provided`, () => { + const petService = TestBed.inject(PetService); + expect(petService).toBeTruthy(); + }); + + it(`should call to the injected basePath //test/pet`, waitForAsync(() => { + const petService = TestBed.inject(PetService); + + petService.addPet(pet).subscribe( + result => expect(result).toEqual(pet), + error => fail(`expected a result, not the error: ${error.message}`), + ); + + const req = httpTestingController.expectOne('//test/pet'); + expect(req.request.method).toEqual('POST'); + req.flush(pet); + })); + + }); + +}); diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/configuration.spec.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/configuration.spec.ts new file mode 100644 index 0000000000..19e983c790 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/configuration.spec.ts @@ -0,0 +1,140 @@ +import { TestBed, waitForAsync } from '@angular/core/testing'; +import { HttpClient } from '@angular/common/http'; +import { HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; +import { + ApiModule, + Configuration, + ConfigurationParameters, + PetService, + Pet, +} from '@swagger/typescript-angular-petstore'; + +describe(`API (with ConfigurationFactory)`, () => { + let httpClient: HttpClient; + let httpTestingController: HttpTestingController; + + const pet: Pet = { + name: `pet`, + photoUrls: [] + }; + + let apiConfigurationParams: ConfigurationParameters = { + // add configuration params here + basePath: '//test-initial' + }; + + let apiConfig: Configuration = new Configuration(apiConfigurationParams); + + const getApiConfig = () => { + return apiConfig; + }; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientTestingModule , + ApiModule.forRoot(getApiConfig) + ], + providers: [ + PetService, + ] + }); + + // Inject the http service and test controller for each test + httpClient = TestBed.inject(HttpClient); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + // After every test, assert that there are no more pending requests. + httpTestingController.verify(); + }); + + describe(`PetService`, () => { + it(`should be provided`, () => { + const petService = TestBed.inject(PetService); + expect(petService).toBeTruthy(); + }); + + it(`should call initially configured basePath //test-initial/pet`, waitForAsync(() => { + const petService = TestBed.inject(PetService); + + petService.addPet(pet).subscribe( + result => expect(result).toEqual(pet), + error => fail(`expected a result, not the error: ${error.message}`), + ); + + const req = httpTestingController.expectOne('//test-initial/pet'); + + expect(req.request.method).toEqual('POST'); + + req.flush(pet); + })); + }); + +}); + +describe(`API (with ConfigurationFactory and empty basePath)`, () => { + let httpClient: HttpClient; + let httpTestingController: HttpTestingController; + + const pet: Pet = { + name: `pet`, + photoUrls: [] + }; + + let apiConfigurationParams: ConfigurationParameters = { + // add configuration params here + basePath: '' + }; + + let apiConfig: Configuration = new Configuration(apiConfigurationParams); + + const getApiConfig = () => { + return apiConfig; + }; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientTestingModule , + ApiModule.forRoot(getApiConfig) + ], + providers: [ + PetService, + ] + }); + + // Inject the http service and test controller for each test + httpClient = TestBed.inject(HttpClient); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + // After every test, assert that there are no more pending requests. + httpTestingController.verify(); + }); + + describe(`PetService`, () => { + it(`should be provided`, () => { + const petService = TestBed.inject(PetService); + expect(petService).toBeTruthy(); + }); + + it(`should call initially configured empty basePath /pet`, waitForAsync(() => { + const petService = TestBed.inject(PetService); + + petService.addPet(pet).subscribe( + result => expect(result).toEqual(pet), + error => fail(`expected a result, not the error: ${error.message}`), + ); + + const req = httpTestingController.expectOne('/pet'); + + expect(req.request.method).toEqual('POST'); + + req.flush(pet); + })); + }); + +}); diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/fakeBackend.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/fakeBackend.ts new file mode 100644 index 0000000000..2ea690270c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/fakeBackend.ts @@ -0,0 +1,92 @@ +import {Injectable, Provider} from '@angular/core'; +import {Observable, Observer} from 'rxjs'; +import { + HTTP_INTERCEPTORS, + HttpEvent, + HttpEventType, + HttpHandler, + HttpInterceptor, + HttpRequest +} from '@angular/common/http'; +import { TestRequest } from "@angular/common/http/testing"; +import { Pet } from "@swagger/typescript-angular-petstore"; + +@Injectable() +export class FakePetstoreBackendInterceptor implements HttpInterceptor { + private fakePetstoreBackend = new FakePetstoreBackend() + + constructor() { + + } + + intercept(req: HttpRequest, next: HttpHandler): Observable> { + const parsedUrl = new URL(req.url); + if (parsedUrl.pathname.indexOf('/v2/pet') === 0) { + if (req.method === 'GET') { + const pathParts = parsedUrl.pathname.split('/'); + const petId = parseInt(pathParts[pathParts.length-1], 10); + return this.respond(req, this.fakePetstoreBackend.getPet(petId)); + } else if (req.method === 'POST') { + return this.respond(req, this.fakePetstoreBackend.addPet(req.body)); + } else if (req.method === 'PUT') { + return this.respond(req, this.fakePetstoreBackend.updatePet(req.body)); + } else if (req.method === 'DELETE') { + const pathParts = parsedUrl.pathname.split('/'); + const petId = parseInt(pathParts[pathParts.length-1], 10); + this.fakePetstoreBackend.deletePet(petId); + return this.respond(req, {}); + } + } else if (parsedUrl.pathname.indexOf('/v2/store/inventory') === 0) { + if (req.method === 'GET') { + return this.respond(req, {mega: 42}); + } + } else if (parsedUrl.pathname.indexOf('/v2/user') === 0) { + if (req.method === 'POST') { + return this.respond(req, {mega: 42}); + } + } + throw new Error('Http call not implemented in fake backend. ' + req.url); + } + + private respond(request: HttpRequest, response: any): Observable> { + return new Observable((observer: Observer) => { + const testReq = new TestRequest(request, observer); + observer.next({ type: HttpEventType.Sent } as HttpEvent); + testReq.flush(response); + return () => { }; + }); + } +} + +@Injectable() +class FakePetstoreBackend { + private nextId = 1; + private pets: Map = new Map(); + + public getPet(id: number): Pet { + return this.pets.get(String(id)); + } + + public addPet(pet: Pet): Pet { + const id = this.nextId++; + this.pets.set(String(id), { + ...pet, + id + }); + return this.getPet(id); + } + + public updatePet(pet: Pet): Pet { + this.pets.set(String(pet.id), pet); + return pet; + } + + public deletePet(id: number): void { + this.pets.delete(String(id)); + } +} + + +export const fakePetstoreBackendProviders: Provider[] = [ + {provide: HTTP_INTERCEPTORS, useClass: FakePetstoreBackendInterceptor, multi: true}, +]; diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/no-configuration.spec.ts b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/no-configuration.spec.ts new file mode 100644 index 0000000000..a1f624ea29 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/test/no-configuration.spec.ts @@ -0,0 +1,61 @@ +import { TestBed, waitForAsync } from '@angular/core/testing'; +import { HttpClient } from '@angular/common/http'; +import { HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing'; +import { + ApiModule, + PetService, + Pet, +} from '@swagger/typescript-angular-petstore'; + +describe(`API (no configuration)`, () => { + let httpClient: HttpClient; + let httpTestingController: HttpTestingController; + + const pet: Pet = { + name: `pet`, + photoUrls: [] + }; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientTestingModule , + ApiModule, + ], + providers: [ + PetService, + ] + }); + + // Inject the http service and test controller for each test + httpClient = TestBed.inject(HttpClient); + httpTestingController = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + // After every test, assert that there are no more pending requests. + httpTestingController.verify(); + }); + + describe(`PetService`, () => { + it(`should be provided`, () => { + const petService = TestBed.inject(PetService); + expect(petService).toBeTruthy(); + }); + + it(`should call to the default basePath http://petstore.swagger.io/v2/pet`, waitForAsync(() => { + const petService = TestBed.inject(PetService); + + petService.addPet(pet).subscribe( + result => expect(result).toEqual(pet), + error => fail(`expected a result, not the error: ${error.message}`), + ); + + const req = httpTestingController.expectOne('http://petstore.swagger.io/v2/pet'); + expect(req.request.method).toEqual('POST'); + req.flush(pet); + })); + + }); + +}); diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/tsconfig.app.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/tsconfig.app.json new file mode 100644 index 0000000000..be37b0474d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/tsconfig.app.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/app", + "types": [] + }, + "files": [ + "main.ts", + "polyfills.ts" + ], + "include": [ + "tests/default/src/**/*.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/tsconfig.spec.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/tsconfig.spec.json new file mode 100644 index 0000000000..2b5ebf4ad4 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/tsconfig.spec.json @@ -0,0 +1,18 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/spec", + "types": [ + "jasmine", + "node" + ] + }, + "files": [ + "test.ts", + "polyfills.ts" + ], + "include": [ + "**/*.spec.ts", + "**/*.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/tslint.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/tslint.json new file mode 100644 index 0000000000..78a62a0db6 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tests/default/src/tslint.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../tslint.json", + "rules": { + "directive-selector": [ + true, + "attribute", + "app", + "camelCase" + ], + "component-selector": [ + true, + "element", + "app", + "kebab-case" + ] + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tsconfig.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/tsconfig.json new file mode 100644 index 0000000000..f3ec5dc066 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "baseUrl": "./", + "downlevelIteration": true, + "module": "es2020", + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es2015", + "typeRoots": [ + "node_modules/@types" + ], + "paths": { + "@swagger/typescript-angular-petstore": ["builds/default"] + }, + "lib": [ + "es2017", + "dom" + ] + } +} diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/tslint.json b/samples/client/petstore/typescript-angular-v14-provided-in-root/tslint.json new file mode 100644 index 0000000000..5065137af3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/tslint.json @@ -0,0 +1,129 @@ +{ + "rulesDirectory": [ + "node_modules/codelyzer" + ], + "rules": { + "arrow-return-shorthand": true, + "callable-types": true, + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "curly": true, + "deprecation": { + "severity": "warn" + }, + "eofline": true, + "forin": true, + "import-blacklist": [ + true, + "rxjs/Rx" + ], + "import-spacing": true, + "indent": [ + true, + "spaces" + ], + "interface-over-type-literal": true, + "label-position": true, + "max-line-length": [ + true, + 140 + ], + "member-access": false, + "member-ordering": [ + true, + { + "order": [ + "static-field", + "instance-field", + "static-method", + "instance-method" + ] + } + ], + "no-arg": true, + "no-bitwise": true, + "no-console": [ + true, + "debug", + "info", + "time", + "timeEnd", + "trace" + ], + "no-construct": true, + "no-debugger": true, + "no-duplicate-super": true, + "no-empty": false, + "no-empty-interface": true, + "no-eval": true, + "no-inferrable-types": [ + true, + "ignore-params" + ], + "no-misused-new": true, + "no-non-null-assertion": true, + "no-shadowed-variable": true, + "no-string-literal": false, + "no-string-throw": true, + "no-switch-case-fall-through": true, + "no-trailing-whitespace": true, + "no-unnecessary-initializer": true, + "no-unused-expression": true, + "no-var-keyword": true, + "object-literal-sort-keys": false, + "one-line": [ + true, + "check-open-brace", + "check-catch", + "check-else", + "check-whitespace" + ], + "prefer-const": true, + "quotemark": [ + true, + "single" + ], + "radix": true, + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "unified-signatures": true, + "variable-name": false, + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ], + "no-output-on-prefix": true, + "no-inputs-metadata-property": true, + "no-outputs-metadata-property": true, + "no-host-metadata-property": true, + "no-input-rename": true, + "no-output-rename": true, + "use-lifecycle-interface": true, + "use-pipe-transform-interface": true, + "component-class-suffix": true, + "directive-class-suffix": true + } +} diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/.gitignore b/samples/client/petstore/typescript-angular-v14-query-param-object-format/.gitignore new file mode 100644 index 0000000000..149b576547 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/openapi3/client/petstore/java/native/.openapi-generator-ignore b/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator-ignore similarity index 100% rename from samples/openapi3/client/petstore/java/native/.openapi-generator-ignore rename to samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator-ignore diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/FILES new file mode 100644 index 0000000000..6e213a61aa --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/FILES @@ -0,0 +1,20 @@ +.gitignore +README.md +api.module.ts +api/api.ts +api/pet.service.ts +api/store.service.ts +api/user.service.ts +configuration.ts +encoder.ts +git_push.sh +index.ts +model/apiResponse.ts +model/category.ts +model/models.ts +model/order.ts +model/pet.ts +model/tag.ts +model/user.ts +param.ts +variables.ts diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/README.md b/samples/client/petstore/typescript-angular-v14-query-param-object-format/README.md new file mode 100644 index 0000000000..de16f95a8b --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/README.md @@ -0,0 +1,226 @@ +## @ + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @ --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from ''; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from ''; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from ''; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from ''; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from ''; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from ''; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from ''; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` + +### Customizing path parameter encoding + +Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple' +and Dates for format 'date-time' are encoded correctly. + +Other styles (e.g. "matrix") are not that easy to encode +and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]). + +To implement your own parameter encoding (or call another library), +pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object +(see [General Usage](#general-usage) above). + +Example value for use in your Configuration-Provider: +```typescript +new Configuration({ + encodeParam: (param: Param) => myFancyParamEncoder(param), +}) +``` + +[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations +[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values +[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/api.module.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api.module.ts new file mode 100644 index 0000000000..2afb8f64e9 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api.module.ts @@ -0,0 +1,33 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/api.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/api.ts new file mode 100644 index 0000000000..8e44b64083 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/pet.service.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/pet.service.ts new file mode 100644 index 0000000000..bb24ea5bcc --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/pet.service.ts @@ -0,0 +1,723 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { ApiResponse } from '../model/apiResponse'; +// @ts-ignore +import { Pet } from '../model/pet'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class PetService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (key != null) { + httpParams = httpParams.append(key, JSON.stringify(value)); + } else { + throw Error("key may not be null if value is a QueryParamObject"); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public addPet(pet: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public addPet(pet: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public addPet(pet: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public addPet(pet: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (pet === null || pet === undefined) { + throw new Error('Required parameter pet was null or undefined when calling addPet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: pet, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + let localVarHeaders = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + localVarHeaders = localVarHeaders.set('api_key', String(apiKey)); + } + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (status) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + status, 'status'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/findByStatus`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + * @deprecated + */ + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (tags) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + tags, 'tags'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/findByTags`; + return this.httpClient.request>('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePet(pet: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public updatePet(pet: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public updatePet(pet: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public updatePet(pet: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (pet === null || pet === undefined) { + throw new Error('Required parameter pet was null or undefined when calling updatePet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: pet, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (name !== undefined) { + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; + } + if (status !== undefined) { + localVarFormParams = localVarFormParams.append('status', status) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (additionalMetadata !== undefined) { + localVarFormParams = localVarFormParams.append('additionalMetadata', additionalMetadata) as any || localVarFormParams; + } + if (file !== undefined) { + localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/store.service.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/store.service.ts new file mode 100644 index 0000000000..04f78cae1c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/store.service.ts @@ -0,0 +1,333 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { Order } from '../model/order'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class StoreService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (key != null) { + httpParams = httpParams.append(key, JSON.stringify(value)); + } else { + throw Error("key may not be null if value is a QueryParamObject"); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/inventory`; + return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public placeOrder(order: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public placeOrder(order: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(order: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(order: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (order === null || order === undefined) { + throw new Error('Required parameter order was null or undefined when calling placeOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/store/order`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: order, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/user.service.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/user.service.ts new file mode 100644 index 0000000000..fcd474cf95 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/api/user.service.ts @@ -0,0 +1,648 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { User } from '../model/user'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class UserService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (Array.isArray(basePath) && basePath.length > 0) { + basePath = basePath[0]; + } + + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + // @ts-ignore + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (key != null) { + httpParams = httpParams.append(key, JSON.stringify(value)); + } else { + throw Error("key may not be null if value is a QueryParamObject"); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUser(user: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUser(user: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(user: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(user: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: user, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithArrayInput(user: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithArrayInput(user: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(user: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(user: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUsersWithArrayInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/createWithArray`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: user, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithListInput(user: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithListInput(user: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(user: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(user: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUsersWithListInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/createWithList`; + return this.httpClient.request('post', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: user, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('delete', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (username !== undefined && username !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + username, 'username'); + } + if (password !== undefined && password !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + password, 'password'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/login`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs out current logged in user session + * + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/logout`; + return this.httpClient.request('get', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param user Updated user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateUser(username: string, user: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updateUser(username: string, user: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, user: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, user: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling updateUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`; + return this.httpClient.request('put', `${this.configuration.basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: user, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/configuration.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/configuration.ts new file mode 100644 index 0000000000..5ea92c82cb --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/configuration.ts @@ -0,0 +1,186 @@ +import { HttpParameterCodec } from '@angular/common/http'; +import { Param } from './param'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Override the default method for encoding path parameters in various + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam?: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + /** + * Takes care of encoding query- and form-parameters. + */ + encoder?: HttpParameterCodec; + /** + * Encoding of various path parameter + * styles. + *

        + * See {@link README.md} for more details + *

        + */ + encodeParam: (param: Param) => string; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.encodeParam) { + this.encodeParam = configurationParameters.encodeParam; + } + else { + this.encodeParam = param => this.defaultEncodeParam(param); + } + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + + // init default api_key credential + if (!this.credentials['api_key']) { + this.credentials['api_key'] = () => { + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } + }; + } + + // init default petstore_auth credential + if (!this.credentials['petstore_auth']) { + this.credentials['petstore_auth'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } + + private defaultEncodeParam(param: Param): string { + // This implementation exists as fallback for missing configuration + // and for backwards compatibility to older typescript-angular generator versions. + // It only works for the 'simple' parameter style. + // Date-handling only works for the 'date-time' format. + // All other styles and Date-formats are probably handled incorrectly. + // + // But: if that's all you need (i.e.: the most common use-case): no need for customization! + + const value = param.dataFormat === 'date-time' + ? (param.value as Date).toISOString() + : param.value; + + return encodeURIComponent(String(value)); + } +} diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/encoder.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/encoder.ts new file mode 100644 index 0000000000..138c4d5cf2 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/git_push.sh b/samples/client/petstore/typescript-angular-v14-query-param-object-format/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/index.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/index.ts new file mode 100644 index 0000000000..104dd3d21e --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/index.ts @@ -0,0 +1,6 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; +export * from './param'; diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/apiResponse.ts new file mode 100644 index 0000000000..682ba47892 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/apiResponse.ts @@ -0,0 +1,22 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/category.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/category.ts new file mode 100644 index 0000000000..b988b6827a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/category.ts @@ -0,0 +1,21 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/models.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/models.ts new file mode 100644 index 0000000000..8607c5dabd --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/order.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/order.ts new file mode 100644 index 0000000000..a29bebe490 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/order.ts @@ -0,0 +1,37 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: string; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/pet.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/pet.ts new file mode 100644 index 0000000000..e0404395f9 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/pet.ts @@ -0,0 +1,39 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/tag.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/tag.ts new file mode 100644 index 0000000000..b6ff210e8d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/tag.ts @@ -0,0 +1,21 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/user.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/user.ts new file mode 100644 index 0000000000..fce5100530 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/model/user.ts @@ -0,0 +1,30 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/param.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/param.ts new file mode 100644 index 0000000000..78a2d20a64 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/param.ts @@ -0,0 +1,69 @@ +/** + * Standard parameter styles defined by OpenAPI spec + */ +export type StandardParamStyle = + | 'matrix' + | 'label' + | 'form' + | 'simple' + | 'spaceDelimited' + | 'pipeDelimited' + | 'deepObject' + ; + +/** + * The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user. + */ +export type ParamStyle = StandardParamStyle | string; + +/** + * Standard parameter locations defined by OpenAPI spec + */ +export type ParamLocation = 'query' | 'header' | 'path' | 'cookie'; + +/** + * Standard types as defined in OpenAPI Specification: Data Types + */ +export type StandardDataType = + | "integer" + | "number" + | "boolean" + | "string" + | "object" + | "array" + ; + +/** + * Standard {@link DataType}s plus your own types/classes. + */ +export type DataType = StandardDataType | string; + +/** + * Standard formats as defined in OpenAPI Specification: Data Types + */ +export type StandardDataFormat = + | "int32" + | "int64" + | "float" + | "double" + | "byte" + | "binary" + | "date" + | "date-time" + | "password" + ; + +export type DataFormat = StandardDataFormat | string; + +/** + * The parameter to encode. + */ +export interface Param { + name: string; + value: unknown; + in: ParamLocation; + style: ParamStyle, + explode: boolean; + dataType: DataType; + dataFormat: DataFormat | undefined; +} diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/variables.ts b/samples/client/petstore/typescript-angular-v14-query-param-object-format/variables.ts new file mode 100644 index 0000000000..6fe58549f3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-aurelia/default/PetApi.ts b/samples/client/petstore/typescript-aurelia/default/PetApi.ts index 1ac19a00fb..d242f5c7d0 100644 --- a/samples/client/petstore/typescript-aurelia/default/PetApi.ts +++ b/samples/client/petstore/typescript-aurelia/default/PetApi.ts @@ -77,7 +77,7 @@ export interface IUpdatePetWithFormParams { export interface IUploadFileParams { petId: number; additionalMetadata?: string; - file?: any; + file?: File; } /** diff --git a/samples/client/petstore/typescript-axios/builds/composed-schemas/common.ts b/samples/client/petstore/typescript-axios/builds/composed-schemas/common.ts index b156f3e26e..57e263ddf7 100644 --- a/samples/client/petstore/typescript-axios/builds/composed-schemas/common.ts +++ b/samples/client/petstore/typescript-axios/builds/composed-schemas/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/default/api.ts b/samples/client/petstore/typescript-axios/builds/default/api.ts index e6faa73c1a..db555ab3b5 100644 --- a/samples/client/petstore/typescript-axios/builds/default/api.ts +++ b/samples/client/petstore/typescript-axios/builds/default/api.ts @@ -318,7 +318,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -550,11 +550,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -693,11 +693,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -790,11 +790,11 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, }; @@ -900,12 +900,12 @@ export class PetApi extends BaseAPI { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/default/common.ts b/samples/client/petstore/typescript-axios/builds/default/common.ts index 1b1d3a4b7a..bb1c102350 100644 --- a/samples/client/petstore/typescript-axios/builds/default/common.ts +++ b/samples/client/petstore/typescript-axios/builds/default/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/FILES b/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/FILES index 534fae710f..37591a69f7 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/FILES @@ -8,4 +8,5 @@ configuration.ts git_push.sh index.ts package.json +tsconfig.esm.json tsconfig.json diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/api.ts b/samples/client/petstore/typescript-axios/builds/es6-target/api.ts index e6faa73c1a..db555ab3b5 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-axios/builds/es6-target/api.ts @@ -318,7 +318,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -550,11 +550,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -693,11 +693,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -790,11 +790,11 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, }; @@ -900,12 +900,12 @@ export class PetApi extends BaseAPI { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/common.ts b/samples/client/petstore/typescript-axios/builds/es6-target/common.ts index 1b1d3a4b7a..bb1c102350 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/common.ts +++ b/samples/client/petstore/typescript-axios/builds/es6-target/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/package.json b/samples/client/petstore/typescript-axios/builds/es6-target/package.json index dc8188688f..97126b0ed2 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/package.json +++ b/samples/client/petstore/typescript-axios/builds/es6-target/package.json @@ -17,8 +17,10 @@ "license": "Unlicense", "main": "./dist/index.js", "typings": "./dist/index.d.ts", + "module": "./dist/esm/index.js", + "sideEffects": false, "scripts": { - "build": "tsc --outDir dist/", + "build": "tsc && tsc -p tsconfig.esm.json", "prepare": "npm run build" }, "dependencies": { diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/tsconfig.esm.json b/samples/client/petstore/typescript-axios/builds/es6-target/tsconfig.esm.json new file mode 100644 index 0000000000..2c0331cce0 --- /dev/null +++ b/samples/client/petstore/typescript-axios/builds/es6-target/tsconfig.esm.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "esnext", + "outDir": "dist/esm" + } +} diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/tsconfig.json b/samples/client/petstore/typescript-axios/builds/es6-target/tsconfig.json index 1d9d883877..30dc264ec7 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/tsconfig.json +++ b/samples/client/petstore/typescript-axios/builds/es6-target/tsconfig.json @@ -2,10 +2,11 @@ "compilerOptions": { "declaration": true, "target": "ES6", - "module": "ES6", + "module": "commonjs", "noImplicitAny": true, "outDir": "dist", "rootDir": ".", + "moduleResolution": "node", "typeRoots": [ "node_modules/@types" ] diff --git a/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts b/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts index fa54a47c8b..dbaaf075a5 100644 --- a/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts +++ b/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts @@ -793,10 +793,10 @@ export interface FormatTest { 'byte': string; /** * - * @type {any} + * @type {File} * @memberof FormatTest */ - 'binary'?: any; + 'binary'?: File; /** * * @type {string} @@ -2257,7 +2257,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {number} [int64] None * @param {number} [_float] None * @param {string} [string] None - * @param {any} [binary] None + * @param {File} [binary] None * @param {string} [date] None * @param {string} [dateTime] None * @param {string} [password] None @@ -2265,7 +2265,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testEndpointParameters: async (number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options: AxiosRequestConfig = {}): Promise => { + testEndpointParameters: async (number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'number' is not null or undefined assertParamExists('testEndpointParameters', 'number', number) // verify required parameter '_double' is not null or undefined @@ -2410,7 +2410,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) localVarHeaderParameter['enum_header_string_array'] = mapped.join(COLLECTION_FORMATS["csv"]); } - if (enumHeaderString !== undefined && enumHeaderString !== null) { + if (enumHeaderString != null) { localVarHeaderParameter['enum_header_string'] = String(enumHeaderString); } @@ -2487,12 +2487,16 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) localVarQueryParameter['int64_group'] = int64Group; } - if (requiredBooleanGroup !== undefined && requiredBooleanGroup !== null) { - localVarHeaderParameter['required_boolean_group'] = String(JSON.stringify(requiredBooleanGroup)); + if (requiredBooleanGroup != null) { + localVarHeaderParameter['required_boolean_group'] = typeof requiredBooleanGroup === 'string' + ? requiredBooleanGroup + : JSON.stringify(requiredBooleanGroup); } - if (booleanGroup !== undefined && booleanGroup !== null) { - localVarHeaderParameter['boolean_group'] = String(JSON.stringify(booleanGroup)); + if (booleanGroup != null) { + localVarHeaderParameter['boolean_group'] = typeof booleanGroup === 'string' + ? booleanGroup + : JSON.stringify(booleanGroup); } @@ -2768,7 +2772,7 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {number} [int64] None * @param {number} [_float] None * @param {string} [string] None - * @param {any} [binary] None + * @param {File} [binary] None * @param {string} [date] None * @param {string} [dateTime] None * @param {string} [password] None @@ -2776,7 +2780,7 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -2956,7 +2960,7 @@ export const FakeApiFactory = function (configuration?: Configuration, basePath? * @param {number} [int64] None * @param {number} [_float] None * @param {string} [string] None - * @param {any} [binary] None + * @param {File} [binary] None * @param {string} [date] None * @param {string} [dateTime] None * @param {string} [password] None @@ -2964,7 +2968,7 @@ export const FakeApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options?: any): AxiosPromise { + testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: any): AxiosPromise { return localVarFp.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options).then((request) => request(axios, basePath)); }, /** @@ -3156,7 +3160,7 @@ export class FakeApi extends BaseAPI { * @param {number} [int64] None * @param {number} [_float] None * @param {string} [string] None - * @param {any} [binary] None + * @param {File} [binary] None * @param {string} [date] None * @param {string} [dateTime] None * @param {string} [password] None @@ -3165,7 +3169,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig) { + public testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig) { return FakeApiFp(this.configuration).testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options).then((request) => request(this.axios, this.basePath)); } @@ -3502,7 +3506,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -3740,11 +3744,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -3791,12 +3795,12 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * * @summary uploads an image (required) * @param {number} petId ID of pet to update - * @param {any} requiredFile file to upload + * @param {File} requiredFile file to upload * @param {string} [additionalMetadata] Additional data to pass to server * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFileWithRequiredFile: async (petId: number, requiredFile: any, additionalMetadata?: string, options: AxiosRequestConfig = {}): Promise => { + uploadFileWithRequiredFile: async (petId: number, requiredFile: File, additionalMetadata?: string, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFileWithRequiredFile', 'petId', petId) // verify required parameter 'requiredFile' is not null or undefined @@ -3937,11 +3941,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -3949,12 +3953,12 @@ export const PetApiFp = function(configuration?: Configuration) { * * @summary uploads an image (required) * @param {number} petId ID of pet to update - * @param {any} requiredFile file to upload + * @param {File} requiredFile file to upload * @param {string} [additionalMetadata] Additional data to pass to server * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFileWithRequiredFile(petId: number, requiredFile: any, additionalMetadata?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -4047,23 +4051,23 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, /** * * @summary uploads an image (required) * @param {number} petId ID of pet to update - * @param {any} requiredFile file to upload + * @param {File} requiredFile file to upload * @param {string} [additionalMetadata] Additional data to pass to server * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFileWithRequiredFile(petId: number, requiredFile: any, additionalMetadata?: string, options?: any): AxiosPromise { + uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: any): AxiosPromise { return localVarFp.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options).then((request) => request(axios, basePath)); }, }; @@ -4169,12 +4173,12 @@ export class PetApi extends BaseAPI { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } @@ -4182,13 +4186,13 @@ export class PetApi extends BaseAPI { * * @summary uploads an image (required) * @param {number} petId ID of pet to update - * @param {any} requiredFile file to upload + * @param {File} requiredFile file to upload * @param {string} [additionalMetadata] Additional data to pass to server * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFileWithRequiredFile(petId: number, requiredFile: any, additionalMetadata?: string, options?: AxiosRequestConfig) { + public uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/test-petstore/common.ts b/samples/client/petstore/typescript-axios/builds/test-petstore/common.ts index 350af25683..b21850044c 100644 --- a/samples/client/petstore/typescript-axios/builds/test-petstore/common.ts +++ b/samples/client/petstore/typescript-axios/builds/test-petstore/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts b/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts index 6eeef75c6a..384805056f 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts @@ -65,6 +65,20 @@ export interface Category { */ 'name'?: string; } +/** + * + * @export + * @enum {string} + */ + +export const MediaType = { + Json: 'application/json', + Xml: 'application/xml' +} as const; + +export type MediaType = typeof MediaType[keyof typeof MediaType]; + + /** * An order for a pets from the pet store * @export @@ -256,10 +270,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {Pet} pet Pet object that needs to be added to the store * @param {Pet} [header1] * @param {Array} [header2] + * @param {MediaType} [accept] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (pet: Pet, header1?: Pet, header2?: Array, options: AxiosRequestConfig = {}): Promise => { + addPet: async (pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'pet' is not null or undefined assertParamExists('addPet', 'pet', pet) const localVarPath = `/pet`; @@ -278,8 +293,10 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (header1 !== undefined && header1 !== null) { - localVarHeaderParameter['header1'] = String(JSON.stringify(header1)); + if (header1 != null) { + localVarHeaderParameter['header1'] = typeof header1 === 'string' + ? header1 + : JSON.stringify(header1); } if (header2) { @@ -287,6 +304,12 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarHeaderParameter['header2'] = mapped.join(COLLECTION_FORMATS["csv"]); } + if (accept != null) { + localVarHeaderParameter['Accept'] = typeof accept === 'string' + ? accept + : JSON.stringify(accept); + } + localVarHeaderParameter['Content-Type'] = 'application/json'; @@ -329,7 +352,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -561,11 +584,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -624,11 +647,12 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {Pet} pet Pet object that needs to be added to the store * @param {Pet} [header1] * @param {Array} [header2] + * @param {MediaType} [accept] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(pet: Pet, header1?: Pet, header2?: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { - const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(pet, header1, header2, options); + async addPet(pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(pet, header1, header2, accept, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** @@ -706,11 +730,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -730,11 +754,12 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @param {Pet} pet Pet object that needs to be added to the store * @param {Pet} [header1] * @param {Array} [header2] + * @param {MediaType} [accept] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet(pet: Pet, header1?: Pet, header2?: Array, options?: any): AxiosPromise { - return localVarFp.addPet(pet, header1, header2, options).then((request) => request(axios, basePath)); + addPet(pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options?: any): AxiosPromise { + return localVarFp.addPet(pet, header1, header2, accept, options).then((request) => request(axios, basePath)); }, /** * @@ -805,11 +830,11 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, }; @@ -828,12 +853,13 @@ export class PetApi extends BaseAPI { * @param {Pet} pet Pet object that needs to be added to the store * @param {Pet} [header1] * @param {Array} [header2] + * @param {MediaType} [accept] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public addPet(pet: Pet, header1?: Pet, header2?: Array, options?: AxiosRequestConfig) { - return PetApiFp(this.configuration).addPet(pet, header1, header2, options).then((request) => request(this.axios, this.basePath)); + public addPet(pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options?: AxiosRequestConfig) { + return PetApiFp(this.configuration).addPet(pet, header1, header2, accept, options).then((request) => request(this.axios, this.basePath)); } /** @@ -917,12 +943,12 @@ export class PetApi extends BaseAPI { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/common.ts b/samples/client/petstore/typescript-axios/builds/with-complex-headers/common.ts index 1b1d3a4b7a..bb1c102350 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts index 24f390bef9..8f5219697c 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts @@ -573,10 +573,10 @@ export interface FormatTest { 'byte': string; /** * - * @type {any} + * @type {File} * @memberof FormatTest */ - 'binary'?: any; + 'binary'?: File; /** * * @type {string} @@ -1855,7 +1855,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {number} [int64] None * @param {number} [_float] None * @param {string} [string] None - * @param {any} [binary] None + * @param {File} [binary] None * @param {string} [date] None * @param {string} [dateTime] None * @param {string} [password] None @@ -1863,7 +1863,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testEndpointParameters: async (number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options: AxiosRequestConfig = {}): Promise => { + testEndpointParameters: async (number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'number' is not null or undefined assertParamExists('testEndpointParameters', 'number', number) // verify required parameter '_double' is not null or undefined @@ -2008,7 +2008,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) localVarHeaderParameter['enum_header_string_array'] = mapped.join(COLLECTION_FORMATS["csv"]); } - if (enumHeaderString !== undefined && enumHeaderString !== null) { + if (enumHeaderString != null) { localVarHeaderParameter['enum_header_string'] = String(enumHeaderString); } @@ -2085,12 +2085,16 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) localVarQueryParameter['int64_group'] = int64Group; } - if (requiredBooleanGroup !== undefined && requiredBooleanGroup !== null) { - localVarHeaderParameter['required_boolean_group'] = String(JSON.stringify(requiredBooleanGroup)); + if (requiredBooleanGroup != null) { + localVarHeaderParameter['required_boolean_group'] = typeof requiredBooleanGroup === 'string' + ? requiredBooleanGroup + : JSON.stringify(requiredBooleanGroup); } - if (booleanGroup !== undefined && booleanGroup !== null) { - localVarHeaderParameter['boolean_group'] = String(JSON.stringify(booleanGroup)); + if (booleanGroup != null) { + localVarHeaderParameter['boolean_group'] = typeof booleanGroup === 'string' + ? booleanGroup + : JSON.stringify(booleanGroup); } @@ -2400,7 +2404,7 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {number} [int64] None * @param {number} [_float] None * @param {string} [string] None - * @param {any} [binary] None + * @param {File} [binary] None * @param {string} [date] None * @param {string} [dateTime] None * @param {string} [password] None @@ -2408,7 +2412,7 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -2590,7 +2594,7 @@ export const FakeApiFactory = function (configuration?: Configuration, basePath? * @param {number} [int64] None * @param {number} [_float] None * @param {string} [string] None - * @param {any} [binary] None + * @param {File} [binary] None * @param {string} [date] None * @param {string} [dateTime] None * @param {string} [password] None @@ -2598,7 +2602,7 @@ export const FakeApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options?: any): AxiosPromise { + testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: any): AxiosPromise { return localVarFp.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options).then((request) => request(axios, basePath)); }, /** @@ -2789,7 +2793,7 @@ export class FakeApi extends BaseAPI { * @param {number} [int64] None * @param {number} [_float] None * @param {string} [string] None - * @param {any} [binary] None + * @param {File} [binary] None * @param {string} [date] None * @param {string} [dateTime] None * @param {string} [password] None @@ -2798,7 +2802,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig) { + public testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig) { return FakeApiFp(this.configuration).testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options).then((request) => request(this.axios, this.basePath)); } @@ -3147,7 +3151,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -3385,11 +3389,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -3436,12 +3440,12 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * * @summary uploads an image (required) * @param {number} petId ID of pet to update - * @param {any} requiredFile file to upload + * @param {File} requiredFile file to upload * @param {string} [additionalMetadata] Additional data to pass to server * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFileWithRequiredFile: async (petId: number, requiredFile: any, additionalMetadata?: string, options: AxiosRequestConfig = {}): Promise => { + uploadFileWithRequiredFile: async (petId: number, requiredFile: File, additionalMetadata?: string, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFileWithRequiredFile', 'petId', petId) // verify required parameter 'requiredFile' is not null or undefined @@ -3582,11 +3586,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -3594,12 +3598,12 @@ export const PetApiFp = function(configuration?: Configuration) { * * @summary uploads an image (required) * @param {number} petId ID of pet to update - * @param {any} requiredFile file to upload + * @param {File} requiredFile file to upload * @param {string} [additionalMetadata] Additional data to pass to server * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFileWithRequiredFile(petId: number, requiredFile: any, additionalMetadata?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -3692,23 +3696,23 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, /** * * @summary uploads an image (required) * @param {number} petId ID of pet to update - * @param {any} requiredFile file to upload + * @param {File} requiredFile file to upload * @param {string} [additionalMetadata] Additional data to pass to server * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFileWithRequiredFile(petId: number, requiredFile: any, additionalMetadata?: string, options?: any): AxiosPromise { + uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: any): AxiosPromise { return localVarFp.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options).then((request) => request(axios, basePath)); }, }; @@ -3814,12 +3818,12 @@ export class PetApi extends BaseAPI { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } @@ -3827,13 +3831,13 @@ export class PetApi extends BaseAPI { * * @summary uploads an image (required) * @param {number} petId ID of pet to update - * @param {any} requiredFile file to upload + * @param {File} requiredFile file to upload * @param {string} [additionalMetadata] Additional data to pass to server * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFileWithRequiredFile(petId: number, requiredFile: any, additionalMetadata?: string, options?: AxiosRequestConfig) { + public uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/common.ts b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/common.ts index 350af25683..b21850044c 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts b/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts index 367b5114e2..abf5cffb90 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts @@ -318,7 +318,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -550,11 +550,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -693,11 +693,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -790,11 +790,11 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, }; @@ -885,12 +885,12 @@ export interface PetApiInterface { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApiInterface */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): AxiosPromise; + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): AxiosPromise; } @@ -994,12 +994,12 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/common.ts b/samples/client/petstore/typescript-axios/builds/with-interfaces/common.ts index 1b1d3a4b7a..bb1c102350 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/with-node-imports/api.ts b/samples/client/petstore/typescript-axios/builds/with-node-imports/api.ts index ddc20affd1..090c0b0a44 100644 --- a/samples/client/petstore/typescript-axios/builds/with-node-imports/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-node-imports/api.ts @@ -322,7 +322,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -554,11 +554,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -697,11 +697,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -794,11 +794,11 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, }; @@ -904,12 +904,12 @@ export class PetApi extends BaseAPI { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-node-imports/common.ts b/samples/client/petstore/typescript-axios/builds/with-node-imports/common.ts index 56fdbc9e25..60db95f613 100644 --- a/samples/client/petstore/typescript-axios/builds/with-node-imports/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-node-imports/common.ts @@ -84,24 +84,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts index a5baf3f11d..904915d276 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts @@ -98,7 +98,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -330,11 +330,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -473,11 +473,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -570,11 +570,11 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, }; @@ -680,12 +680,12 @@ export class PetApi extends BaseAPI { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/common.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/common.ts index 1b1d3a4b7a..bb1c102350 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/model/some/levels/deep/pet.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/model/some/levels/deep/pet.ts index e32493df73..bb1cab2e56 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/model/some/levels/deep/pet.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/model/some/levels/deep/pet.ts @@ -13,7 +13,11 @@ */ +// May contain unused imports in some cases +// @ts-ignore import { Category } from './category'; +// May contain unused imports in some cases +// @ts-ignore import { Tag } from './tag'; /** diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json index dc8188688f..d64b81bc9c 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json @@ -18,7 +18,7 @@ "main": "./dist/index.js", "typings": "./dist/index.d.ts", "scripts": { - "build": "tsc --outDir dist/", + "build": "tsc ", "prepare": "npm run build" }, "dependencies": { diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/tsconfig.json b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/tsconfig.json index 383a290d8b..d953a374d8 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/tsconfig.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "declaration": true, "target": "ES5", - "module": "CommonJS", + "module": "commonjs", "noImplicitAny": true, "outDir": "dist", "rootDir": ".", diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts index e6faa73c1a..db555ab3b5 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts @@ -318,7 +318,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -550,11 +550,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -693,11 +693,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -790,11 +790,11 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, }; @@ -900,12 +900,12 @@ export class PetApi extends BaseAPI { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/common.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version/common.ts index 1b1d3a4b7a..bb1c102350 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json b/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json index dc8188688f..d64b81bc9c 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json @@ -18,7 +18,7 @@ "main": "./dist/index.js", "typings": "./dist/index.d.ts", "scripts": { - "build": "tsc --outDir dist/", + "build": "tsc ", "prepare": "npm run build" }, "dependencies": { diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/tsconfig.json b/samples/client/petstore/typescript-axios/builds/with-npm-version/tsconfig.json index 383a290d8b..d953a374d8 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/tsconfig.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "declaration": true, "target": "ES5", - "module": "CommonJS", + "module": "commonjs", "noImplicitAny": true, "outDir": "dist", "rootDir": ".", diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts index 456715e544..47941dd23e 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts @@ -318,7 +318,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -550,11 +550,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -693,11 +693,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -790,11 +790,11 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, }; @@ -941,10 +941,10 @@ export interface PetApiUploadFileRequest { /** * file to upload - * @type {any} + * @type {File} * @memberof PetApiUploadFile */ - readonly file?: any + readonly file?: File } /** diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/common.ts b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/common.ts index 1b1d3a4b7a..bb1c102350 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/client/petstore/typescript-axios/builds/with-string-enums/api.ts b/samples/client/petstore/typescript-axios/builds/with-string-enums/api.ts index 7ccec3de05..f148034523 100644 --- a/samples/client/petstore/typescript-axios/builds/with-string-enums/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-string-enums/api.ts @@ -322,7 +322,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) // oauth required await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration) - if (apiKey !== undefined && apiKey !== null) { + if (apiKey != null) { localVarHeaderParameter['api_key'] = String(apiKey); } @@ -554,11 +554,11 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -697,11 +697,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, @@ -794,11 +794,11 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise { + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: any): AxiosPromise { return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath)); }, }; @@ -904,12 +904,12 @@ export class PetApi extends BaseAPI { * @summary uploads an image * @param {number} petId ID of pet to update * @param {string} [additionalMetadata] Additional data to pass to server - * @param {any} [file] file to upload + * @param {File} [file] file to upload * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-string-enums/common.ts b/samples/client/petstore/typescript-axios/builds/with-string-enums/common.ts index 1b1d3a4b7a..bb1c102350 100644 --- a/samples/client/petstore/typescript-axios/builds/with-string-enums/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-string-enums/common.ts @@ -83,24 +83,34 @@ export const setOAuthToObject = async function (object: any, name: string, scope } } +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + /** * * @export */ export const setSearchParams = function (url: URL, ...objects: any[]) { const searchParams = new URLSearchParams(url.search); - for (const object of objects) { - for (const key in object) { - if (Array.isArray(object[key])) { - searchParams.delete(key); - for (const item of object[key]) { - searchParams.append(key, item); - } - } else { - searchParams.set(key, object[key]); - } - } - } + setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); } diff --git a/samples/openapi3/client/petstore/python-experimental/.openapi-generator-ignore b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator-ignore similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/.openapi-generator-ignore rename to samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator-ignore diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/FILES b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/FILES new file mode 100644 index 0000000000..4036fef518 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/FILES @@ -0,0 +1,7 @@ +apis/DefaultApi.ts +apis/index.ts +index.ts +models/Club.ts +models/Owner.ts +models/index.ts +runtime.ts diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/apis/DefaultApi.ts b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/apis/DefaultApi.ts new file mode 100644 index 0000000000..416fd54366 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/apis/DefaultApi.ts @@ -0,0 +1,62 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import type { + Club, +} from '../models'; +import { + ClubFromJSON, + ClubToJSON, +} from '../models'; + +export interface ListRequest { + personId: string; +} + +/** + * + */ +export class DefaultApi extends runtime.BaseAPI { + + /** + */ + async listRaw(requestParameters: ListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + if (requestParameters.personId === null || requestParameters.personId === undefined) { + throw new runtime.RequiredError('personId','Required parameter requestParameters.personId was null or undefined when calling list.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/person/display/{personId}`.replace(`{${"personId"}}`, encodeURIComponent(String(requestParameters.personId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ClubFromJSON(jsonValue)); + } + + /** + */ + async list(requestParameters: ListRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.listRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/apis/index.ts b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/apis/index.ts new file mode 100644 index 0000000000..69c44c00fa --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/apis/index.ts @@ -0,0 +1,3 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './DefaultApi'; diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/index.ts b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/index.ts new file mode 100644 index 0000000000..be9d1edeef --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/index.ts @@ -0,0 +1,5 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './runtime'; +export * from './apis'; +export * from './models'; diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/Club.ts b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/Club.ts new file mode 100644 index 0000000000..d2e7090090 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/Club.ts @@ -0,0 +1,71 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +import type { Owner } from './Owner'; +import { + OwnerFromJSON, + OwnerFromJSONTyped, + OwnerToJSON, +} from './Owner'; + +/** + * + * @export + * @interface Club + */ +export interface Club { + /** + * + * @type {Owner} + * @memberof Club + */ + readonly owner?: Owner; +} + +/** + * Check if a given object implements the Club interface. + */ +export function instanceOfClub(value: object): boolean { + let isInstance = true; + + return isInstance; +} + +export function ClubFromJSON(json: any): Club { + return ClubFromJSONTyped(json, false); +} + +export function ClubFromJSONTyped(json: any, ignoreDiscriminator: boolean): Club { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'owner': !exists(json, 'owner') ? undefined : OwnerFromJSON(json['owner']), + }; +} + +export function ClubToJSON(value?: Club | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + }; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/ClubOwner.ts b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/ClubOwner.ts new file mode 100644 index 0000000000..bea129ceed --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/ClubOwner.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * + * @export + * @interface ClubOwner + */ +export interface ClubOwner { + /** + * + * @type {string} + * @memberof ClubOwner + */ + name?: string; +} + +/** + * Check if a given object implements the ClubOwner interface. + */ +export function instanceOfClubOwner(value: object): boolean { + let isInstance = true; + + return isInstance; +} + +export function ClubOwnerFromJSON(json: any): ClubOwner { + return ClubOwnerFromJSONTyped(json, false); +} + +export function ClubOwnerFromJSONTyped(json: any, ignoreDiscriminator: boolean): ClubOwner { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function ClubOwnerToJSON(value?: ClubOwner | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'name': value.name, + }; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/Owner.ts b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/Owner.ts new file mode 100644 index 0000000000..70542125af --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/Owner.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { exists, mapValues } from '../runtime'; +/** + * + * @export + * @interface Owner + */ +export interface Owner { + /** + * + * @type {string} + * @memberof Owner + */ + name?: string; +} + +/** + * Check if a given object implements the Owner interface. + */ +export function instanceOfOwner(value: object): boolean { + let isInstance = true; + + return isInstance; +} + +export function OwnerFromJSON(json: any): Owner { + return OwnerFromJSONTyped(json, false); +} + +export function OwnerFromJSONTyped(json: any, ignoreDiscriminator: boolean): Owner { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function OwnerToJSON(value?: Owner | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'name': value.name, + }; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/index.ts b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/index.ts new file mode 100644 index 0000000000..c5f449053c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/models/index.ts @@ -0,0 +1,4 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './Club'; +export * from './Owner'; diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/runtime.ts b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/runtime.ts new file mode 100644 index 0000000000..cca25bd21c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/runtime.ts @@ -0,0 +1,407 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Example + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const BASE_PATH = "http://api.example.xyz/v1".replace(/\/+$/, ""); + +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | ((name: string) => string); // parameter for apiKey security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + set config(configuration: Configuration) { + this.configuration = configuration; + } + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI | undefined { + return this.configuration.fetchApi; + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : async () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export const DefaultConfig = new Configuration(); + +/** + * This is the base class for all generated API classes. + */ +export class BaseAPI { + + private middleware: Middleware[]; + + constructor(protected configuration = DefaultConfig) { + this.middleware = configuration.middleware; + } + + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; + } + + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); + } + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + const middlewares = postMiddlewares.map((post) => ({ post })); + return this.withMiddleware(...middlewares); + } + + protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { + const { url, init } = await this.createFetchParams(context, initOverrides); + const response = await this.fetchApi(url, init); + if (response && (response.status >= 200 && response.status < 300)) { + return response; + } + throw new ResponseError(response, 'Response returned an error code'); + } + + private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) { + let url = this.configuration.basePath + context.path; + if (context.query !== undefined && Object.keys(context.query).length !== 0) { + // only add the querystring to the URL if there are query parameters. + // this is done to avoid urls ending with a "?" character which buggy webservers + // do not handle correctly sometimes. + url += '?' + this.configuration.queryParamsStringify(context.query); + } + + const headers = Object.assign({}, this.configuration.headers, context.headers); + Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {}); + + const initOverrideFn = + typeof initOverrides === "function" + ? initOverrides + : async () => initOverrides; + + const initParams = { + method: context.method, + headers, + body: context.body, + credentials: this.configuration.credentials, + }; + + const overridedInit: RequestInit = { + ...initParams, + ...(await initOverrideFn({ + init: initParams, + context, + })) + } + + const init: RequestInit = { + ...overridedInit, + body: + isFormData(overridedInit.body) || + overridedInit.body instanceof URLSearchParams || + isBlob(overridedInit.body) + ? overridedInit.body + : JSON.stringify(overridedInit.body), + }; + + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response = undefined; + try { + response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init); + } catch (e) { + for (const middleware of this.middleware) { + if (middleware.onError) { + response = await middleware.onError({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + error: e, + response: response ? response.clone() : undefined, + }) || response; + } + } + if (response === undefined) { + if (e instanceof Error) { + throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } + } + } + for (const middleware of this.middleware) { + if (middleware.post) { + response = await middleware.post({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of `this` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; + +function isBlob(value: any): value is Blob { + return typeof Blob !== 'undefined' && value instanceof Blob +} + +function isFormData(value: any): value is FormData { + return typeof FormData !== "undefined" && value instanceof FormData +} + +export class ResponseError extends Error { + override name: "ResponseError" = "ResponseError"; + constructor(public response: Response, msg?: string) { + super(msg); + } +} + +export class FetchError extends Error { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { + super(msg); + } +} + +export class RequiredError extends Error { + override name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } +} + +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; + +export type Json = any; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; +export type HTTPHeaders = { [key: string]: string }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | Set | HTTPQuery }; +export type HTTPBody = Json | FormData | URLSearchParams; +export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody } +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; + +export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise + +export interface FetchParams { + url: string; + init: RequestInit; +} + +export interface RequestOpts { + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; +} + +export function exists(json: any, key: string) { + const value = json[key]; + return value !== null && value !== undefined; +} + +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map(key => querystringSingleKey(key, params[key], prefix)) + .filter(part => part.length > 0) + .join('&'); +} + +function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array | Set | HTTPQuery, keyPrefix: string = ''): string { + const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key); + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(`&${encodeURIComponent(fullKey)}=`); + return `${encodeURIComponent(fullKey)}=${multiValue}`; + } + if (value instanceof Set) { + const valueAsArray = Array.from(value); + return querystringSingleKey(key, valueAsArray, keyPrefix); + } + if (value instanceof Date) { + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; +} + +export function mapValues(data: any, fn: (item: any) => any) { + return Object.keys(data).reduce( + (acc, key) => ({ ...acc, [key]: fn(data[key]) }), + {} + ); +} + +export function canConsumeForm(consumes: Consume[]): boolean { + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } + } + return false; +} + +export interface Consume { + contentType: string +} + +export interface RequestContext { + fetch: FetchAPI; + url: string; + init: RequestInit; +} + +export interface ResponseContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; +} + +export interface ErrorContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + error: unknown; + response?: Response; +} + +export interface Middleware { + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; + onError?(context: ErrorContext): Promise; +} + +export interface ApiResponse { + raw: Response; + value(): Promise; +} + +export interface ResponseTransformer { + (json: any): T; +} + +export class JSONApiResponse { + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} + + async value(): Promise { + return this.transformer(await this.raw.json()); + } +} + +export class VoidApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return undefined; + } +} + +export class BlobApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.blob(); + }; +} + +export class TextApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.text(); + }; +} diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/AllOfWithSingleRef.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/AllOfWithSingleRef.ts index 61f2a287c8..13958e2ab7 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/AllOfWithSingleRef.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/AllOfWithSingleRef.ts @@ -37,7 +37,7 @@ export interface AllOfWithSingleRef { * @type {SingleRefType} * @memberof AllOfWithSingleRef */ - singleRefType?: SingleRefType | null; + singleRefType?: SingleRefType; } /** diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Pet.ts index f7dc974411..33e2b6db79 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Pet.ts @@ -124,7 +124,7 @@ export function PetToJSON(value?: Pet | null): any { 'id': value.id, 'category': CategoryToJSON(value.category), 'name': value.name, - 'photoUrls': value.photoUrls, + 'photoUrls': Array.from(value.photoUrls as Set), 'tags': value.tags === undefined ? undefined : ((value.tags as Array).map(TagToJSON)), 'status': value.status, }; diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts index 699a8bc46f..cbae0bc962 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/default/runtime.ts b/samples/client/petstore/typescript-fetch/builds/default/runtime.ts index ec8bf8b7c5..faf417ca72 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts b/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts index c3bbbbc6cf..aa6210e382 100644 --- a/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts index ec8bf8b7c5..faf417ca72 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts index ec8bf8b7c5..faf417ca72 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts index ec8bf8b7c5..faf417ca72 100644 --- a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts index ec8bf8b7c5..faf417ca72 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts index ec8bf8b7c5..faf417ca72 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts index ec8bf8b7c5..faf417ca72 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/with-string-enums/runtime.ts b/samples/client/petstore/typescript-fetch/builds/with-string-enums/runtime.ts index c3bbbbc6cf..aa6210e382 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-string-enums/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-string-enums/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts index 18b00f8985..13991f0072 100644 --- a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts @@ -116,7 +116,7 @@ export class BaseAPI { protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); - if (response.status >= 200 && response.status < 300) { + if (response && (response.status >= 200 && response.status < 300)) { return response; } throw new ResponseError(response, 'Response returned an error code'); @@ -193,7 +193,11 @@ export class BaseAPI { } } if (response === undefined) { + if (e instanceof Error) { throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } } } for (const middleware of this.middleware) { @@ -230,21 +234,21 @@ function isFormData(value: any): value is FormData { } export class ResponseError extends Error { - name: "ResponseError" = "ResponseError"; + override name: "ResponseError" = "ResponseError"; constructor(public response: Response, msg?: string) { super(msg); } } export class FetchError extends Error { - name: "FetchError" = "FetchError"; - constructor(public cause: unknown, msg?: string) { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { super(msg); } } export class RequiredError extends Error { - name: "RequiredError" = "RequiredError"; + override name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } diff --git a/samples/client/petstore/typescript-jquery/default/api/PetApi.ts b/samples/client/petstore/typescript-jquery/default/api/PetApi.ts index 4985ab1307..eb9f34587b 100644 --- a/samples/client/petstore/typescript-jquery/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-jquery/default/api/PetApi.ts @@ -584,7 +584,7 @@ export class PetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise< + public uploadFile(petId: number, additionalMetadata?: string, file?: File, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise< { response: JQueryXHR; body: models.ApiResponse; }, { response: JQueryXHR; errorThrown: string } > { diff --git a/samples/client/petstore/typescript-jquery/npm/api/PetApi.ts b/samples/client/petstore/typescript-jquery/npm/api/PetApi.ts index 4985ab1307..eb9f34587b 100644 --- a/samples/client/petstore/typescript-jquery/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-jquery/npm/api/PetApi.ts @@ -584,7 +584,7 @@ export class PetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: any, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise< + public uploadFile(petId: number, additionalMetadata?: string, file?: File, extraJQueryAjaxSettings?: JQueryAjaxSettings): JQuery.Promise< { response: JQueryXHR; body: models.ApiResponse; }, { response: JQueryXHR; errorThrown: string } > { diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.gitignore b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.gitignore new file mode 100644 index 0000000000..149b576547 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/server/petstore/cpp-restbed/.openapi-generator-ignore b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator-ignore similarity index 100% rename from samples/server/petstore/cpp-restbed/.openapi-generator-ignore rename to samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator-ignore diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/FILES new file mode 100644 index 0000000000..d51e5a9a8b --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/FILES @@ -0,0 +1,22 @@ +.gitignore +README.md +api.module.ts +api/api.ts +api/pet.service.ts +api/store.service.ts +api/user.service.ts +configuration.ts +git_push.sh +index.ts +model/apiResponse.ts +model/category.ts +model/models.ts +model/order.ts +model/pet.ts +model/tag.ts +model/user.ts +package.json +tsconfig.build.json +tsconfig.json +tslint.json +variables.ts diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/README.md b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/README.md new file mode 100644 index 0000000000..fc0ff642c3 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/README.md @@ -0,0 +1,137 @@ +## @openapitools/typescript-nestjs-petstore@1.0.0 + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +#### General usage + +In your Nestjs project: + + +``` +// without configuring providers +import { ApiModule } from '@openapitools/typescript-nestjs-petstore'; +import { HttpModule } from '@nestjs/axios'; + +@Module({ + imports: [ + ApiModule, + HttpModule + ], + providers: [] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from '@openapitools/typescript-nestjs-petstore'; + +export function apiConfigFactory (): Configuration => { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@Module({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from '@openapitools/typescript-nestjs-petstore'; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule a dynamic module and instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple swagger files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different swagger files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpModule } from '@nestjs/axios'; + +@Module({ + imports: [ + ApiModule, + OtherApiModule, + HttpModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from '@openapitools/typescript-nestjs-petstore'; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from '@openapitools/typescript-nestjs-petstore'; + +@Module({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @nestjs/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from '@openapitools/typescript-nestjs-petstore'; +import { environment } from '../environments/environment'; + +@Module({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [ + { + provide: 'BASE_PATH', + useValue: environment.API_BASE_PATH + } + ] +}) +export class AppModule { } +``` diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api.module.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api.module.ts new file mode 100644 index 0000000000..394d158b29 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api.module.ts @@ -0,0 +1,32 @@ +import { DynamicModule, Module, Global } from '@nestjs/common'; +import { HttpModule, HttpService } from '@nestjs/axios'; +import { Configuration } from './configuration'; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +@Global() +@Module({ + imports: [ HttpModule ], + exports: [ + PetService, + StoreService, + UserService + ], + providers: [ + PetService, + StoreService, + UserService + ] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): DynamicModule { + return { + module: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( httpService: HttpService) { } +} diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/api.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/api.ts new file mode 100644 index 0000000000..8e44b64083 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/pet.service.ts new file mode 100644 index 0000000000..115e76e75a --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/pet.service.ts @@ -0,0 +1,475 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@nestjs/common'; +import { HttpService } from '@nestjs/axios'; +import { AxiosResponse } from 'axios'; +import { Observable } from 'rxjs'; +import { ApiResponse } from '../model/apiResponse'; +import { Pet } from '../model/pet'; +import { Configuration } from '../configuration'; + + +@Injectable() +export class PetService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders: Record = {}; + public configuration = new Configuration(); + + constructor(protected httpClient: HttpService, @Optional() configuration: Configuration) { + this.configuration = configuration || this.configuration; + this.basePath = configuration?.basePath || this.basePath; + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + return consumes.includes(form); + } + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public addPet(pet: Pet, ): Observable>; + public addPet(pet: Pet, ): Observable { + + if (pet === null || pet === undefined) { + throw new Error('Required parameter pet was null or undefined when calling addPet.'); + } + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers['Content-Type'] = httpContentTypeSelected; + } + return this.httpClient.post(`${this.basePath}/pet`, + pet, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deletePet(petId: number, apiKey?: string, ): Observable>; + public deletePet(petId: number, apiKey?: string, ): Observable { + + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + + let headers = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + headers['api_key'] = String(apiKey); + } + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, ): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, ): Observable { + + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let queryParameters = {}; + if (status) { + queryParameters['status'] = status.join(COLLECTION_FORMATS['csv']); + } + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.get>(`${this.basePath}/pet/findByStatus`, + { + params: queryParameters, + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public findPetsByTags(tags: Array, ): Observable>>; + public findPetsByTags(tags: Array, ): Observable { + + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let queryParameters = {}; + if (tags) { + queryParameters['tags'] = tags.join(COLLECTION_FORMATS['csv']); + } + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.get>(`${this.basePath}/pet/findByTags`, + { + params: queryParameters, + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPetById(petId: number, ): Observable>; + public getPetById(petId: number, ): Observable { + + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers['api_key'] = this.configuration.apiKeys["api_key"]; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePet(pet: Pet, ): Observable>; + public updatePet(pet: Pet, ): Observable { + + if (pet === null || pet === undefined) { + throw new Error('Required parameter pet was null or undefined when calling updatePet.'); + } + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers['Content-Type'] = httpContentTypeSelected; + } + return this.httpClient.put(`${this.basePath}/pet`, + pet, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePetWithForm(petId: number, name?: string, status?: string, ): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, ): Observable { + + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): void; }; + let useForm = false; + let convertFormParamsToString = false; + if (useForm) { + formParams = new FormData(); + } else { + // formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); + } + + if (name !== undefined) { + formParams.append('name', name); + } + + if (status !== undefined) { + formParams.append('status', status); + } + + return this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, + convertFormParamsToString ? formParams.toString() : formParams, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, ): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, ): Observable { + + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + + + let headers = this.defaultHeaders; + + // authentication (petstore_auth) required + if (this.configuration.accessToken) { + const accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers['Authorization'] = 'Bearer ' + accessToken; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): void; }; + let useForm = false; + let convertFormParamsToString = false; + + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + useForm = canConsumeForm; + if (useForm) { + formParams = new FormData(); + } else { + // formParams = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); + } + + if (additionalMetadata !== undefined) { + formParams.append('additionalMetadata', additionalMetadata); + } + + if (file !== undefined) { + formParams.append('file', file); + } + + return this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, + convertFormParamsToString ? formParams.toString() : formParams, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } +} diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/store.service.ts new file mode 100644 index 0000000000..29110b427e --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/store.service.ts @@ -0,0 +1,190 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@nestjs/common'; +import { HttpService } from '@nestjs/axios'; +import { AxiosResponse } from 'axios'; +import { Observable } from 'rxjs'; +import { Order } from '../model/order'; +import { Configuration } from '../configuration'; + + +@Injectable() +export class StoreService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders: Record = {}; + public configuration = new Configuration(); + + constructor(protected httpClient: HttpService, @Optional() configuration: Configuration) { + this.configuration = configuration || this.configuration; + this.basePath = configuration?.basePath || this.basePath; + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + return consumes.includes(form); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteOrder(orderId: string, ): Observable>; + public deleteOrder(orderId: string, ): Observable { + + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.delete(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInventory(): Observable>; + public getInventory(): Observable { + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers['api_key'] = this.configuration.apiKeys["api_key"]; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.get<{ [key: string]: number; }>(`${this.basePath}/store/inventory`, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrderById(orderId: number, ): Observable>; + public getOrderById(orderId: number, ): Observable { + + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.get(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public placeOrder(order: Order, ): Observable>; + public placeOrder(order: Order, ): Observable { + + if (order === null || order === undefined) { + throw new Error('Required parameter order was null or undefined when calling placeOrder.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers['Content-Type'] = httpContentTypeSelected; + } + return this.httpClient.post(`${this.basePath}/store/order`, + order, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } +} diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/user.service.ts new file mode 100644 index 0000000000..265fceafa2 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api/user.service.ts @@ -0,0 +1,387 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@nestjs/common'; +import { HttpService } from '@nestjs/axios'; +import { AxiosResponse } from 'axios'; +import { Observable } from 'rxjs'; +import { User } from '../model/user'; +import { Configuration } from '../configuration'; + + +@Injectable() +export class UserService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders: Record = {}; + public configuration = new Configuration(); + + constructor(protected httpClient: HttpService, @Optional() configuration: Configuration) { + this.configuration = configuration || this.configuration; + this.basePath = configuration?.basePath || this.basePath; + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + return consumes.includes(form); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUser(user: User, ): Observable>; + public createUser(user: User, ): Observable { + + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUser.'); + } + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers['api_key'] = this.configuration.apiKeys["api_key"]; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers['Content-Type'] = httpContentTypeSelected; + } + return this.httpClient.post(`${this.basePath}/user`, + user, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Creates list of users with given input array + * + * @param user List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithArrayInput(user: Array, ): Observable>; + public createUsersWithArrayInput(user: Array, ): Observable { + + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUsersWithArrayInput.'); + } + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers['api_key'] = this.configuration.apiKeys["api_key"]; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers['Content-Type'] = httpContentTypeSelected; + } + return this.httpClient.post(`${this.basePath}/user/createWithArray`, + user, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Creates list of users with given input array + * + * @param user List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithListInput(user: Array, ): Observable>; + public createUsersWithListInput(user: Array, ): Observable { + + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling createUsersWithListInput.'); + } + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers['api_key'] = this.configuration.apiKeys["api_key"]; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers['Content-Type'] = httpContentTypeSelected; + } + return this.httpClient.post(`${this.basePath}/user/createWithList`, + user, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteUser(username: string, ): Observable>; + public deleteUser(username: string, ): Observable { + + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers['api_key'] = this.configuration.apiKeys["api_key"]; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.delete(`${this.basePath}/user/${encodeURIComponent(String(username))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getUserByName(username: string, ): Observable>; + public getUserByName(username: string, ): Observable { + + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.get(`${this.basePath}/user/${encodeURIComponent(String(username))}`, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public loginUser(username: string, password: string, ): Observable>; + public loginUser(username: string, password: string, ): Observable { + + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let queryParameters = {}; + if (username !== undefined && username !== null) { + queryParameters['username'] = username; + } + if (password !== undefined && password !== null) { + queryParameters['password'] = password; + } + + let headers = this.defaultHeaders; + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.get(`${this.basePath}/user/login`, + { + params: queryParameters, + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Logs out current logged in user session + * + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logoutUser(): Observable>; + public logoutUser(): Observable { + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers['api_key'] = this.configuration.apiKeys["api_key"]; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + return this.httpClient.get(`${this.basePath}/user/logout`, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param user Updated user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateUser(username: string, user: User, ): Observable>; + public updateUser(username: string, user: User, ): Observable { + + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + + if (user === null || user === undefined) { + throw new Error('Required parameter user was null or undefined when calling updateUser.'); + } + + let headers = this.defaultHeaders; + + // authentication (api_key) required + if (this.configuration.apiKeys["api_key"]) { + headers['api_key'] = this.configuration.apiKeys["api_key"]; + } + + // to determine the Accept header + let httpHeaderAccepts: string[] = [ + ]; + const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAcceptSelected != undefined) { + headers['Accept'] = httpHeaderAcceptSelected; + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected != undefined) { + headers['Content-Type'] = httpContentTypeSelected; + } + return this.httpClient.put(`${this.basePath}/user/${encodeURIComponent(String(username))}`, + user, + { + withCredentials: this.configuration.withCredentials, + headers: headers + } + ); + } +} diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/configuration.ts new file mode 100644 index 0000000000..82e8458f39 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/configuration.ts @@ -0,0 +1,79 @@ +export interface ConfigurationParameters { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} + +export class Configuration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length == 0) { + return undefined; + } + + let type = contentTypes.find(x => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length == 0) { + return undefined; + } + + let type = accepts.find(x => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime != null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } +} diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/git_push.sh b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/index.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/index.ts new file mode 100644 index 0000000000..c312b70fa3 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/index.ts @@ -0,0 +1,5 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/apiResponse.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/apiResponse.ts new file mode 100644 index 0000000000..682ba47892 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/apiResponse.ts @@ -0,0 +1,22 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/category.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/category.ts new file mode 100644 index 0000000000..b988b6827a --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/category.ts @@ -0,0 +1,21 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/models.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/models.ts new file mode 100644 index 0000000000..8607c5dabd --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/order.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/order.ts new file mode 100644 index 0000000000..a29bebe490 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/order.ts @@ -0,0 +1,37 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: string; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/pet.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/pet.ts new file mode 100644 index 0000000000..e0404395f9 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/pet.ts @@ -0,0 +1,39 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/tag.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/tag.ts new file mode 100644 index 0000000000..b6ff210e8d --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/tag.ts @@ -0,0 +1,21 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/user.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/user.ts new file mode 100644 index 0000000000..fce5100530 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/model/user.ts @@ -0,0 +1,30 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/package.json b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/package.json new file mode 100644 index 0000000000..c49a0a25b9 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/package.json @@ -0,0 +1,73 @@ +{ + "name": "@openapitools/typescript-nestjs-petstore", + "version": "1.0.0", + "description": "REST client for @openapitools/typescript-nestjs-petstore", + "author": "OpenAPI Generator Contributors", + "repository": { + "type": "git", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + }, + "keywords": [ + "swagger-client" + ], + "license": "Unlicense", + "scripts": { + "build": "tsc -p tsconfig.build.json", + "build:clean": "rm -rf dist/ 2> /dev/null && tsc -p tsconfig.build.json", + "format": "prettier --write \"src/**/*.ts\"", + "start": "ts-node -r tsconfig-paths/register src/main.ts", + "start:dev": "concurrently --handle-input \"wait-on dist/main.js && nodemon\" \"tsc -w -p tsconfig.build.json\" ", + "start:debug": "nodemon --config nodemon-debug.json", + "prestart:prod": "rimraf dist && npm run build", + "start:prod": "node dist/main.js", + "lint": "tslint -p tsconfig.json -c tslint.json", + "lint:fix": "tslint -p tsconfig.json -c tslint.json --fix --force", + "test": "jest", + "test:watch": "jest --watch", + "test:cov": "jest --coverage", + "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", + "test:e2e": "jest --config ./test/jest-e2e.json" + }, + "dependencies": { + "@nestjs/common": "^8.0.0", + "@nestjs/core": "^8.0.0", + "@nestjs/platform-express": "^8.0.0", + "reflect-metadata": "^0.1.13", + "rimraf": "^2.6.3", + "rxjs": "^6.5.2" + }, + "devDependencies": { + "@nestjs/testing": "~8.0.0", + "@types/express": "^4.16.0", + "@types/jest": "^24.0.15", + "@types/node": "^12.6.1", + "@types/supertest": "^2.0.8", + "concurrently": "^4.1.1", + "nodemon": "^1.19.1", + "prettier": "^1.18.2", + "supertest": "^4.0.2", + "ts-jest": "24.0.2", + "ts-node": "8.3.0", + "tsconfig-paths": "3.8.0", + "tslint": "5.18.0", + "typescript": "^4.0", + "wait-on": "^3.2.0" + }, + "jest": { + "moduleFileExtensions": [ + "js", + "json", + "ts" + ], + "rootDir": "src", + "testRegex": ".spec.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + }, + "coverageDirectory": "../coverage", + "testEnvironment": "node" + }, + "publishConfig": { + "registry": "https://skimdb.npmjs.com/registry" + } +} diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/tsconfig.build.json b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/tsconfig.build.json new file mode 100644 index 0000000000..77f0c6a75e --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "exclude": [ + "node_modules", + "test", + "dist", + "**/*spec.ts" + ] + } \ No newline at end of file diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/tsconfig.json b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/tsconfig.json new file mode 100644 index 0000000000..c71e17c1b8 --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "declaration": true, + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es5", + "sourceMap": true, + "outDir": "./dist", + "baseUrl": "./", + "incremental": true + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] +} diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/tslint.json b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/tslint.json new file mode 100644 index 0000000000..5651b2f3db --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/tslint.json @@ -0,0 +1,18 @@ +{ + "defaultSeverity": "error", + "extends": ["tslint:recommended"], + "jsRules": { + "no-unused-expression": true + }, + "rules": { + "quotemark": [true, "single"], + "member-access": [false], + "ordered-imports": [false], + "max-line-length": [true, 150], + "member-ordering": [false], + "interface-name": [false], + "arrow-parens": false, + "object-literal-sort-keys": false + }, + "rulesDirectory": [] +} diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/variables.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/variables.ts new file mode 100644 index 0000000000..d52a33f70e --- /dev/null +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/variables.ts @@ -0,0 +1,7 @@ + +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-rxjs/builds/default/runtime.ts b/samples/client/petstore/typescript-rxjs/builds/default/runtime.ts index 88a1393472..d3934f08cc 100644 --- a/samples/client/petstore/typescript-rxjs/builds/default/runtime.ts +++ b/samples/client/petstore/typescript-rxjs/builds/default/runtime.ts @@ -139,7 +139,7 @@ export class BaseAPI { * export for not being a breaking change */ export class RequiredError extends Error { - name: 'RequiredError' = 'RequiredError'; + override name: 'RequiredError' = 'RequiredError'; } export const COLLECTION_FORMATS = { diff --git a/samples/client/petstore/typescript-rxjs/builds/es6-target/runtime.ts b/samples/client/petstore/typescript-rxjs/builds/es6-target/runtime.ts index 88a1393472..d3934f08cc 100644 --- a/samples/client/petstore/typescript-rxjs/builds/es6-target/runtime.ts +++ b/samples/client/petstore/typescript-rxjs/builds/es6-target/runtime.ts @@ -139,7 +139,7 @@ export class BaseAPI { * export for not being a breaking change */ export class RequiredError extends Error { - name: 'RequiredError' = 'RequiredError'; + override name: 'RequiredError' = 'RequiredError'; } export const COLLECTION_FORMATS = { diff --git a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/runtime.ts b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/runtime.ts index 88a1393472..d3934f08cc 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/runtime.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/runtime.ts @@ -139,7 +139,7 @@ export class BaseAPI { * export for not being a breaking change */ export class RequiredError extends Error { - name: 'RequiredError' = 'RequiredError'; + override name: 'RequiredError' = 'RequiredError'; } export const COLLECTION_FORMATS = { diff --git a/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/runtime.ts b/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/runtime.ts index 7133ac675b..4f1419e623 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/runtime.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/runtime.ts @@ -140,7 +140,7 @@ export class BaseAPI { * export for not being a breaking change */ export class RequiredError extends Error { - name: 'RequiredError' = 'RequiredError'; + override name: 'RequiredError' = 'RequiredError'; } export const COLLECTION_FORMATS = { diff --git a/samples/config/petstore/protobuf-schema/.openapi-generator/FILES b/samples/config/petstore/protobuf-schema/.openapi-generator/FILES index 701c1c5236..c65218a716 100644 --- a/samples/config/petstore/protobuf-schema/.openapi-generator/FILES +++ b/samples/config/petstore/protobuf-schema/.openapi-generator/FILES @@ -2,6 +2,7 @@ README.md models/api_response.proto models/category.proto models/order.proto +models/other_test.proto models/pet.proto models/tag.proto models/user.proto diff --git a/samples/config/petstore/protobuf-schema/models/other_test.proto b/samples/config/petstore/protobuf-schema/models/other_test.proto new file mode 100644 index 0000000000..2c6d6b7e5f --- /dev/null +++ b/samples/config/petstore/protobuf-schema/models/other_test.proto @@ -0,0 +1,20 @@ +/* + 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. + + The version of the OpenAPI document: 1.0.0 + + Generated by OpenAPI Generator: https://openapi-generator.tech +*/ + +syntax = "proto3"; + +package petstore; + + +message OtherTest { + + repeated string set_test = 341814865; + +} diff --git a/samples/documentation/html2/.openapi-generator/VERSION b/samples/documentation/html2/.openapi-generator/VERSION index 89648de331..66672d4e9d 100644 --- a/samples/documentation/html2/.openapi-generator/VERSION +++ b/samples/documentation/html2/.openapi-generator/VERSION @@ -1 +1 @@ -6.0.1-SNAPSHOT \ No newline at end of file +6.1.0-SNAPSHOT \ No newline at end of file diff --git a/samples/documentation/html2/index.html b/samples/documentation/html2/index.html index 99b899be5f..a40148036c 100644 --- a/samples/documentation/html2/index.html +++ b/samples/documentation/html2/index.html @@ -1535,6 +1535,7 @@ $(document).ready(function() { if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -2306,6 +2307,7 @@ Status values that need to be considered for filter if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -2715,6 +2717,7 @@ Tags to filter by if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -3130,6 +3133,7 @@ ID of pet to return if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -3610,6 +3614,7 @@ $(document).ready(function() { if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -4529,6 +4534,7 @@ file to upload if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -5190,6 +5196,7 @@ pub fn main() { if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -5543,6 +5550,7 @@ ID of pet that needs to be fetched if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -5963,6 +5971,7 @@ $(document).ready(function() { if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -7758,6 +7767,7 @@ The name that needs to be fetched. Use user1 for testing. if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { @@ -8217,6 +8227,7 @@ The password for login in clear text if (schema.properties[item].$ref != null) { schema.properties[item] = defsParser.$refs.get(schema.properties[item].$ref); } + }); } else if (schema.items != null && schema.items.$ref != null) { schema.items = defsParser.$refs.get(schema.items.$ref); } else { diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/.openapi-generator/FILES b/samples/openapi3/client/3_0_3_unit_test/python-experimental/.openapi-generator/FILES deleted file mode 100644 index e470d78a14..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/.openapi-generator/FILES +++ /dev/null @@ -1,270 +0,0 @@ -.gitignore -.gitlab-ci.yml -.travis.yml -README.md -docs/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md -docs/AdditionalpropertiesAreAllowedByDefault.md -docs/AdditionalpropertiesCanExistByItself.md -docs/AdditionalpropertiesShouldNotLookInApplicators.md -docs/Allof.md -docs/AllofCombinedWithAnyofOneof.md -docs/AllofSimpleTypes.md -docs/AllofWithBaseSchema.md -docs/AllofWithOneEmptySchema.md -docs/AllofWithTheFirstEmptySchema.md -docs/AllofWithTheLastEmptySchema.md -docs/AllofWithTwoEmptySchemas.md -docs/Anyof.md -docs/AnyofComplexTypes.md -docs/AnyofWithBaseSchema.md -docs/AnyofWithOneEmptySchema.md -docs/ArrayTypeMatchesArrays.md -docs/BooleanTypeMatchesBooleans.md -docs/ByInt.md -docs/ByNumber.md -docs/BySmallNumber.md -docs/DateTimeFormat.md -docs/EmailFormat.md -docs/EnumWith0DoesNotMatchFalse.md -docs/EnumWith1DoesNotMatchTrue.md -docs/EnumWithEscapedCharacters.md -docs/EnumWithFalseDoesNotMatch0.md -docs/EnumWithTrueDoesNotMatch1.md -docs/EnumsInProperties.md -docs/ForbiddenProperty.md -docs/HostnameFormat.md -docs/IntegerTypeMatchesIntegers.md -docs/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md -docs/InvalidStringValueForDefault.md -docs/Ipv4Format.md -docs/Ipv6Format.md -docs/JsonPointerFormat.md -docs/MaximumValidation.md -docs/MaximumValidationWithUnsignedInteger.md -docs/MaxitemsValidation.md -docs/MaxlengthValidation.md -docs/Maxproperties0MeansTheObjectIsEmpty.md -docs/MaxpropertiesValidation.md -docs/MinimumValidation.md -docs/MinimumValidationWithSignedInteger.md -docs/MinitemsValidation.md -docs/MinlengthValidation.md -docs/MinpropertiesValidation.md -docs/ModelNot.md -docs/NestedAllofToCheckValidationSemantics.md -docs/NestedAnyofToCheckValidationSemantics.md -docs/NestedItems.md -docs/NestedOneofToCheckValidationSemantics.md -docs/NotMoreComplexSchema.md -docs/NulCharactersInStrings.md -docs/NullTypeMatchesOnlyTheNullObject.md -docs/NumberTypeMatchesNumbers.md -docs/ObjectPropertiesValidation.md -docs/Oneof.md -docs/OneofComplexTypes.md -docs/OneofWithBaseSchema.md -docs/OneofWithEmptySchema.md -docs/PatternIsNotAnchored.md -docs/PatternValidation.md -docs/PropertiesWithEscapedCharacters.md -docs/PropertyNamedRefThatIsNotAReference.md -docs/RefInAdditionalproperties.md -docs/RefInAllof.md -docs/RefInAnyof.md -docs/RefInItems.md -docs/RefInOneof.md -docs/RefInProperty.md -docs/RequiredDefaultValidation.md -docs/RequiredValidation.md -docs/RequiredWithEmptyArray.md -docs/SimpleEnumValidation.md -docs/StringTypeMatchesStrings.md -docs/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md -docs/UniqueitemsFalseValidation.md -docs/UniqueitemsValidation.md -docs/UriFormat.md -docs/UriReferenceFormat.md -docs/UriTemplateFormat.md -git_push.sh -requirements.txt -setup.cfg -setup.py -test-requirements.txt -test/__init__.py -test/test_additionalproperties_allows_a_schema_which_should_validate.py -test/test_additionalproperties_are_allowed_by_default.py -test/test_additionalproperties_can_exist_by_itself.py -test/test_additionalproperties_should_not_look_in_applicators.py -test/test_allof.py -test/test_allof_combined_with_anyof_oneof.py -test/test_allof_simple_types.py -test/test_allof_with_base_schema.py -test/test_allof_with_one_empty_schema.py -test/test_allof_with_the_first_empty_schema.py -test/test_allof_with_the_last_empty_schema.py -test/test_allof_with_two_empty_schemas.py -test/test_anyof.py -test/test_anyof_complex_types.py -test/test_anyof_with_base_schema.py -test/test_anyof_with_one_empty_schema.py -test/test_array_type_matches_arrays.py -test/test_boolean_type_matches_booleans.py -test/test_by_int.py -test/test_by_number.py -test/test_by_small_number.py -test/test_date_time_format.py -test/test_email_format.py -test/test_enum_with0_does_not_match_false.py -test/test_enum_with1_does_not_match_true.py -test/test_enum_with_escaped_characters.py -test/test_enum_with_false_does_not_match0.py -test/test_enum_with_true_does_not_match1.py -test/test_enums_in_properties.py -test/test_forbidden_property.py -test/test_hostname_format.py -test/test_integer_type_matches_integers.py -test/test_invalid_instance_should_not_raise_error_when_float_division_inf.py -test/test_invalid_string_value_for_default.py -test/test_ipv4_format.py -test/test_ipv6_format.py -test/test_json_pointer_format.py -test/test_maximum_validation.py -test/test_maximum_validation_with_unsigned_integer.py -test/test_maxitems_validation.py -test/test_maxlength_validation.py -test/test_maxproperties0_means_the_object_is_empty.py -test/test_maxproperties_validation.py -test/test_minimum_validation.py -test/test_minimum_validation_with_signed_integer.py -test/test_minitems_validation.py -test/test_minlength_validation.py -test/test_minproperties_validation.py -test/test_model_not.py -test/test_nested_allof_to_check_validation_semantics.py -test/test_nested_anyof_to_check_validation_semantics.py -test/test_nested_items.py -test/test_nested_oneof_to_check_validation_semantics.py -test/test_not_more_complex_schema.py -test/test_nul_characters_in_strings.py -test/test_null_type_matches_only_the_null_object.py -test/test_number_type_matches_numbers.py -test/test_object_properties_validation.py -test/test_oneof.py -test/test_oneof_complex_types.py -test/test_oneof_with_base_schema.py -test/test_oneof_with_empty_schema.py -test/test_pattern_is_not_anchored.py -test/test_pattern_validation.py -test/test_properties_with_escaped_characters.py -test/test_property_named_ref_that_is_not_a_reference.py -test/test_ref_in_additionalproperties.py -test/test_ref_in_allof.py -test/test_ref_in_anyof.py -test/test_ref_in_items.py -test/test_ref_in_oneof.py -test/test_ref_in_property.py -test/test_required_default_validation.py -test/test_required_validation.py -test/test_required_with_empty_array.py -test/test_simple_enum_validation.py -test/test_string_type_matches_strings.py -test/test_the_default_keyword_does_not_do_anything_if_the_property_is_missing.py -test/test_uniqueitems_false_validation.py -test/test_uniqueitems_validation.py -test/test_uri_format.py -test/test_uri_reference_format.py -test/test_uri_template_format.py -tox.ini -unit_test_api/__init__.py -unit_test_api/api/__init__.py -unit_test_api/api_client.py -unit_test_api/apis/__init__.py -unit_test_api/configuration.py -unit_test_api/exceptions.py -unit_test_api/model/__init__.py -unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.py -unit_test_api/model/additionalproperties_are_allowed_by_default.py -unit_test_api/model/additionalproperties_can_exist_by_itself.py -unit_test_api/model/additionalproperties_should_not_look_in_applicators.py -unit_test_api/model/allof.py -unit_test_api/model/allof_combined_with_anyof_oneof.py -unit_test_api/model/allof_simple_types.py -unit_test_api/model/allof_with_base_schema.py -unit_test_api/model/allof_with_one_empty_schema.py -unit_test_api/model/allof_with_the_first_empty_schema.py -unit_test_api/model/allof_with_the_last_empty_schema.py -unit_test_api/model/allof_with_two_empty_schemas.py -unit_test_api/model/anyof.py -unit_test_api/model/anyof_complex_types.py -unit_test_api/model/anyof_with_base_schema.py -unit_test_api/model/anyof_with_one_empty_schema.py -unit_test_api/model/array_type_matches_arrays.py -unit_test_api/model/boolean_type_matches_booleans.py -unit_test_api/model/by_int.py -unit_test_api/model/by_number.py -unit_test_api/model/by_small_number.py -unit_test_api/model/date_time_format.py -unit_test_api/model/email_format.py -unit_test_api/model/enum_with0_does_not_match_false.py -unit_test_api/model/enum_with1_does_not_match_true.py -unit_test_api/model/enum_with_escaped_characters.py -unit_test_api/model/enum_with_false_does_not_match0.py -unit_test_api/model/enum_with_true_does_not_match1.py -unit_test_api/model/enums_in_properties.py -unit_test_api/model/forbidden_property.py -unit_test_api/model/hostname_format.py -unit_test_api/model/integer_type_matches_integers.py -unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.py -unit_test_api/model/invalid_string_value_for_default.py -unit_test_api/model/ipv4_format.py -unit_test_api/model/ipv6_format.py -unit_test_api/model/json_pointer_format.py -unit_test_api/model/maximum_validation.py -unit_test_api/model/maximum_validation_with_unsigned_integer.py -unit_test_api/model/maxitems_validation.py -unit_test_api/model/maxlength_validation.py -unit_test_api/model/maxproperties0_means_the_object_is_empty.py -unit_test_api/model/maxproperties_validation.py -unit_test_api/model/minimum_validation.py -unit_test_api/model/minimum_validation_with_signed_integer.py -unit_test_api/model/minitems_validation.py -unit_test_api/model/minlength_validation.py -unit_test_api/model/minproperties_validation.py -unit_test_api/model/model_not.py -unit_test_api/model/nested_allof_to_check_validation_semantics.py -unit_test_api/model/nested_anyof_to_check_validation_semantics.py -unit_test_api/model/nested_items.py -unit_test_api/model/nested_oneof_to_check_validation_semantics.py -unit_test_api/model/not_more_complex_schema.py -unit_test_api/model/nul_characters_in_strings.py -unit_test_api/model/null_type_matches_only_the_null_object.py -unit_test_api/model/number_type_matches_numbers.py -unit_test_api/model/object_properties_validation.py -unit_test_api/model/oneof.py -unit_test_api/model/oneof_complex_types.py -unit_test_api/model/oneof_with_base_schema.py -unit_test_api/model/oneof_with_empty_schema.py -unit_test_api/model/pattern_is_not_anchored.py -unit_test_api/model/pattern_validation.py -unit_test_api/model/properties_with_escaped_characters.py -unit_test_api/model/property_named_ref_that_is_not_a_reference.py -unit_test_api/model/ref_in_additionalproperties.py -unit_test_api/model/ref_in_allof.py -unit_test_api/model/ref_in_anyof.py -unit_test_api/model/ref_in_items.py -unit_test_api/model/ref_in_oneof.py -unit_test_api/model/ref_in_property.py -unit_test_api/model/required_default_validation.py -unit_test_api/model/required_validation.py -unit_test_api/model/required_with_empty_array.py -unit_test_api/model/simple_enum_validation.py -unit_test_api/model/string_type_matches_strings.py -unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.py -unit_test_api/model/uniqueitems_false_validation.py -unit_test_api/model/uniqueitems_validation.py -unit_test_api/model/uri_format.py -unit_test_api/model/uri_reference_format.py -unit_test_api/model/uri_template_format.py -unit_test_api/models/__init__.py -unit_test_api/rest.py -unit_test_api/schemas.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/README.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/README.md deleted file mode 100644 index 8f38f97e69..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/README.md +++ /dev/null @@ -1,173 +0,0 @@ -# unit-test-api -sample spec for testing openapi functionality, built from json schema tests for draft6 - -This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: 0.0.1 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.PythonExperimentalClientCodegen - -## Requirements. - -Python >=3.9 -v3.9 is needed so one can combine classmethod and property decorators to define -object schema properties as classes - -## Installation & Usage -### pip install - -If the python package is hosted on a repository, you can install directly using: - -```sh -pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git -``` -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) - -Then import the package: -```python -import unit_test_api -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: -```python -import unit_test_api -``` - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```python - -import time -import unit_test_api -from pprint import pprint -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://localhost* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- - -## Documentation For Models - - - [AdditionalpropertiesAllowsASchemaWhichShouldValidate](docs/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) - - [AdditionalpropertiesAreAllowedByDefault](docs/AdditionalpropertiesAreAllowedByDefault.md) - - [AdditionalpropertiesCanExistByItself](docs/AdditionalpropertiesCanExistByItself.md) - - [AdditionalpropertiesShouldNotLookInApplicators](docs/AdditionalpropertiesShouldNotLookInApplicators.md) - - [Allof](docs/Allof.md) - - [AllofCombinedWithAnyofOneof](docs/AllofCombinedWithAnyofOneof.md) - - [AllofSimpleTypes](docs/AllofSimpleTypes.md) - - [AllofWithBaseSchema](docs/AllofWithBaseSchema.md) - - [AllofWithOneEmptySchema](docs/AllofWithOneEmptySchema.md) - - [AllofWithTheFirstEmptySchema](docs/AllofWithTheFirstEmptySchema.md) - - [AllofWithTheLastEmptySchema](docs/AllofWithTheLastEmptySchema.md) - - [AllofWithTwoEmptySchemas](docs/AllofWithTwoEmptySchemas.md) - - [Anyof](docs/Anyof.md) - - [AnyofComplexTypes](docs/AnyofComplexTypes.md) - - [AnyofWithBaseSchema](docs/AnyofWithBaseSchema.md) - - [AnyofWithOneEmptySchema](docs/AnyofWithOneEmptySchema.md) - - [ArrayTypeMatchesArrays](docs/ArrayTypeMatchesArrays.md) - - [BooleanTypeMatchesBooleans](docs/BooleanTypeMatchesBooleans.md) - - [ByInt](docs/ByInt.md) - - [ByNumber](docs/ByNumber.md) - - [BySmallNumber](docs/BySmallNumber.md) - - [DateTimeFormat](docs/DateTimeFormat.md) - - [EmailFormat](docs/EmailFormat.md) - - [EnumWith0DoesNotMatchFalse](docs/EnumWith0DoesNotMatchFalse.md) - - [EnumWith1DoesNotMatchTrue](docs/EnumWith1DoesNotMatchTrue.md) - - [EnumWithEscapedCharacters](docs/EnumWithEscapedCharacters.md) - - [EnumWithFalseDoesNotMatch0](docs/EnumWithFalseDoesNotMatch0.md) - - [EnumWithTrueDoesNotMatch1](docs/EnumWithTrueDoesNotMatch1.md) - - [EnumsInProperties](docs/EnumsInProperties.md) - - [ForbiddenProperty](docs/ForbiddenProperty.md) - - [HostnameFormat](docs/HostnameFormat.md) - - [IntegerTypeMatchesIntegers](docs/IntegerTypeMatchesIntegers.md) - - [InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf](docs/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) - - [InvalidStringValueForDefault](docs/InvalidStringValueForDefault.md) - - [Ipv4Format](docs/Ipv4Format.md) - - [Ipv6Format](docs/Ipv6Format.md) - - [JsonPointerFormat](docs/JsonPointerFormat.md) - - [MaximumValidation](docs/MaximumValidation.md) - - [MaximumValidationWithUnsignedInteger](docs/MaximumValidationWithUnsignedInteger.md) - - [MaxitemsValidation](docs/MaxitemsValidation.md) - - [MaxlengthValidation](docs/MaxlengthValidation.md) - - [Maxproperties0MeansTheObjectIsEmpty](docs/Maxproperties0MeansTheObjectIsEmpty.md) - - [MaxpropertiesValidation](docs/MaxpropertiesValidation.md) - - [MinimumValidation](docs/MinimumValidation.md) - - [MinimumValidationWithSignedInteger](docs/MinimumValidationWithSignedInteger.md) - - [MinitemsValidation](docs/MinitemsValidation.md) - - [MinlengthValidation](docs/MinlengthValidation.md) - - [MinpropertiesValidation](docs/MinpropertiesValidation.md) - - [ModelNot](docs/ModelNot.md) - - [NestedAllofToCheckValidationSemantics](docs/NestedAllofToCheckValidationSemantics.md) - - [NestedAnyofToCheckValidationSemantics](docs/NestedAnyofToCheckValidationSemantics.md) - - [NestedItems](docs/NestedItems.md) - - [NestedOneofToCheckValidationSemantics](docs/NestedOneofToCheckValidationSemantics.md) - - [NotMoreComplexSchema](docs/NotMoreComplexSchema.md) - - [NulCharactersInStrings](docs/NulCharactersInStrings.md) - - [NullTypeMatchesOnlyTheNullObject](docs/NullTypeMatchesOnlyTheNullObject.md) - - [NumberTypeMatchesNumbers](docs/NumberTypeMatchesNumbers.md) - - [ObjectPropertiesValidation](docs/ObjectPropertiesValidation.md) - - [Oneof](docs/Oneof.md) - - [OneofComplexTypes](docs/OneofComplexTypes.md) - - [OneofWithBaseSchema](docs/OneofWithBaseSchema.md) - - [OneofWithEmptySchema](docs/OneofWithEmptySchema.md) - - [PatternIsNotAnchored](docs/PatternIsNotAnchored.md) - - [PatternValidation](docs/PatternValidation.md) - - [PropertiesWithEscapedCharacters](docs/PropertiesWithEscapedCharacters.md) - - [PropertyNamedRefThatIsNotAReference](docs/PropertyNamedRefThatIsNotAReference.md) - - [RefInAdditionalproperties](docs/RefInAdditionalproperties.md) - - [RefInAllof](docs/RefInAllof.md) - - [RefInAnyof](docs/RefInAnyof.md) - - [RefInItems](docs/RefInItems.md) - - [RefInOneof](docs/RefInOneof.md) - - [RefInProperty](docs/RefInProperty.md) - - [RequiredDefaultValidation](docs/RequiredDefaultValidation.md) - - [RequiredValidation](docs/RequiredValidation.md) - - [RequiredWithEmptyArray](docs/RequiredWithEmptyArray.md) - - [SimpleEnumValidation](docs/SimpleEnumValidation.md) - - [StringTypeMatchesStrings](docs/StringTypeMatchesStrings.md) - - [TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing](docs/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) - - [UniqueitemsFalseValidation](docs/UniqueitemsFalseValidation.md) - - [UniqueitemsValidation](docs/UniqueitemsValidation.md) - - [UriFormat](docs/UriFormat.md) - - [UriReferenceFormat](docs/UriReferenceFormat.md) - - [UriTemplateFormat](docs/UriTemplateFormat.md) - -## Documentation For Authorization - - All endpoints do not require authorization. - -## Author - - -## Notes for Large OpenAPI documents -If the OpenAPI document is large, imports in unit_test_api.apis and unit_test_api.models may fail with a -RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: - -Solution 1: -Use specific imports for apis and models like: -- `from unit_test_api.api.default_api import DefaultApi` -- `from unit_test_api.model.pet import Pet` - -Solution 1: -Before importing the package, adjust the maximum recursion limit as shown below: -``` -import sys -sys.setrecursionlimit(1500) -import unit_test_api -from unit_test_api.apis import * -from unit_test_api.models import * -``` diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md deleted file mode 100644 index d9981bf45a..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md +++ /dev/null @@ -1,11 +0,0 @@ -# AdditionalpropertiesAllowsASchemaWhichShouldValidate - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**bar** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesAreAllowedByDefault.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesAreAllowedByDefault.md deleted file mode 100644 index d5e7d2747e..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesAreAllowedByDefault.md +++ /dev/null @@ -1,11 +0,0 @@ -# AdditionalpropertiesAreAllowedByDefault - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**bar** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesCanExistByItself.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesCanExistByItself.md deleted file mode 100644 index 72b091b888..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesCanExistByItself.md +++ /dev/null @@ -1,9 +0,0 @@ -# AdditionalpropertiesCanExistByItself - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesShouldNotLookInApplicators.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesShouldNotLookInApplicators.md deleted file mode 100644 index 31efeb974b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AdditionalpropertiesShouldNotLookInApplicators.md +++ /dev/null @@ -1,9 +0,0 @@ -# AdditionalpropertiesShouldNotLookInApplicators - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Allof.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Allof.md deleted file mode 100644 index 77328e52d3..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Allof.md +++ /dev/null @@ -1,9 +0,0 @@ -# Allof - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofCombinedWithAnyofOneof.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofCombinedWithAnyofOneof.md deleted file mode 100644 index 403b07716c..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofCombinedWithAnyofOneof.md +++ /dev/null @@ -1,9 +0,0 @@ -# AllofCombinedWithAnyofOneof - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofSimpleTypes.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofSimpleTypes.md deleted file mode 100644 index b1ababc3e5..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofSimpleTypes.md +++ /dev/null @@ -1,9 +0,0 @@ -# AllofSimpleTypes - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithBaseSchema.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithBaseSchema.md deleted file mode 100644 index a01c8b13de..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithBaseSchema.md +++ /dev/null @@ -1,10 +0,0 @@ -# AllofWithBaseSchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**bar** | **int** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithOneEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithOneEmptySchema.md deleted file mode 100644 index 21e4d7d4ef..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithOneEmptySchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# AllofWithOneEmptySchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithTheFirstEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithTheFirstEmptySchema.md deleted file mode 100644 index d25f566484..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithTheFirstEmptySchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# AllofWithTheFirstEmptySchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithTheLastEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithTheLastEmptySchema.md deleted file mode 100644 index aefbea3036..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithTheLastEmptySchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# AllofWithTheLastEmptySchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithTwoEmptySchemas.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithTwoEmptySchemas.md deleted file mode 100644 index 220b95e4f0..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AllofWithTwoEmptySchemas.md +++ /dev/null @@ -1,9 +0,0 @@ -# AllofWithTwoEmptySchemas - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Anyof.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Anyof.md deleted file mode 100644 index 2a5107e980..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Anyof.md +++ /dev/null @@ -1,9 +0,0 @@ -# Anyof - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AnyofComplexTypes.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AnyofComplexTypes.md deleted file mode 100644 index a6a3dcfa53..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AnyofComplexTypes.md +++ /dev/null @@ -1,9 +0,0 @@ -# AnyofComplexTypes - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AnyofWithBaseSchema.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AnyofWithBaseSchema.md deleted file mode 100644 index cf00c6413d..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AnyofWithBaseSchema.md +++ /dev/null @@ -1,8 +0,0 @@ -# AnyofWithBaseSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AnyofWithOneEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AnyofWithOneEmptySchema.md deleted file mode 100644 index 2d3666e55b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/AnyofWithOneEmptySchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# AnyofWithOneEmptySchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ArrayTypeMatchesArrays.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ArrayTypeMatchesArrays.md deleted file mode 100644 index bf72f2c35b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ArrayTypeMatchesArrays.md +++ /dev/null @@ -1,8 +0,0 @@ -# ArrayTypeMatchesArrays - -Type | Description | Notes -------------- | ------------- | ------------- -**[bool, date, datetime, dict, float, int, list, str, none_type]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/BooleanTypeMatchesBooleans.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/BooleanTypeMatchesBooleans.md deleted file mode 100644 index fa68a60fd2..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/BooleanTypeMatchesBooleans.md +++ /dev/null @@ -1,8 +0,0 @@ -# BooleanTypeMatchesBooleans - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ByInt.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ByInt.md deleted file mode 100644 index 7e089ed79b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ByInt.md +++ /dev/null @@ -1,9 +0,0 @@ -# ByInt - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ByNumber.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ByNumber.md deleted file mode 100644 index 8c272d66b6..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ByNumber.md +++ /dev/null @@ -1,9 +0,0 @@ -# ByNumber - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/BySmallNumber.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/BySmallNumber.md deleted file mode 100644 index 3671c33f9c..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/BySmallNumber.md +++ /dev/null @@ -1,9 +0,0 @@ -# BySmallNumber - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/DateTimeFormat.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/DateTimeFormat.md deleted file mode 100644 index 308c3ad9e3..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/DateTimeFormat.md +++ /dev/null @@ -1,9 +0,0 @@ -# DateTimeFormat - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EmailFormat.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EmailFormat.md deleted file mode 100644 index 25144b9cf4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EmailFormat.md +++ /dev/null @@ -1,9 +0,0 @@ -# EmailFormat - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWith0DoesNotMatchFalse.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWith0DoesNotMatchFalse.md deleted file mode 100644 index d5a6a18701..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWith0DoesNotMatchFalse.md +++ /dev/null @@ -1,8 +0,0 @@ -# EnumWith0DoesNotMatchFalse - -Type | Description | Notes -------------- | ------------- | ------------- -**float** | | must be one of [0, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWith1DoesNotMatchTrue.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWith1DoesNotMatchTrue.md deleted file mode 100644 index 302b358dc6..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWith1DoesNotMatchTrue.md +++ /dev/null @@ -1,8 +0,0 @@ -# EnumWith1DoesNotMatchTrue - -Type | Description | Notes -------------- | ------------- | ------------- -**float** | | must be one of [1, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWithEscapedCharacters.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWithEscapedCharacters.md deleted file mode 100644 index df7d014c64..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWithEscapedCharacters.md +++ /dev/null @@ -1,8 +0,0 @@ -# EnumWithEscapedCharacters - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | must be one of ["foo\nbar", "foo\rbar", ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWithFalseDoesNotMatch0.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWithFalseDoesNotMatch0.md deleted file mode 100644 index 03733e36e0..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWithFalseDoesNotMatch0.md +++ /dev/null @@ -1,8 +0,0 @@ -# EnumWithFalseDoesNotMatch0 - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | must be one of [BoolClass.FALSE, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWithTrueDoesNotMatch1.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWithTrueDoesNotMatch1.md deleted file mode 100644 index add4938784..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumWithTrueDoesNotMatch1.md +++ /dev/null @@ -1,8 +0,0 @@ -# EnumWithTrueDoesNotMatch1 - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | must be one of [BoolClass.TRUE, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumsInProperties.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumsInProperties.md deleted file mode 100644 index 7b058dabb4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/EnumsInProperties.md +++ /dev/null @@ -1,11 +0,0 @@ -# EnumsInProperties - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo** | **str** | | [optional] -**bar** | **str** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ForbiddenProperty.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ForbiddenProperty.md deleted file mode 100644 index acb9f23b22..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ForbiddenProperty.md +++ /dev/null @@ -1,10 +0,0 @@ -# ForbiddenProperty - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/HostnameFormat.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/HostnameFormat.md deleted file mode 100644 index abe7728baa..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/HostnameFormat.md +++ /dev/null @@ -1,9 +0,0 @@ -# HostnameFormat - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/IntegerTypeMatchesIntegers.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/IntegerTypeMatchesIntegers.md deleted file mode 100644 index 141e17fd9a..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/IntegerTypeMatchesIntegers.md +++ /dev/null @@ -1,8 +0,0 @@ -# IntegerTypeMatchesIntegers - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md deleted file mode 100644 index 9acc3f6353..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md +++ /dev/null @@ -1,8 +0,0 @@ -# InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/InvalidStringValueForDefault.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/InvalidStringValueForDefault.md deleted file mode 100644 index ae12943813..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/InvalidStringValueForDefault.md +++ /dev/null @@ -1,10 +0,0 @@ -# InvalidStringValueForDefault - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**bar** | **str** | | [optional] if omitted the server will use the default value of "bad" -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Ipv4Format.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Ipv4Format.md deleted file mode 100644 index 545514e2b8..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Ipv4Format.md +++ /dev/null @@ -1,9 +0,0 @@ -# Ipv4Format - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Ipv6Format.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Ipv6Format.md deleted file mode 100644 index 84f13f968a..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Ipv6Format.md +++ /dev/null @@ -1,9 +0,0 @@ -# Ipv6Format - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/JsonPointerFormat.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/JsonPointerFormat.md deleted file mode 100644 index be35740ae6..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/JsonPointerFormat.md +++ /dev/null @@ -1,9 +0,0 @@ -# JsonPointerFormat - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaximumValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaximumValidation.md deleted file mode 100644 index 2060e3a0d4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaximumValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# MaximumValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaximumValidationWithUnsignedInteger.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaximumValidationWithUnsignedInteger.md deleted file mode 100644 index 9a20b4b7bc..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaximumValidationWithUnsignedInteger.md +++ /dev/null @@ -1,9 +0,0 @@ -# MaximumValidationWithUnsignedInteger - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaxitemsValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaxitemsValidation.md deleted file mode 100644 index 8c60872ae0..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaxitemsValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# MaxitemsValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaxlengthValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaxlengthValidation.md deleted file mode 100644 index 0f9d27bd44..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaxlengthValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# MaxlengthValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Maxproperties0MeansTheObjectIsEmpty.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Maxproperties0MeansTheObjectIsEmpty.md deleted file mode 100644 index ed97994d65..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Maxproperties0MeansTheObjectIsEmpty.md +++ /dev/null @@ -1,9 +0,0 @@ -# Maxproperties0MeansTheObjectIsEmpty - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaxpropertiesValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaxpropertiesValidation.md deleted file mode 100644 index d92c1f77f9..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MaxpropertiesValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# MaxpropertiesValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinimumValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinimumValidation.md deleted file mode 100644 index 0a787d59fe..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinimumValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# MinimumValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinimumValidationWithSignedInteger.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinimumValidationWithSignedInteger.md deleted file mode 100644 index e43ddb8171..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinimumValidationWithSignedInteger.md +++ /dev/null @@ -1,9 +0,0 @@ -# MinimumValidationWithSignedInteger - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinitemsValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinitemsValidation.md deleted file mode 100644 index 14e1884d05..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinitemsValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# MinitemsValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinlengthValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinlengthValidation.md deleted file mode 100644 index c914c02f01..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinlengthValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# MinlengthValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinpropertiesValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinpropertiesValidation.md deleted file mode 100644 index b549f69455..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/MinpropertiesValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# MinpropertiesValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ModelNot.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ModelNot.md deleted file mode 100644 index bac67e7680..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ModelNot.md +++ /dev/null @@ -1,9 +0,0 @@ -# ModelNot - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedAllofToCheckValidationSemantics.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedAllofToCheckValidationSemantics.md deleted file mode 100644 index abd73afca5..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedAllofToCheckValidationSemantics.md +++ /dev/null @@ -1,9 +0,0 @@ -# NestedAllofToCheckValidationSemantics - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedAnyofToCheckValidationSemantics.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedAnyofToCheckValidationSemantics.md deleted file mode 100644 index d95966736d..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedAnyofToCheckValidationSemantics.md +++ /dev/null @@ -1,9 +0,0 @@ -# NestedAnyofToCheckValidationSemantics - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedItems.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedItems.md deleted file mode 100644 index c64b37b166..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedItems.md +++ /dev/null @@ -1,8 +0,0 @@ -# NestedItems - -Type | Description | Notes -------------- | ------------- | ------------- -**[[[[int, float]]]]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedOneofToCheckValidationSemantics.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedOneofToCheckValidationSemantics.md deleted file mode 100644 index 06ba0d5e9e..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NestedOneofToCheckValidationSemantics.md +++ /dev/null @@ -1,9 +0,0 @@ -# NestedOneofToCheckValidationSemantics - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NotMoreComplexSchema.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NotMoreComplexSchema.md deleted file mode 100644 index 2ea5b209cc..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NotMoreComplexSchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# NotMoreComplexSchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NulCharactersInStrings.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NulCharactersInStrings.md deleted file mode 100644 index d90b761591..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NulCharactersInStrings.md +++ /dev/null @@ -1,8 +0,0 @@ -# NulCharactersInStrings - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | must be one of ["hello\x00there", ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NullTypeMatchesOnlyTheNullObject.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NullTypeMatchesOnlyTheNullObject.md deleted file mode 100644 index 54a530d1d3..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NullTypeMatchesOnlyTheNullObject.md +++ /dev/null @@ -1,8 +0,0 @@ -# NullTypeMatchesOnlyTheNullObject - -Type | Description | Notes -------------- | ------------- | ------------- -**none_type** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NumberTypeMatchesNumbers.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NumberTypeMatchesNumbers.md deleted file mode 100644 index 8348aeef2b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/NumberTypeMatchesNumbers.md +++ /dev/null @@ -1,8 +0,0 @@ -# NumberTypeMatchesNumbers - -Type | Description | Notes -------------- | ------------- | ------------- -**float** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ObjectPropertiesValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ObjectPropertiesValidation.md deleted file mode 100644 index 9307469f5b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/ObjectPropertiesValidation.md +++ /dev/null @@ -1,11 +0,0 @@ -# ObjectPropertiesValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo** | **int** | | [optional] -**bar** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Oneof.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Oneof.md deleted file mode 100644 index e42f38aff3..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/Oneof.md +++ /dev/null @@ -1,9 +0,0 @@ -# Oneof - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/OneofComplexTypes.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/OneofComplexTypes.md deleted file mode 100644 index e26c501afd..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/OneofComplexTypes.md +++ /dev/null @@ -1,9 +0,0 @@ -# OneofComplexTypes - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/OneofWithBaseSchema.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/OneofWithBaseSchema.md deleted file mode 100644 index f80a4e8b65..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/OneofWithBaseSchema.md +++ /dev/null @@ -1,8 +0,0 @@ -# OneofWithBaseSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/OneofWithEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/OneofWithEmptySchema.md deleted file mode 100644 index 1310a70f30..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/OneofWithEmptySchema.md +++ /dev/null @@ -1,9 +0,0 @@ -# OneofWithEmptySchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PatternIsNotAnchored.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PatternIsNotAnchored.md deleted file mode 100644 index bca3d004ba..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PatternIsNotAnchored.md +++ /dev/null @@ -1,9 +0,0 @@ -# PatternIsNotAnchored - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PatternValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PatternValidation.md deleted file mode 100644 index ed358b8156..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PatternValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# PatternValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PropertiesWithEscapedCharacters.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PropertiesWithEscapedCharacters.md deleted file mode 100644 index e585f0e8e1..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PropertiesWithEscapedCharacters.md +++ /dev/null @@ -1,15 +0,0 @@ -# PropertiesWithEscapedCharacters - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo\nbar** | **int, float** | | [optional] -**foo\"bar** | **int, float** | | [optional] -**foo\\bar** | **int, float** | | [optional] -**foo\rbar** | **int, float** | | [optional] -**foo\tbar** | **int, float** | | [optional] -**foo\fbar** | **int, float** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PropertyNamedRefThatIsNotAReference.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PropertyNamedRefThatIsNotAReference.md deleted file mode 100644 index 7f51dc33bb..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/PropertyNamedRefThatIsNotAReference.md +++ /dev/null @@ -1,10 +0,0 @@ -# PropertyNamedRefThatIsNotAReference - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**$ref** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInAdditionalproperties.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInAdditionalproperties.md deleted file mode 100644 index d65f094ff7..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInAdditionalproperties.md +++ /dev/null @@ -1,9 +0,0 @@ -# RefInAdditionalproperties - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **PropertyNamedRefThatIsNotAReference** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInAllof.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInAllof.md deleted file mode 100644 index 5c193c05ad..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInAllof.md +++ /dev/null @@ -1,9 +0,0 @@ -# RefInAllof - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInAnyof.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInAnyof.md deleted file mode 100644 index 317cc9a174..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInAnyof.md +++ /dev/null @@ -1,9 +0,0 @@ -# RefInAnyof - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInItems.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInItems.md deleted file mode 100644 index 618c152215..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInItems.md +++ /dev/null @@ -1,8 +0,0 @@ -# RefInItems - -Type | Description | Notes -------------- | ------------- | ------------- -**[PropertyNamedRefThatIsNotAReference]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInOneof.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInOneof.md deleted file mode 100644 index e063bf5a11..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInOneof.md +++ /dev/null @@ -1,9 +0,0 @@ -# RefInOneof - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInProperty.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInProperty.md deleted file mode 100644 index 5e912fa825..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RefInProperty.md +++ /dev/null @@ -1,10 +0,0 @@ -# RefInProperty - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**a** | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RequiredDefaultValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RequiredDefaultValidation.md deleted file mode 100644 index 46c719866d..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RequiredDefaultValidation.md +++ /dev/null @@ -1,10 +0,0 @@ -# RequiredDefaultValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RequiredValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RequiredValidation.md deleted file mode 100644 index 31ab7e70c4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RequiredValidation.md +++ /dev/null @@ -1,11 +0,0 @@ -# RequiredValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo** | **bool, date, datetime, dict, float, int, list, str, none_type** | | -**bar** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RequiredWithEmptyArray.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RequiredWithEmptyArray.md deleted file mode 100644 index c243bc4b3d..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/RequiredWithEmptyArray.md +++ /dev/null @@ -1,10 +0,0 @@ -# RequiredWithEmptyArray - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/SimpleEnumValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/SimpleEnumValidation.md deleted file mode 100644 index 81e6b4f5e6..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/SimpleEnumValidation.md +++ /dev/null @@ -1,8 +0,0 @@ -# SimpleEnumValidation - -Type | Description | Notes -------------- | ------------- | ------------- -**float** | | must be one of [1, 2, 3, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/StringTypeMatchesStrings.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/StringTypeMatchesStrings.md deleted file mode 100644 index cd1125671a..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/StringTypeMatchesStrings.md +++ /dev/null @@ -1,8 +0,0 @@ -# StringTypeMatchesStrings - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md deleted file mode 100644 index 61162c71aa..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md +++ /dev/null @@ -1,10 +0,0 @@ -# TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**alpha** | **int, float** | | [optional] if omitted the server will use the default value of 5 -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UniqueitemsFalseValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UniqueitemsFalseValidation.md deleted file mode 100644 index 99e0a5ba1c..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UniqueitemsFalseValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# UniqueitemsFalseValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UniqueitemsValidation.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UniqueitemsValidation.md deleted file mode 100644 index 8cd8bbdc61..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UniqueitemsValidation.md +++ /dev/null @@ -1,9 +0,0 @@ -# UniqueitemsValidation - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UriFormat.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UriFormat.md deleted file mode 100644 index 45565b815d..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UriFormat.md +++ /dev/null @@ -1,9 +0,0 @@ -# UriFormat - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UriReferenceFormat.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UriReferenceFormat.md deleted file mode 100644 index 5e3d85e8fd..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UriReferenceFormat.md +++ /dev/null @@ -1,9 +0,0 @@ -# UriReferenceFormat - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UriTemplateFormat.md b/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UriTemplateFormat.md deleted file mode 100644 index 5b661945b3..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/docs/UriTemplateFormat.md +++ /dev/null @@ -1,9 +0,0 @@ -# UriTemplateFormat - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/git_push.sh b/samples/openapi3/client/3_0_3_unit_test/python-experimental/git_push.sh deleted file mode 100644 index ced3be2b0c..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/git_push.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/requirements.txt b/samples/openapi3/client/3_0_3_unit_test/python-experimental/requirements.txt deleted file mode 100644 index c9227e58a1..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -certifi >= 14.05.14 -frozendict >= 2.0.3 -python_dateutil >= 2.5.3 -setuptools >= 21.0.0 -urllib3 >= 1.15.1 diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/setup.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/setup.py deleted file mode 100644 index bac2d32398..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/setup.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -from setuptools import setup, find_packages # noqa: H301 - -NAME = "unit-test-api" -VERSION = "1.0.0" -# To install the library, run the following -# -# python setup.py install -# -# prerequisite: setuptools -# http://pypi.python.org/pypi/setuptools - -REQUIRES = [ - "urllib3 >= 1.15", - "certifi", - "python-dateutil", - "frozendict >= 2.0.3", -] - -setup( - name=NAME, - version=VERSION, - description="openapi 3.0.3 sample spec", - author="OpenAPI Generator community", - author_email="team@openapitools.org", - url="", - keywords=["OpenAPI", "OpenAPI-Generator", "openapi 3.0.3 sample spec"], - python_requires=">=3.9", - install_requires=REQUIRES, - packages=find_packages(exclude=["test", "tests"]), - include_package_data=True, - long_description="""\ - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - """ -) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_should_not_look_in_applicators.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_should_not_look_in_applicators.py deleted file mode 100644 index f296b2ad62..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_should_not_look_in_applicators.py +++ /dev/null @@ -1,38 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import unit_test_api -from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators -from unit_test_api import configuration - - -class TestAdditionalpropertiesShouldNotLookInApplicators(unittest.TestCase): - """AdditionalpropertiesShouldNotLookInApplicators unit test stubs""" - _configuration = configuration.Configuration() - - def test_properties_defined_in_allof_are_not_examined_fails(self): - # properties defined in allOf are not examined - with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AdditionalpropertiesShouldNotLookInApplicators._from_openapi_data( - { - "foo": - 1, - "bar": - True, - }, - _configuration=self._configuration - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/tox.ini b/samples/openapi3/client/3_0_3_unit_test/python-experimental/tox.ini deleted file mode 100644 index e4093b56ea..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/tox.ini +++ /dev/null @@ -1,9 +0,0 @@ -[tox] -envlist = py39 - -[testenv] -deps=-r{toxinidir}/requirements.txt - -r{toxinidir}/test-requirements.txt - -commands= - pytest --cov=unit_test_api diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/api_client.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/api_client.py deleted file mode 100644 index 66e52cba29..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/api_client.py +++ /dev/null @@ -1,1420 +0,0 @@ -# coding: utf-8 -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -from decimal import Decimal -import enum -import email -import json -import os -import io -import atexit -from multiprocessing.pool import ThreadPool -import re -import tempfile -import typing -import urllib3 -from urllib3._collections import HTTPHeaderDict -from urllib.parse import quote -from urllib3.fields import RequestField as RequestFieldBase - - -from unit_test_api import rest -from unit_test_api.configuration import Configuration -from unit_test_api.exceptions import ApiTypeError, ApiValueError -from unit_test_api.schemas import ( - NoneClass, - BoolClass, - Schema, - FileIO, - BinarySchema, - date, - datetime, - none_type, - frozendict, - Unset, - unset, -) - - -class RequestField(RequestFieldBase): - def __eq__(self, other): - if not isinstance(other, RequestField): - return False - return self.__dict__ == other.__dict__ - - -class JSONEncoder(json.JSONEncoder): - def default(self, obj): - if isinstance(obj, str): - return str(obj) - elif isinstance(obj, float): - return float(obj) - elif isinstance(obj, int): - return int(obj) - elif isinstance(obj, Decimal): - if obj.as_tuple().exponent >= 0: - return int(obj) - return float(obj) - elif isinstance(obj, NoneClass): - return None - elif isinstance(obj, BoolClass): - return bool(obj) - elif isinstance(obj, (dict, frozendict)): - return {key: self.default(val) for key, val in obj.items()} - elif isinstance(obj, (list, tuple)): - return [self.default(item) for item in obj] - raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__)) - - -class ParameterInType(enum.Enum): - QUERY = 'query' - HEADER = 'header' - PATH = 'path' - COOKIE = 'cookie' - - -class ParameterStyle(enum.Enum): - MATRIX = 'matrix' - LABEL = 'label' - FORM = 'form' - SIMPLE = 'simple' - SPACE_DELIMITED = 'spaceDelimited' - PIPE_DELIMITED = 'pipeDelimited' - DEEP_OBJECT = 'deepObject' - - -class PrefixSeparatorIterator: - # A class to store prefixes and separators for rfc6570 expansions - - def __init__(self, prefix: str, separator: str): - self.prefix = prefix - self.separator = separator - self.first = True - if separator in {'.', '|', '%20'}: - item_separator = separator - else: - item_separator = ',' - self.item_separator = item_separator - - def __iter__(self): - return self - - def __next__(self): - if self.first: - self.first = False - return self.prefix - return self.separator - - -class ParameterSerializerBase: - @classmethod - def get_default_explode(cls, style: ParameterStyle) -> bool: - return False - - @staticmethod - def __ref6570_item_value(in_data: typing.Any, percent_encode: bool): - """ - Get representation if str/float/int/None/items in list/ values in dict - None is returned if an item is undefined, use cases are value= - - None - - [] - - {} - - [None, None None] - - {'a': None, 'b': None} - """ - if type(in_data) in {str, float, int}: - if percent_encode: - return quote(str(in_data)) - return str(in_data) - elif isinstance(in_data, none_type): - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return None - elif isinstance(in_data, list) and not in_data: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return None - elif isinstance(in_data, dict) and not in_data: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return None - raise ApiValueError('Unable to generate a ref6570 item representation of {}'.format(in_data)) - - @staticmethod - def to_dict(name: str, value: str): - return {name: value} - - @classmethod - def ref6570_expansion( - cls, - variable_name: str, - in_data: typing.Any, - explode: bool, - percent_encode: bool, - prefix_separator_iterator: PrefixSeparatorIterator - ) -> str: - """ - Separator is for separate variables like dict with explode true, not for array item separation - """ - named_parameter_expansion = prefix_separator_iterator.separator in {'&', ';'} - var_name_piece = variable_name if named_parameter_expansion else '' - if type(in_data) in {str, float, int}: - item_value = cls.__ref6570_item_value(in_data, percent_encode) - if item_value is None: - return next(prefix_separator_iterator) + var_name_piece - elif item_value == '' and prefix_separator_iterator.separator == ';': - return next(prefix_separator_iterator) + var_name_piece - value_pair_equals = '=' if named_parameter_expansion else '' - return next(prefix_separator_iterator) + var_name_piece + value_pair_equals + item_value - elif isinstance(in_data, none_type): - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return "" - elif isinstance(in_data, list): - item_values = [cls.__ref6570_item_value(v, percent_encode) for v in in_data] - item_values = [v for v in item_values if v is not None] - if not item_values: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return "" - value_pair_equals = '=' if named_parameter_expansion else '' - if not explode: - return ( - next(prefix_separator_iterator) + - var_name_piece + - value_pair_equals + - prefix_separator_iterator.item_separator.join(item_values) - ) - # exploded - return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( - [var_name_piece + value_pair_equals + val for val in item_values] - ) - elif isinstance(in_data, dict): - in_data_transformed = {key: cls.__ref6570_item_value(val, percent_encode) for key, val in in_data.items()} - in_data_transformed = {key: val for key, val in in_data_transformed.items() if val is not None} - if not in_data_transformed: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return "" - value_pair_equals = '=' if named_parameter_expansion else '' - if not explode: - return ( - next(prefix_separator_iterator) + - var_name_piece + value_pair_equals + - prefix_separator_iterator.item_separator.join( - prefix_separator_iterator.item_separator.join( - item_pair - ) for item_pair in in_data_transformed.items() - ) - ) - # exploded - return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( - [key + '=' + val for key, val in in_data_transformed.items()] - ) - # bool, bytes, etc - raise ApiValueError('Unable to generate a ref6570 representation of {}'.format(in_data)) - - -class StyleFormSerializer(ParameterSerializerBase): - @classmethod - def get_default_explode(cls, style: ParameterStyle) -> bool: - if style is ParameterStyle.FORM: - return True - return super().get_default_explode(style) - - def serialize_form( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - name: str, - explode: bool, - percent_encode: bool, - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None - ) -> str: - if prefix_separator_iterator is None: - prefix_separator_iterator = PrefixSeparatorIterator('?', '&') - return self.ref6570_expansion( - variable_name=name, - in_data=in_data, - explode=explode, - percent_encode=percent_encode, - prefix_separator_iterator=prefix_separator_iterator - ) - - -class StyleSimpleSerializer(ParameterSerializerBase): - - def serialize_simple( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - name: str, - explode: bool, - percent_encode: bool - ) -> str: - prefix_separator_iterator = PrefixSeparatorIterator('', ',') - return self.ref6570_expansion( - variable_name=name, - in_data=in_data, - explode=explode, - percent_encode=percent_encode, - prefix_separator_iterator=prefix_separator_iterator - ) - - -@dataclass -class ParameterBase: - name: str - in_type: ParameterInType - required: bool - style: typing.Optional[ParameterStyle] - explode: typing.Optional[bool] - allow_reserved: typing.Optional[bool] - schema: typing.Optional[typing.Type[Schema]] - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] - - __style_to_in_type = { - ParameterStyle.MATRIX: {ParameterInType.PATH}, - ParameterStyle.LABEL: {ParameterInType.PATH}, - ParameterStyle.FORM: {ParameterInType.QUERY, ParameterInType.COOKIE}, - ParameterStyle.SIMPLE: {ParameterInType.PATH, ParameterInType.HEADER}, - ParameterStyle.SPACE_DELIMITED: {ParameterInType.QUERY}, - ParameterStyle.PIPE_DELIMITED: {ParameterInType.QUERY}, - ParameterStyle.DEEP_OBJECT: {ParameterInType.QUERY}, - } - __in_type_to_default_style = { - ParameterInType.QUERY: ParameterStyle.FORM, - ParameterInType.PATH: ParameterStyle.SIMPLE, - ParameterInType.HEADER: ParameterStyle.SIMPLE, - ParameterInType.COOKIE: ParameterStyle.FORM, - } - __disallowed_header_names = {'Accept', 'Content-Type', 'Authorization'} - _json_encoder = JSONEncoder() - _json_content_type = 'application/json' - - @classmethod - def __verify_style_to_in_type(cls, style: typing.Optional[ParameterStyle], in_type: ParameterInType): - if style is None: - return - in_type_set = cls.__style_to_in_type[style] - if in_type not in in_type_set: - raise ValueError( - 'Invalid style and in_type combination. For style={} only in_type={} are allowed'.format( - style, in_type_set - ) - ) - - def __init__( - self, - name: str, - in_type: ParameterInType, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: bool = False, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - if schema is None and content is None: - raise ValueError('Value missing; Pass in either schema or content') - if schema and content: - raise ValueError('Too many values provided. Both schema and content were provided. Only one may be input') - if name in self.__disallowed_header_names and in_type is ParameterInType.HEADER: - raise ValueError('Invalid name, name may not be one of {}'.format(self.__disallowed_header_names)) - self.__verify_style_to_in_type(style, in_type) - if content is None and style is None: - style = self.__in_type_to_default_style[in_type] - if content is not None and in_type in self.__in_type_to_default_style and len(content) != 1: - raise ValueError('Invalid content length, content length must equal 1') - self.in_type = in_type - self.name = name - self.required = required - self.style = style - self.explode = explode - self.allow_reserved = allow_reserved - self.schema = schema - self.content = content - - @staticmethod - def _remove_empty_and_cast( - in_data: typing.Tuple[typing.Tuple[str, str]], - ) -> typing.Dict[str, str]: - data = tuple(t for t in in_data if t) - if not data: - return dict() - return dict(data) - - def _serialize_json( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list] - ) -> str: - return json.dumps(in_data) - - -class PathParameter(ParameterBase, StyleSimpleSerializer): - - def __init__( - self, - name: str, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: bool = False, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - super().__init__( - name, - in_type=ParameterInType.PATH, - required=required, - style=style, - explode=explode, - allow_reserved=allow_reserved, - schema=schema, - content=content - ) - - def _serialize_label( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list] - ) -> typing.Dict[str, str]: - prefix_separator_iterator = PrefixSeparatorIterator('.', '.') - value = self.ref6570_expansion( - variable_name=self.name, - in_data=in_data, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def _serialize_matrix( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list] - ) -> typing.Dict[str, str]: - prefix_separator_iterator = PrefixSeparatorIterator(';', ';') - value = self.ref6570_expansion( - variable_name=self.name, - in_data=in_data, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def _serialize_simple( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - ) -> typing.Dict[str, str]: - value = self.serialize_simple( - in_data=in_data, - name=self.name, - explode=self.explode, - percent_encode=True - ) - return self.to_dict(self.name, value) - - def serialize( - self, - in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] - ) -> typing.Dict[str, str]: - if self.schema: - cast_in_data = self.schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - """ - simple -> path - path: - returns path_params: dict - label -> path - returns path_params - matrix -> path - returns path_params - """ - if self.style: - if self.style is ParameterStyle.SIMPLE: - return self._serialize_simple(cast_in_data) - elif self.style is ParameterStyle.LABEL: - return self._serialize_label(cast_in_data) - elif self.style is ParameterStyle.MATRIX: - return self._serialize_matrix(cast_in_data) - # self.content will be length one - for content_type, schema in self.content.items(): - cast_in_data = schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: - value = self._serialize_json(cast_in_data) - return self.to_dict(self.name, value) - raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) - - -class QueryParameter(ParameterBase, StyleFormSerializer): - - def __init__( - self, - name: str, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: typing.Optional[bool] = None, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - used_style = ParameterStyle.FORM if style is None and content is None and schema else style - used_explode = self.get_default_explode(used_style) if explode is None else explode - - super().__init__( - name, - in_type=ParameterInType.QUERY, - required=required, - style=used_style, - explode=used_explode, - allow_reserved=allow_reserved, - schema=schema, - content=content - ) - - def __serialize_space_delimited( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] - ) -> typing.Dict[str, str]: - if prefix_separator_iterator is None: - prefix_separator_iterator = self.get_prefix_separator_iterator() - value = self.ref6570_expansion( - variable_name=self.name, - in_data=in_data, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def __serialize_pipe_delimited( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] - ) -> typing.Dict[str, str]: - if prefix_separator_iterator is None: - prefix_separator_iterator = self.get_prefix_separator_iterator() - value = self.ref6570_expansion( - variable_name=self.name, - in_data=in_data, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def __serialize_form( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] - ) -> typing.Dict[str, str]: - if prefix_separator_iterator is None: - prefix_separator_iterator = self.get_prefix_separator_iterator() - value = self.serialize_form( - in_data, - name=self.name, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def get_prefix_separator_iterator(self) -> typing.Optional[PrefixSeparatorIterator]: - if not self.schema: - return None - if self.style is ParameterStyle.FORM: - return PrefixSeparatorIterator('?', '&') - elif self.style is ParameterStyle.SPACE_DELIMITED: - return PrefixSeparatorIterator('', '%20') - elif self.style is ParameterStyle.PIPE_DELIMITED: - return PrefixSeparatorIterator('', '|') - - def serialize( - self, - in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict], - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None - ) -> typing.Dict[str, str]: - if self.schema: - cast_in_data = self.schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - """ - form -> query - query: - - GET/HEAD/DELETE: could use fields - - PUT/POST: must use urlencode to send parameters - returns fields: tuple - spaceDelimited -> query - returns fields - pipeDelimited -> query - returns fields - deepObject -> query, https://github.com/OAI/OpenAPI-Specification/issues/1706 - returns fields - """ - if self.style: - # TODO update query ones to omit setting values when [] {} or None is input - if self.style is ParameterStyle.FORM: - return self.__serialize_form(cast_in_data, prefix_separator_iterator) - elif self.style is ParameterStyle.SPACE_DELIMITED: - return self.__serialize_space_delimited(cast_in_data, prefix_separator_iterator) - elif self.style is ParameterStyle.PIPE_DELIMITED: - return self.__serialize_pipe_delimited(cast_in_data, prefix_separator_iterator) - # self.content will be length one - for content_type, schema in self.content.items(): - cast_in_data = schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: - value = self._serialize_json(cast_in_data) - return self.to_dict(self.name, value) - raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) - - -class CookieParameter(ParameterBase, StyleFormSerializer): - - def __init__( - self, - name: str, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: typing.Optional[bool] = None, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - used_style = ParameterStyle.FORM if style is None and content is None and schema else style - used_explode = self.get_default_explode(used_style) if explode is None else explode - - super().__init__( - name, - in_type=ParameterInType.COOKIE, - required=required, - style=used_style, - explode=used_explode, - allow_reserved=allow_reserved, - schema=schema, - content=content - ) - - def serialize( - self, - in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] - ) -> typing.Dict[str, str]: - if self.schema: - cast_in_data = self.schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - """ - form -> cookie - returns fields: tuple - """ - if self.style: - """ - TODO add escaping of comma, space, equals - or turn encoding on - """ - value = self.serialize_form( - cast_in_data, - explode=self.explode, - name=self.name, - percent_encode=False, - prefix_separator_iterator=PrefixSeparatorIterator('', '&') - ) - return self.to_dict(self.name, value) - # self.content will be length one - for content_type, schema in self.content.items(): - cast_in_data = schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: - value = self._serialize_json(cast_in_data) - return self.to_dict(self.name, value) - raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) - - -class HeaderParameter(ParameterBase, StyleSimpleSerializer): - def __init__( - self, - name: str, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: bool = False, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - super().__init__( - name, - in_type=ParameterInType.HEADER, - required=required, - style=style, - explode=explode, - allow_reserved=allow_reserved, - schema=schema, - content=content - ) - - @staticmethod - def __to_headers(in_data: typing.Tuple[typing.Tuple[str, str], ...]) -> HTTPHeaderDict[str, str]: - data = tuple(t for t in in_data if t) - headers = HTTPHeaderDict() - if not data: - return headers - headers.extend(data) - return headers - - def _serialize_simple( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - ) -> str: - return self.serialize_simple(in_data, self.name, self.explode, False) - - def serialize( - self, - in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] - ) -> HTTPHeaderDict[str, str]: - if self.schema: - cast_in_data = self.schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - """ - simple -> header - headers: PoolManager needs a mapping, tuple is close - returns headers: dict - """ - if self.style: - value = self._serialize_simple(cast_in_data) - return self.__to_headers(((self.name, value),)) - # self.content will be length one - for content_type, schema in self.content.items(): - cast_in_data = schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: - value = self._serialize_json(cast_in_data) - return self.__to_headers(((self.name, value),)) - raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) - - -class Encoding: - def __init__( - self, - content_type: str, - headers: typing.Optional[typing.Dict[str, HeaderParameter]] = None, - style: typing.Optional[ParameterStyle] = None, - explode: bool = False, - allow_reserved: bool = False, - ): - self.content_type = content_type - self.headers = headers - self.style = style - self.explode = explode - self.allow_reserved = allow_reserved - - -@dataclass -class MediaType: - """ - Used to store request and response body schema information - encoding: - A map between a property name and its encoding information. - The key, being the property name, MUST exist in the schema as a property. - The encoding object SHALL only apply to requestBody objects when the media type is - multipart or application/x-www-form-urlencoded. - """ - schema: typing.Optional[typing.Type[Schema]] = None - encoding: typing.Optional[typing.Dict[str, Encoding]] = None - - -@dataclass -class ApiResponse: - response: urllib3.HTTPResponse - body: typing.Union[Unset, typing.Type[Schema]] - headers: typing.Union[Unset, typing.List[HeaderParameter]] - - def __init__( - self, - response: urllib3.HTTPResponse, - body: typing.Union[Unset, typing.Type[Schema]], - headers: typing.Union[Unset, typing.List[HeaderParameter]] - ): - """ - pycharm needs this to prevent 'Unexpected argument' warnings - """ - self.response = response - self.body = body - self.headers = headers - - -@dataclass -class ApiResponseWithoutDeserialization(ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[Unset, typing.Type[Schema]] = unset - headers: typing.Union[Unset, typing.List[HeaderParameter]] = unset - - -class JSONDetector: - @staticmethod - def content_type_is_json(content_type: str) -> bool: - """ - for when content_type strings also include charset info like: - application/json; charset=UTF-8 - """ - content_type_piece = content_type.split(';')[0] - if content_type_piece == 'application/json': - return True - return False - - -class OpenApiResponse(JSONDetector): - def __init__( - self, - response_cls: typing.Type[ApiResponse] = ApiResponse, - content: typing.Optional[typing.Dict[str, MediaType]] = None, - headers: typing.Optional[typing.List[HeaderParameter]] = None, - ): - self.headers = headers - if content is not None and len(content) == 0: - raise ValueError('Invalid value for content, the content dict must have >= 1 entry') - self.content = content - self.response_cls = response_cls - - @staticmethod - def __deserialize_json(response: urllib3.HTTPResponse) -> typing.Any: - # python must be >= 3.9 so we can pass in bytes into json.loads - return json.loads(response.data) - - @staticmethod - def __file_name_from_content_disposition(content_disposition: typing.Optional[str]) -> typing.Optional[str]: - if content_disposition is None: - return None - match = re.search('filename="(.+?)"', content_disposition) - if not match: - return None - return match.group(1) - - def __deserialize_application_octet_stream( - self, response: urllib3.HTTPResponse - ) -> typing.Union[bytes, io.BufferedReader]: - """ - urllib3 use cases: - 1. when preload_content=True (stream=False) then supports_chunked_reads is False and bytes are returned - 2. when preload_content=False (stream=True) then supports_chunked_reads is True and - a file will be written and returned - """ - if response.supports_chunked_reads(): - file_name = self.__file_name_from_content_disposition(response.headers.get('content-disposition')) - - if file_name is None: - _fd, path = tempfile.mkstemp() - else: - path = os.path.join(tempfile.gettempdir(), file_name) - # TODO get file_name from the filename at the end of the url if it exists - with open(path, 'wb') as new_file: - chunk_size = 1024 - while True: - data = response.read(chunk_size) - if not data: - break - new_file.write(data) - # release_conn is needed for streaming connections only - response.release_conn() - new_file = open(path, 'rb') - return new_file - else: - return response.data - - @staticmethod - def __deserialize_multipart_form_data( - response: urllib3.HTTPResponse - ) -> typing.Dict[str, typing.Any]: - msg = email.message_from_bytes(response.data) - return { - part.get_param("name", header="Content-Disposition"): part.get_payload( - decode=True - ).decode(part.get_content_charset()) - if part.get_content_charset() - else part.get_payload() - for part in msg.get_payload() - } - - def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse: - content_type = response.getheader('content-type') - deserialized_body = unset - streamed = response.supports_chunked_reads() - - deserialized_headers = unset - if self.headers is not None: - # TODO add header deserialiation here - pass - - if self.content is not None: - if content_type not in self.content: - raise ApiValueError( - f'Invalid content_type={content_type} returned for response with ' - 'status_code={str(response.status)}' - ) - body_schema = self.content[content_type].schema - if body_schema is None: - # some specs do not define response content media type schemas - return self.response_cls( - response=response, - headers=deserialized_headers, - body=unset - ) - - if self.content_type_is_json(content_type): - body_data = self.__deserialize_json(response) - elif content_type == 'application/octet-stream': - body_data = self.__deserialize_application_octet_stream(response) - elif content_type.startswith('multipart/form-data'): - body_data = self.__deserialize_multipart_form_data(response) - content_type = 'multipart/form-data' - else: - raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type)) - deserialized_body = body_schema._from_openapi_data( - body_data, _configuration=configuration) - elif streamed: - response.release_conn() - - return self.response_cls( - response=response, - headers=deserialized_headers, - body=deserialized_body - ) - - -class ApiClient: - """Generic API client for OpenAPI client library builds. - - OpenAPI generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the OpenAPI - templates. - - NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - Do not edit the class manually. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. - """ - - _pool = None - __json_encoder = JSONEncoder() - - def __init__( - self, - configuration: typing.Optional[Configuration] = None, - header_name: typing.Optional[str] = None, - header_value: typing.Optional[str] = None, - cookie: typing.Optional[str] = None, - pool_threads: int = 1 - ): - if configuration is None: - configuration = Configuration() - self.configuration = configuration - self.pool_threads = pool_threads - - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = 'OpenAPI-Generator/1.0.0/python' - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api( - self, - resource_path: str, - method: str, - headers: typing.Optional[HTTPHeaderDict] = None, - body: typing.Optional[typing.Union[str, bytes]] = None, - fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, - auth_settings: typing.Optional[typing.List[str]] = None, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - host: typing.Optional[str] = None, - ) -> urllib3.HTTPResponse: - - # header parameters - headers = headers or {} - headers.update(self.default_headers) - if self.cookie: - headers['Cookie'] = self.cookie - - # auth setting - self.update_params_for_auth(headers, - auth_settings, resource_path, method, body) - - # request url - if host is None: - url = self.configuration.host + resource_path - else: - # use server/host defined in path or operation instead - url = host + resource_path - - # perform request and return response - response = self.request( - method, - url, - headers=headers, - fields=fields, - body=body, - stream=stream, - timeout=timeout, - ) - return response - - def call_api( - self, - resource_path: str, - method: str, - headers: typing.Optional[HTTPHeaderDict] = None, - body: typing.Optional[typing.Union[str, bytes]] = None, - fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, - auth_settings: typing.Optional[typing.List[str]] = None, - async_req: typing.Optional[bool] = None, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - host: typing.Optional[str] = None, - ) -> urllib3.HTTPResponse: - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param headers: Header parameters to be - placed in the request header. - :param body: Request body. - :param fields: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings: Auth Settings names for the request. - :param async_req: execute request asynchronously - :type async_req: bool, optional TODO remove, unused - :param stream: if True, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Also when True, if the openapi spec describes a file download, - the data will be written to a local filesystme file and the BinarySchema - instance will also inherit from FileSchema and FileIO - Default is False. - :type stream: bool, optional - :param timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param host: api endpoint host - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - - if not async_req: - return self.__call_api( - resource_path, - method, - headers, - body, - fields, - auth_settings, - stream, - timeout, - host, - ) - - return self.pool.apply_async( - self.__call_api, - ( - resource_path, - method, - headers, - body, - json, - fields, - auth_settings, - stream, - timeout, - host, - ) - ) - - def request( - self, - method: str, - url: str, - headers: typing.Optional[HTTPHeaderDict] = None, - fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, - body: typing.Optional[typing.Union[str, bytes]] = None, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - ) -> urllib3.HTTPResponse: - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.GET(url, - stream=stream, - timeout=timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.HEAD(url, - stream=stream, - timeout=timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.OPTIONS(url, - headers=headers, - fields=fields, - stream=stream, - timeout=timeout, - body=body) - elif method == "POST": - return self.rest_client.POST(url, - headers=headers, - fields=fields, - stream=stream, - timeout=timeout, - body=body) - elif method == "PUT": - return self.rest_client.PUT(url, - headers=headers, - fields=fields, - stream=stream, - timeout=timeout, - body=body) - elif method == "PATCH": - return self.rest_client.PATCH(url, - headers=headers, - fields=fields, - stream=stream, - timeout=timeout, - body=body) - elif method == "DELETE": - return self.rest_client.DELETE(url, - headers=headers, - stream=stream, - timeout=timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def update_params_for_auth(self, headers, auth_settings, - resource_path, method, body): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param auth_settings: Authentication setting identifiers list. - :param resource_path: A string representation of the HTTP request resource path. - :param method: A string representation of the HTTP request method. - :param body: A object representing the body of the HTTP request. - The object type is the return value of _encoder.default(). - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if auth_setting['in'] == 'cookie': - headers.add('Cookie', auth_setting['value']) - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers.add(auth_setting['key'], auth_setting['value']) - elif auth_setting['in'] == 'query': - """ TODO implement auth in query - need to pass in prefix_separator_iterator - and need to output resource_path with query params added - """ - raise ApiValueError("Auth in query not yet implemented") - else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) - - -class Api: - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client: typing.Optional[ApiClient] = None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - @staticmethod - def _verify_typed_dict_inputs(cls: typing.Type[typing.TypedDict], data: typing.Dict[str, typing.Any]): - """ - Ensures that: - - required keys are present - - additional properties are not input - - value stored under required keys do not have the value unset - Note: detailed value checking is done in schema classes - """ - missing_required_keys = [] - required_keys_with_unset_values = [] - for required_key in cls.__required_keys__: - if required_key not in data: - missing_required_keys.append(required_key) - continue - value = data[required_key] - if value is unset: - required_keys_with_unset_values.append(required_key) - if missing_required_keys: - raise ApiTypeError( - '{} missing {} required arguments: {}'.format( - cls.__name__, len(missing_required_keys), missing_required_keys - ) - ) - if required_keys_with_unset_values: - raise ApiValueError( - '{} contains invalid unset values for {} required keys: {}'.format( - cls.__name__, len(required_keys_with_unset_values), required_keys_with_unset_values - ) - ) - - disallowed_additional_keys = [] - for key in data: - if key in cls.__required_keys__ or key in cls.__optional_keys__: - continue - disallowed_additional_keys.append(key) - if disallowed_additional_keys: - raise ApiTypeError( - '{} got {} unexpected keyword arguments: {}'.format( - cls.__name__, len(disallowed_additional_keys), disallowed_additional_keys - ) - ) - - def get_host( - self, - operation_id: str, - servers: typing.Tuple[typing.Dict[str, str], ...] = tuple(), - host_index: typing.Optional[int] = None - ) -> typing.Optional[str]: - configuration = self.api_client.configuration - try: - if host_index is None: - index = configuration.server_operation_index.get( - operation_id, configuration.server_index - ) - else: - index = host_index - server_variables = configuration.server_operation_variables.get( - operation_id, configuration.server_variables - ) - host = configuration.get_host_from_settings( - index, variables=server_variables, servers=servers - ) - except IndexError: - if servers: - raise ApiValueError( - "Invalid host index. Must be 0 <= index < %s" % - len(servers) - ) - host = None - return host - - -class SerializedRequestBody(typing.TypedDict, total=False): - body: typing.Union[str, bytes] - fields: typing.Tuple[typing.Union[RequestField, tuple[str, str]], ...] - - -class RequestBody(StyleFormSerializer, JSONDetector): - """ - A request body parameter - content: content_type to MediaType Schema info - """ - __json_encoder = JSONEncoder() - - def __init__( - self, - content: typing.Dict[str, MediaType], - required: bool = False, - ): - self.required = required - if len(content) == 0: - raise ValueError('Invalid value for content, the content dict must have >= 1 entry') - self.content = content - - def __serialize_json( - self, - in_data: typing.Any - ) -> typing.Dict[str, bytes]: - in_data = self.__json_encoder.default(in_data) - json_str = json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode( - "utf-8" - ) - return dict(body=json_str) - - @staticmethod - def __serialize_text_plain(in_data: typing.Any) -> typing.Dict[str, str]: - if isinstance(in_data, frozendict): - raise ValueError('Unable to serialize type frozendict to text/plain') - elif isinstance(in_data, tuple): - raise ValueError('Unable to serialize type tuple to text/plain') - elif isinstance(in_data, NoneClass): - raise ValueError('Unable to serialize type NoneClass to text/plain') - elif isinstance(in_data, BoolClass): - raise ValueError('Unable to serialize type BoolClass to text/plain') - return dict(body=str(in_data)) - - def __multipart_json_item(self, key: str, value: Schema) -> RequestField: - json_value = self.__json_encoder.default(value) - return RequestField(name=key, data=json.dumps(json_value), headers={'Content-Type': 'application/json'}) - - def __multipart_form_item(self, key: str, value: Schema) -> RequestField: - if isinstance(value, str): - return RequestField(name=key, data=str(value), headers={'Content-Type': 'text/plain'}) - elif isinstance(value, bytes): - return RequestField(name=key, data=value, headers={'Content-Type': 'application/octet-stream'}) - elif isinstance(value, FileIO): - request_field = RequestField( - name=key, - data=value.read(), - filename=os.path.basename(value.name), - headers={'Content-Type': 'application/octet-stream'} - ) - value.close() - return request_field - else: - return self.__multipart_json_item(key=key, value=value) - - def __serialize_multipart_form_data( - self, in_data: Schema - ) -> typing.Dict[str, typing.Tuple[RequestField, ...]]: - if not isinstance(in_data, frozendict): - raise ValueError(f'Unable to serialize {in_data} to multipart/form-data because it is not a dict of data') - """ - In a multipart/form-data request body, each schema property, or each element of a schema array property, - takes a section in the payload with an internal header as defined by RFC7578. The serialization strategy - for each property of a multipart/form-data request body can be specified in an associated Encoding Object. - - When passing in multipart types, boundaries MAY be used to separate sections of the content being - transferred – thus, the following default Content-Types are defined for multipart: - - If the (object) property is a primitive, or an array of primitive values, the default Content-Type is text/plain - If the property is complex, or an array of complex values, the default Content-Type is application/json - Question: how is the array of primitives encoded? - If the property is a type: string with a contentEncoding, the default Content-Type is application/octet-stream - """ - fields = [] - for key, value in in_data.items(): - if isinstance(value, tuple): - if value: - # values use explode = True, so the code makes a RequestField for each item with name=key - for item in value: - request_field = self.__multipart_form_item(key=key, value=item) - fields.append(request_field) - else: - # send an empty array as json because exploding will not send it - request_field = self.__multipart_json_item(key=key, value=value) - fields.append(request_field) - else: - request_field = self.__multipart_form_item(key=key, value=value) - fields.append(request_field) - - return dict(fields=tuple(fields)) - - def __serialize_application_octet_stream(self, in_data: BinarySchema) -> typing.Dict[str, bytes]: - if isinstance(in_data, bytes): - return dict(body=in_data) - # FileIO type - result = dict(body=in_data.read()) - in_data.close() - return result - - def __serialize_application_x_www_form_data( - self, in_data: typing.Any - ) -> SerializedRequestBody: - """ - POST submission of form data in body - """ - if not isinstance(in_data, frozendict): - raise ValueError( - f'Unable to serialize {in_data} to application/x-www-form-urlencoded because it is not a dict of data') - cast_in_data = self.__json_encoder.default(in_data) - value = self.serialize_form(cast_in_data, name='', explode=True, percent_encode=False) - return dict(body=value) - - def serialize( - self, in_data: typing.Any, content_type: str - ) -> SerializedRequestBody: - """ - If a str is returned then the result will be assigned to data when making the request - If a tuple is returned then the result will be used as fields input in encode_multipart_formdata - Return a tuple of - - The key of the return dict is - - body for application/json - - encode_multipart and fields for multipart/form-data - """ - media_type = self.content[content_type] - if isinstance(in_data, media_type.schema): - cast_in_data = in_data - elif isinstance(in_data, (dict, frozendict)) and in_data: - cast_in_data = media_type.schema(**in_data) - else: - cast_in_data = media_type.schema(in_data) - # TODO check for and use encoding if it exists - # and content_type is multipart or application/x-www-form-urlencoded - if self.content_type_is_json(content_type): - return self.__serialize_json(cast_in_data) - elif content_type == 'text/plain': - return self.__serialize_text_plain(cast_in_data) - elif content_type == 'multipart/form-data': - return self.__serialize_multipart_form_data(cast_in_data) - elif content_type == 'application/x-www-form-urlencoded': - return self.__serialize_application_x_www_form_data(cast_in_data) - elif content_type == 'application/octet-stream': - return self.__serialize_application_octet_stream(cast_in_data) - raise NotImplementedError('Serialization has not yet been implemented for {}'.format(content_type)) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/configuration.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/configuration.py deleted file mode 100644 index 80407ef4b4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/configuration.py +++ /dev/null @@ -1,440 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -from http import client as http_client -from unit_test_api.exceptions import ApiValueError - - -JSON_SCHEMA_VALIDATION_KEYWORDS = { - 'multipleOf', 'maximum', 'exclusiveMaximum', - 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems', - 'uniqueItems', 'maxProperties', 'minProperties', -} - -class Configuration(object): - """NOTE: This class is auto generated by OpenAPI Generator - - Ref: https://openapi-generator.tech - Do not edit the class manually. - - :param host: Base url - :param api_key: Dict to store API key(s). - Each entry in the dict specifies an API key. - The dict key is the name of the security scheme in the OAS specification. - The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer) - The dict key is the name of the security scheme in the OAS specification. - The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication - :param password: Password for HTTP basic authentication - :param discard_unknown_keys: Boolean value indicating whether to discard - unknown properties. A server may send a response that includes additional - properties that are not known by the client in the following scenarios: - 1. The OpenAPI document is incomplete, i.e. it does not match the server - implementation. - 2. The client was generated using an older version of the OpenAPI document - and the server has been upgraded since then. - If a schema in the OpenAPI document defines the additionalProperties attribute, - then all undeclared properties received by the server are injected into the - additional properties map. In that case, there are undeclared properties, and - nothing to discard. - :param disabled_client_side_validations (string): Comma-separated list of - JSON schema validation keywords to disable JSON schema structural validation - rules. The following keywords may be specified: multipleOf, maximum, - exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, - maxItems, minItems. - By default, the validation is performed for data generated locally by the client - and data received from the server, independent of any validation performed by - the server side. If the input data does not satisfy the JSON schema validation - rules specified in the OpenAPI document, an exception is raised. - If disabled_client_side_validations is set, structural validation is - disabled. This can be useful to troubleshoot data validation problem, such as - when the OpenAPI document validation rules do not match the actual API data - received by the server. - :param server_index: Index to servers configuration. - :param server_variables: Mapping with string values to replace variables in - templated server configuration. The validation of enums is performed for - variables with defined enum values before. - :param server_operation_index: Mapping from operation ID to an index to server - configuration. - :param server_operation_variables: Mapping from operation ID to a mapping with - string values to replace variables in templated server configuration. - The validation of enums is performed for variables with defined enum values before. - - """ - - _default = None - - def __init__(self, host=None, - api_key=None, api_key_prefix=None, - username=None, password=None, - discard_unknown_keys=False, - disabled_client_side_validations="", - server_index=None, server_variables=None, - server_operation_index=None, server_operation_variables=None, - ): - """Constructor - """ - self._base_path = "http://localhost" if host is None else host - """Default Base url - """ - self.server_index = 0 if server_index is None and host is None else server_index - self.server_operation_index = server_operation_index or {} - """Default server index - """ - self.server_variables = server_variables or {} - self.server_operation_variables = server_operation_variables or {} - """Default server variables - """ - self.temp_folder_path = None - """Temp file folder for downloading files - """ - # Authentication Settings - self.api_key = {} - if api_key: - self.api_key = api_key - """dict to store API key(s) - """ - self.api_key_prefix = {} - if api_key_prefix: - self.api_key_prefix = api_key_prefix - """dict to store API prefix (e.g. Bearer) - """ - self.refresh_api_key_hook = None - """function hook to refresh API key if expired - """ - self.username = username - """Username for HTTP basic authentication - """ - self.password = password - """Password for HTTP basic authentication - """ - self.discard_unknown_keys = discard_unknown_keys - self.disabled_client_side_validations = disabled_client_side_validations - self.logger = {} - """Logging Settings - """ - self.logger["package_logger"] = logging.getLogger("unit_test_api") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - """Log format - """ - self.logger_stream_handler = None - """Log stream handler - """ - self.logger_file_handler = None - """Log file handler - """ - self.logger_file = None - """Debug file location - """ - self.debug = False - """Debug switch - """ - - self.verify_ssl = True - """SSL/TLS verification - Set this to false to skip verifying SSL certificate when calling API - from https server. - """ - self.ssl_ca_cert = None - """Set this to customize the certificate file to verify the peer. - """ - self.cert_file = None - """client certificate file - """ - self.key_file = None - """client key file - """ - self.assert_hostname = None - """Set this to True/False to enable/disable SSL hostname verification. - """ - - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - """urllib3 connection pool's maximum number of connections saved - per pool. urllib3 uses 1 connection as default value, but this is - not the best value when you are making a lot of possibly parallel - requests to the same host, which is often the case here. - cpu_count * 5 is used as default value to increase performance. - """ - - self.proxy = None - """Proxy URL - """ - self.proxy_headers = None - """Proxy headers - """ - self.safe_chars_for_path_param = '' - """Safe chars for path_param - """ - self.retries = None - """Adding retries to override urllib3 default value 3 - """ - # Enable client side validation - self.client_side_validation = True - - # Options to pass down to the underlying urllib3 socket - self.socket_options = None - - def __deepcopy__(self, memo): - cls = self.__class__ - result = cls.__new__(cls) - memo[id(self)] = result - for k, v in self.__dict__.items(): - if k not in ('logger', 'logger_file_handler'): - setattr(result, k, copy.deepcopy(v, memo)) - # shallow copy of loggers - result.logger = copy.copy(self.logger) - # use setters to configure loggers - result.logger_file = self.logger_file - result.debug = self.debug - return result - - def __setattr__(self, name, value): - object.__setattr__(self, name, value) - if name == 'disabled_client_side_validations': - s = set(filter(None, value.split(','))) - for v in s: - if v not in JSON_SCHEMA_VALIDATION_KEYWORDS: - raise ApiValueError( - "Invalid keyword: '{0}''".format(v)) - self._disabled_client_side_validations = s - - @classmethod - def set_default(cls, default): - """Set default instance of configuration. - - It stores default configuration, which can be - returned by get_default_copy method. - - :param default: object of Configuration - """ - cls._default = copy.deepcopy(default) - - @classmethod - def get_default_copy(cls): - """Return new instance of configuration. - - This method returns newly created, based on default constructor, - object of Configuration class or returns a copy of default - configuration passed by the set_default method. - - :return: The configuration object. - """ - if cls._default is not None: - return copy.deepcopy(cls._default) - return Configuration() - - @property - def logger_file(self): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in self.logger.items(): - logger.addHandler(self.logger_file_handler) - - @property - def debug(self): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in self.logger.items(): - logger.setLevel(logging.DEBUG) - # turn on http_client debug - http_client.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in self.logger.items(): - logger.setLevel(logging.WARNING) - # turn off http_client debug - http_client.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier, alias=None): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :param alias: The alternative identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook is not None: - self.refresh_api_key_hook(self) - key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - username = "" - if self.username is not None: - username = self.username - password = "" - if self.password is not None: - password = self.password - return urllib3.util.make_headers( - basic_auth=username + ':' + password - ).get('authorization') - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - auth = {} - return auth - - def to_debug_report(self): - """Gets the essential information for debugging. - - :return: The report for debugging. - """ - return "Python SDK Debug Report:\n"\ - "OS: {env}\n"\ - "Python Version: {pyversion}\n"\ - "Version of the API: 0.0.1\n"\ - "SDK Package Version: 1.0.0".\ - format(env=sys.platform, pyversion=sys.version) - - def get_host_settings(self): - """Gets an array of host settings - - :return: An array of host settings - """ - return [ - { - 'url': "", - 'description': "No description provided", - } - ] - - def get_host_from_settings(self, index, variables=None, servers=None): - """Gets host URL based on the index and variables - :param index: array index of the host settings - :param variables: hash of variable and the corresponding value - :param servers: an array of host settings or None - :return: URL based on host settings - """ - if index is None: - return self._base_path - - variables = {} if variables is None else variables - servers = self.get_host_settings() if servers is None else servers - - try: - server = servers[index] - except IndexError: - raise ValueError( - "Invalid index {0} when selecting the host settings. " - "Must be less than {1}".format(index, len(servers))) - - url = server['url'] - - # go through variables and replace placeholders - for variable_name, variable in server.get('variables', {}).items(): - used_value = variables.get( - variable_name, variable['default_value']) - - if 'enum_values' in variable \ - and used_value not in variable['enum_values']: - raise ValueError( - "The variable `{0}` in the host URL has invalid value " - "{1}. Must be {2}.".format( - variable_name, variables[variable_name], - variable['enum_values'])) - - url = url.replace("{" + variable_name + "}", used_value) - - return url - - @property - def host(self): - """Return generated host.""" - return self.get_host_from_settings(self.server_index, variables=self.server_variables) - - @host.setter - def host(self, value): - """Fix base path.""" - self._base_path = value - self.server_index = None diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.py deleted file mode 100644 index 5f7428df6f..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AdditionalpropertiesAllowsASchemaWhichShouldValidate( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - foo = AnyTypeSchema - bar = AnyTypeSchema - _additional_properties = BoolSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - foo: typing.Union[foo, Unset] = unset, - bar: typing.Union[bar, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AdditionalpropertiesAllowsASchemaWhichShouldValidate': - return super().__new__( - cls, - *args, - foo=foo, - bar=bar, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_are_allowed_by_default.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_are_allowed_by_default.py deleted file mode 100644 index f51599e5a3..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_are_allowed_by_default.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AdditionalpropertiesAreAllowedByDefault( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - foo = AnyTypeSchema - bar = AnyTypeSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: typing.Union[foo, Unset] = unset, - bar: typing.Union[bar, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AdditionalpropertiesAreAllowedByDefault': - return super().__new__( - cls, - *args, - foo=foo, - bar=bar, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_can_exist_by_itself.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_can_exist_by_itself.py deleted file mode 100644 index 7353e1a249..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_can_exist_by_itself.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AdditionalpropertiesCanExistByItself( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _additional_properties = BoolSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AdditionalpropertiesCanExistByItself': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_should_not_look_in_applicators.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_should_not_look_in_applicators.py deleted file mode 100644 index 5f2482fc08..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/additionalproperties_should_not_look_in_applicators.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AdditionalpropertiesShouldNotLookInApplicators( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _additional_properties = BoolSchema - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - AnyTypeSchema - ): - foo = AnyTypeSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: typing.Union[foo, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_0': - return super().__new__( - cls, - *args, - foo=foo, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AdditionalpropertiesShouldNotLookInApplicators': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof.py deleted file mode 100644 index 51d4cec94c..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Allof( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - AnyTypeSchema - ): - _required_property_names = set(( - 'bar', - )) - bar = IntSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - bar: bar, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_0': - return super().__new__( - cls, - *args, - bar=bar, - _configuration=_configuration, - **kwargs, - ) - - - class allOf_1( - AnyTypeSchema - ): - _required_property_names = set(( - 'foo', - )) - foo = StrSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: foo, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - foo=foo, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - allOf_0, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Allof': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_combined_with_anyof_oneof.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_combined_with_anyof_oneof.py deleted file mode 100644 index ebb7195de0..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_combined_with_anyof_oneof.py +++ /dev/null @@ -1,179 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AllofCombinedWithAnyofOneof( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - _SchemaValidator( - multiple_of=2, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_0': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class oneOf_0( - _SchemaValidator( - multiple_of=5, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'oneOf_0': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class anyOf_0( - _SchemaValidator( - multiple_of=3, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'anyOf_0': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - oneOf_0, - ], - 'anyOf': [ - anyOf_0, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AllofCombinedWithAnyofOneof': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_simple_types.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_simple_types.py deleted file mode 100644 index 6115b79c0f..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_simple_types.py +++ /dev/null @@ -1,157 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AllofSimpleTypes( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - _SchemaValidator( - inclusive_maximum=30, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_0': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class allOf_1( - _SchemaValidator( - inclusive_minimum=20, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - allOf_0, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AllofSimpleTypes': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_base_schema.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_base_schema.py deleted file mode 100644 index b0a4665f9b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_base_schema.py +++ /dev/null @@ -1,169 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AllofWithBaseSchema( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'bar', - )) - bar = IntSchema - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - AnyTypeSchema - ): - _required_property_names = set(( - 'foo', - )) - foo = StrSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: foo, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_0': - return super().__new__( - cls, - *args, - foo=foo, - _configuration=_configuration, - **kwargs, - ) - - - class allOf_1( - AnyTypeSchema - ): - _required_property_names = set(( - 'baz', - )) - baz = NoneSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - baz: baz, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - baz=baz, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - allOf_0, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - bar: bar, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AllofWithBaseSchema': - return super().__new__( - cls, - *args, - bar=bar, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_one_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_one_empty_schema.py deleted file mode 100644 index 02678cbcd7..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_one_empty_schema.py +++ /dev/null @@ -1,115 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AllofWithOneEmptySchema( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = AnyTypeSchema - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AllofWithOneEmptySchema': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_the_first_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_the_first_empty_schema.py deleted file mode 100644 index a23acfe6b4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_the_first_empty_schema.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AllofWithTheFirstEmptySchema( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = AnyTypeSchema - allOf_1 = NumberSchema - return { - 'allOf': [ - allOf_0, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AllofWithTheFirstEmptySchema': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_the_last_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_the_last_empty_schema.py deleted file mode 100644 index 82d9ce92d0..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_the_last_empty_schema.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AllofWithTheLastEmptySchema( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = NumberSchema - allOf_1 = AnyTypeSchema - return { - 'allOf': [ - allOf_0, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AllofWithTheLastEmptySchema': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_two_empty_schemas.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_two_empty_schemas.py deleted file mode 100644 index b690851c8b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/allof_with_two_empty_schemas.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AllofWithTwoEmptySchemas( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = AnyTypeSchema - allOf_1 = AnyTypeSchema - return { - 'allOf': [ - allOf_0, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AllofWithTwoEmptySchemas': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof.py deleted file mode 100644 index b1d4591b55..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof.py +++ /dev/null @@ -1,137 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Anyof( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - anyOf_0 = IntSchema - - - class anyOf_1( - _SchemaValidator( - inclusive_minimum=2, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'anyOf_1': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - anyOf_0, - anyOf_1, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Anyof': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof_complex_types.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof_complex_types.py deleted file mode 100644 index 918cb35d65..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof_complex_types.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AnyofComplexTypes( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class anyOf_0( - AnyTypeSchema - ): - _required_property_names = set(( - 'bar', - )) - bar = IntSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - bar: bar, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'anyOf_0': - return super().__new__( - cls, - *args, - bar=bar, - _configuration=_configuration, - **kwargs, - ) - - - class anyOf_1( - AnyTypeSchema - ): - _required_property_names = set(( - 'foo', - )) - foo = StrSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: foo, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'anyOf_1': - return super().__new__( - cls, - *args, - foo=foo, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - anyOf_0, - anyOf_1, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AnyofComplexTypes': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof_with_base_schema.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof_with_base_schema.py deleted file mode 100644 index 48f7374cb2..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof_with_base_schema.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AnyofWithBaseSchema( - ComposedBase, - StrSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class anyOf_0( - _SchemaValidator( - max_length=2, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'anyOf_0': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class anyOf_1( - _SchemaValidator( - min_length=4, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'anyOf_1': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - anyOf_0, - anyOf_1, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[str, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'AnyofWithBaseSchema': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof_with_one_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof_with_one_empty_schema.py deleted file mode 100644 index ba318600bd..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/anyof_with_one_empty_schema.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AnyofWithOneEmptySchema( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - anyOf_0 = NumberSchema - anyOf_1 = AnyTypeSchema - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - anyOf_0, - anyOf_1, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AnyofWithOneEmptySchema': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/array_type_matches_arrays.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/array_type_matches_arrays.py deleted file mode 100644 index 36f1c01424..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/array_type_matches_arrays.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ArrayTypeMatchesArrays( - ListSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _items = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/boolean_type_matches_booleans.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/boolean_type_matches_booleans.py deleted file mode 100644 index 405d65fe29..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/boolean_type_matches_booleans.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -BooleanTypeMatchesBooleans = BoolSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/by_int.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/by_int.py deleted file mode 100644 index 5ae8498de1..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/by_int.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ByInt( - _SchemaValidator( - multiple_of=2, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ByInt': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/by_number.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/by_number.py deleted file mode 100644 index c5692a559b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/by_number.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ByNumber( - _SchemaValidator( - multiple_of=1.5, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ByNumber': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/by_small_number.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/by_small_number.py deleted file mode 100644 index 03b8054a9a..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/by_small_number.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class BySmallNumber( - _SchemaValidator( - multiple_of=0.00010, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'BySmallNumber': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/date_time_format.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/date_time_format.py deleted file mode 100644 index d2a861677d..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/date_time_format.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -DateTimeFormat = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/email_format.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/email_format.py deleted file mode 100644 index 69fcb22239..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/email_format.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -EmailFormat = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with0_does_not_match_false.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with0_does_not_match_false.py deleted file mode 100644 index 65b18883b7..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with0_does_not_match_false.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EnumWith0DoesNotMatchFalse( - _SchemaEnumMaker( - enum_value_to_name={ - 0: "POSITIVE_0", - } - ), - NumberSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def POSITIVE_0(cls): - return cls(0) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with1_does_not_match_true.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with1_does_not_match_true.py deleted file mode 100644 index 48a26545d5..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with1_does_not_match_true.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EnumWith1DoesNotMatchTrue( - _SchemaEnumMaker( - enum_value_to_name={ - 1: "POSITIVE_1", - } - ), - NumberSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def POSITIVE_1(cls): - return cls(1) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with_escaped_characters.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with_escaped_characters.py deleted file mode 100644 index d8394a82a9..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with_escaped_characters.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EnumWithEscapedCharacters( - _SchemaEnumMaker( - enum_value_to_name={ - "foo\nbar": "FOO_BAR", - "foo\rbar": "FOO_BAR", - } - ), - StrSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def FOO_BAR(cls): - return cls("foo\nbar") - - @classmethod - @property - def FOO_BAR(cls): - return cls("foo\rbar") diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with_false_does_not_match0.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with_false_does_not_match0.py deleted file mode 100644 index e58c3e0f3b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with_false_does_not_match0.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EnumWithFalseDoesNotMatch0( - _SchemaEnumMaker( - enum_value_to_name={ - BoolClass.FALSE: "FALSE", - } - ), - BoolSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def FALSE(cls): - return cls(BoolClass.FALSE) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with_true_does_not_match1.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with_true_does_not_match1.py deleted file mode 100644 index 750921e603..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enum_with_true_does_not_match1.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EnumWithTrueDoesNotMatch1( - _SchemaEnumMaker( - enum_value_to_name={ - BoolClass.TRUE: "TRUE", - } - ), - BoolSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def TRUE(cls): - return cls(BoolClass.TRUE) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enums_in_properties.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enums_in_properties.py deleted file mode 100644 index bdaf150d82..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/enums_in_properties.py +++ /dev/null @@ -1,129 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EnumsInProperties( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'bar', - )) - - - class foo( - _SchemaEnumMaker( - enum_value_to_name={ - "foo": "FOO", - } - ), - StrSchema - ): - - @classmethod - @property - def FOO(cls): - return cls("foo") - - - class bar( - _SchemaEnumMaker( - enum_value_to_name={ - "bar": "BAR", - } - ), - StrSchema - ): - - @classmethod - @property - def BAR(cls): - return cls("bar") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - bar: bar, - foo: typing.Union[foo, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'EnumsInProperties': - return super().__new__( - cls, - *args, - bar=bar, - foo=foo, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/forbidden_property.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/forbidden_property.py deleted file mode 100644 index ccdc7ddc58..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/forbidden_property.py +++ /dev/null @@ -1,134 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ForbiddenProperty( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class foo( - ComposedSchema - ): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - NotSchema = AnyTypeSchema - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - NotSchema - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'foo': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: typing.Union[foo, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ForbiddenProperty': - return super().__new__( - cls, - *args, - foo=foo, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/hostname_format.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/hostname_format.py deleted file mode 100644 index c9e0496649..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/hostname_format.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -HostnameFormat = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/integer_type_matches_integers.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/integer_type_matches_integers.py deleted file mode 100644 index 825e64271a..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/integer_type_matches_integers.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -IntegerTypeMatchesIntegers = IntSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.py deleted file mode 100644 index 053368514d..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf( - _SchemaValidator( - multiple_of=0.123456789, - ), - IntSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/invalid_string_value_for_default.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/invalid_string_value_for_default.py deleted file mode 100644 index 827fe68124..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/invalid_string_value_for_default.py +++ /dev/null @@ -1,102 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class InvalidStringValueForDefault( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class bar( - _SchemaValidator( - min_length=4, - ), - StrSchema - ): - pass - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - bar: typing.Union[bar, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'InvalidStringValueForDefault': - return super().__new__( - cls, - *args, - bar=bar, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ipv4_format.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ipv4_format.py deleted file mode 100644 index 59928308a3..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ipv4_format.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -Ipv4Format = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ipv6_format.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ipv6_format.py deleted file mode 100644 index 79234be74f..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ipv6_format.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -Ipv6Format = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/json_pointer_format.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/json_pointer_format.py deleted file mode 100644 index d2fe143e89..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/json_pointer_format.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -JsonPointerFormat = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maximum_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maximum_validation.py deleted file mode 100644 index 5df92433e0..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maximum_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MaximumValidation( - _SchemaValidator( - inclusive_maximum=3.0, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MaximumValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maximum_validation_with_unsigned_integer.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maximum_validation_with_unsigned_integer.py deleted file mode 100644 index 950d86909f..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maximum_validation_with_unsigned_integer.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MaximumValidationWithUnsignedInteger( - _SchemaValidator( - inclusive_maximum=300, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MaximumValidationWithUnsignedInteger': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxitems_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxitems_validation.py deleted file mode 100644 index c972ac75f4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxitems_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MaxitemsValidation( - _SchemaValidator( - max_items=2, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MaxitemsValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxlength_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxlength_validation.py deleted file mode 100644 index de4c7a9acb..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxlength_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MaxlengthValidation( - _SchemaValidator( - max_length=2, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MaxlengthValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxproperties0_means_the_object_is_empty.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxproperties0_means_the_object_is_empty.py deleted file mode 100644 index c601df9f01..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxproperties0_means_the_object_is_empty.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Maxproperties0MeansTheObjectIsEmpty( - _SchemaValidator( - max_properties=0, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Maxproperties0MeansTheObjectIsEmpty': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxproperties_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxproperties_validation.py deleted file mode 100644 index f88050876c..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/maxproperties_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MaxpropertiesValidation( - _SchemaValidator( - max_properties=2, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MaxpropertiesValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minimum_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minimum_validation.py deleted file mode 100644 index 2b4610a446..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minimum_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MinimumValidation( - _SchemaValidator( - inclusive_minimum=1.1, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MinimumValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minimum_validation_with_signed_integer.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minimum_validation_with_signed_integer.py deleted file mode 100644 index 8e7bc84dd4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minimum_validation_with_signed_integer.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MinimumValidationWithSignedInteger( - _SchemaValidator( - inclusive_minimum=-2, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MinimumValidationWithSignedInteger': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minitems_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minitems_validation.py deleted file mode 100644 index b231150684..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minitems_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MinitemsValidation( - _SchemaValidator( - min_items=1, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MinitemsValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minlength_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minlength_validation.py deleted file mode 100644 index 38933cceef..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minlength_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MinlengthValidation( - _SchemaValidator( - min_length=2, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MinlengthValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minproperties_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minproperties_validation.py deleted file mode 100644 index 38e91f35b5..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/minproperties_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MinpropertiesValidation( - _SchemaValidator( - min_properties=1, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MinpropertiesValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/model_not.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/model_not.py deleted file mode 100644 index 49841aa516..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/model_not.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ModelNot( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - NotSchema = IntSchema - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - NotSchema - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ModelNot': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_allof_to_check_validation_semantics.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_allof_to_check_validation_semantics.py deleted file mode 100644 index 41f27e3664..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_allof_to_check_validation_semantics.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NestedAllofToCheckValidationSemantics( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - ComposedSchema - ): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = NoneSchema - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_0': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'NestedAllofToCheckValidationSemantics': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_anyof_to_check_validation_semantics.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_anyof_to_check_validation_semantics.py deleted file mode 100644 index 6c01a59bcc..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_anyof_to_check_validation_semantics.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NestedAnyofToCheckValidationSemantics( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class anyOf_0( - ComposedSchema - ): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - anyOf_0 = NoneSchema - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - anyOf_0, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'anyOf_0': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - anyOf_0, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'NestedAnyofToCheckValidationSemantics': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_items.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_items.py deleted file mode 100644 index c26c788223..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_items.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NestedItems( - ListSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class _items( - ListSchema - ): - - - class _items( - ListSchema - ): - - - class _items( - ListSchema - ): - _items = NumberSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_oneof_to_check_validation_semantics.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_oneof_to_check_validation_semantics.py deleted file mode 100644 index 4f7280c4e0..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nested_oneof_to_check_validation_semantics.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NestedOneofToCheckValidationSemantics( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class oneOf_0( - ComposedSchema - ): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - oneOf_0 = NoneSchema - return { - 'allOf': [ - ], - 'oneOf': [ - oneOf_0, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'oneOf_0': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ], - 'oneOf': [ - oneOf_0, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'NestedOneofToCheckValidationSemantics': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/not_more_complex_schema.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/not_more_complex_schema.py deleted file mode 100644 index a6b6292f11..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/not_more_complex_schema.py +++ /dev/null @@ -1,135 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NotMoreComplexSchema( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class NotSchema( - DictSchema - ): - foo = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - foo: typing.Union[foo, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'NotSchema': - return super().__new__( - cls, - *args, - foo=foo, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - NotSchema - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'NotMoreComplexSchema': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nul_characters_in_strings.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nul_characters_in_strings.py deleted file mode 100644 index 0ee14c8573..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/nul_characters_in_strings.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NulCharactersInStrings( - _SchemaEnumMaker( - enum_value_to_name={ - "hello\x00there": "HELLOTHERE", - } - ), - StrSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def HELLOTHERE(cls): - return cls("hello\x00there") diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/null_type_matches_only_the_null_object.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/null_type_matches_only_the_null_object.py deleted file mode 100644 index 1c634f9eb1..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/null_type_matches_only_the_null_object.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -NullTypeMatchesOnlyTheNullObject = NoneSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/number_type_matches_numbers.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/number_type_matches_numbers.py deleted file mode 100644 index dda953a7cd..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/number_type_matches_numbers.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -NumberTypeMatchesNumbers = NumberSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/object_properties_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/object_properties_validation.py deleted file mode 100644 index 62b75e4b46..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/object_properties_validation.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ObjectPropertiesValidation( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - foo = IntSchema - bar = StrSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: typing.Union[foo, Unset] = unset, - bar: typing.Union[bar, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ObjectPropertiesValidation': - return super().__new__( - cls, - *args, - foo=foo, - bar=bar, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof.py deleted file mode 100644 index 70eb394c43..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof.py +++ /dev/null @@ -1,137 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Oneof( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - oneOf_0 = IntSchema - - - class oneOf_1( - _SchemaValidator( - inclusive_minimum=2, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'oneOf_1': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ], - 'oneOf': [ - oneOf_0, - oneOf_1, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Oneof': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof_complex_types.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof_complex_types.py deleted file mode 100644 index e3c9861ad4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof_complex_types.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class OneofComplexTypes( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class oneOf_0( - AnyTypeSchema - ): - _required_property_names = set(( - 'bar', - )) - bar = IntSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - bar: bar, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'oneOf_0': - return super().__new__( - cls, - *args, - bar=bar, - _configuration=_configuration, - **kwargs, - ) - - - class oneOf_1( - AnyTypeSchema - ): - _required_property_names = set(( - 'foo', - )) - foo = StrSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: foo, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'oneOf_1': - return super().__new__( - cls, - *args, - foo=foo, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ], - 'oneOf': [ - oneOf_0, - oneOf_1, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'OneofComplexTypes': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof_with_base_schema.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof_with_base_schema.py deleted file mode 100644 index 09bf4d2d52..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof_with_base_schema.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class OneofWithBaseSchema( - ComposedBase, - StrSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class oneOf_0( - _SchemaValidator( - min_length=2, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'oneOf_0': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class oneOf_1( - _SchemaValidator( - max_length=4, - ), - AnyTypeSchema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'oneOf_1': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ], - 'oneOf': [ - oneOf_0, - oneOf_1, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[str, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'OneofWithBaseSchema': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof_with_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof_with_empty_schema.py deleted file mode 100644 index 1ccdc627c9..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/oneof_with_empty_schema.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class OneofWithEmptySchema( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - oneOf_0 = NumberSchema - oneOf_1 = AnyTypeSchema - return { - 'allOf': [ - ], - 'oneOf': [ - oneOf_0, - oneOf_1, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'OneofWithEmptySchema': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/pattern_is_not_anchored.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/pattern_is_not_anchored.py deleted file mode 100644 index cedc5529c7..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/pattern_is_not_anchored.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class PatternIsNotAnchored( - _SchemaValidator( - regex=[{ - 'pattern': r'a+', # noqa: E501 - }], - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'PatternIsNotAnchored': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/pattern_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/pattern_validation.py deleted file mode 100644 index 2e80e68fc4..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/pattern_validation.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class PatternValidation( - _SchemaValidator( - regex=[{ - 'pattern': r'^a*$', # noqa: E501 - }], - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'PatternValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/properties_with_escaped_characters.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/properties_with_escaped_characters.py deleted file mode 100644 index e002e23550..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/properties_with_escaped_characters.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class PropertiesWithEscapedCharacters( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - foobar = NumberSchema - locals()["foo\nbar"] = foobar - del locals()['foobar'] - foobar = NumberSchema - locals()["foo\"bar"] = foobar - del locals()['foobar'] - foo_bar = NumberSchema - locals()["foo\\bar"] = foo_bar - del locals()['foo_bar'] - foobar = NumberSchema - locals()["foo\rbar"] = foobar - del locals()['foobar'] - foobar = NumberSchema - locals()["foo\tbar"] = foobar - del locals()['foobar'] - foobar = NumberSchema - locals()["foo\fbar"] = foobar - del locals()['foobar'] - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'PropertiesWithEscapedCharacters': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/property_named_ref_that_is_not_a_reference.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/property_named_ref_that_is_not_a_reference.py deleted file mode 100644 index e041626a9a..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/property_named_ref_that_is_not_a_reference.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class PropertyNamedRefThatIsNotAReference( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - ref = StrSchema - locals()["$ref"] = ref - del locals()['ref'] - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'PropertyNamedRefThatIsNotAReference': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_additionalproperties.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_additionalproperties.py deleted file mode 100644 index 06a4940e93..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_additionalproperties.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class RefInAdditionalproperties( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _additional_properties(cls) -> typing.Type['PropertyNamedRefThatIsNotAReference']: - return PropertyNamedRefThatIsNotAReference - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'RefInAdditionalproperties': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_allof.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_allof.py deleted file mode 100644 index 692e23e079..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_allof.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class RefInAllof( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - PropertyNamedRefThatIsNotAReference, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'RefInAllof': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_anyof.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_anyof.py deleted file mode 100644 index 50a541d05d..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_anyof.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class RefInAnyof( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - PropertyNamedRefThatIsNotAReference, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'RefInAnyof': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_items.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_items.py deleted file mode 100644 index e9c980b72c..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_items.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class RefInItems( - ListSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _items(cls) -> typing.Type['PropertyNamedRefThatIsNotAReference']: - return PropertyNamedRefThatIsNotAReference - -from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_oneof.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_oneof.py deleted file mode 100644 index 073d08ab9a..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_oneof.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class RefInOneof( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ], - 'oneOf': [ - PropertyNamedRefThatIsNotAReference, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'RefInOneof': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_property.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_property.py deleted file mode 100644 index 9dfabb6891..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/ref_in_property.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class RefInProperty( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def a(cls) -> typing.Type['PropertyNamedRefThatIsNotAReference']: - return PropertyNamedRefThatIsNotAReference - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - a: typing.Union['PropertyNamedRefThatIsNotAReference', Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'RefInProperty': - return super().__new__( - cls, - *args, - a=a, - _configuration=_configuration, - **kwargs, - ) - -from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/required_default_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/required_default_validation.py deleted file mode 100644 index 3a5232f50e..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/required_default_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class RequiredDefaultValidation( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - foo = AnyTypeSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: typing.Union[foo, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'RequiredDefaultValidation': - return super().__new__( - cls, - *args, - foo=foo, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/required_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/required_validation.py deleted file mode 100644 index e8bb57f4fc..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/required_validation.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class RequiredValidation( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'foo', - )) - foo = AnyTypeSchema - bar = AnyTypeSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: foo, - bar: typing.Union[bar, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'RequiredValidation': - return super().__new__( - cls, - *args, - foo=foo, - bar=bar, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/required_with_empty_array.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/required_with_empty_array.py deleted file mode 100644 index 1c9b31e6c3..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/required_with_empty_array.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class RequiredWithEmptyArray( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - foo = AnyTypeSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - foo: typing.Union[foo, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'RequiredWithEmptyArray': - return super().__new__( - cls, - *args, - foo=foo, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/simple_enum_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/simple_enum_validation.py deleted file mode 100644 index 53f2c567d2..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/simple_enum_validation.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class SimpleEnumValidation( - _SchemaEnumMaker( - enum_value_to_name={ - 1: "POSITIVE_1", - 2: "POSITIVE_2", - 3: "POSITIVE_3", - } - ), - NumberSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def POSITIVE_1(cls): - return cls(1) - - @classmethod - @property - def POSITIVE_2(cls): - return cls(2) - - @classmethod - @property - def POSITIVE_3(cls): - return cls(3) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/string_type_matches_strings.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/string_type_matches_strings.py deleted file mode 100644 index 7f9e3f1d4b..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/string_type_matches_strings.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -StringTypeMatchesStrings = StrSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.py deleted file mode 100644 index 342399c3dd..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.py +++ /dev/null @@ -1,103 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class alpha( - _SchemaValidator( - inclusive_maximum=3, - ), - NumberSchema - ): - pass - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - alpha: typing.Union[alpha, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing': - return super().__new__( - cls, - *args, - alpha=alpha, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uniqueitems_false_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uniqueitems_false_validation.py deleted file mode 100644 index b44bd08185..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uniqueitems_false_validation.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class UniqueitemsFalseValidation( - _SchemaValidator( - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'UniqueitemsFalseValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uniqueitems_validation.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uniqueitems_validation.py deleted file mode 100644 index 799794310f..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uniqueitems_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class UniqueitemsValidation( - _SchemaValidator( - unique_items=True, - ), - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'UniqueitemsValidation': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uri_format.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uri_format.py deleted file mode 100644 index 8599fa87d5..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uri_format.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -UriFormat = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uri_reference_format.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uri_reference_format.py deleted file mode 100644 index 791ac4d70a..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uri_reference_format.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -UriReferenceFormat = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uri_template_format.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uri_template_format.py deleted file mode 100644 index 8a2e90d106..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/uri_template_format.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from unit_test_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -UriTemplateFormat = AnyTypeSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/models/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/models/__init__.py deleted file mode 100644 index c794f6ca09..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/models/__init__.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -# import all models into this package -# if you have many models here with many references from one model to another this may -# raise a RecursionError -# to avoid this, import only the models that you directly need like: -# from from unit_test_api.model.pet import Pet -# or import this package, but before doing it, use: -# import sys -# sys.setrecursionlimit(n) - -from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate -from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault -from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself -from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators -from unit_test_api.model.allof import Allof -from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof -from unit_test_api.model.allof_simple_types import AllofSimpleTypes -from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema -from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema -from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema -from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema -from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas -from unit_test_api.model.anyof import Anyof -from unit_test_api.model.anyof_complex_types import AnyofComplexTypes -from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema -from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema -from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays -from unit_test_api.model.boolean_type_matches_booleans import BooleanTypeMatchesBooleans -from unit_test_api.model.by_int import ByInt -from unit_test_api.model.by_number import ByNumber -from unit_test_api.model.by_small_number import BySmallNumber -from unit_test_api.model.date_time_format import DateTimeFormat -from unit_test_api.model.email_format import EmailFormat -from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse -from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue -from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters -from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 -from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 -from unit_test_api.model.enums_in_properties import EnumsInProperties -from unit_test_api.model.forbidden_property import ForbiddenProperty -from unit_test_api.model.hostname_format import HostnameFormat -from unit_test_api.model.integer_type_matches_integers import IntegerTypeMatchesIntegers -from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf -from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault -from unit_test_api.model.ipv4_format import Ipv4Format -from unit_test_api.model.ipv6_format import Ipv6Format -from unit_test_api.model.json_pointer_format import JsonPointerFormat -from unit_test_api.model.maximum_validation import MaximumValidation -from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger -from unit_test_api.model.maxitems_validation import MaxitemsValidation -from unit_test_api.model.maxlength_validation import MaxlengthValidation -from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty -from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation -from unit_test_api.model.minimum_validation import MinimumValidation -from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger -from unit_test_api.model.minitems_validation import MinitemsValidation -from unit_test_api.model.minlength_validation import MinlengthValidation -from unit_test_api.model.minproperties_validation import MinpropertiesValidation -from unit_test_api.model.model_not import ModelNot -from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics -from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics -from unit_test_api.model.nested_items import NestedItems -from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics -from unit_test_api.model.not_more_complex_schema import NotMoreComplexSchema -from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings -from unit_test_api.model.null_type_matches_only_the_null_object import NullTypeMatchesOnlyTheNullObject -from unit_test_api.model.number_type_matches_numbers import NumberTypeMatchesNumbers -from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation -from unit_test_api.model.oneof import Oneof -from unit_test_api.model.oneof_complex_types import OneofComplexTypes -from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema -from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema -from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored -from unit_test_api.model.pattern_validation import PatternValidation -from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters -from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference -from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties -from unit_test_api.model.ref_in_allof import RefInAllof -from unit_test_api.model.ref_in_anyof import RefInAnyof -from unit_test_api.model.ref_in_items import RefInItems -from unit_test_api.model.ref_in_oneof import RefInOneof -from unit_test_api.model.ref_in_property import RefInProperty -from unit_test_api.model.required_default_validation import RequiredDefaultValidation -from unit_test_api.model.required_validation import RequiredValidation -from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray -from unit_test_api.model.simple_enum_validation import SimpleEnumValidation -from unit_test_api.model.string_type_matches_strings import StringTypeMatchesStrings -from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing -from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation -from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation -from unit_test_api.model.uri_format import UriFormat -from unit_test_api.model.uri_reference_format import UriReferenceFormat -from unit_test_api.model.uri_template_format import UriTemplateFormat diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/schemas.py b/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/schemas.py deleted file mode 100644 index d4f8e67b4e..0000000000 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/schemas.py +++ /dev/null @@ -1,2158 +0,0 @@ -# coding: utf-8 - -""" - openapi 3.0.3 sample spec - - sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 - - The version of the OpenAPI document: 0.0.1 - Generated by: https://openapi-generator.tech -""" - -from collections import defaultdict -from datetime import date, datetime, timedelta # noqa: F401 -import functools -import decimal -import io -import os -import re -import tempfile -import typing -import uuid - -from dateutil.parser.isoparser import isoparser, _takes_ascii -from frozendict import frozendict - -from unit_test_api.exceptions import ( - ApiTypeError, - ApiValueError, -) -from unit_test_api.configuration import ( - Configuration, -) - - -class Unset(object): - """ - An instance of this class is set as the default value for object type(dict) properties that are optional - When a property has an unset value, that property will not be assigned in the dict - """ - pass - -unset = Unset() - -none_type = type(None) -file_type = io.IOBase - - -class FileIO(io.FileIO): - """ - A class for storing files - Note: this class is not immutable - """ - - def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader]): - if isinstance(arg, (io.FileIO, io.BufferedReader)): - if arg.closed: - raise ApiValueError('Invalid file state; file is closed and must be open') - arg.close() - inst = super(FileIO, cls).__new__(cls, arg.name) - super(FileIO, inst).__init__(arg.name) - return inst - raise ApiValueError('FileIO must be passed arg which contains the open file') - - def __init__(self, arg: typing.Union[io.FileIO, io.BufferedReader]): - pass - - -def update(d: dict, u: dict): - """ - Adds u to d - Where each dict is defaultdict(set) - """ - if not u: - return d - for k, v in u.items(): - if not v: - continue - if k not in d: - d[k] = v - else: - d[k] = d[k] | v - - -class ValidationMetadata(frozendict): - """ - A class storing metadata that is needed to validate OpenApi Schema payloads - """ - def __new__( - cls, - path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), - from_server: bool = False, - configuration: typing.Optional[Configuration] = None, - seen_classes: typing.FrozenSet[typing.Type] = frozenset(), - validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set['Schema']] = frozendict() - ): - """ - Args: - path_to_item: the path to the current data being instantiated. - For {'a': [1]} if the code is handling, 1, then the path is ('args[0]', 'a', 0) - This changes from location to location - from_server: whether or not this data came form the server - True when receiving server data - False when instantiating model with client side data not form the server - This does not change from location to location - configuration: the Configuration instance to use - This is needed because in Configuration: - - one can disable validation checking - This does not change from location to location - seen_classes: when deserializing data that matches multiple schemas, this is used to store - the schemas that have been traversed. This is used to stop processing when a cycle is seen. - This changes from location to location - validated_path_to_schemas: stores the already validated schema classes for a given path location - This does not change from location to location - """ - return super().__new__( - cls, - path_to_item=path_to_item, - from_server=from_server, - configuration=configuration, - seen_classes=seen_classes, - validated_path_to_schemas=validated_path_to_schemas - ) - - def validation_ran_earlier(self, cls: type) -> bool: - validated_schemas = self.validated_path_to_schemas.get(self.path_to_item, set()) - validation_ran_earlier = validated_schemas and cls in validated_schemas - if validation_ran_earlier: - return True - if cls in self.seen_classes: - return True - return False - - @property - def path_to_item(self) -> typing.Tuple[typing.Union[str, int], ...]: - return self.get('path_to_item') - - @property - def from_server(self) -> bool: - return self.get('from_server') - - @property - def configuration(self) -> typing.Optional[Configuration]: - return self.get('configuration') - - @property - def seen_classes(self) -> typing.FrozenSet[typing.Type]: - return self.get('seen_classes') - - @property - def validated_path_to_schemas(self) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set['Schema']]: - return self.get('validated_path_to_schemas') - - -class ValidatorBase: - @staticmethod - def __is_json_validation_enabled(schema_keyword, configuration=None): - """Returns true if JSON schema validation is enabled for the specified - validation keyword. This can be used to skip JSON schema structural validation - as requested in the configuration. - - Args: - schema_keyword (string): the name of a JSON schema validation keyword. - configuration (Configuration): the configuration class. - """ - - return (configuration is None or - not hasattr(configuration, '_disabled_client_side_validations') or - schema_keyword not in configuration._disabled_client_side_validations) - - @staticmethod - def __raise_validation_error_message(value, constraint_msg, constraint_value, path_to_item, additional_txt=""): - raise ApiValueError( - "Invalid value `{value}`, {constraint_msg} `{constraint_value}`{additional_txt} at {path_to_item}".format( - value=value, - constraint_msg=constraint_msg, - constraint_value=constraint_value, - additional_txt=additional_txt, - path_to_item=path_to_item, - ) - ) - - @classmethod - def __check_str_validations(cls, - validations, input_values, - validation_metadata: ValidationMetadata): - - if (cls.__is_json_validation_enabled('maxLength', validation_metadata.configuration) and - 'max_length' in validations and - len(input_values) > validations['max_length']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="length must be less than or equal to", - constraint_value=validations['max_length'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minLength', validation_metadata.configuration) and - 'min_length' in validations and - len(input_values) < validations['min_length']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="length must be greater than or equal to", - constraint_value=validations['min_length'], - path_to_item=validation_metadata.path_to_item - ) - - checked_value = input_values - if (cls.__is_json_validation_enabled('pattern', validation_metadata.configuration) and - 'regex' in validations): - for regex_dict in validations['regex']: - flags = regex_dict.get('flags', 0) - if not re.search(regex_dict['pattern'], checked_value, flags=flags): - if flags != 0: - # Don't print the regex flags if the flags are not - # specified in the OAS document. - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must match regular expression", - constraint_value=regex_dict['pattern'], - path_to_item=validation_metadata.path_to_item, - additional_txt=" with flags=`{}`".format(flags) - ) - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must match regular expression", - constraint_value=regex_dict['pattern'], - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def __check_tuple_validations( - cls, validations, input_values, - validation_metadata: ValidationMetadata): - - if (cls.__is_json_validation_enabled('maxItems', validation_metadata.configuration) and - 'max_items' in validations and - len(input_values) > validations['max_items']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of items must be less than or equal to", - constraint_value=validations['max_items'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minItems', validation_metadata.configuration) and - 'min_items' in validations and - len(input_values) < validations['min_items']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of items must be greater than or equal to", - constraint_value=validations['min_items'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('uniqueItems', validation_metadata.configuration) and - 'unique_items' in validations and validations['unique_items'] and input_values): - unique_items = set(input_values) - if len(input_values) > len(unique_items): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="duplicate items were found, and the tuple must not contain duplicates because", - constraint_value='unique_items==True', - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def __check_dict_validations( - cls, validations, input_values, - validation_metadata: ValidationMetadata): - - if (cls.__is_json_validation_enabled('maxProperties', validation_metadata.configuration) and - 'max_properties' in validations and - len(input_values) > validations['max_properties']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of properties must be less than or equal to", - constraint_value=validations['max_properties'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minProperties', validation_metadata.configuration) and - 'min_properties' in validations and - len(input_values) < validations['min_properties']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of properties must be greater than or equal to", - constraint_value=validations['min_properties'], - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def __check_numeric_validations( - cls, validations, input_values, - validation_metadata: ValidationMetadata): - - if cls.__is_json_validation_enabled('multipleOf', - validation_metadata.configuration) and 'multiple_of' in validations: - multiple_of_value = validations['multiple_of'] - if (isinstance(input_values, decimal.Decimal) and - not (float(input_values) / multiple_of_value).is_integer() - ): - # Note 'multipleOf' will be as good as the floating point arithmetic. - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="value must be a multiple of", - constraint_value=multiple_of_value, - path_to_item=validation_metadata.path_to_item - ) - - checking_max_or_min_values = {'exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', - 'inclusive_minimum'}.isdisjoint(validations) is False - if not checking_max_or_min_values: - return - max_val = input_values - min_val = input_values - - if (cls.__is_json_validation_enabled('exclusiveMaximum', validation_metadata.configuration) and - 'exclusive_maximum' in validations and - max_val >= validations['exclusive_maximum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value less than", - constraint_value=validations['exclusive_maximum'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('maximum', validation_metadata.configuration) and - 'inclusive_maximum' in validations and - max_val > validations['inclusive_maximum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value less than or equal to", - constraint_value=validations['inclusive_maximum'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('exclusiveMinimum', validation_metadata.configuration) and - 'exclusive_minimum' in validations and - min_val <= validations['exclusive_minimum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value greater than", - constraint_value=validations['exclusive_maximum'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minimum', validation_metadata.configuration) and - 'inclusive_minimum' in validations and - min_val < validations['inclusive_minimum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value greater than or equal to", - constraint_value=validations['inclusive_minimum'], - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def _check_validations_for_types( - cls, - validations, - input_values, - validation_metadata: ValidationMetadata - ): - if isinstance(input_values, str): - cls.__check_str_validations(validations, input_values, validation_metadata) - elif isinstance(input_values, tuple): - cls.__check_tuple_validations(validations, input_values, validation_metadata) - elif isinstance(input_values, frozendict): - cls.__check_dict_validations(validations, input_values, validation_metadata) - elif isinstance(input_values, decimal.Decimal): - cls.__check_numeric_validations(validations, input_values, validation_metadata) - - -class Singleton: - """ - Enums and singletons are the same - The same instance is returned for a given key of (cls, arg) - """ - _instances = {} - - def __new__(cls, arg: typing.Any, **kwargs): - key = (cls, arg) - if key not in cls._instances: - if arg in {None, True, False}: - inst = super().__new__(cls) - cls._instances[key] = inst - elif isinstance(arg, BoolClass): - inst = super().__new__(cls) - cls._instances[key] = inst - elif isinstance(arg, NoneClass): - inst = super().__new__(cls) - cls._instances[key] = inst - else: - cls._instances[key] = super().__new__(cls, arg) - return cls._instances[key] - - def __repr__(self): - if isinstance(self, NoneClass): - return f'<{self.__class__.__name__}: None>' - elif isinstance(self, BoolClass): - if bool(self): - return f'<{self.__class__.__name__}: True>' - return f'<{self.__class__.__name__}: False>' - return f'<{self.__class__.__name__}: {super().__repr__()}>' - - -class NoneClass(Singleton): - @classmethod - @property - def NONE(cls): - return cls(None) - - def __bool__(self) -> bool: - return False - - -class BoolClass(Singleton): - @classmethod - @property - def TRUE(cls): - return cls(True) - - @classmethod - @property - def FALSE(cls): - return cls(False) - - @functools.cache - def __bool__(self) -> bool: - for key, instance in self._instances.items(): - if self is instance: - return bool(key[1]) - raise ValueError('Unable to find the boolean value of this instance') - - -class Validator(typing.Protocol): - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - pass - - -def _SchemaValidator(**validations: typing.Union[str, bool, None, int, float, list[dict[str, typing.Union[str, int, float]]]]) -> Validator: - class SchemaValidator(ValidatorBase): - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - SchemaValidator _validate - Validates that validations pass - """ - cls._check_validations_for_types(validations, arg, validation_metadata) - return super()._validate(arg, validation_metadata) - - return SchemaValidator - - -def _SchemaTypeChecker(union_type_cls: typing.Union[typing.Any]) -> Validator: - if typing.get_origin(union_type_cls) is typing.Union: - union_classes = typing.get_args(union_type_cls) - else: - # note: when a union of a single class is passed in, the union disappears - union_classes = tuple([union_type_cls]) - """ - I want the type hint... union_type_cls - and to use it as a base class but when I do, I get - TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases - """ - class SchemaTypeChecker: - @staticmethod - def __get_valid_classes_phrase(input_classes): - """Returns a string phrase describing what types are allowed""" - all_classes = list(input_classes) - all_classes = sorted(all_classes, key=lambda cls: cls.__name__) - all_class_names = [cls.__name__ for cls in all_classes] - if len(all_class_names) == 1: - return "is {0}".format(all_class_names[0]) - return "is one of [{0}]".format(", ".join(all_class_names)) - - @classmethod - def __type_error_message( - cls, var_value=None, var_name=None, valid_classes=None, key_type=None - ): - """ - Keyword Args: - var_value (any): the variable which has the type_error - var_name (str): the name of the variable which has the typ error - valid_classes (tuple): the accepted classes for current_item's - value - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a tuple - """ - key_or_value = "value" - if key_type: - key_or_value = "key" - valid_classes_phrase = cls.__get_valid_classes_phrase(valid_classes) - msg = "Invalid type. Required {1} type {2} and " "passed type was {3}".format( - var_name, - key_or_value, - valid_classes_phrase, - type(var_value).__name__, - ) - return msg - - @classmethod - def _get_type_error(cls, var_value, path_to_item, valid_classes, key_type=False): - error_msg = cls.__type_error_message( - var_name=path_to_item[-1], - var_value=var_value, - valid_classes=valid_classes, - key_type=key_type, - ) - return ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=valid_classes, - key_type=key_type, - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - SchemaTypeChecker _validate - Validates arg's type - """ - arg_type = type(arg) - if arg_type in union_classes: - return super()._validate(arg, validation_metadata) - raise cls._get_type_error( - arg, - validation_metadata.path_to_item, - union_classes, - key_type=False, - ) - - return SchemaTypeChecker - - -class EnumMakerBase: - pass - - -class EnumMakerInterface(Validator): - @classmethod - @property - def _enum_value_to_name( - cls - ) -> typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]: - pass - - -def _SchemaEnumMaker(enum_value_to_name: typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]) -> EnumMakerInterface: - class SchemaEnumMaker(EnumMakerBase): - @classmethod - @property - def _enum_value_to_name( - cls - ) -> typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]: - pass - try: - super_enum_value_to_name = super()._enum_value_to_name - except AttributeError: - return enum_value_to_name - intersection = dict(enum_value_to_name.items() & super_enum_value_to_name.items()) - return intersection - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - SchemaEnumMaker _validate - Validates that arg is in the enum's allowed values - """ - try: - cls._enum_value_to_name[arg] - except KeyError: - raise ApiValueError("Invalid value {} passed in to {}, {}".format(arg, cls, cls._enum_value_to_name)) - return super()._validate(arg, validation_metadata) - - return SchemaEnumMaker - - -class BoolBase: - def is_true(self) -> bool: - """ - A replacement for x is True - True if the instance is a BoolClass True Singleton - """ - if not issubclass(self.__class__, BoolClass): - return False - return bool(self) - - def is_false(self) -> bool: - """ - A replacement for x is False - True if the instance is a BoolClass False Singleton - """ - if not issubclass(self.__class__, BoolClass): - return False - return bool(self) is False - - -class NoneBase: - def is_none(self) -> bool: - """ - A replacement for x is None - True if the instance is a NoneClass None Singleton - """ - if issubclass(self.__class__, NoneClass): - return True - return False - - -class StrBase: - @property - def as_str(self) -> str: - return self - - @property - def as_date(self) -> date: - raise Exception('not implemented') - - @property - def as_datetime(self) -> datetime: - raise Exception('not implemented') - - @property - def as_decimal(self) -> decimal.Decimal: - raise Exception('not implemented') - - @property - def as_uuid(self) -> uuid.UUID: - raise Exception('not implemented') - - -class UUIDBase(StrBase): - @property - @functools.cache - def as_uuid(self) -> uuid.UUID: - return uuid.UUID(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - uuid.UUID(arg) - return True - except ValueError: - raise ApiValueError( - "Invalid value '{}' for type UUID at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: typing.Optional[ValidationMetadata] = None, - ): - """ - UUIDBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class CustomIsoparser(isoparser): - - @_takes_ascii - def parse_isodatetime(self, dt_str): - components, pos = self._parse_isodate(dt_str) - if len(dt_str) > pos: - if self._sep is None or dt_str[pos:pos + 1] == self._sep: - components += self._parse_isotime(dt_str[pos + 1:]) - else: - raise ValueError('String contains unknown ISO components') - - if len(components) > 3 and components[3] == 24: - components[3] = 0 - return datetime(*components) + timedelta(days=1) - - if len(components) <= 3: - raise ValueError('Value is not a datetime') - - return datetime(*components) - - @_takes_ascii - def parse_isodate(self, datestr): - components, pos = self._parse_isodate(datestr) - - if len(datestr) > pos: - raise ValueError('String contains invalid time components') - - if len(components) > 3: - raise ValueError('String contains invalid time components') - - return date(*components) - - -DEFAULT_ISOPARSER = CustomIsoparser() - - -class DateBase(StrBase): - @property - @functools.cache - def as_date(self) -> date: - return DEFAULT_ISOPARSER.parse_isodate(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - DEFAULT_ISOPARSER.parse_isodate(arg) - return True - except ValueError: - raise ApiValueError( - "Value does not conform to the required ISO-8601 date format. " - "Invalid value '{}' for type date at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: typing.Optional[ValidationMetadata] = None, - ): - """ - DateBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class DateTimeBase: - @property - @functools.cache - def as_datetime(self) -> datetime: - return DEFAULT_ISOPARSER.parse_isodatetime(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - DEFAULT_ISOPARSER.parse_isodatetime(arg) - return True - except ValueError: - raise ApiValueError( - "Value does not conform to the required ISO-8601 datetime format. " - "Invalid value '{}' for type datetime at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - DateTimeBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class DecimalBase(StrBase): - """ - A class for storing decimals that are sent over the wire as strings - These schemas must remain based on StrBase rather than NumberBase - because picking base classes must be deterministic - """ - - @property - @functools.cache - def as_decimal(self) -> decimal.Decimal: - return decimal.Decimal(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - decimal.Decimal(arg) - return True - except decimal.InvalidOperation: - raise ApiValueError( - "Value cannot be converted to a decimal. " - "Invalid value '{}' for type decimal at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - DecimalBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class NumberBase: - @property - def as_int(self) -> int: - try: - return self._as_int - except AttributeError: - """ - Note: for some numbers like 9.0 they could be represented as an - integer but our code chooses to store them as - >>> Decimal('9.0').as_tuple() - DecimalTuple(sign=0, digits=(9, 0), exponent=-1) - so we can tell that the value came from a float and convert it back to a float - during later serialization - """ - if self.as_tuple().exponent < 0: - # this could be represented as an integer but should be represented as a float - # because that's what it was serialized from - raise ApiValueError(f'{self} is not an integer') - self._as_int = int(self) - return self._as_int - - @property - def as_float(self) -> float: - try: - return self._as_float - except AttributeError: - if self.as_tuple().exponent >= 0: - raise ApiValueError(f'{self} is not an float') - self._as_float = float(self) - return self._as_float - - -class ListBase: - @classmethod - def _validate_items(cls, list_items, validation_metadata: ValidationMetadata): - """ - Ensures that: - - values passed in for items are valid - Exceptions will be raised if: - - invalid arguments were passed in - - Args: - list_items: the input list of items - - Raises: - ApiTypeError - for missing required arguments, or for invalid properties - """ - - # if we have definitions for an items schema, use it - # otherwise accept anything - item_cls = getattr(cls, '_items', AnyTypeSchema) - path_to_schemas = {} - for i, value in enumerate(list_items): - item_validation_metadata = ValidationMetadata( - from_server=validation_metadata.from_server, - configuration=validation_metadata.configuration, - path_to_item=validation_metadata.path_to_item+(i,), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - if item_validation_metadata.validation_ran_earlier(item_cls): - continue - other_path_to_schemas = item_cls._validate( - value, validation_metadata=item_validation_metadata) - update(path_to_schemas, other_path_to_schemas) - return path_to_schemas - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - ListBase _validate - We return dynamic classes of different bases depending upon the inputs - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Returns: - new_cls (type): the new class - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - _path_to_schemas = super()._validate(arg, validation_metadata=validation_metadata) - if not isinstance(arg, tuple): - return _path_to_schemas - updated_vm = ValidationMetadata( - configuration=validation_metadata.configuration, - from_server=validation_metadata.from_server, - path_to_item=validation_metadata.path_to_item, - seen_classes=validation_metadata.seen_classes | frozenset({cls}), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - other_path_to_schemas = cls._validate_items(arg, validation_metadata=updated_vm) - update(_path_to_schemas, other_path_to_schemas) - return _path_to_schemas - - @classmethod - def _get_items( - cls: 'Schema', - arg: typing.List[typing.Any], - path_to_item: typing.Tuple[typing.Union[str, int], ...], - path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] - ): - ''' - ListBase _get_items - ''' - list_items = arg - cast_items = [] - # if we have definitions for an items schema, use it - # otherwise accept anything - - cls_item_cls = getattr(cls, '_items', AnyTypeSchema) - for i, value in enumerate(list_items): - item_path_to_item = path_to_item + (i,) - item_cls = path_to_schemas.get(item_path_to_item) - if item_cls is None: - item_cls = cls_item_cls - - if isinstance(value, item_cls): - cast_items.append(value) - continue - - new_value = item_cls._get_new_instance_without_conversion( - value, - item_path_to_item, - path_to_schemas - ) - cast_items.append(new_value) - - return cast_items - - -class Discriminable: - @classmethod - def _ensure_discriminator_value_present(cls, disc_property_name: str, validation_metadata: ValidationMetadata, *args): - if not args or args and disc_property_name not in args[0]: - # The input data does not contain the discriminator property - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '{}' is missing at path: {}".format(disc_property_name, validation_metadata.path_to_item) - ) - - @classmethod - def _get_discriminated_class(cls, disc_property_name: str, disc_payload_value: str): - """ - Used in schemas with discriminators - """ - if not hasattr(cls, '_discriminator'): - return None - disc = cls._discriminator - if disc_property_name not in disc: - return None - discriminated_cls = disc[disc_property_name].get(disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - elif not hasattr(cls, '_composed_schemas'): - return None - # TODO stop traveling if a cycle is hit - for allof_cls in cls._composed_schemas['allOf']: - discriminated_cls = allof_cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - for oneof_cls in cls._composed_schemas['oneOf']: - discriminated_cls = oneof_cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - for anyof_cls in cls._composed_schemas['anyOf']: - discriminated_cls = anyof_cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - return None - - -class DictBase(Discriminable): - # subclass properties - _required_property_names = set() - - @classmethod - def _validate_arg_presence(cls, arg): - """ - Ensures that: - - all required arguments are passed in - - the input variable names are valid - - present in properties or - - accepted because additionalProperties exists - Exceptions will be raised if: - - invalid arguments were passed in - - a var_name is invalid if additionProperties == None and var_name not in _properties - - required properties were not passed in - - Args: - arg: the input dict - - Raises: - ApiTypeError - for missing required arguments, or for invalid properties - """ - seen_required_properties = set() - invalid_arguments = [] - for property_name in arg: - if property_name in cls._required_property_names: - seen_required_properties.add(property_name) - elif property_name in cls._property_names: - continue - elif cls._additional_properties: - continue - else: - invalid_arguments.append(property_name) - missing_required_arguments = list(cls._required_property_names - seen_required_properties) - if missing_required_arguments: - missing_required_arguments.sort() - raise ApiTypeError( - "{} is missing {} required argument{}: {}".format( - cls.__name__, - len(missing_required_arguments), - "s" if len(missing_required_arguments) > 1 else "", - missing_required_arguments - ) - ) - if invalid_arguments: - invalid_arguments.sort() - raise ApiTypeError( - "{} was passed {} invalid argument{}: {}".format( - cls.__name__, - len(invalid_arguments), - "s" if len(invalid_arguments) > 1 else "", - invalid_arguments - ) - ) - - @classmethod - def _validate_args(cls, arg, validation_metadata: ValidationMetadata): - """ - Ensures that: - - values passed in for properties are valid - Exceptions will be raised if: - - invalid arguments were passed in - - Args: - arg: the input dict - - Raises: - ApiTypeError - for missing required arguments, or for invalid properties - """ - path_to_schemas = {} - for property_name, value in arg.items(): - if property_name in cls._required_property_names or property_name in cls._property_names: - schema = getattr(cls, property_name) - elif cls._additional_properties: - schema = cls._additional_properties - else: - raise ApiTypeError('Unable to find schema for value={} in class={} at path_to_item={}'.format( - value, cls, validation_metadata.path_to_item+(property_name,) - )) - arg_validation_metadata = ValidationMetadata( - from_server=validation_metadata.from_server, - configuration=validation_metadata.configuration, - path_to_item=validation_metadata.path_to_item+(property_name,), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - if arg_validation_metadata.validation_ran_earlier(schema): - continue - other_path_to_schemas = schema._validate(value, validation_metadata=arg_validation_metadata) - update(path_to_schemas, other_path_to_schemas) - return path_to_schemas - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - DictBase _validate - We return dynamic classes of different bases depending upon the inputs - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Returns: - new_cls (type): the new class - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - if isinstance(arg, cls): - # an instance of the correct type was passed in - return {} - _path_to_schemas = super()._validate(arg, validation_metadata=validation_metadata) - if not isinstance(arg, frozendict): - return _path_to_schemas - cls._validate_arg_presence(arg) - other_path_to_schemas = cls._validate_args(arg, validation_metadata=validation_metadata) - update(_path_to_schemas, other_path_to_schemas) - try: - _discriminator = cls._discriminator - except AttributeError: - return _path_to_schemas - # discriminator exists - disc_prop_name = list(_discriminator.keys())[0] - cls._ensure_discriminator_value_present(disc_prop_name, validation_metadata, arg) - discriminated_cls = cls._get_discriminated_class( - disc_property_name=disc_prop_name, disc_payload_value=arg[disc_prop_name]) - if discriminated_cls is None: - raise ApiValueError( - "Invalid discriminator value was passed in to {}.{} Only the values {} are allowed at {}".format( - cls.__name__, - disc_prop_name, - list(_discriminator[disc_prop_name].keys()), - validation_metadata.path_to_item + (disc_prop_name,) - ) - ) - updated_vm = ValidationMetadata( - configuration=validation_metadata.configuration, - from_server=validation_metadata.from_server, - path_to_item=validation_metadata.path_to_item, - seen_classes=validation_metadata.seen_classes | frozenset({cls}), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - if updated_vm.validation_ran_earlier(discriminated_cls): - return _path_to_schemas - other_path_to_schemas = discriminated_cls._validate(arg, validation_metadata=updated_vm) - update(_path_to_schemas, other_path_to_schemas) - return _path_to_schemas - - @classmethod - @property - def _additional_properties(cls): - return AnyTypeSchema - - @classmethod - @property - @functools.cache - def _property_names(cls): - property_names = set() - for var_name, var_value in cls.__dict__.items(): - # referenced models are classmethods - is_classmethod = type(var_value) is classmethod - if is_classmethod: - property_names.add(var_name) - continue - is_class = type(var_value) is type - if not is_class: - continue - if not issubclass(var_value, Schema): - continue - if var_name == '_additional_properties': - continue - property_names.add(var_name) - property_names = list(property_names) - property_names.sort() - return tuple(property_names) - - @classmethod - def _get_properties( - cls, - arg: typing.Dict[str, typing.Any], - path_to_item: typing.Tuple[typing.Union[str, int], ...], - path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] - ): - """ - DictBase _get_properties, this is how properties are set - These values already passed validation - """ - dict_items = {} - # if we have definitions for property schemas convert values using it - # otherwise accept anything - - for property_name_js, value in arg.items(): - property_cls = getattr(cls, property_name_js, cls._additional_properties) - property_path_to_item = path_to_item + (property_name_js,) - stored_property_cls = path_to_schemas.get(property_path_to_item) - if stored_property_cls: - property_cls = stored_property_cls - - if isinstance(value, property_cls): - dict_items[property_name_js] = value - continue - - new_value = property_cls._get_new_instance_without_conversion( - value, - property_path_to_item, - path_to_schemas - ) - dict_items[property_name_js] = new_value - return dict_items - - def __setattr__(self, name, value): - if not isinstance(self, FileIO): - raise AttributeError('property setting not supported on immutable instances') - - def __getattr__(self, name): - if isinstance(self, frozendict): - # if an attribute does not exist - try: - return self[name] - except KeyError as ex: - raise AttributeError(str(ex)) - return super().__getattr__(self, name) - - def __getattribute__(self, name): - # if an attribute does exist (for example as a class property but not as an instance method) - try: - return self[name] - except (KeyError, TypeError): - return super().__getattribute__(name) - - -inheritable_primitive_types_set = {decimal.Decimal, str, tuple, frozendict, FileIO, bytes, BoolClass, NoneClass} - - -class Schema: - """ - the base class of all swagger/openapi schemas/models - - ensures that: - - payload passes required validations - - payload is of allowed types - - payload value is an allowed enum value - """ - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - Schema _validate - Runs all schema validation logic and - returns a dynamic class of different bases depending upon the input - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Use cases: - 1. inheritable type: string/decimal.Decimal/frozendict/tuple - 2. singletons: bool/None -> uses the base classes BoolClass/NoneClass - - Required Steps: - 1. verify type of input is valid vs the allowed _types - 2. check validations that are applicable for this type of input - 3. if enums exist, check that the value exists in the enum - - Returns: - path_to_schemas: a map of path to schemas - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - base_class = type(arg) - path_to_schemas = {validation_metadata.path_to_item: set()} - path_to_schemas[validation_metadata.path_to_item].add(cls) - path_to_schemas[validation_metadata.path_to_item].add(base_class) - return path_to_schemas - - @staticmethod - def __process_schema_classes( - schema_classes: typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]] - ): - """ - Processes and mutates schema_classes - If a SomeSchema is a subclass of DictSchema then remove DictSchema because it is already included - """ - if len(schema_classes) < 2: - return - x_schema = schema_type_classes & schema_classes - if not x_schema: - return - x_schema = x_schema.pop() - if any(c is not x_schema and issubclass(c, x_schema) for c in schema_classes): - # needed to not have a mro error in get_new_class - schema_classes.remove(x_schema) - - @classmethod - def __get_new_cls( - cls, - arg, - validation_metadata: ValidationMetadata - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], 'Schema']: - """ - Make a new dynamic class and return an instance of that class - We are making an instance of cls, but instead of making cls - make a new class, new_cls - which includes dynamic bases including cls - return an instance of that new class - - Dict property + List Item Assignment Use cases: - 1. value is NOT an instance of the required schema class - the value is validated by _validate - _validate returns a key value pair - where the key is the path to the item, and the value will be the required manufactured class - made out of the matching schemas - 2. value is an instance of the the correct schema type - the value is NOT validated by _validate, _validate only checks that the instance is of the correct schema type - for this value, _validate does NOT return an entry for it in _path_to_schemas - and in list/dict _get_items,_get_properties the value will be directly assigned - because value is of the correct type, and validation was run earlier when the instance was created - """ - _path_to_schemas = {} - if validation_metadata.validated_path_to_schemas: - update(_path_to_schemas, validation_metadata.validated_path_to_schemas) - if not validation_metadata.validation_ran_earlier(cls): - other_path_to_schemas = cls._validate(arg, validation_metadata=validation_metadata) - update(_path_to_schemas, other_path_to_schemas) - # loop through it make a new class for each entry - # do not modify the returned result because it is cached and we would be modifying the cached value - path_to_schemas = {} - for path, schema_classes in _path_to_schemas.items(): - """ - Use cases - 1. N number of schema classes + enum + type != bool/None, classes in path_to_schemas: tuple/frozendict/str/Decimal/bytes/FileIo - needs Singleton added - 2. N number of schema classes + enum + type == bool/None, classes in path_to_schemas: BoolClass/NoneClass - Singleton already added - 3. N number of schema classes, classes in path_to_schemas: BoolClass/NoneClass/tuple/frozendict/str/Decimal/bytes/FileIo - """ - cls.__process_schema_classes(schema_classes) - enum_schema = any( - hasattr(this_cls, '_enum_value_to_name') for this_cls in schema_classes) - inheritable_primitive_type = schema_classes.intersection(inheritable_primitive_types_set) - chosen_schema_classes = schema_classes - inheritable_primitive_type - suffix = tuple(inheritable_primitive_type) - if enum_schema and suffix[0] not in {NoneClass, BoolClass}: - suffix = (Singleton,) + suffix - - used_classes = tuple(sorted(chosen_schema_classes, key=lambda a_cls: a_cls.__name__)) + suffix - mfg_cls = get_new_class(class_name='DynamicSchema', bases=used_classes) - path_to_schemas[path] = mfg_cls - - return path_to_schemas - - @classmethod - def _get_new_instance_without_conversion( - cls: 'Schema', - arg: typing.Any, - path_to_item: typing.Tuple[typing.Union[str, int], ...], - path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] - ): - # We have a Dynamic class and we are making an instance of it - if issubclass(cls, frozendict): - print(cls.__bases__) - properties = cls._get_properties(arg, path_to_item, path_to_schemas) - return super(Schema, cls).__new__(cls, properties) - elif issubclass(cls, tuple): - items = cls._get_items(arg, path_to_item, path_to_schemas) - return super(Schema, cls).__new__(cls, items) - """ - str = openapi str, date, and datetime - decimal.Decimal = openapi int and float - FileIO = openapi binary type and the user inputs a file - bytes = openapi binary type and the user inputs bytes - """ - return super(Schema, cls).__new__(cls, arg) - - @classmethod - def _from_openapi_data( - cls, - arg: typing.Union[ - str, - date, - datetime, - int, - float, - decimal.Decimal, - bool, - None, - 'Schema', - dict, - frozendict, - tuple, - list, - io.FileIO, - io.BufferedReader, - bytes - ], - _configuration: typing.Optional[Configuration] - ): - """ - Schema _from_openapi_data - """ - from_server = True - validated_path_to_schemas = {} - arg = cast_to_allowed_types(arg, from_server, validated_path_to_schemas) - validation_metadata = ValidationMetadata( - from_server=from_server, configuration=_configuration, validated_path_to_schemas=validated_path_to_schemas) - path_to_schemas = cls.__get_new_cls(arg, validation_metadata) - new_cls = path_to_schemas[validation_metadata.path_to_item] - new_inst = new_cls._get_new_instance_without_conversion( - arg, - validation_metadata.path_to_item, - path_to_schemas - ) - return new_inst - - @staticmethod - def __get_input_dict(*args, **kwargs) -> frozendict: - input_dict = {} - if args and isinstance(args[0], (dict, frozendict)): - input_dict.update(args[0]) - if kwargs: - input_dict.update(kwargs) - return frozendict(input_dict) - - @staticmethod - def __remove_unsets(kwargs): - return {key: val for key, val in kwargs.items() if val is not unset} - - def __new__(cls, *args: typing.Union[dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], _configuration: typing.Optional[Configuration] = None, **kwargs: typing.Union[dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset]): - """ - Schema __new__ - - Args: - args (int/float/decimal.Decimal/str/list/tuple/dict/frozendict/bool/None): the value - kwargs (str, int/float/decimal.Decimal/str/list/tuple/dict/frozendict/bool/None): dict values - _configuration: contains the Configuration that enables json schema validation keywords - like minItems, minLength etc - """ - kwargs = cls.__remove_unsets(kwargs) - if not args and not kwargs: - raise TypeError( - 'No input given. args or kwargs must be given.' - ) - if not kwargs and args and not isinstance(args[0], dict): - arg = args[0] - else: - arg = cls.__get_input_dict(*args, **kwargs) - from_server = False - validated_path_to_schemas = {} - arg = cast_to_allowed_types( - arg, from_server, validated_path_to_schemas) - validation_metadata = ValidationMetadata( - configuration=_configuration, from_server=from_server, validated_path_to_schemas=validated_path_to_schemas) - path_to_schemas = cls.__get_new_cls(arg, validation_metadata) - new_cls = path_to_schemas[validation_metadata.path_to_item] - return new_cls._get_new_instance_without_conversion( - arg, - validation_metadata.path_to_item, - path_to_schemas - ) - - def __init__( - self, - *args: typing.Union[ - dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Union[ - dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset - ] - ): - """ - this is needed to fix 'Unexpected argument' warning in pycharm - this code does nothing because all Schema instances are immutable - this means that all input data is passed into and used in new, and after the new instance is made - no new attributes are assigned and init is not used - """ - pass - - -def cast_to_allowed_types( - arg: typing.Union[str, date, datetime, uuid.UUID, decimal.Decimal, int, float, None, dict, frozendict, list, tuple, bytes, Schema], - from_server: bool, - validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]], - path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), -) -> typing.Union[frozendict, tuple, decimal.Decimal, str, bytes, BoolClass, NoneClass, FileIO]: - """ - Casts the input payload arg into the allowed types - The input validated_path_to_schemas is mutated by running this function - - When from_server is False then - - date/datetime is cast to str - - int/float is cast to Decimal - - If a Schema instance is passed in it is converted back to a primitive instance because - One may need to validate that data to the original Schema class AND additional different classes - those additional classes will need to be added to the new manufactured class for that payload - If the code didn't do this and kept the payload as a Schema instance it would fail to validate to other - Schema classes and the code wouldn't be able to mfg a new class that includes all valid schemas - TODO: store the validated schema classes in validation_metadata - - Args: - arg: the payload - from_server: whether this payload came from the server or not - validated_path_to_schemas: a dict that stores the validated classes at any path location in the payload - """ - if isinstance(arg, Schema): - # store the already run validations - schema_classes = set() - for cls in arg.__class__.__bases__: - if cls is Singleton: - continue - schema_classes.add(cls) - validated_path_to_schemas[path_to_item] = schema_classes - - if isinstance(arg, str): - return str(arg) - elif isinstance(arg, (dict, frozendict)): - return frozendict({key: cast_to_allowed_types(val, from_server, validated_path_to_schemas, path_to_item + (key,)) for key, val in arg.items()}) - elif isinstance(arg, (bool, BoolClass)): - """ - this check must come before isinstance(arg, (int, float)) - because isinstance(True, int) is True - """ - if arg: - return BoolClass.TRUE - return BoolClass.FALSE - elif isinstance(arg, int): - return decimal.Decimal(arg) - elif isinstance(arg, float): - decimal_from_float = decimal.Decimal(arg) - if decimal_from_float.as_integer_ratio()[1] == 1: - # 9.0 -> Decimal('9.0') - # 3.4028234663852886e+38 -> Decimal('340282346638528859811704183484516925440.0') - return decimal.Decimal(str(decimal_from_float)+'.0') - return decimal_from_float - elif isinstance(arg, (tuple, list)): - return tuple([cast_to_allowed_types(item, from_server, validated_path_to_schemas, path_to_item + (i,)) for i, item in enumerate(arg)]) - elif isinstance(arg, (none_type, NoneClass)): - return NoneClass.NONE - elif isinstance(arg, (date, datetime)): - if not from_server: - return arg.isoformat() - # ApiTypeError will be thrown later by _validate_type - return arg - elif isinstance(arg, uuid.UUID): - if not from_server: - return str(arg) - # ApiTypeError will be thrown later by _validate_type - return arg - elif isinstance(arg, decimal.Decimal): - return decimal.Decimal(arg) - elif isinstance(arg, bytes): - return bytes(arg) - elif isinstance(arg, (io.FileIO, io.BufferedReader)): - return FileIO(arg) - raise ValueError('Invalid type passed in got input={} type={}'.format(arg, type(arg))) - - -class ComposedBase(Discriminable): - - @classmethod - def __get_allof_classes(cls, arg, validation_metadata: ValidationMetadata): - path_to_schemas = defaultdict(set) - for allof_cls in cls._composed_schemas['allOf']: - if validation_metadata.validation_ran_earlier(allof_cls): - continue - other_path_to_schemas = allof_cls._validate(arg, validation_metadata=validation_metadata) - update(path_to_schemas, other_path_to_schemas) - return path_to_schemas - - @classmethod - def __get_oneof_class( - cls, - arg, - discriminated_cls, - validation_metadata: ValidationMetadata, - path_to_schemas: typing.Dict[typing.Tuple, typing.Set[typing.Type[Schema]]] - ): - oneof_classes = [] - path_to_schemas = defaultdict(set) - for oneof_cls in cls._composed_schemas['oneOf']: - if oneof_cls in path_to_schemas[validation_metadata.path_to_item]: - oneof_classes.append(oneof_cls) - continue - if validation_metadata.validation_ran_earlier(oneof_cls): - oneof_classes.append(oneof_cls) - continue - try: - path_to_schemas = oneof_cls._validate(arg, validation_metadata=validation_metadata) - except (ApiValueError, ApiTypeError) as ex: - if discriminated_cls is not None and oneof_cls is discriminated_cls: - raise ex - continue - oneof_classes.append(oneof_cls) - if not oneof_classes: - raise ApiValueError( - "Invalid inputs given to generate an instance of {}. None " - "of the oneOf schemas matched the input data.".format(cls) - ) - elif len(oneof_classes) > 1: - raise ApiValueError( - "Invalid inputs given to generate an instance of {}. Multiple " - "oneOf schemas {} matched the inputs, but a max of one is allowed.".format(cls, oneof_classes) - ) - return path_to_schemas - - @classmethod - def __get_anyof_classes( - cls, - arg, - discriminated_cls, - validation_metadata: ValidationMetadata - ): - anyof_classes = [] - path_to_schemas = defaultdict(set) - for anyof_cls in cls._composed_schemas['anyOf']: - if validation_metadata.validation_ran_earlier(anyof_cls): - anyof_classes.append(anyof_cls) - continue - - try: - other_path_to_schemas = anyof_cls._validate(arg, validation_metadata=validation_metadata) - except (ApiValueError, ApiTypeError) as ex: - if discriminated_cls is not None and anyof_cls is discriminated_cls: - raise ex - continue - anyof_classes.append(anyof_cls) - update(path_to_schemas, other_path_to_schemas) - if not anyof_classes: - raise ApiValueError( - "Invalid inputs given to generate an instance of {}. None " - "of the anyOf schemas matched the input data.".format(cls) - ) - return path_to_schemas - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - ComposedBase _validate - We return dynamic classes of different bases depending upon the inputs - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Returns: - new_cls (type): the new class - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - if isinstance(arg, Schema) and validation_metadata.from_server is False: - if isinstance(arg, cls): - # an instance of the correct type was passed in - return {} - raise ApiTypeError( - 'Incorrect type passed in, required type was {} and passed type was {} at {}'.format( - cls, - type(arg), - validation_metadata.path_to_item - ) - ) - - # validation checking on types, validations, and enums - path_to_schemas = super()._validate(arg, validation_metadata=validation_metadata) - - updated_vm = ValidationMetadata( - configuration=validation_metadata.configuration, - from_server=validation_metadata.from_server, - path_to_item=validation_metadata.path_to_item, - seen_classes=validation_metadata.seen_classes | frozenset({cls}), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - - # process composed schema - _discriminator = getattr(cls, '_discriminator', None) - discriminated_cls = None - if _discriminator and arg and isinstance(arg, frozendict): - disc_property_name = list(_discriminator.keys())[0] - cls._ensure_discriminator_value_present(disc_property_name, updated_vm, arg) - # get discriminated_cls by looking at the dict in the current class - discriminated_cls = cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=arg[disc_property_name]) - if discriminated_cls is None: - raise ApiValueError( - "Invalid discriminator value '{}' was passed in to {}.{} Only the values {} are allowed at {}".format( - arg[disc_property_name], - cls.__name__, - disc_property_name, - list(_discriminator[disc_property_name].keys()), - updated_vm.path_to_item + (disc_property_name,) - ) - ) - - if cls._composed_schemas['allOf']: - other_path_to_schemas = cls.__get_allof_classes(arg, validation_metadata=updated_vm) - update(path_to_schemas, other_path_to_schemas) - if cls._composed_schemas['oneOf']: - other_path_to_schemas = cls.__get_oneof_class( - arg, - discriminated_cls=discriminated_cls, - validation_metadata=updated_vm, - path_to_schemas=path_to_schemas - ) - update(path_to_schemas, other_path_to_schemas) - if cls._composed_schemas['anyOf']: - other_path_to_schemas = cls.__get_anyof_classes( - arg, - discriminated_cls=discriminated_cls, - validation_metadata=updated_vm - ) - update(path_to_schemas, other_path_to_schemas) - not_cls = cls._composed_schemas['not'] - if not_cls: - other_path_to_schemas = None - not_exception = ApiValueError( - "Invalid value '{}' was passed in to {}. Value is invalid because it is disallowed by {}".format( - arg, - cls.__name__, - not_cls.__name__, - ) - ) - if updated_vm.validation_ran_earlier(not_cls): - raise not_exception - - try: - other_path_to_schemas = not_cls._validate(arg, validation_metadata=updated_vm) - except (ApiValueError, ApiTypeError): - pass - if other_path_to_schemas: - raise not_exception - - if discriminated_cls is not None and not updated_vm.validation_ran_earlier(discriminated_cls): - # TODO use an exception from this package here - assert discriminated_cls in path_to_schemas[updated_vm.path_to_item] - return path_to_schemas - - -# DictBase, ListBase, NumberBase, StrBase, BoolBase, NoneBase -class ComposedSchema( - _SchemaTypeChecker(typing.Union[NoneClass, str, decimal.Decimal, BoolClass, tuple, frozendict]), - ComposedBase, - DictBase, - ListBase, - NumberBase, - StrBase, - BoolBase, - NoneBase, - Schema -): - - # subclass properties - _composed_schemas = {} - - @classmethod - def _from_openapi_data(cls, *args: typing.Any, _configuration: typing.Optional[Configuration] = None, **kwargs): - if not args: - if not kwargs: - raise ApiTypeError('{} is missing required input data in args or kwargs'.format(cls.__name__)) - args = (kwargs, ) - return super()._from_openapi_data(args[0], _configuration=_configuration) - - -class ListSchema( - _SchemaTypeChecker(typing.Union[tuple]), - ListBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.List[typing.Any], _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[list, tuple], **kwargs: ValidationMetadata): - return super().__new__(cls, arg, **kwargs) - - -class NoneSchema( - _SchemaTypeChecker(typing.Union[NoneClass]), - NoneBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: None, _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: None, **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class NumberSchema( - _SchemaTypeChecker(typing.Union[decimal.Decimal]), - NumberBase, - Schema -): - """ - This is used for type: number with no format - Both integers AND floats are accepted - """ - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[int, float, decimal.Decimal], _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[decimal.Decimal, int, float], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class IntBase(NumberBase): - @property - def as_int(self) -> int: - try: - return self._as_int - except AttributeError: - self._as_int = int(self) - return self._as_int - - @classmethod - def _validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): - if isinstance(arg, decimal.Decimal): - - denominator = arg.as_integer_ratio()[-1] - if denominator != 1: - raise ApiValueError( - "Invalid value '{}' for type integer at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - IntBase _validate - TODO what about types = (int, number) -> IntBase, NumberBase? We could drop int and keep number only - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class IntSchema(IntBase, NumberSchema): - - @classmethod - def _from_openapi_data(cls, arg: int, _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[decimal.Decimal, int], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class Int32Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-2147483648), - inclusive_maximum=decimal.Decimal(2147483647) - ), -): - pass - - -class Int32Schema( - Int32Base, - IntSchema -): - pass - - -class Int64Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-9223372036854775808), - inclusive_maximum=decimal.Decimal(9223372036854775807) - ), -): - pass - - -class Int64Schema( - Int64Base, - IntSchema -): - pass - - -class Float32Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-3.4028234663852886e+38), - inclusive_maximum=decimal.Decimal(3.4028234663852886e+38) - ), -): - pass - - -class Float32Schema( - Float32Base, - NumberSchema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[float, decimal.Decimal], _configuration: typing.Optional[Configuration] = None): - # todo check format - return super()._from_openapi_data(arg, _configuration=_configuration) - - -class Float64Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-1.7976931348623157E+308), - inclusive_maximum=decimal.Decimal(1.7976931348623157E+308) - ), -): - pass - - -class Float64Schema( - Float64Base, - NumberSchema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[float, decimal.Decimal], _configuration: typing.Optional[Configuration] = None): - # todo check format - return super()._from_openapi_data(arg, _configuration=_configuration) - - -class StrSchema( - _SchemaTypeChecker(typing.Union[str]), - StrBase, - Schema -): - """ - date + datetime string types must inherit from this class - That is because one can validate a str payload as both: - - type: string (format unset) - - type: string, format: date - """ - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[str], _configuration: typing.Optional[Configuration] = None) -> 'StrSchema': - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[str, date, datetime, uuid.UUID], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class UUIDSchema(UUIDBase, StrSchema): - - def __new__(cls, arg: typing.Union[str, uuid.UUID], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class DateSchema(DateBase, StrSchema): - - def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class DateTimeSchema(DateTimeBase, StrSchema): - - def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class DecimalSchema(DecimalBase, StrSchema): - - def __new__(cls, arg: typing.Union[str], **kwargs: typing.Union[ValidationMetadata]): - """ - Note: Decimals may not be passed in because cast_to_allowed_types is only invoked once for payloads - which can be simple (str) or complex (dicts or lists with nested values) - Because casting is only done once and recursively casts all values prior to validation then for a potential - client side Decimal input if Decimal was accepted as an input in DecimalSchema then one would not know - if one was using it for a StrSchema (where it should be cast to str) or one is using it for NumberSchema - where it should stay as Decimal. - """ - return super().__new__(cls, arg, **kwargs) - - -class BytesSchema( - _SchemaTypeChecker(typing.Union[bytes]), - Schema, -): - """ - this class will subclass bytes and is immutable - """ - def __new__(cls, arg: typing.Union[bytes], **kwargs: typing.Union[ValidationMetadata]): - return super(Schema, cls).__new__(cls, arg) - - -class FileSchema( - _SchemaTypeChecker(typing.Union[FileIO]), - Schema, -): - """ - This class is NOT immutable - Dynamic classes are built using it for example when AnyType allows in binary data - Al other schema classes ARE immutable - If one wanted to make this immutable one could make this a DictSchema with required properties: - - data = BytesSchema (which would be an immutable bytes based schema) - - file_name = StrSchema - and cast_to_allowed_types would convert bytes and file instances into dicts containing data + file_name - The downside would be that data would be stored in memory which one may not want to do for very large files - - The developer is responsible for closing this file and deleting it - - This class was kept as mutable: - - to allow file reading and writing to disk - - to be able to preserve file name info - """ - - def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader], **kwargs: typing.Union[ValidationMetadata]): - return super(Schema, cls).__new__(cls, arg) - - -class BinaryBase: - pass - - -class BinarySchema( - _SchemaTypeChecker(typing.Union[bytes, FileIO]), - ComposedBase, - BinaryBase, - Schema, -): - - @classmethod - @property - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [], - 'oneOf': [ - BytesSchema, - FileSchema, - ], - 'anyOf': [ - ], - 'not': None - } - - def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader, bytes], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg) - - -class BoolSchema( - _SchemaTypeChecker(typing.Union[BoolClass]), - BoolBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: bool, _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: bool, **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class AnyTypeSchema( - _SchemaTypeChecker( - typing.Union[frozendict, tuple, decimal.Decimal, str, BoolClass, NoneClass, bytes, FileIO] - ), - DictBase, - ListBase, - NumberBase, - StrBase, - BoolBase, - NoneBase, - Schema -): - pass - - -class DictSchema( - _SchemaTypeChecker(typing.Union[frozendict]), - DictBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.Dict[str, typing.Any], _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, *args: typing.Union[dict, frozendict], **kwargs: typing.Union[dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, bytes, Schema, Unset, ValidationMetadata]): - return super().__new__(cls, *args, **kwargs) - - -schema_type_classes = set([NoneSchema, DictSchema, ListSchema, NumberSchema, StrSchema, BoolSchema]) - - -def deserialize_file(response_data, configuration, content_disposition=None): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - Args: - param response_data (str): the file data to write - configuration (Configuration): the instance to use to convert files - - Keyword Args: - content_disposition (str): the value of the Content-Disposition - header - - Returns: - (file_type): the deserialized file which is open - The user is responsible for closing and reading the file - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - if isinstance(response_data, str): - # change str to bytes so we can write it - response_data = response_data.encode('utf-8') - f.write(response_data) - - f = open(path, "rb") - return f - - -@functools.cache -def get_new_class( - class_name: str, - bases: typing.Tuple[typing.Type[typing.Union[Schema, typing.Any]], ...] -) -> typing.Type[Schema]: - """ - Returns a new class that is made with the subclass bases - """ - return type(class_name, bases, {}) - - -LOG_CACHE_USAGE = False - - -def log_cache_usage(cache_fn): - if LOG_CACHE_USAGE: - print(cache_fn.__name__, cache_fn.cache_info()) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/.gitignore b/samples/openapi3/client/3_0_3_unit_test/python/.gitignore similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/.gitignore rename to samples/openapi3/client/3_0_3_unit_test/python/.gitignore diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/.gitlab-ci.yml b/samples/openapi3/client/3_0_3_unit_test/python/.gitlab-ci.yml similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/.gitlab-ci.yml rename to samples/openapi3/client/3_0_3_unit_test/python/.gitlab-ci.yml diff --git a/samples/openapi3/client/3_0_3_unit_test/python/.openapi-generator-ignore b/samples/openapi3/client/3_0_3_unit_test/python/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/.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/openapi3/client/3_0_3_unit_test/python/.openapi-generator/FILES b/samples/openapi3/client/3_0_3_unit_test/python/.openapi-generator/FILES new file mode 100644 index 0000000000..76fb1cb914 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/.openapi-generator/FILES @@ -0,0 +1,421 @@ +.gitignore +.gitlab-ci.yml +.travis.yml +README.md +docs/apis/tags/AdditionalPropertiesApi.md +docs/apis/tags/AllOfApi.md +docs/apis/tags/AnyOfApi.md +docs/apis/tags/ContentTypeJsonApi.md +docs/apis/tags/DefaultApi.md +docs/apis/tags/EnumApi.md +docs/apis/tags/FormatApi.md +docs/apis/tags/ItemsApi.md +docs/apis/tags/MaxItemsApi.md +docs/apis/tags/MaxLengthApi.md +docs/apis/tags/MaxPropertiesApi.md +docs/apis/tags/MaximumApi.md +docs/apis/tags/MinItemsApi.md +docs/apis/tags/MinLengthApi.md +docs/apis/tags/MinPropertiesApi.md +docs/apis/tags/MinimumApi.md +docs/apis/tags/ModelNotApi.md +docs/apis/tags/MultipleOfApi.md +docs/apis/tags/OneOfApi.md +docs/apis/tags/OperationRequestBodyApi.md +docs/apis/tags/PathPostApi.md +docs/apis/tags/PatternApi.md +docs/apis/tags/PropertiesApi.md +docs/apis/tags/RefApi.md +docs/apis/tags/RequiredApi.md +docs/apis/tags/ResponseContentContentTypeSchemaApi.md +docs/apis/tags/TypeApi.md +docs/apis/tags/UniqueItemsApi.md +docs/models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md +docs/models/AdditionalpropertiesAreAllowedByDefault.md +docs/models/AdditionalpropertiesCanExistByItself.md +docs/models/AdditionalpropertiesShouldNotLookInApplicators.md +docs/models/Allof.md +docs/models/AllofCombinedWithAnyofOneof.md +docs/models/AllofSimpleTypes.md +docs/models/AllofWithBaseSchema.md +docs/models/AllofWithOneEmptySchema.md +docs/models/AllofWithTheFirstEmptySchema.md +docs/models/AllofWithTheLastEmptySchema.md +docs/models/AllofWithTwoEmptySchemas.md +docs/models/Anyof.md +docs/models/AnyofComplexTypes.md +docs/models/AnyofWithBaseSchema.md +docs/models/AnyofWithOneEmptySchema.md +docs/models/ArrayTypeMatchesArrays.md +docs/models/BooleanTypeMatchesBooleans.md +docs/models/ByInt.md +docs/models/ByNumber.md +docs/models/BySmallNumber.md +docs/models/DateTimeFormat.md +docs/models/EmailFormat.md +docs/models/EnumWith0DoesNotMatchFalse.md +docs/models/EnumWith1DoesNotMatchTrue.md +docs/models/EnumWithEscapedCharacters.md +docs/models/EnumWithFalseDoesNotMatch0.md +docs/models/EnumWithTrueDoesNotMatch1.md +docs/models/EnumsInProperties.md +docs/models/ForbiddenProperty.md +docs/models/HostnameFormat.md +docs/models/IntegerTypeMatchesIntegers.md +docs/models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md +docs/models/InvalidStringValueForDefault.md +docs/models/Ipv4Format.md +docs/models/Ipv6Format.md +docs/models/JsonPointerFormat.md +docs/models/MaximumValidation.md +docs/models/MaximumValidationWithUnsignedInteger.md +docs/models/MaxitemsValidation.md +docs/models/MaxlengthValidation.md +docs/models/Maxproperties0MeansTheObjectIsEmpty.md +docs/models/MaxpropertiesValidation.md +docs/models/MinimumValidation.md +docs/models/MinimumValidationWithSignedInteger.md +docs/models/MinitemsValidation.md +docs/models/MinlengthValidation.md +docs/models/MinpropertiesValidation.md +docs/models/ModelNot.md +docs/models/NestedAllofToCheckValidationSemantics.md +docs/models/NestedAnyofToCheckValidationSemantics.md +docs/models/NestedItems.md +docs/models/NestedOneofToCheckValidationSemantics.md +docs/models/NotMoreComplexSchema.md +docs/models/NulCharactersInStrings.md +docs/models/NullTypeMatchesOnlyTheNullObject.md +docs/models/NumberTypeMatchesNumbers.md +docs/models/ObjectPropertiesValidation.md +docs/models/Oneof.md +docs/models/OneofComplexTypes.md +docs/models/OneofWithBaseSchema.md +docs/models/OneofWithEmptySchema.md +docs/models/OneofWithRequired.md +docs/models/PatternIsNotAnchored.md +docs/models/PatternValidation.md +docs/models/PropertiesWithEscapedCharacters.md +docs/models/PropertyNamedRefThatIsNotAReference.md +docs/models/RefInAdditionalproperties.md +docs/models/RefInAllof.md +docs/models/RefInAnyof.md +docs/models/RefInItems.md +docs/models/RefInNot.md +docs/models/RefInOneof.md +docs/models/RefInProperty.md +docs/models/RequiredDefaultValidation.md +docs/models/RequiredValidation.md +docs/models/RequiredWithEmptyArray.md +docs/models/RequiredWithEscapedCharacters.md +docs/models/SimpleEnumValidation.md +docs/models/StringTypeMatchesStrings.md +docs/models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md +docs/models/UniqueitemsFalseValidation.md +docs/models/UniqueitemsValidation.md +docs/models/UriFormat.md +docs/models/UriReferenceFormat.md +docs/models/UriTemplateFormat.md +git_push.sh +requirements.txt +setup.cfg +setup.py +test-requirements.txt +test/__init__.py +test/test_models/__init__.py +test/test_models/test_additionalproperties_allows_a_schema_which_should_validate.py +test/test_models/test_additionalproperties_are_allowed_by_default.py +test/test_models/test_additionalproperties_can_exist_by_itself.py +test/test_models/test_additionalproperties_should_not_look_in_applicators.py +test/test_models/test_allof.py +test/test_models/test_allof_combined_with_anyof_oneof.py +test/test_models/test_allof_simple_types.py +test/test_models/test_allof_with_base_schema.py +test/test_models/test_allof_with_one_empty_schema.py +test/test_models/test_allof_with_the_first_empty_schema.py +test/test_models/test_allof_with_the_last_empty_schema.py +test/test_models/test_allof_with_two_empty_schemas.py +test/test_models/test_anyof.py +test/test_models/test_anyof_complex_types.py +test/test_models/test_anyof_with_base_schema.py +test/test_models/test_anyof_with_one_empty_schema.py +test/test_models/test_array_type_matches_arrays.py +test/test_models/test_boolean_type_matches_booleans.py +test/test_models/test_by_int.py +test/test_models/test_by_number.py +test/test_models/test_by_small_number.py +test/test_models/test_date_time_format.py +test/test_models/test_email_format.py +test/test_models/test_enum_with0_does_not_match_false.py +test/test_models/test_enum_with1_does_not_match_true.py +test/test_models/test_enum_with_escaped_characters.py +test/test_models/test_enum_with_false_does_not_match0.py +test/test_models/test_enum_with_true_does_not_match1.py +test/test_models/test_enums_in_properties.py +test/test_models/test_forbidden_property.py +test/test_models/test_hostname_format.py +test/test_models/test_integer_type_matches_integers.py +test/test_models/test_invalid_instance_should_not_raise_error_when_float_division_inf.py +test/test_models/test_invalid_string_value_for_default.py +test/test_models/test_ipv4_format.py +test/test_models/test_ipv6_format.py +test/test_models/test_json_pointer_format.py +test/test_models/test_maximum_validation.py +test/test_models/test_maximum_validation_with_unsigned_integer.py +test/test_models/test_maxitems_validation.py +test/test_models/test_maxlength_validation.py +test/test_models/test_maxproperties0_means_the_object_is_empty.py +test/test_models/test_maxproperties_validation.py +test/test_models/test_minimum_validation.py +test/test_models/test_minimum_validation_with_signed_integer.py +test/test_models/test_minitems_validation.py +test/test_models/test_minlength_validation.py +test/test_models/test_minproperties_validation.py +test/test_models/test_model_not.py +test/test_models/test_nested_allof_to_check_validation_semantics.py +test/test_models/test_nested_anyof_to_check_validation_semantics.py +test/test_models/test_nested_items.py +test/test_models/test_nested_oneof_to_check_validation_semantics.py +test/test_models/test_not_more_complex_schema.py +test/test_models/test_nul_characters_in_strings.py +test/test_models/test_null_type_matches_only_the_null_object.py +test/test_models/test_number_type_matches_numbers.py +test/test_models/test_object_properties_validation.py +test/test_models/test_oneof.py +test/test_models/test_oneof_complex_types.py +test/test_models/test_oneof_with_base_schema.py +test/test_models/test_oneof_with_empty_schema.py +test/test_models/test_oneof_with_required.py +test/test_models/test_pattern_is_not_anchored.py +test/test_models/test_pattern_validation.py +test/test_models/test_properties_with_escaped_characters.py +test/test_models/test_property_named_ref_that_is_not_a_reference.py +test/test_models/test_ref_in_additionalproperties.py +test/test_models/test_ref_in_allof.py +test/test_models/test_ref_in_anyof.py +test/test_models/test_ref_in_items.py +test/test_models/test_ref_in_not.py +test/test_models/test_ref_in_oneof.py +test/test_models/test_ref_in_property.py +test/test_models/test_required_default_validation.py +test/test_models/test_required_validation.py +test/test_models/test_required_with_empty_array.py +test/test_models/test_required_with_escaped_characters.py +test/test_models/test_simple_enum_validation.py +test/test_models/test_string_type_matches_strings.py +test/test_models/test_the_default_keyword_does_not_do_anything_if_the_property_is_missing.py +test/test_models/test_uniqueitems_false_validation.py +test/test_models/test_uniqueitems_validation.py +test/test_models/test_uri_format.py +test/test_models/test_uri_reference_format.py +test/test_models/test_uri_template_format.py +tox.ini +unit_test_api/__init__.py +unit_test_api/api_client.py +unit_test_api/apis/__init__.py +unit_test_api/apis/tags/additional_properties_api.py +unit_test_api/apis/tags/all_of_api.py +unit_test_api/apis/tags/any_of_api.py +unit_test_api/apis/tags/content_type_json_api.py +unit_test_api/apis/tags/default_api.py +unit_test_api/apis/tags/enum_api.py +unit_test_api/apis/tags/format_api.py +unit_test_api/apis/tags/items_api.py +unit_test_api/apis/tags/max_items_api.py +unit_test_api/apis/tags/max_length_api.py +unit_test_api/apis/tags/max_properties_api.py +unit_test_api/apis/tags/maximum_api.py +unit_test_api/apis/tags/min_items_api.py +unit_test_api/apis/tags/min_length_api.py +unit_test_api/apis/tags/min_properties_api.py +unit_test_api/apis/tags/minimum_api.py +unit_test_api/apis/tags/model_not_api.py +unit_test_api/apis/tags/multiple_of_api.py +unit_test_api/apis/tags/one_of_api.py +unit_test_api/apis/tags/operation_request_body_api.py +unit_test_api/apis/tags/path_post_api.py +unit_test_api/apis/tags/pattern_api.py +unit_test_api/apis/tags/properties_api.py +unit_test_api/apis/tags/ref_api.py +unit_test_api/apis/tags/required_api.py +unit_test_api/apis/tags/response_content_content_type_schema_api.py +unit_test_api/apis/tags/type_api.py +unit_test_api/apis/tags/unique_items_api.py +unit_test_api/configuration.py +unit_test_api/exceptions.py +unit_test_api/model/__init__.py +unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.py +unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.pyi +unit_test_api/model/additionalproperties_are_allowed_by_default.py +unit_test_api/model/additionalproperties_are_allowed_by_default.pyi +unit_test_api/model/additionalproperties_can_exist_by_itself.py +unit_test_api/model/additionalproperties_can_exist_by_itself.pyi +unit_test_api/model/additionalproperties_should_not_look_in_applicators.py +unit_test_api/model/additionalproperties_should_not_look_in_applicators.pyi +unit_test_api/model/allof.py +unit_test_api/model/allof.pyi +unit_test_api/model/allof_combined_with_anyof_oneof.py +unit_test_api/model/allof_combined_with_anyof_oneof.pyi +unit_test_api/model/allof_simple_types.py +unit_test_api/model/allof_simple_types.pyi +unit_test_api/model/allof_with_base_schema.py +unit_test_api/model/allof_with_base_schema.pyi +unit_test_api/model/allof_with_one_empty_schema.py +unit_test_api/model/allof_with_one_empty_schema.pyi +unit_test_api/model/allof_with_the_first_empty_schema.py +unit_test_api/model/allof_with_the_first_empty_schema.pyi +unit_test_api/model/allof_with_the_last_empty_schema.py +unit_test_api/model/allof_with_the_last_empty_schema.pyi +unit_test_api/model/allof_with_two_empty_schemas.py +unit_test_api/model/allof_with_two_empty_schemas.pyi +unit_test_api/model/anyof.py +unit_test_api/model/anyof.pyi +unit_test_api/model/anyof_complex_types.py +unit_test_api/model/anyof_complex_types.pyi +unit_test_api/model/anyof_with_base_schema.py +unit_test_api/model/anyof_with_base_schema.pyi +unit_test_api/model/anyof_with_one_empty_schema.py +unit_test_api/model/anyof_with_one_empty_schema.pyi +unit_test_api/model/array_type_matches_arrays.py +unit_test_api/model/array_type_matches_arrays.pyi +unit_test_api/model/boolean_type_matches_booleans.py +unit_test_api/model/boolean_type_matches_booleans.pyi +unit_test_api/model/by_int.py +unit_test_api/model/by_int.pyi +unit_test_api/model/by_number.py +unit_test_api/model/by_number.pyi +unit_test_api/model/by_small_number.py +unit_test_api/model/by_small_number.pyi +unit_test_api/model/date_time_format.py +unit_test_api/model/date_time_format.pyi +unit_test_api/model/email_format.py +unit_test_api/model/email_format.pyi +unit_test_api/model/enum_with0_does_not_match_false.py +unit_test_api/model/enum_with0_does_not_match_false.pyi +unit_test_api/model/enum_with1_does_not_match_true.py +unit_test_api/model/enum_with1_does_not_match_true.pyi +unit_test_api/model/enum_with_escaped_characters.py +unit_test_api/model/enum_with_escaped_characters.pyi +unit_test_api/model/enum_with_false_does_not_match0.py +unit_test_api/model/enum_with_false_does_not_match0.pyi +unit_test_api/model/enum_with_true_does_not_match1.py +unit_test_api/model/enum_with_true_does_not_match1.pyi +unit_test_api/model/enums_in_properties.py +unit_test_api/model/enums_in_properties.pyi +unit_test_api/model/forbidden_property.py +unit_test_api/model/forbidden_property.pyi +unit_test_api/model/hostname_format.py +unit_test_api/model/hostname_format.pyi +unit_test_api/model/integer_type_matches_integers.py +unit_test_api/model/integer_type_matches_integers.pyi +unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.py +unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.pyi +unit_test_api/model/invalid_string_value_for_default.py +unit_test_api/model/invalid_string_value_for_default.pyi +unit_test_api/model/ipv4_format.py +unit_test_api/model/ipv4_format.pyi +unit_test_api/model/ipv6_format.py +unit_test_api/model/ipv6_format.pyi +unit_test_api/model/json_pointer_format.py +unit_test_api/model/json_pointer_format.pyi +unit_test_api/model/maximum_validation.py +unit_test_api/model/maximum_validation.pyi +unit_test_api/model/maximum_validation_with_unsigned_integer.py +unit_test_api/model/maximum_validation_with_unsigned_integer.pyi +unit_test_api/model/maxitems_validation.py +unit_test_api/model/maxitems_validation.pyi +unit_test_api/model/maxlength_validation.py +unit_test_api/model/maxlength_validation.pyi +unit_test_api/model/maxproperties0_means_the_object_is_empty.py +unit_test_api/model/maxproperties0_means_the_object_is_empty.pyi +unit_test_api/model/maxproperties_validation.py +unit_test_api/model/maxproperties_validation.pyi +unit_test_api/model/minimum_validation.py +unit_test_api/model/minimum_validation.pyi +unit_test_api/model/minimum_validation_with_signed_integer.py +unit_test_api/model/minimum_validation_with_signed_integer.pyi +unit_test_api/model/minitems_validation.py +unit_test_api/model/minitems_validation.pyi +unit_test_api/model/minlength_validation.py +unit_test_api/model/minlength_validation.pyi +unit_test_api/model/minproperties_validation.py +unit_test_api/model/minproperties_validation.pyi +unit_test_api/model/model_not.py +unit_test_api/model/model_not.pyi +unit_test_api/model/nested_allof_to_check_validation_semantics.py +unit_test_api/model/nested_allof_to_check_validation_semantics.pyi +unit_test_api/model/nested_anyof_to_check_validation_semantics.py +unit_test_api/model/nested_anyof_to_check_validation_semantics.pyi +unit_test_api/model/nested_items.py +unit_test_api/model/nested_items.pyi +unit_test_api/model/nested_oneof_to_check_validation_semantics.py +unit_test_api/model/nested_oneof_to_check_validation_semantics.pyi +unit_test_api/model/not_more_complex_schema.py +unit_test_api/model/not_more_complex_schema.pyi +unit_test_api/model/nul_characters_in_strings.py +unit_test_api/model/nul_characters_in_strings.pyi +unit_test_api/model/null_type_matches_only_the_null_object.py +unit_test_api/model/null_type_matches_only_the_null_object.pyi +unit_test_api/model/number_type_matches_numbers.py +unit_test_api/model/number_type_matches_numbers.pyi +unit_test_api/model/object_properties_validation.py +unit_test_api/model/object_properties_validation.pyi +unit_test_api/model/oneof.py +unit_test_api/model/oneof.pyi +unit_test_api/model/oneof_complex_types.py +unit_test_api/model/oneof_complex_types.pyi +unit_test_api/model/oneof_with_base_schema.py +unit_test_api/model/oneof_with_base_schema.pyi +unit_test_api/model/oneof_with_empty_schema.py +unit_test_api/model/oneof_with_empty_schema.pyi +unit_test_api/model/oneof_with_required.py +unit_test_api/model/oneof_with_required.pyi +unit_test_api/model/pattern_is_not_anchored.py +unit_test_api/model/pattern_is_not_anchored.pyi +unit_test_api/model/pattern_validation.py +unit_test_api/model/pattern_validation.pyi +unit_test_api/model/properties_with_escaped_characters.py +unit_test_api/model/properties_with_escaped_characters.pyi +unit_test_api/model/property_named_ref_that_is_not_a_reference.py +unit_test_api/model/property_named_ref_that_is_not_a_reference.pyi +unit_test_api/model/ref_in_additionalproperties.py +unit_test_api/model/ref_in_additionalproperties.pyi +unit_test_api/model/ref_in_allof.py +unit_test_api/model/ref_in_allof.pyi +unit_test_api/model/ref_in_anyof.py +unit_test_api/model/ref_in_anyof.pyi +unit_test_api/model/ref_in_items.py +unit_test_api/model/ref_in_items.pyi +unit_test_api/model/ref_in_not.py +unit_test_api/model/ref_in_not.pyi +unit_test_api/model/ref_in_oneof.py +unit_test_api/model/ref_in_oneof.pyi +unit_test_api/model/ref_in_property.py +unit_test_api/model/ref_in_property.pyi +unit_test_api/model/required_default_validation.py +unit_test_api/model/required_default_validation.pyi +unit_test_api/model/required_validation.py +unit_test_api/model/required_validation.pyi +unit_test_api/model/required_with_empty_array.py +unit_test_api/model/required_with_empty_array.pyi +unit_test_api/model/required_with_escaped_characters.py +unit_test_api/model/required_with_escaped_characters.pyi +unit_test_api/model/simple_enum_validation.py +unit_test_api/model/simple_enum_validation.pyi +unit_test_api/model/string_type_matches_strings.py +unit_test_api/model/string_type_matches_strings.pyi +unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.py +unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.pyi +unit_test_api/model/uniqueitems_false_validation.py +unit_test_api/model/uniqueitems_false_validation.pyi +unit_test_api/model/uniqueitems_validation.py +unit_test_api/model/uniqueitems_validation.pyi +unit_test_api/model/uri_format.py +unit_test_api/model/uri_format.pyi +unit_test_api/model/uri_reference_format.py +unit_test_api/model/uri_reference_format.pyi +unit_test_api/model/uri_template_format.py +unit_test_api/model/uri_template_format.pyi +unit_test_api/models/__init__.py +unit_test_api/rest.py +unit_test_api/schemas.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python/.openapi-generator/VERSION b/samples/openapi3/client/3_0_3_unit_test/python/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/.travis.yml b/samples/openapi3/client/3_0_3_unit_test/python/.travis.yml similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/.travis.yml rename to samples/openapi3/client/3_0_3_unit_test/python/.travis.yml diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/Makefile b/samples/openapi3/client/3_0_3_unit_test/python/Makefile similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/Makefile rename to samples/openapi3/client/3_0_3_unit_test/python/Makefile diff --git a/samples/openapi3/client/3_0_3_unit_test/python/README.md b/samples/openapi3/client/3_0_3_unit_test/python/README.md new file mode 100644 index 0000000000..3c71a079b1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/README.md @@ -0,0 +1,1014 @@ +# unit-test-api +sample spec for testing openapi functionality, built from json schema tests for draft6 + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 0.0.1 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonClientCodegen + +## Requirements. + +Python >=3.7 + +## Migration from other generators like python and python-legacy + +### Changes +1. This generator uses spec case for all (object) property names and parameter names. + - So if the spec has a property name like camelCase, it will use camelCase rather than camel_case + - So you will need to update how you input and read properties to use spec case +2. Endpoint parameters are stored in dictionaries to prevent collisions (explanation below) + - So you will need to update how you pass data in to endpoints +3. Endpoint responses now include the original response, the deserialized response body, and (todo)the deserialized headers + - So you will need to update your code to use response.body to access deserialized data +4. All validated data is instantiated in an instance that subclasses all validated Schema classes and Decimal/str/list/tuple/frozendict/NoneClass/BoolClass/bytes/io.FileIO + - This means that you can use isinstance to check if a payload validated against a schema class + - This means that no data will be of type None/True/False + - ingested None will subclass NoneClass + - ingested True will subclass BoolClass + - ingested False will subclass BoolClass + - So if you need to check is True/False/None, instead use instance.is_true_oapg()/.is_false_oapg()/.is_none_oapg() +5. All validated class instances are immutable except for ones based on io.File + - This is because if properties were changed after validation, that validation would no longer apply + - So no changing values or property values after a class has been instantiated +6. String + Number types with formats + - String type data is stored as a string and if you need to access types based on its format like date, + date-time, uuid, number etc then you will need to use accessor functions on the instance + - type string + format: See .as_date_oapg, .as_datetime_oapg, .as_decimal_oapg, .as_uuid_oapg + - type number + format: See .as_float_oapg, .as_int_oapg + - this was done because openapi/json-schema defines constraints. string data may be type string with no format + keyword in one schema, and include a format constraint in another schema + - So if you need to access a string format based type, use as_date_oapg/as_datetime_oapg/as_decimal_oapg/as_uuid_oapg + - So if you need to access a number format based type, use as_int_oapg/as_float_oapg +7. Property access on AnyType(type unset) or object(dict) schemas + - Only required keys with valid python names are properties like .someProp and have type hints + - All optional keys may not exist, so properties are not defined for them + - One can access optional values with dict_instance['optionalProp'] and KeyError will be raised if it does not exist + - Use get_item_oapg if you need a way to always get a value whether or not the key exists + - If the key does not exist, schemas.unset is returned from calling dict_instance.get_item_oapg('optionalProp') + - All required and optional keys have type hints for this method, and @typing.overload is used + - A type hint is also generated for additionalProperties accessed using this method + - So you will need to update you code to use some_instance['optionalProp'] to access optional property + and additionalProperty values +8. The location of the api classes has changed + - Api classes are located in your_package.apis.tags.some_api + - This change was made to eliminate redundant code generation + - Legacy generators generated the same endpoint twice if it had > 1 tag on it + - This generator defines an endpoint in one class, then inherits that class to generate + apis by tags and by paths + - This change reduces code and allows quicker run time if you use the path apis + - path apis are at your_package.apis.paths.some_path + - Those apis will only load their needed models, which is less to load than all of the resources needed in a tag api + - So you will need to update your import paths to the api classes + +### Why are Oapg and _oapg used in class and method names? +Classes can have arbitrarily named properties set on them +Endpoints can have arbitrary operationId method names set +For those reasons, I use the prefix Oapg and _oapg to greatly reduce the likelihood of collisions +on protected + public classes/methods. +oapg stands for OpenApi Python Generator. + +### Object property spec case +This was done because when payloads are ingested, they can be validated against N number of schemas. +If the input signature used a different property name then that has mutated the payload. +So SchemaA and SchemaB must both see the camelCase spec named variable. +Also it is possible to send in two properties, named camelCase and camel_case in the same payload. +That use case should be support so spec case is used. + +### Parameter spec case +Parameters can be included in different locations including: +- query +- path +- header +- cookie + +Any of those parameters could use the same parameter names, so if every parameter +was included as an endpoint parameter in a function signature, they would collide. +For that reason, each of those inputs have been separated out into separate typed dictionaries: +- query_params +- path_params +- header_params +- cookie_params + +So when updating your code, you will need to pass endpoint parameters in using those +dictionaries. + +### Endpoint responses +Endpoint responses have been enriched to now include more information. +Any response reom an endpoint will now include the following properties: +response: urllib3.HTTPResponse +body: typing.Union[Unset, Schema] +headers: typing.Union[Unset, TODO] +Note: response header deserialization has not yet been added + + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: +```python +import unit_test_api +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import unit_test_api +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python + +import time +import unit_test_api +from pprint import pprint +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from unit_test_api.model.ref_in_allof import RefInAllof +from unit_test_api.model.ref_in_anyof import RefInAnyof +from unit_test_api.model.ref_in_items import RefInItems +from unit_test_api.model.ref_in_oneof import RefInOneof +from unit_test_api.model.ref_in_property import RefInProperty +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + property_named_ref_that_is_not_a_reference = PropertyNamedRefThatIsNotAReference(None) # PropertyNamedRefThatIsNotAReference | + + try: + api_instance.post_property_named_ref_that_is_not_a_reference_request_body(property_named_ref_that_is_not_a_reference) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_property_named_ref_that_is_not_a_reference_request_body: %s\n" % e) +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://someserver.com/v1* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*RefApi* | [**post_property_named_ref_that_is_not_a_reference_request_body**](docs/apis/tags/RefApi.md#post_property_named_ref_that_is_not_a_reference_request_body) | **post** /requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody | +*RefApi* | [**post_property_named_ref_that_is_not_a_reference_response_body_for_content_types**](docs/apis/tags/RefApi.md#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types) | **post** /responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes | +*RefApi* | [**post_ref_in_additionalproperties_request_body**](docs/apis/tags/RefApi.md#post_ref_in_additionalproperties_request_body) | **post** /requestBody/postRefInAdditionalpropertiesRequestBody | +*RefApi* | [**post_ref_in_additionalproperties_response_body_for_content_types**](docs/apis/tags/RefApi.md#post_ref_in_additionalproperties_response_body_for_content_types) | **post** /responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes | +*RefApi* | [**post_ref_in_allof_request_body**](docs/apis/tags/RefApi.md#post_ref_in_allof_request_body) | **post** /requestBody/postRefInAllofRequestBody | +*RefApi* | [**post_ref_in_allof_response_body_for_content_types**](docs/apis/tags/RefApi.md#post_ref_in_allof_response_body_for_content_types) | **post** /responseBody/postRefInAllofResponseBodyForContentTypes | +*RefApi* | [**post_ref_in_anyof_request_body**](docs/apis/tags/RefApi.md#post_ref_in_anyof_request_body) | **post** /requestBody/postRefInAnyofRequestBody | +*RefApi* | [**post_ref_in_anyof_response_body_for_content_types**](docs/apis/tags/RefApi.md#post_ref_in_anyof_response_body_for_content_types) | **post** /responseBody/postRefInAnyofResponseBodyForContentTypes | +*RefApi* | [**post_ref_in_items_request_body**](docs/apis/tags/RefApi.md#post_ref_in_items_request_body) | **post** /requestBody/postRefInItemsRequestBody | +*RefApi* | [**post_ref_in_items_response_body_for_content_types**](docs/apis/tags/RefApi.md#post_ref_in_items_response_body_for_content_types) | **post** /responseBody/postRefInItemsResponseBodyForContentTypes | +*RefApi* | [**post_ref_in_not_request_body**](docs/apis/tags/RefApi.md#post_ref_in_not_request_body) | **post** /requestBody/postRefInNotRequestBody | +*RefApi* | [**post_ref_in_not_response_body_for_content_types**](docs/apis/tags/RefApi.md#post_ref_in_not_response_body_for_content_types) | **post** /responseBody/postRefInNotResponseBodyForContentTypes | +*RefApi* | [**post_ref_in_oneof_request_body**](docs/apis/tags/RefApi.md#post_ref_in_oneof_request_body) | **post** /requestBody/postRefInOneofRequestBody | +*RefApi* | [**post_ref_in_oneof_response_body_for_content_types**](docs/apis/tags/RefApi.md#post_ref_in_oneof_response_body_for_content_types) | **post** /responseBody/postRefInOneofResponseBodyForContentTypes | +*RefApi* | [**post_ref_in_property_request_body**](docs/apis/tags/RefApi.md#post_ref_in_property_request_body) | **post** /requestBody/postRefInPropertyRequestBody | +*RefApi* | [**post_ref_in_property_response_body_for_content_types**](docs/apis/tags/RefApi.md#post_ref_in_property_response_body_for_content_types) | **post** /responseBody/postRefInPropertyResponseBodyForContentTypes | +*AdditionalPropertiesApi* | [**post_additionalproperties_allows_a_schema_which_should_validate_request_body**](docs/apis/tags/AdditionalPropertiesApi.md#post_additionalproperties_allows_a_schema_which_should_validate_request_body) | **post** /requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody | +*AdditionalPropertiesApi* | [**post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types**](docs/apis/tags/AdditionalPropertiesApi.md#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes | +*AdditionalPropertiesApi* | [**post_additionalproperties_are_allowed_by_default_request_body**](docs/apis/tags/AdditionalPropertiesApi.md#post_additionalproperties_are_allowed_by_default_request_body) | **post** /requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody | +*AdditionalPropertiesApi* | [**post_additionalproperties_are_allowed_by_default_response_body_for_content_types**](docs/apis/tags/AdditionalPropertiesApi.md#post_additionalproperties_are_allowed_by_default_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes | +*AdditionalPropertiesApi* | [**post_additionalproperties_can_exist_by_itself_request_body**](docs/apis/tags/AdditionalPropertiesApi.md#post_additionalproperties_can_exist_by_itself_request_body) | **post** /requestBody/postAdditionalpropertiesCanExistByItselfRequestBody | +*AdditionalPropertiesApi* | [**post_additionalproperties_can_exist_by_itself_response_body_for_content_types**](docs/apis/tags/AdditionalPropertiesApi.md#post_additionalproperties_can_exist_by_itself_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes | +*AdditionalPropertiesApi* | [**post_additionalproperties_should_not_look_in_applicators_request_body**](docs/apis/tags/AdditionalPropertiesApi.md#post_additionalproperties_should_not_look_in_applicators_request_body) | **post** /requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody | +*AdditionalPropertiesApi* | [**post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types**](docs/apis/tags/AdditionalPropertiesApi.md#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes | +*AllOfApi* | [**post_allof_combined_with_anyof_oneof_request_body**](docs/apis/tags/AllOfApi.md#post_allof_combined_with_anyof_oneof_request_body) | **post** /requestBody/postAllofCombinedWithAnyofOneofRequestBody | +*AllOfApi* | [**post_allof_combined_with_anyof_oneof_response_body_for_content_types**](docs/apis/tags/AllOfApi.md#post_allof_combined_with_anyof_oneof_response_body_for_content_types) | **post** /responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes | +*AllOfApi* | [**post_allof_request_body**](docs/apis/tags/AllOfApi.md#post_allof_request_body) | **post** /requestBody/postAllofRequestBody | +*AllOfApi* | [**post_allof_response_body_for_content_types**](docs/apis/tags/AllOfApi.md#post_allof_response_body_for_content_types) | **post** /responseBody/postAllofResponseBodyForContentTypes | +*AllOfApi* | [**post_allof_simple_types_request_body**](docs/apis/tags/AllOfApi.md#post_allof_simple_types_request_body) | **post** /requestBody/postAllofSimpleTypesRequestBody | +*AllOfApi* | [**post_allof_simple_types_response_body_for_content_types**](docs/apis/tags/AllOfApi.md#post_allof_simple_types_response_body_for_content_types) | **post** /responseBody/postAllofSimpleTypesResponseBodyForContentTypes | +*AllOfApi* | [**post_allof_with_base_schema_request_body**](docs/apis/tags/AllOfApi.md#post_allof_with_base_schema_request_body) | **post** /requestBody/postAllofWithBaseSchemaRequestBody | +*AllOfApi* | [**post_allof_with_base_schema_response_body_for_content_types**](docs/apis/tags/AllOfApi.md#post_allof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes | +*AllOfApi* | [**post_allof_with_one_empty_schema_request_body**](docs/apis/tags/AllOfApi.md#post_allof_with_one_empty_schema_request_body) | **post** /requestBody/postAllofWithOneEmptySchemaRequestBody | +*AllOfApi* | [**post_allof_with_one_empty_schema_response_body_for_content_types**](docs/apis/tags/AllOfApi.md#post_allof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes | +*AllOfApi* | [**post_allof_with_the_first_empty_schema_request_body**](docs/apis/tags/AllOfApi.md#post_allof_with_the_first_empty_schema_request_body) | **post** /requestBody/postAllofWithTheFirstEmptySchemaRequestBody | +*AllOfApi* | [**post_allof_with_the_first_empty_schema_response_body_for_content_types**](docs/apis/tags/AllOfApi.md#post_allof_with_the_first_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes | +*AllOfApi* | [**post_allof_with_the_last_empty_schema_request_body**](docs/apis/tags/AllOfApi.md#post_allof_with_the_last_empty_schema_request_body) | **post** /requestBody/postAllofWithTheLastEmptySchemaRequestBody | +*AllOfApi* | [**post_allof_with_the_last_empty_schema_response_body_for_content_types**](docs/apis/tags/AllOfApi.md#post_allof_with_the_last_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes | +*AllOfApi* | [**post_allof_with_two_empty_schemas_request_body**](docs/apis/tags/AllOfApi.md#post_allof_with_two_empty_schemas_request_body) | **post** /requestBody/postAllofWithTwoEmptySchemasRequestBody | +*AllOfApi* | [**post_allof_with_two_empty_schemas_response_body_for_content_types**](docs/apis/tags/AllOfApi.md#post_allof_with_two_empty_schemas_response_body_for_content_types) | **post** /responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes | +*AllOfApi* | [**post_nested_allof_to_check_validation_semantics_request_body**](docs/apis/tags/AllOfApi.md#post_nested_allof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAllofToCheckValidationSemanticsRequestBody | +*AllOfApi* | [**post_nested_allof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/AllOfApi.md#post_nested_allof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes | +*AnyOfApi* | [**post_anyof_complex_types_request_body**](docs/apis/tags/AnyOfApi.md#post_anyof_complex_types_request_body) | **post** /requestBody/postAnyofComplexTypesRequestBody | +*AnyOfApi* | [**post_anyof_complex_types_response_body_for_content_types**](docs/apis/tags/AnyOfApi.md#post_anyof_complex_types_response_body_for_content_types) | **post** /responseBody/postAnyofComplexTypesResponseBodyForContentTypes | +*AnyOfApi* | [**post_anyof_request_body**](docs/apis/tags/AnyOfApi.md#post_anyof_request_body) | **post** /requestBody/postAnyofRequestBody | +*AnyOfApi* | [**post_anyof_response_body_for_content_types**](docs/apis/tags/AnyOfApi.md#post_anyof_response_body_for_content_types) | **post** /responseBody/postAnyofResponseBodyForContentTypes | +*AnyOfApi* | [**post_anyof_with_base_schema_request_body**](docs/apis/tags/AnyOfApi.md#post_anyof_with_base_schema_request_body) | **post** /requestBody/postAnyofWithBaseSchemaRequestBody | +*AnyOfApi* | [**post_anyof_with_base_schema_response_body_for_content_types**](docs/apis/tags/AnyOfApi.md#post_anyof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes | +*AnyOfApi* | [**post_anyof_with_one_empty_schema_request_body**](docs/apis/tags/AnyOfApi.md#post_anyof_with_one_empty_schema_request_body) | **post** /requestBody/postAnyofWithOneEmptySchemaRequestBody | +*AnyOfApi* | [**post_anyof_with_one_empty_schema_response_body_for_content_types**](docs/apis/tags/AnyOfApi.md#post_anyof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes | +*AnyOfApi* | [**post_nested_anyof_to_check_validation_semantics_request_body**](docs/apis/tags/AnyOfApi.md#post_nested_anyof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody | +*AnyOfApi* | [**post_nested_anyof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/AnyOfApi.md#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_additionalproperties_allows_a_schema_which_should_validate_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_additionalproperties_allows_a_schema_which_should_validate_request_body) | **post** /requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody | +*ContentTypeJsonApi* | [**post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_additionalproperties_are_allowed_by_default_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_additionalproperties_are_allowed_by_default_request_body) | **post** /requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody | +*ContentTypeJsonApi* | [**post_additionalproperties_are_allowed_by_default_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_additionalproperties_are_allowed_by_default_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_additionalproperties_can_exist_by_itself_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_additionalproperties_can_exist_by_itself_request_body) | **post** /requestBody/postAdditionalpropertiesCanExistByItselfRequestBody | +*ContentTypeJsonApi* | [**post_additionalproperties_can_exist_by_itself_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_additionalproperties_can_exist_by_itself_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_additionalproperties_should_not_look_in_applicators_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_additionalproperties_should_not_look_in_applicators_request_body) | **post** /requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody | +*ContentTypeJsonApi* | [**post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_allof_combined_with_anyof_oneof_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_combined_with_anyof_oneof_request_body) | **post** /requestBody/postAllofCombinedWithAnyofOneofRequestBody | +*ContentTypeJsonApi* | [**post_allof_combined_with_anyof_oneof_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_combined_with_anyof_oneof_response_body_for_content_types) | **post** /responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_allof_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_request_body) | **post** /requestBody/postAllofRequestBody | +*ContentTypeJsonApi* | [**post_allof_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_response_body_for_content_types) | **post** /responseBody/postAllofResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_allof_simple_types_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_simple_types_request_body) | **post** /requestBody/postAllofSimpleTypesRequestBody | +*ContentTypeJsonApi* | [**post_allof_simple_types_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_simple_types_response_body_for_content_types) | **post** /responseBody/postAllofSimpleTypesResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_allof_with_base_schema_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_base_schema_request_body) | **post** /requestBody/postAllofWithBaseSchemaRequestBody | +*ContentTypeJsonApi* | [**post_allof_with_base_schema_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_allof_with_one_empty_schema_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_one_empty_schema_request_body) | **post** /requestBody/postAllofWithOneEmptySchemaRequestBody | +*ContentTypeJsonApi* | [**post_allof_with_one_empty_schema_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_allof_with_the_first_empty_schema_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_the_first_empty_schema_request_body) | **post** /requestBody/postAllofWithTheFirstEmptySchemaRequestBody | +*ContentTypeJsonApi* | [**post_allof_with_the_first_empty_schema_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_the_first_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_allof_with_the_last_empty_schema_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_the_last_empty_schema_request_body) | **post** /requestBody/postAllofWithTheLastEmptySchemaRequestBody | +*ContentTypeJsonApi* | [**post_allof_with_the_last_empty_schema_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_the_last_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_allof_with_two_empty_schemas_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_two_empty_schemas_request_body) | **post** /requestBody/postAllofWithTwoEmptySchemasRequestBody | +*ContentTypeJsonApi* | [**post_allof_with_two_empty_schemas_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_allof_with_two_empty_schemas_response_body_for_content_types) | **post** /responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_anyof_complex_types_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_anyof_complex_types_request_body) | **post** /requestBody/postAnyofComplexTypesRequestBody | +*ContentTypeJsonApi* | [**post_anyof_complex_types_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_anyof_complex_types_response_body_for_content_types) | **post** /responseBody/postAnyofComplexTypesResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_anyof_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_anyof_request_body) | **post** /requestBody/postAnyofRequestBody | +*ContentTypeJsonApi* | [**post_anyof_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_anyof_response_body_for_content_types) | **post** /responseBody/postAnyofResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_anyof_with_base_schema_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_anyof_with_base_schema_request_body) | **post** /requestBody/postAnyofWithBaseSchemaRequestBody | +*ContentTypeJsonApi* | [**post_anyof_with_base_schema_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_anyof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_anyof_with_one_empty_schema_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_anyof_with_one_empty_schema_request_body) | **post** /requestBody/postAnyofWithOneEmptySchemaRequestBody | +*ContentTypeJsonApi* | [**post_anyof_with_one_empty_schema_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_anyof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_array_type_matches_arrays_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_array_type_matches_arrays_request_body) | **post** /requestBody/postArrayTypeMatchesArraysRequestBody | +*ContentTypeJsonApi* | [**post_array_type_matches_arrays_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_array_type_matches_arrays_response_body_for_content_types) | **post** /responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_boolean_type_matches_booleans_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_boolean_type_matches_booleans_request_body) | **post** /requestBody/postBooleanTypeMatchesBooleansRequestBody | +*ContentTypeJsonApi* | [**post_boolean_type_matches_booleans_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_boolean_type_matches_booleans_response_body_for_content_types) | **post** /responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_by_int_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_by_int_request_body) | **post** /requestBody/postByIntRequestBody | +*ContentTypeJsonApi* | [**post_by_int_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_by_int_response_body_for_content_types) | **post** /responseBody/postByIntResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_by_number_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_by_number_request_body) | **post** /requestBody/postByNumberRequestBody | +*ContentTypeJsonApi* | [**post_by_number_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_by_number_response_body_for_content_types) | **post** /responseBody/postByNumberResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_by_small_number_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_by_small_number_request_body) | **post** /requestBody/postBySmallNumberRequestBody | +*ContentTypeJsonApi* | [**post_by_small_number_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_by_small_number_response_body_for_content_types) | **post** /responseBody/postBySmallNumberResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_date_time_format_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_date_time_format_request_body) | **post** /requestBody/postDateTimeFormatRequestBody | +*ContentTypeJsonApi* | [**post_date_time_format_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_date_time_format_response_body_for_content_types) | **post** /responseBody/postDateTimeFormatResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_email_format_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_email_format_request_body) | **post** /requestBody/postEmailFormatRequestBody | +*ContentTypeJsonApi* | [**post_email_format_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_email_format_response_body_for_content_types) | **post** /responseBody/postEmailFormatResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_enum_with0_does_not_match_false_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with0_does_not_match_false_request_body) | **post** /requestBody/postEnumWith0DoesNotMatchFalseRequestBody | +*ContentTypeJsonApi* | [**post_enum_with0_does_not_match_false_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with0_does_not_match_false_response_body_for_content_types) | **post** /responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_enum_with1_does_not_match_true_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with1_does_not_match_true_request_body) | **post** /requestBody/postEnumWith1DoesNotMatchTrueRequestBody | +*ContentTypeJsonApi* | [**post_enum_with1_does_not_match_true_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with1_does_not_match_true_response_body_for_content_types) | **post** /responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_enum_with_escaped_characters_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with_escaped_characters_request_body) | **post** /requestBody/postEnumWithEscapedCharactersRequestBody | +*ContentTypeJsonApi* | [**post_enum_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_enum_with_false_does_not_match0_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with_false_does_not_match0_request_body) | **post** /requestBody/postEnumWithFalseDoesNotMatch0RequestBody | +*ContentTypeJsonApi* | [**post_enum_with_false_does_not_match0_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with_false_does_not_match0_response_body_for_content_types) | **post** /responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_enum_with_true_does_not_match1_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with_true_does_not_match1_request_body) | **post** /requestBody/postEnumWithTrueDoesNotMatch1RequestBody | +*ContentTypeJsonApi* | [**post_enum_with_true_does_not_match1_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_enum_with_true_does_not_match1_response_body_for_content_types) | **post** /responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_enums_in_properties_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_enums_in_properties_request_body) | **post** /requestBody/postEnumsInPropertiesRequestBody | +*ContentTypeJsonApi* | [**post_enums_in_properties_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_enums_in_properties_response_body_for_content_types) | **post** /responseBody/postEnumsInPropertiesResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_forbidden_property_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_forbidden_property_request_body) | **post** /requestBody/postForbiddenPropertyRequestBody | +*ContentTypeJsonApi* | [**post_forbidden_property_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_forbidden_property_response_body_for_content_types) | **post** /responseBody/postForbiddenPropertyResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_hostname_format_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_hostname_format_request_body) | **post** /requestBody/postHostnameFormatRequestBody | +*ContentTypeJsonApi* | [**post_hostname_format_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_hostname_format_response_body_for_content_types) | **post** /responseBody/postHostnameFormatResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_integer_type_matches_integers_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_integer_type_matches_integers_request_body) | **post** /requestBody/postIntegerTypeMatchesIntegersRequestBody | +*ContentTypeJsonApi* | [**post_integer_type_matches_integers_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_integer_type_matches_integers_response_body_for_content_types) | **post** /responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body) | **post** /requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody | +*ContentTypeJsonApi* | [**post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types) | **post** /responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_invalid_string_value_for_default_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_invalid_string_value_for_default_request_body) | **post** /requestBody/postInvalidStringValueForDefaultRequestBody | +*ContentTypeJsonApi* | [**post_invalid_string_value_for_default_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_invalid_string_value_for_default_response_body_for_content_types) | **post** /responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_ipv4_format_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_ipv4_format_request_body) | **post** /requestBody/postIpv4FormatRequestBody | +*ContentTypeJsonApi* | [**post_ipv4_format_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_ipv4_format_response_body_for_content_types) | **post** /responseBody/postIpv4FormatResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_ipv6_format_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_ipv6_format_request_body) | **post** /requestBody/postIpv6FormatRequestBody | +*ContentTypeJsonApi* | [**post_ipv6_format_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_ipv6_format_response_body_for_content_types) | **post** /responseBody/postIpv6FormatResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_json_pointer_format_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_json_pointer_format_request_body) | **post** /requestBody/postJsonPointerFormatRequestBody | +*ContentTypeJsonApi* | [**post_json_pointer_format_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_json_pointer_format_response_body_for_content_types) | **post** /responseBody/postJsonPointerFormatResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_maximum_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_maximum_validation_request_body) | **post** /requestBody/postMaximumValidationRequestBody | +*ContentTypeJsonApi* | [**post_maximum_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_maximum_validation_response_body_for_content_types) | **post** /responseBody/postMaximumValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_maximum_validation_with_unsigned_integer_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_maximum_validation_with_unsigned_integer_request_body) | **post** /requestBody/postMaximumValidationWithUnsignedIntegerRequestBody | +*ContentTypeJsonApi* | [**post_maximum_validation_with_unsigned_integer_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_maximum_validation_with_unsigned_integer_response_body_for_content_types) | **post** /responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_maxitems_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_maxitems_validation_request_body) | **post** /requestBody/postMaxitemsValidationRequestBody | +*ContentTypeJsonApi* | [**post_maxitems_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_maxitems_validation_response_body_for_content_types) | **post** /responseBody/postMaxitemsValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_maxlength_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_maxlength_validation_request_body) | **post** /requestBody/postMaxlengthValidationRequestBody | +*ContentTypeJsonApi* | [**post_maxlength_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_maxlength_validation_response_body_for_content_types) | **post** /responseBody/postMaxlengthValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_maxproperties0_means_the_object_is_empty_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_maxproperties0_means_the_object_is_empty_request_body) | **post** /requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody | +*ContentTypeJsonApi* | [**post_maxproperties0_means_the_object_is_empty_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types) | **post** /responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_maxproperties_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_maxproperties_validation_request_body) | **post** /requestBody/postMaxpropertiesValidationRequestBody | +*ContentTypeJsonApi* | [**post_maxproperties_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_maxproperties_validation_response_body_for_content_types) | **post** /responseBody/postMaxpropertiesValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_minimum_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_minimum_validation_request_body) | **post** /requestBody/postMinimumValidationRequestBody | +*ContentTypeJsonApi* | [**post_minimum_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_minimum_validation_response_body_for_content_types) | **post** /responseBody/postMinimumValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_minimum_validation_with_signed_integer_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_minimum_validation_with_signed_integer_request_body) | **post** /requestBody/postMinimumValidationWithSignedIntegerRequestBody | +*ContentTypeJsonApi* | [**post_minimum_validation_with_signed_integer_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_minimum_validation_with_signed_integer_response_body_for_content_types) | **post** /responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_minitems_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_minitems_validation_request_body) | **post** /requestBody/postMinitemsValidationRequestBody | +*ContentTypeJsonApi* | [**post_minitems_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_minitems_validation_response_body_for_content_types) | **post** /responseBody/postMinitemsValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_minlength_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_minlength_validation_request_body) | **post** /requestBody/postMinlengthValidationRequestBody | +*ContentTypeJsonApi* | [**post_minlength_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_minlength_validation_response_body_for_content_types) | **post** /responseBody/postMinlengthValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_minproperties_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_minproperties_validation_request_body) | **post** /requestBody/postMinpropertiesValidationRequestBody | +*ContentTypeJsonApi* | [**post_minproperties_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_minproperties_validation_response_body_for_content_types) | **post** /responseBody/postMinpropertiesValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_nested_allof_to_check_validation_semantics_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_nested_allof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAllofToCheckValidationSemanticsRequestBody | +*ContentTypeJsonApi* | [**post_nested_allof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_nested_allof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_nested_anyof_to_check_validation_semantics_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_nested_anyof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody | +*ContentTypeJsonApi* | [**post_nested_anyof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_nested_items_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_nested_items_request_body) | **post** /requestBody/postNestedItemsRequestBody | +*ContentTypeJsonApi* | [**post_nested_items_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_nested_items_response_body_for_content_types) | **post** /responseBody/postNestedItemsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_nested_oneof_to_check_validation_semantics_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_nested_oneof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedOneofToCheckValidationSemanticsRequestBody | +*ContentTypeJsonApi* | [**post_nested_oneof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_not_more_complex_schema_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_not_more_complex_schema_request_body) | **post** /requestBody/postNotMoreComplexSchemaRequestBody | +*ContentTypeJsonApi* | [**post_not_more_complex_schema_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_not_more_complex_schema_response_body_for_content_types) | **post** /responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_not_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_not_request_body) | **post** /requestBody/postNotRequestBody | +*ContentTypeJsonApi* | [**post_not_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_not_response_body_for_content_types) | **post** /responseBody/postNotResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_nul_characters_in_strings_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_nul_characters_in_strings_request_body) | **post** /requestBody/postNulCharactersInStringsRequestBody | +*ContentTypeJsonApi* | [**post_nul_characters_in_strings_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_nul_characters_in_strings_response_body_for_content_types) | **post** /responseBody/postNulCharactersInStringsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_null_type_matches_only_the_null_object_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_null_type_matches_only_the_null_object_request_body) | **post** /requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody | +*ContentTypeJsonApi* | [**post_null_type_matches_only_the_null_object_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_null_type_matches_only_the_null_object_response_body_for_content_types) | **post** /responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_number_type_matches_numbers_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_number_type_matches_numbers_request_body) | **post** /requestBody/postNumberTypeMatchesNumbersRequestBody | +*ContentTypeJsonApi* | [**post_number_type_matches_numbers_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_number_type_matches_numbers_response_body_for_content_types) | **post** /responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_object_properties_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_object_properties_validation_request_body) | **post** /requestBody/postObjectPropertiesValidationRequestBody | +*ContentTypeJsonApi* | [**post_object_properties_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_object_properties_validation_response_body_for_content_types) | **post** /responseBody/postObjectPropertiesValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_object_type_matches_objects_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_object_type_matches_objects_request_body) | **post** /requestBody/postObjectTypeMatchesObjectsRequestBody | +*ContentTypeJsonApi* | [**post_object_type_matches_objects_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_object_type_matches_objects_response_body_for_content_types) | **post** /responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_oneof_complex_types_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_complex_types_request_body) | **post** /requestBody/postOneofComplexTypesRequestBody | +*ContentTypeJsonApi* | [**post_oneof_complex_types_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_complex_types_response_body_for_content_types) | **post** /responseBody/postOneofComplexTypesResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_oneof_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_request_body) | **post** /requestBody/postOneofRequestBody | +*ContentTypeJsonApi* | [**post_oneof_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_response_body_for_content_types) | **post** /responseBody/postOneofResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_oneof_with_base_schema_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_with_base_schema_request_body) | **post** /requestBody/postOneofWithBaseSchemaRequestBody | +*ContentTypeJsonApi* | [**post_oneof_with_base_schema_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_oneof_with_empty_schema_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_with_empty_schema_request_body) | **post** /requestBody/postOneofWithEmptySchemaRequestBody | +*ContentTypeJsonApi* | [**post_oneof_with_empty_schema_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_with_empty_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_oneof_with_required_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_with_required_request_body) | **post** /requestBody/postOneofWithRequiredRequestBody | +*ContentTypeJsonApi* | [**post_oneof_with_required_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_oneof_with_required_response_body_for_content_types) | **post** /responseBody/postOneofWithRequiredResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_pattern_is_not_anchored_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_pattern_is_not_anchored_request_body) | **post** /requestBody/postPatternIsNotAnchoredRequestBody | +*ContentTypeJsonApi* | [**post_pattern_is_not_anchored_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_pattern_is_not_anchored_response_body_for_content_types) | **post** /responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_pattern_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_pattern_validation_request_body) | **post** /requestBody/postPatternValidationRequestBody | +*ContentTypeJsonApi* | [**post_pattern_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_pattern_validation_response_body_for_content_types) | **post** /responseBody/postPatternValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_properties_with_escaped_characters_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_properties_with_escaped_characters_request_body) | **post** /requestBody/postPropertiesWithEscapedCharactersRequestBody | +*ContentTypeJsonApi* | [**post_properties_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_properties_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_property_named_ref_that_is_not_a_reference_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_property_named_ref_that_is_not_a_reference_request_body) | **post** /requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody | +*ContentTypeJsonApi* | [**post_property_named_ref_that_is_not_a_reference_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types) | **post** /responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_ref_in_additionalproperties_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_additionalproperties_request_body) | **post** /requestBody/postRefInAdditionalpropertiesRequestBody | +*ContentTypeJsonApi* | [**post_ref_in_additionalproperties_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_additionalproperties_response_body_for_content_types) | **post** /responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_ref_in_allof_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_allof_request_body) | **post** /requestBody/postRefInAllofRequestBody | +*ContentTypeJsonApi* | [**post_ref_in_allof_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_allof_response_body_for_content_types) | **post** /responseBody/postRefInAllofResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_ref_in_anyof_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_anyof_request_body) | **post** /requestBody/postRefInAnyofRequestBody | +*ContentTypeJsonApi* | [**post_ref_in_anyof_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_anyof_response_body_for_content_types) | **post** /responseBody/postRefInAnyofResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_ref_in_items_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_items_request_body) | **post** /requestBody/postRefInItemsRequestBody | +*ContentTypeJsonApi* | [**post_ref_in_items_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_items_response_body_for_content_types) | **post** /responseBody/postRefInItemsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_ref_in_not_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_not_request_body) | **post** /requestBody/postRefInNotRequestBody | +*ContentTypeJsonApi* | [**post_ref_in_not_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_not_response_body_for_content_types) | **post** /responseBody/postRefInNotResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_ref_in_oneof_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_oneof_request_body) | **post** /requestBody/postRefInOneofRequestBody | +*ContentTypeJsonApi* | [**post_ref_in_oneof_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_oneof_response_body_for_content_types) | **post** /responseBody/postRefInOneofResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_ref_in_property_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_property_request_body) | **post** /requestBody/postRefInPropertyRequestBody | +*ContentTypeJsonApi* | [**post_ref_in_property_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_ref_in_property_response_body_for_content_types) | **post** /responseBody/postRefInPropertyResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_required_default_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_required_default_validation_request_body) | **post** /requestBody/postRequiredDefaultValidationRequestBody | +*ContentTypeJsonApi* | [**post_required_default_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_required_default_validation_response_body_for_content_types) | **post** /responseBody/postRequiredDefaultValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_required_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_required_validation_request_body) | **post** /requestBody/postRequiredValidationRequestBody | +*ContentTypeJsonApi* | [**post_required_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_required_validation_response_body_for_content_types) | **post** /responseBody/postRequiredValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_required_with_empty_array_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_required_with_empty_array_request_body) | **post** /requestBody/postRequiredWithEmptyArrayRequestBody | +*ContentTypeJsonApi* | [**post_required_with_empty_array_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_required_with_empty_array_response_body_for_content_types) | **post** /responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_required_with_escaped_characters_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_required_with_escaped_characters_request_body) | **post** /requestBody/postRequiredWithEscapedCharactersRequestBody | +*ContentTypeJsonApi* | [**post_required_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_required_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_simple_enum_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_simple_enum_validation_request_body) | **post** /requestBody/postSimpleEnumValidationRequestBody | +*ContentTypeJsonApi* | [**post_simple_enum_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_simple_enum_validation_response_body_for_content_types) | **post** /responseBody/postSimpleEnumValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_string_type_matches_strings_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_string_type_matches_strings_request_body) | **post** /requestBody/postStringTypeMatchesStringsRequestBody | +*ContentTypeJsonApi* | [**post_string_type_matches_strings_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_string_type_matches_strings_response_body_for_content_types) | **post** /responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body) | **post** /requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody | +*ContentTypeJsonApi* | [**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types) | **post** /responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_uniqueitems_false_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_uniqueitems_false_validation_request_body) | **post** /requestBody/postUniqueitemsFalseValidationRequestBody | +*ContentTypeJsonApi* | [**post_uniqueitems_false_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_uniqueitems_false_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_uniqueitems_validation_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_uniqueitems_validation_request_body) | **post** /requestBody/postUniqueitemsValidationRequestBody | +*ContentTypeJsonApi* | [**post_uniqueitems_validation_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_uniqueitems_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsValidationResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_uri_format_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_uri_format_request_body) | **post** /requestBody/postUriFormatRequestBody | +*ContentTypeJsonApi* | [**post_uri_format_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_uri_format_response_body_for_content_types) | **post** /responseBody/postUriFormatResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_uri_reference_format_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_uri_reference_format_request_body) | **post** /requestBody/postUriReferenceFormatRequestBody | +*ContentTypeJsonApi* | [**post_uri_reference_format_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_uri_reference_format_response_body_for_content_types) | **post** /responseBody/postUriReferenceFormatResponseBodyForContentTypes | +*ContentTypeJsonApi* | [**post_uri_template_format_request_body**](docs/apis/tags/ContentTypeJsonApi.md#post_uri_template_format_request_body) | **post** /requestBody/postUriTemplateFormatRequestBody | +*ContentTypeJsonApi* | [**post_uri_template_format_response_body_for_content_types**](docs/apis/tags/ContentTypeJsonApi.md#post_uri_template_format_response_body_for_content_types) | **post** /responseBody/postUriTemplateFormatResponseBodyForContentTypes | +*DefaultApi* | [**post_invalid_string_value_for_default_request_body**](docs/apis/tags/DefaultApi.md#post_invalid_string_value_for_default_request_body) | **post** /requestBody/postInvalidStringValueForDefaultRequestBody | +*DefaultApi* | [**post_invalid_string_value_for_default_response_body_for_content_types**](docs/apis/tags/DefaultApi.md#post_invalid_string_value_for_default_response_body_for_content_types) | **post** /responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes | +*DefaultApi* | [**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body**](docs/apis/tags/DefaultApi.md#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body) | **post** /requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody | +*DefaultApi* | [**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types**](docs/apis/tags/DefaultApi.md#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types) | **post** /responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes | +*EnumApi* | [**post_enum_with0_does_not_match_false_request_body**](docs/apis/tags/EnumApi.md#post_enum_with0_does_not_match_false_request_body) | **post** /requestBody/postEnumWith0DoesNotMatchFalseRequestBody | +*EnumApi* | [**post_enum_with0_does_not_match_false_response_body_for_content_types**](docs/apis/tags/EnumApi.md#post_enum_with0_does_not_match_false_response_body_for_content_types) | **post** /responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes | +*EnumApi* | [**post_enum_with1_does_not_match_true_request_body**](docs/apis/tags/EnumApi.md#post_enum_with1_does_not_match_true_request_body) | **post** /requestBody/postEnumWith1DoesNotMatchTrueRequestBody | +*EnumApi* | [**post_enum_with1_does_not_match_true_response_body_for_content_types**](docs/apis/tags/EnumApi.md#post_enum_with1_does_not_match_true_response_body_for_content_types) | **post** /responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes | +*EnumApi* | [**post_enum_with_escaped_characters_request_body**](docs/apis/tags/EnumApi.md#post_enum_with_escaped_characters_request_body) | **post** /requestBody/postEnumWithEscapedCharactersRequestBody | +*EnumApi* | [**post_enum_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/EnumApi.md#post_enum_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes | +*EnumApi* | [**post_enum_with_false_does_not_match0_request_body**](docs/apis/tags/EnumApi.md#post_enum_with_false_does_not_match0_request_body) | **post** /requestBody/postEnumWithFalseDoesNotMatch0RequestBody | +*EnumApi* | [**post_enum_with_false_does_not_match0_response_body_for_content_types**](docs/apis/tags/EnumApi.md#post_enum_with_false_does_not_match0_response_body_for_content_types) | **post** /responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes | +*EnumApi* | [**post_enum_with_true_does_not_match1_request_body**](docs/apis/tags/EnumApi.md#post_enum_with_true_does_not_match1_request_body) | **post** /requestBody/postEnumWithTrueDoesNotMatch1RequestBody | +*EnumApi* | [**post_enum_with_true_does_not_match1_response_body_for_content_types**](docs/apis/tags/EnumApi.md#post_enum_with_true_does_not_match1_response_body_for_content_types) | **post** /responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes | +*EnumApi* | [**post_enums_in_properties_request_body**](docs/apis/tags/EnumApi.md#post_enums_in_properties_request_body) | **post** /requestBody/postEnumsInPropertiesRequestBody | +*EnumApi* | [**post_enums_in_properties_response_body_for_content_types**](docs/apis/tags/EnumApi.md#post_enums_in_properties_response_body_for_content_types) | **post** /responseBody/postEnumsInPropertiesResponseBodyForContentTypes | +*EnumApi* | [**post_nul_characters_in_strings_request_body**](docs/apis/tags/EnumApi.md#post_nul_characters_in_strings_request_body) | **post** /requestBody/postNulCharactersInStringsRequestBody | +*EnumApi* | [**post_nul_characters_in_strings_response_body_for_content_types**](docs/apis/tags/EnumApi.md#post_nul_characters_in_strings_response_body_for_content_types) | **post** /responseBody/postNulCharactersInStringsResponseBodyForContentTypes | +*EnumApi* | [**post_simple_enum_validation_request_body**](docs/apis/tags/EnumApi.md#post_simple_enum_validation_request_body) | **post** /requestBody/postSimpleEnumValidationRequestBody | +*EnumApi* | [**post_simple_enum_validation_response_body_for_content_types**](docs/apis/tags/EnumApi.md#post_simple_enum_validation_response_body_for_content_types) | **post** /responseBody/postSimpleEnumValidationResponseBodyForContentTypes | +*FormatApi* | [**post_date_time_format_request_body**](docs/apis/tags/FormatApi.md#post_date_time_format_request_body) | **post** /requestBody/postDateTimeFormatRequestBody | +*FormatApi* | [**post_date_time_format_response_body_for_content_types**](docs/apis/tags/FormatApi.md#post_date_time_format_response_body_for_content_types) | **post** /responseBody/postDateTimeFormatResponseBodyForContentTypes | +*FormatApi* | [**post_email_format_request_body**](docs/apis/tags/FormatApi.md#post_email_format_request_body) | **post** /requestBody/postEmailFormatRequestBody | +*FormatApi* | [**post_email_format_response_body_for_content_types**](docs/apis/tags/FormatApi.md#post_email_format_response_body_for_content_types) | **post** /responseBody/postEmailFormatResponseBodyForContentTypes | +*FormatApi* | [**post_hostname_format_request_body**](docs/apis/tags/FormatApi.md#post_hostname_format_request_body) | **post** /requestBody/postHostnameFormatRequestBody | +*FormatApi* | [**post_hostname_format_response_body_for_content_types**](docs/apis/tags/FormatApi.md#post_hostname_format_response_body_for_content_types) | **post** /responseBody/postHostnameFormatResponseBodyForContentTypes | +*FormatApi* | [**post_ipv4_format_request_body**](docs/apis/tags/FormatApi.md#post_ipv4_format_request_body) | **post** /requestBody/postIpv4FormatRequestBody | +*FormatApi* | [**post_ipv4_format_response_body_for_content_types**](docs/apis/tags/FormatApi.md#post_ipv4_format_response_body_for_content_types) | **post** /responseBody/postIpv4FormatResponseBodyForContentTypes | +*FormatApi* | [**post_ipv6_format_request_body**](docs/apis/tags/FormatApi.md#post_ipv6_format_request_body) | **post** /requestBody/postIpv6FormatRequestBody | +*FormatApi* | [**post_ipv6_format_response_body_for_content_types**](docs/apis/tags/FormatApi.md#post_ipv6_format_response_body_for_content_types) | **post** /responseBody/postIpv6FormatResponseBodyForContentTypes | +*FormatApi* | [**post_json_pointer_format_request_body**](docs/apis/tags/FormatApi.md#post_json_pointer_format_request_body) | **post** /requestBody/postJsonPointerFormatRequestBody | +*FormatApi* | [**post_json_pointer_format_response_body_for_content_types**](docs/apis/tags/FormatApi.md#post_json_pointer_format_response_body_for_content_types) | **post** /responseBody/postJsonPointerFormatResponseBodyForContentTypes | +*FormatApi* | [**post_uri_format_request_body**](docs/apis/tags/FormatApi.md#post_uri_format_request_body) | **post** /requestBody/postUriFormatRequestBody | +*FormatApi* | [**post_uri_format_response_body_for_content_types**](docs/apis/tags/FormatApi.md#post_uri_format_response_body_for_content_types) | **post** /responseBody/postUriFormatResponseBodyForContentTypes | +*FormatApi* | [**post_uri_reference_format_request_body**](docs/apis/tags/FormatApi.md#post_uri_reference_format_request_body) | **post** /requestBody/postUriReferenceFormatRequestBody | +*FormatApi* | [**post_uri_reference_format_response_body_for_content_types**](docs/apis/tags/FormatApi.md#post_uri_reference_format_response_body_for_content_types) | **post** /responseBody/postUriReferenceFormatResponseBodyForContentTypes | +*FormatApi* | [**post_uri_template_format_request_body**](docs/apis/tags/FormatApi.md#post_uri_template_format_request_body) | **post** /requestBody/postUriTemplateFormatRequestBody | +*FormatApi* | [**post_uri_template_format_response_body_for_content_types**](docs/apis/tags/FormatApi.md#post_uri_template_format_response_body_for_content_types) | **post** /responseBody/postUriTemplateFormatResponseBodyForContentTypes | +*ItemsApi* | [**post_nested_items_request_body**](docs/apis/tags/ItemsApi.md#post_nested_items_request_body) | **post** /requestBody/postNestedItemsRequestBody | +*ItemsApi* | [**post_nested_items_response_body_for_content_types**](docs/apis/tags/ItemsApi.md#post_nested_items_response_body_for_content_types) | **post** /responseBody/postNestedItemsResponseBodyForContentTypes | +*MaxItemsApi* | [**post_maxitems_validation_request_body**](docs/apis/tags/MaxItemsApi.md#post_maxitems_validation_request_body) | **post** /requestBody/postMaxitemsValidationRequestBody | +*MaxItemsApi* | [**post_maxitems_validation_response_body_for_content_types**](docs/apis/tags/MaxItemsApi.md#post_maxitems_validation_response_body_for_content_types) | **post** /responseBody/postMaxitemsValidationResponseBodyForContentTypes | +*MaxLengthApi* | [**post_maxlength_validation_request_body**](docs/apis/tags/MaxLengthApi.md#post_maxlength_validation_request_body) | **post** /requestBody/postMaxlengthValidationRequestBody | +*MaxLengthApi* | [**post_maxlength_validation_response_body_for_content_types**](docs/apis/tags/MaxLengthApi.md#post_maxlength_validation_response_body_for_content_types) | **post** /responseBody/postMaxlengthValidationResponseBodyForContentTypes | +*MaxPropertiesApi* | [**post_maxproperties0_means_the_object_is_empty_request_body**](docs/apis/tags/MaxPropertiesApi.md#post_maxproperties0_means_the_object_is_empty_request_body) | **post** /requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody | +*MaxPropertiesApi* | [**post_maxproperties0_means_the_object_is_empty_response_body_for_content_types**](docs/apis/tags/MaxPropertiesApi.md#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types) | **post** /responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes | +*MaxPropertiesApi* | [**post_maxproperties_validation_request_body**](docs/apis/tags/MaxPropertiesApi.md#post_maxproperties_validation_request_body) | **post** /requestBody/postMaxpropertiesValidationRequestBody | +*MaxPropertiesApi* | [**post_maxproperties_validation_response_body_for_content_types**](docs/apis/tags/MaxPropertiesApi.md#post_maxproperties_validation_response_body_for_content_types) | **post** /responseBody/postMaxpropertiesValidationResponseBodyForContentTypes | +*MaximumApi* | [**post_maximum_validation_request_body**](docs/apis/tags/MaximumApi.md#post_maximum_validation_request_body) | **post** /requestBody/postMaximumValidationRequestBody | +*MaximumApi* | [**post_maximum_validation_response_body_for_content_types**](docs/apis/tags/MaximumApi.md#post_maximum_validation_response_body_for_content_types) | **post** /responseBody/postMaximumValidationResponseBodyForContentTypes | +*MaximumApi* | [**post_maximum_validation_with_unsigned_integer_request_body**](docs/apis/tags/MaximumApi.md#post_maximum_validation_with_unsigned_integer_request_body) | **post** /requestBody/postMaximumValidationWithUnsignedIntegerRequestBody | +*MaximumApi* | [**post_maximum_validation_with_unsigned_integer_response_body_for_content_types**](docs/apis/tags/MaximumApi.md#post_maximum_validation_with_unsigned_integer_response_body_for_content_types) | **post** /responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes | +*MinItemsApi* | [**post_minitems_validation_request_body**](docs/apis/tags/MinItemsApi.md#post_minitems_validation_request_body) | **post** /requestBody/postMinitemsValidationRequestBody | +*MinItemsApi* | [**post_minitems_validation_response_body_for_content_types**](docs/apis/tags/MinItemsApi.md#post_minitems_validation_response_body_for_content_types) | **post** /responseBody/postMinitemsValidationResponseBodyForContentTypes | +*MinLengthApi* | [**post_minlength_validation_request_body**](docs/apis/tags/MinLengthApi.md#post_minlength_validation_request_body) | **post** /requestBody/postMinlengthValidationRequestBody | +*MinLengthApi* | [**post_minlength_validation_response_body_for_content_types**](docs/apis/tags/MinLengthApi.md#post_minlength_validation_response_body_for_content_types) | **post** /responseBody/postMinlengthValidationResponseBodyForContentTypes | +*MinPropertiesApi* | [**post_minproperties_validation_request_body**](docs/apis/tags/MinPropertiesApi.md#post_minproperties_validation_request_body) | **post** /requestBody/postMinpropertiesValidationRequestBody | +*MinPropertiesApi* | [**post_minproperties_validation_response_body_for_content_types**](docs/apis/tags/MinPropertiesApi.md#post_minproperties_validation_response_body_for_content_types) | **post** /responseBody/postMinpropertiesValidationResponseBodyForContentTypes | +*MinimumApi* | [**post_minimum_validation_request_body**](docs/apis/tags/MinimumApi.md#post_minimum_validation_request_body) | **post** /requestBody/postMinimumValidationRequestBody | +*MinimumApi* | [**post_minimum_validation_response_body_for_content_types**](docs/apis/tags/MinimumApi.md#post_minimum_validation_response_body_for_content_types) | **post** /responseBody/postMinimumValidationResponseBodyForContentTypes | +*MinimumApi* | [**post_minimum_validation_with_signed_integer_request_body**](docs/apis/tags/MinimumApi.md#post_minimum_validation_with_signed_integer_request_body) | **post** /requestBody/postMinimumValidationWithSignedIntegerRequestBody | +*MinimumApi* | [**post_minimum_validation_with_signed_integer_response_body_for_content_types**](docs/apis/tags/MinimumApi.md#post_minimum_validation_with_signed_integer_response_body_for_content_types) | **post** /responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes | +*MultipleOfApi* | [**post_by_int_request_body**](docs/apis/tags/MultipleOfApi.md#post_by_int_request_body) | **post** /requestBody/postByIntRequestBody | +*MultipleOfApi* | [**post_by_int_response_body_for_content_types**](docs/apis/tags/MultipleOfApi.md#post_by_int_response_body_for_content_types) | **post** /responseBody/postByIntResponseBodyForContentTypes | +*MultipleOfApi* | [**post_by_number_request_body**](docs/apis/tags/MultipleOfApi.md#post_by_number_request_body) | **post** /requestBody/postByNumberRequestBody | +*MultipleOfApi* | [**post_by_number_response_body_for_content_types**](docs/apis/tags/MultipleOfApi.md#post_by_number_response_body_for_content_types) | **post** /responseBody/postByNumberResponseBodyForContentTypes | +*MultipleOfApi* | [**post_by_small_number_request_body**](docs/apis/tags/MultipleOfApi.md#post_by_small_number_request_body) | **post** /requestBody/postBySmallNumberRequestBody | +*MultipleOfApi* | [**post_by_small_number_response_body_for_content_types**](docs/apis/tags/MultipleOfApi.md#post_by_small_number_response_body_for_content_types) | **post** /responseBody/postBySmallNumberResponseBodyForContentTypes | +*MultipleOfApi* | [**post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body**](docs/apis/tags/MultipleOfApi.md#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body) | **post** /requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody | +*MultipleOfApi* | [**post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types**](docs/apis/tags/MultipleOfApi.md#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types) | **post** /responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes | +*ModelNotApi* | [**post_forbidden_property_request_body**](docs/apis/tags/ModelNotApi.md#post_forbidden_property_request_body) | **post** /requestBody/postForbiddenPropertyRequestBody | +*ModelNotApi* | [**post_forbidden_property_response_body_for_content_types**](docs/apis/tags/ModelNotApi.md#post_forbidden_property_response_body_for_content_types) | **post** /responseBody/postForbiddenPropertyResponseBodyForContentTypes | +*ModelNotApi* | [**post_not_more_complex_schema_request_body**](docs/apis/tags/ModelNotApi.md#post_not_more_complex_schema_request_body) | **post** /requestBody/postNotMoreComplexSchemaRequestBody | +*ModelNotApi* | [**post_not_more_complex_schema_response_body_for_content_types**](docs/apis/tags/ModelNotApi.md#post_not_more_complex_schema_response_body_for_content_types) | **post** /responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes | +*ModelNotApi* | [**post_not_request_body**](docs/apis/tags/ModelNotApi.md#post_not_request_body) | **post** /requestBody/postNotRequestBody | +*ModelNotApi* | [**post_not_response_body_for_content_types**](docs/apis/tags/ModelNotApi.md#post_not_response_body_for_content_types) | **post** /responseBody/postNotResponseBodyForContentTypes | +*OneOfApi* | [**post_nested_oneof_to_check_validation_semantics_request_body**](docs/apis/tags/OneOfApi.md#post_nested_oneof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedOneofToCheckValidationSemanticsRequestBody | +*OneOfApi* | [**post_nested_oneof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/OneOfApi.md#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes | +*OneOfApi* | [**post_oneof_complex_types_request_body**](docs/apis/tags/OneOfApi.md#post_oneof_complex_types_request_body) | **post** /requestBody/postOneofComplexTypesRequestBody | +*OneOfApi* | [**post_oneof_complex_types_response_body_for_content_types**](docs/apis/tags/OneOfApi.md#post_oneof_complex_types_response_body_for_content_types) | **post** /responseBody/postOneofComplexTypesResponseBodyForContentTypes | +*OneOfApi* | [**post_oneof_request_body**](docs/apis/tags/OneOfApi.md#post_oneof_request_body) | **post** /requestBody/postOneofRequestBody | +*OneOfApi* | [**post_oneof_response_body_for_content_types**](docs/apis/tags/OneOfApi.md#post_oneof_response_body_for_content_types) | **post** /responseBody/postOneofResponseBodyForContentTypes | +*OneOfApi* | [**post_oneof_with_base_schema_request_body**](docs/apis/tags/OneOfApi.md#post_oneof_with_base_schema_request_body) | **post** /requestBody/postOneofWithBaseSchemaRequestBody | +*OneOfApi* | [**post_oneof_with_base_schema_response_body_for_content_types**](docs/apis/tags/OneOfApi.md#post_oneof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes | +*OneOfApi* | [**post_oneof_with_empty_schema_request_body**](docs/apis/tags/OneOfApi.md#post_oneof_with_empty_schema_request_body) | **post** /requestBody/postOneofWithEmptySchemaRequestBody | +*OneOfApi* | [**post_oneof_with_empty_schema_response_body_for_content_types**](docs/apis/tags/OneOfApi.md#post_oneof_with_empty_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes | +*OneOfApi* | [**post_oneof_with_required_request_body**](docs/apis/tags/OneOfApi.md#post_oneof_with_required_request_body) | **post** /requestBody/postOneofWithRequiredRequestBody | +*OneOfApi* | [**post_oneof_with_required_response_body_for_content_types**](docs/apis/tags/OneOfApi.md#post_oneof_with_required_response_body_for_content_types) | **post** /responseBody/postOneofWithRequiredResponseBodyForContentTypes | +*OperationRequestBodyApi* | [**post_additionalproperties_allows_a_schema_which_should_validate_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_additionalproperties_allows_a_schema_which_should_validate_request_body) | **post** /requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody | +*OperationRequestBodyApi* | [**post_additionalproperties_are_allowed_by_default_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_additionalproperties_are_allowed_by_default_request_body) | **post** /requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody | +*OperationRequestBodyApi* | [**post_additionalproperties_can_exist_by_itself_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_additionalproperties_can_exist_by_itself_request_body) | **post** /requestBody/postAdditionalpropertiesCanExistByItselfRequestBody | +*OperationRequestBodyApi* | [**post_additionalproperties_should_not_look_in_applicators_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_additionalproperties_should_not_look_in_applicators_request_body) | **post** /requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody | +*OperationRequestBodyApi* | [**post_allof_combined_with_anyof_oneof_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_allof_combined_with_anyof_oneof_request_body) | **post** /requestBody/postAllofCombinedWithAnyofOneofRequestBody | +*OperationRequestBodyApi* | [**post_allof_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_allof_request_body) | **post** /requestBody/postAllofRequestBody | +*OperationRequestBodyApi* | [**post_allof_simple_types_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_allof_simple_types_request_body) | **post** /requestBody/postAllofSimpleTypesRequestBody | +*OperationRequestBodyApi* | [**post_allof_with_base_schema_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_allof_with_base_schema_request_body) | **post** /requestBody/postAllofWithBaseSchemaRequestBody | +*OperationRequestBodyApi* | [**post_allof_with_one_empty_schema_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_allof_with_one_empty_schema_request_body) | **post** /requestBody/postAllofWithOneEmptySchemaRequestBody | +*OperationRequestBodyApi* | [**post_allof_with_the_first_empty_schema_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_allof_with_the_first_empty_schema_request_body) | **post** /requestBody/postAllofWithTheFirstEmptySchemaRequestBody | +*OperationRequestBodyApi* | [**post_allof_with_the_last_empty_schema_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_allof_with_the_last_empty_schema_request_body) | **post** /requestBody/postAllofWithTheLastEmptySchemaRequestBody | +*OperationRequestBodyApi* | [**post_allof_with_two_empty_schemas_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_allof_with_two_empty_schemas_request_body) | **post** /requestBody/postAllofWithTwoEmptySchemasRequestBody | +*OperationRequestBodyApi* | [**post_anyof_complex_types_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_anyof_complex_types_request_body) | **post** /requestBody/postAnyofComplexTypesRequestBody | +*OperationRequestBodyApi* | [**post_anyof_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_anyof_request_body) | **post** /requestBody/postAnyofRequestBody | +*OperationRequestBodyApi* | [**post_anyof_with_base_schema_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_anyof_with_base_schema_request_body) | **post** /requestBody/postAnyofWithBaseSchemaRequestBody | +*OperationRequestBodyApi* | [**post_anyof_with_one_empty_schema_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_anyof_with_one_empty_schema_request_body) | **post** /requestBody/postAnyofWithOneEmptySchemaRequestBody | +*OperationRequestBodyApi* | [**post_array_type_matches_arrays_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_array_type_matches_arrays_request_body) | **post** /requestBody/postArrayTypeMatchesArraysRequestBody | +*OperationRequestBodyApi* | [**post_boolean_type_matches_booleans_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_boolean_type_matches_booleans_request_body) | **post** /requestBody/postBooleanTypeMatchesBooleansRequestBody | +*OperationRequestBodyApi* | [**post_by_int_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_by_int_request_body) | **post** /requestBody/postByIntRequestBody | +*OperationRequestBodyApi* | [**post_by_number_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_by_number_request_body) | **post** /requestBody/postByNumberRequestBody | +*OperationRequestBodyApi* | [**post_by_small_number_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_by_small_number_request_body) | **post** /requestBody/postBySmallNumberRequestBody | +*OperationRequestBodyApi* | [**post_date_time_format_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_date_time_format_request_body) | **post** /requestBody/postDateTimeFormatRequestBody | +*OperationRequestBodyApi* | [**post_email_format_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_email_format_request_body) | **post** /requestBody/postEmailFormatRequestBody | +*OperationRequestBodyApi* | [**post_enum_with0_does_not_match_false_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_enum_with0_does_not_match_false_request_body) | **post** /requestBody/postEnumWith0DoesNotMatchFalseRequestBody | +*OperationRequestBodyApi* | [**post_enum_with1_does_not_match_true_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_enum_with1_does_not_match_true_request_body) | **post** /requestBody/postEnumWith1DoesNotMatchTrueRequestBody | +*OperationRequestBodyApi* | [**post_enum_with_escaped_characters_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_enum_with_escaped_characters_request_body) | **post** /requestBody/postEnumWithEscapedCharactersRequestBody | +*OperationRequestBodyApi* | [**post_enum_with_false_does_not_match0_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_enum_with_false_does_not_match0_request_body) | **post** /requestBody/postEnumWithFalseDoesNotMatch0RequestBody | +*OperationRequestBodyApi* | [**post_enum_with_true_does_not_match1_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_enum_with_true_does_not_match1_request_body) | **post** /requestBody/postEnumWithTrueDoesNotMatch1RequestBody | +*OperationRequestBodyApi* | [**post_enums_in_properties_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_enums_in_properties_request_body) | **post** /requestBody/postEnumsInPropertiesRequestBody | +*OperationRequestBodyApi* | [**post_forbidden_property_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_forbidden_property_request_body) | **post** /requestBody/postForbiddenPropertyRequestBody | +*OperationRequestBodyApi* | [**post_hostname_format_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_hostname_format_request_body) | **post** /requestBody/postHostnameFormatRequestBody | +*OperationRequestBodyApi* | [**post_integer_type_matches_integers_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_integer_type_matches_integers_request_body) | **post** /requestBody/postIntegerTypeMatchesIntegersRequestBody | +*OperationRequestBodyApi* | [**post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body) | **post** /requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody | +*OperationRequestBodyApi* | [**post_invalid_string_value_for_default_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_invalid_string_value_for_default_request_body) | **post** /requestBody/postInvalidStringValueForDefaultRequestBody | +*OperationRequestBodyApi* | [**post_ipv4_format_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_ipv4_format_request_body) | **post** /requestBody/postIpv4FormatRequestBody | +*OperationRequestBodyApi* | [**post_ipv6_format_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_ipv6_format_request_body) | **post** /requestBody/postIpv6FormatRequestBody | +*OperationRequestBodyApi* | [**post_json_pointer_format_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_json_pointer_format_request_body) | **post** /requestBody/postJsonPointerFormatRequestBody | +*OperationRequestBodyApi* | [**post_maximum_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_maximum_validation_request_body) | **post** /requestBody/postMaximumValidationRequestBody | +*OperationRequestBodyApi* | [**post_maximum_validation_with_unsigned_integer_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_maximum_validation_with_unsigned_integer_request_body) | **post** /requestBody/postMaximumValidationWithUnsignedIntegerRequestBody | +*OperationRequestBodyApi* | [**post_maxitems_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_maxitems_validation_request_body) | **post** /requestBody/postMaxitemsValidationRequestBody | +*OperationRequestBodyApi* | [**post_maxlength_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_maxlength_validation_request_body) | **post** /requestBody/postMaxlengthValidationRequestBody | +*OperationRequestBodyApi* | [**post_maxproperties0_means_the_object_is_empty_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_maxproperties0_means_the_object_is_empty_request_body) | **post** /requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody | +*OperationRequestBodyApi* | [**post_maxproperties_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_maxproperties_validation_request_body) | **post** /requestBody/postMaxpropertiesValidationRequestBody | +*OperationRequestBodyApi* | [**post_minimum_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_minimum_validation_request_body) | **post** /requestBody/postMinimumValidationRequestBody | +*OperationRequestBodyApi* | [**post_minimum_validation_with_signed_integer_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_minimum_validation_with_signed_integer_request_body) | **post** /requestBody/postMinimumValidationWithSignedIntegerRequestBody | +*OperationRequestBodyApi* | [**post_minitems_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_minitems_validation_request_body) | **post** /requestBody/postMinitemsValidationRequestBody | +*OperationRequestBodyApi* | [**post_minlength_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_minlength_validation_request_body) | **post** /requestBody/postMinlengthValidationRequestBody | +*OperationRequestBodyApi* | [**post_minproperties_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_minproperties_validation_request_body) | **post** /requestBody/postMinpropertiesValidationRequestBody | +*OperationRequestBodyApi* | [**post_nested_allof_to_check_validation_semantics_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_nested_allof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAllofToCheckValidationSemanticsRequestBody | +*OperationRequestBodyApi* | [**post_nested_anyof_to_check_validation_semantics_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_nested_anyof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody | +*OperationRequestBodyApi* | [**post_nested_items_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_nested_items_request_body) | **post** /requestBody/postNestedItemsRequestBody | +*OperationRequestBodyApi* | [**post_nested_oneof_to_check_validation_semantics_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_nested_oneof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedOneofToCheckValidationSemanticsRequestBody | +*OperationRequestBodyApi* | [**post_not_more_complex_schema_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_not_more_complex_schema_request_body) | **post** /requestBody/postNotMoreComplexSchemaRequestBody | +*OperationRequestBodyApi* | [**post_not_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_not_request_body) | **post** /requestBody/postNotRequestBody | +*OperationRequestBodyApi* | [**post_nul_characters_in_strings_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_nul_characters_in_strings_request_body) | **post** /requestBody/postNulCharactersInStringsRequestBody | +*OperationRequestBodyApi* | [**post_null_type_matches_only_the_null_object_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_null_type_matches_only_the_null_object_request_body) | **post** /requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody | +*OperationRequestBodyApi* | [**post_number_type_matches_numbers_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_number_type_matches_numbers_request_body) | **post** /requestBody/postNumberTypeMatchesNumbersRequestBody | +*OperationRequestBodyApi* | [**post_object_properties_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_object_properties_validation_request_body) | **post** /requestBody/postObjectPropertiesValidationRequestBody | +*OperationRequestBodyApi* | [**post_object_type_matches_objects_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_object_type_matches_objects_request_body) | **post** /requestBody/postObjectTypeMatchesObjectsRequestBody | +*OperationRequestBodyApi* | [**post_oneof_complex_types_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_oneof_complex_types_request_body) | **post** /requestBody/postOneofComplexTypesRequestBody | +*OperationRequestBodyApi* | [**post_oneof_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_oneof_request_body) | **post** /requestBody/postOneofRequestBody | +*OperationRequestBodyApi* | [**post_oneof_with_base_schema_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_oneof_with_base_schema_request_body) | **post** /requestBody/postOneofWithBaseSchemaRequestBody | +*OperationRequestBodyApi* | [**post_oneof_with_empty_schema_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_oneof_with_empty_schema_request_body) | **post** /requestBody/postOneofWithEmptySchemaRequestBody | +*OperationRequestBodyApi* | [**post_oneof_with_required_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_oneof_with_required_request_body) | **post** /requestBody/postOneofWithRequiredRequestBody | +*OperationRequestBodyApi* | [**post_pattern_is_not_anchored_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_pattern_is_not_anchored_request_body) | **post** /requestBody/postPatternIsNotAnchoredRequestBody | +*OperationRequestBodyApi* | [**post_pattern_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_pattern_validation_request_body) | **post** /requestBody/postPatternValidationRequestBody | +*OperationRequestBodyApi* | [**post_properties_with_escaped_characters_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_properties_with_escaped_characters_request_body) | **post** /requestBody/postPropertiesWithEscapedCharactersRequestBody | +*OperationRequestBodyApi* | [**post_property_named_ref_that_is_not_a_reference_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_property_named_ref_that_is_not_a_reference_request_body) | **post** /requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody | +*OperationRequestBodyApi* | [**post_ref_in_additionalproperties_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_ref_in_additionalproperties_request_body) | **post** /requestBody/postRefInAdditionalpropertiesRequestBody | +*OperationRequestBodyApi* | [**post_ref_in_allof_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_ref_in_allof_request_body) | **post** /requestBody/postRefInAllofRequestBody | +*OperationRequestBodyApi* | [**post_ref_in_anyof_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_ref_in_anyof_request_body) | **post** /requestBody/postRefInAnyofRequestBody | +*OperationRequestBodyApi* | [**post_ref_in_items_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_ref_in_items_request_body) | **post** /requestBody/postRefInItemsRequestBody | +*OperationRequestBodyApi* | [**post_ref_in_not_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_ref_in_not_request_body) | **post** /requestBody/postRefInNotRequestBody | +*OperationRequestBodyApi* | [**post_ref_in_oneof_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_ref_in_oneof_request_body) | **post** /requestBody/postRefInOneofRequestBody | +*OperationRequestBodyApi* | [**post_ref_in_property_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_ref_in_property_request_body) | **post** /requestBody/postRefInPropertyRequestBody | +*OperationRequestBodyApi* | [**post_required_default_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_required_default_validation_request_body) | **post** /requestBody/postRequiredDefaultValidationRequestBody | +*OperationRequestBodyApi* | [**post_required_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_required_validation_request_body) | **post** /requestBody/postRequiredValidationRequestBody | +*OperationRequestBodyApi* | [**post_required_with_empty_array_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_required_with_empty_array_request_body) | **post** /requestBody/postRequiredWithEmptyArrayRequestBody | +*OperationRequestBodyApi* | [**post_required_with_escaped_characters_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_required_with_escaped_characters_request_body) | **post** /requestBody/postRequiredWithEscapedCharactersRequestBody | +*OperationRequestBodyApi* | [**post_simple_enum_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_simple_enum_validation_request_body) | **post** /requestBody/postSimpleEnumValidationRequestBody | +*OperationRequestBodyApi* | [**post_string_type_matches_strings_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_string_type_matches_strings_request_body) | **post** /requestBody/postStringTypeMatchesStringsRequestBody | +*OperationRequestBodyApi* | [**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body) | **post** /requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody | +*OperationRequestBodyApi* | [**post_uniqueitems_false_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_uniqueitems_false_validation_request_body) | **post** /requestBody/postUniqueitemsFalseValidationRequestBody | +*OperationRequestBodyApi* | [**post_uniqueitems_validation_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_uniqueitems_validation_request_body) | **post** /requestBody/postUniqueitemsValidationRequestBody | +*OperationRequestBodyApi* | [**post_uri_format_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_uri_format_request_body) | **post** /requestBody/postUriFormatRequestBody | +*OperationRequestBodyApi* | [**post_uri_reference_format_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_uri_reference_format_request_body) | **post** /requestBody/postUriReferenceFormatRequestBody | +*OperationRequestBodyApi* | [**post_uri_template_format_request_body**](docs/apis/tags/OperationRequestBodyApi.md#post_uri_template_format_request_body) | **post** /requestBody/postUriTemplateFormatRequestBody | +*PathPostApi* | [**post_additionalproperties_allows_a_schema_which_should_validate_request_body**](docs/apis/tags/PathPostApi.md#post_additionalproperties_allows_a_schema_which_should_validate_request_body) | **post** /requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody | +*PathPostApi* | [**post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes | +*PathPostApi* | [**post_additionalproperties_are_allowed_by_default_request_body**](docs/apis/tags/PathPostApi.md#post_additionalproperties_are_allowed_by_default_request_body) | **post** /requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody | +*PathPostApi* | [**post_additionalproperties_are_allowed_by_default_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_additionalproperties_are_allowed_by_default_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes | +*PathPostApi* | [**post_additionalproperties_can_exist_by_itself_request_body**](docs/apis/tags/PathPostApi.md#post_additionalproperties_can_exist_by_itself_request_body) | **post** /requestBody/postAdditionalpropertiesCanExistByItselfRequestBody | +*PathPostApi* | [**post_additionalproperties_can_exist_by_itself_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_additionalproperties_can_exist_by_itself_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes | +*PathPostApi* | [**post_additionalproperties_should_not_look_in_applicators_request_body**](docs/apis/tags/PathPostApi.md#post_additionalproperties_should_not_look_in_applicators_request_body) | **post** /requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody | +*PathPostApi* | [**post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes | +*PathPostApi* | [**post_allof_combined_with_anyof_oneof_request_body**](docs/apis/tags/PathPostApi.md#post_allof_combined_with_anyof_oneof_request_body) | **post** /requestBody/postAllofCombinedWithAnyofOneofRequestBody | +*PathPostApi* | [**post_allof_combined_with_anyof_oneof_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_allof_combined_with_anyof_oneof_response_body_for_content_types) | **post** /responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes | +*PathPostApi* | [**post_allof_request_body**](docs/apis/tags/PathPostApi.md#post_allof_request_body) | **post** /requestBody/postAllofRequestBody | +*PathPostApi* | [**post_allof_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_allof_response_body_for_content_types) | **post** /responseBody/postAllofResponseBodyForContentTypes | +*PathPostApi* | [**post_allof_simple_types_request_body**](docs/apis/tags/PathPostApi.md#post_allof_simple_types_request_body) | **post** /requestBody/postAllofSimpleTypesRequestBody | +*PathPostApi* | [**post_allof_simple_types_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_allof_simple_types_response_body_for_content_types) | **post** /responseBody/postAllofSimpleTypesResponseBodyForContentTypes | +*PathPostApi* | [**post_allof_with_base_schema_request_body**](docs/apis/tags/PathPostApi.md#post_allof_with_base_schema_request_body) | **post** /requestBody/postAllofWithBaseSchemaRequestBody | +*PathPostApi* | [**post_allof_with_base_schema_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_allof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes | +*PathPostApi* | [**post_allof_with_one_empty_schema_request_body**](docs/apis/tags/PathPostApi.md#post_allof_with_one_empty_schema_request_body) | **post** /requestBody/postAllofWithOneEmptySchemaRequestBody | +*PathPostApi* | [**post_allof_with_one_empty_schema_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_allof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes | +*PathPostApi* | [**post_allof_with_the_first_empty_schema_request_body**](docs/apis/tags/PathPostApi.md#post_allof_with_the_first_empty_schema_request_body) | **post** /requestBody/postAllofWithTheFirstEmptySchemaRequestBody | +*PathPostApi* | [**post_allof_with_the_first_empty_schema_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_allof_with_the_first_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes | +*PathPostApi* | [**post_allof_with_the_last_empty_schema_request_body**](docs/apis/tags/PathPostApi.md#post_allof_with_the_last_empty_schema_request_body) | **post** /requestBody/postAllofWithTheLastEmptySchemaRequestBody | +*PathPostApi* | [**post_allof_with_the_last_empty_schema_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_allof_with_the_last_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes | +*PathPostApi* | [**post_allof_with_two_empty_schemas_request_body**](docs/apis/tags/PathPostApi.md#post_allof_with_two_empty_schemas_request_body) | **post** /requestBody/postAllofWithTwoEmptySchemasRequestBody | +*PathPostApi* | [**post_allof_with_two_empty_schemas_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_allof_with_two_empty_schemas_response_body_for_content_types) | **post** /responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes | +*PathPostApi* | [**post_anyof_complex_types_request_body**](docs/apis/tags/PathPostApi.md#post_anyof_complex_types_request_body) | **post** /requestBody/postAnyofComplexTypesRequestBody | +*PathPostApi* | [**post_anyof_complex_types_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_anyof_complex_types_response_body_for_content_types) | **post** /responseBody/postAnyofComplexTypesResponseBodyForContentTypes | +*PathPostApi* | [**post_anyof_request_body**](docs/apis/tags/PathPostApi.md#post_anyof_request_body) | **post** /requestBody/postAnyofRequestBody | +*PathPostApi* | [**post_anyof_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_anyof_response_body_for_content_types) | **post** /responseBody/postAnyofResponseBodyForContentTypes | +*PathPostApi* | [**post_anyof_with_base_schema_request_body**](docs/apis/tags/PathPostApi.md#post_anyof_with_base_schema_request_body) | **post** /requestBody/postAnyofWithBaseSchemaRequestBody | +*PathPostApi* | [**post_anyof_with_base_schema_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_anyof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes | +*PathPostApi* | [**post_anyof_with_one_empty_schema_request_body**](docs/apis/tags/PathPostApi.md#post_anyof_with_one_empty_schema_request_body) | **post** /requestBody/postAnyofWithOneEmptySchemaRequestBody | +*PathPostApi* | [**post_anyof_with_one_empty_schema_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_anyof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes | +*PathPostApi* | [**post_array_type_matches_arrays_request_body**](docs/apis/tags/PathPostApi.md#post_array_type_matches_arrays_request_body) | **post** /requestBody/postArrayTypeMatchesArraysRequestBody | +*PathPostApi* | [**post_array_type_matches_arrays_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_array_type_matches_arrays_response_body_for_content_types) | **post** /responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes | +*PathPostApi* | [**post_boolean_type_matches_booleans_request_body**](docs/apis/tags/PathPostApi.md#post_boolean_type_matches_booleans_request_body) | **post** /requestBody/postBooleanTypeMatchesBooleansRequestBody | +*PathPostApi* | [**post_boolean_type_matches_booleans_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_boolean_type_matches_booleans_response_body_for_content_types) | **post** /responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes | +*PathPostApi* | [**post_by_int_request_body**](docs/apis/tags/PathPostApi.md#post_by_int_request_body) | **post** /requestBody/postByIntRequestBody | +*PathPostApi* | [**post_by_int_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_by_int_response_body_for_content_types) | **post** /responseBody/postByIntResponseBodyForContentTypes | +*PathPostApi* | [**post_by_number_request_body**](docs/apis/tags/PathPostApi.md#post_by_number_request_body) | **post** /requestBody/postByNumberRequestBody | +*PathPostApi* | [**post_by_number_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_by_number_response_body_for_content_types) | **post** /responseBody/postByNumberResponseBodyForContentTypes | +*PathPostApi* | [**post_by_small_number_request_body**](docs/apis/tags/PathPostApi.md#post_by_small_number_request_body) | **post** /requestBody/postBySmallNumberRequestBody | +*PathPostApi* | [**post_by_small_number_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_by_small_number_response_body_for_content_types) | **post** /responseBody/postBySmallNumberResponseBodyForContentTypes | +*PathPostApi* | [**post_date_time_format_request_body**](docs/apis/tags/PathPostApi.md#post_date_time_format_request_body) | **post** /requestBody/postDateTimeFormatRequestBody | +*PathPostApi* | [**post_date_time_format_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_date_time_format_response_body_for_content_types) | **post** /responseBody/postDateTimeFormatResponseBodyForContentTypes | +*PathPostApi* | [**post_email_format_request_body**](docs/apis/tags/PathPostApi.md#post_email_format_request_body) | **post** /requestBody/postEmailFormatRequestBody | +*PathPostApi* | [**post_email_format_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_email_format_response_body_for_content_types) | **post** /responseBody/postEmailFormatResponseBodyForContentTypes | +*PathPostApi* | [**post_enum_with0_does_not_match_false_request_body**](docs/apis/tags/PathPostApi.md#post_enum_with0_does_not_match_false_request_body) | **post** /requestBody/postEnumWith0DoesNotMatchFalseRequestBody | +*PathPostApi* | [**post_enum_with0_does_not_match_false_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_enum_with0_does_not_match_false_response_body_for_content_types) | **post** /responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes | +*PathPostApi* | [**post_enum_with1_does_not_match_true_request_body**](docs/apis/tags/PathPostApi.md#post_enum_with1_does_not_match_true_request_body) | **post** /requestBody/postEnumWith1DoesNotMatchTrueRequestBody | +*PathPostApi* | [**post_enum_with1_does_not_match_true_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_enum_with1_does_not_match_true_response_body_for_content_types) | **post** /responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes | +*PathPostApi* | [**post_enum_with_escaped_characters_request_body**](docs/apis/tags/PathPostApi.md#post_enum_with_escaped_characters_request_body) | **post** /requestBody/postEnumWithEscapedCharactersRequestBody | +*PathPostApi* | [**post_enum_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_enum_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes | +*PathPostApi* | [**post_enum_with_false_does_not_match0_request_body**](docs/apis/tags/PathPostApi.md#post_enum_with_false_does_not_match0_request_body) | **post** /requestBody/postEnumWithFalseDoesNotMatch0RequestBody | +*PathPostApi* | [**post_enum_with_false_does_not_match0_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_enum_with_false_does_not_match0_response_body_for_content_types) | **post** /responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes | +*PathPostApi* | [**post_enum_with_true_does_not_match1_request_body**](docs/apis/tags/PathPostApi.md#post_enum_with_true_does_not_match1_request_body) | **post** /requestBody/postEnumWithTrueDoesNotMatch1RequestBody | +*PathPostApi* | [**post_enum_with_true_does_not_match1_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_enum_with_true_does_not_match1_response_body_for_content_types) | **post** /responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes | +*PathPostApi* | [**post_enums_in_properties_request_body**](docs/apis/tags/PathPostApi.md#post_enums_in_properties_request_body) | **post** /requestBody/postEnumsInPropertiesRequestBody | +*PathPostApi* | [**post_enums_in_properties_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_enums_in_properties_response_body_for_content_types) | **post** /responseBody/postEnumsInPropertiesResponseBodyForContentTypes | +*PathPostApi* | [**post_forbidden_property_request_body**](docs/apis/tags/PathPostApi.md#post_forbidden_property_request_body) | **post** /requestBody/postForbiddenPropertyRequestBody | +*PathPostApi* | [**post_forbidden_property_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_forbidden_property_response_body_for_content_types) | **post** /responseBody/postForbiddenPropertyResponseBodyForContentTypes | +*PathPostApi* | [**post_hostname_format_request_body**](docs/apis/tags/PathPostApi.md#post_hostname_format_request_body) | **post** /requestBody/postHostnameFormatRequestBody | +*PathPostApi* | [**post_hostname_format_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_hostname_format_response_body_for_content_types) | **post** /responseBody/postHostnameFormatResponseBodyForContentTypes | +*PathPostApi* | [**post_integer_type_matches_integers_request_body**](docs/apis/tags/PathPostApi.md#post_integer_type_matches_integers_request_body) | **post** /requestBody/postIntegerTypeMatchesIntegersRequestBody | +*PathPostApi* | [**post_integer_type_matches_integers_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_integer_type_matches_integers_response_body_for_content_types) | **post** /responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes | +*PathPostApi* | [**post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body**](docs/apis/tags/PathPostApi.md#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body) | **post** /requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody | +*PathPostApi* | [**post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types) | **post** /responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes | +*PathPostApi* | [**post_invalid_string_value_for_default_request_body**](docs/apis/tags/PathPostApi.md#post_invalid_string_value_for_default_request_body) | **post** /requestBody/postInvalidStringValueForDefaultRequestBody | +*PathPostApi* | [**post_invalid_string_value_for_default_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_invalid_string_value_for_default_response_body_for_content_types) | **post** /responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes | +*PathPostApi* | [**post_ipv4_format_request_body**](docs/apis/tags/PathPostApi.md#post_ipv4_format_request_body) | **post** /requestBody/postIpv4FormatRequestBody | +*PathPostApi* | [**post_ipv4_format_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_ipv4_format_response_body_for_content_types) | **post** /responseBody/postIpv4FormatResponseBodyForContentTypes | +*PathPostApi* | [**post_ipv6_format_request_body**](docs/apis/tags/PathPostApi.md#post_ipv6_format_request_body) | **post** /requestBody/postIpv6FormatRequestBody | +*PathPostApi* | [**post_ipv6_format_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_ipv6_format_response_body_for_content_types) | **post** /responseBody/postIpv6FormatResponseBodyForContentTypes | +*PathPostApi* | [**post_json_pointer_format_request_body**](docs/apis/tags/PathPostApi.md#post_json_pointer_format_request_body) | **post** /requestBody/postJsonPointerFormatRequestBody | +*PathPostApi* | [**post_json_pointer_format_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_json_pointer_format_response_body_for_content_types) | **post** /responseBody/postJsonPointerFormatResponseBodyForContentTypes | +*PathPostApi* | [**post_maximum_validation_request_body**](docs/apis/tags/PathPostApi.md#post_maximum_validation_request_body) | **post** /requestBody/postMaximumValidationRequestBody | +*PathPostApi* | [**post_maximum_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_maximum_validation_response_body_for_content_types) | **post** /responseBody/postMaximumValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_maximum_validation_with_unsigned_integer_request_body**](docs/apis/tags/PathPostApi.md#post_maximum_validation_with_unsigned_integer_request_body) | **post** /requestBody/postMaximumValidationWithUnsignedIntegerRequestBody | +*PathPostApi* | [**post_maximum_validation_with_unsigned_integer_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_maximum_validation_with_unsigned_integer_response_body_for_content_types) | **post** /responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes | +*PathPostApi* | [**post_maxitems_validation_request_body**](docs/apis/tags/PathPostApi.md#post_maxitems_validation_request_body) | **post** /requestBody/postMaxitemsValidationRequestBody | +*PathPostApi* | [**post_maxitems_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_maxitems_validation_response_body_for_content_types) | **post** /responseBody/postMaxitemsValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_maxlength_validation_request_body**](docs/apis/tags/PathPostApi.md#post_maxlength_validation_request_body) | **post** /requestBody/postMaxlengthValidationRequestBody | +*PathPostApi* | [**post_maxlength_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_maxlength_validation_response_body_for_content_types) | **post** /responseBody/postMaxlengthValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_maxproperties0_means_the_object_is_empty_request_body**](docs/apis/tags/PathPostApi.md#post_maxproperties0_means_the_object_is_empty_request_body) | **post** /requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody | +*PathPostApi* | [**post_maxproperties0_means_the_object_is_empty_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types) | **post** /responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes | +*PathPostApi* | [**post_maxproperties_validation_request_body**](docs/apis/tags/PathPostApi.md#post_maxproperties_validation_request_body) | **post** /requestBody/postMaxpropertiesValidationRequestBody | +*PathPostApi* | [**post_maxproperties_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_maxproperties_validation_response_body_for_content_types) | **post** /responseBody/postMaxpropertiesValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_minimum_validation_request_body**](docs/apis/tags/PathPostApi.md#post_minimum_validation_request_body) | **post** /requestBody/postMinimumValidationRequestBody | +*PathPostApi* | [**post_minimum_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_minimum_validation_response_body_for_content_types) | **post** /responseBody/postMinimumValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_minimum_validation_with_signed_integer_request_body**](docs/apis/tags/PathPostApi.md#post_minimum_validation_with_signed_integer_request_body) | **post** /requestBody/postMinimumValidationWithSignedIntegerRequestBody | +*PathPostApi* | [**post_minimum_validation_with_signed_integer_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_minimum_validation_with_signed_integer_response_body_for_content_types) | **post** /responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes | +*PathPostApi* | [**post_minitems_validation_request_body**](docs/apis/tags/PathPostApi.md#post_minitems_validation_request_body) | **post** /requestBody/postMinitemsValidationRequestBody | +*PathPostApi* | [**post_minitems_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_minitems_validation_response_body_for_content_types) | **post** /responseBody/postMinitemsValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_minlength_validation_request_body**](docs/apis/tags/PathPostApi.md#post_minlength_validation_request_body) | **post** /requestBody/postMinlengthValidationRequestBody | +*PathPostApi* | [**post_minlength_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_minlength_validation_response_body_for_content_types) | **post** /responseBody/postMinlengthValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_minproperties_validation_request_body**](docs/apis/tags/PathPostApi.md#post_minproperties_validation_request_body) | **post** /requestBody/postMinpropertiesValidationRequestBody | +*PathPostApi* | [**post_minproperties_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_minproperties_validation_response_body_for_content_types) | **post** /responseBody/postMinpropertiesValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_nested_allof_to_check_validation_semantics_request_body**](docs/apis/tags/PathPostApi.md#post_nested_allof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAllofToCheckValidationSemanticsRequestBody | +*PathPostApi* | [**post_nested_allof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_nested_allof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes | +*PathPostApi* | [**post_nested_anyof_to_check_validation_semantics_request_body**](docs/apis/tags/PathPostApi.md#post_nested_anyof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody | +*PathPostApi* | [**post_nested_anyof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes | +*PathPostApi* | [**post_nested_items_request_body**](docs/apis/tags/PathPostApi.md#post_nested_items_request_body) | **post** /requestBody/postNestedItemsRequestBody | +*PathPostApi* | [**post_nested_items_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_nested_items_response_body_for_content_types) | **post** /responseBody/postNestedItemsResponseBodyForContentTypes | +*PathPostApi* | [**post_nested_oneof_to_check_validation_semantics_request_body**](docs/apis/tags/PathPostApi.md#post_nested_oneof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedOneofToCheckValidationSemanticsRequestBody | +*PathPostApi* | [**post_nested_oneof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes | +*PathPostApi* | [**post_not_more_complex_schema_request_body**](docs/apis/tags/PathPostApi.md#post_not_more_complex_schema_request_body) | **post** /requestBody/postNotMoreComplexSchemaRequestBody | +*PathPostApi* | [**post_not_more_complex_schema_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_not_more_complex_schema_response_body_for_content_types) | **post** /responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes | +*PathPostApi* | [**post_not_request_body**](docs/apis/tags/PathPostApi.md#post_not_request_body) | **post** /requestBody/postNotRequestBody | +*PathPostApi* | [**post_not_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_not_response_body_for_content_types) | **post** /responseBody/postNotResponseBodyForContentTypes | +*PathPostApi* | [**post_nul_characters_in_strings_request_body**](docs/apis/tags/PathPostApi.md#post_nul_characters_in_strings_request_body) | **post** /requestBody/postNulCharactersInStringsRequestBody | +*PathPostApi* | [**post_nul_characters_in_strings_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_nul_characters_in_strings_response_body_for_content_types) | **post** /responseBody/postNulCharactersInStringsResponseBodyForContentTypes | +*PathPostApi* | [**post_null_type_matches_only_the_null_object_request_body**](docs/apis/tags/PathPostApi.md#post_null_type_matches_only_the_null_object_request_body) | **post** /requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody | +*PathPostApi* | [**post_null_type_matches_only_the_null_object_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_null_type_matches_only_the_null_object_response_body_for_content_types) | **post** /responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes | +*PathPostApi* | [**post_number_type_matches_numbers_request_body**](docs/apis/tags/PathPostApi.md#post_number_type_matches_numbers_request_body) | **post** /requestBody/postNumberTypeMatchesNumbersRequestBody | +*PathPostApi* | [**post_number_type_matches_numbers_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_number_type_matches_numbers_response_body_for_content_types) | **post** /responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes | +*PathPostApi* | [**post_object_properties_validation_request_body**](docs/apis/tags/PathPostApi.md#post_object_properties_validation_request_body) | **post** /requestBody/postObjectPropertiesValidationRequestBody | +*PathPostApi* | [**post_object_properties_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_object_properties_validation_response_body_for_content_types) | **post** /responseBody/postObjectPropertiesValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_object_type_matches_objects_request_body**](docs/apis/tags/PathPostApi.md#post_object_type_matches_objects_request_body) | **post** /requestBody/postObjectTypeMatchesObjectsRequestBody | +*PathPostApi* | [**post_object_type_matches_objects_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_object_type_matches_objects_response_body_for_content_types) | **post** /responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes | +*PathPostApi* | [**post_oneof_complex_types_request_body**](docs/apis/tags/PathPostApi.md#post_oneof_complex_types_request_body) | **post** /requestBody/postOneofComplexTypesRequestBody | +*PathPostApi* | [**post_oneof_complex_types_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_oneof_complex_types_response_body_for_content_types) | **post** /responseBody/postOneofComplexTypesResponseBodyForContentTypes | +*PathPostApi* | [**post_oneof_request_body**](docs/apis/tags/PathPostApi.md#post_oneof_request_body) | **post** /requestBody/postOneofRequestBody | +*PathPostApi* | [**post_oneof_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_oneof_response_body_for_content_types) | **post** /responseBody/postOneofResponseBodyForContentTypes | +*PathPostApi* | [**post_oneof_with_base_schema_request_body**](docs/apis/tags/PathPostApi.md#post_oneof_with_base_schema_request_body) | **post** /requestBody/postOneofWithBaseSchemaRequestBody | +*PathPostApi* | [**post_oneof_with_base_schema_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_oneof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes | +*PathPostApi* | [**post_oneof_with_empty_schema_request_body**](docs/apis/tags/PathPostApi.md#post_oneof_with_empty_schema_request_body) | **post** /requestBody/postOneofWithEmptySchemaRequestBody | +*PathPostApi* | [**post_oneof_with_empty_schema_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_oneof_with_empty_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes | +*PathPostApi* | [**post_oneof_with_required_request_body**](docs/apis/tags/PathPostApi.md#post_oneof_with_required_request_body) | **post** /requestBody/postOneofWithRequiredRequestBody | +*PathPostApi* | [**post_oneof_with_required_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_oneof_with_required_response_body_for_content_types) | **post** /responseBody/postOneofWithRequiredResponseBodyForContentTypes | +*PathPostApi* | [**post_pattern_is_not_anchored_request_body**](docs/apis/tags/PathPostApi.md#post_pattern_is_not_anchored_request_body) | **post** /requestBody/postPatternIsNotAnchoredRequestBody | +*PathPostApi* | [**post_pattern_is_not_anchored_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_pattern_is_not_anchored_response_body_for_content_types) | **post** /responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes | +*PathPostApi* | [**post_pattern_validation_request_body**](docs/apis/tags/PathPostApi.md#post_pattern_validation_request_body) | **post** /requestBody/postPatternValidationRequestBody | +*PathPostApi* | [**post_pattern_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_pattern_validation_response_body_for_content_types) | **post** /responseBody/postPatternValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_properties_with_escaped_characters_request_body**](docs/apis/tags/PathPostApi.md#post_properties_with_escaped_characters_request_body) | **post** /requestBody/postPropertiesWithEscapedCharactersRequestBody | +*PathPostApi* | [**post_properties_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_properties_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes | +*PathPostApi* | [**post_property_named_ref_that_is_not_a_reference_request_body**](docs/apis/tags/PathPostApi.md#post_property_named_ref_that_is_not_a_reference_request_body) | **post** /requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody | +*PathPostApi* | [**post_property_named_ref_that_is_not_a_reference_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types) | **post** /responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes | +*PathPostApi* | [**post_ref_in_additionalproperties_request_body**](docs/apis/tags/PathPostApi.md#post_ref_in_additionalproperties_request_body) | **post** /requestBody/postRefInAdditionalpropertiesRequestBody | +*PathPostApi* | [**post_ref_in_additionalproperties_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_ref_in_additionalproperties_response_body_for_content_types) | **post** /responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes | +*PathPostApi* | [**post_ref_in_allof_request_body**](docs/apis/tags/PathPostApi.md#post_ref_in_allof_request_body) | **post** /requestBody/postRefInAllofRequestBody | +*PathPostApi* | [**post_ref_in_allof_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_ref_in_allof_response_body_for_content_types) | **post** /responseBody/postRefInAllofResponseBodyForContentTypes | +*PathPostApi* | [**post_ref_in_anyof_request_body**](docs/apis/tags/PathPostApi.md#post_ref_in_anyof_request_body) | **post** /requestBody/postRefInAnyofRequestBody | +*PathPostApi* | [**post_ref_in_anyof_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_ref_in_anyof_response_body_for_content_types) | **post** /responseBody/postRefInAnyofResponseBodyForContentTypes | +*PathPostApi* | [**post_ref_in_items_request_body**](docs/apis/tags/PathPostApi.md#post_ref_in_items_request_body) | **post** /requestBody/postRefInItemsRequestBody | +*PathPostApi* | [**post_ref_in_items_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_ref_in_items_response_body_for_content_types) | **post** /responseBody/postRefInItemsResponseBodyForContentTypes | +*PathPostApi* | [**post_ref_in_not_request_body**](docs/apis/tags/PathPostApi.md#post_ref_in_not_request_body) | **post** /requestBody/postRefInNotRequestBody | +*PathPostApi* | [**post_ref_in_not_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_ref_in_not_response_body_for_content_types) | **post** /responseBody/postRefInNotResponseBodyForContentTypes | +*PathPostApi* | [**post_ref_in_oneof_request_body**](docs/apis/tags/PathPostApi.md#post_ref_in_oneof_request_body) | **post** /requestBody/postRefInOneofRequestBody | +*PathPostApi* | [**post_ref_in_oneof_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_ref_in_oneof_response_body_for_content_types) | **post** /responseBody/postRefInOneofResponseBodyForContentTypes | +*PathPostApi* | [**post_ref_in_property_request_body**](docs/apis/tags/PathPostApi.md#post_ref_in_property_request_body) | **post** /requestBody/postRefInPropertyRequestBody | +*PathPostApi* | [**post_ref_in_property_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_ref_in_property_response_body_for_content_types) | **post** /responseBody/postRefInPropertyResponseBodyForContentTypes | +*PathPostApi* | [**post_required_default_validation_request_body**](docs/apis/tags/PathPostApi.md#post_required_default_validation_request_body) | **post** /requestBody/postRequiredDefaultValidationRequestBody | +*PathPostApi* | [**post_required_default_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_required_default_validation_response_body_for_content_types) | **post** /responseBody/postRequiredDefaultValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_required_validation_request_body**](docs/apis/tags/PathPostApi.md#post_required_validation_request_body) | **post** /requestBody/postRequiredValidationRequestBody | +*PathPostApi* | [**post_required_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_required_validation_response_body_for_content_types) | **post** /responseBody/postRequiredValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_required_with_empty_array_request_body**](docs/apis/tags/PathPostApi.md#post_required_with_empty_array_request_body) | **post** /requestBody/postRequiredWithEmptyArrayRequestBody | +*PathPostApi* | [**post_required_with_empty_array_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_required_with_empty_array_response_body_for_content_types) | **post** /responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes | +*PathPostApi* | [**post_required_with_escaped_characters_request_body**](docs/apis/tags/PathPostApi.md#post_required_with_escaped_characters_request_body) | **post** /requestBody/postRequiredWithEscapedCharactersRequestBody | +*PathPostApi* | [**post_required_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_required_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes | +*PathPostApi* | [**post_simple_enum_validation_request_body**](docs/apis/tags/PathPostApi.md#post_simple_enum_validation_request_body) | **post** /requestBody/postSimpleEnumValidationRequestBody | +*PathPostApi* | [**post_simple_enum_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_simple_enum_validation_response_body_for_content_types) | **post** /responseBody/postSimpleEnumValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_string_type_matches_strings_request_body**](docs/apis/tags/PathPostApi.md#post_string_type_matches_strings_request_body) | **post** /requestBody/postStringTypeMatchesStringsRequestBody | +*PathPostApi* | [**post_string_type_matches_strings_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_string_type_matches_strings_response_body_for_content_types) | **post** /responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes | +*PathPostApi* | [**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body**](docs/apis/tags/PathPostApi.md#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body) | **post** /requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody | +*PathPostApi* | [**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types) | **post** /responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes | +*PathPostApi* | [**post_uniqueitems_false_validation_request_body**](docs/apis/tags/PathPostApi.md#post_uniqueitems_false_validation_request_body) | **post** /requestBody/postUniqueitemsFalseValidationRequestBody | +*PathPostApi* | [**post_uniqueitems_false_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_uniqueitems_false_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_uniqueitems_validation_request_body**](docs/apis/tags/PathPostApi.md#post_uniqueitems_validation_request_body) | **post** /requestBody/postUniqueitemsValidationRequestBody | +*PathPostApi* | [**post_uniqueitems_validation_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_uniqueitems_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsValidationResponseBodyForContentTypes | +*PathPostApi* | [**post_uri_format_request_body**](docs/apis/tags/PathPostApi.md#post_uri_format_request_body) | **post** /requestBody/postUriFormatRequestBody | +*PathPostApi* | [**post_uri_format_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_uri_format_response_body_for_content_types) | **post** /responseBody/postUriFormatResponseBodyForContentTypes | +*PathPostApi* | [**post_uri_reference_format_request_body**](docs/apis/tags/PathPostApi.md#post_uri_reference_format_request_body) | **post** /requestBody/postUriReferenceFormatRequestBody | +*PathPostApi* | [**post_uri_reference_format_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_uri_reference_format_response_body_for_content_types) | **post** /responseBody/postUriReferenceFormatResponseBodyForContentTypes | +*PathPostApi* | [**post_uri_template_format_request_body**](docs/apis/tags/PathPostApi.md#post_uri_template_format_request_body) | **post** /requestBody/postUriTemplateFormatRequestBody | +*PathPostApi* | [**post_uri_template_format_response_body_for_content_types**](docs/apis/tags/PathPostApi.md#post_uri_template_format_response_body_for_content_types) | **post** /responseBody/postUriTemplateFormatResponseBodyForContentTypes | +*PatternApi* | [**post_pattern_is_not_anchored_request_body**](docs/apis/tags/PatternApi.md#post_pattern_is_not_anchored_request_body) | **post** /requestBody/postPatternIsNotAnchoredRequestBody | +*PatternApi* | [**post_pattern_is_not_anchored_response_body_for_content_types**](docs/apis/tags/PatternApi.md#post_pattern_is_not_anchored_response_body_for_content_types) | **post** /responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes | +*PatternApi* | [**post_pattern_validation_request_body**](docs/apis/tags/PatternApi.md#post_pattern_validation_request_body) | **post** /requestBody/postPatternValidationRequestBody | +*PatternApi* | [**post_pattern_validation_response_body_for_content_types**](docs/apis/tags/PatternApi.md#post_pattern_validation_response_body_for_content_types) | **post** /responseBody/postPatternValidationResponseBodyForContentTypes | +*PropertiesApi* | [**post_object_properties_validation_request_body**](docs/apis/tags/PropertiesApi.md#post_object_properties_validation_request_body) | **post** /requestBody/postObjectPropertiesValidationRequestBody | +*PropertiesApi* | [**post_object_properties_validation_response_body_for_content_types**](docs/apis/tags/PropertiesApi.md#post_object_properties_validation_response_body_for_content_types) | **post** /responseBody/postObjectPropertiesValidationResponseBodyForContentTypes | +*PropertiesApi* | [**post_properties_with_escaped_characters_request_body**](docs/apis/tags/PropertiesApi.md#post_properties_with_escaped_characters_request_body) | **post** /requestBody/postPropertiesWithEscapedCharactersRequestBody | +*PropertiesApi* | [**post_properties_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/PropertiesApi.md#post_properties_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes | +*RequiredApi* | [**post_required_default_validation_request_body**](docs/apis/tags/RequiredApi.md#post_required_default_validation_request_body) | **post** /requestBody/postRequiredDefaultValidationRequestBody | +*RequiredApi* | [**post_required_default_validation_response_body_for_content_types**](docs/apis/tags/RequiredApi.md#post_required_default_validation_response_body_for_content_types) | **post** /responseBody/postRequiredDefaultValidationResponseBodyForContentTypes | +*RequiredApi* | [**post_required_validation_request_body**](docs/apis/tags/RequiredApi.md#post_required_validation_request_body) | **post** /requestBody/postRequiredValidationRequestBody | +*RequiredApi* | [**post_required_validation_response_body_for_content_types**](docs/apis/tags/RequiredApi.md#post_required_validation_response_body_for_content_types) | **post** /responseBody/postRequiredValidationResponseBodyForContentTypes | +*RequiredApi* | [**post_required_with_empty_array_request_body**](docs/apis/tags/RequiredApi.md#post_required_with_empty_array_request_body) | **post** /requestBody/postRequiredWithEmptyArrayRequestBody | +*RequiredApi* | [**post_required_with_empty_array_response_body_for_content_types**](docs/apis/tags/RequiredApi.md#post_required_with_empty_array_response_body_for_content_types) | **post** /responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes | +*RequiredApi* | [**post_required_with_escaped_characters_request_body**](docs/apis/tags/RequiredApi.md#post_required_with_escaped_characters_request_body) | **post** /requestBody/postRequiredWithEscapedCharactersRequestBody | +*RequiredApi* | [**post_required_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/RequiredApi.md#post_required_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_additionalproperties_are_allowed_by_default_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_additionalproperties_are_allowed_by_default_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_additionalproperties_can_exist_by_itself_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_additionalproperties_can_exist_by_itself_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_allof_combined_with_anyof_oneof_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_allof_combined_with_anyof_oneof_response_body_for_content_types) | **post** /responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_allof_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_allof_response_body_for_content_types) | **post** /responseBody/postAllofResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_allof_simple_types_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_allof_simple_types_response_body_for_content_types) | **post** /responseBody/postAllofSimpleTypesResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_allof_with_base_schema_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_allof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_allof_with_one_empty_schema_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_allof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_allof_with_the_first_empty_schema_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_allof_with_the_first_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_allof_with_the_last_empty_schema_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_allof_with_the_last_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_allof_with_two_empty_schemas_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_allof_with_two_empty_schemas_response_body_for_content_types) | **post** /responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_anyof_complex_types_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_anyof_complex_types_response_body_for_content_types) | **post** /responseBody/postAnyofComplexTypesResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_anyof_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_anyof_response_body_for_content_types) | **post** /responseBody/postAnyofResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_anyof_with_base_schema_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_anyof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_anyof_with_one_empty_schema_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_anyof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_array_type_matches_arrays_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_array_type_matches_arrays_response_body_for_content_types) | **post** /responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_boolean_type_matches_booleans_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_boolean_type_matches_booleans_response_body_for_content_types) | **post** /responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_by_int_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_by_int_response_body_for_content_types) | **post** /responseBody/postByIntResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_by_number_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_by_number_response_body_for_content_types) | **post** /responseBody/postByNumberResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_by_small_number_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_by_small_number_response_body_for_content_types) | **post** /responseBody/postBySmallNumberResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_date_time_format_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_date_time_format_response_body_for_content_types) | **post** /responseBody/postDateTimeFormatResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_email_format_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_email_format_response_body_for_content_types) | **post** /responseBody/postEmailFormatResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_enum_with0_does_not_match_false_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_enum_with0_does_not_match_false_response_body_for_content_types) | **post** /responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_enum_with1_does_not_match_true_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_enum_with1_does_not_match_true_response_body_for_content_types) | **post** /responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_enum_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_enum_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_enum_with_false_does_not_match0_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_enum_with_false_does_not_match0_response_body_for_content_types) | **post** /responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_enum_with_true_does_not_match1_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_enum_with_true_does_not_match1_response_body_for_content_types) | **post** /responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_enums_in_properties_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_enums_in_properties_response_body_for_content_types) | **post** /responseBody/postEnumsInPropertiesResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_forbidden_property_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_forbidden_property_response_body_for_content_types) | **post** /responseBody/postForbiddenPropertyResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_hostname_format_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_hostname_format_response_body_for_content_types) | **post** /responseBody/postHostnameFormatResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_integer_type_matches_integers_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_integer_type_matches_integers_response_body_for_content_types) | **post** /responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types) | **post** /responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_invalid_string_value_for_default_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_invalid_string_value_for_default_response_body_for_content_types) | **post** /responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_ipv4_format_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_ipv4_format_response_body_for_content_types) | **post** /responseBody/postIpv4FormatResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_ipv6_format_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_ipv6_format_response_body_for_content_types) | **post** /responseBody/postIpv6FormatResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_json_pointer_format_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_json_pointer_format_response_body_for_content_types) | **post** /responseBody/postJsonPointerFormatResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_maximum_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_maximum_validation_response_body_for_content_types) | **post** /responseBody/postMaximumValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_maximum_validation_with_unsigned_integer_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_maximum_validation_with_unsigned_integer_response_body_for_content_types) | **post** /responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_maxitems_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_maxitems_validation_response_body_for_content_types) | **post** /responseBody/postMaxitemsValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_maxlength_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_maxlength_validation_response_body_for_content_types) | **post** /responseBody/postMaxlengthValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_maxproperties0_means_the_object_is_empty_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types) | **post** /responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_maxproperties_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_maxproperties_validation_response_body_for_content_types) | **post** /responseBody/postMaxpropertiesValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_minimum_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_minimum_validation_response_body_for_content_types) | **post** /responseBody/postMinimumValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_minimum_validation_with_signed_integer_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_minimum_validation_with_signed_integer_response_body_for_content_types) | **post** /responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_minitems_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_minitems_validation_response_body_for_content_types) | **post** /responseBody/postMinitemsValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_minlength_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_minlength_validation_response_body_for_content_types) | **post** /responseBody/postMinlengthValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_minproperties_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_minproperties_validation_response_body_for_content_types) | **post** /responseBody/postMinpropertiesValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_nested_allof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_nested_allof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_nested_anyof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_nested_items_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_nested_items_response_body_for_content_types) | **post** /responseBody/postNestedItemsResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_nested_oneof_to_check_validation_semantics_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_not_more_complex_schema_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_not_more_complex_schema_response_body_for_content_types) | **post** /responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_not_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_not_response_body_for_content_types) | **post** /responseBody/postNotResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_nul_characters_in_strings_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_nul_characters_in_strings_response_body_for_content_types) | **post** /responseBody/postNulCharactersInStringsResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_null_type_matches_only_the_null_object_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_null_type_matches_only_the_null_object_response_body_for_content_types) | **post** /responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_number_type_matches_numbers_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_number_type_matches_numbers_response_body_for_content_types) | **post** /responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_object_properties_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_object_properties_validation_response_body_for_content_types) | **post** /responseBody/postObjectPropertiesValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_object_type_matches_objects_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_object_type_matches_objects_response_body_for_content_types) | **post** /responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_oneof_complex_types_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_oneof_complex_types_response_body_for_content_types) | **post** /responseBody/postOneofComplexTypesResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_oneof_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_oneof_response_body_for_content_types) | **post** /responseBody/postOneofResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_oneof_with_base_schema_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_oneof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_oneof_with_empty_schema_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_oneof_with_empty_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_oneof_with_required_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_oneof_with_required_response_body_for_content_types) | **post** /responseBody/postOneofWithRequiredResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_pattern_is_not_anchored_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_pattern_is_not_anchored_response_body_for_content_types) | **post** /responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_pattern_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_pattern_validation_response_body_for_content_types) | **post** /responseBody/postPatternValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_properties_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_properties_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_property_named_ref_that_is_not_a_reference_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types) | **post** /responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_ref_in_additionalproperties_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_ref_in_additionalproperties_response_body_for_content_types) | **post** /responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_ref_in_allof_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_ref_in_allof_response_body_for_content_types) | **post** /responseBody/postRefInAllofResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_ref_in_anyof_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_ref_in_anyof_response_body_for_content_types) | **post** /responseBody/postRefInAnyofResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_ref_in_items_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_ref_in_items_response_body_for_content_types) | **post** /responseBody/postRefInItemsResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_ref_in_not_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_ref_in_not_response_body_for_content_types) | **post** /responseBody/postRefInNotResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_ref_in_oneof_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_ref_in_oneof_response_body_for_content_types) | **post** /responseBody/postRefInOneofResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_ref_in_property_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_ref_in_property_response_body_for_content_types) | **post** /responseBody/postRefInPropertyResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_required_default_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_required_default_validation_response_body_for_content_types) | **post** /responseBody/postRequiredDefaultValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_required_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_required_validation_response_body_for_content_types) | **post** /responseBody/postRequiredValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_required_with_empty_array_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_required_with_empty_array_response_body_for_content_types) | **post** /responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_required_with_escaped_characters_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_required_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_simple_enum_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_simple_enum_validation_response_body_for_content_types) | **post** /responseBody/postSimpleEnumValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_string_type_matches_strings_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_string_type_matches_strings_response_body_for_content_types) | **post** /responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types) | **post** /responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_uniqueitems_false_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_uniqueitems_false_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_uniqueitems_validation_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_uniqueitems_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsValidationResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_uri_format_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_uri_format_response_body_for_content_types) | **post** /responseBody/postUriFormatResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_uri_reference_format_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_uri_reference_format_response_body_for_content_types) | **post** /responseBody/postUriReferenceFormatResponseBodyForContentTypes | +*ResponseContentContentTypeSchemaApi* | [**post_uri_template_format_response_body_for_content_types**](docs/apis/tags/ResponseContentContentTypeSchemaApi.md#post_uri_template_format_response_body_for_content_types) | **post** /responseBody/postUriTemplateFormatResponseBodyForContentTypes | +*TypeApi* | [**post_array_type_matches_arrays_request_body**](docs/apis/tags/TypeApi.md#post_array_type_matches_arrays_request_body) | **post** /requestBody/postArrayTypeMatchesArraysRequestBody | +*TypeApi* | [**post_array_type_matches_arrays_response_body_for_content_types**](docs/apis/tags/TypeApi.md#post_array_type_matches_arrays_response_body_for_content_types) | **post** /responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes | +*TypeApi* | [**post_boolean_type_matches_booleans_request_body**](docs/apis/tags/TypeApi.md#post_boolean_type_matches_booleans_request_body) | **post** /requestBody/postBooleanTypeMatchesBooleansRequestBody | +*TypeApi* | [**post_boolean_type_matches_booleans_response_body_for_content_types**](docs/apis/tags/TypeApi.md#post_boolean_type_matches_booleans_response_body_for_content_types) | **post** /responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes | +*TypeApi* | [**post_integer_type_matches_integers_request_body**](docs/apis/tags/TypeApi.md#post_integer_type_matches_integers_request_body) | **post** /requestBody/postIntegerTypeMatchesIntegersRequestBody | +*TypeApi* | [**post_integer_type_matches_integers_response_body_for_content_types**](docs/apis/tags/TypeApi.md#post_integer_type_matches_integers_response_body_for_content_types) | **post** /responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes | +*TypeApi* | [**post_null_type_matches_only_the_null_object_request_body**](docs/apis/tags/TypeApi.md#post_null_type_matches_only_the_null_object_request_body) | **post** /requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody | +*TypeApi* | [**post_null_type_matches_only_the_null_object_response_body_for_content_types**](docs/apis/tags/TypeApi.md#post_null_type_matches_only_the_null_object_response_body_for_content_types) | **post** /responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes | +*TypeApi* | [**post_number_type_matches_numbers_request_body**](docs/apis/tags/TypeApi.md#post_number_type_matches_numbers_request_body) | **post** /requestBody/postNumberTypeMatchesNumbersRequestBody | +*TypeApi* | [**post_number_type_matches_numbers_response_body_for_content_types**](docs/apis/tags/TypeApi.md#post_number_type_matches_numbers_response_body_for_content_types) | **post** /responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes | +*TypeApi* | [**post_object_type_matches_objects_request_body**](docs/apis/tags/TypeApi.md#post_object_type_matches_objects_request_body) | **post** /requestBody/postObjectTypeMatchesObjectsRequestBody | +*TypeApi* | [**post_object_type_matches_objects_response_body_for_content_types**](docs/apis/tags/TypeApi.md#post_object_type_matches_objects_response_body_for_content_types) | **post** /responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes | +*TypeApi* | [**post_string_type_matches_strings_request_body**](docs/apis/tags/TypeApi.md#post_string_type_matches_strings_request_body) | **post** /requestBody/postStringTypeMatchesStringsRequestBody | +*TypeApi* | [**post_string_type_matches_strings_response_body_for_content_types**](docs/apis/tags/TypeApi.md#post_string_type_matches_strings_response_body_for_content_types) | **post** /responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes | +*UniqueItemsApi* | [**post_uniqueitems_false_validation_request_body**](docs/apis/tags/UniqueItemsApi.md#post_uniqueitems_false_validation_request_body) | **post** /requestBody/postUniqueitemsFalseValidationRequestBody | +*UniqueItemsApi* | [**post_uniqueitems_false_validation_response_body_for_content_types**](docs/apis/tags/UniqueItemsApi.md#post_uniqueitems_false_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes | +*UniqueItemsApi* | [**post_uniqueitems_validation_request_body**](docs/apis/tags/UniqueItemsApi.md#post_uniqueitems_validation_request_body) | **post** /requestBody/postUniqueitemsValidationRequestBody | +*UniqueItemsApi* | [**post_uniqueitems_validation_response_body_for_content_types**](docs/apis/tags/UniqueItemsApi.md#post_uniqueitems_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsValidationResponseBodyForContentTypes | + +## Documentation For Models + + - [AdditionalpropertiesAllowsASchemaWhichShouldValidate](docs/models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) + - [AdditionalpropertiesAreAllowedByDefault](docs/models/AdditionalpropertiesAreAllowedByDefault.md) + - [AdditionalpropertiesCanExistByItself](docs/models/AdditionalpropertiesCanExistByItself.md) + - [AdditionalpropertiesShouldNotLookInApplicators](docs/models/AdditionalpropertiesShouldNotLookInApplicators.md) + - [Allof](docs/models/Allof.md) + - [AllofCombinedWithAnyofOneof](docs/models/AllofCombinedWithAnyofOneof.md) + - [AllofSimpleTypes](docs/models/AllofSimpleTypes.md) + - [AllofWithBaseSchema](docs/models/AllofWithBaseSchema.md) + - [AllofWithOneEmptySchema](docs/models/AllofWithOneEmptySchema.md) + - [AllofWithTheFirstEmptySchema](docs/models/AllofWithTheFirstEmptySchema.md) + - [AllofWithTheLastEmptySchema](docs/models/AllofWithTheLastEmptySchema.md) + - [AllofWithTwoEmptySchemas](docs/models/AllofWithTwoEmptySchemas.md) + - [Anyof](docs/models/Anyof.md) + - [AnyofComplexTypes](docs/models/AnyofComplexTypes.md) + - [AnyofWithBaseSchema](docs/models/AnyofWithBaseSchema.md) + - [AnyofWithOneEmptySchema](docs/models/AnyofWithOneEmptySchema.md) + - [ArrayTypeMatchesArrays](docs/models/ArrayTypeMatchesArrays.md) + - [BooleanTypeMatchesBooleans](docs/models/BooleanTypeMatchesBooleans.md) + - [ByInt](docs/models/ByInt.md) + - [ByNumber](docs/models/ByNumber.md) + - [BySmallNumber](docs/models/BySmallNumber.md) + - [DateTimeFormat](docs/models/DateTimeFormat.md) + - [EmailFormat](docs/models/EmailFormat.md) + - [EnumWith0DoesNotMatchFalse](docs/models/EnumWith0DoesNotMatchFalse.md) + - [EnumWith1DoesNotMatchTrue](docs/models/EnumWith1DoesNotMatchTrue.md) + - [EnumWithEscapedCharacters](docs/models/EnumWithEscapedCharacters.md) + - [EnumWithFalseDoesNotMatch0](docs/models/EnumWithFalseDoesNotMatch0.md) + - [EnumWithTrueDoesNotMatch1](docs/models/EnumWithTrueDoesNotMatch1.md) + - [EnumsInProperties](docs/models/EnumsInProperties.md) + - [ForbiddenProperty](docs/models/ForbiddenProperty.md) + - [HostnameFormat](docs/models/HostnameFormat.md) + - [IntegerTypeMatchesIntegers](docs/models/IntegerTypeMatchesIntegers.md) + - [InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf](docs/models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) + - [InvalidStringValueForDefault](docs/models/InvalidStringValueForDefault.md) + - [Ipv4Format](docs/models/Ipv4Format.md) + - [Ipv6Format](docs/models/Ipv6Format.md) + - [JsonPointerFormat](docs/models/JsonPointerFormat.md) + - [MaximumValidation](docs/models/MaximumValidation.md) + - [MaximumValidationWithUnsignedInteger](docs/models/MaximumValidationWithUnsignedInteger.md) + - [MaxitemsValidation](docs/models/MaxitemsValidation.md) + - [MaxlengthValidation](docs/models/MaxlengthValidation.md) + - [Maxproperties0MeansTheObjectIsEmpty](docs/models/Maxproperties0MeansTheObjectIsEmpty.md) + - [MaxpropertiesValidation](docs/models/MaxpropertiesValidation.md) + - [MinimumValidation](docs/models/MinimumValidation.md) + - [MinimumValidationWithSignedInteger](docs/models/MinimumValidationWithSignedInteger.md) + - [MinitemsValidation](docs/models/MinitemsValidation.md) + - [MinlengthValidation](docs/models/MinlengthValidation.md) + - [MinpropertiesValidation](docs/models/MinpropertiesValidation.md) + - [ModelNot](docs/models/ModelNot.md) + - [NestedAllofToCheckValidationSemantics](docs/models/NestedAllofToCheckValidationSemantics.md) + - [NestedAnyofToCheckValidationSemantics](docs/models/NestedAnyofToCheckValidationSemantics.md) + - [NestedItems](docs/models/NestedItems.md) + - [NestedOneofToCheckValidationSemantics](docs/models/NestedOneofToCheckValidationSemantics.md) + - [NotMoreComplexSchema](docs/models/NotMoreComplexSchema.md) + - [NulCharactersInStrings](docs/models/NulCharactersInStrings.md) + - [NullTypeMatchesOnlyTheNullObject](docs/models/NullTypeMatchesOnlyTheNullObject.md) + - [NumberTypeMatchesNumbers](docs/models/NumberTypeMatchesNumbers.md) + - [ObjectPropertiesValidation](docs/models/ObjectPropertiesValidation.md) + - [Oneof](docs/models/Oneof.md) + - [OneofComplexTypes](docs/models/OneofComplexTypes.md) + - [OneofWithBaseSchema](docs/models/OneofWithBaseSchema.md) + - [OneofWithEmptySchema](docs/models/OneofWithEmptySchema.md) + - [OneofWithRequired](docs/models/OneofWithRequired.md) + - [PatternIsNotAnchored](docs/models/PatternIsNotAnchored.md) + - [PatternValidation](docs/models/PatternValidation.md) + - [PropertiesWithEscapedCharacters](docs/models/PropertiesWithEscapedCharacters.md) + - [PropertyNamedRefThatIsNotAReference](docs/models/PropertyNamedRefThatIsNotAReference.md) + - [RefInAdditionalproperties](docs/models/RefInAdditionalproperties.md) + - [RefInAllof](docs/models/RefInAllof.md) + - [RefInAnyof](docs/models/RefInAnyof.md) + - [RefInItems](docs/models/RefInItems.md) + - [RefInNot](docs/models/RefInNot.md) + - [RefInOneof](docs/models/RefInOneof.md) + - [RefInProperty](docs/models/RefInProperty.md) + - [RequiredDefaultValidation](docs/models/RequiredDefaultValidation.md) + - [RequiredValidation](docs/models/RequiredValidation.md) + - [RequiredWithEmptyArray](docs/models/RequiredWithEmptyArray.md) + - [RequiredWithEscapedCharacters](docs/models/RequiredWithEscapedCharacters.md) + - [SimpleEnumValidation](docs/models/SimpleEnumValidation.md) + - [StringTypeMatchesStrings](docs/models/StringTypeMatchesStrings.md) + - [TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing](docs/models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) + - [UniqueitemsFalseValidation](docs/models/UniqueitemsFalseValidation.md) + - [UniqueitemsValidation](docs/models/UniqueitemsValidation.md) + - [UriFormat](docs/models/UriFormat.md) + - [UriReferenceFormat](docs/models/UriReferenceFormat.md) + - [UriTemplateFormat](docs/models/UriTemplateFormat.md) + +## Documentation For Authorization + + All endpoints do not require authorization. + +## Author + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Notes for Large OpenAPI documents +If the OpenAPI document is large, imports in unit_test_api.apis and unit_test_api.models may fail with a +RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: + +Solution 1: +Use specific imports for apis and models like: +- `from unit_test_api.apis.default_api import DefaultApi` +- `from unit_test_api.model.pet import Pet` + +Solution 1: +Before importing the package, adjust the maximum recursion limit as shown below: +``` +import sys +sys.setrecursionlimit(1500) +import unit_test_api +from unit_test_api.apis import * +from unit_test_api.models import * +``` diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/dev-requirements.txt b/samples/openapi3/client/3_0_3_unit_test/python/dev-requirements.txt similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/dev-requirements.txt rename to samples/openapi3/client/3_0_3_unit_test/python/dev-requirements.txt diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/AdditionalPropertiesApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/AdditionalPropertiesApi.md new file mode 100644 index 0000000000..6b758ccf2b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/AdditionalPropertiesApi.md @@ -0,0 +1,545 @@ + +# unit_test_api.apis.tags.additional_properties_api.AdditionalPropertiesApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_additionalproperties_allows_a_schema_which_should_validate_request_body**](#post_additionalproperties_allows_a_schema_which_should_validate_request_body) | **post** /requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody | +[**post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types**](#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes | +[**post_additionalproperties_are_allowed_by_default_request_body**](#post_additionalproperties_are_allowed_by_default_request_body) | **post** /requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody | +[**post_additionalproperties_are_allowed_by_default_response_body_for_content_types**](#post_additionalproperties_are_allowed_by_default_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes | +[**post_additionalproperties_can_exist_by_itself_request_body**](#post_additionalproperties_can_exist_by_itself_request_body) | **post** /requestBody/postAdditionalpropertiesCanExistByItselfRequestBody | +[**post_additionalproperties_can_exist_by_itself_response_body_for_content_types**](#post_additionalproperties_can_exist_by_itself_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes | +[**post_additionalproperties_should_not_look_in_applicators_request_body**](#post_additionalproperties_should_not_look_in_applicators_request_body) | **post** /requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody | +[**post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types**](#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes | + +# **post_additionalproperties_allows_a_schema_which_should_validate_request_body** + +> post_additionalproperties_allows_a_schema_which_should_validate_request_body(additionalproperties_allows_a_schema_which_should_validate) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import additional_properties_api +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = additional_properties_api.AdditionalPropertiesApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesAllowsASchemaWhichShouldValidate( + foo=None, + bar=None, + ) + try: + api_response = api_instance.post_additionalproperties_allows_a_schema_which_should_validate_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AdditionalPropertiesApi->post_additionalproperties_allows_a_schema_which_should_validate_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAllowsASchemaWhichShouldValidate**](../../models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_allows_a_schema_which_should_validate_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_allows_a_schema_which_should_validate_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types** + +> AdditionalpropertiesAllowsASchemaWhichShouldValidate post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import additional_properties_api +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = additional_properties_api.AdditionalPropertiesApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AdditionalPropertiesApi->post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAllowsASchemaWhichShouldValidate**](../../models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_are_allowed_by_default_request_body** + +> post_additionalproperties_are_allowed_by_default_request_body(additionalproperties_are_allowed_by_default) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import additional_properties_api +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = additional_properties_api.AdditionalPropertiesApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesAreAllowedByDefault(None) + try: + api_response = api_instance.post_additionalproperties_are_allowed_by_default_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AdditionalPropertiesApi->post_additionalproperties_are_allowed_by_default_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAreAllowedByDefault**](../../models/AdditionalpropertiesAreAllowedByDefault.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_are_allowed_by_default_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_are_allowed_by_default_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_are_allowed_by_default_response_body_for_content_types** + +> AdditionalpropertiesAreAllowedByDefault post_additionalproperties_are_allowed_by_default_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import additional_properties_api +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = additional_properties_api.AdditionalPropertiesApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_are_allowed_by_default_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AdditionalPropertiesApi->post_additionalproperties_are_allowed_by_default_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_are_allowed_by_default_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_are_allowed_by_default_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAreAllowedByDefault**](../../models/AdditionalpropertiesAreAllowedByDefault.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_can_exist_by_itself_request_body** + +> post_additionalproperties_can_exist_by_itself_request_body(additionalproperties_can_exist_by_itself) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import additional_properties_api +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = additional_properties_api.AdditionalPropertiesApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesCanExistByItself( + key=True, + ) + try: + api_response = api_instance.post_additionalproperties_can_exist_by_itself_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AdditionalPropertiesApi->post_additionalproperties_can_exist_by_itself_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesCanExistByItself**](../../models/AdditionalpropertiesCanExistByItself.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_can_exist_by_itself_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_can_exist_by_itself_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_can_exist_by_itself_response_body_for_content_types** + +> AdditionalpropertiesCanExistByItself post_additionalproperties_can_exist_by_itself_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import additional_properties_api +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = additional_properties_api.AdditionalPropertiesApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_can_exist_by_itself_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AdditionalPropertiesApi->post_additionalproperties_can_exist_by_itself_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_can_exist_by_itself_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_can_exist_by_itself_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesCanExistByItself**](../../models/AdditionalpropertiesCanExistByItself.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_should_not_look_in_applicators_request_body** + +> post_additionalproperties_should_not_look_in_applicators_request_body(additionalproperties_should_not_look_in_applicators) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import additional_properties_api +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = additional_properties_api.AdditionalPropertiesApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesShouldNotLookInApplicators(None) + try: + api_response = api_instance.post_additionalproperties_should_not_look_in_applicators_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AdditionalPropertiesApi->post_additionalproperties_should_not_look_in_applicators_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesShouldNotLookInApplicators**](../../models/AdditionalpropertiesShouldNotLookInApplicators.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_should_not_look_in_applicators_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_should_not_look_in_applicators_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types** + +> AdditionalpropertiesShouldNotLookInApplicators post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import additional_properties_api +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = additional_properties_api.AdditionalPropertiesApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AdditionalPropertiesApi->post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesShouldNotLookInApplicators**](../../models/AdditionalpropertiesShouldNotLookInApplicators.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/AllOfApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/AllOfApi.md new file mode 100644 index 0000000000..16996cfc81 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/AllOfApi.md @@ -0,0 +1,1205 @@ + +# unit_test_api.apis.tags.all_of_api.AllOfApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_allof_combined_with_anyof_oneof_request_body**](#post_allof_combined_with_anyof_oneof_request_body) | **post** /requestBody/postAllofCombinedWithAnyofOneofRequestBody | +[**post_allof_combined_with_anyof_oneof_response_body_for_content_types**](#post_allof_combined_with_anyof_oneof_response_body_for_content_types) | **post** /responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes | +[**post_allof_request_body**](#post_allof_request_body) | **post** /requestBody/postAllofRequestBody | +[**post_allof_response_body_for_content_types**](#post_allof_response_body_for_content_types) | **post** /responseBody/postAllofResponseBodyForContentTypes | +[**post_allof_simple_types_request_body**](#post_allof_simple_types_request_body) | **post** /requestBody/postAllofSimpleTypesRequestBody | +[**post_allof_simple_types_response_body_for_content_types**](#post_allof_simple_types_response_body_for_content_types) | **post** /responseBody/postAllofSimpleTypesResponseBodyForContentTypes | +[**post_allof_with_base_schema_request_body**](#post_allof_with_base_schema_request_body) | **post** /requestBody/postAllofWithBaseSchemaRequestBody | +[**post_allof_with_base_schema_response_body_for_content_types**](#post_allof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes | +[**post_allof_with_one_empty_schema_request_body**](#post_allof_with_one_empty_schema_request_body) | **post** /requestBody/postAllofWithOneEmptySchemaRequestBody | +[**post_allof_with_one_empty_schema_response_body_for_content_types**](#post_allof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_the_first_empty_schema_request_body**](#post_allof_with_the_first_empty_schema_request_body) | **post** /requestBody/postAllofWithTheFirstEmptySchemaRequestBody | +[**post_allof_with_the_first_empty_schema_response_body_for_content_types**](#post_allof_with_the_first_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_the_last_empty_schema_request_body**](#post_allof_with_the_last_empty_schema_request_body) | **post** /requestBody/postAllofWithTheLastEmptySchemaRequestBody | +[**post_allof_with_the_last_empty_schema_response_body_for_content_types**](#post_allof_with_the_last_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_two_empty_schemas_request_body**](#post_allof_with_two_empty_schemas_request_body) | **post** /requestBody/postAllofWithTwoEmptySchemasRequestBody | +[**post_allof_with_two_empty_schemas_response_body_for_content_types**](#post_allof_with_two_empty_schemas_response_body_for_content_types) | **post** /responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes | +[**post_nested_allof_to_check_validation_semantics_request_body**](#post_nested_allof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAllofToCheckValidationSemanticsRequestBody | +[**post_nested_allof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_allof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes | + +# **post_allof_combined_with_anyof_oneof_request_body** + +> post_allof_combined_with_anyof_oneof_request_body(allof_combined_with_anyof_oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofCombinedWithAnyofOneof(None) + try: + api_response = api_instance.post_allof_combined_with_anyof_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_combined_with_anyof_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofCombinedWithAnyofOneof**](../../models/AllofCombinedWithAnyofOneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_combined_with_anyof_oneof_request_body.ApiResponseFor200) | success + +#### post_allof_combined_with_anyof_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_combined_with_anyof_oneof_response_body_for_content_types** + +> AllofCombinedWithAnyofOneof post_allof_combined_with_anyof_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_combined_with_anyof_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_combined_with_anyof_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_combined_with_anyof_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_combined_with_anyof_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofCombinedWithAnyofOneof**](../../models/AllofCombinedWithAnyofOneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_request_body** + +> post_allof_request_body(allof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof import Allof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example passing only required values which don't have defaults set + body = Allof(None) + try: + api_response = api_instance.post_allof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Allof**](../../models/Allof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_request_body.ApiResponseFor200) | success + +#### post_allof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_response_body_for_content_types** + +> Allof post_allof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof import Allof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Allof**](../../models/Allof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_simple_types_request_body** + +> post_allof_simple_types_request_body(allof_simple_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_simple_types import AllofSimpleTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofSimpleTypes(None) + try: + api_response = api_instance.post_allof_simple_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_simple_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofSimpleTypes**](../../models/AllofSimpleTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_simple_types_request_body.ApiResponseFor200) | success + +#### post_allof_simple_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_simple_types_response_body_for_content_types** + +> AllofSimpleTypes post_allof_simple_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_simple_types import AllofSimpleTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_simple_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_simple_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_simple_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_simple_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofSimpleTypes**](../../models/AllofSimpleTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_base_schema_request_body** + +> post_allof_with_base_schema_request_body(allof_with_base_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithBaseSchema({}) + try: + api_response = api_instance.post_allof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithBaseSchema**](../../models/AllofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_base_schema_response_body_for_content_types** + +> AllofWithBaseSchema post_allof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithBaseSchema**](../../models/AllofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_one_empty_schema_request_body** + +> post_allof_with_one_empty_schema_request_body(allof_with_one_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithOneEmptySchema(None) + try: + api_response = api_instance.post_allof_with_one_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_one_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithOneEmptySchema**](../../models/AllofWithOneEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_one_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_one_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_one_empty_schema_response_body_for_content_types** + +> AllofWithOneEmptySchema post_allof_with_one_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_one_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_one_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithOneEmptySchema**](../../models/AllofWithOneEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_first_empty_schema_request_body** + +> post_allof_with_the_first_empty_schema_request_body(allof_with_the_first_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTheFirstEmptySchema(None) + try: + api_response = api_instance.post_allof_with_the_first_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_the_first_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheFirstEmptySchema**](../../models/AllofWithTheFirstEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_first_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_the_first_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_first_empty_schema_response_body_for_content_types** + +> AllofWithTheFirstEmptySchema post_allof_with_the_first_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_the_first_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_the_first_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_first_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_the_first_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheFirstEmptySchema**](../../models/AllofWithTheFirstEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_last_empty_schema_request_body** + +> post_allof_with_the_last_empty_schema_request_body(allof_with_the_last_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTheLastEmptySchema(None) + try: + api_response = api_instance.post_allof_with_the_last_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_the_last_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheLastEmptySchema**](../../models/AllofWithTheLastEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_last_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_the_last_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_last_empty_schema_response_body_for_content_types** + +> AllofWithTheLastEmptySchema post_allof_with_the_last_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_the_last_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_the_last_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_last_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_the_last_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheLastEmptySchema**](../../models/AllofWithTheLastEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_two_empty_schemas_request_body** + +> post_allof_with_two_empty_schemas_request_body(allof_with_two_empty_schemas) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTwoEmptySchemas(None) + try: + api_response = api_instance.post_allof_with_two_empty_schemas_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_two_empty_schemas_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTwoEmptySchemas**](../../models/AllofWithTwoEmptySchemas.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_two_empty_schemas_request_body.ApiResponseFor200) | success + +#### post_allof_with_two_empty_schemas_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_two_empty_schemas_response_body_for_content_types** + +> AllofWithTwoEmptySchemas post_allof_with_two_empty_schemas_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_two_empty_schemas_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_allof_with_two_empty_schemas_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_two_empty_schemas_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_two_empty_schemas_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTwoEmptySchemas**](../../models/AllofWithTwoEmptySchemas.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_allof_to_check_validation_semantics_request_body** + +> post_nested_allof_to_check_validation_semantics_request_body(nested_allof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedAllofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_allof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_nested_allof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAllofToCheckValidationSemantics**](../../models/NestedAllofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_allof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_allof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_allof_to_check_validation_semantics_response_body_for_content_types** + +> NestedAllofToCheckValidationSemantics post_nested_allof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import all_of_api +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = all_of_api.AllOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_allof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AllOfApi->post_nested_allof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_allof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_allof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAllofToCheckValidationSemantics**](../../models/NestedAllofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/AnyOfApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/AnyOfApi.md new file mode 100644 index 0000000000..8f0a035a81 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/AnyOfApi.md @@ -0,0 +1,673 @@ + +# unit_test_api.apis.tags.any_of_api.AnyOfApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_anyof_complex_types_request_body**](#post_anyof_complex_types_request_body) | **post** /requestBody/postAnyofComplexTypesRequestBody | +[**post_anyof_complex_types_response_body_for_content_types**](#post_anyof_complex_types_response_body_for_content_types) | **post** /responseBody/postAnyofComplexTypesResponseBodyForContentTypes | +[**post_anyof_request_body**](#post_anyof_request_body) | **post** /requestBody/postAnyofRequestBody | +[**post_anyof_response_body_for_content_types**](#post_anyof_response_body_for_content_types) | **post** /responseBody/postAnyofResponseBodyForContentTypes | +[**post_anyof_with_base_schema_request_body**](#post_anyof_with_base_schema_request_body) | **post** /requestBody/postAnyofWithBaseSchemaRequestBody | +[**post_anyof_with_base_schema_response_body_for_content_types**](#post_anyof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes | +[**post_anyof_with_one_empty_schema_request_body**](#post_anyof_with_one_empty_schema_request_body) | **post** /requestBody/postAnyofWithOneEmptySchemaRequestBody | +[**post_anyof_with_one_empty_schema_response_body_for_content_types**](#post_anyof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes | +[**post_nested_anyof_to_check_validation_semantics_request_body**](#post_nested_anyof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody | +[**post_nested_anyof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes | + +# **post_anyof_complex_types_request_body** + +> post_anyof_complex_types_request_body(anyof_complex_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofComplexTypes(None) + try: + api_response = api_instance.post_anyof_complex_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_anyof_complex_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofComplexTypes**](../../models/AnyofComplexTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_complex_types_request_body.ApiResponseFor200) | success + +#### post_anyof_complex_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_complex_types_response_body_for_content_types** + +> AnyofComplexTypes post_anyof_complex_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_complex_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_anyof_complex_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_complex_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_complex_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofComplexTypes**](../../models/AnyofComplexTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_request_body** + +> post_anyof_request_body(anyof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.anyof import Anyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example passing only required values which don't have defaults set + body = Anyof(None) + try: + api_response = api_instance.post_anyof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_anyof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Anyof**](../../models/Anyof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_request_body.ApiResponseFor200) | success + +#### post_anyof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_response_body_for_content_types** + +> Anyof post_anyof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.anyof import Anyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_anyof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Anyof**](../../models/Anyof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_base_schema_request_body** + +> post_anyof_with_base_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofWithBaseSchema("body_example") + try: + api_response = api_instance.post_anyof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_anyof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithBaseSchema**](../../models/AnyofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_anyof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_base_schema_response_body_for_content_types** + +> AnyofWithBaseSchema post_anyof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_anyof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithBaseSchema**](../../models/AnyofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_one_empty_schema_request_body** + +> post_anyof_with_one_empty_schema_request_body(anyof_with_one_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofWithOneEmptySchema(None) + try: + api_response = api_instance.post_anyof_with_one_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_anyof_with_one_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithOneEmptySchema**](../../models/AnyofWithOneEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_one_empty_schema_request_body.ApiResponseFor200) | success + +#### post_anyof_with_one_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_one_empty_schema_response_body_for_content_types** + +> AnyofWithOneEmptySchema post_anyof_with_one_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_with_one_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_anyof_with_one_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithOneEmptySchema**](../../models/AnyofWithOneEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_anyof_to_check_validation_semantics_request_body** + +> post_nested_anyof_to_check_validation_semantics_request_body(nested_anyof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedAnyofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_anyof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_nested_anyof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAnyofToCheckValidationSemantics**](../../models/NestedAnyofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_anyof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_anyof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_anyof_to_check_validation_semantics_response_body_for_content_types** + +> NestedAnyofToCheckValidationSemantics post_nested_anyof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import any_of_api +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = any_of_api.AnyOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_anyof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling AnyOfApi->post_nested_anyof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAnyofToCheckValidationSemantics**](../../models/NestedAnyofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ContentTypeJsonApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ContentTypeJsonApi.md new file mode 100644 index 0000000000..0a1a6bd184 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ContentTypeJsonApi.md @@ -0,0 +1,11681 @@ + +# unit_test_api.apis.tags.content_type_json_api.ContentTypeJsonApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_additionalproperties_allows_a_schema_which_should_validate_request_body**](#post_additionalproperties_allows_a_schema_which_should_validate_request_body) | **post** /requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody | +[**post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types**](#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes | +[**post_additionalproperties_are_allowed_by_default_request_body**](#post_additionalproperties_are_allowed_by_default_request_body) | **post** /requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody | +[**post_additionalproperties_are_allowed_by_default_response_body_for_content_types**](#post_additionalproperties_are_allowed_by_default_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes | +[**post_additionalproperties_can_exist_by_itself_request_body**](#post_additionalproperties_can_exist_by_itself_request_body) | **post** /requestBody/postAdditionalpropertiesCanExistByItselfRequestBody | +[**post_additionalproperties_can_exist_by_itself_response_body_for_content_types**](#post_additionalproperties_can_exist_by_itself_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes | +[**post_additionalproperties_should_not_look_in_applicators_request_body**](#post_additionalproperties_should_not_look_in_applicators_request_body) | **post** /requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody | +[**post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types**](#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes | +[**post_allof_combined_with_anyof_oneof_request_body**](#post_allof_combined_with_anyof_oneof_request_body) | **post** /requestBody/postAllofCombinedWithAnyofOneofRequestBody | +[**post_allof_combined_with_anyof_oneof_response_body_for_content_types**](#post_allof_combined_with_anyof_oneof_response_body_for_content_types) | **post** /responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes | +[**post_allof_request_body**](#post_allof_request_body) | **post** /requestBody/postAllofRequestBody | +[**post_allof_response_body_for_content_types**](#post_allof_response_body_for_content_types) | **post** /responseBody/postAllofResponseBodyForContentTypes | +[**post_allof_simple_types_request_body**](#post_allof_simple_types_request_body) | **post** /requestBody/postAllofSimpleTypesRequestBody | +[**post_allof_simple_types_response_body_for_content_types**](#post_allof_simple_types_response_body_for_content_types) | **post** /responseBody/postAllofSimpleTypesResponseBodyForContentTypes | +[**post_allof_with_base_schema_request_body**](#post_allof_with_base_schema_request_body) | **post** /requestBody/postAllofWithBaseSchemaRequestBody | +[**post_allof_with_base_schema_response_body_for_content_types**](#post_allof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes | +[**post_allof_with_one_empty_schema_request_body**](#post_allof_with_one_empty_schema_request_body) | **post** /requestBody/postAllofWithOneEmptySchemaRequestBody | +[**post_allof_with_one_empty_schema_response_body_for_content_types**](#post_allof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_the_first_empty_schema_request_body**](#post_allof_with_the_first_empty_schema_request_body) | **post** /requestBody/postAllofWithTheFirstEmptySchemaRequestBody | +[**post_allof_with_the_first_empty_schema_response_body_for_content_types**](#post_allof_with_the_first_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_the_last_empty_schema_request_body**](#post_allof_with_the_last_empty_schema_request_body) | **post** /requestBody/postAllofWithTheLastEmptySchemaRequestBody | +[**post_allof_with_the_last_empty_schema_response_body_for_content_types**](#post_allof_with_the_last_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_two_empty_schemas_request_body**](#post_allof_with_two_empty_schemas_request_body) | **post** /requestBody/postAllofWithTwoEmptySchemasRequestBody | +[**post_allof_with_two_empty_schemas_response_body_for_content_types**](#post_allof_with_two_empty_schemas_response_body_for_content_types) | **post** /responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes | +[**post_anyof_complex_types_request_body**](#post_anyof_complex_types_request_body) | **post** /requestBody/postAnyofComplexTypesRequestBody | +[**post_anyof_complex_types_response_body_for_content_types**](#post_anyof_complex_types_response_body_for_content_types) | **post** /responseBody/postAnyofComplexTypesResponseBodyForContentTypes | +[**post_anyof_request_body**](#post_anyof_request_body) | **post** /requestBody/postAnyofRequestBody | +[**post_anyof_response_body_for_content_types**](#post_anyof_response_body_for_content_types) | **post** /responseBody/postAnyofResponseBodyForContentTypes | +[**post_anyof_with_base_schema_request_body**](#post_anyof_with_base_schema_request_body) | **post** /requestBody/postAnyofWithBaseSchemaRequestBody | +[**post_anyof_with_base_schema_response_body_for_content_types**](#post_anyof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes | +[**post_anyof_with_one_empty_schema_request_body**](#post_anyof_with_one_empty_schema_request_body) | **post** /requestBody/postAnyofWithOneEmptySchemaRequestBody | +[**post_anyof_with_one_empty_schema_response_body_for_content_types**](#post_anyof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes | +[**post_array_type_matches_arrays_request_body**](#post_array_type_matches_arrays_request_body) | **post** /requestBody/postArrayTypeMatchesArraysRequestBody | +[**post_array_type_matches_arrays_response_body_for_content_types**](#post_array_type_matches_arrays_response_body_for_content_types) | **post** /responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes | +[**post_boolean_type_matches_booleans_request_body**](#post_boolean_type_matches_booleans_request_body) | **post** /requestBody/postBooleanTypeMatchesBooleansRequestBody | +[**post_boolean_type_matches_booleans_response_body_for_content_types**](#post_boolean_type_matches_booleans_response_body_for_content_types) | **post** /responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes | +[**post_by_int_request_body**](#post_by_int_request_body) | **post** /requestBody/postByIntRequestBody | +[**post_by_int_response_body_for_content_types**](#post_by_int_response_body_for_content_types) | **post** /responseBody/postByIntResponseBodyForContentTypes | +[**post_by_number_request_body**](#post_by_number_request_body) | **post** /requestBody/postByNumberRequestBody | +[**post_by_number_response_body_for_content_types**](#post_by_number_response_body_for_content_types) | **post** /responseBody/postByNumberResponseBodyForContentTypes | +[**post_by_small_number_request_body**](#post_by_small_number_request_body) | **post** /requestBody/postBySmallNumberRequestBody | +[**post_by_small_number_response_body_for_content_types**](#post_by_small_number_response_body_for_content_types) | **post** /responseBody/postBySmallNumberResponseBodyForContentTypes | +[**post_date_time_format_request_body**](#post_date_time_format_request_body) | **post** /requestBody/postDateTimeFormatRequestBody | +[**post_date_time_format_response_body_for_content_types**](#post_date_time_format_response_body_for_content_types) | **post** /responseBody/postDateTimeFormatResponseBodyForContentTypes | +[**post_email_format_request_body**](#post_email_format_request_body) | **post** /requestBody/postEmailFormatRequestBody | +[**post_email_format_response_body_for_content_types**](#post_email_format_response_body_for_content_types) | **post** /responseBody/postEmailFormatResponseBodyForContentTypes | +[**post_enum_with0_does_not_match_false_request_body**](#post_enum_with0_does_not_match_false_request_body) | **post** /requestBody/postEnumWith0DoesNotMatchFalseRequestBody | +[**post_enum_with0_does_not_match_false_response_body_for_content_types**](#post_enum_with0_does_not_match_false_response_body_for_content_types) | **post** /responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes | +[**post_enum_with1_does_not_match_true_request_body**](#post_enum_with1_does_not_match_true_request_body) | **post** /requestBody/postEnumWith1DoesNotMatchTrueRequestBody | +[**post_enum_with1_does_not_match_true_response_body_for_content_types**](#post_enum_with1_does_not_match_true_response_body_for_content_types) | **post** /responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes | +[**post_enum_with_escaped_characters_request_body**](#post_enum_with_escaped_characters_request_body) | **post** /requestBody/postEnumWithEscapedCharactersRequestBody | +[**post_enum_with_escaped_characters_response_body_for_content_types**](#post_enum_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes | +[**post_enum_with_false_does_not_match0_request_body**](#post_enum_with_false_does_not_match0_request_body) | **post** /requestBody/postEnumWithFalseDoesNotMatch0RequestBody | +[**post_enum_with_false_does_not_match0_response_body_for_content_types**](#post_enum_with_false_does_not_match0_response_body_for_content_types) | **post** /responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes | +[**post_enum_with_true_does_not_match1_request_body**](#post_enum_with_true_does_not_match1_request_body) | **post** /requestBody/postEnumWithTrueDoesNotMatch1RequestBody | +[**post_enum_with_true_does_not_match1_response_body_for_content_types**](#post_enum_with_true_does_not_match1_response_body_for_content_types) | **post** /responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes | +[**post_enums_in_properties_request_body**](#post_enums_in_properties_request_body) | **post** /requestBody/postEnumsInPropertiesRequestBody | +[**post_enums_in_properties_response_body_for_content_types**](#post_enums_in_properties_response_body_for_content_types) | **post** /responseBody/postEnumsInPropertiesResponseBodyForContentTypes | +[**post_forbidden_property_request_body**](#post_forbidden_property_request_body) | **post** /requestBody/postForbiddenPropertyRequestBody | +[**post_forbidden_property_response_body_for_content_types**](#post_forbidden_property_response_body_for_content_types) | **post** /responseBody/postForbiddenPropertyResponseBodyForContentTypes | +[**post_hostname_format_request_body**](#post_hostname_format_request_body) | **post** /requestBody/postHostnameFormatRequestBody | +[**post_hostname_format_response_body_for_content_types**](#post_hostname_format_response_body_for_content_types) | **post** /responseBody/postHostnameFormatResponseBodyForContentTypes | +[**post_integer_type_matches_integers_request_body**](#post_integer_type_matches_integers_request_body) | **post** /requestBody/postIntegerTypeMatchesIntegersRequestBody | +[**post_integer_type_matches_integers_response_body_for_content_types**](#post_integer_type_matches_integers_response_body_for_content_types) | **post** /responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes | +[**post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body**](#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body) | **post** /requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody | +[**post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types**](#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types) | **post** /responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes | +[**post_invalid_string_value_for_default_request_body**](#post_invalid_string_value_for_default_request_body) | **post** /requestBody/postInvalidStringValueForDefaultRequestBody | +[**post_invalid_string_value_for_default_response_body_for_content_types**](#post_invalid_string_value_for_default_response_body_for_content_types) | **post** /responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes | +[**post_ipv4_format_request_body**](#post_ipv4_format_request_body) | **post** /requestBody/postIpv4FormatRequestBody | +[**post_ipv4_format_response_body_for_content_types**](#post_ipv4_format_response_body_for_content_types) | **post** /responseBody/postIpv4FormatResponseBodyForContentTypes | +[**post_ipv6_format_request_body**](#post_ipv6_format_request_body) | **post** /requestBody/postIpv6FormatRequestBody | +[**post_ipv6_format_response_body_for_content_types**](#post_ipv6_format_response_body_for_content_types) | **post** /responseBody/postIpv6FormatResponseBodyForContentTypes | +[**post_json_pointer_format_request_body**](#post_json_pointer_format_request_body) | **post** /requestBody/postJsonPointerFormatRequestBody | +[**post_json_pointer_format_response_body_for_content_types**](#post_json_pointer_format_response_body_for_content_types) | **post** /responseBody/postJsonPointerFormatResponseBodyForContentTypes | +[**post_maximum_validation_request_body**](#post_maximum_validation_request_body) | **post** /requestBody/postMaximumValidationRequestBody | +[**post_maximum_validation_response_body_for_content_types**](#post_maximum_validation_response_body_for_content_types) | **post** /responseBody/postMaximumValidationResponseBodyForContentTypes | +[**post_maximum_validation_with_unsigned_integer_request_body**](#post_maximum_validation_with_unsigned_integer_request_body) | **post** /requestBody/postMaximumValidationWithUnsignedIntegerRequestBody | +[**post_maximum_validation_with_unsigned_integer_response_body_for_content_types**](#post_maximum_validation_with_unsigned_integer_response_body_for_content_types) | **post** /responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes | +[**post_maxitems_validation_request_body**](#post_maxitems_validation_request_body) | **post** /requestBody/postMaxitemsValidationRequestBody | +[**post_maxitems_validation_response_body_for_content_types**](#post_maxitems_validation_response_body_for_content_types) | **post** /responseBody/postMaxitemsValidationResponseBodyForContentTypes | +[**post_maxlength_validation_request_body**](#post_maxlength_validation_request_body) | **post** /requestBody/postMaxlengthValidationRequestBody | +[**post_maxlength_validation_response_body_for_content_types**](#post_maxlength_validation_response_body_for_content_types) | **post** /responseBody/postMaxlengthValidationResponseBodyForContentTypes | +[**post_maxproperties0_means_the_object_is_empty_request_body**](#post_maxproperties0_means_the_object_is_empty_request_body) | **post** /requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody | +[**post_maxproperties0_means_the_object_is_empty_response_body_for_content_types**](#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types) | **post** /responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes | +[**post_maxproperties_validation_request_body**](#post_maxproperties_validation_request_body) | **post** /requestBody/postMaxpropertiesValidationRequestBody | +[**post_maxproperties_validation_response_body_for_content_types**](#post_maxproperties_validation_response_body_for_content_types) | **post** /responseBody/postMaxpropertiesValidationResponseBodyForContentTypes | +[**post_minimum_validation_request_body**](#post_minimum_validation_request_body) | **post** /requestBody/postMinimumValidationRequestBody | +[**post_minimum_validation_response_body_for_content_types**](#post_minimum_validation_response_body_for_content_types) | **post** /responseBody/postMinimumValidationResponseBodyForContentTypes | +[**post_minimum_validation_with_signed_integer_request_body**](#post_minimum_validation_with_signed_integer_request_body) | **post** /requestBody/postMinimumValidationWithSignedIntegerRequestBody | +[**post_minimum_validation_with_signed_integer_response_body_for_content_types**](#post_minimum_validation_with_signed_integer_response_body_for_content_types) | **post** /responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes | +[**post_minitems_validation_request_body**](#post_minitems_validation_request_body) | **post** /requestBody/postMinitemsValidationRequestBody | +[**post_minitems_validation_response_body_for_content_types**](#post_minitems_validation_response_body_for_content_types) | **post** /responseBody/postMinitemsValidationResponseBodyForContentTypes | +[**post_minlength_validation_request_body**](#post_minlength_validation_request_body) | **post** /requestBody/postMinlengthValidationRequestBody | +[**post_minlength_validation_response_body_for_content_types**](#post_minlength_validation_response_body_for_content_types) | **post** /responseBody/postMinlengthValidationResponseBodyForContentTypes | +[**post_minproperties_validation_request_body**](#post_minproperties_validation_request_body) | **post** /requestBody/postMinpropertiesValidationRequestBody | +[**post_minproperties_validation_response_body_for_content_types**](#post_minproperties_validation_response_body_for_content_types) | **post** /responseBody/postMinpropertiesValidationResponseBodyForContentTypes | +[**post_nested_allof_to_check_validation_semantics_request_body**](#post_nested_allof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAllofToCheckValidationSemanticsRequestBody | +[**post_nested_allof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_allof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_nested_anyof_to_check_validation_semantics_request_body**](#post_nested_anyof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody | +[**post_nested_anyof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_nested_items_request_body**](#post_nested_items_request_body) | **post** /requestBody/postNestedItemsRequestBody | +[**post_nested_items_response_body_for_content_types**](#post_nested_items_response_body_for_content_types) | **post** /responseBody/postNestedItemsResponseBodyForContentTypes | +[**post_nested_oneof_to_check_validation_semantics_request_body**](#post_nested_oneof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedOneofToCheckValidationSemanticsRequestBody | +[**post_nested_oneof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_not_more_complex_schema_request_body**](#post_not_more_complex_schema_request_body) | **post** /requestBody/postNotMoreComplexSchemaRequestBody | +[**post_not_more_complex_schema_response_body_for_content_types**](#post_not_more_complex_schema_response_body_for_content_types) | **post** /responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes | +[**post_not_request_body**](#post_not_request_body) | **post** /requestBody/postNotRequestBody | +[**post_not_response_body_for_content_types**](#post_not_response_body_for_content_types) | **post** /responseBody/postNotResponseBodyForContentTypes | +[**post_nul_characters_in_strings_request_body**](#post_nul_characters_in_strings_request_body) | **post** /requestBody/postNulCharactersInStringsRequestBody | +[**post_nul_characters_in_strings_response_body_for_content_types**](#post_nul_characters_in_strings_response_body_for_content_types) | **post** /responseBody/postNulCharactersInStringsResponseBodyForContentTypes | +[**post_null_type_matches_only_the_null_object_request_body**](#post_null_type_matches_only_the_null_object_request_body) | **post** /requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody | +[**post_null_type_matches_only_the_null_object_response_body_for_content_types**](#post_null_type_matches_only_the_null_object_response_body_for_content_types) | **post** /responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes | +[**post_number_type_matches_numbers_request_body**](#post_number_type_matches_numbers_request_body) | **post** /requestBody/postNumberTypeMatchesNumbersRequestBody | +[**post_number_type_matches_numbers_response_body_for_content_types**](#post_number_type_matches_numbers_response_body_for_content_types) | **post** /responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes | +[**post_object_properties_validation_request_body**](#post_object_properties_validation_request_body) | **post** /requestBody/postObjectPropertiesValidationRequestBody | +[**post_object_properties_validation_response_body_for_content_types**](#post_object_properties_validation_response_body_for_content_types) | **post** /responseBody/postObjectPropertiesValidationResponseBodyForContentTypes | +[**post_object_type_matches_objects_request_body**](#post_object_type_matches_objects_request_body) | **post** /requestBody/postObjectTypeMatchesObjectsRequestBody | +[**post_object_type_matches_objects_response_body_for_content_types**](#post_object_type_matches_objects_response_body_for_content_types) | **post** /responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes | +[**post_oneof_complex_types_request_body**](#post_oneof_complex_types_request_body) | **post** /requestBody/postOneofComplexTypesRequestBody | +[**post_oneof_complex_types_response_body_for_content_types**](#post_oneof_complex_types_response_body_for_content_types) | **post** /responseBody/postOneofComplexTypesResponseBodyForContentTypes | +[**post_oneof_request_body**](#post_oneof_request_body) | **post** /requestBody/postOneofRequestBody | +[**post_oneof_response_body_for_content_types**](#post_oneof_response_body_for_content_types) | **post** /responseBody/postOneofResponseBodyForContentTypes | +[**post_oneof_with_base_schema_request_body**](#post_oneof_with_base_schema_request_body) | **post** /requestBody/postOneofWithBaseSchemaRequestBody | +[**post_oneof_with_base_schema_response_body_for_content_types**](#post_oneof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes | +[**post_oneof_with_empty_schema_request_body**](#post_oneof_with_empty_schema_request_body) | **post** /requestBody/postOneofWithEmptySchemaRequestBody | +[**post_oneof_with_empty_schema_response_body_for_content_types**](#post_oneof_with_empty_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes | +[**post_oneof_with_required_request_body**](#post_oneof_with_required_request_body) | **post** /requestBody/postOneofWithRequiredRequestBody | +[**post_oneof_with_required_response_body_for_content_types**](#post_oneof_with_required_response_body_for_content_types) | **post** /responseBody/postOneofWithRequiredResponseBodyForContentTypes | +[**post_pattern_is_not_anchored_request_body**](#post_pattern_is_not_anchored_request_body) | **post** /requestBody/postPatternIsNotAnchoredRequestBody | +[**post_pattern_is_not_anchored_response_body_for_content_types**](#post_pattern_is_not_anchored_response_body_for_content_types) | **post** /responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes | +[**post_pattern_validation_request_body**](#post_pattern_validation_request_body) | **post** /requestBody/postPatternValidationRequestBody | +[**post_pattern_validation_response_body_for_content_types**](#post_pattern_validation_response_body_for_content_types) | **post** /responseBody/postPatternValidationResponseBodyForContentTypes | +[**post_properties_with_escaped_characters_request_body**](#post_properties_with_escaped_characters_request_body) | **post** /requestBody/postPropertiesWithEscapedCharactersRequestBody | +[**post_properties_with_escaped_characters_response_body_for_content_types**](#post_properties_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes | +[**post_property_named_ref_that_is_not_a_reference_request_body**](#post_property_named_ref_that_is_not_a_reference_request_body) | **post** /requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody | +[**post_property_named_ref_that_is_not_a_reference_response_body_for_content_types**](#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types) | **post** /responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes | +[**post_ref_in_additionalproperties_request_body**](#post_ref_in_additionalproperties_request_body) | **post** /requestBody/postRefInAdditionalpropertiesRequestBody | +[**post_ref_in_additionalproperties_response_body_for_content_types**](#post_ref_in_additionalproperties_response_body_for_content_types) | **post** /responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes | +[**post_ref_in_allof_request_body**](#post_ref_in_allof_request_body) | **post** /requestBody/postRefInAllofRequestBody | +[**post_ref_in_allof_response_body_for_content_types**](#post_ref_in_allof_response_body_for_content_types) | **post** /responseBody/postRefInAllofResponseBodyForContentTypes | +[**post_ref_in_anyof_request_body**](#post_ref_in_anyof_request_body) | **post** /requestBody/postRefInAnyofRequestBody | +[**post_ref_in_anyof_response_body_for_content_types**](#post_ref_in_anyof_response_body_for_content_types) | **post** /responseBody/postRefInAnyofResponseBodyForContentTypes | +[**post_ref_in_items_request_body**](#post_ref_in_items_request_body) | **post** /requestBody/postRefInItemsRequestBody | +[**post_ref_in_items_response_body_for_content_types**](#post_ref_in_items_response_body_for_content_types) | **post** /responseBody/postRefInItemsResponseBodyForContentTypes | +[**post_ref_in_not_request_body**](#post_ref_in_not_request_body) | **post** /requestBody/postRefInNotRequestBody | +[**post_ref_in_not_response_body_for_content_types**](#post_ref_in_not_response_body_for_content_types) | **post** /responseBody/postRefInNotResponseBodyForContentTypes | +[**post_ref_in_oneof_request_body**](#post_ref_in_oneof_request_body) | **post** /requestBody/postRefInOneofRequestBody | +[**post_ref_in_oneof_response_body_for_content_types**](#post_ref_in_oneof_response_body_for_content_types) | **post** /responseBody/postRefInOneofResponseBodyForContentTypes | +[**post_ref_in_property_request_body**](#post_ref_in_property_request_body) | **post** /requestBody/postRefInPropertyRequestBody | +[**post_ref_in_property_response_body_for_content_types**](#post_ref_in_property_response_body_for_content_types) | **post** /responseBody/postRefInPropertyResponseBodyForContentTypes | +[**post_required_default_validation_request_body**](#post_required_default_validation_request_body) | **post** /requestBody/postRequiredDefaultValidationRequestBody | +[**post_required_default_validation_response_body_for_content_types**](#post_required_default_validation_response_body_for_content_types) | **post** /responseBody/postRequiredDefaultValidationResponseBodyForContentTypes | +[**post_required_validation_request_body**](#post_required_validation_request_body) | **post** /requestBody/postRequiredValidationRequestBody | +[**post_required_validation_response_body_for_content_types**](#post_required_validation_response_body_for_content_types) | **post** /responseBody/postRequiredValidationResponseBodyForContentTypes | +[**post_required_with_empty_array_request_body**](#post_required_with_empty_array_request_body) | **post** /requestBody/postRequiredWithEmptyArrayRequestBody | +[**post_required_with_empty_array_response_body_for_content_types**](#post_required_with_empty_array_response_body_for_content_types) | **post** /responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes | +[**post_required_with_escaped_characters_request_body**](#post_required_with_escaped_characters_request_body) | **post** /requestBody/postRequiredWithEscapedCharactersRequestBody | +[**post_required_with_escaped_characters_response_body_for_content_types**](#post_required_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes | +[**post_simple_enum_validation_request_body**](#post_simple_enum_validation_request_body) | **post** /requestBody/postSimpleEnumValidationRequestBody | +[**post_simple_enum_validation_response_body_for_content_types**](#post_simple_enum_validation_response_body_for_content_types) | **post** /responseBody/postSimpleEnumValidationResponseBodyForContentTypes | +[**post_string_type_matches_strings_request_body**](#post_string_type_matches_strings_request_body) | **post** /requestBody/postStringTypeMatchesStringsRequestBody | +[**post_string_type_matches_strings_response_body_for_content_types**](#post_string_type_matches_strings_response_body_for_content_types) | **post** /responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes | +[**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body**](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body) | **post** /requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody | +[**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types**](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types) | **post** /responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes | +[**post_uniqueitems_false_validation_request_body**](#post_uniqueitems_false_validation_request_body) | **post** /requestBody/postUniqueitemsFalseValidationRequestBody | +[**post_uniqueitems_false_validation_response_body_for_content_types**](#post_uniqueitems_false_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes | +[**post_uniqueitems_validation_request_body**](#post_uniqueitems_validation_request_body) | **post** /requestBody/postUniqueitemsValidationRequestBody | +[**post_uniqueitems_validation_response_body_for_content_types**](#post_uniqueitems_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsValidationResponseBodyForContentTypes | +[**post_uri_format_request_body**](#post_uri_format_request_body) | **post** /requestBody/postUriFormatRequestBody | +[**post_uri_format_response_body_for_content_types**](#post_uri_format_response_body_for_content_types) | **post** /responseBody/postUriFormatResponseBodyForContentTypes | +[**post_uri_reference_format_request_body**](#post_uri_reference_format_request_body) | **post** /requestBody/postUriReferenceFormatRequestBody | +[**post_uri_reference_format_response_body_for_content_types**](#post_uri_reference_format_response_body_for_content_types) | **post** /responseBody/postUriReferenceFormatResponseBodyForContentTypes | +[**post_uri_template_format_request_body**](#post_uri_template_format_request_body) | **post** /requestBody/postUriTemplateFormatRequestBody | +[**post_uri_template_format_response_body_for_content_types**](#post_uri_template_format_response_body_for_content_types) | **post** /responseBody/postUriTemplateFormatResponseBodyForContentTypes | + +# **post_additionalproperties_allows_a_schema_which_should_validate_request_body** + +> post_additionalproperties_allows_a_schema_which_should_validate_request_body(additionalproperties_allows_a_schema_which_should_validate) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesAllowsASchemaWhichShouldValidate( + foo=None, + bar=None, + ) + try: + api_response = api_instance.post_additionalproperties_allows_a_schema_which_should_validate_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_additionalproperties_allows_a_schema_which_should_validate_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAllowsASchemaWhichShouldValidate**](../../models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_allows_a_schema_which_should_validate_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_allows_a_schema_which_should_validate_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types** + +> AdditionalpropertiesAllowsASchemaWhichShouldValidate post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAllowsASchemaWhichShouldValidate**](../../models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_are_allowed_by_default_request_body** + +> post_additionalproperties_are_allowed_by_default_request_body(additionalproperties_are_allowed_by_default) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesAreAllowedByDefault(None) + try: + api_response = api_instance.post_additionalproperties_are_allowed_by_default_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_additionalproperties_are_allowed_by_default_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAreAllowedByDefault**](../../models/AdditionalpropertiesAreAllowedByDefault.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_are_allowed_by_default_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_are_allowed_by_default_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_are_allowed_by_default_response_body_for_content_types** + +> AdditionalpropertiesAreAllowedByDefault post_additionalproperties_are_allowed_by_default_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_are_allowed_by_default_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_additionalproperties_are_allowed_by_default_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_are_allowed_by_default_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_are_allowed_by_default_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAreAllowedByDefault**](../../models/AdditionalpropertiesAreAllowedByDefault.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_can_exist_by_itself_request_body** + +> post_additionalproperties_can_exist_by_itself_request_body(additionalproperties_can_exist_by_itself) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesCanExistByItself( + key=True, + ) + try: + api_response = api_instance.post_additionalproperties_can_exist_by_itself_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_additionalproperties_can_exist_by_itself_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesCanExistByItself**](../../models/AdditionalpropertiesCanExistByItself.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_can_exist_by_itself_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_can_exist_by_itself_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_can_exist_by_itself_response_body_for_content_types** + +> AdditionalpropertiesCanExistByItself post_additionalproperties_can_exist_by_itself_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_can_exist_by_itself_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_additionalproperties_can_exist_by_itself_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_can_exist_by_itself_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_can_exist_by_itself_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesCanExistByItself**](../../models/AdditionalpropertiesCanExistByItself.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_should_not_look_in_applicators_request_body** + +> post_additionalproperties_should_not_look_in_applicators_request_body(additionalproperties_should_not_look_in_applicators) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesShouldNotLookInApplicators(None) + try: + api_response = api_instance.post_additionalproperties_should_not_look_in_applicators_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_additionalproperties_should_not_look_in_applicators_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesShouldNotLookInApplicators**](../../models/AdditionalpropertiesShouldNotLookInApplicators.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_should_not_look_in_applicators_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_should_not_look_in_applicators_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types** + +> AdditionalpropertiesShouldNotLookInApplicators post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesShouldNotLookInApplicators**](../../models/AdditionalpropertiesShouldNotLookInApplicators.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_combined_with_anyof_oneof_request_body** + +> post_allof_combined_with_anyof_oneof_request_body(allof_combined_with_anyof_oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofCombinedWithAnyofOneof(None) + try: + api_response = api_instance.post_allof_combined_with_anyof_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_combined_with_anyof_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofCombinedWithAnyofOneof**](../../models/AllofCombinedWithAnyofOneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_combined_with_anyof_oneof_request_body.ApiResponseFor200) | success + +#### post_allof_combined_with_anyof_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_combined_with_anyof_oneof_response_body_for_content_types** + +> AllofCombinedWithAnyofOneof post_allof_combined_with_anyof_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_combined_with_anyof_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_combined_with_anyof_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_combined_with_anyof_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_combined_with_anyof_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofCombinedWithAnyofOneof**](../../models/AllofCombinedWithAnyofOneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_request_body** + +> post_allof_request_body(allof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof import Allof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = Allof(None) + try: + api_response = api_instance.post_allof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Allof**](../../models/Allof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_request_body.ApiResponseFor200) | success + +#### post_allof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_response_body_for_content_types** + +> Allof post_allof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof import Allof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Allof**](../../models/Allof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_simple_types_request_body** + +> post_allof_simple_types_request_body(allof_simple_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_simple_types import AllofSimpleTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofSimpleTypes(None) + try: + api_response = api_instance.post_allof_simple_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_simple_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofSimpleTypes**](../../models/AllofSimpleTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_simple_types_request_body.ApiResponseFor200) | success + +#### post_allof_simple_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_simple_types_response_body_for_content_types** + +> AllofSimpleTypes post_allof_simple_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_simple_types import AllofSimpleTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_simple_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_simple_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_simple_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_simple_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofSimpleTypes**](../../models/AllofSimpleTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_base_schema_request_body** + +> post_allof_with_base_schema_request_body(allof_with_base_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithBaseSchema({}) + try: + api_response = api_instance.post_allof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithBaseSchema**](../../models/AllofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_base_schema_response_body_for_content_types** + +> AllofWithBaseSchema post_allof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithBaseSchema**](../../models/AllofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_one_empty_schema_request_body** + +> post_allof_with_one_empty_schema_request_body(allof_with_one_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithOneEmptySchema(None) + try: + api_response = api_instance.post_allof_with_one_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_one_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithOneEmptySchema**](../../models/AllofWithOneEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_one_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_one_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_one_empty_schema_response_body_for_content_types** + +> AllofWithOneEmptySchema post_allof_with_one_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_one_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_one_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithOneEmptySchema**](../../models/AllofWithOneEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_first_empty_schema_request_body** + +> post_allof_with_the_first_empty_schema_request_body(allof_with_the_first_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTheFirstEmptySchema(None) + try: + api_response = api_instance.post_allof_with_the_first_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_the_first_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheFirstEmptySchema**](../../models/AllofWithTheFirstEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_first_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_the_first_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_first_empty_schema_response_body_for_content_types** + +> AllofWithTheFirstEmptySchema post_allof_with_the_first_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_the_first_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_the_first_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_first_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_the_first_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheFirstEmptySchema**](../../models/AllofWithTheFirstEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_last_empty_schema_request_body** + +> post_allof_with_the_last_empty_schema_request_body(allof_with_the_last_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTheLastEmptySchema(None) + try: + api_response = api_instance.post_allof_with_the_last_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_the_last_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheLastEmptySchema**](../../models/AllofWithTheLastEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_last_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_the_last_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_last_empty_schema_response_body_for_content_types** + +> AllofWithTheLastEmptySchema post_allof_with_the_last_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_the_last_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_the_last_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_last_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_the_last_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheLastEmptySchema**](../../models/AllofWithTheLastEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_two_empty_schemas_request_body** + +> post_allof_with_two_empty_schemas_request_body(allof_with_two_empty_schemas) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTwoEmptySchemas(None) + try: + api_response = api_instance.post_allof_with_two_empty_schemas_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_two_empty_schemas_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTwoEmptySchemas**](../../models/AllofWithTwoEmptySchemas.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_two_empty_schemas_request_body.ApiResponseFor200) | success + +#### post_allof_with_two_empty_schemas_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_two_empty_schemas_response_body_for_content_types** + +> AllofWithTwoEmptySchemas post_allof_with_two_empty_schemas_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_two_empty_schemas_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_allof_with_two_empty_schemas_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_two_empty_schemas_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_two_empty_schemas_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTwoEmptySchemas**](../../models/AllofWithTwoEmptySchemas.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_complex_types_request_body** + +> post_anyof_complex_types_request_body(anyof_complex_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofComplexTypes(None) + try: + api_response = api_instance.post_anyof_complex_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_anyof_complex_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofComplexTypes**](../../models/AnyofComplexTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_complex_types_request_body.ApiResponseFor200) | success + +#### post_anyof_complex_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_complex_types_response_body_for_content_types** + +> AnyofComplexTypes post_anyof_complex_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_complex_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_anyof_complex_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_complex_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_complex_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofComplexTypes**](../../models/AnyofComplexTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_request_body** + +> post_anyof_request_body(anyof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.anyof import Anyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = Anyof(None) + try: + api_response = api_instance.post_anyof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_anyof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Anyof**](../../models/Anyof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_request_body.ApiResponseFor200) | success + +#### post_anyof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_response_body_for_content_types** + +> Anyof post_anyof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.anyof import Anyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_anyof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Anyof**](../../models/Anyof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_base_schema_request_body** + +> post_anyof_with_base_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofWithBaseSchema("body_example") + try: + api_response = api_instance.post_anyof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_anyof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithBaseSchema**](../../models/AnyofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_anyof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_base_schema_response_body_for_content_types** + +> AnyofWithBaseSchema post_anyof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_anyof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithBaseSchema**](../../models/AnyofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_one_empty_schema_request_body** + +> post_anyof_with_one_empty_schema_request_body(anyof_with_one_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofWithOneEmptySchema(None) + try: + api_response = api_instance.post_anyof_with_one_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_anyof_with_one_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithOneEmptySchema**](../../models/AnyofWithOneEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_one_empty_schema_request_body.ApiResponseFor200) | success + +#### post_anyof_with_one_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_one_empty_schema_response_body_for_content_types** + +> AnyofWithOneEmptySchema post_anyof_with_one_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_with_one_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_anyof_with_one_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithOneEmptySchema**](../../models/AnyofWithOneEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_array_type_matches_arrays_request_body** + +> post_array_type_matches_arrays_request_body(array_type_matches_arrays) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = ArrayTypeMatchesArrays([ + None + ]) + try: + api_response = api_instance.post_array_type_matches_arrays_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_array_type_matches_arrays_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayTypeMatchesArrays**](../../models/ArrayTypeMatchesArrays.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_array_type_matches_arrays_request_body.ApiResponseFor200) | success + +#### post_array_type_matches_arrays_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_array_type_matches_arrays_response_body_for_content_types** + +> ArrayTypeMatchesArrays post_array_type_matches_arrays_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_array_type_matches_arrays_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_array_type_matches_arrays_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_array_type_matches_arrays_response_body_for_content_types.ApiResponseFor200) | success + +#### post_array_type_matches_arrays_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayTypeMatchesArrays**](../../models/ArrayTypeMatchesArrays.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_boolean_type_matches_booleans_request_body** + +> post_boolean_type_matches_booleans_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = True + try: + api_response = api_instance.post_boolean_type_matches_booleans_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_boolean_type_matches_booleans_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_boolean_type_matches_booleans_request_body.ApiResponseFor200) | success + +#### post_boolean_type_matches_booleans_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_boolean_type_matches_booleans_response_body_for_content_types** + +> bool post_boolean_type_matches_booleans_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_boolean_type_matches_booleans_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_boolean_type_matches_booleans_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_boolean_type_matches_booleans_response_body_for_content_types.ApiResponseFor200) | success + +#### post_boolean_type_matches_booleans_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_int_request_body** + +> post_by_int_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.by_int import ByInt +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = ByInt(None) + try: + api_response = api_instance.post_by_int_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_by_int_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByInt**](../../models/ByInt.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_int_request_body.ApiResponseFor200) | success + +#### post_by_int_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_int_response_body_for_content_types** + +> ByInt post_by_int_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.by_int import ByInt +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_int_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_by_int_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_int_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_int_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByInt**](../../models/ByInt.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_number_request_body** + +> post_by_number_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.by_number import ByNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = ByNumber(None) + try: + api_response = api_instance.post_by_number_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_by_number_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByNumber**](../../models/ByNumber.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_number_request_body.ApiResponseFor200) | success + +#### post_by_number_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_number_response_body_for_content_types** + +> ByNumber post_by_number_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.by_number import ByNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_number_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_by_number_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_number_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_number_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByNumber**](../../models/ByNumber.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_small_number_request_body** + +> post_by_small_number_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.by_small_number import BySmallNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = BySmallNumber(None) + try: + api_response = api_instance.post_by_small_number_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_by_small_number_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**BySmallNumber**](../../models/BySmallNumber.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_small_number_request_body.ApiResponseFor200) | success + +#### post_by_small_number_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_small_number_response_body_for_content_types** + +> BySmallNumber post_by_small_number_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.by_small_number import BySmallNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_small_number_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_by_small_number_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_small_number_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_small_number_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**BySmallNumber**](../../models/BySmallNumber.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_date_time_format_request_body** + +> post_date_time_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_date_time_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_date_time_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | value must conform to RFC-3339 date-time + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_date_time_format_request_body.ApiResponseFor200) | success + +#### post_date_time_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_date_time_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_date_time_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_date_time_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_date_time_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_date_time_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_date_time_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | value must conform to RFC-3339 date-time + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_email_format_request_body** + +> post_email_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_email_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_email_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_email_format_request_body.ApiResponseFor200) | success + +#### post_email_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_email_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_email_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_email_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_email_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_email_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_email_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with0_does_not_match_false_request_body** + +> post_enum_with0_does_not_match_false_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWith0DoesNotMatchFalse(0) + try: + api_response = api_instance.post_enum_with0_does_not_match_false_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with0_does_not_match_false_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith0DoesNotMatchFalse**](../../models/EnumWith0DoesNotMatchFalse.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with0_does_not_match_false_request_body.ApiResponseFor200) | success + +#### post_enum_with0_does_not_match_false_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with0_does_not_match_false_response_body_for_content_types** + +> EnumWith0DoesNotMatchFalse post_enum_with0_does_not_match_false_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with0_does_not_match_false_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with0_does_not_match_false_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with0_does_not_match_false_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with0_does_not_match_false_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith0DoesNotMatchFalse**](../../models/EnumWith0DoesNotMatchFalse.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with1_does_not_match_true_request_body** + +> post_enum_with1_does_not_match_true_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWith1DoesNotMatchTrue(1) + try: + api_response = api_instance.post_enum_with1_does_not_match_true_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with1_does_not_match_true_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith1DoesNotMatchTrue**](../../models/EnumWith1DoesNotMatchTrue.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with1_does_not_match_true_request_body.ApiResponseFor200) | success + +#### post_enum_with1_does_not_match_true_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with1_does_not_match_true_response_body_for_content_types** + +> EnumWith1DoesNotMatchTrue post_enum_with1_does_not_match_true_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with1_does_not_match_true_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with1_does_not_match_true_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with1_does_not_match_true_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with1_does_not_match_true_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith1DoesNotMatchTrue**](../../models/EnumWith1DoesNotMatchTrue.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_escaped_characters_request_body** + +> post_enum_with_escaped_characters_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithEscapedCharacters("foo\nbar") + try: + api_response = api_instance.post_enum_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithEscapedCharacters**](../../models/EnumWithEscapedCharacters.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_enum_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_escaped_characters_response_body_for_content_types** + +> EnumWithEscapedCharacters post_enum_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithEscapedCharacters**](../../models/EnumWithEscapedCharacters.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_false_does_not_match0_request_body** + +> post_enum_with_false_does_not_match0_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithFalseDoesNotMatch0(False) + try: + api_response = api_instance.post_enum_with_false_does_not_match0_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with_false_does_not_match0_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithFalseDoesNotMatch0**](../../models/EnumWithFalseDoesNotMatch0.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_false_does_not_match0_request_body.ApiResponseFor200) | success + +#### post_enum_with_false_does_not_match0_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_false_does_not_match0_response_body_for_content_types** + +> EnumWithFalseDoesNotMatch0 post_enum_with_false_does_not_match0_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_false_does_not_match0_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with_false_does_not_match0_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_false_does_not_match0_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_false_does_not_match0_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithFalseDoesNotMatch0**](../../models/EnumWithFalseDoesNotMatch0.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_true_does_not_match1_request_body** + +> post_enum_with_true_does_not_match1_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithTrueDoesNotMatch1(True) + try: + api_response = api_instance.post_enum_with_true_does_not_match1_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with_true_does_not_match1_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithTrueDoesNotMatch1**](../../models/EnumWithTrueDoesNotMatch1.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_true_does_not_match1_request_body.ApiResponseFor200) | success + +#### post_enum_with_true_does_not_match1_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_true_does_not_match1_response_body_for_content_types** + +> EnumWithTrueDoesNotMatch1 post_enum_with_true_does_not_match1_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_true_does_not_match1_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enum_with_true_does_not_match1_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_true_does_not_match1_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_true_does_not_match1_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithTrueDoesNotMatch1**](../../models/EnumWithTrueDoesNotMatch1.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enums_in_properties_request_body** + +> post_enums_in_properties_request_body(enums_in_properties) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enums_in_properties import EnumsInProperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumsInProperties( + foo="foo", + bar="bar", + ) + try: + api_response = api_instance.post_enums_in_properties_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enums_in_properties_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumsInProperties**](../../models/EnumsInProperties.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enums_in_properties_request_body.ApiResponseFor200) | success + +#### post_enums_in_properties_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enums_in_properties_response_body_for_content_types** + +> EnumsInProperties post_enums_in_properties_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.enums_in_properties import EnumsInProperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enums_in_properties_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_enums_in_properties_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enums_in_properties_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enums_in_properties_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumsInProperties**](../../models/EnumsInProperties.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_forbidden_property_request_body** + +> post_forbidden_property_request_body(forbidden_property) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.forbidden_property import ForbiddenProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = ForbiddenProperty(None) + try: + api_response = api_instance.post_forbidden_property_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_forbidden_property_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ForbiddenProperty**](../../models/ForbiddenProperty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_forbidden_property_request_body.ApiResponseFor200) | success + +#### post_forbidden_property_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_forbidden_property_response_body_for_content_types** + +> ForbiddenProperty post_forbidden_property_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.forbidden_property import ForbiddenProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_forbidden_property_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_forbidden_property_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_forbidden_property_response_body_for_content_types.ApiResponseFor200) | success + +#### post_forbidden_property_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ForbiddenProperty**](../../models/ForbiddenProperty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_hostname_format_request_body** + +> post_hostname_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_hostname_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_hostname_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_hostname_format_request_body.ApiResponseFor200) | success + +#### post_hostname_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_hostname_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_hostname_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_hostname_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_hostname_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_hostname_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_hostname_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_integer_type_matches_integers_request_body** + +> post_integer_type_matches_integers_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = 1 + try: + api_response = api_instance.post_integer_type_matches_integers_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_integer_type_matches_integers_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_integer_type_matches_integers_request_body.ApiResponseFor200) | success + +#### post_integer_type_matches_integers_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_integer_type_matches_integers_response_body_for_content_types** + +> int post_integer_type_matches_integers_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_integer_type_matches_integers_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_integer_type_matches_integers_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_integer_type_matches_integers_response_body_for_content_types.ApiResponseFor200) | success + +#### post_integer_type_matches_integers_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body** + +> post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf(1) + try: + api_response = api_instance.post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf**](../../models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.ApiResponseFor200) | success + +#### post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types** + +> InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.ApiResponseFor200) | success + +#### post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf**](../../models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_string_value_for_default_request_body** + +> post_invalid_string_value_for_default_request_body(invalid_string_value_for_default) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = InvalidStringValueForDefault(None) + try: + api_response = api_instance.post_invalid_string_value_for_default_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_invalid_string_value_for_default_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidStringValueForDefault**](../../models/InvalidStringValueForDefault.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_string_value_for_default_request_body.ApiResponseFor200) | success + +#### post_invalid_string_value_for_default_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_string_value_for_default_response_body_for_content_types** + +> InvalidStringValueForDefault post_invalid_string_value_for_default_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_invalid_string_value_for_default_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_invalid_string_value_for_default_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_string_value_for_default_response_body_for_content_types.ApiResponseFor200) | success + +#### post_invalid_string_value_for_default_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidStringValueForDefault**](../../models/InvalidStringValueForDefault.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv4_format_request_body** + +> post_ipv4_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ipv4_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ipv4_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv4_format_request_body.ApiResponseFor200) | success + +#### post_ipv4_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv4_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ipv4_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ipv4_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ipv4_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv4_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ipv4_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv6_format_request_body** + +> post_ipv6_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ipv6_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ipv6_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv6_format_request_body.ApiResponseFor200) | success + +#### post_ipv6_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv6_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ipv6_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ipv6_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ipv6_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv6_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ipv6_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_json_pointer_format_request_body** + +> post_json_pointer_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_json_pointer_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_json_pointer_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_json_pointer_format_request_body.ApiResponseFor200) | success + +#### post_json_pointer_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_json_pointer_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_json_pointer_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_json_pointer_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_json_pointer_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_json_pointer_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_json_pointer_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_request_body** + +> post_maximum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maximum_validation import MaximumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MaximumValidation(None) + try: + api_response = api_instance.post_maximum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maximum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidation**](../../models/MaximumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_request_body.ApiResponseFor200) | success + +#### post_maximum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_response_body_for_content_types** + +> MaximumValidation post_maximum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maximum_validation import MaximumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maximum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maximum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maximum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidation**](../../models/MaximumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_with_unsigned_integer_request_body** + +> post_maximum_validation_with_unsigned_integer_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MaximumValidationWithUnsignedInteger(None) + try: + api_response = api_instance.post_maximum_validation_with_unsigned_integer_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maximum_validation_with_unsigned_integer_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidationWithUnsignedInteger**](../../models/MaximumValidationWithUnsignedInteger.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_with_unsigned_integer_request_body.ApiResponseFor200) | success + +#### post_maximum_validation_with_unsigned_integer_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_with_unsigned_integer_response_body_for_content_types** + +> MaximumValidationWithUnsignedInteger post_maximum_validation_with_unsigned_integer_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maximum_validation_with_unsigned_integer_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maximum_validation_with_unsigned_integer_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_with_unsigned_integer_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maximum_validation_with_unsigned_integer_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidationWithUnsignedInteger**](../../models/MaximumValidationWithUnsignedInteger.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxitems_validation_request_body** + +> post_maxitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maxitems_validation import MaxitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxitemsValidation(None) + try: + api_response = api_instance.post_maxitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maxitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxitemsValidation**](../../models/MaxitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxitems_validation_request_body.ApiResponseFor200) | success + +#### post_maxitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxitems_validation_response_body_for_content_types** + +> MaxitemsValidation post_maxitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maxitems_validation import MaxitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maxitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxitemsValidation**](../../models/MaxitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxlength_validation_request_body** + +> post_maxlength_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maxlength_validation import MaxlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxlengthValidation(None) + try: + api_response = api_instance.post_maxlength_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maxlength_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxlengthValidation**](../../models/MaxlengthValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxlength_validation_request_body.ApiResponseFor200) | success + +#### post_maxlength_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxlength_validation_response_body_for_content_types** + +> MaxlengthValidation post_maxlength_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maxlength_validation import MaxlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxlength_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maxlength_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxlength_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxlength_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxlengthValidation**](../../models/MaxlengthValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties0_means_the_object_is_empty_request_body** + +> post_maxproperties0_means_the_object_is_empty_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = Maxproperties0MeansTheObjectIsEmpty(None) + try: + api_response = api_instance.post_maxproperties0_means_the_object_is_empty_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maxproperties0_means_the_object_is_empty_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Maxproperties0MeansTheObjectIsEmpty**](../../models/Maxproperties0MeansTheObjectIsEmpty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties0_means_the_object_is_empty_request_body.ApiResponseFor200) | success + +#### post_maxproperties0_means_the_object_is_empty_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties0_means_the_object_is_empty_response_body_for_content_types** + +> Maxproperties0MeansTheObjectIsEmpty post_maxproperties0_means_the_object_is_empty_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxproperties0_means_the_object_is_empty_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maxproperties0_means_the_object_is_empty_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Maxproperties0MeansTheObjectIsEmpty**](../../models/Maxproperties0MeansTheObjectIsEmpty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties_validation_request_body** + +> post_maxproperties_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxpropertiesValidation(None) + try: + api_response = api_instance.post_maxproperties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maxproperties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxpropertiesValidation**](../../models/MaxpropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties_validation_request_body.ApiResponseFor200) | success + +#### post_maxproperties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties_validation_response_body_for_content_types** + +> MaxpropertiesValidation post_maxproperties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxproperties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_maxproperties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxproperties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxpropertiesValidation**](../../models/MaxpropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_request_body** + +> post_minimum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minimum_validation import MinimumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MinimumValidation(None) + try: + api_response = api_instance.post_minimum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minimum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidation**](../../models/MinimumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_request_body.ApiResponseFor200) | success + +#### post_minimum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_response_body_for_content_types** + +> MinimumValidation post_minimum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minimum_validation import MinimumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minimum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minimum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minimum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidation**](../../models/MinimumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_with_signed_integer_request_body** + +> post_minimum_validation_with_signed_integer_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MinimumValidationWithSignedInteger(None) + try: + api_response = api_instance.post_minimum_validation_with_signed_integer_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minimum_validation_with_signed_integer_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidationWithSignedInteger**](../../models/MinimumValidationWithSignedInteger.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_with_signed_integer_request_body.ApiResponseFor200) | success + +#### post_minimum_validation_with_signed_integer_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_with_signed_integer_response_body_for_content_types** + +> MinimumValidationWithSignedInteger post_minimum_validation_with_signed_integer_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minimum_validation_with_signed_integer_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minimum_validation_with_signed_integer_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_with_signed_integer_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minimum_validation_with_signed_integer_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidationWithSignedInteger**](../../models/MinimumValidationWithSignedInteger.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minitems_validation_request_body** + +> post_minitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minitems_validation import MinitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MinitemsValidation(None) + try: + api_response = api_instance.post_minitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinitemsValidation**](../../models/MinitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minitems_validation_request_body.ApiResponseFor200) | success + +#### post_minitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minitems_validation_response_body_for_content_types** + +> MinitemsValidation post_minitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minitems_validation import MinitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinitemsValidation**](../../models/MinitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minlength_validation_request_body** + +> post_minlength_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minlength_validation import MinlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MinlengthValidation(None) + try: + api_response = api_instance.post_minlength_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minlength_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinlengthValidation**](../../models/MinlengthValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minlength_validation_request_body.ApiResponseFor200) | success + +#### post_minlength_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minlength_validation_response_body_for_content_types** + +> MinlengthValidation post_minlength_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minlength_validation import MinlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minlength_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minlength_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minlength_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minlength_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinlengthValidation**](../../models/MinlengthValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minproperties_validation_request_body** + +> post_minproperties_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minproperties_validation import MinpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = MinpropertiesValidation(None) + try: + api_response = api_instance.post_minproperties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minproperties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinpropertiesValidation**](../../models/MinpropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minproperties_validation_request_body.ApiResponseFor200) | success + +#### post_minproperties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minproperties_validation_response_body_for_content_types** + +> MinpropertiesValidation post_minproperties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.minproperties_validation import MinpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minproperties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_minproperties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minproperties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minproperties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinpropertiesValidation**](../../models/MinpropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_allof_to_check_validation_semantics_request_body** + +> post_nested_allof_to_check_validation_semantics_request_body(nested_allof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedAllofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_allof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nested_allof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAllofToCheckValidationSemantics**](../../models/NestedAllofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_allof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_allof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_allof_to_check_validation_semantics_response_body_for_content_types** + +> NestedAllofToCheckValidationSemantics post_nested_allof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_allof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nested_allof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_allof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_allof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAllofToCheckValidationSemantics**](../../models/NestedAllofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_anyof_to_check_validation_semantics_request_body** + +> post_nested_anyof_to_check_validation_semantics_request_body(nested_anyof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedAnyofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_anyof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nested_anyof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAnyofToCheckValidationSemantics**](../../models/NestedAnyofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_anyof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_anyof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_anyof_to_check_validation_semantics_response_body_for_content_types** + +> NestedAnyofToCheckValidationSemantics post_nested_anyof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_anyof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nested_anyof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAnyofToCheckValidationSemantics**](../../models/NestedAnyofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_items_request_body** + +> post_nested_items_request_body(nested_items) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nested_items import NestedItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedItems([ + [ + [ + [ + 3.14 + ] + ] + ] + ]) + try: + api_response = api_instance.post_nested_items_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nested_items_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedItems**](../../models/NestedItems.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_items_request_body.ApiResponseFor200) | success + +#### post_nested_items_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_items_response_body_for_content_types** + +> NestedItems post_nested_items_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nested_items import NestedItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_items_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nested_items_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_items_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_items_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedItems**](../../models/NestedItems.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_oneof_to_check_validation_semantics_request_body** + +> post_nested_oneof_to_check_validation_semantics_request_body(nested_oneof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedOneofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_oneof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nested_oneof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedOneofToCheckValidationSemantics**](../../models/NestedOneofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_oneof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_oneof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_oneof_to_check_validation_semantics_response_body_for_content_types** + +> NestedOneofToCheckValidationSemantics post_nested_oneof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_oneof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nested_oneof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedOneofToCheckValidationSemantics**](../../models/NestedOneofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_more_complex_schema_request_body** + +> post_not_more_complex_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_not_more_complex_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_not_more_complex_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_more_complex_schema_request_body.ApiResponseFor200) | success + +#### post_not_more_complex_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_more_complex_schema_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_not_more_complex_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_not_more_complex_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_not_more_complex_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_more_complex_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_not_more_complex_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_request_body** + +> post_not_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_not_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_not_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | decimal.Decimal, int, | decimal.Decimal, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_request_body.ApiResponseFor200) | success + +#### post_not_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_not_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_not_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_not_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_response_body_for_content_types.ApiResponseFor200) | success + +#### post_not_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | decimal.Decimal, int, | decimal.Decimal, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nul_characters_in_strings_request_body** + +> post_nul_characters_in_strings_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = NulCharactersInStrings("hello\x00there") + try: + api_response = api_instance.post_nul_characters_in_strings_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nul_characters_in_strings_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NulCharactersInStrings**](../../models/NulCharactersInStrings.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nul_characters_in_strings_request_body.ApiResponseFor200) | success + +#### post_nul_characters_in_strings_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nul_characters_in_strings_response_body_for_content_types** + +> NulCharactersInStrings post_nul_characters_in_strings_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nul_characters_in_strings_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_nul_characters_in_strings_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nul_characters_in_strings_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nul_characters_in_strings_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NulCharactersInStrings**](../../models/NulCharactersInStrings.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_null_type_matches_only_the_null_object_request_body** + +> post_null_type_matches_only_the_null_object_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_null_type_matches_only_the_null_object_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_null_type_matches_only_the_null_object_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_null_type_matches_only_the_null_object_request_body.ApiResponseFor200) | success + +#### post_null_type_matches_only_the_null_object_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_null_type_matches_only_the_null_object_response_body_for_content_types** + +> none_type post_null_type_matches_only_the_null_object_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_null_type_matches_only_the_null_object_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_null_type_matches_only_the_null_object_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_null_type_matches_only_the_null_object_response_body_for_content_types.ApiResponseFor200) | success + +#### post_null_type_matches_only_the_null_object_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_number_type_matches_numbers_request_body** + +> post_number_type_matches_numbers_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = 3.14 + try: + api_response = api_instance.post_number_type_matches_numbers_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_number_type_matches_numbers_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_number_type_matches_numbers_request_body.ApiResponseFor200) | success + +#### post_number_type_matches_numbers_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_number_type_matches_numbers_response_body_for_content_types** + +> int, float post_number_type_matches_numbers_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_number_type_matches_numbers_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_number_type_matches_numbers_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_number_type_matches_numbers_response_body_for_content_types.ApiResponseFor200) | success + +#### post_number_type_matches_numbers_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_properties_validation_request_body** + +> post_object_properties_validation_request_body(object_properties_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = ObjectPropertiesValidation(None) + try: + api_response = api_instance.post_object_properties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_object_properties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectPropertiesValidation**](../../models/ObjectPropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_properties_validation_request_body.ApiResponseFor200) | success + +#### post_object_properties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_properties_validation_response_body_for_content_types** + +> ObjectPropertiesValidation post_object_properties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_object_properties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_object_properties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_properties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_object_properties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectPropertiesValidation**](../../models/ObjectPropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_type_matches_objects_request_body** + +> post_object_type_matches_objects_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = dict() + try: + api_response = api_instance.post_object_type_matches_objects_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_object_type_matches_objects_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_type_matches_objects_request_body.ApiResponseFor200) | success + +#### post_object_type_matches_objects_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_type_matches_objects_response_body_for_content_types** + +> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} post_object_type_matches_objects_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_object_type_matches_objects_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_object_type_matches_objects_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_type_matches_objects_response_body_for_content_types.ApiResponseFor200) | success + +#### post_object_type_matches_objects_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_complex_types_request_body** + +> post_oneof_complex_types_request_body(oneof_complex_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof_complex_types import OneofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofComplexTypes(None) + try: + api_response = api_instance.post_oneof_complex_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_complex_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofComplexTypes**](../../models/OneofComplexTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_complex_types_request_body.ApiResponseFor200) | success + +#### post_oneof_complex_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_complex_types_response_body_for_content_types** + +> OneofComplexTypes post_oneof_complex_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof_complex_types import OneofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_complex_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_complex_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_complex_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_complex_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofComplexTypes**](../../models/OneofComplexTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_request_body** + +> post_oneof_request_body(oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof import Oneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = Oneof(None) + try: + api_response = api_instance.post_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Oneof**](../../models/Oneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_request_body.ApiResponseFor200) | success + +#### post_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_response_body_for_content_types** + +> Oneof post_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof import Oneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Oneof**](../../models/Oneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_base_schema_request_body** + +> post_oneof_with_base_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithBaseSchema("body_example") + try: + api_response = api_instance.post_oneof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithBaseSchema**](../../models/OneofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_oneof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_base_schema_response_body_for_content_types** + +> OneofWithBaseSchema post_oneof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithBaseSchema**](../../models/OneofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_empty_schema_request_body** + +> post_oneof_with_empty_schema_request_body(oneof_with_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithEmptySchema(None) + try: + api_response = api_instance.post_oneof_with_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_with_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithEmptySchema**](../../models/OneofWithEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_empty_schema_request_body.ApiResponseFor200) | success + +#### post_oneof_with_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_empty_schema_response_body_for_content_types** + +> OneofWithEmptySchema post_oneof_with_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_with_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithEmptySchema**](../../models/OneofWithEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_required_request_body** + +> post_oneof_with_required_request_body(oneof_with_required) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof_with_required import OneofWithRequired +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithRequired() + try: + api_response = api_instance.post_oneof_with_required_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_with_required_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithRequired**](../../models/OneofWithRequired.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_required_request_body.ApiResponseFor200) | success + +#### post_oneof_with_required_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_required_response_body_for_content_types** + +> OneofWithRequired post_oneof_with_required_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.oneof_with_required import OneofWithRequired +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_required_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_oneof_with_required_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_required_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_required_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithRequired**](../../models/OneofWithRequired.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_is_not_anchored_request_body** + +> post_pattern_is_not_anchored_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = PatternIsNotAnchored(None) + try: + api_response = api_instance.post_pattern_is_not_anchored_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_pattern_is_not_anchored_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternIsNotAnchored**](../../models/PatternIsNotAnchored.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_is_not_anchored_request_body.ApiResponseFor200) | success + +#### post_pattern_is_not_anchored_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_is_not_anchored_response_body_for_content_types** + +> PatternIsNotAnchored post_pattern_is_not_anchored_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_pattern_is_not_anchored_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_pattern_is_not_anchored_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_is_not_anchored_response_body_for_content_types.ApiResponseFor200) | success + +#### post_pattern_is_not_anchored_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternIsNotAnchored**](../../models/PatternIsNotAnchored.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_validation_request_body** + +> post_pattern_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.pattern_validation import PatternValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = PatternValidation(None) + try: + api_response = api_instance.post_pattern_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_pattern_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternValidation**](../../models/PatternValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_validation_request_body.ApiResponseFor200) | success + +#### post_pattern_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_validation_response_body_for_content_types** + +> PatternValidation post_pattern_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.pattern_validation import PatternValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_pattern_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_pattern_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_pattern_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternValidation**](../../models/PatternValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_properties_with_escaped_characters_request_body** + +> post_properties_with_escaped_characters_request_body(properties_with_escaped_characters) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = PropertiesWithEscapedCharacters(None) + try: + api_response = api_instance.post_properties_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_properties_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertiesWithEscapedCharacters**](../../models/PropertiesWithEscapedCharacters.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_properties_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_properties_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_properties_with_escaped_characters_response_body_for_content_types** + +> PropertiesWithEscapedCharacters post_properties_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_properties_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_properties_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_properties_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_properties_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertiesWithEscapedCharacters**](../../models/PropertiesWithEscapedCharacters.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_property_named_ref_that_is_not_a_reference_request_body** + +> post_property_named_ref_that_is_not_a_reference_request_body(property_named_ref_that_is_not_a_reference) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = PropertyNamedRefThatIsNotAReference(None) + try: + api_response = api_instance.post_property_named_ref_that_is_not_a_reference_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_property_named_ref_that_is_not_a_reference_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertyNamedRefThatIsNotAReference**](../../models/PropertyNamedRefThatIsNotAReference.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_property_named_ref_that_is_not_a_reference_request_body.ApiResponseFor200) | success + +#### post_property_named_ref_that_is_not_a_reference_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_property_named_ref_that_is_not_a_reference_response_body_for_content_types** + +> PropertyNamedRefThatIsNotAReference post_property_named_ref_that_is_not_a_reference_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_property_named_ref_that_is_not_a_reference_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_property_named_ref_that_is_not_a_reference_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.ApiResponseFor200) | success + +#### post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertyNamedRefThatIsNotAReference**](../../models/PropertyNamedRefThatIsNotAReference.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_additionalproperties_request_body** + +> post_ref_in_additionalproperties_request_body(ref_in_additionalproperties) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAdditionalproperties( + key=PropertyNamedRefThatIsNotAReference(None), + ) + try: + api_response = api_instance.post_ref_in_additionalproperties_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_additionalproperties_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAdditionalproperties**](../../models/RefInAdditionalproperties.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_additionalproperties_request_body.ApiResponseFor200) | success + +#### post_ref_in_additionalproperties_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_additionalproperties_response_body_for_content_types** + +> RefInAdditionalproperties post_ref_in_additionalproperties_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_additionalproperties_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_additionalproperties_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_additionalproperties_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_additionalproperties_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAdditionalproperties**](../../models/RefInAdditionalproperties.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_allof_request_body** + +> post_ref_in_allof_request_body(ref_in_allof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_allof import RefInAllof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAllof(None) + try: + api_response = api_instance.post_ref_in_allof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_allof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAllof**](../../models/RefInAllof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_allof_request_body.ApiResponseFor200) | success + +#### post_ref_in_allof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_allof_response_body_for_content_types** + +> RefInAllof post_ref_in_allof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_allof import RefInAllof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_allof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_allof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_allof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_allof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAllof**](../../models/RefInAllof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_anyof_request_body** + +> post_ref_in_anyof_request_body(ref_in_anyof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_anyof import RefInAnyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAnyof(None) + try: + api_response = api_instance.post_ref_in_anyof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_anyof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAnyof**](../../models/RefInAnyof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_anyof_request_body.ApiResponseFor200) | success + +#### post_ref_in_anyof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_anyof_response_body_for_content_types** + +> RefInAnyof post_ref_in_anyof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_anyof import RefInAnyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_anyof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_anyof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_anyof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_anyof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAnyof**](../../models/RefInAnyof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_items_request_body** + +> post_ref_in_items_request_body(ref_in_items) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_items import RefInItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInItems([ + PropertyNamedRefThatIsNotAReference(None) + ]) + try: + api_response = api_instance.post_ref_in_items_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_items_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInItems**](../../models/RefInItems.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_items_request_body.ApiResponseFor200) | success + +#### post_ref_in_items_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_items_response_body_for_content_types** + +> RefInItems post_ref_in_items_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_items import RefInItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_items_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_items_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_items_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_items_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInItems**](../../models/RefInItems.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_not_request_body** + +> post_ref_in_not_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ref_in_not_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_not_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_not_request_body.ApiResponseFor200) | success + +#### post_ref_in_not_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_not_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ref_in_not_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_not_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_not_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_not_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_not_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_oneof_request_body** + +> post_ref_in_oneof_request_body(ref_in_oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_oneof import RefInOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInOneof(None) + try: + api_response = api_instance.post_ref_in_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInOneof**](../../models/RefInOneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_oneof_request_body.ApiResponseFor200) | success + +#### post_ref_in_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_oneof_response_body_for_content_types** + +> RefInOneof post_ref_in_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_oneof import RefInOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInOneof**](../../models/RefInOneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_property_request_body** + +> post_ref_in_property_request_body(ref_in_property) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_property import RefInProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInProperty(None) + try: + api_response = api_instance.post_ref_in_property_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_property_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInProperty**](../../models/RefInProperty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_property_request_body.ApiResponseFor200) | success + +#### post_ref_in_property_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_property_response_body_for_content_types** + +> RefInProperty post_ref_in_property_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.ref_in_property import RefInProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_property_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_ref_in_property_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_property_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_property_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInProperty**](../../models/RefInProperty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_default_validation_request_body** + +> post_required_default_validation_request_body(required_default_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.required_default_validation import RequiredDefaultValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredDefaultValidation(None) + try: + api_response = api_instance.post_required_default_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_required_default_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredDefaultValidation**](../../models/RequiredDefaultValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_default_validation_request_body.ApiResponseFor200) | success + +#### post_required_default_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_default_validation_response_body_for_content_types** + +> RequiredDefaultValidation post_required_default_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.required_default_validation import RequiredDefaultValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_default_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_required_default_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_default_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_default_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredDefaultValidation**](../../models/RequiredDefaultValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_validation_request_body** + +> post_required_validation_request_body(required_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.required_validation import RequiredValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredValidation(None) + try: + api_response = api_instance.post_required_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_required_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredValidation**](../../models/RequiredValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_validation_request_body.ApiResponseFor200) | success + +#### post_required_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_validation_response_body_for_content_types** + +> RequiredValidation post_required_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.required_validation import RequiredValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_required_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredValidation**](../../models/RequiredValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_empty_array_request_body** + +> post_required_with_empty_array_request_body(required_with_empty_array) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredWithEmptyArray(None) + try: + api_response = api_instance.post_required_with_empty_array_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_required_with_empty_array_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredWithEmptyArray**](../../models/RequiredWithEmptyArray.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_empty_array_request_body.ApiResponseFor200) | success + +#### post_required_with_empty_array_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_empty_array_response_body_for_content_types** + +> RequiredWithEmptyArray post_required_with_empty_array_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_with_empty_array_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_required_with_empty_array_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_empty_array_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_with_empty_array_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredWithEmptyArray**](../../models/RequiredWithEmptyArray.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_escaped_characters_request_body** + +> post_required_with_escaped_characters_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_required_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_required_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_required_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_escaped_characters_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_required_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_required_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_simple_enum_validation_request_body** + +> post_simple_enum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = SimpleEnumValidation(1) + try: + api_response = api_instance.post_simple_enum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_simple_enum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**SimpleEnumValidation**](../../models/SimpleEnumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_simple_enum_validation_request_body.ApiResponseFor200) | success + +#### post_simple_enum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_simple_enum_validation_response_body_for_content_types** + +> SimpleEnumValidation post_simple_enum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_simple_enum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_simple_enum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_simple_enum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_simple_enum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**SimpleEnumValidation**](../../models/SimpleEnumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_string_type_matches_strings_request_body** + +> post_string_type_matches_strings_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = "body_example" + try: + api_response = api_instance.post_string_type_matches_strings_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_string_type_matches_strings_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_string_type_matches_strings_request_body.ApiResponseFor200) | success + +#### post_string_type_matches_strings_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_string_type_matches_strings_response_body_for_content_types** + +> str post_string_type_matches_strings_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_string_type_matches_strings_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_string_type_matches_strings_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_string_type_matches_strings_response_body_for_content_types.ApiResponseFor200) | success + +#### post_string_type_matches_strings_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body** + +> post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body(the_default_keyword_does_not_do_anything_if_the_property_is_missing) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing( + alpha=5, + ) + try: + api_response = api_instance.post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing**](../../models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.ApiResponseFor200) | success + +#### post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types** + +> TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.ApiResponseFor200) | success + +#### post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing**](../../models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_false_validation_request_body** + +> post_uniqueitems_false_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = UniqueitemsFalseValidation(None) + try: + api_response = api_instance.post_uniqueitems_false_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uniqueitems_false_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsFalseValidation**](../../models/UniqueitemsFalseValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_false_validation_request_body.ApiResponseFor200) | success + +#### post_uniqueitems_false_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_false_validation_response_body_for_content_types** + +> UniqueitemsFalseValidation post_uniqueitems_false_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uniqueitems_false_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uniqueitems_false_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_false_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uniqueitems_false_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsFalseValidation**](../../models/UniqueitemsFalseValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_validation_request_body** + +> post_uniqueitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = UniqueitemsValidation(None) + try: + api_response = api_instance.post_uniqueitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uniqueitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsValidation**](../../models/UniqueitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_validation_request_body.ApiResponseFor200) | success + +#### post_uniqueitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_validation_response_body_for_content_types** + +> UniqueitemsValidation post_uniqueitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uniqueitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uniqueitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uniqueitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsValidation**](../../models/UniqueitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_format_request_body** + +> post_uri_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uri_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_format_request_body.ApiResponseFor200) | success + +#### post_uri_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uri_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_reference_format_request_body** + +> post_uri_reference_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_reference_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uri_reference_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_reference_format_request_body.ApiResponseFor200) | success + +#### post_uri_reference_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_reference_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_reference_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_reference_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uri_reference_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_reference_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_reference_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_template_format_request_body** + +> post_uri_template_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_template_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uri_template_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_template_format_request_body.ApiResponseFor200) | success + +#### post_uri_template_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_template_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_template_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import content_type_json_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = content_type_json_api.ContentTypeJsonApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_template_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ContentTypeJsonApi->post_uri_template_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_template_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_template_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/DefaultApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/DefaultApi.md new file mode 100644 index 0000000000..4fb214ed39 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/DefaultApi.md @@ -0,0 +1,276 @@ + +# unit_test_api.apis.tags.default_api.DefaultApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_invalid_string_value_for_default_request_body**](#post_invalid_string_value_for_default_request_body) | **post** /requestBody/postInvalidStringValueForDefaultRequestBody | +[**post_invalid_string_value_for_default_response_body_for_content_types**](#post_invalid_string_value_for_default_response_body_for_content_types) | **post** /responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes | +[**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body**](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body) | **post** /requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody | +[**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types**](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types) | **post** /responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes | + +# **post_invalid_string_value_for_default_request_body** + +> post_invalid_string_value_for_default_request_body(invalid_string_value_for_default) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import default_api +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = default_api.DefaultApi(api_client) + + # example passing only required values which don't have defaults set + body = InvalidStringValueForDefault(None) + try: + api_response = api_instance.post_invalid_string_value_for_default_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling DefaultApi->post_invalid_string_value_for_default_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidStringValueForDefault**](../../models/InvalidStringValueForDefault.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_string_value_for_default_request_body.ApiResponseFor200) | success + +#### post_invalid_string_value_for_default_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_string_value_for_default_response_body_for_content_types** + +> InvalidStringValueForDefault post_invalid_string_value_for_default_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import default_api +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = default_api.DefaultApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_invalid_string_value_for_default_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling DefaultApi->post_invalid_string_value_for_default_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_string_value_for_default_response_body_for_content_types.ApiResponseFor200) | success + +#### post_invalid_string_value_for_default_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidStringValueForDefault**](../../models/InvalidStringValueForDefault.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body** + +> post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body(the_default_keyword_does_not_do_anything_if_the_property_is_missing) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import default_api +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = default_api.DefaultApi(api_client) + + # example passing only required values which don't have defaults set + body = TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing( + alpha=5, + ) + try: + api_response = api_instance.post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling DefaultApi->post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing**](../../models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.ApiResponseFor200) | success + +#### post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types** + +> TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import default_api +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = default_api.DefaultApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling DefaultApi->post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.ApiResponseFor200) | success + +#### post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing**](../../models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/EnumApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/EnumApi.md new file mode 100644 index 0000000000..ec34586909 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/EnumApi.md @@ -0,0 +1,1075 @@ + +# unit_test_api.apis.tags.enum_api.EnumApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_enum_with0_does_not_match_false_request_body**](#post_enum_with0_does_not_match_false_request_body) | **post** /requestBody/postEnumWith0DoesNotMatchFalseRequestBody | +[**post_enum_with0_does_not_match_false_response_body_for_content_types**](#post_enum_with0_does_not_match_false_response_body_for_content_types) | **post** /responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes | +[**post_enum_with1_does_not_match_true_request_body**](#post_enum_with1_does_not_match_true_request_body) | **post** /requestBody/postEnumWith1DoesNotMatchTrueRequestBody | +[**post_enum_with1_does_not_match_true_response_body_for_content_types**](#post_enum_with1_does_not_match_true_response_body_for_content_types) | **post** /responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes | +[**post_enum_with_escaped_characters_request_body**](#post_enum_with_escaped_characters_request_body) | **post** /requestBody/postEnumWithEscapedCharactersRequestBody | +[**post_enum_with_escaped_characters_response_body_for_content_types**](#post_enum_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes | +[**post_enum_with_false_does_not_match0_request_body**](#post_enum_with_false_does_not_match0_request_body) | **post** /requestBody/postEnumWithFalseDoesNotMatch0RequestBody | +[**post_enum_with_false_does_not_match0_response_body_for_content_types**](#post_enum_with_false_does_not_match0_response_body_for_content_types) | **post** /responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes | +[**post_enum_with_true_does_not_match1_request_body**](#post_enum_with_true_does_not_match1_request_body) | **post** /requestBody/postEnumWithTrueDoesNotMatch1RequestBody | +[**post_enum_with_true_does_not_match1_response_body_for_content_types**](#post_enum_with_true_does_not_match1_response_body_for_content_types) | **post** /responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes | +[**post_enums_in_properties_request_body**](#post_enums_in_properties_request_body) | **post** /requestBody/postEnumsInPropertiesRequestBody | +[**post_enums_in_properties_response_body_for_content_types**](#post_enums_in_properties_response_body_for_content_types) | **post** /responseBody/postEnumsInPropertiesResponseBodyForContentTypes | +[**post_nul_characters_in_strings_request_body**](#post_nul_characters_in_strings_request_body) | **post** /requestBody/postNulCharactersInStringsRequestBody | +[**post_nul_characters_in_strings_response_body_for_content_types**](#post_nul_characters_in_strings_response_body_for_content_types) | **post** /responseBody/postNulCharactersInStringsResponseBodyForContentTypes | +[**post_simple_enum_validation_request_body**](#post_simple_enum_validation_request_body) | **post** /requestBody/postSimpleEnumValidationRequestBody | +[**post_simple_enum_validation_response_body_for_content_types**](#post_simple_enum_validation_response_body_for_content_types) | **post** /responseBody/postSimpleEnumValidationResponseBodyForContentTypes | + +# **post_enum_with0_does_not_match_false_request_body** + +> post_enum_with0_does_not_match_false_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWith0DoesNotMatchFalse(0) + try: + api_response = api_instance.post_enum_with0_does_not_match_false_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with0_does_not_match_false_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith0DoesNotMatchFalse**](../../models/EnumWith0DoesNotMatchFalse.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with0_does_not_match_false_request_body.ApiResponseFor200) | success + +#### post_enum_with0_does_not_match_false_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with0_does_not_match_false_response_body_for_content_types** + +> EnumWith0DoesNotMatchFalse post_enum_with0_does_not_match_false_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with0_does_not_match_false_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with0_does_not_match_false_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with0_does_not_match_false_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with0_does_not_match_false_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith0DoesNotMatchFalse**](../../models/EnumWith0DoesNotMatchFalse.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with1_does_not_match_true_request_body** + +> post_enum_with1_does_not_match_true_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWith1DoesNotMatchTrue(1) + try: + api_response = api_instance.post_enum_with1_does_not_match_true_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with1_does_not_match_true_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith1DoesNotMatchTrue**](../../models/EnumWith1DoesNotMatchTrue.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with1_does_not_match_true_request_body.ApiResponseFor200) | success + +#### post_enum_with1_does_not_match_true_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with1_does_not_match_true_response_body_for_content_types** + +> EnumWith1DoesNotMatchTrue post_enum_with1_does_not_match_true_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with1_does_not_match_true_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with1_does_not_match_true_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with1_does_not_match_true_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with1_does_not_match_true_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith1DoesNotMatchTrue**](../../models/EnumWith1DoesNotMatchTrue.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_escaped_characters_request_body** + +> post_enum_with_escaped_characters_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithEscapedCharacters("foo\nbar") + try: + api_response = api_instance.post_enum_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithEscapedCharacters**](../../models/EnumWithEscapedCharacters.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_enum_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_escaped_characters_response_body_for_content_types** + +> EnumWithEscapedCharacters post_enum_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithEscapedCharacters**](../../models/EnumWithEscapedCharacters.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_false_does_not_match0_request_body** + +> post_enum_with_false_does_not_match0_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithFalseDoesNotMatch0(False) + try: + api_response = api_instance.post_enum_with_false_does_not_match0_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with_false_does_not_match0_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithFalseDoesNotMatch0**](../../models/EnumWithFalseDoesNotMatch0.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_false_does_not_match0_request_body.ApiResponseFor200) | success + +#### post_enum_with_false_does_not_match0_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_false_does_not_match0_response_body_for_content_types** + +> EnumWithFalseDoesNotMatch0 post_enum_with_false_does_not_match0_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_false_does_not_match0_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with_false_does_not_match0_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_false_does_not_match0_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_false_does_not_match0_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithFalseDoesNotMatch0**](../../models/EnumWithFalseDoesNotMatch0.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_true_does_not_match1_request_body** + +> post_enum_with_true_does_not_match1_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithTrueDoesNotMatch1(True) + try: + api_response = api_instance.post_enum_with_true_does_not_match1_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with_true_does_not_match1_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithTrueDoesNotMatch1**](../../models/EnumWithTrueDoesNotMatch1.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_true_does_not_match1_request_body.ApiResponseFor200) | success + +#### post_enum_with_true_does_not_match1_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_true_does_not_match1_response_body_for_content_types** + +> EnumWithTrueDoesNotMatch1 post_enum_with_true_does_not_match1_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_true_does_not_match1_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enum_with_true_does_not_match1_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_true_does_not_match1_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_true_does_not_match1_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithTrueDoesNotMatch1**](../../models/EnumWithTrueDoesNotMatch1.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enums_in_properties_request_body** + +> post_enums_in_properties_request_body(enums_in_properties) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enums_in_properties import EnumsInProperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumsInProperties( + foo="foo", + bar="bar", + ) + try: + api_response = api_instance.post_enums_in_properties_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enums_in_properties_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumsInProperties**](../../models/EnumsInProperties.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enums_in_properties_request_body.ApiResponseFor200) | success + +#### post_enums_in_properties_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enums_in_properties_response_body_for_content_types** + +> EnumsInProperties post_enums_in_properties_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.enums_in_properties import EnumsInProperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enums_in_properties_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_enums_in_properties_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enums_in_properties_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enums_in_properties_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumsInProperties**](../../models/EnumsInProperties.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nul_characters_in_strings_request_body** + +> post_nul_characters_in_strings_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example passing only required values which don't have defaults set + body = NulCharactersInStrings("hello\x00there") + try: + api_response = api_instance.post_nul_characters_in_strings_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_nul_characters_in_strings_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NulCharactersInStrings**](../../models/NulCharactersInStrings.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nul_characters_in_strings_request_body.ApiResponseFor200) | success + +#### post_nul_characters_in_strings_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nul_characters_in_strings_response_body_for_content_types** + +> NulCharactersInStrings post_nul_characters_in_strings_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nul_characters_in_strings_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_nul_characters_in_strings_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nul_characters_in_strings_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nul_characters_in_strings_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NulCharactersInStrings**](../../models/NulCharactersInStrings.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_simple_enum_validation_request_body** + +> post_simple_enum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example passing only required values which don't have defaults set + body = SimpleEnumValidation(1) + try: + api_response = api_instance.post_simple_enum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_simple_enum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**SimpleEnumValidation**](../../models/SimpleEnumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_simple_enum_validation_request_body.ApiResponseFor200) | success + +#### post_simple_enum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_simple_enum_validation_response_body_for_content_types** + +> SimpleEnumValidation post_simple_enum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import enum_api +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = enum_api.EnumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_simple_enum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling EnumApi->post_simple_enum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_simple_enum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_simple_enum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**SimpleEnumValidation**](../../models/SimpleEnumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/FormatApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/FormatApi.md new file mode 100644 index 0000000000..08431f22e6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/FormatApi.md @@ -0,0 +1,1205 @@ + +# unit_test_api.apis.tags.format_api.FormatApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_date_time_format_request_body**](#post_date_time_format_request_body) | **post** /requestBody/postDateTimeFormatRequestBody | +[**post_date_time_format_response_body_for_content_types**](#post_date_time_format_response_body_for_content_types) | **post** /responseBody/postDateTimeFormatResponseBodyForContentTypes | +[**post_email_format_request_body**](#post_email_format_request_body) | **post** /requestBody/postEmailFormatRequestBody | +[**post_email_format_response_body_for_content_types**](#post_email_format_response_body_for_content_types) | **post** /responseBody/postEmailFormatResponseBodyForContentTypes | +[**post_hostname_format_request_body**](#post_hostname_format_request_body) | **post** /requestBody/postHostnameFormatRequestBody | +[**post_hostname_format_response_body_for_content_types**](#post_hostname_format_response_body_for_content_types) | **post** /responseBody/postHostnameFormatResponseBodyForContentTypes | +[**post_ipv4_format_request_body**](#post_ipv4_format_request_body) | **post** /requestBody/postIpv4FormatRequestBody | +[**post_ipv4_format_response_body_for_content_types**](#post_ipv4_format_response_body_for_content_types) | **post** /responseBody/postIpv4FormatResponseBodyForContentTypes | +[**post_ipv6_format_request_body**](#post_ipv6_format_request_body) | **post** /requestBody/postIpv6FormatRequestBody | +[**post_ipv6_format_response_body_for_content_types**](#post_ipv6_format_response_body_for_content_types) | **post** /responseBody/postIpv6FormatResponseBodyForContentTypes | +[**post_json_pointer_format_request_body**](#post_json_pointer_format_request_body) | **post** /requestBody/postJsonPointerFormatRequestBody | +[**post_json_pointer_format_response_body_for_content_types**](#post_json_pointer_format_response_body_for_content_types) | **post** /responseBody/postJsonPointerFormatResponseBodyForContentTypes | +[**post_uri_format_request_body**](#post_uri_format_request_body) | **post** /requestBody/postUriFormatRequestBody | +[**post_uri_format_response_body_for_content_types**](#post_uri_format_response_body_for_content_types) | **post** /responseBody/postUriFormatResponseBodyForContentTypes | +[**post_uri_reference_format_request_body**](#post_uri_reference_format_request_body) | **post** /requestBody/postUriReferenceFormatRequestBody | +[**post_uri_reference_format_response_body_for_content_types**](#post_uri_reference_format_response_body_for_content_types) | **post** /responseBody/postUriReferenceFormatResponseBodyForContentTypes | +[**post_uri_template_format_request_body**](#post_uri_template_format_request_body) | **post** /requestBody/postUriTemplateFormatRequestBody | +[**post_uri_template_format_response_body_for_content_types**](#post_uri_template_format_response_body_for_content_types) | **post** /responseBody/postUriTemplateFormatResponseBodyForContentTypes | + +# **post_date_time_format_request_body** + +> post_date_time_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_date_time_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_date_time_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | value must conform to RFC-3339 date-time + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_date_time_format_request_body.ApiResponseFor200) | success + +#### post_date_time_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_date_time_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_date_time_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_date_time_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_date_time_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_date_time_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_date_time_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | value must conform to RFC-3339 date-time + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_email_format_request_body** + +> post_email_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_email_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_email_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_email_format_request_body.ApiResponseFor200) | success + +#### post_email_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_email_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_email_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_email_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_email_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_email_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_email_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_hostname_format_request_body** + +> post_hostname_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_hostname_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_hostname_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_hostname_format_request_body.ApiResponseFor200) | success + +#### post_hostname_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_hostname_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_hostname_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_hostname_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_hostname_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_hostname_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_hostname_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv4_format_request_body** + +> post_ipv4_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ipv4_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_ipv4_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv4_format_request_body.ApiResponseFor200) | success + +#### post_ipv4_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv4_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ipv4_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ipv4_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_ipv4_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv4_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ipv4_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv6_format_request_body** + +> post_ipv6_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ipv6_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_ipv6_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv6_format_request_body.ApiResponseFor200) | success + +#### post_ipv6_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv6_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ipv6_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ipv6_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_ipv6_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv6_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ipv6_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_json_pointer_format_request_body** + +> post_json_pointer_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_json_pointer_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_json_pointer_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_json_pointer_format_request_body.ApiResponseFor200) | success + +#### post_json_pointer_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_json_pointer_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_json_pointer_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_json_pointer_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_json_pointer_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_json_pointer_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_json_pointer_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_format_request_body** + +> post_uri_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_uri_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_format_request_body.ApiResponseFor200) | success + +#### post_uri_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_uri_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_reference_format_request_body** + +> post_uri_reference_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_reference_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_uri_reference_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_reference_format_request_body.ApiResponseFor200) | success + +#### post_uri_reference_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_reference_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_reference_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_reference_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_uri_reference_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_reference_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_reference_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_template_format_request_body** + +> post_uri_template_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_template_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_uri_template_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_template_format_request_body.ApiResponseFor200) | success + +#### post_uri_template_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_template_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_template_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import format_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = format_api.FormatApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_template_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling FormatApi->post_uri_template_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_template_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_template_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ItemsApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ItemsApi.md new file mode 100644 index 0000000000..a3892956f1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ItemsApi.md @@ -0,0 +1,149 @@ + +# unit_test_api.apis.tags.items_api.ItemsApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_nested_items_request_body**](#post_nested_items_request_body) | **post** /requestBody/postNestedItemsRequestBody | +[**post_nested_items_response_body_for_content_types**](#post_nested_items_response_body_for_content_types) | **post** /responseBody/postNestedItemsResponseBodyForContentTypes | + +# **post_nested_items_request_body** + +> post_nested_items_request_body(nested_items) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import items_api +from unit_test_api.model.nested_items import NestedItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = items_api.ItemsApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedItems([ + [ + [ + [ + 3.14 + ] + ] + ] + ]) + try: + api_response = api_instance.post_nested_items_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ItemsApi->post_nested_items_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedItems**](../../models/NestedItems.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_items_request_body.ApiResponseFor200) | success + +#### post_nested_items_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_items_response_body_for_content_types** + +> NestedItems post_nested_items_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import items_api +from unit_test_api.model.nested_items import NestedItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = items_api.ItemsApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_items_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ItemsApi->post_nested_items_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_items_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_items_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedItems**](../../models/NestedItems.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaxItemsApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaxItemsApi.md new file mode 100644 index 0000000000..481d933e61 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaxItemsApi.md @@ -0,0 +1,141 @@ + +# unit_test_api.apis.tags.max_items_api.MaxItemsApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_maxitems_validation_request_body**](#post_maxitems_validation_request_body) | **post** /requestBody/postMaxitemsValidationRequestBody | +[**post_maxitems_validation_response_body_for_content_types**](#post_maxitems_validation_response_body_for_content_types) | **post** /responseBody/postMaxitemsValidationResponseBodyForContentTypes | + +# **post_maxitems_validation_request_body** + +> post_maxitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import max_items_api +from unit_test_api.model.maxitems_validation import MaxitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = max_items_api.MaxItemsApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxitemsValidation(None) + try: + api_response = api_instance.post_maxitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MaxItemsApi->post_maxitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxitemsValidation**](../../models/MaxitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxitems_validation_request_body.ApiResponseFor200) | success + +#### post_maxitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxitems_validation_response_body_for_content_types** + +> MaxitemsValidation post_maxitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import max_items_api +from unit_test_api.model.maxitems_validation import MaxitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = max_items_api.MaxItemsApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MaxItemsApi->post_maxitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxitemsValidation**](../../models/MaxitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaxLengthApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaxLengthApi.md new file mode 100644 index 0000000000..98d63d4924 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaxLengthApi.md @@ -0,0 +1,141 @@ + +# unit_test_api.apis.tags.max_length_api.MaxLengthApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_maxlength_validation_request_body**](#post_maxlength_validation_request_body) | **post** /requestBody/postMaxlengthValidationRequestBody | +[**post_maxlength_validation_response_body_for_content_types**](#post_maxlength_validation_response_body_for_content_types) | **post** /responseBody/postMaxlengthValidationResponseBodyForContentTypes | + +# **post_maxlength_validation_request_body** + +> post_maxlength_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import max_length_api +from unit_test_api.model.maxlength_validation import MaxlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = max_length_api.MaxLengthApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxlengthValidation(None) + try: + api_response = api_instance.post_maxlength_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MaxLengthApi->post_maxlength_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxlengthValidation**](../../models/MaxlengthValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxlength_validation_request_body.ApiResponseFor200) | success + +#### post_maxlength_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxlength_validation_response_body_for_content_types** + +> MaxlengthValidation post_maxlength_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import max_length_api +from unit_test_api.model.maxlength_validation import MaxlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = max_length_api.MaxLengthApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxlength_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MaxLengthApi->post_maxlength_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxlength_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxlength_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxlengthValidation**](../../models/MaxlengthValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaxPropertiesApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaxPropertiesApi.md new file mode 100644 index 0000000000..30bb70e217 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaxPropertiesApi.md @@ -0,0 +1,274 @@ + +# unit_test_api.apis.tags.max_properties_api.MaxPropertiesApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_maxproperties0_means_the_object_is_empty_request_body**](#post_maxproperties0_means_the_object_is_empty_request_body) | **post** /requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody | +[**post_maxproperties0_means_the_object_is_empty_response_body_for_content_types**](#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types) | **post** /responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes | +[**post_maxproperties_validation_request_body**](#post_maxproperties_validation_request_body) | **post** /requestBody/postMaxpropertiesValidationRequestBody | +[**post_maxproperties_validation_response_body_for_content_types**](#post_maxproperties_validation_response_body_for_content_types) | **post** /responseBody/postMaxpropertiesValidationResponseBodyForContentTypes | + +# **post_maxproperties0_means_the_object_is_empty_request_body** + +> post_maxproperties0_means_the_object_is_empty_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import max_properties_api +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = max_properties_api.MaxPropertiesApi(api_client) + + # example passing only required values which don't have defaults set + body = Maxproperties0MeansTheObjectIsEmpty(None) + try: + api_response = api_instance.post_maxproperties0_means_the_object_is_empty_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MaxPropertiesApi->post_maxproperties0_means_the_object_is_empty_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Maxproperties0MeansTheObjectIsEmpty**](../../models/Maxproperties0MeansTheObjectIsEmpty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties0_means_the_object_is_empty_request_body.ApiResponseFor200) | success + +#### post_maxproperties0_means_the_object_is_empty_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties0_means_the_object_is_empty_response_body_for_content_types** + +> Maxproperties0MeansTheObjectIsEmpty post_maxproperties0_means_the_object_is_empty_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import max_properties_api +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = max_properties_api.MaxPropertiesApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxproperties0_means_the_object_is_empty_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MaxPropertiesApi->post_maxproperties0_means_the_object_is_empty_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Maxproperties0MeansTheObjectIsEmpty**](../../models/Maxproperties0MeansTheObjectIsEmpty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties_validation_request_body** + +> post_maxproperties_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import max_properties_api +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = max_properties_api.MaxPropertiesApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxpropertiesValidation(None) + try: + api_response = api_instance.post_maxproperties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MaxPropertiesApi->post_maxproperties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxpropertiesValidation**](../../models/MaxpropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties_validation_request_body.ApiResponseFor200) | success + +#### post_maxproperties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties_validation_response_body_for_content_types** + +> MaxpropertiesValidation post_maxproperties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import max_properties_api +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = max_properties_api.MaxPropertiesApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxproperties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MaxPropertiesApi->post_maxproperties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxproperties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxpropertiesValidation**](../../models/MaxpropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaximumApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaximumApi.md new file mode 100644 index 0000000000..388aa8b796 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MaximumApi.md @@ -0,0 +1,274 @@ + +# unit_test_api.apis.tags.maximum_api.MaximumApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_maximum_validation_request_body**](#post_maximum_validation_request_body) | **post** /requestBody/postMaximumValidationRequestBody | +[**post_maximum_validation_response_body_for_content_types**](#post_maximum_validation_response_body_for_content_types) | **post** /responseBody/postMaximumValidationResponseBodyForContentTypes | +[**post_maximum_validation_with_unsigned_integer_request_body**](#post_maximum_validation_with_unsigned_integer_request_body) | **post** /requestBody/postMaximumValidationWithUnsignedIntegerRequestBody | +[**post_maximum_validation_with_unsigned_integer_response_body_for_content_types**](#post_maximum_validation_with_unsigned_integer_response_body_for_content_types) | **post** /responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes | + +# **post_maximum_validation_request_body** + +> post_maximum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import maximum_api +from unit_test_api.model.maximum_validation import MaximumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = maximum_api.MaximumApi(api_client) + + # example passing only required values which don't have defaults set + body = MaximumValidation(None) + try: + api_response = api_instance.post_maximum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MaximumApi->post_maximum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidation**](../../models/MaximumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_request_body.ApiResponseFor200) | success + +#### post_maximum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_response_body_for_content_types** + +> MaximumValidation post_maximum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import maximum_api +from unit_test_api.model.maximum_validation import MaximumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = maximum_api.MaximumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maximum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MaximumApi->post_maximum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maximum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidation**](../../models/MaximumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_with_unsigned_integer_request_body** + +> post_maximum_validation_with_unsigned_integer_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import maximum_api +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = maximum_api.MaximumApi(api_client) + + # example passing only required values which don't have defaults set + body = MaximumValidationWithUnsignedInteger(None) + try: + api_response = api_instance.post_maximum_validation_with_unsigned_integer_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MaximumApi->post_maximum_validation_with_unsigned_integer_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidationWithUnsignedInteger**](../../models/MaximumValidationWithUnsignedInteger.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_with_unsigned_integer_request_body.ApiResponseFor200) | success + +#### post_maximum_validation_with_unsigned_integer_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_with_unsigned_integer_response_body_for_content_types** + +> MaximumValidationWithUnsignedInteger post_maximum_validation_with_unsigned_integer_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import maximum_api +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = maximum_api.MaximumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maximum_validation_with_unsigned_integer_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MaximumApi->post_maximum_validation_with_unsigned_integer_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_with_unsigned_integer_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maximum_validation_with_unsigned_integer_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidationWithUnsignedInteger**](../../models/MaximumValidationWithUnsignedInteger.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinItemsApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinItemsApi.md new file mode 100644 index 0000000000..47fece8482 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinItemsApi.md @@ -0,0 +1,141 @@ + +# unit_test_api.apis.tags.min_items_api.MinItemsApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_minitems_validation_request_body**](#post_minitems_validation_request_body) | **post** /requestBody/postMinitemsValidationRequestBody | +[**post_minitems_validation_response_body_for_content_types**](#post_minitems_validation_response_body_for_content_types) | **post** /responseBody/postMinitemsValidationResponseBodyForContentTypes | + +# **post_minitems_validation_request_body** + +> post_minitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import min_items_api +from unit_test_api.model.minitems_validation import MinitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = min_items_api.MinItemsApi(api_client) + + # example passing only required values which don't have defaults set + body = MinitemsValidation(None) + try: + api_response = api_instance.post_minitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MinItemsApi->post_minitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinitemsValidation**](../../models/MinitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minitems_validation_request_body.ApiResponseFor200) | success + +#### post_minitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minitems_validation_response_body_for_content_types** + +> MinitemsValidation post_minitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import min_items_api +from unit_test_api.model.minitems_validation import MinitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = min_items_api.MinItemsApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MinItemsApi->post_minitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinitemsValidation**](../../models/MinitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinLengthApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinLengthApi.md new file mode 100644 index 0000000000..918d02f43e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinLengthApi.md @@ -0,0 +1,141 @@ + +# unit_test_api.apis.tags.min_length_api.MinLengthApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_minlength_validation_request_body**](#post_minlength_validation_request_body) | **post** /requestBody/postMinlengthValidationRequestBody | +[**post_minlength_validation_response_body_for_content_types**](#post_minlength_validation_response_body_for_content_types) | **post** /responseBody/postMinlengthValidationResponseBodyForContentTypes | + +# **post_minlength_validation_request_body** + +> post_minlength_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import min_length_api +from unit_test_api.model.minlength_validation import MinlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = min_length_api.MinLengthApi(api_client) + + # example passing only required values which don't have defaults set + body = MinlengthValidation(None) + try: + api_response = api_instance.post_minlength_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MinLengthApi->post_minlength_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinlengthValidation**](../../models/MinlengthValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minlength_validation_request_body.ApiResponseFor200) | success + +#### post_minlength_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minlength_validation_response_body_for_content_types** + +> MinlengthValidation post_minlength_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import min_length_api +from unit_test_api.model.minlength_validation import MinlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = min_length_api.MinLengthApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minlength_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MinLengthApi->post_minlength_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minlength_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minlength_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinlengthValidation**](../../models/MinlengthValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinPropertiesApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinPropertiesApi.md new file mode 100644 index 0000000000..7d44da6f0b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinPropertiesApi.md @@ -0,0 +1,141 @@ + +# unit_test_api.apis.tags.min_properties_api.MinPropertiesApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_minproperties_validation_request_body**](#post_minproperties_validation_request_body) | **post** /requestBody/postMinpropertiesValidationRequestBody | +[**post_minproperties_validation_response_body_for_content_types**](#post_minproperties_validation_response_body_for_content_types) | **post** /responseBody/postMinpropertiesValidationResponseBodyForContentTypes | + +# **post_minproperties_validation_request_body** + +> post_minproperties_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import min_properties_api +from unit_test_api.model.minproperties_validation import MinpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = min_properties_api.MinPropertiesApi(api_client) + + # example passing only required values which don't have defaults set + body = MinpropertiesValidation(None) + try: + api_response = api_instance.post_minproperties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MinPropertiesApi->post_minproperties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinpropertiesValidation**](../../models/MinpropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minproperties_validation_request_body.ApiResponseFor200) | success + +#### post_minproperties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minproperties_validation_response_body_for_content_types** + +> MinpropertiesValidation post_minproperties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import min_properties_api +from unit_test_api.model.minproperties_validation import MinpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = min_properties_api.MinPropertiesApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minproperties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MinPropertiesApi->post_minproperties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minproperties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minproperties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinpropertiesValidation**](../../models/MinpropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinimumApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinimumApi.md new file mode 100644 index 0000000000..b176533c96 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MinimumApi.md @@ -0,0 +1,274 @@ + +# unit_test_api.apis.tags.minimum_api.MinimumApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_minimum_validation_request_body**](#post_minimum_validation_request_body) | **post** /requestBody/postMinimumValidationRequestBody | +[**post_minimum_validation_response_body_for_content_types**](#post_minimum_validation_response_body_for_content_types) | **post** /responseBody/postMinimumValidationResponseBodyForContentTypes | +[**post_minimum_validation_with_signed_integer_request_body**](#post_minimum_validation_with_signed_integer_request_body) | **post** /requestBody/postMinimumValidationWithSignedIntegerRequestBody | +[**post_minimum_validation_with_signed_integer_response_body_for_content_types**](#post_minimum_validation_with_signed_integer_response_body_for_content_types) | **post** /responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes | + +# **post_minimum_validation_request_body** + +> post_minimum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import minimum_api +from unit_test_api.model.minimum_validation import MinimumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = minimum_api.MinimumApi(api_client) + + # example passing only required values which don't have defaults set + body = MinimumValidation(None) + try: + api_response = api_instance.post_minimum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MinimumApi->post_minimum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidation**](../../models/MinimumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_request_body.ApiResponseFor200) | success + +#### post_minimum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_response_body_for_content_types** + +> MinimumValidation post_minimum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import minimum_api +from unit_test_api.model.minimum_validation import MinimumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = minimum_api.MinimumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minimum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MinimumApi->post_minimum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minimum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidation**](../../models/MinimumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_with_signed_integer_request_body** + +> post_minimum_validation_with_signed_integer_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import minimum_api +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = minimum_api.MinimumApi(api_client) + + # example passing only required values which don't have defaults set + body = MinimumValidationWithSignedInteger(None) + try: + api_response = api_instance.post_minimum_validation_with_signed_integer_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MinimumApi->post_minimum_validation_with_signed_integer_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidationWithSignedInteger**](../../models/MinimumValidationWithSignedInteger.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_with_signed_integer_request_body.ApiResponseFor200) | success + +#### post_minimum_validation_with_signed_integer_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_with_signed_integer_response_body_for_content_types** + +> MinimumValidationWithSignedInteger post_minimum_validation_with_signed_integer_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import minimum_api +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = minimum_api.MinimumApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minimum_validation_with_signed_integer_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MinimumApi->post_minimum_validation_with_signed_integer_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_with_signed_integer_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minimum_validation_with_signed_integer_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidationWithSignedInteger**](../../models/MinimumValidationWithSignedInteger.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ModelNotApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ModelNotApi.md new file mode 100644 index 0000000000..0c1ab7ec02 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ModelNotApi.md @@ -0,0 +1,471 @@ + +# unit_test_api.apis.tags.model_not_api.ModelNotApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_forbidden_property_request_body**](#post_forbidden_property_request_body) | **post** /requestBody/postForbiddenPropertyRequestBody | +[**post_forbidden_property_response_body_for_content_types**](#post_forbidden_property_response_body_for_content_types) | **post** /responseBody/postForbiddenPropertyResponseBodyForContentTypes | +[**post_not_more_complex_schema_request_body**](#post_not_more_complex_schema_request_body) | **post** /requestBody/postNotMoreComplexSchemaRequestBody | +[**post_not_more_complex_schema_response_body_for_content_types**](#post_not_more_complex_schema_response_body_for_content_types) | **post** /responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes | +[**post_not_request_body**](#post_not_request_body) | **post** /requestBody/postNotRequestBody | +[**post_not_response_body_for_content_types**](#post_not_response_body_for_content_types) | **post** /responseBody/postNotResponseBodyForContentTypes | + +# **post_forbidden_property_request_body** + +> post_forbidden_property_request_body(forbidden_property) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import model_not_api +from unit_test_api.model.forbidden_property import ForbiddenProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = model_not_api.ModelNotApi(api_client) + + # example passing only required values which don't have defaults set + body = ForbiddenProperty(None) + try: + api_response = api_instance.post_forbidden_property_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ModelNotApi->post_forbidden_property_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ForbiddenProperty**](../../models/ForbiddenProperty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_forbidden_property_request_body.ApiResponseFor200) | success + +#### post_forbidden_property_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_forbidden_property_response_body_for_content_types** + +> ForbiddenProperty post_forbidden_property_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import model_not_api +from unit_test_api.model.forbidden_property import ForbiddenProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = model_not_api.ModelNotApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_forbidden_property_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ModelNotApi->post_forbidden_property_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_forbidden_property_response_body_for_content_types.ApiResponseFor200) | success + +#### post_forbidden_property_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ForbiddenProperty**](../../models/ForbiddenProperty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_more_complex_schema_request_body** + +> post_not_more_complex_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import model_not_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = model_not_api.ModelNotApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_not_more_complex_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ModelNotApi->post_not_more_complex_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_more_complex_schema_request_body.ApiResponseFor200) | success + +#### post_not_more_complex_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_more_complex_schema_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_not_more_complex_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import model_not_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = model_not_api.ModelNotApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_not_more_complex_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ModelNotApi->post_not_more_complex_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_more_complex_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_not_more_complex_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_request_body** + +> post_not_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import model_not_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = model_not_api.ModelNotApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_not_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling ModelNotApi->post_not_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | decimal.Decimal, int, | decimal.Decimal, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_request_body.ApiResponseFor200) | success + +#### post_not_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_not_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import model_not_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = model_not_api.ModelNotApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_not_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ModelNotApi->post_not_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_response_body_for_content_types.ApiResponseFor200) | success + +#### post_not_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | decimal.Decimal, int, | decimal.Decimal, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MultipleOfApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MultipleOfApi.md new file mode 100644 index 0000000000..dae45d4773 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/MultipleOfApi.md @@ -0,0 +1,540 @@ + +# unit_test_api.apis.tags.multiple_of_api.MultipleOfApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_by_int_request_body**](#post_by_int_request_body) | **post** /requestBody/postByIntRequestBody | +[**post_by_int_response_body_for_content_types**](#post_by_int_response_body_for_content_types) | **post** /responseBody/postByIntResponseBodyForContentTypes | +[**post_by_number_request_body**](#post_by_number_request_body) | **post** /requestBody/postByNumberRequestBody | +[**post_by_number_response_body_for_content_types**](#post_by_number_response_body_for_content_types) | **post** /responseBody/postByNumberResponseBodyForContentTypes | +[**post_by_small_number_request_body**](#post_by_small_number_request_body) | **post** /requestBody/postBySmallNumberRequestBody | +[**post_by_small_number_response_body_for_content_types**](#post_by_small_number_response_body_for_content_types) | **post** /responseBody/postBySmallNumberResponseBodyForContentTypes | +[**post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body**](#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body) | **post** /requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody | +[**post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types**](#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types) | **post** /responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes | + +# **post_by_int_request_body** + +> post_by_int_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import multiple_of_api +from unit_test_api.model.by_int import ByInt +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = multiple_of_api.MultipleOfApi(api_client) + + # example passing only required values which don't have defaults set + body = ByInt(None) + try: + api_response = api_instance.post_by_int_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MultipleOfApi->post_by_int_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByInt**](../../models/ByInt.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_int_request_body.ApiResponseFor200) | success + +#### post_by_int_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_int_response_body_for_content_types** + +> ByInt post_by_int_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import multiple_of_api +from unit_test_api.model.by_int import ByInt +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = multiple_of_api.MultipleOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_int_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MultipleOfApi->post_by_int_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_int_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_int_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByInt**](../../models/ByInt.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_number_request_body** + +> post_by_number_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import multiple_of_api +from unit_test_api.model.by_number import ByNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = multiple_of_api.MultipleOfApi(api_client) + + # example passing only required values which don't have defaults set + body = ByNumber(None) + try: + api_response = api_instance.post_by_number_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MultipleOfApi->post_by_number_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByNumber**](../../models/ByNumber.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_number_request_body.ApiResponseFor200) | success + +#### post_by_number_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_number_response_body_for_content_types** + +> ByNumber post_by_number_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import multiple_of_api +from unit_test_api.model.by_number import ByNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = multiple_of_api.MultipleOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_number_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MultipleOfApi->post_by_number_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_number_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_number_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByNumber**](../../models/ByNumber.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_small_number_request_body** + +> post_by_small_number_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import multiple_of_api +from unit_test_api.model.by_small_number import BySmallNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = multiple_of_api.MultipleOfApi(api_client) + + # example passing only required values which don't have defaults set + body = BySmallNumber(None) + try: + api_response = api_instance.post_by_small_number_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MultipleOfApi->post_by_small_number_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**BySmallNumber**](../../models/BySmallNumber.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_small_number_request_body.ApiResponseFor200) | success + +#### post_by_small_number_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_small_number_response_body_for_content_types** + +> BySmallNumber post_by_small_number_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import multiple_of_api +from unit_test_api.model.by_small_number import BySmallNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = multiple_of_api.MultipleOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_small_number_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MultipleOfApi->post_by_small_number_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_small_number_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_small_number_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**BySmallNumber**](../../models/BySmallNumber.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body** + +> post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import multiple_of_api +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = multiple_of_api.MultipleOfApi(api_client) + + # example passing only required values which don't have defaults set + body = InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf(1) + try: + api_response = api_instance.post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling MultipleOfApi->post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf**](../../models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.ApiResponseFor200) | success + +#### post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types** + +> InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import multiple_of_api +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = multiple_of_api.MultipleOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling MultipleOfApi->post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.ApiResponseFor200) | success + +#### post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf**](../../models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/OneOfApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/OneOfApi.md new file mode 100644 index 0000000000..9f6c2b244d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/OneOfApi.md @@ -0,0 +1,806 @@ + +# unit_test_api.apis.tags.one_of_api.OneOfApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_nested_oneof_to_check_validation_semantics_request_body**](#post_nested_oneof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedOneofToCheckValidationSemanticsRequestBody | +[**post_nested_oneof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_oneof_complex_types_request_body**](#post_oneof_complex_types_request_body) | **post** /requestBody/postOneofComplexTypesRequestBody | +[**post_oneof_complex_types_response_body_for_content_types**](#post_oneof_complex_types_response_body_for_content_types) | **post** /responseBody/postOneofComplexTypesResponseBodyForContentTypes | +[**post_oneof_request_body**](#post_oneof_request_body) | **post** /requestBody/postOneofRequestBody | +[**post_oneof_response_body_for_content_types**](#post_oneof_response_body_for_content_types) | **post** /responseBody/postOneofResponseBodyForContentTypes | +[**post_oneof_with_base_schema_request_body**](#post_oneof_with_base_schema_request_body) | **post** /requestBody/postOneofWithBaseSchemaRequestBody | +[**post_oneof_with_base_schema_response_body_for_content_types**](#post_oneof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes | +[**post_oneof_with_empty_schema_request_body**](#post_oneof_with_empty_schema_request_body) | **post** /requestBody/postOneofWithEmptySchemaRequestBody | +[**post_oneof_with_empty_schema_response_body_for_content_types**](#post_oneof_with_empty_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes | +[**post_oneof_with_required_request_body**](#post_oneof_with_required_request_body) | **post** /requestBody/postOneofWithRequiredRequestBody | +[**post_oneof_with_required_response_body_for_content_types**](#post_oneof_with_required_response_body_for_content_types) | **post** /responseBody/postOneofWithRequiredResponseBodyForContentTypes | + +# **post_nested_oneof_to_check_validation_semantics_request_body** + +> post_nested_oneof_to_check_validation_semantics_request_body(nested_oneof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedOneofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_oneof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_nested_oneof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedOneofToCheckValidationSemantics**](../../models/NestedOneofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_oneof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_oneof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_oneof_to_check_validation_semantics_response_body_for_content_types** + +> NestedOneofToCheckValidationSemantics post_nested_oneof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_oneof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_nested_oneof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedOneofToCheckValidationSemantics**](../../models/NestedOneofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_complex_types_request_body** + +> post_oneof_complex_types_request_body(oneof_complex_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof_complex_types import OneofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofComplexTypes(None) + try: + api_response = api_instance.post_oneof_complex_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_complex_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofComplexTypes**](../../models/OneofComplexTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_complex_types_request_body.ApiResponseFor200) | success + +#### post_oneof_complex_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_complex_types_response_body_for_content_types** + +> OneofComplexTypes post_oneof_complex_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof_complex_types import OneofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_complex_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_complex_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_complex_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_complex_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofComplexTypes**](../../models/OneofComplexTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_request_body** + +> post_oneof_request_body(oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof import Oneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example passing only required values which don't have defaults set + body = Oneof(None) + try: + api_response = api_instance.post_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Oneof**](../../models/Oneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_request_body.ApiResponseFor200) | success + +#### post_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_response_body_for_content_types** + +> Oneof post_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof import Oneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Oneof**](../../models/Oneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_base_schema_request_body** + +> post_oneof_with_base_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithBaseSchema("body_example") + try: + api_response = api_instance.post_oneof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithBaseSchema**](../../models/OneofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_oneof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_base_schema_response_body_for_content_types** + +> OneofWithBaseSchema post_oneof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithBaseSchema**](../../models/OneofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_empty_schema_request_body** + +> post_oneof_with_empty_schema_request_body(oneof_with_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithEmptySchema(None) + try: + api_response = api_instance.post_oneof_with_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_with_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithEmptySchema**](../../models/OneofWithEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_empty_schema_request_body.ApiResponseFor200) | success + +#### post_oneof_with_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_empty_schema_response_body_for_content_types** + +> OneofWithEmptySchema post_oneof_with_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_with_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithEmptySchema**](../../models/OneofWithEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_required_request_body** + +> post_oneof_with_required_request_body(oneof_with_required) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof_with_required import OneofWithRequired +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithRequired() + try: + api_response = api_instance.post_oneof_with_required_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_with_required_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithRequired**](../../models/OneofWithRequired.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_required_request_body.ApiResponseFor200) | success + +#### post_oneof_with_required_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_required_response_body_for_content_types** + +> OneofWithRequired post_oneof_with_required_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import one_of_api +from unit_test_api.model.oneof_with_required import OneofWithRequired +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = one_of_api.OneOfApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_required_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling OneOfApi->post_oneof_with_required_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_required_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_required_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithRequired**](../../models/OneofWithRequired.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/OperationRequestBodyApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/OperationRequestBodyApi.md new file mode 100644 index 0000000000..b483f613cc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/OperationRequestBodyApi.md @@ -0,0 +1,6335 @@ + +# unit_test_api.apis.tags.operation_request_body_api.OperationRequestBodyApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_additionalproperties_allows_a_schema_which_should_validate_request_body**](#post_additionalproperties_allows_a_schema_which_should_validate_request_body) | **post** /requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody | +[**post_additionalproperties_are_allowed_by_default_request_body**](#post_additionalproperties_are_allowed_by_default_request_body) | **post** /requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody | +[**post_additionalproperties_can_exist_by_itself_request_body**](#post_additionalproperties_can_exist_by_itself_request_body) | **post** /requestBody/postAdditionalpropertiesCanExistByItselfRequestBody | +[**post_additionalproperties_should_not_look_in_applicators_request_body**](#post_additionalproperties_should_not_look_in_applicators_request_body) | **post** /requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody | +[**post_allof_combined_with_anyof_oneof_request_body**](#post_allof_combined_with_anyof_oneof_request_body) | **post** /requestBody/postAllofCombinedWithAnyofOneofRequestBody | +[**post_allof_request_body**](#post_allof_request_body) | **post** /requestBody/postAllofRequestBody | +[**post_allof_simple_types_request_body**](#post_allof_simple_types_request_body) | **post** /requestBody/postAllofSimpleTypesRequestBody | +[**post_allof_with_base_schema_request_body**](#post_allof_with_base_schema_request_body) | **post** /requestBody/postAllofWithBaseSchemaRequestBody | +[**post_allof_with_one_empty_schema_request_body**](#post_allof_with_one_empty_schema_request_body) | **post** /requestBody/postAllofWithOneEmptySchemaRequestBody | +[**post_allof_with_the_first_empty_schema_request_body**](#post_allof_with_the_first_empty_schema_request_body) | **post** /requestBody/postAllofWithTheFirstEmptySchemaRequestBody | +[**post_allof_with_the_last_empty_schema_request_body**](#post_allof_with_the_last_empty_schema_request_body) | **post** /requestBody/postAllofWithTheLastEmptySchemaRequestBody | +[**post_allof_with_two_empty_schemas_request_body**](#post_allof_with_two_empty_schemas_request_body) | **post** /requestBody/postAllofWithTwoEmptySchemasRequestBody | +[**post_anyof_complex_types_request_body**](#post_anyof_complex_types_request_body) | **post** /requestBody/postAnyofComplexTypesRequestBody | +[**post_anyof_request_body**](#post_anyof_request_body) | **post** /requestBody/postAnyofRequestBody | +[**post_anyof_with_base_schema_request_body**](#post_anyof_with_base_schema_request_body) | **post** /requestBody/postAnyofWithBaseSchemaRequestBody | +[**post_anyof_with_one_empty_schema_request_body**](#post_anyof_with_one_empty_schema_request_body) | **post** /requestBody/postAnyofWithOneEmptySchemaRequestBody | +[**post_array_type_matches_arrays_request_body**](#post_array_type_matches_arrays_request_body) | **post** /requestBody/postArrayTypeMatchesArraysRequestBody | +[**post_boolean_type_matches_booleans_request_body**](#post_boolean_type_matches_booleans_request_body) | **post** /requestBody/postBooleanTypeMatchesBooleansRequestBody | +[**post_by_int_request_body**](#post_by_int_request_body) | **post** /requestBody/postByIntRequestBody | +[**post_by_number_request_body**](#post_by_number_request_body) | **post** /requestBody/postByNumberRequestBody | +[**post_by_small_number_request_body**](#post_by_small_number_request_body) | **post** /requestBody/postBySmallNumberRequestBody | +[**post_date_time_format_request_body**](#post_date_time_format_request_body) | **post** /requestBody/postDateTimeFormatRequestBody | +[**post_email_format_request_body**](#post_email_format_request_body) | **post** /requestBody/postEmailFormatRequestBody | +[**post_enum_with0_does_not_match_false_request_body**](#post_enum_with0_does_not_match_false_request_body) | **post** /requestBody/postEnumWith0DoesNotMatchFalseRequestBody | +[**post_enum_with1_does_not_match_true_request_body**](#post_enum_with1_does_not_match_true_request_body) | **post** /requestBody/postEnumWith1DoesNotMatchTrueRequestBody | +[**post_enum_with_escaped_characters_request_body**](#post_enum_with_escaped_characters_request_body) | **post** /requestBody/postEnumWithEscapedCharactersRequestBody | +[**post_enum_with_false_does_not_match0_request_body**](#post_enum_with_false_does_not_match0_request_body) | **post** /requestBody/postEnumWithFalseDoesNotMatch0RequestBody | +[**post_enum_with_true_does_not_match1_request_body**](#post_enum_with_true_does_not_match1_request_body) | **post** /requestBody/postEnumWithTrueDoesNotMatch1RequestBody | +[**post_enums_in_properties_request_body**](#post_enums_in_properties_request_body) | **post** /requestBody/postEnumsInPropertiesRequestBody | +[**post_forbidden_property_request_body**](#post_forbidden_property_request_body) | **post** /requestBody/postForbiddenPropertyRequestBody | +[**post_hostname_format_request_body**](#post_hostname_format_request_body) | **post** /requestBody/postHostnameFormatRequestBody | +[**post_integer_type_matches_integers_request_body**](#post_integer_type_matches_integers_request_body) | **post** /requestBody/postIntegerTypeMatchesIntegersRequestBody | +[**post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body**](#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body) | **post** /requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody | +[**post_invalid_string_value_for_default_request_body**](#post_invalid_string_value_for_default_request_body) | **post** /requestBody/postInvalidStringValueForDefaultRequestBody | +[**post_ipv4_format_request_body**](#post_ipv4_format_request_body) | **post** /requestBody/postIpv4FormatRequestBody | +[**post_ipv6_format_request_body**](#post_ipv6_format_request_body) | **post** /requestBody/postIpv6FormatRequestBody | +[**post_json_pointer_format_request_body**](#post_json_pointer_format_request_body) | **post** /requestBody/postJsonPointerFormatRequestBody | +[**post_maximum_validation_request_body**](#post_maximum_validation_request_body) | **post** /requestBody/postMaximumValidationRequestBody | +[**post_maximum_validation_with_unsigned_integer_request_body**](#post_maximum_validation_with_unsigned_integer_request_body) | **post** /requestBody/postMaximumValidationWithUnsignedIntegerRequestBody | +[**post_maxitems_validation_request_body**](#post_maxitems_validation_request_body) | **post** /requestBody/postMaxitemsValidationRequestBody | +[**post_maxlength_validation_request_body**](#post_maxlength_validation_request_body) | **post** /requestBody/postMaxlengthValidationRequestBody | +[**post_maxproperties0_means_the_object_is_empty_request_body**](#post_maxproperties0_means_the_object_is_empty_request_body) | **post** /requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody | +[**post_maxproperties_validation_request_body**](#post_maxproperties_validation_request_body) | **post** /requestBody/postMaxpropertiesValidationRequestBody | +[**post_minimum_validation_request_body**](#post_minimum_validation_request_body) | **post** /requestBody/postMinimumValidationRequestBody | +[**post_minimum_validation_with_signed_integer_request_body**](#post_minimum_validation_with_signed_integer_request_body) | **post** /requestBody/postMinimumValidationWithSignedIntegerRequestBody | +[**post_minitems_validation_request_body**](#post_minitems_validation_request_body) | **post** /requestBody/postMinitemsValidationRequestBody | +[**post_minlength_validation_request_body**](#post_minlength_validation_request_body) | **post** /requestBody/postMinlengthValidationRequestBody | +[**post_minproperties_validation_request_body**](#post_minproperties_validation_request_body) | **post** /requestBody/postMinpropertiesValidationRequestBody | +[**post_nested_allof_to_check_validation_semantics_request_body**](#post_nested_allof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAllofToCheckValidationSemanticsRequestBody | +[**post_nested_anyof_to_check_validation_semantics_request_body**](#post_nested_anyof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody | +[**post_nested_items_request_body**](#post_nested_items_request_body) | **post** /requestBody/postNestedItemsRequestBody | +[**post_nested_oneof_to_check_validation_semantics_request_body**](#post_nested_oneof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedOneofToCheckValidationSemanticsRequestBody | +[**post_not_more_complex_schema_request_body**](#post_not_more_complex_schema_request_body) | **post** /requestBody/postNotMoreComplexSchemaRequestBody | +[**post_not_request_body**](#post_not_request_body) | **post** /requestBody/postNotRequestBody | +[**post_nul_characters_in_strings_request_body**](#post_nul_characters_in_strings_request_body) | **post** /requestBody/postNulCharactersInStringsRequestBody | +[**post_null_type_matches_only_the_null_object_request_body**](#post_null_type_matches_only_the_null_object_request_body) | **post** /requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody | +[**post_number_type_matches_numbers_request_body**](#post_number_type_matches_numbers_request_body) | **post** /requestBody/postNumberTypeMatchesNumbersRequestBody | +[**post_object_properties_validation_request_body**](#post_object_properties_validation_request_body) | **post** /requestBody/postObjectPropertiesValidationRequestBody | +[**post_object_type_matches_objects_request_body**](#post_object_type_matches_objects_request_body) | **post** /requestBody/postObjectTypeMatchesObjectsRequestBody | +[**post_oneof_complex_types_request_body**](#post_oneof_complex_types_request_body) | **post** /requestBody/postOneofComplexTypesRequestBody | +[**post_oneof_request_body**](#post_oneof_request_body) | **post** /requestBody/postOneofRequestBody | +[**post_oneof_with_base_schema_request_body**](#post_oneof_with_base_schema_request_body) | **post** /requestBody/postOneofWithBaseSchemaRequestBody | +[**post_oneof_with_empty_schema_request_body**](#post_oneof_with_empty_schema_request_body) | **post** /requestBody/postOneofWithEmptySchemaRequestBody | +[**post_oneof_with_required_request_body**](#post_oneof_with_required_request_body) | **post** /requestBody/postOneofWithRequiredRequestBody | +[**post_pattern_is_not_anchored_request_body**](#post_pattern_is_not_anchored_request_body) | **post** /requestBody/postPatternIsNotAnchoredRequestBody | +[**post_pattern_validation_request_body**](#post_pattern_validation_request_body) | **post** /requestBody/postPatternValidationRequestBody | +[**post_properties_with_escaped_characters_request_body**](#post_properties_with_escaped_characters_request_body) | **post** /requestBody/postPropertiesWithEscapedCharactersRequestBody | +[**post_property_named_ref_that_is_not_a_reference_request_body**](#post_property_named_ref_that_is_not_a_reference_request_body) | **post** /requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody | +[**post_ref_in_additionalproperties_request_body**](#post_ref_in_additionalproperties_request_body) | **post** /requestBody/postRefInAdditionalpropertiesRequestBody | +[**post_ref_in_allof_request_body**](#post_ref_in_allof_request_body) | **post** /requestBody/postRefInAllofRequestBody | +[**post_ref_in_anyof_request_body**](#post_ref_in_anyof_request_body) | **post** /requestBody/postRefInAnyofRequestBody | +[**post_ref_in_items_request_body**](#post_ref_in_items_request_body) | **post** /requestBody/postRefInItemsRequestBody | +[**post_ref_in_not_request_body**](#post_ref_in_not_request_body) | **post** /requestBody/postRefInNotRequestBody | +[**post_ref_in_oneof_request_body**](#post_ref_in_oneof_request_body) | **post** /requestBody/postRefInOneofRequestBody | +[**post_ref_in_property_request_body**](#post_ref_in_property_request_body) | **post** /requestBody/postRefInPropertyRequestBody | +[**post_required_default_validation_request_body**](#post_required_default_validation_request_body) | **post** /requestBody/postRequiredDefaultValidationRequestBody | +[**post_required_validation_request_body**](#post_required_validation_request_body) | **post** /requestBody/postRequiredValidationRequestBody | +[**post_required_with_empty_array_request_body**](#post_required_with_empty_array_request_body) | **post** /requestBody/postRequiredWithEmptyArrayRequestBody | +[**post_required_with_escaped_characters_request_body**](#post_required_with_escaped_characters_request_body) | **post** /requestBody/postRequiredWithEscapedCharactersRequestBody | +[**post_simple_enum_validation_request_body**](#post_simple_enum_validation_request_body) | **post** /requestBody/postSimpleEnumValidationRequestBody | +[**post_string_type_matches_strings_request_body**](#post_string_type_matches_strings_request_body) | **post** /requestBody/postStringTypeMatchesStringsRequestBody | +[**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body**](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body) | **post** /requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody | +[**post_uniqueitems_false_validation_request_body**](#post_uniqueitems_false_validation_request_body) | **post** /requestBody/postUniqueitemsFalseValidationRequestBody | +[**post_uniqueitems_validation_request_body**](#post_uniqueitems_validation_request_body) | **post** /requestBody/postUniqueitemsValidationRequestBody | +[**post_uri_format_request_body**](#post_uri_format_request_body) | **post** /requestBody/postUriFormatRequestBody | +[**post_uri_reference_format_request_body**](#post_uri_reference_format_request_body) | **post** /requestBody/postUriReferenceFormatRequestBody | +[**post_uri_template_format_request_body**](#post_uri_template_format_request_body) | **post** /requestBody/postUriTemplateFormatRequestBody | + +# **post_additionalproperties_allows_a_schema_which_should_validate_request_body** + +> post_additionalproperties_allows_a_schema_which_should_validate_request_body(additionalproperties_allows_a_schema_which_should_validate) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesAllowsASchemaWhichShouldValidate( + foo=None, + bar=None, + ) + try: + api_response = api_instance.post_additionalproperties_allows_a_schema_which_should_validate_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_additionalproperties_allows_a_schema_which_should_validate_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAllowsASchemaWhichShouldValidate**](../../models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_allows_a_schema_which_should_validate_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_allows_a_schema_which_should_validate_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_are_allowed_by_default_request_body** + +> post_additionalproperties_are_allowed_by_default_request_body(additionalproperties_are_allowed_by_default) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesAreAllowedByDefault(None) + try: + api_response = api_instance.post_additionalproperties_are_allowed_by_default_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_additionalproperties_are_allowed_by_default_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAreAllowedByDefault**](../../models/AdditionalpropertiesAreAllowedByDefault.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_are_allowed_by_default_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_are_allowed_by_default_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_can_exist_by_itself_request_body** + +> post_additionalproperties_can_exist_by_itself_request_body(additionalproperties_can_exist_by_itself) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesCanExistByItself( + key=True, + ) + try: + api_response = api_instance.post_additionalproperties_can_exist_by_itself_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_additionalproperties_can_exist_by_itself_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesCanExistByItself**](../../models/AdditionalpropertiesCanExistByItself.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_can_exist_by_itself_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_can_exist_by_itself_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_should_not_look_in_applicators_request_body** + +> post_additionalproperties_should_not_look_in_applicators_request_body(additionalproperties_should_not_look_in_applicators) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesShouldNotLookInApplicators(None) + try: + api_response = api_instance.post_additionalproperties_should_not_look_in_applicators_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_additionalproperties_should_not_look_in_applicators_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesShouldNotLookInApplicators**](../../models/AdditionalpropertiesShouldNotLookInApplicators.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_should_not_look_in_applicators_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_should_not_look_in_applicators_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_combined_with_anyof_oneof_request_body** + +> post_allof_combined_with_anyof_oneof_request_body(allof_combined_with_anyof_oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofCombinedWithAnyofOneof(None) + try: + api_response = api_instance.post_allof_combined_with_anyof_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_allof_combined_with_anyof_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofCombinedWithAnyofOneof**](../../models/AllofCombinedWithAnyofOneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_combined_with_anyof_oneof_request_body.ApiResponseFor200) | success + +#### post_allof_combined_with_anyof_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_request_body** + +> post_allof_request_body(allof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.allof import Allof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = Allof(None) + try: + api_response = api_instance.post_allof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_allof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Allof**](../../models/Allof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_request_body.ApiResponseFor200) | success + +#### post_allof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_simple_types_request_body** + +> post_allof_simple_types_request_body(allof_simple_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.allof_simple_types import AllofSimpleTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofSimpleTypes(None) + try: + api_response = api_instance.post_allof_simple_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_allof_simple_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofSimpleTypes**](../../models/AllofSimpleTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_simple_types_request_body.ApiResponseFor200) | success + +#### post_allof_simple_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_base_schema_request_body** + +> post_allof_with_base_schema_request_body(allof_with_base_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithBaseSchema({}) + try: + api_response = api_instance.post_allof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_allof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithBaseSchema**](../../models/AllofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_one_empty_schema_request_body** + +> post_allof_with_one_empty_schema_request_body(allof_with_one_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithOneEmptySchema(None) + try: + api_response = api_instance.post_allof_with_one_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_allof_with_one_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithOneEmptySchema**](../../models/AllofWithOneEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_one_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_one_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_first_empty_schema_request_body** + +> post_allof_with_the_first_empty_schema_request_body(allof_with_the_first_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTheFirstEmptySchema(None) + try: + api_response = api_instance.post_allof_with_the_first_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_allof_with_the_first_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheFirstEmptySchema**](../../models/AllofWithTheFirstEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_first_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_the_first_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_last_empty_schema_request_body** + +> post_allof_with_the_last_empty_schema_request_body(allof_with_the_last_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTheLastEmptySchema(None) + try: + api_response = api_instance.post_allof_with_the_last_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_allof_with_the_last_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheLastEmptySchema**](../../models/AllofWithTheLastEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_last_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_the_last_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_two_empty_schemas_request_body** + +> post_allof_with_two_empty_schemas_request_body(allof_with_two_empty_schemas) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTwoEmptySchemas(None) + try: + api_response = api_instance.post_allof_with_two_empty_schemas_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_allof_with_two_empty_schemas_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTwoEmptySchemas**](../../models/AllofWithTwoEmptySchemas.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_two_empty_schemas_request_body.ApiResponseFor200) | success + +#### post_allof_with_two_empty_schemas_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_complex_types_request_body** + +> post_anyof_complex_types_request_body(anyof_complex_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofComplexTypes(None) + try: + api_response = api_instance.post_anyof_complex_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_anyof_complex_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofComplexTypes**](../../models/AnyofComplexTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_complex_types_request_body.ApiResponseFor200) | success + +#### post_anyof_complex_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_request_body** + +> post_anyof_request_body(anyof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.anyof import Anyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = Anyof(None) + try: + api_response = api_instance.post_anyof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_anyof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Anyof**](../../models/Anyof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_request_body.ApiResponseFor200) | success + +#### post_anyof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_base_schema_request_body** + +> post_anyof_with_base_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofWithBaseSchema("body_example") + try: + api_response = api_instance.post_anyof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_anyof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithBaseSchema**](../../models/AnyofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_anyof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_one_empty_schema_request_body** + +> post_anyof_with_one_empty_schema_request_body(anyof_with_one_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofWithOneEmptySchema(None) + try: + api_response = api_instance.post_anyof_with_one_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_anyof_with_one_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithOneEmptySchema**](../../models/AnyofWithOneEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_one_empty_schema_request_body.ApiResponseFor200) | success + +#### post_anyof_with_one_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_array_type_matches_arrays_request_body** + +> post_array_type_matches_arrays_request_body(array_type_matches_arrays) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = ArrayTypeMatchesArrays([ + None + ]) + try: + api_response = api_instance.post_array_type_matches_arrays_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_array_type_matches_arrays_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayTypeMatchesArrays**](../../models/ArrayTypeMatchesArrays.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_array_type_matches_arrays_request_body.ApiResponseFor200) | success + +#### post_array_type_matches_arrays_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_boolean_type_matches_booleans_request_body** + +> post_boolean_type_matches_booleans_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = True + try: + api_response = api_instance.post_boolean_type_matches_booleans_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_boolean_type_matches_booleans_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_boolean_type_matches_booleans_request_body.ApiResponseFor200) | success + +#### post_boolean_type_matches_booleans_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_int_request_body** + +> post_by_int_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.by_int import ByInt +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = ByInt(None) + try: + api_response = api_instance.post_by_int_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_by_int_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByInt**](../../models/ByInt.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_int_request_body.ApiResponseFor200) | success + +#### post_by_int_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_number_request_body** + +> post_by_number_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.by_number import ByNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = ByNumber(None) + try: + api_response = api_instance.post_by_number_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_by_number_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByNumber**](../../models/ByNumber.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_number_request_body.ApiResponseFor200) | success + +#### post_by_number_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_small_number_request_body** + +> post_by_small_number_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.by_small_number import BySmallNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = BySmallNumber(None) + try: + api_response = api_instance.post_by_small_number_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_by_small_number_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**BySmallNumber**](../../models/BySmallNumber.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_small_number_request_body.ApiResponseFor200) | success + +#### post_by_small_number_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_date_time_format_request_body** + +> post_date_time_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_date_time_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_date_time_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | value must conform to RFC-3339 date-time + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_date_time_format_request_body.ApiResponseFor200) | success + +#### post_date_time_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_email_format_request_body** + +> post_email_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_email_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_email_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_email_format_request_body.ApiResponseFor200) | success + +#### post_email_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with0_does_not_match_false_request_body** + +> post_enum_with0_does_not_match_false_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWith0DoesNotMatchFalse(0) + try: + api_response = api_instance.post_enum_with0_does_not_match_false_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_enum_with0_does_not_match_false_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith0DoesNotMatchFalse**](../../models/EnumWith0DoesNotMatchFalse.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with0_does_not_match_false_request_body.ApiResponseFor200) | success + +#### post_enum_with0_does_not_match_false_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with1_does_not_match_true_request_body** + +> post_enum_with1_does_not_match_true_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWith1DoesNotMatchTrue(1) + try: + api_response = api_instance.post_enum_with1_does_not_match_true_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_enum_with1_does_not_match_true_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith1DoesNotMatchTrue**](../../models/EnumWith1DoesNotMatchTrue.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with1_does_not_match_true_request_body.ApiResponseFor200) | success + +#### post_enum_with1_does_not_match_true_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_escaped_characters_request_body** + +> post_enum_with_escaped_characters_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithEscapedCharacters("foo\nbar") + try: + api_response = api_instance.post_enum_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_enum_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithEscapedCharacters**](../../models/EnumWithEscapedCharacters.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_enum_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_false_does_not_match0_request_body** + +> post_enum_with_false_does_not_match0_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithFalseDoesNotMatch0(False) + try: + api_response = api_instance.post_enum_with_false_does_not_match0_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_enum_with_false_does_not_match0_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithFalseDoesNotMatch0**](../../models/EnumWithFalseDoesNotMatch0.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_false_does_not_match0_request_body.ApiResponseFor200) | success + +#### post_enum_with_false_does_not_match0_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_true_does_not_match1_request_body** + +> post_enum_with_true_does_not_match1_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithTrueDoesNotMatch1(True) + try: + api_response = api_instance.post_enum_with_true_does_not_match1_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_enum_with_true_does_not_match1_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithTrueDoesNotMatch1**](../../models/EnumWithTrueDoesNotMatch1.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_true_does_not_match1_request_body.ApiResponseFor200) | success + +#### post_enum_with_true_does_not_match1_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enums_in_properties_request_body** + +> post_enums_in_properties_request_body(enums_in_properties) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.enums_in_properties import EnumsInProperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumsInProperties( + foo="foo", + bar="bar", + ) + try: + api_response = api_instance.post_enums_in_properties_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_enums_in_properties_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumsInProperties**](../../models/EnumsInProperties.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enums_in_properties_request_body.ApiResponseFor200) | success + +#### post_enums_in_properties_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_forbidden_property_request_body** + +> post_forbidden_property_request_body(forbidden_property) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.forbidden_property import ForbiddenProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = ForbiddenProperty(None) + try: + api_response = api_instance.post_forbidden_property_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_forbidden_property_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ForbiddenProperty**](../../models/ForbiddenProperty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_forbidden_property_request_body.ApiResponseFor200) | success + +#### post_forbidden_property_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_hostname_format_request_body** + +> post_hostname_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_hostname_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_hostname_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_hostname_format_request_body.ApiResponseFor200) | success + +#### post_hostname_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_integer_type_matches_integers_request_body** + +> post_integer_type_matches_integers_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = 1 + try: + api_response = api_instance.post_integer_type_matches_integers_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_integer_type_matches_integers_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_integer_type_matches_integers_request_body.ApiResponseFor200) | success + +#### post_integer_type_matches_integers_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body** + +> post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf(1) + try: + api_response = api_instance.post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf**](../../models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.ApiResponseFor200) | success + +#### post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_string_value_for_default_request_body** + +> post_invalid_string_value_for_default_request_body(invalid_string_value_for_default) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = InvalidStringValueForDefault(None) + try: + api_response = api_instance.post_invalid_string_value_for_default_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_invalid_string_value_for_default_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidStringValueForDefault**](../../models/InvalidStringValueForDefault.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_string_value_for_default_request_body.ApiResponseFor200) | success + +#### post_invalid_string_value_for_default_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv4_format_request_body** + +> post_ipv4_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ipv4_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_ipv4_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv4_format_request_body.ApiResponseFor200) | success + +#### post_ipv4_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv6_format_request_body** + +> post_ipv6_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ipv6_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_ipv6_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv6_format_request_body.ApiResponseFor200) | success + +#### post_ipv6_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_json_pointer_format_request_body** + +> post_json_pointer_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_json_pointer_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_json_pointer_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_json_pointer_format_request_body.ApiResponseFor200) | success + +#### post_json_pointer_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_request_body** + +> post_maximum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.maximum_validation import MaximumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MaximumValidation(None) + try: + api_response = api_instance.post_maximum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_maximum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidation**](../../models/MaximumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_request_body.ApiResponseFor200) | success + +#### post_maximum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_with_unsigned_integer_request_body** + +> post_maximum_validation_with_unsigned_integer_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MaximumValidationWithUnsignedInteger(None) + try: + api_response = api_instance.post_maximum_validation_with_unsigned_integer_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_maximum_validation_with_unsigned_integer_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidationWithUnsignedInteger**](../../models/MaximumValidationWithUnsignedInteger.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_with_unsigned_integer_request_body.ApiResponseFor200) | success + +#### post_maximum_validation_with_unsigned_integer_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxitems_validation_request_body** + +> post_maxitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.maxitems_validation import MaxitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxitemsValidation(None) + try: + api_response = api_instance.post_maxitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_maxitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxitemsValidation**](../../models/MaxitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxitems_validation_request_body.ApiResponseFor200) | success + +#### post_maxitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxlength_validation_request_body** + +> post_maxlength_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.maxlength_validation import MaxlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxlengthValidation(None) + try: + api_response = api_instance.post_maxlength_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_maxlength_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxlengthValidation**](../../models/MaxlengthValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxlength_validation_request_body.ApiResponseFor200) | success + +#### post_maxlength_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties0_means_the_object_is_empty_request_body** + +> post_maxproperties0_means_the_object_is_empty_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = Maxproperties0MeansTheObjectIsEmpty(None) + try: + api_response = api_instance.post_maxproperties0_means_the_object_is_empty_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_maxproperties0_means_the_object_is_empty_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Maxproperties0MeansTheObjectIsEmpty**](../../models/Maxproperties0MeansTheObjectIsEmpty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties0_means_the_object_is_empty_request_body.ApiResponseFor200) | success + +#### post_maxproperties0_means_the_object_is_empty_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties_validation_request_body** + +> post_maxproperties_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxpropertiesValidation(None) + try: + api_response = api_instance.post_maxproperties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_maxproperties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxpropertiesValidation**](../../models/MaxpropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties_validation_request_body.ApiResponseFor200) | success + +#### post_maxproperties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_request_body** + +> post_minimum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.minimum_validation import MinimumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MinimumValidation(None) + try: + api_response = api_instance.post_minimum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_minimum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidation**](../../models/MinimumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_request_body.ApiResponseFor200) | success + +#### post_minimum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_with_signed_integer_request_body** + +> post_minimum_validation_with_signed_integer_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MinimumValidationWithSignedInteger(None) + try: + api_response = api_instance.post_minimum_validation_with_signed_integer_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_minimum_validation_with_signed_integer_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidationWithSignedInteger**](../../models/MinimumValidationWithSignedInteger.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_with_signed_integer_request_body.ApiResponseFor200) | success + +#### post_minimum_validation_with_signed_integer_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minitems_validation_request_body** + +> post_minitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.minitems_validation import MinitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MinitemsValidation(None) + try: + api_response = api_instance.post_minitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_minitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinitemsValidation**](../../models/MinitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minitems_validation_request_body.ApiResponseFor200) | success + +#### post_minitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minlength_validation_request_body** + +> post_minlength_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.minlength_validation import MinlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MinlengthValidation(None) + try: + api_response = api_instance.post_minlength_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_minlength_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinlengthValidation**](../../models/MinlengthValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minlength_validation_request_body.ApiResponseFor200) | success + +#### post_minlength_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minproperties_validation_request_body** + +> post_minproperties_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.minproperties_validation import MinpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = MinpropertiesValidation(None) + try: + api_response = api_instance.post_minproperties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_minproperties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinpropertiesValidation**](../../models/MinpropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minproperties_validation_request_body.ApiResponseFor200) | success + +#### post_minproperties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_allof_to_check_validation_semantics_request_body** + +> post_nested_allof_to_check_validation_semantics_request_body(nested_allof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedAllofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_allof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_nested_allof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAllofToCheckValidationSemantics**](../../models/NestedAllofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_allof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_allof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_anyof_to_check_validation_semantics_request_body** + +> post_nested_anyof_to_check_validation_semantics_request_body(nested_anyof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedAnyofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_anyof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_nested_anyof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAnyofToCheckValidationSemantics**](../../models/NestedAnyofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_anyof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_anyof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_items_request_body** + +> post_nested_items_request_body(nested_items) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.nested_items import NestedItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedItems([ + [ + [ + [ + 3.14 + ] + ] + ] + ]) + try: + api_response = api_instance.post_nested_items_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_nested_items_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedItems**](../../models/NestedItems.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_items_request_body.ApiResponseFor200) | success + +#### post_nested_items_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_oneof_to_check_validation_semantics_request_body** + +> post_nested_oneof_to_check_validation_semantics_request_body(nested_oneof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedOneofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_oneof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_nested_oneof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedOneofToCheckValidationSemantics**](../../models/NestedOneofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_oneof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_oneof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_more_complex_schema_request_body** + +> post_not_more_complex_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_not_more_complex_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_not_more_complex_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_more_complex_schema_request_body.ApiResponseFor200) | success + +#### post_not_more_complex_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_request_body** + +> post_not_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_not_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_not_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | decimal.Decimal, int, | decimal.Decimal, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_request_body.ApiResponseFor200) | success + +#### post_not_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nul_characters_in_strings_request_body** + +> post_nul_characters_in_strings_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = NulCharactersInStrings("hello\x00there") + try: + api_response = api_instance.post_nul_characters_in_strings_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_nul_characters_in_strings_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NulCharactersInStrings**](../../models/NulCharactersInStrings.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nul_characters_in_strings_request_body.ApiResponseFor200) | success + +#### post_nul_characters_in_strings_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_null_type_matches_only_the_null_object_request_body** + +> post_null_type_matches_only_the_null_object_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_null_type_matches_only_the_null_object_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_null_type_matches_only_the_null_object_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_null_type_matches_only_the_null_object_request_body.ApiResponseFor200) | success + +#### post_null_type_matches_only_the_null_object_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_number_type_matches_numbers_request_body** + +> post_number_type_matches_numbers_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = 3.14 + try: + api_response = api_instance.post_number_type_matches_numbers_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_number_type_matches_numbers_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_number_type_matches_numbers_request_body.ApiResponseFor200) | success + +#### post_number_type_matches_numbers_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_properties_validation_request_body** + +> post_object_properties_validation_request_body(object_properties_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = ObjectPropertiesValidation(None) + try: + api_response = api_instance.post_object_properties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_object_properties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectPropertiesValidation**](../../models/ObjectPropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_properties_validation_request_body.ApiResponseFor200) | success + +#### post_object_properties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_type_matches_objects_request_body** + +> post_object_type_matches_objects_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = dict() + try: + api_response = api_instance.post_object_type_matches_objects_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_object_type_matches_objects_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_type_matches_objects_request_body.ApiResponseFor200) | success + +#### post_object_type_matches_objects_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_complex_types_request_body** + +> post_oneof_complex_types_request_body(oneof_complex_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.oneof_complex_types import OneofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofComplexTypes(None) + try: + api_response = api_instance.post_oneof_complex_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_oneof_complex_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofComplexTypes**](../../models/OneofComplexTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_complex_types_request_body.ApiResponseFor200) | success + +#### post_oneof_complex_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_request_body** + +> post_oneof_request_body(oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.oneof import Oneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = Oneof(None) + try: + api_response = api_instance.post_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Oneof**](../../models/Oneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_request_body.ApiResponseFor200) | success + +#### post_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_base_schema_request_body** + +> post_oneof_with_base_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithBaseSchema("body_example") + try: + api_response = api_instance.post_oneof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_oneof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithBaseSchema**](../../models/OneofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_oneof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_empty_schema_request_body** + +> post_oneof_with_empty_schema_request_body(oneof_with_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithEmptySchema(None) + try: + api_response = api_instance.post_oneof_with_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_oneof_with_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithEmptySchema**](../../models/OneofWithEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_empty_schema_request_body.ApiResponseFor200) | success + +#### post_oneof_with_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_required_request_body** + +> post_oneof_with_required_request_body(oneof_with_required) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.oneof_with_required import OneofWithRequired +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithRequired() + try: + api_response = api_instance.post_oneof_with_required_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_oneof_with_required_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithRequired**](../../models/OneofWithRequired.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_required_request_body.ApiResponseFor200) | success + +#### post_oneof_with_required_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_is_not_anchored_request_body** + +> post_pattern_is_not_anchored_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = PatternIsNotAnchored(None) + try: + api_response = api_instance.post_pattern_is_not_anchored_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_pattern_is_not_anchored_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternIsNotAnchored**](../../models/PatternIsNotAnchored.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_is_not_anchored_request_body.ApiResponseFor200) | success + +#### post_pattern_is_not_anchored_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_validation_request_body** + +> post_pattern_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.pattern_validation import PatternValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = PatternValidation(None) + try: + api_response = api_instance.post_pattern_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_pattern_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternValidation**](../../models/PatternValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_validation_request_body.ApiResponseFor200) | success + +#### post_pattern_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_properties_with_escaped_characters_request_body** + +> post_properties_with_escaped_characters_request_body(properties_with_escaped_characters) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = PropertiesWithEscapedCharacters(None) + try: + api_response = api_instance.post_properties_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_properties_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertiesWithEscapedCharacters**](../../models/PropertiesWithEscapedCharacters.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_properties_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_properties_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_property_named_ref_that_is_not_a_reference_request_body** + +> post_property_named_ref_that_is_not_a_reference_request_body(property_named_ref_that_is_not_a_reference) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = PropertyNamedRefThatIsNotAReference(None) + try: + api_response = api_instance.post_property_named_ref_that_is_not_a_reference_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_property_named_ref_that_is_not_a_reference_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertyNamedRefThatIsNotAReference**](../../models/PropertyNamedRefThatIsNotAReference.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_property_named_ref_that_is_not_a_reference_request_body.ApiResponseFor200) | success + +#### post_property_named_ref_that_is_not_a_reference_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_additionalproperties_request_body** + +> post_ref_in_additionalproperties_request_body(ref_in_additionalproperties) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAdditionalproperties( + key=PropertyNamedRefThatIsNotAReference(None), + ) + try: + api_response = api_instance.post_ref_in_additionalproperties_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_ref_in_additionalproperties_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAdditionalproperties**](../../models/RefInAdditionalproperties.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_additionalproperties_request_body.ApiResponseFor200) | success + +#### post_ref_in_additionalproperties_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_allof_request_body** + +> post_ref_in_allof_request_body(ref_in_allof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.ref_in_allof import RefInAllof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAllof(None) + try: + api_response = api_instance.post_ref_in_allof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_ref_in_allof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAllof**](../../models/RefInAllof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_allof_request_body.ApiResponseFor200) | success + +#### post_ref_in_allof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_anyof_request_body** + +> post_ref_in_anyof_request_body(ref_in_anyof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.ref_in_anyof import RefInAnyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAnyof(None) + try: + api_response = api_instance.post_ref_in_anyof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_ref_in_anyof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAnyof**](../../models/RefInAnyof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_anyof_request_body.ApiResponseFor200) | success + +#### post_ref_in_anyof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_items_request_body** + +> post_ref_in_items_request_body(ref_in_items) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.ref_in_items import RefInItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInItems([ + PropertyNamedRefThatIsNotAReference(None) + ]) + try: + api_response = api_instance.post_ref_in_items_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_ref_in_items_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInItems**](../../models/RefInItems.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_items_request_body.ApiResponseFor200) | success + +#### post_ref_in_items_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_not_request_body** + +> post_ref_in_not_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ref_in_not_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_ref_in_not_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_not_request_body.ApiResponseFor200) | success + +#### post_ref_in_not_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_oneof_request_body** + +> post_ref_in_oneof_request_body(ref_in_oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.ref_in_oneof import RefInOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInOneof(None) + try: + api_response = api_instance.post_ref_in_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_ref_in_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInOneof**](../../models/RefInOneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_oneof_request_body.ApiResponseFor200) | success + +#### post_ref_in_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_property_request_body** + +> post_ref_in_property_request_body(ref_in_property) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.ref_in_property import RefInProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInProperty(None) + try: + api_response = api_instance.post_ref_in_property_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_ref_in_property_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInProperty**](../../models/RefInProperty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_property_request_body.ApiResponseFor200) | success + +#### post_ref_in_property_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_default_validation_request_body** + +> post_required_default_validation_request_body(required_default_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.required_default_validation import RequiredDefaultValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredDefaultValidation(None) + try: + api_response = api_instance.post_required_default_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_required_default_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredDefaultValidation**](../../models/RequiredDefaultValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_default_validation_request_body.ApiResponseFor200) | success + +#### post_required_default_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_validation_request_body** + +> post_required_validation_request_body(required_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.required_validation import RequiredValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredValidation(None) + try: + api_response = api_instance.post_required_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_required_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredValidation**](../../models/RequiredValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_validation_request_body.ApiResponseFor200) | success + +#### post_required_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_empty_array_request_body** + +> post_required_with_empty_array_request_body(required_with_empty_array) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredWithEmptyArray(None) + try: + api_response = api_instance.post_required_with_empty_array_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_required_with_empty_array_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredWithEmptyArray**](../../models/RequiredWithEmptyArray.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_empty_array_request_body.ApiResponseFor200) | success + +#### post_required_with_empty_array_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_escaped_characters_request_body** + +> post_required_with_escaped_characters_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_required_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_required_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_required_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_simple_enum_validation_request_body** + +> post_simple_enum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = SimpleEnumValidation(1) + try: + api_response = api_instance.post_simple_enum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_simple_enum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**SimpleEnumValidation**](../../models/SimpleEnumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_simple_enum_validation_request_body.ApiResponseFor200) | success + +#### post_simple_enum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_string_type_matches_strings_request_body** + +> post_string_type_matches_strings_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = "body_example" + try: + api_response = api_instance.post_string_type_matches_strings_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_string_type_matches_strings_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_string_type_matches_strings_request_body.ApiResponseFor200) | success + +#### post_string_type_matches_strings_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body** + +> post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body(the_default_keyword_does_not_do_anything_if_the_property_is_missing) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing( + alpha=5, + ) + try: + api_response = api_instance.post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing**](../../models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.ApiResponseFor200) | success + +#### post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_false_validation_request_body** + +> post_uniqueitems_false_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = UniqueitemsFalseValidation(None) + try: + api_response = api_instance.post_uniqueitems_false_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_uniqueitems_false_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsFalseValidation**](../../models/UniqueitemsFalseValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_false_validation_request_body.ApiResponseFor200) | success + +#### post_uniqueitems_false_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_validation_request_body** + +> post_uniqueitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = UniqueitemsValidation(None) + try: + api_response = api_instance.post_uniqueitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_uniqueitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsValidation**](../../models/UniqueitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_validation_request_body.ApiResponseFor200) | success + +#### post_uniqueitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_format_request_body** + +> post_uri_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_uri_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_format_request_body.ApiResponseFor200) | success + +#### post_uri_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_reference_format_request_body** + +> post_uri_reference_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_reference_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_uri_reference_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_reference_format_request_body.ApiResponseFor200) | success + +#### post_uri_reference_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_template_format_request_body** + +> post_uri_template_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import operation_request_body_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = operation_request_body_api.OperationRequestBodyApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_template_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling OperationRequestBodyApi->post_uri_template_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_template_format_request_body.ApiResponseFor200) | success + +#### post_uri_template_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/PathPostApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/PathPostApi.md new file mode 100644 index 0000000000..f59e95a4c9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/PathPostApi.md @@ -0,0 +1,11681 @@ + +# unit_test_api.apis.tags.path_post_api.PathPostApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_additionalproperties_allows_a_schema_which_should_validate_request_body**](#post_additionalproperties_allows_a_schema_which_should_validate_request_body) | **post** /requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody | +[**post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types**](#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes | +[**post_additionalproperties_are_allowed_by_default_request_body**](#post_additionalproperties_are_allowed_by_default_request_body) | **post** /requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody | +[**post_additionalproperties_are_allowed_by_default_response_body_for_content_types**](#post_additionalproperties_are_allowed_by_default_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes | +[**post_additionalproperties_can_exist_by_itself_request_body**](#post_additionalproperties_can_exist_by_itself_request_body) | **post** /requestBody/postAdditionalpropertiesCanExistByItselfRequestBody | +[**post_additionalproperties_can_exist_by_itself_response_body_for_content_types**](#post_additionalproperties_can_exist_by_itself_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes | +[**post_additionalproperties_should_not_look_in_applicators_request_body**](#post_additionalproperties_should_not_look_in_applicators_request_body) | **post** /requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody | +[**post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types**](#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes | +[**post_allof_combined_with_anyof_oneof_request_body**](#post_allof_combined_with_anyof_oneof_request_body) | **post** /requestBody/postAllofCombinedWithAnyofOneofRequestBody | +[**post_allof_combined_with_anyof_oneof_response_body_for_content_types**](#post_allof_combined_with_anyof_oneof_response_body_for_content_types) | **post** /responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes | +[**post_allof_request_body**](#post_allof_request_body) | **post** /requestBody/postAllofRequestBody | +[**post_allof_response_body_for_content_types**](#post_allof_response_body_for_content_types) | **post** /responseBody/postAllofResponseBodyForContentTypes | +[**post_allof_simple_types_request_body**](#post_allof_simple_types_request_body) | **post** /requestBody/postAllofSimpleTypesRequestBody | +[**post_allof_simple_types_response_body_for_content_types**](#post_allof_simple_types_response_body_for_content_types) | **post** /responseBody/postAllofSimpleTypesResponseBodyForContentTypes | +[**post_allof_with_base_schema_request_body**](#post_allof_with_base_schema_request_body) | **post** /requestBody/postAllofWithBaseSchemaRequestBody | +[**post_allof_with_base_schema_response_body_for_content_types**](#post_allof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes | +[**post_allof_with_one_empty_schema_request_body**](#post_allof_with_one_empty_schema_request_body) | **post** /requestBody/postAllofWithOneEmptySchemaRequestBody | +[**post_allof_with_one_empty_schema_response_body_for_content_types**](#post_allof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_the_first_empty_schema_request_body**](#post_allof_with_the_first_empty_schema_request_body) | **post** /requestBody/postAllofWithTheFirstEmptySchemaRequestBody | +[**post_allof_with_the_first_empty_schema_response_body_for_content_types**](#post_allof_with_the_first_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_the_last_empty_schema_request_body**](#post_allof_with_the_last_empty_schema_request_body) | **post** /requestBody/postAllofWithTheLastEmptySchemaRequestBody | +[**post_allof_with_the_last_empty_schema_response_body_for_content_types**](#post_allof_with_the_last_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_two_empty_schemas_request_body**](#post_allof_with_two_empty_schemas_request_body) | **post** /requestBody/postAllofWithTwoEmptySchemasRequestBody | +[**post_allof_with_two_empty_schemas_response_body_for_content_types**](#post_allof_with_two_empty_schemas_response_body_for_content_types) | **post** /responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes | +[**post_anyof_complex_types_request_body**](#post_anyof_complex_types_request_body) | **post** /requestBody/postAnyofComplexTypesRequestBody | +[**post_anyof_complex_types_response_body_for_content_types**](#post_anyof_complex_types_response_body_for_content_types) | **post** /responseBody/postAnyofComplexTypesResponseBodyForContentTypes | +[**post_anyof_request_body**](#post_anyof_request_body) | **post** /requestBody/postAnyofRequestBody | +[**post_anyof_response_body_for_content_types**](#post_anyof_response_body_for_content_types) | **post** /responseBody/postAnyofResponseBodyForContentTypes | +[**post_anyof_with_base_schema_request_body**](#post_anyof_with_base_schema_request_body) | **post** /requestBody/postAnyofWithBaseSchemaRequestBody | +[**post_anyof_with_base_schema_response_body_for_content_types**](#post_anyof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes | +[**post_anyof_with_one_empty_schema_request_body**](#post_anyof_with_one_empty_schema_request_body) | **post** /requestBody/postAnyofWithOneEmptySchemaRequestBody | +[**post_anyof_with_one_empty_schema_response_body_for_content_types**](#post_anyof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes | +[**post_array_type_matches_arrays_request_body**](#post_array_type_matches_arrays_request_body) | **post** /requestBody/postArrayTypeMatchesArraysRequestBody | +[**post_array_type_matches_arrays_response_body_for_content_types**](#post_array_type_matches_arrays_response_body_for_content_types) | **post** /responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes | +[**post_boolean_type_matches_booleans_request_body**](#post_boolean_type_matches_booleans_request_body) | **post** /requestBody/postBooleanTypeMatchesBooleansRequestBody | +[**post_boolean_type_matches_booleans_response_body_for_content_types**](#post_boolean_type_matches_booleans_response_body_for_content_types) | **post** /responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes | +[**post_by_int_request_body**](#post_by_int_request_body) | **post** /requestBody/postByIntRequestBody | +[**post_by_int_response_body_for_content_types**](#post_by_int_response_body_for_content_types) | **post** /responseBody/postByIntResponseBodyForContentTypes | +[**post_by_number_request_body**](#post_by_number_request_body) | **post** /requestBody/postByNumberRequestBody | +[**post_by_number_response_body_for_content_types**](#post_by_number_response_body_for_content_types) | **post** /responseBody/postByNumberResponseBodyForContentTypes | +[**post_by_small_number_request_body**](#post_by_small_number_request_body) | **post** /requestBody/postBySmallNumberRequestBody | +[**post_by_small_number_response_body_for_content_types**](#post_by_small_number_response_body_for_content_types) | **post** /responseBody/postBySmallNumberResponseBodyForContentTypes | +[**post_date_time_format_request_body**](#post_date_time_format_request_body) | **post** /requestBody/postDateTimeFormatRequestBody | +[**post_date_time_format_response_body_for_content_types**](#post_date_time_format_response_body_for_content_types) | **post** /responseBody/postDateTimeFormatResponseBodyForContentTypes | +[**post_email_format_request_body**](#post_email_format_request_body) | **post** /requestBody/postEmailFormatRequestBody | +[**post_email_format_response_body_for_content_types**](#post_email_format_response_body_for_content_types) | **post** /responseBody/postEmailFormatResponseBodyForContentTypes | +[**post_enum_with0_does_not_match_false_request_body**](#post_enum_with0_does_not_match_false_request_body) | **post** /requestBody/postEnumWith0DoesNotMatchFalseRequestBody | +[**post_enum_with0_does_not_match_false_response_body_for_content_types**](#post_enum_with0_does_not_match_false_response_body_for_content_types) | **post** /responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes | +[**post_enum_with1_does_not_match_true_request_body**](#post_enum_with1_does_not_match_true_request_body) | **post** /requestBody/postEnumWith1DoesNotMatchTrueRequestBody | +[**post_enum_with1_does_not_match_true_response_body_for_content_types**](#post_enum_with1_does_not_match_true_response_body_for_content_types) | **post** /responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes | +[**post_enum_with_escaped_characters_request_body**](#post_enum_with_escaped_characters_request_body) | **post** /requestBody/postEnumWithEscapedCharactersRequestBody | +[**post_enum_with_escaped_characters_response_body_for_content_types**](#post_enum_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes | +[**post_enum_with_false_does_not_match0_request_body**](#post_enum_with_false_does_not_match0_request_body) | **post** /requestBody/postEnumWithFalseDoesNotMatch0RequestBody | +[**post_enum_with_false_does_not_match0_response_body_for_content_types**](#post_enum_with_false_does_not_match0_response_body_for_content_types) | **post** /responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes | +[**post_enum_with_true_does_not_match1_request_body**](#post_enum_with_true_does_not_match1_request_body) | **post** /requestBody/postEnumWithTrueDoesNotMatch1RequestBody | +[**post_enum_with_true_does_not_match1_response_body_for_content_types**](#post_enum_with_true_does_not_match1_response_body_for_content_types) | **post** /responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes | +[**post_enums_in_properties_request_body**](#post_enums_in_properties_request_body) | **post** /requestBody/postEnumsInPropertiesRequestBody | +[**post_enums_in_properties_response_body_for_content_types**](#post_enums_in_properties_response_body_for_content_types) | **post** /responseBody/postEnumsInPropertiesResponseBodyForContentTypes | +[**post_forbidden_property_request_body**](#post_forbidden_property_request_body) | **post** /requestBody/postForbiddenPropertyRequestBody | +[**post_forbidden_property_response_body_for_content_types**](#post_forbidden_property_response_body_for_content_types) | **post** /responseBody/postForbiddenPropertyResponseBodyForContentTypes | +[**post_hostname_format_request_body**](#post_hostname_format_request_body) | **post** /requestBody/postHostnameFormatRequestBody | +[**post_hostname_format_response_body_for_content_types**](#post_hostname_format_response_body_for_content_types) | **post** /responseBody/postHostnameFormatResponseBodyForContentTypes | +[**post_integer_type_matches_integers_request_body**](#post_integer_type_matches_integers_request_body) | **post** /requestBody/postIntegerTypeMatchesIntegersRequestBody | +[**post_integer_type_matches_integers_response_body_for_content_types**](#post_integer_type_matches_integers_response_body_for_content_types) | **post** /responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes | +[**post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body**](#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body) | **post** /requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody | +[**post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types**](#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types) | **post** /responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes | +[**post_invalid_string_value_for_default_request_body**](#post_invalid_string_value_for_default_request_body) | **post** /requestBody/postInvalidStringValueForDefaultRequestBody | +[**post_invalid_string_value_for_default_response_body_for_content_types**](#post_invalid_string_value_for_default_response_body_for_content_types) | **post** /responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes | +[**post_ipv4_format_request_body**](#post_ipv4_format_request_body) | **post** /requestBody/postIpv4FormatRequestBody | +[**post_ipv4_format_response_body_for_content_types**](#post_ipv4_format_response_body_for_content_types) | **post** /responseBody/postIpv4FormatResponseBodyForContentTypes | +[**post_ipv6_format_request_body**](#post_ipv6_format_request_body) | **post** /requestBody/postIpv6FormatRequestBody | +[**post_ipv6_format_response_body_for_content_types**](#post_ipv6_format_response_body_for_content_types) | **post** /responseBody/postIpv6FormatResponseBodyForContentTypes | +[**post_json_pointer_format_request_body**](#post_json_pointer_format_request_body) | **post** /requestBody/postJsonPointerFormatRequestBody | +[**post_json_pointer_format_response_body_for_content_types**](#post_json_pointer_format_response_body_for_content_types) | **post** /responseBody/postJsonPointerFormatResponseBodyForContentTypes | +[**post_maximum_validation_request_body**](#post_maximum_validation_request_body) | **post** /requestBody/postMaximumValidationRequestBody | +[**post_maximum_validation_response_body_for_content_types**](#post_maximum_validation_response_body_for_content_types) | **post** /responseBody/postMaximumValidationResponseBodyForContentTypes | +[**post_maximum_validation_with_unsigned_integer_request_body**](#post_maximum_validation_with_unsigned_integer_request_body) | **post** /requestBody/postMaximumValidationWithUnsignedIntegerRequestBody | +[**post_maximum_validation_with_unsigned_integer_response_body_for_content_types**](#post_maximum_validation_with_unsigned_integer_response_body_for_content_types) | **post** /responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes | +[**post_maxitems_validation_request_body**](#post_maxitems_validation_request_body) | **post** /requestBody/postMaxitemsValidationRequestBody | +[**post_maxitems_validation_response_body_for_content_types**](#post_maxitems_validation_response_body_for_content_types) | **post** /responseBody/postMaxitemsValidationResponseBodyForContentTypes | +[**post_maxlength_validation_request_body**](#post_maxlength_validation_request_body) | **post** /requestBody/postMaxlengthValidationRequestBody | +[**post_maxlength_validation_response_body_for_content_types**](#post_maxlength_validation_response_body_for_content_types) | **post** /responseBody/postMaxlengthValidationResponseBodyForContentTypes | +[**post_maxproperties0_means_the_object_is_empty_request_body**](#post_maxproperties0_means_the_object_is_empty_request_body) | **post** /requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody | +[**post_maxproperties0_means_the_object_is_empty_response_body_for_content_types**](#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types) | **post** /responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes | +[**post_maxproperties_validation_request_body**](#post_maxproperties_validation_request_body) | **post** /requestBody/postMaxpropertiesValidationRequestBody | +[**post_maxproperties_validation_response_body_for_content_types**](#post_maxproperties_validation_response_body_for_content_types) | **post** /responseBody/postMaxpropertiesValidationResponseBodyForContentTypes | +[**post_minimum_validation_request_body**](#post_minimum_validation_request_body) | **post** /requestBody/postMinimumValidationRequestBody | +[**post_minimum_validation_response_body_for_content_types**](#post_minimum_validation_response_body_for_content_types) | **post** /responseBody/postMinimumValidationResponseBodyForContentTypes | +[**post_minimum_validation_with_signed_integer_request_body**](#post_minimum_validation_with_signed_integer_request_body) | **post** /requestBody/postMinimumValidationWithSignedIntegerRequestBody | +[**post_minimum_validation_with_signed_integer_response_body_for_content_types**](#post_minimum_validation_with_signed_integer_response_body_for_content_types) | **post** /responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes | +[**post_minitems_validation_request_body**](#post_minitems_validation_request_body) | **post** /requestBody/postMinitemsValidationRequestBody | +[**post_minitems_validation_response_body_for_content_types**](#post_minitems_validation_response_body_for_content_types) | **post** /responseBody/postMinitemsValidationResponseBodyForContentTypes | +[**post_minlength_validation_request_body**](#post_minlength_validation_request_body) | **post** /requestBody/postMinlengthValidationRequestBody | +[**post_minlength_validation_response_body_for_content_types**](#post_minlength_validation_response_body_for_content_types) | **post** /responseBody/postMinlengthValidationResponseBodyForContentTypes | +[**post_minproperties_validation_request_body**](#post_minproperties_validation_request_body) | **post** /requestBody/postMinpropertiesValidationRequestBody | +[**post_minproperties_validation_response_body_for_content_types**](#post_minproperties_validation_response_body_for_content_types) | **post** /responseBody/postMinpropertiesValidationResponseBodyForContentTypes | +[**post_nested_allof_to_check_validation_semantics_request_body**](#post_nested_allof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAllofToCheckValidationSemanticsRequestBody | +[**post_nested_allof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_allof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_nested_anyof_to_check_validation_semantics_request_body**](#post_nested_anyof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody | +[**post_nested_anyof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_nested_items_request_body**](#post_nested_items_request_body) | **post** /requestBody/postNestedItemsRequestBody | +[**post_nested_items_response_body_for_content_types**](#post_nested_items_response_body_for_content_types) | **post** /responseBody/postNestedItemsResponseBodyForContentTypes | +[**post_nested_oneof_to_check_validation_semantics_request_body**](#post_nested_oneof_to_check_validation_semantics_request_body) | **post** /requestBody/postNestedOneofToCheckValidationSemanticsRequestBody | +[**post_nested_oneof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_not_more_complex_schema_request_body**](#post_not_more_complex_schema_request_body) | **post** /requestBody/postNotMoreComplexSchemaRequestBody | +[**post_not_more_complex_schema_response_body_for_content_types**](#post_not_more_complex_schema_response_body_for_content_types) | **post** /responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes | +[**post_not_request_body**](#post_not_request_body) | **post** /requestBody/postNotRequestBody | +[**post_not_response_body_for_content_types**](#post_not_response_body_for_content_types) | **post** /responseBody/postNotResponseBodyForContentTypes | +[**post_nul_characters_in_strings_request_body**](#post_nul_characters_in_strings_request_body) | **post** /requestBody/postNulCharactersInStringsRequestBody | +[**post_nul_characters_in_strings_response_body_for_content_types**](#post_nul_characters_in_strings_response_body_for_content_types) | **post** /responseBody/postNulCharactersInStringsResponseBodyForContentTypes | +[**post_null_type_matches_only_the_null_object_request_body**](#post_null_type_matches_only_the_null_object_request_body) | **post** /requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody | +[**post_null_type_matches_only_the_null_object_response_body_for_content_types**](#post_null_type_matches_only_the_null_object_response_body_for_content_types) | **post** /responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes | +[**post_number_type_matches_numbers_request_body**](#post_number_type_matches_numbers_request_body) | **post** /requestBody/postNumberTypeMatchesNumbersRequestBody | +[**post_number_type_matches_numbers_response_body_for_content_types**](#post_number_type_matches_numbers_response_body_for_content_types) | **post** /responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes | +[**post_object_properties_validation_request_body**](#post_object_properties_validation_request_body) | **post** /requestBody/postObjectPropertiesValidationRequestBody | +[**post_object_properties_validation_response_body_for_content_types**](#post_object_properties_validation_response_body_for_content_types) | **post** /responseBody/postObjectPropertiesValidationResponseBodyForContentTypes | +[**post_object_type_matches_objects_request_body**](#post_object_type_matches_objects_request_body) | **post** /requestBody/postObjectTypeMatchesObjectsRequestBody | +[**post_object_type_matches_objects_response_body_for_content_types**](#post_object_type_matches_objects_response_body_for_content_types) | **post** /responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes | +[**post_oneof_complex_types_request_body**](#post_oneof_complex_types_request_body) | **post** /requestBody/postOneofComplexTypesRequestBody | +[**post_oneof_complex_types_response_body_for_content_types**](#post_oneof_complex_types_response_body_for_content_types) | **post** /responseBody/postOneofComplexTypesResponseBodyForContentTypes | +[**post_oneof_request_body**](#post_oneof_request_body) | **post** /requestBody/postOneofRequestBody | +[**post_oneof_response_body_for_content_types**](#post_oneof_response_body_for_content_types) | **post** /responseBody/postOneofResponseBodyForContentTypes | +[**post_oneof_with_base_schema_request_body**](#post_oneof_with_base_schema_request_body) | **post** /requestBody/postOneofWithBaseSchemaRequestBody | +[**post_oneof_with_base_schema_response_body_for_content_types**](#post_oneof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes | +[**post_oneof_with_empty_schema_request_body**](#post_oneof_with_empty_schema_request_body) | **post** /requestBody/postOneofWithEmptySchemaRequestBody | +[**post_oneof_with_empty_schema_response_body_for_content_types**](#post_oneof_with_empty_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes | +[**post_oneof_with_required_request_body**](#post_oneof_with_required_request_body) | **post** /requestBody/postOneofWithRequiredRequestBody | +[**post_oneof_with_required_response_body_for_content_types**](#post_oneof_with_required_response_body_for_content_types) | **post** /responseBody/postOneofWithRequiredResponseBodyForContentTypes | +[**post_pattern_is_not_anchored_request_body**](#post_pattern_is_not_anchored_request_body) | **post** /requestBody/postPatternIsNotAnchoredRequestBody | +[**post_pattern_is_not_anchored_response_body_for_content_types**](#post_pattern_is_not_anchored_response_body_for_content_types) | **post** /responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes | +[**post_pattern_validation_request_body**](#post_pattern_validation_request_body) | **post** /requestBody/postPatternValidationRequestBody | +[**post_pattern_validation_response_body_for_content_types**](#post_pattern_validation_response_body_for_content_types) | **post** /responseBody/postPatternValidationResponseBodyForContentTypes | +[**post_properties_with_escaped_characters_request_body**](#post_properties_with_escaped_characters_request_body) | **post** /requestBody/postPropertiesWithEscapedCharactersRequestBody | +[**post_properties_with_escaped_characters_response_body_for_content_types**](#post_properties_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes | +[**post_property_named_ref_that_is_not_a_reference_request_body**](#post_property_named_ref_that_is_not_a_reference_request_body) | **post** /requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody | +[**post_property_named_ref_that_is_not_a_reference_response_body_for_content_types**](#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types) | **post** /responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes | +[**post_ref_in_additionalproperties_request_body**](#post_ref_in_additionalproperties_request_body) | **post** /requestBody/postRefInAdditionalpropertiesRequestBody | +[**post_ref_in_additionalproperties_response_body_for_content_types**](#post_ref_in_additionalproperties_response_body_for_content_types) | **post** /responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes | +[**post_ref_in_allof_request_body**](#post_ref_in_allof_request_body) | **post** /requestBody/postRefInAllofRequestBody | +[**post_ref_in_allof_response_body_for_content_types**](#post_ref_in_allof_response_body_for_content_types) | **post** /responseBody/postRefInAllofResponseBodyForContentTypes | +[**post_ref_in_anyof_request_body**](#post_ref_in_anyof_request_body) | **post** /requestBody/postRefInAnyofRequestBody | +[**post_ref_in_anyof_response_body_for_content_types**](#post_ref_in_anyof_response_body_for_content_types) | **post** /responseBody/postRefInAnyofResponseBodyForContentTypes | +[**post_ref_in_items_request_body**](#post_ref_in_items_request_body) | **post** /requestBody/postRefInItemsRequestBody | +[**post_ref_in_items_response_body_for_content_types**](#post_ref_in_items_response_body_for_content_types) | **post** /responseBody/postRefInItemsResponseBodyForContentTypes | +[**post_ref_in_not_request_body**](#post_ref_in_not_request_body) | **post** /requestBody/postRefInNotRequestBody | +[**post_ref_in_not_response_body_for_content_types**](#post_ref_in_not_response_body_for_content_types) | **post** /responseBody/postRefInNotResponseBodyForContentTypes | +[**post_ref_in_oneof_request_body**](#post_ref_in_oneof_request_body) | **post** /requestBody/postRefInOneofRequestBody | +[**post_ref_in_oneof_response_body_for_content_types**](#post_ref_in_oneof_response_body_for_content_types) | **post** /responseBody/postRefInOneofResponseBodyForContentTypes | +[**post_ref_in_property_request_body**](#post_ref_in_property_request_body) | **post** /requestBody/postRefInPropertyRequestBody | +[**post_ref_in_property_response_body_for_content_types**](#post_ref_in_property_response_body_for_content_types) | **post** /responseBody/postRefInPropertyResponseBodyForContentTypes | +[**post_required_default_validation_request_body**](#post_required_default_validation_request_body) | **post** /requestBody/postRequiredDefaultValidationRequestBody | +[**post_required_default_validation_response_body_for_content_types**](#post_required_default_validation_response_body_for_content_types) | **post** /responseBody/postRequiredDefaultValidationResponseBodyForContentTypes | +[**post_required_validation_request_body**](#post_required_validation_request_body) | **post** /requestBody/postRequiredValidationRequestBody | +[**post_required_validation_response_body_for_content_types**](#post_required_validation_response_body_for_content_types) | **post** /responseBody/postRequiredValidationResponseBodyForContentTypes | +[**post_required_with_empty_array_request_body**](#post_required_with_empty_array_request_body) | **post** /requestBody/postRequiredWithEmptyArrayRequestBody | +[**post_required_with_empty_array_response_body_for_content_types**](#post_required_with_empty_array_response_body_for_content_types) | **post** /responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes | +[**post_required_with_escaped_characters_request_body**](#post_required_with_escaped_characters_request_body) | **post** /requestBody/postRequiredWithEscapedCharactersRequestBody | +[**post_required_with_escaped_characters_response_body_for_content_types**](#post_required_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes | +[**post_simple_enum_validation_request_body**](#post_simple_enum_validation_request_body) | **post** /requestBody/postSimpleEnumValidationRequestBody | +[**post_simple_enum_validation_response_body_for_content_types**](#post_simple_enum_validation_response_body_for_content_types) | **post** /responseBody/postSimpleEnumValidationResponseBodyForContentTypes | +[**post_string_type_matches_strings_request_body**](#post_string_type_matches_strings_request_body) | **post** /requestBody/postStringTypeMatchesStringsRequestBody | +[**post_string_type_matches_strings_response_body_for_content_types**](#post_string_type_matches_strings_response_body_for_content_types) | **post** /responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes | +[**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body**](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body) | **post** /requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody | +[**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types**](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types) | **post** /responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes | +[**post_uniqueitems_false_validation_request_body**](#post_uniqueitems_false_validation_request_body) | **post** /requestBody/postUniqueitemsFalseValidationRequestBody | +[**post_uniqueitems_false_validation_response_body_for_content_types**](#post_uniqueitems_false_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes | +[**post_uniqueitems_validation_request_body**](#post_uniqueitems_validation_request_body) | **post** /requestBody/postUniqueitemsValidationRequestBody | +[**post_uniqueitems_validation_response_body_for_content_types**](#post_uniqueitems_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsValidationResponseBodyForContentTypes | +[**post_uri_format_request_body**](#post_uri_format_request_body) | **post** /requestBody/postUriFormatRequestBody | +[**post_uri_format_response_body_for_content_types**](#post_uri_format_response_body_for_content_types) | **post** /responseBody/postUriFormatResponseBodyForContentTypes | +[**post_uri_reference_format_request_body**](#post_uri_reference_format_request_body) | **post** /requestBody/postUriReferenceFormatRequestBody | +[**post_uri_reference_format_response_body_for_content_types**](#post_uri_reference_format_response_body_for_content_types) | **post** /responseBody/postUriReferenceFormatResponseBodyForContentTypes | +[**post_uri_template_format_request_body**](#post_uri_template_format_request_body) | **post** /requestBody/postUriTemplateFormatRequestBody | +[**post_uri_template_format_response_body_for_content_types**](#post_uri_template_format_response_body_for_content_types) | **post** /responseBody/postUriTemplateFormatResponseBodyForContentTypes | + +# **post_additionalproperties_allows_a_schema_which_should_validate_request_body** + +> post_additionalproperties_allows_a_schema_which_should_validate_request_body(additionalproperties_allows_a_schema_which_should_validate) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesAllowsASchemaWhichShouldValidate( + foo=None, + bar=None, + ) + try: + api_response = api_instance.post_additionalproperties_allows_a_schema_which_should_validate_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_additionalproperties_allows_a_schema_which_should_validate_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAllowsASchemaWhichShouldValidate**](../../models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_allows_a_schema_which_should_validate_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_allows_a_schema_which_should_validate_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types** + +> AdditionalpropertiesAllowsASchemaWhichShouldValidate post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAllowsASchemaWhichShouldValidate**](../../models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_are_allowed_by_default_request_body** + +> post_additionalproperties_are_allowed_by_default_request_body(additionalproperties_are_allowed_by_default) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesAreAllowedByDefault(None) + try: + api_response = api_instance.post_additionalproperties_are_allowed_by_default_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_additionalproperties_are_allowed_by_default_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAreAllowedByDefault**](../../models/AdditionalpropertiesAreAllowedByDefault.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_are_allowed_by_default_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_are_allowed_by_default_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_are_allowed_by_default_response_body_for_content_types** + +> AdditionalpropertiesAreAllowedByDefault post_additionalproperties_are_allowed_by_default_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_are_allowed_by_default_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_additionalproperties_are_allowed_by_default_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_are_allowed_by_default_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_are_allowed_by_default_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAreAllowedByDefault**](../../models/AdditionalpropertiesAreAllowedByDefault.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_can_exist_by_itself_request_body** + +> post_additionalproperties_can_exist_by_itself_request_body(additionalproperties_can_exist_by_itself) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesCanExistByItself( + key=True, + ) + try: + api_response = api_instance.post_additionalproperties_can_exist_by_itself_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_additionalproperties_can_exist_by_itself_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesCanExistByItself**](../../models/AdditionalpropertiesCanExistByItself.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_can_exist_by_itself_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_can_exist_by_itself_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_can_exist_by_itself_response_body_for_content_types** + +> AdditionalpropertiesCanExistByItself post_additionalproperties_can_exist_by_itself_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_can_exist_by_itself_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_additionalproperties_can_exist_by_itself_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_can_exist_by_itself_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_can_exist_by_itself_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesCanExistByItself**](../../models/AdditionalpropertiesCanExistByItself.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_should_not_look_in_applicators_request_body** + +> post_additionalproperties_should_not_look_in_applicators_request_body(additionalproperties_should_not_look_in_applicators) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AdditionalpropertiesShouldNotLookInApplicators(None) + try: + api_response = api_instance.post_additionalproperties_should_not_look_in_applicators_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_additionalproperties_should_not_look_in_applicators_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesShouldNotLookInApplicators**](../../models/AdditionalpropertiesShouldNotLookInApplicators.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_should_not_look_in_applicators_request_body.ApiResponseFor200) | success + +#### post_additionalproperties_should_not_look_in_applicators_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types** + +> AdditionalpropertiesShouldNotLookInApplicators post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesShouldNotLookInApplicators**](../../models/AdditionalpropertiesShouldNotLookInApplicators.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_combined_with_anyof_oneof_request_body** + +> post_allof_combined_with_anyof_oneof_request_body(allof_combined_with_anyof_oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofCombinedWithAnyofOneof(None) + try: + api_response = api_instance.post_allof_combined_with_anyof_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_combined_with_anyof_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofCombinedWithAnyofOneof**](../../models/AllofCombinedWithAnyofOneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_combined_with_anyof_oneof_request_body.ApiResponseFor200) | success + +#### post_allof_combined_with_anyof_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_combined_with_anyof_oneof_response_body_for_content_types** + +> AllofCombinedWithAnyofOneof post_allof_combined_with_anyof_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_combined_with_anyof_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_combined_with_anyof_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_combined_with_anyof_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_combined_with_anyof_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofCombinedWithAnyofOneof**](../../models/AllofCombinedWithAnyofOneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_request_body** + +> post_allof_request_body(allof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof import Allof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = Allof(None) + try: + api_response = api_instance.post_allof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Allof**](../../models/Allof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_request_body.ApiResponseFor200) | success + +#### post_allof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_response_body_for_content_types** + +> Allof post_allof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof import Allof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Allof**](../../models/Allof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_simple_types_request_body** + +> post_allof_simple_types_request_body(allof_simple_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_simple_types import AllofSimpleTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofSimpleTypes(None) + try: + api_response = api_instance.post_allof_simple_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_simple_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofSimpleTypes**](../../models/AllofSimpleTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_simple_types_request_body.ApiResponseFor200) | success + +#### post_allof_simple_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_simple_types_response_body_for_content_types** + +> AllofSimpleTypes post_allof_simple_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_simple_types import AllofSimpleTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_simple_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_simple_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_simple_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_simple_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofSimpleTypes**](../../models/AllofSimpleTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_base_schema_request_body** + +> post_allof_with_base_schema_request_body(allof_with_base_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithBaseSchema({}) + try: + api_response = api_instance.post_allof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithBaseSchema**](../../models/AllofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_base_schema_response_body_for_content_types** + +> AllofWithBaseSchema post_allof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithBaseSchema**](../../models/AllofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_one_empty_schema_request_body** + +> post_allof_with_one_empty_schema_request_body(allof_with_one_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithOneEmptySchema(None) + try: + api_response = api_instance.post_allof_with_one_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_one_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithOneEmptySchema**](../../models/AllofWithOneEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_one_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_one_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_one_empty_schema_response_body_for_content_types** + +> AllofWithOneEmptySchema post_allof_with_one_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_one_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_one_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithOneEmptySchema**](../../models/AllofWithOneEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_first_empty_schema_request_body** + +> post_allof_with_the_first_empty_schema_request_body(allof_with_the_first_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTheFirstEmptySchema(None) + try: + api_response = api_instance.post_allof_with_the_first_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_the_first_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheFirstEmptySchema**](../../models/AllofWithTheFirstEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_first_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_the_first_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_first_empty_schema_response_body_for_content_types** + +> AllofWithTheFirstEmptySchema post_allof_with_the_first_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_the_first_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_the_first_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_first_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_the_first_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheFirstEmptySchema**](../../models/AllofWithTheFirstEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_last_empty_schema_request_body** + +> post_allof_with_the_last_empty_schema_request_body(allof_with_the_last_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTheLastEmptySchema(None) + try: + api_response = api_instance.post_allof_with_the_last_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_the_last_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheLastEmptySchema**](../../models/AllofWithTheLastEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_last_empty_schema_request_body.ApiResponseFor200) | success + +#### post_allof_with_the_last_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_last_empty_schema_response_body_for_content_types** + +> AllofWithTheLastEmptySchema post_allof_with_the_last_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_the_last_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_the_last_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_last_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_the_last_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheLastEmptySchema**](../../models/AllofWithTheLastEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_two_empty_schemas_request_body** + +> post_allof_with_two_empty_schemas_request_body(allof_with_two_empty_schemas) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AllofWithTwoEmptySchemas(None) + try: + api_response = api_instance.post_allof_with_two_empty_schemas_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_two_empty_schemas_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTwoEmptySchemas**](../../models/AllofWithTwoEmptySchemas.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_two_empty_schemas_request_body.ApiResponseFor200) | success + +#### post_allof_with_two_empty_schemas_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_two_empty_schemas_response_body_for_content_types** + +> AllofWithTwoEmptySchemas post_allof_with_two_empty_schemas_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_two_empty_schemas_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_allof_with_two_empty_schemas_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_two_empty_schemas_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_two_empty_schemas_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTwoEmptySchemas**](../../models/AllofWithTwoEmptySchemas.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_complex_types_request_body** + +> post_anyof_complex_types_request_body(anyof_complex_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofComplexTypes(None) + try: + api_response = api_instance.post_anyof_complex_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_anyof_complex_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofComplexTypes**](../../models/AnyofComplexTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_complex_types_request_body.ApiResponseFor200) | success + +#### post_anyof_complex_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_complex_types_response_body_for_content_types** + +> AnyofComplexTypes post_anyof_complex_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_complex_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_anyof_complex_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_complex_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_complex_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofComplexTypes**](../../models/AnyofComplexTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_request_body** + +> post_anyof_request_body(anyof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.anyof import Anyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = Anyof(None) + try: + api_response = api_instance.post_anyof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_anyof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Anyof**](../../models/Anyof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_request_body.ApiResponseFor200) | success + +#### post_anyof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_response_body_for_content_types** + +> Anyof post_anyof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.anyof import Anyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_anyof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Anyof**](../../models/Anyof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_base_schema_request_body** + +> post_anyof_with_base_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofWithBaseSchema("body_example") + try: + api_response = api_instance.post_anyof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_anyof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithBaseSchema**](../../models/AnyofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_anyof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_base_schema_response_body_for_content_types** + +> AnyofWithBaseSchema post_anyof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_anyof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithBaseSchema**](../../models/AnyofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_one_empty_schema_request_body** + +> post_anyof_with_one_empty_schema_request_body(anyof_with_one_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = AnyofWithOneEmptySchema(None) + try: + api_response = api_instance.post_anyof_with_one_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_anyof_with_one_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithOneEmptySchema**](../../models/AnyofWithOneEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_one_empty_schema_request_body.ApiResponseFor200) | success + +#### post_anyof_with_one_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_one_empty_schema_response_body_for_content_types** + +> AnyofWithOneEmptySchema post_anyof_with_one_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_with_one_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_anyof_with_one_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithOneEmptySchema**](../../models/AnyofWithOneEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_array_type_matches_arrays_request_body** + +> post_array_type_matches_arrays_request_body(array_type_matches_arrays) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = ArrayTypeMatchesArrays([ + None + ]) + try: + api_response = api_instance.post_array_type_matches_arrays_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_array_type_matches_arrays_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayTypeMatchesArrays**](../../models/ArrayTypeMatchesArrays.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_array_type_matches_arrays_request_body.ApiResponseFor200) | success + +#### post_array_type_matches_arrays_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_array_type_matches_arrays_response_body_for_content_types** + +> ArrayTypeMatchesArrays post_array_type_matches_arrays_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_array_type_matches_arrays_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_array_type_matches_arrays_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_array_type_matches_arrays_response_body_for_content_types.ApiResponseFor200) | success + +#### post_array_type_matches_arrays_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayTypeMatchesArrays**](../../models/ArrayTypeMatchesArrays.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_boolean_type_matches_booleans_request_body** + +> post_boolean_type_matches_booleans_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = True + try: + api_response = api_instance.post_boolean_type_matches_booleans_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_boolean_type_matches_booleans_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_boolean_type_matches_booleans_request_body.ApiResponseFor200) | success + +#### post_boolean_type_matches_booleans_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_boolean_type_matches_booleans_response_body_for_content_types** + +> bool post_boolean_type_matches_booleans_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_boolean_type_matches_booleans_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_boolean_type_matches_booleans_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_boolean_type_matches_booleans_response_body_for_content_types.ApiResponseFor200) | success + +#### post_boolean_type_matches_booleans_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_int_request_body** + +> post_by_int_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.by_int import ByInt +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = ByInt(None) + try: + api_response = api_instance.post_by_int_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_by_int_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByInt**](../../models/ByInt.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_int_request_body.ApiResponseFor200) | success + +#### post_by_int_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_int_response_body_for_content_types** + +> ByInt post_by_int_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.by_int import ByInt +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_int_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_by_int_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_int_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_int_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByInt**](../../models/ByInt.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_number_request_body** + +> post_by_number_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.by_number import ByNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = ByNumber(None) + try: + api_response = api_instance.post_by_number_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_by_number_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByNumber**](../../models/ByNumber.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_number_request_body.ApiResponseFor200) | success + +#### post_by_number_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_number_response_body_for_content_types** + +> ByNumber post_by_number_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.by_number import ByNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_number_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_by_number_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_number_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_number_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByNumber**](../../models/ByNumber.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_small_number_request_body** + +> post_by_small_number_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.by_small_number import BySmallNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = BySmallNumber(None) + try: + api_response = api_instance.post_by_small_number_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_by_small_number_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**BySmallNumber**](../../models/BySmallNumber.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_small_number_request_body.ApiResponseFor200) | success + +#### post_by_small_number_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_small_number_response_body_for_content_types** + +> BySmallNumber post_by_small_number_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.by_small_number import BySmallNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_small_number_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_by_small_number_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_small_number_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_small_number_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**BySmallNumber**](../../models/BySmallNumber.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_date_time_format_request_body** + +> post_date_time_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_date_time_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_date_time_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | value must conform to RFC-3339 date-time + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_date_time_format_request_body.ApiResponseFor200) | success + +#### post_date_time_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_date_time_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_date_time_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_date_time_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_date_time_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_date_time_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_date_time_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | value must conform to RFC-3339 date-time + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_email_format_request_body** + +> post_email_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_email_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_email_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_email_format_request_body.ApiResponseFor200) | success + +#### post_email_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_email_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_email_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_email_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_email_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_email_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_email_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with0_does_not_match_false_request_body** + +> post_enum_with0_does_not_match_false_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWith0DoesNotMatchFalse(0) + try: + api_response = api_instance.post_enum_with0_does_not_match_false_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with0_does_not_match_false_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith0DoesNotMatchFalse**](../../models/EnumWith0DoesNotMatchFalse.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with0_does_not_match_false_request_body.ApiResponseFor200) | success + +#### post_enum_with0_does_not_match_false_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with0_does_not_match_false_response_body_for_content_types** + +> EnumWith0DoesNotMatchFalse post_enum_with0_does_not_match_false_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with0_does_not_match_false_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with0_does_not_match_false_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with0_does_not_match_false_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with0_does_not_match_false_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith0DoesNotMatchFalse**](../../models/EnumWith0DoesNotMatchFalse.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with1_does_not_match_true_request_body** + +> post_enum_with1_does_not_match_true_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWith1DoesNotMatchTrue(1) + try: + api_response = api_instance.post_enum_with1_does_not_match_true_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with1_does_not_match_true_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith1DoesNotMatchTrue**](../../models/EnumWith1DoesNotMatchTrue.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with1_does_not_match_true_request_body.ApiResponseFor200) | success + +#### post_enum_with1_does_not_match_true_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with1_does_not_match_true_response_body_for_content_types** + +> EnumWith1DoesNotMatchTrue post_enum_with1_does_not_match_true_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with1_does_not_match_true_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with1_does_not_match_true_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with1_does_not_match_true_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with1_does_not_match_true_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith1DoesNotMatchTrue**](../../models/EnumWith1DoesNotMatchTrue.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_escaped_characters_request_body** + +> post_enum_with_escaped_characters_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithEscapedCharacters("foo\nbar") + try: + api_response = api_instance.post_enum_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithEscapedCharacters**](../../models/EnumWithEscapedCharacters.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_enum_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_escaped_characters_response_body_for_content_types** + +> EnumWithEscapedCharacters post_enum_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithEscapedCharacters**](../../models/EnumWithEscapedCharacters.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_false_does_not_match0_request_body** + +> post_enum_with_false_does_not_match0_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithFalseDoesNotMatch0(False) + try: + api_response = api_instance.post_enum_with_false_does_not_match0_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with_false_does_not_match0_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithFalseDoesNotMatch0**](../../models/EnumWithFalseDoesNotMatch0.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_false_does_not_match0_request_body.ApiResponseFor200) | success + +#### post_enum_with_false_does_not_match0_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_false_does_not_match0_response_body_for_content_types** + +> EnumWithFalseDoesNotMatch0 post_enum_with_false_does_not_match0_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_false_does_not_match0_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with_false_does_not_match0_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_false_does_not_match0_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_false_does_not_match0_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithFalseDoesNotMatch0**](../../models/EnumWithFalseDoesNotMatch0.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_true_does_not_match1_request_body** + +> post_enum_with_true_does_not_match1_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumWithTrueDoesNotMatch1(True) + try: + api_response = api_instance.post_enum_with_true_does_not_match1_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with_true_does_not_match1_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithTrueDoesNotMatch1**](../../models/EnumWithTrueDoesNotMatch1.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_true_does_not_match1_request_body.ApiResponseFor200) | success + +#### post_enum_with_true_does_not_match1_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_true_does_not_match1_response_body_for_content_types** + +> EnumWithTrueDoesNotMatch1 post_enum_with_true_does_not_match1_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_true_does_not_match1_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enum_with_true_does_not_match1_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_true_does_not_match1_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_true_does_not_match1_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithTrueDoesNotMatch1**](../../models/EnumWithTrueDoesNotMatch1.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enums_in_properties_request_body** + +> post_enums_in_properties_request_body(enums_in_properties) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enums_in_properties import EnumsInProperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = EnumsInProperties( + foo="foo", + bar="bar", + ) + try: + api_response = api_instance.post_enums_in_properties_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enums_in_properties_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumsInProperties**](../../models/EnumsInProperties.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enums_in_properties_request_body.ApiResponseFor200) | success + +#### post_enums_in_properties_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enums_in_properties_response_body_for_content_types** + +> EnumsInProperties post_enums_in_properties_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.enums_in_properties import EnumsInProperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enums_in_properties_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_enums_in_properties_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enums_in_properties_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enums_in_properties_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumsInProperties**](../../models/EnumsInProperties.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_forbidden_property_request_body** + +> post_forbidden_property_request_body(forbidden_property) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.forbidden_property import ForbiddenProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = ForbiddenProperty(None) + try: + api_response = api_instance.post_forbidden_property_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_forbidden_property_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ForbiddenProperty**](../../models/ForbiddenProperty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_forbidden_property_request_body.ApiResponseFor200) | success + +#### post_forbidden_property_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_forbidden_property_response_body_for_content_types** + +> ForbiddenProperty post_forbidden_property_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.forbidden_property import ForbiddenProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_forbidden_property_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_forbidden_property_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_forbidden_property_response_body_for_content_types.ApiResponseFor200) | success + +#### post_forbidden_property_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ForbiddenProperty**](../../models/ForbiddenProperty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_hostname_format_request_body** + +> post_hostname_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_hostname_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_hostname_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_hostname_format_request_body.ApiResponseFor200) | success + +#### post_hostname_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_hostname_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_hostname_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_hostname_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_hostname_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_hostname_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_hostname_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_integer_type_matches_integers_request_body** + +> post_integer_type_matches_integers_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = 1 + try: + api_response = api_instance.post_integer_type_matches_integers_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_integer_type_matches_integers_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_integer_type_matches_integers_request_body.ApiResponseFor200) | success + +#### post_integer_type_matches_integers_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_integer_type_matches_integers_response_body_for_content_types** + +> int post_integer_type_matches_integers_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_integer_type_matches_integers_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_integer_type_matches_integers_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_integer_type_matches_integers_response_body_for_content_types.ApiResponseFor200) | success + +#### post_integer_type_matches_integers_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body** + +> post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf(1) + try: + api_response = api_instance.post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf**](../../models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.ApiResponseFor200) | success + +#### post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types** + +> InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.ApiResponseFor200) | success + +#### post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf**](../../models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_string_value_for_default_request_body** + +> post_invalid_string_value_for_default_request_body(invalid_string_value_for_default) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = InvalidStringValueForDefault(None) + try: + api_response = api_instance.post_invalid_string_value_for_default_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_invalid_string_value_for_default_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidStringValueForDefault**](../../models/InvalidStringValueForDefault.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_string_value_for_default_request_body.ApiResponseFor200) | success + +#### post_invalid_string_value_for_default_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_string_value_for_default_response_body_for_content_types** + +> InvalidStringValueForDefault post_invalid_string_value_for_default_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_invalid_string_value_for_default_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_invalid_string_value_for_default_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_string_value_for_default_response_body_for_content_types.ApiResponseFor200) | success + +#### post_invalid_string_value_for_default_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidStringValueForDefault**](../../models/InvalidStringValueForDefault.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv4_format_request_body** + +> post_ipv4_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ipv4_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ipv4_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv4_format_request_body.ApiResponseFor200) | success + +#### post_ipv4_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv4_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ipv4_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ipv4_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ipv4_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv4_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ipv4_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv6_format_request_body** + +> post_ipv6_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ipv6_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ipv6_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv6_format_request_body.ApiResponseFor200) | success + +#### post_ipv6_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv6_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ipv6_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ipv6_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ipv6_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv6_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ipv6_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_json_pointer_format_request_body** + +> post_json_pointer_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_json_pointer_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_json_pointer_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_json_pointer_format_request_body.ApiResponseFor200) | success + +#### post_json_pointer_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_json_pointer_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_json_pointer_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_json_pointer_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_json_pointer_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_json_pointer_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_json_pointer_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_request_body** + +> post_maximum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maximum_validation import MaximumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MaximumValidation(None) + try: + api_response = api_instance.post_maximum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maximum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidation**](../../models/MaximumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_request_body.ApiResponseFor200) | success + +#### post_maximum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_response_body_for_content_types** + +> MaximumValidation post_maximum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maximum_validation import MaximumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maximum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maximum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maximum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidation**](../../models/MaximumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_with_unsigned_integer_request_body** + +> post_maximum_validation_with_unsigned_integer_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MaximumValidationWithUnsignedInteger(None) + try: + api_response = api_instance.post_maximum_validation_with_unsigned_integer_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maximum_validation_with_unsigned_integer_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidationWithUnsignedInteger**](../../models/MaximumValidationWithUnsignedInteger.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_with_unsigned_integer_request_body.ApiResponseFor200) | success + +#### post_maximum_validation_with_unsigned_integer_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_with_unsigned_integer_response_body_for_content_types** + +> MaximumValidationWithUnsignedInteger post_maximum_validation_with_unsigned_integer_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maximum_validation_with_unsigned_integer_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maximum_validation_with_unsigned_integer_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_with_unsigned_integer_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maximum_validation_with_unsigned_integer_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidationWithUnsignedInteger**](../../models/MaximumValidationWithUnsignedInteger.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxitems_validation_request_body** + +> post_maxitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maxitems_validation import MaxitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxitemsValidation(None) + try: + api_response = api_instance.post_maxitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maxitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxitemsValidation**](../../models/MaxitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxitems_validation_request_body.ApiResponseFor200) | success + +#### post_maxitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxitems_validation_response_body_for_content_types** + +> MaxitemsValidation post_maxitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maxitems_validation import MaxitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maxitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxitemsValidation**](../../models/MaxitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxlength_validation_request_body** + +> post_maxlength_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maxlength_validation import MaxlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxlengthValidation(None) + try: + api_response = api_instance.post_maxlength_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maxlength_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxlengthValidation**](../../models/MaxlengthValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxlength_validation_request_body.ApiResponseFor200) | success + +#### post_maxlength_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxlength_validation_response_body_for_content_types** + +> MaxlengthValidation post_maxlength_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maxlength_validation import MaxlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxlength_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maxlength_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxlength_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxlength_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxlengthValidation**](../../models/MaxlengthValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties0_means_the_object_is_empty_request_body** + +> post_maxproperties0_means_the_object_is_empty_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = Maxproperties0MeansTheObjectIsEmpty(None) + try: + api_response = api_instance.post_maxproperties0_means_the_object_is_empty_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maxproperties0_means_the_object_is_empty_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Maxproperties0MeansTheObjectIsEmpty**](../../models/Maxproperties0MeansTheObjectIsEmpty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties0_means_the_object_is_empty_request_body.ApiResponseFor200) | success + +#### post_maxproperties0_means_the_object_is_empty_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties0_means_the_object_is_empty_response_body_for_content_types** + +> Maxproperties0MeansTheObjectIsEmpty post_maxproperties0_means_the_object_is_empty_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxproperties0_means_the_object_is_empty_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maxproperties0_means_the_object_is_empty_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Maxproperties0MeansTheObjectIsEmpty**](../../models/Maxproperties0MeansTheObjectIsEmpty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties_validation_request_body** + +> post_maxproperties_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MaxpropertiesValidation(None) + try: + api_response = api_instance.post_maxproperties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maxproperties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxpropertiesValidation**](../../models/MaxpropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties_validation_request_body.ApiResponseFor200) | success + +#### post_maxproperties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties_validation_response_body_for_content_types** + +> MaxpropertiesValidation post_maxproperties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxproperties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_maxproperties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxproperties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxpropertiesValidation**](../../models/MaxpropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_request_body** + +> post_minimum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minimum_validation import MinimumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MinimumValidation(None) + try: + api_response = api_instance.post_minimum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minimum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidation**](../../models/MinimumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_request_body.ApiResponseFor200) | success + +#### post_minimum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_response_body_for_content_types** + +> MinimumValidation post_minimum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minimum_validation import MinimumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minimum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minimum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minimum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidation**](../../models/MinimumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_with_signed_integer_request_body** + +> post_minimum_validation_with_signed_integer_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MinimumValidationWithSignedInteger(None) + try: + api_response = api_instance.post_minimum_validation_with_signed_integer_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minimum_validation_with_signed_integer_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidationWithSignedInteger**](../../models/MinimumValidationWithSignedInteger.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_with_signed_integer_request_body.ApiResponseFor200) | success + +#### post_minimum_validation_with_signed_integer_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_with_signed_integer_response_body_for_content_types** + +> MinimumValidationWithSignedInteger post_minimum_validation_with_signed_integer_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minimum_validation_with_signed_integer_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minimum_validation_with_signed_integer_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_with_signed_integer_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minimum_validation_with_signed_integer_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidationWithSignedInteger**](../../models/MinimumValidationWithSignedInteger.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minitems_validation_request_body** + +> post_minitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minitems_validation import MinitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MinitemsValidation(None) + try: + api_response = api_instance.post_minitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinitemsValidation**](../../models/MinitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minitems_validation_request_body.ApiResponseFor200) | success + +#### post_minitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minitems_validation_response_body_for_content_types** + +> MinitemsValidation post_minitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minitems_validation import MinitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinitemsValidation**](../../models/MinitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minlength_validation_request_body** + +> post_minlength_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minlength_validation import MinlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MinlengthValidation(None) + try: + api_response = api_instance.post_minlength_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minlength_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinlengthValidation**](../../models/MinlengthValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minlength_validation_request_body.ApiResponseFor200) | success + +#### post_minlength_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minlength_validation_response_body_for_content_types** + +> MinlengthValidation post_minlength_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minlength_validation import MinlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minlength_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minlength_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minlength_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minlength_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinlengthValidation**](../../models/MinlengthValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minproperties_validation_request_body** + +> post_minproperties_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minproperties_validation import MinpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = MinpropertiesValidation(None) + try: + api_response = api_instance.post_minproperties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minproperties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinpropertiesValidation**](../../models/MinpropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minproperties_validation_request_body.ApiResponseFor200) | success + +#### post_minproperties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minproperties_validation_response_body_for_content_types** + +> MinpropertiesValidation post_minproperties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.minproperties_validation import MinpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minproperties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_minproperties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minproperties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minproperties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinpropertiesValidation**](../../models/MinpropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_allof_to_check_validation_semantics_request_body** + +> post_nested_allof_to_check_validation_semantics_request_body(nested_allof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedAllofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_allof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nested_allof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAllofToCheckValidationSemantics**](../../models/NestedAllofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_allof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_allof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_allof_to_check_validation_semantics_response_body_for_content_types** + +> NestedAllofToCheckValidationSemantics post_nested_allof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_allof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nested_allof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_allof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_allof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAllofToCheckValidationSemantics**](../../models/NestedAllofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_anyof_to_check_validation_semantics_request_body** + +> post_nested_anyof_to_check_validation_semantics_request_body(nested_anyof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedAnyofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_anyof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nested_anyof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAnyofToCheckValidationSemantics**](../../models/NestedAnyofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_anyof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_anyof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_anyof_to_check_validation_semantics_response_body_for_content_types** + +> NestedAnyofToCheckValidationSemantics post_nested_anyof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_anyof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nested_anyof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAnyofToCheckValidationSemantics**](../../models/NestedAnyofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_items_request_body** + +> post_nested_items_request_body(nested_items) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nested_items import NestedItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedItems([ + [ + [ + [ + 3.14 + ] + ] + ] + ]) + try: + api_response = api_instance.post_nested_items_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nested_items_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedItems**](../../models/NestedItems.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_items_request_body.ApiResponseFor200) | success + +#### post_nested_items_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_items_response_body_for_content_types** + +> NestedItems post_nested_items_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nested_items import NestedItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_items_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nested_items_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_items_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_items_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedItems**](../../models/NestedItems.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_oneof_to_check_validation_semantics_request_body** + +> post_nested_oneof_to_check_validation_semantics_request_body(nested_oneof_to_check_validation_semantics) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = NestedOneofToCheckValidationSemantics(None) + try: + api_response = api_instance.post_nested_oneof_to_check_validation_semantics_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nested_oneof_to_check_validation_semantics_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedOneofToCheckValidationSemantics**](../../models/NestedOneofToCheckValidationSemantics.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_oneof_to_check_validation_semantics_request_body.ApiResponseFor200) | success + +#### post_nested_oneof_to_check_validation_semantics_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_oneof_to_check_validation_semantics_response_body_for_content_types** + +> NestedOneofToCheckValidationSemantics post_nested_oneof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_oneof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nested_oneof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedOneofToCheckValidationSemantics**](../../models/NestedOneofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_more_complex_schema_request_body** + +> post_not_more_complex_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_not_more_complex_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_not_more_complex_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_more_complex_schema_request_body.ApiResponseFor200) | success + +#### post_not_more_complex_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_more_complex_schema_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_not_more_complex_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_not_more_complex_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_not_more_complex_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_more_complex_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_not_more_complex_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_request_body** + +> post_not_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_not_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_not_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | decimal.Decimal, int, | decimal.Decimal, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_request_body.ApiResponseFor200) | success + +#### post_not_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_not_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_not_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_not_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_response_body_for_content_types.ApiResponseFor200) | success + +#### post_not_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | decimal.Decimal, int, | decimal.Decimal, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nul_characters_in_strings_request_body** + +> post_nul_characters_in_strings_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = NulCharactersInStrings("hello\x00there") + try: + api_response = api_instance.post_nul_characters_in_strings_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nul_characters_in_strings_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NulCharactersInStrings**](../../models/NulCharactersInStrings.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nul_characters_in_strings_request_body.ApiResponseFor200) | success + +#### post_nul_characters_in_strings_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nul_characters_in_strings_response_body_for_content_types** + +> NulCharactersInStrings post_nul_characters_in_strings_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nul_characters_in_strings_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_nul_characters_in_strings_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nul_characters_in_strings_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nul_characters_in_strings_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NulCharactersInStrings**](../../models/NulCharactersInStrings.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_null_type_matches_only_the_null_object_request_body** + +> post_null_type_matches_only_the_null_object_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_null_type_matches_only_the_null_object_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_null_type_matches_only_the_null_object_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_null_type_matches_only_the_null_object_request_body.ApiResponseFor200) | success + +#### post_null_type_matches_only_the_null_object_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_null_type_matches_only_the_null_object_response_body_for_content_types** + +> none_type post_null_type_matches_only_the_null_object_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_null_type_matches_only_the_null_object_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_null_type_matches_only_the_null_object_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_null_type_matches_only_the_null_object_response_body_for_content_types.ApiResponseFor200) | success + +#### post_null_type_matches_only_the_null_object_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_number_type_matches_numbers_request_body** + +> post_number_type_matches_numbers_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = 3.14 + try: + api_response = api_instance.post_number_type_matches_numbers_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_number_type_matches_numbers_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_number_type_matches_numbers_request_body.ApiResponseFor200) | success + +#### post_number_type_matches_numbers_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_number_type_matches_numbers_response_body_for_content_types** + +> int, float post_number_type_matches_numbers_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_number_type_matches_numbers_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_number_type_matches_numbers_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_number_type_matches_numbers_response_body_for_content_types.ApiResponseFor200) | success + +#### post_number_type_matches_numbers_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_properties_validation_request_body** + +> post_object_properties_validation_request_body(object_properties_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = ObjectPropertiesValidation(None) + try: + api_response = api_instance.post_object_properties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_object_properties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectPropertiesValidation**](../../models/ObjectPropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_properties_validation_request_body.ApiResponseFor200) | success + +#### post_object_properties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_properties_validation_response_body_for_content_types** + +> ObjectPropertiesValidation post_object_properties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_object_properties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_object_properties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_properties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_object_properties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectPropertiesValidation**](../../models/ObjectPropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_type_matches_objects_request_body** + +> post_object_type_matches_objects_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = dict() + try: + api_response = api_instance.post_object_type_matches_objects_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_object_type_matches_objects_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_type_matches_objects_request_body.ApiResponseFor200) | success + +#### post_object_type_matches_objects_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_type_matches_objects_response_body_for_content_types** + +> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} post_object_type_matches_objects_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_object_type_matches_objects_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_object_type_matches_objects_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_type_matches_objects_response_body_for_content_types.ApiResponseFor200) | success + +#### post_object_type_matches_objects_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_complex_types_request_body** + +> post_oneof_complex_types_request_body(oneof_complex_types) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof_complex_types import OneofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofComplexTypes(None) + try: + api_response = api_instance.post_oneof_complex_types_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_complex_types_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofComplexTypes**](../../models/OneofComplexTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_complex_types_request_body.ApiResponseFor200) | success + +#### post_oneof_complex_types_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_complex_types_response_body_for_content_types** + +> OneofComplexTypes post_oneof_complex_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof_complex_types import OneofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_complex_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_complex_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_complex_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_complex_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofComplexTypes**](../../models/OneofComplexTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_request_body** + +> post_oneof_request_body(oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof import Oneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = Oneof(None) + try: + api_response = api_instance.post_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Oneof**](../../models/Oneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_request_body.ApiResponseFor200) | success + +#### post_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_response_body_for_content_types** + +> Oneof post_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof import Oneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Oneof**](../../models/Oneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_base_schema_request_body** + +> post_oneof_with_base_schema_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithBaseSchema("body_example") + try: + api_response = api_instance.post_oneof_with_base_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_with_base_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithBaseSchema**](../../models/OneofWithBaseSchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_base_schema_request_body.ApiResponseFor200) | success + +#### post_oneof_with_base_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_base_schema_response_body_for_content_types** + +> OneofWithBaseSchema post_oneof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithBaseSchema**](../../models/OneofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_empty_schema_request_body** + +> post_oneof_with_empty_schema_request_body(oneof_with_empty_schema) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithEmptySchema(None) + try: + api_response = api_instance.post_oneof_with_empty_schema_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_with_empty_schema_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithEmptySchema**](../../models/OneofWithEmptySchema.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_empty_schema_request_body.ApiResponseFor200) | success + +#### post_oneof_with_empty_schema_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_empty_schema_response_body_for_content_types** + +> OneofWithEmptySchema post_oneof_with_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_with_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithEmptySchema**](../../models/OneofWithEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_required_request_body** + +> post_oneof_with_required_request_body(oneof_with_required) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof_with_required import OneofWithRequired +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = OneofWithRequired() + try: + api_response = api_instance.post_oneof_with_required_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_with_required_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithRequired**](../../models/OneofWithRequired.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_required_request_body.ApiResponseFor200) | success + +#### post_oneof_with_required_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_required_response_body_for_content_types** + +> OneofWithRequired post_oneof_with_required_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.oneof_with_required import OneofWithRequired +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_required_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_oneof_with_required_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_required_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_required_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithRequired**](../../models/OneofWithRequired.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_is_not_anchored_request_body** + +> post_pattern_is_not_anchored_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = PatternIsNotAnchored(None) + try: + api_response = api_instance.post_pattern_is_not_anchored_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_pattern_is_not_anchored_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternIsNotAnchored**](../../models/PatternIsNotAnchored.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_is_not_anchored_request_body.ApiResponseFor200) | success + +#### post_pattern_is_not_anchored_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_is_not_anchored_response_body_for_content_types** + +> PatternIsNotAnchored post_pattern_is_not_anchored_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_pattern_is_not_anchored_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_pattern_is_not_anchored_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_is_not_anchored_response_body_for_content_types.ApiResponseFor200) | success + +#### post_pattern_is_not_anchored_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternIsNotAnchored**](../../models/PatternIsNotAnchored.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_validation_request_body** + +> post_pattern_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.pattern_validation import PatternValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = PatternValidation(None) + try: + api_response = api_instance.post_pattern_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_pattern_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternValidation**](../../models/PatternValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_validation_request_body.ApiResponseFor200) | success + +#### post_pattern_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_validation_response_body_for_content_types** + +> PatternValidation post_pattern_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.pattern_validation import PatternValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_pattern_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_pattern_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_pattern_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternValidation**](../../models/PatternValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_properties_with_escaped_characters_request_body** + +> post_properties_with_escaped_characters_request_body(properties_with_escaped_characters) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = PropertiesWithEscapedCharacters(None) + try: + api_response = api_instance.post_properties_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_properties_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertiesWithEscapedCharacters**](../../models/PropertiesWithEscapedCharacters.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_properties_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_properties_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_properties_with_escaped_characters_response_body_for_content_types** + +> PropertiesWithEscapedCharacters post_properties_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_properties_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_properties_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_properties_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_properties_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertiesWithEscapedCharacters**](../../models/PropertiesWithEscapedCharacters.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_property_named_ref_that_is_not_a_reference_request_body** + +> post_property_named_ref_that_is_not_a_reference_request_body(property_named_ref_that_is_not_a_reference) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = PropertyNamedRefThatIsNotAReference(None) + try: + api_response = api_instance.post_property_named_ref_that_is_not_a_reference_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_property_named_ref_that_is_not_a_reference_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertyNamedRefThatIsNotAReference**](../../models/PropertyNamedRefThatIsNotAReference.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_property_named_ref_that_is_not_a_reference_request_body.ApiResponseFor200) | success + +#### post_property_named_ref_that_is_not_a_reference_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_property_named_ref_that_is_not_a_reference_response_body_for_content_types** + +> PropertyNamedRefThatIsNotAReference post_property_named_ref_that_is_not_a_reference_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_property_named_ref_that_is_not_a_reference_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_property_named_ref_that_is_not_a_reference_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.ApiResponseFor200) | success + +#### post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertyNamedRefThatIsNotAReference**](../../models/PropertyNamedRefThatIsNotAReference.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_additionalproperties_request_body** + +> post_ref_in_additionalproperties_request_body(ref_in_additionalproperties) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAdditionalproperties( + key=PropertyNamedRefThatIsNotAReference(None), + ) + try: + api_response = api_instance.post_ref_in_additionalproperties_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_additionalproperties_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAdditionalproperties**](../../models/RefInAdditionalproperties.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_additionalproperties_request_body.ApiResponseFor200) | success + +#### post_ref_in_additionalproperties_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_additionalproperties_response_body_for_content_types** + +> RefInAdditionalproperties post_ref_in_additionalproperties_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_additionalproperties_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_additionalproperties_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_additionalproperties_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_additionalproperties_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAdditionalproperties**](../../models/RefInAdditionalproperties.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_allof_request_body** + +> post_ref_in_allof_request_body(ref_in_allof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_allof import RefInAllof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAllof(None) + try: + api_response = api_instance.post_ref_in_allof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_allof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAllof**](../../models/RefInAllof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_allof_request_body.ApiResponseFor200) | success + +#### post_ref_in_allof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_allof_response_body_for_content_types** + +> RefInAllof post_ref_in_allof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_allof import RefInAllof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_allof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_allof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_allof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_allof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAllof**](../../models/RefInAllof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_anyof_request_body** + +> post_ref_in_anyof_request_body(ref_in_anyof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_anyof import RefInAnyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAnyof(None) + try: + api_response = api_instance.post_ref_in_anyof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_anyof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAnyof**](../../models/RefInAnyof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_anyof_request_body.ApiResponseFor200) | success + +#### post_ref_in_anyof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_anyof_response_body_for_content_types** + +> RefInAnyof post_ref_in_anyof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_anyof import RefInAnyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_anyof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_anyof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_anyof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_anyof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAnyof**](../../models/RefInAnyof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_items_request_body** + +> post_ref_in_items_request_body(ref_in_items) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_items import RefInItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInItems([ + PropertyNamedRefThatIsNotAReference(None) + ]) + try: + api_response = api_instance.post_ref_in_items_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_items_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInItems**](../../models/RefInItems.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_items_request_body.ApiResponseFor200) | success + +#### post_ref_in_items_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_items_response_body_for_content_types** + +> RefInItems post_ref_in_items_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_items import RefInItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_items_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_items_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_items_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_items_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInItems**](../../models/RefInItems.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_not_request_body** + +> post_ref_in_not_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ref_in_not_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_not_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_not_request_body.ApiResponseFor200) | success + +#### post_ref_in_not_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_not_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ref_in_not_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_not_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_not_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_not_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_not_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_oneof_request_body** + +> post_ref_in_oneof_request_body(ref_in_oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_oneof import RefInOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInOneof(None) + try: + api_response = api_instance.post_ref_in_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInOneof**](../../models/RefInOneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_oneof_request_body.ApiResponseFor200) | success + +#### post_ref_in_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_oneof_response_body_for_content_types** + +> RefInOneof post_ref_in_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_oneof import RefInOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInOneof**](../../models/RefInOneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_property_request_body** + +> post_ref_in_property_request_body(ref_in_property) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_property import RefInProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInProperty(None) + try: + api_response = api_instance.post_ref_in_property_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_property_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInProperty**](../../models/RefInProperty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_property_request_body.ApiResponseFor200) | success + +#### post_ref_in_property_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_property_response_body_for_content_types** + +> RefInProperty post_ref_in_property_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.ref_in_property import RefInProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_property_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_ref_in_property_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_property_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_property_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInProperty**](../../models/RefInProperty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_default_validation_request_body** + +> post_required_default_validation_request_body(required_default_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.required_default_validation import RequiredDefaultValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredDefaultValidation(None) + try: + api_response = api_instance.post_required_default_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_required_default_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredDefaultValidation**](../../models/RequiredDefaultValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_default_validation_request_body.ApiResponseFor200) | success + +#### post_required_default_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_default_validation_response_body_for_content_types** + +> RequiredDefaultValidation post_required_default_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.required_default_validation import RequiredDefaultValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_default_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_required_default_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_default_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_default_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredDefaultValidation**](../../models/RequiredDefaultValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_validation_request_body** + +> post_required_validation_request_body(required_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.required_validation import RequiredValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredValidation(None) + try: + api_response = api_instance.post_required_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_required_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredValidation**](../../models/RequiredValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_validation_request_body.ApiResponseFor200) | success + +#### post_required_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_validation_response_body_for_content_types** + +> RequiredValidation post_required_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.required_validation import RequiredValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_required_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredValidation**](../../models/RequiredValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_empty_array_request_body** + +> post_required_with_empty_array_request_body(required_with_empty_array) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredWithEmptyArray(None) + try: + api_response = api_instance.post_required_with_empty_array_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_required_with_empty_array_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredWithEmptyArray**](../../models/RequiredWithEmptyArray.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_empty_array_request_body.ApiResponseFor200) | success + +#### post_required_with_empty_array_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_empty_array_response_body_for_content_types** + +> RequiredWithEmptyArray post_required_with_empty_array_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_with_empty_array_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_required_with_empty_array_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_empty_array_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_with_empty_array_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredWithEmptyArray**](../../models/RequiredWithEmptyArray.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_escaped_characters_request_body** + +> post_required_with_escaped_characters_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_required_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_required_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_required_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_escaped_characters_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_required_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_required_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_simple_enum_validation_request_body** + +> post_simple_enum_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = SimpleEnumValidation(1) + try: + api_response = api_instance.post_simple_enum_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_simple_enum_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**SimpleEnumValidation**](../../models/SimpleEnumValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_simple_enum_validation_request_body.ApiResponseFor200) | success + +#### post_simple_enum_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_simple_enum_validation_response_body_for_content_types** + +> SimpleEnumValidation post_simple_enum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_simple_enum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_simple_enum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_simple_enum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_simple_enum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**SimpleEnumValidation**](../../models/SimpleEnumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_string_type_matches_strings_request_body** + +> post_string_type_matches_strings_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = "body_example" + try: + api_response = api_instance.post_string_type_matches_strings_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_string_type_matches_strings_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_string_type_matches_strings_request_body.ApiResponseFor200) | success + +#### post_string_type_matches_strings_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_string_type_matches_strings_response_body_for_content_types** + +> str post_string_type_matches_strings_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_string_type_matches_strings_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_string_type_matches_strings_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_string_type_matches_strings_response_body_for_content_types.ApiResponseFor200) | success + +#### post_string_type_matches_strings_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body** + +> post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body(the_default_keyword_does_not_do_anything_if_the_property_is_missing) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing( + alpha=5, + ) + try: + api_response = api_instance.post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing**](../../models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.ApiResponseFor200) | success + +#### post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types** + +> TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.ApiResponseFor200) | success + +#### post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing**](../../models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_false_validation_request_body** + +> post_uniqueitems_false_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = UniqueitemsFalseValidation(None) + try: + api_response = api_instance.post_uniqueitems_false_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uniqueitems_false_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsFalseValidation**](../../models/UniqueitemsFalseValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_false_validation_request_body.ApiResponseFor200) | success + +#### post_uniqueitems_false_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_false_validation_response_body_for_content_types** + +> UniqueitemsFalseValidation post_uniqueitems_false_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uniqueitems_false_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uniqueitems_false_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_false_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uniqueitems_false_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsFalseValidation**](../../models/UniqueitemsFalseValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_validation_request_body** + +> post_uniqueitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = UniqueitemsValidation(None) + try: + api_response = api_instance.post_uniqueitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uniqueitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsValidation**](../../models/UniqueitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_validation_request_body.ApiResponseFor200) | success + +#### post_uniqueitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_validation_response_body_for_content_types** + +> UniqueitemsValidation post_uniqueitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uniqueitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uniqueitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uniqueitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsValidation**](../../models/UniqueitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_format_request_body** + +> post_uri_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uri_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_format_request_body.ApiResponseFor200) | success + +#### post_uri_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uri_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_reference_format_request_body** + +> post_uri_reference_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_reference_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uri_reference_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_reference_format_request_body.ApiResponseFor200) | success + +#### post_uri_reference_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_reference_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_reference_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_reference_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uri_reference_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_reference_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_reference_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_template_format_request_body** + +> post_uri_template_format_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_uri_template_format_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uri_template_format_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_template_format_request_body.ApiResponseFor200) | success + +#### post_uri_template_format_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_template_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_template_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import path_post_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = path_post_api.PathPostApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_template_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PathPostApi->post_uri_template_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_template_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_template_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/PatternApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/PatternApi.md new file mode 100644 index 0000000000..a6cae4de54 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/PatternApi.md @@ -0,0 +1,274 @@ + +# unit_test_api.apis.tags.pattern_api.PatternApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_pattern_is_not_anchored_request_body**](#post_pattern_is_not_anchored_request_body) | **post** /requestBody/postPatternIsNotAnchoredRequestBody | +[**post_pattern_is_not_anchored_response_body_for_content_types**](#post_pattern_is_not_anchored_response_body_for_content_types) | **post** /responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes | +[**post_pattern_validation_request_body**](#post_pattern_validation_request_body) | **post** /requestBody/postPatternValidationRequestBody | +[**post_pattern_validation_response_body_for_content_types**](#post_pattern_validation_response_body_for_content_types) | **post** /responseBody/postPatternValidationResponseBodyForContentTypes | + +# **post_pattern_is_not_anchored_request_body** + +> post_pattern_is_not_anchored_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import pattern_api +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pattern_api.PatternApi(api_client) + + # example passing only required values which don't have defaults set + body = PatternIsNotAnchored(None) + try: + api_response = api_instance.post_pattern_is_not_anchored_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PatternApi->post_pattern_is_not_anchored_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternIsNotAnchored**](../../models/PatternIsNotAnchored.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_is_not_anchored_request_body.ApiResponseFor200) | success + +#### post_pattern_is_not_anchored_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_is_not_anchored_response_body_for_content_types** + +> PatternIsNotAnchored post_pattern_is_not_anchored_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import pattern_api +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pattern_api.PatternApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_pattern_is_not_anchored_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PatternApi->post_pattern_is_not_anchored_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_is_not_anchored_response_body_for_content_types.ApiResponseFor200) | success + +#### post_pattern_is_not_anchored_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternIsNotAnchored**](../../models/PatternIsNotAnchored.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_validation_request_body** + +> post_pattern_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import pattern_api +from unit_test_api.model.pattern_validation import PatternValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pattern_api.PatternApi(api_client) + + # example passing only required values which don't have defaults set + body = PatternValidation(None) + try: + api_response = api_instance.post_pattern_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PatternApi->post_pattern_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternValidation**](../../models/PatternValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_validation_request_body.ApiResponseFor200) | success + +#### post_pattern_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_validation_response_body_for_content_types** + +> PatternValidation post_pattern_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import pattern_api +from unit_test_api.model.pattern_validation import PatternValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pattern_api.PatternApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_pattern_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PatternApi->post_pattern_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_pattern_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternValidation**](../../models/PatternValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/PropertiesApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/PropertiesApi.md new file mode 100644 index 0000000000..67c74c2c13 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/PropertiesApi.md @@ -0,0 +1,274 @@ + +# unit_test_api.apis.tags.properties_api.PropertiesApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_object_properties_validation_request_body**](#post_object_properties_validation_request_body) | **post** /requestBody/postObjectPropertiesValidationRequestBody | +[**post_object_properties_validation_response_body_for_content_types**](#post_object_properties_validation_response_body_for_content_types) | **post** /responseBody/postObjectPropertiesValidationResponseBodyForContentTypes | +[**post_properties_with_escaped_characters_request_body**](#post_properties_with_escaped_characters_request_body) | **post** /requestBody/postPropertiesWithEscapedCharactersRequestBody | +[**post_properties_with_escaped_characters_response_body_for_content_types**](#post_properties_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes | + +# **post_object_properties_validation_request_body** + +> post_object_properties_validation_request_body(object_properties_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import properties_api +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = properties_api.PropertiesApi(api_client) + + # example passing only required values which don't have defaults set + body = ObjectPropertiesValidation(None) + try: + api_response = api_instance.post_object_properties_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PropertiesApi->post_object_properties_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectPropertiesValidation**](../../models/ObjectPropertiesValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_properties_validation_request_body.ApiResponseFor200) | success + +#### post_object_properties_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_properties_validation_response_body_for_content_types** + +> ObjectPropertiesValidation post_object_properties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import properties_api +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = properties_api.PropertiesApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_object_properties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PropertiesApi->post_object_properties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_properties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_object_properties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectPropertiesValidation**](../../models/ObjectPropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_properties_with_escaped_characters_request_body** + +> post_properties_with_escaped_characters_request_body(properties_with_escaped_characters) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import properties_api +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = properties_api.PropertiesApi(api_client) + + # example passing only required values which don't have defaults set + body = PropertiesWithEscapedCharacters(None) + try: + api_response = api_instance.post_properties_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling PropertiesApi->post_properties_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertiesWithEscapedCharacters**](../../models/PropertiesWithEscapedCharacters.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_properties_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_properties_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_properties_with_escaped_characters_response_body_for_content_types** + +> PropertiesWithEscapedCharacters post_properties_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import properties_api +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = properties_api.PropertiesApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_properties_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling PropertiesApi->post_properties_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_properties_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_properties_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertiesWithEscapedCharacters**](../../models/PropertiesWithEscapedCharacters.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/RefApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/RefApi.md new file mode 100644 index 0000000000..520d9c3230 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/RefApi.md @@ -0,0 +1,1090 @@ + +# unit_test_api.apis.tags.ref_api.RefApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_property_named_ref_that_is_not_a_reference_request_body**](#post_property_named_ref_that_is_not_a_reference_request_body) | **post** /requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody | +[**post_property_named_ref_that_is_not_a_reference_response_body_for_content_types**](#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types) | **post** /responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes | +[**post_ref_in_additionalproperties_request_body**](#post_ref_in_additionalproperties_request_body) | **post** /requestBody/postRefInAdditionalpropertiesRequestBody | +[**post_ref_in_additionalproperties_response_body_for_content_types**](#post_ref_in_additionalproperties_response_body_for_content_types) | **post** /responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes | +[**post_ref_in_allof_request_body**](#post_ref_in_allof_request_body) | **post** /requestBody/postRefInAllofRequestBody | +[**post_ref_in_allof_response_body_for_content_types**](#post_ref_in_allof_response_body_for_content_types) | **post** /responseBody/postRefInAllofResponseBodyForContentTypes | +[**post_ref_in_anyof_request_body**](#post_ref_in_anyof_request_body) | **post** /requestBody/postRefInAnyofRequestBody | +[**post_ref_in_anyof_response_body_for_content_types**](#post_ref_in_anyof_response_body_for_content_types) | **post** /responseBody/postRefInAnyofResponseBodyForContentTypes | +[**post_ref_in_items_request_body**](#post_ref_in_items_request_body) | **post** /requestBody/postRefInItemsRequestBody | +[**post_ref_in_items_response_body_for_content_types**](#post_ref_in_items_response_body_for_content_types) | **post** /responseBody/postRefInItemsResponseBodyForContentTypes | +[**post_ref_in_not_request_body**](#post_ref_in_not_request_body) | **post** /requestBody/postRefInNotRequestBody | +[**post_ref_in_not_response_body_for_content_types**](#post_ref_in_not_response_body_for_content_types) | **post** /responseBody/postRefInNotResponseBodyForContentTypes | +[**post_ref_in_oneof_request_body**](#post_ref_in_oneof_request_body) | **post** /requestBody/postRefInOneofRequestBody | +[**post_ref_in_oneof_response_body_for_content_types**](#post_ref_in_oneof_response_body_for_content_types) | **post** /responseBody/postRefInOneofResponseBodyForContentTypes | +[**post_ref_in_property_request_body**](#post_ref_in_property_request_body) | **post** /requestBody/postRefInPropertyRequestBody | +[**post_ref_in_property_response_body_for_content_types**](#post_ref_in_property_response_body_for_content_types) | **post** /responseBody/postRefInPropertyResponseBodyForContentTypes | + +# **post_property_named_ref_that_is_not_a_reference_request_body** + +> post_property_named_ref_that_is_not_a_reference_request_body(property_named_ref_that_is_not_a_reference) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example passing only required values which don't have defaults set + body = PropertyNamedRefThatIsNotAReference(None) + try: + api_response = api_instance.post_property_named_ref_that_is_not_a_reference_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_property_named_ref_that_is_not_a_reference_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertyNamedRefThatIsNotAReference**](../../models/PropertyNamedRefThatIsNotAReference.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_property_named_ref_that_is_not_a_reference_request_body.ApiResponseFor200) | success + +#### post_property_named_ref_that_is_not_a_reference_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_property_named_ref_that_is_not_a_reference_response_body_for_content_types** + +> PropertyNamedRefThatIsNotAReference post_property_named_ref_that_is_not_a_reference_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_property_named_ref_that_is_not_a_reference_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_property_named_ref_that_is_not_a_reference_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.ApiResponseFor200) | success + +#### post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertyNamedRefThatIsNotAReference**](../../models/PropertyNamedRefThatIsNotAReference.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_additionalproperties_request_body** + +> post_ref_in_additionalproperties_request_body(ref_in_additionalproperties) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAdditionalproperties( + key=PropertyNamedRefThatIsNotAReference(None), + ) + try: + api_response = api_instance.post_ref_in_additionalproperties_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_additionalproperties_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAdditionalproperties**](../../models/RefInAdditionalproperties.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_additionalproperties_request_body.ApiResponseFor200) | success + +#### post_ref_in_additionalproperties_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_additionalproperties_response_body_for_content_types** + +> RefInAdditionalproperties post_ref_in_additionalproperties_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_additionalproperties_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_additionalproperties_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_additionalproperties_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_additionalproperties_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAdditionalproperties**](../../models/RefInAdditionalproperties.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_allof_request_body** + +> post_ref_in_allof_request_body(ref_in_allof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_allof import RefInAllof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAllof(None) + try: + api_response = api_instance.post_ref_in_allof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_allof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAllof**](../../models/RefInAllof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_allof_request_body.ApiResponseFor200) | success + +#### post_ref_in_allof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_allof_response_body_for_content_types** + +> RefInAllof post_ref_in_allof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_allof import RefInAllof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_allof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_allof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_allof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_allof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAllof**](../../models/RefInAllof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_anyof_request_body** + +> post_ref_in_anyof_request_body(ref_in_anyof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_anyof import RefInAnyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInAnyof(None) + try: + api_response = api_instance.post_ref_in_anyof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_anyof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAnyof**](../../models/RefInAnyof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_anyof_request_body.ApiResponseFor200) | success + +#### post_ref_in_anyof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_anyof_response_body_for_content_types** + +> RefInAnyof post_ref_in_anyof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_anyof import RefInAnyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_anyof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_anyof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_anyof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_anyof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAnyof**](../../models/RefInAnyof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_items_request_body** + +> post_ref_in_items_request_body(ref_in_items) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_items import RefInItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInItems([ + PropertyNamedRefThatIsNotAReference(None) + ]) + try: + api_response = api_instance.post_ref_in_items_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_items_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInItems**](../../models/RefInItems.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_items_request_body.ApiResponseFor200) | success + +#### post_ref_in_items_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_items_response_body_for_content_types** + +> RefInItems post_ref_in_items_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_items import RefInItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_items_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_items_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_items_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_items_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInItems**](../../models/RefInItems.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_not_request_body** + +> post_ref_in_not_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_ref_in_not_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_not_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_not_request_body.ApiResponseFor200) | success + +#### post_ref_in_not_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_not_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ref_in_not_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_not_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_not_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_not_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_not_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_oneof_request_body** + +> post_ref_in_oneof_request_body(ref_in_oneof) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_oneof import RefInOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInOneof(None) + try: + api_response = api_instance.post_ref_in_oneof_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_oneof_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInOneof**](../../models/RefInOneof.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_oneof_request_body.ApiResponseFor200) | success + +#### post_ref_in_oneof_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_oneof_response_body_for_content_types** + +> RefInOneof post_ref_in_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_oneof import RefInOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInOneof**](../../models/RefInOneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_property_request_body** + +> post_ref_in_property_request_body(ref_in_property) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_property import RefInProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example passing only required values which don't have defaults set + body = RefInProperty(None) + try: + api_response = api_instance.post_ref_in_property_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_property_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInProperty**](../../models/RefInProperty.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_property_request_body.ApiResponseFor200) | success + +#### post_ref_in_property_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_property_response_body_for_content_types** + +> RefInProperty post_ref_in_property_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import ref_api +from unit_test_api.model.ref_in_property import RefInProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = ref_api.RefApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_property_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RefApi->post_ref_in_property_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_property_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_property_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInProperty**](../../models/RefInProperty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/RequiredApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/RequiredApi.md new file mode 100644 index 0000000000..7ed6e02f04 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/RequiredApi.md @@ -0,0 +1,540 @@ + +# unit_test_api.apis.tags.required_api.RequiredApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_required_default_validation_request_body**](#post_required_default_validation_request_body) | **post** /requestBody/postRequiredDefaultValidationRequestBody | +[**post_required_default_validation_response_body_for_content_types**](#post_required_default_validation_response_body_for_content_types) | **post** /responseBody/postRequiredDefaultValidationResponseBodyForContentTypes | +[**post_required_validation_request_body**](#post_required_validation_request_body) | **post** /requestBody/postRequiredValidationRequestBody | +[**post_required_validation_response_body_for_content_types**](#post_required_validation_response_body_for_content_types) | **post** /responseBody/postRequiredValidationResponseBodyForContentTypes | +[**post_required_with_empty_array_request_body**](#post_required_with_empty_array_request_body) | **post** /requestBody/postRequiredWithEmptyArrayRequestBody | +[**post_required_with_empty_array_response_body_for_content_types**](#post_required_with_empty_array_response_body_for_content_types) | **post** /responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes | +[**post_required_with_escaped_characters_request_body**](#post_required_with_escaped_characters_request_body) | **post** /requestBody/postRequiredWithEscapedCharactersRequestBody | +[**post_required_with_escaped_characters_response_body_for_content_types**](#post_required_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes | + +# **post_required_default_validation_request_body** + +> post_required_default_validation_request_body(required_default_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import required_api +from unit_test_api.model.required_default_validation import RequiredDefaultValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = required_api.RequiredApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredDefaultValidation(None) + try: + api_response = api_instance.post_required_default_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RequiredApi->post_required_default_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredDefaultValidation**](../../models/RequiredDefaultValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_default_validation_request_body.ApiResponseFor200) | success + +#### post_required_default_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_default_validation_response_body_for_content_types** + +> RequiredDefaultValidation post_required_default_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import required_api +from unit_test_api.model.required_default_validation import RequiredDefaultValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = required_api.RequiredApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_default_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RequiredApi->post_required_default_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_default_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_default_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredDefaultValidation**](../../models/RequiredDefaultValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_validation_request_body** + +> post_required_validation_request_body(required_validation) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import required_api +from unit_test_api.model.required_validation import RequiredValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = required_api.RequiredApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredValidation(None) + try: + api_response = api_instance.post_required_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RequiredApi->post_required_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredValidation**](../../models/RequiredValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_validation_request_body.ApiResponseFor200) | success + +#### post_required_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_validation_response_body_for_content_types** + +> RequiredValidation post_required_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import required_api +from unit_test_api.model.required_validation import RequiredValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = required_api.RequiredApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RequiredApi->post_required_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredValidation**](../../models/RequiredValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_empty_array_request_body** + +> post_required_with_empty_array_request_body(required_with_empty_array) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import required_api +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = required_api.RequiredApi(api_client) + + # example passing only required values which don't have defaults set + body = RequiredWithEmptyArray(None) + try: + api_response = api_instance.post_required_with_empty_array_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RequiredApi->post_required_with_empty_array_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredWithEmptyArray**](../../models/RequiredWithEmptyArray.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_empty_array_request_body.ApiResponseFor200) | success + +#### post_required_with_empty_array_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_empty_array_response_body_for_content_types** + +> RequiredWithEmptyArray post_required_with_empty_array_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import required_api +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = required_api.RequiredApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_with_empty_array_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RequiredApi->post_required_with_empty_array_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_empty_array_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_with_empty_array_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredWithEmptyArray**](../../models/RequiredWithEmptyArray.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_escaped_characters_request_body** + +> post_required_with_escaped_characters_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import required_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = required_api.RequiredApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_required_with_escaped_characters_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling RequiredApi->post_required_with_escaped_characters_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_escaped_characters_request_body.ApiResponseFor200) | success + +#### post_required_with_escaped_characters_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_escaped_characters_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_required_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import required_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = required_api.RequiredApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling RequiredApi->post_required_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ResponseContentContentTypeSchemaApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ResponseContentContentTypeSchemaApi.md new file mode 100644 index 0000000000..0147f02e5f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/ResponseContentContentTypeSchemaApi.md @@ -0,0 +1,5354 @@ + +# unit_test_api.apis.tags.response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types**](#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes | +[**post_additionalproperties_are_allowed_by_default_response_body_for_content_types**](#post_additionalproperties_are_allowed_by_default_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes | +[**post_additionalproperties_can_exist_by_itself_response_body_for_content_types**](#post_additionalproperties_can_exist_by_itself_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes | +[**post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types**](#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types) | **post** /responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes | +[**post_allof_combined_with_anyof_oneof_response_body_for_content_types**](#post_allof_combined_with_anyof_oneof_response_body_for_content_types) | **post** /responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes | +[**post_allof_response_body_for_content_types**](#post_allof_response_body_for_content_types) | **post** /responseBody/postAllofResponseBodyForContentTypes | +[**post_allof_simple_types_response_body_for_content_types**](#post_allof_simple_types_response_body_for_content_types) | **post** /responseBody/postAllofSimpleTypesResponseBodyForContentTypes | +[**post_allof_with_base_schema_response_body_for_content_types**](#post_allof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes | +[**post_allof_with_one_empty_schema_response_body_for_content_types**](#post_allof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_the_first_empty_schema_response_body_for_content_types**](#post_allof_with_the_first_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_the_last_empty_schema_response_body_for_content_types**](#post_allof_with_the_last_empty_schema_response_body_for_content_types) | **post** /responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes | +[**post_allof_with_two_empty_schemas_response_body_for_content_types**](#post_allof_with_two_empty_schemas_response_body_for_content_types) | **post** /responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes | +[**post_anyof_complex_types_response_body_for_content_types**](#post_anyof_complex_types_response_body_for_content_types) | **post** /responseBody/postAnyofComplexTypesResponseBodyForContentTypes | +[**post_anyof_response_body_for_content_types**](#post_anyof_response_body_for_content_types) | **post** /responseBody/postAnyofResponseBodyForContentTypes | +[**post_anyof_with_base_schema_response_body_for_content_types**](#post_anyof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes | +[**post_anyof_with_one_empty_schema_response_body_for_content_types**](#post_anyof_with_one_empty_schema_response_body_for_content_types) | **post** /responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes | +[**post_array_type_matches_arrays_response_body_for_content_types**](#post_array_type_matches_arrays_response_body_for_content_types) | **post** /responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes | +[**post_boolean_type_matches_booleans_response_body_for_content_types**](#post_boolean_type_matches_booleans_response_body_for_content_types) | **post** /responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes | +[**post_by_int_response_body_for_content_types**](#post_by_int_response_body_for_content_types) | **post** /responseBody/postByIntResponseBodyForContentTypes | +[**post_by_number_response_body_for_content_types**](#post_by_number_response_body_for_content_types) | **post** /responseBody/postByNumberResponseBodyForContentTypes | +[**post_by_small_number_response_body_for_content_types**](#post_by_small_number_response_body_for_content_types) | **post** /responseBody/postBySmallNumberResponseBodyForContentTypes | +[**post_date_time_format_response_body_for_content_types**](#post_date_time_format_response_body_for_content_types) | **post** /responseBody/postDateTimeFormatResponseBodyForContentTypes | +[**post_email_format_response_body_for_content_types**](#post_email_format_response_body_for_content_types) | **post** /responseBody/postEmailFormatResponseBodyForContentTypes | +[**post_enum_with0_does_not_match_false_response_body_for_content_types**](#post_enum_with0_does_not_match_false_response_body_for_content_types) | **post** /responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes | +[**post_enum_with1_does_not_match_true_response_body_for_content_types**](#post_enum_with1_does_not_match_true_response_body_for_content_types) | **post** /responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes | +[**post_enum_with_escaped_characters_response_body_for_content_types**](#post_enum_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes | +[**post_enum_with_false_does_not_match0_response_body_for_content_types**](#post_enum_with_false_does_not_match0_response_body_for_content_types) | **post** /responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes | +[**post_enum_with_true_does_not_match1_response_body_for_content_types**](#post_enum_with_true_does_not_match1_response_body_for_content_types) | **post** /responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes | +[**post_enums_in_properties_response_body_for_content_types**](#post_enums_in_properties_response_body_for_content_types) | **post** /responseBody/postEnumsInPropertiesResponseBodyForContentTypes | +[**post_forbidden_property_response_body_for_content_types**](#post_forbidden_property_response_body_for_content_types) | **post** /responseBody/postForbiddenPropertyResponseBodyForContentTypes | +[**post_hostname_format_response_body_for_content_types**](#post_hostname_format_response_body_for_content_types) | **post** /responseBody/postHostnameFormatResponseBodyForContentTypes | +[**post_integer_type_matches_integers_response_body_for_content_types**](#post_integer_type_matches_integers_response_body_for_content_types) | **post** /responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes | +[**post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types**](#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types) | **post** /responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes | +[**post_invalid_string_value_for_default_response_body_for_content_types**](#post_invalid_string_value_for_default_response_body_for_content_types) | **post** /responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes | +[**post_ipv4_format_response_body_for_content_types**](#post_ipv4_format_response_body_for_content_types) | **post** /responseBody/postIpv4FormatResponseBodyForContentTypes | +[**post_ipv6_format_response_body_for_content_types**](#post_ipv6_format_response_body_for_content_types) | **post** /responseBody/postIpv6FormatResponseBodyForContentTypes | +[**post_json_pointer_format_response_body_for_content_types**](#post_json_pointer_format_response_body_for_content_types) | **post** /responseBody/postJsonPointerFormatResponseBodyForContentTypes | +[**post_maximum_validation_response_body_for_content_types**](#post_maximum_validation_response_body_for_content_types) | **post** /responseBody/postMaximumValidationResponseBodyForContentTypes | +[**post_maximum_validation_with_unsigned_integer_response_body_for_content_types**](#post_maximum_validation_with_unsigned_integer_response_body_for_content_types) | **post** /responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes | +[**post_maxitems_validation_response_body_for_content_types**](#post_maxitems_validation_response_body_for_content_types) | **post** /responseBody/postMaxitemsValidationResponseBodyForContentTypes | +[**post_maxlength_validation_response_body_for_content_types**](#post_maxlength_validation_response_body_for_content_types) | **post** /responseBody/postMaxlengthValidationResponseBodyForContentTypes | +[**post_maxproperties0_means_the_object_is_empty_response_body_for_content_types**](#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types) | **post** /responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes | +[**post_maxproperties_validation_response_body_for_content_types**](#post_maxproperties_validation_response_body_for_content_types) | **post** /responseBody/postMaxpropertiesValidationResponseBodyForContentTypes | +[**post_minimum_validation_response_body_for_content_types**](#post_minimum_validation_response_body_for_content_types) | **post** /responseBody/postMinimumValidationResponseBodyForContentTypes | +[**post_minimum_validation_with_signed_integer_response_body_for_content_types**](#post_minimum_validation_with_signed_integer_response_body_for_content_types) | **post** /responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes | +[**post_minitems_validation_response_body_for_content_types**](#post_minitems_validation_response_body_for_content_types) | **post** /responseBody/postMinitemsValidationResponseBodyForContentTypes | +[**post_minlength_validation_response_body_for_content_types**](#post_minlength_validation_response_body_for_content_types) | **post** /responseBody/postMinlengthValidationResponseBodyForContentTypes | +[**post_minproperties_validation_response_body_for_content_types**](#post_minproperties_validation_response_body_for_content_types) | **post** /responseBody/postMinpropertiesValidationResponseBodyForContentTypes | +[**post_nested_allof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_allof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_nested_anyof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_nested_items_response_body_for_content_types**](#post_nested_items_response_body_for_content_types) | **post** /responseBody/postNestedItemsResponseBodyForContentTypes | +[**post_nested_oneof_to_check_validation_semantics_response_body_for_content_types**](#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types) | **post** /responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes | +[**post_not_more_complex_schema_response_body_for_content_types**](#post_not_more_complex_schema_response_body_for_content_types) | **post** /responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes | +[**post_not_response_body_for_content_types**](#post_not_response_body_for_content_types) | **post** /responseBody/postNotResponseBodyForContentTypes | +[**post_nul_characters_in_strings_response_body_for_content_types**](#post_nul_characters_in_strings_response_body_for_content_types) | **post** /responseBody/postNulCharactersInStringsResponseBodyForContentTypes | +[**post_null_type_matches_only_the_null_object_response_body_for_content_types**](#post_null_type_matches_only_the_null_object_response_body_for_content_types) | **post** /responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes | +[**post_number_type_matches_numbers_response_body_for_content_types**](#post_number_type_matches_numbers_response_body_for_content_types) | **post** /responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes | +[**post_object_properties_validation_response_body_for_content_types**](#post_object_properties_validation_response_body_for_content_types) | **post** /responseBody/postObjectPropertiesValidationResponseBodyForContentTypes | +[**post_object_type_matches_objects_response_body_for_content_types**](#post_object_type_matches_objects_response_body_for_content_types) | **post** /responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes | +[**post_oneof_complex_types_response_body_for_content_types**](#post_oneof_complex_types_response_body_for_content_types) | **post** /responseBody/postOneofComplexTypesResponseBodyForContentTypes | +[**post_oneof_response_body_for_content_types**](#post_oneof_response_body_for_content_types) | **post** /responseBody/postOneofResponseBodyForContentTypes | +[**post_oneof_with_base_schema_response_body_for_content_types**](#post_oneof_with_base_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes | +[**post_oneof_with_empty_schema_response_body_for_content_types**](#post_oneof_with_empty_schema_response_body_for_content_types) | **post** /responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes | +[**post_oneof_with_required_response_body_for_content_types**](#post_oneof_with_required_response_body_for_content_types) | **post** /responseBody/postOneofWithRequiredResponseBodyForContentTypes | +[**post_pattern_is_not_anchored_response_body_for_content_types**](#post_pattern_is_not_anchored_response_body_for_content_types) | **post** /responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes | +[**post_pattern_validation_response_body_for_content_types**](#post_pattern_validation_response_body_for_content_types) | **post** /responseBody/postPatternValidationResponseBodyForContentTypes | +[**post_properties_with_escaped_characters_response_body_for_content_types**](#post_properties_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes | +[**post_property_named_ref_that_is_not_a_reference_response_body_for_content_types**](#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types) | **post** /responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes | +[**post_ref_in_additionalproperties_response_body_for_content_types**](#post_ref_in_additionalproperties_response_body_for_content_types) | **post** /responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes | +[**post_ref_in_allof_response_body_for_content_types**](#post_ref_in_allof_response_body_for_content_types) | **post** /responseBody/postRefInAllofResponseBodyForContentTypes | +[**post_ref_in_anyof_response_body_for_content_types**](#post_ref_in_anyof_response_body_for_content_types) | **post** /responseBody/postRefInAnyofResponseBodyForContentTypes | +[**post_ref_in_items_response_body_for_content_types**](#post_ref_in_items_response_body_for_content_types) | **post** /responseBody/postRefInItemsResponseBodyForContentTypes | +[**post_ref_in_not_response_body_for_content_types**](#post_ref_in_not_response_body_for_content_types) | **post** /responseBody/postRefInNotResponseBodyForContentTypes | +[**post_ref_in_oneof_response_body_for_content_types**](#post_ref_in_oneof_response_body_for_content_types) | **post** /responseBody/postRefInOneofResponseBodyForContentTypes | +[**post_ref_in_property_response_body_for_content_types**](#post_ref_in_property_response_body_for_content_types) | **post** /responseBody/postRefInPropertyResponseBodyForContentTypes | +[**post_required_default_validation_response_body_for_content_types**](#post_required_default_validation_response_body_for_content_types) | **post** /responseBody/postRequiredDefaultValidationResponseBodyForContentTypes | +[**post_required_validation_response_body_for_content_types**](#post_required_validation_response_body_for_content_types) | **post** /responseBody/postRequiredValidationResponseBodyForContentTypes | +[**post_required_with_empty_array_response_body_for_content_types**](#post_required_with_empty_array_response_body_for_content_types) | **post** /responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes | +[**post_required_with_escaped_characters_response_body_for_content_types**](#post_required_with_escaped_characters_response_body_for_content_types) | **post** /responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes | +[**post_simple_enum_validation_response_body_for_content_types**](#post_simple_enum_validation_response_body_for_content_types) | **post** /responseBody/postSimpleEnumValidationResponseBodyForContentTypes | +[**post_string_type_matches_strings_response_body_for_content_types**](#post_string_type_matches_strings_response_body_for_content_types) | **post** /responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes | +[**post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types**](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types) | **post** /responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes | +[**post_uniqueitems_false_validation_response_body_for_content_types**](#post_uniqueitems_false_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes | +[**post_uniqueitems_validation_response_body_for_content_types**](#post_uniqueitems_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsValidationResponseBodyForContentTypes | +[**post_uri_format_response_body_for_content_types**](#post_uri_format_response_body_for_content_types) | **post** /responseBody/postUriFormatResponseBodyForContentTypes | +[**post_uri_reference_format_response_body_for_content_types**](#post_uri_reference_format_response_body_for_content_types) | **post** /responseBody/postUriReferenceFormatResponseBodyForContentTypes | +[**post_uri_template_format_response_body_for_content_types**](#post_uri_template_format_response_body_for_content_types) | **post** /responseBody/postUriTemplateFormatResponseBodyForContentTypes | + +# **post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types** + +> AdditionalpropertiesAllowsASchemaWhichShouldValidate post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAllowsASchemaWhichShouldValidate**](../../models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_are_allowed_by_default_response_body_for_content_types** + +> AdditionalpropertiesAreAllowedByDefault post_additionalproperties_are_allowed_by_default_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_are_allowed_by_default_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_additionalproperties_are_allowed_by_default_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_are_allowed_by_default_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_are_allowed_by_default_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesAreAllowedByDefault**](../../models/AdditionalpropertiesAreAllowedByDefault.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_can_exist_by_itself_response_body_for_content_types** + +> AdditionalpropertiesCanExistByItself post_additionalproperties_can_exist_by_itself_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_can_exist_by_itself_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_additionalproperties_can_exist_by_itself_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_can_exist_by_itself_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_can_exist_by_itself_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesCanExistByItself**](../../models/AdditionalpropertiesCanExistByItself.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types** + +> AdditionalpropertiesShouldNotLookInApplicators post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.ApiResponseFor200) | success + +#### post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalpropertiesShouldNotLookInApplicators**](../../models/AdditionalpropertiesShouldNotLookInApplicators.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_combined_with_anyof_oneof_response_body_for_content_types** + +> AllofCombinedWithAnyofOneof post_allof_combined_with_anyof_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_combined_with_anyof_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_allof_combined_with_anyof_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_combined_with_anyof_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_combined_with_anyof_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofCombinedWithAnyofOneof**](../../models/AllofCombinedWithAnyofOneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_response_body_for_content_types** + +> Allof post_allof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.allof import Allof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_allof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Allof**](../../models/Allof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_simple_types_response_body_for_content_types** + +> AllofSimpleTypes post_allof_simple_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.allof_simple_types import AllofSimpleTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_simple_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_allof_simple_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_simple_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_simple_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofSimpleTypes**](../../models/AllofSimpleTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_base_schema_response_body_for_content_types** + +> AllofWithBaseSchema post_allof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_allof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithBaseSchema**](../../models/AllofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_one_empty_schema_response_body_for_content_types** + +> AllofWithOneEmptySchema post_allof_with_one_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_one_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_allof_with_one_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithOneEmptySchema**](../../models/AllofWithOneEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_first_empty_schema_response_body_for_content_types** + +> AllofWithTheFirstEmptySchema post_allof_with_the_first_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_the_first_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_allof_with_the_first_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_first_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_the_first_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheFirstEmptySchema**](../../models/AllofWithTheFirstEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_the_last_empty_schema_response_body_for_content_types** + +> AllofWithTheLastEmptySchema post_allof_with_the_last_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_the_last_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_allof_with_the_last_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_the_last_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_the_last_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTheLastEmptySchema**](../../models/AllofWithTheLastEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_allof_with_two_empty_schemas_response_body_for_content_types** + +> AllofWithTwoEmptySchemas post_allof_with_two_empty_schemas_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_allof_with_two_empty_schemas_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_allof_with_two_empty_schemas_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_allof_with_two_empty_schemas_response_body_for_content_types.ApiResponseFor200) | success + +#### post_allof_with_two_empty_schemas_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AllofWithTwoEmptySchemas**](../../models/AllofWithTwoEmptySchemas.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_complex_types_response_body_for_content_types** + +> AnyofComplexTypes post_anyof_complex_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_complex_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_anyof_complex_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_complex_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_complex_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofComplexTypes**](../../models/AnyofComplexTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_response_body_for_content_types** + +> Anyof post_anyof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.anyof import Anyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_anyof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Anyof**](../../models/Anyof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_base_schema_response_body_for_content_types** + +> AnyofWithBaseSchema post_anyof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_anyof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithBaseSchema**](../../models/AnyofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_anyof_with_one_empty_schema_response_body_for_content_types** + +> AnyofWithOneEmptySchema post_anyof_with_one_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_anyof_with_one_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_anyof_with_one_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_anyof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_anyof_with_one_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnyofWithOneEmptySchema**](../../models/AnyofWithOneEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_array_type_matches_arrays_response_body_for_content_types** + +> ArrayTypeMatchesArrays post_array_type_matches_arrays_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_array_type_matches_arrays_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_array_type_matches_arrays_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_array_type_matches_arrays_response_body_for_content_types.ApiResponseFor200) | success + +#### post_array_type_matches_arrays_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayTypeMatchesArrays**](../../models/ArrayTypeMatchesArrays.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_boolean_type_matches_booleans_response_body_for_content_types** + +> bool post_boolean_type_matches_booleans_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_boolean_type_matches_booleans_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_boolean_type_matches_booleans_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_boolean_type_matches_booleans_response_body_for_content_types.ApiResponseFor200) | success + +#### post_boolean_type_matches_booleans_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_int_response_body_for_content_types** + +> ByInt post_by_int_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.by_int import ByInt +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_int_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_by_int_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_int_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_int_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByInt**](../../models/ByInt.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_number_response_body_for_content_types** + +> ByNumber post_by_number_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.by_number import ByNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_number_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_by_number_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_number_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_number_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ByNumber**](../../models/ByNumber.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_by_small_number_response_body_for_content_types** + +> BySmallNumber post_by_small_number_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.by_small_number import BySmallNumber +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_by_small_number_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_by_small_number_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_by_small_number_response_body_for_content_types.ApiResponseFor200) | success + +#### post_by_small_number_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**BySmallNumber**](../../models/BySmallNumber.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_date_time_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_date_time_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_date_time_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_date_time_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_date_time_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_date_time_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | value must conform to RFC-3339 date-time + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_email_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_email_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_email_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_email_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_email_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_email_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with0_does_not_match_false_response_body_for_content_types** + +> EnumWith0DoesNotMatchFalse post_enum_with0_does_not_match_false_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with0_does_not_match_false_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_enum_with0_does_not_match_false_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with0_does_not_match_false_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with0_does_not_match_false_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith0DoesNotMatchFalse**](../../models/EnumWith0DoesNotMatchFalse.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with1_does_not_match_true_response_body_for_content_types** + +> EnumWith1DoesNotMatchTrue post_enum_with1_does_not_match_true_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with1_does_not_match_true_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_enum_with1_does_not_match_true_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with1_does_not_match_true_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with1_does_not_match_true_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWith1DoesNotMatchTrue**](../../models/EnumWith1DoesNotMatchTrue.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_escaped_characters_response_body_for_content_types** + +> EnumWithEscapedCharacters post_enum_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_enum_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithEscapedCharacters**](../../models/EnumWithEscapedCharacters.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_false_does_not_match0_response_body_for_content_types** + +> EnumWithFalseDoesNotMatch0 post_enum_with_false_does_not_match0_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_false_does_not_match0_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_enum_with_false_does_not_match0_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_false_does_not_match0_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_false_does_not_match0_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithFalseDoesNotMatch0**](../../models/EnumWithFalseDoesNotMatch0.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enum_with_true_does_not_match1_response_body_for_content_types** + +> EnumWithTrueDoesNotMatch1 post_enum_with_true_does_not_match1_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enum_with_true_does_not_match1_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_enum_with_true_does_not_match1_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enum_with_true_does_not_match1_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enum_with_true_does_not_match1_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumWithTrueDoesNotMatch1**](../../models/EnumWithTrueDoesNotMatch1.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_enums_in_properties_response_body_for_content_types** + +> EnumsInProperties post_enums_in_properties_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.enums_in_properties import EnumsInProperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_enums_in_properties_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_enums_in_properties_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_enums_in_properties_response_body_for_content_types.ApiResponseFor200) | success + +#### post_enums_in_properties_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**EnumsInProperties**](../../models/EnumsInProperties.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_forbidden_property_response_body_for_content_types** + +> ForbiddenProperty post_forbidden_property_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.forbidden_property import ForbiddenProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_forbidden_property_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_forbidden_property_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_forbidden_property_response_body_for_content_types.ApiResponseFor200) | success + +#### post_forbidden_property_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ForbiddenProperty**](../../models/ForbiddenProperty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_hostname_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_hostname_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_hostname_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_hostname_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_hostname_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_hostname_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_integer_type_matches_integers_response_body_for_content_types** + +> int post_integer_type_matches_integers_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_integer_type_matches_integers_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_integer_type_matches_integers_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_integer_type_matches_integers_response_body_for_content_types.ApiResponseFor200) | success + +#### post_integer_type_matches_integers_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types** + +> InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.ApiResponseFor200) | success + +#### post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf**](../../models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_invalid_string_value_for_default_response_body_for_content_types** + +> InvalidStringValueForDefault post_invalid_string_value_for_default_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_invalid_string_value_for_default_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_invalid_string_value_for_default_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_invalid_string_value_for_default_response_body_for_content_types.ApiResponseFor200) | success + +#### post_invalid_string_value_for_default_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**InvalidStringValueForDefault**](../../models/InvalidStringValueForDefault.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv4_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ipv4_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ipv4_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_ipv4_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv4_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ipv4_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ipv6_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ipv6_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ipv6_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_ipv6_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ipv6_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ipv6_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_json_pointer_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_json_pointer_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_json_pointer_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_json_pointer_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_json_pointer_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_json_pointer_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_response_body_for_content_types** + +> MaximumValidation post_maximum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.maximum_validation import MaximumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maximum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_maximum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maximum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidation**](../../models/MaximumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maximum_validation_with_unsigned_integer_response_body_for_content_types** + +> MaximumValidationWithUnsignedInteger post_maximum_validation_with_unsigned_integer_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maximum_validation_with_unsigned_integer_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_maximum_validation_with_unsigned_integer_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maximum_validation_with_unsigned_integer_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maximum_validation_with_unsigned_integer_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaximumValidationWithUnsignedInteger**](../../models/MaximumValidationWithUnsignedInteger.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxitems_validation_response_body_for_content_types** + +> MaxitemsValidation post_maxitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.maxitems_validation import MaxitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_maxitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxitemsValidation**](../../models/MaxitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxlength_validation_response_body_for_content_types** + +> MaxlengthValidation post_maxlength_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.maxlength_validation import MaxlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxlength_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_maxlength_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxlength_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxlength_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxlengthValidation**](../../models/MaxlengthValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties0_means_the_object_is_empty_response_body_for_content_types** + +> Maxproperties0MeansTheObjectIsEmpty post_maxproperties0_means_the_object_is_empty_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxproperties0_means_the_object_is_empty_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_maxproperties0_means_the_object_is_empty_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Maxproperties0MeansTheObjectIsEmpty**](../../models/Maxproperties0MeansTheObjectIsEmpty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_maxproperties_validation_response_body_for_content_types** + +> MaxpropertiesValidation post_maxproperties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_maxproperties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_maxproperties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_maxproperties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_maxproperties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MaxpropertiesValidation**](../../models/MaxpropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_response_body_for_content_types** + +> MinimumValidation post_minimum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.minimum_validation import MinimumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minimum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_minimum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minimum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidation**](../../models/MinimumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minimum_validation_with_signed_integer_response_body_for_content_types** + +> MinimumValidationWithSignedInteger post_minimum_validation_with_signed_integer_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minimum_validation_with_signed_integer_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_minimum_validation_with_signed_integer_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minimum_validation_with_signed_integer_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minimum_validation_with_signed_integer_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinimumValidationWithSignedInteger**](../../models/MinimumValidationWithSignedInteger.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minitems_validation_response_body_for_content_types** + +> MinitemsValidation post_minitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.minitems_validation import MinitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_minitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinitemsValidation**](../../models/MinitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minlength_validation_response_body_for_content_types** + +> MinlengthValidation post_minlength_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.minlength_validation import MinlengthValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minlength_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_minlength_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minlength_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minlength_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinlengthValidation**](../../models/MinlengthValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_minproperties_validation_response_body_for_content_types** + +> MinpropertiesValidation post_minproperties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.minproperties_validation import MinpropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_minproperties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_minproperties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_minproperties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_minproperties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**MinpropertiesValidation**](../../models/MinpropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_allof_to_check_validation_semantics_response_body_for_content_types** + +> NestedAllofToCheckValidationSemantics post_nested_allof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_allof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_nested_allof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_allof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_allof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAllofToCheckValidationSemantics**](../../models/NestedAllofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_anyof_to_check_validation_semantics_response_body_for_content_types** + +> NestedAnyofToCheckValidationSemantics post_nested_anyof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_anyof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_nested_anyof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedAnyofToCheckValidationSemantics**](../../models/NestedAnyofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_items_response_body_for_content_types** + +> NestedItems post_nested_items_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.nested_items import NestedItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_items_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_nested_items_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_items_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_items_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedItems**](../../models/NestedItems.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nested_oneof_to_check_validation_semantics_response_body_for_content_types** + +> NestedOneofToCheckValidationSemantics post_nested_oneof_to_check_validation_semantics_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nested_oneof_to_check_validation_semantics_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_nested_oneof_to_check_validation_semantics_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NestedOneofToCheckValidationSemantics**](../../models/NestedOneofToCheckValidationSemantics.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_more_complex_schema_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_not_more_complex_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_not_more_complex_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_not_more_complex_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_more_complex_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_not_more_complex_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_not_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_not_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_not_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_not_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_not_response_body_for_content_types.ApiResponseFor200) | success + +#### post_not_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | decimal.Decimal, int, | decimal.Decimal, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_nul_characters_in_strings_response_body_for_content_types** + +> NulCharactersInStrings post_nul_characters_in_strings_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_nul_characters_in_strings_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_nul_characters_in_strings_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_nul_characters_in_strings_response_body_for_content_types.ApiResponseFor200) | success + +#### post_nul_characters_in_strings_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NulCharactersInStrings**](../../models/NulCharactersInStrings.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_null_type_matches_only_the_null_object_response_body_for_content_types** + +> none_type post_null_type_matches_only_the_null_object_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_null_type_matches_only_the_null_object_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_null_type_matches_only_the_null_object_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_null_type_matches_only_the_null_object_response_body_for_content_types.ApiResponseFor200) | success + +#### post_null_type_matches_only_the_null_object_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_number_type_matches_numbers_response_body_for_content_types** + +> int, float post_number_type_matches_numbers_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_number_type_matches_numbers_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_number_type_matches_numbers_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_number_type_matches_numbers_response_body_for_content_types.ApiResponseFor200) | success + +#### post_number_type_matches_numbers_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_properties_validation_response_body_for_content_types** + +> ObjectPropertiesValidation post_object_properties_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_object_properties_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_object_properties_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_properties_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_object_properties_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectPropertiesValidation**](../../models/ObjectPropertiesValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_type_matches_objects_response_body_for_content_types** + +> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} post_object_type_matches_objects_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_object_type_matches_objects_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_object_type_matches_objects_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_type_matches_objects_response_body_for_content_types.ApiResponseFor200) | success + +#### post_object_type_matches_objects_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_complex_types_response_body_for_content_types** + +> OneofComplexTypes post_oneof_complex_types_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.oneof_complex_types import OneofComplexTypes +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_complex_types_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_oneof_complex_types_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_complex_types_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_complex_types_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofComplexTypes**](../../models/OneofComplexTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_response_body_for_content_types** + +> Oneof post_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.oneof import Oneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Oneof**](../../models/Oneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_base_schema_response_body_for_content_types** + +> OneofWithBaseSchema post_oneof_with_base_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_base_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_oneof_with_base_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_base_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_base_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithBaseSchema**](../../models/OneofWithBaseSchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_empty_schema_response_body_for_content_types** + +> OneofWithEmptySchema post_oneof_with_empty_schema_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_empty_schema_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_oneof_with_empty_schema_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_empty_schema_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_empty_schema_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithEmptySchema**](../../models/OneofWithEmptySchema.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_oneof_with_required_response_body_for_content_types** + +> OneofWithRequired post_oneof_with_required_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.oneof_with_required import OneofWithRequired +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_oneof_with_required_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_oneof_with_required_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_oneof_with_required_response_body_for_content_types.ApiResponseFor200) | success + +#### post_oneof_with_required_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**OneofWithRequired**](../../models/OneofWithRequired.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_is_not_anchored_response_body_for_content_types** + +> PatternIsNotAnchored post_pattern_is_not_anchored_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_pattern_is_not_anchored_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_pattern_is_not_anchored_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_is_not_anchored_response_body_for_content_types.ApiResponseFor200) | success + +#### post_pattern_is_not_anchored_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternIsNotAnchored**](../../models/PatternIsNotAnchored.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_pattern_validation_response_body_for_content_types** + +> PatternValidation post_pattern_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.pattern_validation import PatternValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_pattern_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_pattern_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_pattern_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_pattern_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PatternValidation**](../../models/PatternValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_properties_with_escaped_characters_response_body_for_content_types** + +> PropertiesWithEscapedCharacters post_properties_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_properties_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_properties_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_properties_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_properties_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertiesWithEscapedCharacters**](../../models/PropertiesWithEscapedCharacters.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_property_named_ref_that_is_not_a_reference_response_body_for_content_types** + +> PropertyNamedRefThatIsNotAReference post_property_named_ref_that_is_not_a_reference_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_property_named_ref_that_is_not_a_reference_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_property_named_ref_that_is_not_a_reference_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.ApiResponseFor200) | success + +#### post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**PropertyNamedRefThatIsNotAReference**](../../models/PropertyNamedRefThatIsNotAReference.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_additionalproperties_response_body_for_content_types** + +> RefInAdditionalproperties post_ref_in_additionalproperties_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_additionalproperties_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_ref_in_additionalproperties_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_additionalproperties_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_additionalproperties_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAdditionalproperties**](../../models/RefInAdditionalproperties.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_allof_response_body_for_content_types** + +> RefInAllof post_ref_in_allof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.ref_in_allof import RefInAllof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_allof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_ref_in_allof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_allof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_allof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAllof**](../../models/RefInAllof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_anyof_response_body_for_content_types** + +> RefInAnyof post_ref_in_anyof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.ref_in_anyof import RefInAnyof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_anyof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_ref_in_anyof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_anyof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_anyof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInAnyof**](../../models/RefInAnyof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_items_response_body_for_content_types** + +> RefInItems post_ref_in_items_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.ref_in_items import RefInItems +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_items_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_ref_in_items_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_items_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_items_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInItems**](../../models/RefInItems.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_not_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_ref_in_not_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_not_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_ref_in_not_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_not_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_not_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**]({{complexTypePrefix}}PropertyNamedRefThatIsNotAReference.md) | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_oneof_response_body_for_content_types** + +> RefInOneof post_ref_in_oneof_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.ref_in_oneof import RefInOneof +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_oneof_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_ref_in_oneof_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_oneof_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_oneof_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInOneof**](../../models/RefInOneof.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_ref_in_property_response_body_for_content_types** + +> RefInProperty post_ref_in_property_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.ref_in_property import RefInProperty +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_ref_in_property_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_ref_in_property_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_ref_in_property_response_body_for_content_types.ApiResponseFor200) | success + +#### post_ref_in_property_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RefInProperty**](../../models/RefInProperty.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_default_validation_response_body_for_content_types** + +> RequiredDefaultValidation post_required_default_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.required_default_validation import RequiredDefaultValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_default_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_required_default_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_default_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_default_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredDefaultValidation**](../../models/RequiredDefaultValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_validation_response_body_for_content_types** + +> RequiredValidation post_required_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.required_validation import RequiredValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_required_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredValidation**](../../models/RequiredValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_empty_array_response_body_for_content_types** + +> RequiredWithEmptyArray post_required_with_empty_array_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_with_empty_array_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_required_with_empty_array_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_empty_array_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_with_empty_array_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**RequiredWithEmptyArray**](../../models/RequiredWithEmptyArray.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_required_with_escaped_characters_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_required_with_escaped_characters_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_required_with_escaped_characters_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_required_with_escaped_characters_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_required_with_escaped_characters_response_body_for_content_types.ApiResponseFor200) | success + +#### post_required_with_escaped_characters_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_simple_enum_validation_response_body_for_content_types** + +> SimpleEnumValidation post_simple_enum_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_simple_enum_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_simple_enum_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_simple_enum_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_simple_enum_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**SimpleEnumValidation**](../../models/SimpleEnumValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_string_type_matches_strings_response_body_for_content_types** + +> str post_string_type_matches_strings_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_string_type_matches_strings_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_string_type_matches_strings_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_string_type_matches_strings_response_body_for_content_types.ApiResponseFor200) | success + +#### post_string_type_matches_strings_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types** + +> TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.ApiResponseFor200) | success + +#### post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing**](../../models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_false_validation_response_body_for_content_types** + +> UniqueitemsFalseValidation post_uniqueitems_false_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uniqueitems_false_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_uniqueitems_false_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_false_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uniqueitems_false_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsFalseValidation**](../../models/UniqueitemsFalseValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_validation_response_body_for_content_types** + +> UniqueitemsValidation post_uniqueitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uniqueitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_uniqueitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uniqueitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsValidation**](../../models/UniqueitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_uri_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_reference_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_reference_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_reference_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_uri_reference_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_reference_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_reference_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uri_template_format_response_body_for_content_types** + +> bool, date, datetime, dict, float, int, list, str, none_type post_uri_template_format_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import response_content_content_type_schema_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = response_content_content_type_schema_api.ResponseContentContentTypeSchemaApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uri_template_format_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling ResponseContentContentTypeSchemaApi->post_uri_template_format_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uri_template_format_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uri_template_format_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/TypeApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/TypeApi.md new file mode 100644 index 0000000000..f3f2d1bebd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/TypeApi.md @@ -0,0 +1,941 @@ + +# unit_test_api.apis.tags.type_api.TypeApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_array_type_matches_arrays_request_body**](#post_array_type_matches_arrays_request_body) | **post** /requestBody/postArrayTypeMatchesArraysRequestBody | +[**post_array_type_matches_arrays_response_body_for_content_types**](#post_array_type_matches_arrays_response_body_for_content_types) | **post** /responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes | +[**post_boolean_type_matches_booleans_request_body**](#post_boolean_type_matches_booleans_request_body) | **post** /requestBody/postBooleanTypeMatchesBooleansRequestBody | +[**post_boolean_type_matches_booleans_response_body_for_content_types**](#post_boolean_type_matches_booleans_response_body_for_content_types) | **post** /responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes | +[**post_integer_type_matches_integers_request_body**](#post_integer_type_matches_integers_request_body) | **post** /requestBody/postIntegerTypeMatchesIntegersRequestBody | +[**post_integer_type_matches_integers_response_body_for_content_types**](#post_integer_type_matches_integers_response_body_for_content_types) | **post** /responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes | +[**post_null_type_matches_only_the_null_object_request_body**](#post_null_type_matches_only_the_null_object_request_body) | **post** /requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody | +[**post_null_type_matches_only_the_null_object_response_body_for_content_types**](#post_null_type_matches_only_the_null_object_response_body_for_content_types) | **post** /responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes | +[**post_number_type_matches_numbers_request_body**](#post_number_type_matches_numbers_request_body) | **post** /requestBody/postNumberTypeMatchesNumbersRequestBody | +[**post_number_type_matches_numbers_response_body_for_content_types**](#post_number_type_matches_numbers_response_body_for_content_types) | **post** /responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes | +[**post_object_type_matches_objects_request_body**](#post_object_type_matches_objects_request_body) | **post** /requestBody/postObjectTypeMatchesObjectsRequestBody | +[**post_object_type_matches_objects_response_body_for_content_types**](#post_object_type_matches_objects_response_body_for_content_types) | **post** /responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes | +[**post_string_type_matches_strings_request_body**](#post_string_type_matches_strings_request_body) | **post** /requestBody/postStringTypeMatchesStringsRequestBody | +[**post_string_type_matches_strings_response_body_for_content_types**](#post_string_type_matches_strings_response_body_for_content_types) | **post** /responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes | + +# **post_array_type_matches_arrays_request_body** + +> post_array_type_matches_arrays_request_body(array_type_matches_arrays) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example passing only required values which don't have defaults set + body = ArrayTypeMatchesArrays([ + None + ]) + try: + api_response = api_instance.post_array_type_matches_arrays_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_array_type_matches_arrays_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayTypeMatchesArrays**](../../models/ArrayTypeMatchesArrays.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_array_type_matches_arrays_request_body.ApiResponseFor200) | success + +#### post_array_type_matches_arrays_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_array_type_matches_arrays_response_body_for_content_types** + +> ArrayTypeMatchesArrays post_array_type_matches_arrays_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_array_type_matches_arrays_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_array_type_matches_arrays_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_array_type_matches_arrays_response_body_for_content_types.ApiResponseFor200) | success + +#### post_array_type_matches_arrays_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayTypeMatchesArrays**](../../models/ArrayTypeMatchesArrays.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_boolean_type_matches_booleans_request_body** + +> post_boolean_type_matches_booleans_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example passing only required values which don't have defaults set + body = True + try: + api_response = api_instance.post_boolean_type_matches_booleans_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_boolean_type_matches_booleans_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_boolean_type_matches_booleans_request_body.ApiResponseFor200) | success + +#### post_boolean_type_matches_booleans_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_boolean_type_matches_booleans_response_body_for_content_types** + +> bool post_boolean_type_matches_booleans_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_boolean_type_matches_booleans_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_boolean_type_matches_booleans_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_boolean_type_matches_booleans_response_body_for_content_types.ApiResponseFor200) | success + +#### post_boolean_type_matches_booleans_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_integer_type_matches_integers_request_body** + +> post_integer_type_matches_integers_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example passing only required values which don't have defaults set + body = 1 + try: + api_response = api_instance.post_integer_type_matches_integers_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_integer_type_matches_integers_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_integer_type_matches_integers_request_body.ApiResponseFor200) | success + +#### post_integer_type_matches_integers_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_integer_type_matches_integers_response_body_for_content_types** + +> int post_integer_type_matches_integers_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_integer_type_matches_integers_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_integer_type_matches_integers_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_integer_type_matches_integers_response_body_for_content_types.ApiResponseFor200) | success + +#### post_integer_type_matches_integers_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_null_type_matches_only_the_null_object_request_body** + +> post_null_type_matches_only_the_null_object_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example passing only required values which don't have defaults set + body = None + try: + api_response = api_instance.post_null_type_matches_only_the_null_object_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_null_type_matches_only_the_null_object_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_null_type_matches_only_the_null_object_request_body.ApiResponseFor200) | success + +#### post_null_type_matches_only_the_null_object_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_null_type_matches_only_the_null_object_response_body_for_content_types** + +> none_type post_null_type_matches_only_the_null_object_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_null_type_matches_only_the_null_object_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_null_type_matches_only_the_null_object_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_null_type_matches_only_the_null_object_response_body_for_content_types.ApiResponseFor200) | success + +#### post_null_type_matches_only_the_null_object_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_number_type_matches_numbers_request_body** + +> post_number_type_matches_numbers_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example passing only required values which don't have defaults set + body = 3.14 + try: + api_response = api_instance.post_number_type_matches_numbers_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_number_type_matches_numbers_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_number_type_matches_numbers_request_body.ApiResponseFor200) | success + +#### post_number_type_matches_numbers_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_number_type_matches_numbers_response_body_for_content_types** + +> int, float post_number_type_matches_numbers_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_number_type_matches_numbers_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_number_type_matches_numbers_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_number_type_matches_numbers_response_body_for_content_types.ApiResponseFor200) | success + +#### post_number_type_matches_numbers_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_type_matches_objects_request_body** + +> post_object_type_matches_objects_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example passing only required values which don't have defaults set + body = dict() + try: + api_response = api_instance.post_object_type_matches_objects_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_object_type_matches_objects_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_type_matches_objects_request_body.ApiResponseFor200) | success + +#### post_object_type_matches_objects_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_object_type_matches_objects_response_body_for_content_types** + +> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} post_object_type_matches_objects_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_object_type_matches_objects_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_object_type_matches_objects_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_object_type_matches_objects_response_body_for_content_types.ApiResponseFor200) | success + +#### post_object_type_matches_objects_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_string_type_matches_strings_request_body** + +> post_string_type_matches_strings_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example passing only required values which don't have defaults set + body = "body_example" + try: + api_response = api_instance.post_string_type_matches_strings_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_string_type_matches_strings_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_string_type_matches_strings_request_body.ApiResponseFor200) | success + +#### post_string_type_matches_strings_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_string_type_matches_strings_response_body_for_content_types** + +> str post_string_type_matches_strings_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import type_api +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = type_api.TypeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_string_type_matches_strings_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling TypeApi->post_string_type_matches_strings_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_string_type_matches_strings_response_body_for_content_types.ApiResponseFor200) | success + +#### post_string_type_matches_strings_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/UniqueItemsApi.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/UniqueItemsApi.md new file mode 100644 index 0000000000..529b69479c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/apis/tags/UniqueItemsApi.md @@ -0,0 +1,274 @@ + +# unit_test_api.apis.tags.unique_items_api.UniqueItemsApi + +All URIs are relative to *https://someserver.com/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**post_uniqueitems_false_validation_request_body**](#post_uniqueitems_false_validation_request_body) | **post** /requestBody/postUniqueitemsFalseValidationRequestBody | +[**post_uniqueitems_false_validation_response_body_for_content_types**](#post_uniqueitems_false_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes | +[**post_uniqueitems_validation_request_body**](#post_uniqueitems_validation_request_body) | **post** /requestBody/postUniqueitemsValidationRequestBody | +[**post_uniqueitems_validation_response_body_for_content_types**](#post_uniqueitems_validation_response_body_for_content_types) | **post** /responseBody/postUniqueitemsValidationResponseBodyForContentTypes | + +# **post_uniqueitems_false_validation_request_body** + +> post_uniqueitems_false_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import unique_items_api +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = unique_items_api.UniqueItemsApi(api_client) + + # example passing only required values which don't have defaults set + body = UniqueitemsFalseValidation(None) + try: + api_response = api_instance.post_uniqueitems_false_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling UniqueItemsApi->post_uniqueitems_false_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsFalseValidation**](../../models/UniqueitemsFalseValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_false_validation_request_body.ApiResponseFor200) | success + +#### post_uniqueitems_false_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_false_validation_response_body_for_content_types** + +> UniqueitemsFalseValidation post_uniqueitems_false_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import unique_items_api +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = unique_items_api.UniqueItemsApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uniqueitems_false_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling UniqueItemsApi->post_uniqueitems_false_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_false_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uniqueitems_false_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsFalseValidation**](../../models/UniqueitemsFalseValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_validation_request_body** + +> post_uniqueitems_validation_request_body(body) + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import unique_items_api +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = unique_items_api.UniqueItemsApi(api_client) + + # example passing only required values which don't have defaults set + body = UniqueitemsValidation(None) + try: + api_response = api_instance.post_uniqueitems_validation_request_body( + body=body, + ) + except unit_test_api.ApiException as e: + print("Exception when calling UniqueItemsApi->post_uniqueitems_validation_request_body: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsValidation**](../../models/UniqueitemsValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_validation_request_body.ApiResponseFor200) | success + +#### post_uniqueitems_validation_request_body.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **post_uniqueitems_validation_response_body_for_content_types** + +> UniqueitemsValidation post_uniqueitems_validation_response_body_for_content_types() + + + +### Example + +```python +import unit_test_api +from unit_test_api.apis.tags import unique_items_api +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation +from pprint import pprint +# Defining the host is optional and defaults to https://someserver.com/v1 +# See configuration.py for a list of all supported configuration parameters. +configuration = unit_test_api.Configuration( + host = "https://someserver.com/v1" +) + +# Enter a context with an instance of the API client +with unit_test_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = unique_items_api.UniqueItemsApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.post_uniqueitems_validation_response_body_for_content_types() + pprint(api_response) + except unit_test_api.ApiException as e: + print("Exception when calling UniqueItemsApi->post_uniqueitems_validation_response_body_for_content_types: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#post_uniqueitems_validation_response_body_for_content_types.ApiResponseFor200) | success + +#### post_uniqueitems_validation_response_body_for_content_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**UniqueitemsValidation**](../../models/UniqueitemsValidation.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md new file mode 100644 index 0000000000..e32452e5c8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesAllowsASchemaWhichShouldValidate.md @@ -0,0 +1,16 @@ +# unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate.AdditionalpropertiesAllowsASchemaWhichShouldValidate + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**bar** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | bool, | BoolClass, | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesAreAllowedByDefault.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesAreAllowedByDefault.md new file mode 100644 index 0000000000..7548452e43 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesAreAllowedByDefault.md @@ -0,0 +1,16 @@ +# unit_test_api.model.additionalproperties_are_allowed_by_default.AdditionalpropertiesAreAllowedByDefault + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**bar** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesCanExistByItself.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesCanExistByItself.md new file mode 100644 index 0000000000..09f1d02d8d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesCanExistByItself.md @@ -0,0 +1,14 @@ +# unit_test_api.model.additionalproperties_can_exist_by_itself.AdditionalpropertiesCanExistByItself + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | bool, | BoolClass, | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesShouldNotLookInApplicators.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesShouldNotLookInApplicators.md new file mode 100644 index 0000000000..fa1430a42e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AdditionalpropertiesShouldNotLookInApplicators.md @@ -0,0 +1,33 @@ +# unit_test_api.model.additionalproperties_should_not_look_in_applicators.AdditionalpropertiesShouldNotLookInApplicators + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | bool, | BoolClass, | any string name can be used but the value must be the correct type | [optional] + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Allof.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Allof.md new file mode 100644 index 0000000000..db9cd5c720 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Allof.md @@ -0,0 +1,42 @@ +# unit_test_api.model.allof.Allof + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**bar** | decimal.Decimal, int, | decimal.Decimal, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofCombinedWithAnyofOneof.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofCombinedWithAnyofOneof.md new file mode 100644 index 0000000000..5b26a94969 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofCombinedWithAnyofOneof.md @@ -0,0 +1,44 @@ +# unit_test_api.model.allof_combined_with_anyof_oneof.AllofCombinedWithAnyofOneof + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[any_of_0](#any_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# any_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofSimpleTypes.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofSimpleTypes.md new file mode 100644 index 0000000000..75e8863db6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofSimpleTypes.md @@ -0,0 +1,30 @@ +# unit_test_api.model.allof_simple_types.AllofSimpleTypes + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithBaseSchema.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithBaseSchema.md new file mode 100644 index 0000000000..e9db83fae8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithBaseSchema.md @@ -0,0 +1,48 @@ +# unit_test_api.model.allof_with_base_schema.AllofWithBaseSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**bar** | decimal.Decimal, int, | decimal.Decimal, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**baz** | None, | NoneClass, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithOneEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithOneEmptySchema.md new file mode 100644 index 0000000000..429e2ac820 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithOneEmptySchema.md @@ -0,0 +1,22 @@ +# unit_test_api.model.allof_with_one_empty_schema.AllofWithOneEmptySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithTheFirstEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithTheFirstEmptySchema.md new file mode 100644 index 0000000000..bb6fd4199b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithTheFirstEmptySchema.md @@ -0,0 +1,30 @@ +# unit_test_api.model.allof_with_the_first_empty_schema.AllofWithTheFirstEmptySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[all_of_1](#all_of_1) | decimal.Decimal, int, float, | decimal.Decimal, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithTheLastEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithTheLastEmptySchema.md new file mode 100644 index 0000000000..2e40966de7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithTheLastEmptySchema.md @@ -0,0 +1,30 @@ +# unit_test_api.model.allof_with_the_last_empty_schema.AllofWithTheLastEmptySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | decimal.Decimal, int, float, | decimal.Decimal, | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithTwoEmptySchemas.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithTwoEmptySchemas.md new file mode 100644 index 0000000000..1bc82005d3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AllofWithTwoEmptySchemas.md @@ -0,0 +1,30 @@ +# unit_test_api.model.allof_with_two_empty_schemas.AllofWithTwoEmptySchemas + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Anyof.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Anyof.md new file mode 100644 index 0000000000..53747ab915 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Anyof.md @@ -0,0 +1,30 @@ +# unit_test_api.model.anyof.Anyof + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[any_of_0](#any_of_0) | decimal.Decimal, int, | decimal.Decimal, | | +[any_of_1](#any_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# any_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +# any_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AnyofComplexTypes.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AnyofComplexTypes.md new file mode 100644 index 0000000000..12f091e3c9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AnyofComplexTypes.md @@ -0,0 +1,42 @@ +# unit_test_api.model.anyof_complex_types.AnyofComplexTypes + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[any_of_0](#any_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[any_of_1](#any_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# any_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**bar** | decimal.Decimal, int, | decimal.Decimal, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# any_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AnyofWithBaseSchema.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AnyofWithBaseSchema.md new file mode 100644 index 0000000000..ad1b6b4d57 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AnyofWithBaseSchema.md @@ -0,0 +1,30 @@ +# unit_test_api.model.anyof_with_base_schema.AnyofWithBaseSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[any_of_0](#any_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[any_of_1](#any_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# any_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# any_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AnyofWithOneEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AnyofWithOneEmptySchema.md new file mode 100644 index 0000000000..12c5c93067 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/AnyofWithOneEmptySchema.md @@ -0,0 +1,30 @@ +# unit_test_api.model.anyof_with_one_empty_schema.AnyofWithOneEmptySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[any_of_0](#any_of_0) | decimal.Decimal, int, float, | decimal.Decimal, | | +[any_of_1](#any_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# any_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +# any_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ArrayTypeMatchesArrays.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ArrayTypeMatchesArrays.md new file mode 100644 index 0000000000..ea887dfa1b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ArrayTypeMatchesArrays.md @@ -0,0 +1,14 @@ +# unit_test_api.model.array_type_matches_arrays.ArrayTypeMatchesArrays + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/BooleanTypeMatchesBooleans.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/BooleanTypeMatchesBooleans.md new file mode 100644 index 0000000000..63d7e87453 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/BooleanTypeMatchesBooleans.md @@ -0,0 +1,9 @@ +# unit_test_api.model.boolean_type_matches_booleans.BooleanTypeMatchesBooleans + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ByInt.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ByInt.md new file mode 100644 index 0000000000..7c7c706c1a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ByInt.md @@ -0,0 +1,9 @@ +# unit_test_api.model.by_int.ByInt + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ByNumber.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ByNumber.md new file mode 100644 index 0000000000..4f58cada0e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ByNumber.md @@ -0,0 +1,9 @@ +# unit_test_api.model.by_number.ByNumber + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/BySmallNumber.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/BySmallNumber.md new file mode 100644 index 0000000000..7b61298957 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/BySmallNumber.md @@ -0,0 +1,9 @@ +# unit_test_api.model.by_small_number.BySmallNumber + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/DateTimeFormat.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/DateTimeFormat.md new file mode 100644 index 0000000000..4dffa18e51 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/DateTimeFormat.md @@ -0,0 +1,9 @@ +# unit_test_api.model.date_time_format.DateTimeFormat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | value must conform to RFC-3339 date-time + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EmailFormat.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EmailFormat.md new file mode 100644 index 0000000000..1a2bb153a2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EmailFormat.md @@ -0,0 +1,9 @@ +# unit_test_api.model.email_format.EmailFormat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWith0DoesNotMatchFalse.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWith0DoesNotMatchFalse.md new file mode 100644 index 0000000000..8acc40f17f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWith0DoesNotMatchFalse.md @@ -0,0 +1,9 @@ +# unit_test_api.model.enum_with0_does_not_match_false.EnumWith0DoesNotMatchFalse + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | must be one of [0, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWith1DoesNotMatchTrue.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWith1DoesNotMatchTrue.md new file mode 100644 index 0000000000..40b4a8a2f5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWith1DoesNotMatchTrue.md @@ -0,0 +1,9 @@ +# unit_test_api.model.enum_with1_does_not_match_true.EnumWith1DoesNotMatchTrue + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | must be one of [1, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWithEscapedCharacters.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWithEscapedCharacters.md new file mode 100644 index 0000000000..7910c5126e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWithEscapedCharacters.md @@ -0,0 +1,9 @@ +# unit_test_api.model.enum_with_escaped_characters.EnumWithEscapedCharacters + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | must be one of ["foo\nbar", "foo\rbar", ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWithFalseDoesNotMatch0.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWithFalseDoesNotMatch0.md new file mode 100644 index 0000000000..19b1b49815 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWithFalseDoesNotMatch0.md @@ -0,0 +1,9 @@ +# unit_test_api.model.enum_with_false_does_not_match0.EnumWithFalseDoesNotMatch0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | must be one of [False, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWithTrueDoesNotMatch1.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWithTrueDoesNotMatch1.md new file mode 100644 index 0000000000..469529fa84 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumWithTrueDoesNotMatch1.md @@ -0,0 +1,9 @@ +# unit_test_api.model.enum_with_true_does_not_match1.EnumWithTrueDoesNotMatch1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | must be one of [True, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumsInProperties.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumsInProperties.md new file mode 100644 index 0000000000..0e08a4a23d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/EnumsInProperties.md @@ -0,0 +1,16 @@ +# unit_test_api.model.enums_in_properties.EnumsInProperties + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**bar** | str, | str, | | must be one of ["bar", ] +**foo** | str, | str, | | [optional] must be one of ["foo", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ForbiddenProperty.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ForbiddenProperty.md new file mode 100644 index 0000000000..3fc2175e9b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ForbiddenProperty.md @@ -0,0 +1,35 @@ +# unit_test_api.model.forbidden_property.ForbiddenProperty + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[foo](#foo)** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# foo + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/HostnameFormat.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/HostnameFormat.md new file mode 100644 index 0000000000..5efd27d124 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/HostnameFormat.md @@ -0,0 +1,9 @@ +# unit_test_api.model.hostname_format.HostnameFormat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/IntegerTypeMatchesIntegers.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/IntegerTypeMatchesIntegers.md new file mode 100644 index 0000000000..2575c1ca53 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/IntegerTypeMatchesIntegers.md @@ -0,0 +1,9 @@ +# unit_test_api.model.integer_type_matches_integers.IntegerTypeMatchesIntegers + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md new file mode 100644 index 0000000000..753345128a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.md @@ -0,0 +1,9 @@ +# unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf.InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/InvalidStringValueForDefault.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/InvalidStringValueForDefault.md new file mode 100644 index 0000000000..296bfd7351 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/InvalidStringValueForDefault.md @@ -0,0 +1,15 @@ +# unit_test_api.model.invalid_string_value_for_default.InvalidStringValueForDefault + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**bar** | str, | str, | | [optional] if omitted the server will use the default value of "bad" +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Ipv4Format.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Ipv4Format.md new file mode 100644 index 0000000000..67ab85c934 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Ipv4Format.md @@ -0,0 +1,9 @@ +# unit_test_api.model.ipv4_format.Ipv4Format + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Ipv6Format.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Ipv6Format.md new file mode 100644 index 0000000000..e2086bee89 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Ipv6Format.md @@ -0,0 +1,9 @@ +# unit_test_api.model.ipv6_format.Ipv6Format + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/JsonPointerFormat.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/JsonPointerFormat.md new file mode 100644 index 0000000000..4067557190 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/JsonPointerFormat.md @@ -0,0 +1,9 @@ +# unit_test_api.model.json_pointer_format.JsonPointerFormat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaximumValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaximumValidation.md new file mode 100644 index 0000000000..826c055762 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaximumValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.maximum_validation.MaximumValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaximumValidationWithUnsignedInteger.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaximumValidationWithUnsignedInteger.md new file mode 100644 index 0000000000..edc23e16bc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaximumValidationWithUnsignedInteger.md @@ -0,0 +1,9 @@ +# unit_test_api.model.maximum_validation_with_unsigned_integer.MaximumValidationWithUnsignedInteger + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaxitemsValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaxitemsValidation.md new file mode 100644 index 0000000000..0aa20c0e8c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaxitemsValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.maxitems_validation.MaxitemsValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaxlengthValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaxlengthValidation.md new file mode 100644 index 0000000000..030db5c34f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaxlengthValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.maxlength_validation.MaxlengthValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Maxproperties0MeansTheObjectIsEmpty.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Maxproperties0MeansTheObjectIsEmpty.md new file mode 100644 index 0000000000..1bbc951f00 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Maxproperties0MeansTheObjectIsEmpty.md @@ -0,0 +1,9 @@ +# unit_test_api.model.maxproperties0_means_the_object_is_empty.Maxproperties0MeansTheObjectIsEmpty + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaxpropertiesValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaxpropertiesValidation.md new file mode 100644 index 0000000000..e68e3d87ad --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MaxpropertiesValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.maxproperties_validation.MaxpropertiesValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinimumValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinimumValidation.md new file mode 100644 index 0000000000..768068c3a6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinimumValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.minimum_validation.MinimumValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinimumValidationWithSignedInteger.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinimumValidationWithSignedInteger.md new file mode 100644 index 0000000000..59d2cb9edf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinimumValidationWithSignedInteger.md @@ -0,0 +1,9 @@ +# unit_test_api.model.minimum_validation_with_signed_integer.MinimumValidationWithSignedInteger + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinitemsValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinitemsValidation.md new file mode 100644 index 0000000000..48bbb8e309 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinitemsValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.minitems_validation.MinitemsValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinlengthValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinlengthValidation.md new file mode 100644 index 0000000000..43ec10fc79 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinlengthValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.minlength_validation.MinlengthValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinpropertiesValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinpropertiesValidation.md new file mode 100644 index 0000000000..b5ab4b4fcb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/MinpropertiesValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.minproperties_validation.MinpropertiesValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ModelNot.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ModelNot.md new file mode 100644 index 0000000000..e7f25eaa6e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ModelNot.md @@ -0,0 +1,22 @@ +# unit_test_api.model.model_not.ModelNot + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | decimal.Decimal, int, | decimal.Decimal, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedAllofToCheckValidationSemantics.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedAllofToCheckValidationSemantics.md new file mode 100644 index 0000000000..c760ab62bf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedAllofToCheckValidationSemantics.md @@ -0,0 +1,35 @@ +# unit_test_api.model.nested_allof_to_check_validation_semantics.NestedAllofToCheckValidationSemantics + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | None, | NoneClass, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedAnyofToCheckValidationSemantics.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedAnyofToCheckValidationSemantics.md new file mode 100644 index 0000000000..747506abdc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedAnyofToCheckValidationSemantics.md @@ -0,0 +1,35 @@ +# unit_test_api.model.nested_anyof_to_check_validation_semantics.NestedAnyofToCheckValidationSemantics + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[any_of_0](#any_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# any_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[any_of_0](#any_of_0) | None, | NoneClass, | | + +# any_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedItems.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedItems.md new file mode 100644 index 0000000000..2247f45f60 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedItems.md @@ -0,0 +1,50 @@ +# unit_test_api.model.nested_items.NestedItems + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | list, tuple, | tuple, | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | list, tuple, | tuple, | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | list, tuple, | tuple, | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | decimal.Decimal, int, float, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedOneofToCheckValidationSemantics.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedOneofToCheckValidationSemantics.md new file mode 100644 index 0000000000..a225e1f676 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NestedOneofToCheckValidationSemantics.md @@ -0,0 +1,35 @@ +# unit_test_api.model.nested_oneof_to_check_validation_semantics.NestedOneofToCheckValidationSemantics + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | None, | NoneClass, | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NotMoreComplexSchema.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NotMoreComplexSchema.md new file mode 100644 index 0000000000..45e198b377 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NotMoreComplexSchema.md @@ -0,0 +1,28 @@ +# unit_test_api.model.not_more_complex_schema.NotMoreComplexSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NulCharactersInStrings.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NulCharactersInStrings.md new file mode 100644 index 0000000000..8532d97c92 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NulCharactersInStrings.md @@ -0,0 +1,9 @@ +# unit_test_api.model.nul_characters_in_strings.NulCharactersInStrings + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | must be one of ["hello\x00there", ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NullTypeMatchesOnlyTheNullObject.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NullTypeMatchesOnlyTheNullObject.md new file mode 100644 index 0000000000..9a8e21c21b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NullTypeMatchesOnlyTheNullObject.md @@ -0,0 +1,9 @@ +# unit_test_api.model.null_type_matches_only_the_null_object.NullTypeMatchesOnlyTheNullObject + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NumberTypeMatchesNumbers.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NumberTypeMatchesNumbers.md new file mode 100644 index 0000000000..deebc8ff56 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/NumberTypeMatchesNumbers.md @@ -0,0 +1,9 @@ +# unit_test_api.model.number_type_matches_numbers.NumberTypeMatchesNumbers + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ObjectPropertiesValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ObjectPropertiesValidation.md new file mode 100644 index 0000000000..9d145f8312 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/ObjectPropertiesValidation.md @@ -0,0 +1,16 @@ +# unit_test_api.model.object_properties_validation.ObjectPropertiesValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | decimal.Decimal, int, | decimal.Decimal, | | [optional] +**bar** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Oneof.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Oneof.md new file mode 100644 index 0000000000..0c056074c4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/Oneof.md @@ -0,0 +1,30 @@ +# unit_test_api.model.oneof.Oneof + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | decimal.Decimal, int, | decimal.Decimal, | | +[one_of_1](#one_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +# one_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofComplexTypes.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofComplexTypes.md new file mode 100644 index 0000000000..57278d6a7e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofComplexTypes.md @@ -0,0 +1,42 @@ +# unit_test_api.model.oneof_complex_types.OneofComplexTypes + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[one_of_1](#one_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**bar** | decimal.Decimal, int, | decimal.Decimal, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# one_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | str, | str, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofWithBaseSchema.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofWithBaseSchema.md new file mode 100644 index 0000000000..20776594f4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofWithBaseSchema.md @@ -0,0 +1,30 @@ +# unit_test_api.model.oneof_with_base_schema.OneofWithBaseSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[one_of_1](#one_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofWithEmptySchema.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofWithEmptySchema.md new file mode 100644 index 0000000000..f420f5c61d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofWithEmptySchema.md @@ -0,0 +1,30 @@ +# unit_test_api.model.oneof_with_empty_schema.OneofWithEmptySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | decimal.Decimal, int, float, | decimal.Decimal, | | +[one_of_1](#one_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +# one_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofWithRequired.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofWithRequired.md new file mode 100644 index 0000000000..e9ba38802c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/OneofWithRequired.md @@ -0,0 +1,30 @@ +# unit_test_api.model.oneof_with_required.OneofWithRequired + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +[one_of_1](#one_of_1) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PatternIsNotAnchored.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PatternIsNotAnchored.md new file mode 100644 index 0000000000..e9b758d826 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PatternIsNotAnchored.md @@ -0,0 +1,9 @@ +# unit_test_api.model.pattern_is_not_anchored.PatternIsNotAnchored + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PatternValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PatternValidation.md new file mode 100644 index 0000000000..a2c7e75f30 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PatternValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.pattern_validation.PatternValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PropertiesWithEscapedCharacters.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PropertiesWithEscapedCharacters.md new file mode 100644 index 0000000000..7505eb4e1c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PropertiesWithEscapedCharacters.md @@ -0,0 +1,20 @@ +# unit_test_api.model.properties_with_escaped_characters.PropertiesWithEscapedCharacters + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo\nbar** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] +**foo\"bar** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] +**foo\\bar** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] +**foo\rbar** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] +**foo\tbar** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] +**foo\fbar** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PropertyNamedRefThatIsNotAReference.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PropertyNamedRefThatIsNotAReference.md new file mode 100644 index 0000000000..4d0ec59257 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/PropertyNamedRefThatIsNotAReference.md @@ -0,0 +1,15 @@ +# unit_test_api.model.property_named_ref_that_is_not_a_reference.PropertyNamedRefThatIsNotAReference + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**$ref** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInAdditionalproperties.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInAdditionalproperties.md new file mode 100644 index 0000000000..15d5366ac5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInAdditionalproperties.md @@ -0,0 +1,14 @@ +# unit_test_api.model.ref_in_additionalproperties.RefInAdditionalproperties + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInAllof.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInAllof.md new file mode 100644 index 0000000000..12158f9e28 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInAllof.md @@ -0,0 +1,15 @@ +# unit_test_api.model.ref_in_allof.RefInAllof + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInAnyof.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInAnyof.md new file mode 100644 index 0000000000..5ff141f69b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInAnyof.md @@ -0,0 +1,15 @@ +# unit_test_api.model.ref_in_anyof.RefInAnyof + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInItems.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInItems.md new file mode 100644 index 0000000000..687a4da176 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInItems.md @@ -0,0 +1,14 @@ +# unit_test_api.model.ref_in_items.RefInItems + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInNot.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInNot.md new file mode 100644 index 0000000000..4414c35841 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInNot.md @@ -0,0 +1,15 @@ +# unit_test_api.model.ref_in_not.RefInNot + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInOneof.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInOneof.md new file mode 100644 index 0000000000..68659fd58a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInOneof.md @@ -0,0 +1,15 @@ +# unit_test_api.model.ref_in_oneof.RefInOneof + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[PropertyNamedRefThatIsNotAReference](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInProperty.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInProperty.md new file mode 100644 index 0000000000..67ac9dd119 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RefInProperty.md @@ -0,0 +1,15 @@ +# unit_test_api.model.ref_in_property.RefInProperty + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**a** | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | [**PropertyNamedRefThatIsNotAReference**](PropertyNamedRefThatIsNotAReference.md) | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredDefaultValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredDefaultValidation.md new file mode 100644 index 0000000000..942d13d264 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredDefaultValidation.md @@ -0,0 +1,15 @@ +# unit_test_api.model.required_default_validation.RequiredDefaultValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredValidation.md new file mode 100644 index 0000000000..0bdb9e6461 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredValidation.md @@ -0,0 +1,16 @@ +# unit_test_api.model.required_validation.RequiredValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | +**bar** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredWithEmptyArray.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredWithEmptyArray.md new file mode 100644 index 0000000000..097a433c64 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredWithEmptyArray.md @@ -0,0 +1,15 @@ +# unit_test_api.model.required_with_empty_array.RequiredWithEmptyArray + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**foo** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredWithEscapedCharacters.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredWithEscapedCharacters.md new file mode 100644 index 0000000000..a89c4b8bf8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/RequiredWithEscapedCharacters.md @@ -0,0 +1,9 @@ +# unit_test_api.model.required_with_escaped_characters.RequiredWithEscapedCharacters + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/SimpleEnumValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/SimpleEnumValidation.md new file mode 100644 index 0000000000..12c0eaf4f8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/SimpleEnumValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.simple_enum_validation.SimpleEnumValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | must be one of [1, 2, 3, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/StringTypeMatchesStrings.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/StringTypeMatchesStrings.md new file mode 100644 index 0000000000..6cee3b4720 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/StringTypeMatchesStrings.md @@ -0,0 +1,9 @@ +# unit_test_api.model.string_type_matches_strings.StringTypeMatchesStrings + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md new file mode 100644 index 0000000000..5d3e500000 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.md @@ -0,0 +1,15 @@ +# unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing.TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**alpha** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] if omitted the server will use the default value of 5 +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UniqueitemsFalseValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UniqueitemsFalseValidation.md new file mode 100644 index 0000000000..f06a22b0be --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UniqueitemsFalseValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.uniqueitems_false_validation.UniqueitemsFalseValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UniqueitemsValidation.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UniqueitemsValidation.md new file mode 100644 index 0000000000..89fe7ce657 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UniqueitemsValidation.md @@ -0,0 +1,9 @@ +# unit_test_api.model.uniqueitems_validation.UniqueitemsValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UriFormat.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UriFormat.md new file mode 100644 index 0000000000..82ee5f3cdb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UriFormat.md @@ -0,0 +1,9 @@ +# unit_test_api.model.uri_format.UriFormat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UriReferenceFormat.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UriReferenceFormat.md new file mode 100644 index 0000000000..c0bdbf8e26 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UriReferenceFormat.md @@ -0,0 +1,9 @@ +# unit_test_api.model.uri_reference_format.UriReferenceFormat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UriTemplateFormat.md b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UriTemplateFormat.md new file mode 100644 index 0000000000..cfb0c0c98d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/docs/models/UriTemplateFormat.md @@ -0,0 +1,9 @@ +# unit_test_api.model.uri_template_format.UriTemplateFormat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/rust/hyper/fileResponseTest/git_push.sh b/samples/openapi3/client/3_0_3_unit_test/python/git_push.sh similarity index 100% rename from samples/client/petstore/rust/hyper/fileResponseTest/git_push.sh rename to samples/openapi3/client/3_0_3_unit_test/python/git_push.sh diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/pom.xml b/samples/openapi3/client/3_0_3_unit_test/python/pom.xml similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/pom.xml rename to samples/openapi3/client/3_0_3_unit_test/python/pom.xml diff --git a/samples/openapi3/client/3_0_3_unit_test/python/requirements.txt b/samples/openapi3/client/3_0_3_unit_test/python/requirements.txt new file mode 100644 index 0000000000..3cb6612669 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/requirements.txt @@ -0,0 +1,6 @@ +certifi >= 14.5.14 +frozendict ~= 2.3.4 +python-dateutil ~= 2.7.0 +setuptools >= 21.0.0 +typing_extensions ~= 4.3.0 +urllib3 ~= 1.26.7 diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/setup.cfg b/samples/openapi3/client/3_0_3_unit_test/python/setup.cfg similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/setup.cfg rename to samples/openapi3/client/3_0_3_unit_test/python/setup.cfg diff --git a/samples/openapi3/client/3_0_3_unit_test/python/setup.py b/samples/openapi3/client/3_0_3_unit_test/python/setup.py new file mode 100644 index 0000000000..1fc837120c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/setup.py @@ -0,0 +1,47 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from setuptools import setup, find_packages # noqa: H301 + +NAME = "unit-test-api" +VERSION = "1.0.0" +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = [ + "certifi >= 14.5.14", + "frozendict ~= 2.3.4", + "python-dateutil ~= 2.7.0", + "setuptools >= 21.0.0", + "typing_extensions ~= 4.3.0", + "urllib3 ~= 1.26.7", +] + +setup( + name=NAME, + version=VERSION, + description="openapi 3.0.3 sample spec", + author="OpenAPI Generator community", + author_email="team@openapitools.org", + url="", + keywords=["OpenAPI", "OpenAPI-Generator", "openapi 3.0.3 sample spec"], + python_requires=">=3.7", + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + long_description="""\ + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + """ +) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test-requirements.txt b/samples/openapi3/client/3_0_3_unit_test/python/test-requirements.txt similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test-requirements.txt rename to samples/openapi3/client/3_0_3_unit_test/python/test-requirements.txt diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/__init__.py similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/__init__.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/__init__.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/api/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/__init__.py similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/api/__init__.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/__init__.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_allows_a_schema_which_should_validate.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_allows_a_schema_which_should_validate.py similarity index 90% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_allows_a_schema_which_should_validate.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_allows_a_schema_which_should_validate.py index 9d9c82d710..b946a7840f 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_allows_a_schema_which_should_validate.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_allows_a_schema_which_should_validate.py @@ -22,7 +22,7 @@ class TestAdditionalpropertiesAllowsASchemaWhichShouldValidate(unittest.TestCase def test_no_additional_properties_is_valid_passes(self): # no additional properties is valid - AdditionalpropertiesAllowsASchemaWhichShouldValidate._from_openapi_data( + AdditionalpropertiesAllowsASchemaWhichShouldValidate.from_openapi_data_oapg( { "foo": 1, @@ -33,7 +33,7 @@ class TestAdditionalpropertiesAllowsASchemaWhichShouldValidate(unittest.TestCase def test_an_additional_invalid_property_is_invalid_fails(self): # an additional invalid property is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AdditionalpropertiesAllowsASchemaWhichShouldValidate._from_openapi_data( + AdditionalpropertiesAllowsASchemaWhichShouldValidate.from_openapi_data_oapg( { "foo": 1, @@ -47,7 +47,7 @@ class TestAdditionalpropertiesAllowsASchemaWhichShouldValidate(unittest.TestCase def test_an_additional_valid_property_is_valid_passes(self): # an additional valid property is valid - AdditionalpropertiesAllowsASchemaWhichShouldValidate._from_openapi_data( + AdditionalpropertiesAllowsASchemaWhichShouldValidate.from_openapi_data_oapg( { "foo": 1, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_are_allowed_by_default.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_are_allowed_by_default.py similarity index 93% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_are_allowed_by_default.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_are_allowed_by_default.py index e52b193fdb..ede7b00650 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_are_allowed_by_default.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_are_allowed_by_default.py @@ -22,7 +22,7 @@ class TestAdditionalpropertiesAreAllowedByDefault(unittest.TestCase): def test_additional_properties_are_allowed_passes(self): # additional properties are allowed - AdditionalpropertiesAreAllowedByDefault._from_openapi_data( + AdditionalpropertiesAreAllowedByDefault.from_openapi_data_oapg( { "foo": 1, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_can_exist_by_itself.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_can_exist_by_itself.py similarity index 90% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_can_exist_by_itself.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_can_exist_by_itself.py index 3a6473f23b..fd4c4b4e9f 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_additionalproperties_can_exist_by_itself.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_can_exist_by_itself.py @@ -23,7 +23,7 @@ class TestAdditionalpropertiesCanExistByItself(unittest.TestCase): def test_an_additional_invalid_property_is_invalid_fails(self): # an additional invalid property is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AdditionalpropertiesCanExistByItself._from_openapi_data( + AdditionalpropertiesCanExistByItself.from_openapi_data_oapg( { "foo": 1, @@ -33,7 +33,7 @@ class TestAdditionalpropertiesCanExistByItself(unittest.TestCase): def test_an_additional_valid_property_is_valid_passes(self): # an additional valid property is valid - AdditionalpropertiesCanExistByItself._from_openapi_data( + AdditionalpropertiesCanExistByItself.from_openapi_data_oapg( { "foo": True, diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_should_not_look_in_applicators.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_should_not_look_in_applicators.py new file mode 100644 index 0000000000..cc08697897 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_additionalproperties_should_not_look_in_applicators.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import unit_test_api +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from unit_test_api import configuration + + +class TestAdditionalpropertiesShouldNotLookInApplicators(unittest.TestCase): + """AdditionalpropertiesShouldNotLookInApplicators unit test stubs""" + _configuration = configuration.Configuration() + + def test_properties_defined_in_allof_are_not_examined_fails(self): + # properties defined in allOf are not examined + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + AdditionalpropertiesShouldNotLookInApplicators.from_openapi_data_oapg( + { + "foo": + 1, + "bar": + True, + }, + _configuration=self._configuration + ) + + def test_valid_test_case_passes(self): + # valid test case + AdditionalpropertiesShouldNotLookInApplicators.from_openapi_data_oapg( + { + "foo": + False, + "bar": + True, + }, + _configuration=self._configuration + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof.py similarity index 91% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof.py index 9337a2edd4..d03edae4b7 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof.py @@ -22,7 +22,7 @@ class TestAllof(unittest.TestCase): def test_allof_passes(self): # allOf - Allof._from_openapi_data( + Allof.from_openapi_data_oapg( { "foo": "baz", @@ -35,7 +35,7 @@ class TestAllof(unittest.TestCase): def test_mismatch_first_fails(self): # mismatch first with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - Allof._from_openapi_data( + Allof.from_openapi_data_oapg( { "bar": 2, @@ -46,7 +46,7 @@ class TestAllof(unittest.TestCase): def test_mismatch_second_fails(self): # mismatch second with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - Allof._from_openapi_data( + Allof.from_openapi_data_oapg( { "foo": "baz", @@ -57,7 +57,7 @@ class TestAllof(unittest.TestCase): def test_wrong_type_fails(self): # wrong type with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - Allof._from_openapi_data( + Allof.from_openapi_data_oapg( { "foo": "baz", diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_combined_with_anyof_oneof.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_combined_with_anyof_oneof.py similarity index 84% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_combined_with_anyof_oneof.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_combined_with_anyof_oneof.py index 56a76b5d05..f1875ccfff 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_combined_with_anyof_oneof.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_combined_with_anyof_oneof.py @@ -23,7 +23,7 @@ class TestAllofCombinedWithAnyofOneof(unittest.TestCase): def test_allof_true_anyof_false_oneof_false_fails(self): # allOf: true, anyOf: false, oneOf: false with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofCombinedWithAnyofOneof._from_openapi_data( + AllofCombinedWithAnyofOneof.from_openapi_data_oapg( 2, _configuration=self._configuration ) @@ -31,7 +31,7 @@ class TestAllofCombinedWithAnyofOneof(unittest.TestCase): def test_allof_false_anyof_false_oneof_true_fails(self): # allOf: false, anyOf: false, oneOf: true with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofCombinedWithAnyofOneof._from_openapi_data( + AllofCombinedWithAnyofOneof.from_openapi_data_oapg( 5, _configuration=self._configuration ) @@ -39,7 +39,7 @@ class TestAllofCombinedWithAnyofOneof(unittest.TestCase): def test_allof_false_anyof_true_oneof_true_fails(self): # allOf: false, anyOf: true, oneOf: true with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofCombinedWithAnyofOneof._from_openapi_data( + AllofCombinedWithAnyofOneof.from_openapi_data_oapg( 15, _configuration=self._configuration ) @@ -47,14 +47,14 @@ class TestAllofCombinedWithAnyofOneof(unittest.TestCase): def test_allof_true_anyof_true_oneof_false_fails(self): # allOf: true, anyOf: true, oneOf: false with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofCombinedWithAnyofOneof._from_openapi_data( + AllofCombinedWithAnyofOneof.from_openapi_data_oapg( 6, _configuration=self._configuration ) def test_allof_true_anyof_true_oneof_true_passes(self): # allOf: true, anyOf: true, oneOf: true - AllofCombinedWithAnyofOneof._from_openapi_data( + AllofCombinedWithAnyofOneof.from_openapi_data_oapg( 30, _configuration=self._configuration ) @@ -62,7 +62,7 @@ class TestAllofCombinedWithAnyofOneof(unittest.TestCase): def test_allof_true_anyof_false_oneof_true_fails(self): # allOf: true, anyOf: false, oneOf: true with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofCombinedWithAnyofOneof._from_openapi_data( + AllofCombinedWithAnyofOneof.from_openapi_data_oapg( 10, _configuration=self._configuration ) @@ -70,7 +70,7 @@ class TestAllofCombinedWithAnyofOneof(unittest.TestCase): def test_allof_false_anyof_true_oneof_false_fails(self): # allOf: false, anyOf: true, oneOf: false with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofCombinedWithAnyofOneof._from_openapi_data( + AllofCombinedWithAnyofOneof.from_openapi_data_oapg( 3, _configuration=self._configuration ) @@ -78,7 +78,7 @@ class TestAllofCombinedWithAnyofOneof(unittest.TestCase): def test_allof_false_anyof_false_oneof_false_fails(self): # allOf: false, anyOf: false, oneOf: false with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofCombinedWithAnyofOneof._from_openapi_data( + AllofCombinedWithAnyofOneof.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_simple_types.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_simple_types.py similarity index 90% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_simple_types.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_simple_types.py index db0c8b5b52..7f35109890 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_simple_types.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_simple_types.py @@ -22,7 +22,7 @@ class TestAllofSimpleTypes(unittest.TestCase): def test_valid_passes(self): # valid - AllofSimpleTypes._from_openapi_data( + AllofSimpleTypes.from_openapi_data_oapg( 25, _configuration=self._configuration ) @@ -30,7 +30,7 @@ class TestAllofSimpleTypes(unittest.TestCase): def test_mismatch_one_fails(self): # mismatch one with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofSimpleTypes._from_openapi_data( + AllofSimpleTypes.from_openapi_data_oapg( 35, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_base_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_base_schema.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_base_schema.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_base_schema.py index f9922161cb..f089c4a39f 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_base_schema.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_base_schema.py @@ -22,7 +22,7 @@ class TestAllofWithBaseSchema(unittest.TestCase): def test_valid_passes(self): # valid - AllofWithBaseSchema._from_openapi_data( + AllofWithBaseSchema.from_openapi_data_oapg( { "foo": "quux", @@ -37,7 +37,7 @@ class TestAllofWithBaseSchema(unittest.TestCase): def test_mismatch_first_allof_fails(self): # mismatch first allOf with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofWithBaseSchema._from_openapi_data( + AllofWithBaseSchema.from_openapi_data_oapg( { "bar": 2, @@ -50,7 +50,7 @@ class TestAllofWithBaseSchema(unittest.TestCase): def test_mismatch_base_schema_fails(self): # mismatch base schema with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofWithBaseSchema._from_openapi_data( + AllofWithBaseSchema.from_openapi_data_oapg( { "foo": "quux", @@ -63,7 +63,7 @@ class TestAllofWithBaseSchema(unittest.TestCase): def test_mismatch_both_fails(self): # mismatch both with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofWithBaseSchema._from_openapi_data( + AllofWithBaseSchema.from_openapi_data_oapg( { "bar": 2, @@ -74,7 +74,7 @@ class TestAllofWithBaseSchema(unittest.TestCase): def test_mismatch_second_allof_fails(self): # mismatch second allOf with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofWithBaseSchema._from_openapi_data( + AllofWithBaseSchema.from_openapi_data_oapg( { "foo": "quux", diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_one_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_one_empty_schema.py similarity index 93% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_one_empty_schema.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_one_empty_schema.py index ac60d40856..f3eee78309 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_one_empty_schema.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_one_empty_schema.py @@ -22,7 +22,7 @@ class TestAllofWithOneEmptySchema(unittest.TestCase): def test_any_data_is_valid_passes(self): # any data is valid - AllofWithOneEmptySchema._from_openapi_data( + AllofWithOneEmptySchema.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_the_first_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_the_first_empty_schema.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_the_first_empty_schema.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_the_first_empty_schema.py index 5dacdfb979..f30ef23cb2 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_the_first_empty_schema.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_the_first_empty_schema.py @@ -23,14 +23,14 @@ class TestAllofWithTheFirstEmptySchema(unittest.TestCase): def test_string_is_invalid_fails(self): # string is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofWithTheFirstEmptySchema._from_openapi_data( + AllofWithTheFirstEmptySchema.from_openapi_data_oapg( "foo", _configuration=self._configuration ) def test_number_is_valid_passes(self): # number is valid - AllofWithTheFirstEmptySchema._from_openapi_data( + AllofWithTheFirstEmptySchema.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_the_last_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_the_last_empty_schema.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_the_last_empty_schema.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_the_last_empty_schema.py index bd425c3147..94e0a662c1 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_the_last_empty_schema.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_the_last_empty_schema.py @@ -23,14 +23,14 @@ class TestAllofWithTheLastEmptySchema(unittest.TestCase): def test_string_is_invalid_fails(self): # string is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AllofWithTheLastEmptySchema._from_openapi_data( + AllofWithTheLastEmptySchema.from_openapi_data_oapg( "foo", _configuration=self._configuration ) def test_number_is_valid_passes(self): # number is valid - AllofWithTheLastEmptySchema._from_openapi_data( + AllofWithTheLastEmptySchema.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_two_empty_schemas.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_two_empty_schemas.py similarity index 93% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_two_empty_schemas.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_two_empty_schemas.py index 45356cece7..db5b6fa9ca 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_allof_with_two_empty_schemas.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_allof_with_two_empty_schemas.py @@ -22,7 +22,7 @@ class TestAllofWithTwoEmptySchemas(unittest.TestCase): def test_any_data_is_valid_passes(self): # any data is valid - AllofWithTwoEmptySchemas._from_openapi_data( + AllofWithTwoEmptySchemas.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof.py similarity index 88% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof.py index 197c3449a9..d300d967d0 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof.py @@ -22,7 +22,7 @@ class TestAnyof(unittest.TestCase): def test_second_anyof_valid_passes(self): # second anyOf valid - Anyof._from_openapi_data( + Anyof.from_openapi_data_oapg( 2.5, _configuration=self._configuration ) @@ -30,21 +30,21 @@ class TestAnyof(unittest.TestCase): def test_neither_anyof_valid_fails(self): # neither anyOf valid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - Anyof._from_openapi_data( + Anyof.from_openapi_data_oapg( 1.5, _configuration=self._configuration ) def test_both_anyof_valid_passes(self): # both anyOf valid - Anyof._from_openapi_data( + Anyof.from_openapi_data_oapg( 3, _configuration=self._configuration ) def test_first_anyof_valid_passes(self): # first anyOf valid - Anyof._from_openapi_data( + Anyof.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof_complex_types.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof_complex_types.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof_complex_types.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof_complex_types.py index eeb533e619..fc6d14191d 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof_complex_types.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof_complex_types.py @@ -22,7 +22,7 @@ class TestAnyofComplexTypes(unittest.TestCase): def test_second_anyof_valid_complex_passes(self): # second anyOf valid (complex) - AnyofComplexTypes._from_openapi_data( + AnyofComplexTypes.from_openapi_data_oapg( { "foo": "baz", @@ -33,7 +33,7 @@ class TestAnyofComplexTypes(unittest.TestCase): def test_neither_anyof_valid_complex_fails(self): # neither anyOf valid (complex) with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AnyofComplexTypes._from_openapi_data( + AnyofComplexTypes.from_openapi_data_oapg( { "foo": 2, @@ -45,7 +45,7 @@ class TestAnyofComplexTypes(unittest.TestCase): def test_both_anyof_valid_complex_passes(self): # both anyOf valid (complex) - AnyofComplexTypes._from_openapi_data( + AnyofComplexTypes.from_openapi_data_oapg( { "foo": "baz", @@ -57,7 +57,7 @@ class TestAnyofComplexTypes(unittest.TestCase): def test_first_anyof_valid_complex_passes(self): # first anyOf valid (complex) - AnyofComplexTypes._from_openapi_data( + AnyofComplexTypes.from_openapi_data_oapg( { "bar": 2, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof_with_base_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof_with_base_schema.py similarity index 88% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof_with_base_schema.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof_with_base_schema.py index 96e03720d6..7edf767ad5 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof_with_base_schema.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof_with_base_schema.py @@ -22,7 +22,7 @@ class TestAnyofWithBaseSchema(unittest.TestCase): def test_one_anyof_valid_passes(self): # one anyOf valid - AnyofWithBaseSchema._from_openapi_data( + AnyofWithBaseSchema.from_openapi_data_oapg( "foobar", _configuration=self._configuration ) @@ -30,7 +30,7 @@ class TestAnyofWithBaseSchema(unittest.TestCase): def test_both_anyof_invalid_fails(self): # both anyOf invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AnyofWithBaseSchema._from_openapi_data( + AnyofWithBaseSchema.from_openapi_data_oapg( "foo", _configuration=self._configuration ) @@ -38,7 +38,7 @@ class TestAnyofWithBaseSchema(unittest.TestCase): def test_mismatch_base_schema_fails(self): # mismatch base schema with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - AnyofWithBaseSchema._from_openapi_data( + AnyofWithBaseSchema.from_openapi_data_oapg( 3, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof_with_one_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof_with_one_empty_schema.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof_with_one_empty_schema.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof_with_one_empty_schema.py index dcb2c0ea80..31cc78ca3c 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_anyof_with_one_empty_schema.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_anyof_with_one_empty_schema.py @@ -22,14 +22,14 @@ class TestAnyofWithOneEmptySchema(unittest.TestCase): def test_string_is_valid_passes(self): # string is valid - AnyofWithOneEmptySchema._from_openapi_data( + AnyofWithOneEmptySchema.from_openapi_data_oapg( "foo", _configuration=self._configuration ) def test_number_is_valid_passes(self): # number is valid - AnyofWithOneEmptySchema._from_openapi_data( + AnyofWithOneEmptySchema.from_openapi_data_oapg( 123, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_array_type_matches_arrays.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_array_type_matches_arrays.py similarity index 85% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_array_type_matches_arrays.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_array_type_matches_arrays.py index b8bc156e18..98fbd44a16 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_array_type_matches_arrays.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_array_type_matches_arrays.py @@ -23,7 +23,7 @@ class TestArrayTypeMatchesArrays(unittest.TestCase): def test_a_float_is_not_an_array_fails(self): # a float is not an array with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ArrayTypeMatchesArrays._from_openapi_data( + ArrayTypeMatchesArrays.from_openapi_data_oapg( 1.1, _configuration=self._configuration ) @@ -31,7 +31,7 @@ class TestArrayTypeMatchesArrays(unittest.TestCase): def test_a_boolean_is_not_an_array_fails(self): # a boolean is not an array with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ArrayTypeMatchesArrays._from_openapi_data( + ArrayTypeMatchesArrays.from_openapi_data_oapg( True, _configuration=self._configuration ) @@ -39,7 +39,7 @@ class TestArrayTypeMatchesArrays(unittest.TestCase): def test_null_is_not_an_array_fails(self): # null is not an array with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ArrayTypeMatchesArrays._from_openapi_data( + ArrayTypeMatchesArrays.from_openapi_data_oapg( None, _configuration=self._configuration ) @@ -47,7 +47,7 @@ class TestArrayTypeMatchesArrays(unittest.TestCase): def test_an_object_is_not_an_array_fails(self): # an object is not an array with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ArrayTypeMatchesArrays._from_openapi_data( + ArrayTypeMatchesArrays.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -56,14 +56,14 @@ class TestArrayTypeMatchesArrays(unittest.TestCase): def test_a_string_is_not_an_array_fails(self): # a string is not an array with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ArrayTypeMatchesArrays._from_openapi_data( + ArrayTypeMatchesArrays.from_openapi_data_oapg( "foo", _configuration=self._configuration ) def test_an_array_is_an_array_passes(self): # an array is an array - ArrayTypeMatchesArrays._from_openapi_data( + ArrayTypeMatchesArrays.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -72,7 +72,7 @@ class TestArrayTypeMatchesArrays(unittest.TestCase): def test_an_integer_is_not_an_array_fails(self): # an integer is not an array with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ArrayTypeMatchesArrays._from_openapi_data( + ArrayTypeMatchesArrays.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_boolean_type_matches_booleans.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_boolean_type_matches_booleans.py similarity index 83% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_boolean_type_matches_booleans.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_boolean_type_matches_booleans.py index 3ffb73ed95..fc20c8059d 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_boolean_type_matches_booleans.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_boolean_type_matches_booleans.py @@ -23,7 +23,7 @@ class TestBooleanTypeMatchesBooleans(unittest.TestCase): def test_an_empty_string_is_not_a_boolean_fails(self): # an empty string is not a boolean with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( "", _configuration=self._configuration ) @@ -31,7 +31,7 @@ class TestBooleanTypeMatchesBooleans(unittest.TestCase): def test_a_float_is_not_a_boolean_fails(self): # a float is not a boolean with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( 1.1, _configuration=self._configuration ) @@ -39,7 +39,7 @@ class TestBooleanTypeMatchesBooleans(unittest.TestCase): def test_null_is_not_a_boolean_fails(self): # null is not a boolean with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( None, _configuration=self._configuration ) @@ -47,7 +47,7 @@ class TestBooleanTypeMatchesBooleans(unittest.TestCase): def test_zero_is_not_a_boolean_fails(self): # zero is not a boolean with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( 0, _configuration=self._configuration ) @@ -55,7 +55,7 @@ class TestBooleanTypeMatchesBooleans(unittest.TestCase): def test_an_array_is_not_a_boolean_fails(self): # an array is not a boolean with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -64,14 +64,14 @@ class TestBooleanTypeMatchesBooleans(unittest.TestCase): def test_a_string_is_not_a_boolean_fails(self): # a string is not a boolean with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( "foo", _configuration=self._configuration ) def test_false_is_a_boolean_passes(self): # false is a boolean - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( False, _configuration=self._configuration ) @@ -79,14 +79,14 @@ class TestBooleanTypeMatchesBooleans(unittest.TestCase): def test_an_integer_is_not_a_boolean_fails(self): # an integer is not a boolean with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( 1, _configuration=self._configuration ) def test_true_is_a_boolean_passes(self): # true is a boolean - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( True, _configuration=self._configuration ) @@ -94,7 +94,7 @@ class TestBooleanTypeMatchesBooleans(unittest.TestCase): def test_an_object_is_not_a_boolean_fails(self): # an object is not a boolean with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - BooleanTypeMatchesBooleans._from_openapi_data( + BooleanTypeMatchesBooleans.from_openapi_data_oapg( { }, _configuration=self._configuration diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_by_int.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_by_int.py similarity index 90% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_by_int.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_by_int.py index 26254a7aaa..4abbab69a5 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_by_int.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_by_int.py @@ -23,21 +23,21 @@ class TestByInt(unittest.TestCase): def test_int_by_int_fail_fails(self): # int by int fail with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ByInt._from_openapi_data( + ByInt.from_openapi_data_oapg( 7, _configuration=self._configuration ) def test_int_by_int_passes(self): # int by int - ByInt._from_openapi_data( + ByInt.from_openapi_data_oapg( 10, _configuration=self._configuration ) def test_ignores_non_numbers_passes(self): # ignores non-numbers - ByInt._from_openapi_data( + ByInt.from_openapi_data_oapg( "foo", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_by_number.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_by_number.py similarity index 90% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_by_number.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_by_number.py index 928b8f3c64..9614cc470d 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_by_number.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_by_number.py @@ -22,7 +22,7 @@ class TestByNumber(unittest.TestCase): def test_45_is_multiple_of15_passes(self): # 4.5 is multiple of 1.5 - ByNumber._from_openapi_data( + ByNumber.from_openapi_data_oapg( 4.5, _configuration=self._configuration ) @@ -30,14 +30,14 @@ class TestByNumber(unittest.TestCase): def test_35_is_not_multiple_of15_fails(self): # 35 is not multiple of 1.5 with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ByNumber._from_openapi_data( + ByNumber.from_openapi_data_oapg( 35, _configuration=self._configuration ) def test_zero_is_multiple_of_anything_passes(self): # zero is multiple of anything - ByNumber._from_openapi_data( + ByNumber.from_openapi_data_oapg( 0, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_by_small_number.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_by_small_number.py similarity index 91% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_by_small_number.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_by_small_number.py index cc683feebe..3a4e1449ca 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_by_small_number.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_by_small_number.py @@ -23,14 +23,14 @@ class TestBySmallNumber(unittest.TestCase): def test_000751_is_not_multiple_of00001_fails(self): # 0.00751 is not multiple of 0.0001 with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - BySmallNumber._from_openapi_data( + BySmallNumber.from_openapi_data_oapg( 0.00751, _configuration=self._configuration ) def test_00075_is_multiple_of00001_passes(self): # 0.0075 is multiple of 0.0001 - BySmallNumber._from_openapi_data( + BySmallNumber.from_openapi_data_oapg( 0.0075, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_date_time_format.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_date_time_format.py similarity index 85% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_date_time_format.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_date_time_format.py index b3a2b15437..1fdd3e3614 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_date_time_format.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_date_time_format.py @@ -22,7 +22,7 @@ class TestDateTimeFormat(unittest.TestCase): def test_all_string_formats_ignore_objects_passes(self): # all string formats ignore objects - DateTimeFormat._from_openapi_data( + DateTimeFormat.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,28 +30,28 @@ class TestDateTimeFormat(unittest.TestCase): def test_all_string_formats_ignore_booleans_passes(self): # all string formats ignore booleans - DateTimeFormat._from_openapi_data( + DateTimeFormat.from_openapi_data_oapg( False, _configuration=self._configuration ) def test_all_string_formats_ignore_integers_passes(self): # all string formats ignore integers - DateTimeFormat._from_openapi_data( + DateTimeFormat.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_all_string_formats_ignore_floats_passes(self): # all string formats ignore floats - DateTimeFormat._from_openapi_data( + DateTimeFormat.from_openapi_data_oapg( 13.7, _configuration=self._configuration ) def test_all_string_formats_ignore_arrays_passes(self): # all string formats ignore arrays - DateTimeFormat._from_openapi_data( + DateTimeFormat.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -59,7 +59,7 @@ class TestDateTimeFormat(unittest.TestCase): def test_all_string_formats_ignore_nulls_passes(self): # all string formats ignore nulls - DateTimeFormat._from_openapi_data( + DateTimeFormat.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_email_format.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_email_format.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_email_format.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_email_format.py index c6b2d51c19..830b136aae 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_email_format.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_email_format.py @@ -22,7 +22,7 @@ class TestEmailFormat(unittest.TestCase): def test_all_string_formats_ignore_objects_passes(self): # all string formats ignore objects - EmailFormat._from_openapi_data( + EmailFormat.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,28 +30,28 @@ class TestEmailFormat(unittest.TestCase): def test_all_string_formats_ignore_booleans_passes(self): # all string formats ignore booleans - EmailFormat._from_openapi_data( + EmailFormat.from_openapi_data_oapg( False, _configuration=self._configuration ) def test_all_string_formats_ignore_integers_passes(self): # all string formats ignore integers - EmailFormat._from_openapi_data( + EmailFormat.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_all_string_formats_ignore_floats_passes(self): # all string formats ignore floats - EmailFormat._from_openapi_data( + EmailFormat.from_openapi_data_oapg( 13.7, _configuration=self._configuration ) def test_all_string_formats_ignore_arrays_passes(self): # all string formats ignore arrays - EmailFormat._from_openapi_data( + EmailFormat.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -59,7 +59,7 @@ class TestEmailFormat(unittest.TestCase): def test_all_string_formats_ignore_nulls_passes(self): # all string formats ignore nulls - EmailFormat._from_openapi_data( + EmailFormat.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with0_does_not_match_false.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with0_does_not_match_false.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with0_does_not_match_false.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with0_does_not_match_false.py index f2917a571b..5456b86202 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with0_does_not_match_false.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with0_does_not_match_false.py @@ -22,14 +22,14 @@ class TestEnumWith0DoesNotMatchFalse(unittest.TestCase): def test_integer_zero_is_valid_passes(self): # integer zero is valid - EnumWith0DoesNotMatchFalse._from_openapi_data( + EnumWith0DoesNotMatchFalse.from_openapi_data_oapg( 0, _configuration=self._configuration ) def test_float_zero_is_valid_passes(self): # float zero is valid - EnumWith0DoesNotMatchFalse._from_openapi_data( + EnumWith0DoesNotMatchFalse.from_openapi_data_oapg( 0.0, _configuration=self._configuration ) @@ -37,7 +37,7 @@ class TestEnumWith0DoesNotMatchFalse(unittest.TestCase): def test_false_is_invalid_fails(self): # false is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumWith0DoesNotMatchFalse._from_openapi_data( + EnumWith0DoesNotMatchFalse.from_openapi_data_oapg( False, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with1_does_not_match_true.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with1_does_not_match_true.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with1_does_not_match_true.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with1_does_not_match_true.py index 8b49818076..e9a97663fe 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with1_does_not_match_true.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with1_does_not_match_true.py @@ -23,21 +23,21 @@ class TestEnumWith1DoesNotMatchTrue(unittest.TestCase): def test_true_is_invalid_fails(self): # true is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumWith1DoesNotMatchTrue._from_openapi_data( + EnumWith1DoesNotMatchTrue.from_openapi_data_oapg( True, _configuration=self._configuration ) def test_integer_one_is_valid_passes(self): # integer one is valid - EnumWith1DoesNotMatchTrue._from_openapi_data( + EnumWith1DoesNotMatchTrue.from_openapi_data_oapg( 1, _configuration=self._configuration ) def test_float_one_is_valid_passes(self): # float one is valid - EnumWith1DoesNotMatchTrue._from_openapi_data( + EnumWith1DoesNotMatchTrue.from_openapi_data_oapg( 1.0, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with_escaped_characters.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with_escaped_characters.py similarity index 87% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with_escaped_characters.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with_escaped_characters.py index 658588f2b0..4144f3b77d 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with_escaped_characters.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with_escaped_characters.py @@ -22,14 +22,14 @@ class TestEnumWithEscapedCharacters(unittest.TestCase): def test_member2_is_valid_passes(self): # member 2 is valid - EnumWithEscapedCharacters._from_openapi_data( + EnumWithEscapedCharacters.from_openapi_data_oapg( "foo\rbar", _configuration=self._configuration ) def test_member1_is_valid_passes(self): # member 1 is valid - EnumWithEscapedCharacters._from_openapi_data( + EnumWithEscapedCharacters.from_openapi_data_oapg( "foo\nbar", _configuration=self._configuration ) @@ -37,7 +37,7 @@ class TestEnumWithEscapedCharacters(unittest.TestCase): def test_another_string_is_invalid_fails(self): # another string is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumWithEscapedCharacters._from_openapi_data( + EnumWithEscapedCharacters.from_openapi_data_oapg( "abc", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with_false_does_not_match0.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with_false_does_not_match0.py similarity index 87% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with_false_does_not_match0.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with_false_does_not_match0.py index c62d5f7909..ebd6bc55d4 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with_false_does_not_match0.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with_false_does_not_match0.py @@ -22,7 +22,7 @@ class TestEnumWithFalseDoesNotMatch0(unittest.TestCase): def test_false_is_valid_passes(self): # false is valid - EnumWithFalseDoesNotMatch0._from_openapi_data( + EnumWithFalseDoesNotMatch0.from_openapi_data_oapg( False, _configuration=self._configuration ) @@ -30,7 +30,7 @@ class TestEnumWithFalseDoesNotMatch0(unittest.TestCase): def test_float_zero_is_invalid_fails(self): # float zero is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumWithFalseDoesNotMatch0._from_openapi_data( + EnumWithFalseDoesNotMatch0.from_openapi_data_oapg( 0.0, _configuration=self._configuration ) @@ -38,7 +38,7 @@ class TestEnumWithFalseDoesNotMatch0(unittest.TestCase): def test_integer_zero_is_invalid_fails(self): # integer zero is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumWithFalseDoesNotMatch0._from_openapi_data( + EnumWithFalseDoesNotMatch0.from_openapi_data_oapg( 0, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with_true_does_not_match1.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with_true_does_not_match1.py similarity index 87% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with_true_does_not_match1.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with_true_does_not_match1.py index 9339856f4f..7827ca725b 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enum_with_true_does_not_match1.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enum_with_true_does_not_match1.py @@ -23,14 +23,14 @@ class TestEnumWithTrueDoesNotMatch1(unittest.TestCase): def test_float_one_is_invalid_fails(self): # float one is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumWithTrueDoesNotMatch1._from_openapi_data( + EnumWithTrueDoesNotMatch1.from_openapi_data_oapg( 1.0, _configuration=self._configuration ) def test_true_is_valid_passes(self): # true is valid - EnumWithTrueDoesNotMatch1._from_openapi_data( + EnumWithTrueDoesNotMatch1.from_openapi_data_oapg( True, _configuration=self._configuration ) @@ -38,7 +38,7 @@ class TestEnumWithTrueDoesNotMatch1(unittest.TestCase): def test_integer_one_is_invalid_fails(self): # integer one is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumWithTrueDoesNotMatch1._from_openapi_data( + EnumWithTrueDoesNotMatch1.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enums_in_properties.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enums_in_properties.py similarity index 88% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enums_in_properties.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enums_in_properties.py index 87c5112a3f..3850f849db 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_enums_in_properties.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_enums_in_properties.py @@ -22,7 +22,7 @@ class TestEnumsInProperties(unittest.TestCase): def test_missing_optional_property_is_valid_passes(self): # missing optional property is valid - EnumsInProperties._from_openapi_data( + EnumsInProperties.from_openapi_data_oapg( { "bar": "bar", @@ -33,7 +33,7 @@ class TestEnumsInProperties(unittest.TestCase): def test_wrong_foo_value_fails(self): # wrong foo value with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumsInProperties._from_openapi_data( + EnumsInProperties.from_openapi_data_oapg( { "foo": "foot", @@ -45,7 +45,7 @@ class TestEnumsInProperties(unittest.TestCase): def test_both_properties_are_valid_passes(self): # both properties are valid - EnumsInProperties._from_openapi_data( + EnumsInProperties.from_openapi_data_oapg( { "foo": "foo", @@ -58,7 +58,7 @@ class TestEnumsInProperties(unittest.TestCase): def test_wrong_bar_value_fails(self): # wrong bar value with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumsInProperties._from_openapi_data( + EnumsInProperties.from_openapi_data_oapg( { "foo": "foo", @@ -71,7 +71,7 @@ class TestEnumsInProperties(unittest.TestCase): def test_missing_all_properties_is_invalid_fails(self): # missing all properties is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumsInProperties._from_openapi_data( + EnumsInProperties.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -80,7 +80,7 @@ class TestEnumsInProperties(unittest.TestCase): def test_missing_required_property_is_invalid_fails(self): # missing required property is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - EnumsInProperties._from_openapi_data( + EnumsInProperties.from_openapi_data_oapg( { "foo": "foo", diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_forbidden_property.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_forbidden_property.py similarity index 92% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_forbidden_property.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_forbidden_property.py index b48d39902f..f1db3521b1 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_forbidden_property.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_forbidden_property.py @@ -23,7 +23,7 @@ class TestForbiddenProperty(unittest.TestCase): def test_property_present_fails(self): # property present with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ForbiddenProperty._from_openapi_data( + ForbiddenProperty.from_openapi_data_oapg( { "foo": 1, @@ -35,7 +35,7 @@ class TestForbiddenProperty(unittest.TestCase): def test_property_absent_passes(self): # property absent - ForbiddenProperty._from_openapi_data( + ForbiddenProperty.from_openapi_data_oapg( { "bar": 1, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_hostname_format.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_hostname_format.py similarity index 85% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_hostname_format.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_hostname_format.py index 32a6f0d003..20c3febcb3 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_hostname_format.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_hostname_format.py @@ -22,7 +22,7 @@ class TestHostnameFormat(unittest.TestCase): def test_all_string_formats_ignore_objects_passes(self): # all string formats ignore objects - HostnameFormat._from_openapi_data( + HostnameFormat.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,28 +30,28 @@ class TestHostnameFormat(unittest.TestCase): def test_all_string_formats_ignore_booleans_passes(self): # all string formats ignore booleans - HostnameFormat._from_openapi_data( + HostnameFormat.from_openapi_data_oapg( False, _configuration=self._configuration ) def test_all_string_formats_ignore_integers_passes(self): # all string formats ignore integers - HostnameFormat._from_openapi_data( + HostnameFormat.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_all_string_formats_ignore_floats_passes(self): # all string formats ignore floats - HostnameFormat._from_openapi_data( + HostnameFormat.from_openapi_data_oapg( 13.7, _configuration=self._configuration ) def test_all_string_formats_ignore_arrays_passes(self): # all string formats ignore arrays - HostnameFormat._from_openapi_data( + HostnameFormat.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -59,7 +59,7 @@ class TestHostnameFormat(unittest.TestCase): def test_all_string_formats_ignore_nulls_passes(self): # all string formats ignore nulls - HostnameFormat._from_openapi_data( + HostnameFormat.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_integer_type_matches_integers.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_integer_type_matches_integers.py similarity index 84% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_integer_type_matches_integers.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_integer_type_matches_integers.py index ecf83a0586..4ffba76e32 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_integer_type_matches_integers.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_integer_type_matches_integers.py @@ -23,7 +23,7 @@ class TestIntegerTypeMatchesIntegers(unittest.TestCase): def test_an_object_is_not_an_integer_fails(self): # an object is not an integer with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - IntegerTypeMatchesIntegers._from_openapi_data( + IntegerTypeMatchesIntegers.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -32,7 +32,7 @@ class TestIntegerTypeMatchesIntegers(unittest.TestCase): def test_a_string_is_not_an_integer_fails(self): # a string is not an integer with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - IntegerTypeMatchesIntegers._from_openapi_data( + IntegerTypeMatchesIntegers.from_openapi_data_oapg( "foo", _configuration=self._configuration ) @@ -40,14 +40,14 @@ class TestIntegerTypeMatchesIntegers(unittest.TestCase): def test_null_is_not_an_integer_fails(self): # null is not an integer with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - IntegerTypeMatchesIntegers._from_openapi_data( + IntegerTypeMatchesIntegers.from_openapi_data_oapg( None, _configuration=self._configuration ) def test_a_float_with_zero_fractional_part_is_an_integer_passes(self): # a float with zero fractional part is an integer - IntegerTypeMatchesIntegers._from_openapi_data( + IntegerTypeMatchesIntegers.from_openapi_data_oapg( 1.0, _configuration=self._configuration ) @@ -55,7 +55,7 @@ class TestIntegerTypeMatchesIntegers(unittest.TestCase): def test_a_float_is_not_an_integer_fails(self): # a float is not an integer with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - IntegerTypeMatchesIntegers._from_openapi_data( + IntegerTypeMatchesIntegers.from_openapi_data_oapg( 1.1, _configuration=self._configuration ) @@ -63,14 +63,14 @@ class TestIntegerTypeMatchesIntegers(unittest.TestCase): def test_a_boolean_is_not_an_integer_fails(self): # a boolean is not an integer with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - IntegerTypeMatchesIntegers._from_openapi_data( + IntegerTypeMatchesIntegers.from_openapi_data_oapg( True, _configuration=self._configuration ) def test_an_integer_is_an_integer_passes(self): # an integer is an integer - IntegerTypeMatchesIntegers._from_openapi_data( + IntegerTypeMatchesIntegers.from_openapi_data_oapg( 1, _configuration=self._configuration ) @@ -78,7 +78,7 @@ class TestIntegerTypeMatchesIntegers(unittest.TestCase): def test_a_string_is_still_not_an_integer_even_if_it_looks_like_one_fails(self): # a string is still not an integer, even if it looks like one with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - IntegerTypeMatchesIntegers._from_openapi_data( + IntegerTypeMatchesIntegers.from_openapi_data_oapg( "1", _configuration=self._configuration ) @@ -86,7 +86,7 @@ class TestIntegerTypeMatchesIntegers(unittest.TestCase): def test_an_array_is_not_an_integer_fails(self): # an array is not an integer with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - IntegerTypeMatchesIntegers._from_openapi_data( + IntegerTypeMatchesIntegers.from_openapi_data_oapg( [ ], _configuration=self._configuration diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_invalid_instance_should_not_raise_error_when_float_division_inf.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_invalid_instance_should_not_raise_error_when_float_division_inf.py similarity index 79% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_invalid_instance_should_not_raise_error_when_float_division_inf.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_invalid_instance_should_not_raise_error_when_float_division_inf.py index 67ce05d42f..fb2c597c56 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_invalid_instance_should_not_raise_error_when_float_division_inf.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_invalid_instance_should_not_raise_error_when_float_division_inf.py @@ -23,11 +23,18 @@ class TestInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf(unittest.TestCa def test_always_invalid_but_naive_implementations_may_raise_an_overflow_error_fails(self): # always invalid, but naive implementations may raise an overflow error with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf._from_openapi_data( + InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.from_openapi_data_oapg( 1.0E308, _configuration=self._configuration ) + def test_valid_integer_with_multipleof_float_passes(self): + # valid integer with multipleOf float + InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf.from_openapi_data_oapg( + 123456789, + _configuration=self._configuration + ) + if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_invalid_string_value_for_default.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_invalid_string_value_for_default.py similarity index 90% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_invalid_string_value_for_default.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_invalid_string_value_for_default.py index 50f165727b..c62e6e45b5 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_invalid_string_value_for_default.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_invalid_string_value_for_default.py @@ -22,7 +22,7 @@ class TestInvalidStringValueForDefault(unittest.TestCase): def test_valid_when_property_is_specified_passes(self): # valid when property is specified - InvalidStringValueForDefault._from_openapi_data( + InvalidStringValueForDefault.from_openapi_data_oapg( { "bar": "good", @@ -32,7 +32,7 @@ class TestInvalidStringValueForDefault(unittest.TestCase): def test_still_valid_when_the_invalid_default_is_used_passes(self): # still valid when the invalid default is used - InvalidStringValueForDefault._from_openapi_data( + InvalidStringValueForDefault.from_openapi_data_oapg( { }, _configuration=self._configuration diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ipv4_format.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ipv4_format.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ipv4_format.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ipv4_format.py index cd4cd9a69d..19e925b9a7 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ipv4_format.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ipv4_format.py @@ -22,7 +22,7 @@ class TestIpv4Format(unittest.TestCase): def test_all_string_formats_ignore_objects_passes(self): # all string formats ignore objects - Ipv4Format._from_openapi_data( + Ipv4Format.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,28 +30,28 @@ class TestIpv4Format(unittest.TestCase): def test_all_string_formats_ignore_booleans_passes(self): # all string formats ignore booleans - Ipv4Format._from_openapi_data( + Ipv4Format.from_openapi_data_oapg( False, _configuration=self._configuration ) def test_all_string_formats_ignore_integers_passes(self): # all string formats ignore integers - Ipv4Format._from_openapi_data( + Ipv4Format.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_all_string_formats_ignore_floats_passes(self): # all string formats ignore floats - Ipv4Format._from_openapi_data( + Ipv4Format.from_openapi_data_oapg( 13.7, _configuration=self._configuration ) def test_all_string_formats_ignore_arrays_passes(self): # all string formats ignore arrays - Ipv4Format._from_openapi_data( + Ipv4Format.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -59,7 +59,7 @@ class TestIpv4Format(unittest.TestCase): def test_all_string_formats_ignore_nulls_passes(self): # all string formats ignore nulls - Ipv4Format._from_openapi_data( + Ipv4Format.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ipv6_format.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ipv6_format.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ipv6_format.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ipv6_format.py index e9e10a4890..09e7895b46 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ipv6_format.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ipv6_format.py @@ -22,7 +22,7 @@ class TestIpv6Format(unittest.TestCase): def test_all_string_formats_ignore_objects_passes(self): # all string formats ignore objects - Ipv6Format._from_openapi_data( + Ipv6Format.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,28 +30,28 @@ class TestIpv6Format(unittest.TestCase): def test_all_string_formats_ignore_booleans_passes(self): # all string formats ignore booleans - Ipv6Format._from_openapi_data( + Ipv6Format.from_openapi_data_oapg( False, _configuration=self._configuration ) def test_all_string_formats_ignore_integers_passes(self): # all string formats ignore integers - Ipv6Format._from_openapi_data( + Ipv6Format.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_all_string_formats_ignore_floats_passes(self): # all string formats ignore floats - Ipv6Format._from_openapi_data( + Ipv6Format.from_openapi_data_oapg( 13.7, _configuration=self._configuration ) def test_all_string_formats_ignore_arrays_passes(self): # all string formats ignore arrays - Ipv6Format._from_openapi_data( + Ipv6Format.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -59,7 +59,7 @@ class TestIpv6Format(unittest.TestCase): def test_all_string_formats_ignore_nulls_passes(self): # all string formats ignore nulls - Ipv6Format._from_openapi_data( + Ipv6Format.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_json_pointer_format.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_json_pointer_format.py similarity index 85% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_json_pointer_format.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_json_pointer_format.py index f20c6aff94..9b5fae8d6e 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_json_pointer_format.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_json_pointer_format.py @@ -22,7 +22,7 @@ class TestJsonPointerFormat(unittest.TestCase): def test_all_string_formats_ignore_objects_passes(self): # all string formats ignore objects - JsonPointerFormat._from_openapi_data( + JsonPointerFormat.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,28 +30,28 @@ class TestJsonPointerFormat(unittest.TestCase): def test_all_string_formats_ignore_booleans_passes(self): # all string formats ignore booleans - JsonPointerFormat._from_openapi_data( + JsonPointerFormat.from_openapi_data_oapg( False, _configuration=self._configuration ) def test_all_string_formats_ignore_integers_passes(self): # all string formats ignore integers - JsonPointerFormat._from_openapi_data( + JsonPointerFormat.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_all_string_formats_ignore_floats_passes(self): # all string formats ignore floats - JsonPointerFormat._from_openapi_data( + JsonPointerFormat.from_openapi_data_oapg( 13.7, _configuration=self._configuration ) def test_all_string_formats_ignore_arrays_passes(self): # all string formats ignore arrays - JsonPointerFormat._from_openapi_data( + JsonPointerFormat.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -59,7 +59,7 @@ class TestJsonPointerFormat(unittest.TestCase): def test_all_string_formats_ignore_nulls_passes(self): # all string formats ignore nulls - JsonPointerFormat._from_openapi_data( + JsonPointerFormat.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maximum_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maximum_validation.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maximum_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maximum_validation.py index 5c0e51f822..b9cdf9e361 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maximum_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maximum_validation.py @@ -22,14 +22,14 @@ class TestMaximumValidation(unittest.TestCase): def test_below_the_maximum_is_valid_passes(self): # below the maximum is valid - MaximumValidation._from_openapi_data( + MaximumValidation.from_openapi_data_oapg( 2.6, _configuration=self._configuration ) def test_boundary_point_is_valid_passes(self): # boundary point is valid - MaximumValidation._from_openapi_data( + MaximumValidation.from_openapi_data_oapg( 3.0, _configuration=self._configuration ) @@ -37,14 +37,14 @@ class TestMaximumValidation(unittest.TestCase): def test_above_the_maximum_is_invalid_fails(self): # above the maximum is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MaximumValidation._from_openapi_data( + MaximumValidation.from_openapi_data_oapg( 3.5, _configuration=self._configuration ) def test_ignores_non_numbers_passes(self): # ignores non-numbers - MaximumValidation._from_openapi_data( + MaximumValidation.from_openapi_data_oapg( "x", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maximum_validation_with_unsigned_integer.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maximum_validation_with_unsigned_integer.py similarity index 84% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maximum_validation_with_unsigned_integer.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maximum_validation_with_unsigned_integer.py index 4bc8a4f837..c18028ee2a 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maximum_validation_with_unsigned_integer.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maximum_validation_with_unsigned_integer.py @@ -22,7 +22,7 @@ class TestMaximumValidationWithUnsignedInteger(unittest.TestCase): def test_below_the_maximum_is_invalid_passes(self): # below the maximum is invalid - MaximumValidationWithUnsignedInteger._from_openapi_data( + MaximumValidationWithUnsignedInteger.from_openapi_data_oapg( 299.97, _configuration=self._configuration ) @@ -30,21 +30,21 @@ class TestMaximumValidationWithUnsignedInteger(unittest.TestCase): def test_above_the_maximum_is_invalid_fails(self): # above the maximum is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MaximumValidationWithUnsignedInteger._from_openapi_data( + MaximumValidationWithUnsignedInteger.from_openapi_data_oapg( 300.5, _configuration=self._configuration ) def test_boundary_point_integer_is_valid_passes(self): # boundary point integer is valid - MaximumValidationWithUnsignedInteger._from_openapi_data( + MaximumValidationWithUnsignedInteger.from_openapi_data_oapg( 300, _configuration=self._configuration ) def test_boundary_point_float_is_valid_passes(self): # boundary point float is valid - MaximumValidationWithUnsignedInteger._from_openapi_data( + MaximumValidationWithUnsignedInteger.from_openapi_data_oapg( 300.0, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxitems_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxitems_validation.py similarity index 87% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxitems_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxitems_validation.py index 10804599c3..1a8afe4e9b 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxitems_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxitems_validation.py @@ -23,7 +23,7 @@ class TestMaxitemsValidation(unittest.TestCase): def test_too_long_is_invalid_fails(self): # too long is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MaxitemsValidation._from_openapi_data( + MaxitemsValidation.from_openapi_data_oapg( [ 1, 2, @@ -34,14 +34,14 @@ class TestMaxitemsValidation(unittest.TestCase): def test_ignores_non_arrays_passes(self): # ignores non-arrays - MaxitemsValidation._from_openapi_data( + MaxitemsValidation.from_openapi_data_oapg( "foobar", _configuration=self._configuration ) def test_shorter_is_valid_passes(self): # shorter is valid - MaxitemsValidation._from_openapi_data( + MaxitemsValidation.from_openapi_data_oapg( [ 1, ], @@ -50,7 +50,7 @@ class TestMaxitemsValidation(unittest.TestCase): def test_exact_length_is_valid_passes(self): # exact length is valid - MaxitemsValidation._from_openapi_data( + MaxitemsValidation.from_openapi_data_oapg( [ 1, 2, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxlength_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxlength_validation.py similarity index 85% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxlength_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxlength_validation.py index e5871ed0f1..7454b37934 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxlength_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxlength_validation.py @@ -23,35 +23,35 @@ class TestMaxlengthValidation(unittest.TestCase): def test_too_long_is_invalid_fails(self): # too long is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MaxlengthValidation._from_openapi_data( + MaxlengthValidation.from_openapi_data_oapg( "foo", _configuration=self._configuration ) def test_ignores_non_strings_passes(self): # ignores non-strings - MaxlengthValidation._from_openapi_data( + MaxlengthValidation.from_openapi_data_oapg( 100, _configuration=self._configuration ) def test_shorter_is_valid_passes(self): # shorter is valid - MaxlengthValidation._from_openapi_data( + MaxlengthValidation.from_openapi_data_oapg( "f", _configuration=self._configuration ) def test_two_supplementary_unicode_code_points_is_long_enough_passes(self): # two supplementary Unicode code points is long enough - MaxlengthValidation._from_openapi_data( + MaxlengthValidation.from_openapi_data_oapg( "💩💩", _configuration=self._configuration ) def test_exact_length_is_valid_passes(self): # exact length is valid - MaxlengthValidation._from_openapi_data( + MaxlengthValidation.from_openapi_data_oapg( "fo", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxproperties0_means_the_object_is_empty.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxproperties0_means_the_object_is_empty.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxproperties0_means_the_object_is_empty.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxproperties0_means_the_object_is_empty.py index 57764ac4a8..92a8cf2139 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxproperties0_means_the_object_is_empty.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxproperties0_means_the_object_is_empty.py @@ -22,7 +22,7 @@ class TestMaxproperties0MeansTheObjectIsEmpty(unittest.TestCase): def test_no_properties_is_valid_passes(self): # no properties is valid - Maxproperties0MeansTheObjectIsEmpty._from_openapi_data( + Maxproperties0MeansTheObjectIsEmpty.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -31,7 +31,7 @@ class TestMaxproperties0MeansTheObjectIsEmpty(unittest.TestCase): def test_one_property_is_invalid_fails(self): # one property is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - Maxproperties0MeansTheObjectIsEmpty._from_openapi_data( + Maxproperties0MeansTheObjectIsEmpty.from_openapi_data_oapg( { "foo": 1, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxproperties_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxproperties_validation.py similarity index 85% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxproperties_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxproperties_validation.py index cd87cbfc64..cc3684783b 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_maxproperties_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_maxproperties_validation.py @@ -23,7 +23,7 @@ class TestMaxpropertiesValidation(unittest.TestCase): def test_too_long_is_invalid_fails(self): # too long is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MaxpropertiesValidation._from_openapi_data( + MaxpropertiesValidation.from_openapi_data_oapg( { "foo": 1, @@ -37,7 +37,7 @@ class TestMaxpropertiesValidation(unittest.TestCase): def test_ignores_arrays_passes(self): # ignores arrays - MaxpropertiesValidation._from_openapi_data( + MaxpropertiesValidation.from_openapi_data_oapg( [ 1, 2, @@ -48,21 +48,21 @@ class TestMaxpropertiesValidation(unittest.TestCase): def test_ignores_other_non_objects_passes(self): # ignores other non-objects - MaxpropertiesValidation._from_openapi_data( + MaxpropertiesValidation.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_ignores_strings_passes(self): # ignores strings - MaxpropertiesValidation._from_openapi_data( + MaxpropertiesValidation.from_openapi_data_oapg( "foobar", _configuration=self._configuration ) def test_shorter_is_valid_passes(self): # shorter is valid - MaxpropertiesValidation._from_openapi_data( + MaxpropertiesValidation.from_openapi_data_oapg( { "foo": 1, @@ -72,7 +72,7 @@ class TestMaxpropertiesValidation(unittest.TestCase): def test_exact_length_is_valid_passes(self): # exact length is valid - MaxpropertiesValidation._from_openapi_data( + MaxpropertiesValidation.from_openapi_data_oapg( { "foo": 1, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minimum_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minimum_validation.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minimum_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minimum_validation.py index d72abd6e1f..9c3798fadb 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minimum_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minimum_validation.py @@ -22,7 +22,7 @@ class TestMinimumValidation(unittest.TestCase): def test_boundary_point_is_valid_passes(self): # boundary point is valid - MinimumValidation._from_openapi_data( + MinimumValidation.from_openapi_data_oapg( 1.1, _configuration=self._configuration ) @@ -30,21 +30,21 @@ class TestMinimumValidation(unittest.TestCase): def test_below_the_minimum_is_invalid_fails(self): # below the minimum is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MinimumValidation._from_openapi_data( + MinimumValidation.from_openapi_data_oapg( 0.6, _configuration=self._configuration ) def test_above_the_minimum_is_valid_passes(self): # above the minimum is valid - MinimumValidation._from_openapi_data( + MinimumValidation.from_openapi_data_oapg( 2.6, _configuration=self._configuration ) def test_ignores_non_numbers_passes(self): # ignores non-numbers - MinimumValidation._from_openapi_data( + MinimumValidation.from_openapi_data_oapg( "x", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minimum_validation_with_signed_integer.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minimum_validation_with_signed_integer.py similarity index 81% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minimum_validation_with_signed_integer.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minimum_validation_with_signed_integer.py index d4f2307a2a..02795c0929 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minimum_validation_with_signed_integer.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minimum_validation_with_signed_integer.py @@ -22,14 +22,14 @@ class TestMinimumValidationWithSignedInteger(unittest.TestCase): def test_boundary_point_is_valid_passes(self): # boundary point is valid - MinimumValidationWithSignedInteger._from_openapi_data( + MinimumValidationWithSignedInteger.from_openapi_data_oapg( -2, _configuration=self._configuration ) def test_positive_above_the_minimum_is_valid_passes(self): # positive above the minimum is valid - MinimumValidationWithSignedInteger._from_openapi_data( + MinimumValidationWithSignedInteger.from_openapi_data_oapg( 0, _configuration=self._configuration ) @@ -37,7 +37,7 @@ class TestMinimumValidationWithSignedInteger(unittest.TestCase): def test_int_below_the_minimum_is_invalid_fails(self): # int below the minimum is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MinimumValidationWithSignedInteger._from_openapi_data( + MinimumValidationWithSignedInteger.from_openapi_data_oapg( -3, _configuration=self._configuration ) @@ -45,28 +45,28 @@ class TestMinimumValidationWithSignedInteger(unittest.TestCase): def test_float_below_the_minimum_is_invalid_fails(self): # float below the minimum is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MinimumValidationWithSignedInteger._from_openapi_data( + MinimumValidationWithSignedInteger.from_openapi_data_oapg( -2.0001, _configuration=self._configuration ) def test_boundary_point_with_float_is_valid_passes(self): # boundary point with float is valid - MinimumValidationWithSignedInteger._from_openapi_data( + MinimumValidationWithSignedInteger.from_openapi_data_oapg( -2.0, _configuration=self._configuration ) def test_negative_above_the_minimum_is_valid_passes(self): # negative above the minimum is valid - MinimumValidationWithSignedInteger._from_openapi_data( + MinimumValidationWithSignedInteger.from_openapi_data_oapg( -1, _configuration=self._configuration ) def test_ignores_non_numbers_passes(self): # ignores non-numbers - MinimumValidationWithSignedInteger._from_openapi_data( + MinimumValidationWithSignedInteger.from_openapi_data_oapg( "x", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minitems_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minitems_validation.py similarity index 87% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minitems_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minitems_validation.py index bca2643fcc..db5bb4eea0 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minitems_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minitems_validation.py @@ -23,7 +23,7 @@ class TestMinitemsValidation(unittest.TestCase): def test_too_short_is_invalid_fails(self): # too short is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MinitemsValidation._from_openapi_data( + MinitemsValidation.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -31,14 +31,14 @@ class TestMinitemsValidation(unittest.TestCase): def test_ignores_non_arrays_passes(self): # ignores non-arrays - MinitemsValidation._from_openapi_data( + MinitemsValidation.from_openapi_data_oapg( "", _configuration=self._configuration ) def test_longer_is_valid_passes(self): # longer is valid - MinitemsValidation._from_openapi_data( + MinitemsValidation.from_openapi_data_oapg( [ 1, 2, @@ -48,7 +48,7 @@ class TestMinitemsValidation(unittest.TestCase): def test_exact_length_is_valid_passes(self): # exact length is valid - MinitemsValidation._from_openapi_data( + MinitemsValidation.from_openapi_data_oapg( [ 1, ], diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minlength_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minlength_validation.py similarity index 85% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minlength_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minlength_validation.py index 515b2958eb..e7327d1a4d 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minlength_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minlength_validation.py @@ -23,7 +23,7 @@ class TestMinlengthValidation(unittest.TestCase): def test_too_short_is_invalid_fails(self): # too short is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MinlengthValidation._from_openapi_data( + MinlengthValidation.from_openapi_data_oapg( "f", _configuration=self._configuration ) @@ -31,28 +31,28 @@ class TestMinlengthValidation(unittest.TestCase): def test_one_supplementary_unicode_code_point_is_not_long_enough_fails(self): # one supplementary Unicode code point is not long enough with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MinlengthValidation._from_openapi_data( + MinlengthValidation.from_openapi_data_oapg( "💩", _configuration=self._configuration ) def test_longer_is_valid_passes(self): # longer is valid - MinlengthValidation._from_openapi_data( + MinlengthValidation.from_openapi_data_oapg( "foo", _configuration=self._configuration ) def test_ignores_non_strings_passes(self): # ignores non-strings - MinlengthValidation._from_openapi_data( + MinlengthValidation.from_openapi_data_oapg( 1, _configuration=self._configuration ) def test_exact_length_is_valid_passes(self): # exact length is valid - MinlengthValidation._from_openapi_data( + MinlengthValidation.from_openapi_data_oapg( "fo", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minproperties_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minproperties_validation.py similarity index 84% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minproperties_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minproperties_validation.py index b8202eb346..6d79810b1d 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_minproperties_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_minproperties_validation.py @@ -22,7 +22,7 @@ class TestMinpropertiesValidation(unittest.TestCase): def test_ignores_arrays_passes(self): # ignores arrays - MinpropertiesValidation._from_openapi_data( + MinpropertiesValidation.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -30,7 +30,7 @@ class TestMinpropertiesValidation(unittest.TestCase): def test_ignores_other_non_objects_passes(self): # ignores other non-objects - MinpropertiesValidation._from_openapi_data( + MinpropertiesValidation.from_openapi_data_oapg( 12, _configuration=self._configuration ) @@ -38,7 +38,7 @@ class TestMinpropertiesValidation(unittest.TestCase): def test_too_short_is_invalid_fails(self): # too short is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - MinpropertiesValidation._from_openapi_data( + MinpropertiesValidation.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -46,14 +46,14 @@ class TestMinpropertiesValidation(unittest.TestCase): def test_ignores_strings_passes(self): # ignores strings - MinpropertiesValidation._from_openapi_data( + MinpropertiesValidation.from_openapi_data_oapg( "", _configuration=self._configuration ) def test_longer_is_valid_passes(self): # longer is valid - MinpropertiesValidation._from_openapi_data( + MinpropertiesValidation.from_openapi_data_oapg( { "foo": 1, @@ -65,7 +65,7 @@ class TestMinpropertiesValidation(unittest.TestCase): def test_exact_length_is_valid_passes(self): # exact length is valid - MinpropertiesValidation._from_openapi_data( + MinpropertiesValidation.from_openapi_data_oapg( { "foo": 1, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_model_not.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_model_not.py similarity index 91% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_model_not.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_model_not.py index 7bc1095617..996812828d 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_model_not.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_model_not.py @@ -22,7 +22,7 @@ class TestModelNot(unittest.TestCase): def test_allowed_passes(self): # allowed - ModelNot._from_openapi_data( + ModelNot.from_openapi_data_oapg( "foo", _configuration=self._configuration ) @@ -30,7 +30,7 @@ class TestModelNot(unittest.TestCase): def test_disallowed_fails(self): # disallowed with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ModelNot._from_openapi_data( + ModelNot.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_allof_to_check_validation_semantics.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_allof_to_check_validation_semantics.py similarity index 88% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_allof_to_check_validation_semantics.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_allof_to_check_validation_semantics.py index 61cefebba0..7919e40463 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_allof_to_check_validation_semantics.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_allof_to_check_validation_semantics.py @@ -23,14 +23,14 @@ class TestNestedAllofToCheckValidationSemantics(unittest.TestCase): def test_anything_non_null_is_invalid_fails(self): # anything non-null is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NestedAllofToCheckValidationSemantics._from_openapi_data( + NestedAllofToCheckValidationSemantics.from_openapi_data_oapg( 123, _configuration=self._configuration ) def test_null_is_valid_passes(self): # null is valid - NestedAllofToCheckValidationSemantics._from_openapi_data( + NestedAllofToCheckValidationSemantics.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_anyof_to_check_validation_semantics.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_anyof_to_check_validation_semantics.py similarity index 88% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_anyof_to_check_validation_semantics.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_anyof_to_check_validation_semantics.py index 9790a71c84..2be0dd8eda 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_anyof_to_check_validation_semantics.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_anyof_to_check_validation_semantics.py @@ -23,14 +23,14 @@ class TestNestedAnyofToCheckValidationSemantics(unittest.TestCase): def test_anything_non_null_is_invalid_fails(self): # anything non-null is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NestedAnyofToCheckValidationSemantics._from_openapi_data( + NestedAnyofToCheckValidationSemantics.from_openapi_data_oapg( 123, _configuration=self._configuration ) def test_null_is_valid_passes(self): # null is valid - NestedAnyofToCheckValidationSemantics._from_openapi_data( + NestedAnyofToCheckValidationSemantics.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_items.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_items.py similarity index 96% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_items.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_items.py index e6d42516d3..273f27f8b7 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_items.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_items.py @@ -22,7 +22,7 @@ class TestNestedItems(unittest.TestCase): def test_valid_nested_array_passes(self): # valid nested array - NestedItems._from_openapi_data( + NestedItems.from_openapi_data_oapg( [ [ [ @@ -59,7 +59,7 @@ class TestNestedItems(unittest.TestCase): def test_nested_array_with_invalid_type_fails(self): # nested array with invalid type with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NestedItems._from_openapi_data( + NestedItems.from_openapi_data_oapg( [ [ [ @@ -96,7 +96,7 @@ class TestNestedItems(unittest.TestCase): def test_not_deep_enough_fails(self): # not deep enough with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NestedItems._from_openapi_data( + NestedItems.from_openapi_data_oapg( [ [ [ diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_oneof_to_check_validation_semantics.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_oneof_to_check_validation_semantics.py similarity index 88% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_oneof_to_check_validation_semantics.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_oneof_to_check_validation_semantics.py index 48f2ffeb02..80f80e3ec4 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nested_oneof_to_check_validation_semantics.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nested_oneof_to_check_validation_semantics.py @@ -23,14 +23,14 @@ class TestNestedOneofToCheckValidationSemantics(unittest.TestCase): def test_anything_non_null_is_invalid_fails(self): # anything non-null is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NestedOneofToCheckValidationSemantics._from_openapi_data( + NestedOneofToCheckValidationSemantics.from_openapi_data_oapg( 123, _configuration=self._configuration ) def test_null_is_valid_passes(self): # null is valid - NestedOneofToCheckValidationSemantics._from_openapi_data( + NestedOneofToCheckValidationSemantics.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_not_more_complex_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_not_more_complex_schema.py similarity index 88% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_not_more_complex_schema.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_not_more_complex_schema.py index b7ab21dadd..38acbc0e04 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_not_more_complex_schema.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_not_more_complex_schema.py @@ -22,7 +22,7 @@ class TestNotMoreComplexSchema(unittest.TestCase): def test_other_match_passes(self): # other match - NotMoreComplexSchema._from_openapi_data( + NotMoreComplexSchema.from_openapi_data_oapg( { "foo": 1, @@ -33,7 +33,7 @@ class TestNotMoreComplexSchema(unittest.TestCase): def test_mismatch_fails(self): # mismatch with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NotMoreComplexSchema._from_openapi_data( + NotMoreComplexSchema.from_openapi_data_oapg( { "foo": "bar", @@ -43,7 +43,7 @@ class TestNotMoreComplexSchema(unittest.TestCase): def test_match_passes(self): # match - NotMoreComplexSchema._from_openapi_data( + NotMoreComplexSchema.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nul_characters_in_strings.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nul_characters_in_strings.py similarity index 90% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nul_characters_in_strings.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nul_characters_in_strings.py index 5f9465d868..c5bbe09859 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_nul_characters_in_strings.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_nul_characters_in_strings.py @@ -22,7 +22,7 @@ class TestNulCharactersInStrings(unittest.TestCase): def test_match_string_with_nul_passes(self): # match string with nul - NulCharactersInStrings._from_openapi_data( + NulCharactersInStrings.from_openapi_data_oapg( "hello\x00there", _configuration=self._configuration ) @@ -30,7 +30,7 @@ class TestNulCharactersInStrings(unittest.TestCase): def test_do_not_match_string_lacking_nul_fails(self): # do not match string lacking nul with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NulCharactersInStrings._from_openapi_data( + NulCharactersInStrings.from_openapi_data_oapg( "hellothere", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_null_type_matches_only_the_null_object.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_null_type_matches_only_the_null_object.py similarity index 82% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_null_type_matches_only_the_null_object.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_null_type_matches_only_the_null_object.py index 0057f89b2b..be22b3587c 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_null_type_matches_only_the_null_object.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_null_type_matches_only_the_null_object.py @@ -23,7 +23,7 @@ class TestNullTypeMatchesOnlyTheNullObject(unittest.TestCase): def test_a_float_is_not_null_fails(self): # a float is not null with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( 1.1, _configuration=self._configuration ) @@ -31,7 +31,7 @@ class TestNullTypeMatchesOnlyTheNullObject(unittest.TestCase): def test_an_object_is_not_null_fails(self): # an object is not null with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -40,7 +40,7 @@ class TestNullTypeMatchesOnlyTheNullObject(unittest.TestCase): def test_false_is_not_null_fails(self): # false is not null with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( False, _configuration=self._configuration ) @@ -48,7 +48,7 @@ class TestNullTypeMatchesOnlyTheNullObject(unittest.TestCase): def test_an_integer_is_not_null_fails(self): # an integer is not null with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( 1, _configuration=self._configuration ) @@ -56,7 +56,7 @@ class TestNullTypeMatchesOnlyTheNullObject(unittest.TestCase): def test_true_is_not_null_fails(self): # true is not null with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( True, _configuration=self._configuration ) @@ -64,7 +64,7 @@ class TestNullTypeMatchesOnlyTheNullObject(unittest.TestCase): def test_zero_is_not_null_fails(self): # zero is not null with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( 0, _configuration=self._configuration ) @@ -72,14 +72,14 @@ class TestNullTypeMatchesOnlyTheNullObject(unittest.TestCase): def test_an_empty_string_is_not_null_fails(self): # an empty string is not null with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( "", _configuration=self._configuration ) def test_null_is_null_passes(self): # null is null - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( None, _configuration=self._configuration ) @@ -87,7 +87,7 @@ class TestNullTypeMatchesOnlyTheNullObject(unittest.TestCase): def test_an_array_is_not_null_fails(self): # an array is not null with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -96,7 +96,7 @@ class TestNullTypeMatchesOnlyTheNullObject(unittest.TestCase): def test_a_string_is_not_null_fails(self): # a string is not null with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NullTypeMatchesOnlyTheNullObject._from_openapi_data( + NullTypeMatchesOnlyTheNullObject.from_openapi_data_oapg( "foo", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_number_type_matches_numbers.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_number_type_matches_numbers.py similarity index 84% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_number_type_matches_numbers.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_number_type_matches_numbers.py index c71c9a01f7..2070edb70c 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_number_type_matches_numbers.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_number_type_matches_numbers.py @@ -23,7 +23,7 @@ class TestNumberTypeMatchesNumbers(unittest.TestCase): def test_an_array_is_not_a_number_fails(self): # an array is not a number with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NumberTypeMatchesNumbers._from_openapi_data( + NumberTypeMatchesNumbers.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -32,7 +32,7 @@ class TestNumberTypeMatchesNumbers(unittest.TestCase): def test_null_is_not_a_number_fails(self): # null is not a number with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NumberTypeMatchesNumbers._from_openapi_data( + NumberTypeMatchesNumbers.from_openapi_data_oapg( None, _configuration=self._configuration ) @@ -40,7 +40,7 @@ class TestNumberTypeMatchesNumbers(unittest.TestCase): def test_an_object_is_not_a_number_fails(self): # an object is not a number with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NumberTypeMatchesNumbers._from_openapi_data( + NumberTypeMatchesNumbers.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -49,14 +49,14 @@ class TestNumberTypeMatchesNumbers(unittest.TestCase): def test_a_boolean_is_not_a_number_fails(self): # a boolean is not a number with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NumberTypeMatchesNumbers._from_openapi_data( + NumberTypeMatchesNumbers.from_openapi_data_oapg( True, _configuration=self._configuration ) def test_a_float_is_a_number_passes(self): # a float is a number - NumberTypeMatchesNumbers._from_openapi_data( + NumberTypeMatchesNumbers.from_openapi_data_oapg( 1.1, _configuration=self._configuration ) @@ -64,7 +64,7 @@ class TestNumberTypeMatchesNumbers(unittest.TestCase): def test_a_string_is_still_not_a_number_even_if_it_looks_like_one_fails(self): # a string is still not a number, even if it looks like one with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NumberTypeMatchesNumbers._from_openapi_data( + NumberTypeMatchesNumbers.from_openapi_data_oapg( "1", _configuration=self._configuration ) @@ -72,21 +72,21 @@ class TestNumberTypeMatchesNumbers(unittest.TestCase): def test_a_string_is_not_a_number_fails(self): # a string is not a number with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - NumberTypeMatchesNumbers._from_openapi_data( + NumberTypeMatchesNumbers.from_openapi_data_oapg( "foo", _configuration=self._configuration ) def test_an_integer_is_a_number_passes(self): # an integer is a number - NumberTypeMatchesNumbers._from_openapi_data( + NumberTypeMatchesNumbers.from_openapi_data_oapg( 1, _configuration=self._configuration ) def test_a_float_with_zero_fractional_part_is_a_number_and_an_integer_passes(self): # a float with zero fractional part is a number (and an integer) - NumberTypeMatchesNumbers._from_openapi_data( + NumberTypeMatchesNumbers.from_openapi_data_oapg( 1.0, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_object_properties_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_object_properties_validation.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_object_properties_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_object_properties_validation.py index f4e44b15ad..9b74a32cc9 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_object_properties_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_object_properties_validation.py @@ -22,7 +22,7 @@ class TestObjectPropertiesValidation(unittest.TestCase): def test_ignores_arrays_passes(self): # ignores arrays - ObjectPropertiesValidation._from_openapi_data( + ObjectPropertiesValidation.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -30,7 +30,7 @@ class TestObjectPropertiesValidation(unittest.TestCase): def test_ignores_other_non_objects_passes(self): # ignores other non-objects - ObjectPropertiesValidation._from_openapi_data( + ObjectPropertiesValidation.from_openapi_data_oapg( 12, _configuration=self._configuration ) @@ -38,7 +38,7 @@ class TestObjectPropertiesValidation(unittest.TestCase): def test_one_property_invalid_is_invalid_fails(self): # one property invalid is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ObjectPropertiesValidation._from_openapi_data( + ObjectPropertiesValidation.from_openapi_data_oapg( { "foo": 1, @@ -51,7 +51,7 @@ class TestObjectPropertiesValidation(unittest.TestCase): def test_both_properties_present_and_valid_is_valid_passes(self): # both properties present and valid is valid - ObjectPropertiesValidation._from_openapi_data( + ObjectPropertiesValidation.from_openapi_data_oapg( { "foo": 1, @@ -63,7 +63,7 @@ class TestObjectPropertiesValidation(unittest.TestCase): def test_doesn_t_invalidate_other_properties_passes(self): # doesn't invalidate other properties - ObjectPropertiesValidation._from_openapi_data( + ObjectPropertiesValidation.from_openapi_data_oapg( { "quux": [ @@ -75,7 +75,7 @@ class TestObjectPropertiesValidation(unittest.TestCase): def test_both_properties_invalid_is_invalid_fails(self): # both properties invalid is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - ObjectPropertiesValidation._from_openapi_data( + ObjectPropertiesValidation.from_openapi_data_oapg( { "foo": [ diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof.py index 5daa47d179..c23316082f 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof.py @@ -22,7 +22,7 @@ class TestOneof(unittest.TestCase): def test_second_oneof_valid_passes(self): # second oneOf valid - Oneof._from_openapi_data( + Oneof.from_openapi_data_oapg( 2.5, _configuration=self._configuration ) @@ -30,14 +30,14 @@ class TestOneof(unittest.TestCase): def test_both_oneof_valid_fails(self): # both oneOf valid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - Oneof._from_openapi_data( + Oneof.from_openapi_data_oapg( 3, _configuration=self._configuration ) def test_first_oneof_valid_passes(self): # first oneOf valid - Oneof._from_openapi_data( + Oneof.from_openapi_data_oapg( 1, _configuration=self._configuration ) @@ -45,7 +45,7 @@ class TestOneof(unittest.TestCase): def test_neither_oneof_valid_fails(self): # neither oneOf valid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - Oneof._from_openapi_data( + Oneof.from_openapi_data_oapg( 1.5, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof_complex_types.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_complex_types.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof_complex_types.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_complex_types.py index 16e639618c..f577d4cfa7 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof_complex_types.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_complex_types.py @@ -22,7 +22,7 @@ class TestOneofComplexTypes(unittest.TestCase): def test_first_oneof_valid_complex_passes(self): # first oneOf valid (complex) - OneofComplexTypes._from_openapi_data( + OneofComplexTypes.from_openapi_data_oapg( { "bar": 2, @@ -33,7 +33,7 @@ class TestOneofComplexTypes(unittest.TestCase): def test_neither_oneof_valid_complex_fails(self): # neither oneOf valid (complex) with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - OneofComplexTypes._from_openapi_data( + OneofComplexTypes.from_openapi_data_oapg( { "foo": 2, @@ -46,7 +46,7 @@ class TestOneofComplexTypes(unittest.TestCase): def test_both_oneof_valid_complex_fails(self): # both oneOf valid (complex) with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - OneofComplexTypes._from_openapi_data( + OneofComplexTypes.from_openapi_data_oapg( { "foo": "baz", @@ -58,7 +58,7 @@ class TestOneofComplexTypes(unittest.TestCase): def test_second_oneof_valid_complex_passes(self): # second oneOf valid (complex) - OneofComplexTypes._from_openapi_data( + OneofComplexTypes.from_openapi_data_oapg( { "foo": "baz", diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof_with_base_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_with_base_schema.py similarity index 88% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof_with_base_schema.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_with_base_schema.py index 52e075c47c..a1662542c1 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof_with_base_schema.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_with_base_schema.py @@ -23,7 +23,7 @@ class TestOneofWithBaseSchema(unittest.TestCase): def test_both_oneof_valid_fails(self): # both oneOf valid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - OneofWithBaseSchema._from_openapi_data( + OneofWithBaseSchema.from_openapi_data_oapg( "foo", _configuration=self._configuration ) @@ -31,14 +31,14 @@ class TestOneofWithBaseSchema(unittest.TestCase): def test_mismatch_base_schema_fails(self): # mismatch base schema with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - OneofWithBaseSchema._from_openapi_data( + OneofWithBaseSchema.from_openapi_data_oapg( 3, _configuration=self._configuration ) def test_one_oneof_valid_passes(self): # one oneOf valid - OneofWithBaseSchema._from_openapi_data( + OneofWithBaseSchema.from_openapi_data_oapg( "foobar", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof_with_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_with_empty_schema.py similarity index 90% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof_with_empty_schema.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_with_empty_schema.py index 66b9d79990..ad3cd28618 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_oneof_with_empty_schema.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_with_empty_schema.py @@ -23,14 +23,14 @@ class TestOneofWithEmptySchema(unittest.TestCase): def test_both_valid_invalid_fails(self): # both valid - invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - OneofWithEmptySchema._from_openapi_data( + OneofWithEmptySchema.from_openapi_data_oapg( 123, _configuration=self._configuration ) def test_one_valid_valid_passes(self): # one valid - valid - OneofWithEmptySchema._from_openapi_data( + OneofWithEmptySchema.from_openapi_data_oapg( "foo", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_with_required.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_with_required.py new file mode 100644 index 0000000000..5c8132375d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_oneof_with_required.py @@ -0,0 +1,75 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import unit_test_api +from unit_test_api.model.oneof_with_required import OneofWithRequired +from unit_test_api import configuration + + +class TestOneofWithRequired(unittest.TestCase): + """OneofWithRequired unit test stubs""" + _configuration = configuration.Configuration() + + def test_both_valid_invalid_fails(self): + # both valid - invalid + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + OneofWithRequired.from_openapi_data_oapg( + { + "foo": + 1, + "bar": + 2, + "baz": + 3, + }, + _configuration=self._configuration + ) + + def test_both_invalid_invalid_fails(self): + # both invalid - invalid + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + OneofWithRequired.from_openapi_data_oapg( + { + "bar": + 2, + }, + _configuration=self._configuration + ) + + def test_first_valid_valid_passes(self): + # first valid - valid + OneofWithRequired.from_openapi_data_oapg( + { + "foo": + 1, + "bar": + 2, + }, + _configuration=self._configuration + ) + + def test_second_valid_valid_passes(self): + # second valid - valid + OneofWithRequired.from_openapi_data_oapg( + { + "foo": + 1, + "baz": + 3, + }, + _configuration=self._configuration + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_pattern_is_not_anchored.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_pattern_is_not_anchored.py similarity index 93% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_pattern_is_not_anchored.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_pattern_is_not_anchored.py index 15eb5c2558..42f533b901 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_pattern_is_not_anchored.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_pattern_is_not_anchored.py @@ -22,7 +22,7 @@ class TestPatternIsNotAnchored(unittest.TestCase): def test_matches_a_substring_passes(self): # matches a substring - PatternIsNotAnchored._from_openapi_data( + PatternIsNotAnchored.from_openapi_data_oapg( "xxaayy", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_pattern_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_pattern_validation.py similarity index 82% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_pattern_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_pattern_validation.py index fc76731c83..60cb2e1a1c 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_pattern_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_pattern_validation.py @@ -22,7 +22,7 @@ class TestPatternValidation(unittest.TestCase): def test_ignores_arrays_passes(self): # ignores arrays - PatternValidation._from_openapi_data( + PatternValidation.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -30,7 +30,7 @@ class TestPatternValidation(unittest.TestCase): def test_ignores_objects_passes(self): # ignores objects - PatternValidation._from_openapi_data( + PatternValidation.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -38,14 +38,14 @@ class TestPatternValidation(unittest.TestCase): def test_ignores_null_passes(self): # ignores null - PatternValidation._from_openapi_data( + PatternValidation.from_openapi_data_oapg( None, _configuration=self._configuration ) def test_ignores_floats_passes(self): # ignores floats - PatternValidation._from_openapi_data( + PatternValidation.from_openapi_data_oapg( 1.0, _configuration=self._configuration ) @@ -53,28 +53,28 @@ class TestPatternValidation(unittest.TestCase): def test_a_non_matching_pattern_is_invalid_fails(self): # a non-matching pattern is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - PatternValidation._from_openapi_data( + PatternValidation.from_openapi_data_oapg( "abc", _configuration=self._configuration ) def test_ignores_booleans_passes(self): # ignores booleans - PatternValidation._from_openapi_data( + PatternValidation.from_openapi_data_oapg( True, _configuration=self._configuration ) def test_a_matching_pattern_is_valid_passes(self): # a matching pattern is valid - PatternValidation._from_openapi_data( + PatternValidation.from_openapi_data_oapg( "aaa", _configuration=self._configuration ) def test_ignores_integers_passes(self): # ignores integers - PatternValidation._from_openapi_data( + PatternValidation.from_openapi_data_oapg( 123, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_properties_with_escaped_characters.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_properties_with_escaped_characters.py similarity index 93% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_properties_with_escaped_characters.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_properties_with_escaped_characters.py index d7a0c7b919..9cef87212d 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_properties_with_escaped_characters.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_properties_with_escaped_characters.py @@ -22,7 +22,7 @@ class TestPropertiesWithEscapedCharacters(unittest.TestCase): def test_object_with_all_numbers_is_valid_passes(self): # object with all numbers is valid - PropertiesWithEscapedCharacters._from_openapi_data( + PropertiesWithEscapedCharacters.from_openapi_data_oapg( { "foo\nbar": 1, @@ -43,7 +43,7 @@ class TestPropertiesWithEscapedCharacters(unittest.TestCase): def test_object_with_strings_is_invalid_fails(self): # object with strings is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - PropertiesWithEscapedCharacters._from_openapi_data( + PropertiesWithEscapedCharacters.from_openapi_data_oapg( { "foo\nbar": "1", diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_property_named_ref_that_is_not_a_reference.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_property_named_ref_that_is_not_a_reference.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_property_named_ref_that_is_not_a_reference.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_property_named_ref_that_is_not_a_reference.py index 2599fd45d4..52809d26e4 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_property_named_ref_that_is_not_a_reference.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_property_named_ref_that_is_not_a_reference.py @@ -22,7 +22,7 @@ class TestPropertyNamedRefThatIsNotAReference(unittest.TestCase): def test_property_named_ref_valid_passes(self): # property named $ref valid - PropertyNamedRefThatIsNotAReference._from_openapi_data( + PropertyNamedRefThatIsNotAReference.from_openapi_data_oapg( { "$ref": "a", @@ -33,7 +33,7 @@ class TestPropertyNamedRefThatIsNotAReference(unittest.TestCase): def test_property_named_ref_invalid_fails(self): # property named $ref invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - PropertyNamedRefThatIsNotAReference._from_openapi_data( + PropertyNamedRefThatIsNotAReference.from_openapi_data_oapg( { "$ref": 2, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_additionalproperties.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_additionalproperties.py similarity index 92% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_additionalproperties.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_additionalproperties.py index 3079918ced..db4bc26bbb 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_additionalproperties.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_additionalproperties.py @@ -22,7 +22,7 @@ class TestRefInAdditionalproperties(unittest.TestCase): def test_property_named_ref_valid_passes(self): # property named $ref valid - RefInAdditionalproperties._from_openapi_data( + RefInAdditionalproperties.from_openapi_data_oapg( { "someProp": { @@ -36,7 +36,7 @@ class TestRefInAdditionalproperties(unittest.TestCase): def test_property_named_ref_invalid_fails(self): # property named $ref invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - RefInAdditionalproperties._from_openapi_data( + RefInAdditionalproperties.from_openapi_data_oapg( { "someProp": { diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_allof.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_allof.py similarity index 92% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_allof.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_allof.py index a1bcc36509..66ff7e5cdc 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_allof.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_allof.py @@ -22,7 +22,7 @@ class TestRefInAllof(unittest.TestCase): def test_property_named_ref_valid_passes(self): # property named $ref valid - RefInAllof._from_openapi_data( + RefInAllof.from_openapi_data_oapg( { "$ref": "a", @@ -33,7 +33,7 @@ class TestRefInAllof(unittest.TestCase): def test_property_named_ref_invalid_fails(self): # property named $ref invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - RefInAllof._from_openapi_data( + RefInAllof.from_openapi_data_oapg( { "$ref": 2, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_anyof.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_anyof.py similarity index 92% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_anyof.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_anyof.py index 33ece563af..ddf2086676 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_anyof.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_anyof.py @@ -22,7 +22,7 @@ class TestRefInAnyof(unittest.TestCase): def test_property_named_ref_valid_passes(self): # property named $ref valid - RefInAnyof._from_openapi_data( + RefInAnyof.from_openapi_data_oapg( { "$ref": "a", @@ -33,7 +33,7 @@ class TestRefInAnyof(unittest.TestCase): def test_property_named_ref_invalid_fails(self): # property named $ref invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - RefInAnyof._from_openapi_data( + RefInAnyof.from_openapi_data_oapg( { "$ref": 2, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_items.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_items.py similarity index 93% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_items.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_items.py index 1cc69e3556..4f39d31763 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_items.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_items.py @@ -22,7 +22,7 @@ class TestRefInItems(unittest.TestCase): def test_property_named_ref_valid_passes(self): # property named $ref valid - RefInItems._from_openapi_data( + RefInItems.from_openapi_data_oapg( [ { "$ref": @@ -35,7 +35,7 @@ class TestRefInItems(unittest.TestCase): def test_property_named_ref_invalid_fails(self): # property named $ref invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - RefInItems._from_openapi_data( + RefInItems.from_openapi_data_oapg( [ { "$ref": diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_not.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_not.py new file mode 100644 index 0000000000..c33378cd27 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_not.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import unit_test_api +from unit_test_api.model.ref_in_not import RefInNot +from unit_test_api import configuration + + +class TestRefInNot(unittest.TestCase): + """RefInNot unit test stubs""" + _configuration = configuration.Configuration() + + def test_property_named_ref_valid_passes(self): + # property named $ref valid + RefInNot.from_openapi_data_oapg( + { + "$ref": + 2, + }, + _configuration=self._configuration + ) + + def test_property_named_ref_invalid_fails(self): + # property named $ref invalid + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + RefInNot.from_openapi_data_oapg( + { + "$ref": + "a", + }, + _configuration=self._configuration + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_oneof.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_oneof.py similarity index 92% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_oneof.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_oneof.py index f063204479..f21623c8d8 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_oneof.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_oneof.py @@ -22,7 +22,7 @@ class TestRefInOneof(unittest.TestCase): def test_property_named_ref_valid_passes(self): # property named $ref valid - RefInOneof._from_openapi_data( + RefInOneof.from_openapi_data_oapg( { "$ref": "a", @@ -33,7 +33,7 @@ class TestRefInOneof(unittest.TestCase): def test_property_named_ref_invalid_fails(self): # property named $ref invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - RefInOneof._from_openapi_data( + RefInOneof.from_openapi_data_oapg( { "$ref": 2, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_property.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_property.py similarity index 93% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_property.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_property.py index da213d35ed..38113b134f 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_ref_in_property.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_ref_in_property.py @@ -22,7 +22,7 @@ class TestRefInProperty(unittest.TestCase): def test_property_named_ref_valid_passes(self): # property named $ref valid - RefInProperty._from_openapi_data( + RefInProperty.from_openapi_data_oapg( { "a": { @@ -36,7 +36,7 @@ class TestRefInProperty(unittest.TestCase): def test_property_named_ref_invalid_fails(self): # property named $ref invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - RefInProperty._from_openapi_data( + RefInProperty.from_openapi_data_oapg( { "a": { diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_required_default_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_default_validation.py similarity index 93% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_required_default_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_default_validation.py index c17d16842b..839aa6742d 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_required_default_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_default_validation.py @@ -22,7 +22,7 @@ class TestRequiredDefaultValidation(unittest.TestCase): def test_not_required_by_default_passes(self): # not required by default - RequiredDefaultValidation._from_openapi_data( + RequiredDefaultValidation.from_openapi_data_oapg( { }, _configuration=self._configuration diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_required_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_validation.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_required_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_validation.py index 559f0be8d5..9f1f18cc6a 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_required_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_validation.py @@ -22,7 +22,7 @@ class TestRequiredValidation(unittest.TestCase): def test_ignores_arrays_passes(self): # ignores arrays - RequiredValidation._from_openapi_data( + RequiredValidation.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -30,7 +30,7 @@ class TestRequiredValidation(unittest.TestCase): def test_present_required_property_is_valid_passes(self): # present required property is valid - RequiredValidation._from_openapi_data( + RequiredValidation.from_openapi_data_oapg( { "foo": 1, @@ -40,14 +40,14 @@ class TestRequiredValidation(unittest.TestCase): def test_ignores_other_non_objects_passes(self): # ignores other non-objects - RequiredValidation._from_openapi_data( + RequiredValidation.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_ignores_strings_passes(self): # ignores strings - RequiredValidation._from_openapi_data( + RequiredValidation.from_openapi_data_oapg( "", _configuration=self._configuration ) @@ -55,7 +55,7 @@ class TestRequiredValidation(unittest.TestCase): def test_non_present_required_property_is_invalid_fails(self): # non-present required property is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - RequiredValidation._from_openapi_data( + RequiredValidation.from_openapi_data_oapg( { "bar": 1, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_required_with_empty_array.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_with_empty_array.py similarity index 93% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_required_with_empty_array.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_with_empty_array.py index aced932c70..8a42ce63ba 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_required_with_empty_array.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_with_empty_array.py @@ -22,7 +22,7 @@ class TestRequiredWithEmptyArray(unittest.TestCase): def test_property_not_required_passes(self): # property not required - RequiredWithEmptyArray._from_openapi_data( + RequiredWithEmptyArray.from_openapi_data_oapg( { }, _configuration=self._configuration diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_with_escaped_characters.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_with_escaped_characters.py new file mode 100644 index 0000000000..bd327f0981 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_required_with_escaped_characters.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import unit_test_api +from unit_test_api.model.required_with_escaped_characters import RequiredWithEscapedCharacters +from unit_test_api import configuration + + +class TestRequiredWithEscapedCharacters(unittest.TestCase): + """RequiredWithEscapedCharacters unit test stubs""" + _configuration = configuration.Configuration() + + def test_object_with_some_properties_missing_is_invalid_fails(self): + # object with some properties missing is invalid + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + RequiredWithEscapedCharacters.from_openapi_data_oapg( + { + "foo\nbar": + "1", + "foo\"bar": + "1", + }, + _configuration=self._configuration + ) + + def test_object_with_all_properties_present_is_valid_passes(self): + # object with all properties present is valid + RequiredWithEscapedCharacters.from_openapi_data_oapg( + { + "foo\nbar": + 1, + "foo\"bar": + 1, + "foo\\bar": + 1, + "foo\rbar": + 1, + "foo\tbar": + 1, + "foo\fbar": + 1, + }, + _configuration=self._configuration + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_simple_enum_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_simple_enum_validation.py similarity index 90% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_simple_enum_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_simple_enum_validation.py index 56d2746b84..7665812618 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_simple_enum_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_simple_enum_validation.py @@ -23,14 +23,14 @@ class TestSimpleEnumValidation(unittest.TestCase): def test_something_else_is_invalid_fails(self): # something else is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - SimpleEnumValidation._from_openapi_data( + SimpleEnumValidation.from_openapi_data_oapg( 4, _configuration=self._configuration ) def test_one_of_the_enum_is_valid_passes(self): # one of the enum is valid - SimpleEnumValidation._from_openapi_data( + SimpleEnumValidation.from_openapi_data_oapg( 1, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_string_type_matches_strings.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_string_type_matches_strings.py similarity index 83% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_string_type_matches_strings.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_string_type_matches_strings.py index 807e2afe1c..a1990db302 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_string_type_matches_strings.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_string_type_matches_strings.py @@ -23,21 +23,21 @@ class TestStringTypeMatchesStrings(unittest.TestCase): def test_1_is_not_a_string_fails(self): # 1 is not a string with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - StringTypeMatchesStrings._from_openapi_data( + StringTypeMatchesStrings.from_openapi_data_oapg( 1, _configuration=self._configuration ) def test_a_string_is_still_a_string_even_if_it_looks_like_a_number_passes(self): # a string is still a string, even if it looks like a number - StringTypeMatchesStrings._from_openapi_data( + StringTypeMatchesStrings.from_openapi_data_oapg( "1", _configuration=self._configuration ) def test_an_empty_string_is_still_a_string_passes(self): # an empty string is still a string - StringTypeMatchesStrings._from_openapi_data( + StringTypeMatchesStrings.from_openapi_data_oapg( "", _configuration=self._configuration ) @@ -45,7 +45,7 @@ class TestStringTypeMatchesStrings(unittest.TestCase): def test_a_float_is_not_a_string_fails(self): # a float is not a string with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - StringTypeMatchesStrings._from_openapi_data( + StringTypeMatchesStrings.from_openapi_data_oapg( 1.1, _configuration=self._configuration ) @@ -53,7 +53,7 @@ class TestStringTypeMatchesStrings(unittest.TestCase): def test_an_object_is_not_a_string_fails(self): # an object is not a string with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - StringTypeMatchesStrings._from_openapi_data( + StringTypeMatchesStrings.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -62,7 +62,7 @@ class TestStringTypeMatchesStrings(unittest.TestCase): def test_an_array_is_not_a_string_fails(self): # an array is not a string with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - StringTypeMatchesStrings._from_openapi_data( + StringTypeMatchesStrings.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -71,7 +71,7 @@ class TestStringTypeMatchesStrings(unittest.TestCase): def test_a_boolean_is_not_a_string_fails(self): # a boolean is not a string with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - StringTypeMatchesStrings._from_openapi_data( + StringTypeMatchesStrings.from_openapi_data_oapg( True, _configuration=self._configuration ) @@ -79,14 +79,14 @@ class TestStringTypeMatchesStrings(unittest.TestCase): def test_null_is_not_a_string_fails(self): # null is not a string with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - StringTypeMatchesStrings._from_openapi_data( + StringTypeMatchesStrings.from_openapi_data_oapg( None, _configuration=self._configuration ) def test_a_string_is_a_string_passes(self): # a string is a string - StringTypeMatchesStrings._from_openapi_data( + StringTypeMatchesStrings.from_openapi_data_oapg( "foo", _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_the_default_keyword_does_not_do_anything_if_the_property_is_missing.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_the_default_keyword_does_not_do_anything_if_the_property_is_missing.py similarity index 96% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_the_default_keyword_does_not_do_anything_if_the_property_is_missing.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_the_default_keyword_does_not_do_anything_if_the_property_is_missing.py index 4f8e583c41..d3ab488aa5 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_the_default_keyword_does_not_do_anything_if_the_property_is_missing.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_the_default_keyword_does_not_do_anything_if_the_property_is_missing.py @@ -22,7 +22,7 @@ class TestTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing(unittest.Test def test_missing_properties_are_not_filled_in_with_the_default_passes(self): # missing properties are not filled in with the default - TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing._from_openapi_data( + TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,7 +30,7 @@ class TestTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing(unittest.Test def test_an_explicit_property_value_is_checked_against_maximum_passing_passes(self): # an explicit property value is checked against maximum (passing) - TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing._from_openapi_data( + TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.from_openapi_data_oapg( { "alpha": 1, @@ -41,7 +41,7 @@ class TestTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing(unittest.Test def test_an_explicit_property_value_is_checked_against_maximum_failing_fails(self): # an explicit property value is checked against maximum (failing) with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing._from_openapi_data( + TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing.from_openapi_data_oapg( { "alpha": 5, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uniqueitems_false_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uniqueitems_false_validation.py similarity index 87% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uniqueitems_false_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uniqueitems_false_validation.py index afe2f481d7..cda8f76732 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uniqueitems_false_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uniqueitems_false_validation.py @@ -22,7 +22,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_non_unique_array_of_integers_is_valid_passes(self): # non-unique array of integers is valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ 1, 1, @@ -32,7 +32,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_unique_array_of_objects_is_valid_passes(self): # unique array of objects is valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ { "foo": @@ -48,7 +48,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_non_unique_array_of_nested_objects_is_valid_passes(self): # non-unique array of nested objects is valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ { "foo": @@ -76,7 +76,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_non_unique_array_of_objects_is_valid_passes(self): # non-unique array of objects is valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ { "foo": @@ -92,7 +92,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_1_and_true_are_unique_passes(self): # 1 and true are unique - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ 1, True, @@ -102,7 +102,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_unique_array_of_integers_is_valid_passes(self): # unique array of integers is valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ 1, 2, @@ -112,7 +112,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_non_unique_array_of_arrays_is_valid_passes(self): # non-unique array of arrays is valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ [ "foo", @@ -126,7 +126,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_numbers_are_unique_if_mathematically_unequal_passes(self): # numbers are unique if mathematically unequal - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ 1.0, 1.0, @@ -137,7 +137,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_false_is_not_equal_to_zero_passes(self): # false is not equal to zero - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ 0, False, @@ -147,7 +147,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_unique_array_of_nested_objects_is_valid_passes(self): # unique array of nested objects is valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ { "foo": @@ -175,7 +175,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_0_and_false_are_unique_passes(self): # 0 and false are unique - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ 0, False, @@ -185,7 +185,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_unique_array_of_arrays_is_valid_passes(self): # unique array of arrays is valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ [ "foo", @@ -199,7 +199,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_true_is_not_equal_to_one_passes(self): # true is not equal to one - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ 1, True, @@ -209,7 +209,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_non_unique_heterogeneous_types_are_valid_passes(self): # non-unique heterogeneous types are valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ { }, @@ -227,7 +227,7 @@ class TestUniqueitemsFalseValidation(unittest.TestCase): def test_unique_heterogeneous_types_are_valid_passes(self): # unique heterogeneous types are valid - UniqueitemsFalseValidation._from_openapi_data( + UniqueitemsFalseValidation.from_openapi_data_oapg( [ { }, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uniqueitems_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uniqueitems_validation.py similarity index 89% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uniqueitems_validation.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uniqueitems_validation.py index f4032887b6..819beed307 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uniqueitems_validation.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uniqueitems_validation.py @@ -22,7 +22,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_unique_array_of_objects_is_valid_passes(self): # unique array of objects is valid - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { "foo": @@ -38,7 +38,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_a_true_and_a1_are_unique_passes(self): # {"a": true} and {"a": 1} are unique - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { "a": @@ -55,7 +55,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_non_unique_heterogeneous_types_are_invalid_fails(self): # non-unique heterogeneous types are invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { }, @@ -73,7 +73,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_nested0_and_false_are_unique_passes(self): # nested [0] and [false] are unique - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ [ [ @@ -93,7 +93,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_a_false_and_a0_are_unique_passes(self): # {"a": false} and {"a": 0} are unique - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { "a": @@ -110,7 +110,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_numbers_are_unique_if_mathematically_unequal_fails(self): # numbers are unique if mathematically unequal with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ 1.0, 1.0, @@ -121,7 +121,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_false_is_not_equal_to_zero_passes(self): # false is not equal to zero - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ 0, False, @@ -131,7 +131,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_0_and_false_are_unique_passes(self): # [0] and [false] are unique - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ [ 0, @@ -145,7 +145,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_unique_array_of_arrays_is_valid_passes(self): # unique array of arrays is valid - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ [ "foo", @@ -160,7 +160,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_non_unique_array_of_nested_objects_is_invalid_fails(self): # non-unique array of nested objects is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { "foo": @@ -189,7 +189,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_non_unique_array_of_more_than_two_integers_is_invalid_fails(self): # non-unique array of more than two integers is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ 1, 2, @@ -200,7 +200,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_true_is_not_equal_to_one_passes(self): # true is not equal to one - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ 1, True, @@ -211,7 +211,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_objects_are_non_unique_despite_key_order_fails(self): # objects are non-unique despite key order with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { "a": @@ -231,7 +231,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_unique_array_of_strings_is_valid_passes(self): # unique array of strings is valid - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ "foo", "bar", @@ -242,7 +242,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_1_and_true_are_unique_passes(self): # [1] and [true] are unique - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ [ 1, @@ -256,7 +256,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_different_objects_are_unique_passes(self): # different objects are unique - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { "a": @@ -276,7 +276,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_unique_array_of_integers_is_valid_passes(self): # unique array of integers is valid - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ 1, 2, @@ -287,7 +287,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_non_unique_array_of_more_than_two_arrays_is_invalid_fails(self): # non-unique array of more than two arrays is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ [ "foo", @@ -305,7 +305,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_non_unique_array_of_objects_is_invalid_fails(self): # non-unique array of objects is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { "foo": @@ -321,7 +321,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_unique_array_of_nested_objects_is_valid_passes(self): # unique array of nested objects is valid - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { "foo": @@ -350,7 +350,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_non_unique_array_of_arrays_is_invalid_fails(self): # non-unique array of arrays is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ [ "foo", @@ -365,7 +365,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_non_unique_array_of_strings_is_invalid_fails(self): # non-unique array of strings is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ "foo", "bar", @@ -376,7 +376,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_nested1_and_true_are_unique_passes(self): # nested [1] and [true] are unique - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ [ [ @@ -396,7 +396,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_unique_heterogeneous_types_are_valid_passes(self): # unique heterogeneous types are valid - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ { }, @@ -414,7 +414,7 @@ class TestUniqueitemsValidation(unittest.TestCase): def test_non_unique_array_of_integers_is_invalid_fails(self): # non-unique array of integers is invalid with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): - UniqueitemsValidation._from_openapi_data( + UniqueitemsValidation.from_openapi_data_oapg( [ 1, 1, diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uri_format.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uri_format.py similarity index 86% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uri_format.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uri_format.py index 2f6def9024..b44051e385 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uri_format.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uri_format.py @@ -22,7 +22,7 @@ class TestUriFormat(unittest.TestCase): def test_all_string_formats_ignore_objects_passes(self): # all string formats ignore objects - UriFormat._from_openapi_data( + UriFormat.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,28 +30,28 @@ class TestUriFormat(unittest.TestCase): def test_all_string_formats_ignore_booleans_passes(self): # all string formats ignore booleans - UriFormat._from_openapi_data( + UriFormat.from_openapi_data_oapg( False, _configuration=self._configuration ) def test_all_string_formats_ignore_integers_passes(self): # all string formats ignore integers - UriFormat._from_openapi_data( + UriFormat.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_all_string_formats_ignore_floats_passes(self): # all string formats ignore floats - UriFormat._from_openapi_data( + UriFormat.from_openapi_data_oapg( 13.7, _configuration=self._configuration ) def test_all_string_formats_ignore_arrays_passes(self): # all string formats ignore arrays - UriFormat._from_openapi_data( + UriFormat.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -59,7 +59,7 @@ class TestUriFormat(unittest.TestCase): def test_all_string_formats_ignore_nulls_passes(self): # all string formats ignore nulls - UriFormat._from_openapi_data( + UriFormat.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uri_reference_format.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uri_reference_format.py similarity index 84% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uri_reference_format.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uri_reference_format.py index c5508b68bc..4feeaca278 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uri_reference_format.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uri_reference_format.py @@ -22,7 +22,7 @@ class TestUriReferenceFormat(unittest.TestCase): def test_all_string_formats_ignore_objects_passes(self): # all string formats ignore objects - UriReferenceFormat._from_openapi_data( + UriReferenceFormat.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,28 +30,28 @@ class TestUriReferenceFormat(unittest.TestCase): def test_all_string_formats_ignore_booleans_passes(self): # all string formats ignore booleans - UriReferenceFormat._from_openapi_data( + UriReferenceFormat.from_openapi_data_oapg( False, _configuration=self._configuration ) def test_all_string_formats_ignore_integers_passes(self): # all string formats ignore integers - UriReferenceFormat._from_openapi_data( + UriReferenceFormat.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_all_string_formats_ignore_floats_passes(self): # all string formats ignore floats - UriReferenceFormat._from_openapi_data( + UriReferenceFormat.from_openapi_data_oapg( 13.7, _configuration=self._configuration ) def test_all_string_formats_ignore_arrays_passes(self): # all string formats ignore arrays - UriReferenceFormat._from_openapi_data( + UriReferenceFormat.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -59,7 +59,7 @@ class TestUriReferenceFormat(unittest.TestCase): def test_all_string_formats_ignore_nulls_passes(self): # all string formats ignore nulls - UriReferenceFormat._from_openapi_data( + UriReferenceFormat.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uri_template_format.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uri_template_format.py similarity index 85% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uri_template_format.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uri_template_format.py index 456c0794ad..a3e1e2f987 100644 --- a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test/test_uri_template_format.py +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_models/test_uri_template_format.py @@ -22,7 +22,7 @@ class TestUriTemplateFormat(unittest.TestCase): def test_all_string_formats_ignore_objects_passes(self): # all string formats ignore objects - UriTemplateFormat._from_openapi_data( + UriTemplateFormat.from_openapi_data_oapg( { }, _configuration=self._configuration @@ -30,28 +30,28 @@ class TestUriTemplateFormat(unittest.TestCase): def test_all_string_formats_ignore_booleans_passes(self): # all string formats ignore booleans - UriTemplateFormat._from_openapi_data( + UriTemplateFormat.from_openapi_data_oapg( False, _configuration=self._configuration ) def test_all_string_formats_ignore_integers_passes(self): # all string formats ignore integers - UriTemplateFormat._from_openapi_data( + UriTemplateFormat.from_openapi_data_oapg( 12, _configuration=self._configuration ) def test_all_string_formats_ignore_floats_passes(self): # all string formats ignore floats - UriTemplateFormat._from_openapi_data( + UriTemplateFormat.from_openapi_data_oapg( 13.7, _configuration=self._configuration ) def test_all_string_formats_ignore_arrays_passes(self): # all string formats ignore arrays - UriTemplateFormat._from_openapi_data( + UriTemplateFormat.from_openapi_data_oapg( [ ], _configuration=self._configuration @@ -59,7 +59,7 @@ class TestUriTemplateFormat(unittest.TestCase): def test_all_string_formats_ignore_nulls_passes(self): # all string formats ignore nulls - UriTemplateFormat._from_openapi_data( + UriTemplateFormat.from_openapi_data_oapg( None, _configuration=self._configuration ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/__init__.py new file mode 100644 index 0000000000..1309632d3d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/__init__.py @@ -0,0 +1,68 @@ +import json +import typing + +import urllib3 +from urllib3._collections import HTTPHeaderDict + + +class ApiTestMixin: + json_content_type = 'application/json' + user_agent = 'OpenAPI-Generator/1.0.0/python' + + @classmethod + def assert_pool_manager_request_called_with( + cls, + mock_request, + url: str, + method: str = 'POST', + body: typing.Optional[bytes] = None, + content_type: typing.Optional[str] = None, + accept_content_type: typing.Optional[str] = None, + stream: bool = False, + ): + headers = { + 'User-Agent': cls.user_agent + } + if accept_content_type: + headers['Accept'] = accept_content_type + if content_type: + headers['Content-Type'] = content_type + kwargs = dict( + headers=HTTPHeaderDict(headers), + preload_content=not stream, + timeout=None, + ) + if content_type and method != 'GET': + kwargs['body'] = body + mock_request.assert_called_with( + method, + url, + **kwargs + ) + + @staticmethod + def headers_for_content_type(content_type: str) -> typing.Dict[str, str]: + return {'content-type': content_type} + + @classmethod + def response( + cls, + body: typing.Union[str, bytes], + status: int = 200, + content_type: str = json_content_type, + headers: typing.Optional[typing.Dict[str, str]] = None, + preload_content: bool = True + ) -> urllib3.HTTPResponse: + if headers is None: + headers = {} + headers.update(cls.headers_for_content_type(content_type)) + return urllib3.HTTPResponse( + body, + headers=headers, + status=status, + preload_content=preload_content + ) + + @staticmethod + def json_bytes(in_data: typing.Any) -> bytes: + return json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode('utf-8') diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/apis/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/__init__.py similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/apis/__init__.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/__init__.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/test_post.py new file mode 100644 index 0000000000..1ec438f9e0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/test_post.py @@ -0,0 +1,132 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_no_additional_properties_is_valid_passes(self): + content_type = 'application/json' + # no additional properties is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_an_additional_invalid_property_is_invalid_fails(self): + content_type = 'application/json' + # an additional invalid property is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "quux": + 12, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_additional_valid_property_is_valid_passes(self): + content_type = 'application/json' + # an additional valid property is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "quux": + True, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/test/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_are_allowed_by_default_request_body/__init__.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/test/__init__.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_are_allowed_by_default_request_body/__init__.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_are_allowed_by_default_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_are_allowed_by_default_request_body/test_post.py new file mode 100644 index 0000000000..51206546a3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_are_allowed_by_default_request_body/test_post.py @@ -0,0 +1,78 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_additionalproperties_are_allowed_by_default_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAdditionalpropertiesAreAllowedByDefaultRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAdditionalpropertiesAreAllowedByDefaultRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_additional_properties_are_allowed_passes(self): + content_type = 'application/json' + # additional properties are allowed + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "quux": + True, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_can_exist_by_itself_request_body/__init__.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/test/__init__.py rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_can_exist_by_itself_request_body/__init__.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_can_exist_by_itself_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_can_exist_by_itself_request_body/test_post.py new file mode 100644 index 0000000000..6ef684d7aa --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_can_exist_by_itself_request_body/test_post.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_additionalproperties_can_exist_by_itself_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAdditionalpropertiesCanExistByItselfRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAdditionalpropertiesCanExistByItselfRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_an_additional_invalid_property_is_invalid_fails(self): + content_type = 'application/json' + # an additional invalid property is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_additional_valid_property_is_valid_passes(self): + content_type = 'application/json' + # an additional valid property is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + True, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAdditionalpropertiesCanExistByItselfRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/rust/reqwest/fileResponseTest/src/models/mod.rs b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_should_not_look_in_applicators_request_body/__init__.py similarity index 100% rename from samples/client/petstore/rust/reqwest/fileResponseTest/src/models/mod.rs rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_should_not_look_in_applicators_request_body/__init__.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_should_not_look_in_applicators_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_should_not_look_in_applicators_request_body/test_post.py new file mode 100644 index 0000000000..b8eadc2525 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_additionalproperties_should_not_look_in_applicators_request_body/test_post.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_additionalproperties_should_not_look_in_applicators_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_properties_defined_in_allof_are_not_examined_fails(self): + content_type = 'application/json' + # properties defined in allOf are not examined + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + True, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_valid_test_case_passes(self): + content_type = 'application/json' + # valid test case + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + False, + "bar": + True, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/java/native/gradle.properties b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_combined_with_anyof_oneof_request_body/__init__.py similarity index 100% rename from samples/openapi3/client/petstore/java/native/gradle.properties rename to samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_combined_with_anyof_oneof_request_body/__init__.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_combined_with_anyof_oneof_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_combined_with_anyof_oneof_request_body/test_post.py new file mode 100644 index 0000000000..d1c7dc2125 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_combined_with_anyof_oneof_request_body/test_post.py @@ -0,0 +1,169 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_allof_combined_with_anyof_oneof_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAllofCombinedWithAnyofOneofRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAllofCombinedWithAnyofOneofRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_allof_true_anyof_false_oneof_false_fails(self): + content_type = 'application/json' + # allOf: true, anyOf: false, oneOf: false + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_allof_false_anyof_false_oneof_true_fails(self): + content_type = 'application/json' + # allOf: false, anyOf: false, oneOf: true + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 5 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_allof_false_anyof_true_oneof_true_fails(self): + content_type = 'application/json' + # allOf: false, anyOf: true, oneOf: true + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 15 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_allof_true_anyof_true_oneof_false_fails(self): + content_type = 'application/json' + # allOf: true, anyOf: true, oneOf: false + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 6 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_allof_true_anyof_true_oneof_true_passes(self): + content_type = 'application/json' + # allOf: true, anyOf: true, oneOf: true + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 30 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAllofCombinedWithAnyofOneofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_allof_true_anyof_false_oneof_true_fails(self): + content_type = 'application/json' + # allOf: true, anyOf: false, oneOf: true + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 10 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_allof_false_anyof_true_oneof_false_fails(self): + content_type = 'application/json' + # allOf: false, anyOf: true, oneOf: false + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_allof_false_anyof_false_oneof_false_fails(self): + content_type = 'application/json' + # allOf: false, anyOf: false, oneOf: false + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_request_body/test_post.py new file mode 100644 index 0000000000..b5b226da39 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_request_body/test_post.py @@ -0,0 +1,129 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_allof_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAllofRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAllofRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_allof_passes(self): + content_type = 'application/json' + # allOf + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + "bar": + 2, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAllofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_mismatch_first_fails(self): + content_type = 'application/json' + # mismatch first + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_mismatch_second_fails(self): + content_type = 'application/json' + # mismatch second + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_wrong_type_fails(self): + content_type = 'application/json' + # wrong type + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + "bar": + "quux", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_simple_types_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_simple_types_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_simple_types_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_simple_types_request_body/test_post.py new file mode 100644 index 0000000000..9bc320bd60 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_simple_types_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_allof_simple_types_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAllofSimpleTypesRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAllofSimpleTypesRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_valid_passes(self): + content_type = 'application/json' + # valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 25 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAllofSimpleTypesRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_mismatch_one_fails(self): + content_type = 'application/json' + # mismatch one + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 35 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_base_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_base_schema_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_base_schema_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_base_schema_request_body/test_post.py new file mode 100644 index 0000000000..b9cbf29522 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_base_schema_request_body/test_post.py @@ -0,0 +1,152 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_allof_with_base_schema_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAllofWithBaseSchemaRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAllofWithBaseSchemaRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_valid_passes(self): + content_type = 'application/json' + # valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "quux", + "bar": + 2, + "baz": + None, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAllofWithBaseSchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_mismatch_first_allof_fails(self): + content_type = 'application/json' + # mismatch first allOf + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + "baz": + None, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_mismatch_base_schema_fails(self): + content_type = 'application/json' + # mismatch base schema + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "quux", + "baz": + None, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_mismatch_both_fails(self): + content_type = 'application/json' + # mismatch both + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_mismatch_second_allof_fails(self): + content_type = 'application/json' + # mismatch second allOf + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "quux", + "bar": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_one_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_one_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_one_empty_schema_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_one_empty_schema_request_body/test_post.py new file mode 100644 index 0000000000..908bd1ca7b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_one_empty_schema_request_body/test_post.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_allof_with_one_empty_schema_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAllofWithOneEmptySchemaRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAllofWithOneEmptySchemaRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_any_data_is_valid_passes(self): + content_type = 'application/json' + # any data is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAllofWithOneEmptySchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_first_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_first_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_first_empty_schema_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_first_empty_schema_request_body/test_post.py new file mode 100644 index 0000000000..72bd0bed2b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_first_empty_schema_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_allof_with_the_first_empty_schema_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAllofWithTheFirstEmptySchemaRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAllofWithTheFirstEmptySchemaRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_string_is_invalid_fails(self): + content_type = 'application/json' + # string is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_number_is_valid_passes(self): + content_type = 'application/json' + # number is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAllofWithTheFirstEmptySchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_last_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_last_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_last_empty_schema_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_last_empty_schema_request_body/test_post.py new file mode 100644 index 0000000000..46ab77081d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_the_last_empty_schema_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_allof_with_the_last_empty_schema_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAllofWithTheLastEmptySchemaRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAllofWithTheLastEmptySchemaRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_string_is_invalid_fails(self): + content_type = 'application/json' + # string is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_number_is_valid_passes(self): + content_type = 'application/json' + # number is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAllofWithTheLastEmptySchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_two_empty_schemas_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_two_empty_schemas_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_two_empty_schemas_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_two_empty_schemas_request_body/test_post.py new file mode 100644 index 0000000000..7457f41818 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_allof_with_two_empty_schemas_request_body/test_post.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_allof_with_two_empty_schemas_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAllofWithTwoEmptySchemasRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAllofWithTwoEmptySchemasRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_any_data_is_valid_passes(self): + content_type = 'application/json' + # any data is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAllofWithTwoEmptySchemasRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_complex_types_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_complex_types_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_complex_types_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_complex_types_request_body/test_post.py new file mode 100644 index 0000000000..2cd85be49f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_complex_types_request_body/test_post.py @@ -0,0 +1,161 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_anyof_complex_types_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAnyofComplexTypesRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAnyofComplexTypesRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_second_anyof_valid_complex_passes(self): + content_type = 'application/json' + # second anyOf valid (complex) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAnyofComplexTypesRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_neither_anyof_valid_complex_fails(self): + content_type = 'application/json' + # neither anyOf valid (complex) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 2, + "bar": + "quux", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_both_anyof_valid_complex_passes(self): + content_type = 'application/json' + # both anyOf valid (complex) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + "bar": + 2, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAnyofComplexTypesRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_first_anyof_valid_complex_passes(self): + content_type = 'application/json' + # first anyOf valid (complex) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAnyofComplexTypesRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_request_body/test_post.py new file mode 100644 index 0000000000..8405d6e318 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_request_body/test_post.py @@ -0,0 +1,145 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_anyof_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAnyofRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAnyofRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_second_anyof_valid_passes(self): + content_type = 'application/json' + # second anyOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2.5 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAnyofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_neither_anyof_valid_fails(self): + content_type = 'application/json' + # neither anyOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.5 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_both_anyof_valid_passes(self): + content_type = 'application/json' + # both anyOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAnyofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_first_anyof_valid_passes(self): + content_type = 'application/json' + # first anyOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAnyofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_base_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_base_schema_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_base_schema_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_base_schema_request_body/test_post.py new file mode 100644 index 0000000000..7db203a0e1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_base_schema_request_body/test_post.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_anyof_with_base_schema_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAnyofWithBaseSchemaRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAnyofWithBaseSchemaRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_one_anyof_valid_passes(self): + content_type = 'application/json' + # one anyOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foobar" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAnyofWithBaseSchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_both_anyof_invalid_fails(self): + content_type = 'application/json' + # both anyOf invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_mismatch_base_schema_fails(self): + content_type = 'application/json' + # mismatch base schema + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_one_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_one_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_one_empty_schema_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_one_empty_schema_request_body/test_post.py new file mode 100644 index 0000000000..15e0575d87 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_anyof_with_one_empty_schema_request_body/test_post.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_anyof_with_one_empty_schema_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostAnyofWithOneEmptySchemaRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostAnyofWithOneEmptySchemaRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_string_is_valid_passes(self): + content_type = 'application/json' + # string is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAnyofWithOneEmptySchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_number_is_valid_passes(self): + content_type = 'application/json' + # number is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postAnyofWithOneEmptySchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_array_type_matches_arrays_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_array_type_matches_arrays_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_array_type_matches_arrays_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_array_type_matches_arrays_request_body/test_post.py new file mode 100644 index 0000000000..6132d9c26b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_array_type_matches_arrays_request_body/test_post.py @@ -0,0 +1,157 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_array_type_matches_arrays_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostArrayTypeMatchesArraysRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostArrayTypeMatchesArraysRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_a_float_is_not_an_array_fails(self): + content_type = 'application/json' + # a float is not an array + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_boolean_is_not_an_array_fails(self): + content_type = 'application/json' + # a boolean is not an array + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_not_an_array_fails(self): + content_type = 'application/json' + # null is not an array + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_object_is_not_an_array_fails(self): + content_type = 'application/json' + # an object is not an array + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_string_is_not_an_array_fails(self): + content_type = 'application/json' + # a string is not an array + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_array_is_an_array_passes(self): + content_type = 'application/json' + # an array is an array + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postArrayTypeMatchesArraysRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_an_integer_is_not_an_array_fails(self): + content_type = 'application/json' + # an integer is not an array + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_boolean_type_matches_booleans_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_boolean_type_matches_booleans_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_boolean_type_matches_booleans_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_boolean_type_matches_booleans_request_body/test_post.py new file mode 100644 index 0000000000..3755adac41 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_boolean_type_matches_booleans_request_body/test_post.py @@ -0,0 +1,215 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_boolean_type_matches_booleans_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostBooleanTypeMatchesBooleansRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostBooleanTypeMatchesBooleansRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_an_empty_string_is_not_a_boolean_fails(self): + content_type = 'application/json' + # an empty string is not a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_float_is_not_a_boolean_fails(self): + content_type = 'application/json' + # a float is not a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_not_a_boolean_fails(self): + content_type = 'application/json' + # null is not a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_zero_is_not_a_boolean_fails(self): + content_type = 'application/json' + # zero is not a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_array_is_not_a_boolean_fails(self): + content_type = 'application/json' + # an array is not a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_string_is_not_a_boolean_fails(self): + content_type = 'application/json' + # a string is not a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_false_is_a_boolean_passes(self): + content_type = 'application/json' + # false is a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postBooleanTypeMatchesBooleansRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_an_integer_is_not_a_boolean_fails(self): + content_type = 'application/json' + # an integer is not a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_true_is_a_boolean_passes(self): + content_type = 'application/json' + # true is a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postBooleanTypeMatchesBooleansRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_an_object_is_not_a_boolean_fails(self): + content_type = 'application/json' + # an object is not a boolean + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_int_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_int_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_int_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_int_request_body/test_post.py new file mode 100644 index 0000000000..6792b35353 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_int_request_body/test_post.py @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_by_int_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostByIntRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostByIntRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_int_by_int_fail_fails(self): + content_type = 'application/json' + # int by int fail + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 7 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_int_by_int_passes(self): + content_type = 'application/json' + # int by int + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 10 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postByIntRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_non_numbers_passes(self): + content_type = 'application/json' + # ignores non-numbers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postByIntRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_number_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_number_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_number_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_number_request_body/test_post.py new file mode 100644 index 0000000000..71cf382735 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_number_request_body/test_post.py @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_by_number_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostByNumberRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostByNumberRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_45_is_multiple_of15_passes(self): + content_type = 'application/json' + # 4.5 is multiple of 1.5 + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 4.5 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postByNumberRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_35_is_not_multiple_of15_fails(self): + content_type = 'application/json' + # 35 is not multiple of 1.5 + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 35 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_zero_is_multiple_of_anything_passes(self): + content_type = 'application/json' + # zero is multiple of anything + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postByNumberRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_small_number_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_small_number_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_small_number_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_small_number_request_body/test_post.py new file mode 100644 index 0000000000..f16340e5b9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_by_small_number_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_by_small_number_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostBySmallNumberRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostBySmallNumberRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_000751_is_not_multiple_of00001_fails(self): + content_type = 'application/json' + # 0.00751 is not multiple of 0.0001 + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.00751 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_00075_is_multiple_of00001_passes(self): + content_type = 'application/json' + # 0.0075 is multiple of 0.0001 + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.0075 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postBySmallNumberRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_date_time_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_date_time_format_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_date_time_format_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_date_time_format_request_body/test_post.py new file mode 100644 index 0000000000..51f2f2fd42 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_date_time_format_request_body/test_post.py @@ -0,0 +1,223 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_date_time_format_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostDateTimeFormatRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostDateTimeFormatRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_all_string_formats_ignore_objects_passes(self): + content_type = 'application/json' + # all string formats ignore objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postDateTimeFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_booleans_passes(self): + content_type = 'application/json' + # all string formats ignore booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postDateTimeFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_integers_passes(self): + content_type = 'application/json' + # all string formats ignore integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postDateTimeFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_floats_passes(self): + content_type = 'application/json' + # all string formats ignore floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postDateTimeFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_arrays_passes(self): + content_type = 'application/json' + # all string formats ignore arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postDateTimeFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_nulls_passes(self): + content_type = 'application/json' + # all string formats ignore nulls + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postDateTimeFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_email_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_email_format_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_email_format_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_email_format_request_body/test_post.py new file mode 100644 index 0000000000..4d1a472e3b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_email_format_request_body/test_post.py @@ -0,0 +1,223 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_email_format_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostEmailFormatRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostEmailFormatRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_all_string_formats_ignore_objects_passes(self): + content_type = 'application/json' + # all string formats ignore objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEmailFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_booleans_passes(self): + content_type = 'application/json' + # all string formats ignore booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEmailFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_integers_passes(self): + content_type = 'application/json' + # all string formats ignore integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEmailFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_floats_passes(self): + content_type = 'application/json' + # all string formats ignore floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEmailFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_arrays_passes(self): + content_type = 'application/json' + # all string formats ignore arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEmailFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_nulls_passes(self): + content_type = 'application/json' + # all string formats ignore nulls + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEmailFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with0_does_not_match_false_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with0_does_not_match_false_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with0_does_not_match_false_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with0_does_not_match_false_request_body/test_post.py new file mode 100644 index 0000000000..c58a7e635a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with0_does_not_match_false_request_body/test_post.py @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_enum_with0_does_not_match_false_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostEnumWith0DoesNotMatchFalseRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostEnumWith0DoesNotMatchFalseRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_integer_zero_is_valid_passes(self): + content_type = 'application/json' + # integer zero is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumWith0DoesNotMatchFalseRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_float_zero_is_valid_passes(self): + content_type = 'application/json' + # float zero is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumWith0DoesNotMatchFalseRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_false_is_invalid_fails(self): + content_type = 'application/json' + # false is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with1_does_not_match_true_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with1_does_not_match_true_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with1_does_not_match_true_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with1_does_not_match_true_request_body/test_post.py new file mode 100644 index 0000000000..837485e2b9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with1_does_not_match_true_request_body/test_post.py @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_enum_with1_does_not_match_true_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostEnumWith1DoesNotMatchTrueRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostEnumWith1DoesNotMatchTrueRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_true_is_invalid_fails(self): + content_type = 'application/json' + # true is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_integer_one_is_valid_passes(self): + content_type = 'application/json' + # integer one is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumWith1DoesNotMatchTrueRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_float_one_is_valid_passes(self): + content_type = 'application/json' + # float one is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumWith1DoesNotMatchTrueRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_escaped_characters_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_escaped_characters_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_escaped_characters_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_escaped_characters_request_body/test_post.py new file mode 100644 index 0000000000..2aaa5a405e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_escaped_characters_request_body/test_post.py @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_enum_with_escaped_characters_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostEnumWithEscapedCharactersRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostEnumWithEscapedCharactersRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_member2_is_valid_passes(self): + content_type = 'application/json' + # member 2 is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo\rbar" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumWithEscapedCharactersRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_member1_is_valid_passes(self): + content_type = 'application/json' + # member 1 is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo\nbar" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumWithEscapedCharactersRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_another_string_is_invalid_fails(self): + content_type = 'application/json' + # another string is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "abc" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_false_does_not_match0_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_false_does_not_match0_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_false_does_not_match0_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_false_does_not_match0_request_body/test_post.py new file mode 100644 index 0000000000..f68456be55 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_false_does_not_match0_request_body/test_post.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_enum_with_false_does_not_match0_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostEnumWithFalseDoesNotMatch0RequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostEnumWithFalseDoesNotMatch0RequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_false_is_valid_passes(self): + content_type = 'application/json' + # false is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumWithFalseDoesNotMatch0RequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_float_zero_is_invalid_fails(self): + content_type = 'application/json' + # float zero is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.0 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_integer_zero_is_invalid_fails(self): + content_type = 'application/json' + # integer zero is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_true_does_not_match1_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_true_does_not_match1_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_true_does_not_match1_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_true_does_not_match1_request_body/test_post.py new file mode 100644 index 0000000000..36fc116919 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enum_with_true_does_not_match1_request_body/test_post.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_enum_with_true_does_not_match1_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostEnumWithTrueDoesNotMatch1RequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostEnumWithTrueDoesNotMatch1RequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_float_one_is_invalid_fails(self): + content_type = 'application/json' + # float one is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_true_is_valid_passes(self): + content_type = 'application/json' + # true is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumWithTrueDoesNotMatch1RequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_integer_one_is_invalid_fails(self): + content_type = 'application/json' + # integer one is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enums_in_properties_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enums_in_properties_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enums_in_properties_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enums_in_properties_request_body/test_post.py new file mode 100644 index 0000000000..9244bfd182 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_enums_in_properties_request_body/test_post.py @@ -0,0 +1,179 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_enums_in_properties_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostEnumsInPropertiesRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostEnumsInPropertiesRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_missing_optional_property_is_valid_passes(self): + content_type = 'application/json' + # missing optional property is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + "bar", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumsInPropertiesRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_wrong_foo_value_fails(self): + content_type = 'application/json' + # wrong foo value + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "foot", + "bar": + "bar", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_both_properties_are_valid_passes(self): + content_type = 'application/json' + # both properties are valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "foo", + "bar": + "bar", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postEnumsInPropertiesRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_wrong_bar_value_fails(self): + content_type = 'application/json' + # wrong bar value + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "foo", + "bar": + "bart", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_missing_all_properties_is_invalid_fails(self): + content_type = 'application/json' + # missing all properties is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_missing_required_property_is_invalid_fails(self): + content_type = 'application/json' + # missing required property is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "foo", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_forbidden_property_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_forbidden_property_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_forbidden_property_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_forbidden_property_request_body/test_post.py new file mode 100644 index 0000000000..38f04c4f87 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_forbidden_property_request_body/test_post.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_forbidden_property_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostForbiddenPropertyRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostForbiddenPropertyRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_present_fails(self): + content_type = 'application/json' + # property present + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_property_absent_passes(self): + content_type = 'application/json' + # property absent + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 1, + "baz": + 2, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postForbiddenPropertyRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_hostname_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_hostname_format_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_hostname_format_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_hostname_format_request_body/test_post.py new file mode 100644 index 0000000000..b626fef6e2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_hostname_format_request_body/test_post.py @@ -0,0 +1,223 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_hostname_format_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostHostnameFormatRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostHostnameFormatRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_all_string_formats_ignore_objects_passes(self): + content_type = 'application/json' + # all string formats ignore objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postHostnameFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_booleans_passes(self): + content_type = 'application/json' + # all string formats ignore booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postHostnameFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_integers_passes(self): + content_type = 'application/json' + # all string formats ignore integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postHostnameFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_floats_passes(self): + content_type = 'application/json' + # all string formats ignore floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postHostnameFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_arrays_passes(self): + content_type = 'application/json' + # all string formats ignore arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postHostnameFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_nulls_passes(self): + content_type = 'application/json' + # all string formats ignore nulls + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postHostnameFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_integer_type_matches_integers_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_integer_type_matches_integers_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_integer_type_matches_integers_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_integer_type_matches_integers_request_body/test_post.py new file mode 100644 index 0000000000..d30a2776da --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_integer_type_matches_integers_request_body/test_post.py @@ -0,0 +1,201 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_integer_type_matches_integers_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostIntegerTypeMatchesIntegersRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostIntegerTypeMatchesIntegersRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_an_object_is_not_an_integer_fails(self): + content_type = 'application/json' + # an object is not an integer + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_string_is_not_an_integer_fails(self): + content_type = 'application/json' + # a string is not an integer + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_not_an_integer_fails(self): + content_type = 'application/json' + # null is not an integer + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_float_with_zero_fractional_part_is_an_integer_passes(self): + content_type = 'application/json' + # a float with zero fractional part is an integer + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIntegerTypeMatchesIntegersRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_float_is_not_an_integer_fails(self): + content_type = 'application/json' + # a float is not an integer + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_boolean_is_not_an_integer_fails(self): + content_type = 'application/json' + # a boolean is not an integer + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_integer_is_an_integer_passes(self): + content_type = 'application/json' + # an integer is an integer + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIntegerTypeMatchesIntegersRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_string_is_still_not_an_integer_even_if_it_looks_like_one_fails(self): + content_type = 'application/json' + # a string is still not an integer, even if it looks like one + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "1" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_array_is_not_an_integer_fails(self): + content_type = 'application/json' + # an array is not an integer + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/test_post.py new file mode 100644 index 0000000000..c2ff2adebe --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_always_invalid_but_naive_implementations_may_raise_an_overflow_error_fails(self): + content_type = 'application/json' + # always invalid, but naive implementations may raise an overflow error + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0E308 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_valid_integer_with_multipleof_float_passes(self): + content_type = 'application/json' + # valid integer with multipleOf float + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123456789 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_string_value_for_default_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_string_value_for_default_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_string_value_for_default_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_string_value_for_default_request_body/test_post.py new file mode 100644 index 0000000000..e3d1edeeee --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_invalid_string_value_for_default_request_body/test_post.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_invalid_string_value_for_default_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostInvalidStringValueForDefaultRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostInvalidStringValueForDefaultRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_valid_when_property_is_specified_passes(self): + content_type = 'application/json' + # valid when property is specified + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + "good", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postInvalidStringValueForDefaultRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_still_valid_when_the_invalid_default_is_used_passes(self): + content_type = 'application/json' + # still valid when the invalid default is used + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postInvalidStringValueForDefaultRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv4_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv4_format_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv4_format_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv4_format_request_body/test_post.py new file mode 100644 index 0000000000..0c7408ba02 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv4_format_request_body/test_post.py @@ -0,0 +1,223 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_ipv4_format_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostIpv4FormatRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostIpv4FormatRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_all_string_formats_ignore_objects_passes(self): + content_type = 'application/json' + # all string formats ignore objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv4FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_booleans_passes(self): + content_type = 'application/json' + # all string formats ignore booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv4FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_integers_passes(self): + content_type = 'application/json' + # all string formats ignore integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv4FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_floats_passes(self): + content_type = 'application/json' + # all string formats ignore floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv4FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_arrays_passes(self): + content_type = 'application/json' + # all string formats ignore arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv4FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_nulls_passes(self): + content_type = 'application/json' + # all string formats ignore nulls + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv4FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv6_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv6_format_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv6_format_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv6_format_request_body/test_post.py new file mode 100644 index 0000000000..19214ebb3a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ipv6_format_request_body/test_post.py @@ -0,0 +1,223 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_ipv6_format_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostIpv6FormatRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostIpv6FormatRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_all_string_formats_ignore_objects_passes(self): + content_type = 'application/json' + # all string formats ignore objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv6FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_booleans_passes(self): + content_type = 'application/json' + # all string formats ignore booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv6FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_integers_passes(self): + content_type = 'application/json' + # all string formats ignore integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv6FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_floats_passes(self): + content_type = 'application/json' + # all string formats ignore floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv6FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_arrays_passes(self): + content_type = 'application/json' + # all string formats ignore arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv6FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_nulls_passes(self): + content_type = 'application/json' + # all string formats ignore nulls + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postIpv6FormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_json_pointer_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_json_pointer_format_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_json_pointer_format_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_json_pointer_format_request_body/test_post.py new file mode 100644 index 0000000000..ae8f171dd6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_json_pointer_format_request_body/test_post.py @@ -0,0 +1,223 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_json_pointer_format_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostJsonPointerFormatRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostJsonPointerFormatRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_all_string_formats_ignore_objects_passes(self): + content_type = 'application/json' + # all string formats ignore objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postJsonPointerFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_booleans_passes(self): + content_type = 'application/json' + # all string formats ignore booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postJsonPointerFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_integers_passes(self): + content_type = 'application/json' + # all string formats ignore integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postJsonPointerFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_floats_passes(self): + content_type = 'application/json' + # all string formats ignore floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postJsonPointerFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_arrays_passes(self): + content_type = 'application/json' + # all string formats ignore arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postJsonPointerFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_nulls_passes(self): + content_type = 'application/json' + # all string formats ignore nulls + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postJsonPointerFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_request_body/test_post.py new file mode 100644 index 0000000000..d16fe2926b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_request_body/test_post.py @@ -0,0 +1,145 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_maximum_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMaximumValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMaximumValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_below_the_maximum_is_valid_passes(self): + content_type = 'application/json' + # below the maximum is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2.6 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaximumValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_boundary_point_is_valid_passes(self): + content_type = 'application/json' + # boundary point is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3.0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaximumValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_above_the_maximum_is_invalid_fails(self): + content_type = 'application/json' + # above the maximum is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3.5 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_ignores_non_numbers_passes(self): + content_type = 'application/json' + # ignores non-numbers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "x" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaximumValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_with_unsigned_integer_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_with_unsigned_integer_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_with_unsigned_integer_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_with_unsigned_integer_request_body/test_post.py new file mode 100644 index 0000000000..e26b9b2dae --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maximum_validation_with_unsigned_integer_request_body/test_post.py @@ -0,0 +1,145 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_maximum_validation_with_unsigned_integer_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMaximumValidationWithUnsignedIntegerRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMaximumValidationWithUnsignedIntegerRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_below_the_maximum_is_invalid_passes(self): + content_type = 'application/json' + # below the maximum is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 299.97 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaximumValidationWithUnsignedIntegerRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_above_the_maximum_is_invalid_fails(self): + content_type = 'application/json' + # above the maximum is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 300.5 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_boundary_point_integer_is_valid_passes(self): + content_type = 'application/json' + # boundary point integer is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 300 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaximumValidationWithUnsignedIntegerRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_boundary_point_float_is_valid_passes(self): + content_type = 'application/json' + # boundary point float is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 300.0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaximumValidationWithUnsignedIntegerRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxitems_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxitems_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxitems_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxitems_validation_request_body/test_post.py new file mode 100644 index 0000000000..de8c99ca79 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxitems_validation_request_body/test_post.py @@ -0,0 +1,154 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_maxitems_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMaxitemsValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMaxitemsValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_too_long_is_invalid_fails(self): + content_type = 'application/json' + # too long is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + 3, + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_ignores_non_arrays_passes(self): + content_type = 'application/json' + # ignores non-arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foobar" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_shorter_is_valid_passes(self): + content_type = 'application/json' + # shorter is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_exact_length_is_valid_passes(self): + content_type = 'application/json' + # exact length is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxlength_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxlength_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxlength_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxlength_validation_request_body/test_post.py new file mode 100644 index 0000000000..8443176e95 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxlength_validation_request_body/test_post.py @@ -0,0 +1,175 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_maxlength_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMaxlengthValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMaxlengthValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_too_long_is_invalid_fails(self): + content_type = 'application/json' + # too long is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_ignores_non_strings_passes(self): + content_type = 'application/json' + # ignores non-strings + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 100 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxlengthValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_shorter_is_valid_passes(self): + content_type = 'application/json' + # shorter is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "f" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxlengthValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_two_supplementary_unicode_code_points_is_long_enough_passes(self): + content_type = 'application/json' + # two supplementary Unicode code points is long enough + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "💩💩" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxlengthValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_exact_length_is_valid_passes(self): + content_type = 'application/json' + # exact length is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "fo" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxlengthValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties0_means_the_object_is_empty_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties0_means_the_object_is_empty_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties0_means_the_object_is_empty_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties0_means_the_object_is_empty_request_body/test_post.py new file mode 100644 index 0000000000..53c93f5ba2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties0_means_the_object_is_empty_request_body/test_post.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_maxproperties0_means_the_object_is_empty_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMaxproperties0MeansTheObjectIsEmptyRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMaxproperties0MeansTheObjectIsEmptyRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_no_properties_is_valid_passes(self): + content_type = 'application/json' + # no properties is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_one_property_is_invalid_fails(self): + content_type = 'application/json' + # one property is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties_validation_request_body/test_post.py new file mode 100644 index 0000000000..75849461f6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_maxproperties_validation_request_body/test_post.py @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_maxproperties_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMaxpropertiesValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMaxpropertiesValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_too_long_is_invalid_fails(self): + content_type = 'application/json' + # too long is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "baz": + 3, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_ignores_arrays_passes(self): + content_type = 'application/json' + # ignores arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + 3, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_other_non_objects_passes(self): + content_type = 'application/json' + # ignores other non-objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_strings_passes(self): + content_type = 'application/json' + # ignores strings + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foobar" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_shorter_is_valid_passes(self): + content_type = 'application/json' + # shorter is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_exact_length_is_valid_passes(self): + content_type = 'application/json' + # exact length is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMaxpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_request_body/test_post.py new file mode 100644 index 0000000000..b637e0e80a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_request_body/test_post.py @@ -0,0 +1,145 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_minimum_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMinimumValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMinimumValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_boundary_point_is_valid_passes(self): + content_type = 'application/json' + # boundary point is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinimumValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_below_the_minimum_is_invalid_fails(self): + content_type = 'application/json' + # below the minimum is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.6 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_above_the_minimum_is_valid_passes(self): + content_type = 'application/json' + # above the minimum is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2.6 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinimumValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_non_numbers_passes(self): + content_type = 'application/json' + # ignores non-numbers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "x" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinimumValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_with_signed_integer_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_with_signed_integer_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_with_signed_integer_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_with_signed_integer_request_body/test_post.py new file mode 100644 index 0000000000..37dab1a048 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minimum_validation_with_signed_integer_request_body/test_post.py @@ -0,0 +1,219 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_minimum_validation_with_signed_integer_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMinimumValidationWithSignedIntegerRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMinimumValidationWithSignedIntegerRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_boundary_point_is_valid_passes(self): + content_type = 'application/json' + # boundary point is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -2 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinimumValidationWithSignedIntegerRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_positive_above_the_minimum_is_valid_passes(self): + content_type = 'application/json' + # positive above the minimum is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinimumValidationWithSignedIntegerRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_int_below_the_minimum_is_invalid_fails(self): + content_type = 'application/json' + # int below the minimum is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -3 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_float_below_the_minimum_is_invalid_fails(self): + content_type = 'application/json' + # float below the minimum is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -2.0001 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_boundary_point_with_float_is_valid_passes(self): + content_type = 'application/json' + # boundary point with float is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -2.0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinimumValidationWithSignedIntegerRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_negative_above_the_minimum_is_valid_passes(self): + content_type = 'application/json' + # negative above the minimum is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinimumValidationWithSignedIntegerRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_non_numbers_passes(self): + content_type = 'application/json' + # ignores non-numbers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "x" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinimumValidationWithSignedIntegerRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minitems_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minitems_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minitems_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minitems_validation_request_body/test_post.py new file mode 100644 index 0000000000..af54b84112 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minitems_validation_request_body/test_post.py @@ -0,0 +1,151 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_minitems_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMinitemsValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMinitemsValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_too_short_is_invalid_fails(self): + content_type = 'application/json' + # too short is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_ignores_non_arrays_passes(self): + content_type = 'application/json' + # ignores non-arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_longer_is_valid_passes(self): + content_type = 'application/json' + # longer is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_exact_length_is_valid_passes(self): + content_type = 'application/json' + # exact length is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minlength_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minlength_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minlength_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minlength_validation_request_body/test_post.py new file mode 100644 index 0000000000..1a1db934bb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minlength_validation_request_body/test_post.py @@ -0,0 +1,159 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_minlength_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMinlengthValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMinlengthValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_too_short_is_invalid_fails(self): + content_type = 'application/json' + # too short is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "f" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_one_supplementary_unicode_code_point_is_not_long_enough_fails(self): + content_type = 'application/json' + # one supplementary Unicode code point is not long enough + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "💩" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_longer_is_valid_passes(self): + content_type = 'application/json' + # longer is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinlengthValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_non_strings_passes(self): + content_type = 'application/json' + # ignores non-strings + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinlengthValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_exact_length_is_valid_passes(self): + content_type = 'application/json' + # exact length is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "fo" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinlengthValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minproperties_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minproperties_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minproperties_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minproperties_validation_request_body/test_post.py new file mode 100644 index 0000000000..91341e06d7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_minproperties_validation_request_body/test_post.py @@ -0,0 +1,215 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_minproperties_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostMinpropertiesValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostMinpropertiesValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_ignores_arrays_passes(self): + content_type = 'application/json' + # ignores arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_other_non_objects_passes(self): + content_type = 'application/json' + # ignores other non-objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_too_short_is_invalid_fails(self): + content_type = 'application/json' + # too short is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_ignores_strings_passes(self): + content_type = 'application/json' + # ignores strings + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_longer_is_valid_passes(self): + content_type = 'application/json' + # longer is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_exact_length_is_valid_passes(self): + content_type = 'application/json' + # exact length is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postMinpropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_allof_to_check_validation_semantics_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_allof_to_check_validation_semantics_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_allof_to_check_validation_semantics_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_allof_to_check_validation_semantics_request_body/test_post.py new file mode 100644 index 0000000000..73e992a05f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_allof_to_check_validation_semantics_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_nested_allof_to_check_validation_semantics_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostNestedAllofToCheckValidationSemanticsRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostNestedAllofToCheckValidationSemanticsRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_anything_non_null_is_invalid_fails(self): + content_type = 'application/json' + # anything non-null is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_valid_passes(self): + content_type = 'application/json' + # null is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNestedAllofToCheckValidationSemanticsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_anyof_to_check_validation_semantics_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_anyof_to_check_validation_semantics_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_anyof_to_check_validation_semantics_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_anyof_to_check_validation_semantics_request_body/test_post.py new file mode 100644 index 0000000000..7951e3c8e8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_anyof_to_check_validation_semantics_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_nested_anyof_to_check_validation_semantics_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostNestedAnyofToCheckValidationSemanticsRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostNestedAnyofToCheckValidationSemanticsRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_anything_non_null_is_invalid_fails(self): + content_type = 'application/json' + # anything non-null is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_valid_passes(self): + content_type = 'application/json' + # null is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_items_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_items_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_items_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_items_request_body/test_post.py new file mode 100644 index 0000000000..60874a6b8a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_items_request_body/test_post.py @@ -0,0 +1,180 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_nested_items_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostNestedItemsRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostNestedItemsRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_valid_nested_array_passes(self): + content_type = 'application/json' + # valid nested array + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + [ + 1, + ], + ], + [ + [ + 2, + ], + [ + 3, + ], + ], + ], + [ + [ + [ + 4, + ], + [ + 5, + ], + [ + 6, + ], + ], + ], + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNestedItemsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_nested_array_with_invalid_type_fails(self): + content_type = 'application/json' + # nested array with invalid type + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + [ + "1", + ], + ], + [ + [ + 2, + ], + [ + 3, + ], + ], + ], + [ + [ + [ + 4, + ], + [ + 5, + ], + [ + 6, + ], + ], + ], + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_not_deep_enough_fails(self): + content_type = 'application/json' + # not deep enough + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + 1, + ], + [ + 2, + ], + [ + 3, + ], + ], + [ + [ + 4, + ], + [ + 5, + ], + [ + 6, + ], + ], + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_oneof_to_check_validation_semantics_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_oneof_to_check_validation_semantics_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_oneof_to_check_validation_semantics_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_oneof_to_check_validation_semantics_request_body/test_post.py new file mode 100644 index 0000000000..42a97ddac7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nested_oneof_to_check_validation_semantics_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_nested_oneof_to_check_validation_semantics_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostNestedOneofToCheckValidationSemanticsRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostNestedOneofToCheckValidationSemanticsRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_anything_non_null_is_invalid_fails(self): + content_type = 'application/json' + # anything non-null is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_valid_passes(self): + content_type = 'application/json' + # null is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNestedOneofToCheckValidationSemanticsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_more_complex_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_more_complex_schema_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_more_complex_schema_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_more_complex_schema_request_body/test_post.py new file mode 100644 index 0000000000..eaacac00eb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_more_complex_schema_request_body/test_post.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_not_more_complex_schema_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostNotMoreComplexSchemaRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostNotMoreComplexSchemaRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_other_match_passes(self): + content_type = 'application/json' + # other match + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNotMoreComplexSchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_mismatch_fails(self): + content_type = 'application/json' + # mismatch + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "bar", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_match_passes(self): + content_type = 'application/json' + # match + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNotMoreComplexSchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_request_body/test_post.py new file mode 100644 index 0000000000..c9bd6f3f30 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_not_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_not_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostNotRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostNotRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_allowed_passes(self): + content_type = 'application/json' + # allowed + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNotRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_disallowed_fails(self): + content_type = 'application/json' + # disallowed + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nul_characters_in_strings_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nul_characters_in_strings_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nul_characters_in_strings_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nul_characters_in_strings_request_body/test_post.py new file mode 100644 index 0000000000..0586243d61 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_nul_characters_in_strings_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_nul_characters_in_strings_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostNulCharactersInStringsRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostNulCharactersInStringsRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_match_string_with_nul_passes(self): + content_type = 'application/json' + # match string with nul + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "hello\x00there" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNulCharactersInStringsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_do_not_match_string_lacking_nul_fails(self): + content_type = 'application/json' + # do not match string lacking nul + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "hellothere" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_null_type_matches_only_the_null_object_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_null_type_matches_only_the_null_object_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_null_type_matches_only_the_null_object_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_null_type_matches_only_the_null_object_request_body/test_post.py new file mode 100644 index 0000000000..f75a20619f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_null_type_matches_only_the_null_object_request_body/test_post.py @@ -0,0 +1,199 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_null_type_matches_only_the_null_object_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostNullTypeMatchesOnlyTheNullObjectRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostNullTypeMatchesOnlyTheNullObjectRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_a_float_is_not_null_fails(self): + content_type = 'application/json' + # a float is not null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_object_is_not_null_fails(self): + content_type = 'application/json' + # an object is not null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_false_is_not_null_fails(self): + content_type = 'application/json' + # false is not null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_integer_is_not_null_fails(self): + content_type = 'application/json' + # an integer is not null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_true_is_not_null_fails(self): + content_type = 'application/json' + # true is not null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_zero_is_not_null_fails(self): + content_type = 'application/json' + # zero is not null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_empty_string_is_not_null_fails(self): + content_type = 'application/json' + # an empty string is not null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_null_passes(self): + content_type = 'application/json' + # null is null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_an_array_is_not_null_fails(self): + content_type = 'application/json' + # an array is not null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_string_is_not_null_fails(self): + content_type = 'application/json' + # a string is not null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_number_type_matches_numbers_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_number_type_matches_numbers_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_number_type_matches_numbers_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_number_type_matches_numbers_request_body/test_post.py new file mode 100644 index 0000000000..70284734ef --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_number_type_matches_numbers_request_body/test_post.py @@ -0,0 +1,217 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_number_type_matches_numbers_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostNumberTypeMatchesNumbersRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostNumberTypeMatchesNumbersRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_an_array_is_not_a_number_fails(self): + content_type = 'application/json' + # an array is not a number + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_not_a_number_fails(self): + content_type = 'application/json' + # null is not a number + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_object_is_not_a_number_fails(self): + content_type = 'application/json' + # an object is not a number + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_boolean_is_not_a_number_fails(self): + content_type = 'application/json' + # a boolean is not a number + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_float_is_a_number_passes(self): + content_type = 'application/json' + # a float is a number + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNumberTypeMatchesNumbersRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_string_is_still_not_a_number_even_if_it_looks_like_one_fails(self): + content_type = 'application/json' + # a string is still not a number, even if it looks like one + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "1" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_string_is_not_a_number_fails(self): + content_type = 'application/json' + # a string is not a number + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_integer_is_a_number_passes(self): + content_type = 'application/json' + # an integer is a number + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNumberTypeMatchesNumbersRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_float_with_zero_fractional_part_is_a_number_and_an_integer_passes(self): + content_type = 'application/json' + # a float with zero fractional part is a number (and an integer) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postNumberTypeMatchesNumbersRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_properties_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_properties_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_properties_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_properties_validation_request_body/test_post.py new file mode 100644 index 0000000000..67fe785a8e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_properties_validation_request_body/test_post.py @@ -0,0 +1,212 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_object_properties_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostObjectPropertiesValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostObjectPropertiesValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_ignores_arrays_passes(self): + content_type = 'application/json' + # ignores arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postObjectPropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_other_non_objects_passes(self): + content_type = 'application/json' + # ignores other non-objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postObjectPropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_one_property_invalid_is_invalid_fails(self): + content_type = 'application/json' + # one property invalid is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + { + }, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_both_properties_present_and_valid_is_valid_passes(self): + content_type = 'application/json' + # both properties present and valid is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + "baz", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postObjectPropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_doesn_t_invalidate_other_properties_passes(self): + content_type = 'application/json' + # doesn't invalidate other properties + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "quux": + [ + ], + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postObjectPropertiesValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_both_properties_invalid_is_invalid_fails(self): + content_type = 'application/json' + # both properties invalid is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + [ + ], + "bar": + { + }, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_type_matches_objects_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_type_matches_objects_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_type_matches_objects_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_type_matches_objects_request_body/test_post.py new file mode 100644 index 0000000000..da5fdf5754 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_object_type_matches_objects_request_body/test_post.py @@ -0,0 +1,157 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_object_type_matches_objects_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostObjectTypeMatchesObjectsRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostObjectTypeMatchesObjectsRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_a_float_is_not_an_object_fails(self): + content_type = 'application/json' + # a float is not an object + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_not_an_object_fails(self): + content_type = 'application/json' + # null is not an object + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_array_is_not_an_object_fails(self): + content_type = 'application/json' + # an array is not an object + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_object_is_an_object_passes(self): + content_type = 'application/json' + # an object is an object + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postObjectTypeMatchesObjectsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_string_is_not_an_object_fails(self): + content_type = 'application/json' + # a string is not an object + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_integer_is_not_an_object_fails(self): + content_type = 'application/json' + # an integer is not an object + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_boolean_is_not_an_object_fails(self): + content_type = 'application/json' + # a boolean is not an object + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_complex_types_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_complex_types_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_complex_types_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_complex_types_request_body/test_post.py new file mode 100644 index 0000000000..a786ebf4eb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_complex_types_request_body/test_post.py @@ -0,0 +1,145 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_oneof_complex_types_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostOneofComplexTypesRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostOneofComplexTypesRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_first_oneof_valid_complex_passes(self): + content_type = 'application/json' + # first oneOf valid (complex) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postOneofComplexTypesRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_neither_oneof_valid_complex_fails(self): + content_type = 'application/json' + # neither oneOf valid (complex) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 2, + "bar": + "quux", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_both_oneof_valid_complex_fails(self): + content_type = 'application/json' + # both oneOf valid (complex) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + "bar": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_second_oneof_valid_complex_passes(self): + content_type = 'application/json' + # second oneOf valid (complex) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postOneofComplexTypesRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_request_body/test_post.py new file mode 100644 index 0000000000..1b837331c1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_request_body/test_post.py @@ -0,0 +1,129 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_oneof_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostOneofRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostOneofRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_second_oneof_valid_passes(self): + content_type = 'application/json' + # second oneOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2.5 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postOneofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_both_oneof_valid_fails(self): + content_type = 'application/json' + # both oneOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_first_oneof_valid_passes(self): + content_type = 'application/json' + # first oneOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postOneofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_neither_oneof_valid_fails(self): + content_type = 'application/json' + # neither oneOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.5 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_base_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_base_schema_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_base_schema_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_base_schema_request_body/test_post.py new file mode 100644 index 0000000000..57bc715f62 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_base_schema_request_body/test_post.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_oneof_with_base_schema_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostOneofWithBaseSchemaRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostOneofWithBaseSchemaRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_both_oneof_valid_fails(self): + content_type = 'application/json' + # both oneOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_mismatch_base_schema_fails(self): + content_type = 'application/json' + # mismatch base schema + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_one_oneof_valid_passes(self): + content_type = 'application/json' + # one oneOf valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foobar" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postOneofWithBaseSchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_empty_schema_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_empty_schema_request_body/test_post.py new file mode 100644 index 0000000000..191c9dc3dc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_empty_schema_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_oneof_with_empty_schema_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostOneofWithEmptySchemaRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostOneofWithEmptySchemaRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_both_valid_invalid_fails(self): + content_type = 'application/json' + # both valid - invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_one_valid_valid_passes(self): + content_type = 'application/json' + # one valid - valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postOneofWithEmptySchemaRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_required_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_required_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_required_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_required_request_body/test_post.py new file mode 100644 index 0000000000..6f01d9c6e5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_oneof_with_required_request_body/test_post.py @@ -0,0 +1,149 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_oneof_with_required_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostOneofWithRequiredRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostOneofWithRequiredRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_both_valid_invalid_fails(self): + content_type = 'application/json' + # both valid - invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "baz": + 3, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_both_invalid_invalid_fails(self): + content_type = 'application/json' + # both invalid - invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_first_valid_valid_passes(self): + content_type = 'application/json' + # first valid - valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postOneofWithRequiredRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_second_valid_valid_passes(self): + content_type = 'application/json' + # second valid - valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "baz": + 3, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postOneofWithRequiredRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_is_not_anchored_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_is_not_anchored_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_is_not_anchored_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_is_not_anchored_request_body/test_post.py new file mode 100644 index 0000000000..6ec8ce1d92 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_is_not_anchored_request_body/test_post.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_pattern_is_not_anchored_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostPatternIsNotAnchoredRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostPatternIsNotAnchoredRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_matches_a_substring_passes(self): + content_type = 'application/json' + # matches a substring + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "xxaayy" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPatternIsNotAnchoredRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_validation_request_body/test_post.py new file mode 100644 index 0000000000..e788bd9e21 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_pattern_validation_request_body/test_post.py @@ -0,0 +1,267 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_pattern_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostPatternValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostPatternValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_ignores_arrays_passes(self): + content_type = 'application/json' + # ignores arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPatternValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_objects_passes(self): + content_type = 'application/json' + # ignores objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPatternValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_null_passes(self): + content_type = 'application/json' + # ignores null + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPatternValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_floats_passes(self): + content_type = 'application/json' + # ignores floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPatternValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_non_matching_pattern_is_invalid_fails(self): + content_type = 'application/json' + # a non-matching pattern is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "abc" + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_ignores_booleans_passes(self): + content_type = 'application/json' + # ignores booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPatternValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_matching_pattern_is_valid_passes(self): + content_type = 'application/json' + # a matching pattern is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "aaa" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPatternValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_integers_passes(self): + content_type = 'application/json' + # ignores integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPatternValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_properties_with_escaped_characters_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_properties_with_escaped_characters_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_properties_with_escaped_characters_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_properties_with_escaped_characters_request_body/test_post.py new file mode 100644 index 0000000000..f0ce9cfad2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_properties_with_escaped_characters_request_body/test_post.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_properties_with_escaped_characters_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostPropertiesWithEscapedCharactersRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostPropertiesWithEscapedCharactersRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_object_with_all_numbers_is_valid_passes(self): + content_type = 'application/json' + # object with all numbers is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo\nbar": + 1, + "foo\"bar": + 1, + "foo\\bar": + 1, + "foo\rbar": + 1, + "foo\tbar": + 1, + "foo\fbar": + 1, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPropertiesWithEscapedCharactersRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_object_with_strings_is_invalid_fails(self): + content_type = 'application/json' + # object with strings is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo\nbar": + "1", + "foo\"bar": + "1", + "foo\\bar": + "1", + "foo\rbar": + "1", + "foo\tbar": + "1", + "foo\fbar": + "1", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_property_named_ref_that_is_not_a_reference_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_property_named_ref_that_is_not_a_reference_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_property_named_ref_that_is_not_a_reference_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_property_named_ref_that_is_not_a_reference_request_body/test_post.py new file mode 100644 index 0000000000..486fa4c5ae --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_property_named_ref_that_is_not_a_reference_request_body/test_post.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_property_named_ref_that_is_not_a_reference_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostPropertyNamedRefThatIsNotAReferenceRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostPropertyNamedRefThatIsNotAReferenceRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_named_ref_valid_passes(self): + content_type = 'application/json' + # property named $ref valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_property_named_ref_invalid_fails(self): + content_type = 'application/json' + # property named $ref invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_additionalproperties_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_additionalproperties_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_additionalproperties_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_additionalproperties_request_body/test_post.py new file mode 100644 index 0000000000..eabe92bd69 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_additionalproperties_request_body/test_post.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_ref_in_additionalproperties_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRefInAdditionalpropertiesRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRefInAdditionalpropertiesRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_named_ref_valid_passes(self): + content_type = 'application/json' + # property named $ref valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "someProp": + { + "$ref": + "a", + }, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRefInAdditionalpropertiesRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_property_named_ref_invalid_fails(self): + content_type = 'application/json' + # property named $ref invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "someProp": + { + "$ref": + 2, + }, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_allof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_allof_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_allof_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_allof_request_body/test_post.py new file mode 100644 index 0000000000..b7aa28e7bd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_allof_request_body/test_post.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_ref_in_allof_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRefInAllofRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRefInAllofRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_named_ref_valid_passes(self): + content_type = 'application/json' + # property named $ref valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRefInAllofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_property_named_ref_invalid_fails(self): + content_type = 'application/json' + # property named $ref invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_anyof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_anyof_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_anyof_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_anyof_request_body/test_post.py new file mode 100644 index 0000000000..517d2427df --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_anyof_request_body/test_post.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_ref_in_anyof_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRefInAnyofRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRefInAnyofRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_named_ref_valid_passes(self): + content_type = 'application/json' + # property named $ref valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRefInAnyofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_property_named_ref_invalid_fails(self): + content_type = 'application/json' + # property named $ref invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_items_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_items_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_items_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_items_request_body/test_post.py new file mode 100644 index 0000000000..e32c859fc6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_items_request_body/test_post.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_ref_in_items_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRefInItemsRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRefInItemsRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_named_ref_valid_passes(self): + content_type = 'application/json' + # property named $ref valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "$ref": + "a", + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRefInItemsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_property_named_ref_invalid_fails(self): + content_type = 'application/json' + # property named $ref invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "$ref": + 2, + }, + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_not_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_not_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_not_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_not_request_body/test_post.py new file mode 100644 index 0000000000..2285d7c3b4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_not_request_body/test_post.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_ref_in_not_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRefInNotRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRefInNotRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_named_ref_valid_passes(self): + content_type = 'application/json' + # property named $ref valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRefInNotRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_property_named_ref_invalid_fails(self): + content_type = 'application/json' + # property named $ref invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_oneof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_oneof_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_oneof_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_oneof_request_body/test_post.py new file mode 100644 index 0000000000..7606a57de9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_oneof_request_body/test_post.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_ref_in_oneof_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRefInOneofRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRefInOneofRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_named_ref_valid_passes(self): + content_type = 'application/json' + # property named $ref valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRefInOneofRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_property_named_ref_invalid_fails(self): + content_type = 'application/json' + # property named $ref invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_property_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_property_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_property_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_property_request_body/test_post.py new file mode 100644 index 0000000000..7f46926445 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_ref_in_property_request_body/test_post.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_ref_in_property_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRefInPropertyRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRefInPropertyRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_named_ref_valid_passes(self): + content_type = 'application/json' + # property named $ref valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "a": + { + "$ref": + "a", + }, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRefInPropertyRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_property_named_ref_invalid_fails(self): + content_type = 'application/json' + # property named $ref invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "a": + { + "$ref": + 2, + }, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_default_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_default_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_default_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_default_validation_request_body/test_post.py new file mode 100644 index 0000000000..17a9e08c7a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_default_validation_request_body/test_post.py @@ -0,0 +1,72 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_required_default_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRequiredDefaultValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRequiredDefaultValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_not_required_by_default_passes(self): + content_type = 'application/json' + # not required by default + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRequiredDefaultValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_validation_request_body/test_post.py new file mode 100644 index 0000000000..ab17be3022 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_validation_request_body/test_post.py @@ -0,0 +1,182 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_required_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRequiredValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRequiredValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_ignores_arrays_passes(self): + content_type = 'application/json' + # ignores arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRequiredValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_present_required_property_is_valid_passes(self): + content_type = 'application/json' + # present required property is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRequiredValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_other_non_objects_passes(self): + content_type = 'application/json' + # ignores other non-objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRequiredValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_ignores_strings_passes(self): + content_type = 'application/json' + # ignores strings + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRequiredValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_present_required_property_is_invalid_fails(self): + content_type = 'application/json' + # non-present required property is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 1, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_empty_array_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_empty_array_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_empty_array_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_empty_array_request_body/test_post.py new file mode 100644 index 0000000000..3e3491d182 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_empty_array_request_body/test_post.py @@ -0,0 +1,72 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_required_with_empty_array_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRequiredWithEmptyArrayRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRequiredWithEmptyArrayRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_property_not_required_passes(self): + content_type = 'application/json' + # property not required + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRequiredWithEmptyArrayRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_escaped_characters_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_escaped_characters_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_escaped_characters_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_escaped_characters_request_body/test_post.py new file mode 100644 index 0000000000..607f536873 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_required_with_escaped_characters_request_body/test_post.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_required_with_escaped_characters_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostRequiredWithEscapedCharactersRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostRequiredWithEscapedCharactersRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_object_with_some_properties_missing_is_invalid_fails(self): + content_type = 'application/json' + # object with some properties missing is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo\nbar": + "1", + "foo\"bar": + "1", + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_object_with_all_properties_present_is_valid_passes(self): + content_type = 'application/json' + # object with all properties present is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo\nbar": + 1, + "foo\"bar": + 1, + "foo\\bar": + 1, + "foo\rbar": + 1, + "foo\tbar": + 1, + "foo\fbar": + 1, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postRequiredWithEscapedCharactersRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_simple_enum_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_simple_enum_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_simple_enum_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_simple_enum_validation_request_body/test_post.py new file mode 100644 index 0000000000..a6ee338a7e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_simple_enum_validation_request_body/test_post.py @@ -0,0 +1,85 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_simple_enum_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostSimpleEnumValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostSimpleEnumValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_something_else_is_invalid_fails(self): + content_type = 'application/json' + # something else is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 4 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_one_of_the_enum_is_valid_passes(self): + content_type = 'application/json' + # one of the enum is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postSimpleEnumValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_string_type_matches_strings_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_string_type_matches_strings_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_string_type_matches_strings_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_string_type_matches_strings_request_body/test_post.py new file mode 100644 index 0000000000..12f1e9bfef --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_string_type_matches_strings_request_body/test_post.py @@ -0,0 +1,217 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_string_type_matches_strings_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostStringTypeMatchesStringsRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostStringTypeMatchesStringsRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_1_is_not_a_string_fails(self): + content_type = 'application/json' + # 1 is not a string + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_string_is_still_a_string_even_if_it_looks_like_a_number_passes(self): + content_type = 'application/json' + # a string is still a string, even if it looks like a number + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "1" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postStringTypeMatchesStringsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_an_empty_string_is_still_a_string_passes(self): + content_type = 'application/json' + # an empty string is still a string + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postStringTypeMatchesStringsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_float_is_not_a_string_fails(self): + content_type = 'application/json' + # a float is not a string + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_object_is_not_a_string_fails(self): + content_type = 'application/json' + # an object is not a string + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_an_array_is_not_a_string_fails(self): + content_type = 'application/json' + # an array is not a string + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_boolean_is_not_a_string_fails(self): + content_type = 'application/json' + # a boolean is not a string + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_null_is_not_a_string_fails(self): + content_type = 'application/json' + # null is not a string + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_a_string_is_a_string_passes(self): + content_type = 'application/json' + # a string is a string + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postStringTypeMatchesStringsRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/test_post.py new file mode 100644 index 0000000000..56ea79de77 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/test_post.py @@ -0,0 +1,122 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_missing_properties_are_not_filled_in_with_the_default_passes(self): + content_type = 'application/json' + # missing properties are not filled in with the default + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_an_explicit_property_value_is_checked_against_maximum_passing_passes(self): + content_type = 'application/json' + # an explicit property value is checked against maximum (passing) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "alpha": + 1, + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_an_explicit_property_value_is_checked_against_maximum_failing_fails(self): + content_type = 'application/json' + # an explicit property value is checked against maximum (failing) + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "alpha": + 5, + } + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_false_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_false_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_false_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_false_validation_request_body/test_post.py new file mode 100644 index 0000000000..affd09c519 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_false_validation_request_body/test_post.py @@ -0,0 +1,607 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_uniqueitems_false_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostUniqueitemsFalseValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostUniqueitemsFalseValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_non_unique_array_of_integers_is_valid_passes(self): + content_type = 'application/json' + # non-unique array of integers is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 1, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_unique_array_of_objects_is_valid_passes(self): + content_type = 'application/json' + # unique array of objects is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + "bar", + }, + { + "foo": + "baz", + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_unique_array_of_nested_objects_is_valid_passes(self): + content_type = 'application/json' + # non-unique array of nested objects is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_unique_array_of_objects_is_valid_passes(self): + content_type = 'application/json' + # non-unique array of objects is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + "bar", + }, + { + "foo": + "bar", + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_1_and_true_are_unique_passes(self): + content_type = 'application/json' + # 1 and true are unique + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + True, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_unique_array_of_integers_is_valid_passes(self): + content_type = 'application/json' + # unique array of integers is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_unique_array_of_arrays_is_valid_passes(self): + content_type = 'application/json' + # non-unique array of arrays is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "foo", + ], + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_numbers_are_unique_if_mathematically_unequal_passes(self): + content_type = 'application/json' + # numbers are unique if mathematically unequal + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1.0, + 1.0, + 1, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_false_is_not_equal_to_zero_passes(self): + content_type = 'application/json' + # false is not equal to zero + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 0, + False, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_unique_array_of_nested_objects_is_valid_passes(self): + content_type = 'application/json' + # unique array of nested objects is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + { + "foo": + { + "bar": + { + "baz": + False, + }, + }, + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_0_and_false_are_unique_passes(self): + content_type = 'application/json' + # 0 and false are unique + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 0, + False, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_unique_array_of_arrays_is_valid_passes(self): + content_type = 'application/json' + # unique array of arrays is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "bar", + ], + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_true_is_not_equal_to_one_passes(self): + content_type = 'application/json' + # true is not equal to one + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + True, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_unique_heterogeneous_types_are_valid_passes(self): + content_type = 'application/json' + # non-unique heterogeneous types are valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + }, + [ + 1, + ], + True, + None, + { + }, + 1, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_unique_heterogeneous_types_are_valid_passes(self): + content_type = 'application/json' + # unique heterogeneous types are valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + }, + [ + 1, + ], + True, + None, + 1, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsFalseValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_validation_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_validation_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_validation_request_body/test_post.py new file mode 100644 index 0000000000..12d95ae7ae --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uniqueitems_validation_request_body/test_post.py @@ -0,0 +1,848 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_uniqueitems_validation_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostUniqueitemsValidationRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostUniqueitemsValidationRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_unique_array_of_objects_is_valid_passes(self): + content_type = 'application/json' + # unique array of objects is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + "bar", + }, + { + "foo": + "baz", + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_true_and_a1_are_unique_passes(self): + content_type = 'application/json' + # {"a": true} and {"a": 1} are unique + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "a": + True, + }, + { + "a": + 1, + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_unique_heterogeneous_types_are_invalid_fails(self): + content_type = 'application/json' + # non-unique heterogeneous types are invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + }, + [ + 1, + ], + True, + None, + { + }, + 1, + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_nested0_and_false_are_unique_passes(self): + content_type = 'application/json' + # nested [0] and [false] are unique + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + 0, + ], + "foo", + ], + [ + [ + False, + ], + "foo", + ], + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_a_false_and_a0_are_unique_passes(self): + content_type = 'application/json' + # {"a": false} and {"a": 0} are unique + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "a": + False, + }, + { + "a": + 0, + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_numbers_are_unique_if_mathematically_unequal_fails(self): + content_type = 'application/json' + # numbers are unique if mathematically unequal + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1.0, + 1.0, + 1, + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_false_is_not_equal_to_zero_passes(self): + content_type = 'application/json' + # false is not equal to zero + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 0, + False, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_0_and_false_are_unique_passes(self): + content_type = 'application/json' + # [0] and [false] are unique + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + 0, + ], + [ + False, + ], + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_unique_array_of_arrays_is_valid_passes(self): + content_type = 'application/json' + # unique array of arrays is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "bar", + ], + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_unique_array_of_nested_objects_is_invalid_fails(self): + content_type = 'application/json' + # non-unique array of nested objects is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_non_unique_array_of_more_than_two_integers_is_invalid_fails(self): + content_type = 'application/json' + # non-unique array of more than two integers is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + 1, + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_true_is_not_equal_to_one_passes(self): + content_type = 'application/json' + # true is not equal to one + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + True, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_objects_are_non_unique_despite_key_order_fails(self): + content_type = 'application/json' + # objects are non-unique despite key order + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "a": + 1, + "b": + 2, + }, + { + "b": + 2, + "a": + 1, + }, + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_unique_array_of_strings_is_valid_passes(self): + content_type = 'application/json' + # unique array of strings is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + "foo", + "bar", + "baz", + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_1_and_true_are_unique_passes(self): + content_type = 'application/json' + # [1] and [true] are unique + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + 1, + ], + [ + True, + ], + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_different_objects_are_unique_passes(self): + content_type = 'application/json' + # different objects are unique + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "a": + 1, + "b": + 2, + }, + { + "a": + 2, + "b": + 1, + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_unique_array_of_integers_is_valid_passes(self): + content_type = 'application/json' + # unique array of integers is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_unique_array_of_more_than_two_arrays_is_invalid_fails(self): + content_type = 'application/json' + # non-unique array of more than two arrays is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "bar", + ], + [ + "foo", + ], + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_non_unique_array_of_objects_is_invalid_fails(self): + content_type = 'application/json' + # non-unique array of objects is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + "bar", + }, + { + "foo": + "bar", + }, + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_unique_array_of_nested_objects_is_valid_passes(self): + content_type = 'application/json' + # unique array of nested objects is valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + { + "foo": + { + "bar": + { + "baz": + False, + }, + }, + }, + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_unique_array_of_arrays_is_invalid_fails(self): + content_type = 'application/json' + # non-unique array of arrays is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "foo", + ], + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_non_unique_array_of_strings_is_invalid_fails(self): + content_type = 'application/json' + # non-unique array of strings is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + "foo", + "bar", + "foo", + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + def test_nested1_and_true_are_unique_passes(self): + content_type = 'application/json' + # nested [1] and [true] are unique + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + 1, + ], + "foo", + ], + [ + [ + True, + ], + "foo", + ], + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_unique_heterogeneous_types_are_valid_passes(self): + content_type = 'application/json' + # unique heterogeneous types are valid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + }, + [ + 1, + ], + True, + None, + 1, + "{}", + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUniqueitemsValidationRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_non_unique_array_of_integers_is_invalid_fails(self): + content_type = 'application/json' + # non-unique array of integers is invalid + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 1, + ] + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + self.api.post(body=body) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_format_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_format_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_format_request_body/test_post.py new file mode 100644 index 0000000000..94a07cc1f5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_format_request_body/test_post.py @@ -0,0 +1,223 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_uri_format_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostUriFormatRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostUriFormatRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_all_string_formats_ignore_objects_passes(self): + content_type = 'application/json' + # all string formats ignore objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_booleans_passes(self): + content_type = 'application/json' + # all string formats ignore booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_integers_passes(self): + content_type = 'application/json' + # all string formats ignore integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_floats_passes(self): + content_type = 'application/json' + # all string formats ignore floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_arrays_passes(self): + content_type = 'application/json' + # all string formats ignore arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_nulls_passes(self): + content_type = 'application/json' + # all string formats ignore nulls + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_reference_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_reference_format_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_reference_format_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_reference_format_request_body/test_post.py new file mode 100644 index 0000000000..9dfca7bbc6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_reference_format_request_body/test_post.py @@ -0,0 +1,223 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_uri_reference_format_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostUriReferenceFormatRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostUriReferenceFormatRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_all_string_formats_ignore_objects_passes(self): + content_type = 'application/json' + # all string formats ignore objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriReferenceFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_booleans_passes(self): + content_type = 'application/json' + # all string formats ignore booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriReferenceFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_integers_passes(self): + content_type = 'application/json' + # all string formats ignore integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriReferenceFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_floats_passes(self): + content_type = 'application/json' + # all string formats ignore floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriReferenceFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_arrays_passes(self): + content_type = 'application/json' + # all string formats ignore arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriReferenceFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_nulls_passes(self): + content_type = 'application/json' + # all string formats ignore nulls + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriReferenceFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_template_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_template_format_request_body/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_template_format_request_body/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_template_format_request_body/test_post.py new file mode 100644 index 0000000000..93544bef16 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_request_body_post_uri_template_format_request_body/test_post.py @@ -0,0 +1,223 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.request_body_post_uri_template_format_request_body import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestRequestBodyPostUriTemplateFormatRequestBody(ApiTestMixin, unittest.TestCase): + """ + RequestBodyPostUriTemplateFormatRequestBody unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + def test_all_string_formats_ignore_objects_passes(self): + content_type = 'application/json' + # all string formats ignore objects + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriTemplateFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_booleans_passes(self): + content_type = 'application/json' + # all string formats ignore booleans + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriTemplateFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_integers_passes(self): + content_type = 'application/json' + # all string formats ignore integers + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriTemplateFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_floats_passes(self): + content_type = 'application/json' + # all string formats ignore floats + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriTemplateFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_arrays_passes(self): + content_type = 'application/json' + # all string formats ignore arrays + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriTemplateFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + def test_all_string_formats_ignore_nulls_passes(self): + content_type = 'application/json' + # all string formats ignore nulls + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + body = post.SchemaForRequestBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + mock_request.return_value = self.response( + self.json_bytes(self.response_body), + status=self.response_status + ) + api_response = self.api.post( + body=body, + content_type=content_type + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/requestBody/postUriTemplateFormatRequestBody', + method='post'.upper(), + body=self.json_bytes(payload), + content_type=content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..4c408162b7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/test_post.py @@ -0,0 +1,141 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_no_additional_properties_is_valid_passes(self): + # no additional properties is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_an_additional_invalid_property_is_invalid_fails(self): + # an additional invalid property is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "quux": + 12, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_additional_valid_property_is_valid_passes(self): + # an additional valid property is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "quux": + True, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..2a8383382a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/test_post.py @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_additional_properties_are_allowed_passes(self): + # additional properties are allowed + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "quux": + True, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..fa6be7937e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/test_post.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_an_additional_invalid_property_is_invalid_fails(self): + # an additional invalid property is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_additional_valid_property_is_valid_passes(self): + # an additional valid property is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + True, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..66faadd6a0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/test_post.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_properties_defined_in_allof_are_not_examined_fails(self): + # properties defined in allOf are not examined + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + True, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_valid_test_case_passes(self): + # valid test case + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + False, + "bar": + True, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..50707b5fb2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/test_post.py @@ -0,0 +1,238 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAllofCombinedWithAnyofOneofResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAllofCombinedWithAnyofOneofResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_allof_true_anyof_false_oneof_false_fails(self): + # allOf: true, anyOf: false, oneOf: false + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_allof_false_anyof_false_oneof_true_fails(self): + # allOf: false, anyOf: false, oneOf: true + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 5 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_allof_false_anyof_true_oneof_true_fails(self): + # allOf: false, anyOf: true, oneOf: true + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 15 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_allof_true_anyof_true_oneof_false_fails(self): + # allOf: true, anyOf: true, oneOf: false + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 6 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_allof_true_anyof_true_oneof_true_passes(self): + # allOf: true, anyOf: true, oneOf: true + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 30 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_allof_true_anyof_false_oneof_true_fails(self): + # allOf: true, anyOf: false, oneOf: true + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 10 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_allof_false_anyof_true_oneof_false_fails(self): + # allOf: false, anyOf: true, oneOf: false + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_allof_false_anyof_false_oneof_false_fails(self): + # allOf: false, anyOf: false, oneOf: false + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..dae6394211 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_response_body_for_content_types/test_post.py @@ -0,0 +1,158 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_allof_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAllofResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAllofResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_allof_passes(self): + # allOf + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_mismatch_first_fails(self): + # mismatch first + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_mismatch_second_fails(self): + # mismatch second + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_wrong_type_fails(self): + # wrong type + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + "bar": + "quux", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_simple_types_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_simple_types_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_simple_types_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_simple_types_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..7713cf8e73 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_simple_types_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_allof_simple_types_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAllofSimpleTypesResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAllofSimpleTypesResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_valid_passes(self): + # valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 25 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofSimpleTypesResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_mismatch_one_fails(self): + # mismatch one + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 35 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofSimpleTypesResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_base_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_base_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_base_schema_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_base_schema_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..42142f307e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_base_schema_response_body_for_content_types/test_post.py @@ -0,0 +1,191 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_allof_with_base_schema_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAllofWithBaseSchemaResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAllofWithBaseSchemaResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_valid_passes(self): + # valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "quux", + "bar": + 2, + "baz": + None, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_mismatch_first_allof_fails(self): + # mismatch first allOf + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + "baz": + None, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_mismatch_base_schema_fails(self): + # mismatch base schema + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "quux", + "baz": + None, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_mismatch_both_fails(self): + # mismatch both + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_mismatch_second_allof_fails(self): + # mismatch second allOf + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "quux", + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_one_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_one_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_one_empty_schema_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_one_empty_schema_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..68d704af40 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_one_empty_schema_response_body_for_content_types/test_post.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_allof_with_one_empty_schema_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAllofWithOneEmptySchemaResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAllofWithOneEmptySchemaResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_any_data_is_valid_passes(self): + # any data is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..0d11bae4db --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_string_is_invalid_fails(self): + # string is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_number_is_valid_passes(self): + # number is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..557fe4b749 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAllofWithTheLastEmptySchemaResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAllofWithTheLastEmptySchemaResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_string_is_invalid_fails(self): + # string is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_number_is_valid_passes(self): + # number is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..3e280d443b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/test_post.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_allof_with_two_empty_schemas_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAllofWithTwoEmptySchemasResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAllofWithTwoEmptySchemasResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_any_data_is_valid_passes(self): + # any data is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_complex_types_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_complex_types_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_complex_types_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_complex_types_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..2a40c9b558 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_complex_types_response_body_for_content_types/test_post.py @@ -0,0 +1,170 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_anyof_complex_types_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAnyofComplexTypesResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAnyofComplexTypesResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_second_anyof_valid_complex_passes(self): + # second anyOf valid (complex) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofComplexTypesResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_neither_anyof_valid_complex_fails(self): + # neither anyOf valid (complex) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 2, + "bar": + "quux", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofComplexTypesResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_both_anyof_valid_complex_passes(self): + # both anyOf valid (complex) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofComplexTypesResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_first_anyof_valid_complex_passes(self): + # first anyOf valid (complex) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofComplexTypesResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..7707cd74ac --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_response_body_for_content_types/test_post.py @@ -0,0 +1,154 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_anyof_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAnyofResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAnyofResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_second_anyof_valid_passes(self): + # second anyOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2.5 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_neither_anyof_valid_fails(self): + # neither anyOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.5 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_both_anyof_valid_passes(self): + # both anyOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_first_anyof_valid_passes(self): + # first anyOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_base_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_base_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_base_schema_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_base_schema_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..d8981bb737 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_base_schema_response_body_for_content_types/test_post.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_anyof_with_base_schema_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAnyofWithBaseSchemaResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAnyofWithBaseSchemaResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_one_anyof_valid_passes(self): + # one anyOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foobar" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_both_anyof_invalid_fails(self): + # both anyOf invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_mismatch_base_schema_fails(self): + # mismatch base schema + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..d8a37341e9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/test_post.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_anyof_with_one_empty_schema_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostAnyofWithOneEmptySchemaResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostAnyofWithOneEmptySchemaResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_string_is_valid_passes(self): + # string is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_number_is_valid_passes(self): + # number is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_array_type_matches_arrays_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_array_type_matches_arrays_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_array_type_matches_arrays_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_array_type_matches_arrays_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..717a6d1e2d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_array_type_matches_arrays_response_body_for_content_types/test_post.py @@ -0,0 +1,216 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_array_type_matches_arrays_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostArrayTypeMatchesArraysResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostArrayTypeMatchesArraysResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_a_float_is_not_an_array_fails(self): + # a float is not an array + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_boolean_is_not_an_array_fails(self): + # a boolean is not an array + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_not_an_array_fails(self): + # null is not an array + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_object_is_not_an_array_fails(self): + # an object is not an array + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_string_is_not_an_array_fails(self): + # a string is not an array + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_array_is_an_array_passes(self): + # an array is an array + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_an_integer_is_not_an_array_fails(self): + # an integer is not an array + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_boolean_type_matches_booleans_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_boolean_type_matches_booleans_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_boolean_type_matches_booleans_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_boolean_type_matches_booleans_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..f4daf112ba --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_boolean_type_matches_booleans_response_body_for_content_types/test_post.py @@ -0,0 +1,294 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_boolean_type_matches_booleans_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostBooleanTypeMatchesBooleansResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostBooleanTypeMatchesBooleansResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_an_empty_string_is_not_a_boolean_fails(self): + # an empty string is not a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_float_is_not_a_boolean_fails(self): + # a float is not a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_not_a_boolean_fails(self): + # null is not a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_zero_is_not_a_boolean_fails(self): + # zero is not a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_array_is_not_a_boolean_fails(self): + # an array is not a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_string_is_not_a_boolean_fails(self): + # a string is not a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_false_is_a_boolean_passes(self): + # false is a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_an_integer_is_not_a_boolean_fails(self): + # an integer is not a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_true_is_a_boolean_passes(self): + # true is a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_an_object_is_not_a_boolean_fails(self): + # an object is not a boolean + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_int_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_int_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_int_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_int_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..ccb4450d00 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_int_response_body_for_content_types/test_post.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_by_int_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostByIntResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostByIntResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_int_by_int_fail_fails(self): + # int by int fail + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postByIntResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_int_by_int_passes(self): + # int by int + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 10 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postByIntResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_non_numbers_passes(self): + # ignores non-numbers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postByIntResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_number_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_number_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_number_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_number_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..553452dd34 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_number_response_body_for_content_types/test_post.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_by_number_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostByNumberResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostByNumberResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_45_is_multiple_of15_passes(self): + # 4.5 is multiple of 1.5 + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 4.5 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postByNumberResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_35_is_not_multiple_of15_fails(self): + # 35 is not multiple of 1.5 + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 35 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postByNumberResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_zero_is_multiple_of_anything_passes(self): + # zero is multiple of anything + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postByNumberResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_small_number_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_small_number_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_small_number_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_small_number_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..c8e0af97ed --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_by_small_number_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_by_small_number_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostBySmallNumberResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostBySmallNumberResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_000751_is_not_multiple_of00001_fails(self): + # 0.00751 is not multiple of 0.0001 + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.00751 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBySmallNumberResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_00075_is_multiple_of00001_passes(self): + # 0.0075 is multiple of 0.0001 + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.0075 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postBySmallNumberResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_date_time_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_date_time_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_date_time_format_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_date_time_format_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..813449ce9a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_date_time_format_response_body_for_content_types/test_post.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_date_time_format_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostDateTimeFormatResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostDateTimeFormatResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_all_string_formats_ignore_objects_passes(self): + # all string formats ignore objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postDateTimeFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_booleans_passes(self): + # all string formats ignore booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postDateTimeFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_integers_passes(self): + # all string formats ignore integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postDateTimeFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_floats_passes(self): + # all string formats ignore floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postDateTimeFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_arrays_passes(self): + # all string formats ignore arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postDateTimeFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_nulls_passes(self): + # all string formats ignore nulls + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postDateTimeFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_email_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_email_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_email_format_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_email_format_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..0d82125e12 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_email_format_response_body_for_content_types/test_post.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_email_format_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostEmailFormatResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostEmailFormatResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_all_string_formats_ignore_objects_passes(self): + # all string formats ignore objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEmailFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_booleans_passes(self): + # all string formats ignore booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEmailFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_integers_passes(self): + # all string formats ignore integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEmailFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_floats_passes(self): + # all string formats ignore floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEmailFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_arrays_passes(self): + # all string formats ignore arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEmailFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_nulls_passes(self): + # all string formats ignore nulls + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEmailFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..35e2256415 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/test_post.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_enum_with0_does_not_match_false_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_integer_zero_is_valid_passes(self): + # integer zero is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_float_zero_is_valid_passes(self): + # float zero is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_false_is_invalid_fails(self): + # false is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..3ddc9a784b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/test_post.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_enum_with1_does_not_match_true_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_true_is_invalid_fails(self): + # true is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_integer_one_is_valid_passes(self): + # integer one is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_float_one_is_valid_passes(self): + # float one is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_escaped_characters_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_escaped_characters_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_escaped_characters_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_escaped_characters_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..a775da33fc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_escaped_characters_response_body_for_content_types/test_post.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_enum_with_escaped_characters_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostEnumWithEscapedCharactersResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostEnumWithEscapedCharactersResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_member2_is_valid_passes(self): + # member 2 is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo\rbar" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_member1_is_valid_passes(self): + # member 1 is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo\nbar" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_another_string_is_invalid_fails(self): + # another string is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "abc" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..229b64beab --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/test_post.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_enum_with_false_does_not_match0_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_false_is_valid_passes(self): + # false is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_float_zero_is_invalid_fails(self): + # float zero is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_integer_zero_is_invalid_fails(self): + # integer zero is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..abb8635973 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/test_post.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_enum_with_true_does_not_match1_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_float_one_is_invalid_fails(self): + # float one is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_true_is_valid_passes(self): + # true is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_integer_one_is_invalid_fails(self): + # integer one is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enums_in_properties_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enums_in_properties_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enums_in_properties_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enums_in_properties_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..59f2f9b9ac --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_enums_in_properties_response_body_for_content_types/test_post.py @@ -0,0 +1,218 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_enums_in_properties_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostEnumsInPropertiesResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostEnumsInPropertiesResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_missing_optional_property_is_valid_passes(self): + # missing optional property is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + "bar", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumsInPropertiesResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_wrong_foo_value_fails(self): + # wrong foo value + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "foot", + "bar": + "bar", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumsInPropertiesResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_both_properties_are_valid_passes(self): + # both properties are valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "foo", + "bar": + "bar", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumsInPropertiesResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_wrong_bar_value_fails(self): + # wrong bar value + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "foo", + "bar": + "bart", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumsInPropertiesResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_missing_all_properties_is_invalid_fails(self): + # missing all properties is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumsInPropertiesResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_missing_required_property_is_invalid_fails(self): + # missing required property is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "foo", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postEnumsInPropertiesResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_forbidden_property_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_forbidden_property_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_forbidden_property_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_forbidden_property_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..5610f1bd7a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_forbidden_property_response_body_for_content_types/test_post.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_forbidden_property_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostForbiddenPropertyResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostForbiddenPropertyResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_present_fails(self): + # property present + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postForbiddenPropertyResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_property_absent_passes(self): + # property absent + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 1, + "baz": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postForbiddenPropertyResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_hostname_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_hostname_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_hostname_format_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_hostname_format_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..ac74108dd3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_hostname_format_response_body_for_content_types/test_post.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_hostname_format_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostHostnameFormatResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostHostnameFormatResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_all_string_formats_ignore_objects_passes(self): + # all string formats ignore objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postHostnameFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_booleans_passes(self): + # all string formats ignore booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postHostnameFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_integers_passes(self): + # all string formats ignore integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postHostnameFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_floats_passes(self): + # all string formats ignore floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postHostnameFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_arrays_passes(self): + # all string formats ignore arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postHostnameFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_nulls_passes(self): + # all string formats ignore nulls + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postHostnameFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_integer_type_matches_integers_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_integer_type_matches_integers_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_integer_type_matches_integers_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_integer_type_matches_integers_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..c772cd05dc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_integer_type_matches_integers_response_body_for_content_types/test_post.py @@ -0,0 +1,270 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_integer_type_matches_integers_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostIntegerTypeMatchesIntegersResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostIntegerTypeMatchesIntegersResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_an_object_is_not_an_integer_fails(self): + # an object is not an integer + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_string_is_not_an_integer_fails(self): + # a string is not an integer + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_not_an_integer_fails(self): + # null is not an integer + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_float_with_zero_fractional_part_is_an_integer_passes(self): + # a float with zero fractional part is an integer + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_float_is_not_an_integer_fails(self): + # a float is not an integer + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_boolean_is_not_an_integer_fails(self): + # a boolean is not an integer + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_integer_is_an_integer_passes(self): + # an integer is an integer + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_string_is_still_not_an_integer_even_if_it_looks_like_one_fails(self): + # a string is still not an integer, even if it looks like one + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "1" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_array_is_not_an_integer_fails(self): + # an array is not an integer + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..a198deb37b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_always_invalid_but_naive_implementations_may_raise_an_overflow_error_fails(self): + # always invalid, but naive implementations may raise an overflow error + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0E308 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_valid_integer_with_multipleof_float_passes(self): + # valid integer with multipleOf float + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123456789 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_string_value_for_default_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_string_value_for_default_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_string_value_for_default_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_string_value_for_default_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..3cd375f9db --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_invalid_string_value_for_default_response_body_for_content_types/test_post.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_invalid_string_value_for_default_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostInvalidStringValueForDefaultResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostInvalidStringValueForDefaultResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_valid_when_property_is_specified_passes(self): + # valid when property is specified + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + "good", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_still_valid_when_the_invalid_default_is_used_passes(self): + # still valid when the invalid default is used + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv4_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv4_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv4_format_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv4_format_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..4804e8e5a1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv4_format_response_body_for_content_types/test_post.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_ipv4_format_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostIpv4FormatResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostIpv4FormatResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_all_string_formats_ignore_objects_passes(self): + # all string formats ignore objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv4FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_booleans_passes(self): + # all string formats ignore booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv4FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_integers_passes(self): + # all string formats ignore integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv4FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_floats_passes(self): + # all string formats ignore floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv4FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_arrays_passes(self): + # all string formats ignore arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv4FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_nulls_passes(self): + # all string formats ignore nulls + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv4FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv6_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv6_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv6_format_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv6_format_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..b63faab6c4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ipv6_format_response_body_for_content_types/test_post.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_ipv6_format_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostIpv6FormatResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostIpv6FormatResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_all_string_formats_ignore_objects_passes(self): + # all string formats ignore objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv6FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_booleans_passes(self): + # all string formats ignore booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv6FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_integers_passes(self): + # all string formats ignore integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv6FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_floats_passes(self): + # all string formats ignore floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv6FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_arrays_passes(self): + # all string formats ignore arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv6FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_nulls_passes(self): + # all string formats ignore nulls + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postIpv6FormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_json_pointer_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_json_pointer_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_json_pointer_format_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_json_pointer_format_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..49e2e9df94 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_json_pointer_format_response_body_for_content_types/test_post.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_json_pointer_format_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostJsonPointerFormatResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostJsonPointerFormatResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_all_string_formats_ignore_objects_passes(self): + # all string formats ignore objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postJsonPointerFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_booleans_passes(self): + # all string formats ignore booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postJsonPointerFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_integers_passes(self): + # all string formats ignore integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postJsonPointerFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_floats_passes(self): + # all string formats ignore floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postJsonPointerFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_arrays_passes(self): + # all string formats ignore arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postJsonPointerFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_nulls_passes(self): + # all string formats ignore nulls + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postJsonPointerFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..42ccfe7cb1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,154 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_maximum_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMaximumValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMaximumValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_below_the_maximum_is_valid_passes(self): + # below the maximum is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2.6 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaximumValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_boundary_point_is_valid_passes(self): + # boundary point is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaximumValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_above_the_maximum_is_invalid_fails(self): + # above the maximum is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3.5 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaximumValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_ignores_non_numbers_passes(self): + # ignores non-numbers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "x" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaximumValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..725ca59dd9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/test_post.py @@ -0,0 +1,154 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_below_the_maximum_is_invalid_passes(self): + # below the maximum is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 299.97 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_above_the_maximum_is_invalid_fails(self): + # above the maximum is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 300.5 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_boundary_point_integer_is_valid_passes(self): + # boundary point integer is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 300 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_boundary_point_float_is_valid_passes(self): + # boundary point float is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 300.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxitems_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxitems_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxitems_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxitems_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..d297f38843 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxitems_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,163 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_maxitems_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMaxitemsValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMaxitemsValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_too_long_is_invalid_fails(self): + # too long is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + 3, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_ignores_non_arrays_passes(self): + # ignores non-arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foobar" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_shorter_is_valid_passes(self): + # shorter is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_exact_length_is_valid_passes(self): + # exact length is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxlength_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxlength_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxlength_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxlength_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..7f5622b34b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxlength_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,184 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_maxlength_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMaxlengthValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMaxlengthValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_too_long_is_invalid_fails(self): + # too long is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_ignores_non_strings_passes(self): + # ignores non-strings + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 100 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_shorter_is_valid_passes(self): + # shorter is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "f" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_two_supplementary_unicode_code_points_is_long_enough_passes(self): + # two supplementary Unicode code points is long enough + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "💩💩" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_exact_length_is_valid_passes(self): + # exact length is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "fo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..58145de041 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/test_post.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_no_properties_is_valid_passes(self): + # no properties is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_one_property_is_invalid_fails(self): + # one property is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..28a24d6e03 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_maxproperties_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,233 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_maxproperties_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMaxpropertiesValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMaxpropertiesValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_too_long_is_invalid_fails(self): + # too long is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "baz": + 3, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_ignores_arrays_passes(self): + # ignores arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + 3, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_other_non_objects_passes(self): + # ignores other non-objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_strings_passes(self): + # ignores strings + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foobar" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_shorter_is_valid_passes(self): + # shorter is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_exact_length_is_valid_passes(self): + # exact length is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMaxpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..ca262ddbde --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,154 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_minimum_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMinimumValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMinimumValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_boundary_point_is_valid_passes(self): + # boundary point is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_below_the_minimum_is_invalid_fails(self): + # below the minimum is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0.6 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_above_the_minimum_is_valid_passes(self): + # above the minimum is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2.6 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_non_numbers_passes(self): + # ignores non-numbers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "x" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..d5842cf8a4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/test_post.py @@ -0,0 +1,238 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMinimumValidationWithSignedIntegerResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMinimumValidationWithSignedIntegerResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_boundary_point_is_valid_passes(self): + # boundary point is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -2 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_positive_above_the_minimum_is_valid_passes(self): + # positive above the minimum is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_int_below_the_minimum_is_invalid_fails(self): + # int below the minimum is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -3 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_float_below_the_minimum_is_invalid_fails(self): + # float below the minimum is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -2.0001 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_boundary_point_with_float_is_valid_passes(self): + # boundary point with float is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -2.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_negative_above_the_minimum_is_valid_passes(self): + # negative above the minimum is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + -1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_non_numbers_passes(self): + # ignores non-numbers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "x" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minitems_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minitems_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minitems_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minitems_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..4450462f99 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minitems_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,160 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_minitems_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMinitemsValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMinitemsValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_too_short_is_invalid_fails(self): + # too short is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_ignores_non_arrays_passes(self): + # ignores non-arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_longer_is_valid_passes(self): + # longer is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_exact_length_is_valid_passes(self): + # exact length is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minlength_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minlength_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minlength_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minlength_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..247a17756b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minlength_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,178 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_minlength_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMinlengthValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMinlengthValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_too_short_is_invalid_fails(self): + # too short is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "f" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_one_supplementary_unicode_code_point_is_not_long_enough_fails(self): + # one supplementary Unicode code point is not long enough + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "💩" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_longer_is_valid_passes(self): + # longer is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_non_strings_passes(self): + # ignores non-strings + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_exact_length_is_valid_passes(self): + # exact length is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "fo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinlengthValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minproperties_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minproperties_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minproperties_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minproperties_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..2f3aadb358 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_minproperties_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_minproperties_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostMinpropertiesValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostMinpropertiesValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_ignores_arrays_passes(self): + # ignores arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_other_non_objects_passes(self): + # ignores other non-objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_too_short_is_invalid_fails(self): + # too short is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_ignores_strings_passes(self): + # ignores strings + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_longer_is_valid_passes(self): + # longer is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_exact_length_is_valid_passes(self): + # exact length is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postMinpropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..9d8f8fbf93 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_anything_non_null_is_invalid_fails(self): + # anything non-null is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_valid_passes(self): + # null is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..8fc358252f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_anything_non_null_is_invalid_fails(self): + # anything non-null is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_valid_passes(self): + # null is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_items_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_items_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_items_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_items_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..ffb0092cb8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_items_response_body_for_content_types/test_post.py @@ -0,0 +1,199 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_nested_items_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostNestedItemsResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostNestedItemsResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_valid_nested_array_passes(self): + # valid nested array + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + [ + 1, + ], + ], + [ + [ + 2, + ], + [ + 3, + ], + ], + ], + [ + [ + [ + 4, + ], + [ + 5, + ], + [ + 6, + ], + ], + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNestedItemsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_nested_array_with_invalid_type_fails(self): + # nested array with invalid type + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + [ + "1", + ], + ], + [ + [ + 2, + ], + [ + 3, + ], + ], + ], + [ + [ + [ + 4, + ], + [ + 5, + ], + [ + 6, + ], + ], + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNestedItemsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_not_deep_enough_fails(self): + # not deep enough + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + 1, + ], + [ + 2, + ], + [ + 3, + ], + ], + [ + [ + 4, + ], + [ + 5, + ], + [ + 6, + ], + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNestedItemsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..188ce661ff --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_anything_non_null_is_invalid_fails(self): + # anything non-null is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_valid_passes(self): + # null is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_more_complex_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_more_complex_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_more_complex_schema_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_more_complex_schema_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..4b615daed1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_more_complex_schema_response_body_for_content_types/test_post.py @@ -0,0 +1,130 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_not_more_complex_schema_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostNotMoreComplexSchemaResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostNotMoreComplexSchemaResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_other_match_passes(self): + # other match + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_mismatch_fails(self): + # mismatch + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "bar", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_match_passes(self): + # match + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..4b505c1b4d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_not_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_not_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostNotResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostNotResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_allowed_passes(self): + # allowed + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNotResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_disallowed_fails(self): + # disallowed + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNotResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nul_characters_in_strings_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nul_characters_in_strings_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nul_characters_in_strings_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nul_characters_in_strings_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..b0ce13a519 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_nul_characters_in_strings_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_nul_characters_in_strings_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostNulCharactersInStringsResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostNulCharactersInStringsResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_match_string_with_nul_passes(self): + # match string with nul + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "hello\x00there" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNulCharactersInStringsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_do_not_match_string_lacking_nul_fails(self): + # do not match string lacking nul + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "hellothere" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNulCharactersInStringsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..3968560933 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/test_post.py @@ -0,0 +1,288 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_a_float_is_not_null_fails(self): + # a float is not null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_object_is_not_null_fails(self): + # an object is not null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_false_is_not_null_fails(self): + # false is not null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_integer_is_not_null_fails(self): + # an integer is not null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_true_is_not_null_fails(self): + # true is not null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_zero_is_not_null_fails(self): + # zero is not null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_empty_string_is_not_null_fails(self): + # an empty string is not null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_null_passes(self): + # null is null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_an_array_is_not_null_fails(self): + # an array is not null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_string_is_not_null_fails(self): + # a string is not null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_number_type_matches_numbers_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_number_type_matches_numbers_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_number_type_matches_numbers_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_number_type_matches_numbers_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..aa54a7620b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_number_type_matches_numbers_response_body_for_content_types/test_post.py @@ -0,0 +1,276 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_number_type_matches_numbers_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostNumberTypeMatchesNumbersResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostNumberTypeMatchesNumbersResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_an_array_is_not_a_number_fails(self): + # an array is not a number + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_not_a_number_fails(self): + # null is not a number + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_object_is_not_a_number_fails(self): + # an object is not a number + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_boolean_is_not_a_number_fails(self): + # a boolean is not a number + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_float_is_a_number_passes(self): + # a float is a number + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_string_is_still_not_a_number_even_if_it_looks_like_one_fails(self): + # a string is still not a number, even if it looks like one + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "1" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_string_is_not_a_number_fails(self): + # a string is not a number + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_integer_is_a_number_passes(self): + # an integer is a number + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_float_with_zero_fractional_part_is_a_number_and_an_integer_passes(self): + # a float with zero fractional part is a number (and an integer) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_properties_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_properties_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_properties_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_properties_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..28b78c6816 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_properties_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_object_properties_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostObjectPropertiesValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostObjectPropertiesValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_ignores_arrays_passes(self): + # ignores arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectPropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_other_non_objects_passes(self): + # ignores other non-objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectPropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_one_property_invalid_is_invalid_fails(self): + # one property invalid is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + { + }, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectPropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_both_properties_present_and_valid_is_valid_passes(self): + # both properties present and valid is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + "baz", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectPropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_doesn_t_invalidate_other_properties_passes(self): + # doesn't invalidate other properties + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "quux": + [ + ], + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectPropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_both_properties_invalid_is_invalid_fails(self): + # both properties invalid is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + [ + ], + "bar": + { + }, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectPropertiesValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_type_matches_objects_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_type_matches_objects_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_type_matches_objects_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_type_matches_objects_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..55da20de7e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_object_type_matches_objects_response_body_for_content_types/test_post.py @@ -0,0 +1,216 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_object_type_matches_objects_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostObjectTypeMatchesObjectsResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostObjectTypeMatchesObjectsResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_a_float_is_not_an_object_fails(self): + # a float is not an object + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_not_an_object_fails(self): + # null is not an object + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_array_is_not_an_object_fails(self): + # an array is not an object + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_object_is_an_object_passes(self): + # an object is an object + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_string_is_not_an_object_fails(self): + # a string is not an object + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_integer_is_not_an_object_fails(self): + # an integer is not an object + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_boolean_is_not_an_object_fails(self): + # a boolean is not an object + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_complex_types_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_complex_types_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_complex_types_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_complex_types_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..678c4ad809 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_complex_types_response_body_for_content_types/test_post.py @@ -0,0 +1,164 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_oneof_complex_types_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostOneofComplexTypesResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostOneofComplexTypesResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_first_oneof_valid_complex_passes(self): + # first oneOf valid (complex) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofComplexTypesResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_neither_oneof_valid_complex_fails(self): + # neither oneOf valid (complex) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 2, + "bar": + "quux", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofComplexTypesResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_both_oneof_valid_complex_fails(self): + # both oneOf valid (complex) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofComplexTypesResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_second_oneof_valid_complex_passes(self): + # second oneOf valid (complex) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + "baz", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofComplexTypesResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..ea487855ed --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_response_body_for_content_types/test_post.py @@ -0,0 +1,148 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_oneof_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostOneofResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostOneofResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_second_oneof_valid_passes(self): + # second oneOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 2.5 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_both_oneof_valid_fails(self): + # both oneOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_first_oneof_valid_passes(self): + # first oneOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_neither_oneof_valid_fails(self): + # neither oneOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.5 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_base_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_base_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_base_schema_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_base_schema_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..cfe0200c08 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_base_schema_response_body_for_content_types/test_post.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_oneof_with_base_schema_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostOneofWithBaseSchemaResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostOneofWithBaseSchemaResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_both_oneof_valid_fails(self): + # both oneOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_mismatch_base_schema_fails(self): + # mismatch base schema + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 3 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_one_oneof_valid_passes(self): + # one oneOf valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foobar" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_empty_schema_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_empty_schema_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..471fdae40c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_empty_schema_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_oneof_with_empty_schema_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostOneofWithEmptySchemaResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostOneofWithEmptySchemaResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_both_valid_invalid_fails(self): + # both valid - invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_one_valid_valid_passes(self): + # one valid - valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_required_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_required_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_required_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_required_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..dca5c2b919 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_oneof_with_required_response_body_for_content_types/test_post.py @@ -0,0 +1,168 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_oneof_with_required_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostOneofWithRequiredResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostOneofWithRequiredResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_both_valid_invalid_fails(self): + # both valid - invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + "baz": + 3, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofWithRequiredResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_both_invalid_invalid_fails(self): + # both invalid - invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofWithRequiredResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_first_valid_valid_passes(self): + # first valid - valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "bar": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofWithRequiredResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_second_valid_valid_passes(self): + # second valid - valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + "baz": + 3, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postOneofWithRequiredResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_is_not_anchored_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_is_not_anchored_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_is_not_anchored_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_is_not_anchored_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..245619a948 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_is_not_anchored_response_body_for_content_types/test_post.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_pattern_is_not_anchored_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostPatternIsNotAnchoredResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostPatternIsNotAnchoredResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_matches_a_substring_passes(self): + # matches a substring + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "xxaayy" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..15e3b6dc96 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_pattern_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,276 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_pattern_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostPatternValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostPatternValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_ignores_arrays_passes(self): + # ignores arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPatternValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_objects_passes(self): + # ignores objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPatternValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_null_passes(self): + # ignores null + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPatternValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_floats_passes(self): + # ignores floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.0 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPatternValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_non_matching_pattern_is_invalid_fails(self): + # a non-matching pattern is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "abc" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPatternValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_ignores_booleans_passes(self): + # ignores booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPatternValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_matching_pattern_is_valid_passes(self): + # a matching pattern is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "aaa" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPatternValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_integers_passes(self): + # ignores integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 123 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPatternValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_properties_with_escaped_characters_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_properties_with_escaped_characters_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_properties_with_escaped_characters_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_properties_with_escaped_characters_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..d3104eca24 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_properties_with_escaped_characters_response_body_for_content_types/test_post.py @@ -0,0 +1,120 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_properties_with_escaped_characters_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostPropertiesWithEscapedCharactersResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostPropertiesWithEscapedCharactersResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_object_with_all_numbers_is_valid_passes(self): + # object with all numbers is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo\nbar": + 1, + "foo\"bar": + 1, + "foo\\bar": + 1, + "foo\rbar": + 1, + "foo\tbar": + 1, + "foo\fbar": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_object_with_strings_is_invalid_fails(self): + # object with strings is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo\nbar": + "1", + "foo\"bar": + "1", + "foo\\bar": + "1", + "foo\rbar": + "1", + "foo\tbar": + "1", + "foo\fbar": + "1", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..15809e33db --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/test_post.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_named_ref_valid_passes(self): + # property named $ref valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_property_named_ref_invalid_fails(self): + # property named $ref invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_additionalproperties_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_additionalproperties_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_additionalproperties_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_additionalproperties_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..00e6305e31 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_additionalproperties_response_body_for_content_types/test_post.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_ref_in_additionalproperties_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRefInAdditionalpropertiesResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRefInAdditionalpropertiesResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_named_ref_valid_passes(self): + # property named $ref valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "someProp": + { + "$ref": + "a", + }, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_property_named_ref_invalid_fails(self): + # property named $ref invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "someProp": + { + "$ref": + 2, + }, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_allof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_allof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_allof_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_allof_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..02b7a73a40 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_allof_response_body_for_content_types/test_post.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_ref_in_allof_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRefInAllofResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRefInAllofResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_named_ref_valid_passes(self): + # property named $ref valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInAllofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_property_named_ref_invalid_fails(self): + # property named $ref invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInAllofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_anyof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_anyof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_anyof_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_anyof_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..5094e0cc1c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_anyof_response_body_for_content_types/test_post.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_ref_in_anyof_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRefInAnyofResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRefInAnyofResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_named_ref_valid_passes(self): + # property named $ref valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInAnyofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_property_named_ref_invalid_fails(self): + # property named $ref invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInAnyofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_items_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_items_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_items_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_items_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..73d211de56 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_items_response_body_for_content_types/test_post.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_ref_in_items_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRefInItemsResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRefInItemsResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_named_ref_valid_passes(self): + # property named $ref valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "$ref": + "a", + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInItemsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_property_named_ref_invalid_fails(self): + # property named $ref invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "$ref": + 2, + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInItemsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_not_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_not_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_not_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_not_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..fa87d82640 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_not_response_body_for_content_types/test_post.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_ref_in_not_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRefInNotResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRefInNotResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_named_ref_valid_passes(self): + # property named $ref valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInNotResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_property_named_ref_invalid_fails(self): + # property named $ref invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInNotResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_oneof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_oneof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_oneof_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_oneof_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..50be3af9dc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_oneof_response_body_for_content_types/test_post.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_ref_in_oneof_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRefInOneofResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRefInOneofResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_named_ref_valid_passes(self): + # property named $ref valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + "a", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInOneofResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_property_named_ref_invalid_fails(self): + # property named $ref invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "$ref": + 2, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInOneofResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_property_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_property_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_property_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_property_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..3d93977c2b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_ref_in_property_response_body_for_content_types/test_post.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_ref_in_property_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRefInPropertyResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRefInPropertyResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_named_ref_valid_passes(self): + # property named $ref valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "a": + { + "$ref": + "a", + }, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInPropertyResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_property_named_ref_invalid_fails(self): + # property named $ref invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "a": + { + "$ref": + 2, + }, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRefInPropertyResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_default_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_default_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_default_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_default_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..c7978bfe4b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_default_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_required_default_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRequiredDefaultValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRequiredDefaultValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_not_required_by_default_passes(self): + # not required by default + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRequiredDefaultValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..e3c20b581c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,191 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_required_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRequiredValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRequiredValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_ignores_arrays_passes(self): + # ignores arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRequiredValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_present_required_property_is_valid_passes(self): + # present required property is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRequiredValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_other_non_objects_passes(self): + # ignores other non-objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRequiredValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_ignores_strings_passes(self): + # ignores strings + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRequiredValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_present_required_property_is_invalid_fails(self): + # non-present required property is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "bar": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRequiredValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_empty_array_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_empty_array_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_empty_array_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_empty_array_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..2e220a6fcc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_empty_array_response_body_for_content_types/test_post.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_required_with_empty_array_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRequiredWithEmptyArrayResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRequiredWithEmptyArrayResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_property_not_required_passes(self): + # property not required + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_escaped_characters_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_escaped_characters_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_escaped_characters_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_escaped_characters_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..921a4c2923 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_required_with_escaped_characters_response_body_for_content_types/test_post.py @@ -0,0 +1,112 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_required_with_escaped_characters_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostRequiredWithEscapedCharactersResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostRequiredWithEscapedCharactersResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_object_with_some_properties_missing_is_invalid_fails(self): + # object with some properties missing is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo\nbar": + "1", + "foo\"bar": + "1", + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_object_with_all_properties_present_is_valid_passes(self): + # object with all properties present is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "foo\nbar": + 1, + "foo\"bar": + 1, + "foo\\bar": + 1, + "foo\rbar": + 1, + "foo\tbar": + 1, + "foo\fbar": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_simple_enum_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_simple_enum_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_simple_enum_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_simple_enum_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..abadbf18cb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_simple_enum_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_simple_enum_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostSimpleEnumValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostSimpleEnumValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_something_else_is_invalid_fails(self): + # something else is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 4 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postSimpleEnumValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_one_of_the_enum_is_valid_passes(self): + # one of the enum is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postSimpleEnumValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_string_type_matches_strings_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_string_type_matches_strings_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_string_type_matches_strings_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_string_type_matches_strings_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..e1a0a1dd84 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_string_type_matches_strings_response_body_for_content_types/test_post.py @@ -0,0 +1,276 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_string_type_matches_strings_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostStringTypeMatchesStringsResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostStringTypeMatchesStringsResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_1_is_not_a_string_fails(self): + # 1 is not a string + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_string_is_still_a_string_even_if_it_looks_like_a_number_passes(self): + # a string is still a string, even if it looks like a number + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "1" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_an_empty_string_is_still_a_string_passes(self): + # an empty string is still a string + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_float_is_not_a_string_fails(self): + # a float is not a string + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 1.1 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_object_is_not_a_string_fails(self): + # an object is not a string + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_an_array_is_not_a_string_fails(self): + # an array is not a string + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_boolean_is_not_a_string_fails(self): + # a boolean is not a string + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + True + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_null_is_not_a_string_fails(self): + # null is not a string + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_a_string_is_a_string_passes(self): + # a string is a string + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + "foo" + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..c729358716 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/test_post.py @@ -0,0 +1,131 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_missing_properties_are_not_filled_in_with_the_default_passes(self): + # missing properties are not filled in with the default + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_an_explicit_property_value_is_checked_against_maximum_passing_passes(self): + # an explicit property value is checked against maximum (passing) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "alpha": + 1, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_an_explicit_property_value_is_checked_against_maximum_failing_fails(self): + # an explicit property value is checked against maximum (failing) + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + "alpha": + 5, + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_false_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_false_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_false_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_false_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..f78f2961df --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_false_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,606 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_uniqueitems_false_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostUniqueitemsFalseValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostUniqueitemsFalseValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_non_unique_array_of_integers_is_valid_passes(self): + # non-unique array of integers is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_unique_array_of_objects_is_valid_passes(self): + # unique array of objects is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + "bar", + }, + { + "foo": + "baz", + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_unique_array_of_nested_objects_is_valid_passes(self): + # non-unique array of nested objects is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_unique_array_of_objects_is_valid_passes(self): + # non-unique array of objects is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + "bar", + }, + { + "foo": + "bar", + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_1_and_true_are_unique_passes(self): + # 1 and true are unique + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + True, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_unique_array_of_integers_is_valid_passes(self): + # unique array of integers is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_unique_array_of_arrays_is_valid_passes(self): + # non-unique array of arrays is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "foo", + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_numbers_are_unique_if_mathematically_unequal_passes(self): + # numbers are unique if mathematically unequal + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1.0, + 1.0, + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_false_is_not_equal_to_zero_passes(self): + # false is not equal to zero + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 0, + False, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_unique_array_of_nested_objects_is_valid_passes(self): + # unique array of nested objects is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + { + "foo": + { + "bar": + { + "baz": + False, + }, + }, + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_0_and_false_are_unique_passes(self): + # 0 and false are unique + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 0, + False, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_unique_array_of_arrays_is_valid_passes(self): + # unique array of arrays is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "bar", + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_true_is_not_equal_to_one_passes(self): + # true is not equal to one + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + True, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_unique_heterogeneous_types_are_valid_passes(self): + # non-unique heterogeneous types are valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + }, + [ + 1, + ], + True, + None, + { + }, + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_unique_heterogeneous_types_are_valid_passes(self): + # unique heterogeneous types are valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + }, + [ + 1, + ], + True, + None, + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_validation_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_validation_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..f7a88f24b2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uniqueitems_validation_response_body_for_content_types/test_post.py @@ -0,0 +1,947 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_uniqueitems_validation_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostUniqueitemsValidationResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostUniqueitemsValidationResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_unique_array_of_objects_is_valid_passes(self): + # unique array of objects is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + "bar", + }, + { + "foo": + "baz", + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_true_and_a1_are_unique_passes(self): + # {"a": true} and {"a": 1} are unique + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "a": + True, + }, + { + "a": + 1, + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_unique_heterogeneous_types_are_invalid_fails(self): + # non-unique heterogeneous types are invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + }, + [ + 1, + ], + True, + None, + { + }, + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_nested0_and_false_are_unique_passes(self): + # nested [0] and [false] are unique + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + 0, + ], + "foo", + ], + [ + [ + False, + ], + "foo", + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_a_false_and_a0_are_unique_passes(self): + # {"a": false} and {"a": 0} are unique + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "a": + False, + }, + { + "a": + 0, + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_numbers_are_unique_if_mathematically_unequal_fails(self): + # numbers are unique if mathematically unequal + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1.0, + 1.0, + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_false_is_not_equal_to_zero_passes(self): + # false is not equal to zero + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 0, + False, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_0_and_false_are_unique_passes(self): + # [0] and [false] are unique + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + 0, + ], + [ + False, + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_unique_array_of_arrays_is_valid_passes(self): + # unique array of arrays is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "bar", + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_unique_array_of_nested_objects_is_invalid_fails(self): + # non-unique array of nested objects is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_non_unique_array_of_more_than_two_integers_is_invalid_fails(self): + # non-unique array of more than two integers is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_true_is_not_equal_to_one_passes(self): + # true is not equal to one + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + True, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_objects_are_non_unique_despite_key_order_fails(self): + # objects are non-unique despite key order + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "a": + 1, + "b": + 2, + }, + { + "b": + 2, + "a": + 1, + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_unique_array_of_strings_is_valid_passes(self): + # unique array of strings is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + "foo", + "bar", + "baz", + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_1_and_true_are_unique_passes(self): + # [1] and [true] are unique + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + 1, + ], + [ + True, + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_different_objects_are_unique_passes(self): + # different objects are unique + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "a": + 1, + "b": + 2, + }, + { + "a": + 2, + "b": + 1, + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_unique_array_of_integers_is_valid_passes(self): + # unique array of integers is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 2, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_unique_array_of_more_than_two_arrays_is_invalid_fails(self): + # non-unique array of more than two arrays is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "bar", + ], + [ + "foo", + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_non_unique_array_of_objects_is_invalid_fails(self): + # non-unique array of objects is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + "bar", + }, + { + "foo": + "bar", + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_unique_array_of_nested_objects_is_valid_passes(self): + # unique array of nested objects is valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + "foo": + { + "bar": + { + "baz": + True, + }, + }, + }, + { + "foo": + { + "bar": + { + "baz": + False, + }, + }, + }, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_unique_array_of_arrays_is_invalid_fails(self): + # non-unique array of arrays is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + "foo", + ], + [ + "foo", + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_non_unique_array_of_strings_is_invalid_fails(self): + # non-unique array of strings is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + "foo", + "bar", + "foo", + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + def test_nested1_and_true_are_unique_passes(self): + # nested [1] and [true] are unique + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + [ + [ + 1, + ], + "foo", + ], + [ + [ + True, + ], + "foo", + ], + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_unique_heterogeneous_types_are_valid_passes(self): + # unique heterogeneous types are valid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + { + }, + [ + 1, + ], + True, + None, + 1, + "{}", + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_non_unique_array_of_integers_is_invalid_fails(self): + # non-unique array of integers is invalid + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + 1, + 1, + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)): + self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUniqueitemsValidationResponseBodyForContentTypes', + method='post'.upper(), + content_type=None, + accept_content_type=accept_content_type, + ) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_format_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_format_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..2c93b63f9e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_format_response_body_for_content_types/test_post.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_uri_format_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostUriFormatResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostUriFormatResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_all_string_formats_ignore_objects_passes(self): + # all string formats ignore objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_booleans_passes(self): + # all string formats ignore booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_integers_passes(self): + # all string formats ignore integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_floats_passes(self): + # all string formats ignore floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_arrays_passes(self): + # all string formats ignore arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_nulls_passes(self): + # all string formats ignore nulls + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_reference_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_reference_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_reference_format_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_reference_format_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..6fa62462b5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_reference_format_response_body_for_content_types/test_post.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_uri_reference_format_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostUriReferenceFormatResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostUriReferenceFormatResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_all_string_formats_ignore_objects_passes(self): + # all string formats ignore objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriReferenceFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_booleans_passes(self): + # all string formats ignore booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriReferenceFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_integers_passes(self): + # all string formats ignore integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriReferenceFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_floats_passes(self): + # all string formats ignore floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriReferenceFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_arrays_passes(self): + # all string formats ignore arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriReferenceFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_nulls_passes(self): + # all string formats ignore nulls + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriReferenceFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_template_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_template_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_template_format_response_body_for_content_types/test_post.py b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_template_format_response_body_for_content_types/test_post.py new file mode 100644 index 0000000000..3a57d51e1a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/test/test_paths/test_response_body_post_uri_template_format_response_body_for_content_types/test_post.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import unit_test_api +from unit_test_api.paths.response_body_post_uri_template_format_response_body_for_content_types import post # noqa: E501 +from unit_test_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestResponseBodyPostUriTemplateFormatResponseBodyForContentTypes(ApiTestMixin, unittest.TestCase): + """ + ResponseBodyPostUriTemplateFormatResponseBodyForContentTypes unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + def test_all_string_formats_ignore_objects_passes(self): + # all string formats ignore objects + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + { + } + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriTemplateFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_booleans_passes(self): + # all string formats ignore booleans + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + False + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriTemplateFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_integers_passes(self): + # all string formats ignore integers + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 12 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriTemplateFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_floats_passes(self): + # all string formats ignore floats + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + 13.7 + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriTemplateFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_arrays_passes(self): + # all string formats ignore arrays + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + [ + ] + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriTemplateFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + def test_all_string_formats_ignore_nulls_passes(self): + # all string formats ignore nulls + accept_content_type = 'application/json' + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + payload = ( + None + ) + mock_request.return_value = self.response( + self.json_bytes(payload), + status=self.response_status + ) + api_response = self.api.post( + accept_content_types=(accept_content_type,) + ) + self.assert_pool_manager_request_called_with( + mock_request, + self._configuration.host + '/responseBody/postUriTemplateFormatResponseBodyForContentTypes', + method='post'.upper(), + accept_content_type=accept_content_type, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, post.SchemaFor200ResponseBodyApplicationJson) + deserialized_response_body = post.SchemaFor200ResponseBodyApplicationJson.from_openapi_data_oapg( + payload, + _configuration=self._configuration + ) + assert api_response.body == deserialized_response_body + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/test_python.sh b/samples/openapi3/client/3_0_3_unit_test/python/test_python.sh similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/test_python.sh rename to samples/openapi3/client/3_0_3_unit_test/python/test_python.sh diff --git a/samples/openapi3/client/3_0_3_unit_test/python/tox.ini b/samples/openapi3/client/3_0_3_unit_test/python/tox.ini new file mode 100644 index 0000000000..6db4b8ba64 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/tox.ini @@ -0,0 +1,10 @@ +[tox] +envlist = py37 + +[testenv] +passenv = PYTHON_VERSION +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + pytest --cov=unit_test_api diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/__init__.py similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/__init__.py rename to samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/__init__.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/api_client.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/api_client.py new file mode 100644 index 0000000000..dfbf6822aa --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/api_client.py @@ -0,0 +1,1499 @@ +# coding: utf-8 +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +from decimal import Decimal +import enum +import email +import json +import os +import io +import atexit +from multiprocessing.pool import ThreadPool +import re +import tempfile +import typing +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict +from urllib.parse import urlparse, quote +from urllib3.fields import RequestField as RequestFieldBase + +import frozendict + +from unit_test_api import rest +from unit_test_api.configuration import Configuration +from unit_test_api.exceptions import ApiTypeError, ApiValueError +from unit_test_api.schemas import ( + NoneClass, + BoolClass, + Schema, + FileIO, + BinarySchema, + date, + datetime, + none_type, + Unset, + unset, +) + + +class RequestField(RequestFieldBase): + def __eq__(self, other): + if not isinstance(other, RequestField): + return False + return self.__dict__ == other.__dict__ + + +class JSONEncoder(json.JSONEncoder): + compact_separators = (',', ':') + + def default(self, obj): + if isinstance(obj, str): + return str(obj) + elif isinstance(obj, float): + return float(obj) + elif isinstance(obj, int): + return int(obj) + elif isinstance(obj, Decimal): + if obj.as_tuple().exponent >= 0: + return int(obj) + return float(obj) + elif isinstance(obj, NoneClass): + return None + elif isinstance(obj, BoolClass): + return bool(obj) + elif isinstance(obj, (dict, frozendict.frozendict)): + return {key: self.default(val) for key, val in obj.items()} + elif isinstance(obj, (list, tuple)): + return [self.default(item) for item in obj] + raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__)) + + +class ParameterInType(enum.Enum): + QUERY = 'query' + HEADER = 'header' + PATH = 'path' + COOKIE = 'cookie' + + +class ParameterStyle(enum.Enum): + MATRIX = 'matrix' + LABEL = 'label' + FORM = 'form' + SIMPLE = 'simple' + SPACE_DELIMITED = 'spaceDelimited' + PIPE_DELIMITED = 'pipeDelimited' + DEEP_OBJECT = 'deepObject' + + +class PrefixSeparatorIterator: + # A class to store prefixes and separators for rfc6570 expansions + + def __init__(self, prefix: str, separator: str): + self.prefix = prefix + self.separator = separator + self.first = True + if separator in {'.', '|', '%20'}: + item_separator = separator + else: + item_separator = ',' + self.item_separator = item_separator + + def __iter__(self): + return self + + def __next__(self): + if self.first: + self.first = False + return self.prefix + return self.separator + + +class ParameterSerializerBase: + @classmethod + def _get_default_explode(cls, style: ParameterStyle) -> bool: + return False + + @staticmethod + def __ref6570_item_value(in_data: typing.Any, percent_encode: bool): + """ + Get representation if str/float/int/None/items in list/ values in dict + None is returned if an item is undefined, use cases are value= + - None + - [] + - {} + - [None, None None] + - {'a': None, 'b': None} + """ + if type(in_data) in {str, float, int}: + if percent_encode: + return quote(str(in_data)) + return str(in_data) + elif isinstance(in_data, none_type): + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return None + elif isinstance(in_data, list) and not in_data: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return None + elif isinstance(in_data, dict) and not in_data: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return None + raise ApiValueError('Unable to generate a ref6570 item representation of {}'.format(in_data)) + + @staticmethod + def _to_dict(name: str, value: str): + return {name: value} + + @classmethod + def __ref6570_str_float_int_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + item_value = cls.__ref6570_item_value(in_data, percent_encode) + if item_value is None or (item_value == '' and prefix_separator_iterator.separator == ';'): + return next(prefix_separator_iterator) + var_name_piece + value_pair_equals = '=' if named_parameter_expansion else '' + return next(prefix_separator_iterator) + var_name_piece + value_pair_equals + item_value + + @classmethod + def __ref6570_list_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + item_values = [cls.__ref6570_item_value(v, percent_encode) for v in in_data] + item_values = [v for v in item_values if v is not None] + if not item_values: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + value_pair_equals = '=' if named_parameter_expansion else '' + if not explode: + return ( + next(prefix_separator_iterator) + + var_name_piece + + value_pair_equals + + prefix_separator_iterator.item_separator.join(item_values) + ) + # exploded + return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( + [var_name_piece + value_pair_equals + val for val in item_values] + ) + + @classmethod + def __ref6570_dict_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + in_data_transformed = {key: cls.__ref6570_item_value(val, percent_encode) for key, val in in_data.items()} + in_data_transformed = {key: val for key, val in in_data_transformed.items() if val is not None} + if not in_data_transformed: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + value_pair_equals = '=' if named_parameter_expansion else '' + if not explode: + return ( + next(prefix_separator_iterator) + + var_name_piece + value_pair_equals + + prefix_separator_iterator.item_separator.join( + prefix_separator_iterator.item_separator.join( + item_pair + ) for item_pair in in_data_transformed.items() + ) + ) + # exploded + return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( + [key + '=' + val for key, val in in_data_transformed.items()] + ) + + @classmethod + def _ref6570_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator + ) -> str: + """ + Separator is for separate variables like dict with explode true, not for array item separation + """ + named_parameter_expansion = prefix_separator_iterator.separator in {'&', ';'} + var_name_piece = variable_name if named_parameter_expansion else '' + if type(in_data) in {str, float, int}: + return cls.__ref6570_str_float_int_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) + elif isinstance(in_data, none_type): + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + elif isinstance(in_data, list): + return cls.__ref6570_list_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) + elif isinstance(in_data, dict): + return cls.__ref6570_dict_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) + # bool, bytes, etc + raise ApiValueError('Unable to generate a ref6570 representation of {}'.format(in_data)) + + +class StyleFormSerializer(ParameterSerializerBase): + @classmethod + def _get_default_explode(cls, style: ParameterStyle) -> bool: + if style is ParameterStyle.FORM: + return True + return super()._get_default_explode(style) + + def _serialize_form( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None + ) -> str: + if prefix_separator_iterator is None: + prefix_separator_iterator = PrefixSeparatorIterator('?', '&') + return self._ref6570_expansion( + variable_name=name, + in_data=in_data, + explode=explode, + percent_encode=percent_encode, + prefix_separator_iterator=prefix_separator_iterator + ) + + +class StyleSimpleSerializer(ParameterSerializerBase): + + def _serialize_simple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + percent_encode: bool + ) -> str: + prefix_separator_iterator = PrefixSeparatorIterator('', ',') + return self._ref6570_expansion( + variable_name=name, + in_data=in_data, + explode=explode, + percent_encode=percent_encode, + prefix_separator_iterator=prefix_separator_iterator + ) + + +class JSONDetector: + """ + Works for: + application/json + application/json; charset=UTF-8 + application/json-patch+json + application/geo+json + """ + __json_content_type_pattern = re.compile("application/[^+]*[+]?(json);?.*") + + @classmethod + def _content_type_is_json(cls, content_type: str) -> bool: + if cls.__json_content_type_pattern.match(content_type): + return True + return False + + +@dataclass +class ParameterBase(JSONDetector): + name: str + in_type: ParameterInType + required: bool + style: typing.Optional[ParameterStyle] + explode: typing.Optional[bool] + allow_reserved: typing.Optional[bool] + schema: typing.Optional[typing.Type[Schema]] + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] + + __style_to_in_type = { + ParameterStyle.MATRIX: {ParameterInType.PATH}, + ParameterStyle.LABEL: {ParameterInType.PATH}, + ParameterStyle.FORM: {ParameterInType.QUERY, ParameterInType.COOKIE}, + ParameterStyle.SIMPLE: {ParameterInType.PATH, ParameterInType.HEADER}, + ParameterStyle.SPACE_DELIMITED: {ParameterInType.QUERY}, + ParameterStyle.PIPE_DELIMITED: {ParameterInType.QUERY}, + ParameterStyle.DEEP_OBJECT: {ParameterInType.QUERY}, + } + __in_type_to_default_style = { + ParameterInType.QUERY: ParameterStyle.FORM, + ParameterInType.PATH: ParameterStyle.SIMPLE, + ParameterInType.HEADER: ParameterStyle.SIMPLE, + ParameterInType.COOKIE: ParameterStyle.FORM, + } + __disallowed_header_names = {'Accept', 'Content-Type', 'Authorization'} + _json_encoder = JSONEncoder() + + @classmethod + def __verify_style_to_in_type(cls, style: typing.Optional[ParameterStyle], in_type: ParameterInType): + if style is None: + return + in_type_set = cls.__style_to_in_type[style] + if in_type not in in_type_set: + raise ValueError( + 'Invalid style and in_type combination. For style={} only in_type={} are allowed'.format( + style, in_type_set + ) + ) + + def __init__( + self, + name: str, + in_type: ParameterInType, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + if schema is None and content is None: + raise ValueError('Value missing; Pass in either schema or content') + if schema and content: + raise ValueError('Too many values provided. Both schema and content were provided. Only one may be input') + if name in self.__disallowed_header_names and in_type is ParameterInType.HEADER: + raise ValueError('Invalid name, name may not be one of {}'.format(self.__disallowed_header_names)) + self.__verify_style_to_in_type(style, in_type) + if content is None and style is None: + style = self.__in_type_to_default_style[in_type] + if content is not None and in_type in self.__in_type_to_default_style and len(content) != 1: + raise ValueError('Invalid content length, content length must equal 1') + self.in_type = in_type + self.name = name + self.required = required + self.style = style + self.explode = explode + self.allow_reserved = allow_reserved + self.schema = schema + self.content = content + + def _serialize_json( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + eliminate_whitespace: bool = False + ) -> str: + if eliminate_whitespace: + return json.dumps(in_data, separators=self._json_encoder.compact_separators) + return json.dumps(in_data) + + +class PathParameter(ParameterBase, StyleSimpleSerializer): + + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + super().__init__( + name, + in_type=ParameterInType.PATH, + required=required, + style=style, + explode=explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + def __serialize_label( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Dict[str, str]: + prefix_separator_iterator = PrefixSeparatorIterator('.', '.') + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_matrix( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Dict[str, str]: + prefix_separator_iterator = PrefixSeparatorIterator(';', ';') + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_simple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + ) -> typing.Dict[str, str]: + value = self._serialize_simple( + in_data=in_data, + name=self.name, + explode=self.explode, + percent_encode=True + ) + return self._to_dict(self.name, value) + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> typing.Dict[str, str]: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + simple -> path + path: + returns path_params: dict + label -> path + returns path_params + matrix -> path + returns path_params + """ + if self.style: + if self.style is ParameterStyle.SIMPLE: + return self.__serialize_simple(cast_in_data) + elif self.style is ParameterStyle.LABEL: + return self.__serialize_label(cast_in_data) + elif self.style is ParameterStyle.MATRIX: + return self.__serialize_matrix(cast_in_data) + # self.content will be length one + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data) + return self._to_dict(self.name, value) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class QueryParameter(ParameterBase, StyleFormSerializer): + + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: typing.Optional[bool] = None, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + used_style = ParameterStyle.FORM if style is None else style + used_explode = self._get_default_explode(used_style) if explode is None else explode + + super().__init__( + name, + in_type=ParameterInType.QUERY, + required=required, + style=used_style, + explode=used_explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + def __serialize_space_delimited( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] + ) -> typing.Dict[str, str]: + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_pipe_delimited( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] + ) -> typing.Dict[str, str]: + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_form( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] + ) -> typing.Dict[str, str]: + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + value = self._serialize_form( + in_data, + name=self.name, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def get_prefix_separator_iterator(self) -> typing.Optional[PrefixSeparatorIterator]: + if self.style is ParameterStyle.FORM: + return PrefixSeparatorIterator('?', '&') + elif self.style is ParameterStyle.SPACE_DELIMITED: + return PrefixSeparatorIterator('', '%20') + elif self.style is ParameterStyle.PIPE_DELIMITED: + return PrefixSeparatorIterator('', '|') + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None + ) -> typing.Dict[str, str]: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + form -> query + query: + - GET/HEAD/DELETE: could use fields + - PUT/POST: must use urlencode to send parameters + returns fields: tuple + spaceDelimited -> query + returns fields + pipeDelimited -> query + returns fields + deepObject -> query, https://github.com/OAI/OpenAPI-Specification/issues/1706 + returns fields + """ + if self.style: + # TODO update query ones to omit setting values when [] {} or None is input + if self.style is ParameterStyle.FORM: + return self.__serialize_form(cast_in_data, prefix_separator_iterator) + elif self.style is ParameterStyle.SPACE_DELIMITED: + return self.__serialize_space_delimited(cast_in_data, prefix_separator_iterator) + elif self.style is ParameterStyle.PIPE_DELIMITED: + return self.__serialize_pipe_delimited(cast_in_data, prefix_separator_iterator) + # self.content will be length one + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data, eliminate_whitespace=True) + return self._to_dict( + self.name, + next(prefix_separator_iterator) + self.name + '=' + quote(value) + ) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class CookieParameter(ParameterBase, StyleFormSerializer): + + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: typing.Optional[bool] = None, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + used_style = ParameterStyle.FORM if style is None and content is None and schema else style + used_explode = self._get_default_explode(used_style) if explode is None else explode + + super().__init__( + name, + in_type=ParameterInType.COOKIE, + required=required, + style=used_style, + explode=used_explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> typing.Dict[str, str]: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + form -> cookie + returns fields: tuple + """ + if self.style: + """ + TODO add escaping of comma, space, equals + or turn encoding on + """ + value = self._serialize_form( + cast_in_data, + explode=self.explode, + name=self.name, + percent_encode=False, + prefix_separator_iterator=PrefixSeparatorIterator('', '&') + ) + return self._to_dict(self.name, value) + # self.content will be length one + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data) + return self._to_dict(self.name, value) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class HeaderParameter(ParameterBase, StyleSimpleSerializer): + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + super().__init__( + name, + in_type=ParameterInType.HEADER, + required=required, + style=style, + explode=explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + @staticmethod + def __to_headers(in_data: typing.Tuple[typing.Tuple[str, str], ...]) -> HTTPHeaderDict: + data = tuple(t for t in in_data if t) + headers = HTTPHeaderDict() + if not data: + return headers + headers.extend(data) + return headers + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> HTTPHeaderDict: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + simple -> header + headers: PoolManager needs a mapping, tuple is close + returns headers: dict + """ + if self.style: + value = self._serialize_simple(cast_in_data, self.name, self.explode, False) + return self.__to_headers(((self.name, value),)) + # self.content will be length one + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data) + return self.__to_headers(((self.name, value),)) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class Encoding: + def __init__( + self, + content_type: str, + headers: typing.Optional[typing.Dict[str, HeaderParameter]] = None, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: bool = False, + ): + self.content_type = content_type + self.headers = headers + self.style = style + self.explode = explode + self.allow_reserved = allow_reserved + + +@dataclass +class MediaType: + """ + Used to store request and response body schema information + encoding: + A map between a property name and its encoding information. + The key, being the property name, MUST exist in the schema as a property. + The encoding object SHALL only apply to requestBody objects when the media type is + multipart or application/x-www-form-urlencoded. + """ + schema: typing.Optional[typing.Type[Schema]] = None + encoding: typing.Optional[typing.Dict[str, Encoding]] = None + + +@dataclass +class ApiResponse: + response: urllib3.HTTPResponse + body: typing.Union[Unset, Schema] + headers: typing.Union[Unset, typing.List[HeaderParameter]] + + def __init__( + self, + response: urllib3.HTTPResponse, + body: typing.Union[Unset, typing.Type[Schema]], + headers: typing.Union[Unset, typing.List[HeaderParameter]] + ): + """ + pycharm needs this to prevent 'Unexpected argument' warnings + """ + self.response = response + self.body = body + self.headers = headers + + +@dataclass +class ApiResponseWithoutDeserialization(ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[Unset, typing.Type[Schema]] = unset + headers: typing.Union[Unset, typing.List[HeaderParameter]] = unset + + +class OpenApiResponse(JSONDetector): + __filename_content_disposition_pattern = re.compile('filename="(.+?)"') + + def __init__( + self, + response_cls: typing.Type[ApiResponse] = ApiResponse, + content: typing.Optional[typing.Dict[str, MediaType]] = None, + headers: typing.Optional[typing.List[HeaderParameter]] = None, + ): + self.headers = headers + if content is not None and len(content) == 0: + raise ValueError('Invalid value for content, the content dict must have >= 1 entry') + self.content = content + self.response_cls = response_cls + + @staticmethod + def __deserialize_json(response: urllib3.HTTPResponse) -> typing.Any: + # python must be >= 3.9 so we can pass in bytes into json.loads + return json.loads(response.data) + + @staticmethod + def __file_name_from_response_url(response_url: typing.Optional[str]) -> typing.Optional[str]: + if response_url is None: + return None + url_path = urlparse(response_url).path + if url_path: + path_basename = os.path.basename(url_path) + if path_basename: + _filename, ext = os.path.splitext(path_basename) + if ext: + return path_basename + return None + + @classmethod + def __file_name_from_content_disposition(cls, content_disposition: typing.Optional[str]) -> typing.Optional[str]: + if content_disposition is None: + return None + match = cls.__filename_content_disposition_pattern.search(content_disposition) + if not match: + return None + return match.group(1) + + def __deserialize_application_octet_stream( + self, response: urllib3.HTTPResponse + ) -> typing.Union[bytes, io.BufferedReader]: + """ + urllib3 use cases: + 1. when preload_content=True (stream=False) then supports_chunked_reads is False and bytes are returned + 2. when preload_content=False (stream=True) then supports_chunked_reads is True and + a file will be written and returned + """ + if response.supports_chunked_reads(): + file_name = ( + self.__file_name_from_content_disposition(response.headers.get('content-disposition')) + or self.__file_name_from_response_url(response.geturl()) + ) + + if file_name is None: + _fd, path = tempfile.mkstemp() + else: + path = os.path.join(tempfile.gettempdir(), file_name) + + with open(path, 'wb') as new_file: + chunk_size = 1024 + while True: + data = response.read(chunk_size) + if not data: + break + new_file.write(data) + # release_conn is needed for streaming connections only + response.release_conn() + new_file = open(path, 'rb') + return new_file + else: + return response.data + + @staticmethod + def __deserialize_multipart_form_data( + response: urllib3.HTTPResponse + ) -> typing.Dict[str, typing.Any]: + msg = email.message_from_bytes(response.data) + return { + part.get_param("name", header="Content-Disposition"): part.get_payload( + decode=True + ).decode(part.get_content_charset()) + if part.get_content_charset() + else part.get_payload() + for part in msg.get_payload() + } + + def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse: + content_type = response.getheader('content-type') + deserialized_body = unset + streamed = response.supports_chunked_reads() + + deserialized_headers = unset + if self.headers is not None: + # TODO add header deserialiation here + pass + + if self.content is not None: + if content_type not in self.content: + raise ApiValueError( + f"Invalid content_type returned. Content_type='{content_type}' was returned " + f"when only {str(set(self.content))} are defined for status_code={str(response.status)}" + ) + body_schema = self.content[content_type].schema + if body_schema is None: + # some specs do not define response content media type schemas + return self.response_cls( + response=response, + headers=deserialized_headers, + body=unset + ) + + if self._content_type_is_json(content_type): + body_data = self.__deserialize_json(response) + elif content_type == 'application/octet-stream': + body_data = self.__deserialize_application_octet_stream(response) + elif content_type.startswith('multipart/form-data'): + body_data = self.__deserialize_multipart_form_data(response) + content_type = 'multipart/form-data' + else: + raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type)) + deserialized_body = body_schema.from_openapi_data_oapg( + body_data, _configuration=configuration) + elif streamed: + response.release_conn() + + return self.response_cls( + response=response, + headers=deserialized_headers, + body=deserialized_body + ) + + +class ApiClient: + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + :param pool_threads: The number of threads to use for async requests + to the API. More threads means more concurrent API requests. + """ + + _pool = None + + def __init__( + self, + configuration: typing.Optional[Configuration] = None, + header_name: typing.Optional[str] = None, + header_value: typing.Optional[str] = None, + cookie: typing.Optional[str] = None, + pool_threads: int = 1 + ): + if configuration is None: + configuration = Configuration() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = HTTPHeaderDict() + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + if self._pool: + self._pool.close() + self._pool.join() + self._pool = None + if hasattr(atexit, 'unregister'): + atexit.unregister(self.close) + + @property + def pool(self): + """Create thread pool on first request + avoids instantiating unused threadpool for blocking clients. + """ + if self._pool is None: + atexit.register(self.close) + self._pool = ThreadPool(self.pool_threads) + return self._pool + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + def __call_api( + self, + resource_path: str, + method: str, + headers: typing.Optional[HTTPHeaderDict] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + host: typing.Optional[str] = None, + ) -> urllib3.HTTPResponse: + + # header parameters + used_headers = HTTPHeaderDict(self.default_headers) + if self.cookie: + headers['Cookie'] = self.cookie + + # auth setting + self.update_params_for_auth(used_headers, + auth_settings, resource_path, method, body) + + # must happen after cookie setting and auth setting in case user is overriding those + if headers: + used_headers.update(headers) + + # request url + if host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = host + resource_path + + # perform request and return response + response = self.request( + method, + url, + headers=used_headers, + fields=fields, + body=body, + stream=stream, + timeout=timeout, + ) + return response + + def call_api( + self, + resource_path: str, + method: str, + headers: typing.Optional[HTTPHeaderDict] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + async_req: typing.Optional[bool] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + host: typing.Optional[str] = None, + ) -> urllib3.HTTPResponse: + """Makes the HTTP request (synchronous) and returns deserialized data. + + To make an async_req request, set the async_req parameter. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param headers: Header parameters to be + placed in the request header. + :param body: Request body. + :param fields: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings: Auth Settings names for the request. + :param async_req: execute request asynchronously + :type async_req: bool, optional TODO remove, unused + :param stream: if True, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Also when True, if the openapi spec describes a file download, + the data will be written to a local filesystme file and the BinarySchema + instance will also inherit from FileSchema and FileIO + Default is False. + :type stream: bool, optional + :param timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param host: api endpoint host + :return: + If async_req parameter is True, + the request will be called asynchronously. + The method will return the request thread. + If parameter async_req is False or missing, + then the method will return the response directly. + """ + + if not async_req: + return self.__call_api( + resource_path, + method, + headers, + body, + fields, + auth_settings, + stream, + timeout, + host, + ) + + return self.pool.apply_async( + self.__call_api, + ( + resource_path, + method, + headers, + body, + json, + fields, + auth_settings, + stream, + timeout, + host, + ) + ) + + def request( + self, + method: str, + url: str, + headers: typing.Optional[HTTPHeaderDict] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> urllib3.HTTPResponse: + """Makes the HTTP request using RESTClient.""" + if method == "GET": + return self.rest_client.GET(url, + stream=stream, + timeout=timeout, + headers=headers) + elif method == "HEAD": + return self.rest_client.HEAD(url, + stream=stream, + timeout=timeout, + headers=headers) + elif method == "OPTIONS": + return self.rest_client.OPTIONS(url, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "POST": + return self.rest_client.POST(url, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "PUT": + return self.rest_client.PUT(url, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "PATCH": + return self.rest_client.PATCH(url, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "DELETE": + return self.rest_client.DELETE(url, + headers=headers, + stream=stream, + timeout=timeout, + body=body) + else: + raise ApiValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def update_params_for_auth(self, headers, auth_settings, + resource_path, method, body): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param auth_settings: Authentication setting identifiers list. + :param resource_path: A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method. + :param body: A object representing the body of the HTTP request. + The object type is the return value of _encoder.default(). + """ + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if not auth_setting: + continue + if auth_setting['in'] == 'cookie': + headers.add('Cookie', auth_setting['value']) + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers.add(auth_setting['key'], auth_setting['value']) + elif auth_setting['in'] == 'query': + """ TODO implement auth in query + need to pass in prefix_separator_iterator + and need to output resource_path with query params added + """ + raise ApiValueError("Auth in query not yet implemented") + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + +class Api: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client: typing.Optional[ApiClient] = None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + @staticmethod + def _verify_typed_dict_inputs_oapg(cls: typing.Type[typing_extensions.TypedDict], data: typing.Dict[str, typing.Any]): + """ + Ensures that: + - required keys are present + - additional properties are not input + - value stored under required keys do not have the value unset + Note: detailed value checking is done in schema classes + """ + missing_required_keys = [] + required_keys_with_unset_values = [] + for required_key in cls.__required_keys__: + if required_key not in data: + missing_required_keys.append(required_key) + continue + value = data[required_key] + if value is unset: + required_keys_with_unset_values.append(required_key) + if missing_required_keys: + raise ApiTypeError( + '{} missing {} required arguments: {}'.format( + cls.__name__, len(missing_required_keys), missing_required_keys + ) + ) + if required_keys_with_unset_values: + raise ApiValueError( + '{} contains invalid unset values for {} required keys: {}'.format( + cls.__name__, len(required_keys_with_unset_values), required_keys_with_unset_values + ) + ) + + disallowed_additional_keys = [] + for key in data: + if key in cls.__required_keys__ or key in cls.__optional_keys__: + continue + disallowed_additional_keys.append(key) + if disallowed_additional_keys: + raise ApiTypeError( + '{} got {} unexpected keyword arguments: {}'.format( + cls.__name__, len(disallowed_additional_keys), disallowed_additional_keys + ) + ) + + def _get_host_oapg( + self, + operation_id: str, + servers: typing.Tuple[typing.Dict[str, str], ...] = tuple(), + host_index: typing.Optional[int] = None + ) -> typing.Optional[str]: + configuration = self.api_client.configuration + try: + if host_index is None: + index = configuration.server_operation_index.get( + operation_id, configuration.server_index + ) + else: + index = host_index + server_variables = configuration.server_operation_variables.get( + operation_id, configuration.server_variables + ) + host = configuration.get_host_from_settings( + index, variables=server_variables, servers=servers + ) + except IndexError: + if servers: + raise ApiValueError( + "Invalid host index. Must be 0 <= index < %s" % + len(servers) + ) + host = None + return host + + +class SerializedRequestBody(typing_extensions.TypedDict, total=False): + body: typing.Union[str, bytes] + fields: typing.Tuple[typing.Union[RequestField, typing.Tuple[str, str]], ...] + + +class RequestBody(StyleFormSerializer, JSONDetector): + """ + A request body parameter + content: content_type to MediaType Schema info + """ + __json_encoder = JSONEncoder() + + def __init__( + self, + content: typing.Dict[str, MediaType], + required: bool = False, + ): + self.required = required + if len(content) == 0: + raise ValueError('Invalid value for content, the content dict must have >= 1 entry') + self.content = content + + def __serialize_json( + self, + in_data: typing.Any + ) -> typing.Dict[str, bytes]: + in_data = self.__json_encoder.default(in_data) + json_str = json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode( + "utf-8" + ) + return dict(body=json_str) + + @staticmethod + def __serialize_text_plain(in_data: typing.Any) -> typing.Dict[str, str]: + if isinstance(in_data, frozendict.frozendict): + raise ValueError('Unable to serialize type frozendict.frozendict to text/plain') + elif isinstance(in_data, tuple): + raise ValueError('Unable to serialize type tuple to text/plain') + elif isinstance(in_data, NoneClass): + raise ValueError('Unable to serialize type NoneClass to text/plain') + elif isinstance(in_data, BoolClass): + raise ValueError('Unable to serialize type BoolClass to text/plain') + return dict(body=str(in_data)) + + def __multipart_json_item(self, key: str, value: Schema) -> RequestField: + json_value = self.__json_encoder.default(value) + return RequestField(name=key, data=json.dumps(json_value), headers={'Content-Type': 'application/json'}) + + def __multipart_form_item(self, key: str, value: Schema) -> RequestField: + if isinstance(value, str): + return RequestField(name=key, data=str(value), headers={'Content-Type': 'text/plain'}) + elif isinstance(value, bytes): + return RequestField(name=key, data=value, headers={'Content-Type': 'application/octet-stream'}) + elif isinstance(value, FileIO): + request_field = RequestField( + name=key, + data=value.read(), + filename=os.path.basename(value.name), + headers={'Content-Type': 'application/octet-stream'} + ) + value.close() + return request_field + else: + return self.__multipart_json_item(key=key, value=value) + + def __serialize_multipart_form_data( + self, in_data: Schema + ) -> typing.Dict[str, typing.Tuple[RequestField, ...]]: + if not isinstance(in_data, frozendict.frozendict): + raise ValueError(f'Unable to serialize {in_data} to multipart/form-data because it is not a dict of data') + """ + In a multipart/form-data request body, each schema property, or each element of a schema array property, + takes a section in the payload with an internal header as defined by RFC7578. The serialization strategy + for each property of a multipart/form-data request body can be specified in an associated Encoding Object. + + When passing in multipart types, boundaries MAY be used to separate sections of the content being + transferred – thus, the following default Content-Types are defined for multipart: + + If the (object) property is a primitive, or an array of primitive values, the default Content-Type is text/plain + If the property is complex, or an array of complex values, the default Content-Type is application/json + Question: how is the array of primitives encoded? + If the property is a type: string with a contentEncoding, the default Content-Type is application/octet-stream + """ + fields = [] + for key, value in in_data.items(): + if isinstance(value, tuple): + if value: + # values use explode = True, so the code makes a RequestField for each item with name=key + for item in value: + request_field = self.__multipart_form_item(key=key, value=item) + fields.append(request_field) + else: + # send an empty array as json because exploding will not send it + request_field = self.__multipart_json_item(key=key, value=value) + fields.append(request_field) + else: + request_field = self.__multipart_form_item(key=key, value=value) + fields.append(request_field) + + return dict(fields=tuple(fields)) + + def __serialize_application_octet_stream(self, in_data: BinarySchema) -> typing.Dict[str, bytes]: + if isinstance(in_data, bytes): + return dict(body=in_data) + # FileIO type + result = dict(body=in_data.read()) + in_data.close() + return result + + def __serialize_application_x_www_form_data( + self, in_data: typing.Any + ) -> SerializedRequestBody: + """ + POST submission of form data in body + """ + if not isinstance(in_data, frozendict.frozendict): + raise ValueError( + f'Unable to serialize {in_data} to application/x-www-form-urlencoded because it is not a dict of data') + cast_in_data = self.__json_encoder.default(in_data) + value = self._serialize_form(cast_in_data, name='', explode=True, percent_encode=False) + return dict(body=value) + + def serialize( + self, in_data: typing.Any, content_type: str + ) -> SerializedRequestBody: + """ + If a str is returned then the result will be assigned to data when making the request + If a tuple is returned then the result will be used as fields input in encode_multipart_formdata + Return a tuple of + + The key of the return dict is + - body for application/json + - encode_multipart and fields for multipart/form-data + """ + media_type = self.content[content_type] + if isinstance(in_data, media_type.schema): + cast_in_data = in_data + elif isinstance(in_data, (dict, frozendict.frozendict)) and in_data: + cast_in_data = media_type.schema(**in_data) + else: + cast_in_data = media_type.schema(in_data) + # TODO check for and use encoding if it exists + # and content_type is multipart or application/x-www-form-urlencoded + if self._content_type_is_json(content_type): + return self.__serialize_json(cast_in_data) + elif content_type == 'text/plain': + return self.__serialize_text_plain(cast_in_data) + elif content_type == 'multipart/form-data': + return self.__serialize_multipart_form_data(cast_in_data) + elif content_type == 'application/x-www-form-urlencoded': + return self.__serialize_application_x_www_form_data(cast_in_data) + elif content_type == 'application/octet-stream': + return self.__serialize_application_octet_stream(cast_in_data) + raise NotImplementedError('Serialization has not yet been implemented for {}'.format(content_type)) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/__init__.py new file mode 100644 index 0000000000..7840f7726f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/__init__.py @@ -0,0 +1,3 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints then import them from +# tags, paths, or path_to_api, or tag_to_api \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/path_to_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/path_to_api.py new file mode 100644 index 0000000000..8a75c50c3e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/path_to_api.py @@ -0,0 +1,536 @@ +import typing_extensions + +from unit_test_api.paths import PathValues +from unit_test_api.apis.paths.request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body import RequestBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody +from unit_test_api.apis.paths.response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types import ResponseBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_additionalproperties_can_exist_by_itself_request_body import RequestBodyPostAdditionalpropertiesCanExistByItselfRequestBody +from unit_test_api.apis.paths.response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types import ResponseBodyPostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_additionalproperties_are_allowed_by_default_request_body import RequestBodyPostAdditionalpropertiesAreAllowedByDefaultRequestBody +from unit_test_api.apis.paths.response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types import ResponseBodyPostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_additionalproperties_should_not_look_in_applicators_request_body import RequestBodyPostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody +from unit_test_api.apis.paths.response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types import ResponseBodyPostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_allof_request_body import RequestBodyPostAllofRequestBody +from unit_test_api.apis.paths.response_body_post_allof_response_body_for_content_types import ResponseBodyPostAllofResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_allof_with_base_schema_request_body import RequestBodyPostAllofWithBaseSchemaRequestBody +from unit_test_api.apis.paths.response_body_post_allof_with_base_schema_response_body_for_content_types import ResponseBodyPostAllofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_allof_simple_types_request_body import RequestBodyPostAllofSimpleTypesRequestBody +from unit_test_api.apis.paths.response_body_post_allof_simple_types_response_body_for_content_types import ResponseBodyPostAllofSimpleTypesResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_allof_with_one_empty_schema_request_body import RequestBodyPostAllofWithOneEmptySchemaRequestBody +from unit_test_api.apis.paths.response_body_post_allof_with_one_empty_schema_response_body_for_content_types import ResponseBodyPostAllofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_allof_with_two_empty_schemas_request_body import RequestBodyPostAllofWithTwoEmptySchemasRequestBody +from unit_test_api.apis.paths.response_body_post_allof_with_two_empty_schemas_response_body_for_content_types import ResponseBodyPostAllofWithTwoEmptySchemasResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_allof_with_the_first_empty_schema_request_body import RequestBodyPostAllofWithTheFirstEmptySchemaRequestBody +from unit_test_api.apis.paths.response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types import ResponseBodyPostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_allof_with_the_last_empty_schema_request_body import RequestBodyPostAllofWithTheLastEmptySchemaRequestBody +from unit_test_api.apis.paths.response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types import ResponseBodyPostAllofWithTheLastEmptySchemaResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_nested_allof_to_check_validation_semantics_request_body import RequestBodyPostNestedAllofToCheckValidationSemanticsRequestBody +from unit_test_api.apis.paths.response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types import ResponseBodyPostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_allof_combined_with_anyof_oneof_request_body import RequestBodyPostAllofCombinedWithAnyofOneofRequestBody +from unit_test_api.apis.paths.response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types import ResponseBodyPostAllofCombinedWithAnyofOneofResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_anyof_request_body import RequestBodyPostAnyofRequestBody +from unit_test_api.apis.paths.response_body_post_anyof_response_body_for_content_types import ResponseBodyPostAnyofResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_anyof_with_base_schema_request_body import RequestBodyPostAnyofWithBaseSchemaRequestBody +from unit_test_api.apis.paths.response_body_post_anyof_with_base_schema_response_body_for_content_types import ResponseBodyPostAnyofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_anyof_complex_types_request_body import RequestBodyPostAnyofComplexTypesRequestBody +from unit_test_api.apis.paths.response_body_post_anyof_complex_types_response_body_for_content_types import ResponseBodyPostAnyofComplexTypesResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_anyof_with_one_empty_schema_request_body import RequestBodyPostAnyofWithOneEmptySchemaRequestBody +from unit_test_api.apis.paths.response_body_post_anyof_with_one_empty_schema_response_body_for_content_types import ResponseBodyPostAnyofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_nested_anyof_to_check_validation_semantics_request_body import RequestBodyPostNestedAnyofToCheckValidationSemanticsRequestBody +from unit_test_api.apis.paths.response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types import ResponseBodyPostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_invalid_string_value_for_default_request_body import RequestBodyPostInvalidStringValueForDefaultRequestBody +from unit_test_api.apis.paths.response_body_post_invalid_string_value_for_default_response_body_for_content_types import ResponseBodyPostInvalidStringValueForDefaultResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body import RequestBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody +from unit_test_api.apis.paths.response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types import ResponseBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_simple_enum_validation_request_body import RequestBodyPostSimpleEnumValidationRequestBody +from unit_test_api.apis.paths.response_body_post_simple_enum_validation_response_body_for_content_types import ResponseBodyPostSimpleEnumValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_enums_in_properties_request_body import RequestBodyPostEnumsInPropertiesRequestBody +from unit_test_api.apis.paths.response_body_post_enums_in_properties_response_body_for_content_types import ResponseBodyPostEnumsInPropertiesResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_enum_with_escaped_characters_request_body import RequestBodyPostEnumWithEscapedCharactersRequestBody +from unit_test_api.apis.paths.response_body_post_enum_with_escaped_characters_response_body_for_content_types import ResponseBodyPostEnumWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_enum_with_false_does_not_match0_request_body import RequestBodyPostEnumWithFalseDoesNotMatch0RequestBody +from unit_test_api.apis.paths.response_body_post_enum_with_false_does_not_match0_response_body_for_content_types import ResponseBodyPostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_enum_with_true_does_not_match1_request_body import RequestBodyPostEnumWithTrueDoesNotMatch1RequestBody +from unit_test_api.apis.paths.response_body_post_enum_with_true_does_not_match1_response_body_for_content_types import ResponseBodyPostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_enum_with0_does_not_match_false_request_body import RequestBodyPostEnumWith0DoesNotMatchFalseRequestBody +from unit_test_api.apis.paths.response_body_post_enum_with0_does_not_match_false_response_body_for_content_types import ResponseBodyPostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_enum_with1_does_not_match_true_request_body import RequestBodyPostEnumWith1DoesNotMatchTrueRequestBody +from unit_test_api.apis.paths.response_body_post_enum_with1_does_not_match_true_response_body_for_content_types import ResponseBodyPostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_nul_characters_in_strings_request_body import RequestBodyPostNulCharactersInStringsRequestBody +from unit_test_api.apis.paths.response_body_post_nul_characters_in_strings_response_body_for_content_types import ResponseBodyPostNulCharactersInStringsResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_email_format_request_body import RequestBodyPostEmailFormatRequestBody +from unit_test_api.apis.paths.response_body_post_email_format_response_body_for_content_types import ResponseBodyPostEmailFormatResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_ipv4_format_request_body import RequestBodyPostIpv4FormatRequestBody +from unit_test_api.apis.paths.response_body_post_ipv4_format_response_body_for_content_types import ResponseBodyPostIpv4FormatResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_ipv6_format_request_body import RequestBodyPostIpv6FormatRequestBody +from unit_test_api.apis.paths.response_body_post_ipv6_format_response_body_for_content_types import ResponseBodyPostIpv6FormatResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_hostname_format_request_body import RequestBodyPostHostnameFormatRequestBody +from unit_test_api.apis.paths.response_body_post_hostname_format_response_body_for_content_types import ResponseBodyPostHostnameFormatResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_date_time_format_request_body import RequestBodyPostDateTimeFormatRequestBody +from unit_test_api.apis.paths.response_body_post_date_time_format_response_body_for_content_types import ResponseBodyPostDateTimeFormatResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_json_pointer_format_request_body import RequestBodyPostJsonPointerFormatRequestBody +from unit_test_api.apis.paths.response_body_post_json_pointer_format_response_body_for_content_types import ResponseBodyPostJsonPointerFormatResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_uri_format_request_body import RequestBodyPostUriFormatRequestBody +from unit_test_api.apis.paths.response_body_post_uri_format_response_body_for_content_types import ResponseBodyPostUriFormatResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_uri_reference_format_request_body import RequestBodyPostUriReferenceFormatRequestBody +from unit_test_api.apis.paths.response_body_post_uri_reference_format_response_body_for_content_types import ResponseBodyPostUriReferenceFormatResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_uri_template_format_request_body import RequestBodyPostUriTemplateFormatRequestBody +from unit_test_api.apis.paths.response_body_post_uri_template_format_response_body_for_content_types import ResponseBodyPostUriTemplateFormatResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_nested_items_request_body import RequestBodyPostNestedItemsRequestBody +from unit_test_api.apis.paths.response_body_post_nested_items_response_body_for_content_types import ResponseBodyPostNestedItemsResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_maximum_validation_request_body import RequestBodyPostMaximumValidationRequestBody +from unit_test_api.apis.paths.response_body_post_maximum_validation_response_body_for_content_types import ResponseBodyPostMaximumValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_maximum_validation_with_unsigned_integer_request_body import RequestBodyPostMaximumValidationWithUnsignedIntegerRequestBody +from unit_test_api.apis.paths.response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types import ResponseBodyPostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_maxitems_validation_request_body import RequestBodyPostMaxitemsValidationRequestBody +from unit_test_api.apis.paths.response_body_post_maxitems_validation_response_body_for_content_types import ResponseBodyPostMaxitemsValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_maxlength_validation_request_body import RequestBodyPostMaxlengthValidationRequestBody +from unit_test_api.apis.paths.response_body_post_maxlength_validation_response_body_for_content_types import ResponseBodyPostMaxlengthValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_maxproperties_validation_request_body import RequestBodyPostMaxpropertiesValidationRequestBody +from unit_test_api.apis.paths.response_body_post_maxproperties_validation_response_body_for_content_types import ResponseBodyPostMaxpropertiesValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_maxproperties0_means_the_object_is_empty_request_body import RequestBodyPostMaxproperties0MeansTheObjectIsEmptyRequestBody +from unit_test_api.apis.paths.response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types import ResponseBodyPostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_minimum_validation_request_body import RequestBodyPostMinimumValidationRequestBody +from unit_test_api.apis.paths.response_body_post_minimum_validation_response_body_for_content_types import ResponseBodyPostMinimumValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_minimum_validation_with_signed_integer_request_body import RequestBodyPostMinimumValidationWithSignedIntegerRequestBody +from unit_test_api.apis.paths.response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types import ResponseBodyPostMinimumValidationWithSignedIntegerResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_minitems_validation_request_body import RequestBodyPostMinitemsValidationRequestBody +from unit_test_api.apis.paths.response_body_post_minitems_validation_response_body_for_content_types import ResponseBodyPostMinitemsValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_minlength_validation_request_body import RequestBodyPostMinlengthValidationRequestBody +from unit_test_api.apis.paths.response_body_post_minlength_validation_response_body_for_content_types import ResponseBodyPostMinlengthValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_minproperties_validation_request_body import RequestBodyPostMinpropertiesValidationRequestBody +from unit_test_api.apis.paths.response_body_post_minproperties_validation_response_body_for_content_types import ResponseBodyPostMinpropertiesValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_by_int_request_body import RequestBodyPostByIntRequestBody +from unit_test_api.apis.paths.response_body_post_by_int_response_body_for_content_types import ResponseBodyPostByIntResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_by_number_request_body import RequestBodyPostByNumberRequestBody +from unit_test_api.apis.paths.response_body_post_by_number_response_body_for_content_types import ResponseBodyPostByNumberResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_by_small_number_request_body import RequestBodyPostBySmallNumberRequestBody +from unit_test_api.apis.paths.response_body_post_by_small_number_response_body_for_content_types import ResponseBodyPostBySmallNumberResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body import RequestBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody +from unit_test_api.apis.paths.response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types import ResponseBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_not_request_body import RequestBodyPostNotRequestBody +from unit_test_api.apis.paths.response_body_post_not_response_body_for_content_types import ResponseBodyPostNotResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_not_more_complex_schema_request_body import RequestBodyPostNotMoreComplexSchemaRequestBody +from unit_test_api.apis.paths.response_body_post_not_more_complex_schema_response_body_for_content_types import ResponseBodyPostNotMoreComplexSchemaResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_forbidden_property_request_body import RequestBodyPostForbiddenPropertyRequestBody +from unit_test_api.apis.paths.response_body_post_forbidden_property_response_body_for_content_types import ResponseBodyPostForbiddenPropertyResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_oneof_request_body import RequestBodyPostOneofRequestBody +from unit_test_api.apis.paths.response_body_post_oneof_response_body_for_content_types import ResponseBodyPostOneofResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_oneof_with_base_schema_request_body import RequestBodyPostOneofWithBaseSchemaRequestBody +from unit_test_api.apis.paths.response_body_post_oneof_with_base_schema_response_body_for_content_types import ResponseBodyPostOneofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_oneof_complex_types_request_body import RequestBodyPostOneofComplexTypesRequestBody +from unit_test_api.apis.paths.response_body_post_oneof_complex_types_response_body_for_content_types import ResponseBodyPostOneofComplexTypesResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_oneof_with_empty_schema_request_body import RequestBodyPostOneofWithEmptySchemaRequestBody +from unit_test_api.apis.paths.response_body_post_oneof_with_empty_schema_response_body_for_content_types import ResponseBodyPostOneofWithEmptySchemaResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_oneof_with_required_request_body import RequestBodyPostOneofWithRequiredRequestBody +from unit_test_api.apis.paths.response_body_post_oneof_with_required_response_body_for_content_types import ResponseBodyPostOneofWithRequiredResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_nested_oneof_to_check_validation_semantics_request_body import RequestBodyPostNestedOneofToCheckValidationSemanticsRequestBody +from unit_test_api.apis.paths.response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types import ResponseBodyPostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_pattern_validation_request_body import RequestBodyPostPatternValidationRequestBody +from unit_test_api.apis.paths.response_body_post_pattern_validation_response_body_for_content_types import ResponseBodyPostPatternValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_pattern_is_not_anchored_request_body import RequestBodyPostPatternIsNotAnchoredRequestBody +from unit_test_api.apis.paths.response_body_post_pattern_is_not_anchored_response_body_for_content_types import ResponseBodyPostPatternIsNotAnchoredResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_object_properties_validation_request_body import RequestBodyPostObjectPropertiesValidationRequestBody +from unit_test_api.apis.paths.response_body_post_object_properties_validation_response_body_for_content_types import ResponseBodyPostObjectPropertiesValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_properties_with_escaped_characters_request_body import RequestBodyPostPropertiesWithEscapedCharactersRequestBody +from unit_test_api.apis.paths.response_body_post_properties_with_escaped_characters_response_body_for_content_types import ResponseBodyPostPropertiesWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_property_named_ref_that_is_not_a_reference_request_body import RequestBodyPostPropertyNamedRefThatIsNotAReferenceRequestBody +from unit_test_api.apis.paths.response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types import ResponseBodyPostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_ref_in_additionalproperties_request_body import RequestBodyPostRefInAdditionalpropertiesRequestBody +from unit_test_api.apis.paths.response_body_post_ref_in_additionalproperties_response_body_for_content_types import ResponseBodyPostRefInAdditionalpropertiesResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_ref_in_items_request_body import RequestBodyPostRefInItemsRequestBody +from unit_test_api.apis.paths.response_body_post_ref_in_items_response_body_for_content_types import ResponseBodyPostRefInItemsResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_ref_in_property_request_body import RequestBodyPostRefInPropertyRequestBody +from unit_test_api.apis.paths.response_body_post_ref_in_property_response_body_for_content_types import ResponseBodyPostRefInPropertyResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_ref_in_allof_request_body import RequestBodyPostRefInAllofRequestBody +from unit_test_api.apis.paths.response_body_post_ref_in_allof_response_body_for_content_types import ResponseBodyPostRefInAllofResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_ref_in_oneof_request_body import RequestBodyPostRefInOneofRequestBody +from unit_test_api.apis.paths.response_body_post_ref_in_oneof_response_body_for_content_types import ResponseBodyPostRefInOneofResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_ref_in_anyof_request_body import RequestBodyPostRefInAnyofRequestBody +from unit_test_api.apis.paths.response_body_post_ref_in_anyof_response_body_for_content_types import ResponseBodyPostRefInAnyofResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_ref_in_not_request_body import RequestBodyPostRefInNotRequestBody +from unit_test_api.apis.paths.response_body_post_ref_in_not_response_body_for_content_types import ResponseBodyPostRefInNotResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_required_validation_request_body import RequestBodyPostRequiredValidationRequestBody +from unit_test_api.apis.paths.response_body_post_required_validation_response_body_for_content_types import ResponseBodyPostRequiredValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_required_default_validation_request_body import RequestBodyPostRequiredDefaultValidationRequestBody +from unit_test_api.apis.paths.response_body_post_required_default_validation_response_body_for_content_types import ResponseBodyPostRequiredDefaultValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_required_with_empty_array_request_body import RequestBodyPostRequiredWithEmptyArrayRequestBody +from unit_test_api.apis.paths.response_body_post_required_with_empty_array_response_body_for_content_types import ResponseBodyPostRequiredWithEmptyArrayResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_required_with_escaped_characters_request_body import RequestBodyPostRequiredWithEscapedCharactersRequestBody +from unit_test_api.apis.paths.response_body_post_required_with_escaped_characters_response_body_for_content_types import ResponseBodyPostRequiredWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_integer_type_matches_integers_request_body import RequestBodyPostIntegerTypeMatchesIntegersRequestBody +from unit_test_api.apis.paths.response_body_post_integer_type_matches_integers_response_body_for_content_types import ResponseBodyPostIntegerTypeMatchesIntegersResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_number_type_matches_numbers_request_body import RequestBodyPostNumberTypeMatchesNumbersRequestBody +from unit_test_api.apis.paths.response_body_post_number_type_matches_numbers_response_body_for_content_types import ResponseBodyPostNumberTypeMatchesNumbersResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_string_type_matches_strings_request_body import RequestBodyPostStringTypeMatchesStringsRequestBody +from unit_test_api.apis.paths.response_body_post_string_type_matches_strings_response_body_for_content_types import ResponseBodyPostStringTypeMatchesStringsResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_object_type_matches_objects_request_body import RequestBodyPostObjectTypeMatchesObjectsRequestBody +from unit_test_api.apis.paths.response_body_post_object_type_matches_objects_response_body_for_content_types import ResponseBodyPostObjectTypeMatchesObjectsResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_boolean_type_matches_booleans_request_body import RequestBodyPostBooleanTypeMatchesBooleansRequestBody +from unit_test_api.apis.paths.response_body_post_boolean_type_matches_booleans_response_body_for_content_types import ResponseBodyPostBooleanTypeMatchesBooleansResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_null_type_matches_only_the_null_object_request_body import RequestBodyPostNullTypeMatchesOnlyTheNullObjectRequestBody +from unit_test_api.apis.paths.response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types import ResponseBodyPostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_array_type_matches_arrays_request_body import RequestBodyPostArrayTypeMatchesArraysRequestBody +from unit_test_api.apis.paths.response_body_post_array_type_matches_arrays_response_body_for_content_types import ResponseBodyPostArrayTypeMatchesArraysResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_uniqueitems_validation_request_body import RequestBodyPostUniqueitemsValidationRequestBody +from unit_test_api.apis.paths.response_body_post_uniqueitems_validation_response_body_for_content_types import ResponseBodyPostUniqueitemsValidationResponseBodyForContentTypes +from unit_test_api.apis.paths.request_body_post_uniqueitems_false_validation_request_body import RequestBodyPostUniqueitemsFalseValidationRequestBody +from unit_test_api.apis.paths.response_body_post_uniqueitems_false_validation_response_body_for_content_types import ResponseBodyPostUniqueitemsFalseValidationResponseBodyForContentTypes + +PathToApi = typing_extensions.TypedDict( + 'PathToApi', + { + PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_ALLOWS_ASCHEMA_WHICH_SHOULD_VALIDATE_REQUEST_BODY: RequestBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody, + PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_ALLOWS_ASCHEMA_WHICH_SHOULD_VALIDATE_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_CAN_EXIST_BY_ITSELF_REQUEST_BODY: RequestBodyPostAdditionalpropertiesCanExistByItselfRequestBody, + PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_CAN_EXIST_BY_ITSELF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_ARE_ALLOWED_BY_DEFAULT_REQUEST_BODY: RequestBodyPostAdditionalpropertiesAreAllowedByDefaultRequestBody, + PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_ARE_ALLOWED_BY_DEFAULT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_SHOULD_NOT_LOOK_IN_APPLICATORS_REQUEST_BODY: RequestBodyPostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody, + PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_SHOULD_NOT_LOOK_IN_APPLICATORS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_REQUEST_BODY: RequestBodyPostAllofRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_BASE_SCHEMA_REQUEST_BODY: RequestBodyPostAllofWithBaseSchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithBaseSchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_SIMPLE_TYPES_REQUEST_BODY: RequestBodyPostAllofSimpleTypesRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_SIMPLE_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofSimpleTypesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_ONE_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostAllofWithOneEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_ONE_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithOneEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_TWO_EMPTY_SCHEMAS_REQUEST_BODY: RequestBodyPostAllofWithTwoEmptySchemasRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_TWO_EMPTY_SCHEMAS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithTwoEmptySchemasResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_THE_FIRST_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostAllofWithTheFirstEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_THE_FIRST_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_THE_LAST_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostAllofWithTheLastEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_THE_LAST_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithTheLastEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NESTED_ALLOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY: RequestBodyPostNestedAllofToCheckValidationSemanticsRequestBody, + PathValues.RESPONSE_BODY_POST_NESTED_ALLOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_COMBINED_WITH_ANYOF_ONEOF_REQUEST_BODY: RequestBodyPostAllofCombinedWithAnyofOneofRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_COMBINED_WITH_ANYOF_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofCombinedWithAnyofOneofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ANYOF_REQUEST_BODY: RequestBodyPostAnyofRequestBody, + PathValues.RESPONSE_BODY_POST_ANYOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAnyofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ANYOF_WITH_BASE_SCHEMA_REQUEST_BODY: RequestBodyPostAnyofWithBaseSchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ANYOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAnyofWithBaseSchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ANYOF_COMPLEX_TYPES_REQUEST_BODY: RequestBodyPostAnyofComplexTypesRequestBody, + PathValues.RESPONSE_BODY_POST_ANYOF_COMPLEX_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAnyofComplexTypesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ANYOF_WITH_ONE_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostAnyofWithOneEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ANYOF_WITH_ONE_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAnyofWithOneEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NESTED_ANYOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY: RequestBodyPostNestedAnyofToCheckValidationSemanticsRequestBody, + PathValues.RESPONSE_BODY_POST_NESTED_ANYOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_INVALID_STRING_VALUE_FOR_DEFAULT_REQUEST_BODY: RequestBodyPostInvalidStringValueForDefaultRequestBody, + PathValues.RESPONSE_BODY_POST_INVALID_STRING_VALUE_FOR_DEFAULT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostInvalidStringValueForDefaultResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_THE_DEFAULT_KEYWORD_DOES_NOT_DO_ANYTHING_IF_THE_PROPERTY_IS_MISSING_REQUEST_BODY: RequestBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody, + PathValues.RESPONSE_BODY_POST_THE_DEFAULT_KEYWORD_DOES_NOT_DO_ANYTHING_IF_THE_PROPERTY_IS_MISSING_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_SIMPLE_ENUM_VALIDATION_REQUEST_BODY: RequestBodyPostSimpleEnumValidationRequestBody, + PathValues.RESPONSE_BODY_POST_SIMPLE_ENUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostSimpleEnumValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUMS_IN_PROPERTIES_REQUEST_BODY: RequestBodyPostEnumsInPropertiesRequestBody, + PathValues.RESPONSE_BODY_POST_ENUMS_IN_PROPERTIES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumsInPropertiesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH_ESCAPED_CHARACTERS_REQUEST_BODY: RequestBodyPostEnumWithEscapedCharactersRequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWithEscapedCharactersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH_FALSE_DOES_NOT_MATCH0REQUEST_BODY: RequestBodyPostEnumWithFalseDoesNotMatch0RequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH_FALSE_DOES_NOT_MATCH0RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH_TRUE_DOES_NOT_MATCH1REQUEST_BODY: RequestBodyPostEnumWithTrueDoesNotMatch1RequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH_TRUE_DOES_NOT_MATCH1RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH0DOES_NOT_MATCH_FALSE_REQUEST_BODY: RequestBodyPostEnumWith0DoesNotMatchFalseRequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH0DOES_NOT_MATCH_FALSE_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH1DOES_NOT_MATCH_TRUE_REQUEST_BODY: RequestBodyPostEnumWith1DoesNotMatchTrueRequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH1DOES_NOT_MATCH_TRUE_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NUL_CHARACTERS_IN_STRINGS_REQUEST_BODY: RequestBodyPostNulCharactersInStringsRequestBody, + PathValues.RESPONSE_BODY_POST_NUL_CHARACTERS_IN_STRINGS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNulCharactersInStringsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_EMAIL_FORMAT_REQUEST_BODY: RequestBodyPostEmailFormatRequestBody, + PathValues.RESPONSE_BODY_POST_EMAIL_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEmailFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_IPV4FORMAT_REQUEST_BODY: RequestBodyPostIpv4FormatRequestBody, + PathValues.RESPONSE_BODY_POST_IPV4FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostIpv4FormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_IPV6FORMAT_REQUEST_BODY: RequestBodyPostIpv6FormatRequestBody, + PathValues.RESPONSE_BODY_POST_IPV6FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostIpv6FormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_HOSTNAME_FORMAT_REQUEST_BODY: RequestBodyPostHostnameFormatRequestBody, + PathValues.RESPONSE_BODY_POST_HOSTNAME_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostHostnameFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_DATE_TIME_FORMAT_REQUEST_BODY: RequestBodyPostDateTimeFormatRequestBody, + PathValues.RESPONSE_BODY_POST_DATE_TIME_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostDateTimeFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_JSON_POINTER_FORMAT_REQUEST_BODY: RequestBodyPostJsonPointerFormatRequestBody, + PathValues.RESPONSE_BODY_POST_JSON_POINTER_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostJsonPointerFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_URI_FORMAT_REQUEST_BODY: RequestBodyPostUriFormatRequestBody, + PathValues.RESPONSE_BODY_POST_URI_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUriFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_URI_REFERENCE_FORMAT_REQUEST_BODY: RequestBodyPostUriReferenceFormatRequestBody, + PathValues.RESPONSE_BODY_POST_URI_REFERENCE_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUriReferenceFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_URI_TEMPLATE_FORMAT_REQUEST_BODY: RequestBodyPostUriTemplateFormatRequestBody, + PathValues.RESPONSE_BODY_POST_URI_TEMPLATE_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUriTemplateFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NESTED_ITEMS_REQUEST_BODY: RequestBodyPostNestedItemsRequestBody, + PathValues.RESPONSE_BODY_POST_NESTED_ITEMS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNestedItemsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXIMUM_VALIDATION_REQUEST_BODY: RequestBodyPostMaximumValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MAXIMUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaximumValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXIMUM_VALIDATION_WITH_UNSIGNED_INTEGER_REQUEST_BODY: RequestBodyPostMaximumValidationWithUnsignedIntegerRequestBody, + PathValues.RESPONSE_BODY_POST_MAXIMUM_VALIDATION_WITH_UNSIGNED_INTEGER_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXITEMS_VALIDATION_REQUEST_BODY: RequestBodyPostMaxitemsValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MAXITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaxitemsValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXLENGTH_VALIDATION_REQUEST_BODY: RequestBodyPostMaxlengthValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MAXLENGTH_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaxlengthValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXPROPERTIES_VALIDATION_REQUEST_BODY: RequestBodyPostMaxpropertiesValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MAXPROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaxpropertiesValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXPROPERTIES0MEANS_THE_OBJECT_IS_EMPTY_REQUEST_BODY: RequestBodyPostMaxproperties0MeansTheObjectIsEmptyRequestBody, + PathValues.RESPONSE_BODY_POST_MAXPROPERTIES0MEANS_THE_OBJECT_IS_EMPTY_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINIMUM_VALIDATION_REQUEST_BODY: RequestBodyPostMinimumValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MINIMUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinimumValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINIMUM_VALIDATION_WITH_SIGNED_INTEGER_REQUEST_BODY: RequestBodyPostMinimumValidationWithSignedIntegerRequestBody, + PathValues.RESPONSE_BODY_POST_MINIMUM_VALIDATION_WITH_SIGNED_INTEGER_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinimumValidationWithSignedIntegerResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINITEMS_VALIDATION_REQUEST_BODY: RequestBodyPostMinitemsValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MINITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinitemsValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINLENGTH_VALIDATION_REQUEST_BODY: RequestBodyPostMinlengthValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MINLENGTH_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinlengthValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINPROPERTIES_VALIDATION_REQUEST_BODY: RequestBodyPostMinpropertiesValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MINPROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinpropertiesValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_BY_INT_REQUEST_BODY: RequestBodyPostByIntRequestBody, + PathValues.RESPONSE_BODY_POST_BY_INT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostByIntResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_BY_NUMBER_REQUEST_BODY: RequestBodyPostByNumberRequestBody, + PathValues.RESPONSE_BODY_POST_BY_NUMBER_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostByNumberResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_BY_SMALL_NUMBER_REQUEST_BODY: RequestBodyPostBySmallNumberRequestBody, + PathValues.RESPONSE_BODY_POST_BY_SMALL_NUMBER_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostBySmallNumberResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_INVALID_INSTANCE_SHOULD_NOT_RAISE_ERROR_WHEN_FLOAT_DIVISION_INF_REQUEST_BODY: RequestBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody, + PathValues.RESPONSE_BODY_POST_INVALID_INSTANCE_SHOULD_NOT_RAISE_ERROR_WHEN_FLOAT_DIVISION_INF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NOT_REQUEST_BODY: RequestBodyPostNotRequestBody, + PathValues.RESPONSE_BODY_POST_NOT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNotResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NOT_MORE_COMPLEX_SCHEMA_REQUEST_BODY: RequestBodyPostNotMoreComplexSchemaRequestBody, + PathValues.RESPONSE_BODY_POST_NOT_MORE_COMPLEX_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNotMoreComplexSchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_FORBIDDEN_PROPERTY_REQUEST_BODY: RequestBodyPostForbiddenPropertyRequestBody, + PathValues.RESPONSE_BODY_POST_FORBIDDEN_PROPERTY_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostForbiddenPropertyResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_REQUEST_BODY: RequestBodyPostOneofRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_WITH_BASE_SCHEMA_REQUEST_BODY: RequestBodyPostOneofWithBaseSchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofWithBaseSchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_COMPLEX_TYPES_REQUEST_BODY: RequestBodyPostOneofComplexTypesRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_COMPLEX_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofComplexTypesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_WITH_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostOneofWithEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_WITH_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofWithEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_WITH_REQUIRED_REQUEST_BODY: RequestBodyPostOneofWithRequiredRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_WITH_REQUIRED_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofWithRequiredResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NESTED_ONEOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY: RequestBodyPostNestedOneofToCheckValidationSemanticsRequestBody, + PathValues.RESPONSE_BODY_POST_NESTED_ONEOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_PATTERN_VALIDATION_REQUEST_BODY: RequestBodyPostPatternValidationRequestBody, + PathValues.RESPONSE_BODY_POST_PATTERN_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostPatternValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_PATTERN_IS_NOT_ANCHORED_REQUEST_BODY: RequestBodyPostPatternIsNotAnchoredRequestBody, + PathValues.RESPONSE_BODY_POST_PATTERN_IS_NOT_ANCHORED_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostPatternIsNotAnchoredResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_OBJECT_PROPERTIES_VALIDATION_REQUEST_BODY: RequestBodyPostObjectPropertiesValidationRequestBody, + PathValues.RESPONSE_BODY_POST_OBJECT_PROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostObjectPropertiesValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_PROPERTIES_WITH_ESCAPED_CHARACTERS_REQUEST_BODY: RequestBodyPostPropertiesWithEscapedCharactersRequestBody, + PathValues.RESPONSE_BODY_POST_PROPERTIES_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostPropertiesWithEscapedCharactersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_PROPERTY_NAMED_REF_THAT_IS_NOT_AREFERENCE_REQUEST_BODY: RequestBodyPostPropertyNamedRefThatIsNotAReferenceRequestBody, + PathValues.RESPONSE_BODY_POST_PROPERTY_NAMED_REF_THAT_IS_NOT_AREFERENCE_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ADDITIONALPROPERTIES_REQUEST_BODY: RequestBodyPostRefInAdditionalpropertiesRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ADDITIONALPROPERTIES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInAdditionalpropertiesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ITEMS_REQUEST_BODY: RequestBodyPostRefInItemsRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ITEMS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInItemsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_PROPERTY_REQUEST_BODY: RequestBodyPostRefInPropertyRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_PROPERTY_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInPropertyResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ALLOF_REQUEST_BODY: RequestBodyPostRefInAllofRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ALLOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInAllofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ONEOF_REQUEST_BODY: RequestBodyPostRefInOneofRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInOneofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ANYOF_REQUEST_BODY: RequestBodyPostRefInAnyofRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ANYOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInAnyofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_NOT_REQUEST_BODY: RequestBodyPostRefInNotRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_NOT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInNotResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REQUIRED_VALIDATION_REQUEST_BODY: RequestBodyPostRequiredValidationRequestBody, + PathValues.RESPONSE_BODY_POST_REQUIRED_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRequiredValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REQUIRED_DEFAULT_VALIDATION_REQUEST_BODY: RequestBodyPostRequiredDefaultValidationRequestBody, + PathValues.RESPONSE_BODY_POST_REQUIRED_DEFAULT_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRequiredDefaultValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REQUIRED_WITH_EMPTY_ARRAY_REQUEST_BODY: RequestBodyPostRequiredWithEmptyArrayRequestBody, + PathValues.RESPONSE_BODY_POST_REQUIRED_WITH_EMPTY_ARRAY_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRequiredWithEmptyArrayResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REQUIRED_WITH_ESCAPED_CHARACTERS_REQUEST_BODY: RequestBodyPostRequiredWithEscapedCharactersRequestBody, + PathValues.RESPONSE_BODY_POST_REQUIRED_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRequiredWithEscapedCharactersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_INTEGER_TYPE_MATCHES_INTEGERS_REQUEST_BODY: RequestBodyPostIntegerTypeMatchesIntegersRequestBody, + PathValues.RESPONSE_BODY_POST_INTEGER_TYPE_MATCHES_INTEGERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostIntegerTypeMatchesIntegersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NUMBER_TYPE_MATCHES_NUMBERS_REQUEST_BODY: RequestBodyPostNumberTypeMatchesNumbersRequestBody, + PathValues.RESPONSE_BODY_POST_NUMBER_TYPE_MATCHES_NUMBERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNumberTypeMatchesNumbersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_STRING_TYPE_MATCHES_STRINGS_REQUEST_BODY: RequestBodyPostStringTypeMatchesStringsRequestBody, + PathValues.RESPONSE_BODY_POST_STRING_TYPE_MATCHES_STRINGS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostStringTypeMatchesStringsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_OBJECT_TYPE_MATCHES_OBJECTS_REQUEST_BODY: RequestBodyPostObjectTypeMatchesObjectsRequestBody, + PathValues.RESPONSE_BODY_POST_OBJECT_TYPE_MATCHES_OBJECTS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostObjectTypeMatchesObjectsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_BOOLEAN_TYPE_MATCHES_BOOLEANS_REQUEST_BODY: RequestBodyPostBooleanTypeMatchesBooleansRequestBody, + PathValues.RESPONSE_BODY_POST_BOOLEAN_TYPE_MATCHES_BOOLEANS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostBooleanTypeMatchesBooleansResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NULL_TYPE_MATCHES_ONLY_THE_NULL_OBJECT_REQUEST_BODY: RequestBodyPostNullTypeMatchesOnlyTheNullObjectRequestBody, + PathValues.RESPONSE_BODY_POST_NULL_TYPE_MATCHES_ONLY_THE_NULL_OBJECT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ARRAY_TYPE_MATCHES_ARRAYS_REQUEST_BODY: RequestBodyPostArrayTypeMatchesArraysRequestBody, + PathValues.RESPONSE_BODY_POST_ARRAY_TYPE_MATCHES_ARRAYS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostArrayTypeMatchesArraysResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_UNIQUEITEMS_VALIDATION_REQUEST_BODY: RequestBodyPostUniqueitemsValidationRequestBody, + PathValues.RESPONSE_BODY_POST_UNIQUEITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUniqueitemsValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_UNIQUEITEMS_FALSE_VALIDATION_REQUEST_BODY: RequestBodyPostUniqueitemsFalseValidationRequestBody, + PathValues.RESPONSE_BODY_POST_UNIQUEITEMS_FALSE_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUniqueitemsFalseValidationResponseBodyForContentTypes, + } +) + +path_to_api = PathToApi( + { + PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_ALLOWS_ASCHEMA_WHICH_SHOULD_VALIDATE_REQUEST_BODY: RequestBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody, + PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_ALLOWS_ASCHEMA_WHICH_SHOULD_VALIDATE_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_CAN_EXIST_BY_ITSELF_REQUEST_BODY: RequestBodyPostAdditionalpropertiesCanExistByItselfRequestBody, + PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_CAN_EXIST_BY_ITSELF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_ARE_ALLOWED_BY_DEFAULT_REQUEST_BODY: RequestBodyPostAdditionalpropertiesAreAllowedByDefaultRequestBody, + PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_ARE_ALLOWED_BY_DEFAULT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_SHOULD_NOT_LOOK_IN_APPLICATORS_REQUEST_BODY: RequestBodyPostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody, + PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_SHOULD_NOT_LOOK_IN_APPLICATORS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_REQUEST_BODY: RequestBodyPostAllofRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_BASE_SCHEMA_REQUEST_BODY: RequestBodyPostAllofWithBaseSchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithBaseSchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_SIMPLE_TYPES_REQUEST_BODY: RequestBodyPostAllofSimpleTypesRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_SIMPLE_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofSimpleTypesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_ONE_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostAllofWithOneEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_ONE_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithOneEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_TWO_EMPTY_SCHEMAS_REQUEST_BODY: RequestBodyPostAllofWithTwoEmptySchemasRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_TWO_EMPTY_SCHEMAS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithTwoEmptySchemasResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_THE_FIRST_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostAllofWithTheFirstEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_THE_FIRST_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_WITH_THE_LAST_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostAllofWithTheLastEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_WITH_THE_LAST_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofWithTheLastEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NESTED_ALLOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY: RequestBodyPostNestedAllofToCheckValidationSemanticsRequestBody, + PathValues.RESPONSE_BODY_POST_NESTED_ALLOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ALLOF_COMBINED_WITH_ANYOF_ONEOF_REQUEST_BODY: RequestBodyPostAllofCombinedWithAnyofOneofRequestBody, + PathValues.RESPONSE_BODY_POST_ALLOF_COMBINED_WITH_ANYOF_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAllofCombinedWithAnyofOneofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ANYOF_REQUEST_BODY: RequestBodyPostAnyofRequestBody, + PathValues.RESPONSE_BODY_POST_ANYOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAnyofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ANYOF_WITH_BASE_SCHEMA_REQUEST_BODY: RequestBodyPostAnyofWithBaseSchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ANYOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAnyofWithBaseSchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ANYOF_COMPLEX_TYPES_REQUEST_BODY: RequestBodyPostAnyofComplexTypesRequestBody, + PathValues.RESPONSE_BODY_POST_ANYOF_COMPLEX_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAnyofComplexTypesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ANYOF_WITH_ONE_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostAnyofWithOneEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ANYOF_WITH_ONE_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostAnyofWithOneEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NESTED_ANYOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY: RequestBodyPostNestedAnyofToCheckValidationSemanticsRequestBody, + PathValues.RESPONSE_BODY_POST_NESTED_ANYOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_INVALID_STRING_VALUE_FOR_DEFAULT_REQUEST_BODY: RequestBodyPostInvalidStringValueForDefaultRequestBody, + PathValues.RESPONSE_BODY_POST_INVALID_STRING_VALUE_FOR_DEFAULT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostInvalidStringValueForDefaultResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_THE_DEFAULT_KEYWORD_DOES_NOT_DO_ANYTHING_IF_THE_PROPERTY_IS_MISSING_REQUEST_BODY: RequestBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody, + PathValues.RESPONSE_BODY_POST_THE_DEFAULT_KEYWORD_DOES_NOT_DO_ANYTHING_IF_THE_PROPERTY_IS_MISSING_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_SIMPLE_ENUM_VALIDATION_REQUEST_BODY: RequestBodyPostSimpleEnumValidationRequestBody, + PathValues.RESPONSE_BODY_POST_SIMPLE_ENUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostSimpleEnumValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUMS_IN_PROPERTIES_REQUEST_BODY: RequestBodyPostEnumsInPropertiesRequestBody, + PathValues.RESPONSE_BODY_POST_ENUMS_IN_PROPERTIES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumsInPropertiesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH_ESCAPED_CHARACTERS_REQUEST_BODY: RequestBodyPostEnumWithEscapedCharactersRequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWithEscapedCharactersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH_FALSE_DOES_NOT_MATCH0REQUEST_BODY: RequestBodyPostEnumWithFalseDoesNotMatch0RequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH_FALSE_DOES_NOT_MATCH0RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH_TRUE_DOES_NOT_MATCH1REQUEST_BODY: RequestBodyPostEnumWithTrueDoesNotMatch1RequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH_TRUE_DOES_NOT_MATCH1RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH0DOES_NOT_MATCH_FALSE_REQUEST_BODY: RequestBodyPostEnumWith0DoesNotMatchFalseRequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH0DOES_NOT_MATCH_FALSE_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ENUM_WITH1DOES_NOT_MATCH_TRUE_REQUEST_BODY: RequestBodyPostEnumWith1DoesNotMatchTrueRequestBody, + PathValues.RESPONSE_BODY_POST_ENUM_WITH1DOES_NOT_MATCH_TRUE_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NUL_CHARACTERS_IN_STRINGS_REQUEST_BODY: RequestBodyPostNulCharactersInStringsRequestBody, + PathValues.RESPONSE_BODY_POST_NUL_CHARACTERS_IN_STRINGS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNulCharactersInStringsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_EMAIL_FORMAT_REQUEST_BODY: RequestBodyPostEmailFormatRequestBody, + PathValues.RESPONSE_BODY_POST_EMAIL_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostEmailFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_IPV4FORMAT_REQUEST_BODY: RequestBodyPostIpv4FormatRequestBody, + PathValues.RESPONSE_BODY_POST_IPV4FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostIpv4FormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_IPV6FORMAT_REQUEST_BODY: RequestBodyPostIpv6FormatRequestBody, + PathValues.RESPONSE_BODY_POST_IPV6FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostIpv6FormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_HOSTNAME_FORMAT_REQUEST_BODY: RequestBodyPostHostnameFormatRequestBody, + PathValues.RESPONSE_BODY_POST_HOSTNAME_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostHostnameFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_DATE_TIME_FORMAT_REQUEST_BODY: RequestBodyPostDateTimeFormatRequestBody, + PathValues.RESPONSE_BODY_POST_DATE_TIME_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostDateTimeFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_JSON_POINTER_FORMAT_REQUEST_BODY: RequestBodyPostJsonPointerFormatRequestBody, + PathValues.RESPONSE_BODY_POST_JSON_POINTER_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostJsonPointerFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_URI_FORMAT_REQUEST_BODY: RequestBodyPostUriFormatRequestBody, + PathValues.RESPONSE_BODY_POST_URI_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUriFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_URI_REFERENCE_FORMAT_REQUEST_BODY: RequestBodyPostUriReferenceFormatRequestBody, + PathValues.RESPONSE_BODY_POST_URI_REFERENCE_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUriReferenceFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_URI_TEMPLATE_FORMAT_REQUEST_BODY: RequestBodyPostUriTemplateFormatRequestBody, + PathValues.RESPONSE_BODY_POST_URI_TEMPLATE_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUriTemplateFormatResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NESTED_ITEMS_REQUEST_BODY: RequestBodyPostNestedItemsRequestBody, + PathValues.RESPONSE_BODY_POST_NESTED_ITEMS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNestedItemsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXIMUM_VALIDATION_REQUEST_BODY: RequestBodyPostMaximumValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MAXIMUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaximumValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXIMUM_VALIDATION_WITH_UNSIGNED_INTEGER_REQUEST_BODY: RequestBodyPostMaximumValidationWithUnsignedIntegerRequestBody, + PathValues.RESPONSE_BODY_POST_MAXIMUM_VALIDATION_WITH_UNSIGNED_INTEGER_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXITEMS_VALIDATION_REQUEST_BODY: RequestBodyPostMaxitemsValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MAXITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaxitemsValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXLENGTH_VALIDATION_REQUEST_BODY: RequestBodyPostMaxlengthValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MAXLENGTH_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaxlengthValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXPROPERTIES_VALIDATION_REQUEST_BODY: RequestBodyPostMaxpropertiesValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MAXPROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaxpropertiesValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MAXPROPERTIES0MEANS_THE_OBJECT_IS_EMPTY_REQUEST_BODY: RequestBodyPostMaxproperties0MeansTheObjectIsEmptyRequestBody, + PathValues.RESPONSE_BODY_POST_MAXPROPERTIES0MEANS_THE_OBJECT_IS_EMPTY_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINIMUM_VALIDATION_REQUEST_BODY: RequestBodyPostMinimumValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MINIMUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinimumValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINIMUM_VALIDATION_WITH_SIGNED_INTEGER_REQUEST_BODY: RequestBodyPostMinimumValidationWithSignedIntegerRequestBody, + PathValues.RESPONSE_BODY_POST_MINIMUM_VALIDATION_WITH_SIGNED_INTEGER_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinimumValidationWithSignedIntegerResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINITEMS_VALIDATION_REQUEST_BODY: RequestBodyPostMinitemsValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MINITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinitemsValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINLENGTH_VALIDATION_REQUEST_BODY: RequestBodyPostMinlengthValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MINLENGTH_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinlengthValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_MINPROPERTIES_VALIDATION_REQUEST_BODY: RequestBodyPostMinpropertiesValidationRequestBody, + PathValues.RESPONSE_BODY_POST_MINPROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostMinpropertiesValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_BY_INT_REQUEST_BODY: RequestBodyPostByIntRequestBody, + PathValues.RESPONSE_BODY_POST_BY_INT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostByIntResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_BY_NUMBER_REQUEST_BODY: RequestBodyPostByNumberRequestBody, + PathValues.RESPONSE_BODY_POST_BY_NUMBER_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostByNumberResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_BY_SMALL_NUMBER_REQUEST_BODY: RequestBodyPostBySmallNumberRequestBody, + PathValues.RESPONSE_BODY_POST_BY_SMALL_NUMBER_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostBySmallNumberResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_INVALID_INSTANCE_SHOULD_NOT_RAISE_ERROR_WHEN_FLOAT_DIVISION_INF_REQUEST_BODY: RequestBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody, + PathValues.RESPONSE_BODY_POST_INVALID_INSTANCE_SHOULD_NOT_RAISE_ERROR_WHEN_FLOAT_DIVISION_INF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NOT_REQUEST_BODY: RequestBodyPostNotRequestBody, + PathValues.RESPONSE_BODY_POST_NOT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNotResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NOT_MORE_COMPLEX_SCHEMA_REQUEST_BODY: RequestBodyPostNotMoreComplexSchemaRequestBody, + PathValues.RESPONSE_BODY_POST_NOT_MORE_COMPLEX_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNotMoreComplexSchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_FORBIDDEN_PROPERTY_REQUEST_BODY: RequestBodyPostForbiddenPropertyRequestBody, + PathValues.RESPONSE_BODY_POST_FORBIDDEN_PROPERTY_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostForbiddenPropertyResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_REQUEST_BODY: RequestBodyPostOneofRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_WITH_BASE_SCHEMA_REQUEST_BODY: RequestBodyPostOneofWithBaseSchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofWithBaseSchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_COMPLEX_TYPES_REQUEST_BODY: RequestBodyPostOneofComplexTypesRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_COMPLEX_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofComplexTypesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_WITH_EMPTY_SCHEMA_REQUEST_BODY: RequestBodyPostOneofWithEmptySchemaRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_WITH_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofWithEmptySchemaResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ONEOF_WITH_REQUIRED_REQUEST_BODY: RequestBodyPostOneofWithRequiredRequestBody, + PathValues.RESPONSE_BODY_POST_ONEOF_WITH_REQUIRED_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostOneofWithRequiredResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NESTED_ONEOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY: RequestBodyPostNestedOneofToCheckValidationSemanticsRequestBody, + PathValues.RESPONSE_BODY_POST_NESTED_ONEOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_PATTERN_VALIDATION_REQUEST_BODY: RequestBodyPostPatternValidationRequestBody, + PathValues.RESPONSE_BODY_POST_PATTERN_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostPatternValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_PATTERN_IS_NOT_ANCHORED_REQUEST_BODY: RequestBodyPostPatternIsNotAnchoredRequestBody, + PathValues.RESPONSE_BODY_POST_PATTERN_IS_NOT_ANCHORED_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostPatternIsNotAnchoredResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_OBJECT_PROPERTIES_VALIDATION_REQUEST_BODY: RequestBodyPostObjectPropertiesValidationRequestBody, + PathValues.RESPONSE_BODY_POST_OBJECT_PROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostObjectPropertiesValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_PROPERTIES_WITH_ESCAPED_CHARACTERS_REQUEST_BODY: RequestBodyPostPropertiesWithEscapedCharactersRequestBody, + PathValues.RESPONSE_BODY_POST_PROPERTIES_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostPropertiesWithEscapedCharactersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_PROPERTY_NAMED_REF_THAT_IS_NOT_AREFERENCE_REQUEST_BODY: RequestBodyPostPropertyNamedRefThatIsNotAReferenceRequestBody, + PathValues.RESPONSE_BODY_POST_PROPERTY_NAMED_REF_THAT_IS_NOT_AREFERENCE_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ADDITIONALPROPERTIES_REQUEST_BODY: RequestBodyPostRefInAdditionalpropertiesRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ADDITIONALPROPERTIES_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInAdditionalpropertiesResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ITEMS_REQUEST_BODY: RequestBodyPostRefInItemsRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ITEMS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInItemsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_PROPERTY_REQUEST_BODY: RequestBodyPostRefInPropertyRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_PROPERTY_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInPropertyResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ALLOF_REQUEST_BODY: RequestBodyPostRefInAllofRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ALLOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInAllofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ONEOF_REQUEST_BODY: RequestBodyPostRefInOneofRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInOneofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_ANYOF_REQUEST_BODY: RequestBodyPostRefInAnyofRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_ANYOF_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInAnyofResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REF_IN_NOT_REQUEST_BODY: RequestBodyPostRefInNotRequestBody, + PathValues.RESPONSE_BODY_POST_REF_IN_NOT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRefInNotResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REQUIRED_VALIDATION_REQUEST_BODY: RequestBodyPostRequiredValidationRequestBody, + PathValues.RESPONSE_BODY_POST_REQUIRED_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRequiredValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REQUIRED_DEFAULT_VALIDATION_REQUEST_BODY: RequestBodyPostRequiredDefaultValidationRequestBody, + PathValues.RESPONSE_BODY_POST_REQUIRED_DEFAULT_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRequiredDefaultValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REQUIRED_WITH_EMPTY_ARRAY_REQUEST_BODY: RequestBodyPostRequiredWithEmptyArrayRequestBody, + PathValues.RESPONSE_BODY_POST_REQUIRED_WITH_EMPTY_ARRAY_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRequiredWithEmptyArrayResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_REQUIRED_WITH_ESCAPED_CHARACTERS_REQUEST_BODY: RequestBodyPostRequiredWithEscapedCharactersRequestBody, + PathValues.RESPONSE_BODY_POST_REQUIRED_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostRequiredWithEscapedCharactersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_INTEGER_TYPE_MATCHES_INTEGERS_REQUEST_BODY: RequestBodyPostIntegerTypeMatchesIntegersRequestBody, + PathValues.RESPONSE_BODY_POST_INTEGER_TYPE_MATCHES_INTEGERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostIntegerTypeMatchesIntegersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NUMBER_TYPE_MATCHES_NUMBERS_REQUEST_BODY: RequestBodyPostNumberTypeMatchesNumbersRequestBody, + PathValues.RESPONSE_BODY_POST_NUMBER_TYPE_MATCHES_NUMBERS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNumberTypeMatchesNumbersResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_STRING_TYPE_MATCHES_STRINGS_REQUEST_BODY: RequestBodyPostStringTypeMatchesStringsRequestBody, + PathValues.RESPONSE_BODY_POST_STRING_TYPE_MATCHES_STRINGS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostStringTypeMatchesStringsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_OBJECT_TYPE_MATCHES_OBJECTS_REQUEST_BODY: RequestBodyPostObjectTypeMatchesObjectsRequestBody, + PathValues.RESPONSE_BODY_POST_OBJECT_TYPE_MATCHES_OBJECTS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostObjectTypeMatchesObjectsResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_BOOLEAN_TYPE_MATCHES_BOOLEANS_REQUEST_BODY: RequestBodyPostBooleanTypeMatchesBooleansRequestBody, + PathValues.RESPONSE_BODY_POST_BOOLEAN_TYPE_MATCHES_BOOLEANS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostBooleanTypeMatchesBooleansResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_NULL_TYPE_MATCHES_ONLY_THE_NULL_OBJECT_REQUEST_BODY: RequestBodyPostNullTypeMatchesOnlyTheNullObjectRequestBody, + PathValues.RESPONSE_BODY_POST_NULL_TYPE_MATCHES_ONLY_THE_NULL_OBJECT_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_ARRAY_TYPE_MATCHES_ARRAYS_REQUEST_BODY: RequestBodyPostArrayTypeMatchesArraysRequestBody, + PathValues.RESPONSE_BODY_POST_ARRAY_TYPE_MATCHES_ARRAYS_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostArrayTypeMatchesArraysResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_UNIQUEITEMS_VALIDATION_REQUEST_BODY: RequestBodyPostUniqueitemsValidationRequestBody, + PathValues.RESPONSE_BODY_POST_UNIQUEITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUniqueitemsValidationResponseBodyForContentTypes, + PathValues.REQUEST_BODY_POST_UNIQUEITEMS_FALSE_VALIDATION_REQUEST_BODY: RequestBodyPostUniqueitemsFalseValidationRequestBody, + PathValues.RESPONSE_BODY_POST_UNIQUEITEMS_FALSE_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES: ResponseBodyPostUniqueitemsFalseValidationResponseBodyForContentTypes, + } +) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/__init__.py new file mode 100644 index 0000000000..53ee69932f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/__init__.py @@ -0,0 +1,3 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.apis.path_to_api import path_to_api diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body.py new file mode 100644 index 0000000000..b192522f2a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body.post import ApiForpost + + +class RequestBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body.py new file mode 100644 index 0000000000..451e8f9002 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_additionalproperties_are_allowed_by_default_request_body.post import ApiForpost + + +class RequestBodyPostAdditionalpropertiesAreAllowedByDefaultRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body.py new file mode 100644 index 0000000000..c52850fbd6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_additionalproperties_can_exist_by_itself_request_body.post import ApiForpost + + +class RequestBodyPostAdditionalpropertiesCanExistByItselfRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body.py new file mode 100644 index 0000000000..ce1a4fdad6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_additionalproperties_should_not_look_in_applicators_request_body.post import ApiForpost + + +class RequestBodyPostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_combined_with_anyof_oneof_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_combined_with_anyof_oneof_request_body.py new file mode 100644 index 0000000000..6793b00407 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_combined_with_anyof_oneof_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_allof_combined_with_anyof_oneof_request_body.post import ApiForpost + + +class RequestBodyPostAllofCombinedWithAnyofOneofRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_request_body.py new file mode 100644 index 0000000000..37c84da359 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_allof_request_body.post import ApiForpost + + +class RequestBodyPostAllofRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_simple_types_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_simple_types_request_body.py new file mode 100644 index 0000000000..9fc93cccdb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_simple_types_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_allof_simple_types_request_body.post import ApiForpost + + +class RequestBodyPostAllofSimpleTypesRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_base_schema_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_base_schema_request_body.py new file mode 100644 index 0000000000..86134ff521 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_base_schema_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_allof_with_base_schema_request_body.post import ApiForpost + + +class RequestBodyPostAllofWithBaseSchemaRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_one_empty_schema_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_one_empty_schema_request_body.py new file mode 100644 index 0000000000..2a53c4f4e6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_one_empty_schema_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_allof_with_one_empty_schema_request_body.post import ApiForpost + + +class RequestBodyPostAllofWithOneEmptySchemaRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_the_first_empty_schema_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_the_first_empty_schema_request_body.py new file mode 100644 index 0000000000..d7e39a3366 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_the_first_empty_schema_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_allof_with_the_first_empty_schema_request_body.post import ApiForpost + + +class RequestBodyPostAllofWithTheFirstEmptySchemaRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_the_last_empty_schema_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_the_last_empty_schema_request_body.py new file mode 100644 index 0000000000..e89f23b2e6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_the_last_empty_schema_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_allof_with_the_last_empty_schema_request_body.post import ApiForpost + + +class RequestBodyPostAllofWithTheLastEmptySchemaRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_two_empty_schemas_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_two_empty_schemas_request_body.py new file mode 100644 index 0000000000..52d37e5368 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_allof_with_two_empty_schemas_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_allof_with_two_empty_schemas_request_body.post import ApiForpost + + +class RequestBodyPostAllofWithTwoEmptySchemasRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_complex_types_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_complex_types_request_body.py new file mode 100644 index 0000000000..e0451e5440 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_complex_types_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_anyof_complex_types_request_body.post import ApiForpost + + +class RequestBodyPostAnyofComplexTypesRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_request_body.py new file mode 100644 index 0000000000..664362a7a1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_anyof_request_body.post import ApiForpost + + +class RequestBodyPostAnyofRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_with_base_schema_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_with_base_schema_request_body.py new file mode 100644 index 0000000000..7cb12e0242 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_with_base_schema_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_anyof_with_base_schema_request_body.post import ApiForpost + + +class RequestBodyPostAnyofWithBaseSchemaRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_with_one_empty_schema_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_with_one_empty_schema_request_body.py new file mode 100644 index 0000000000..debf0a4001 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_anyof_with_one_empty_schema_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_anyof_with_one_empty_schema_request_body.post import ApiForpost + + +class RequestBodyPostAnyofWithOneEmptySchemaRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_array_type_matches_arrays_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_array_type_matches_arrays_request_body.py new file mode 100644 index 0000000000..07f36e7221 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_array_type_matches_arrays_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_array_type_matches_arrays_request_body.post import ApiForpost + + +class RequestBodyPostArrayTypeMatchesArraysRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_boolean_type_matches_booleans_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_boolean_type_matches_booleans_request_body.py new file mode 100644 index 0000000000..8d84adf946 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_boolean_type_matches_booleans_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_boolean_type_matches_booleans_request_body.post import ApiForpost + + +class RequestBodyPostBooleanTypeMatchesBooleansRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_by_int_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_by_int_request_body.py new file mode 100644 index 0000000000..dd56fe4d76 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_by_int_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_by_int_request_body.post import ApiForpost + + +class RequestBodyPostByIntRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_by_number_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_by_number_request_body.py new file mode 100644 index 0000000000..1c4479a583 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_by_number_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_by_number_request_body.post import ApiForpost + + +class RequestBodyPostByNumberRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_by_small_number_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_by_small_number_request_body.py new file mode 100644 index 0000000000..a02655bdcf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_by_small_number_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_by_small_number_request_body.post import ApiForpost + + +class RequestBodyPostBySmallNumberRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_date_time_format_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_date_time_format_request_body.py new file mode 100644 index 0000000000..7a8bcf9dd3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_date_time_format_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_date_time_format_request_body.post import ApiForpost + + +class RequestBodyPostDateTimeFormatRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_email_format_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_email_format_request_body.py new file mode 100644 index 0000000000..d981e181d7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_email_format_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_email_format_request_body.post import ApiForpost + + +class RequestBodyPostEmailFormatRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with0_does_not_match_false_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with0_does_not_match_false_request_body.py new file mode 100644 index 0000000000..2ad5fc633c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with0_does_not_match_false_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_enum_with0_does_not_match_false_request_body.post import ApiForpost + + +class RequestBodyPostEnumWith0DoesNotMatchFalseRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with1_does_not_match_true_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with1_does_not_match_true_request_body.py new file mode 100644 index 0000000000..e839c2072b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with1_does_not_match_true_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_enum_with1_does_not_match_true_request_body.post import ApiForpost + + +class RequestBodyPostEnumWith1DoesNotMatchTrueRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with_escaped_characters_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with_escaped_characters_request_body.py new file mode 100644 index 0000000000..7f2d1af225 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with_escaped_characters_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_enum_with_escaped_characters_request_body.post import ApiForpost + + +class RequestBodyPostEnumWithEscapedCharactersRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with_false_does_not_match0_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with_false_does_not_match0_request_body.py new file mode 100644 index 0000000000..3a411072ad --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with_false_does_not_match0_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_enum_with_false_does_not_match0_request_body.post import ApiForpost + + +class RequestBodyPostEnumWithFalseDoesNotMatch0RequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with_true_does_not_match1_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with_true_does_not_match1_request_body.py new file mode 100644 index 0000000000..b4de11a45a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enum_with_true_does_not_match1_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_enum_with_true_does_not_match1_request_body.post import ApiForpost + + +class RequestBodyPostEnumWithTrueDoesNotMatch1RequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enums_in_properties_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enums_in_properties_request_body.py new file mode 100644 index 0000000000..2691381350 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_enums_in_properties_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_enums_in_properties_request_body.post import ApiForpost + + +class RequestBodyPostEnumsInPropertiesRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_forbidden_property_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_forbidden_property_request_body.py new file mode 100644 index 0000000000..2d47b6c3b2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_forbidden_property_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_forbidden_property_request_body.post import ApiForpost + + +class RequestBodyPostForbiddenPropertyRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_hostname_format_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_hostname_format_request_body.py new file mode 100644 index 0000000000..7c7f8a231e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_hostname_format_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_hostname_format_request_body.post import ApiForpost + + +class RequestBodyPostHostnameFormatRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_integer_type_matches_integers_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_integer_type_matches_integers_request_body.py new file mode 100644 index 0000000000..77edb2b06b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_integer_type_matches_integers_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_integer_type_matches_integers_request_body.post import ApiForpost + + +class RequestBodyPostIntegerTypeMatchesIntegersRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.py new file mode 100644 index 0000000000..5941f7771d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.post import ApiForpost + + +class RequestBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_invalid_string_value_for_default_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_invalid_string_value_for_default_request_body.py new file mode 100644 index 0000000000..4ba3eccbfc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_invalid_string_value_for_default_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_invalid_string_value_for_default_request_body.post import ApiForpost + + +class RequestBodyPostInvalidStringValueForDefaultRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ipv4_format_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ipv4_format_request_body.py new file mode 100644 index 0000000000..3a08ac42fb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ipv4_format_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_ipv4_format_request_body.post import ApiForpost + + +class RequestBodyPostIpv4FormatRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ipv6_format_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ipv6_format_request_body.py new file mode 100644 index 0000000000..a4c7795912 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ipv6_format_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_ipv6_format_request_body.post import ApiForpost + + +class RequestBodyPostIpv6FormatRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_json_pointer_format_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_json_pointer_format_request_body.py new file mode 100644 index 0000000000..72c1b75f11 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_json_pointer_format_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_json_pointer_format_request_body.post import ApiForpost + + +class RequestBodyPostJsonPointerFormatRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maximum_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maximum_validation_request_body.py new file mode 100644 index 0000000000..be4ee24b7b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maximum_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_maximum_validation_request_body.post import ApiForpost + + +class RequestBodyPostMaximumValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body.py new file mode 100644 index 0000000000..8320d0e690 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_maximum_validation_with_unsigned_integer_request_body.post import ApiForpost + + +class RequestBodyPostMaximumValidationWithUnsignedIntegerRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxitems_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxitems_validation_request_body.py new file mode 100644 index 0000000000..0cd52b5704 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxitems_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_maxitems_validation_request_body.post import ApiForpost + + +class RequestBodyPostMaxitemsValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxlength_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxlength_validation_request_body.py new file mode 100644 index 0000000000..3bbe70bf34 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxlength_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_maxlength_validation_request_body.post import ApiForpost + + +class RequestBodyPostMaxlengthValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body.py new file mode 100644 index 0000000000..98a7f6edf7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_maxproperties0_means_the_object_is_empty_request_body.post import ApiForpost + + +class RequestBodyPostMaxproperties0MeansTheObjectIsEmptyRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxproperties_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxproperties_validation_request_body.py new file mode 100644 index 0000000000..d4e696fd84 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_maxproperties_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_maxproperties_validation_request_body.post import ApiForpost + + +class RequestBodyPostMaxpropertiesValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minimum_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minimum_validation_request_body.py new file mode 100644 index 0000000000..027c18ffde --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minimum_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_minimum_validation_request_body.post import ApiForpost + + +class RequestBodyPostMinimumValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minimum_validation_with_signed_integer_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minimum_validation_with_signed_integer_request_body.py new file mode 100644 index 0000000000..dafbf06e91 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minimum_validation_with_signed_integer_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_minimum_validation_with_signed_integer_request_body.post import ApiForpost + + +class RequestBodyPostMinimumValidationWithSignedIntegerRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minitems_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minitems_validation_request_body.py new file mode 100644 index 0000000000..799cb6d8c9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minitems_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_minitems_validation_request_body.post import ApiForpost + + +class RequestBodyPostMinitemsValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minlength_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minlength_validation_request_body.py new file mode 100644 index 0000000000..5998484905 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minlength_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_minlength_validation_request_body.post import ApiForpost + + +class RequestBodyPostMinlengthValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minproperties_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minproperties_validation_request_body.py new file mode 100644 index 0000000000..2198665c3b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_minproperties_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_minproperties_validation_request_body.post import ApiForpost + + +class RequestBodyPostMinpropertiesValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body.py new file mode 100644 index 0000000000..65e76d896e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_nested_allof_to_check_validation_semantics_request_body.post import ApiForpost + + +class RequestBodyPostNestedAllofToCheckValidationSemanticsRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body.py new file mode 100644 index 0000000000..806340cb35 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_nested_anyof_to_check_validation_semantics_request_body.post import ApiForpost + + +class RequestBodyPostNestedAnyofToCheckValidationSemanticsRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_items_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_items_request_body.py new file mode 100644 index 0000000000..a32286fd14 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_items_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_nested_items_request_body.post import ApiForpost + + +class RequestBodyPostNestedItemsRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body.py new file mode 100644 index 0000000000..e88c0c4cfd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_nested_oneof_to_check_validation_semantics_request_body.post import ApiForpost + + +class RequestBodyPostNestedOneofToCheckValidationSemanticsRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_not_more_complex_schema_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_not_more_complex_schema_request_body.py new file mode 100644 index 0000000000..5b3f9fe969 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_not_more_complex_schema_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_not_more_complex_schema_request_body.post import ApiForpost + + +class RequestBodyPostNotMoreComplexSchemaRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_not_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_not_request_body.py new file mode 100644 index 0000000000..631de4606c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_not_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_not_request_body.post import ApiForpost + + +class RequestBodyPostNotRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nul_characters_in_strings_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nul_characters_in_strings_request_body.py new file mode 100644 index 0000000000..3b58e5d911 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_nul_characters_in_strings_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_nul_characters_in_strings_request_body.post import ApiForpost + + +class RequestBodyPostNulCharactersInStringsRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_null_type_matches_only_the_null_object_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_null_type_matches_only_the_null_object_request_body.py new file mode 100644 index 0000000000..a1b6fef89e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_null_type_matches_only_the_null_object_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_null_type_matches_only_the_null_object_request_body.post import ApiForpost + + +class RequestBodyPostNullTypeMatchesOnlyTheNullObjectRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_number_type_matches_numbers_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_number_type_matches_numbers_request_body.py new file mode 100644 index 0000000000..406a6293d3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_number_type_matches_numbers_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_number_type_matches_numbers_request_body.post import ApiForpost + + +class RequestBodyPostNumberTypeMatchesNumbersRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_object_properties_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_object_properties_validation_request_body.py new file mode 100644 index 0000000000..5d2954070a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_object_properties_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_object_properties_validation_request_body.post import ApiForpost + + +class RequestBodyPostObjectPropertiesValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_object_type_matches_objects_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_object_type_matches_objects_request_body.py new file mode 100644 index 0000000000..44a8c119ba --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_object_type_matches_objects_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_object_type_matches_objects_request_body.post import ApiForpost + + +class RequestBodyPostObjectTypeMatchesObjectsRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_complex_types_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_complex_types_request_body.py new file mode 100644 index 0000000000..a717308f2c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_complex_types_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_oneof_complex_types_request_body.post import ApiForpost + + +class RequestBodyPostOneofComplexTypesRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_request_body.py new file mode 100644 index 0000000000..45d31d7fdf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_oneof_request_body.post import ApiForpost + + +class RequestBodyPostOneofRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_with_base_schema_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_with_base_schema_request_body.py new file mode 100644 index 0000000000..4f599245d0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_with_base_schema_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_oneof_with_base_schema_request_body.post import ApiForpost + + +class RequestBodyPostOneofWithBaseSchemaRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_with_empty_schema_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_with_empty_schema_request_body.py new file mode 100644 index 0000000000..2ec2d18c53 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_with_empty_schema_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_oneof_with_empty_schema_request_body.post import ApiForpost + + +class RequestBodyPostOneofWithEmptySchemaRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_with_required_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_with_required_request_body.py new file mode 100644 index 0000000000..774cf6dc1a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_oneof_with_required_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_oneof_with_required_request_body.post import ApiForpost + + +class RequestBodyPostOneofWithRequiredRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_pattern_is_not_anchored_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_pattern_is_not_anchored_request_body.py new file mode 100644 index 0000000000..06aca1f2b3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_pattern_is_not_anchored_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_pattern_is_not_anchored_request_body.post import ApiForpost + + +class RequestBodyPostPatternIsNotAnchoredRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_pattern_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_pattern_validation_request_body.py new file mode 100644 index 0000000000..5ddc1ec9b7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_pattern_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_pattern_validation_request_body.post import ApiForpost + + +class RequestBodyPostPatternValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_properties_with_escaped_characters_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_properties_with_escaped_characters_request_body.py new file mode 100644 index 0000000000..dd94800146 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_properties_with_escaped_characters_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_properties_with_escaped_characters_request_body.post import ApiForpost + + +class RequestBodyPostPropertiesWithEscapedCharactersRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body.py new file mode 100644 index 0000000000..c211121f9d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_property_named_ref_that_is_not_a_reference_request_body.post import ApiForpost + + +class RequestBodyPostPropertyNamedRefThatIsNotAReferenceRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_additionalproperties_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_additionalproperties_request_body.py new file mode 100644 index 0000000000..b74804c5e7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_additionalproperties_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_ref_in_additionalproperties_request_body.post import ApiForpost + + +class RequestBodyPostRefInAdditionalpropertiesRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_allof_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_allof_request_body.py new file mode 100644 index 0000000000..4720ef7849 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_allof_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_ref_in_allof_request_body.post import ApiForpost + + +class RequestBodyPostRefInAllofRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_anyof_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_anyof_request_body.py new file mode 100644 index 0000000000..c86e528960 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_anyof_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_ref_in_anyof_request_body.post import ApiForpost + + +class RequestBodyPostRefInAnyofRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_items_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_items_request_body.py new file mode 100644 index 0000000000..1552ea32ee --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_items_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_ref_in_items_request_body.post import ApiForpost + + +class RequestBodyPostRefInItemsRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_not_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_not_request_body.py new file mode 100644 index 0000000000..12dbc3510d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_not_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_ref_in_not_request_body.post import ApiForpost + + +class RequestBodyPostRefInNotRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_oneof_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_oneof_request_body.py new file mode 100644 index 0000000000..3e66c6cef4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_oneof_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_ref_in_oneof_request_body.post import ApiForpost + + +class RequestBodyPostRefInOneofRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_property_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_property_request_body.py new file mode 100644 index 0000000000..9950d6d085 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_ref_in_property_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_ref_in_property_request_body.post import ApiForpost + + +class RequestBodyPostRefInPropertyRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_default_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_default_validation_request_body.py new file mode 100644 index 0000000000..f000c3cdc8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_default_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_required_default_validation_request_body.post import ApiForpost + + +class RequestBodyPostRequiredDefaultValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_validation_request_body.py new file mode 100644 index 0000000000..f31a3846f3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_required_validation_request_body.post import ApiForpost + + +class RequestBodyPostRequiredValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_with_empty_array_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_with_empty_array_request_body.py new file mode 100644 index 0000000000..eb7c393317 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_with_empty_array_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_required_with_empty_array_request_body.post import ApiForpost + + +class RequestBodyPostRequiredWithEmptyArrayRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_with_escaped_characters_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_with_escaped_characters_request_body.py new file mode 100644 index 0000000000..2098fa9255 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_required_with_escaped_characters_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_required_with_escaped_characters_request_body.post import ApiForpost + + +class RequestBodyPostRequiredWithEscapedCharactersRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_simple_enum_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_simple_enum_validation_request_body.py new file mode 100644 index 0000000000..867da55645 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_simple_enum_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_simple_enum_validation_request_body.post import ApiForpost + + +class RequestBodyPostSimpleEnumValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_string_type_matches_strings_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_string_type_matches_strings_request_body.py new file mode 100644 index 0000000000..8fecfc63a8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_string_type_matches_strings_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_string_type_matches_strings_request_body.post import ApiForpost + + +class RequestBodyPostStringTypeMatchesStringsRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.py new file mode 100644 index 0000000000..f661679de9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.post import ApiForpost + + +class RequestBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uniqueitems_false_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uniqueitems_false_validation_request_body.py new file mode 100644 index 0000000000..59cd97a909 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uniqueitems_false_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_uniqueitems_false_validation_request_body.post import ApiForpost + + +class RequestBodyPostUniqueitemsFalseValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uniqueitems_validation_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uniqueitems_validation_request_body.py new file mode 100644 index 0000000000..3491c6ceb9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uniqueitems_validation_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_uniqueitems_validation_request_body.post import ApiForpost + + +class RequestBodyPostUniqueitemsValidationRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uri_format_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uri_format_request_body.py new file mode 100644 index 0000000000..efed57abe1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uri_format_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_uri_format_request_body.post import ApiForpost + + +class RequestBodyPostUriFormatRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uri_reference_format_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uri_reference_format_request_body.py new file mode 100644 index 0000000000..42007af52d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uri_reference_format_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_uri_reference_format_request_body.post import ApiForpost + + +class RequestBodyPostUriReferenceFormatRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uri_template_format_request_body.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uri_template_format_request_body.py new file mode 100644 index 0000000000..91da7cc919 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/request_body_post_uri_template_format_request_body.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.request_body_post_uri_template_format_request_body.post import ApiForpost + + +class RequestBodyPostUriTemplateFormatRequestBody( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.py new file mode 100644 index 0000000000..40fb8b563e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types.py new file mode 100644 index 0000000000..76fa69d786 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types.py new file mode 100644 index 0000000000..745ec3b920 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.py new file mode 100644 index 0000000000..84f7d2c57f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types.py new file mode 100644 index 0000000000..48e10e30dd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAllofCombinedWithAnyofOneofResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_response_body_for_content_types.py new file mode 100644 index 0000000000..b33146d83b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_allof_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAllofResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_simple_types_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_simple_types_response_body_for_content_types.py new file mode 100644 index 0000000000..eed8988477 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_simple_types_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_allof_simple_types_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAllofSimpleTypesResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_base_schema_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_base_schema_response_body_for_content_types.py new file mode 100644 index 0000000000..9773d68717 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_base_schema_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_allof_with_base_schema_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAllofWithBaseSchemaResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types.py new file mode 100644 index 0000000000..cfbab79671 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_allof_with_one_empty_schema_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAllofWithOneEmptySchemaResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types.py new file mode 100644 index 0000000000..4ef24243e3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types.py new file mode 100644 index 0000000000..6a072308b9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAllofWithTheLastEmptySchemaResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types.py new file mode 100644 index 0000000000..cb2d392a27 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_allof_with_two_empty_schemas_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAllofWithTwoEmptySchemasResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_complex_types_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_complex_types_response_body_for_content_types.py new file mode 100644 index 0000000000..57c0463550 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_complex_types_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_anyof_complex_types_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAnyofComplexTypesResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_response_body_for_content_types.py new file mode 100644 index 0000000000..9548bd80a8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_anyof_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAnyofResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types.py new file mode 100644 index 0000000000..9a9acdee10 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_anyof_with_base_schema_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAnyofWithBaseSchemaResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types.py new file mode 100644 index 0000000000..1e7d7dd503 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_anyof_with_one_empty_schema_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostAnyofWithOneEmptySchemaResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types.py new file mode 100644 index 0000000000..234e28085a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_array_type_matches_arrays_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostArrayTypeMatchesArraysResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types.py new file mode 100644 index 0000000000..d9c89215c6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_boolean_type_matches_booleans_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostBooleanTypeMatchesBooleansResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_by_int_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_by_int_response_body_for_content_types.py new file mode 100644 index 0000000000..c24958f9e9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_by_int_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_by_int_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostByIntResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_by_number_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_by_number_response_body_for_content_types.py new file mode 100644 index 0000000000..b25ffaf327 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_by_number_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_by_number_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostByNumberResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_by_small_number_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_by_small_number_response_body_for_content_types.py new file mode 100644 index 0000000000..ebd44f5eac --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_by_small_number_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_by_small_number_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostBySmallNumberResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_date_time_format_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_date_time_format_response_body_for_content_types.py new file mode 100644 index 0000000000..e94b0c2552 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_date_time_format_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_date_time_format_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostDateTimeFormatResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_email_format_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_email_format_response_body_for_content_types.py new file mode 100644 index 0000000000..fd0f359da1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_email_format_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_email_format_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostEmailFormatResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types.py new file mode 100644 index 0000000000..57ad82fd77 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_enum_with0_does_not_match_false_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types.py new file mode 100644 index 0000000000..72d1997838 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_enum_with1_does_not_match_true_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types.py new file mode 100644 index 0000000000..c8305686f7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_enum_with_escaped_characters_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostEnumWithEscapedCharactersResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types.py new file mode 100644 index 0000000000..05231260c7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_enum_with_false_does_not_match0_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types.py new file mode 100644 index 0000000000..bea4b3e3f6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_enum_with_true_does_not_match1_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enums_in_properties_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enums_in_properties_response_body_for_content_types.py new file mode 100644 index 0000000000..0edfd61b88 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_enums_in_properties_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_enums_in_properties_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostEnumsInPropertiesResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_forbidden_property_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_forbidden_property_response_body_for_content_types.py new file mode 100644 index 0000000000..5393f81369 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_forbidden_property_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_forbidden_property_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostForbiddenPropertyResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_hostname_format_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_hostname_format_response_body_for_content_types.py new file mode 100644 index 0000000000..780d18a115 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_hostname_format_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_hostname_format_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostHostnameFormatResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types.py new file mode 100644 index 0000000000..28ace3c210 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_integer_type_matches_integers_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostIntegerTypeMatchesIntegersResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.py new file mode 100644 index 0000000000..b4f0e5ace7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types.py new file mode 100644 index 0000000000..a9a3fcce75 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_invalid_string_value_for_default_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostInvalidStringValueForDefaultResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ipv4_format_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ipv4_format_response_body_for_content_types.py new file mode 100644 index 0000000000..5c2a095c50 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ipv4_format_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_ipv4_format_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostIpv4FormatResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ipv6_format_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ipv6_format_response_body_for_content_types.py new file mode 100644 index 0000000000..231daa31e1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ipv6_format_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_ipv6_format_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostIpv6FormatResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_json_pointer_format_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_json_pointer_format_response_body_for_content_types.py new file mode 100644 index 0000000000..14fe52abf3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_json_pointer_format_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_json_pointer_format_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostJsonPointerFormatResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maximum_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maximum_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..135c48eb88 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maximum_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_maximum_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMaximumValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types.py new file mode 100644 index 0000000000..0b9f4c6585 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxitems_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxitems_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..f650e8dbda --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxitems_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_maxitems_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMaxitemsValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxlength_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxlength_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..e300e8a9cb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxlength_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_maxlength_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMaxlengthValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.py new file mode 100644 index 0000000000..ed154e366d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxproperties_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxproperties_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..7bbc0d7dd2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_maxproperties_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_maxproperties_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMaxpropertiesValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minimum_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minimum_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..5db44592d2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minimum_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_minimum_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMinimumValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types.py new file mode 100644 index 0000000000..d33537118b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMinimumValidationWithSignedIntegerResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minitems_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minitems_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..62e83546f0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minitems_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_minitems_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMinitemsValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minlength_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minlength_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..c33c6ff17c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minlength_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_minlength_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMinlengthValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minproperties_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minproperties_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..7cdf0b9ac7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_minproperties_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_minproperties_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostMinpropertiesValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types.py new file mode 100644 index 0000000000..0268fe25aa --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.py new file mode 100644 index 0000000000..68ad0f0a4d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_items_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_items_response_body_for_content_types.py new file mode 100644 index 0000000000..78492c45a5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_items_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_nested_items_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostNestedItemsResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.py new file mode 100644 index 0000000000..18390d6cdd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_not_more_complex_schema_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_not_more_complex_schema_response_body_for_content_types.py new file mode 100644 index 0000000000..2321185dcc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_not_more_complex_schema_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_not_more_complex_schema_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostNotMoreComplexSchemaResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_not_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_not_response_body_for_content_types.py new file mode 100644 index 0000000000..4479983190 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_not_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_not_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostNotResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types.py new file mode 100644 index 0000000000..c1c7cb23cd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_nul_characters_in_strings_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostNulCharactersInStringsResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types.py new file mode 100644 index 0000000000..0d4058d552 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types.py new file mode 100644 index 0000000000..62135db0c7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_number_type_matches_numbers_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostNumberTypeMatchesNumbersResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_object_properties_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_object_properties_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..141786c230 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_object_properties_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_object_properties_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostObjectPropertiesValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_object_type_matches_objects_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_object_type_matches_objects_response_body_for_content_types.py new file mode 100644 index 0000000000..211c386ed6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_object_type_matches_objects_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_object_type_matches_objects_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostObjectTypeMatchesObjectsResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_complex_types_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_complex_types_response_body_for_content_types.py new file mode 100644 index 0000000000..f56b2bef46 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_complex_types_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_oneof_complex_types_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostOneofComplexTypesResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_response_body_for_content_types.py new file mode 100644 index 0000000000..b88819ef17 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_oneof_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostOneofResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types.py new file mode 100644 index 0000000000..fcdbccfce4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_oneof_with_base_schema_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostOneofWithBaseSchemaResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types.py new file mode 100644 index 0000000000..02e6abc4b1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_oneof_with_empty_schema_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostOneofWithEmptySchemaResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_with_required_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_with_required_response_body_for_content_types.py new file mode 100644 index 0000000000..f5a9664a51 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_oneof_with_required_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_oneof_with_required_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostOneofWithRequiredResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types.py new file mode 100644 index 0000000000..1a862e844b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_pattern_is_not_anchored_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostPatternIsNotAnchoredResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_pattern_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_pattern_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..88c3da5de6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_pattern_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_pattern_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostPatternValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types.py new file mode 100644 index 0000000000..081476765e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_properties_with_escaped_characters_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostPropertiesWithEscapedCharactersResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.py new file mode 100644 index 0000000000..0b75f8b148 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types.py new file mode 100644 index 0000000000..94fc9c9da2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_ref_in_additionalproperties_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRefInAdditionalpropertiesResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_allof_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_allof_response_body_for_content_types.py new file mode 100644 index 0000000000..a40dcf8e5a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_allof_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_ref_in_allof_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRefInAllofResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_anyof_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_anyof_response_body_for_content_types.py new file mode 100644 index 0000000000..e0f407a0fd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_anyof_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_ref_in_anyof_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRefInAnyofResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_items_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_items_response_body_for_content_types.py new file mode 100644 index 0000000000..dae8c31146 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_items_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_ref_in_items_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRefInItemsResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_not_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_not_response_body_for_content_types.py new file mode 100644 index 0000000000..383fa2cf0e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_not_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_ref_in_not_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRefInNotResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_oneof_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_oneof_response_body_for_content_types.py new file mode 100644 index 0000000000..82d7f90272 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_oneof_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_ref_in_oneof_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRefInOneofResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_property_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_property_response_body_for_content_types.py new file mode 100644 index 0000000000..b2d7ad4468 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_ref_in_property_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_ref_in_property_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRefInPropertyResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_default_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_default_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..51feba5684 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_default_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_required_default_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRequiredDefaultValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..b41f1105d7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_required_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRequiredValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_with_empty_array_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_with_empty_array_response_body_for_content_types.py new file mode 100644 index 0000000000..928bbc72a7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_with_empty_array_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_required_with_empty_array_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRequiredWithEmptyArrayResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types.py new file mode 100644 index 0000000000..50f83818f4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_required_with_escaped_characters_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostRequiredWithEscapedCharactersResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_simple_enum_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_simple_enum_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..d9e1b211f1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_simple_enum_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_simple_enum_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostSimpleEnumValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_string_type_matches_strings_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_string_type_matches_strings_response_body_for_content_types.py new file mode 100644 index 0000000000..e7b69a9985 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_string_type_matches_strings_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_string_type_matches_strings_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostStringTypeMatchesStringsResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.py new file mode 100644 index 0000000000..e591237938 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..4ed02742f9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_uniqueitems_false_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostUniqueitemsFalseValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uniqueitems_validation_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uniqueitems_validation_response_body_for_content_types.py new file mode 100644 index 0000000000..11ef62e6f6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uniqueitems_validation_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_uniqueitems_validation_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostUniqueitemsValidationResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uri_format_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uri_format_response_body_for_content_types.py new file mode 100644 index 0000000000..a99810c721 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uri_format_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_uri_format_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostUriFormatResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uri_reference_format_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uri_reference_format_response_body_for_content_types.py new file mode 100644 index 0000000000..61ffe53b6c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uri_reference_format_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_uri_reference_format_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostUriReferenceFormatResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uri_template_format_response_body_for_content_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uri_template_format_response_body_for_content_types.py new file mode 100644 index 0000000000..5a32fe1814 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/paths/response_body_post_uri_template_format_response_body_for_content_types.py @@ -0,0 +1,7 @@ +from unit_test_api.paths.response_body_post_uri_template_format_response_body_for_content_types.post import ApiForpost + + +class ResponseBodyPostUriTemplateFormatResponseBodyForContentTypes( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tag_to_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tag_to_api.py new file mode 100644 index 0000000000..a40db5c5f9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tag_to_api.py @@ -0,0 +1,98 @@ +import typing_extensions + +from unit_test_api.apis.tags import TagValues +from unit_test_api.apis.tags.operation_request_body_api import OperationRequestBodyApi +from unit_test_api.apis.tags.path_post_api import PathPostApi +from unit_test_api.apis.tags.content_type_json_api import ContentTypeJsonApi +from unit_test_api.apis.tags.response_content_content_type_schema_api import ResponseContentContentTypeSchemaApi +from unit_test_api.apis.tags.additional_properties_api import AdditionalPropertiesApi +from unit_test_api.apis.tags.all_of_api import AllOfApi +from unit_test_api.apis.tags.any_of_api import AnyOfApi +from unit_test_api.apis.tags.default_api import DefaultApi +from unit_test_api.apis.tags.enum_api import EnumApi +from unit_test_api.apis.tags.format_api import FormatApi +from unit_test_api.apis.tags.items_api import ItemsApi +from unit_test_api.apis.tags.maximum_api import MaximumApi +from unit_test_api.apis.tags.max_items_api import MaxItemsApi +from unit_test_api.apis.tags.max_length_api import MaxLengthApi +from unit_test_api.apis.tags.max_properties_api import MaxPropertiesApi +from unit_test_api.apis.tags.minimum_api import MinimumApi +from unit_test_api.apis.tags.min_items_api import MinItemsApi +from unit_test_api.apis.tags.min_length_api import MinLengthApi +from unit_test_api.apis.tags.min_properties_api import MinPropertiesApi +from unit_test_api.apis.tags.multiple_of_api import MultipleOfApi +from unit_test_api.apis.tags.model_not_api import ModelNotApi +from unit_test_api.apis.tags.one_of_api import OneOfApi +from unit_test_api.apis.tags.pattern_api import PatternApi +from unit_test_api.apis.tags.properties_api import PropertiesApi +from unit_test_api.apis.tags.ref_api import RefApi +from unit_test_api.apis.tags.required_api import RequiredApi +from unit_test_api.apis.tags.type_api import TypeApi +from unit_test_api.apis.tags.unique_items_api import UniqueItemsApi + +TagToApi = typing_extensions.TypedDict( + 'TagToApi', + { + TagValues.OPERATION_REQUEST_BODY: OperationRequestBodyApi, + TagValues.PATH_POST: PathPostApi, + TagValues.CONTENT_TYPE_JSON: ContentTypeJsonApi, + TagValues.RESPONSE_CONTENT_CONTENT_TYPE_SCHEMA: ResponseContentContentTypeSchemaApi, + TagValues.ADDITIONAL_PROPERTIES: AdditionalPropertiesApi, + TagValues.ALL_OF: AllOfApi, + TagValues.ANY_OF: AnyOfApi, + TagValues.DEFAULT: DefaultApi, + TagValues.ENUM: EnumApi, + TagValues.FORMAT: FormatApi, + TagValues.ITEMS: ItemsApi, + TagValues.MAXIMUM: MaximumApi, + TagValues.MAX_ITEMS: MaxItemsApi, + TagValues.MAX_LENGTH: MaxLengthApi, + TagValues.MAX_PROPERTIES: MaxPropertiesApi, + TagValues.MINIMUM: MinimumApi, + TagValues.MIN_ITEMS: MinItemsApi, + TagValues.MIN_LENGTH: MinLengthApi, + TagValues.MIN_PROPERTIES: MinPropertiesApi, + TagValues.MULTIPLE_OF: MultipleOfApi, + TagValues.NOT: ModelNotApi, + TagValues.ONE_OF: OneOfApi, + TagValues.PATTERN: PatternApi, + TagValues.PROPERTIES: PropertiesApi, + TagValues.REF: RefApi, + TagValues.REQUIRED: RequiredApi, + TagValues.TYPE: TypeApi, + TagValues.UNIQUE_ITEMS: UniqueItemsApi, + } +) + +tag_to_api = TagToApi( + { + TagValues.OPERATION_REQUEST_BODY: OperationRequestBodyApi, + TagValues.PATH_POST: PathPostApi, + TagValues.CONTENT_TYPE_JSON: ContentTypeJsonApi, + TagValues.RESPONSE_CONTENT_CONTENT_TYPE_SCHEMA: ResponseContentContentTypeSchemaApi, + TagValues.ADDITIONAL_PROPERTIES: AdditionalPropertiesApi, + TagValues.ALL_OF: AllOfApi, + TagValues.ANY_OF: AnyOfApi, + TagValues.DEFAULT: DefaultApi, + TagValues.ENUM: EnumApi, + TagValues.FORMAT: FormatApi, + TagValues.ITEMS: ItemsApi, + TagValues.MAXIMUM: MaximumApi, + TagValues.MAX_ITEMS: MaxItemsApi, + TagValues.MAX_LENGTH: MaxLengthApi, + TagValues.MAX_PROPERTIES: MaxPropertiesApi, + TagValues.MINIMUM: MinimumApi, + TagValues.MIN_ITEMS: MinItemsApi, + TagValues.MIN_LENGTH: MinLengthApi, + TagValues.MIN_PROPERTIES: MinPropertiesApi, + TagValues.MULTIPLE_OF: MultipleOfApi, + TagValues.NOT: ModelNotApi, + TagValues.ONE_OF: OneOfApi, + TagValues.PATTERN: PatternApi, + TagValues.PROPERTIES: PropertiesApi, + TagValues.REF: RefApi, + TagValues.REQUIRED: RequiredApi, + TagValues.TYPE: TypeApi, + TagValues.UNIQUE_ITEMS: UniqueItemsApi, + } +) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/__init__.py new file mode 100644 index 0000000000..7a2dacb2e4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/__init__.py @@ -0,0 +1,36 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.apis.tag_to_api import tag_to_api + +import enum + + +class TagValues(str, enum.Enum): + OPERATION_REQUEST_BODY = "operation.requestBody" + PATH_POST = "path.post" + CONTENT_TYPE_JSON = "contentType_json" + RESPONSE_CONTENT_CONTENT_TYPE_SCHEMA = "response.content.contentType.schema" + ADDITIONAL_PROPERTIES = "additionalProperties" + ALL_OF = "allOf" + ANY_OF = "anyOf" + DEFAULT = "default" + ENUM = "enum" + FORMAT = "format" + ITEMS = "items" + MAXIMUM = "maximum" + MAX_ITEMS = "maxItems" + MAX_LENGTH = "maxLength" + MAX_PROPERTIES = "maxProperties" + MINIMUM = "minimum" + MIN_ITEMS = "minItems" + MIN_LENGTH = "minLength" + MIN_PROPERTIES = "minProperties" + MULTIPLE_OF = "multipleOf" + NOT = "not" + ONE_OF = "oneOf" + PATTERN = "pattern" + PROPERTIES = "properties" + REF = "$ref" + REQUIRED = "required" + TYPE = "type" + UNIQUE_ITEMS = "uniqueItems" diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/additional_properties_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/additional_properties_api.py new file mode 100644 index 0000000000..764e56412c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/additional_properties_api.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body.post import PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.post import PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_additionalproperties_are_allowed_by_default_request_body.post import PostAdditionalpropertiesAreAllowedByDefaultRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types.post import PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_additionalproperties_can_exist_by_itself_request_body.post import PostAdditionalpropertiesCanExistByItselfRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types.post import PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_additionalproperties_should_not_look_in_applicators_request_body.post import PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.post import PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes + + +class AdditionalPropertiesApi( + PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody, + PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes, + PostAdditionalpropertiesAreAllowedByDefaultRequestBody, + PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes, + PostAdditionalpropertiesCanExistByItselfRequestBody, + PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes, + PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody, + PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/all_of_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/all_of_api.py new file mode 100644 index 0000000000..cce0174269 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/all_of_api.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_allof_combined_with_anyof_oneof_request_body.post import PostAllofCombinedWithAnyofOneofRequestBody +from unit_test_api.paths.response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types.post import PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_request_body.post import PostAllofRequestBody +from unit_test_api.paths.response_body_post_allof_response_body_for_content_types.post import PostAllofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_simple_types_request_body.post import PostAllofSimpleTypesRequestBody +from unit_test_api.paths.response_body_post_allof_simple_types_response_body_for_content_types.post import PostAllofSimpleTypesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_base_schema_request_body.post import PostAllofWithBaseSchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_base_schema_response_body_for_content_types.post import PostAllofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_one_empty_schema_request_body.post import PostAllofWithOneEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_one_empty_schema_response_body_for_content_types.post import PostAllofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_the_first_empty_schema_request_body.post import PostAllofWithTheFirstEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types.post import PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_the_last_empty_schema_request_body.post import PostAllofWithTheLastEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types.post import PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_two_empty_schemas_request_body.post import PostAllofWithTwoEmptySchemasRequestBody +from unit_test_api.paths.response_body_post_allof_with_two_empty_schemas_response_body_for_content_types.post import PostAllofWithTwoEmptySchemasResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_allof_to_check_validation_semantics_request_body.post import PostNestedAllofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes + + +class AllOfApi( + PostAllofCombinedWithAnyofOneofRequestBody, + PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes, + PostAllofRequestBody, + PostAllofResponseBodyForContentTypes, + PostAllofSimpleTypesRequestBody, + PostAllofSimpleTypesResponseBodyForContentTypes, + PostAllofWithBaseSchemaRequestBody, + PostAllofWithBaseSchemaResponseBodyForContentTypes, + PostAllofWithOneEmptySchemaRequestBody, + PostAllofWithOneEmptySchemaResponseBodyForContentTypes, + PostAllofWithTheFirstEmptySchemaRequestBody, + PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes, + PostAllofWithTheLastEmptySchemaRequestBody, + PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes, + PostAllofWithTwoEmptySchemasRequestBody, + PostAllofWithTwoEmptySchemasResponseBodyForContentTypes, + PostNestedAllofToCheckValidationSemanticsRequestBody, + PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/any_of_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/any_of_api.py new file mode 100644 index 0000000000..de0242b5ae --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/any_of_api.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_anyof_complex_types_request_body.post import PostAnyofComplexTypesRequestBody +from unit_test_api.paths.response_body_post_anyof_complex_types_response_body_for_content_types.post import PostAnyofComplexTypesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_request_body.post import PostAnyofRequestBody +from unit_test_api.paths.response_body_post_anyof_response_body_for_content_types.post import PostAnyofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_with_base_schema_request_body.post import PostAnyofWithBaseSchemaRequestBody +from unit_test_api.paths.response_body_post_anyof_with_base_schema_response_body_for_content_types.post import PostAnyofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_with_one_empty_schema_request_body.post import PostAnyofWithOneEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_anyof_with_one_empty_schema_response_body_for_content_types.post import PostAnyofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_anyof_to_check_validation_semantics_request_body.post import PostNestedAnyofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes + + +class AnyOfApi( + PostAnyofComplexTypesRequestBody, + PostAnyofComplexTypesResponseBodyForContentTypes, + PostAnyofRequestBody, + PostAnyofResponseBodyForContentTypes, + PostAnyofWithBaseSchemaRequestBody, + PostAnyofWithBaseSchemaResponseBodyForContentTypes, + PostAnyofWithOneEmptySchemaRequestBody, + PostAnyofWithOneEmptySchemaResponseBodyForContentTypes, + PostNestedAnyofToCheckValidationSemanticsRequestBody, + PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/content_type_json_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/content_type_json_api.py new file mode 100644 index 0000000000..0e5d3b26c3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/content_type_json_api.py @@ -0,0 +1,369 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body.post import PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.post import PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_additionalproperties_are_allowed_by_default_request_body.post import PostAdditionalpropertiesAreAllowedByDefaultRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types.post import PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_additionalproperties_can_exist_by_itself_request_body.post import PostAdditionalpropertiesCanExistByItselfRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types.post import PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_additionalproperties_should_not_look_in_applicators_request_body.post import PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.post import PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_combined_with_anyof_oneof_request_body.post import PostAllofCombinedWithAnyofOneofRequestBody +from unit_test_api.paths.response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types.post import PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_request_body.post import PostAllofRequestBody +from unit_test_api.paths.response_body_post_allof_response_body_for_content_types.post import PostAllofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_simple_types_request_body.post import PostAllofSimpleTypesRequestBody +from unit_test_api.paths.response_body_post_allof_simple_types_response_body_for_content_types.post import PostAllofSimpleTypesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_base_schema_request_body.post import PostAllofWithBaseSchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_base_schema_response_body_for_content_types.post import PostAllofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_one_empty_schema_request_body.post import PostAllofWithOneEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_one_empty_schema_response_body_for_content_types.post import PostAllofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_the_first_empty_schema_request_body.post import PostAllofWithTheFirstEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types.post import PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_the_last_empty_schema_request_body.post import PostAllofWithTheLastEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types.post import PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_two_empty_schemas_request_body.post import PostAllofWithTwoEmptySchemasRequestBody +from unit_test_api.paths.response_body_post_allof_with_two_empty_schemas_response_body_for_content_types.post import PostAllofWithTwoEmptySchemasResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_complex_types_request_body.post import PostAnyofComplexTypesRequestBody +from unit_test_api.paths.response_body_post_anyof_complex_types_response_body_for_content_types.post import PostAnyofComplexTypesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_request_body.post import PostAnyofRequestBody +from unit_test_api.paths.response_body_post_anyof_response_body_for_content_types.post import PostAnyofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_with_base_schema_request_body.post import PostAnyofWithBaseSchemaRequestBody +from unit_test_api.paths.response_body_post_anyof_with_base_schema_response_body_for_content_types.post import PostAnyofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_with_one_empty_schema_request_body.post import PostAnyofWithOneEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_anyof_with_one_empty_schema_response_body_for_content_types.post import PostAnyofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_array_type_matches_arrays_request_body.post import PostArrayTypeMatchesArraysRequestBody +from unit_test_api.paths.response_body_post_array_type_matches_arrays_response_body_for_content_types.post import PostArrayTypeMatchesArraysResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_boolean_type_matches_booleans_request_body.post import PostBooleanTypeMatchesBooleansRequestBody +from unit_test_api.paths.response_body_post_boolean_type_matches_booleans_response_body_for_content_types.post import PostBooleanTypeMatchesBooleansResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_by_int_request_body.post import PostByIntRequestBody +from unit_test_api.paths.response_body_post_by_int_response_body_for_content_types.post import PostByIntResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_by_number_request_body.post import PostByNumberRequestBody +from unit_test_api.paths.response_body_post_by_number_response_body_for_content_types.post import PostByNumberResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_by_small_number_request_body.post import PostBySmallNumberRequestBody +from unit_test_api.paths.response_body_post_by_small_number_response_body_for_content_types.post import PostBySmallNumberResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_date_time_format_request_body.post import PostDateTimeFormatRequestBody +from unit_test_api.paths.response_body_post_date_time_format_response_body_for_content_types.post import PostDateTimeFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_email_format_request_body.post import PostEmailFormatRequestBody +from unit_test_api.paths.response_body_post_email_format_response_body_for_content_types.post import PostEmailFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with0_does_not_match_false_request_body.post import PostEnumWith0DoesNotMatchFalseRequestBody +from unit_test_api.paths.response_body_post_enum_with0_does_not_match_false_response_body_for_content_types.post import PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with1_does_not_match_true_request_body.post import PostEnumWith1DoesNotMatchTrueRequestBody +from unit_test_api.paths.response_body_post_enum_with1_does_not_match_true_response_body_for_content_types.post import PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with_escaped_characters_request_body.post import PostEnumWithEscapedCharactersRequestBody +from unit_test_api.paths.response_body_post_enum_with_escaped_characters_response_body_for_content_types.post import PostEnumWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with_false_does_not_match0_request_body.post import PostEnumWithFalseDoesNotMatch0RequestBody +from unit_test_api.paths.response_body_post_enum_with_false_does_not_match0_response_body_for_content_types.post import PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with_true_does_not_match1_request_body.post import PostEnumWithTrueDoesNotMatch1RequestBody +from unit_test_api.paths.response_body_post_enum_with_true_does_not_match1_response_body_for_content_types.post import PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enums_in_properties_request_body.post import PostEnumsInPropertiesRequestBody +from unit_test_api.paths.response_body_post_enums_in_properties_response_body_for_content_types.post import PostEnumsInPropertiesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_forbidden_property_request_body.post import PostForbiddenPropertyRequestBody +from unit_test_api.paths.response_body_post_forbidden_property_response_body_for_content_types.post import PostForbiddenPropertyResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_hostname_format_request_body.post import PostHostnameFormatRequestBody +from unit_test_api.paths.response_body_post_hostname_format_response_body_for_content_types.post import PostHostnameFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_integer_type_matches_integers_request_body.post import PostIntegerTypeMatchesIntegersRequestBody +from unit_test_api.paths.response_body_post_integer_type_matches_integers_response_body_for_content_types.post import PostIntegerTypeMatchesIntegersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.post import PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody +from unit_test_api.paths.response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.post import PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_invalid_string_value_for_default_request_body.post import PostInvalidStringValueForDefaultRequestBody +from unit_test_api.paths.response_body_post_invalid_string_value_for_default_response_body_for_content_types.post import PostInvalidStringValueForDefaultResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ipv4_format_request_body.post import PostIpv4FormatRequestBody +from unit_test_api.paths.response_body_post_ipv4_format_response_body_for_content_types.post import PostIpv4FormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ipv6_format_request_body.post import PostIpv6FormatRequestBody +from unit_test_api.paths.response_body_post_ipv6_format_response_body_for_content_types.post import PostIpv6FormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_json_pointer_format_request_body.post import PostJsonPointerFormatRequestBody +from unit_test_api.paths.response_body_post_json_pointer_format_response_body_for_content_types.post import PostJsonPointerFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maximum_validation_request_body.post import PostMaximumValidationRequestBody +from unit_test_api.paths.response_body_post_maximum_validation_response_body_for_content_types.post import PostMaximumValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maximum_validation_with_unsigned_integer_request_body.post import PostMaximumValidationWithUnsignedIntegerRequestBody +from unit_test_api.paths.response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types.post import PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maxitems_validation_request_body.post import PostMaxitemsValidationRequestBody +from unit_test_api.paths.response_body_post_maxitems_validation_response_body_for_content_types.post import PostMaxitemsValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maxlength_validation_request_body.post import PostMaxlengthValidationRequestBody +from unit_test_api.paths.response_body_post_maxlength_validation_response_body_for_content_types.post import PostMaxlengthValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maxproperties0_means_the_object_is_empty_request_body.post import PostMaxproperties0MeansTheObjectIsEmptyRequestBody +from unit_test_api.paths.response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.post import PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maxproperties_validation_request_body.post import PostMaxpropertiesValidationRequestBody +from unit_test_api.paths.response_body_post_maxproperties_validation_response_body_for_content_types.post import PostMaxpropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minimum_validation_request_body.post import PostMinimumValidationRequestBody +from unit_test_api.paths.response_body_post_minimum_validation_response_body_for_content_types.post import PostMinimumValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minimum_validation_with_signed_integer_request_body.post import PostMinimumValidationWithSignedIntegerRequestBody +from unit_test_api.paths.response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types.post import PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minitems_validation_request_body.post import PostMinitemsValidationRequestBody +from unit_test_api.paths.response_body_post_minitems_validation_response_body_for_content_types.post import PostMinitemsValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minlength_validation_request_body.post import PostMinlengthValidationRequestBody +from unit_test_api.paths.response_body_post_minlength_validation_response_body_for_content_types.post import PostMinlengthValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minproperties_validation_request_body.post import PostMinpropertiesValidationRequestBody +from unit_test_api.paths.response_body_post_minproperties_validation_response_body_for_content_types.post import PostMinpropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_allof_to_check_validation_semantics_request_body.post import PostNestedAllofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_anyof_to_check_validation_semantics_request_body.post import PostNestedAnyofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_items_request_body.post import PostNestedItemsRequestBody +from unit_test_api.paths.response_body_post_nested_items_response_body_for_content_types.post import PostNestedItemsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_oneof_to_check_validation_semantics_request_body.post import PostNestedOneofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_not_more_complex_schema_request_body.post import PostNotMoreComplexSchemaRequestBody +from unit_test_api.paths.response_body_post_not_more_complex_schema_response_body_for_content_types.post import PostNotMoreComplexSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_not_request_body.post import PostNotRequestBody +from unit_test_api.paths.response_body_post_not_response_body_for_content_types.post import PostNotResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nul_characters_in_strings_request_body.post import PostNulCharactersInStringsRequestBody +from unit_test_api.paths.response_body_post_nul_characters_in_strings_response_body_for_content_types.post import PostNulCharactersInStringsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_null_type_matches_only_the_null_object_request_body.post import PostNullTypeMatchesOnlyTheNullObjectRequestBody +from unit_test_api.paths.response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types.post import PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_number_type_matches_numbers_request_body.post import PostNumberTypeMatchesNumbersRequestBody +from unit_test_api.paths.response_body_post_number_type_matches_numbers_response_body_for_content_types.post import PostNumberTypeMatchesNumbersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_object_properties_validation_request_body.post import PostObjectPropertiesValidationRequestBody +from unit_test_api.paths.response_body_post_object_properties_validation_response_body_for_content_types.post import PostObjectPropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_object_type_matches_objects_request_body.post import PostObjectTypeMatchesObjectsRequestBody +from unit_test_api.paths.response_body_post_object_type_matches_objects_response_body_for_content_types.post import PostObjectTypeMatchesObjectsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_complex_types_request_body.post import PostOneofComplexTypesRequestBody +from unit_test_api.paths.response_body_post_oneof_complex_types_response_body_for_content_types.post import PostOneofComplexTypesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_request_body.post import PostOneofRequestBody +from unit_test_api.paths.response_body_post_oneof_response_body_for_content_types.post import PostOneofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_with_base_schema_request_body.post import PostOneofWithBaseSchemaRequestBody +from unit_test_api.paths.response_body_post_oneof_with_base_schema_response_body_for_content_types.post import PostOneofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_with_empty_schema_request_body.post import PostOneofWithEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_oneof_with_empty_schema_response_body_for_content_types.post import PostOneofWithEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_with_required_request_body.post import PostOneofWithRequiredRequestBody +from unit_test_api.paths.response_body_post_oneof_with_required_response_body_for_content_types.post import PostOneofWithRequiredResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_pattern_is_not_anchored_request_body.post import PostPatternIsNotAnchoredRequestBody +from unit_test_api.paths.response_body_post_pattern_is_not_anchored_response_body_for_content_types.post import PostPatternIsNotAnchoredResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_pattern_validation_request_body.post import PostPatternValidationRequestBody +from unit_test_api.paths.response_body_post_pattern_validation_response_body_for_content_types.post import PostPatternValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_properties_with_escaped_characters_request_body.post import PostPropertiesWithEscapedCharactersRequestBody +from unit_test_api.paths.response_body_post_properties_with_escaped_characters_response_body_for_content_types.post import PostPropertiesWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_property_named_ref_that_is_not_a_reference_request_body.post import PostPropertyNamedRefThatIsNotAReferenceRequestBody +from unit_test_api.paths.response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.post import PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_additionalproperties_request_body.post import PostRefInAdditionalpropertiesRequestBody +from unit_test_api.paths.response_body_post_ref_in_additionalproperties_response_body_for_content_types.post import PostRefInAdditionalpropertiesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_allof_request_body.post import PostRefInAllofRequestBody +from unit_test_api.paths.response_body_post_ref_in_allof_response_body_for_content_types.post import PostRefInAllofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_anyof_request_body.post import PostRefInAnyofRequestBody +from unit_test_api.paths.response_body_post_ref_in_anyof_response_body_for_content_types.post import PostRefInAnyofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_items_request_body.post import PostRefInItemsRequestBody +from unit_test_api.paths.response_body_post_ref_in_items_response_body_for_content_types.post import PostRefInItemsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_not_request_body.post import PostRefInNotRequestBody +from unit_test_api.paths.response_body_post_ref_in_not_response_body_for_content_types.post import PostRefInNotResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_oneof_request_body.post import PostRefInOneofRequestBody +from unit_test_api.paths.response_body_post_ref_in_oneof_response_body_for_content_types.post import PostRefInOneofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_property_request_body.post import PostRefInPropertyRequestBody +from unit_test_api.paths.response_body_post_ref_in_property_response_body_for_content_types.post import PostRefInPropertyResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_default_validation_request_body.post import PostRequiredDefaultValidationRequestBody +from unit_test_api.paths.response_body_post_required_default_validation_response_body_for_content_types.post import PostRequiredDefaultValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_validation_request_body.post import PostRequiredValidationRequestBody +from unit_test_api.paths.response_body_post_required_validation_response_body_for_content_types.post import PostRequiredValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_with_empty_array_request_body.post import PostRequiredWithEmptyArrayRequestBody +from unit_test_api.paths.response_body_post_required_with_empty_array_response_body_for_content_types.post import PostRequiredWithEmptyArrayResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_with_escaped_characters_request_body.post import PostRequiredWithEscapedCharactersRequestBody +from unit_test_api.paths.response_body_post_required_with_escaped_characters_response_body_for_content_types.post import PostRequiredWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_simple_enum_validation_request_body.post import PostSimpleEnumValidationRequestBody +from unit_test_api.paths.response_body_post_simple_enum_validation_response_body_for_content_types.post import PostSimpleEnumValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_string_type_matches_strings_request_body.post import PostStringTypeMatchesStringsRequestBody +from unit_test_api.paths.response_body_post_string_type_matches_strings_response_body_for_content_types.post import PostStringTypeMatchesStringsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.post import PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody +from unit_test_api.paths.response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.post import PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uniqueitems_false_validation_request_body.post import PostUniqueitemsFalseValidationRequestBody +from unit_test_api.paths.response_body_post_uniqueitems_false_validation_response_body_for_content_types.post import PostUniqueitemsFalseValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uniqueitems_validation_request_body.post import PostUniqueitemsValidationRequestBody +from unit_test_api.paths.response_body_post_uniqueitems_validation_response_body_for_content_types.post import PostUniqueitemsValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uri_format_request_body.post import PostUriFormatRequestBody +from unit_test_api.paths.response_body_post_uri_format_response_body_for_content_types.post import PostUriFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uri_reference_format_request_body.post import PostUriReferenceFormatRequestBody +from unit_test_api.paths.response_body_post_uri_reference_format_response_body_for_content_types.post import PostUriReferenceFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uri_template_format_request_body.post import PostUriTemplateFormatRequestBody +from unit_test_api.paths.response_body_post_uri_template_format_response_body_for_content_types.post import PostUriTemplateFormatResponseBodyForContentTypes + + +class ContentTypeJsonApi( + PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody, + PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes, + PostAdditionalpropertiesAreAllowedByDefaultRequestBody, + PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes, + PostAdditionalpropertiesCanExistByItselfRequestBody, + PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes, + PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody, + PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes, + PostAllofCombinedWithAnyofOneofRequestBody, + PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes, + PostAllofRequestBody, + PostAllofResponseBodyForContentTypes, + PostAllofSimpleTypesRequestBody, + PostAllofSimpleTypesResponseBodyForContentTypes, + PostAllofWithBaseSchemaRequestBody, + PostAllofWithBaseSchemaResponseBodyForContentTypes, + PostAllofWithOneEmptySchemaRequestBody, + PostAllofWithOneEmptySchemaResponseBodyForContentTypes, + PostAllofWithTheFirstEmptySchemaRequestBody, + PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes, + PostAllofWithTheLastEmptySchemaRequestBody, + PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes, + PostAllofWithTwoEmptySchemasRequestBody, + PostAllofWithTwoEmptySchemasResponseBodyForContentTypes, + PostAnyofComplexTypesRequestBody, + PostAnyofComplexTypesResponseBodyForContentTypes, + PostAnyofRequestBody, + PostAnyofResponseBodyForContentTypes, + PostAnyofWithBaseSchemaRequestBody, + PostAnyofWithBaseSchemaResponseBodyForContentTypes, + PostAnyofWithOneEmptySchemaRequestBody, + PostAnyofWithOneEmptySchemaResponseBodyForContentTypes, + PostArrayTypeMatchesArraysRequestBody, + PostArrayTypeMatchesArraysResponseBodyForContentTypes, + PostBooleanTypeMatchesBooleansRequestBody, + PostBooleanTypeMatchesBooleansResponseBodyForContentTypes, + PostByIntRequestBody, + PostByIntResponseBodyForContentTypes, + PostByNumberRequestBody, + PostByNumberResponseBodyForContentTypes, + PostBySmallNumberRequestBody, + PostBySmallNumberResponseBodyForContentTypes, + PostDateTimeFormatRequestBody, + PostDateTimeFormatResponseBodyForContentTypes, + PostEmailFormatRequestBody, + PostEmailFormatResponseBodyForContentTypes, + PostEnumWith0DoesNotMatchFalseRequestBody, + PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes, + PostEnumWith1DoesNotMatchTrueRequestBody, + PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes, + PostEnumWithEscapedCharactersRequestBody, + PostEnumWithEscapedCharactersResponseBodyForContentTypes, + PostEnumWithFalseDoesNotMatch0RequestBody, + PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes, + PostEnumWithTrueDoesNotMatch1RequestBody, + PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes, + PostEnumsInPropertiesRequestBody, + PostEnumsInPropertiesResponseBodyForContentTypes, + PostForbiddenPropertyRequestBody, + PostForbiddenPropertyResponseBodyForContentTypes, + PostHostnameFormatRequestBody, + PostHostnameFormatResponseBodyForContentTypes, + PostIntegerTypeMatchesIntegersRequestBody, + PostIntegerTypeMatchesIntegersResponseBodyForContentTypes, + PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody, + PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes, + PostInvalidStringValueForDefaultRequestBody, + PostInvalidStringValueForDefaultResponseBodyForContentTypes, + PostIpv4FormatRequestBody, + PostIpv4FormatResponseBodyForContentTypes, + PostIpv6FormatRequestBody, + PostIpv6FormatResponseBodyForContentTypes, + PostJsonPointerFormatRequestBody, + PostJsonPointerFormatResponseBodyForContentTypes, + PostMaximumValidationRequestBody, + PostMaximumValidationResponseBodyForContentTypes, + PostMaximumValidationWithUnsignedIntegerRequestBody, + PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes, + PostMaxitemsValidationRequestBody, + PostMaxitemsValidationResponseBodyForContentTypes, + PostMaxlengthValidationRequestBody, + PostMaxlengthValidationResponseBodyForContentTypes, + PostMaxproperties0MeansTheObjectIsEmptyRequestBody, + PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes, + PostMaxpropertiesValidationRequestBody, + PostMaxpropertiesValidationResponseBodyForContentTypes, + PostMinimumValidationRequestBody, + PostMinimumValidationResponseBodyForContentTypes, + PostMinimumValidationWithSignedIntegerRequestBody, + PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes, + PostMinitemsValidationRequestBody, + PostMinitemsValidationResponseBodyForContentTypes, + PostMinlengthValidationRequestBody, + PostMinlengthValidationResponseBodyForContentTypes, + PostMinpropertiesValidationRequestBody, + PostMinpropertiesValidationResponseBodyForContentTypes, + PostNestedAllofToCheckValidationSemanticsRequestBody, + PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes, + PostNestedAnyofToCheckValidationSemanticsRequestBody, + PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes, + PostNestedItemsRequestBody, + PostNestedItemsResponseBodyForContentTypes, + PostNestedOneofToCheckValidationSemanticsRequestBody, + PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes, + PostNotMoreComplexSchemaRequestBody, + PostNotMoreComplexSchemaResponseBodyForContentTypes, + PostNotRequestBody, + PostNotResponseBodyForContentTypes, + PostNulCharactersInStringsRequestBody, + PostNulCharactersInStringsResponseBodyForContentTypes, + PostNullTypeMatchesOnlyTheNullObjectRequestBody, + PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes, + PostNumberTypeMatchesNumbersRequestBody, + PostNumberTypeMatchesNumbersResponseBodyForContentTypes, + PostObjectPropertiesValidationRequestBody, + PostObjectPropertiesValidationResponseBodyForContentTypes, + PostObjectTypeMatchesObjectsRequestBody, + PostObjectTypeMatchesObjectsResponseBodyForContentTypes, + PostOneofComplexTypesRequestBody, + PostOneofComplexTypesResponseBodyForContentTypes, + PostOneofRequestBody, + PostOneofResponseBodyForContentTypes, + PostOneofWithBaseSchemaRequestBody, + PostOneofWithBaseSchemaResponseBodyForContentTypes, + PostOneofWithEmptySchemaRequestBody, + PostOneofWithEmptySchemaResponseBodyForContentTypes, + PostOneofWithRequiredRequestBody, + PostOneofWithRequiredResponseBodyForContentTypes, + PostPatternIsNotAnchoredRequestBody, + PostPatternIsNotAnchoredResponseBodyForContentTypes, + PostPatternValidationRequestBody, + PostPatternValidationResponseBodyForContentTypes, + PostPropertiesWithEscapedCharactersRequestBody, + PostPropertiesWithEscapedCharactersResponseBodyForContentTypes, + PostPropertyNamedRefThatIsNotAReferenceRequestBody, + PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes, + PostRefInAdditionalpropertiesRequestBody, + PostRefInAdditionalpropertiesResponseBodyForContentTypes, + PostRefInAllofRequestBody, + PostRefInAllofResponseBodyForContentTypes, + PostRefInAnyofRequestBody, + PostRefInAnyofResponseBodyForContentTypes, + PostRefInItemsRequestBody, + PostRefInItemsResponseBodyForContentTypes, + PostRefInNotRequestBody, + PostRefInNotResponseBodyForContentTypes, + PostRefInOneofRequestBody, + PostRefInOneofResponseBodyForContentTypes, + PostRefInPropertyRequestBody, + PostRefInPropertyResponseBodyForContentTypes, + PostRequiredDefaultValidationRequestBody, + PostRequiredDefaultValidationResponseBodyForContentTypes, + PostRequiredValidationRequestBody, + PostRequiredValidationResponseBodyForContentTypes, + PostRequiredWithEmptyArrayRequestBody, + PostRequiredWithEmptyArrayResponseBodyForContentTypes, + PostRequiredWithEscapedCharactersRequestBody, + PostRequiredWithEscapedCharactersResponseBodyForContentTypes, + PostSimpleEnumValidationRequestBody, + PostSimpleEnumValidationResponseBodyForContentTypes, + PostStringTypeMatchesStringsRequestBody, + PostStringTypeMatchesStringsResponseBodyForContentTypes, + PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody, + PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes, + PostUniqueitemsFalseValidationRequestBody, + PostUniqueitemsFalseValidationResponseBodyForContentTypes, + PostUniqueitemsValidationRequestBody, + PostUniqueitemsValidationResponseBodyForContentTypes, + PostUriFormatRequestBody, + PostUriFormatResponseBodyForContentTypes, + PostUriReferenceFormatRequestBody, + PostUriReferenceFormatResponseBodyForContentTypes, + PostUriTemplateFormatRequestBody, + PostUriTemplateFormatResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/default_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/default_api.py new file mode 100644 index 0000000000..63ec1b87fe --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/default_api.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_invalid_string_value_for_default_request_body.post import PostInvalidStringValueForDefaultRequestBody +from unit_test_api.paths.response_body_post_invalid_string_value_for_default_response_body_for_content_types.post import PostInvalidStringValueForDefaultResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.post import PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody +from unit_test_api.paths.response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.post import PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes + + +class DefaultApi( + PostInvalidStringValueForDefaultRequestBody, + PostInvalidStringValueForDefaultResponseBodyForContentTypes, + PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody, + PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/enum_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/enum_api.py new file mode 100644 index 0000000000..a5fe300661 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/enum_api.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_enum_with0_does_not_match_false_request_body.post import PostEnumWith0DoesNotMatchFalseRequestBody +from unit_test_api.paths.response_body_post_enum_with0_does_not_match_false_response_body_for_content_types.post import PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with1_does_not_match_true_request_body.post import PostEnumWith1DoesNotMatchTrueRequestBody +from unit_test_api.paths.response_body_post_enum_with1_does_not_match_true_response_body_for_content_types.post import PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with_escaped_characters_request_body.post import PostEnumWithEscapedCharactersRequestBody +from unit_test_api.paths.response_body_post_enum_with_escaped_characters_response_body_for_content_types.post import PostEnumWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with_false_does_not_match0_request_body.post import PostEnumWithFalseDoesNotMatch0RequestBody +from unit_test_api.paths.response_body_post_enum_with_false_does_not_match0_response_body_for_content_types.post import PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with_true_does_not_match1_request_body.post import PostEnumWithTrueDoesNotMatch1RequestBody +from unit_test_api.paths.response_body_post_enum_with_true_does_not_match1_response_body_for_content_types.post import PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enums_in_properties_request_body.post import PostEnumsInPropertiesRequestBody +from unit_test_api.paths.response_body_post_enums_in_properties_response_body_for_content_types.post import PostEnumsInPropertiesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nul_characters_in_strings_request_body.post import PostNulCharactersInStringsRequestBody +from unit_test_api.paths.response_body_post_nul_characters_in_strings_response_body_for_content_types.post import PostNulCharactersInStringsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_simple_enum_validation_request_body.post import PostSimpleEnumValidationRequestBody +from unit_test_api.paths.response_body_post_simple_enum_validation_response_body_for_content_types.post import PostSimpleEnumValidationResponseBodyForContentTypes + + +class EnumApi( + PostEnumWith0DoesNotMatchFalseRequestBody, + PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes, + PostEnumWith1DoesNotMatchTrueRequestBody, + PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes, + PostEnumWithEscapedCharactersRequestBody, + PostEnumWithEscapedCharactersResponseBodyForContentTypes, + PostEnumWithFalseDoesNotMatch0RequestBody, + PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes, + PostEnumWithTrueDoesNotMatch1RequestBody, + PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes, + PostEnumsInPropertiesRequestBody, + PostEnumsInPropertiesResponseBodyForContentTypes, + PostNulCharactersInStringsRequestBody, + PostNulCharactersInStringsResponseBodyForContentTypes, + PostSimpleEnumValidationRequestBody, + PostSimpleEnumValidationResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/format_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/format_api.py new file mode 100644 index 0000000000..2741a9bac7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/format_api.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_date_time_format_request_body.post import PostDateTimeFormatRequestBody +from unit_test_api.paths.response_body_post_date_time_format_response_body_for_content_types.post import PostDateTimeFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_email_format_request_body.post import PostEmailFormatRequestBody +from unit_test_api.paths.response_body_post_email_format_response_body_for_content_types.post import PostEmailFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_hostname_format_request_body.post import PostHostnameFormatRequestBody +from unit_test_api.paths.response_body_post_hostname_format_response_body_for_content_types.post import PostHostnameFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ipv4_format_request_body.post import PostIpv4FormatRequestBody +from unit_test_api.paths.response_body_post_ipv4_format_response_body_for_content_types.post import PostIpv4FormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ipv6_format_request_body.post import PostIpv6FormatRequestBody +from unit_test_api.paths.response_body_post_ipv6_format_response_body_for_content_types.post import PostIpv6FormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_json_pointer_format_request_body.post import PostJsonPointerFormatRequestBody +from unit_test_api.paths.response_body_post_json_pointer_format_response_body_for_content_types.post import PostJsonPointerFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uri_format_request_body.post import PostUriFormatRequestBody +from unit_test_api.paths.response_body_post_uri_format_response_body_for_content_types.post import PostUriFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uri_reference_format_request_body.post import PostUriReferenceFormatRequestBody +from unit_test_api.paths.response_body_post_uri_reference_format_response_body_for_content_types.post import PostUriReferenceFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uri_template_format_request_body.post import PostUriTemplateFormatRequestBody +from unit_test_api.paths.response_body_post_uri_template_format_response_body_for_content_types.post import PostUriTemplateFormatResponseBodyForContentTypes + + +class FormatApi( + PostDateTimeFormatRequestBody, + PostDateTimeFormatResponseBodyForContentTypes, + PostEmailFormatRequestBody, + PostEmailFormatResponseBodyForContentTypes, + PostHostnameFormatRequestBody, + PostHostnameFormatResponseBodyForContentTypes, + PostIpv4FormatRequestBody, + PostIpv4FormatResponseBodyForContentTypes, + PostIpv6FormatRequestBody, + PostIpv6FormatResponseBodyForContentTypes, + PostJsonPointerFormatRequestBody, + PostJsonPointerFormatResponseBodyForContentTypes, + PostUriFormatRequestBody, + PostUriFormatResponseBodyForContentTypes, + PostUriReferenceFormatRequestBody, + PostUriReferenceFormatResponseBodyForContentTypes, + PostUriTemplateFormatRequestBody, + PostUriTemplateFormatResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/items_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/items_api.py new file mode 100644 index 0000000000..edfe56e91f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/items_api.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_nested_items_request_body.post import PostNestedItemsRequestBody +from unit_test_api.paths.response_body_post_nested_items_response_body_for_content_types.post import PostNestedItemsResponseBodyForContentTypes + + +class ItemsApi( + PostNestedItemsRequestBody, + PostNestedItemsResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/max_items_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/max_items_api.py new file mode 100644 index 0000000000..4d06489252 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/max_items_api.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_maxitems_validation_request_body.post import PostMaxitemsValidationRequestBody +from unit_test_api.paths.response_body_post_maxitems_validation_response_body_for_content_types.post import PostMaxitemsValidationResponseBodyForContentTypes + + +class MaxItemsApi( + PostMaxitemsValidationRequestBody, + PostMaxitemsValidationResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/max_length_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/max_length_api.py new file mode 100644 index 0000000000..693a1ef965 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/max_length_api.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_maxlength_validation_request_body.post import PostMaxlengthValidationRequestBody +from unit_test_api.paths.response_body_post_maxlength_validation_response_body_for_content_types.post import PostMaxlengthValidationResponseBodyForContentTypes + + +class MaxLengthApi( + PostMaxlengthValidationRequestBody, + PostMaxlengthValidationResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/max_properties_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/max_properties_api.py new file mode 100644 index 0000000000..56c90ed28c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/max_properties_api.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_maxproperties0_means_the_object_is_empty_request_body.post import PostMaxproperties0MeansTheObjectIsEmptyRequestBody +from unit_test_api.paths.response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.post import PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maxproperties_validation_request_body.post import PostMaxpropertiesValidationRequestBody +from unit_test_api.paths.response_body_post_maxproperties_validation_response_body_for_content_types.post import PostMaxpropertiesValidationResponseBodyForContentTypes + + +class MaxPropertiesApi( + PostMaxproperties0MeansTheObjectIsEmptyRequestBody, + PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes, + PostMaxpropertiesValidationRequestBody, + PostMaxpropertiesValidationResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/maximum_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/maximum_api.py new file mode 100644 index 0000000000..017bc30650 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/maximum_api.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_maximum_validation_request_body.post import PostMaximumValidationRequestBody +from unit_test_api.paths.response_body_post_maximum_validation_response_body_for_content_types.post import PostMaximumValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maximum_validation_with_unsigned_integer_request_body.post import PostMaximumValidationWithUnsignedIntegerRequestBody +from unit_test_api.paths.response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types.post import PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes + + +class MaximumApi( + PostMaximumValidationRequestBody, + PostMaximumValidationResponseBodyForContentTypes, + PostMaximumValidationWithUnsignedIntegerRequestBody, + PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/min_items_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/min_items_api.py new file mode 100644 index 0000000000..93f1ae37b0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/min_items_api.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_minitems_validation_request_body.post import PostMinitemsValidationRequestBody +from unit_test_api.paths.response_body_post_minitems_validation_response_body_for_content_types.post import PostMinitemsValidationResponseBodyForContentTypes + + +class MinItemsApi( + PostMinitemsValidationRequestBody, + PostMinitemsValidationResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/min_length_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/min_length_api.py new file mode 100644 index 0000000000..60429b6e3c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/min_length_api.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_minlength_validation_request_body.post import PostMinlengthValidationRequestBody +from unit_test_api.paths.response_body_post_minlength_validation_response_body_for_content_types.post import PostMinlengthValidationResponseBodyForContentTypes + + +class MinLengthApi( + PostMinlengthValidationRequestBody, + PostMinlengthValidationResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/min_properties_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/min_properties_api.py new file mode 100644 index 0000000000..d51d44f4b8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/min_properties_api.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_minproperties_validation_request_body.post import PostMinpropertiesValidationRequestBody +from unit_test_api.paths.response_body_post_minproperties_validation_response_body_for_content_types.post import PostMinpropertiesValidationResponseBodyForContentTypes + + +class MinPropertiesApi( + PostMinpropertiesValidationRequestBody, + PostMinpropertiesValidationResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/minimum_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/minimum_api.py new file mode 100644 index 0000000000..f7e4c9ac0e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/minimum_api.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_minimum_validation_request_body.post import PostMinimumValidationRequestBody +from unit_test_api.paths.response_body_post_minimum_validation_response_body_for_content_types.post import PostMinimumValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minimum_validation_with_signed_integer_request_body.post import PostMinimumValidationWithSignedIntegerRequestBody +from unit_test_api.paths.response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types.post import PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes + + +class MinimumApi( + PostMinimumValidationRequestBody, + PostMinimumValidationResponseBodyForContentTypes, + PostMinimumValidationWithSignedIntegerRequestBody, + PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/model_not_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/model_not_api.py new file mode 100644 index 0000000000..ae8de1451f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/model_not_api.py @@ -0,0 +1,33 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_forbidden_property_request_body.post import PostForbiddenPropertyRequestBody +from unit_test_api.paths.response_body_post_forbidden_property_response_body_for_content_types.post import PostForbiddenPropertyResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_not_more_complex_schema_request_body.post import PostNotMoreComplexSchemaRequestBody +from unit_test_api.paths.response_body_post_not_more_complex_schema_response_body_for_content_types.post import PostNotMoreComplexSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_not_request_body.post import PostNotRequestBody +from unit_test_api.paths.response_body_post_not_response_body_for_content_types.post import PostNotResponseBodyForContentTypes + + +class ModelNotApi( + PostForbiddenPropertyRequestBody, + PostForbiddenPropertyResponseBodyForContentTypes, + PostNotMoreComplexSchemaRequestBody, + PostNotMoreComplexSchemaResponseBodyForContentTypes, + PostNotRequestBody, + PostNotResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/multiple_of_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/multiple_of_api.py new file mode 100644 index 0000000000..f694870392 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/multiple_of_api.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_by_int_request_body.post import PostByIntRequestBody +from unit_test_api.paths.response_body_post_by_int_response_body_for_content_types.post import PostByIntResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_by_number_request_body.post import PostByNumberRequestBody +from unit_test_api.paths.response_body_post_by_number_response_body_for_content_types.post import PostByNumberResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_by_small_number_request_body.post import PostBySmallNumberRequestBody +from unit_test_api.paths.response_body_post_by_small_number_response_body_for_content_types.post import PostBySmallNumberResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.post import PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody +from unit_test_api.paths.response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.post import PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes + + +class MultipleOfApi( + PostByIntRequestBody, + PostByIntResponseBodyForContentTypes, + PostByNumberRequestBody, + PostByNumberResponseBodyForContentTypes, + PostBySmallNumberRequestBody, + PostBySmallNumberResponseBodyForContentTypes, + PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody, + PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/one_of_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/one_of_api.py new file mode 100644 index 0000000000..4582b5e30f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/one_of_api.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_nested_oneof_to_check_validation_semantics_request_body.post import PostNestedOneofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_complex_types_request_body.post import PostOneofComplexTypesRequestBody +from unit_test_api.paths.response_body_post_oneof_complex_types_response_body_for_content_types.post import PostOneofComplexTypesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_request_body.post import PostOneofRequestBody +from unit_test_api.paths.response_body_post_oneof_response_body_for_content_types.post import PostOneofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_with_base_schema_request_body.post import PostOneofWithBaseSchemaRequestBody +from unit_test_api.paths.response_body_post_oneof_with_base_schema_response_body_for_content_types.post import PostOneofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_with_empty_schema_request_body.post import PostOneofWithEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_oneof_with_empty_schema_response_body_for_content_types.post import PostOneofWithEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_with_required_request_body.post import PostOneofWithRequiredRequestBody +from unit_test_api.paths.response_body_post_oneof_with_required_response_body_for_content_types.post import PostOneofWithRequiredResponseBodyForContentTypes + + +class OneOfApi( + PostNestedOneofToCheckValidationSemanticsRequestBody, + PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes, + PostOneofComplexTypesRequestBody, + PostOneofComplexTypesResponseBodyForContentTypes, + PostOneofRequestBody, + PostOneofResponseBodyForContentTypes, + PostOneofWithBaseSchemaRequestBody, + PostOneofWithBaseSchemaResponseBodyForContentTypes, + PostOneofWithEmptySchemaRequestBody, + PostOneofWithEmptySchemaResponseBodyForContentTypes, + PostOneofWithRequiredRequestBody, + PostOneofWithRequiredResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/operation_request_body_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/operation_request_body_api.py new file mode 100644 index 0000000000..2f64723d30 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/operation_request_body_api.py @@ -0,0 +1,195 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body.post import PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody +from unit_test_api.paths.request_body_post_additionalproperties_are_allowed_by_default_request_body.post import PostAdditionalpropertiesAreAllowedByDefaultRequestBody +from unit_test_api.paths.request_body_post_additionalproperties_can_exist_by_itself_request_body.post import PostAdditionalpropertiesCanExistByItselfRequestBody +from unit_test_api.paths.request_body_post_additionalproperties_should_not_look_in_applicators_request_body.post import PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody +from unit_test_api.paths.request_body_post_allof_combined_with_anyof_oneof_request_body.post import PostAllofCombinedWithAnyofOneofRequestBody +from unit_test_api.paths.request_body_post_allof_request_body.post import PostAllofRequestBody +from unit_test_api.paths.request_body_post_allof_simple_types_request_body.post import PostAllofSimpleTypesRequestBody +from unit_test_api.paths.request_body_post_allof_with_base_schema_request_body.post import PostAllofWithBaseSchemaRequestBody +from unit_test_api.paths.request_body_post_allof_with_one_empty_schema_request_body.post import PostAllofWithOneEmptySchemaRequestBody +from unit_test_api.paths.request_body_post_allof_with_the_first_empty_schema_request_body.post import PostAllofWithTheFirstEmptySchemaRequestBody +from unit_test_api.paths.request_body_post_allof_with_the_last_empty_schema_request_body.post import PostAllofWithTheLastEmptySchemaRequestBody +from unit_test_api.paths.request_body_post_allof_with_two_empty_schemas_request_body.post import PostAllofWithTwoEmptySchemasRequestBody +from unit_test_api.paths.request_body_post_anyof_complex_types_request_body.post import PostAnyofComplexTypesRequestBody +from unit_test_api.paths.request_body_post_anyof_request_body.post import PostAnyofRequestBody +from unit_test_api.paths.request_body_post_anyof_with_base_schema_request_body.post import PostAnyofWithBaseSchemaRequestBody +from unit_test_api.paths.request_body_post_anyof_with_one_empty_schema_request_body.post import PostAnyofWithOneEmptySchemaRequestBody +from unit_test_api.paths.request_body_post_array_type_matches_arrays_request_body.post import PostArrayTypeMatchesArraysRequestBody +from unit_test_api.paths.request_body_post_boolean_type_matches_booleans_request_body.post import PostBooleanTypeMatchesBooleansRequestBody +from unit_test_api.paths.request_body_post_by_int_request_body.post import PostByIntRequestBody +from unit_test_api.paths.request_body_post_by_number_request_body.post import PostByNumberRequestBody +from unit_test_api.paths.request_body_post_by_small_number_request_body.post import PostBySmallNumberRequestBody +from unit_test_api.paths.request_body_post_date_time_format_request_body.post import PostDateTimeFormatRequestBody +from unit_test_api.paths.request_body_post_email_format_request_body.post import PostEmailFormatRequestBody +from unit_test_api.paths.request_body_post_enum_with0_does_not_match_false_request_body.post import PostEnumWith0DoesNotMatchFalseRequestBody +from unit_test_api.paths.request_body_post_enum_with1_does_not_match_true_request_body.post import PostEnumWith1DoesNotMatchTrueRequestBody +from unit_test_api.paths.request_body_post_enum_with_escaped_characters_request_body.post import PostEnumWithEscapedCharactersRequestBody +from unit_test_api.paths.request_body_post_enum_with_false_does_not_match0_request_body.post import PostEnumWithFalseDoesNotMatch0RequestBody +from unit_test_api.paths.request_body_post_enum_with_true_does_not_match1_request_body.post import PostEnumWithTrueDoesNotMatch1RequestBody +from unit_test_api.paths.request_body_post_enums_in_properties_request_body.post import PostEnumsInPropertiesRequestBody +from unit_test_api.paths.request_body_post_forbidden_property_request_body.post import PostForbiddenPropertyRequestBody +from unit_test_api.paths.request_body_post_hostname_format_request_body.post import PostHostnameFormatRequestBody +from unit_test_api.paths.request_body_post_integer_type_matches_integers_request_body.post import PostIntegerTypeMatchesIntegersRequestBody +from unit_test_api.paths.request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.post import PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody +from unit_test_api.paths.request_body_post_invalid_string_value_for_default_request_body.post import PostInvalidStringValueForDefaultRequestBody +from unit_test_api.paths.request_body_post_ipv4_format_request_body.post import PostIpv4FormatRequestBody +from unit_test_api.paths.request_body_post_ipv6_format_request_body.post import PostIpv6FormatRequestBody +from unit_test_api.paths.request_body_post_json_pointer_format_request_body.post import PostJsonPointerFormatRequestBody +from unit_test_api.paths.request_body_post_maximum_validation_request_body.post import PostMaximumValidationRequestBody +from unit_test_api.paths.request_body_post_maximum_validation_with_unsigned_integer_request_body.post import PostMaximumValidationWithUnsignedIntegerRequestBody +from unit_test_api.paths.request_body_post_maxitems_validation_request_body.post import PostMaxitemsValidationRequestBody +from unit_test_api.paths.request_body_post_maxlength_validation_request_body.post import PostMaxlengthValidationRequestBody +from unit_test_api.paths.request_body_post_maxproperties0_means_the_object_is_empty_request_body.post import PostMaxproperties0MeansTheObjectIsEmptyRequestBody +from unit_test_api.paths.request_body_post_maxproperties_validation_request_body.post import PostMaxpropertiesValidationRequestBody +from unit_test_api.paths.request_body_post_minimum_validation_request_body.post import PostMinimumValidationRequestBody +from unit_test_api.paths.request_body_post_minimum_validation_with_signed_integer_request_body.post import PostMinimumValidationWithSignedIntegerRequestBody +from unit_test_api.paths.request_body_post_minitems_validation_request_body.post import PostMinitemsValidationRequestBody +from unit_test_api.paths.request_body_post_minlength_validation_request_body.post import PostMinlengthValidationRequestBody +from unit_test_api.paths.request_body_post_minproperties_validation_request_body.post import PostMinpropertiesValidationRequestBody +from unit_test_api.paths.request_body_post_nested_allof_to_check_validation_semantics_request_body.post import PostNestedAllofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.request_body_post_nested_anyof_to_check_validation_semantics_request_body.post import PostNestedAnyofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.request_body_post_nested_items_request_body.post import PostNestedItemsRequestBody +from unit_test_api.paths.request_body_post_nested_oneof_to_check_validation_semantics_request_body.post import PostNestedOneofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.request_body_post_not_more_complex_schema_request_body.post import PostNotMoreComplexSchemaRequestBody +from unit_test_api.paths.request_body_post_not_request_body.post import PostNotRequestBody +from unit_test_api.paths.request_body_post_nul_characters_in_strings_request_body.post import PostNulCharactersInStringsRequestBody +from unit_test_api.paths.request_body_post_null_type_matches_only_the_null_object_request_body.post import PostNullTypeMatchesOnlyTheNullObjectRequestBody +from unit_test_api.paths.request_body_post_number_type_matches_numbers_request_body.post import PostNumberTypeMatchesNumbersRequestBody +from unit_test_api.paths.request_body_post_object_properties_validation_request_body.post import PostObjectPropertiesValidationRequestBody +from unit_test_api.paths.request_body_post_object_type_matches_objects_request_body.post import PostObjectTypeMatchesObjectsRequestBody +from unit_test_api.paths.request_body_post_oneof_complex_types_request_body.post import PostOneofComplexTypesRequestBody +from unit_test_api.paths.request_body_post_oneof_request_body.post import PostOneofRequestBody +from unit_test_api.paths.request_body_post_oneof_with_base_schema_request_body.post import PostOneofWithBaseSchemaRequestBody +from unit_test_api.paths.request_body_post_oneof_with_empty_schema_request_body.post import PostOneofWithEmptySchemaRequestBody +from unit_test_api.paths.request_body_post_oneof_with_required_request_body.post import PostOneofWithRequiredRequestBody +from unit_test_api.paths.request_body_post_pattern_is_not_anchored_request_body.post import PostPatternIsNotAnchoredRequestBody +from unit_test_api.paths.request_body_post_pattern_validation_request_body.post import PostPatternValidationRequestBody +from unit_test_api.paths.request_body_post_properties_with_escaped_characters_request_body.post import PostPropertiesWithEscapedCharactersRequestBody +from unit_test_api.paths.request_body_post_property_named_ref_that_is_not_a_reference_request_body.post import PostPropertyNamedRefThatIsNotAReferenceRequestBody +from unit_test_api.paths.request_body_post_ref_in_additionalproperties_request_body.post import PostRefInAdditionalpropertiesRequestBody +from unit_test_api.paths.request_body_post_ref_in_allof_request_body.post import PostRefInAllofRequestBody +from unit_test_api.paths.request_body_post_ref_in_anyof_request_body.post import PostRefInAnyofRequestBody +from unit_test_api.paths.request_body_post_ref_in_items_request_body.post import PostRefInItemsRequestBody +from unit_test_api.paths.request_body_post_ref_in_not_request_body.post import PostRefInNotRequestBody +from unit_test_api.paths.request_body_post_ref_in_oneof_request_body.post import PostRefInOneofRequestBody +from unit_test_api.paths.request_body_post_ref_in_property_request_body.post import PostRefInPropertyRequestBody +from unit_test_api.paths.request_body_post_required_default_validation_request_body.post import PostRequiredDefaultValidationRequestBody +from unit_test_api.paths.request_body_post_required_validation_request_body.post import PostRequiredValidationRequestBody +from unit_test_api.paths.request_body_post_required_with_empty_array_request_body.post import PostRequiredWithEmptyArrayRequestBody +from unit_test_api.paths.request_body_post_required_with_escaped_characters_request_body.post import PostRequiredWithEscapedCharactersRequestBody +from unit_test_api.paths.request_body_post_simple_enum_validation_request_body.post import PostSimpleEnumValidationRequestBody +from unit_test_api.paths.request_body_post_string_type_matches_strings_request_body.post import PostStringTypeMatchesStringsRequestBody +from unit_test_api.paths.request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.post import PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody +from unit_test_api.paths.request_body_post_uniqueitems_false_validation_request_body.post import PostUniqueitemsFalseValidationRequestBody +from unit_test_api.paths.request_body_post_uniqueitems_validation_request_body.post import PostUniqueitemsValidationRequestBody +from unit_test_api.paths.request_body_post_uri_format_request_body.post import PostUriFormatRequestBody +from unit_test_api.paths.request_body_post_uri_reference_format_request_body.post import PostUriReferenceFormatRequestBody +from unit_test_api.paths.request_body_post_uri_template_format_request_body.post import PostUriTemplateFormatRequestBody + + +class OperationRequestBodyApi( + PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody, + PostAdditionalpropertiesAreAllowedByDefaultRequestBody, + PostAdditionalpropertiesCanExistByItselfRequestBody, + PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody, + PostAllofCombinedWithAnyofOneofRequestBody, + PostAllofRequestBody, + PostAllofSimpleTypesRequestBody, + PostAllofWithBaseSchemaRequestBody, + PostAllofWithOneEmptySchemaRequestBody, + PostAllofWithTheFirstEmptySchemaRequestBody, + PostAllofWithTheLastEmptySchemaRequestBody, + PostAllofWithTwoEmptySchemasRequestBody, + PostAnyofComplexTypesRequestBody, + PostAnyofRequestBody, + PostAnyofWithBaseSchemaRequestBody, + PostAnyofWithOneEmptySchemaRequestBody, + PostArrayTypeMatchesArraysRequestBody, + PostBooleanTypeMatchesBooleansRequestBody, + PostByIntRequestBody, + PostByNumberRequestBody, + PostBySmallNumberRequestBody, + PostDateTimeFormatRequestBody, + PostEmailFormatRequestBody, + PostEnumWith0DoesNotMatchFalseRequestBody, + PostEnumWith1DoesNotMatchTrueRequestBody, + PostEnumWithEscapedCharactersRequestBody, + PostEnumWithFalseDoesNotMatch0RequestBody, + PostEnumWithTrueDoesNotMatch1RequestBody, + PostEnumsInPropertiesRequestBody, + PostForbiddenPropertyRequestBody, + PostHostnameFormatRequestBody, + PostIntegerTypeMatchesIntegersRequestBody, + PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody, + PostInvalidStringValueForDefaultRequestBody, + PostIpv4FormatRequestBody, + PostIpv6FormatRequestBody, + PostJsonPointerFormatRequestBody, + PostMaximumValidationRequestBody, + PostMaximumValidationWithUnsignedIntegerRequestBody, + PostMaxitemsValidationRequestBody, + PostMaxlengthValidationRequestBody, + PostMaxproperties0MeansTheObjectIsEmptyRequestBody, + PostMaxpropertiesValidationRequestBody, + PostMinimumValidationRequestBody, + PostMinimumValidationWithSignedIntegerRequestBody, + PostMinitemsValidationRequestBody, + PostMinlengthValidationRequestBody, + PostMinpropertiesValidationRequestBody, + PostNestedAllofToCheckValidationSemanticsRequestBody, + PostNestedAnyofToCheckValidationSemanticsRequestBody, + PostNestedItemsRequestBody, + PostNestedOneofToCheckValidationSemanticsRequestBody, + PostNotMoreComplexSchemaRequestBody, + PostNotRequestBody, + PostNulCharactersInStringsRequestBody, + PostNullTypeMatchesOnlyTheNullObjectRequestBody, + PostNumberTypeMatchesNumbersRequestBody, + PostObjectPropertiesValidationRequestBody, + PostObjectTypeMatchesObjectsRequestBody, + PostOneofComplexTypesRequestBody, + PostOneofRequestBody, + PostOneofWithBaseSchemaRequestBody, + PostOneofWithEmptySchemaRequestBody, + PostOneofWithRequiredRequestBody, + PostPatternIsNotAnchoredRequestBody, + PostPatternValidationRequestBody, + PostPropertiesWithEscapedCharactersRequestBody, + PostPropertyNamedRefThatIsNotAReferenceRequestBody, + PostRefInAdditionalpropertiesRequestBody, + PostRefInAllofRequestBody, + PostRefInAnyofRequestBody, + PostRefInItemsRequestBody, + PostRefInNotRequestBody, + PostRefInOneofRequestBody, + PostRefInPropertyRequestBody, + PostRequiredDefaultValidationRequestBody, + PostRequiredValidationRequestBody, + PostRequiredWithEmptyArrayRequestBody, + PostRequiredWithEscapedCharactersRequestBody, + PostSimpleEnumValidationRequestBody, + PostStringTypeMatchesStringsRequestBody, + PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody, + PostUniqueitemsFalseValidationRequestBody, + PostUniqueitemsValidationRequestBody, + PostUriFormatRequestBody, + PostUriReferenceFormatRequestBody, + PostUriTemplateFormatRequestBody, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/path_post_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/path_post_api.py new file mode 100644 index 0000000000..3003735504 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/path_post_api.py @@ -0,0 +1,369 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body.post import PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.post import PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_additionalproperties_are_allowed_by_default_request_body.post import PostAdditionalpropertiesAreAllowedByDefaultRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types.post import PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_additionalproperties_can_exist_by_itself_request_body.post import PostAdditionalpropertiesCanExistByItselfRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types.post import PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_additionalproperties_should_not_look_in_applicators_request_body.post import PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody +from unit_test_api.paths.response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.post import PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_combined_with_anyof_oneof_request_body.post import PostAllofCombinedWithAnyofOneofRequestBody +from unit_test_api.paths.response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types.post import PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_request_body.post import PostAllofRequestBody +from unit_test_api.paths.response_body_post_allof_response_body_for_content_types.post import PostAllofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_simple_types_request_body.post import PostAllofSimpleTypesRequestBody +from unit_test_api.paths.response_body_post_allof_simple_types_response_body_for_content_types.post import PostAllofSimpleTypesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_base_schema_request_body.post import PostAllofWithBaseSchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_base_schema_response_body_for_content_types.post import PostAllofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_one_empty_schema_request_body.post import PostAllofWithOneEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_one_empty_schema_response_body_for_content_types.post import PostAllofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_the_first_empty_schema_request_body.post import PostAllofWithTheFirstEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types.post import PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_the_last_empty_schema_request_body.post import PostAllofWithTheLastEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types.post import PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_allof_with_two_empty_schemas_request_body.post import PostAllofWithTwoEmptySchemasRequestBody +from unit_test_api.paths.response_body_post_allof_with_two_empty_schemas_response_body_for_content_types.post import PostAllofWithTwoEmptySchemasResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_complex_types_request_body.post import PostAnyofComplexTypesRequestBody +from unit_test_api.paths.response_body_post_anyof_complex_types_response_body_for_content_types.post import PostAnyofComplexTypesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_request_body.post import PostAnyofRequestBody +from unit_test_api.paths.response_body_post_anyof_response_body_for_content_types.post import PostAnyofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_with_base_schema_request_body.post import PostAnyofWithBaseSchemaRequestBody +from unit_test_api.paths.response_body_post_anyof_with_base_schema_response_body_for_content_types.post import PostAnyofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_anyof_with_one_empty_schema_request_body.post import PostAnyofWithOneEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_anyof_with_one_empty_schema_response_body_for_content_types.post import PostAnyofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_array_type_matches_arrays_request_body.post import PostArrayTypeMatchesArraysRequestBody +from unit_test_api.paths.response_body_post_array_type_matches_arrays_response_body_for_content_types.post import PostArrayTypeMatchesArraysResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_boolean_type_matches_booleans_request_body.post import PostBooleanTypeMatchesBooleansRequestBody +from unit_test_api.paths.response_body_post_boolean_type_matches_booleans_response_body_for_content_types.post import PostBooleanTypeMatchesBooleansResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_by_int_request_body.post import PostByIntRequestBody +from unit_test_api.paths.response_body_post_by_int_response_body_for_content_types.post import PostByIntResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_by_number_request_body.post import PostByNumberRequestBody +from unit_test_api.paths.response_body_post_by_number_response_body_for_content_types.post import PostByNumberResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_by_small_number_request_body.post import PostBySmallNumberRequestBody +from unit_test_api.paths.response_body_post_by_small_number_response_body_for_content_types.post import PostBySmallNumberResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_date_time_format_request_body.post import PostDateTimeFormatRequestBody +from unit_test_api.paths.response_body_post_date_time_format_response_body_for_content_types.post import PostDateTimeFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_email_format_request_body.post import PostEmailFormatRequestBody +from unit_test_api.paths.response_body_post_email_format_response_body_for_content_types.post import PostEmailFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with0_does_not_match_false_request_body.post import PostEnumWith0DoesNotMatchFalseRequestBody +from unit_test_api.paths.response_body_post_enum_with0_does_not_match_false_response_body_for_content_types.post import PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with1_does_not_match_true_request_body.post import PostEnumWith1DoesNotMatchTrueRequestBody +from unit_test_api.paths.response_body_post_enum_with1_does_not_match_true_response_body_for_content_types.post import PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with_escaped_characters_request_body.post import PostEnumWithEscapedCharactersRequestBody +from unit_test_api.paths.response_body_post_enum_with_escaped_characters_response_body_for_content_types.post import PostEnumWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with_false_does_not_match0_request_body.post import PostEnumWithFalseDoesNotMatch0RequestBody +from unit_test_api.paths.response_body_post_enum_with_false_does_not_match0_response_body_for_content_types.post import PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enum_with_true_does_not_match1_request_body.post import PostEnumWithTrueDoesNotMatch1RequestBody +from unit_test_api.paths.response_body_post_enum_with_true_does_not_match1_response_body_for_content_types.post import PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_enums_in_properties_request_body.post import PostEnumsInPropertiesRequestBody +from unit_test_api.paths.response_body_post_enums_in_properties_response_body_for_content_types.post import PostEnumsInPropertiesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_forbidden_property_request_body.post import PostForbiddenPropertyRequestBody +from unit_test_api.paths.response_body_post_forbidden_property_response_body_for_content_types.post import PostForbiddenPropertyResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_hostname_format_request_body.post import PostHostnameFormatRequestBody +from unit_test_api.paths.response_body_post_hostname_format_response_body_for_content_types.post import PostHostnameFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_integer_type_matches_integers_request_body.post import PostIntegerTypeMatchesIntegersRequestBody +from unit_test_api.paths.response_body_post_integer_type_matches_integers_response_body_for_content_types.post import PostIntegerTypeMatchesIntegersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body.post import PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody +from unit_test_api.paths.response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.post import PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_invalid_string_value_for_default_request_body.post import PostInvalidStringValueForDefaultRequestBody +from unit_test_api.paths.response_body_post_invalid_string_value_for_default_response_body_for_content_types.post import PostInvalidStringValueForDefaultResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ipv4_format_request_body.post import PostIpv4FormatRequestBody +from unit_test_api.paths.response_body_post_ipv4_format_response_body_for_content_types.post import PostIpv4FormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ipv6_format_request_body.post import PostIpv6FormatRequestBody +from unit_test_api.paths.response_body_post_ipv6_format_response_body_for_content_types.post import PostIpv6FormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_json_pointer_format_request_body.post import PostJsonPointerFormatRequestBody +from unit_test_api.paths.response_body_post_json_pointer_format_response_body_for_content_types.post import PostJsonPointerFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maximum_validation_request_body.post import PostMaximumValidationRequestBody +from unit_test_api.paths.response_body_post_maximum_validation_response_body_for_content_types.post import PostMaximumValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maximum_validation_with_unsigned_integer_request_body.post import PostMaximumValidationWithUnsignedIntegerRequestBody +from unit_test_api.paths.response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types.post import PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maxitems_validation_request_body.post import PostMaxitemsValidationRequestBody +from unit_test_api.paths.response_body_post_maxitems_validation_response_body_for_content_types.post import PostMaxitemsValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maxlength_validation_request_body.post import PostMaxlengthValidationRequestBody +from unit_test_api.paths.response_body_post_maxlength_validation_response_body_for_content_types.post import PostMaxlengthValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maxproperties0_means_the_object_is_empty_request_body.post import PostMaxproperties0MeansTheObjectIsEmptyRequestBody +from unit_test_api.paths.response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.post import PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_maxproperties_validation_request_body.post import PostMaxpropertiesValidationRequestBody +from unit_test_api.paths.response_body_post_maxproperties_validation_response_body_for_content_types.post import PostMaxpropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minimum_validation_request_body.post import PostMinimumValidationRequestBody +from unit_test_api.paths.response_body_post_minimum_validation_response_body_for_content_types.post import PostMinimumValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minimum_validation_with_signed_integer_request_body.post import PostMinimumValidationWithSignedIntegerRequestBody +from unit_test_api.paths.response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types.post import PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minitems_validation_request_body.post import PostMinitemsValidationRequestBody +from unit_test_api.paths.response_body_post_minitems_validation_response_body_for_content_types.post import PostMinitemsValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minlength_validation_request_body.post import PostMinlengthValidationRequestBody +from unit_test_api.paths.response_body_post_minlength_validation_response_body_for_content_types.post import PostMinlengthValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_minproperties_validation_request_body.post import PostMinpropertiesValidationRequestBody +from unit_test_api.paths.response_body_post_minproperties_validation_response_body_for_content_types.post import PostMinpropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_allof_to_check_validation_semantics_request_body.post import PostNestedAllofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_anyof_to_check_validation_semantics_request_body.post import PostNestedAnyofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_items_request_body.post import PostNestedItemsRequestBody +from unit_test_api.paths.response_body_post_nested_items_response_body_for_content_types.post import PostNestedItemsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nested_oneof_to_check_validation_semantics_request_body.post import PostNestedOneofToCheckValidationSemanticsRequestBody +from unit_test_api.paths.response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_not_more_complex_schema_request_body.post import PostNotMoreComplexSchemaRequestBody +from unit_test_api.paths.response_body_post_not_more_complex_schema_response_body_for_content_types.post import PostNotMoreComplexSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_not_request_body.post import PostNotRequestBody +from unit_test_api.paths.response_body_post_not_response_body_for_content_types.post import PostNotResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_nul_characters_in_strings_request_body.post import PostNulCharactersInStringsRequestBody +from unit_test_api.paths.response_body_post_nul_characters_in_strings_response_body_for_content_types.post import PostNulCharactersInStringsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_null_type_matches_only_the_null_object_request_body.post import PostNullTypeMatchesOnlyTheNullObjectRequestBody +from unit_test_api.paths.response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types.post import PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_number_type_matches_numbers_request_body.post import PostNumberTypeMatchesNumbersRequestBody +from unit_test_api.paths.response_body_post_number_type_matches_numbers_response_body_for_content_types.post import PostNumberTypeMatchesNumbersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_object_properties_validation_request_body.post import PostObjectPropertiesValidationRequestBody +from unit_test_api.paths.response_body_post_object_properties_validation_response_body_for_content_types.post import PostObjectPropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_object_type_matches_objects_request_body.post import PostObjectTypeMatchesObjectsRequestBody +from unit_test_api.paths.response_body_post_object_type_matches_objects_response_body_for_content_types.post import PostObjectTypeMatchesObjectsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_complex_types_request_body.post import PostOneofComplexTypesRequestBody +from unit_test_api.paths.response_body_post_oneof_complex_types_response_body_for_content_types.post import PostOneofComplexTypesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_request_body.post import PostOneofRequestBody +from unit_test_api.paths.response_body_post_oneof_response_body_for_content_types.post import PostOneofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_with_base_schema_request_body.post import PostOneofWithBaseSchemaRequestBody +from unit_test_api.paths.response_body_post_oneof_with_base_schema_response_body_for_content_types.post import PostOneofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_with_empty_schema_request_body.post import PostOneofWithEmptySchemaRequestBody +from unit_test_api.paths.response_body_post_oneof_with_empty_schema_response_body_for_content_types.post import PostOneofWithEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_oneof_with_required_request_body.post import PostOneofWithRequiredRequestBody +from unit_test_api.paths.response_body_post_oneof_with_required_response_body_for_content_types.post import PostOneofWithRequiredResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_pattern_is_not_anchored_request_body.post import PostPatternIsNotAnchoredRequestBody +from unit_test_api.paths.response_body_post_pattern_is_not_anchored_response_body_for_content_types.post import PostPatternIsNotAnchoredResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_pattern_validation_request_body.post import PostPatternValidationRequestBody +from unit_test_api.paths.response_body_post_pattern_validation_response_body_for_content_types.post import PostPatternValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_properties_with_escaped_characters_request_body.post import PostPropertiesWithEscapedCharactersRequestBody +from unit_test_api.paths.response_body_post_properties_with_escaped_characters_response_body_for_content_types.post import PostPropertiesWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_property_named_ref_that_is_not_a_reference_request_body.post import PostPropertyNamedRefThatIsNotAReferenceRequestBody +from unit_test_api.paths.response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.post import PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_additionalproperties_request_body.post import PostRefInAdditionalpropertiesRequestBody +from unit_test_api.paths.response_body_post_ref_in_additionalproperties_response_body_for_content_types.post import PostRefInAdditionalpropertiesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_allof_request_body.post import PostRefInAllofRequestBody +from unit_test_api.paths.response_body_post_ref_in_allof_response_body_for_content_types.post import PostRefInAllofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_anyof_request_body.post import PostRefInAnyofRequestBody +from unit_test_api.paths.response_body_post_ref_in_anyof_response_body_for_content_types.post import PostRefInAnyofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_items_request_body.post import PostRefInItemsRequestBody +from unit_test_api.paths.response_body_post_ref_in_items_response_body_for_content_types.post import PostRefInItemsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_not_request_body.post import PostRefInNotRequestBody +from unit_test_api.paths.response_body_post_ref_in_not_response_body_for_content_types.post import PostRefInNotResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_oneof_request_body.post import PostRefInOneofRequestBody +from unit_test_api.paths.response_body_post_ref_in_oneof_response_body_for_content_types.post import PostRefInOneofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_property_request_body.post import PostRefInPropertyRequestBody +from unit_test_api.paths.response_body_post_ref_in_property_response_body_for_content_types.post import PostRefInPropertyResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_default_validation_request_body.post import PostRequiredDefaultValidationRequestBody +from unit_test_api.paths.response_body_post_required_default_validation_response_body_for_content_types.post import PostRequiredDefaultValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_validation_request_body.post import PostRequiredValidationRequestBody +from unit_test_api.paths.response_body_post_required_validation_response_body_for_content_types.post import PostRequiredValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_with_empty_array_request_body.post import PostRequiredWithEmptyArrayRequestBody +from unit_test_api.paths.response_body_post_required_with_empty_array_response_body_for_content_types.post import PostRequiredWithEmptyArrayResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_with_escaped_characters_request_body.post import PostRequiredWithEscapedCharactersRequestBody +from unit_test_api.paths.response_body_post_required_with_escaped_characters_response_body_for_content_types.post import PostRequiredWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_simple_enum_validation_request_body.post import PostSimpleEnumValidationRequestBody +from unit_test_api.paths.response_body_post_simple_enum_validation_response_body_for_content_types.post import PostSimpleEnumValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_string_type_matches_strings_request_body.post import PostStringTypeMatchesStringsRequestBody +from unit_test_api.paths.response_body_post_string_type_matches_strings_response_body_for_content_types.post import PostStringTypeMatchesStringsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body.post import PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody +from unit_test_api.paths.response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.post import PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uniqueitems_false_validation_request_body.post import PostUniqueitemsFalseValidationRequestBody +from unit_test_api.paths.response_body_post_uniqueitems_false_validation_response_body_for_content_types.post import PostUniqueitemsFalseValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uniqueitems_validation_request_body.post import PostUniqueitemsValidationRequestBody +from unit_test_api.paths.response_body_post_uniqueitems_validation_response_body_for_content_types.post import PostUniqueitemsValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uri_format_request_body.post import PostUriFormatRequestBody +from unit_test_api.paths.response_body_post_uri_format_response_body_for_content_types.post import PostUriFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uri_reference_format_request_body.post import PostUriReferenceFormatRequestBody +from unit_test_api.paths.response_body_post_uri_reference_format_response_body_for_content_types.post import PostUriReferenceFormatResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uri_template_format_request_body.post import PostUriTemplateFormatRequestBody +from unit_test_api.paths.response_body_post_uri_template_format_response_body_for_content_types.post import PostUriTemplateFormatResponseBodyForContentTypes + + +class PathPostApi( + PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody, + PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes, + PostAdditionalpropertiesAreAllowedByDefaultRequestBody, + PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes, + PostAdditionalpropertiesCanExistByItselfRequestBody, + PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes, + PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody, + PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes, + PostAllofCombinedWithAnyofOneofRequestBody, + PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes, + PostAllofRequestBody, + PostAllofResponseBodyForContentTypes, + PostAllofSimpleTypesRequestBody, + PostAllofSimpleTypesResponseBodyForContentTypes, + PostAllofWithBaseSchemaRequestBody, + PostAllofWithBaseSchemaResponseBodyForContentTypes, + PostAllofWithOneEmptySchemaRequestBody, + PostAllofWithOneEmptySchemaResponseBodyForContentTypes, + PostAllofWithTheFirstEmptySchemaRequestBody, + PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes, + PostAllofWithTheLastEmptySchemaRequestBody, + PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes, + PostAllofWithTwoEmptySchemasRequestBody, + PostAllofWithTwoEmptySchemasResponseBodyForContentTypes, + PostAnyofComplexTypesRequestBody, + PostAnyofComplexTypesResponseBodyForContentTypes, + PostAnyofRequestBody, + PostAnyofResponseBodyForContentTypes, + PostAnyofWithBaseSchemaRequestBody, + PostAnyofWithBaseSchemaResponseBodyForContentTypes, + PostAnyofWithOneEmptySchemaRequestBody, + PostAnyofWithOneEmptySchemaResponseBodyForContentTypes, + PostArrayTypeMatchesArraysRequestBody, + PostArrayTypeMatchesArraysResponseBodyForContentTypes, + PostBooleanTypeMatchesBooleansRequestBody, + PostBooleanTypeMatchesBooleansResponseBodyForContentTypes, + PostByIntRequestBody, + PostByIntResponseBodyForContentTypes, + PostByNumberRequestBody, + PostByNumberResponseBodyForContentTypes, + PostBySmallNumberRequestBody, + PostBySmallNumberResponseBodyForContentTypes, + PostDateTimeFormatRequestBody, + PostDateTimeFormatResponseBodyForContentTypes, + PostEmailFormatRequestBody, + PostEmailFormatResponseBodyForContentTypes, + PostEnumWith0DoesNotMatchFalseRequestBody, + PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes, + PostEnumWith1DoesNotMatchTrueRequestBody, + PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes, + PostEnumWithEscapedCharactersRequestBody, + PostEnumWithEscapedCharactersResponseBodyForContentTypes, + PostEnumWithFalseDoesNotMatch0RequestBody, + PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes, + PostEnumWithTrueDoesNotMatch1RequestBody, + PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes, + PostEnumsInPropertiesRequestBody, + PostEnumsInPropertiesResponseBodyForContentTypes, + PostForbiddenPropertyRequestBody, + PostForbiddenPropertyResponseBodyForContentTypes, + PostHostnameFormatRequestBody, + PostHostnameFormatResponseBodyForContentTypes, + PostIntegerTypeMatchesIntegersRequestBody, + PostIntegerTypeMatchesIntegersResponseBodyForContentTypes, + PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody, + PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes, + PostInvalidStringValueForDefaultRequestBody, + PostInvalidStringValueForDefaultResponseBodyForContentTypes, + PostIpv4FormatRequestBody, + PostIpv4FormatResponseBodyForContentTypes, + PostIpv6FormatRequestBody, + PostIpv6FormatResponseBodyForContentTypes, + PostJsonPointerFormatRequestBody, + PostJsonPointerFormatResponseBodyForContentTypes, + PostMaximumValidationRequestBody, + PostMaximumValidationResponseBodyForContentTypes, + PostMaximumValidationWithUnsignedIntegerRequestBody, + PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes, + PostMaxitemsValidationRequestBody, + PostMaxitemsValidationResponseBodyForContentTypes, + PostMaxlengthValidationRequestBody, + PostMaxlengthValidationResponseBodyForContentTypes, + PostMaxproperties0MeansTheObjectIsEmptyRequestBody, + PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes, + PostMaxpropertiesValidationRequestBody, + PostMaxpropertiesValidationResponseBodyForContentTypes, + PostMinimumValidationRequestBody, + PostMinimumValidationResponseBodyForContentTypes, + PostMinimumValidationWithSignedIntegerRequestBody, + PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes, + PostMinitemsValidationRequestBody, + PostMinitemsValidationResponseBodyForContentTypes, + PostMinlengthValidationRequestBody, + PostMinlengthValidationResponseBodyForContentTypes, + PostMinpropertiesValidationRequestBody, + PostMinpropertiesValidationResponseBodyForContentTypes, + PostNestedAllofToCheckValidationSemanticsRequestBody, + PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes, + PostNestedAnyofToCheckValidationSemanticsRequestBody, + PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes, + PostNestedItemsRequestBody, + PostNestedItemsResponseBodyForContentTypes, + PostNestedOneofToCheckValidationSemanticsRequestBody, + PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes, + PostNotMoreComplexSchemaRequestBody, + PostNotMoreComplexSchemaResponseBodyForContentTypes, + PostNotRequestBody, + PostNotResponseBodyForContentTypes, + PostNulCharactersInStringsRequestBody, + PostNulCharactersInStringsResponseBodyForContentTypes, + PostNullTypeMatchesOnlyTheNullObjectRequestBody, + PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes, + PostNumberTypeMatchesNumbersRequestBody, + PostNumberTypeMatchesNumbersResponseBodyForContentTypes, + PostObjectPropertiesValidationRequestBody, + PostObjectPropertiesValidationResponseBodyForContentTypes, + PostObjectTypeMatchesObjectsRequestBody, + PostObjectTypeMatchesObjectsResponseBodyForContentTypes, + PostOneofComplexTypesRequestBody, + PostOneofComplexTypesResponseBodyForContentTypes, + PostOneofRequestBody, + PostOneofResponseBodyForContentTypes, + PostOneofWithBaseSchemaRequestBody, + PostOneofWithBaseSchemaResponseBodyForContentTypes, + PostOneofWithEmptySchemaRequestBody, + PostOneofWithEmptySchemaResponseBodyForContentTypes, + PostOneofWithRequiredRequestBody, + PostOneofWithRequiredResponseBodyForContentTypes, + PostPatternIsNotAnchoredRequestBody, + PostPatternIsNotAnchoredResponseBodyForContentTypes, + PostPatternValidationRequestBody, + PostPatternValidationResponseBodyForContentTypes, + PostPropertiesWithEscapedCharactersRequestBody, + PostPropertiesWithEscapedCharactersResponseBodyForContentTypes, + PostPropertyNamedRefThatIsNotAReferenceRequestBody, + PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes, + PostRefInAdditionalpropertiesRequestBody, + PostRefInAdditionalpropertiesResponseBodyForContentTypes, + PostRefInAllofRequestBody, + PostRefInAllofResponseBodyForContentTypes, + PostRefInAnyofRequestBody, + PostRefInAnyofResponseBodyForContentTypes, + PostRefInItemsRequestBody, + PostRefInItemsResponseBodyForContentTypes, + PostRefInNotRequestBody, + PostRefInNotResponseBodyForContentTypes, + PostRefInOneofRequestBody, + PostRefInOneofResponseBodyForContentTypes, + PostRefInPropertyRequestBody, + PostRefInPropertyResponseBodyForContentTypes, + PostRequiredDefaultValidationRequestBody, + PostRequiredDefaultValidationResponseBodyForContentTypes, + PostRequiredValidationRequestBody, + PostRequiredValidationResponseBodyForContentTypes, + PostRequiredWithEmptyArrayRequestBody, + PostRequiredWithEmptyArrayResponseBodyForContentTypes, + PostRequiredWithEscapedCharactersRequestBody, + PostRequiredWithEscapedCharactersResponseBodyForContentTypes, + PostSimpleEnumValidationRequestBody, + PostSimpleEnumValidationResponseBodyForContentTypes, + PostStringTypeMatchesStringsRequestBody, + PostStringTypeMatchesStringsResponseBodyForContentTypes, + PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody, + PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes, + PostUniqueitemsFalseValidationRequestBody, + PostUniqueitemsFalseValidationResponseBodyForContentTypes, + PostUniqueitemsValidationRequestBody, + PostUniqueitemsValidationResponseBodyForContentTypes, + PostUriFormatRequestBody, + PostUriFormatResponseBodyForContentTypes, + PostUriReferenceFormatRequestBody, + PostUriReferenceFormatResponseBodyForContentTypes, + PostUriTemplateFormatRequestBody, + PostUriTemplateFormatResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/pattern_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/pattern_api.py new file mode 100644 index 0000000000..0e1e1dad2c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/pattern_api.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_pattern_is_not_anchored_request_body.post import PostPatternIsNotAnchoredRequestBody +from unit_test_api.paths.response_body_post_pattern_is_not_anchored_response_body_for_content_types.post import PostPatternIsNotAnchoredResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_pattern_validation_request_body.post import PostPatternValidationRequestBody +from unit_test_api.paths.response_body_post_pattern_validation_response_body_for_content_types.post import PostPatternValidationResponseBodyForContentTypes + + +class PatternApi( + PostPatternIsNotAnchoredRequestBody, + PostPatternIsNotAnchoredResponseBodyForContentTypes, + PostPatternValidationRequestBody, + PostPatternValidationResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/properties_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/properties_api.py new file mode 100644 index 0000000000..3514d13575 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/properties_api.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_object_properties_validation_request_body.post import PostObjectPropertiesValidationRequestBody +from unit_test_api.paths.response_body_post_object_properties_validation_response_body_for_content_types.post import PostObjectPropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_properties_with_escaped_characters_request_body.post import PostPropertiesWithEscapedCharactersRequestBody +from unit_test_api.paths.response_body_post_properties_with_escaped_characters_response_body_for_content_types.post import PostPropertiesWithEscapedCharactersResponseBodyForContentTypes + + +class PropertiesApi( + PostObjectPropertiesValidationRequestBody, + PostObjectPropertiesValidationResponseBodyForContentTypes, + PostPropertiesWithEscapedCharactersRequestBody, + PostPropertiesWithEscapedCharactersResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/ref_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/ref_api.py new file mode 100644 index 0000000000..7775cd1104 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/ref_api.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_property_named_ref_that_is_not_a_reference_request_body.post import PostPropertyNamedRefThatIsNotAReferenceRequestBody +from unit_test_api.paths.response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.post import PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_additionalproperties_request_body.post import PostRefInAdditionalpropertiesRequestBody +from unit_test_api.paths.response_body_post_ref_in_additionalproperties_response_body_for_content_types.post import PostRefInAdditionalpropertiesResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_allof_request_body.post import PostRefInAllofRequestBody +from unit_test_api.paths.response_body_post_ref_in_allof_response_body_for_content_types.post import PostRefInAllofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_anyof_request_body.post import PostRefInAnyofRequestBody +from unit_test_api.paths.response_body_post_ref_in_anyof_response_body_for_content_types.post import PostRefInAnyofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_items_request_body.post import PostRefInItemsRequestBody +from unit_test_api.paths.response_body_post_ref_in_items_response_body_for_content_types.post import PostRefInItemsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_not_request_body.post import PostRefInNotRequestBody +from unit_test_api.paths.response_body_post_ref_in_not_response_body_for_content_types.post import PostRefInNotResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_oneof_request_body.post import PostRefInOneofRequestBody +from unit_test_api.paths.response_body_post_ref_in_oneof_response_body_for_content_types.post import PostRefInOneofResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_ref_in_property_request_body.post import PostRefInPropertyRequestBody +from unit_test_api.paths.response_body_post_ref_in_property_response_body_for_content_types.post import PostRefInPropertyResponseBodyForContentTypes + + +class RefApi( + PostPropertyNamedRefThatIsNotAReferenceRequestBody, + PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes, + PostRefInAdditionalpropertiesRequestBody, + PostRefInAdditionalpropertiesResponseBodyForContentTypes, + PostRefInAllofRequestBody, + PostRefInAllofResponseBodyForContentTypes, + PostRefInAnyofRequestBody, + PostRefInAnyofResponseBodyForContentTypes, + PostRefInItemsRequestBody, + PostRefInItemsResponseBodyForContentTypes, + PostRefInNotRequestBody, + PostRefInNotResponseBodyForContentTypes, + PostRefInOneofRequestBody, + PostRefInOneofResponseBodyForContentTypes, + PostRefInPropertyRequestBody, + PostRefInPropertyResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/required_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/required_api.py new file mode 100644 index 0000000000..4ba23de087 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/required_api.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_required_default_validation_request_body.post import PostRequiredDefaultValidationRequestBody +from unit_test_api.paths.response_body_post_required_default_validation_response_body_for_content_types.post import PostRequiredDefaultValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_validation_request_body.post import PostRequiredValidationRequestBody +from unit_test_api.paths.response_body_post_required_validation_response_body_for_content_types.post import PostRequiredValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_with_empty_array_request_body.post import PostRequiredWithEmptyArrayRequestBody +from unit_test_api.paths.response_body_post_required_with_empty_array_response_body_for_content_types.post import PostRequiredWithEmptyArrayResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_required_with_escaped_characters_request_body.post import PostRequiredWithEscapedCharactersRequestBody +from unit_test_api.paths.response_body_post_required_with_escaped_characters_response_body_for_content_types.post import PostRequiredWithEscapedCharactersResponseBodyForContentTypes + + +class RequiredApi( + PostRequiredDefaultValidationRequestBody, + PostRequiredDefaultValidationResponseBodyForContentTypes, + PostRequiredValidationRequestBody, + PostRequiredValidationResponseBodyForContentTypes, + PostRequiredWithEmptyArrayRequestBody, + PostRequiredWithEmptyArrayResponseBodyForContentTypes, + PostRequiredWithEscapedCharactersRequestBody, + PostRequiredWithEscapedCharactersResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/response_content_content_type_schema_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/response_content_content_type_schema_api.py new file mode 100644 index 0000000000..0e0e47d3f8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/response_content_content_type_schema_api.py @@ -0,0 +1,195 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types.post import PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types.post import PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types.post import PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types.post import PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types.post import PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_allof_response_body_for_content_types.post import PostAllofResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_allof_simple_types_response_body_for_content_types.post import PostAllofSimpleTypesResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_allof_with_base_schema_response_body_for_content_types.post import PostAllofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_allof_with_one_empty_schema_response_body_for_content_types.post import PostAllofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types.post import PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types.post import PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_allof_with_two_empty_schemas_response_body_for_content_types.post import PostAllofWithTwoEmptySchemasResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_anyof_complex_types_response_body_for_content_types.post import PostAnyofComplexTypesResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_anyof_response_body_for_content_types.post import PostAnyofResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_anyof_with_base_schema_response_body_for_content_types.post import PostAnyofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_anyof_with_one_empty_schema_response_body_for_content_types.post import PostAnyofWithOneEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_array_type_matches_arrays_response_body_for_content_types.post import PostArrayTypeMatchesArraysResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_boolean_type_matches_booleans_response_body_for_content_types.post import PostBooleanTypeMatchesBooleansResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_by_int_response_body_for_content_types.post import PostByIntResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_by_number_response_body_for_content_types.post import PostByNumberResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_by_small_number_response_body_for_content_types.post import PostBySmallNumberResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_date_time_format_response_body_for_content_types.post import PostDateTimeFormatResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_email_format_response_body_for_content_types.post import PostEmailFormatResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_enum_with0_does_not_match_false_response_body_for_content_types.post import PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_enum_with1_does_not_match_true_response_body_for_content_types.post import PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_enum_with_escaped_characters_response_body_for_content_types.post import PostEnumWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_enum_with_false_does_not_match0_response_body_for_content_types.post import PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_enum_with_true_does_not_match1_response_body_for_content_types.post import PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_enums_in_properties_response_body_for_content_types.post import PostEnumsInPropertiesResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_forbidden_property_response_body_for_content_types.post import PostForbiddenPropertyResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_hostname_format_response_body_for_content_types.post import PostHostnameFormatResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_integer_type_matches_integers_response_body_for_content_types.post import PostIntegerTypeMatchesIntegersResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types.post import PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_invalid_string_value_for_default_response_body_for_content_types.post import PostInvalidStringValueForDefaultResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_ipv4_format_response_body_for_content_types.post import PostIpv4FormatResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_ipv6_format_response_body_for_content_types.post import PostIpv6FormatResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_json_pointer_format_response_body_for_content_types.post import PostJsonPointerFormatResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_maximum_validation_response_body_for_content_types.post import PostMaximumValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types.post import PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_maxitems_validation_response_body_for_content_types.post import PostMaxitemsValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_maxlength_validation_response_body_for_content_types.post import PostMaxlengthValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types.post import PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_maxproperties_validation_response_body_for_content_types.post import PostMaxpropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_minimum_validation_response_body_for_content_types.post import PostMinimumValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types.post import PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_minitems_validation_response_body_for_content_types.post import PostMinitemsValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_minlength_validation_response_body_for_content_types.post import PostMinlengthValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_minproperties_validation_response_body_for_content_types.post import PostMinpropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_nested_items_response_body_for_content_types.post import PostNestedItemsResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types.post import PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_not_more_complex_schema_response_body_for_content_types.post import PostNotMoreComplexSchemaResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_not_response_body_for_content_types.post import PostNotResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_nul_characters_in_strings_response_body_for_content_types.post import PostNulCharactersInStringsResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types.post import PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_number_type_matches_numbers_response_body_for_content_types.post import PostNumberTypeMatchesNumbersResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_object_properties_validation_response_body_for_content_types.post import PostObjectPropertiesValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_object_type_matches_objects_response_body_for_content_types.post import PostObjectTypeMatchesObjectsResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_oneof_complex_types_response_body_for_content_types.post import PostOneofComplexTypesResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_oneof_response_body_for_content_types.post import PostOneofResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_oneof_with_base_schema_response_body_for_content_types.post import PostOneofWithBaseSchemaResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_oneof_with_empty_schema_response_body_for_content_types.post import PostOneofWithEmptySchemaResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_oneof_with_required_response_body_for_content_types.post import PostOneofWithRequiredResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_pattern_is_not_anchored_response_body_for_content_types.post import PostPatternIsNotAnchoredResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_pattern_validation_response_body_for_content_types.post import PostPatternValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_properties_with_escaped_characters_response_body_for_content_types.post import PostPropertiesWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types.post import PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_ref_in_additionalproperties_response_body_for_content_types.post import PostRefInAdditionalpropertiesResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_ref_in_allof_response_body_for_content_types.post import PostRefInAllofResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_ref_in_anyof_response_body_for_content_types.post import PostRefInAnyofResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_ref_in_items_response_body_for_content_types.post import PostRefInItemsResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_ref_in_not_response_body_for_content_types.post import PostRefInNotResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_ref_in_oneof_response_body_for_content_types.post import PostRefInOneofResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_ref_in_property_response_body_for_content_types.post import PostRefInPropertyResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_required_default_validation_response_body_for_content_types.post import PostRequiredDefaultValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_required_validation_response_body_for_content_types.post import PostRequiredValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_required_with_empty_array_response_body_for_content_types.post import PostRequiredWithEmptyArrayResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_required_with_escaped_characters_response_body_for_content_types.post import PostRequiredWithEscapedCharactersResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_simple_enum_validation_response_body_for_content_types.post import PostSimpleEnumValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_string_type_matches_strings_response_body_for_content_types.post import PostStringTypeMatchesStringsResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types.post import PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_uniqueitems_false_validation_response_body_for_content_types.post import PostUniqueitemsFalseValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_uniqueitems_validation_response_body_for_content_types.post import PostUniqueitemsValidationResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_uri_format_response_body_for_content_types.post import PostUriFormatResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_uri_reference_format_response_body_for_content_types.post import PostUriReferenceFormatResponseBodyForContentTypes +from unit_test_api.paths.response_body_post_uri_template_format_response_body_for_content_types.post import PostUriTemplateFormatResponseBodyForContentTypes + + +class ResponseContentContentTypeSchemaApi( + PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes, + PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes, + PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes, + PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes, + PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes, + PostAllofResponseBodyForContentTypes, + PostAllofSimpleTypesResponseBodyForContentTypes, + PostAllofWithBaseSchemaResponseBodyForContentTypes, + PostAllofWithOneEmptySchemaResponseBodyForContentTypes, + PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes, + PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes, + PostAllofWithTwoEmptySchemasResponseBodyForContentTypes, + PostAnyofComplexTypesResponseBodyForContentTypes, + PostAnyofResponseBodyForContentTypes, + PostAnyofWithBaseSchemaResponseBodyForContentTypes, + PostAnyofWithOneEmptySchemaResponseBodyForContentTypes, + PostArrayTypeMatchesArraysResponseBodyForContentTypes, + PostBooleanTypeMatchesBooleansResponseBodyForContentTypes, + PostByIntResponseBodyForContentTypes, + PostByNumberResponseBodyForContentTypes, + PostBySmallNumberResponseBodyForContentTypes, + PostDateTimeFormatResponseBodyForContentTypes, + PostEmailFormatResponseBodyForContentTypes, + PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes, + PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes, + PostEnumWithEscapedCharactersResponseBodyForContentTypes, + PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes, + PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes, + PostEnumsInPropertiesResponseBodyForContentTypes, + PostForbiddenPropertyResponseBodyForContentTypes, + PostHostnameFormatResponseBodyForContentTypes, + PostIntegerTypeMatchesIntegersResponseBodyForContentTypes, + PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes, + PostInvalidStringValueForDefaultResponseBodyForContentTypes, + PostIpv4FormatResponseBodyForContentTypes, + PostIpv6FormatResponseBodyForContentTypes, + PostJsonPointerFormatResponseBodyForContentTypes, + PostMaximumValidationResponseBodyForContentTypes, + PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes, + PostMaxitemsValidationResponseBodyForContentTypes, + PostMaxlengthValidationResponseBodyForContentTypes, + PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes, + PostMaxpropertiesValidationResponseBodyForContentTypes, + PostMinimumValidationResponseBodyForContentTypes, + PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes, + PostMinitemsValidationResponseBodyForContentTypes, + PostMinlengthValidationResponseBodyForContentTypes, + PostMinpropertiesValidationResponseBodyForContentTypes, + PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes, + PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes, + PostNestedItemsResponseBodyForContentTypes, + PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes, + PostNotMoreComplexSchemaResponseBodyForContentTypes, + PostNotResponseBodyForContentTypes, + PostNulCharactersInStringsResponseBodyForContentTypes, + PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes, + PostNumberTypeMatchesNumbersResponseBodyForContentTypes, + PostObjectPropertiesValidationResponseBodyForContentTypes, + PostObjectTypeMatchesObjectsResponseBodyForContentTypes, + PostOneofComplexTypesResponseBodyForContentTypes, + PostOneofResponseBodyForContentTypes, + PostOneofWithBaseSchemaResponseBodyForContentTypes, + PostOneofWithEmptySchemaResponseBodyForContentTypes, + PostOneofWithRequiredResponseBodyForContentTypes, + PostPatternIsNotAnchoredResponseBodyForContentTypes, + PostPatternValidationResponseBodyForContentTypes, + PostPropertiesWithEscapedCharactersResponseBodyForContentTypes, + PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes, + PostRefInAdditionalpropertiesResponseBodyForContentTypes, + PostRefInAllofResponseBodyForContentTypes, + PostRefInAnyofResponseBodyForContentTypes, + PostRefInItemsResponseBodyForContentTypes, + PostRefInNotResponseBodyForContentTypes, + PostRefInOneofResponseBodyForContentTypes, + PostRefInPropertyResponseBodyForContentTypes, + PostRequiredDefaultValidationResponseBodyForContentTypes, + PostRequiredValidationResponseBodyForContentTypes, + PostRequiredWithEmptyArrayResponseBodyForContentTypes, + PostRequiredWithEscapedCharactersResponseBodyForContentTypes, + PostSimpleEnumValidationResponseBodyForContentTypes, + PostStringTypeMatchesStringsResponseBodyForContentTypes, + PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes, + PostUniqueitemsFalseValidationResponseBodyForContentTypes, + PostUniqueitemsValidationResponseBodyForContentTypes, + PostUriFormatResponseBodyForContentTypes, + PostUriReferenceFormatResponseBodyForContentTypes, + PostUriTemplateFormatResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/type_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/type_api.py new file mode 100644 index 0000000000..dbb518c1c0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/type_api.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_array_type_matches_arrays_request_body.post import PostArrayTypeMatchesArraysRequestBody +from unit_test_api.paths.response_body_post_array_type_matches_arrays_response_body_for_content_types.post import PostArrayTypeMatchesArraysResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_boolean_type_matches_booleans_request_body.post import PostBooleanTypeMatchesBooleansRequestBody +from unit_test_api.paths.response_body_post_boolean_type_matches_booleans_response_body_for_content_types.post import PostBooleanTypeMatchesBooleansResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_integer_type_matches_integers_request_body.post import PostIntegerTypeMatchesIntegersRequestBody +from unit_test_api.paths.response_body_post_integer_type_matches_integers_response_body_for_content_types.post import PostIntegerTypeMatchesIntegersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_null_type_matches_only_the_null_object_request_body.post import PostNullTypeMatchesOnlyTheNullObjectRequestBody +from unit_test_api.paths.response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types.post import PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_number_type_matches_numbers_request_body.post import PostNumberTypeMatchesNumbersRequestBody +from unit_test_api.paths.response_body_post_number_type_matches_numbers_response_body_for_content_types.post import PostNumberTypeMatchesNumbersResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_object_type_matches_objects_request_body.post import PostObjectTypeMatchesObjectsRequestBody +from unit_test_api.paths.response_body_post_object_type_matches_objects_response_body_for_content_types.post import PostObjectTypeMatchesObjectsResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_string_type_matches_strings_request_body.post import PostStringTypeMatchesStringsRequestBody +from unit_test_api.paths.response_body_post_string_type_matches_strings_response_body_for_content_types.post import PostStringTypeMatchesStringsResponseBodyForContentTypes + + +class TypeApi( + PostArrayTypeMatchesArraysRequestBody, + PostArrayTypeMatchesArraysResponseBodyForContentTypes, + PostBooleanTypeMatchesBooleansRequestBody, + PostBooleanTypeMatchesBooleansResponseBodyForContentTypes, + PostIntegerTypeMatchesIntegersRequestBody, + PostIntegerTypeMatchesIntegersResponseBodyForContentTypes, + PostNullTypeMatchesOnlyTheNullObjectRequestBody, + PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes, + PostNumberTypeMatchesNumbersRequestBody, + PostNumberTypeMatchesNumbersResponseBodyForContentTypes, + PostObjectTypeMatchesObjectsRequestBody, + PostObjectTypeMatchesObjectsResponseBodyForContentTypes, + PostStringTypeMatchesStringsRequestBody, + PostStringTypeMatchesStringsResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/unique_items_api.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/unique_items_api.py new file mode 100644 index 0000000000..820896d289 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/apis/tags/unique_items_api.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from unit_test_api.paths.request_body_post_uniqueitems_false_validation_request_body.post import PostUniqueitemsFalseValidationRequestBody +from unit_test_api.paths.response_body_post_uniqueitems_false_validation_response_body_for_content_types.post import PostUniqueitemsFalseValidationResponseBodyForContentTypes +from unit_test_api.paths.request_body_post_uniqueitems_validation_request_body.post import PostUniqueitemsValidationRequestBody +from unit_test_api.paths.response_body_post_uniqueitems_validation_response_body_for_content_types.post import PostUniqueitemsValidationResponseBodyForContentTypes + + +class UniqueItemsApi( + PostUniqueitemsFalseValidationRequestBody, + PostUniqueitemsFalseValidationResponseBodyForContentTypes, + PostUniqueitemsValidationRequestBody, + PostUniqueitemsValidationResponseBodyForContentTypes, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/configuration.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/configuration.py new file mode 100644 index 0000000000..ee4ca7e842 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/configuration.py @@ -0,0 +1,440 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +import copy +import logging +import multiprocessing +import sys +import urllib3 + +from http import client as http_client +from unit_test_api.exceptions import ApiValueError + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems', + 'uniqueItems', 'maxProperties', 'minProperties', +} + +class Configuration(object): + """NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param host: Base url + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer) + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication + :param password: Password for HTTP basic authentication + :param discard_unknown_keys: Boolean value indicating whether to discard + unknown properties. A server may send a response that includes additional + properties that are not known by the client in the following scenarios: + 1. The OpenAPI document is incomplete, i.e. it does not match the server + implementation. + 2. The client was generated using an older version of the OpenAPI document + and the server has been upgraded since then. + If a schema in the OpenAPI document defines the additionalProperties attribute, + then all undeclared properties received by the server are injected into the + additional properties map. In that case, there are undeclared properties, and + nothing to discard. + :param disabled_client_side_validations (string): Comma-separated list of + JSON schema validation keywords to disable JSON schema structural validation + rules. The following keywords may be specified: multipleOf, maximum, + exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, + maxItems, minItems. + By default, the validation is performed for data generated locally by the client + and data received from the server, independent of any validation performed by + the server side. If the input data does not satisfy the JSON schema validation + rules specified in the OpenAPI document, an exception is raised. + If disabled_client_side_validations is set, structural validation is + disabled. This can be useful to troubleshoot data validation problem, such as + when the OpenAPI document validation rules do not match the actual API data + received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. + + """ + + _default = None + + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + username=None, password=None, + discard_unknown_keys=False, + disabled_client_side_validations="", + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ): + """Constructor + """ + self._base_path = "https://someserver.com/v1" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.discard_unknown_keys = discard_unknown_keys + self.disabled_client_side_validations = disabled_client_side_validations + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("unit_test_api") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + self.debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = None + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = None + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + # Options to pass down to the underlying urllib3 socket + self.socket_options = None + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) + if name == 'disabled_client_side_validations': + s = set(filter(None, value.split(','))) + for v in s: + if v not in JSON_SCHEMA_VALIDATION_KEYWORDS: + raise ApiValueError( + "Invalid keyword: '{0}''".format(v)) + self._disabled_client_side_validations = s + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = copy.deepcopy(default) + + @classmethod + def get_default_copy(cls): + """Return new instance of configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration passed by the set_default method. + + :return: The configuration object. + """ + if cls._default is not None: + return copy.deepcopy(cls._default) + return Configuration() + + @property + def logger_file(self): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on http_client debug + http_client.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off http_client debug + http_client.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier, alias=None): + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth = {} + return auth + + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 0.0.1\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "https://someserver.com/v1", + 'description': "No description provided", + } + ] + + def get_host_from_settings(self, index, variables=None, servers=None): + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/exceptions.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/exceptions.py similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/exceptions.py rename to samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/exceptions.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/__init__.py similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/model/__init__.py rename to samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/__init__.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.py new file mode 100644 index 0000000000..66cc28eb41 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AdditionalpropertiesAllowsASchemaWhichShouldValidate( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + bar = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + "bar": bar, + } + additional_properties = schemas.BoolSchema + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> MetaOapg.additional_properties: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo"], typing_extensions.Literal["bar"], str, ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[MetaOapg.additional_properties, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo"], typing_extensions.Literal["bar"], str, ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + bar: typing.Union[MetaOapg.properties.bar, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'AdditionalpropertiesAllowsASchemaWhichShouldValidate': + return super().__new__( + cls, + *args, + foo=foo, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.pyi new file mode 100644 index 0000000000..66cc28eb41 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_allows_a_schema_which_should_validate.pyi @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AdditionalpropertiesAllowsASchemaWhichShouldValidate( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + bar = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + "bar": bar, + } + additional_properties = schemas.BoolSchema + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> MetaOapg.additional_properties: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo"], typing_extensions.Literal["bar"], str, ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[MetaOapg.additional_properties, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo"], typing_extensions.Literal["bar"], str, ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + bar: typing.Union[MetaOapg.properties.bar, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'AdditionalpropertiesAllowsASchemaWhichShouldValidate': + return super().__new__( + cls, + *args, + foo=foo, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_are_allowed_by_default.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_are_allowed_by_default.py new file mode 100644 index 0000000000..273766346b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_are_allowed_by_default.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AdditionalpropertiesAreAllowedByDefault( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + bar = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + "bar": bar, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + bar: typing.Union[MetaOapg.properties.bar, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AdditionalpropertiesAreAllowedByDefault': + return super().__new__( + cls, + *args, + foo=foo, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_are_allowed_by_default.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_are_allowed_by_default.pyi new file mode 100644 index 0000000000..273766346b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_are_allowed_by_default.pyi @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AdditionalpropertiesAreAllowedByDefault( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + bar = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + "bar": bar, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + bar: typing.Union[MetaOapg.properties.bar, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AdditionalpropertiesAreAllowedByDefault': + return super().__new__( + cls, + *args, + foo=foo, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_can_exist_by_itself.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_can_exist_by_itself.py new file mode 100644 index 0000000000..6f57c6b4e8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_can_exist_by_itself.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AdditionalpropertiesCanExistByItself( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + additional_properties = schemas.BoolSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'AdditionalpropertiesCanExistByItself': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_can_exist_by_itself.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_can_exist_by_itself.pyi new file mode 100644 index 0000000000..6f57c6b4e8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_can_exist_by_itself.pyi @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AdditionalpropertiesCanExistByItself( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + additional_properties = schemas.BoolSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'AdditionalpropertiesCanExistByItself': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_should_not_look_in_applicators.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_should_not_look_in_applicators.py new file mode 100644 index 0000000000..cabf9af560 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_should_not_look_in_applicators.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AdditionalpropertiesShouldNotLookInApplicators( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + additional_properties = schemas.BoolSchema + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'AdditionalpropertiesShouldNotLookInApplicators': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_should_not_look_in_applicators.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_should_not_look_in_applicators.pyi new file mode 100644 index 0000000000..cabf9af560 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/additionalproperties_should_not_look_in_applicators.pyi @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AdditionalpropertiesShouldNotLookInApplicators( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + additional_properties = schemas.BoolSchema + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'AdditionalpropertiesShouldNotLookInApplicators': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof.py new file mode 100644 index 0000000000..2e093c6cec --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof.py @@ -0,0 +1,177 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Allof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "bar", + } + + class properties: + bar = schemas.IntSchema + __annotations__ = { + "bar": bar, + } + + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Allof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof.pyi new file mode 100644 index 0000000000..2e093c6cec --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof.pyi @@ -0,0 +1,177 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Allof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "bar", + } + + class properties: + bar = schemas.IntSchema + __annotations__ = { + "bar": bar, + } + + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Allof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_combined_with_anyof_oneof.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_combined_with_anyof_oneof.py new file mode 100644 index 0000000000..e40aab43eb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_combined_with_anyof_oneof.py @@ -0,0 +1,161 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofCombinedWithAnyofOneof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + multiple_of = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + multiple_of = 5 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class any_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + multiple_of = 3 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + ] + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofCombinedWithAnyofOneof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_combined_with_anyof_oneof.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_combined_with_anyof_oneof.pyi new file mode 100644 index 0000000000..bc7e2eaf6b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_combined_with_anyof_oneof.pyi @@ -0,0 +1,158 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofCombinedWithAnyofOneof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class any_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + ] + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofCombinedWithAnyofOneof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_simple_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_simple_types.py new file mode 100644 index 0000000000..da2bd54477 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_simple_types.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofSimpleTypes( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + inclusive_maximum = 30 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + inclusive_minimum = 20 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofSimpleTypes': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_simple_types.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_simple_types.pyi new file mode 100644 index 0000000000..ce96198a3e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_simple_types.pyi @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofSimpleTypes( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofSimpleTypes': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_base_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_base_schema.py new file mode 100644 index 0000000000..6677ca50a7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_base_schema.py @@ -0,0 +1,211 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithBaseSchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "bar", + } + + class properties: + bar = schemas.IntSchema + __annotations__ = { + "bar": bar, + } + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "baz", + } + + class properties: + baz = schemas.NoneSchema + __annotations__ = { + "baz": baz, + } + + + baz: MetaOapg.properties.baz + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["baz"]) -> MetaOapg.properties.baz: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["baz", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["baz"]) -> MetaOapg.properties.baz: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["baz", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + baz: typing.Union[MetaOapg.properties.baz, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + baz=baz, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithBaseSchema': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_base_schema.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_base_schema.pyi new file mode 100644 index 0000000000..6677ca50a7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_base_schema.pyi @@ -0,0 +1,211 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithBaseSchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "bar", + } + + class properties: + bar = schemas.IntSchema + __annotations__ = { + "bar": bar, + } + + + class all_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "baz", + } + + class properties: + baz = schemas.NoneSchema + __annotations__ = { + "baz": baz, + } + + + baz: MetaOapg.properties.baz + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["baz"]) -> MetaOapg.properties.baz: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["baz", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["baz"]) -> MetaOapg.properties.baz: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["baz", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + baz: typing.Union[MetaOapg.properties.baz, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + baz=baz, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithBaseSchema': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_one_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_one_empty_schema.py new file mode 100644 index 0000000000..ccdf6237db --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_one_empty_schema.py @@ -0,0 +1,65 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithOneEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithOneEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_one_empty_schema.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_one_empty_schema.pyi new file mode 100644 index 0000000000..ccdf6237db --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_one_empty_schema.pyi @@ -0,0 +1,65 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithOneEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithOneEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_first_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_first_empty_schema.py new file mode 100644 index 0000000000..ca512486cf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_first_empty_schema.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithTheFirstEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + all_of_1 = schemas.NumberSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithTheFirstEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_first_empty_schema.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_first_empty_schema.pyi new file mode 100644 index 0000000000..ca512486cf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_first_empty_schema.pyi @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithTheFirstEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + all_of_1 = schemas.NumberSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithTheFirstEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_last_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_last_empty_schema.py new file mode 100644 index 0000000000..d243c83104 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_last_empty_schema.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithTheLastEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.NumberSchema + all_of_1 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithTheLastEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_last_empty_schema.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_last_empty_schema.pyi new file mode 100644 index 0000000000..d243c83104 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_the_last_empty_schema.pyi @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithTheLastEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.NumberSchema + all_of_1 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithTheLastEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_two_empty_schemas.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_two_empty_schemas.py new file mode 100644 index 0000000000..0ee8f8a324 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_two_empty_schemas.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithTwoEmptySchemas( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + all_of_1 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithTwoEmptySchemas': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_two_empty_schemas.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_two_empty_schemas.pyi new file mode 100644 index 0000000000..0ee8f8a324 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/allof_with_two_empty_schemas.pyi @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AllofWithTwoEmptySchemas( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + all_of_1 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AllofWithTwoEmptySchemas': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof.py new file mode 100644 index 0000000000..fe69e48143 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Anyof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + any_of_0 = schemas.IntSchema + + + class any_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + inclusive_minimum = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Anyof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof.pyi new file mode 100644 index 0000000000..d2bf4a03d2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof.pyi @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Anyof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + any_of_0 = schemas.IntSchema + + + class any_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Anyof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_complex_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_complex_types.py new file mode 100644 index 0000000000..6e0b801eef --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_complex_types.py @@ -0,0 +1,177 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AnyofComplexTypes( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class any_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "bar", + } + + class properties: + bar = schemas.IntSchema + __annotations__ = { + "bar": bar, + } + + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_0': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) + + + class any_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_1': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AnyofComplexTypes': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_complex_types.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_complex_types.pyi new file mode 100644 index 0000000000..6e0b801eef --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_complex_types.pyi @@ -0,0 +1,177 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AnyofComplexTypes( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class any_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "bar", + } + + class properties: + bar = schemas.IntSchema + __annotations__ = { + "bar": bar, + } + + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_0': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) + + + class any_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_1': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AnyofComplexTypes': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_base_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_base_schema.py new file mode 100644 index 0000000000..a310a33c9d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_base_schema.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AnyofWithBaseSchema( + schemas.ComposedBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class any_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + max_length = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class any_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + min_length = 4 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'AnyofWithBaseSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_base_schema.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_base_schema.pyi new file mode 100644 index 0000000000..65862600d5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_base_schema.pyi @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AnyofWithBaseSchema( + schemas.ComposedBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class any_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class any_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'AnyofWithBaseSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_one_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_one_empty_schema.py new file mode 100644 index 0000000000..117c0374aa --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_one_empty_schema.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AnyofWithOneEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + any_of_0 = schemas.NumberSchema + any_of_1 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AnyofWithOneEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_one_empty_schema.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_one_empty_schema.pyi new file mode 100644 index 0000000000..117c0374aa --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/anyof_with_one_empty_schema.pyi @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class AnyofWithOneEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + any_of_0 = schemas.NumberSchema + any_of_1 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AnyofWithOneEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/array_type_matches_arrays.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/array_type_matches_arrays.py new file mode 100644 index 0000000000..7c6cc33a3d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/array_type_matches_arrays.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ArrayTypeMatchesArrays( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayTypeMatchesArrays': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/array_type_matches_arrays.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/array_type_matches_arrays.pyi new file mode 100644 index 0000000000..7c6cc33a3d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/array_type_matches_arrays.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ArrayTypeMatchesArrays( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayTypeMatchesArrays': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/boolean_type_matches_booleans.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/boolean_type_matches_booleans.py new file mode 100644 index 0000000000..8e9d55f91a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/boolean_type_matches_booleans.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +BooleanTypeMatchesBooleans = schemas.BoolSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/boolean_type_matches_booleans.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/boolean_type_matches_booleans.pyi new file mode 100644 index 0000000000..8e9d55f91a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/boolean_type_matches_booleans.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +BooleanTypeMatchesBooleans = schemas.BoolSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_int.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_int.py new file mode 100644 index 0000000000..76988d6593 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_int.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ByInt( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + multiple_of = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ByInt': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_int.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_int.pyi new file mode 100644 index 0000000000..d93f787d68 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_int.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ByInt( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ByInt': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_number.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_number.py new file mode 100644 index 0000000000..184acb97b7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_number.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ByNumber( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + multiple_of = 1.5 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ByNumber': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_number.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_number.pyi new file mode 100644 index 0000000000..1a082d5d3e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_number.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ByNumber( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ByNumber': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_small_number.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_small_number.py new file mode 100644 index 0000000000..426ee59b91 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_small_number.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class BySmallNumber( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + multiple_of = 0.00010 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'BySmallNumber': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_small_number.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_small_number.pyi new file mode 100644 index 0000000000..95da8644ea --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/by_small_number.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class BySmallNumber( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'BySmallNumber': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/date_time_format.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/date_time_format.py new file mode 100644 index 0000000000..9fed78c490 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/date_time_format.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class DateTimeFormat( + schemas.DateTimeBase, + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'DateTimeFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/date_time_format.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/date_time_format.pyi new file mode 100644 index 0000000000..9fed78c490 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/date_time_format.pyi @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class DateTimeFormat( + schemas.DateTimeBase, + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'DateTimeFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/email_format.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/email_format.py new file mode 100644 index 0000000000..8a3fa4bbab --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/email_format.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EmailFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'email' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EmailFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/email_format.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/email_format.pyi new file mode 100644 index 0000000000..8a3fa4bbab --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/email_format.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EmailFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'email' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EmailFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with0_does_not_match_false.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with0_does_not_match_false.py new file mode 100644 index 0000000000..2f77c5996f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with0_does_not_match_false.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWith0DoesNotMatchFalse( + schemas.EnumBase, + schemas.NumberSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + 0: "POSITIVE_0", + } + + @schemas.classproperty + def POSITIVE_0(cls): + return cls(0) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with0_does_not_match_false.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with0_does_not_match_false.pyi new file mode 100644 index 0000000000..337edc4956 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with0_does_not_match_false.pyi @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWith0DoesNotMatchFalse( + schemas.EnumBase, + schemas.NumberSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def POSITIVE_0(cls): + return cls(0) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with1_does_not_match_true.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with1_does_not_match_true.py new file mode 100644 index 0000000000..2acbb376d6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with1_does_not_match_true.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWith1DoesNotMatchTrue( + schemas.EnumBase, + schemas.NumberSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + 1: "POSITIVE_1", + } + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with1_does_not_match_true.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with1_does_not_match_true.pyi new file mode 100644 index 0000000000..8664a7f747 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with1_does_not_match_true.pyi @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWith1DoesNotMatchTrue( + schemas.EnumBase, + schemas.NumberSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_escaped_characters.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_escaped_characters.py new file mode 100644 index 0000000000..c8f68c1000 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_escaped_characters.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWithEscapedCharacters( + schemas.EnumBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + "foo\nbar": "FOO_BAR", + "foo\rbar": "FOO_BAR", + } + + @schemas.classproperty + def FOO_BAR(cls): + return cls("foo\nbar") + + @schemas.classproperty + def FOO_BAR(cls): + return cls("foo\rbar") diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_escaped_characters.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_escaped_characters.pyi new file mode 100644 index 0000000000..6fb1827e44 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_escaped_characters.pyi @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWithEscapedCharacters( + schemas.EnumBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def FOO_BAR(cls): + return cls("foo\nbar") + + @schemas.classproperty + def FOO_BAR(cls): + return cls("foo\rbar") diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_false_does_not_match0.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_false_does_not_match0.py new file mode 100644 index 0000000000..c4992b57a3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_false_does_not_match0.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWithFalseDoesNotMatch0( + schemas.EnumBase, + schemas.BoolSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + schemas.BoolClass.FALSE: "FALSE", + } + + @schemas.classproperty + def FALSE(cls): + return cls(False) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_false_does_not_match0.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_false_does_not_match0.pyi new file mode 100644 index 0000000000..35ef43076c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_false_does_not_match0.pyi @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWithFalseDoesNotMatch0( + schemas.EnumBase, + schemas.BoolSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def FALSE(cls): + return cls(False) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_true_does_not_match1.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_true_does_not_match1.py new file mode 100644 index 0000000000..a8e8074710 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_true_does_not_match1.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWithTrueDoesNotMatch1( + schemas.EnumBase, + schemas.BoolSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + schemas.BoolClass.TRUE: "TRUE", + } + + @schemas.classproperty + def TRUE(cls): + return cls(True) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_true_does_not_match1.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_true_does_not_match1.pyi new file mode 100644 index 0000000000..f86fc0d281 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enum_with_true_does_not_match1.pyi @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumWithTrueDoesNotMatch1( + schemas.EnumBase, + schemas.BoolSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def TRUE(cls): + return cls(True) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enums_in_properties.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enums_in_properties.py new file mode 100644 index 0000000000..0010f712ab --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enums_in_properties.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumsInProperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "bar", + } + + class properties: + + + class bar( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "bar": "BAR", + } + + @schemas.classproperty + def BAR(cls): + return cls("bar") + + + class foo( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "foo": "FOO", + } + + @schemas.classproperty + def FOO(cls): + return cls("foo") + __annotations__ = { + "bar": bar, + "foo": foo, + } + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", "foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", "foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + bar: typing.Union[MetaOapg.properties.bar, str, ], + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EnumsInProperties': + return super().__new__( + cls, + *args, + bar=bar, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enums_in_properties.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enums_in_properties.pyi new file mode 100644 index 0000000000..d45a82aad0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/enums_in_properties.pyi @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class EnumsInProperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "bar", + } + + class properties: + + + class bar( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def BAR(cls): + return cls("bar") + + + class foo( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def FOO(cls): + return cls("foo") + __annotations__ = { + "bar": bar, + "foo": foo, + } + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", "foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", "foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + bar: typing.Union[MetaOapg.properties.bar, str, ], + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EnumsInProperties': + return super().__new__( + cls, + *args, + bar=bar, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/forbidden_property.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/forbidden_property.py new file mode 100644 index 0000000000..b81f17e5b1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/forbidden_property.py @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ForbiddenProperty( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.NotAnyTypeSchema + __annotations__ = { + "foo": foo, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ForbiddenProperty': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/forbidden_property.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/forbidden_property.pyi new file mode 100644 index 0000000000..b81f17e5b1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/forbidden_property.pyi @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ForbiddenProperty( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.NotAnyTypeSchema + __annotations__ = { + "foo": foo, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ForbiddenProperty': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/hostname_format.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/hostname_format.py new file mode 100644 index 0000000000..40942f67b8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/hostname_format.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class HostnameFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'hostname' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'HostnameFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/hostname_format.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/hostname_format.pyi new file mode 100644 index 0000000000..40942f67b8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/hostname_format.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class HostnameFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'hostname' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'HostnameFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/integer_type_matches_integers.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/integer_type_matches_integers.py new file mode 100644 index 0000000000..ccb986ac46 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/integer_type_matches_integers.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +IntegerTypeMatchesIntegers = schemas.IntSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/integer_type_matches_integers.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/integer_type_matches_integers.pyi new file mode 100644 index 0000000000..ccb986ac46 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/integer_type_matches_integers.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +IntegerTypeMatchesIntegers = schemas.IntSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.py new file mode 100644 index 0000000000..3f5ff42395 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf( + schemas.IntSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + multiple_of = 0.123456789 diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.pyi new file mode 100644 index 0000000000..33c88d1040 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_instance_should_not_raise_error_when_float_division_inf.pyi @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf( + schemas.IntSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_string_value_for_default.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_string_value_for_default.py new file mode 100644 index 0000000000..4752986369 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_string_value_for_default.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class InvalidStringValueForDefault( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class bar( + schemas.StrSchema + ): + + + class MetaOapg: + min_length = 4 + __annotations__ = { + "bar": bar, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'InvalidStringValueForDefault': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_string_value_for_default.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_string_value_for_default.pyi new file mode 100644 index 0000000000..7ab2145d29 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/invalid_string_value_for_default.pyi @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class InvalidStringValueForDefault( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class bar( + schemas.StrSchema + ): + pass + __annotations__ = { + "bar": bar, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'InvalidStringValueForDefault': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv4_format.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv4_format.py new file mode 100644 index 0000000000..0eae025a87 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv4_format.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Ipv4Format( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'ipv4' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Ipv4Format': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv4_format.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv4_format.pyi new file mode 100644 index 0000000000..0eae025a87 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv4_format.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Ipv4Format( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'ipv4' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Ipv4Format': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv6_format.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv6_format.py new file mode 100644 index 0000000000..23a8aa658d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv6_format.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Ipv6Format( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'ipv6' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Ipv6Format': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv6_format.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv6_format.pyi new file mode 100644 index 0000000000..23a8aa658d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ipv6_format.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Ipv6Format( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'ipv6' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Ipv6Format': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/json_pointer_format.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/json_pointer_format.py new file mode 100644 index 0000000000..ddbc508423 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/json_pointer_format.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class JsonPointerFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'json-pointer' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'JsonPointerFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/json_pointer_format.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/json_pointer_format.pyi new file mode 100644 index 0000000000..ddbc508423 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/json_pointer_format.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class JsonPointerFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'json-pointer' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'JsonPointerFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation.py new file mode 100644 index 0000000000..5a992b87f0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaximumValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + inclusive_maximum = 3.0 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaximumValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation.pyi new file mode 100644 index 0000000000..f0f3010b94 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaximumValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaximumValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation_with_unsigned_integer.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation_with_unsigned_integer.py new file mode 100644 index 0000000000..dc28bf37f3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation_with_unsigned_integer.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaximumValidationWithUnsignedInteger( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + inclusive_maximum = 300 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaximumValidationWithUnsignedInteger': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation_with_unsigned_integer.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation_with_unsigned_integer.pyi new file mode 100644 index 0000000000..223cf29f83 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maximum_validation_with_unsigned_integer.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaximumValidationWithUnsignedInteger( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaximumValidationWithUnsignedInteger': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxitems_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxitems_validation.py new file mode 100644 index 0000000000..de40bec0b0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxitems_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaxitemsValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + max_items = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaxitemsValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxitems_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxitems_validation.pyi new file mode 100644 index 0000000000..7c0a10e4fb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxitems_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaxitemsValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaxitemsValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxlength_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxlength_validation.py new file mode 100644 index 0000000000..c34f02ea11 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxlength_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaxlengthValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + max_length = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaxlengthValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxlength_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxlength_validation.pyi new file mode 100644 index 0000000000..1ed6a96b36 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxlength_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaxlengthValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaxlengthValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties0_means_the_object_is_empty.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties0_means_the_object_is_empty.py new file mode 100644 index 0000000000..24dd02220f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties0_means_the_object_is_empty.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Maxproperties0MeansTheObjectIsEmpty( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + max_properties = 0 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Maxproperties0MeansTheObjectIsEmpty': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties0_means_the_object_is_empty.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties0_means_the_object_is_empty.pyi new file mode 100644 index 0000000000..82013206b8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties0_means_the_object_is_empty.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Maxproperties0MeansTheObjectIsEmpty( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Maxproperties0MeansTheObjectIsEmpty': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties_validation.py new file mode 100644 index 0000000000..2adf12f750 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaxpropertiesValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + max_properties = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaxpropertiesValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties_validation.pyi new file mode 100644 index 0000000000..4252e69a43 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/maxproperties_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MaxpropertiesValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MaxpropertiesValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation.py new file mode 100644 index 0000000000..6409f72d48 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinimumValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + inclusive_minimum = 1.1 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinimumValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation.pyi new file mode 100644 index 0000000000..a96f7db6e3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinimumValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinimumValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation_with_signed_integer.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation_with_signed_integer.py new file mode 100644 index 0000000000..73e0b2613d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation_with_signed_integer.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinimumValidationWithSignedInteger( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + inclusive_minimum = -2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinimumValidationWithSignedInteger': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation_with_signed_integer.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation_with_signed_integer.pyi new file mode 100644 index 0000000000..c57929021a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minimum_validation_with_signed_integer.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinimumValidationWithSignedInteger( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinimumValidationWithSignedInteger': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minitems_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minitems_validation.py new file mode 100644 index 0000000000..2ae9925d45 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minitems_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinitemsValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + min_items = 1 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinitemsValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minitems_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minitems_validation.pyi new file mode 100644 index 0000000000..d84e653cfc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minitems_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinitemsValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinitemsValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minlength_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minlength_validation.py new file mode 100644 index 0000000000..acd0d6d892 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minlength_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinlengthValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + min_length = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinlengthValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minlength_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minlength_validation.pyi new file mode 100644 index 0000000000..7e633c88ee --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minlength_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinlengthValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinlengthValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minproperties_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minproperties_validation.py new file mode 100644 index 0000000000..ebc2b1db51 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minproperties_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinpropertiesValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + min_properties = 1 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinpropertiesValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minproperties_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minproperties_validation.pyi new file mode 100644 index 0000000000..ea06a20b31 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/minproperties_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class MinpropertiesValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MinpropertiesValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/model_not.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/model_not.py new file mode 100644 index 0000000000..317bddb0d8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/model_not.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ModelNot( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + not_schema = schemas.IntSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ModelNot': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/model_not.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/model_not.pyi new file mode 100644 index 0000000000..317bddb0d8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/model_not.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ModelNot( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + not_schema = schemas.IntSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ModelNot': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_allof_to_check_validation_semantics.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_allof_to_check_validation_semantics.py new file mode 100644 index 0000000000..f6f8069357 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_allof_to_check_validation_semantics.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NestedAllofToCheckValidationSemantics( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.ComposedSchema, + ): + + + class MetaOapg: + all_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NestedAllofToCheckValidationSemantics': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_allof_to_check_validation_semantics.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_allof_to_check_validation_semantics.pyi new file mode 100644 index 0000000000..f6f8069357 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_allof_to_check_validation_semantics.pyi @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NestedAllofToCheckValidationSemantics( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.ComposedSchema, + ): + + + class MetaOapg: + all_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NestedAllofToCheckValidationSemantics': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_anyof_to_check_validation_semantics.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_anyof_to_check_validation_semantics.py new file mode 100644 index 0000000000..65ae3adef0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_anyof_to_check_validation_semantics.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NestedAnyofToCheckValidationSemantics( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class any_of_0( + schemas.ComposedSchema, + ): + + + class MetaOapg: + any_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NestedAnyofToCheckValidationSemantics': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_anyof_to_check_validation_semantics.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_anyof_to_check_validation_semantics.pyi new file mode 100644 index 0000000000..65ae3adef0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_anyof_to_check_validation_semantics.pyi @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NestedAnyofToCheckValidationSemantics( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class any_of_0( + schemas.ComposedSchema, + ): + + + class MetaOapg: + any_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'any_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NestedAnyofToCheckValidationSemantics': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_items.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_items.py new file mode 100644 index 0000000000..36f1aad97f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_items.py @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NestedItems( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.NumberSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'NestedItems': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_items.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_items.pyi new file mode 100644 index 0000000000..36f1aad97f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_items.pyi @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NestedItems( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.NumberSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'NestedItems': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_oneof_to_check_validation_semantics.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_oneof_to_check_validation_semantics.py new file mode 100644 index 0000000000..ebede9469d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_oneof_to_check_validation_semantics.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NestedOneofToCheckValidationSemantics( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class one_of_0( + schemas.ComposedSchema, + ): + + + class MetaOapg: + one_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NestedOneofToCheckValidationSemantics': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_oneof_to_check_validation_semantics.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_oneof_to_check_validation_semantics.pyi new file mode 100644 index 0000000000..ebede9469d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nested_oneof_to_check_validation_semantics.pyi @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NestedOneofToCheckValidationSemantics( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class one_of_0( + schemas.ComposedSchema, + ): + + + class MetaOapg: + one_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NestedOneofToCheckValidationSemantics': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/not_more_complex_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/not_more_complex_schema.py new file mode 100644 index 0000000000..f04fa2d4d9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/not_more_complex_schema.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NotMoreComplexSchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class not_schema( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'not_schema': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NotMoreComplexSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/not_more_complex_schema.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/not_more_complex_schema.pyi new file mode 100644 index 0000000000..f04fa2d4d9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/not_more_complex_schema.pyi @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NotMoreComplexSchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class not_schema( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'not_schema': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NotMoreComplexSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nul_characters_in_strings.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nul_characters_in_strings.py new file mode 100644 index 0000000000..3aa6a9fe9b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nul_characters_in_strings.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NulCharactersInStrings( + schemas.EnumBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + "hello\x00there": "HELLOTHERE", + } + + @schemas.classproperty + def HELLOTHERE(cls): + return cls("hello\x00there") diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nul_characters_in_strings.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nul_characters_in_strings.pyi new file mode 100644 index 0000000000..eb9d42800c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/nul_characters_in_strings.pyi @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class NulCharactersInStrings( + schemas.EnumBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def HELLOTHERE(cls): + return cls("hello\x00there") diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/null_type_matches_only_the_null_object.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/null_type_matches_only_the_null_object.py new file mode 100644 index 0000000000..4b1bff62a1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/null_type_matches_only_the_null_object.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +NullTypeMatchesOnlyTheNullObject = schemas.NoneSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/null_type_matches_only_the_null_object.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/null_type_matches_only_the_null_object.pyi new file mode 100644 index 0000000000..4b1bff62a1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/null_type_matches_only_the_null_object.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +NullTypeMatchesOnlyTheNullObject = schemas.NoneSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/number_type_matches_numbers.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/number_type_matches_numbers.py new file mode 100644 index 0000000000..e4d1d79b97 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/number_type_matches_numbers.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +NumberTypeMatchesNumbers = schemas.NumberSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/number_type_matches_numbers.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/number_type_matches_numbers.pyi new file mode 100644 index 0000000000..e4d1d79b97 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/number_type_matches_numbers.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +NumberTypeMatchesNumbers = schemas.NumberSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/object_properties_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/object_properties_validation.py new file mode 100644 index 0000000000..d74b394f06 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/object_properties_validation.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ObjectPropertiesValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.IntSchema + bar = schemas.StrSchema + __annotations__ = { + "foo": foo, + "bar": bar, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, decimal.Decimal, int, schemas.Unset] = schemas.unset, + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectPropertiesValidation': + return super().__new__( + cls, + *args, + foo=foo, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/object_properties_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/object_properties_validation.pyi new file mode 100644 index 0000000000..d74b394f06 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/object_properties_validation.pyi @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class ObjectPropertiesValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.IntSchema + bar = schemas.StrSchema + __annotations__ = { + "foo": foo, + "bar": bar, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, decimal.Decimal, int, schemas.Unset] = schemas.unset, + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectPropertiesValidation': + return super().__new__( + cls, + *args, + foo=foo, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof.py new file mode 100644 index 0000000000..072f28a7fb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Oneof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + one_of_0 = schemas.IntSchema + + + class one_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + inclusive_minimum = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Oneof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof.pyi new file mode 100644 index 0000000000..fcf3fb1022 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof.pyi @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class Oneof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + one_of_0 = schemas.IntSchema + + + class one_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Oneof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_complex_types.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_complex_types.py new file mode 100644 index 0000000000..b38b5751a7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_complex_types.py @@ -0,0 +1,177 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class OneofComplexTypes( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class one_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "bar", + } + + class properties: + bar = schemas.IntSchema + __annotations__ = { + "bar": bar, + } + + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_1': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'OneofComplexTypes': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_complex_types.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_complex_types.pyi new file mode 100644 index 0000000000..b38b5751a7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_complex_types.pyi @@ -0,0 +1,177 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class OneofComplexTypes( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class one_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "bar", + } + + class properties: + bar = schemas.IntSchema + __annotations__ = { + "bar": bar, + } + + + bar: MetaOapg.properties.bar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_1': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'OneofComplexTypes': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_base_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_base_schema.py new file mode 100644 index 0000000000..343181f846 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_base_schema.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class OneofWithBaseSchema( + schemas.ComposedBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class one_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + min_length = 2 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + max_length = 4 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'OneofWithBaseSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_base_schema.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_base_schema.pyi new file mode 100644 index 0000000000..dbd9a7fdf3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_base_schema.pyi @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class OneofWithBaseSchema( + schemas.ComposedBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class one_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'OneofWithBaseSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_empty_schema.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_empty_schema.py new file mode 100644 index 0000000000..d0339f57ed --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_empty_schema.py @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class OneofWithEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + one_of_0 = schemas.NumberSchema + one_of_1 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'OneofWithEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_empty_schema.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_empty_schema.pyi new file mode 100644 index 0000000000..d0339f57ed --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_empty_schema.pyi @@ -0,0 +1,67 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class OneofWithEmptySchema( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + one_of_0 = schemas.NumberSchema + one_of_1 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'OneofWithEmptySchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_required.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_required.py new file mode 100644 index 0000000000..06bb23edda --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_required.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class OneofWithRequired( + schemas.ComposedBase, + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class one_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "bar", + "foo", + } + + + bar: schemas.AnyTypeSchema + foo: schemas.AnyTypeSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + "baz", + } + + + foo: schemas.AnyTypeSchema + baz: schemas.AnyTypeSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'OneofWithRequired': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_required.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_required.pyi new file mode 100644 index 0000000000..06bb23edda --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/oneof_with_required.pyi @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class OneofWithRequired( + schemas.ComposedBase, + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class one_of_0( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "bar", + "foo", + } + + + bar: schemas.AnyTypeSchema + foo: schemas.AnyTypeSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_1( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + required = { + "foo", + "baz", + } + + + foo: schemas.AnyTypeSchema + baz: schemas.AnyTypeSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + cls.one_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'OneofWithRequired': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_is_not_anchored.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_is_not_anchored.py new file mode 100644 index 0000000000..48773cbbe5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_is_not_anchored.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class PatternIsNotAnchored( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + regex=[{ + 'pattern': r'a+', # noqa: E501 + }] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'PatternIsNotAnchored': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_is_not_anchored.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_is_not_anchored.pyi new file mode 100644 index 0000000000..d4c18e7fc2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_is_not_anchored.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class PatternIsNotAnchored( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'PatternIsNotAnchored': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_validation.py new file mode 100644 index 0000000000..49594057cf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_validation.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class PatternValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + regex=[{ + 'pattern': r'^a*$', # noqa: E501 + }] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'PatternValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_validation.pyi new file mode 100644 index 0000000000..a2fb9d02f1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/pattern_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class PatternValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'PatternValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/properties_with_escaped_characters.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/properties_with_escaped_characters.py new file mode 100644 index 0000000000..7c73a200e5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/properties_with_escaped_characters.py @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class PropertiesWithEscapedCharacters( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo_nbar = schemas.NumberSchema + foo_bar = schemas.NumberSchema + foo__bar = schemas.NumberSchema + foo_rbar = schemas.NumberSchema + foo_tbar = schemas.NumberSchema + foo_fbar = schemas.NumberSchema + __annotations__ = { + "foo\nbar": foo_nbar, + "foo\"bar": foo_bar, + "foo\\bar": foo__bar, + "foo\rbar": foo_rbar, + "foo\tbar": foo_tbar, + "foo\fbar": foo_fbar, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\nbar"]) -> MetaOapg.properties.foo_nbar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\"bar"]) -> MetaOapg.properties.foo_bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\\bar"]) -> MetaOapg.properties.foo__bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\rbar"]) -> MetaOapg.properties.foo_rbar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\tbar"]) -> MetaOapg.properties.foo_tbar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\fbar"]) -> MetaOapg.properties.foo_fbar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo\nbar", "foo\"bar", "foo\\bar", "foo\rbar", "foo\tbar", "foo\fbar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\nbar"]) -> typing.Union[MetaOapg.properties.foo_nbar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\"bar"]) -> typing.Union[MetaOapg.properties.foo_bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\\bar"]) -> typing.Union[MetaOapg.properties.foo__bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\rbar"]) -> typing.Union[MetaOapg.properties.foo_rbar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\tbar"]) -> typing.Union[MetaOapg.properties.foo_tbar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\fbar"]) -> typing.Union[MetaOapg.properties.foo_fbar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo\nbar", "foo\"bar", "foo\\bar", "foo\rbar", "foo\tbar", "foo\fbar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'PropertiesWithEscapedCharacters': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/properties_with_escaped_characters.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/properties_with_escaped_characters.pyi new file mode 100644 index 0000000000..7c73a200e5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/properties_with_escaped_characters.pyi @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class PropertiesWithEscapedCharacters( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo_nbar = schemas.NumberSchema + foo_bar = schemas.NumberSchema + foo__bar = schemas.NumberSchema + foo_rbar = schemas.NumberSchema + foo_tbar = schemas.NumberSchema + foo_fbar = schemas.NumberSchema + __annotations__ = { + "foo\nbar": foo_nbar, + "foo\"bar": foo_bar, + "foo\\bar": foo__bar, + "foo\rbar": foo_rbar, + "foo\tbar": foo_tbar, + "foo\fbar": foo_fbar, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\nbar"]) -> MetaOapg.properties.foo_nbar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\"bar"]) -> MetaOapg.properties.foo_bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\\bar"]) -> MetaOapg.properties.foo__bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\rbar"]) -> MetaOapg.properties.foo_rbar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\tbar"]) -> MetaOapg.properties.foo_tbar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo\fbar"]) -> MetaOapg.properties.foo_fbar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo\nbar", "foo\"bar", "foo\\bar", "foo\rbar", "foo\tbar", "foo\fbar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\nbar"]) -> typing.Union[MetaOapg.properties.foo_nbar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\"bar"]) -> typing.Union[MetaOapg.properties.foo_bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\\bar"]) -> typing.Union[MetaOapg.properties.foo__bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\rbar"]) -> typing.Union[MetaOapg.properties.foo_rbar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\tbar"]) -> typing.Union[MetaOapg.properties.foo_tbar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo\fbar"]) -> typing.Union[MetaOapg.properties.foo_fbar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo\nbar", "foo\"bar", "foo\\bar", "foo\rbar", "foo\tbar", "foo\fbar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'PropertiesWithEscapedCharacters': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/property_named_ref_that_is_not_a_reference.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/property_named_ref_that_is_not_a_reference.py new file mode 100644 index 0000000000..344414e9cc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/property_named_ref_that_is_not_a_reference.py @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class PropertyNamedRefThatIsNotAReference( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + ref = schemas.StrSchema + __annotations__ = { + "$ref": ref, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["$ref"]) -> MetaOapg.properties.ref: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["$ref", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["$ref"]) -> typing.Union[MetaOapg.properties.ref, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["$ref", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'PropertyNamedRefThatIsNotAReference': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/property_named_ref_that_is_not_a_reference.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/property_named_ref_that_is_not_a_reference.pyi new file mode 100644 index 0000000000..344414e9cc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/property_named_ref_that_is_not_a_reference.pyi @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class PropertyNamedRefThatIsNotAReference( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + ref = schemas.StrSchema + __annotations__ = { + "$ref": ref, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["$ref"]) -> MetaOapg.properties.ref: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["$ref", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["$ref"]) -> typing.Union[MetaOapg.properties.ref, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["$ref", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'PropertyNamedRefThatIsNotAReference': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_additionalproperties.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_additionalproperties.py new file mode 100644 index 0000000000..a15df31054 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_additionalproperties.py @@ -0,0 +1,62 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInAdditionalproperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def additional_properties() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + def __getitem__(self, name: typing.Union[str, ]) -> 'PropertyNamedRefThatIsNotAReference': + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> 'PropertyNamedRefThatIsNotAReference': + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: 'PropertyNamedRefThatIsNotAReference', + ) -> 'RefInAdditionalproperties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_additionalproperties.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_additionalproperties.pyi new file mode 100644 index 0000000000..a15df31054 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_additionalproperties.pyi @@ -0,0 +1,62 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInAdditionalproperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def additional_properties() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + def __getitem__(self, name: typing.Union[str, ]) -> 'PropertyNamedRefThatIsNotAReference': + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> 'PropertyNamedRefThatIsNotAReference': + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: 'PropertyNamedRefThatIsNotAReference', + ) -> 'RefInAdditionalproperties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_allof.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_allof.py new file mode 100644 index 0000000000..979c66540f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_allof.py @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInAllof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + PropertyNamedRefThatIsNotAReference, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInAllof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_allof.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_allof.pyi new file mode 100644 index 0000000000..979c66540f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_allof.pyi @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInAllof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + PropertyNamedRefThatIsNotAReference, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInAllof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_anyof.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_anyof.py new file mode 100644 index 0000000000..df7546c1c2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_anyof.py @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInAnyof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + PropertyNamedRefThatIsNotAReference, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInAnyof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_anyof.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_anyof.pyi new file mode 100644 index 0000000000..df7546c1c2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_anyof.pyi @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInAnyof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + PropertyNamedRefThatIsNotAReference, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInAnyof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_items.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_items.py new file mode 100644 index 0000000000..73663ab9c0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_items.py @@ -0,0 +1,56 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInItems( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + def __new__( + cls, + arg: typing.Union[typing.Tuple['PropertyNamedRefThatIsNotAReference'], typing.List['PropertyNamedRefThatIsNotAReference']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'RefInItems': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'PropertyNamedRefThatIsNotAReference': + return super().__getitem__(i) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_items.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_items.pyi new file mode 100644 index 0000000000..73663ab9c0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_items.pyi @@ -0,0 +1,56 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInItems( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + def __new__( + cls, + arg: typing.Union[typing.Tuple['PropertyNamedRefThatIsNotAReference'], typing.List['PropertyNamedRefThatIsNotAReference']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'RefInItems': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'PropertyNamedRefThatIsNotAReference': + return super().__getitem__(i) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_not.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_not.py new file mode 100644 index 0000000000..b1362b851a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_not.py @@ -0,0 +1,56 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInNot( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def not_schema() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInNot': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_not.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_not.pyi new file mode 100644 index 0000000000..b1362b851a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_not.pyi @@ -0,0 +1,56 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInNot( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def not_schema() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInNot': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_oneof.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_oneof.py new file mode 100644 index 0000000000..99be8069ed --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_oneof.py @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInOneof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + PropertyNamedRefThatIsNotAReference, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInOneof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_oneof.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_oneof.pyi new file mode 100644 index 0000000000..99be8069ed --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_oneof.pyi @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInOneof( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + PropertyNamedRefThatIsNotAReference, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInOneof': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_property.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_property.py new file mode 100644 index 0000000000..00390b0805 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_property.py @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInProperty( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + @staticmethod + def a() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + __annotations__ = { + "a": a, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["a"]) -> 'PropertyNamedRefThatIsNotAReference': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["a", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["a"]) -> typing.Union['PropertyNamedRefThatIsNotAReference', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["a", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + a: typing.Union['PropertyNamedRefThatIsNotAReference', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInProperty': + return super().__new__( + cls, + *args, + a=a, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_property.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_property.pyi new file mode 100644 index 0000000000..00390b0805 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/ref_in_property.pyi @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RefInProperty( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + @staticmethod + def a() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + __annotations__ = { + "a": a, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["a"]) -> 'PropertyNamedRefThatIsNotAReference': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["a", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["a"]) -> typing.Union['PropertyNamedRefThatIsNotAReference', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["a", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + a: typing.Union['PropertyNamedRefThatIsNotAReference', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RefInProperty': + return super().__new__( + cls, + *args, + a=a, + _configuration=_configuration, + **kwargs, + ) + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_default_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_default_validation.py new file mode 100644 index 0000000000..464498e13f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_default_validation.py @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RequiredDefaultValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RequiredDefaultValidation': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_default_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_default_validation.pyi new file mode 100644 index 0000000000..464498e13f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_default_validation.pyi @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RequiredDefaultValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RequiredDefaultValidation': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_validation.py new file mode 100644 index 0000000000..aa43367ca2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_validation.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RequiredValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.AnyTypeSchema + bar = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + "bar": bar, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RequiredValidation': + return super().__new__( + cls, + *args, + foo=foo, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_validation.pyi new file mode 100644 index 0000000000..aa43367ca2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_validation.pyi @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RequiredValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "foo", + } + + class properties: + foo = schemas.AnyTypeSchema + bar = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + "bar": bar, + } + + + foo: MetaOapg.properties.foo + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", "bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + bar: typing.Union[MetaOapg.properties.bar, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RequiredValidation': + return super().__new__( + cls, + *args, + foo=foo, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_empty_array.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_empty_array.py new file mode 100644 index 0000000000..98018693bc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_empty_array.py @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RequiredWithEmptyArray( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RequiredWithEmptyArray': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_empty_array.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_empty_array.pyi new file mode 100644 index 0000000000..98018693bc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_empty_array.pyi @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RequiredWithEmptyArray( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + foo = schemas.AnyTypeSchema + __annotations__ = { + "foo": foo, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + foo: typing.Union[MetaOapg.properties.foo, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RequiredWithEmptyArray': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_escaped_characters.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_escaped_characters.py new file mode 100644 index 0000000000..52a8999cd2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_escaped_characters.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RequiredWithEscapedCharacters( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "foo\"bar", + "foo\nbar", + "foo\fbar", + "foo\tbar", + "foo\rbar", + "foo\\bar", + } + + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RequiredWithEscapedCharacters': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_escaped_characters.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_escaped_characters.pyi new file mode 100644 index 0000000000..52a8999cd2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/required_with_escaped_characters.pyi @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class RequiredWithEscapedCharacters( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "foo\"bar", + "foo\nbar", + "foo\fbar", + "foo\tbar", + "foo\rbar", + "foo\\bar", + } + + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'RequiredWithEscapedCharacters': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/simple_enum_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/simple_enum_validation.py new file mode 100644 index 0000000000..26641b8c99 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/simple_enum_validation.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class SimpleEnumValidation( + schemas.EnumBase, + schemas.NumberSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + 1: "POSITIVE_1", + 2: "POSITIVE_2", + 3: "POSITIVE_3", + } + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def POSITIVE_2(cls): + return cls(2) + + @schemas.classproperty + def POSITIVE_3(cls): + return cls(3) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/simple_enum_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/simple_enum_validation.pyi new file mode 100644 index 0000000000..61ed175912 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/simple_enum_validation.pyi @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class SimpleEnumValidation( + schemas.EnumBase, + schemas.NumberSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def POSITIVE_2(cls): + return cls(2) + + @schemas.classproperty + def POSITIVE_3(cls): + return cls(3) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/string_type_matches_strings.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/string_type_matches_strings.py new file mode 100644 index 0000000000..573e83bc99 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/string_type_matches_strings.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +StringTypeMatchesStrings = schemas.StrSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/string_type_matches_strings.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/string_type_matches_strings.pyi new file mode 100644 index 0000000000..573e83bc99 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/string_type_matches_strings.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 +StringTypeMatchesStrings = schemas.StrSchema diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.py new file mode 100644 index 0000000000..57a001ad75 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class alpha( + schemas.NumberSchema + ): + + + class MetaOapg: + inclusive_maximum = 3 + __annotations__ = { + "alpha": alpha, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["alpha"]) -> MetaOapg.properties.alpha: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["alpha", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["alpha"]) -> typing.Union[MetaOapg.properties.alpha, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["alpha", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + alpha: typing.Union[MetaOapg.properties.alpha, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing': + return super().__new__( + cls, + *args, + alpha=alpha, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.pyi new file mode 100644 index 0000000000..caec048424 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/the_default_keyword_does_not_do_anything_if_the_property_is_missing.pyi @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class alpha( + schemas.NumberSchema + ): + pass + __annotations__ = { + "alpha": alpha, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["alpha"]) -> MetaOapg.properties.alpha: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["alpha", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["alpha"]) -> typing.Union[MetaOapg.properties.alpha, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["alpha", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + alpha: typing.Union[MetaOapg.properties.alpha, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing': + return super().__new__( + cls, + *args, + alpha=alpha, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_false_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_false_validation.py new file mode 100644 index 0000000000..485edf4e3c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_false_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UniqueitemsFalseValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + unique_items = False + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UniqueitemsFalseValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_false_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_false_validation.pyi new file mode 100644 index 0000000000..c5ded11279 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_false_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UniqueitemsFalseValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UniqueitemsFalseValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_validation.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_validation.py new file mode 100644 index 0000000000..9fd610f660 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_validation.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UniqueitemsValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + unique_items = True + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UniqueitemsValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_validation.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_validation.pyi new file mode 100644 index 0000000000..175556c680 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uniqueitems_validation.pyi @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UniqueitemsValidation( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UniqueitemsValidation': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_format.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_format.py new file mode 100644 index 0000000000..c8202e8dcc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_format.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UriFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'uri' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UriFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_format.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_format.pyi new file mode 100644 index 0000000000..c8202e8dcc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_format.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UriFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'uri' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UriFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_reference_format.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_reference_format.py new file mode 100644 index 0000000000..8a66998c4f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_reference_format.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UriReferenceFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'uri-reference' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UriReferenceFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_reference_format.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_reference_format.pyi new file mode 100644 index 0000000000..8a66998c4f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_reference_format.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UriReferenceFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'uri-reference' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UriReferenceFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_template_format.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_template_format.py new file mode 100644 index 0000000000..50fb98bcac --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_template_format.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UriTemplateFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'uri-template' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UriTemplateFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_template_format.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_template_format.pyi new file mode 100644 index 0000000000..50fb98bcac --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/model/uri_template_format.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + +class UriTemplateFormat( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'uri-template' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'UriTemplateFormat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/models/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/models/__init__.py new file mode 100644 index 0000000000..3dd512a4cd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/models/__init__.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +# flake8: noqa + +# import all models into this package +# if you have many models here with many references from one model to another this may +# raise a RecursionError +# to avoid this, import only the models that you directly need like: +# from from unit_test_api.model.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) + +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators +from unit_test_api.model.allof import Allof +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof +from unit_test_api.model.allof_simple_types import AllofSimpleTypes +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas +from unit_test_api.model.anyof import Anyof +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays +from unit_test_api.model.boolean_type_matches_booleans import BooleanTypeMatchesBooleans +from unit_test_api.model.by_int import ByInt +from unit_test_api.model.by_number import ByNumber +from unit_test_api.model.by_small_number import BySmallNumber +from unit_test_api.model.date_time_format import DateTimeFormat +from unit_test_api.model.email_format import EmailFormat +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 +from unit_test_api.model.enums_in_properties import EnumsInProperties +from unit_test_api.model.forbidden_property import ForbiddenProperty +from unit_test_api.model.hostname_format import HostnameFormat +from unit_test_api.model.integer_type_matches_integers import IntegerTypeMatchesIntegers +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault +from unit_test_api.model.ipv4_format import Ipv4Format +from unit_test_api.model.ipv6_format import Ipv6Format +from unit_test_api.model.json_pointer_format import JsonPointerFormat +from unit_test_api.model.maximum_validation import MaximumValidation +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger +from unit_test_api.model.maxitems_validation import MaxitemsValidation +from unit_test_api.model.maxlength_validation import MaxlengthValidation +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation +from unit_test_api.model.minimum_validation import MinimumValidation +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger +from unit_test_api.model.minitems_validation import MinitemsValidation +from unit_test_api.model.minlength_validation import MinlengthValidation +from unit_test_api.model.minproperties_validation import MinpropertiesValidation +from unit_test_api.model.model_not import ModelNot +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics +from unit_test_api.model.nested_items import NestedItems +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics +from unit_test_api.model.not_more_complex_schema import NotMoreComplexSchema +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings +from unit_test_api.model.null_type_matches_only_the_null_object import NullTypeMatchesOnlyTheNullObject +from unit_test_api.model.number_type_matches_numbers import NumberTypeMatchesNumbers +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation +from unit_test_api.model.oneof import Oneof +from unit_test_api.model.oneof_complex_types import OneofComplexTypes +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema +from unit_test_api.model.oneof_with_required import OneofWithRequired +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored +from unit_test_api.model.pattern_validation import PatternValidation +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties +from unit_test_api.model.ref_in_allof import RefInAllof +from unit_test_api.model.ref_in_anyof import RefInAnyof +from unit_test_api.model.ref_in_items import RefInItems +from unit_test_api.model.ref_in_not import RefInNot +from unit_test_api.model.ref_in_oneof import RefInOneof +from unit_test_api.model.ref_in_property import RefInProperty +from unit_test_api.model.required_default_validation import RequiredDefaultValidation +from unit_test_api.model.required_validation import RequiredValidation +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray +from unit_test_api.model.required_with_escaped_characters import RequiredWithEscapedCharacters +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation +from unit_test_api.model.string_type_matches_strings import StringTypeMatchesStrings +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation +from unit_test_api.model.uri_format import UriFormat +from unit_test_api.model.uri_reference_format import UriReferenceFormat +from unit_test_api.model.uri_template_format import UriTemplateFormat diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/__init__.py new file mode 100644 index 0000000000..2522dcf8f1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/__init__.py @@ -0,0 +1,182 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.apis.path_to_api import path_to_api + +import enum + + +class PathValues(str, enum.Enum): + REQUEST_BODY_POST_ADDITIONALPROPERTIES_ALLOWS_ASCHEMA_WHICH_SHOULD_VALIDATE_REQUEST_BODY = "/requestBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody" + RESPONSE_BODY_POST_ADDITIONALPROPERTIES_ALLOWS_ASCHEMA_WHICH_SHOULD_VALIDATE_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes" + REQUEST_BODY_POST_ADDITIONALPROPERTIES_CAN_EXIST_BY_ITSELF_REQUEST_BODY = "/requestBody/postAdditionalpropertiesCanExistByItselfRequestBody" + RESPONSE_BODY_POST_ADDITIONALPROPERTIES_CAN_EXIST_BY_ITSELF_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes" + REQUEST_BODY_POST_ADDITIONALPROPERTIES_ARE_ALLOWED_BY_DEFAULT_REQUEST_BODY = "/requestBody/postAdditionalpropertiesAreAllowedByDefaultRequestBody" + RESPONSE_BODY_POST_ADDITIONALPROPERTIES_ARE_ALLOWED_BY_DEFAULT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes" + REQUEST_BODY_POST_ADDITIONALPROPERTIES_SHOULD_NOT_LOOK_IN_APPLICATORS_REQUEST_BODY = "/requestBody/postAdditionalpropertiesShouldNotLookInApplicatorsRequestBody" + RESPONSE_BODY_POST_ADDITIONALPROPERTIES_SHOULD_NOT_LOOK_IN_APPLICATORS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes" + REQUEST_BODY_POST_ALLOF_REQUEST_BODY = "/requestBody/postAllofRequestBody" + RESPONSE_BODY_POST_ALLOF_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAllofResponseBodyForContentTypes" + REQUEST_BODY_POST_ALLOF_WITH_BASE_SCHEMA_REQUEST_BODY = "/requestBody/postAllofWithBaseSchemaRequestBody" + RESPONSE_BODY_POST_ALLOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAllofWithBaseSchemaResponseBodyForContentTypes" + REQUEST_BODY_POST_ALLOF_SIMPLE_TYPES_REQUEST_BODY = "/requestBody/postAllofSimpleTypesRequestBody" + RESPONSE_BODY_POST_ALLOF_SIMPLE_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAllofSimpleTypesResponseBodyForContentTypes" + REQUEST_BODY_POST_ALLOF_WITH_ONE_EMPTY_SCHEMA_REQUEST_BODY = "/requestBody/postAllofWithOneEmptySchemaRequestBody" + RESPONSE_BODY_POST_ALLOF_WITH_ONE_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAllofWithOneEmptySchemaResponseBodyForContentTypes" + REQUEST_BODY_POST_ALLOF_WITH_TWO_EMPTY_SCHEMAS_REQUEST_BODY = "/requestBody/postAllofWithTwoEmptySchemasRequestBody" + RESPONSE_BODY_POST_ALLOF_WITH_TWO_EMPTY_SCHEMAS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAllofWithTwoEmptySchemasResponseBodyForContentTypes" + REQUEST_BODY_POST_ALLOF_WITH_THE_FIRST_EMPTY_SCHEMA_REQUEST_BODY = "/requestBody/postAllofWithTheFirstEmptySchemaRequestBody" + RESPONSE_BODY_POST_ALLOF_WITH_THE_FIRST_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAllofWithTheFirstEmptySchemaResponseBodyForContentTypes" + REQUEST_BODY_POST_ALLOF_WITH_THE_LAST_EMPTY_SCHEMA_REQUEST_BODY = "/requestBody/postAllofWithTheLastEmptySchemaRequestBody" + RESPONSE_BODY_POST_ALLOF_WITH_THE_LAST_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAllofWithTheLastEmptySchemaResponseBodyForContentTypes" + REQUEST_BODY_POST_NESTED_ALLOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY = "/requestBody/postNestedAllofToCheckValidationSemanticsRequestBody" + RESPONSE_BODY_POST_NESTED_ALLOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes" + REQUEST_BODY_POST_ALLOF_COMBINED_WITH_ANYOF_ONEOF_REQUEST_BODY = "/requestBody/postAllofCombinedWithAnyofOneofRequestBody" + RESPONSE_BODY_POST_ALLOF_COMBINED_WITH_ANYOF_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAllofCombinedWithAnyofOneofResponseBodyForContentTypes" + REQUEST_BODY_POST_ANYOF_REQUEST_BODY = "/requestBody/postAnyofRequestBody" + RESPONSE_BODY_POST_ANYOF_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAnyofResponseBodyForContentTypes" + REQUEST_BODY_POST_ANYOF_WITH_BASE_SCHEMA_REQUEST_BODY = "/requestBody/postAnyofWithBaseSchemaRequestBody" + RESPONSE_BODY_POST_ANYOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAnyofWithBaseSchemaResponseBodyForContentTypes" + REQUEST_BODY_POST_ANYOF_COMPLEX_TYPES_REQUEST_BODY = "/requestBody/postAnyofComplexTypesRequestBody" + RESPONSE_BODY_POST_ANYOF_COMPLEX_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAnyofComplexTypesResponseBodyForContentTypes" + REQUEST_BODY_POST_ANYOF_WITH_ONE_EMPTY_SCHEMA_REQUEST_BODY = "/requestBody/postAnyofWithOneEmptySchemaRequestBody" + RESPONSE_BODY_POST_ANYOF_WITH_ONE_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postAnyofWithOneEmptySchemaResponseBodyForContentTypes" + REQUEST_BODY_POST_NESTED_ANYOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY = "/requestBody/postNestedAnyofToCheckValidationSemanticsRequestBody" + RESPONSE_BODY_POST_NESTED_ANYOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes" + REQUEST_BODY_POST_INVALID_STRING_VALUE_FOR_DEFAULT_REQUEST_BODY = "/requestBody/postInvalidStringValueForDefaultRequestBody" + RESPONSE_BODY_POST_INVALID_STRING_VALUE_FOR_DEFAULT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postInvalidStringValueForDefaultResponseBodyForContentTypes" + REQUEST_BODY_POST_THE_DEFAULT_KEYWORD_DOES_NOT_DO_ANYTHING_IF_THE_PROPERTY_IS_MISSING_REQUEST_BODY = "/requestBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody" + RESPONSE_BODY_POST_THE_DEFAULT_KEYWORD_DOES_NOT_DO_ANYTHING_IF_THE_PROPERTY_IS_MISSING_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes" + REQUEST_BODY_POST_SIMPLE_ENUM_VALIDATION_REQUEST_BODY = "/requestBody/postSimpleEnumValidationRequestBody" + RESPONSE_BODY_POST_SIMPLE_ENUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postSimpleEnumValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_ENUMS_IN_PROPERTIES_REQUEST_BODY = "/requestBody/postEnumsInPropertiesRequestBody" + RESPONSE_BODY_POST_ENUMS_IN_PROPERTIES_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postEnumsInPropertiesResponseBodyForContentTypes" + REQUEST_BODY_POST_ENUM_WITH_ESCAPED_CHARACTERS_REQUEST_BODY = "/requestBody/postEnumWithEscapedCharactersRequestBody" + RESPONSE_BODY_POST_ENUM_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postEnumWithEscapedCharactersResponseBodyForContentTypes" + REQUEST_BODY_POST_ENUM_WITH_FALSE_DOES_NOT_MATCH0REQUEST_BODY = "/requestBody/postEnumWithFalseDoesNotMatch0RequestBody" + RESPONSE_BODY_POST_ENUM_WITH_FALSE_DOES_NOT_MATCH0RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes" + REQUEST_BODY_POST_ENUM_WITH_TRUE_DOES_NOT_MATCH1REQUEST_BODY = "/requestBody/postEnumWithTrueDoesNotMatch1RequestBody" + RESPONSE_BODY_POST_ENUM_WITH_TRUE_DOES_NOT_MATCH1RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes" + REQUEST_BODY_POST_ENUM_WITH0DOES_NOT_MATCH_FALSE_REQUEST_BODY = "/requestBody/postEnumWith0DoesNotMatchFalseRequestBody" + RESPONSE_BODY_POST_ENUM_WITH0DOES_NOT_MATCH_FALSE_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postEnumWith0DoesNotMatchFalseResponseBodyForContentTypes" + REQUEST_BODY_POST_ENUM_WITH1DOES_NOT_MATCH_TRUE_REQUEST_BODY = "/requestBody/postEnumWith1DoesNotMatchTrueRequestBody" + RESPONSE_BODY_POST_ENUM_WITH1DOES_NOT_MATCH_TRUE_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postEnumWith1DoesNotMatchTrueResponseBodyForContentTypes" + REQUEST_BODY_POST_NUL_CHARACTERS_IN_STRINGS_REQUEST_BODY = "/requestBody/postNulCharactersInStringsRequestBody" + RESPONSE_BODY_POST_NUL_CHARACTERS_IN_STRINGS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postNulCharactersInStringsResponseBodyForContentTypes" + REQUEST_BODY_POST_EMAIL_FORMAT_REQUEST_BODY = "/requestBody/postEmailFormatRequestBody" + RESPONSE_BODY_POST_EMAIL_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postEmailFormatResponseBodyForContentTypes" + REQUEST_BODY_POST_IPV4FORMAT_REQUEST_BODY = "/requestBody/postIpv4FormatRequestBody" + RESPONSE_BODY_POST_IPV4FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postIpv4FormatResponseBodyForContentTypes" + REQUEST_BODY_POST_IPV6FORMAT_REQUEST_BODY = "/requestBody/postIpv6FormatRequestBody" + RESPONSE_BODY_POST_IPV6FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postIpv6FormatResponseBodyForContentTypes" + REQUEST_BODY_POST_HOSTNAME_FORMAT_REQUEST_BODY = "/requestBody/postHostnameFormatRequestBody" + RESPONSE_BODY_POST_HOSTNAME_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postHostnameFormatResponseBodyForContentTypes" + REQUEST_BODY_POST_DATE_TIME_FORMAT_REQUEST_BODY = "/requestBody/postDateTimeFormatRequestBody" + RESPONSE_BODY_POST_DATE_TIME_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postDateTimeFormatResponseBodyForContentTypes" + REQUEST_BODY_POST_JSON_POINTER_FORMAT_REQUEST_BODY = "/requestBody/postJsonPointerFormatRequestBody" + RESPONSE_BODY_POST_JSON_POINTER_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postJsonPointerFormatResponseBodyForContentTypes" + REQUEST_BODY_POST_URI_FORMAT_REQUEST_BODY = "/requestBody/postUriFormatRequestBody" + RESPONSE_BODY_POST_URI_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postUriFormatResponseBodyForContentTypes" + REQUEST_BODY_POST_URI_REFERENCE_FORMAT_REQUEST_BODY = "/requestBody/postUriReferenceFormatRequestBody" + RESPONSE_BODY_POST_URI_REFERENCE_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postUriReferenceFormatResponseBodyForContentTypes" + REQUEST_BODY_POST_URI_TEMPLATE_FORMAT_REQUEST_BODY = "/requestBody/postUriTemplateFormatRequestBody" + RESPONSE_BODY_POST_URI_TEMPLATE_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postUriTemplateFormatResponseBodyForContentTypes" + REQUEST_BODY_POST_NESTED_ITEMS_REQUEST_BODY = "/requestBody/postNestedItemsRequestBody" + RESPONSE_BODY_POST_NESTED_ITEMS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postNestedItemsResponseBodyForContentTypes" + REQUEST_BODY_POST_MAXIMUM_VALIDATION_REQUEST_BODY = "/requestBody/postMaximumValidationRequestBody" + RESPONSE_BODY_POST_MAXIMUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMaximumValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_MAXIMUM_VALIDATION_WITH_UNSIGNED_INTEGER_REQUEST_BODY = "/requestBody/postMaximumValidationWithUnsignedIntegerRequestBody" + RESPONSE_BODY_POST_MAXIMUM_VALIDATION_WITH_UNSIGNED_INTEGER_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes" + REQUEST_BODY_POST_MAXITEMS_VALIDATION_REQUEST_BODY = "/requestBody/postMaxitemsValidationRequestBody" + RESPONSE_BODY_POST_MAXITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMaxitemsValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_MAXLENGTH_VALIDATION_REQUEST_BODY = "/requestBody/postMaxlengthValidationRequestBody" + RESPONSE_BODY_POST_MAXLENGTH_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMaxlengthValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_MAXPROPERTIES_VALIDATION_REQUEST_BODY = "/requestBody/postMaxpropertiesValidationRequestBody" + RESPONSE_BODY_POST_MAXPROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMaxpropertiesValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_MAXPROPERTIES0MEANS_THE_OBJECT_IS_EMPTY_REQUEST_BODY = "/requestBody/postMaxproperties0MeansTheObjectIsEmptyRequestBody" + RESPONSE_BODY_POST_MAXPROPERTIES0MEANS_THE_OBJECT_IS_EMPTY_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes" + REQUEST_BODY_POST_MINIMUM_VALIDATION_REQUEST_BODY = "/requestBody/postMinimumValidationRequestBody" + RESPONSE_BODY_POST_MINIMUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMinimumValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_MINIMUM_VALIDATION_WITH_SIGNED_INTEGER_REQUEST_BODY = "/requestBody/postMinimumValidationWithSignedIntegerRequestBody" + RESPONSE_BODY_POST_MINIMUM_VALIDATION_WITH_SIGNED_INTEGER_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMinimumValidationWithSignedIntegerResponseBodyForContentTypes" + REQUEST_BODY_POST_MINITEMS_VALIDATION_REQUEST_BODY = "/requestBody/postMinitemsValidationRequestBody" + RESPONSE_BODY_POST_MINITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMinitemsValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_MINLENGTH_VALIDATION_REQUEST_BODY = "/requestBody/postMinlengthValidationRequestBody" + RESPONSE_BODY_POST_MINLENGTH_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMinlengthValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_MINPROPERTIES_VALIDATION_REQUEST_BODY = "/requestBody/postMinpropertiesValidationRequestBody" + RESPONSE_BODY_POST_MINPROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postMinpropertiesValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_BY_INT_REQUEST_BODY = "/requestBody/postByIntRequestBody" + RESPONSE_BODY_POST_BY_INT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postByIntResponseBodyForContentTypes" + REQUEST_BODY_POST_BY_NUMBER_REQUEST_BODY = "/requestBody/postByNumberRequestBody" + RESPONSE_BODY_POST_BY_NUMBER_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postByNumberResponseBodyForContentTypes" + REQUEST_BODY_POST_BY_SMALL_NUMBER_REQUEST_BODY = "/requestBody/postBySmallNumberRequestBody" + RESPONSE_BODY_POST_BY_SMALL_NUMBER_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postBySmallNumberResponseBodyForContentTypes" + REQUEST_BODY_POST_INVALID_INSTANCE_SHOULD_NOT_RAISE_ERROR_WHEN_FLOAT_DIVISION_INF_REQUEST_BODY = "/requestBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody" + RESPONSE_BODY_POST_INVALID_INSTANCE_SHOULD_NOT_RAISE_ERROR_WHEN_FLOAT_DIVISION_INF_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes" + REQUEST_BODY_POST_NOT_REQUEST_BODY = "/requestBody/postNotRequestBody" + RESPONSE_BODY_POST_NOT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postNotResponseBodyForContentTypes" + REQUEST_BODY_POST_NOT_MORE_COMPLEX_SCHEMA_REQUEST_BODY = "/requestBody/postNotMoreComplexSchemaRequestBody" + RESPONSE_BODY_POST_NOT_MORE_COMPLEX_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postNotMoreComplexSchemaResponseBodyForContentTypes" + REQUEST_BODY_POST_FORBIDDEN_PROPERTY_REQUEST_BODY = "/requestBody/postForbiddenPropertyRequestBody" + RESPONSE_BODY_POST_FORBIDDEN_PROPERTY_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postForbiddenPropertyResponseBodyForContentTypes" + REQUEST_BODY_POST_ONEOF_REQUEST_BODY = "/requestBody/postOneofRequestBody" + RESPONSE_BODY_POST_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postOneofResponseBodyForContentTypes" + REQUEST_BODY_POST_ONEOF_WITH_BASE_SCHEMA_REQUEST_BODY = "/requestBody/postOneofWithBaseSchemaRequestBody" + RESPONSE_BODY_POST_ONEOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postOneofWithBaseSchemaResponseBodyForContentTypes" + REQUEST_BODY_POST_ONEOF_COMPLEX_TYPES_REQUEST_BODY = "/requestBody/postOneofComplexTypesRequestBody" + RESPONSE_BODY_POST_ONEOF_COMPLEX_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postOneofComplexTypesResponseBodyForContentTypes" + REQUEST_BODY_POST_ONEOF_WITH_EMPTY_SCHEMA_REQUEST_BODY = "/requestBody/postOneofWithEmptySchemaRequestBody" + RESPONSE_BODY_POST_ONEOF_WITH_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postOneofWithEmptySchemaResponseBodyForContentTypes" + REQUEST_BODY_POST_ONEOF_WITH_REQUIRED_REQUEST_BODY = "/requestBody/postOneofWithRequiredRequestBody" + RESPONSE_BODY_POST_ONEOF_WITH_REQUIRED_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postOneofWithRequiredResponseBodyForContentTypes" + REQUEST_BODY_POST_NESTED_ONEOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY = "/requestBody/postNestedOneofToCheckValidationSemanticsRequestBody" + RESPONSE_BODY_POST_NESTED_ONEOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes" + REQUEST_BODY_POST_PATTERN_VALIDATION_REQUEST_BODY = "/requestBody/postPatternValidationRequestBody" + RESPONSE_BODY_POST_PATTERN_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postPatternValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_PATTERN_IS_NOT_ANCHORED_REQUEST_BODY = "/requestBody/postPatternIsNotAnchoredRequestBody" + RESPONSE_BODY_POST_PATTERN_IS_NOT_ANCHORED_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postPatternIsNotAnchoredResponseBodyForContentTypes" + REQUEST_BODY_POST_OBJECT_PROPERTIES_VALIDATION_REQUEST_BODY = "/requestBody/postObjectPropertiesValidationRequestBody" + RESPONSE_BODY_POST_OBJECT_PROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postObjectPropertiesValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_PROPERTIES_WITH_ESCAPED_CHARACTERS_REQUEST_BODY = "/requestBody/postPropertiesWithEscapedCharactersRequestBody" + RESPONSE_BODY_POST_PROPERTIES_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postPropertiesWithEscapedCharactersResponseBodyForContentTypes" + REQUEST_BODY_POST_PROPERTY_NAMED_REF_THAT_IS_NOT_AREFERENCE_REQUEST_BODY = "/requestBody/postPropertyNamedRefThatIsNotAReferenceRequestBody" + RESPONSE_BODY_POST_PROPERTY_NAMED_REF_THAT_IS_NOT_AREFERENCE_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes" + REQUEST_BODY_POST_REF_IN_ADDITIONALPROPERTIES_REQUEST_BODY = "/requestBody/postRefInAdditionalpropertiesRequestBody" + RESPONSE_BODY_POST_REF_IN_ADDITIONALPROPERTIES_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRefInAdditionalpropertiesResponseBodyForContentTypes" + REQUEST_BODY_POST_REF_IN_ITEMS_REQUEST_BODY = "/requestBody/postRefInItemsRequestBody" + RESPONSE_BODY_POST_REF_IN_ITEMS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRefInItemsResponseBodyForContentTypes" + REQUEST_BODY_POST_REF_IN_PROPERTY_REQUEST_BODY = "/requestBody/postRefInPropertyRequestBody" + RESPONSE_BODY_POST_REF_IN_PROPERTY_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRefInPropertyResponseBodyForContentTypes" + REQUEST_BODY_POST_REF_IN_ALLOF_REQUEST_BODY = "/requestBody/postRefInAllofRequestBody" + RESPONSE_BODY_POST_REF_IN_ALLOF_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRefInAllofResponseBodyForContentTypes" + REQUEST_BODY_POST_REF_IN_ONEOF_REQUEST_BODY = "/requestBody/postRefInOneofRequestBody" + RESPONSE_BODY_POST_REF_IN_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRefInOneofResponseBodyForContentTypes" + REQUEST_BODY_POST_REF_IN_ANYOF_REQUEST_BODY = "/requestBody/postRefInAnyofRequestBody" + RESPONSE_BODY_POST_REF_IN_ANYOF_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRefInAnyofResponseBodyForContentTypes" + REQUEST_BODY_POST_REF_IN_NOT_REQUEST_BODY = "/requestBody/postRefInNotRequestBody" + RESPONSE_BODY_POST_REF_IN_NOT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRefInNotResponseBodyForContentTypes" + REQUEST_BODY_POST_REQUIRED_VALIDATION_REQUEST_BODY = "/requestBody/postRequiredValidationRequestBody" + RESPONSE_BODY_POST_REQUIRED_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRequiredValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_REQUIRED_DEFAULT_VALIDATION_REQUEST_BODY = "/requestBody/postRequiredDefaultValidationRequestBody" + RESPONSE_BODY_POST_REQUIRED_DEFAULT_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRequiredDefaultValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_REQUIRED_WITH_EMPTY_ARRAY_REQUEST_BODY = "/requestBody/postRequiredWithEmptyArrayRequestBody" + RESPONSE_BODY_POST_REQUIRED_WITH_EMPTY_ARRAY_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRequiredWithEmptyArrayResponseBodyForContentTypes" + REQUEST_BODY_POST_REQUIRED_WITH_ESCAPED_CHARACTERS_REQUEST_BODY = "/requestBody/postRequiredWithEscapedCharactersRequestBody" + RESPONSE_BODY_POST_REQUIRED_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postRequiredWithEscapedCharactersResponseBodyForContentTypes" + REQUEST_BODY_POST_INTEGER_TYPE_MATCHES_INTEGERS_REQUEST_BODY = "/requestBody/postIntegerTypeMatchesIntegersRequestBody" + RESPONSE_BODY_POST_INTEGER_TYPE_MATCHES_INTEGERS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postIntegerTypeMatchesIntegersResponseBodyForContentTypes" + REQUEST_BODY_POST_NUMBER_TYPE_MATCHES_NUMBERS_REQUEST_BODY = "/requestBody/postNumberTypeMatchesNumbersRequestBody" + RESPONSE_BODY_POST_NUMBER_TYPE_MATCHES_NUMBERS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postNumberTypeMatchesNumbersResponseBodyForContentTypes" + REQUEST_BODY_POST_STRING_TYPE_MATCHES_STRINGS_REQUEST_BODY = "/requestBody/postStringTypeMatchesStringsRequestBody" + RESPONSE_BODY_POST_STRING_TYPE_MATCHES_STRINGS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postStringTypeMatchesStringsResponseBodyForContentTypes" + REQUEST_BODY_POST_OBJECT_TYPE_MATCHES_OBJECTS_REQUEST_BODY = "/requestBody/postObjectTypeMatchesObjectsRequestBody" + RESPONSE_BODY_POST_OBJECT_TYPE_MATCHES_OBJECTS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postObjectTypeMatchesObjectsResponseBodyForContentTypes" + REQUEST_BODY_POST_BOOLEAN_TYPE_MATCHES_BOOLEANS_REQUEST_BODY = "/requestBody/postBooleanTypeMatchesBooleansRequestBody" + RESPONSE_BODY_POST_BOOLEAN_TYPE_MATCHES_BOOLEANS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postBooleanTypeMatchesBooleansResponseBodyForContentTypes" + REQUEST_BODY_POST_NULL_TYPE_MATCHES_ONLY_THE_NULL_OBJECT_REQUEST_BODY = "/requestBody/postNullTypeMatchesOnlyTheNullObjectRequestBody" + RESPONSE_BODY_POST_NULL_TYPE_MATCHES_ONLY_THE_NULL_OBJECT_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes" + REQUEST_BODY_POST_ARRAY_TYPE_MATCHES_ARRAYS_REQUEST_BODY = "/requestBody/postArrayTypeMatchesArraysRequestBody" + RESPONSE_BODY_POST_ARRAY_TYPE_MATCHES_ARRAYS_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postArrayTypeMatchesArraysResponseBodyForContentTypes" + REQUEST_BODY_POST_UNIQUEITEMS_VALIDATION_REQUEST_BODY = "/requestBody/postUniqueitemsValidationRequestBody" + RESPONSE_BODY_POST_UNIQUEITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postUniqueitemsValidationResponseBodyForContentTypes" + REQUEST_BODY_POST_UNIQUEITEMS_FALSE_VALIDATION_REQUEST_BODY = "/requestBody/postUniqueitemsFalseValidationRequestBody" + RESPONSE_BODY_POST_UNIQUEITEMS_FALSE_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES = "/responseBody/postUniqueitemsFalseValidationResponseBodyForContentTypes" diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/__init__.py new file mode 100644 index 0000000000..70345f0107 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_ALLOWS_ASCHEMA_WHICH_SHOULD_VALIDATE_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/post.py new file mode 100644 index 0000000000..51f747166d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AdditionalpropertiesAllowsASchemaWhichShouldValidate + + +request_body_additionalproperties_allows_a_schema_which_should_validate = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_additionalproperties_allows_a_schema_which_should_validate.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/post.pyi new file mode 100644 index 0000000000..fb323cc1c8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_allows_a_schema_which_should_validate_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate + +# body param +SchemaForRequestBodyApplicationJson = AdditionalpropertiesAllowsASchemaWhichShouldValidate + + +request_body_additionalproperties_allows_a_schema_which_should_validate = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_additionalproperties_allows_a_schema_which_should_validate.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesAllowsASchemaWhichShouldValidateRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_allows_a_schema_which_should_validate_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_allows_a_schema_which_should_validate_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body/__init__.py new file mode 100644 index 0000000000..6430d2326a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_additionalproperties_are_allowed_by_default_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_ARE_ALLOWED_BY_DEFAULT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body/post.py new file mode 100644 index 0000000000..7be02743e6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AdditionalpropertiesAreAllowedByDefault + + +request_body_additionalproperties_are_allowed_by_default = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_additionalproperties_are_allowed_by_default.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesAreAllowedByDefaultRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_are_allowed_by_default_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_are_allowed_by_default_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body/post.pyi new file mode 100644 index 0000000000..8155ff2963 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_are_allowed_by_default_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault + +# body param +SchemaForRequestBodyApplicationJson = AdditionalpropertiesAreAllowedByDefault + + +request_body_additionalproperties_are_allowed_by_default = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_are_allowed_by_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_additionalproperties_are_allowed_by_default.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesAreAllowedByDefaultRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_are_allowed_by_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_are_allowed_by_default_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_are_allowed_by_default_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body/__init__.py new file mode 100644 index 0000000000..96c4aff53e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_additionalproperties_can_exist_by_itself_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_CAN_EXIST_BY_ITSELF_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body/post.py new file mode 100644 index 0000000000..f561016356 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AdditionalpropertiesCanExistByItself + + +request_body_additionalproperties_can_exist_by_itself = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_additionalproperties_can_exist_by_itself.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesCanExistByItselfRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_can_exist_by_itself_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_can_exist_by_itself_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body/post.pyi new file mode 100644 index 0000000000..6ba0464fbd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_can_exist_by_itself_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself + +# body param +SchemaForRequestBodyApplicationJson = AdditionalpropertiesCanExistByItself + + +request_body_additionalproperties_can_exist_by_itself = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_can_exist_by_itself_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_additionalproperties_can_exist_by_itself.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesCanExistByItselfRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_can_exist_by_itself_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_can_exist_by_itself_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_can_exist_by_itself_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body/__init__.py new file mode 100644 index 0000000000..7777dd53d6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_additionalproperties_should_not_look_in_applicators_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ADDITIONALPROPERTIES_SHOULD_NOT_LOOK_IN_APPLICATORS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body/post.py new file mode 100644 index 0000000000..0e3ae3974b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AdditionalpropertiesShouldNotLookInApplicators + + +request_body_additionalproperties_should_not_look_in_applicators = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_additionalproperties_should_not_look_in_applicators.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body/post.pyi new file mode 100644 index 0000000000..fea43428f8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_additionalproperties_should_not_look_in_applicators_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators + +# body param +SchemaForRequestBodyApplicationJson = AdditionalpropertiesShouldNotLookInApplicators + + +request_body_additionalproperties_should_not_look_in_applicators = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_additionalproperties_should_not_look_in_applicators.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesShouldNotLookInApplicatorsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_should_not_look_in_applicators_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_should_not_look_in_applicators_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_combined_with_anyof_oneof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_combined_with_anyof_oneof_request_body/__init__.py new file mode 100644 index 0000000000..60e8ae1384 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_combined_with_anyof_oneof_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_allof_combined_with_anyof_oneof_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ALLOF_COMBINED_WITH_ANYOF_ONEOF_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_combined_with_anyof_oneof_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_combined_with_anyof_oneof_request_body/post.py new file mode 100644 index 0000000000..053e2d964a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_combined_with_anyof_oneof_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AllofCombinedWithAnyofOneof + + +request_body_allof_combined_with_anyof_oneof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_combined_with_anyof_oneof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofCombinedWithAnyofOneofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_combined_with_anyof_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_combined_with_anyof_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_combined_with_anyof_oneof_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_combined_with_anyof_oneof_request_body/post.pyi new file mode 100644 index 0000000000..e62508b3e2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_combined_with_anyof_oneof_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof + +# body param +SchemaForRequestBodyApplicationJson = AllofCombinedWithAnyofOneof + + +request_body_allof_combined_with_anyof_oneof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_combined_with_anyof_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_combined_with_anyof_oneof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofCombinedWithAnyofOneofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_combined_with_anyof_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_combined_with_anyof_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_combined_with_anyof_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_request_body/__init__.py new file mode 100644 index 0000000000..00e22cf143 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_allof_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ALLOF_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_request_body/post.py new file mode 100644 index 0000000000..89a3a94019 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof import Allof + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Allof + + +request_body_allof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_request_body/post.pyi new file mode 100644 index 0000000000..4deddd781e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof import Allof + +# body param +SchemaForRequestBodyApplicationJson = Allof + + +request_body_allof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_simple_types_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_simple_types_request_body/__init__.py new file mode 100644 index 0000000000..0a136645b8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_simple_types_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_allof_simple_types_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ALLOF_SIMPLE_TYPES_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_simple_types_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_simple_types_request_body/post.py new file mode 100644 index 0000000000..5bc90d06c4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_simple_types_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_simple_types import AllofSimpleTypes + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AllofSimpleTypes + + +request_body_allof_simple_types = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_simple_types.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofSimpleTypesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_simple_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_simple_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_simple_types_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_simple_types_request_body/post.pyi new file mode 100644 index 0000000000..f334d8eeb4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_simple_types_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_simple_types import AllofSimpleTypes + +# body param +SchemaForRequestBodyApplicationJson = AllofSimpleTypes + + +request_body_allof_simple_types = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_simple_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_simple_types.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofSimpleTypesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_simple_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_simple_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_simple_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_base_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_base_schema_request_body/__init__.py new file mode 100644 index 0000000000..65a8c436dd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_base_schema_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_allof_with_base_schema_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ALLOF_WITH_BASE_SCHEMA_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_base_schema_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_base_schema_request_body/post.py new file mode 100644 index 0000000000..0af6bbed3e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_base_schema_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AllofWithBaseSchema + + +request_body_allof_with_base_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_base_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithBaseSchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_base_schema_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_base_schema_request_body/post.pyi new file mode 100644 index 0000000000..b973fab5af --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_base_schema_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema + +# body param +SchemaForRequestBodyApplicationJson = AllofWithBaseSchema + + +request_body_allof_with_base_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_base_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithBaseSchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_one_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_one_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..1dcfbcb8c4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_one_empty_schema_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_allof_with_one_empty_schema_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ALLOF_WITH_ONE_EMPTY_SCHEMA_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_one_empty_schema_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_one_empty_schema_request_body/post.py new file mode 100644 index 0000000000..0598041551 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_one_empty_schema_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AllofWithOneEmptySchema + + +request_body_allof_with_one_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_one_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithOneEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_one_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_one_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_one_empty_schema_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_one_empty_schema_request_body/post.pyi new file mode 100644 index 0000000000..19358a62ae --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_one_empty_schema_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema + +# body param +SchemaForRequestBodyApplicationJson = AllofWithOneEmptySchema + + +request_body_allof_with_one_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_one_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithOneEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_one_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_one_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_first_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_first_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..404be3a169 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_first_empty_schema_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_allof_with_the_first_empty_schema_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ALLOF_WITH_THE_FIRST_EMPTY_SCHEMA_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_first_empty_schema_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_first_empty_schema_request_body/post.py new file mode 100644 index 0000000000..3d2e11c346 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_first_empty_schema_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AllofWithTheFirstEmptySchema + + +request_body_allof_with_the_first_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_the_first_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTheFirstEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_first_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_first_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_first_empty_schema_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_first_empty_schema_request_body/post.pyi new file mode 100644 index 0000000000..9094994b1f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_first_empty_schema_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema + +# body param +SchemaForRequestBodyApplicationJson = AllofWithTheFirstEmptySchema + + +request_body_allof_with_the_first_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_the_first_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_the_first_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTheFirstEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_the_first_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_first_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_first_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_last_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_last_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..19dd1d7abf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_last_empty_schema_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_allof_with_the_last_empty_schema_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ALLOF_WITH_THE_LAST_EMPTY_SCHEMA_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_last_empty_schema_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_last_empty_schema_request_body/post.py new file mode 100644 index 0000000000..427873e471 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_last_empty_schema_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AllofWithTheLastEmptySchema + + +request_body_allof_with_the_last_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_the_last_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTheLastEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_last_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_last_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_last_empty_schema_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_last_empty_schema_request_body/post.pyi new file mode 100644 index 0000000000..fa64bb7f00 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_the_last_empty_schema_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema + +# body param +SchemaForRequestBodyApplicationJson = AllofWithTheLastEmptySchema + + +request_body_allof_with_the_last_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_the_last_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_the_last_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTheLastEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_the_last_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_last_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_last_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_two_empty_schemas_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_two_empty_schemas_request_body/__init__.py new file mode 100644 index 0000000000..9a8175cea1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_two_empty_schemas_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_allof_with_two_empty_schemas_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ALLOF_WITH_TWO_EMPTY_SCHEMAS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_two_empty_schemas_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_two_empty_schemas_request_body/post.py new file mode 100644 index 0000000000..c47e5a9411 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_two_empty_schemas_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AllofWithTwoEmptySchemas + + +request_body_allof_with_two_empty_schemas = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_two_empty_schemas.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTwoEmptySchemasRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_two_empty_schemas_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_two_empty_schemas_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_two_empty_schemas_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_two_empty_schemas_request_body/post.pyi new file mode 100644 index 0000000000..3f4116de0f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_allof_with_two_empty_schemas_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas + +# body param +SchemaForRequestBodyApplicationJson = AllofWithTwoEmptySchemas + + +request_body_allof_with_two_empty_schemas = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_two_empty_schemas_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_allof_with_two_empty_schemas.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTwoEmptySchemasRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_two_empty_schemas_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_two_empty_schemas_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_two_empty_schemas_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_complex_types_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_complex_types_request_body/__init__.py new file mode 100644 index 0000000000..cbd8b46e5a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_complex_types_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_anyof_complex_types_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ANYOF_COMPLEX_TYPES_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_complex_types_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_complex_types_request_body/post.py new file mode 100644 index 0000000000..bc529f7e11 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_complex_types_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AnyofComplexTypes + + +request_body_anyof_complex_types = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_anyof_complex_types.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofComplexTypesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_complex_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_complex_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_complex_types_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_complex_types_request_body/post.pyi new file mode 100644 index 0000000000..8b1ea8f8ca --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_complex_types_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes + +# body param +SchemaForRequestBodyApplicationJson = AnyofComplexTypes + + +request_body_anyof_complex_types = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_anyof_complex_types.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofComplexTypesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_complex_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_complex_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_request_body/__init__.py new file mode 100644 index 0000000000..b4b0fa5ebe --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_anyof_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ANYOF_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_request_body/post.py new file mode 100644 index 0000000000..8e99ee7a3c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof import Anyof + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Anyof + + +request_body_anyof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_anyof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_request_body/post.pyi new file mode 100644 index 0000000000..69a0a26d93 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof import Anyof + +# body param +SchemaForRequestBodyApplicationJson = Anyof + + +request_body_anyof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_anyof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_base_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_base_schema_request_body/__init__.py new file mode 100644 index 0000000000..1f25c05703 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_base_schema_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_anyof_with_base_schema_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ANYOF_WITH_BASE_SCHEMA_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_base_schema_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_base_schema_request_body/post.py new file mode 100644 index 0000000000..217369cd91 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_base_schema_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AnyofWithBaseSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofWithBaseSchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_base_schema_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_base_schema_request_body/post.pyi new file mode 100644 index 0000000000..bc85fc6cd1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_base_schema_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema + +# body param +SchemaForRequestBodyApplicationJson = AnyofWithBaseSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofWithBaseSchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_one_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_one_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..7f519de28b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_one_empty_schema_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_anyof_with_one_empty_schema_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ANYOF_WITH_ONE_EMPTY_SCHEMA_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_one_empty_schema_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_one_empty_schema_request_body/post.py new file mode 100644 index 0000000000..f08f875b41 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_one_empty_schema_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AnyofWithOneEmptySchema + + +request_body_anyof_with_one_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_anyof_with_one_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofWithOneEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_one_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_one_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_one_empty_schema_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_one_empty_schema_request_body/post.pyi new file mode 100644 index 0000000000..fdd3f85a03 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_anyof_with_one_empty_schema_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema + +# body param +SchemaForRequestBodyApplicationJson = AnyofWithOneEmptySchema + + +request_body_anyof_with_one_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_with_one_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_anyof_with_one_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofWithOneEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_with_one_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_one_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_one_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_array_type_matches_arrays_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_array_type_matches_arrays_request_body/__init__.py new file mode 100644 index 0000000000..434d64c1f5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_array_type_matches_arrays_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_array_type_matches_arrays_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ARRAY_TYPE_MATCHES_ARRAYS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_array_type_matches_arrays_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_array_type_matches_arrays_request_body/post.py new file mode 100644 index 0000000000..7511003b1d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_array_type_matches_arrays_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = ArrayTypeMatchesArrays + + +request_body_array_type_matches_arrays = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_array_type_matches_arrays.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostArrayTypeMatchesArraysRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_array_type_matches_arrays_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_array_type_matches_arrays_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_array_type_matches_arrays_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_array_type_matches_arrays_request_body/post.pyi new file mode 100644 index 0000000000..672a3a3a6a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_array_type_matches_arrays_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays + +# body param +SchemaForRequestBodyApplicationJson = ArrayTypeMatchesArrays + + +request_body_array_type_matches_arrays = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_array_type_matches_arrays_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_array_type_matches_arrays.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostArrayTypeMatchesArraysRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_array_type_matches_arrays_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_array_type_matches_arrays_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_array_type_matches_arrays_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_boolean_type_matches_booleans_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_boolean_type_matches_booleans_request_body/__init__.py new file mode 100644 index 0000000000..dd529eb006 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_boolean_type_matches_booleans_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_boolean_type_matches_booleans_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_BOOLEAN_TYPE_MATCHES_BOOLEANS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_boolean_type_matches_booleans_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_boolean_type_matches_booleans_request_body/post.py new file mode 100644 index 0000000000..db22058d0f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_boolean_type_matches_booleans_request_body/post.py @@ -0,0 +1,296 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = schemas.BoolSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostBooleanTypeMatchesBooleansRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_boolean_type_matches_booleans_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_boolean_type_matches_booleans_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_boolean_type_matches_booleans_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_boolean_type_matches_booleans_request_body/post.pyi new file mode 100644 index 0000000000..b30d7be40c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_boolean_type_matches_booleans_request_body/post.pyi @@ -0,0 +1,291 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationJson = schemas.BoolSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_boolean_type_matches_booleans_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostBooleanTypeMatchesBooleansRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_boolean_type_matches_booleans_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_boolean_type_matches_booleans_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,bool, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_boolean_type_matches_booleans_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_int_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_int_request_body/__init__.py new file mode 100644 index 0000000000..1e7404f60c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_int_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_by_int_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_BY_INT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_int_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_int_request_body/post.py new file mode 100644 index 0000000000..5d69029a34 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_int_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_int import ByInt + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = ByInt + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostByIntRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_int_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_int_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_int_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_int_request_body/post.pyi new file mode 100644 index 0000000000..599b4979b6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_int_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_int import ByInt + +# body param +SchemaForRequestBodyApplicationJson = ByInt + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_int_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostByIntRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_int_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_int_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_int_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_number_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_number_request_body/__init__.py new file mode 100644 index 0000000000..f146d05f52 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_number_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_by_number_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_BY_NUMBER_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_number_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_number_request_body/post.py new file mode 100644 index 0000000000..8e84300e73 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_number_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_number import ByNumber + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = ByNumber + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostByNumberRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_number_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_number_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_number_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_number_request_body/post.pyi new file mode 100644 index 0000000000..2965ae1919 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_number_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_number import ByNumber + +# body param +SchemaForRequestBodyApplicationJson = ByNumber + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostByNumberRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_number_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_number_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_small_number_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_small_number_request_body/__init__.py new file mode 100644 index 0000000000..e3016e6929 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_small_number_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_by_small_number_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_BY_SMALL_NUMBER_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_small_number_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_small_number_request_body/post.py new file mode 100644 index 0000000000..668ee59186 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_small_number_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_small_number import BySmallNumber + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = BySmallNumber + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostBySmallNumberRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_small_number_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_small_number_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_small_number_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_small_number_request_body/post.pyi new file mode 100644 index 0000000000..adc387a8ea --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_by_small_number_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_small_number import BySmallNumber + +# body param +SchemaForRequestBodyApplicationJson = BySmallNumber + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_small_number_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostBySmallNumberRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_small_number_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_small_number_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_small_number_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_date_time_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_date_time_format_request_body/__init__.py new file mode 100644 index 0000000000..54e91fac2c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_date_time_format_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_date_time_format_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_DATE_TIME_FORMAT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_date_time_format_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_date_time_format_request_body/post.py new file mode 100644 index 0000000000..9499c4998d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_date_time_format_request_body/post.py @@ -0,0 +1,319 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.DateTimeBase, + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostDateTimeFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_date_time_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_date_time_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_date_time_format_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_date_time_format_request_body/post.pyi new file mode 100644 index 0000000000..e75c82d05c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_date_time_format_request_body/post.pyi @@ -0,0 +1,314 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.DateTimeBase, + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_date_time_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostDateTimeFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_date_time_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_date_time_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_date_time_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_email_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_email_format_request_body/__init__.py new file mode 100644 index 0000000000..ac461d949e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_email_format_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_email_format_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_EMAIL_FORMAT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_email_format_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_email_format_request_body/post.py new file mode 100644 index 0000000000..61c0e558b2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_email_format_request_body/post.py @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'email' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEmailFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_email_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_email_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_email_format_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_email_format_request_body/post.pyi new file mode 100644 index 0000000000..624a2c83bd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_email_format_request_body/post.pyi @@ -0,0 +1,313 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'email' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_email_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEmailFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_email_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_email_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_email_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with0_does_not_match_false_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with0_does_not_match_false_request_body/__init__.py new file mode 100644 index 0000000000..0d0a92e77a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with0_does_not_match_false_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_enum_with0_does_not_match_false_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ENUM_WITH0DOES_NOT_MATCH_FALSE_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with0_does_not_match_false_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with0_does_not_match_false_request_body/post.py new file mode 100644 index 0000000000..1d6fde1b75 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with0_does_not_match_false_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = EnumWith0DoesNotMatchFalse + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWith0DoesNotMatchFalseRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with0_does_not_match_false_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with0_does_not_match_false_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with0_does_not_match_false_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with0_does_not_match_false_request_body/post.pyi new file mode 100644 index 0000000000..fc3b37cec2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with0_does_not_match_false_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse + +# body param +SchemaForRequestBodyApplicationJson = EnumWith0DoesNotMatchFalse + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with0_does_not_match_false_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWith0DoesNotMatchFalseRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with0_does_not_match_false_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with0_does_not_match_false_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with0_does_not_match_false_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with1_does_not_match_true_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with1_does_not_match_true_request_body/__init__.py new file mode 100644 index 0000000000..ddc8ab9640 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with1_does_not_match_true_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_enum_with1_does_not_match_true_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ENUM_WITH1DOES_NOT_MATCH_TRUE_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with1_does_not_match_true_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with1_does_not_match_true_request_body/post.py new file mode 100644 index 0000000000..e54e98dc38 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with1_does_not_match_true_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = EnumWith1DoesNotMatchTrue + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWith1DoesNotMatchTrueRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with1_does_not_match_true_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with1_does_not_match_true_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with1_does_not_match_true_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with1_does_not_match_true_request_body/post.pyi new file mode 100644 index 0000000000..5dfa978e1f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with1_does_not_match_true_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue + +# body param +SchemaForRequestBodyApplicationJson = EnumWith1DoesNotMatchTrue + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with1_does_not_match_true_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWith1DoesNotMatchTrueRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with1_does_not_match_true_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with1_does_not_match_true_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with1_does_not_match_true_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_escaped_characters_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_escaped_characters_request_body/__init__.py new file mode 100644 index 0000000000..69670a038c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_escaped_characters_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_enum_with_escaped_characters_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ENUM_WITH_ESCAPED_CHARACTERS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_escaped_characters_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_escaped_characters_request_body/post.py new file mode 100644 index 0000000000..abf4252d66 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_escaped_characters_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = EnumWithEscapedCharacters + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithEscapedCharactersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_escaped_characters_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_escaped_characters_request_body/post.pyi new file mode 100644 index 0000000000..ae3cd9c56a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_escaped_characters_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters + +# body param +SchemaForRequestBodyApplicationJson = EnumWithEscapedCharacters + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithEscapedCharactersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_false_does_not_match0_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_false_does_not_match0_request_body/__init__.py new file mode 100644 index 0000000000..3d8993bf56 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_false_does_not_match0_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_enum_with_false_does_not_match0_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ENUM_WITH_FALSE_DOES_NOT_MATCH0REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_false_does_not_match0_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_false_does_not_match0_request_body/post.py new file mode 100644 index 0000000000..f13496bc39 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_false_does_not_match0_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = EnumWithFalseDoesNotMatch0 + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithFalseDoesNotMatch0RequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_false_does_not_match0_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_false_does_not_match0_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_false_does_not_match0_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_false_does_not_match0_request_body/post.pyi new file mode 100644 index 0000000000..d2a2fb5b1a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_false_does_not_match0_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 + +# body param +SchemaForRequestBodyApplicationJson = EnumWithFalseDoesNotMatch0 + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_false_does_not_match0_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithFalseDoesNotMatch0RequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_false_does_not_match0_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_false_does_not_match0_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_false_does_not_match0_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_true_does_not_match1_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_true_does_not_match1_request_body/__init__.py new file mode 100644 index 0000000000..7cec94a70c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_true_does_not_match1_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_enum_with_true_does_not_match1_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ENUM_WITH_TRUE_DOES_NOT_MATCH1REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_true_does_not_match1_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_true_does_not_match1_request_body/post.py new file mode 100644 index 0000000000..cdda0d34c5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_true_does_not_match1_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = EnumWithTrueDoesNotMatch1 + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithTrueDoesNotMatch1RequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_true_does_not_match1_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_true_does_not_match1_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_true_does_not_match1_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_true_does_not_match1_request_body/post.pyi new file mode 100644 index 0000000000..ede86715a9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enum_with_true_does_not_match1_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 + +# body param +SchemaForRequestBodyApplicationJson = EnumWithTrueDoesNotMatch1 + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_true_does_not_match1_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithTrueDoesNotMatch1RequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_true_does_not_match1_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_true_does_not_match1_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_true_does_not_match1_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enums_in_properties_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enums_in_properties_request_body/__init__.py new file mode 100644 index 0000000000..9c1d975460 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enums_in_properties_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_enums_in_properties_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ENUMS_IN_PROPERTIES_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enums_in_properties_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enums_in_properties_request_body/post.py new file mode 100644 index 0000000000..dc053602f5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enums_in_properties_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enums_in_properties import EnumsInProperties + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = EnumsInProperties + + +request_body_enums_in_properties = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_enums_in_properties.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumsInPropertiesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enums_in_properties_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enums_in_properties_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enums_in_properties_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enums_in_properties_request_body/post.pyi new file mode 100644 index 0000000000..082bb8a018 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_enums_in_properties_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enums_in_properties import EnumsInProperties + +# body param +SchemaForRequestBodyApplicationJson = EnumsInProperties + + +request_body_enums_in_properties = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enums_in_properties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_enums_in_properties.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumsInPropertiesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enums_in_properties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enums_in_properties_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enums_in_properties_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_forbidden_property_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_forbidden_property_request_body/__init__.py new file mode 100644 index 0000000000..3d25a7311c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_forbidden_property_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_forbidden_property_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_FORBIDDEN_PROPERTY_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_forbidden_property_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_forbidden_property_request_body/post.py new file mode 100644 index 0000000000..e1e4462162 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_forbidden_property_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.forbidden_property import ForbiddenProperty + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = ForbiddenProperty + + +request_body_forbidden_property = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_forbidden_property.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostForbiddenPropertyRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_forbidden_property_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_forbidden_property_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_forbidden_property_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_forbidden_property_request_body/post.pyi new file mode 100644 index 0000000000..688fcb76f9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_forbidden_property_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.forbidden_property import ForbiddenProperty + +# body param +SchemaForRequestBodyApplicationJson = ForbiddenProperty + + +request_body_forbidden_property = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_forbidden_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_forbidden_property.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostForbiddenPropertyRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_forbidden_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_forbidden_property_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_forbidden_property_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_hostname_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_hostname_format_request_body/__init__.py new file mode 100644 index 0000000000..c02c074d76 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_hostname_format_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_hostname_format_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_HOSTNAME_FORMAT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_hostname_format_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_hostname_format_request_body/post.py new file mode 100644 index 0000000000..531dc56c32 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_hostname_format_request_body/post.py @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'hostname' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostHostnameFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_hostname_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_hostname_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_hostname_format_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_hostname_format_request_body/post.pyi new file mode 100644 index 0000000000..96b59201e8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_hostname_format_request_body/post.pyi @@ -0,0 +1,313 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'hostname' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_hostname_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostHostnameFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_hostname_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_hostname_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_hostname_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_integer_type_matches_integers_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_integer_type_matches_integers_request_body/__init__.py new file mode 100644 index 0000000000..4be9e60848 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_integer_type_matches_integers_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_integer_type_matches_integers_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_INTEGER_TYPE_MATCHES_INTEGERS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_integer_type_matches_integers_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_integer_type_matches_integers_request_body/post.py new file mode 100644 index 0000000000..746839d1cd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_integer_type_matches_integers_request_body/post.py @@ -0,0 +1,296 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = schemas.IntSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIntegerTypeMatchesIntegersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_integer_type_matches_integers_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_integer_type_matches_integers_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_integer_type_matches_integers_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_integer_type_matches_integers_request_body/post.pyi new file mode 100644 index 0000000000..a2d00a4f70 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_integer_type_matches_integers_request_body/post.pyi @@ -0,0 +1,291 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationJson = schemas.IntSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_integer_type_matches_integers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIntegerTypeMatchesIntegersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_integer_type_matches_integers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_integer_type_matches_integers_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_integer_type_matches_integers_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/__init__.py new file mode 100644 index 0000000000..f60497ab73 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_INVALID_INSTANCE_SHOULD_NOT_RAISE_ERROR_WHEN_FLOAT_DIVISION_INF_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/post.py new file mode 100644 index 0000000000..a437389877 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/post.pyi new file mode 100644 index 0000000000..15c6c30122 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf + +# body param +SchemaForRequestBodyApplicationJson = InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_instance_should_not_raise_error_when_float_division_inf_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_string_value_for_default_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_string_value_for_default_request_body/__init__.py new file mode 100644 index 0000000000..b00384bdb1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_string_value_for_default_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_invalid_string_value_for_default_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_INVALID_STRING_VALUE_FOR_DEFAULT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_string_value_for_default_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_string_value_for_default_request_body/post.py new file mode 100644 index 0000000000..27ac856881 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_string_value_for_default_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = InvalidStringValueForDefault + + +request_body_invalid_string_value_for_default = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_invalid_string_value_for_default.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostInvalidStringValueForDefaultRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_string_value_for_default_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_string_value_for_default_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_string_value_for_default_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_string_value_for_default_request_body/post.pyi new file mode 100644 index 0000000000..00c9f71b02 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_invalid_string_value_for_default_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault + +# body param +SchemaForRequestBodyApplicationJson = InvalidStringValueForDefault + + +request_body_invalid_string_value_for_default = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_invalid_string_value_for_default_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_invalid_string_value_for_default.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostInvalidStringValueForDefaultRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_invalid_string_value_for_default_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_string_value_for_default_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_string_value_for_default_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv4_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv4_format_request_body/__init__.py new file mode 100644 index 0000000000..e71b237c89 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv4_format_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_ipv4_format_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_IPV4FORMAT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv4_format_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv4_format_request_body/post.py new file mode 100644 index 0000000000..9ffdb8d5be --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv4_format_request_body/post.py @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'ipv4' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIpv4FormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv4_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv4_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv4_format_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv4_format_request_body/post.pyi new file mode 100644 index 0000000000..21a1c8c504 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv4_format_request_body/post.pyi @@ -0,0 +1,313 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'ipv4' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ipv4_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIpv4FormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ipv4_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv4_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv4_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv6_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv6_format_request_body/__init__.py new file mode 100644 index 0000000000..f9b9074867 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv6_format_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_ipv6_format_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_IPV6FORMAT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv6_format_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv6_format_request_body/post.py new file mode 100644 index 0000000000..8fb701cc61 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv6_format_request_body/post.py @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'ipv6' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIpv6FormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv6_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv6_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv6_format_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv6_format_request_body/post.pyi new file mode 100644 index 0000000000..b50a09052e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ipv6_format_request_body/post.pyi @@ -0,0 +1,313 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'ipv6' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ipv6_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIpv6FormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ipv6_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv6_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv6_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_json_pointer_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_json_pointer_format_request_body/__init__.py new file mode 100644 index 0000000000..aed1ba09bc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_json_pointer_format_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_json_pointer_format_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_JSON_POINTER_FORMAT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_json_pointer_format_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_json_pointer_format_request_body/post.py new file mode 100644 index 0000000000..1ad92bc825 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_json_pointer_format_request_body/post.py @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'json-pointer' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostJsonPointerFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_json_pointer_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_json_pointer_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_json_pointer_format_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_json_pointer_format_request_body/post.pyi new file mode 100644 index 0000000000..4e2d9ef6c5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_json_pointer_format_request_body/post.pyi @@ -0,0 +1,313 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'json-pointer' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_json_pointer_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostJsonPointerFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_json_pointer_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_json_pointer_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_json_pointer_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_request_body/__init__.py new file mode 100644 index 0000000000..0c3a542459 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_maximum_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MAXIMUM_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_request_body/post.py new file mode 100644 index 0000000000..982f83c735 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maximum_validation import MaximumValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MaximumValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaximumValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_request_body/post.pyi new file mode 100644 index 0000000000..a0723cca70 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maximum_validation import MaximumValidation + +# body param +SchemaForRequestBodyApplicationJson = MaximumValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maximum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaximumValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maximum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body/__init__.py new file mode 100644 index 0000000000..01a0a917a1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_maximum_validation_with_unsigned_integer_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MAXIMUM_VALIDATION_WITH_UNSIGNED_INTEGER_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body/post.py new file mode 100644 index 0000000000..fcf0f9c4e2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MaximumValidationWithUnsignedInteger + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaximumValidationWithUnsignedIntegerRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_with_unsigned_integer_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_with_unsigned_integer_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body/post.pyi new file mode 100644 index 0000000000..4e5c945af5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maximum_validation_with_unsigned_integer_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger + +# body param +SchemaForRequestBodyApplicationJson = MaximumValidationWithUnsignedInteger + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maximum_validation_with_unsigned_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaximumValidationWithUnsignedIntegerRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maximum_validation_with_unsigned_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_with_unsigned_integer_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_with_unsigned_integer_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxitems_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxitems_validation_request_body/__init__.py new file mode 100644 index 0000000000..86e4dc9f14 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxitems_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_maxitems_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MAXITEMS_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxitems_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxitems_validation_request_body/post.py new file mode 100644 index 0000000000..08f984ff02 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxitems_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxitems_validation import MaxitemsValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MaxitemsValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxitemsValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxitems_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxitems_validation_request_body/post.pyi new file mode 100644 index 0000000000..a42d2f09c2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxitems_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxitems_validation import MaxitemsValidation + +# body param +SchemaForRequestBodyApplicationJson = MaxitemsValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxitemsValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxlength_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxlength_validation_request_body/__init__.py new file mode 100644 index 0000000000..40b927a792 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxlength_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_maxlength_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MAXLENGTH_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxlength_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxlength_validation_request_body/post.py new file mode 100644 index 0000000000..d9f0c7ca46 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxlength_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxlength_validation import MaxlengthValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MaxlengthValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxlengthValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxlength_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxlength_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxlength_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxlength_validation_request_body/post.pyi new file mode 100644 index 0000000000..b2e42052a3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxlength_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxlength_validation import MaxlengthValidation + +# body param +SchemaForRequestBodyApplicationJson = MaxlengthValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxlengthValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxlength_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxlength_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body/__init__.py new file mode 100644 index 0000000000..d0abb2424f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_maxproperties0_means_the_object_is_empty_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MAXPROPERTIES0MEANS_THE_OBJECT_IS_EMPTY_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body/post.py new file mode 100644 index 0000000000..8df9e45dde --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Maxproperties0MeansTheObjectIsEmpty + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxproperties0MeansTheObjectIsEmptyRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties0_means_the_object_is_empty_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties0_means_the_object_is_empty_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body/post.pyi new file mode 100644 index 0000000000..544af50745 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties0_means_the_object_is_empty_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty + +# body param +SchemaForRequestBodyApplicationJson = Maxproperties0MeansTheObjectIsEmpty + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxproperties0_means_the_object_is_empty_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxproperties0MeansTheObjectIsEmptyRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxproperties0_means_the_object_is_empty_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties0_means_the_object_is_empty_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties0_means_the_object_is_empty_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties_validation_request_body/__init__.py new file mode 100644 index 0000000000..40f9c62162 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_maxproperties_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MAXPROPERTIES_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties_validation_request_body/post.py new file mode 100644 index 0000000000..67fd2d8ab4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MaxpropertiesValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxpropertiesValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties_validation_request_body/post.pyi new file mode 100644 index 0000000000..5119d69b5e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_maxproperties_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation + +# body param +SchemaForRequestBodyApplicationJson = MaxpropertiesValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxpropertiesValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_request_body/__init__.py new file mode 100644 index 0000000000..a2ebaf49e2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_minimum_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MINIMUM_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_request_body/post.py new file mode 100644 index 0000000000..b1e1c0d227 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minimum_validation import MinimumValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MinimumValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinimumValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_request_body/post.pyi new file mode 100644 index 0000000000..0e7fa1996f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minimum_validation import MinimumValidation + +# body param +SchemaForRequestBodyApplicationJson = MinimumValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minimum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinimumValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minimum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_with_signed_integer_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_with_signed_integer_request_body/__init__.py new file mode 100644 index 0000000000..55f61d940e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_with_signed_integer_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_minimum_validation_with_signed_integer_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MINIMUM_VALIDATION_WITH_SIGNED_INTEGER_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_with_signed_integer_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_with_signed_integer_request_body/post.py new file mode 100644 index 0000000000..78129065be --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_with_signed_integer_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MinimumValidationWithSignedInteger + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinimumValidationWithSignedIntegerRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_with_signed_integer_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_with_signed_integer_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_with_signed_integer_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_with_signed_integer_request_body/post.pyi new file mode 100644 index 0000000000..c8539721b2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minimum_validation_with_signed_integer_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger + +# body param +SchemaForRequestBodyApplicationJson = MinimumValidationWithSignedInteger + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minimum_validation_with_signed_integer_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinimumValidationWithSignedIntegerRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minimum_validation_with_signed_integer_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_with_signed_integer_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_with_signed_integer_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minitems_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minitems_validation_request_body/__init__.py new file mode 100644 index 0000000000..d4df22e904 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minitems_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_minitems_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MINITEMS_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minitems_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minitems_validation_request_body/post.py new file mode 100644 index 0000000000..e6282c3f44 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minitems_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minitems_validation import MinitemsValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MinitemsValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinitemsValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minitems_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minitems_validation_request_body/post.pyi new file mode 100644 index 0000000000..d755c0d755 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minitems_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minitems_validation import MinitemsValidation + +# body param +SchemaForRequestBodyApplicationJson = MinitemsValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinitemsValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minlength_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minlength_validation_request_body/__init__.py new file mode 100644 index 0000000000..b68e6e60ee --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minlength_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_minlength_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MINLENGTH_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minlength_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minlength_validation_request_body/post.py new file mode 100644 index 0000000000..192b4f1d15 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minlength_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minlength_validation import MinlengthValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MinlengthValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinlengthValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minlength_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minlength_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minlength_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minlength_validation_request_body/post.pyi new file mode 100644 index 0000000000..7436c84bb2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minlength_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minlength_validation import MinlengthValidation + +# body param +SchemaForRequestBodyApplicationJson = MinlengthValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minlength_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinlengthValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minlength_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minlength_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minlength_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minproperties_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minproperties_validation_request_body/__init__.py new file mode 100644 index 0000000000..b76e1db9aa --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minproperties_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_minproperties_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_MINPROPERTIES_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minproperties_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minproperties_validation_request_body/post.py new file mode 100644 index 0000000000..e616271212 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minproperties_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minproperties_validation import MinpropertiesValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = MinpropertiesValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinpropertiesValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minproperties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minproperties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minproperties_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minproperties_validation_request_body/post.pyi new file mode 100644 index 0000000000..2d4602b4aa --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_minproperties_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minproperties_validation import MinpropertiesValidation + +# body param +SchemaForRequestBodyApplicationJson = MinpropertiesValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minproperties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinpropertiesValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minproperties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minproperties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minproperties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body/__init__.py new file mode 100644 index 0000000000..6c1f7d73a4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_nested_allof_to_check_validation_semantics_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_NESTED_ALLOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body/post.py new file mode 100644 index 0000000000..04886b3f9f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = NestedAllofToCheckValidationSemantics + + +request_body_nested_allof_to_check_validation_semantics = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_nested_allof_to_check_validation_semantics.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedAllofToCheckValidationSemanticsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_allof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_allof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body/post.pyi new file mode 100644 index 0000000000..ba2e00fa21 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_allof_to_check_validation_semantics_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics + +# body param +SchemaForRequestBodyApplicationJson = NestedAllofToCheckValidationSemantics + + +request_body_nested_allof_to_check_validation_semantics = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_allof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_nested_allof_to_check_validation_semantics.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedAllofToCheckValidationSemanticsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_allof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_allof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_allof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body/__init__.py new file mode 100644 index 0000000000..e7b3408e53 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_nested_anyof_to_check_validation_semantics_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_NESTED_ANYOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body/post.py new file mode 100644 index 0000000000..ddfa4e71d8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = NestedAnyofToCheckValidationSemantics + + +request_body_nested_anyof_to_check_validation_semantics = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_nested_anyof_to_check_validation_semantics.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedAnyofToCheckValidationSemanticsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_anyof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_anyof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body/post.pyi new file mode 100644 index 0000000000..b660117c48 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_anyof_to_check_validation_semantics_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics + +# body param +SchemaForRequestBodyApplicationJson = NestedAnyofToCheckValidationSemantics + + +request_body_nested_anyof_to_check_validation_semantics = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_anyof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_nested_anyof_to_check_validation_semantics.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedAnyofToCheckValidationSemanticsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_anyof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_anyof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_anyof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_items_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_items_request_body/__init__.py new file mode 100644 index 0000000000..b38abd5342 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_items_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_nested_items_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_NESTED_ITEMS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_items_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_items_request_body/post.py new file mode 100644 index 0000000000..2072cebde7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_items_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_items import NestedItems + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = NestedItems + + +request_body_nested_items = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_nested_items.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedItemsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_items_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_items_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_items_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_items_request_body/post.pyi new file mode 100644 index 0000000000..f46fe5841f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_items_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_items import NestedItems + +# body param +SchemaForRequestBodyApplicationJson = NestedItems + + +request_body_nested_items = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_nested_items.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedItemsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_items_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_items_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body/__init__.py new file mode 100644 index 0000000000..8a24e9c066 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_nested_oneof_to_check_validation_semantics_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_NESTED_ONEOF_TO_CHECK_VALIDATION_SEMANTICS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body/post.py new file mode 100644 index 0000000000..eeeb6bfee2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = NestedOneofToCheckValidationSemantics + + +request_body_nested_oneof_to_check_validation_semantics = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_nested_oneof_to_check_validation_semantics.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedOneofToCheckValidationSemanticsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_oneof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_oneof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body/post.pyi new file mode 100644 index 0000000000..fa49ae4894 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nested_oneof_to_check_validation_semantics_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics + +# body param +SchemaForRequestBodyApplicationJson = NestedOneofToCheckValidationSemantics + + +request_body_nested_oneof_to_check_validation_semantics = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_oneof_to_check_validation_semantics_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_nested_oneof_to_check_validation_semantics.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedOneofToCheckValidationSemanticsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_oneof_to_check_validation_semantics_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_oneof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_oneof_to_check_validation_semantics_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_more_complex_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_more_complex_schema_request_body/__init__.py new file mode 100644 index 0000000000..c4fccb535c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_more_complex_schema_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_not_more_complex_schema_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_NOT_MORE_COMPLEX_SCHEMA_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_more_complex_schema_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_more_complex_schema_request_body/post.py new file mode 100644 index 0000000000..7d44a344cc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_more_complex_schema_request_body/post.py @@ -0,0 +1,367 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class not_schema( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'not_schema': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNotMoreComplexSchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_more_complex_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_more_complex_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_more_complex_schema_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_more_complex_schema_request_body/post.pyi new file mode 100644 index 0000000000..5f1d96b0b8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_more_complex_schema_request_body/post.pyi @@ -0,0 +1,362 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class not_schema( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'not_schema': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_not_more_complex_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNotMoreComplexSchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_not_more_complex_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_more_complex_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_more_complex_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_request_body/__init__.py new file mode 100644 index 0000000000..f37c1cc913 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_not_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_NOT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_request_body/post.py new file mode 100644 index 0000000000..1fdc493740 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_request_body/post.py @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + not_schema = schemas.IntSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNotRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_request_body/post.pyi new file mode 100644 index 0000000000..ef2e02253e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_not_request_body/post.pyi @@ -0,0 +1,313 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + not_schema = schemas.IntSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNotRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nul_characters_in_strings_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nul_characters_in_strings_request_body/__init__.py new file mode 100644 index 0000000000..a6d59aa973 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nul_characters_in_strings_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_nul_characters_in_strings_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_NUL_CHARACTERS_IN_STRINGS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nul_characters_in_strings_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nul_characters_in_strings_request_body/post.py new file mode 100644 index 0000000000..d4b9e53a03 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nul_characters_in_strings_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = NulCharactersInStrings + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNulCharactersInStringsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nul_characters_in_strings_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nul_characters_in_strings_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nul_characters_in_strings_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nul_characters_in_strings_request_body/post.pyi new file mode 100644 index 0000000000..7445caa5a5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_nul_characters_in_strings_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings + +# body param +SchemaForRequestBodyApplicationJson = NulCharactersInStrings + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nul_characters_in_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNulCharactersInStringsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nul_characters_in_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nul_characters_in_strings_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nul_characters_in_strings_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_null_type_matches_only_the_null_object_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_null_type_matches_only_the_null_object_request_body/__init__.py new file mode 100644 index 0000000000..c4be57a944 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_null_type_matches_only_the_null_object_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_null_type_matches_only_the_null_object_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_NULL_TYPE_MATCHES_ONLY_THE_NULL_OBJECT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_null_type_matches_only_the_null_object_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_null_type_matches_only_the_null_object_request_body/post.py new file mode 100644 index 0000000000..c94d8b66af --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_null_type_matches_only_the_null_object_request_body/post.py @@ -0,0 +1,296 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = schemas.NoneSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNullTypeMatchesOnlyTheNullObjectRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_null_type_matches_only_the_null_object_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_null_type_matches_only_the_null_object_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_null_type_matches_only_the_null_object_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_null_type_matches_only_the_null_object_request_body/post.pyi new file mode 100644 index 0000000000..6adc097d24 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_null_type_matches_only_the_null_object_request_body/post.pyi @@ -0,0 +1,291 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationJson = schemas.NoneSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_null_type_matches_only_the_null_object_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNullTypeMatchesOnlyTheNullObjectRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_null_type_matches_only_the_null_object_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_null_type_matches_only_the_null_object_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,None, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_null_type_matches_only_the_null_object_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_number_type_matches_numbers_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_number_type_matches_numbers_request_body/__init__.py new file mode 100644 index 0000000000..b95a838eac --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_number_type_matches_numbers_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_number_type_matches_numbers_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_NUMBER_TYPE_MATCHES_NUMBERS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_number_type_matches_numbers_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_number_type_matches_numbers_request_body/post.py new file mode 100644 index 0000000000..1ca4120948 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_number_type_matches_numbers_request_body/post.py @@ -0,0 +1,296 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = schemas.NumberSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNumberTypeMatchesNumbersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_number_type_matches_numbers_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_number_type_matches_numbers_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_number_type_matches_numbers_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_number_type_matches_numbers_request_body/post.pyi new file mode 100644 index 0000000000..f4f08b5ead --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_number_type_matches_numbers_request_body/post.pyi @@ -0,0 +1,291 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationJson = schemas.NumberSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_number_type_matches_numbers_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNumberTypeMatchesNumbersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_number_type_matches_numbers_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_number_type_matches_numbers_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,decimal.Decimal, int, float, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_number_type_matches_numbers_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_properties_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_properties_validation_request_body/__init__.py new file mode 100644 index 0000000000..d7d33f2aef --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_properties_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_object_properties_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_OBJECT_PROPERTIES_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_properties_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_properties_validation_request_body/post.py new file mode 100644 index 0000000000..6b2af7b5d7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_properties_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = ObjectPropertiesValidation + + +request_body_object_properties_validation = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_object_properties_validation.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostObjectPropertiesValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_properties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_properties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_properties_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_properties_validation_request_body/post.pyi new file mode 100644 index 0000000000..0a0ecb89fe --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_properties_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation + +# body param +SchemaForRequestBodyApplicationJson = ObjectPropertiesValidation + + +request_body_object_properties_validation = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_object_properties_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_object_properties_validation.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostObjectPropertiesValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_object_properties_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_properties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_properties_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_type_matches_objects_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_type_matches_objects_request_body/__init__.py new file mode 100644 index 0000000000..d125b30a97 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_type_matches_objects_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_object_type_matches_objects_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_OBJECT_TYPE_MATCHES_OBJECTS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_type_matches_objects_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_type_matches_objects_request_body/post.py new file mode 100644 index 0000000000..9458ed3bdb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_type_matches_objects_request_body/post.py @@ -0,0 +1,296 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = schemas.DictSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostObjectTypeMatchesObjectsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_type_matches_objects_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_type_matches_objects_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_type_matches_objects_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_type_matches_objects_request_body/post.pyi new file mode 100644 index 0000000000..26a3aa0e9d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_object_type_matches_objects_request_body/post.pyi @@ -0,0 +1,291 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationJson = schemas.DictSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_object_type_matches_objects_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostObjectTypeMatchesObjectsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_object_type_matches_objects_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_type_matches_objects_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_type_matches_objects_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_complex_types_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_complex_types_request_body/__init__.py new file mode 100644 index 0000000000..1b089b411f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_complex_types_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_oneof_complex_types_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ONEOF_COMPLEX_TYPES_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_complex_types_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_complex_types_request_body/post.py new file mode 100644 index 0000000000..1e9c85a757 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_complex_types_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_complex_types import OneofComplexTypes + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = OneofComplexTypes + + +request_body_oneof_complex_types = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_oneof_complex_types.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofComplexTypesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_complex_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_complex_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_complex_types_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_complex_types_request_body/post.pyi new file mode 100644 index 0000000000..5c61455e78 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_complex_types_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_complex_types import OneofComplexTypes + +# body param +SchemaForRequestBodyApplicationJson = OneofComplexTypes + + +request_body_oneof_complex_types = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_complex_types_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_oneof_complex_types.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofComplexTypesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_complex_types_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_complex_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_complex_types_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_request_body/__init__.py new file mode 100644 index 0000000000..c19aa40ea9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_oneof_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ONEOF_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_request_body/post.py new file mode 100644 index 0000000000..bc372832e5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof import Oneof + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Oneof + + +request_body_oneof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_oneof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_request_body/post.pyi new file mode 100644 index 0000000000..78a9a83c94 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof import Oneof + +# body param +SchemaForRequestBodyApplicationJson = Oneof + + +request_body_oneof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_oneof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_base_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_base_schema_request_body/__init__.py new file mode 100644 index 0000000000..605ed77fbe --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_base_schema_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_oneof_with_base_schema_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ONEOF_WITH_BASE_SCHEMA_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_base_schema_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_base_schema_request_body/post.py new file mode 100644 index 0000000000..8d00db16b5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_base_schema_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = OneofWithBaseSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithBaseSchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_base_schema_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_base_schema_request_body/post.pyi new file mode 100644 index 0000000000..0d4fe45599 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_base_schema_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema + +# body param +SchemaForRequestBodyApplicationJson = OneofWithBaseSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_base_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithBaseSchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_base_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_base_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_empty_schema_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_empty_schema_request_body/__init__.py new file mode 100644 index 0000000000..ba897616f7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_empty_schema_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_oneof_with_empty_schema_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ONEOF_WITH_EMPTY_SCHEMA_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_empty_schema_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_empty_schema_request_body/post.py new file mode 100644 index 0000000000..de00a1e19e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_empty_schema_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = OneofWithEmptySchema + + +request_body_oneof_with_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_oneof_with_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_empty_schema_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_empty_schema_request_body/post.pyi new file mode 100644 index 0000000000..2d41910403 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_empty_schema_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema + +# body param +SchemaForRequestBodyApplicationJson = OneofWithEmptySchema + + +request_body_oneof_with_empty_schema = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_empty_schema_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_oneof_with_empty_schema.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithEmptySchemaRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_empty_schema_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_empty_schema_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_required_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_required_request_body/__init__.py new file mode 100644 index 0000000000..748f67c50b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_required_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_oneof_with_required_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_ONEOF_WITH_REQUIRED_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_required_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_required_request_body/post.py new file mode 100644 index 0000000000..e32e6df399 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_required_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_required import OneofWithRequired + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = OneofWithRequired + + +request_body_oneof_with_required = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_oneof_with_required.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithRequiredRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_required_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_required_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_required_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_required_request_body/post.pyi new file mode 100644 index 0000000000..b75ad8f9a9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_oneof_with_required_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_required import OneofWithRequired + +# body param +SchemaForRequestBodyApplicationJson = OneofWithRequired + + +request_body_oneof_with_required = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_required_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_oneof_with_required.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithRequiredRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_required_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_required_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_required_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_is_not_anchored_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_is_not_anchored_request_body/__init__.py new file mode 100644 index 0000000000..30f8d5d82d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_is_not_anchored_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_pattern_is_not_anchored_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_PATTERN_IS_NOT_ANCHORED_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_is_not_anchored_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_is_not_anchored_request_body/post.py new file mode 100644 index 0000000000..c5120a7acd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_is_not_anchored_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = PatternIsNotAnchored + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPatternIsNotAnchoredRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_is_not_anchored_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_is_not_anchored_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_is_not_anchored_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_is_not_anchored_request_body/post.pyi new file mode 100644 index 0000000000..1848470356 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_is_not_anchored_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored + +# body param +SchemaForRequestBodyApplicationJson = PatternIsNotAnchored + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_pattern_is_not_anchored_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPatternIsNotAnchoredRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_pattern_is_not_anchored_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_is_not_anchored_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_is_not_anchored_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_validation_request_body/__init__.py new file mode 100644 index 0000000000..9f48e004c5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_pattern_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_PATTERN_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_validation_request_body/post.py new file mode 100644 index 0000000000..422b433e46 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.pattern_validation import PatternValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = PatternValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPatternValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_validation_request_body/post.pyi new file mode 100644 index 0000000000..d812670966 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_pattern_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.pattern_validation import PatternValidation + +# body param +SchemaForRequestBodyApplicationJson = PatternValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_pattern_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPatternValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_pattern_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_properties_with_escaped_characters_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_properties_with_escaped_characters_request_body/__init__.py new file mode 100644 index 0000000000..0191726a9d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_properties_with_escaped_characters_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_properties_with_escaped_characters_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_PROPERTIES_WITH_ESCAPED_CHARACTERS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_properties_with_escaped_characters_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_properties_with_escaped_characters_request_body/post.py new file mode 100644 index 0000000000..bcc74a2ae9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_properties_with_escaped_characters_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = PropertiesWithEscapedCharacters + + +request_body_properties_with_escaped_characters = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_properties_with_escaped_characters.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPropertiesWithEscapedCharactersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_properties_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_properties_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_properties_with_escaped_characters_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_properties_with_escaped_characters_request_body/post.pyi new file mode 100644 index 0000000000..1bab1c15f1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_properties_with_escaped_characters_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters + +# body param +SchemaForRequestBodyApplicationJson = PropertiesWithEscapedCharacters + + +request_body_properties_with_escaped_characters = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_properties_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_properties_with_escaped_characters.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPropertiesWithEscapedCharactersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_properties_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_properties_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_properties_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body/__init__.py new file mode 100644 index 0000000000..d75d1defcf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_property_named_ref_that_is_not_a_reference_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_PROPERTY_NAMED_REF_THAT_IS_NOT_AREFERENCE_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body/post.py new file mode 100644 index 0000000000..a176ec4b34 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = PropertyNamedRefThatIsNotAReference + + +request_body_property_named_ref_that_is_not_a_reference = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_property_named_ref_that_is_not_a_reference.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPropertyNamedRefThatIsNotAReferenceRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_property_named_ref_that_is_not_a_reference_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_property_named_ref_that_is_not_a_reference_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body/post.pyi new file mode 100644 index 0000000000..ff3985bce8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_property_named_ref_that_is_not_a_reference_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference + +# body param +SchemaForRequestBodyApplicationJson = PropertyNamedRefThatIsNotAReference + + +request_body_property_named_ref_that_is_not_a_reference = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_property_named_ref_that_is_not_a_reference_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_property_named_ref_that_is_not_a_reference.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPropertyNamedRefThatIsNotAReferenceRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_property_named_ref_that_is_not_a_reference_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_property_named_ref_that_is_not_a_reference_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_property_named_ref_that_is_not_a_reference_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_additionalproperties_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_additionalproperties_request_body/__init__.py new file mode 100644 index 0000000000..39685b6807 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_additionalproperties_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_ref_in_additionalproperties_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REF_IN_ADDITIONALPROPERTIES_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_additionalproperties_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_additionalproperties_request_body/post.py new file mode 100644 index 0000000000..baae0992b5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_additionalproperties_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = RefInAdditionalproperties + + +request_body_ref_in_additionalproperties = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_additionalproperties.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAdditionalpropertiesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_additionalproperties_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_additionalproperties_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_additionalproperties_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_additionalproperties_request_body/post.pyi new file mode 100644 index 0000000000..ae66e236ba --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_additionalproperties_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties + +# body param +SchemaForRequestBodyApplicationJson = RefInAdditionalproperties + + +request_body_ref_in_additionalproperties = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_additionalproperties_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_additionalproperties.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAdditionalpropertiesRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_additionalproperties_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_additionalproperties_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_additionalproperties_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_allof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_allof_request_body/__init__.py new file mode 100644 index 0000000000..6865649fc9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_allof_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_ref_in_allof_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REF_IN_ALLOF_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_allof_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_allof_request_body/post.py new file mode 100644 index 0000000000..32d5d6cba9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_allof_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_allof import RefInAllof + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = RefInAllof + + +request_body_ref_in_allof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_allof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAllofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_allof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_allof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_allof_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_allof_request_body/post.pyi new file mode 100644 index 0000000000..6eddfe043b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_allof_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_allof import RefInAllof + +# body param +SchemaForRequestBodyApplicationJson = RefInAllof + + +request_body_ref_in_allof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_allof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_allof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAllofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_allof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_allof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_allof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_anyof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_anyof_request_body/__init__.py new file mode 100644 index 0000000000..9eff1a1046 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_anyof_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_ref_in_anyof_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REF_IN_ANYOF_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_anyof_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_anyof_request_body/post.py new file mode 100644 index 0000000000..c61b0c0346 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_anyof_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_anyof import RefInAnyof + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = RefInAnyof + + +request_body_ref_in_anyof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_anyof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAnyofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_anyof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_anyof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_anyof_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_anyof_request_body/post.pyi new file mode 100644 index 0000000000..61d129a8cd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_anyof_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_anyof import RefInAnyof + +# body param +SchemaForRequestBodyApplicationJson = RefInAnyof + + +request_body_ref_in_anyof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_anyof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_anyof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAnyofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_anyof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_anyof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_anyof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_items_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_items_request_body/__init__.py new file mode 100644 index 0000000000..cfe5fc1bde --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_items_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_ref_in_items_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REF_IN_ITEMS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_items_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_items_request_body/post.py new file mode 100644 index 0000000000..3cf5261cef --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_items_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_items import RefInItems + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = RefInItems + + +request_body_ref_in_items = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_items.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInItemsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_items_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_items_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_items_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_items_request_body/post.pyi new file mode 100644 index 0000000000..b41e000b84 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_items_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_items import RefInItems + +# body param +SchemaForRequestBodyApplicationJson = RefInItems + + +request_body_ref_in_items = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_items_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_items.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInItemsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_items_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_items_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_items_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_not_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_not_request_body/__init__.py new file mode 100644 index 0000000000..3d3ad62339 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_not_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_ref_in_not_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REF_IN_NOT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_not_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_not_request_body/post.py new file mode 100644 index 0000000000..16778e01bf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_not_request_body/post.py @@ -0,0 +1,323 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + @staticmethod + def not_schema() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInNotRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_not_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_not_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_not_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_not_request_body/post.pyi new file mode 100644 index 0000000000..18e7489d24 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_not_request_body/post.pyi @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + @staticmethod + def not_schema() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_not_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInNotRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_not_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_not_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_not_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_oneof_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_oneof_request_body/__init__.py new file mode 100644 index 0000000000..3cf7e2dfb0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_oneof_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_ref_in_oneof_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REF_IN_ONEOF_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_oneof_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_oneof_request_body/post.py new file mode 100644 index 0000000000..f1dc48460c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_oneof_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_oneof import RefInOneof + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = RefInOneof + + +request_body_ref_in_oneof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_oneof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInOneofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_oneof_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_oneof_request_body/post.pyi new file mode 100644 index 0000000000..e3ca8f0a1b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_oneof_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_oneof import RefInOneof + +# body param +SchemaForRequestBodyApplicationJson = RefInOneof + + +request_body_ref_in_oneof = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_oneof_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_oneof.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInOneofRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_oneof_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_oneof_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_property_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_property_request_body/__init__.py new file mode 100644 index 0000000000..e531594000 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_property_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_ref_in_property_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REF_IN_PROPERTY_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_property_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_property_request_body/post.py new file mode 100644 index 0000000000..bc58c723b4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_property_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_property import RefInProperty + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = RefInProperty + + +request_body_ref_in_property = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_property.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInPropertyRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_property_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_property_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_property_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_property_request_body/post.pyi new file mode 100644 index 0000000000..105713baa0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_ref_in_property_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_property import RefInProperty + +# body param +SchemaForRequestBodyApplicationJson = RefInProperty + + +request_body_ref_in_property = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_property_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_ref_in_property.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInPropertyRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_property_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_property_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_property_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_default_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_default_validation_request_body/__init__.py new file mode 100644 index 0000000000..c281e13df0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_default_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_required_default_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REQUIRED_DEFAULT_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_default_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_default_validation_request_body/post.py new file mode 100644 index 0000000000..b290ef0c3c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_default_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_default_validation import RequiredDefaultValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = RequiredDefaultValidation + + +request_body_required_default_validation = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_required_default_validation.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredDefaultValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_default_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_default_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_default_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_default_validation_request_body/post.pyi new file mode 100644 index 0000000000..78d8bb0262 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_default_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_default_validation import RequiredDefaultValidation + +# body param +SchemaForRequestBodyApplicationJson = RequiredDefaultValidation + + +request_body_required_default_validation = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_default_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_required_default_validation.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredDefaultValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_default_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_default_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_default_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_validation_request_body/__init__.py new file mode 100644 index 0000000000..64140f0c88 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_required_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REQUIRED_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_validation_request_body/post.py new file mode 100644 index 0000000000..31366c3fd8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_validation import RequiredValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = RequiredValidation + + +request_body_required_validation = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_required_validation.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_validation_request_body/post.pyi new file mode 100644 index 0000000000..a0149cd11b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_validation import RequiredValidation + +# body param +SchemaForRequestBodyApplicationJson = RequiredValidation + + +request_body_required_validation = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_required_validation.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_empty_array_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_empty_array_request_body/__init__.py new file mode 100644 index 0000000000..2b789e16f4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_empty_array_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_required_with_empty_array_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REQUIRED_WITH_EMPTY_ARRAY_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_empty_array_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_empty_array_request_body/post.py new file mode 100644 index 0000000000..828d01bed2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_empty_array_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = RequiredWithEmptyArray + + +request_body_required_with_empty_array = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_required_with_empty_array.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredWithEmptyArrayRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_empty_array_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_empty_array_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_empty_array_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_empty_array_request_body/post.pyi new file mode 100644 index 0000000000..6490beb525 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_empty_array_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray + +# body param +SchemaForRequestBodyApplicationJson = RequiredWithEmptyArray + + +request_body_required_with_empty_array = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_with_empty_array_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_required_with_empty_array.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredWithEmptyArrayRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_with_empty_array_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_empty_array_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_empty_array_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_escaped_characters_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_escaped_characters_request_body/__init__.py new file mode 100644 index 0000000000..84963ff881 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_escaped_characters_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_required_with_escaped_characters_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_REQUIRED_WITH_ESCAPED_CHARACTERS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_escaped_characters_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_escaped_characters_request_body/post.py new file mode 100644 index 0000000000..5546b1c722 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_escaped_characters_request_body/post.py @@ -0,0 +1,326 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + required = { + "foo\"bar", + "foo\nbar", + "foo\fbar", + "foo\tbar", + "foo\rbar", + "foo\\bar", + } + + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredWithEscapedCharactersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_escaped_characters_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_escaped_characters_request_body/post.pyi new file mode 100644 index 0000000000..4b9319331a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_required_with_escaped_characters_request_body/post.pyi @@ -0,0 +1,321 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + required = { + "foo\"bar", + "foo\nbar", + "foo\fbar", + "foo\tbar", + "foo\rbar", + "foo\\bar", + } + + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_with_escaped_characters_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredWithEscapedCharactersRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_with_escaped_characters_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_escaped_characters_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_simple_enum_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_simple_enum_validation_request_body/__init__.py new file mode 100644 index 0000000000..9fbc857f5f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_simple_enum_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_simple_enum_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_SIMPLE_ENUM_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_simple_enum_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_simple_enum_validation_request_body/post.py new file mode 100644 index 0000000000..48ce45ab21 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_simple_enum_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = SimpleEnumValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostSimpleEnumValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_simple_enum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_simple_enum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_simple_enum_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_simple_enum_validation_request_body/post.pyi new file mode 100644 index 0000000000..b0ba5e5753 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_simple_enum_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation + +# body param +SchemaForRequestBodyApplicationJson = SimpleEnumValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_simple_enum_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostSimpleEnumValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_simple_enum_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_simple_enum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_simple_enum_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_string_type_matches_strings_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_string_type_matches_strings_request_body/__init__.py new file mode 100644 index 0000000000..a5975daf71 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_string_type_matches_strings_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_string_type_matches_strings_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_STRING_TYPE_MATCHES_STRINGS_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_string_type_matches_strings_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_string_type_matches_strings_request_body/post.py new file mode 100644 index 0000000000..6db3472e65 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_string_type_matches_strings_request_body/post.py @@ -0,0 +1,296 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = schemas.StrSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostStringTypeMatchesStringsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_string_type_matches_strings_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_string_type_matches_strings_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_string_type_matches_strings_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_string_type_matches_strings_request_body/post.pyi new file mode 100644 index 0000000000..241d59964c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_string_type_matches_strings_request_body/post.pyi @@ -0,0 +1,291 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationJson = schemas.StrSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_string_type_matches_strings_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostStringTypeMatchesStringsRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_string_type_matches_strings_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_string_type_matches_strings_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,str, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_string_type_matches_strings_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/__init__.py new file mode 100644 index 0000000000..19bb1f267e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_THE_DEFAULT_KEYWORD_DOES_NOT_DO_ANYTHING_IF_THE_PROPERTY_IS_MISSING_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/post.py new file mode 100644 index 0000000000..baaf238e68 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing + + +request_body_the_default_keyword_does_not_do_anything_if_the_property_is_missing = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_the_default_keyword_does_not_do_anything_if_the_property_is_missing.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/post.pyi new file mode 100644 index 0000000000..50cbe14533 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing + +# body param +SchemaForRequestBodyApplicationJson = TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing + + +request_body_the_default_keyword_does_not_do_anything_if_the_property_is_missing = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_the_default_keyword_does_not_do_anything_if_the_property_is_missing.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_false_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_false_validation_request_body/__init__.py new file mode 100644 index 0000000000..cfdcae95f6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_false_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_uniqueitems_false_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_UNIQUEITEMS_FALSE_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_false_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_false_validation_request_body/post.py new file mode 100644 index 0000000000..2d9e8e8482 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_false_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = UniqueitemsFalseValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUniqueitemsFalseValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_false_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_false_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_false_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_false_validation_request_body/post.pyi new file mode 100644 index 0000000000..f1cb3b3ce3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_false_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation + +# body param +SchemaForRequestBodyApplicationJson = UniqueitemsFalseValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uniqueitems_false_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUniqueitemsFalseValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uniqueitems_false_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_false_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_false_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_validation_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_validation_request_body/__init__.py new file mode 100644 index 0000000000..e3afc7776c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_validation_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_uniqueitems_validation_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_UNIQUEITEMS_VALIDATION_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_validation_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_validation_request_body/post.py new file mode 100644 index 0000000000..75738c8906 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_validation_request_body/post.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = UniqueitemsValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUniqueitemsValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_validation_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_validation_request_body/post.pyi new file mode 100644 index 0000000000..471f7aa06b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uniqueitems_validation_request_body/post.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation + +# body param +SchemaForRequestBodyApplicationJson = UniqueitemsValidation + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uniqueitems_validation_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUniqueitemsValidationRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uniqueitems_validation_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_validation_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_format_request_body/__init__.py new file mode 100644 index 0000000000..8b7bbf53e8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_format_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_uri_format_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_URI_FORMAT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_format_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_format_request_body/post.py new file mode 100644 index 0000000000..01f1e01a38 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_format_request_body/post.py @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_format_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_format_request_body/post.pyi new file mode 100644 index 0000000000..bd57141d4f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_format_request_body/post.pyi @@ -0,0 +1,313 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_reference_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_reference_format_request_body/__init__.py new file mode 100644 index 0000000000..75781edad7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_reference_format_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_uri_reference_format_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_URI_REFERENCE_FORMAT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_reference_format_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_reference_format_request_body/post.py new file mode 100644 index 0000000000..ac7b2ca12e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_reference_format_request_body/post.py @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri-reference' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriReferenceFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_reference_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_reference_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_reference_format_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_reference_format_request_body/post.pyi new file mode 100644 index 0000000000..32efe64f38 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_reference_format_request_body/post.pyi @@ -0,0 +1,313 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri-reference' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_reference_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriReferenceFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_reference_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_reference_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_reference_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_template_format_request_body/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_template_format_request_body/__init__.py new file mode 100644 index 0000000000..5c3430004e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_template_format_request_body/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.request_body_post_uri_template_format_request_body import Api + +from unit_test_api.paths import PathValues + +path = PathValues.REQUEST_BODY_POST_URI_TEMPLATE_FORMAT_REQUEST_BODY \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_template_format_request_body/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_template_format_request_body/post.py new file mode 100644 index 0000000000..ecbb8a5992 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_template_format_request_body/post.py @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri-template' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriTemplateFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_template_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_template_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_template_format_request_body/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_template_format_request_body/post.pyi new file mode 100644 index 0000000000..c11c280ca8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/request_body_post_uri_template_format_request_body/post.pyi @@ -0,0 +1,313 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri-template' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_template_format_request_body_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriTemplateFormatRequestBody(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_template_format_request_body( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_template_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_template_format_request_body_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..952a3a3781 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_ALLOWS_ASCHEMA_WHICH_SHOULD_VALIDATE_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/post.py new file mode 100644 index 0000000000..a26ef4d234 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AdditionalpropertiesAllowsASchemaWhichShouldValidate + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..d1507bf9f2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_allows_a_schema_which_should_validate import AdditionalpropertiesAllowsASchemaWhichShouldValidate + +SchemaFor200ResponseBodyApplicationJson = AdditionalpropertiesAllowsASchemaWhichShouldValidate + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesAllowsASchemaWhichShouldValidateResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_allows_a_schema_which_should_validate_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..8ba816b84c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_ARE_ALLOWED_BY_DEFAULT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/post.py new file mode 100644 index 0000000000..dbe7ce6e67 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AdditionalpropertiesAreAllowedByDefault + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_are_allowed_by_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_are_allowed_by_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_are_allowed_by_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_are_allowed_by_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..c248434a47 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_are_allowed_by_default_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_are_allowed_by_default import AdditionalpropertiesAreAllowedByDefault + +SchemaFor200ResponseBodyApplicationJson = AdditionalpropertiesAreAllowedByDefault + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesAreAllowedByDefaultResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_are_allowed_by_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_are_allowed_by_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_are_allowed_by_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_are_allowed_by_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_are_allowed_by_default_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..2c17dfc57e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_CAN_EXIST_BY_ITSELF_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/post.py new file mode 100644 index 0000000000..a4195f8bec --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AdditionalpropertiesCanExistByItself + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_can_exist_by_itself_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_can_exist_by_itself_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_can_exist_by_itself_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_can_exist_by_itself_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..82150f4679 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_can_exist_by_itself_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_can_exist_by_itself import AdditionalpropertiesCanExistByItself + +SchemaFor200ResponseBodyApplicationJson = AdditionalpropertiesCanExistByItself + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesCanExistByItselfResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_can_exist_by_itself_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_can_exist_by_itself_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_can_exist_by_itself_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_can_exist_by_itself_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_can_exist_by_itself_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..91245978b9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ADDITIONALPROPERTIES_SHOULD_NOT_LOOK_IN_APPLICATORS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/post.py new file mode 100644 index 0000000000..3783c4bff5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AdditionalpropertiesShouldNotLookInApplicators + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..901c227bbb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.additionalproperties_should_not_look_in_applicators import AdditionalpropertiesShouldNotLookInApplicators + +SchemaFor200ResponseBodyApplicationJson = AdditionalpropertiesShouldNotLookInApplicators + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAdditionalpropertiesShouldNotLookInApplicatorsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_additionalproperties_should_not_look_in_applicators_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..c2954dad02 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ALLOF_COMBINED_WITH_ANYOF_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/post.py new file mode 100644 index 0000000000..ea70220749 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AllofCombinedWithAnyofOneof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_combined_with_anyof_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_combined_with_anyof_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_combined_with_anyof_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_combined_with_anyof_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..966c85fbff --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_combined_with_anyof_oneof_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_combined_with_anyof_oneof import AllofCombinedWithAnyofOneof + +SchemaFor200ResponseBodyApplicationJson = AllofCombinedWithAnyofOneof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofCombinedWithAnyofOneofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_combined_with_anyof_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_combined_with_anyof_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_combined_with_anyof_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_combined_with_anyof_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_combined_with_anyof_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..966421655a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_allof_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ALLOF_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_response_body_for_content_types/post.py new file mode 100644 index 0000000000..4c7e148515 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof import Allof + +from . import path + +SchemaFor200ResponseBodyApplicationJson = Allof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..983e72c024 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof import Allof + +SchemaFor200ResponseBodyApplicationJson = Allof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_simple_types_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_simple_types_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..d3d3b345f6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_simple_types_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_allof_simple_types_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ALLOF_SIMPLE_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_simple_types_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_simple_types_response_body_for_content_types/post.py new file mode 100644 index 0000000000..04dc25c28d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_simple_types_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_simple_types import AllofSimpleTypes + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AllofSimpleTypes + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_simple_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_simple_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_simple_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_simple_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofSimpleTypesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_simple_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_simple_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_simple_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_simple_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_simple_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_simple_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_simple_types_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_simple_types_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..17fb582dc3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_simple_types_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_simple_types import AllofSimpleTypes + +SchemaFor200ResponseBodyApplicationJson = AllofSimpleTypes + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_simple_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_simple_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_simple_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_simple_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofSimpleTypesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_simple_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_simple_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_simple_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_simple_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_simple_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_simple_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_base_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_base_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..ead19c4102 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_base_schema_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_allof_with_base_schema_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ALLOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_base_schema_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_base_schema_response_body_for_content_types/post.py new file mode 100644 index 0000000000..e0ec00ff54 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_base_schema_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AllofWithBaseSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithBaseSchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_base_schema_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_base_schema_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..203f7e9833 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_base_schema_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_base_schema import AllofWithBaseSchema + +SchemaFor200ResponseBodyApplicationJson = AllofWithBaseSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithBaseSchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..5b925dbe84 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_allof_with_one_empty_schema_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ALLOF_WITH_ONE_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types/post.py new file mode 100644 index 0000000000..db5c47fe16 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AllofWithOneEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithOneEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..6458869c87 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_one_empty_schema_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_one_empty_schema import AllofWithOneEmptySchema + +SchemaFor200ResponseBodyApplicationJson = AllofWithOneEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithOneEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_one_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..d2158fd591 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ALLOF_WITH_THE_FIRST_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/post.py new file mode 100644 index 0000000000..1cc370ae25 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AllofWithTheFirstEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_the_first_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_the_first_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_the_first_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_the_first_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..885e09eaa5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_first_empty_schema_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_the_first_empty_schema import AllofWithTheFirstEmptySchema + +SchemaFor200ResponseBodyApplicationJson = AllofWithTheFirstEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTheFirstEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_the_first_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_the_first_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_the_first_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_the_first_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_first_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..96db6f89d5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ALLOF_WITH_THE_LAST_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/post.py new file mode 100644 index 0000000000..8e550c0e2a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AllofWithTheLastEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_the_last_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_the_last_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_the_last_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_the_last_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..7ce32b9623 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_the_last_empty_schema_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_the_last_empty_schema import AllofWithTheLastEmptySchema + +SchemaFor200ResponseBodyApplicationJson = AllofWithTheLastEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTheLastEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_the_last_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_the_last_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_the_last_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_the_last_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_the_last_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..fcb8c8f7ec --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_allof_with_two_empty_schemas_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ALLOF_WITH_TWO_EMPTY_SCHEMAS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/post.py new file mode 100644 index 0000000000..a8336a1284 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AllofWithTwoEmptySchemas + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTwoEmptySchemasResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_two_empty_schemas_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_two_empty_schemas_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_two_empty_schemas_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_two_empty_schemas_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..ad1d640063 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_allof_with_two_empty_schemas_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.allof_with_two_empty_schemas import AllofWithTwoEmptySchemas + +SchemaFor200ResponseBodyApplicationJson = AllofWithTwoEmptySchemas + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAllofWithTwoEmptySchemasResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_allof_with_two_empty_schemas_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_allof_with_two_empty_schemas_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_allof_with_two_empty_schemas_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_allof_with_two_empty_schemas_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_allof_with_two_empty_schemas_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_complex_types_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_complex_types_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..b028f3bec7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_complex_types_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_anyof_complex_types_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ANYOF_COMPLEX_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_complex_types_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_complex_types_response_body_for_content_types/post.py new file mode 100644 index 0000000000..61104a1a4b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_complex_types_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AnyofComplexTypes + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofComplexTypesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_complex_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_complex_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_complex_types_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_complex_types_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..686b9db9f7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_complex_types_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_complex_types import AnyofComplexTypes + +SchemaFor200ResponseBodyApplicationJson = AnyofComplexTypes + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofComplexTypesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_complex_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_complex_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..de1893c9ea --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_anyof_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ANYOF_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_response_body_for_content_types/post.py new file mode 100644 index 0000000000..4f1056d49a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof import Anyof + +from . import path + +SchemaFor200ResponseBodyApplicationJson = Anyof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..d95e2fb269 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof import Anyof + +SchemaFor200ResponseBodyApplicationJson = Anyof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..bbb82f9ffc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_anyof_with_base_schema_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ANYOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types/post.py new file mode 100644 index 0000000000..cb7e1a5bdb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AnyofWithBaseSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofWithBaseSchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..4a1ef40878 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_base_schema_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_with_base_schema import AnyofWithBaseSchema + +SchemaFor200ResponseBodyApplicationJson = AnyofWithBaseSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofWithBaseSchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..ceb7349121 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_anyof_with_one_empty_schema_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ANYOF_WITH_ONE_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/post.py new file mode 100644 index 0000000000..dc5293f4aa --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema + +from . import path + +SchemaFor200ResponseBodyApplicationJson = AnyofWithOneEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofWithOneEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..2937f62ea2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_anyof_with_one_empty_schema_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.anyof_with_one_empty_schema import AnyofWithOneEmptySchema + +SchemaFor200ResponseBodyApplicationJson = AnyofWithOneEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostAnyofWithOneEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_anyof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_anyof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_anyof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_anyof_with_one_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_anyof_with_one_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..2fdd3453b9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_array_type_matches_arrays_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ARRAY_TYPE_MATCHES_ARRAYS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types/post.py new file mode 100644 index 0000000000..5cc8abd84a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays + +from . import path + +SchemaFor200ResponseBodyApplicationJson = ArrayTypeMatchesArrays + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_array_type_matches_arrays_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_array_type_matches_arrays_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_array_type_matches_arrays_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_array_type_matches_arrays_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostArrayTypeMatchesArraysResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_array_type_matches_arrays_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_array_type_matches_arrays_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_array_type_matches_arrays_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_array_type_matches_arrays_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_array_type_matches_arrays_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_array_type_matches_arrays_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..de0a2d5865 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_array_type_matches_arrays_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.array_type_matches_arrays import ArrayTypeMatchesArrays + +SchemaFor200ResponseBodyApplicationJson = ArrayTypeMatchesArrays + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_array_type_matches_arrays_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_array_type_matches_arrays_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_array_type_matches_arrays_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_array_type_matches_arrays_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostArrayTypeMatchesArraysResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_array_type_matches_arrays_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_array_type_matches_arrays_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_array_type_matches_arrays_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_array_type_matches_arrays_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_array_type_matches_arrays_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_array_type_matches_arrays_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..bb12060f2d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_boolean_type_matches_booleans_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_BOOLEAN_TYPE_MATCHES_BOOLEANS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types/post.py new file mode 100644 index 0000000000..db449dae16 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types/post.py @@ -0,0 +1,229 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +SchemaFor200ResponseBodyApplicationJson = schemas.BoolSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostBooleanTypeMatchesBooleansResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_boolean_type_matches_booleans_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_boolean_type_matches_booleans_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_boolean_type_matches_booleans_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_boolean_type_matches_booleans_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..8a82428ed2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_boolean_type_matches_booleans_response_body_for_content_types/post.pyi @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +SchemaFor200ResponseBodyApplicationJson = schemas.BoolSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostBooleanTypeMatchesBooleansResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_boolean_type_matches_booleans_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_boolean_type_matches_booleans_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_boolean_type_matches_booleans_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_boolean_type_matches_booleans_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_boolean_type_matches_booleans_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_int_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_int_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..65dc15fb38 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_int_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_by_int_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_BY_INT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_int_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_int_response_body_for_content_types/post.py new file mode 100644 index 0000000000..7b33589740 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_int_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_int import ByInt + +from . import path + +SchemaFor200ResponseBodyApplicationJson = ByInt + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_int_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_int_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_int_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_int_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostByIntResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_int_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_int_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_int_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_int_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_int_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_int_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_int_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_int_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..ddbd626545 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_int_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_int import ByInt + +SchemaFor200ResponseBodyApplicationJson = ByInt + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_int_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_int_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_int_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_int_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostByIntResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_int_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_int_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_int_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_int_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_int_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_int_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_number_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_number_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..c4a2ebe963 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_number_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_by_number_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_BY_NUMBER_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_number_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_number_response_body_for_content_types/post.py new file mode 100644 index 0000000000..5ca4e97bda --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_number_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_number import ByNumber + +from . import path + +SchemaFor200ResponseBodyApplicationJson = ByNumber + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostByNumberResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_number_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_number_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_number_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_number_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..3b889482a1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_number_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_number import ByNumber + +SchemaFor200ResponseBodyApplicationJson = ByNumber + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostByNumberResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_number_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_number_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_small_number_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_small_number_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..8006bf4884 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_small_number_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_by_small_number_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_BY_SMALL_NUMBER_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_small_number_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_small_number_response_body_for_content_types/post.py new file mode 100644 index 0000000000..919173804e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_small_number_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_small_number import BySmallNumber + +from . import path + +SchemaFor200ResponseBodyApplicationJson = BySmallNumber + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_small_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_small_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_small_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_small_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostBySmallNumberResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_small_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_small_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_small_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_small_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_small_number_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_small_number_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_small_number_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_small_number_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..624538655e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_by_small_number_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.by_small_number import BySmallNumber + +SchemaFor200ResponseBodyApplicationJson = BySmallNumber + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_by_small_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_by_small_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_by_small_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_by_small_number_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostBySmallNumberResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_by_small_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_by_small_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_by_small_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_by_small_number_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_small_number_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_by_small_number_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_date_time_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_date_time_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..da7708ad05 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_date_time_format_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_date_time_format_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_DATE_TIME_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_date_time_format_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_date_time_format_response_body_for_content_types/post.py new file mode 100644 index 0000000000..7671740107 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_date_time_format_response_body_for_content_types/post.py @@ -0,0 +1,252 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.DateTimeBase, + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_date_time_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_date_time_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_date_time_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_date_time_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostDateTimeFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_date_time_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_date_time_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_date_time_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_date_time_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_date_time_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_date_time_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_date_time_format_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_date_time_format_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..af7e94cd9a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_date_time_format_response_body_for_content_types/post.pyi @@ -0,0 +1,247 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.DateTimeBase, + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_date_time_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_date_time_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_date_time_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_date_time_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostDateTimeFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_date_time_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_date_time_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_date_time_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_date_time_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_date_time_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_date_time_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_email_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_email_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..0946a580d7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_email_format_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_email_format_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_EMAIL_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_email_format_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_email_format_response_body_for_content_types/post.py new file mode 100644 index 0000000000..84ceb9f853 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_email_format_response_body_for_content_types/post.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'email' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_email_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_email_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_email_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_email_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEmailFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_email_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_email_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_email_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_email_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_email_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_email_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_email_format_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_email_format_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..873bf91676 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_email_format_response_body_for_content_types/post.pyi @@ -0,0 +1,246 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'email' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_email_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_email_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_email_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_email_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEmailFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_email_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_email_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_email_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_email_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_email_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_email_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..974d688885 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_enum_with0_does_not_match_false_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ENUM_WITH0DOES_NOT_MATCH_FALSE_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/post.py new file mode 100644 index 0000000000..b5b4c1392a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse + +from . import path + +SchemaFor200ResponseBodyApplicationJson = EnumWith0DoesNotMatchFalse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with0_does_not_match_false_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with0_does_not_match_false_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with0_does_not_match_false_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with0_does_not_match_false_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..3bafefb7aa --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with0_does_not_match_false_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with0_does_not_match_false import EnumWith0DoesNotMatchFalse + +SchemaFor200ResponseBodyApplicationJson = EnumWith0DoesNotMatchFalse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWith0DoesNotMatchFalseResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with0_does_not_match_false_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with0_does_not_match_false_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with0_does_not_match_false_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with0_does_not_match_false_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with0_does_not_match_false_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..2234fa84bf --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_enum_with1_does_not_match_true_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ENUM_WITH1DOES_NOT_MATCH_TRUE_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/post.py new file mode 100644 index 0000000000..2b2e15e491 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue + +from . import path + +SchemaFor200ResponseBodyApplicationJson = EnumWith1DoesNotMatchTrue + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with1_does_not_match_true_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with1_does_not_match_true_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with1_does_not_match_true_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with1_does_not_match_true_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..207a6acb0c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with1_does_not_match_true_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with1_does_not_match_true import EnumWith1DoesNotMatchTrue + +SchemaFor200ResponseBodyApplicationJson = EnumWith1DoesNotMatchTrue + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWith1DoesNotMatchTrueResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with1_does_not_match_true_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with1_does_not_match_true_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with1_does_not_match_true_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with1_does_not_match_true_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with1_does_not_match_true_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..29277c539a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_enum_with_escaped_characters_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ENUM_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types/post.py new file mode 100644 index 0000000000..c3a46becdd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters + +from . import path + +SchemaFor200ResponseBodyApplicationJson = EnumWithEscapedCharacters + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithEscapedCharactersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..1f98603a73 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_escaped_characters_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_escaped_characters import EnumWithEscapedCharacters + +SchemaFor200ResponseBodyApplicationJson = EnumWithEscapedCharacters + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithEscapedCharactersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..754d48ea26 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_enum_with_false_does_not_match0_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ENUM_WITH_FALSE_DOES_NOT_MATCH0RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/post.py new file mode 100644 index 0000000000..7230c68ea2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 + +from . import path + +SchemaFor200ResponseBodyApplicationJson = EnumWithFalseDoesNotMatch0 + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_false_does_not_match0_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_false_does_not_match0_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_false_does_not_match0_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_false_does_not_match0_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..8c5611e6ec --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_false_does_not_match0_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_false_does_not_match0 import EnumWithFalseDoesNotMatch0 + +SchemaFor200ResponseBodyApplicationJson = EnumWithFalseDoesNotMatch0 + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithFalseDoesNotMatch0ResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_false_does_not_match0_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_false_does_not_match0_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_false_does_not_match0_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_false_does_not_match0_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_false_does_not_match0_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..49e7a0e789 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_enum_with_true_does_not_match1_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ENUM_WITH_TRUE_DOES_NOT_MATCH1RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/post.py new file mode 100644 index 0000000000..fef0e8c61e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 + +from . import path + +SchemaFor200ResponseBodyApplicationJson = EnumWithTrueDoesNotMatch1 + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_true_does_not_match1_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_true_does_not_match1_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_true_does_not_match1_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_true_does_not_match1_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..fdcec3d0b3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enum_with_true_does_not_match1_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enum_with_true_does_not_match1 import EnumWithTrueDoesNotMatch1 + +SchemaFor200ResponseBodyApplicationJson = EnumWithTrueDoesNotMatch1 + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumWithTrueDoesNotMatch1ResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enum_with_true_does_not_match1_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enum_with_true_does_not_match1_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enum_with_true_does_not_match1_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enum_with_true_does_not_match1_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enum_with_true_does_not_match1_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enums_in_properties_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enums_in_properties_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..9b16fee8d8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enums_in_properties_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_enums_in_properties_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ENUMS_IN_PROPERTIES_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enums_in_properties_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enums_in_properties_response_body_for_content_types/post.py new file mode 100644 index 0000000000..ad9d898342 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enums_in_properties_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enums_in_properties import EnumsInProperties + +from . import path + +SchemaFor200ResponseBodyApplicationJson = EnumsInProperties + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enums_in_properties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enums_in_properties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enums_in_properties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enums_in_properties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumsInPropertiesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enums_in_properties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enums_in_properties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enums_in_properties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enums_in_properties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enums_in_properties_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enums_in_properties_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enums_in_properties_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enums_in_properties_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..f3e7352a9d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_enums_in_properties_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.enums_in_properties import EnumsInProperties + +SchemaFor200ResponseBodyApplicationJson = EnumsInProperties + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_enums_in_properties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_enums_in_properties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_enums_in_properties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_enums_in_properties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostEnumsInPropertiesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_enums_in_properties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_enums_in_properties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_enums_in_properties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_enums_in_properties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enums_in_properties_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_enums_in_properties_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_forbidden_property_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_forbidden_property_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..2aa3240b7b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_forbidden_property_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_forbidden_property_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_FORBIDDEN_PROPERTY_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_forbidden_property_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_forbidden_property_response_body_for_content_types/post.py new file mode 100644 index 0000000000..0d7ba92648 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_forbidden_property_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.forbidden_property import ForbiddenProperty + +from . import path + +SchemaFor200ResponseBodyApplicationJson = ForbiddenProperty + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_forbidden_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_forbidden_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_forbidden_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_forbidden_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostForbiddenPropertyResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_forbidden_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_forbidden_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_forbidden_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_forbidden_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_forbidden_property_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_forbidden_property_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_forbidden_property_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_forbidden_property_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..fdb543ed0c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_forbidden_property_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.forbidden_property import ForbiddenProperty + +SchemaFor200ResponseBodyApplicationJson = ForbiddenProperty + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_forbidden_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_forbidden_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_forbidden_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_forbidden_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostForbiddenPropertyResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_forbidden_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_forbidden_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_forbidden_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_forbidden_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_forbidden_property_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_forbidden_property_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_hostname_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_hostname_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..fda9b15ffc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_hostname_format_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_hostname_format_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_HOSTNAME_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_hostname_format_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_hostname_format_response_body_for_content_types/post.py new file mode 100644 index 0000000000..db71744866 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_hostname_format_response_body_for_content_types/post.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'hostname' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_hostname_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_hostname_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_hostname_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_hostname_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostHostnameFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_hostname_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_hostname_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_hostname_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_hostname_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_hostname_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_hostname_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_hostname_format_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_hostname_format_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..5e743f86d8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_hostname_format_response_body_for_content_types/post.pyi @@ -0,0 +1,246 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'hostname' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_hostname_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_hostname_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_hostname_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_hostname_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostHostnameFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_hostname_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_hostname_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_hostname_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_hostname_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_hostname_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_hostname_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..cc00a644c9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_integer_type_matches_integers_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_INTEGER_TYPE_MATCHES_INTEGERS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types/post.py new file mode 100644 index 0000000000..9c89b09ba7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types/post.py @@ -0,0 +1,229 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +SchemaFor200ResponseBodyApplicationJson = schemas.IntSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_integer_type_matches_integers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_integer_type_matches_integers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_integer_type_matches_integers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_integer_type_matches_integers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIntegerTypeMatchesIntegersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_integer_type_matches_integers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_integer_type_matches_integers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_integer_type_matches_integers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_integer_type_matches_integers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_integer_type_matches_integers_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_integer_type_matches_integers_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..d8c15f8b3e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_integer_type_matches_integers_response_body_for_content_types/post.pyi @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +SchemaFor200ResponseBodyApplicationJson = schemas.IntSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_integer_type_matches_integers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_integer_type_matches_integers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_integer_type_matches_integers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_integer_type_matches_integers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIntegerTypeMatchesIntegersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_integer_type_matches_integers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_integer_type_matches_integers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_integer_type_matches_integers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_integer_type_matches_integers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_integer_type_matches_integers_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_integer_type_matches_integers_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..511449f662 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_INVALID_INSTANCE_SHOULD_NOT_RAISE_ERROR_WHEN_FLOAT_DIVISION_INF_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/post.py new file mode 100644 index 0000000000..42efb7a3b9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf + +from . import path + +SchemaFor200ResponseBodyApplicationJson = InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..e9a1d5381c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.invalid_instance_should_not_raise_error_when_float_division_inf import InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf + +SchemaFor200ResponseBodyApplicationJson = InvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInf + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostInvalidInstanceShouldNotRaiseErrorWhenFloatDivisionInfResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_instance_should_not_raise_error_when_float_division_inf_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..fb4cadd116 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_invalid_string_value_for_default_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_INVALID_STRING_VALUE_FOR_DEFAULT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types/post.py new file mode 100644 index 0000000000..3efddb842f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault + +from . import path + +SchemaFor200ResponseBodyApplicationJson = InvalidStringValueForDefault + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_invalid_string_value_for_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_invalid_string_value_for_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_invalid_string_value_for_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_invalid_string_value_for_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostInvalidStringValueForDefaultResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_invalid_string_value_for_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_invalid_string_value_for_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_invalid_string_value_for_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_invalid_string_value_for_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_string_value_for_default_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_string_value_for_default_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..3ddd4b967d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_invalid_string_value_for_default_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.invalid_string_value_for_default import InvalidStringValueForDefault + +SchemaFor200ResponseBodyApplicationJson = InvalidStringValueForDefault + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_invalid_string_value_for_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_invalid_string_value_for_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_invalid_string_value_for_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_invalid_string_value_for_default_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostInvalidStringValueForDefaultResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_invalid_string_value_for_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_invalid_string_value_for_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_invalid_string_value_for_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_invalid_string_value_for_default_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_string_value_for_default_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_invalid_string_value_for_default_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv4_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv4_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..1b7b9c3555 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv4_format_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_ipv4_format_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_IPV4FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv4_format_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv4_format_response_body_for_content_types/post.py new file mode 100644 index 0000000000..3a909408c1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv4_format_response_body_for_content_types/post.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'ipv4' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ipv4_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ipv4_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ipv4_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ipv4_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIpv4FormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ipv4_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ipv4_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ipv4_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ipv4_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv4_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv4_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv4_format_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv4_format_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..c33a67b768 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv4_format_response_body_for_content_types/post.pyi @@ -0,0 +1,246 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'ipv4' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ipv4_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ipv4_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ipv4_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ipv4_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIpv4FormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ipv4_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ipv4_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ipv4_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ipv4_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv4_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv4_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv6_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv6_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..a1919a789e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv6_format_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_ipv6_format_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_IPV6FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv6_format_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv6_format_response_body_for_content_types/post.py new file mode 100644 index 0000000000..50675e4975 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv6_format_response_body_for_content_types/post.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'ipv6' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ipv6_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ipv6_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ipv6_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ipv6_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIpv6FormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ipv6_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ipv6_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ipv6_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ipv6_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv6_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv6_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv6_format_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv6_format_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..671be4e1b4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ipv6_format_response_body_for_content_types/post.pyi @@ -0,0 +1,246 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'ipv6' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ipv6_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ipv6_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ipv6_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ipv6_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostIpv6FormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ipv6_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ipv6_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ipv6_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ipv6_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv6_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ipv6_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_json_pointer_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_json_pointer_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..bd56842c09 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_json_pointer_format_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_json_pointer_format_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_JSON_POINTER_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_json_pointer_format_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_json_pointer_format_response_body_for_content_types/post.py new file mode 100644 index 0000000000..e14fec5a32 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_json_pointer_format_response_body_for_content_types/post.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'json-pointer' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_json_pointer_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_json_pointer_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_json_pointer_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_json_pointer_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostJsonPointerFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_json_pointer_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_json_pointer_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_json_pointer_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_json_pointer_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_json_pointer_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_json_pointer_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_json_pointer_format_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_json_pointer_format_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..b15178f375 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_json_pointer_format_response_body_for_content_types/post.pyi @@ -0,0 +1,246 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'json-pointer' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_json_pointer_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_json_pointer_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_json_pointer_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_json_pointer_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostJsonPointerFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_json_pointer_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_json_pointer_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_json_pointer_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_json_pointer_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_json_pointer_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_json_pointer_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..0a37153cc0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_maximum_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MAXIMUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..014815369d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maximum_validation import MaximumValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MaximumValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maximum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maximum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maximum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maximum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaximumValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maximum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maximum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maximum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maximum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..67f10e833c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maximum_validation import MaximumValidation + +SchemaFor200ResponseBodyApplicationJson = MaximumValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maximum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maximum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maximum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maximum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaximumValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maximum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maximum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maximum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maximum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..eb036d358c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MAXIMUM_VALIDATION_WITH_UNSIGNED_INTEGER_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/post.py new file mode 100644 index 0000000000..2d6a599008 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MaximumValidationWithUnsignedInteger + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maximum_validation_with_unsigned_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maximum_validation_with_unsigned_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maximum_validation_with_unsigned_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maximum_validation_with_unsigned_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..7dc51f79d7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maximum_validation_with_unsigned_integer_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maximum_validation_with_unsigned_integer import MaximumValidationWithUnsignedInteger + +SchemaFor200ResponseBodyApplicationJson = MaximumValidationWithUnsignedInteger + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaximumValidationWithUnsignedIntegerResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maximum_validation_with_unsigned_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maximum_validation_with_unsigned_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maximum_validation_with_unsigned_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maximum_validation_with_unsigned_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maximum_validation_with_unsigned_integer_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxitems_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxitems_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..7c0b46d8d7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxitems_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_maxitems_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MAXITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxitems_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxitems_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..4922837883 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxitems_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxitems_validation import MaxitemsValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MaxitemsValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxitemsValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxitems_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxitems_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..7976bfe5b8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxitems_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxitems_validation import MaxitemsValidation + +SchemaFor200ResponseBodyApplicationJson = MaxitemsValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxitemsValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxlength_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxlength_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..0fe9a95208 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxlength_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_maxlength_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MAXLENGTH_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxlength_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxlength_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..857194aedd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxlength_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxlength_validation import MaxlengthValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MaxlengthValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxlengthValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxlength_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxlength_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxlength_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxlength_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..722b323171 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxlength_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxlength_validation import MaxlengthValidation + +SchemaFor200ResponseBodyApplicationJson = MaxlengthValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxlengthValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxlength_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxlength_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..109f64b15b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MAXPROPERTIES0MEANS_THE_OBJECT_IS_EMPTY_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/post.py new file mode 100644 index 0000000000..2f1fe908a9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty + +from . import path + +SchemaFor200ResponseBodyApplicationJson = Maxproperties0MeansTheObjectIsEmpty + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxproperties0_means_the_object_is_empty_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..906b57dca1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties0_means_the_object_is_empty_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxproperties0_means_the_object_is_empty import Maxproperties0MeansTheObjectIsEmpty + +SchemaFor200ResponseBodyApplicationJson = Maxproperties0MeansTheObjectIsEmpty + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxproperties0MeansTheObjectIsEmptyResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxproperties0_means_the_object_is_empty_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxproperties0_means_the_object_is_empty_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties0_means_the_object_is_empty_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..4331ff3b54 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_maxproperties_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MAXPROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..caef224ec8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MaxpropertiesValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxpropertiesValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..a12bafc024 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_maxproperties_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.maxproperties_validation import MaxpropertiesValidation + +SchemaFor200ResponseBodyApplicationJson = MaxpropertiesValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_maxproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_maxproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_maxproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_maxproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMaxpropertiesValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_maxproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_maxproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_maxproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_maxproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_maxproperties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..ddb4f8db27 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_minimum_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MINIMUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..455b40680e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minimum_validation import MinimumValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MinimumValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minimum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minimum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minimum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minimum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinimumValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minimum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minimum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minimum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minimum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..3ecf130dc0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minimum_validation import MinimumValidation + +SchemaFor200ResponseBodyApplicationJson = MinimumValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minimum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minimum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minimum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minimum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinimumValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minimum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minimum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minimum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minimum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..3b5de8d211 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MINIMUM_VALIDATION_WITH_SIGNED_INTEGER_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/post.py new file mode 100644 index 0000000000..c7dbae7b64 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MinimumValidationWithSignedInteger + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minimum_validation_with_signed_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minimum_validation_with_signed_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minimum_validation_with_signed_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minimum_validation_with_signed_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..4a94bf8db0 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minimum_validation_with_signed_integer_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minimum_validation_with_signed_integer import MinimumValidationWithSignedInteger + +SchemaFor200ResponseBodyApplicationJson = MinimumValidationWithSignedInteger + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinimumValidationWithSignedIntegerResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minimum_validation_with_signed_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minimum_validation_with_signed_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minimum_validation_with_signed_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minimum_validation_with_signed_integer_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minimum_validation_with_signed_integer_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minitems_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minitems_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..243d71070c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minitems_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_minitems_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MINITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minitems_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minitems_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..05ed4ee8bb --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minitems_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minitems_validation import MinitemsValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MinitemsValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinitemsValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minitems_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minitems_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..c9e8bb7a6f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minitems_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minitems_validation import MinitemsValidation + +SchemaFor200ResponseBodyApplicationJson = MinitemsValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinitemsValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minlength_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minlength_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..ee102e9b97 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minlength_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_minlength_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MINLENGTH_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minlength_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minlength_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..fd1d4f2d1a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minlength_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minlength_validation import MinlengthValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MinlengthValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinlengthValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minlength_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minlength_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minlength_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minlength_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..a67f5177d9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minlength_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minlength_validation import MinlengthValidation + +SchemaFor200ResponseBodyApplicationJson = MinlengthValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minlength_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinlengthValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minlength_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minlength_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minlength_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minproperties_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minproperties_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..43828ac6ee --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minproperties_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_minproperties_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_MINPROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minproperties_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minproperties_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..7fe9a3c69b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minproperties_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minproperties_validation import MinpropertiesValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = MinpropertiesValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinpropertiesValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minproperties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minproperties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minproperties_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minproperties_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..9684d04445 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_minproperties_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.minproperties_validation import MinpropertiesValidation + +SchemaFor200ResponseBodyApplicationJson = MinpropertiesValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_minproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_minproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_minproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_minproperties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostMinpropertiesValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_minproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_minproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_minproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_minproperties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minproperties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_minproperties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..d5438b625b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_NESTED_ALLOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/post.py new file mode 100644 index 0000000000..e29ea0fbc5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics + +from . import path + +SchemaFor200ResponseBodyApplicationJson = NestedAllofToCheckValidationSemantics + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_allof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_allof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_allof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_allof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..4810724d1d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_allof_to_check_validation_semantics_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_allof_to_check_validation_semantics import NestedAllofToCheckValidationSemantics + +SchemaFor200ResponseBodyApplicationJson = NestedAllofToCheckValidationSemantics + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedAllofToCheckValidationSemanticsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_allof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_allof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_allof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_allof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_allof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e8b0c6f26e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_NESTED_ANYOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/post.py new file mode 100644 index 0000000000..3489d66401 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics + +from . import path + +SchemaFor200ResponseBodyApplicationJson = NestedAnyofToCheckValidationSemantics + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_anyof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..80692348d7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_anyof_to_check_validation_semantics_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_anyof_to_check_validation_semantics import NestedAnyofToCheckValidationSemantics + +SchemaFor200ResponseBodyApplicationJson = NestedAnyofToCheckValidationSemantics + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedAnyofToCheckValidationSemanticsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_anyof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_anyof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_anyof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_items_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_items_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..9c30762831 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_items_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_nested_items_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_NESTED_ITEMS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_items_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_items_response_body_for_content_types/post.py new file mode 100644 index 0000000000..492ff13454 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_items_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_items import NestedItems + +from . import path + +SchemaFor200ResponseBodyApplicationJson = NestedItems + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedItemsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_items_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_items_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_items_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_items_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..df06609b95 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_items_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_items import NestedItems + +SchemaFor200ResponseBodyApplicationJson = NestedItems + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedItemsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_items_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_items_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..3db488be78 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_NESTED_ONEOF_TO_CHECK_VALIDATION_SEMANTICS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/post.py new file mode 100644 index 0000000000..d4e4887665 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics + +from . import path + +SchemaFor200ResponseBodyApplicationJson = NestedOneofToCheckValidationSemantics + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_oneof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..7d498d603b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nested_oneof_to_check_validation_semantics_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nested_oneof_to_check_validation_semantics import NestedOneofToCheckValidationSemantics + +SchemaFor200ResponseBodyApplicationJson = NestedOneofToCheckValidationSemantics + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNestedOneofToCheckValidationSemanticsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nested_oneof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nested_oneof_to_check_validation_semantics_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nested_oneof_to_check_validation_semantics_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_more_complex_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_more_complex_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..8af95c890e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_more_complex_schema_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_not_more_complex_schema_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_NOT_MORE_COMPLEX_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_more_complex_schema_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_more_complex_schema_response_body_for_content_types/post.py new file mode 100644 index 0000000000..6bc017808f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_more_complex_schema_response_body_for_content_types/post.py @@ -0,0 +1,300 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class not_schema( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'not_schema': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_not_more_complex_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_not_more_complex_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_not_more_complex_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_not_more_complex_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNotMoreComplexSchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_not_more_complex_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_not_more_complex_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_not_more_complex_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_not_more_complex_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_more_complex_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_more_complex_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_more_complex_schema_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_more_complex_schema_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..3957b33cb1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_more_complex_schema_response_body_for_content_types/post.pyi @@ -0,0 +1,295 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class not_schema( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + foo = schemas.StrSchema + __annotations__ = { + "foo": foo, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'not_schema': + return super().__new__( + cls, + *args, + foo=foo, + _configuration=_configuration, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_not_more_complex_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_not_more_complex_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_not_more_complex_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_not_more_complex_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNotMoreComplexSchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_not_more_complex_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_not_more_complex_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_not_more_complex_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_not_more_complex_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_more_complex_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_more_complex_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..e832b365dd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_not_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_NOT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_response_body_for_content_types/post.py new file mode 100644 index 0000000000..03d9ffcda1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_response_body_for_content_types/post.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + not_schema = schemas.IntSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNotResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..7b2fa049ca --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_not_response_body_for_content_types/post.pyi @@ -0,0 +1,246 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + not_schema = schemas.IntSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNotResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_not_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..f91e082d1f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_nul_characters_in_strings_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_NUL_CHARACTERS_IN_STRINGS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types/post.py new file mode 100644 index 0000000000..8337995803 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings + +from . import path + +SchemaFor200ResponseBodyApplicationJson = NulCharactersInStrings + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nul_characters_in_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nul_characters_in_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nul_characters_in_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nul_characters_in_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNulCharactersInStringsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nul_characters_in_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nul_characters_in_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nul_characters_in_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nul_characters_in_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nul_characters_in_strings_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nul_characters_in_strings_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..017495d5d2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_nul_characters_in_strings_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.nul_characters_in_strings import NulCharactersInStrings + +SchemaFor200ResponseBodyApplicationJson = NulCharactersInStrings + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_nul_characters_in_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_nul_characters_in_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_nul_characters_in_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_nul_characters_in_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNulCharactersInStringsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_nul_characters_in_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_nul_characters_in_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_nul_characters_in_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_nul_characters_in_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nul_characters_in_strings_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_nul_characters_in_strings_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..bc488406d9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_NULL_TYPE_MATCHES_ONLY_THE_NULL_OBJECT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/post.py new file mode 100644 index 0000000000..3ad92b9b8f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/post.py @@ -0,0 +1,229 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +SchemaFor200ResponseBodyApplicationJson = schemas.NoneSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_null_type_matches_only_the_null_object_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_null_type_matches_only_the_null_object_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_null_type_matches_only_the_null_object_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_null_type_matches_only_the_null_object_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..199f916cee --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_null_type_matches_only_the_null_object_response_body_for_content_types/post.pyi @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +SchemaFor200ResponseBodyApplicationJson = schemas.NoneSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNullTypeMatchesOnlyTheNullObjectResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_null_type_matches_only_the_null_object_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_null_type_matches_only_the_null_object_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_null_type_matches_only_the_null_object_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_null_type_matches_only_the_null_object_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_null_type_matches_only_the_null_object_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..77109139f3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_number_type_matches_numbers_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_NUMBER_TYPE_MATCHES_NUMBERS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types/post.py new file mode 100644 index 0000000000..cde93c72ce --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types/post.py @@ -0,0 +1,229 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +SchemaFor200ResponseBodyApplicationJson = schemas.NumberSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_number_type_matches_numbers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_number_type_matches_numbers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_number_type_matches_numbers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_number_type_matches_numbers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNumberTypeMatchesNumbersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_number_type_matches_numbers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_number_type_matches_numbers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_number_type_matches_numbers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_number_type_matches_numbers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_number_type_matches_numbers_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_number_type_matches_numbers_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..6e88c42dd6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_number_type_matches_numbers_response_body_for_content_types/post.pyi @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +SchemaFor200ResponseBodyApplicationJson = schemas.NumberSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_number_type_matches_numbers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_number_type_matches_numbers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_number_type_matches_numbers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_number_type_matches_numbers_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostNumberTypeMatchesNumbersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_number_type_matches_numbers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_number_type_matches_numbers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_number_type_matches_numbers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_number_type_matches_numbers_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_number_type_matches_numbers_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_number_type_matches_numbers_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_properties_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_properties_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..b2c02e85ca --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_properties_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_object_properties_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_OBJECT_PROPERTIES_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_properties_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_properties_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..e5e9f0db80 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_properties_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = ObjectPropertiesValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_object_properties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_object_properties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_object_properties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_object_properties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostObjectPropertiesValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_object_properties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_object_properties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_object_properties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_object_properties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_properties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_properties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_properties_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_properties_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..47259e1d4e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_properties_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.object_properties_validation import ObjectPropertiesValidation + +SchemaFor200ResponseBodyApplicationJson = ObjectPropertiesValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_object_properties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_object_properties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_object_properties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_object_properties_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostObjectPropertiesValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_object_properties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_object_properties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_object_properties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_object_properties_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_properties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_properties_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_type_matches_objects_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_type_matches_objects_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..c069354cd1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_type_matches_objects_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_object_type_matches_objects_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_OBJECT_TYPE_MATCHES_OBJECTS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_type_matches_objects_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_type_matches_objects_response_body_for_content_types/post.py new file mode 100644 index 0000000000..4637ea3d38 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_type_matches_objects_response_body_for_content_types/post.py @@ -0,0 +1,229 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +SchemaFor200ResponseBodyApplicationJson = schemas.DictSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_object_type_matches_objects_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_object_type_matches_objects_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_object_type_matches_objects_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_object_type_matches_objects_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostObjectTypeMatchesObjectsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_object_type_matches_objects_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_object_type_matches_objects_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_object_type_matches_objects_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_object_type_matches_objects_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_type_matches_objects_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_type_matches_objects_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_type_matches_objects_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_type_matches_objects_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..5c554c8ce2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_object_type_matches_objects_response_body_for_content_types/post.pyi @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +SchemaFor200ResponseBodyApplicationJson = schemas.DictSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_object_type_matches_objects_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_object_type_matches_objects_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_object_type_matches_objects_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_object_type_matches_objects_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostObjectTypeMatchesObjectsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_object_type_matches_objects_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_object_type_matches_objects_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_object_type_matches_objects_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_object_type_matches_objects_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_type_matches_objects_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_object_type_matches_objects_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_complex_types_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_complex_types_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..2003410c48 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_complex_types_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_oneof_complex_types_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ONEOF_COMPLEX_TYPES_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_complex_types_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_complex_types_response_body_for_content_types/post.py new file mode 100644 index 0000000000..0670aeb2be --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_complex_types_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_complex_types import OneofComplexTypes + +from . import path + +SchemaFor200ResponseBodyApplicationJson = OneofComplexTypes + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofComplexTypesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_complex_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_complex_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_complex_types_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_complex_types_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..a3801d37e4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_complex_types_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_complex_types import OneofComplexTypes + +SchemaFor200ResponseBodyApplicationJson = OneofComplexTypes + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_complex_types_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofComplexTypesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_complex_types_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_complex_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_complex_types_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..5b88a1224f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_oneof_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_response_body_for_content_types/post.py new file mode 100644 index 0000000000..473bcca1fe --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof import Oneof + +from . import path + +SchemaFor200ResponseBodyApplicationJson = Oneof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..ef5fdf6e1c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof import Oneof + +SchemaFor200ResponseBodyApplicationJson = Oneof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..075773cc7e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_oneof_with_base_schema_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ONEOF_WITH_BASE_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types/post.py new file mode 100644 index 0000000000..ad58937033 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema + +from . import path + +SchemaFor200ResponseBodyApplicationJson = OneofWithBaseSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithBaseSchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..95e8f8bff4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_base_schema_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_base_schema import OneofWithBaseSchema + +SchemaFor200ResponseBodyApplicationJson = OneofWithBaseSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_base_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithBaseSchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_base_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_base_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..7640477c2f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_oneof_with_empty_schema_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ONEOF_WITH_EMPTY_SCHEMA_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types/post.py new file mode 100644 index 0000000000..a2936bd0d6 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema + +from . import path + +SchemaFor200ResponseBodyApplicationJson = OneofWithEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..de60f66e0b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_empty_schema_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_empty_schema import OneofWithEmptySchema + +SchemaFor200ResponseBodyApplicationJson = OneofWithEmptySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_empty_schema_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithEmptySchemaResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_empty_schema_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_empty_schema_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_required_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_required_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..1439a56296 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_required_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_oneof_with_required_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_ONEOF_WITH_REQUIRED_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_required_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_required_response_body_for_content_types/post.py new file mode 100644 index 0000000000..a05894d401 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_required_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_required import OneofWithRequired + +from . import path + +SchemaFor200ResponseBodyApplicationJson = OneofWithRequired + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_required_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_required_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_required_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_required_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithRequiredResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_required_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_required_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_required_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_required_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_required_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_required_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_required_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_required_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..f48e1c66e4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_oneof_with_required_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.oneof_with_required import OneofWithRequired + +SchemaFor200ResponseBodyApplicationJson = OneofWithRequired + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_oneof_with_required_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_oneof_with_required_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_oneof_with_required_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_oneof_with_required_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostOneofWithRequiredResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_oneof_with_required_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_oneof_with_required_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_oneof_with_required_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_oneof_with_required_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_required_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_oneof_with_required_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..f1ac8646a8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_pattern_is_not_anchored_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_PATTERN_IS_NOT_ANCHORED_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types/post.py new file mode 100644 index 0000000000..e1274eb003 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored + +from . import path + +SchemaFor200ResponseBodyApplicationJson = PatternIsNotAnchored + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_pattern_is_not_anchored_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_pattern_is_not_anchored_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_pattern_is_not_anchored_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_pattern_is_not_anchored_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPatternIsNotAnchoredResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_pattern_is_not_anchored_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_pattern_is_not_anchored_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_pattern_is_not_anchored_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_pattern_is_not_anchored_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_is_not_anchored_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_is_not_anchored_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..128e1246ff --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_is_not_anchored_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.pattern_is_not_anchored import PatternIsNotAnchored + +SchemaFor200ResponseBodyApplicationJson = PatternIsNotAnchored + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_pattern_is_not_anchored_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_pattern_is_not_anchored_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_pattern_is_not_anchored_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_pattern_is_not_anchored_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPatternIsNotAnchoredResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_pattern_is_not_anchored_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_pattern_is_not_anchored_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_pattern_is_not_anchored_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_pattern_is_not_anchored_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_is_not_anchored_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_is_not_anchored_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..3789f6ceca --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_pattern_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_PATTERN_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..a12b35e167 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.pattern_validation import PatternValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = PatternValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_pattern_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_pattern_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_pattern_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_pattern_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPatternValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_pattern_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_pattern_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_pattern_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_pattern_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..2e1b4cbec5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_pattern_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.pattern_validation import PatternValidation + +SchemaFor200ResponseBodyApplicationJson = PatternValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_pattern_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_pattern_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_pattern_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_pattern_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPatternValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_pattern_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_pattern_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_pattern_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_pattern_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_pattern_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..9aaa4005c4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_properties_with_escaped_characters_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_PROPERTIES_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types/post.py new file mode 100644 index 0000000000..936ad66657 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters + +from . import path + +SchemaFor200ResponseBodyApplicationJson = PropertiesWithEscapedCharacters + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_properties_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_properties_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_properties_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_properties_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPropertiesWithEscapedCharactersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_properties_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_properties_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_properties_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_properties_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_properties_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_properties_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..7e41369c86 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_properties_with_escaped_characters_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.properties_with_escaped_characters import PropertiesWithEscapedCharacters + +SchemaFor200ResponseBodyApplicationJson = PropertiesWithEscapedCharacters + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_properties_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_properties_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_properties_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_properties_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPropertiesWithEscapedCharactersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_properties_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_properties_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_properties_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_properties_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_properties_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_properties_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..424bb192e4 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_PROPERTY_NAMED_REF_THAT_IS_NOT_AREFERENCE_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/post.py new file mode 100644 index 0000000000..d05ed431c8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference + +from . import path + +SchemaFor200ResponseBodyApplicationJson = PropertyNamedRefThatIsNotAReference + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_property_named_ref_that_is_not_a_reference_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..8bb97630bc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_property_named_ref_that_is_not_a_reference_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference + +SchemaFor200ResponseBodyApplicationJson = PropertyNamedRefThatIsNotAReference + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostPropertyNamedRefThatIsNotAReferenceResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_property_named_ref_that_is_not_a_reference_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_property_named_ref_that_is_not_a_reference_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_property_named_ref_that_is_not_a_reference_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..af2e8f8096 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_ref_in_additionalproperties_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REF_IN_ADDITIONALPROPERTIES_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types/post.py new file mode 100644 index 0000000000..a91f8813a7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties + +from . import path + +SchemaFor200ResponseBodyApplicationJson = RefInAdditionalproperties + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_additionalproperties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_additionalproperties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_additionalproperties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_additionalproperties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAdditionalpropertiesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_additionalproperties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_additionalproperties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_additionalproperties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_additionalproperties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_additionalproperties_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_additionalproperties_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..900f555421 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_additionalproperties_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_additionalproperties import RefInAdditionalproperties + +SchemaFor200ResponseBodyApplicationJson = RefInAdditionalproperties + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_additionalproperties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_additionalproperties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_additionalproperties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_additionalproperties_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAdditionalpropertiesResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_additionalproperties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_additionalproperties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_additionalproperties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_additionalproperties_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_additionalproperties_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_additionalproperties_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_allof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_allof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..2aff994d8f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_allof_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_ref_in_allof_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REF_IN_ALLOF_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_allof_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_allof_response_body_for_content_types/post.py new file mode 100644 index 0000000000..fcae793b61 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_allof_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_allof import RefInAllof + +from . import path + +SchemaFor200ResponseBodyApplicationJson = RefInAllof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAllofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_allof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_allof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_allof_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_allof_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..265a672db3 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_allof_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_allof import RefInAllof + +SchemaFor200ResponseBodyApplicationJson = RefInAllof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_allof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAllofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_allof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_allof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_allof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_anyof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_anyof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..662467ec6d --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_anyof_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_ref_in_anyof_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REF_IN_ANYOF_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_anyof_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_anyof_response_body_for_content_types/post.py new file mode 100644 index 0000000000..8e4026bb2f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_anyof_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_anyof import RefInAnyof + +from . import path + +SchemaFor200ResponseBodyApplicationJson = RefInAnyof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAnyofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_anyof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_anyof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_anyof_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_anyof_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..a2d53f3dad --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_anyof_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_anyof import RefInAnyof + +SchemaFor200ResponseBodyApplicationJson = RefInAnyof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_anyof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInAnyofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_anyof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_anyof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_anyof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_items_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_items_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..5f4fef4581 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_items_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_ref_in_items_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REF_IN_ITEMS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_items_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_items_response_body_for_content_types/post.py new file mode 100644 index 0000000000..d6faf25623 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_items_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_items import RefInItems + +from . import path + +SchemaFor200ResponseBodyApplicationJson = RefInItems + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInItemsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_items_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_items_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_items_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_items_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..7ac9c2f3dc --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_items_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_items import RefInItems + +SchemaFor200ResponseBodyApplicationJson = RefInItems + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_items_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInItemsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_items_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_items_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_items_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_not_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_not_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..81c335c672 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_not_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_ref_in_not_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REF_IN_NOT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_not_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_not_response_body_for_content_types/post.py new file mode 100644 index 0000000000..d289f34e4c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_not_response_body_for_content_types/post.py @@ -0,0 +1,256 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + @staticmethod + def not_schema() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInNotResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_not_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_not_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_not_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_not_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..3b8376118f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_not_response_body_for_content_types/post.pyi @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.property_named_ref_that_is_not_a_reference import PropertyNamedRefThatIsNotAReference + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + @staticmethod + def not_schema() -> typing.Type['PropertyNamedRefThatIsNotAReference']: + return PropertyNamedRefThatIsNotAReference + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_not_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInNotResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_not_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_not_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_not_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_oneof_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_oneof_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..40113e93f2 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_oneof_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_ref_in_oneof_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REF_IN_ONEOF_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_oneof_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_oneof_response_body_for_content_types/post.py new file mode 100644 index 0000000000..c4173c7164 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_oneof_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_oneof import RefInOneof + +from . import path + +SchemaFor200ResponseBodyApplicationJson = RefInOneof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInOneofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_oneof_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_oneof_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..78aec76544 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_oneof_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_oneof import RefInOneof + +SchemaFor200ResponseBodyApplicationJson = RefInOneof + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_oneof_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInOneofResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_oneof_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_oneof_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_property_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_property_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..46badf3657 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_property_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_ref_in_property_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REF_IN_PROPERTY_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_property_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_property_response_body_for_content_types/post.py new file mode 100644 index 0000000000..8c919aea71 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_property_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_property import RefInProperty + +from . import path + +SchemaFor200ResponseBodyApplicationJson = RefInProperty + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInPropertyResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_property_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_property_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_property_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_property_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..87b6d58596 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_ref_in_property_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.ref_in_property import RefInProperty + +SchemaFor200ResponseBodyApplicationJson = RefInProperty + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_ref_in_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_ref_in_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_ref_in_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_ref_in_property_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRefInPropertyResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_ref_in_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_ref_in_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_ref_in_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_ref_in_property_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_property_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_ref_in_property_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_default_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_default_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..5d1b90f267 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_default_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_required_default_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REQUIRED_DEFAULT_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_default_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_default_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..2f071fcad9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_default_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_default_validation import RequiredDefaultValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = RequiredDefaultValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_default_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_default_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_default_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_default_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredDefaultValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_default_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_default_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_default_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_default_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_default_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_default_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_default_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_default_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..ba9ce4b930 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_default_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_default_validation import RequiredDefaultValidation + +SchemaFor200ResponseBodyApplicationJson = RequiredDefaultValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_default_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_default_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_default_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_default_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredDefaultValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_default_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_default_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_default_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_default_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_default_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_default_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..b17c030e82 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_required_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REQUIRED_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..feece12371 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_validation import RequiredValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = RequiredValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..0c226b3e2e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_validation import RequiredValidation + +SchemaFor200ResponseBodyApplicationJson = RequiredValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_empty_array_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_empty_array_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..a890c56e6e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_empty_array_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_required_with_empty_array_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REQUIRED_WITH_EMPTY_ARRAY_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_empty_array_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_empty_array_response_body_for_content_types/post.py new file mode 100644 index 0000000000..ae3f890c1b --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_empty_array_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray + +from . import path + +SchemaFor200ResponseBodyApplicationJson = RequiredWithEmptyArray + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_with_empty_array_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_with_empty_array_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_with_empty_array_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_with_empty_array_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredWithEmptyArrayResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_with_empty_array_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_with_empty_array_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_with_empty_array_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_with_empty_array_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_empty_array_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_empty_array_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_empty_array_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_empty_array_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..550654feff --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_empty_array_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.required_with_empty_array import RequiredWithEmptyArray + +SchemaFor200ResponseBodyApplicationJson = RequiredWithEmptyArray + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_with_empty_array_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_with_empty_array_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_with_empty_array_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_with_empty_array_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredWithEmptyArrayResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_with_empty_array_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_with_empty_array_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_with_empty_array_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_with_empty_array_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_empty_array_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_empty_array_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..b9fb929544 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_required_with_escaped_characters_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_REQUIRED_WITH_ESCAPED_CHARACTERS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types/post.py new file mode 100644 index 0000000000..837f66395a --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types/post.py @@ -0,0 +1,259 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + required = { + "foo\"bar", + "foo\nbar", + "foo\fbar", + "foo\tbar", + "foo\rbar", + "foo\\bar", + } + + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredWithEscapedCharactersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..38ff81848c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_required_with_escaped_characters_response_body_for_content_types/post.pyi @@ -0,0 +1,254 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + required = { + "foo\"bar", + "foo\nbar", + "foo\fbar", + "foo\tbar", + "foo\rbar", + "foo\\bar", + } + + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_required_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_required_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_required_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_required_with_escaped_characters_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostRequiredWithEscapedCharactersResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_required_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_required_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_required_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_required_with_escaped_characters_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_required_with_escaped_characters_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_simple_enum_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_simple_enum_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..5434927f1f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_simple_enum_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_simple_enum_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_SIMPLE_ENUM_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_simple_enum_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_simple_enum_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..f33666b2d9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_simple_enum_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = SimpleEnumValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_simple_enum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_simple_enum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_simple_enum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_simple_enum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostSimpleEnumValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_simple_enum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_simple_enum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_simple_enum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_simple_enum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_simple_enum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_simple_enum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_simple_enum_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_simple_enum_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..525cc8b427 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_simple_enum_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.simple_enum_validation import SimpleEnumValidation + +SchemaFor200ResponseBodyApplicationJson = SimpleEnumValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_simple_enum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_simple_enum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_simple_enum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_simple_enum_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostSimpleEnumValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_simple_enum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_simple_enum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_simple_enum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_simple_enum_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_simple_enum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_simple_enum_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_string_type_matches_strings_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_string_type_matches_strings_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..0e9991d012 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_string_type_matches_strings_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_string_type_matches_strings_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_STRING_TYPE_MATCHES_STRINGS_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_string_type_matches_strings_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_string_type_matches_strings_response_body_for_content_types/post.py new file mode 100644 index 0000000000..232e64e2fd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_string_type_matches_strings_response_body_for_content_types/post.py @@ -0,0 +1,229 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + +SchemaFor200ResponseBodyApplicationJson = schemas.StrSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_string_type_matches_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_string_type_matches_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_string_type_matches_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_string_type_matches_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostStringTypeMatchesStringsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_string_type_matches_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_string_type_matches_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_string_type_matches_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_string_type_matches_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_string_type_matches_strings_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_string_type_matches_strings_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_string_type_matches_strings_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_string_type_matches_strings_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..92cb39e7f9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_string_type_matches_strings_response_body_for_content_types/post.pyi @@ -0,0 +1,224 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +SchemaFor200ResponseBodyApplicationJson = schemas.StrSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_string_type_matches_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_string_type_matches_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_string_type_matches_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_string_type_matches_strings_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostStringTypeMatchesStringsResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_string_type_matches_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_string_type_matches_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_string_type_matches_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_string_type_matches_strings_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_string_type_matches_strings_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_string_type_matches_strings_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..ec8ccdc38e --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_THE_DEFAULT_KEYWORD_DOES_NOT_DO_ANYTHING_IF_THE_PROPERTY_IS_MISSING_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/post.py new file mode 100644 index 0000000000..7ec32ffcd5 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing + +from . import path + +SchemaFor200ResponseBodyApplicationJson = TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..5e4fef20ac --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.the_default_keyword_does_not_do_anything_if_the_property_is_missing import TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing + +SchemaFor200ResponseBodyApplicationJson = TheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissing + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostTheDefaultKeywordDoesNotDoAnythingIfThePropertyIsMissingResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_the_default_keyword_does_not_do_anything_if_the_property_is_missing_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..f40589c90c --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_uniqueitems_false_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_UNIQUEITEMS_FALSE_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..2ca6488bc1 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = UniqueitemsFalseValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uniqueitems_false_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uniqueitems_false_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uniqueitems_false_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uniqueitems_false_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUniqueitemsFalseValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uniqueitems_false_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uniqueitems_false_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uniqueitems_false_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uniqueitems_false_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_false_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_false_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..3054b49516 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_false_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.uniqueitems_false_validation import UniqueitemsFalseValidation + +SchemaFor200ResponseBodyApplicationJson = UniqueitemsFalseValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uniqueitems_false_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uniqueitems_false_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uniqueitems_false_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uniqueitems_false_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUniqueitemsFalseValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uniqueitems_false_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uniqueitems_false_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uniqueitems_false_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uniqueitems_false_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_false_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_false_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_validation_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_validation_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..693706fd00 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_validation_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_uniqueitems_validation_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_UNIQUEITEMS_VALIDATION_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_validation_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_validation_response_body_for_content_types/post.py new file mode 100644 index 0000000000..c4f75d43a8 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_validation_response_body_for_content_types/post.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation + +from . import path + +SchemaFor200ResponseBodyApplicationJson = UniqueitemsValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uniqueitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uniqueitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uniqueitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uniqueitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUniqueitemsValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uniqueitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uniqueitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uniqueitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uniqueitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_validation_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_validation_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..b8d23d3e76 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uniqueitems_validation_response_body_for_content_types/post.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from unit_test_api.model.uniqueitems_validation import UniqueitemsValidation + +SchemaFor200ResponseBodyApplicationJson = UniqueitemsValidation + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uniqueitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uniqueitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uniqueitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uniqueitems_validation_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUniqueitemsValidationResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uniqueitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uniqueitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uniqueitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uniqueitems_validation_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uniqueitems_validation_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..d7621b5832 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_format_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_uri_format_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_URI_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_format_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_format_response_body_for_content_types/post.py new file mode 100644 index 0000000000..b0bb6afea9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_format_response_body_for_content_types/post.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_format_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_format_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..aec6e6c16f --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_format_response_body_for_content_types/post.pyi @@ -0,0 +1,246 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_reference_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_reference_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..dd5c4ffc43 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_reference_format_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_uri_reference_format_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_URI_REFERENCE_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_reference_format_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_reference_format_response_body_for_content_types/post.py new file mode 100644 index 0000000000..b0f9310247 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_reference_format_response_body_for_content_types/post.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri-reference' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_reference_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_reference_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_reference_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_reference_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriReferenceFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_reference_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_reference_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_reference_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_reference_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_reference_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_reference_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_reference_format_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_reference_format_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..3de5191676 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_reference_format_response_body_for_content_types/post.pyi @@ -0,0 +1,246 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri-reference' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_reference_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_reference_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_reference_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_reference_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriReferenceFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_reference_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_reference_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_reference_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_reference_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_reference_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_reference_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_template_format_response_body_for_content_types/__init__.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_template_format_response_body_for_content_types/__init__.py new file mode 100644 index 0000000000..468a1c4cfd --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_template_format_response_body_for_content_types/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from unit_test_api.paths.response_body_post_uri_template_format_response_body_for_content_types import Api + +from unit_test_api.paths import PathValues + +path = PathValues.RESPONSE_BODY_POST_URI_TEMPLATE_FORMAT_RESPONSE_BODY_FOR_CONTENT_TYPES \ No newline at end of file diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_template_format_response_body_for_content_types/post.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_template_format_response_body_for_content_types/post.py new file mode 100644 index 0000000000..1eea3901e9 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_template_format_response_body_for_content_types/post.py @@ -0,0 +1,251 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + +from . import path + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri-template' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_template_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_template_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_template_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_template_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriTemplateFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_template_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_template_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_template_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_template_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_template_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_template_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_template_format_response_body_for_content_types/post.pyi b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_template_format_response_body_for_content_types/post.pyi new file mode 100644 index 0000000000..06064e29e7 --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/paths/response_body_post_uri_template_format_response_body_for_content_types/post.pyi @@ -0,0 +1,246 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from unit_test_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from unit_test_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.AnyTypeSchema, +): + + + class MetaOapg: + format = 'uri-template' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _post_uri_template_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _post_uri_template_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _post_uri_template_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _post_uri_template_format_response_body_for_content_types_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PostUriTemplateFormatResponseBodyForContentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def post_uri_template_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post_uri_template_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post_uri_template_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post_uri_template_format_response_body_for_content_types( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_template_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._post_uri_template_format_response_body_for_content_types_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/rest.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/rest.py similarity index 100% rename from samples/openapi3/client/3_0_3_unit_test/python-experimental/unit_test_api/rest.py rename to samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/rest.py diff --git a/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/schemas.py b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/schemas.py new file mode 100644 index 0000000000..c9fe4b6fec --- /dev/null +++ b/samples/openapi3/client/3_0_3_unit_test/python/unit_test_api/schemas.py @@ -0,0 +1,2462 @@ +# coding: utf-8 + +""" + openapi 3.0.3 sample spec + + sample spec for testing openapi functionality, built from json schema tests for draft6 # noqa: E501 + + The version of the OpenAPI document: 0.0.1 + Generated by: https://openapi-generator.tech +""" + +from collections import defaultdict +from datetime import date, datetime, timedelta # noqa: F401 +import functools +import decimal +import io +import re +import types +import typing +import uuid + +from dateutil.parser.isoparser import isoparser, _takes_ascii +import frozendict + +from unit_test_api.exceptions import ( + ApiTypeError, + ApiValueError, +) +from unit_test_api.configuration import ( + Configuration, +) + + +class Unset(object): + """ + An instance of this class is set as the default value for object type(dict) properties that are optional + When a property has an unset value, that property will not be assigned in the dict + """ + pass + +unset = Unset() + +none_type = type(None) +file_type = io.IOBase + + +class FileIO(io.FileIO): + """ + A class for storing files + Note: this class is not immutable + """ + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader]): + if isinstance(arg, (io.FileIO, io.BufferedReader)): + if arg.closed: + raise ApiValueError('Invalid file state; file is closed and must be open') + arg.close() + inst = super(FileIO, cls).__new__(cls, arg.name) + super(FileIO, inst).__init__(arg.name) + return inst + raise ApiValueError('FileIO must be passed arg which contains the open file') + + def __init__(self, arg: typing.Union[io.FileIO, io.BufferedReader]): + pass + + +def update(d: dict, u: dict): + """ + Adds u to d + Where each dict is defaultdict(set) + """ + if not u: + return d + for k, v in u.items(): + if k not in d: + d[k] = v + else: + d[k] = d[k] | v + + +class ValidationMetadata(frozendict.frozendict): + """ + A class storing metadata that is needed to validate OpenApi Schema payloads + """ + def __new__( + cls, + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), + from_server: bool = False, + configuration: typing.Optional[Configuration] = None, + seen_classes: typing.FrozenSet[typing.Type] = frozenset(), + validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]] = frozendict.frozendict() + ): + """ + Args: + path_to_item: the path to the current data being instantiated. + For {'a': [1]} if the code is handling, 1, then the path is ('args[0]', 'a', 0) + This changes from location to location + from_server: whether or not this data came form the server + True when receiving server data + False when instantiating model with client side data not form the server + This does not change from location to location + configuration: the Configuration instance to use + This is needed because in Configuration: + - one can disable validation checking + This does not change from location to location + seen_classes: when deserializing data that matches multiple schemas, this is used to store + the schemas that have been traversed. This is used to stop processing when a cycle is seen. + This changes from location to location + validated_path_to_schemas: stores the already validated schema classes for a given path location + This does not change from location to location + """ + return super().__new__( + cls, + path_to_item=path_to_item, + from_server=from_server, + configuration=configuration, + seen_classes=seen_classes, + validated_path_to_schemas=validated_path_to_schemas + ) + + def validation_ran_earlier(self, cls: type) -> bool: + validated_schemas = self.validated_path_to_schemas.get(self.path_to_item, set()) + validation_ran_earlier = validated_schemas and cls in validated_schemas + if validation_ran_earlier: + return True + if cls in self.seen_classes: + return True + return False + + @property + def path_to_item(self) -> typing.Tuple[typing.Union[str, int], ...]: + return self.get('path_to_item') + + @property + def from_server(self) -> bool: + return self.get('from_server') + + @property + def configuration(self) -> typing.Optional[Configuration]: + return self.get('configuration') + + @property + def seen_classes(self) -> typing.FrozenSet[typing.Type]: + return self.get('seen_classes') + + @property + def validated_path_to_schemas(self) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]]: + return self.get('validated_path_to_schemas') + + +class Singleton: + """ + Enums and singletons are the same + The same instance is returned for a given key of (cls, arg) + """ + _instances = {} + + def __new__(cls, arg: typing.Any, **kwargs): + """ + cls base classes: BoolClass, NoneClass, str, decimal.Decimal + The 3rd key is used in the tuple below for a corner case where an enum contains integer 1 + However 1.0 can also be ingested into that enum schema because 1.0 == 1 and + Decimal('1.0') == Decimal('1') + But if we omitted the 3rd value in the key, then Decimal('1.0') would be stored as Decimal('1') + and json serializing that instance would be '1' rather than the expected '1.0' + Adding the 3rd value, the str of arg ensures that 1.0 -> Decimal('1.0') which is serialized as 1.0 + """ + key = (cls, arg, str(arg)) + if key not in cls._instances: + if isinstance(arg, (none_type, bool, BoolClass, NoneClass)): + inst = super().__new__(cls) + cls._instances[key] = inst + else: + cls._instances[key] = super().__new__(cls, arg) + return cls._instances[key] + + def __repr__(self): + if isinstance(self, NoneClass): + return f'<{self.__class__.__name__}: None>' + elif isinstance(self, BoolClass): + if bool(self): + return f'<{self.__class__.__name__}: True>' + return f'<{self.__class__.__name__}: False>' + return f'<{self.__class__.__name__}: {super().__repr__()}>' + + +class classproperty: + + def __init__(self, fget): + self.fget = fget + + def __get__(self, owner_self, owner_cls): + return self.fget(owner_cls) + + +class NoneClass(Singleton): + @classproperty + def NONE(cls): + return cls(None) + + def __bool__(self) -> bool: + return False + + +class BoolClass(Singleton): + @classproperty + def TRUE(cls): + return cls(True) + + @classproperty + def FALSE(cls): + return cls(False) + + @functools.lru_cache() + def __bool__(self) -> bool: + for key, instance in self._instances.items(): + if self is instance: + return bool(key[1]) + raise ValueError('Unable to find the boolean value of this instance') + + +class MetaOapgTyped: + exclusive_maximum: typing.Union[int, float] + inclusive_maximum: typing.Union[int, float] + exclusive_minimum: typing.Union[int, float] + inclusive_minimum: typing.Union[int, float] + max_items: int + min_items: int + discriminator: typing.Dict[str, typing.Dict[str, typing.Type['Schema']]] + + + class properties: + # to hold object properties + pass + + additional_properties: typing.Optional[typing.Type['Schema']] + max_properties: int + min_properties: int + all_of: typing.List[typing.Type['Schema']] + one_of: typing.List[typing.Type['Schema']] + any_of: typing.List[typing.Type['Schema']] + not_schema: typing.Type['Schema'] + max_length: int + min_length: int + items: typing.Type['Schema'] + + +class Schema: + """ + the base class of all swagger/openapi schemas/models + """ + __inheritable_primitive_types_set = {decimal.Decimal, str, tuple, frozendict.frozendict, FileIO, bytes, BoolClass, NoneClass} + _types: typing.Set[typing.Type] + MetaOapg = MetaOapgTyped + + @staticmethod + def __get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed""" + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return "is {0}".format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + @staticmethod + def _get_class_oapg(item_cls: typing.Union[types.FunctionType, staticmethod, typing.Type['Schema']]) -> typing.Type['Schema']: + if isinstance(item_cls, types.FunctionType): + # referenced schema + return item_cls() + elif isinstance(item_cls, staticmethod): + # referenced schema + return item_cls.__func__() + return item_cls + + @classmethod + def __type_error_message( + cls, var_value=None, var_name=None, valid_classes=None, key_type=None + ): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a tuple + """ + key_or_value = "value" + if key_type: + key_or_value = "key" + valid_classes_phrase = cls.__get_valid_classes_phrase(valid_classes) + msg = "Invalid type. Required {1} type {2} and " "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + return msg + + @classmethod + def __get_type_error(cls, var_value, path_to_item, valid_classes, key_type=False): + error_msg = cls.__type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type, + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type, + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + Schema _validate_oapg + All keyword validation except for type checking was done in calling stack frames + If those validations passed, the validated classes are collected in path_to_schemas + + Returns: + path_to_schemas: a map of path to schemas + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + base_class = type(arg) + if base_class not in cls._types: + raise cls.__get_type_error( + arg, + validation_metadata.path_to_item, + cls._types, + key_type=False, + ) + + path_to_schemas = {validation_metadata.path_to_item: set()} + path_to_schemas[validation_metadata.path_to_item].add(cls) + path_to_schemas[validation_metadata.path_to_item].add(base_class) + return path_to_schemas + + @staticmethod + def _process_schema_classes_oapg( + schema_classes: typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]] + ): + """ + Processes and mutates schema_classes + If a SomeSchema is a subclass of DictSchema then remove DictSchema because it is already included + """ + if len(schema_classes) < 2: + return + if len(schema_classes) > 2 and UnsetAnyTypeSchema in schema_classes: + schema_classes.remove(UnsetAnyTypeSchema) + x_schema = schema_type_classes & schema_classes + if not x_schema: + return + x_schema = x_schema.pop() + if any(c is not x_schema and issubclass(c, x_schema) for c in schema_classes): + # needed to not have a mro error in get_new_class + schema_classes.remove(x_schema) + + @classmethod + def __get_new_cls( + cls, + arg, + validation_metadata: ValidationMetadata + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']]: + """ + Make a new dynamic class and return an instance of that class + We are making an instance of cls, but instead of making cls + make a new class, new_cls + which includes dynamic bases including cls + return an instance of that new class + + Dict property + List Item Assignment Use cases: + 1. value is NOT an instance of the required schema class + the value is validated by _validate_oapg + _validate_oapg returns a key value pair + where the key is the path to the item, and the value will be the required manufactured class + made out of the matching schemas + 2. value is an instance of the the correct schema type + the value is NOT validated by _validate_oapg, _validate_oapg only checks that the instance is of the correct schema type + for this value, _validate_oapg does NOT return an entry for it in _path_to_schemas + and in list/dict _get_items_oapg,_get_properties_oapg the value will be directly assigned + because value is of the correct type, and validation was run earlier when the instance was created + """ + _path_to_schemas = {} + if validation_metadata.validated_path_to_schemas: + update(_path_to_schemas, validation_metadata.validated_path_to_schemas) + if not validation_metadata.validation_ran_earlier(cls): + other_path_to_schemas = cls._validate_oapg(arg, validation_metadata=validation_metadata) + update(_path_to_schemas, other_path_to_schemas) + # loop through it make a new class for each entry + # do not modify the returned result because it is cached and we would be modifying the cached value + path_to_schemas = {} + for path, schema_classes in _path_to_schemas.items(): + """ + Use cases + 1. N number of schema classes + enum + type != bool/None, classes in path_to_schemas: tuple/frozendict.frozendict/str/Decimal/bytes/FileIo + needs Singleton added + 2. N number of schema classes + enum + type == bool/None, classes in path_to_schemas: BoolClass/NoneClass + Singleton already added + 3. N number of schema classes, classes in path_to_schemas: BoolClass/NoneClass/tuple/frozendict.frozendict/str/Decimal/bytes/FileIo + """ + cls._process_schema_classes_oapg(schema_classes) + enum_schema = any( + issubclass(this_cls, EnumBase) for this_cls in schema_classes) + inheritable_primitive_type = schema_classes.intersection(cls.__inheritable_primitive_types_set) + chosen_schema_classes = schema_classes - inheritable_primitive_type + suffix = tuple(inheritable_primitive_type) + if enum_schema and suffix[0] not in {NoneClass, BoolClass}: + suffix = (Singleton,) + suffix + + used_classes = tuple(sorted(chosen_schema_classes, key=lambda a_cls: a_cls.__name__)) + suffix + mfg_cls = get_new_class(class_name='DynamicSchema', bases=used_classes) + path_to_schemas[path] = mfg_cls + + return path_to_schemas + + @classmethod + def _get_new_instance_without_conversion_oapg( + cls, + arg: typing.Any, + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + # We have a Dynamic class and we are making an instance of it + if issubclass(cls, frozendict.frozendict) and issubclass(cls, DictBase): + properties = cls._get_properties_oapg(arg, path_to_item, path_to_schemas) + return super(Schema, cls).__new__(cls, properties) + elif issubclass(cls, tuple) and issubclass(cls, ListBase): + items = cls._get_items_oapg(arg, path_to_item, path_to_schemas) + return super(Schema, cls).__new__(cls, items) + """ + str = openapi str, date, and datetime + decimal.Decimal = openapi int and float + FileIO = openapi binary type and the user inputs a file + bytes = openapi binary type and the user inputs bytes + """ + return super(Schema, cls).__new__(cls, arg) + + @classmethod + def from_openapi_data_oapg( + cls, + arg: typing.Union[ + str, + date, + datetime, + int, + float, + decimal.Decimal, + bool, + None, + 'Schema', + dict, + frozendict.frozendict, + tuple, + list, + io.FileIO, + io.BufferedReader, + bytes + ], + _configuration: typing.Optional[Configuration] + ): + """ + Schema from_openapi_data_oapg + """ + from_server = True + validated_path_to_schemas = {} + arg = cast_to_allowed_types(arg, from_server, validated_path_to_schemas) + validation_metadata = ValidationMetadata( + from_server=from_server, configuration=_configuration, validated_path_to_schemas=validated_path_to_schemas) + path_to_schemas = cls.__get_new_cls(arg, validation_metadata) + new_cls = path_to_schemas[validation_metadata.path_to_item] + new_inst = new_cls._get_new_instance_without_conversion_oapg( + arg, + validation_metadata.path_to_item, + path_to_schemas + ) + return new_inst + + @staticmethod + def __get_input_dict(*args, **kwargs) -> frozendict.frozendict: + input_dict = {} + if args and isinstance(args[0], (dict, frozendict.frozendict)): + input_dict.update(args[0]) + if kwargs: + input_dict.update(kwargs) + return frozendict.frozendict(input_dict) + + @staticmethod + def __remove_unsets(kwargs): + return {key: val for key, val in kwargs.items() if val is not unset} + + def __new__(cls, *args: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], _configuration: typing.Optional[Configuration] = None, **kwargs: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset]): + """ + Schema __new__ + + Args: + args (int/float/decimal.Decimal/str/list/tuple/dict/frozendict.frozendict/bool/None): the value + kwargs (str, int/float/decimal.Decimal/str/list/tuple/dict/frozendict.frozendict/bool/None): dict values + _configuration: contains the Configuration that enables json schema validation keywords + like minItems, minLength etc + + Note: double underscores are used here because pycharm thinks that these variables + are instance properties if they are named normally :( + """ + __kwargs = cls.__remove_unsets(kwargs) + if not args and not __kwargs: + raise TypeError( + 'No input given. args or kwargs must be given.' + ) + if not __kwargs and args and not isinstance(args[0], dict): + __arg = args[0] + else: + __arg = cls.__get_input_dict(*args, **__kwargs) + __from_server = False + __validated_path_to_schemas = {} + __arg = cast_to_allowed_types( + __arg, __from_server, __validated_path_to_schemas) + __validation_metadata = ValidationMetadata( + configuration=_configuration, from_server=__from_server, validated_path_to_schemas=__validated_path_to_schemas) + __path_to_schemas = cls.__get_new_cls(__arg, __validation_metadata) + __new_cls = __path_to_schemas[__validation_metadata.path_to_item] + return __new_cls._get_new_instance_without_conversion_oapg( + __arg, + __validation_metadata.path_to_item, + __path_to_schemas + ) + + def __init__( + self, + *args: typing.Union[ + dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], + _configuration: typing.Optional[Configuration] = None, + **kwargs: typing.Union[ + dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset + ] + ): + """ + this is needed to fix 'Unexpected argument' warning in pycharm + this code does nothing because all Schema instances are immutable + this means that all input data is passed into and used in new, and after the new instance is made + no new attributes are assigned and init is not used + """ + pass + +""" +import itertools +data_types = ('None', 'FrozenDict', 'Tuple', 'Str', 'Decimal', 'Bool') +type_to_cls = { + 'None': 'NoneClass', + 'FrozenDict': 'frozendict.frozendict', + 'Tuple': 'tuple', + 'Str': 'str', + 'Decimal': 'decimal.Decimal', + 'Bool': 'BoolClass' +} +cls_tuples = [v for v in itertools.combinations(data_types, 5)] +typed_classes = [f"class {''.join(cls_tuple)}Mixin({', '.join(type_to_cls[typ] for typ in cls_tuple)}):\n pass" for cls_tuple in cls_tuples] +for cls in typed_classes: + print(cls) +object_classes = [f"{''.join(cls_tuple)}Mixin = object" for cls_tuple in cls_tuples] +for cls in object_classes: + print(cls) +""" +if typing.TYPE_CHECKING: + # qty 1 + NoneMixin = NoneClass + FrozenDictMixin = frozendict.frozendict + TupleMixin = tuple + StrMixin = str + DecimalMixin = decimal.Decimal + BoolMixin = BoolClass + BytesMixin = bytes + FileMixin = FileIO + # qty 2 + class BinaryMixin(bytes, FileIO): + pass + class NoneFrozenDictMixin(NoneClass, frozendict.frozendict): + pass + class NoneTupleMixin(NoneClass, tuple): + pass + class NoneStrMixin(NoneClass, str): + pass + class NoneDecimalMixin(NoneClass, decimal.Decimal): + pass + class NoneBoolMixin(NoneClass, BoolClass): + pass + class FrozenDictTupleMixin(frozendict.frozendict, tuple): + pass + class FrozenDictStrMixin(frozendict.frozendict, str): + pass + class FrozenDictDecimalMixin(frozendict.frozendict, decimal.Decimal): + pass + class FrozenDictBoolMixin(frozendict.frozendict, BoolClass): + pass + class TupleStrMixin(tuple, str): + pass + class TupleDecimalMixin(tuple, decimal.Decimal): + pass + class TupleBoolMixin(tuple, BoolClass): + pass + class StrDecimalMixin(str, decimal.Decimal): + pass + class StrBoolMixin(str, BoolClass): + pass + class DecimalBoolMixin(decimal.Decimal, BoolClass): + pass + # qty 3 + class NoneFrozenDictTupleMixin(NoneClass, frozendict.frozendict, tuple): + pass + class NoneFrozenDictStrMixin(NoneClass, frozendict.frozendict, str): + pass + class NoneFrozenDictDecimalMixin(NoneClass, frozendict.frozendict, decimal.Decimal): + pass + class NoneFrozenDictBoolMixin(NoneClass, frozendict.frozendict, BoolClass): + pass + class NoneTupleStrMixin(NoneClass, tuple, str): + pass + class NoneTupleDecimalMixin(NoneClass, tuple, decimal.Decimal): + pass + class NoneTupleBoolMixin(NoneClass, tuple, BoolClass): + pass + class NoneStrDecimalMixin(NoneClass, str, decimal.Decimal): + pass + class NoneStrBoolMixin(NoneClass, str, BoolClass): + pass + class NoneDecimalBoolMixin(NoneClass, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrMixin(frozendict.frozendict, tuple, str): + pass + class FrozenDictTupleDecimalMixin(frozendict.frozendict, tuple, decimal.Decimal): + pass + class FrozenDictTupleBoolMixin(frozendict.frozendict, tuple, BoolClass): + pass + class FrozenDictStrDecimalMixin(frozendict.frozendict, str, decimal.Decimal): + pass + class FrozenDictStrBoolMixin(frozendict.frozendict, str, BoolClass): + pass + class FrozenDictDecimalBoolMixin(frozendict.frozendict, decimal.Decimal, BoolClass): + pass + class TupleStrDecimalMixin(tuple, str, decimal.Decimal): + pass + class TupleStrBoolMixin(tuple, str, BoolClass): + pass + class TupleDecimalBoolMixin(tuple, decimal.Decimal, BoolClass): + pass + class StrDecimalBoolMixin(str, decimal.Decimal, BoolClass): + pass + # qty 4 + class NoneFrozenDictTupleStrMixin(NoneClass, frozendict.frozendict, tuple, str): + pass + class NoneFrozenDictTupleDecimalMixin(NoneClass, frozendict.frozendict, tuple, decimal.Decimal): + pass + class NoneFrozenDictTupleBoolMixin(NoneClass, frozendict.frozendict, tuple, BoolClass): + pass + class NoneFrozenDictStrDecimalMixin(NoneClass, frozendict.frozendict, str, decimal.Decimal): + pass + class NoneFrozenDictStrBoolMixin(NoneClass, frozendict.frozendict, str, BoolClass): + pass + class NoneFrozenDictDecimalBoolMixin(NoneClass, frozendict.frozendict, decimal.Decimal, BoolClass): + pass + class NoneTupleStrDecimalMixin(NoneClass, tuple, str, decimal.Decimal): + pass + class NoneTupleStrBoolMixin(NoneClass, tuple, str, BoolClass): + pass + class NoneTupleDecimalBoolMixin(NoneClass, tuple, decimal.Decimal, BoolClass): + pass + class NoneStrDecimalBoolMixin(NoneClass, str, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrDecimalMixin(frozendict.frozendict, tuple, str, decimal.Decimal): + pass + class FrozenDictTupleStrBoolMixin(frozendict.frozendict, tuple, str, BoolClass): + pass + class FrozenDictTupleDecimalBoolMixin(frozendict.frozendict, tuple, decimal.Decimal, BoolClass): + pass + class FrozenDictStrDecimalBoolMixin(frozendict.frozendict, str, decimal.Decimal, BoolClass): + pass + class TupleStrDecimalBoolMixin(tuple, str, decimal.Decimal, BoolClass): + pass + # qty 5 + class NoneFrozenDictTupleStrDecimalMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal): + pass + class NoneFrozenDictTupleStrBoolMixin(NoneClass, frozendict.frozendict, tuple, str, BoolClass): + pass + class NoneFrozenDictTupleDecimalBoolMixin(NoneClass, frozendict.frozendict, tuple, decimal.Decimal, BoolClass): + pass + class NoneFrozenDictStrDecimalBoolMixin(NoneClass, frozendict.frozendict, str, decimal.Decimal, BoolClass): + pass + class NoneTupleStrDecimalBoolMixin(NoneClass, tuple, str, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrDecimalBoolMixin(frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass): + pass + # qty 6 + class NoneFrozenDictTupleStrDecimalBoolMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass): + pass + # qty 8 + class NoneFrozenDictTupleStrDecimalBoolFileBytesMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass, FileIO, bytes): + pass +else: + # qty 1 + class NoneMixin: + _types = {NoneClass} + class FrozenDictMixin: + _types = {frozendict.frozendict} + class TupleMixin: + _types = {tuple} + class StrMixin: + _types = {str} + class DecimalMixin: + _types = {decimal.Decimal} + class BoolMixin: + _types = {BoolClass} + class BytesMixin: + _types = {bytes} + class FileMixin: + _types = {FileIO} + # qty 2 + class BinaryMixin: + _types = {bytes, FileIO} + class NoneFrozenDictMixin: + _types = {NoneClass, frozendict.frozendict} + class NoneTupleMixin: + _types = {NoneClass, tuple} + class NoneStrMixin: + _types = {NoneClass, str} + class NoneDecimalMixin: + _types = {NoneClass, decimal.Decimal} + class NoneBoolMixin: + _types = {NoneClass, BoolClass} + class FrozenDictTupleMixin: + _types = {frozendict.frozendict, tuple} + class FrozenDictStrMixin: + _types = {frozendict.frozendict, str} + class FrozenDictDecimalMixin: + _types = {frozendict.frozendict, decimal.Decimal} + class FrozenDictBoolMixin: + _types = {frozendict.frozendict, BoolClass} + class TupleStrMixin: + _types = {tuple, str} + class TupleDecimalMixin: + _types = {tuple, decimal.Decimal} + class TupleBoolMixin: + _types = {tuple, BoolClass} + class StrDecimalMixin: + _types = {str, decimal.Decimal} + class StrBoolMixin: + _types = {str, BoolClass} + class DecimalBoolMixin: + _types = {decimal.Decimal, BoolClass} + # qty 3 + class NoneFrozenDictTupleMixin: + _types = {NoneClass, frozendict.frozendict, tuple} + class NoneFrozenDictStrMixin: + _types = {NoneClass, frozendict.frozendict, str} + class NoneFrozenDictDecimalMixin: + _types = {NoneClass, frozendict.frozendict, decimal.Decimal} + class NoneFrozenDictBoolMixin: + _types = {NoneClass, frozendict.frozendict, BoolClass} + class NoneTupleStrMixin: + _types = {NoneClass, tuple, str} + class NoneTupleDecimalMixin: + _types = {NoneClass, tuple, decimal.Decimal} + class NoneTupleBoolMixin: + _types = {NoneClass, tuple, BoolClass} + class NoneStrDecimalMixin: + _types = {NoneClass, str, decimal.Decimal} + class NoneStrBoolMixin: + _types = {NoneClass, str, BoolClass} + class NoneDecimalBoolMixin: + _types = {NoneClass, decimal.Decimal, BoolClass} + class FrozenDictTupleStrMixin: + _types = {frozendict.frozendict, tuple, str} + class FrozenDictTupleDecimalMixin: + _types = {frozendict.frozendict, tuple, decimal.Decimal} + class FrozenDictTupleBoolMixin: + _types = {frozendict.frozendict, tuple, BoolClass} + class FrozenDictStrDecimalMixin: + _types = {frozendict.frozendict, str, decimal.Decimal} + class FrozenDictStrBoolMixin: + _types = {frozendict.frozendict, str, BoolClass} + class FrozenDictDecimalBoolMixin: + _types = {frozendict.frozendict, decimal.Decimal, BoolClass} + class TupleStrDecimalMixin: + _types = {tuple, str, decimal.Decimal} + class TupleStrBoolMixin: + _types = {tuple, str, BoolClass} + class TupleDecimalBoolMixin: + _types = {tuple, decimal.Decimal, BoolClass} + class StrDecimalBoolMixin: + _types = {str, decimal.Decimal, BoolClass} + # qty 4 + class NoneFrozenDictTupleStrMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str} + class NoneFrozenDictTupleDecimalMixin: + _types = {NoneClass, frozendict.frozendict, tuple, decimal.Decimal} + class NoneFrozenDictTupleBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, BoolClass} + class NoneFrozenDictStrDecimalMixin: + _types = {NoneClass, frozendict.frozendict, str, decimal.Decimal} + class NoneFrozenDictStrBoolMixin: + _types = {NoneClass, frozendict.frozendict, str, BoolClass} + class NoneFrozenDictDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, decimal.Decimal, BoolClass} + class NoneTupleStrDecimalMixin: + _types = {NoneClass, tuple, str, decimal.Decimal} + class NoneTupleStrBoolMixin: + _types = {NoneClass, tuple, str, BoolClass} + class NoneTupleDecimalBoolMixin: + _types = {NoneClass, tuple, decimal.Decimal, BoolClass} + class NoneStrDecimalBoolMixin: + _types = {NoneClass, str, decimal.Decimal, BoolClass} + class FrozenDictTupleStrDecimalMixin: + _types = {frozendict.frozendict, tuple, str, decimal.Decimal} + class FrozenDictTupleStrBoolMixin: + _types = {frozendict.frozendict, tuple, str, BoolClass} + class FrozenDictTupleDecimalBoolMixin: + _types = {frozendict.frozendict, tuple, decimal.Decimal, BoolClass} + class FrozenDictStrDecimalBoolMixin: + _types = {frozendict.frozendict, str, decimal.Decimal, BoolClass} + class TupleStrDecimalBoolMixin: + _types = {tuple, str, decimal.Decimal, BoolClass} + # qty 5 + class NoneFrozenDictTupleStrDecimalMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal} + class NoneFrozenDictTupleStrBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, BoolClass} + class NoneFrozenDictTupleDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, decimal.Decimal, BoolClass} + class NoneFrozenDictStrDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, str, decimal.Decimal, BoolClass} + class NoneTupleStrDecimalBoolMixin: + _types = {NoneClass, tuple, str, decimal.Decimal, BoolClass} + class FrozenDictTupleStrDecimalBoolMixin: + _types = {frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass} + # qty 6 + class NoneFrozenDictTupleStrDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass} + # qty 8 + class NoneFrozenDictTupleStrDecimalBoolFileBytesMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass, FileIO, bytes} + + +class ValidatorBase: + @staticmethod + def _is_json_validation_enabled_oapg(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + Note: the suffix _oapg stands for openapi python (experimental) generator and + it has been added to prevent collisions with other methods and properties + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + @staticmethod + def _raise_validation_errror_message_oapg(value, constraint_msg, constraint_value, path_to_item, additional_txt=""): + raise ApiValueError( + "Invalid value `{value}`, {constraint_msg} `{constraint_value}`{additional_txt} at {path_to_item}".format( + value=value, + constraint_msg=constraint_msg, + constraint_value=constraint_value, + additional_txt=additional_txt, + path_to_item=path_to_item, + ) + ) + + +class EnumBase: + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + EnumBase _validate_oapg + Validates that arg is in the enum's allowed values + """ + try: + cls.MetaOapg.enum_value_to_name[arg] + except KeyError: + raise ApiValueError("Invalid value {} passed in to {}, allowed_values={}".format(arg, cls, cls.MetaOapg.enum_value_to_name.keys())) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class BoolBase: + def is_true_oapg(self) -> bool: + """ + A replacement for x is True + True if the instance is a BoolClass True Singleton + """ + if not issubclass(self.__class__, BoolClass): + return False + return bool(self) + + def is_false_oapg(self) -> bool: + """ + A replacement for x is False + True if the instance is a BoolClass False Singleton + """ + if not issubclass(self.__class__, BoolClass): + return False + return bool(self) is False + + +class NoneBase: + def is_none_oapg(self) -> bool: + """ + A replacement for x is None + True if the instance is a NoneClass None Singleton + """ + if issubclass(self.__class__, NoneClass): + return True + return False + + +class StrBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @property + def as_str_oapg(self) -> str: + return self + + @property + def as_date_oapg(self) -> date: + raise Exception('not implemented') + + @property + def as_datetime_oapg(self) -> datetime: + raise Exception('not implemented') + + @property + def as_decimal_oapg(self) -> decimal.Decimal: + raise Exception('not implemented') + + @property + def as_uuid_oapg(self) -> uuid.UUID: + raise Exception('not implemented') + + @classmethod + def __check_str_validations( + cls, + arg: str, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxLength', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_length') and + len(arg) > cls.MetaOapg.max_length): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="length must be less than or equal to", + constraint_value=cls.MetaOapg.max_length, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minLength', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_length') and + len(arg) < cls.MetaOapg.min_length): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="length must be greater than or equal to", + constraint_value=cls.MetaOapg.min_length, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('pattern', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'regex')): + for regex_dict in cls.MetaOapg.regex: + flags = regex_dict.get('flags', 0) + if not re.search(regex_dict['pattern'], arg, flags=flags): + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must match regular expression", + constraint_value=regex_dict['pattern'], + path_to_item=validation_metadata.path_to_item, + additional_txt=" with flags=`{}`".format(flags) + ) + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must match regular expression", + constraint_value=regex_dict['pattern'], + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + StrBase _validate_oapg + Validates that validations pass + """ + if isinstance(arg, str): + cls.__check_str_validations(arg, validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class UUIDBase: + @property + @functools.lru_cache() + def as_uuid_oapg(self) -> uuid.UUID: + return uuid.UUID(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + uuid.UUID(arg) + return True + except ValueError: + raise ApiValueError( + "Invalid value '{}' for type UUID at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: typing.Optional[ValidationMetadata] = None, + ): + """ + UUIDBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class CustomIsoparser(isoparser): + + @_takes_ascii + def parse_isodatetime(self, dt_str): + components, pos = self._parse_isodate(dt_str) + if len(dt_str) > pos: + if self._sep is None or dt_str[pos:pos + 1] == self._sep: + components += self._parse_isotime(dt_str[pos + 1:]) + else: + raise ValueError('String contains unknown ISO components') + + if len(components) > 3 and components[3] == 24: + components[3] = 0 + return datetime(*components) + timedelta(days=1) + + if len(components) <= 3: + raise ValueError('Value is not a datetime') + + return datetime(*components) + + @_takes_ascii + def parse_isodate(self, datestr): + components, pos = self._parse_isodate(datestr) + + if len(datestr) > pos: + raise ValueError('String contains invalid time components') + + if len(components) > 3: + raise ValueError('String contains invalid time components') + + return date(*components) + + +DEFAULT_ISOPARSER = CustomIsoparser() + + +class DateBase: + @property + @functools.lru_cache() + def as_date_oapg(self) -> date: + return DEFAULT_ISOPARSER.parse_isodate(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + DEFAULT_ISOPARSER.parse_isodate(arg) + return True + except ValueError: + raise ApiValueError( + "Value does not conform to the required ISO-8601 date format. " + "Invalid value '{}' for type date at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: typing.Optional[ValidationMetadata] = None, + ): + """ + DateBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class DateTimeBase: + @property + @functools.lru_cache() + def as_datetime_oapg(self) -> datetime: + return DEFAULT_ISOPARSER.parse_isodatetime(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + DEFAULT_ISOPARSER.parse_isodatetime(arg) + return True + except ValueError: + raise ApiValueError( + "Value does not conform to the required ISO-8601 datetime format. " + "Invalid value '{}' for type datetime at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DateTimeBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class DecimalBase: + """ + A class for storing decimals that are sent over the wire as strings + These schemas must remain based on StrBase rather than NumberBase + because picking base classes must be deterministic + """ + + @property + @functools.lru_cache() + def as_decimal_oapg(self) -> decimal.Decimal: + return decimal.Decimal(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + decimal.Decimal(arg) + return True + except decimal.InvalidOperation: + raise ApiValueError( + "Value cannot be converted to a decimal. " + "Invalid value '{}' for type decimal at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DecimalBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class NumberBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @property + def as_int_oapg(self) -> int: + try: + return self._as_int + except AttributeError: + """ + Note: for some numbers like 9.0 they could be represented as an + integer but our code chooses to store them as + >>> Decimal('9.0').as_tuple() + DecimalTuple(sign=0, digits=(9, 0), exponent=-1) + so we can tell that the value came from a float and convert it back to a float + during later serialization + """ + if self.as_tuple().exponent < 0: + # this could be represented as an integer but should be represented as a float + # because that's what it was serialized from + raise ApiValueError(f'{self} is not an integer') + self._as_int = int(self) + return self._as_int + + @property + def as_float_oapg(self) -> float: + try: + return self._as_float + except AttributeError: + if self.as_tuple().exponent >= 0: + raise ApiValueError(f'{self} is not an float') + self._as_float = float(self) + return self._as_float + + @classmethod + def __check_numeric_validations( + cls, + arg, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if cls._is_json_validation_enabled_oapg('multipleOf', + validation_metadata.configuration) and hasattr(cls.MetaOapg, 'multiple_of'): + multiple_of_value = cls.MetaOapg.multiple_of + if (not (float(arg) / multiple_of_value).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="value must be a multiple of", + constraint_value=multiple_of_value, + path_to_item=validation_metadata.path_to_item + ) + + checking_max_or_min_values = any( + hasattr(cls.MetaOapg, validation_key) for validation_key in { + 'exclusive_maximum', + 'inclusive_maximum', + 'exclusive_minimum', + 'inclusive_minimum', + } + ) + if not checking_max_or_min_values: + return + + if (cls._is_json_validation_enabled_oapg('exclusiveMaximum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'exclusive_maximum') and + arg >= cls.MetaOapg.exclusive_maximum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value less than", + constraint_value=cls.MetaOapg.exclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('maximum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'inclusive_maximum') and + arg > cls.MetaOapg.inclusive_maximum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value less than or equal to", + constraint_value=cls.MetaOapg.inclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('exclusiveMinimum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'exclusive_minimum') and + arg <= cls.MetaOapg.exclusive_minimum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value greater than", + constraint_value=cls.MetaOapg.exclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minimum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'inclusive_minimum') and + arg < cls.MetaOapg.inclusive_minimum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value greater than or equal to", + constraint_value=cls.MetaOapg.inclusive_minimum, + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + NumberBase _validate_oapg + Validates that validations pass + """ + if isinstance(arg, decimal.Decimal): + cls.__check_numeric_validations(arg, validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class ListBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @classmethod + def __validate_items(cls, list_items, validation_metadata: ValidationMetadata): + """ + Ensures that: + - values passed in for items are valid + Exceptions will be raised if: + - invalid arguments were passed in + + Args: + list_items: the input list of items + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + + # if we have definitions for an items schema, use it + # otherwise accept anything + item_cls = getattr(cls.MetaOapg, 'items', UnsetAnyTypeSchema) + item_cls = cls._get_class_oapg(item_cls) + path_to_schemas = {} + for i, value in enumerate(list_items): + item_validation_metadata = ValidationMetadata( + from_server=validation_metadata.from_server, + configuration=validation_metadata.configuration, + path_to_item=validation_metadata.path_to_item+(i,), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if item_validation_metadata.validation_ran_earlier(item_cls): + continue + other_path_to_schemas = item_cls._validate_oapg( + value, validation_metadata=item_validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __check_tuple_validations( + cls, arg, + validation_metadata: ValidationMetadata): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_items') and + len(arg) > cls.MetaOapg.max_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of items must be less than or equal to", + constraint_value=cls.MetaOapg.max_items, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_items') and + len(arg) < cls.MetaOapg.min_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of items must be greater than or equal to", + constraint_value=cls.MetaOapg.min_items, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('uniqueItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'unique_items') and cls.MetaOapg.unique_items and arg): + unique_items = set(arg) + if len(arg) > len(unique_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="duplicate items were found, and the tuple must not contain duplicates because", + constraint_value='unique_items==True', + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + ListBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + if isinstance(arg, tuple): + cls.__check_tuple_validations(arg, validation_metadata) + _path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + if not isinstance(arg, tuple): + return _path_to_schemas + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + other_path_to_schemas = cls.__validate_items(arg, validation_metadata=updated_vm) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_items_oapg( + cls: 'Schema', + arg: typing.List[typing.Any], + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + ''' + ListBase _get_items_oapg + ''' + cast_items = [] + + for i, value in enumerate(arg): + item_path_to_item = path_to_item + (i,) + item_cls = path_to_schemas[item_path_to_item] + new_value = item_cls._get_new_instance_without_conversion_oapg( + value, + item_path_to_item, + path_to_schemas + ) + cast_items.append(new_value) + + return cast_items + + +class Discriminable: + MetaOapg: MetaOapgTyped + + @classmethod + def _ensure_discriminator_value_present_oapg(cls, disc_property_name: str, validation_metadata: ValidationMetadata, *args): + if not args or args and disc_property_name not in args[0]: + # The input data does not contain the discriminator property + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '{}' is missing at path: {}".format(disc_property_name, validation_metadata.path_to_item) + ) + + @classmethod + def get_discriminated_class_oapg(cls, disc_property_name: str, disc_payload_value: str): + """ + Used in schemas with discriminators + """ + if not hasattr(cls.MetaOapg, 'discriminator'): + return None + disc = cls.MetaOapg.discriminator() + if disc_property_name not in disc: + return None + discriminated_cls = disc[disc_property_name].get(disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if not hasattr(cls, 'MetaOapg'): + return None + elif not ( + hasattr(cls.MetaOapg, 'all_of') or + hasattr(cls.MetaOapg, 'one_of') or + hasattr(cls.MetaOapg, 'any_of') + ): + return None + # TODO stop traveling if a cycle is hit + if hasattr(cls.MetaOapg, 'all_of'): + for allof_cls in cls.MetaOapg.all_of(): + discriminated_cls = allof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if hasattr(cls.MetaOapg, 'one_of'): + for oneof_cls in cls.MetaOapg.one_of(): + discriminated_cls = oneof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if hasattr(cls.MetaOapg, 'any_of'): + for anyof_cls in cls.MetaOapg.any_of(): + discriminated_cls = anyof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + return None + + +class DictBase(Discriminable, ValidatorBase): + + @classmethod + def __validate_arg_presence(cls, arg): + """ + Ensures that: + - all required arguments are passed in + - the input variable names are valid + - present in properties or + - accepted because additionalProperties exists + Exceptions will be raised if: + - invalid arguments were passed in + - a var_name is invalid if additional_properties == NotAnyTypeSchema + and var_name not in properties.__annotations__ + - required properties were not passed in + + Args: + arg: the input dict + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + seen_required_properties = set() + invalid_arguments = [] + required_property_names = getattr(cls.MetaOapg, 'required', set()) + additional_properties = getattr(cls.MetaOapg, 'additional_properties', UnsetAnyTypeSchema) + properties = getattr(cls.MetaOapg, 'properties', {}) + property_annotations = getattr(properties, '__annotations__', {}) + for property_name in arg: + if property_name in required_property_names: + seen_required_properties.add(property_name) + elif property_name in property_annotations: + continue + elif additional_properties is not NotAnyTypeSchema: + continue + else: + invalid_arguments.append(property_name) + missing_required_arguments = list(required_property_names - seen_required_properties) + if missing_required_arguments: + missing_required_arguments.sort() + raise ApiTypeError( + "{} is missing {} required argument{}: {}".format( + cls.__name__, + len(missing_required_arguments), + "s" if len(missing_required_arguments) > 1 else "", + missing_required_arguments + ) + ) + if invalid_arguments: + invalid_arguments.sort() + raise ApiTypeError( + "{} was passed {} invalid argument{}: {}".format( + cls.__name__, + len(invalid_arguments), + "s" if len(invalid_arguments) > 1 else "", + invalid_arguments + ) + ) + + @classmethod + def __validate_args(cls, arg, validation_metadata: ValidationMetadata): + """ + Ensures that: + - values passed in for properties are valid + Exceptions will be raised if: + - invalid arguments were passed in + + Args: + arg: the input dict + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + path_to_schemas = {} + additional_properties = getattr(cls.MetaOapg, 'additional_properties', UnsetAnyTypeSchema) + properties = getattr(cls.MetaOapg, 'properties', {}) + property_annotations = getattr(properties, '__annotations__', {}) + for property_name, value in arg.items(): + path_to_item = validation_metadata.path_to_item+(property_name,) + if property_name in property_annotations: + schema = property_annotations[property_name] + elif additional_properties is not NotAnyTypeSchema: + if additional_properties is UnsetAnyTypeSchema: + """ + If additionalProperties is unset and this path_to_item does not yet have + any validations on it, validate it. + If it already has validations on it, skip this validation. + """ + if path_to_item in path_to_schemas: + continue + schema = additional_properties + else: + raise ApiTypeError('Unable to find schema for value={} in class={} at path_to_item={}'.format( + value, cls, validation_metadata.path_to_item+(property_name,) + )) + schema = cls._get_class_oapg(schema) + arg_validation_metadata = ValidationMetadata( + from_server=validation_metadata.from_server, + configuration=validation_metadata.configuration, + path_to_item=path_to_item, + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if arg_validation_metadata.validation_ran_earlier(schema): + continue + other_path_to_schemas = schema._validate_oapg(value, validation_metadata=arg_validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __check_dict_validations( + cls, + arg, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxProperties', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_properties') and + len(arg) > cls.MetaOapg.max_properties): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of properties must be less than or equal to", + constraint_value=cls.MetaOapg.max_properties, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minProperties', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_properties') and + len(arg) < cls.MetaOapg.min_properties): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of properties must be greater than or equal to", + constraint_value=cls.MetaOapg.min_properties, + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DictBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + if isinstance(arg, frozendict.frozendict): + cls.__check_dict_validations(arg, validation_metadata) + _path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + if not isinstance(arg, frozendict.frozendict): + return _path_to_schemas + cls.__validate_arg_presence(arg) + other_path_to_schemas = cls.__validate_args(arg, validation_metadata=validation_metadata) + update(_path_to_schemas, other_path_to_schemas) + try: + discriminator = cls.MetaOapg.discriminator() + except AttributeError: + return _path_to_schemas + # discriminator exists + disc_prop_name = list(discriminator.keys())[0] + cls._ensure_discriminator_value_present_oapg(disc_prop_name, validation_metadata, arg) + discriminated_cls = cls.get_discriminated_class_oapg( + disc_property_name=disc_prop_name, disc_payload_value=arg[disc_prop_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value was passed in to {}.{} Only the values {} are allowed at {}".format( + cls.__name__, + disc_prop_name, + list(discriminator[disc_prop_name].keys()), + validation_metadata.path_to_item + (disc_prop_name,) + ) + ) + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if updated_vm.validation_ran_earlier(discriminated_cls): + return _path_to_schemas + other_path_to_schemas = discriminated_cls._validate_oapg(arg, validation_metadata=updated_vm) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_properties_oapg( + cls, + arg: typing.Dict[str, typing.Any], + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + """ + DictBase _get_properties_oapg, this is how properties are set + These values already passed validation + """ + dict_items = {} + + for property_name_js, value in arg.items(): + property_path_to_item = path_to_item + (property_name_js,) + property_cls = path_to_schemas[property_path_to_item] + new_value = property_cls._get_new_instance_without_conversion_oapg( + value, + property_path_to_item, + path_to_schemas + ) + dict_items[property_name_js] = new_value + + return dict_items + + def __setattr__(self, name: str, value: typing.Any): + if not isinstance(self, FileIO): + raise AttributeError('property setting not supported on immutable instances') + + def __getattr__(self, name: str): + """ + for instance.name access + Properties are only type hinted for required properties + so that hasattr(instance, 'optionalProp') is False when that key is not present + """ + if not isinstance(self, frozendict.frozendict): + return super().__getattr__(name) + if name not in self.__class__.__annotations__: + raise AttributeError(f"{self} has no attribute '{name}'") + try: + value = self[name] + return value + except KeyError as ex: + raise AttributeError(str(ex)) + + def __getitem__(self, name: str): + """ + dict_instance[name] accessor + key errors thrown + """ + if not isinstance(self, frozendict.frozendict): + return super().__getattr__(name) + return super().__getitem__(name) + + def get_item_oapg(self, name: str) -> typing.Union['AnyTypeSchema', Unset]: + # dict_instance[name] accessor + if not isinstance(self, frozendict.frozendict): + raise NotImplementedError() + try: + return super().__getitem__(name) + except KeyError: + return unset + + +def cast_to_allowed_types( + arg: typing.Union[str, date, datetime, uuid.UUID, decimal.Decimal, int, float, None, dict, frozendict.frozendict, list, tuple, bytes, Schema, io.FileIO, io.BufferedReader], + from_server: bool, + validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]], + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), +) -> typing.Union[frozendict.frozendict, tuple, decimal.Decimal, str, bytes, BoolClass, NoneClass, FileIO]: + """ + Casts the input payload arg into the allowed types + The input validated_path_to_schemas is mutated by running this function + + When from_server is False then + - date/datetime is cast to str + - int/float is cast to Decimal + + If a Schema instance is passed in it is converted back to a primitive instance because + One may need to validate that data to the original Schema class AND additional different classes + those additional classes will need to be added to the new manufactured class for that payload + If the code didn't do this and kept the payload as a Schema instance it would fail to validate to other + Schema classes and the code wouldn't be able to mfg a new class that includes all valid schemas + TODO: store the validated schema classes in validation_metadata + + Args: + arg: the payload + from_server: whether this payload came from the server or not + validated_path_to_schemas: a dict that stores the validated classes at any path location in the payload + """ + if isinstance(arg, Schema): + # store the already run validations + schema_classes = set() + source_schema_was_unset = len(arg.__class__.__bases__) == 2 and UnsetAnyTypeSchema in arg.__class__.__bases__ + if not source_schema_was_unset: + """ + Do not include UnsetAnyTypeSchema and its base class because + it did not exist in the original spec schema definition + It was added to ensure that all instances are of type Schema and the allowed base types + """ + for cls in arg.__class__.__bases__: + if cls is Singleton: + # Skip Singleton + continue + schema_classes.add(cls) + validated_path_to_schemas[path_to_item] = schema_classes + + type_error = ApiTypeError(f"Invalid type. Required value type is str and passed type was {type(arg)} at {path_to_item}") + if isinstance(arg, str): + return str(arg) + elif isinstance(arg, (dict, frozendict.frozendict)): + return frozendict.frozendict({key: cast_to_allowed_types(val, from_server, validated_path_to_schemas, path_to_item + (key,)) for key, val in arg.items()}) + elif isinstance(arg, (bool, BoolClass)): + """ + this check must come before isinstance(arg, (int, float)) + because isinstance(True, int) is True + """ + if arg: + return BoolClass.TRUE + return BoolClass.FALSE + elif isinstance(arg, int): + return decimal.Decimal(arg) + elif isinstance(arg, float): + decimal_from_float = decimal.Decimal(arg) + if decimal_from_float.as_integer_ratio()[1] == 1: + # 9.0 -> Decimal('9.0') + # 3.4028234663852886e+38 -> Decimal('340282346638528859811704183484516925440.0') + return decimal.Decimal(str(decimal_from_float)+'.0') + return decimal_from_float + elif isinstance(arg, (tuple, list)): + return tuple([cast_to_allowed_types(item, from_server, validated_path_to_schemas, path_to_item + (i,)) for i, item in enumerate(arg)]) + elif isinstance(arg, (none_type, NoneClass)): + return NoneClass.NONE + elif isinstance(arg, (date, datetime)): + if not from_server: + return arg.isoformat() + raise type_error + elif isinstance(arg, uuid.UUID): + if not from_server: + return str(arg) + raise type_error + elif isinstance(arg, decimal.Decimal): + return decimal.Decimal(arg) + elif isinstance(arg, bytes): + return bytes(arg) + elif isinstance(arg, (io.FileIO, io.BufferedReader)): + return FileIO(arg) + raise ValueError('Invalid type passed in got input={} type={}'.format(arg, type(arg))) + + +class ComposedBase(Discriminable): + + @classmethod + def __get_allof_classes(cls, arg, validation_metadata: ValidationMetadata): + path_to_schemas = defaultdict(set) + for allof_cls in cls.MetaOapg.all_of(): + if validation_metadata.validation_ran_earlier(allof_cls): + continue + other_path_to_schemas = allof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __get_oneof_class( + cls, + arg, + discriminated_cls, + validation_metadata: ValidationMetadata, + ): + oneof_classes = [] + path_to_schemas = defaultdict(set) + for oneof_cls in cls.MetaOapg.one_of(): + if oneof_cls in path_to_schemas[validation_metadata.path_to_item]: + oneof_classes.append(oneof_cls) + continue + if validation_metadata.validation_ran_earlier(oneof_cls): + oneof_classes.append(oneof_cls) + continue + try: + path_to_schemas = oneof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and oneof_cls is discriminated_cls: + raise ex + continue + oneof_classes.append(oneof_cls) + if not oneof_classes: + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. None " + "of the oneOf schemas matched the input data.".format(cls) + ) + elif len(oneof_classes) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. Multiple " + "oneOf schemas {} matched the inputs, but a max of one is allowed.".format(cls, oneof_classes) + ) + # exactly one class matches + return path_to_schemas + + @classmethod + def __get_anyof_classes( + cls, + arg, + discriminated_cls, + validation_metadata: ValidationMetadata + ): + anyof_classes = [] + path_to_schemas = defaultdict(set) + for anyof_cls in cls.MetaOapg.any_of(): + if validation_metadata.validation_ran_earlier(anyof_cls): + anyof_classes.append(anyof_cls) + continue + + try: + other_path_to_schemas = anyof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and anyof_cls is discriminated_cls: + raise ex + continue + anyof_classes.append(anyof_cls) + update(path_to_schemas, other_path_to_schemas) + if not anyof_classes: + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. None " + "of the anyOf schemas matched the input data.".format(cls) + ) + return path_to_schemas + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + ComposedBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + # validation checking on types, validations, and enums + path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + + # process composed schema + discriminator = None + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'discriminator'): + discriminator = cls.MetaOapg.discriminator() + discriminated_cls = None + if discriminator and arg and isinstance(arg, frozendict.frozendict): + disc_property_name = list(discriminator.keys())[0] + cls._ensure_discriminator_value_present_oapg(disc_property_name, updated_vm, arg) + # get discriminated_cls by looking at the dict in the current class + discriminated_cls = cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=arg[disc_property_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value '{}' was passed in to {}.{} Only the values {} are allowed at {}".format( + arg[disc_property_name], + cls.__name__, + disc_property_name, + list(discriminator[disc_property_name].keys()), + updated_vm.path_to_item + (disc_property_name,) + ) + ) + + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'all_of'): + other_path_to_schemas = cls.__get_allof_classes(arg, validation_metadata=updated_vm) + update(path_to_schemas, other_path_to_schemas) + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'one_of'): + other_path_to_schemas = cls.__get_oneof_class( + arg, + discriminated_cls=discriminated_cls, + validation_metadata=updated_vm + ) + update(path_to_schemas, other_path_to_schemas) + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'any_of'): + other_path_to_schemas = cls.__get_anyof_classes( + arg, + discriminated_cls=discriminated_cls, + validation_metadata=updated_vm + ) + update(path_to_schemas, other_path_to_schemas) + not_cls = None + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'not_schema'): + not_cls = cls.MetaOapg.not_schema + not_cls = cls._get_class_oapg(not_cls) + if not_cls: + other_path_to_schemas = None + not_exception = ApiValueError( + "Invalid value '{}' was passed in to {}. Value is invalid because it is disallowed by {}".format( + arg, + cls.__name__, + not_cls.__name__, + ) + ) + if updated_vm.validation_ran_earlier(not_cls): + raise not_exception + + try: + other_path_to_schemas = not_cls._validate_oapg(arg, validation_metadata=updated_vm) + except (ApiValueError, ApiTypeError): + pass + if other_path_to_schemas: + raise not_exception + + if discriminated_cls is not None and not updated_vm.validation_ran_earlier(discriminated_cls): + # TODO use an exception from this package here + assert discriminated_cls in path_to_schemas[updated_vm.path_to_item] + return path_to_schemas + + +# DictBase, ListBase, NumberBase, StrBase, BoolBase, NoneBase +class ComposedSchema( + ComposedBase, + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema, + NoneFrozenDictTupleStrDecimalBoolMixin +): + @classmethod + def from_openapi_data_oapg(cls, *args: typing.Any, _configuration: typing.Optional[Configuration] = None, **kwargs): + if not args: + if not kwargs: + raise ApiTypeError('{} is missing required input data in args or kwargs'.format(cls.__name__)) + args = (kwargs, ) + return super().from_openapi_data_oapg(args[0], _configuration=_configuration) + + +class ListSchema( + ListBase, + Schema, + TupleMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: typing.List[typing.Any], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[typing.List[typing.Any], typing.Tuple[typing.Any]], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class NoneSchema( + NoneBase, + Schema, + NoneMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: None, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: None, **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class NumberSchema( + NumberBase, + Schema, + DecimalMixin +): + """ + This is used for type: number with no format + Both integers AND floats are accepted + """ + + @classmethod + def from_openapi_data_oapg(cls, arg: typing.Union[int, float], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[decimal.Decimal, int, float], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class IntBase: + @property + def as_int_oapg(self) -> int: + try: + return self._as_int + except AttributeError: + self._as_int = int(self) + return self._as_int + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + + denominator = arg.as_integer_ratio()[-1] + if denominator != 1: + raise ApiValueError( + "Invalid value '{}' for type integer at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + IntBase _validate_oapg + TODO what about types = (int, number) -> IntBase, NumberBase? We could drop int and keep number only + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class IntSchema(IntBase, NumberSchema): + + @classmethod + def from_openapi_data_oapg(cls, arg: int, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[decimal.Decimal, int], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class Int32Base: + __inclusive_minimum = decimal.Decimal(-2147483648) + __inclusive_maximum = decimal.Decimal(2147483647) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal) and arg.as_tuple().exponent == 0: + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type int32 at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Int32Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Int32Schema( + Int32Base, + IntSchema +): + pass + + +class Int64Base: + __inclusive_minimum = decimal.Decimal(-9223372036854775808) + __inclusive_maximum = decimal.Decimal(9223372036854775807) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal) and arg.as_tuple().exponent == 0: + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type int64 at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Int64Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Int64Schema( + Int64Base, + IntSchema +): + pass + + +class Float32Base: + __inclusive_minimum = decimal.Decimal(-3.4028234663852886e+38) + __inclusive_maximum = decimal.Decimal(3.4028234663852886e+38) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type float at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Float32Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Float32Schema( + Float32Base, + NumberSchema +): + + @classmethod + def from_openapi_data_oapg(cls, arg: float, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + +class Float64Base: + __inclusive_minimum = decimal.Decimal(-1.7976931348623157E+308) + __inclusive_maximum = decimal.Decimal(1.7976931348623157E+308) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type double at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Float64Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + +class Float64Schema( + Float64Base, + NumberSchema +): + + @classmethod + def from_openapi_data_oapg(cls, arg: float, _configuration: typing.Optional[Configuration] = None): + # todo check format + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + +class StrSchema( + StrBase, + Schema, + StrMixin +): + """ + date + datetime string types must inherit from this class + That is because one can validate a str payload as both: + - type: string (format unset) + - type: string, format: date + """ + + @classmethod + def from_openapi_data_oapg(cls, arg: str, _configuration: typing.Optional[Configuration] = None) -> 'StrSchema': + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[str, date, datetime, uuid.UUID], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class UUIDSchema(UUIDBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, uuid.UUID], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DateSchema(DateBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, date], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DateTimeSchema(DateTimeBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, datetime], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DecimalSchema(DecimalBase, StrSchema): + + def __new__(cls, arg: str, **kwargs: Configuration): + """ + Note: Decimals may not be passed in because cast_to_allowed_types is only invoked once for payloads + which can be simple (str) or complex (dicts or lists with nested values) + Because casting is only done once and recursively casts all values prior to validation then for a potential + client side Decimal input if Decimal was accepted as an input in DecimalSchema then one would not know + if one was using it for a StrSchema (where it should be cast to str) or one is using it for NumberSchema + where it should stay as Decimal. + """ + return super().__new__(cls, arg, **kwargs) + + +class BytesSchema( + Schema, + BytesMixin +): + """ + this class will subclass bytes and is immutable + """ + def __new__(cls, arg: bytes, **kwargs: Configuration): + return super(Schema, cls).__new__(cls, arg) + + +class FileSchema( + Schema, + FileMixin +): + """ + This class is NOT immutable + Dynamic classes are built using it for example when AnyType allows in binary data + Al other schema classes ARE immutable + If one wanted to make this immutable one could make this a DictSchema with required properties: + - data = BytesSchema (which would be an immutable bytes based schema) + - file_name = StrSchema + and cast_to_allowed_types would convert bytes and file instances into dicts containing data + file_name + The downside would be that data would be stored in memory which one may not want to do for very large files + + The developer is responsible for closing this file and deleting it + + This class was kept as mutable: + - to allow file reading and writing to disk + - to be able to preserve file name info + """ + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader], **kwargs: Configuration): + return super(Schema, cls).__new__(cls, arg) + + +class BinaryBase: + pass + + +class BinarySchema( + ComposedBase, + BinaryBase, + Schema, + BinaryMixin +): + class MetaOapg: + @staticmethod + def one_of(): + return [ + BytesSchema, + FileSchema, + ] + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader, bytes], **kwargs: Configuration): + return super().__new__(cls, arg) + + +class BoolSchema( + BoolBase, + Schema, + BoolMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: bool, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: bool, **kwargs: ValidationMetadata): + return super().__new__(cls, arg, **kwargs) + + +class AnyTypeSchema( + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema, + NoneFrozenDictTupleStrDecimalBoolFileBytesMixin +): + # Python representation of a schema defined as true or {} + pass + + +class UnsetAnyTypeSchema(AnyTypeSchema): + # Used when additionalProperties/items was not explicitly defined and a defining schema is needed + pass + + +class NotAnyTypeSchema( + ComposedSchema, +): + """ + Python representation of a schema defined as false or {'not': {}} + Does not allow inputs in of AnyType + Note: validations on this class are never run because the code knows that no inputs will ever validate + """ + + class MetaOapg: + not_schema = AnyTypeSchema + + def __new__( + cls, + *args, + _configuration: typing.Optional[Configuration] = None, + ) -> 'NotAnyTypeSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + +class DictSchema( + DictBase, + Schema, + FrozenDictMixin +): + @classmethod + def from_openapi_data_oapg(cls, arg: typing.Dict[str, typing.Any], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, *args: typing.Union[dict, frozendict.frozendict], **kwargs: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, bytes, Schema, Unset, ValidationMetadata]): + return super().__new__(cls, *args, **kwargs) + + +schema_type_classes = {NoneSchema, DictSchema, ListSchema, NumberSchema, StrSchema, BoolSchema, AnyTypeSchema} + + +@functools.lru_cache() +def get_new_class( + class_name: str, + bases: typing.Tuple[typing.Type[typing.Union[Schema, typing.Any]], ...] +) -> typing.Type[Schema]: + """ + Returns a new class that is made with the subclass bases + """ + new_cls: typing.Type[Schema] = type(class_name, bases, {}) + return new_cls + + +LOG_CACHE_USAGE = False + + +def log_cache_usage(cache_fn): + if LOG_CACHE_USAGE: + print(cache_fn.__name__, cache_fn.cache_info()) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md index 5921adf7dc..21f35abad1 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md @@ -61,7 +61,7 @@ Each operation can use different server URL defined using `OperationServers` map An operation is uniquely identified by `"{classname}Service.{nickname}"` string. Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. -``` +```golang ctx := context.WithValue(context.Background(), x_auth_id_alias.ContextOperationServerIndices, map[string]int{ "{classname}Service.{nickname}": 2, }) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/test/api_usage_test.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/test/api_usage_test.go new file mode 100644 index 0000000000..7aa3f68f51 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/test/api_usage_test.go @@ -0,0 +1,73 @@ +/* +OpenAPI Extension x-auth-id-alias + +Testing UsageApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package x_auth_id_alias + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_x_auth_id_alias_UsageApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test UsageApiService AnyKey", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UsageApi.AnyKey(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UsageApiService BothKeys", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UsageApi.BothKeys(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UsageApiService KeyInHeader", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UsageApi.KeyInHeader(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UsageApiService KeyInQuery", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UsageApi.KeyInQuery(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/.gitignore b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.gitignore similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/.gitignore rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.gitignore diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/.gitlab-ci.yml b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.gitlab-ci.yml similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/.gitlab-ci.yml rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.gitlab-ci.yml diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.openapi-generator-ignore b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.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/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator/FILES b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.openapi-generator/FILES similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator/FILES rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.openapi-generator/FILES diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/.travis.yml b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.travis.yml similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/.travis.yml rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/.travis.yml diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/README.md b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/README.md new file mode 100644 index 0000000000..12a5abda0b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/README.md @@ -0,0 +1,146 @@ +# x-auth-id-alias +This specification shows how to use x-auth-id-alias extension for API keys. + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonPriorClientCodegen + +## Requirements. + +Python >=3.6 + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: +```python +import x_auth_id_alias +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import x_auth_id_alias +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python + +import time +import x_auth_id_alias +from pprint import pprint +from x_auth_id_alias.api import usage_api +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = x_auth_id_alias.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure API key authorization: api_key +configuration.api_key['api_key'] = 'YOUR_API_KEY' + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['api_key'] = 'Bearer' + +# Configure API key authorization: api_key_query +configuration.api_key['api_key_query'] = 'YOUR_API_KEY' + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['api_key_query'] = 'Bearer' + + +# Enter a context with an instance of the API client +with x_auth_id_alias.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = usage_api.UsageApi(api_client) + + try: + # Use any API key + api_response = api_instance.any_key() + pprint(api_response) + except x_auth_id_alias.ApiException as e: + print("Exception when calling UsageApi->any_key: %s\n" % e) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*UsageApi* | [**any_key**](docs/UsageApi.md#any_key) | **GET** /any | Use any API key +*UsageApi* | [**both_keys**](docs/UsageApi.md#both_keys) | **GET** /both | Use both API keys +*UsageApi* | [**key_in_header**](docs/UsageApi.md#key_in_header) | **GET** /header | Use API key in header +*UsageApi* | [**key_in_query**](docs/UsageApi.md#key_in_query) | **GET** /query | Use API key in query + + +## Documentation For Models + + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: X-Api-Key +- **Location**: HTTP header + + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: URL query string + + +## Author + + + + +## Notes for Large OpenAPI documents +If the OpenAPI document is large, imports in x_auth_id_alias.apis and x_auth_id_alias.models may fail with a +RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: + +Solution 1: +Use specific imports for apis and models like: +- `from x_auth_id_alias.api.default_api import DefaultApi` +- `from x_auth_id_alias.model.pet import Pet` + +Solution 2: +Before importing the package, adjust the maximum recursion limit as shown below: +``` +import sys +sys.setrecursionlimit(1500) +import x_auth_id_alias +from x_auth_id_alias.apis import * +from x_auth_id_alias.models import * +``` + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/docs/UsageApi.md b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/docs/UsageApi.md similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/docs/UsageApi.md rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/docs/UsageApi.md diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/git_push.sh b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/requirements.txt b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/requirements.txt similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/requirements.txt rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/requirements.txt diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/setup.cfg b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/setup.cfg similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/setup.cfg rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/setup.cfg diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/setup.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/setup.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/setup.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/setup.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/test-requirements.txt b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/test-requirements.txt similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/test-requirements.txt rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/test-requirements.txt diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/test/__init__.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/test/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/test/test_usage_api.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/test/test_usage_api.py similarity index 98% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/test/test_usage_api.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/test/test_usage_api.py index db5d36ec62..01ebfea969 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/test/test_usage_api.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/test/test_usage_api.py @@ -1,5 +1,3 @@ -# coding: utf-8 - """ OpenAPI Extension x-auth-id-alias diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/tests/test_api_keys.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/tests/test_api_keys.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/tests/test_api_keys.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/tests/test_api_keys.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/tox.ini b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/tox.ini similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/tox.ini rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/tox.ini diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/__init__.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/__init__.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/__init__.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/__init__.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api/__init__.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/api/__init__.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api/__init__.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/api/__init__.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api/usage_api.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/api/usage_api.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api/usage_api.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/api/usage_api.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api_client.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/api_client.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api_client.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/api_client.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/apis/__init__.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/apis/__init__.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/apis/__init__.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/apis/__init__.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/configuration.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/configuration.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/configuration.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/configuration.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/exceptions.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/exceptions.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/exceptions.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/exceptions.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model/__init__.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/model/__init__.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model/__init__.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/model/__init__.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/model_utils.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/model_utils.py new file mode 100644 index 0000000000..d90e2383d8 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/model_utils.py @@ -0,0 +1,2058 @@ +""" + OpenAPI Extension x-auth-id-alias + + This specification shows how to use x-auth-id-alias extension for API keys. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from datetime import date, datetime # noqa: F401 +from copy import deepcopy +import inspect +import io +import os +import pprint +import re +import tempfile +import uuid + +from dateutil.parser import parse + +from x_auth_id_alias.exceptions import ( + ApiKeyError, + ApiAttributeError, + ApiTypeError, + ApiValueError, +) + +none_type = type(None) +file_type = io.IOBase + + +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python( + kwargs, _self if isinstance( + _self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + +class cached_property(object): + # this caches the result of the function call for fn with no inputs + # use this as a decorator on function methods that you want converted + # into cached properties + result_key = '_results' + + def __init__(self, fn): + self._fn = fn + + def __get__(self, instance, cls=None): + if self.result_key in vars(self): + return vars(self)[self.result_key] + else: + result = self._fn() + setattr(self, self.result_key, result) + return result + + +PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) + + +def allows_single_value_input(cls): + """ + This function returns True if the input composed schema model or any + descendant model allows a value only input + This is true for cases where oneOf contains items like: + oneOf: + - float + - NumberWithValidation + - StringEnum + - ArrayModel + - null + TODO: lru_cache this + """ + if ( + issubclass(cls, ModelSimple) or + cls in PRIMITIVE_TYPES + ): + return True + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return False + return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) + return False + + +def composed_model_input_classes(cls): + """ + This function returns a list of the possible models that can be accepted as + inputs. + TODO: lru_cache this + """ + if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: + return [cls] + elif issubclass(cls, ModelNormal): + if cls.discriminator is None: + return [cls] + else: + return get_discriminated_classes(cls) + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return [] + if cls.discriminator is None: + input_classes = [] + for c in cls._composed_schemas['oneOf']: + input_classes.extend(composed_model_input_classes(c)) + return input_classes + else: + return get_discriminated_classes(cls) + return [] + + +class OpenApiModel(object): + """The base class for all OpenAPIModels""" + + def set_attribute(self, name, value): + # this is only used to set properties on self + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + + if name in self.openapi_types: + required_types_mixed = self.openapi_types[name] + elif self.additional_properties_type is None: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + path_to_item + ) + elif self.additional_properties_type is not None: + required_types_mixed = self.additional_properties_type + + if get_simple_class(name) != str: + error_msg = type_error_message( + var_name=name, + var_value=name, + valid_classes=(str,), + key_type=True + ) + raise ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=(str,), + key_type=True + ) + + if self._check_type: + value = validate_and_convert_types( + value, required_types_mixed, path_to_item, self._spec_property_naming, + self._check_type, configuration=self._configuration) + if (name,) in self.allowed_values: + check_allowed_values( + self.allowed_values, + (name,), + value + ) + if (name,) in self.validations: + check_validations( + self.validations, + (name,), + value, + self._configuration + ) + self.__dict__['_data_store'][name] = value + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other + + def __setattr__(self, attr, value): + """set the value of an attribute using dot notation: `instance.attr = val`""" + self[attr] = value + + def __getattr__(self, attr): + """get the value of an attribute using dot notation: `instance.attr`""" + return self.__getitem__(attr) + + def __copy__(self): + cls = self.__class__ + if self.get("_spec_property_naming", False): + return cls._new_from_openapi_data(**self.__dict__) + else: + return cls.__new__(cls, **self.__dict__) + + def __deepcopy__(self, memo): + cls = self.__class__ + + if self.get("_spec_property_naming", False): + new_inst = cls._new_from_openapi_data() + else: + new_inst = cls.__new__(cls, **self.__dict__) + + for k, v in self.__dict__.items(): + setattr(new_inst, k, deepcopy(v, memo)) + return new_inst + + + def __new__(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return super(OpenApiModel, cls).__new__(cls) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return super(OpenApiModel, cls).__new__(cls) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = super(OpenApiModel, cls).__new__(cls) + self_inst.__init__(*args, **kwargs) + + if kwargs.get("_spec_property_naming", False): + # when true, implies new is from deserialization + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + else: + new_inst = new_cls.__new__(new_cls, *args, **kwargs) + new_inst.__init__(*args, **kwargs) + + return new_inst + + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + +class ModelSimple(OpenApiModel): + """the parent class of models whose type != object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_str(self): + """Returns the string representation of the model""" + return str(self.value) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + this_val = self._data_store['value'] + that_val = other._data_store['value'] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + return vals_equal + + +class ModelNormal(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +class ModelComposed(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi and have oneOf/allOf/anyOf + + When one sets a property we use var_name_to_model_instances to store the value in + the correct class instances + run any type checking + validation code. + When one gets a property we use var_name_to_model_instances to get the value + from the correct class instances. + This allows multiple composed schemas to contain the same property with additive + constraints on the value. + + _composed_schemas (dict) stores the anyOf/allOf/oneOf classes + key (str): allOf/oneOf/anyOf + value (list): the classes in the XOf definition. + Note: none_type can be included when the openapi document version >= 3.1.0 + _composed_instances (list): stores a list of instances of the composed schemas + defined in _composed_schemas. When properties are accessed in the self instance, + they are returned from the self._data_store or the data stores in the instances + in self._composed_schemas + _var_name_to_model_instances (dict): maps between a variable name on self and + the composed instances (self included) which contain that data + key (str): property name + value (list): list of class instances, self or instances in _composed_instances + which contain the value that the key is referring to. + """ + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None + + __unset_attribute_value__ = object() + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + # get the attribute from the correct instance + model_instances = self._var_name_to_model_instances.get(name) + values = [] + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + v = model_instance._data_store[name] + if v not in values: + values.append(v) + len_values = len(values) + if len_values == 0: + return default + elif len_values == 1: + return values[0] + elif len_values > 1: + raise ApiValueError( + "Values stored for property {0} in {1} differ when looking " + "at self and self's composed instances. All values must be " + "the same".format(name, type(self).__name__), + [e for e in [self._path_to_item, name] if e] + ) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + value = self.get(name, self.__unset_attribute_value__) + if value is self.__unset_attribute_value__: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + return value + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + + if name in self.required_properties: + return name in self.__dict__ + + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + return True + + return False + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +COERCION_INDEX_BY_TYPE = { + ModelComposed: 0, + ModelNormal: 1, + ModelSimple: 2, + none_type: 3, # The type of 'None'. + list: 4, + dict: 5, + float: 6, + int: 7, + bool: 8, + datetime: 9, + date: 10, + str: 11, + file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. +} + +# these are used to limit what type conversions we try to do +# when we have a valid type already and we want to try converting +# to another type +UPCONVERSION_TYPE_PAIRS = ( + (str, datetime), + (str, date), + # A float may be serialized as an integer, e.g. '3' is a valid serialized float. + (int, float), + (list, ModelComposed), + (dict, ModelComposed), + (str, ModelComposed), + (int, ModelComposed), + (float, ModelComposed), + (list, ModelComposed), + (list, ModelNormal), + (dict, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), +) + +COERCIBLE_TYPE_PAIRS = { + False: ( # client instantiation of a model with client data + # (dict, ModelComposed), + # (list, ModelComposed), + # (dict, ModelNormal), + # (list, ModelNormal), + # (str, ModelSimple), + # (int, ModelSimple), + # (float, ModelSimple), + # (list, ModelSimple), + # (str, int), + # (str, float), + # (str, datetime), + # (str, date), + # (int, str), + # (float, str), + ), + True: ( # server -> client data + (dict, ModelComposed), + (list, ModelComposed), + (dict, ModelNormal), + (list, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), + # (str, int), + # (str, float), + (str, datetime), + (str, date), + # (int, str), + # (float, str), + (str, file_type) + ), +} + + +def get_simple_class(input_value): + """Returns an input_value's simple class that we will use for type checking + Python2: + float and int will return int, where int is the python3 int backport + str and unicode will return str, where str is the python3 str backport + Note: float and int ARE both instances of int backport + Note: str_py2 and unicode_py2 are NOT both instances of str backport + + Args: + input_value (class/class_instance): the item for which we will return + the simple class + """ + if isinstance(input_value, type): + # input_value is a class + return input_value + elif isinstance(input_value, tuple): + return tuple + elif isinstance(input_value, list): + return list + elif isinstance(input_value, dict): + return dict + elif isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, file_type): + return file_type + elif isinstance(input_value, bool): + # this must be higher than the int check because + # isinstance(True, int) == True + return bool + elif isinstance(input_value, int): + return int + elif isinstance(input_value, datetime): + # this must be higher than the date check because + # isinstance(datetime_instance, date) == True + return datetime + elif isinstance(input_value, date): + return date + elif isinstance(input_value, str): + return str + return type(input_value) + + +def check_allowed_values(allowed_values, input_variable_path, input_values): + """Raises an exception if the input_values are not allowed + + Args: + allowed_values (dict): the allowed_values dict + input_variable_path (tuple): the path to the input variable + input_values (list/str/int/float/date/datetime): the values that we + are checking to see if they are in allowed_values + """ + these_allowed_values = list(allowed_values[input_variable_path].values()) + if (isinstance(input_values, list) + and not set(input_values).issubset( + set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values) - set(these_allowed_values))), + raise ApiValueError( + "Invalid values for `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (isinstance(input_values, dict) + and not set( + input_values.keys()).issubset(set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values.keys()) - set(these_allowed_values))) + raise ApiValueError( + "Invalid keys in `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (not isinstance(input_values, (list, dict)) + and input_values not in these_allowed_values): + raise ApiValueError( + "Invalid value for `%s` (%s), must be one of %s" % + ( + input_variable_path[0], + input_values, + these_allowed_values + ) + ) + + +def is_json_validation_enabled(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + +def check_validations( + validations, input_variable_path, input_values, + configuration=None): + """Raises an exception if the input_values are invalid + + Args: + validations (dict): the validation dictionary. + input_variable_path (tuple): the path to the input variable. + input_values (list/str/int/float/date/datetime): the values that we + are checking. + configuration (Configuration): the configuration class. + """ + + if input_values is None: + return + + current_validations = validations[input_variable_path] + if (is_json_validation_enabled('multipleOf', configuration) and + 'multiple_of' in current_validations and + isinstance(input_values, (int, float)) and + not (float(input_values) / current_validations['multiple_of']).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + raise ApiValueError( + "Invalid value for `%s`, value must be a multiple of " + "`%s`" % ( + input_variable_path[0], + current_validations['multiple_of'] + ) + ) + + if (is_json_validation_enabled('maxLength', configuration) and + 'max_length' in current_validations and + len(input_values) > current_validations['max_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['max_length'] + ) + ) + + if (is_json_validation_enabled('minLength', configuration) and + 'min_length' in current_validations and + len(input_values) < current_validations['min_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be greater than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['min_length'] + ) + ) + + if (is_json_validation_enabled('maxItems', configuration) and + 'max_items' in current_validations and + len(input_values) > current_validations['max_items']): + raise ApiValueError( + "Invalid value for `%s`, number of items must be less than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['max_items'] + ) + ) + + if (is_json_validation_enabled('minItems', configuration) and + 'min_items' in current_validations and + len(input_values) < current_validations['min_items']): + raise ValueError( + "Invalid value for `%s`, number of items must be greater than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['min_items'] + ) + ) + + items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', + 'inclusive_minimum') + if (any(item in current_validations for item in items)): + if isinstance(input_values, list): + max_val = max(input_values) + min_val = min(input_values) + elif isinstance(input_values, dict): + max_val = max(input_values.values()) + min_val = min(input_values.values()) + else: + max_val = input_values + min_val = input_values + + if (is_json_validation_enabled('exclusiveMaximum', configuration) and + 'exclusive_maximum' in current_validations and + max_val >= current_validations['exclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than `%s`" % ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('maximum', configuration) and + 'inclusive_maximum' in current_validations and + max_val > current_validations['inclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['inclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('exclusiveMinimum', configuration) and + 'exclusive_minimum' in current_validations and + min_val <= current_validations['exclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than `%s`" % + ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('minimum', configuration) and + 'inclusive_minimum' in current_validations and + min_val < current_validations['inclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than or equal " + "to `%s`" % ( + input_variable_path[0], + current_validations['inclusive_minimum'] + ) + ) + flags = current_validations.get('regex', {}).get('flags', 0) + if (is_json_validation_enabled('pattern', configuration) and + 'regex' in current_validations and + not re.search(current_validations['regex']['pattern'], + input_values, flags=flags)): + err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( + input_variable_path[0], + current_validations['regex']['pattern'] + ) + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + err_msg = r"%s with flags=`%s`" % (err_msg, flags) + raise ApiValueError(err_msg) + + +def order_response_types(required_types): + """Returns the required types sorted in coercion order + + Args: + required_types (list/tuple): collection of classes or instance of + list or dict with class information inside it. + + Returns: + (list): coercion order sorted collection of classes or instance + of list or dict with class information inside it. + """ + + def index_getter(class_or_instance): + if isinstance(class_or_instance, list): + return COERCION_INDEX_BY_TYPE[list] + elif isinstance(class_or_instance, dict): + return COERCION_INDEX_BY_TYPE[dict] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelComposed)): + return COERCION_INDEX_BY_TYPE[ModelComposed] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelNormal)): + return COERCION_INDEX_BY_TYPE[ModelNormal] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelSimple)): + return COERCION_INDEX_BY_TYPE[ModelSimple] + elif class_or_instance in COERCION_INDEX_BY_TYPE: + return COERCION_INDEX_BY_TYPE[class_or_instance] + raise ApiValueError("Unsupported type: %s" % class_or_instance) + + sorted_types = sorted( + required_types, + key=lambda class_or_instance: index_getter(class_or_instance) + ) + return sorted_types + + +def remove_uncoercible(required_types_classes, current_item, spec_property_naming, + must_convert=True): + """Only keeps the type conversions that are possible + + Args: + required_types_classes (tuple): tuple of classes that are required + these should be ordered by COERCION_INDEX_BY_TYPE + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + current_item (any): the current item (input data) to be converted + + Keyword Args: + must_convert (bool): if True the item to convert is of the wrong + type and we want a big list of coercibles + if False, we want a limited list of coercibles + + Returns: + (list): the remaining coercible required types, classes only + """ + current_type_simple = get_simple_class(current_item) + + results_classes = [] + for required_type_class in required_types_classes: + # convert our models to OpenApiModel + required_type_class_simplified = required_type_class + if isinstance(required_type_class_simplified, type): + if issubclass(required_type_class_simplified, ModelComposed): + required_type_class_simplified = ModelComposed + elif issubclass(required_type_class_simplified, ModelNormal): + required_type_class_simplified = ModelNormal + elif issubclass(required_type_class_simplified, ModelSimple): + required_type_class_simplified = ModelSimple + + if required_type_class_simplified == current_type_simple: + # don't consider converting to one's own class + continue + + class_pair = (current_type_simple, required_type_class_simplified) + if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: + results_classes.append(required_type_class) + elif class_pair in UPCONVERSION_TYPE_PAIRS: + results_classes.append(required_type_class) + return results_classes + + +def get_discriminated_classes(cls): + """ + Returns all the classes that a discriminator converts to + TODO: lru_cache this + """ + possible_classes = [] + key = list(cls.discriminator.keys())[0] + if is_type_nullable(cls): + possible_classes.append(cls) + for discr_cls in cls.discriminator[key].values(): + if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: + possible_classes.extend(get_discriminated_classes(discr_cls)) + else: + possible_classes.append(discr_cls) + return possible_classes + + +def get_possible_classes(cls, from_server_context): + # TODO: lru_cache this + possible_classes = [cls] + if from_server_context: + return possible_classes + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + possible_classes = [] + possible_classes.extend(get_discriminated_classes(cls)) + elif issubclass(cls, ModelComposed): + possible_classes.extend(composed_model_input_classes(cls)) + return possible_classes + + +def get_required_type_classes(required_types_mixed, spec_property_naming): + """Converts the tuple required_types into a tuple and a dict described + below + + Args: + required_types_mixed (tuple/list): will contain either classes or + instance of list or dict + spec_property_naming (bool): if True these values came from the + server, and we use the data types in our endpoints. + If False, we are client side and we need to include + oneOf and discriminator classes inside the data types in our endpoints + + Returns: + (valid_classes, dict_valid_class_to_child_types_mixed): + valid_classes (tuple): the valid classes that the current item + should be + dict_valid_class_to_child_types_mixed (dict): + valid_class (class): this is the key + child_types_mixed (list/dict/tuple): describes the valid child + types + """ + valid_classes = [] + child_req_types_by_current_type = {} + for required_type in required_types_mixed: + if isinstance(required_type, list): + valid_classes.append(list) + child_req_types_by_current_type[list] = required_type + elif isinstance(required_type, tuple): + valid_classes.append(tuple) + child_req_types_by_current_type[tuple] = required_type + elif isinstance(required_type, dict): + valid_classes.append(dict) + child_req_types_by_current_type[dict] = required_type[str] + else: + valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) + return tuple(valid_classes), child_req_types_by_current_type + + +def change_keys_js_to_python(input_dict, model_class): + """ + Converts from javascript_key keys in the input_dict to python_keys in + the output dict using the mapping in model_class. + If the input_dict contains a key which does not declared in the model_class, + the key is added to the output dict as is. The assumption is the model_class + may have undeclared properties (additionalProperties attribute in the OAS + document). + """ + + if getattr(model_class, 'attribute_map', None) is None: + return input_dict + output_dict = {} + reversed_attr_map = {value: key for key, value in + model_class.attribute_map.items()} + for javascript_key, value in input_dict.items(): + python_key = reversed_attr_map.get(javascript_key) + if python_key is None: + # if the key is unknown, it is in error or it is an + # additionalProperties variable + python_key = javascript_key + output_dict[python_key] = value + return output_dict + + +def get_type_error(var_value, path_to_item, valid_classes, key_type=False): + error_msg = type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type + ) + + +def deserialize_primitive(data, klass, path_to_item): + """Deserializes string to primitive type. + + :param data: str/int/float + :param klass: str/class the class to convert to + + :return: int, float, str, bool, date, datetime + """ + additional_message = "" + try: + if klass in {datetime, date}: + additional_message = ( + "If you need your parameter to have a fallback " + "string value, please set its type as `type: {}` in your " + "spec. That allows the value to be any type. " + ) + if klass == datetime: + if len(data) < 8: + raise ValueError("This is not a datetime") + # The string should be in iso8601 datetime format. + parsed_datetime = parse(data) + date_only = ( + parsed_datetime.hour == 0 and + parsed_datetime.minute == 0 and + parsed_datetime.second == 0 and + parsed_datetime.tzinfo is None and + 8 <= len(data) <= 10 + ) + if date_only: + raise ValueError("This is a date, not a datetime") + return parsed_datetime + elif klass == date: + if len(data) < 8: + raise ValueError("This is not a date") + return parse(data).date() + else: + converted_value = klass(data) + if isinstance(data, str) and klass == float: + if str(converted_value) != data: + # '7' -> 7.0 -> '7.0' != '7' + raise ValueError('This is not a float') + return converted_value + except (OverflowError, ValueError) as ex: + # parse can raise OverflowError + raise ApiValueError( + "{0}Failed to parse {1} as {2}".format( + additional_message, repr(data), klass.__name__ + ), + path_to_item=path_to_item + ) from ex + + +def get_discriminator_class(model_class, + discr_name, + discr_value, cls_visited): + """Returns the child class specified by the discriminator. + + Args: + model_class (OpenApiModel): the model class. + discr_name (string): the name of the discriminator property. + discr_value (any): the discriminator value. + cls_visited (list): list of model classes that have been visited. + Used to determine the discriminator class without + visiting circular references indefinitely. + + Returns: + used_model_class (class/None): the chosen child class that will be used + to deserialize the data, for example dog.Dog. + If a class is not found, None is returned. + """ + + if model_class in cls_visited: + # The class has already been visited and no suitable class was found. + return None + cls_visited.append(model_class) + used_model_class = None + if discr_name in model_class.discriminator: + class_name_to_discr_class = model_class.discriminator[discr_name] + used_model_class = class_name_to_discr_class.get(discr_value) + if used_model_class is None: + # We didn't find a discriminated class in class_name_to_discr_class. + # So look in the ancestor or descendant discriminators + # The discriminator mapping may exist in a descendant (anyOf, oneOf) + # or ancestor (allOf). + # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat + # hierarchy, the discriminator mappings may be defined at any level + # in the hierarchy. + # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig + # if we try to make BasquePig from mammal, we need to travel through + # the oneOf descendant discriminators to find BasquePig + descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ + model_class._composed_schemas.get('anyOf', ()) + ancestor_classes = model_class._composed_schemas.get('allOf', ()) + possible_classes = descendant_classes + ancestor_classes + for cls in possible_classes: + # Check if the schema has inherited discriminators. + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + used_model_class = get_discriminator_class( + cls, discr_name, discr_value, cls_visited) + if used_model_class is not None: + return used_model_class + return used_model_class + + +def deserialize_model(model_data, model_class, path_to_item, check_type, + configuration, spec_property_naming): + """Deserializes model_data to model instance. + + Args: + model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model + model_class (OpenApiModel): the model class + path_to_item (list): path to the model in the received data + check_type (bool): whether to check the data tupe for the values in + the model + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + + Returns: + model instance + + Raise: + ApiTypeError + ApiValueError + ApiKeyError + """ + + kw_args = dict(_check_type=check_type, + _path_to_item=path_to_item, + _configuration=configuration, + _spec_property_naming=spec_property_naming) + + if issubclass(model_class, ModelSimple): + return model_class._new_from_openapi_data(model_data, **kw_args) + elif isinstance(model_data, list): + return model_class._new_from_openapi_data(*model_data, **kw_args) + if isinstance(model_data, dict): + kw_args.update(model_data) + return model_class._new_from_openapi_data(**kw_args) + elif isinstance(model_data, PRIMITIVE_TYPES): + return model_class._new_from_openapi_data(model_data, **kw_args) + + +def deserialize_file(response_data, configuration, content_disposition=None): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + Args: + param response_data (str): the file data to write + configuration (Configuration): the instance to use to convert files + + Keyword Args: + content_disposition (str): the value of the Content-Disposition + header + + Returns: + (file_type): the deserialized file which is open + The user is responsible for closing and reading the file + """ + fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition, + flags=re.I) + if filename is not None: + filename = filename.group(1) + else: + filename = "default_" + str(uuid.uuid4()) + + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + if isinstance(response_data, str): + # change str to bytes so we can write it + response_data = response_data.encode('utf-8') + f.write(response_data) + + f = open(path, "rb") + return f + + +def attempt_convert_item(input_value, valid_classes, path_to_item, + configuration, spec_property_naming, key_type=False, + must_convert=False, check_type=True): + """ + Args: + input_value (any): the data to convert + valid_classes (any): the classes that are valid + path_to_item (list): the path to the item to convert + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + key_type (bool): if True we need to convert a key type (not supported) + must_convert (bool): if True we must convert + check_type (bool): if True we check the type or the returned data in + ModelComposed/ModelNormal/ModelSimple instances + + Returns: + instance (any) the fixed item + + Raises: + ApiTypeError + ApiValueError + ApiKeyError + """ + valid_classes_ordered = order_response_types(valid_classes) + valid_classes_coercible = remove_uncoercible( + valid_classes_ordered, input_value, spec_property_naming) + if not valid_classes_coercible or key_type: + # we do not handle keytype errors, json will take care + # of this for us + if configuration is None or not configuration.discard_unknown_keys: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=key_type) + for valid_class in valid_classes_coercible: + try: + if issubclass(valid_class, OpenApiModel): + return deserialize_model(input_value, valid_class, + path_to_item, check_type, + configuration, spec_property_naming) + elif valid_class == file_type: + return deserialize_file(input_value, configuration) + return deserialize_primitive(input_value, valid_class, + path_to_item) + except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: + if must_convert: + raise conversion_exc + # if we have conversion errors when must_convert == False + # we ignore the exception and move on to the next class + continue + # we were unable to convert, must_convert == False + return input_value + + +def is_type_nullable(input_type): + """ + Returns true if None is an allowed value for the specified input_type. + + A type is nullable if at least one of the following conditions is true: + 1. The OAS 'nullable' attribute has been specified, + 1. The type is the 'null' type, + 1. The type is a anyOf/oneOf composed schema, and a child schema is + the 'null' type. + Args: + input_type (type): the class of the input_value that we are + checking + Returns: + bool + """ + if input_type is none_type: + return True + if issubclass(input_type, OpenApiModel) and input_type._nullable: + return True + if issubclass(input_type, ModelComposed): + # If oneOf/anyOf, check if the 'null' type is one of the allowed types. + for t in input_type._composed_schemas.get('oneOf', ()): + if is_type_nullable(t): + return True + for t in input_type._composed_schemas.get('anyOf', ()): + if is_type_nullable(t): + return True + return False + + +def is_valid_type(input_class_simple, valid_classes): + """ + Args: + input_class_simple (class): the class of the input_value that we are + checking + valid_classes (tuple): the valid classes that the current item + should be + Returns: + bool + """ + if issubclass(input_class_simple, OpenApiModel) and \ + valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,): + return True + valid_type = input_class_simple in valid_classes + if not valid_type and ( + issubclass(input_class_simple, OpenApiModel) or + input_class_simple is none_type): + for valid_class in valid_classes: + if input_class_simple is none_type and is_type_nullable(valid_class): + # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. + return True + if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): + continue + discr_propertyname_py = list(valid_class.discriminator.keys())[0] + discriminator_classes = ( + valid_class.discriminator[discr_propertyname_py].values() + ) + valid_type = is_valid_type(input_class_simple, discriminator_classes) + if valid_type: + return True + return valid_type + + +def validate_and_convert_types(input_value, required_types_mixed, path_to_item, + spec_property_naming, _check_type, configuration=None): + """Raises a TypeError is there is a problem, otherwise returns value + + Args: + input_value (any): the data to validate/convert + required_types_mixed (list/dict/tuple): A list of + valid classes, or a list tuples of valid classes, or a dict where + the value is a tuple of value classes + path_to_item: (list) the path to the data being validated + this stores a list of keys or indices to get to the data being + validated + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + _check_type: (boolean) if true, type will be checked and conversion + will be attempted. + configuration: (Configuration): the configuration class to use + when converting file_type items. + If passed, conversion will be attempted when possible + If not passed, no conversions will be attempted and + exceptions will be raised + + Returns: + the correctly typed value + + Raises: + ApiTypeError + """ + results = get_required_type_classes(required_types_mixed, spec_property_naming) + valid_classes, child_req_types_by_current_type = results + + input_class_simple = get_simple_class(input_value) + valid_type = is_valid_type(input_class_simple, valid_classes) + if not valid_type: + if (configuration + or (input_class_simple == dict + and dict not in valid_classes)): + # if input_value is not valid_type try to convert it + converted_instance = attempt_convert_item( + input_value, + valid_classes, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=True, + check_type=_check_type + ) + return converted_instance + else: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=False) + + # input_value's type is in valid_classes + if len(valid_classes) > 1 and configuration: + # there are valid classes which are not the current class + valid_classes_coercible = remove_uncoercible( + valid_classes, input_value, spec_property_naming, must_convert=False) + if valid_classes_coercible: + converted_instance = attempt_convert_item( + input_value, + valid_classes_coercible, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=False, + check_type=_check_type + ) + return converted_instance + + if child_req_types_by_current_type == {}: + # all types are of the required types and there are no more inner + # variables left to look at + return input_value + inner_required_types = child_req_types_by_current_type.get( + type(input_value) + ) + if inner_required_types is None: + # for this type, there are not more inner variables left to look at + return input_value + if isinstance(input_value, list): + if input_value == []: + # allow an empty list + return input_value + for index, inner_value in enumerate(input_value): + inner_path = list(path_to_item) + inner_path.append(index) + input_value[index] = validate_and_convert_types( + inner_value, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + elif isinstance(input_value, dict): + if input_value == {}: + # allow an empty dict + return input_value + for inner_key, inner_val in input_value.items(): + inner_path = list(path_to_item) + inner_path.append(inner_key) + if get_simple_class(inner_key) != str: + raise get_type_error(inner_key, inner_path, valid_classes, + key_type=True) + input_value[inner_key] = validate_and_convert_types( + inner_val, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + return input_value + + +def model_to_dict(model_instance, serialize=True): + """Returns the model properties as a dict + + Args: + model_instance (one of your model instances): the model instance that + will be converted to a dict. + + Keyword Args: + serialize (bool): if True, the keys in the dict will be values from + attribute_map + """ + result = {} + + def extract_item(item): return ( + item[0], model_to_dict( + item[1], serialize=serialize)) if hasattr( + item[1], '_data_store') else item + + model_instances = [model_instance] + if model_instance._composed_schemas: + model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} + for model_instance in model_instances: + for attr, value in model_instance._data_store.items(): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) + if isinstance(value, list): + if not value: + # empty list or None + result[attr] = value + else: + res = [] + for v in value: + if isinstance(v, PRIMITIVE_TYPES) or v is None: + res.append(v) + elif isinstance(v, ModelSimple): + res.append(v.value) + elif isinstance(v, dict): + res.append(dict(map( + extract_item, + v.items() + ))) + else: + res.append(model_to_dict(v, serialize=serialize)) + result[attr] = res + elif isinstance(value, dict): + result[attr] = dict(map( + extract_item, + value.items() + )) + elif isinstance(value, ModelSimple): + result[attr] = value.value + elif hasattr(value, '_data_store'): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] + + return result + + +def type_error_message(var_value=None, var_name=None, valid_classes=None, + key_type=None): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + """ + key_or_value = 'value' + if key_type: + key_or_value = 'key' + valid_classes_phrase = get_valid_classes_phrase(valid_classes) + msg = ( + "Invalid type for variable '{0}'. Required {1} type {2} and " + "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + ) + return msg + + +def get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed + """ + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return 'is {0}'.format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas['allOf']: + + try: + if constant_args.get('_spec_property_naming'): + allof_instance = allof_class._from_openapi_data(**model_args, **constant_args) + else: + allof_instance = allof_class(**model_args, **constant_args) + composed_instances.append(allof_instance) + except Exception as ex: + raise ApiValueError( + "Invalid inputs given to generate an instance of '%s'. The " + "input data was invalid for the allOf schema '%s' in the composed " + "schema '%s'. Error=%s" % ( + allof_class.__name__, + allof_class.__name__, + self.__class__.__name__, + str(ex) + ) + ) from ex + return composed_instances + + +def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): + """ + Find the oneOf schema that matches the input data (e.g. payload). + If exactly one schema matches the input data, an instance of that schema + is returned. + If zero or more than one schema match the input data, an exception is raised. + In OAS 3.x, the payload MUST, by validation, match exactly one of the + schemas described by oneOf. + + Args: + cls: the class we are handling + model_kwargs (dict): var_name to var_value + The input data, e.g. the payload that must match a oneOf schema + in the OpenAPI document. + constant_kwargs (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Kwargs: + model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): + the value to assign to a primitive class or ModelSimple class + Notes: + - this is only passed in when oneOf includes types which are not object + - None is used to suppress handling of model_arg, nullable models are handled in __new__ + + Returns + oneof_instance (instance) + """ + if len(cls._composed_schemas['oneOf']) == 0: + return None + + oneof_instances = [] + # Iterate over each oneOf schema and determine if the input data + # matches the oneOf schemas. + for oneof_class in cls._composed_schemas['oneOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if oneof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + single_value_input = allows_single_value_input(oneof_class) + + try: + if not single_value_input: + if constant_kwargs.get('_spec_property_naming'): + oneof_instance = oneof_class._from_openapi_data( + **model_kwargs, **constant_kwargs) + else: + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) + else: + if issubclass(oneof_class, ModelSimple): + if constant_kwargs.get('_spec_property_naming'): + oneof_instance = oneof_class._from_openapi_data( + model_arg, **constant_kwargs) + else: + oneof_instance = oneof_class(model_arg, **constant_kwargs) + elif oneof_class in PRIMITIVE_TYPES: + oneof_instance = validate_and_convert_types( + model_arg, + (oneof_class,), + constant_kwargs['_path_to_item'], + constant_kwargs['_spec_property_naming'], + constant_kwargs['_check_type'], + configuration=constant_kwargs['_configuration'] + ) + oneof_instances.append(oneof_instance) + except Exception: + pass + if len(oneof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None " + "of the oneOf schemas matched the input data." % + cls.__name__ + ) + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf schemas matched the inputs, but a max of one is allowed." % + cls.__name__ + ) + return oneof_instances[0] + + +def get_anyof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + The input data, e.g. the payload that must match at least one + anyOf child schema in the OpenAPI document. + constant_args (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Returns + anyof_instances (list) + """ + anyof_instances = [] + if len(self._composed_schemas['anyOf']) == 0: + return anyof_instances + + for anyof_class in self._composed_schemas['anyOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if anyof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + try: + if constant_args.get('_spec_property_naming'): + anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args) + else: + anyof_instance = anyof_class(**model_args, **constant_args) + anyof_instances.append(anyof_instance) + except Exception: + pass + if len(anyof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None of the " + "anyOf schemas matched the inputs." % + self.__class__.__name__ + ) + return anyof_instances + + +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names + # before __init__ was called + for instance in composed_instances: + if instance.__class__ in self._composed_schemas['allOf']: + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + else: + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args + + +def validate_get_composed_info(constant_args, model_args, self): + """ + For composed schemas, generate schema instances for + all schemas in the oneOf/anyOf/allOf definition. If additional + properties are allowed, also assign those properties on + all matched schemas that contain additionalProperties. + Openapi schemas are python classes. + + Exceptions are raised if: + - 0 or > 1 oneOf schema matches the model_args input data + - no anyOf schema matches the model_args input data + - any of the allOf schemas do not match the model_args input data + + Args: + constant_args (dict): these are the args that every model requires + model_args (dict): these are the required and optional spec args that + were passed in to make this model + self (class): the class that we are instantiating + This class contains self._composed_schemas + + Returns: + composed_info (list): length three + composed_instances (list): the composed instances which are not + self + var_name_to_model_instances (dict): a dict going from var_name + to the model_instance which holds that var_name + the model_instance may be self or an instance of one of the + classes in self.composed_instances() + additional_properties_model_instances (list): a list of the + model instances which have the property + additional_properties_type. This list can include self + """ + # create composed_instances + composed_instances = [] + allof_instances = get_allof_instances(self, model_args, constant_args) + composed_instances.extend(allof_instances) + oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) + if oneof_instance is not None: + composed_instances.append(oneof_instance) + anyof_instances = get_anyof_instances(self, model_args, constant_args) + composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] + + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) + + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + list( + filter( + lambda x: prop_name in x.openapi_types, composed_instances)) + + return [ + composed_instances, + var_name_to_model_instances, + additional_properties_model_instances, + discarded_args + ] diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/models/__init__.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/models/__init__.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/models/__init__.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/models/__init__.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/rest.py b/samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/rest.py similarity index 100% rename from samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/rest.py rename to samples/openapi3/client/extensions/x-auth-id-alias/python-prior/x_auth_id_alias/rest.py diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/README.md b/samples/openapi3/client/extensions/x-auth-id-alias/python/README.md deleted file mode 100644 index cf8ca84034..0000000000 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/README.md +++ /dev/null @@ -1,146 +0,0 @@ -# x-auth-id-alias -This specification shows how to use x-auth-id-alias extension for API keys. - -This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: 1.0.0 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.PythonClientCodegen - -## Requirements. - -Python >=3.6 - -## Installation & Usage -### pip install - -If the python package is hosted on a repository, you can install directly using: - -```sh -pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git -``` -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) - -Then import the package: -```python -import x_auth_id_alias -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: -```python -import x_auth_id_alias -``` - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```python - -import time -import x_auth_id_alias -from pprint import pprint -from x_auth_id_alias.api import usage_api -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = x_auth_id_alias.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure API key authorization: api_key -configuration.api_key['api_key'] = 'YOUR_API_KEY' - -# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -# configuration.api_key_prefix['api_key'] = 'Bearer' - -# Configure API key authorization: api_key_query -configuration.api_key['api_key_query'] = 'YOUR_API_KEY' - -# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -# configuration.api_key_prefix['api_key_query'] = 'Bearer' - - -# Enter a context with an instance of the API client -with x_auth_id_alias.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = usage_api.UsageApi(api_client) - - try: - # Use any API key - api_response = api_instance.any_key() - pprint(api_response) - except x_auth_id_alias.ApiException as e: - print("Exception when calling UsageApi->any_key: %s\n" % e) -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*UsageApi* | [**any_key**](docs/UsageApi.md#any_key) | **GET** /any | Use any API key -*UsageApi* | [**both_keys**](docs/UsageApi.md#both_keys) | **GET** /both | Use both API keys -*UsageApi* | [**key_in_header**](docs/UsageApi.md#key_in_header) | **GET** /header | Use API key in header -*UsageApi* | [**key_in_query**](docs/UsageApi.md#key_in_query) | **GET** /query | Use API key in query - - -## Documentation For Models - - - -## Documentation For Authorization - - -## api_key - -- **Type**: API key -- **API key parameter name**: X-Api-Key -- **Location**: HTTP header - - -## api_key_query - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: URL query string - - -## Author - - - - -## Notes for Large OpenAPI documents -If the OpenAPI document is large, imports in x_auth_id_alias.apis and x_auth_id_alias.models may fail with a -RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: - -Solution 1: -Use specific imports for apis and models like: -- `from x_auth_id_alias.api.default_api import DefaultApi` -- `from x_auth_id_alias.model.pet import Pet` - -Solution 2: -Before importing the package, adjust the maximum recursion limit as shown below: -``` -import sys -sys.setrecursionlimit(1500) -import x_auth_id_alias -from x_auth_id_alias.apis import * -from x_auth_id_alias.models import * -``` - diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py deleted file mode 100644 index a2711d1362..0000000000 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py +++ /dev/null @@ -1,2058 +0,0 @@ -""" - OpenAPI Extension x-auth-id-alias - - This specification shows how to use x-auth-id-alias extension for API keys. # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from datetime import date, datetime # noqa: F401 -from copy import deepcopy -import inspect -import io -import os -import pprint -import re -import tempfile -import uuid - -from dateutil.parser import parse - -from x_auth_id_alias.exceptions import ( - ApiKeyError, - ApiAttributeError, - ApiTypeError, - ApiValueError, -) - -none_type = type(None) -file_type = io.IOBase - - -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python( - kwargs, _self if isinstance( - _self, type) else _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - -class cached_property(object): - # this caches the result of the function call for fn with no inputs - # use this as a decorator on function methods that you want converted - # into cached properties - result_key = '_results' - - def __init__(self, fn): - self._fn = fn - - def __get__(self, instance, cls=None): - if self.result_key in vars(self): - return vars(self)[self.result_key] - else: - result = self._fn() - setattr(self, self.result_key, result) - return result - - -PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) - - -def allows_single_value_input(cls): - """ - This function returns True if the input composed schema model or any - descendant model allows a value only input - This is true for cases where oneOf contains items like: - oneOf: - - float - - NumberWithValidation - - StringEnum - - ArrayModel - - null - TODO: lru_cache this - """ - if ( - issubclass(cls, ModelSimple) or - cls in PRIMITIVE_TYPES - ): - return True - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas['oneOf']: - return False - return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) - return False - - -def composed_model_input_classes(cls): - """ - This function returns a list of the possible models that can be accepted as - inputs. - TODO: lru_cache this - """ - if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: - return [cls] - elif issubclass(cls, ModelNormal): - if cls.discriminator is None: - return [cls] - else: - return get_discriminated_classes(cls) - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas['oneOf']: - return [] - if cls.discriminator is None: - input_classes = [] - for c in cls._composed_schemas['oneOf']: - input_classes.extend(composed_model_input_classes(c)) - return input_classes - else: - return get_discriminated_classes(cls) - return [] - - -class OpenApiModel(object): - """The base class for all OpenAPIModels""" - - def set_attribute(self, name, value): - # this is only used to set properties on self - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._spec_property_naming, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value, - self._configuration - ) - self.__dict__['_data_store'][name] = value - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other - - def __setattr__(self, attr, value): - """set the value of an attribute using dot notation: `instance.attr = val`""" - self[attr] = value - - def __getattr__(self, attr): - """get the value of an attribute using dot notation: `instance.attr`""" - return self.__getitem__(attr) - - def __copy__(self): - cls = self.__class__ - if self.get("_spec_property_naming", False): - return cls._new_from_openapi_data(**self.__dict__) - else: - return cls.__new__(cls, **self.__dict__) - - def __deepcopy__(self, memo): - cls = self.__class__ - - if self.get("_spec_property_naming", False): - new_inst = cls._new_from_openapi_data() - else: - new_inst = cls.__new__(cls) - - for k, v in self.__dict__.items(): - setattr(new_inst, k, deepcopy(v, memo)) - return new_inst - - - def __new__(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get('_visited_composed_classes', ()) - if ( - cls.discriminator is None or - cls in visited_composed_classes - ): - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: If Animal has a discriminator - # petType and we pass in "Dog", and the class Dog - # allOf includes Animal, we move through Animal - # once using the discriminator, and pick Dog. - # Then in the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return super(OpenApiModel, cls).__new__(cls) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % - (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class( - cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get('_path_to_item', ()) - disc_prop_value = kwargs.get( - discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % - (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return super(OpenApiModel, cls).__new__(cls) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = ( - cls._composed_schemas.get('oneOf', ()) + - cls._composed_schemas.get('anyOf', ())) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get('allOf') and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = super(OpenApiModel, cls).__new__(cls) - self_inst.__init__(*args, **kwargs) - - if kwargs.get("_spec_property_naming", False): - # when true, implies new is from deserialization - new_inst = new_cls._new_from_openapi_data(*args, **kwargs) - else: - new_inst = new_cls.__new__(new_cls, *args, **kwargs) - new_inst.__init__(*args, **kwargs) - - return new_inst - - @classmethod - @convert_js_args_to_python_args - def _new_from_openapi_data(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get('_visited_composed_classes', ()) - if ( - cls.discriminator is None or - cls in visited_composed_classes - ): - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: If Animal has a discriminator - # petType and we pass in "Dog", and the class Dog - # allOf includes Animal, we move through Animal - # once using the discriminator, and pick Dog. - # Then in the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return cls._from_openapi_data(*args, **kwargs) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % - (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class( - cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get('_path_to_item', ()) - disc_prop_value = kwargs.get( - discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % - (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return cls._from_openapi_data(*args, **kwargs) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = ( - cls._composed_schemas.get('oneOf', ()) + - cls._composed_schemas.get('anyOf', ())) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get('allOf') and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = cls._from_openapi_data(*args, **kwargs) - - new_inst = new_cls._new_from_openapi_data(*args, **kwargs) - return new_inst - - -class ModelSimple(OpenApiModel): - """the parent class of models whose type != object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__['_data_store'].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__['_data_store'] - - def to_str(self): - """Returns the string representation of the model""" - return str(self.value) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - this_val = self._data_store['value'] - that_val = other._data_store['value'] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - return vals_equal - - -class ModelNormal(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__['_data_store'].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__['_data_store'] - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -class ModelComposed(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi and have oneOf/allOf/anyOf - - When one sets a property we use var_name_to_model_instances to store the value in - the correct class instances + run any type checking + validation code. - When one gets a property we use var_name_to_model_instances to get the value - from the correct class instances. - This allows multiple composed schemas to contain the same property with additive - constraints on the value. - - _composed_schemas (dict) stores the anyOf/allOf/oneOf classes - key (str): allOf/oneOf/anyOf - value (list): the classes in the XOf definition. - Note: none_type can be included when the openapi document version >= 3.1.0 - _composed_instances (list): stores a list of instances of the composed schemas - defined in _composed_schemas. When properties are accessed in the self instance, - they are returned from the self._data_store or the data stores in the instances - in self._composed_schemas - _var_name_to_model_instances (dict): maps between a variable name on self and - the composed instances (self included) which contain that data - key (str): property name - value (list): list of class instances, self or instances in _composed_instances - which contain the value that the key is referring to. - """ - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - """ - Use cases: - 1. additional_properties_type is None (additionalProperties == False in spec) - Check for property presence in self.openapi_types - if not present then throw an error - if present set in self, set attribute - always set on composed schemas - 2. additional_properties_type exists - set attribute on self - always set on composed schemas - """ - if self.additional_properties_type is None: - """ - For an attribute to exist on a composed schema it must: - - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND - - fulfill schema_requirements in each oneOf/anyOf/allOf schemas - - schema_requirements: - For an attribute to exist on a schema it must: - - be present in properties at the schema OR - - have additionalProperties unset (defaults additionalProperties = any type) OR - - have additionalProperties set - """ - if name not in self.openapi_types: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - # attribute must be set on self and composed instances - self.set_attribute(name, value) - for model_instance in self._composed_instances: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] - return None - - __unset_attribute_value__ = object() - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get(name) - values = [] - # A composed model stores self and child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. - # Any property must exist in self and all model instances - # The value stored in all model instances must be the same - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - v = model_instance._data_store[name] - if v not in values: - values.append(v) - len_values = len(values) - if len_values == 0: - return default - elif len_values == 1: - return values[0] - elif len_values > 1: - raise ApiValueError( - "Values stored for property {0} in {1} differ when looking " - "at self and self's composed instances. All values must be " - "the same".format(name, type(self).__name__), - [e for e in [self._path_to_item, name] if e] - ) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - value = self.get(name, self.__unset_attribute_value__) - if value is self.__unset_attribute_value__: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - return value - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - - if name in self.required_properties: - return name in self.__dict__ - - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) - - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - return True - - return False - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -COERCION_INDEX_BY_TYPE = { - ModelComposed: 0, - ModelNormal: 1, - ModelSimple: 2, - none_type: 3, # The type of 'None'. - list: 4, - dict: 5, - float: 6, - int: 7, - bool: 8, - datetime: 9, - date: 10, - str: 11, - file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. -} - -# these are used to limit what type conversions we try to do -# when we have a valid type already and we want to try converting -# to another type -UPCONVERSION_TYPE_PAIRS = ( - (str, datetime), - (str, date), - # A float may be serialized as an integer, e.g. '3' is a valid serialized float. - (int, float), - (list, ModelComposed), - (dict, ModelComposed), - (str, ModelComposed), - (int, ModelComposed), - (float, ModelComposed), - (list, ModelComposed), - (list, ModelNormal), - (dict, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), -) - -COERCIBLE_TYPE_PAIRS = { - False: ( # client instantiation of a model with client data - # (dict, ModelComposed), - # (list, ModelComposed), - # (dict, ModelNormal), - # (list, ModelNormal), - # (str, ModelSimple), - # (int, ModelSimple), - # (float, ModelSimple), - # (list, ModelSimple), - # (str, int), - # (str, float), - # (str, datetime), - # (str, date), - # (int, str), - # (float, str), - ), - True: ( # server -> client data - (dict, ModelComposed), - (list, ModelComposed), - (dict, ModelNormal), - (list, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), - # (str, int), - # (str, float), - (str, datetime), - (str, date), - # (int, str), - # (float, str), - (str, file_type) - ), -} - - -def get_simple_class(input_value): - """Returns an input_value's simple class that we will use for type checking - Python2: - float and int will return int, where int is the python3 int backport - str and unicode will return str, where str is the python3 str backport - Note: float and int ARE both instances of int backport - Note: str_py2 and unicode_py2 are NOT both instances of str backport - - Args: - input_value (class/class_instance): the item for which we will return - the simple class - """ - if isinstance(input_value, type): - # input_value is a class - return input_value - elif isinstance(input_value, tuple): - return tuple - elif isinstance(input_value, list): - return list - elif isinstance(input_value, dict): - return dict - elif isinstance(input_value, none_type): - return none_type - elif isinstance(input_value, file_type): - return file_type - elif isinstance(input_value, bool): - # this must be higher than the int check because - # isinstance(True, int) == True - return bool - elif isinstance(input_value, int): - return int - elif isinstance(input_value, datetime): - # this must be higher than the date check because - # isinstance(datetime_instance, date) == True - return datetime - elif isinstance(input_value, date): - return date - elif isinstance(input_value, str): - return str - return type(input_value) - - -def check_allowed_values(allowed_values, input_variable_path, input_values): - """Raises an exception if the input_values are not allowed - - Args: - allowed_values (dict): the allowed_values dict - input_variable_path (tuple): the path to the input variable - input_values (list/str/int/float/date/datetime): the values that we - are checking to see if they are in allowed_values - """ - these_allowed_values = list(allowed_values[input_variable_path].values()) - if (isinstance(input_values, list) - and not set(input_values).issubset( - set(these_allowed_values))): - invalid_values = ", ".join( - map(str, set(input_values) - set(these_allowed_values))), - raise ApiValueError( - "Invalid values for `%s` [%s], must be a subset of [%s]" % - ( - input_variable_path[0], - invalid_values, - ", ".join(map(str, these_allowed_values)) - ) - ) - elif (isinstance(input_values, dict) - and not set( - input_values.keys()).issubset(set(these_allowed_values))): - invalid_values = ", ".join( - map(str, set(input_values.keys()) - set(these_allowed_values))) - raise ApiValueError( - "Invalid keys in `%s` [%s], must be a subset of [%s]" % - ( - input_variable_path[0], - invalid_values, - ", ".join(map(str, these_allowed_values)) - ) - ) - elif (not isinstance(input_values, (list, dict)) - and input_values not in these_allowed_values): - raise ApiValueError( - "Invalid value for `%s` (%s), must be one of %s" % - ( - input_variable_path[0], - input_values, - these_allowed_values - ) - ) - - -def is_json_validation_enabled(schema_keyword, configuration=None): - """Returns true if JSON schema validation is enabled for the specified - validation keyword. This can be used to skip JSON schema structural validation - as requested in the configuration. - - Args: - schema_keyword (string): the name of a JSON schema validation keyword. - configuration (Configuration): the configuration class. - """ - - return (configuration is None or - not hasattr(configuration, '_disabled_client_side_validations') or - schema_keyword not in configuration._disabled_client_side_validations) - - -def check_validations( - validations, input_variable_path, input_values, - configuration=None): - """Raises an exception if the input_values are invalid - - Args: - validations (dict): the validation dictionary. - input_variable_path (tuple): the path to the input variable. - input_values (list/str/int/float/date/datetime): the values that we - are checking. - configuration (Configuration): the configuration class. - """ - - if input_values is None: - return - - current_validations = validations[input_variable_path] - if (is_json_validation_enabled('multipleOf', configuration) and - 'multiple_of' in current_validations and - isinstance(input_values, (int, float)) and - not (float(input_values) / current_validations['multiple_of']).is_integer()): - # Note 'multipleOf' will be as good as the floating point arithmetic. - raise ApiValueError( - "Invalid value for `%s`, value must be a multiple of " - "`%s`" % ( - input_variable_path[0], - current_validations['multiple_of'] - ) - ) - - if (is_json_validation_enabled('maxLength', configuration) and - 'max_length' in current_validations and - len(input_values) > current_validations['max_length']): - raise ApiValueError( - "Invalid value for `%s`, length must be less than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['max_length'] - ) - ) - - if (is_json_validation_enabled('minLength', configuration) and - 'min_length' in current_validations and - len(input_values) < current_validations['min_length']): - raise ApiValueError( - "Invalid value for `%s`, length must be greater than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['min_length'] - ) - ) - - if (is_json_validation_enabled('maxItems', configuration) and - 'max_items' in current_validations and - len(input_values) > current_validations['max_items']): - raise ApiValueError( - "Invalid value for `%s`, number of items must be less than or " - "equal to `%s`" % ( - input_variable_path[0], - current_validations['max_items'] - ) - ) - - if (is_json_validation_enabled('minItems', configuration) and - 'min_items' in current_validations and - len(input_values) < current_validations['min_items']): - raise ValueError( - "Invalid value for `%s`, number of items must be greater than or " - "equal to `%s`" % ( - input_variable_path[0], - current_validations['min_items'] - ) - ) - - items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', - 'inclusive_minimum') - if (any(item in current_validations for item in items)): - if isinstance(input_values, list): - max_val = max(input_values) - min_val = min(input_values) - elif isinstance(input_values, dict): - max_val = max(input_values.values()) - min_val = min(input_values.values()) - else: - max_val = input_values - min_val = input_values - - if (is_json_validation_enabled('exclusiveMaximum', configuration) and - 'exclusive_maximum' in current_validations and - max_val >= current_validations['exclusive_maximum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than `%s`" % ( - input_variable_path[0], - current_validations['exclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('maximum', configuration) and - 'inclusive_maximum' in current_validations and - max_val > current_validations['inclusive_maximum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['inclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('exclusiveMinimum', configuration) and - 'exclusive_minimum' in current_validations and - min_val <= current_validations['exclusive_minimum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than `%s`" % - ( - input_variable_path[0], - current_validations['exclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('minimum', configuration) and - 'inclusive_minimum' in current_validations and - min_val < current_validations['inclusive_minimum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than or equal " - "to `%s`" % ( - input_variable_path[0], - current_validations['inclusive_minimum'] - ) - ) - flags = current_validations.get('regex', {}).get('flags', 0) - if (is_json_validation_enabled('pattern', configuration) and - 'regex' in current_validations and - not re.search(current_validations['regex']['pattern'], - input_values, flags=flags)): - err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( - input_variable_path[0], - current_validations['regex']['pattern'] - ) - if flags != 0: - # Don't print the regex flags if the flags are not - # specified in the OAS document. - err_msg = r"%s with flags=`%s`" % (err_msg, flags) - raise ApiValueError(err_msg) - - -def order_response_types(required_types): - """Returns the required types sorted in coercion order - - Args: - required_types (list/tuple): collection of classes or instance of - list or dict with class information inside it. - - Returns: - (list): coercion order sorted collection of classes or instance - of list or dict with class information inside it. - """ - - def index_getter(class_or_instance): - if isinstance(class_or_instance, list): - return COERCION_INDEX_BY_TYPE[list] - elif isinstance(class_or_instance, dict): - return COERCION_INDEX_BY_TYPE[dict] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelComposed)): - return COERCION_INDEX_BY_TYPE[ModelComposed] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelNormal)): - return COERCION_INDEX_BY_TYPE[ModelNormal] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelSimple)): - return COERCION_INDEX_BY_TYPE[ModelSimple] - elif class_or_instance in COERCION_INDEX_BY_TYPE: - return COERCION_INDEX_BY_TYPE[class_or_instance] - raise ApiValueError("Unsupported type: %s" % class_or_instance) - - sorted_types = sorted( - required_types, - key=lambda class_or_instance: index_getter(class_or_instance) - ) - return sorted_types - - -def remove_uncoercible(required_types_classes, current_item, spec_property_naming, - must_convert=True): - """Only keeps the type conversions that are possible - - Args: - required_types_classes (tuple): tuple of classes that are required - these should be ordered by COERCION_INDEX_BY_TYPE - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - current_item (any): the current item (input data) to be converted - - Keyword Args: - must_convert (bool): if True the item to convert is of the wrong - type and we want a big list of coercibles - if False, we want a limited list of coercibles - - Returns: - (list): the remaining coercible required types, classes only - """ - current_type_simple = get_simple_class(current_item) - - results_classes = [] - for required_type_class in required_types_classes: - # convert our models to OpenApiModel - required_type_class_simplified = required_type_class - if isinstance(required_type_class_simplified, type): - if issubclass(required_type_class_simplified, ModelComposed): - required_type_class_simplified = ModelComposed - elif issubclass(required_type_class_simplified, ModelNormal): - required_type_class_simplified = ModelNormal - elif issubclass(required_type_class_simplified, ModelSimple): - required_type_class_simplified = ModelSimple - - if required_type_class_simplified == current_type_simple: - # don't consider converting to one's own class - continue - - class_pair = (current_type_simple, required_type_class_simplified) - if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: - results_classes.append(required_type_class) - elif class_pair in UPCONVERSION_TYPE_PAIRS: - results_classes.append(required_type_class) - return results_classes - - -def get_discriminated_classes(cls): - """ - Returns all the classes that a discriminator converts to - TODO: lru_cache this - """ - possible_classes = [] - key = list(cls.discriminator.keys())[0] - if is_type_nullable(cls): - possible_classes.append(cls) - for discr_cls in cls.discriminator[key].values(): - if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: - possible_classes.extend(get_discriminated_classes(discr_cls)) - else: - possible_classes.append(discr_cls) - return possible_classes - - -def get_possible_classes(cls, from_server_context): - # TODO: lru_cache this - possible_classes = [cls] - if from_server_context: - return possible_classes - if hasattr(cls, 'discriminator') and cls.discriminator is not None: - possible_classes = [] - possible_classes.extend(get_discriminated_classes(cls)) - elif issubclass(cls, ModelComposed): - possible_classes.extend(composed_model_input_classes(cls)) - return possible_classes - - -def get_required_type_classes(required_types_mixed, spec_property_naming): - """Converts the tuple required_types into a tuple and a dict described - below - - Args: - required_types_mixed (tuple/list): will contain either classes or - instance of list or dict - spec_property_naming (bool): if True these values came from the - server, and we use the data types in our endpoints. - If False, we are client side and we need to include - oneOf and discriminator classes inside the data types in our endpoints - - Returns: - (valid_classes, dict_valid_class_to_child_types_mixed): - valid_classes (tuple): the valid classes that the current item - should be - dict_valid_class_to_child_types_mixed (dict): - valid_class (class): this is the key - child_types_mixed (list/dict/tuple): describes the valid child - types - """ - valid_classes = [] - child_req_types_by_current_type = {} - for required_type in required_types_mixed: - if isinstance(required_type, list): - valid_classes.append(list) - child_req_types_by_current_type[list] = required_type - elif isinstance(required_type, tuple): - valid_classes.append(tuple) - child_req_types_by_current_type[tuple] = required_type - elif isinstance(required_type, dict): - valid_classes.append(dict) - child_req_types_by_current_type[dict] = required_type[str] - else: - valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) - return tuple(valid_classes), child_req_types_by_current_type - - -def change_keys_js_to_python(input_dict, model_class): - """ - Converts from javascript_key keys in the input_dict to python_keys in - the output dict using the mapping in model_class. - If the input_dict contains a key which does not declared in the model_class, - the key is added to the output dict as is. The assumption is the model_class - may have undeclared properties (additionalProperties attribute in the OAS - document). - """ - - if getattr(model_class, 'attribute_map', None) is None: - return input_dict - output_dict = {} - reversed_attr_map = {value: key for key, value in - model_class.attribute_map.items()} - for javascript_key, value in input_dict.items(): - python_key = reversed_attr_map.get(javascript_key) - if python_key is None: - # if the key is unknown, it is in error or it is an - # additionalProperties variable - python_key = javascript_key - output_dict[python_key] = value - return output_dict - - -def get_type_error(var_value, path_to_item, valid_classes, key_type=False): - error_msg = type_error_message( - var_name=path_to_item[-1], - var_value=var_value, - valid_classes=valid_classes, - key_type=key_type - ) - return ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=valid_classes, - key_type=key_type - ) - - -def deserialize_primitive(data, klass, path_to_item): - """Deserializes string to primitive type. - - :param data: str/int/float - :param klass: str/class the class to convert to - - :return: int, float, str, bool, date, datetime - """ - additional_message = "" - try: - if klass in {datetime, date}: - additional_message = ( - "If you need your parameter to have a fallback " - "string value, please set its type as `type: {}` in your " - "spec. That allows the value to be any type. " - ) - if klass == datetime: - if len(data) < 8: - raise ValueError("This is not a datetime") - # The string should be in iso8601 datetime format. - parsed_datetime = parse(data) - date_only = ( - parsed_datetime.hour == 0 and - parsed_datetime.minute == 0 and - parsed_datetime.second == 0 and - parsed_datetime.tzinfo is None and - 8 <= len(data) <= 10 - ) - if date_only: - raise ValueError("This is a date, not a datetime") - return parsed_datetime - elif klass == date: - if len(data) < 8: - raise ValueError("This is not a date") - return parse(data).date() - else: - converted_value = klass(data) - if isinstance(data, str) and klass == float: - if str(converted_value) != data: - # '7' -> 7.0 -> '7.0' != '7' - raise ValueError('This is not a float') - return converted_value - except (OverflowError, ValueError) as ex: - # parse can raise OverflowError - raise ApiValueError( - "{0}Failed to parse {1} as {2}".format( - additional_message, repr(data), klass.__name__ - ), - path_to_item=path_to_item - ) from ex - - -def get_discriminator_class(model_class, - discr_name, - discr_value, cls_visited): - """Returns the child class specified by the discriminator. - - Args: - model_class (OpenApiModel): the model class. - discr_name (string): the name of the discriminator property. - discr_value (any): the discriminator value. - cls_visited (list): list of model classes that have been visited. - Used to determine the discriminator class without - visiting circular references indefinitely. - - Returns: - used_model_class (class/None): the chosen child class that will be used - to deserialize the data, for example dog.Dog. - If a class is not found, None is returned. - """ - - if model_class in cls_visited: - # The class has already been visited and no suitable class was found. - return None - cls_visited.append(model_class) - used_model_class = None - if discr_name in model_class.discriminator: - class_name_to_discr_class = model_class.discriminator[discr_name] - used_model_class = class_name_to_discr_class.get(discr_value) - if used_model_class is None: - # We didn't find a discriminated class in class_name_to_discr_class. - # So look in the ancestor or descendant discriminators - # The discriminator mapping may exist in a descendant (anyOf, oneOf) - # or ancestor (allOf). - # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat - # hierarchy, the discriminator mappings may be defined at any level - # in the hierarchy. - # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig - # if we try to make BasquePig from mammal, we need to travel through - # the oneOf descendant discriminators to find BasquePig - descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ - model_class._composed_schemas.get('anyOf', ()) - ancestor_classes = model_class._composed_schemas.get('allOf', ()) - possible_classes = descendant_classes + ancestor_classes - for cls in possible_classes: - # Check if the schema has inherited discriminators. - if hasattr(cls, 'discriminator') and cls.discriminator is not None: - used_model_class = get_discriminator_class( - cls, discr_name, discr_value, cls_visited) - if used_model_class is not None: - return used_model_class - return used_model_class - - -def deserialize_model(model_data, model_class, path_to_item, check_type, - configuration, spec_property_naming): - """Deserializes model_data to model instance. - - Args: - model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model - model_class (OpenApiModel): the model class - path_to_item (list): path to the model in the received data - check_type (bool): whether to check the data tupe for the values in - the model - configuration (Configuration): the instance to use to convert files - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - - Returns: - model instance - - Raise: - ApiTypeError - ApiValueError - ApiKeyError - """ - - kw_args = dict(_check_type=check_type, - _path_to_item=path_to_item, - _configuration=configuration, - _spec_property_naming=spec_property_naming) - - if issubclass(model_class, ModelSimple): - return model_class._new_from_openapi_data(model_data, **kw_args) - elif isinstance(model_data, list): - return model_class._new_from_openapi_data(*model_data, **kw_args) - if isinstance(model_data, dict): - kw_args.update(model_data) - return model_class._new_from_openapi_data(**kw_args) - elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class._new_from_openapi_data(model_data, **kw_args) - - -def deserialize_file(response_data, configuration, content_disposition=None): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - Args: - param response_data (str): the file data to write - configuration (Configuration): the instance to use to convert files - - Keyword Args: - content_disposition (str): the value of the Content-Disposition - header - - Returns: - (file_type): the deserialized file which is open - The user is responsible for closing and reading the file - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition, - flags=re.I) - if filename is not None: - filename = filename.group(1) - else: - filename = "default_" + str(uuid.uuid4()) - - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - if isinstance(response_data, str): - # change str to bytes so we can write it - response_data = response_data.encode('utf-8') - f.write(response_data) - - f = open(path, "rb") - return f - - -def attempt_convert_item(input_value, valid_classes, path_to_item, - configuration, spec_property_naming, key_type=False, - must_convert=False, check_type=True): - """ - Args: - input_value (any): the data to convert - valid_classes (any): the classes that are valid - path_to_item (list): the path to the item to convert - configuration (Configuration): the instance to use to convert files - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - key_type (bool): if True we need to convert a key type (not supported) - must_convert (bool): if True we must convert - check_type (bool): if True we check the type or the returned data in - ModelComposed/ModelNormal/ModelSimple instances - - Returns: - instance (any) the fixed item - - Raises: - ApiTypeError - ApiValueError - ApiKeyError - """ - valid_classes_ordered = order_response_types(valid_classes) - valid_classes_coercible = remove_uncoercible( - valid_classes_ordered, input_value, spec_property_naming) - if not valid_classes_coercible or key_type: - # we do not handle keytype errors, json will take care - # of this for us - if configuration is None or not configuration.discard_unknown_keys: - raise get_type_error(input_value, path_to_item, valid_classes, - key_type=key_type) - for valid_class in valid_classes_coercible: - try: - if issubclass(valid_class, OpenApiModel): - return deserialize_model(input_value, valid_class, - path_to_item, check_type, - configuration, spec_property_naming) - elif valid_class == file_type: - return deserialize_file(input_value, configuration) - return deserialize_primitive(input_value, valid_class, - path_to_item) - except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: - if must_convert: - raise conversion_exc - # if we have conversion errors when must_convert == False - # we ignore the exception and move on to the next class - continue - # we were unable to convert, must_convert == False - return input_value - - -def is_type_nullable(input_type): - """ - Returns true if None is an allowed value for the specified input_type. - - A type is nullable if at least one of the following conditions is true: - 1. The OAS 'nullable' attribute has been specified, - 1. The type is the 'null' type, - 1. The type is a anyOf/oneOf composed schema, and a child schema is - the 'null' type. - Args: - input_type (type): the class of the input_value that we are - checking - Returns: - bool - """ - if input_type is none_type: - return True - if issubclass(input_type, OpenApiModel) and input_type._nullable: - return True - if issubclass(input_type, ModelComposed): - # If oneOf/anyOf, check if the 'null' type is one of the allowed types. - for t in input_type._composed_schemas.get('oneOf', ()): - if is_type_nullable(t): - return True - for t in input_type._composed_schemas.get('anyOf', ()): - if is_type_nullable(t): - return True - return False - - -def is_valid_type(input_class_simple, valid_classes): - """ - Args: - input_class_simple (class): the class of the input_value that we are - checking - valid_classes (tuple): the valid classes that the current item - should be - Returns: - bool - """ - if issubclass(input_class_simple, OpenApiModel) and \ - valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,): - return True - valid_type = input_class_simple in valid_classes - if not valid_type and ( - issubclass(input_class_simple, OpenApiModel) or - input_class_simple is none_type): - for valid_class in valid_classes: - if input_class_simple is none_type and is_type_nullable(valid_class): - # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. - return True - if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): - continue - discr_propertyname_py = list(valid_class.discriminator.keys())[0] - discriminator_classes = ( - valid_class.discriminator[discr_propertyname_py].values() - ) - valid_type = is_valid_type(input_class_simple, discriminator_classes) - if valid_type: - return True - return valid_type - - -def validate_and_convert_types(input_value, required_types_mixed, path_to_item, - spec_property_naming, _check_type, configuration=None): - """Raises a TypeError is there is a problem, otherwise returns value - - Args: - input_value (any): the data to validate/convert - required_types_mixed (list/dict/tuple): A list of - valid classes, or a list tuples of valid classes, or a dict where - the value is a tuple of value classes - path_to_item: (list) the path to the data being validated - this stores a list of keys or indices to get to the data being - validated - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - _check_type: (boolean) if true, type will be checked and conversion - will be attempted. - configuration: (Configuration): the configuration class to use - when converting file_type items. - If passed, conversion will be attempted when possible - If not passed, no conversions will be attempted and - exceptions will be raised - - Returns: - the correctly typed value - - Raises: - ApiTypeError - """ - results = get_required_type_classes(required_types_mixed, spec_property_naming) - valid_classes, child_req_types_by_current_type = results - - input_class_simple = get_simple_class(input_value) - valid_type = is_valid_type(input_class_simple, valid_classes) - if not valid_type: - if (configuration - or (input_class_simple == dict - and dict not in valid_classes)): - # if input_value is not valid_type try to convert it - converted_instance = attempt_convert_item( - input_value, - valid_classes, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=True, - check_type=_check_type - ) - return converted_instance - else: - raise get_type_error(input_value, path_to_item, valid_classes, - key_type=False) - - # input_value's type is in valid_classes - if len(valid_classes) > 1 and configuration: - # there are valid classes which are not the current class - valid_classes_coercible = remove_uncoercible( - valid_classes, input_value, spec_property_naming, must_convert=False) - if valid_classes_coercible: - converted_instance = attempt_convert_item( - input_value, - valid_classes_coercible, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=False, - check_type=_check_type - ) - return converted_instance - - if child_req_types_by_current_type == {}: - # all types are of the required types and there are no more inner - # variables left to look at - return input_value - inner_required_types = child_req_types_by_current_type.get( - type(input_value) - ) - if inner_required_types is None: - # for this type, there are not more inner variables left to look at - return input_value - if isinstance(input_value, list): - if input_value == []: - # allow an empty list - return input_value - for index, inner_value in enumerate(input_value): - inner_path = list(path_to_item) - inner_path.append(index) - input_value[index] = validate_and_convert_types( - inner_value, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration - ) - elif isinstance(input_value, dict): - if input_value == {}: - # allow an empty dict - return input_value - for inner_key, inner_val in input_value.items(): - inner_path = list(path_to_item) - inner_path.append(inner_key) - if get_simple_class(inner_key) != str: - raise get_type_error(inner_key, inner_path, valid_classes, - key_type=True) - input_value[inner_key] = validate_and_convert_types( - inner_val, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration - ) - return input_value - - -def model_to_dict(model_instance, serialize=True): - """Returns the model properties as a dict - - Args: - model_instance (one of your model instances): the model instance that - will be converted to a dict. - - Keyword Args: - serialize (bool): if True, the keys in the dict will be values from - attribute_map - """ - result = {} - - def extract_item(item): return ( - item[0], model_to_dict( - item[1], serialize=serialize)) if hasattr( - item[1], '_data_store') else item - - model_instances = [model_instance] - if model_instance._composed_schemas: - model_instances.extend(model_instance._composed_instances) - seen_json_attribute_names = set() - used_fallback_python_attribute_names = set() - py_to_json_map = {} - for model_instance in model_instances: - for attr, value in model_instance._data_store.items(): - if serialize: - # we use get here because additional property key names do not - # exist in attribute_map - try: - attr = model_instance.attribute_map[attr] - py_to_json_map.update(model_instance.attribute_map) - seen_json_attribute_names.add(attr) - except KeyError: - used_fallback_python_attribute_names.add(attr) - if isinstance(value, list): - if not value: - # empty list or None - result[attr] = value - else: - res = [] - for v in value: - if isinstance(v, PRIMITIVE_TYPES) or v is None: - res.append(v) - elif isinstance(v, ModelSimple): - res.append(v.value) - elif isinstance(v, dict): - res.append(dict(map( - extract_item, - v.items() - ))) - else: - res.append(model_to_dict(v, serialize=serialize)) - result[attr] = res - elif isinstance(value, dict): - result[attr] = dict(map( - extract_item, - value.items() - )) - elif isinstance(value, ModelSimple): - result[attr] = value.value - elif hasattr(value, '_data_store'): - result[attr] = model_to_dict(value, serialize=serialize) - else: - result[attr] = value - if serialize: - for python_key in used_fallback_python_attribute_names: - json_key = py_to_json_map.get(python_key) - if json_key is None: - continue - if python_key == json_key: - continue - json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names - if json_key_assigned_no_need_for_python_key: - del result[python_key] - - return result - - -def type_error_message(var_value=None, var_name=None, valid_classes=None, - key_type=None): - """ - Keyword Args: - var_value (any): the variable which has the type_error - var_name (str): the name of the variable which has the typ error - valid_classes (tuple): the accepted classes for current_item's - value - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - """ - key_or_value = 'value' - if key_type: - key_or_value = 'key' - valid_classes_phrase = get_valid_classes_phrase(valid_classes) - msg = ( - "Invalid type for variable '{0}'. Required {1} type {2} and " - "passed type was {3}".format( - var_name, - key_or_value, - valid_classes_phrase, - type(var_value).__name__, - ) - ) - return msg - - -def get_valid_classes_phrase(input_classes): - """Returns a string phrase describing what types are allowed - """ - all_classes = list(input_classes) - all_classes = sorted(all_classes, key=lambda cls: cls.__name__) - all_class_names = [cls.__name__ for cls in all_classes] - if len(all_class_names) == 1: - return 'is {0}'.format(all_class_names[0]) - return "is one of [{0}]".format(", ".join(all_class_names)) - - -def get_allof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - used to make instances - constant_args (dict): - metadata arguments: - _check_type - _path_to_item - _spec_property_naming - _configuration - _visited_composed_classes - - Returns - composed_instances (list) - """ - composed_instances = [] - for allof_class in self._composed_schemas['allOf']: - - try: - if constant_args.get('_spec_property_naming'): - allof_instance = allof_class._from_openapi_data(**model_args, **constant_args) - else: - allof_instance = allof_class(**model_args, **constant_args) - composed_instances.append(allof_instance) - except Exception as ex: - raise ApiValueError( - "Invalid inputs given to generate an instance of '%s'. The " - "input data was invalid for the allOf schema '%s' in the composed " - "schema '%s'. Error=%s" % ( - allof_class.__name__, - allof_class.__name__, - self.__class__.__name__, - str(ex) - ) - ) from ex - return composed_instances - - -def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): - """ - Find the oneOf schema that matches the input data (e.g. payload). - If exactly one schema matches the input data, an instance of that schema - is returned. - If zero or more than one schema match the input data, an exception is raised. - In OAS 3.x, the payload MUST, by validation, match exactly one of the - schemas described by oneOf. - - Args: - cls: the class we are handling - model_kwargs (dict): var_name to var_value - The input data, e.g. the payload that must match a oneOf schema - in the OpenAPI document. - constant_kwargs (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Kwargs: - model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): - the value to assign to a primitive class or ModelSimple class - Notes: - - this is only passed in when oneOf includes types which are not object - - None is used to suppress handling of model_arg, nullable models are handled in __new__ - - Returns - oneof_instance (instance) - """ - if len(cls._composed_schemas['oneOf']) == 0: - return None - - oneof_instances = [] - # Iterate over each oneOf schema and determine if the input data - # matches the oneOf schemas. - for oneof_class in cls._composed_schemas['oneOf']: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if oneof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - single_value_input = allows_single_value_input(oneof_class) - - try: - if not single_value_input: - if constant_kwargs.get('_spec_property_naming'): - oneof_instance = oneof_class._from_openapi_data( - **model_kwargs, **constant_kwargs) - else: - oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) - else: - if issubclass(oneof_class, ModelSimple): - if constant_kwargs.get('_spec_property_naming'): - oneof_instance = oneof_class._from_openapi_data( - model_arg, **constant_kwargs) - else: - oneof_instance = oneof_class(model_arg, **constant_kwargs) - elif oneof_class in PRIMITIVE_TYPES: - oneof_instance = validate_and_convert_types( - model_arg, - (oneof_class,), - constant_kwargs['_path_to_item'], - constant_kwargs['_spec_property_naming'], - constant_kwargs['_check_type'], - configuration=constant_kwargs['_configuration'] - ) - oneof_instances.append(oneof_instance) - except Exception: - pass - if len(oneof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None " - "of the oneOf schemas matched the input data." % - cls.__name__ - ) - elif len(oneof_instances) > 1: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. Multiple " - "oneOf schemas matched the inputs, but a max of one is allowed." % - cls.__name__ - ) - return oneof_instances[0] - - -def get_anyof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - The input data, e.g. the payload that must match at least one - anyOf child schema in the OpenAPI document. - constant_args (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Returns - anyof_instances (list) - """ - anyof_instances = [] - if len(self._composed_schemas['anyOf']) == 0: - return anyof_instances - - for anyof_class in self._composed_schemas['anyOf']: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if anyof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - try: - if constant_args.get('_spec_property_naming'): - anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args) - else: - anyof_instance = anyof_class(**model_args, **constant_args) - anyof_instances.append(anyof_instance) - except Exception: - pass - if len(anyof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None of the " - "anyOf schemas matched the inputs." % - self.__class__.__name__ - ) - return anyof_instances - - -def get_discarded_args(self, composed_instances, model_args): - """ - Gathers the args that were discarded by configuration.discard_unknown_keys - """ - model_arg_keys = model_args.keys() - discarded_args = set() - # arguments passed to self were already converted to python names - # before __init__ was called - for instance in composed_instances: - if instance.__class__ in self._composed_schemas['allOf']: - try: - keys = instance.to_dict().keys() - discarded_keys = model_args - keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - else: - try: - all_keys = set(model_to_dict(instance, serialize=False).keys()) - js_keys = model_to_dict(instance, serialize=True).keys() - all_keys.update(js_keys) - discarded_keys = model_arg_keys - all_keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - return discarded_args - - -def validate_get_composed_info(constant_args, model_args, self): - """ - For composed schemas, generate schema instances for - all schemas in the oneOf/anyOf/allOf definition. If additional - properties are allowed, also assign those properties on - all matched schemas that contain additionalProperties. - Openapi schemas are python classes. - - Exceptions are raised if: - - 0 or > 1 oneOf schema matches the model_args input data - - no anyOf schema matches the model_args input data - - any of the allOf schemas do not match the model_args input data - - Args: - constant_args (dict): these are the args that every model requires - model_args (dict): these are the required and optional spec args that - were passed in to make this model - self (class): the class that we are instantiating - This class contains self._composed_schemas - - Returns: - composed_info (list): length three - composed_instances (list): the composed instances which are not - self - var_name_to_model_instances (dict): a dict going from var_name - to the model_instance which holds that var_name - the model_instance may be self or an instance of one of the - classes in self.composed_instances() - additional_properties_model_instances (list): a list of the - model instances which have the property - additional_properties_type. This list can include self - """ - # create composed_instances - composed_instances = [] - allof_instances = get_allof_instances(self, model_args, constant_args) - composed_instances.extend(allof_instances) - oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) - if oneof_instance is not None: - composed_instances.append(oneof_instance) - anyof_instances = get_anyof_instances(self, model_args, constant_args) - composed_instances.extend(anyof_instances) - """ - set additional_properties_model_instances - additional properties must be evaluated at the schema level - so self's additional properties are most important - If self is a composed schema with: - - no properties defined in self - - additionalProperties: False - Then for object payloads every property is an additional property - and they are not allowed, so only empty dict is allowed - - Properties must be set on all matching schemas - so when a property is assigned toa composed instance, it must be set on all - composed instances regardless of additionalProperties presence - keeping it to prevent breaking changes in v5.0.1 - TODO remove cls._additional_properties_model_instances in 6.0.0 - """ - additional_properties_model_instances = [] - if self.additional_properties_type is not None: - additional_properties_model_instances = [self] - - """ - no need to set properties on self in here, they will be set in __init__ - By here all composed schema oneOf/anyOf/allOf instances have their properties set using - model_args - """ - discarded_args = get_discarded_args(self, composed_instances, model_args) - - # map variable names to composed_instances - var_name_to_model_instances = {} - for prop_name in model_args: - if prop_name not in discarded_args: - var_name_to_model_instances[prop_name] = [self] + list( - filter( - lambda x: prop_name in x.openapi_types, composed_instances)) - - return [ - composed_instances, - var_name_to_model_instances, - additional_properties_model_instances, - discarded_args - ] diff --git a/samples/openapi3/client/features/dynamic-servers/python/.gitignore b/samples/openapi3/client/features/dynamic-servers/python/.gitignore index 43995bd42f..a62e8aba43 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/.gitignore +++ b/samples/openapi3/client/features/dynamic-servers/python/.gitignore @@ -33,6 +33,7 @@ var/ # Installer logs pip-log.txt pip-delete-this-directory.txt +dev-requirements.txt.log # Unit test / coverage reports htmlcov/ diff --git a/samples/openapi3/client/features/dynamic-servers/python/.gitlab-ci.yml b/samples/openapi3/client/features/dynamic-servers/python/.gitlab-ci.yml index 5f3063bdcb..3d7864a767 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/.gitlab-ci.yml +++ b/samples/openapi3/client/features/dynamic-servers/python/.gitlab-ci.yml @@ -10,6 +10,9 @@ stages: - pip install -r test-requirements.txt - pytest --cov=dynamic_servers +test-3.5: + extends: .tests + image: python:3.5-alpine test-3.6: extends: .tests image: python:3.6-alpine @@ -19,6 +22,3 @@ test-3.7: test-3.8: extends: .tests image: python:3.8-alpine -test-3.9: - extends: .tests - image: python:3.9-alpine diff --git a/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/FILES b/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/FILES index e9b1845416..ae692977ef 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/FILES +++ b/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/FILES @@ -2,22 +2,22 @@ .gitlab-ci.yml .travis.yml README.md -docs/UsageApi.md +docs/apis/tags/UsageApi.md dynamic_servers/__init__.py -dynamic_servers/api/__init__.py -dynamic_servers/api/usage_api.py dynamic_servers/api_client.py dynamic_servers/apis/__init__.py +dynamic_servers/apis/tags/usage_api.py dynamic_servers/configuration.py dynamic_servers/exceptions.py dynamic_servers/model/__init__.py -dynamic_servers/model_utils.py dynamic_servers/models/__init__.py dynamic_servers/rest.py +dynamic_servers/schemas.py git_push.sh requirements.txt setup.cfg setup.py test-requirements.txt test/__init__.py +test/test_models/__init__.py tox.ini diff --git a/samples/openapi3/client/features/dynamic-servers/python/.travis.yml b/samples/openapi3/client/features/dynamic-servers/python/.travis.yml index 33011d57a8..2ed01c9973 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/.travis.yml +++ b/samples/openapi3/client/features/dynamic-servers/python/.travis.yml @@ -1,10 +1,10 @@ # ref: https://docs.travis-ci.com/user/languages/python language: python python: + - "3.5" - "3.6" - "3.7" - "3.8" - - "3.9" # command to install dependencies install: - "pip install -r requirements.txt" diff --git a/samples/openapi3/client/features/dynamic-servers/python/README.md b/samples/openapi3/client/features/dynamic-servers/python/README.md index f75ed4a6d0..c7567b057f 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/README.md +++ b/samples/openapi3/client/features/dynamic-servers/python/README.md @@ -9,7 +9,98 @@ This Python package is automatically generated by the [OpenAPI Generator](https: ## Requirements. -Python >=3.6 +Python >=3.7 + +## Migration from other generators like python and python-legacy + +### Changes +1. This generator uses spec case for all (object) property names and parameter names. + - So if the spec has a property name like camelCase, it will use camelCase rather than camel_case + - So you will need to update how you input and read properties to use spec case +2. Endpoint parameters are stored in dictionaries to prevent collisions (explanation below) + - So you will need to update how you pass data in to endpoints +3. Endpoint responses now include the original response, the deserialized response body, and (todo)the deserialized headers + - So you will need to update your code to use response.body to access deserialized data +4. All validated data is instantiated in an instance that subclasses all validated Schema classes and Decimal/str/list/tuple/frozendict/NoneClass/BoolClass/bytes/io.FileIO + - This means that you can use isinstance to check if a payload validated against a schema class + - This means that no data will be of type None/True/False + - ingested None will subclass NoneClass + - ingested True will subclass BoolClass + - ingested False will subclass BoolClass + - So if you need to check is True/False/None, instead use instance.is_true_oapg()/.is_false_oapg()/.is_none_oapg() +5. All validated class instances are immutable except for ones based on io.File + - This is because if properties were changed after validation, that validation would no longer apply + - So no changing values or property values after a class has been instantiated +6. String + Number types with formats + - String type data is stored as a string and if you need to access types based on its format like date, + date-time, uuid, number etc then you will need to use accessor functions on the instance + - type string + format: See .as_date_oapg, .as_datetime_oapg, .as_decimal_oapg, .as_uuid_oapg + - type number + format: See .as_float_oapg, .as_int_oapg + - this was done because openapi/json-schema defines constraints. string data may be type string with no format + keyword in one schema, and include a format constraint in another schema + - So if you need to access a string format based type, use as_date_oapg/as_datetime_oapg/as_decimal_oapg/as_uuid_oapg + - So if you need to access a number format based type, use as_int_oapg/as_float_oapg +7. Property access on AnyType(type unset) or object(dict) schemas + - Only required keys with valid python names are properties like .someProp and have type hints + - All optional keys may not exist, so properties are not defined for them + - One can access optional values with dict_instance['optionalProp'] and KeyError will be raised if it does not exist + - Use get_item_oapg if you need a way to always get a value whether or not the key exists + - If the key does not exist, schemas.unset is returned from calling dict_instance.get_item_oapg('optionalProp') + - All required and optional keys have type hints for this method, and @typing.overload is used + - A type hint is also generated for additionalProperties accessed using this method + - So you will need to update you code to use some_instance['optionalProp'] to access optional property + and additionalProperty values +8. The location of the api classes has changed + - Api classes are located in your_package.apis.tags.some_api + - This change was made to eliminate redundant code generation + - Legacy generators generated the same endpoint twice if it had > 1 tag on it + - This generator defines an endpoint in one class, then inherits that class to generate + apis by tags and by paths + - This change reduces code and allows quicker run time if you use the path apis + - path apis are at your_package.apis.paths.some_path + - Those apis will only load their needed models, which is less to load than all of the resources needed in a tag api + - So you will need to update your import paths to the api classes + +### Why are Oapg and _oapg used in class and method names? +Classes can have arbitrarily named properties set on them +Endpoints can have arbitrary operationId method names set +For those reasons, I use the prefix Oapg and _oapg to greatly reduce the likelihood of collisions +on protected + public classes/methods. +oapg stands for OpenApi Python Generator. + +### Object property spec case +This was done because when payloads are ingested, they can be validated against N number of schemas. +If the input signature used a different property name then that has mutated the payload. +So SchemaA and SchemaB must both see the camelCase spec named variable. +Also it is possible to send in two properties, named camelCase and camel_case in the same payload. +That use case should be support so spec case is used. + +### Parameter spec case +Parameters can be included in different locations including: +- query +- path +- header +- cookie + +Any of those parameters could use the same parameter names, so if every parameter +was included as an endpoint parameter in a function signature, they would collide. +For that reason, each of those inputs have been separated out into separate typed dictionaries: +- query_params +- path_params +- header_params +- cookie_params + +So when updating your code, you will need to pass endpoint parameters in using those +dictionaries. + +### Endpoint responses +Endpoint responses have been enriched to now include more information. +Any response reom an endpoint will now include the following properties: +response: urllib3.HTTPResponse +body: typing.Union[Unset, Schema] +headers: typing.Union[Unset, TODO] +Note: response header deserialization has not yet been added + ## Installation & Usage ### pip install @@ -49,7 +140,7 @@ Please follow the [installation procedure](#installation--usage) and then run th import time import dynamic_servers from pprint import pprint -from dynamic_servers.api import usage_api +from dynamic_servers.apis.tags import usage_api # Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 # See configuration.py for a list of all supported configuration parameters. configuration = dynamic_servers.Configuration( @@ -57,12 +148,11 @@ configuration = dynamic_servers.Configuration( ) - # Enter a context with an instance of the API client with dynamic_servers.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = usage_api.UsageApi(api_client) - + try: # Use custom server api_response = api_instance.custom_server() @@ -77,14 +167,12 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*UsageApi* | [**custom_server**](docs/UsageApi.md#custom_server) | **GET** /custom | Use custom server -*UsageApi* | [**default_server**](docs/UsageApi.md#default_server) | **GET** /default | Use default server - +*UsageApi* | [**custom_server**](docs/apis/tags/UsageApi.md#custom_server) | **get** /custom | Use custom server +*UsageApi* | [**default_server**](docs/apis/tags/UsageApi.md#default_server) | **get** /default | Use default server ## Documentation For Models - ## Documentation For Authorization All endpoints do not require authorization. @@ -93,17 +181,16 @@ Class | Method | HTTP request | Description - ## Notes for Large OpenAPI documents If the OpenAPI document is large, imports in dynamic_servers.apis and dynamic_servers.models may fail with a RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: Solution 1: Use specific imports for apis and models like: -- `from dynamic_servers.api.default_api import DefaultApi` +- `from dynamic_servers.apis.default_api import DefaultApi` - `from dynamic_servers.model.pet import Pet` -Solution 2: +Solution 1: Before importing the package, adjust the maximum recursion limit as shown below: ``` import sys @@ -112,4 +199,3 @@ import dynamic_servers from dynamic_servers.apis import * from dynamic_servers.models import * ``` - diff --git a/samples/openapi3/client/features/dynamic-servers/python/docs/apis/tags/UsageApi.md b/samples/openapi3/client/features/dynamic-servers/python/docs/apis/tags/UsageApi.md new file mode 100644 index 0000000000..fd5794f87d --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/docs/apis/tags/UsageApi.md @@ -0,0 +1,136 @@ + +# dynamic_servers.apis.tags.usage_api.UsageApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**custom_server**](#custom_server) | **get** /custom | Use custom server +[**default_server**](#default_server) | **get** /default | Use default server + +# **custom_server** + +> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} custom_server() + +Use custom server + +Use custom server + +### Example + +```python +import dynamic_servers +from dynamic_servers.apis.tags import usage_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = dynamic_servers.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with dynamic_servers.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = usage_api.UsageApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Use custom server + api_response = api_instance.custom_server() + pprint(api_response) + except dynamic_servers.ApiException as e: + print("Exception when calling UsageApi->custom_server: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#custom_server.ApiResponseFor200) | successful operation + +#### custom_server.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **default_server** + +> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} default_server() + +Use default server + +Use default server + +### Example + +```python +import dynamic_servers +from dynamic_servers.apis.tags import usage_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = dynamic_servers.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with dynamic_servers.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = usage_api.UsageApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Use default server + api_response = api_instance.default_server() + pprint(api_response) + except dynamic_servers.ApiException as e: + print("Exception when calling UsageApi->default_server: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#default_server.ApiResponseFor200) | successful operation + +#### default_server.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/__init__.py index f12625bd4e..887687d8b5 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/__init__.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/__init__.py @@ -1,3 +1,5 @@ +# coding: utf-8 + # flake8: noqa """ @@ -9,7 +11,6 @@ Generated by: https://openapi-generator.tech """ - __version__ = "1.0.0" # import ApiClient diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api_client.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api_client.py index 6106c4b752..b931cc044f 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api_client.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api_client.py @@ -1,3 +1,4 @@ +# coding: utf-8 """ OpenAPI Extension with dynamic servers @@ -7,39 +8,959 @@ Generated by: https://openapi-generator.tech """ - +from dataclasses import dataclass +from decimal import Decimal +import enum +import email import json -import atexit -import mimetypes -from multiprocessing.pool import ThreadPool -import io import os +import io +import atexit +from multiprocessing.pool import ThreadPool import re +import tempfile import typing -from urllib.parse import quote -from urllib3.fields import RequestField +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict +from urllib.parse import urlparse, quote +from urllib3.fields import RequestField as RequestFieldBase +import frozendict from dynamic_servers import rest from dynamic_servers.configuration import Configuration -from dynamic_servers.exceptions import ApiTypeError, ApiValueError, ApiException -from dynamic_servers.model_utils import ( - ModelNormal, - ModelSimple, - ModelComposed, - check_allowed_values, - check_validations, +from dynamic_servers.exceptions import ApiTypeError, ApiValueError +from dynamic_servers.schemas import ( + NoneClass, + BoolClass, + Schema, + FileIO, + BinarySchema, date, datetime, - deserialize_file, - file_type, - model_to_dict, none_type, - validate_and_convert_types + Unset, + unset, ) -class ApiClient(object): +class RequestField(RequestFieldBase): + def __eq__(self, other): + if not isinstance(other, RequestField): + return False + return self.__dict__ == other.__dict__ + + +class JSONEncoder(json.JSONEncoder): + compact_separators = (',', ':') + + def default(self, obj): + if isinstance(obj, str): + return str(obj) + elif isinstance(obj, float): + return float(obj) + elif isinstance(obj, int): + return int(obj) + elif isinstance(obj, Decimal): + if obj.as_tuple().exponent >= 0: + return int(obj) + return float(obj) + elif isinstance(obj, NoneClass): + return None + elif isinstance(obj, BoolClass): + return bool(obj) + elif isinstance(obj, (dict, frozendict.frozendict)): + return {key: self.default(val) for key, val in obj.items()} + elif isinstance(obj, (list, tuple)): + return [self.default(item) for item in obj] + raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__)) + + +class ParameterInType(enum.Enum): + QUERY = 'query' + HEADER = 'header' + PATH = 'path' + COOKIE = 'cookie' + + +class ParameterStyle(enum.Enum): + MATRIX = 'matrix' + LABEL = 'label' + FORM = 'form' + SIMPLE = 'simple' + SPACE_DELIMITED = 'spaceDelimited' + PIPE_DELIMITED = 'pipeDelimited' + DEEP_OBJECT = 'deepObject' + + +class PrefixSeparatorIterator: + # A class to store prefixes and separators for rfc6570 expansions + + def __init__(self, prefix: str, separator: str): + self.prefix = prefix + self.separator = separator + self.first = True + if separator in {'.', '|', '%20'}: + item_separator = separator + else: + item_separator = ',' + self.item_separator = item_separator + + def __iter__(self): + return self + + def __next__(self): + if self.first: + self.first = False + return self.prefix + return self.separator + + +class ParameterSerializerBase: + @classmethod + def _get_default_explode(cls, style: ParameterStyle) -> bool: + return False + + @staticmethod + def __ref6570_item_value(in_data: typing.Any, percent_encode: bool): + """ + Get representation if str/float/int/None/items in list/ values in dict + None is returned if an item is undefined, use cases are value= + - None + - [] + - {} + - [None, None None] + - {'a': None, 'b': None} + """ + if type(in_data) in {str, float, int}: + if percent_encode: + return quote(str(in_data)) + return str(in_data) + elif isinstance(in_data, none_type): + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return None + elif isinstance(in_data, list) and not in_data: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return None + elif isinstance(in_data, dict) and not in_data: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return None + raise ApiValueError('Unable to generate a ref6570 item representation of {}'.format(in_data)) + + @staticmethod + def _to_dict(name: str, value: str): + return {name: value} + + @classmethod + def __ref6570_str_float_int_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + item_value = cls.__ref6570_item_value(in_data, percent_encode) + if item_value is None or (item_value == '' and prefix_separator_iterator.separator == ';'): + return next(prefix_separator_iterator) + var_name_piece + value_pair_equals = '=' if named_parameter_expansion else '' + return next(prefix_separator_iterator) + var_name_piece + value_pair_equals + item_value + + @classmethod + def __ref6570_list_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + item_values = [cls.__ref6570_item_value(v, percent_encode) for v in in_data] + item_values = [v for v in item_values if v is not None] + if not item_values: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + value_pair_equals = '=' if named_parameter_expansion else '' + if not explode: + return ( + next(prefix_separator_iterator) + + var_name_piece + + value_pair_equals + + prefix_separator_iterator.item_separator.join(item_values) + ) + # exploded + return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( + [var_name_piece + value_pair_equals + val for val in item_values] + ) + + @classmethod + def __ref6570_dict_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + in_data_transformed = {key: cls.__ref6570_item_value(val, percent_encode) for key, val in in_data.items()} + in_data_transformed = {key: val for key, val in in_data_transformed.items() if val is not None} + if not in_data_transformed: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + value_pair_equals = '=' if named_parameter_expansion else '' + if not explode: + return ( + next(prefix_separator_iterator) + + var_name_piece + value_pair_equals + + prefix_separator_iterator.item_separator.join( + prefix_separator_iterator.item_separator.join( + item_pair + ) for item_pair in in_data_transformed.items() + ) + ) + # exploded + return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( + [key + '=' + val for key, val in in_data_transformed.items()] + ) + + @classmethod + def _ref6570_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator + ) -> str: + """ + Separator is for separate variables like dict with explode true, not for array item separation + """ + named_parameter_expansion = prefix_separator_iterator.separator in {'&', ';'} + var_name_piece = variable_name if named_parameter_expansion else '' + if type(in_data) in {str, float, int}: + return cls.__ref6570_str_float_int_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) + elif isinstance(in_data, none_type): + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + elif isinstance(in_data, list): + return cls.__ref6570_list_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) + elif isinstance(in_data, dict): + return cls.__ref6570_dict_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) + # bool, bytes, etc + raise ApiValueError('Unable to generate a ref6570 representation of {}'.format(in_data)) + + +class StyleFormSerializer(ParameterSerializerBase): + @classmethod + def _get_default_explode(cls, style: ParameterStyle) -> bool: + if style is ParameterStyle.FORM: + return True + return super()._get_default_explode(style) + + def _serialize_form( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None + ) -> str: + if prefix_separator_iterator is None: + prefix_separator_iterator = PrefixSeparatorIterator('?', '&') + return self._ref6570_expansion( + variable_name=name, + in_data=in_data, + explode=explode, + percent_encode=percent_encode, + prefix_separator_iterator=prefix_separator_iterator + ) + + +class StyleSimpleSerializer(ParameterSerializerBase): + + def _serialize_simple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + percent_encode: bool + ) -> str: + prefix_separator_iterator = PrefixSeparatorIterator('', ',') + return self._ref6570_expansion( + variable_name=name, + in_data=in_data, + explode=explode, + percent_encode=percent_encode, + prefix_separator_iterator=prefix_separator_iterator + ) + + +class JSONDetector: + """ + Works for: + application/json + application/json; charset=UTF-8 + application/json-patch+json + application/geo+json + """ + __json_content_type_pattern = re.compile("application/[^+]*[+]?(json);?.*") + + @classmethod + def _content_type_is_json(cls, content_type: str) -> bool: + if cls.__json_content_type_pattern.match(content_type): + return True + return False + + +@dataclass +class ParameterBase(JSONDetector): + name: str + in_type: ParameterInType + required: bool + style: typing.Optional[ParameterStyle] + explode: typing.Optional[bool] + allow_reserved: typing.Optional[bool] + schema: typing.Optional[typing.Type[Schema]] + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] + + __style_to_in_type = { + ParameterStyle.MATRIX: {ParameterInType.PATH}, + ParameterStyle.LABEL: {ParameterInType.PATH}, + ParameterStyle.FORM: {ParameterInType.QUERY, ParameterInType.COOKIE}, + ParameterStyle.SIMPLE: {ParameterInType.PATH, ParameterInType.HEADER}, + ParameterStyle.SPACE_DELIMITED: {ParameterInType.QUERY}, + ParameterStyle.PIPE_DELIMITED: {ParameterInType.QUERY}, + ParameterStyle.DEEP_OBJECT: {ParameterInType.QUERY}, + } + __in_type_to_default_style = { + ParameterInType.QUERY: ParameterStyle.FORM, + ParameterInType.PATH: ParameterStyle.SIMPLE, + ParameterInType.HEADER: ParameterStyle.SIMPLE, + ParameterInType.COOKIE: ParameterStyle.FORM, + } + __disallowed_header_names = {'Accept', 'Content-Type', 'Authorization'} + _json_encoder = JSONEncoder() + + @classmethod + def __verify_style_to_in_type(cls, style: typing.Optional[ParameterStyle], in_type: ParameterInType): + if style is None: + return + in_type_set = cls.__style_to_in_type[style] + if in_type not in in_type_set: + raise ValueError( + 'Invalid style and in_type combination. For style={} only in_type={} are allowed'.format( + style, in_type_set + ) + ) + + def __init__( + self, + name: str, + in_type: ParameterInType, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + if schema is None and content is None: + raise ValueError('Value missing; Pass in either schema or content') + if schema and content: + raise ValueError('Too many values provided. Both schema and content were provided. Only one may be input') + if name in self.__disallowed_header_names and in_type is ParameterInType.HEADER: + raise ValueError('Invalid name, name may not be one of {}'.format(self.__disallowed_header_names)) + self.__verify_style_to_in_type(style, in_type) + if content is None and style is None: + style = self.__in_type_to_default_style[in_type] + if content is not None and in_type in self.__in_type_to_default_style and len(content) != 1: + raise ValueError('Invalid content length, content length must equal 1') + self.in_type = in_type + self.name = name + self.required = required + self.style = style + self.explode = explode + self.allow_reserved = allow_reserved + self.schema = schema + self.content = content + + def _serialize_json( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + eliminate_whitespace: bool = False + ) -> str: + if eliminate_whitespace: + return json.dumps(in_data, separators=self._json_encoder.compact_separators) + return json.dumps(in_data) + + +class PathParameter(ParameterBase, StyleSimpleSerializer): + + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + super().__init__( + name, + in_type=ParameterInType.PATH, + required=required, + style=style, + explode=explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + def __serialize_label( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Dict[str, str]: + prefix_separator_iterator = PrefixSeparatorIterator('.', '.') + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_matrix( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Dict[str, str]: + prefix_separator_iterator = PrefixSeparatorIterator(';', ';') + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_simple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + ) -> typing.Dict[str, str]: + value = self._serialize_simple( + in_data=in_data, + name=self.name, + explode=self.explode, + percent_encode=True + ) + return self._to_dict(self.name, value) + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> typing.Dict[str, str]: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + simple -> path + path: + returns path_params: dict + label -> path + returns path_params + matrix -> path + returns path_params + """ + if self.style: + if self.style is ParameterStyle.SIMPLE: + return self.__serialize_simple(cast_in_data) + elif self.style is ParameterStyle.LABEL: + return self.__serialize_label(cast_in_data) + elif self.style is ParameterStyle.MATRIX: + return self.__serialize_matrix(cast_in_data) + # self.content will be length one + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data) + return self._to_dict(self.name, value) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class QueryParameter(ParameterBase, StyleFormSerializer): + + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: typing.Optional[bool] = None, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + used_style = ParameterStyle.FORM if style is None else style + used_explode = self._get_default_explode(used_style) if explode is None else explode + + super().__init__( + name, + in_type=ParameterInType.QUERY, + required=required, + style=used_style, + explode=used_explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + def __serialize_space_delimited( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] + ) -> typing.Dict[str, str]: + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_pipe_delimited( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] + ) -> typing.Dict[str, str]: + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_form( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] + ) -> typing.Dict[str, str]: + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + value = self._serialize_form( + in_data, + name=self.name, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def get_prefix_separator_iterator(self) -> typing.Optional[PrefixSeparatorIterator]: + if self.style is ParameterStyle.FORM: + return PrefixSeparatorIterator('?', '&') + elif self.style is ParameterStyle.SPACE_DELIMITED: + return PrefixSeparatorIterator('', '%20') + elif self.style is ParameterStyle.PIPE_DELIMITED: + return PrefixSeparatorIterator('', '|') + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None + ) -> typing.Dict[str, str]: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + form -> query + query: + - GET/HEAD/DELETE: could use fields + - PUT/POST: must use urlencode to send parameters + returns fields: tuple + spaceDelimited -> query + returns fields + pipeDelimited -> query + returns fields + deepObject -> query, https://github.com/OAI/OpenAPI-Specification/issues/1706 + returns fields + """ + if self.style: + # TODO update query ones to omit setting values when [] {} or None is input + if self.style is ParameterStyle.FORM: + return self.__serialize_form(cast_in_data, prefix_separator_iterator) + elif self.style is ParameterStyle.SPACE_DELIMITED: + return self.__serialize_space_delimited(cast_in_data, prefix_separator_iterator) + elif self.style is ParameterStyle.PIPE_DELIMITED: + return self.__serialize_pipe_delimited(cast_in_data, prefix_separator_iterator) + # self.content will be length one + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data, eliminate_whitespace=True) + return self._to_dict( + self.name, + next(prefix_separator_iterator) + self.name + '=' + quote(value) + ) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class CookieParameter(ParameterBase, StyleFormSerializer): + + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: typing.Optional[bool] = None, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + used_style = ParameterStyle.FORM if style is None and content is None and schema else style + used_explode = self._get_default_explode(used_style) if explode is None else explode + + super().__init__( + name, + in_type=ParameterInType.COOKIE, + required=required, + style=used_style, + explode=used_explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> typing.Dict[str, str]: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + form -> cookie + returns fields: tuple + """ + if self.style: + """ + TODO add escaping of comma, space, equals + or turn encoding on + """ + value = self._serialize_form( + cast_in_data, + explode=self.explode, + name=self.name, + percent_encode=False, + prefix_separator_iterator=PrefixSeparatorIterator('', '&') + ) + return self._to_dict(self.name, value) + # self.content will be length one + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data) + return self._to_dict(self.name, value) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class HeaderParameter(ParameterBase, StyleSimpleSerializer): + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + super().__init__( + name, + in_type=ParameterInType.HEADER, + required=required, + style=style, + explode=explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + @staticmethod + def __to_headers(in_data: typing.Tuple[typing.Tuple[str, str], ...]) -> HTTPHeaderDict: + data = tuple(t for t in in_data if t) + headers = HTTPHeaderDict() + if not data: + return headers + headers.extend(data) + return headers + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> HTTPHeaderDict: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + simple -> header + headers: PoolManager needs a mapping, tuple is close + returns headers: dict + """ + if self.style: + value = self._serialize_simple(cast_in_data, self.name, self.explode, False) + return self.__to_headers(((self.name, value),)) + # self.content will be length one + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data) + return self.__to_headers(((self.name, value),)) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class Encoding: + def __init__( + self, + content_type: str, + headers: typing.Optional[typing.Dict[str, HeaderParameter]] = None, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: bool = False, + ): + self.content_type = content_type + self.headers = headers + self.style = style + self.explode = explode + self.allow_reserved = allow_reserved + + +@dataclass +class MediaType: + """ + Used to store request and response body schema information + encoding: + A map between a property name and its encoding information. + The key, being the property name, MUST exist in the schema as a property. + The encoding object SHALL only apply to requestBody objects when the media type is + multipart or application/x-www-form-urlencoded. + """ + schema: typing.Optional[typing.Type[Schema]] = None + encoding: typing.Optional[typing.Dict[str, Encoding]] = None + + +@dataclass +class ApiResponse: + response: urllib3.HTTPResponse + body: typing.Union[Unset, Schema] + headers: typing.Union[Unset, typing.List[HeaderParameter]] + + def __init__( + self, + response: urllib3.HTTPResponse, + body: typing.Union[Unset, typing.Type[Schema]], + headers: typing.Union[Unset, typing.List[HeaderParameter]] + ): + """ + pycharm needs this to prevent 'Unexpected argument' warnings + """ + self.response = response + self.body = body + self.headers = headers + + +@dataclass +class ApiResponseWithoutDeserialization(ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[Unset, typing.Type[Schema]] = unset + headers: typing.Union[Unset, typing.List[HeaderParameter]] = unset + + +class OpenApiResponse(JSONDetector): + __filename_content_disposition_pattern = re.compile('filename="(.+?)"') + + def __init__( + self, + response_cls: typing.Type[ApiResponse] = ApiResponse, + content: typing.Optional[typing.Dict[str, MediaType]] = None, + headers: typing.Optional[typing.List[HeaderParameter]] = None, + ): + self.headers = headers + if content is not None and len(content) == 0: + raise ValueError('Invalid value for content, the content dict must have >= 1 entry') + self.content = content + self.response_cls = response_cls + + @staticmethod + def __deserialize_json(response: urllib3.HTTPResponse) -> typing.Any: + # python must be >= 3.9 so we can pass in bytes into json.loads + return json.loads(response.data) + + @staticmethod + def __file_name_from_response_url(response_url: typing.Optional[str]) -> typing.Optional[str]: + if response_url is None: + return None + url_path = urlparse(response_url).path + if url_path: + path_basename = os.path.basename(url_path) + if path_basename: + _filename, ext = os.path.splitext(path_basename) + if ext: + return path_basename + return None + + @classmethod + def __file_name_from_content_disposition(cls, content_disposition: typing.Optional[str]) -> typing.Optional[str]: + if content_disposition is None: + return None + match = cls.__filename_content_disposition_pattern.search(content_disposition) + if not match: + return None + return match.group(1) + + def __deserialize_application_octet_stream( + self, response: urllib3.HTTPResponse + ) -> typing.Union[bytes, io.BufferedReader]: + """ + urllib3 use cases: + 1. when preload_content=True (stream=False) then supports_chunked_reads is False and bytes are returned + 2. when preload_content=False (stream=True) then supports_chunked_reads is True and + a file will be written and returned + """ + if response.supports_chunked_reads(): + file_name = ( + self.__file_name_from_content_disposition(response.headers.get('content-disposition')) + or self.__file_name_from_response_url(response.geturl()) + ) + + if file_name is None: + _fd, path = tempfile.mkstemp() + else: + path = os.path.join(tempfile.gettempdir(), file_name) + + with open(path, 'wb') as new_file: + chunk_size = 1024 + while True: + data = response.read(chunk_size) + if not data: + break + new_file.write(data) + # release_conn is needed for streaming connections only + response.release_conn() + new_file = open(path, 'rb') + return new_file + else: + return response.data + + @staticmethod + def __deserialize_multipart_form_data( + response: urllib3.HTTPResponse + ) -> typing.Dict[str, typing.Any]: + msg = email.message_from_bytes(response.data) + return { + part.get_param("name", header="Content-Disposition"): part.get_payload( + decode=True + ).decode(part.get_content_charset()) + if part.get_content_charset() + else part.get_payload() + for part in msg.get_payload() + } + + def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse: + content_type = response.getheader('content-type') + deserialized_body = unset + streamed = response.supports_chunked_reads() + + deserialized_headers = unset + if self.headers is not None: + # TODO add header deserialiation here + pass + + if self.content is not None: + if content_type not in self.content: + raise ApiValueError( + f"Invalid content_type returned. Content_type='{content_type}' was returned " + f"when only {str(set(self.content))} are defined for status_code={str(response.status)}" + ) + body_schema = self.content[content_type].schema + if body_schema is None: + # some specs do not define response content media type schemas + return self.response_cls( + response=response, + headers=deserialized_headers, + body=unset + ) + + if self._content_type_is_json(content_type): + body_data = self.__deserialize_json(response) + elif content_type == 'application/octet-stream': + body_data = self.__deserialize_application_octet_stream(response) + elif content_type.startswith('multipart/form-data'): + body_data = self.__deserialize_multipart_form_data(response) + content_type = 'multipart/form-data' + else: + raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type)) + deserialized_body = body_schema.from_openapi_data_oapg( + body_data, _configuration=configuration) + elif streamed: + response.release_conn() + + return self.response_cls( + response=response, + headers=deserialized_headers, + body=deserialized_body + ) + + +class ApiClient: """Generic API client for OpenAPI client library builds. OpenAPI generic API client. This client handles the client- @@ -63,15 +984,21 @@ class ApiClient(object): _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1): + def __init__( + self, + configuration: typing.Optional[Configuration] = None, + header_name: typing.Optional[str] = None, + header_value: typing.Optional[str] = None, + cookie: typing.Optional[str] = None, + pool_threads: int = 1 + ): if configuration is None: - configuration = Configuration.get_default_copy() + configuration = Configuration() self.configuration = configuration self.pool_threads = pool_threads self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} + self.default_headers = HTTPHeaderDict() if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie @@ -118,298 +1045,86 @@ class ApiClient(object): self, resource_path: str, method: str, - path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - body: typing.Optional[typing.Any] = None, - post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, - response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + headers: typing.Optional[HTTPHeaderDict] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, auth_settings: typing.Optional[typing.List[str]] = None, - _return_http_data_only: typing.Optional[bool] = None, - collection_formats: typing.Optional[typing.Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, - _host: typing.Optional[str] = None, - _check_type: typing.Optional[bool] = None, - _content_type: typing.Optional[str] = None, - _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None - ): - - config = self.configuration + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + host: typing.Optional[str] = None, + ) -> urllib3.HTTPResponse: # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) + used_headers = HTTPHeaderDict(self.default_headers) if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - '{%s}' % k, - quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, - collection_formats) - - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) - post_params.extend(self.files_parameters(files)) - if header_params['Content-Type'].startswith("multipart"): - post_params = self.parameters_to_multipart(post_params, - (dict)) - - # body - if body: - body = self.sanitize_for_serialization(body) + headers['Cookie'] = self.cookie # auth setting - self.update_params_for_auth(header_params, query_params, - auth_settings, resource_path, method, body, - request_auths=_request_auths) + self.update_params_for_auth(used_headers, + auth_settings, resource_path, method, body) + + # must happen after cookie setting and auth setting in case user is overriding those + if headers: + used_headers.update(headers) # request url - if _host is None: + if host is None: url = self.configuration.host + resource_path else: # use server/host defined in path or operation instead - url = _host + resource_path + url = host + resource_path - try: - # perform request and return response - response_data = self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - except ApiException as e: - e.body = e.body.decode('utf-8') - raise e - - self.last_response = response_data - - return_data = response_data - - if not _preload_content: - return (return_data) - return return_data - - # deserialize response data - if response_type: - if response_type != (file_type,): - encoding = "utf-8" - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) - if match: - encoding = match.group(1) - response_data.data = response_data.data.decode(encoding) - - return_data = self.deserialize( - response_data, - response_type, - _check_type - ) - else: - return_data = None - - if _return_http_data_only: - return (return_data) - else: - return (return_data, response_data.status, - response_data.getheaders()) - - def parameters_to_multipart(self, params, collection_types): - """Get parameters as list of tuples, formatting as json if value is collection_types - - :param params: Parameters as list of two-tuples - :param dict collection_types: Parameter collection types - :return: Parameters as list of tuple or urllib3.fields.RequestField - """ - new_params = [] - if collection_types is None: - collection_types = (dict) - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance( - v, collection_types): # v is instance of collection_type, formatting as application/json - v = json.dumps(v, ensure_ascii=False).encode("utf-8") - field = RequestField(k, v) - field.make_multipart(content_type="application/json; charset=utf-8") - new_params.append(field) - else: - new_params.append((k, v)) - return new_params - - @classmethod - def sanitize_for_serialization(cls, obj): - """Prepares data for transmission before it is sent with the rest client - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is OpenAPI model, return the properties dict. - If obj is io.IOBase, return the bytes - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if isinstance(obj, (ModelNormal, ModelComposed)): - return { - key: cls.sanitize_for_serialization(val) for key, - val in model_to_dict( - obj, - serialize=True).items()} - elif isinstance(obj, io.IOBase): - return cls.get_file_data_and_close_file(obj) - elif isinstance(obj, (str, int, float, none_type, bool)): - return obj - elif isinstance(obj, (datetime, date)): - return obj.isoformat() - elif isinstance(obj, ModelSimple): - return cls.sanitize_for_serialization(obj.value) - elif isinstance(obj, (list, tuple)): - return [cls.sanitize_for_serialization(item) for item in obj] - if isinstance(obj, dict): - return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()} - raise ApiValueError( - 'Unable to prepare type {} for serialization'.format( - obj.__class__.__name__)) - - def deserialize(self, response, response_type, _check_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: For the response, a tuple containing: - valid classes - a list containing valid classes (for list schemas) - a dict containing a tuple of valid classes as the value - Example values: - (str,) - (Pet,) - (float, none_type) - ([int, none_type],) - ({str: (bool, str, int, float, date, datetime, str, none_type)},) - :param _check_type: boolean, whether to check the types of the data - received from the server - :type _check_type: bool - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == (file_type,): - content_disposition = response.getheader("Content-Disposition") - return deserialize_file(response.data, self.configuration, - content_disposition=content_disposition) - - # fetch data from response object - try: - received_data = json.loads(response.data) - except ValueError: - received_data = response.data - - # store our data under the key of 'received_data' so users have some - # context if they are deserializing a string and the data type is wrong - deserialized_data = validate_and_convert_types( - received_data, - response_type, - ['received_data'], - True, - _check_type, - configuration=self.configuration + # perform request and return response + response = self.request( + method, + url, + headers=used_headers, + fields=fields, + body=body, + stream=stream, + timeout=timeout, ) - return deserialized_data + return response def call_api( self, resource_path: str, method: str, - path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - body: typing.Optional[typing.Any] = None, - post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, - response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + headers: typing.Optional[HTTPHeaderDict] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, auth_settings: typing.Optional[typing.List[str]] = None, async_req: typing.Optional[bool] = None, - _return_http_data_only: typing.Optional[bool] = None, - collection_formats: typing.Optional[typing.Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, - _host: typing.Optional[str] = None, - _check_type: typing.Optional[bool] = None, - _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None - ): + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + host: typing.Optional[str] = None, + ) -> urllib3.HTTPResponse: """Makes the HTTP request (synchronous) and returns deserialized data. To make an async_req request, set the async_req parameter. :param resource_path: Path to method endpoint. :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be + :param headers: Header parameters to be placed in the request header. :param body: Request body. - :param post_params dict: Request post form parameters, + :param fields: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response_type: For the response, a tuple containing: - valid classes - a list containing valid classes (for list schemas) - a dict containing a tuple of valid classes as the value - Example values: - (str,) - (Pet,) - (float, none_type) - ([int, none_type],) - ({str: (bool, str, int, float, date, datetime, str, none_type)},) - :param files: key -> field name, value -> a list of open file - objects for `multipart/form-data`. - :type files: dict - :param async_req bool: execute request asynchronously - :type async_req: bool, optional - :param _return_http_data_only: response data without head status code - and headers - :type _return_http_data_only: bool, optional - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :type collection_formats: dict, optional - :param _preload_content: if False, the urllib3.HTTPResponse object will + :param auth_settings: Auth Settings names for the request. + :param async_req: execute request asynchronously + :type async_req: bool, optional TODO remove, unused + :param stream: if True, the urllib3.HTTPResponse object will be returned without reading/decoding response - data. Default is True. - :type _preload_content: bool, optional - :param _request_timeout: timeout setting for this request. If one + data. Also when True, if the openapi spec describes a file download, + the data will be written to a local filesystme file and the BinarySchema + instance will also inherit from FileSchema and FileIO + Default is False. + :type stream: bool, optional + :param timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. - :param _check_type: boolean describing if the data back from the server - should have its type checked. - :type _check_type: bool, optional - :param _request_auths: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auths: list, optional + :param host: api endpoint host :return: If async_req parameter is True, the request will be called asynchronously. @@ -417,82 +1132,90 @@ class ApiClient(object): If parameter async_req is False or missing, then the method will return the response directly. """ + if not async_req: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, - _return_http_data_only, collection_formats, - _preload_content, _request_timeout, _host, - _check_type, _request_auths=_request_auths) + return self.__call_api( + resource_path, + method, + headers, + body, + fields, + auth_settings, + stream, + timeout, + host, + ) - return self.pool.apply_async(self.__call_api, (resource_path, - method, path_params, - query_params, - header_params, body, - post_params, files, - response_type, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, _check_type, None, _request_auths)) + return self.pool.apply_async( + self.__call_api, + ( + resource_path, + method, + headers, + body, + json, + fields, + auth_settings, + stream, + timeout, + host, + ) + ) - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def request( + self, + method: str, + url: str, + headers: typing.Optional[HTTPHeaderDict] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> urllib3.HTTPResponse: """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.GET(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + stream=stream, + timeout=timeout, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + stream=stream, + timeout=timeout, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, - query_params=query_params, headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + fields=fields, + stream=stream, + timeout=timeout, body=body) elif method == "POST": return self.rest_client.POST(url, - query_params=query_params, headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + fields=fields, + stream=stream, + timeout=timeout, body=body) elif method == "PUT": return self.rest_client.PUT(url, - query_params=query_params, headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + fields=fields, + stream=stream, + timeout=timeout, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, - query_params=query_params, headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + fields=fields, + stream=stream, + timeout=timeout, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, - query_params=query_params, headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + stream=stream, + timeout=timeout, body=body) else: raise ApiValueError( @@ -500,397 +1223,277 @@ class ApiClient(object): " `POST`, `PATCH`, `PUT` or `DELETE`." ) - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - @staticmethod - def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: - file_data = file_instance.read() - file_instance.close() - return file_data - - def files_parameters(self, - files: typing.Optional[typing.Dict[str, - typing.List[io.IOBase]]] = None): - """Builds form parameters. - - :param files: None or a dict with key=param_name and - value is a list of open file objects - :return: List of tuples of form parameters with file data - """ - if files is None: - return [] - - params = [] - for param_name, file_instances in files.items(): - if file_instances is None: - # if the file field is nullable, skip None values - continue - for file_instance in file_instances: - if file_instance is None: - # if the file field is nullable, skip None values - continue - if file_instance.closed is True: - raise ApiValueError( - "Cannot read a closed file. The passed in file_type " - "for %s must be open." % param_name - ) - filename = os.path.basename(file_instance.name) - filedata = self.get_file_data_and_close_file(file_instance) - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') - params.append( - tuple([param_name, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - accepts = [x.lower() for x in accepts] - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types, method=None, body=None): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :param method: http method (e.g. POST, PATCH). - :param body: http body to send. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return None - - content_types = [x.lower() for x in content_types] - - if (method == 'PATCH' and - 'application/json-patch+json' in content_types and - isinstance(body, list)): - return 'application/json-patch+json' - - if 'application/json' in content_types or '*/*' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, request_auths=None): + def update_params_for_auth(self, headers, auth_settings, + resource_path, method, body): """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. :param resource_path: A string representation of the HTTP request resource path. :param method: A string representation of the HTTP request method. :param body: A object representing the body of the HTTP request. The object type is the return value of _encoder.default(). - :param request_auths: if set, the provided settings will - override the token in the configuration. """ if not auth_settings: return - if request_auths: - for auth_setting in request_auths: - self._apply_auth_params( - headers, queries, resource_path, method, body, auth_setting) - return - for auth in auth_settings: auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params( - headers, queries, resource_path, method, body, auth_setting) - - def _apply_auth_params(self, headers, queries, resource_path, method, body, auth_setting): - if auth_setting['in'] == 'cookie': - headers['Cookie'] = auth_setting['key'] + "=" + auth_setting['value'] - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - queries.append((auth_setting['key'], auth_setting['value'])) - else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) - - -class Endpoint(object): - def __init__(self, settings=None, params_map=None, root_map=None, - headers_map=None, api_client=None, callable=None): - """Creates an endpoint - - Args: - settings (dict): see below key value pairs - 'response_type' (tuple/None): response type - 'auth' (list): a list of auth type keys - 'endpoint_path' (str): the endpoint path - 'operation_id' (str): endpoint string identifier - 'http_method' (str): POST/PUT/PATCH/GET etc - 'servers' (list): list of str servers that this endpoint is at - params_map (dict): see below key value pairs - 'all' (list): list of str endpoint parameter names - 'required' (list): list of required parameter names - 'nullable' (list): list of nullable parameter names - 'enum' (list): list of parameters with enum values - 'validation' (list): list of parameters with validations - root_map - 'validations' (dict): the dict mapping endpoint parameter tuple - paths to their validation dictionaries - 'allowed_values' (dict): the dict mapping endpoint parameter - tuple paths to their allowed_values (enum) dictionaries - 'openapi_types' (dict): param_name to openapi type - 'attribute_map' (dict): param_name to camelCase name - 'location_map' (dict): param_name to 'body', 'file', 'form', - 'header', 'path', 'query' - collection_format_map (dict): param_name to `csv` etc. - headers_map (dict): see below key value pairs - 'accept' (list): list of Accept header strings - 'content_type' (list): list of Content-Type header strings - api_client (ApiClient) api client instance - callable (function): the function which is invoked when the - Endpoint is called - """ - self.settings = settings - self.params_map = params_map - self.params_map['all'].extend([ - 'async_req', - '_host_index', - '_preload_content', - '_request_timeout', - '_return_http_data_only', - '_check_input_type', - '_check_return_type', - '_content_type', - '_spec_property_naming', - '_request_auths' - ]) - self.params_map['nullable'].extend(['_request_timeout']) - self.validations = root_map['validations'] - self.allowed_values = root_map['allowed_values'] - self.openapi_types = root_map['openapi_types'] - extra_types = { - 'async_req': (bool,), - '_host_index': (none_type, int), - '_preload_content': (bool,), - '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), - '_return_http_data_only': (bool,), - '_check_input_type': (bool,), - '_check_return_type': (bool,), - '_spec_property_naming': (bool,), - '_content_type': (none_type, str), - '_request_auths': (none_type, list) - } - self.openapi_types.update(extra_types) - self.attribute_map = root_map['attribute_map'] - self.location_map = root_map['location_map'] - self.collection_format_map = root_map['collection_format_map'] - self.headers_map = headers_map - self.api_client = api_client - self.callable = callable - - def __validate_inputs(self, kwargs): - for param in self.params_map['enum']: - if param in kwargs: - check_allowed_values( - self.allowed_values, - (param,), - kwargs[param] - ) - - for param in self.params_map['validation']: - if param in kwargs: - check_validations( - self.validations, - (param,), - kwargs[param], - configuration=self.api_client.configuration - ) - - if kwargs['_check_input_type'] is False: - return - - for key, value in kwargs.items(): - fixed_val = validate_and_convert_types( - value, - self.openapi_types[key], - [key], - kwargs['_spec_property_naming'], - kwargs['_check_input_type'], - configuration=self.api_client.configuration - ) - kwargs[key] = fixed_val - - def __gather_params(self, kwargs): - params = { - 'body': None, - 'collection_format': {}, - 'file': {}, - 'form': [], - 'header': {}, - 'path': {}, - 'query': [] - } - - for param_name, param_value in kwargs.items(): - param_location = self.location_map.get(param_name) - if param_location is None: + if not auth_setting: continue - if param_location: - if param_location == 'body': - params['body'] = param_value - continue - base_name = self.attribute_map[param_name] - if (param_location == 'form' and - self.openapi_types[param_name] == (file_type,)): - params['file'][base_name] = [param_value] - elif (param_location == 'form' and - self.openapi_types[param_name] == ([file_type],)): - # param_value is already a list - params['file'][base_name] = param_value - elif param_location in {'form', 'query'}: - param_value_full = (base_name, param_value) - params[param_location].append(param_value_full) - if param_location not in {'form', 'query'}: - params[param_location][base_name] = param_value - collection_format = self.collection_format_map.get(param_name) - if collection_format: - params['collection_format'][base_name] = collection_format + if auth_setting['in'] == 'cookie': + headers.add('Cookie', auth_setting['value']) + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers.add(auth_setting['key'], auth_setting['value']) + elif auth_setting['in'] == 'query': + """ TODO implement auth in query + need to pass in prefix_separator_iterator + and need to output resource_path with query params added + """ + raise ApiValueError("Auth in query not yet implemented") + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) - return params - def __call__(self, *args, **kwargs): - """ This method is invoked when endpoints are called - Example: +class Api: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech - api_instance = UsageApi() - api_instance.custom_server # this is an instance of the class Endpoint - api_instance.custom_server() # this invokes api_instance.custom_server.__call__() - which then invokes the callable functions stored in that endpoint at - api_instance.custom_server.callable or self.callable in this class + Do not edit the class manually. + """ + def __init__(self, api_client: typing.Optional[ApiClient] = None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + @staticmethod + def _verify_typed_dict_inputs_oapg(cls: typing.Type[typing_extensions.TypedDict], data: typing.Dict[str, typing.Any]): """ - return self.callable(self, *args, **kwargs) - - def call_with_http_info(self, **kwargs): - - try: - index = self.api_client.configuration.server_operation_index.get( - self.settings['operation_id'], self.api_client.configuration.server_index - ) if kwargs['_host_index'] is None else kwargs['_host_index'] - server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'], self.api_client.configuration.server_variables + Ensures that: + - required keys are present + - additional properties are not input + - value stored under required keys do not have the value unset + Note: detailed value checking is done in schema classes + """ + missing_required_keys = [] + required_keys_with_unset_values = [] + for required_key in cls.__required_keys__: + if required_key not in data: + missing_required_keys.append(required_key) + continue + value = data[required_key] + if value is unset: + required_keys_with_unset_values.append(required_key) + if missing_required_keys: + raise ApiTypeError( + '{} missing {} required arguments: {}'.format( + cls.__name__, len(missing_required_keys), missing_required_keys + ) + ) + if required_keys_with_unset_values: + raise ApiValueError( + '{} contains invalid unset values for {} required keys: {}'.format( + cls.__name__, len(required_keys_with_unset_values), required_keys_with_unset_values + ) ) - _host = self.api_client.configuration.get_host_from_settings( - index, variables=server_variables, servers=self.settings['servers'] + + disallowed_additional_keys = [] + for key in data: + if key in cls.__required_keys__ or key in cls.__optional_keys__: + continue + disallowed_additional_keys.append(key) + if disallowed_additional_keys: + raise ApiTypeError( + '{} got {} unexpected keyword arguments: {}'.format( + cls.__name__, len(disallowed_additional_keys), disallowed_additional_keys + ) + ) + + def _get_host_oapg( + self, + operation_id: str, + servers: typing.Tuple[typing.Dict[str, str], ...] = tuple(), + host_index: typing.Optional[int] = None + ) -> typing.Optional[str]: + configuration = self.api_client.configuration + try: + if host_index is None: + index = configuration.server_operation_index.get( + operation_id, configuration.server_index + ) + else: + index = host_index + server_variables = configuration.server_operation_variables.get( + operation_id, configuration.server_variables + ) + host = configuration.get_host_from_settings( + index, variables=server_variables, servers=servers ) except IndexError: - if self.settings['servers']: + if servers: raise ApiValueError( "Invalid host index. Must be 0 <= index < %s" % - len(self.settings['servers']) + len(servers) ) - _host = None + host = None + return host - for key, value in kwargs.items(): - if key not in self.params_map['all']: - raise ApiTypeError( - "Got an unexpected parameter '%s'" - " to method `%s`" % - (key, self.settings['operation_id']) - ) - # only throw this nullable ApiValueError if _check_input_type - # is False, if _check_input_type==True we catch this case - # in self.__validate_inputs - if (key not in self.params_map['nullable'] and value is None - and kwargs['_check_input_type'] is False): - raise ApiValueError( - "Value may not be None for non-nullable parameter `%s`" - " when calling `%s`" % - (key, self.settings['operation_id']) - ) - for key in self.params_map['required']: - if key not in kwargs.keys(): - raise ApiValueError( - "Missing the required parameter `%s` when calling " - "`%s`" % (key, self.settings['operation_id']) - ) +class SerializedRequestBody(typing_extensions.TypedDict, total=False): + body: typing.Union[str, bytes] + fields: typing.Tuple[typing.Union[RequestField, typing.Tuple[str, str]], ...] - self.__validate_inputs(kwargs) - params = self.__gather_params(kwargs) +class RequestBody(StyleFormSerializer, JSONDetector): + """ + A request body parameter + content: content_type to MediaType Schema info + """ + __json_encoder = JSONEncoder() - accept_headers_list = self.headers_map['accept'] - if accept_headers_list: - params['header']['Accept'] = self.api_client.select_header_accept( - accept_headers_list) + def __init__( + self, + content: typing.Dict[str, MediaType], + required: bool = False, + ): + self.required = required + if len(content) == 0: + raise ValueError('Invalid value for content, the content dict must have >= 1 entry') + self.content = content - if kwargs.get('_content_type'): - params['header']['Content-Type'] = kwargs['_content_type'] + def __serialize_json( + self, + in_data: typing.Any + ) -> typing.Dict[str, bytes]: + in_data = self.__json_encoder.default(in_data) + json_str = json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode( + "utf-8" + ) + return dict(body=json_str) + + @staticmethod + def __serialize_text_plain(in_data: typing.Any) -> typing.Dict[str, str]: + if isinstance(in_data, frozendict.frozendict): + raise ValueError('Unable to serialize type frozendict.frozendict to text/plain') + elif isinstance(in_data, tuple): + raise ValueError('Unable to serialize type tuple to text/plain') + elif isinstance(in_data, NoneClass): + raise ValueError('Unable to serialize type NoneClass to text/plain') + elif isinstance(in_data, BoolClass): + raise ValueError('Unable to serialize type BoolClass to text/plain') + return dict(body=str(in_data)) + + def __multipart_json_item(self, key: str, value: Schema) -> RequestField: + json_value = self.__json_encoder.default(value) + return RequestField(name=key, data=json.dumps(json_value), headers={'Content-Type': 'application/json'}) + + def __multipart_form_item(self, key: str, value: Schema) -> RequestField: + if isinstance(value, str): + return RequestField(name=key, data=str(value), headers={'Content-Type': 'text/plain'}) + elif isinstance(value, bytes): + return RequestField(name=key, data=value, headers={'Content-Type': 'application/octet-stream'}) + elif isinstance(value, FileIO): + request_field = RequestField( + name=key, + data=value.read(), + filename=os.path.basename(value.name), + headers={'Content-Type': 'application/octet-stream'} + ) + value.close() + return request_field else: - content_type_headers_list = self.headers_map['content_type'] - if content_type_headers_list: - if params['body'] != "": - content_types_list = self.api_client.select_header_content_type( - content_type_headers_list, self.settings['http_method'], - params['body']) - if content_types_list: - params['header']['Content-Type'] = content_types_list + return self.__multipart_json_item(key=key, value=value) - return self.api_client.call_api( - self.settings['endpoint_path'], self.settings['http_method'], - params['path'], - params['query'], - params['header'], - body=params['body'], - post_params=params['form'], - files=params['file'], - response_type=self.settings['response_type'], - auth_settings=self.settings['auth'], - async_req=kwargs['async_req'], - _check_type=kwargs['_check_return_type'], - _return_http_data_only=kwargs['_return_http_data_only'], - _preload_content=kwargs['_preload_content'], - _request_timeout=kwargs['_request_timeout'], - _host=_host, - _request_auths=kwargs['_request_auths'], - collection_formats=params['collection_format']) + def __serialize_multipart_form_data( + self, in_data: Schema + ) -> typing.Dict[str, typing.Tuple[RequestField, ...]]: + if not isinstance(in_data, frozendict.frozendict): + raise ValueError(f'Unable to serialize {in_data} to multipart/form-data because it is not a dict of data') + """ + In a multipart/form-data request body, each schema property, or each element of a schema array property, + takes a section in the payload with an internal header as defined by RFC7578. The serialization strategy + for each property of a multipart/form-data request body can be specified in an associated Encoding Object. + + When passing in multipart types, boundaries MAY be used to separate sections of the content being + transferred – thus, the following default Content-Types are defined for multipart: + + If the (object) property is a primitive, or an array of primitive values, the default Content-Type is text/plain + If the property is complex, or an array of complex values, the default Content-Type is application/json + Question: how is the array of primitives encoded? + If the property is a type: string with a contentEncoding, the default Content-Type is application/octet-stream + """ + fields = [] + for key, value in in_data.items(): + if isinstance(value, tuple): + if value: + # values use explode = True, so the code makes a RequestField for each item with name=key + for item in value: + request_field = self.__multipart_form_item(key=key, value=item) + fields.append(request_field) + else: + # send an empty array as json because exploding will not send it + request_field = self.__multipart_json_item(key=key, value=value) + fields.append(request_field) + else: + request_field = self.__multipart_form_item(key=key, value=value) + fields.append(request_field) + + return dict(fields=tuple(fields)) + + def __serialize_application_octet_stream(self, in_data: BinarySchema) -> typing.Dict[str, bytes]: + if isinstance(in_data, bytes): + return dict(body=in_data) + # FileIO type + result = dict(body=in_data.read()) + in_data.close() + return result + + def __serialize_application_x_www_form_data( + self, in_data: typing.Any + ) -> SerializedRequestBody: + """ + POST submission of form data in body + """ + if not isinstance(in_data, frozendict.frozendict): + raise ValueError( + f'Unable to serialize {in_data} to application/x-www-form-urlencoded because it is not a dict of data') + cast_in_data = self.__json_encoder.default(in_data) + value = self._serialize_form(cast_in_data, name='', explode=True, percent_encode=False) + return dict(body=value) + + def serialize( + self, in_data: typing.Any, content_type: str + ) -> SerializedRequestBody: + """ + If a str is returned then the result will be assigned to data when making the request + If a tuple is returned then the result will be used as fields input in encode_multipart_formdata + Return a tuple of + + The key of the return dict is + - body for application/json + - encode_multipart and fields for multipart/form-data + """ + media_type = self.content[content_type] + if isinstance(in_data, media_type.schema): + cast_in_data = in_data + elif isinstance(in_data, (dict, frozendict.frozendict)) and in_data: + cast_in_data = media_type.schema(**in_data) + else: + cast_in_data = media_type.schema(in_data) + # TODO check for and use encoding if it exists + # and content_type is multipart or application/x-www-form-urlencoded + if self._content_type_is_json(content_type): + return self.__serialize_json(cast_in_data) + elif content_type == 'text/plain': + return self.__serialize_text_plain(cast_in_data) + elif content_type == 'multipart/form-data': + return self.__serialize_multipart_form_data(cast_in_data) + elif content_type == 'application/x-www-form-urlencoded': + return self.__serialize_application_x_www_form_data(cast_in_data) + elif content_type == 'application/octet-stream': + return self.__serialize_application_octet_stream(cast_in_data) + raise NotImplementedError('Serialization has not yet been implemented for {}'.format(content_type)) diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/__init__.py index 21c779b74b..7840f7726f 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/__init__.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/__init__.py @@ -1,17 +1,3 @@ - -# flake8: noqa - -# Import all APIs into this package. -# If you have many APIs here with many many models used in each API this may -# raise a `RecursionError`. -# In order to avoid this, import only the API that you directly need like: -# -# from dynamic_servers.api.usage_api import UsageApi -# -# or import this package, but before doing it, use: -# -# import sys -# sys.setrecursionlimit(n) - -# Import APIs into API package: -from dynamic_servers.api.usage_api import UsageApi +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints then import them from +# tags, paths, or path_to_api, or tag_to_api \ No newline at end of file diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/path_to_api.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/path_to_api.py new file mode 100644 index 0000000000..0ee69ff5af --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/path_to_api.py @@ -0,0 +1,20 @@ +import typing_extensions + +from dynamic_servers.paths import PathValues +from dynamic_servers.apis.paths.default import Default +from dynamic_servers.apis.paths.custom import Custom + +PathToApi = typing_extensions.TypedDict( + 'PathToApi', + { + PathValues.DEFAULT: Default, + PathValues.CUSTOM: Custom, + } +) + +path_to_api = PathToApi( + { + PathValues.DEFAULT: Default, + PathValues.CUSTOM: Custom, + } +) diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/paths/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/paths/__init__.py new file mode 100644 index 0000000000..eabedf0f65 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/paths/__init__.py @@ -0,0 +1,3 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from dynamic_servers.apis.path_to_api import path_to_api diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/paths/custom.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/paths/custom.py new file mode 100644 index 0000000000..3f82f1a0d4 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/paths/custom.py @@ -0,0 +1,7 @@ +from dynamic_servers.paths.custom.get import ApiForget + + +class Custom( + ApiForget, +): + pass diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/paths/default.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/paths/default.py new file mode 100644 index 0000000000..22d4848e13 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/paths/default.py @@ -0,0 +1,7 @@ +from dynamic_servers.paths.default.get import ApiForget + + +class Default( + ApiForget, +): + pass diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/tag_to_api.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/tag_to_api.py new file mode 100644 index 0000000000..fb38df5157 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/tag_to_api.py @@ -0,0 +1,17 @@ +import typing_extensions + +from dynamic_servers.apis.tags import TagValues +from dynamic_servers.apis.tags.usage_api import UsageApi + +TagToApi = typing_extensions.TypedDict( + 'TagToApi', + { + TagValues.USAGE: UsageApi, + } +) + +tag_to_api = TagToApi( + { + TagValues.USAGE: UsageApi, + } +) diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/tags/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/tags/__init__.py new file mode 100644 index 0000000000..2e44715917 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/tags/__init__.py @@ -0,0 +1,9 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from dynamic_servers.apis.tag_to_api import tag_to_api + +import enum + + +class TagValues(str, enum.Enum): + USAGE = "usage" diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/tags/usage_api.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/tags/usage_api.py new file mode 100644 index 0000000000..0c8658ad88 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/apis/tags/usage_api.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from dynamic_servers.paths.custom.get import CustomServer +from dynamic_servers.paths.default.get import DefaultServer + + +class UsageApi( + CustomServer, + DefaultServer, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/configuration.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/configuration.py index 61b3561a82..226e3f7a6e 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/configuration.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/configuration.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Extension with dynamic servers @@ -7,7 +9,6 @@ Generated by: https://openapi-generator.tech """ - import copy import logging import multiprocessing @@ -21,7 +22,8 @@ from dynamic_servers.exceptions import ApiValueError JSON_SCHEMA_VALIDATION_KEYWORDS = { 'multipleOf', 'maximum', 'exclusiveMaximum', 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems' + 'minLength', 'pattern', 'maxItems', 'minItems', + 'uniqueItems', 'maxProperties', 'minProperties', } class Configuration(object): @@ -73,8 +75,6 @@ class Configuration(object): :param server_operation_variables: Mapping from operation ID to a mapping with string values to replace variables in templated server configuration. The validation of enums is performed for variables with defined enum values before. - :param ssl_ca_cert: str - the path to a file of concatenated CA certificates - in PEM format """ @@ -82,13 +82,11 @@ class Configuration(object): def __init__(self, host=None, api_key=None, api_key_prefix=None, - access_token=None, username=None, password=None, discard_unknown_keys=False, disabled_client_side_validations="", server_index=None, server_variables=None, server_operation_index=None, server_operation_variables=None, - ssl_ca_cert=None, ): """Constructor """ @@ -107,7 +105,6 @@ class Configuration(object): """Temp file folder for downloading files """ # Authentication Settings - self.access_token = access_token self.api_key = {} if api_key: self.api_key = api_key @@ -155,7 +152,7 @@ class Configuration(object): Set this to false to skip verifying SSL certificate when calling API from https server. """ - self.ssl_ca_cert = ssl_ca_cert + self.ssl_ca_cert = None """Set this to customize the certificate file to verify the peer. """ self.cert_file = None @@ -179,9 +176,6 @@ class Configuration(object): self.proxy = None """Proxy URL """ - self.no_proxy = None - """bypass proxy for host in the no_proxy list. - """ self.proxy_headers = None """Proxy headers """ @@ -401,7 +395,7 @@ class Configuration(object): "qa-petstore", "dev-petstore" ] - }, + }, 'port': { 'description': "No description provided", 'default_value': "80", @@ -409,8 +403,8 @@ class Configuration(object): "80", "8080" ] + } } - } }, { 'url': "https://localhost:8080/{version}", @@ -424,8 +418,8 @@ class Configuration(object): "v2", "v3" ] + } } - } } ] diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/exceptions.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/exceptions.py index 0939031a89..e6fc3856fc 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/exceptions.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/exceptions.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Extension with dynamic servers @@ -97,12 +99,12 @@ class ApiKeyError(OpenApiException, KeyError): class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() + def __init__(self, status=None, reason=None, api_response: 'dynamic_servers.api_client.ApiResponse' = None): + if api_response: + self.status = api_response.response.status + self.reason = api_response.response.reason + self.body = api_response.response.data + self.headers = api_response.response.getheaders() else: self.status = status self.reason = reason @@ -111,7 +113,7 @@ class ApiException(OpenApiException): def __str__(self): """Custom error messages for exception""" - error_message = "Status Code: {0}\n"\ + error_message = "({0})\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: error_message += "HTTP response headers: {0}\n".format( @@ -123,30 +125,6 @@ class ApiException(OpenApiException): return error_message -class NotFoundException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(NotFoundException, self).__init__(status, reason, http_resp) - - -class UnauthorizedException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(UnauthorizedException, self).__init__(status, reason, http_resp) - - -class ForbiddenException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ForbiddenException, self).__init__(status, reason, http_resp) - - -class ServiceException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ServiceException, self).__init__(status, reason, http_resp) - - def render_path(path_to_item): """Returns a string representation of a path""" result = "" diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py index 38902e7afd..a7da81cfaf 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py @@ -205,7 +205,7 @@ class OpenApiModel(object): if self.get("_spec_property_naming", False): new_inst = cls._new_from_openapi_data() else: - new_inst = cls.__new__(cls) + new_inst = cls.__new__(cls, **self.__dict__) for k, v in self.__dict__.items(): setattr(new_inst, k, deepcopy(v, memo)) diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/models/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/models/__init__.py index 7929e82858..0cb2976e7c 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/models/__init__.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/models/__init__.py @@ -1,3 +1,5 @@ +# coding: utf-8 + # flake8: noqa # import all models into this package diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/__init__.py new file mode 100644 index 0000000000..b2acdc1cdc --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/__init__.py @@ -0,0 +1,10 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from dynamic_servers.apis.path_to_api import path_to_api + +import enum + + +class PathValues(str, enum.Enum): + DEFAULT = "/default" + CUSTOM = "/custom" diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/custom/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/custom/__init__.py new file mode 100644 index 0000000000..fa96c95e72 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/custom/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from dynamic_servers.paths.custom import Api + +from dynamic_servers.paths import PathValues + +path = PathValues.CUSTOM \ No newline at end of file diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/custom/get.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/custom/get.py new file mode 100644 index 0000000000..593d61673a --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/custom/get.py @@ -0,0 +1,297 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from dynamic_servers import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from dynamic_servers import schemas # noqa: F401 + +from . import path + +_servers = ( + { + 'url': "https://{server}.swagger.io:{port}/v2", + 'description': "No description provided", + 'variables': { + 'server': { + 'description': "No description provided", + 'default_value': "custom-petstore", + 'enum_values': [ + "custom-petstore", + "custom-qa-petstore", + "custom-dev-petstore" + ] + }, + 'port': { + 'description': "No description provided", + 'default_value': "8080", + 'enum_values': [ + "80", + "8080" + ] + } + } + }, + { + 'url': "https://localhost:8081/{version}", + 'description': "The local custom server", + 'variables': { + 'version': { + 'description': "No description provided", + 'default_value': "v2", + 'enum_values': [ + "v1", + "v2", + "v3" + ] + } + } + }, + { + 'url': "https://third.example.com/{prefix}", + 'description': "The local custom server", + 'variables': { + 'prefix': { + 'description': "No description provided", + 'default_value': "custom", + } + } + }, +) +SchemaFor200ResponseBodyApplicationJson = schemas.DictSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _custom_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _custom_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _custom_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _custom_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Use custom server + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + host = self._get_host_oapg('custom_server', _servers, host_index) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + host=host, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CustomServer(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def custom_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def custom_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def custom_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def custom_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._custom_server_oapg( + accept_content_types=accept_content_types, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._custom_server_oapg( + accept_content_types=accept_content_types, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/custom/get.pyi b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/custom/get.pyi new file mode 100644 index 0000000000..1fd19d9ea6 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/custom/get.pyi @@ -0,0 +1,242 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from dynamic_servers import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from dynamic_servers import schemas # noqa: F401 + +SchemaFor200ResponseBodyApplicationJson = schemas.DictSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _custom_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _custom_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _custom_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _custom_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Use custom server + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + host = self._get_host_oapg('custom_server', _servers, host_index) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + host=host, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CustomServer(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def custom_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def custom_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def custom_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def custom_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._custom_server_oapg( + accept_content_types=accept_content_types, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._custom_server_oapg( + accept_content_types=accept_content_types, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/default/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/default/__init__.py new file mode 100644 index 0000000000..cb9e2d07e2 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/default/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from dynamic_servers.paths.default import Api + +from dynamic_servers.paths import PathValues + +path = PathValues.DEFAULT \ No newline at end of file diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/default/get.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/default/get.py new file mode 100644 index 0000000000..a4e2fdce47 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/default/get.py @@ -0,0 +1,230 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from dynamic_servers import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from dynamic_servers import schemas # noqa: F401 + +from . import path + +SchemaFor200ResponseBodyApplicationJson = schemas.DictSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _default_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _default_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _default_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _default_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Use default server + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DefaultServer(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def default_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def default_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def default_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def default_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._default_server_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._default_server_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/default/get.pyi b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/default/get.pyi new file mode 100644 index 0000000000..89e925ed40 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/paths/default/get.pyi @@ -0,0 +1,225 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from dynamic_servers import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from dynamic_servers import schemas # noqa: F401 + +SchemaFor200ResponseBodyApplicationJson = schemas.DictSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _default_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _default_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _default_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _default_server_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Use default server + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DefaultServer(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def default_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def default_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def default_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def default_server( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._default_server_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._default_server_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/rest.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/rest.py index 8e5886bb99..d1a0e37cb2 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/rest.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/rest.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Extension with dynamic servers @@ -7,41 +9,21 @@ Generated by: https://openapi-generator.tech """ - -import io -import json import logging -import re import ssl from urllib.parse import urlencode -from urllib.parse import urlparse -from urllib.request import proxy_bypass_environment -import urllib3 -import ipaddress +import typing -from dynamic_servers.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError +import certifi +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from dynamic_servers.exceptions import ApiException, ApiValueError logger = logging.getLogger(__name__) -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.getheader(name, default) - - class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=None): @@ -57,6 +39,13 @@ class RESTClientObject(object): else: cert_reqs = ssl.CERT_NONE + # ca_certs + if configuration.ssl_ca_cert: + ca_certs = configuration.ssl_ca_cert + else: + # if not set certificate file, use Mozilla's root certificates. + ca_certs = certifi.where() + addition_pool_args = {} if configuration.assert_hostname is not None: addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 @@ -74,13 +63,12 @@ class RESTClientObject(object): maxsize = 4 # https pool manager - if configuration.proxy and not should_bypass_proxies( - configuration.host, no_proxy=configuration.no_proxy or ''): + if configuration.proxy: self.pool_manager = urllib3.ProxyManager( num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, + ca_certs=ca_certs, cert_file=configuration.cert_file, key_file=configuration.key_file, proxy_url=configuration.proxy, @@ -92,79 +80,75 @@ class RESTClientObject(object): num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, + ca_certs=ca_certs, cert_file=configuration.cert_file, key_file=configuration.key_file, **addition_pool_args ) - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + def request( + self, + method: str, + url: str, + headers: typing.Optional[HTTPHeaderDict] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, typing.Any], ...]] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> urllib3.HTTPResponse: """Perform requests. :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param body: request body, for other types + :param fields: request parameters for + `application/x-www-form-urlencoded` + or `multipart/form-data` + :param stream: if True, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is False. + :param timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] - if post_params and body: + if fields and body: raise ApiValueError( - "body parameter cannot be used with post_params parameter." + "body parameter cannot be used with fields parameter." ) - post_params = post_params or {} + fields = fields or {} headers = headers or {} - timeout = None - if _request_timeout: - if isinstance(_request_timeout, (int, float)): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) + if timeout: + if isinstance(timeout, (int, float)): # noqa: E501,F821 + timeout = urllib3.Timeout(total=timeout) + elif (isinstance(timeout, tuple) and + len(timeout) == 2): + timeout = urllib3.Timeout(connect=timeout[0], read=timeout[1]) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests - if (method != 'DELETE') and ('Content-Type' not in headers): - headers['Content-Type'] = 'application/json' - if query_params: - url += '?' + urlencode(query_params) - if ('Content-Type' not in headers) or (re.search('json', - headers['Content-Type'], re.IGNORECASE)): - request_body = None - if body is not None: - request_body = json.dumps(body) + if 'Content-Type' not in headers and body is None: r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, + method, + url, + preload_content=not stream, timeout=timeout, - headers=headers) + headers=headers + ) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 r = self.pool_manager.request( method, url, - fields=post_params, + fields=fields, encode_multipart=False, - preload_content=_preload_content, + preload_content=not stream, timeout=timeout, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': @@ -174,9 +158,9 @@ class RESTClientObject(object): del headers['Content-Type'] r = self.pool_manager.request( method, url, - fields=post_params, + fields=fields, encode_multipart=True, - preload_content=_preload_content, + preload_content=not stream, timeout=timeout, headers=headers) # Pass a `string` parameter directly in the body to support @@ -187,7 +171,7 @@ class RESTClientObject(object): r = self.pool_manager.request( method, url, body=request_body, - preload_content=_preload_content, + preload_content=not stream, timeout=timeout, headers=headers) else: @@ -199,154 +183,71 @@ class RESTClientObject(object): # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, - fields=query_params, - preload_content=_preload_content, + preload_content=not stream, timeout=timeout, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) - if _preload_content: - r = RESTResponse(r) - + if not stream: # log response body logger.debug("response body: %s", r.data) - if not 200 <= r.status <= 299: - if r.status == 401: - raise UnauthorizedException(http_resp=r) - - if r.status == 403: - raise ForbiddenException(http_resp=r) - - if r.status == 404: - raise NotFoundException(http_resp=r) - - if 500 <= r.status <= 599: - raise ServiceException(http_resp=r) - - raise ApiException(http_resp=r) - return r - def GET(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): + def GET(self, url, headers=None, stream=False, + timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("GET", url, headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) + stream=stream, + timeout=timeout, + fields=fields) - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): + def HEAD(self, url, headers=None, stream=False, + timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("HEAD", url, headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) + stream=stream, + timeout=timeout, + fields=fields) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): + def OPTIONS(self, url, headers=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("OPTIONS", url, headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + stream=stream, + timeout=timeout, + body=body, fields=fields) - def DELETE(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): + def DELETE(self, url, headers=None, body=None, + stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("DELETE", url, headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + stream=stream, + timeout=timeout, + body=body, fields=fields) - def POST(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): + def POST(self, url, headers=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("POST", url, headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + stream=stream, + timeout=timeout, + body=body, fields=fields) - def PUT(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): + def PUT(self, url, headers=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("PUT", url, headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + stream=stream, + timeout=timeout, + body=body, fields=fields) - def PATCH(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): + def PATCH(self, url, headers=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("PATCH", url, headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - -# end of class RESTClientObject - - -def is_ipv4(target): - """ Test if IPv4 address or not - """ - try: - chk = ipaddress.IPv4Address(target) - return True - except ipaddress.AddressValueError: - return False - - -def in_ipv4net(target, net): - """ Test if target belongs to given IPv4 network - """ - try: - nw = ipaddress.IPv4Network(net) - ip = ipaddress.IPv4Address(target) - if ip in nw: - return True - return False - except ipaddress.AddressValueError: - return False - except ipaddress.NetmaskValueError: - return False - - -def should_bypass_proxies(url, no_proxy=None): - """ Yet another requests.should_bypass_proxies - Test if proxies should not be used for a particular url. - """ - - parsed = urlparse(url) - - # special cases - if parsed.hostname in [None, '']: - return True - - # special cases - if no_proxy in [None, '']: - return False - if no_proxy == '*': - return True - - no_proxy = no_proxy.lower().replace(' ', ''); - entries = ( - host for host in no_proxy.split(',') if host - ) - - if is_ipv4(parsed.hostname): - for item in entries: - if in_ipv4net(parsed.hostname, item): - return True - return proxy_bypass_environment(parsed.hostname, {'no': no_proxy}) + stream=stream, + timeout=timeout, + body=body, fields=fields) diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/schemas.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/schemas.py new file mode 100644 index 0000000000..3678a82945 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/schemas.py @@ -0,0 +1,2462 @@ +# coding: utf-8 + +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from collections import defaultdict +from datetime import date, datetime, timedelta # noqa: F401 +import functools +import decimal +import io +import re +import types +import typing +import uuid + +from dateutil.parser.isoparser import isoparser, _takes_ascii +import frozendict + +from dynamic_servers.exceptions import ( + ApiTypeError, + ApiValueError, +) +from dynamic_servers.configuration import ( + Configuration, +) + + +class Unset(object): + """ + An instance of this class is set as the default value for object type(dict) properties that are optional + When a property has an unset value, that property will not be assigned in the dict + """ + pass + +unset = Unset() + +none_type = type(None) +file_type = io.IOBase + + +class FileIO(io.FileIO): + """ + A class for storing files + Note: this class is not immutable + """ + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader]): + if isinstance(arg, (io.FileIO, io.BufferedReader)): + if arg.closed: + raise ApiValueError('Invalid file state; file is closed and must be open') + arg.close() + inst = super(FileIO, cls).__new__(cls, arg.name) + super(FileIO, inst).__init__(arg.name) + return inst + raise ApiValueError('FileIO must be passed arg which contains the open file') + + def __init__(self, arg: typing.Union[io.FileIO, io.BufferedReader]): + pass + + +def update(d: dict, u: dict): + """ + Adds u to d + Where each dict is defaultdict(set) + """ + if not u: + return d + for k, v in u.items(): + if k not in d: + d[k] = v + else: + d[k] = d[k] | v + + +class ValidationMetadata(frozendict.frozendict): + """ + A class storing metadata that is needed to validate OpenApi Schema payloads + """ + def __new__( + cls, + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), + from_server: bool = False, + configuration: typing.Optional[Configuration] = None, + seen_classes: typing.FrozenSet[typing.Type] = frozenset(), + validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]] = frozendict.frozendict() + ): + """ + Args: + path_to_item: the path to the current data being instantiated. + For {'a': [1]} if the code is handling, 1, then the path is ('args[0]', 'a', 0) + This changes from location to location + from_server: whether or not this data came form the server + True when receiving server data + False when instantiating model with client side data not form the server + This does not change from location to location + configuration: the Configuration instance to use + This is needed because in Configuration: + - one can disable validation checking + This does not change from location to location + seen_classes: when deserializing data that matches multiple schemas, this is used to store + the schemas that have been traversed. This is used to stop processing when a cycle is seen. + This changes from location to location + validated_path_to_schemas: stores the already validated schema classes for a given path location + This does not change from location to location + """ + return super().__new__( + cls, + path_to_item=path_to_item, + from_server=from_server, + configuration=configuration, + seen_classes=seen_classes, + validated_path_to_schemas=validated_path_to_schemas + ) + + def validation_ran_earlier(self, cls: type) -> bool: + validated_schemas = self.validated_path_to_schemas.get(self.path_to_item, set()) + validation_ran_earlier = validated_schemas and cls in validated_schemas + if validation_ran_earlier: + return True + if cls in self.seen_classes: + return True + return False + + @property + def path_to_item(self) -> typing.Tuple[typing.Union[str, int], ...]: + return self.get('path_to_item') + + @property + def from_server(self) -> bool: + return self.get('from_server') + + @property + def configuration(self) -> typing.Optional[Configuration]: + return self.get('configuration') + + @property + def seen_classes(self) -> typing.FrozenSet[typing.Type]: + return self.get('seen_classes') + + @property + def validated_path_to_schemas(self) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]]: + return self.get('validated_path_to_schemas') + + +class Singleton: + """ + Enums and singletons are the same + The same instance is returned for a given key of (cls, arg) + """ + _instances = {} + + def __new__(cls, arg: typing.Any, **kwargs): + """ + cls base classes: BoolClass, NoneClass, str, decimal.Decimal + The 3rd key is used in the tuple below for a corner case where an enum contains integer 1 + However 1.0 can also be ingested into that enum schema because 1.0 == 1 and + Decimal('1.0') == Decimal('1') + But if we omitted the 3rd value in the key, then Decimal('1.0') would be stored as Decimal('1') + and json serializing that instance would be '1' rather than the expected '1.0' + Adding the 3rd value, the str of arg ensures that 1.0 -> Decimal('1.0') which is serialized as 1.0 + """ + key = (cls, arg, str(arg)) + if key not in cls._instances: + if isinstance(arg, (none_type, bool, BoolClass, NoneClass)): + inst = super().__new__(cls) + cls._instances[key] = inst + else: + cls._instances[key] = super().__new__(cls, arg) + return cls._instances[key] + + def __repr__(self): + if isinstance(self, NoneClass): + return f'<{self.__class__.__name__}: None>' + elif isinstance(self, BoolClass): + if bool(self): + return f'<{self.__class__.__name__}: True>' + return f'<{self.__class__.__name__}: False>' + return f'<{self.__class__.__name__}: {super().__repr__()}>' + + +class classproperty: + + def __init__(self, fget): + self.fget = fget + + def __get__(self, owner_self, owner_cls): + return self.fget(owner_cls) + + +class NoneClass(Singleton): + @classproperty + def NONE(cls): + return cls(None) + + def __bool__(self) -> bool: + return False + + +class BoolClass(Singleton): + @classproperty + def TRUE(cls): + return cls(True) + + @classproperty + def FALSE(cls): + return cls(False) + + @functools.lru_cache() + def __bool__(self) -> bool: + for key, instance in self._instances.items(): + if self is instance: + return bool(key[1]) + raise ValueError('Unable to find the boolean value of this instance') + + +class MetaOapgTyped: + exclusive_maximum: typing.Union[int, float] + inclusive_maximum: typing.Union[int, float] + exclusive_minimum: typing.Union[int, float] + inclusive_minimum: typing.Union[int, float] + max_items: int + min_items: int + discriminator: typing.Dict[str, typing.Dict[str, typing.Type['Schema']]] + + + class properties: + # to hold object properties + pass + + additional_properties: typing.Optional[typing.Type['Schema']] + max_properties: int + min_properties: int + all_of: typing.List[typing.Type['Schema']] + one_of: typing.List[typing.Type['Schema']] + any_of: typing.List[typing.Type['Schema']] + not_schema: typing.Type['Schema'] + max_length: int + min_length: int + items: typing.Type['Schema'] + + +class Schema: + """ + the base class of all swagger/openapi schemas/models + """ + __inheritable_primitive_types_set = {decimal.Decimal, str, tuple, frozendict.frozendict, FileIO, bytes, BoolClass, NoneClass} + _types: typing.Set[typing.Type] + MetaOapg = MetaOapgTyped + + @staticmethod + def __get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed""" + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return "is {0}".format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + @staticmethod + def _get_class_oapg(item_cls: typing.Union[types.FunctionType, staticmethod, typing.Type['Schema']]) -> typing.Type['Schema']: + if isinstance(item_cls, types.FunctionType): + # referenced schema + return item_cls() + elif isinstance(item_cls, staticmethod): + # referenced schema + return item_cls.__func__() + return item_cls + + @classmethod + def __type_error_message( + cls, var_value=None, var_name=None, valid_classes=None, key_type=None + ): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a tuple + """ + key_or_value = "value" + if key_type: + key_or_value = "key" + valid_classes_phrase = cls.__get_valid_classes_phrase(valid_classes) + msg = "Invalid type. Required {1} type {2} and " "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + return msg + + @classmethod + def __get_type_error(cls, var_value, path_to_item, valid_classes, key_type=False): + error_msg = cls.__type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type, + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type, + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + Schema _validate_oapg + All keyword validation except for type checking was done in calling stack frames + If those validations passed, the validated classes are collected in path_to_schemas + + Returns: + path_to_schemas: a map of path to schemas + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + base_class = type(arg) + if base_class not in cls._types: + raise cls.__get_type_error( + arg, + validation_metadata.path_to_item, + cls._types, + key_type=False, + ) + + path_to_schemas = {validation_metadata.path_to_item: set()} + path_to_schemas[validation_metadata.path_to_item].add(cls) + path_to_schemas[validation_metadata.path_to_item].add(base_class) + return path_to_schemas + + @staticmethod + def _process_schema_classes_oapg( + schema_classes: typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]] + ): + """ + Processes and mutates schema_classes + If a SomeSchema is a subclass of DictSchema then remove DictSchema because it is already included + """ + if len(schema_classes) < 2: + return + if len(schema_classes) > 2 and UnsetAnyTypeSchema in schema_classes: + schema_classes.remove(UnsetAnyTypeSchema) + x_schema = schema_type_classes & schema_classes + if not x_schema: + return + x_schema = x_schema.pop() + if any(c is not x_schema and issubclass(c, x_schema) for c in schema_classes): + # needed to not have a mro error in get_new_class + schema_classes.remove(x_schema) + + @classmethod + def __get_new_cls( + cls, + arg, + validation_metadata: ValidationMetadata + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']]: + """ + Make a new dynamic class and return an instance of that class + We are making an instance of cls, but instead of making cls + make a new class, new_cls + which includes dynamic bases including cls + return an instance of that new class + + Dict property + List Item Assignment Use cases: + 1. value is NOT an instance of the required schema class + the value is validated by _validate_oapg + _validate_oapg returns a key value pair + where the key is the path to the item, and the value will be the required manufactured class + made out of the matching schemas + 2. value is an instance of the the correct schema type + the value is NOT validated by _validate_oapg, _validate_oapg only checks that the instance is of the correct schema type + for this value, _validate_oapg does NOT return an entry for it in _path_to_schemas + and in list/dict _get_items_oapg,_get_properties_oapg the value will be directly assigned + because value is of the correct type, and validation was run earlier when the instance was created + """ + _path_to_schemas = {} + if validation_metadata.validated_path_to_schemas: + update(_path_to_schemas, validation_metadata.validated_path_to_schemas) + if not validation_metadata.validation_ran_earlier(cls): + other_path_to_schemas = cls._validate_oapg(arg, validation_metadata=validation_metadata) + update(_path_to_schemas, other_path_to_schemas) + # loop through it make a new class for each entry + # do not modify the returned result because it is cached and we would be modifying the cached value + path_to_schemas = {} + for path, schema_classes in _path_to_schemas.items(): + """ + Use cases + 1. N number of schema classes + enum + type != bool/None, classes in path_to_schemas: tuple/frozendict.frozendict/str/Decimal/bytes/FileIo + needs Singleton added + 2. N number of schema classes + enum + type == bool/None, classes in path_to_schemas: BoolClass/NoneClass + Singleton already added + 3. N number of schema classes, classes in path_to_schemas: BoolClass/NoneClass/tuple/frozendict.frozendict/str/Decimal/bytes/FileIo + """ + cls._process_schema_classes_oapg(schema_classes) + enum_schema = any( + issubclass(this_cls, EnumBase) for this_cls in schema_classes) + inheritable_primitive_type = schema_classes.intersection(cls.__inheritable_primitive_types_set) + chosen_schema_classes = schema_classes - inheritable_primitive_type + suffix = tuple(inheritable_primitive_type) + if enum_schema and suffix[0] not in {NoneClass, BoolClass}: + suffix = (Singleton,) + suffix + + used_classes = tuple(sorted(chosen_schema_classes, key=lambda a_cls: a_cls.__name__)) + suffix + mfg_cls = get_new_class(class_name='DynamicSchema', bases=used_classes) + path_to_schemas[path] = mfg_cls + + return path_to_schemas + + @classmethod + def _get_new_instance_without_conversion_oapg( + cls, + arg: typing.Any, + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + # We have a Dynamic class and we are making an instance of it + if issubclass(cls, frozendict.frozendict) and issubclass(cls, DictBase): + properties = cls._get_properties_oapg(arg, path_to_item, path_to_schemas) + return super(Schema, cls).__new__(cls, properties) + elif issubclass(cls, tuple) and issubclass(cls, ListBase): + items = cls._get_items_oapg(arg, path_to_item, path_to_schemas) + return super(Schema, cls).__new__(cls, items) + """ + str = openapi str, date, and datetime + decimal.Decimal = openapi int and float + FileIO = openapi binary type and the user inputs a file + bytes = openapi binary type and the user inputs bytes + """ + return super(Schema, cls).__new__(cls, arg) + + @classmethod + def from_openapi_data_oapg( + cls, + arg: typing.Union[ + str, + date, + datetime, + int, + float, + decimal.Decimal, + bool, + None, + 'Schema', + dict, + frozendict.frozendict, + tuple, + list, + io.FileIO, + io.BufferedReader, + bytes + ], + _configuration: typing.Optional[Configuration] + ): + """ + Schema from_openapi_data_oapg + """ + from_server = True + validated_path_to_schemas = {} + arg = cast_to_allowed_types(arg, from_server, validated_path_to_schemas) + validation_metadata = ValidationMetadata( + from_server=from_server, configuration=_configuration, validated_path_to_schemas=validated_path_to_schemas) + path_to_schemas = cls.__get_new_cls(arg, validation_metadata) + new_cls = path_to_schemas[validation_metadata.path_to_item] + new_inst = new_cls._get_new_instance_without_conversion_oapg( + arg, + validation_metadata.path_to_item, + path_to_schemas + ) + return new_inst + + @staticmethod + def __get_input_dict(*args, **kwargs) -> frozendict.frozendict: + input_dict = {} + if args and isinstance(args[0], (dict, frozendict.frozendict)): + input_dict.update(args[0]) + if kwargs: + input_dict.update(kwargs) + return frozendict.frozendict(input_dict) + + @staticmethod + def __remove_unsets(kwargs): + return {key: val for key, val in kwargs.items() if val is not unset} + + def __new__(cls, *args: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], _configuration: typing.Optional[Configuration] = None, **kwargs: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset]): + """ + Schema __new__ + + Args: + args (int/float/decimal.Decimal/str/list/tuple/dict/frozendict.frozendict/bool/None): the value + kwargs (str, int/float/decimal.Decimal/str/list/tuple/dict/frozendict.frozendict/bool/None): dict values + _configuration: contains the Configuration that enables json schema validation keywords + like minItems, minLength etc + + Note: double underscores are used here because pycharm thinks that these variables + are instance properties if they are named normally :( + """ + __kwargs = cls.__remove_unsets(kwargs) + if not args and not __kwargs: + raise TypeError( + 'No input given. args or kwargs must be given.' + ) + if not __kwargs and args and not isinstance(args[0], dict): + __arg = args[0] + else: + __arg = cls.__get_input_dict(*args, **__kwargs) + __from_server = False + __validated_path_to_schemas = {} + __arg = cast_to_allowed_types( + __arg, __from_server, __validated_path_to_schemas) + __validation_metadata = ValidationMetadata( + configuration=_configuration, from_server=__from_server, validated_path_to_schemas=__validated_path_to_schemas) + __path_to_schemas = cls.__get_new_cls(__arg, __validation_metadata) + __new_cls = __path_to_schemas[__validation_metadata.path_to_item] + return __new_cls._get_new_instance_without_conversion_oapg( + __arg, + __validation_metadata.path_to_item, + __path_to_schemas + ) + + def __init__( + self, + *args: typing.Union[ + dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], + _configuration: typing.Optional[Configuration] = None, + **kwargs: typing.Union[ + dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset + ] + ): + """ + this is needed to fix 'Unexpected argument' warning in pycharm + this code does nothing because all Schema instances are immutable + this means that all input data is passed into and used in new, and after the new instance is made + no new attributes are assigned and init is not used + """ + pass + +""" +import itertools +data_types = ('None', 'FrozenDict', 'Tuple', 'Str', 'Decimal', 'Bool') +type_to_cls = { + 'None': 'NoneClass', + 'FrozenDict': 'frozendict.frozendict', + 'Tuple': 'tuple', + 'Str': 'str', + 'Decimal': 'decimal.Decimal', + 'Bool': 'BoolClass' +} +cls_tuples = [v for v in itertools.combinations(data_types, 5)] +typed_classes = [f"class {''.join(cls_tuple)}Mixin({', '.join(type_to_cls[typ] for typ in cls_tuple)}):\n pass" for cls_tuple in cls_tuples] +for cls in typed_classes: + print(cls) +object_classes = [f"{''.join(cls_tuple)}Mixin = object" for cls_tuple in cls_tuples] +for cls in object_classes: + print(cls) +""" +if typing.TYPE_CHECKING: + # qty 1 + NoneMixin = NoneClass + FrozenDictMixin = frozendict.frozendict + TupleMixin = tuple + StrMixin = str + DecimalMixin = decimal.Decimal + BoolMixin = BoolClass + BytesMixin = bytes + FileMixin = FileIO + # qty 2 + class BinaryMixin(bytes, FileIO): + pass + class NoneFrozenDictMixin(NoneClass, frozendict.frozendict): + pass + class NoneTupleMixin(NoneClass, tuple): + pass + class NoneStrMixin(NoneClass, str): + pass + class NoneDecimalMixin(NoneClass, decimal.Decimal): + pass + class NoneBoolMixin(NoneClass, BoolClass): + pass + class FrozenDictTupleMixin(frozendict.frozendict, tuple): + pass + class FrozenDictStrMixin(frozendict.frozendict, str): + pass + class FrozenDictDecimalMixin(frozendict.frozendict, decimal.Decimal): + pass + class FrozenDictBoolMixin(frozendict.frozendict, BoolClass): + pass + class TupleStrMixin(tuple, str): + pass + class TupleDecimalMixin(tuple, decimal.Decimal): + pass + class TupleBoolMixin(tuple, BoolClass): + pass + class StrDecimalMixin(str, decimal.Decimal): + pass + class StrBoolMixin(str, BoolClass): + pass + class DecimalBoolMixin(decimal.Decimal, BoolClass): + pass + # qty 3 + class NoneFrozenDictTupleMixin(NoneClass, frozendict.frozendict, tuple): + pass + class NoneFrozenDictStrMixin(NoneClass, frozendict.frozendict, str): + pass + class NoneFrozenDictDecimalMixin(NoneClass, frozendict.frozendict, decimal.Decimal): + pass + class NoneFrozenDictBoolMixin(NoneClass, frozendict.frozendict, BoolClass): + pass + class NoneTupleStrMixin(NoneClass, tuple, str): + pass + class NoneTupleDecimalMixin(NoneClass, tuple, decimal.Decimal): + pass + class NoneTupleBoolMixin(NoneClass, tuple, BoolClass): + pass + class NoneStrDecimalMixin(NoneClass, str, decimal.Decimal): + pass + class NoneStrBoolMixin(NoneClass, str, BoolClass): + pass + class NoneDecimalBoolMixin(NoneClass, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrMixin(frozendict.frozendict, tuple, str): + pass + class FrozenDictTupleDecimalMixin(frozendict.frozendict, tuple, decimal.Decimal): + pass + class FrozenDictTupleBoolMixin(frozendict.frozendict, tuple, BoolClass): + pass + class FrozenDictStrDecimalMixin(frozendict.frozendict, str, decimal.Decimal): + pass + class FrozenDictStrBoolMixin(frozendict.frozendict, str, BoolClass): + pass + class FrozenDictDecimalBoolMixin(frozendict.frozendict, decimal.Decimal, BoolClass): + pass + class TupleStrDecimalMixin(tuple, str, decimal.Decimal): + pass + class TupleStrBoolMixin(tuple, str, BoolClass): + pass + class TupleDecimalBoolMixin(tuple, decimal.Decimal, BoolClass): + pass + class StrDecimalBoolMixin(str, decimal.Decimal, BoolClass): + pass + # qty 4 + class NoneFrozenDictTupleStrMixin(NoneClass, frozendict.frozendict, tuple, str): + pass + class NoneFrozenDictTupleDecimalMixin(NoneClass, frozendict.frozendict, tuple, decimal.Decimal): + pass + class NoneFrozenDictTupleBoolMixin(NoneClass, frozendict.frozendict, tuple, BoolClass): + pass + class NoneFrozenDictStrDecimalMixin(NoneClass, frozendict.frozendict, str, decimal.Decimal): + pass + class NoneFrozenDictStrBoolMixin(NoneClass, frozendict.frozendict, str, BoolClass): + pass + class NoneFrozenDictDecimalBoolMixin(NoneClass, frozendict.frozendict, decimal.Decimal, BoolClass): + pass + class NoneTupleStrDecimalMixin(NoneClass, tuple, str, decimal.Decimal): + pass + class NoneTupleStrBoolMixin(NoneClass, tuple, str, BoolClass): + pass + class NoneTupleDecimalBoolMixin(NoneClass, tuple, decimal.Decimal, BoolClass): + pass + class NoneStrDecimalBoolMixin(NoneClass, str, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrDecimalMixin(frozendict.frozendict, tuple, str, decimal.Decimal): + pass + class FrozenDictTupleStrBoolMixin(frozendict.frozendict, tuple, str, BoolClass): + pass + class FrozenDictTupleDecimalBoolMixin(frozendict.frozendict, tuple, decimal.Decimal, BoolClass): + pass + class FrozenDictStrDecimalBoolMixin(frozendict.frozendict, str, decimal.Decimal, BoolClass): + pass + class TupleStrDecimalBoolMixin(tuple, str, decimal.Decimal, BoolClass): + pass + # qty 5 + class NoneFrozenDictTupleStrDecimalMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal): + pass + class NoneFrozenDictTupleStrBoolMixin(NoneClass, frozendict.frozendict, tuple, str, BoolClass): + pass + class NoneFrozenDictTupleDecimalBoolMixin(NoneClass, frozendict.frozendict, tuple, decimal.Decimal, BoolClass): + pass + class NoneFrozenDictStrDecimalBoolMixin(NoneClass, frozendict.frozendict, str, decimal.Decimal, BoolClass): + pass + class NoneTupleStrDecimalBoolMixin(NoneClass, tuple, str, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrDecimalBoolMixin(frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass): + pass + # qty 6 + class NoneFrozenDictTupleStrDecimalBoolMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass): + pass + # qty 8 + class NoneFrozenDictTupleStrDecimalBoolFileBytesMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass, FileIO, bytes): + pass +else: + # qty 1 + class NoneMixin: + _types = {NoneClass} + class FrozenDictMixin: + _types = {frozendict.frozendict} + class TupleMixin: + _types = {tuple} + class StrMixin: + _types = {str} + class DecimalMixin: + _types = {decimal.Decimal} + class BoolMixin: + _types = {BoolClass} + class BytesMixin: + _types = {bytes} + class FileMixin: + _types = {FileIO} + # qty 2 + class BinaryMixin: + _types = {bytes, FileIO} + class NoneFrozenDictMixin: + _types = {NoneClass, frozendict.frozendict} + class NoneTupleMixin: + _types = {NoneClass, tuple} + class NoneStrMixin: + _types = {NoneClass, str} + class NoneDecimalMixin: + _types = {NoneClass, decimal.Decimal} + class NoneBoolMixin: + _types = {NoneClass, BoolClass} + class FrozenDictTupleMixin: + _types = {frozendict.frozendict, tuple} + class FrozenDictStrMixin: + _types = {frozendict.frozendict, str} + class FrozenDictDecimalMixin: + _types = {frozendict.frozendict, decimal.Decimal} + class FrozenDictBoolMixin: + _types = {frozendict.frozendict, BoolClass} + class TupleStrMixin: + _types = {tuple, str} + class TupleDecimalMixin: + _types = {tuple, decimal.Decimal} + class TupleBoolMixin: + _types = {tuple, BoolClass} + class StrDecimalMixin: + _types = {str, decimal.Decimal} + class StrBoolMixin: + _types = {str, BoolClass} + class DecimalBoolMixin: + _types = {decimal.Decimal, BoolClass} + # qty 3 + class NoneFrozenDictTupleMixin: + _types = {NoneClass, frozendict.frozendict, tuple} + class NoneFrozenDictStrMixin: + _types = {NoneClass, frozendict.frozendict, str} + class NoneFrozenDictDecimalMixin: + _types = {NoneClass, frozendict.frozendict, decimal.Decimal} + class NoneFrozenDictBoolMixin: + _types = {NoneClass, frozendict.frozendict, BoolClass} + class NoneTupleStrMixin: + _types = {NoneClass, tuple, str} + class NoneTupleDecimalMixin: + _types = {NoneClass, tuple, decimal.Decimal} + class NoneTupleBoolMixin: + _types = {NoneClass, tuple, BoolClass} + class NoneStrDecimalMixin: + _types = {NoneClass, str, decimal.Decimal} + class NoneStrBoolMixin: + _types = {NoneClass, str, BoolClass} + class NoneDecimalBoolMixin: + _types = {NoneClass, decimal.Decimal, BoolClass} + class FrozenDictTupleStrMixin: + _types = {frozendict.frozendict, tuple, str} + class FrozenDictTupleDecimalMixin: + _types = {frozendict.frozendict, tuple, decimal.Decimal} + class FrozenDictTupleBoolMixin: + _types = {frozendict.frozendict, tuple, BoolClass} + class FrozenDictStrDecimalMixin: + _types = {frozendict.frozendict, str, decimal.Decimal} + class FrozenDictStrBoolMixin: + _types = {frozendict.frozendict, str, BoolClass} + class FrozenDictDecimalBoolMixin: + _types = {frozendict.frozendict, decimal.Decimal, BoolClass} + class TupleStrDecimalMixin: + _types = {tuple, str, decimal.Decimal} + class TupleStrBoolMixin: + _types = {tuple, str, BoolClass} + class TupleDecimalBoolMixin: + _types = {tuple, decimal.Decimal, BoolClass} + class StrDecimalBoolMixin: + _types = {str, decimal.Decimal, BoolClass} + # qty 4 + class NoneFrozenDictTupleStrMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str} + class NoneFrozenDictTupleDecimalMixin: + _types = {NoneClass, frozendict.frozendict, tuple, decimal.Decimal} + class NoneFrozenDictTupleBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, BoolClass} + class NoneFrozenDictStrDecimalMixin: + _types = {NoneClass, frozendict.frozendict, str, decimal.Decimal} + class NoneFrozenDictStrBoolMixin: + _types = {NoneClass, frozendict.frozendict, str, BoolClass} + class NoneFrozenDictDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, decimal.Decimal, BoolClass} + class NoneTupleStrDecimalMixin: + _types = {NoneClass, tuple, str, decimal.Decimal} + class NoneTupleStrBoolMixin: + _types = {NoneClass, tuple, str, BoolClass} + class NoneTupleDecimalBoolMixin: + _types = {NoneClass, tuple, decimal.Decimal, BoolClass} + class NoneStrDecimalBoolMixin: + _types = {NoneClass, str, decimal.Decimal, BoolClass} + class FrozenDictTupleStrDecimalMixin: + _types = {frozendict.frozendict, tuple, str, decimal.Decimal} + class FrozenDictTupleStrBoolMixin: + _types = {frozendict.frozendict, tuple, str, BoolClass} + class FrozenDictTupleDecimalBoolMixin: + _types = {frozendict.frozendict, tuple, decimal.Decimal, BoolClass} + class FrozenDictStrDecimalBoolMixin: + _types = {frozendict.frozendict, str, decimal.Decimal, BoolClass} + class TupleStrDecimalBoolMixin: + _types = {tuple, str, decimal.Decimal, BoolClass} + # qty 5 + class NoneFrozenDictTupleStrDecimalMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal} + class NoneFrozenDictTupleStrBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, BoolClass} + class NoneFrozenDictTupleDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, decimal.Decimal, BoolClass} + class NoneFrozenDictStrDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, str, decimal.Decimal, BoolClass} + class NoneTupleStrDecimalBoolMixin: + _types = {NoneClass, tuple, str, decimal.Decimal, BoolClass} + class FrozenDictTupleStrDecimalBoolMixin: + _types = {frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass} + # qty 6 + class NoneFrozenDictTupleStrDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass} + # qty 8 + class NoneFrozenDictTupleStrDecimalBoolFileBytesMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass, FileIO, bytes} + + +class ValidatorBase: + @staticmethod + def _is_json_validation_enabled_oapg(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + Note: the suffix _oapg stands for openapi python (experimental) generator and + it has been added to prevent collisions with other methods and properties + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + @staticmethod + def _raise_validation_errror_message_oapg(value, constraint_msg, constraint_value, path_to_item, additional_txt=""): + raise ApiValueError( + "Invalid value `{value}`, {constraint_msg} `{constraint_value}`{additional_txt} at {path_to_item}".format( + value=value, + constraint_msg=constraint_msg, + constraint_value=constraint_value, + additional_txt=additional_txt, + path_to_item=path_to_item, + ) + ) + + +class EnumBase: + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + EnumBase _validate_oapg + Validates that arg is in the enum's allowed values + """ + try: + cls.MetaOapg.enum_value_to_name[arg] + except KeyError: + raise ApiValueError("Invalid value {} passed in to {}, allowed_values={}".format(arg, cls, cls.MetaOapg.enum_value_to_name.keys())) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class BoolBase: + def is_true_oapg(self) -> bool: + """ + A replacement for x is True + True if the instance is a BoolClass True Singleton + """ + if not issubclass(self.__class__, BoolClass): + return False + return bool(self) + + def is_false_oapg(self) -> bool: + """ + A replacement for x is False + True if the instance is a BoolClass False Singleton + """ + if not issubclass(self.__class__, BoolClass): + return False + return bool(self) is False + + +class NoneBase: + def is_none_oapg(self) -> bool: + """ + A replacement for x is None + True if the instance is a NoneClass None Singleton + """ + if issubclass(self.__class__, NoneClass): + return True + return False + + +class StrBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @property + def as_str_oapg(self) -> str: + return self + + @property + def as_date_oapg(self) -> date: + raise Exception('not implemented') + + @property + def as_datetime_oapg(self) -> datetime: + raise Exception('not implemented') + + @property + def as_decimal_oapg(self) -> decimal.Decimal: + raise Exception('not implemented') + + @property + def as_uuid_oapg(self) -> uuid.UUID: + raise Exception('not implemented') + + @classmethod + def __check_str_validations( + cls, + arg: str, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxLength', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_length') and + len(arg) > cls.MetaOapg.max_length): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="length must be less than or equal to", + constraint_value=cls.MetaOapg.max_length, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minLength', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_length') and + len(arg) < cls.MetaOapg.min_length): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="length must be greater than or equal to", + constraint_value=cls.MetaOapg.min_length, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('pattern', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'regex')): + for regex_dict in cls.MetaOapg.regex: + flags = regex_dict.get('flags', 0) + if not re.search(regex_dict['pattern'], arg, flags=flags): + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must match regular expression", + constraint_value=regex_dict['pattern'], + path_to_item=validation_metadata.path_to_item, + additional_txt=" with flags=`{}`".format(flags) + ) + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must match regular expression", + constraint_value=regex_dict['pattern'], + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + StrBase _validate_oapg + Validates that validations pass + """ + if isinstance(arg, str): + cls.__check_str_validations(arg, validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class UUIDBase: + @property + @functools.lru_cache() + def as_uuid_oapg(self) -> uuid.UUID: + return uuid.UUID(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + uuid.UUID(arg) + return True + except ValueError: + raise ApiValueError( + "Invalid value '{}' for type UUID at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: typing.Optional[ValidationMetadata] = None, + ): + """ + UUIDBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class CustomIsoparser(isoparser): + + @_takes_ascii + def parse_isodatetime(self, dt_str): + components, pos = self._parse_isodate(dt_str) + if len(dt_str) > pos: + if self._sep is None or dt_str[pos:pos + 1] == self._sep: + components += self._parse_isotime(dt_str[pos + 1:]) + else: + raise ValueError('String contains unknown ISO components') + + if len(components) > 3 and components[3] == 24: + components[3] = 0 + return datetime(*components) + timedelta(days=1) + + if len(components) <= 3: + raise ValueError('Value is not a datetime') + + return datetime(*components) + + @_takes_ascii + def parse_isodate(self, datestr): + components, pos = self._parse_isodate(datestr) + + if len(datestr) > pos: + raise ValueError('String contains invalid time components') + + if len(components) > 3: + raise ValueError('String contains invalid time components') + + return date(*components) + + +DEFAULT_ISOPARSER = CustomIsoparser() + + +class DateBase: + @property + @functools.lru_cache() + def as_date_oapg(self) -> date: + return DEFAULT_ISOPARSER.parse_isodate(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + DEFAULT_ISOPARSER.parse_isodate(arg) + return True + except ValueError: + raise ApiValueError( + "Value does not conform to the required ISO-8601 date format. " + "Invalid value '{}' for type date at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: typing.Optional[ValidationMetadata] = None, + ): + """ + DateBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class DateTimeBase: + @property + @functools.lru_cache() + def as_datetime_oapg(self) -> datetime: + return DEFAULT_ISOPARSER.parse_isodatetime(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + DEFAULT_ISOPARSER.parse_isodatetime(arg) + return True + except ValueError: + raise ApiValueError( + "Value does not conform to the required ISO-8601 datetime format. " + "Invalid value '{}' for type datetime at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DateTimeBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class DecimalBase: + """ + A class for storing decimals that are sent over the wire as strings + These schemas must remain based on StrBase rather than NumberBase + because picking base classes must be deterministic + """ + + @property + @functools.lru_cache() + def as_decimal_oapg(self) -> decimal.Decimal: + return decimal.Decimal(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + decimal.Decimal(arg) + return True + except decimal.InvalidOperation: + raise ApiValueError( + "Value cannot be converted to a decimal. " + "Invalid value '{}' for type decimal at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DecimalBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class NumberBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @property + def as_int_oapg(self) -> int: + try: + return self._as_int + except AttributeError: + """ + Note: for some numbers like 9.0 they could be represented as an + integer but our code chooses to store them as + >>> Decimal('9.0').as_tuple() + DecimalTuple(sign=0, digits=(9, 0), exponent=-1) + so we can tell that the value came from a float and convert it back to a float + during later serialization + """ + if self.as_tuple().exponent < 0: + # this could be represented as an integer but should be represented as a float + # because that's what it was serialized from + raise ApiValueError(f'{self} is not an integer') + self._as_int = int(self) + return self._as_int + + @property + def as_float_oapg(self) -> float: + try: + return self._as_float + except AttributeError: + if self.as_tuple().exponent >= 0: + raise ApiValueError(f'{self} is not an float') + self._as_float = float(self) + return self._as_float + + @classmethod + def __check_numeric_validations( + cls, + arg, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if cls._is_json_validation_enabled_oapg('multipleOf', + validation_metadata.configuration) and hasattr(cls.MetaOapg, 'multiple_of'): + multiple_of_value = cls.MetaOapg.multiple_of + if (not (float(arg) / multiple_of_value).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="value must be a multiple of", + constraint_value=multiple_of_value, + path_to_item=validation_metadata.path_to_item + ) + + checking_max_or_min_values = any( + hasattr(cls.MetaOapg, validation_key) for validation_key in { + 'exclusive_maximum', + 'inclusive_maximum', + 'exclusive_minimum', + 'inclusive_minimum', + } + ) + if not checking_max_or_min_values: + return + + if (cls._is_json_validation_enabled_oapg('exclusiveMaximum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'exclusive_maximum') and + arg >= cls.MetaOapg.exclusive_maximum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value less than", + constraint_value=cls.MetaOapg.exclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('maximum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'inclusive_maximum') and + arg > cls.MetaOapg.inclusive_maximum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value less than or equal to", + constraint_value=cls.MetaOapg.inclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('exclusiveMinimum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'exclusive_minimum') and + arg <= cls.MetaOapg.exclusive_minimum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value greater than", + constraint_value=cls.MetaOapg.exclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minimum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'inclusive_minimum') and + arg < cls.MetaOapg.inclusive_minimum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value greater than or equal to", + constraint_value=cls.MetaOapg.inclusive_minimum, + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + NumberBase _validate_oapg + Validates that validations pass + """ + if isinstance(arg, decimal.Decimal): + cls.__check_numeric_validations(arg, validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class ListBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @classmethod + def __validate_items(cls, list_items, validation_metadata: ValidationMetadata): + """ + Ensures that: + - values passed in for items are valid + Exceptions will be raised if: + - invalid arguments were passed in + + Args: + list_items: the input list of items + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + + # if we have definitions for an items schema, use it + # otherwise accept anything + item_cls = getattr(cls.MetaOapg, 'items', UnsetAnyTypeSchema) + item_cls = cls._get_class_oapg(item_cls) + path_to_schemas = {} + for i, value in enumerate(list_items): + item_validation_metadata = ValidationMetadata( + from_server=validation_metadata.from_server, + configuration=validation_metadata.configuration, + path_to_item=validation_metadata.path_to_item+(i,), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if item_validation_metadata.validation_ran_earlier(item_cls): + continue + other_path_to_schemas = item_cls._validate_oapg( + value, validation_metadata=item_validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __check_tuple_validations( + cls, arg, + validation_metadata: ValidationMetadata): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_items') and + len(arg) > cls.MetaOapg.max_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of items must be less than or equal to", + constraint_value=cls.MetaOapg.max_items, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_items') and + len(arg) < cls.MetaOapg.min_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of items must be greater than or equal to", + constraint_value=cls.MetaOapg.min_items, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('uniqueItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'unique_items') and cls.MetaOapg.unique_items and arg): + unique_items = set(arg) + if len(arg) > len(unique_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="duplicate items were found, and the tuple must not contain duplicates because", + constraint_value='unique_items==True', + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + ListBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + if isinstance(arg, tuple): + cls.__check_tuple_validations(arg, validation_metadata) + _path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + if not isinstance(arg, tuple): + return _path_to_schemas + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + other_path_to_schemas = cls.__validate_items(arg, validation_metadata=updated_vm) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_items_oapg( + cls: 'Schema', + arg: typing.List[typing.Any], + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + ''' + ListBase _get_items_oapg + ''' + cast_items = [] + + for i, value in enumerate(arg): + item_path_to_item = path_to_item + (i,) + item_cls = path_to_schemas[item_path_to_item] + new_value = item_cls._get_new_instance_without_conversion_oapg( + value, + item_path_to_item, + path_to_schemas + ) + cast_items.append(new_value) + + return cast_items + + +class Discriminable: + MetaOapg: MetaOapgTyped + + @classmethod + def _ensure_discriminator_value_present_oapg(cls, disc_property_name: str, validation_metadata: ValidationMetadata, *args): + if not args or args and disc_property_name not in args[0]: + # The input data does not contain the discriminator property + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '{}' is missing at path: {}".format(disc_property_name, validation_metadata.path_to_item) + ) + + @classmethod + def get_discriminated_class_oapg(cls, disc_property_name: str, disc_payload_value: str): + """ + Used in schemas with discriminators + """ + if not hasattr(cls.MetaOapg, 'discriminator'): + return None + disc = cls.MetaOapg.discriminator() + if disc_property_name not in disc: + return None + discriminated_cls = disc[disc_property_name].get(disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if not hasattr(cls, 'MetaOapg'): + return None + elif not ( + hasattr(cls.MetaOapg, 'all_of') or + hasattr(cls.MetaOapg, 'one_of') or + hasattr(cls.MetaOapg, 'any_of') + ): + return None + # TODO stop traveling if a cycle is hit + if hasattr(cls.MetaOapg, 'all_of'): + for allof_cls in cls.MetaOapg.all_of(): + discriminated_cls = allof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if hasattr(cls.MetaOapg, 'one_of'): + for oneof_cls in cls.MetaOapg.one_of(): + discriminated_cls = oneof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if hasattr(cls.MetaOapg, 'any_of'): + for anyof_cls in cls.MetaOapg.any_of(): + discriminated_cls = anyof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + return None + + +class DictBase(Discriminable, ValidatorBase): + + @classmethod + def __validate_arg_presence(cls, arg): + """ + Ensures that: + - all required arguments are passed in + - the input variable names are valid + - present in properties or + - accepted because additionalProperties exists + Exceptions will be raised if: + - invalid arguments were passed in + - a var_name is invalid if additional_properties == NotAnyTypeSchema + and var_name not in properties.__annotations__ + - required properties were not passed in + + Args: + arg: the input dict + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + seen_required_properties = set() + invalid_arguments = [] + required_property_names = getattr(cls.MetaOapg, 'required', set()) + additional_properties = getattr(cls.MetaOapg, 'additional_properties', UnsetAnyTypeSchema) + properties = getattr(cls.MetaOapg, 'properties', {}) + property_annotations = getattr(properties, '__annotations__', {}) + for property_name in arg: + if property_name in required_property_names: + seen_required_properties.add(property_name) + elif property_name in property_annotations: + continue + elif additional_properties is not NotAnyTypeSchema: + continue + else: + invalid_arguments.append(property_name) + missing_required_arguments = list(required_property_names - seen_required_properties) + if missing_required_arguments: + missing_required_arguments.sort() + raise ApiTypeError( + "{} is missing {} required argument{}: {}".format( + cls.__name__, + len(missing_required_arguments), + "s" if len(missing_required_arguments) > 1 else "", + missing_required_arguments + ) + ) + if invalid_arguments: + invalid_arguments.sort() + raise ApiTypeError( + "{} was passed {} invalid argument{}: {}".format( + cls.__name__, + len(invalid_arguments), + "s" if len(invalid_arguments) > 1 else "", + invalid_arguments + ) + ) + + @classmethod + def __validate_args(cls, arg, validation_metadata: ValidationMetadata): + """ + Ensures that: + - values passed in for properties are valid + Exceptions will be raised if: + - invalid arguments were passed in + + Args: + arg: the input dict + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + path_to_schemas = {} + additional_properties = getattr(cls.MetaOapg, 'additional_properties', UnsetAnyTypeSchema) + properties = getattr(cls.MetaOapg, 'properties', {}) + property_annotations = getattr(properties, '__annotations__', {}) + for property_name, value in arg.items(): + path_to_item = validation_metadata.path_to_item+(property_name,) + if property_name in property_annotations: + schema = property_annotations[property_name] + elif additional_properties is not NotAnyTypeSchema: + if additional_properties is UnsetAnyTypeSchema: + """ + If additionalProperties is unset and this path_to_item does not yet have + any validations on it, validate it. + If it already has validations on it, skip this validation. + """ + if path_to_item in path_to_schemas: + continue + schema = additional_properties + else: + raise ApiTypeError('Unable to find schema for value={} in class={} at path_to_item={}'.format( + value, cls, validation_metadata.path_to_item+(property_name,) + )) + schema = cls._get_class_oapg(schema) + arg_validation_metadata = ValidationMetadata( + from_server=validation_metadata.from_server, + configuration=validation_metadata.configuration, + path_to_item=path_to_item, + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if arg_validation_metadata.validation_ran_earlier(schema): + continue + other_path_to_schemas = schema._validate_oapg(value, validation_metadata=arg_validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __check_dict_validations( + cls, + arg, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxProperties', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_properties') and + len(arg) > cls.MetaOapg.max_properties): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of properties must be less than or equal to", + constraint_value=cls.MetaOapg.max_properties, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minProperties', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_properties') and + len(arg) < cls.MetaOapg.min_properties): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of properties must be greater than or equal to", + constraint_value=cls.MetaOapg.min_properties, + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DictBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + if isinstance(arg, frozendict.frozendict): + cls.__check_dict_validations(arg, validation_metadata) + _path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + if not isinstance(arg, frozendict.frozendict): + return _path_to_schemas + cls.__validate_arg_presence(arg) + other_path_to_schemas = cls.__validate_args(arg, validation_metadata=validation_metadata) + update(_path_to_schemas, other_path_to_schemas) + try: + discriminator = cls.MetaOapg.discriminator() + except AttributeError: + return _path_to_schemas + # discriminator exists + disc_prop_name = list(discriminator.keys())[0] + cls._ensure_discriminator_value_present_oapg(disc_prop_name, validation_metadata, arg) + discriminated_cls = cls.get_discriminated_class_oapg( + disc_property_name=disc_prop_name, disc_payload_value=arg[disc_prop_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value was passed in to {}.{} Only the values {} are allowed at {}".format( + cls.__name__, + disc_prop_name, + list(discriminator[disc_prop_name].keys()), + validation_metadata.path_to_item + (disc_prop_name,) + ) + ) + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if updated_vm.validation_ran_earlier(discriminated_cls): + return _path_to_schemas + other_path_to_schemas = discriminated_cls._validate_oapg(arg, validation_metadata=updated_vm) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_properties_oapg( + cls, + arg: typing.Dict[str, typing.Any], + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + """ + DictBase _get_properties_oapg, this is how properties are set + These values already passed validation + """ + dict_items = {} + + for property_name_js, value in arg.items(): + property_path_to_item = path_to_item + (property_name_js,) + property_cls = path_to_schemas[property_path_to_item] + new_value = property_cls._get_new_instance_without_conversion_oapg( + value, + property_path_to_item, + path_to_schemas + ) + dict_items[property_name_js] = new_value + + return dict_items + + def __setattr__(self, name: str, value: typing.Any): + if not isinstance(self, FileIO): + raise AttributeError('property setting not supported on immutable instances') + + def __getattr__(self, name: str): + """ + for instance.name access + Properties are only type hinted for required properties + so that hasattr(instance, 'optionalProp') is False when that key is not present + """ + if not isinstance(self, frozendict.frozendict): + return super().__getattr__(name) + if name not in self.__class__.__annotations__: + raise AttributeError(f"{self} has no attribute '{name}'") + try: + value = self[name] + return value + except KeyError as ex: + raise AttributeError(str(ex)) + + def __getitem__(self, name: str): + """ + dict_instance[name] accessor + key errors thrown + """ + if not isinstance(self, frozendict.frozendict): + return super().__getattr__(name) + return super().__getitem__(name) + + def get_item_oapg(self, name: str) -> typing.Union['AnyTypeSchema', Unset]: + # dict_instance[name] accessor + if not isinstance(self, frozendict.frozendict): + raise NotImplementedError() + try: + return super().__getitem__(name) + except KeyError: + return unset + + +def cast_to_allowed_types( + arg: typing.Union[str, date, datetime, uuid.UUID, decimal.Decimal, int, float, None, dict, frozendict.frozendict, list, tuple, bytes, Schema, io.FileIO, io.BufferedReader], + from_server: bool, + validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]], + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), +) -> typing.Union[frozendict.frozendict, tuple, decimal.Decimal, str, bytes, BoolClass, NoneClass, FileIO]: + """ + Casts the input payload arg into the allowed types + The input validated_path_to_schemas is mutated by running this function + + When from_server is False then + - date/datetime is cast to str + - int/float is cast to Decimal + + If a Schema instance is passed in it is converted back to a primitive instance because + One may need to validate that data to the original Schema class AND additional different classes + those additional classes will need to be added to the new manufactured class for that payload + If the code didn't do this and kept the payload as a Schema instance it would fail to validate to other + Schema classes and the code wouldn't be able to mfg a new class that includes all valid schemas + TODO: store the validated schema classes in validation_metadata + + Args: + arg: the payload + from_server: whether this payload came from the server or not + validated_path_to_schemas: a dict that stores the validated classes at any path location in the payload + """ + if isinstance(arg, Schema): + # store the already run validations + schema_classes = set() + source_schema_was_unset = len(arg.__class__.__bases__) == 2 and UnsetAnyTypeSchema in arg.__class__.__bases__ + if not source_schema_was_unset: + """ + Do not include UnsetAnyTypeSchema and its base class because + it did not exist in the original spec schema definition + It was added to ensure that all instances are of type Schema and the allowed base types + """ + for cls in arg.__class__.__bases__: + if cls is Singleton: + # Skip Singleton + continue + schema_classes.add(cls) + validated_path_to_schemas[path_to_item] = schema_classes + + type_error = ApiTypeError(f"Invalid type. Required value type is str and passed type was {type(arg)} at {path_to_item}") + if isinstance(arg, str): + return str(arg) + elif isinstance(arg, (dict, frozendict.frozendict)): + return frozendict.frozendict({key: cast_to_allowed_types(val, from_server, validated_path_to_schemas, path_to_item + (key,)) for key, val in arg.items()}) + elif isinstance(arg, (bool, BoolClass)): + """ + this check must come before isinstance(arg, (int, float)) + because isinstance(True, int) is True + """ + if arg: + return BoolClass.TRUE + return BoolClass.FALSE + elif isinstance(arg, int): + return decimal.Decimal(arg) + elif isinstance(arg, float): + decimal_from_float = decimal.Decimal(arg) + if decimal_from_float.as_integer_ratio()[1] == 1: + # 9.0 -> Decimal('9.0') + # 3.4028234663852886e+38 -> Decimal('340282346638528859811704183484516925440.0') + return decimal.Decimal(str(decimal_from_float)+'.0') + return decimal_from_float + elif isinstance(arg, (tuple, list)): + return tuple([cast_to_allowed_types(item, from_server, validated_path_to_schemas, path_to_item + (i,)) for i, item in enumerate(arg)]) + elif isinstance(arg, (none_type, NoneClass)): + return NoneClass.NONE + elif isinstance(arg, (date, datetime)): + if not from_server: + return arg.isoformat() + raise type_error + elif isinstance(arg, uuid.UUID): + if not from_server: + return str(arg) + raise type_error + elif isinstance(arg, decimal.Decimal): + return decimal.Decimal(arg) + elif isinstance(arg, bytes): + return bytes(arg) + elif isinstance(arg, (io.FileIO, io.BufferedReader)): + return FileIO(arg) + raise ValueError('Invalid type passed in got input={} type={}'.format(arg, type(arg))) + + +class ComposedBase(Discriminable): + + @classmethod + def __get_allof_classes(cls, arg, validation_metadata: ValidationMetadata): + path_to_schemas = defaultdict(set) + for allof_cls in cls.MetaOapg.all_of(): + if validation_metadata.validation_ran_earlier(allof_cls): + continue + other_path_to_schemas = allof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __get_oneof_class( + cls, + arg, + discriminated_cls, + validation_metadata: ValidationMetadata, + ): + oneof_classes = [] + path_to_schemas = defaultdict(set) + for oneof_cls in cls.MetaOapg.one_of(): + if oneof_cls in path_to_schemas[validation_metadata.path_to_item]: + oneof_classes.append(oneof_cls) + continue + if validation_metadata.validation_ran_earlier(oneof_cls): + oneof_classes.append(oneof_cls) + continue + try: + path_to_schemas = oneof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and oneof_cls is discriminated_cls: + raise ex + continue + oneof_classes.append(oneof_cls) + if not oneof_classes: + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. None " + "of the oneOf schemas matched the input data.".format(cls) + ) + elif len(oneof_classes) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. Multiple " + "oneOf schemas {} matched the inputs, but a max of one is allowed.".format(cls, oneof_classes) + ) + # exactly one class matches + return path_to_schemas + + @classmethod + def __get_anyof_classes( + cls, + arg, + discriminated_cls, + validation_metadata: ValidationMetadata + ): + anyof_classes = [] + path_to_schemas = defaultdict(set) + for anyof_cls in cls.MetaOapg.any_of(): + if validation_metadata.validation_ran_earlier(anyof_cls): + anyof_classes.append(anyof_cls) + continue + + try: + other_path_to_schemas = anyof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and anyof_cls is discriminated_cls: + raise ex + continue + anyof_classes.append(anyof_cls) + update(path_to_schemas, other_path_to_schemas) + if not anyof_classes: + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. None " + "of the anyOf schemas matched the input data.".format(cls) + ) + return path_to_schemas + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + ComposedBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + # validation checking on types, validations, and enums + path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + + # process composed schema + discriminator = None + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'discriminator'): + discriminator = cls.MetaOapg.discriminator() + discriminated_cls = None + if discriminator and arg and isinstance(arg, frozendict.frozendict): + disc_property_name = list(discriminator.keys())[0] + cls._ensure_discriminator_value_present_oapg(disc_property_name, updated_vm, arg) + # get discriminated_cls by looking at the dict in the current class + discriminated_cls = cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=arg[disc_property_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value '{}' was passed in to {}.{} Only the values {} are allowed at {}".format( + arg[disc_property_name], + cls.__name__, + disc_property_name, + list(discriminator[disc_property_name].keys()), + updated_vm.path_to_item + (disc_property_name,) + ) + ) + + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'all_of'): + other_path_to_schemas = cls.__get_allof_classes(arg, validation_metadata=updated_vm) + update(path_to_schemas, other_path_to_schemas) + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'one_of'): + other_path_to_schemas = cls.__get_oneof_class( + arg, + discriminated_cls=discriminated_cls, + validation_metadata=updated_vm + ) + update(path_to_schemas, other_path_to_schemas) + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'any_of'): + other_path_to_schemas = cls.__get_anyof_classes( + arg, + discriminated_cls=discriminated_cls, + validation_metadata=updated_vm + ) + update(path_to_schemas, other_path_to_schemas) + not_cls = None + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'not_schema'): + not_cls = cls.MetaOapg.not_schema + not_cls = cls._get_class_oapg(not_cls) + if not_cls: + other_path_to_schemas = None + not_exception = ApiValueError( + "Invalid value '{}' was passed in to {}. Value is invalid because it is disallowed by {}".format( + arg, + cls.__name__, + not_cls.__name__, + ) + ) + if updated_vm.validation_ran_earlier(not_cls): + raise not_exception + + try: + other_path_to_schemas = not_cls._validate_oapg(arg, validation_metadata=updated_vm) + except (ApiValueError, ApiTypeError): + pass + if other_path_to_schemas: + raise not_exception + + if discriminated_cls is not None and not updated_vm.validation_ran_earlier(discriminated_cls): + # TODO use an exception from this package here + assert discriminated_cls in path_to_schemas[updated_vm.path_to_item] + return path_to_schemas + + +# DictBase, ListBase, NumberBase, StrBase, BoolBase, NoneBase +class ComposedSchema( + ComposedBase, + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema, + NoneFrozenDictTupleStrDecimalBoolMixin +): + @classmethod + def from_openapi_data_oapg(cls, *args: typing.Any, _configuration: typing.Optional[Configuration] = None, **kwargs): + if not args: + if not kwargs: + raise ApiTypeError('{} is missing required input data in args or kwargs'.format(cls.__name__)) + args = (kwargs, ) + return super().from_openapi_data_oapg(args[0], _configuration=_configuration) + + +class ListSchema( + ListBase, + Schema, + TupleMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: typing.List[typing.Any], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[typing.List[typing.Any], typing.Tuple[typing.Any]], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class NoneSchema( + NoneBase, + Schema, + NoneMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: None, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: None, **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class NumberSchema( + NumberBase, + Schema, + DecimalMixin +): + """ + This is used for type: number with no format + Both integers AND floats are accepted + """ + + @classmethod + def from_openapi_data_oapg(cls, arg: typing.Union[int, float], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[decimal.Decimal, int, float], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class IntBase: + @property + def as_int_oapg(self) -> int: + try: + return self._as_int + except AttributeError: + self._as_int = int(self) + return self._as_int + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + + denominator = arg.as_integer_ratio()[-1] + if denominator != 1: + raise ApiValueError( + "Invalid value '{}' for type integer at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + IntBase _validate_oapg + TODO what about types = (int, number) -> IntBase, NumberBase? We could drop int and keep number only + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class IntSchema(IntBase, NumberSchema): + + @classmethod + def from_openapi_data_oapg(cls, arg: int, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[decimal.Decimal, int], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class Int32Base: + __inclusive_minimum = decimal.Decimal(-2147483648) + __inclusive_maximum = decimal.Decimal(2147483647) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal) and arg.as_tuple().exponent == 0: + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type int32 at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Int32Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Int32Schema( + Int32Base, + IntSchema +): + pass + + +class Int64Base: + __inclusive_minimum = decimal.Decimal(-9223372036854775808) + __inclusive_maximum = decimal.Decimal(9223372036854775807) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal) and arg.as_tuple().exponent == 0: + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type int64 at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Int64Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Int64Schema( + Int64Base, + IntSchema +): + pass + + +class Float32Base: + __inclusive_minimum = decimal.Decimal(-3.4028234663852886e+38) + __inclusive_maximum = decimal.Decimal(3.4028234663852886e+38) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type float at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Float32Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Float32Schema( + Float32Base, + NumberSchema +): + + @classmethod + def from_openapi_data_oapg(cls, arg: float, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + +class Float64Base: + __inclusive_minimum = decimal.Decimal(-1.7976931348623157E+308) + __inclusive_maximum = decimal.Decimal(1.7976931348623157E+308) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type double at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Float64Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + +class Float64Schema( + Float64Base, + NumberSchema +): + + @classmethod + def from_openapi_data_oapg(cls, arg: float, _configuration: typing.Optional[Configuration] = None): + # todo check format + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + +class StrSchema( + StrBase, + Schema, + StrMixin +): + """ + date + datetime string types must inherit from this class + That is because one can validate a str payload as both: + - type: string (format unset) + - type: string, format: date + """ + + @classmethod + def from_openapi_data_oapg(cls, arg: str, _configuration: typing.Optional[Configuration] = None) -> 'StrSchema': + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[str, date, datetime, uuid.UUID], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class UUIDSchema(UUIDBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, uuid.UUID], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DateSchema(DateBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, date], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DateTimeSchema(DateTimeBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, datetime], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DecimalSchema(DecimalBase, StrSchema): + + def __new__(cls, arg: str, **kwargs: Configuration): + """ + Note: Decimals may not be passed in because cast_to_allowed_types is only invoked once for payloads + which can be simple (str) or complex (dicts or lists with nested values) + Because casting is only done once and recursively casts all values prior to validation then for a potential + client side Decimal input if Decimal was accepted as an input in DecimalSchema then one would not know + if one was using it for a StrSchema (where it should be cast to str) or one is using it for NumberSchema + where it should stay as Decimal. + """ + return super().__new__(cls, arg, **kwargs) + + +class BytesSchema( + Schema, + BytesMixin +): + """ + this class will subclass bytes and is immutable + """ + def __new__(cls, arg: bytes, **kwargs: Configuration): + return super(Schema, cls).__new__(cls, arg) + + +class FileSchema( + Schema, + FileMixin +): + """ + This class is NOT immutable + Dynamic classes are built using it for example when AnyType allows in binary data + Al other schema classes ARE immutable + If one wanted to make this immutable one could make this a DictSchema with required properties: + - data = BytesSchema (which would be an immutable bytes based schema) + - file_name = StrSchema + and cast_to_allowed_types would convert bytes and file instances into dicts containing data + file_name + The downside would be that data would be stored in memory which one may not want to do for very large files + + The developer is responsible for closing this file and deleting it + + This class was kept as mutable: + - to allow file reading and writing to disk + - to be able to preserve file name info + """ + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader], **kwargs: Configuration): + return super(Schema, cls).__new__(cls, arg) + + +class BinaryBase: + pass + + +class BinarySchema( + ComposedBase, + BinaryBase, + Schema, + BinaryMixin +): + class MetaOapg: + @staticmethod + def one_of(): + return [ + BytesSchema, + FileSchema, + ] + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader, bytes], **kwargs: Configuration): + return super().__new__(cls, arg) + + +class BoolSchema( + BoolBase, + Schema, + BoolMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: bool, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: bool, **kwargs: ValidationMetadata): + return super().__new__(cls, arg, **kwargs) + + +class AnyTypeSchema( + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema, + NoneFrozenDictTupleStrDecimalBoolFileBytesMixin +): + # Python representation of a schema defined as true or {} + pass + + +class UnsetAnyTypeSchema(AnyTypeSchema): + # Used when additionalProperties/items was not explicitly defined and a defining schema is needed + pass + + +class NotAnyTypeSchema( + ComposedSchema, +): + """ + Python representation of a schema defined as false or {'not': {}} + Does not allow inputs in of AnyType + Note: validations on this class are never run because the code knows that no inputs will ever validate + """ + + class MetaOapg: + not_schema = AnyTypeSchema + + def __new__( + cls, + *args, + _configuration: typing.Optional[Configuration] = None, + ) -> 'NotAnyTypeSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + +class DictSchema( + DictBase, + Schema, + FrozenDictMixin +): + @classmethod + def from_openapi_data_oapg(cls, arg: typing.Dict[str, typing.Any], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, *args: typing.Union[dict, frozendict.frozendict], **kwargs: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, bytes, Schema, Unset, ValidationMetadata]): + return super().__new__(cls, *args, **kwargs) + + +schema_type_classes = {NoneSchema, DictSchema, ListSchema, NumberSchema, StrSchema, BoolSchema, AnyTypeSchema} + + +@functools.lru_cache() +def get_new_class( + class_name: str, + bases: typing.Tuple[typing.Type[typing.Union[Schema, typing.Any]], ...] +) -> typing.Type[Schema]: + """ + Returns a new class that is made with the subclass bases + """ + new_cls: typing.Type[Schema] = type(class_name, bases, {}) + return new_cls + + +LOG_CACHE_USAGE = False + + +def log_cache_usage(cache_fn): + if LOG_CACHE_USAGE: + print(cache_fn.__name__, cache_fn.cache_info()) diff --git a/samples/openapi3/client/features/dynamic-servers/python/git_push.sh b/samples/openapi3/client/features/dynamic-servers/python/git_push.sh index f53a75d4fa..ced3be2b0c 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/git_push.sh +++ b/samples/openapi3/client/features/dynamic-servers/python/git_push.sh @@ -1,7 +1,7 @@ #!/bin/sh # ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ # -# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" git_user_id=$1 git_repo_id=$2 @@ -38,14 +38,14 @@ git add . git commit -m "$release_note" # Sets the new remote -git_remote=$(git remote) +git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git fi fi @@ -55,3 +55,4 @@ git pull origin master # Pushes (Forces) the changes in the local repository up to the remote repository echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/openapi3/client/features/dynamic-servers/python/requirements.txt b/samples/openapi3/client/features/dynamic-servers/python/requirements.txt index 96947f6040..3cb6612669 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/requirements.txt +++ b/samples/openapi3/client/features/dynamic-servers/python/requirements.txt @@ -1,3 +1,6 @@ -python_dateutil >= 2.5.3 +certifi >= 14.5.14 +frozendict ~= 2.3.4 +python-dateutil ~= 2.7.0 setuptools >= 21.0.0 -urllib3 >= 1.25.3 +typing_extensions ~= 4.3.0 +urllib3 ~= 1.26.7 diff --git a/samples/openapi3/client/features/dynamic-servers/python/setup.py b/samples/openapi3/client/features/dynamic-servers/python/setup.py index 16802f144f..4c1b543715 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/setup.py +++ b/samples/openapi3/client/features/dynamic-servers/python/setup.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Extension with dynamic servers @@ -7,7 +9,6 @@ Generated by: https://openapi-generator.tech """ - from setuptools import setup, find_packages # noqa: H301 NAME = "dynamic-servers" @@ -20,8 +21,12 @@ VERSION = "1.0.0" # http://pypi.python.org/pypi/setuptools REQUIRES = [ - "urllib3 >= 1.25.3", - "python-dateutil", + "certifi >= 14.5.14", + "frozendict ~= 2.3.4", + "python-dateutil ~= 2.7.0", + "setuptools >= 21.0.0", + "typing_extensions ~= 4.3.0", + "urllib3 ~= 1.26.7", ] setup( @@ -32,7 +37,7 @@ setup( author_email="team@openapitools.org", url="", keywords=["OpenAPI", "OpenAPI-Generator", "OpenAPI Extension with dynamic servers"], - python_requires=">=3.6", + python_requires=">=3.7", install_requires=REQUIRES, packages=find_packages(exclude=["test", "tests"]), include_package_data=True, diff --git a/samples/openapi3/client/features/dynamic-servers/python/test-requirements.txt b/samples/openapi3/client/features/dynamic-servers/python/test-requirements.txt index bb4f22bb7a..2d88b03419 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/test-requirements.txt +++ b/samples/openapi3/client/features/dynamic-servers/python/test-requirements.txt @@ -1 +1,3 @@ +pytest~=4.6.7 # needed for python 3.4 pytest-cov>=2.8.1 +pytest-randomly==1.2.3 # needed for python 3.4 diff --git a/samples/openapi3/client/features/dynamic-servers/python/test/test_models/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/test/test_models/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/__init__.py new file mode 100644 index 0000000000..1309632d3d --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/__init__.py @@ -0,0 +1,68 @@ +import json +import typing + +import urllib3 +from urllib3._collections import HTTPHeaderDict + + +class ApiTestMixin: + json_content_type = 'application/json' + user_agent = 'OpenAPI-Generator/1.0.0/python' + + @classmethod + def assert_pool_manager_request_called_with( + cls, + mock_request, + url: str, + method: str = 'POST', + body: typing.Optional[bytes] = None, + content_type: typing.Optional[str] = None, + accept_content_type: typing.Optional[str] = None, + stream: bool = False, + ): + headers = { + 'User-Agent': cls.user_agent + } + if accept_content_type: + headers['Accept'] = accept_content_type + if content_type: + headers['Content-Type'] = content_type + kwargs = dict( + headers=HTTPHeaderDict(headers), + preload_content=not stream, + timeout=None, + ) + if content_type and method != 'GET': + kwargs['body'] = body + mock_request.assert_called_with( + method, + url, + **kwargs + ) + + @staticmethod + def headers_for_content_type(content_type: str) -> typing.Dict[str, str]: + return {'content-type': content_type} + + @classmethod + def response( + cls, + body: typing.Union[str, bytes], + status: int = 200, + content_type: str = json_content_type, + headers: typing.Optional[typing.Dict[str, str]] = None, + preload_content: bool = True + ) -> urllib3.HTTPResponse: + if headers is None: + headers = {} + headers.update(cls.headers_for_content_type(content_type)) + return urllib3.HTTPResponse( + body, + headers=headers, + status=status, + preload_content=preload_content + ) + + @staticmethod + def json_bytes(in_data: typing.Any) -> bytes: + return json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode('utf-8') diff --git a/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_custom/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_custom/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_custom/test_get.py b/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_custom/test_get.py new file mode 100644 index 0000000000..5c1e563e34 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_custom/test_get.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import dynamic_servers +from dynamic_servers.paths.custom import get # noqa: E501 +from dynamic_servers import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestCustom(ApiTestMixin, unittest.TestCase): + """ + Custom unit test stubs + Use custom server # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_default/__init__.py b/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_default/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_default/test_get.py b/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_default/test_get.py new file mode 100644 index 0000000000..7816dd50f2 --- /dev/null +++ b/samples/openapi3/client/features/dynamic-servers/python/test/test_paths/test_default/test_get.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import dynamic_servers +from dynamic_servers.paths.default import get # noqa: E501 +from dynamic_servers import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestDefault(ApiTestMixin, unittest.TestCase): + """ + Default unit test stubs + Use default server # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/features/dynamic-servers/python/tox.ini b/samples/openapi3/client/features/dynamic-servers/python/tox.ini index c27e7fe327..67c29e77f4 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/tox.ini +++ b/samples/openapi3/client/features/dynamic-servers/python/tox.ini @@ -1,7 +1,8 @@ [tox] -envlist = py3 +envlist = py37 [testenv] +passenv = PYTHON_VERSION deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/.gitignore b/samples/openapi3/client/petstore/dart-dio/oneof/.gitignore new file mode 100644 index 0000000000..4298cdcbd1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/.gitignore @@ -0,0 +1,41 @@ +# See https://dart.dev/guides/libraries/private-files + +# Files and directories created by pub +.dart_tool/ +.buildlog +.packages +.project +.pub/ +build/ +**/packages/ + +# Files created by dart2js +# (Most Dart developers will use pub build to compile Dart, use/modify these +# rules if you intend to use dart2js directly +# Convention is to use extension '.dart.js' for Dart compiled to Javascript to +# differentiate from explicit Javascript files) +*.dart.js +*.part.js +*.js.deps +*.js.map +*.info.json + +# Directory created by dartdoc +doc/api/ + +# Don't commit pubspec lock file +# (Library packages only! Remove pattern if developing an application package) +pubspec.lock + +# Don’t commit files and directories created by other development environments. +# For example, if your development environment creates any of the following files, +# consider putting them in a global ignore file: + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator-ignore b/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/.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/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/FILES b/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/FILES new file mode 100644 index 0000000000..f1ab7b5540 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/FILES @@ -0,0 +1,23 @@ +.gitignore +README.md +analysis_options.yaml +doc/Apple.md +doc/Banana.md +doc/DefaultApi.md +doc/Fruit.md +lib/openapi.dart +lib/src/api.dart +lib/src/api/default_api.dart +lib/src/api_util.dart +lib/src/auth/api_key_auth.dart +lib/src/auth/auth.dart +lib/src/auth/basic_auth.dart +lib/src/auth/bearer_auth.dart +lib/src/auth/oauth.dart +lib/src/date_serializer.dart +lib/src/model/apple.dart +lib/src/model/banana.dart +lib/src/model/date.dart +lib/src/model/fruit.dart +lib/src/serializers.dart +pubspec.yaml diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/README.md b/samples/openapi3/client/petstore/dart-dio/oneof/README.md new file mode 100644 index 0000000000..53bfd08fec --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/README.md @@ -0,0 +1,84 @@ +# openapi (EXPERIMENTAL) +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +This Dart package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 0.0.1 +- Build package: org.openapitools.codegen.languages.DartDioClientCodegen + +## Requirements + +* Dart 2.12.0 or later OR Flutter 1.26.0 or later +* Dio 4.0.0+ + +## Installation & Usage + +### pub.dev +To use the package from [pub.dev](https://pub.dev), please include the following in pubspec.yaml +```yaml +dependencies: + openapi: 1.0.0 +``` + +### Github +If this Dart package is published to Github, please include the following in pubspec.yaml +```yaml +dependencies: + openapi: + git: + url: https://github.com/GIT_USER_ID/GIT_REPO_ID.git + #ref: main +``` + +### Local development +To use the package from your local drive, please include the following in pubspec.yaml +```yaml +dependencies: + openapi: + path: /path/to/openapi +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```dart +import 'package:openapi/openapi.dart'; + + +final api = Openapi().getDefaultApi(); + +try { + final response = await api.rootGet(); + print(response); +} catch on DioError (e) { + print("Exception when calling DefaultApi->rootGet: $e\n"); +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +[*DefaultApi*](doc/DefaultApi.md) | [**rootGet**](doc/DefaultApi.md#rootget) | **GET** / | + + +## Documentation For Models + + - [Apple](doc/Apple.md) + - [Banana](doc/Banana.md) + - [Fruit](doc/Fruit.md) + + +## Documentation For Authorization + + All endpoints do not require authorization. + + +## Author + + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/oneof/analysis_options.yaml new file mode 100644 index 0000000000..a611887d3a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/analysis_options.yaml @@ -0,0 +1,9 @@ +analyzer: + language: + strict-inference: true + strict-raw-types: true + strong-mode: + implicit-dynamic: false + implicit-casts: false + exclude: + - test/*.dart diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/doc/Apple.md b/samples/openapi3/client/petstore/dart-dio/oneof/doc/Apple.md new file mode 100644 index 0000000000..c7f711b87c --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/doc/Apple.md @@ -0,0 +1,15 @@ +# openapi.model.Apple + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/doc/Banana.md b/samples/openapi3/client/petstore/dart-dio/oneof/doc/Banana.md new file mode 100644 index 0000000000..bef8a58a42 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/doc/Banana.md @@ -0,0 +1,15 @@ +# openapi.model.Banana + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**count** | **num** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/doc/DefaultApi.md b/samples/openapi3/client/petstore/dart-dio/oneof/doc/DefaultApi.md new file mode 100644 index 0000000000..41c9b6f941 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/doc/DefaultApi.md @@ -0,0 +1,51 @@ +# openapi.api.DefaultApi + +## Load the API package +```dart +import 'package:openapi/api.dart'; +``` + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**rootGet**](DefaultApi.md#rootget) | **GET** / | + + +# **rootGet** +> Fruit rootGet() + + + +### Example +```dart +import 'package:openapi/api.dart'; + +final api = Openapi().getDefaultApi(); + +try { + final response = api.rootGet(); + print(response); +} catch on DioError (e) { + print('Exception when calling DefaultApi->rootGet: $e\n'); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Fruit**](Fruit.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/doc/Fruit.md b/samples/openapi3/client/petstore/dart-dio/oneof/doc/Fruit.md new file mode 100644 index 0000000000..5d48cc6e6d --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/doc/Fruit.md @@ -0,0 +1,17 @@ +# openapi.model.Fruit + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**color** | **String** | | [optional] +**kind** | **String** | | [optional] +**count** | **num** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/openapi.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/openapi.dart new file mode 100644 index 0000000000..d85a16fc6a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/openapi.dart @@ -0,0 +1,16 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +export 'package:openapi/src/api.dart'; +export 'package:openapi/src/auth/api_key_auth.dart'; +export 'package:openapi/src/auth/basic_auth.dart'; +export 'package:openapi/src/auth/oauth.dart'; +export 'package:openapi/src/serializers.dart'; +export 'package:openapi/src/model/date.dart'; + +export 'package:openapi/src/api/default_api.dart'; + +export 'package:openapi/src/model/apple.dart'; +export 'package:openapi/src/model/banana.dart'; +export 'package:openapi/src/model/fruit.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/api.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/api.dart new file mode 100644 index 0000000000..ba9424a2d2 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/api.dart @@ -0,0 +1,73 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; +import 'package:built_value/serializer.dart'; +import 'package:openapi/src/serializers.dart'; +import 'package:openapi/src/auth/api_key_auth.dart'; +import 'package:openapi/src/auth/basic_auth.dart'; +import 'package:openapi/src/auth/bearer_auth.dart'; +import 'package:openapi/src/auth/oauth.dart'; +import 'package:openapi/src/api/default_api.dart'; + +class Openapi { + static const String basePath = r'http://localhost'; + + final Dio dio; + final Serializers serializers; + + Openapi({ + Dio? dio, + Serializers? serializers, + String? basePathOverride, + List? interceptors, + }) : this.serializers = serializers ?? standardSerializers, + this.dio = dio ?? + Dio(BaseOptions( + baseUrl: basePathOverride ?? basePath, + connectTimeout: 5000, + receiveTimeout: 3000, + )) { + if (interceptors == null) { + this.dio.interceptors.addAll([ + OAuthInterceptor(), + BasicAuthInterceptor(), + BearerAuthInterceptor(), + ApiKeyAuthInterceptor(), + ]); + } else { + this.dio.interceptors.addAll(interceptors); + } + } + + void setOAuthToken(String name, String token) { + if (this.dio.interceptors.any((i) => i is OAuthInterceptor)) { + (this.dio.interceptors.firstWhere((i) => i is OAuthInterceptor) as OAuthInterceptor).tokens[name] = token; + } + } + + void setBearerAuth(String name, String token) { + if (this.dio.interceptors.any((i) => i is BearerAuthInterceptor)) { + (this.dio.interceptors.firstWhere((i) => i is BearerAuthInterceptor) as BearerAuthInterceptor).tokens[name] = token; + } + } + + void setBasicAuth(String name, String username, String password) { + if (this.dio.interceptors.any((i) => i is BasicAuthInterceptor)) { + (this.dio.interceptors.firstWhere((i) => i is BasicAuthInterceptor) as BasicAuthInterceptor).authInfo[name] = BasicAuthInfo(username, password); + } + } + + void setApiKey(String name, String apiKey) { + if (this.dio.interceptors.any((i) => i is ApiKeyAuthInterceptor)) { + (this.dio.interceptors.firstWhere((element) => element is ApiKeyAuthInterceptor) as ApiKeyAuthInterceptor).apiKeys[name] = apiKey; + } + } + + /// Get DefaultApi instance, base route and serializer can be overridden by a given but be careful, + /// by doing that all interceptors will not be executed + DefaultApi getDefaultApi() { + return DefaultApi(dio, serializers); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/api/default_api.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/api/default_api.dart new file mode 100644 index 0000000000..e98b7ae9ca --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/api/default_api.dart @@ -0,0 +1,92 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:async'; + +import 'package:built_value/serializer.dart'; +import 'package:dio/dio.dart'; + +import 'package:openapi/src/model/fruit.dart'; + +class DefaultApi { + + final Dio _dio; + + final Serializers _serializers; + + const DefaultApi(this._dio, this._serializers); + + /// rootGet + /// + /// + /// Parameters: + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [Fruit] as data + /// Throws [DioError] if API call or serialization fails + Future> rootGet({ + CancelToken? cancelToken, + Map? headers, + Map? extra, + ValidateStatus? validateStatus, + ProgressCallback? onSendProgress, + ProgressCallback? onReceiveProgress, + }) async { + final _path = r'/'; + final _options = Options( + method: r'GET', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + validateStatus: validateStatus, + ); + + final _response = await _dio.request( + _path, + options: _options, + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + Fruit _responseData; + + try { + const _responseType = FullType(Fruit); + _responseData = _serializers.deserialize( + _response.data!, + specifiedType: _responseType, + ) as Fruit; + + } catch (error, stackTrace) { + throw DioError( + requestOptions: _response.requestOptions, + response: _response, + type: DioErrorType.other, + error: error, + )..stackTrace = stackTrace; + } + + return Response( + data: _responseData, + headers: _response.headers, + isRedirect: _response.isRedirect, + requestOptions: _response.requestOptions, + redirects: _response.redirects, + statusCode: _response.statusCode, + statusMessage: _response.statusMessage, + extra: _response.extra, + ); + } + +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/api_util.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/api_util.dart new file mode 100644 index 0000000000..ed3bb12f25 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/api_util.dart @@ -0,0 +1,77 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:dio/dio.dart'; + +/// Format the given form parameter object into something that Dio can handle. +/// Returns primitive or String. +/// Returns List/Map if the value is BuildList/BuiltMap. +dynamic encodeFormParameter(Serializers serializers, dynamic value, FullType type) { + if (value == null) { + return ''; + } + if (value is String || value is num || value is bool) { + return value; + } + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (serialized is String) { + return serialized; + } + if (value is BuiltList || value is BuiltSet || value is BuiltMap) { + return serialized; + } + return json.encode(serialized); +} + +dynamic encodeQueryParameter( + Serializers serializers, + dynamic value, + FullType type, +) { + if (value == null) { + return ''; + } + if (value is String || value is num || value is bool) { + return value; + } + if (value is Uint8List) { + // Currently not sure how to serialize this + return value; + } + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (serialized == null) { + return ''; + } + if (serialized is String) { + return serialized; + } + return serialized; +} + +ListParam encodeCollectionQueryParameter( + Serializers serializers, + dynamic value, + FullType type, { + ListFormat format = ListFormat.multi, +}) { + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (value is BuiltList || value is BuiltSet) { + return ListParam(List.of((serialized as Iterable).cast()), format); + } + throw ArgumentError('Invalid value passed to encodeCollectionQueryParameter'); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/api_key_auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/api_key_auth.dart new file mode 100644 index 0000000000..ee16e3f0f9 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/api_key_auth.dart @@ -0,0 +1,30 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class ApiKeyAuthInterceptor extends AuthInterceptor { + final Map apiKeys = {}; + + @override + void onRequest(RequestOptions options, RequestInterceptorHandler handler) { + final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'apiKey'); + for (final info in authInfo) { + final authName = info['name'] as String; + final authKeyName = info['keyName'] as String; + final authWhere = info['where'] as String; + final apiKey = apiKeys[authName]; + if (apiKey != null) { + if (authWhere == 'query') { + options.queryParameters[authKeyName] = apiKey; + } else { + options.headers[authKeyName] = apiKey; + } + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/auth.dart new file mode 100644 index 0000000000..f7ae9bf3f1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/auth.dart @@ -0,0 +1,18 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; + +abstract class AuthInterceptor extends Interceptor { + /// Get auth information on given route for the given type. + /// Can return an empty list if type is not present on auth data or + /// if route doesn't need authentication. + List> getAuthInfo(RequestOptions route, bool Function(Map secure) handles) { + if (route.extra.containsKey('secure')) { + final auth = route.extra['secure'] as List>; + return auth.where((secure) => handles(secure)).toList(); + } + return []; + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/basic_auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/basic_auth.dart new file mode 100644 index 0000000000..b6e6dce04f --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/basic_auth.dart @@ -0,0 +1,37 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:convert'; + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class BasicAuthInfo { + final String username; + final String password; + + const BasicAuthInfo(this.username, this.password); +} + +class BasicAuthInterceptor extends AuthInterceptor { + final Map authInfo = {}; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) { + final metadataAuthInfo = getAuthInfo(options, (secure) => (secure['type'] == 'http' && secure['scheme'] == 'basic') || secure['type'] == 'basic'); + for (final info in metadataAuthInfo) { + final authName = info['name'] as String; + final basicAuthInfo = authInfo[authName]; + if (basicAuthInfo != null) { + final basicAuth = 'Basic ${base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}'))}'; + options.headers['Authorization'] = basicAuth; + break; + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/bearer_auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/bearer_auth.dart new file mode 100644 index 0000000000..1d4402b376 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/bearer_auth.dart @@ -0,0 +1,26 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class BearerAuthInterceptor extends AuthInterceptor { + final Map tokens = {}; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) { + final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'http' && secure['scheme'] == 'bearer'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; + break; + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/oauth.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/oauth.dart new file mode 100644 index 0000000000..337cf762b0 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/auth/oauth.dart @@ -0,0 +1,26 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class OAuthInterceptor extends AuthInterceptor { + final Map tokens = {}; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) { + final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'oauth' || secure['type'] == 'oauth2'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; + break; + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/date_serializer.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/date_serializer.dart new file mode 100644 index 0000000000..db3c5c437d --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/date_serializer.dart @@ -0,0 +1,31 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:openapi/src/model/date.dart'; + +class DateSerializer implements PrimitiveSerializer { + + const DateSerializer(); + + @override + Iterable get types => BuiltList.of([Date]); + + @override + String get wireName => 'Date'; + + @override + Date deserialize(Serializers serializers, Object serialized, + {FullType specifiedType = FullType.unspecified}) { + final parsed = DateTime.parse(serialized as String); + return Date(parsed.year, parsed.month, parsed.day); + } + + @override + Object serialize(Serializers serializers, Date date, + {FullType specifiedType = FullType.unspecified}) { + return date.toString(); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/apple.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/apple.dart new file mode 100644 index 0000000000..02ca94190b --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/apple.dart @@ -0,0 +1,108 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'apple.g.dart'; + +/// Apple +/// +/// Properties: +/// * [kind] +@BuiltValue() +abstract class Apple implements Built { + @BuiltValueField(wireName: r'kind') + String? get kind; + + Apple._(); + + factory Apple([void updates(AppleBuilder b)]) = _$Apple; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(AppleBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$AppleSerializer(); +} + +class _$AppleSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Apple, _$Apple]; + + @override + final String wireName = r'Apple'; + + Iterable _serializeProperties( + Serializers serializers, + Apple object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.kind != null) { + yield r'kind'; + yield serializers.serialize( + object.kind, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Apple object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required AppleBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'kind': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.kind = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Apple deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = AppleBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/banana.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/banana.dart new file mode 100644 index 0000000000..bf2d632ee1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/banana.dart @@ -0,0 +1,108 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'banana.g.dart'; + +/// Banana +/// +/// Properties: +/// * [count] +@BuiltValue() +abstract class Banana implements Built { + @BuiltValueField(wireName: r'count') + num? get count; + + Banana._(); + + factory Banana([void updates(BananaBuilder b)]) = _$Banana; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(BananaBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$BananaSerializer(); +} + +class _$BananaSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Banana, _$Banana]; + + @override + final String wireName = r'Banana'; + + Iterable _serializeProperties( + Serializers serializers, + Banana object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.count != null) { + yield r'count'; + yield serializers.serialize( + object.count, + specifiedType: const FullType(num), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Banana object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required BananaBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'count': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(num), + ) as num; + result.count = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Banana deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = BananaBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/date.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/date.dart new file mode 100644 index 0000000000..b21c7f544b --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/date.dart @@ -0,0 +1,70 @@ +/// A gregorian calendar date generated by +/// OpenAPI generator to differentiate +/// between [DateTime] and [Date] formats. +class Date implements Comparable { + final int year; + + /// January is 1. + final int month; + + /// First day is 1. + final int day; + + Date(this.year, this.month, this.day); + + /// The current date + static Date now({bool utc = false}) { + var now = DateTime.now(); + if (utc) { + now = now.toUtc(); + } + return now.toDate(); + } + + /// Convert to a [DateTime]. + DateTime toDateTime({bool utc = false}) { + if (utc) { + return DateTime.utc(year, month, day); + } else { + return DateTime(year, month, day); + } + } + + @override + int compareTo(Date other) { + int d = year.compareTo(other.year); + if (d != 0) { + return d; + } + d = month.compareTo(other.month); + if (d != 0) { + return d; + } + return day.compareTo(other.day); + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is Date && + runtimeType == other.runtimeType && + year == other.year && + month == other.month && + day == other.day; + + @override + int get hashCode => year.hashCode ^ month.hashCode ^ day.hashCode; + + @override + String toString() { + final yyyy = year.toString(); + final mm = month.toString().padLeft(2, '0'); + final dd = day.toString().padLeft(2, '0'); + + return '$yyyy-$mm-$dd'; + } +} + +extension DateTimeToDate on DateTime { + Date toDate() => Date(year, month, day); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/fruit.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/fruit.dart new file mode 100644 index 0000000000..11f8cfa705 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/model/fruit.dart @@ -0,0 +1,123 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/apple.dart'; +import 'package:openapi/src/model/banana.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; +import 'package:one_of/one_of.dart'; + +part 'fruit.g.dart'; + +/// Fruit +/// +/// Properties: +/// * [color] +/// * [kind] +/// * [count] +@BuiltValue() +abstract class Fruit implements Built { + @BuiltValueField(wireName: r'color') + String? get color; + + /// One Of [Apple], [Banana] + OneOf get oneOf; + + Fruit._(); + + factory Fruit([void updates(FruitBuilder b)]) = _$Fruit; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(FruitBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$FruitSerializer(); +} + +class _$FruitSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Fruit, _$Fruit]; + + @override + final String wireName = r'Fruit'; + + Iterable _serializeProperties( + Serializers serializers, + Fruit object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.color != null) { + yield r'color'; + yield serializers.serialize( + object.color, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Fruit object, { + FullType specifiedType = FullType.unspecified, + }) { + final oneOf = object.oneOf; + final result = _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + result.addAll(serializers.serialize(oneOf.value, specifiedType: FullType(oneOf.valueType)) as Iterable); + return result; + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required FruitBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'color': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.color = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Fruit deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = FruitBuilder(); + Object? oneOfDataSrc; + final targetType = const FullType(OneOf, [FullType(Apple), FullType(Banana), ]); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + oneOfDataSrc = unhandled; + result.oneOf = serializers.deserialize(oneOfDataSrc, specifiedType: targetType) as OneOf; + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/serializers.dart new file mode 100644 index 0000000000..ddb1d66a1f --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/lib/src/serializers.dart @@ -0,0 +1,36 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_import + +import 'package:one_of_serializer/any_of_serializer.dart'; +import 'package:one_of_serializer/one_of_serializer.dart'; +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/json_object.dart'; +import 'package:built_value/serializer.dart'; +import 'package:built_value/standard_json_plugin.dart'; +import 'package:built_value/iso_8601_date_time_serializer.dart'; +import 'package:openapi/src/date_serializer.dart'; +import 'package:openapi/src/model/date.dart'; + +import 'package:openapi/src/model/apple.dart'; +import 'package:openapi/src/model/banana.dart'; +import 'package:openapi/src/model/fruit.dart'; + +part 'serializers.g.dart'; + +@SerializersFor([ + Apple, + Banana, + Fruit, +]) +Serializers serializers = (_$serializers.toBuilder() + ..add(const OneOfSerializer()) + ..add(const AnyOfSerializer()) + ..add(const DateSerializer()) + ..add(Iso8601DateTimeSerializer())) + .build(); + +Serializers standardSerializers = + (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(); diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/pom.xml b/samples/openapi3/client/petstore/dart-dio/oneof/pom.xml new file mode 100644 index 0000000000..810c7d48d7 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/pom.xml @@ -0,0 +1,88 @@ + + 4.0.0 + org.openapitools + DartDioOneOf + pom + 1.0.0-SNAPSHOT + DartDio OneOf + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + pub-get + pre-integration-test + + exec + + + pub + + get + + + + + pub-run-build-runner + pre-integration-test + + exec + + + pub + + run + build_runner + build + + + + + dart-analyze + integration-test + + exec + + + dart + + analyze + --fatal-infos + + + + + dart-test + integration-test + + exec + + + dart + + test + + + + + + + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/oneof/pubspec.yaml new file mode 100644 index 0000000000..fb676f65c3 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/pubspec.yaml @@ -0,0 +1,19 @@ +name: openapi +version: 1.0.0 +description: OpenAPI API client +homepage: homepage + +environment: + sdk: '>=2.12.0 <3.0.0' + +dependencies: + dio: '>=4.0.1 <5.0.0' + one_of: '>=1.5.0 <2.0.0' + one_of_serializer: '>=1.5.0 <2.0.0' + built_value: '>=8.4.0 <9.0.0' + built_collection: '>=5.1.1 <6.0.0' + +dev_dependencies: + built_value_generator: '>=8.4.0 <9.0.0' + build_runner: any + test: ^1.16.0 diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/test/apple_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof/test/apple_test.dart new file mode 100644 index 0000000000..1d54216955 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/test/apple_test.dart @@ -0,0 +1,16 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Apple +void main() { + final instance = AppleBuilder(); + // TODO add properties to the builder and call build() + + group(Apple, () { + // String kind + test('to test the property `kind`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/test/banana_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof/test/banana_test.dart new file mode 100644 index 0000000000..a883acc0a9 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/test/banana_test.dart @@ -0,0 +1,16 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Banana +void main() { + final instance = BananaBuilder(); + // TODO add properties to the builder and call build() + + group(Banana, () { + // num count + test('to test the property `count`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/test/default_api_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof/test/default_api_test.dart new file mode 100644 index 0000000000..07d256d2e5 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/test/default_api_test.dart @@ -0,0 +1,16 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + + +/// tests for DefaultApi +void main() { + final instance = Openapi().getDefaultApi(); + + group(DefaultApi, () { + //Future rootGet() async + test('test rootGet', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/test/fruit_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof/test/fruit_test.dart new file mode 100644 index 0000000000..c18790ae95 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof/test/fruit_test.dart @@ -0,0 +1,26 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Fruit +void main() { + final instance = FruitBuilder(); + // TODO add properties to the builder and call build() + + group(Fruit, () { + // String color + test('to test the property `color`', () async { + // TODO + }); + + // String kind + test('to test the property `kind`', () async { + // TODO + }); + + // num count + test('to test the property `count`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.gitignore b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.gitignore new file mode 100644 index 0000000000..4298cdcbd1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.gitignore @@ -0,0 +1,41 @@ +# See https://dart.dev/guides/libraries/private-files + +# Files and directories created by pub +.dart_tool/ +.buildlog +.packages +.project +.pub/ +build/ +**/packages/ + +# Files created by dart2js +# (Most Dart developers will use pub build to compile Dart, use/modify these +# rules if you intend to use dart2js directly +# Convention is to use extension '.dart.js' for Dart compiled to Javascript to +# differentiate from explicit Javascript files) +*.dart.js +*.part.js +*.js.deps +*.js.map +*.info.json + +# Directory created by dartdoc +doc/api/ + +# Don't commit pubspec lock file +# (Library packages only! Remove pattern if developing an application package) +pubspec.lock + +# Don’t commit files and directories created by other development environments. +# For example, if your development environment creates any of the following files, +# consider putting them in a global ignore file: + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator-ignore b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.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/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/FILES b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/FILES new file mode 100644 index 0000000000..52a900a196 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/FILES @@ -0,0 +1,47 @@ +.gitignore +README.md +analysis_options.yaml +doc/Addressable.md +doc/Bar.md +doc/BarApi.md +doc/BarCreate.md +doc/BarRef.md +doc/BarRefOrValue.md +doc/Entity.md +doc/EntityRef.md +doc/Extensible.md +doc/Foo.md +doc/FooApi.md +doc/FooRef.md +doc/FooRefOrValue.md +doc/Pasta.md +doc/Pizza.md +doc/PizzaSpeziale.md +lib/openapi.dart +lib/src/api.dart +lib/src/api/bar_api.dart +lib/src/api/foo_api.dart +lib/src/api_util.dart +lib/src/auth/api_key_auth.dart +lib/src/auth/auth.dart +lib/src/auth/basic_auth.dart +lib/src/auth/bearer_auth.dart +lib/src/auth/oauth.dart +lib/src/date_serializer.dart +lib/src/model/addressable.dart +lib/src/model/bar.dart +lib/src/model/bar_create.dart +lib/src/model/bar_ref.dart +lib/src/model/bar_ref_or_value.dart +lib/src/model/date.dart +lib/src/model/entity.dart +lib/src/model/entity_ref.dart +lib/src/model/extensible.dart +lib/src/model/foo.dart +lib/src/model/foo_ref.dart +lib/src/model/foo_ref_or_value.dart +lib/src/model/pasta.dart +lib/src/model/pizza.dart +lib/src/model/pizza_speziale.dart +lib/src/serializers.dart +pubspec.yaml diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/README.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/README.md new file mode 100644 index 0000000000..6a3fea771a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/README.md @@ -0,0 +1,99 @@ +# openapi (EXPERIMENTAL) +This tests for a oneOf interface representation + + +This Dart package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 0.0.1 +- Build package: org.openapitools.codegen.languages.DartDioClientCodegen + +## Requirements + +* Dart 2.12.0 or later OR Flutter 1.26.0 or later +* Dio 4.0.0+ + +## Installation & Usage + +### pub.dev +To use the package from [pub.dev](https://pub.dev), please include the following in pubspec.yaml +```yaml +dependencies: + openapi: 1.0.0 +``` + +### Github +If this Dart package is published to Github, please include the following in pubspec.yaml +```yaml +dependencies: + openapi: + git: + url: https://github.com/GIT_USER_ID/GIT_REPO_ID.git + #ref: main +``` + +### Local development +To use the package from your local drive, please include the following in pubspec.yaml +```yaml +dependencies: + openapi: + path: /path/to/openapi +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```dart +import 'package:openapi/openapi.dart'; + + +final api = Openapi().getBarApi(); +final BarCreate barCreate = ; // BarCreate | + +try { + final response = await api.createBar(barCreate); + print(response); +} catch on DioError (e) { + print("Exception when calling BarApi->createBar: $e\n"); +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost:8080* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +[*BarApi*](doc/BarApi.md) | [**createBar**](doc/BarApi.md#createbar) | **POST** /bar | Create a Bar +[*FooApi*](doc/FooApi.md) | [**createFoo**](doc/FooApi.md#createfoo) | **POST** /foo | Create a Foo +[*FooApi*](doc/FooApi.md) | [**getAllFoos**](doc/FooApi.md#getallfoos) | **GET** /foo | GET all Foos + + +## Documentation For Models + + - [Addressable](doc/Addressable.md) + - [Bar](doc/Bar.md) + - [BarCreate](doc/BarCreate.md) + - [BarRef](doc/BarRef.md) + - [BarRefOrValue](doc/BarRefOrValue.md) + - [Entity](doc/Entity.md) + - [EntityRef](doc/EntityRef.md) + - [Extensible](doc/Extensible.md) + - [Foo](doc/Foo.md) + - [FooRef](doc/FooRef.md) + - [FooRefOrValue](doc/FooRefOrValue.md) + - [Pasta](doc/Pasta.md) + - [Pizza](doc/Pizza.md) + - [PizzaSpeziale](doc/PizzaSpeziale.md) + + +## Documentation For Authorization + + All endpoints do not require authorization. + + +## Author + + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/analysis_options.yaml new file mode 100644 index 0000000000..a611887d3a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/analysis_options.yaml @@ -0,0 +1,9 @@ +analyzer: + language: + strict-inference: true + strict-raw-types: true + strong-mode: + implicit-dynamic: false + implicit-casts: false + exclude: + - test/*.dart diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Addressable.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Addressable.md new file mode 100644 index 0000000000..0fcd81b803 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Addressable.md @@ -0,0 +1,16 @@ +# openapi.model.Addressable + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Bar.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Bar.md new file mode 100644 index 0000000000..4cccc863a4 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Bar.md @@ -0,0 +1,22 @@ +# openapi.model.Bar + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | | +**barPropA** | **String** | | [optional] +**fooPropB** | **String** | | [optional] +**foo** | [**FooRefOrValue**](FooRefOrValue.md) | | [optional] +**href** | **String** | Hyperlink reference | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarApi.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarApi.md new file mode 100644 index 0000000000..3ef168ecf3 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarApi.md @@ -0,0 +1,55 @@ +# openapi.api.BarApi + +## Load the API package +```dart +import 'package:openapi/api.dart'; +``` + +All URIs are relative to *http://localhost:8080* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createBar**](BarApi.md#createbar) | **POST** /bar | Create a Bar + + +# **createBar** +> Bar createBar(barCreate) + +Create a Bar + +### Example +```dart +import 'package:openapi/api.dart'; + +final api = Openapi().getBarApi(); +final BarCreate barCreate = ; // BarCreate | + +try { + final response = api.createBar(barCreate); + print(response); +} catch on DioError (e) { + print('Exception when calling BarApi->createBar: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **barCreate** | [**BarCreate**](BarCreate.md)| | + +### Return type + +[**Bar**](Bar.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarCreate.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarCreate.md new file mode 100644 index 0000000000..c0b4ba6edc --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarCreate.md @@ -0,0 +1,22 @@ +# openapi.model.BarCreate + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**barPropA** | **String** | | [optional] +**fooPropB** | **String** | | [optional] +**foo** | [**FooRefOrValue**](FooRefOrValue.md) | | [optional] +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRef.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRef.md new file mode 100644 index 0000000000..949695f4d3 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRef.md @@ -0,0 +1,19 @@ +# openapi.model.BarRef + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRefOrValue.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRefOrValue.md new file mode 100644 index 0000000000..9dafa2d6b2 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRefOrValue.md @@ -0,0 +1,19 @@ +# openapi.model.BarRefOrValue + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Entity.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Entity.md new file mode 100644 index 0000000000..5ba2144b44 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Entity.md @@ -0,0 +1,19 @@ +# openapi.model.Entity + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/EntityRef.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/EntityRef.md new file mode 100644 index 0000000000..80eae55f41 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/EntityRef.md @@ -0,0 +1,21 @@ +# openapi.model.EntityRef + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | Name of the related entity. | [optional] +**atReferredType** | **String** | The actual type of the target instance when needed for disambiguation. | [optional] +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Extensible.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Extensible.md new file mode 100644 index 0000000000..7a781e578e --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Extensible.md @@ -0,0 +1,17 @@ +# openapi.model.Extensible + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Foo.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Foo.md new file mode 100644 index 0000000000..2627691fef --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Foo.md @@ -0,0 +1,21 @@ +# openapi.model.Foo + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**fooPropA** | **String** | | [optional] +**fooPropB** | **String** | | [optional] +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooApi.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooApi.md new file mode 100644 index 0000000000..9e8990ebb8 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooApi.md @@ -0,0 +1,93 @@ +# openapi.api.FooApi + +## Load the API package +```dart +import 'package:openapi/api.dart'; +``` + +All URIs are relative to *http://localhost:8080* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createFoo**](FooApi.md#createfoo) | **POST** /foo | Create a Foo +[**getAllFoos**](FooApi.md#getallfoos) | **GET** /foo | GET all Foos + + +# **createFoo** +> FooRefOrValue createFoo(foo) + +Create a Foo + +### Example +```dart +import 'package:openapi/api.dart'; + +final api = Openapi().getFooApi(); +final Foo foo = ; // Foo | The Foo to be created + +try { + final response = api.createFoo(foo); + print(response); +} catch on DioError (e) { + print('Exception when calling FooApi->createFoo: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **foo** | [**Foo**](Foo.md)| The Foo to be created | [optional] + +### Return type + +[**FooRefOrValue**](FooRefOrValue.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json;charset=utf-8 + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getAllFoos** +> BuiltList getAllFoos() + +GET all Foos + +### Example +```dart +import 'package:openapi/api.dart'; + +final api = Openapi().getFooApi(); + +try { + final response = api.getAllFoos(); + print(response); +} catch on DioError (e) { + print('Exception when calling FooApi->getAllFoos: $e\n'); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**BuiltList<FooRefOrValue>**](FooRefOrValue.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json;charset=utf-8 + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRef.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRef.md new file mode 100644 index 0000000000..68104b2272 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRef.md @@ -0,0 +1,20 @@ +# openapi.model.FooRef + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foorefPropA** | **String** | | [optional] +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValue.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValue.md new file mode 100644 index 0000000000..35e9fd114e --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValue.md @@ -0,0 +1,19 @@ +# openapi.model.FooRefOrValue + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValueWithProperties.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValueWithProperties.md new file mode 100644 index 0000000000..05aa2b0bbc --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValueWithProperties.md @@ -0,0 +1,19 @@ +# openapi.model.FooRefOrValueWithProperties + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Pasta.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Pasta.md new file mode 100644 index 0000000000..034ff420d3 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Pasta.md @@ -0,0 +1,20 @@ +# openapi.model.Pasta + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**vendor** | **String** | | [optional] +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Pizza.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Pizza.md new file mode 100644 index 0000000000..e4b040a6a7 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/Pizza.md @@ -0,0 +1,20 @@ +# openapi.model.Pizza + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pizzaSize** | **num** | | [optional] +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/PizzaSpeziale.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/PizzaSpeziale.md new file mode 100644 index 0000000000..e1d8434c07 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/PizzaSpeziale.md @@ -0,0 +1,20 @@ +# openapi.model.PizzaSpeziale + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**toppings** | **String** | | [optional] +**href** | **String** | Hyperlink reference | [optional] +**id** | **String** | unique identifier | [optional] +**atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] +**atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] +**atType** | **String** | When sub-classing, this defines the sub-class Extensible name | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/openapi.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/openapi.dart new file mode 100644 index 0000000000..ea87a7cb47 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/openapi.dart @@ -0,0 +1,28 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +export 'package:openapi/src/api.dart'; +export 'package:openapi/src/auth/api_key_auth.dart'; +export 'package:openapi/src/auth/basic_auth.dart'; +export 'package:openapi/src/auth/oauth.dart'; +export 'package:openapi/src/serializers.dart'; +export 'package:openapi/src/model/date.dart'; + +export 'package:openapi/src/api/bar_api.dart'; +export 'package:openapi/src/api/foo_api.dart'; + +export 'package:openapi/src/model/addressable.dart'; +export 'package:openapi/src/model/bar.dart'; +export 'package:openapi/src/model/bar_create.dart'; +export 'package:openapi/src/model/bar_ref.dart'; +export 'package:openapi/src/model/bar_ref_or_value.dart'; +export 'package:openapi/src/model/entity.dart'; +export 'package:openapi/src/model/entity_ref.dart'; +export 'package:openapi/src/model/extensible.dart'; +export 'package:openapi/src/model/foo.dart'; +export 'package:openapi/src/model/foo_ref.dart'; +export 'package:openapi/src/model/foo_ref_or_value.dart'; +export 'package:openapi/src/model/pasta.dart'; +export 'package:openapi/src/model/pizza.dart'; +export 'package:openapi/src/model/pizza_speziale.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api.dart new file mode 100644 index 0000000000..0bb368eace --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api.dart @@ -0,0 +1,80 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; +import 'package:built_value/serializer.dart'; +import 'package:openapi/src/serializers.dart'; +import 'package:openapi/src/auth/api_key_auth.dart'; +import 'package:openapi/src/auth/basic_auth.dart'; +import 'package:openapi/src/auth/bearer_auth.dart'; +import 'package:openapi/src/auth/oauth.dart'; +import 'package:openapi/src/api/bar_api.dart'; +import 'package:openapi/src/api/foo_api.dart'; + +class Openapi { + static const String basePath = r'http://localhost:8080'; + + final Dio dio; + final Serializers serializers; + + Openapi({ + Dio? dio, + Serializers? serializers, + String? basePathOverride, + List? interceptors, + }) : this.serializers = serializers ?? standardSerializers, + this.dio = dio ?? + Dio(BaseOptions( + baseUrl: basePathOverride ?? basePath, + connectTimeout: 5000, + receiveTimeout: 3000, + )) { + if (interceptors == null) { + this.dio.interceptors.addAll([ + OAuthInterceptor(), + BasicAuthInterceptor(), + BearerAuthInterceptor(), + ApiKeyAuthInterceptor(), + ]); + } else { + this.dio.interceptors.addAll(interceptors); + } + } + + void setOAuthToken(String name, String token) { + if (this.dio.interceptors.any((i) => i is OAuthInterceptor)) { + (this.dio.interceptors.firstWhere((i) => i is OAuthInterceptor) as OAuthInterceptor).tokens[name] = token; + } + } + + void setBearerAuth(String name, String token) { + if (this.dio.interceptors.any((i) => i is BearerAuthInterceptor)) { + (this.dio.interceptors.firstWhere((i) => i is BearerAuthInterceptor) as BearerAuthInterceptor).tokens[name] = token; + } + } + + void setBasicAuth(String name, String username, String password) { + if (this.dio.interceptors.any((i) => i is BasicAuthInterceptor)) { + (this.dio.interceptors.firstWhere((i) => i is BasicAuthInterceptor) as BasicAuthInterceptor).authInfo[name] = BasicAuthInfo(username, password); + } + } + + void setApiKey(String name, String apiKey) { + if (this.dio.interceptors.any((i) => i is ApiKeyAuthInterceptor)) { + (this.dio.interceptors.firstWhere((element) => element is ApiKeyAuthInterceptor) as ApiKeyAuthInterceptor).apiKeys[name] = apiKey; + } + } + + /// Get BarApi instance, base route and serializer can be overridden by a given but be careful, + /// by doing that all interceptors will not be executed + BarApi getBarApi() { + return BarApi(dio, serializers); + } + + /// Get FooApi instance, base route and serializer can be overridden by a given but be careful, + /// by doing that all interceptors will not be executed + FooApi getFooApi() { + return FooApi(dio, serializers); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api/bar_api.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api/bar_api.dart new file mode 100644 index 0000000000..4afe604a55 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api/bar_api.dart @@ -0,0 +1,114 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:async'; + +import 'package:built_value/serializer.dart'; +import 'package:dio/dio.dart'; + +import 'package:openapi/src/model/bar.dart'; +import 'package:openapi/src/model/bar_create.dart'; + +class BarApi { + + final Dio _dio; + + final Serializers _serializers; + + const BarApi(this._dio, this._serializers); + + /// Create a Bar + /// + /// + /// Parameters: + /// * [barCreate] + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [Bar] as data + /// Throws [DioError] if API call or serialization fails + Future> createBar({ + required BarCreate barCreate, + CancelToken? cancelToken, + Map? headers, + Map? extra, + ValidateStatus? validateStatus, + ProgressCallback? onSendProgress, + ProgressCallback? onReceiveProgress, + }) async { + final _path = r'/bar'; + final _options = Options( + method: r'POST', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + contentType: 'application/json', + validateStatus: validateStatus, + ); + + dynamic _bodyData; + + try { + const _type = FullType(BarCreate); + _bodyData = _serializers.serialize(barCreate, specifiedType: _type); + + } catch(error, stackTrace) { + throw DioError( + requestOptions: _options.compose( + _dio.options, + _path, + ), + type: DioErrorType.other, + error: error, + )..stackTrace = stackTrace; + } + + final _response = await _dio.request( + _path, + data: _bodyData, + options: _options, + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + Bar _responseData; + + try { + const _responseType = FullType(Bar); + _responseData = _serializers.deserialize( + _response.data!, + specifiedType: _responseType, + ) as Bar; + + } catch (error, stackTrace) { + throw DioError( + requestOptions: _response.requestOptions, + response: _response, + type: DioErrorType.other, + error: error, + )..stackTrace = stackTrace; + } + + return Response( + data: _responseData, + headers: _response.headers, + isRedirect: _response.isRedirect, + requestOptions: _response.requestOptions, + redirects: _response.redirects, + statusCode: _response.statusCode, + statusMessage: _response.statusMessage, + extra: _response.extra, + ); + } + +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api/foo_api.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api/foo_api.dart new file mode 100644 index 0000000000..232392c76a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api/foo_api.dart @@ -0,0 +1,187 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:async'; + +import 'package:built_value/serializer.dart'; +import 'package:dio/dio.dart'; + +import 'package:built_collection/built_collection.dart'; +import 'package:openapi/src/model/foo.dart'; +import 'package:openapi/src/model/foo_ref_or_value.dart'; + +class FooApi { + + final Dio _dio; + + final Serializers _serializers; + + const FooApi(this._dio, this._serializers); + + /// Create a Foo + /// + /// + /// Parameters: + /// * [foo] - The Foo to be created + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [FooRefOrValue] as data + /// Throws [DioError] if API call or serialization fails + Future> createFoo({ + Foo? foo, + CancelToken? cancelToken, + Map? headers, + Map? extra, + ValidateStatus? validateStatus, + ProgressCallback? onSendProgress, + ProgressCallback? onReceiveProgress, + }) async { + final _path = r'/foo'; + final _options = Options( + method: r'POST', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + contentType: 'application/json;charset=utf-8', + validateStatus: validateStatus, + ); + + dynamic _bodyData; + + try { + const _type = FullType(Foo); + _bodyData = foo == null ? null : _serializers.serialize(foo, specifiedType: _type); + + } catch(error, stackTrace) { + throw DioError( + requestOptions: _options.compose( + _dio.options, + _path, + ), + type: DioErrorType.other, + error: error, + )..stackTrace = stackTrace; + } + + final _response = await _dio.request( + _path, + data: _bodyData, + options: _options, + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + FooRefOrValue _responseData; + + try { + const _responseType = FullType(FooRefOrValue); + _responseData = _serializers.deserialize( + _response.data!, + specifiedType: _responseType, + ) as FooRefOrValue; + + } catch (error, stackTrace) { + throw DioError( + requestOptions: _response.requestOptions, + response: _response, + type: DioErrorType.other, + error: error, + )..stackTrace = stackTrace; + } + + return Response( + data: _responseData, + headers: _response.headers, + isRedirect: _response.isRedirect, + requestOptions: _response.requestOptions, + redirects: _response.redirects, + statusCode: _response.statusCode, + statusMessage: _response.statusMessage, + extra: _response.extra, + ); + } + + /// GET all Foos + /// + /// + /// Parameters: + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [BuiltList] as data + /// Throws [DioError] if API call or serialization fails + Future>> getAllFoos({ + CancelToken? cancelToken, + Map? headers, + Map? extra, + ValidateStatus? validateStatus, + ProgressCallback? onSendProgress, + ProgressCallback? onReceiveProgress, + }) async { + final _path = r'/foo'; + final _options = Options( + method: r'GET', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + validateStatus: validateStatus, + ); + + final _response = await _dio.request( + _path, + options: _options, + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + BuiltList _responseData; + + try { + const _responseType = FullType(BuiltList, [FullType(FooRefOrValue)]); + _responseData = _serializers.deserialize( + _response.data!, + specifiedType: _responseType, + ) as BuiltList; + + } catch (error, stackTrace) { + throw DioError( + requestOptions: _response.requestOptions, + response: _response, + type: DioErrorType.other, + error: error, + )..stackTrace = stackTrace; + } + + return Response>( + data: _responseData, + headers: _response.headers, + isRedirect: _response.isRedirect, + requestOptions: _response.requestOptions, + redirects: _response.redirects, + statusCode: _response.statusCode, + statusMessage: _response.statusMessage, + extra: _response.extra, + ); + } + +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api_util.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api_util.dart new file mode 100644 index 0000000000..ed3bb12f25 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/api_util.dart @@ -0,0 +1,77 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:dio/dio.dart'; + +/// Format the given form parameter object into something that Dio can handle. +/// Returns primitive or String. +/// Returns List/Map if the value is BuildList/BuiltMap. +dynamic encodeFormParameter(Serializers serializers, dynamic value, FullType type) { + if (value == null) { + return ''; + } + if (value is String || value is num || value is bool) { + return value; + } + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (serialized is String) { + return serialized; + } + if (value is BuiltList || value is BuiltSet || value is BuiltMap) { + return serialized; + } + return json.encode(serialized); +} + +dynamic encodeQueryParameter( + Serializers serializers, + dynamic value, + FullType type, +) { + if (value == null) { + return ''; + } + if (value is String || value is num || value is bool) { + return value; + } + if (value is Uint8List) { + // Currently not sure how to serialize this + return value; + } + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (serialized == null) { + return ''; + } + if (serialized is String) { + return serialized; + } + return serialized; +} + +ListParam encodeCollectionQueryParameter( + Serializers serializers, + dynamic value, + FullType type, { + ListFormat format = ListFormat.multi, +}) { + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (value is BuiltList || value is BuiltSet) { + return ListParam(List.of((serialized as Iterable).cast()), format); + } + throw ArgumentError('Invalid value passed to encodeCollectionQueryParameter'); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/api_key_auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/api_key_auth.dart new file mode 100644 index 0000000000..ee16e3f0f9 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/api_key_auth.dart @@ -0,0 +1,30 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class ApiKeyAuthInterceptor extends AuthInterceptor { + final Map apiKeys = {}; + + @override + void onRequest(RequestOptions options, RequestInterceptorHandler handler) { + final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'apiKey'); + for (final info in authInfo) { + final authName = info['name'] as String; + final authKeyName = info['keyName'] as String; + final authWhere = info['where'] as String; + final apiKey = apiKeys[authName]; + if (apiKey != null) { + if (authWhere == 'query') { + options.queryParameters[authKeyName] = apiKey; + } else { + options.headers[authKeyName] = apiKey; + } + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/auth.dart new file mode 100644 index 0000000000..f7ae9bf3f1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/auth.dart @@ -0,0 +1,18 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; + +abstract class AuthInterceptor extends Interceptor { + /// Get auth information on given route for the given type. + /// Can return an empty list if type is not present on auth data or + /// if route doesn't need authentication. + List> getAuthInfo(RequestOptions route, bool Function(Map secure) handles) { + if (route.extra.containsKey('secure')) { + final auth = route.extra['secure'] as List>; + return auth.where((secure) => handles(secure)).toList(); + } + return []; + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/basic_auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/basic_auth.dart new file mode 100644 index 0000000000..b6e6dce04f --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/basic_auth.dart @@ -0,0 +1,37 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:convert'; + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class BasicAuthInfo { + final String username; + final String password; + + const BasicAuthInfo(this.username, this.password); +} + +class BasicAuthInterceptor extends AuthInterceptor { + final Map authInfo = {}; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) { + final metadataAuthInfo = getAuthInfo(options, (secure) => (secure['type'] == 'http' && secure['scheme'] == 'basic') || secure['type'] == 'basic'); + for (final info in metadataAuthInfo) { + final authName = info['name'] as String; + final basicAuthInfo = authInfo[authName]; + if (basicAuthInfo != null) { + final basicAuth = 'Basic ${base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}'))}'; + options.headers['Authorization'] = basicAuth; + break; + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/bearer_auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/bearer_auth.dart new file mode 100644 index 0000000000..1d4402b376 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/bearer_auth.dart @@ -0,0 +1,26 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class BearerAuthInterceptor extends AuthInterceptor { + final Map tokens = {}; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) { + final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'http' && secure['scheme'] == 'bearer'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; + break; + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/oauth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/oauth.dart new file mode 100644 index 0000000000..337cf762b0 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/auth/oauth.dart @@ -0,0 +1,26 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class OAuthInterceptor extends AuthInterceptor { + final Map tokens = {}; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) { + final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'oauth' || secure['type'] == 'oauth2'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; + break; + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/date_serializer.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/date_serializer.dart new file mode 100644 index 0000000000..db3c5c437d --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/date_serializer.dart @@ -0,0 +1,31 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:openapi/src/model/date.dart'; + +class DateSerializer implements PrimitiveSerializer { + + const DateSerializer(); + + @override + Iterable get types => BuiltList.of([Date]); + + @override + String get wireName => 'Date'; + + @override + Date deserialize(Serializers serializers, Object serialized, + {FullType specifiedType = FullType.unspecified}) { + final parsed = DateTime.parse(serialized as String); + return Date(parsed.year, parsed.month, parsed.day); + } + + @override + Object serialize(Serializers serializers, Date date, + {FullType specifiedType = FullType.unspecified}) { + return date.toString(); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/addressable.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/addressable.dart new file mode 100644 index 0000000000..e0311b6595 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/addressable.dart @@ -0,0 +1,161 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'addressable.g.dart'; + +/// Base schema for adressable entities +/// +/// Properties: +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +@BuiltValue(instantiable: false) +abstract class Addressable { + /// Hyperlink reference + @BuiltValueField(wireName: r'href') + String? get href; + + /// unique identifier + @BuiltValueField(wireName: r'id') + String? get id; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$AddressableSerializer(); +} + +class _$AddressableSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Addressable]; + + @override + final String wireName = r'Addressable'; + + Iterable _serializeProperties( + Serializers serializers, + Addressable object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Addressable object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + @override + Addressable deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.deserialize(serialized, specifiedType: FullType($Addressable)) as $Addressable; + } +} + +/// a concrete implementation of [Addressable], since [Addressable] is not instantiable +@BuiltValue(instantiable: true) +abstract class $Addressable implements Addressable, Built<$Addressable, $AddressableBuilder> { + $Addressable._(); + + factory $Addressable([void Function($AddressableBuilder)? updates]) = _$$Addressable; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults($AddressableBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer<$Addressable> get serializer => _$$AddressableSerializer(); +} + +class _$$AddressableSerializer implements PrimitiveSerializer<$Addressable> { + @override + final Iterable types = const [$Addressable, _$$Addressable]; + + @override + final String wireName = r'$Addressable'; + + @override + Object serialize( + Serializers serializers, + $Addressable object, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.serialize(object, specifiedType: FullType(Addressable))!; + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required AddressableBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + $Addressable deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = $AddressableBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar.dart new file mode 100644 index 0000000000..9c52802b84 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar.dart @@ -0,0 +1,221 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/foo_ref_or_value.dart'; +import 'package:openapi/src/model/entity.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'bar.g.dart'; + +/// Bar +/// +/// Properties: +/// * [id] +/// * [barPropA] +/// * [fooPropB] +/// * [foo] +/// * [href] - Hyperlink reference +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue() +abstract class Bar implements Entity, Built { + @BuiltValueField(wireName: r'foo') + FooRefOrValue? get foo; + + @BuiltValueField(wireName: r'fooPropB') + String? get fooPropB; + + @BuiltValueField(wireName: r'barPropA') + String? get barPropA; + + static const String discriminatorFieldName = r'atType'; + + Bar._(); + + factory Bar([void updates(BarBuilder b)]) = _$Bar; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(BarBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$BarSerializer(); +} + +class _$BarSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Bar, _$Bar]; + + @override + final String wireName = r'Bar'; + + Iterable _serializeProperties( + Serializers serializers, + Bar object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.foo != null) { + yield r'foo'; + yield serializers.serialize( + object.foo, + specifiedType: const FullType(FooRefOrValue), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.fooPropB != null) { + yield r'fooPropB'; + yield serializers.serialize( + object.fooPropB, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + if (object.barPropA != null) { + yield r'barPropA'; + yield serializers.serialize( + object.barPropA, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Bar object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required BarBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'foo': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(FooRefOrValue), + ) as FooRefOrValue; + result.foo.replace(valueDes); + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'fooPropB': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.fooPropB = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + case r'barPropA': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.barPropA = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Bar deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = BarBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_create.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_create.dart new file mode 100644 index 0000000000..ebbce35778 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_create.dart @@ -0,0 +1,221 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/foo_ref_or_value.dart'; +import 'package:openapi/src/model/entity.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'bar_create.g.dart'; + +/// BarCreate +/// +/// Properties: +/// * [barPropA] +/// * [fooPropB] +/// * [foo] +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue() +abstract class BarCreate implements Entity, Built { + @BuiltValueField(wireName: r'foo') + FooRefOrValue? get foo; + + @BuiltValueField(wireName: r'fooPropB') + String? get fooPropB; + + @BuiltValueField(wireName: r'barPropA') + String? get barPropA; + + static const String discriminatorFieldName = r'atType'; + + BarCreate._(); + + factory BarCreate([void updates(BarCreateBuilder b)]) = _$BarCreate; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(BarCreateBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$BarCreateSerializer(); +} + +class _$BarCreateSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [BarCreate, _$BarCreate]; + + @override + final String wireName = r'BarCreate'; + + Iterable _serializeProperties( + Serializers serializers, + BarCreate object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.foo != null) { + yield r'foo'; + yield serializers.serialize( + object.foo, + specifiedType: const FullType(FooRefOrValue), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.fooPropB != null) { + yield r'fooPropB'; + yield serializers.serialize( + object.fooPropB, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + if (object.barPropA != null) { + yield r'barPropA'; + yield serializers.serialize( + object.barPropA, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + BarCreate object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required BarCreateBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'foo': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(FooRefOrValue), + ) as FooRefOrValue; + result.foo.replace(valueDes); + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'fooPropB': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.fooPropB = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + case r'barPropA': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.barPropA = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + BarCreate deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = BarCreateBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref.dart new file mode 100644 index 0000000000..bb4965bea8 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref.dart @@ -0,0 +1,194 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/entity_ref.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'bar_ref.g.dart'; + +/// BarRef +/// +/// Properties: +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue() +abstract class BarRef implements EntityRef, Built { + static const String discriminatorFieldName = r'atType'; + + BarRef._(); + + factory BarRef([void updates(BarRefBuilder b)]) = _$BarRef; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(BarRefBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$BarRefSerializer(); +} + +class _$BarRefSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [BarRef, _$BarRef]; + + @override + final String wireName = r'BarRef'; + + Iterable _serializeProperties( + Serializers serializers, + BarRef object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.atReferredType != null) { + yield r'@referredType'; + yield serializers.serialize( + object.atReferredType, + specifiedType: const FullType(String), + ); + } + if (object.name != null) { + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(String), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + } + + @override + Object serialize( + Serializers serializers, + BarRef object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required BarRefBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'@referredType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atReferredType = valueDes; + break; + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.name = valueDes; + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + BarRef deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = BarRefBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref_or_value.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref_or_value.dart new file mode 100644 index 0000000000..09d7b0b99c --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref_or_value.dart @@ -0,0 +1,106 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/bar_ref.dart'; +import 'package:openapi/src/model/bar.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; +import 'package:one_of/one_of.dart'; + +part 'bar_ref_or_value.g.dart'; + +/// BarRefOrValue +/// +/// Properties: +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue() +abstract class BarRefOrValue implements Built { + /// One Of [Bar], [BarRef] + OneOf get oneOf; + + static const String discriminatorFieldName = r'atType'; + + static const Map discriminatorMapping = { + r'Bar': Bar, + r'BarRef': BarRef, + }; + + BarRefOrValue._(); + + factory BarRefOrValue([void updates(BarRefOrValueBuilder b)]) = _$BarRefOrValue; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(BarRefOrValueBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$BarRefOrValueSerializer(); +} + +class _$BarRefOrValueSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [BarRefOrValue, _$BarRefOrValue]; + + @override + final String wireName = r'BarRefOrValue'; + + Iterable _serializeProperties( + Serializers serializers, + BarRefOrValue object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + } + + @override + Object serialize( + Serializers serializers, + BarRefOrValue object, { + FullType specifiedType = FullType.unspecified, + }) { + final oneOf = object.oneOf; + return serializers.serialize(oneOf.value, specifiedType: FullType(oneOf.valueType))!; + } + + @override + BarRefOrValue deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = BarRefOrValueBuilder(); + Object? oneOfDataSrc; + final serializedList = (serialized as Iterable).toList(); + final discIndex = serializedList.indexOf(BarRefOrValue.discriminatorFieldName) + 1; + final discValue = serializers.deserialize(serializedList[discIndex], specifiedType: FullType(String)) as String; + oneOfDataSrc = serialized; + final oneOfTypes = [Bar, BarRef, ]; + Object oneOfResult; + Type oneOfType; + switch (discValue) { + case 'Bar': + oneOfResult = serializers.deserialize( + oneOfDataSrc, + specifiedType: FullType(Bar), + ) as Bar; + oneOfType = Bar; + break; + case 'BarRef': + oneOfResult = serializers.deserialize( + oneOfDataSrc, + specifiedType: FullType(BarRef), + ) as BarRef; + oneOfType = BarRef; + break; + default: + throw UnsupportedError("Couldn't deserialize oneOf for the discriminator value: ${discValue}"); + } + result.oneOf = OneOfDynamic(typeIndex: oneOfTypes.indexOf(oneOfType), types: oneOfTypes, value: oneOfResult); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/date.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/date.dart new file mode 100644 index 0000000000..b21c7f544b --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/date.dart @@ -0,0 +1,70 @@ +/// A gregorian calendar date generated by +/// OpenAPI generator to differentiate +/// between [DateTime] and [Date] formats. +class Date implements Comparable { + final int year; + + /// January is 1. + final int month; + + /// First day is 1. + final int day; + + Date(this.year, this.month, this.day); + + /// The current date + static Date now({bool utc = false}) { + var now = DateTime.now(); + if (utc) { + now = now.toUtc(); + } + return now.toDate(); + } + + /// Convert to a [DateTime]. + DateTime toDateTime({bool utc = false}) { + if (utc) { + return DateTime.utc(year, month, day); + } else { + return DateTime(year, month, day); + } + } + + @override + int compareTo(Date other) { + int d = year.compareTo(other.year); + if (d != 0) { + return d; + } + d = month.compareTo(other.month); + if (d != 0) { + return d; + } + return day.compareTo(other.day); + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is Date && + runtimeType == other.runtimeType && + year == other.year && + month == other.month && + day == other.day; + + @override + int get hashCode => year.hashCode ^ month.hashCode ^ day.hashCode; + + @override + String toString() { + final yyyy = year.toString(); + final mm = month.toString().padLeft(2, '0'); + final dd = day.toString().padLeft(2, '0'); + + return '$yyyy-$mm-$dd'; + } +} + +extension DateTimeToDate on DateTime { + Date toDate() => Date(year, month, day); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/entity.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/entity.dart new file mode 100644 index 0000000000..1a83a5d6b5 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/entity.dart @@ -0,0 +1,251 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/extensible.dart'; +import 'package:openapi/src/model/pizza_speziale.dart'; +import 'package:openapi/src/model/foo.dart'; +import 'package:openapi/src/model/pizza.dart'; +import 'package:openapi/src/model/addressable.dart'; +import 'package:openapi/src/model/pasta.dart'; +import 'package:openapi/src/model/bar_create.dart'; +import 'package:openapi/src/model/bar.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'entity.g.dart'; + +/// Entity +/// +/// Properties: +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue(instantiable: false) +abstract class Entity implements Addressable, Extensible { + static const String discriminatorFieldName = r'atType'; + + static const Map discriminatorMapping = { + r'Bar': Bar, + r'Bar_Create': BarCreate, + r'Foo': Foo, + r'Pasta': Pasta, + r'Pizza': Pizza, + r'PizzaSpeziale': PizzaSpeziale, + }; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$EntitySerializer(); +} + +class _$EntitySerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Entity]; + + @override + final String wireName = r'Entity'; + + Iterable _serializeProperties( + Serializers serializers, + Entity object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + } + + @override + Object serialize( + Serializers serializers, + Entity object, { + FullType specifiedType = FullType.unspecified, + }) { + if (object is Bar) { + return serializers.serialize(object, specifiedType: FullType(Bar))!; + } + if (object is BarCreate) { + return serializers.serialize(object, specifiedType: FullType(BarCreate))!; + } + if (object is Foo) { + return serializers.serialize(object, specifiedType: FullType(Foo))!; + } + if (object is Pasta) { + return serializers.serialize(object, specifiedType: FullType(Pasta))!; + } + if (object is Pizza) { + return serializers.serialize(object, specifiedType: FullType(Pizza))!; + } + if (object is PizzaSpeziale) { + return serializers.serialize(object, specifiedType: FullType(PizzaSpeziale))!; + } + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + @override + Entity deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final serializedList = (serialized as Iterable).toList(); + final discIndex = serializedList.indexOf(Entity.discriminatorFieldName) + 1; + final discValue = serializers.deserialize(serializedList[discIndex], specifiedType: FullType(String)) as String; + switch (discValue) { + case 'Bar': + return serializers.deserialize(serialized, specifiedType: FullType(Bar)) as Bar; + case 'Bar_Create': + return serializers.deserialize(serialized, specifiedType: FullType(BarCreate)) as BarCreate; + case 'Foo': + return serializers.deserialize(serialized, specifiedType: FullType(Foo)) as Foo; + case 'Pasta': + return serializers.deserialize(serialized, specifiedType: FullType(Pasta)) as Pasta; + case 'Pizza': + return serializers.deserialize(serialized, specifiedType: FullType(Pizza)) as Pizza; + case 'PizzaSpeziale': + return serializers.deserialize(serialized, specifiedType: FullType(PizzaSpeziale)) as PizzaSpeziale; + default: + return serializers.deserialize(serialized, specifiedType: FullType($Entity)) as $Entity; + } + } +} + +/// a concrete implementation of [Entity], since [Entity] is not instantiable +@BuiltValue(instantiable: true) +abstract class $Entity implements Entity, Built<$Entity, $EntityBuilder> { + $Entity._(); + + factory $Entity([void Function($EntityBuilder)? updates]) = _$$Entity; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults($EntityBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer<$Entity> get serializer => _$$EntitySerializer(); +} + +class _$$EntitySerializer implements PrimitiveSerializer<$Entity> { + @override + final Iterable types = const [$Entity, _$$Entity]; + + @override + final String wireName = r'$Entity'; + + @override + Object serialize( + Serializers serializers, + $Entity object, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.serialize(object, specifiedType: FullType(Entity))!; + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required EntityBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + $Entity deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = $EntityBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/entity_ref.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/entity_ref.dart new file mode 100644 index 0000000000..278aa92276 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/entity_ref.dart @@ -0,0 +1,261 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/extensible.dart'; +import 'package:openapi/src/model/bar_ref.dart'; +import 'package:openapi/src/model/addressable.dart'; +import 'package:openapi/src/model/foo_ref.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'entity_ref.g.dart'; + +/// Entity reference schema to be use for all entityRef class. +/// +/// Properties: +/// * [name] - Name of the related entity. +/// * [atReferredType] - The actual type of the target instance when needed for disambiguation. +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue(instantiable: false) +abstract class EntityRef implements Addressable, Extensible { + /// The actual type of the target instance when needed for disambiguation. + @BuiltValueField(wireName: r'@referredType') + String? get atReferredType; + + /// Name of the related entity. + @BuiltValueField(wireName: r'name') + String? get name; + + static const String discriminatorFieldName = r'atType'; + + static const Map discriminatorMapping = { + r'BarRef': BarRef, + r'FooRef': FooRef, + }; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$EntityRefSerializer(); +} + +class _$EntityRefSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [EntityRef]; + + @override + final String wireName = r'EntityRef'; + + Iterable _serializeProperties( + Serializers serializers, + EntityRef object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.atReferredType != null) { + yield r'@referredType'; + yield serializers.serialize( + object.atReferredType, + specifiedType: const FullType(String), + ); + } + if (object.name != null) { + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(String), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + } + + @override + Object serialize( + Serializers serializers, + EntityRef object, { + FullType specifiedType = FullType.unspecified, + }) { + if (object is BarRef) { + return serializers.serialize(object, specifiedType: FullType(BarRef))!; + } + if (object is FooRef) { + return serializers.serialize(object, specifiedType: FullType(FooRef))!; + } + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + @override + EntityRef deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final serializedList = (serialized as Iterable).toList(); + final discIndex = serializedList.indexOf(EntityRef.discriminatorFieldName) + 1; + final discValue = serializers.deserialize(serializedList[discIndex], specifiedType: FullType(String)) as String; + switch (discValue) { + case 'BarRef': + return serializers.deserialize(serialized, specifiedType: FullType(BarRef)) as BarRef; + case 'FooRef': + return serializers.deserialize(serialized, specifiedType: FullType(FooRef)) as FooRef; + default: + return serializers.deserialize(serialized, specifiedType: FullType($EntityRef)) as $EntityRef; + } + } +} + +/// a concrete implementation of [EntityRef], since [EntityRef] is not instantiable +@BuiltValue(instantiable: true) +abstract class $EntityRef implements EntityRef, Built<$EntityRef, $EntityRefBuilder> { + $EntityRef._(); + + factory $EntityRef([void Function($EntityRefBuilder)? updates]) = _$$EntityRef; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults($EntityRefBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer<$EntityRef> get serializer => _$$EntityRefSerializer(); +} + +class _$$EntityRefSerializer implements PrimitiveSerializer<$EntityRef> { + @override + final Iterable types = const [$EntityRef, _$$EntityRef]; + + @override + final String wireName = r'$EntityRef'; + + @override + Object serialize( + Serializers serializers, + $EntityRef object, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.serialize(object, specifiedType: FullType(EntityRef))!; + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required EntityRefBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'@referredType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atReferredType = valueDes; + break; + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.name = valueDes; + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + $EntityRef deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = $EntityRefBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/extensible.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/extensible.dart new file mode 100644 index 0000000000..2423fb2764 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/extensible.dart @@ -0,0 +1,178 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'extensible.g.dart'; + +/// Extensible +/// +/// Properties: +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue(instantiable: false) +abstract class Extensible { + /// A URI to a JSON-Schema file that defines additional attributes and relationships + @BuiltValueField(wireName: r'@schemaLocation') + String? get atSchemaLocation; + + /// When sub-classing, this defines the super-class + @BuiltValueField(wireName: r'@baseType') + String? get atBaseType; + + /// When sub-classing, this defines the sub-class Extensible name + @BuiltValueField(wireName: r'@type') + String get atType; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ExtensibleSerializer(); +} + +class _$ExtensibleSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Extensible]; + + @override + final String wireName = r'Extensible'; + + Iterable _serializeProperties( + Serializers serializers, + Extensible object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + } + + @override + Object serialize( + Serializers serializers, + Extensible object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + @override + Extensible deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.deserialize(serialized, specifiedType: FullType($Extensible)) as $Extensible; + } +} + +/// a concrete implementation of [Extensible], since [Extensible] is not instantiable +@BuiltValue(instantiable: true) +abstract class $Extensible implements Extensible, Built<$Extensible, $ExtensibleBuilder> { + $Extensible._(); + + factory $Extensible([void Function($ExtensibleBuilder)? updates]) = _$$Extensible; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults($ExtensibleBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer<$Extensible> get serializer => _$$ExtensibleSerializer(); +} + +class _$$ExtensibleSerializer implements PrimitiveSerializer<$Extensible> { + @override + final Iterable types = const [$Extensible, _$$Extensible]; + + @override + final String wireName = r'$Extensible'; + + @override + Object serialize( + Serializers serializers, + $Extensible object, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.serialize(object, specifiedType: FullType(Extensible))!; + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ExtensibleBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + $Extensible deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = $ExtensibleBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo.dart new file mode 100644 index 0000000000..efb327dd66 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo.dart @@ -0,0 +1,202 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/entity.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'foo.g.dart'; + +/// Foo +/// +/// Properties: +/// * [fooPropA] +/// * [fooPropB] +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue() +abstract class Foo implements Entity, Built { + @BuiltValueField(wireName: r'fooPropA') + String? get fooPropA; + + @BuiltValueField(wireName: r'fooPropB') + String? get fooPropB; + + static const String discriminatorFieldName = r'atType'; + + Foo._(); + + factory Foo([void updates(FooBuilder b)]) = _$Foo; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(FooBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$FooSerializer(); +} + +class _$FooSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Foo, _$Foo]; + + @override + final String wireName = r'Foo'; + + Iterable _serializeProperties( + Serializers serializers, + Foo object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.fooPropA != null) { + yield r'fooPropA'; + yield serializers.serialize( + object.fooPropA, + specifiedType: const FullType(String), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.fooPropB != null) { + yield r'fooPropB'; + yield serializers.serialize( + object.fooPropB, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + } + + @override + Object serialize( + Serializers serializers, + Foo object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required FooBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'fooPropA': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.fooPropA = valueDes; + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'fooPropB': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.fooPropB = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Foo deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = FooBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref.dart new file mode 100644 index 0000000000..dd05a2d478 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref.dart @@ -0,0 +1,212 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/entity_ref.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'foo_ref.g.dart'; + +/// FooRef +/// +/// Properties: +/// * [foorefPropA] +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue() +abstract class FooRef implements EntityRef, Built { + @BuiltValueField(wireName: r'foorefPropA') + String? get foorefPropA; + + static const String discriminatorFieldName = r'atType'; + + FooRef._(); + + factory FooRef([void updates(FooRefBuilder b)]) = _$FooRef; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(FooRefBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$FooRefSerializer(); +} + +class _$FooRefSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [FooRef, _$FooRef]; + + @override + final String wireName = r'FooRef'; + + Iterable _serializeProperties( + Serializers serializers, + FooRef object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.atReferredType != null) { + yield r'@referredType'; + yield serializers.serialize( + object.atReferredType, + specifiedType: const FullType(String), + ); + } + if (object.foorefPropA != null) { + yield r'foorefPropA'; + yield serializers.serialize( + object.foorefPropA, + specifiedType: const FullType(String), + ); + } + if (object.name != null) { + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(String), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + } + + @override + Object serialize( + Serializers serializers, + FooRef object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required FooRefBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'@referredType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atReferredType = valueDes; + break; + case r'foorefPropA': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.foorefPropA = valueDes; + break; + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.name = valueDes; + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + FooRef deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = FooRefBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref_or_value.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref_or_value.dart new file mode 100644 index 0000000000..f512292196 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref_or_value.dart @@ -0,0 +1,106 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/foo.dart'; +import 'package:openapi/src/model/foo_ref.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; +import 'package:one_of/one_of.dart'; + +part 'foo_ref_or_value.g.dart'; + +/// FooRefOrValue +/// +/// Properties: +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue() +abstract class FooRefOrValue implements Built { + /// One Of [Foo], [FooRef] + OneOf get oneOf; + + static const String discriminatorFieldName = r'atType'; + + static const Map discriminatorMapping = { + r'Foo': Foo, + r'FooRef': FooRef, + }; + + FooRefOrValue._(); + + factory FooRefOrValue([void updates(FooRefOrValueBuilder b)]) = _$FooRefOrValue; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(FooRefOrValueBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$FooRefOrValueSerializer(); +} + +class _$FooRefOrValueSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [FooRefOrValue, _$FooRefOrValue]; + + @override + final String wireName = r'FooRefOrValue'; + + Iterable _serializeProperties( + Serializers serializers, + FooRefOrValue object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + } + + @override + Object serialize( + Serializers serializers, + FooRefOrValue object, { + FullType specifiedType = FullType.unspecified, + }) { + final oneOf = object.oneOf; + return serializers.serialize(oneOf.value, specifiedType: FullType(oneOf.valueType))!; + } + + @override + FooRefOrValue deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = FooRefOrValueBuilder(); + Object? oneOfDataSrc; + final serializedList = (serialized as Iterable).toList(); + final discIndex = serializedList.indexOf(FooRefOrValue.discriminatorFieldName) + 1; + final discValue = serializers.deserialize(serializedList[discIndex], specifiedType: FullType(String)) as String; + oneOfDataSrc = serialized; + final oneOfTypes = [Foo, FooRef, ]; + Object oneOfResult; + Type oneOfType; + switch (discValue) { + case 'Foo': + oneOfResult = serializers.deserialize( + oneOfDataSrc, + specifiedType: FullType(Foo), + ) as Foo; + oneOfType = Foo; + break; + case 'FooRef': + oneOfResult = serializers.deserialize( + oneOfDataSrc, + specifiedType: FullType(FooRef), + ) as FooRef; + oneOfType = FooRef; + break; + default: + throw UnsupportedError("Couldn't deserialize oneOf for the discriminator value: ${discValue}"); + } + result.oneOf = OneOfDynamic(typeIndex: oneOfTypes.indexOf(oneOfType), types: oneOfTypes, value: oneOfResult); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pasta.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pasta.dart new file mode 100644 index 0000000000..5c5ef72537 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pasta.dart @@ -0,0 +1,184 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/entity.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'pasta.g.dart'; + +/// Pasta +/// +/// Properties: +/// * [vendor] +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue() +abstract class Pasta implements Entity, Built { + @BuiltValueField(wireName: r'vendor') + String? get vendor; + + static const String discriminatorFieldName = r'atType'; + + Pasta._(); + + factory Pasta([void updates(PastaBuilder b)]) = _$Pasta; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(PastaBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$PastaSerializer(); +} + +class _$PastaSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Pasta, _$Pasta]; + + @override + final String wireName = r'Pasta'; + + Iterable _serializeProperties( + Serializers serializers, + Pasta object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + if (object.vendor != null) { + yield r'vendor'; + yield serializers.serialize( + object.vendor, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Pasta object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required PastaBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + case r'vendor': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.vendor = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Pasta deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = PastaBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza.dart new file mode 100644 index 0000000000..866daab885 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza.dart @@ -0,0 +1,233 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/pizza_speziale.dart'; +import 'package:openapi/src/model/entity.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'pizza.g.dart'; + +/// Pizza +/// +/// Properties: +/// * [pizzaSize] +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue(instantiable: false) +abstract class Pizza implements Entity { + @BuiltValueField(wireName: r'pizzaSize') + num? get pizzaSize; + + static const String discriminatorFieldName = r'atType'; + + static const Map discriminatorMapping = { + r'PizzaSpeziale': PizzaSpeziale, + }; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$PizzaSerializer(); +} + +class _$PizzaSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Pizza]; + + @override + final String wireName = r'Pizza'; + + Iterable _serializeProperties( + Serializers serializers, + Pizza object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.pizzaSize != null) { + yield r'pizzaSize'; + yield serializers.serialize( + object.pizzaSize, + specifiedType: const FullType(num), + ); + } + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + } + + @override + Object serialize( + Serializers serializers, + Pizza object, { + FullType specifiedType = FullType.unspecified, + }) { + if (object is PizzaSpeziale) { + return serializers.serialize(object, specifiedType: FullType(PizzaSpeziale))!; + } + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + @override + Pizza deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final serializedList = (serialized as Iterable).toList(); + final discIndex = serializedList.indexOf(Pizza.discriminatorFieldName) + 1; + final discValue = serializers.deserialize(serializedList[discIndex], specifiedType: FullType(String)) as String; + switch (discValue) { + case 'PizzaSpeziale': + return serializers.deserialize(serialized, specifiedType: FullType(PizzaSpeziale)) as PizzaSpeziale; + default: + return serializers.deserialize(serialized, specifiedType: FullType($Pizza)) as $Pizza; + } + } +} + +/// a concrete implementation of [Pizza], since [Pizza] is not instantiable +@BuiltValue(instantiable: true) +abstract class $Pizza implements Pizza, Built<$Pizza, $PizzaBuilder> { + $Pizza._(); + + factory $Pizza([void Function($PizzaBuilder)? updates]) = _$$Pizza; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults($PizzaBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer<$Pizza> get serializer => _$$PizzaSerializer(); +} + +class _$$PizzaSerializer implements PrimitiveSerializer<$Pizza> { + @override + final Iterable types = const [$Pizza, _$$Pizza]; + + @override + final String wireName = r'$Pizza'; + + @override + Object serialize( + Serializers serializers, + $Pizza object, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.serialize(object, specifiedType: FullType(Pizza))!; + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required PizzaBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'pizzaSize': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(num), + ) as num; + result.pizzaSize = valueDes; + break; + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + $Pizza deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = $PizzaBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza_speziale.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza_speziale.dart new file mode 100644 index 0000000000..7f17257e50 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza_speziale.dart @@ -0,0 +1,198 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/pizza.dart'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'pizza_speziale.g.dart'; + +/// PizzaSpeziale +/// +/// Properties: +/// * [toppings] +/// * [href] - Hyperlink reference +/// * [id] - unique identifier +/// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships +/// * [atBaseType] - When sub-classing, this defines the super-class +/// * [atType] - When sub-classing, this defines the sub-class Extensible name +@BuiltValue() +abstract class PizzaSpeziale implements Pizza, Built { + @BuiltValueField(wireName: r'toppings') + String? get toppings; + + static const String discriminatorFieldName = r'atType'; + + PizzaSpeziale._(); + + factory PizzaSpeziale([void updates(PizzaSpezialeBuilder b)]) = _$PizzaSpeziale; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(PizzaSpezialeBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$PizzaSpezialeSerializer(); +} + +class _$PizzaSpezialeSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [PizzaSpeziale, _$PizzaSpeziale]; + + @override + final String wireName = r'PizzaSpeziale'; + + Iterable _serializeProperties( + Serializers serializers, + PizzaSpeziale object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.atSchemaLocation != null) { + yield r'@schemaLocation'; + yield serializers.serialize( + object.atSchemaLocation, + specifiedType: const FullType(String), + ); + } + if (object.pizzaSize != null) { + yield r'pizzaSize'; + yield serializers.serialize( + object.pizzaSize, + specifiedType: const FullType(num), + ); + } + if (object.toppings != null) { + yield r'toppings'; + yield serializers.serialize( + object.toppings, + specifiedType: const FullType(String), + ); + } + if (object.atBaseType != null) { + yield r'@baseType'; + yield serializers.serialize( + object.atBaseType, + specifiedType: const FullType(String), + ); + } + if (object.href != null) { + yield r'href'; + yield serializers.serialize( + object.href, + specifiedType: const FullType(String), + ); + } + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(String), + ); + } + yield r'@type'; + yield serializers.serialize( + object.atType, + specifiedType: const FullType(String), + ); + } + + @override + Object serialize( + Serializers serializers, + PizzaSpeziale object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required PizzaSpezialeBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'@schemaLocation': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atSchemaLocation = valueDes; + break; + case r'pizzaSize': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(num), + ) as num; + result.pizzaSize = valueDes; + break; + case r'toppings': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.toppings = valueDes; + break; + case r'@baseType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atBaseType = valueDes; + break; + case r'href': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.href = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.id = valueDes; + break; + case r'@type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.atType = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + PizzaSpeziale deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = PizzaSpezialeBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/serializers.dart new file mode 100644 index 0000000000..55083251e5 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/serializers.dart @@ -0,0 +1,67 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_import + +import 'package:one_of_serializer/any_of_serializer.dart'; +import 'package:one_of_serializer/one_of_serializer.dart'; +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/json_object.dart'; +import 'package:built_value/serializer.dart'; +import 'package:built_value/standard_json_plugin.dart'; +import 'package:built_value/iso_8601_date_time_serializer.dart'; +import 'package:openapi/src/date_serializer.dart'; +import 'package:openapi/src/model/date.dart'; + +import 'package:openapi/src/model/addressable.dart'; +import 'package:openapi/src/model/bar.dart'; +import 'package:openapi/src/model/bar_create.dart'; +import 'package:openapi/src/model/bar_ref.dart'; +import 'package:openapi/src/model/bar_ref_or_value.dart'; +import 'package:openapi/src/model/entity.dart'; +import 'package:openapi/src/model/entity_ref.dart'; +import 'package:openapi/src/model/extensible.dart'; +import 'package:openapi/src/model/foo.dart'; +import 'package:openapi/src/model/foo_ref.dart'; +import 'package:openapi/src/model/foo_ref_or_value.dart'; +import 'package:openapi/src/model/pasta.dart'; +import 'package:openapi/src/model/pizza.dart'; +import 'package:openapi/src/model/pizza_speziale.dart'; + +part 'serializers.g.dart'; + +@SerializersFor([ + Addressable,$Addressable, + Bar, + BarCreate, + BarRef, + BarRefOrValue, + Entity,$Entity, + EntityRef,$EntityRef, + Extensible,$Extensible, + Foo, + FooRef, + FooRefOrValue, + Pasta, + Pizza,$Pizza, + PizzaSpeziale, +]) +Serializers serializers = (_$serializers.toBuilder() + ..addBuilderFactory( + const FullType(BuiltList, [FullType(FooRefOrValue)]), + () => ListBuilder(), + ) + ..add(Addressable.serializer) + ..add(Entity.serializer) + ..add(EntityRef.serializer) + ..add(Extensible.serializer) + ..add(Pizza.serializer) + ..add(const OneOfSerializer()) + ..add(const AnyOfSerializer()) + ..add(const DateSerializer()) + ..add(Iso8601DateTimeSerializer())) + .build(); + +Serializers standardSerializers = + (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(); diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/pom.xml b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/pom.xml new file mode 100644 index 0000000000..50f62b7f8d --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/pom.xml @@ -0,0 +1,88 @@ + + 4.0.0 + org.openapitools + DartDioOneOfPolymorphismAndInheritance + pom + 1.0.0-SNAPSHOT + DartDio OneOf Polymorphism and Inheritance + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + pub-get + pre-integration-test + + exec + + + pub + + get + + + + + pub-run-build-runner + pre-integration-test + + exec + + + pub + + run + build_runner + build + + + + + dart-analyze + integration-test + + exec + + + dart + + analyze + --fatal-infos + + + + + dart-test + integration-test + + exec + + + dart + + test + + + + + + + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/pubspec.yaml new file mode 100644 index 0000000000..fb676f65c3 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/pubspec.yaml @@ -0,0 +1,19 @@ +name: openapi +version: 1.0.0 +description: OpenAPI API client +homepage: homepage + +environment: + sdk: '>=2.12.0 <3.0.0' + +dependencies: + dio: '>=4.0.1 <5.0.0' + one_of: '>=1.5.0 <2.0.0' + one_of_serializer: '>=1.5.0 <2.0.0' + built_value: '>=8.4.0 <9.0.0' + built_collection: '>=5.1.1 <6.0.0' + +dev_dependencies: + built_value_generator: '>=8.4.0 <9.0.0' + build_runner: any + test: ^1.16.0 diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/addressable_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/addressable_test.dart new file mode 100644 index 0000000000..696e26e8e5 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/addressable_test.dart @@ -0,0 +1,23 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Addressable +void main() { + //final instance = AddressableBuilder(); + // TODO add properties to the builder and call build() + + group(Addressable, () { + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_api_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_api_test.dart new file mode 100644 index 0000000000..73be91c446 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_api_test.dart @@ -0,0 +1,18 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + + +/// tests for BarApi +void main() { + final instance = Openapi().getBarApi(); + + group(BarApi, () { + // Create a Bar + // + //Future createBar(BarCreate barCreate) async + test('test createBar', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_create_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_create_test.dart new file mode 100644 index 0000000000..1bf90151be --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_create_test.dart @@ -0,0 +1,56 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for BarCreate +void main() { + final instance = BarCreateBuilder(); + // TODO add properties to the builder and call build() + + group(BarCreate, () { + // String barPropA + test('to test the property `barPropA`', () async { + // TODO + }); + + // String fooPropB + test('to test the property `fooPropB`', () async { + // TODO + }); + + // FooRefOrValue foo + test('to test the property `foo`', () async { + // TODO + }); + + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_ref_or_value_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_ref_or_value_test.dart new file mode 100644 index 0000000000..c132ac0994 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_ref_or_value_test.dart @@ -0,0 +1,41 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for BarRefOrValue +void main() { + final instance = BarRefOrValueBuilder(); + // TODO add properties to the builder and call build() + + group(BarRefOrValue, () { + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_ref_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_ref_test.dart new file mode 100644 index 0000000000..9c410b2b5c --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_ref_test.dart @@ -0,0 +1,41 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for BarRef +void main() { + final instance = BarRefBuilder(); + // TODO add properties to the builder and call build() + + group(BarRef, () { + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_test.dart new file mode 100644 index 0000000000..dc6daaa340 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/bar_test.dart @@ -0,0 +1,55 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Bar +void main() { + final instance = BarBuilder(); + // TODO add properties to the builder and call build() + + group(Bar, () { + // String id + test('to test the property `id`', () async { + // TODO + }); + + // String barPropA + test('to test the property `barPropA`', () async { + // TODO + }); + + // String fooPropB + test('to test the property `fooPropB`', () async { + // TODO + }); + + // FooRefOrValue foo + test('to test the property `foo`', () async { + // TODO + }); + + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/entity_ref_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/entity_ref_test.dart new file mode 100644 index 0000000000..836289893f --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/entity_ref_test.dart @@ -0,0 +1,53 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for EntityRef +void main() { + //final instance = EntityRefBuilder(); + // TODO add properties to the builder and call build() + + group(EntityRef, () { + // Name of the related entity. + // String name + test('to test the property `name`', () async { + // TODO + }); + + // The actual type of the target instance when needed for disambiguation. + // String atReferredType + test('to test the property `atReferredType`', () async { + // TODO + }); + + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/entity_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/entity_test.dart new file mode 100644 index 0000000000..3042974756 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/entity_test.dart @@ -0,0 +1,41 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Entity +void main() { + //final instance = EntityBuilder(); + // TODO add properties to the builder and call build() + + group(Entity, () { + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/extensible_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/extensible_test.dart new file mode 100644 index 0000000000..75e6211e07 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/extensible_test.dart @@ -0,0 +1,29 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Extensible +void main() { + //final instance = ExtensibleBuilder(); + // TODO add properties to the builder and call build() + + group(Extensible, () { + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_api_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_api_test.dart new file mode 100644 index 0000000000..f33986a08b --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_api_test.dart @@ -0,0 +1,25 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + + +/// tests for FooApi +void main() { + final instance = Openapi().getFooApi(); + + group(FooApi, () { + // Create a Foo + // + //Future createFoo({ Foo foo }) async + test('test createFoo', () async { + // TODO + }); + + // GET all Foos + // + //Future> getAllFoos() async + test('test getAllFoos', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_ref_or_value_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_ref_or_value_test.dart new file mode 100644 index 0000000000..029d030e5e --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_ref_or_value_test.dart @@ -0,0 +1,41 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for FooRefOrValue +void main() { + final instance = FooRefOrValueBuilder(); + // TODO add properties to the builder and call build() + + group(FooRefOrValue, () { + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_ref_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_ref_test.dart new file mode 100644 index 0000000000..a1398787bb --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_ref_test.dart @@ -0,0 +1,46 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for FooRef +void main() { + final instance = FooRefBuilder(); + // TODO add properties to the builder and call build() + + group(FooRef, () { + // String foorefPropA + test('to test the property `foorefPropA`', () async { + // TODO + }); + + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_test.dart new file mode 100644 index 0000000000..93a5286e2b --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/foo_test.dart @@ -0,0 +1,51 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Foo +void main() { + final instance = FooBuilder(); + // TODO add properties to the builder and call build() + + group(Foo, () { + // String fooPropA + test('to test the property `fooPropA`', () async { + // TODO + }); + + // String fooPropB + test('to test the property `fooPropB`', () async { + // TODO + }); + + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/pasta_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/pasta_test.dart new file mode 100644 index 0000000000..6a3ae338ee --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/pasta_test.dart @@ -0,0 +1,46 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Pasta +void main() { + final instance = PastaBuilder(); + // TODO add properties to the builder and call build() + + group(Pasta, () { + // String vendor + test('to test the property `vendor`', () async { + // TODO + }); + + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/pizza_speziale_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/pizza_speziale_test.dart new file mode 100644 index 0000000000..774320231c --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/pizza_speziale_test.dart @@ -0,0 +1,46 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for PizzaSpeziale +void main() { + final instance = PizzaSpezialeBuilder(); + // TODO add properties to the builder and call build() + + group(PizzaSpeziale, () { + // String toppings + test('to test the property `toppings`', () async { + // TODO + }); + + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/pizza_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/pizza_test.dart new file mode 100644 index 0000000000..5c6e1af95a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/test/pizza_test.dart @@ -0,0 +1,46 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Pizza +void main() { + //final instance = PizzaBuilder(); + // TODO add properties to the builder and call build() + + group(Pizza, () { + // num pizzaSize + test('to test the property `pizzaSize`', () async { + // TODO + }); + + // Hyperlink reference + // String href + test('to test the property `href`', () async { + // TODO + }); + + // unique identifier + // String id + test('to test the property `id`', () async { + // TODO + }); + + // A URI to a JSON-Schema file that defines additional attributes and relationships + // String atSchemaLocation + test('to test the property `atSchemaLocation`', () async { + // TODO + }); + + // When sub-classing, this defines the super-class + // String atBaseType + test('to test the property `atBaseType`', () async { + // TODO + }); + + // When sub-classing, this defines the sub-class Extensible name + // String atType + test('to test the property `atType`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.gitignore b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.gitignore new file mode 100644 index 0000000000..4298cdcbd1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.gitignore @@ -0,0 +1,41 @@ +# See https://dart.dev/guides/libraries/private-files + +# Files and directories created by pub +.dart_tool/ +.buildlog +.packages +.project +.pub/ +build/ +**/packages/ + +# Files created by dart2js +# (Most Dart developers will use pub build to compile Dart, use/modify these +# rules if you intend to use dart2js directly +# Convention is to use extension '.dart.js' for Dart compiled to Javascript to +# differentiate from explicit Javascript files) +*.dart.js +*.part.js +*.js.deps +*.js.map +*.info.json + +# Directory created by dartdoc +doc/api/ + +# Don't commit pubspec lock file +# (Library packages only! Remove pattern if developing an application package) +pubspec.lock + +# Don’t commit files and directories created by other development environments. +# For example, if your development environment creates any of the following files, +# consider putting them in a global ignore file: + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator-ignore b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.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/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/FILES b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/FILES new file mode 100644 index 0000000000..7f2ac59bf6 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/FILES @@ -0,0 +1,21 @@ +.gitignore +README.md +analysis_options.yaml +doc/Child.md +doc/DefaultApi.md +doc/Example.md +lib/openapi.dart +lib/src/api.dart +lib/src/api/default_api.dart +lib/src/api_util.dart +lib/src/auth/api_key_auth.dart +lib/src/auth/auth.dart +lib/src/auth/basic_auth.dart +lib/src/auth/bearer_auth.dart +lib/src/auth/oauth.dart +lib/src/date_serializer.dart +lib/src/model/child.dart +lib/src/model/date.dart +lib/src/model/example.dart +lib/src/serializers.dart +pubspec.yaml diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/README.md b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/README.md new file mode 100644 index 0000000000..d73bafd4c6 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/README.md @@ -0,0 +1,83 @@ +# openapi (EXPERIMENTAL) +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +This Dart package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Build package: org.openapitools.codegen.languages.DartDioClientCodegen + +## Requirements + +* Dart 2.12.0 or later OR Flutter 1.26.0 or later +* Dio 4.0.0+ + +## Installation & Usage + +### pub.dev +To use the package from [pub.dev](https://pub.dev), please include the following in pubspec.yaml +```yaml +dependencies: + openapi: 1.0.0 +``` + +### Github +If this Dart package is published to Github, please include the following in pubspec.yaml +```yaml +dependencies: + openapi: + git: + url: https://github.com/GIT_USER_ID/GIT_REPO_ID.git + #ref: main +``` + +### Local development +To use the package from your local drive, please include the following in pubspec.yaml +```yaml +dependencies: + openapi: + path: /path/to/openapi +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```dart +import 'package:openapi/openapi.dart'; + + +final api = Openapi().getDefaultApi(); + +try { + final response = await api.list(); + print(response); +} catch on DioError (e) { + print("Exception when calling DefaultApi->list: $e\n"); +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://api.example.xyz/v1* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +[*DefaultApi*](doc/DefaultApi.md) | [**list**](doc/DefaultApi.md#list) | **GET** /example | + + +## Documentation For Models + + - [Child](doc/Child.md) + - [Example](doc/Example.md) + + +## Documentation For Authorization + + All endpoints do not require authorization. + + +## Author + + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/analysis_options.yaml new file mode 100644 index 0000000000..a611887d3a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/analysis_options.yaml @@ -0,0 +1,9 @@ +analyzer: + language: + strict-inference: true + strict-raw-types: true + strong-mode: + implicit-dynamic: false + implicit-casts: false + exclude: + - test/*.dart diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/doc/Child.md b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/doc/Child.md new file mode 100644 index 0000000000..bed0f2feec --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/doc/Child.md @@ -0,0 +1,15 @@ +# openapi.model.Child + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/doc/DefaultApi.md b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/doc/DefaultApi.md new file mode 100644 index 0000000000..abbf5f07f4 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/doc/DefaultApi.md @@ -0,0 +1,51 @@ +# openapi.api.DefaultApi + +## Load the API package +```dart +import 'package:openapi/api.dart'; +``` + +All URIs are relative to *http://api.example.xyz/v1* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**list**](DefaultApi.md#list) | **GET** /example | + + +# **list** +> Example list() + + + +### Example +```dart +import 'package:openapi/api.dart'; + +final api = Openapi().getDefaultApi(); + +try { + final response = api.list(); + print(response); +} catch on DioError (e) { + print('Exception when calling DefaultApi->list: $e\n'); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Example**](Example.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/doc/Example.md b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/doc/Example.md new file mode 100644 index 0000000000..bf49bb137a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/doc/Example.md @@ -0,0 +1,15 @@ +# openapi.model.Example + +## Load the model package +```dart +import 'package:openapi/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/openapi.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/openapi.dart new file mode 100644 index 0000000000..220621d696 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/openapi.dart @@ -0,0 +1,15 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +export 'package:openapi/src/api.dart'; +export 'package:openapi/src/auth/api_key_auth.dart'; +export 'package:openapi/src/auth/basic_auth.dart'; +export 'package:openapi/src/auth/oauth.dart'; +export 'package:openapi/src/serializers.dart'; +export 'package:openapi/src/model/date.dart'; + +export 'package:openapi/src/api/default_api.dart'; + +export 'package:openapi/src/model/child.dart'; +export 'package:openapi/src/model/example.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/api.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/api.dart new file mode 100644 index 0000000000..776737680d --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/api.dart @@ -0,0 +1,73 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; +import 'package:built_value/serializer.dart'; +import 'package:openapi/src/serializers.dart'; +import 'package:openapi/src/auth/api_key_auth.dart'; +import 'package:openapi/src/auth/basic_auth.dart'; +import 'package:openapi/src/auth/bearer_auth.dart'; +import 'package:openapi/src/auth/oauth.dart'; +import 'package:openapi/src/api/default_api.dart'; + +class Openapi { + static const String basePath = r'http://api.example.xyz/v1'; + + final Dio dio; + final Serializers serializers; + + Openapi({ + Dio? dio, + Serializers? serializers, + String? basePathOverride, + List? interceptors, + }) : this.serializers = serializers ?? standardSerializers, + this.dio = dio ?? + Dio(BaseOptions( + baseUrl: basePathOverride ?? basePath, + connectTimeout: 5000, + receiveTimeout: 3000, + )) { + if (interceptors == null) { + this.dio.interceptors.addAll([ + OAuthInterceptor(), + BasicAuthInterceptor(), + BearerAuthInterceptor(), + ApiKeyAuthInterceptor(), + ]); + } else { + this.dio.interceptors.addAll(interceptors); + } + } + + void setOAuthToken(String name, String token) { + if (this.dio.interceptors.any((i) => i is OAuthInterceptor)) { + (this.dio.interceptors.firstWhere((i) => i is OAuthInterceptor) as OAuthInterceptor).tokens[name] = token; + } + } + + void setBearerAuth(String name, String token) { + if (this.dio.interceptors.any((i) => i is BearerAuthInterceptor)) { + (this.dio.interceptors.firstWhere((i) => i is BearerAuthInterceptor) as BearerAuthInterceptor).tokens[name] = token; + } + } + + void setBasicAuth(String name, String username, String password) { + if (this.dio.interceptors.any((i) => i is BasicAuthInterceptor)) { + (this.dio.interceptors.firstWhere((i) => i is BasicAuthInterceptor) as BasicAuthInterceptor).authInfo[name] = BasicAuthInfo(username, password); + } + } + + void setApiKey(String name, String apiKey) { + if (this.dio.interceptors.any((i) => i is ApiKeyAuthInterceptor)) { + (this.dio.interceptors.firstWhere((element) => element is ApiKeyAuthInterceptor) as ApiKeyAuthInterceptor).apiKeys[name] = apiKey; + } + } + + /// Get DefaultApi instance, base route and serializer can be overridden by a given but be careful, + /// by doing that all interceptors will not be executed + DefaultApi getDefaultApi() { + return DefaultApi(dio, serializers); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/api/default_api.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/api/default_api.dart new file mode 100644 index 0000000000..8d500cb70a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/api/default_api.dart @@ -0,0 +1,92 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:async'; + +import 'package:built_value/serializer.dart'; +import 'package:dio/dio.dart'; + +import 'package:openapi/src/model/example.dart'; + +class DefaultApi { + + final Dio _dio; + + final Serializers _serializers; + + const DefaultApi(this._dio, this._serializers); + + /// list + /// + /// + /// Parameters: + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [Example] as data + /// Throws [DioError] if API call or serialization fails + Future> list({ + CancelToken? cancelToken, + Map? headers, + Map? extra, + ValidateStatus? validateStatus, + ProgressCallback? onSendProgress, + ProgressCallback? onReceiveProgress, + }) async { + final _path = r'/example'; + final _options = Options( + method: r'GET', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + validateStatus: validateStatus, + ); + + final _response = await _dio.request( + _path, + options: _options, + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + Example _responseData; + + try { + const _responseType = FullType(Example); + _responseData = _serializers.deserialize( + _response.data!, + specifiedType: _responseType, + ) as Example; + + } catch (error, stackTrace) { + throw DioError( + requestOptions: _response.requestOptions, + response: _response, + type: DioErrorType.other, + error: error, + )..stackTrace = stackTrace; + } + + return Response( + data: _responseData, + headers: _response.headers, + isRedirect: _response.isRedirect, + requestOptions: _response.requestOptions, + redirects: _response.redirects, + statusCode: _response.statusCode, + statusMessage: _response.statusMessage, + extra: _response.extra, + ); + } + +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/api_util.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/api_util.dart new file mode 100644 index 0000000000..ed3bb12f25 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/api_util.dart @@ -0,0 +1,77 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:dio/dio.dart'; + +/// Format the given form parameter object into something that Dio can handle. +/// Returns primitive or String. +/// Returns List/Map if the value is BuildList/BuiltMap. +dynamic encodeFormParameter(Serializers serializers, dynamic value, FullType type) { + if (value == null) { + return ''; + } + if (value is String || value is num || value is bool) { + return value; + } + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (serialized is String) { + return serialized; + } + if (value is BuiltList || value is BuiltSet || value is BuiltMap) { + return serialized; + } + return json.encode(serialized); +} + +dynamic encodeQueryParameter( + Serializers serializers, + dynamic value, + FullType type, +) { + if (value == null) { + return ''; + } + if (value is String || value is num || value is bool) { + return value; + } + if (value is Uint8List) { + // Currently not sure how to serialize this + return value; + } + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (serialized == null) { + return ''; + } + if (serialized is String) { + return serialized; + } + return serialized; +} + +ListParam encodeCollectionQueryParameter( + Serializers serializers, + dynamic value, + FullType type, { + ListFormat format = ListFormat.multi, +}) { + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (value is BuiltList || value is BuiltSet) { + return ListParam(List.of((serialized as Iterable).cast()), format); + } + throw ArgumentError('Invalid value passed to encodeCollectionQueryParameter'); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/api_key_auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/api_key_auth.dart new file mode 100644 index 0000000000..ee16e3f0f9 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/api_key_auth.dart @@ -0,0 +1,30 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class ApiKeyAuthInterceptor extends AuthInterceptor { + final Map apiKeys = {}; + + @override + void onRequest(RequestOptions options, RequestInterceptorHandler handler) { + final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'apiKey'); + for (final info in authInfo) { + final authName = info['name'] as String; + final authKeyName = info['keyName'] as String; + final authWhere = info['where'] as String; + final apiKey = apiKeys[authName]; + if (apiKey != null) { + if (authWhere == 'query') { + options.queryParameters[authKeyName] = apiKey; + } else { + options.headers[authKeyName] = apiKey; + } + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/auth.dart new file mode 100644 index 0000000000..f7ae9bf3f1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/auth.dart @@ -0,0 +1,18 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; + +abstract class AuthInterceptor extends Interceptor { + /// Get auth information on given route for the given type. + /// Can return an empty list if type is not present on auth data or + /// if route doesn't need authentication. + List> getAuthInfo(RequestOptions route, bool Function(Map secure) handles) { + if (route.extra.containsKey('secure')) { + final auth = route.extra['secure'] as List>; + return auth.where((secure) => handles(secure)).toList(); + } + return []; + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/basic_auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/basic_auth.dart new file mode 100644 index 0000000000..b6e6dce04f --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/basic_auth.dart @@ -0,0 +1,37 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'dart:convert'; + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class BasicAuthInfo { + final String username; + final String password; + + const BasicAuthInfo(this.username, this.password); +} + +class BasicAuthInterceptor extends AuthInterceptor { + final Map authInfo = {}; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) { + final metadataAuthInfo = getAuthInfo(options, (secure) => (secure['type'] == 'http' && secure['scheme'] == 'basic') || secure['type'] == 'basic'); + for (final info in metadataAuthInfo) { + final authName = info['name'] as String; + final basicAuthInfo = authInfo[authName]; + if (basicAuthInfo != null) { + final basicAuth = 'Basic ${base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}'))}'; + options.headers['Authorization'] = basicAuth; + break; + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/bearer_auth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/bearer_auth.dart new file mode 100644 index 0000000000..1d4402b376 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/bearer_auth.dart @@ -0,0 +1,26 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class BearerAuthInterceptor extends AuthInterceptor { + final Map tokens = {}; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) { + final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'http' && secure['scheme'] == 'bearer'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; + break; + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/oauth.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/oauth.dart new file mode 100644 index 0000000000..337cf762b0 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/auth/oauth.dart @@ -0,0 +1,26 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:dio/dio.dart'; +import 'package:openapi/src/auth/auth.dart'; + +class OAuthInterceptor extends AuthInterceptor { + final Map tokens = {}; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) { + final authInfo = getAuthInfo(options, (secure) => secure['type'] == 'oauth' || secure['type'] == 'oauth2'); + for (final info in authInfo) { + final token = tokens[info['name']]; + if (token != null) { + options.headers['Authorization'] = 'Bearer ${token}'; + break; + } + } + super.onRequest(options, handler); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/date_serializer.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/date_serializer.dart new file mode 100644 index 0000000000..db3c5c437d --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/date_serializer.dart @@ -0,0 +1,31 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:openapi/src/model/date.dart'; + +class DateSerializer implements PrimitiveSerializer { + + const DateSerializer(); + + @override + Iterable get types => BuiltList.of([Date]); + + @override + String get wireName => 'Date'; + + @override + Date deserialize(Serializers serializers, Object serialized, + {FullType specifiedType = FullType.unspecified}) { + final parsed = DateTime.parse(serialized as String); + return Date(parsed.year, parsed.month, parsed.day); + } + + @override + Object serialize(Serializers serializers, Date date, + {FullType specifiedType = FullType.unspecified}) { + return date.toString(); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/model/child.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/model/child.dart new file mode 100644 index 0000000000..987b52ca72 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/model/child.dart @@ -0,0 +1,108 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; + +part 'child.g.dart'; + +/// Child +/// +/// Properties: +/// * [name] +@BuiltValue() +abstract class Child implements Built { + @BuiltValueField(wireName: r'name') + String? get name; + + Child._(); + + factory Child([void updates(ChildBuilder b)]) = _$Child; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ChildBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ChildSerializer(); +} + +class _$ChildSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Child, _$Child]; + + @override + final String wireName = r'Child'; + + Iterable _serializeProperties( + Serializers serializers, + Child object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.name != null) { + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Child object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ChildBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.name = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Child deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ChildBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/model/date.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/model/date.dart new file mode 100644 index 0000000000..b21c7f544b --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/model/date.dart @@ -0,0 +1,70 @@ +/// A gregorian calendar date generated by +/// OpenAPI generator to differentiate +/// between [DateTime] and [Date] formats. +class Date implements Comparable { + final int year; + + /// January is 1. + final int month; + + /// First day is 1. + final int day; + + Date(this.year, this.month, this.day); + + /// The current date + static Date now({bool utc = false}) { + var now = DateTime.now(); + if (utc) { + now = now.toUtc(); + } + return now.toDate(); + } + + /// Convert to a [DateTime]. + DateTime toDateTime({bool utc = false}) { + if (utc) { + return DateTime.utc(year, month, day); + } else { + return DateTime(year, month, day); + } + } + + @override + int compareTo(Date other) { + int d = year.compareTo(other.year); + if (d != 0) { + return d; + } + d = month.compareTo(other.month); + if (d != 0) { + return d; + } + return day.compareTo(other.day); + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is Date && + runtimeType == other.runtimeType && + year == other.year && + month == other.month && + day == other.day; + + @override + int get hashCode => year.hashCode ^ month.hashCode ^ day.hashCode; + + @override + String toString() { + final yyyy = year.toString(); + final mm = month.toString().padLeft(2, '0'); + final dd = day.toString().padLeft(2, '0'); + + return '$yyyy-$mm-$dd'; + } +} + +extension DateTimeToDate on DateTime { + Date toDate() => Date(year, month, day); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/model/example.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/model/example.dart new file mode 100644 index 0000000000..799b77e4e1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/model/example.dart @@ -0,0 +1,72 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_element +import 'package:openapi/src/model/child.dart'; +import 'dart:core'; +import 'package:built_value/built_value.dart'; +import 'package:built_value/serializer.dart'; +import 'package:one_of/one_of.dart'; + +part 'example.g.dart'; + +/// Example +/// +/// Properties: +/// * [name] +@BuiltValue() +abstract class Example implements Built { + /// One Of [Child], [int] + OneOf get oneOf; + + Example._(); + + factory Example([void updates(ExampleBuilder b)]) = _$Example; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ExampleBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ExampleSerializer(); +} + +class _$ExampleSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Example, _$Example]; + + @override + final String wireName = r'Example'; + + Iterable _serializeProperties( + Serializers serializers, + Example object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + } + + @override + Object serialize( + Serializers serializers, + Example object, { + FullType specifiedType = FullType.unspecified, + }) { + final oneOf = object.oneOf; + return serializers.serialize(oneOf.value, specifiedType: FullType(oneOf.valueType))!; + } + + @override + Example deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ExampleBuilder(); + Object? oneOfDataSrc; + final targetType = const FullType(OneOf, [FullType(Child), FullType(int), ]); + oneOfDataSrc = serialized; + result.oneOf = serializers.deserialize(oneOfDataSrc, specifiedType: targetType) as OneOf; + return result.build(); + } +} + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/serializers.dart new file mode 100644 index 0000000000..cbd8870dc6 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/lib/src/serializers.dart @@ -0,0 +1,34 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +// ignore_for_file: unused_import + +import 'package:one_of_serializer/any_of_serializer.dart'; +import 'package:one_of_serializer/one_of_serializer.dart'; +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/json_object.dart'; +import 'package:built_value/serializer.dart'; +import 'package:built_value/standard_json_plugin.dart'; +import 'package:built_value/iso_8601_date_time_serializer.dart'; +import 'package:openapi/src/date_serializer.dart'; +import 'package:openapi/src/model/date.dart'; + +import 'package:openapi/src/model/child.dart'; +import 'package:openapi/src/model/example.dart'; + +part 'serializers.g.dart'; + +@SerializersFor([ + Child, + Example, +]) +Serializers serializers = (_$serializers.toBuilder() + ..add(const OneOfSerializer()) + ..add(const AnyOfSerializer()) + ..add(const DateSerializer()) + ..add(Iso8601DateTimeSerializer())) + .build(); + +Serializers standardSerializers = + (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(); diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/pom.xml b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/pom.xml new file mode 100644 index 0000000000..cceaebd895 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/pom.xml @@ -0,0 +1,88 @@ + + 4.0.0 + org.openapitools + DartDioOneOfPrimitive + pom + 1.0.0-SNAPSHOT + DartDio OneOf Primitive + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + pub-get + pre-integration-test + + exec + + + pub + + get + + + + + pub-run-build-runner + pre-integration-test + + exec + + + pub + + run + build_runner + build + + + + + dart-analyze + integration-test + + exec + + + dart + + analyze + --fatal-infos + + + + + dart-test + integration-test + + exec + + + dart + + test + + + + + + + + diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/pubspec.yaml new file mode 100644 index 0000000000..fb676f65c3 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/pubspec.yaml @@ -0,0 +1,19 @@ +name: openapi +version: 1.0.0 +description: OpenAPI API client +homepage: homepage + +environment: + sdk: '>=2.12.0 <3.0.0' + +dependencies: + dio: '>=4.0.1 <5.0.0' + one_of: '>=1.5.0 <2.0.0' + one_of_serializer: '>=1.5.0 <2.0.0' + built_value: '>=8.4.0 <9.0.0' + built_collection: '>=5.1.1 <6.0.0' + +dev_dependencies: + built_value_generator: '>=8.4.0 <9.0.0' + build_runner: any + test: ^1.16.0 diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/test/child_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/test/child_test.dart new file mode 100644 index 0000000000..d40451a84c --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/test/child_test.dart @@ -0,0 +1,16 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Child +void main() { + final instance = ChildBuilder(); + // TODO add properties to the builder and call build() + + group(Child, () { + // String name + test('to test the property `name`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/test/default_api_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/test/default_api_test.dart new file mode 100644 index 0000000000..e4ec570779 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/test/default_api_test.dart @@ -0,0 +1,16 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + + +/// tests for DefaultApi +void main() { + final instance = Openapi().getDefaultApi(); + + group(DefaultApi, () { + //Future list() async + test('test list', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/test/example_test.dart b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/test/example_test.dart new file mode 100644 index 0000000000..ccb3512114 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/test/example_test.dart @@ -0,0 +1,16 @@ +import 'package:test/test.dart'; +import 'package:openapi/openapi.dart'; + +// tests for Example +void main() { + final instance = ExampleBuilder(); + // TODO add properties to the builder and call build() + + group(Example, () { + // String name + test('to test the property `name`', () async { + // TODO + }); + + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/additional_properties_class.dart index d45eeef83d..a3d4df084b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/additional_properties_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'additional_properties_class.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/all_of_with_single_ref.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/all_of_with_single_ref.dart index 460aec9a9c..dd3a19e9d9 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/all_of_with_single_ref.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/all_of_with_single_ref.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/single_ref_type.dart'; import 'package:json_annotation/json_annotation.dart'; @@ -55,7 +56,7 @@ class AllOfWithSingleRef { @override int get hashCode => username.hashCode + - (singleRefType == null ? 0 : singleRefType.hashCode); + singleRefType.hashCode; factory AllOfWithSingleRef.fromJson(Map json) => _$AllOfWithSingleRefFromJson(json); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/animal.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/animal.dart index 26090b1092..22a196ce7d 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/animal.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/animal.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'animal.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/api_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/api_response.dart index ac22fd59d6..c6700e2d39 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/api_response.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'api_response.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_array_of_number_only.dart index dbae180528..7372be1583 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_array_of_number_only.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'array_of_array_of_number_only.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_number_only.dart index a203361bcc..d538bb312f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_number_only.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'array_of_number_only.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_test.dart index 1f1720b2b6..30a6ec8a8b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_test.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/read_only_first.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/capitalization.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/capitalization.dart index d40127b68a..707cb05a04 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/capitalization.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/capitalization.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'capitalization.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat.dart index 9d79ad4822..0b176faf31 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/animal.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat_all_of.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat_all_of.dart index 55e2a10832..abb9dbc25e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat_all_of.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'cat_all_of.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/category.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/category.dart index 6bc66f3441..b94c615799 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/category.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/category.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'category.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/class_model.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/class_model.dart index 015d2d0297..01837bfcca 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/class_model.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/class_model.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'class_model.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/deprecated_object.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/deprecated_object.dart index 9240f1160d..b97e063725 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/deprecated_object.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/deprecated_object.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'deprecated_object.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog.dart index 62527c046b..a049d0479f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/animal.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog_all_of.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog_all_of.dart index d5ceabdc3a..19bd4c0267 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog_all_of.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'dog_all_of.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_arrays.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_arrays.dart index 54c9839b9f..a97d069a3d 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_arrays.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_arrays.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'enum_arrays.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_test.dart index 17a67de347..80555c14d0 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_test.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/outer_enum.dart'; import 'package:openapi/src/model/outer_enum_default_value.dart'; import 'package:openapi/src/model/outer_enum_integer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/file_schema_test_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/file_schema_test_class.dart index 99d4dd3551..bd2a9dc6f2 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/file_schema_test_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/file_schema_test_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/model_file.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo.dart index b21bae484e..b43572d222 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'foo.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo_get_default_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo_get_default_response.dart index 423f93eb77..acc1c60e43 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo_get_default_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo_get_default_response.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/foo.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/format_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/format_test.dart index a83f4721d8..91b35595a3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/format_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/format_test.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:dio/dio.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/has_only_read_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/has_only_read_only.dart index 25d25ddd06..84c99fbc18 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/has_only_read_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/has_only_read_only.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'has_only_read_only.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/health_check_result.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/health_check_result.dart index 43a07ec7d5..fcb2973b75 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/health_check_result.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/health_check_result.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'health_check_result.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/map_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/map_test.dart index 5c4c3edb70..7ab19eabd5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/map_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/map_test.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'map_test.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/mixed_properties_and_additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/mixed_properties_and_additional_properties_class.dart index 649f795580..e2e3cd0b85 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/mixed_properties_and_additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/mixed_properties_and_additional_properties_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/animal.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model200_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model200_response.dart index f4be2b420f..346f125755 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model200_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model200_response.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'model200_response.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_client.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_client.dart index 811e277685..14e22005a1 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_client.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_client.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'model_client.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_enum_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_enum_class.dart index e3323e17a1..8abf107d98 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_enum_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_enum_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_file.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_file.dart index fa38556a54..fe95e3ff00 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_file.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_file.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'model_file.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_list.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_list.dart index f5ae9fdbd7..543b79ac9f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_list.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_list.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'model_list.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_return.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_return.dart index a2b022414f..192b134d8f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_return.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_return.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'model_return.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/name.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/name.dart index c361e4397e..6613fa3afc 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/name.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/name.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'name.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart index 3816bb3383..897d489ba4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'nullable_class.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/number_only.dart index 8efb55ea16..3ca6bf704b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/number_only.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'number_only.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/object_with_deprecated_fields.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/object_with_deprecated_fields.dart index 522ee40e2e..1736161360 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/object_with_deprecated_fields.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/object_with_deprecated_fields.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/deprecated_object.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/order.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/order.dart index 087980a08e..54134b5113 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/order.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/order.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'order.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_composite.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_composite.dart index f452e4b233..f2509cb992 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_composite.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_composite.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'outer_composite.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum.dart index 5b863632d5..514507968c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_default_value.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_default_value.dart index f4585362ec..0c8116edea 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_default_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_default_value.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer.dart index c3f134455d..34268d0e9c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer_default_value.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer_default_value.dart index d94f696f81..97b3259388 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer_default_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer_default_value.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_object_with_enum_property.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_object_with_enum_property.dart index 80331fe4df..76d18676a1 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_object_with_enum_property.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_object_with_enum_property.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/outer_enum_integer.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/pet.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/pet.dart index f9cf648838..28d6294bae 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/pet.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/pet.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/category.dart'; import 'package:openapi/src/model/tag.dart'; import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/read_only_first.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/read_only_first.dart index c79e7df9ae..c71c088f13 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/read_only_first.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/read_only_first.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'read_only_first.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/single_ref_type.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/single_ref_type.dart index 072d072e0b..ca56d9841a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/single_ref_type.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/single_ref_type.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/special_model_name.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/special_model_name.dart index 84332bb1a1..acd3ba0995 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/special_model_name.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/special_model_name.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'special_model_name.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/tag.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/tag.dart index d0372c1742..d8a87eec18 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/tag.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/tag.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'tag.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/user.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/user.dart index 8bb2ae70ce..62f132ce77 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/user.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/user.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:json_annotation/json_annotation.dart'; part 'user.g.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart index 4d45be3abb..3fdac6d5a4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -13,75 +14,114 @@ part 'additional_properties_class.g.dart'; /// Properties: /// * [mapProperty] /// * [mapOfMapProperty] +@BuiltValue() abstract class AdditionalPropertiesClass implements Built { - @BuiltValueField(wireName: r'map_property') - BuiltMap? get mapProperty; + @BuiltValueField(wireName: r'map_property') + BuiltMap? get mapProperty; - @BuiltValueField(wireName: r'map_of_map_property') - BuiltMap>? get mapOfMapProperty; + @BuiltValueField(wireName: r'map_of_map_property') + BuiltMap>? get mapOfMapProperty; - AdditionalPropertiesClass._(); + AdditionalPropertiesClass._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(AdditionalPropertiesClassBuilder b) => b; + factory AdditionalPropertiesClass([void updates(AdditionalPropertiesClassBuilder b)]) = _$AdditionalPropertiesClass; - factory AdditionalPropertiesClass([void updates(AdditionalPropertiesClassBuilder b)]) = _$AdditionalPropertiesClass; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(AdditionalPropertiesClassBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$AdditionalPropertiesClassSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$AdditionalPropertiesClassSerializer(); } -class _$AdditionalPropertiesClassSerializer implements StructuredSerializer { - @override - final Iterable types = const [AdditionalPropertiesClass, _$AdditionalPropertiesClass]; +class _$AdditionalPropertiesClassSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [AdditionalPropertiesClass, _$AdditionalPropertiesClass]; - @override - final String wireName = r'AdditionalPropertiesClass'; + @override + final String wireName = r'AdditionalPropertiesClass'; - @override - Iterable serialize(Serializers serializers, AdditionalPropertiesClass object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.mapProperty != null) { - result - ..add(r'map_property') - ..add(serializers.serialize(object.mapProperty, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(String)]))); - } - if (object.mapOfMapProperty != null) { - result - ..add(r'map_of_map_property') - ..add(serializers.serialize(object.mapOfMapProperty, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(BuiltMap, [FullType(String), FullType(String)])]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + AdditionalPropertiesClass object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.mapProperty != null) { + yield r'map_property'; + yield serializers.serialize( + object.mapProperty, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(String)]), + ); } - - @override - AdditionalPropertiesClass deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = AdditionalPropertiesClassBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'map_property': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(String)])) as BuiltMap; - result.mapProperty.replace(valueDes); - break; - case r'map_of_map_property': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(BuiltMap, [FullType(String), FullType(String)])])) as BuiltMap>; - result.mapOfMapProperty.replace(valueDes); - break; - } - } - return result.build(); + if (object.mapOfMapProperty != null) { + yield r'map_of_map_property'; + yield serializers.serialize( + object.mapOfMapProperty, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(BuiltMap, [FullType(String), FullType(String)])]), + ); } + } + + @override + Object serialize( + Serializers serializers, + AdditionalPropertiesClass object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required AdditionalPropertiesClassBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'map_property': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(String)]), + ) as BuiltMap; + result.mapProperty.replace(valueDes); + break; + case r'map_of_map_property': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(BuiltMap, [FullType(String), FullType(String)])]), + ) as BuiltMap>; + result.mapOfMapProperty.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + AdditionalPropertiesClass deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = AdditionalPropertiesClassBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/all_of_with_single_ref.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/all_of_with_single_ref.dart index 3319d53814..04f59d3601 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/all_of_with_single_ref.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/all_of_with_single_ref.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/single_ref_type.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -13,76 +14,114 @@ part 'all_of_with_single_ref.g.dart'; /// Properties: /// * [username] /// * [singleRefType] +@BuiltValue() abstract class AllOfWithSingleRef implements Built { - @BuiltValueField(wireName: r'username') - String? get username; + @BuiltValueField(wireName: r'username') + String? get username; - @BuiltValueField(wireName: r'SingleRefType') - SingleRefType? get singleRefType; + @BuiltValueField(wireName: r'SingleRefType') + SingleRefType? get singleRefType; - AllOfWithSingleRef._(); + AllOfWithSingleRef._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(AllOfWithSingleRefBuilder b) => b; + factory AllOfWithSingleRef([void updates(AllOfWithSingleRefBuilder b)]) = _$AllOfWithSingleRef; - factory AllOfWithSingleRef([void updates(AllOfWithSingleRefBuilder b)]) = _$AllOfWithSingleRef; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(AllOfWithSingleRefBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$AllOfWithSingleRefSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$AllOfWithSingleRefSerializer(); } -class _$AllOfWithSingleRefSerializer implements StructuredSerializer { - @override - final Iterable types = const [AllOfWithSingleRef, _$AllOfWithSingleRef]; +class _$AllOfWithSingleRefSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [AllOfWithSingleRef, _$AllOfWithSingleRef]; - @override - final String wireName = r'AllOfWithSingleRef'; + @override + final String wireName = r'AllOfWithSingleRef'; - @override - Iterable serialize(Serializers serializers, AllOfWithSingleRef object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.username != null) { - result - ..add(r'username') - ..add(serializers.serialize(object.username, - specifiedType: const FullType(String))); - } - if (object.singleRefType != null) { - result - ..add(r'SingleRefType') - ..add(serializers.serialize(object.singleRefType, - specifiedType: const FullType.nullable(SingleRefType))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + AllOfWithSingleRef object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.username != null) { + yield r'username'; + yield serializers.serialize( + object.username, + specifiedType: const FullType(String), + ); } - - @override - AllOfWithSingleRef deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = AllOfWithSingleRefBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'username': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.username = valueDes; - break; - case r'SingleRefType': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(SingleRefType)) as SingleRefType?; - if (valueDes == null) continue; - result.singleRefType = valueDes; - break; - } - } - return result.build(); + if (object.singleRefType != null) { + yield r'SingleRefType'; + yield serializers.serialize( + object.singleRefType, + specifiedType: const FullType(SingleRefType), + ); } + } + + @override + Object serialize( + Serializers serializers, + AllOfWithSingleRef object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required AllOfWithSingleRefBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'username': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.username = valueDes; + break; + case r'SingleRefType': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(SingleRefType), + ) as SingleRefType; + result.singleRefType = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + AllOfWithSingleRef deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = AllOfWithSingleRefBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/animal.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/animal.dart index cd9084ceb2..a8f8aa9c90 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/animal.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/animal.dart @@ -2,6 +2,9 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element +import 'package:openapi/src/model/dog.dart'; +import 'package:openapi/src/model/cat.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,74 +15,168 @@ part 'animal.g.dart'; /// Properties: /// * [className] /// * [color] -abstract class Animal implements Built { - @BuiltValueField(wireName: r'className') - String get className; +@BuiltValue(instantiable: false) +abstract class Animal { + @BuiltValueField(wireName: r'className') + String get className; - @BuiltValueField(wireName: r'color') - String? get color; + @BuiltValueField(wireName: r'color') + String? get color; - Animal._(); + static const String discriminatorFieldName = r'className'; - @BuiltValueHook(initializeBuilder: true) - static void _defaults(AnimalBuilder b) => b - ..color = 'red'; + static const Map discriminatorMapping = { + r'Cat': Cat, + r'Dog': Dog, + }; - factory Animal([void updates(AnimalBuilder b)]) = _$Animal; - - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$AnimalSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$AnimalSerializer(); } -class _$AnimalSerializer implements StructuredSerializer { - @override - final Iterable types = const [Animal, _$Animal]; +class _$AnimalSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Animal]; - @override - final String wireName = r'Animal'; + @override + final String wireName = r'Animal'; - @override - Iterable serialize(Serializers serializers, Animal object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - result - ..add(r'className') - ..add(serializers.serialize(object.className, - specifiedType: const FullType(String))); - if (object.color != null) { - result - ..add(r'color') - ..add(serializers.serialize(object.color, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Animal object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + yield r'className'; + yield serializers.serialize( + object.className, + specifiedType: const FullType(String), + ); + if (object.color != null) { + yield r'color'; + yield serializers.serialize( + object.color, + specifiedType: const FullType(String), + ); } + } - @override - Animal deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = AnimalBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'className': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.className = valueDes; - break; - case r'color': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.color = valueDes; - break; - } - } - return result.build(); + @override + Object serialize( + Serializers serializers, + Animal object, { + FullType specifiedType = FullType.unspecified, + }) { + if (object is Cat) { + return serializers.serialize(object, specifiedType: FullType(Cat))!; } + if (object is Dog) { + return serializers.serialize(object, specifiedType: FullType(Dog))!; + } + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + @override + Animal deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final serializedList = (serialized as Iterable).toList(); + final discIndex = serializedList.indexOf(Animal.discriminatorFieldName) + 1; + final discValue = serializers.deserialize(serializedList[discIndex], specifiedType: FullType(String)) as String; + switch (discValue) { + case 'Cat': + return serializers.deserialize(serialized, specifiedType: FullType(Cat)) as Cat; + case 'Dog': + return serializers.deserialize(serialized, specifiedType: FullType(Dog)) as Dog; + default: + return serializers.deserialize(serialized, specifiedType: FullType($Animal)) as $Animal; + } + } +} + +/// a concrete implementation of [Animal], since [Animal] is not instantiable +@BuiltValue(instantiable: true) +abstract class $Animal implements Animal, Built<$Animal, $AnimalBuilder> { + $Animal._(); + + factory $Animal([void Function($AnimalBuilder)? updates]) = _$$Animal; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults($AnimalBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer<$Animal> get serializer => _$$AnimalSerializer(); +} + +class _$$AnimalSerializer implements PrimitiveSerializer<$Animal> { + @override + final Iterable types = const [$Animal, _$$Animal]; + + @override + final String wireName = r'$Animal'; + + @override + Object serialize( + Serializers serializers, + $Animal object, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.serialize(object, specifiedType: FullType(Animal))!; + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required AnimalBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'className': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.className = valueDes; + break; + case r'color': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.color = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + $Animal deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = $AnimalBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/api_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/api_response.dart index c2ebff7ffe..aadcd792e2 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/api_response.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -13,89 +14,131 @@ part 'api_response.g.dart'; /// * [code] /// * [type] /// * [message] +@BuiltValue() abstract class ApiResponse implements Built { - @BuiltValueField(wireName: r'code') - int? get code; + @BuiltValueField(wireName: r'code') + int? get code; - @BuiltValueField(wireName: r'type') - String? get type; + @BuiltValueField(wireName: r'type') + String? get type; - @BuiltValueField(wireName: r'message') - String? get message; + @BuiltValueField(wireName: r'message') + String? get message; - ApiResponse._(); + ApiResponse._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ApiResponseBuilder b) => b; + factory ApiResponse([void updates(ApiResponseBuilder b)]) = _$ApiResponse; - factory ApiResponse([void updates(ApiResponseBuilder b)]) = _$ApiResponse; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ApiResponseBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ApiResponseSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ApiResponseSerializer(); } -class _$ApiResponseSerializer implements StructuredSerializer { - @override - final Iterable types = const [ApiResponse, _$ApiResponse]; +class _$ApiResponseSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ApiResponse, _$ApiResponse]; - @override - final String wireName = r'ApiResponse'; + @override + final String wireName = r'ApiResponse'; - @override - Iterable serialize(Serializers serializers, ApiResponse object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.code != null) { - result - ..add(r'code') - ..add(serializers.serialize(object.code, - specifiedType: const FullType(int))); - } - if (object.type != null) { - result - ..add(r'type') - ..add(serializers.serialize(object.type, - specifiedType: const FullType(String))); - } - if (object.message != null) { - result - ..add(r'message') - ..add(serializers.serialize(object.message, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ApiResponse object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.code != null) { + yield r'code'; + yield serializers.serialize( + object.code, + specifiedType: const FullType(int), + ); } - - @override - ApiResponse deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ApiResponseBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'code': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.code = valueDes; - break; - case r'type': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.type = valueDes; - break; - case r'message': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.message = valueDes; - break; - } - } - return result.build(); + if (object.type != null) { + yield r'type'; + yield serializers.serialize( + object.type, + specifiedType: const FullType(String), + ); } + if (object.message != null) { + yield r'message'; + yield serializers.serialize( + object.message, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + ApiResponse object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ApiResponseBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'code': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.code = valueDes; + break; + case r'type': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.type = valueDes; + break; + case r'message': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.message = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + ApiResponse deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ApiResponseBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart index 1fa583bccc..5bc0982b8a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,61 +13,97 @@ part 'array_of_array_of_number_only.g.dart'; /// /// Properties: /// * [arrayArrayNumber] +@BuiltValue() abstract class ArrayOfArrayOfNumberOnly implements Built { - @BuiltValueField(wireName: r'ArrayArrayNumber') - BuiltList>? get arrayArrayNumber; + @BuiltValueField(wireName: r'ArrayArrayNumber') + BuiltList>? get arrayArrayNumber; - ArrayOfArrayOfNumberOnly._(); + ArrayOfArrayOfNumberOnly._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ArrayOfArrayOfNumberOnlyBuilder b) => b; + factory ArrayOfArrayOfNumberOnly([void updates(ArrayOfArrayOfNumberOnlyBuilder b)]) = _$ArrayOfArrayOfNumberOnly; - factory ArrayOfArrayOfNumberOnly([void updates(ArrayOfArrayOfNumberOnlyBuilder b)]) = _$ArrayOfArrayOfNumberOnly; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ArrayOfArrayOfNumberOnlyBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ArrayOfArrayOfNumberOnlySerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ArrayOfArrayOfNumberOnlySerializer(); } -class _$ArrayOfArrayOfNumberOnlySerializer implements StructuredSerializer { - @override - final Iterable types = const [ArrayOfArrayOfNumberOnly, _$ArrayOfArrayOfNumberOnly]; +class _$ArrayOfArrayOfNumberOnlySerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ArrayOfArrayOfNumberOnly, _$ArrayOfArrayOfNumberOnly]; - @override - final String wireName = r'ArrayOfArrayOfNumberOnly'; + @override + final String wireName = r'ArrayOfArrayOfNumberOnly'; - @override - Iterable serialize(Serializers serializers, ArrayOfArrayOfNumberOnly object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.arrayArrayNumber != null) { - result - ..add(r'ArrayArrayNumber') - ..add(serializers.serialize(object.arrayArrayNumber, - specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(num)])]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ArrayOfArrayOfNumberOnly object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.arrayArrayNumber != null) { + yield r'ArrayArrayNumber'; + yield serializers.serialize( + object.arrayArrayNumber, + specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(num)])]), + ); } + } - @override - ArrayOfArrayOfNumberOnly deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ArrayOfArrayOfNumberOnlyBuilder(); + @override + Object serialize( + Serializers serializers, + ArrayOfArrayOfNumberOnly object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'ArrayArrayNumber': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(num)])])) as BuiltList>; - result.arrayArrayNumber.replace(valueDes); - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ArrayOfArrayOfNumberOnlyBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'ArrayArrayNumber': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(num)])]), + ) as BuiltList>; + result.arrayArrayNumber.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + ArrayOfArrayOfNumberOnly deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ArrayOfArrayOfNumberOnlyBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart index fcbd7d393b..72239924f5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,61 +13,97 @@ part 'array_of_number_only.g.dart'; /// /// Properties: /// * [arrayNumber] +@BuiltValue() abstract class ArrayOfNumberOnly implements Built { - @BuiltValueField(wireName: r'ArrayNumber') - BuiltList? get arrayNumber; + @BuiltValueField(wireName: r'ArrayNumber') + BuiltList? get arrayNumber; - ArrayOfNumberOnly._(); + ArrayOfNumberOnly._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ArrayOfNumberOnlyBuilder b) => b; + factory ArrayOfNumberOnly([void updates(ArrayOfNumberOnlyBuilder b)]) = _$ArrayOfNumberOnly; - factory ArrayOfNumberOnly([void updates(ArrayOfNumberOnlyBuilder b)]) = _$ArrayOfNumberOnly; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ArrayOfNumberOnlyBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ArrayOfNumberOnlySerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ArrayOfNumberOnlySerializer(); } -class _$ArrayOfNumberOnlySerializer implements StructuredSerializer { - @override - final Iterable types = const [ArrayOfNumberOnly, _$ArrayOfNumberOnly]; +class _$ArrayOfNumberOnlySerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ArrayOfNumberOnly, _$ArrayOfNumberOnly]; - @override - final String wireName = r'ArrayOfNumberOnly'; + @override + final String wireName = r'ArrayOfNumberOnly'; - @override - Iterable serialize(Serializers serializers, ArrayOfNumberOnly object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.arrayNumber != null) { - result - ..add(r'ArrayNumber') - ..add(serializers.serialize(object.arrayNumber, - specifiedType: const FullType(BuiltList, [FullType(num)]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ArrayOfNumberOnly object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.arrayNumber != null) { + yield r'ArrayNumber'; + yield serializers.serialize( + object.arrayNumber, + specifiedType: const FullType(BuiltList, [FullType(num)]), + ); } + } - @override - ArrayOfNumberOnly deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ArrayOfNumberOnlyBuilder(); + @override + Object serialize( + Serializers serializers, + ArrayOfNumberOnly object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'ArrayNumber': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType(num)])) as BuiltList; - result.arrayNumber.replace(valueDes); - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ArrayOfNumberOnlyBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'ArrayNumber': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType(num)]), + ) as BuiltList; + result.arrayNumber.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + ArrayOfNumberOnly deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ArrayOfNumberOnlyBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_test.dart index 8025d141c1..21f3a5a4c2 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/array_test.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:openapi/src/model/read_only_first.dart'; import 'package:built_value/built_value.dart'; @@ -15,89 +16,131 @@ part 'array_test.g.dart'; /// * [arrayOfString] /// * [arrayArrayOfInteger] /// * [arrayArrayOfModel] +@BuiltValue() abstract class ArrayTest implements Built { - @BuiltValueField(wireName: r'array_of_string') - BuiltList? get arrayOfString; + @BuiltValueField(wireName: r'array_of_string') + BuiltList? get arrayOfString; - @BuiltValueField(wireName: r'array_array_of_integer') - BuiltList>? get arrayArrayOfInteger; + @BuiltValueField(wireName: r'array_array_of_integer') + BuiltList>? get arrayArrayOfInteger; - @BuiltValueField(wireName: r'array_array_of_model') - BuiltList>? get arrayArrayOfModel; + @BuiltValueField(wireName: r'array_array_of_model') + BuiltList>? get arrayArrayOfModel; - ArrayTest._(); + ArrayTest._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ArrayTestBuilder b) => b; + factory ArrayTest([void updates(ArrayTestBuilder b)]) = _$ArrayTest; - factory ArrayTest([void updates(ArrayTestBuilder b)]) = _$ArrayTest; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ArrayTestBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ArrayTestSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ArrayTestSerializer(); } -class _$ArrayTestSerializer implements StructuredSerializer { - @override - final Iterable types = const [ArrayTest, _$ArrayTest]; +class _$ArrayTestSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ArrayTest, _$ArrayTest]; - @override - final String wireName = r'ArrayTest'; + @override + final String wireName = r'ArrayTest'; - @override - Iterable serialize(Serializers serializers, ArrayTest object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.arrayOfString != null) { - result - ..add(r'array_of_string') - ..add(serializers.serialize(object.arrayOfString, - specifiedType: const FullType(BuiltList, [FullType(String)]))); - } - if (object.arrayArrayOfInteger != null) { - result - ..add(r'array_array_of_integer') - ..add(serializers.serialize(object.arrayArrayOfInteger, - specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(int)])]))); - } - if (object.arrayArrayOfModel != null) { - result - ..add(r'array_array_of_model') - ..add(serializers.serialize(object.arrayArrayOfModel, - specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(ReadOnlyFirst)])]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ArrayTest object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.arrayOfString != null) { + yield r'array_of_string'; + yield serializers.serialize( + object.arrayOfString, + specifiedType: const FullType(BuiltList, [FullType(String)]), + ); } - - @override - ArrayTest deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ArrayTestBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'array_of_string': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType(String)])) as BuiltList; - result.arrayOfString.replace(valueDes); - break; - case r'array_array_of_integer': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(int)])])) as BuiltList>; - result.arrayArrayOfInteger.replace(valueDes); - break; - case r'array_array_of_model': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(ReadOnlyFirst)])])) as BuiltList>; - result.arrayArrayOfModel.replace(valueDes); - break; - } - } - return result.build(); + if (object.arrayArrayOfInteger != null) { + yield r'array_array_of_integer'; + yield serializers.serialize( + object.arrayArrayOfInteger, + specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(int)])]), + ); } + if (object.arrayArrayOfModel != null) { + yield r'array_array_of_model'; + yield serializers.serialize( + object.arrayArrayOfModel, + specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(ReadOnlyFirst)])]), + ); + } + } + + @override + Object serialize( + Serializers serializers, + ArrayTest object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ArrayTestBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'array_of_string': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType(String)]), + ) as BuiltList; + result.arrayOfString.replace(valueDes); + break; + case r'array_array_of_integer': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(int)])]), + ) as BuiltList>; + result.arrayArrayOfInteger.replace(valueDes); + break; + case r'array_array_of_model': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType(BuiltList, [FullType(ReadOnlyFirst)])]), + ) as BuiltList>; + result.arrayArrayOfModel.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + ArrayTest deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ArrayTestBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/capitalization.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/capitalization.dart index 15a8f080e9..75827b9a42 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/capitalization.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/capitalization.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -16,132 +17,183 @@ part 'capitalization.g.dart'; /// * [capitalSnake] /// * [sCAETHFlowPoints] /// * [ATT_NAME] - Name of the pet +@BuiltValue() abstract class Capitalization implements Built { - @BuiltValueField(wireName: r'smallCamel') - String? get smallCamel; + @BuiltValueField(wireName: r'smallCamel') + String? get smallCamel; - @BuiltValueField(wireName: r'CapitalCamel') - String? get capitalCamel; + @BuiltValueField(wireName: r'CapitalCamel') + String? get capitalCamel; - @BuiltValueField(wireName: r'small_Snake') - String? get smallSnake; + @BuiltValueField(wireName: r'small_Snake') + String? get smallSnake; - @BuiltValueField(wireName: r'Capital_Snake') - String? get capitalSnake; + @BuiltValueField(wireName: r'Capital_Snake') + String? get capitalSnake; - @BuiltValueField(wireName: r'SCA_ETH_Flow_Points') - String? get sCAETHFlowPoints; + @BuiltValueField(wireName: r'SCA_ETH_Flow_Points') + String? get sCAETHFlowPoints; - /// Name of the pet - @BuiltValueField(wireName: r'ATT_NAME') - String? get ATT_NAME; + /// Name of the pet + @BuiltValueField(wireName: r'ATT_NAME') + String? get ATT_NAME; - Capitalization._(); + Capitalization._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(CapitalizationBuilder b) => b; + factory Capitalization([void updates(CapitalizationBuilder b)]) = _$Capitalization; - factory Capitalization([void updates(CapitalizationBuilder b)]) = _$Capitalization; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(CapitalizationBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$CapitalizationSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$CapitalizationSerializer(); } -class _$CapitalizationSerializer implements StructuredSerializer { - @override - final Iterable types = const [Capitalization, _$Capitalization]; +class _$CapitalizationSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Capitalization, _$Capitalization]; - @override - final String wireName = r'Capitalization'; + @override + final String wireName = r'Capitalization'; - @override - Iterable serialize(Serializers serializers, Capitalization object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.smallCamel != null) { - result - ..add(r'smallCamel') - ..add(serializers.serialize(object.smallCamel, - specifiedType: const FullType(String))); - } - if (object.capitalCamel != null) { - result - ..add(r'CapitalCamel') - ..add(serializers.serialize(object.capitalCamel, - specifiedType: const FullType(String))); - } - if (object.smallSnake != null) { - result - ..add(r'small_Snake') - ..add(serializers.serialize(object.smallSnake, - specifiedType: const FullType(String))); - } - if (object.capitalSnake != null) { - result - ..add(r'Capital_Snake') - ..add(serializers.serialize(object.capitalSnake, - specifiedType: const FullType(String))); - } - if (object.sCAETHFlowPoints != null) { - result - ..add(r'SCA_ETH_Flow_Points') - ..add(serializers.serialize(object.sCAETHFlowPoints, - specifiedType: const FullType(String))); - } - if (object.ATT_NAME != null) { - result - ..add(r'ATT_NAME') - ..add(serializers.serialize(object.ATT_NAME, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Capitalization object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.smallCamel != null) { + yield r'smallCamel'; + yield serializers.serialize( + object.smallCamel, + specifiedType: const FullType(String), + ); } - - @override - Capitalization deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = CapitalizationBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'smallCamel': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.smallCamel = valueDes; - break; - case r'CapitalCamel': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.capitalCamel = valueDes; - break; - case r'small_Snake': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.smallSnake = valueDes; - break; - case r'Capital_Snake': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.capitalSnake = valueDes; - break; - case r'SCA_ETH_Flow_Points': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.sCAETHFlowPoints = valueDes; - break; - case r'ATT_NAME': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.ATT_NAME = valueDes; - break; - } - } - return result.build(); + if (object.capitalCamel != null) { + yield r'CapitalCamel'; + yield serializers.serialize( + object.capitalCamel, + specifiedType: const FullType(String), + ); } + if (object.smallSnake != null) { + yield r'small_Snake'; + yield serializers.serialize( + object.smallSnake, + specifiedType: const FullType(String), + ); + } + if (object.capitalSnake != null) { + yield r'Capital_Snake'; + yield serializers.serialize( + object.capitalSnake, + specifiedType: const FullType(String), + ); + } + if (object.sCAETHFlowPoints != null) { + yield r'SCA_ETH_Flow_Points'; + yield serializers.serialize( + object.sCAETHFlowPoints, + specifiedType: const FullType(String), + ); + } + if (object.ATT_NAME != null) { + yield r'ATT_NAME'; + yield serializers.serialize( + object.ATT_NAME, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Capitalization object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required CapitalizationBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'smallCamel': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.smallCamel = valueDes; + break; + case r'CapitalCamel': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.capitalCamel = valueDes; + break; + case r'small_Snake': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.smallSnake = valueDes; + break; + case r'Capital_Snake': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.capitalSnake = valueDes; + break; + case r'SCA_ETH_Flow_Points': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.sCAETHFlowPoints = valueDes; + break; + case r'ATT_NAME': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.ATT_NAME = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Capitalization deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = CapitalizationBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/cat.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/cat.dart index cad5f349da..31a2b14769 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/cat.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/cat.dart @@ -2,102 +2,137 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/animal.dart'; +import 'package:openapi/src/model/cat_all_of.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'cat.g.dart'; -// ignore_for_file: unused_import - /// Cat /// /// Properties: /// * [className] /// * [color] /// * [declawed] -abstract class Cat implements Built { - @BuiltValueField(wireName: r'className') - String get className; +@BuiltValue() +abstract class Cat implements Animal, CatAllOf, Built { + static const String discriminatorFieldName = r'className'; - @BuiltValueField(wireName: r'color') - String? get color; + Cat._(); - @BuiltValueField(wireName: r'declawed') - bool? get declawed; + factory Cat([void updates(CatBuilder b)]) = _$Cat; - Cat._(); + @BuiltValueHook(initializeBuilder: true) + static void _defaults(CatBuilder b) => b + ..color = 'red'; - @BuiltValueHook(initializeBuilder: true) - static void _defaults(CatBuilder b) => b - ..color = 'red'; - - factory Cat([void updates(CatBuilder b)]) = _$Cat; - - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$CatSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$CatSerializer(); } -class _$CatSerializer implements StructuredSerializer { - @override - final Iterable types = const [Cat, _$Cat]; +class _$CatSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Cat, _$Cat]; - @override - final String wireName = r'Cat'; + @override + final String wireName = r'Cat'; - @override - Iterable serialize(Serializers serializers, Cat object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - result - ..add(r'className') - ..add(serializers.serialize(object.className, - specifiedType: const FullType(String))); - if (object.color != null) { - result - ..add(r'color') - ..add(serializers.serialize(object.color, - specifiedType: const FullType(String))); - } - if (object.declawed != null) { - result - ..add(r'declawed') - ..add(serializers.serialize(object.declawed, - specifiedType: const FullType(bool))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Cat object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + yield r'className'; + yield serializers.serialize( + object.className, + specifiedType: const FullType(String), + ); + if (object.color != null) { + yield r'color'; + yield serializers.serialize( + object.color, + specifiedType: const FullType(String), + ); } - - @override - Cat deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = CatBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'className': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.className = valueDes; - break; - case r'color': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.color = valueDes; - break; - case r'declawed': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(bool)) as bool; - result.declawed = valueDes; - break; - } - } - return result.build(); + if (object.declawed != null) { + yield r'declawed'; + yield serializers.serialize( + object.declawed, + specifiedType: const FullType(bool), + ); } + } + + @override + Object serialize( + Serializers serializers, + Cat object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required CatBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'className': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.className = valueDes; + break; + case r'color': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.color = valueDes; + break; + case r'declawed': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(bool), + ) as bool; + result.declawed = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Cat deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = CatBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/cat_all_of.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/cat_all_of.dart index 1734098fe2..02d9cce0ca 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/cat_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/cat_all_of.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,61 +12,130 @@ part 'cat_all_of.g.dart'; /// /// Properties: /// * [declawed] -abstract class CatAllOf implements Built { - @BuiltValueField(wireName: r'declawed') - bool? get declawed; +@BuiltValue(instantiable: false) +abstract class CatAllOf { + @BuiltValueField(wireName: r'declawed') + bool? get declawed; - CatAllOf._(); - - @BuiltValueHook(initializeBuilder: true) - static void _defaults(CatAllOfBuilder b) => b; - - factory CatAllOf([void updates(CatAllOfBuilder b)]) = _$CatAllOf; - - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$CatAllOfSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$CatAllOfSerializer(); } -class _$CatAllOfSerializer implements StructuredSerializer { - @override - final Iterable types = const [CatAllOf, _$CatAllOf]; +class _$CatAllOfSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [CatAllOf]; - @override - final String wireName = r'CatAllOf'; + @override + final String wireName = r'CatAllOf'; - @override - Iterable serialize(Serializers serializers, CatAllOf object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.declawed != null) { - result - ..add(r'declawed') - ..add(serializers.serialize(object.declawed, - specifiedType: const FullType(bool))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + CatAllOf object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.declawed != null) { + yield r'declawed'; + yield serializers.serialize( + object.declawed, + specifiedType: const FullType(bool), + ); } + } - @override - CatAllOf deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = CatAllOfBuilder(); + @override + Object serialize( + Serializers serializers, + CatAllOf object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'declawed': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(bool)) as bool; - result.declawed = valueDes; - break; - } - } - return result.build(); - } + @override + CatAllOf deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.deserialize(serialized, specifiedType: FullType($CatAllOf)) as $CatAllOf; + } +} + +/// a concrete implementation of [CatAllOf], since [CatAllOf] is not instantiable +@BuiltValue(instantiable: true) +abstract class $CatAllOf implements CatAllOf, Built<$CatAllOf, $CatAllOfBuilder> { + $CatAllOf._(); + + factory $CatAllOf([void Function($CatAllOfBuilder)? updates]) = _$$CatAllOf; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults($CatAllOfBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer<$CatAllOf> get serializer => _$$CatAllOfSerializer(); +} + +class _$$CatAllOfSerializer implements PrimitiveSerializer<$CatAllOf> { + @override + final Iterable types = const [$CatAllOf, _$$CatAllOf]; + + @override + final String wireName = r'$CatAllOf'; + + @override + Object serialize( + Serializers serializers, + $CatAllOf object, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.serialize(object, specifiedType: FullType(CatAllOf))!; + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required CatAllOfBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'declawed': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(bool), + ) as bool; + result.declawed = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + $CatAllOf deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = $CatAllOfBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/category.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/category.dart index 9ee9a94a3e..3a541dd1fa 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/category.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/category.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,74 +13,113 @@ part 'category.g.dart'; /// Properties: /// * [id] /// * [name] +@BuiltValue() abstract class Category implements Built { - @BuiltValueField(wireName: r'id') - int? get id; + @BuiltValueField(wireName: r'id') + int? get id; - @BuiltValueField(wireName: r'name') - String get name; + @BuiltValueField(wireName: r'name') + String get name; - Category._(); + Category._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(CategoryBuilder b) => b - ..name = 'default-name'; + factory Category([void updates(CategoryBuilder b)]) = _$Category; - factory Category([void updates(CategoryBuilder b)]) = _$Category; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(CategoryBuilder b) => b + ..name = 'default-name'; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$CategorySerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$CategorySerializer(); } -class _$CategorySerializer implements StructuredSerializer { - @override - final Iterable types = const [Category, _$Category]; +class _$CategorySerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Category, _$Category]; - @override - final String wireName = r'Category'; + @override + final String wireName = r'Category'; - @override - Iterable serialize(Serializers serializers, Category object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.id != null) { - result - ..add(r'id') - ..add(serializers.serialize(object.id, - specifiedType: const FullType(int))); - } - result - ..add(r'name') - ..add(serializers.serialize(object.name, - specifiedType: const FullType(String))); - return result; + Iterable _serializeProperties( + Serializers serializers, + Category object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(int), + ); } + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(String), + ); + } - @override - Category deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = CategoryBuilder(); + @override + Object serialize( + Serializers serializers, + Category object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'id': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.id = valueDes; - break; - case r'name': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.name = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required CategoryBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.id = valueDes; + break; + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.name = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + Category deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = CategoryBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/class_model.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/class_model.dart index 3a000f56cb..51166943c6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/class_model.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/class_model.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,61 +12,97 @@ part 'class_model.g.dart'; /// /// Properties: /// * [classField] +@BuiltValue() abstract class ClassModel implements Built { - @BuiltValueField(wireName: r'_class') - String? get classField; + @BuiltValueField(wireName: r'_class') + String? get classField; - ClassModel._(); + ClassModel._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ClassModelBuilder b) => b; + factory ClassModel([void updates(ClassModelBuilder b)]) = _$ClassModel; - factory ClassModel([void updates(ClassModelBuilder b)]) = _$ClassModel; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ClassModelBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ClassModelSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ClassModelSerializer(); } -class _$ClassModelSerializer implements StructuredSerializer { - @override - final Iterable types = const [ClassModel, _$ClassModel]; +class _$ClassModelSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ClassModel, _$ClassModel]; - @override - final String wireName = r'ClassModel'; + @override + final String wireName = r'ClassModel'; - @override - Iterable serialize(Serializers serializers, ClassModel object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.classField != null) { - result - ..add(r'_class') - ..add(serializers.serialize(object.classField, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ClassModel object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.classField != null) { + yield r'_class'; + yield serializers.serialize( + object.classField, + specifiedType: const FullType(String), + ); } + } - @override - ClassModel deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ClassModelBuilder(); + @override + Object serialize( + Serializers serializers, + ClassModel object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'_class': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.classField = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ClassModelBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'_class': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.classField = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + ClassModel deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ClassModelBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/deprecated_object.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/deprecated_object.dart index 98db39b4f4..91d0b428e9 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/deprecated_object.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/deprecated_object.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,61 +12,97 @@ part 'deprecated_object.g.dart'; /// /// Properties: /// * [name] +@BuiltValue() abstract class DeprecatedObject implements Built { - @BuiltValueField(wireName: r'name') - String? get name; + @BuiltValueField(wireName: r'name') + String? get name; - DeprecatedObject._(); + DeprecatedObject._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(DeprecatedObjectBuilder b) => b; + factory DeprecatedObject([void updates(DeprecatedObjectBuilder b)]) = _$DeprecatedObject; - factory DeprecatedObject([void updates(DeprecatedObjectBuilder b)]) = _$DeprecatedObject; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(DeprecatedObjectBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$DeprecatedObjectSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$DeprecatedObjectSerializer(); } -class _$DeprecatedObjectSerializer implements StructuredSerializer { - @override - final Iterable types = const [DeprecatedObject, _$DeprecatedObject]; +class _$DeprecatedObjectSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [DeprecatedObject, _$DeprecatedObject]; - @override - final String wireName = r'DeprecatedObject'; + @override + final String wireName = r'DeprecatedObject'; - @override - Iterable serialize(Serializers serializers, DeprecatedObject object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.name != null) { - result - ..add(r'name') - ..add(serializers.serialize(object.name, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + DeprecatedObject object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.name != null) { + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(String), + ); } + } - @override - DeprecatedObject deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = DeprecatedObjectBuilder(); + @override + Object serialize( + Serializers serializers, + DeprecatedObject object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'name': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.name = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required DeprecatedObjectBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.name = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + DeprecatedObject deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = DeprecatedObjectBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/dog.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/dog.dart index 2ca3df3863..b7cb6bf731 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/dog.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/dog.dart @@ -2,102 +2,137 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element +import 'package:openapi/src/model/dog_all_of.dart'; import 'package:openapi/src/model/animal.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'dog.g.dart'; -// ignore_for_file: unused_import - /// Dog /// /// Properties: /// * [className] /// * [color] /// * [breed] -abstract class Dog implements Built { - @BuiltValueField(wireName: r'className') - String get className; +@BuiltValue() +abstract class Dog implements Animal, DogAllOf, Built { + static const String discriminatorFieldName = r'className'; - @BuiltValueField(wireName: r'color') - String? get color; + Dog._(); - @BuiltValueField(wireName: r'breed') - String? get breed; + factory Dog([void updates(DogBuilder b)]) = _$Dog; - Dog._(); + @BuiltValueHook(initializeBuilder: true) + static void _defaults(DogBuilder b) => b + ..color = 'red'; - @BuiltValueHook(initializeBuilder: true) - static void _defaults(DogBuilder b) => b - ..color = 'red'; - - factory Dog([void updates(DogBuilder b)]) = _$Dog; - - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$DogSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$DogSerializer(); } -class _$DogSerializer implements StructuredSerializer { - @override - final Iterable types = const [Dog, _$Dog]; +class _$DogSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Dog, _$Dog]; - @override - final String wireName = r'Dog'; + @override + final String wireName = r'Dog'; - @override - Iterable serialize(Serializers serializers, Dog object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - result - ..add(r'className') - ..add(serializers.serialize(object.className, - specifiedType: const FullType(String))); - if (object.color != null) { - result - ..add(r'color') - ..add(serializers.serialize(object.color, - specifiedType: const FullType(String))); - } - if (object.breed != null) { - result - ..add(r'breed') - ..add(serializers.serialize(object.breed, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Dog object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + yield r'className'; + yield serializers.serialize( + object.className, + specifiedType: const FullType(String), + ); + if (object.color != null) { + yield r'color'; + yield serializers.serialize( + object.color, + specifiedType: const FullType(String), + ); } - - @override - Dog deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = DogBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'className': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.className = valueDes; - break; - case r'color': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.color = valueDes; - break; - case r'breed': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.breed = valueDes; - break; - } - } - return result.build(); + if (object.breed != null) { + yield r'breed'; + yield serializers.serialize( + object.breed, + specifiedType: const FullType(String), + ); } + } + + @override + Object serialize( + Serializers serializers, + Dog object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required DogBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'className': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.className = valueDes; + break; + case r'color': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.color = valueDes; + break; + case r'breed': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.breed = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Dog deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = DogBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/dog_all_of.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/dog_all_of.dart index 23387e4da7..bd52567fa6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/dog_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/dog_all_of.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,61 +12,130 @@ part 'dog_all_of.g.dart'; /// /// Properties: /// * [breed] -abstract class DogAllOf implements Built { - @BuiltValueField(wireName: r'breed') - String? get breed; +@BuiltValue(instantiable: false) +abstract class DogAllOf { + @BuiltValueField(wireName: r'breed') + String? get breed; - DogAllOf._(); - - @BuiltValueHook(initializeBuilder: true) - static void _defaults(DogAllOfBuilder b) => b; - - factory DogAllOf([void updates(DogAllOfBuilder b)]) = _$DogAllOf; - - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$DogAllOfSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$DogAllOfSerializer(); } -class _$DogAllOfSerializer implements StructuredSerializer { - @override - final Iterable types = const [DogAllOf, _$DogAllOf]; +class _$DogAllOfSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [DogAllOf]; - @override - final String wireName = r'DogAllOf'; + @override + final String wireName = r'DogAllOf'; - @override - Iterable serialize(Serializers serializers, DogAllOf object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.breed != null) { - result - ..add(r'breed') - ..add(serializers.serialize(object.breed, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + DogAllOf object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.breed != null) { + yield r'breed'; + yield serializers.serialize( + object.breed, + specifiedType: const FullType(String), + ); } + } - @override - DogAllOf deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = DogAllOfBuilder(); + @override + Object serialize( + Serializers serializers, + DogAllOf object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'breed': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.breed = valueDes; - break; - } - } - return result.build(); - } + @override + DogAllOf deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.deserialize(serialized, specifiedType: FullType($DogAllOf)) as $DogAllOf; + } +} + +/// a concrete implementation of [DogAllOf], since [DogAllOf] is not instantiable +@BuiltValue(instantiable: true) +abstract class $DogAllOf implements DogAllOf, Built<$DogAllOf, $DogAllOfBuilder> { + $DogAllOf._(); + + factory $DogAllOf([void Function($DogAllOfBuilder)? updates]) = _$$DogAllOf; + + @BuiltValueHook(initializeBuilder: true) + static void _defaults($DogAllOfBuilder b) => b; + + @BuiltValueSerializer(custom: true) + static Serializer<$DogAllOf> get serializer => _$$DogAllOfSerializer(); +} + +class _$$DogAllOfSerializer implements PrimitiveSerializer<$DogAllOf> { + @override + final Iterable types = const [$DogAllOf, _$$DogAllOf]; + + @override + final String wireName = r'$DogAllOf'; + + @override + Object serialize( + Serializers serializers, + $DogAllOf object, { + FullType specifiedType = FullType.unspecified, + }) { + return serializers.serialize(object, specifiedType: FullType(DogAllOf))!; + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required DogAllOfBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'breed': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.breed = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + $DogAllOf deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = $DogAllOfBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/enum_arrays.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/enum_arrays.dart index 2626b35426..b79a175e83 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/enum_arrays.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/enum_arrays.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -13,78 +14,117 @@ part 'enum_arrays.g.dart'; /// Properties: /// * [justSymbol] /// * [arrayEnum] +@BuiltValue() abstract class EnumArrays implements Built { - @BuiltValueField(wireName: r'just_symbol') - EnumArraysJustSymbolEnum? get justSymbol; - // enum justSymbolEnum { >=, $, }; + @BuiltValueField(wireName: r'just_symbol') + EnumArraysJustSymbolEnum? get justSymbol; + // enum justSymbolEnum { >=, $, }; - @BuiltValueField(wireName: r'array_enum') - BuiltList? get arrayEnum; - // enum arrayEnumEnum { fish, crab, }; + @BuiltValueField(wireName: r'array_enum') + BuiltList? get arrayEnum; + // enum arrayEnumEnum { fish, crab, }; - EnumArrays._(); + EnumArrays._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(EnumArraysBuilder b) => b; + factory EnumArrays([void updates(EnumArraysBuilder b)]) = _$EnumArrays; - factory EnumArrays([void updates(EnumArraysBuilder b)]) = _$EnumArrays; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(EnumArraysBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$EnumArraysSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$EnumArraysSerializer(); } -class _$EnumArraysSerializer implements StructuredSerializer { - @override - final Iterable types = const [EnumArrays, _$EnumArrays]; +class _$EnumArraysSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [EnumArrays, _$EnumArrays]; - @override - final String wireName = r'EnumArrays'; + @override + final String wireName = r'EnumArrays'; - @override - Iterable serialize(Serializers serializers, EnumArrays object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.justSymbol != null) { - result - ..add(r'just_symbol') - ..add(serializers.serialize(object.justSymbol, - specifiedType: const FullType(EnumArraysJustSymbolEnum))); - } - if (object.arrayEnum != null) { - result - ..add(r'array_enum') - ..add(serializers.serialize(object.arrayEnum, - specifiedType: const FullType(BuiltList, [FullType(EnumArraysArrayEnumEnum)]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + EnumArrays object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.justSymbol != null) { + yield r'just_symbol'; + yield serializers.serialize( + object.justSymbol, + specifiedType: const FullType(EnumArraysJustSymbolEnum), + ); } - - @override - EnumArrays deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = EnumArraysBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'just_symbol': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(EnumArraysJustSymbolEnum)) as EnumArraysJustSymbolEnum; - result.justSymbol = valueDes; - break; - case r'array_enum': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType(EnumArraysArrayEnumEnum)])) as BuiltList; - result.arrayEnum.replace(valueDes); - break; - } - } - return result.build(); + if (object.arrayEnum != null) { + yield r'array_enum'; + yield serializers.serialize( + object.arrayEnum, + specifiedType: const FullType(BuiltList, [FullType(EnumArraysArrayEnumEnum)]), + ); } + } + + @override + Object serialize( + Serializers serializers, + EnumArrays object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required EnumArraysBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'just_symbol': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(EnumArraysJustSymbolEnum), + ) as EnumArraysJustSymbolEnum; + result.justSymbol = valueDes; + break; + case r'array_enum': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType(EnumArraysArrayEnumEnum)]), + ) as BuiltList; + result.arrayEnum.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + EnumArrays deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = EnumArraysBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } class EnumArraysJustSymbolEnum extends EnumClass { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/enum_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/enum_test.dart index ff022e646e..831f5b9d6d 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/enum_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/enum_test.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/outer_enum.dart'; import 'package:openapi/src/model/outer_enum_default_value.dart'; import 'package:built_collection/built_collection.dart'; @@ -23,167 +24,224 @@ part 'enum_test.g.dart'; /// * [outerEnumInteger] /// * [outerEnumDefaultValue] /// * [outerEnumIntegerDefaultValue] +@BuiltValue() abstract class EnumTest implements Built { - @BuiltValueField(wireName: r'enum_string') - EnumTestEnumStringEnum? get enumString; - // enum enumStringEnum { UPPER, lower, , }; + @BuiltValueField(wireName: r'enum_string') + EnumTestEnumStringEnum? get enumString; + // enum enumStringEnum { UPPER, lower, , }; - @BuiltValueField(wireName: r'enum_string_required') - EnumTestEnumStringRequiredEnum get enumStringRequired; - // enum enumStringRequiredEnum { UPPER, lower, , }; + @BuiltValueField(wireName: r'enum_string_required') + EnumTestEnumStringRequiredEnum get enumStringRequired; + // enum enumStringRequiredEnum { UPPER, lower, , }; - @BuiltValueField(wireName: r'enum_integer') - EnumTestEnumIntegerEnum? get enumInteger; - // enum enumIntegerEnum { 1, -1, }; + @BuiltValueField(wireName: r'enum_integer') + EnumTestEnumIntegerEnum? get enumInteger; + // enum enumIntegerEnum { 1, -1, }; - @BuiltValueField(wireName: r'enum_number') - EnumTestEnumNumberEnum? get enumNumber; - // enum enumNumberEnum { 1.1, -1.2, }; + @BuiltValueField(wireName: r'enum_number') + EnumTestEnumNumberEnum? get enumNumber; + // enum enumNumberEnum { 1.1, -1.2, }; - @BuiltValueField(wireName: r'outerEnum') - OuterEnum? get outerEnum; - // enum outerEnumEnum { placed, approved, delivered, }; + @BuiltValueField(wireName: r'outerEnum') + OuterEnum? get outerEnum; + // enum outerEnumEnum { placed, approved, delivered, }; - @BuiltValueField(wireName: r'outerEnumInteger') - OuterEnumInteger? get outerEnumInteger; - // enum outerEnumIntegerEnum { 0, 1, 2, }; + @BuiltValueField(wireName: r'outerEnumInteger') + OuterEnumInteger? get outerEnumInteger; + // enum outerEnumIntegerEnum { 0, 1, 2, }; - @BuiltValueField(wireName: r'outerEnumDefaultValue') - OuterEnumDefaultValue? get outerEnumDefaultValue; - // enum outerEnumDefaultValueEnum { placed, approved, delivered, }; + @BuiltValueField(wireName: r'outerEnumDefaultValue') + OuterEnumDefaultValue? get outerEnumDefaultValue; + // enum outerEnumDefaultValueEnum { placed, approved, delivered, }; - @BuiltValueField(wireName: r'outerEnumIntegerDefaultValue') - OuterEnumIntegerDefaultValue? get outerEnumIntegerDefaultValue; - // enum outerEnumIntegerDefaultValueEnum { 0, 1, 2, }; + @BuiltValueField(wireName: r'outerEnumIntegerDefaultValue') + OuterEnumIntegerDefaultValue? get outerEnumIntegerDefaultValue; + // enum outerEnumIntegerDefaultValueEnum { 0, 1, 2, }; - EnumTest._(); + EnumTest._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(EnumTestBuilder b) => b; + factory EnumTest([void updates(EnumTestBuilder b)]) = _$EnumTest; - factory EnumTest([void updates(EnumTestBuilder b)]) = _$EnumTest; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(EnumTestBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$EnumTestSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$EnumTestSerializer(); } -class _$EnumTestSerializer implements StructuredSerializer { - @override - final Iterable types = const [EnumTest, _$EnumTest]; +class _$EnumTestSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [EnumTest, _$EnumTest]; - @override - final String wireName = r'EnumTest'; + @override + final String wireName = r'EnumTest'; - @override - Iterable serialize(Serializers serializers, EnumTest object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.enumString != null) { - result - ..add(r'enum_string') - ..add(serializers.serialize(object.enumString, - specifiedType: const FullType(EnumTestEnumStringEnum))); - } - result - ..add(r'enum_string_required') - ..add(serializers.serialize(object.enumStringRequired, - specifiedType: const FullType(EnumTestEnumStringRequiredEnum))); - if (object.enumInteger != null) { - result - ..add(r'enum_integer') - ..add(serializers.serialize(object.enumInteger, - specifiedType: const FullType(EnumTestEnumIntegerEnum))); - } - if (object.enumNumber != null) { - result - ..add(r'enum_number') - ..add(serializers.serialize(object.enumNumber, - specifiedType: const FullType(EnumTestEnumNumberEnum))); - } - if (object.outerEnum != null) { - result - ..add(r'outerEnum') - ..add(serializers.serialize(object.outerEnum, - specifiedType: const FullType.nullable(OuterEnum))); - } - if (object.outerEnumInteger != null) { - result - ..add(r'outerEnumInteger') - ..add(serializers.serialize(object.outerEnumInteger, - specifiedType: const FullType(OuterEnumInteger))); - } - if (object.outerEnumDefaultValue != null) { - result - ..add(r'outerEnumDefaultValue') - ..add(serializers.serialize(object.outerEnumDefaultValue, - specifiedType: const FullType(OuterEnumDefaultValue))); - } - if (object.outerEnumIntegerDefaultValue != null) { - result - ..add(r'outerEnumIntegerDefaultValue') - ..add(serializers.serialize(object.outerEnumIntegerDefaultValue, - specifiedType: const FullType(OuterEnumIntegerDefaultValue))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + EnumTest object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.enumString != null) { + yield r'enum_string'; + yield serializers.serialize( + object.enumString, + specifiedType: const FullType(EnumTestEnumStringEnum), + ); } - - @override - EnumTest deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = EnumTestBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'enum_string': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(EnumTestEnumStringEnum)) as EnumTestEnumStringEnum; - result.enumString = valueDes; - break; - case r'enum_string_required': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(EnumTestEnumStringRequiredEnum)) as EnumTestEnumStringRequiredEnum; - result.enumStringRequired = valueDes; - break; - case r'enum_integer': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(EnumTestEnumIntegerEnum)) as EnumTestEnumIntegerEnum; - result.enumInteger = valueDes; - break; - case r'enum_number': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(EnumTestEnumNumberEnum)) as EnumTestEnumNumberEnum; - result.enumNumber = valueDes; - break; - case r'outerEnum': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(OuterEnum)) as OuterEnum?; - if (valueDes == null) continue; - result.outerEnum = valueDes; - break; - case r'outerEnumInteger': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(OuterEnumInteger)) as OuterEnumInteger; - result.outerEnumInteger = valueDes; - break; - case r'outerEnumDefaultValue': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(OuterEnumDefaultValue)) as OuterEnumDefaultValue; - result.outerEnumDefaultValue = valueDes; - break; - case r'outerEnumIntegerDefaultValue': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(OuterEnumIntegerDefaultValue)) as OuterEnumIntegerDefaultValue; - result.outerEnumIntegerDefaultValue = valueDes; - break; - } - } - return result.build(); + yield r'enum_string_required'; + yield serializers.serialize( + object.enumStringRequired, + specifiedType: const FullType(EnumTestEnumStringRequiredEnum), + ); + if (object.enumInteger != null) { + yield r'enum_integer'; + yield serializers.serialize( + object.enumInteger, + specifiedType: const FullType(EnumTestEnumIntegerEnum), + ); } + if (object.enumNumber != null) { + yield r'enum_number'; + yield serializers.serialize( + object.enumNumber, + specifiedType: const FullType(EnumTestEnumNumberEnum), + ); + } + if (object.outerEnum != null) { + yield r'outerEnum'; + yield serializers.serialize( + object.outerEnum, + specifiedType: const FullType.nullable(OuterEnum), + ); + } + if (object.outerEnumInteger != null) { + yield r'outerEnumInteger'; + yield serializers.serialize( + object.outerEnumInteger, + specifiedType: const FullType(OuterEnumInteger), + ); + } + if (object.outerEnumDefaultValue != null) { + yield r'outerEnumDefaultValue'; + yield serializers.serialize( + object.outerEnumDefaultValue, + specifiedType: const FullType(OuterEnumDefaultValue), + ); + } + if (object.outerEnumIntegerDefaultValue != null) { + yield r'outerEnumIntegerDefaultValue'; + yield serializers.serialize( + object.outerEnumIntegerDefaultValue, + specifiedType: const FullType(OuterEnumIntegerDefaultValue), + ); + } + } + + @override + Object serialize( + Serializers serializers, + EnumTest object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required EnumTestBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'enum_string': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(EnumTestEnumStringEnum), + ) as EnumTestEnumStringEnum; + result.enumString = valueDes; + break; + case r'enum_string_required': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(EnumTestEnumStringRequiredEnum), + ) as EnumTestEnumStringRequiredEnum; + result.enumStringRequired = valueDes; + break; + case r'enum_integer': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(EnumTestEnumIntegerEnum), + ) as EnumTestEnumIntegerEnum; + result.enumInteger = valueDes; + break; + case r'enum_number': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(EnumTestEnumNumberEnum), + ) as EnumTestEnumNumberEnum; + result.enumNumber = valueDes; + break; + case r'outerEnum': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(OuterEnum), + ) as OuterEnum?; + if (valueDes == null) continue; + result.outerEnum = valueDes; + break; + case r'outerEnumInteger': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(OuterEnumInteger), + ) as OuterEnumInteger; + result.outerEnumInteger = valueDes; + break; + case r'outerEnumDefaultValue': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(OuterEnumDefaultValue), + ) as OuterEnumDefaultValue; + result.outerEnumDefaultValue = valueDes; + break; + case r'outerEnumIntegerDefaultValue': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(OuterEnumIntegerDefaultValue), + ) as OuterEnumIntegerDefaultValue; + result.outerEnumIntegerDefaultValue = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + EnumTest deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = EnumTestBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } class EnumTestEnumStringEnum extends EnumClass { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart index 7a2090e87d..5ab41d14f4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:openapi/src/model/model_file.dart'; import 'package:built_value/built_value.dart'; @@ -14,75 +15,114 @@ part 'file_schema_test_class.g.dart'; /// Properties: /// * [file] /// * [files] +@BuiltValue() abstract class FileSchemaTestClass implements Built { - @BuiltValueField(wireName: r'file') - ModelFile? get file; + @BuiltValueField(wireName: r'file') + ModelFile? get file; - @BuiltValueField(wireName: r'files') - BuiltList? get files; + @BuiltValueField(wireName: r'files') + BuiltList? get files; - FileSchemaTestClass._(); + FileSchemaTestClass._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(FileSchemaTestClassBuilder b) => b; + factory FileSchemaTestClass([void updates(FileSchemaTestClassBuilder b)]) = _$FileSchemaTestClass; - factory FileSchemaTestClass([void updates(FileSchemaTestClassBuilder b)]) = _$FileSchemaTestClass; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(FileSchemaTestClassBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$FileSchemaTestClassSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$FileSchemaTestClassSerializer(); } -class _$FileSchemaTestClassSerializer implements StructuredSerializer { - @override - final Iterable types = const [FileSchemaTestClass, _$FileSchemaTestClass]; +class _$FileSchemaTestClassSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [FileSchemaTestClass, _$FileSchemaTestClass]; - @override - final String wireName = r'FileSchemaTestClass'; + @override + final String wireName = r'FileSchemaTestClass'; - @override - Iterable serialize(Serializers serializers, FileSchemaTestClass object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.file != null) { - result - ..add(r'file') - ..add(serializers.serialize(object.file, - specifiedType: const FullType(ModelFile))); - } - if (object.files != null) { - result - ..add(r'files') - ..add(serializers.serialize(object.files, - specifiedType: const FullType(BuiltList, [FullType(ModelFile)]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + FileSchemaTestClass object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.file != null) { + yield r'file'; + yield serializers.serialize( + object.file, + specifiedType: const FullType(ModelFile), + ); } - - @override - FileSchemaTestClass deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = FileSchemaTestClassBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'file': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(ModelFile)) as ModelFile; - result.file.replace(valueDes); - break; - case r'files': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType(ModelFile)])) as BuiltList; - result.files.replace(valueDes); - break; - } - } - return result.build(); + if (object.files != null) { + yield r'files'; + yield serializers.serialize( + object.files, + specifiedType: const FullType(BuiltList, [FullType(ModelFile)]), + ); } + } + + @override + Object serialize( + Serializers serializers, + FileSchemaTestClass object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required FileSchemaTestClassBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'file': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(ModelFile), + ) as ModelFile; + result.file.replace(valueDes); + break; + case r'files': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType(ModelFile)]), + ) as BuiltList; + result.files.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + FileSchemaTestClass deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = FileSchemaTestClassBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/foo.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/foo.dart index dd3691968d..57e0992c67 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/foo.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/foo.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,62 +12,98 @@ part 'foo.g.dart'; /// /// Properties: /// * [bar] +@BuiltValue() abstract class Foo implements Built { - @BuiltValueField(wireName: r'bar') - String? get bar; + @BuiltValueField(wireName: r'bar') + String? get bar; - Foo._(); + Foo._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(FooBuilder b) => b - ..bar = 'bar'; + factory Foo([void updates(FooBuilder b)]) = _$Foo; - factory Foo([void updates(FooBuilder b)]) = _$Foo; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(FooBuilder b) => b + ..bar = 'bar'; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$FooSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$FooSerializer(); } -class _$FooSerializer implements StructuredSerializer { - @override - final Iterable types = const [Foo, _$Foo]; +class _$FooSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Foo, _$Foo]; - @override - final String wireName = r'Foo'; + @override + final String wireName = r'Foo'; - @override - Iterable serialize(Serializers serializers, Foo object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.bar != null) { - result - ..add(r'bar') - ..add(serializers.serialize(object.bar, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Foo object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.bar != null) { + yield r'bar'; + yield serializers.serialize( + object.bar, + specifiedType: const FullType(String), + ); } + } - @override - Foo deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = FooBuilder(); + @override + Object serialize( + Serializers serializers, + Foo object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'bar': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.bar = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required FooBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'bar': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.bar = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + Foo deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = FooBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/foo_get_default_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/foo_get_default_response.dart index 655b5f480d..b5903ebd5d 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/foo_get_default_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/foo_get_default_response.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/foo.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,61 +13,97 @@ part 'foo_get_default_response.g.dart'; /// /// Properties: /// * [string] +@BuiltValue() abstract class FooGetDefaultResponse implements Built { - @BuiltValueField(wireName: r'string') - Foo? get string; + @BuiltValueField(wireName: r'string') + Foo? get string; - FooGetDefaultResponse._(); + FooGetDefaultResponse._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(FooGetDefaultResponseBuilder b) => b; + factory FooGetDefaultResponse([void updates(FooGetDefaultResponseBuilder b)]) = _$FooGetDefaultResponse; - factory FooGetDefaultResponse([void updates(FooGetDefaultResponseBuilder b)]) = _$FooGetDefaultResponse; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(FooGetDefaultResponseBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$FooGetDefaultResponseSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$FooGetDefaultResponseSerializer(); } -class _$FooGetDefaultResponseSerializer implements StructuredSerializer { - @override - final Iterable types = const [FooGetDefaultResponse, _$FooGetDefaultResponse]; +class _$FooGetDefaultResponseSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [FooGetDefaultResponse, _$FooGetDefaultResponse]; - @override - final String wireName = r'FooGetDefaultResponse'; + @override + final String wireName = r'FooGetDefaultResponse'; - @override - Iterable serialize(Serializers serializers, FooGetDefaultResponse object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.string != null) { - result - ..add(r'string') - ..add(serializers.serialize(object.string, - specifiedType: const FullType(Foo))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + FooGetDefaultResponse object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.string != null) { + yield r'string'; + yield serializers.serialize( + object.string, + specifiedType: const FullType(Foo), + ); } + } - @override - FooGetDefaultResponse deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = FooGetDefaultResponseBuilder(); + @override + Object serialize( + Serializers serializers, + FooGetDefaultResponse object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'string': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(Foo)) as Foo; - result.string.replace(valueDes); - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required FooGetDefaultResponseBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'string': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(Foo), + ) as Foo; + result.string.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + FooGetDefaultResponse deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = FooGetDefaultResponseBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/format_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/format_test.dart index cf1be44ab5..3377523147 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/format_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/format_test.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'dart:typed_data'; import 'package:openapi/src/model/date.dart'; import 'package:built_value/built_value.dart'; @@ -28,265 +29,346 @@ part 'format_test.g.dart'; /// * [password] /// * [patternWithDigits] - A string that is a 10 digit number. Can have leading zeros. /// * [patternWithDigitsAndDelimiter] - A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. +@BuiltValue() abstract class FormatTest implements Built { - @BuiltValueField(wireName: r'integer') - int? get integer; + @BuiltValueField(wireName: r'integer') + int? get integer; - @BuiltValueField(wireName: r'int32') - int? get int32; + @BuiltValueField(wireName: r'int32') + int? get int32; - @BuiltValueField(wireName: r'int64') - int? get int64; + @BuiltValueField(wireName: r'int64') + int? get int64; - @BuiltValueField(wireName: r'number') - num get number; + @BuiltValueField(wireName: r'number') + num get number; - @BuiltValueField(wireName: r'float') - double? get float; + @BuiltValueField(wireName: r'float') + double? get float; - @BuiltValueField(wireName: r'double') - double? get double_; + @BuiltValueField(wireName: r'double') + double? get double_; - @BuiltValueField(wireName: r'decimal') - double? get decimal; + @BuiltValueField(wireName: r'decimal') + double? get decimal; - @BuiltValueField(wireName: r'string') - String? get string; + @BuiltValueField(wireName: r'string') + String? get string; - @BuiltValueField(wireName: r'byte') - String get byte; + @BuiltValueField(wireName: r'byte') + String get byte; - @BuiltValueField(wireName: r'binary') - Uint8List? get binary; + @BuiltValueField(wireName: r'binary') + Uint8List? get binary; - @BuiltValueField(wireName: r'date') - Date get date; + @BuiltValueField(wireName: r'date') + Date get date; - @BuiltValueField(wireName: r'dateTime') - DateTime? get dateTime; + @BuiltValueField(wireName: r'dateTime') + DateTime? get dateTime; - @BuiltValueField(wireName: r'uuid') - String? get uuid; + @BuiltValueField(wireName: r'uuid') + String? get uuid; - @BuiltValueField(wireName: r'password') - String get password; + @BuiltValueField(wireName: r'password') + String get password; - /// A string that is a 10 digit number. Can have leading zeros. - @BuiltValueField(wireName: r'pattern_with_digits') - String? get patternWithDigits; + /// A string that is a 10 digit number. Can have leading zeros. + @BuiltValueField(wireName: r'pattern_with_digits') + String? get patternWithDigits; - /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. - @BuiltValueField(wireName: r'pattern_with_digits_and_delimiter') - String? get patternWithDigitsAndDelimiter; + /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + @BuiltValueField(wireName: r'pattern_with_digits_and_delimiter') + String? get patternWithDigitsAndDelimiter; - FormatTest._(); + FormatTest._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(FormatTestBuilder b) => b; + factory FormatTest([void updates(FormatTestBuilder b)]) = _$FormatTest; - factory FormatTest([void updates(FormatTestBuilder b)]) = _$FormatTest; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(FormatTestBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$FormatTestSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$FormatTestSerializer(); } -class _$FormatTestSerializer implements StructuredSerializer { - @override - final Iterable types = const [FormatTest, _$FormatTest]; +class _$FormatTestSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [FormatTest, _$FormatTest]; - @override - final String wireName = r'FormatTest'; + @override + final String wireName = r'FormatTest'; - @override - Iterable serialize(Serializers serializers, FormatTest object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.integer != null) { - result - ..add(r'integer') - ..add(serializers.serialize(object.integer, - specifiedType: const FullType(int))); - } - if (object.int32 != null) { - result - ..add(r'int32') - ..add(serializers.serialize(object.int32, - specifiedType: const FullType(int))); - } - if (object.int64 != null) { - result - ..add(r'int64') - ..add(serializers.serialize(object.int64, - specifiedType: const FullType(int))); - } - result - ..add(r'number') - ..add(serializers.serialize(object.number, - specifiedType: const FullType(num))); - if (object.float != null) { - result - ..add(r'float') - ..add(serializers.serialize(object.float, - specifiedType: const FullType(double))); - } - if (object.double_ != null) { - result - ..add(r'double') - ..add(serializers.serialize(object.double_, - specifiedType: const FullType(double))); - } - if (object.decimal != null) { - result - ..add(r'decimal') - ..add(serializers.serialize(object.decimal, - specifiedType: const FullType(double))); - } - if (object.string != null) { - result - ..add(r'string') - ..add(serializers.serialize(object.string, - specifiedType: const FullType(String))); - } - result - ..add(r'byte') - ..add(serializers.serialize(object.byte, - specifiedType: const FullType(String))); - if (object.binary != null) { - result - ..add(r'binary') - ..add(serializers.serialize(object.binary, - specifiedType: const FullType(Uint8List))); - } - result - ..add(r'date') - ..add(serializers.serialize(object.date, - specifiedType: const FullType(Date))); - if (object.dateTime != null) { - result - ..add(r'dateTime') - ..add(serializers.serialize(object.dateTime, - specifiedType: const FullType(DateTime))); - } - if (object.uuid != null) { - result - ..add(r'uuid') - ..add(serializers.serialize(object.uuid, - specifiedType: const FullType(String))); - } - result - ..add(r'password') - ..add(serializers.serialize(object.password, - specifiedType: const FullType(String))); - if (object.patternWithDigits != null) { - result - ..add(r'pattern_with_digits') - ..add(serializers.serialize(object.patternWithDigits, - specifiedType: const FullType(String))); - } - if (object.patternWithDigitsAndDelimiter != null) { - result - ..add(r'pattern_with_digits_and_delimiter') - ..add(serializers.serialize(object.patternWithDigitsAndDelimiter, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + FormatTest object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.integer != null) { + yield r'integer'; + yield serializers.serialize( + object.integer, + specifiedType: const FullType(int), + ); } - - @override - FormatTest deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = FormatTestBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'integer': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.integer = valueDes; - break; - case r'int32': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.int32 = valueDes; - break; - case r'int64': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.int64 = valueDes; - break; - case r'number': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(num)) as num; - result.number = valueDes; - break; - case r'float': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(double)) as double; - result.float = valueDes; - break; - case r'double': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(double)) as double; - result.double_ = valueDes; - break; - case r'decimal': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(double)) as double; - result.decimal = valueDes; - break; - case r'string': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.string = valueDes; - break; - case r'byte': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.byte = valueDes; - break; - case r'binary': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(Uint8List)) as Uint8List; - result.binary = valueDes; - break; - case r'date': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(Date)) as Date; - result.date = valueDes; - break; - case r'dateTime': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(DateTime)) as DateTime; - result.dateTime = valueDes; - break; - case r'uuid': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.uuid = valueDes; - break; - case r'password': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.password = valueDes; - break; - case r'pattern_with_digits': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.patternWithDigits = valueDes; - break; - case r'pattern_with_digits_and_delimiter': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.patternWithDigitsAndDelimiter = valueDes; - break; - } - } - return result.build(); + if (object.int32 != null) { + yield r'int32'; + yield serializers.serialize( + object.int32, + specifiedType: const FullType(int), + ); } + if (object.int64 != null) { + yield r'int64'; + yield serializers.serialize( + object.int64, + specifiedType: const FullType(int), + ); + } + yield r'number'; + yield serializers.serialize( + object.number, + specifiedType: const FullType(num), + ); + if (object.float != null) { + yield r'float'; + yield serializers.serialize( + object.float, + specifiedType: const FullType(double), + ); + } + if (object.double_ != null) { + yield r'double'; + yield serializers.serialize( + object.double_, + specifiedType: const FullType(double), + ); + } + if (object.decimal != null) { + yield r'decimal'; + yield serializers.serialize( + object.decimal, + specifiedType: const FullType(double), + ); + } + if (object.string != null) { + yield r'string'; + yield serializers.serialize( + object.string, + specifiedType: const FullType(String), + ); + } + yield r'byte'; + yield serializers.serialize( + object.byte, + specifiedType: const FullType(String), + ); + if (object.binary != null) { + yield r'binary'; + yield serializers.serialize( + object.binary, + specifiedType: const FullType(Uint8List), + ); + } + yield r'date'; + yield serializers.serialize( + object.date, + specifiedType: const FullType(Date), + ); + if (object.dateTime != null) { + yield r'dateTime'; + yield serializers.serialize( + object.dateTime, + specifiedType: const FullType(DateTime), + ); + } + if (object.uuid != null) { + yield r'uuid'; + yield serializers.serialize( + object.uuid, + specifiedType: const FullType(String), + ); + } + yield r'password'; + yield serializers.serialize( + object.password, + specifiedType: const FullType(String), + ); + if (object.patternWithDigits != null) { + yield r'pattern_with_digits'; + yield serializers.serialize( + object.patternWithDigits, + specifiedType: const FullType(String), + ); + } + if (object.patternWithDigitsAndDelimiter != null) { + yield r'pattern_with_digits_and_delimiter'; + yield serializers.serialize( + object.patternWithDigitsAndDelimiter, + specifiedType: const FullType(String), + ); + } + } + + @override + Object serialize( + Serializers serializers, + FormatTest object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required FormatTestBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'integer': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.integer = valueDes; + break; + case r'int32': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.int32 = valueDes; + break; + case r'int64': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.int64 = valueDes; + break; + case r'number': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(num), + ) as num; + result.number = valueDes; + break; + case r'float': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(double), + ) as double; + result.float = valueDes; + break; + case r'double': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(double), + ) as double; + result.double_ = valueDes; + break; + case r'decimal': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(double), + ) as double; + result.decimal = valueDes; + break; + case r'string': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.string = valueDes; + break; + case r'byte': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.byte = valueDes; + break; + case r'binary': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(Uint8List), + ) as Uint8List; + result.binary = valueDes; + break; + case r'date': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(Date), + ) as Date; + result.date = valueDes; + break; + case r'dateTime': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(DateTime), + ) as DateTime; + result.dateTime = valueDes; + break; + case r'uuid': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.uuid = valueDes; + break; + case r'password': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.password = valueDes; + break; + case r'pattern_with_digits': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.patternWithDigits = valueDes; + break; + case r'pattern_with_digits_and_delimiter': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.patternWithDigitsAndDelimiter = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + FormatTest deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = FormatTestBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart index 21b44ece26..9683985cf1 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,75 +13,114 @@ part 'has_only_read_only.g.dart'; /// Properties: /// * [bar] /// * [foo] +@BuiltValue() abstract class HasOnlyReadOnly implements Built { - @BuiltValueField(wireName: r'bar') - String? get bar; + @BuiltValueField(wireName: r'bar') + String? get bar; - @BuiltValueField(wireName: r'foo') - String? get foo; + @BuiltValueField(wireName: r'foo') + String? get foo; - HasOnlyReadOnly._(); + HasOnlyReadOnly._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(HasOnlyReadOnlyBuilder b) => b; + factory HasOnlyReadOnly([void updates(HasOnlyReadOnlyBuilder b)]) = _$HasOnlyReadOnly; - factory HasOnlyReadOnly([void updates(HasOnlyReadOnlyBuilder b)]) = _$HasOnlyReadOnly; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(HasOnlyReadOnlyBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$HasOnlyReadOnlySerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$HasOnlyReadOnlySerializer(); } -class _$HasOnlyReadOnlySerializer implements StructuredSerializer { - @override - final Iterable types = const [HasOnlyReadOnly, _$HasOnlyReadOnly]; +class _$HasOnlyReadOnlySerializer implements PrimitiveSerializer { + @override + final Iterable types = const [HasOnlyReadOnly, _$HasOnlyReadOnly]; - @override - final String wireName = r'HasOnlyReadOnly'; + @override + final String wireName = r'HasOnlyReadOnly'; - @override - Iterable serialize(Serializers serializers, HasOnlyReadOnly object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.bar != null) { - result - ..add(r'bar') - ..add(serializers.serialize(object.bar, - specifiedType: const FullType(String))); - } - if (object.foo != null) { - result - ..add(r'foo') - ..add(serializers.serialize(object.foo, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + HasOnlyReadOnly object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.bar != null) { + yield r'bar'; + yield serializers.serialize( + object.bar, + specifiedType: const FullType(String), + ); } - - @override - HasOnlyReadOnly deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = HasOnlyReadOnlyBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'bar': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.bar = valueDes; - break; - case r'foo': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.foo = valueDes; - break; - } - } - return result.build(); + if (object.foo != null) { + yield r'foo'; + yield serializers.serialize( + object.foo, + specifiedType: const FullType(String), + ); } + } + + @override + Object serialize( + Serializers serializers, + HasOnlyReadOnly object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required HasOnlyReadOnlyBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'bar': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.bar = valueDes; + break; + case r'foo': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.foo = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + HasOnlyReadOnly deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = HasOnlyReadOnlyBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/health_check_result.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/health_check_result.dart index e589cb7bd3..c092a535f2 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/health_check_result.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/health_check_result.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,62 +12,98 @@ part 'health_check_result.g.dart'; /// /// Properties: /// * [nullableMessage] +@BuiltValue() abstract class HealthCheckResult implements Built { - @BuiltValueField(wireName: r'NullableMessage') - String? get nullableMessage; + @BuiltValueField(wireName: r'NullableMessage') + String? get nullableMessage; - HealthCheckResult._(); + HealthCheckResult._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(HealthCheckResultBuilder b) => b; + factory HealthCheckResult([void updates(HealthCheckResultBuilder b)]) = _$HealthCheckResult; - factory HealthCheckResult([void updates(HealthCheckResultBuilder b)]) = _$HealthCheckResult; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(HealthCheckResultBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$HealthCheckResultSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$HealthCheckResultSerializer(); } -class _$HealthCheckResultSerializer implements StructuredSerializer { - @override - final Iterable types = const [HealthCheckResult, _$HealthCheckResult]; +class _$HealthCheckResultSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [HealthCheckResult, _$HealthCheckResult]; - @override - final String wireName = r'HealthCheckResult'; + @override + final String wireName = r'HealthCheckResult'; - @override - Iterable serialize(Serializers serializers, HealthCheckResult object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.nullableMessage != null) { - result - ..add(r'NullableMessage') - ..add(serializers.serialize(object.nullableMessage, - specifiedType: const FullType.nullable(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + HealthCheckResult object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.nullableMessage != null) { + yield r'NullableMessage'; + yield serializers.serialize( + object.nullableMessage, + specifiedType: const FullType.nullable(String), + ); } + } - @override - HealthCheckResult deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = HealthCheckResultBuilder(); + @override + Object serialize( + Serializers serializers, + HealthCheckResult object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'NullableMessage': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(String)) as String?; - if (valueDes == null) continue; - result.nullableMessage = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required HealthCheckResultBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'NullableMessage': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(String), + ) as String?; + if (valueDes == null) continue; + result.nullableMessage = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + HealthCheckResult deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = HealthCheckResultBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/inline_response_default.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/inline_response_default.dart index b611f8beb6..74d5ed70f1 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/inline_response_default.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/inline_response_default.dart @@ -5,6 +5,9 @@ import 'package:openapi/src/model/foo.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; +import 'package:one_of/one_of.dart'; +import 'package:one_of/any_of.dart'; +// ignore_for_file: unused_element, unused_import part 'inline_response_default.g.dart'; @@ -12,61 +15,77 @@ part 'inline_response_default.g.dart'; /// /// Properties: /// * [string] +@BuiltValue() abstract class InlineResponseDefault implements Built { @BuiltValueField(wireName: r'string') Foo? get string; + InlineResponseDefault._(); + + factory InlineResponseDefault([void updates(InlineResponseDefaultBuilder b)]) = _$InlineResponseDefault; @BuiltValueHook(initializeBuilder: true) static void _defaults(InlineResponseDefaultBuilder b) => b; - factory InlineResponseDefault([void updates(InlineResponseDefaultBuilder b)]) = _$InlineResponseDefault; - @BuiltValueSerializer(custom: true) static Serializer get serializer => _$InlineResponseDefaultSerializer(); + + } -class _$InlineResponseDefaultSerializer implements StructuredSerializer { +class _$InlineResponseDefaultSerializer implements PrimitiveSerializer { @override final Iterable types = const [InlineResponseDefault, _$InlineResponseDefault]; @override final String wireName = r'InlineResponseDefault'; - @override - Iterable serialize(Serializers serializers, InlineResponseDefault object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; + Iterable _serializeProperties(Serializers serializers, InlineResponseDefault object, + {FullType specifiedType = FullType.unspecified}) sync* { if (object.string != null) { - result - ..add(r'string') - ..add(serializers.serialize(object.string, - specifiedType: const FullType(Foo))); + yield r'string'; + yield serializers.serialize(object.string, + specifiedType: const FullType(Foo)); } - return result; } @override - InlineResponseDefault deserialize(Serializers serializers, Iterable serialized, + Object serialize(Serializers serializers, InlineResponseDefault object, {FullType specifiedType = FullType.unspecified}) { - final result = InlineResponseDefaultBuilder(); + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - + void _deserializeProperties(Serializers serializers, Object serialized, + {FullType specifiedType = FullType.unspecified, required List serializedList,required InlineResponseDefaultBuilder result, required List unhandled}) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; switch (key) { - case r'string': + case r'string': final valueDes = serializers.deserialize(value, specifiedType: const FullType(Foo)) as Foo; result.string.replace(valueDes); break; + default: + unhandled.add(key); + unhandled.add(value); + break; } } + } + + @override + InlineResponseDefault deserialize(Serializers serializers, Object serialized, + {FullType specifiedType = FullType.unspecified}) { + final result = InlineResponseDefaultBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties(serializers, serialized, specifiedType: specifiedType, serializedList: serializedList, unhandled: unhandled, result: result); return result.build(); } } + + + diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/map_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/map_test.dart index 16df0490e1..9fa58677a8 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/map_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/map_test.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -15,105 +16,150 @@ part 'map_test.g.dart'; /// * [mapOfEnumString] /// * [directMap] /// * [indirectMap] +@BuiltValue() abstract class MapTest implements Built { - @BuiltValueField(wireName: r'map_map_of_string') - BuiltMap>? get mapMapOfString; + @BuiltValueField(wireName: r'map_map_of_string') + BuiltMap>? get mapMapOfString; - @BuiltValueField(wireName: r'map_of_enum_string') - BuiltMap? get mapOfEnumString; - // enum mapOfEnumStringEnum { UPPER, lower, }; + @BuiltValueField(wireName: r'map_of_enum_string') + BuiltMap? get mapOfEnumString; + // enum mapOfEnumStringEnum { UPPER, lower, }; - @BuiltValueField(wireName: r'direct_map') - BuiltMap? get directMap; + @BuiltValueField(wireName: r'direct_map') + BuiltMap? get directMap; - @BuiltValueField(wireName: r'indirect_map') - BuiltMap? get indirectMap; + @BuiltValueField(wireName: r'indirect_map') + BuiltMap? get indirectMap; - MapTest._(); + MapTest._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(MapTestBuilder b) => b; + factory MapTest([void updates(MapTestBuilder b)]) = _$MapTest; - factory MapTest([void updates(MapTestBuilder b)]) = _$MapTest; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(MapTestBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$MapTestSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$MapTestSerializer(); } -class _$MapTestSerializer implements StructuredSerializer { - @override - final Iterable types = const [MapTest, _$MapTest]; +class _$MapTestSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [MapTest, _$MapTest]; - @override - final String wireName = r'MapTest'; + @override + final String wireName = r'MapTest'; - @override - Iterable serialize(Serializers serializers, MapTest object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.mapMapOfString != null) { - result - ..add(r'map_map_of_string') - ..add(serializers.serialize(object.mapMapOfString, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(BuiltMap, [FullType(String), FullType(String)])]))); - } - if (object.mapOfEnumString != null) { - result - ..add(r'map_of_enum_string') - ..add(serializers.serialize(object.mapOfEnumString, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(MapTestMapOfEnumStringEnum)]))); - } - if (object.directMap != null) { - result - ..add(r'direct_map') - ..add(serializers.serialize(object.directMap, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(bool)]))); - } - if (object.indirectMap != null) { - result - ..add(r'indirect_map') - ..add(serializers.serialize(object.indirectMap, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(bool)]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + MapTest object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.mapMapOfString != null) { + yield r'map_map_of_string'; + yield serializers.serialize( + object.mapMapOfString, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(BuiltMap, [FullType(String), FullType(String)])]), + ); } - - @override - MapTest deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = MapTestBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'map_map_of_string': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(BuiltMap, [FullType(String), FullType(String)])])) as BuiltMap>; - result.mapMapOfString.replace(valueDes); - break; - case r'map_of_enum_string': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(MapTestMapOfEnumStringEnum)])) as BuiltMap; - result.mapOfEnumString.replace(valueDes); - break; - case r'direct_map': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(bool)])) as BuiltMap; - result.directMap.replace(valueDes); - break; - case r'indirect_map': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(bool)])) as BuiltMap; - result.indirectMap.replace(valueDes); - break; - } - } - return result.build(); + if (object.mapOfEnumString != null) { + yield r'map_of_enum_string'; + yield serializers.serialize( + object.mapOfEnumString, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(MapTestMapOfEnumStringEnum)]), + ); } + if (object.directMap != null) { + yield r'direct_map'; + yield serializers.serialize( + object.directMap, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(bool)]), + ); + } + if (object.indirectMap != null) { + yield r'indirect_map'; + yield serializers.serialize( + object.indirectMap, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(bool)]), + ); + } + } + + @override + Object serialize( + Serializers serializers, + MapTest object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required MapTestBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'map_map_of_string': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(BuiltMap, [FullType(String), FullType(String)])]), + ) as BuiltMap>; + result.mapMapOfString.replace(valueDes); + break; + case r'map_of_enum_string': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(MapTestMapOfEnumStringEnum)]), + ) as BuiltMap; + result.mapOfEnumString.replace(valueDes); + break; + case r'direct_map': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(bool)]), + ) as BuiltMap; + result.directMap.replace(valueDes); + break; + case r'indirect_map': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(bool)]), + ) as BuiltMap; + result.indirectMap.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + MapTest deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = MapTestBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } class MapTestMapOfEnumStringEnum extends EnumClass { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart index 27c6993cc7..76b5933ae5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:openapi/src/model/animal.dart'; import 'package:built_value/built_value.dart'; @@ -15,89 +16,131 @@ part 'mixed_properties_and_additional_properties_class.g.dart'; /// * [uuid] /// * [dateTime] /// * [map] +@BuiltValue() abstract class MixedPropertiesAndAdditionalPropertiesClass implements Built { - @BuiltValueField(wireName: r'uuid') - String? get uuid; + @BuiltValueField(wireName: r'uuid') + String? get uuid; - @BuiltValueField(wireName: r'dateTime') - DateTime? get dateTime; + @BuiltValueField(wireName: r'dateTime') + DateTime? get dateTime; - @BuiltValueField(wireName: r'map') - BuiltMap? get map; + @BuiltValueField(wireName: r'map') + BuiltMap? get map; - MixedPropertiesAndAdditionalPropertiesClass._(); + MixedPropertiesAndAdditionalPropertiesClass._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(MixedPropertiesAndAdditionalPropertiesClassBuilder b) => b; + factory MixedPropertiesAndAdditionalPropertiesClass([void updates(MixedPropertiesAndAdditionalPropertiesClassBuilder b)]) = _$MixedPropertiesAndAdditionalPropertiesClass; - factory MixedPropertiesAndAdditionalPropertiesClass([void updates(MixedPropertiesAndAdditionalPropertiesClassBuilder b)]) = _$MixedPropertiesAndAdditionalPropertiesClass; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(MixedPropertiesAndAdditionalPropertiesClassBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$MixedPropertiesAndAdditionalPropertiesClassSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$MixedPropertiesAndAdditionalPropertiesClassSerializer(); } -class _$MixedPropertiesAndAdditionalPropertiesClassSerializer implements StructuredSerializer { - @override - final Iterable types = const [MixedPropertiesAndAdditionalPropertiesClass, _$MixedPropertiesAndAdditionalPropertiesClass]; +class _$MixedPropertiesAndAdditionalPropertiesClassSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [MixedPropertiesAndAdditionalPropertiesClass, _$MixedPropertiesAndAdditionalPropertiesClass]; - @override - final String wireName = r'MixedPropertiesAndAdditionalPropertiesClass'; + @override + final String wireName = r'MixedPropertiesAndAdditionalPropertiesClass'; - @override - Iterable serialize(Serializers serializers, MixedPropertiesAndAdditionalPropertiesClass object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.uuid != null) { - result - ..add(r'uuid') - ..add(serializers.serialize(object.uuid, - specifiedType: const FullType(String))); - } - if (object.dateTime != null) { - result - ..add(r'dateTime') - ..add(serializers.serialize(object.dateTime, - specifiedType: const FullType(DateTime))); - } - if (object.map != null) { - result - ..add(r'map') - ..add(serializers.serialize(object.map, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(Animal)]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + MixedPropertiesAndAdditionalPropertiesClass object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.uuid != null) { + yield r'uuid'; + yield serializers.serialize( + object.uuid, + specifiedType: const FullType(String), + ); } - - @override - MixedPropertiesAndAdditionalPropertiesClass deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = MixedPropertiesAndAdditionalPropertiesClassBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'uuid': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.uuid = valueDes; - break; - case r'dateTime': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(DateTime)) as DateTime; - result.dateTime = valueDes; - break; - case r'map': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType(Animal)])) as BuiltMap; - result.map.replace(valueDes); - break; - } - } - return result.build(); + if (object.dateTime != null) { + yield r'dateTime'; + yield serializers.serialize( + object.dateTime, + specifiedType: const FullType(DateTime), + ); } + if (object.map != null) { + yield r'map'; + yield serializers.serialize( + object.map, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(Animal)]), + ); + } + } + + @override + Object serialize( + Serializers serializers, + MixedPropertiesAndAdditionalPropertiesClass object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required MixedPropertiesAndAdditionalPropertiesClassBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'uuid': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.uuid = valueDes; + break; + case r'dateTime': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(DateTime), + ) as DateTime; + result.dateTime = valueDes; + break; + case r'map': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType(Animal)]), + ) as BuiltMap; + result.map.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + MixedPropertiesAndAdditionalPropertiesClass deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = MixedPropertiesAndAdditionalPropertiesClassBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model200_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model200_response.dart index 1e7b31e2af..0a2cfb4411 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model200_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model200_response.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,75 +13,114 @@ part 'model200_response.g.dart'; /// Properties: /// * [name] /// * [classField] +@BuiltValue() abstract class Model200Response implements Built { - @BuiltValueField(wireName: r'name') - int? get name; + @BuiltValueField(wireName: r'name') + int? get name; - @BuiltValueField(wireName: r'class') - String? get classField; + @BuiltValueField(wireName: r'class') + String? get classField; - Model200Response._(); + Model200Response._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(Model200ResponseBuilder b) => b; + factory Model200Response([void updates(Model200ResponseBuilder b)]) = _$Model200Response; - factory Model200Response([void updates(Model200ResponseBuilder b)]) = _$Model200Response; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(Model200ResponseBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$Model200ResponseSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$Model200ResponseSerializer(); } -class _$Model200ResponseSerializer implements StructuredSerializer { - @override - final Iterable types = const [Model200Response, _$Model200Response]; +class _$Model200ResponseSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Model200Response, _$Model200Response]; - @override - final String wireName = r'Model200Response'; + @override + final String wireName = r'Model200Response'; - @override - Iterable serialize(Serializers serializers, Model200Response object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.name != null) { - result - ..add(r'name') - ..add(serializers.serialize(object.name, - specifiedType: const FullType(int))); - } - if (object.classField != null) { - result - ..add(r'class') - ..add(serializers.serialize(object.classField, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Model200Response object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.name != null) { + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(int), + ); } - - @override - Model200Response deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = Model200ResponseBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'name': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.name = valueDes; - break; - case r'class': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.classField = valueDes; - break; - } - } - return result.build(); + if (object.classField != null) { + yield r'class'; + yield serializers.serialize( + object.classField, + specifiedType: const FullType(String), + ); } + } + + @override + Object serialize( + Serializers serializers, + Model200Response object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required Model200ResponseBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.name = valueDes; + break; + case r'class': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.classField = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Model200Response deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = Model200ResponseBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_client.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_client.dart index 23c30a77f2..3669097742 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_client.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_client.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,61 +12,97 @@ part 'model_client.g.dart'; /// /// Properties: /// * [client] +@BuiltValue() abstract class ModelClient implements Built { - @BuiltValueField(wireName: r'client') - String? get client; + @BuiltValueField(wireName: r'client') + String? get client; - ModelClient._(); + ModelClient._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ModelClientBuilder b) => b; + factory ModelClient([void updates(ModelClientBuilder b)]) = _$ModelClient; - factory ModelClient([void updates(ModelClientBuilder b)]) = _$ModelClient; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ModelClientBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ModelClientSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ModelClientSerializer(); } -class _$ModelClientSerializer implements StructuredSerializer { - @override - final Iterable types = const [ModelClient, _$ModelClient]; +class _$ModelClientSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ModelClient, _$ModelClient]; - @override - final String wireName = r'ModelClient'; + @override + final String wireName = r'ModelClient'; - @override - Iterable serialize(Serializers serializers, ModelClient object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.client != null) { - result - ..add(r'client') - ..add(serializers.serialize(object.client, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ModelClient object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.client != null) { + yield r'client'; + yield serializers.serialize( + object.client, + specifiedType: const FullType(String), + ); } + } - @override - ModelClient deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ModelClientBuilder(); + @override + Object serialize( + Serializers serializers, + ModelClient object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'client': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.client = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ModelClientBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'client': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.client = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + ModelClient deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ModelClientBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_enum_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_enum_class.dart index f49be90d2b..ac609bfd15 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_enum_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_enum_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_file.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_file.dart index aa7b5ecfed..2702c21d36 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_file.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_file.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,62 +12,98 @@ part 'model_file.g.dart'; /// /// Properties: /// * [sourceURI] - Test capitalization +@BuiltValue() abstract class ModelFile implements Built { - /// Test capitalization - @BuiltValueField(wireName: r'sourceURI') - String? get sourceURI; + /// Test capitalization + @BuiltValueField(wireName: r'sourceURI') + String? get sourceURI; - ModelFile._(); + ModelFile._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ModelFileBuilder b) => b; + factory ModelFile([void updates(ModelFileBuilder b)]) = _$ModelFile; - factory ModelFile([void updates(ModelFileBuilder b)]) = _$ModelFile; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ModelFileBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ModelFileSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ModelFileSerializer(); } -class _$ModelFileSerializer implements StructuredSerializer { - @override - final Iterable types = const [ModelFile, _$ModelFile]; +class _$ModelFileSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ModelFile, _$ModelFile]; - @override - final String wireName = r'ModelFile'; + @override + final String wireName = r'ModelFile'; - @override - Iterable serialize(Serializers serializers, ModelFile object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.sourceURI != null) { - result - ..add(r'sourceURI') - ..add(serializers.serialize(object.sourceURI, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ModelFile object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.sourceURI != null) { + yield r'sourceURI'; + yield serializers.serialize( + object.sourceURI, + specifiedType: const FullType(String), + ); } + } - @override - ModelFile deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ModelFileBuilder(); + @override + Object serialize( + Serializers serializers, + ModelFile object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'sourceURI': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.sourceURI = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ModelFileBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'sourceURI': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.sourceURI = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + ModelFile deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ModelFileBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_list.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_list.dart index 87e10153b1..579853258f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_list.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_list.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,61 +12,97 @@ part 'model_list.g.dart'; /// /// Properties: /// * [n123list] +@BuiltValue() abstract class ModelList implements Built { - @BuiltValueField(wireName: r'123-list') - String? get n123list; + @BuiltValueField(wireName: r'123-list') + String? get n123list; - ModelList._(); + ModelList._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ModelListBuilder b) => b; + factory ModelList([void updates(ModelListBuilder b)]) = _$ModelList; - factory ModelList([void updates(ModelListBuilder b)]) = _$ModelList; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ModelListBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ModelListSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ModelListSerializer(); } -class _$ModelListSerializer implements StructuredSerializer { - @override - final Iterable types = const [ModelList, _$ModelList]; +class _$ModelListSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ModelList, _$ModelList]; - @override - final String wireName = r'ModelList'; + @override + final String wireName = r'ModelList'; - @override - Iterable serialize(Serializers serializers, ModelList object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.n123list != null) { - result - ..add(r'123-list') - ..add(serializers.serialize(object.n123list, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ModelList object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.n123list != null) { + yield r'123-list'; + yield serializers.serialize( + object.n123list, + specifiedType: const FullType(String), + ); } + } - @override - ModelList deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ModelListBuilder(); + @override + Object serialize( + Serializers serializers, + ModelList object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'123-list': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.n123list = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ModelListBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'123-list': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.n123list = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + ModelList deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ModelListBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_return.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_return.dart index c63e0464fa..45a2f67f8a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_return.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/model_return.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,61 +12,97 @@ part 'model_return.g.dart'; /// /// Properties: /// * [return_] +@BuiltValue() abstract class ModelReturn implements Built { - @BuiltValueField(wireName: r'return') - int? get return_; + @BuiltValueField(wireName: r'return') + int? get return_; - ModelReturn._(); + ModelReturn._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ModelReturnBuilder b) => b; + factory ModelReturn([void updates(ModelReturnBuilder b)]) = _$ModelReturn; - factory ModelReturn([void updates(ModelReturnBuilder b)]) = _$ModelReturn; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ModelReturnBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ModelReturnSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ModelReturnSerializer(); } -class _$ModelReturnSerializer implements StructuredSerializer { - @override - final Iterable types = const [ModelReturn, _$ModelReturn]; +class _$ModelReturnSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ModelReturn, _$ModelReturn]; - @override - final String wireName = r'ModelReturn'; + @override + final String wireName = r'ModelReturn'; - @override - Iterable serialize(Serializers serializers, ModelReturn object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.return_ != null) { - result - ..add(r'return') - ..add(serializers.serialize(object.return_, - specifiedType: const FullType(int))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ModelReturn object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.return_ != null) { + yield r'return'; + yield serializers.serialize( + object.return_, + specifiedType: const FullType(int), + ); } + } - @override - ModelReturn deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ModelReturnBuilder(); + @override + Object serialize( + Serializers serializers, + ModelReturn object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'return': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.return_ = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ModelReturnBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'return': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.return_ = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + ModelReturn deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ModelReturnBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/name.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/name.dart index 78f9f8e545..10fa99e6a5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/name.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/name.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -14,101 +15,146 @@ part 'name.g.dart'; /// * [snakeCase] /// * [property] /// * [n123number] +@BuiltValue() abstract class Name implements Built { - @BuiltValueField(wireName: r'name') - int get name; + @BuiltValueField(wireName: r'name') + int get name; - @BuiltValueField(wireName: r'snake_case') - int? get snakeCase; + @BuiltValueField(wireName: r'snake_case') + int? get snakeCase; - @BuiltValueField(wireName: r'property') - String? get property; + @BuiltValueField(wireName: r'property') + String? get property; - @BuiltValueField(wireName: r'123Number') - int? get n123number; + @BuiltValueField(wireName: r'123Number') + int? get n123number; - Name._(); + Name._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(NameBuilder b) => b; + factory Name([void updates(NameBuilder b)]) = _$Name; - factory Name([void updates(NameBuilder b)]) = _$Name; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(NameBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$NameSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$NameSerializer(); } -class _$NameSerializer implements StructuredSerializer { - @override - final Iterable types = const [Name, _$Name]; +class _$NameSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Name, _$Name]; - @override - final String wireName = r'Name'; + @override + final String wireName = r'Name'; - @override - Iterable serialize(Serializers serializers, Name object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - result - ..add(r'name') - ..add(serializers.serialize(object.name, - specifiedType: const FullType(int))); - if (object.snakeCase != null) { - result - ..add(r'snake_case') - ..add(serializers.serialize(object.snakeCase, - specifiedType: const FullType(int))); - } - if (object.property != null) { - result - ..add(r'property') - ..add(serializers.serialize(object.property, - specifiedType: const FullType(String))); - } - if (object.n123number != null) { - result - ..add(r'123Number') - ..add(serializers.serialize(object.n123number, - specifiedType: const FullType(int))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Name object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(int), + ); + if (object.snakeCase != null) { + yield r'snake_case'; + yield serializers.serialize( + object.snakeCase, + specifiedType: const FullType(int), + ); } - - @override - Name deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = NameBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'name': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.name = valueDes; - break; - case r'snake_case': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.snakeCase = valueDes; - break; - case r'property': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.property = valueDes; - break; - case r'123Number': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.n123number = valueDes; - break; - } - } - return result.build(); + if (object.property != null) { + yield r'property'; + yield serializers.serialize( + object.property, + specifiedType: const FullType(String), + ); } + if (object.n123number != null) { + yield r'123Number'; + yield serializers.serialize( + object.n123number, + specifiedType: const FullType(int), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Name object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required NameBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.name = valueDes; + break; + case r'snake_case': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.snakeCase = valueDes; + break; + case r'property': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.property = valueDes; + break; + case r'123Number': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.n123number = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Name deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = NameBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/nullable_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/nullable_class.dart index efddc42e30..c993a41303 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/nullable_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/nullable_class.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:openapi/src/model/date.dart'; import 'package:built_value/json_object.dart'; @@ -25,225 +26,294 @@ part 'nullable_class.g.dart'; /// * [objectNullableProp] /// * [objectAndItemsNullableProp] /// * [objectItemsNullable] +@BuiltValue() abstract class NullableClass implements Built { - @BuiltValueField(wireName: r'integer_prop') - int? get integerProp; + @BuiltValueField(wireName: r'integer_prop') + int? get integerProp; - @BuiltValueField(wireName: r'number_prop') - num? get numberProp; + @BuiltValueField(wireName: r'number_prop') + num? get numberProp; - @BuiltValueField(wireName: r'boolean_prop') - bool? get booleanProp; + @BuiltValueField(wireName: r'boolean_prop') + bool? get booleanProp; - @BuiltValueField(wireName: r'string_prop') - String? get stringProp; + @BuiltValueField(wireName: r'string_prop') + String? get stringProp; - @BuiltValueField(wireName: r'date_prop') - Date? get dateProp; + @BuiltValueField(wireName: r'date_prop') + Date? get dateProp; - @BuiltValueField(wireName: r'datetime_prop') - DateTime? get datetimeProp; + @BuiltValueField(wireName: r'datetime_prop') + DateTime? get datetimeProp; - @BuiltValueField(wireName: r'array_nullable_prop') - BuiltList? get arrayNullableProp; + @BuiltValueField(wireName: r'array_nullable_prop') + BuiltList? get arrayNullableProp; - @BuiltValueField(wireName: r'array_and_items_nullable_prop') - BuiltList? get arrayAndItemsNullableProp; + @BuiltValueField(wireName: r'array_and_items_nullable_prop') + BuiltList? get arrayAndItemsNullableProp; - @BuiltValueField(wireName: r'array_items_nullable') - BuiltList? get arrayItemsNullable; + @BuiltValueField(wireName: r'array_items_nullable') + BuiltList? get arrayItemsNullable; - @BuiltValueField(wireName: r'object_nullable_prop') - BuiltMap? get objectNullableProp; + @BuiltValueField(wireName: r'object_nullable_prop') + BuiltMap? get objectNullableProp; - @BuiltValueField(wireName: r'object_and_items_nullable_prop') - BuiltMap? get objectAndItemsNullableProp; + @BuiltValueField(wireName: r'object_and_items_nullable_prop') + BuiltMap? get objectAndItemsNullableProp; - @BuiltValueField(wireName: r'object_items_nullable') - BuiltMap? get objectItemsNullable; + @BuiltValueField(wireName: r'object_items_nullable') + BuiltMap? get objectItemsNullable; - NullableClass._(); + NullableClass._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(NullableClassBuilder b) => b; + factory NullableClass([void updates(NullableClassBuilder b)]) = _$NullableClass; - factory NullableClass([void updates(NullableClassBuilder b)]) = _$NullableClass; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(NullableClassBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$NullableClassSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$NullableClassSerializer(); } -class _$NullableClassSerializer implements StructuredSerializer { - @override - final Iterable types = const [NullableClass, _$NullableClass]; +class _$NullableClassSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [NullableClass, _$NullableClass]; - @override - final String wireName = r'NullableClass'; + @override + final String wireName = r'NullableClass'; - @override - Iterable serialize(Serializers serializers, NullableClass object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.integerProp != null) { - result - ..add(r'integer_prop') - ..add(serializers.serialize(object.integerProp, - specifiedType: const FullType.nullable(int))); - } - if (object.numberProp != null) { - result - ..add(r'number_prop') - ..add(serializers.serialize(object.numberProp, - specifiedType: const FullType.nullable(num))); - } - if (object.booleanProp != null) { - result - ..add(r'boolean_prop') - ..add(serializers.serialize(object.booleanProp, - specifiedType: const FullType.nullable(bool))); - } - if (object.stringProp != null) { - result - ..add(r'string_prop') - ..add(serializers.serialize(object.stringProp, - specifiedType: const FullType.nullable(String))); - } - if (object.dateProp != null) { - result - ..add(r'date_prop') - ..add(serializers.serialize(object.dateProp, - specifiedType: const FullType.nullable(Date))); - } - if (object.datetimeProp != null) { - result - ..add(r'datetime_prop') - ..add(serializers.serialize(object.datetimeProp, - specifiedType: const FullType.nullable(DateTime))); - } - if (object.arrayNullableProp != null) { - result - ..add(r'array_nullable_prop') - ..add(serializers.serialize(object.arrayNullableProp, - specifiedType: const FullType.nullable(BuiltList, [FullType(JsonObject)]))); - } - if (object.arrayAndItemsNullableProp != null) { - result - ..add(r'array_and_items_nullable_prop') - ..add(serializers.serialize(object.arrayAndItemsNullableProp, - specifiedType: const FullType.nullable(BuiltList, [FullType.nullable(JsonObject)]))); - } - if (object.arrayItemsNullable != null) { - result - ..add(r'array_items_nullable') - ..add(serializers.serialize(object.arrayItemsNullable, - specifiedType: const FullType(BuiltList, [FullType.nullable(JsonObject)]))); - } - if (object.objectNullableProp != null) { - result - ..add(r'object_nullable_prop') - ..add(serializers.serialize(object.objectNullableProp, - specifiedType: const FullType.nullable(BuiltMap, [FullType(String), FullType(JsonObject)]))); - } - if (object.objectAndItemsNullableProp != null) { - result - ..add(r'object_and_items_nullable_prop') - ..add(serializers.serialize(object.objectAndItemsNullableProp, - specifiedType: const FullType.nullable(BuiltMap, [FullType(String), FullType.nullable(JsonObject)]))); - } - if (object.objectItemsNullable != null) { - result - ..add(r'object_items_nullable') - ..add(serializers.serialize(object.objectItemsNullable, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType.nullable(JsonObject)]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + NullableClass object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.integerProp != null) { + yield r'integer_prop'; + yield serializers.serialize( + object.integerProp, + specifiedType: const FullType.nullable(int), + ); } - - @override - NullableClass deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = NullableClassBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'integer_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(int)) as int?; - if (valueDes == null) continue; - result.integerProp = valueDes; - break; - case r'number_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(num)) as num?; - if (valueDes == null) continue; - result.numberProp = valueDes; - break; - case r'boolean_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(bool)) as bool?; - if (valueDes == null) continue; - result.booleanProp = valueDes; - break; - case r'string_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(String)) as String?; - if (valueDes == null) continue; - result.stringProp = valueDes; - break; - case r'date_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(Date)) as Date?; - if (valueDes == null) continue; - result.dateProp = valueDes; - break; - case r'datetime_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(DateTime)) as DateTime?; - if (valueDes == null) continue; - result.datetimeProp = valueDes; - break; - case r'array_nullable_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(BuiltList, [FullType(JsonObject)])) as BuiltList?; - if (valueDes == null) continue; - result.arrayNullableProp.replace(valueDes); - break; - case r'array_and_items_nullable_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(BuiltList, [FullType.nullable(JsonObject)])) as BuiltList?; - if (valueDes == null) continue; - result.arrayAndItemsNullableProp.replace(valueDes); - break; - case r'array_items_nullable': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType.nullable(JsonObject)])) as BuiltList; - result.arrayItemsNullable.replace(valueDes); - break; - case r'object_nullable_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(BuiltMap, [FullType(String), FullType(JsonObject)])) as BuiltMap?; - if (valueDes == null) continue; - result.objectNullableProp.replace(valueDes); - break; - case r'object_and_items_nullable_prop': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType.nullable(BuiltMap, [FullType(String), FullType.nullable(JsonObject)])) as BuiltMap?; - if (valueDes == null) continue; - result.objectAndItemsNullableProp.replace(valueDes); - break; - case r'object_items_nullable': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, [FullType(String), FullType.nullable(JsonObject)])) as BuiltMap; - result.objectItemsNullable.replace(valueDes); - break; - } - } - return result.build(); + if (object.numberProp != null) { + yield r'number_prop'; + yield serializers.serialize( + object.numberProp, + specifiedType: const FullType.nullable(num), + ); } + if (object.booleanProp != null) { + yield r'boolean_prop'; + yield serializers.serialize( + object.booleanProp, + specifiedType: const FullType.nullable(bool), + ); + } + if (object.stringProp != null) { + yield r'string_prop'; + yield serializers.serialize( + object.stringProp, + specifiedType: const FullType.nullable(String), + ); + } + if (object.dateProp != null) { + yield r'date_prop'; + yield serializers.serialize( + object.dateProp, + specifiedType: const FullType.nullable(Date), + ); + } + if (object.datetimeProp != null) { + yield r'datetime_prop'; + yield serializers.serialize( + object.datetimeProp, + specifiedType: const FullType.nullable(DateTime), + ); + } + if (object.arrayNullableProp != null) { + yield r'array_nullable_prop'; + yield serializers.serialize( + object.arrayNullableProp, + specifiedType: const FullType.nullable(BuiltList, [FullType(JsonObject)]), + ); + } + if (object.arrayAndItemsNullableProp != null) { + yield r'array_and_items_nullable_prop'; + yield serializers.serialize( + object.arrayAndItemsNullableProp, + specifiedType: const FullType.nullable(BuiltList, [FullType.nullable(JsonObject)]), + ); + } + if (object.arrayItemsNullable != null) { + yield r'array_items_nullable'; + yield serializers.serialize( + object.arrayItemsNullable, + specifiedType: const FullType(BuiltList, [FullType.nullable(JsonObject)]), + ); + } + if (object.objectNullableProp != null) { + yield r'object_nullable_prop'; + yield serializers.serialize( + object.objectNullableProp, + specifiedType: const FullType.nullable(BuiltMap, [FullType(String), FullType(JsonObject)]), + ); + } + if (object.objectAndItemsNullableProp != null) { + yield r'object_and_items_nullable_prop'; + yield serializers.serialize( + object.objectAndItemsNullableProp, + specifiedType: const FullType.nullable(BuiltMap, [FullType(String), FullType.nullable(JsonObject)]), + ); + } + if (object.objectItemsNullable != null) { + yield r'object_items_nullable'; + yield serializers.serialize( + object.objectItemsNullable, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType.nullable(JsonObject)]), + ); + } + } + + @override + Object serialize( + Serializers serializers, + NullableClass object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required NullableClassBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'integer_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(int), + ) as int?; + if (valueDes == null) continue; + result.integerProp = valueDes; + break; + case r'number_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(num), + ) as num?; + if (valueDes == null) continue; + result.numberProp = valueDes; + break; + case r'boolean_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(bool), + ) as bool?; + if (valueDes == null) continue; + result.booleanProp = valueDes; + break; + case r'string_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(String), + ) as String?; + if (valueDes == null) continue; + result.stringProp = valueDes; + break; + case r'date_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(Date), + ) as Date?; + if (valueDes == null) continue; + result.dateProp = valueDes; + break; + case r'datetime_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(DateTime), + ) as DateTime?; + if (valueDes == null) continue; + result.datetimeProp = valueDes; + break; + case r'array_nullable_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(BuiltList, [FullType(JsonObject)]), + ) as BuiltList?; + if (valueDes == null) continue; + result.arrayNullableProp.replace(valueDes); + break; + case r'array_and_items_nullable_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(BuiltList, [FullType.nullable(JsonObject)]), + ) as BuiltList?; + if (valueDes == null) continue; + result.arrayAndItemsNullableProp.replace(valueDes); + break; + case r'array_items_nullable': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType.nullable(JsonObject)]), + ) as BuiltList; + result.arrayItemsNullable.replace(valueDes); + break; + case r'object_nullable_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(BuiltMap, [FullType(String), FullType(JsonObject)]), + ) as BuiltMap?; + if (valueDes == null) continue; + result.objectNullableProp.replace(valueDes); + break; + case r'object_and_items_nullable_prop': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType.nullable(BuiltMap, [FullType(String), FullType.nullable(JsonObject)]), + ) as BuiltMap?; + if (valueDes == null) continue; + result.objectAndItemsNullableProp.replace(valueDes); + break; + case r'object_items_nullable': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltMap, [FullType(String), FullType.nullable(JsonObject)]), + ) as BuiltMap; + result.objectItemsNullable.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + NullableClass deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = NullableClassBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/number_only.dart index e90cc9b934..482a95f3e5 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/number_only.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,61 +12,97 @@ part 'number_only.g.dart'; /// /// Properties: /// * [justNumber] +@BuiltValue() abstract class NumberOnly implements Built { - @BuiltValueField(wireName: r'JustNumber') - num? get justNumber; + @BuiltValueField(wireName: r'JustNumber') + num? get justNumber; - NumberOnly._(); + NumberOnly._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(NumberOnlyBuilder b) => b; + factory NumberOnly([void updates(NumberOnlyBuilder b)]) = _$NumberOnly; - factory NumberOnly([void updates(NumberOnlyBuilder b)]) = _$NumberOnly; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(NumberOnlyBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$NumberOnlySerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$NumberOnlySerializer(); } -class _$NumberOnlySerializer implements StructuredSerializer { - @override - final Iterable types = const [NumberOnly, _$NumberOnly]; +class _$NumberOnlySerializer implements PrimitiveSerializer { + @override + final Iterable types = const [NumberOnly, _$NumberOnly]; - @override - final String wireName = r'NumberOnly'; + @override + final String wireName = r'NumberOnly'; - @override - Iterable serialize(Serializers serializers, NumberOnly object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.justNumber != null) { - result - ..add(r'JustNumber') - ..add(serializers.serialize(object.justNumber, - specifiedType: const FullType(num))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + NumberOnly object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.justNumber != null) { + yield r'JustNumber'; + yield serializers.serialize( + object.justNumber, + specifiedType: const FullType(num), + ); } + } - @override - NumberOnly deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = NumberOnlyBuilder(); + @override + Object serialize( + Serializers serializers, + NumberOnly object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'JustNumber': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(num)) as num; - result.justNumber = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required NumberOnlyBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'JustNumber': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(num), + ) as num; + result.justNumber = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + NumberOnly deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = NumberOnlyBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/object_with_deprecated_fields.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/object_with_deprecated_fields.dart index 881ede54d0..f59131ea6f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/object_with_deprecated_fields.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/object_with_deprecated_fields.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:openapi/src/model/deprecated_object.dart'; import 'package:built_value/built_value.dart'; @@ -16,103 +17,148 @@ part 'object_with_deprecated_fields.g.dart'; /// * [id] /// * [deprecatedRef] /// * [bars] +@BuiltValue() abstract class ObjectWithDeprecatedFields implements Built { - @BuiltValueField(wireName: r'uuid') - String? get uuid; + @BuiltValueField(wireName: r'uuid') + String? get uuid; - @BuiltValueField(wireName: r'id') - num? get id; + @BuiltValueField(wireName: r'id') + num? get id; - @BuiltValueField(wireName: r'deprecatedRef') - DeprecatedObject? get deprecatedRef; + @BuiltValueField(wireName: r'deprecatedRef') + DeprecatedObject? get deprecatedRef; - @BuiltValueField(wireName: r'bars') - BuiltList? get bars; + @BuiltValueField(wireName: r'bars') + BuiltList? get bars; - ObjectWithDeprecatedFields._(); + ObjectWithDeprecatedFields._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ObjectWithDeprecatedFieldsBuilder b) => b; + factory ObjectWithDeprecatedFields([void updates(ObjectWithDeprecatedFieldsBuilder b)]) = _$ObjectWithDeprecatedFields; - factory ObjectWithDeprecatedFields([void updates(ObjectWithDeprecatedFieldsBuilder b)]) = _$ObjectWithDeprecatedFields; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ObjectWithDeprecatedFieldsBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ObjectWithDeprecatedFieldsSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ObjectWithDeprecatedFieldsSerializer(); } -class _$ObjectWithDeprecatedFieldsSerializer implements StructuredSerializer { - @override - final Iterable types = const [ObjectWithDeprecatedFields, _$ObjectWithDeprecatedFields]; +class _$ObjectWithDeprecatedFieldsSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ObjectWithDeprecatedFields, _$ObjectWithDeprecatedFields]; - @override - final String wireName = r'ObjectWithDeprecatedFields'; + @override + final String wireName = r'ObjectWithDeprecatedFields'; - @override - Iterable serialize(Serializers serializers, ObjectWithDeprecatedFields object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.uuid != null) { - result - ..add(r'uuid') - ..add(serializers.serialize(object.uuid, - specifiedType: const FullType(String))); - } - if (object.id != null) { - result - ..add(r'id') - ..add(serializers.serialize(object.id, - specifiedType: const FullType(num))); - } - if (object.deprecatedRef != null) { - result - ..add(r'deprecatedRef') - ..add(serializers.serialize(object.deprecatedRef, - specifiedType: const FullType(DeprecatedObject))); - } - if (object.bars != null) { - result - ..add(r'bars') - ..add(serializers.serialize(object.bars, - specifiedType: const FullType(BuiltList, [FullType(String)]))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ObjectWithDeprecatedFields object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.uuid != null) { + yield r'uuid'; + yield serializers.serialize( + object.uuid, + specifiedType: const FullType(String), + ); } - - @override - ObjectWithDeprecatedFields deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ObjectWithDeprecatedFieldsBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'uuid': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.uuid = valueDes; - break; - case r'id': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(num)) as num; - result.id = valueDes; - break; - case r'deprecatedRef': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(DeprecatedObject)) as DeprecatedObject; - result.deprecatedRef.replace(valueDes); - break; - case r'bars': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType(String)])) as BuiltList; - result.bars.replace(valueDes); - break; - } - } - return result.build(); + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(num), + ); } + if (object.deprecatedRef != null) { + yield r'deprecatedRef'; + yield serializers.serialize( + object.deprecatedRef, + specifiedType: const FullType(DeprecatedObject), + ); + } + if (object.bars != null) { + yield r'bars'; + yield serializers.serialize( + object.bars, + specifiedType: const FullType(BuiltList, [FullType(String)]), + ); + } + } + + @override + Object serialize( + Serializers serializers, + ObjectWithDeprecatedFields object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ObjectWithDeprecatedFieldsBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'uuid': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.uuid = valueDes; + break; + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(num), + ) as num; + result.id = valueDes; + break; + case r'deprecatedRef': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(DeprecatedObject), + ) as DeprecatedObject; + result.deprecatedRef.replace(valueDes); + break; + case r'bars': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType(String)]), + ) as BuiltList; + result.bars.replace(valueDes); + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + ObjectWithDeprecatedFields deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ObjectWithDeprecatedFieldsBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/order.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/order.dart index 507a1e3a98..a44e1b340c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/order.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/order.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -17,135 +18,186 @@ part 'order.g.dart'; /// * [shipDate] /// * [status] - Order Status /// * [complete] +@BuiltValue() abstract class Order implements Built { - @BuiltValueField(wireName: r'id') - int? get id; + @BuiltValueField(wireName: r'id') + int? get id; - @BuiltValueField(wireName: r'petId') - int? get petId; + @BuiltValueField(wireName: r'petId') + int? get petId; - @BuiltValueField(wireName: r'quantity') - int? get quantity; + @BuiltValueField(wireName: r'quantity') + int? get quantity; - @BuiltValueField(wireName: r'shipDate') - DateTime? get shipDate; + @BuiltValueField(wireName: r'shipDate') + DateTime? get shipDate; - /// Order Status - @BuiltValueField(wireName: r'status') - OrderStatusEnum? get status; - // enum statusEnum { placed, approved, delivered, }; + /// Order Status + @BuiltValueField(wireName: r'status') + OrderStatusEnum? get status; + // enum statusEnum { placed, approved, delivered, }; - @BuiltValueField(wireName: r'complete') - bool? get complete; + @BuiltValueField(wireName: r'complete') + bool? get complete; - Order._(); + Order._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(OrderBuilder b) => b - ..complete = false; + factory Order([void updates(OrderBuilder b)]) = _$Order; - factory Order([void updates(OrderBuilder b)]) = _$Order; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(OrderBuilder b) => b + ..complete = false; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$OrderSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$OrderSerializer(); } -class _$OrderSerializer implements StructuredSerializer { - @override - final Iterable types = const [Order, _$Order]; +class _$OrderSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Order, _$Order]; - @override - final String wireName = r'Order'; + @override + final String wireName = r'Order'; - @override - Iterable serialize(Serializers serializers, Order object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.id != null) { - result - ..add(r'id') - ..add(serializers.serialize(object.id, - specifiedType: const FullType(int))); - } - if (object.petId != null) { - result - ..add(r'petId') - ..add(serializers.serialize(object.petId, - specifiedType: const FullType(int))); - } - if (object.quantity != null) { - result - ..add(r'quantity') - ..add(serializers.serialize(object.quantity, - specifiedType: const FullType(int))); - } - if (object.shipDate != null) { - result - ..add(r'shipDate') - ..add(serializers.serialize(object.shipDate, - specifiedType: const FullType(DateTime))); - } - if (object.status != null) { - result - ..add(r'status') - ..add(serializers.serialize(object.status, - specifiedType: const FullType(OrderStatusEnum))); - } - if (object.complete != null) { - result - ..add(r'complete') - ..add(serializers.serialize(object.complete, - specifiedType: const FullType(bool))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Order object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(int), + ); } - - @override - Order deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = OrderBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'id': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.id = valueDes; - break; - case r'petId': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.petId = valueDes; - break; - case r'quantity': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.quantity = valueDes; - break; - case r'shipDate': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(DateTime)) as DateTime; - result.shipDate = valueDes; - break; - case r'status': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(OrderStatusEnum)) as OrderStatusEnum; - result.status = valueDes; - break; - case r'complete': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(bool)) as bool; - result.complete = valueDes; - break; - } - } - return result.build(); + if (object.petId != null) { + yield r'petId'; + yield serializers.serialize( + object.petId, + specifiedType: const FullType(int), + ); } + if (object.quantity != null) { + yield r'quantity'; + yield serializers.serialize( + object.quantity, + specifiedType: const FullType(int), + ); + } + if (object.shipDate != null) { + yield r'shipDate'; + yield serializers.serialize( + object.shipDate, + specifiedType: const FullType(DateTime), + ); + } + if (object.status != null) { + yield r'status'; + yield serializers.serialize( + object.status, + specifiedType: const FullType(OrderStatusEnum), + ); + } + if (object.complete != null) { + yield r'complete'; + yield serializers.serialize( + object.complete, + specifiedType: const FullType(bool), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Order object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required OrderBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.id = valueDes; + break; + case r'petId': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.petId = valueDes; + break; + case r'quantity': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.quantity = valueDes; + break; + case r'shipDate': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(DateTime), + ) as DateTime; + result.shipDate = valueDes; + break; + case r'status': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(OrderStatusEnum), + ) as OrderStatusEnum; + result.status = valueDes; + break; + case r'complete': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(bool), + ) as bool; + result.complete = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Order deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = OrderBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } class OrderStatusEnum extends EnumClass { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_composite.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_composite.dart index 0715bdff30..0d6341cc12 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_composite.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_composite.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -13,89 +14,131 @@ part 'outer_composite.g.dart'; /// * [myNumber] /// * [myString] /// * [myBoolean] +@BuiltValue() abstract class OuterComposite implements Built { - @BuiltValueField(wireName: r'my_number') - num? get myNumber; + @BuiltValueField(wireName: r'my_number') + num? get myNumber; - @BuiltValueField(wireName: r'my_string') - String? get myString; + @BuiltValueField(wireName: r'my_string') + String? get myString; - @BuiltValueField(wireName: r'my_boolean') - bool? get myBoolean; + @BuiltValueField(wireName: r'my_boolean') + bool? get myBoolean; - OuterComposite._(); + OuterComposite._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(OuterCompositeBuilder b) => b; + factory OuterComposite([void updates(OuterCompositeBuilder b)]) = _$OuterComposite; - factory OuterComposite([void updates(OuterCompositeBuilder b)]) = _$OuterComposite; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(OuterCompositeBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$OuterCompositeSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$OuterCompositeSerializer(); } -class _$OuterCompositeSerializer implements StructuredSerializer { - @override - final Iterable types = const [OuterComposite, _$OuterComposite]; +class _$OuterCompositeSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [OuterComposite, _$OuterComposite]; - @override - final String wireName = r'OuterComposite'; + @override + final String wireName = r'OuterComposite'; - @override - Iterable serialize(Serializers serializers, OuterComposite object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.myNumber != null) { - result - ..add(r'my_number') - ..add(serializers.serialize(object.myNumber, - specifiedType: const FullType(num))); - } - if (object.myString != null) { - result - ..add(r'my_string') - ..add(serializers.serialize(object.myString, - specifiedType: const FullType(String))); - } - if (object.myBoolean != null) { - result - ..add(r'my_boolean') - ..add(serializers.serialize(object.myBoolean, - specifiedType: const FullType(bool))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + OuterComposite object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.myNumber != null) { + yield r'my_number'; + yield serializers.serialize( + object.myNumber, + specifiedType: const FullType(num), + ); } - - @override - OuterComposite deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = OuterCompositeBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'my_number': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(num)) as num; - result.myNumber = valueDes; - break; - case r'my_string': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.myString = valueDes; - break; - case r'my_boolean': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(bool)) as bool; - result.myBoolean = valueDes; - break; - } - } - return result.build(); + if (object.myString != null) { + yield r'my_string'; + yield serializers.serialize( + object.myString, + specifiedType: const FullType(String), + ); } + if (object.myBoolean != null) { + yield r'my_boolean'; + yield serializers.serialize( + object.myBoolean, + specifiedType: const FullType(bool), + ); + } + } + + @override + Object serialize( + Serializers serializers, + OuterComposite object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required OuterCompositeBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'my_number': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(num), + ) as num; + result.myNumber = valueDes; + break; + case r'my_string': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.myString = valueDes; + break; + case r'my_boolean': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(bool), + ) as bool; + result.myBoolean = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + OuterComposite deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = OuterCompositeBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum.dart index 882219e06c..5ad5d8009b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_default_value.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_default_value.dart index 77353c0771..62c3cefe84 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_default_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_default_value.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_integer.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_integer.dart index 9b17913147..988b30785d 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_integer.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_integer.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_integer_default_value.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_integer_default_value.dart index ded5b2c723..3fe792cedb 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_integer_default_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_enum_integer_default_value.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart index 91524a285b..1733298564 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:openapi/src/model/outer_enum_integer.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,60 +13,96 @@ part 'outer_object_with_enum_property.g.dart'; /// /// Properties: /// * [value] +@BuiltValue() abstract class OuterObjectWithEnumProperty implements Built { - @BuiltValueField(wireName: r'value') - OuterEnumInteger get value; - // enum valueEnum { 0, 1, 2, }; + @BuiltValueField(wireName: r'value') + OuterEnumInteger get value; + // enum valueEnum { 0, 1, 2, }; - OuterObjectWithEnumProperty._(); + OuterObjectWithEnumProperty._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(OuterObjectWithEnumPropertyBuilder b) => b; + factory OuterObjectWithEnumProperty([void updates(OuterObjectWithEnumPropertyBuilder b)]) = _$OuterObjectWithEnumProperty; - factory OuterObjectWithEnumProperty([void updates(OuterObjectWithEnumPropertyBuilder b)]) = _$OuterObjectWithEnumProperty; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(OuterObjectWithEnumPropertyBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$OuterObjectWithEnumPropertySerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$OuterObjectWithEnumPropertySerializer(); } -class _$OuterObjectWithEnumPropertySerializer implements StructuredSerializer { - @override - final Iterable types = const [OuterObjectWithEnumProperty, _$OuterObjectWithEnumProperty]; +class _$OuterObjectWithEnumPropertySerializer implements PrimitiveSerializer { + @override + final Iterable types = const [OuterObjectWithEnumProperty, _$OuterObjectWithEnumProperty]; - @override - final String wireName = r'OuterObjectWithEnumProperty'; + @override + final String wireName = r'OuterObjectWithEnumProperty'; - @override - Iterable serialize(Serializers serializers, OuterObjectWithEnumProperty object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - result - ..add(r'value') - ..add(serializers.serialize(object.value, - specifiedType: const FullType(OuterEnumInteger))); - return result; + Iterable _serializeProperties( + Serializers serializers, + OuterObjectWithEnumProperty object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + yield r'value'; + yield serializers.serialize( + object.value, + specifiedType: const FullType(OuterEnumInteger), + ); + } + + @override + Object serialize( + Serializers serializers, + OuterObjectWithEnumProperty object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required OuterObjectWithEnumPropertyBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'value': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(OuterEnumInteger), + ) as OuterEnumInteger; + result.value = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } - @override - OuterObjectWithEnumProperty deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = OuterObjectWithEnumPropertyBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'value': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(OuterEnumInteger)) as OuterEnumInteger; - result.value = valueDes; - break; - } - } - return result.build(); - } + @override + OuterObjectWithEnumProperty deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = OuterObjectWithEnumPropertyBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/pet.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/pet.dart index 8ed90d104a..4d6358bef2 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/pet.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/pet.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:openapi/src/model/category.dart'; import 'package:openapi/src/model/tag.dart'; @@ -19,130 +20,181 @@ part 'pet.g.dart'; /// * [photoUrls] /// * [tags] /// * [status] - pet status in the store +@BuiltValue() abstract class Pet implements Built { - @BuiltValueField(wireName: r'id') - int? get id; + @BuiltValueField(wireName: r'id') + int? get id; - @BuiltValueField(wireName: r'category') - Category? get category; + @BuiltValueField(wireName: r'category') + Category? get category; - @BuiltValueField(wireName: r'name') - String get name; + @BuiltValueField(wireName: r'name') + String get name; - @BuiltValueField(wireName: r'photoUrls') - BuiltSet get photoUrls; + @BuiltValueField(wireName: r'photoUrls') + BuiltSet get photoUrls; - @BuiltValueField(wireName: r'tags') - BuiltList? get tags; + @BuiltValueField(wireName: r'tags') + BuiltList? get tags; - /// pet status in the store - @BuiltValueField(wireName: r'status') - PetStatusEnum? get status; - // enum statusEnum { available, pending, sold, }; + /// pet status in the store + @BuiltValueField(wireName: r'status') + PetStatusEnum? get status; + // enum statusEnum { available, pending, sold, }; - Pet._(); + Pet._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(PetBuilder b) => b; + factory Pet([void updates(PetBuilder b)]) = _$Pet; - factory Pet([void updates(PetBuilder b)]) = _$Pet; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(PetBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$PetSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$PetSerializer(); } -class _$PetSerializer implements StructuredSerializer { - @override - final Iterable types = const [Pet, _$Pet]; +class _$PetSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Pet, _$Pet]; - @override - final String wireName = r'Pet'; + @override + final String wireName = r'Pet'; - @override - Iterable serialize(Serializers serializers, Pet object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.id != null) { - result - ..add(r'id') - ..add(serializers.serialize(object.id, - specifiedType: const FullType(int))); - } - if (object.category != null) { - result - ..add(r'category') - ..add(serializers.serialize(object.category, - specifiedType: const FullType(Category))); - } - result - ..add(r'name') - ..add(serializers.serialize(object.name, - specifiedType: const FullType(String))); - result - ..add(r'photoUrls') - ..add(serializers.serialize(object.photoUrls, - specifiedType: const FullType(BuiltSet, [FullType(String)]))); - if (object.tags != null) { - result - ..add(r'tags') - ..add(serializers.serialize(object.tags, - specifiedType: const FullType(BuiltList, [FullType(Tag)]))); - } - if (object.status != null) { - result - ..add(r'status') - ..add(serializers.serialize(object.status, - specifiedType: const FullType(PetStatusEnum))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Pet object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(int), + ); } - - @override - Pet deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = PetBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'id': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.id = valueDes; - break; - case r'category': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(Category)) as Category; - result.category.replace(valueDes); - break; - case r'name': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.name = valueDes; - break; - case r'photoUrls': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltSet, [FullType(String)])) as BuiltSet; - result.photoUrls.replace(valueDes); - break; - case r'tags': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(BuiltList, [FullType(Tag)])) as BuiltList; - result.tags.replace(valueDes); - break; - case r'status': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(PetStatusEnum)) as PetStatusEnum; - result.status = valueDes; - break; - } - } - return result.build(); + if (object.category != null) { + yield r'category'; + yield serializers.serialize( + object.category, + specifiedType: const FullType(Category), + ); } + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(String), + ); + yield r'photoUrls'; + yield serializers.serialize( + object.photoUrls, + specifiedType: const FullType(BuiltSet, [FullType(String)]), + ); + if (object.tags != null) { + yield r'tags'; + yield serializers.serialize( + object.tags, + specifiedType: const FullType(BuiltList, [FullType(Tag)]), + ); + } + if (object.status != null) { + yield r'status'; + yield serializers.serialize( + object.status, + specifiedType: const FullType(PetStatusEnum), + ); + } + } + + @override + Object serialize( + Serializers serializers, + Pet object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required PetBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.id = valueDes; + break; + case r'category': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(Category), + ) as Category; + result.category.replace(valueDes); + break; + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.name = valueDes; + break; + case r'photoUrls': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltSet, [FullType(String)]), + ) as BuiltSet; + result.photoUrls.replace(valueDes); + break; + case r'tags': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(BuiltList, [FullType(Tag)]), + ) as BuiltList; + result.tags.replace(valueDes); + break; + case r'status': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(PetStatusEnum), + ) as PetStatusEnum; + result.status = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Pet deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = PetBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } class PetStatusEnum extends EnumClass { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/read_only_first.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/read_only_first.dart index b9f108fb62..b619217ab3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/read_only_first.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/read_only_first.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,75 +13,114 @@ part 'read_only_first.g.dart'; /// Properties: /// * [bar] /// * [baz] +@BuiltValue() abstract class ReadOnlyFirst implements Built { - @BuiltValueField(wireName: r'bar') - String? get bar; + @BuiltValueField(wireName: r'bar') + String? get bar; - @BuiltValueField(wireName: r'baz') - String? get baz; + @BuiltValueField(wireName: r'baz') + String? get baz; - ReadOnlyFirst._(); + ReadOnlyFirst._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(ReadOnlyFirstBuilder b) => b; + factory ReadOnlyFirst([void updates(ReadOnlyFirstBuilder b)]) = _$ReadOnlyFirst; - factory ReadOnlyFirst([void updates(ReadOnlyFirstBuilder b)]) = _$ReadOnlyFirst; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(ReadOnlyFirstBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$ReadOnlyFirstSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$ReadOnlyFirstSerializer(); } -class _$ReadOnlyFirstSerializer implements StructuredSerializer { - @override - final Iterable types = const [ReadOnlyFirst, _$ReadOnlyFirst]; +class _$ReadOnlyFirstSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [ReadOnlyFirst, _$ReadOnlyFirst]; - @override - final String wireName = r'ReadOnlyFirst'; + @override + final String wireName = r'ReadOnlyFirst'; - @override - Iterable serialize(Serializers serializers, ReadOnlyFirst object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.bar != null) { - result - ..add(r'bar') - ..add(serializers.serialize(object.bar, - specifiedType: const FullType(String))); - } - if (object.baz != null) { - result - ..add(r'baz') - ..add(serializers.serialize(object.baz, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + ReadOnlyFirst object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.bar != null) { + yield r'bar'; + yield serializers.serialize( + object.bar, + specifiedType: const FullType(String), + ); } - - @override - ReadOnlyFirst deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = ReadOnlyFirstBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'bar': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.bar = valueDes; - break; - case r'baz': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.baz = valueDes; - break; - } - } - return result.build(); + if (object.baz != null) { + yield r'baz'; + yield serializers.serialize( + object.baz, + specifiedType: const FullType(String), + ); } + } + + @override + Object serialize( + Serializers serializers, + ReadOnlyFirst object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required ReadOnlyFirstBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'bar': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.bar = valueDes; + break; + case r'baz': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.baz = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + ReadOnlyFirst deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = ReadOnlyFirstBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/single_ref_type.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/single_ref_type.dart index f1e6aef099..b51e77292e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/single_ref_type.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/single_ref_type.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_collection/built_collection.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/special_model_name.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/special_model_name.dart index dcfe12bb06..fa860056b4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/special_model_name.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/special_model_name.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -11,61 +12,97 @@ part 'special_model_name.g.dart'; /// /// Properties: /// * [dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket] +@BuiltValue() abstract class SpecialModelName implements Built { - @BuiltValueField(wireName: r'$special[property.name]') - int? get dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket; + @BuiltValueField(wireName: r'$special[property.name]') + int? get dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket; - SpecialModelName._(); + SpecialModelName._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(SpecialModelNameBuilder b) => b; + factory SpecialModelName([void updates(SpecialModelNameBuilder b)]) = _$SpecialModelName; - factory SpecialModelName([void updates(SpecialModelNameBuilder b)]) = _$SpecialModelName; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(SpecialModelNameBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$SpecialModelNameSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$SpecialModelNameSerializer(); } -class _$SpecialModelNameSerializer implements StructuredSerializer { - @override - final Iterable types = const [SpecialModelName, _$SpecialModelName]; +class _$SpecialModelNameSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [SpecialModelName, _$SpecialModelName]; - @override - final String wireName = r'SpecialModelName'; + @override + final String wireName = r'SpecialModelName'; - @override - Iterable serialize(Serializers serializers, SpecialModelName object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket != null) { - result - ..add(r'$special[property.name]') - ..add(serializers.serialize(object.dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket, - specifiedType: const FullType(int))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + SpecialModelName object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket != null) { + yield r'$special[property.name]'; + yield serializers.serialize( + object.dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket, + specifiedType: const FullType(int), + ); } + } - @override - SpecialModelName deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = SpecialModelNameBuilder(); + @override + Object serialize( + Serializers serializers, + SpecialModelName object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'$special[property.name]': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket = valueDes; - break; - } - } - return result.build(); + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required SpecialModelNameBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'$special[property.name]': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } } + } + + @override + SpecialModelName deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = SpecialModelNameBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/tag.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/tag.dart index 5a7ed38d94..3be220d818 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/tag.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/tag.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -12,75 +13,114 @@ part 'tag.g.dart'; /// Properties: /// * [id] /// * [name] +@BuiltValue() abstract class Tag implements Built { - @BuiltValueField(wireName: r'id') - int? get id; + @BuiltValueField(wireName: r'id') + int? get id; - @BuiltValueField(wireName: r'name') - String? get name; + @BuiltValueField(wireName: r'name') + String? get name; - Tag._(); + Tag._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(TagBuilder b) => b; + factory Tag([void updates(TagBuilder b)]) = _$Tag; - factory Tag([void updates(TagBuilder b)]) = _$Tag; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(TagBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$TagSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$TagSerializer(); } -class _$TagSerializer implements StructuredSerializer { - @override - final Iterable types = const [Tag, _$Tag]; +class _$TagSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [Tag, _$Tag]; - @override - final String wireName = r'Tag'; + @override + final String wireName = r'Tag'; - @override - Iterable serialize(Serializers serializers, Tag object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.id != null) { - result - ..add(r'id') - ..add(serializers.serialize(object.id, - specifiedType: const FullType(int))); - } - if (object.name != null) { - result - ..add(r'name') - ..add(serializers.serialize(object.name, - specifiedType: const FullType(String))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + Tag object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(int), + ); } - - @override - Tag deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = TagBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'id': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.id = valueDes; - break; - case r'name': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.name = valueDes; - break; - } - } - return result.build(); + if (object.name != null) { + yield r'name'; + yield serializers.serialize( + object.name, + specifiedType: const FullType(String), + ); } + } + + @override + Object serialize( + Serializers serializers, + Tag object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required TagBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.id = valueDes; + break; + case r'name': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.name = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + Tag deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = TagBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/user.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/user.dart index d590c20bdc..f7577d7e1e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/user.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/model/user.dart @@ -2,6 +2,7 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_element import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; @@ -18,160 +19,217 @@ part 'user.g.dart'; /// * [password] /// * [phone] /// * [userStatus] - User Status +@BuiltValue() abstract class User implements Built { - @BuiltValueField(wireName: r'id') - int? get id; + @BuiltValueField(wireName: r'id') + int? get id; - @BuiltValueField(wireName: r'username') - String? get username; + @BuiltValueField(wireName: r'username') + String? get username; - @BuiltValueField(wireName: r'firstName') - String? get firstName; + @BuiltValueField(wireName: r'firstName') + String? get firstName; - @BuiltValueField(wireName: r'lastName') - String? get lastName; + @BuiltValueField(wireName: r'lastName') + String? get lastName; - @BuiltValueField(wireName: r'email') - String? get email; + @BuiltValueField(wireName: r'email') + String? get email; - @BuiltValueField(wireName: r'password') - String? get password; + @BuiltValueField(wireName: r'password') + String? get password; - @BuiltValueField(wireName: r'phone') - String? get phone; + @BuiltValueField(wireName: r'phone') + String? get phone; - /// User Status - @BuiltValueField(wireName: r'userStatus') - int? get userStatus; + /// User Status + @BuiltValueField(wireName: r'userStatus') + int? get userStatus; - User._(); + User._(); - @BuiltValueHook(initializeBuilder: true) - static void _defaults(UserBuilder b) => b; + factory User([void updates(UserBuilder b)]) = _$User; - factory User([void updates(UserBuilder b)]) = _$User; + @BuiltValueHook(initializeBuilder: true) + static void _defaults(UserBuilder b) => b; - @BuiltValueSerializer(custom: true) - static Serializer get serializer => _$UserSerializer(); + @BuiltValueSerializer(custom: true) + static Serializer get serializer => _$UserSerializer(); } -class _$UserSerializer implements StructuredSerializer { - @override - final Iterable types = const [User, _$User]; +class _$UserSerializer implements PrimitiveSerializer { + @override + final Iterable types = const [User, _$User]; - @override - final String wireName = r'User'; + @override + final String wireName = r'User'; - @override - Iterable serialize(Serializers serializers, User object, - {FullType specifiedType = FullType.unspecified}) { - final result = []; - if (object.id != null) { - result - ..add(r'id') - ..add(serializers.serialize(object.id, - specifiedType: const FullType(int))); - } - if (object.username != null) { - result - ..add(r'username') - ..add(serializers.serialize(object.username, - specifiedType: const FullType(String))); - } - if (object.firstName != null) { - result - ..add(r'firstName') - ..add(serializers.serialize(object.firstName, - specifiedType: const FullType(String))); - } - if (object.lastName != null) { - result - ..add(r'lastName') - ..add(serializers.serialize(object.lastName, - specifiedType: const FullType(String))); - } - if (object.email != null) { - result - ..add(r'email') - ..add(serializers.serialize(object.email, - specifiedType: const FullType(String))); - } - if (object.password != null) { - result - ..add(r'password') - ..add(serializers.serialize(object.password, - specifiedType: const FullType(String))); - } - if (object.phone != null) { - result - ..add(r'phone') - ..add(serializers.serialize(object.phone, - specifiedType: const FullType(String))); - } - if (object.userStatus != null) { - result - ..add(r'userStatus') - ..add(serializers.serialize(object.userStatus, - specifiedType: const FullType(int))); - } - return result; + Iterable _serializeProperties( + Serializers serializers, + User object, { + FullType specifiedType = FullType.unspecified, + }) sync* { + if (object.id != null) { + yield r'id'; + yield serializers.serialize( + object.id, + specifiedType: const FullType(int), + ); } - - @override - User deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType = FullType.unspecified}) { - final result = UserBuilder(); - - final iterator = serialized.iterator; - while (iterator.moveNext()) { - final key = iterator.current as String; - iterator.moveNext(); - final Object? value = iterator.current; - - switch (key) { - case r'id': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.id = valueDes; - break; - case r'username': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.username = valueDes; - break; - case r'firstName': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.firstName = valueDes; - break; - case r'lastName': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.lastName = valueDes; - break; - case r'email': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.email = valueDes; - break; - case r'password': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.password = valueDes; - break; - case r'phone': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(String)) as String; - result.phone = valueDes; - break; - case r'userStatus': - final valueDes = serializers.deserialize(value, - specifiedType: const FullType(int)) as int; - result.userStatus = valueDes; - break; - } - } - return result.build(); + if (object.username != null) { + yield r'username'; + yield serializers.serialize( + object.username, + specifiedType: const FullType(String), + ); } + if (object.firstName != null) { + yield r'firstName'; + yield serializers.serialize( + object.firstName, + specifiedType: const FullType(String), + ); + } + if (object.lastName != null) { + yield r'lastName'; + yield serializers.serialize( + object.lastName, + specifiedType: const FullType(String), + ); + } + if (object.email != null) { + yield r'email'; + yield serializers.serialize( + object.email, + specifiedType: const FullType(String), + ); + } + if (object.password != null) { + yield r'password'; + yield serializers.serialize( + object.password, + specifiedType: const FullType(String), + ); + } + if (object.phone != null) { + yield r'phone'; + yield serializers.serialize( + object.phone, + specifiedType: const FullType(String), + ); + } + if (object.userStatus != null) { + yield r'userStatus'; + yield serializers.serialize( + object.userStatus, + specifiedType: const FullType(int), + ); + } + } + + @override + Object serialize( + Serializers serializers, + User object, { + FullType specifiedType = FullType.unspecified, + }) { + return _serializeProperties(serializers, object, specifiedType: specifiedType).toList(); + } + + void _deserializeProperties( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + required List serializedList, + required UserBuilder result, + required List unhandled, + }) { + for (var i = 0; i < serializedList.length; i += 2) { + final key = serializedList[i] as String; + final value = serializedList[i + 1]; + switch (key) { + case r'id': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.id = valueDes; + break; + case r'username': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.username = valueDes; + break; + case r'firstName': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.firstName = valueDes; + break; + case r'lastName': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.lastName = valueDes; + break; + case r'email': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.email = valueDes; + break; + case r'password': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.password = valueDes; + break; + case r'phone': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(String), + ) as String; + result.phone = valueDes; + break; + case r'userStatus': + final valueDes = serializers.deserialize( + value, + specifiedType: const FullType(int), + ) as int; + result.userStatus = valueDes; + break; + default: + unhandled.add(key); + unhandled.add(value); + break; + } + } + } + + @override + User deserialize( + Serializers serializers, + Object serialized, { + FullType specifiedType = FullType.unspecified, + }) { + final result = UserBuilder(); + final serializedList = (serialized as Iterable).toList(); + final unhandled = []; + _deserializeProperties( + serializers, + serialized, + specifiedType: specifiedType, + serializedList: serializedList, + unhandled: unhandled, + result: result, + ); + return result.build(); + } } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/serializers.dart index 8ac0fc258f..60f50e5a77 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/serializers.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/serializers.dart @@ -4,6 +4,8 @@ // ignore_for_file: unused_import +import 'package:one_of_serializer/any_of_serializer.dart'; +import 'package:one_of_serializer/one_of_serializer.dart'; import 'package:built_collection/built_collection.dart'; import 'package:built_value/json_object.dart'; import 'package:built_value/serializer.dart'; @@ -66,19 +68,19 @@ part 'serializers.g.dart'; @SerializersFor([ AdditionalPropertiesClass, AllOfWithSingleRef, - Animal, + Animal,$Animal, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Capitalization, Cat, - CatAllOf, + CatAllOf,$CatAllOf, Category, ClassModel, DeprecatedObject, Dog, - DogAllOf, + DogAllOf,$DogAllOf, EnumArrays, EnumTest, FileSchemaTestClass, @@ -146,6 +148,11 @@ Serializers serializers = (_$serializers.toBuilder() const FullType(BuiltList, [FullType(String)]), () => ListBuilder(), ) + ..add(Animal.serializer) + ..add(CatAllOf.serializer) + ..add(DogAllOf.serializer) + ..add(const OneOfSerializer()) + ..add(const AnyOfSerializer()) ..add(const DateSerializer()) ..add(Iso8601DateTimeSerializer())) .build(); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml index 5a3cc4e4df..fb676f65c3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml @@ -8,10 +8,12 @@ environment: dependencies: dio: '>=4.0.1 <5.0.0' - built_value: '>=8.1.0 <9.0.0' - built_collection: '>=5.1.0 <6.0.0' + one_of: '>=1.5.0 <2.0.0' + one_of_serializer: '>=1.5.0 <2.0.0' + built_value: '>=8.4.0 <9.0.0' + built_collection: '>=5.1.1 <6.0.0' dev_dependencies: - built_value_generator: '>=8.1.0 <9.0.0' + built_value_generator: '>=8.4.0 <9.0.0' build_runner: any test: ^1.16.0 diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/all_of_with_single_ref_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/all_of_with_single_ref_test.dart index 8fdb1603ce..64e241a4dc 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/all_of_with_single_ref_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/all_of_with_single_ref_test.dart @@ -12,7 +12,7 @@ void main() { // TODO }); - // AllOfWithSingleRefSingleRefType singleRefType + // SingleRefType singleRefType test('to test the property `singleRefType`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/animal_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/animal_test.dart index 875bb42a10..39b8b59cdf 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/animal_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/animal_test.dart @@ -3,7 +3,7 @@ import 'package:openapi/openapi.dart'; // tests for Animal void main() { - final instance = AnimalBuilder(); + //final instance = AnimalBuilder(); // TODO add properties to the builder and call build() group(Animal, () { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_all_of_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_all_of_test.dart index afdac82ad1..fb7e999bf8 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_all_of_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/cat_all_of_test.dart @@ -3,7 +3,7 @@ import 'package:openapi/openapi.dart'; // tests for CatAllOf void main() { - final instance = CatAllOfBuilder(); + //final instance = CatAllOfBuilder(); // TODO add properties to the builder and call build() group(CatAllOf, () { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/class_model_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/class_model_test.dart index 92f95f186c..89f1d35e55 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/class_model_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/class_model_test.dart @@ -7,8 +7,8 @@ void main() { // TODO add properties to the builder and call build() group(ClassModel, () { - // String class_ - test('to test the property `class_`', () async { + // String classField + test('to test the property `classField`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/default_api_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/default_api_test.dart index eef4c41652..f079565f97 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/default_api_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/default_api_test.dart @@ -7,7 +7,7 @@ void main() { final instance = Openapi().getDefaultApi(); group(DefaultApi, () { - //Future fooGet() async + //Future fooGet() async test('test fooGet', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_all_of_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_all_of_test.dart index 7b58b3a275..7b4f4095dc 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_all_of_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/dog_all_of_test.dart @@ -3,7 +3,7 @@ import 'package:openapi/openapi.dart'; // tests for DogAllOf void main() { - final instance = DogAllOfBuilder(); + //final instance = DogAllOfBuilder(); // TODO add properties to the builder and call build() group(DogAllOf, () { diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model200_response_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model200_response_test.dart index 39ff6ec59c..11bac07faf 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model200_response_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/model200_response_test.dart @@ -12,8 +12,8 @@ void main() { // TODO }); - // String class_ - test('to test the property `class_`', () async { + // String classField + test('to test the property `classField`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/user_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/user_test.dart index d4555abccc..1e6a1bc23f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/user_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/test/user_test.dart @@ -48,10 +48,5 @@ void main() { // TODO }); - // UserType userType - test('to test the property `userType`', () async { - // TODO - }); - }); } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake_tests/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake_tests/pubspec.yaml index 518f45b62e..80178cb89a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake_tests/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake_tests/pubspec.yaml @@ -8,8 +8,8 @@ environment: sdk: '>=2.10.0 <3.0.0' dev_dependencies: - built_collection: 5.1.0 - built_value: 8.1.0 + built_collection: 5.1.1 + built_value: 8.4.0 dio: 4.0.1 http_mock_adapter: 0.3.2 mockito: 5.0.11 diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake_tests/puby.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake_tests/puby.yaml new file mode 100644 index 0000000000..64080c7e80 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake_tests/puby.yaml @@ -0,0 +1,3 @@ +exclude: + - test + - pub run build_runner \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart index ce5560f03f..00b9e81f7e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart @@ -11,11 +11,13 @@ part of openapi.api; class ApiClient { - ApiClient({this.basePath = 'http://petstore.swagger.io/v2', this.authentication}); + ApiClient({this.basePath = 'http://petstore.swagger.io/v2', this.authentication,}); final String basePath; + final Authentication? authentication; var _client = Client(); + final _defaultHeaderMap = {}; /// Returns the current HTTP [Client] instance to use in this class. /// @@ -27,15 +29,12 @@ class ApiClient { _client = newClient; } - final _defaultHeaderMap = {}; - final Authentication? authentication; + Map get defaultHeaderMap => _defaultHeaderMap; void addDefaultHeader(String key, String value) { _defaultHeaderMap[key] = value; } - Map get defaultHeaderMap => _defaultHeaderMap; - // We don't use a Map for queryParams. // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( @@ -47,7 +46,7 @@ class ApiClient { Map formParams, String? contentType, ) async { - _updateParamsForAuth(queryParams, headerParams); + await authentication?.applyToParams(queryParams, headerParams); headerParams.addAll(_defaultHeaderMap); if (contentType != null) { @@ -165,16 +164,6 @@ class ApiClient { @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') String serialize(Object? value) => value == null ? '' : json.encode(value); - /// Update query and header parameters based on authentication settings. - void _updateParamsForAuth( - List queryParams, - Map headerParams, - ) { - if (authentication != null) { - authentication!.applyToParams(queryParams, headerParams); - } - } - static dynamic _deserialize(dynamic value, String targetType, {bool growable = false}) { try { switch (targetType) { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart index e304eda321..84dc2955c2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/api_key_auth.dart @@ -20,7 +20,7 @@ class ApiKeyAuth implements Authentication { String apiKey = ''; @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { final paramValue = apiKeyPrefix.isEmpty ? apiKey : '$apiKeyPrefix $apiKey'; if (paramValue.isNotEmpty) { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart index 49baf7c46a..1b1b8ae11e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/authentication.dart @@ -13,5 +13,5 @@ part of openapi.api; // ignore: one_member_abstracts abstract class Authentication { /// Apply authentication settings to header and query params. - void applyToParams(List queryParams, Map headerParams); + Future applyToParams(List queryParams, Map headerParams); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart index 81abd7185f..dfedaa50d0 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_basic_auth.dart @@ -17,7 +17,7 @@ class HttpBasicAuth implements Authentication { String password; @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { if (username.isNotEmpty && password.isNotEmpty) { final credentials = '$username:$password'; headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart index 213f3483b8..eddf3a59cb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/http_bearer_auth.dart @@ -27,7 +27,7 @@ class HttpBearerAuth implements Authentication { } @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { if (_accessToken == null) { return; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart index e9b87cffb0..e9e7d784c3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/auth/oauth.dart @@ -16,7 +16,7 @@ class OAuth implements Authentication { String accessToken; @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { if (accessToken.isNotEmpty) { headerParams['Authorization'] = 'Bearer $accessToken'; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart index a4eaa58a9d..666778ab61 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart @@ -59,23 +59,23 @@ class ApiResponse { String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; Map toJson() { - final _json = {}; - if (code != null) { - _json[r'code'] = code; + final json = {}; + if (this.code != null) { + json[r'code'] = this.code; } else { - _json[r'code'] = null; + json[r'code'] = null; } - if (type != null) { - _json[r'type'] = type; + if (this.type != null) { + json[r'type'] = this.type; } else { - _json[r'type'] = null; + json[r'type'] = null; } - if (message != null) { - _json[r'message'] = message; + if (this.message != null) { + json[r'message'] = this.message; } else { - _json[r'message'] = null; + json[r'message'] = null; } - return _json; + return json; } /// Returns a new [ApiResponse] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart index d010dbf2c4..06f01cc120 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart @@ -48,18 +48,18 @@ class Category { String toString() => 'Category[id=$id, name=$name]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (name != null) { - _json[r'name'] = name; + if (this.name != null) { + json[r'name'] = this.name; } else { - _json[r'name'] = null; + json[r'name'] = null; } - return _json; + return json; } /// Returns a new [Category] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart index 27db5fd318..d317b6b411 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart @@ -81,34 +81,34 @@ class Order { String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (petId != null) { - _json[r'petId'] = petId; + if (this.petId != null) { + json[r'petId'] = this.petId; } else { - _json[r'petId'] = null; + json[r'petId'] = null; } - if (quantity != null) { - _json[r'quantity'] = quantity; + if (this.quantity != null) { + json[r'quantity'] = this.quantity; } else { - _json[r'quantity'] = null; + json[r'quantity'] = null; } - if (shipDate != null) { - _json[r'shipDate'] = shipDate!.toUtc().toIso8601String(); + if (this.shipDate != null) { + json[r'shipDate'] = this.shipDate!.toUtc().toIso8601String(); } else { - _json[r'shipDate'] = null; + json[r'shipDate'] = null; } - if (status != null) { - _json[r'status'] = status; + if (this.status != null) { + json[r'status'] = this.status; } else { - _json[r'status'] = null; + json[r'status'] = null; } - _json[r'complete'] = complete; - return _json; + json[r'complete'] = this.complete; + return json; } /// Returns a new [Order] instance and imports its values from @@ -247,7 +247,7 @@ class OrderStatusEnumTypeTransformer { /// and users are still using an old app with the old code. OrderStatusEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'placed': return OrderStatusEnum.placed; case r'approved': return OrderStatusEnum.approved; case r'delivered': return OrderStatusEnum.delivered; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart index e93bff4b5d..89e862f59a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart @@ -69,26 +69,26 @@ class Pet { String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (category != null) { - _json[r'category'] = category; + if (this.category != null) { + json[r'category'] = this.category; } else { - _json[r'category'] = null; + json[r'category'] = null; } - _json[r'name'] = name; - _json[r'photoUrls'] = photoUrls; - _json[r'tags'] = tags; - if (status != null) { - _json[r'status'] = status; + json[r'name'] = this.name; + json[r'photoUrls'] = this.photoUrls; + json[r'tags'] = this.tags; + if (this.status != null) { + json[r'status'] = this.status; } else { - _json[r'status'] = null; + json[r'status'] = null; } - return _json; + return json; } /// Returns a new [Pet] instance and imports its values from @@ -231,7 +231,7 @@ class PetStatusEnumTypeTransformer { /// and users are still using an old app with the old code. PetStatusEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'available': return PetStatusEnum.available; case r'pending': return PetStatusEnum.pending; case r'sold': return PetStatusEnum.sold; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart index 18e86440a1..1fd6d01f16 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart @@ -48,18 +48,18 @@ class Tag { String toString() => 'Tag[id=$id, name=$name]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (name != null) { - _json[r'name'] = name; + if (this.name != null) { + json[r'name'] = this.name; } else { - _json[r'name'] = null; + json[r'name'] = null; } - return _json; + return json; } /// Returns a new [Tag] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart index 4d3d14508c..63fc8e5281 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart @@ -115,48 +115,48 @@ class User { String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (username != null) { - _json[r'username'] = username; + if (this.username != null) { + json[r'username'] = this.username; } else { - _json[r'username'] = null; + json[r'username'] = null; } - if (firstName != null) { - _json[r'firstName'] = firstName; + if (this.firstName != null) { + json[r'firstName'] = this.firstName; } else { - _json[r'firstName'] = null; + json[r'firstName'] = null; } - if (lastName != null) { - _json[r'lastName'] = lastName; + if (this.lastName != null) { + json[r'lastName'] = this.lastName; } else { - _json[r'lastName'] = null; + json[r'lastName'] = null; } - if (email != null) { - _json[r'email'] = email; + if (this.email != null) { + json[r'email'] = this.email; } else { - _json[r'email'] = null; + json[r'email'] = null; } - if (password != null) { - _json[r'password'] = password; + if (this.password != null) { + json[r'password'] = this.password; } else { - _json[r'password'] = null; + json[r'password'] = null; } - if (phone != null) { - _json[r'phone'] = phone; + if (this.phone != null) { + json[r'phone'] = this.phone; } else { - _json[r'phone'] = null; + json[r'phone'] = null; } - if (userStatus != null) { - _json[r'userStatus'] = userStatus; + if (this.userStatus != null) { + json[r'userStatus'] = this.userStatus; } else { - _json[r'userStatus'] = null; + json[r'userStatus'] = null; } - return _json; + return json; } /// Returns a new [User] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart index 94a25909e6..22839ae04f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart @@ -11,11 +11,13 @@ part of openapi.api; class ApiClient { - ApiClient({this.basePath = 'http://petstore.swagger.io:80/v2', this.authentication}); + ApiClient({this.basePath = 'http://petstore.swagger.io:80/v2', this.authentication,}); final String basePath; + final Authentication? authentication; var _client = Client(); + final _defaultHeaderMap = {}; /// Returns the current HTTP [Client] instance to use in this class. /// @@ -27,15 +29,12 @@ class ApiClient { _client = newClient; } - final _defaultHeaderMap = {}; - final Authentication? authentication; + Map get defaultHeaderMap => _defaultHeaderMap; void addDefaultHeader(String key, String value) { _defaultHeaderMap[key] = value; } - Map get defaultHeaderMap => _defaultHeaderMap; - // We don't use a Map for queryParams. // If collectionFormat is 'multi', a key might appear multiple times. Future invokeAPI( @@ -47,7 +46,7 @@ class ApiClient { Map formParams, String? contentType, ) async { - _updateParamsForAuth(queryParams, headerParams); + await authentication?.applyToParams(queryParams, headerParams); headerParams.addAll(_defaultHeaderMap); if (contentType != null) { @@ -165,16 +164,6 @@ class ApiClient { @Deprecated('Scheduled for removal in OpenAPI Generator 6.x. Use serializeAsync() instead.') String serialize(Object? value) => value == null ? '' : json.encode(value); - /// Update query and header parameters based on authentication settings. - void _updateParamsForAuth( - List queryParams, - Map headerParams, - ) { - if (authentication != null) { - authentication!.applyToParams(queryParams, headerParams); - } - } - static dynamic _deserialize(dynamic value, String targetType, {bool growable = false}) { try { switch (targetType) { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/api_key_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/api_key_auth.dart index e304eda321..84dc2955c2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/api_key_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/api_key_auth.dart @@ -20,7 +20,7 @@ class ApiKeyAuth implements Authentication { String apiKey = ''; @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { final paramValue = apiKeyPrefix.isEmpty ? apiKey : '$apiKeyPrefix $apiKey'; if (paramValue.isNotEmpty) { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/authentication.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/authentication.dart index 49baf7c46a..1b1b8ae11e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/authentication.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/authentication.dart @@ -13,5 +13,5 @@ part of openapi.api; // ignore: one_member_abstracts abstract class Authentication { /// Apply authentication settings to header and query params. - void applyToParams(List queryParams, Map headerParams); + Future applyToParams(List queryParams, Map headerParams); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_basic_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_basic_auth.dart index 81abd7185f..dfedaa50d0 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_basic_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_basic_auth.dart @@ -17,7 +17,7 @@ class HttpBasicAuth implements Authentication { String password; @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { if (username.isNotEmpty && password.isNotEmpty) { final credentials = '$username:$password'; headerParams['Authorization'] = 'Basic ${base64.encode(utf8.encode(credentials))}'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_bearer_auth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_bearer_auth.dart index 213f3483b8..eddf3a59cb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_bearer_auth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/http_bearer_auth.dart @@ -27,7 +27,7 @@ class HttpBearerAuth implements Authentication { } @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { if (_accessToken == null) { return; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/oauth.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/oauth.dart index e9b87cffb0..e9e7d784c3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/oauth.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/auth/oauth.dart @@ -16,7 +16,7 @@ class OAuth implements Authentication { String accessToken; @override - void applyToParams(List queryParams, Map headerParams) { + Future applyToParams(List queryParams, Map headerParams,) async { if (accessToken.isNotEmpty) { headerParams['Authorization'] = 'Bearer $accessToken'; } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart index 43adda6ff7..68e479ee4f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart @@ -36,10 +36,10 @@ class AdditionalPropertiesClass { String toString() => 'AdditionalPropertiesClass[mapProperty=$mapProperty, mapOfMapProperty=$mapOfMapProperty]'; Map toJson() { - final _json = {}; - _json[r'map_property'] = mapProperty; - _json[r'map_of_map_property'] = mapOfMapProperty; - return _json; + final json = {}; + json[r'map_property'] = this.mapProperty; + json[r'map_of_map_property'] = this.mapOfMapProperty; + return json; } /// Returns a new [AdditionalPropertiesClass] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/all_of_with_single_ref.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/all_of_with_single_ref.dart index 22a9e4600d..e98860d25a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/all_of_with_single_ref.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/all_of_with_single_ref.dart @@ -42,18 +42,18 @@ class AllOfWithSingleRef { String toString() => 'AllOfWithSingleRef[username=$username, singleRefType=$singleRefType]'; Map toJson() { - final _json = {}; - if (username != null) { - _json[r'username'] = username; + final json = {}; + if (this.username != null) { + json[r'username'] = this.username; } else { - _json[r'username'] = null; + json[r'username'] = null; } - if (singleRefType != null) { - _json[r'SingleRefType'] = singleRefType; + if (this.singleRefType != null) { + json[r'SingleRefType'] = this.singleRefType; } else { - _json[r'SingleRefType'] = null; + json[r'SingleRefType'] = null; } - return _json; + return json; } /// Returns a new [AllOfWithSingleRef] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart index ab9fe4decc..2329953a70 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart @@ -36,10 +36,10 @@ class Animal { String toString() => 'Animal[className=$className, color=$color]'; Map toJson() { - final _json = {}; - _json[r'className'] = className; - _json[r'color'] = color; - return _json; + final json = {}; + json[r'className'] = this.className; + json[r'color'] = this.color; + return json; } /// Returns a new [Animal] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart index a4eaa58a9d..666778ab61 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart @@ -59,23 +59,23 @@ class ApiResponse { String toString() => 'ApiResponse[code=$code, type=$type, message=$message]'; Map toJson() { - final _json = {}; - if (code != null) { - _json[r'code'] = code; + final json = {}; + if (this.code != null) { + json[r'code'] = this.code; } else { - _json[r'code'] = null; + json[r'code'] = null; } - if (type != null) { - _json[r'type'] = type; + if (this.type != null) { + json[r'type'] = this.type; } else { - _json[r'type'] = null; + json[r'type'] = null; } - if (message != null) { - _json[r'message'] = message; + if (this.message != null) { + json[r'message'] = this.message; } else { - _json[r'message'] = null; + json[r'message'] = null; } - return _json; + return json; } /// Returns a new [ApiResponse] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart index c328bc86ab..99f89a1ee2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart @@ -31,9 +31,9 @@ class ArrayOfArrayOfNumberOnly { String toString() => 'ArrayOfArrayOfNumberOnly[arrayArrayNumber=$arrayArrayNumber]'; Map toJson() { - final _json = {}; - _json[r'ArrayArrayNumber'] = arrayArrayNumber; - return _json; + final json = {}; + json[r'ArrayArrayNumber'] = this.arrayArrayNumber; + return json; } /// Returns a new [ArrayOfArrayOfNumberOnly] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart index 15a737605d..321f7c4f40 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart @@ -31,9 +31,9 @@ class ArrayOfNumberOnly { String toString() => 'ArrayOfNumberOnly[arrayNumber=$arrayNumber]'; Map toJson() { - final _json = {}; - _json[r'ArrayNumber'] = arrayNumber; - return _json; + final json = {}; + json[r'ArrayNumber'] = this.arrayNumber; + return json; } /// Returns a new [ArrayOfNumberOnly] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart index f9497f9a71..c0b262e7d2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart @@ -41,11 +41,11 @@ class ArrayTest { String toString() => 'ArrayTest[arrayOfString=$arrayOfString, arrayArrayOfInteger=$arrayArrayOfInteger, arrayArrayOfModel=$arrayArrayOfModel]'; Map toJson() { - final _json = {}; - _json[r'array_of_string'] = arrayOfString; - _json[r'array_array_of_integer'] = arrayArrayOfInteger; - _json[r'array_array_of_model'] = arrayArrayOfModel; - return _json; + final json = {}; + json[r'array_of_string'] = this.arrayOfString; + json[r'array_array_of_integer'] = this.arrayArrayOfInteger; + json[r'array_array_of_model'] = this.arrayArrayOfModel; + return json; } /// Returns a new [ArrayTest] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart index fc5ed9f6d2..838c767d3e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart @@ -93,38 +93,38 @@ class Capitalization { String toString() => 'Capitalization[smallCamel=$smallCamel, capitalCamel=$capitalCamel, smallSnake=$smallSnake, capitalSnake=$capitalSnake, sCAETHFlowPoints=$sCAETHFlowPoints, ATT_NAME=$ATT_NAME]'; Map toJson() { - final _json = {}; - if (smallCamel != null) { - _json[r'smallCamel'] = smallCamel; + final json = {}; + if (this.smallCamel != null) { + json[r'smallCamel'] = this.smallCamel; } else { - _json[r'smallCamel'] = null; + json[r'smallCamel'] = null; } - if (capitalCamel != null) { - _json[r'CapitalCamel'] = capitalCamel; + if (this.capitalCamel != null) { + json[r'CapitalCamel'] = this.capitalCamel; } else { - _json[r'CapitalCamel'] = null; + json[r'CapitalCamel'] = null; } - if (smallSnake != null) { - _json[r'small_Snake'] = smallSnake; + if (this.smallSnake != null) { + json[r'small_Snake'] = this.smallSnake; } else { - _json[r'small_Snake'] = null; + json[r'small_Snake'] = null; } - if (capitalSnake != null) { - _json[r'Capital_Snake'] = capitalSnake; + if (this.capitalSnake != null) { + json[r'Capital_Snake'] = this.capitalSnake; } else { - _json[r'Capital_Snake'] = null; + json[r'Capital_Snake'] = null; } - if (sCAETHFlowPoints != null) { - _json[r'SCA_ETH_Flow_Points'] = sCAETHFlowPoints; + if (this.sCAETHFlowPoints != null) { + json[r'SCA_ETH_Flow_Points'] = this.sCAETHFlowPoints; } else { - _json[r'SCA_ETH_Flow_Points'] = null; + json[r'SCA_ETH_Flow_Points'] = null; } - if (ATT_NAME != null) { - _json[r'ATT_NAME'] = ATT_NAME; + if (this.ATT_NAME != null) { + json[r'ATT_NAME'] = this.ATT_NAME; } else { - _json[r'ATT_NAME'] = null; + json[r'ATT_NAME'] = null; } - return _json; + return json; } /// Returns a new [Capitalization] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart index a3011f6a11..6bfb040ad1 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart @@ -47,15 +47,15 @@ class Cat { String toString() => 'Cat[className=$className, color=$color, declawed=$declawed]'; Map toJson() { - final _json = {}; - _json[r'className'] = className; - _json[r'color'] = color; - if (declawed != null) { - _json[r'declawed'] = declawed; + final json = {}; + json[r'className'] = this.className; + json[r'color'] = this.color; + if (this.declawed != null) { + json[r'declawed'] = this.declawed; } else { - _json[r'declawed'] = null; + json[r'declawed'] = null; } - return _json; + return json; } /// Returns a new [Cat] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart index d9b6f73005..63ed47e43f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart @@ -37,13 +37,13 @@ class CatAllOf { String toString() => 'CatAllOf[declawed=$declawed]'; Map toJson() { - final _json = {}; - if (declawed != null) { - _json[r'declawed'] = declawed; + final json = {}; + if (this.declawed != null) { + json[r'declawed'] = this.declawed; } else { - _json[r'declawed'] = null; + json[r'declawed'] = null; } - return _json; + return json; } /// Returns a new [CatAllOf] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart index 364afedb3e..f0cb75c98e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart @@ -42,14 +42,14 @@ class Category { String toString() => 'Category[id=$id, name=$name]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - _json[r'name'] = name; - return _json; + json[r'name'] = this.name; + return json; } /// Returns a new [Category] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart index 96e9daa12e..b4398348c5 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart @@ -37,13 +37,13 @@ class ClassModel { String toString() => 'ClassModel[class_=$class_]'; Map toJson() { - final _json = {}; - if (class_ != null) { - _json[r'_class'] = class_; + final json = {}; + if (this.class_ != null) { + json[r'_class'] = this.class_; } else { - _json[r'_class'] = null; + json[r'_class'] = null; } - return _json; + return json; } /// Returns a new [ClassModel] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/deprecated_object.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/deprecated_object.dart index bb90d8abe8..6f3ff3dc5f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/deprecated_object.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/deprecated_object.dart @@ -37,13 +37,13 @@ class DeprecatedObject { String toString() => 'DeprecatedObject[name=$name]'; Map toJson() { - final _json = {}; - if (name != null) { - _json[r'name'] = name; + final json = {}; + if (this.name != null) { + json[r'name'] = this.name; } else { - _json[r'name'] = null; + json[r'name'] = null; } - return _json; + return json; } /// Returns a new [DeprecatedObject] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart index bad82eff1e..0375767475 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart @@ -47,15 +47,15 @@ class Dog { String toString() => 'Dog[className=$className, color=$color, breed=$breed]'; Map toJson() { - final _json = {}; - _json[r'className'] = className; - _json[r'color'] = color; - if (breed != null) { - _json[r'breed'] = breed; + final json = {}; + json[r'className'] = this.className; + json[r'color'] = this.color; + if (this.breed != null) { + json[r'breed'] = this.breed; } else { - _json[r'breed'] = null; + json[r'breed'] = null; } - return _json; + return json; } /// Returns a new [Dog] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart index fd2aedb5a7..ae05b515cf 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart @@ -37,13 +37,13 @@ class DogAllOf { String toString() => 'DogAllOf[breed=$breed]'; Map toJson() { - final _json = {}; - if (breed != null) { - _json[r'breed'] = breed; + final json = {}; + if (this.breed != null) { + json[r'breed'] = this.breed; } else { - _json[r'breed'] = null; + json[r'breed'] = null; } - return _json; + return json; } /// Returns a new [DogAllOf] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart index 42830ee437..78205e004b 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart @@ -36,14 +36,14 @@ class EnumArrays { String toString() => 'EnumArrays[justSymbol=$justSymbol, arrayEnum=$arrayEnum]'; Map toJson() { - final _json = {}; - if (justSymbol != null) { - _json[r'just_symbol'] = justSymbol; + final json = {}; + if (this.justSymbol != null) { + json[r'just_symbol'] = this.justSymbol; } else { - _json[r'just_symbol'] = null; + json[r'just_symbol'] = null; } - _json[r'array_enum'] = arrayEnum; - return _json; + json[r'array_enum'] = this.arrayEnum; + return json; } /// Returns a new [EnumArrays] instance and imports its values from @@ -176,7 +176,7 @@ class EnumArraysJustSymbolEnumTypeTransformer { /// and users are still using an old app with the old code. EnumArraysJustSymbolEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'>=': return EnumArraysJustSymbolEnum.greaterThanEqual; case r'$': return EnumArraysJustSymbolEnum.dollar; default: @@ -250,7 +250,7 @@ class EnumArraysArrayEnumEnumTypeTransformer { /// and users are still using an old app with the old code. EnumArraysArrayEnumEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'fish': return EnumArraysArrayEnumEnum.fish; case r'crab': return EnumArraysArrayEnumEnum.crab; default: diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_class.dart index ad0fee1948..eac54fb357 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_class.dart @@ -69,7 +69,7 @@ class EnumClassTypeTransformer { /// and users are still using an old app with the old code. EnumClass? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'_abc': return EnumClass.abc; case r'-efg': return EnumClass.efg; case r'(xyz)': return EnumClass.leftParenthesisXyzRightParenthesis; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart index d947a241e5..a51d323672 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart @@ -84,44 +84,44 @@ class EnumTest { String toString() => 'EnumTest[enumString=$enumString, enumStringRequired=$enumStringRequired, enumInteger=$enumInteger, enumNumber=$enumNumber, outerEnum=$outerEnum, outerEnumInteger=$outerEnumInteger, outerEnumDefaultValue=$outerEnumDefaultValue, outerEnumIntegerDefaultValue=$outerEnumIntegerDefaultValue]'; Map toJson() { - final _json = {}; - if (enumString != null) { - _json[r'enum_string'] = enumString; + final json = {}; + if (this.enumString != null) { + json[r'enum_string'] = this.enumString; } else { - _json[r'enum_string'] = null; + json[r'enum_string'] = null; } - _json[r'enum_string_required'] = enumStringRequired; - if (enumInteger != null) { - _json[r'enum_integer'] = enumInteger; + json[r'enum_string_required'] = this.enumStringRequired; + if (this.enumInteger != null) { + json[r'enum_integer'] = this.enumInteger; } else { - _json[r'enum_integer'] = null; + json[r'enum_integer'] = null; } - if (enumNumber != null) { - _json[r'enum_number'] = enumNumber; + if (this.enumNumber != null) { + json[r'enum_number'] = this.enumNumber; } else { - _json[r'enum_number'] = null; + json[r'enum_number'] = null; } - if (outerEnum != null) { - _json[r'outerEnum'] = outerEnum; + if (this.outerEnum != null) { + json[r'outerEnum'] = this.outerEnum; } else { - _json[r'outerEnum'] = null; + json[r'outerEnum'] = null; } - if (outerEnumInteger != null) { - _json[r'outerEnumInteger'] = outerEnumInteger; + if (this.outerEnumInteger != null) { + json[r'outerEnumInteger'] = this.outerEnumInteger; } else { - _json[r'outerEnumInteger'] = null; + json[r'outerEnumInteger'] = null; } - if (outerEnumDefaultValue != null) { - _json[r'outerEnumDefaultValue'] = outerEnumDefaultValue; + if (this.outerEnumDefaultValue != null) { + json[r'outerEnumDefaultValue'] = this.outerEnumDefaultValue; } else { - _json[r'outerEnumDefaultValue'] = null; + json[r'outerEnumDefaultValue'] = null; } - if (outerEnumIntegerDefaultValue != null) { - _json[r'outerEnumIntegerDefaultValue'] = outerEnumIntegerDefaultValue; + if (this.outerEnumIntegerDefaultValue != null) { + json[r'outerEnumIntegerDefaultValue'] = this.outerEnumIntegerDefaultValue; } else { - _json[r'outerEnumIntegerDefaultValue'] = null; + json[r'outerEnumIntegerDefaultValue'] = null; } - return _json; + return json; } /// Returns a new [EnumTest] instance and imports its values from @@ -263,7 +263,7 @@ class EnumTestEnumStringEnumTypeTransformer { /// and users are still using an old app with the old code. EnumTestEnumStringEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'UPPER': return EnumTestEnumStringEnum.UPPER; case r'lower': return EnumTestEnumStringEnum.lower; case r'': return EnumTestEnumStringEnum.empty; @@ -340,7 +340,7 @@ class EnumTestEnumStringRequiredEnumTypeTransformer { /// and users are still using an old app with the old code. EnumTestEnumStringRequiredEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'UPPER': return EnumTestEnumStringRequiredEnum.UPPER; case r'lower': return EnumTestEnumStringRequiredEnum.lower; case r'': return EnumTestEnumStringRequiredEnum.empty; @@ -415,7 +415,7 @@ class EnumTestEnumIntegerEnumTypeTransformer { /// and users are still using an old app with the old code. EnumTestEnumIntegerEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case 1: return EnumTestEnumIntegerEnum.number1; case -1: return EnumTestEnumIntegerEnum.numberNegative1; default: @@ -489,7 +489,7 @@ class EnumTestEnumNumberEnumTypeTransformer { /// and users are still using an old app with the old code. EnumTestEnumNumberEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case '1.1': return EnumTestEnumNumberEnum.number1Period1; case '-1.2': return EnumTestEnumNumberEnum.numberNegative1Period2; default: diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart index 57332cfe38..8fe78c1a8f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart @@ -42,14 +42,14 @@ class FileSchemaTestClass { String toString() => 'FileSchemaTestClass[file=$file, files=$files]'; Map toJson() { - final _json = {}; - if (file != null) { - _json[r'file'] = file; + final json = {}; + if (this.file != null) { + json[r'file'] = this.file; } else { - _json[r'file'] = null; + json[r'file'] = null; } - _json[r'files'] = files; - return _json; + json[r'files'] = this.files; + return json; } /// Returns a new [FileSchemaTestClass] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart index d788ffcc5b..758f13c778 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart @@ -31,9 +31,9 @@ class Foo { String toString() => 'Foo[bar=$bar]'; Map toJson() { - final _json = {}; - _json[r'bar'] = bar; - return _json; + final json = {}; + json[r'bar'] = this.bar; + return json; } /// Returns a new [Foo] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo_get_default_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo_get_default_response.dart index e240869104..dcdcf7220a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo_get_default_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo_get_default_response.dart @@ -37,13 +37,13 @@ class FooGetDefaultResponse { String toString() => 'FooGetDefaultResponse[string=$string]'; Map toJson() { - final _json = {}; - if (string != null) { - _json[r'string'] = string; + final json = {}; + if (this.string != null) { + json[r'string'] = this.string; } else { - _json[r'string'] = null; + json[r'string'] = null; } - return _json; + return json; } /// Returns a new [FooGetDefaultResponse] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart index 20bf557aa8..9a184cb391 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart @@ -190,72 +190,72 @@ class FormatTest { String toString() => 'FormatTest[integer=$integer, int32=$int32, int64=$int64, number=$number, float=$float, double_=$double_, decimal=$decimal, string=$string, byte=$byte, binary=$binary, date=$date, dateTime=$dateTime, uuid=$uuid, password=$password, patternWithDigits=$patternWithDigits, patternWithDigitsAndDelimiter=$patternWithDigitsAndDelimiter]'; Map toJson() { - final _json = {}; - if (integer != null) { - _json[r'integer'] = integer; + final json = {}; + if (this.integer != null) { + json[r'integer'] = this.integer; } else { - _json[r'integer'] = null; + json[r'integer'] = null; } - if (int32 != null) { - _json[r'int32'] = int32; + if (this.int32 != null) { + json[r'int32'] = this.int32; } else { - _json[r'int32'] = null; + json[r'int32'] = null; } - if (int64 != null) { - _json[r'int64'] = int64; + if (this.int64 != null) { + json[r'int64'] = this.int64; } else { - _json[r'int64'] = null; + json[r'int64'] = null; } - _json[r'number'] = number; - if (float != null) { - _json[r'float'] = float; + json[r'number'] = this.number; + if (this.float != null) { + json[r'float'] = this.float; } else { - _json[r'float'] = null; + json[r'float'] = null; } - if (double_ != null) { - _json[r'double'] = double_; + if (this.double_ != null) { + json[r'double'] = this.double_; } else { - _json[r'double'] = null; + json[r'double'] = null; } - if (decimal != null) { - _json[r'decimal'] = decimal; + if (this.decimal != null) { + json[r'decimal'] = this.decimal; } else { - _json[r'decimal'] = null; + json[r'decimal'] = null; } - if (string != null) { - _json[r'string'] = string; + if (this.string != null) { + json[r'string'] = this.string; } else { - _json[r'string'] = null; + json[r'string'] = null; } - _json[r'byte'] = byte; - if (binary != null) { - _json[r'binary'] = binary; + json[r'byte'] = this.byte; + if (this.binary != null) { + json[r'binary'] = this.binary; } else { - _json[r'binary'] = null; + json[r'binary'] = null; } - _json[r'date'] = _dateFormatter.format(date.toUtc()); - if (dateTime != null) { - _json[r'dateTime'] = dateTime!.toUtc().toIso8601String(); + json[r'date'] = _dateFormatter.format(this.date.toUtc()); + if (this.dateTime != null) { + json[r'dateTime'] = this.dateTime!.toUtc().toIso8601String(); } else { - _json[r'dateTime'] = null; + json[r'dateTime'] = null; } - if (uuid != null) { - _json[r'uuid'] = uuid; + if (this.uuid != null) { + json[r'uuid'] = this.uuid; } else { - _json[r'uuid'] = null; + json[r'uuid'] = null; } - _json[r'password'] = password; - if (patternWithDigits != null) { - _json[r'pattern_with_digits'] = patternWithDigits; + json[r'password'] = this.password; + if (this.patternWithDigits != null) { + json[r'pattern_with_digits'] = this.patternWithDigits; } else { - _json[r'pattern_with_digits'] = null; + json[r'pattern_with_digits'] = null; } - if (patternWithDigitsAndDelimiter != null) { - _json[r'pattern_with_digits_and_delimiter'] = patternWithDigitsAndDelimiter; + if (this.patternWithDigitsAndDelimiter != null) { + json[r'pattern_with_digits_and_delimiter'] = this.patternWithDigitsAndDelimiter; } else { - _json[r'pattern_with_digits_and_delimiter'] = null; + json[r'pattern_with_digits_and_delimiter'] = null; } - return _json; + return json; } /// Returns a new [FormatTest] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart index cdbc81b89b..0950c83518 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart @@ -48,18 +48,18 @@ class HasOnlyReadOnly { String toString() => 'HasOnlyReadOnly[bar=$bar, foo=$foo]'; Map toJson() { - final _json = {}; - if (bar != null) { - _json[r'bar'] = bar; + final json = {}; + if (this.bar != null) { + json[r'bar'] = this.bar; } else { - _json[r'bar'] = null; + json[r'bar'] = null; } - if (foo != null) { - _json[r'foo'] = foo; + if (this.foo != null) { + json[r'foo'] = this.foo; } else { - _json[r'foo'] = null; + json[r'foo'] = null; } - return _json; + return json; } /// Returns a new [HasOnlyReadOnly] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart index 05da330f66..4d00753933 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart @@ -31,13 +31,13 @@ class HealthCheckResult { String toString() => 'HealthCheckResult[nullableMessage=$nullableMessage]'; Map toJson() { - final _json = {}; - if (nullableMessage != null) { - _json[r'NullableMessage'] = nullableMessage; + final json = {}; + if (this.nullableMessage != null) { + json[r'NullableMessage'] = this.nullableMessage; } else { - _json[r'NullableMessage'] = null; + json[r'NullableMessage'] = null; } - return _json; + return json; } /// Returns a new [HealthCheckResult] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart index b544dc8c6f..8c6c143bb7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart @@ -46,12 +46,12 @@ class MapTest { String toString() => 'MapTest[mapMapOfString=$mapMapOfString, mapOfEnumString=$mapOfEnumString, directMap=$directMap, indirectMap=$indirectMap]'; Map toJson() { - final _json = {}; - _json[r'map_map_of_string'] = mapMapOfString; - _json[r'map_of_enum_string'] = mapOfEnumString; - _json[r'direct_map'] = directMap; - _json[r'indirect_map'] = indirectMap; - return _json; + final json = {}; + json[r'map_map_of_string'] = this.mapMapOfString; + json[r'map_of_enum_string'] = this.mapOfEnumString; + json[r'direct_map'] = this.directMap; + json[r'indirect_map'] = this.indirectMap; + return json; } /// Returns a new [MapTest] instance and imports its values from @@ -186,7 +186,7 @@ class MapTestMapOfEnumStringEnumTypeTransformer { /// and users are still using an old app with the old code. MapTestMapOfEnumStringEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'UPPER': return MapTestMapOfEnumStringEnum.UPPER; case r'lower': return MapTestMapOfEnumStringEnum.lower; default: diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart index 268c7b3e72..2e938ae194 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart @@ -53,19 +53,19 @@ class MixedPropertiesAndAdditionalPropertiesClass { String toString() => 'MixedPropertiesAndAdditionalPropertiesClass[uuid=$uuid, dateTime=$dateTime, map=$map]'; Map toJson() { - final _json = {}; - if (uuid != null) { - _json[r'uuid'] = uuid; + final json = {}; + if (this.uuid != null) { + json[r'uuid'] = this.uuid; } else { - _json[r'uuid'] = null; + json[r'uuid'] = null; } - if (dateTime != null) { - _json[r'dateTime'] = dateTime!.toUtc().toIso8601String(); + if (this.dateTime != null) { + json[r'dateTime'] = this.dateTime!.toUtc().toIso8601String(); } else { - _json[r'dateTime'] = null; + json[r'dateTime'] = null; } - _json[r'map'] = map; - return _json; + json[r'map'] = this.map; + return json; } /// Returns a new [MixedPropertiesAndAdditionalPropertiesClass] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart index ab3afaa2bc..1019d663db 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart @@ -48,18 +48,18 @@ class Model200Response { String toString() => 'Model200Response[name=$name, class_=$class_]'; Map toJson() { - final _json = {}; - if (name != null) { - _json[r'name'] = name; + final json = {}; + if (this.name != null) { + json[r'name'] = this.name; } else { - _json[r'name'] = null; + json[r'name'] = null; } - if (class_ != null) { - _json[r'class'] = class_; + if (this.class_ != null) { + json[r'class'] = this.class_; } else { - _json[r'class'] = null; + json[r'class'] = null; } - return _json; + return json; } /// Returns a new [Model200Response] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart index e5602b1733..aaf943cfc0 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart @@ -37,13 +37,13 @@ class ModelClient { String toString() => 'ModelClient[client=$client]'; Map toJson() { - final _json = {}; - if (client != null) { - _json[r'client'] = client; + final json = {}; + if (this.client != null) { + json[r'client'] = this.client; } else { - _json[r'client'] = null; + json[r'client'] = null; } - return _json; + return json; } /// Returns a new [ModelClient] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart index a5c0a44feb..1d9ea9ddde 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart @@ -38,13 +38,13 @@ class ModelFile { String toString() => 'ModelFile[sourceURI=$sourceURI]'; Map toJson() { - final _json = {}; - if (sourceURI != null) { - _json[r'sourceURI'] = sourceURI; + final json = {}; + if (this.sourceURI != null) { + json[r'sourceURI'] = this.sourceURI; } else { - _json[r'sourceURI'] = null; + json[r'sourceURI'] = null; } - return _json; + return json; } /// Returns a new [ModelFile] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart index 1b0780f7c6..4883a04905 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart @@ -37,13 +37,13 @@ class ModelList { String toString() => 'ModelList[n123list=$n123list]'; Map toJson() { - final _json = {}; - if (n123list != null) { - _json[r'123-list'] = n123list; + final json = {}; + if (this.n123list != null) { + json[r'123-list'] = this.n123list; } else { - _json[r'123-list'] = null; + json[r'123-list'] = null; } - return _json; + return json; } /// Returns a new [ModelList] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart index 5b4bfe2703..faf127da4b 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart @@ -37,13 +37,13 @@ class ModelReturn { String toString() => 'ModelReturn[return_=$return_]'; Map toJson() { - final _json = {}; - if (return_ != null) { - _json[r'return'] = return_; + final json = {}; + if (this.return_ != null) { + json[r'return'] = this.return_; } else { - _json[r'return'] = null; + json[r'return'] = null; } - return _json; + return json; } /// Returns a new [ModelReturn] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart index 79e3220d0a..e41090c54c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart @@ -64,24 +64,24 @@ class Name { String toString() => 'Name[name=$name, snakeCase=$snakeCase, property=$property, n123number=$n123number]'; Map toJson() { - final _json = {}; - _json[r'name'] = name; - if (snakeCase != null) { - _json[r'snake_case'] = snakeCase; + final json = {}; + json[r'name'] = this.name; + if (this.snakeCase != null) { + json[r'snake_case'] = this.snakeCase; } else { - _json[r'snake_case'] = null; + json[r'snake_case'] = null; } - if (property != null) { - _json[r'property'] = property; + if (this.property != null) { + json[r'property'] = this.property; } else { - _json[r'property'] = null; + json[r'property'] = null; } - if (n123number != null) { - _json[r'123Number'] = n123number; + if (this.n123number != null) { + json[r'123Number'] = this.n123number; } else { - _json[r'123Number'] = null; + json[r'123Number'] = null; } - return _json; + return json; } /// Returns a new [Name] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart index 36133b3142..631f60ab09 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart @@ -86,60 +86,60 @@ class NullableClass { String toString() => 'NullableClass[integerProp=$integerProp, numberProp=$numberProp, booleanProp=$booleanProp, stringProp=$stringProp, dateProp=$dateProp, datetimeProp=$datetimeProp, arrayNullableProp=$arrayNullableProp, arrayAndItemsNullableProp=$arrayAndItemsNullableProp, arrayItemsNullable=$arrayItemsNullable, objectNullableProp=$objectNullableProp, objectAndItemsNullableProp=$objectAndItemsNullableProp, objectItemsNullable=$objectItemsNullable]'; Map toJson() { - final _json = {}; - if (integerProp != null) { - _json[r'integer_prop'] = integerProp; + final json = {}; + if (this.integerProp != null) { + json[r'integer_prop'] = this.integerProp; } else { - _json[r'integer_prop'] = null; + json[r'integer_prop'] = null; } - if (numberProp != null) { - _json[r'number_prop'] = numberProp; + if (this.numberProp != null) { + json[r'number_prop'] = this.numberProp; } else { - _json[r'number_prop'] = null; + json[r'number_prop'] = null; } - if (booleanProp != null) { - _json[r'boolean_prop'] = booleanProp; + if (this.booleanProp != null) { + json[r'boolean_prop'] = this.booleanProp; } else { - _json[r'boolean_prop'] = null; + json[r'boolean_prop'] = null; } - if (stringProp != null) { - _json[r'string_prop'] = stringProp; + if (this.stringProp != null) { + json[r'string_prop'] = this.stringProp; } else { - _json[r'string_prop'] = null; + json[r'string_prop'] = null; } - if (dateProp != null) { - _json[r'date_prop'] = _dateFormatter.format(dateProp!.toUtc()); + if (this.dateProp != null) { + json[r'date_prop'] = _dateFormatter.format(this.dateProp!.toUtc()); } else { - _json[r'date_prop'] = null; + json[r'date_prop'] = null; } - if (datetimeProp != null) { - _json[r'datetime_prop'] = datetimeProp!.toUtc().toIso8601String(); + if (this.datetimeProp != null) { + json[r'datetime_prop'] = this.datetimeProp!.toUtc().toIso8601String(); } else { - _json[r'datetime_prop'] = null; + json[r'datetime_prop'] = null; } - if (arrayNullableProp != null) { - _json[r'array_nullable_prop'] = arrayNullableProp; + if (this.arrayNullableProp != null) { + json[r'array_nullable_prop'] = this.arrayNullableProp; } else { - _json[r'array_nullable_prop'] = null; + json[r'array_nullable_prop'] = null; } - if (arrayAndItemsNullableProp != null) { - _json[r'array_and_items_nullable_prop'] = arrayAndItemsNullableProp; + if (this.arrayAndItemsNullableProp != null) { + json[r'array_and_items_nullable_prop'] = this.arrayAndItemsNullableProp; } else { - _json[r'array_and_items_nullable_prop'] = null; + json[r'array_and_items_nullable_prop'] = null; } - _json[r'array_items_nullable'] = arrayItemsNullable; - if (objectNullableProp != null) { - _json[r'object_nullable_prop'] = objectNullableProp; + json[r'array_items_nullable'] = this.arrayItemsNullable; + if (this.objectNullableProp != null) { + json[r'object_nullable_prop'] = this.objectNullableProp; } else { - _json[r'object_nullable_prop'] = null; + json[r'object_nullable_prop'] = null; } - if (objectAndItemsNullableProp != null) { - _json[r'object_and_items_nullable_prop'] = objectAndItemsNullableProp; + if (this.objectAndItemsNullableProp != null) { + json[r'object_and_items_nullable_prop'] = this.objectAndItemsNullableProp; } else { - _json[r'object_and_items_nullable_prop'] = null; + json[r'object_and_items_nullable_prop'] = null; } - _json[r'object_items_nullable'] = objectItemsNullable; - return _json; + json[r'object_items_nullable'] = this.objectItemsNullable; + return json; } /// Returns a new [NullableClass] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart index 3fce2c7850..387397e6e4 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart @@ -37,13 +37,13 @@ class NumberOnly { String toString() => 'NumberOnly[justNumber=$justNumber]'; Map toJson() { - final _json = {}; - if (justNumber != null) { - _json[r'JustNumber'] = justNumber; + final json = {}; + if (this.justNumber != null) { + json[r'JustNumber'] = this.justNumber; } else { - _json[r'JustNumber'] = null; + json[r'JustNumber'] = null; } - return _json; + return json; } /// Returns a new [NumberOnly] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/object_with_deprecated_fields.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/object_with_deprecated_fields.dart index 6c67afbbdd..36b0fee3d7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/object_with_deprecated_fields.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/object_with_deprecated_fields.dart @@ -64,24 +64,24 @@ class ObjectWithDeprecatedFields { String toString() => 'ObjectWithDeprecatedFields[uuid=$uuid, id=$id, deprecatedRef=$deprecatedRef, bars=$bars]'; Map toJson() { - final _json = {}; - if (uuid != null) { - _json[r'uuid'] = uuid; + final json = {}; + if (this.uuid != null) { + json[r'uuid'] = this.uuid; } else { - _json[r'uuid'] = null; + json[r'uuid'] = null; } - if (id != null) { - _json[r'id'] = id; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (deprecatedRef != null) { - _json[r'deprecatedRef'] = deprecatedRef; + if (this.deprecatedRef != null) { + json[r'deprecatedRef'] = this.deprecatedRef; } else { - _json[r'deprecatedRef'] = null; + json[r'deprecatedRef'] = null; } - _json[r'bars'] = bars; - return _json; + json[r'bars'] = this.bars; + return json; } /// Returns a new [ObjectWithDeprecatedFields] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart index 27db5fd318..d317b6b411 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart @@ -81,34 +81,34 @@ class Order { String toString() => 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (petId != null) { - _json[r'petId'] = petId; + if (this.petId != null) { + json[r'petId'] = this.petId; } else { - _json[r'petId'] = null; + json[r'petId'] = null; } - if (quantity != null) { - _json[r'quantity'] = quantity; + if (this.quantity != null) { + json[r'quantity'] = this.quantity; } else { - _json[r'quantity'] = null; + json[r'quantity'] = null; } - if (shipDate != null) { - _json[r'shipDate'] = shipDate!.toUtc().toIso8601String(); + if (this.shipDate != null) { + json[r'shipDate'] = this.shipDate!.toUtc().toIso8601String(); } else { - _json[r'shipDate'] = null; + json[r'shipDate'] = null; } - if (status != null) { - _json[r'status'] = status; + if (this.status != null) { + json[r'status'] = this.status; } else { - _json[r'status'] = null; + json[r'status'] = null; } - _json[r'complete'] = complete; - return _json; + json[r'complete'] = this.complete; + return json; } /// Returns a new [Order] instance and imports its values from @@ -247,7 +247,7 @@ class OrderStatusEnumTypeTransformer { /// and users are still using an old app with the old code. OrderStatusEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'placed': return OrderStatusEnum.placed; case r'approved': return OrderStatusEnum.approved; case r'delivered': return OrderStatusEnum.delivered; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart index f31cf4b0a3..6898564d6f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart @@ -59,23 +59,23 @@ class OuterComposite { String toString() => 'OuterComposite[myNumber=$myNumber, myString=$myString, myBoolean=$myBoolean]'; Map toJson() { - final _json = {}; - if (myNumber != null) { - _json[r'my_number'] = myNumber; + final json = {}; + if (this.myNumber != null) { + json[r'my_number'] = this.myNumber; } else { - _json[r'my_number'] = null; + json[r'my_number'] = null; } - if (myString != null) { - _json[r'my_string'] = myString; + if (this.myString != null) { + json[r'my_string'] = this.myString; } else { - _json[r'my_string'] = null; + json[r'my_string'] = null; } - if (myBoolean != null) { - _json[r'my_boolean'] = myBoolean; + if (this.myBoolean != null) { + json[r'my_boolean'] = this.myBoolean; } else { - _json[r'my_boolean'] = null; + json[r'my_boolean'] = null; } - return _json; + return json; } /// Returns a new [OuterComposite] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum.dart index 79990cc426..9b4da61506 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum.dart @@ -69,7 +69,7 @@ class OuterEnumTypeTransformer { /// and users are still using an old app with the old code. OuterEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'placed': return OuterEnum.placed; case r'approved': return OuterEnum.approved; case r'delivered': return OuterEnum.delivered; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart index 710bffc01d..7b6061f493 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_default_value.dart @@ -69,7 +69,7 @@ class OuterEnumDefaultValueTypeTransformer { /// and users are still using an old app with the old code. OuterEnumDefaultValue? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'placed': return OuterEnumDefaultValue.placed; case r'approved': return OuterEnumDefaultValue.approved; case r'delivered': return OuterEnumDefaultValue.delivered; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer.dart index 7d0f2e371b..eebb241e55 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer.dart @@ -69,7 +69,7 @@ class OuterEnumIntegerTypeTransformer { /// and users are still using an old app with the old code. OuterEnumInteger? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case 0: return OuterEnumInteger.number0; case 1: return OuterEnumInteger.number1; case 2: return OuterEnumInteger.number2; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart index f82ae23497..f1b26dedd8 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_enum_integer_default_value.dart @@ -69,7 +69,7 @@ class OuterEnumIntegerDefaultValueTypeTransformer { /// and users are still using an old app with the old code. OuterEnumIntegerDefaultValue? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case 0: return OuterEnumIntegerDefaultValue.number0; case 1: return OuterEnumIntegerDefaultValue.number1; case 2: return OuterEnumIntegerDefaultValue.number2; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart index bb346014c7..04177475ea 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart @@ -31,9 +31,9 @@ class OuterObjectWithEnumProperty { String toString() => 'OuterObjectWithEnumProperty[value=$value]'; Map toJson() { - final _json = {}; - _json[r'value'] = value; - return _json; + final json = {}; + json[r'value'] = this.value; + return json; } /// Returns a new [OuterObjectWithEnumProperty] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart index 5944a349b9..a00ec5e394 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart @@ -69,26 +69,26 @@ class Pet { String toString() => 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (category != null) { - _json[r'category'] = category; + if (this.category != null) { + json[r'category'] = this.category; } else { - _json[r'category'] = null; + json[r'category'] = null; } - _json[r'name'] = name; - _json[r'photoUrls'] = photoUrls; - _json[r'tags'] = tags; - if (status != null) { - _json[r'status'] = status; + json[r'name'] = this.name; + json[r'photoUrls'] = this.photoUrls; + json[r'tags'] = this.tags; + if (this.status != null) { + json[r'status'] = this.status; } else { - _json[r'status'] = null; + json[r'status'] = null; } - return _json; + return json; } /// Returns a new [Pet] instance and imports its values from @@ -231,7 +231,7 @@ class PetStatusEnumTypeTransformer { /// and users are still using an old app with the old code. PetStatusEnum? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'available': return PetStatusEnum.available; case r'pending': return PetStatusEnum.pending; case r'sold': return PetStatusEnum.sold; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart index 4701b8c575..3599aff10a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart @@ -48,18 +48,18 @@ class ReadOnlyFirst { String toString() => 'ReadOnlyFirst[bar=$bar, baz=$baz]'; Map toJson() { - final _json = {}; - if (bar != null) { - _json[r'bar'] = bar; + final json = {}; + if (this.bar != null) { + json[r'bar'] = this.bar; } else { - _json[r'bar'] = null; + json[r'bar'] = null; } - if (baz != null) { - _json[r'baz'] = baz; + if (this.baz != null) { + json[r'baz'] = this.baz; } else { - _json[r'baz'] = null; + json[r'baz'] = null; } - return _json; + return json; } /// Returns a new [ReadOnlyFirst] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/single_ref_type.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/single_ref_type.dart index 66809ed402..a4f17af4d5 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/single_ref_type.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/single_ref_type.dart @@ -67,7 +67,7 @@ class SingleRefTypeTypeTransformer { /// and users are still using an old app with the old code. SingleRefType? decode(dynamic data, {bool allowNull = true}) { if (data != null) { - switch (data.toString()) { + switch (data) { case r'admin': return SingleRefType.admin; case r'user': return SingleRefType.user; default: diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart index 869667d125..f92b8d67d7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart @@ -37,13 +37,13 @@ class SpecialModelName { String toString() => 'SpecialModelName[dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket=$dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket]'; Map toJson() { - final _json = {}; - if (dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket != null) { - _json[r'$special[property.name]'] = dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket; + final json = {}; + if (this.dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket != null) { + json[r'$special[property.name]'] = this.dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket; } else { - _json[r'$special[property.name]'] = null; + json[r'$special[property.name]'] = null; } - return _json; + return json; } /// Returns a new [SpecialModelName] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart index 18e86440a1..1fd6d01f16 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart @@ -48,18 +48,18 @@ class Tag { String toString() => 'Tag[id=$id, name=$name]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (name != null) { - _json[r'name'] = name; + if (this.name != null) { + json[r'name'] = this.name; } else { - _json[r'name'] = null; + json[r'name'] = null; } - return _json; + return json; } /// Returns a new [Tag] instance and imports its values from diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart index 4d3d14508c..63fc8e5281 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart @@ -115,48 +115,48 @@ class User { String toString() => 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus]'; Map toJson() { - final _json = {}; - if (id != null) { - _json[r'id'] = id; + final json = {}; + if (this.id != null) { + json[r'id'] = this.id; } else { - _json[r'id'] = null; + json[r'id'] = null; } - if (username != null) { - _json[r'username'] = username; + if (this.username != null) { + json[r'username'] = this.username; } else { - _json[r'username'] = null; + json[r'username'] = null; } - if (firstName != null) { - _json[r'firstName'] = firstName; + if (this.firstName != null) { + json[r'firstName'] = this.firstName; } else { - _json[r'firstName'] = null; + json[r'firstName'] = null; } - if (lastName != null) { - _json[r'lastName'] = lastName; + if (this.lastName != null) { + json[r'lastName'] = this.lastName; } else { - _json[r'lastName'] = null; + json[r'lastName'] = null; } - if (email != null) { - _json[r'email'] = email; + if (this.email != null) { + json[r'email'] = this.email; } else { - _json[r'email'] = null; + json[r'email'] = null; } - if (password != null) { - _json[r'password'] = password; + if (this.password != null) { + json[r'password'] = this.password; } else { - _json[r'password'] = null; + json[r'password'] = null; } - if (phone != null) { - _json[r'phone'] = phone; + if (this.phone != null) { + json[r'phone'] = this.phone; } else { - _json[r'phone'] = null; + json[r'phone'] = null; } - if (userStatus != null) { - _json[r'userStatus'] = userStatus; + if (this.userStatus != null) { + json[r'userStatus'] = this.userStatus; } else { - _json[r'userStatus'] = null; + json[r'userStatus'] = null; } - return _json; + return json; } /// Returns a new [User] instance and imports its values from diff --git a/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/FILES b/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/FILES index 602bebcdf5..257af3a4dc 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/FILES @@ -31,6 +31,9 @@ docs/Client.md docs/DefaultApi.md docs/Dog.md docs/DogAllOf.md +docs/DuplicatedPropChild.md +docs/DuplicatedPropChildAllOf.md +docs/DuplicatedPropParent.md docs/EnumArrays.md docs/EnumClass.md docs/EnumTest.md @@ -48,6 +51,7 @@ docs/HasOnlyReadOnly.md docs/HealthCheckResult.md docs/List.md docs/Mammal.md +docs/MapOfFileTest.md docs/MapTest.md docs/MixedPropertiesAndAdditionalPropertiesClass.md docs/Model200Response.md @@ -100,6 +104,9 @@ model_class_model.go model_client.go model_dog.go model_dog_all_of.go +model_duplicated_prop_child.go +model_duplicated_prop_child_all_of.go +model_duplicated_prop_parent.go model_enum_arrays.go model_enum_class.go model_enum_test_.go @@ -114,6 +121,7 @@ model_has_only_read_only.go model_health_check_result.go model_list.go model_mammal.go +model_map_of_file_test_.go model_map_test_.go model_mixed_properties_and_additional_properties_class.go model_name.go diff --git a/samples/openapi3/client/petstore/go/go-petstore/README.md b/samples/openapi3/client/petstore/go/go-petstore/README.md index 52c0fcc98d..643757ee60 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/README.md +++ b/samples/openapi3/client/petstore/go/go-petstore/README.md @@ -61,7 +61,7 @@ Each operation can use different server URL defined using `OperationServers` map An operation is uniquely identified by `"{classname}Service.{nickname}"` string. Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. -``` +```golang ctx := context.WithValue(context.Background(), petstore.ContextOperationServerIndices, map[string]int{ "{classname}Service.{nickname}": 2, }) @@ -139,6 +139,9 @@ Class | Method | HTTP request | Description - [Client](docs/Client.md) - [Dog](docs/Dog.md) - [DogAllOf](docs/DogAllOf.md) + - [DuplicatedPropChild](docs/DuplicatedPropChild.md) + - [DuplicatedPropChildAllOf](docs/DuplicatedPropChildAllOf.md) + - [DuplicatedPropParent](docs/DuplicatedPropParent.md) - [EnumArrays](docs/EnumArrays.md) - [EnumClass](docs/EnumClass.md) - [EnumTest](docs/EnumTest.md) @@ -154,6 +157,7 @@ Class | Method | HTTP request | Description - [HealthCheckResult](docs/HealthCheckResult.md) - [List](docs/List.md) - [Mammal](docs/Mammal.md) + - [MapOfFileTest](docs/MapOfFileTest.md) - [MapTest](docs/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) diff --git a/samples/openapi3/client/petstore/go/go-petstore/api/openapi.yaml b/samples/openapi3/client/petstore/go/go-petstore/api/openapi.yaml index e94f609d54..e198da0405 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api/openapi.yaml +++ b/samples/openapi3/client/petstore/go/go-petstore/api/openapi.yaml @@ -667,6 +667,12 @@ paths: responses: "400": description: Someting wrong + "5XX": + content: + applicatino/json: + schema: + $ref: '#/components/schemas/OuterNumber' + description: Someting wrong security: - bearer_test: [] summary: Fake endpoint to test group parameters (optional) @@ -1953,6 +1959,31 @@ components: items: type: string type: array + DuplicatedPropChild: + allOf: + - $ref: '#/components/schemas/DuplicatedPropParent' + - $ref: '#/components/schemas/DuplicatedPropChild_allOf' + DuplicatedPropParent: + description: parent model with duplicated property + discriminator: + propertyName: dup-prop + properties: + dup-prop: + description: A discriminator value + type: string + required: + - dup-prop + type: object + MapOfFileTest: + description: test map of file in a property + properties: + prop_test: + additionalProperties: + format: binary + type: string + description: a property to test map of file + type: object + type: object _foo_get_default_response: example: string: @@ -2101,15 +2132,24 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null NullableAllOf_child: allOf: - $ref: '#/components/schemas/NullableAllOfChild' nullable: true + DuplicatedPropChild_allOf: + properties: + dup-prop: + description: A discriminator value + type: string + type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_fake.go b/samples/openapi3/client/petstore/go/go-petstore/api_fake.go index dcef3ab365..516497d599 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_fake.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_fake.go @@ -1626,7 +1626,7 @@ func (a *FakeApiService) TestGroupParametersExecute(r ApiTestGroupParametersRequ } // to determine the Accept header - localVarHTTPHeaderAccepts := []string{} + localVarHTTPHeaderAccepts := []string{"applicatino/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) @@ -1659,6 +1659,15 @@ func (a *FakeApiService) TestGroupParametersExecute(r ApiTestGroupParametersRequ body: localVarBody, error: localVarHTTPResponse.Status, } + if localVarHTTPResponse.StatusCode >= 500 { + var v float32 + err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarHTTPResponse, newErr + } + newErr.model = v + } return localVarHTTPResponse, newErr } diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/DuplicatedPropChild.md b/samples/openapi3/client/petstore/go/go-petstore/docs/DuplicatedPropChild.md new file mode 100644 index 0000000000..a5a34c7930 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/DuplicatedPropChild.md @@ -0,0 +1,56 @@ +# DuplicatedPropChild + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**DupProp** | Pointer to **string** | A discriminator value | [optional] + +## Methods + +### NewDuplicatedPropChild + +`func NewDuplicatedPropChild() *DuplicatedPropChild` + +NewDuplicatedPropChild instantiates a new DuplicatedPropChild object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewDuplicatedPropChildWithDefaults + +`func NewDuplicatedPropChildWithDefaults() *DuplicatedPropChild` + +NewDuplicatedPropChildWithDefaults instantiates a new DuplicatedPropChild object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetDupProp + +`func (o *DuplicatedPropChild) GetDupProp() string` + +GetDupProp returns the DupProp field if non-nil, zero value otherwise. + +### GetDupPropOk + +`func (o *DuplicatedPropChild) GetDupPropOk() (*string, bool)` + +GetDupPropOk returns a tuple with the DupProp field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetDupProp + +`func (o *DuplicatedPropChild) SetDupProp(v string)` + +SetDupProp sets DupProp field to given value. + +### HasDupProp + +`func (o *DuplicatedPropChild) HasDupProp() bool` + +HasDupProp returns a boolean if a field has been set. + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/DuplicatedPropChildAllOf.md b/samples/openapi3/client/petstore/go/go-petstore/docs/DuplicatedPropChildAllOf.md new file mode 100644 index 0000000000..8f5f1c7cd5 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/DuplicatedPropChildAllOf.md @@ -0,0 +1,56 @@ +# DuplicatedPropChildAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**DupProp** | Pointer to **string** | A discriminator value | [optional] + +## Methods + +### NewDuplicatedPropChildAllOf + +`func NewDuplicatedPropChildAllOf() *DuplicatedPropChildAllOf` + +NewDuplicatedPropChildAllOf instantiates a new DuplicatedPropChildAllOf object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewDuplicatedPropChildAllOfWithDefaults + +`func NewDuplicatedPropChildAllOfWithDefaults() *DuplicatedPropChildAllOf` + +NewDuplicatedPropChildAllOfWithDefaults instantiates a new DuplicatedPropChildAllOf object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetDupProp + +`func (o *DuplicatedPropChildAllOf) GetDupProp() string` + +GetDupProp returns the DupProp field if non-nil, zero value otherwise. + +### GetDupPropOk + +`func (o *DuplicatedPropChildAllOf) GetDupPropOk() (*string, bool)` + +GetDupPropOk returns a tuple with the DupProp field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetDupProp + +`func (o *DuplicatedPropChildAllOf) SetDupProp(v string)` + +SetDupProp sets DupProp field to given value. + +### HasDupProp + +`func (o *DuplicatedPropChildAllOf) HasDupProp() bool` + +HasDupProp returns a boolean if a field has been set. + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/DuplicatedPropParent.md b/samples/openapi3/client/petstore/go/go-petstore/docs/DuplicatedPropParent.md new file mode 100644 index 0000000000..93172af629 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/DuplicatedPropParent.md @@ -0,0 +1,51 @@ +# DuplicatedPropParent + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**DupProp** | **string** | A discriminator value | + +## Methods + +### NewDuplicatedPropParent + +`func NewDuplicatedPropParent(dupProp string, ) *DuplicatedPropParent` + +NewDuplicatedPropParent instantiates a new DuplicatedPropParent object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewDuplicatedPropParentWithDefaults + +`func NewDuplicatedPropParentWithDefaults() *DuplicatedPropParent` + +NewDuplicatedPropParentWithDefaults instantiates a new DuplicatedPropParent object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetDupProp + +`func (o *DuplicatedPropParent) GetDupProp() string` + +GetDupProp returns the DupProp field if non-nil, zero value otherwise. + +### GetDupPropOk + +`func (o *DuplicatedPropParent) GetDupPropOk() (*string, bool)` + +GetDupPropOk returns a tuple with the DupProp field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetDupProp + +`func (o *DuplicatedPropParent) SetDupProp(v string)` + +SetDupProp sets DupProp field to given value. + + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/FakeApi.md b/samples/openapi3/client/petstore/go/go-petstore/docs/FakeApi.md index bc168c13b0..b7f7f5b0b1 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/FakeApi.md @@ -775,7 +775,7 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined -- **Accept**: Not defined +- **Accept**: applicatino/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/MapOfFileTest.md b/samples/openapi3/client/petstore/go/go-petstore/docs/MapOfFileTest.md new file mode 100644 index 0000000000..245df44f8d --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/MapOfFileTest.md @@ -0,0 +1,56 @@ +# MapOfFileTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**PropTest** | Pointer to **map[string]*os.File** | a property to test map of file | [optional] + +## Methods + +### NewMapOfFileTest + +`func NewMapOfFileTest() *MapOfFileTest` + +NewMapOfFileTest instantiates a new MapOfFileTest object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewMapOfFileTestWithDefaults + +`func NewMapOfFileTestWithDefaults() *MapOfFileTest` + +NewMapOfFileTestWithDefaults instantiates a new MapOfFileTest object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetPropTest + +`func (o *MapOfFileTest) GetPropTest() map[string]*os.File` + +GetPropTest returns the PropTest field if non-nil, zero value otherwise. + +### GetPropTestOk + +`func (o *MapOfFileTest) GetPropTestOk() (*map[string]*os.File, bool)` + +GetPropTestOk returns a tuple with the PropTest field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetPropTest + +`func (o *MapOfFileTest) SetPropTest(v map[string]*os.File)` + +SetPropTest sets PropTest field to given value. + +### HasPropTest + +`func (o *MapOfFileTest) HasPropTest() bool` + +HasPropTest returns a boolean if a field has been set. + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child.go b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child.go new file mode 100644 index 0000000000..cc199bfc04 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child.go @@ -0,0 +1,190 @@ +/* +OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" + "reflect" + "strings" +) + +// DuplicatedPropChild struct for DuplicatedPropChild +type DuplicatedPropChild struct { + DuplicatedPropParent + // A discriminator value + DupProp *string `json:"dup-prop,omitempty"` + AdditionalProperties map[string]interface{} +} + +type _DuplicatedPropChild DuplicatedPropChild + +// NewDuplicatedPropChild instantiates a new DuplicatedPropChild object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDuplicatedPropChild() *DuplicatedPropChild { + this := DuplicatedPropChild{} + return &this +} + +// NewDuplicatedPropChildWithDefaults instantiates a new DuplicatedPropChild object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDuplicatedPropChildWithDefaults() *DuplicatedPropChild { + this := DuplicatedPropChild{} + return &this +} + +// GetDupProp returns the DupProp field value if set, zero value otherwise. +func (o *DuplicatedPropChild) GetDupProp() string { + if o == nil || o.DupProp == nil { + var ret string + return ret + } + return *o.DupProp +} + +// GetDupPropOk returns a tuple with the DupProp field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DuplicatedPropChild) GetDupPropOk() (*string, bool) { + if o == nil || o.DupProp == nil { + return nil, false + } + return o.DupProp, true +} + +// HasDupProp returns a boolean if a field has been set. +func (o *DuplicatedPropChild) HasDupProp() bool { + if o != nil && o.DupProp != nil { + return true + } + + return false +} + +// SetDupProp gets a reference to the given string and assigns it to the DupProp field. +func (o *DuplicatedPropChild) SetDupProp(v string) { + o.DupProp = &v +} + +func (o DuplicatedPropChild) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + serializedDuplicatedPropParent, errDuplicatedPropParent := json.Marshal(o.DuplicatedPropParent) + if errDuplicatedPropParent != nil { + return []byte{}, errDuplicatedPropParent + } + errDuplicatedPropParent = json.Unmarshal([]byte(serializedDuplicatedPropParent), &toSerialize) + if errDuplicatedPropParent != nil { + return []byte{}, errDuplicatedPropParent + } + if o.DupProp != nil { + toSerialize["dup-prop"] = o.DupProp + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return json.Marshal(toSerialize) +} + +func (o *DuplicatedPropChild) UnmarshalJSON(bytes []byte) (err error) { + type DuplicatedPropChildWithoutEmbeddedStruct struct { + // A discriminator value + DupProp *string `json:"dup-prop,omitempty"` + } + + varDuplicatedPropChildWithoutEmbeddedStruct := DuplicatedPropChildWithoutEmbeddedStruct{} + + err = json.Unmarshal(bytes, &varDuplicatedPropChildWithoutEmbeddedStruct) + if err == nil { + varDuplicatedPropChild := _DuplicatedPropChild{} + varDuplicatedPropChild.DupProp = varDuplicatedPropChildWithoutEmbeddedStruct.DupProp + *o = DuplicatedPropChild(varDuplicatedPropChild) + } else { + return err + } + + varDuplicatedPropChild := _DuplicatedPropChild{} + + err = json.Unmarshal(bytes, &varDuplicatedPropChild) + if err == nil { + o.DuplicatedPropParent = varDuplicatedPropChild.DuplicatedPropParent + } else { + return err + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "dup-prop") + + // remove fields from embedded structs + reflectDuplicatedPropParent := reflect.ValueOf(o.DuplicatedPropParent) + for i := 0; i < reflectDuplicatedPropParent.Type().NumField(); i++ { + t := reflectDuplicatedPropParent.Type().Field(i) + + if jsonTag := t.Tag.Get("json"); jsonTag != "" { + fieldName := "" + if commaIdx := strings.Index(jsonTag, ","); commaIdx > 0 { + fieldName = jsonTag[:commaIdx] + } else { + fieldName = jsonTag + } + if fieldName != "AdditionalProperties" { + delete(additionalProperties, fieldName) + } + } + } + + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullableDuplicatedPropChild struct { + value *DuplicatedPropChild + isSet bool +} + +func (v NullableDuplicatedPropChild) Get() *DuplicatedPropChild { + return v.value +} + +func (v *NullableDuplicatedPropChild) Set(val *DuplicatedPropChild) { + v.value = val + v.isSet = true +} + +func (v NullableDuplicatedPropChild) IsSet() bool { + return v.isSet +} + +func (v *NullableDuplicatedPropChild) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDuplicatedPropChild(val *DuplicatedPropChild) *NullableDuplicatedPropChild { + return &NullableDuplicatedPropChild{value: val, isSet: true} +} + +func (v NullableDuplicatedPropChild) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDuplicatedPropChild) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child_all_of.go b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child_all_of.go new file mode 100644 index 0000000000..ff6387b681 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child_all_of.go @@ -0,0 +1,141 @@ +/* +OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" +) + +// DuplicatedPropChildAllOf struct for DuplicatedPropChildAllOf +type DuplicatedPropChildAllOf struct { + // A discriminator value + DupProp *string `json:"dup-prop,omitempty"` + AdditionalProperties map[string]interface{} +} + +type _DuplicatedPropChildAllOf DuplicatedPropChildAllOf + +// NewDuplicatedPropChildAllOf instantiates a new DuplicatedPropChildAllOf object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDuplicatedPropChildAllOf() *DuplicatedPropChildAllOf { + this := DuplicatedPropChildAllOf{} + return &this +} + +// NewDuplicatedPropChildAllOfWithDefaults instantiates a new DuplicatedPropChildAllOf object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDuplicatedPropChildAllOfWithDefaults() *DuplicatedPropChildAllOf { + this := DuplicatedPropChildAllOf{} + return &this +} + +// GetDupProp returns the DupProp field value if set, zero value otherwise. +func (o *DuplicatedPropChildAllOf) GetDupProp() string { + if o == nil || o.DupProp == nil { + var ret string + return ret + } + return *o.DupProp +} + +// GetDupPropOk returns a tuple with the DupProp field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *DuplicatedPropChildAllOf) GetDupPropOk() (*string, bool) { + if o == nil || o.DupProp == nil { + return nil, false + } + return o.DupProp, true +} + +// HasDupProp returns a boolean if a field has been set. +func (o *DuplicatedPropChildAllOf) HasDupProp() bool { + if o != nil && o.DupProp != nil { + return true + } + + return false +} + +// SetDupProp gets a reference to the given string and assigns it to the DupProp field. +func (o *DuplicatedPropChildAllOf) SetDupProp(v string) { + o.DupProp = &v +} + +func (o DuplicatedPropChildAllOf) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.DupProp != nil { + toSerialize["dup-prop"] = o.DupProp + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return json.Marshal(toSerialize) +} + +func (o *DuplicatedPropChildAllOf) UnmarshalJSON(bytes []byte) (err error) { + varDuplicatedPropChildAllOf := _DuplicatedPropChildAllOf{} + + if err = json.Unmarshal(bytes, &varDuplicatedPropChildAllOf); err == nil { + *o = DuplicatedPropChildAllOf(varDuplicatedPropChildAllOf) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "dup-prop") + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullableDuplicatedPropChildAllOf struct { + value *DuplicatedPropChildAllOf + isSet bool +} + +func (v NullableDuplicatedPropChildAllOf) Get() *DuplicatedPropChildAllOf { + return v.value +} + +func (v *NullableDuplicatedPropChildAllOf) Set(val *DuplicatedPropChildAllOf) { + v.value = val + v.isSet = true +} + +func (v NullableDuplicatedPropChildAllOf) IsSet() bool { + return v.isSet +} + +func (v *NullableDuplicatedPropChildAllOf) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDuplicatedPropChildAllOf(val *DuplicatedPropChildAllOf) *NullableDuplicatedPropChildAllOf { + return &NullableDuplicatedPropChildAllOf{value: val, isSet: true} +} + +func (v NullableDuplicatedPropChildAllOf) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDuplicatedPropChildAllOf) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_parent.go b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_parent.go new file mode 100644 index 0000000000..59f7f32eb7 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_parent.go @@ -0,0 +1,134 @@ +/* +OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" +) + +// DuplicatedPropParent parent model with duplicated property +type DuplicatedPropParent struct { + // A discriminator value + DupProp string `json:"dup-prop"` + AdditionalProperties map[string]interface{} +} + +type _DuplicatedPropParent DuplicatedPropParent + +// NewDuplicatedPropParent instantiates a new DuplicatedPropParent object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewDuplicatedPropParent(dupProp string) *DuplicatedPropParent { + this := DuplicatedPropParent{} + this.DupProp = dupProp + return &this +} + +// NewDuplicatedPropParentWithDefaults instantiates a new DuplicatedPropParent object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewDuplicatedPropParentWithDefaults() *DuplicatedPropParent { + this := DuplicatedPropParent{} + return &this +} + +// GetDupProp returns the DupProp field value +func (o *DuplicatedPropParent) GetDupProp() string { + if o == nil { + var ret string + return ret + } + + return o.DupProp +} + +// GetDupPropOk returns a tuple with the DupProp field value +// and a boolean to check if the value has been set. +func (o *DuplicatedPropParent) GetDupPropOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.DupProp, true +} + +// SetDupProp sets field value +func (o *DuplicatedPropParent) SetDupProp(v string) { + o.DupProp = v +} + +func (o DuplicatedPropParent) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if true { + toSerialize["dup-prop"] = o.DupProp + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return json.Marshal(toSerialize) +} + +func (o *DuplicatedPropParent) UnmarshalJSON(bytes []byte) (err error) { + varDuplicatedPropParent := _DuplicatedPropParent{} + + if err = json.Unmarshal(bytes, &varDuplicatedPropParent); err == nil { + *o = DuplicatedPropParent(varDuplicatedPropParent) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "dup-prop") + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullableDuplicatedPropParent struct { + value *DuplicatedPropParent + isSet bool +} + +func (v NullableDuplicatedPropParent) Get() *DuplicatedPropParent { + return v.value +} + +func (v *NullableDuplicatedPropParent) Set(val *DuplicatedPropParent) { + v.value = val + v.isSet = true +} + +func (v NullableDuplicatedPropParent) IsSet() bool { + return v.isSet +} + +func (v *NullableDuplicatedPropParent) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDuplicatedPropParent(val *DuplicatedPropParent) *NullableDuplicatedPropParent { + return &NullableDuplicatedPropParent{value: val, isSet: true} +} + +func (v NullableDuplicatedPropParent) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDuplicatedPropParent) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_map_of_file_test_.go b/samples/openapi3/client/petstore/go/go-petstore/model_map_of_file_test_.go new file mode 100644 index 0000000000..89690bd72c --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/model_map_of_file_test_.go @@ -0,0 +1,142 @@ +/* +OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" + "os" +) + +// MapOfFileTest test map of file in a property +type MapOfFileTest struct { + // a property to test map of file + PropTest *map[string]*os.File `json:"prop_test,omitempty"` + AdditionalProperties map[string]interface{} +} + +type _MapOfFileTest MapOfFileTest + +// NewMapOfFileTest instantiates a new MapOfFileTest object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewMapOfFileTest() *MapOfFileTest { + this := MapOfFileTest{} + return &this +} + +// NewMapOfFileTestWithDefaults instantiates a new MapOfFileTest object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewMapOfFileTestWithDefaults() *MapOfFileTest { + this := MapOfFileTest{} + return &this +} + +// GetPropTest returns the PropTest field value if set, zero value otherwise. +func (o *MapOfFileTest) GetPropTest() map[string]*os.File { + if o == nil || o.PropTest == nil { + var ret map[string]*os.File + return ret + } + return *o.PropTest +} + +// GetPropTestOk returns a tuple with the PropTest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *MapOfFileTest) GetPropTestOk() (*map[string]*os.File, bool) { + if o == nil || o.PropTest == nil { + return nil, false + } + return o.PropTest, true +} + +// HasPropTest returns a boolean if a field has been set. +func (o *MapOfFileTest) HasPropTest() bool { + if o != nil && o.PropTest != nil { + return true + } + + return false +} + +// SetPropTest gets a reference to the given map[string]*os.File and assigns it to the PropTest field. +func (o *MapOfFileTest) SetPropTest(v map[string]*os.File) { + o.PropTest = &v +} + +func (o MapOfFileTest) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.PropTest != nil { + toSerialize["prop_test"] = o.PropTest + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return json.Marshal(toSerialize) +} + +func (o *MapOfFileTest) UnmarshalJSON(bytes []byte) (err error) { + varMapOfFileTest := _MapOfFileTest{} + + if err = json.Unmarshal(bytes, &varMapOfFileTest); err == nil { + *o = MapOfFileTest(varMapOfFileTest) + } + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + delete(additionalProperties, "prop_test") + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullableMapOfFileTest struct { + value *MapOfFileTest + isSet bool +} + +func (v NullableMapOfFileTest) Get() *MapOfFileTest { + return v.value +} + +func (v *NullableMapOfFileTest) Set(val *MapOfFileTest) { + v.value = val + v.isSet = true +} + +func (v NullableMapOfFileTest) IsSet() bool { + return v.isSet +} + +func (v *NullableMapOfFileTest) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableMapOfFileTest(val *MapOfFileTest) *NullableMapOfFileTest { + return &NullableMapOfFileTest{value: val, isSet: true} +} + +func (v NullableMapOfFileTest) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableMapOfFileTest) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go/go-petstore/test/api_another_fake_test.go b/samples/openapi3/client/petstore/go/go-petstore/test/api_another_fake_test.go new file mode 100644 index 0000000000..bf60a1c855 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/test/api_another_fake_test.go @@ -0,0 +1,37 @@ +/* +OpenAPI Petstore + +Testing AnotherFakeApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_AnotherFakeApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test AnotherFakeApiService Call123TestSpecialTags", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.AnotherFakeApi.Call123TestSpecialTags(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/petstore/go/go-petstore/test/api_default_test.go b/samples/openapi3/client/petstore/go/go-petstore/test/api_default_test.go new file mode 100644 index 0000000000..111a0bd49b --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/test/api_default_test.go @@ -0,0 +1,37 @@ +/* +OpenAPI Petstore + +Testing DefaultApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_DefaultApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test DefaultApiService FooGet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.DefaultApi.FooGet(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/petstore/go/go-petstore/test/api_fake_classname_tags123_test.go b/samples/openapi3/client/petstore/go/go-petstore/test/api_fake_classname_tags123_test.go new file mode 100644 index 0000000000..963e4a42da --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/test/api_fake_classname_tags123_test.go @@ -0,0 +1,37 @@ +/* +OpenAPI Petstore + +Testing FakeClassnameTags123ApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_FakeClassnameTags123ApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test FakeClassnameTags123ApiService TestClassname", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeClassnameTags123Api.TestClassname(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/petstore/go/go-petstore/test/api_fake_test.go b/samples/openapi3/client/petstore/go/go-petstore/test/api_fake_test.go new file mode 100644 index 0000000000..8a5882019b --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/test/api_fake_test.go @@ -0,0 +1,205 @@ +/* +OpenAPI Petstore + +Testing FakeApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_FakeApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test FakeApiService FakeHealthGet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.FakeHealthGet(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService FakeOuterBooleanSerialize", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.FakeOuterBooleanSerialize(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService FakeOuterCompositeSerialize", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.FakeOuterCompositeSerialize(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService FakeOuterNumberSerialize", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.FakeOuterNumberSerialize(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService FakeOuterStringSerialize", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.FakeOuterStringSerialize(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestBodyWithFileSchema", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestBodyWithFileSchema(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestBodyWithQueryParams", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestBodyWithQueryParams(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestClientModel", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestClientModel(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestEndpointParameters", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestEndpointParameters(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestEnumParameters", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestEnumParameters(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestGroupParameters", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestGroupParameters(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestInlineAdditionalProperties", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestInlineAdditionalProperties(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestJsonFormData", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestJsonFormData(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestQueryParameterCollectionFormat", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestQueryParameterCollectionFormat(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test FakeApiService TestUniqueItemsHeaderAndQueryParameterCollectionFormat", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.FakeApi.TestUniqueItemsHeaderAndQueryParameterCollectionFormat(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/petstore/go/go-petstore/test/api_pet_test.go b/samples/openapi3/client/petstore/go/go-petstore/test/api_pet_test.go new file mode 100644 index 0000000000..94d4d0fa7f --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/test/api_pet_test.go @@ -0,0 +1,143 @@ +/* +OpenAPI Petstore + +Testing PetApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_PetApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test PetApiService AddPet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetApi.AddPet(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService DeletePet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.DeletePet(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService FindPetsByStatus", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetApi.FindPetsByStatus(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService FindPetsByTags", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetApi.FindPetsByTags(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService GetPetById", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.GetPetById(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService UpdatePet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetApi.UpdatePet(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService UpdatePetWithForm", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.UpdatePetWithForm(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService UploadFile", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.UploadFile(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test PetApiService UploadFileWithRequiredFile", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var petId int64 + + resp, httpRes, err := apiClient.PetApi.UploadFileWithRequiredFile(context.Background(), petId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/petstore/go/go-petstore/test/api_store_test.go b/samples/openapi3/client/petstore/go/go-petstore/test/api_store_test.go new file mode 100644 index 0000000000..48c1db2eb5 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/test/api_store_test.go @@ -0,0 +1,77 @@ +/* +OpenAPI Petstore + +Testing StoreApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_StoreApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test StoreApiService DeleteOrder", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var orderId string + + resp, httpRes, err := apiClient.StoreApi.DeleteOrder(context.Background(), orderId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test StoreApiService GetInventory", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.StoreApi.GetInventory(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test StoreApiService GetOrderById", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var orderId int64 + + resp, httpRes, err := apiClient.StoreApi.GetOrderById(context.Background(), orderId).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test StoreApiService PlaceOrder", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.StoreApi.PlaceOrder(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/petstore/go/go-petstore/test/api_user_test.go b/samples/openapi3/client/petstore/go/go-petstore/test/api_user_test.go new file mode 100644 index 0000000000..072179b486 --- /dev/null +++ b/samples/openapi3/client/petstore/go/go-petstore/test/api_user_test.go @@ -0,0 +1,127 @@ +/* +OpenAPI Petstore + +Testing UserApiService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "./openapi" +) + +func Test_petstore_UserApiService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test UserApiService CreateUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.CreateUser(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService CreateUsersWithArrayInput", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.CreateUsersWithArrayInput(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService CreateUsersWithListInput", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.CreateUsersWithListInput(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService DeleteUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var username string + + resp, httpRes, err := apiClient.UserApi.DeleteUser(context.Background(), username).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService GetUserByName", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var username string + + resp, httpRes, err := apiClient.UserApi.GetUserByName(context.Background(), username).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService LoginUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.LoginUser(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService LogoutUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.UserApi.LogoutUser(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + + t.Run("Test UserApiService UpdateUser", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + var username string + + resp, httpRes, err := apiClient.UserApi.UpdateUser(context.Background(), username).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/petstore/go/go.mod b/samples/openapi3/client/petstore/go/go.mod index 439761133d..4496dcaf0b 100644 --- a/samples/openapi3/client/petstore/go/go.mod +++ b/samples/openapi3/client/petstore/go/go.mod @@ -5,8 +5,8 @@ go 1.16 replace go-petstore => ./go-petstore require ( - github.com/stretchr/testify v1.7.0 + github.com/stretchr/testify v1.8.0 go-petstore v0.0.0-00010101000000-000000000000 - golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect - golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a + golang.org/x/net v0.0.0-20221004154528-8021a29435af // indirect + golang.org/x/oauth2 v0.0.0-20221006150949-b44042a4b9c1 ) diff --git a/samples/openapi3/client/petstore/go/go.sum b/samples/openapi3/client/petstore/go/go.sum index c8c9afd72f..63916a8bc4 100644 --- a/samples/openapi3/client/petstore/go/go.sum +++ b/samples/openapi3/client/petstore/go/go.sum @@ -13,14 +13,36 @@ cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKV cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= +cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= +cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= +cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= +cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= +cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY= +cloud.google.com/go v0.84.0/go.mod h1:RazrYuxIK6Kb7YrzzhPoLmCVzl7Sup4NrbKPg8KHSUM= +cloud.google.com/go v0.87.0/go.mod h1:TpDYlFy7vuLzZMMZ+B6iRiELaY7z/gJPaqbMx6mlWcY= +cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aDQ= +cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= +cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW4= +cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= +cloud.google.com/go v0.99.0/go.mod h1:w0Xx2nLzqWJPuozYQX+hFfCSI8WioryfRDzkoI/Y2ZA= +cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w99A= +cloud.google.com/go v0.102.0/go.mod h1:oWcCzKlqJ5zgHQt9YsaeTY9KzIvjyy0ArmiBUgpQ+nc= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/compute v0.1.0/go.mod h1:GAesmwr110a34z04OlxYkATPBEfVhkymfTBXtfbBFow= +cloud.google.com/go/compute v1.3.0/go.mod h1:cCZiE1NHEtai4wiufUhW8I8S1JKkAnhnQJWM7YD99wM= +cloud.google.com/go/compute v1.5.0/go.mod h1:9SMHyhJlzhlkJqrPAc839t2BZFTSk6Jdj6mkzQJeu0M= +cloud.google.com/go/compute v1.6.0/go.mod h1:T29tfhtVbq1wvAPo0E3+7vhgmkOYeXjhFvz/FMzPu0s= +cloud.google.com/go/compute v1.6.1/go.mod h1:g85FgpzFvNULZ+S8AYq87axRKuf2Kh7deLqV/jJ3thU= +cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQHHZWZxy9U= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp4bnY= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= @@ -30,21 +52,43 @@ cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0Zeo cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq6kuBTW58Y= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= +github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= @@ -59,6 +103,8 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -73,6 +119,12 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= +github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -83,8 +135,17 @@ github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.1 h1:JFrFEBb2xKufg6XkJsJr+WbKb4FQlURi5RUcBveYu9k= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.2.1/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= @@ -92,12 +153,29 @@ github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.0.0-20220520183353-fd19c99a87aa/go.mod h1:17drOmN3MwGY7t0e+Ei9b45FFGA3fBs3x36SsCg1hq8= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= +github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM= +github.com/googleapis/gax-go/v2 v2.2.0/go.mod h1:as02EH8zWkzwUoLbBaFeQ+arQaj/OthfcblKl4IGNaM= +github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99EXz9pXxye9YM= +github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK9wbMD5+iXC6c= +github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= @@ -109,19 +187,32 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -149,6 +240,8 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -157,6 +250,9 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -184,19 +280,58 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202 h1:VvcQYSHwXgi7W+TpUR6A9g6Up98WAHf3f/ulnJ62IyA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e h1:TsQ7F31D3bUCLeqPT0u+yjp1guoArKaNKmCr22PYgTQ= +golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48 h1:N9Vc/rorQUDes6B9CNdIxAn5jODGj2wzfrei2x4wNj4= +golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.0.0-20220809184613-07c6da5e1ced h1:3dYNDff0VT5xj+mbj2XucFst9WKk6PdGOrb9n+SbIvw= +golang.org/x/net v0.0.0-20220809184613-07c6da5e1ced/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.0.0-20221004154528-8021a29435af h1:wv66FM3rLZGPdxpYL+ApnDe2HzHcTFta3z5nsc13wI4= +golang.org/x/net v0.0.0-20221004154528-8021a29435af/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210323180902-22b0adad7558 h1:D7nTwh4J0i+5mW4Zjzn5omvlr6YBcWywE6KOcatyNxY= golang.org/x/oauth2 v0.0.0-20210323180902-22b0adad7558/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a h1:qfl7ob3DIEs3Ml9oLuPwY2N04gymzAW04WsUQHIClgM= golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220608161450-d0670ef3b1eb/go.mod h1:jaDAt6Dkxork7LmZnYtzbRWj0W47D86a3TGe0YHBvmE= +golang.org/x/oauth2 v0.0.0-20220808172628-8227340efae7 h1:dtndE8FcEta75/4kHF3AbpuWzV6f1LjnLrM4pe2SZrw= +golang.org/x/oauth2 v0.0.0-20220808172628-8227340efae7/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= +golang.org/x/oauth2 v0.0.0-20221006150949-b44042a4b9c1 h1:3VPzK7eqH25j7GYw5w6g/GzNRc0/fYtrxz27z1gD4W0= +golang.org/x/oauth2 v0.0.0-20221006150949-b44042a4b9c1/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -205,6 +340,10 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -230,14 +369,50 @@ golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220502124256-b6088ccd6cba/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -282,11 +457,25 @@ golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= +golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= @@ -303,6 +492,29 @@ google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0M google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= +google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= +google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= +google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= +google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= +google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4= +google.golang.org/api v0.50.0/go.mod h1:4bNT5pAuq5ji4SRZm+5QIkjny9JAyVD/3gaSihNefaw= +google.golang.org/api v0.51.0/go.mod h1:t4HdrdoNgyN5cbEfm7Lum0lcLDLiise1F8qDKX00sOU= +google.golang.org/api v0.54.0/go.mod h1:7C4bFFOvVDGXjfDTAsgGwDgAxRDeQ4X8NvUedIt6z3k= +google.golang.org/api v0.55.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= +google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= +google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdrMgI= +google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I= +google.golang.org/api v0.63.0/go.mod h1:gs4ij2ffTRXwuzzgJl/56BdwJaA194ijkfn++9tDuPo= +google.golang.org/api v0.67.0/go.mod h1:ShHKP8E60yPsKNw/w8w+VYaj9H6buA5UqDp8dhbQZ6g= +google.golang.org/api v0.70.0/go.mod h1:Bs4ZM2HGifEvXwd50TtW70ovgJffJYw2oRCOFU/SkfA= +google.golang.org/api v0.71.0/go.mod h1:4PyU6e6JogV1f9eA4voyrTY2batOLdgZ5qZ5HOCc4j8= +google.golang.org/api v0.74.0/go.mod h1:ZpfMZOVRMywNyvJFeqL9HRWBgAuRfSjJFpe9QtRRyDs= +google.golang.org/api v0.75.0/go.mod h1:pU9QmyHLnzlpar1Mjt4IbapUCy8J+6HD6GeELN69ljA= +google.golang.org/api v0.78.0/go.mod h1:1Sg78yoMLOhlQTeF+ARBoytAcH1NNyyl390YMy6rKmw= +google.golang.org/api v0.80.0/go.mod h1:xY3nI94gbvBrE0J6NHXhxOmW97HG7Khjkku6AFB3Hyg= +google.golang.org/api v0.84.0/go.mod h1:NTsGnUFJMYROtiquksZHBWtHfeMC7iYthki7Eq3pa8o= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -310,6 +522,8 @@ google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6 h1:lMO5rYAqUxkmaj76jAkRUvt5JZgFymx/+Q5Mzfivuhc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -333,12 +547,61 @@ google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfG google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210329143202-679c6ae281ee/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210604141403-392c879c8b08/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210608205507-b6d2f5bf0d7d/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= +google.golang.org/genproto v0.0.0-20210713002101-d411969a0d9a/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210728212813-7823e685a01f/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210813162853-db860fec028c/go.mod h1:cFeNkxwySK631ADgubI+/XFU/xp8FD5KIVV4rj8UC5w= +google.golang.org/genproto v0.0.0-20210821163610-241b8fcbd6c8/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210831024726-fe130286e0e2/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210903162649-d08c68adba83/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210909211513-a8c4777a87af/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210924002016-3dee208752a0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211221195035-429b39de9b1c/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220126215142-9970aeb2e350/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220207164111-0872dc986b00/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220218161850-94dd64e39d7c/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220222213610-43724f9ea8cf/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220304144024-325a89244dc8/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220310185008-1973136f34c6/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220324131243-acbaeb5b85eb/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= +google.golang.org/genproto v0.0.0-20220407144326-9054f6ed7bac/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220413183235-5e96e2839df9/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220421151946-72621c1f0bd3/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220429170224-98d788798c3e/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220505152158-f39f71e6c8f3/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220518221133-4f43b3371335/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220523171625-347a074981d8/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220608133413-ed9918b62aac/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220616135557-88e70c0c3a90/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -351,6 +614,26 @@ google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKa google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= +google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc v1.40.1/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc v1.44.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= +google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.46.2/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.47.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -362,13 +645,21 @@ google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpAD google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/api/openapi.yaml b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/api/openapi.yaml index a74ced4404..369e485b55 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/api/openapi.yaml +++ b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/api/openapi.yaml @@ -48,9 +48,11 @@ components: prop1: type: string type: object + example: null MySchemaName___Characters_allOf: properties: prop2: type: string type: object + example: null diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml b/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml index 1db8f0a9d1..bd4e3fa22b 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml +++ b/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml @@ -2286,11 +2286,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null ChildCat_allOf: properties: name: @@ -2302,6 +2304,7 @@ components: type: string x-enum-as-string: true type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/openapi3/client/petstore/java/native/.openapi-generator/FILES b/samples/openapi3/client/petstore/java/native/.openapi-generator/FILES deleted file mode 100644 index a63acd8dcc..0000000000 --- a/samples/openapi3/client/petstore/java/native/.openapi-generator/FILES +++ /dev/null @@ -1,187 +0,0 @@ -.gitignore -.travis.yml -README.md -api/openapi.yaml -build.gradle -build.sbt -docs/AdditionalPropertiesClass.md -docs/Animal.md -docs/AnotherFakeApi.md -docs/Apple.md -docs/AppleReq.md -docs/ArrayOfArrayOfNumberOnly.md -docs/ArrayOfNumberOnly.md -docs/ArrayTest.md -docs/Banana.md -docs/BananaReq.md -docs/BasquePig.md -docs/Capitalization.md -docs/Cat.md -docs/CatAllOf.md -docs/Category.md -docs/ChildCat.md -docs/ChildCatAllOf.md -docs/ClassModel.md -docs/Client.md -docs/ComplexQuadrilateral.md -docs/DanishPig.md -docs/DefaultApi.md -docs/DeprecatedObject.md -docs/Dog.md -docs/DogAllOf.md -docs/Drawing.md -docs/EnumArrays.md -docs/EnumClass.md -docs/EnumTest.md -docs/EquilateralTriangle.md -docs/FakeApi.md -docs/FakeClassnameTags123Api.md -docs/FileSchemaTestClass.md -docs/Foo.md -docs/FormatTest.md -docs/Fruit.md -docs/FruitReq.md -docs/GmFruit.md -docs/GrandparentAnimal.md -docs/HasOnlyReadOnly.md -docs/HealthCheckResult.md -docs/InlineResponseDefault.md -docs/IsoscelesTriangle.md -docs/Mammal.md -docs/MapTest.md -docs/MixedPropertiesAndAdditionalPropertiesClass.md -docs/Model200Response.md -docs/ModelApiResponse.md -docs/ModelReturn.md -docs/Name.md -docs/NullableClass.md -docs/NullableShape.md -docs/NumberOnly.md -docs/ObjectWithDeprecatedFields.md -docs/Order.md -docs/OuterComposite.md -docs/OuterEnum.md -docs/OuterEnumDefaultValue.md -docs/OuterEnumInteger.md -docs/OuterEnumIntegerDefaultValue.md -docs/ParentPet.md -docs/Pet.md -docs/PetApi.md -docs/Pig.md -docs/Quadrilateral.md -docs/QuadrilateralInterface.md -docs/ReadOnlyFirst.md -docs/ScaleneTriangle.md -docs/Shape.md -docs/ShapeInterface.md -docs/ShapeOrNull.md -docs/SimpleQuadrilateral.md -docs/SpecialModelName.md -docs/StoreApi.md -docs/Tag.md -docs/Triangle.md -docs/TriangleInterface.md -docs/User.md -docs/UserApi.md -docs/Whale.md -docs/Zebra.md -git_push.sh -gradle.properties -gradle/wrapper/gradle-wrapper.jar -gradle/wrapper/gradle-wrapper.properties -gradlew -gradlew.bat -pom.xml -settings.gradle -src/main/AndroidManifest.xml -src/main/java/org/openapitools/client/ApiClient.java -src/main/java/org/openapitools/client/ApiException.java -src/main/java/org/openapitools/client/ApiResponse.java -src/main/java/org/openapitools/client/Configuration.java -src/main/java/org/openapitools/client/JSON.java -src/main/java/org/openapitools/client/Pair.java -src/main/java/org/openapitools/client/RFC3339DateFormat.java -src/main/java/org/openapitools/client/ServerConfiguration.java -src/main/java/org/openapitools/client/ServerVariable.java -src/main/java/org/openapitools/client/api/AnotherFakeApi.java -src/main/java/org/openapitools/client/api/DefaultApi.java -src/main/java/org/openapitools/client/api/FakeApi.java -src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java -src/main/java/org/openapitools/client/api/PetApi.java -src/main/java/org/openapitools/client/api/StoreApi.java -src/main/java/org/openapitools/client/api/UserApi.java -src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java -src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java -src/main/java/org/openapitools/client/model/Animal.java -src/main/java/org/openapitools/client/model/Apple.java -src/main/java/org/openapitools/client/model/AppleReq.java -src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java -src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java -src/main/java/org/openapitools/client/model/ArrayTest.java -src/main/java/org/openapitools/client/model/Banana.java -src/main/java/org/openapitools/client/model/BananaReq.java -src/main/java/org/openapitools/client/model/BasquePig.java -src/main/java/org/openapitools/client/model/Capitalization.java -src/main/java/org/openapitools/client/model/Cat.java -src/main/java/org/openapitools/client/model/CatAllOf.java -src/main/java/org/openapitools/client/model/Category.java -src/main/java/org/openapitools/client/model/ChildCat.java -src/main/java/org/openapitools/client/model/ChildCatAllOf.java -src/main/java/org/openapitools/client/model/ClassModel.java -src/main/java/org/openapitools/client/model/Client.java -src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java -src/main/java/org/openapitools/client/model/DanishPig.java -src/main/java/org/openapitools/client/model/DeprecatedObject.java -src/main/java/org/openapitools/client/model/Dog.java -src/main/java/org/openapitools/client/model/DogAllOf.java -src/main/java/org/openapitools/client/model/Drawing.java -src/main/java/org/openapitools/client/model/EnumArrays.java -src/main/java/org/openapitools/client/model/EnumClass.java -src/main/java/org/openapitools/client/model/EnumTest.java -src/main/java/org/openapitools/client/model/EquilateralTriangle.java -src/main/java/org/openapitools/client/model/FileSchemaTestClass.java -src/main/java/org/openapitools/client/model/Foo.java -src/main/java/org/openapitools/client/model/FormatTest.java -src/main/java/org/openapitools/client/model/Fruit.java -src/main/java/org/openapitools/client/model/FruitReq.java -src/main/java/org/openapitools/client/model/GmFruit.java -src/main/java/org/openapitools/client/model/GrandparentAnimal.java -src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java -src/main/java/org/openapitools/client/model/HealthCheckResult.java -src/main/java/org/openapitools/client/model/InlineResponseDefault.java -src/main/java/org/openapitools/client/model/IsoscelesTriangle.java -src/main/java/org/openapitools/client/model/Mammal.java -src/main/java/org/openapitools/client/model/MapTest.java -src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java -src/main/java/org/openapitools/client/model/Model200Response.java -src/main/java/org/openapitools/client/model/ModelApiResponse.java -src/main/java/org/openapitools/client/model/ModelReturn.java -src/main/java/org/openapitools/client/model/Name.java -src/main/java/org/openapitools/client/model/NullableClass.java -src/main/java/org/openapitools/client/model/NullableShape.java -src/main/java/org/openapitools/client/model/NumberOnly.java -src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java -src/main/java/org/openapitools/client/model/Order.java -src/main/java/org/openapitools/client/model/OuterComposite.java -src/main/java/org/openapitools/client/model/OuterEnum.java -src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java -src/main/java/org/openapitools/client/model/OuterEnumInteger.java -src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java -src/main/java/org/openapitools/client/model/ParentPet.java -src/main/java/org/openapitools/client/model/Pet.java -src/main/java/org/openapitools/client/model/Pig.java -src/main/java/org/openapitools/client/model/Quadrilateral.java -src/main/java/org/openapitools/client/model/QuadrilateralInterface.java -src/main/java/org/openapitools/client/model/ReadOnlyFirst.java -src/main/java/org/openapitools/client/model/ScaleneTriangle.java -src/main/java/org/openapitools/client/model/Shape.java -src/main/java/org/openapitools/client/model/ShapeInterface.java -src/main/java/org/openapitools/client/model/ShapeOrNull.java -src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java -src/main/java/org/openapitools/client/model/SpecialModelName.java -src/main/java/org/openapitools/client/model/Tag.java -src/main/java/org/openapitools/client/model/Triangle.java -src/main/java/org/openapitools/client/model/TriangleInterface.java -src/main/java/org/openapitools/client/model/User.java -src/main/java/org/openapitools/client/model/Whale.java -src/main/java/org/openapitools/client/model/Zebra.java diff --git a/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION b/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION deleted file mode 100644 index 5f68295fc1..0000000000 --- a/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -6.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/native/.travis.yml b/samples/openapi3/client/petstore/java/native/.travis.yml deleted file mode 100644 index d489da682e..0000000000 --- a/samples/openapi3/client/petstore/java/native/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Generated by: https://openapi-generator.tech -# -language: java -jdk: - - oraclejdk11 -before_install: - # ensure gradlew has proper permission - - chmod a+x ./gradlew -script: - # test using maven - - mvn test - # uncomment below to test using gradle - # - gradle test - # uncomment below to test using sbt - # - sbt test diff --git a/samples/openapi3/client/petstore/java/native/README.md b/samples/openapi3/client/petstore/java/native/README.md deleted file mode 100644 index 53409eae50..0000000000 --- a/samples/openapi3/client/petstore/java/native/README.md +++ /dev/null @@ -1,317 +0,0 @@ -# petstore-openapi3-native - -OpenAPI Petstore - -- API version: 1.0.0 - -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - - -*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* - -## Requirements - -Building the API client library requires: - -1. Java 11+ -2. Maven/Gradle - -## Installation - -To install the API client library to your local Maven repository, simply execute: - -```shell -mvn clean install -``` - -To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: - -```shell -mvn clean deploy -``` - -Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. - -### Maven users - -Add this dependency to your project's POM: - -```xml - - org.openapitools - petstore-openapi3-native - 1.0.0 - compile - -``` - -### Gradle users - -Add this dependency to your project's build file: - -```groovy -compile "org.openapitools:petstore-openapi3-native:1.0.0" -``` - -### Others - -At first generate the JAR by executing: - -```shell -mvn clean package -``` - -Then manually install the following JARs: - -- `target/petstore-openapi3-native-1.0.0.jar` -- `target/lib/*.jar` - -## Getting Started - -Please follow the [installation](#installation) instruction and execute the following Java code: - -```java - -import org.openapitools.client.*; -import org.openapitools.client.model.*; -import org.openapitools.client.api.AnotherFakeApi; - -public class AnotherFakeApiExample { - - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - // Configure clients using the `defaultClient` object, such as - // overriding the host and port, timeout, etc. - AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); - Client client = new Client(); // Client | client model - try { - Client result = apiInstance.call123testSpecialTags(client); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling AnotherFakeApi#call123testSpecialTags"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} - -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**call123testSpecialTags**](docs/AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags -*AnotherFakeApi* | [**call123testSpecialTagsWithHttpInfo**](docs/AnotherFakeApi.md#call123testSpecialTagsWithHttpInfo) | **PATCH** /another-fake/dummy | To test special tags -*DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooGet) | **GET** /foo | -*DefaultApi* | [**fooGetWithHttpInfo**](docs/DefaultApi.md#fooGetWithHttpInfo) | **GET** /foo | -*FakeApi* | [**fakeHealthGet**](docs/FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint -*FakeApi* | [**fakeHealthGetWithHttpInfo**](docs/FakeApi.md#fakeHealthGetWithHttpInfo) | **GET** /fake/health | Health check endpoint -*FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | -*FakeApi* | [**fakeOuterBooleanSerializeWithHttpInfo**](docs/FakeApi.md#fakeOuterBooleanSerializeWithHttpInfo) | **POST** /fake/outer/boolean | -*FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | -*FakeApi* | [**fakeOuterCompositeSerializeWithHttpInfo**](docs/FakeApi.md#fakeOuterCompositeSerializeWithHttpInfo) | **POST** /fake/outer/composite | -*FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | -*FakeApi* | [**fakeOuterNumberSerializeWithHttpInfo**](docs/FakeApi.md#fakeOuterNumberSerializeWithHttpInfo) | **POST** /fake/outer/number | -*FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | -*FakeApi* | [**fakeOuterStringSerializeWithHttpInfo**](docs/FakeApi.md#fakeOuterStringSerializeWithHttpInfo) | **POST** /fake/outer/string | -*FakeApi* | [**getArrayOfEnums**](docs/FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums -*FakeApi* | [**getArrayOfEnumsWithHttpInfo**](docs/FakeApi.md#getArrayOfEnumsWithHttpInfo) | **GET** /fake/array-of-enums | Array of Enums -*FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | -*FakeApi* | [**testBodyWithFileSchemaWithHttpInfo**](docs/FakeApi.md#testBodyWithFileSchemaWithHttpInfo) | **PUT** /fake/body-with-file-schema | -*FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | -*FakeApi* | [**testBodyWithQueryParamsWithHttpInfo**](docs/FakeApi.md#testBodyWithQueryParamsWithHttpInfo) | **PUT** /fake/body-with-query-params | -*FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model -*FakeApi* | [**testClientModelWithHttpInfo**](docs/FakeApi.md#testClientModelWithHttpInfo) | **PATCH** /fake | To test \"client\" model -*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**testEndpointParametersWithHttpInfo**](docs/FakeApi.md#testEndpointParametersWithHttpInfo) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters -*FakeApi* | [**testEnumParametersWithHttpInfo**](docs/FakeApi.md#testEnumParametersWithHttpInfo) | **GET** /fake | To test enum parameters -*FakeApi* | [**testGroupParameters**](docs/FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**testGroupParametersWithHttpInfo**](docs/FakeApi.md#testGroupParametersWithHttpInfo) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**testInlineAdditionalPropertiesWithHttpInfo**](docs/FakeApi.md#testInlineAdditionalPropertiesWithHttpInfo) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data -*FakeApi* | [**testJsonFormDataWithHttpInfo**](docs/FakeApi.md#testJsonFormDataWithHttpInfo) | **GET** /fake/jsonFormData | test json serialization of form data -*FakeApi* | [**testQueryParameterCollectionFormat**](docs/FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | -*FakeApi* | [**testQueryParameterCollectionFormatWithHttpInfo**](docs/FakeApi.md#testQueryParameterCollectionFormatWithHttpInfo) | **PUT** /fake/test-query-parameters | -*FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case -*FakeClassnameTags123Api* | [**testClassnameWithHttpInfo**](docs/FakeClassnameTags123Api.md#testClassnameWithHttpInfo) | **PATCH** /fake_classname_test | To test class name in snake case -*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**addPetWithHttpInfo**](docs/PetApi.md#addPetWithHttpInfo) | **POST** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**deletePetWithHttpInfo**](docs/PetApi.md#deletePetWithHttpInfo) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByStatusWithHttpInfo**](docs/PetApi.md#findPetsByStatusWithHttpInfo) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**findPetsByTagsWithHttpInfo**](docs/PetApi.md#findPetsByTagsWithHttpInfo) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**getPetByIdWithHttpInfo**](docs/PetApi.md#getPetByIdWithHttpInfo) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet -*PetApi* | [**updatePetWithHttpInfo**](docs/PetApi.md#updatePetWithHttpInfo) | **PUT** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**updatePetWithFormWithHttpInfo**](docs/PetApi.md#updatePetWithFormWithHttpInfo) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image -*PetApi* | [**uploadFileWithHttpInfo**](docs/PetApi.md#uploadFileWithHttpInfo) | **POST** /pet/{petId}/uploadImage | uploads an image -*PetApi* | [**uploadFileWithRequiredFile**](docs/PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -*PetApi* | [**uploadFileWithRequiredFileWithHttpInfo**](docs/PetApi.md#uploadFileWithRequiredFileWithHttpInfo) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**deleteOrderWithHttpInfo**](docs/StoreApi.md#deleteOrderWithHttpInfo) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getInventoryWithHttpInfo**](docs/StoreApi.md#getInventoryWithHttpInfo) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**getOrderByIdWithHttpInfo**](docs/StoreApi.md#getOrderByIdWithHttpInfo) | **GET** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet -*StoreApi* | [**placeOrderWithHttpInfo**](docs/StoreApi.md#placeOrderWithHttpInfo) | **POST** /store/order | Place an order for a pet -*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user -*UserApi* | [**createUserWithHttpInfo**](docs/UserApi.md#createUserWithHttpInfo) | **POST** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithArrayInputWithHttpInfo**](docs/UserApi.md#createUsersWithArrayInputWithHttpInfo) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**createUsersWithListInputWithHttpInfo**](docs/UserApi.md#createUsersWithListInputWithHttpInfo) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user -*UserApi* | [**deleteUserWithHttpInfo**](docs/UserApi.md#deleteUserWithHttpInfo) | **DELETE** /user/{username} | Delete user -*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name -*UserApi* | [**getUserByNameWithHttpInfo**](docs/UserApi.md#getUserByNameWithHttpInfo) | **GET** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system -*UserApi* | [**loginUserWithHttpInfo**](docs/UserApi.md#loginUserWithHttpInfo) | **GET** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**logoutUserWithHttpInfo**](docs/UserApi.md#logoutUserWithHttpInfo) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user -*UserApi* | [**updateUserWithHttpInfo**](docs/UserApi.md#updateUserWithHttpInfo) | **PUT** /user/{username} | Updated user - - -## Documentation for Models - - - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - - [Animal](docs/Animal.md) - - [Apple](docs/Apple.md) - - [AppleReq](docs/AppleReq.md) - - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - - [ArrayTest](docs/ArrayTest.md) - - [Banana](docs/Banana.md) - - [BananaReq](docs/BananaReq.md) - - [BasquePig](docs/BasquePig.md) - - [Capitalization](docs/Capitalization.md) - - [Cat](docs/Cat.md) - - [CatAllOf](docs/CatAllOf.md) - - [Category](docs/Category.md) - - [ChildCat](docs/ChildCat.md) - - [ChildCatAllOf](docs/ChildCatAllOf.md) - - [ClassModel](docs/ClassModel.md) - - [Client](docs/Client.md) - - [ComplexQuadrilateral](docs/ComplexQuadrilateral.md) - - [DanishPig](docs/DanishPig.md) - - [DeprecatedObject](docs/DeprecatedObject.md) - - [Dog](docs/Dog.md) - - [DogAllOf](docs/DogAllOf.md) - - [Drawing](docs/Drawing.md) - - [EnumArrays](docs/EnumArrays.md) - - [EnumClass](docs/EnumClass.md) - - [EnumTest](docs/EnumTest.md) - - [EquilateralTriangle](docs/EquilateralTriangle.md) - - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - - [Foo](docs/Foo.md) - - [FormatTest](docs/FormatTest.md) - - [Fruit](docs/Fruit.md) - - [FruitReq](docs/FruitReq.md) - - [GmFruit](docs/GmFruit.md) - - [GrandparentAnimal](docs/GrandparentAnimal.md) - - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - - [HealthCheckResult](docs/HealthCheckResult.md) - - [InlineResponseDefault](docs/InlineResponseDefault.md) - - [IsoscelesTriangle](docs/IsoscelesTriangle.md) - - [Mammal](docs/Mammal.md) - - [MapTest](docs/MapTest.md) - - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - - [Model200Response](docs/Model200Response.md) - - [ModelApiResponse](docs/ModelApiResponse.md) - - [ModelReturn](docs/ModelReturn.md) - - [Name](docs/Name.md) - - [NullableClass](docs/NullableClass.md) - - [NullableShape](docs/NullableShape.md) - - [NumberOnly](docs/NumberOnly.md) - - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) - - [Order](docs/Order.md) - - [OuterComposite](docs/OuterComposite.md) - - [OuterEnum](docs/OuterEnum.md) - - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) - - [OuterEnumInteger](docs/OuterEnumInteger.md) - - [OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) - - [ParentPet](docs/ParentPet.md) - - [Pet](docs/Pet.md) - - [Pig](docs/Pig.md) - - [Quadrilateral](docs/Quadrilateral.md) - - [QuadrilateralInterface](docs/QuadrilateralInterface.md) - - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - - [ScaleneTriangle](docs/ScaleneTriangle.md) - - [Shape](docs/Shape.md) - - [ShapeInterface](docs/ShapeInterface.md) - - [ShapeOrNull](docs/ShapeOrNull.md) - - [SimpleQuadrilateral](docs/SimpleQuadrilateral.md) - - [SpecialModelName](docs/SpecialModelName.md) - - [Tag](docs/Tag.md) - - [Triangle](docs/Triangle.md) - - [TriangleInterface](docs/TriangleInterface.md) - - [User](docs/User.md) - - [Whale](docs/Whale.md) - - [Zebra](docs/Zebra.md) - - -## Documentation for Authorization - -Authentication schemes defined for the API: -### api_key - - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - -### api_key_query - - -- **Type**: API key -- **API key parameter name**: api_key_query -- **Location**: URL query string - -### bearer_test - - -- **Type**: HTTP basic authentication - -### http_basic_test - - -- **Type**: HTTP basic authentication - -### http_signature_test - - -- **Type**: HTTP basic authentication - -### petstore_auth - - -- **Type**: OAuth -- **Flow**: implicit -- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog -- **Scopes**: - - write:pets: modify pets in your account - - read:pets: read your pets - - -## Recommendation - -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. -However, the instances of the api clients created from the `ApiClient` are thread-safe and can be re-used. - -## Author - - - diff --git a/samples/openapi3/client/petstore/java/native/api/openapi.yaml b/samples/openapi3/client/petstore/java/native/api/openapi.yaml deleted file mode 100644 index 66a182e3a0..0000000000 --- a/samples/openapi3/client/petstore/java/native/api/openapi.yaml +++ /dev/null @@ -1,2478 +0,0 @@ -openapi: 3.0.0 -info: - description: 'This spec is mainly for testing Petstore server and contains fake - endpoints, models. Please do not use this for any other purpose. Special characters: - " \' - license: - name: Apache-2.0 - url: https://www.apache.org/licenses/LICENSE-2.0.html - title: OpenAPI Petstore - version: 1.0.0 -servers: -- description: petstore server - url: http://{server}.swagger.io:{port}/v2 - variables: - server: - default: petstore - enum: - - petstore - - qa-petstore - - dev-petstore - port: - default: "80" - enum: - - "80" - - "8080" -- description: The local server - url: https://localhost:8080/{version} - variables: - version: - default: v2 - enum: - - v1 - - v2 -- description: The local server without variables - url: https://127.0.0.1/no_variable -tags: -- description: Everything about your Pets - name: pet -- description: Access to Petstore orders - name: store -- description: Operations about user - name: user -paths: - /foo: - get: - responses: - default: - content: - application/json: - schema: - $ref: '#/components/schemas/inline_response_default' - description: response - x-accepts: application/json - /pet: - post: - operationId: addPet - requestBody: - $ref: '#/components/requestBodies/Pet' - responses: - "405": - description: Invalid input - security: - - http_signature_test: [] - - petstore_auth: - - write:pets - - read:pets - summary: Add a new pet to the store - tags: - - pet - x-contentType: application/json - x-accepts: application/json - put: - operationId: updatePet - requestBody: - $ref: '#/components/requestBodies/Pet' - responses: - "400": - description: Invalid ID supplied - "404": - description: Pet not found - "405": - description: Validation exception - security: - - http_signature_test: [] - - petstore_auth: - - write:pets - - read:pets - summary: Update an existing pet - tags: - - pet - x-contentType: application/json - x-accepts: application/json - servers: - - url: http://petstore.swagger.io/v2 - - url: http://path-server-test.petstore.local/v2 - /pet/findByStatus: - get: - description: Multiple status values can be provided with comma separated strings - operationId: findPetsByStatus - parameters: - - description: Status values that need to be considered for filter - explode: false - in: query - name: status - required: true - schema: - items: - default: available - enum: - - available - - pending - - sold - type: string - type: array - style: form - responses: - "200": - content: - application/xml: - schema: - items: - $ref: '#/components/schemas/Pet' - type: array - application/json: - schema: - items: - $ref: '#/components/schemas/Pet' - type: array - description: successful operation - "400": - description: Invalid status value - security: - - http_signature_test: [] - - petstore_auth: - - write:pets - - read:pets - summary: Finds Pets by status - tags: - - pet - x-accepts: application/json - /pet/findByTags: - get: - deprecated: true - description: Multiple tags can be provided with comma separated strings. Use - tag1, tag2, tag3 for testing. - operationId: findPetsByTags - parameters: - - description: Tags to filter by - explode: false - in: query - name: tags - required: true - schema: - items: - type: string - type: array - style: form - responses: - "200": - content: - application/xml: - schema: - items: - $ref: '#/components/schemas/Pet' - type: array - application/json: - schema: - items: - $ref: '#/components/schemas/Pet' - type: array - description: successful operation - "400": - description: Invalid tag value - security: - - http_signature_test: [] - - petstore_auth: - - write:pets - - read:pets - summary: Finds Pets by tags - tags: - - pet - x-accepts: application/json - /pet/{petId}: - delete: - operationId: deletePet - parameters: - - explode: false - in: header - name: api_key - required: false - schema: - type: string - style: simple - - description: Pet id to delete - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - responses: - "400": - description: Invalid pet value - security: - - petstore_auth: - - write:pets - - read:pets - summary: Deletes a pet - tags: - - pet - x-accepts: application/json - get: - description: Returns a single pet - operationId: getPetById - parameters: - - description: ID of pet to return - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - responses: - "200": - content: - application/xml: - schema: - $ref: '#/components/schemas/Pet' - application/json: - schema: - $ref: '#/components/schemas/Pet' - description: successful operation - "400": - description: Invalid ID supplied - "404": - description: Pet not found - security: - - api_key: [] - summary: Find pet by ID - tags: - - pet - x-accepts: application/json - post: - operationId: updatePetWithForm - parameters: - - description: ID of pet that needs to be updated - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - requestBody: - $ref: '#/components/requestBodies/inline_object' - content: - application/x-www-form-urlencoded: - schema: - properties: - name: - description: Updated name of the pet - type: string - status: - description: Updated status of the pet - type: string - type: object - responses: - "405": - description: Invalid input - security: - - petstore_auth: - - write:pets - - read:pets - summary: Updates a pet in the store with form data - tags: - - pet - x-contentType: application/x-www-form-urlencoded - x-accepts: application/json - /pet/{petId}/uploadImage: - post: - operationId: uploadFile - parameters: - - description: ID of pet to update - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - requestBody: - $ref: '#/components/requestBodies/inline_object_1' - content: - multipart/form-data: - schema: - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - file: - description: file to upload - format: binary - type: string - type: object - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: successful operation - security: - - petstore_auth: - - write:pets - - read:pets - summary: uploads an image - tags: - - pet - x-contentType: multipart/form-data - x-accepts: application/json - /store/inventory: - get: - description: Returns a map of status codes to quantities - operationId: getInventory - responses: - "200": - content: - application/json: - schema: - additionalProperties: - format: int32 - type: integer - type: object - description: successful operation - security: - - api_key: [] - summary: Returns pet inventories by status - tags: - - store - x-accepts: application/json - /store/order: - post: - operationId: placeOrder - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/Order' - description: order placed for purchasing the pet - required: true - responses: - "200": - content: - application/xml: - schema: - $ref: '#/components/schemas/Order' - application/json: - schema: - $ref: '#/components/schemas/Order' - description: successful operation - "400": - description: Invalid Order - summary: Place an order for a pet - tags: - - store - x-contentType: application/json - x-accepts: application/json - /store/order/{order_id}: - delete: - description: For valid response try integer IDs with value < 1000. Anything - above 1000 or nonintegers will generate API errors - operationId: deleteOrder - parameters: - - description: ID of the order that needs to be deleted - explode: false - in: path - name: order_id - required: true - schema: - type: string - style: simple - responses: - "400": - description: Invalid ID supplied - "404": - description: Order not found - summary: Delete purchase order by ID - tags: - - store - x-accepts: application/json - get: - description: For valid response try integer IDs with value <= 5 or > 10. Other - values will generated exceptions - operationId: getOrderById - parameters: - - description: ID of pet that needs to be fetched - explode: false - in: path - name: order_id - required: true - schema: - format: int64 - maximum: 5 - minimum: 1 - type: integer - style: simple - responses: - "200": - content: - application/xml: - schema: - $ref: '#/components/schemas/Order' - application/json: - schema: - $ref: '#/components/schemas/Order' - description: successful operation - "400": - description: Invalid ID supplied - "404": - description: Order not found - summary: Find purchase order by ID - tags: - - store - x-accepts: application/json - /user: - post: - description: This can only be done by the logged in user. - operationId: createUser - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/User' - description: Created user object - required: true - responses: - default: - description: successful operation - summary: Create user - tags: - - user - x-contentType: application/json - x-accepts: application/json - /user/createWithArray: - post: - operationId: createUsersWithArrayInput - requestBody: - $ref: '#/components/requestBodies/UserArray' - responses: - default: - description: successful operation - summary: Creates list of users with given input array - tags: - - user - x-contentType: application/json - x-accepts: application/json - /user/createWithList: - post: - operationId: createUsersWithListInput - requestBody: - $ref: '#/components/requestBodies/UserArray' - responses: - default: - description: successful operation - summary: Creates list of users with given input array - tags: - - user - x-contentType: application/json - x-accepts: application/json - /user/login: - get: - operationId: loginUser - parameters: - - description: The user name for login - explode: true - in: query - name: username - required: true - schema: - type: string - style: form - - description: The password for login in clear text - explode: true - in: query - name: password - required: true - schema: - type: string - style: form - responses: - "200": - content: - application/xml: - schema: - type: string - application/json: - schema: - type: string - description: successful operation - headers: - X-Rate-Limit: - description: calls per hour allowed by the user - explode: false - schema: - format: int32 - type: integer - style: simple - X-Expires-After: - description: date in UTC when token expires - explode: false - schema: - format: date-time - type: string - style: simple - "400": - description: Invalid username/password supplied - summary: Logs user into the system - tags: - - user - x-accepts: application/json - /user/logout: - get: - operationId: logoutUser - responses: - default: - description: successful operation - summary: Logs out current logged in user session - tags: - - user - x-accepts: application/json - /user/{username}: - delete: - description: This can only be done by the logged in user. - operationId: deleteUser - parameters: - - description: The name that needs to be deleted - explode: false - in: path - name: username - required: true - schema: - type: string - style: simple - responses: - "400": - description: Invalid username supplied - "404": - description: User not found - summary: Delete user - tags: - - user - x-accepts: application/json - get: - operationId: getUserByName - parameters: - - description: The name that needs to be fetched. Use user1 for testing. - explode: false - in: path - name: username - required: true - schema: - type: string - style: simple - responses: - "200": - content: - application/xml: - schema: - $ref: '#/components/schemas/User' - application/json: - schema: - $ref: '#/components/schemas/User' - description: successful operation - "400": - description: Invalid username supplied - "404": - description: User not found - summary: Get user by user name - tags: - - user - x-accepts: application/json - put: - description: This can only be done by the logged in user. - operationId: updateUser - parameters: - - description: name that need to be deleted - explode: false - in: path - name: username - required: true - schema: - type: string - style: simple - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/User' - description: Updated user object - required: true - responses: - "400": - description: Invalid user supplied - "404": - description: User not found - summary: Updated user - tags: - - user - x-contentType: application/json - x-accepts: application/json - /fake_classname_test: - patch: - description: To test class name in snake case - operationId: testClassname - requestBody: - $ref: '#/components/requestBodies/Client' - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/Client' - description: successful operation - security: - - api_key_query: [] - summary: To test class name in snake case - tags: - - fake_classname_tags 123#$%^ - x-contentType: application/json - x-accepts: application/json - /fake: - delete: - description: Fake endpoint to test group parameters (optional) - operationId: testGroupParameters - parameters: - - description: Required String in group parameters - explode: true - in: query - name: required_string_group - required: true - schema: - type: integer - style: form - - description: Required Boolean in group parameters - explode: false - in: header - name: required_boolean_group - required: true - schema: - type: boolean - style: simple - - description: Required Integer in group parameters - explode: true - in: query - name: required_int64_group - required: true - schema: - format: int64 - type: integer - style: form - - description: String in group parameters - explode: true - in: query - name: string_group - required: false - schema: - type: integer - style: form - - description: Boolean in group parameters - explode: false - in: header - name: boolean_group - required: false - schema: - type: boolean - style: simple - - description: Integer in group parameters - explode: true - in: query - name: int64_group - required: false - schema: - format: int64 - type: integer - style: form - responses: - "400": - description: Someting wrong - security: - - bearer_test: [] - summary: Fake endpoint to test group parameters (optional) - tags: - - fake - x-group-parameters: true - x-accepts: application/json - get: - description: To test enum parameters - operationId: testEnumParameters - parameters: - - description: Header parameter enum test (string array) - explode: false - in: header - name: enum_header_string_array - required: false - schema: - items: - default: $ - enum: - - '>' - - $ - type: string - type: array - style: simple - - description: Header parameter enum test (string) - explode: false - in: header - name: enum_header_string - required: false - schema: - default: -efg - enum: - - _abc - - -efg - - (xyz) - type: string - style: simple - - description: Query parameter enum test (string array) - explode: true - in: query - name: enum_query_string_array - required: false - schema: - items: - default: $ - enum: - - '>' - - $ - type: string - type: array - style: form - - description: Query parameter enum test (string) - explode: true - in: query - name: enum_query_string - required: false - schema: - default: -efg - enum: - - _abc - - -efg - - (xyz) - type: string - style: form - - description: Query parameter enum test (double) - explode: true - in: query - name: enum_query_integer - required: false - schema: - enum: - - 1 - - -2 - format: int32 - type: integer - style: form - - description: Query parameter enum test (double) - explode: true - in: query - name: enum_query_double - required: false - schema: - enum: - - 1.1 - - -1.2 - format: double - type: number - style: form - requestBody: - $ref: '#/components/requestBodies/inline_object_2' - content: - application/x-www-form-urlencoded: - schema: - properties: - enum_form_string_array: - description: Form parameter enum test (string array) - items: - default: $ - enum: - - '>' - - $ - type: string - type: array - enum_form_string: - default: -efg - description: Form parameter enum test (string) - enum: - - _abc - - -efg - - (xyz) - type: string - type: object - responses: - "400": - description: Invalid request - "404": - description: Not found - summary: To test enum parameters - tags: - - fake - x-contentType: application/x-www-form-urlencoded - x-accepts: application/json - patch: - description: To test "client" model - operationId: testClientModel - requestBody: - $ref: '#/components/requestBodies/Client' - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/Client' - description: successful operation - summary: To test "client" model - tags: - - fake - x-contentType: application/json - x-accepts: application/json - post: - description: | - Fake endpoint for testing various parameters - 假端點 - 偽のエンドポイント - 가짜 엔드 포인트 - operationId: testEndpointParameters - requestBody: - $ref: '#/components/requestBodies/inline_object_3' - content: - application/x-www-form-urlencoded: - schema: - properties: - integer: - description: None - maximum: 100 - minimum: 10 - type: integer - int32: - description: None - format: int32 - maximum: 200 - minimum: 20 - type: integer - int64: - description: None - format: int64 - type: integer - number: - description: None - maximum: 543.2 - minimum: 32.1 - type: number - float: - description: None - format: float - maximum: 987.6 - type: number - double: - description: None - format: double - maximum: 123.4 - minimum: 67.8 - type: number - string: - description: None - pattern: /[a-z]/i - type: string - pattern_without_delimiter: - description: None - pattern: ^[A-Z].* - type: string - byte: - description: None - format: byte - type: string - binary: - description: None - format: binary - type: string - date: - description: None - format: date - type: string - dateTime: - default: 2010-02-01T10:20:10.11111+01:00 - description: None - example: 2020-02-02T20:20:20.22222Z - format: date-time - type: string - password: - description: None - format: password - maxLength: 64 - minLength: 10 - type: string - callback: - description: None - type: string - required: - - byte - - double - - number - - pattern_without_delimiter - type: object - responses: - "400": - description: Invalid username supplied - "404": - description: User not found - security: - - http_basic_test: [] - summary: | - Fake endpoint for testing various parameters - 假端點 - 偽のエンドポイント - 가짜 엔드 포인트 - tags: - - fake - x-contentType: application/x-www-form-urlencoded - x-accepts: application/json - /fake/outer/number: - post: - description: Test serialization of outer number types - operationId: fakeOuterNumberSerialize - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/OuterNumber' - description: Input number as post body - responses: - "200": - content: - '*/*': - schema: - $ref: '#/components/schemas/OuterNumber' - description: Output number - tags: - - fake - x-contentType: application/json - x-accepts: '*/*' - /fake/outer/string: - post: - description: Test serialization of outer string types - operationId: fakeOuterStringSerialize - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/OuterString' - description: Input string as post body - responses: - "200": - content: - '*/*': - schema: - $ref: '#/components/schemas/OuterString' - description: Output string - tags: - - fake - x-contentType: application/json - x-accepts: '*/*' - /fake/outer/boolean: - post: - description: Test serialization of outer boolean types - operationId: fakeOuterBooleanSerialize - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/OuterBoolean' - description: Input boolean as post body - responses: - "200": - content: - '*/*': - schema: - $ref: '#/components/schemas/OuterBoolean' - description: Output boolean - tags: - - fake - x-contentType: application/json - x-accepts: '*/*' - /fake/outer/composite: - post: - description: Test serialization of object with outer number type - operationId: fakeOuterCompositeSerialize - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/OuterComposite' - description: Input composite as post body - responses: - "200": - content: - '*/*': - schema: - $ref: '#/components/schemas/OuterComposite' - description: Output composite - tags: - - fake - x-contentType: application/json - x-accepts: '*/*' - /fake/jsonFormData: - get: - operationId: testJsonFormData - requestBody: - $ref: '#/components/requestBodies/inline_object_4' - content: - application/x-www-form-urlencoded: - schema: - properties: - param: - description: field1 - type: string - param2: - description: field2 - type: string - required: - - param - - param2 - type: object - responses: - "200": - description: successful operation - summary: test json serialization of form data - tags: - - fake - x-contentType: application/x-www-form-urlencoded - x-accepts: application/json - /fake/inline-additionalProperties: - post: - operationId: testInlineAdditionalProperties - requestBody: - content: - application/json: - schema: - additionalProperties: - type: string - type: object - description: request body - required: true - responses: - "200": - description: successful operation - summary: test inline additionalProperties - tags: - - fake - x-contentType: application/json - x-accepts: application/json - /fake/body-with-query-params: - put: - operationId: testBodyWithQueryParams - parameters: - - explode: true - in: query - name: query - required: true - schema: - type: string - style: form - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/User' - required: true - responses: - "200": - description: Success - tags: - - fake - x-contentType: application/json - x-accepts: application/json - /another-fake/dummy: - patch: - description: To test special tags and operation ID starting with number - operationId: 123_test_@#$%_special_tags - requestBody: - $ref: '#/components/requestBodies/Client' - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/Client' - description: successful operation - summary: To test special tags - tags: - - $another-fake? - x-contentType: application/json - x-accepts: application/json - /fake/body-with-file-schema: - put: - description: For this test, the body for this request much reference a schema - named `File`. - operationId: testBodyWithFileSchema - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/FileSchemaTestClass' - required: true - responses: - "200": - description: Success - tags: - - fake - x-contentType: application/json - x-accepts: application/json - /fake/test-query-parameters: - put: - description: To test the collection format in query parameters - operationId: testQueryParameterCollectionFormat - parameters: - - explode: true - in: query - name: pipe - required: true - schema: - items: - type: string - type: array - style: form - - explode: false - in: query - name: ioutil - required: true - schema: - items: - type: string - type: array - style: form - - explode: false - in: query - name: http - required: true - schema: - items: - type: string - type: array - style: spaceDelimited - - explode: false - in: query - name: url - required: true - schema: - items: - type: string - type: array - style: form - - explode: true - in: query - name: context - required: true - schema: - items: - type: string - type: array - style: form - responses: - "200": - description: Success - tags: - - fake - x-accepts: application/json - /fake/{petId}/uploadImageWithRequiredFile: - post: - operationId: uploadFileWithRequiredFile - parameters: - - description: ID of pet to update - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - requestBody: - $ref: '#/components/requestBodies/inline_object_5' - content: - multipart/form-data: - schema: - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - requiredFile: - description: file to upload - format: binary - type: string - required: - - requiredFile - type: object - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: successful operation - security: - - petstore_auth: - - write:pets - - read:pets - summary: uploads an image (required) - tags: - - pet - x-contentType: multipart/form-data - x-accepts: application/json - /fake/health: - get: - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/HealthCheckResult' - description: The instance started successfully - summary: Health check endpoint - tags: - - fake - x-accepts: application/json - /fake/array-of-enums: - get: - operationId: getArrayOfEnums - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/ArrayOfEnums' - description: Got named array of enums - summary: Array of Enums - tags: - - fake - x-accepts: application/json -components: - requestBodies: - UserArray: - content: - application/json: - examples: - simple-list: - description: Should not get into code examples - summary: Simple list example - value: - - username: foo - - username: bar - schema: - items: - $ref: '#/components/schemas/User' - type: array - description: List of user object - required: true - Client: - content: - application/json: - schema: - $ref: '#/components/schemas/Client' - description: client model - required: true - Pet: - content: - application/json: - schema: - $ref: '#/components/schemas/Pet' - application/xml: - schema: - $ref: '#/components/schemas/Pet' - description: Pet object that needs to be added to the store - required: true - inline_object: - content: - application/x-www-form-urlencoded: - schema: - $ref: '#/components/schemas/inline_object' - inline_object_1: - content: - multipart/form-data: - schema: - $ref: '#/components/schemas/inline_object_1' - inline_object_2: - content: - application/x-www-form-urlencoded: - schema: - $ref: '#/components/schemas/inline_object_2' - inline_object_3: - content: - application/x-www-form-urlencoded: - schema: - $ref: '#/components/schemas/inline_object_3' - inline_object_4: - content: - application/x-www-form-urlencoded: - schema: - $ref: '#/components/schemas/inline_object_4' - inline_object_5: - content: - multipart/form-data: - schema: - $ref: '#/components/schemas/inline_object_5' - schemas: - Foo: - example: - bar: bar - properties: - bar: - default: bar - type: string - type: object - Bar: - default: bar - type: string - Order: - example: - petId: 6 - quantity: 1 - id: 0 - shipDate: 2020-02-02T20:20:20.000222Z - complete: false - status: placed - properties: - id: - format: int64 - type: integer - petId: - format: int64 - type: integer - quantity: - format: int32 - type: integer - shipDate: - example: 2020-02-02T20:20:20.000222Z - format: date-time - type: string - status: - description: Order Status - enum: - - placed - - approved - - delivered - type: string - complete: - default: false - type: boolean - type: object - xml: - name: Order - Category: - example: - name: default-name - id: 6 - properties: - id: - format: int64 - type: integer - name: - default: default-name - type: string - required: - - name - type: object - xml: - name: Category - User: - example: - firstName: firstName - lastName: lastName - password: password - userStatus: 6 - objectWithNoDeclaredPropsNullable: '{}' - phone: phone - objectWithNoDeclaredProps: '{}' - id: 0 - anyTypePropNullable: "" - email: email - anyTypeProp: "" - username: username - properties: - id: - format: int64 - type: integer - x-is-unique: true - username: - type: string - firstName: - type: string - lastName: - type: string - email: - type: string - password: - type: string - phone: - type: string - userStatus: - description: User Status - format: int32 - type: integer - objectWithNoDeclaredProps: - description: test code generation for objects Value must be a map of strings - to values. It cannot be the 'null' value. - type: object - objectWithNoDeclaredPropsNullable: - description: test code generation for nullable objects. Value must be a - map of strings to values or the 'null' value. - nullable: true - type: object - anyTypeProp: - description: test code generation for any type Here the 'type' attribute - is not specified, which means the value can be anything, including the - null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - anyTypePropNullable: - description: test code generation for any type Here the 'type' attribute - is not specified, which means the value can be anything, including the - null value, string, number, boolean, array or object. The 'nullable' attribute - does not change the allowed values. - nullable: true - type: object - xml: - name: User - Tag: - example: - name: name - id: 1 - properties: - id: - format: int64 - type: integer - name: - type: string - type: object - xml: - name: Tag - Pet: - example: - photoUrls: - - photoUrls - - photoUrls - name: doggie - id: 0 - category: - name: default-name - id: 6 - tags: - - name: name - id: 1 - - name: name - id: 1 - status: available - properties: - id: - format: int64 - type: integer - x-is-unique: true - category: - $ref: '#/components/schemas/Category' - name: - example: doggie - type: string - photoUrls: - items: - type: string - type: array - xml: - name: photoUrl - wrapped: true - tags: - items: - $ref: '#/components/schemas/Tag' - type: array - xml: - name: tag - wrapped: true - status: - description: pet status in the store - enum: - - available - - pending - - sold - type: string - required: - - name - - photoUrls - type: object - xml: - name: Pet - ApiResponse: - example: - code: 0 - type: type - message: message - properties: - code: - format: int32 - type: integer - type: - type: string - message: - type: string - type: object - Return: - description: Model for testing reserved words - properties: - return: - format: int32 - type: integer - xml: - name: Return - Name: - description: Model for testing model name same as property name - properties: - name: - format: int32 - type: integer - snake_case: - format: int32 - readOnly: true - type: integer - property: - type: string - "123Number": - readOnly: true - type: integer - required: - - name - xml: - name: Name - "200_response": - description: Model for testing model name starting with number - properties: - name: - format: int32 - type: integer - class: - type: string - xml: - name: Name - ClassModel: - description: Model for testing model with "_class" property - properties: - _class: - type: string - Dog: - allOf: - - $ref: '#/components/schemas/Animal' - - $ref: '#/components/schemas/Dog_allOf' - Cat: - allOf: - - $ref: '#/components/schemas/Animal' - - $ref: '#/components/schemas/Address' - - $ref: '#/components/schemas/Cat_allOf' - Address: - additionalProperties: - type: integer - type: object - Animal: - discriminator: - propertyName: className - properties: - className: - type: string - color: - default: red - type: string - required: - - className - type: object - AnimalFarm: - items: - $ref: '#/components/schemas/Animal' - type: array - format_test: - properties: - integer: - maximum: 100 - minimum: 10 - multipleOf: 2 - type: integer - int32: - format: int32 - maximum: 200 - minimum: 20 - type: integer - int64: - format: int64 - type: integer - number: - maximum: 543.2 - minimum: 32.1 - multipleOf: 32.5 - type: number - float: - format: float - maximum: 987.6 - minimum: 54.3 - type: number - double: - format: double - maximum: 123.4 - minimum: 67.8 - type: number - decimal: - format: number - type: string - string: - pattern: /[a-z]/i - type: string - byte: - format: byte - type: string - binary: - format: binary - type: string - date: - example: 2020-02-02 - format: date - type: string - dateTime: - example: 2007-12-03T10:15:30+01:00 - format: date-time - type: string - uuid: - example: 72f98069-206d-4f12-9f12-3d1e525a8e84 - format: uuid - type: string - password: - format: password - maxLength: 64 - minLength: 10 - type: string - pattern_with_digits: - description: A string that is a 10 digit number. Can have leading zeros. - pattern: ^\d{10}$ - type: string - pattern_with_digits_and_delimiter: - description: A string starting with 'image_' (case insensitive) and one - to three digits following i.e. Image_01. - pattern: /^image_\d{1,3}$/i - type: string - required: - - byte - - date - - number - - password - type: object - EnumClass: - default: -efg - enum: - - _abc - - -efg - - (xyz) - type: string - Enum_Test: - properties: - enum_string: - enum: - - UPPER - - lower - - "" - type: string - enum_string_required: - enum: - - UPPER - - lower - - "" - type: string - enum_integer: - enum: - - 1 - - -1 - format: int32 - type: integer - enum_integer_only: - enum: - - 2 - - -2 - type: integer - enum_number: - enum: - - 1.1 - - -1.2 - format: double - type: number - outerEnum: - $ref: '#/components/schemas/OuterEnum' - outerEnumInteger: - $ref: '#/components/schemas/OuterEnumInteger' - outerEnumDefaultValue: - $ref: '#/components/schemas/OuterEnumDefaultValue' - outerEnumIntegerDefaultValue: - $ref: '#/components/schemas/OuterEnumIntegerDefaultValue' - required: - - enum_string_required - type: object - AdditionalPropertiesClass: - properties: - map_property: - additionalProperties: - type: string - type: object - map_of_map_property: - additionalProperties: - additionalProperties: - type: string - type: object - type: object - anytype_1: {} - map_with_undeclared_properties_anytype_1: - type: object - map_with_undeclared_properties_anytype_2: - properties: {} - type: object - map_with_undeclared_properties_anytype_3: - additionalProperties: true - type: object - empty_map: - additionalProperties: false - description: an object with no declared properties and no undeclared properties, - hence it's an empty map. - type: object - map_with_undeclared_properties_string: - additionalProperties: - type: string - type: object - type: object - MixedPropertiesAndAdditionalPropertiesClass: - properties: - uuid: - format: uuid - type: string - dateTime: - format: date-time - type: string - map: - additionalProperties: - $ref: '#/components/schemas/Animal' - type: object - type: object - List: - properties: - "123-list": - type: string - type: object - Client: - example: - client: client - properties: - client: - type: string - type: object - ReadOnlyFirst: - properties: - bar: - readOnly: true - type: string - baz: - type: string - type: object - hasOnlyReadOnly: - properties: - bar: - readOnly: true - type: string - foo: - readOnly: true - type: string - type: object - Capitalization: - properties: - smallCamel: - type: string - CapitalCamel: - type: string - small_Snake: - type: string - Capital_Snake: - type: string - SCA_ETH_Flow_Points: - type: string - ATT_NAME: - description: | - Name of the pet - type: string - type: object - MapTest: - properties: - map_map_of_string: - additionalProperties: - additionalProperties: - type: string - type: object - type: object - map_of_enum_string: - additionalProperties: - enum: - - UPPER - - lower - type: string - type: object - direct_map: - additionalProperties: - type: boolean - type: object - indirect_map: - additionalProperties: - type: boolean - type: object - type: object - ArrayTest: - properties: - array_of_string: - items: - type: string - type: array - array_array_of_integer: - items: - items: - format: int64 - type: integer - type: array - type: array - array_array_of_model: - items: - items: - $ref: '#/components/schemas/ReadOnlyFirst' - type: array - type: array - type: object - NumberOnly: - properties: - JustNumber: - type: number - type: object - ArrayOfNumberOnly: - properties: - ArrayNumber: - items: - type: number - type: array - type: object - ArrayOfArrayOfNumberOnly: - properties: - ArrayArrayNumber: - items: - items: - type: number - type: array - type: array - type: object - EnumArrays: - properties: - just_symbol: - enum: - - '>=' - - $ - type: string - array_enum: - items: - enum: - - fish - - crab - type: string - type: array - type: object - OuterEnum: - enum: - - placed - - approved - - delivered - nullable: true - type: string - OuterEnumInteger: - enum: - - 0 - - 1 - - 2 - type: integer - OuterEnumDefaultValue: - default: placed - enum: - - placed - - approved - - delivered - type: string - OuterEnumIntegerDefaultValue: - default: 0 - enum: - - 0 - - 1 - - 2 - type: integer - OuterComposite: - example: - my_string: my_string - my_number: 0.8008281904610115 - my_boolean: true - properties: - my_number: - type: number - my_string: - type: string - my_boolean: - type: boolean - x-codegen-body-parameter-name: boolean_post_body - type: object - OuterNumber: - type: number - OuterString: - type: string - OuterBoolean: - type: boolean - x-codegen-body-parameter-name: boolean_post_body - StringBooleanMap: - additionalProperties: - type: boolean - type: object - FileSchemaTestClass: - example: - file: - sourceURI: sourceURI - files: - - sourceURI: sourceURI - - sourceURI: sourceURI - properties: - file: - $ref: '#/components/schemas/File' - files: - items: - $ref: '#/components/schemas/File' - type: array - type: object - File: - description: Must be named `File` for test. - example: - sourceURI: sourceURI - properties: - sourceURI: - description: Test capitalization - type: string - type: object - _special_model.name_: - properties: - $special[property.name]: - format: int64 - type: integer - _special_model.name_: - type: string - xml: - name: $special[model.name] - HealthCheckResult: - description: Just a string to inform instance is up and running. Make it nullable - in hope to get it as pointer in generated model. - example: - NullableMessage: NullableMessage - properties: - NullableMessage: - nullable: true - type: string - type: object - NullableClass: - additionalProperties: - nullable: true - type: object - properties: - integer_prop: - nullable: true - type: integer - number_prop: - nullable: true - type: number - boolean_prop: - nullable: true - type: boolean - string_prop: - nullable: true - type: string - date_prop: - format: date - nullable: true - type: string - datetime_prop: - format: date-time - nullable: true - type: string - array_nullable_prop: - items: - type: object - nullable: true - type: array - array_and_items_nullable_prop: - items: - nullable: true - type: object - nullable: true - type: array - array_items_nullable: - items: - nullable: true - type: object - type: array - object_nullable_prop: - additionalProperties: - type: object - nullable: true - type: object - object_and_items_nullable_prop: - additionalProperties: - nullable: true - type: object - nullable: true - type: object - object_items_nullable: - additionalProperties: - nullable: true - type: object - type: object - type: object - fruit: - additionalProperties: false - oneOf: - - $ref: '#/components/schemas/apple' - - $ref: '#/components/schemas/banana' - properties: - color: - type: string - apple: - nullable: true - properties: - cultivar: - pattern: ^[a-zA-Z\s]*$ - type: string - origin: - pattern: /^[A-Z\s]*$/i - type: string - type: object - banana: - properties: - lengthCm: - type: number - type: object - mammal: - discriminator: - propertyName: className - oneOf: - - $ref: '#/components/schemas/whale' - - $ref: '#/components/schemas/zebra' - - $ref: '#/components/schemas/Pig' - whale: - properties: - hasBaleen: - type: boolean - hasTeeth: - type: boolean - className: - type: string - required: - - className - type: object - zebra: - additionalProperties: true - properties: - type: - enum: - - plains - - mountain - - grevys - type: string - className: - type: string - required: - - className - type: object - Pig: - discriminator: - propertyName: className - oneOf: - - $ref: '#/components/schemas/BasquePig' - - $ref: '#/components/schemas/DanishPig' - BasquePig: - properties: - className: - type: string - required: - - className - type: object - DanishPig: - properties: - className: - type: string - required: - - className - type: object - gmFruit: - additionalProperties: false - anyOf: - - $ref: '#/components/schemas/apple' - - $ref: '#/components/schemas/banana' - properties: - color: - type: string - fruitReq: - additionalProperties: false - oneOf: - - type: "null" - - $ref: '#/components/schemas/appleReq' - - $ref: '#/components/schemas/bananaReq' - appleReq: - additionalProperties: false - properties: - cultivar: - type: string - mealy: - type: boolean - required: - - cultivar - type: object - bananaReq: - additionalProperties: false - properties: - lengthCm: - type: number - sweet: - type: boolean - required: - - lengthCm - type: object - Drawing: - additionalProperties: - $ref: '#/components/schemas/fruit' - properties: - mainShape: - $ref: '#/components/schemas/Shape' - shapeOrNull: - $ref: '#/components/schemas/ShapeOrNull' - nullableShape: - $ref: '#/components/schemas/NullableShape' - shapes: - items: - $ref: '#/components/schemas/Shape' - type: array - type: object - Shape: - discriminator: - propertyName: shapeType - oneOf: - - $ref: '#/components/schemas/Triangle' - - $ref: '#/components/schemas/Quadrilateral' - ShapeOrNull: - description: The value may be a shape or the 'null' value. This is introduced - in OAS schema >= 3.1. - discriminator: - propertyName: shapeType - oneOf: - - type: "null" - - $ref: '#/components/schemas/Triangle' - - $ref: '#/components/schemas/Quadrilateral' - NullableShape: - description: The value may be a shape or the 'null' value. The 'nullable' attribute - was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema - >= 3.1. - discriminator: - propertyName: shapeType - nullable: true - oneOf: - - $ref: '#/components/schemas/Triangle' - - $ref: '#/components/schemas/Quadrilateral' - ShapeInterface: - properties: - shapeType: - type: string - required: - - shapeType - TriangleInterface: - properties: - triangleType: - type: string - required: - - triangleType - Triangle: - discriminator: - propertyName: triangleType - oneOf: - - $ref: '#/components/schemas/EquilateralTriangle' - - $ref: '#/components/schemas/IsoscelesTriangle' - - $ref: '#/components/schemas/ScaleneTriangle' - EquilateralTriangle: - allOf: - - $ref: '#/components/schemas/ShapeInterface' - - $ref: '#/components/schemas/TriangleInterface' - IsoscelesTriangle: - additionalProperties: false - allOf: - - $ref: '#/components/schemas/ShapeInterface' - - $ref: '#/components/schemas/TriangleInterface' - ScaleneTriangle: - allOf: - - $ref: '#/components/schemas/ShapeInterface' - - $ref: '#/components/schemas/TriangleInterface' - QuadrilateralInterface: - properties: - quadrilateralType: - type: string - required: - - quadrilateralType - Quadrilateral: - discriminator: - propertyName: quadrilateralType - oneOf: - - $ref: '#/components/schemas/SimpleQuadrilateral' - - $ref: '#/components/schemas/ComplexQuadrilateral' - SimpleQuadrilateral: - allOf: - - $ref: '#/components/schemas/ShapeInterface' - - $ref: '#/components/schemas/QuadrilateralInterface' - ComplexQuadrilateral: - allOf: - - $ref: '#/components/schemas/ShapeInterface' - - $ref: '#/components/schemas/QuadrilateralInterface' - GrandparentAnimal: - discriminator: - propertyName: pet_type - properties: - pet_type: - type: string - required: - - pet_type - type: object - ParentPet: - allOf: - - $ref: '#/components/schemas/GrandparentAnimal' - type: object - ChildCat: - allOf: - - $ref: '#/components/schemas/ParentPet' - - $ref: '#/components/schemas/ChildCat_allOf' - ArrayOfEnums: - items: - $ref: '#/components/schemas/OuterEnum' - type: array - DateTimeTest: - default: 2010-01-01T10:10:10.000111+01:00 - example: 2010-01-01T10:10:10.000111+01:00 - format: date-time - type: string - DeprecatedObject: - deprecated: true - properties: - name: - type: string - type: object - ObjectWithDeprecatedFields: - properties: - uuid: - type: string - id: - deprecated: true - type: number - deprecatedRef: - $ref: '#/components/schemas/DeprecatedObject' - bars: - deprecated: true - items: - $ref: '#/components/schemas/Bar' - type: array - type: object - inline_response_default: - example: - string: - bar: bar - properties: - string: - $ref: '#/components/schemas/Foo' - type: object - inline_object: - properties: - name: - description: Updated name of the pet - type: string - status: - description: Updated status of the pet - type: string - type: object - inline_object_1: - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - file: - description: file to upload - format: binary - type: string - type: object - inline_object_2: - properties: - enum_form_string_array: - description: Form parameter enum test (string array) - items: - default: $ - enum: - - '>' - - $ - type: string - type: array - enum_form_string: - default: -efg - description: Form parameter enum test (string) - enum: - - _abc - - -efg - - (xyz) - type: string - type: object - inline_object_3: - properties: - integer: - description: None - maximum: 100 - minimum: 10 - type: integer - int32: - description: None - format: int32 - maximum: 200 - minimum: 20 - type: integer - int64: - description: None - format: int64 - type: integer - number: - description: None - maximum: 543.2 - minimum: 32.1 - type: number - float: - description: None - format: float - maximum: 987.6 - type: number - double: - description: None - format: double - maximum: 123.4 - minimum: 67.8 - type: number - string: - description: None - pattern: /[a-z]/i - type: string - pattern_without_delimiter: - description: None - pattern: ^[A-Z].* - type: string - byte: - description: None - format: byte - type: string - binary: - description: None - format: binary - type: string - date: - description: None - format: date - type: string - dateTime: - default: 2010-02-01T10:20:10.11111+01:00 - description: None - example: 2020-02-02T20:20:20.22222Z - format: date-time - type: string - password: - description: None - format: password - maxLength: 64 - minLength: 10 - type: string - callback: - description: None - type: string - required: - - byte - - double - - number - - pattern_without_delimiter - type: object - inline_object_4: - properties: - param: - description: field1 - type: string - param2: - description: field2 - type: string - required: - - param - - param2 - type: object - inline_object_5: - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - requiredFile: - description: file to upload - format: binary - type: string - required: - - requiredFile - type: object - Dog_allOf: - properties: - breed: - type: string - type: object - Cat_allOf: - properties: - declawed: - type: boolean - type: object - ChildCat_allOf: - properties: - name: - type: string - pet_type: - default: ChildCat - enum: - - ChildCat - type: string - x-enum-as-string: true - type: object - securitySchemes: - petstore_auth: - flows: - implicit: - authorizationUrl: http://petstore.swagger.io/api/oauth/dialog - scopes: - write:pets: modify pets in your account - read:pets: read your pets - type: oauth2 - api_key: - in: header - name: api_key - type: apiKey - api_key_query: - in: query - name: api_key_query - type: apiKey - http_basic_test: - scheme: basic - type: http - bearer_test: - bearerFormat: JWT - scheme: bearer - type: http - http_signature_test: - scheme: signature - type: http - diff --git a/samples/openapi3/client/petstore/java/native/build.gradle b/samples/openapi3/client/petstore/java/native/build.gradle deleted file mode 100644 index 4003c55d19..0000000000 --- a/samples/openapi3/client/petstore/java/native/build.gradle +++ /dev/null @@ -1,80 +0,0 @@ -apply plugin: 'idea' -apply plugin: 'eclipse' - -group = 'org.openapitools' -version = '1.0.0' - -buildscript { - repositories { - mavenCentral() - } -} - -repositories { - mavenCentral() -} - -apply plugin: 'java' -apply plugin: 'maven-publish' - -sourceCompatibility = JavaVersion.VERSION_11 -targetCompatibility = JavaVersion.VERSION_11 - -// Some text from the schema is copy pasted into the source files as UTF-8 -// but the default still seems to be to use platform encoding -tasks.withType(JavaCompile) { - configure(options) { - options.encoding = 'UTF-8' - } -} -javadoc { - options.encoding = 'UTF-8' -} - -publishing { - publications { - maven(MavenPublication) { - artifactId = 'petstore-openapi3-native' - from components.java - } - } -} - -task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath -} - -task sourcesJar(type: Jar, dependsOn: classes) { - classifier = 'sources' - from sourceSets.main.allSource -} - -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -artifacts { - archives sourcesJar - archives javadocJar -} - - -ext { - swagger_annotations_version = "1.5.22" - jackson_version = "2.10.4" - junit_version = "4.13.2" -} - -dependencies { - implementation "io.swagger:swagger-annotations:$swagger_annotations_version" - implementation "com.google.code.findbugs:jsr305:3.0.2" - implementation "com.fasterxml.jackson.core:jackson-core:$jackson_version" - implementation "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" - implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_version" - implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" - implementation "org.openapitools:jackson-databind-nullable:0.2.1" - implementation 'javax.annotation:javax.annotation-api:1.3.2' - testImplementation "junit:junit:$junit_version" -} diff --git a/samples/openapi3/client/petstore/java/native/build.sbt b/samples/openapi3/client/petstore/java/native/build.sbt deleted file mode 100644 index 464090415c..0000000000 --- a/samples/openapi3/client/petstore/java/native/build.sbt +++ /dev/null @@ -1 +0,0 @@ -# TODO diff --git a/samples/openapi3/client/petstore/java/native/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/java/native/docs/AdditionalPropertiesClass.md deleted file mode 100644 index 3d032d4504..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/AdditionalPropertiesClass.md +++ /dev/null @@ -1,20 +0,0 @@ - - -# AdditionalPropertiesClass - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**mapProperty** | **Map<String, String>** | | [optional] -**mapOfMapProperty** | **Map<String, Map<String, String>>** | | [optional] -**anytype1** | **Object** | | [optional] -**mapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] -**mapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] -**mapWithUndeclaredPropertiesAnytype3** | **Map<String, Object>** | | [optional] -**emptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] -**mapWithUndeclaredPropertiesString** | **Map<String, String>** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Animal.md b/samples/openapi3/client/petstore/java/native/docs/Animal.md deleted file mode 100644 index 7edc25cd2b..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Animal.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# Animal - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**className** | **String** | | -**color** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/AnotherFakeApi.md b/samples/openapi3/client/petstore/java/native/docs/AnotherFakeApi.md deleted file mode 100644 index 39985d5394..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/AnotherFakeApi.md +++ /dev/null @@ -1,144 +0,0 @@ -# AnotherFakeApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**call123testSpecialTags**](AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags -[**call123testSpecialTagsWithHttpInfo**](AnotherFakeApi.md#call123testSpecialTagsWithHttpInfo) | **PATCH** /another-fake/dummy | To test special tags - - - -## call123testSpecialTags - -> Client call123testSpecialTags(client) - -To test special tags - -To test special tags and operation ID starting with number - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.AnotherFakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); - Client client = new Client(); // Client | client model - try { - Client result = apiInstance.call123testSpecialTags(client); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling AnotherFakeApi#call123testSpecialTags"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md)| client model | - -### Return type - -[**Client**](Client.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -## call123testSpecialTagsWithHttpInfo - -> ApiResponse call123testSpecialTags call123testSpecialTagsWithHttpInfo(client) - -To test special tags - -To test special tags and operation ID starting with number - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.AnotherFakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); - Client client = new Client(); // Client | client model - try { - ApiResponse response = apiInstance.call123testSpecialTagsWithHttpInfo(client); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling AnotherFakeApi#call123testSpecialTags"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md)| client model | - -### Return type - -ApiResponse<[**Client**](Client.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - diff --git a/samples/openapi3/client/petstore/java/native/docs/Apple.md b/samples/openapi3/client/petstore/java/native/docs/Apple.md deleted file mode 100644 index 513643aeb7..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Apple.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# Apple - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**cultivar** | **String** | | [optional] -**origin** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/AppleReq.md b/samples/openapi3/client/petstore/java/native/docs/AppleReq.md deleted file mode 100644 index d2fccd5306..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/AppleReq.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# AppleReq - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**cultivar** | **String** | | -**mealy** | **Boolean** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/java/native/docs/ArrayOfArrayOfNumberOnly.md deleted file mode 100644 index 9b1f858699..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ArrayOfArrayOfNumberOnly.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# ArrayOfArrayOfNumberOnly - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**arrayArrayNumber** | **List<List<BigDecimal>>** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/java/native/docs/ArrayOfNumberOnly.md deleted file mode 100644 index 4e95f1ae74..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ArrayOfNumberOnly.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# ArrayOfNumberOnly - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**arrayNumber** | **List<BigDecimal>** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ArrayTest.md b/samples/openapi3/client/petstore/java/native/docs/ArrayTest.md deleted file mode 100644 index 9b90810fc2..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ArrayTest.md +++ /dev/null @@ -1,15 +0,0 @@ - - -# ArrayTest - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**arrayOfString** | **List<String>** | | [optional] -**arrayArrayOfInteger** | **List<List<Long>>** | | [optional] -**arrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Banana.md b/samples/openapi3/client/petstore/java/native/docs/Banana.md deleted file mode 100644 index 7ddff9847a..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Banana.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Banana - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**lengthCm** | **BigDecimal** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/BananaReq.md b/samples/openapi3/client/petstore/java/native/docs/BananaReq.md deleted file mode 100644 index 35a773503b..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/BananaReq.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# BananaReq - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**lengthCm** | **BigDecimal** | | -**sweet** | **Boolean** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/BasquePig.md b/samples/openapi3/client/petstore/java/native/docs/BasquePig.md deleted file mode 100644 index 05d4cf3970..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/BasquePig.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# BasquePig - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**className** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Capitalization.md b/samples/openapi3/client/petstore/java/native/docs/Capitalization.md deleted file mode 100644 index ad8939b744..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Capitalization.md +++ /dev/null @@ -1,18 +0,0 @@ - - -# Capitalization - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**smallCamel** | **String** | | [optional] -**capitalCamel** | **String** | | [optional] -**smallSnake** | **String** | | [optional] -**capitalSnake** | **String** | | [optional] -**scAETHFlowPoints** | **String** | | [optional] -**ATT_NAME** | **String** | Name of the pet | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Cat.md b/samples/openapi3/client/petstore/java/native/docs/Cat.md deleted file mode 100644 index 87a3ab44a3..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Cat.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Cat - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**declawed** | **Boolean** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/CatAllOf.md b/samples/openapi3/client/petstore/java/native/docs/CatAllOf.md deleted file mode 100644 index 3fd01aaebf..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/CatAllOf.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# CatAllOf - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**declawed** | **Boolean** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Category.md b/samples/openapi3/client/petstore/java/native/docs/Category.md deleted file mode 100644 index d03ffbfd06..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Category.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# Category - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **Long** | | [optional] -**name** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ChildCat.md b/samples/openapi3/client/petstore/java/native/docs/ChildCat.md deleted file mode 100644 index da63b7067f..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ChildCat.md +++ /dev/null @@ -1,22 +0,0 @@ - - -# ChildCat - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] -**petType** | [**String**](#String) | | - - - -## Enum: String - -Name | Value ----- | ----- -CHILDCAT | "ChildCat" - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ChildCatAllOf.md b/samples/openapi3/client/petstore/java/native/docs/ChildCatAllOf.md deleted file mode 100644 index 35c6b1c43a..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ChildCatAllOf.md +++ /dev/null @@ -1,22 +0,0 @@ - - -# ChildCatAllOf - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] -**petType** | [**String**](#String) | | [optional] - - - -## Enum: String - -Name | Value ----- | ----- -CHILDCAT | "ChildCat" - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ClassModel.md b/samples/openapi3/client/petstore/java/native/docs/ClassModel.md deleted file mode 100644 index 04beba3384..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ClassModel.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# ClassModel - -Model for testing model with \"_class\" property - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**propertyClass** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Client.md b/samples/openapi3/client/petstore/java/native/docs/Client.md deleted file mode 100644 index 125a20b3fc..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Client.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Client - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**client** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ComplexQuadrilateral.md b/samples/openapi3/client/petstore/java/native/docs/ComplexQuadrilateral.md deleted file mode 100644 index 9e7a27f8a5..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ComplexQuadrilateral.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# ComplexQuadrilateral - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**shapeType** | **String** | | -**quadrilateralType** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/DanishPig.md b/samples/openapi3/client/petstore/java/native/docs/DanishPig.md deleted file mode 100644 index 0e86a67165..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/DanishPig.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# DanishPig - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**className** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/DefaultApi.md b/samples/openapi3/client/petstore/java/native/docs/DefaultApi.md deleted file mode 100644 index 75b7a51d2c..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/DefaultApi.md +++ /dev/null @@ -1,132 +0,0 @@ -# DefaultApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**fooGet**](DefaultApi.md#fooGet) | **GET** /foo | -[**fooGetWithHttpInfo**](DefaultApi.md#fooGetWithHttpInfo) | **GET** /foo | - - - -## fooGet - -> InlineResponseDefault fooGet() - - - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.DefaultApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - DefaultApi apiInstance = new DefaultApi(defaultClient); - try { - InlineResponseDefault result = apiInstance.fooGet(); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling DefaultApi#fooGet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -[**InlineResponseDefault**](InlineResponseDefault.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | response | - | - -## fooGetWithHttpInfo - -> ApiResponse fooGet fooGetWithHttpInfo() - - - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.DefaultApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - DefaultApi apiInstance = new DefaultApi(defaultClient); - try { - ApiResponse response = apiInstance.fooGetWithHttpInfo(); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling DefaultApi#fooGet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -ApiResponse<[**InlineResponseDefault**](InlineResponseDefault.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | response | - | - diff --git a/samples/openapi3/client/petstore/java/native/docs/DeprecatedObject.md b/samples/openapi3/client/petstore/java/native/docs/DeprecatedObject.md deleted file mode 100644 index d5128bdb84..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/DeprecatedObject.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# DeprecatedObject - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Dog.md b/samples/openapi3/client/petstore/java/native/docs/Dog.md deleted file mode 100644 index f4ba57fa3b..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Dog.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Dog - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**breed** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/DogAllOf.md b/samples/openapi3/client/petstore/java/native/docs/DogAllOf.md deleted file mode 100644 index 1f7e23d981..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/DogAllOf.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# DogAllOf - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**breed** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Drawing.md b/samples/openapi3/client/petstore/java/native/docs/Drawing.md deleted file mode 100644 index 0874f4811d..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Drawing.md +++ /dev/null @@ -1,16 +0,0 @@ - - -# Drawing - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**mainShape** | [**Shape**](Shape.md) | | [optional] -**shapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] -**nullableShape** | [**NullableShape**](NullableShape.md) | | [optional] -**shapes** | [**List<Shape>**](Shape.md) | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/EnumArrays.md b/samples/openapi3/client/petstore/java/native/docs/EnumArrays.md deleted file mode 100644 index 9450527672..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/EnumArrays.md +++ /dev/null @@ -1,32 +0,0 @@ - - -# EnumArrays - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**justSymbol** | [**JustSymbolEnum**](#JustSymbolEnum) | | [optional] -**arrayEnum** | [**List<ArrayEnumEnum>**](#List<ArrayEnumEnum>) | | [optional] - - - -## Enum: JustSymbolEnum - -Name | Value ----- | ----- -GREATER_THAN_OR_EQUAL_TO | ">=" -DOLLAR | "$" - - - -## Enum: List<ArrayEnumEnum> - -Name | Value ----- | ----- -FISH | "fish" -CRAB | "crab" - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/EnumTest.md b/samples/openapi3/client/petstore/java/native/docs/EnumTest.md deleted file mode 100644 index 342b462ccc..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/EnumTest.md +++ /dev/null @@ -1,68 +0,0 @@ - - -# EnumTest - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] -**enumStringRequired** | [**EnumStringRequiredEnum**](#EnumStringRequiredEnum) | | -**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] -**enumIntegerOnly** | [**EnumIntegerOnlyEnum**](#EnumIntegerOnlyEnum) | | [optional] -**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] -**outerEnum** | **OuterEnum** | | [optional] -**outerEnumInteger** | **OuterEnumInteger** | | [optional] -**outerEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] -**outerEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] - - - -## Enum: EnumStringEnum - -Name | Value ----- | ----- -UPPER | "UPPER" -LOWER | "lower" -EMPTY | "" - - - -## Enum: EnumStringRequiredEnum - -Name | Value ----- | ----- -UPPER | "UPPER" -LOWER | "lower" -EMPTY | "" - - - -## Enum: EnumIntegerEnum - -Name | Value ----- | ----- -NUMBER_1 | 1 -NUMBER_MINUS_1 | -1 - - - -## Enum: EnumIntegerOnlyEnum - -Name | Value ----- | ----- -NUMBER_2 | 2 -NUMBER_MINUS_2 | -2 - - - -## Enum: EnumNumberEnum - -Name | Value ----- | ----- -NUMBER_1_DOT_1 | 1.1 -NUMBER_MINUS_1_DOT_2 | -1.2 - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/EquilateralTriangle.md b/samples/openapi3/client/petstore/java/native/docs/EquilateralTriangle.md deleted file mode 100644 index e4b49735d6..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/EquilateralTriangle.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# EquilateralTriangle - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**shapeType** | **String** | | -**triangleType** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/FakeApi.md b/samples/openapi3/client/petstore/java/native/docs/FakeApi.md deleted file mode 100644 index 1ad9f946af..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/FakeApi.md +++ /dev/null @@ -1,2167 +0,0 @@ -# FakeApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**fakeHealthGet**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint -[**fakeHealthGetWithHttpInfo**](FakeApi.md#fakeHealthGetWithHttpInfo) | **GET** /fake/health | Health check endpoint -[**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | -[**fakeOuterBooleanSerializeWithHttpInfo**](FakeApi.md#fakeOuterBooleanSerializeWithHttpInfo) | **POST** /fake/outer/boolean | -[**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | -[**fakeOuterCompositeSerializeWithHttpInfo**](FakeApi.md#fakeOuterCompositeSerializeWithHttpInfo) | **POST** /fake/outer/composite | -[**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | -[**fakeOuterNumberSerializeWithHttpInfo**](FakeApi.md#fakeOuterNumberSerializeWithHttpInfo) | **POST** /fake/outer/number | -[**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | -[**fakeOuterStringSerializeWithHttpInfo**](FakeApi.md#fakeOuterStringSerializeWithHttpInfo) | **POST** /fake/outer/string | -[**getArrayOfEnums**](FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums -[**getArrayOfEnumsWithHttpInfo**](FakeApi.md#getArrayOfEnumsWithHttpInfo) | **GET** /fake/array-of-enums | Array of Enums -[**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | -[**testBodyWithFileSchemaWithHttpInfo**](FakeApi.md#testBodyWithFileSchemaWithHttpInfo) | **PUT** /fake/body-with-file-schema | -[**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | -[**testBodyWithQueryParamsWithHttpInfo**](FakeApi.md#testBodyWithQueryParamsWithHttpInfo) | **PUT** /fake/body-with-query-params | -[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model -[**testClientModelWithHttpInfo**](FakeApi.md#testClientModelWithHttpInfo) | **PATCH** /fake | To test \"client\" model -[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEndpointParametersWithHttpInfo**](FakeApi.md#testEndpointParametersWithHttpInfo) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters -[**testEnumParametersWithHttpInfo**](FakeApi.md#testEnumParametersWithHttpInfo) | **GET** /fake | To test enum parameters -[**testGroupParameters**](FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -[**testGroupParametersWithHttpInfo**](FakeApi.md#testGroupParametersWithHttpInfo) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -[**testInlineAdditionalPropertiesWithHttpInfo**](FakeApi.md#testInlineAdditionalPropertiesWithHttpInfo) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -[**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data -[**testJsonFormDataWithHttpInfo**](FakeApi.md#testJsonFormDataWithHttpInfo) | **GET** /fake/jsonFormData | test json serialization of form data -[**testQueryParameterCollectionFormat**](FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | -[**testQueryParameterCollectionFormatWithHttpInfo**](FakeApi.md#testQueryParameterCollectionFormatWithHttpInfo) | **PUT** /fake/test-query-parameters | - - - -## fakeHealthGet - -> HealthCheckResult fakeHealthGet() - -Health check endpoint - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - try { - HealthCheckResult result = apiInstance.fakeHealthGet(); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeHealthGet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -[**HealthCheckResult**](HealthCheckResult.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | The instance started successfully | - | - -## fakeHealthGetWithHttpInfo - -> ApiResponse fakeHealthGet fakeHealthGetWithHttpInfo() - -Health check endpoint - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - try { - ApiResponse response = apiInstance.fakeHealthGetWithHttpInfo(); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeHealthGet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -ApiResponse<[**HealthCheckResult**](HealthCheckResult.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | The instance started successfully | - | - - -## fakeOuterBooleanSerialize - -> Boolean fakeOuterBooleanSerialize(body) - - - -Test serialization of outer boolean types - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - Boolean body = true; // Boolean | Input boolean as post body - try { - Boolean result = apiInstance.fakeOuterBooleanSerialize(body); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeOuterBooleanSerialize"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **Boolean**| Input boolean as post body | [optional] - -### Return type - -**Boolean** - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: */* - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Output boolean | - | - -## fakeOuterBooleanSerializeWithHttpInfo - -> ApiResponse fakeOuterBooleanSerialize fakeOuterBooleanSerializeWithHttpInfo(body) - - - -Test serialization of outer boolean types - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - Boolean body = true; // Boolean | Input boolean as post body - try { - ApiResponse response = apiInstance.fakeOuterBooleanSerializeWithHttpInfo(body); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeOuterBooleanSerialize"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **Boolean**| Input boolean as post body | [optional] - -### Return type - -ApiResponse<**Boolean**> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: */* - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Output boolean | - | - - -## fakeOuterCompositeSerialize - -> OuterComposite fakeOuterCompositeSerialize(outerComposite) - - - -Test serialization of object with outer number type - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - OuterComposite outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body - try { - OuterComposite result = apiInstance.fakeOuterCompositeSerialize(outerComposite); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeOuterCompositeSerialize"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] - -### Return type - -[**OuterComposite**](OuterComposite.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: */* - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Output composite | - | - -## fakeOuterCompositeSerializeWithHttpInfo - -> ApiResponse fakeOuterCompositeSerialize fakeOuterCompositeSerializeWithHttpInfo(outerComposite) - - - -Test serialization of object with outer number type - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - OuterComposite outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body - try { - ApiResponse response = apiInstance.fakeOuterCompositeSerializeWithHttpInfo(outerComposite); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeOuterCompositeSerialize"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] - -### Return type - -ApiResponse<[**OuterComposite**](OuterComposite.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: */* - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Output composite | - | - - -## fakeOuterNumberSerialize - -> BigDecimal fakeOuterNumberSerialize(body) - - - -Test serialization of outer number types - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - BigDecimal body = new BigDecimal(78); // BigDecimal | Input number as post body - try { - BigDecimal result = apiInstance.fakeOuterNumberSerialize(body); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeOuterNumberSerialize"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **BigDecimal**| Input number as post body | [optional] - -### Return type - -[**BigDecimal**](BigDecimal.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: */* - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Output number | - | - -## fakeOuterNumberSerializeWithHttpInfo - -> ApiResponse fakeOuterNumberSerialize fakeOuterNumberSerializeWithHttpInfo(body) - - - -Test serialization of outer number types - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - BigDecimal body = new BigDecimal(78); // BigDecimal | Input number as post body - try { - ApiResponse response = apiInstance.fakeOuterNumberSerializeWithHttpInfo(body); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeOuterNumberSerialize"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **BigDecimal**| Input number as post body | [optional] - -### Return type - -ApiResponse<[**BigDecimal**](BigDecimal.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: */* - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Output number | - | - - -## fakeOuterStringSerialize - -> String fakeOuterStringSerialize(body) - - - -Test serialization of outer string types - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - String body = "body_example"; // String | Input string as post body - try { - String result = apiInstance.fakeOuterStringSerialize(body); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeOuterStringSerialize"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **String**| Input string as post body | [optional] - -### Return type - -**String** - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: */* - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Output string | - | - -## fakeOuterStringSerializeWithHttpInfo - -> ApiResponse fakeOuterStringSerialize fakeOuterStringSerializeWithHttpInfo(body) - - - -Test serialization of outer string types - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - String body = "body_example"; // String | Input string as post body - try { - ApiResponse response = apiInstance.fakeOuterStringSerializeWithHttpInfo(body); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#fakeOuterStringSerialize"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **String**| Input string as post body | [optional] - -### Return type - -ApiResponse<**String**> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: */* - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Output string | - | - - -## getArrayOfEnums - -> List getArrayOfEnums() - -Array of Enums - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - try { - List result = apiInstance.getArrayOfEnums(); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#getArrayOfEnums"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -[**List<OuterEnum>**](OuterEnum.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Got named array of enums | - | - -## getArrayOfEnumsWithHttpInfo - -> ApiResponse> getArrayOfEnums getArrayOfEnumsWithHttpInfo() - -Array of Enums - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - try { - ApiResponse> response = apiInstance.getArrayOfEnumsWithHttpInfo(); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#getArrayOfEnums"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -ApiResponse<[**List<OuterEnum>**](OuterEnum.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Got named array of enums | - | - - -## testBodyWithFileSchema - -> void testBodyWithFileSchema(fileSchemaTestClass) - - - -For this test, the body for this request much reference a schema named `File`. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - FileSchemaTestClass fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | - try { - apiInstance.testBodyWithFileSchema(fileSchemaTestClass); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testBodyWithFileSchema"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Success | - | - -## testBodyWithFileSchemaWithHttpInfo - -> ApiResponse testBodyWithFileSchema testBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass) - - - -For this test, the body for this request much reference a schema named `File`. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - FileSchemaTestClass fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | - try { - ApiResponse response = apiInstance.testBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testBodyWithFileSchema"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Success | - | - - -## testBodyWithQueryParams - -> void testBodyWithQueryParams(query, user) - - - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - String query = "query_example"; // String | - User user = new User(); // User | - try { - apiInstance.testBodyWithQueryParams(query, user); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testBodyWithQueryParams"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **query** | **String**| | - **user** | [**User**](User.md)| | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Success | - | - -## testBodyWithQueryParamsWithHttpInfo - -> ApiResponse testBodyWithQueryParams testBodyWithQueryParamsWithHttpInfo(query, user) - - - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - String query = "query_example"; // String | - User user = new User(); // User | - try { - ApiResponse response = apiInstance.testBodyWithQueryParamsWithHttpInfo(query, user); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testBodyWithQueryParams"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **query** | **String**| | - **user** | [**User**](User.md)| | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Success | - | - - -## testClientModel - -> Client testClientModel(client) - -To test \"client\" model - -To test \"client\" model - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - Client client = new Client(); // Client | client model - try { - Client result = apiInstance.testClientModel(client); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testClientModel"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md)| client model | - -### Return type - -[**Client**](Client.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -## testClientModelWithHttpInfo - -> ApiResponse testClientModel testClientModelWithHttpInfo(client) - -To test \"client\" model - -To test \"client\" model - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - Client client = new Client(); // Client | client model - try { - ApiResponse response = apiInstance.testClientModelWithHttpInfo(client); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testClientModel"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md)| client model | - -### Return type - -ApiResponse<[**Client**](Client.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - - -## testEndpointParameters - -> void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure HTTP basic authorization: http_basic_test - HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); - http_basic_test.setUsername("YOUR USERNAME"); - http_basic_test.setPassword("YOUR PASSWORD"); - - FakeApi apiInstance = new FakeApi(defaultClient); - BigDecimal number = new BigDecimal(78); // BigDecimal | None - Double _double = 3.4D; // Double | None - String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None - byte[] _byte = null; // byte[] | None - Integer integer = 56; // Integer | None - Integer int32 = 56; // Integer | None - Long int64 = 56L; // Long | None - Float _float = 3.4F; // Float | None - String string = "string_example"; // String | None - File binary = new File("/path/to/file"); // File | None - LocalDate date = new LocalDate(); // LocalDate | None - OffsetDateTime dateTime = OffsetDateTime.now(); // OffsetDateTime | None - String password = "password_example"; // String | None - String paramCallback = "paramCallback_example"; // String | None - try { - apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEndpointParameters"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **number** | **BigDecimal**| None | - **_double** | **Double**| None | - **patternWithoutDelimiter** | **String**| None | - **_byte** | **byte[]**| None | - **integer** | **Integer**| None | [optional] - **int32** | **Integer**| None | [optional] - **int64** | **Long**| None | [optional] - **_float** | **Float**| None | [optional] - **string** | **String**| None | [optional] - **binary** | **File**| None | [optional] - **date** | **LocalDate**| None | [optional] - **dateTime** | **OffsetDateTime**| None | [optional] [default to OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))] - **password** | **String**| None | [optional] - **paramCallback** | **String**| None | [optional] - -### Return type - - -null (empty response body) - -### Authorization - -[http_basic_test](../README.md#http_basic_test) - -### HTTP request headers - -- **Content-Type**: application/x-www-form-urlencoded -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid username supplied | - | -| **404** | User not found | - | - -## testEndpointParametersWithHttpInfo - -> ApiResponse testEndpointParameters testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure HTTP basic authorization: http_basic_test - HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); - http_basic_test.setUsername("YOUR USERNAME"); - http_basic_test.setPassword("YOUR PASSWORD"); - - FakeApi apiInstance = new FakeApi(defaultClient); - BigDecimal number = new BigDecimal(78); // BigDecimal | None - Double _double = 3.4D; // Double | None - String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None - byte[] _byte = null; // byte[] | None - Integer integer = 56; // Integer | None - Integer int32 = 56; // Integer | None - Long int64 = 56L; // Long | None - Float _float = 3.4F; // Float | None - String string = "string_example"; // String | None - File binary = new File("/path/to/file"); // File | None - LocalDate date = new LocalDate(); // LocalDate | None - OffsetDateTime dateTime = OffsetDateTime.now(); // OffsetDateTime | None - String password = "password_example"; // String | None - String paramCallback = "paramCallback_example"; // String | None - try { - ApiResponse response = apiInstance.testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEndpointParameters"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **number** | **BigDecimal**| None | - **_double** | **Double**| None | - **patternWithoutDelimiter** | **String**| None | - **_byte** | **byte[]**| None | - **integer** | **Integer**| None | [optional] - **int32** | **Integer**| None | [optional] - **int64** | **Long**| None | [optional] - **_float** | **Float**| None | [optional] - **string** | **String**| None | [optional] - **binary** | **File**| None | [optional] - **date** | **LocalDate**| None | [optional] - **dateTime** | **OffsetDateTime**| None | [optional] [default to OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))] - **password** | **String**| None | [optional] - **paramCallback** | **String**| None | [optional] - -### Return type - - -ApiResponse - -### Authorization - -[http_basic_test](../README.md#http_basic_test) - -### HTTP request headers - -- **Content-Type**: application/x-www-form-urlencoded -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid username supplied | - | -| **404** | User not found | - | - - -## testEnumParameters - -> void testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString) - -To test enum parameters - -To test enum parameters - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - List enumHeaderStringArray = Arrays.asList("$"); // List | Header parameter enum test (string array) - String enumHeaderString = "-efg"; // String | Header parameter enum test (string) - List enumQueryStringArray = Arrays.asList("$"); // List | Query parameter enum test (string array) - String enumQueryString = "-efg"; // String | Query parameter enum test (string) - Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) - Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) - List enumFormStringArray = "$"; // List | Form parameter enum test (string array) - String enumFormString = "-efg"; // String | Form parameter enum test (string) - try { - apiInstance.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumParameters"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] - **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] - **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] [enum: 1, -2] - **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] [enum: 1.1, -1.2] - **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] - **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/x-www-form-urlencoded -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid request | - | -| **404** | Not found | - | - -## testEnumParametersWithHttpInfo - -> ApiResponse testEnumParameters testEnumParametersWithHttpInfo(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString) - -To test enum parameters - -To test enum parameters - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - List enumHeaderStringArray = Arrays.asList("$"); // List | Header parameter enum test (string array) - String enumHeaderString = "-efg"; // String | Header parameter enum test (string) - List enumQueryStringArray = Arrays.asList("$"); // List | Query parameter enum test (string array) - String enumQueryString = "-efg"; // String | Query parameter enum test (string) - Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) - Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) - List enumFormStringArray = "$"; // List | Form parameter enum test (string array) - String enumFormString = "-efg"; // String | Form parameter enum test (string) - try { - ApiResponse response = apiInstance.testEnumParametersWithHttpInfo(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testEnumParameters"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] - **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] - **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] [enum: 1, -2] - **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] [enum: 1.1, -1.2] - **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] - **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/x-www-form-urlencoded -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid request | - | -| **404** | Not found | - | - - -## testGroupParameters - -> void testGroupParameters(testGroupParametersRequest) - -Fake endpoint to test group parameters (optional) - -Fake endpoint to test group parameters (optional) - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; -import org.openapitools.client.api.FakeApi.*; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure HTTP bearer authorization: bearer_test - HttpBearerAuth bearer_test = (HttpBearerAuth) defaultClient.getAuthentication("bearer_test"); - bearer_test.setBearerToken("BEARER TOKEN"); - - FakeApi apiInstance = new FakeApi(defaultClient); - Integer requiredStringGroup = 56; // Integer | Required String in group parameters - Boolean requiredBooleanGroup = true; // Boolean | Required Boolean in group parameters - Long requiredInt64Group = 56L; // Long | Required Integer in group parameters - Integer stringGroup = 56; // Integer | String in group parameters - Boolean booleanGroup = true; // Boolean | Boolean in group parameters - Long int64Group = 56L; // Long | Integer in group parameters - try { - APItestGroupParametersRequest request = APItestGroupParametersRequest.newBuilder() - .requiredStringGroup(requiredStringGroup) - .requiredBooleanGroup(requiredBooleanGroup) - .requiredInt64Group(requiredInt64Group) - .stringGroup(stringGroup) - .booleanGroup(booleanGroup) - .int64Group(int64Group) - .build(); - apiInstance.testGroupParameters(request); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testGroupParameters"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -| Name | Type | Description | Notes | -|------------- | ------------- | ------------- | -------------| -| testGroupParametersRequest | [**APItestGroupParametersRequest**](FakeApi.md#APItestGroupParametersRequest)|-|-| - -### Return type - - -null (empty response body) - -### Authorization - -[bearer_test](../README.md#bearer_test) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Someting wrong | - | - -## testGroupParametersWithHttpInfo - -> ApiResponse testGroupParameters testGroupParametersWithHttpInfo(testGroupParametersRequest) - -Fake endpoint to test group parameters (optional) - -Fake endpoint to test group parameters (optional) - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; -import org.openapitools.client.api.FakeApi.*; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure HTTP bearer authorization: bearer_test - HttpBearerAuth bearer_test = (HttpBearerAuth) defaultClient.getAuthentication("bearer_test"); - bearer_test.setBearerToken("BEARER TOKEN"); - - FakeApi apiInstance = new FakeApi(defaultClient); - Integer requiredStringGroup = 56; // Integer | Required String in group parameters - Boolean requiredBooleanGroup = true; // Boolean | Required Boolean in group parameters - Long requiredInt64Group = 56L; // Long | Required Integer in group parameters - Integer stringGroup = 56; // Integer | String in group parameters - Boolean booleanGroup = true; // Boolean | Boolean in group parameters - Long int64Group = 56L; // Long | Integer in group parameters - try { - APItestGroupParametersRequest request = APItestGroupParametersRequest.newBuilder() - .requiredStringGroup(requiredStringGroup) - .requiredBooleanGroup(requiredBooleanGroup) - .requiredInt64Group(requiredInt64Group) - .stringGroup(stringGroup) - .booleanGroup(booleanGroup) - .int64Group(int64Group) - .build(); - ApiResponse response = apiInstance.testGroupParametersWithHttpInfo(request); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testGroupParameters"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -| Name | Type | Description | Notes | -|------------- | ------------- | ------------- | -------------| -| testGroupParametersRequest | [**APItestGroupParametersRequest**](FakeApi.md#APItestGroupParametersRequest)|-|-| - -### Return type - - -ApiResponse - -### Authorization - -[bearer_test](../README.md#bearer_test) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Someting wrong | - | - - - -## APItestGroupParametersRequest -### Properties - -| Name | Type | Description | Notes | -| ------------- | ------------- | ------------- | -------------| - **requiredStringGroup** | **Integer** | Required String in group parameters | - **requiredBooleanGroup** | **Boolean** | Required Boolean in group parameters | - **requiredInt64Group** | **Long** | Required Integer in group parameters | - **stringGroup** | **Integer** | String in group parameters | [optional] - **booleanGroup** | **Boolean** | Boolean in group parameters | [optional] - **int64Group** | **Long** | Integer in group parameters | [optional] - - - -## testInlineAdditionalProperties - -> void testInlineAdditionalProperties(requestBody) - -test inline additionalProperties - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - Map requestBody = new HashMap(); // Map | request body - try { - apiInstance.testInlineAdditionalProperties(requestBody); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **requestBody** | [**Map<String, String>**](String.md)| request body | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -## testInlineAdditionalPropertiesWithHttpInfo - -> ApiResponse testInlineAdditionalProperties testInlineAdditionalPropertiesWithHttpInfo(requestBody) - -test inline additionalProperties - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - Map requestBody = new HashMap(); // Map | request body - try { - ApiResponse response = apiInstance.testInlineAdditionalPropertiesWithHttpInfo(requestBody); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **requestBody** | [**Map<String, String>**](String.md)| request body | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - - -## testJsonFormData - -> void testJsonFormData(param, param2) - -test json serialization of form data - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - String param = "param_example"; // String | field1 - String param2 = "param2_example"; // String | field2 - try { - apiInstance.testJsonFormData(param, param2); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testJsonFormData"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **param** | **String**| field1 | - **param2** | **String**| field2 | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/x-www-form-urlencoded -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -## testJsonFormDataWithHttpInfo - -> ApiResponse testJsonFormData testJsonFormDataWithHttpInfo(param, param2) - -test json serialization of form data - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - String param = "param_example"; // String | field1 - String param2 = "param2_example"; // String | field2 - try { - ApiResponse response = apiInstance.testJsonFormDataWithHttpInfo(param, param2); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testJsonFormData"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **param** | **String**| field1 | - **param2** | **String**| field2 | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/x-www-form-urlencoded -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - - -## testQueryParameterCollectionFormat - -> void testQueryParameterCollectionFormat(pipe, ioutil, http, url, context) - - - -To test the collection format in query parameters - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - List pipe = Arrays.asList(); // List | - List ioutil = Arrays.asList(); // List | - List http = Arrays.asList(); // List | - List url = Arrays.asList(); // List | - List context = Arrays.asList(); // List | - try { - apiInstance.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testQueryParameterCollectionFormat"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pipe** | [**List<String>**](String.md)| | - **ioutil** | [**List<String>**](String.md)| | - **http** | [**List<String>**](String.md)| | - **url** | [**List<String>**](String.md)| | - **context** | [**List<String>**](String.md)| | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Success | - | - -## testQueryParameterCollectionFormatWithHttpInfo - -> ApiResponse testQueryParameterCollectionFormat testQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context) - - - -To test the collection format in query parameters - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - FakeApi apiInstance = new FakeApi(defaultClient); - List pipe = Arrays.asList(); // List | - List ioutil = Arrays.asList(); // List | - List http = Arrays.asList(); // List | - List url = Arrays.asList(); // List | - List context = Arrays.asList(); // List | - try { - ApiResponse response = apiInstance.testQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testQueryParameterCollectionFormat"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pipe** | [**List<String>**](String.md)| | - **ioutil** | [**List<String>**](String.md)| | - **http** | [**List<String>**](String.md)| | - **url** | [**List<String>**](String.md)| | - **context** | [**List<String>**](String.md)| | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | Success | - | - diff --git a/samples/openapi3/client/petstore/java/native/docs/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/java/native/docs/FakeClassnameTags123Api.md deleted file mode 100644 index 0472427204..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/FakeClassnameTags123Api.md +++ /dev/null @@ -1,158 +0,0 @@ -# FakeClassnameTags123Api - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**testClassname**](FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case -[**testClassnameWithHttpInfo**](FakeClassnameTags123Api.md#testClassnameWithHttpInfo) | **PATCH** /fake_classname_test | To test class name in snake case - - - -## testClassname - -> Client testClassname(client) - -To test class name in snake case - -To test class name in snake case - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeClassnameTags123Api; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure API key authorization: api_key_query - ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); - api_key_query.setApiKey("YOUR API KEY"); - // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) - //api_key_query.setApiKeyPrefix("Token"); - - FakeClassnameTags123Api apiInstance = new FakeClassnameTags123Api(defaultClient); - Client client = new Client(); // Client | client model - try { - Client result = apiInstance.testClassname(client); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling FakeClassnameTags123Api#testClassname"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md)| client model | - -### Return type - -[**Client**](Client.md) - - -### Authorization - -[api_key_query](../README.md#api_key_query) - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -## testClassnameWithHttpInfo - -> ApiResponse testClassname testClassnameWithHttpInfo(client) - -To test class name in snake case - -To test class name in snake case - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.FakeClassnameTags123Api; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure API key authorization: api_key_query - ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); - api_key_query.setApiKey("YOUR API KEY"); - // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) - //api_key_query.setApiKeyPrefix("Token"); - - FakeClassnameTags123Api apiInstance = new FakeClassnameTags123Api(defaultClient); - Client client = new Client(); // Client | client model - try { - ApiResponse response = apiInstance.testClassnameWithHttpInfo(client); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling FakeClassnameTags123Api#testClassname"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md)| client model | - -### Return type - -ApiResponse<[**Client**](Client.md)> - - -### Authorization - -[api_key_query](../README.md#api_key_query) - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - diff --git a/samples/openapi3/client/petstore/java/native/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/java/native/docs/FileSchemaTestClass.md deleted file mode 100644 index 2602dc7461..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/FileSchemaTestClass.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# FileSchemaTestClass - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**file** | [**java.io.File**](java.io.File.md) | | [optional] -**files** | [**List<java.io.File>**](java.io.File.md) | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Foo.md b/samples/openapi3/client/petstore/java/native/docs/Foo.md deleted file mode 100644 index 7893cf3f44..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Foo.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Foo - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**bar** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/FormatTest.md b/samples/openapi3/client/petstore/java/native/docs/FormatTest.md deleted file mode 100644 index 91da637f08..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/FormatTest.md +++ /dev/null @@ -1,28 +0,0 @@ - - -# FormatTest - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | **Integer** | | [optional] -**int32** | **Integer** | | [optional] -**int64** | **Long** | | [optional] -**number** | **BigDecimal** | | -**_float** | **Float** | | [optional] -**_double** | **Double** | | [optional] -**decimal** | **BigDecimal** | | [optional] -**string** | **String** | | [optional] -**_byte** | **byte[]** | | -**binary** | **File** | | [optional] -**date** | **LocalDate** | | -**dateTime** | **OffsetDateTime** | | [optional] -**uuid** | **UUID** | | [optional] -**password** | **String** | | -**patternWithDigits** | **String** | A string that is a 10 digit number. Can have leading zeros. | [optional] -**patternWithDigitsAndDelimiter** | **String** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Fruit.md b/samples/openapi3/client/petstore/java/native/docs/Fruit.md deleted file mode 100644 index 41b3152250..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Fruit.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# Fruit - -## oneOf schemas -* [Apple](Apple.md) -* [Banana](Banana.md) - -## Example -```java -// Import classes: -import org.openapitools.client.model.Fruit; -import org.openapitools.client.model.Apple; -import org.openapitools.client.model.Banana; - -public class Example { - public static void main(String[] args) { - Fruit exampleFruit = new Fruit(); - - // create a new Apple - Apple exampleApple = new Apple(); - // set Fruit to Apple - exampleFruit.setActualInstance(exampleApple); - // to get back the Apple set earlier - Apple testApple = (Apple) exampleFruit.getActualInstance(); - - // create a new Banana - Banana exampleBanana = new Banana(); - // set Fruit to Banana - exampleFruit.setActualInstance(exampleBanana); - // to get back the Banana set earlier - Banana testBanana = (Banana) exampleFruit.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/FruitReq.md b/samples/openapi3/client/petstore/java/native/docs/FruitReq.md deleted file mode 100644 index 9d9c875cd3..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/FruitReq.md +++ /dev/null @@ -1,39 +0,0 @@ - - -# FruitReq - -## oneOf schemas -* [AppleReq](AppleReq.md) -* [BananaReq](BananaReq.md) - -NOTE: this class is nullable. - -## Example -```java -// Import classes: -import org.openapitools.client.model.FruitReq; -import org.openapitools.client.model.AppleReq; -import org.openapitools.client.model.BananaReq; - -public class Example { - public static void main(String[] args) { - FruitReq exampleFruitReq = new FruitReq(); - - // create a new AppleReq - AppleReq exampleAppleReq = new AppleReq(); - // set FruitReq to AppleReq - exampleFruitReq.setActualInstance(exampleAppleReq); - // to get back the AppleReq set earlier - AppleReq testAppleReq = (AppleReq) exampleFruitReq.getActualInstance(); - - // create a new BananaReq - BananaReq exampleBananaReq = new BananaReq(); - // set FruitReq to BananaReq - exampleFruitReq.setActualInstance(exampleBananaReq); - // to get back the BananaReq set earlier - BananaReq testBananaReq = (BananaReq) exampleFruitReq.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/GmFruit.md b/samples/openapi3/client/petstore/java/native/docs/GmFruit.md deleted file mode 100644 index c9dc50b92c..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/GmFruit.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# GmFruit - -## anyOf schemas -* [Apple](Apple.md) -* [Banana](Banana.md) - -## Example -```java -// Import classes: -import org.openapitools.client.model.GmFruit; -import org.openapitools.client.model.Apple; -import org.openapitools.client.model.Banana; - -public class Example { - public static void main(String[] args) { - GmFruit exampleGmFruit = new GmFruit(); - - // create a new Apple - Apple exampleApple = new Apple(); - // set GmFruit to Apple - exampleGmFruit.setActualInstance(exampleApple); - // to get back the Apple set earlier - Apple testApple = (Apple) exampleGmFruit.getActualInstance(); - - // create a new Banana - Banana exampleBanana = new Banana(); - // set GmFruit to Banana - exampleGmFruit.setActualInstance(exampleBanana); - // to get back the Banana set earlier - Banana testBanana = (Banana) exampleGmFruit.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/GrandparentAnimal.md b/samples/openapi3/client/petstore/java/native/docs/GrandparentAnimal.md deleted file mode 100644 index 8c7632266e..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/GrandparentAnimal.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# GrandparentAnimal - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**petType** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/java/native/docs/HasOnlyReadOnly.md deleted file mode 100644 index 6416f8f371..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/HasOnlyReadOnly.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# HasOnlyReadOnly - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**bar** | **String** | | [optional] [readonly] -**foo** | **String** | | [optional] [readonly] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/java/native/docs/HealthCheckResult.md deleted file mode 100644 index 80ba4783bb..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/HealthCheckResult.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# HealthCheckResult - -Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**nullableMessage** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/InlineObject.md b/samples/openapi3/client/petstore/java/native/docs/InlineObject.md deleted file mode 100644 index 999fe3ef00..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/InlineObject.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# InlineObject - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **String** | Updated name of the pet | [optional] -**status** | **String** | Updated status of the pet | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/InlineObject1.md b/samples/openapi3/client/petstore/java/native/docs/InlineObject1.md deleted file mode 100644 index 10cc19ce03..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/InlineObject1.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# InlineObject1 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**file** | **File** | file to upload | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/InlineObject2.md b/samples/openapi3/client/petstore/java/native/docs/InlineObject2.md deleted file mode 100644 index 7e4ed7591c..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/InlineObject2.md +++ /dev/null @@ -1,32 +0,0 @@ - - -# InlineObject2 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enumFormStringArray** | [**List<EnumFormStringArrayEnum>**](#List<EnumFormStringArrayEnum>) | Form parameter enum test (string array) | [optional] -**enumFormString** | [**EnumFormStringEnum**](#EnumFormStringEnum) | Form parameter enum test (string) | [optional] - - - -## Enum: List<EnumFormStringArrayEnum> - -Name | Value ----- | ----- -GREATER_THAN | ">" -DOLLAR | "$" - - - -## Enum: EnumFormStringEnum - -Name | Value ----- | ----- -_ABC | "_abc" -_EFG | "-efg" -_XYZ_ | "(xyz)" - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/InlineObject3.md b/samples/openapi3/client/petstore/java/native/docs/InlineObject3.md deleted file mode 100644 index fef7fdf803..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/InlineObject3.md +++ /dev/null @@ -1,25 +0,0 @@ - - -# InlineObject3 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | **Integer** | None | [optional] -**int32** | **Integer** | None | [optional] -**int64** | **Long** | None | [optional] -**number** | **BigDecimal** | None | -**_float** | **Float** | None | [optional] -**_double** | **Double** | None | -**string** | **String** | None | [optional] -**patternWithoutDelimiter** | **String** | None | -**_byte** | **byte[]** | None | -**binary** | **File** | None | [optional] -**date** | **LocalDate** | None | [optional] -**dateTime** | **OffsetDateTime** | None | [optional] -**password** | **String** | None | [optional] -**callback** | **String** | None | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/InlineObject4.md b/samples/openapi3/client/petstore/java/native/docs/InlineObject4.md deleted file mode 100644 index 5ebef87240..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/InlineObject4.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# InlineObject4 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**param** | **String** | field1 | -**param2** | **String** | field2 | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/InlineObject5.md b/samples/openapi3/client/petstore/java/native/docs/InlineObject5.md deleted file mode 100644 index ec5d4309f4..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/InlineObject5.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# InlineObject5 - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **String** | Additional data to pass to server | [optional] -**requiredFile** | **File** | file to upload | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/InlineResponseDefault.md b/samples/openapi3/client/petstore/java/native/docs/InlineResponseDefault.md deleted file mode 100644 index 1c7c639d48..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/InlineResponseDefault.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# InlineResponseDefault - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**string** | [**Foo**](Foo.md) | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/IsoscelesTriangle.md b/samples/openapi3/client/petstore/java/native/docs/IsoscelesTriangle.md deleted file mode 100644 index 535e921641..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/IsoscelesTriangle.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# IsoscelesTriangle - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**shapeType** | **String** | | -**triangleType** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Mammal.md b/samples/openapi3/client/petstore/java/native/docs/Mammal.md deleted file mode 100644 index 11bbff5e2b..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Mammal.md +++ /dev/null @@ -1,46 +0,0 @@ - - -# Mammal - -## oneOf schemas -* [Pig](Pig.md) -* [Whale](Whale.md) -* [Zebra](Zebra.md) - -## Example -```java -// Import classes: -import org.openapitools.client.model.Mammal; -import org.openapitools.client.model.Pig; -import org.openapitools.client.model.Whale; -import org.openapitools.client.model.Zebra; - -public class Example { - public static void main(String[] args) { - Mammal exampleMammal = new Mammal(); - - // create a new Pig - Pig examplePig = new Pig(); - // set Mammal to Pig - exampleMammal.setActualInstance(examplePig); - // to get back the Pig set earlier - Pig testPig = (Pig) exampleMammal.getActualInstance(); - - // create a new Whale - Whale exampleWhale = new Whale(); - // set Mammal to Whale - exampleMammal.setActualInstance(exampleWhale); - // to get back the Whale set earlier - Whale testWhale = (Whale) exampleMammal.getActualInstance(); - - // create a new Zebra - Zebra exampleZebra = new Zebra(); - // set Mammal to Zebra - exampleMammal.setActualInstance(exampleZebra); - // to get back the Zebra set earlier - Zebra testZebra = (Zebra) exampleMammal.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/MapTest.md b/samples/openapi3/client/petstore/java/native/docs/MapTest.md deleted file mode 100644 index 16f3ab9344..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/MapTest.md +++ /dev/null @@ -1,25 +0,0 @@ - - -# MapTest - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**mapMapOfString** | **Map<String, Map<String, String>>** | | [optional] -**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] -**directMap** | **Map<String, Boolean>** | | [optional] -**indirectMap** | **Map<String, Boolean>** | | [optional] - - - -## Enum: Map<String, InnerEnum> - -Name | Value ----- | ----- -UPPER | "UPPER" -LOWER | "lower" - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/java/native/docs/MixedPropertiesAndAdditionalPropertiesClass.md deleted file mode 100644 index 8bc2ed1571..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ /dev/null @@ -1,15 +0,0 @@ - - -# MixedPropertiesAndAdditionalPropertiesClass - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**uuid** | **UUID** | | [optional] -**dateTime** | **OffsetDateTime** | | [optional] -**map** | [**Map<String, Animal>**](Animal.md) | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Model200Response.md b/samples/openapi3/client/petstore/java/native/docs/Model200Response.md deleted file mode 100644 index 91c45e4942..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Model200Response.md +++ /dev/null @@ -1,15 +0,0 @@ - - -# Model200Response - -Model for testing model name starting with number - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **Integer** | | [optional] -**propertyClass** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ModelApiResponse.md b/samples/openapi3/client/petstore/java/native/docs/ModelApiResponse.md deleted file mode 100644 index aca98405e3..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ModelApiResponse.md +++ /dev/null @@ -1,15 +0,0 @@ - - -# ModelApiResponse - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**code** | **Integer** | | [optional] -**type** | **String** | | [optional] -**message** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ModelReturn.md b/samples/openapi3/client/petstore/java/native/docs/ModelReturn.md deleted file mode 100644 index 3684358a04..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ModelReturn.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# ModelReturn - -Model for testing reserved words - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**_return** | **Integer** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Name.md b/samples/openapi3/client/petstore/java/native/docs/Name.md deleted file mode 100644 index 219628217c..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Name.md +++ /dev/null @@ -1,17 +0,0 @@ - - -# Name - -Model for testing model name same as property name - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **Integer** | | -**snakeCase** | **Integer** | | [optional] [readonly] -**property** | **String** | | [optional] -**_123number** | **Integer** | | [optional] [readonly] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/NullableClass.md b/samples/openapi3/client/petstore/java/native/docs/NullableClass.md deleted file mode 100644 index c8152be3d3..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/NullableClass.md +++ /dev/null @@ -1,24 +0,0 @@ - - -# NullableClass - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integerProp** | **Integer** | | [optional] -**numberProp** | **BigDecimal** | | [optional] -**booleanProp** | **Boolean** | | [optional] -**stringProp** | **String** | | [optional] -**dateProp** | **LocalDate** | | [optional] -**datetimeProp** | **OffsetDateTime** | | [optional] -**arrayNullableProp** | **List<Object>** | | [optional] -**arrayAndItemsNullableProp** | **List<Object>** | | [optional] -**arrayItemsNullable** | **List<Object>** | | [optional] -**objectNullableProp** | **Map<String, Object>** | | [optional] -**objectAndItemsNullableProp** | **Map<String, Object>** | | [optional] -**objectItemsNullable** | **Map<String, Object>** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/NullableShape.md b/samples/openapi3/client/petstore/java/native/docs/NullableShape.md deleted file mode 100644 index 60c45b2684..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/NullableShape.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# NullableShape - -The value may be a shape or the 'null' value. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. - -## oneOf schemas -* [Quadrilateral](Quadrilateral.md) -* [Triangle](Triangle.md) - -NOTE: this class is nullable. - -## Example -```java -// Import classes: -import org.openapitools.client.model.NullableShape; -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.Triangle; - -public class Example { - public static void main(String[] args) { - NullableShape exampleNullableShape = new NullableShape(); - - // create a new Quadrilateral - Quadrilateral exampleQuadrilateral = new Quadrilateral(); - // set NullableShape to Quadrilateral - exampleNullableShape.setActualInstance(exampleQuadrilateral); - // to get back the Quadrilateral set earlier - Quadrilateral testQuadrilateral = (Quadrilateral) exampleNullableShape.getActualInstance(); - - // create a new Triangle - Triangle exampleTriangle = new Triangle(); - // set NullableShape to Triangle - exampleNullableShape.setActualInstance(exampleTriangle); - // to get back the Triangle set earlier - Triangle testTriangle = (Triangle) exampleNullableShape.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/NumberOnly.md b/samples/openapi3/client/petstore/java/native/docs/NumberOnly.md deleted file mode 100644 index 26c0b18032..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/NumberOnly.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# NumberOnly - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**justNumber** | **BigDecimal** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ObjectWithDeprecatedFields.md b/samples/openapi3/client/petstore/java/native/docs/ObjectWithDeprecatedFields.md deleted file mode 100644 index be55a96c3b..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ObjectWithDeprecatedFields.md +++ /dev/null @@ -1,16 +0,0 @@ - - -# ObjectWithDeprecatedFields - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**uuid** | **String** | | [optional] -**id** | **BigDecimal** | | [optional] -**deprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] -**bars** | **List<String>** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Order.md b/samples/openapi3/client/petstore/java/native/docs/Order.md deleted file mode 100644 index fa708e8824..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Order.md +++ /dev/null @@ -1,28 +0,0 @@ - - -# Order - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **Long** | | [optional] -**petId** | **Long** | | [optional] -**quantity** | **Integer** | | [optional] -**shipDate** | **OffsetDateTime** | | [optional] -**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] -**complete** | **Boolean** | | [optional] - - - -## Enum: StatusEnum - -Name | Value ----- | ----- -PLACED | "placed" -APPROVED | "approved" -DELIVERED | "delivered" - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/OuterComposite.md b/samples/openapi3/client/petstore/java/native/docs/OuterComposite.md deleted file mode 100644 index 7274cb0759..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/OuterComposite.md +++ /dev/null @@ -1,15 +0,0 @@ - - -# OuterComposite - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**myNumber** | **BigDecimal** | | [optional] -**myString** | **String** | | [optional] -**myBoolean** | **Boolean** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ParentPet.md b/samples/openapi3/client/petstore/java/native/docs/ParentPet.md deleted file mode 100644 index ad7e021966..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ParentPet.md +++ /dev/null @@ -1,12 +0,0 @@ - - -# ParentPet - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Pet.md b/samples/openapi3/client/petstore/java/native/docs/Pet.md deleted file mode 100644 index 8aab745368..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Pet.md +++ /dev/null @@ -1,28 +0,0 @@ - - -# Pet - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **Long** | | [optional] -**category** | [**Category**](Category.md) | | [optional] -**name** | **String** | | -**photoUrls** | **List<String>** | | -**tags** | [**List<Tag>**](Tag.md) | | [optional] -**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] - - - -## Enum: StatusEnum - -Name | Value ----- | ----- -AVAILABLE | "available" -PENDING | "pending" -SOLD | "sold" - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/PetApi.md b/samples/openapi3/client/petstore/java/native/docs/PetApi.md deleted file mode 100644 index 769d314895..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/PetApi.md +++ /dev/null @@ -1,1342 +0,0 @@ -# PetApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -[**addPetWithHttpInfo**](PetApi.md#addPetWithHttpInfo) | **POST** /pet | Add a new pet to the store -[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet -[**deletePetWithHttpInfo**](PetApi.md#deletePetWithHttpInfo) | **DELETE** /pet/{petId} | Deletes a pet -[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status -[**findPetsByStatusWithHttpInfo**](PetApi.md#findPetsByStatusWithHttpInfo) | **GET** /pet/findByStatus | Finds Pets by status -[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags -[**findPetsByTagsWithHttpInfo**](PetApi.md#findPetsByTagsWithHttpInfo) | **GET** /pet/findByTags | Finds Pets by tags -[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID -[**getPetByIdWithHttpInfo**](PetApi.md#getPetByIdWithHttpInfo) | **GET** /pet/{petId} | Find pet by ID -[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet -[**updatePetWithHttpInfo**](PetApi.md#updatePetWithHttpInfo) | **PUT** /pet | Update an existing pet -[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data -[**updatePetWithFormWithHttpInfo**](PetApi.md#updatePetWithFormWithHttpInfo) | **POST** /pet/{petId} | Updates a pet in the store with form data -[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image -[**uploadFileWithHttpInfo**](PetApi.md#uploadFileWithHttpInfo) | **POST** /pet/{petId}/uploadImage | uploads an image -[**uploadFileWithRequiredFile**](PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -[**uploadFileWithRequiredFileWithHttpInfo**](PetApi.md#uploadFileWithRequiredFileWithHttpInfo) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) - - - -## addPet - -> void addPet(pet) - -Add a new pet to the store - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store - try { - apiInstance.addPet(pet); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#addPet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | - -### Return type - - -null (empty response body) - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: application/json, application/xml -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **405** | Invalid input | - | - -## addPetWithHttpInfo - -> ApiResponse addPet addPetWithHttpInfo(pet) - -Add a new pet to the store - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store - try { - ApiResponse response = apiInstance.addPetWithHttpInfo(pet); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#addPet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | - -### Return type - - -ApiResponse - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: application/json, application/xml -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **405** | Invalid input | - | - - -## deletePet - -> void deletePet(petId, apiKey) - -Deletes a pet - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | Pet id to delete - String apiKey = "apiKey_example"; // String | - try { - apiInstance.deletePet(petId, apiKey); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#deletePet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| Pet id to delete | - **apiKey** | **String**| | [optional] - -### Return type - - -null (empty response body) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid pet value | - | - -## deletePetWithHttpInfo - -> ApiResponse deletePet deletePetWithHttpInfo(petId, apiKey) - -Deletes a pet - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | Pet id to delete - String apiKey = "apiKey_example"; // String | - try { - ApiResponse response = apiInstance.deletePetWithHttpInfo(petId, apiKey); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#deletePet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| Pet id to delete | - **apiKey** | **String**| | [optional] - -### Return type - - -ApiResponse - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid pet value | - | - - -## findPetsByStatus - -> List findPetsByStatus(status) - -Finds Pets by status - -Multiple status values can be provided with comma separated strings - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - List status = Arrays.asList("available"); // List | Status values that need to be considered for filter - try { - List result = apiInstance.findPetsByStatus(status); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#findPetsByStatus"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] - -### Return type - -[**List<Pet>**](Pet.md) - - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid status value | - | - -## findPetsByStatusWithHttpInfo - -> ApiResponse> findPetsByStatus findPetsByStatusWithHttpInfo(status) - -Finds Pets by status - -Multiple status values can be provided with comma separated strings - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - List status = Arrays.asList("available"); // List | Status values that need to be considered for filter - try { - ApiResponse> response = apiInstance.findPetsByStatusWithHttpInfo(status); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#findPetsByStatus"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] - -### Return type - -ApiResponse<[**List<Pet>**](Pet.md)> - - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid status value | - | - - -## findPetsByTags - -> List findPetsByTags(tags) - -Finds Pets by tags - -Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - List tags = Arrays.asList(); // List | Tags to filter by - try { - List result = apiInstance.findPetsByTags(tags); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#findPetsByTags"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **tags** | [**List<String>**](String.md)| Tags to filter by | - -### Return type - -[**List<Pet>**](Pet.md) - - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid tag value | - | - -## findPetsByTagsWithHttpInfo - -> ApiResponse> findPetsByTags findPetsByTagsWithHttpInfo(tags) - -Finds Pets by tags - -Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - List tags = Arrays.asList(); // List | Tags to filter by - try { - ApiResponse> response = apiInstance.findPetsByTagsWithHttpInfo(tags); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#findPetsByTags"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **tags** | [**List<String>**](String.md)| Tags to filter by | - -### Return type - -ApiResponse<[**List<Pet>**](Pet.md)> - - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid tag value | - | - - -## getPetById - -> Pet getPetById(petId) - -Find pet by ID - -Returns a single pet - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure API key authorization: api_key - ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); - api_key.setApiKey("YOUR API KEY"); - // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) - //api_key.setApiKeyPrefix("Token"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | ID of pet to return - try { - Pet result = apiInstance.getPetById(petId); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#getPetById"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| ID of pet to return | - -### Return type - -[**Pet**](Pet.md) - - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid ID supplied | - | -| **404** | Pet not found | - | - -## getPetByIdWithHttpInfo - -> ApiResponse getPetById getPetByIdWithHttpInfo(petId) - -Find pet by ID - -Returns a single pet - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure API key authorization: api_key - ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); - api_key.setApiKey("YOUR API KEY"); - // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) - //api_key.setApiKeyPrefix("Token"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | ID of pet to return - try { - ApiResponse response = apiInstance.getPetByIdWithHttpInfo(petId); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#getPetById"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| ID of pet to return | - -### Return type - -ApiResponse<[**Pet**](Pet.md)> - - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid ID supplied | - | -| **404** | Pet not found | - | - - -## updatePet - -> void updatePet(pet) - -Update an existing pet - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store - try { - apiInstance.updatePet(pet); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#updatePet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | - -### Return type - - -null (empty response body) - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: application/json, application/xml -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid ID supplied | - | -| **404** | Pet not found | - | -| **405** | Validation exception | - | - -## updatePetWithHttpInfo - -> ApiResponse updatePet updatePetWithHttpInfo(pet) - -Update an existing pet - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store - try { - ApiResponse response = apiInstance.updatePetWithHttpInfo(pet); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#updatePet"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | - -### Return type - - -ApiResponse - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: application/json, application/xml -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid ID supplied | - | -| **404** | Pet not found | - | -| **405** | Validation exception | - | - - -## updatePetWithForm - -> void updatePetWithForm(petId, name, status) - -Updates a pet in the store with form data - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | ID of pet that needs to be updated - String name = "name_example"; // String | Updated name of the pet - String status = "status_example"; // String | Updated status of the pet - try { - apiInstance.updatePetWithForm(petId, name, status); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#updatePetWithForm"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| ID of pet that needs to be updated | - **name** | **String**| Updated name of the pet | [optional] - **status** | **String**| Updated status of the pet | [optional] - -### Return type - - -null (empty response body) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: application/x-www-form-urlencoded -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **405** | Invalid input | - | - -## updatePetWithFormWithHttpInfo - -> ApiResponse updatePetWithForm updatePetWithFormWithHttpInfo(petId, name, status) - -Updates a pet in the store with form data - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | ID of pet that needs to be updated - String name = "name_example"; // String | Updated name of the pet - String status = "status_example"; // String | Updated status of the pet - try { - ApiResponse response = apiInstance.updatePetWithFormWithHttpInfo(petId, name, status); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#updatePetWithForm"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| ID of pet that needs to be updated | - **name** | **String**| Updated name of the pet | [optional] - **status** | **String**| Updated status of the pet | [optional] - -### Return type - - -ApiResponse - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: application/x-www-form-urlencoded -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **405** | Invalid input | - | - - -## uploadFile - -> ModelApiResponse uploadFile(petId, additionalMetadata, file) - -uploads an image - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | ID of pet to update - String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server - File file = new File("/path/to/file"); // File | file to upload - try { - ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#uploadFile"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| ID of pet to update | - **additionalMetadata** | **String**| Additional data to pass to server | [optional] - **file** | **File**| file to upload | [optional] - -### Return type - -[**ModelApiResponse**](ModelApiResponse.md) - - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: multipart/form-data -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -## uploadFileWithHttpInfo - -> ApiResponse uploadFile uploadFileWithHttpInfo(petId, additionalMetadata, file) - -uploads an image - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | ID of pet to update - String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server - File file = new File("/path/to/file"); // File | file to upload - try { - ApiResponse response = apiInstance.uploadFileWithHttpInfo(petId, additionalMetadata, file); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#uploadFile"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| ID of pet to update | - **additionalMetadata** | **String**| Additional data to pass to server | [optional] - **file** | **File**| file to upload | [optional] - -### Return type - -ApiResponse<[**ModelApiResponse**](ModelApiResponse.md)> - - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: multipart/form-data -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - - -## uploadFileWithRequiredFile - -> ModelApiResponse uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata) - -uploads an image (required) - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | ID of pet to update - File requiredFile = new File("/path/to/file"); // File | file to upload - String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server - try { - ModelApiResponse result = apiInstance.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#uploadFileWithRequiredFile"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| ID of pet to update | - **requiredFile** | **File**| file to upload | - **additionalMetadata** | **String**| Additional data to pass to server | [optional] - -### Return type - -[**ModelApiResponse**](ModelApiResponse.md) - - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: multipart/form-data -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -## uploadFileWithRequiredFileWithHttpInfo - -> ApiResponse uploadFileWithRequiredFile uploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata) - -uploads an image (required) - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - PetApi apiInstance = new PetApi(defaultClient); - Long petId = 56L; // Long | ID of pet to update - File requiredFile = new File("/path/to/file"); // File | file to upload - String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server - try { - ApiResponse response = apiInstance.uploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling PetApi#uploadFileWithRequiredFile"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **petId** | **Long**| ID of pet to update | - **requiredFile** | **File**| file to upload | - **additionalMetadata** | **String**| Additional data to pass to server | [optional] - -### Return type - -ApiResponse<[**ModelApiResponse**](ModelApiResponse.md)> - - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -### HTTP request headers - -- **Content-Type**: multipart/form-data -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - diff --git a/samples/openapi3/client/petstore/java/native/docs/Pig.md b/samples/openapi3/client/petstore/java/native/docs/Pig.md deleted file mode 100644 index f0a92bbe61..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Pig.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# Pig - -## oneOf schemas -* [BasquePig](BasquePig.md) -* [DanishPig](DanishPig.md) - -## Example -```java -// Import classes: -import org.openapitools.client.model.Pig; -import org.openapitools.client.model.BasquePig; -import org.openapitools.client.model.DanishPig; - -public class Example { - public static void main(String[] args) { - Pig examplePig = new Pig(); - - // create a new BasquePig - BasquePig exampleBasquePig = new BasquePig(); - // set Pig to BasquePig - examplePig.setActualInstance(exampleBasquePig); - // to get back the BasquePig set earlier - BasquePig testBasquePig = (BasquePig) examplePig.getActualInstance(); - - // create a new DanishPig - DanishPig exampleDanishPig = new DanishPig(); - // set Pig to DanishPig - examplePig.setActualInstance(exampleDanishPig); - // to get back the DanishPig set earlier - DanishPig testDanishPig = (DanishPig) examplePig.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Quadrilateral.md b/samples/openapi3/client/petstore/java/native/docs/Quadrilateral.md deleted file mode 100644 index 83ffea0c74..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Quadrilateral.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# Quadrilateral - -## oneOf schemas -* [ComplexQuadrilateral](ComplexQuadrilateral.md) -* [SimpleQuadrilateral](SimpleQuadrilateral.md) - -## Example -```java -// Import classes: -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.ComplexQuadrilateral; -import org.openapitools.client.model.SimpleQuadrilateral; - -public class Example { - public static void main(String[] args) { - Quadrilateral exampleQuadrilateral = new Quadrilateral(); - - // create a new ComplexQuadrilateral - ComplexQuadrilateral exampleComplexQuadrilateral = new ComplexQuadrilateral(); - // set Quadrilateral to ComplexQuadrilateral - exampleQuadrilateral.setActualInstance(exampleComplexQuadrilateral); - // to get back the ComplexQuadrilateral set earlier - ComplexQuadrilateral testComplexQuadrilateral = (ComplexQuadrilateral) exampleQuadrilateral.getActualInstance(); - - // create a new SimpleQuadrilateral - SimpleQuadrilateral exampleSimpleQuadrilateral = new SimpleQuadrilateral(); - // set Quadrilateral to SimpleQuadrilateral - exampleQuadrilateral.setActualInstance(exampleSimpleQuadrilateral); - // to get back the SimpleQuadrilateral set earlier - SimpleQuadrilateral testSimpleQuadrilateral = (SimpleQuadrilateral) exampleQuadrilateral.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/QuadrilateralInterface.md b/samples/openapi3/client/petstore/java/native/docs/QuadrilateralInterface.md deleted file mode 100644 index a26b271077..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/QuadrilateralInterface.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# QuadrilateralInterface - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**quadrilateralType** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/java/native/docs/ReadOnlyFirst.md deleted file mode 100644 index a329bf4419..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ReadOnlyFirst.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# ReadOnlyFirst - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**bar** | **String** | | [optional] [readonly] -**baz** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ScaleneTriangle.md b/samples/openapi3/client/petstore/java/native/docs/ScaleneTriangle.md deleted file mode 100644 index f49fe5a12f..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ScaleneTriangle.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# ScaleneTriangle - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**shapeType** | **String** | | -**triangleType** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Shape.md b/samples/openapi3/client/petstore/java/native/docs/Shape.md deleted file mode 100644 index 9c237eefb0..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Shape.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# Shape - -## oneOf schemas -* [Quadrilateral](Quadrilateral.md) -* [Triangle](Triangle.md) - -## Example -```java -// Import classes: -import org.openapitools.client.model.Shape; -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.Triangle; - -public class Example { - public static void main(String[] args) { - Shape exampleShape = new Shape(); - - // create a new Quadrilateral - Quadrilateral exampleQuadrilateral = new Quadrilateral(); - // set Shape to Quadrilateral - exampleShape.setActualInstance(exampleQuadrilateral); - // to get back the Quadrilateral set earlier - Quadrilateral testQuadrilateral = (Quadrilateral) exampleShape.getActualInstance(); - - // create a new Triangle - Triangle exampleTriangle = new Triangle(); - // set Shape to Triangle - exampleShape.setActualInstance(exampleTriangle); - // to get back the Triangle set earlier - Triangle testTriangle = (Triangle) exampleShape.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ShapeInterface.md b/samples/openapi3/client/petstore/java/native/docs/ShapeInterface.md deleted file mode 100644 index f8b65a8a97..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ShapeInterface.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# ShapeInterface - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**shapeType** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/ShapeOrNull.md b/samples/openapi3/client/petstore/java/native/docs/ShapeOrNull.md deleted file mode 100644 index 6a738c4b98..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/ShapeOrNull.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# ShapeOrNull - -The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. - -## oneOf schemas -* [Quadrilateral](Quadrilateral.md) -* [Triangle](Triangle.md) - -NOTE: this class is nullable. - -## Example -```java -// Import classes: -import org.openapitools.client.model.ShapeOrNull; -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.Triangle; - -public class Example { - public static void main(String[] args) { - ShapeOrNull exampleShapeOrNull = new ShapeOrNull(); - - // create a new Quadrilateral - Quadrilateral exampleQuadrilateral = new Quadrilateral(); - // set ShapeOrNull to Quadrilateral - exampleShapeOrNull.setActualInstance(exampleQuadrilateral); - // to get back the Quadrilateral set earlier - Quadrilateral testQuadrilateral = (Quadrilateral) exampleShapeOrNull.getActualInstance(); - - // create a new Triangle - Triangle exampleTriangle = new Triangle(); - // set ShapeOrNull to Triangle - exampleShapeOrNull.setActualInstance(exampleTriangle); - // to get back the Triangle set earlier - Triangle testTriangle = (Triangle) exampleShapeOrNull.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/SimpleQuadrilateral.md b/samples/openapi3/client/petstore/java/native/docs/SimpleQuadrilateral.md deleted file mode 100644 index c2cf751d1b..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/SimpleQuadrilateral.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# SimpleQuadrilateral - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**shapeType** | **String** | | -**quadrilateralType** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/SpecialModelName.md b/samples/openapi3/client/petstore/java/native/docs/SpecialModelName.md deleted file mode 100644 index 352611142d..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/SpecialModelName.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# SpecialModelName - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**$specialPropertyName** | **Long** | | [optional] -**specialModelName** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/StoreApi.md b/samples/openapi3/client/petstore/java/native/docs/StoreApi.md deleted file mode 100644 index 0d685762bf..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/StoreApi.md +++ /dev/null @@ -1,560 +0,0 @@ -# StoreApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -[**deleteOrderWithHttpInfo**](StoreApi.md#deleteOrderWithHttpInfo) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -[**getInventoryWithHttpInfo**](StoreApi.md#getInventoryWithHttpInfo) | **GET** /store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID -[**getOrderByIdWithHttpInfo**](StoreApi.md#getOrderByIdWithHttpInfo) | **GET** /store/order/{order_id} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet -[**placeOrderWithHttpInfo**](StoreApi.md#placeOrderWithHttpInfo) | **POST** /store/order | Place an order for a pet - - - -## deleteOrder - -> void deleteOrder(orderId) - -Delete purchase order by ID - -For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.StoreApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - StoreApi apiInstance = new StoreApi(defaultClient); - String orderId = "orderId_example"; // String | ID of the order that needs to be deleted - try { - apiInstance.deleteOrder(orderId); - } catch (ApiException e) { - System.err.println("Exception when calling StoreApi#deleteOrder"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **orderId** | **String**| ID of the order that needs to be deleted | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid ID supplied | - | -| **404** | Order not found | - | - -## deleteOrderWithHttpInfo - -> ApiResponse deleteOrder deleteOrderWithHttpInfo(orderId) - -Delete purchase order by ID - -For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.StoreApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - StoreApi apiInstance = new StoreApi(defaultClient); - String orderId = "orderId_example"; // String | ID of the order that needs to be deleted - try { - ApiResponse response = apiInstance.deleteOrderWithHttpInfo(orderId); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling StoreApi#deleteOrder"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **orderId** | **String**| ID of the order that needs to be deleted | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid ID supplied | - | -| **404** | Order not found | - | - - -## getInventory - -> Map getInventory() - -Returns pet inventories by status - -Returns a map of status codes to quantities - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.StoreApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure API key authorization: api_key - ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); - api_key.setApiKey("YOUR API KEY"); - // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) - //api_key.setApiKeyPrefix("Token"); - - StoreApi apiInstance = new StoreApi(defaultClient); - try { - Map result = apiInstance.getInventory(); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling StoreApi#getInventory"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -**Map<String, Integer>** - - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - -## getInventoryWithHttpInfo - -> ApiResponse> getInventory getInventoryWithHttpInfo() - -Returns pet inventories by status - -Returns a map of status codes to quantities - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; -import org.openapitools.client.api.StoreApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - // Configure API key authorization: api_key - ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); - api_key.setApiKey("YOUR API KEY"); - // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) - //api_key.setApiKeyPrefix("Token"); - - StoreApi apiInstance = new StoreApi(defaultClient); - try { - ApiResponse> response = apiInstance.getInventoryWithHttpInfo(); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling StoreApi#getInventory"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - -ApiResponse<**Map<String, Integer>**> - - -### Authorization - -[api_key](../README.md#api_key) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | - - -## getOrderById - -> Order getOrderById(orderId) - -Find purchase order by ID - -For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.StoreApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - StoreApi apiInstance = new StoreApi(defaultClient); - Long orderId = 56L; // Long | ID of pet that needs to be fetched - try { - Order result = apiInstance.getOrderById(orderId); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling StoreApi#getOrderById"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **orderId** | **Long**| ID of pet that needs to be fetched | - -### Return type - -[**Order**](Order.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid ID supplied | - | -| **404** | Order not found | - | - -## getOrderByIdWithHttpInfo - -> ApiResponse getOrderById getOrderByIdWithHttpInfo(orderId) - -Find purchase order by ID - -For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.StoreApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - StoreApi apiInstance = new StoreApi(defaultClient); - Long orderId = 56L; // Long | ID of pet that needs to be fetched - try { - ApiResponse response = apiInstance.getOrderByIdWithHttpInfo(orderId); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling StoreApi#getOrderById"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **orderId** | **Long**| ID of pet that needs to be fetched | - -### Return type - -ApiResponse<[**Order**](Order.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid ID supplied | - | -| **404** | Order not found | - | - - -## placeOrder - -> Order placeOrder(order) - -Place an order for a pet - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.StoreApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - StoreApi apiInstance = new StoreApi(defaultClient); - Order order = new Order(); // Order | order placed for purchasing the pet - try { - Order result = apiInstance.placeOrder(order); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling StoreApi#placeOrder"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **order** | [**Order**](Order.md)| order placed for purchasing the pet | - -### Return type - -[**Order**](Order.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid Order | - | - -## placeOrderWithHttpInfo - -> ApiResponse placeOrder placeOrderWithHttpInfo(order) - -Place an order for a pet - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.StoreApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - StoreApi apiInstance = new StoreApi(defaultClient); - Order order = new Order(); // Order | order placed for purchasing the pet - try { - ApiResponse response = apiInstance.placeOrderWithHttpInfo(order); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling StoreApi#placeOrder"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **order** | [**Order**](Order.md)| order placed for purchasing the pet | - -### Return type - -ApiResponse<[**Order**](Order.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid Order | - | - diff --git a/samples/openapi3/client/petstore/java/native/docs/Tag.md b/samples/openapi3/client/petstore/java/native/docs/Tag.md deleted file mode 100644 index 70d36f5d0d..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Tag.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# Tag - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **Long** | | [optional] -**name** | **String** | | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Triangle.md b/samples/openapi3/client/petstore/java/native/docs/Triangle.md deleted file mode 100644 index daf9d153ff..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Triangle.md +++ /dev/null @@ -1,46 +0,0 @@ - - -# Triangle - -## oneOf schemas -* [EquilateralTriangle](EquilateralTriangle.md) -* [IsoscelesTriangle](IsoscelesTriangle.md) -* [ScaleneTriangle](ScaleneTriangle.md) - -## Example -```java -// Import classes: -import org.openapitools.client.model.Triangle; -import org.openapitools.client.model.EquilateralTriangle; -import org.openapitools.client.model.IsoscelesTriangle; -import org.openapitools.client.model.ScaleneTriangle; - -public class Example { - public static void main(String[] args) { - Triangle exampleTriangle = new Triangle(); - - // create a new EquilateralTriangle - EquilateralTriangle exampleEquilateralTriangle = new EquilateralTriangle(); - // set Triangle to EquilateralTriangle - exampleTriangle.setActualInstance(exampleEquilateralTriangle); - // to get back the EquilateralTriangle set earlier - EquilateralTriangle testEquilateralTriangle = (EquilateralTriangle) exampleTriangle.getActualInstance(); - - // create a new IsoscelesTriangle - IsoscelesTriangle exampleIsoscelesTriangle = new IsoscelesTriangle(); - // set Triangle to IsoscelesTriangle - exampleTriangle.setActualInstance(exampleIsoscelesTriangle); - // to get back the IsoscelesTriangle set earlier - IsoscelesTriangle testIsoscelesTriangle = (IsoscelesTriangle) exampleTriangle.getActualInstance(); - - // create a new ScaleneTriangle - ScaleneTriangle exampleScaleneTriangle = new ScaleneTriangle(); - // set Triangle to ScaleneTriangle - exampleTriangle.setActualInstance(exampleScaleneTriangle); - // to get back the ScaleneTriangle set earlier - ScaleneTriangle testScaleneTriangle = (ScaleneTriangle) exampleTriangle.getActualInstance(); - } -} -``` - - diff --git a/samples/openapi3/client/petstore/java/native/docs/TriangleInterface.md b/samples/openapi3/client/petstore/java/native/docs/TriangleInterface.md deleted file mode 100644 index 525872029f..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/TriangleInterface.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# TriangleInterface - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**triangleType** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/User.md b/samples/openapi3/client/petstore/java/native/docs/User.md deleted file mode 100644 index c29bce5c12..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/User.md +++ /dev/null @@ -1,24 +0,0 @@ - - -# User - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **Long** | | [optional] -**username** | **String** | | [optional] -**firstName** | **String** | | [optional] -**lastName** | **String** | | [optional] -**email** | **String** | | [optional] -**password** | **String** | | [optional] -**phone** | **String** | | [optional] -**userStatus** | **Integer** | User Status | [optional] -**objectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] -**objectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] -**anyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] -**anyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/UserApi.md b/samples/openapi3/client/petstore/java/native/docs/UserApi.md deleted file mode 100644 index 2fc189e761..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/UserApi.md +++ /dev/null @@ -1,1074 +0,0 @@ -# UserApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**createUser**](UserApi.md#createUser) | **POST** /user | Create user -[**createUserWithHttpInfo**](UserApi.md#createUserWithHttpInfo) | **POST** /user | Create user -[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array -[**createUsersWithArrayInputWithHttpInfo**](UserApi.md#createUsersWithArrayInputWithHttpInfo) | **POST** /user/createWithArray | Creates list of users with given input array -[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array -[**createUsersWithListInputWithHttpInfo**](UserApi.md#createUsersWithListInputWithHttpInfo) | **POST** /user/createWithList | Creates list of users with given input array -[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user -[**deleteUserWithHttpInfo**](UserApi.md#deleteUserWithHttpInfo) | **DELETE** /user/{username} | Delete user -[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name -[**getUserByNameWithHttpInfo**](UserApi.md#getUserByNameWithHttpInfo) | **GET** /user/{username} | Get user by user name -[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system -[**loginUserWithHttpInfo**](UserApi.md#loginUserWithHttpInfo) | **GET** /user/login | Logs user into the system -[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session -[**logoutUserWithHttpInfo**](UserApi.md#logoutUserWithHttpInfo) | **GET** /user/logout | Logs out current logged in user session -[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user -[**updateUserWithHttpInfo**](UserApi.md#updateUserWithHttpInfo) | **PUT** /user/{username} | Updated user - - - -## createUser - -> void createUser(user) - -Create user - -This can only be done by the logged in user. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - User user = new User(); // User | Created user object - try { - apiInstance.createUser(user); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#createUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**User**](User.md)| Created user object | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - -## createUserWithHttpInfo - -> ApiResponse createUser createUserWithHttpInfo(user) - -Create user - -This can only be done by the logged in user. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - User user = new User(); // User | Created user object - try { - ApiResponse response = apiInstance.createUserWithHttpInfo(user); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#createUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**User**](User.md)| Created user object | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - - -## createUsersWithArrayInput - -> void createUsersWithArrayInput(user) - -Creates list of users with given input array - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - List user = Arrays.asList(); // List | List of user object - try { - apiInstance.createUsersWithArrayInput(user); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**List<User>**](User.md)| List of user object | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - -## createUsersWithArrayInputWithHttpInfo - -> ApiResponse createUsersWithArrayInput createUsersWithArrayInputWithHttpInfo(user) - -Creates list of users with given input array - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - List user = Arrays.asList(); // List | List of user object - try { - ApiResponse response = apiInstance.createUsersWithArrayInputWithHttpInfo(user); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**List<User>**](User.md)| List of user object | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - - -## createUsersWithListInput - -> void createUsersWithListInput(user) - -Creates list of users with given input array - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - List user = Arrays.asList(); // List | List of user object - try { - apiInstance.createUsersWithListInput(user); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#createUsersWithListInput"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**List<User>**](User.md)| List of user object | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - -## createUsersWithListInputWithHttpInfo - -> ApiResponse createUsersWithListInput createUsersWithListInputWithHttpInfo(user) - -Creates list of users with given input array - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - List user = Arrays.asList(); // List | List of user object - try { - ApiResponse response = apiInstance.createUsersWithListInputWithHttpInfo(user); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#createUsersWithListInput"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **user** | [**List<User>**](User.md)| List of user object | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - - -## deleteUser - -> void deleteUser(username) - -Delete user - -This can only be done by the logged in user. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - String username = "username_example"; // String | The name that needs to be deleted - try { - apiInstance.deleteUser(username); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#deleteUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **String**| The name that needs to be deleted | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid username supplied | - | -| **404** | User not found | - | - -## deleteUserWithHttpInfo - -> ApiResponse deleteUser deleteUserWithHttpInfo(username) - -Delete user - -This can only be done by the logged in user. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - String username = "username_example"; // String | The name that needs to be deleted - try { - ApiResponse response = apiInstance.deleteUserWithHttpInfo(username); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#deleteUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **String**| The name that needs to be deleted | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid username supplied | - | -| **404** | User not found | - | - - -## getUserByName - -> User getUserByName(username) - -Get user by user name - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. - try { - User result = apiInstance.getUserByName(username); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#getUserByName"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **String**| The name that needs to be fetched. Use user1 for testing. | - -### Return type - -[**User**](User.md) - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid username supplied | - | -| **404** | User not found | - | - -## getUserByNameWithHttpInfo - -> ApiResponse getUserByName getUserByNameWithHttpInfo(username) - -Get user by user name - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. - try { - ApiResponse response = apiInstance.getUserByNameWithHttpInfo(username); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#getUserByName"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **String**| The name that needs to be fetched. Use user1 for testing. | - -### Return type - -ApiResponse<[**User**](User.md)> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | - | -| **400** | Invalid username supplied | - | -| **404** | User not found | - | - - -## loginUser - -> String loginUser(username, password) - -Logs user into the system - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - String username = "username_example"; // String | The user name for login - String password = "password_example"; // String | The password for login in clear text - try { - String result = apiInstance.loginUser(username, password); - System.out.println(result); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#loginUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **String**| The user name for login | - **password** | **String**| The password for login in clear text | - -### Return type - -**String** - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
        * X-Expires-After - date in UTC when token expires
        | -| **400** | Invalid username/password supplied | - | - -## loginUserWithHttpInfo - -> ApiResponse loginUser loginUserWithHttpInfo(username, password) - -Logs user into the system - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - String username = "username_example"; // String | The user name for login - String password = "password_example"; // String | The password for login in clear text - try { - ApiResponse response = apiInstance.loginUserWithHttpInfo(username, password); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - System.out.println("Response body: " + response.getData()); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#loginUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **String**| The user name for login | - **password** | **String**| The password for login in clear text | - -### Return type - -ApiResponse<**String**> - - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/xml, application/json - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
        * X-Expires-After - date in UTC when token expires
        | -| **400** | Invalid username/password supplied | - | - - -## logoutUser - -> void logoutUser() - -Logs out current logged in user session - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - try { - apiInstance.logoutUser(); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#logoutUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - -## logoutUserWithHttpInfo - -> ApiResponse logoutUser logoutUserWithHttpInfo() - -Logs out current logged in user session - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - try { - ApiResponse response = apiInstance.logoutUserWithHttpInfo(); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#logoutUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - -This endpoint does not need any parameter. - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **0** | successful operation | - | - - -## updateUser - -> void updateUser(username, user) - -Updated user - -This can only be done by the logged in user. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - String username = "username_example"; // String | name that need to be deleted - User user = new User(); // User | Updated user object - try { - apiInstance.updateUser(username, user); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#updateUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Reason: " + e.getResponseBody()); - System.err.println("Response headers: " + e.getResponseHeaders()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **String**| name that need to be deleted | - **user** | [**User**](User.md)| Updated user object | - -### Return type - - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid user supplied | - | -| **404** | User not found | - | - -## updateUserWithHttpInfo - -> ApiResponse updateUser updateUserWithHttpInfo(username, user) - -Updated user - -This can only be done by the logged in user. - -### Example - -```java -// Import classes: -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Configuration; -import org.openapitools.client.models.*; -import org.openapitools.client.api.UserApi; - -public class Example { - public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); - - UserApi apiInstance = new UserApi(defaultClient); - String username = "username_example"; // String | name that need to be deleted - User user = new User(); // User | Updated user object - try { - ApiResponse response = apiInstance.updateUserWithHttpInfo(username, user); - System.out.println("Status code: " + response.getStatusCode()); - System.out.println("Response headers: " + response.getHeaders()); - } catch (ApiException e) { - System.err.println("Exception when calling UserApi#updateUser"); - System.err.println("Status code: " + e.getCode()); - System.err.println("Response headers: " + e.getResponseHeaders()); - System.err.println("Reason: " + e.getResponseBody()); - e.printStackTrace(); - } - } -} -``` - -### Parameters - - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **username** | **String**| name that need to be deleted | - **user** | [**User**](User.md)| Updated user object | - -### Return type - - -ApiResponse - -### Authorization - -No authorization required - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: Not defined - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -| **400** | Invalid user supplied | - | -| **404** | User not found | - | - diff --git a/samples/openapi3/client/petstore/java/native/docs/Whale.md b/samples/openapi3/client/petstore/java/native/docs/Whale.md deleted file mode 100644 index 87470ae5fa..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Whale.md +++ /dev/null @@ -1,15 +0,0 @@ - - -# Whale - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**hasBaleen** | **Boolean** | | [optional] -**hasTeeth** | **Boolean** | | [optional] -**className** | **String** | | - - - diff --git a/samples/openapi3/client/petstore/java/native/docs/Zebra.md b/samples/openapi3/client/petstore/java/native/docs/Zebra.md deleted file mode 100644 index eafe1861f2..0000000000 --- a/samples/openapi3/client/petstore/java/native/docs/Zebra.md +++ /dev/null @@ -1,24 +0,0 @@ - - -# Zebra - - -## Properties - -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**type** | [**TypeEnum**](#TypeEnum) | | [optional] -**className** | **String** | | - - - -## Enum: TypeEnum - -Name | Value ----- | ----- -PLAINS | "plains" -MOUNTAIN | "mountain" -GREVYS | "grevys" - - - diff --git a/samples/openapi3/client/petstore/java/native/git_push.sh b/samples/openapi3/client/petstore/java/native/git_push.sh deleted file mode 100644 index ced3be2b0c..0000000000 --- a/samples/openapi3/client/petstore/java/native/git_push.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - diff --git a/samples/openapi3/client/petstore/java/native/gradle/wrapper/gradle-wrapper.jar b/samples/openapi3/client/petstore/java/native/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 7454180f2a..0000000000 Binary files a/samples/openapi3/client/petstore/java/native/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/samples/openapi3/client/petstore/java/native/gradlew b/samples/openapi3/client/petstore/java/native/gradlew deleted file mode 100755 index 1b6c787337..0000000000 --- a/samples/openapi3/client/petstore/java/native/gradlew +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# 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. -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" -APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/samples/openapi3/client/petstore/java/native/pom.xml b/samples/openapi3/client/petstore/java/native/pom.xml index e2f71f0ec3..83e5524313 100644 --- a/samples/openapi3/client/petstore/java/native/pom.xml +++ b/samples/openapi3/client/petstore/java/native/pom.xml @@ -1,222 +1,17 @@ - - 4.0.0 - org.openapitools - petstore-openapi3-native - jar - petstore-openapi3-native - 1.0.0 - https://github.com/openapitools/openapi-generator - OpenAPI Java - - scm:git:git@github.com:openapitools/openapi-generator.git - scm:git:git@github.com:openapitools/openapi-generator.git - https://github.com/openapitools/openapi-generator - - - - - Unlicense - https://www.apache.org/licenses/LICENSE-2.0.html - repo - - - - - - OpenAPI-Generator Contributors - team@openapitools.org - OpenAPITools.org - http://openapitools.org - - - + + + 4.0.0 + org.openapitools.dummy + dummy-pom + 1.0 - maven-enforcer-plugin - 3.0.0-M1 - - - enforce-maven - - enforce - - - - - 3 - - - 11 - - - - - - - - maven-surefire-plugin - 3.0.0-M3 - - - conf/log4j.properties - - -Xms512m -Xmx1500m - methods - 10 - - - + org.apache.maven.plugins maven-dependency-plugin - 3.1.1 - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.1.2 - - - - test-jar - - - - - - - - maven-compiler-plugin - 3.8.1 - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.1.0 - - - attach-javadocs - - jar - - - - - - maven-source-plugin - 3.1.0 - - - attach-sources - - jar-no-fork - - - + 2.8 - - - - sign-artifacts - - - - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - - - - - - - - - io.swagger - swagger-annotations - ${swagger-annotations-version} - - - - - com.fasterxml.jackson.core - jackson-core - ${jackson-version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson-version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson-version} - - - org.openapitools - jackson-databind-nullable - ${jackson-databind-nullable-version} - - - - - com.google.code.findbugs - jsr305 - 3.0.2 - - - jakarta.annotation - jakarta.annotation-api - ${jakarta-annotation-version} - provided - - - - - junit - junit - ${junit-version} - test - - - - - UTF-8 - 1.5.22 - 11 - 11 - 2.10.4 - 0.2.1 - 1.3.5 - 4.13.2 - diff --git a/samples/openapi3/client/petstore/java/native/settings.gradle b/samples/openapi3/client/petstore/java/native/settings.gradle deleted file mode 100644 index 80c85ec483..0000000000 --- a/samples/openapi3/client/petstore/java/native/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = "petstore-openapi3-native" \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/native/src/main/AndroidManifest.xml b/samples/openapi3/client/petstore/java/native/src/main/AndroidManifest.xml deleted file mode 100644 index 54fbcb3da1..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/AndroidManifest.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java deleted file mode 100644 index 4b5a1fb4bd..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package org.openapitools.client; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import org.openapitools.jackson.nullable.JsonNullableModule; - -import java.io.InputStream; -import java.net.URI; -import java.net.URLEncoder; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.StringJoiner; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import static java.nio.charset.StandardCharsets.UTF_8; - -/** - * Configuration and utility class for API clients. - * - *

        This class can be constructed and modified, then used to instantiate the - * various API classes. The API classes use the settings in this class to - * configure themselves, but otherwise do not store a link to this class.

        - * - *

        This class is mutable and not synchronized, so it is not thread-safe. - * The API classes generated from this are immutable and thread-safe.

        - * - *

        The setter methods of this class return the current object to facilitate - * a fluent style of configuration.

        - */ -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ApiClient { - - private HttpClient.Builder builder; - private ObjectMapper mapper; - private String scheme; - private String host; - private int port; - private String basePath; - private Consumer interceptor; - private Consumer> responseInterceptor; - private Duration readTimeout; - - private static String valueToString(Object value) { - if (value == null) { - return ""; - } - if (value instanceof OffsetDateTime) { - return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - } - return value.toString(); - } - - /** - * URL encode a string in the UTF-8 encoding. - * - * @param s String to encode. - * @return URL-encoded representation of the input string. - */ - public static String urlEncode(String s) { - return URLEncoder.encode(s, UTF_8); - } - - /** - * Convert a URL query name/value parameter to a list of encoded {@link Pair} - * objects. - * - *

        The value can be null, in which case an empty list is returned.

        - * - * @param name The query name parameter. - * @param value The query value, which may not be a collection but may be - * null. - * @return A singleton list of the {@link Pair} objects representing the input - * parameters, which is encoded for use in a URL. If the value is null, an - * empty list is returned. - */ - public static List parameterToPairs(String name, Object value) { - if (name == null || name.isEmpty() || value == null) { - return Collections.emptyList(); - } - return Collections.singletonList(new Pair(urlEncode(name), urlEncode(valueToString(value)))); - } - - /** - * Convert a URL query name/collection parameter to a list of encoded - * {@link Pair} objects. - * - * @param collectionFormat The swagger collectionFormat string (csv, tsv, etc). - * @param name The query name parameter. - * @param values A collection of values for the given query name, which may be - * null. - * @return A list of {@link Pair} objects representing the input parameters, - * which is encoded for use in a URL. If the values collection is null, an - * empty list is returned. - */ - public static List parameterToPairs( - String collectionFormat, String name, Collection values) { - if (name == null || name.isEmpty() || values == null || values.isEmpty()) { - return Collections.emptyList(); - } - - // get the collection format (default: csv) - String format = collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat; - - // create the params based on the collection format - if ("multi".equals(format)) { - return values.stream() - .map(value -> new Pair(urlEncode(name), urlEncode(valueToString(value)))) - .collect(Collectors.toList()); - } - - String delimiter; - switch(format) { - case "csv": - delimiter = urlEncode(","); - break; - case "ssv": - delimiter = urlEncode(" "); - break; - case "tsv": - delimiter = urlEncode("\t"); - break; - case "pipes": - delimiter = urlEncode("|"); - break; - default: - throw new IllegalArgumentException("Illegal collection format: " + collectionFormat); - } - - StringJoiner joiner = new StringJoiner(delimiter); - for (Object value : values) { - joiner.add(urlEncode(valueToString(value))); - } - - return Collections.singletonList(new Pair(urlEncode(name), joiner.toString())); - } - - /** - * Ctor. - */ - public ApiClient() { - this.builder = createDefaultHttpClientBuilder(); - this.mapper = createDefaultObjectMapper(); - updateBaseUri(getDefaultBaseUri()); - interceptor = null; - readTimeout = null; - responseInterceptor = null; - } - - /** - * Ctor. - */ - public ApiClient(HttpClient.Builder builder, ObjectMapper mapper, String baseUri) { - this.builder = builder; - this.mapper = mapper; - updateBaseUri(baseUri != null ? baseUri : getDefaultBaseUri()); - interceptor = null; - readTimeout = null; - responseInterceptor = null; - } - - protected ObjectMapper createDefaultObjectMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); - mapper.registerModule(new JavaTimeModule()); - mapper.registerModule(new JsonNullableModule()); - return mapper; - } - - protected String getDefaultBaseUri() { - return "http://petstore.swagger.io:80/v2"; - } - - protected HttpClient.Builder createDefaultHttpClientBuilder() { - return HttpClient.newBuilder(); - } - - public void updateBaseUri(String baseUri) { - URI uri = URI.create(baseUri); - scheme = uri.getScheme(); - host = uri.getHost(); - port = uri.getPort(); - basePath = uri.getRawPath(); - } - - /** - * Set a custom {@link HttpClient.Builder} object to use when creating the - * {@link HttpClient} that is used by the API client. - * - * @param builder Custom client builder. - * @return This object. - */ - public ApiClient setHttpClientBuilder(HttpClient.Builder builder) { - this.builder = builder; - return this; - } - - /** - * Get an {@link HttpClient} based on the current {@link HttpClient.Builder}. - * - *

        The returned object is immutable and thread-safe.

        - * - * @return The HTTP client. - */ - public HttpClient getHttpClient() { - return builder.build(); - } - - /** - * Set a custom {@link ObjectMapper} to serialize and deserialize the request - * and response bodies. - * - * @param mapper Custom object mapper. - * @return This object. - */ - public ApiClient setObjectMapper(ObjectMapper mapper) { - this.mapper = mapper; - return this; - } - - /** - * Get a copy of the current {@link ObjectMapper}. - * - * @return A copy of the current object mapper. - */ - public ObjectMapper getObjectMapper() { - return mapper.copy(); - } - - /** - * Set a custom host name for the target service. - * - * @param host The host name of the target service. - * @return This object. - */ - public ApiClient setHost(String host) { - this.host = host; - return this; - } - - /** - * Set a custom port number for the target service. - * - * @param port The port of the target service. Set this to -1 to reset the - * value to the default for the scheme. - * @return This object. - */ - public ApiClient setPort(int port) { - this.port = port; - return this; - } - - /** - * Set a custom base path for the target service, for example '/v2'. - * - * @param basePath The base path against which the rest of the path is - * resolved. - * @return This object. - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Get the base URI to resolve the endpoint paths against. - * - * @return The complete base URI that the rest of the API parameters are - * resolved against. - */ - public String getBaseUri() { - return scheme + "://" + host + (port == -1 ? "" : ":" + port) + basePath; - } - - /** - * Set a custom scheme for the target service, for example 'https'. - * - * @param scheme The scheme of the target service - * @return This object. - */ - public ApiClient setScheme(String scheme){ - this.scheme = scheme; - return this; - } - - /** - * Set a custom request interceptor. - * - *

        A request interceptor is a mechanism for altering each request before it - * is sent. After the request has been fully configured but not yet built, the - * request builder is passed into this function for further modification, - * after which it is sent out.

        - * - *

        This is useful for altering the requests in a custom manner, such as - * adding headers. It could also be used for logging and monitoring.

        - * - * @param interceptor A function invoked before creating each request. A value - * of null resets the interceptor to a no-op. - * @return This object. - */ - public ApiClient setRequestInterceptor(Consumer interceptor) { - this.interceptor = interceptor; - return this; - } - - /** - * Get the custom interceptor. - * - * @return The custom interceptor that was set, or null if there isn't any. - */ - public Consumer getRequestInterceptor() { - return interceptor; - } - - /** - * Set a custom response interceptor. - * - *

        This is useful for logging, monitoring or extraction of header variables

        - * - * @param interceptor A function invoked before creating each request. A value - * of null resets the interceptor to a no-op. - * @return This object. - */ - public ApiClient setResponseInterceptor(Consumer> interceptor) { - this.responseInterceptor = interceptor; - return this; - } - - /** - * Get the custom response interceptor. - * - * @return The custom interceptor that was set, or null if there isn't any. - */ - public Consumer> getResponseInterceptor() { - return responseInterceptor; - } - - /** - * Set the read timeout for the http client. - * - *

        This is the value used by default for each request, though it can be - * overridden on a per-request basis with a request interceptor.

        - * - * @param readTimeout The read timeout used by default by the http client. - * Setting this value to null resets the timeout to an - * effectively infinite value. - * @return This object. - */ - public ApiClient setReadTimeout(Duration readTimeout) { - this.readTimeout = readTimeout; - return this; - } - - /** - * Get the read timeout that was set. - * - * @return The read timeout, or null if no timeout was set. Null represents - * an infinite wait time. - */ - public Duration getReadTimeout() { - return readTimeout; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiException.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiException.java deleted file mode 100644 index 9b6bbf0dc3..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiException.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client; - -import java.net.http.HttpHeaders; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ApiException extends Exception { - private int code = 0; - private HttpHeaders responseHeaders = null; - private String responseBody = null; - - public ApiException() {} - - public ApiException(Throwable throwable) { - super(throwable); - } - - public ApiException(String message) { - super(message); - } - - public ApiException(String message, Throwable throwable, int code, HttpHeaders responseHeaders, String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - public ApiException(String message, int code, HttpHeaders responseHeaders, String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(String message, Throwable throwable, int code, HttpHeaders responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } - - public ApiException(int code, HttpHeaders responseHeaders, String responseBody) { - this((String) null, (Throwable) null, code, responseHeaders, responseBody); - } - - public ApiException(int code, String message) { - super(message); - this.code = code; - } - - public ApiException(int code, String message, HttpHeaders responseHeaders, String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - /** - * Get the HTTP status code. - * - * @return HTTP status code - */ - public int getCode() { - return code; - } - - /** - * Get the HTTP response headers. - * - * @return Headers as an HttpHeaders object - */ - public HttpHeaders getResponseHeaders() { - return responseHeaders; - } - - /** - * Get the HTTP response body. - * - * @return Response body in the form of string - */ - public String getResponseBody() { - return responseBody; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiResponse.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiResponse.java deleted file mode 100644 index 9bb5cac17b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiResponse.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client; - -import java.util.List; -import java.util.Map; - -/** - * API response returned by API call. - * - * @param The type of data that is deserialized from response body - */ -public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } - - /** - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } - - public int getStatusCode() { - return statusCode; - } - - public Map> getHeaders() { - return headers; - } - - public T getData() { - return data; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/Configuration.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/Configuration.java deleted file mode 100644 index 29538391ae..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/Configuration.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java deleted file mode 100644 index 04d3f7c179..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java +++ /dev/null @@ -1,240 +0,0 @@ -package org.openapitools.client; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import org.openapitools.jackson.nullable.JsonNullableModule; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import org.openapitools.client.model.*; - -import java.text.DateFormat; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class JSON { - private ObjectMapper mapper; - - public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); - mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.setDateFormat(new RFC3339DateFormat()); - mapper.registerModule(new JavaTimeModule()); - JsonNullableModule jnm = new JsonNullableModule(); - mapper.registerModule(jnm); - } - - /** - * Set the date format for JSON (de)serialization with Date properties. - * @param dateFormat Date format - */ - public void setDateFormat(DateFormat dateFormat) { - mapper.setDateFormat(dateFormat); - } - - /** - * Get the object mapper - * - * @return object mapper - */ - public ObjectMapper getMapper() { return mapper; } - - /** - * Returns the target model class that should be used to deserialize the input data. - * The discriminator mappings are used to determine the target model class. - * - * @param node The input data. - * @param modelClass The class that contains the discriminator mappings. - */ - public static Class getClassForElement(JsonNode node, Class modelClass) { - ClassDiscriminatorMapping cdm = modelDiscriminators.get(modelClass); - if (cdm != null) { - return cdm.getClassForElement(node, new HashSet>()); - } - return null; - } - - /** - * Helper class to register the discriminator mappings. - */ - private static class ClassDiscriminatorMapping { - // The model class name. - Class modelClass; - // The name of the discriminator property. - String discriminatorName; - // The discriminator mappings for a model class. - Map> discriminatorMappings; - - // Constructs a new class discriminator. - ClassDiscriminatorMapping(Class cls, String propertyName, Map> mappings) { - modelClass = cls; - discriminatorName = propertyName; - discriminatorMappings = new HashMap>(); - if (mappings != null) { - discriminatorMappings.putAll(mappings); - } - } - - // Return the name of the discriminator property for this model class. - String getDiscriminatorPropertyName() { - return discriminatorName; - } - - // Return the discriminator value or null if the discriminator is not - // present in the payload. - String getDiscriminatorValue(JsonNode node) { - // Determine the value of the discriminator property in the input data. - if (discriminatorName != null) { - // Get the value of the discriminator property, if present in the input payload. - node = node.get(discriminatorName); - if (node != null && node.isValueNode()) { - String discrValue = node.asText(); - if (discrValue != null) { - return discrValue; - } - } - } - return null; - } - - /** - * Returns the target model class that should be used to deserialize the input data. - * This function can be invoked for anyOf/oneOf composed models with discriminator mappings. - * The discriminator mappings are used to determine the target model class. - * - * @param node The input data. - * @param visitedClasses The set of classes that have already been visited. - */ - Class getClassForElement(JsonNode node, Set> visitedClasses) { - if (visitedClasses.contains(modelClass)) { - // Class has already been visited. - return null; - } - // Determine the value of the discriminator property in the input data. - String discrValue = getDiscriminatorValue(node); - if (discrValue == null) { - return null; - } - Class cls = discriminatorMappings.get(discrValue); - // It may not be sufficient to return this cls directly because that target class - // may itself be a composed schema, possibly with its own discriminator. - visitedClasses.add(modelClass); - for (Class childClass : discriminatorMappings.values()) { - ClassDiscriminatorMapping childCdm = modelDiscriminators.get(childClass); - if (childCdm == null) { - continue; - } - if (!discriminatorName.equals(childCdm.discriminatorName)) { - discrValue = getDiscriminatorValue(node); - if (discrValue == null) { - continue; - } - } - if (childCdm != null) { - // Recursively traverse the discriminator mappings. - Class childDiscr = childCdm.getClassForElement(node, visitedClasses); - if (childDiscr != null) { - return childDiscr; - } - } - } - return cls; - } - } - - /** - * Returns true if inst is an instance of modelClass in the OpenAPI model hierarchy. - * - * The Java class hierarchy is not implemented the same way as the OpenAPI model hierarchy, - * so it's not possible to use the instanceof keyword. - * - * @param modelClass A OpenAPI model class. - * @param inst The instance object. - */ - public static boolean isInstanceOf(Class modelClass, Object inst, Set> visitedClasses) { - if (modelClass.isInstance(inst)) { - // This handles the 'allOf' use case with single parent inheritance. - return true; - } - if (visitedClasses.contains(modelClass)) { - // This is to prevent infinite recursion when the composed schemas have - // a circular dependency. - return false; - } - visitedClasses.add(modelClass); - - // Traverse the oneOf/anyOf composed schemas. - Map> descendants = modelDescendants.get(modelClass); - if (descendants != null) { - for (Class childType : descendants.values()) { - if (isInstanceOf(childType, inst, visitedClasses)) { - return true; - } - } - } - return false; - } - - /** - * A map of discriminators for all model classes. - */ - private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap<>(); - - /** - * A map of oneOf/anyOf descendants for each model class. - */ - private static Map, Map>> modelDescendants = new HashMap<>(); - - /** - * Register a model class discriminator. - * - * @param modelClass the model class - * @param discriminatorPropertyName the name of the discriminator property - * @param mappings a map with the discriminator mappings. - */ - public static void registerDiscriminator(Class modelClass, String discriminatorPropertyName, Map> mappings) { - ClassDiscriminatorMapping m = new ClassDiscriminatorMapping(modelClass, discriminatorPropertyName, mappings); - modelDiscriminators.put(modelClass, m); - } - - /** - * Register the oneOf/anyOf descendants of the modelClass. - * - * @param modelClass the model class - * @param descendants a map of oneOf/anyOf descendants. - */ - public static void registerDescendants(Class modelClass, Map> descendants) { - modelDescendants.put(modelClass, descendants); - } - - private static JSON json; - - static { - json = new JSON(); - } - - /** - * Get the default JSON instance. - * - * @return the default JSON instance - */ - public static JSON getDefault() { - return json; - } - - /** - * Set the default JSON instance. - * - * @param json JSON instance to be used - */ - public static void setDefault(JSON json) { - JSON.json = json; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/RFC3339DateFormat.java deleted file mode 100644 index 07d7e782b0..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package org.openapitools.client; - -import com.fasterxml.jackson.databind.util.StdDateFormat; - -import java.text.DateFormat; -import java.text.FieldPosition; -import java.text.ParsePosition; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -public class RFC3339DateFormat extends DateFormat { - private static final long serialVersionUID = 1L; - private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - - private final StdDateFormat fmt = new StdDateFormat() - .withTimeZone(TIMEZONE_Z) - .withColonInTimeZone(true); - - public RFC3339DateFormat() { - this.calendar = new GregorianCalendar(); - } - - @Override - public Date parse(String source) { - return parse(source, new ParsePosition(0)); - } - - @Override - public Date parse(String source, ParsePosition pos) { - return fmt.parse(source, pos); - } - - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - return fmt.format(date, toAppendTo, fieldPosition); - } - - @Override - public Object clone() { - return this; - } -} \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ServerConfiguration.java deleted file mode 100644 index a1107a8690..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ServerConfiguration.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.openapitools.client; - -import java.util.Map; - -/** - * Representing a Server configuration. - */ -public class ServerConfiguration { - public String URL; - public String description; - public Map variables; - - /** - * @param URL A URL to the target host. - * @param description A describtion of the host designated by the URL. - * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. - */ - public ServerConfiguration(String URL, String description, Map variables) { - this.URL = URL; - this.description = description; - this.variables = variables; - } - - /** - * Format URL template using given variables. - * - * @param variables A map between a variable name and its value. - * @return Formatted URL. - */ - public String URL(Map variables) { - String url = this.URL; - - // go through variables and replace placeholders - for (Map.Entry variable: this.variables.entrySet()) { - String name = variable.getKey(); - ServerVariable serverVariable = variable.getValue(); - String value = serverVariable.defaultValue; - - if (variables != null && variables.containsKey(name)) { - value = variables.get(name); - if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { - throw new RuntimeException("The variable " + name + " in the server URL has invalid value " + value + "."); - } - } - url = url.replaceAll("\\{" + name + "\\}", value); - } - return url; - } - - /** - * Format URL template using default server variables. - * - * @return Formatted URL. - */ - public String URL() { - return URL(null); - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ServerVariable.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ServerVariable.java deleted file mode 100644 index c2f13e2166..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ServerVariable.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openapitools.client; - -import java.util.HashSet; - -/** - * Representing a Server Variable for server URL template substitution. - */ -public class ServerVariable { - public String description; - public String defaultValue; - public HashSet enumValues = null; - - /** - * @param description A description for the server variable. - * @param defaultValue The default value to use for substitution. - * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. - */ - public ServerVariable(String description, String defaultValue, HashSet enumValues) { - this.description = description; - this.defaultValue = defaultValue; - this.enumValues = enumValues; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java deleted file mode 100644 index 9e3aae3650..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package org.openapitools.client.api; - -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Pair; - -import org.openapitools.client.model.Client; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.function.Consumer; - -import java.util.ArrayList; -import java.util.StringJoiner; -import java.util.List; -import java.util.Map; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class AnotherFakeApi { - private final HttpClient memberVarHttpClient; - private final ObjectMapper memberVarObjectMapper; - private final String memberVarBaseUri; - private final Consumer memberVarInterceptor; - private final Duration memberVarReadTimeout; - private final Consumer> memberVarResponseInterceptor; - - public AnotherFakeApi() { - this(new ApiClient()); - } - - public AnotherFakeApi(ApiClient apiClient) { - memberVarHttpClient = apiClient.getHttpClient(); - memberVarObjectMapper = apiClient.getObjectMapper(); - memberVarBaseUri = apiClient.getBaseUri(); - memberVarInterceptor = apiClient.getRequestInterceptor(); - memberVarReadTimeout = apiClient.getReadTimeout(); - memberVarResponseInterceptor = apiClient.getResponseInterceptor(); - } - - protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - String message = formatExceptionMessage(operationId, response.statusCode(), body); - return new ApiException(response.statusCode(), message, response.headers(), body); - } - - private String formatExceptionMessage(String operationId, int statusCode, String body) { - if (body == null || body.isEmpty()) { - body = "[no body]"; - } - return operationId + " call failed with: " + statusCode + " - " + body; - } - - /** - * To test special tags - * To test special tags and operation ID starting with number - * @param client client model (required) - * @return Client - * @throws ApiException if fails to make API call - */ - public Client call123testSpecialTags(Client client) throws ApiException { - ApiResponse localVarResponse = call123testSpecialTagsWithHttpInfo(client); - return localVarResponse.getData(); - } - - /** - * To test special tags - * To test special tags and operation ID starting with number - * @param client client model (required) - * @return ApiResponse<Client> - * @throws ApiException if fails to make API call - */ - public ApiResponse call123testSpecialTagsWithHttpInfo(Client client) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = call123testSpecialTagsRequestBuilder(client); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("call123testSpecialTags", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder call123testSpecialTagsRequestBuilder(Client client) throws ApiException { - // verify the required parameter 'client' is set - if (client == null) { - throw new ApiException(400, "Missing the required parameter 'client' when calling call123testSpecialTags"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/another-fake/dummy"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(client); - localVarRequestBuilder.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java deleted file mode 100644 index 5dc086e5ed..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package org.openapitools.client.api; - -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Pair; - -import org.openapitools.client.model.InlineResponseDefault; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.function.Consumer; - -import java.util.ArrayList; -import java.util.StringJoiner; -import java.util.List; -import java.util.Map; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DefaultApi { - private final HttpClient memberVarHttpClient; - private final ObjectMapper memberVarObjectMapper; - private final String memberVarBaseUri; - private final Consumer memberVarInterceptor; - private final Duration memberVarReadTimeout; - private final Consumer> memberVarResponseInterceptor; - - public DefaultApi() { - this(new ApiClient()); - } - - public DefaultApi(ApiClient apiClient) { - memberVarHttpClient = apiClient.getHttpClient(); - memberVarObjectMapper = apiClient.getObjectMapper(); - memberVarBaseUri = apiClient.getBaseUri(); - memberVarInterceptor = apiClient.getRequestInterceptor(); - memberVarReadTimeout = apiClient.getReadTimeout(); - memberVarResponseInterceptor = apiClient.getResponseInterceptor(); - } - - protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - String message = formatExceptionMessage(operationId, response.statusCode(), body); - return new ApiException(response.statusCode(), message, response.headers(), body); - } - - private String formatExceptionMessage(String operationId, int statusCode, String body) { - if (body == null || body.isEmpty()) { - body = "[no body]"; - } - return operationId + " call failed with: " + statusCode + " - " + body; - } - - /** - * - * - * @return InlineResponseDefault - * @throws ApiException if fails to make API call - */ - public InlineResponseDefault fooGet() throws ApiException { - ApiResponse localVarResponse = fooGetWithHttpInfo(); - return localVarResponse.getData(); - } - - /** - * - * - * @return ApiResponse<InlineResponseDefault> - * @throws ApiException if fails to make API call - */ - public ApiResponse fooGetWithHttpInfo() throws ApiException { - HttpRequest.Builder localVarRequestBuilder = fooGetRequestBuilder(); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fooGet", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder fooGetRequestBuilder() throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/foo"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java deleted file mode 100644 index 71f3084b35..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java +++ /dev/null @@ -1,1377 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package org.openapitools.client.api; - -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Pair; - -import java.math.BigDecimal; -import org.openapitools.client.model.Client; -import java.io.File; -import org.openapitools.client.model.FileSchemaTestClass; -import org.openapitools.client.model.HealthCheckResult; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import org.openapitools.client.model.OuterComposite; -import org.openapitools.client.model.OuterEnum; -import org.openapitools.client.model.User; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.function.Consumer; - -import java.util.ArrayList; -import java.util.StringJoiner; -import java.util.List; -import java.util.Map; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class FakeApi { - private final HttpClient memberVarHttpClient; - private final ObjectMapper memberVarObjectMapper; - private final String memberVarBaseUri; - private final Consumer memberVarInterceptor; - private final Duration memberVarReadTimeout; - private final Consumer> memberVarResponseInterceptor; - - public FakeApi() { - this(new ApiClient()); - } - - public FakeApi(ApiClient apiClient) { - memberVarHttpClient = apiClient.getHttpClient(); - memberVarObjectMapper = apiClient.getObjectMapper(); - memberVarBaseUri = apiClient.getBaseUri(); - memberVarInterceptor = apiClient.getRequestInterceptor(); - memberVarReadTimeout = apiClient.getReadTimeout(); - memberVarResponseInterceptor = apiClient.getResponseInterceptor(); - } - - protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - String message = formatExceptionMessage(operationId, response.statusCode(), body); - return new ApiException(response.statusCode(), message, response.headers(), body); - } - - private String formatExceptionMessage(String operationId, int statusCode, String body) { - if (body == null || body.isEmpty()) { - body = "[no body]"; - } - return operationId + " call failed with: " + statusCode + " - " + body; - } - - /** - * Health check endpoint - * - * @return HealthCheckResult - * @throws ApiException if fails to make API call - */ - public HealthCheckResult fakeHealthGet() throws ApiException { - ApiResponse localVarResponse = fakeHealthGetWithHttpInfo(); - return localVarResponse.getData(); - } - - /** - * Health check endpoint - * - * @return ApiResponse<HealthCheckResult> - * @throws ApiException if fails to make API call - */ - public ApiResponse fakeHealthGetWithHttpInfo() throws ApiException { - HttpRequest.Builder localVarRequestBuilder = fakeHealthGetRequestBuilder(); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fakeHealthGet", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder fakeHealthGetRequestBuilder() throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/health"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * - * Test serialization of outer boolean types - * @param body Input boolean as post body (optional) - * @return Boolean - * @throws ApiException if fails to make API call - */ - public Boolean fakeOuterBooleanSerialize(Boolean body) throws ApiException { - ApiResponse localVarResponse = fakeOuterBooleanSerializeWithHttpInfo(body); - return localVarResponse.getData(); - } - - /** - * - * Test serialization of outer boolean types - * @param body Input boolean as post body (optional) - * @return ApiResponse<Boolean> - * @throws ApiException if fails to make API call - */ - public ApiResponse fakeOuterBooleanSerializeWithHttpInfo(Boolean body) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = fakeOuterBooleanSerializeRequestBuilder(body); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fakeOuterBooleanSerialize", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder fakeOuterBooleanSerializeRequestBuilder(Boolean body) throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/outer/boolean"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(body); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * - * Test serialization of object with outer number type - * @param outerComposite Input composite as post body (optional) - * @return OuterComposite - * @throws ApiException if fails to make API call - */ - public OuterComposite fakeOuterCompositeSerialize(OuterComposite outerComposite) throws ApiException { - ApiResponse localVarResponse = fakeOuterCompositeSerializeWithHttpInfo(outerComposite); - return localVarResponse.getData(); - } - - /** - * - * Test serialization of object with outer number type - * @param outerComposite Input composite as post body (optional) - * @return ApiResponse<OuterComposite> - * @throws ApiException if fails to make API call - */ - public ApiResponse fakeOuterCompositeSerializeWithHttpInfo(OuterComposite outerComposite) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = fakeOuterCompositeSerializeRequestBuilder(outerComposite); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fakeOuterCompositeSerialize", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder fakeOuterCompositeSerializeRequestBuilder(OuterComposite outerComposite) throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/outer/composite"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(outerComposite); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * - * Test serialization of outer number types - * @param body Input number as post body (optional) - * @return BigDecimal - * @throws ApiException if fails to make API call - */ - public BigDecimal fakeOuterNumberSerialize(BigDecimal body) throws ApiException { - ApiResponse localVarResponse = fakeOuterNumberSerializeWithHttpInfo(body); - return localVarResponse.getData(); - } - - /** - * - * Test serialization of outer number types - * @param body Input number as post body (optional) - * @return ApiResponse<BigDecimal> - * @throws ApiException if fails to make API call - */ - public ApiResponse fakeOuterNumberSerializeWithHttpInfo(BigDecimal body) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = fakeOuterNumberSerializeRequestBuilder(body); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fakeOuterNumberSerialize", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder fakeOuterNumberSerializeRequestBuilder(BigDecimal body) throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/outer/number"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(body); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * - * Test serialization of outer string types - * @param body Input string as post body (optional) - * @return String - * @throws ApiException if fails to make API call - */ - public String fakeOuterStringSerialize(String body) throws ApiException { - ApiResponse localVarResponse = fakeOuterStringSerializeWithHttpInfo(body); - return localVarResponse.getData(); - } - - /** - * - * Test serialization of outer string types - * @param body Input string as post body (optional) - * @return ApiResponse<String> - * @throws ApiException if fails to make API call - */ - public ApiResponse fakeOuterStringSerializeWithHttpInfo(String body) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = fakeOuterStringSerializeRequestBuilder(body); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fakeOuterStringSerialize", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder fakeOuterStringSerializeRequestBuilder(String body) throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/outer/string"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(body); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Array of Enums - * - * @return List<OuterEnum> - * @throws ApiException if fails to make API call - */ - public List getArrayOfEnums() throws ApiException { - ApiResponse> localVarResponse = getArrayOfEnumsWithHttpInfo(); - return localVarResponse.getData(); - } - - /** - * Array of Enums - * - * @return ApiResponse<List<OuterEnum>> - * @throws ApiException if fails to make API call - */ - public ApiResponse> getArrayOfEnumsWithHttpInfo() throws ApiException { - HttpRequest.Builder localVarRequestBuilder = getArrayOfEnumsRequestBuilder(); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("getArrayOfEnums", localVarResponse); - } - return new ApiResponse>( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder getArrayOfEnumsRequestBuilder() throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/array-of-enums"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * - * For this test, the body for this request much reference a schema named `File`. - * @param fileSchemaTestClass (required) - * @throws ApiException if fails to make API call - */ - public void testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) throws ApiException { - testBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); - } - - /** - * - * For this test, the body for this request much reference a schema named `File`. - * @param fileSchemaTestClass (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse testBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass fileSchemaTestClass) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testBodyWithFileSchemaRequestBuilder(fileSchemaTestClass); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testBodyWithFileSchema", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testBodyWithFileSchemaRequestBuilder(FileSchemaTestClass fileSchemaTestClass) throws ApiException { - // verify the required parameter 'fileSchemaTestClass' is set - if (fileSchemaTestClass == null) { - throw new ApiException(400, "Missing the required parameter 'fileSchemaTestClass' when calling testBodyWithFileSchema"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/body-with-file-schema"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(fileSchemaTestClass); - localVarRequestBuilder.method("PUT", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * - * - * @param query (required) - * @param user (required) - * @throws ApiException if fails to make API call - */ - public void testBodyWithQueryParams(String query, User user) throws ApiException { - testBodyWithQueryParamsWithHttpInfo(query, user); - } - - /** - * - * - * @param query (required) - * @param user (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse testBodyWithQueryParamsWithHttpInfo(String query, User user) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testBodyWithQueryParamsRequestBuilder(query, user); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testBodyWithQueryParams", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testBodyWithQueryParamsRequestBuilder(String query, User user) throws ApiException { - // verify the required parameter 'query' is set - if (query == null) { - throw new ApiException(400, "Missing the required parameter 'query' when calling testBodyWithQueryParams"); - } - // verify the required parameter 'user' is set - if (user == null) { - throw new ApiException(400, "Missing the required parameter 'user' when calling testBodyWithQueryParams"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/body-with-query-params"; - - List localVarQueryParams = new ArrayList<>(); - localVarQueryParams.addAll(ApiClient.parameterToPairs("query", query)); - - if (!localVarQueryParams.isEmpty()) { - StringJoiner queryJoiner = new StringJoiner("&"); - localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); - } else { - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - } - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(user); - localVarRequestBuilder.method("PUT", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * To test \"client\" model - * To test \"client\" model - * @param client client model (required) - * @return Client - * @throws ApiException if fails to make API call - */ - public Client testClientModel(Client client) throws ApiException { - ApiResponse localVarResponse = testClientModelWithHttpInfo(client); - return localVarResponse.getData(); - } - - /** - * To test \"client\" model - * To test \"client\" model - * @param client client model (required) - * @return ApiResponse<Client> - * @throws ApiException if fails to make API call - */ - public ApiResponse testClientModelWithHttpInfo(Client client) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testClientModelRequestBuilder(client); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testClientModel", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testClientModelRequestBuilder(Client client) throws ApiException { - // verify the required parameter 'client' is set - if (client == null) { - throw new ApiException(400, "Missing the required parameter 'client' when calling testClientModel"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(client); - localVarRequestBuilder.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional, default to OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))) - * @param password None (optional) - * @param paramCallback None (optional) - * @throws ApiException if fails to make API call - */ - public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional, default to OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))) - * @param password None (optional) - * @param paramCallback None (optional) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testEndpointParametersRequestBuilder(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testEndpointParameters", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testEndpointParametersRequestBuilder(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); - } - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); - } - // verify the required parameter 'patternWithoutDelimiter' is set - if (patternWithoutDelimiter == null) { - throw new ApiException(400, "Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters"); - } - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * To test enum parameters - * To test enum parameters - * @param enumHeaderStringArray Header parameter enum test (string array) (optional - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param enumFormStringArray Form parameter enum test (string array) (optional - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @throws ApiException if fails to make API call - */ - public void testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) throws ApiException { - testEnumParametersWithHttpInfo(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); - } - - /** - * To test enum parameters - * To test enum parameters - * @param enumHeaderStringArray Header parameter enum test (string array) (optional - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param enumFormStringArray Form parameter enum test (string array) (optional - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse testEnumParametersWithHttpInfo(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testEnumParametersRequestBuilder(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testEnumParameters", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testEnumParametersRequestBuilder(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake"; - - List localVarQueryParams = new ArrayList<>(); - localVarQueryParams.addAll(ApiClient.parameterToPairs("multi", "enum_query_string_array", enumQueryStringArray)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("enum_query_string", enumQueryString)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("enum_query_integer", enumQueryInteger)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("enum_query_double", enumQueryDouble)); - - if (!localVarQueryParams.isEmpty()) { - StringJoiner queryJoiner = new StringJoiner("&"); - localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); - } else { - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - } - - if (enumHeaderStringArray != null) { - localVarRequestBuilder.header("enum_header_string_array", enumHeaderStringArray.toString()); - } - if (enumHeaderString != null) { - localVarRequestBuilder.header("enum_header_string", enumHeaderString.toString()); - } - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Fake endpoint to test group parameters (optional) - * Fake endpoint to test group parameters (optional) - * @param apiRequest {@link APItestGroupParametersRequest} - * @throws ApiException if fails to make API call - */ - public void testGroupParameters(APItestGroupParametersRequest apiRequest) throws ApiException { - Integer requiredStringGroup = apiRequest.requiredStringGroup(); - Boolean requiredBooleanGroup = apiRequest.requiredBooleanGroup(); - Long requiredInt64Group = apiRequest.requiredInt64Group(); - Integer stringGroup = apiRequest.stringGroup(); - Boolean booleanGroup = apiRequest.booleanGroup(); - Long int64Group = apiRequest.int64Group(); - testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); - } - - /** - * Fake endpoint to test group parameters (optional) - * Fake endpoint to test group parameters (optional) - * @param apiRequest {@link APItestGroupParametersRequest} - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse testGroupParametersWithHttpInfo(APItestGroupParametersRequest apiRequest) throws ApiException { - Integer requiredStringGroup = apiRequest.requiredStringGroup(); - Boolean requiredBooleanGroup = apiRequest.requiredBooleanGroup(); - Long requiredInt64Group = apiRequest.requiredInt64Group(); - Integer stringGroup = apiRequest.stringGroup(); - Boolean booleanGroup = apiRequest.booleanGroup(); - Long int64Group = apiRequest.int64Group(); - return testGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); - } - - /** - * Fake endpoint to test group parameters (optional) - * Fake endpoint to test group parameters (optional) - * @param requiredStringGroup Required String in group parameters (required) - * @param requiredBooleanGroup Required Boolean in group parameters (required) - * @param requiredInt64Group Required Integer in group parameters (required) - * @param stringGroup String in group parameters (optional) - * @param booleanGroup Boolean in group parameters (optional) - * @param int64Group Integer in group parameters (optional) - * @throws ApiException if fails to make API call - */ - public void testGroupParameters(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws ApiException { - testGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); - } - - /** - * Fake endpoint to test group parameters (optional) - * Fake endpoint to test group parameters (optional) - * @param requiredStringGroup Required String in group parameters (required) - * @param requiredBooleanGroup Required Boolean in group parameters (required) - * @param requiredInt64Group Required Integer in group parameters (required) - * @param stringGroup String in group parameters (optional) - * @param booleanGroup Boolean in group parameters (optional) - * @param int64Group Integer in group parameters (optional) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse testGroupParametersWithHttpInfo(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testGroupParametersRequestBuilder(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testGroupParameters", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testGroupParametersRequestBuilder(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws ApiException { - // verify the required parameter 'requiredStringGroup' is set - if (requiredStringGroup == null) { - throw new ApiException(400, "Missing the required parameter 'requiredStringGroup' when calling testGroupParameters"); - } - // verify the required parameter 'requiredBooleanGroup' is set - if (requiredBooleanGroup == null) { - throw new ApiException(400, "Missing the required parameter 'requiredBooleanGroup' when calling testGroupParameters"); - } - // verify the required parameter 'requiredInt64Group' is set - if (requiredInt64Group == null) { - throw new ApiException(400, "Missing the required parameter 'requiredInt64Group' when calling testGroupParameters"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake"; - - List localVarQueryParams = new ArrayList<>(); - localVarQueryParams.addAll(ApiClient.parameterToPairs("required_string_group", requiredStringGroup)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("required_int64_group", requiredInt64Group)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("string_group", stringGroup)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("int64_group", int64Group)); - - if (!localVarQueryParams.isEmpty()) { - StringJoiner queryJoiner = new StringJoiner("&"); - localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); - } else { - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - } - - if (requiredBooleanGroup != null) { - localVarRequestBuilder.header("required_boolean_group", requiredBooleanGroup.toString()); - } - if (booleanGroup != null) { - localVarRequestBuilder.header("boolean_group", booleanGroup.toString()); - } - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("DELETE", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - - public static final class APItestGroupParametersRequest { - private Integer requiredStringGroup; // Required String in group parameters (required) - private Boolean requiredBooleanGroup; // Required Boolean in group parameters (required) - private Long requiredInt64Group; // Required Integer in group parameters (required) - private Integer stringGroup; // String in group parameters (optional) - private Boolean booleanGroup; // Boolean in group parameters (optional) - private Long int64Group; // Integer in group parameters (optional) - - private APItestGroupParametersRequest(Builder builder) { - this.requiredStringGroup = builder.requiredStringGroup; - this.requiredBooleanGroup = builder.requiredBooleanGroup; - this.requiredInt64Group = builder.requiredInt64Group; - this.stringGroup = builder.stringGroup; - this.booleanGroup = builder.booleanGroup; - this.int64Group = builder.int64Group; - } - public Integer requiredStringGroup() { - return requiredStringGroup; - } - public Boolean requiredBooleanGroup() { - return requiredBooleanGroup; - } - public Long requiredInt64Group() { - return requiredInt64Group; - } - public Integer stringGroup() { - return stringGroup; - } - public Boolean booleanGroup() { - return booleanGroup; - } - public Long int64Group() { - return int64Group; - } - public static Builder newBuilder() { - return new Builder(); - } - - public static class Builder { - private Integer requiredStringGroup; - private Boolean requiredBooleanGroup; - private Long requiredInt64Group; - private Integer stringGroup; - private Boolean booleanGroup; - private Long int64Group; - - public Builder requiredStringGroup(Integer requiredStringGroup) { - this.requiredStringGroup = requiredStringGroup; - return this; - } - public Builder requiredBooleanGroup(Boolean requiredBooleanGroup) { - this.requiredBooleanGroup = requiredBooleanGroup; - return this; - } - public Builder requiredInt64Group(Long requiredInt64Group) { - this.requiredInt64Group = requiredInt64Group; - return this; - } - public Builder stringGroup(Integer stringGroup) { - this.stringGroup = stringGroup; - return this; - } - public Builder booleanGroup(Boolean booleanGroup) { - this.booleanGroup = booleanGroup; - return this; - } - public Builder int64Group(Long int64Group) { - this.int64Group = int64Group; - return this; - } - public APItestGroupParametersRequest build() { - return new APItestGroupParametersRequest(this); - } - } - } - - /** - * test inline additionalProperties - * - * @param requestBody request body (required) - * @throws ApiException if fails to make API call - */ - public void testInlineAdditionalProperties(Map requestBody) throws ApiException { - testInlineAdditionalPropertiesWithHttpInfo(requestBody); - } - - /** - * test inline additionalProperties - * - * @param requestBody request body (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse testInlineAdditionalPropertiesWithHttpInfo(Map requestBody) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testInlineAdditionalPropertiesRequestBuilder(requestBody); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testInlineAdditionalProperties", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testInlineAdditionalPropertiesRequestBuilder(Map requestBody) throws ApiException { - // verify the required parameter 'requestBody' is set - if (requestBody == null) { - throw new ApiException(400, "Missing the required parameter 'requestBody' when calling testInlineAdditionalProperties"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/inline-additionalProperties"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(requestBody); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * test json serialization of form data - * - * @param param field1 (required) - * @param param2 field2 (required) - * @throws ApiException if fails to make API call - */ - public void testJsonFormData(String param, String param2) throws ApiException { - testJsonFormDataWithHttpInfo(param, param2); - } - - /** - * test json serialization of form data - * - * @param param field1 (required) - * @param param2 field2 (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse testJsonFormDataWithHttpInfo(String param, String param2) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testJsonFormDataRequestBuilder(param, param2); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testJsonFormData", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testJsonFormDataRequestBuilder(String param, String param2) throws ApiException { - // verify the required parameter 'param' is set - if (param == null) { - throw new ApiException(400, "Missing the required parameter 'param' when calling testJsonFormData"); - } - // verify the required parameter 'param2' is set - if (param2 == null) { - throw new ApiException(400, "Missing the required parameter 'param2' when calling testJsonFormData"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/jsonFormData"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * - * To test the collection format in query parameters - * @param pipe (required) - * @param ioutil (required) - * @param http (required) - * @param url (required) - * @param context (required) - * @throws ApiException if fails to make API call - */ - public void testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) throws ApiException { - testQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context); - } - - /** - * - * To test the collection format in query parameters - * @param pipe (required) - * @param ioutil (required) - * @param http (required) - * @param url (required) - * @param context (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse testQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testQueryParameterCollectionFormatRequestBuilder(pipe, ioutil, http, url, context); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testQueryParameterCollectionFormat", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testQueryParameterCollectionFormatRequestBuilder(List pipe, List ioutil, List http, List url, List context) throws ApiException { - // verify the required parameter 'pipe' is set - if (pipe == null) { - throw new ApiException(400, "Missing the required parameter 'pipe' when calling testQueryParameterCollectionFormat"); - } - // verify the required parameter 'ioutil' is set - if (ioutil == null) { - throw new ApiException(400, "Missing the required parameter 'ioutil' when calling testQueryParameterCollectionFormat"); - } - // verify the required parameter 'http' is set - if (http == null) { - throw new ApiException(400, "Missing the required parameter 'http' when calling testQueryParameterCollectionFormat"); - } - // verify the required parameter 'url' is set - if (url == null) { - throw new ApiException(400, "Missing the required parameter 'url' when calling testQueryParameterCollectionFormat"); - } - // verify the required parameter 'context' is set - if (context == null) { - throw new ApiException(400, "Missing the required parameter 'context' when calling testQueryParameterCollectionFormat"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/test-query-parameters"; - - List localVarQueryParams = new ArrayList<>(); - localVarQueryParams.addAll(ApiClient.parameterToPairs("multi", "pipe", pipe)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("csv", "ioutil", ioutil)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("ssv", "http", http)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("csv", "url", url)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("multi", "context", context)); - - if (!localVarQueryParams.isEmpty()) { - StringJoiner queryJoiner = new StringJoiner("&"); - localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); - } else { - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - } - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("PUT", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java deleted file mode 100644 index 098b07e149..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package org.openapitools.client.api; - -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Pair; - -import org.openapitools.client.model.Client; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.function.Consumer; - -import java.util.ArrayList; -import java.util.StringJoiner; -import java.util.List; -import java.util.Map; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class FakeClassnameTags123Api { - private final HttpClient memberVarHttpClient; - private final ObjectMapper memberVarObjectMapper; - private final String memberVarBaseUri; - private final Consumer memberVarInterceptor; - private final Duration memberVarReadTimeout; - private final Consumer> memberVarResponseInterceptor; - - public FakeClassnameTags123Api() { - this(new ApiClient()); - } - - public FakeClassnameTags123Api(ApiClient apiClient) { - memberVarHttpClient = apiClient.getHttpClient(); - memberVarObjectMapper = apiClient.getObjectMapper(); - memberVarBaseUri = apiClient.getBaseUri(); - memberVarInterceptor = apiClient.getRequestInterceptor(); - memberVarReadTimeout = apiClient.getReadTimeout(); - memberVarResponseInterceptor = apiClient.getResponseInterceptor(); - } - - protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - String message = formatExceptionMessage(operationId, response.statusCode(), body); - return new ApiException(response.statusCode(), message, response.headers(), body); - } - - private String formatExceptionMessage(String operationId, int statusCode, String body) { - if (body == null || body.isEmpty()) { - body = "[no body]"; - } - return operationId + " call failed with: " + statusCode + " - " + body; - } - - /** - * To test class name in snake case - * To test class name in snake case - * @param client client model (required) - * @return Client - * @throws ApiException if fails to make API call - */ - public Client testClassname(Client client) throws ApiException { - ApiResponse localVarResponse = testClassnameWithHttpInfo(client); - return localVarResponse.getData(); - } - - /** - * To test class name in snake case - * To test class name in snake case - * @param client client model (required) - * @return ApiResponse<Client> - * @throws ApiException if fails to make API call - */ - public ApiResponse testClassnameWithHttpInfo(Client client) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = testClassnameRequestBuilder(client); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testClassname", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder testClassnameRequestBuilder(Client client) throws ApiException { - // verify the required parameter 'client' is set - if (client == null) { - throw new ApiException(400, "Missing the required parameter 'client' when calling testClassname"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake_classname_test"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(client); - localVarRequestBuilder.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java deleted file mode 100644 index 4f2bfe172f..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java +++ /dev/null @@ -1,740 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package org.openapitools.client.api; - -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Pair; - -import java.io.File; -import org.openapitools.client.model.ModelApiResponse; -import org.openapitools.client.model.Pet; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.function.Consumer; - -import java.util.ArrayList; -import java.util.StringJoiner; -import java.util.List; -import java.util.Map; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class PetApi { - private final HttpClient memberVarHttpClient; - private final ObjectMapper memberVarObjectMapper; - private final String memberVarBaseUri; - private final Consumer memberVarInterceptor; - private final Duration memberVarReadTimeout; - private final Consumer> memberVarResponseInterceptor; - - public PetApi() { - this(new ApiClient()); - } - - public PetApi(ApiClient apiClient) { - memberVarHttpClient = apiClient.getHttpClient(); - memberVarObjectMapper = apiClient.getObjectMapper(); - memberVarBaseUri = apiClient.getBaseUri(); - memberVarInterceptor = apiClient.getRequestInterceptor(); - memberVarReadTimeout = apiClient.getReadTimeout(); - memberVarResponseInterceptor = apiClient.getResponseInterceptor(); - } - - protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - String message = formatExceptionMessage(operationId, response.statusCode(), body); - return new ApiException(response.statusCode(), message, response.headers(), body); - } - - private String formatExceptionMessage(String operationId, int statusCode, String body) { - if (body == null || body.isEmpty()) { - body = "[no body]"; - } - return operationId + " call failed with: " + statusCode + " - " + body; - } - - /** - * Add a new pet to the store - * - * @param pet Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void addPet(Pet pet) throws ApiException { - addPetWithHttpInfo(pet); - } - - /** - * Add a new pet to the store - * - * @param pet Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse addPetWithHttpInfo(Pet pet) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = addPetRequestBuilder(pet); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("addPet", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder addPetRequestBuilder(Pet pet) throws ApiException { - // verify the required parameter 'pet' is set - if (pet == null) { - throw new ApiException(400, "Missing the required parameter 'pet' when calling addPet"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/pet"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(pet); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException if fails to make API call - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = deletePetRequestBuilder(petId, apiKey); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("deletePet", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder deletePetRequestBuilder(Long petId, String apiKey) throws ApiException { - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/pet/{petId}" - .replace("{petId}", ApiClient.urlEncode(petId.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - if (apiKey != null) { - localVarRequestBuilder.header("api_key", apiKey.toString()); - } - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("DELETE", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List<Pet> - * @throws ApiException if fails to make API call - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> localVarResponse = findPetsByStatusWithHttpInfo(status); - return localVarResponse.getData(); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException if fails to make API call - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = findPetsByStatusRequestBuilder(status); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("findPetsByStatus", localVarResponse); - } - return new ApiResponse>( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder findPetsByStatusRequestBuilder(List status) throws ApiException { - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/pet/findByStatus"; - - List localVarQueryParams = new ArrayList<>(); - localVarQueryParams.addAll(ApiClient.parameterToPairs("csv", "status", status)); - - if (!localVarQueryParams.isEmpty()) { - StringJoiner queryJoiner = new StringJoiner("&"); - localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); - } else { - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - } - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List<Pet> - * @throws ApiException if fails to make API call - * @deprecated - */ - @Deprecated - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> localVarResponse = findPetsByTagsWithHttpInfo(tags); - return localVarResponse.getData(); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException if fails to make API call - * @deprecated - */ - @Deprecated - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = findPetsByTagsRequestBuilder(tags); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("findPetsByTags", localVarResponse); - } - return new ApiResponse>( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder findPetsByTagsRequestBuilder(List tags) throws ApiException { - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/pet/findByTags"; - - List localVarQueryParams = new ArrayList<>(); - localVarQueryParams.addAll(ApiClient.parameterToPairs("csv", "tags", tags)); - - if (!localVarQueryParams.isEmpty()) { - StringJoiner queryJoiner = new StringJoiner("&"); - localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); - } else { - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - } - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException if fails to make API call - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse localVarResponse = getPetByIdWithHttpInfo(petId); - return localVarResponse.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse<Pet> - * @throws ApiException if fails to make API call - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = getPetByIdRequestBuilder(petId); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("getPetById", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder getPetByIdRequestBuilder(Long petId) throws ApiException { - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/pet/{petId}" - .replace("{petId}", ApiClient.urlEncode(petId.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Update an existing pet - * - * @param pet Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void updatePet(Pet pet) throws ApiException { - updatePetWithHttpInfo(pet); - } - - /** - * Update an existing pet - * - * @param pet Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse updatePetWithHttpInfo(Pet pet) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = updatePetRequestBuilder(pet); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("updatePet", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder updatePetRequestBuilder(Pet pet) throws ApiException { - // verify the required parameter 'pet' is set - if (pet == null) { - throw new ApiException(400, "Missing the required parameter 'pet' when calling updatePet"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/pet"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(pet); - localVarRequestBuilder.method("PUT", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException if fails to make API call - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = updatePetWithFormRequestBuilder(petId, name, status); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("updatePetWithForm", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder updatePetWithFormRequestBuilder(Long petId, String name, String status) throws ApiException { - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/pet/{petId}" - .replace("{petId}", ApiClient.urlEncode(petId.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException if fails to make API call - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse localVarResponse = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return localVarResponse.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse<ModelApiResponse> - * @throws ApiException if fails to make API call - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = uploadFileRequestBuilder(petId, additionalMetadata, file); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("uploadFile", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder uploadFileRequestBuilder(Long petId, String additionalMetadata, File file) throws ApiException { - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/pet/{petId}/uploadImage" - .replace("{petId}", ApiClient.urlEncode(petId.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * uploads an image (required) - * - * @param petId ID of pet to update (required) - * @param requiredFile file to upload (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @return ModelApiResponse - * @throws ApiException if fails to make API call - */ - public ModelApiResponse uploadFileWithRequiredFile(Long petId, File requiredFile, String additionalMetadata) throws ApiException { - ApiResponse localVarResponse = uploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); - return localVarResponse.getData(); - } - - /** - * uploads an image (required) - * - * @param petId ID of pet to update (required) - * @param requiredFile file to upload (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @return ApiResponse<ModelApiResponse> - * @throws ApiException if fails to make API call - */ - public ApiResponse uploadFileWithRequiredFileWithHttpInfo(Long petId, File requiredFile, String additionalMetadata) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = uploadFileWithRequiredFileRequestBuilder(petId, requiredFile, additionalMetadata); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("uploadFileWithRequiredFile", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder uploadFileWithRequiredFileRequestBuilder(Long petId, File requiredFile, String additionalMetadata) throws ApiException { - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFileWithRequiredFile"); - } - // verify the required parameter 'requiredFile' is set - if (requiredFile == null) { - throw new ApiException(400, "Missing the required parameter 'requiredFile' when calling uploadFileWithRequiredFile"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/fake/{petId}/uploadImageWithRequiredFile" - .replace("{petId}", ApiClient.urlEncode(petId.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java deleted file mode 100644 index 0bd1cd35ff..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package org.openapitools.client.api; - -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Pair; - -import org.openapitools.client.model.Order; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.function.Consumer; - -import java.util.ArrayList; -import java.util.StringJoiner; -import java.util.List; -import java.util.Map; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class StoreApi { - private final HttpClient memberVarHttpClient; - private final ObjectMapper memberVarObjectMapper; - private final String memberVarBaseUri; - private final Consumer memberVarInterceptor; - private final Duration memberVarReadTimeout; - private final Consumer> memberVarResponseInterceptor; - - public StoreApi() { - this(new ApiClient()); - } - - public StoreApi(ApiClient apiClient) { - memberVarHttpClient = apiClient.getHttpClient(); - memberVarObjectMapper = apiClient.getObjectMapper(); - memberVarBaseUri = apiClient.getBaseUri(); - memberVarInterceptor = apiClient.getRequestInterceptor(); - memberVarReadTimeout = apiClient.getReadTimeout(); - memberVarResponseInterceptor = apiClient.getResponseInterceptor(); - } - - protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - String message = formatExceptionMessage(operationId, response.statusCode(), body); - return new ApiException(response.statusCode(), message, response.headers(), body); - } - - private String formatExceptionMessage(String operationId, int statusCode, String body) { - if (body == null || body.isEmpty()) { - body = "[no body]"; - } - return operationId + " call failed with: " + statusCode + " - " + body; - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteOrder(String orderId) throws ApiException { - deleteOrderWithHttpInfo(orderId); - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = deleteOrderRequestBuilder(orderId); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("deleteOrder", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder deleteOrderRequestBuilder(String orderId) throws ApiException { - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/store/order/{order_id}" - .replace("{order_id}", ApiClient.urlEncode(orderId.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("DELETE", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map<String, Integer> - * @throws ApiException if fails to make API call - */ - public Map getInventory() throws ApiException { - ApiResponse> localVarResponse = getInventoryWithHttpInfo(); - return localVarResponse.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse<Map<String, Integer>> - * @throws ApiException if fails to make API call - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - HttpRequest.Builder localVarRequestBuilder = getInventoryRequestBuilder(); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("getInventory", localVarResponse); - } - return new ApiResponse>( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder getInventoryRequestBuilder() throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/store/inventory"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse localVarResponse = getOrderByIdWithHttpInfo(orderId); - return localVarResponse.getData(); - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return ApiResponse<Order> - * @throws ApiException if fails to make API call - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = getOrderByIdRequestBuilder(orderId); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("getOrderById", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder getOrderByIdRequestBuilder(Long orderId) throws ApiException { - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/store/order/{order_id}" - .replace("{order_id}", ApiClient.urlEncode(orderId.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Place an order for a pet - * - * @param order order placed for purchasing the pet (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order placeOrder(Order order) throws ApiException { - ApiResponse localVarResponse = placeOrderWithHttpInfo(order); - return localVarResponse.getData(); - } - - /** - * Place an order for a pet - * - * @param order order placed for purchasing the pet (required) - * @return ApiResponse<Order> - * @throws ApiException if fails to make API call - */ - public ApiResponse placeOrderWithHttpInfo(Order order) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = placeOrderRequestBuilder(order); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("placeOrder", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder placeOrderRequestBuilder(Order order) throws ApiException { - // verify the required parameter 'order' is set - if (order == null) { - throw new ApiException(400, "Missing the required parameter 'order' when calling placeOrder"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/store/order"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(order); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java deleted file mode 100644 index 008303b316..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java +++ /dev/null @@ -1,649 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package org.openapitools.client.api; - -import org.openapitools.client.ApiClient; -import org.openapitools.client.ApiException; -import org.openapitools.client.ApiResponse; -import org.openapitools.client.Pair; - -import org.openapitools.client.model.User; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.function.Consumer; - -import java.util.ArrayList; -import java.util.StringJoiner; -import java.util.List; -import java.util.Map; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class UserApi { - private final HttpClient memberVarHttpClient; - private final ObjectMapper memberVarObjectMapper; - private final String memberVarBaseUri; - private final Consumer memberVarInterceptor; - private final Duration memberVarReadTimeout; - private final Consumer> memberVarResponseInterceptor; - - public UserApi() { - this(new ApiClient()); - } - - public UserApi(ApiClient apiClient) { - memberVarHttpClient = apiClient.getHttpClient(); - memberVarObjectMapper = apiClient.getObjectMapper(); - memberVarBaseUri = apiClient.getBaseUri(); - memberVarInterceptor = apiClient.getRequestInterceptor(); - memberVarReadTimeout = apiClient.getReadTimeout(); - memberVarResponseInterceptor = apiClient.getResponseInterceptor(); - } - - protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - String message = formatExceptionMessage(operationId, response.statusCode(), body); - return new ApiException(response.statusCode(), message, response.headers(), body); - } - - private String formatExceptionMessage(String operationId, int statusCode, String body) { - if (body == null || body.isEmpty()) { - body = "[no body]"; - } - return operationId + " call failed with: " + statusCode + " - " + body; - } - - /** - * Create user - * This can only be done by the logged in user. - * @param user Created user object (required) - * @throws ApiException if fails to make API call - */ - public void createUser(User user) throws ApiException { - createUserWithHttpInfo(user); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param user Created user object (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse createUserWithHttpInfo(User user) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = createUserRequestBuilder(user); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("createUser", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder createUserRequestBuilder(User user) throws ApiException { - // verify the required parameter 'user' is set - if (user == null) { - throw new ApiException(400, "Missing the required parameter 'user' when calling createUser"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/user"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(user); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Creates list of users with given input array - * - * @param user List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithArrayInput(List user) throws ApiException { - createUsersWithArrayInputWithHttpInfo(user); - } - - /** - * Creates list of users with given input array - * - * @param user List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List user) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = createUsersWithArrayInputRequestBuilder(user); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("createUsersWithArrayInput", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder createUsersWithArrayInputRequestBuilder(List user) throws ApiException { - // verify the required parameter 'user' is set - if (user == null) { - throw new ApiException(400, "Missing the required parameter 'user' when calling createUsersWithArrayInput"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/user/createWithArray"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(user); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Creates list of users with given input array - * - * @param user List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithListInput(List user) throws ApiException { - createUsersWithListInputWithHttpInfo(user); - } - - /** - * Creates list of users with given input array - * - * @param user List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List user) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = createUsersWithListInputRequestBuilder(user); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("createUsersWithListInput", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder createUsersWithListInputRequestBuilder(List user) throws ApiException { - // verify the required parameter 'user' is set - if (user == null) { - throw new ApiException(400, "Missing the required parameter 'user' when calling createUsersWithListInput"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/user/createWithList"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(user); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = deleteUserRequestBuilder(username); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("deleteUser", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder deleteUserRequestBuilder(String username) throws ApiException { - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/user/{username}" - .replace("{username}", ApiClient.urlEncode(username.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("DELETE", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException if fails to make API call - */ - public User getUserByName(String username) throws ApiException { - ApiResponse localVarResponse = getUserByNameWithHttpInfo(username); - return localVarResponse.getData(); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse<User> - * @throws ApiException if fails to make API call - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = getUserByNameRequestBuilder(username); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("getUserByName", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder getUserByNameRequestBuilder(String username) throws ApiException { - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/user/{username}" - .replace("{username}", ApiClient.urlEncode(username.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException if fails to make API call - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse localVarResponse = loginUserWithHttpInfo(username, password); - return localVarResponse.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse<String> - * @throws ApiException if fails to make API call - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = loginUserRequestBuilder(username, password); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("loginUser", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder loginUserRequestBuilder(String username, String password) throws ApiException { - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); - } - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/user/login"; - - List localVarQueryParams = new ArrayList<>(); - localVarQueryParams.addAll(ApiClient.parameterToPairs("username", username)); - localVarQueryParams.addAll(ApiClient.parameterToPairs("password", password)); - - if (!localVarQueryParams.isEmpty()) { - StringJoiner queryJoiner = new StringJoiner("&"); - localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath + '?' + queryJoiner.toString())); - } else { - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - } - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Logs out current logged in user session - * - * @throws ApiException if fails to make API call - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } - - /** - * Logs out current logged in user session - * - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - HttpRequest.Builder localVarRequestBuilder = logoutUserRequestBuilder(); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("logoutUser", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder logoutUserRequestBuilder() throws ApiException { - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/user/logout"; - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param user Updated user object (required) - * @throws ApiException if fails to make API call - */ - public void updateUser(String username, User user) throws ApiException { - updateUserWithHttpInfo(username, user); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param user Updated user object (required) - * @return ApiResponse<Void> - * @throws ApiException if fails to make API call - */ - public ApiResponse updateUserWithHttpInfo(String username, User user) throws ApiException { - HttpRequest.Builder localVarRequestBuilder = updateUserRequestBuilder(username, user); - try { - HttpResponse localVarResponse = memberVarHttpClient.send( - localVarRequestBuilder.build(), - HttpResponse.BodyHandlers.ofInputStream()); - if (memberVarResponseInterceptor != null) { - memberVarResponseInterceptor.accept(localVarResponse); - } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("updateUser", localVarResponse); - } - return new ApiResponse( - localVarResponse.statusCode(), - localVarResponse.headers().map(), - null - ); - } catch (IOException e) { - throw new ApiException(e); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new ApiException(e); - } - } - - private HttpRequest.Builder updateUserRequestBuilder(String username, User user) throws ApiException { - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - } - // verify the required parameter 'user' is set - if (user == null) { - throw new ApiException(400, "Missing the required parameter 'user' when calling updateUser"); - } - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/user/{username}" - .replace("{username}", ApiClient.urlEncode(username.toString())); - - localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - try { - byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(user); - localVarRequestBuilder.method("PUT", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - if (memberVarReadTimeout != null) { - localVarRequestBuilder.timeout(memberVarReadTimeout); - } - if (memberVarInterceptor != null) { - memberVarInterceptor.accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java deleted file mode 100644 index 882bf6fc3a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import org.openapitools.client.ApiException; -import java.util.Objects; -import java.lang.reflect.Type; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonValue; - -/** - * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec - */ -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public abstract class AbstractOpenApiSchema { - - // store the actual instance of the schema/object - private Object instance; - - // is nullable - private Boolean isNullable; - - // schema type (e.g. oneOf, anyOf) - private final String schemaType; - - public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { - this.schemaType = schemaType; - this.isNullable = isNullable; - } - - /** - * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object - * - * @return an instance of the actual schema/object - */ - public abstract Map> getSchemas(); - - /** - * Get the actual instance - * - * @return an instance of the actual schema/object - */ - @JsonValue - public Object getActualInstance() {return instance;} - - /** - * Set the actual instance - * - * @param instance the actual instance of the schema/object - */ - public void setActualInstance(Object instance) {this.instance = instance;} - - /** - * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well - * - * @return an instance of the actual schema/object - */ - public Object getActualInstanceRecursively() { - return getActualInstanceRecursively(this); - } - - private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { - if (object.getActualInstance() == null) { - return null; - } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { - return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); - } else { - return object.getActualInstance(); - } - } - - /** - * Get the schema type (e.g. anyOf, oneOf) - * - * @return the schema type - */ - public String getSchemaType() { - return schemaType; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ").append(getClass()).append(" {\n"); - sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); - sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); - sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); - } - - @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); - } - - /** - * Is nullalble - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } - - - -} diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java deleted file mode 100644 index d171e2cb56..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * AdditionalPropertiesClass - */ -@JsonPropertyOrder({ - AdditionalPropertiesClass.JSON_PROPERTY_MAP_PROPERTY, - AdditionalPropertiesClass.JSON_PROPERTY_MAP_OF_MAP_PROPERTY, - AdditionalPropertiesClass.JSON_PROPERTY_ANYTYPE1, - AdditionalPropertiesClass.JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE1, - AdditionalPropertiesClass.JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE2, - AdditionalPropertiesClass.JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE3, - AdditionalPropertiesClass.JSON_PROPERTY_EMPTY_MAP, - AdditionalPropertiesClass.JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_STRING -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class AdditionalPropertiesClass { - public static final String JSON_PROPERTY_MAP_PROPERTY = "map_property"; - private Map mapProperty = null; - - public static final String JSON_PROPERTY_MAP_OF_MAP_PROPERTY = "map_of_map_property"; - private Map> mapOfMapProperty = null; - - public static final String JSON_PROPERTY_ANYTYPE1 = "anytype_1"; - private JsonNullable anytype1 = JsonNullable.of(null); - - public static final String JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE1 = "map_with_undeclared_properties_anytype_1"; - private Object mapWithUndeclaredPropertiesAnytype1; - - public static final String JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE2 = "map_with_undeclared_properties_anytype_2"; - private Object mapWithUndeclaredPropertiesAnytype2; - - public static final String JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE3 = "map_with_undeclared_properties_anytype_3"; - private Map mapWithUndeclaredPropertiesAnytype3 = null; - - public static final String JSON_PROPERTY_EMPTY_MAP = "empty_map"; - private Object emptyMap; - - public static final String JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_STRING = "map_with_undeclared_properties_string"; - private Map mapWithUndeclaredPropertiesString = null; - - - public AdditionalPropertiesClass mapProperty(Map mapProperty) { - this.mapProperty = mapProperty; - return this; - } - - public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { - if (this.mapProperty == null) { - this.mapProperty = new HashMap<>(); - } - this.mapProperty.put(key, mapPropertyItem); - return this; - } - - /** - * Get mapProperty - * @return mapProperty - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAP_PROPERTY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Map getMapProperty() { - return mapProperty; - } - - - @JsonProperty(JSON_PROPERTY_MAP_PROPERTY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMapProperty(Map mapProperty) { - this.mapProperty = mapProperty; - } - - - public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; - return this; - } - - public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { - if (this.mapOfMapProperty == null) { - this.mapOfMapProperty = new HashMap<>(); - } - this.mapOfMapProperty.put(key, mapOfMapPropertyItem); - return this; - } - - /** - * Get mapOfMapProperty - * @return mapOfMapProperty - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAP_OF_MAP_PROPERTY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Map> getMapOfMapProperty() { - return mapOfMapProperty; - } - - - @JsonProperty(JSON_PROPERTY_MAP_OF_MAP_PROPERTY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; - } - - - public AdditionalPropertiesClass anytype1(Object anytype1) { - this.anytype1 = JsonNullable.of(anytype1); - return this; - } - - /** - * Get anytype1 - * @return anytype1 - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public Object getAnytype1() { - return anytype1.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_ANYTYPE1) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getAnytype1_JsonNullable() { - return anytype1; - } - - @JsonProperty(JSON_PROPERTY_ANYTYPE1) - public void setAnytype1_JsonNullable(JsonNullable anytype1) { - this.anytype1 = anytype1; - } - - public void setAnytype1(Object anytype1) { - this.anytype1 = JsonNullable.of(anytype1); - } - - - public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype1(Object mapWithUndeclaredPropertiesAnytype1) { - this.mapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; - return this; - } - - /** - * Get mapWithUndeclaredPropertiesAnytype1 - * @return mapWithUndeclaredPropertiesAnytype1 - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE1) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Object getMapWithUndeclaredPropertiesAnytype1() { - return mapWithUndeclaredPropertiesAnytype1; - } - - - @JsonProperty(JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE1) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMapWithUndeclaredPropertiesAnytype1(Object mapWithUndeclaredPropertiesAnytype1) { - this.mapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; - } - - - public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype2(Object mapWithUndeclaredPropertiesAnytype2) { - this.mapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; - return this; - } - - /** - * Get mapWithUndeclaredPropertiesAnytype2 - * @return mapWithUndeclaredPropertiesAnytype2 - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE2) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Object getMapWithUndeclaredPropertiesAnytype2() { - return mapWithUndeclaredPropertiesAnytype2; - } - - - @JsonProperty(JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE2) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMapWithUndeclaredPropertiesAnytype2(Object mapWithUndeclaredPropertiesAnytype2) { - this.mapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; - } - - - public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype3(Map mapWithUndeclaredPropertiesAnytype3) { - this.mapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; - return this; - } - - public AdditionalPropertiesClass putMapWithUndeclaredPropertiesAnytype3Item(String key, Object mapWithUndeclaredPropertiesAnytype3Item) { - if (this.mapWithUndeclaredPropertiesAnytype3 == null) { - this.mapWithUndeclaredPropertiesAnytype3 = new HashMap<>(); - } - this.mapWithUndeclaredPropertiesAnytype3.put(key, mapWithUndeclaredPropertiesAnytype3Item); - return this; - } - - /** - * Get mapWithUndeclaredPropertiesAnytype3 - * @return mapWithUndeclaredPropertiesAnytype3 - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE3) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - - public Map getMapWithUndeclaredPropertiesAnytype3() { - return mapWithUndeclaredPropertiesAnytype3; - } - - - @JsonProperty(JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE3) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setMapWithUndeclaredPropertiesAnytype3(Map mapWithUndeclaredPropertiesAnytype3) { - this.mapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; - } - - - public AdditionalPropertiesClass emptyMap(Object emptyMap) { - this.emptyMap = emptyMap; - return this; - } - - /** - * an object with no declared properties and no undeclared properties, hence it's an empty map. - * @return emptyMap - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "an object with no declared properties and no undeclared properties, hence it's an empty map.") - @JsonProperty(JSON_PROPERTY_EMPTY_MAP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Object getEmptyMap() { - return emptyMap; - } - - - @JsonProperty(JSON_PROPERTY_EMPTY_MAP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setEmptyMap(Object emptyMap) { - this.emptyMap = emptyMap; - } - - - public AdditionalPropertiesClass mapWithUndeclaredPropertiesString(Map mapWithUndeclaredPropertiesString) { - this.mapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; - return this; - } - - public AdditionalPropertiesClass putMapWithUndeclaredPropertiesStringItem(String key, String mapWithUndeclaredPropertiesStringItem) { - if (this.mapWithUndeclaredPropertiesString == null) { - this.mapWithUndeclaredPropertiesString = new HashMap<>(); - } - this.mapWithUndeclaredPropertiesString.put(key, mapWithUndeclaredPropertiesStringItem); - return this; - } - - /** - * Get mapWithUndeclaredPropertiesString - * @return mapWithUndeclaredPropertiesString - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Map getMapWithUndeclaredPropertiesString() { - return mapWithUndeclaredPropertiesString; - } - - - @JsonProperty(JSON_PROPERTY_MAP_WITH_UNDECLARED_PROPERTIES_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMapWithUndeclaredPropertiesString(Map mapWithUndeclaredPropertiesString) { - this.mapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; - } - - - /** - * Return true if this AdditionalPropertiesClass object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && - Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty) && - Objects.equals(this.anytype1, additionalPropertiesClass.anytype1) && - Objects.equals(this.mapWithUndeclaredPropertiesAnytype1, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype1) && - Objects.equals(this.mapWithUndeclaredPropertiesAnytype2, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype2) && - Objects.equals(this.mapWithUndeclaredPropertiesAnytype3, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype3) && - Objects.equals(this.emptyMap, additionalPropertiesClass.emptyMap) && - Objects.equals(this.mapWithUndeclaredPropertiesString, additionalPropertiesClass.mapWithUndeclaredPropertiesString); - } - - @Override - public int hashCode() { - return Objects.hash(mapProperty, mapOfMapProperty, anytype1, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, emptyMap, mapWithUndeclaredPropertiesString); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AdditionalPropertiesClass {\n"); - sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); - sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); - sb.append(" anytype1: ").append(toIndentedString(anytype1)).append("\n"); - sb.append(" mapWithUndeclaredPropertiesAnytype1: ").append(toIndentedString(mapWithUndeclaredPropertiesAnytype1)).append("\n"); - sb.append(" mapWithUndeclaredPropertiesAnytype2: ").append(toIndentedString(mapWithUndeclaredPropertiesAnytype2)).append("\n"); - sb.append(" mapWithUndeclaredPropertiesAnytype3: ").append(toIndentedString(mapWithUndeclaredPropertiesAnytype3)).append("\n"); - sb.append(" emptyMap: ").append(toIndentedString(emptyMap)).append("\n"); - sb.append(" mapWithUndeclaredPropertiesString: ").append(toIndentedString(mapWithUndeclaredPropertiesString)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Animal.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Animal.java deleted file mode 100644 index f90886fb61..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Animal.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Cat; -import org.openapitools.client.model.Dog; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import org.openapitools.client.JSON; -/** - * Animal - */ -@JsonPropertyOrder({ - Animal.JSON_PROPERTY_CLASS_NAME, - Animal.JSON_PROPERTY_COLOR -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "className", visible = true) -@JsonSubTypes({ - @JsonSubTypes.Type(value = Cat.class, name = "Cat"), - @JsonSubTypes.Type(value = Dog.class, name = "Dog"), -}) - -public class Animal { - public static final String JSON_PROPERTY_CLASS_NAME = "className"; - private String className; - - public static final String JSON_PROPERTY_COLOR = "color"; - private String color = "red"; - - - public Animal className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getClassName() { - return className; - } - - - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setClassName(String className) { - this.className = className; - } - - - public Animal color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_COLOR) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getColor() { - return color; - } - - - @JsonProperty(JSON_PROPERTY_COLOR) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setColor(String color) { - this.color = color; - } - - - /** - * Return true if this Animal object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className) && - Objects.equals(this.color, animal.color); - } - - @Override - public int hashCode() { - return Objects.hash(className, color); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Animal {\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -static { - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("Cat", Cat.class); - mappings.put("Dog", Dog.class); - mappings.put("Animal", Animal.class); - JSON.registerDiscriminator(Animal.class, "className", mappings); -} -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Apple.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Apple.java deleted file mode 100644 index d9b3a291f4..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Apple.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Apple - */ -@JsonPropertyOrder({ - Apple.JSON_PROPERTY_CULTIVAR, - Apple.JSON_PROPERTY_ORIGIN -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Apple { - public static final String JSON_PROPERTY_CULTIVAR = "cultivar"; - private String cultivar; - - public static final String JSON_PROPERTY_ORIGIN = "origin"; - private String origin; - - - public Apple cultivar(String cultivar) { - this.cultivar = cultivar; - return this; - } - - /** - * Get cultivar - * @return cultivar - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_CULTIVAR) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getCultivar() { - return cultivar; - } - - - @JsonProperty(JSON_PROPERTY_CULTIVAR) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setCultivar(String cultivar) { - this.cultivar = cultivar; - } - - - public Apple origin(String origin) { - this.origin = origin; - return this; - } - - /** - * Get origin - * @return origin - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ORIGIN) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getOrigin() { - return origin; - } - - - @JsonProperty(JSON_PROPERTY_ORIGIN) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setOrigin(String origin) { - this.origin = origin; - } - - - /** - * Return true if this apple object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Apple apple = (Apple) o; - return Objects.equals(this.cultivar, apple.cultivar) && - Objects.equals(this.origin, apple.origin); - } - - @Override - public int hashCode() { - return Objects.hash(cultivar, origin); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Apple {\n"); - sb.append(" cultivar: ").append(toIndentedString(cultivar)).append("\n"); - sb.append(" origin: ").append(toIndentedString(origin)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AppleReq.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AppleReq.java deleted file mode 100644 index a2edcdfb3e..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AppleReq.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * AppleReq - */ -@JsonPropertyOrder({ - AppleReq.JSON_PROPERTY_CULTIVAR, - AppleReq.JSON_PROPERTY_MEALY -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class AppleReq { - public static final String JSON_PROPERTY_CULTIVAR = "cultivar"; - private String cultivar; - - public static final String JSON_PROPERTY_MEALY = "mealy"; - private Boolean mealy; - - - public AppleReq cultivar(String cultivar) { - this.cultivar = cultivar; - return this; - } - - /** - * Get cultivar - * @return cultivar - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_CULTIVAR) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getCultivar() { - return cultivar; - } - - - @JsonProperty(JSON_PROPERTY_CULTIVAR) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setCultivar(String cultivar) { - this.cultivar = cultivar; - } - - - public AppleReq mealy(Boolean mealy) { - this.mealy = mealy; - return this; - } - - /** - * Get mealy - * @return mealy - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MEALY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Boolean getMealy() { - return mealy; - } - - - @JsonProperty(JSON_PROPERTY_MEALY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMealy(Boolean mealy) { - this.mealy = mealy; - } - - - /** - * Return true if this appleReq object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AppleReq appleReq = (AppleReq) o; - return Objects.equals(this.cultivar, appleReq.cultivar) && - Objects.equals(this.mealy, appleReq.mealy); - } - - @Override - public int hashCode() { - return Objects.hash(cultivar, mealy); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AppleReq {\n"); - sb.append(" cultivar: ").append(toIndentedString(cultivar)).append("\n"); - sb.append(" mealy: ").append(toIndentedString(mealy)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java deleted file mode 100644 index 6dad127d9e..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ArrayOfArrayOfNumberOnly - */ -@JsonPropertyOrder({ - ArrayOfArrayOfNumberOnly.JSON_PROPERTY_ARRAY_ARRAY_NUMBER -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ArrayOfArrayOfNumberOnly { - public static final String JSON_PROPERTY_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; - private List> arrayArrayNumber = null; - - - public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; - return this; - } - - public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { - if (this.arrayArrayNumber == null) { - this.arrayArrayNumber = new ArrayList<>(); - } - this.arrayArrayNumber.add(arrayArrayNumberItem); - return this; - } - - /** - * Get arrayArrayNumber - * @return arrayArrayNumber - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List> getArrayArrayNumber() { - return arrayArrayNumber; - } - - - @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; - } - - - /** - * Return true if this ArrayOfArrayOfNumberOnly object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; - return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); - } - - @Override - public int hashCode() { - return Objects.hash(arrayArrayNumber); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayOfArrayOfNumberOnly {\n"); - sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java deleted file mode 100644 index 5e59c851d5..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ArrayOfNumberOnly - */ -@JsonPropertyOrder({ - ArrayOfNumberOnly.JSON_PROPERTY_ARRAY_NUMBER -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ArrayOfNumberOnly { - public static final String JSON_PROPERTY_ARRAY_NUMBER = "ArrayNumber"; - private List arrayNumber = null; - - - public ArrayOfNumberOnly arrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; - return this; - } - - public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { - if (this.arrayNumber == null) { - this.arrayNumber = new ArrayList<>(); - } - this.arrayNumber.add(arrayNumberItem); - return this; - } - - /** - * Get arrayNumber - * @return arrayNumber - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ARRAY_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List getArrayNumber() { - return arrayNumber; - } - - - @JsonProperty(JSON_PROPERTY_ARRAY_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; - } - - - /** - * Return true if this ArrayOfNumberOnly object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; - return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); - } - - @Override - public int hashCode() { - return Objects.hash(arrayNumber); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayOfNumberOnly {\n"); - sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ArrayTest.java deleted file mode 100644 index a3aef6b1ba..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ArrayTest.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import org.openapitools.client.model.ReadOnlyFirst; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ArrayTest - */ -@JsonPropertyOrder({ - ArrayTest.JSON_PROPERTY_ARRAY_OF_STRING, - ArrayTest.JSON_PROPERTY_ARRAY_ARRAY_OF_INTEGER, - ArrayTest.JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ArrayTest { - public static final String JSON_PROPERTY_ARRAY_OF_STRING = "array_of_string"; - private List arrayOfString = null; - - public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_INTEGER = "array_array_of_integer"; - private List> arrayArrayOfInteger = null; - - public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; - private List> arrayArrayOfModel = null; - - - public ArrayTest arrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; - return this; - } - - public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { - if (this.arrayOfString == null) { - this.arrayOfString = new ArrayList<>(); - } - this.arrayOfString.add(arrayOfStringItem); - return this; - } - - /** - * Get arrayOfString - * @return arrayOfString - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ARRAY_OF_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List getArrayOfString() { - return arrayOfString; - } - - - @JsonProperty(JSON_PROPERTY_ARRAY_OF_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; - } - - - public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; - return this; - } - - public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { - if (this.arrayArrayOfInteger == null) { - this.arrayArrayOfInteger = new ArrayList<>(); - } - this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); - return this; - } - - /** - * Get arrayArrayOfInteger - * @return arrayArrayOfInteger - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_INTEGER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List> getArrayArrayOfInteger() { - return arrayArrayOfInteger; - } - - - @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_INTEGER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; - } - - - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; - return this; - } - - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { - if (this.arrayArrayOfModel == null) { - this.arrayArrayOfModel = new ArrayList<>(); - } - this.arrayArrayOfModel.add(arrayArrayOfModelItem); - return this; - } - - /** - * Get arrayArrayOfModel - * @return arrayArrayOfModel - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List> getArrayArrayOfModel() { - return arrayArrayOfModel; - } - - - @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; - } - - - /** - * Return true if this ArrayTest object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && - Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); - } - - @Override - public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayTest {\n"); - sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); - sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); - sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Banana.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Banana.java deleted file mode 100644 index 73dae081b0..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Banana.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Banana - */ -@JsonPropertyOrder({ - Banana.JSON_PROPERTY_LENGTH_CM -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Banana { - public static final String JSON_PROPERTY_LENGTH_CM = "lengthCm"; - private BigDecimal lengthCm; - - - public Banana lengthCm(BigDecimal lengthCm) { - this.lengthCm = lengthCm; - return this; - } - - /** - * Get lengthCm - * @return lengthCm - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_LENGTH_CM) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public BigDecimal getLengthCm() { - return lengthCm; - } - - - @JsonProperty(JSON_PROPERTY_LENGTH_CM) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setLengthCm(BigDecimal lengthCm) { - this.lengthCm = lengthCm; - } - - - /** - * Return true if this banana object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Banana banana = (Banana) o; - return Objects.equals(this.lengthCm, banana.lengthCm); - } - - @Override - public int hashCode() { - return Objects.hash(lengthCm); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Banana {\n"); - sb.append(" lengthCm: ").append(toIndentedString(lengthCm)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/BananaReq.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/BananaReq.java deleted file mode 100644 index a21f5c33ee..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/BananaReq.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * BananaReq - */ -@JsonPropertyOrder({ - BananaReq.JSON_PROPERTY_LENGTH_CM, - BananaReq.JSON_PROPERTY_SWEET -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class BananaReq { - public static final String JSON_PROPERTY_LENGTH_CM = "lengthCm"; - private BigDecimal lengthCm; - - public static final String JSON_PROPERTY_SWEET = "sweet"; - private Boolean sweet; - - - public BananaReq lengthCm(BigDecimal lengthCm) { - this.lengthCm = lengthCm; - return this; - } - - /** - * Get lengthCm - * @return lengthCm - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_LENGTH_CM) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public BigDecimal getLengthCm() { - return lengthCm; - } - - - @JsonProperty(JSON_PROPERTY_LENGTH_CM) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setLengthCm(BigDecimal lengthCm) { - this.lengthCm = lengthCm; - } - - - public BananaReq sweet(Boolean sweet) { - this.sweet = sweet; - return this; - } - - /** - * Get sweet - * @return sweet - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_SWEET) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Boolean getSweet() { - return sweet; - } - - - @JsonProperty(JSON_PROPERTY_SWEET) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setSweet(Boolean sweet) { - this.sweet = sweet; - } - - - /** - * Return true if this bananaReq object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - BananaReq bananaReq = (BananaReq) o; - return Objects.equals(this.lengthCm, bananaReq.lengthCm) && - Objects.equals(this.sweet, bananaReq.sweet); - } - - @Override - public int hashCode() { - return Objects.hash(lengthCm, sweet); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class BananaReq {\n"); - sb.append(" lengthCm: ").append(toIndentedString(lengthCm)).append("\n"); - sb.append(" sweet: ").append(toIndentedString(sweet)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/BasquePig.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/BasquePig.java deleted file mode 100644 index 3755c8ad21..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/BasquePig.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * BasquePig - */ -@JsonPropertyOrder({ - BasquePig.JSON_PROPERTY_CLASS_NAME -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class BasquePig { - public static final String JSON_PROPERTY_CLASS_NAME = "className"; - private String className; - - - public BasquePig className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getClassName() { - return className; - } - - - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setClassName(String className) { - this.className = className; - } - - - /** - * Return true if this BasquePig object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - BasquePig basquePig = (BasquePig) o; - return Objects.equals(this.className, basquePig.className); - } - - @Override - public int hashCode() { - return Objects.hash(className); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class BasquePig {\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Capitalization.java deleted file mode 100644 index 89294f5ef6..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Capitalization.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Capitalization - */ -@JsonPropertyOrder({ - Capitalization.JSON_PROPERTY_SMALL_CAMEL, - Capitalization.JSON_PROPERTY_CAPITAL_CAMEL, - Capitalization.JSON_PROPERTY_SMALL_SNAKE, - Capitalization.JSON_PROPERTY_CAPITAL_SNAKE, - Capitalization.JSON_PROPERTY_SC_A_E_T_H_FLOW_POINTS, - Capitalization.JSON_PROPERTY_A_T_T_N_A_M_E -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Capitalization { - public static final String JSON_PROPERTY_SMALL_CAMEL = "smallCamel"; - private String smallCamel; - - public static final String JSON_PROPERTY_CAPITAL_CAMEL = "CapitalCamel"; - private String capitalCamel; - - public static final String JSON_PROPERTY_SMALL_SNAKE = "small_Snake"; - private String smallSnake; - - public static final String JSON_PROPERTY_CAPITAL_SNAKE = "Capital_Snake"; - private String capitalSnake; - - public static final String JSON_PROPERTY_SC_A_E_T_H_FLOW_POINTS = "SCA_ETH_Flow_Points"; - private String scAETHFlowPoints; - - public static final String JSON_PROPERTY_A_T_T_N_A_M_E = "ATT_NAME"; - private String ATT_NAME; - - - public Capitalization smallCamel(String smallCamel) { - this.smallCamel = smallCamel; - return this; - } - - /** - * Get smallCamel - * @return smallCamel - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_SMALL_CAMEL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getSmallCamel() { - return smallCamel; - } - - - @JsonProperty(JSON_PROPERTY_SMALL_CAMEL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setSmallCamel(String smallCamel) { - this.smallCamel = smallCamel; - } - - - public Capitalization capitalCamel(String capitalCamel) { - this.capitalCamel = capitalCamel; - return this; - } - - /** - * Get capitalCamel - * @return capitalCamel - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_CAPITAL_CAMEL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getCapitalCamel() { - return capitalCamel; - } - - - @JsonProperty(JSON_PROPERTY_CAPITAL_CAMEL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setCapitalCamel(String capitalCamel) { - this.capitalCamel = capitalCamel; - } - - - public Capitalization smallSnake(String smallSnake) { - this.smallSnake = smallSnake; - return this; - } - - /** - * Get smallSnake - * @return smallSnake - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_SMALL_SNAKE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getSmallSnake() { - return smallSnake; - } - - - @JsonProperty(JSON_PROPERTY_SMALL_SNAKE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setSmallSnake(String smallSnake) { - this.smallSnake = smallSnake; - } - - - public Capitalization capitalSnake(String capitalSnake) { - this.capitalSnake = capitalSnake; - return this; - } - - /** - * Get capitalSnake - * @return capitalSnake - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_CAPITAL_SNAKE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getCapitalSnake() { - return capitalSnake; - } - - - @JsonProperty(JSON_PROPERTY_CAPITAL_SNAKE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setCapitalSnake(String capitalSnake) { - this.capitalSnake = capitalSnake; - } - - - public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { - this.scAETHFlowPoints = scAETHFlowPoints; - return this; - } - - /** - * Get scAETHFlowPoints - * @return scAETHFlowPoints - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_SC_A_E_T_H_FLOW_POINTS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getScAETHFlowPoints() { - return scAETHFlowPoints; - } - - - @JsonProperty(JSON_PROPERTY_SC_A_E_T_H_FLOW_POINTS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setScAETHFlowPoints(String scAETHFlowPoints) { - this.scAETHFlowPoints = scAETHFlowPoints; - } - - - public Capitalization ATT_NAME(String ATT_NAME) { - this.ATT_NAME = ATT_NAME; - return this; - } - - /** - * Name of the pet - * @return ATT_NAME - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "Name of the pet ") - @JsonProperty(JSON_PROPERTY_A_T_T_N_A_M_E) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getATTNAME() { - return ATT_NAME; - } - - - @JsonProperty(JSON_PROPERTY_A_T_T_N_A_M_E) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setATTNAME(String ATT_NAME) { - this.ATT_NAME = ATT_NAME; - } - - - /** - * Return true if this Capitalization object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Capitalization capitalization = (Capitalization) o; - return Objects.equals(this.smallCamel, capitalization.smallCamel) && - Objects.equals(this.capitalCamel, capitalization.capitalCamel) && - Objects.equals(this.smallSnake, capitalization.smallSnake) && - Objects.equals(this.capitalSnake, capitalization.capitalSnake) && - Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && - Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); - } - - @Override - public int hashCode() { - return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Capitalization {\n"); - sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); - sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); - sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); - sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); - sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); - sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Cat.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Cat.java deleted file mode 100644 index ddecc54736..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Cat.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Animal; -import org.openapitools.client.model.CatAllOf; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import org.openapitools.client.JSON; -/** - * Cat - */ -@JsonPropertyOrder({ - Cat.JSON_PROPERTY_DECLAWED -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "className", visible = true) - -public class Cat extends Animal { - public static final String JSON_PROPERTY_DECLAWED = "declawed"; - private Boolean declawed; - - - public Cat declawed(Boolean declawed) { - this.declawed = declawed; - return this; - } - - /** - * Get declawed - * @return declawed - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_DECLAWED) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Boolean getDeclawed() { - return declawed; - } - - - @JsonProperty(JSON_PROPERTY_DECLAWED) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setDeclawed(Boolean declawed) { - this.declawed = declawed; - } - - - /** - * Return true if this Cat object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Cat cat = (Cat) o; - return Objects.equals(this.declawed, cat.declawed) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(declawed, super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Cat {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -static { - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("Cat", Cat.class); - JSON.registerDiscriminator(Cat.class, "className", mappings); -} -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/CatAllOf.java deleted file mode 100644 index 39934c2a02..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/CatAllOf.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * CatAllOf - */ -@JsonPropertyOrder({ - CatAllOf.JSON_PROPERTY_DECLAWED -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class CatAllOf { - public static final String JSON_PROPERTY_DECLAWED = "declawed"; - private Boolean declawed; - - - public CatAllOf declawed(Boolean declawed) { - this.declawed = declawed; - return this; - } - - /** - * Get declawed - * @return declawed - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_DECLAWED) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Boolean getDeclawed() { - return declawed; - } - - - @JsonProperty(JSON_PROPERTY_DECLAWED) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setDeclawed(Boolean declawed) { - this.declawed = declawed; - } - - - /** - * Return true if this Cat_allOf object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - CatAllOf catAllOf = (CatAllOf) o; - return Objects.equals(this.declawed, catAllOf.declawed); - } - - @Override - public int hashCode() { - return Objects.hash(declawed); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class CatAllOf {\n"); - sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Category.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Category.java deleted file mode 100644 index 130ef22584..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Category.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Category - */ -@JsonPropertyOrder({ - Category.JSON_PROPERTY_ID, - Category.JSON_PROPERTY_NAME -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Category { - public static final String JSON_PROPERTY_ID = "id"; - private Long id; - - public static final String JSON_PROPERTY_NAME = "name"; - private String name = "default-name"; - - - public Category id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Long getId() { - return id; - } - - - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setId(Long id) { - this.id = id; - } - - - public Category name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getName() { - return name; - } - - - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setName(String name) { - this.name = name; - } - - - /** - * Return true if this Category object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Category category = (Category) o; - return Objects.equals(this.id, category.id) && - Objects.equals(this.name, category.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Category {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ChildCat.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ChildCat.java deleted file mode 100644 index b2fc54afa0..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ChildCat.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ChildCatAllOf; -import org.openapitools.client.model.ParentPet; -import java.util.Set; -import java.util.HashSet; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import org.openapitools.client.JSON; -/** - * ChildCat - */ -@JsonPropertyOrder({ - ChildCat.JSON_PROPERTY_NAME, - ChildCat.JSON_PROPERTY_PET_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "pet_type", visible = true) - -public class ChildCat extends ParentPet { - public static final String JSON_PROPERTY_NAME = "name"; - private String name; - - public static final String JSON_PROPERTY_PET_TYPE = "pet_type"; - private String petType = "ChildCat"; - - - public ChildCat name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getName() { - return name; - } - - - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setName(String name) { - this.name = name; - } - - - public static final Set PET_TYPE_VALUES = new HashSet<>(Arrays.asList( - "ChildCat" - )); - - public ChildCat petType(String petType) { - if (!PET_TYPE_VALUES.contains(petType)) { - throw new IllegalArgumentException(petType + " is invalid. Possible values for petType: " + String.join(", ", PET_TYPE_VALUES)); - } - - this.petType = petType; - return this; - } - - /** - * Get petType - * @return petType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_PET_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getPetType() { - return petType; - } - - - @JsonProperty(JSON_PROPERTY_PET_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setPetType(String petType) { - if (!PET_TYPE_VALUES.contains(petType)) { - throw new IllegalArgumentException(petType + " is invalid. Possible values for petType: " + String.join(", ", PET_TYPE_VALUES)); - } - - this.petType = petType; - } - - - /** - * Return true if this ChildCat object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ChildCat childCat = (ChildCat) o; - return Objects.equals(this.name, childCat.name) && - Objects.equals(this.petType, childCat.petType) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(name, petType, super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ChildCat {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" petType: ").append(toIndentedString(petType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -static { - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("ChildCat", ChildCat.class); - JSON.registerDiscriminator(ChildCat.class, "pet_type", mappings); -} -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ChildCatAllOf.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ChildCatAllOf.java deleted file mode 100644 index 7168d83071..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ChildCatAllOf.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.Set; -import java.util.HashSet; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ChildCatAllOf - */ -@JsonPropertyOrder({ - ChildCatAllOf.JSON_PROPERTY_NAME, - ChildCatAllOf.JSON_PROPERTY_PET_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ChildCatAllOf { - public static final String JSON_PROPERTY_NAME = "name"; - private String name; - - public static final String JSON_PROPERTY_PET_TYPE = "pet_type"; - private String petType = "ChildCat"; - - - public ChildCatAllOf name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getName() { - return name; - } - - - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setName(String name) { - this.name = name; - } - - - public static final Set PET_TYPE_VALUES = new HashSet<>(Arrays.asList( - "ChildCat" - )); - - public ChildCatAllOf petType(String petType) { - if (!PET_TYPE_VALUES.contains(petType)) { - throw new IllegalArgumentException(petType + " is invalid. Possible values for petType: " + String.join(", ", PET_TYPE_VALUES)); - } - - this.petType = petType; - return this; - } - - /** - * Get petType - * @return petType - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_PET_TYPE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getPetType() { - return petType; - } - - - @JsonProperty(JSON_PROPERTY_PET_TYPE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setPetType(String petType) { - if (!PET_TYPE_VALUES.contains(petType)) { - throw new IllegalArgumentException(petType + " is invalid. Possible values for petType: " + String.join(", ", PET_TYPE_VALUES)); - } - - this.petType = petType; - } - - - /** - * Return true if this ChildCat_allOf object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ChildCatAllOf childCatAllOf = (ChildCatAllOf) o; - return Objects.equals(this.name, childCatAllOf.name) && - Objects.equals(this.petType, childCatAllOf.petType); - } - - @Override - public int hashCode() { - return Objects.hash(name, petType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ChildCatAllOf {\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" petType: ").append(toIndentedString(petType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ClassModel.java deleted file mode 100644 index df97250205..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ClassModel.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Model for testing model with \"_class\" property - */ -@ApiModel(description = "Model for testing model with \"_class\" property") -@JsonPropertyOrder({ - ClassModel.JSON_PROPERTY_PROPERTY_CLASS -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ClassModel { - public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; - private String propertyClass; - - - public ClassModel propertyClass(String propertyClass) { - this.propertyClass = propertyClass; - return this; - } - - /** - * Get propertyClass - * @return propertyClass - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_PROPERTY_CLASS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getPropertyClass() { - return propertyClass; - } - - - @JsonProperty(JSON_PROPERTY_PROPERTY_CLASS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setPropertyClass(String propertyClass) { - this.propertyClass = propertyClass; - } - - - /** - * Return true if this ClassModel object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ClassModel classModel = (ClassModel) o; - return Objects.equals(this.propertyClass, classModel.propertyClass); - } - - @Override - public int hashCode() { - return Objects.hash(propertyClass); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ClassModel {\n"); - sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Client.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Client.java deleted file mode 100644 index c6bdbf4ba6..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Client.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Client - */ -@JsonPropertyOrder({ - Client.JSON_PROPERTY_CLIENT -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Client { - public static final String JSON_PROPERTY_CLIENT = "client"; - private String client; - - - public Client client(String client) { - this.client = client; - return this; - } - - /** - * Get client - * @return client - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_CLIENT) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getClient() { - return client; - } - - - @JsonProperty(JSON_PROPERTY_CLIENT) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setClient(String client) { - this.client = client; - } - - - /** - * Return true if this Client object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Client client = (Client) o; - return Objects.equals(this.client, client.client); - } - - @Override - public int hashCode() { - return Objects.hash(client); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Client {\n"); - sb.append(" client: ").append(toIndentedString(client)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java deleted file mode 100644 index c6672e54e1..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.QuadrilateralInterface; -import org.openapitools.client.model.ShapeInterface; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ComplexQuadrilateral - */ -@JsonPropertyOrder({ - ComplexQuadrilateral.JSON_PROPERTY_SHAPE_TYPE, - ComplexQuadrilateral.JSON_PROPERTY_QUADRILATERAL_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ComplexQuadrilateral { - public static final String JSON_PROPERTY_SHAPE_TYPE = "shapeType"; - private String shapeType; - - public static final String JSON_PROPERTY_QUADRILATERAL_TYPE = "quadrilateralType"; - private String quadrilateralType; - - - public ComplexQuadrilateral shapeType(String shapeType) { - this.shapeType = shapeType; - return this; - } - - /** - * Get shapeType - * @return shapeType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getShapeType() { - return shapeType; - } - - - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setShapeType(String shapeType) { - this.shapeType = shapeType; - } - - - public ComplexQuadrilateral quadrilateralType(String quadrilateralType) { - this.quadrilateralType = quadrilateralType; - return this; - } - - /** - * Get quadrilateralType - * @return quadrilateralType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_QUADRILATERAL_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getQuadrilateralType() { - return quadrilateralType; - } - - - @JsonProperty(JSON_PROPERTY_QUADRILATERAL_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setQuadrilateralType(String quadrilateralType) { - this.quadrilateralType = quadrilateralType; - } - - - /** - * Return true if this ComplexQuadrilateral object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ComplexQuadrilateral complexQuadrilateral = (ComplexQuadrilateral) o; - return Objects.equals(this.shapeType, complexQuadrilateral.shapeType) && - Objects.equals(this.quadrilateralType, complexQuadrilateral.quadrilateralType); - } - - @Override - public int hashCode() { - return Objects.hash(shapeType, quadrilateralType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ComplexQuadrilateral {\n"); - sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); - sb.append(" quadrilateralType: ").append(toIndentedString(quadrilateralType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/DanishPig.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/DanishPig.java deleted file mode 100644 index 0f9c0ad005..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/DanishPig.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * DanishPig - */ -@JsonPropertyOrder({ - DanishPig.JSON_PROPERTY_CLASS_NAME -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DanishPig { - public static final String JSON_PROPERTY_CLASS_NAME = "className"; - private String className; - - - public DanishPig className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getClassName() { - return className; - } - - - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setClassName(String className) { - this.className = className; - } - - - /** - * Return true if this DanishPig object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DanishPig danishPig = (DanishPig) o; - return Objects.equals(this.className, danishPig.className); - } - - @Override - public int hashCode() { - return Objects.hash(className); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DanishPig {\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/DeprecatedObject.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/DeprecatedObject.java deleted file mode 100644 index b1c356f1ca..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/DeprecatedObject.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * DeprecatedObject - * @deprecated - */ -@Deprecated -@JsonPropertyOrder({ - DeprecatedObject.JSON_PROPERTY_NAME -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DeprecatedObject { - public static final String JSON_PROPERTY_NAME = "name"; - private String name; - - - public DeprecatedObject name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getName() { - return name; - } - - - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setName(String name) { - this.name = name; - } - - - /** - * Return true if this DeprecatedObject object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DeprecatedObject deprecatedObject = (DeprecatedObject) o; - return Objects.equals(this.name, deprecatedObject.name); - } - - @Override - public int hashCode() { - return Objects.hash(name); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DeprecatedObject {\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Dog.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Dog.java deleted file mode 100644 index 9baad459f3..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Dog.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Animal; -import org.openapitools.client.model.DogAllOf; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import org.openapitools.client.JSON; -/** - * Dog - */ -@JsonPropertyOrder({ - Dog.JSON_PROPERTY_BREED -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "className", visible = true) - -public class Dog extends Animal { - public static final String JSON_PROPERTY_BREED = "breed"; - private String breed; - - - public Dog breed(String breed) { - this.breed = breed; - return this; - } - - /** - * Get breed - * @return breed - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_BREED) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getBreed() { - return breed; - } - - - @JsonProperty(JSON_PROPERTY_BREED) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setBreed(String breed) { - this.breed = breed; - } - - - /** - * Return true if this Dog object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Dog dog = (Dog) o; - return Objects.equals(this.breed, dog.breed) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(breed, super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Dog {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -static { - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("Dog", Dog.class); - JSON.registerDiscriminator(Dog.class, "className", mappings); -} -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/DogAllOf.java deleted file mode 100644 index d553743634..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/DogAllOf.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * DogAllOf - */ -@JsonPropertyOrder({ - DogAllOf.JSON_PROPERTY_BREED -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class DogAllOf { - public static final String JSON_PROPERTY_BREED = "breed"; - private String breed; - - - public DogAllOf breed(String breed) { - this.breed = breed; - return this; - } - - /** - * Get breed - * @return breed - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_BREED) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getBreed() { - return breed; - } - - - @JsonProperty(JSON_PROPERTY_BREED) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setBreed(String breed) { - this.breed = breed; - } - - - /** - * Return true if this Dog_allOf object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DogAllOf dogAllOf = (DogAllOf) o; - return Objects.equals(this.breed, dogAllOf.breed); - } - - @Override - public int hashCode() { - return Objects.hash(breed); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DogAllOf {\n"); - sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Drawing.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Drawing.java deleted file mode 100644 index 213c4d548c..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Drawing.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.openapitools.client.model.Fruit; -import org.openapitools.client.model.NullableShape; -import org.openapitools.client.model.Shape; -import org.openapitools.client.model.ShapeOrNull; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Drawing - */ -@JsonPropertyOrder({ - Drawing.JSON_PROPERTY_MAIN_SHAPE, - Drawing.JSON_PROPERTY_SHAPE_OR_NULL, - Drawing.JSON_PROPERTY_NULLABLE_SHAPE, - Drawing.JSON_PROPERTY_SHAPES -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Drawing extends HashMap { - public static final String JSON_PROPERTY_MAIN_SHAPE = "mainShape"; - private Shape mainShape; - - public static final String JSON_PROPERTY_SHAPE_OR_NULL = "shapeOrNull"; - private ShapeOrNull shapeOrNull; - - public static final String JSON_PROPERTY_NULLABLE_SHAPE = "nullableShape"; - private JsonNullable nullableShape = JsonNullable.undefined(); - - public static final String JSON_PROPERTY_SHAPES = "shapes"; - private List shapes = null; - - - public Drawing mainShape(Shape mainShape) { - this.mainShape = mainShape; - return this; - } - - /** - * Get mainShape - * @return mainShape - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAIN_SHAPE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Shape getMainShape() { - return mainShape; - } - - - @JsonProperty(JSON_PROPERTY_MAIN_SHAPE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMainShape(Shape mainShape) { - this.mainShape = mainShape; - } - - - public Drawing shapeOrNull(ShapeOrNull shapeOrNull) { - this.shapeOrNull = shapeOrNull; - return this; - } - - /** - * Get shapeOrNull - * @return shapeOrNull - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_SHAPE_OR_NULL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public ShapeOrNull getShapeOrNull() { - return shapeOrNull; - } - - - @JsonProperty(JSON_PROPERTY_SHAPE_OR_NULL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setShapeOrNull(ShapeOrNull shapeOrNull) { - this.shapeOrNull = shapeOrNull; - } - - - public Drawing nullableShape(NullableShape nullableShape) { - this.nullableShape = JsonNullable.of(nullableShape); - return this; - } - - /** - * Get nullableShape - * @return nullableShape - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public NullableShape getNullableShape() { - return nullableShape.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_NULLABLE_SHAPE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getNullableShape_JsonNullable() { - return nullableShape; - } - - @JsonProperty(JSON_PROPERTY_NULLABLE_SHAPE) - public void setNullableShape_JsonNullable(JsonNullable nullableShape) { - this.nullableShape = nullableShape; - } - - public void setNullableShape(NullableShape nullableShape) { - this.nullableShape = JsonNullable.of(nullableShape); - } - - - public Drawing shapes(List shapes) { - this.shapes = shapes; - return this; - } - - public Drawing addShapesItem(Shape shapesItem) { - if (this.shapes == null) { - this.shapes = new ArrayList<>(); - } - this.shapes.add(shapesItem); - return this; - } - - /** - * Get shapes - * @return shapes - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_SHAPES) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List getShapes() { - return shapes; - } - - - @JsonProperty(JSON_PROPERTY_SHAPES) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setShapes(List shapes) { - this.shapes = shapes; - } - - /** - * A container for additional, undeclared properties. - * This is a holder for any undeclared properties as specified with - * the 'additionalProperties' keyword in the OAS document. - */ - private Map additionalProperties; - - /** - * Set the additional (undeclared) property with the specified name and value. - * If the property does not already exist, create it otherwise replace it. - */ - @JsonAnySetter - public Drawing putAdditionalProperty(String key, Fruit value) { - if (this.additionalProperties == null) { - this.additionalProperties = new HashMap(); - } - this.additionalProperties.put(key, value); - return this; - } - - /** - * Return the additional (undeclared) property. - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return additionalProperties; - } - - /** - * Return the additional (undeclared) property with the specified name. - */ - public Fruit getAdditionalProperty(String key) { - if (this.additionalProperties == null) { - return null; - } - return this.additionalProperties.get(key); - } - - /** - * Return true if this Drawing object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Drawing drawing = (Drawing) o; - return Objects.equals(this.mainShape, drawing.mainShape) && - Objects.equals(this.shapeOrNull, drawing.shapeOrNull) && - Objects.equals(this.nullableShape, drawing.nullableShape) && - Objects.equals(this.shapes, drawing.shapes)&& - Objects.equals(this.additionalProperties, drawing.additionalProperties) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(mainShape, shapeOrNull, nullableShape, shapes, super.hashCode(), additionalProperties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Drawing {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" mainShape: ").append(toIndentedString(mainShape)).append("\n"); - sb.append(" shapeOrNull: ").append(toIndentedString(shapeOrNull)).append("\n"); - sb.append(" nullableShape: ").append(toIndentedString(nullableShape)).append("\n"); - sb.append(" shapes: ").append(toIndentedString(shapes)).append("\n"); - sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EnumArrays.java deleted file mode 100644 index cc9944eec5..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EnumArrays.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * EnumArrays - */ -@JsonPropertyOrder({ - EnumArrays.JSON_PROPERTY_JUST_SYMBOL, - EnumArrays.JSON_PROPERTY_ARRAY_ENUM -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class EnumArrays { - /** - * Gets or Sets justSymbol - */ - public enum JustSymbolEnum { - GREATER_THAN_OR_EQUAL_TO(">="), - - DOLLAR("$"); - - private String value; - - JustSymbolEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static JustSymbolEnum fromValue(String value) { - for (JustSymbolEnum b : JustSymbolEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_JUST_SYMBOL = "just_symbol"; - private JustSymbolEnum justSymbol; - - /** - * Gets or Sets arrayEnum - */ - public enum ArrayEnumEnum { - FISH("fish"), - - CRAB("crab"); - - private String value; - - ArrayEnumEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static ArrayEnumEnum fromValue(String value) { - for (ArrayEnumEnum b : ArrayEnumEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_ARRAY_ENUM = "array_enum"; - private List arrayEnum = null; - - - public EnumArrays justSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; - return this; - } - - /** - * Get justSymbol - * @return justSymbol - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_JUST_SYMBOL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JustSymbolEnum getJustSymbol() { - return justSymbol; - } - - - @JsonProperty(JSON_PROPERTY_JUST_SYMBOL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setJustSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; - } - - - public EnumArrays arrayEnum(List arrayEnum) { - this.arrayEnum = arrayEnum; - return this; - } - - public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { - if (this.arrayEnum == null) { - this.arrayEnum = new ArrayList<>(); - } - this.arrayEnum.add(arrayEnumItem); - return this; - } - - /** - * Get arrayEnum - * @return arrayEnum - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ARRAY_ENUM) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List getArrayEnum() { - return arrayEnum; - } - - - @JsonProperty(JSON_PROPERTY_ARRAY_ENUM) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayEnum(List arrayEnum) { - this.arrayEnum = arrayEnum; - } - - - /** - * Return true if this EnumArrays object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - EnumArrays enumArrays = (EnumArrays) o; - return Objects.equals(this.justSymbol, enumArrays.justSymbol) && - Objects.equals(this.arrayEnum, enumArrays.arrayEnum); - } - - @Override - public int hashCode() { - return Objects.hash(justSymbol, arrayEnum); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumArrays {\n"); - sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); - sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EnumClass.java deleted file mode 100644 index 0fdfb1bf6b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EnumClass.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - -/** - * Gets or Sets EnumClass - */ -public enum EnumClass { - - _ABC("_abc"), - - _EFG("-efg"), - - _XYZ_("(xyz)"); - - private String value; - - EnumClass(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumClass fromValue(String value) { - for (EnumClass b : EnumClass.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EnumTest.java deleted file mode 100644 index a6fbd06d9b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EnumTest.java +++ /dev/null @@ -1,559 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.OuterEnum; -import org.openapitools.client.model.OuterEnumDefaultValue; -import org.openapitools.client.model.OuterEnumInteger; -import org.openapitools.client.model.OuterEnumIntegerDefaultValue; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * EnumTest - */ -@JsonPropertyOrder({ - EnumTest.JSON_PROPERTY_ENUM_STRING, - EnumTest.JSON_PROPERTY_ENUM_STRING_REQUIRED, - EnumTest.JSON_PROPERTY_ENUM_INTEGER, - EnumTest.JSON_PROPERTY_ENUM_INTEGER_ONLY, - EnumTest.JSON_PROPERTY_ENUM_NUMBER, - EnumTest.JSON_PROPERTY_OUTER_ENUM, - EnumTest.JSON_PROPERTY_OUTER_ENUM_INTEGER, - EnumTest.JSON_PROPERTY_OUTER_ENUM_DEFAULT_VALUE, - EnumTest.JSON_PROPERTY_OUTER_ENUM_INTEGER_DEFAULT_VALUE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class EnumTest { - /** - * Gets or Sets enumString - */ - public enum EnumStringEnum { - UPPER("UPPER"), - - LOWER("lower"), - - EMPTY(""); - - private String value; - - EnumStringEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumStringEnum fromValue(String value) { - for (EnumStringEnum b : EnumStringEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_ENUM_STRING = "enum_string"; - private EnumStringEnum enumString; - - /** - * Gets or Sets enumStringRequired - */ - public enum EnumStringRequiredEnum { - UPPER("UPPER"), - - LOWER("lower"), - - EMPTY(""); - - private String value; - - EnumStringRequiredEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumStringRequiredEnum fromValue(String value) { - for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_ENUM_STRING_REQUIRED = "enum_string_required"; - private EnumStringRequiredEnum enumStringRequired; - - /** - * Gets or Sets enumInteger - */ - public enum EnumIntegerEnum { - NUMBER_1(1), - - NUMBER_MINUS_1(-1); - - private Integer value; - - EnumIntegerEnum(Integer value) { - this.value = value; - } - - @JsonValue - public Integer getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumIntegerEnum fromValue(Integer value) { - for (EnumIntegerEnum b : EnumIntegerEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_ENUM_INTEGER = "enum_integer"; - private EnumIntegerEnum enumInteger; - - /** - * Gets or Sets enumIntegerOnly - */ - public enum EnumIntegerOnlyEnum { - NUMBER_2(2), - - NUMBER_MINUS_2(-2); - - private Integer value; - - EnumIntegerOnlyEnum(Integer value) { - this.value = value; - } - - @JsonValue - public Integer getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumIntegerOnlyEnum fromValue(Integer value) { - for (EnumIntegerOnlyEnum b : EnumIntegerOnlyEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_ENUM_INTEGER_ONLY = "enum_integer_only"; - private EnumIntegerOnlyEnum enumIntegerOnly; - - /** - * Gets or Sets enumNumber - */ - public enum EnumNumberEnum { - NUMBER_1_DOT_1(1.1), - - NUMBER_MINUS_1_DOT_2(-1.2); - - private Double value; - - EnumNumberEnum(Double value) { - this.value = value; - } - - @JsonValue - public Double getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumNumberEnum fromValue(Double value) { - for (EnumNumberEnum b : EnumNumberEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_ENUM_NUMBER = "enum_number"; - private EnumNumberEnum enumNumber; - - public static final String JSON_PROPERTY_OUTER_ENUM = "outerEnum"; - private JsonNullable outerEnum = JsonNullable.undefined(); - - public static final String JSON_PROPERTY_OUTER_ENUM_INTEGER = "outerEnumInteger"; - private OuterEnumInteger outerEnumInteger; - - public static final String JSON_PROPERTY_OUTER_ENUM_DEFAULT_VALUE = "outerEnumDefaultValue"; - private OuterEnumDefaultValue outerEnumDefaultValue = OuterEnumDefaultValue.PLACED; - - public static final String JSON_PROPERTY_OUTER_ENUM_INTEGER_DEFAULT_VALUE = "outerEnumIntegerDefaultValue"; - private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; - - - public EnumTest enumString(EnumStringEnum enumString) { - this.enumString = enumString; - return this; - } - - /** - * Get enumString - * @return enumString - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ENUM_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public EnumStringEnum getEnumString() { - return enumString; - } - - - @JsonProperty(JSON_PROPERTY_ENUM_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setEnumString(EnumStringEnum enumString) { - this.enumString = enumString; - } - - - public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { - this.enumStringRequired = enumStringRequired; - return this; - } - - /** - * Get enumStringRequired - * @return enumStringRequired - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_ENUM_STRING_REQUIRED) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public EnumStringRequiredEnum getEnumStringRequired() { - return enumStringRequired; - } - - - @JsonProperty(JSON_PROPERTY_ENUM_STRING_REQUIRED) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { - this.enumStringRequired = enumStringRequired; - } - - - public EnumTest enumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - return this; - } - - /** - * Get enumInteger - * @return enumInteger - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ENUM_INTEGER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public EnumIntegerEnum getEnumInteger() { - return enumInteger; - } - - - @JsonProperty(JSON_PROPERTY_ENUM_INTEGER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setEnumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - } - - - public EnumTest enumIntegerOnly(EnumIntegerOnlyEnum enumIntegerOnly) { - this.enumIntegerOnly = enumIntegerOnly; - return this; - } - - /** - * Get enumIntegerOnly - * @return enumIntegerOnly - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ENUM_INTEGER_ONLY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public EnumIntegerOnlyEnum getEnumIntegerOnly() { - return enumIntegerOnly; - } - - - @JsonProperty(JSON_PROPERTY_ENUM_INTEGER_ONLY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setEnumIntegerOnly(EnumIntegerOnlyEnum enumIntegerOnly) { - this.enumIntegerOnly = enumIntegerOnly; - } - - - public EnumTest enumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - return this; - } - - /** - * Get enumNumber - * @return enumNumber - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ENUM_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public EnumNumberEnum getEnumNumber() { - return enumNumber; - } - - - @JsonProperty(JSON_PROPERTY_ENUM_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setEnumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - } - - - public EnumTest outerEnum(OuterEnum outerEnum) { - this.outerEnum = JsonNullable.of(outerEnum); - return this; - } - - /** - * Get outerEnum - * @return outerEnum - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public OuterEnum getOuterEnum() { - return outerEnum.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_OUTER_ENUM) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getOuterEnum_JsonNullable() { - return outerEnum; - } - - @JsonProperty(JSON_PROPERTY_OUTER_ENUM) - public void setOuterEnum_JsonNullable(JsonNullable outerEnum) { - this.outerEnum = outerEnum; - } - - public void setOuterEnum(OuterEnum outerEnum) { - this.outerEnum = JsonNullable.of(outerEnum); - } - - - public EnumTest outerEnumInteger(OuterEnumInteger outerEnumInteger) { - this.outerEnumInteger = outerEnumInteger; - return this; - } - - /** - * Get outerEnumInteger - * @return outerEnumInteger - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_OUTER_ENUM_INTEGER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public OuterEnumInteger getOuterEnumInteger() { - return outerEnumInteger; - } - - - @JsonProperty(JSON_PROPERTY_OUTER_ENUM_INTEGER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setOuterEnumInteger(OuterEnumInteger outerEnumInteger) { - this.outerEnumInteger = outerEnumInteger; - } - - - public EnumTest outerEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { - this.outerEnumDefaultValue = outerEnumDefaultValue; - return this; - } - - /** - * Get outerEnumDefaultValue - * @return outerEnumDefaultValue - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_OUTER_ENUM_DEFAULT_VALUE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public OuterEnumDefaultValue getOuterEnumDefaultValue() { - return outerEnumDefaultValue; - } - - - @JsonProperty(JSON_PROPERTY_OUTER_ENUM_DEFAULT_VALUE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setOuterEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { - this.outerEnumDefaultValue = outerEnumDefaultValue; - } - - - public EnumTest outerEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { - this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; - return this; - } - - /** - * Get outerEnumIntegerDefaultValue - * @return outerEnumIntegerDefaultValue - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_OUTER_ENUM_INTEGER_DEFAULT_VALUE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() { - return outerEnumIntegerDefaultValue; - } - - - @JsonProperty(JSON_PROPERTY_OUTER_ENUM_INTEGER_DEFAULT_VALUE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setOuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { - this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; - } - - - /** - * Return true if this Enum_Test object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - EnumTest enumTest = (EnumTest) o; - return Objects.equals(this.enumString, enumTest.enumString) && - Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && - Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumIntegerOnly, enumTest.enumIntegerOnly) && - Objects.equals(this.enumNumber, enumTest.enumNumber) && - Objects.equals(this.outerEnum, enumTest.outerEnum) && - Objects.equals(this.outerEnumInteger, enumTest.outerEnumInteger) && - Objects.equals(this.outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && - Objects.equals(this.outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue); - } - - @Override - public int hashCode() { - return Objects.hash(enumString, enumStringRequired, enumInteger, enumIntegerOnly, enumNumber, outerEnum, outerEnumInteger, outerEnumDefaultValue, outerEnumIntegerDefaultValue); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumTest {\n"); - sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); - sb.append(" enumStringRequired: ").append(toIndentedString(enumStringRequired)).append("\n"); - sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); - sb.append(" enumIntegerOnly: ").append(toIndentedString(enumIntegerOnly)).append("\n"); - sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); - sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); - sb.append(" outerEnumInteger: ").append(toIndentedString(outerEnumInteger)).append("\n"); - sb.append(" outerEnumDefaultValue: ").append(toIndentedString(outerEnumDefaultValue)).append("\n"); - sb.append(" outerEnumIntegerDefaultValue: ").append(toIndentedString(outerEnumIntegerDefaultValue)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EquilateralTriangle.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EquilateralTriangle.java deleted file mode 100644 index c122af1f45..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/EquilateralTriangle.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ShapeInterface; -import org.openapitools.client.model.TriangleInterface; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * EquilateralTriangle - */ -@JsonPropertyOrder({ - EquilateralTriangle.JSON_PROPERTY_SHAPE_TYPE, - EquilateralTriangle.JSON_PROPERTY_TRIANGLE_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class EquilateralTriangle { - public static final String JSON_PROPERTY_SHAPE_TYPE = "shapeType"; - private String shapeType; - - public static final String JSON_PROPERTY_TRIANGLE_TYPE = "triangleType"; - private String triangleType; - - - public EquilateralTriangle shapeType(String shapeType) { - this.shapeType = shapeType; - return this; - } - - /** - * Get shapeType - * @return shapeType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getShapeType() { - return shapeType; - } - - - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setShapeType(String shapeType) { - this.shapeType = shapeType; - } - - - public EquilateralTriangle triangleType(String triangleType) { - this.triangleType = triangleType; - return this; - } - - /** - * Get triangleType - * @return triangleType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_TRIANGLE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getTriangleType() { - return triangleType; - } - - - @JsonProperty(JSON_PROPERTY_TRIANGLE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setTriangleType(String triangleType) { - this.triangleType = triangleType; - } - - - /** - * Return true if this EquilateralTriangle object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - EquilateralTriangle equilateralTriangle = (EquilateralTriangle) o; - return Objects.equals(this.shapeType, equilateralTriangle.shapeType) && - Objects.equals(this.triangleType, equilateralTriangle.triangleType); - } - - @Override - public int hashCode() { - return Objects.hash(shapeType, triangleType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EquilateralTriangle {\n"); - sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); - sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java deleted file mode 100644 index 74e4a914ed..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * FileSchemaTestClass - */ -@JsonPropertyOrder({ - FileSchemaTestClass.JSON_PROPERTY_FILE, - FileSchemaTestClass.JSON_PROPERTY_FILES -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class FileSchemaTestClass { - public static final String JSON_PROPERTY_FILE = "file"; - private java.io.File file; - - public static final String JSON_PROPERTY_FILES = "files"; - private List files = null; - - - public FileSchemaTestClass file(java.io.File file) { - this.file = file; - return this; - } - - /** - * Get file - * @return file - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_FILE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public java.io.File getFile() { - return file; - } - - - @JsonProperty(JSON_PROPERTY_FILE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setFile(java.io.File file) { - this.file = file; - } - - - public FileSchemaTestClass files(List files) { - this.files = files; - return this; - } - - public FileSchemaTestClass addFilesItem(java.io.File filesItem) { - if (this.files == null) { - this.files = new ArrayList<>(); - } - this.files.add(filesItem); - return this; - } - - /** - * Get files - * @return files - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_FILES) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List getFiles() { - return files; - } - - - @JsonProperty(JSON_PROPERTY_FILES) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setFiles(List files) { - this.files = files; - } - - - /** - * Return true if this FileSchemaTestClass object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; - return Objects.equals(this.file, fileSchemaTestClass.file) && - Objects.equals(this.files, fileSchemaTestClass.files); - } - - @Override - public int hashCode() { - return Objects.hash(file, files); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class FileSchemaTestClass {\n"); - sb.append(" file: ").append(toIndentedString(file)).append("\n"); - sb.append(" files: ").append(toIndentedString(files)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Foo.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Foo.java deleted file mode 100644 index f5e65c3424..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Foo.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Foo - */ -@JsonPropertyOrder({ - Foo.JSON_PROPERTY_BAR -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Foo { - public static final String JSON_PROPERTY_BAR = "bar"; - private String bar = "bar"; - - - public Foo bar(String bar) { - this.bar = bar; - return this; - } - - /** - * Get bar - * @return bar - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_BAR) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getBar() { - return bar; - } - - - @JsonProperty(JSON_PROPERTY_BAR) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setBar(String bar) { - this.bar = bar; - } - - - /** - * Return true if this Foo object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Foo foo = (Foo) o; - return Objects.equals(this.bar, foo.bar); - } - - @Override - public int hashCode() { - return Objects.hash(bar); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Foo {\n"); - sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FormatTest.java deleted file mode 100644 index 34dcfd8c31..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FormatTest.java +++ /dev/null @@ -1,604 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.io.File; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.util.UUID; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * FormatTest - */ -@JsonPropertyOrder({ - FormatTest.JSON_PROPERTY_INTEGER, - FormatTest.JSON_PROPERTY_INT32, - FormatTest.JSON_PROPERTY_INT64, - FormatTest.JSON_PROPERTY_NUMBER, - FormatTest.JSON_PROPERTY_FLOAT, - FormatTest.JSON_PROPERTY_DOUBLE, - FormatTest.JSON_PROPERTY_DECIMAL, - FormatTest.JSON_PROPERTY_STRING, - FormatTest.JSON_PROPERTY_BYTE, - FormatTest.JSON_PROPERTY_BINARY, - FormatTest.JSON_PROPERTY_DATE, - FormatTest.JSON_PROPERTY_DATE_TIME, - FormatTest.JSON_PROPERTY_UUID, - FormatTest.JSON_PROPERTY_PASSWORD, - FormatTest.JSON_PROPERTY_PATTERN_WITH_DIGITS, - FormatTest.JSON_PROPERTY_PATTERN_WITH_DIGITS_AND_DELIMITER -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class FormatTest { - public static final String JSON_PROPERTY_INTEGER = "integer"; - private Integer integer; - - public static final String JSON_PROPERTY_INT32 = "int32"; - private Integer int32; - - public static final String JSON_PROPERTY_INT64 = "int64"; - private Long int64; - - public static final String JSON_PROPERTY_NUMBER = "number"; - private BigDecimal number; - - public static final String JSON_PROPERTY_FLOAT = "float"; - private Float _float; - - public static final String JSON_PROPERTY_DOUBLE = "double"; - private Double _double; - - public static final String JSON_PROPERTY_DECIMAL = "decimal"; - private BigDecimal decimal; - - public static final String JSON_PROPERTY_STRING = "string"; - private String string; - - public static final String JSON_PROPERTY_BYTE = "byte"; - private byte[] _byte; - - public static final String JSON_PROPERTY_BINARY = "binary"; - private File binary; - - public static final String JSON_PROPERTY_DATE = "date"; - private LocalDate date; - - public static final String JSON_PROPERTY_DATE_TIME = "dateTime"; - private OffsetDateTime dateTime; - - public static final String JSON_PROPERTY_UUID = "uuid"; - private UUID uuid; - - public static final String JSON_PROPERTY_PASSWORD = "password"; - private String password; - - public static final String JSON_PROPERTY_PATTERN_WITH_DIGITS = "pattern_with_digits"; - private String patternWithDigits; - - public static final String JSON_PROPERTY_PATTERN_WITH_DIGITS_AND_DELIMITER = "pattern_with_digits_and_delimiter"; - private String patternWithDigitsAndDelimiter; - - - public FormatTest integer(Integer integer) { - this.integer = integer; - return this; - } - - /** - * Get integer - * minimum: 10 - * maximum: 100 - * @return integer - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_INTEGER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getInteger() { - return integer; - } - - - @JsonProperty(JSON_PROPERTY_INTEGER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setInteger(Integer integer) { - this.integer = integer; - } - - - public FormatTest int32(Integer int32) { - this.int32 = int32; - return this; - } - - /** - * Get int32 - * minimum: 20 - * maximum: 200 - * @return int32 - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_INT32) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getInt32() { - return int32; - } - - - @JsonProperty(JSON_PROPERTY_INT32) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setInt32(Integer int32) { - this.int32 = int32; - } - - - public FormatTest int64(Long int64) { - this.int64 = int64; - return this; - } - - /** - * Get int64 - * @return int64 - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_INT64) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Long getInt64() { - return int64; - } - - - @JsonProperty(JSON_PROPERTY_INT64) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setInt64(Long int64) { - this.int64 = int64; - } - - - public FormatTest number(BigDecimal number) { - this.number = number; - return this; - } - - /** - * Get number - * minimum: 32.1 - * maximum: 543.2 - * @return number - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_NUMBER) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public BigDecimal getNumber() { - return number; - } - - - @JsonProperty(JSON_PROPERTY_NUMBER) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setNumber(BigDecimal number) { - this.number = number; - } - - - public FormatTest _float(Float _float) { - this._float = _float; - return this; - } - - /** - * Get _float - * minimum: 54.3 - * maximum: 987.6 - * @return _float - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_FLOAT) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Float getFloat() { - return _float; - } - - - @JsonProperty(JSON_PROPERTY_FLOAT) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setFloat(Float _float) { - this._float = _float; - } - - - public FormatTest _double(Double _double) { - this._double = _double; - return this; - } - - /** - * Get _double - * minimum: 67.8 - * maximum: 123.4 - * @return _double - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_DOUBLE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Double getDouble() { - return _double; - } - - - @JsonProperty(JSON_PROPERTY_DOUBLE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setDouble(Double _double) { - this._double = _double; - } - - - public FormatTest decimal(BigDecimal decimal) { - this.decimal = decimal; - return this; - } - - /** - * Get decimal - * @return decimal - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_DECIMAL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public BigDecimal getDecimal() { - return decimal; - } - - - @JsonProperty(JSON_PROPERTY_DECIMAL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setDecimal(BigDecimal decimal) { - this.decimal = decimal; - } - - - public FormatTest string(String string) { - this.string = string; - return this; - } - - /** - * Get string - * @return string - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getString() { - return string; - } - - - @JsonProperty(JSON_PROPERTY_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setString(String string) { - this.string = string; - } - - - public FormatTest _byte(byte[] _byte) { - this._byte = _byte; - return this; - } - - /** - * Get _byte - * @return _byte - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_BYTE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public byte[] getByte() { - return _byte; - } - - - @JsonProperty(JSON_PROPERTY_BYTE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setByte(byte[] _byte) { - this._byte = _byte; - } - - - public FormatTest binary(File binary) { - this.binary = binary; - return this; - } - - /** - * Get binary - * @return binary - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_BINARY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public File getBinary() { - return binary; - } - - - @JsonProperty(JSON_PROPERTY_BINARY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setBinary(File binary) { - this.binary = binary; - } - - - public FormatTest date(LocalDate date) { - this.date = date; - return this; - } - - /** - * Get date - * @return date - **/ - @javax.annotation.Nonnull - @ApiModelProperty(example = "Sun Feb 02 00:00:00 UTC 2020", required = true, value = "") - @JsonProperty(JSON_PROPERTY_DATE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public LocalDate getDate() { - return date; - } - - - @JsonProperty(JSON_PROPERTY_DATE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setDate(LocalDate date) { - this.date = date; - } - - - public FormatTest dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; - return this; - } - - /** - * Get dateTime - * @return dateTime - **/ - @javax.annotation.Nullable - @ApiModelProperty(example = "2007-12-03T10:15:30+01:00", value = "") - @JsonProperty(JSON_PROPERTY_DATE_TIME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public OffsetDateTime getDateTime() { - return dateTime; - } - - - @JsonProperty(JSON_PROPERTY_DATE_TIME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setDateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; - } - - - public FormatTest uuid(UUID uuid) { - this.uuid = uuid; - return this; - } - - /** - * Get uuid - * @return uuid - **/ - @javax.annotation.Nullable - @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") - @JsonProperty(JSON_PROPERTY_UUID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public UUID getUuid() { - return uuid; - } - - - @JsonProperty(JSON_PROPERTY_UUID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setUuid(UUID uuid) { - this.uuid = uuid; - } - - - public FormatTest password(String password) { - this.password = password; - return this; - } - - /** - * Get password - * @return password - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_PASSWORD) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getPassword() { - return password; - } - - - @JsonProperty(JSON_PROPERTY_PASSWORD) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setPassword(String password) { - this.password = password; - } - - - public FormatTest patternWithDigits(String patternWithDigits) { - this.patternWithDigits = patternWithDigits; - return this; - } - - /** - * A string that is a 10 digit number. Can have leading zeros. - * @return patternWithDigits - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "A string that is a 10 digit number. Can have leading zeros.") - @JsonProperty(JSON_PROPERTY_PATTERN_WITH_DIGITS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getPatternWithDigits() { - return patternWithDigits; - } - - - @JsonProperty(JSON_PROPERTY_PATTERN_WITH_DIGITS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setPatternWithDigits(String patternWithDigits) { - this.patternWithDigits = patternWithDigits; - } - - - public FormatTest patternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { - this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; - return this; - } - - /** - * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. - * @return patternWithDigitsAndDelimiter - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.") - @JsonProperty(JSON_PROPERTY_PATTERN_WITH_DIGITS_AND_DELIMITER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getPatternWithDigitsAndDelimiter() { - return patternWithDigitsAndDelimiter; - } - - - @JsonProperty(JSON_PROPERTY_PATTERN_WITH_DIGITS_AND_DELIMITER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setPatternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { - this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; - } - - - /** - * Return true if this format_test object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - FormatTest formatTest = (FormatTest) o; - return Objects.equals(this.integer, formatTest.integer) && - Objects.equals(this.int32, formatTest.int32) && - Objects.equals(this.int64, formatTest.int64) && - Objects.equals(this.number, formatTest.number) && - Objects.equals(this._float, formatTest._float) && - Objects.equals(this._double, formatTest._double) && - Objects.equals(this.decimal, formatTest.decimal) && - Objects.equals(this.string, formatTest.string) && - Arrays.equals(this._byte, formatTest._byte) && - Objects.equals(this.binary, formatTest.binary) && - Objects.equals(this.date, formatTest.date) && - Objects.equals(this.dateTime, formatTest.dateTime) && - Objects.equals(this.uuid, formatTest.uuid) && - Objects.equals(this.password, formatTest.password) && - Objects.equals(this.patternWithDigits, formatTest.patternWithDigits) && - Objects.equals(this.patternWithDigitsAndDelimiter, formatTest.patternWithDigitsAndDelimiter); - } - - @Override - public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, decimal, string, Arrays.hashCode(_byte), binary, date, dateTime, uuid, password, patternWithDigits, patternWithDigitsAndDelimiter); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class FormatTest {\n"); - sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); - sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); - sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); - sb.append(" number: ").append(toIndentedString(number)).append("\n"); - sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); - sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); - sb.append(" decimal: ").append(toIndentedString(decimal)).append("\n"); - sb.append(" string: ").append(toIndentedString(string)).append("\n"); - sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); - sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); - sb.append(" date: ").append(toIndentedString(date)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); - sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Fruit.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Fruit.java deleted file mode 100644 index 548e7ab3c3..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Fruit.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.openapitools.client.model.Apple; -import org.openapitools.client.model.Banana; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import com.fasterxml.jackson.core.type.TypeReference; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using = Fruit.FruitDeserializer.class) -@JsonSerialize(using = Fruit.FruitSerializer.class) -public class Fruit extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(Fruit.class.getName()); - - public static class FruitSerializer extends StdSerializer { - public FruitSerializer(Class t) { - super(t); - } - - public FruitSerializer() { - this(null); - } - - @Override - public void serialize(Fruit value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class FruitDeserializer extends StdDeserializer { - public FruitDeserializer() { - this(Fruit.class); - } - - public FruitDeserializer(Class vc) { - super(vc); - } - - @Override - public Fruit deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - Object deserialized = null; - boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); - int match = 0; - JsonToken token = tree.traverse(jp.getCodec()).nextToken(); - // deserialize Apple - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Apple.class.equals(Integer.class) || Apple.class.equals(Long.class) || Apple.class.equals(Float.class) || Apple.class.equals(Double.class) || Apple.class.equals(Boolean.class) || Apple.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Apple.class.equals(Integer.class) || Apple.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Apple.class.equals(Float.class) || Apple.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Apple.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Apple.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Apple.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Apple'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Apple'", e); - } - - // deserialize Banana - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Banana.class.equals(Integer.class) || Banana.class.equals(Long.class) || Banana.class.equals(Float.class) || Banana.class.equals(Double.class) || Banana.class.equals(Boolean.class) || Banana.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Banana.class.equals(Integer.class) || Banana.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Banana.class.equals(Float.class) || Banana.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Banana.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Banana.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Banana.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Banana'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Banana'", e); - } - - if (match == 1) { - Fruit ret = new Fruit(); - ret.setActualInstance(deserialized); - return ret; - } - throw new IOException(String.format("Failed deserialization for Fruit: %d classes match result, expected 1", match)); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public Fruit getNullValue(DeserializationContext ctxt) throws JsonMappingException { - throw new JsonMappingException(ctxt.getParser(), "Fruit cannot be null"); - } - } - - // store a list of schema names defined in oneOf - public static final Map> schemas = new HashMap<>(); - - public Fruit() { - super("oneOf", Boolean.FALSE); - } - - public Fruit(Apple o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - public Fruit(Banana o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("Apple", Apple.class); - schemas.put("Banana", Banana.class); - JSON.registerDescendants(Fruit.class, Collections.unmodifiableMap(schemas)); - } - - @Override - public Map> getSchemas() { - return Fruit.schemas; - } - - /** - * Set the instance that matches the oneOf child schema, check - * the instance parameter is valid against the oneOf child schemas: - * Apple, Banana - * - * It could be an instance of the 'oneOf' schemas. - * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). - */ - @Override - public void setActualInstance(Object instance) { - if (JSON.isInstanceOf(Apple.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(Banana.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Apple, Banana"); - } - - /** - * Get the actual instance, which can be the following: - * Apple, Banana - * - * @return The actual instance (Apple, Banana) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `Apple`. If the actual instanct is not `Apple`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Apple` - * @throws ClassCastException if the instance is not `Apple` - */ - public Apple getApple() throws ClassCastException { - return (Apple)super.getActualInstance(); - } - - /** - * Get the actual instance of `Banana`. If the actual instanct is not `Banana`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Banana` - * @throws ClassCastException if the instance is not `Banana` - */ - public Banana getBanana() throws ClassCastException { - return (Banana)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FruitReq.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FruitReq.java deleted file mode 100644 index c73123d08d..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FruitReq.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.openapitools.client.model.AppleReq; -import org.openapitools.client.model.BananaReq; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import com.fasterxml.jackson.core.type.TypeReference; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using = FruitReq.FruitReqDeserializer.class) -@JsonSerialize(using = FruitReq.FruitReqSerializer.class) -public class FruitReq extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(FruitReq.class.getName()); - - public static class FruitReqSerializer extends StdSerializer { - public FruitReqSerializer(Class t) { - super(t); - } - - public FruitReqSerializer() { - this(null); - } - - @Override - public void serialize(FruitReq value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class FruitReqDeserializer extends StdDeserializer { - public FruitReqDeserializer() { - this(FruitReq.class); - } - - public FruitReqDeserializer(Class vc) { - super(vc); - } - - @Override - public FruitReq deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - Object deserialized = null; - boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); - int match = 0; - JsonToken token = tree.traverse(jp.getCodec()).nextToken(); - // deserialize AppleReq - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (AppleReq.class.equals(Integer.class) || AppleReq.class.equals(Long.class) || AppleReq.class.equals(Float.class) || AppleReq.class.equals(Double.class) || AppleReq.class.equals(Boolean.class) || AppleReq.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((AppleReq.class.equals(Integer.class) || AppleReq.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((AppleReq.class.equals(Float.class) || AppleReq.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (AppleReq.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (AppleReq.class.equals(String.class) && token == JsonToken.VALUE_STRING); - attemptParsing |= (token == JsonToken.VALUE_NULL); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(AppleReq.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'AppleReq'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'AppleReq'", e); - } - - // deserialize BananaReq - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (BananaReq.class.equals(Integer.class) || BananaReq.class.equals(Long.class) || BananaReq.class.equals(Float.class) || BananaReq.class.equals(Double.class) || BananaReq.class.equals(Boolean.class) || BananaReq.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((BananaReq.class.equals(Integer.class) || BananaReq.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((BananaReq.class.equals(Float.class) || BananaReq.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (BananaReq.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (BananaReq.class.equals(String.class) && token == JsonToken.VALUE_STRING); - attemptParsing |= (token == JsonToken.VALUE_NULL); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(BananaReq.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'BananaReq'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'BananaReq'", e); - } - - if (match == 1) { - FruitReq ret = new FruitReq(); - ret.setActualInstance(deserialized); - return ret; - } - throw new IOException(String.format("Failed deserialization for FruitReq: %d classes match result, expected 1", match)); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public FruitReq getNullValue(DeserializationContext ctxt) throws JsonMappingException { - return null; - } - } - - // store a list of schema names defined in oneOf - public static final Map> schemas = new HashMap<>(); - - public FruitReq() { - super("oneOf", Boolean.TRUE); - } - - public FruitReq(AppleReq o) { - super("oneOf", Boolean.TRUE); - setActualInstance(o); - } - - public FruitReq(BananaReq o) { - super("oneOf", Boolean.TRUE); - setActualInstance(o); - } - - static { - schemas.put("AppleReq", AppleReq.class); - schemas.put("BananaReq", BananaReq.class); - JSON.registerDescendants(FruitReq.class, Collections.unmodifiableMap(schemas)); - } - - @Override - public Map> getSchemas() { - return FruitReq.schemas; - } - - /** - * Set the instance that matches the oneOf child schema, check - * the instance parameter is valid against the oneOf child schemas: - * AppleReq, BananaReq - * - * It could be an instance of the 'oneOf' schemas. - * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). - */ - @Override - public void setActualInstance(Object instance) { - if (instance == null) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(AppleReq.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(BananaReq.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be AppleReq, BananaReq"); - } - - /** - * Get the actual instance, which can be the following: - * AppleReq, BananaReq - * - * @return The actual instance (AppleReq, BananaReq) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `AppleReq`. If the actual instanct is not `AppleReq`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `AppleReq` - * @throws ClassCastException if the instance is not `AppleReq` - */ - public AppleReq getAppleReq() throws ClassCastException { - return (AppleReq)super.getActualInstance(); - } - - /** - * Get the actual instance of `BananaReq`. If the actual instanct is not `BananaReq`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `BananaReq` - * @throws ClassCastException if the instance is not `BananaReq` - */ - public BananaReq getBananaReq() throws ClassCastException { - return (BananaReq)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GmFruit.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GmFruit.java deleted file mode 100644 index c6c672512d..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GmFruit.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.openapitools.client.model.Apple; -import org.openapitools.client.model.Banana; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using=GmFruit.GmFruitDeserializer.class) -@JsonSerialize(using = GmFruit.GmFruitSerializer.class) -public class GmFruit extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(GmFruit.class.getName()); - - public static class GmFruitSerializer extends StdSerializer { - public GmFruitSerializer(Class t) { - super(t); - } - - public GmFruitSerializer() { - this(null); - } - - @Override - public void serialize(GmFruit value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class GmFruitDeserializer extends StdDeserializer { - public GmFruitDeserializer() { - this(GmFruit.class); - } - - public GmFruitDeserializer(Class vc) { - super(vc); - } - - @Override - public GmFruit deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - - Object deserialized = null; - // deserialize Apple - try { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Apple.class); - GmFruit ret = new GmFruit(); - ret.setActualInstance(deserialized); - return ret; - } catch (Exception e) { - // deserialization failed, continue, log to help debugging - log.log(Level.FINER, "Input data does not match 'GmFruit'", e); - } - - // deserialize Banana - try { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Banana.class); - GmFruit ret = new GmFruit(); - ret.setActualInstance(deserialized); - return ret; - } catch (Exception e) { - // deserialization failed, continue, log to help debugging - log.log(Level.FINER, "Input data does not match 'GmFruit'", e); - } - - throw new IOException(String.format("Failed deserialization for GmFruit: no match found")); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public GmFruit getNullValue(DeserializationContext ctxt) throws JsonMappingException { - throw new JsonMappingException(ctxt.getParser(), "GmFruit cannot be null"); - } - } - - // store a list of schema names defined in anyOf - public static final Map> schemas = new HashMap>(); - - public GmFruit() { - super("anyOf", Boolean.FALSE); - } - - public GmFruit(Apple o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - - public GmFruit(Banana o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("Apple", Apple.class); - schemas.put("Banana", Banana.class); - JSON.registerDescendants(GmFruit.class, Collections.unmodifiableMap(schemas)); - } - - @Override - public Map> getSchemas() { - return GmFruit.schemas; - } - - /** - * Set the instance that matches the anyOf child schema, check - * the instance parameter is valid against the anyOf child schemas: - * Apple, Banana - * - * It could be an instance of the 'anyOf' schemas. - * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). - */ - @Override - public void setActualInstance(Object instance) { - if (JSON.isInstanceOf(Apple.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(Banana.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Apple, Banana"); - } - - /** - * Get the actual instance, which can be the following: - * Apple, Banana - * - * @return The actual instance (Apple, Banana) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `Apple`. If the actual instanct is not `Apple`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Apple` - * @throws ClassCastException if the instance is not `Apple` - */ - public Apple getApple() throws ClassCastException { - return (Apple)super.getActualInstance(); - } - - /** - * Get the actual instance of `Banana`. If the actual instanct is not `Banana`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Banana` - * @throws ClassCastException if the instance is not `Banana` - */ - public Banana getBanana() throws ClassCastException { - return (Banana)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GrandparentAnimal.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GrandparentAnimal.java deleted file mode 100644 index 85e70e350a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GrandparentAnimal.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ChildCat; -import org.openapitools.client.model.ParentPet; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import org.openapitools.client.JSON; -/** - * GrandparentAnimal - */ -@JsonPropertyOrder({ - GrandparentAnimal.JSON_PROPERTY_PET_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "pet_type", visible = true) -@JsonSubTypes({ - @JsonSubTypes.Type(value = ChildCat.class, name = "ChildCat"), - @JsonSubTypes.Type(value = ParentPet.class, name = "ParentPet"), -}) - -public class GrandparentAnimal { - public static final String JSON_PROPERTY_PET_TYPE = "pet_type"; - private String petType; - - - public GrandparentAnimal petType(String petType) { - this.petType = petType; - return this; - } - - /** - * Get petType - * @return petType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_PET_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getPetType() { - return petType; - } - - - @JsonProperty(JSON_PROPERTY_PET_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setPetType(String petType) { - this.petType = petType; - } - - - /** - * Return true if this GrandparentAnimal object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - GrandparentAnimal grandparentAnimal = (GrandparentAnimal) o; - return Objects.equals(this.petType, grandparentAnimal.petType); - } - - @Override - public int hashCode() { - return Objects.hash(petType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class GrandparentAnimal {\n"); - sb.append(" petType: ").append(toIndentedString(petType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -static { - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("ChildCat", ChildCat.class); - mappings.put("ParentPet", ParentPet.class); - mappings.put("GrandparentAnimal", GrandparentAnimal.class); - JSON.registerDiscriminator(GrandparentAnimal.class, "pet_type", mappings); -} -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java deleted file mode 100644 index a8573d9708..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * HasOnlyReadOnly - */ -@JsonPropertyOrder({ - HasOnlyReadOnly.JSON_PROPERTY_BAR, - HasOnlyReadOnly.JSON_PROPERTY_FOO -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class HasOnlyReadOnly { - public static final String JSON_PROPERTY_BAR = "bar"; - private String bar; - - public static final String JSON_PROPERTY_FOO = "foo"; - private String foo; - - - /** - * Get bar - * @return bar - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_BAR) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getBar() { - return bar; - } - - - - - /** - * Get foo - * @return foo - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_FOO) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getFoo() { - return foo; - } - - - - - /** - * Return true if this hasOnlyReadOnly object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; - return Objects.equals(this.bar, hasOnlyReadOnly.bar) && - Objects.equals(this.foo, hasOnlyReadOnly.foo); - } - - @Override - public int hashCode() { - return Objects.hash(bar, foo); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class HasOnlyReadOnly {\n"); - sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); - sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/HealthCheckResult.java deleted file mode 100644 index 7d4ccdfc8d..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/HealthCheckResult.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. - */ -@ApiModel(description = "Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model.") -@JsonPropertyOrder({ - HealthCheckResult.JSON_PROPERTY_NULLABLE_MESSAGE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class HealthCheckResult { - public static final String JSON_PROPERTY_NULLABLE_MESSAGE = "NullableMessage"; - private JsonNullable nullableMessage = JsonNullable.undefined(); - - - public HealthCheckResult nullableMessage(String nullableMessage) { - this.nullableMessage = JsonNullable.of(nullableMessage); - return this; - } - - /** - * Get nullableMessage - * @return nullableMessage - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public String getNullableMessage() { - return nullableMessage.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_NULLABLE_MESSAGE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getNullableMessage_JsonNullable() { - return nullableMessage; - } - - @JsonProperty(JSON_PROPERTY_NULLABLE_MESSAGE) - public void setNullableMessage_JsonNullable(JsonNullable nullableMessage) { - this.nullableMessage = nullableMessage; - } - - public void setNullableMessage(String nullableMessage) { - this.nullableMessage = JsonNullable.of(nullableMessage); - } - - - /** - * Return true if this HealthCheckResult object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - HealthCheckResult healthCheckResult = (HealthCheckResult) o; - return Objects.equals(this.nullableMessage, healthCheckResult.nullableMessage); - } - - @Override - public int hashCode() { - return Objects.hash(nullableMessage); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class HealthCheckResult {\n"); - sb.append(" nullableMessage: ").append(toIndentedString(nullableMessage)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject.java deleted file mode 100644 index 96733af0b2..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.openapitools.client.JSON; - - -/** - * InlineObject - */ -@JsonPropertyOrder({ - InlineObject.JSON_PROPERTY_NAME, - InlineObject.JSON_PROPERTY_STATUS -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class InlineObject { - public static final String JSON_PROPERTY_NAME = "name"; - private String name; - - public static final String JSON_PROPERTY_STATUS = "status"; - private String status; - - - public InlineObject name(String name) { - this.name = name; - return this; - } - - /** - * Updated name of the pet - * @return name - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "Updated name of the pet") - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - - - public InlineObject status(String status) { - this.status = status; - return this; - } - - /** - * Updated status of the pet - * @return status - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "Updated status of the pet") - @JsonProperty(JSON_PROPERTY_STATUS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getStatus() { - return status; - } - - - public void setStatus(String status) { - this.status = status; - } - - - /** - * Return true if this inline_object object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - InlineObject inlineObject = (InlineObject) o; - return Objects.equals(this.name, inlineObject.name) && - Objects.equals(this.status, inlineObject.status); - } - - @Override - public int hashCode() { - return Objects.hash(name, status); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class InlineObject {\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject1.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject1.java deleted file mode 100644 index 98828b675d..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject1.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.io.File; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.openapitools.client.JSON; - - -/** - * InlineObject1 - */ -@JsonPropertyOrder({ - InlineObject1.JSON_PROPERTY_ADDITIONAL_METADATA, - InlineObject1.JSON_PROPERTY_FILE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class InlineObject1 { - public static final String JSON_PROPERTY_ADDITIONAL_METADATA = "additionalMetadata"; - private String additionalMetadata; - - public static final String JSON_PROPERTY_FILE = "file"; - private File file; - - - public InlineObject1 additionalMetadata(String additionalMetadata) { - this.additionalMetadata = additionalMetadata; - return this; - } - - /** - * Additional data to pass to server - * @return additionalMetadata - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "Additional data to pass to server") - @JsonProperty(JSON_PROPERTY_ADDITIONAL_METADATA) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getAdditionalMetadata() { - return additionalMetadata; - } - - - public void setAdditionalMetadata(String additionalMetadata) { - this.additionalMetadata = additionalMetadata; - } - - - public InlineObject1 file(File file) { - this.file = file; - return this; - } - - /** - * file to upload - * @return file - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "file to upload") - @JsonProperty(JSON_PROPERTY_FILE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public File getFile() { - return file; - } - - - public void setFile(File file) { - this.file = file; - } - - - /** - * Return true if this inline_object_1 object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - InlineObject1 inlineObject1 = (InlineObject1) o; - return Objects.equals(this.additionalMetadata, inlineObject1.additionalMetadata) && - Objects.equals(this.file, inlineObject1.file); - } - - @Override - public int hashCode() { - return Objects.hash(additionalMetadata, file); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class InlineObject1 {\n"); - sb.append(" additionalMetadata: ").append(toIndentedString(additionalMetadata)).append("\n"); - sb.append(" file: ").append(toIndentedString(file)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject2.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject2.java deleted file mode 100644 index 0d18883bf4..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject2.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.openapitools.client.JSON; - - -/** - * InlineObject2 - */ -@JsonPropertyOrder({ - InlineObject2.JSON_PROPERTY_ENUM_FORM_STRING_ARRAY, - InlineObject2.JSON_PROPERTY_ENUM_FORM_STRING -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class InlineObject2 { - /** - * Gets or Sets enumFormStringArray - */ - public enum EnumFormStringArrayEnum { - GREATER_THAN(">"), - - DOLLAR("$"); - - private String value; - - EnumFormStringArrayEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumFormStringArrayEnum fromValue(String value) { - for (EnumFormStringArrayEnum b : EnumFormStringArrayEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_ENUM_FORM_STRING_ARRAY = "enum_form_string_array"; - private List enumFormStringArray = null; - - /** - * Form parameter enum test (string) - */ - public enum EnumFormStringEnum { - _ABC("_abc"), - - _EFG("-efg"), - - _XYZ_("(xyz)"); - - private String value; - - EnumFormStringEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumFormStringEnum fromValue(String value) { - for (EnumFormStringEnum b : EnumFormStringEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_ENUM_FORM_STRING = "enum_form_string"; - private EnumFormStringEnum enumFormString = EnumFormStringEnum._EFG; - - - public InlineObject2 enumFormStringArray(List enumFormStringArray) { - this.enumFormStringArray = enumFormStringArray; - return this; - } - - public InlineObject2 addEnumFormStringArrayItem(EnumFormStringArrayEnum enumFormStringArrayItem) { - if (this.enumFormStringArray == null) { - this.enumFormStringArray = new ArrayList<>(); - } - this.enumFormStringArray.add(enumFormStringArrayItem); - return this; - } - - /** - * Form parameter enum test (string array) - * @return enumFormStringArray - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "Form parameter enum test (string array)") - @JsonProperty(JSON_PROPERTY_ENUM_FORM_STRING_ARRAY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List getEnumFormStringArray() { - return enumFormStringArray; - } - - - public void setEnumFormStringArray(List enumFormStringArray) { - this.enumFormStringArray = enumFormStringArray; - } - - - public InlineObject2 enumFormString(EnumFormStringEnum enumFormString) { - this.enumFormString = enumFormString; - return this; - } - - /** - * Form parameter enum test (string) - * @return enumFormString - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "Form parameter enum test (string)") - @JsonProperty(JSON_PROPERTY_ENUM_FORM_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public EnumFormStringEnum getEnumFormString() { - return enumFormString; - } - - - public void setEnumFormString(EnumFormStringEnum enumFormString) { - this.enumFormString = enumFormString; - } - - - /** - * Return true if this inline_object_2 object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - InlineObject2 inlineObject2 = (InlineObject2) o; - return Objects.equals(this.enumFormStringArray, inlineObject2.enumFormStringArray) && - Objects.equals(this.enumFormString, inlineObject2.enumFormString); - } - - @Override - public int hashCode() { - return Objects.hash(enumFormStringArray, enumFormString); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class InlineObject2 {\n"); - sb.append(" enumFormStringArray: ").append(toIndentedString(enumFormStringArray)).append("\n"); - sb.append(" enumFormString: ").append(toIndentedString(enumFormString)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject3.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject3.java deleted file mode 100644 index fd4eba10cf..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject3.java +++ /dev/null @@ -1,507 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.io.File; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.openapitools.client.JSON; - - -/** - * InlineObject3 - */ -@JsonPropertyOrder({ - InlineObject3.JSON_PROPERTY_INTEGER, - InlineObject3.JSON_PROPERTY_INT32, - InlineObject3.JSON_PROPERTY_INT64, - InlineObject3.JSON_PROPERTY_NUMBER, - InlineObject3.JSON_PROPERTY_FLOAT, - InlineObject3.JSON_PROPERTY_DOUBLE, - InlineObject3.JSON_PROPERTY_STRING, - InlineObject3.JSON_PROPERTY_PATTERN_WITHOUT_DELIMITER, - InlineObject3.JSON_PROPERTY_BYTE, - InlineObject3.JSON_PROPERTY_BINARY, - InlineObject3.JSON_PROPERTY_DATE, - InlineObject3.JSON_PROPERTY_DATE_TIME, - InlineObject3.JSON_PROPERTY_PASSWORD, - InlineObject3.JSON_PROPERTY_CALLBACK -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class InlineObject3 { - public static final String JSON_PROPERTY_INTEGER = "integer"; - private Integer integer; - - public static final String JSON_PROPERTY_INT32 = "int32"; - private Integer int32; - - public static final String JSON_PROPERTY_INT64 = "int64"; - private Long int64; - - public static final String JSON_PROPERTY_NUMBER = "number"; - private BigDecimal number; - - public static final String JSON_PROPERTY_FLOAT = "float"; - private Float _float; - - public static final String JSON_PROPERTY_DOUBLE = "double"; - private Double _double; - - public static final String JSON_PROPERTY_STRING = "string"; - private String string; - - public static final String JSON_PROPERTY_PATTERN_WITHOUT_DELIMITER = "pattern_without_delimiter"; - private String patternWithoutDelimiter; - - public static final String JSON_PROPERTY_BYTE = "byte"; - private byte[] _byte; - - public static final String JSON_PROPERTY_BINARY = "binary"; - private File binary; - - public static final String JSON_PROPERTY_DATE = "date"; - private LocalDate date; - - public static final String JSON_PROPERTY_DATE_TIME = "dateTime"; - private OffsetDateTime dateTime = OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault())); - - public static final String JSON_PROPERTY_PASSWORD = "password"; - private String password; - - public static final String JSON_PROPERTY_CALLBACK = "callback"; - private String callback; - - - public InlineObject3 integer(Integer integer) { - this.integer = integer; - return this; - } - - /** - * None - * minimum: 10 - * maximum: 100 - * @return integer - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "None") - @JsonProperty(JSON_PROPERTY_INTEGER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getInteger() { - return integer; - } - - - public void setInteger(Integer integer) { - this.integer = integer; - } - - - public InlineObject3 int32(Integer int32) { - this.int32 = int32; - return this; - } - - /** - * None - * minimum: 20 - * maximum: 200 - * @return int32 - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "None") - @JsonProperty(JSON_PROPERTY_INT32) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getInt32() { - return int32; - } - - - public void setInt32(Integer int32) { - this.int32 = int32; - } - - - public InlineObject3 int64(Long int64) { - this.int64 = int64; - return this; - } - - /** - * None - * @return int64 - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "None") - @JsonProperty(JSON_PROPERTY_INT64) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Long getInt64() { - return int64; - } - - - public void setInt64(Long int64) { - this.int64 = int64; - } - - - public InlineObject3 number(BigDecimal number) { - this.number = number; - return this; - } - - /** - * None - * minimum: 32.1 - * maximum: 543.2 - * @return number - **/ - @ApiModelProperty(required = true, value = "None") - @JsonProperty(JSON_PROPERTY_NUMBER) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public BigDecimal getNumber() { - return number; - } - - - public void setNumber(BigDecimal number) { - this.number = number; - } - - - public InlineObject3 _float(Float _float) { - this._float = _float; - return this; - } - - /** - * None - * maximum: 987.6 - * @return _float - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "None") - @JsonProperty(JSON_PROPERTY_FLOAT) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Float getFloat() { - return _float; - } - - - public void setFloat(Float _float) { - this._float = _float; - } - - - public InlineObject3 _double(Double _double) { - this._double = _double; - return this; - } - - /** - * None - * minimum: 67.8 - * maximum: 123.4 - * @return _double - **/ - @ApiModelProperty(required = true, value = "None") - @JsonProperty(JSON_PROPERTY_DOUBLE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public Double getDouble() { - return _double; - } - - - public void setDouble(Double _double) { - this._double = _double; - } - - - public InlineObject3 string(String string) { - this.string = string; - return this; - } - - /** - * None - * @return string - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "None") - @JsonProperty(JSON_PROPERTY_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getString() { - return string; - } - - - public void setString(String string) { - this.string = string; - } - - - public InlineObject3 patternWithoutDelimiter(String patternWithoutDelimiter) { - this.patternWithoutDelimiter = patternWithoutDelimiter; - return this; - } - - /** - * None - * @return patternWithoutDelimiter - **/ - @ApiModelProperty(required = true, value = "None") - @JsonProperty(JSON_PROPERTY_PATTERN_WITHOUT_DELIMITER) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getPatternWithoutDelimiter() { - return patternWithoutDelimiter; - } - - - public void setPatternWithoutDelimiter(String patternWithoutDelimiter) { - this.patternWithoutDelimiter = patternWithoutDelimiter; - } - - - public InlineObject3 _byte(byte[] _byte) { - this._byte = _byte; - return this; - } - - /** - * None - * @return _byte - **/ - @ApiModelProperty(required = true, value = "None") - @JsonProperty(JSON_PROPERTY_BYTE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public byte[] getByte() { - return _byte; - } - - - public void setByte(byte[] _byte) { - this._byte = _byte; - } - - - public InlineObject3 binary(File binary) { - this.binary = binary; - return this; - } - - /** - * None - * @return binary - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "None") - @JsonProperty(JSON_PROPERTY_BINARY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public File getBinary() { - return binary; - } - - - public void setBinary(File binary) { - this.binary = binary; - } - - - public InlineObject3 date(LocalDate date) { - this.date = date; - return this; - } - - /** - * None - * @return date - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "None") - @JsonProperty(JSON_PROPERTY_DATE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public LocalDate getDate() { - return date; - } - - - public void setDate(LocalDate date) { - this.date = date; - } - - - public InlineObject3 dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; - return this; - } - - /** - * None - * @return dateTime - **/ - @javax.annotation.Nullable - @ApiModelProperty(example = "2020-02-02T20:20:20.222220Z", value = "None") - @JsonProperty(JSON_PROPERTY_DATE_TIME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public OffsetDateTime getDateTime() { - return dateTime; - } - - - public void setDateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; - } - - - public InlineObject3 password(String password) { - this.password = password; - return this; - } - - /** - * None - * @return password - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "None") - @JsonProperty(JSON_PROPERTY_PASSWORD) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getPassword() { - return password; - } - - - public void setPassword(String password) { - this.password = password; - } - - - public InlineObject3 callback(String callback) { - this.callback = callback; - return this; - } - - /** - * None - * @return callback - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "None") - @JsonProperty(JSON_PROPERTY_CALLBACK) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getCallback() { - return callback; - } - - - public void setCallback(String callback) { - this.callback = callback; - } - - - /** - * Return true if this inline_object_3 object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - InlineObject3 inlineObject3 = (InlineObject3) o; - return Objects.equals(this.integer, inlineObject3.integer) && - Objects.equals(this.int32, inlineObject3.int32) && - Objects.equals(this.int64, inlineObject3.int64) && - Objects.equals(this.number, inlineObject3.number) && - Objects.equals(this._float, inlineObject3._float) && - Objects.equals(this._double, inlineObject3._double) && - Objects.equals(this.string, inlineObject3.string) && - Objects.equals(this.patternWithoutDelimiter, inlineObject3.patternWithoutDelimiter) && - Arrays.equals(this._byte, inlineObject3._byte) && - Objects.equals(this.binary, inlineObject3.binary) && - Objects.equals(this.date, inlineObject3.date) && - Objects.equals(this.dateTime, inlineObject3.dateTime) && - Objects.equals(this.password, inlineObject3.password) && - Objects.equals(this.callback, inlineObject3.callback); - } - - @Override - public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, patternWithoutDelimiter, Arrays.hashCode(_byte), binary, date, dateTime, password, callback); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class InlineObject3 {\n"); - sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); - sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); - sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); - sb.append(" number: ").append(toIndentedString(number)).append("\n"); - sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); - sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); - sb.append(" string: ").append(toIndentedString(string)).append("\n"); - sb.append(" patternWithoutDelimiter: ").append(toIndentedString(patternWithoutDelimiter)).append("\n"); - sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); - sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); - sb.append(" date: ").append(toIndentedString(date)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append(" callback: ").append(toIndentedString(callback)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject4.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject4.java deleted file mode 100644 index f920fb0734..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject4.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.openapitools.client.JSON; - - -/** - * InlineObject4 - */ -@JsonPropertyOrder({ - InlineObject4.JSON_PROPERTY_PARAM, - InlineObject4.JSON_PROPERTY_PARAM2 -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class InlineObject4 { - public static final String JSON_PROPERTY_PARAM = "param"; - private String param; - - public static final String JSON_PROPERTY_PARAM2 = "param2"; - private String param2; - - - public InlineObject4 param(String param) { - this.param = param; - return this; - } - - /** - * field1 - * @return param - **/ - @ApiModelProperty(required = true, value = "field1") - @JsonProperty(JSON_PROPERTY_PARAM) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getParam() { - return param; - } - - - public void setParam(String param) { - this.param = param; - } - - - public InlineObject4 param2(String param2) { - this.param2 = param2; - return this; - } - - /** - * field2 - * @return param2 - **/ - @ApiModelProperty(required = true, value = "field2") - @JsonProperty(JSON_PROPERTY_PARAM2) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getParam2() { - return param2; - } - - - public void setParam2(String param2) { - this.param2 = param2; - } - - - /** - * Return true if this inline_object_4 object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - InlineObject4 inlineObject4 = (InlineObject4) o; - return Objects.equals(this.param, inlineObject4.param) && - Objects.equals(this.param2, inlineObject4.param2); - } - - @Override - public int hashCode() { - return Objects.hash(param, param2); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class InlineObject4 {\n"); - sb.append(" param: ").append(toIndentedString(param)).append("\n"); - sb.append(" param2: ").append(toIndentedString(param2)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject5.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject5.java deleted file mode 100644 index d941f0d5b7..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineObject5.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.io.File; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.openapitools.client.JSON; - - -/** - * InlineObject5 - */ -@JsonPropertyOrder({ - InlineObject5.JSON_PROPERTY_ADDITIONAL_METADATA, - InlineObject5.JSON_PROPERTY_REQUIRED_FILE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class InlineObject5 { - public static final String JSON_PROPERTY_ADDITIONAL_METADATA = "additionalMetadata"; - private String additionalMetadata; - - public static final String JSON_PROPERTY_REQUIRED_FILE = "requiredFile"; - private File requiredFile; - - - public InlineObject5 additionalMetadata(String additionalMetadata) { - this.additionalMetadata = additionalMetadata; - return this; - } - - /** - * Additional data to pass to server - * @return additionalMetadata - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "Additional data to pass to server") - @JsonProperty(JSON_PROPERTY_ADDITIONAL_METADATA) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getAdditionalMetadata() { - return additionalMetadata; - } - - - public void setAdditionalMetadata(String additionalMetadata) { - this.additionalMetadata = additionalMetadata; - } - - - public InlineObject5 requiredFile(File requiredFile) { - this.requiredFile = requiredFile; - return this; - } - - /** - * file to upload - * @return requiredFile - **/ - @ApiModelProperty(required = true, value = "file to upload") - @JsonProperty(JSON_PROPERTY_REQUIRED_FILE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public File getRequiredFile() { - return requiredFile; - } - - - public void setRequiredFile(File requiredFile) { - this.requiredFile = requiredFile; - } - - - /** - * Return true if this inline_object_5 object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - InlineObject5 inlineObject5 = (InlineObject5) o; - return Objects.equals(this.additionalMetadata, inlineObject5.additionalMetadata) && - Objects.equals(this.requiredFile, inlineObject5.requiredFile); - } - - @Override - public int hashCode() { - return Objects.hash(additionalMetadata, requiredFile); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class InlineObject5 {\n"); - sb.append(" additionalMetadata: ").append(toIndentedString(additionalMetadata)).append("\n"); - sb.append(" requiredFile: ").append(toIndentedString(requiredFile)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineResponseDefault.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineResponseDefault.java deleted file mode 100644 index b8bdb14abc..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/InlineResponseDefault.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Foo; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * InlineResponseDefault - */ -@JsonPropertyOrder({ - InlineResponseDefault.JSON_PROPERTY_STRING -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class InlineResponseDefault { - public static final String JSON_PROPERTY_STRING = "string"; - private Foo string; - - - public InlineResponseDefault string(Foo string) { - this.string = string; - return this; - } - - /** - * Get string - * @return string - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Foo getString() { - return string; - } - - - @JsonProperty(JSON_PROPERTY_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setString(Foo string) { - this.string = string; - } - - - /** - * Return true if this inline_response_default object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - InlineResponseDefault inlineResponseDefault = (InlineResponseDefault) o; - return Objects.equals(this.string, inlineResponseDefault.string); - } - - @Override - public int hashCode() { - return Objects.hash(string); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class InlineResponseDefault {\n"); - sb.append(" string: ").append(toIndentedString(string)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java deleted file mode 100644 index 5d15dcb553..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ShapeInterface; -import org.openapitools.client.model.TriangleInterface; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * IsoscelesTriangle - */ -@JsonPropertyOrder({ - IsoscelesTriangle.JSON_PROPERTY_SHAPE_TYPE, - IsoscelesTriangle.JSON_PROPERTY_TRIANGLE_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class IsoscelesTriangle { - public static final String JSON_PROPERTY_SHAPE_TYPE = "shapeType"; - private String shapeType; - - public static final String JSON_PROPERTY_TRIANGLE_TYPE = "triangleType"; - private String triangleType; - - - public IsoscelesTriangle shapeType(String shapeType) { - this.shapeType = shapeType; - return this; - } - - /** - * Get shapeType - * @return shapeType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getShapeType() { - return shapeType; - } - - - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setShapeType(String shapeType) { - this.shapeType = shapeType; - } - - - public IsoscelesTriangle triangleType(String triangleType) { - this.triangleType = triangleType; - return this; - } - - /** - * Get triangleType - * @return triangleType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_TRIANGLE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getTriangleType() { - return triangleType; - } - - - @JsonProperty(JSON_PROPERTY_TRIANGLE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setTriangleType(String triangleType) { - this.triangleType = triangleType; - } - - - /** - * Return true if this IsoscelesTriangle object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - IsoscelesTriangle isoscelesTriangle = (IsoscelesTriangle) o; - return Objects.equals(this.shapeType, isoscelesTriangle.shapeType) && - Objects.equals(this.triangleType, isoscelesTriangle.triangleType); - } - - @Override - public int hashCode() { - return Objects.hash(shapeType, triangleType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class IsoscelesTriangle {\n"); - sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); - sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Mammal.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Mammal.java deleted file mode 100644 index 9d1e871feb..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Mammal.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Pig; -import org.openapitools.client.model.Whale; -import org.openapitools.client.model.Zebra; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import com.fasterxml.jackson.core.type.TypeReference; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using = Mammal.MammalDeserializer.class) -@JsonSerialize(using = Mammal.MammalSerializer.class) -public class Mammal extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(Mammal.class.getName()); - - public static class MammalSerializer extends StdSerializer { - public MammalSerializer(Class t) { - super(t); - } - - public MammalSerializer() { - this(null); - } - - @Override - public void serialize(Mammal value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class MammalDeserializer extends StdDeserializer { - public MammalDeserializer() { - this(Mammal.class); - } - - public MammalDeserializer(Class vc) { - super(vc); - } - - @Override - public Mammal deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - Object deserialized = null; - Mammal newMammal = new Mammal(); - Map result2 = tree.traverse(jp.getCodec()).readValueAs(new TypeReference>() {}); - String discriminatorValue = (String)result2.get("className"); - switch (discriminatorValue) { - case "Pig": - deserialized = tree.traverse(jp.getCodec()).readValueAs(Pig.class); - newMammal.setActualInstance(deserialized); - return newMammal; - case "whale": - deserialized = tree.traverse(jp.getCodec()).readValueAs(Whale.class); - newMammal.setActualInstance(deserialized); - return newMammal; - case "zebra": - deserialized = tree.traverse(jp.getCodec()).readValueAs(Zebra.class); - newMammal.setActualInstance(deserialized); - return newMammal; - default: - log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); - } - - boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); - int match = 0; - JsonToken token = tree.traverse(jp.getCodec()).nextToken(); - // deserialize Pig - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Pig.class.equals(Integer.class) || Pig.class.equals(Long.class) || Pig.class.equals(Float.class) || Pig.class.equals(Double.class) || Pig.class.equals(Boolean.class) || Pig.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Pig.class.equals(Integer.class) || Pig.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Pig.class.equals(Float.class) || Pig.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Pig.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Pig.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Pig.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Pig'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Pig'", e); - } - - // deserialize Whale - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Whale.class.equals(Integer.class) || Whale.class.equals(Long.class) || Whale.class.equals(Float.class) || Whale.class.equals(Double.class) || Whale.class.equals(Boolean.class) || Whale.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Whale.class.equals(Integer.class) || Whale.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Whale.class.equals(Float.class) || Whale.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Whale.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Whale.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Whale.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Whale'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Whale'", e); - } - - // deserialize Zebra - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Zebra.class.equals(Integer.class) || Zebra.class.equals(Long.class) || Zebra.class.equals(Float.class) || Zebra.class.equals(Double.class) || Zebra.class.equals(Boolean.class) || Zebra.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Zebra.class.equals(Integer.class) || Zebra.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Zebra.class.equals(Float.class) || Zebra.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Zebra.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Zebra.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Zebra.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Zebra'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Zebra'", e); - } - - if (match == 1) { - Mammal ret = new Mammal(); - ret.setActualInstance(deserialized); - return ret; - } - throw new IOException(String.format("Failed deserialization for Mammal: %d classes match result, expected 1", match)); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public Mammal getNullValue(DeserializationContext ctxt) throws JsonMappingException { - throw new JsonMappingException(ctxt.getParser(), "Mammal cannot be null"); - } - } - - // store a list of schema names defined in oneOf - public static final Map> schemas = new HashMap<>(); - - public Mammal() { - super("oneOf", Boolean.FALSE); - } - - public Mammal(Pig o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - public Mammal(Whale o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - public Mammal(Zebra o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("Pig", Pig.class); - schemas.put("Whale", Whale.class); - schemas.put("Zebra", Zebra.class); - JSON.registerDescendants(Mammal.class, Collections.unmodifiableMap(schemas)); - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("Pig", Pig.class); - mappings.put("whale", Whale.class); - mappings.put("zebra", Zebra.class); - mappings.put("mammal", Mammal.class); - JSON.registerDiscriminator(Mammal.class, "className", mappings); - } - - @Override - public Map> getSchemas() { - return Mammal.schemas; - } - - /** - * Set the instance that matches the oneOf child schema, check - * the instance parameter is valid against the oneOf child schemas: - * Pig, Whale, Zebra - * - * It could be an instance of the 'oneOf' schemas. - * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). - */ - @Override - public void setActualInstance(Object instance) { - if (JSON.isInstanceOf(Pig.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(Whale.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(Zebra.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Pig, Whale, Zebra"); - } - - /** - * Get the actual instance, which can be the following: - * Pig, Whale, Zebra - * - * @return The actual instance (Pig, Whale, Zebra) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `Pig`. If the actual instanct is not `Pig`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Pig` - * @throws ClassCastException if the instance is not `Pig` - */ - public Pig getPig() throws ClassCastException { - return (Pig)super.getActualInstance(); - } - - /** - * Get the actual instance of `Whale`. If the actual instanct is not `Whale`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Whale` - * @throws ClassCastException if the instance is not `Whale` - */ - public Whale getWhale() throws ClassCastException { - return (Whale)super.getActualInstance(); - } - - /** - * Get the actual instance of `Zebra`. If the actual instanct is not `Zebra`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Zebra` - * @throws ClassCastException if the instance is not `Zebra` - */ - public Zebra getZebra() throws ClassCastException { - return (Zebra)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/MapTest.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/MapTest.java deleted file mode 100644 index 10f46d27b3..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/MapTest.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * MapTest - */ -@JsonPropertyOrder({ - MapTest.JSON_PROPERTY_MAP_MAP_OF_STRING, - MapTest.JSON_PROPERTY_MAP_OF_ENUM_STRING, - MapTest.JSON_PROPERTY_DIRECT_MAP, - MapTest.JSON_PROPERTY_INDIRECT_MAP -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class MapTest { - public static final String JSON_PROPERTY_MAP_MAP_OF_STRING = "map_map_of_string"; - private Map> mapMapOfString = null; - - /** - * Gets or Sets inner - */ - public enum InnerEnum { - UPPER("UPPER"), - - LOWER("lower"); - - private String value; - - InnerEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static InnerEnum fromValue(String value) { - for (InnerEnum b : InnerEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_MAP_OF_ENUM_STRING = "map_of_enum_string"; - private Map mapOfEnumString = null; - - public static final String JSON_PROPERTY_DIRECT_MAP = "direct_map"; - private Map directMap = null; - - public static final String JSON_PROPERTY_INDIRECT_MAP = "indirect_map"; - private Map indirectMap = null; - - - public MapTest mapMapOfString(Map> mapMapOfString) { - this.mapMapOfString = mapMapOfString; - return this; - } - - public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { - if (this.mapMapOfString == null) { - this.mapMapOfString = new HashMap<>(); - } - this.mapMapOfString.put(key, mapMapOfStringItem); - return this; - } - - /** - * Get mapMapOfString - * @return mapMapOfString - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAP_MAP_OF_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Map> getMapMapOfString() { - return mapMapOfString; - } - - - @JsonProperty(JSON_PROPERTY_MAP_MAP_OF_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMapMapOfString(Map> mapMapOfString) { - this.mapMapOfString = mapMapOfString; - } - - - public MapTest mapOfEnumString(Map mapOfEnumString) { - this.mapOfEnumString = mapOfEnumString; - return this; - } - - public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { - if (this.mapOfEnumString == null) { - this.mapOfEnumString = new HashMap<>(); - } - this.mapOfEnumString.put(key, mapOfEnumStringItem); - return this; - } - - /** - * Get mapOfEnumString - * @return mapOfEnumString - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAP_OF_ENUM_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Map getMapOfEnumString() { - return mapOfEnumString; - } - - - @JsonProperty(JSON_PROPERTY_MAP_OF_ENUM_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMapOfEnumString(Map mapOfEnumString) { - this.mapOfEnumString = mapOfEnumString; - } - - - public MapTest directMap(Map directMap) { - this.directMap = directMap; - return this; - } - - public MapTest putDirectMapItem(String key, Boolean directMapItem) { - if (this.directMap == null) { - this.directMap = new HashMap<>(); - } - this.directMap.put(key, directMapItem); - return this; - } - - /** - * Get directMap - * @return directMap - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_DIRECT_MAP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Map getDirectMap() { - return directMap; - } - - - @JsonProperty(JSON_PROPERTY_DIRECT_MAP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setDirectMap(Map directMap) { - this.directMap = directMap; - } - - - public MapTest indirectMap(Map indirectMap) { - this.indirectMap = indirectMap; - return this; - } - - public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { - if (this.indirectMap == null) { - this.indirectMap = new HashMap<>(); - } - this.indirectMap.put(key, indirectMapItem); - return this; - } - - /** - * Get indirectMap - * @return indirectMap - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_INDIRECT_MAP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Map getIndirectMap() { - return indirectMap; - } - - - @JsonProperty(JSON_PROPERTY_INDIRECT_MAP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setIndirectMap(Map indirectMap) { - this.indirectMap = indirectMap; - } - - - /** - * Return true if this MapTest object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MapTest mapTest = (MapTest) o; - return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && - Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && - Objects.equals(this.directMap, mapTest.directMap) && - Objects.equals(this.indirectMap, mapTest.indirectMap); - } - - @Override - public int hashCode() { - return Objects.hash(mapMapOfString, mapOfEnumString, directMap, indirectMap); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MapTest {\n"); - sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); - sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); - sb.append(" directMap: ").append(toIndentedString(directMap)).append("\n"); - sb.append(" indirectMap: ").append(toIndentedString(indirectMap)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java deleted file mode 100644 index da802dcc32..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.time.OffsetDateTime; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import org.openapitools.client.model.Animal; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * MixedPropertiesAndAdditionalPropertiesClass - */ -@JsonPropertyOrder({ - MixedPropertiesAndAdditionalPropertiesClass.JSON_PROPERTY_UUID, - MixedPropertiesAndAdditionalPropertiesClass.JSON_PROPERTY_DATE_TIME, - MixedPropertiesAndAdditionalPropertiesClass.JSON_PROPERTY_MAP -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class MixedPropertiesAndAdditionalPropertiesClass { - public static final String JSON_PROPERTY_UUID = "uuid"; - private UUID uuid; - - public static final String JSON_PROPERTY_DATE_TIME = "dateTime"; - private OffsetDateTime dateTime; - - public static final String JSON_PROPERTY_MAP = "map"; - private Map map = null; - - - public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { - this.uuid = uuid; - return this; - } - - /** - * Get uuid - * @return uuid - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_UUID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public UUID getUuid() { - return uuid; - } - - - @JsonProperty(JSON_PROPERTY_UUID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setUuid(UUID uuid) { - this.uuid = uuid; - } - - - public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; - return this; - } - - /** - * Get dateTime - * @return dateTime - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_DATE_TIME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public OffsetDateTime getDateTime() { - return dateTime; - } - - - @JsonProperty(JSON_PROPERTY_DATE_TIME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setDateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; - } - - - public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { - this.map = map; - return this; - } - - public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { - if (this.map == null) { - this.map = new HashMap<>(); - } - this.map.put(key, mapItem); - return this; - } - - /** - * Get map - * @return map - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MAP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Map getMap() { - return map; - } - - - @JsonProperty(JSON_PROPERTY_MAP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMap(Map map) { - this.map = map; - } - - - /** - * Return true if this MixedPropertiesAndAdditionalPropertiesClass object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); - } - - @Override - public int hashCode() { - return Objects.hash(uuid, dateTime, map); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" map: ").append(toIndentedString(map)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Model200Response.java deleted file mode 100644 index 95ce97e156..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Model200Response.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Model for testing model name starting with number - */ -@ApiModel(description = "Model for testing model name starting with number") -@JsonPropertyOrder({ - Model200Response.JSON_PROPERTY_NAME, - Model200Response.JSON_PROPERTY_PROPERTY_CLASS -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Model200Response { - public static final String JSON_PROPERTY_NAME = "name"; - private Integer name; - - public static final String JSON_PROPERTY_PROPERTY_CLASS = "class"; - private String propertyClass; - - - public Model200Response name(Integer name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getName() { - return name; - } - - - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setName(Integer name) { - this.name = name; - } - - - public Model200Response propertyClass(String propertyClass) { - this.propertyClass = propertyClass; - return this; - } - - /** - * Get propertyClass - * @return propertyClass - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_PROPERTY_CLASS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getPropertyClass() { - return propertyClass; - } - - - @JsonProperty(JSON_PROPERTY_PROPERTY_CLASS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setPropertyClass(String propertyClass) { - this.propertyClass = propertyClass; - } - - - /** - * Return true if this 200_response object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Model200Response _200response = (Model200Response) o; - return Objects.equals(this.name, _200response.name) && - Objects.equals(this.propertyClass, _200response.propertyClass); - } - - @Override - public int hashCode() { - return Objects.hash(name, propertyClass); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Model200Response {\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ModelApiResponse.java deleted file mode 100644 index 5def3f4a8d..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ModelApiResponse - */ -@JsonPropertyOrder({ - ModelApiResponse.JSON_PROPERTY_CODE, - ModelApiResponse.JSON_PROPERTY_TYPE, - ModelApiResponse.JSON_PROPERTY_MESSAGE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ModelApiResponse { - public static final String JSON_PROPERTY_CODE = "code"; - private Integer code; - - public static final String JSON_PROPERTY_TYPE = "type"; - private String type; - - public static final String JSON_PROPERTY_MESSAGE = "message"; - private String message; - - - public ModelApiResponse code(Integer code) { - this.code = code; - return this; - } - - /** - * Get code - * @return code - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_CODE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getCode() { - return code; - } - - - @JsonProperty(JSON_PROPERTY_CODE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setCode(Integer code) { - this.code = code; - } - - - public ModelApiResponse type(String type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_TYPE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getType() { - return type; - } - - - @JsonProperty(JSON_PROPERTY_TYPE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setType(String type) { - this.type = type; - } - - - public ModelApiResponse message(String message) { - this.message = message; - return this; - } - - /** - * Get message - * @return message - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MESSAGE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getMessage() { - return message; - } - - - @JsonProperty(JSON_PROPERTY_MESSAGE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMessage(String message) { - this.message = message; - } - - - /** - * Return true if this ApiResponse object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(this.code, _apiResponse.code) && - Objects.equals(this.type, _apiResponse.type) && - Objects.equals(this.message, _apiResponse.message); - } - - @Override - public int hashCode() { - return Objects.hash(code, type, message); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelApiResponse {\n"); - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" message: ").append(toIndentedString(message)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ModelReturn.java deleted file mode 100644 index 9640108d1b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ModelReturn.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Model for testing reserved words - */ -@ApiModel(description = "Model for testing reserved words") -@JsonPropertyOrder({ - ModelReturn.JSON_PROPERTY_RETURN -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ModelReturn { - public static final String JSON_PROPERTY_RETURN = "return"; - private Integer _return; - - - public ModelReturn _return(Integer _return) { - this._return = _return; - return this; - } - - /** - * Get _return - * @return _return - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_RETURN) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getReturn() { - return _return; - } - - - @JsonProperty(JSON_PROPERTY_RETURN) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setReturn(Integer _return) { - this._return = _return; - } - - - /** - * Return true if this Return object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ModelReturn _return = (ModelReturn) o; - return Objects.equals(this._return, _return._return); - } - - @Override - public int hashCode() { - return Objects.hash(_return); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelReturn {\n"); - sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Name.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Name.java deleted file mode 100644 index fd3b90dddf..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Name.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Model for testing model name same as property name - */ -@ApiModel(description = "Model for testing model name same as property name") -@JsonPropertyOrder({ - Name.JSON_PROPERTY_NAME, - Name.JSON_PROPERTY_SNAKE_CASE, - Name.JSON_PROPERTY_PROPERTY, - Name.JSON_PROPERTY_123NUMBER -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Name { - public static final String JSON_PROPERTY_NAME = "name"; - private Integer name; - - public static final String JSON_PROPERTY_SNAKE_CASE = "snake_case"; - private Integer snakeCase; - - public static final String JSON_PROPERTY_PROPERTY = "property"; - private String property; - - public static final String JSON_PROPERTY_123NUMBER = "123Number"; - private Integer _123number; - - - public Name name(Integer name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public Integer getName() { - return name; - } - - - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setName(Integer name) { - this.name = name; - } - - - /** - * Get snakeCase - * @return snakeCase - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_SNAKE_CASE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getSnakeCase() { - return snakeCase; - } - - - - - public Name property(String property) { - this.property = property; - return this; - } - - /** - * Get property - * @return property - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_PROPERTY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getProperty() { - return property; - } - - - @JsonProperty(JSON_PROPERTY_PROPERTY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setProperty(String property) { - this.property = property; - } - - - /** - * Get _123number - * @return _123number - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_123NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer get123number() { - return _123number; - } - - - - - /** - * Return true if this Name object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Name name = (Name) o; - return Objects.equals(this.name, name.name) && - Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property) && - Objects.equals(this._123number, name._123number); - } - - @Override - public int hashCode() { - return Objects.hash(name, snakeCase, property, _123number); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Name {\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); - sb.append(" property: ").append(toIndentedString(property)).append("\n"); - sb.append(" _123number: ").append(toIndentedString(_123number)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableClass.java deleted file mode 100644 index ae35e6746a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableClass.java +++ /dev/null @@ -1,660 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * NullableClass - */ -@JsonPropertyOrder({ - NullableClass.JSON_PROPERTY_INTEGER_PROP, - NullableClass.JSON_PROPERTY_NUMBER_PROP, - NullableClass.JSON_PROPERTY_BOOLEAN_PROP, - NullableClass.JSON_PROPERTY_STRING_PROP, - NullableClass.JSON_PROPERTY_DATE_PROP, - NullableClass.JSON_PROPERTY_DATETIME_PROP, - NullableClass.JSON_PROPERTY_ARRAY_NULLABLE_PROP, - NullableClass.JSON_PROPERTY_ARRAY_AND_ITEMS_NULLABLE_PROP, - NullableClass.JSON_PROPERTY_ARRAY_ITEMS_NULLABLE, - NullableClass.JSON_PROPERTY_OBJECT_NULLABLE_PROP, - NullableClass.JSON_PROPERTY_OBJECT_AND_ITEMS_NULLABLE_PROP, - NullableClass.JSON_PROPERTY_OBJECT_ITEMS_NULLABLE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class NullableClass extends HashMap { - public static final String JSON_PROPERTY_INTEGER_PROP = "integer_prop"; - private JsonNullable integerProp = JsonNullable.undefined(); - - public static final String JSON_PROPERTY_NUMBER_PROP = "number_prop"; - private JsonNullable numberProp = JsonNullable.undefined(); - - public static final String JSON_PROPERTY_BOOLEAN_PROP = "boolean_prop"; - private JsonNullable booleanProp = JsonNullable.undefined(); - - public static final String JSON_PROPERTY_STRING_PROP = "string_prop"; - private JsonNullable stringProp = JsonNullable.undefined(); - - public static final String JSON_PROPERTY_DATE_PROP = "date_prop"; - private JsonNullable dateProp = JsonNullable.undefined(); - - public static final String JSON_PROPERTY_DATETIME_PROP = "datetime_prop"; - private JsonNullable datetimeProp = JsonNullable.undefined(); - - public static final String JSON_PROPERTY_ARRAY_NULLABLE_PROP = "array_nullable_prop"; - private JsonNullable> arrayNullableProp = JsonNullable.>undefined(); - - public static final String JSON_PROPERTY_ARRAY_AND_ITEMS_NULLABLE_PROP = "array_and_items_nullable_prop"; - private JsonNullable> arrayAndItemsNullableProp = JsonNullable.>undefined(); - - public static final String JSON_PROPERTY_ARRAY_ITEMS_NULLABLE = "array_items_nullable"; - private List arrayItemsNullable = null; - - public static final String JSON_PROPERTY_OBJECT_NULLABLE_PROP = "object_nullable_prop"; - private JsonNullable> objectNullableProp = JsonNullable.>undefined(); - - public static final String JSON_PROPERTY_OBJECT_AND_ITEMS_NULLABLE_PROP = "object_and_items_nullable_prop"; - private JsonNullable> objectAndItemsNullableProp = JsonNullable.>undefined(); - - public static final String JSON_PROPERTY_OBJECT_ITEMS_NULLABLE = "object_items_nullable"; - private Map objectItemsNullable = null; - - - public NullableClass integerProp(Integer integerProp) { - this.integerProp = JsonNullable.of(integerProp); - return this; - } - - /** - * Get integerProp - * @return integerProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public Integer getIntegerProp() { - return integerProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_INTEGER_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getIntegerProp_JsonNullable() { - return integerProp; - } - - @JsonProperty(JSON_PROPERTY_INTEGER_PROP) - public void setIntegerProp_JsonNullable(JsonNullable integerProp) { - this.integerProp = integerProp; - } - - public void setIntegerProp(Integer integerProp) { - this.integerProp = JsonNullable.of(integerProp); - } - - - public NullableClass numberProp(BigDecimal numberProp) { - this.numberProp = JsonNullable.of(numberProp); - return this; - } - - /** - * Get numberProp - * @return numberProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public BigDecimal getNumberProp() { - return numberProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_NUMBER_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getNumberProp_JsonNullable() { - return numberProp; - } - - @JsonProperty(JSON_PROPERTY_NUMBER_PROP) - public void setNumberProp_JsonNullable(JsonNullable numberProp) { - this.numberProp = numberProp; - } - - public void setNumberProp(BigDecimal numberProp) { - this.numberProp = JsonNullable.of(numberProp); - } - - - public NullableClass booleanProp(Boolean booleanProp) { - this.booleanProp = JsonNullable.of(booleanProp); - return this; - } - - /** - * Get booleanProp - * @return booleanProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public Boolean getBooleanProp() { - return booleanProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_BOOLEAN_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getBooleanProp_JsonNullable() { - return booleanProp; - } - - @JsonProperty(JSON_PROPERTY_BOOLEAN_PROP) - public void setBooleanProp_JsonNullable(JsonNullable booleanProp) { - this.booleanProp = booleanProp; - } - - public void setBooleanProp(Boolean booleanProp) { - this.booleanProp = JsonNullable.of(booleanProp); - } - - - public NullableClass stringProp(String stringProp) { - this.stringProp = JsonNullable.of(stringProp); - return this; - } - - /** - * Get stringProp - * @return stringProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public String getStringProp() { - return stringProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_STRING_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getStringProp_JsonNullable() { - return stringProp; - } - - @JsonProperty(JSON_PROPERTY_STRING_PROP) - public void setStringProp_JsonNullable(JsonNullable stringProp) { - this.stringProp = stringProp; - } - - public void setStringProp(String stringProp) { - this.stringProp = JsonNullable.of(stringProp); - } - - - public NullableClass dateProp(LocalDate dateProp) { - this.dateProp = JsonNullable.of(dateProp); - return this; - } - - /** - * Get dateProp - * @return dateProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public LocalDate getDateProp() { - return dateProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_DATE_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getDateProp_JsonNullable() { - return dateProp; - } - - @JsonProperty(JSON_PROPERTY_DATE_PROP) - public void setDateProp_JsonNullable(JsonNullable dateProp) { - this.dateProp = dateProp; - } - - public void setDateProp(LocalDate dateProp) { - this.dateProp = JsonNullable.of(dateProp); - } - - - public NullableClass datetimeProp(OffsetDateTime datetimeProp) { - this.datetimeProp = JsonNullable.of(datetimeProp); - return this; - } - - /** - * Get datetimeProp - * @return datetimeProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public OffsetDateTime getDatetimeProp() { - return datetimeProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_DATETIME_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getDatetimeProp_JsonNullable() { - return datetimeProp; - } - - @JsonProperty(JSON_PROPERTY_DATETIME_PROP) - public void setDatetimeProp_JsonNullable(JsonNullable datetimeProp) { - this.datetimeProp = datetimeProp; - } - - public void setDatetimeProp(OffsetDateTime datetimeProp) { - this.datetimeProp = JsonNullable.of(datetimeProp); - } - - - public NullableClass arrayNullableProp(List arrayNullableProp) { - this.arrayNullableProp = JsonNullable.>of(arrayNullableProp); - return this; - } - - public NullableClass addArrayNullablePropItem(Object arrayNullablePropItem) { - if (this.arrayNullableProp == null || !this.arrayNullableProp.isPresent()) { - this.arrayNullableProp = JsonNullable.>of(new ArrayList<>()); - } - try { - this.arrayNullableProp.get().add(arrayNullablePropItem); - } catch (java.util.NoSuchElementException e) { - // this can never happen, as we make sure above that the value is present - } - return this; - } - - /** - * Get arrayNullableProp - * @return arrayNullableProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public List getArrayNullableProp() { - return arrayNullableProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_ARRAY_NULLABLE_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable> getArrayNullableProp_JsonNullable() { - return arrayNullableProp; - } - - @JsonProperty(JSON_PROPERTY_ARRAY_NULLABLE_PROP) - public void setArrayNullableProp_JsonNullable(JsonNullable> arrayNullableProp) { - this.arrayNullableProp = arrayNullableProp; - } - - public void setArrayNullableProp(List arrayNullableProp) { - this.arrayNullableProp = JsonNullable.>of(arrayNullableProp); - } - - - public NullableClass arrayAndItemsNullableProp(List arrayAndItemsNullableProp) { - this.arrayAndItemsNullableProp = JsonNullable.>of(arrayAndItemsNullableProp); - return this; - } - - public NullableClass addArrayAndItemsNullablePropItem(Object arrayAndItemsNullablePropItem) { - if (this.arrayAndItemsNullableProp == null || !this.arrayAndItemsNullableProp.isPresent()) { - this.arrayAndItemsNullableProp = JsonNullable.>of(new ArrayList<>()); - } - try { - this.arrayAndItemsNullableProp.get().add(arrayAndItemsNullablePropItem); - } catch (java.util.NoSuchElementException e) { - // this can never happen, as we make sure above that the value is present - } - return this; - } - - /** - * Get arrayAndItemsNullableProp - * @return arrayAndItemsNullableProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public List getArrayAndItemsNullableProp() { - return arrayAndItemsNullableProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_ARRAY_AND_ITEMS_NULLABLE_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable> getArrayAndItemsNullableProp_JsonNullable() { - return arrayAndItemsNullableProp; - } - - @JsonProperty(JSON_PROPERTY_ARRAY_AND_ITEMS_NULLABLE_PROP) - public void setArrayAndItemsNullableProp_JsonNullable(JsonNullable> arrayAndItemsNullableProp) { - this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; - } - - public void setArrayAndItemsNullableProp(List arrayAndItemsNullableProp) { - this.arrayAndItemsNullableProp = JsonNullable.>of(arrayAndItemsNullableProp); - } - - - public NullableClass arrayItemsNullable(List arrayItemsNullable) { - this.arrayItemsNullable = arrayItemsNullable; - return this; - } - - public NullableClass addArrayItemsNullableItem(Object arrayItemsNullableItem) { - if (this.arrayItemsNullable == null) { - this.arrayItemsNullable = new ArrayList<>(); - } - this.arrayItemsNullable.add(arrayItemsNullableItem); - return this; - } - - /** - * Get arrayItemsNullable - * @return arrayItemsNullable - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ARRAY_ITEMS_NULLABLE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List getArrayItemsNullable() { - return arrayItemsNullable; - } - - - @JsonProperty(JSON_PROPERTY_ARRAY_ITEMS_NULLABLE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayItemsNullable(List arrayItemsNullable) { - this.arrayItemsNullable = arrayItemsNullable; - } - - - public NullableClass objectNullableProp(Map objectNullableProp) { - this.objectNullableProp = JsonNullable.>of(objectNullableProp); - return this; - } - - public NullableClass putObjectNullablePropItem(String key, Object objectNullablePropItem) { - if (this.objectNullableProp == null || !this.objectNullableProp.isPresent()) { - this.objectNullableProp = JsonNullable.>of(new HashMap<>()); - } - try { - this.objectNullableProp.get().put(key, objectNullablePropItem); - } catch (java.util.NoSuchElementException e) { - // this can never happen, as we make sure above that the value is present - } - return this; - } - - /** - * Get objectNullableProp - * @return objectNullableProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public Map getObjectNullableProp() { - return objectNullableProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_OBJECT_NULLABLE_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable> getObjectNullableProp_JsonNullable() { - return objectNullableProp; - } - - @JsonProperty(JSON_PROPERTY_OBJECT_NULLABLE_PROP) - public void setObjectNullableProp_JsonNullable(JsonNullable> objectNullableProp) { - this.objectNullableProp = objectNullableProp; - } - - public void setObjectNullableProp(Map objectNullableProp) { - this.objectNullableProp = JsonNullable.>of(objectNullableProp); - } - - - public NullableClass objectAndItemsNullableProp(Map objectAndItemsNullableProp) { - this.objectAndItemsNullableProp = JsonNullable.>of(objectAndItemsNullableProp); - return this; - } - - public NullableClass putObjectAndItemsNullablePropItem(String key, Object objectAndItemsNullablePropItem) { - if (this.objectAndItemsNullableProp == null || !this.objectAndItemsNullableProp.isPresent()) { - this.objectAndItemsNullableProp = JsonNullable.>of(new HashMap<>()); - } - try { - this.objectAndItemsNullableProp.get().put(key, objectAndItemsNullablePropItem); - } catch (java.util.NoSuchElementException e) { - // this can never happen, as we make sure above that the value is present - } - return this; - } - - /** - * Get objectAndItemsNullableProp - * @return objectAndItemsNullableProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonIgnore - - public Map getObjectAndItemsNullableProp() { - return objectAndItemsNullableProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_OBJECT_AND_ITEMS_NULLABLE_PROP) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable> getObjectAndItemsNullableProp_JsonNullable() { - return objectAndItemsNullableProp; - } - - @JsonProperty(JSON_PROPERTY_OBJECT_AND_ITEMS_NULLABLE_PROP) - public void setObjectAndItemsNullableProp_JsonNullable(JsonNullable> objectAndItemsNullableProp) { - this.objectAndItemsNullableProp = objectAndItemsNullableProp; - } - - public void setObjectAndItemsNullableProp(Map objectAndItemsNullableProp) { - this.objectAndItemsNullableProp = JsonNullable.>of(objectAndItemsNullableProp); - } - - - public NullableClass objectItemsNullable(Map objectItemsNullable) { - this.objectItemsNullable = objectItemsNullable; - return this; - } - - public NullableClass putObjectItemsNullableItem(String key, Object objectItemsNullableItem) { - if (this.objectItemsNullable == null) { - this.objectItemsNullable = new HashMap<>(); - } - this.objectItemsNullable.put(key, objectItemsNullableItem); - return this; - } - - /** - * Get objectItemsNullable - * @return objectItemsNullable - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_OBJECT_ITEMS_NULLABLE) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - - public Map getObjectItemsNullable() { - return objectItemsNullable; - } - - - @JsonProperty(JSON_PROPERTY_OBJECT_ITEMS_NULLABLE) - @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) - public void setObjectItemsNullable(Map objectItemsNullable) { - this.objectItemsNullable = objectItemsNullable; - } - - /** - * A container for additional, undeclared properties. - * This is a holder for any undeclared properties as specified with - * the 'additionalProperties' keyword in the OAS document. - */ - private Map additionalProperties; - - /** - * Set the additional (undeclared) property with the specified name and value. - * If the property does not already exist, create it otherwise replace it. - */ - @JsonAnySetter - public NullableClass putAdditionalProperty(String key, Object value) { - if (this.additionalProperties == null) { - this.additionalProperties = new HashMap(); - } - this.additionalProperties.put(key, value); - return this; - } - - /** - * Return the additional (undeclared) property. - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return additionalProperties; - } - - /** - * Return the additional (undeclared) property with the specified name. - */ - public Object getAdditionalProperty(String key) { - if (this.additionalProperties == null) { - return null; - } - return this.additionalProperties.get(key); - } - - /** - * Return true if this NullableClass object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - NullableClass nullableClass = (NullableClass) o; - return Objects.equals(this.integerProp, nullableClass.integerProp) && - Objects.equals(this.numberProp, nullableClass.numberProp) && - Objects.equals(this.booleanProp, nullableClass.booleanProp) && - Objects.equals(this.stringProp, nullableClass.stringProp) && - Objects.equals(this.dateProp, nullableClass.dateProp) && - Objects.equals(this.datetimeProp, nullableClass.datetimeProp) && - Objects.equals(this.arrayNullableProp, nullableClass.arrayNullableProp) && - Objects.equals(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && - Objects.equals(this.arrayItemsNullable, nullableClass.arrayItemsNullable) && - Objects.equals(this.objectNullableProp, nullableClass.objectNullableProp) && - Objects.equals(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && - Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable)&& - Objects.equals(this.additionalProperties, nullableClass.additionalProperties) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(integerProp, numberProp, booleanProp, stringProp, dateProp, datetimeProp, arrayNullableProp, arrayAndItemsNullableProp, arrayItemsNullable, objectNullableProp, objectAndItemsNullableProp, objectItemsNullable, super.hashCode(), additionalProperties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class NullableClass {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" integerProp: ").append(toIndentedString(integerProp)).append("\n"); - sb.append(" numberProp: ").append(toIndentedString(numberProp)).append("\n"); - sb.append(" booleanProp: ").append(toIndentedString(booleanProp)).append("\n"); - sb.append(" stringProp: ").append(toIndentedString(stringProp)).append("\n"); - sb.append(" dateProp: ").append(toIndentedString(dateProp)).append("\n"); - sb.append(" datetimeProp: ").append(toIndentedString(datetimeProp)).append("\n"); - sb.append(" arrayNullableProp: ").append(toIndentedString(arrayNullableProp)).append("\n"); - sb.append(" arrayAndItemsNullableProp: ").append(toIndentedString(arrayAndItemsNullableProp)).append("\n"); - sb.append(" arrayItemsNullable: ").append(toIndentedString(arrayItemsNullable)).append("\n"); - sb.append(" objectNullableProp: ").append(toIndentedString(objectNullableProp)).append("\n"); - sb.append(" objectAndItemsNullableProp: ").append(toIndentedString(objectAndItemsNullableProp)).append("\n"); - sb.append(" objectItemsNullable: ").append(toIndentedString(objectItemsNullable)).append("\n"); - sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableShape.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableShape.java deleted file mode 100644 index 77d27e3e2c..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableShape.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.Triangle; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import com.fasterxml.jackson.core.type.TypeReference; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using = NullableShape.NullableShapeDeserializer.class) -@JsonSerialize(using = NullableShape.NullableShapeSerializer.class) -public class NullableShape extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(NullableShape.class.getName()); - - public static class NullableShapeSerializer extends StdSerializer { - public NullableShapeSerializer(Class t) { - super(t); - } - - public NullableShapeSerializer() { - this(null); - } - - @Override - public void serialize(NullableShape value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class NullableShapeDeserializer extends StdDeserializer { - public NullableShapeDeserializer() { - this(NullableShape.class); - } - - public NullableShapeDeserializer(Class vc) { - super(vc); - } - - @Override - public NullableShape deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - Object deserialized = null; - NullableShape newNullableShape = new NullableShape(); - Map result2 = tree.traverse(jp.getCodec()).readValueAs(new TypeReference>() {}); - String discriminatorValue = (String)result2.get("shapeType"); - switch (discriminatorValue) { - case "Quadrilateral": - deserialized = tree.traverse(jp.getCodec()).readValueAs(Quadrilateral.class); - newNullableShape.setActualInstance(deserialized); - return newNullableShape; - case "Triangle": - deserialized = tree.traverse(jp.getCodec()).readValueAs(Triangle.class); - newNullableShape.setActualInstance(deserialized); - return newNullableShape; - default: - log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); - } - - boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); - int match = 0; - JsonToken token = tree.traverse(jp.getCodec()).nextToken(); - // deserialize Quadrilateral - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Quadrilateral.class.equals(Integer.class) || Quadrilateral.class.equals(Long.class) || Quadrilateral.class.equals(Float.class) || Quadrilateral.class.equals(Double.class) || Quadrilateral.class.equals(Boolean.class) || Quadrilateral.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Quadrilateral.class.equals(Integer.class) || Quadrilateral.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Quadrilateral.class.equals(Float.class) || Quadrilateral.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Quadrilateral.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Quadrilateral.class.equals(String.class) && token == JsonToken.VALUE_STRING); - attemptParsing |= (token == JsonToken.VALUE_NULL); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Quadrilateral.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Quadrilateral'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e); - } - - // deserialize Triangle - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Triangle.class.equals(Integer.class) || Triangle.class.equals(Long.class) || Triangle.class.equals(Float.class) || Triangle.class.equals(Double.class) || Triangle.class.equals(Boolean.class) || Triangle.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Triangle.class.equals(Integer.class) || Triangle.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Triangle.class.equals(Float.class) || Triangle.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Triangle.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Triangle.class.equals(String.class) && token == JsonToken.VALUE_STRING); - attemptParsing |= (token == JsonToken.VALUE_NULL); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Triangle.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Triangle'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Triangle'", e); - } - - if (match == 1) { - NullableShape ret = new NullableShape(); - ret.setActualInstance(deserialized); - return ret; - } - throw new IOException(String.format("Failed deserialization for NullableShape: %d classes match result, expected 1", match)); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public NullableShape getNullValue(DeserializationContext ctxt) throws JsonMappingException { - return null; - } - } - - // store a list of schema names defined in oneOf - public static final Map> schemas = new HashMap<>(); - - public NullableShape() { - super("oneOf", Boolean.TRUE); - } - - public NullableShape(Quadrilateral o) { - super("oneOf", Boolean.TRUE); - setActualInstance(o); - } - - public NullableShape(Triangle o) { - super("oneOf", Boolean.TRUE); - setActualInstance(o); - } - - static { - schemas.put("Quadrilateral", Quadrilateral.class); - schemas.put("Triangle", Triangle.class); - JSON.registerDescendants(NullableShape.class, Collections.unmodifiableMap(schemas)); - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("Quadrilateral", Quadrilateral.class); - mappings.put("Triangle", Triangle.class); - mappings.put("NullableShape", NullableShape.class); - JSON.registerDiscriminator(NullableShape.class, "shapeType", mappings); - } - - @Override - public Map> getSchemas() { - return NullableShape.schemas; - } - - /** - * Set the instance that matches the oneOf child schema, check - * the instance parameter is valid against the oneOf child schemas: - * Quadrilateral, Triangle - * - * It could be an instance of the 'oneOf' schemas. - * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). - */ - @Override - public void setActualInstance(Object instance) { - if (instance == null) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(Quadrilateral.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(Triangle.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Quadrilateral, Triangle"); - } - - /** - * Get the actual instance, which can be the following: - * Quadrilateral, Triangle - * - * @return The actual instance (Quadrilateral, Triangle) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `Quadrilateral`. If the actual instanct is not `Quadrilateral`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Quadrilateral` - * @throws ClassCastException if the instance is not `Quadrilateral` - */ - public Quadrilateral getQuadrilateral() throws ClassCastException { - return (Quadrilateral)super.getActualInstance(); - } - - /** - * Get the actual instance of `Triangle`. If the actual instanct is not `Triangle`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Triangle` - * @throws ClassCastException if the instance is not `Triangle` - */ - public Triangle getTriangle() throws ClassCastException { - return (Triangle)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NumberOnly.java deleted file mode 100644 index 296aeb125a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NumberOnly.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * NumberOnly - */ -@JsonPropertyOrder({ - NumberOnly.JSON_PROPERTY_JUST_NUMBER -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class NumberOnly { - public static final String JSON_PROPERTY_JUST_NUMBER = "JustNumber"; - private BigDecimal justNumber; - - - public NumberOnly justNumber(BigDecimal justNumber) { - this.justNumber = justNumber; - return this; - } - - /** - * Get justNumber - * @return justNumber - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_JUST_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public BigDecimal getJustNumber() { - return justNumber; - } - - - @JsonProperty(JSON_PROPERTY_JUST_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setJustNumber(BigDecimal justNumber) { - this.justNumber = justNumber; - } - - - /** - * Return true if this NumberOnly object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - NumberOnly numberOnly = (NumberOnly) o; - return Objects.equals(this.justNumber, numberOnly.justNumber); - } - - @Override - public int hashCode() { - return Objects.hash(justNumber); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class NumberOnly {\n"); - sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java deleted file mode 100644 index 6142bce52b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; -import org.openapitools.client.model.DeprecatedObject; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ObjectWithDeprecatedFields - */ -@JsonPropertyOrder({ - ObjectWithDeprecatedFields.JSON_PROPERTY_UUID, - ObjectWithDeprecatedFields.JSON_PROPERTY_ID, - ObjectWithDeprecatedFields.JSON_PROPERTY_DEPRECATED_REF, - ObjectWithDeprecatedFields.JSON_PROPERTY_BARS -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ObjectWithDeprecatedFields { - public static final String JSON_PROPERTY_UUID = "uuid"; - private String uuid; - - public static final String JSON_PROPERTY_ID = "id"; - private BigDecimal id; - - public static final String JSON_PROPERTY_DEPRECATED_REF = "deprecatedRef"; - private DeprecatedObject deprecatedRef; - - public static final String JSON_PROPERTY_BARS = "bars"; - private List bars = null; - - - public ObjectWithDeprecatedFields uuid(String uuid) { - this.uuid = uuid; - return this; - } - - /** - * Get uuid - * @return uuid - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_UUID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getUuid() { - return uuid; - } - - - @JsonProperty(JSON_PROPERTY_UUID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setUuid(String uuid) { - this.uuid = uuid; - } - - - public ObjectWithDeprecatedFields id(BigDecimal id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - * @deprecated - **/ - @Deprecated - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public BigDecimal getId() { - return id; - } - - - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setId(BigDecimal id) { - this.id = id; - } - - - public ObjectWithDeprecatedFields deprecatedRef(DeprecatedObject deprecatedRef) { - this.deprecatedRef = deprecatedRef; - return this; - } - - /** - * Get deprecatedRef - * @return deprecatedRef - * @deprecated - **/ - @Deprecated - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_DEPRECATED_REF) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public DeprecatedObject getDeprecatedRef() { - return deprecatedRef; - } - - - @JsonProperty(JSON_PROPERTY_DEPRECATED_REF) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setDeprecatedRef(DeprecatedObject deprecatedRef) { - this.deprecatedRef = deprecatedRef; - } - - - public ObjectWithDeprecatedFields bars(List bars) { - this.bars = bars; - return this; - } - - public ObjectWithDeprecatedFields addBarsItem(String barsItem) { - if (this.bars == null) { - this.bars = new ArrayList<>(); - } - this.bars.add(barsItem); - return this; - } - - /** - * Get bars - * @return bars - * @deprecated - **/ - @Deprecated - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_BARS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List getBars() { - return bars; - } - - - @JsonProperty(JSON_PROPERTY_BARS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setBars(List bars) { - this.bars = bars; - } - - - /** - * Return true if this ObjectWithDeprecatedFields object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ObjectWithDeprecatedFields objectWithDeprecatedFields = (ObjectWithDeprecatedFields) o; - return Objects.equals(this.uuid, objectWithDeprecatedFields.uuid) && - Objects.equals(this.id, objectWithDeprecatedFields.id) && - Objects.equals(this.deprecatedRef, objectWithDeprecatedFields.deprecatedRef) && - Objects.equals(this.bars, objectWithDeprecatedFields.bars); - } - - @Override - public int hashCode() { - return Objects.hash(uuid, id, deprecatedRef, bars); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ObjectWithDeprecatedFields {\n"); - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" deprecatedRef: ").append(toIndentedString(deprecatedRef)).append("\n"); - sb.append(" bars: ").append(toIndentedString(bars)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Order.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Order.java deleted file mode 100644 index 05eacb91b5..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Order.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.time.OffsetDateTime; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Order - */ -@JsonPropertyOrder({ - Order.JSON_PROPERTY_ID, - Order.JSON_PROPERTY_PET_ID, - Order.JSON_PROPERTY_QUANTITY, - Order.JSON_PROPERTY_SHIP_DATE, - Order.JSON_PROPERTY_STATUS, - Order.JSON_PROPERTY_COMPLETE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Order { - public static final String JSON_PROPERTY_ID = "id"; - private Long id; - - public static final String JSON_PROPERTY_PET_ID = "petId"; - private Long petId; - - public static final String JSON_PROPERTY_QUANTITY = "quantity"; - private Integer quantity; - - public static final String JSON_PROPERTY_SHIP_DATE = "shipDate"; - private OffsetDateTime shipDate; - - /** - * Order Status - */ - public enum StatusEnum { - PLACED("placed"), - - APPROVED("approved"), - - DELIVERED("delivered"); - - private String value; - - StatusEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static StatusEnum fromValue(String value) { - for (StatusEnum b : StatusEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_STATUS = "status"; - private StatusEnum status; - - public static final String JSON_PROPERTY_COMPLETE = "complete"; - private Boolean complete = false; - - - public Order id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Long getId() { - return id; - } - - - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setId(Long id) { - this.id = id; - } - - - public Order petId(Long petId) { - this.petId = petId; - return this; - } - - /** - * Get petId - * @return petId - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_PET_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Long getPetId() { - return petId; - } - - - @JsonProperty(JSON_PROPERTY_PET_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setPetId(Long petId) { - this.petId = petId; - } - - - public Order quantity(Integer quantity) { - this.quantity = quantity; - return this; - } - - /** - * Get quantity - * @return quantity - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_QUANTITY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getQuantity() { - return quantity; - } - - - @JsonProperty(JSON_PROPERTY_QUANTITY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - - public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; - return this; - } - - /** - * Get shipDate - * @return shipDate - **/ - @javax.annotation.Nullable - @ApiModelProperty(example = "2020-02-02T20:20:20.000222Z", value = "") - @JsonProperty(JSON_PROPERTY_SHIP_DATE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public OffsetDateTime getShipDate() { - return shipDate; - } - - - @JsonProperty(JSON_PROPERTY_SHIP_DATE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setShipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; - } - - - public Order status(StatusEnum status) { - this.status = status; - return this; - } - - /** - * Order Status - * @return status - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "Order Status") - @JsonProperty(JSON_PROPERTY_STATUS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public StatusEnum getStatus() { - return status; - } - - - @JsonProperty(JSON_PROPERTY_STATUS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setStatus(StatusEnum status) { - this.status = status; - } - - - public Order complete(Boolean complete) { - this.complete = complete; - return this; - } - - /** - * Get complete - * @return complete - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_COMPLETE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Boolean getComplete() { - return complete; - } - - - @JsonProperty(JSON_PROPERTY_COMPLETE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setComplete(Boolean complete) { - this.complete = complete; - } - - - /** - * Return true if this Order object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Order order = (Order) o; - return Objects.equals(this.id, order.id) && - Objects.equals(this.petId, order.petId) && - Objects.equals(this.quantity, order.quantity) && - Objects.equals(this.shipDate, order.shipDate) && - Objects.equals(this.status, order.status) && - Objects.equals(this.complete, order.complete); - } - - @Override - public int hashCode() { - return Objects.hash(id, petId, quantity, shipDate, status, complete); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); - sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); - sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterComposite.java deleted file mode 100644 index 2ff2cfeb31..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterComposite.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * OuterComposite - */ -@JsonPropertyOrder({ - OuterComposite.JSON_PROPERTY_MY_NUMBER, - OuterComposite.JSON_PROPERTY_MY_STRING, - OuterComposite.JSON_PROPERTY_MY_BOOLEAN -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class OuterComposite { - public static final String JSON_PROPERTY_MY_NUMBER = "my_number"; - private BigDecimal myNumber; - - public static final String JSON_PROPERTY_MY_STRING = "my_string"; - private String myString; - - public static final String JSON_PROPERTY_MY_BOOLEAN = "my_boolean"; - private Boolean myBoolean; - - - public OuterComposite myNumber(BigDecimal myNumber) { - this.myNumber = myNumber; - return this; - } - - /** - * Get myNumber - * @return myNumber - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MY_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public BigDecimal getMyNumber() { - return myNumber; - } - - - @JsonProperty(JSON_PROPERTY_MY_NUMBER) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMyNumber(BigDecimal myNumber) { - this.myNumber = myNumber; - } - - - public OuterComposite myString(String myString) { - this.myString = myString; - return this; - } - - /** - * Get myString - * @return myString - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MY_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getMyString() { - return myString; - } - - - @JsonProperty(JSON_PROPERTY_MY_STRING) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMyString(String myString) { - this.myString = myString; - } - - - public OuterComposite myBoolean(Boolean myBoolean) { - this.myBoolean = myBoolean; - return this; - } - - /** - * Get myBoolean - * @return myBoolean - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_MY_BOOLEAN) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Boolean getMyBoolean() { - return myBoolean; - } - - - @JsonProperty(JSON_PROPERTY_MY_BOOLEAN) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setMyBoolean(Boolean myBoolean) { - this.myBoolean = myBoolean; - } - - - /** - * Return true if this OuterComposite object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - OuterComposite outerComposite = (OuterComposite) o; - return Objects.equals(this.myNumber, outerComposite.myNumber) && - Objects.equals(this.myString, outerComposite.myString) && - Objects.equals(this.myBoolean, outerComposite.myBoolean); - } - - @Override - public int hashCode() { - return Objects.hash(myNumber, myString, myBoolean); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class OuterComposite {\n"); - sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); - sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); - sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnum.java deleted file mode 100644 index afc9120412..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnum.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - -/** - * Gets or Sets OuterEnum - */ -public enum OuterEnum { - - PLACED("placed"), - - APPROVED("approved"), - - DELIVERED("delivered"); - - private String value; - - OuterEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static OuterEnum fromValue(String value) { - for (OuterEnum b : OuterEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - return null; - } -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java deleted file mode 100644 index f24d69e69e..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - -/** - * Gets or Sets OuterEnumDefaultValue - */ -public enum OuterEnumDefaultValue { - - PLACED("placed"), - - APPROVED("approved"), - - DELIVERED("delivered"); - - private String value; - - OuterEnumDefaultValue(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static OuterEnumDefaultValue fromValue(String value) { - for (OuterEnumDefaultValue b : OuterEnumDefaultValue.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnumInteger.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnumInteger.java deleted file mode 100644 index e2d7dd1409..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnumInteger.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - -/** - * Gets or Sets OuterEnumInteger - */ -public enum OuterEnumInteger { - - NUMBER_0(0), - - NUMBER_1(1), - - NUMBER_2(2); - - private Integer value; - - OuterEnumInteger(Integer value) { - this.value = value; - } - - @JsonValue - public Integer getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static OuterEnumInteger fromValue(Integer value) { - for (OuterEnumInteger b : OuterEnumInteger.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java deleted file mode 100644 index 029cf8899a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - -/** - * Gets or Sets OuterEnumIntegerDefaultValue - */ -public enum OuterEnumIntegerDefaultValue { - - NUMBER_0(0), - - NUMBER_1(1), - - NUMBER_2(2); - - private Integer value; - - OuterEnumIntegerDefaultValue(Integer value) { - this.value = value; - } - - @JsonValue - public Integer getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static OuterEnumIntegerDefaultValue fromValue(Integer value) { - for (OuterEnumIntegerDefaultValue b : OuterEnumIntegerDefaultValue.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ParentPet.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ParentPet.java deleted file mode 100644 index 2175d750c0..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ParentPet.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ChildCat; -import org.openapitools.client.model.GrandparentAnimal; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -import org.openapitools.client.JSON; -/** - * ParentPet - */ -@JsonPropertyOrder({ -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "pet_type", visible = true) -@JsonSubTypes({ - @JsonSubTypes.Type(value = ChildCat.class, name = "ChildCat"), -}) - -public class ParentPet extends GrandparentAnimal { - - /** - * Return true if this ParentPet object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - return super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ParentPet {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -static { - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("ChildCat", ChildCat.class); - mappings.put("ParentPet", ParentPet.class); - JSON.registerDiscriminator(ParentPet.class, "pet_type", mappings); -} -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pet.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pet.java deleted file mode 100644 index e822ec8ae6..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pet.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import org.openapitools.client.model.Category; -import org.openapitools.client.model.Tag; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Pet - */ -@JsonPropertyOrder({ - Pet.JSON_PROPERTY_ID, - Pet.JSON_PROPERTY_CATEGORY, - Pet.JSON_PROPERTY_NAME, - Pet.JSON_PROPERTY_PHOTO_URLS, - Pet.JSON_PROPERTY_TAGS, - Pet.JSON_PROPERTY_STATUS -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Pet { - public static final String JSON_PROPERTY_ID = "id"; - private Long id; - - public static final String JSON_PROPERTY_CATEGORY = "category"; - private Category category; - - public static final String JSON_PROPERTY_NAME = "name"; - private String name; - - public static final String JSON_PROPERTY_PHOTO_URLS = "photoUrls"; - private List photoUrls = new ArrayList<>(); - - public static final String JSON_PROPERTY_TAGS = "tags"; - private List tags = null; - - /** - * pet status in the store - */ - public enum StatusEnum { - AVAILABLE("available"), - - PENDING("pending"), - - SOLD("sold"); - - private String value; - - StatusEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static StatusEnum fromValue(String value) { - for (StatusEnum b : StatusEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_STATUS = "status"; - private StatusEnum status; - - - public Pet id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Long getId() { - return id; - } - - - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setId(Long id) { - this.id = id; - } - - - public Pet category(Category category) { - this.category = category; - return this; - } - - /** - * Get category - * @return category - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_CATEGORY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Category getCategory() { - return category; - } - - - @JsonProperty(JSON_PROPERTY_CATEGORY) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setCategory(Category category) { - this.category = category; - } - - - public Pet name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @javax.annotation.Nonnull - @ApiModelProperty(example = "doggie", required = true, value = "") - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getName() { - return name; - } - - - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setName(String name) { - this.name = name; - } - - - public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; - return this; - } - - public Pet addPhotoUrlsItem(String photoUrlsItem) { - this.photoUrls.add(photoUrlsItem); - return this; - } - - /** - * Get photoUrls - * @return photoUrls - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_PHOTO_URLS) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public List getPhotoUrls() { - return photoUrls; - } - - - @JsonProperty(JSON_PROPERTY_PHOTO_URLS) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setPhotoUrls(List photoUrls) { - this.photoUrls = photoUrls; - } - - - public Pet tags(List tags) { - this.tags = tags; - return this; - } - - public Pet addTagsItem(Tag tagsItem) { - if (this.tags == null) { - this.tags = new ArrayList<>(); - } - this.tags.add(tagsItem); - return this; - } - - /** - * Get tags - * @return tags - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_TAGS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public List getTags() { - return tags; - } - - - @JsonProperty(JSON_PROPERTY_TAGS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setTags(List tags) { - this.tags = tags; - } - - - public Pet status(StatusEnum status) { - this.status = status; - return this; - } - - /** - * pet status in the store - * @return status - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "pet status in the store") - @JsonProperty(JSON_PROPERTY_STATUS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public StatusEnum getStatus() { - return status; - } - - - @JsonProperty(JSON_PROPERTY_STATUS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setStatus(StatusEnum status) { - this.status = status; - } - - - /** - * Return true if this Pet object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Pet pet = (Pet) o; - return Objects.equals(this.id, pet.id) && - Objects.equals(this.category, pet.category) && - Objects.equals(this.name, pet.name) && - Objects.equals(this.photoUrls, pet.photoUrls) && - Objects.equals(this.tags, pet.tags) && - Objects.equals(this.status, pet.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, category, name, photoUrls, tags, status); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Pet {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" category: ").append(toIndentedString(category)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); - sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pig.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pig.java deleted file mode 100644 index e77218d922..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pig.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.BasquePig; -import org.openapitools.client.model.DanishPig; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import com.fasterxml.jackson.core.type.TypeReference; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using = Pig.PigDeserializer.class) -@JsonSerialize(using = Pig.PigSerializer.class) -public class Pig extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(Pig.class.getName()); - - public static class PigSerializer extends StdSerializer { - public PigSerializer(Class t) { - super(t); - } - - public PigSerializer() { - this(null); - } - - @Override - public void serialize(Pig value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class PigDeserializer extends StdDeserializer { - public PigDeserializer() { - this(Pig.class); - } - - public PigDeserializer(Class vc) { - super(vc); - } - - @Override - public Pig deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - Object deserialized = null; - Pig newPig = new Pig(); - Map result2 = tree.traverse(jp.getCodec()).readValueAs(new TypeReference>() {}); - String discriminatorValue = (String)result2.get("className"); - switch (discriminatorValue) { - case "BasquePig": - deserialized = tree.traverse(jp.getCodec()).readValueAs(BasquePig.class); - newPig.setActualInstance(deserialized); - return newPig; - case "DanishPig": - deserialized = tree.traverse(jp.getCodec()).readValueAs(DanishPig.class); - newPig.setActualInstance(deserialized); - return newPig; - default: - log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); - } - - boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); - int match = 0; - JsonToken token = tree.traverse(jp.getCodec()).nextToken(); - // deserialize BasquePig - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (BasquePig.class.equals(Integer.class) || BasquePig.class.equals(Long.class) || BasquePig.class.equals(Float.class) || BasquePig.class.equals(Double.class) || BasquePig.class.equals(Boolean.class) || BasquePig.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((BasquePig.class.equals(Integer.class) || BasquePig.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((BasquePig.class.equals(Float.class) || BasquePig.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (BasquePig.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (BasquePig.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(BasquePig.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'BasquePig'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'BasquePig'", e); - } - - // deserialize DanishPig - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (DanishPig.class.equals(Integer.class) || DanishPig.class.equals(Long.class) || DanishPig.class.equals(Float.class) || DanishPig.class.equals(Double.class) || DanishPig.class.equals(Boolean.class) || DanishPig.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((DanishPig.class.equals(Integer.class) || DanishPig.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((DanishPig.class.equals(Float.class) || DanishPig.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (DanishPig.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (DanishPig.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(DanishPig.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'DanishPig'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'DanishPig'", e); - } - - if (match == 1) { - Pig ret = new Pig(); - ret.setActualInstance(deserialized); - return ret; - } - throw new IOException(String.format("Failed deserialization for Pig: %d classes match result, expected 1", match)); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public Pig getNullValue(DeserializationContext ctxt) throws JsonMappingException { - throw new JsonMappingException(ctxt.getParser(), "Pig cannot be null"); - } - } - - // store a list of schema names defined in oneOf - public static final Map> schemas = new HashMap<>(); - - public Pig() { - super("oneOf", Boolean.FALSE); - } - - public Pig(BasquePig o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - public Pig(DanishPig o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("BasquePig", BasquePig.class); - schemas.put("DanishPig", DanishPig.class); - JSON.registerDescendants(Pig.class, Collections.unmodifiableMap(schemas)); - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("BasquePig", BasquePig.class); - mappings.put("DanishPig", DanishPig.class); - mappings.put("Pig", Pig.class); - JSON.registerDiscriminator(Pig.class, "className", mappings); - } - - @Override - public Map> getSchemas() { - return Pig.schemas; - } - - /** - * Set the instance that matches the oneOf child schema, check - * the instance parameter is valid against the oneOf child schemas: - * BasquePig, DanishPig - * - * It could be an instance of the 'oneOf' schemas. - * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). - */ - @Override - public void setActualInstance(Object instance) { - if (JSON.isInstanceOf(BasquePig.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(DanishPig.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be BasquePig, DanishPig"); - } - - /** - * Get the actual instance, which can be the following: - * BasquePig, DanishPig - * - * @return The actual instance (BasquePig, DanishPig) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `BasquePig`. If the actual instanct is not `BasquePig`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `BasquePig` - * @throws ClassCastException if the instance is not `BasquePig` - */ - public BasquePig getBasquePig() throws ClassCastException { - return (BasquePig)super.getActualInstance(); - } - - /** - * Get the actual instance of `DanishPig`. If the actual instanct is not `DanishPig`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `DanishPig` - * @throws ClassCastException if the instance is not `DanishPig` - */ - public DanishPig getDanishPig() throws ClassCastException { - return (DanishPig)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Quadrilateral.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Quadrilateral.java deleted file mode 100644 index b2c184698d..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Quadrilateral.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ComplexQuadrilateral; -import org.openapitools.client.model.SimpleQuadrilateral; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import com.fasterxml.jackson.core.type.TypeReference; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using = Quadrilateral.QuadrilateralDeserializer.class) -@JsonSerialize(using = Quadrilateral.QuadrilateralSerializer.class) -public class Quadrilateral extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(Quadrilateral.class.getName()); - - public static class QuadrilateralSerializer extends StdSerializer { - public QuadrilateralSerializer(Class t) { - super(t); - } - - public QuadrilateralSerializer() { - this(null); - } - - @Override - public void serialize(Quadrilateral value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class QuadrilateralDeserializer extends StdDeserializer { - public QuadrilateralDeserializer() { - this(Quadrilateral.class); - } - - public QuadrilateralDeserializer(Class vc) { - super(vc); - } - - @Override - public Quadrilateral deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - Object deserialized = null; - Quadrilateral newQuadrilateral = new Quadrilateral(); - Map result2 = tree.traverse(jp.getCodec()).readValueAs(new TypeReference>() {}); - String discriminatorValue = (String)result2.get("quadrilateralType"); - switch (discriminatorValue) { - case "ComplexQuadrilateral": - deserialized = tree.traverse(jp.getCodec()).readValueAs(ComplexQuadrilateral.class); - newQuadrilateral.setActualInstance(deserialized); - return newQuadrilateral; - case "SimpleQuadrilateral": - deserialized = tree.traverse(jp.getCodec()).readValueAs(SimpleQuadrilateral.class); - newQuadrilateral.setActualInstance(deserialized); - return newQuadrilateral; - default: - log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); - } - - boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); - int match = 0; - JsonToken token = tree.traverse(jp.getCodec()).nextToken(); - // deserialize ComplexQuadrilateral - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (ComplexQuadrilateral.class.equals(Integer.class) || ComplexQuadrilateral.class.equals(Long.class) || ComplexQuadrilateral.class.equals(Float.class) || ComplexQuadrilateral.class.equals(Double.class) || ComplexQuadrilateral.class.equals(Boolean.class) || ComplexQuadrilateral.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((ComplexQuadrilateral.class.equals(Integer.class) || ComplexQuadrilateral.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((ComplexQuadrilateral.class.equals(Float.class) || ComplexQuadrilateral.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (ComplexQuadrilateral.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (ComplexQuadrilateral.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(ComplexQuadrilateral.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'ComplexQuadrilateral'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'ComplexQuadrilateral'", e); - } - - // deserialize SimpleQuadrilateral - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (SimpleQuadrilateral.class.equals(Integer.class) || SimpleQuadrilateral.class.equals(Long.class) || SimpleQuadrilateral.class.equals(Float.class) || SimpleQuadrilateral.class.equals(Double.class) || SimpleQuadrilateral.class.equals(Boolean.class) || SimpleQuadrilateral.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((SimpleQuadrilateral.class.equals(Integer.class) || SimpleQuadrilateral.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((SimpleQuadrilateral.class.equals(Float.class) || SimpleQuadrilateral.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (SimpleQuadrilateral.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (SimpleQuadrilateral.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(SimpleQuadrilateral.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'SimpleQuadrilateral'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'SimpleQuadrilateral'", e); - } - - if (match == 1) { - Quadrilateral ret = new Quadrilateral(); - ret.setActualInstance(deserialized); - return ret; - } - throw new IOException(String.format("Failed deserialization for Quadrilateral: %d classes match result, expected 1", match)); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public Quadrilateral getNullValue(DeserializationContext ctxt) throws JsonMappingException { - throw new JsonMappingException(ctxt.getParser(), "Quadrilateral cannot be null"); - } - } - - // store a list of schema names defined in oneOf - public static final Map> schemas = new HashMap<>(); - - public Quadrilateral() { - super("oneOf", Boolean.FALSE); - } - - public Quadrilateral(ComplexQuadrilateral o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - public Quadrilateral(SimpleQuadrilateral o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("ComplexQuadrilateral", ComplexQuadrilateral.class); - schemas.put("SimpleQuadrilateral", SimpleQuadrilateral.class); - JSON.registerDescendants(Quadrilateral.class, Collections.unmodifiableMap(schemas)); - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("ComplexQuadrilateral", ComplexQuadrilateral.class); - mappings.put("SimpleQuadrilateral", SimpleQuadrilateral.class); - mappings.put("Quadrilateral", Quadrilateral.class); - JSON.registerDiscriminator(Quadrilateral.class, "quadrilateralType", mappings); - } - - @Override - public Map> getSchemas() { - return Quadrilateral.schemas; - } - - /** - * Set the instance that matches the oneOf child schema, check - * the instance parameter is valid against the oneOf child schemas: - * ComplexQuadrilateral, SimpleQuadrilateral - * - * It could be an instance of the 'oneOf' schemas. - * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). - */ - @Override - public void setActualInstance(Object instance) { - if (JSON.isInstanceOf(ComplexQuadrilateral.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(SimpleQuadrilateral.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be ComplexQuadrilateral, SimpleQuadrilateral"); - } - - /** - * Get the actual instance, which can be the following: - * ComplexQuadrilateral, SimpleQuadrilateral - * - * @return The actual instance (ComplexQuadrilateral, SimpleQuadrilateral) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `ComplexQuadrilateral`. If the actual instanct is not `ComplexQuadrilateral`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `ComplexQuadrilateral` - * @throws ClassCastException if the instance is not `ComplexQuadrilateral` - */ - public ComplexQuadrilateral getComplexQuadrilateral() throws ClassCastException { - return (ComplexQuadrilateral)super.getActualInstance(); - } - - /** - * Get the actual instance of `SimpleQuadrilateral`. If the actual instanct is not `SimpleQuadrilateral`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `SimpleQuadrilateral` - * @throws ClassCastException if the instance is not `SimpleQuadrilateral` - */ - public SimpleQuadrilateral getSimpleQuadrilateral() throws ClassCastException { - return (SimpleQuadrilateral)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java deleted file mode 100644 index 0541aba57d..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * QuadrilateralInterface - */ -@JsonPropertyOrder({ - QuadrilateralInterface.JSON_PROPERTY_QUADRILATERAL_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class QuadrilateralInterface { - public static final String JSON_PROPERTY_QUADRILATERAL_TYPE = "quadrilateralType"; - private String quadrilateralType; - - - public QuadrilateralInterface quadrilateralType(String quadrilateralType) { - this.quadrilateralType = quadrilateralType; - return this; - } - - /** - * Get quadrilateralType - * @return quadrilateralType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_QUADRILATERAL_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getQuadrilateralType() { - return quadrilateralType; - } - - - @JsonProperty(JSON_PROPERTY_QUADRILATERAL_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setQuadrilateralType(String quadrilateralType) { - this.quadrilateralType = quadrilateralType; - } - - - /** - * Return true if this QuadrilateralInterface object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - QuadrilateralInterface quadrilateralInterface = (QuadrilateralInterface) o; - return Objects.equals(this.quadrilateralType, quadrilateralInterface.quadrilateralType); - } - - @Override - public int hashCode() { - return Objects.hash(quadrilateralType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class QuadrilateralInterface {\n"); - sb.append(" quadrilateralType: ").append(toIndentedString(quadrilateralType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java deleted file mode 100644 index f36aeefc3b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ReadOnlyFirst - */ -@JsonPropertyOrder({ - ReadOnlyFirst.JSON_PROPERTY_BAR, - ReadOnlyFirst.JSON_PROPERTY_BAZ -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ReadOnlyFirst { - public static final String JSON_PROPERTY_BAR = "bar"; - private String bar; - - public static final String JSON_PROPERTY_BAZ = "baz"; - private String baz; - - - /** - * Get bar - * @return bar - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_BAR) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getBar() { - return bar; - } - - - - - public ReadOnlyFirst baz(String baz) { - this.baz = baz; - return this; - } - - /** - * Get baz - * @return baz - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_BAZ) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getBaz() { - return baz; - } - - - @JsonProperty(JSON_PROPERTY_BAZ) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setBaz(String baz) { - this.baz = baz; - } - - - /** - * Return true if this ReadOnlyFirst object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(this.bar, readOnlyFirst.bar) && - Objects.equals(this.baz, readOnlyFirst.baz); - } - - @Override - public int hashCode() { - return Objects.hash(bar, baz); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ReadOnlyFirst {\n"); - sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); - sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ScaleneTriangle.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ScaleneTriangle.java deleted file mode 100644 index 08dff3550b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ScaleneTriangle.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ShapeInterface; -import org.openapitools.client.model.TriangleInterface; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ScaleneTriangle - */ -@JsonPropertyOrder({ - ScaleneTriangle.JSON_PROPERTY_SHAPE_TYPE, - ScaleneTriangle.JSON_PROPERTY_TRIANGLE_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ScaleneTriangle { - public static final String JSON_PROPERTY_SHAPE_TYPE = "shapeType"; - private String shapeType; - - public static final String JSON_PROPERTY_TRIANGLE_TYPE = "triangleType"; - private String triangleType; - - - public ScaleneTriangle shapeType(String shapeType) { - this.shapeType = shapeType; - return this; - } - - /** - * Get shapeType - * @return shapeType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getShapeType() { - return shapeType; - } - - - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setShapeType(String shapeType) { - this.shapeType = shapeType; - } - - - public ScaleneTriangle triangleType(String triangleType) { - this.triangleType = triangleType; - return this; - } - - /** - * Get triangleType - * @return triangleType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_TRIANGLE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getTriangleType() { - return triangleType; - } - - - @JsonProperty(JSON_PROPERTY_TRIANGLE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setTriangleType(String triangleType) { - this.triangleType = triangleType; - } - - - /** - * Return true if this ScaleneTriangle object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ScaleneTriangle scaleneTriangle = (ScaleneTriangle) o; - return Objects.equals(this.shapeType, scaleneTriangle.shapeType) && - Objects.equals(this.triangleType, scaleneTriangle.triangleType); - } - - @Override - public int hashCode() { - return Objects.hash(shapeType, triangleType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ScaleneTriangle {\n"); - sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); - sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Shape.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Shape.java deleted file mode 100644 index b29a366dad..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Shape.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.Triangle; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import com.fasterxml.jackson.core.type.TypeReference; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using = Shape.ShapeDeserializer.class) -@JsonSerialize(using = Shape.ShapeSerializer.class) -public class Shape extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(Shape.class.getName()); - - public static class ShapeSerializer extends StdSerializer { - public ShapeSerializer(Class t) { - super(t); - } - - public ShapeSerializer() { - this(null); - } - - @Override - public void serialize(Shape value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class ShapeDeserializer extends StdDeserializer { - public ShapeDeserializer() { - this(Shape.class); - } - - public ShapeDeserializer(Class vc) { - super(vc); - } - - @Override - public Shape deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - Object deserialized = null; - Shape newShape = new Shape(); - Map result2 = tree.traverse(jp.getCodec()).readValueAs(new TypeReference>() {}); - String discriminatorValue = (String)result2.get("shapeType"); - switch (discriminatorValue) { - case "Quadrilateral": - deserialized = tree.traverse(jp.getCodec()).readValueAs(Quadrilateral.class); - newShape.setActualInstance(deserialized); - return newShape; - case "Triangle": - deserialized = tree.traverse(jp.getCodec()).readValueAs(Triangle.class); - newShape.setActualInstance(deserialized); - return newShape; - default: - log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); - } - - boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); - int match = 0; - JsonToken token = tree.traverse(jp.getCodec()).nextToken(); - // deserialize Quadrilateral - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Quadrilateral.class.equals(Integer.class) || Quadrilateral.class.equals(Long.class) || Quadrilateral.class.equals(Float.class) || Quadrilateral.class.equals(Double.class) || Quadrilateral.class.equals(Boolean.class) || Quadrilateral.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Quadrilateral.class.equals(Integer.class) || Quadrilateral.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Quadrilateral.class.equals(Float.class) || Quadrilateral.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Quadrilateral.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Quadrilateral.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Quadrilateral.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Quadrilateral'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e); - } - - // deserialize Triangle - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Triangle.class.equals(Integer.class) || Triangle.class.equals(Long.class) || Triangle.class.equals(Float.class) || Triangle.class.equals(Double.class) || Triangle.class.equals(Boolean.class) || Triangle.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Triangle.class.equals(Integer.class) || Triangle.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Triangle.class.equals(Float.class) || Triangle.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Triangle.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Triangle.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Triangle.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Triangle'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Triangle'", e); - } - - if (match == 1) { - Shape ret = new Shape(); - ret.setActualInstance(deserialized); - return ret; - } - throw new IOException(String.format("Failed deserialization for Shape: %d classes match result, expected 1", match)); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public Shape getNullValue(DeserializationContext ctxt) throws JsonMappingException { - throw new JsonMappingException(ctxt.getParser(), "Shape cannot be null"); - } - } - - // store a list of schema names defined in oneOf - public static final Map> schemas = new HashMap<>(); - - public Shape() { - super("oneOf", Boolean.FALSE); - } - - public Shape(Quadrilateral o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - public Shape(Triangle o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("Quadrilateral", Quadrilateral.class); - schemas.put("Triangle", Triangle.class); - JSON.registerDescendants(Shape.class, Collections.unmodifiableMap(schemas)); - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("Quadrilateral", Quadrilateral.class); - mappings.put("Triangle", Triangle.class); - mappings.put("Shape", Shape.class); - JSON.registerDiscriminator(Shape.class, "shapeType", mappings); - } - - @Override - public Map> getSchemas() { - return Shape.schemas; - } - - /** - * Set the instance that matches the oneOf child schema, check - * the instance parameter is valid against the oneOf child schemas: - * Quadrilateral, Triangle - * - * It could be an instance of the 'oneOf' schemas. - * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). - */ - @Override - public void setActualInstance(Object instance) { - if (JSON.isInstanceOf(Quadrilateral.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(Triangle.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Quadrilateral, Triangle"); - } - - /** - * Get the actual instance, which can be the following: - * Quadrilateral, Triangle - * - * @return The actual instance (Quadrilateral, Triangle) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `Quadrilateral`. If the actual instanct is not `Quadrilateral`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Quadrilateral` - * @throws ClassCastException if the instance is not `Quadrilateral` - */ - public Quadrilateral getQuadrilateral() throws ClassCastException { - return (Quadrilateral)super.getActualInstance(); - } - - /** - * Get the actual instance of `Triangle`. If the actual instanct is not `Triangle`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Triangle` - * @throws ClassCastException if the instance is not `Triangle` - */ - public Triangle getTriangle() throws ClassCastException { - return (Triangle)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeInterface.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeInterface.java deleted file mode 100644 index 06c82740a4..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeInterface.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * ShapeInterface - */ -@JsonPropertyOrder({ - ShapeInterface.JSON_PROPERTY_SHAPE_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class ShapeInterface { - public static final String JSON_PROPERTY_SHAPE_TYPE = "shapeType"; - private String shapeType; - - - public ShapeInterface shapeType(String shapeType) { - this.shapeType = shapeType; - return this; - } - - /** - * Get shapeType - * @return shapeType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getShapeType() { - return shapeType; - } - - - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setShapeType(String shapeType) { - this.shapeType = shapeType; - } - - - /** - * Return true if this ShapeInterface object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ShapeInterface shapeInterface = (ShapeInterface) o; - return Objects.equals(this.shapeType, shapeInterface.shapeType); - } - - @Override - public int hashCode() { - return Objects.hash(shapeType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ShapeInterface {\n"); - sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeOrNull.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeOrNull.java deleted file mode 100644 index 05598727e1..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeOrNull.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.Triangle; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import com.fasterxml.jackson.core.type.TypeReference; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using = ShapeOrNull.ShapeOrNullDeserializer.class) -@JsonSerialize(using = ShapeOrNull.ShapeOrNullSerializer.class) -public class ShapeOrNull extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(ShapeOrNull.class.getName()); - - public static class ShapeOrNullSerializer extends StdSerializer { - public ShapeOrNullSerializer(Class t) { - super(t); - } - - public ShapeOrNullSerializer() { - this(null); - } - - @Override - public void serialize(ShapeOrNull value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class ShapeOrNullDeserializer extends StdDeserializer { - public ShapeOrNullDeserializer() { - this(ShapeOrNull.class); - } - - public ShapeOrNullDeserializer(Class vc) { - super(vc); - } - - @Override - public ShapeOrNull deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - Object deserialized = null; - ShapeOrNull newShapeOrNull = new ShapeOrNull(); - Map result2 = tree.traverse(jp.getCodec()).readValueAs(new TypeReference>() {}); - String discriminatorValue = (String)result2.get("shapeType"); - switch (discriminatorValue) { - case "Quadrilateral": - deserialized = tree.traverse(jp.getCodec()).readValueAs(Quadrilateral.class); - newShapeOrNull.setActualInstance(deserialized); - return newShapeOrNull; - case "Triangle": - deserialized = tree.traverse(jp.getCodec()).readValueAs(Triangle.class); - newShapeOrNull.setActualInstance(deserialized); - return newShapeOrNull; - default: - log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); - } - - boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); - int match = 0; - JsonToken token = tree.traverse(jp.getCodec()).nextToken(); - // deserialize Quadrilateral - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Quadrilateral.class.equals(Integer.class) || Quadrilateral.class.equals(Long.class) || Quadrilateral.class.equals(Float.class) || Quadrilateral.class.equals(Double.class) || Quadrilateral.class.equals(Boolean.class) || Quadrilateral.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Quadrilateral.class.equals(Integer.class) || Quadrilateral.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Quadrilateral.class.equals(Float.class) || Quadrilateral.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Quadrilateral.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Quadrilateral.class.equals(String.class) && token == JsonToken.VALUE_STRING); - attemptParsing |= (token == JsonToken.VALUE_NULL); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Quadrilateral.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Quadrilateral'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e); - } - - // deserialize Triangle - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (Triangle.class.equals(Integer.class) || Triangle.class.equals(Long.class) || Triangle.class.equals(Float.class) || Triangle.class.equals(Double.class) || Triangle.class.equals(Boolean.class) || Triangle.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((Triangle.class.equals(Integer.class) || Triangle.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((Triangle.class.equals(Float.class) || Triangle.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (Triangle.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (Triangle.class.equals(String.class) && token == JsonToken.VALUE_STRING); - attemptParsing |= (token == JsonToken.VALUE_NULL); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(Triangle.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'Triangle'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'Triangle'", e); - } - - if (match == 1) { - ShapeOrNull ret = new ShapeOrNull(); - ret.setActualInstance(deserialized); - return ret; - } - throw new IOException(String.format("Failed deserialization for ShapeOrNull: %d classes match result, expected 1", match)); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public ShapeOrNull getNullValue(DeserializationContext ctxt) throws JsonMappingException { - return null; - } - } - - // store a list of schema names defined in oneOf - public static final Map> schemas = new HashMap<>(); - - public ShapeOrNull() { - super("oneOf", Boolean.TRUE); - } - - public ShapeOrNull(Quadrilateral o) { - super("oneOf", Boolean.TRUE); - setActualInstance(o); - } - - public ShapeOrNull(Triangle o) { - super("oneOf", Boolean.TRUE); - setActualInstance(o); - } - - static { - schemas.put("Quadrilateral", Quadrilateral.class); - schemas.put("Triangle", Triangle.class); - JSON.registerDescendants(ShapeOrNull.class, Collections.unmodifiableMap(schemas)); - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("Quadrilateral", Quadrilateral.class); - mappings.put("Triangle", Triangle.class); - mappings.put("ShapeOrNull", ShapeOrNull.class); - JSON.registerDiscriminator(ShapeOrNull.class, "shapeType", mappings); - } - - @Override - public Map> getSchemas() { - return ShapeOrNull.schemas; - } - - /** - * Set the instance that matches the oneOf child schema, check - * the instance parameter is valid against the oneOf child schemas: - * Quadrilateral, Triangle - * - * It could be an instance of the 'oneOf' schemas. - * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). - */ - @Override - public void setActualInstance(Object instance) { - if (instance == null) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(Quadrilateral.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(Triangle.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Quadrilateral, Triangle"); - } - - /** - * Get the actual instance, which can be the following: - * Quadrilateral, Triangle - * - * @return The actual instance (Quadrilateral, Triangle) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `Quadrilateral`. If the actual instanct is not `Quadrilateral`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Quadrilateral` - * @throws ClassCastException if the instance is not `Quadrilateral` - */ - public Quadrilateral getQuadrilateral() throws ClassCastException { - return (Quadrilateral)super.getActualInstance(); - } - - /** - * Get the actual instance of `Triangle`. If the actual instanct is not `Triangle`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Triangle` - * @throws ClassCastException if the instance is not `Triangle` - */ - public Triangle getTriangle() throws ClassCastException { - return (Triangle)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java deleted file mode 100644 index a4eb641c0b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.QuadrilateralInterface; -import org.openapitools.client.model.ShapeInterface; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * SimpleQuadrilateral - */ -@JsonPropertyOrder({ - SimpleQuadrilateral.JSON_PROPERTY_SHAPE_TYPE, - SimpleQuadrilateral.JSON_PROPERTY_QUADRILATERAL_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class SimpleQuadrilateral { - public static final String JSON_PROPERTY_SHAPE_TYPE = "shapeType"; - private String shapeType; - - public static final String JSON_PROPERTY_QUADRILATERAL_TYPE = "quadrilateralType"; - private String quadrilateralType; - - - public SimpleQuadrilateral shapeType(String shapeType) { - this.shapeType = shapeType; - return this; - } - - /** - * Get shapeType - * @return shapeType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getShapeType() { - return shapeType; - } - - - @JsonProperty(JSON_PROPERTY_SHAPE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setShapeType(String shapeType) { - this.shapeType = shapeType; - } - - - public SimpleQuadrilateral quadrilateralType(String quadrilateralType) { - this.quadrilateralType = quadrilateralType; - return this; - } - - /** - * Get quadrilateralType - * @return quadrilateralType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_QUADRILATERAL_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getQuadrilateralType() { - return quadrilateralType; - } - - - @JsonProperty(JSON_PROPERTY_QUADRILATERAL_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setQuadrilateralType(String quadrilateralType) { - this.quadrilateralType = quadrilateralType; - } - - - /** - * Return true if this SimpleQuadrilateral object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SimpleQuadrilateral simpleQuadrilateral = (SimpleQuadrilateral) o; - return Objects.equals(this.shapeType, simpleQuadrilateral.shapeType) && - Objects.equals(this.quadrilateralType, simpleQuadrilateral.quadrilateralType); - } - - @Override - public int hashCode() { - return Objects.hash(shapeType, quadrilateralType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SimpleQuadrilateral {\n"); - sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); - sb.append(" quadrilateralType: ").append(toIndentedString(quadrilateralType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/SpecialModelName.java deleted file mode 100644 index 758ed1e21b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * SpecialModelName - */ -@JsonPropertyOrder({ - SpecialModelName.JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME, - SpecialModelName.JSON_PROPERTY_SPECIAL_MODEL_NAME -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class SpecialModelName { - public static final String JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; - private Long $specialPropertyName; - - public static final String JSON_PROPERTY_SPECIAL_MODEL_NAME = "_special_model.name_"; - private String specialModelName; - - - public SpecialModelName $specialPropertyName(Long $specialPropertyName) { - this.$specialPropertyName = $specialPropertyName; - return this; - } - - /** - * Get $specialPropertyName - * @return $specialPropertyName - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Long get$SpecialPropertyName() { - return $specialPropertyName; - } - - - @JsonProperty(JSON_PROPERTY_$_SPECIAL_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void set$SpecialPropertyName(Long $specialPropertyName) { - this.$specialPropertyName = $specialPropertyName; - } - - - public SpecialModelName specialModelName(String specialModelName) { - this.specialModelName = specialModelName; - return this; - } - - /** - * Get specialModelName - * @return specialModelName - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_SPECIAL_MODEL_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getSpecialModelName() { - return specialModelName; - } - - - @JsonProperty(JSON_PROPERTY_SPECIAL_MODEL_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setSpecialModelName(String specialModelName) { - this.specialModelName = specialModelName; - } - - - /** - * Return true if this _special_model.name_ object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SpecialModelName specialModelName = (SpecialModelName) o; - return Objects.equals(this.$specialPropertyName, specialModelName.$specialPropertyName) && - Objects.equals(this.specialModelName, specialModelName.specialModelName); - } - - @Override - public int hashCode() { - return Objects.hash($specialPropertyName, specialModelName); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SpecialModelName {\n"); - sb.append(" $specialPropertyName: ").append(toIndentedString($specialPropertyName)).append("\n"); - sb.append(" specialModelName: ").append(toIndentedString(specialModelName)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Tag.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Tag.java deleted file mode 100644 index d376bd2485..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Tag.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Tag - */ -@JsonPropertyOrder({ - Tag.JSON_PROPERTY_ID, - Tag.JSON_PROPERTY_NAME -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Tag { - public static final String JSON_PROPERTY_ID = "id"; - private Long id; - - public static final String JSON_PROPERTY_NAME = "name"; - private String name; - - - public Tag id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Long getId() { - return id; - } - - - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setId(Long id) { - this.id = id; - } - - - public Tag name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getName() { - return name; - } - - - @JsonProperty(JSON_PROPERTY_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setName(String name) { - this.name = name; - } - - - /** - * Return true if this Tag object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Tag tag = (Tag) o; - return Objects.equals(this.id, tag.id) && - Objects.equals(this.name, tag.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Tag {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Triangle.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Triangle.java deleted file mode 100644 index 073b1c351f..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Triangle.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.EquilateralTriangle; -import org.openapitools.client.model.IsoscelesTriangle; -import org.openapitools.client.model.ScaleneTriangle; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import com.fasterxml.jackson.core.type.TypeReference; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.openapitools.client.JSON; - -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -@JsonDeserialize(using = Triangle.TriangleDeserializer.class) -@JsonSerialize(using = Triangle.TriangleSerializer.class) -public class Triangle extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(Triangle.class.getName()); - - public static class TriangleSerializer extends StdSerializer { - public TriangleSerializer(Class t) { - super(t); - } - - public TriangleSerializer() { - this(null); - } - - @Override - public void serialize(Triangle value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeObject(value.getActualInstance()); - } - } - - public static class TriangleDeserializer extends StdDeserializer { - public TriangleDeserializer() { - this(Triangle.class); - } - - public TriangleDeserializer(Class vc) { - super(vc); - } - - @Override - public Triangle deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode tree = jp.readValueAsTree(); - Object deserialized = null; - Triangle newTriangle = new Triangle(); - Map result2 = tree.traverse(jp.getCodec()).readValueAs(new TypeReference>() {}); - String discriminatorValue = (String)result2.get("triangleType"); - switch (discriminatorValue) { - case "EquilateralTriangle": - deserialized = tree.traverse(jp.getCodec()).readValueAs(EquilateralTriangle.class); - newTriangle.setActualInstance(deserialized); - return newTriangle; - case "IsoscelesTriangle": - deserialized = tree.traverse(jp.getCodec()).readValueAs(IsoscelesTriangle.class); - newTriangle.setActualInstance(deserialized); - return newTriangle; - case "ScaleneTriangle": - deserialized = tree.traverse(jp.getCodec()).readValueAs(ScaleneTriangle.class); - newTriangle.setActualInstance(deserialized); - return newTriangle; - default: - log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); - } - - boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); - int match = 0; - JsonToken token = tree.traverse(jp.getCodec()).nextToken(); - // deserialize EquilateralTriangle - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (EquilateralTriangle.class.equals(Integer.class) || EquilateralTriangle.class.equals(Long.class) || EquilateralTriangle.class.equals(Float.class) || EquilateralTriangle.class.equals(Double.class) || EquilateralTriangle.class.equals(Boolean.class) || EquilateralTriangle.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((EquilateralTriangle.class.equals(Integer.class) || EquilateralTriangle.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((EquilateralTriangle.class.equals(Float.class) || EquilateralTriangle.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (EquilateralTriangle.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (EquilateralTriangle.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(EquilateralTriangle.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'EquilateralTriangle'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'EquilateralTriangle'", e); - } - - // deserialize IsoscelesTriangle - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (IsoscelesTriangle.class.equals(Integer.class) || IsoscelesTriangle.class.equals(Long.class) || IsoscelesTriangle.class.equals(Float.class) || IsoscelesTriangle.class.equals(Double.class) || IsoscelesTriangle.class.equals(Boolean.class) || IsoscelesTriangle.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((IsoscelesTriangle.class.equals(Integer.class) || IsoscelesTriangle.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((IsoscelesTriangle.class.equals(Float.class) || IsoscelesTriangle.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (IsoscelesTriangle.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (IsoscelesTriangle.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(IsoscelesTriangle.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'IsoscelesTriangle'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'IsoscelesTriangle'", e); - } - - // deserialize ScaleneTriangle - try { - boolean attemptParsing = true; - // ensure that we respect type coercion as set on the client ObjectMapper - if (ScaleneTriangle.class.equals(Integer.class) || ScaleneTriangle.class.equals(Long.class) || ScaleneTriangle.class.equals(Float.class) || ScaleneTriangle.class.equals(Double.class) || ScaleneTriangle.class.equals(Boolean.class) || ScaleneTriangle.class.equals(String.class)) { - attemptParsing = typeCoercion; - if (!attemptParsing) { - attemptParsing |= ((ScaleneTriangle.class.equals(Integer.class) || ScaleneTriangle.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); - attemptParsing |= ((ScaleneTriangle.class.equals(Float.class) || ScaleneTriangle.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); - attemptParsing |= (ScaleneTriangle.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); - attemptParsing |= (ScaleneTriangle.class.equals(String.class) && token == JsonToken.VALUE_STRING); - } - } - if (attemptParsing) { - deserialized = tree.traverse(jp.getCodec()).readValueAs(ScaleneTriangle.class); - // TODO: there is no validation against JSON schema constraints - // (min, max, enum, pattern...), this does not perform a strict JSON - // validation, which means the 'match' count may be higher than it should be. - match++; - log.log(Level.FINER, "Input data matches schema 'ScaleneTriangle'"); - } - } catch (Exception e) { - // deserialization failed, continue - log.log(Level.FINER, "Input data does not match schema 'ScaleneTriangle'", e); - } - - if (match == 1) { - Triangle ret = new Triangle(); - ret.setActualInstance(deserialized); - return ret; - } - throw new IOException(String.format("Failed deserialization for Triangle: %d classes match result, expected 1", match)); - } - - /** - * Handle deserialization of the 'null' value. - */ - @Override - public Triangle getNullValue(DeserializationContext ctxt) throws JsonMappingException { - throw new JsonMappingException(ctxt.getParser(), "Triangle cannot be null"); - } - } - - // store a list of schema names defined in oneOf - public static final Map> schemas = new HashMap<>(); - - public Triangle() { - super("oneOf", Boolean.FALSE); - } - - public Triangle(EquilateralTriangle o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - public Triangle(IsoscelesTriangle o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - public Triangle(ScaleneTriangle o) { - super("oneOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("EquilateralTriangle", EquilateralTriangle.class); - schemas.put("IsoscelesTriangle", IsoscelesTriangle.class); - schemas.put("ScaleneTriangle", ScaleneTriangle.class); - JSON.registerDescendants(Triangle.class, Collections.unmodifiableMap(schemas)); - // Initialize and register the discriminator mappings. - Map> mappings = new HashMap>(); - mappings.put("EquilateralTriangle", EquilateralTriangle.class); - mappings.put("IsoscelesTriangle", IsoscelesTriangle.class); - mappings.put("ScaleneTriangle", ScaleneTriangle.class); - mappings.put("Triangle", Triangle.class); - JSON.registerDiscriminator(Triangle.class, "triangleType", mappings); - } - - @Override - public Map> getSchemas() { - return Triangle.schemas; - } - - /** - * Set the instance that matches the oneOf child schema, check - * the instance parameter is valid against the oneOf child schemas: - * EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle - * - * It could be an instance of the 'oneOf' schemas. - * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). - */ - @Override - public void setActualInstance(Object instance) { - if (JSON.isInstanceOf(EquilateralTriangle.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(IsoscelesTriangle.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - if (JSON.isInstanceOf(ScaleneTriangle.class, instance, new HashSet>())) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle"); - } - - /** - * Get the actual instance, which can be the following: - * EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle - * - * @return The actual instance (EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle) - */ - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `EquilateralTriangle`. If the actual instanct is not `EquilateralTriangle`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `EquilateralTriangle` - * @throws ClassCastException if the instance is not `EquilateralTriangle` - */ - public EquilateralTriangle getEquilateralTriangle() throws ClassCastException { - return (EquilateralTriangle)super.getActualInstance(); - } - - /** - * Get the actual instance of `IsoscelesTriangle`. If the actual instanct is not `IsoscelesTriangle`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `IsoscelesTriangle` - * @throws ClassCastException if the instance is not `IsoscelesTriangle` - */ - public IsoscelesTriangle getIsoscelesTriangle() throws ClassCastException { - return (IsoscelesTriangle)super.getActualInstance(); - } - - /** - * Get the actual instance of `ScaleneTriangle`. If the actual instanct is not `ScaleneTriangle`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `ScaleneTriangle` - * @throws ClassCastException if the instance is not `ScaleneTriangle` - */ - public ScaleneTriangle getScaleneTriangle() throws ClassCastException { - return (ScaleneTriangle)super.getActualInstance(); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/TriangleInterface.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/TriangleInterface.java deleted file mode 100644 index 12a16bd967..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/TriangleInterface.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * TriangleInterface - */ -@JsonPropertyOrder({ - TriangleInterface.JSON_PROPERTY_TRIANGLE_TYPE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class TriangleInterface { - public static final String JSON_PROPERTY_TRIANGLE_TYPE = "triangleType"; - private String triangleType; - - - public TriangleInterface triangleType(String triangleType) { - this.triangleType = triangleType; - return this; - } - - /** - * Get triangleType - * @return triangleType - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_TRIANGLE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getTriangleType() { - return triangleType; - } - - - @JsonProperty(JSON_PROPERTY_TRIANGLE_TYPE) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setTriangleType(String triangleType) { - this.triangleType = triangleType; - } - - - /** - * Return true if this TriangleInterface object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - TriangleInterface triangleInterface = (TriangleInterface) o; - return Objects.equals(this.triangleType, triangleInterface.triangleType); - } - - @Override - public int hashCode() { - return Objects.hash(triangleType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class TriangleInterface {\n"); - sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/User.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/User.java deleted file mode 100644 index a591269f00..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/User.java +++ /dev/null @@ -1,488 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * User - */ -@JsonPropertyOrder({ - User.JSON_PROPERTY_ID, - User.JSON_PROPERTY_USERNAME, - User.JSON_PROPERTY_FIRST_NAME, - User.JSON_PROPERTY_LAST_NAME, - User.JSON_PROPERTY_EMAIL, - User.JSON_PROPERTY_PASSWORD, - User.JSON_PROPERTY_PHONE, - User.JSON_PROPERTY_USER_STATUS, - User.JSON_PROPERTY_OBJECT_WITH_NO_DECLARED_PROPS, - User.JSON_PROPERTY_OBJECT_WITH_NO_DECLARED_PROPS_NULLABLE, - User.JSON_PROPERTY_ANY_TYPE_PROP, - User.JSON_PROPERTY_ANY_TYPE_PROP_NULLABLE -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class User { - public static final String JSON_PROPERTY_ID = "id"; - private Long id; - - public static final String JSON_PROPERTY_USERNAME = "username"; - private String username; - - public static final String JSON_PROPERTY_FIRST_NAME = "firstName"; - private String firstName; - - public static final String JSON_PROPERTY_LAST_NAME = "lastName"; - private String lastName; - - public static final String JSON_PROPERTY_EMAIL = "email"; - private String email; - - public static final String JSON_PROPERTY_PASSWORD = "password"; - private String password; - - public static final String JSON_PROPERTY_PHONE = "phone"; - private String phone; - - public static final String JSON_PROPERTY_USER_STATUS = "userStatus"; - private Integer userStatus; - - public static final String JSON_PROPERTY_OBJECT_WITH_NO_DECLARED_PROPS = "objectWithNoDeclaredProps"; - private Object objectWithNoDeclaredProps; - - public static final String JSON_PROPERTY_OBJECT_WITH_NO_DECLARED_PROPS_NULLABLE = "objectWithNoDeclaredPropsNullable"; - private JsonNullable objectWithNoDeclaredPropsNullable = JsonNullable.undefined(); - - public static final String JSON_PROPERTY_ANY_TYPE_PROP = "anyTypeProp"; - private JsonNullable anyTypeProp = JsonNullable.of(null); - - public static final String JSON_PROPERTY_ANY_TYPE_PROP_NULLABLE = "anyTypePropNullable"; - private JsonNullable anyTypePropNullable = JsonNullable.of(null); - - - public User id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Long getId() { - return id; - } - - - @JsonProperty(JSON_PROPERTY_ID) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setId(Long id) { - this.id = id; - } - - - public User username(String username) { - this.username = username; - return this; - } - - /** - * Get username - * @return username - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_USERNAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getUsername() { - return username; - } - - - @JsonProperty(JSON_PROPERTY_USERNAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setUsername(String username) { - this.username = username; - } - - - public User firstName(String firstName) { - this.firstName = firstName; - return this; - } - - /** - * Get firstName - * @return firstName - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_FIRST_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getFirstName() { - return firstName; - } - - - @JsonProperty(JSON_PROPERTY_FIRST_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - - public User lastName(String lastName) { - this.lastName = lastName; - return this; - } - - /** - * Get lastName - * @return lastName - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_LAST_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getLastName() { - return lastName; - } - - - @JsonProperty(JSON_PROPERTY_LAST_NAME) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setLastName(String lastName) { - this.lastName = lastName; - } - - - public User email(String email) { - this.email = email; - return this; - } - - /** - * Get email - * @return email - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_EMAIL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getEmail() { - return email; - } - - - @JsonProperty(JSON_PROPERTY_EMAIL) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setEmail(String email) { - this.email = email; - } - - - public User password(String password) { - this.password = password; - return this; - } - - /** - * Get password - * @return password - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_PASSWORD) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getPassword() { - return password; - } - - - @JsonProperty(JSON_PROPERTY_PASSWORD) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setPassword(String password) { - this.password = password; - } - - - public User phone(String phone) { - this.phone = phone; - return this; - } - - /** - * Get phone - * @return phone - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_PHONE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public String getPhone() { - return phone; - } - - - @JsonProperty(JSON_PROPERTY_PHONE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setPhone(String phone) { - this.phone = phone; - } - - - public User userStatus(Integer userStatus) { - this.userStatus = userStatus; - return this; - } - - /** - * User Status - * @return userStatus - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "User Status") - @JsonProperty(JSON_PROPERTY_USER_STATUS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Integer getUserStatus() { - return userStatus; - } - - - @JsonProperty(JSON_PROPERTY_USER_STATUS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - - - public User objectWithNoDeclaredProps(Object objectWithNoDeclaredProps) { - this.objectWithNoDeclaredProps = objectWithNoDeclaredProps; - return this; - } - - /** - * test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. - * @return objectWithNoDeclaredProps - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value.") - @JsonProperty(JSON_PROPERTY_OBJECT_WITH_NO_DECLARED_PROPS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Object getObjectWithNoDeclaredProps() { - return objectWithNoDeclaredProps; - } - - - @JsonProperty(JSON_PROPERTY_OBJECT_WITH_NO_DECLARED_PROPS) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setObjectWithNoDeclaredProps(Object objectWithNoDeclaredProps) { - this.objectWithNoDeclaredProps = objectWithNoDeclaredProps; - } - - - public User objectWithNoDeclaredPropsNullable(Object objectWithNoDeclaredPropsNullable) { - this.objectWithNoDeclaredPropsNullable = JsonNullable.of(objectWithNoDeclaredPropsNullable); - return this; - } - - /** - * test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. - * @return objectWithNoDeclaredPropsNullable - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "test code generation for nullable objects. Value must be a map of strings to values or the 'null' value.") - @JsonIgnore - - public Object getObjectWithNoDeclaredPropsNullable() { - return objectWithNoDeclaredPropsNullable.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_OBJECT_WITH_NO_DECLARED_PROPS_NULLABLE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getObjectWithNoDeclaredPropsNullable_JsonNullable() { - return objectWithNoDeclaredPropsNullable; - } - - @JsonProperty(JSON_PROPERTY_OBJECT_WITH_NO_DECLARED_PROPS_NULLABLE) - public void setObjectWithNoDeclaredPropsNullable_JsonNullable(JsonNullable objectWithNoDeclaredPropsNullable) { - this.objectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; - } - - public void setObjectWithNoDeclaredPropsNullable(Object objectWithNoDeclaredPropsNullable) { - this.objectWithNoDeclaredPropsNullable = JsonNullable.of(objectWithNoDeclaredPropsNullable); - } - - - public User anyTypeProp(Object anyTypeProp) { - this.anyTypeProp = JsonNullable.of(anyTypeProp); - return this; - } - - /** - * test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - * @return anyTypeProp - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389") - @JsonIgnore - - public Object getAnyTypeProp() { - return anyTypeProp.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_ANY_TYPE_PROP) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getAnyTypeProp_JsonNullable() { - return anyTypeProp; - } - - @JsonProperty(JSON_PROPERTY_ANY_TYPE_PROP) - public void setAnyTypeProp_JsonNullable(JsonNullable anyTypeProp) { - this.anyTypeProp = anyTypeProp; - } - - public void setAnyTypeProp(Object anyTypeProp) { - this.anyTypeProp = JsonNullable.of(anyTypeProp); - } - - - public User anyTypePropNullable(Object anyTypePropNullable) { - this.anyTypePropNullable = JsonNullable.of(anyTypePropNullable); - return this; - } - - /** - * test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. - * @return anyTypePropNullable - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values.") - @JsonIgnore - - public Object getAnyTypePropNullable() { - return anyTypePropNullable.orElse(null); - } - - @JsonProperty(JSON_PROPERTY_ANY_TYPE_PROP_NULLABLE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public JsonNullable getAnyTypePropNullable_JsonNullable() { - return anyTypePropNullable; - } - - @JsonProperty(JSON_PROPERTY_ANY_TYPE_PROP_NULLABLE) - public void setAnyTypePropNullable_JsonNullable(JsonNullable anyTypePropNullable) { - this.anyTypePropNullable = anyTypePropNullable; - } - - public void setAnyTypePropNullable(Object anyTypePropNullable) { - this.anyTypePropNullable = JsonNullable.of(anyTypePropNullable); - } - - - /** - * Return true if this User object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - User user = (User) o; - return Objects.equals(this.id, user.id) && - Objects.equals(this.username, user.username) && - Objects.equals(this.firstName, user.firstName) && - Objects.equals(this.lastName, user.lastName) && - Objects.equals(this.email, user.email) && - Objects.equals(this.password, user.password) && - Objects.equals(this.phone, user.phone) && - Objects.equals(this.userStatus, user.userStatus) && - Objects.equals(this.objectWithNoDeclaredProps, user.objectWithNoDeclaredProps) && - Objects.equals(this.objectWithNoDeclaredPropsNullable, user.objectWithNoDeclaredPropsNullable) && - Objects.equals(this.anyTypeProp, user.anyTypeProp) && - Objects.equals(this.anyTypePropNullable, user.anyTypePropNullable); - } - - @Override - public int hashCode() { - return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus, objectWithNoDeclaredProps, objectWithNoDeclaredPropsNullable, anyTypeProp, anyTypePropNullable); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class User {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" username: ").append(toIndentedString(username)).append("\n"); - sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); - sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); - sb.append(" email: ").append(toIndentedString(email)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); - sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); - sb.append(" objectWithNoDeclaredProps: ").append(toIndentedString(objectWithNoDeclaredProps)).append("\n"); - sb.append(" objectWithNoDeclaredPropsNullable: ").append(toIndentedString(objectWithNoDeclaredPropsNullable)).append("\n"); - sb.append(" anyTypeProp: ").append(toIndentedString(anyTypeProp)).append("\n"); - sb.append(" anyTypePropNullable: ").append(toIndentedString(anyTypePropNullable)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Whale.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Whale.java deleted file mode 100644 index 7343f40123..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Whale.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Whale - */ -@JsonPropertyOrder({ - Whale.JSON_PROPERTY_HAS_BALEEN, - Whale.JSON_PROPERTY_HAS_TEETH, - Whale.JSON_PROPERTY_CLASS_NAME -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Whale { - public static final String JSON_PROPERTY_HAS_BALEEN = "hasBaleen"; - private Boolean hasBaleen; - - public static final String JSON_PROPERTY_HAS_TEETH = "hasTeeth"; - private Boolean hasTeeth; - - public static final String JSON_PROPERTY_CLASS_NAME = "className"; - private String className; - - - public Whale hasBaleen(Boolean hasBaleen) { - this.hasBaleen = hasBaleen; - return this; - } - - /** - * Get hasBaleen - * @return hasBaleen - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_HAS_BALEEN) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Boolean getHasBaleen() { - return hasBaleen; - } - - - @JsonProperty(JSON_PROPERTY_HAS_BALEEN) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setHasBaleen(Boolean hasBaleen) { - this.hasBaleen = hasBaleen; - } - - - public Whale hasTeeth(Boolean hasTeeth) { - this.hasTeeth = hasTeeth; - return this; - } - - /** - * Get hasTeeth - * @return hasTeeth - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_HAS_TEETH) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public Boolean getHasTeeth() { - return hasTeeth; - } - - - @JsonProperty(JSON_PROPERTY_HAS_TEETH) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setHasTeeth(Boolean hasTeeth) { - this.hasTeeth = hasTeeth; - } - - - public Whale className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getClassName() { - return className; - } - - - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setClassName(String className) { - this.className = className; - } - - - /** - * Return true if this whale object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Whale whale = (Whale) o; - return Objects.equals(this.hasBaleen, whale.hasBaleen) && - Objects.equals(this.hasTeeth, whale.hasTeeth) && - Objects.equals(this.className, whale.className); - } - - @Override - public int hashCode() { - return Objects.hash(hasBaleen, hasTeeth, className); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Whale {\n"); - sb.append(" hasBaleen: ").append(toIndentedString(hasBaleen)).append("\n"); - sb.append(" hasTeeth: ").append(toIndentedString(hasTeeth)).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Zebra.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Zebra.java deleted file mode 100644 index fc19f618cb..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Zebra.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import java.util.Objects; -import java.util.Arrays; -import java.util.Map; -import java.util.HashMap; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.Map; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - - -/** - * Zebra - */ -@JsonPropertyOrder({ - Zebra.JSON_PROPERTY_TYPE, - Zebra.JSON_PROPERTY_CLASS_NAME -}) -@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class Zebra extends HashMap { - /** - * Gets or Sets type - */ - public enum TypeEnum { - PLAINS("plains"), - - MOUNTAIN("mountain"), - - GREVYS("grevys"); - - private String value; - - TypeEnum(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static TypeEnum fromValue(String value) { - for (TypeEnum b : TypeEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - } - - public static final String JSON_PROPERTY_TYPE = "type"; - private TypeEnum type; - - public static final String JSON_PROPERTY_CLASS_NAME = "className"; - private String className; - - - public Zebra type(TypeEnum type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - @JsonProperty(JSON_PROPERTY_TYPE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - - public TypeEnum getType() { - return type; - } - - - @JsonProperty(JSON_PROPERTY_TYPE) - @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setType(TypeEnum type) { - this.type = type; - } - - - public Zebra className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @javax.annotation.Nonnull - @ApiModelProperty(required = true, value = "") - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - - public String getClassName() { - return className; - } - - - @JsonProperty(JSON_PROPERTY_CLASS_NAME) - @JsonInclude(value = JsonInclude.Include.ALWAYS) - public void setClassName(String className) { - this.className = className; - } - - /** - * A container for additional, undeclared properties. - * This is a holder for any undeclared properties as specified with - * the 'additionalProperties' keyword in the OAS document. - */ - private Map additionalProperties; - - /** - * Set the additional (undeclared) property with the specified name and value. - * If the property does not already exist, create it otherwise replace it. - */ - @JsonAnySetter - public Zebra putAdditionalProperty(String key, Object value) { - if (this.additionalProperties == null) { - this.additionalProperties = new HashMap(); - } - this.additionalProperties.put(key, value); - return this; - } - - /** - * Return the additional (undeclared) property. - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return additionalProperties; - } - - /** - * Return the additional (undeclared) property with the specified name. - */ - public Object getAdditionalProperty(String key) { - if (this.additionalProperties == null) { - return null; - } - return this.additionalProperties.get(key); - } - - /** - * Return true if this zebra object is equal to o. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Zebra zebra = (Zebra) o; - return Objects.equals(this.type, zebra.type) && - Objects.equals(this.className, zebra.className)&& - Objects.equals(this.additionalProperties, zebra.additionalProperties) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(type, className, super.hashCode(), additionalProperties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Zebra {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} - diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java deleted file mode 100644 index 23e59ea2b2..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.api; - -import org.openapitools.client.ApiException; -import org.openapitools.client.model.Client; -import org.junit.Test; -import org.junit.Ignore; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * API tests for AnotherFakeApi - */ -@Ignore -public class AnotherFakeApiTest { - - private final AnotherFakeApi api = new AnotherFakeApi(); - - - /** - * To test special tags - * - * To test special tags and operation ID starting with number - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void call123testSpecialTagsTest() throws ApiException { - Client client = null; - Client response = - api.call123testSpecialTags(client); - - // TODO: test validations - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/DefaultApiTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/DefaultApiTest.java deleted file mode 100644 index f4b84040f3..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/DefaultApiTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.api; - -import org.openapitools.client.ApiException; -import org.openapitools.client.model.InlineResponseDefault; -import org.junit.Test; -import org.junit.Ignore; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * API tests for DefaultApi - */ -@Ignore -public class DefaultApiTest { - - private final DefaultApi api = new DefaultApi(); - - - /** - * - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void fooGetTest() throws ApiException { - InlineResponseDefault response = - api.fooGet(); - - // TODO: test validations - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/FakeApiTest.java deleted file mode 100644 index 22b3216475..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/FakeApiTest.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.api; - -import org.openapitools.client.ApiException; -import java.math.BigDecimal; -import org.openapitools.client.model.Client; -import java.io.File; -import org.openapitools.client.model.FileSchemaTestClass; -import org.openapitools.client.model.HealthCheckResult; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import org.openapitools.client.model.OuterComposite; -import org.openapitools.client.model.OuterEnum; -import org.openapitools.client.model.User; -import org.junit.Test; -import org.junit.Ignore; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * API tests for FakeApi - */ -@Ignore -public class FakeApiTest { - - private final FakeApi api = new FakeApi(); - - - /** - * Health check endpoint - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void fakeHealthGetTest() throws ApiException { - HealthCheckResult response = - api.fakeHealthGet(); - - // TODO: test validations - } - - /** - * - * - * Test serialization of outer boolean types - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void fakeOuterBooleanSerializeTest() throws ApiException { - Boolean body = null; - Boolean response = - api.fakeOuterBooleanSerialize(body); - - // TODO: test validations - } - - /** - * - * - * Test serialization of object with outer number type - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void fakeOuterCompositeSerializeTest() throws ApiException { - OuterComposite outerComposite = null; - OuterComposite response = - api.fakeOuterCompositeSerialize(outerComposite); - - // TODO: test validations - } - - /** - * - * - * Test serialization of outer number types - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void fakeOuterNumberSerializeTest() throws ApiException { - BigDecimal body = null; - BigDecimal response = - api.fakeOuterNumberSerialize(body); - - // TODO: test validations - } - - /** - * - * - * Test serialization of outer string types - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void fakeOuterStringSerializeTest() throws ApiException { - String body = null; - String response = - api.fakeOuterStringSerialize(body); - - // TODO: test validations - } - - /** - * Array of Enums - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void getArrayOfEnumsTest() throws ApiException { - List response = - api.getArrayOfEnums(); - - // TODO: test validations - } - - /** - * - * - * For this test, the body for this request much reference a schema named `File`. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testBodyWithFileSchemaTest() throws ApiException { - FileSchemaTestClass fileSchemaTestClass = null; - - api.testBodyWithFileSchema(fileSchemaTestClass); - - // TODO: test validations - } - - /** - * - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testBodyWithQueryParamsTest() throws ApiException { - String query = null; - User user = null; - - api.testBodyWithQueryParams(query, user); - - // TODO: test validations - } - - /** - * To test \"client\" model - * - * To test \"client\" model - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testClientModelTest() throws ApiException { - Client client = null; - Client response = - api.testClientModel(client); - - // TODO: test validations - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testEndpointParametersTest() throws ApiException { - BigDecimal number = null; - Double _double = null; - String patternWithoutDelimiter = null; - byte[] _byte = null; - Integer integer = null; - Integer int32 = null; - Long int64 = null; - Float _float = null; - String string = null; - File binary = null; - LocalDate date = null; - OffsetDateTime dateTime = null; - String password = null; - String paramCallback = null; - - api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - - // TODO: test validations - } - - /** - * To test enum parameters - * - * To test enum parameters - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testEnumParametersTest() throws ApiException { - List enumHeaderStringArray = null; - String enumHeaderString = null; - List enumQueryStringArray = null; - String enumQueryString = null; - Integer enumQueryInteger = null; - Double enumQueryDouble = null; - List enumFormStringArray = null; - String enumFormString = null; - - api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); - - // TODO: test validations - } - - /** - * Fake endpoint to test group parameters (optional) - * - * Fake endpoint to test group parameters (optional) - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testGroupParametersTest() throws ApiException { - Integer requiredStringGroup = null; - Boolean requiredBooleanGroup = null; - Long requiredInt64Group = null; - Integer stringGroup = null; - Boolean booleanGroup = null; - Long int64Group = null; - - FakeApi.APItestGroupParametersRequest request = FakeApi.APItestGroupParametersRequest.newBuilder() - .requiredStringGroup(requiredStringGroup) - .requiredBooleanGroup(requiredBooleanGroup) - .requiredInt64Group(requiredInt64Group) - .stringGroup(stringGroup) - .booleanGroup(booleanGroup) - .int64Group(int64Group) - .build(); - - api.testGroupParameters(request); - - // TODO: test validations - } - - /** - * test inline additionalProperties - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testInlineAdditionalPropertiesTest() throws ApiException { - Map requestBody = null; - - api.testInlineAdditionalProperties(requestBody); - - // TODO: test validations - } - - /** - * test json serialization of form data - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testJsonFormDataTest() throws ApiException { - String param = null; - String param2 = null; - - api.testJsonFormData(param, param2); - - // TODO: test validations - } - - /** - * - * - * To test the collection format in query parameters - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testQueryParameterCollectionFormatTest() throws ApiException { - List pipe = null; - List ioutil = null; - List http = null; - List url = null; - List context = null; - - api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); - - // TODO: test validations - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java deleted file mode 100644 index 68589bc482..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.api; - -import org.openapitools.client.ApiException; -import org.openapitools.client.model.Client; -import org.junit.Test; -import org.junit.Ignore; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * API tests for FakeClassnameTags123Api - */ -@Ignore -public class FakeClassnameTags123ApiTest { - - private final FakeClassnameTags123Api api = new FakeClassnameTags123Api(); - - - /** - * To test class name in snake case - * - * To test class name in snake case - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testClassnameTest() throws ApiException { - Client client = null; - Client response = - api.testClassname(client); - - // TODO: test validations - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/PetApiTest.java deleted file mode 100644 index 08c2c113fa..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/PetApiTest.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.api; - -import org.openapitools.client.ApiException; -import java.io.File; -import org.openapitools.client.model.ModelApiResponse; -import org.openapitools.client.model.Pet; -import org.junit.Test; -import org.junit.Ignore; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * API tests for PetApi - */ -@Ignore -public class PetApiTest { - - private final PetApi api = new PetApi(); - - - /** - * Add a new pet to the store - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void addPetTest() throws ApiException { - Pet pet = null; - - api.addPet(pet); - - // TODO: test validations - } - - /** - * Deletes a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deletePetTest() throws ApiException { - Long petId = null; - String apiKey = null; - - api.deletePet(petId, apiKey); - - // TODO: test validations - } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void findPetsByStatusTest() throws ApiException { - List status = null; - List response = - api.findPetsByStatus(status); - - // TODO: test validations - } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void findPetsByTagsTest() throws ApiException { - List tags = null; - List response = - api.findPetsByTags(tags); - - // TODO: test validations - } - - /** - * Find pet by ID - * - * Returns a single pet - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void getPetByIdTest() throws ApiException { - Long petId = null; - Pet response = - api.getPetById(petId); - - // TODO: test validations - } - - /** - * Update an existing pet - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void updatePetTest() throws ApiException { - Pet pet = null; - - api.updatePet(pet); - - // TODO: test validations - } - - /** - * Updates a pet in the store with form data - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void updatePetWithFormTest() throws ApiException { - Long petId = null; - String name = null; - String status = null; - - api.updatePetWithForm(petId, name, status); - - // TODO: test validations - } - - /** - * uploads an image - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void uploadFileTest() throws ApiException { - Long petId = null; - String additionalMetadata = null; - File file = null; - ModelApiResponse response = - api.uploadFile(petId, additionalMetadata, file); - - // TODO: test validations - } - - /** - * uploads an image (required) - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void uploadFileWithRequiredFileTest() throws ApiException { - Long petId = null; - File requiredFile = null; - String additionalMetadata = null; - ModelApiResponse response = - api.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); - - // TODO: test validations - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/StoreApiTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/StoreApiTest.java deleted file mode 100644 index df23a79994..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/StoreApiTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.api; - -import org.openapitools.client.ApiException; -import org.openapitools.client.model.Order; -import org.junit.Test; -import org.junit.Ignore; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * API tests for StoreApi - */ -@Ignore -public class StoreApiTest { - - private final StoreApi api = new StoreApi(); - - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteOrderTest() throws ApiException { - String orderId = null; - - api.deleteOrder(orderId); - - // TODO: test validations - } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void getInventoryTest() throws ApiException { - Map response = - api.getInventory(); - - // TODO: test validations - } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void getOrderByIdTest() throws ApiException { - Long orderId = null; - Order response = - api.getOrderById(orderId); - - // TODO: test validations - } - - /** - * Place an order for a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void placeOrderTest() throws ApiException { - Order order = null; - Order response = - api.placeOrder(order); - - // TODO: test validations - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/UserApiTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/UserApiTest.java deleted file mode 100644 index 0f6416aac5..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/api/UserApiTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.api; - -import org.openapitools.client.ApiException; -import org.openapitools.client.model.User; -import org.junit.Test; -import org.junit.Ignore; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * API tests for UserApi - */ -@Ignore -public class UserApiTest { - - private final UserApi api = new UserApi(); - - - /** - * Create user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUserTest() throws ApiException { - User user = null; - - api.createUser(user); - - // TODO: test validations - } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUsersWithArrayInputTest() throws ApiException { - List user = null; - - api.createUsersWithArrayInput(user); - - // TODO: test validations - } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUsersWithListInputTest() throws ApiException { - List user = null; - - api.createUsersWithListInput(user); - - // TODO: test validations - } - - /** - * Delete user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteUserTest() throws ApiException { - String username = null; - - api.deleteUser(username); - - // TODO: test validations - } - - /** - * Get user by user name - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void getUserByNameTest() throws ApiException { - String username = null; - User response = - api.getUserByName(username); - - // TODO: test validations - } - - /** - * Logs user into the system - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void loginUserTest() throws ApiException { - String username = null; - String password = null; - String response = - api.loginUser(username, password); - - // TODO: test validations - } - - /** - * Logs out current logged in user session - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void logoutUserTest() throws ApiException { - - api.logoutUser(); - - // TODO: test validations - } - - /** - * Updated user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void updateUserTest() throws ApiException { - String username = null; - User user = null; - - api.updateUser(username, user); - - // TODO: test validations - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java deleted file mode 100644 index 048f375167..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for AdditionalPropertiesClass - */ -public class AdditionalPropertiesClassTest { - private final AdditionalPropertiesClass model = new AdditionalPropertiesClass(); - - /** - * Model tests for AdditionalPropertiesClass - */ - @Test - public void testAdditionalPropertiesClass() { - // TODO: test AdditionalPropertiesClass - } - - /** - * Test the property 'mapProperty' - */ - @Test - public void mapPropertyTest() { - // TODO: test mapProperty - } - - /** - * Test the property 'mapOfMapProperty' - */ - @Test - public void mapOfMapPropertyTest() { - // TODO: test mapOfMapProperty - } - - /** - * Test the property 'anytype1' - */ - @Test - public void anytype1Test() { - // TODO: test anytype1 - } - - /** - * Test the property 'mapWithUndeclaredPropertiesAnytype1' - */ - @Test - public void mapWithUndeclaredPropertiesAnytype1Test() { - // TODO: test mapWithUndeclaredPropertiesAnytype1 - } - - /** - * Test the property 'mapWithUndeclaredPropertiesAnytype2' - */ - @Test - public void mapWithUndeclaredPropertiesAnytype2Test() { - // TODO: test mapWithUndeclaredPropertiesAnytype2 - } - - /** - * Test the property 'mapWithUndeclaredPropertiesAnytype3' - */ - @Test - public void mapWithUndeclaredPropertiesAnytype3Test() { - // TODO: test mapWithUndeclaredPropertiesAnytype3 - } - - /** - * Test the property 'emptyMap' - */ - @Test - public void emptyMapTest() { - // TODO: test emptyMap - } - - /** - * Test the property 'mapWithUndeclaredPropertiesString' - */ - @Test - public void mapWithUndeclaredPropertiesStringTest() { - // TODO: test mapWithUndeclaredPropertiesString - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AnimalTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AnimalTest.java deleted file mode 100644 index ccbffdf2b2..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AnimalTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Cat; -import org.openapitools.client.model.Dog; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Animal - */ -public class AnimalTest { - private final Animal model = new Animal(); - - /** - * Model tests for Animal - */ - @Test - public void testAnimal() { - // TODO: test Animal - } - - /** - * Test the property 'className' - */ - @Test - public void classNameTest() { - // TODO: test className - } - - /** - * Test the property 'color' - */ - @Test - public void colorTest() { - // TODO: test color - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AppleReqTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AppleReqTest.java deleted file mode 100644 index 896ef7f65f..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AppleReqTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for AppleReq - */ -public class AppleReqTest { - private final AppleReq model = new AppleReq(); - - /** - * Model tests for AppleReq - */ - @Test - public void testAppleReq() { - // TODO: test AppleReq - } - - /** - * Test the property 'cultivar' - */ - @Test - public void cultivarTest() { - // TODO: test cultivar - } - - /** - * Test the property 'mealy' - */ - @Test - public void mealyTest() { - // TODO: test mealy - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AppleTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AppleTest.java deleted file mode 100644 index 98f2c81089..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/AppleTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Apple - */ -public class AppleTest { - private final Apple model = new Apple(); - - /** - * Model tests for Apple - */ - @Test - public void testApple() { - // TODO: test Apple - } - - /** - * Test the property 'cultivar' - */ - @Test - public void cultivarTest() { - // TODO: test cultivar - } - - /** - * Test the property 'origin' - */ - @Test - public void originTest() { - // TODO: test origin - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java deleted file mode 100644 index 928e297399..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ArrayOfArrayOfNumberOnly - */ -public class ArrayOfArrayOfNumberOnlyTest { - private final ArrayOfArrayOfNumberOnly model = new ArrayOfArrayOfNumberOnly(); - - /** - * Model tests for ArrayOfArrayOfNumberOnly - */ - @Test - public void testArrayOfArrayOfNumberOnly() { - // TODO: test ArrayOfArrayOfNumberOnly - } - - /** - * Test the property 'arrayArrayNumber' - */ - @Test - public void arrayArrayNumberTest() { - // TODO: test arrayArrayNumber - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java deleted file mode 100644 index 0c02796dc7..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ArrayOfNumberOnly - */ -public class ArrayOfNumberOnlyTest { - private final ArrayOfNumberOnly model = new ArrayOfNumberOnly(); - - /** - * Model tests for ArrayOfNumberOnly - */ - @Test - public void testArrayOfNumberOnly() { - // TODO: test ArrayOfNumberOnly - } - - /** - * Test the property 'arrayNumber' - */ - @Test - public void arrayNumberTest() { - // TODO: test arrayNumber - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ArrayTestTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ArrayTestTest.java deleted file mode 100644 index bc5ac74467..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ArrayTestTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import org.openapitools.client.model.ReadOnlyFirst; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ArrayTest - */ -public class ArrayTestTest { - private final ArrayTest model = new ArrayTest(); - - /** - * Model tests for ArrayTest - */ - @Test - public void testArrayTest() { - // TODO: test ArrayTest - } - - /** - * Test the property 'arrayOfString' - */ - @Test - public void arrayOfStringTest() { - // TODO: test arrayOfString - } - - /** - * Test the property 'arrayArrayOfInteger' - */ - @Test - public void arrayArrayOfIntegerTest() { - // TODO: test arrayArrayOfInteger - } - - /** - * Test the property 'arrayArrayOfModel' - */ - @Test - public void arrayArrayOfModelTest() { - // TODO: test arrayArrayOfModel - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/BananaReqTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/BananaReqTest.java deleted file mode 100644 index 63497d40c0..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/BananaReqTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for BananaReq - */ -public class BananaReqTest { - private final BananaReq model = new BananaReq(); - - /** - * Model tests for BananaReq - */ - @Test - public void testBananaReq() { - // TODO: test BananaReq - } - - /** - * Test the property 'lengthCm' - */ - @Test - public void lengthCmTest() { - // TODO: test lengthCm - } - - /** - * Test the property 'sweet' - */ - @Test - public void sweetTest() { - // TODO: test sweet - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/BananaTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/BananaTest.java deleted file mode 100644 index 0c3b7747ec..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/BananaTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Banana - */ -public class BananaTest { - private final Banana model = new Banana(); - - /** - * Model tests for Banana - */ - @Test - public void testBanana() { - // TODO: test Banana - } - - /** - * Test the property 'lengthCm' - */ - @Test - public void lengthCmTest() { - // TODO: test lengthCm - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/BasquePigTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/BasquePigTest.java deleted file mode 100644 index ea987d244c..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/BasquePigTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for BasquePig - */ -public class BasquePigTest { - private final BasquePig model = new BasquePig(); - - /** - * Model tests for BasquePig - */ - @Test - public void testBasquePig() { - // TODO: test BasquePig - } - - /** - * Test the property 'className' - */ - @Test - public void classNameTest() { - // TODO: test className - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CapitalizationTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CapitalizationTest.java deleted file mode 100644 index ffa72405fa..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CapitalizationTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Capitalization - */ -public class CapitalizationTest { - private final Capitalization model = new Capitalization(); - - /** - * Model tests for Capitalization - */ - @Test - public void testCapitalization() { - // TODO: test Capitalization - } - - /** - * Test the property 'smallCamel' - */ - @Test - public void smallCamelTest() { - // TODO: test smallCamel - } - - /** - * Test the property 'capitalCamel' - */ - @Test - public void capitalCamelTest() { - // TODO: test capitalCamel - } - - /** - * Test the property 'smallSnake' - */ - @Test - public void smallSnakeTest() { - // TODO: test smallSnake - } - - /** - * Test the property 'capitalSnake' - */ - @Test - public void capitalSnakeTest() { - // TODO: test capitalSnake - } - - /** - * Test the property 'scAETHFlowPoints' - */ - @Test - public void scAETHFlowPointsTest() { - // TODO: test scAETHFlowPoints - } - - /** - * Test the property 'ATT_NAME' - */ - @Test - public void ATT_NAMETest() { - // TODO: test ATT_NAME - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CatAllOfTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CatAllOfTest.java deleted file mode 100644 index 7884c04c72..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CatAllOfTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for CatAllOf - */ -public class CatAllOfTest { - private final CatAllOf model = new CatAllOf(); - - /** - * Model tests for CatAllOf - */ - @Test - public void testCatAllOf() { - // TODO: test CatAllOf - } - - /** - * Test the property 'declawed' - */ - @Test - public void declawedTest() { - // TODO: test declawed - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CatTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CatTest.java deleted file mode 100644 index 163c3eae43..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CatTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Animal; -import org.openapitools.client.model.CatAllOf; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Cat - */ -public class CatTest { - private final Cat model = new Cat(); - - /** - * Model tests for Cat - */ - @Test - public void testCat() { - // TODO: test Cat - } - - /** - * Test the property 'className' - */ - @Test - public void classNameTest() { - // TODO: test className - } - - /** - * Test the property 'color' - */ - @Test - public void colorTest() { - // TODO: test color - } - - /** - * Test the property 'declawed' - */ - @Test - public void declawedTest() { - // TODO: test declawed - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CategoryTest.java deleted file mode 100644 index 7f149cec85..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/CategoryTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Category - */ -public class CategoryTest { - private final Category model = new Category(); - - /** - * Model tests for Category - */ - @Test - public void testCategory() { - // TODO: test Category - } - - /** - * Test the property 'id' - */ - @Test - public void idTest() { - // TODO: test id - } - - /** - * Test the property 'name' - */ - @Test - public void nameTest() { - // TODO: test name - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ChildCatAllOfTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ChildCatAllOfTest.java deleted file mode 100644 index cb215a3c4b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ChildCatAllOfTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.Set; -import java.util.HashSet; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ChildCatAllOf - */ -public class ChildCatAllOfTest { - private final ChildCatAllOf model = new ChildCatAllOf(); - - /** - * Model tests for ChildCatAllOf - */ - @Test - public void testChildCatAllOf() { - // TODO: test ChildCatAllOf - } - - /** - * Test the property 'name' - */ - @Test - public void nameTest() { - // TODO: test name - } - - /** - * Test the property 'petType' - */ - @Test - public void petTypeTest() { - // TODO: test petType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ChildCatTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ChildCatTest.java deleted file mode 100644 index 625bcbedfa..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ChildCatTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ChildCatAllOf; -import org.openapitools.client.model.ParentPet; -import java.util.Set; -import java.util.HashSet; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ChildCat - */ -public class ChildCatTest { - private final ChildCat model = new ChildCat(); - - /** - * Model tests for ChildCat - */ - @Test - public void testChildCat() { - // TODO: test ChildCat - } - - /** - * Test the property 'petType' - */ - @Test - public void petTypeTest() { - // TODO: test petType - } - - /** - * Test the property 'name' - */ - @Test - public void nameTest() { - // TODO: test name - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ClassModelTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ClassModelTest.java deleted file mode 100644 index afac01e835..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ClassModelTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ClassModel - */ -public class ClassModelTest { - private final ClassModel model = new ClassModel(); - - /** - * Model tests for ClassModel - */ - @Test - public void testClassModel() { - // TODO: test ClassModel - } - - /** - * Test the property 'propertyClass' - */ - @Test - public void propertyClassTest() { - // TODO: test propertyClass - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ClientTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ClientTest.java deleted file mode 100644 index cf90750a91..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ClientTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Client - */ -public class ClientTest { - private final Client model = new Client(); - - /** - * Model tests for Client - */ - @Test - public void testClient() { - // TODO: test Client - } - - /** - * Test the property 'client' - */ - @Test - public void clientTest() { - // TODO: test client - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java deleted file mode 100644 index 41f5f736ab..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.QuadrilateralInterface; -import org.openapitools.client.model.ShapeInterface; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ComplexQuadrilateral - */ -public class ComplexQuadrilateralTest { - private final ComplexQuadrilateral model = new ComplexQuadrilateral(); - - /** - * Model tests for ComplexQuadrilateral - */ - @Test - public void testComplexQuadrilateral() { - // TODO: test ComplexQuadrilateral - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'quadrilateralType' - */ - @Test - public void quadrilateralTypeTest() { - // TODO: test quadrilateralType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DanishPigTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DanishPigTest.java deleted file mode 100644 index 0db1333f5d..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DanishPigTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for DanishPig - */ -public class DanishPigTest { - private final DanishPig model = new DanishPig(); - - /** - * Model tests for DanishPig - */ - @Test - public void testDanishPig() { - // TODO: test DanishPig - } - - /** - * Test the property 'className' - */ - @Test - public void classNameTest() { - // TODO: test className - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java deleted file mode 100644 index 91da27da0a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for DeprecatedObject - */ -public class DeprecatedObjectTest { - private final DeprecatedObject model = new DeprecatedObject(); - - /** - * Model tests for DeprecatedObject - */ - @Test - public void testDeprecatedObject() { - // TODO: test DeprecatedObject - } - - /** - * Test the property 'name' - */ - @Test - public void nameTest() { - // TODO: test name - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DogAllOfTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DogAllOfTest.java deleted file mode 100644 index 0ac24507de..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DogAllOfTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for DogAllOf - */ -public class DogAllOfTest { - private final DogAllOf model = new DogAllOf(); - - /** - * Model tests for DogAllOf - */ - @Test - public void testDogAllOf() { - // TODO: test DogAllOf - } - - /** - * Test the property 'breed' - */ - @Test - public void breedTest() { - // TODO: test breed - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DogTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DogTest.java deleted file mode 100644 index 2903f6657e..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DogTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Animal; -import org.openapitools.client.model.DogAllOf; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Dog - */ -public class DogTest { - private final Dog model = new Dog(); - - /** - * Model tests for Dog - */ - @Test - public void testDog() { - // TODO: test Dog - } - - /** - * Test the property 'className' - */ - @Test - public void classNameTest() { - // TODO: test className - } - - /** - * Test the property 'color' - */ - @Test - public void colorTest() { - // TODO: test color - } - - /** - * Test the property 'breed' - */ - @Test - public void breedTest() { - // TODO: test breed - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DrawingTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DrawingTest.java deleted file mode 100644 index 812a17c2d7..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/DrawingTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.openapitools.client.model.Fruit; -import org.openapitools.client.model.NullableShape; -import org.openapitools.client.model.Shape; -import org.openapitools.client.model.ShapeOrNull; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Drawing - */ -public class DrawingTest { - private final Drawing model = new Drawing(); - - /** - * Model tests for Drawing - */ - @Test - public void testDrawing() { - // TODO: test Drawing - } - - /** - * Test the property 'mainShape' - */ - @Test - public void mainShapeTest() { - // TODO: test mainShape - } - - /** - * Test the property 'shapeOrNull' - */ - @Test - public void shapeOrNullTest() { - // TODO: test shapeOrNull - } - - /** - * Test the property 'nullableShape' - */ - @Test - public void nullableShapeTest() { - // TODO: test nullableShape - } - - /** - * Test the property 'shapes' - */ - @Test - public void shapesTest() { - // TODO: test shapes - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EnumArraysTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EnumArraysTest.java deleted file mode 100644 index 3130e2a5a0..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EnumArraysTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for EnumArrays - */ -public class EnumArraysTest { - private final EnumArrays model = new EnumArrays(); - - /** - * Model tests for EnumArrays - */ - @Test - public void testEnumArrays() { - // TODO: test EnumArrays - } - - /** - * Test the property 'justSymbol' - */ - @Test - public void justSymbolTest() { - // TODO: test justSymbol - } - - /** - * Test the property 'arrayEnum' - */ - @Test - public void arrayEnumTest() { - // TODO: test arrayEnum - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EnumClassTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EnumClassTest.java deleted file mode 100644 index 9e45543fac..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EnumClassTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for EnumClass - */ -public class EnumClassTest { - /** - * Model tests for EnumClass - */ - @Test - public void testEnumClass() { - // TODO: test EnumClass - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EnumTestTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EnumTestTest.java deleted file mode 100644 index 8cdf2bf6d6..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EnumTestTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.OuterEnum; -import org.openapitools.client.model.OuterEnumDefaultValue; -import org.openapitools.client.model.OuterEnumInteger; -import org.openapitools.client.model.OuterEnumIntegerDefaultValue; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for EnumTest - */ -public class EnumTestTest { - private final EnumTest model = new EnumTest(); - - /** - * Model tests for EnumTest - */ - @Test - public void testEnumTest() { - // TODO: test EnumTest - } - - /** - * Test the property 'enumString' - */ - @Test - public void enumStringTest() { - // TODO: test enumString - } - - /** - * Test the property 'enumStringRequired' - */ - @Test - public void enumStringRequiredTest() { - // TODO: test enumStringRequired - } - - /** - * Test the property 'enumInteger' - */ - @Test - public void enumIntegerTest() { - // TODO: test enumInteger - } - - /** - * Test the property 'enumNumber' - */ - @Test - public void enumNumberTest() { - // TODO: test enumNumber - } - - /** - * Test the property 'outerEnum' - */ - @Test - public void outerEnumTest() { - // TODO: test outerEnum - } - - /** - * Test the property 'outerEnumInteger' - */ - @Test - public void outerEnumIntegerTest() { - // TODO: test outerEnumInteger - } - - /** - * Test the property 'outerEnumDefaultValue' - */ - @Test - public void outerEnumDefaultValueTest() { - // TODO: test outerEnumDefaultValue - } - - /** - * Test the property 'outerEnumIntegerDefaultValue' - */ - @Test - public void outerEnumIntegerDefaultValueTest() { - // TODO: test outerEnumIntegerDefaultValue - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java deleted file mode 100644 index 4b7781bac4..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ShapeInterface; -import org.openapitools.client.model.TriangleInterface; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for EquilateralTriangle - */ -public class EquilateralTriangleTest { - private final EquilateralTriangle model = new EquilateralTriangle(); - - /** - * Model tests for EquilateralTriangle - */ - @Test - public void testEquilateralTriangle() { - // TODO: test EquilateralTriangle - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'triangleType' - */ - @Test - public void triangleTypeTest() { - // TODO: test triangleType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java deleted file mode 100644 index c3c78aa3aa..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for FileSchemaTestClass - */ -public class FileSchemaTestClassTest { - private final FileSchemaTestClass model = new FileSchemaTestClass(); - - /** - * Model tests for FileSchemaTestClass - */ - @Test - public void testFileSchemaTestClass() { - // TODO: test FileSchemaTestClass - } - - /** - * Test the property 'file' - */ - @Test - public void fileTest() { - // TODO: test file - } - - /** - * Test the property 'files' - */ - @Test - public void filesTest() { - // TODO: test files - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FooTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FooTest.java deleted file mode 100644 index f79b9cd7df..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FooTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Foo - */ -public class FooTest { - private final Foo model = new Foo(); - - /** - * Model tests for Foo - */ - @Test - public void testFoo() { - // TODO: test Foo - } - - /** - * Test the property 'bar' - */ - @Test - public void barTest() { - // TODO: test bar - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FormatTestTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FormatTestTest.java deleted file mode 100644 index d4db0a294b..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FormatTestTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.io.File; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.util.UUID; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for FormatTest - */ -public class FormatTestTest { - private final FormatTest model = new FormatTest(); - - /** - * Model tests for FormatTest - */ - @Test - public void testFormatTest() { - // TODO: test FormatTest - } - - /** - * Test the property 'integer' - */ - @Test - public void integerTest() { - // TODO: test integer - } - - /** - * Test the property 'int32' - */ - @Test - public void int32Test() { - // TODO: test int32 - } - - /** - * Test the property 'int64' - */ - @Test - public void int64Test() { - // TODO: test int64 - } - - /** - * Test the property 'number' - */ - @Test - public void numberTest() { - // TODO: test number - } - - /** - * Test the property '_float' - */ - @Test - public void _floatTest() { - // TODO: test _float - } - - /** - * Test the property '_double' - */ - @Test - public void _doubleTest() { - // TODO: test _double - } - - /** - * Test the property 'string' - */ - @Test - public void stringTest() { - // TODO: test string - } - - /** - * Test the property '_byte' - */ - @Test - public void _byteTest() { - // TODO: test _byte - } - - /** - * Test the property 'binary' - */ - @Test - public void binaryTest() { - // TODO: test binary - } - - /** - * Test the property 'date' - */ - @Test - public void dateTest() { - // TODO: test date - } - - /** - * Test the property 'dateTime' - */ - @Test - public void dateTimeTest() { - // TODO: test dateTime - } - - /** - * Test the property 'uuid' - */ - @Test - public void uuidTest() { - // TODO: test uuid - } - - /** - * Test the property 'password' - */ - @Test - public void passwordTest() { - // TODO: test password - } - - /** - * Test the property 'patternWithDigits' - */ - @Test - public void patternWithDigitsTest() { - // TODO: test patternWithDigits - } - - /** - * Test the property 'patternWithDigitsAndDelimiter' - */ - @Test - public void patternWithDigitsAndDelimiterTest() { - // TODO: test patternWithDigitsAndDelimiter - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FruitReqTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FruitReqTest.java deleted file mode 100644 index 29b7ab74fa..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FruitReqTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.openapitools.client.model.AppleReq; -import org.openapitools.client.model.BananaReq; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for FruitReq - */ -public class FruitReqTest { - private final FruitReq model = new FruitReq(); - - /** - * Model tests for FruitReq - */ - @Test - public void testFruitReq() { - // TODO: test FruitReq - } - - /** - * Test the property 'cultivar' - */ - @Test - public void cultivarTest() { - // TODO: test cultivar - } - - /** - * Test the property 'mealy' - */ - @Test - public void mealyTest() { - // TODO: test mealy - } - - /** - * Test the property 'lengthCm' - */ - @Test - public void lengthCmTest() { - // TODO: test lengthCm - } - - /** - * Test the property 'sweet' - */ - @Test - public void sweetTest() { - // TODO: test sweet - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FruitTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FruitTest.java deleted file mode 100644 index 2bb4bec642..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/FruitTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.openapitools.client.model.Apple; -import org.openapitools.client.model.Banana; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Fruit - */ -public class FruitTest { - private final Fruit model = new Fruit(); - - /** - * Model tests for Fruit - */ - @Test - public void testFruit() { - // TODO: test Fruit - } - - /** - * Test the property 'cultivar' - */ - @Test - public void cultivarTest() { - // TODO: test cultivar - } - - /** - * Test the property 'origin' - */ - @Test - public void originTest() { - // TODO: test origin - } - - /** - * Test the property 'lengthCm' - */ - @Test - public void lengthCmTest() { - // TODO: test lengthCm - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/GmFruitTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/GmFruitTest.java deleted file mode 100644 index 0a60d7d072..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/GmFruitTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.openapitools.client.model.Apple; -import org.openapitools.client.model.Banana; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for GmFruit - */ -public class GmFruitTest { - private final GmFruit model = new GmFruit(); - - /** - * Model tests for GmFruit - */ - @Test - public void testGmFruit() { - // TODO: test GmFruit - } - - /** - * Test the property 'cultivar' - */ - @Test - public void cultivarTest() { - // TODO: test cultivar - } - - /** - * Test the property 'origin' - */ - @Test - public void originTest() { - // TODO: test origin - } - - /** - * Test the property 'lengthCm' - */ - @Test - public void lengthCmTest() { - // TODO: test lengthCm - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java deleted file mode 100644 index dfbfa148fd..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ChildCat; -import org.openapitools.client.model.ParentPet; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for GrandparentAnimal - */ -public class GrandparentAnimalTest { - private final GrandparentAnimal model = new GrandparentAnimal(); - - /** - * Model tests for GrandparentAnimal - */ - @Test - public void testGrandparentAnimal() { - // TODO: test GrandparentAnimal - } - - /** - * Test the property 'petType' - */ - @Test - public void petTypeTest() { - // TODO: test petType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java deleted file mode 100644 index e28f7d7441..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for HasOnlyReadOnly - */ -public class HasOnlyReadOnlyTest { - private final HasOnlyReadOnly model = new HasOnlyReadOnly(); - - /** - * Model tests for HasOnlyReadOnly - */ - @Test - public void testHasOnlyReadOnly() { - // TODO: test HasOnlyReadOnly - } - - /** - * Test the property 'bar' - */ - @Test - public void barTest() { - // TODO: test bar - } - - /** - * Test the property 'foo' - */ - @Test - public void fooTest() { - // TODO: test foo - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java deleted file mode 100644 index 02bac64439..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for HealthCheckResult - */ -public class HealthCheckResultTest { - private final HealthCheckResult model = new HealthCheckResult(); - - /** - * Model tests for HealthCheckResult - */ - @Test - public void testHealthCheckResult() { - // TODO: test HealthCheckResult - } - - /** - * Test the property 'nullableMessage' - */ - @Test - public void nullableMessageTest() { - // TODO: test nullableMessage - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject1Test.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject1Test.java deleted file mode 100644 index 539e09fc99..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject1Test.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.io.File; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for InlineObject1 - */ -public class InlineObject1Test { - private final InlineObject1 model = new InlineObject1(); - - /** - * Model tests for InlineObject1 - */ - @Test - public void testInlineObject1() { - // TODO: test InlineObject1 - } - - /** - * Test the property 'additionalMetadata' - */ - @Test - public void additionalMetadataTest() { - // TODO: test additionalMetadata - } - - /** - * Test the property 'file' - */ - @Test - public void fileTest() { - // TODO: test file - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject2Test.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject2Test.java deleted file mode 100644 index 19c5f9c72d..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject2Test.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for InlineObject2 - */ -public class InlineObject2Test { - private final InlineObject2 model = new InlineObject2(); - - /** - * Model tests for InlineObject2 - */ - @Test - public void testInlineObject2() { - // TODO: test InlineObject2 - } - - /** - * Test the property 'enumFormStringArray' - */ - @Test - public void enumFormStringArrayTest() { - // TODO: test enumFormStringArray - } - - /** - * Test the property 'enumFormString' - */ - @Test - public void enumFormStringTest() { - // TODO: test enumFormString - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject3Test.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject3Test.java deleted file mode 100644 index 15ac17b004..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject3Test.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.io.File; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for InlineObject3 - */ -public class InlineObject3Test { - private final InlineObject3 model = new InlineObject3(); - - /** - * Model tests for InlineObject3 - */ - @Test - public void testInlineObject3() { - // TODO: test InlineObject3 - } - - /** - * Test the property 'integer' - */ - @Test - public void integerTest() { - // TODO: test integer - } - - /** - * Test the property 'int32' - */ - @Test - public void int32Test() { - // TODO: test int32 - } - - /** - * Test the property 'int64' - */ - @Test - public void int64Test() { - // TODO: test int64 - } - - /** - * Test the property 'number' - */ - @Test - public void numberTest() { - // TODO: test number - } - - /** - * Test the property '_float' - */ - @Test - public void _floatTest() { - // TODO: test _float - } - - /** - * Test the property '_double' - */ - @Test - public void _doubleTest() { - // TODO: test _double - } - - /** - * Test the property 'string' - */ - @Test - public void stringTest() { - // TODO: test string - } - - /** - * Test the property 'patternWithoutDelimiter' - */ - @Test - public void patternWithoutDelimiterTest() { - // TODO: test patternWithoutDelimiter - } - - /** - * Test the property '_byte' - */ - @Test - public void _byteTest() { - // TODO: test _byte - } - - /** - * Test the property 'binary' - */ - @Test - public void binaryTest() { - // TODO: test binary - } - - /** - * Test the property 'date' - */ - @Test - public void dateTest() { - // TODO: test date - } - - /** - * Test the property 'dateTime' - */ - @Test - public void dateTimeTest() { - // TODO: test dateTime - } - - /** - * Test the property 'password' - */ - @Test - public void passwordTest() { - // TODO: test password - } - - /** - * Test the property 'callback' - */ - @Test - public void callbackTest() { - // TODO: test callback - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject4Test.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject4Test.java deleted file mode 100644 index 59778e276c..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject4Test.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for InlineObject4 - */ -public class InlineObject4Test { - private final InlineObject4 model = new InlineObject4(); - - /** - * Model tests for InlineObject4 - */ - @Test - public void testInlineObject4() { - // TODO: test InlineObject4 - } - - /** - * Test the property 'param' - */ - @Test - public void paramTest() { - // TODO: test param - } - - /** - * Test the property 'param2' - */ - @Test - public void param2Test() { - // TODO: test param2 - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject5Test.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject5Test.java deleted file mode 100644 index 943cbbfc63..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObject5Test.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.io.File; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for InlineObject5 - */ -public class InlineObject5Test { - private final InlineObject5 model = new InlineObject5(); - - /** - * Model tests for InlineObject5 - */ - @Test - public void testInlineObject5() { - // TODO: test InlineObject5 - } - - /** - * Test the property 'additionalMetadata' - */ - @Test - public void additionalMetadataTest() { - // TODO: test additionalMetadata - } - - /** - * Test the property 'requiredFile' - */ - @Test - public void requiredFileTest() { - // TODO: test requiredFile - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObjectTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObjectTest.java deleted file mode 100644 index 4a5f5d0de9..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineObjectTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for InlineObject - */ -public class InlineObjectTest { - private final InlineObject model = new InlineObject(); - - /** - * Model tests for InlineObject - */ - @Test - public void testInlineObject() { - // TODO: test InlineObject - } - - /** - * Test the property 'name' - */ - @Test - public void nameTest() { - // TODO: test name - } - - /** - * Test the property 'status' - */ - @Test - public void statusTest() { - // TODO: test status - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineResponseDefaultTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineResponseDefaultTest.java deleted file mode 100644 index e787c93112..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/InlineResponseDefaultTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Foo; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for InlineResponseDefault - */ -public class InlineResponseDefaultTest { - private final InlineResponseDefault model = new InlineResponseDefault(); - - /** - * Model tests for InlineResponseDefault - */ - @Test - public void testInlineResponseDefault() { - // TODO: test InlineResponseDefault - } - - /** - * Test the property 'string' - */ - @Test - public void stringTest() { - // TODO: test string - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java deleted file mode 100644 index 74ea4bbdb0..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ShapeInterface; -import org.openapitools.client.model.TriangleInterface; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for IsoscelesTriangle - */ -public class IsoscelesTriangleTest { - private final IsoscelesTriangle model = new IsoscelesTriangle(); - - /** - * Model tests for IsoscelesTriangle - */ - @Test - public void testIsoscelesTriangle() { - // TODO: test IsoscelesTriangle - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'triangleType' - */ - @Test - public void triangleTypeTest() { - // TODO: test triangleType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/MammalTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/MammalTest.java deleted file mode 100644 index 9461420b10..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/MammalTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Pig; -import org.openapitools.client.model.Whale; -import org.openapitools.client.model.Zebra; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Mammal - */ -public class MammalTest { - private final Mammal model = new Mammal(); - - /** - * Model tests for Mammal - */ - @Test - public void testMammal() { - // TODO: test Mammal - } - - /** - * Test the property 'hasBaleen' - */ - @Test - public void hasBaleenTest() { - // TODO: test hasBaleen - } - - /** - * Test the property 'hasTeeth' - */ - @Test - public void hasTeethTest() { - // TODO: test hasTeeth - } - - /** - * Test the property 'className' - */ - @Test - public void classNameTest() { - // TODO: test className - } - - /** - * Test the property 'type' - */ - @Test - public void typeTest() { - // TODO: test type - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/MapTestTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/MapTestTest.java deleted file mode 100644 index 8d1b64dfce..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/MapTestTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for MapTest - */ -public class MapTestTest { - private final MapTest model = new MapTest(); - - /** - * Model tests for MapTest - */ - @Test - public void testMapTest() { - // TODO: test MapTest - } - - /** - * Test the property 'mapMapOfString' - */ - @Test - public void mapMapOfStringTest() { - // TODO: test mapMapOfString - } - - /** - * Test the property 'mapOfEnumString' - */ - @Test - public void mapOfEnumStringTest() { - // TODO: test mapOfEnumString - } - - /** - * Test the property 'directMap' - */ - @Test - public void directMapTest() { - // TODO: test directMap - } - - /** - * Test the property 'indirectMap' - */ - @Test - public void indirectMapTest() { - // TODO: test indirectMap - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java deleted file mode 100644 index e90ad8889a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.time.OffsetDateTime; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import org.openapitools.client.model.Animal; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for MixedPropertiesAndAdditionalPropertiesClass - */ -public class MixedPropertiesAndAdditionalPropertiesClassTest { - private final MixedPropertiesAndAdditionalPropertiesClass model = new MixedPropertiesAndAdditionalPropertiesClass(); - - /** - * Model tests for MixedPropertiesAndAdditionalPropertiesClass - */ - @Test - public void testMixedPropertiesAndAdditionalPropertiesClass() { - // TODO: test MixedPropertiesAndAdditionalPropertiesClass - } - - /** - * Test the property 'uuid' - */ - @Test - public void uuidTest() { - // TODO: test uuid - } - - /** - * Test the property 'dateTime' - */ - @Test - public void dateTimeTest() { - // TODO: test dateTime - } - - /** - * Test the property 'map' - */ - @Test - public void mapTest() { - // TODO: test map - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/Model200ResponseTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/Model200ResponseTest.java deleted file mode 100644 index 20dee01ae5..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/Model200ResponseTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Model200Response - */ -public class Model200ResponseTest { - private final Model200Response model = new Model200Response(); - - /** - * Model tests for Model200Response - */ - @Test - public void testModel200Response() { - // TODO: test Model200Response - } - - /** - * Test the property 'name' - */ - @Test - public void nameTest() { - // TODO: test name - } - - /** - * Test the property 'propertyClass' - */ - @Test - public void propertyClassTest() { - // TODO: test propertyClass - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java deleted file mode 100644 index 5dfb76f406..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ModelApiResponse - */ -public class ModelApiResponseTest { - private final ModelApiResponse model = new ModelApiResponse(); - - /** - * Model tests for ModelApiResponse - */ - @Test - public void testModelApiResponse() { - // TODO: test ModelApiResponse - } - - /** - * Test the property 'code' - */ - @Test - public void codeTest() { - // TODO: test code - } - - /** - * Test the property 'type' - */ - @Test - public void typeTest() { - // TODO: test type - } - - /** - * Test the property 'message' - */ - @Test - public void messageTest() { - // TODO: test message - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ModelReturnTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ModelReturnTest.java deleted file mode 100644 index a1517b158a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ModelReturnTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ModelReturn - */ -public class ModelReturnTest { - private final ModelReturn model = new ModelReturn(); - - /** - * Model tests for ModelReturn - */ - @Test - public void testModelReturn() { - // TODO: test ModelReturn - } - - /** - * Test the property '_return' - */ - @Test - public void _returnTest() { - // TODO: test _return - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NameTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NameTest.java deleted file mode 100644 index d54b90ad16..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NameTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Name - */ -public class NameTest { - private final Name model = new Name(); - - /** - * Model tests for Name - */ - @Test - public void testName() { - // TODO: test Name - } - - /** - * Test the property 'name' - */ - @Test - public void nameTest() { - // TODO: test name - } - - /** - * Test the property 'snakeCase' - */ - @Test - public void snakeCaseTest() { - // TODO: test snakeCase - } - - /** - * Test the property 'property' - */ - @Test - public void propertyTest() { - // TODO: test property - } - - /** - * Test the property '_123number' - */ - @Test - public void _123numberTest() { - // TODO: test _123number - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NullableClassTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NullableClassTest.java deleted file mode 100644 index fe9c2841bb..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NullableClassTest.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for NullableClass - */ -public class NullableClassTest { - private final NullableClass model = new NullableClass(); - - /** - * Model tests for NullableClass - */ - @Test - public void testNullableClass() { - // TODO: test NullableClass - } - - /** - * Test the property 'integerProp' - */ - @Test - public void integerPropTest() { - // TODO: test integerProp - } - - /** - * Test the property 'numberProp' - */ - @Test - public void numberPropTest() { - // TODO: test numberProp - } - - /** - * Test the property 'booleanProp' - */ - @Test - public void booleanPropTest() { - // TODO: test booleanProp - } - - /** - * Test the property 'stringProp' - */ - @Test - public void stringPropTest() { - // TODO: test stringProp - } - - /** - * Test the property 'dateProp' - */ - @Test - public void datePropTest() { - // TODO: test dateProp - } - - /** - * Test the property 'datetimeProp' - */ - @Test - public void datetimePropTest() { - // TODO: test datetimeProp - } - - /** - * Test the property 'arrayNullableProp' - */ - @Test - public void arrayNullablePropTest() { - // TODO: test arrayNullableProp - } - - /** - * Test the property 'arrayAndItemsNullableProp' - */ - @Test - public void arrayAndItemsNullablePropTest() { - // TODO: test arrayAndItemsNullableProp - } - - /** - * Test the property 'arrayItemsNullable' - */ - @Test - public void arrayItemsNullableTest() { - // TODO: test arrayItemsNullable - } - - /** - * Test the property 'objectNullableProp' - */ - @Test - public void objectNullablePropTest() { - // TODO: test objectNullableProp - } - - /** - * Test the property 'objectAndItemsNullableProp' - */ - @Test - public void objectAndItemsNullablePropTest() { - // TODO: test objectAndItemsNullableProp - } - - /** - * Test the property 'objectItemsNullable' - */ - @Test - public void objectItemsNullableTest() { - // TODO: test objectItemsNullable - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NullableShapeTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NullableShapeTest.java deleted file mode 100644 index a280cb013a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NullableShapeTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.Triangle; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for NullableShape - */ -public class NullableShapeTest { - private final NullableShape model = new NullableShape(); - - /** - * Model tests for NullableShape - */ - @Test - public void testNullableShape() { - // TODO: test NullableShape - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'triangleType' - */ - @Test - public void triangleTypeTest() { - // TODO: test triangleType - } - - /** - * Test the property 'quadrilateralType' - */ - @Test - public void quadrilateralTypeTest() { - // TODO: test quadrilateralType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NumberOnlyTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NumberOnlyTest.java deleted file mode 100644 index 4238632f54..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/NumberOnlyTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for NumberOnly - */ -public class NumberOnlyTest { - private final NumberOnly model = new NumberOnly(); - - /** - * Model tests for NumberOnly - */ - @Test - public void testNumberOnly() { - // TODO: test NumberOnly - } - - /** - * Test the property 'justNumber' - */ - @Test - public void justNumberTest() { - // TODO: test justNumber - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java deleted file mode 100644 index 6f2848cab5..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; -import org.openapitools.client.model.DeprecatedObject; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ObjectWithDeprecatedFields - */ -public class ObjectWithDeprecatedFieldsTest { - private final ObjectWithDeprecatedFields model = new ObjectWithDeprecatedFields(); - - /** - * Model tests for ObjectWithDeprecatedFields - */ - @Test - public void testObjectWithDeprecatedFields() { - // TODO: test ObjectWithDeprecatedFields - } - - /** - * Test the property 'uuid' - */ - @Test - public void uuidTest() { - // TODO: test uuid - } - - /** - * Test the property 'id' - */ - @Test - public void idTest() { - // TODO: test id - } - - /** - * Test the property 'deprecatedRef' - */ - @Test - public void deprecatedRefTest() { - // TODO: test deprecatedRef - } - - /** - * Test the property 'bars' - */ - @Test - public void barsTest() { - // TODO: test bars - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OrderTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OrderTest.java deleted file mode 100644 index 007f1aaea8..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OrderTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.time.OffsetDateTime; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Order - */ -public class OrderTest { - private final Order model = new Order(); - - /** - * Model tests for Order - */ - @Test - public void testOrder() { - // TODO: test Order - } - - /** - * Test the property 'id' - */ - @Test - public void idTest() { - // TODO: test id - } - - /** - * Test the property 'petId' - */ - @Test - public void petIdTest() { - // TODO: test petId - } - - /** - * Test the property 'quantity' - */ - @Test - public void quantityTest() { - // TODO: test quantity - } - - /** - * Test the property 'shipDate' - */ - @Test - public void shipDateTest() { - // TODO: test shipDate - } - - /** - * Test the property 'status' - */ - @Test - public void statusTest() { - // TODO: test status - } - - /** - * Test the property 'complete' - */ - @Test - public void completeTest() { - // TODO: test complete - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterCompositeTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterCompositeTest.java deleted file mode 100644 index 527a5df91a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterCompositeTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for OuterComposite - */ -public class OuterCompositeTest { - private final OuterComposite model = new OuterComposite(); - - /** - * Model tests for OuterComposite - */ - @Test - public void testOuterComposite() { - // TODO: test OuterComposite - } - - /** - * Test the property 'myNumber' - */ - @Test - public void myNumberTest() { - // TODO: test myNumber - } - - /** - * Test the property 'myString' - */ - @Test - public void myStringTest() { - // TODO: test myString - } - - /** - * Test the property 'myBoolean' - */ - @Test - public void myBooleanTest() { - // TODO: test myBoolean - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java deleted file mode 100644 index 59c4eebd2f..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for OuterEnumDefaultValue - */ -public class OuterEnumDefaultValueTest { - /** - * Model tests for OuterEnumDefaultValue - */ - @Test - public void testOuterEnumDefaultValue() { - // TODO: test OuterEnumDefaultValue - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java deleted file mode 100644 index fa981c7093..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for OuterEnumIntegerDefaultValue - */ -public class OuterEnumIntegerDefaultValueTest { - /** - * Model tests for OuterEnumIntegerDefaultValue - */ - @Test - public void testOuterEnumIntegerDefaultValue() { - // TODO: test OuterEnumIntegerDefaultValue - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java deleted file mode 100644 index 1b98d326bb..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for OuterEnumInteger - */ -public class OuterEnumIntegerTest { - /** - * Model tests for OuterEnumInteger - */ - @Test - public void testOuterEnumInteger() { - // TODO: test OuterEnumInteger - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumTest.java deleted file mode 100644 index cf0ebae0fa..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/OuterEnumTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for OuterEnum - */ -public class OuterEnumTest { - /** - * Model tests for OuterEnum - */ - @Test - public void testOuterEnum() { - // TODO: test OuterEnum - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ParentPetTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ParentPetTest.java deleted file mode 100644 index bf6d29c75f..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ParentPetTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ChildCat; -import org.openapitools.client.model.GrandparentAnimal; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ParentPet - */ -public class ParentPetTest { - private final ParentPet model = new ParentPet(); - - /** - * Model tests for ParentPet - */ - @Test - public void testParentPet() { - // TODO: test ParentPet - } - - /** - * Test the property 'petType' - */ - @Test - public void petTypeTest() { - // TODO: test petType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/PetTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/PetTest.java deleted file mode 100644 index 7d56063b3e..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/PetTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; -import org.openapitools.client.model.Category; -import org.openapitools.client.model.Tag; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Pet - */ -public class PetTest { - private final Pet model = new Pet(); - - /** - * Model tests for Pet - */ - @Test - public void testPet() { - // TODO: test Pet - } - - /** - * Test the property 'id' - */ - @Test - public void idTest() { - // TODO: test id - } - - /** - * Test the property 'category' - */ - @Test - public void categoryTest() { - // TODO: test category - } - - /** - * Test the property 'name' - */ - @Test - public void nameTest() { - // TODO: test name - } - - /** - * Test the property 'photoUrls' - */ - @Test - public void photoUrlsTest() { - // TODO: test photoUrls - } - - /** - * Test the property 'tags' - */ - @Test - public void tagsTest() { - // TODO: test tags - } - - /** - * Test the property 'status' - */ - @Test - public void statusTest() { - // TODO: test status - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/PigTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/PigTest.java deleted file mode 100644 index 1c59ee0698..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/PigTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.BasquePig; -import org.openapitools.client.model.DanishPig; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Pig - */ -public class PigTest { - private final Pig model = new Pig(); - - /** - * Model tests for Pig - */ - @Test - public void testPig() { - // TODO: test Pig - } - - /** - * Test the property 'className' - */ - @Test - public void classNameTest() { - // TODO: test className - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java deleted file mode 100644 index cd6b36ad48..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for QuadrilateralInterface - */ -public class QuadrilateralInterfaceTest { - private final QuadrilateralInterface model = new QuadrilateralInterface(); - - /** - * Model tests for QuadrilateralInterface - */ - @Test - public void testQuadrilateralInterface() { - // TODO: test QuadrilateralInterface - } - - /** - * Test the property 'quadrilateralType' - */ - @Test - public void quadrilateralTypeTest() { - // TODO: test quadrilateralType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/QuadrilateralTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/QuadrilateralTest.java deleted file mode 100644 index 2250cc3f5c..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/QuadrilateralTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ComplexQuadrilateral; -import org.openapitools.client.model.SimpleQuadrilateral; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Quadrilateral - */ -public class QuadrilateralTest { - private final Quadrilateral model = new Quadrilateral(); - - /** - * Model tests for Quadrilateral - */ - @Test - public void testQuadrilateral() { - // TODO: test Quadrilateral - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'quadrilateralType' - */ - @Test - public void quadrilateralTypeTest() { - // TODO: test quadrilateralType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java deleted file mode 100644 index 5d460c3c69..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ReadOnlyFirst - */ -public class ReadOnlyFirstTest { - private final ReadOnlyFirst model = new ReadOnlyFirst(); - - /** - * Model tests for ReadOnlyFirst - */ - @Test - public void testReadOnlyFirst() { - // TODO: test ReadOnlyFirst - } - - /** - * Test the property 'bar' - */ - @Test - public void barTest() { - // TODO: test bar - } - - /** - * Test the property 'baz' - */ - @Test - public void bazTest() { - // TODO: test baz - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java deleted file mode 100644 index b9e7aec3a9..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.ShapeInterface; -import org.openapitools.client.model.TriangleInterface; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ScaleneTriangle - */ -public class ScaleneTriangleTest { - private final ScaleneTriangle model = new ScaleneTriangle(); - - /** - * Model tests for ScaleneTriangle - */ - @Test - public void testScaleneTriangle() { - // TODO: test ScaleneTriangle - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'triangleType' - */ - @Test - public void triangleTypeTest() { - // TODO: test triangleType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java deleted file mode 100644 index bf492afc1a..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ShapeInterface - */ -public class ShapeInterfaceTest { - private final ShapeInterface model = new ShapeInterface(); - - /** - * Model tests for ShapeInterface - */ - @Test - public void testShapeInterface() { - // TODO: test ShapeInterface - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java deleted file mode 100644 index 1a679d15a0..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.Triangle; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for ShapeOrNull - */ -public class ShapeOrNullTest { - private final ShapeOrNull model = new ShapeOrNull(); - - /** - * Model tests for ShapeOrNull - */ - @Test - public void testShapeOrNull() { - // TODO: test ShapeOrNull - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'triangleType' - */ - @Test - public void triangleTypeTest() { - // TODO: test triangleType - } - - /** - * Test the property 'quadrilateralType' - */ - @Test - public void quadrilateralTypeTest() { - // TODO: test quadrilateralType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ShapeTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ShapeTest.java deleted file mode 100644 index c82182ab7c..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ShapeTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.Quadrilateral; -import org.openapitools.client.model.Triangle; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Shape - */ -public class ShapeTest { - private final Shape model = new Shape(); - - /** - * Model tests for Shape - */ - @Test - public void testShape() { - // TODO: test Shape - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'triangleType' - */ - @Test - public void triangleTypeTest() { - // TODO: test triangleType - } - - /** - * Test the property 'quadrilateralType' - */ - @Test - public void quadrilateralTypeTest() { - // TODO: test quadrilateralType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java deleted file mode 100644 index 4eae4b7653..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.QuadrilateralInterface; -import org.openapitools.client.model.ShapeInterface; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for SimpleQuadrilateral - */ -public class SimpleQuadrilateralTest { - private final SimpleQuadrilateral model = new SimpleQuadrilateral(); - - /** - * Model tests for SimpleQuadrilateral - */ - @Test - public void testSimpleQuadrilateral() { - // TODO: test SimpleQuadrilateral - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'quadrilateralType' - */ - @Test - public void quadrilateralTypeTest() { - // TODO: test quadrilateralType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java deleted file mode 100644 index da6a64c20f..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for SpecialModelName - */ -public class SpecialModelNameTest { - private final SpecialModelName model = new SpecialModelName(); - - /** - * Model tests for SpecialModelName - */ - @Test - public void testSpecialModelName() { - // TODO: test SpecialModelName - } - - /** - * Test the property '$specialPropertyName' - */ - @Test - public void $specialPropertyNameTest() { - // TODO: test $specialPropertyName - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/TagTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/TagTest.java deleted file mode 100644 index 51852d8005..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/TagTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Tag - */ -public class TagTest { - private final Tag model = new Tag(); - - /** - * Model tests for Tag - */ - @Test - public void testTag() { - // TODO: test Tag - } - - /** - * Test the property 'id' - */ - @Test - public void idTest() { - // TODO: test id - } - - /** - * Test the property 'name' - */ - @Test - public void nameTest() { - // TODO: test name - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java deleted file mode 100644 index 5a12bd48e9..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for TriangleInterface - */ -public class TriangleInterfaceTest { - private final TriangleInterface model = new TriangleInterface(); - - /** - * Model tests for TriangleInterface - */ - @Test - public void testTriangleInterface() { - // TODO: test TriangleInterface - } - - /** - * Test the property 'triangleType' - */ - @Test - public void triangleTypeTest() { - // TODO: test triangleType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/TriangleTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/TriangleTest.java deleted file mode 100644 index a6acdee6e6..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/TriangleTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.EquilateralTriangle; -import org.openapitools.client.model.IsoscelesTriangle; -import org.openapitools.client.model.ScaleneTriangle; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Triangle - */ -public class TriangleTest { - private final Triangle model = new Triangle(); - - /** - * Model tests for Triangle - */ - @Test - public void testTriangle() { - // TODO: test Triangle - } - - /** - * Test the property 'shapeType' - */ - @Test - public void shapeTypeTest() { - // TODO: test shapeType - } - - /** - * Test the property 'triangleType' - */ - @Test - public void triangleTypeTest() { - // TODO: test triangleType - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/UserTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/UserTest.java deleted file mode 100644 index c3c50f3fba..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/UserTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openapitools.jackson.nullable.JsonNullable; -import java.util.NoSuchElementException; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for User - */ -public class UserTest { - private final User model = new User(); - - /** - * Model tests for User - */ - @Test - public void testUser() { - // TODO: test User - } - - /** - * Test the property 'id' - */ - @Test - public void idTest() { - // TODO: test id - } - - /** - * Test the property 'username' - */ - @Test - public void usernameTest() { - // TODO: test username - } - - /** - * Test the property 'firstName' - */ - @Test - public void firstNameTest() { - // TODO: test firstName - } - - /** - * Test the property 'lastName' - */ - @Test - public void lastNameTest() { - // TODO: test lastName - } - - /** - * Test the property 'email' - */ - @Test - public void emailTest() { - // TODO: test email - } - - /** - * Test the property 'password' - */ - @Test - public void passwordTest() { - // TODO: test password - } - - /** - * Test the property 'phone' - */ - @Test - public void phoneTest() { - // TODO: test phone - } - - /** - * Test the property 'userStatus' - */ - @Test - public void userStatusTest() { - // TODO: test userStatus - } - - /** - * Test the property 'objectWithNoDeclaredProps' - */ - @Test - public void objectWithNoDeclaredPropsTest() { - // TODO: test objectWithNoDeclaredProps - } - - /** - * Test the property 'objectWithNoDeclaredPropsNullable' - */ - @Test - public void objectWithNoDeclaredPropsNullableTest() { - // TODO: test objectWithNoDeclaredPropsNullable - } - - /** - * Test the property 'anyTypeProp' - */ - @Test - public void anyTypePropTest() { - // TODO: test anyTypeProp - } - - /** - * Test the property 'anyTypePropNullable' - */ - @Test - public void anyTypePropNullableTest() { - // TODO: test anyTypePropNullable - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/WhaleTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/WhaleTest.java deleted file mode 100644 index 82d2bba7a4..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/WhaleTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Whale - */ -public class WhaleTest { - private final Whale model = new Whale(); - - /** - * Model tests for Whale - */ - @Test - public void testWhale() { - // TODO: test Whale - } - - /** - * Test the property 'hasBaleen' - */ - @Test - public void hasBaleenTest() { - // TODO: test hasBaleen - } - - /** - * Test the property 'hasTeeth' - */ - @Test - public void hasTeethTest() { - // TODO: test hasTeeth - } - - /** - * Test the property 'className' - */ - @Test - public void classNameTest() { - // TODO: test className - } - -} diff --git a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ZebraTest.java b/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ZebraTest.java deleted file mode 100644 index aa8af2090f..0000000000 --- a/samples/openapi3/client/petstore/java/native/src/test/java/org/openapitools/client/model/ZebraTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package org.openapitools.client.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.Map; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - - -/** - * Model tests for Zebra - */ -public class ZebraTest { - private final Zebra model = new Zebra(); - - /** - * Model tests for Zebra - */ - @Test - public void testZebra() { - // TODO: test Zebra - } - - /** - * Test the property 'type' - */ - @Test - public void typeTest() { - // TODO: test type - } - - /** - * Test the property 'className' - */ - @Test - public void classNameTest() { - // TODO: test className - } - -} diff --git a/samples/openapi3/client/petstore/python-experimental/.gitignore b/samples/openapi3/client/petstore/python-experimental/.gitignore deleted file mode 100644 index a62e8aba43..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/.gitignore +++ /dev/null @@ -1,67 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt -dev-requirements.txt.log - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ -venv/ -.venv/ -.python-version -.pytest_cache - -# Translations -*.mo -*.pot - -# Django stuff: -*.log - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -#Ipython Notebook -.ipynb_checkpoints diff --git a/samples/openapi3/client/petstore/python-experimental/.gitlab-ci.yml b/samples/openapi3/client/petstore/python-experimental/.gitlab-ci.yml deleted file mode 100644 index 611e425676..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/.gitlab-ci.yml +++ /dev/null @@ -1,24 +0,0 @@ -# ref: https://docs.gitlab.com/ee/ci/README.html - -stages: - - test - -.tests: - stage: test - script: - - pip install -r requirements.txt - - pip install -r test-requirements.txt - - pytest --cov=petstore_api - -test-3.5: - extends: .tests - image: python:3.5-alpine -test-3.6: - extends: .tests - image: python:3.6-alpine -test-3.7: - extends: .tests - image: python:3.7-alpine -test-3.8: - extends: .tests - image: python:3.8-alpine diff --git a/samples/openapi3/client/petstore/python-experimental/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-experimental/.openapi-generator/FILES deleted file mode 100644 index af47fddb53..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/.openapi-generator/FILES +++ /dev/null @@ -1,258 +0,0 @@ -.gitignore -.gitlab-ci.yml -.travis.yml -README.md -docs/AdditionalPropertiesClass.md -docs/AdditionalPropertiesWithArrayOfEnums.md -docs/Address.md -docs/Animal.md -docs/AnimalFarm.md -docs/AnotherFakeApi.md -docs/AnyTypeNotString.md -docs/ApiResponse.md -docs/Apple.md -docs/AppleReq.md -docs/ArrayHoldingAnyType.md -docs/ArrayOfArrayOfNumberOnly.md -docs/ArrayOfEnums.md -docs/ArrayOfNumberOnly.md -docs/ArrayTest.md -docs/ArrayWithValidationsInItems.md -docs/Banana.md -docs/BananaReq.md -docs/Bar.md -docs/BasquePig.md -docs/Boolean.md -docs/BooleanEnum.md -docs/Capitalization.md -docs/Cat.md -docs/Category.md -docs/ChildCat.md -docs/ClassModel.md -docs/Client.md -docs/ComplexQuadrilateral.md -docs/ComposedAnyOfDifferentTypesNoValidations.md -docs/ComposedArray.md -docs/ComposedBool.md -docs/ComposedNone.md -docs/ComposedNumber.md -docs/ComposedObject.md -docs/ComposedOneOfDifferentTypes.md -docs/ComposedString.md -docs/Currency.md -docs/DanishPig.md -docs/DateTimeTest.md -docs/DateTimeWithValidations.md -docs/DateWithValidations.md -docs/DecimalPayload.md -docs/DefaultApi.md -docs/Dog.md -docs/Drawing.md -docs/EnumArrays.md -docs/EnumClass.md -docs/EnumTest.md -docs/EquilateralTriangle.md -docs/FakeApi.md -docs/FakeClassnameTags123Api.md -docs/File.md -docs/FileSchemaTestClass.md -docs/Foo.md -docs/FormatTest.md -docs/Fruit.md -docs/FruitReq.md -docs/GmFruit.md -docs/GrandparentAnimal.md -docs/HasOnlyReadOnly.md -docs/HealthCheckResult.md -docs/IntegerEnum.md -docs/IntegerEnumBig.md -docs/IntegerEnumOneValue.md -docs/IntegerEnumWithDefaultValue.md -docs/IntegerMax10.md -docs/IntegerMin15.md -docs/IsoscelesTriangle.md -docs/Mammal.md -docs/MapTest.md -docs/MixedPropertiesAndAdditionalPropertiesClass.md -docs/Model200Response.md -docs/ModelReturn.md -docs/Money.md -docs/Name.md -docs/NoAdditionalProperties.md -docs/NullableClass.md -docs/NullableShape.md -docs/NullableString.md -docs/Number.md -docs/NumberOnly.md -docs/NumberWithValidations.md -docs/ObjectInterface.md -docs/ObjectModelWithRefProps.md -docs/ObjectWithDecimalProperties.md -docs/ObjectWithDifficultlyNamedProps.md -docs/ObjectWithInlineCompositionProperty.md -docs/ObjectWithValidations.md -docs/Order.md -docs/ParentPet.md -docs/Pet.md -docs/PetApi.md -docs/Pig.md -docs/Player.md -docs/Quadrilateral.md -docs/QuadrilateralInterface.md -docs/ReadOnlyFirst.md -docs/ScaleneTriangle.md -docs/Shape.md -docs/ShapeOrNull.md -docs/SimpleQuadrilateral.md -docs/SomeObject.md -docs/SpecialModelName.md -docs/StoreApi.md -docs/String.md -docs/StringBooleanMap.md -docs/StringEnum.md -docs/StringEnumWithDefaultValue.md -docs/StringWithValidation.md -docs/Tag.md -docs/Triangle.md -docs/TriangleInterface.md -docs/UUIDString.md -docs/User.md -docs/UserApi.md -docs/Whale.md -docs/Zebra.md -git_push.sh -petstore_api/__init__.py -petstore_api/api/__init__.py -petstore_api/api/another_fake_api.py -petstore_api/api/default_api.py -petstore_api/api/fake_api.py -petstore_api/api/fake_classname_tags123_api.py -petstore_api/api/pet_api.py -petstore_api/api/store_api.py -petstore_api/api/user_api.py -petstore_api/api_client.py -petstore_api/apis/__init__.py -petstore_api/configuration.py -petstore_api/exceptions.py -petstore_api/model/__init__.py -petstore_api/model/additional_properties_class.py -petstore_api/model/additional_properties_with_array_of_enums.py -petstore_api/model/address.py -petstore_api/model/animal.py -petstore_api/model/animal_farm.py -petstore_api/model/any_type_not_string.py -petstore_api/model/api_response.py -petstore_api/model/apple.py -petstore_api/model/apple_req.py -petstore_api/model/array_holding_any_type.py -petstore_api/model/array_of_array_of_number_only.py -petstore_api/model/array_of_enums.py -petstore_api/model/array_of_number_only.py -petstore_api/model/array_test.py -petstore_api/model/array_with_validations_in_items.py -petstore_api/model/banana.py -petstore_api/model/banana_req.py -petstore_api/model/bar.py -petstore_api/model/basque_pig.py -petstore_api/model/boolean.py -petstore_api/model/boolean_enum.py -petstore_api/model/capitalization.py -petstore_api/model/cat.py -petstore_api/model/category.py -petstore_api/model/child_cat.py -petstore_api/model/class_model.py -petstore_api/model/client.py -petstore_api/model/complex_quadrilateral.py -petstore_api/model/composed_any_of_different_types_no_validations.py -petstore_api/model/composed_array.py -petstore_api/model/composed_bool.py -petstore_api/model/composed_none.py -petstore_api/model/composed_number.py -petstore_api/model/composed_object.py -petstore_api/model/composed_one_of_different_types.py -petstore_api/model/composed_string.py -petstore_api/model/currency.py -petstore_api/model/danish_pig.py -petstore_api/model/date_time_test.py -petstore_api/model/date_time_with_validations.py -petstore_api/model/date_with_validations.py -petstore_api/model/decimal_payload.py -petstore_api/model/dog.py -petstore_api/model/drawing.py -petstore_api/model/enum_arrays.py -petstore_api/model/enum_class.py -petstore_api/model/enum_test.py -petstore_api/model/equilateral_triangle.py -petstore_api/model/file.py -petstore_api/model/file_schema_test_class.py -petstore_api/model/foo.py -petstore_api/model/format_test.py -petstore_api/model/fruit.py -petstore_api/model/fruit_req.py -petstore_api/model/gm_fruit.py -petstore_api/model/grandparent_animal.py -petstore_api/model/has_only_read_only.py -petstore_api/model/health_check_result.py -petstore_api/model/integer_enum.py -petstore_api/model/integer_enum_big.py -petstore_api/model/integer_enum_one_value.py -petstore_api/model/integer_enum_with_default_value.py -petstore_api/model/integer_max10.py -petstore_api/model/integer_min15.py -petstore_api/model/isosceles_triangle.py -petstore_api/model/mammal.py -petstore_api/model/map_test.py -petstore_api/model/mixed_properties_and_additional_properties_class.py -petstore_api/model/model200_response.py -petstore_api/model/model_return.py -petstore_api/model/money.py -petstore_api/model/name.py -petstore_api/model/no_additional_properties.py -petstore_api/model/nullable_class.py -petstore_api/model/nullable_shape.py -petstore_api/model/nullable_string.py -petstore_api/model/number.py -petstore_api/model/number_only.py -petstore_api/model/number_with_validations.py -petstore_api/model/object_interface.py -petstore_api/model/object_model_with_ref_props.py -petstore_api/model/object_with_decimal_properties.py -petstore_api/model/object_with_difficultly_named_props.py -petstore_api/model/object_with_inline_composition_property.py -petstore_api/model/object_with_validations.py -petstore_api/model/order.py -petstore_api/model/parent_pet.py -petstore_api/model/pet.py -petstore_api/model/pig.py -petstore_api/model/player.py -petstore_api/model/quadrilateral.py -petstore_api/model/quadrilateral_interface.py -petstore_api/model/read_only_first.py -petstore_api/model/scalene_triangle.py -petstore_api/model/shape.py -petstore_api/model/shape_or_null.py -petstore_api/model/simple_quadrilateral.py -petstore_api/model/some_object.py -petstore_api/model/special_model_name.py -petstore_api/model/string.py -petstore_api/model/string_boolean_map.py -petstore_api/model/string_enum.py -petstore_api/model/string_enum_with_default_value.py -petstore_api/model/string_with_validation.py -petstore_api/model/tag.py -petstore_api/model/triangle.py -petstore_api/model/triangle_interface.py -petstore_api/model/user.py -petstore_api/model/uuid_string.py -petstore_api/model/whale.py -petstore_api/model/zebra.py -petstore_api/models/__init__.py -petstore_api/rest.py -petstore_api/schemas.py -petstore_api/signing.py -requirements.txt -setup.cfg -setup.py -test-requirements.txt -test/__init__.py -tox.ini diff --git a/samples/openapi3/client/petstore/python-experimental/.travis.yml b/samples/openapi3/client/petstore/python-experimental/.travis.yml deleted file mode 100644 index f931f0f74b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -# ref: https://docs.travis-ci.com/user/languages/python -language: python -python: - - "3.5" - - "3.6" - - "3.7" - - "3.8" -# command to install dependencies -install: - - "pip install -r requirements.txt" - - "pip install -r test-requirements.txt" -# command to run tests -script: pytest --cov=petstore_api diff --git a/samples/openapi3/client/petstore/python-experimental/Makefile b/samples/openapi3/client/petstore/python-experimental/Makefile deleted file mode 100644 index 863c380ebe..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -REQUIREMENTS_FILE=dev-requirements.txt -REQUIREMENTS_OUT=dev-requirements.txt.log -SETUP_OUT=*.egg-info -VENV=venv - -clean: - rm -rf $(REQUIREMENTS_OUT) - rm -rf $(SETUP_OUT) - rm -rf $(VENV) - rm -rf .tox - rm -rf .coverage - find . -name "*.py[oc]" -delete - find . -name "__pycache__" -delete - -test: clean - bash ./test_python.sh \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-experimental/README.md b/samples/openapi3/client/petstore/python-experimental/README.md deleted file mode 100644 index 9f5d5132d2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/README.md +++ /dev/null @@ -1,324 +0,0 @@ -# petstore-api -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - -This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - -- API version: 1.0.0 -- Package version: 1.0.0 -- Build package: org.openapitools.codegen.languages.PythonExperimentalClientCodegen - -## Requirements. - -Python >=3.9 -v3.9 is needed so one can combine classmethod and property decorators to define -object schema properties as classes - -## Installation & Usage -### pip install - -If the python package is hosted on a repository, you can install directly using: - -```sh -pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git -``` -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) - -Then import the package: -```python -import petstore_api -``` - -### Setuptools - -Install via [Setuptools](http://pypi.python.org/pypi/setuptools). - -```sh -python setup.py install --user -``` -(or `sudo python setup.py install` to install the package for all users) - -Then import the package: -```python -import petstore_api -``` - -## Getting Started - -Please follow the [installation procedure](#installation--usage) and then run the following: - -```python -import datetimeimport datetimeimport datetimeimport datetimeimport datetimeimport datetimeimport datetime -import time -import petstore_api -from pprint import pprint -from petstore_api.api import another_fake_api -from petstore_api.model.client import Client -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = another_fake_api.AnotherFakeApi(api_client) - client = Client( - client="client_example", - ) # Client | client model - - try: - # To test special tags - api_response = api_instance.call_123_test_special_tags(client) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) -``` - -## Documentation for API Endpoints - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags -*DefaultApi* | [**foo_get**](docs/DefaultApi.md#foo_get) | **GET** /foo | -*FakeApi* | [**additional_properties_with_array_of_enums**](docs/FakeApi.md#additional_properties_with_array_of_enums) | **GET** /fake/additional-properties-with-array-of-enums | Additional Properties with Array of Enums -*FakeApi* | [**array_model**](docs/FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | -*FakeApi* | [**array_of_enums**](docs/FakeApi.md#array_of_enums) | **POST** /fake/refs/array-of-enums | Array of Enums -*FakeApi* | [**body_with_file_schema**](docs/FakeApi.md#body_with_file_schema) | **PUT** /fake/body-with-file-schema | -*FakeApi* | [**body_with_query_params**](docs/FakeApi.md#body_with_query_params) | **PUT** /fake/body-with-query-params | -*FakeApi* | [**boolean**](docs/FakeApi.md#boolean) | **POST** /fake/refs/boolean | -*FakeApi* | [**case_sensitive_params**](docs/FakeApi.md#case_sensitive_params) | **PUT** /fake/case-sensitive-params | -*FakeApi* | [**client_model**](docs/FakeApi.md#client_model) | **PATCH** /fake | To test \"client\" model -*FakeApi* | [**composed_one_of_different_types**](docs/FakeApi.md#composed_one_of_different_types) | **POST** /fake/refs/composed_one_of_number_with_validations | -*FakeApi* | [**delete_coffee**](docs/FakeApi.md#delete_coffee) | **DELETE** /fake/deleteCoffee/{id} | Delete coffee -*FakeApi* | [**endpoint_parameters**](docs/FakeApi.md#endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**enum_parameters**](docs/FakeApi.md#enum_parameters) | **GET** /fake | To test enum parameters -*FakeApi* | [**fake_health_get**](docs/FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint -*FakeApi* | [**group_parameters**](docs/FakeApi.md#group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**inline_additional_properties**](docs/FakeApi.md#inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**inline_composition**](docs/FakeApi.md#inline_composition) | **POST** /fake/inlineComposition/ | testing composed schemas at inline locations -*FakeApi* | [**json_form_data**](docs/FakeApi.md#json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data -*FakeApi* | [**json_with_charset**](docs/FakeApi.md#json_with_charset) | **POST** /fake/jsonWithCharset | json with charset tx and rx -*FakeApi* | [**mammal**](docs/FakeApi.md#mammal) | **POST** /fake/refs/mammal | -*FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | -*FakeApi* | [**object_in_query**](docs/FakeApi.md#object_in_query) | **GET** /fake/objInQuery | user list -*FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | -*FakeApi* | [**parameter_collisions**](docs/FakeApi.md#parameter_collisions) | **POST** /fake/parameterCollisions/{1}/{aB}/{Ab}/{self}/{A-B}/ | parameter collision case -*FakeApi* | [**query_parameter_collection_format**](docs/FakeApi.md#query_parameter_collection_format) | **PUT** /fake/test-query-paramters | -*FakeApi* | [**ref_object_in_query**](docs/FakeApi.md#ref_object_in_query) | **GET** /fake/refObjInQuery | user list -*FakeApi* | [**response_without_schema**](docs/FakeApi.md#response_without_schema) | **GET** /fake/responseWithoutSchema | receives a response without schema -*FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | -*FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | -*FakeApi* | [**upload_download_file**](docs/FakeApi.md#upload_download_file) | **POST** /fake/uploadDownloadFile | uploads a file and downloads a file using application/octet-stream -*FakeApi* | [**upload_file**](docs/FakeApi.md#upload_file) | **POST** /fake/uploadFile | uploads a file using multipart/form-data -*FakeApi* | [**upload_files**](docs/FakeApi.md#upload_files) | **POST** /fake/uploadFiles | uploads files using multipart/form-data -*FakeClassnameTags123Api* | [**classname**](docs/FakeClassnameTags123Api.md#classname) | **PATCH** /fake_classname_test | To test class name in snake case -*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet -*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**upload_file_with_required_file**](docs/PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -*PetApi* | [**upload_image**](docs/PetApi.md#upload_image) | **POST** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet -*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user -*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user -*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name -*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system -*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user - -## Documentation For Models - - - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - - [AdditionalPropertiesWithArrayOfEnums](docs/AdditionalPropertiesWithArrayOfEnums.md) - - [Address](docs/Address.md) - - [Animal](docs/Animal.md) - - [AnimalFarm](docs/AnimalFarm.md) - - [AnyTypeNotString](docs/AnyTypeNotString.md) - - [ApiResponse](docs/ApiResponse.md) - - [Apple](docs/Apple.md) - - [AppleReq](docs/AppleReq.md) - - [ArrayHoldingAnyType](docs/ArrayHoldingAnyType.md) - - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - - [ArrayOfEnums](docs/ArrayOfEnums.md) - - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - - [ArrayTest](docs/ArrayTest.md) - - [ArrayWithValidationsInItems](docs/ArrayWithValidationsInItems.md) - - [Banana](docs/Banana.md) - - [BananaReq](docs/BananaReq.md) - - [Bar](docs/Bar.md) - - [BasquePig](docs/BasquePig.md) - - [Boolean](docs/Boolean.md) - - [BooleanEnum](docs/BooleanEnum.md) - - [Capitalization](docs/Capitalization.md) - - [Cat](docs/Cat.md) - - [Category](docs/Category.md) - - [ChildCat](docs/ChildCat.md) - - [ClassModel](docs/ClassModel.md) - - [Client](docs/Client.md) - - [ComplexQuadrilateral](docs/ComplexQuadrilateral.md) - - [ComposedAnyOfDifferentTypesNoValidations](docs/ComposedAnyOfDifferentTypesNoValidations.md) - - [ComposedArray](docs/ComposedArray.md) - - [ComposedBool](docs/ComposedBool.md) - - [ComposedNone](docs/ComposedNone.md) - - [ComposedNumber](docs/ComposedNumber.md) - - [ComposedObject](docs/ComposedObject.md) - - [ComposedOneOfDifferentTypes](docs/ComposedOneOfDifferentTypes.md) - - [ComposedString](docs/ComposedString.md) - - [Currency](docs/Currency.md) - - [DanishPig](docs/DanishPig.md) - - [DateTimeTest](docs/DateTimeTest.md) - - [DateTimeWithValidations](docs/DateTimeWithValidations.md) - - [DateWithValidations](docs/DateWithValidations.md) - - [DecimalPayload](docs/DecimalPayload.md) - - [Dog](docs/Dog.md) - - [Drawing](docs/Drawing.md) - - [EnumArrays](docs/EnumArrays.md) - - [EnumClass](docs/EnumClass.md) - - [EnumTest](docs/EnumTest.md) - - [EquilateralTriangle](docs/EquilateralTriangle.md) - - [File](docs/File.md) - - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - - [Foo](docs/Foo.md) - - [FormatTest](docs/FormatTest.md) - - [Fruit](docs/Fruit.md) - - [FruitReq](docs/FruitReq.md) - - [GmFruit](docs/GmFruit.md) - - [GrandparentAnimal](docs/GrandparentAnimal.md) - - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - - [HealthCheckResult](docs/HealthCheckResult.md) - - [IntegerEnum](docs/IntegerEnum.md) - - [IntegerEnumBig](docs/IntegerEnumBig.md) - - [IntegerEnumOneValue](docs/IntegerEnumOneValue.md) - - [IntegerEnumWithDefaultValue](docs/IntegerEnumWithDefaultValue.md) - - [IntegerMax10](docs/IntegerMax10.md) - - [IntegerMin15](docs/IntegerMin15.md) - - [IsoscelesTriangle](docs/IsoscelesTriangle.md) - - [Mammal](docs/Mammal.md) - - [MapTest](docs/MapTest.md) - - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - - [Model200Response](docs/Model200Response.md) - - [ModelReturn](docs/ModelReturn.md) - - [Money](docs/Money.md) - - [Name](docs/Name.md) - - [NoAdditionalProperties](docs/NoAdditionalProperties.md) - - [NullableClass](docs/NullableClass.md) - - [NullableShape](docs/NullableShape.md) - - [NullableString](docs/NullableString.md) - - [Number](docs/Number.md) - - [NumberOnly](docs/NumberOnly.md) - - [NumberWithValidations](docs/NumberWithValidations.md) - - [ObjectInterface](docs/ObjectInterface.md) - - [ObjectModelWithRefProps](docs/ObjectModelWithRefProps.md) - - [ObjectWithDecimalProperties](docs/ObjectWithDecimalProperties.md) - - [ObjectWithDifficultlyNamedProps](docs/ObjectWithDifficultlyNamedProps.md) - - [ObjectWithInlineCompositionProperty](docs/ObjectWithInlineCompositionProperty.md) - - [ObjectWithValidations](docs/ObjectWithValidations.md) - - [Order](docs/Order.md) - - [ParentPet](docs/ParentPet.md) - - [Pet](docs/Pet.md) - - [Pig](docs/Pig.md) - - [Player](docs/Player.md) - - [Quadrilateral](docs/Quadrilateral.md) - - [QuadrilateralInterface](docs/QuadrilateralInterface.md) - - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - - [ScaleneTriangle](docs/ScaleneTriangle.md) - - [Shape](docs/Shape.md) - - [ShapeOrNull](docs/ShapeOrNull.md) - - [SimpleQuadrilateral](docs/SimpleQuadrilateral.md) - - [SomeObject](docs/SomeObject.md) - - [SpecialModelName](docs/SpecialModelName.md) - - [String](docs/String.md) - - [StringBooleanMap](docs/StringBooleanMap.md) - - [StringEnum](docs/StringEnum.md) - - [StringEnumWithDefaultValue](docs/StringEnumWithDefaultValue.md) - - [StringWithValidation](docs/StringWithValidation.md) - - [Tag](docs/Tag.md) - - [Triangle](docs/Triangle.md) - - [TriangleInterface](docs/TriangleInterface.md) - - [UUIDString](docs/UUIDString.md) - - [User](docs/User.md) - - [Whale](docs/Whale.md) - - [Zebra](docs/Zebra.md) - -## Documentation For Authorization - - -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - - -## api_key_query - -- **Type**: API key -- **API key parameter name**: api_key_query -- **Location**: URL query string - - -## bearer_test - -- **Type**: Bearer authentication (JWT) - - -## http_basic_test - -- **Type**: HTTP basic authentication - - -## http_signature_test - -- **Type**: HTTP signature authentication - - Authentication schemes defined for the API: -## petstore_auth - -- **Type**: OAuth -- **Flow**: implicit -- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog -- **Scopes**: - - **write:pets**: modify pets in your account - - **read:pets**: read your pets - - -## Author - - - - - - - - - -## Notes for Large OpenAPI documents -If the OpenAPI document is large, imports in petstore_api.apis and petstore_api.models may fail with a -RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: - -Solution 1: -Use specific imports for apis and models like: -- `from petstore_api.api.default_api import DefaultApi` -- `from petstore_api.model.pet import Pet` - -Solution 1: -Before importing the package, adjust the maximum recursion limit as shown below: -``` -import sys -sys.setrecursionlimit(1500) -import petstore_api -from petstore_api.apis import * -from petstore_api.models import * -``` diff --git a/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md deleted file mode 100644 index 9e727e732d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md +++ /dev/null @@ -1,17 +0,0 @@ -# AdditionalPropertiesClass - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**map_property** | **{str: (str,)}** | | [optional] -**map_of_map_property** | **{str: ({str: (str,)},)}** | | [optional] -**anytype_1** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**map_with_undeclared_properties_anytype_1** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** | | [optional] -**map_with_undeclared_properties_anytype_2** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** | | [optional] -**map_with_undeclared_properties_anytype_3** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** | | [optional] -**empty_map** | **{str: typing.Any}** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] -**map_with_undeclared_properties_string** | **{str: (str,)}** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesWithArrayOfEnums.md b/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesWithArrayOfEnums.md deleted file mode 100644 index 81d4ee5540..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesWithArrayOfEnums.md +++ /dev/null @@ -1,9 +0,0 @@ -# AdditionalPropertiesWithArrayOfEnums - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **[EnumClass]** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Address.md b/samples/openapi3/client/petstore/python-experimental/docs/Address.md deleted file mode 100644 index a6060817c8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Address.md +++ /dev/null @@ -1,9 +0,0 @@ -# Address - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **int** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Animal.md b/samples/openapi3/client/petstore/python-experimental/docs/Animal.md deleted file mode 100644 index 8d43981dc8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Animal.md +++ /dev/null @@ -1,11 +0,0 @@ -# Animal - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**className** | **str** | | -**color** | **str** | | [optional] if omitted the server will use the default value of "red" -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/AnimalFarm.md b/samples/openapi3/client/petstore/python-experimental/docs/AnimalFarm.md deleted file mode 100644 index 04db36a075..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/AnimalFarm.md +++ /dev/null @@ -1,8 +0,0 @@ -# AnimalFarm - -Type | Description | Notes -------------- | ------------- | ------------- -**[Animal]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/AnotherFakeApi.md b/samples/openapi3/client/petstore/python-experimental/docs/AnotherFakeApi.md deleted file mode 100644 index 163f2000ca..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/AnotherFakeApi.md +++ /dev/null @@ -1,94 +0,0 @@ -# petstore_api.AnotherFakeApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**call_123_test_special_tags**](AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags - -# **call_123_test_special_tags** -> Client call_123_test_special_tags(client) - -To test special tags - -To test special tags and operation ID starting with number - -### Example - -```python -import petstore_api -from petstore_api.api import another_fake_api -from petstore_api.model.client import Client -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = another_fake_api.AnotherFakeApi(api_client) - - # example passing only required values which don't have defaults set - body = Client( - client="client_example", - ) - try: - # To test special tags - api_response = api_instance.call_123_test_special_tags( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Client**](Client.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Client**](Client.md) | | - - - -[**Client**](Client.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/AnyTypeNotString.md b/samples/openapi3/client/petstore/python-experimental/docs/AnyTypeNotString.md deleted file mode 100644 index 6ec0912a0b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/AnyTypeNotString.md +++ /dev/null @@ -1,9 +0,0 @@ -# AnyTypeNotString - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ApiResponse.md b/samples/openapi3/client/petstore/python-experimental/docs/ApiResponse.md deleted file mode 100644 index 6206bcbe61..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ApiResponse.md +++ /dev/null @@ -1,12 +0,0 @@ -# ApiResponse - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**code** | **int** | | [optional] -**type** | **str** | | [optional] -**message** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Apple.md b/samples/openapi3/client/petstore/python-experimental/docs/Apple.md deleted file mode 100644 index 93f59b3a2e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Apple.md +++ /dev/null @@ -1,11 +0,0 @@ -# Apple - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**cultivar** | **str** | | -**origin** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/AppleReq.md b/samples/openapi3/client/petstore/python-experimental/docs/AppleReq.md deleted file mode 100644 index 1dde25261b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/AppleReq.md +++ /dev/null @@ -1,10 +0,0 @@ -# AppleReq - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**cultivar** | **str** | | -**mealy** | **bool** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ArrayHoldingAnyType.md b/samples/openapi3/client/petstore/python-experimental/docs/ArrayHoldingAnyType.md deleted file mode 100644 index db0bfa793a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ArrayHoldingAnyType.md +++ /dev/null @@ -1,8 +0,0 @@ -# ArrayHoldingAnyType - -Type | Description | Notes -------------- | ------------- | ------------- -**[bool, date, datetime, dict, float, int, list, str, none_type]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfArrayOfNumberOnly.md deleted file mode 100644 index 5b5c89bfd6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfArrayOfNumberOnly.md +++ /dev/null @@ -1,10 +0,0 @@ -# ArrayOfArrayOfNumberOnly - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**ArrayArrayNumber** | **[[int, float]]** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfEnums.md b/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfEnums.md deleted file mode 100644 index ce8778c78f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfEnums.md +++ /dev/null @@ -1,8 +0,0 @@ -# ArrayOfEnums - -Type | Description | Notes -------------- | ------------- | ------------- -**[StringEnum]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfNumberOnly.md deleted file mode 100644 index 2fa514a786..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfNumberOnly.md +++ /dev/null @@ -1,10 +0,0 @@ -# ArrayOfNumberOnly - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**ArrayNumber** | **[int, float]** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ArrayTest.md b/samples/openapi3/client/petstore/python-experimental/docs/ArrayTest.md deleted file mode 100644 index b84215f20a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ArrayTest.md +++ /dev/null @@ -1,12 +0,0 @@ -# ArrayTest - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**array_of_string** | **[str]** | | [optional] -**array_array_of_integer** | **[[int]]** | | [optional] -**array_array_of_model** | **[[ReadOnlyFirst]]** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ArrayWithValidationsInItems.md b/samples/openapi3/client/petstore/python-experimental/docs/ArrayWithValidationsInItems.md deleted file mode 100644 index d19d241bfe..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ArrayWithValidationsInItems.md +++ /dev/null @@ -1,8 +0,0 @@ -# ArrayWithValidationsInItems - -Type | Description | Notes -------------- | ------------- | ------------- -**[int]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Banana.md b/samples/openapi3/client/petstore/python-experimental/docs/Banana.md deleted file mode 100644 index 11b9e97a5c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Banana.md +++ /dev/null @@ -1,10 +0,0 @@ -# Banana - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**lengthCm** | **int, float** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/BananaReq.md b/samples/openapi3/client/petstore/python-experimental/docs/BananaReq.md deleted file mode 100644 index 68959cfbd6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/BananaReq.md +++ /dev/null @@ -1,10 +0,0 @@ -# BananaReq - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**lengthCm** | **int, float** | | -**sweet** | **bool** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Bar.md b/samples/openapi3/client/petstore/python-experimental/docs/Bar.md deleted file mode 100644 index f6e0141c5f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Bar.md +++ /dev/null @@ -1,8 +0,0 @@ -# Bar - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | defaults to "bar" - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/BasquePig.md b/samples/openapi3/client/petstore/python-experimental/docs/BasquePig.md deleted file mode 100644 index 76fa224a37..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/BasquePig.md +++ /dev/null @@ -1,10 +0,0 @@ -# BasquePig - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**className** | **str** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Boolean.md b/samples/openapi3/client/petstore/python-experimental/docs/Boolean.md deleted file mode 100644 index 9e64a63c8e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Boolean.md +++ /dev/null @@ -1,8 +0,0 @@ -# Boolean - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/BooleanEnum.md b/samples/openapi3/client/petstore/python-experimental/docs/BooleanEnum.md deleted file mode 100644 index bd60b09809..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/BooleanEnum.md +++ /dev/null @@ -1,8 +0,0 @@ -# BooleanEnum - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | must be one of [BoolClass.TRUE, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Capitalization.md b/samples/openapi3/client/petstore/python-experimental/docs/Capitalization.md deleted file mode 100644 index a9f4f6ecda..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Capitalization.md +++ /dev/null @@ -1,15 +0,0 @@ -# Capitalization - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**smallCamel** | **str** | | [optional] -**CapitalCamel** | **str** | | [optional] -**small_Snake** | **str** | | [optional] -**Capital_Snake** | **str** | | [optional] -**SCA_ETH_Flow_Points** | **str** | | [optional] -**ATT_NAME** | **str** | Name of the pet | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Cat.md b/samples/openapi3/client/petstore/python-experimental/docs/Cat.md deleted file mode 100644 index a6d67ac801..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Cat.md +++ /dev/null @@ -1,9 +0,0 @@ -# Cat - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Category.md b/samples/openapi3/client/petstore/python-experimental/docs/Category.md deleted file mode 100644 index a847da44a1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Category.md +++ /dev/null @@ -1,11 +0,0 @@ -# Category - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **int** | | [optional] -**name** | **str** | | if omitted the server will use the default value of "default-name" -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ChildCat.md b/samples/openapi3/client/petstore/python-experimental/docs/ChildCat.md deleted file mode 100644 index 08b6b3c1cb..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ChildCat.md +++ /dev/null @@ -1,9 +0,0 @@ -# ChildCat - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ClassModel.md b/samples/openapi3/client/petstore/python-experimental/docs/ClassModel.md deleted file mode 100644 index 97d387878b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ClassModel.md +++ /dev/null @@ -1,12 +0,0 @@ -# ClassModel - -Model for testing model with \"_class\" property - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**_class** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Client.md b/samples/openapi3/client/petstore/python-experimental/docs/Client.md deleted file mode 100644 index 7c0ad6e973..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Client.md +++ /dev/null @@ -1,10 +0,0 @@ -# Client - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**client** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ComplexQuadrilateral.md b/samples/openapi3/client/petstore/python-experimental/docs/ComplexQuadrilateral.md deleted file mode 100644 index 0c647b1689..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ComplexQuadrilateral.md +++ /dev/null @@ -1,9 +0,0 @@ -# ComplexQuadrilateral - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ComposedAnyOfDifferentTypesNoValidations.md b/samples/openapi3/client/petstore/python-experimental/docs/ComposedAnyOfDifferentTypesNoValidations.md deleted file mode 100644 index 3dad57b962..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ComposedAnyOfDifferentTypesNoValidations.md +++ /dev/null @@ -1,9 +0,0 @@ -# ComposedAnyOfDifferentTypesNoValidations - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ComposedArray.md b/samples/openapi3/client/petstore/python-experimental/docs/ComposedArray.md deleted file mode 100644 index 6f0ebdc39e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ComposedArray.md +++ /dev/null @@ -1,8 +0,0 @@ -# ComposedArray - -Type | Description | Notes -------------- | ------------- | ------------- -**[bool, date, datetime, dict, float, int, list, str, none_type]** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ComposedBool.md b/samples/openapi3/client/petstore/python-experimental/docs/ComposedBool.md deleted file mode 100644 index 64ba095ebe..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ComposedBool.md +++ /dev/null @@ -1,8 +0,0 @@ -# ComposedBool - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ComposedNone.md b/samples/openapi3/client/petstore/python-experimental/docs/ComposedNone.md deleted file mode 100644 index f295563e70..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ComposedNone.md +++ /dev/null @@ -1,8 +0,0 @@ -# ComposedNone - -Type | Description | Notes -------------- | ------------- | ------------- -**none_type** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ComposedNumber.md b/samples/openapi3/client/petstore/python-experimental/docs/ComposedNumber.md deleted file mode 100644 index 4c52af546f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ComposedNumber.md +++ /dev/null @@ -1,8 +0,0 @@ -# ComposedNumber - -Type | Description | Notes -------------- | ------------- | ------------- -**float** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ComposedObject.md b/samples/openapi3/client/petstore/python-experimental/docs/ComposedObject.md deleted file mode 100644 index 3939050270..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ComposedObject.md +++ /dev/null @@ -1,9 +0,0 @@ -# ComposedObject - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ComposedOneOfDifferentTypes.md b/samples/openapi3/client/petstore/python-experimental/docs/ComposedOneOfDifferentTypes.md deleted file mode 100644 index 59ed1efabc..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ComposedOneOfDifferentTypes.md +++ /dev/null @@ -1,11 +0,0 @@ -# ComposedOneOfDifferentTypes - -this is a model that allows payloads of type object or number - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ComposedString.md b/samples/openapi3/client/petstore/python-experimental/docs/ComposedString.md deleted file mode 100644 index 37b16f50b4..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ComposedString.md +++ /dev/null @@ -1,8 +0,0 @@ -# ComposedString - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Currency.md b/samples/openapi3/client/petstore/python-experimental/docs/Currency.md deleted file mode 100644 index 9811a54c6e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Currency.md +++ /dev/null @@ -1,8 +0,0 @@ -# Currency - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | must be one of ["eur", "usd", ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/DanishPig.md b/samples/openapi3/client/petstore/python-experimental/docs/DanishPig.md deleted file mode 100644 index f239dc9731..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/DanishPig.md +++ /dev/null @@ -1,10 +0,0 @@ -# DanishPig - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**className** | **str** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/DateTimeTest.md b/samples/openapi3/client/petstore/python-experimental/docs/DateTimeTest.md deleted file mode 100644 index 4dd977eac9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/DateTimeTest.md +++ /dev/null @@ -1,8 +0,0 @@ -# DateTimeTest - -Type | Description | Notes -------------- | ------------- | ------------- -**datetime** | | defaults to 2010-01-01T10:10:10.000111+01:00 - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/DateTimeWithValidations.md b/samples/openapi3/client/petstore/python-experimental/docs/DateTimeWithValidations.md deleted file mode 100644 index bb2e7e17e7..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/DateTimeWithValidations.md +++ /dev/null @@ -1,8 +0,0 @@ -# DateTimeWithValidations - -Type | Description | Notes -------------- | ------------- | ------------- -**datetime** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/DateWithValidations.md b/samples/openapi3/client/petstore/python-experimental/docs/DateWithValidations.md deleted file mode 100644 index bce951bc5b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/DateWithValidations.md +++ /dev/null @@ -1,8 +0,0 @@ -# DateWithValidations - -Type | Description | Notes -------------- | ------------- | ------------- -**date** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/DecimalPayload.md b/samples/openapi3/client/petstore/python-experimental/docs/DecimalPayload.md deleted file mode 100644 index 2e0821dd05..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/DecimalPayload.md +++ /dev/null @@ -1,8 +0,0 @@ -# DecimalPayload - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/DefaultApi.md b/samples/openapi3/client/petstore/python-experimental/docs/DefaultApi.md deleted file mode 100644 index c001abdb9f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/DefaultApi.md +++ /dev/null @@ -1,72 +0,0 @@ -# petstore_api.DefaultApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**foo_get**](DefaultApi.md#foo_get) | **GET** /foo | - -# **foo_get** -> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} foo_get() - - - -### Example - -```python -import petstore_api -from petstore_api.api import default_api -from petstore_api.model.foo import Foo -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = default_api.DefaultApi(api_client) - - # example, this endpoint has no required or optional parameters - try: - api_response = api_instance.foo_get() - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling DefaultApi->foo_get: %s\n" % e) -``` -### Parameters -This endpoint does not need any parameter. - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -default | ApiResponseForDefault | response - -#### ApiResponseForDefault -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor0ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor0ResponseBodyApplicationJson - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**string** | [**Foo**](Foo.md) | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - - -**{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Dog.md b/samples/openapi3/client/petstore/python-experimental/docs/Dog.md deleted file mode 100644 index 851567bc58..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Dog.md +++ /dev/null @@ -1,9 +0,0 @@ -# Dog - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Drawing.md b/samples/openapi3/client/petstore/python-experimental/docs/Drawing.md deleted file mode 100644 index e535601a73..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Drawing.md +++ /dev/null @@ -1,13 +0,0 @@ -# Drawing - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**mainShape** | [**Shape**](Shape.md) | | [optional] -**shapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] -**nullableShape** | [**NullableShape**](NullableShape.md) | | [optional] -**shapes** | **[Shape]** | | [optional] -**any string name** | **Fruit** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/EnumArrays.md b/samples/openapi3/client/petstore/python-experimental/docs/EnumArrays.md deleted file mode 100644 index 78ecdb677e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/EnumArrays.md +++ /dev/null @@ -1,11 +0,0 @@ -# EnumArrays - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**just_symbol** | **str** | | [optional] -**array_enum** | **[str]** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/EnumClass.md b/samples/openapi3/client/petstore/python-experimental/docs/EnumClass.md deleted file mode 100644 index 1399e59181..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/EnumClass.md +++ /dev/null @@ -1,8 +0,0 @@ -# EnumClass - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/EnumTest.md b/samples/openapi3/client/petstore/python-experimental/docs/EnumTest.md deleted file mode 100644 index e720f3bf92..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/EnumTest.md +++ /dev/null @@ -1,18 +0,0 @@ -# EnumTest - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enum_string** | **str** | | [optional] -**enum_string_required** | **str** | | -**enum_integer** | **int** | | [optional] -**enum_number** | **int, float** | | [optional] -**stringEnum** | [**StringEnum**](StringEnum.md) | | [optional] -**IntegerEnum** | [**IntegerEnum**](IntegerEnum.md) | | [optional] -**StringEnumWithDefaultValue** | [**StringEnumWithDefaultValue**](StringEnumWithDefaultValue.md) | | [optional] -**IntegerEnumWithDefaultValue** | [**IntegerEnumWithDefaultValue**](IntegerEnumWithDefaultValue.md) | | [optional] -**IntegerEnumOneValue** | [**IntegerEnumOneValue**](IntegerEnumOneValue.md) | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/EquilateralTriangle.md b/samples/openapi3/client/petstore/python-experimental/docs/EquilateralTriangle.md deleted file mode 100644 index 834bcb30fd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/EquilateralTriangle.md +++ /dev/null @@ -1,9 +0,0 @@ -# EquilateralTriangle - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/FakeApi.md b/samples/openapi3/client/petstore/python-experimental/docs/FakeApi.md deleted file mode 100644 index cd82dc3587..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/FakeApi.md +++ /dev/null @@ -1,3132 +0,0 @@ -# petstore_api.FakeApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**additional_properties_with_array_of_enums**](FakeApi.md#additional_properties_with_array_of_enums) | **GET** /fake/additional-properties-with-array-of-enums | Additional Properties with Array of Enums -[**array_model**](FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | -[**array_of_enums**](FakeApi.md#array_of_enums) | **POST** /fake/refs/array-of-enums | Array of Enums -[**body_with_file_schema**](FakeApi.md#body_with_file_schema) | **PUT** /fake/body-with-file-schema | -[**body_with_query_params**](FakeApi.md#body_with_query_params) | **PUT** /fake/body-with-query-params | -[**boolean**](FakeApi.md#boolean) | **POST** /fake/refs/boolean | -[**case_sensitive_params**](FakeApi.md#case_sensitive_params) | **PUT** /fake/case-sensitive-params | -[**client_model**](FakeApi.md#client_model) | **PATCH** /fake | To test \"client\" model -[**composed_one_of_different_types**](FakeApi.md#composed_one_of_different_types) | **POST** /fake/refs/composed_one_of_number_with_validations | -[**delete_coffee**](FakeApi.md#delete_coffee) | **DELETE** /fake/deleteCoffee/{id} | Delete coffee -[**endpoint_parameters**](FakeApi.md#endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**enum_parameters**](FakeApi.md#enum_parameters) | **GET** /fake | To test enum parameters -[**fake_health_get**](FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint -[**group_parameters**](FakeApi.md#group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -[**inline_additional_properties**](FakeApi.md#inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -[**inline_composition**](FakeApi.md#inline_composition) | **POST** /fake/inlineComposition/ | testing composed schemas at inline locations -[**json_form_data**](FakeApi.md#json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data -[**json_with_charset**](FakeApi.md#json_with_charset) | **POST** /fake/jsonWithCharset | json with charset tx and rx -[**mammal**](FakeApi.md#mammal) | **POST** /fake/refs/mammal | -[**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | -[**object_in_query**](FakeApi.md#object_in_query) | **GET** /fake/objInQuery | user list -[**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | -[**parameter_collisions**](FakeApi.md#parameter_collisions) | **POST** /fake/parameterCollisions/{1}/{aB}/{Ab}/{self}/{A-B}/ | parameter collision case -[**query_parameter_collection_format**](FakeApi.md#query_parameter_collection_format) | **PUT** /fake/test-query-paramters | -[**ref_object_in_query**](FakeApi.md#ref_object_in_query) | **GET** /fake/refObjInQuery | user list -[**response_without_schema**](FakeApi.md#response_without_schema) | **GET** /fake/responseWithoutSchema | receives a response without schema -[**string**](FakeApi.md#string) | **POST** /fake/refs/string | -[**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | -[**upload_download_file**](FakeApi.md#upload_download_file) | **POST** /fake/uploadDownloadFile | uploads a file and downloads a file using application/octet-stream -[**upload_file**](FakeApi.md#upload_file) | **POST** /fake/uploadFile | uploads a file using multipart/form-data -[**upload_files**](FakeApi.md#upload_files) | **POST** /fake/uploadFiles | uploads files using multipart/form-data - -# **additional_properties_with_array_of_enums** -> AdditionalPropertiesWithArrayOfEnums additional_properties_with_array_of_enums() - -Additional Properties with Array of Enums - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = AdditionalPropertiesWithArrayOfEnums( - key=[ - EnumClass("-efg") - ], - ) - try: - # Additional Properties with Array of Enums - api_response = api_instance.additional_properties_with_array_of_enums( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->additional_properties_with_array_of_enums: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**AdditionalPropertiesWithArrayOfEnums**](AdditionalPropertiesWithArrayOfEnums.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Got object with additional properties with array of enums - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**AdditionalPropertiesWithArrayOfEnums**](AdditionalPropertiesWithArrayOfEnums.md) | | - - - -[**AdditionalPropertiesWithArrayOfEnums**](AdditionalPropertiesWithArrayOfEnums.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **array_model** -> AnimalFarm array_model() - - - -Test serialization of ArrayModel - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.animal_farm import AnimalFarm -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = AnimalFarm([ - Animal() - ]) - try: - api_response = api_instance.array_model( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->array_model: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**AnimalFarm**](AnimalFarm.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Output model - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**AnimalFarm**](AnimalFarm.md) | | - - - -[**AnimalFarm**](AnimalFarm.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **array_of_enums** -> ArrayOfEnums array_of_enums() - -Array of Enums - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.array_of_enums import ArrayOfEnums -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = ArrayOfEnums([ - StringEnum("placed") - ]) - try: - # Array of Enums - api_response = api_instance.array_of_enums( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->array_of_enums: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ArrayOfEnums**](ArrayOfEnums.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Got named array of enums - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ArrayOfEnums**](ArrayOfEnums.md) | | - - - -[**ArrayOfEnums**](ArrayOfEnums.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **body_with_file_schema** -> body_with_file_schema(file_schema_test_class) - - - -For this test, the body for this request much reference a schema named `File`. - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.file_schema_test_class import FileSchemaTestClass -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - body = FileSchemaTestClass( - file=File( - source_uri="source_uri_example", - ), - files=[ - File() - ], - ) - try: - api_response = api_instance.body_with_file_schema( - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->body_with_file_schema: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**FileSchemaTestClass**](FileSchemaTestClass.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Success - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **body_with_query_params** -> body_with_query_params(queryuser) - - - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.user import User -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - query_params = { - 'query': "query_example", - } - body = User( - id=1, - username="username_example", - first_name="first_name_example", - last_name="last_name_example", - email="email_example", - password="password_example", - phone="phone_example", - user_status=1, - object_with_no_declared_props=dict(), - object_with_no_declared_props_nullable=dict(), - any_type_prop=None, - any_type_except_null_prop=None, - any_type_prop_nullable=None, - ) - try: - api_response = api_instance.body_with_query_params( - query_params=query_params, - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->body_with_query_params: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -query_params | RequestQueryParams | | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**User**](User.md) | | - - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -query | QuerySchema | | - - -#### QuerySchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Success - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **boolean** -> bool boolean() - - - -Test serialization of outer boolean types - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = True - try: - api_response = api_instance.boolean( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->boolean: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Output boolean - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | - - -**bool** - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **case_sensitive_params** -> case_sensitive_params(some_varsome_var2some_var3) - - - -Ensures that original naming is used in endpoint params, that way we on't have collisions - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - query_params = { - 'someVar': "someVar_example", - 'SomeVar': "SomeVar_example", - 'some_var': "some_var_example", - } - try: - api_response = api_instance.case_sensitive_params( - query_params=query_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->case_sensitive_params: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -query_params | RequestQueryParams | | -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -someVar | SomeVarSchema | | -SomeVar | SomeVarSchema | | -some_var | SomeVarSchema | | - - -#### SomeVarSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### SomeVarSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### SomeVarSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Success - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **client_model** -> Client client_model(client) - -To test \"client\" model - -To test \"client\" model - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.client import Client -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - body = Client( - client="client_example", - ) - try: - # To test \"client\" model - api_response = api_instance.client_model( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->client_model: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Client**](Client.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Client**](Client.md) | | - - - -[**Client**](Client.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **composed_one_of_different_types** -> ComposedOneOfDifferentTypes composed_one_of_different_types() - - - -Test serialization of object with $refed properties - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = ComposedOneOfDifferentTypes(None) - try: - api_response = api_instance.composed_one_of_different_types( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->composed_one_of_different_types: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ComposedOneOfDifferentTypes**](ComposedOneOfDifferentTypes.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Output model - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ComposedOneOfDifferentTypes**](ComposedOneOfDifferentTypes.md) | | - - - -[**ComposedOneOfDifferentTypes**](ComposedOneOfDifferentTypes.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_coffee** -> delete_coffee(id) - -Delete coffee - -Delete the coffee identified by the given id, (delete without request body) - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'id': "id_example", - } - try: - # Delete coffee - api_response = api_instance.delete_coffee( - path_params=path_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->delete_coffee: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -path_params | RequestPathParams | | -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -id | IdSchema | | - -#### IdSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | OK -default | ApiResponseForDefault | Unexpected error - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseForDefault -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **endpoint_parameters** -> endpoint_parameters() - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -### Example - -* Basic Authentication (http_basic_test): -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure HTTP basic authorization: http_basic_test -configuration = petstore_api.Configuration( - username = 'YOUR_USERNAME', - password = 'YOUR_PASSWORD' -) -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = dict( - integer=10, - int32=20, - int64=1, - number=32.1, - _float=3.14, - double=67.8, - string="A", - pattern_without_delimiter="Aj", - byte='YQ==', - binary=open('/path/to/file', 'rb'), - date="1970-01-01", - date_time="2020-02-02T20:20:20.222220Z", - password="password_example", - callback="callback_example", - ) - try: - # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_response = api_instance.endpoint_parameters( - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->endpoint_parameters: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/x-www-form-urlencoded' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationXWwwFormUrlencoded - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | **int** | None | [optional] -**int32** | **int** | None | [optional] -**int64** | **int** | None | [optional] -**number** | **int, float** | None | -**float** | **int, float** | None | [optional] -**double** | **int, float** | None | -**string** | **str** | None | [optional] -**pattern_without_delimiter** | **str** | None | -**byte** | **str** | None | -**binary** | **file_type** | None | [optional] -**date** | **date** | None | [optional] -**dateTime** | **datetime** | None | [optional] if omitted the server will use the default value of 2010-02-01T10:20:10.11111+01:00 -**password** | **str** | None | [optional] -**callback** | **str** | None | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -400 | ApiResponseFor400 | Invalid username supplied -404 | ApiResponseFor404 | User not found - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor404 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -[http_basic_test](../README.md#http_basic_test) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **enum_parameters** -> enum_parameters() - -To test enum parameters - -To test enum parameters - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - query_params = { - 'enum_query_string_array': [ - "$" - ], - 'enum_query_string': "-efg", - 'enum_query_integer': 1, - 'enum_query_double': 1.1, - } - header_params = { - 'enum_header_string_array': [ - "$" - ], - 'enum_header_string': "-efg", - } - body = dict( - enum_form_string_array=[ - "$" - ], - enum_form_string="-efg", - ) - try: - # To test enum parameters - api_response = api_instance.enum_parameters( - query_params=query_params, - header_params=header_params, - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->enum_parameters: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] | optional, default is unset | -query_params | RequestQueryParams | | -header_params | RequestHeaderParams | | -content_type | str | optional, default is 'application/x-www-form-urlencoded' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationXWwwFormUrlencoded - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enum_form_string_array** | **[str]** | Form parameter enum test (string array) | [optional] -**enum_form_string** | **str** | Form parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -enum_query_string_array | EnumQueryStringArraySchema | | optional -enum_query_string | EnumQueryStringSchema | | optional -enum_query_integer | EnumQueryIntegerSchema | | optional -enum_query_double | EnumQueryDoubleSchema | | optional - - -#### EnumQueryStringArraySchema - -Type | Description | Notes -------------- | ------------- | ------------- -**[str]** | | - -#### EnumQueryStringSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] - -#### EnumQueryIntegerSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | must be one of [1, -2, ] - -#### EnumQueryDoubleSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int, float** | | must be one of [1.1, -1.2, ] - -### header_params -#### RequestHeaderParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -enum_header_string_array | EnumHeaderStringArraySchema | | optional -enum_header_string | EnumHeaderStringSchema | | optional - -#### EnumHeaderStringArraySchema - -Type | Description | Notes -------------- | ------------- | ------------- -**[str]** | | - -#### EnumHeaderStringSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -400 | ApiResponseFor400 | Invalid request -404 | ApiResponseFor404 | Not found - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor404 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **fake_health_get** -> HealthCheckResult fake_health_get() - -Health check endpoint - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.health_check_result import HealthCheckResult -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example, this endpoint has no required or optional parameters - try: - # Health check endpoint - api_response = api_instance.fake_health_get() - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->fake_health_get: %s\n" % e) -``` -### Parameters -This endpoint does not need any parameter. - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | The instance started successfully - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**HealthCheckResult**](HealthCheckResult.md) | | - - - -[**HealthCheckResult**](HealthCheckResult.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **group_parameters** -> group_parameters(required_string_grouprequired_boolean_grouprequired_int64_group) - -Fake endpoint to test group parameters (optional) - -Fake endpoint to test group parameters (optional) - -### Example - -* Bearer (JWT) Authentication (bearer_test): -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization (JWT): bearer_test -configuration = petstore_api.Configuration( - access_token = 'YOUR_BEARER_TOKEN' -) -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - query_params = { - 'required_string_group': 1, - 'required_int64_group': 1, - } - header_params = { - 'required_boolean_group': True, - } - try: - # Fake endpoint to test group parameters (optional) - api_response = api_instance.group_parameters( - query_params=query_params, - header_params=header_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->group_parameters: %s\n" % e) - - # example passing only optional values - query_params = { - 'required_string_group': 1, - 'required_int64_group': 1, - 'string_group': 1, - 'int64_group': 1, - } - header_params = { - 'required_boolean_group': True, - 'boolean_group': True, - } - try: - # Fake endpoint to test group parameters (optional) - api_response = api_instance.group_parameters( - query_params=query_params, - header_params=header_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->group_parameters: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -query_params | RequestQueryParams | | -header_params | RequestHeaderParams | | -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -required_string_group | RequiredStringGroupSchema | | -required_int64_group | RequiredInt64GroupSchema | | -string_group | StringGroupSchema | | optional -int64_group | Int64GroupSchema | | optional - - -#### RequiredStringGroupSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -#### RequiredInt64GroupSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -#### StringGroupSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -#### Int64GroupSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -### header_params -#### RequestHeaderParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -required_boolean_group | RequiredBooleanGroupSchema | | -boolean_group | BooleanGroupSchema | | optional - -#### RequiredBooleanGroupSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | - -#### BooleanGroupSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**bool** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -400 | ApiResponseFor400 | Someting wrong - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -[bearer_test](../README.md#bearer_test) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **inline_additional_properties** -> inline_additional_properties(request_body) - -test inline additionalProperties - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - body = dict( - "key": "key_example", - ) - try: - # test inline additionalProperties - api_response = api_instance.inline_additional_properties( - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->inline_additional_properties: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **str** | any string name can be used but the value must be the correct type | [optional] - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **inline_composition** -> bool, date, datetime, dict, float, int, list, str, none_type inline_composition() - -testing composed schemas at inline locations - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - query_params = { - 'compositionAtRoot': None, - 'compositionInProperty': dict( - some_prop=None, - ), - } - body = None - try: - # testing composed schemas at inline locations - api_response = api_instance.inline_composition( - query_params=query_params, - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->inline_composition: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | -query_params | RequestQueryParams | | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', 'multipart/form-data', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -#### SchemaForRequestBodyMultipartFormData - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**someProp** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -compositionAtRoot | CompositionAtRootSchema | | optional -compositionInProperty | CompositionInPropertySchema | | optional - - -#### CompositionAtRootSchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -#### CompositionInPropertySchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**someProp** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | success - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, SchemaFor200ResponseBodyMultipartFormData, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -#### SchemaFor200ResponseBodyMultipartFormData - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**someProp** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - - -**bool, date, datetime, dict, float, int, list, str, none_type** - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **json_form_data** -> json_form_data() - -test json serialization of form data - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = dict( - param="param_example", - param2="param2_example", - ) - try: - # test json serialization of form data - api_response = api_instance.json_form_data( - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->json_form_data: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/x-www-form-urlencoded' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationXWwwFormUrlencoded - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**param** | **str** | field1 | -**param2** | **str** | field2 | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **json_with_charset** -> bool, date, datetime, dict, float, int, list, str, none_type json_with_charset() - -json with charset tx and rx - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = None - try: - # json with charset tx and rx - api_response = api_instance.json_with_charset( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->json_with_charset: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json; charset=utf-8' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json; charset=utf-8', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJsonCharsetutf8 - -Type | Description | Notes -------------- | ------------- | ------------- -typing.Union[dict, frozendict, str, date, datetime, int, float, bool, Decimal, None, list, tuple, bytes] | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | success - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJsonCharsetutf8, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJsonCharsetutf8 - -Type | Description | Notes -------------- | ------------- | ------------- -typing.Union[dict, frozendict, str, date, datetime, int, float, bool, Decimal, None, list, tuple, bytes] | | - - -**bool, date, datetime, dict, float, int, list, str, none_type** - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **mammal** -> Mammal mammal(mammal) - - - -Test serialization of mammals - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.mammal import Mammal -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - body = Mammal( - has_baleen=True, - has_teeth=True, - class_name="whale", - ) - try: - api_response = api_instance.mammal( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->mammal: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Mammal**](Mammal.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Output mammal - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Mammal**](Mammal.md) | | - - - -[**Mammal**](Mammal.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **number_with_validations** -> NumberWithValidations number_with_validations() - - - -Test serialization of outer number types - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.number_with_validations import NumberWithValidations -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = NumberWithValidations(10) - try: - api_response = api_instance.number_with_validations( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->number_with_validations: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**NumberWithValidations**](NumberWithValidations.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Output number - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**NumberWithValidations**](NumberWithValidations.md) | | - - - -[**NumberWithValidations**](NumberWithValidations.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **object_in_query** -> object_in_query() - -user list - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - query_params = { - 'mapBean': dict( - keyword="keyword_example", - ), - } - try: - # user list - api_response = api_instance.object_in_query( - query_params=query_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->object_in_query: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -query_params | RequestQueryParams | | -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -mapBean | MapBeanSchema | | optional - - -#### MapBeanSchema - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**keyword** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | ok - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **object_model_with_ref_props** -> ObjectModelWithRefProps object_model_with_ref_props() - - - -Test serialization of object with $refed properties - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = ObjectModelWithRefProps( - my_number=NumberWithValidations(10), - my_string="my_string_example", - my_boolean=True, - ) - try: - api_response = api_instance.object_model_with_ref_props( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Output model - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) | | - - - -[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **parameter_collisions** -> bool, date, datetime, dict, float, int, list, str, none_type parameter_collisions(_3a_b5ab2_self3a_b6) - -parameter collision case - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - '1': "1_example", - 'aB': "aB_example", - 'Ab': "Ab_example", - 'self': "self_example", - 'A-B': "A-B_example", - } - query_params = { - } - cookie_params = { - } - header_params = { - } - try: - # parameter collision case - api_response = api_instance.parameter_collisions( - path_params=path_params, - query_params=query_params, - header_params=header_params, - cookie_params=cookie_params, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->parameter_collisions: %s\n" % e) - - # example passing only optional values - path_params = { - '1': "1_example", - 'aB': "aB_example", - 'Ab': "Ab_example", - 'self': "self_example", - 'A-B': "A-B_example", - } - query_params = { - '1': "1_example", - 'aB': "aB_example", - 'Ab': "Ab_example", - 'self': "self_example", - 'A-B': "A-B_example", - } - cookie_params = { - '1': "1_example", - 'aB': "aB_example", - 'Ab': "Ab_example", - 'self': "self_example", - 'A-B': "A-B_example", - } - header_params = { - '1': "1_example", - 'aB': "aB_example", - 'self': "self_example", - 'A-B': "A-B_example", - } - body = None - try: - # parameter collision case - api_response = api_instance.parameter_collisions( - path_params=path_params, - query_params=query_params, - header_params=header_params, - cookie_params=cookie_params, - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->parameter_collisions: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -query_params | RequestQueryParams | | -header_params | RequestHeaderParams | | -path_params | RequestPathParams | | -cookie_params | RequestCookieParams | | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -typing.Union[dict, frozendict, str, date, datetime, int, float, bool, Decimal, None, list, tuple, bytes] | | - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -1 | Model1Schema | | optional -aB | ABSchema | | optional -Ab | AbSchema | | optional -self | ModelSelfSchema | | optional -A-B | ABSchema | | optional - - -#### Model1Schema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ABSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### AbSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ModelSelfSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ABSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### header_params -#### RequestHeaderParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -1 | Model1Schema | | optional -aB | ABSchema | | optional -self | ModelSelfSchema | | optional -A-B | ABSchema | | optional - -#### Model1Schema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ABSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ModelSelfSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ABSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -1 | Model1Schema | | -aB | ABSchema | | -Ab | AbSchema | | -self | ModelSelfSchema | | -A-B | ABSchema | | - -#### Model1Schema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ABSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### AbSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ModelSelfSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ABSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### cookie_params -#### RequestCookieParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -1 | Model1Schema | | optional -aB | ABSchema | | optional -Ab | AbSchema | | optional -self | ModelSelfSchema | | optional -A-B | ABSchema | | optional - -#### Model1Schema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ABSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### AbSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ModelSelfSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### ABSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | success - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -typing.Union[dict, frozendict, str, date, datetime, int, float, bool, Decimal, None, list, tuple, bytes] | | - - -**bool, date, datetime, dict, float, int, list, str, none_type** - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **query_parameter_collection_format** -> query_parameter_collection_format(pipeioutilhttpurlcontextref_param) - - - -To test the collection format in query parameters - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.string_with_validation import StringWithValidation -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - query_params = { - 'pipe': [ - "pipe_example" - ], - 'ioutil': [ - "ioutil_example" - ], - 'http': [ - "http_example" - ], - 'url': [ - "url_example" - ], - 'context': [ - "context_example" - ], - 'refParam': StringWithValidation("refParam_example"), - } - try: - api_response = api_instance.query_parameter_collection_format( - query_params=query_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->query_parameter_collection_format: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -query_params | RequestQueryParams | | -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -pipe | PipeSchema | | -ioutil | IoutilSchema | | -http | HttpSchema | | -url | UrlSchema | | -context | ContextSchema | | -refParam | RefParamSchema | | - - -#### PipeSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**[str]** | | - -#### IoutilSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**[str]** | | - -#### HttpSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**[str]** | | - -#### UrlSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**[str]** | | - -#### ContextSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**[str]** | | - -#### RefParamSchema -Type | Description | Notes -------------- | ------------- | ------------- -[**StringWithValidation**](StringWithValidation.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Success - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **ref_object_in_query** -> ref_object_in_query() - -user list - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.foo import Foo -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - query_params = { - 'mapBean': Foo( - bar="bar", - ), - } - try: - # user list - api_response = api_instance.ref_object_in_query( - query_params=query_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->ref_object_in_query: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -query_params | RequestQueryParams | | -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -mapBean | MapBeanSchema | | optional - - -#### MapBeanSchema -Type | Description | Notes -------------- | ------------- | ------------- -[**Foo**](Foo.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | ok - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **response_without_schema** -> response_without_schema() - -receives a response without schema - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example, this endpoint has no required or optional parameters - try: - # receives a response without schema - api_response = api_instance.response_without_schema() - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->response_without_schema: %s\n" % e) -``` -### Parameters -This endpoint does not need any parameter. - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | contents without schema definition - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[Unset, Unset, ] | | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **string** -> str string() - - - -Test serialization of outer string types - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = "body_example" - try: - api_response = api_instance.string( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->string: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Output string - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - - -**str** - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **string_enum** -> StringEnum string_enum() - - - -Test serialization of outer enum - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.string_enum import StringEnum -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = StringEnum("placed") - try: - api_response = api_instance.string_enum( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->string_enum: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**StringEnum**](StringEnum.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Output enum - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**StringEnum**](StringEnum.md) | | - - - -[**StringEnum**](StringEnum.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **upload_download_file** -> file_type upload_download_file(body) - -uploads a file and downloads a file using application/octet-stream - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only required values which don't have defaults set - body = open('/path/to/file', 'rb') - try: - # uploads a file and downloads a file using application/octet-stream - api_response = api_instance.upload_download_file( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->upload_download_file: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationOctetStream] | required | -content_type | str | optional, default is 'application/octet-stream' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/octet-stream', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationOctetStream - -file to upload - -Type | Description | Notes -------------- | ------------- | ------------- -**file_type** | file to upload | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationOctetStream, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationOctetStream - -file to download - -Type | Description | Notes -------------- | ------------- | ------------- -**file_type** | file to download | - - -**file_type** - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **upload_file** -> ApiResponse upload_file() - -uploads a file using multipart/form-data - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.api_response import ApiResponse -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = dict( - additional_metadata="additional_metadata_example", - file=open('/path/to/file', 'rb'), - ) - try: - # uploads a file using multipart/form-data - api_response = api_instance.upload_file( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->upload_file: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | -content_type | str | optional, default is 'multipart/form-data' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyMultipartFormData - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **str** | Additional data to pass to server | [optional] -**file** | **file_type** | file to upload | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ApiResponse**](ApiResponse.md) | | - - - -[**ApiResponse**](ApiResponse.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **upload_files** -> ApiResponse upload_files() - -uploads files using multipart/form-data - -### Example - -```python -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.api_response import ApiResponse -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example passing only optional values - body = dict( - files=[ - open('/path/to/file', 'rb') - ], - ) - try: - # uploads files using multipart/form-data - api_response = api_instance.upload_files( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->upload_files: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | -content_type | str | optional, default is 'multipart/form-data' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyMultipartFormData - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**files** | **[file_type]** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ApiResponse**](ApiResponse.md) | | - - - -[**ApiResponse**](ApiResponse.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/python-experimental/docs/FakeClassnameTags123Api.md deleted file mode 100644 index 1a956e633d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/FakeClassnameTags123Api.md +++ /dev/null @@ -1,105 +0,0 @@ -# petstore_api.FakeClassnameTags123Api - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**classname**](FakeClassnameTags123Api.md#classname) | **PATCH** /fake_classname_test | To test class name in snake case - -# **classname** -> Client classname(client) - -To test class name in snake case - -To test class name in snake case - -### Example - -* Api Key Authentication (api_key_query): -```python -import petstore_api -from petstore_api.api import fake_classname_tags123_api -from petstore_api.model.client import Client -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure API key authorization: api_key_query -configuration.api_key['api_key_query'] = 'YOUR_API_KEY' - -# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -# configuration.api_key_prefix['api_key_query'] = 'Bearer' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_classname_tags123_api.FakeClassnameTags123Api(api_client) - - # example passing only required values which don't have defaults set - body = Client( - client="client_example", - ) - try: - # To test class name in snake case - api_response = api_instance.classname( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeClassnameTags123Api->classname: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Client**](Client.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Client**](Client.md) | | - - - -[**Client**](Client.md) - -### Authorization - -[api_key_query](../README.md#api_key_query) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/File.md b/samples/openapi3/client/petstore/python-experimental/docs/File.md deleted file mode 100644 index d541f9f0ab..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/File.md +++ /dev/null @@ -1,12 +0,0 @@ -# File - -Must be named `File` for test. - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**sourceURI** | **str** | Test capitalization | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python-experimental/docs/FileSchemaTestClass.md deleted file mode 100644 index e7bdc36bfd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/FileSchemaTestClass.md +++ /dev/null @@ -1,11 +0,0 @@ -# FileSchemaTestClass - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**file** | [**File**](File.md) | | [optional] -**files** | **[File]** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Foo.md b/samples/openapi3/client/petstore/python-experimental/docs/Foo.md deleted file mode 100644 index e948b10cae..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Foo.md +++ /dev/null @@ -1,10 +0,0 @@ -# Foo - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**bar** | **str** | | [optional] if omitted the server will use the default value of "bar" -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/FormatTest.md b/samples/openapi3/client/petstore/python-experimental/docs/FormatTest.md deleted file mode 100644 index 472216aa45..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/FormatTest.md +++ /dev/null @@ -1,30 +0,0 @@ -# FormatTest - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer** | **int** | | [optional] -**int32** | **int** | | [optional] -**int32withValidations** | **int** | | [optional] -**int64** | **int** | | [optional] -**number** | **int, float** | | -**float** | **int, float** | this is a reserved python keyword | [optional] -**float32** | **int, float** | | [optional] -**double** | **int, float** | | [optional] -**float64** | **int, float** | | [optional] -**arrayWithUniqueItems** | **[int, float]** | | [optional] -**string** | **str** | | [optional] -**byte** | **str** | | -**binary** | **file_type** | | [optional] -**date** | **date** | | -**dateTime** | **datetime** | | [optional] -**uuid** | **str** | | [optional] -**uuidNoExample** | **str** | | [optional] -**password** | **str** | | -**pattern_with_digits** | **str** | A string that is a 10 digit number. Can have leading zeros. | [optional] -**pattern_with_digits_and_delimiter** | **str** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] -**noneProp** | **none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Fruit.md b/samples/openapi3/client/petstore/python-experimental/docs/Fruit.md deleted file mode 100644 index 42684ab7a1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Fruit.md +++ /dev/null @@ -1,10 +0,0 @@ -# Fruit - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**color** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/FruitReq.md b/samples/openapi3/client/petstore/python-experimental/docs/FruitReq.md deleted file mode 100644 index eceb328ee6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/FruitReq.md +++ /dev/null @@ -1,9 +0,0 @@ -# FruitReq - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/GmFruit.md b/samples/openapi3/client/petstore/python-experimental/docs/GmFruit.md deleted file mode 100644 index 13879f2632..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/GmFruit.md +++ /dev/null @@ -1,10 +0,0 @@ -# GmFruit - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**color** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/GrandparentAnimal.md b/samples/openapi3/client/petstore/python-experimental/docs/GrandparentAnimal.md deleted file mode 100644 index ed51b57286..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/GrandparentAnimal.md +++ /dev/null @@ -1,10 +0,0 @@ -# GrandparentAnimal - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**pet_type** | **str** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python-experimental/docs/HasOnlyReadOnly.md deleted file mode 100644 index 14ac98c076..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/HasOnlyReadOnly.md +++ /dev/null @@ -1,11 +0,0 @@ -# HasOnlyReadOnly - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**bar** | **str** | | [optional] [readonly] -**foo** | **str** | | [optional] [readonly] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python-experimental/docs/HealthCheckResult.md deleted file mode 100644 index 8ce835f39a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/HealthCheckResult.md +++ /dev/null @@ -1,12 +0,0 @@ -# HealthCheckResult - -Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**NullableMessage** | **str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnum.md b/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnum.md deleted file mode 100644 index 32d6654144..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnum.md +++ /dev/null @@ -1,8 +0,0 @@ -# IntegerEnum - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | must be one of [0, 1, 2, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumBig.md b/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumBig.md deleted file mode 100644 index 58d94b3102..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumBig.md +++ /dev/null @@ -1,8 +0,0 @@ -# IntegerEnumBig - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | must be one of [10, 11, 12, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumOneValue.md b/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumOneValue.md deleted file mode 100644 index 6fea6c1d44..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumOneValue.md +++ /dev/null @@ -1,8 +0,0 @@ -# IntegerEnumOneValue - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | must be one of [0, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumWithDefaultValue.md b/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumWithDefaultValue.md deleted file mode 100644 index b95a839f9b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumWithDefaultValue.md +++ /dev/null @@ -1,8 +0,0 @@ -# IntegerEnumWithDefaultValue - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | defaults to 0, must be one of [0, 1, 2, ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/IntegerMax10.md b/samples/openapi3/client/petstore/python-experimental/docs/IntegerMax10.md deleted file mode 100644 index 768902e0ac..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/IntegerMax10.md +++ /dev/null @@ -1,8 +0,0 @@ -# IntegerMax10 - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/IntegerMin15.md b/samples/openapi3/client/petstore/python-experimental/docs/IntegerMin15.md deleted file mode 100644 index 35043be2fa..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/IntegerMin15.md +++ /dev/null @@ -1,8 +0,0 @@ -# IntegerMin15 - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/IsoscelesTriangle.md b/samples/openapi3/client/petstore/python-experimental/docs/IsoscelesTriangle.md deleted file mode 100644 index 7891fd5aa7..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/IsoscelesTriangle.md +++ /dev/null @@ -1,9 +0,0 @@ -# IsoscelesTriangle - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Mammal.md b/samples/openapi3/client/petstore/python-experimental/docs/Mammal.md deleted file mode 100644 index 6ecc91576e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Mammal.md +++ /dev/null @@ -1,9 +0,0 @@ -# Mammal - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/MapTest.md b/samples/openapi3/client/petstore/python-experimental/docs/MapTest.md deleted file mode 100644 index b842ca9985..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/MapTest.md +++ /dev/null @@ -1,13 +0,0 @@ -# MapTest - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**map_map_of_string** | **{str: ({str: (str,)},)}** | | [optional] -**map_of_enum_string** | **{str: (str,)}** | | [optional] -**direct_map** | **{str: (bool,)}** | | [optional] -**indirect_map** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-experimental/docs/MixedPropertiesAndAdditionalPropertiesClass.md deleted file mode 100644 index f8406a0af4..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ /dev/null @@ -1,12 +0,0 @@ -# MixedPropertiesAndAdditionalPropertiesClass - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**uuid** | **str** | | [optional] -**dateTime** | **datetime** | | [optional] -**map** | **{str: (Animal,)}** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Model200Response.md b/samples/openapi3/client/petstore/python-experimental/docs/Model200Response.md deleted file mode 100644 index 71af8e1044..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Model200Response.md +++ /dev/null @@ -1,13 +0,0 @@ -# Model200Response - -model with an invalid class name for python, starts with a number - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **int** | | [optional] -**class** | **str** | this is a reserved python keyword | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ModelReturn.md b/samples/openapi3/client/petstore/python-experimental/docs/ModelReturn.md deleted file mode 100644 index 35abb51e23..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ModelReturn.md +++ /dev/null @@ -1,12 +0,0 @@ -# ModelReturn - -Model for testing reserved words - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**return** | **int** | this is a reserved python keyword | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Money.md b/samples/openapi3/client/petstore/python-experimental/docs/Money.md deleted file mode 100644 index 5deec5712a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Money.md +++ /dev/null @@ -1,11 +0,0 @@ -# Money - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**amount** | **str** | | -**currency** | [**Currency**](Currency.md) | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Name.md b/samples/openapi3/client/petstore/python-experimental/docs/Name.md deleted file mode 100644 index 446d314fbd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Name.md +++ /dev/null @@ -1,14 +0,0 @@ -# Name - -Model for testing model name same as property name - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **int** | | -**snake_case** | **int** | | [optional] [readonly] -**property** | **str** | this is a reserved python keyword | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/NoAdditionalProperties.md b/samples/openapi3/client/petstore/python-experimental/docs/NoAdditionalProperties.md deleted file mode 100644 index e5bf9b9be8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/NoAdditionalProperties.md +++ /dev/null @@ -1,10 +0,0 @@ -# NoAdditionalProperties - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **int** | | -**petId** | **int** | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/NullableClass.md b/samples/openapi3/client/petstore/python-experimental/docs/NullableClass.md deleted file mode 100644 index 5f2a1280eb..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/NullableClass.md +++ /dev/null @@ -1,21 +0,0 @@ -# NullableClass - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**integer_prop** | **int, none_type** | | [optional] -**number_prop** | **int, float, none_type** | | [optional] -**boolean_prop** | **bool, none_type** | | [optional] -**string_prop** | **str, none_type** | | [optional] -**date_prop** | **date, none_type** | | [optional] -**datetime_prop** | **datetime, none_type** | | [optional] -**array_nullable_prop** | **[{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type** | | [optional] -**array_and_items_nullable_prop** | **[{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type** | | [optional] -**array_items_nullable** | **[{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type]** | | [optional] -**object_nullable_prop** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type** | | [optional] -**object_and_items_nullable_prop** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type** | | [optional] -**object_items_nullable** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}** | | [optional] -**any string name** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/NullableShape.md b/samples/openapi3/client/petstore/python-experimental/docs/NullableShape.md deleted file mode 100644 index 4e676ae4d5..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/NullableShape.md +++ /dev/null @@ -1,11 +0,0 @@ -# NullableShape - -The value may be a shape or the 'null' value. For a composed schema to validate a null payload, one of its chosen oneOf schemas must be type null or nullable (introduced in OAS schema >= 3.0) - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/NullableString.md b/samples/openapi3/client/petstore/python-experimental/docs/NullableString.md deleted file mode 100644 index c01cb80678..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/NullableString.md +++ /dev/null @@ -1,8 +0,0 @@ -# NullableString - -Type | Description | Notes -------------- | ------------- | ------------- -typing.Union[str, None, ] | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Number.md b/samples/openapi3/client/petstore/python-experimental/docs/Number.md deleted file mode 100644 index 63e3c42fdb..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Number.md +++ /dev/null @@ -1,8 +0,0 @@ -# Number - -Type | Description | Notes -------------- | ------------- | ------------- -**float** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/NumberOnly.md b/samples/openapi3/client/petstore/python-experimental/docs/NumberOnly.md deleted file mode 100644 index 699674314e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/NumberOnly.md +++ /dev/null @@ -1,10 +0,0 @@ -# NumberOnly - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**JustNumber** | **int, float** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/NumberWithValidations.md b/samples/openapi3/client/petstore/python-experimental/docs/NumberWithValidations.md deleted file mode 100644 index 9fe4c99f8d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/NumberWithValidations.md +++ /dev/null @@ -1,8 +0,0 @@ -# NumberWithValidations - -Type | Description | Notes -------------- | ------------- | ------------- -**float** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ObjectInterface.md b/samples/openapi3/client/petstore/python-experimental/docs/ObjectInterface.md deleted file mode 100644 index 1ce1b34d41..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ObjectInterface.md +++ /dev/null @@ -1,9 +0,0 @@ -# ObjectInterface - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ObjectModelWithRefProps.md b/samples/openapi3/client/petstore/python-experimental/docs/ObjectModelWithRefProps.md deleted file mode 100644 index 637175bc2f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ObjectModelWithRefProps.md +++ /dev/null @@ -1,14 +0,0 @@ -# ObjectModelWithRefProps - -a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**myNumber** | [**NumberWithValidations**](NumberWithValidations.md) | | [optional] -**myString** | **str** | | [optional] -**myBoolean** | **bool** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithDecimalProperties.md b/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithDecimalProperties.md deleted file mode 100644 index 10bd9061c0..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithDecimalProperties.md +++ /dev/null @@ -1,12 +0,0 @@ -# ObjectWithDecimalProperties - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**length** | **str** | | [optional] -**width** | **str** | | [optional] -**cost** | [**Money**](Money.md) | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithDifficultlyNamedProps.md b/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithDifficultlyNamedProps.md deleted file mode 100644 index cb45c6b10e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithDifficultlyNamedProps.md +++ /dev/null @@ -1,14 +0,0 @@ -# ObjectWithDifficultlyNamedProps - -model with properties that have invalid names for python - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**$special[property.name]** | **int** | | [optional] -**123-list** | **str** | | -**123Number** | **int** | | [optional] [readonly] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithInlineCompositionProperty.md b/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithInlineCompositionProperty.md deleted file mode 100644 index fbd037b732..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithInlineCompositionProperty.md +++ /dev/null @@ -1,10 +0,0 @@ -# ObjectWithInlineCompositionProperty - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**someProp** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithValidations.md b/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithValidations.md deleted file mode 100644 index 3950d2ab95..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithValidations.md +++ /dev/null @@ -1,9 +0,0 @@ -# ObjectWithValidations - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Order.md b/samples/openapi3/client/petstore/python-experimental/docs/Order.md deleted file mode 100644 index 374172ad32..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Order.md +++ /dev/null @@ -1,15 +0,0 @@ -# Order - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **int** | | [optional] -**petId** | **int** | | [optional] -**quantity** | **int** | | [optional] -**shipDate** | **datetime** | | [optional] -**status** | **str** | Order Status | [optional] -**complete** | **bool** | | [optional] if omitted the server will use the default value of False -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ParentPet.md b/samples/openapi3/client/petstore/python-experimental/docs/ParentPet.md deleted file mode 100644 index 28a57b84fe..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ParentPet.md +++ /dev/null @@ -1,9 +0,0 @@ -# ParentPet - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Pet.md b/samples/openapi3/client/petstore/python-experimental/docs/Pet.md deleted file mode 100644 index 8eec44141d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Pet.md +++ /dev/null @@ -1,17 +0,0 @@ -# Pet - -Pet object that needs to be added to the store - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **int** | | [optional] -**category** | [**Category**](Category.md) | | [optional] -**name** | **str** | | -**photoUrls** | **[str]** | | -**tags** | **[Tag]** | | [optional] -**status** | **str** | pet status in the store | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/PetApi.md b/samples/openapi3/client/petstore/python-experimental/docs/PetApi.md deleted file mode 100644 index d8ee4cb32f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/PetApi.md +++ /dev/null @@ -1,1362 +0,0 @@ -# petstore_api.PetApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store -[**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet -[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status -[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags -[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID -[**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet -[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data -[**upload_file_with_required_file**](PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -[**upload_image**](PetApi.md#upload_image) | **POST** /pet/{petId}/uploadImage | uploads an image - -# **add_pet** -> add_pet(pet) - -Add a new pet to the store - -Add a new pet to the store - -### Example - -* OAuth Authentication (petstore_auth): -```python -import petstore_api -from petstore_api.api import pet_api -from petstore_api.model.pet import Pet -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure HTTP message signature: http_signature_test -# The HTTP Signature Header mechanism that can be used by a client to -# authenticate the sender of a message and ensure that particular headers -# have not been modified in transit. -# -# You can specify the signing key-id, private key path, signing scheme, -# signing algorithm, list of signed headers and signature max validity. -# The 'key_id' parameter is an opaque string that the API server can use -# to lookup the client and validate the signature. -# The 'private_key_path' parameter should be the path to a file that -# contains a DER or base-64 encoded private key. -# The 'private_key_passphrase' parameter is optional. Set the passphrase -# if the private key is encrypted. -# The 'signed_headers' parameter is used to specify the list of -# HTTP headers included when generating the signature for the message. -# You can specify HTTP headers that you want to protect with a cryptographic -# signature. Note that proxies may add, modify or remove HTTP headers -# for legitimate reasons, so you should only add headers that you know -# will not be modified. For example, if you want to protect the HTTP request -# body, you can specify the Digest header. In that case, the client calculates -# the digest of the HTTP request body and includes the digest in the message -# signature. -# The 'signature_max_validity' parameter is optional. It is configured as a -# duration to express when the signature ceases to be valid. The client calculates -# the expiration date every time it generates the cryptographic signature -# of an HTTP request. The API server may have its own security policy -# that controls the maximum validity of the signature. The client max validity -# must be lower than the server max validity. -# The time on the client and server must be synchronized, otherwise the -# server may reject the client signature. -# -# The client must use a combination of private key, signing scheme, -# signing algorithm and hash algorithm that matches the security policy of -# the API server. -# -# See petstore_api.signing for a list of all supported parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2", - signing_info = petstore_api.signing.HttpSigningConfiguration( - key_id = 'my-key-id', - private_key_path = 'private_key.pem', - private_key_passphrase = 'YOUR_PASSPHRASE', - signing_scheme = petstore_api.signing.SCHEME_HS2019, - signing_algorithm = petstore_api.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, - hash_algorithm = petstore_api.signing.SCHEME_RSA_SHA256, - signed_headers = [ - petstore_api.signing.HEADER_REQUEST_TARGET, - petstore_api.signing.HEADER_CREATED, - petstore_api.signing.HEADER_EXPIRES, - petstore_api.signing.HEADER_HOST, - petstore_api.signing.HEADER_DATE, - petstore_api.signing.HEADER_DIGEST, - 'Content-Type', - 'Content-Length', - 'User-Agent' - ], - signature_max_validity = datetime.timedelta(minutes=5) - ) -) - -# Configure OAuth2 access token for authorization: petstore_auth -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) -configuration.access_token = 'YOUR_ACCESS_TOKEN' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = pet_api.PetApi(api_client) - - # example passing only required values which don't have defaults set - body = Pet( - id=1, - category=Category( - id=1, - name="default-name", - ), - name="doggie", - photo_urls=[ - "photo_urls_example" - ], - tags=[ - Tag( - id=1, - name="name_example", - ) - ], - status="available", - ) - try: - # Add a new pet to the store - api_response = api_instance.add_pet( - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->add_pet: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, SchemaForRequestBodyApplicationXml] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -host_index | typing.Optional[int] | default is None | Allows one to select a different host -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Pet**](Pet.md) | | - - -#### SchemaForRequestBodyApplicationXml -Type | Description | Notes -------------- | ------------- | ------------- -[**Pet**](Pet.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | Ok -405 | ApiResponseFor405 | Invalid input - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor405 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_pet** -> delete_pet(pet_id) - -Deletes a pet - -### Example - -* OAuth Authentication (petstore_auth): -```python -import petstore_api -from petstore_api.api import pet_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure OAuth2 access token for authorization: petstore_auth -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) -configuration.access_token = 'YOUR_ACCESS_TOKEN' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = pet_api.PetApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'petId': 1, - } - header_params = { - } - try: - # Deletes a pet - api_response = api_instance.delete_pet( - path_params=path_params, - header_params=header_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->delete_pet: %s\n" % e) - - # example passing only optional values - path_params = { - 'petId': 1, - } - header_params = { - 'api_key': "api_key_example", - } - try: - # Deletes a pet - api_response = api_instance.delete_pet( - path_params=path_params, - header_params=header_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->delete_pet: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -header_params | RequestHeaderParams | | -path_params | RequestPathParams | | -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### header_params -#### RequestHeaderParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -api_key | ApiKeySchema | | optional - -#### ApiKeySchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -petId | PetIdSchema | | - -#### PetIdSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -400 | ApiResponseFor400 | Invalid pet value - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **find_pets_by_status** -> [Pet] find_pets_by_status(status) - -Finds Pets by status - -Multiple status values can be provided with comma separated strings - -### Example - -* OAuth Authentication (petstore_auth): -```python -import petstore_api -from petstore_api.api import pet_api -from petstore_api.model.pet import Pet -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure HTTP message signature: http_signature_test -# The HTTP Signature Header mechanism that can be used by a client to -# authenticate the sender of a message and ensure that particular headers -# have not been modified in transit. -# -# You can specify the signing key-id, private key path, signing scheme, -# signing algorithm, list of signed headers and signature max validity. -# The 'key_id' parameter is an opaque string that the API server can use -# to lookup the client and validate the signature. -# The 'private_key_path' parameter should be the path to a file that -# contains a DER or base-64 encoded private key. -# The 'private_key_passphrase' parameter is optional. Set the passphrase -# if the private key is encrypted. -# The 'signed_headers' parameter is used to specify the list of -# HTTP headers included when generating the signature for the message. -# You can specify HTTP headers that you want to protect with a cryptographic -# signature. Note that proxies may add, modify or remove HTTP headers -# for legitimate reasons, so you should only add headers that you know -# will not be modified. For example, if you want to protect the HTTP request -# body, you can specify the Digest header. In that case, the client calculates -# the digest of the HTTP request body and includes the digest in the message -# signature. -# The 'signature_max_validity' parameter is optional. It is configured as a -# duration to express when the signature ceases to be valid. The client calculates -# the expiration date every time it generates the cryptographic signature -# of an HTTP request. The API server may have its own security policy -# that controls the maximum validity of the signature. The client max validity -# must be lower than the server max validity. -# The time on the client and server must be synchronized, otherwise the -# server may reject the client signature. -# -# The client must use a combination of private key, signing scheme, -# signing algorithm and hash algorithm that matches the security policy of -# the API server. -# -# See petstore_api.signing for a list of all supported parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2", - signing_info = petstore_api.signing.HttpSigningConfiguration( - key_id = 'my-key-id', - private_key_path = 'private_key.pem', - private_key_passphrase = 'YOUR_PASSPHRASE', - signing_scheme = petstore_api.signing.SCHEME_HS2019, - signing_algorithm = petstore_api.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, - hash_algorithm = petstore_api.signing.SCHEME_RSA_SHA256, - signed_headers = [ - petstore_api.signing.HEADER_REQUEST_TARGET, - petstore_api.signing.HEADER_CREATED, - petstore_api.signing.HEADER_EXPIRES, - petstore_api.signing.HEADER_HOST, - petstore_api.signing.HEADER_DATE, - petstore_api.signing.HEADER_DIGEST, - 'Content-Type', - 'Content-Length', - 'User-Agent' - ], - signature_max_validity = datetime.timedelta(minutes=5) - ) -) - -# Configure OAuth2 access token for authorization: petstore_auth -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) -configuration.access_token = 'YOUR_ACCESS_TOKEN' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = pet_api.PetApi(api_client) - - # example passing only required values which don't have defaults set - query_params = { - 'status': [ - "available" - ], - } - try: - # Finds Pets by status - api_response = api_instance.find_pets_by_status( - query_params=query_params, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->find_pets_by_status: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -query_params | RequestQueryParams | | -accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -status | StatusSchema | | - - -#### StatusSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**[str]** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation -400 | ApiResponseFor400 | Invalid status value - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationXml - -Type | Description | Notes -------------- | ------------- | ------------- -**[Pet]** | | - -#### SchemaFor200ResponseBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -**[Pet]** | | - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -[**[Pet]**](Pet.md) - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **find_pets_by_tags** -> [Pet] find_pets_by_tags(tags) - -Finds Pets by tags - -Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - -### Example - -* OAuth Authentication (petstore_auth): -```python -import petstore_api -from petstore_api.api import pet_api -from petstore_api.model.pet import Pet -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure HTTP message signature: http_signature_test -# The HTTP Signature Header mechanism that can be used by a client to -# authenticate the sender of a message and ensure that particular headers -# have not been modified in transit. -# -# You can specify the signing key-id, private key path, signing scheme, -# signing algorithm, list of signed headers and signature max validity. -# The 'key_id' parameter is an opaque string that the API server can use -# to lookup the client and validate the signature. -# The 'private_key_path' parameter should be the path to a file that -# contains a DER or base-64 encoded private key. -# The 'private_key_passphrase' parameter is optional. Set the passphrase -# if the private key is encrypted. -# The 'signed_headers' parameter is used to specify the list of -# HTTP headers included when generating the signature for the message. -# You can specify HTTP headers that you want to protect with a cryptographic -# signature. Note that proxies may add, modify or remove HTTP headers -# for legitimate reasons, so you should only add headers that you know -# will not be modified. For example, if you want to protect the HTTP request -# body, you can specify the Digest header. In that case, the client calculates -# the digest of the HTTP request body and includes the digest in the message -# signature. -# The 'signature_max_validity' parameter is optional. It is configured as a -# duration to express when the signature ceases to be valid. The client calculates -# the expiration date every time it generates the cryptographic signature -# of an HTTP request. The API server may have its own security policy -# that controls the maximum validity of the signature. The client max validity -# must be lower than the server max validity. -# The time on the client and server must be synchronized, otherwise the -# server may reject the client signature. -# -# The client must use a combination of private key, signing scheme, -# signing algorithm and hash algorithm that matches the security policy of -# the API server. -# -# See petstore_api.signing for a list of all supported parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2", - signing_info = petstore_api.signing.HttpSigningConfiguration( - key_id = 'my-key-id', - private_key_path = 'private_key.pem', - private_key_passphrase = 'YOUR_PASSPHRASE', - signing_scheme = petstore_api.signing.SCHEME_HS2019, - signing_algorithm = petstore_api.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, - hash_algorithm = petstore_api.signing.SCHEME_RSA_SHA256, - signed_headers = [ - petstore_api.signing.HEADER_REQUEST_TARGET, - petstore_api.signing.HEADER_CREATED, - petstore_api.signing.HEADER_EXPIRES, - petstore_api.signing.HEADER_HOST, - petstore_api.signing.HEADER_DATE, - petstore_api.signing.HEADER_DIGEST, - 'Content-Type', - 'Content-Length', - 'User-Agent' - ], - signature_max_validity = datetime.timedelta(minutes=5) - ) -) - -# Configure OAuth2 access token for authorization: petstore_auth -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) -configuration.access_token = 'YOUR_ACCESS_TOKEN' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = pet_api.PetApi(api_client) - - # example passing only required values which don't have defaults set - query_params = { - 'tags': [ - "tags_example" - ], - } - try: - # Finds Pets by tags - api_response = api_instance.find_pets_by_tags( - query_params=query_params, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->find_pets_by_tags: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -query_params | RequestQueryParams | | -accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -tags | TagsSchema | | - - -#### TagsSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**[str]** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation -400 | ApiResponseFor400 | Invalid tag value - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationXml - -Type | Description | Notes -------------- | ------------- | ------------- -**[Pet]** | | - -#### SchemaFor200ResponseBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -**[Pet]** | | - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -[**[Pet]**](Pet.md) - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_pet_by_id** -> Pet get_pet_by_id(pet_id) - -Find pet by ID - -Returns a single pet - -### Example - -* Api Key Authentication (api_key): -```python -import petstore_api -from petstore_api.api import pet_api -from petstore_api.model.pet import Pet -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure API key authorization: api_key -configuration.api_key['api_key'] = 'YOUR_API_KEY' - -# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -# configuration.api_key_prefix['api_key'] = 'Bearer' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = pet_api.PetApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'petId': 1, - } - try: - # Find pet by ID - api_response = api_instance.get_pet_by_id( - path_params=path_params, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->get_pet_by_id: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -path_params | RequestPathParams | | -accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -petId | PetIdSchema | | - -#### PetIdSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation -400 | ApiResponseFor400 | Invalid ID supplied -404 | ApiResponseFor404 | Pet not found - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationXml -Type | Description | Notes -------------- | ------------- | ------------- -[**Pet**](Pet.md) | | - - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Pet**](Pet.md) | | - - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor404 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -[**Pet**](Pet.md) - -### Authorization - -[api_key](../README.md#api_key) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_pet** -> update_pet(pet) - -Update an existing pet - -### Example - -* OAuth Authentication (petstore_auth): -```python -import petstore_api -from petstore_api.api import pet_api -from petstore_api.model.pet import Pet -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure HTTP message signature: http_signature_test -# The HTTP Signature Header mechanism that can be used by a client to -# authenticate the sender of a message and ensure that particular headers -# have not been modified in transit. -# -# You can specify the signing key-id, private key path, signing scheme, -# signing algorithm, list of signed headers and signature max validity. -# The 'key_id' parameter is an opaque string that the API server can use -# to lookup the client and validate the signature. -# The 'private_key_path' parameter should be the path to a file that -# contains a DER or base-64 encoded private key. -# The 'private_key_passphrase' parameter is optional. Set the passphrase -# if the private key is encrypted. -# The 'signed_headers' parameter is used to specify the list of -# HTTP headers included when generating the signature for the message. -# You can specify HTTP headers that you want to protect with a cryptographic -# signature. Note that proxies may add, modify or remove HTTP headers -# for legitimate reasons, so you should only add headers that you know -# will not be modified. For example, if you want to protect the HTTP request -# body, you can specify the Digest header. In that case, the client calculates -# the digest of the HTTP request body and includes the digest in the message -# signature. -# The 'signature_max_validity' parameter is optional. It is configured as a -# duration to express when the signature ceases to be valid. The client calculates -# the expiration date every time it generates the cryptographic signature -# of an HTTP request. The API server may have its own security policy -# that controls the maximum validity of the signature. The client max validity -# must be lower than the server max validity. -# The time on the client and server must be synchronized, otherwise the -# server may reject the client signature. -# -# The client must use a combination of private key, signing scheme, -# signing algorithm and hash algorithm that matches the security policy of -# the API server. -# -# See petstore_api.signing for a list of all supported parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2", - signing_info = petstore_api.signing.HttpSigningConfiguration( - key_id = 'my-key-id', - private_key_path = 'private_key.pem', - private_key_passphrase = 'YOUR_PASSPHRASE', - signing_scheme = petstore_api.signing.SCHEME_HS2019, - signing_algorithm = petstore_api.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, - hash_algorithm = petstore_api.signing.SCHEME_RSA_SHA256, - signed_headers = [ - petstore_api.signing.HEADER_REQUEST_TARGET, - petstore_api.signing.HEADER_CREATED, - petstore_api.signing.HEADER_EXPIRES, - petstore_api.signing.HEADER_HOST, - petstore_api.signing.HEADER_DATE, - petstore_api.signing.HEADER_DIGEST, - 'Content-Type', - 'Content-Length', - 'User-Agent' - ], - signature_max_validity = datetime.timedelta(minutes=5) - ) -) - -# Configure OAuth2 access token for authorization: petstore_auth -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) -configuration.access_token = 'YOUR_ACCESS_TOKEN' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = pet_api.PetApi(api_client) - - # example passing only required values which don't have defaults set - body = Pet( - id=1, - category=Category( - id=1, - name="default-name", - ), - name="doggie", - photo_urls=[ - "photo_urls_example" - ], - tags=[ - Tag( - id=1, - name="name_example", - ) - ], - status="available", - ) - try: - # Update an existing pet - api_response = api_instance.update_pet( - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->update_pet: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson, SchemaForRequestBodyApplicationXml] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -host_index | typing.Optional[int] | default is None | Allows one to select a different host -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Pet**](Pet.md) | | - - -#### SchemaForRequestBodyApplicationXml -Type | Description | Notes -------------- | ------------- | ------------- -[**Pet**](Pet.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -400 | ApiResponseFor400 | Invalid ID supplied -404 | ApiResponseFor404 | Pet not found -405 | ApiResponseFor405 | Validation exception - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor404 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor405 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_pet_with_form** -> update_pet_with_form(pet_id) - -Updates a pet in the store with form data - -### Example - -* OAuth Authentication (petstore_auth): -```python -import petstore_api -from petstore_api.api import pet_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure OAuth2 access token for authorization: petstore_auth -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) -configuration.access_token = 'YOUR_ACCESS_TOKEN' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = pet_api.PetApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'petId': 1, - } - try: - # Updates a pet in the store with form data - api_response = api_instance.update_pet_with_form( - path_params=path_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) - - # example passing only optional values - path_params = { - 'petId': 1, - } - body = dict( - name="name_example", - status="status_example", - ) - try: - # Updates a pet in the store with form data - api_response = api_instance.update_pet_with_form( - path_params=path_params, - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] | optional, default is unset | -path_params | RequestPathParams | | -content_type | str | optional, default is 'application/x-www-form-urlencoded' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationXWwwFormUrlencoded - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **str** | Updated name of the pet | [optional] -**status** | **str** | Updated status of the pet | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -petId | PetIdSchema | | - -#### PetIdSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -405 | ApiResponseFor405 | Invalid input - -#### ApiResponseFor405 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **upload_file_with_required_file** -> ApiResponse upload_file_with_required_file(pet_id) - -uploads an image (required) - -### Example - -* OAuth Authentication (petstore_auth): -```python -import petstore_api -from petstore_api.api import pet_api -from petstore_api.model.api_response import ApiResponse -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure OAuth2 access token for authorization: petstore_auth -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) -configuration.access_token = 'YOUR_ACCESS_TOKEN' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = pet_api.PetApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'petId': 1, - } - try: - # uploads an image (required) - api_response = api_instance.upload_file_with_required_file( - path_params=path_params, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->upload_file_with_required_file: %s\n" % e) - - # example passing only optional values - path_params = { - 'petId': 1, - } - body = dict( - additional_metadata="additional_metadata_example", - required_file=open('/path/to/file', 'rb'), - ) - try: - # uploads an image (required) - api_response = api_instance.upload_file_with_required_file( - path_params=path_params, - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->upload_file_with_required_file: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | -path_params | RequestPathParams | | -content_type | str | optional, default is 'multipart/form-data' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyMultipartFormData - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **str** | Additional data to pass to server | [optional] -**requiredFile** | **file_type** | file to upload | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -petId | PetIdSchema | | - -#### PetIdSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ApiResponse**](ApiResponse.md) | | - - - -[**ApiResponse**](ApiResponse.md) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **upload_image** -> ApiResponse upload_image(pet_id) - -uploads an image - -### Example - -* OAuth Authentication (petstore_auth): -```python -import petstore_api -from petstore_api.api import pet_api -from petstore_api.model.api_response import ApiResponse -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure OAuth2 access token for authorization: petstore_auth -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) -configuration.access_token = 'YOUR_ACCESS_TOKEN' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = pet_api.PetApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'petId': 1, - } - try: - # uploads an image - api_response = api_instance.upload_image( - path_params=path_params, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->upload_image: %s\n" % e) - - # example passing only optional values - path_params = { - 'petId': 1, - } - body = dict( - additional_metadata="additional_metadata_example", - file=open('/path/to/file', 'rb'), - ) - try: - # uploads an image - api_response = api_instance.upload_image( - path_params=path_params, - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling PetApi->upload_image: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | -path_params | RequestPathParams | | -content_type | str | optional, default is 'multipart/form-data' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyMultipartFormData - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**additionalMetadata** | **str** | Additional data to pass to server | [optional] -**file** | **file_type** | file to upload | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -petId | PetIdSchema | | - -#### PetIdSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**ApiResponse**](ApiResponse.md) | | - - - -[**ApiResponse**](ApiResponse.md) - -### Authorization - -[petstore_auth](../README.md#petstore_auth) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Pig.md b/samples/openapi3/client/petstore/python-experimental/docs/Pig.md deleted file mode 100644 index 97259b026f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Pig.md +++ /dev/null @@ -1,9 +0,0 @@ -# Pig - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Player.md b/samples/openapi3/client/petstore/python-experimental/docs/Player.md deleted file mode 100644 index 2daf47240c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Player.md +++ /dev/null @@ -1,13 +0,0 @@ -# Player - -a model that includes a self reference this forces properties and additionalProperties to be lazy loaded in python models because the Player class has not fully loaded when defining properties - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **str** | | [optional] -**enemyPlayer** | [**Player**](Player.md) | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Quadrilateral.md b/samples/openapi3/client/petstore/python-experimental/docs/Quadrilateral.md deleted file mode 100644 index e840c9b8fd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Quadrilateral.md +++ /dev/null @@ -1,9 +0,0 @@ -# Quadrilateral - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/QuadrilateralInterface.md b/samples/openapi3/client/petstore/python-experimental/docs/QuadrilateralInterface.md deleted file mode 100644 index ee7c4db4ba..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/QuadrilateralInterface.md +++ /dev/null @@ -1,11 +0,0 @@ -# QuadrilateralInterface - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**shapeType** | **str** | | -**quadrilateralType** | **str** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python-experimental/docs/ReadOnlyFirst.md deleted file mode 100644 index a6c2e4524b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ReadOnlyFirst.md +++ /dev/null @@ -1,11 +0,0 @@ -# ReadOnlyFirst - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**bar** | **str** | | [optional] [readonly] -**baz** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ScaleneTriangle.md b/samples/openapi3/client/petstore/python-experimental/docs/ScaleneTriangle.md deleted file mode 100644 index 941e9e6311..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ScaleneTriangle.md +++ /dev/null @@ -1,9 +0,0 @@ -# ScaleneTriangle - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Shape.md b/samples/openapi3/client/petstore/python-experimental/docs/Shape.md deleted file mode 100644 index 798438fbd2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Shape.md +++ /dev/null @@ -1,9 +0,0 @@ -# Shape - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/ShapeOrNull.md b/samples/openapi3/client/petstore/python-experimental/docs/ShapeOrNull.md deleted file mode 100644 index 17fa7c5057..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/ShapeOrNull.md +++ /dev/null @@ -1,11 +0,0 @@ -# ShapeOrNull - -The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/SimpleQuadrilateral.md b/samples/openapi3/client/petstore/python-experimental/docs/SimpleQuadrilateral.md deleted file mode 100644 index d9ce2f02b0..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/SimpleQuadrilateral.md +++ /dev/null @@ -1,9 +0,0 @@ -# SimpleQuadrilateral - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/SomeObject.md b/samples/openapi3/client/petstore/python-experimental/docs/SomeObject.md deleted file mode 100644 index 55a308e4f8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/SomeObject.md +++ /dev/null @@ -1,9 +0,0 @@ -# SomeObject - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python-experimental/docs/SpecialModelName.md deleted file mode 100644 index 8c02dca9ab..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/SpecialModelName.md +++ /dev/null @@ -1,12 +0,0 @@ -# SpecialModelName - -model with an invalid class name for python - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**a** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/StoreApi.md b/samples/openapi3/client/petstore/python-experimental/docs/StoreApi.md deleted file mode 100644 index 9840cc8134..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/StoreApi.md +++ /dev/null @@ -1,391 +0,0 @@ -# petstore_api.StoreApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -[**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status -[**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID -[**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet - -# **delete_order** -> delete_order(order_id) - -Delete purchase order by ID - -For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - -### Example - -```python -import petstore_api -from petstore_api.api import store_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = store_api.StoreApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'order_id': "order_id_example", - } - try: - # Delete purchase order by ID - api_response = api_instance.delete_order( - path_params=path_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling StoreApi->delete_order: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -path_params | RequestPathParams | | -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -order_id | OrderIdSchema | | - -#### OrderIdSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -400 | ApiResponseFor400 | Invalid ID supplied -404 | ApiResponseFor404 | Order not found - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor404 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_inventory** -> {str: (int,)} get_inventory() - -Returns pet inventories by status - -Returns a map of status codes to quantities - -### Example - -* Api Key Authentication (api_key): -```python -import petstore_api -from petstore_api.api import store_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure API key authorization: api_key -configuration.api_key['api_key'] = 'YOUR_API_KEY' - -# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -# configuration.api_key_prefix['api_key'] = 'Bearer' -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = store_api.StoreApi(api_client) - - # example, this endpoint has no required or optional parameters - try: - # Returns pet inventories by status - api_response = api_instance.get_inventory() - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling StoreApi->get_inventory: %s\n" % e) -``` -### Parameters -This endpoint does not need any parameter. - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationJson - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **int** | any string name can be used but the value must be the correct type | [optional] - - -**{str: (int,)}** - -### Authorization - -[api_key](../README.md#api_key) - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_order_by_id** -> Order get_order_by_id(order_id) - -Find purchase order by ID - -For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - -### Example - -```python -import petstore_api -from petstore_api.api import store_api -from petstore_api.model.order import Order -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = store_api.StoreApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'order_id': 1, - } - try: - # Find purchase order by ID - api_response = api_instance.get_order_by_id( - path_params=path_params, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling StoreApi->get_order_by_id: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -path_params | RequestPathParams | | -accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -order_id | OrderIdSchema | | - -#### OrderIdSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation -400 | ApiResponseFor400 | Invalid ID supplied -404 | ApiResponseFor404 | Order not found - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationXml -Type | Description | Notes -------------- | ------------- | ------------- -[**Order**](Order.md) | | - - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Order**](Order.md) | | - - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor404 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -[**Order**](Order.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **place_order** -> Order place_order(order) - -Place an order for a pet - -### Example - -```python -import petstore_api -from petstore_api.api import store_api -from petstore_api.model.order import Order -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = store_api.StoreApi(api_client) - - # example passing only required values which don't have defaults set - body = Order( - id=1, - pet_id=1, - quantity=1, - ship_date="2020-02-02T20:20:20.000222Z", - status="placed", - complete=False, - ) - try: - # Place an order for a pet - api_response = api_instance.place_order( - body=body, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling StoreApi->place_order: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Order**](Order.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation -400 | ApiResponseFor400 | Invalid Order - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationXml -Type | Description | Notes -------------- | ------------- | ------------- -[**Order**](Order.md) | | - - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**Order**](Order.md) | | - - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -[**Order**](Order.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/String.md b/samples/openapi3/client/petstore/python-experimental/docs/String.md deleted file mode 100644 index ca058fd710..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/String.md +++ /dev/null @@ -1,8 +0,0 @@ -# String - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/StringBooleanMap.md b/samples/openapi3/client/petstore/python-experimental/docs/StringBooleanMap.md deleted file mode 100644 index 89b85004e9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/StringBooleanMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# StringBooleanMap - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/StringEnum.md b/samples/openapi3/client/petstore/python-experimental/docs/StringEnum.md deleted file mode 100644 index cb91199244..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/StringEnum.md +++ /dev/null @@ -1,8 +0,0 @@ -# StringEnum - -Type | Description | Notes -------------- | ------------- | ------------- -typing.Union[str, None, ] | | must be one of ["placed", "approved", "delivered", "single quoted", "multiple\nlines", "double quote \n with newline", ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/StringEnumWithDefaultValue.md b/samples/openapi3/client/petstore/python-experimental/docs/StringEnumWithDefaultValue.md deleted file mode 100644 index 08a337a526..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/StringEnumWithDefaultValue.md +++ /dev/null @@ -1,8 +0,0 @@ -# StringEnumWithDefaultValue - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | defaults to "placed", must be one of ["placed", "approved", "delivered", ] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/StringWithValidation.md b/samples/openapi3/client/petstore/python-experimental/docs/StringWithValidation.md deleted file mode 100644 index 870752b1df..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/StringWithValidation.md +++ /dev/null @@ -1,8 +0,0 @@ -# StringWithValidation - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Tag.md b/samples/openapi3/client/petstore/python-experimental/docs/Tag.md deleted file mode 100644 index 42cf6ecbc8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Tag.md +++ /dev/null @@ -1,11 +0,0 @@ -# Tag - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **int** | | [optional] -**name** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Triangle.md b/samples/openapi3/client/petstore/python-experimental/docs/Triangle.md deleted file mode 100644 index 0820ec390f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Triangle.md +++ /dev/null @@ -1,9 +0,0 @@ -# Triangle - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/TriangleInterface.md b/samples/openapi3/client/petstore/python-experimental/docs/TriangleInterface.md deleted file mode 100644 index 11c7c8e454..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/TriangleInterface.md +++ /dev/null @@ -1,11 +0,0 @@ -# TriangleInterface - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**shapeType** | **str** | | -**triangleType** | **str** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/UUIDString.md b/samples/openapi3/client/petstore/python-experimental/docs/UUIDString.md deleted file mode 100644 index 6f743509ec..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/UUIDString.md +++ /dev/null @@ -1,8 +0,0 @@ -# UUIDString - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/User.md b/samples/openapi3/client/petstore/python-experimental/docs/User.md deleted file mode 100644 index 58f817c0cf..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/User.md +++ /dev/null @@ -1,22 +0,0 @@ -# User - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **int** | | [optional] -**username** | **str** | | [optional] -**firstName** | **str** | | [optional] -**lastName** | **str** | | [optional] -**email** | **str** | | [optional] -**password** | **str** | | [optional] -**phone** | **str** | | [optional] -**userStatus** | **int** | User Status | [optional] -**objectWithNoDeclaredProps** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] -**objectWithNoDeclaredPropsNullable** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] -**anyTypeProp** | **bool, date, datetime, dict, float, int, list, str, none_type** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] -**anyTypeExceptNullProp** | **bool, date, datetime, dict, float, int, list, str, none_type** | any type except 'null' Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. | [optional] -**anyTypePropNullable** | **bool, date, datetime, dict, float, int, list, str, none_type** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/UserApi.md b/samples/openapi3/client/petstore/python-experimental/docs/UserApi.md deleted file mode 100644 index ab65024eaf..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/UserApi.md +++ /dev/null @@ -1,788 +0,0 @@ -# petstore_api.UserApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**create_user**](UserApi.md#create_user) | **POST** /user | Create user -[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array -[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array -[**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user -[**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name -[**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system -[**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session -[**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user - -# **create_user** -> create_user(user) - -Create user - -This can only be done by the logged in user. - -### Example - -```python -import petstore_api -from petstore_api.api import user_api -from petstore_api.model.user import User -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = user_api.UserApi(api_client) - - # example passing only required values which don't have defaults set - body = User( - id=1, - username="username_example", - first_name="first_name_example", - last_name="last_name_example", - email="email_example", - password="password_example", - phone="phone_example", - user_status=1, - object_with_no_declared_props=dict(), - object_with_no_declared_props_nullable=dict(), - any_type_prop=None, - any_type_except_null_prop=None, - any_type_prop_nullable=None, - ) - try: - # Create user - api_response = api_instance.create_user( - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling UserApi->create_user: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**User**](User.md) | | - - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -default | ApiResponseForDefault | successful operation - -#### ApiResponseForDefault -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_users_with_array_input** -> create_users_with_array_input(user) - -Creates list of users with given input array - -### Example - -```python -import petstore_api -from petstore_api.api import user_api -from petstore_api.model.user import User -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = user_api.UserApi(api_client) - - # example passing only required values which don't have defaults set - body = [ - User( - id=1, - username="username_example", - first_name="first_name_example", - last_name="last_name_example", - email="email_example", - password="password_example", - phone="phone_example", - user_status=1, - object_with_no_declared_props=dict(), - object_with_no_declared_props_nullable=dict(), - any_type_prop=None, - any_type_except_null_prop=None, - any_type_prop_nullable=None, - ) - ] - try: - # Creates list of users with given input array - api_response = api_instance.create_users_with_array_input( - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling UserApi->create_users_with_array_input: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -**[User]** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -default | ApiResponseForDefault | successful operation - -#### ApiResponseForDefault -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **create_users_with_list_input** -> create_users_with_list_input(user) - -Creates list of users with given input array - -### Example - -```python -import petstore_api -from petstore_api.api import user_api -from petstore_api.model.user import User -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = user_api.UserApi(api_client) - - # example passing only required values which don't have defaults set - body = [ - User( - id=1, - username="username_example", - first_name="first_name_example", - last_name="last_name_example", - email="email_example", - password="password_example", - phone="phone_example", - user_status=1, - object_with_no_declared_props=dict(), - object_with_no_declared_props_nullable=dict(), - any_type_prop=None, - any_type_except_null_prop=None, - any_type_prop_nullable=None, - ) - ] - try: - # Creates list of users with given input array - api_response = api_instance.create_users_with_list_input( - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling UserApi->create_users_with_list_input: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -**[User]** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -default | ApiResponseForDefault | successful operation - -#### ApiResponseForDefault -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **delete_user** -> delete_user(username) - -Delete user - -This can only be done by the logged in user. - -### Example - -```python -import petstore_api -from petstore_api.api import user_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = user_api.UserApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'username': "username_example", - } - try: - # Delete user - api_response = api_instance.delete_user( - path_params=path_params, - ) - except petstore_api.ApiException as e: - print("Exception when calling UserApi->delete_user: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -path_params | RequestPathParams | | -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -username | UsernameSchema | | - -#### UsernameSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -400 | ApiResponseFor400 | Invalid username supplied -404 | ApiResponseFor404 | User not found - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor404 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **get_user_by_name** -> User get_user_by_name(username) - -Get user by user name - -### Example - -```python -import petstore_api -from petstore_api.api import user_api -from petstore_api.model.user import User -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = user_api.UserApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'username': "username_example", - } - try: - # Get user by user name - api_response = api_instance.get_user_by_name( - path_params=path_params, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling UserApi->get_user_by_name: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -path_params | RequestPathParams | | -accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -username | UsernameSchema | | - -#### UsernameSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation -400 | ApiResponseFor400 | Invalid username supplied -404 | ApiResponseFor404 | User not found - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | -headers | Unset | headers were not defined | - -#### SchemaFor200ResponseBodyApplicationXml -Type | Description | Notes -------------- | ------------- | ------------- -[**User**](User.md) | | - - -#### SchemaFor200ResponseBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**User**](User.md) | | - - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor404 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -[**User**](User.md) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **login_user** -> str login_user(usernamepassword) - -Logs user into the system - -### Example - -```python -import petstore_api -from petstore_api.api import user_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = user_api.UserApi(api_client) - - # example passing only required values which don't have defaults set - query_params = { - 'username': "username_example", - 'password': "password_example", - } - try: - # Logs user into the system - api_response = api_instance.login_user( - query_params=query_params, - ) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling UserApi->login_user: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -query_params | RequestQueryParams | | -accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### query_params -#### RequestQueryParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -username | UsernameSchema | | -password | PasswordSchema | | - - -#### UsernameSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### PasswordSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -200 | ApiResponseFor200 | successful operation -400 | ApiResponseFor400 | Invalid username/password supplied - -#### ApiResponseFor200 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | -headers | ResponseHeadersFor200 | | - -#### SchemaFor200ResponseBodyApplicationXml - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -#### SchemaFor200ResponseBodyApplicationJson - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | -#### ResponseHeadersFor200 - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -X-Rate-Limit | XRateLimitSchema | | optional -X-Expires-After | XExpiresAfterSchema | | optional - -#### XRateLimitSchema - -calls per hour allowed by the user - -Type | Description | Notes -------------- | ------------- | ------------- -**int** | calls per hour allowed by the user | - -#### XExpiresAfterSchema - -date in UTC when token expires - -Type | Description | Notes -------------- | ------------- | ------------- -**datetime** | date in UTC when token expires | - - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -**str** - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **logout_user** -> logout_user() - -Logs out current logged in user session - -### Example - -```python -import petstore_api -from petstore_api.api import user_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = user_api.UserApi(api_client) - - # example, this endpoint has no required or optional parameters - try: - # Logs out current logged in user session - api_response = api_instance.logout_user() - except petstore_api.ApiException as e: - print("Exception when calling UserApi->logout_user: %s\n" % e) -``` -### Parameters -This endpoint does not need any parameter. - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -default | ApiResponseForDefault | successful operation - -#### ApiResponseForDefault -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **update_user** -> update_user(usernameuser) - -Updated user - -This can only be done by the logged in user. - -### Example - -```python -import petstore_api -from petstore_api.api import user_api -from petstore_api.model.user import User -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = user_api.UserApi(api_client) - - # example passing only required values which don't have defaults set - path_params = { - 'username': "username_example", - } - body = User( - id=1, - username="username_example", - first_name="first_name_example", - last_name="last_name_example", - email="email_example", - password="password_example", - phone="phone_example", - user_status=1, - object_with_no_declared_props=dict(), - object_with_no_declared_props_nullable=dict(), - any_type_prop=None, - any_type_except_null_prop=None, - any_type_prop_nullable=None, - ) - try: - # Updated user - api_response = api_instance.update_user( - path_params=path_params, - body=body, - ) - except petstore_api.ApiException as e: - print("Exception when calling UserApi->update_user: %s\n" % e) -``` -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -body | typing.Union[SchemaForRequestBodyApplicationJson] | required | -path_params | RequestPathParams | | -content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body -stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file -timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client -skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned - -### body - -#### SchemaForRequestBodyApplicationJson -Type | Description | Notes -------------- | ------------- | ------------- -[**User**](User.md) | | - - -### path_params -#### RequestPathParams - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -username | UsernameSchema | | - -#### UsernameSchema - -Type | Description | Notes -------------- | ------------- | ------------- -**str** | | - -### Return Types, Responses - -Code | Class | Description -------------- | ------------- | ------------- -n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned -400 | ApiResponseFor400 | Invalid user supplied -404 | ApiResponseFor404 | User not found - -#### ApiResponseFor400 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - -#### ApiResponseFor404 -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- -response | urllib3.HTTPResponse | Raw response | -body | Unset | body was not defined | -headers | Unset | headers were not defined | - - -void (empty response body) - -### Authorization - -No authorization required - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Whale.md b/samples/openapi3/client/petstore/python-experimental/docs/Whale.md deleted file mode 100644 index f0b2dbc51e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Whale.md +++ /dev/null @@ -1,12 +0,0 @@ -# Whale - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**hasBaleen** | **bool** | | [optional] -**hasTeeth** | **bool** | | [optional] -**className** | **str** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Zebra.md b/samples/openapi3/client/petstore/python-experimental/docs/Zebra.md deleted file mode 100644 index ae12668a3a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/docs/Zebra.md +++ /dev/null @@ -1,11 +0,0 @@ -# Zebra - -#### Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**type** | **str** | | [optional] -**className** | **str** | | -**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python-experimental/git_push.sh b/samples/openapi3/client/petstore/python-experimental/git_push.sh deleted file mode 100644 index ced3be2b0c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/git_push.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/__init__.py deleted file mode 100644 index 26b0467759..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -__version__ = "1.0.0" - -# import ApiClient -from petstore_api.api_client import ApiClient - -# import Configuration -from petstore_api.configuration import Configuration -from petstore_api.signing import HttpSigningConfiguration - -# import exceptions -from petstore_api.exceptions import OpenApiException -from petstore_api.exceptions import ApiAttributeError -from petstore_api.exceptions import ApiTypeError -from petstore_api.exceptions import ApiValueError -from petstore_api.exceptions import ApiKeyError -from petstore_api.exceptions import ApiException - -__import__('sys').setrecursionlimit(1234) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api_endpoints/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api_endpoints/__init__.py deleted file mode 100644 index 464f50cb8e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api_endpoints/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# do not import all endpoints into this module because that uses a lot of memory and stack frames -# if you need the ability to import all endpoints from this module, import them with -# from petstore_api.api.another_fake_api import AnotherFakeApi diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api_endpoints/call_123_test_special_tags.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api_endpoints/call_123_test_special_tags.py deleted file mode 100644 index 943d62ce47..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api_endpoints/call_123_test_special_tags.py +++ /dev/null @@ -1,172 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.client import Client - -# body param -SchemaForRequestBodyApplicationJson = Client - - -request_body_client = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/another-fake/dummy' -_method = 'PATCH' -SchemaFor200ResponseBodyApplicationJson = Client - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class Call123TestSpecialTags(api_client.Api): - - def call_123_test_special_tags( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - To test special tags - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_client.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py deleted file mode 100644 index 28b822701b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from petstore_api.api_client import ApiClient -from petstore_api.api.default_api_endpoints.foo_get import FooGet - - -class DefaultApi( - FooGet, - ApiClient, -): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api_endpoints/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api_endpoints/__init__.py deleted file mode 100644 index 9dad5771ea..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api_endpoints/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# do not import all endpoints into this module because that uses a lot of memory and stack frames -# if you need the ability to import all endpoints from this module, import them with -# from petstore_api.api.default_api import DefaultApi diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api_endpoints/foo_get.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api_endpoints/foo_get.py deleted file mode 100644 index 9c321a2dc9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api_endpoints/foo_get.py +++ /dev/null @@ -1,174 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.foo import Foo - -_path = '/foo' -_method = 'GET' - - -class SchemaFor0ResponseBodyApplicationJson( - DictSchema -): - - @classmethod - @property - def string(cls) -> typing.Type['Foo']: - return Foo - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - string: typing.Union['Foo', Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaFor0ResponseBodyApplicationJson': - return super().__new__( - cls, - *args, - string=string, - _configuration=_configuration, - **kwargs, - ) - - -@dataclass -class ApiResponseForDefault(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor0ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_default = api_client.OpenApiResponse( - response_cls=ApiResponseForDefault, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor0ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - 'default': _response_for_default, -} -_all_accept_content_types = ( - 'application/json', -) - - -class FooGet(api_client.Api): - - def foo_get( - self: api_client.Api, - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseForDefault, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - default_response = _status_code_to_response.get('default') - if default_response: - api_response = default_response.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py deleted file mode 100644 index 5e2fc9ec13..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from petstore_api.api_client import ApiClient -from petstore_api.api.fake_api_endpoints.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums -from petstore_api.api.fake_api_endpoints.array_model import ArrayModel -from petstore_api.api.fake_api_endpoints.array_of_enums import ArrayOfEnums -from petstore_api.api.fake_api_endpoints.body_with_file_schema import BodyWithFileSchema -from petstore_api.api.fake_api_endpoints.body_with_query_params import BodyWithQueryParams -from petstore_api.api.fake_api_endpoints.boolean import Boolean -from petstore_api.api.fake_api_endpoints.case_sensitive_params import CaseSensitiveParams -from petstore_api.api.fake_api_endpoints.client_model import ClientModel -from petstore_api.api.fake_api_endpoints.composed_one_of_different_types import ComposedOneOfDifferentTypes -from petstore_api.api.fake_api_endpoints.delete_coffee import DeleteCoffee -from petstore_api.api.fake_api_endpoints.endpoint_parameters import EndpointParameters -from petstore_api.api.fake_api_endpoints.enum_parameters import EnumParameters -from petstore_api.api.fake_api_endpoints.fake_health_get import FakeHealthGet -from petstore_api.api.fake_api_endpoints.group_parameters import GroupParameters -from petstore_api.api.fake_api_endpoints.inline_additional_properties import InlineAdditionalProperties -from petstore_api.api.fake_api_endpoints.inline_composition import InlineComposition -from petstore_api.api.fake_api_endpoints.json_form_data import JsonFormData -from petstore_api.api.fake_api_endpoints.json_with_charset import JsonWithCharset -from petstore_api.api.fake_api_endpoints.mammal import Mammal -from petstore_api.api.fake_api_endpoints.number_with_validations import NumberWithValidations -from petstore_api.api.fake_api_endpoints.object_in_query import ObjectInQuery -from petstore_api.api.fake_api_endpoints.object_model_with_ref_props import ObjectModelWithRefProps -from petstore_api.api.fake_api_endpoints.parameter_collisions import ParameterCollisions -from petstore_api.api.fake_api_endpoints.query_parameter_collection_format import QueryParameterCollectionFormat -from petstore_api.api.fake_api_endpoints.ref_object_in_query import RefObjectInQuery -from petstore_api.api.fake_api_endpoints.response_without_schema import ResponseWithoutSchema -from petstore_api.api.fake_api_endpoints.string import String -from petstore_api.api.fake_api_endpoints.string_enum import StringEnum -from petstore_api.api.fake_api_endpoints.upload_download_file import UploadDownloadFile -from petstore_api.api.fake_api_endpoints.upload_file import UploadFile -from petstore_api.api.fake_api_endpoints.upload_files import UploadFiles - - -class FakeApi( - AdditionalPropertiesWithArrayOfEnums, - ArrayModel, - ArrayOfEnums, - BodyWithFileSchema, - BodyWithQueryParams, - Boolean, - CaseSensitiveParams, - ClientModel, - ComposedOneOfDifferentTypes, - DeleteCoffee, - EndpointParameters, - EnumParameters, - FakeHealthGet, - GroupParameters, - InlineAdditionalProperties, - InlineComposition, - JsonFormData, - JsonWithCharset, - Mammal, - NumberWithValidations, - ObjectInQuery, - ObjectModelWithRefProps, - ParameterCollisions, - QueryParameterCollectionFormat, - RefObjectInQuery, - ResponseWithoutSchema, - String, - StringEnum, - UploadDownloadFile, - UploadFile, - UploadFiles, - ApiClient, -): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/__init__.py deleted file mode 100644 index 46b30d43ce..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# do not import all endpoints into this module because that uses a lot of memory and stack frames -# if you need the ability to import all endpoints from this module, import them with -# from petstore_api.api.fake_api import FakeApi diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/additional_properties_with_array_of_enums.py deleted file mode 100644 index be1abb21db..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/additional_properties_with_array_of_enums.py +++ /dev/null @@ -1,169 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums - -# body param -SchemaForRequestBodyApplicationJson = AdditionalPropertiesWithArrayOfEnums - - -request_body_additional_properties_with_array_of_enums = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/additional-properties-with-array-of-enums' -_method = 'GET' -SchemaFor200ResponseBodyApplicationJson = AdditionalPropertiesWithArrayOfEnums - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class AdditionalPropertiesWithArrayOfEnums(api_client.Api): - - def additional_properties_with_array_of_enums( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Additional Properties with Array of Enums - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_additional_properties_with_array_of_enums.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/array_model.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/array_model.py deleted file mode 100644 index 380c4e37fe..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/array_model.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.animal_farm import AnimalFarm - -# body param -SchemaForRequestBodyApplicationJson = AnimalFarm - - -request_body_body = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/refs/arraymodel' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = AnimalFarm - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class ArrayModel(api_client.Api): - - def array_model( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/array_of_enums.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/array_of_enums.py deleted file mode 100644 index a8b420e409..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/array_of_enums.py +++ /dev/null @@ -1,169 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.array_of_enums import ArrayOfEnums - -# body param -SchemaForRequestBodyApplicationJson = ArrayOfEnums - - -request_body_array_of_enums = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/refs/array-of-enums' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = ArrayOfEnums - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class ArrayOfEnums(api_client.Api): - - def array_of_enums( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Array of Enums - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_array_of_enums.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/body_with_file_schema.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/body_with_file_schema.py deleted file mode 100644 index 0c6b77e952..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/body_with_file_schema.py +++ /dev/null @@ -1,157 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.file_schema_test_class import FileSchemaTestClass - -# body param -SchemaForRequestBodyApplicationJson = FileSchemaTestClass - - -request_body_file_schema_test_class = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/fake/body-with-file-schema' -_method = 'PUT' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) -_status_code_to_response = { - '200': _response_for_200, -} - - -class BodyWithFileSchema(api_client.Api): - - def body_with_file_schema( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_file_schema_test_class.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/body_with_query_params.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/body_with_query_params.py deleted file mode 100644 index 0678ee1e42..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/body_with_query_params.py +++ /dev/null @@ -1,199 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.user import User - -# query params -QuerySchema = StrSchema -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - 'query': QuerySchema, - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_query = api_client.QueryParameter( - name="query", - style=api_client.ParameterStyle.FORM, - schema=QuerySchema, - required=True, - explode=True, -) -# body param -SchemaForRequestBodyApplicationJson = User - - -request_body_user = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/fake/body-with-query-params' -_method = 'PUT' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) -_status_code_to_response = { - '200': _response_for_200, -} - - -class BodyWithQueryParams(api_client.Api): - - def body_with_query_params( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - query_params: RequestQueryParams = frozendict(), - content_type: str = 'application/json', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_query, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_user.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/boolean.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/boolean.py deleted file mode 100644 index d3664ca80b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/boolean.py +++ /dev/null @@ -1,166 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# body param -SchemaForRequestBodyApplicationJson = BoolSchema - - -request_body_body = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/refs/boolean' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = BoolSchema - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class Boolean(api_client.Api): - - def boolean( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/case_sensitive_params.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/case_sensitive_params.py deleted file mode 100644 index 5fc282857a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/case_sensitive_params.py +++ /dev/null @@ -1,187 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# query params -SomeVarSchema = StrSchema -SomeVarSchema = StrSchema -SomeVarSchema = StrSchema -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - 'someVar': SomeVarSchema, - 'SomeVar': SomeVarSchema, - 'some_var': SomeVarSchema, - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_some_var = api_client.QueryParameter( - name="someVar", - style=api_client.ParameterStyle.FORM, - schema=SomeVarSchema, - required=True, - explode=True, -) -request_query_some_var2 = api_client.QueryParameter( - name="SomeVar", - style=api_client.ParameterStyle.FORM, - schema=SomeVarSchema, - required=True, - explode=True, -) -request_query_some_var3 = api_client.QueryParameter( - name="some_var", - style=api_client.ParameterStyle.FORM, - schema=SomeVarSchema, - required=True, - explode=True, -) -_path = '/fake/case-sensitive-params' -_method = 'PUT' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) -_status_code_to_response = { - '200': _response_for_200, -} - - -class CaseSensitiveParams(api_client.Api): - - def case_sensitive_params( - self: api_client.Api, - query_params: RequestQueryParams = frozendict(), - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_some_var, - request_query_some_var2, - request_query_some_var3, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/client_model.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/client_model.py deleted file mode 100644 index f5dba651d6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/client_model.py +++ /dev/null @@ -1,172 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.client import Client - -# body param -SchemaForRequestBodyApplicationJson = Client - - -request_body_client = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/fake' -_method = 'PATCH' -SchemaFor200ResponseBodyApplicationJson = Client - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class ClientModel(api_client.Api): - - def client_model( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - To test \"client\" model - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_client.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/composed_one_of_different_types.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/composed_one_of_different_types.py deleted file mode 100644 index 15edba9ec9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/composed_one_of_different_types.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes - -# body param -SchemaForRequestBodyApplicationJson = ComposedOneOfDifferentTypes - - -request_body_composed_one_of_different_types = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/refs/composed_one_of_number_with_validations' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = ComposedOneOfDifferentTypes - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class ComposedOneOfDifferentTypes(api_client.Api): - - def composed_one_of_different_types( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_composed_one_of_different_types.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/delete_coffee.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/delete_coffee.py deleted file mode 100644 index 0824c6bb56..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/delete_coffee.py +++ /dev/null @@ -1,185 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# path params -IdSchema = StrSchema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'id': IdSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_id = api_client.PathParameter( - name="id", - style=api_client.ParameterStyle.SIMPLE, - schema=IdSchema, - required=True, -) -_path = '/fake/deleteCoffee/{id}' -_method = 'DELETE' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) - - -@dataclass -class ApiResponseForDefault(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_default = api_client.OpenApiResponse( - response_cls=ApiResponseForDefault, -) -_status_code_to_response = { - '200': _response_for_200, - 'default': _response_for_default, -} - - -class DeleteCoffee(api_client.Api): - - def delete_coffee( - self: api_client.Api, - path_params: RequestPathParams = frozendict(), - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - ApiResponseForDefault, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Delete coffee - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_id, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - default_response = _status_code_to_response.get('default') - if default_response: - api_response = default_response.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/endpoint_parameters.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/endpoint_parameters.py deleted file mode 100644 index d4bfb218fd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/endpoint_parameters.py +++ /dev/null @@ -1,311 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# body param - - -class SchemaForRequestBodyApplicationXWwwFormUrlencoded( - DictSchema -): - _required_property_names = set(( - 'number', - 'double', - 'pattern_without_delimiter', - 'byte', - )) - - - class integer( - _SchemaValidator( - inclusive_maximum=100, - inclusive_minimum=10, - ), - IntSchema - ): - pass - - - class int32( - _SchemaValidator( - inclusive_maximum=200, - inclusive_minimum=20, - ), - Int32Schema - ): - pass - int64 = Int64Schema - - - class number( - _SchemaValidator( - inclusive_maximum=543.2, - inclusive_minimum=32.1, - ), - NumberSchema - ): - pass - - - class _float( - _SchemaValidator( - inclusive_maximum=987.6, - ), - Float32Schema - ): - pass - locals()["float"] = _float - del locals()['_float'] - - - class double( - _SchemaValidator( - inclusive_maximum=123.4, - inclusive_minimum=67.8, - ), - Float64Schema - ): - pass - - - class string( - _SchemaValidator( - regex=[{ - 'pattern': r'[a-z]', # noqa: E501 - 'flags': ( - re.IGNORECASE - ) - }], - ), - StrSchema - ): - pass - - - class pattern_without_delimiter( - _SchemaValidator( - regex=[{ - 'pattern': r'^[A-Z].*', # noqa: E501 - }], - ), - StrSchema - ): - pass - byte = StrSchema - binary = BinarySchema - date = DateSchema - dateTime = DateTimeSchema - - - class password( - _SchemaValidator( - max_length=64, - min_length=10, - ), - StrSchema - ): - pass - callback = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - number: number, - double: double, - pattern_without_delimiter: pattern_without_delimiter, - byte: byte, - integer: typing.Union[integer, Unset] = unset, - int32: typing.Union[int32, Unset] = unset, - int64: typing.Union[int64, Unset] = unset, - string: typing.Union[string, Unset] = unset, - binary: typing.Union[binary, Unset] = unset, - date: typing.Union[date, Unset] = unset, - dateTime: typing.Union[dateTime, Unset] = unset, - password: typing.Union[password, Unset] = unset, - callback: typing.Union[callback, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': - return super().__new__( - cls, - *args, - number=number, - double=double, - pattern_without_delimiter=pattern_without_delimiter, - byte=byte, - integer=integer, - int32=int32, - int64=int64, - string=string, - binary=binary, - date=date, - dateTime=dateTime, - password=password, - callback=callback, - _configuration=_configuration, - **kwargs, - ) - - -request_body_body = api_client.RequestBody( - content={ - 'application/x-www-form-urlencoded': api_client.MediaType( - schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), - }, -) -_path = '/fake' -_method = 'POST' -_auth = [ - 'http_basic_test', -] - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) - - -@dataclass -class ApiResponseFor404(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_404 = api_client.OpenApiResponse( - response_cls=ApiResponseFor404, -) -_status_code_to_response = { - '400': _response_for_400, - '404': _response_for_404, -} - - -class EndpointParameters(api_client.Api): - - def endpoint_parameters( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] = unset, - content_type: str = 'application/x-www-form-urlencoded', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - api_client.ApiResponseWithoutDeserialization - ]: - """ - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/enum_parameters.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/enum_parameters.py deleted file mode 100644 index b6e8924f58..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/enum_parameters.py +++ /dev/null @@ -1,493 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# query params - - -class EnumQueryStringArraySchema( - ListSchema -): - - - class _items( - _SchemaEnumMaker( - enum_value_to_name={ - ">": "GREATER_THAN", - "$": "DOLLAR", - } - ), - StrSchema - ): - - @classmethod - @property - def GREATER_THAN(cls): - return cls(">") - - @classmethod - @property - def DOLLAR(cls): - return cls("$") - - -class EnumQueryStringSchema( - _SchemaEnumMaker( - enum_value_to_name={ - "_abc": "_ABC", - "-efg": "EFG", - "(xyz)": "XYZ", - } - ), - StrSchema -): - - @classmethod - @property - def _ABC(cls): - return cls("_abc") - - @classmethod - @property - def EFG(cls): - return cls("-efg") - - @classmethod - @property - def XYZ(cls): - return cls("(xyz)") - - -class EnumQueryIntegerSchema( - _SchemaEnumMaker( - enum_value_to_name={ - 1: "POSITIVE_1", - -2: "NEGATIVE_2", - } - ), - Int32Schema -): - - @classmethod - @property - def POSITIVE_1(cls): - return cls(1) - - @classmethod - @property - def NEGATIVE_2(cls): - return cls(-2) - - -class EnumQueryDoubleSchema( - _SchemaEnumMaker( - enum_value_to_name={ - 1.1: "POSITIVE_1_PT_1", - -1.2: "NEGATIVE_1_PT_2", - } - ), - Float64Schema -): - - @classmethod - @property - def POSITIVE_1_PT_1(cls): - return cls(1.1) - - @classmethod - @property - def NEGATIVE_1_PT_2(cls): - return cls(-1.2) -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - 'enum_query_string_array': EnumQueryStringArraySchema, - 'enum_query_string': EnumQueryStringSchema, - 'enum_query_integer': EnumQueryIntegerSchema, - 'enum_query_double': EnumQueryDoubleSchema, - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_enum_query_string_array = api_client.QueryParameter( - name="enum_query_string_array", - style=api_client.ParameterStyle.FORM, - schema=EnumQueryStringArraySchema, - explode=True, -) -request_query_enum_query_string = api_client.QueryParameter( - name="enum_query_string", - style=api_client.ParameterStyle.FORM, - schema=EnumQueryStringSchema, - explode=True, -) -request_query_enum_query_integer = api_client.QueryParameter( - name="enum_query_integer", - style=api_client.ParameterStyle.FORM, - schema=EnumQueryIntegerSchema, - explode=True, -) -request_query_enum_query_double = api_client.QueryParameter( - name="enum_query_double", - style=api_client.ParameterStyle.FORM, - schema=EnumQueryDoubleSchema, - explode=True, -) -# header params - - -class EnumHeaderStringArraySchema( - ListSchema -): - - - class _items( - _SchemaEnumMaker( - enum_value_to_name={ - ">": "GREATER_THAN", - "$": "DOLLAR", - } - ), - StrSchema - ): - - @classmethod - @property - def GREATER_THAN(cls): - return cls(">") - - @classmethod - @property - def DOLLAR(cls): - return cls("$") - - -class EnumHeaderStringSchema( - _SchemaEnumMaker( - enum_value_to_name={ - "_abc": "_ABC", - "-efg": "EFG", - "(xyz)": "XYZ", - } - ), - StrSchema -): - - @classmethod - @property - def _ABC(cls): - return cls("_abc") - - @classmethod - @property - def EFG(cls): - return cls("-efg") - - @classmethod - @property - def XYZ(cls): - return cls("(xyz)") -RequestRequiredHeaderParams = typing.TypedDict( - 'RequestRequiredHeaderParams', - { - } -) -RequestOptionalHeaderParams = typing.TypedDict( - 'RequestOptionalHeaderParams', - { - 'enum_header_string_array': EnumHeaderStringArraySchema, - 'enum_header_string': EnumHeaderStringSchema, - }, - total=False -) - - -class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): - pass - - -request_header_enum_header_string_array = api_client.HeaderParameter( - name="enum_header_string_array", - style=api_client.ParameterStyle.SIMPLE, - schema=EnumHeaderStringArraySchema, -) -request_header_enum_header_string = api_client.HeaderParameter( - name="enum_header_string", - style=api_client.ParameterStyle.SIMPLE, - schema=EnumHeaderStringSchema, -) -# body param - - -class SchemaForRequestBodyApplicationXWwwFormUrlencoded( - DictSchema -): - - - class enum_form_string_array( - ListSchema - ): - - - class _items( - _SchemaEnumMaker( - enum_value_to_name={ - ">": "GREATER_THAN", - "$": "DOLLAR", - } - ), - StrSchema - ): - - @classmethod - @property - def GREATER_THAN(cls): - return cls(">") - - @classmethod - @property - def DOLLAR(cls): - return cls("$") - - - class enum_form_string( - _SchemaEnumMaker( - enum_value_to_name={ - "_abc": "_ABC", - "-efg": "EFG", - "(xyz)": "XYZ", - } - ), - StrSchema - ): - - @classmethod - @property - def _ABC(cls): - return cls("_abc") - - @classmethod - @property - def EFG(cls): - return cls("-efg") - - @classmethod - @property - def XYZ(cls): - return cls("(xyz)") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - enum_form_string_array: typing.Union[enum_form_string_array, Unset] = unset, - enum_form_string: typing.Union[enum_form_string, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': - return super().__new__( - cls, - *args, - enum_form_string_array=enum_form_string_array, - enum_form_string=enum_form_string, - _configuration=_configuration, - **kwargs, - ) - - -request_body_body = api_client.RequestBody( - content={ - 'application/x-www-form-urlencoded': api_client.MediaType( - schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), - }, -) -_path = '/fake' -_method = 'GET' - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) - - -@dataclass -class ApiResponseFor404(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_404 = api_client.OpenApiResponse( - response_cls=ApiResponseFor404, -) -_status_code_to_response = { - '400': _response_for_400, - '404': _response_for_404, -} - - -class EnumParameters(api_client.Api): - - def enum_parameters( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] = unset, - query_params: RequestQueryParams = frozendict(), - header_params: RequestHeaderParams = frozendict(), - content_type: str = 'application/x-www-form-urlencoded', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - api_client.ApiResponseWithoutDeserialization - ]: - """ - To test enum parameters - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - self._verify_typed_dict_inputs(RequestHeaderParams, header_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_enum_query_string_array, - request_query_enum_query_string, - request_query_enum_query_integer, - request_query_enum_query_double, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - - _headers = HTTPHeaderDict() - for parameter in ( - request_header_enum_header_string_array, - request_header_enum_header_string, - ): - parameter_data = header_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _headers.extend(serialized_data) - # TODO add cookie handling - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/fake_health_get.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/fake_health_get.py deleted file mode 100644 index 6c6324c4a0..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/fake_health_get.py +++ /dev/null @@ -1,146 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.health_check_result import HealthCheckResult - -_path = '/fake/health' -_method = 'GET' -SchemaFor200ResponseBodyApplicationJson = HealthCheckResult - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class FakeHealthGet(api_client.Api): - - def fake_health_get( - self: api_client.Api, - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Health check endpoint - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/group_parameters.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/group_parameters.py deleted file mode 100644 index fd2d96c973..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/group_parameters.py +++ /dev/null @@ -1,247 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# query params -RequiredStringGroupSchema = IntSchema -RequiredInt64GroupSchema = Int64Schema -StringGroupSchema = IntSchema -Int64GroupSchema = Int64Schema -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - 'required_string_group': RequiredStringGroupSchema, - 'required_int64_group': RequiredInt64GroupSchema, - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - 'string_group': StringGroupSchema, - 'int64_group': Int64GroupSchema, - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_required_string_group = api_client.QueryParameter( - name="required_string_group", - style=api_client.ParameterStyle.FORM, - schema=RequiredStringGroupSchema, - required=True, - explode=True, -) -request_query_required_int64_group = api_client.QueryParameter( - name="required_int64_group", - style=api_client.ParameterStyle.FORM, - schema=RequiredInt64GroupSchema, - required=True, - explode=True, -) -request_query_string_group = api_client.QueryParameter( - name="string_group", - style=api_client.ParameterStyle.FORM, - schema=StringGroupSchema, - explode=True, -) -request_query_int64_group = api_client.QueryParameter( - name="int64_group", - style=api_client.ParameterStyle.FORM, - schema=Int64GroupSchema, - explode=True, -) -# header params -RequiredBooleanGroupSchema = BoolSchema -BooleanGroupSchema = BoolSchema -RequestRequiredHeaderParams = typing.TypedDict( - 'RequestRequiredHeaderParams', - { - 'required_boolean_group': RequiredBooleanGroupSchema, - } -) -RequestOptionalHeaderParams = typing.TypedDict( - 'RequestOptionalHeaderParams', - { - 'boolean_group': BooleanGroupSchema, - }, - total=False -) - - -class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): - pass - - -request_header_required_boolean_group = api_client.HeaderParameter( - name="required_boolean_group", - style=api_client.ParameterStyle.SIMPLE, - schema=RequiredBooleanGroupSchema, - required=True, -) -request_header_boolean_group = api_client.HeaderParameter( - name="boolean_group", - style=api_client.ParameterStyle.SIMPLE, - schema=BooleanGroupSchema, -) -_path = '/fake' -_method = 'DELETE' -_auth = [ - 'bearer_test', -] - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) -_status_code_to_response = { - '400': _response_for_400, -} - - -class GroupParameters(api_client.Api): - - def group_parameters( - self: api_client.Api, - query_params: RequestQueryParams = frozendict(), - header_params: RequestHeaderParams = frozendict(), - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - api_client.ApiResponseWithoutDeserialization - ]: - """ - Fake endpoint to test group parameters (optional) - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - self._verify_typed_dict_inputs(RequestHeaderParams, header_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_required_string_group, - request_query_required_int64_group, - request_query_string_group, - request_query_int64_group, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - - _headers = HTTPHeaderDict() - for parameter in ( - request_header_required_boolean_group, - request_header_boolean_group, - ): - parameter_data = header_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _headers.extend(serialized_data) - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/inline_additional_properties.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/inline_additional_properties.py deleted file mode 100644 index 7f2d1202cd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/inline_additional_properties.py +++ /dev/null @@ -1,175 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# body param - - -class SchemaForRequestBodyApplicationJson( - DictSchema -): - _additional_properties = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyApplicationJson': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - -request_body_request_body = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/fake/inline-additionalProperties' -_method = 'POST' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) -_status_code_to_response = { - '200': _response_for_200, -} - - -class InlineAdditionalProperties(api_client.Api): - - def inline_additional_properties( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - test inline additionalProperties - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_request_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/inline_composition.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/inline_composition.py deleted file mode 100644 index 99d7e470a8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/inline_composition.py +++ /dev/null @@ -1,582 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# query params - - -class CompositionAtRootSchema( - ComposedSchema -): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - _SchemaValidator( - min_length=1, - ), - StrSchema - ): - pass - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'CompositionAtRootSchema': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - -class CompositionInPropertySchema( - DictSchema -): - - - class someProp( - ComposedSchema - ): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - _SchemaValidator( - min_length=1, - ), - StrSchema - ): - pass - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'someProp': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - someProp: typing.Union[someProp, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'CompositionInPropertySchema': - return super().__new__( - cls, - *args, - someProp=someProp, - _configuration=_configuration, - **kwargs, - ) -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - 'compositionAtRoot': CompositionAtRootSchema, - 'compositionInProperty': CompositionInPropertySchema, - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_composition_at_root = api_client.QueryParameter( - name="compositionAtRoot", - style=api_client.ParameterStyle.FORM, - schema=CompositionAtRootSchema, - explode=True, -) -request_query_composition_in_property = api_client.QueryParameter( - name="compositionInProperty", - style=api_client.ParameterStyle.FORM, - schema=CompositionInPropertySchema, - explode=True, -) -# body param - - -class SchemaForRequestBodyApplicationJson( - ComposedSchema -): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - _SchemaValidator( - min_length=1, - ), - StrSchema - ): - pass - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyApplicationJson': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - -class SchemaForRequestBodyMultipartFormData( - DictSchema -): - - - class someProp( - ComposedSchema - ): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - _SchemaValidator( - min_length=1, - ), - StrSchema - ): - pass - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'someProp': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - someProp: typing.Union[someProp, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyMultipartFormData': - return super().__new__( - cls, - *args, - someProp=someProp, - _configuration=_configuration, - **kwargs, - ) - - -request_body_any_type = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - 'multipart/form-data': api_client.MediaType( - schema=SchemaForRequestBodyMultipartFormData), - }, -) -_path = '/fake/inlineComposition/' -_method = 'POST' - - -class SchemaFor200ResponseBodyApplicationJson( - ComposedSchema -): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - _SchemaValidator( - min_length=1, - ), - StrSchema - ): - pass - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaFor200ResponseBodyApplicationJson': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - -class SchemaFor200ResponseBodyMultipartFormData( - DictSchema -): - - - class someProp( - ComposedSchema - ): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - _SchemaValidator( - min_length=1, - ), - StrSchema - ): - pass - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'someProp': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - someProp: typing.Union[someProp, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaFor200ResponseBodyMultipartFormData': - return super().__new__( - cls, - *args, - someProp=someProp, - _configuration=_configuration, - **kwargs, - ) - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - SchemaFor200ResponseBodyMultipartFormData, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - 'multipart/form-data': api_client.MediaType( - schema=SchemaFor200ResponseBodyMultipartFormData), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', - 'multipart/form-data', -) - - -class InlineComposition(api_client.Api): - - def inline_composition( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, SchemaForRequestBodyMultipartFormData, Unset] = unset, - query_params: RequestQueryParams = frozendict(), - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - testing composed schemas at inline locations - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_composition_at_root, - request_query_composition_in_property, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_any_type.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/json_form_data.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/json_form_data.py deleted file mode 100644 index ce7e5851c6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/json_form_data.py +++ /dev/null @@ -1,181 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# body param - - -class SchemaForRequestBodyApplicationXWwwFormUrlencoded( - DictSchema -): - _required_property_names = set(( - 'param', - 'param2', - )) - param = StrSchema - param2 = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - param: param, - param2: param2, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': - return super().__new__( - cls, - *args, - param=param, - param2=param2, - _configuration=_configuration, - **kwargs, - ) - - -request_body_body = api_client.RequestBody( - content={ - 'application/x-www-form-urlencoded': api_client.MediaType( - schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), - }, -) -_path = '/fake/jsonFormData' -_method = 'GET' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) -_status_code_to_response = { - '200': _response_for_200, -} - - -class JsonFormData(api_client.Api): - - def json_form_data( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] = unset, - content_type: str = 'application/x-www-form-urlencoded', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - test json serialization of form data - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/json_with_charset.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/json_with_charset.py deleted file mode 100644 index f923afb936..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/json_with_charset.py +++ /dev/null @@ -1,167 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# body param -SchemaForRequestBodyApplicationJsonCharsetutf8 = AnyTypeSchema - - -request_body_body = api_client.RequestBody( - content={ - 'application/json; charset=utf-8': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJsonCharsetutf8), - }, -) -_path = '/fake/jsonWithCharset' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJsonCharsetutf8 = AnyTypeSchema - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJsonCharsetutf8, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json; charset=utf-8': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJsonCharsetutf8), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json; charset=utf-8', -) - - -class JsonWithCharset(api_client.Api): - - def json_with_charset( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, Unset] = unset, - content_type: str = 'application/json; charset=utf-8', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - json with charset tx and rx - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/mammal.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/mammal.py deleted file mode 100644 index 9b32bf0a62..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/mammal.py +++ /dev/null @@ -1,171 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.mammal import Mammal - -# body param -SchemaForRequestBodyApplicationJson = Mammal - - -request_body_mammal = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/fake/refs/mammal' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = Mammal - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class Mammal(api_client.Api): - - def mammal( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_mammal.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/number_with_validations.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/number_with_validations.py deleted file mode 100644 index 0a626c8249..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/number_with_validations.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.number_with_validations import NumberWithValidations - -# body param -SchemaForRequestBodyApplicationJson = NumberWithValidations - - -request_body_body = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/refs/number' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = NumberWithValidations - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class NumberWithValidations(api_client.Api): - - def number_with_validations( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/object_in_query.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/object_in_query.py deleted file mode 100644 index 94b5e0d865..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/object_in_query.py +++ /dev/null @@ -1,188 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# query params - - -class MapBeanSchema( - DictSchema -): - keyword = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - keyword: typing.Union[keyword, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MapBeanSchema': - return super().__new__( - cls, - *args, - keyword=keyword, - _configuration=_configuration, - **kwargs, - ) -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - 'mapBean': MapBeanSchema, - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_map_bean = api_client.QueryParameter( - name="mapBean", - style=api_client.ParameterStyle.DEEP_OBJECT, - schema=MapBeanSchema, - explode=True, -) -_path = '/fake/objInQuery' -_method = 'GET' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) -_status_code_to_response = { - '200': _response_for_200, -} - - -class ObjectInQuery(api_client.Api): - - def object_in_query( - self: api_client.Api, - query_params: RequestQueryParams = frozendict(), - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - user list - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_map_bean, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/object_model_with_ref_props.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/object_model_with_ref_props.py deleted file mode 100644 index 0dfa23dcb3..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/object_model_with_ref_props.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps - -# body param -SchemaForRequestBodyApplicationJson = ObjectModelWithRefProps - - -request_body_body = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/refs/object_model_with_ref_props' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = ObjectModelWithRefProps - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class ObjectModelWithRefProps(api_client.Api): - - def object_model_with_ref_props( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/parameter_collisions.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/parameter_collisions.py deleted file mode 100644 index 6cedc0e070..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/parameter_collisions.py +++ /dev/null @@ -1,440 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# query params -Model1Schema = StrSchema -ABSchema = StrSchema -AbSchema = StrSchema -ModelSelfSchema = StrSchema -ABSchema = StrSchema -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - '1': Model1Schema, - 'aB': ABSchema, - 'Ab': AbSchema, - 'self': ModelSelfSchema, - 'A-B': ABSchema, - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query__1 = api_client.QueryParameter( - name="1", - style=api_client.ParameterStyle.FORM, - schema=Model1Schema, - explode=True, -) -request_query_a_b = api_client.QueryParameter( - name="aB", - style=api_client.ParameterStyle.FORM, - schema=ABSchema, - explode=True, -) -request_query_ab = api_client.QueryParameter( - name="Ab", - style=api_client.ParameterStyle.FORM, - schema=AbSchema, - explode=True, -) -request_query__self = api_client.QueryParameter( - name="self", - style=api_client.ParameterStyle.FORM, - schema=ModelSelfSchema, - explode=True, -) -request_query_a_b2 = api_client.QueryParameter( - name="A-B", - style=api_client.ParameterStyle.FORM, - schema=ABSchema, - explode=True, -) -# header params -Model1Schema = StrSchema -ABSchema = StrSchema -ModelSelfSchema = StrSchema -ABSchema = StrSchema -RequestRequiredHeaderParams = typing.TypedDict( - 'RequestRequiredHeaderParams', - { - } -) -RequestOptionalHeaderParams = typing.TypedDict( - 'RequestOptionalHeaderParams', - { - '1': Model1Schema, - 'aB': ABSchema, - 'self': ModelSelfSchema, - 'A-B': ABSchema, - }, - total=False -) - - -class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): - pass - - -request_header__2 = api_client.HeaderParameter( - name="1", - style=api_client.ParameterStyle.SIMPLE, - schema=Model1Schema, -) -request_header_a_b3 = api_client.HeaderParameter( - name="aB", - style=api_client.ParameterStyle.SIMPLE, - schema=ABSchema, -) -request_header__self2 = api_client.HeaderParameter( - name="self", - style=api_client.ParameterStyle.SIMPLE, - schema=ModelSelfSchema, -) -request_header_a_b4 = api_client.HeaderParameter( - name="A-B", - style=api_client.ParameterStyle.SIMPLE, - schema=ABSchema, -) -# path params -Model1Schema = StrSchema -ABSchema = StrSchema -AbSchema = StrSchema -ModelSelfSchema = StrSchema -ABSchema = StrSchema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - '1': Model1Schema, - 'aB': ABSchema, - 'Ab': AbSchema, - 'self': ModelSelfSchema, - 'A-B': ABSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path__3 = api_client.PathParameter( - name="1", - style=api_client.ParameterStyle.SIMPLE, - schema=Model1Schema, - required=True, -) -request_path_a_b5 = api_client.PathParameter( - name="aB", - style=api_client.ParameterStyle.SIMPLE, - schema=ABSchema, - required=True, -) -request_path_ab2 = api_client.PathParameter( - name="Ab", - style=api_client.ParameterStyle.SIMPLE, - schema=AbSchema, - required=True, -) -request_path__self3 = api_client.PathParameter( - name="self", - style=api_client.ParameterStyle.SIMPLE, - schema=ModelSelfSchema, - required=True, -) -request_path_a_b6 = api_client.PathParameter( - name="A-B", - style=api_client.ParameterStyle.SIMPLE, - schema=ABSchema, - required=True, -) -# cookie params -Model1Schema = StrSchema -ABSchema = StrSchema -AbSchema = StrSchema -ModelSelfSchema = StrSchema -ABSchema = StrSchema -RequestRequiredCookieParams = typing.TypedDict( - 'RequestRequiredCookieParams', - { - } -) -RequestOptionalCookieParams = typing.TypedDict( - 'RequestOptionalCookieParams', - { - '1': Model1Schema, - 'aB': ABSchema, - 'Ab': AbSchema, - 'self': ModelSelfSchema, - 'A-B': ABSchema, - }, - total=False -) - - -class RequestCookieParams(RequestRequiredCookieParams, RequestOptionalCookieParams): - pass - - -request_cookie__4 = api_client.CookieParameter( - name="1", - style=api_client.ParameterStyle.FORM, - schema=Model1Schema, - explode=True, -) -request_cookie_a_b7 = api_client.CookieParameter( - name="aB", - style=api_client.ParameterStyle.FORM, - schema=ABSchema, - explode=True, -) -request_cookie_ab3 = api_client.CookieParameter( - name="Ab", - style=api_client.ParameterStyle.FORM, - schema=AbSchema, - explode=True, -) -request_cookie__self4 = api_client.CookieParameter( - name="self", - style=api_client.ParameterStyle.FORM, - schema=ModelSelfSchema, - explode=True, -) -request_cookie_a_b8 = api_client.CookieParameter( - name="A-B", - style=api_client.ParameterStyle.FORM, - schema=ABSchema, - explode=True, -) -# body param -SchemaForRequestBodyApplicationJson = AnyTypeSchema - - -request_body_body = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/parameterCollisions/{1}/{aB}/{Ab}/{self}/{A-B}/' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = AnyTypeSchema - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class ParameterCollisions(api_client.Api): - - def parameter_collisions( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - query_params: RequestQueryParams = frozendict(), - header_params: RequestHeaderParams = frozendict(), - path_params: RequestPathParams = frozendict(), - cookie_params: RequestCookieParams = frozendict(), - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - parameter collision case - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - self._verify_typed_dict_inputs(RequestHeaderParams, header_params) - self._verify_typed_dict_inputs(RequestPathParams, path_params) - self._verify_typed_dict_inputs(RequestCookieParams, cookie_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path__3, - request_path_a_b5, - request_path_ab2, - request_path__self3, - request_path_a_b6, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - - prefix_separator_iterator = None - for parameter in ( - request_query__1, - request_query_a_b, - request_query_ab, - request_query__self, - request_query_a_b2, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - - _headers = HTTPHeaderDict() - for parameter in ( - request_header__2, - request_header_a_b3, - request_header__self2, - request_header_a_b4, - ): - parameter_data = header_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _headers.extend(serialized_data) - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/query_parameter_collection_format.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/query_parameter_collection_format.py deleted file mode 100644 index 8a330bc9ee..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/query_parameter_collection_format.py +++ /dev/null @@ -1,241 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.string_with_validation import StringWithValidation - -# query params - - -class PipeSchema( - ListSchema -): - _items = StrSchema - - -class IoutilSchema( - ListSchema -): - _items = StrSchema - - -class HttpSchema( - ListSchema -): - _items = StrSchema - - -class UrlSchema( - ListSchema -): - _items = StrSchema - - -class ContextSchema( - ListSchema -): - _items = StrSchema -RefParamSchema = StringWithValidation -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - 'pipe': PipeSchema, - 'ioutil': IoutilSchema, - 'http': HttpSchema, - 'url': UrlSchema, - 'context': ContextSchema, - 'refParam': RefParamSchema, - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_pipe = api_client.QueryParameter( - name="pipe", - style=api_client.ParameterStyle.FORM, - schema=PipeSchema, - required=True, - explode=True, -) -request_query_ioutil = api_client.QueryParameter( - name="ioutil", - style=api_client.ParameterStyle.FORM, - schema=IoutilSchema, - required=True, -) -request_query_http = api_client.QueryParameter( - name="http", - style=api_client.ParameterStyle.SPACE_DELIMITED, - schema=HttpSchema, - required=True, -) -request_query_url = api_client.QueryParameter( - name="url", - style=api_client.ParameterStyle.FORM, - schema=UrlSchema, - required=True, -) -request_query_context = api_client.QueryParameter( - name="context", - style=api_client.ParameterStyle.FORM, - schema=ContextSchema, - required=True, - explode=True, -) -request_query_ref_param = api_client.QueryParameter( - name="refParam", - style=api_client.ParameterStyle.FORM, - schema=RefParamSchema, - required=True, - explode=True, -) -_path = '/fake/test-query-paramters' -_method = 'PUT' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) -_status_code_to_response = { - '200': _response_for_200, -} - - -class QueryParameterCollectionFormat(api_client.Api): - - def query_parameter_collection_format( - self: api_client.Api, - query_params: RequestQueryParams = frozendict(), - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_pipe, - request_query_ioutil, - request_query_http, - request_query_url, - request_query_context, - request_query_ref_param, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/ref_object_in_query.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/ref_object_in_query.py deleted file mode 100644 index 31c96a704f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/ref_object_in_query.py +++ /dev/null @@ -1,169 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.foo import Foo - -# query params -MapBeanSchema = Foo -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - 'mapBean': MapBeanSchema, - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_map_bean = api_client.QueryParameter( - name="mapBean", - style=api_client.ParameterStyle.DEEP_OBJECT, - schema=MapBeanSchema, - explode=True, -) -_path = '/fake/refObjInQuery' -_method = 'GET' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) -_status_code_to_response = { - '200': _response_for_200, -} - - -class RefObjectInQuery(api_client.Api): - - def ref_object_in_query( - self: api_client.Api, - query_params: RequestQueryParams = frozendict(), - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - user list - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_map_bean, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/response_without_schema.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/response_without_schema.py deleted file mode 100644 index bb56af4d75..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/response_without_schema.py +++ /dev/null @@ -1,145 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -_path = '/fake/responseWithoutSchema' -_method = 'GET' - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - Unset, - Unset, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType(), - 'application/xml': api_client.MediaType(), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', - 'application/xml', -) - - -class ResponseWithoutSchema(api_client.Api): - - def response_without_schema( - self: api_client.Api, - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - receives a response without schema - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/string.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/string.py deleted file mode 100644 index 311dcc72a3..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/string.py +++ /dev/null @@ -1,166 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# body param -SchemaForRequestBodyApplicationJson = StrSchema - - -request_body_body = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/refs/string' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = StrSchema - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class String(api_client.Api): - - def string( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/string_enum.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/string_enum.py deleted file mode 100644 index 32cf1d5615..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/string_enum.py +++ /dev/null @@ -1,168 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.string_enum import StringEnum - -# body param -SchemaForRequestBodyApplicationJson = StringEnum - - -request_body_body = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, -) -_path = '/fake/refs/enum' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = StringEnum - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class StringEnum(api_client.Api): - - def string_enum( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset, - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_download_file.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_download_file.py deleted file mode 100644 index d272589ed5..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_download_file.py +++ /dev/null @@ -1,170 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# body param -SchemaForRequestBodyApplicationOctetStream = BinarySchema - - -request_body_body = api_client.RequestBody( - content={ - 'application/octet-stream': api_client.MediaType( - schema=SchemaForRequestBodyApplicationOctetStream), - }, - required=True, -) -_path = '/fake/uploadDownloadFile' -_method = 'POST' -SchemaFor200ResponseBodyApplicationOctetStream = BinarySchema - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationOctetStream, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/octet-stream': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationOctetStream), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/octet-stream', -) - - -class UploadDownloadFile(api_client.Api): - - def upload_download_file( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationOctetStream], - content_type: str = 'application/octet-stream', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - uploads a file and downloads a file using application/octet-stream - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_file.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_file.py deleted file mode 100644 index c8c8a179a5..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_file.py +++ /dev/null @@ -1,196 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.api_response import ApiResponse - -# body param - - -class SchemaForRequestBodyMultipartFormData( - DictSchema -): - _required_property_names = set(( - 'file', - )) - additionalMetadata = StrSchema - file = BinarySchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - file: file, - additionalMetadata: typing.Union[additionalMetadata, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyMultipartFormData': - return super().__new__( - cls, - *args, - file=file, - additionalMetadata=additionalMetadata, - _configuration=_configuration, - **kwargs, - ) - - -request_body_body = api_client.RequestBody( - content={ - 'multipart/form-data': api_client.MediaType( - schema=SchemaForRequestBodyMultipartFormData), - }, -) -_path = '/fake/uploadFile' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = ApiResponse - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class UploadFile(api_client.Api): - - def upload_file( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyMultipartFormData, Unset] = unset, - content_type: str = 'multipart/form-data', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - uploads a file using multipart/form-data - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_files.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_files.py deleted file mode 100644 index 574195370b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_files.py +++ /dev/null @@ -1,195 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.api_response import ApiResponse - -# body param - - -class SchemaForRequestBodyMultipartFormData( - DictSchema -): - - - class files( - ListSchema - ): - _items = BinarySchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - files: typing.Union[files, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyMultipartFormData': - return super().__new__( - cls, - *args, - files=files, - _configuration=_configuration, - **kwargs, - ) - - -request_body_body = api_client.RequestBody( - content={ - 'multipart/form-data': api_client.MediaType( - schema=SchemaForRequestBodyMultipartFormData), - }, -) -_path = '/fake/uploadFiles' -_method = 'POST' -SchemaFor200ResponseBodyApplicationJson = ApiResponse - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class UploadFiles(api_client.Api): - - def upload_files( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyMultipartFormData, Unset] = unset, - content_type: str = 'multipart/form-data', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - uploads files using multipart/form-data - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags123_api_endpoints/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags123_api_endpoints/__init__.py deleted file mode 100644 index 51f0b89af1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags123_api_endpoints/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# do not import all endpoints into this module because that uses a lot of memory and stack frames -# if you need the ability to import all endpoints from this module, import them with -# from petstore_api.api.fake_classname_tags123_api import FakeClassnameTags123Api diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags123_api_endpoints/classname.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags123_api_endpoints/classname.py deleted file mode 100644 index a9d14bad61..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags123_api_endpoints/classname.py +++ /dev/null @@ -1,176 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.client import Client - -# body param -SchemaForRequestBodyApplicationJson = Client - - -request_body_client = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/fake_classname_test' -_method = 'PATCH' -_auth = [ - 'api_key_query', -] -SchemaFor200ResponseBodyApplicationJson = Client - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class Classname(api_client.Api): - - def classname( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - To test class name in snake case - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_client.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py deleted file mode 100644 index cda926e1d0..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from petstore_api.api_client import ApiClient -from petstore_api.api.fake_classname_tags_123_api_endpoints.classname import Classname - - -class FakeClassnameTags123Api( - Classname, - ApiClient, -): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py deleted file mode 100644 index 83efafb3ec..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from petstore_api.api_client import ApiClient -from petstore_api.api.pet_api_endpoints.add_pet import AddPet -from petstore_api.api.pet_api_endpoints.delete_pet import DeletePet -from petstore_api.api.pet_api_endpoints.find_pets_by_status import FindPetsByStatus -from petstore_api.api.pet_api_endpoints.find_pets_by_tags import FindPetsByTags -from petstore_api.api.pet_api_endpoints.get_pet_by_id import GetPetById -from petstore_api.api.pet_api_endpoints.update_pet import UpdatePet -from petstore_api.api.pet_api_endpoints.update_pet_with_form import UpdatePetWithForm -from petstore_api.api.pet_api_endpoints.upload_file_with_required_file import UploadFileWithRequiredFile -from petstore_api.api.pet_api_endpoints.upload_image import UploadImage - - -class PetApi( - AddPet, - DeletePet, - FindPetsByStatus, - FindPetsByTags, - GetPetById, - UpdatePet, - UpdatePetWithForm, - UploadFileWithRequiredFile, - UploadImage, - ApiClient, -): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/__init__.py deleted file mode 100644 index 71e83ec445..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# do not import all endpoints into this module because that uses a lot of memory and stack frames -# if you need the ability to import all endpoints from this module, import them with -# from petstore_api.api.pet_api import PetApi diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/add_pet.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/add_pet.py deleted file mode 100644 index 9c288856f0..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/add_pet.py +++ /dev/null @@ -1,193 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.pet import Pet - -# body param -SchemaForRequestBodyApplicationJson = Pet -SchemaForRequestBodyApplicationXml = Pet - - -request_body_pet = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - 'application/xml': api_client.MediaType( - schema=SchemaForRequestBodyApplicationXml), - }, - required=True, -) -_path = '/pet' -_method = 'POST' -_auth = [ - 'http_signature_test', - 'petstore_auth', -] -_servers = ( - { - 'url': "http://petstore.swagger.io/v2", - 'description': "No description provided", - }, - { - 'url': "http://path-server-test.petstore.local/v2", - 'description': "No description provided", - }, -) - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, -) - - -@dataclass -class ApiResponseFor405(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_405 = api_client.OpenApiResponse( - response_cls=ApiResponseFor405, -) -_status_code_to_response = { - '200': _response_for_200, - '405': _response_for_405, -} - - -class AddPet(api_client.Api): - - def add_pet( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, SchemaForRequestBodyApplicationXml], - content_type: str = 'application/json', - host_index: typing.Optional[int] = None, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Add a new pet to the store - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_pet.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - host = self.get_host('add_pet', _servers, host_index) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - auth_settings=_auth, - host=host, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/delete_pet.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/delete_pet.py deleted file mode 100644 index 73c6243b64..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/delete_pet.py +++ /dev/null @@ -1,209 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# header params -ApiKeySchema = StrSchema -RequestRequiredHeaderParams = typing.TypedDict( - 'RequestRequiredHeaderParams', - { - } -) -RequestOptionalHeaderParams = typing.TypedDict( - 'RequestOptionalHeaderParams', - { - 'api_key': ApiKeySchema, - }, - total=False -) - - -class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): - pass - - -request_header_api_key = api_client.HeaderParameter( - name="api_key", - style=api_client.ParameterStyle.SIMPLE, - schema=ApiKeySchema, -) -# path params -PetIdSchema = Int64Schema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'petId': PetIdSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_pet_id = api_client.PathParameter( - name="petId", - style=api_client.ParameterStyle.SIMPLE, - schema=PetIdSchema, - required=True, -) -_path = '/pet/{petId}' -_method = 'DELETE' -_auth = [ - 'petstore_auth', -] - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) -_status_code_to_response = { - '400': _response_for_400, -} - - -class DeletePet(api_client.Api): - - def delete_pet( - self: api_client.Api, - header_params: RequestHeaderParams = frozendict(), - path_params: RequestPathParams = frozendict(), - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - api_client.ApiResponseWithoutDeserialization - ]: - """ - Deletes a pet - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestHeaderParams, header_params) - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_pet_id, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - - _headers = HTTPHeaderDict() - for parameter in ( - request_header_api_key, - ): - parameter_data = header_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _headers.extend(serialized_data) - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/find_pets_by_status.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/find_pets_by_status.py deleted file mode 100644 index ba51127bae..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/find_pets_by_status.py +++ /dev/null @@ -1,259 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.pet import Pet - -# query params - - -class StatusSchema( - ListSchema -): - - - class _items( - _SchemaEnumMaker( - enum_value_to_name={ - "available": "AVAILABLE", - "pending": "PENDING", - "sold": "SOLD", - } - ), - StrSchema - ): - - @classmethod - @property - def AVAILABLE(cls): - return cls("available") - - @classmethod - @property - def PENDING(cls): - return cls("pending") - - @classmethod - @property - def SOLD(cls): - return cls("sold") -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - 'status': StatusSchema, - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_status = api_client.QueryParameter( - name="status", - style=api_client.ParameterStyle.FORM, - schema=StatusSchema, - required=True, -) -_path = '/pet/findByStatus' -_method = 'GET' -_auth = [ - 'http_signature_test', - 'petstore_auth', -] - - -class SchemaFor200ResponseBodyApplicationXml( - ListSchema -): - - @classmethod - @property - def _items(cls) -> typing.Type['Pet']: - return Pet - - -class SchemaFor200ResponseBodyApplicationJson( - ListSchema -): - - @classmethod - @property - def _items(cls) -> typing.Type['Pet']: - return Pet - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationXml, - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/xml': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationXml), - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) -_status_code_to_response = { - '200': _response_for_200, - '400': _response_for_400, -} -_all_accept_content_types = ( - 'application/xml', - 'application/json', -) - - -class FindPetsByStatus(api_client.Api): - - def find_pets_by_status( - self: api_client.Api, - query_params: RequestQueryParams = frozendict(), - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Finds Pets by status - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_status, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/find_pets_by_tags.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/find_pets_by_tags.py deleted file mode 100644 index 7be1cd57d8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/find_pets_by_tags.py +++ /dev/null @@ -1,233 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.pet import Pet - -# query params - - -class TagsSchema( - ListSchema -): - _items = StrSchema -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - 'tags': TagsSchema, - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_tags = api_client.QueryParameter( - name="tags", - style=api_client.ParameterStyle.FORM, - schema=TagsSchema, - required=True, -) -_path = '/pet/findByTags' -_method = 'GET' -_auth = [ - 'http_signature_test', - 'petstore_auth', -] - - -class SchemaFor200ResponseBodyApplicationXml( - ListSchema -): - - @classmethod - @property - def _items(cls) -> typing.Type['Pet']: - return Pet - - -class SchemaFor200ResponseBodyApplicationJson( - ListSchema -): - - @classmethod - @property - def _items(cls) -> typing.Type['Pet']: - return Pet - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationXml, - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/xml': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationXml), - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) -_status_code_to_response = { - '200': _response_for_200, - '400': _response_for_400, -} -_all_accept_content_types = ( - 'application/xml', - 'application/json', -) - - -class FindPetsByTags(api_client.Api): - - def find_pets_by_tags( - self: api_client.Api, - query_params: RequestQueryParams = frozendict(), - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Finds Pets by tags - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_tags, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/get_pet_by_id.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/get_pet_by_id.py deleted file mode 100644 index a7509c9742..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/get_pet_by_id.py +++ /dev/null @@ -1,222 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.pet import Pet - -# path params -PetIdSchema = Int64Schema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'petId': PetIdSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_pet_id = api_client.PathParameter( - name="petId", - style=api_client.ParameterStyle.SIMPLE, - schema=PetIdSchema, - required=True, -) -_path = '/pet/{petId}' -_method = 'GET' -_auth = [ - 'api_key', -] -SchemaFor200ResponseBodyApplicationXml = Pet -SchemaFor200ResponseBodyApplicationJson = Pet - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationXml, - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/xml': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationXml), - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) - - -@dataclass -class ApiResponseFor404(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_404 = api_client.OpenApiResponse( - response_cls=ApiResponseFor404, -) -_status_code_to_response = { - '200': _response_for_200, - '400': _response_for_400, - '404': _response_for_404, -} -_all_accept_content_types = ( - 'application/xml', - 'application/json', -) - - -class GetPetById(api_client.Api): - - def get_pet_by_id( - self: api_client.Api, - path_params: RequestPathParams = frozendict(), - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Find pet by ID - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_pet_id, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/update_pet.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/update_pet.py deleted file mode 100644 index c7d9459244..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/update_pet.py +++ /dev/null @@ -1,205 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.pet import Pet - -# body param -SchemaForRequestBodyApplicationJson = Pet -SchemaForRequestBodyApplicationXml = Pet - - -request_body_pet = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - 'application/xml': api_client.MediaType( - schema=SchemaForRequestBodyApplicationXml), - }, - required=True, -) -_path = '/pet' -_method = 'PUT' -_auth = [ - 'http_signature_test', - 'petstore_auth', -] -_servers = ( - { - 'url': "http://petstore.swagger.io/v2", - 'description': "No description provided", - }, - { - 'url': "http://path-server-test.petstore.local/v2", - 'description': "No description provided", - }, -) - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) - - -@dataclass -class ApiResponseFor404(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_404 = api_client.OpenApiResponse( - response_cls=ApiResponseFor404, -) - - -@dataclass -class ApiResponseFor405(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_405 = api_client.OpenApiResponse( - response_cls=ApiResponseFor405, -) -_status_code_to_response = { - '400': _response_for_400, - '404': _response_for_404, - '405': _response_for_405, -} - - -class UpdatePet(api_client.Api): - - def update_pet( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson, SchemaForRequestBodyApplicationXml], - content_type: str = 'application/json', - host_index: typing.Optional[int] = None, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - api_client.ApiResponseWithoutDeserialization - ]: - """ - Update an existing pet - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_pet.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - host = self.get_host('update_pet', _servers, host_index) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - auth_settings=_auth, - host=host, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/update_pet_with_form.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/update_pet_with_form.py deleted file mode 100644 index c9ba7a9816..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/update_pet_with_form.py +++ /dev/null @@ -1,221 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# path params -PetIdSchema = Int64Schema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'petId': PetIdSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_pet_id = api_client.PathParameter( - name="petId", - style=api_client.ParameterStyle.SIMPLE, - schema=PetIdSchema, - required=True, -) -# body param - - -class SchemaForRequestBodyApplicationXWwwFormUrlencoded( - DictSchema -): - name = StrSchema - status = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - name: typing.Union[name, Unset] = unset, - status: typing.Union[status, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': - return super().__new__( - cls, - *args, - name=name, - status=status, - _configuration=_configuration, - **kwargs, - ) - - -request_body_body = api_client.RequestBody( - content={ - 'application/x-www-form-urlencoded': api_client.MediaType( - schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), - }, -) -_path = '/pet/{petId}' -_method = 'POST' -_auth = [ - 'petstore_auth', -] - - -@dataclass -class ApiResponseFor405(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_405 = api_client.OpenApiResponse( - response_cls=ApiResponseFor405, -) -_status_code_to_response = { - '405': _response_for_405, -} - - -class UpdatePetWithForm(api_client.Api): - - def update_pet_with_form( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] = unset, - path_params: RequestPathParams = frozendict(), - content_type: str = 'application/x-www-form-urlencoded', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - api_client.ApiResponseWithoutDeserialization - ]: - """ - Updates a pet in the store with form data - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_pet_id, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_file_with_required_file.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_file_with_required_file.py deleted file mode 100644 index fb1375c1b8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_file_with_required_file.py +++ /dev/null @@ -1,241 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.api_response import ApiResponse - -# path params -PetIdSchema = Int64Schema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'petId': PetIdSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_pet_id = api_client.PathParameter( - name="petId", - style=api_client.ParameterStyle.SIMPLE, - schema=PetIdSchema, - required=True, -) -# body param - - -class SchemaForRequestBodyMultipartFormData( - DictSchema -): - _required_property_names = set(( - 'requiredFile', - )) - additionalMetadata = StrSchema - requiredFile = BinarySchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - requiredFile: requiredFile, - additionalMetadata: typing.Union[additionalMetadata, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyMultipartFormData': - return super().__new__( - cls, - *args, - requiredFile=requiredFile, - additionalMetadata=additionalMetadata, - _configuration=_configuration, - **kwargs, - ) - - -request_body_body = api_client.RequestBody( - content={ - 'multipart/form-data': api_client.MediaType( - schema=SchemaForRequestBodyMultipartFormData), - }, -) -_path = '/fake/{petId}/uploadImageWithRequiredFile' -_method = 'POST' -_auth = [ - 'petstore_auth', -] -SchemaFor200ResponseBodyApplicationJson = ApiResponse - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class UploadFileWithRequiredFile(api_client.Api): - - def upload_file_with_required_file( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyMultipartFormData, Unset] = unset, - path_params: RequestPathParams = frozendict(), - content_type: str = 'multipart/form-data', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - uploads an image (required) - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_pet_id, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_image.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_image.py deleted file mode 100644 index 20bb010ae1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_image.py +++ /dev/null @@ -1,238 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.api_response import ApiResponse - -# path params -PetIdSchema = Int64Schema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'petId': PetIdSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_pet_id = api_client.PathParameter( - name="petId", - style=api_client.ParameterStyle.SIMPLE, - schema=PetIdSchema, - required=True, -) -# body param - - -class SchemaForRequestBodyMultipartFormData( - DictSchema -): - additionalMetadata = StrSchema - file = BinarySchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - additionalMetadata: typing.Union[additionalMetadata, Unset] = unset, - file: typing.Union[file, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaForRequestBodyMultipartFormData': - return super().__new__( - cls, - *args, - additionalMetadata=additionalMetadata, - file=file, - _configuration=_configuration, - **kwargs, - ) - - -request_body_body = api_client.RequestBody( - content={ - 'multipart/form-data': api_client.MediaType( - schema=SchemaForRequestBodyMultipartFormData), - }, -) -_path = '/pet/{petId}/uploadImage' -_method = 'POST' -_auth = [ - 'petstore_auth', -] -SchemaFor200ResponseBodyApplicationJson = ApiResponse - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class UploadImage(api_client.Api): - - def upload_image( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyMultipartFormData, Unset] = unset, - path_params: RequestPathParams = frozendict(), - content_type: str = 'multipart/form-data', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - uploads an image - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_pet_id, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - _fields = None - _body = None - if body is not unset: - serialized_data = request_body_body.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py deleted file mode 100644 index 3685a17280..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py +++ /dev/null @@ -1,31 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from petstore_api.api_client import ApiClient -from petstore_api.api.store_api_endpoints.delete_order import DeleteOrder -from petstore_api.api.store_api_endpoints.get_inventory import GetInventory -from petstore_api.api.store_api_endpoints.get_order_by_id import GetOrderById -from petstore_api.api.store_api_endpoints.place_order import PlaceOrder - - -class StoreApi( - DeleteOrder, - GetInventory, - GetOrderById, - PlaceOrder, - ApiClient, -): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/__init__.py deleted file mode 100644 index 30de2b107c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# do not import all endpoints into this module because that uses a lot of memory and stack frames -# if you need the ability to import all endpoints from this module, import them with -# from petstore_api.api.store_api import StoreApi diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/delete_order.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/delete_order.py deleted file mode 100644 index 46f33d453b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/delete_order.py +++ /dev/null @@ -1,179 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# path params -OrderIdSchema = StrSchema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'order_id': OrderIdSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_order_id = api_client.PathParameter( - name="order_id", - style=api_client.ParameterStyle.SIMPLE, - schema=OrderIdSchema, - required=True, -) -_path = '/store/order/{order_id}' -_method = 'DELETE' - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) - - -@dataclass -class ApiResponseFor404(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_404 = api_client.OpenApiResponse( - response_cls=ApiResponseFor404, -) -_status_code_to_response = { - '400': _response_for_400, - '404': _response_for_404, -} - - -class DeleteOrder(api_client.Api): - - def delete_order( - self: api_client.Api, - path_params: RequestPathParams = frozendict(), - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - api_client.ApiResponseWithoutDeserialization - ]: - """ - Delete purchase order by ID - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_order_id, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/get_inventory.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/get_inventory.py deleted file mode 100644 index 73410c09c7..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/get_inventory.py +++ /dev/null @@ -1,167 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -_path = '/store/inventory' -_method = 'GET' -_auth = [ - 'api_key', -] - - -class SchemaFor200ResponseBodyApplicationJson( - DictSchema -): - _additional_properties = Int32Schema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SchemaFor200ResponseBodyApplicationJson': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) -_status_code_to_response = { - '200': _response_for_200, -} -_all_accept_content_types = ( - 'application/json', -) - - -class GetInventory(api_client.Api): - - def get_inventory( - self: api_client.Api, - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Returns pet inventories by status - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - auth_settings=_auth, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/get_order_by_id.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/get_order_by_id.py deleted file mode 100644 index 56ef500f9d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/get_order_by_id.py +++ /dev/null @@ -1,227 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.order import Order - -# path params - - -class OrderIdSchema( - _SchemaValidator( - inclusive_maximum=5, - inclusive_minimum=1, - ), - Int64Schema -): - pass -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'order_id': OrderIdSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_order_id = api_client.PathParameter( - name="order_id", - style=api_client.ParameterStyle.SIMPLE, - schema=OrderIdSchema, - required=True, -) -_path = '/store/order/{order_id}' -_method = 'GET' -SchemaFor200ResponseBodyApplicationXml = Order -SchemaFor200ResponseBodyApplicationJson = Order - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationXml, - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/xml': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationXml), - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) - - -@dataclass -class ApiResponseFor404(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_404 = api_client.OpenApiResponse( - response_cls=ApiResponseFor404, -) -_status_code_to_response = { - '200': _response_for_200, - '400': _response_for_400, - '404': _response_for_404, -} -_all_accept_content_types = ( - 'application/xml', - 'application/json', -) - - -class GetOrderById(api_client.Api): - - def get_order_by_id( - self: api_client.Api, - path_params: RequestPathParams = frozendict(), - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Find purchase order by ID - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_order_id, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/place_order.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/place_order.py deleted file mode 100644 index 73a6355582..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/place_order.py +++ /dev/null @@ -1,190 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.order import Order - -# body param -SchemaForRequestBodyApplicationJson = Order - - -request_body_order = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/store/order' -_method = 'POST' -SchemaFor200ResponseBodyApplicationXml = Order -SchemaFor200ResponseBodyApplicationJson = Order - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationXml, - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/xml': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationXml), - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) -_status_code_to_response = { - '200': _response_for_200, - '400': _response_for_400, -} -_all_accept_content_types = ( - 'application/xml', - 'application/json', -) - - -class PlaceOrder(api_client.Api): - - def place_order( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Place an order for a pet - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_order.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py deleted file mode 100644 index 1975100b9e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from petstore_api.api_client import ApiClient -from petstore_api.api.user_api_endpoints.create_user import CreateUser -from petstore_api.api.user_api_endpoints.create_users_with_array_input import CreateUsersWithArrayInput -from petstore_api.api.user_api_endpoints.create_users_with_list_input import CreateUsersWithListInput -from petstore_api.api.user_api_endpoints.delete_user import DeleteUser -from petstore_api.api.user_api_endpoints.get_user_by_name import GetUserByName -from petstore_api.api.user_api_endpoints.login_user import LoginUser -from petstore_api.api.user_api_endpoints.logout_user import LogoutUser -from petstore_api.api.user_api_endpoints.update_user import UpdateUser - - -class UserApi( - CreateUser, - CreateUsersWithArrayInput, - CreateUsersWithListInput, - DeleteUser, - GetUserByName, - LoginUser, - LogoutUser, - UpdateUser, - ApiClient, -): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/__init__.py deleted file mode 100644 index 8dced02b76..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# do not import all endpoints into this module because that uses a lot of memory and stack frames -# if you need the ability to import all endpoints from this module, import them with -# from petstore_api.api.user_api import UserApi diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_user.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_user.py deleted file mode 100644 index 2871f0d215..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_user.py +++ /dev/null @@ -1,162 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.user import User - -# body param -SchemaForRequestBodyApplicationJson = User - - -request_body_user = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/user' -_method = 'POST' - - -@dataclass -class ApiResponseForDefault(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_default = api_client.OpenApiResponse( - response_cls=ApiResponseForDefault, -) -_status_code_to_response = { - 'default': _response_for_default, -} - - -class CreateUser(api_client.Api): - - def create_user( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseForDefault, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Create user - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_user.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - default_response = _status_code_to_response.get('default') - if default_response: - api_response = default_response.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_users_with_array_input.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_users_with_array_input.py deleted file mode 100644 index a2a462399b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_users_with_array_input.py +++ /dev/null @@ -1,171 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.user import User - -# body param - - -class SchemaForRequestBodyApplicationJson( - ListSchema -): - - @classmethod - @property - def _items(cls) -> typing.Type['User']: - return User - - -request_body_user = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/user/createWithArray' -_method = 'POST' - - -@dataclass -class ApiResponseForDefault(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_default = api_client.OpenApiResponse( - response_cls=ApiResponseForDefault, -) -_status_code_to_response = { - 'default': _response_for_default, -} - - -class CreateUsersWithArrayInput(api_client.Api): - - def create_users_with_array_input( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseForDefault, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Creates list of users with given input array - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_user.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - default_response = _status_code_to_response.get('default') - if default_response: - api_response = default_response.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_users_with_list_input.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_users_with_list_input.py deleted file mode 100644 index e79cba97e8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_users_with_list_input.py +++ /dev/null @@ -1,171 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.user import User - -# body param - - -class SchemaForRequestBodyApplicationJson( - ListSchema -): - - @classmethod - @property - def _items(cls) -> typing.Type['User']: - return User - - -request_body_user = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/user/createWithList' -_method = 'POST' - - -@dataclass -class ApiResponseForDefault(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_default = api_client.OpenApiResponse( - response_cls=ApiResponseForDefault, -) -_status_code_to_response = { - 'default': _response_for_default, -} - - -class CreateUsersWithListInput(api_client.Api): - - def create_users_with_list_input( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - content_type: str = 'application/json', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseForDefault, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Creates list of users with given input array - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_user.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - default_response = _status_code_to_response.get('default') - if default_response: - api_response = default_response.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/delete_user.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/delete_user.py deleted file mode 100644 index 34dc9d85bc..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/delete_user.py +++ /dev/null @@ -1,179 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# path params -UsernameSchema = StrSchema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'username': UsernameSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_username = api_client.PathParameter( - name="username", - style=api_client.ParameterStyle.SIMPLE, - schema=UsernameSchema, - required=True, -) -_path = '/user/{username}' -_method = 'DELETE' - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) - - -@dataclass -class ApiResponseFor404(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_404 = api_client.OpenApiResponse( - response_cls=ApiResponseFor404, -) -_status_code_to_response = { - '400': _response_for_400, - '404': _response_for_404, -} - - -class DeleteUser(api_client.Api): - - def delete_user( - self: api_client.Api, - path_params: RequestPathParams = frozendict(), - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - api_client.ApiResponseWithoutDeserialization - ]: - """ - Delete user - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_username, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/get_user_by_name.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/get_user_by_name.py deleted file mode 100644 index 71a9819913..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/get_user_by_name.py +++ /dev/null @@ -1,218 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.user import User - -# path params -UsernameSchema = StrSchema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'username': UsernameSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_username = api_client.PathParameter( - name="username", - style=api_client.ParameterStyle.SIMPLE, - schema=UsernameSchema, - required=True, -) -_path = '/user/{username}' -_method = 'GET' -SchemaFor200ResponseBodyApplicationXml = User -SchemaFor200ResponseBodyApplicationJson = User - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationXml, - SchemaFor200ResponseBodyApplicationJson, - ] - headers: Unset = unset - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/xml': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationXml), - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, -) - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) - - -@dataclass -class ApiResponseFor404(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_404 = api_client.OpenApiResponse( - response_cls=ApiResponseFor404, -) -_status_code_to_response = { - '200': _response_for_200, - '400': _response_for_400, - '404': _response_for_404, -} -_all_accept_content_types = ( - 'application/xml', - 'application/json', -) - - -class GetUserByName(api_client.Api): - - def get_user_by_name( - self: api_client.Api, - path_params: RequestPathParams = frozendict(), - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Get user by user name - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_username, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/login_user.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/login_user.py deleted file mode 100644 index d48dc43dc6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/login_user.py +++ /dev/null @@ -1,237 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -# query params -UsernameSchema = StrSchema -PasswordSchema = StrSchema -RequestRequiredQueryParams = typing.TypedDict( - 'RequestRequiredQueryParams', - { - 'username': UsernameSchema, - 'password': PasswordSchema, - } -) -RequestOptionalQueryParams = typing.TypedDict( - 'RequestOptionalQueryParams', - { - }, - total=False -) - - -class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): - pass - - -request_query_username = api_client.QueryParameter( - name="username", - style=api_client.ParameterStyle.FORM, - schema=UsernameSchema, - required=True, - explode=True, -) -request_query_password = api_client.QueryParameter( - name="password", - style=api_client.ParameterStyle.FORM, - schema=PasswordSchema, - required=True, - explode=True, -) -_path = '/user/login' -_method = 'GET' -XRateLimitSchema = Int32Schema -x_rate_limit_parameter = api_client.HeaderParameter( - name="X-Rate-Limit", - style=api_client.ParameterStyle.SIMPLE, - schema=XRateLimitSchema, -) -XExpiresAfterSchema = DateTimeSchema -x_expires_after_parameter = api_client.HeaderParameter( - name="X-Expires-After", - style=api_client.ParameterStyle.SIMPLE, - schema=XExpiresAfterSchema, -) -SchemaFor200ResponseBodyApplicationXml = StrSchema -SchemaFor200ResponseBodyApplicationJson = StrSchema -ResponseHeadersFor200 = typing.TypedDict( - 'ResponseHeadersFor200', - { - 'X-Rate-Limit': XRateLimitSchema, - 'X-Expires-After': XExpiresAfterSchema, - } -) - - -@dataclass -class ApiResponseFor200(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[ - SchemaFor200ResponseBodyApplicationXml, - SchemaFor200ResponseBodyApplicationJson, - ] - headers: ResponseHeadersFor200 - - -_response_for_200 = api_client.OpenApiResponse( - response_cls=ApiResponseFor200, - content={ - 'application/xml': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationXml), - 'application/json': api_client.MediaType( - schema=SchemaFor200ResponseBodyApplicationJson), - }, - headers=[ - x_rate_limit_parameter, - x_expires_after_parameter, - ] -) - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) -_status_code_to_response = { - '200': _response_for_200, - '400': _response_for_400, -} -_all_accept_content_types = ( - 'application/xml', - 'application/json', -) - - -class LoginUser(api_client.Api): - - def login_user( - self: api_client.Api, - query_params: RequestQueryParams = frozendict(), - accept_content_types: typing.Tuple[str] = _all_accept_content_types, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseFor200, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Logs user into the system - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestQueryParams, query_params) - used_path = _path - - prefix_separator_iterator = None - for parameter in ( - request_query_username, - request_query_password, - ): - parameter_data = query_params.get(parameter.name, unset) - if parameter_data is unset: - continue - if prefix_separator_iterator is None: - prefix_separator_iterator = parameter.get_prefix_separator_iterator() - serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) - for serialized_value in serialized_data.values(): - used_path += serialized_value - - _headers = HTTPHeaderDict() - # TODO add cookie handling - if accept_content_types: - for accept_content_type in accept_content_types: - _headers.add('Accept', accept_content_type) - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/logout_user.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/logout_user.py deleted file mode 100644 index d91518c02c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/logout_user.py +++ /dev/null @@ -1,130 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -_path = '/user/logout' -_method = 'GET' - - -@dataclass -class ApiResponseForDefault(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_default = api_client.OpenApiResponse( - response_cls=ApiResponseForDefault, -) -_status_code_to_response = { - 'default': _response_for_default, -} - - -class LogoutUser(api_client.Api): - - def logout_user( - self: api_client.Api, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - ApiResponseForDefault, - api_client.ApiResponseWithoutDeserialization - ]: - """ - Logs out current logged in user session - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - used_path = _path - # TODO add cookie handling - - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - default_response = _status_code_to_response.get('default') - if default_response: - api_response = default_response.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/update_user.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/update_user.py deleted file mode 100644 index 15cc7be110..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/update_user.py +++ /dev/null @@ -1,211 +0,0 @@ -# coding: utf-8 - -""" - - - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -import re # noqa: F401 -import sys # noqa: F401 -import typing -import urllib3 -import functools # noqa: F401 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client, exceptions -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - -from petstore_api.model.user import User - -# path params -UsernameSchema = StrSchema -RequestRequiredPathParams = typing.TypedDict( - 'RequestRequiredPathParams', - { - 'username': UsernameSchema, - } -) -RequestOptionalPathParams = typing.TypedDict( - 'RequestOptionalPathParams', - { - }, - total=False -) - - -class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): - pass - - -request_path_username = api_client.PathParameter( - name="username", - style=api_client.ParameterStyle.SIMPLE, - schema=UsernameSchema, - required=True, -) -# body param -SchemaForRequestBodyApplicationJson = User - - -request_body_user = api_client.RequestBody( - content={ - 'application/json': api_client.MediaType( - schema=SchemaForRequestBodyApplicationJson), - }, - required=True, -) -_path = '/user/{username}' -_method = 'PUT' - - -@dataclass -class ApiResponseFor400(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_400 = api_client.OpenApiResponse( - response_cls=ApiResponseFor400, -) - - -@dataclass -class ApiResponseFor404(api_client.ApiResponse): - response: urllib3.HTTPResponse - body: Unset = unset - headers: Unset = unset - - -_response_for_404 = api_client.OpenApiResponse( - response_cls=ApiResponseFor404, -) -_status_code_to_response = { - '400': _response_for_400, - '404': _response_for_404, -} - - -class UpdateUser(api_client.Api): - - def update_user( - self: api_client.Api, - body: typing.Union[SchemaForRequestBodyApplicationJson], - path_params: RequestPathParams = frozendict(), - content_type: str = 'application/json', - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - skip_deserialization: bool = False, - ) -> typing.Union[ - api_client.ApiResponseWithoutDeserialization - ]: - """ - Updated user - :param skip_deserialization: If true then api_response.response will be set but - api_response.body and api_response.headers will not be deserialized into schema - class instances - """ - self._verify_typed_dict_inputs(RequestPathParams, path_params) - used_path = _path - - _path_params = {} - for parameter in ( - request_path_username, - ): - parameter_data = path_params.get(parameter.name, unset) - if parameter_data is unset: - continue - serialized_data = parameter.serialize(parameter_data) - _path_params.update(serialized_data) - - for k, v in _path_params.items(): - used_path = used_path.replace('{%s}' % k, v) - - _headers = HTTPHeaderDict() - # TODO add cookie handling - - if body is unset: - raise exceptions.ApiValueError( - 'The required body parameter has an invalid value of: unset. Set a valid value instead') - _fields = None - _body = None - serialized_data = request_body_user.serialize(body, content_type) - _headers.add('Content-Type', content_type) - if 'fields' in serialized_data: - _fields = serialized_data['fields'] - elif 'body' in serialized_data: - _body = serialized_data['body'] - response = self.api_client.call_api( - resource_path=used_path, - method=_method, - headers=_headers, - fields=_fields, - body=_body, - stream=stream, - timeout=timeout, - ) - - if skip_deserialization: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - else: - response_for_status = _status_code_to_response.get(str(response.status)) - if response_for_status: - api_response = response_for_status.deserialize(response, self.api_client.configuration) - else: - api_response = api_client.ApiResponseWithoutDeserialization(response=response) - - if not 200 <= response.status <= 299: - raise exceptions.ApiException(api_response=api_response) - - return api_response diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api_client.py deleted file mode 100644 index fcd76cc5ca..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api_client.py +++ /dev/null @@ -1,1429 +0,0 @@ -# coding: utf-8 -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from dataclasses import dataclass -from decimal import Decimal -import enum -import email -import json -import os -import io -import atexit -from multiprocessing.pool import ThreadPool -import re -import tempfile -import typing -import urllib3 -from urllib3._collections import HTTPHeaderDict -from urllib.parse import quote -from urllib3.fields import RequestField as RequestFieldBase - - -from petstore_api import rest -from petstore_api.configuration import Configuration -from petstore_api.exceptions import ApiTypeError, ApiValueError -from petstore_api.schemas import ( - NoneClass, - BoolClass, - Schema, - FileIO, - BinarySchema, - date, - datetime, - none_type, - frozendict, - Unset, - unset, -) - - -class RequestField(RequestFieldBase): - def __eq__(self, other): - if not isinstance(other, RequestField): - return False - return self.__dict__ == other.__dict__ - - -class JSONEncoder(json.JSONEncoder): - def default(self, obj): - if isinstance(obj, str): - return str(obj) - elif isinstance(obj, float): - return float(obj) - elif isinstance(obj, int): - return int(obj) - elif isinstance(obj, Decimal): - if obj.as_tuple().exponent >= 0: - return int(obj) - return float(obj) - elif isinstance(obj, NoneClass): - return None - elif isinstance(obj, BoolClass): - return bool(obj) - elif isinstance(obj, (dict, frozendict)): - return {key: self.default(val) for key, val in obj.items()} - elif isinstance(obj, (list, tuple)): - return [self.default(item) for item in obj] - raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__)) - - -class ParameterInType(enum.Enum): - QUERY = 'query' - HEADER = 'header' - PATH = 'path' - COOKIE = 'cookie' - - -class ParameterStyle(enum.Enum): - MATRIX = 'matrix' - LABEL = 'label' - FORM = 'form' - SIMPLE = 'simple' - SPACE_DELIMITED = 'spaceDelimited' - PIPE_DELIMITED = 'pipeDelimited' - DEEP_OBJECT = 'deepObject' - - -class PrefixSeparatorIterator: - # A class to store prefixes and separators for rfc6570 expansions - - def __init__(self, prefix: str, separator: str): - self.prefix = prefix - self.separator = separator - self.first = True - if separator in {'.', '|', '%20'}: - item_separator = separator - else: - item_separator = ',' - self.item_separator = item_separator - - def __iter__(self): - return self - - def __next__(self): - if self.first: - self.first = False - return self.prefix - return self.separator - - -class ParameterSerializerBase: - @classmethod - def get_default_explode(cls, style: ParameterStyle) -> bool: - return False - - @staticmethod - def __ref6570_item_value(in_data: typing.Any, percent_encode: bool): - """ - Get representation if str/float/int/None/items in list/ values in dict - None is returned if an item is undefined, use cases are value= - - None - - [] - - {} - - [None, None None] - - {'a': None, 'b': None} - """ - if type(in_data) in {str, float, int}: - if percent_encode: - return quote(str(in_data)) - return str(in_data) - elif isinstance(in_data, none_type): - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return None - elif isinstance(in_data, list) and not in_data: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return None - elif isinstance(in_data, dict) and not in_data: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return None - raise ApiValueError('Unable to generate a ref6570 item representation of {}'.format(in_data)) - - @staticmethod - def to_dict(name: str, value: str): - return {name: value} - - @classmethod - def ref6570_expansion( - cls, - variable_name: str, - in_data: typing.Any, - explode: bool, - percent_encode: bool, - prefix_separator_iterator: PrefixSeparatorIterator - ) -> str: - """ - Separator is for separate variables like dict with explode true, not for array item separation - """ - named_parameter_expansion = prefix_separator_iterator.separator in {'&', ';'} - var_name_piece = variable_name if named_parameter_expansion else '' - if type(in_data) in {str, float, int}: - item_value = cls.__ref6570_item_value(in_data, percent_encode) - if item_value is None: - return next(prefix_separator_iterator) + var_name_piece - elif item_value == '' and prefix_separator_iterator.separator == ';': - return next(prefix_separator_iterator) + var_name_piece - value_pair_equals = '=' if named_parameter_expansion else '' - return next(prefix_separator_iterator) + var_name_piece + value_pair_equals + item_value - elif isinstance(in_data, none_type): - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return "" - elif isinstance(in_data, list): - item_values = [cls.__ref6570_item_value(v, percent_encode) for v in in_data] - item_values = [v for v in item_values if v is not None] - if not item_values: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return "" - value_pair_equals = '=' if named_parameter_expansion else '' - if not explode: - return ( - next(prefix_separator_iterator) + - var_name_piece + - value_pair_equals + - prefix_separator_iterator.item_separator.join(item_values) - ) - # exploded - return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( - [var_name_piece + value_pair_equals + val for val in item_values] - ) - elif isinstance(in_data, dict): - in_data_transformed = {key: cls.__ref6570_item_value(val, percent_encode) for key, val in in_data.items()} - in_data_transformed = {key: val for key, val in in_data_transformed.items() if val is not None} - if not in_data_transformed: - # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 - return "" - value_pair_equals = '=' if named_parameter_expansion else '' - if not explode: - return ( - next(prefix_separator_iterator) + - var_name_piece + value_pair_equals + - prefix_separator_iterator.item_separator.join( - prefix_separator_iterator.item_separator.join( - item_pair - ) for item_pair in in_data_transformed.items() - ) - ) - # exploded - return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( - [key + '=' + val for key, val in in_data_transformed.items()] - ) - # bool, bytes, etc - raise ApiValueError('Unable to generate a ref6570 representation of {}'.format(in_data)) - - -class StyleFormSerializer(ParameterSerializerBase): - @classmethod - def get_default_explode(cls, style: ParameterStyle) -> bool: - if style is ParameterStyle.FORM: - return True - return super().get_default_explode(style) - - def serialize_form( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - name: str, - explode: bool, - percent_encode: bool, - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None - ) -> str: - if prefix_separator_iterator is None: - prefix_separator_iterator = PrefixSeparatorIterator('?', '&') - return self.ref6570_expansion( - variable_name=name, - in_data=in_data, - explode=explode, - percent_encode=percent_encode, - prefix_separator_iterator=prefix_separator_iterator - ) - - -class StyleSimpleSerializer(ParameterSerializerBase): - - def serialize_simple( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - name: str, - explode: bool, - percent_encode: bool - ) -> str: - prefix_separator_iterator = PrefixSeparatorIterator('', ',') - return self.ref6570_expansion( - variable_name=name, - in_data=in_data, - explode=explode, - percent_encode=percent_encode, - prefix_separator_iterator=prefix_separator_iterator - ) - - -@dataclass -class ParameterBase: - name: str - in_type: ParameterInType - required: bool - style: typing.Optional[ParameterStyle] - explode: typing.Optional[bool] - allow_reserved: typing.Optional[bool] - schema: typing.Optional[typing.Type[Schema]] - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] - - __style_to_in_type = { - ParameterStyle.MATRIX: {ParameterInType.PATH}, - ParameterStyle.LABEL: {ParameterInType.PATH}, - ParameterStyle.FORM: {ParameterInType.QUERY, ParameterInType.COOKIE}, - ParameterStyle.SIMPLE: {ParameterInType.PATH, ParameterInType.HEADER}, - ParameterStyle.SPACE_DELIMITED: {ParameterInType.QUERY}, - ParameterStyle.PIPE_DELIMITED: {ParameterInType.QUERY}, - ParameterStyle.DEEP_OBJECT: {ParameterInType.QUERY}, - } - __in_type_to_default_style = { - ParameterInType.QUERY: ParameterStyle.FORM, - ParameterInType.PATH: ParameterStyle.SIMPLE, - ParameterInType.HEADER: ParameterStyle.SIMPLE, - ParameterInType.COOKIE: ParameterStyle.FORM, - } - __disallowed_header_names = {'Accept', 'Content-Type', 'Authorization'} - _json_encoder = JSONEncoder() - _json_content_type = 'application/json' - - @classmethod - def __verify_style_to_in_type(cls, style: typing.Optional[ParameterStyle], in_type: ParameterInType): - if style is None: - return - in_type_set = cls.__style_to_in_type[style] - if in_type not in in_type_set: - raise ValueError( - 'Invalid style and in_type combination. For style={} only in_type={} are allowed'.format( - style, in_type_set - ) - ) - - def __init__( - self, - name: str, - in_type: ParameterInType, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: bool = False, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - if schema is None and content is None: - raise ValueError('Value missing; Pass in either schema or content') - if schema and content: - raise ValueError('Too many values provided. Both schema and content were provided. Only one may be input') - if name in self.__disallowed_header_names and in_type is ParameterInType.HEADER: - raise ValueError('Invalid name, name may not be one of {}'.format(self.__disallowed_header_names)) - self.__verify_style_to_in_type(style, in_type) - if content is None and style is None: - style = self.__in_type_to_default_style[in_type] - if content is not None and in_type in self.__in_type_to_default_style and len(content) != 1: - raise ValueError('Invalid content length, content length must equal 1') - self.in_type = in_type - self.name = name - self.required = required - self.style = style - self.explode = explode - self.allow_reserved = allow_reserved - self.schema = schema - self.content = content - - @staticmethod - def _remove_empty_and_cast( - in_data: typing.Tuple[typing.Tuple[str, str]], - ) -> typing.Dict[str, str]: - data = tuple(t for t in in_data if t) - if not data: - return dict() - return dict(data) - - def _serialize_json( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list] - ) -> str: - return json.dumps(in_data) - - -class PathParameter(ParameterBase, StyleSimpleSerializer): - - def __init__( - self, - name: str, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: bool = False, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - super().__init__( - name, - in_type=ParameterInType.PATH, - required=required, - style=style, - explode=explode, - allow_reserved=allow_reserved, - schema=schema, - content=content - ) - - def _serialize_label( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list] - ) -> typing.Dict[str, str]: - prefix_separator_iterator = PrefixSeparatorIterator('.', '.') - value = self.ref6570_expansion( - variable_name=self.name, - in_data=in_data, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def _serialize_matrix( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list] - ) -> typing.Dict[str, str]: - prefix_separator_iterator = PrefixSeparatorIterator(';', ';') - value = self.ref6570_expansion( - variable_name=self.name, - in_data=in_data, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def _serialize_simple( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - ) -> typing.Dict[str, str]: - value = self.serialize_simple( - in_data=in_data, - name=self.name, - explode=self.explode, - percent_encode=True - ) - return self.to_dict(self.name, value) - - def serialize( - self, - in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] - ) -> typing.Dict[str, str]: - if self.schema: - cast_in_data = self.schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - """ - simple -> path - path: - returns path_params: dict - label -> path - returns path_params - matrix -> path - returns path_params - """ - if self.style: - if self.style is ParameterStyle.SIMPLE: - return self._serialize_simple(cast_in_data) - elif self.style is ParameterStyle.LABEL: - return self._serialize_label(cast_in_data) - elif self.style is ParameterStyle.MATRIX: - return self._serialize_matrix(cast_in_data) - # self.content will be length one - for content_type, schema in self.content.items(): - cast_in_data = schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: - value = self._serialize_json(cast_in_data) - return self.to_dict(self.name, value) - raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) - - -class QueryParameter(ParameterBase, StyleFormSerializer): - - def __init__( - self, - name: str, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: typing.Optional[bool] = None, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - used_style = ParameterStyle.FORM if style is None and content is None and schema else style - used_explode = self.get_default_explode(used_style) if explode is None else explode - - super().__init__( - name, - in_type=ParameterInType.QUERY, - required=required, - style=used_style, - explode=used_explode, - allow_reserved=allow_reserved, - schema=schema, - content=content - ) - - def __serialize_space_delimited( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] - ) -> typing.Dict[str, str]: - if prefix_separator_iterator is None: - prefix_separator_iterator = self.get_prefix_separator_iterator() - value = self.ref6570_expansion( - variable_name=self.name, - in_data=in_data, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def __serialize_pipe_delimited( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] - ) -> typing.Dict[str, str]: - if prefix_separator_iterator is None: - prefix_separator_iterator = self.get_prefix_separator_iterator() - value = self.ref6570_expansion( - variable_name=self.name, - in_data=in_data, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def __serialize_form( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] - ) -> typing.Dict[str, str]: - if prefix_separator_iterator is None: - prefix_separator_iterator = self.get_prefix_separator_iterator() - value = self.serialize_form( - in_data, - name=self.name, - explode=self.explode, - percent_encode=True, - prefix_separator_iterator=prefix_separator_iterator - ) - return self.to_dict(self.name, value) - - def get_prefix_separator_iterator(self) -> typing.Optional[PrefixSeparatorIterator]: - if not self.schema: - return None - if self.style is ParameterStyle.FORM: - return PrefixSeparatorIterator('?', '&') - elif self.style is ParameterStyle.SPACE_DELIMITED: - return PrefixSeparatorIterator('', '%20') - elif self.style is ParameterStyle.PIPE_DELIMITED: - return PrefixSeparatorIterator('', '|') - - def serialize( - self, - in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict], - prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None - ) -> typing.Dict[str, str]: - if self.schema: - cast_in_data = self.schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - """ - form -> query - query: - - GET/HEAD/DELETE: could use fields - - PUT/POST: must use urlencode to send parameters - returns fields: tuple - spaceDelimited -> query - returns fields - pipeDelimited -> query - returns fields - deepObject -> query, https://github.com/OAI/OpenAPI-Specification/issues/1706 - returns fields - """ - if self.style: - # TODO update query ones to omit setting values when [] {} or None is input - if self.style is ParameterStyle.FORM: - return self.__serialize_form(cast_in_data, prefix_separator_iterator) - elif self.style is ParameterStyle.SPACE_DELIMITED: - return self.__serialize_space_delimited(cast_in_data, prefix_separator_iterator) - elif self.style is ParameterStyle.PIPE_DELIMITED: - return self.__serialize_pipe_delimited(cast_in_data, prefix_separator_iterator) - # self.content will be length one - for content_type, schema in self.content.items(): - cast_in_data = schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: - value = self._serialize_json(cast_in_data) - return self.to_dict(self.name, value) - raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) - - -class CookieParameter(ParameterBase, StyleFormSerializer): - - def __init__( - self, - name: str, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: typing.Optional[bool] = None, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - used_style = ParameterStyle.FORM if style is None and content is None and schema else style - used_explode = self.get_default_explode(used_style) if explode is None else explode - - super().__init__( - name, - in_type=ParameterInType.COOKIE, - required=required, - style=used_style, - explode=used_explode, - allow_reserved=allow_reserved, - schema=schema, - content=content - ) - - def serialize( - self, - in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] - ) -> typing.Dict[str, str]: - if self.schema: - cast_in_data = self.schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - """ - form -> cookie - returns fields: tuple - """ - if self.style: - """ - TODO add escaping of comma, space, equals - or turn encoding on - """ - value = self.serialize_form( - cast_in_data, - explode=self.explode, - name=self.name, - percent_encode=False, - prefix_separator_iterator=PrefixSeparatorIterator('', '&') - ) - return self.to_dict(self.name, value) - # self.content will be length one - for content_type, schema in self.content.items(): - cast_in_data = schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: - value = self._serialize_json(cast_in_data) - return self.to_dict(self.name, value) - raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) - - -class HeaderParameter(ParameterBase, StyleSimpleSerializer): - def __init__( - self, - name: str, - required: bool = False, - style: typing.Optional[ParameterStyle] = None, - explode: bool = False, - allow_reserved: typing.Optional[bool] = None, - schema: typing.Optional[typing.Type[Schema]] = None, - content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None - ): - super().__init__( - name, - in_type=ParameterInType.HEADER, - required=required, - style=style, - explode=explode, - allow_reserved=allow_reserved, - schema=schema, - content=content - ) - - @staticmethod - def __to_headers(in_data: typing.Tuple[typing.Tuple[str, str], ...]) -> HTTPHeaderDict[str, str]: - data = tuple(t for t in in_data if t) - headers = HTTPHeaderDict() - if not data: - return headers - headers.extend(data) - return headers - - def _serialize_simple( - self, - in_data: typing.Union[None, int, float, str, bool, dict, list], - ) -> str: - return self.serialize_simple(in_data, self.name, self.explode, False) - - def serialize( - self, - in_data: typing.Union[ - Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] - ) -> HTTPHeaderDict[str, str]: - if self.schema: - cast_in_data = self.schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - """ - simple -> header - headers: PoolManager needs a mapping, tuple is close - returns headers: dict - """ - if self.style: - value = self._serialize_simple(cast_in_data) - return self.__to_headers(((self.name, value),)) - # self.content will be length one - for content_type, schema in self.content.items(): - cast_in_data = schema(in_data) - cast_in_data = self._json_encoder.default(cast_in_data) - if content_type == self._json_content_type: - value = self._serialize_json(cast_in_data) - return self.__to_headers(((self.name, value),)) - raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) - - -class Encoding: - def __init__( - self, - content_type: str, - headers: typing.Optional[typing.Dict[str, HeaderParameter]] = None, - style: typing.Optional[ParameterStyle] = None, - explode: bool = False, - allow_reserved: bool = False, - ): - self.content_type = content_type - self.headers = headers - self.style = style - self.explode = explode - self.allow_reserved = allow_reserved - - -@dataclass -class MediaType: - """ - Used to store request and response body schema information - encoding: - A map between a property name and its encoding information. - The key, being the property name, MUST exist in the schema as a property. - The encoding object SHALL only apply to requestBody objects when the media type is - multipart or application/x-www-form-urlencoded. - """ - schema: typing.Optional[typing.Type[Schema]] = None - encoding: typing.Optional[typing.Dict[str, Encoding]] = None - - -@dataclass -class ApiResponse: - response: urllib3.HTTPResponse - body: typing.Union[Unset, typing.Type[Schema]] - headers: typing.Union[Unset, typing.List[HeaderParameter]] - - def __init__( - self, - response: urllib3.HTTPResponse, - body: typing.Union[Unset, typing.Type[Schema]], - headers: typing.Union[Unset, typing.List[HeaderParameter]] - ): - """ - pycharm needs this to prevent 'Unexpected argument' warnings - """ - self.response = response - self.body = body - self.headers = headers - - -@dataclass -class ApiResponseWithoutDeserialization(ApiResponse): - response: urllib3.HTTPResponse - body: typing.Union[Unset, typing.Type[Schema]] = unset - headers: typing.Union[Unset, typing.List[HeaderParameter]] = unset - - -class JSONDetector: - @staticmethod - def content_type_is_json(content_type: str) -> bool: - """ - for when content_type strings also include charset info like: - application/json; charset=UTF-8 - """ - content_type_piece = content_type.split(';')[0] - if content_type_piece == 'application/json': - return True - return False - - -class OpenApiResponse(JSONDetector): - def __init__( - self, - response_cls: typing.Type[ApiResponse] = ApiResponse, - content: typing.Optional[typing.Dict[str, MediaType]] = None, - headers: typing.Optional[typing.List[HeaderParameter]] = None, - ): - self.headers = headers - if content is not None and len(content) == 0: - raise ValueError('Invalid value for content, the content dict must have >= 1 entry') - self.content = content - self.response_cls = response_cls - - @staticmethod - def __deserialize_json(response: urllib3.HTTPResponse) -> typing.Any: - # python must be >= 3.9 so we can pass in bytes into json.loads - return json.loads(response.data) - - @staticmethod - def __file_name_from_content_disposition(content_disposition: typing.Optional[str]) -> typing.Optional[str]: - if content_disposition is None: - return None - match = re.search('filename="(.+?)"', content_disposition) - if not match: - return None - return match.group(1) - - def __deserialize_application_octet_stream( - self, response: urllib3.HTTPResponse - ) -> typing.Union[bytes, io.BufferedReader]: - """ - urllib3 use cases: - 1. when preload_content=True (stream=False) then supports_chunked_reads is False and bytes are returned - 2. when preload_content=False (stream=True) then supports_chunked_reads is True and - a file will be written and returned - """ - if response.supports_chunked_reads(): - file_name = self.__file_name_from_content_disposition(response.headers.get('content-disposition')) - - if file_name is None: - _fd, path = tempfile.mkstemp() - else: - path = os.path.join(tempfile.gettempdir(), file_name) - # TODO get file_name from the filename at the end of the url if it exists - with open(path, 'wb') as new_file: - chunk_size = 1024 - while True: - data = response.read(chunk_size) - if not data: - break - new_file.write(data) - # release_conn is needed for streaming connections only - response.release_conn() - new_file = open(path, 'rb') - return new_file - else: - return response.data - - @staticmethod - def __deserialize_multipart_form_data( - response: urllib3.HTTPResponse - ) -> typing.Dict[str, typing.Any]: - msg = email.message_from_bytes(response.data) - return { - part.get_param("name", header="Content-Disposition"): part.get_payload( - decode=True - ).decode(part.get_content_charset()) - if part.get_content_charset() - else part.get_payload() - for part in msg.get_payload() - } - - def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse: - content_type = response.getheader('content-type') - deserialized_body = unset - streamed = response.supports_chunked_reads() - - deserialized_headers = unset - if self.headers is not None: - # TODO add header deserialiation here - pass - - if self.content is not None: - if content_type not in self.content: - raise ApiValueError( - f'Invalid content_type={content_type} returned for response with ' - 'status_code={str(response.status)}' - ) - body_schema = self.content[content_type].schema - if body_schema is None: - # some specs do not define response content media type schemas - return self.response_cls( - response=response, - headers=deserialized_headers, - body=unset - ) - - if self.content_type_is_json(content_type): - body_data = self.__deserialize_json(response) - elif content_type == 'application/octet-stream': - body_data = self.__deserialize_application_octet_stream(response) - elif content_type.startswith('multipart/form-data'): - body_data = self.__deserialize_multipart_form_data(response) - content_type = 'multipart/form-data' - else: - raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type)) - deserialized_body = body_schema._from_openapi_data( - body_data, _configuration=configuration) - elif streamed: - response.release_conn() - - return self.response_cls( - response=response, - headers=deserialized_headers, - body=deserialized_body - ) - - -class ApiClient: - """Generic API client for OpenAPI client library builds. - - OpenAPI generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the OpenAPI - templates. - - NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - Do not edit the class manually. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. - """ - - _pool = None - __json_encoder = JSONEncoder() - - def __init__( - self, - configuration: typing.Optional[Configuration] = None, - header_name: typing.Optional[str] = None, - header_value: typing.Optional[str] = None, - cookie: typing.Optional[str] = None, - pool_threads: int = 1 - ): - if configuration is None: - configuration = Configuration() - self.configuration = configuration - self.pool_threads = pool_threads - - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = 'OpenAPI-Generator/1.0.0/python' - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api( - self, - resource_path: str, - method: str, - headers: typing.Optional[HTTPHeaderDict] = None, - body: typing.Optional[typing.Union[str, bytes]] = None, - fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, - auth_settings: typing.Optional[typing.List[str]] = None, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - host: typing.Optional[str] = None, - ) -> urllib3.HTTPResponse: - - # header parameters - headers = headers or {} - headers.update(self.default_headers) - if self.cookie: - headers['Cookie'] = self.cookie - - # auth setting - self.update_params_for_auth(headers, - auth_settings, resource_path, method, body) - - # request url - if host is None: - url = self.configuration.host + resource_path - else: - # use server/host defined in path or operation instead - url = host + resource_path - - # perform request and return response - response = self.request( - method, - url, - headers=headers, - fields=fields, - body=body, - stream=stream, - timeout=timeout, - ) - return response - - def call_api( - self, - resource_path: str, - method: str, - headers: typing.Optional[HTTPHeaderDict] = None, - body: typing.Optional[typing.Union[str, bytes]] = None, - fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, - auth_settings: typing.Optional[typing.List[str]] = None, - async_req: typing.Optional[bool] = None, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - host: typing.Optional[str] = None, - ) -> urllib3.HTTPResponse: - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param headers: Header parameters to be - placed in the request header. - :param body: Request body. - :param fields: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings: Auth Settings names for the request. - :param async_req: execute request asynchronously - :type async_req: bool, optional TODO remove, unused - :param stream: if True, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Also when True, if the openapi spec describes a file download, - the data will be written to a local filesystme file and the BinarySchema - instance will also inherit from FileSchema and FileIO - Default is False. - :type stream: bool, optional - :param timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param host: api endpoint host - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - - if not async_req: - return self.__call_api( - resource_path, - method, - headers, - body, - fields, - auth_settings, - stream, - timeout, - host, - ) - - return self.pool.apply_async( - self.__call_api, - ( - resource_path, - method, - headers, - body, - json, - fields, - auth_settings, - stream, - timeout, - host, - ) - ) - - def request( - self, - method: str, - url: str, - headers: typing.Optional[HTTPHeaderDict] = None, - fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, - body: typing.Optional[typing.Union[str, bytes]] = None, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - ) -> urllib3.HTTPResponse: - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.GET(url, - stream=stream, - timeout=timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.HEAD(url, - stream=stream, - timeout=timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.OPTIONS(url, - headers=headers, - fields=fields, - stream=stream, - timeout=timeout, - body=body) - elif method == "POST": - return self.rest_client.POST(url, - headers=headers, - fields=fields, - stream=stream, - timeout=timeout, - body=body) - elif method == "PUT": - return self.rest_client.PUT(url, - headers=headers, - fields=fields, - stream=stream, - timeout=timeout, - body=body) - elif method == "PATCH": - return self.rest_client.PATCH(url, - headers=headers, - fields=fields, - stream=stream, - timeout=timeout, - body=body) - elif method == "DELETE": - return self.rest_client.DELETE(url, - headers=headers, - stream=stream, - timeout=timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def update_params_for_auth(self, headers, auth_settings, - resource_path, method, body): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param auth_settings: Authentication setting identifiers list. - :param resource_path: A string representation of the HTTP request resource path. - :param method: A string representation of the HTTP request method. - :param body: A object representing the body of the HTTP request. - The object type is the return value of _encoder.default(). - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if auth_setting['in'] == 'cookie': - headers.add('Cookie', auth_setting['value']) - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers.add(auth_setting['key'], auth_setting['value']) - else: - # The HTTP signature scheme requires multiple HTTP headers - # that are calculated dynamically. - signing_info = self.configuration.signing_info - querys = tuple() - auth_headers = signing_info.get_http_signature_headers( - resource_path, method, headers, body, querys) - for key, value in auth_headers.items(): - headers.add(key, value) - elif auth_setting['in'] == 'query': - """ TODO implement auth in query - need to pass in prefix_separator_iterator - and need to output resource_path with query params added - """ - raise ApiValueError("Auth in query not yet implemented") - else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) - - -class Api: - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client: typing.Optional[ApiClient] = None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - @staticmethod - def _verify_typed_dict_inputs(cls: typing.Type[typing.TypedDict], data: typing.Dict[str, typing.Any]): - """ - Ensures that: - - required keys are present - - additional properties are not input - - value stored under required keys do not have the value unset - Note: detailed value checking is done in schema classes - """ - missing_required_keys = [] - required_keys_with_unset_values = [] - for required_key in cls.__required_keys__: - if required_key not in data: - missing_required_keys.append(required_key) - continue - value = data[required_key] - if value is unset: - required_keys_with_unset_values.append(required_key) - if missing_required_keys: - raise ApiTypeError( - '{} missing {} required arguments: {}'.format( - cls.__name__, len(missing_required_keys), missing_required_keys - ) - ) - if required_keys_with_unset_values: - raise ApiValueError( - '{} contains invalid unset values for {} required keys: {}'.format( - cls.__name__, len(required_keys_with_unset_values), required_keys_with_unset_values - ) - ) - - disallowed_additional_keys = [] - for key in data: - if key in cls.__required_keys__ or key in cls.__optional_keys__: - continue - disallowed_additional_keys.append(key) - if disallowed_additional_keys: - raise ApiTypeError( - '{} got {} unexpected keyword arguments: {}'.format( - cls.__name__, len(disallowed_additional_keys), disallowed_additional_keys - ) - ) - - def get_host( - self, - operation_id: str, - servers: typing.Tuple[typing.Dict[str, str], ...] = tuple(), - host_index: typing.Optional[int] = None - ) -> typing.Optional[str]: - configuration = self.api_client.configuration - try: - if host_index is None: - index = configuration.server_operation_index.get( - operation_id, configuration.server_index - ) - else: - index = host_index - server_variables = configuration.server_operation_variables.get( - operation_id, configuration.server_variables - ) - host = configuration.get_host_from_settings( - index, variables=server_variables, servers=servers - ) - except IndexError: - if servers: - raise ApiValueError( - "Invalid host index. Must be 0 <= index < %s" % - len(servers) - ) - host = None - return host - - -class SerializedRequestBody(typing.TypedDict, total=False): - body: typing.Union[str, bytes] - fields: typing.Tuple[typing.Union[RequestField, tuple[str, str]], ...] - - -class RequestBody(StyleFormSerializer, JSONDetector): - """ - A request body parameter - content: content_type to MediaType Schema info - """ - __json_encoder = JSONEncoder() - - def __init__( - self, - content: typing.Dict[str, MediaType], - required: bool = False, - ): - self.required = required - if len(content) == 0: - raise ValueError('Invalid value for content, the content dict must have >= 1 entry') - self.content = content - - def __serialize_json( - self, - in_data: typing.Any - ) -> typing.Dict[str, bytes]: - in_data = self.__json_encoder.default(in_data) - json_str = json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode( - "utf-8" - ) - return dict(body=json_str) - - @staticmethod - def __serialize_text_plain(in_data: typing.Any) -> typing.Dict[str, str]: - if isinstance(in_data, frozendict): - raise ValueError('Unable to serialize type frozendict to text/plain') - elif isinstance(in_data, tuple): - raise ValueError('Unable to serialize type tuple to text/plain') - elif isinstance(in_data, NoneClass): - raise ValueError('Unable to serialize type NoneClass to text/plain') - elif isinstance(in_data, BoolClass): - raise ValueError('Unable to serialize type BoolClass to text/plain') - return dict(body=str(in_data)) - - def __multipart_json_item(self, key: str, value: Schema) -> RequestField: - json_value = self.__json_encoder.default(value) - return RequestField(name=key, data=json.dumps(json_value), headers={'Content-Type': 'application/json'}) - - def __multipart_form_item(self, key: str, value: Schema) -> RequestField: - if isinstance(value, str): - return RequestField(name=key, data=str(value), headers={'Content-Type': 'text/plain'}) - elif isinstance(value, bytes): - return RequestField(name=key, data=value, headers={'Content-Type': 'application/octet-stream'}) - elif isinstance(value, FileIO): - request_field = RequestField( - name=key, - data=value.read(), - filename=os.path.basename(value.name), - headers={'Content-Type': 'application/octet-stream'} - ) - value.close() - return request_field - else: - return self.__multipart_json_item(key=key, value=value) - - def __serialize_multipart_form_data( - self, in_data: Schema - ) -> typing.Dict[str, typing.Tuple[RequestField, ...]]: - if not isinstance(in_data, frozendict): - raise ValueError(f'Unable to serialize {in_data} to multipart/form-data because it is not a dict of data') - """ - In a multipart/form-data request body, each schema property, or each element of a schema array property, - takes a section in the payload with an internal header as defined by RFC7578. The serialization strategy - for each property of a multipart/form-data request body can be specified in an associated Encoding Object. - - When passing in multipart types, boundaries MAY be used to separate sections of the content being - transferred – thus, the following default Content-Types are defined for multipart: - - If the (object) property is a primitive, or an array of primitive values, the default Content-Type is text/plain - If the property is complex, or an array of complex values, the default Content-Type is application/json - Question: how is the array of primitives encoded? - If the property is a type: string with a contentEncoding, the default Content-Type is application/octet-stream - """ - fields = [] - for key, value in in_data.items(): - if isinstance(value, tuple): - if value: - # values use explode = True, so the code makes a RequestField for each item with name=key - for item in value: - request_field = self.__multipart_form_item(key=key, value=item) - fields.append(request_field) - else: - # send an empty array as json because exploding will not send it - request_field = self.__multipart_json_item(key=key, value=value) - fields.append(request_field) - else: - request_field = self.__multipart_form_item(key=key, value=value) - fields.append(request_field) - - return dict(fields=tuple(fields)) - - def __serialize_application_octet_stream(self, in_data: BinarySchema) -> typing.Dict[str, bytes]: - if isinstance(in_data, bytes): - return dict(body=in_data) - # FileIO type - result = dict(body=in_data.read()) - in_data.close() - return result - - def __serialize_application_x_www_form_data( - self, in_data: typing.Any - ) -> SerializedRequestBody: - """ - POST submission of form data in body - """ - if not isinstance(in_data, frozendict): - raise ValueError( - f'Unable to serialize {in_data} to application/x-www-form-urlencoded because it is not a dict of data') - cast_in_data = self.__json_encoder.default(in_data) - value = self.serialize_form(cast_in_data, name='', explode=True, percent_encode=False) - return dict(body=value) - - def serialize( - self, in_data: typing.Any, content_type: str - ) -> SerializedRequestBody: - """ - If a str is returned then the result will be assigned to data when making the request - If a tuple is returned then the result will be used as fields input in encode_multipart_formdata - Return a tuple of - - The key of the return dict is - - body for application/json - - encode_multipart and fields for multipart/form-data - """ - media_type = self.content[content_type] - if isinstance(in_data, media_type.schema): - cast_in_data = in_data - elif isinstance(in_data, (dict, frozendict)) and in_data: - cast_in_data = media_type.schema(**in_data) - else: - cast_in_data = media_type.schema(in_data) - # TODO check for and use encoding if it exists - # and content_type is multipart or application/x-www-form-urlencoded - if self.content_type_is_json(content_type): - return self.__serialize_json(cast_in_data) - elif content_type == 'text/plain': - return self.__serialize_text_plain(cast_in_data) - elif content_type == 'multipart/form-data': - return self.__serialize_multipart_form_data(cast_in_data) - elif content_type == 'application/x-www-form-urlencoded': - return self.__serialize_application_x_www_form_data(cast_in_data) - elif content_type == 'application/octet-stream': - return self.__serialize_application_octet_stream(cast_in_data) - raise NotImplementedError('Serialization has not yet been implemented for {}'.format(content_type)) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/apis/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/apis/__init__.py deleted file mode 100644 index 58c23b81b4..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/apis/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -# Import all APIs into this package. -# If you have many APIs here with many many models used in each API this may -# raise a `RecursionError`. -# In order to avoid this, import only the API that you directly need like: -# -# from petstore_api.api.another_fake_api import AnotherFakeApi -# -# or import this package, but before doing it, use: -# -# import sys -# sys.setrecursionlimit(n) - -# Import APIs into API package: -from petstore_api.api.another_fake_api import AnotherFakeApi -from petstore_api.api.default_api import DefaultApi -from petstore_api.api.fake_api import FakeApi -from petstore_api.api.fake_classname_tags123_api import FakeClassnameTags123Api -from petstore_api.api.pet_api import PetApi -from petstore_api.api.store_api import StoreApi -from petstore_api.api.user_api import UserApi diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py deleted file mode 100644 index f7c2a3ff91..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py +++ /dev/null @@ -1,610 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -from http import client as http_client -from petstore_api.exceptions import ApiValueError - - -JSON_SCHEMA_VALIDATION_KEYWORDS = { - 'multipleOf', 'maximum', 'exclusiveMaximum', - 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems', - 'uniqueItems', 'maxProperties', 'minProperties', -} - -class Configuration(object): - """NOTE: This class is auto generated by OpenAPI Generator - - Ref: https://openapi-generator.tech - Do not edit the class manually. - - :param host: Base url - :param api_key: Dict to store API key(s). - Each entry in the dict specifies an API key. - The dict key is the name of the security scheme in the OAS specification. - The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer) - The dict key is the name of the security scheme in the OAS specification. - The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication - :param password: Password for HTTP basic authentication - :param discard_unknown_keys: Boolean value indicating whether to discard - unknown properties. A server may send a response that includes additional - properties that are not known by the client in the following scenarios: - 1. The OpenAPI document is incomplete, i.e. it does not match the server - implementation. - 2. The client was generated using an older version of the OpenAPI document - and the server has been upgraded since then. - If a schema in the OpenAPI document defines the additionalProperties attribute, - then all undeclared properties received by the server are injected into the - additional properties map. In that case, there are undeclared properties, and - nothing to discard. - :param disabled_client_side_validations (string): Comma-separated list of - JSON schema validation keywords to disable JSON schema structural validation - rules. The following keywords may be specified: multipleOf, maximum, - exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, - maxItems, minItems. - By default, the validation is performed for data generated locally by the client - and data received from the server, independent of any validation performed by - the server side. If the input data does not satisfy the JSON schema validation - rules specified in the OpenAPI document, an exception is raised. - If disabled_client_side_validations is set, structural validation is - disabled. This can be useful to troubleshoot data validation problem, such as - when the OpenAPI document validation rules do not match the actual API data - received by the server. - :param signing_info: Configuration parameters for the HTTP signature security scheme. - Must be an instance of petstore_api.signing.HttpSigningConfiguration - :param server_index: Index to servers configuration. - :param server_variables: Mapping with string values to replace variables in - templated server configuration. The validation of enums is performed for - variables with defined enum values before. - :param server_operation_index: Mapping from operation ID to an index to server - configuration. - :param server_operation_variables: Mapping from operation ID to a mapping with - string values to replace variables in templated server configuration. - The validation of enums is performed for variables with defined enum values before. - - :Example: - - API Key Authentication Example. - Given the following security scheme in the OpenAPI specification: - components: - securitySchemes: - cookieAuth: # name for the security scheme - type: apiKey - in: cookie - name: JSESSIONID # cookie name - - You can programmatically set the cookie: - -conf = petstore_api.Configuration( - api_key={'cookieAuth': 'abc123'} - api_key_prefix={'cookieAuth': 'JSESSIONID'} -) - - The following cookie will be added to the HTTP request: - Cookie: JSESSIONID abc123 - - HTTP Basic Authentication Example. - Given the following security scheme in the OpenAPI specification: - components: - securitySchemes: - http_basic_auth: - type: http - scheme: basic - - Configure API client with HTTP basic authentication: - -conf = petstore_api.Configuration( - username='the-user', - password='the-password', -) - - - HTTP Signature Authentication Example. - Given the following security scheme in the OpenAPI specification: - components: - securitySchemes: - http_basic_auth: - type: http - scheme: signature - - Configure API client with HTTP signature authentication. Use the 'hs2019' signature scheme, - sign the HTTP requests with the RSA-SSA-PSS signature algorithm, and set the expiration time - of the signature to 5 minutes after the signature has been created. - Note you can use the constants defined in the petstore_api.signing module, and you can - also specify arbitrary HTTP headers to be included in the HTTP signature, except for the - 'Authorization' header, which is used to carry the signature. - - One may be tempted to sign all headers by default, but in practice it rarely works. - This is beccause explicit proxies, transparent proxies, TLS termination endpoints or - load balancers may add/modify/remove headers. Include the HTTP headers that you know - are not going to be modified in transit. - -conf = petstore_api.Configuration( - signing_info = petstore_api.signing.HttpSigningConfiguration( - key_id = 'my-key-id', - private_key_path = 'rsa.pem', - signing_scheme = petstore_api.signing.SCHEME_HS2019, - signing_algorithm = petstore_api.signing.ALGORITHM_RSASSA_PSS, - signed_headers = [petstore_api.signing.HEADER_REQUEST_TARGET, - petstore_api.signing.HEADER_CREATED, - petstore_api.signing.HEADER_EXPIRES, - petstore_api.signing.HEADER_HOST, - petstore_api.signing.HEADER_DATE, - petstore_api.signing.HEADER_DIGEST, - 'Content-Type', - 'User-Agent' - ], - signature_max_validity = datetime.timedelta(minutes=5) - ) -) - """ - - _default = None - - def __init__(self, host=None, - api_key=None, api_key_prefix=None, - username=None, password=None, - discard_unknown_keys=False, - disabled_client_side_validations="", - signing_info=None, - server_index=None, server_variables=None, - server_operation_index=None, server_operation_variables=None, - ): - """Constructor - """ - self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host - """Default Base url - """ - self.server_index = 0 if server_index is None and host is None else server_index - self.server_operation_index = server_operation_index or {} - """Default server index - """ - self.server_variables = server_variables or {} - self.server_operation_variables = server_operation_variables or {} - """Default server variables - """ - self.temp_folder_path = None - """Temp file folder for downloading files - """ - # Authentication Settings - self.api_key = {} - if api_key: - self.api_key = api_key - """dict to store API key(s) - """ - self.api_key_prefix = {} - if api_key_prefix: - self.api_key_prefix = api_key_prefix - """dict to store API prefix (e.g. Bearer) - """ - self.refresh_api_key_hook = None - """function hook to refresh API key if expired - """ - self.username = username - """Username for HTTP basic authentication - """ - self.password = password - """Password for HTTP basic authentication - """ - self.discard_unknown_keys = discard_unknown_keys - self.disabled_client_side_validations = disabled_client_side_validations - if signing_info is not None: - signing_info.host = host - self.signing_info = signing_info - """The HTTP signing configuration - """ - self.access_token = None - """access token for OAuth/Bearer - """ - self.logger = {} - """Logging Settings - """ - self.logger["package_logger"] = logging.getLogger("petstore_api") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - """Log format - """ - self.logger_stream_handler = None - """Log stream handler - """ - self.logger_file_handler = None - """Log file handler - """ - self.logger_file = None - """Debug file location - """ - self.debug = False - """Debug switch - """ - - self.verify_ssl = True - """SSL/TLS verification - Set this to false to skip verifying SSL certificate when calling API - from https server. - """ - self.ssl_ca_cert = None - """Set this to customize the certificate file to verify the peer. - """ - self.cert_file = None - """client certificate file - """ - self.key_file = None - """client key file - """ - self.assert_hostname = None - """Set this to True/False to enable/disable SSL hostname verification. - """ - - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - """urllib3 connection pool's maximum number of connections saved - per pool. urllib3 uses 1 connection as default value, but this is - not the best value when you are making a lot of possibly parallel - requests to the same host, which is often the case here. - cpu_count * 5 is used as default value to increase performance. - """ - - self.proxy = None - """Proxy URL - """ - self.proxy_headers = None - """Proxy headers - """ - self.safe_chars_for_path_param = '' - """Safe chars for path_param - """ - self.retries = None - """Adding retries to override urllib3 default value 3 - """ - # Enable client side validation - self.client_side_validation = True - - # Options to pass down to the underlying urllib3 socket - self.socket_options = None - - def __deepcopy__(self, memo): - cls = self.__class__ - result = cls.__new__(cls) - memo[id(self)] = result - for k, v in self.__dict__.items(): - if k not in ('logger', 'logger_file_handler'): - setattr(result, k, copy.deepcopy(v, memo)) - # shallow copy of loggers - result.logger = copy.copy(self.logger) - # use setters to configure loggers - result.logger_file = self.logger_file - result.debug = self.debug - return result - - def __setattr__(self, name, value): - object.__setattr__(self, name, value) - if name == 'disabled_client_side_validations': - s = set(filter(None, value.split(','))) - for v in s: - if v not in JSON_SCHEMA_VALIDATION_KEYWORDS: - raise ApiValueError( - "Invalid keyword: '{0}''".format(v)) - self._disabled_client_side_validations = s - if name == "signing_info" and value is not None: - # Ensure the host paramater from signing info is the same as - # Configuration.host. - value.host = self.host - - @classmethod - def set_default(cls, default): - """Set default instance of configuration. - - It stores default configuration, which can be - returned by get_default_copy method. - - :param default: object of Configuration - """ - cls._default = copy.deepcopy(default) - - @classmethod - def get_default_copy(cls): - """Return new instance of configuration. - - This method returns newly created, based on default constructor, - object of Configuration class or returns a copy of default - configuration passed by the set_default method. - - :return: The configuration object. - """ - if cls._default is not None: - return copy.deepcopy(cls._default) - return Configuration() - - @property - def logger_file(self): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in self.logger.items(): - logger.addHandler(self.logger_file_handler) - - @property - def debug(self): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in self.logger.items(): - logger.setLevel(logging.DEBUG) - # turn on http_client debug - http_client.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in self.logger.items(): - logger.setLevel(logging.WARNING) - # turn off http_client debug - http_client.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier, alias=None): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :param alias: The alternative identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook is not None: - self.refresh_api_key_hook(self) - key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - username = "" - if self.username is not None: - username = self.username - password = "" - if self.password is not None: - password = self.password - return urllib3.util.make_headers( - basic_auth=username + ':' + password - ).get('authorization') - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - auth = {} - if 'api_key' in self.api_key: - auth['api_key'] = { - 'type': 'api_key', - 'in': 'header', - 'key': 'api_key', - 'value': self.get_api_key_with_prefix( - 'api_key', - ), - } - if 'api_key_query' in self.api_key: - auth['api_key_query'] = { - 'type': 'api_key', - 'in': 'query', - 'key': 'api_key_query', - 'value': self.get_api_key_with_prefix( - 'api_key_query', - ), - } - if self.access_token is not None: - auth['bearer_test'] = { - 'type': 'bearer', - 'in': 'header', - 'format': 'JWT', - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token - } - if self.username is not None and self.password is not None: - auth['http_basic_test'] = { - 'type': 'basic', - 'in': 'header', - 'key': 'Authorization', - 'value': self.get_basic_auth_token() - } - if self.signing_info is not None: - auth['http_signature_test'] = { - 'type': 'http-signature', - 'in': 'header', - 'key': 'Authorization', - 'value': None # Signature headers are calculated for every HTTP request - } - if self.access_token is not None: - auth['petstore_auth'] = { - 'type': 'oauth2', - 'in': 'header', - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token - } - return auth - - def to_debug_report(self): - """Gets the essential information for debugging. - - :return: The report for debugging. - """ - return "Python SDK Debug Report:\n"\ - "OS: {env}\n"\ - "Python Version: {pyversion}\n"\ - "Version of the API: 1.0.0\n"\ - "SDK Package Version: 1.0.0".\ - format(env=sys.platform, pyversion=sys.version) - - def get_host_settings(self): - """Gets an array of host settings - - :return: An array of host settings - """ - return [ - { - 'url': "http://{server}.swagger.io:{port}/v2", - 'description': "petstore server", - 'variables': { - 'server': { - 'description': "No description provided", - 'default_value': "petstore", - 'enum_values': [ - "petstore", - "qa-petstore", - "dev-petstore" - ] - }, - 'port': { - 'description': "No description provided", - 'default_value': "80", - 'enum_values': [ - "80", - "8080" - ] - } - } - }, - { - 'url': "https://localhost:8080/{version}", - 'description': "The local server", - 'variables': { - 'version': { - 'description': "No description provided", - 'default_value': "v2", - 'enum_values': [ - "v1", - "v2" - ] - } - } - } - ] - - def get_host_from_settings(self, index, variables=None, servers=None): - """Gets host URL based on the index and variables - :param index: array index of the host settings - :param variables: hash of variable and the corresponding value - :param servers: an array of host settings or None - :return: URL based on host settings - """ - if index is None: - return self._base_path - - variables = {} if variables is None else variables - servers = self.get_host_settings() if servers is None else servers - - try: - server = servers[index] - except IndexError: - raise ValueError( - "Invalid index {0} when selecting the host settings. " - "Must be less than {1}".format(index, len(servers))) - - url = server['url'] - - # go through variables and replace placeholders - for variable_name, variable in server.get('variables', {}).items(): - used_value = variables.get( - variable_name, variable['default_value']) - - if 'enum_values' in variable \ - and used_value not in variable['enum_values']: - raise ValueError( - "The variable `{0}` in the host URL has invalid value " - "{1}. Must be {2}.".format( - variable_name, variables[variable_name], - variable['enum_values'])) - - url = url.replace("{" + variable_name + "}", used_value) - - return url - - @property - def host(self): - """Return generated host.""" - return self.get_host_from_settings(self.server_index, variables=self.server_variables) - - @host.setter - def host(self, value): - """Fix base path.""" - self._base_path = value - self.server_index = None diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/additional_properties_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/additional_properties_class.py deleted file mode 100644 index 8339daf8f7..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/additional_properties_class.py +++ /dev/null @@ -1,209 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AdditionalPropertiesClass( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class map_property( - DictSchema - ): - _additional_properties = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'map_property': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class map_of_map_property( - DictSchema - ): - - - class _additional_properties( - DictSchema - ): - _additional_properties = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> '_additional_properties': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'map_of_map_property': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - anytype_1 = AnyTypeSchema - map_with_undeclared_properties_anytype_1 = DictSchema - map_with_undeclared_properties_anytype_2 = DictSchema - map_with_undeclared_properties_anytype_3 = DictSchema - - - class empty_map( - DictSchema - ): - _additional_properties = None - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'empty_map': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - class map_with_undeclared_properties_string( - DictSchema - ): - _additional_properties = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'map_with_undeclared_properties_string': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - map_property: typing.Union[map_property, Unset] = unset, - map_of_map_property: typing.Union[map_of_map_property, Unset] = unset, - anytype_1: typing.Union[anytype_1, Unset] = unset, - map_with_undeclared_properties_anytype_1: typing.Union[map_with_undeclared_properties_anytype_1, Unset] = unset, - map_with_undeclared_properties_anytype_2: typing.Union[map_with_undeclared_properties_anytype_2, Unset] = unset, - map_with_undeclared_properties_anytype_3: typing.Union[map_with_undeclared_properties_anytype_3, Unset] = unset, - empty_map: typing.Union[empty_map, Unset] = unset, - map_with_undeclared_properties_string: typing.Union[map_with_undeclared_properties_string, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AdditionalPropertiesClass': - return super().__new__( - cls, - *args, - map_property=map_property, - map_of_map_property=map_of_map_property, - anytype_1=anytype_1, - map_with_undeclared_properties_anytype_1=map_with_undeclared_properties_anytype_1, - map_with_undeclared_properties_anytype_2=map_with_undeclared_properties_anytype_2, - map_with_undeclared_properties_anytype_3=map_with_undeclared_properties_anytype_3, - empty_map=empty_map, - map_with_undeclared_properties_string=map_with_undeclared_properties_string, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/additional_properties_with_array_of_enums.py deleted file mode 100644 index cf4ff6075b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/additional_properties_with_array_of_enums.py +++ /dev/null @@ -1,104 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AdditionalPropertiesWithArrayOfEnums( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class _additional_properties( - ListSchema - ): - - @classmethod - @property - def _items(cls) -> typing.Type['EnumClass']: - return EnumClass - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AdditionalPropertiesWithArrayOfEnums': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.enum_class import EnumClass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/address.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/address.py deleted file mode 100644 index 8aabd4c6e1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/address.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Address( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _additional_properties = IntSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Address': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/animal.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/animal.py deleted file mode 100644 index 8081aca81d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/animal.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Animal( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'className', - )) - className = StrSchema - color = StrSchema - - @classmethod - @property - def _discriminator(cls): - return { - 'className': { - 'Cat': Cat, - 'Dog': Dog, - } - } - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - className: className, - color: typing.Union[color, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Animal': - return super().__new__( - cls, - *args, - className=className, - color=color, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.cat import Cat -from petstore_api.model.dog import Dog diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/animal_farm.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/animal_farm.py deleted file mode 100644 index dc1e04af56..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/animal_farm.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AnimalFarm( - ListSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _items(cls) -> typing.Type['Animal']: - return Animal - -from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/any_type_not_string.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/any_type_not_string.py deleted file mode 100644 index d3b1f5179c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/any_type_not_string.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AnyTypeNotString( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - NotSchema = StrSchema - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - NotSchema - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'AnyTypeNotString': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/api_response.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/api_response.py deleted file mode 100644 index 62fc4e31da..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/api_response.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ApiResponse( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - code = Int32Schema - type = StrSchema - message = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - code: typing.Union[code, Unset] = unset, - type: typing.Union[type, Unset] = unset, - message: typing.Union[message, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ApiResponse': - return super().__new__( - cls, - *args, - code=code, - type=type, - message=message, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/apple.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/apple.py deleted file mode 100644 index f0ca74fc19..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/apple.py +++ /dev/null @@ -1,124 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Apple( - _SchemaTypeChecker(typing.Union[frozendict, NoneClass, ]), - DictBase, - NoneBase, - Schema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'cultivar', - )) - - - class cultivar( - _SchemaValidator( - regex=[{ - 'pattern': r'^[a-zA-Z\s]*$', # noqa: E501 - }], - ), - StrSchema - ): - pass - - - class origin( - _SchemaValidator( - regex=[{ - 'pattern': r'^[A-Z\s]*$', # noqa: E501 - 'flags': ( - re.IGNORECASE - ) - }], - ), - StrSchema - ): - pass - - def __new__( - cls, - *args: typing.Union[dict, frozendict, None, ], - origin: typing.Union[origin, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Apple': - return super().__new__( - cls, - *args, - origin=origin, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/apple_req.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/apple_req.py deleted file mode 100644 index bb6ec8503f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/apple_req.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class AppleReq( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'cultivar', - )) - cultivar = StrSchema - mealy = BoolSchema - _additional_properties = None - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - cultivar: cultivar, - mealy: typing.Union[mealy, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - ) -> 'AppleReq': - return super().__new__( - cls, - *args, - cultivar=cultivar, - mealy=mealy, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_holding_any_type.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_holding_any_type.py deleted file mode 100644 index 427e3a7849..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_holding_any_type.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ArrayHoldingAnyType( - ListSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _items = AnyTypeSchema diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_array_of_number_only.py deleted file mode 100644 index 4d961402e3..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_array_of_number_only.py +++ /dev/null @@ -1,105 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ArrayOfArrayOfNumberOnly( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class ArrayArrayNumber( - ListSchema - ): - - - class _items( - ListSchema - ): - _items = NumberSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - ArrayArrayNumber: typing.Union[ArrayArrayNumber, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ArrayOfArrayOfNumberOnly': - return super().__new__( - cls, - *args, - ArrayArrayNumber=ArrayArrayNumber, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_enums.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_enums.py deleted file mode 100644 index 55735ae7a1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_enums.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ArrayOfEnums( - ListSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _items(cls) -> typing.Type['StringEnum']: - return StringEnum - -from petstore_api.model.string_enum import StringEnum diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_number_only.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_number_only.py deleted file mode 100644 index cf97c7288a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_number_only.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ArrayOfNumberOnly( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class ArrayNumber( - ListSchema - ): - _items = NumberSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - ArrayNumber: typing.Union[ArrayNumber, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ArrayOfNumberOnly': - return super().__new__( - cls, - *args, - ArrayNumber=ArrayNumber, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_test.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_test.py deleted file mode 100644 index 92af59070d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_test.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ArrayTest( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class array_of_string( - ListSchema - ): - _items = StrSchema - - - class array_array_of_integer( - ListSchema - ): - - - class _items( - ListSchema - ): - _items = Int64Schema - - - class array_array_of_model( - ListSchema - ): - - - class _items( - ListSchema - ): - - @classmethod - @property - def _items(cls) -> typing.Type['ReadOnlyFirst']: - return ReadOnlyFirst - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - array_of_string: typing.Union[array_of_string, Unset] = unset, - array_array_of_integer: typing.Union[array_array_of_integer, Unset] = unset, - array_array_of_model: typing.Union[array_array_of_model, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ArrayTest': - return super().__new__( - cls, - *args, - array_of_string=array_of_string, - array_array_of_integer=array_array_of_integer, - array_array_of_model=array_array_of_model, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.read_only_first import ReadOnlyFirst diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_with_validations_in_items.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_with_validations_in_items.py deleted file mode 100644 index 02df64785d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_with_validations_in_items.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ArrayWithValidationsInItems( - _SchemaValidator( - max_items=2, - ), - ListSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class _items( - _SchemaValidator( - inclusive_maximum=7, - ), - Int64Schema - ): - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/banana.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/banana.py deleted file mode 100644 index 2dd4fbc2d1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/banana.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Banana( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'lengthCm', - )) - lengthCm = NumberSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - lengthCm: lengthCm, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Banana': - return super().__new__( - cls, - *args, - lengthCm=lengthCm, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/banana_req.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/banana_req.py deleted file mode 100644 index b77c7566e7..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/banana_req.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class BananaReq( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'lengthCm', - )) - lengthCm = NumberSchema - sweet = BoolSchema - _additional_properties = None - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - lengthCm: lengthCm, - sweet: typing.Union[sweet, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - ) -> 'BananaReq': - return super().__new__( - cls, - *args, - lengthCm=lengthCm, - sweet=sweet, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/bar.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/bar.py deleted file mode 100644 index 5d00a2a89d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/bar.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -Bar = StrSchema diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/basque_pig.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/basque_pig.py deleted file mode 100644 index 6bc0e9e7b9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/basque_pig.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class BasquePig( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'className', - )) - - - class className( - _SchemaEnumMaker( - enum_value_to_name={ - "BasquePig": "BASQUEPIG", - } - ), - StrSchema - ): - - @classmethod - @property - def BASQUEPIG(cls): - return cls("BasquePig") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - className: className, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'BasquePig': - return super().__new__( - cls, - *args, - className=className, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/boolean.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/boolean.py deleted file mode 100644 index 4c79b9b00a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/boolean.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -Boolean = BoolSchema diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/boolean_enum.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/boolean_enum.py deleted file mode 100644 index a223a2ce06..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/boolean_enum.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class BooleanEnum( - _SchemaEnumMaker( - enum_value_to_name={ - BoolClass.TRUE: "TRUE", - } - ), - BoolSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def TRUE(cls): - return cls(BoolClass.TRUE) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/capitalization.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/capitalization.py deleted file mode 100644 index 56cf406a70..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/capitalization.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Capitalization( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - smallCamel = StrSchema - CapitalCamel = StrSchema - small_Snake = StrSchema - Capital_Snake = StrSchema - SCA_ETH_Flow_Points = StrSchema - ATT_NAME = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - smallCamel: typing.Union[smallCamel, Unset] = unset, - CapitalCamel: typing.Union[CapitalCamel, Unset] = unset, - small_Snake: typing.Union[small_Snake, Unset] = unset, - Capital_Snake: typing.Union[Capital_Snake, Unset] = unset, - SCA_ETH_Flow_Points: typing.Union[SCA_ETH_Flow_Points, Unset] = unset, - ATT_NAME: typing.Union[ATT_NAME, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Capitalization': - return super().__new__( - cls, - *args, - smallCamel=smallCamel, - CapitalCamel=CapitalCamel, - small_Snake=small_Snake, - Capital_Snake=Capital_Snake, - SCA_ETH_Flow_Points=SCA_ETH_Flow_Points, - ATT_NAME=ATT_NAME, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/cat.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/cat.py deleted file mode 100644 index e77e96fcfa..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/cat.py +++ /dev/null @@ -1,139 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Cat( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_1( - DictSchema - ): - declawed = BoolSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - declawed: typing.Union[declawed, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - declawed=declawed, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - Animal, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Cat': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/category.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/category.py deleted file mode 100644 index ef72720072..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/category.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Category( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'name', - )) - id = Int64Schema - name = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - name: name, - id: typing.Union[id, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Category': - return super().__new__( - cls, - *args, - name=name, - id=id, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/child_cat.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/child_cat.py deleted file mode 100644 index 7a8751c2c1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/child_cat.py +++ /dev/null @@ -1,139 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ChildCat( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_1( - DictSchema - ): - name = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - name: typing.Union[name, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - name=name, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - ParentPet, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ChildCat': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.parent_pet import ParentPet diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/class_model.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/class_model.py deleted file mode 100644 index d7cf4de512..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/class_model.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ClassModel( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Model for testing model with "_class" property - """ - _class = StrSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _class: typing.Union[_class, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ClassModel': - return super().__new__( - cls, - *args, - _class=_class, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/client.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/client.py deleted file mode 100644 index 13ad5e5ff3..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/client.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Client( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - client = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - client: typing.Union[client, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Client': - return super().__new__( - cls, - *args, - client=client, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/complex_quadrilateral.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/complex_quadrilateral.py deleted file mode 100644 index aafa7e29d2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/complex_quadrilateral.py +++ /dev/null @@ -1,153 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ComplexQuadrilateral( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_1( - DictSchema - ): - - - class quadrilateralType( - _SchemaEnumMaker( - enum_value_to_name={ - "ComplexQuadrilateral": "COMPLEXQUADRILATERAL", - } - ), - StrSchema - ): - - @classmethod - @property - def COMPLEXQUADRILATERAL(cls): - return cls("ComplexQuadrilateral") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - quadrilateralType: typing.Union[quadrilateralType, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - quadrilateralType=quadrilateralType, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - QuadrilateralInterface, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ComplexQuadrilateral': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.quadrilateral_interface import QuadrilateralInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_any_of_different_types_no_validations.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_any_of_different_types_no_validations.py deleted file mode 100644 index c0fa339d9f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_any_of_different_types_no_validations.py +++ /dev/null @@ -1,150 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ComposedAnyOfDifferentTypesNoValidations( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - anyOf_0 = DictSchema - anyOf_1 = DateSchema - anyOf_2 = DateTimeSchema - anyOf_3 = BinarySchema - anyOf_4 = StrSchema - anyOf_5 = StrSchema - anyOf_6 = DictSchema - anyOf_7 = BoolSchema - anyOf_8 = NoneSchema - - - class anyOf_9( - ListSchema - ): - _items = AnyTypeSchema - anyOf_10 = NumberSchema - anyOf_11 = Float32Schema - anyOf_12 = Float64Schema - anyOf_13 = IntSchema - anyOf_14 = Int32Schema - anyOf_15 = Int64Schema - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - anyOf_0, - anyOf_1, - anyOf_2, - anyOf_3, - anyOf_4, - anyOf_5, - anyOf_6, - anyOf_7, - anyOf_8, - anyOf_9, - anyOf_10, - anyOf_11, - anyOf_12, - anyOf_13, - anyOf_14, - anyOf_15, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ComposedAnyOfDifferentTypesNoValidations': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_array.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_array.py deleted file mode 100644 index 221abb75d3..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_array.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ComposedArray( - ListSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _items = AnyTypeSchema diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_bool.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_bool.py deleted file mode 100644 index c7fae992ce..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_bool.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ComposedBool( - ComposedBase, - BoolSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = AnyTypeSchema - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[bool, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'ComposedBool': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_none.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_none.py deleted file mode 100644 index c0fbf1abde..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_none.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ComposedNone( - ComposedBase, - NoneSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = AnyTypeSchema - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'ComposedNone': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_number.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_number.py deleted file mode 100644 index 6c53edc342..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_number.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ComposedNumber( - ComposedBase, - NumberSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = AnyTypeSchema - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[float, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'ComposedNumber': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_object.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_object.py deleted file mode 100644 index 3579c7965d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_object.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ComposedObject( - ComposedBase, - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = AnyTypeSchema - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ComposedObject': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_one_of_different_types.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_one_of_different_types.py deleted file mode 100644 index 3e27e2a996..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_one_of_different_types.py +++ /dev/null @@ -1,171 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ComposedOneOfDifferentTypes( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - this is a model that allows payloads of type object or number - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - oneOf_2 = NoneSchema - oneOf_3 = DateSchema - - - class oneOf_4( - _SchemaValidator( - max_properties=4, - min_properties=4, - ), - DictSchema - ): - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'oneOf_4': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class oneOf_5( - _SchemaValidator( - max_items=4, - min_items=4, - ), - ListSchema - ): - _items = AnyTypeSchema - - - class oneOf_6( - _SchemaValidator( - regex=[{ - 'pattern': r'^2020.*', # noqa: E501 - }], - ), - DateTimeSchema - ): - pass - return { - 'allOf': [ - ], - 'oneOf': [ - NumberWithValidations, - Animal, - oneOf_2, - oneOf_3, - oneOf_4, - oneOf_5, - oneOf_6, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ComposedOneOfDifferentTypes': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.animal import Animal -from petstore_api.model.number_with_validations import NumberWithValidations diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_string.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_string.py deleted file mode 100644 index da33e5202f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_string.py +++ /dev/null @@ -1,114 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ComposedString( - ComposedBase, - StrSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - allOf_0 = AnyTypeSchema - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[str, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'ComposedString': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/currency.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/currency.py deleted file mode 100644 index 0844fa544b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/currency.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Currency( - _SchemaEnumMaker( - enum_value_to_name={ - "eur": "EUR", - "usd": "USD", - } - ), - StrSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def EUR(cls): - return cls("eur") - - @classmethod - @property - def USD(cls): - return cls("usd") diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/danish_pig.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/danish_pig.py deleted file mode 100644 index 3f30915125..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/danish_pig.py +++ /dev/null @@ -1,112 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class DanishPig( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'className', - )) - - - class className( - _SchemaEnumMaker( - enum_value_to_name={ - "DanishPig": "DANISHPIG", - } - ), - StrSchema - ): - - @classmethod - @property - def DANISHPIG(cls): - return cls("DanishPig") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - className: className, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'DanishPig': - return super().__new__( - cls, - *args, - className=className, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_time_test.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_time_test.py deleted file mode 100644 index a4cc1eea68..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_time_test.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -DateTimeTest = DateTimeSchema diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_time_with_validations.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_time_with_validations.py deleted file mode 100644 index f4c7c07278..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_time_with_validations.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class DateTimeWithValidations( - _SchemaValidator( - regex=[{ - 'pattern': r'^2020.*', # noqa: E501 - }], - ), - DateTimeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_with_validations.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_with_validations.py deleted file mode 100644 index f3dceba1cd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_with_validations.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class DateWithValidations( - _SchemaValidator( - regex=[{ - 'pattern': r'^2020.*', # noqa: E501 - }], - ), - DateSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/decimal_payload.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/decimal_payload.py deleted file mode 100644 index 1bae833848..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/decimal_payload.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -DecimalPayload = DecimalSchema diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/dog.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/dog.py deleted file mode 100644 index 130512a669..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/dog.py +++ /dev/null @@ -1,139 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Dog( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_1( - DictSchema - ): - breed = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - breed: typing.Union[breed, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - breed=breed, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - Animal, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Dog': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/drawing.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/drawing.py deleted file mode 100644 index c3cb01e0ae..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/drawing.py +++ /dev/null @@ -1,135 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Drawing( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def mainShape(cls) -> typing.Type['Shape']: - return Shape - - @classmethod - @property - def shapeOrNull(cls) -> typing.Type['ShapeOrNull']: - return ShapeOrNull - - @classmethod - @property - def nullableShape(cls) -> typing.Type['NullableShape']: - return NullableShape - - - class shapes( - ListSchema - ): - - @classmethod - @property - def _items(cls) -> typing.Type['Shape']: - return Shape - - @classmethod - @property - def _additional_properties(cls) -> typing.Type['Fruit']: - return Fruit - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - mainShape: typing.Union['Shape', Unset] = unset, - shapeOrNull: typing.Union['ShapeOrNull', Unset] = unset, - nullableShape: typing.Union['NullableShape', Unset] = unset, - shapes: typing.Union[shapes, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Drawing': - return super().__new__( - cls, - *args, - mainShape=mainShape, - shapeOrNull=shapeOrNull, - nullableShape=nullableShape, - shapes=shapes, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.fruit import Fruit -from petstore_api.model.nullable_shape import NullableShape -from petstore_api.model.shape import Shape -from petstore_api.model.shape_or_null import ShapeOrNull diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_arrays.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_arrays.py deleted file mode 100644 index be4182fe23..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_arrays.py +++ /dev/null @@ -1,143 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EnumArrays( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class just_symbol( - _SchemaEnumMaker( - enum_value_to_name={ - ">=": "GREATER_THAN_EQUALS", - "$": "DOLLAR", - } - ), - StrSchema - ): - - @classmethod - @property - def GREATER_THAN_EQUALS(cls): - return cls(">=") - - @classmethod - @property - def DOLLAR(cls): - return cls("$") - - - class array_enum( - ListSchema - ): - - - class _items( - _SchemaEnumMaker( - enum_value_to_name={ - "fish": "FISH", - "crab": "CRAB", - } - ), - StrSchema - ): - - @classmethod - @property - def FISH(cls): - return cls("fish") - - @classmethod - @property - def CRAB(cls): - return cls("crab") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - just_symbol: typing.Union[just_symbol, Unset] = unset, - array_enum: typing.Union[array_enum, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'EnumArrays': - return super().__new__( - cls, - *args, - just_symbol=just_symbol, - array_enum=array_enum, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_class.py deleted file mode 100644 index 019001d208..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_class.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EnumClass( - _SchemaEnumMaker( - enum_value_to_name={ - "_abc": "_ABC", - "-efg": "EFG", - "(xyz)": "XYZ", - } - ), - StrSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _ABC(cls): - return cls("_abc") - - @classmethod - @property - def EFG(cls): - return cls("-efg") - - @classmethod - @property - def XYZ(cls): - return cls("(xyz)") diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_test.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_test.py deleted file mode 100644 index 319b0282de..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_test.py +++ /dev/null @@ -1,240 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EnumTest( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'enum_string_required', - )) - - - class enum_string( - _SchemaEnumMaker( - enum_value_to_name={ - "UPPER": "UPPER", - "lower": "LOWER", - "": "EMPTY", - } - ), - StrSchema - ): - - @classmethod - @property - def UPPER(cls): - return cls("UPPER") - - @classmethod - @property - def LOWER(cls): - return cls("lower") - - @classmethod - @property - def EMPTY(cls): - return cls("") - - - class enum_string_required( - _SchemaEnumMaker( - enum_value_to_name={ - "UPPER": "UPPER", - "lower": "LOWER", - "": "EMPTY", - } - ), - StrSchema - ): - - @classmethod - @property - def UPPER(cls): - return cls("UPPER") - - @classmethod - @property - def LOWER(cls): - return cls("lower") - - @classmethod - @property - def EMPTY(cls): - return cls("") - - - class enum_integer( - _SchemaEnumMaker( - enum_value_to_name={ - 1: "POSITIVE_1", - -1: "NEGATIVE_1", - } - ), - Int32Schema - ): - - @classmethod - @property - def POSITIVE_1(cls): - return cls(1) - - @classmethod - @property - def NEGATIVE_1(cls): - return cls(-1) - - - class enum_number( - _SchemaEnumMaker( - enum_value_to_name={ - 1.1: "POSITIVE_1_PT_1", - -1.2: "NEGATIVE_1_PT_2", - } - ), - Float64Schema - ): - - @classmethod - @property - def POSITIVE_1_PT_1(cls): - return cls(1.1) - - @classmethod - @property - def NEGATIVE_1_PT_2(cls): - return cls(-1.2) - - @classmethod - @property - def stringEnum(cls) -> typing.Type['StringEnum']: - return StringEnum - - @classmethod - @property - def IntegerEnum(cls) -> typing.Type['IntegerEnum']: - return IntegerEnum - - @classmethod - @property - def StringEnumWithDefaultValue(cls) -> typing.Type['StringEnumWithDefaultValue']: - return StringEnumWithDefaultValue - - @classmethod - @property - def IntegerEnumWithDefaultValue(cls) -> typing.Type['IntegerEnumWithDefaultValue']: - return IntegerEnumWithDefaultValue - - @classmethod - @property - def IntegerEnumOneValue(cls) -> typing.Type['IntegerEnumOneValue']: - return IntegerEnumOneValue - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - enum_string_required: enum_string_required, - enum_string: typing.Union[enum_string, Unset] = unset, - enum_integer: typing.Union[enum_integer, Unset] = unset, - enum_number: typing.Union[enum_number, Unset] = unset, - stringEnum: typing.Union['StringEnum', Unset] = unset, - IntegerEnum: typing.Union['IntegerEnum', Unset] = unset, - StringEnumWithDefaultValue: typing.Union['StringEnumWithDefaultValue', Unset] = unset, - IntegerEnumWithDefaultValue: typing.Union['IntegerEnumWithDefaultValue', Unset] = unset, - IntegerEnumOneValue: typing.Union['IntegerEnumOneValue', Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'EnumTest': - return super().__new__( - cls, - *args, - enum_string_required=enum_string_required, - enum_string=enum_string, - enum_integer=enum_integer, - enum_number=enum_number, - stringEnum=stringEnum, - IntegerEnum=IntegerEnum, - StringEnumWithDefaultValue=StringEnumWithDefaultValue, - IntegerEnumWithDefaultValue=IntegerEnumWithDefaultValue, - IntegerEnumOneValue=IntegerEnumOneValue, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.integer_enum import IntegerEnum -from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue -from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue -from petstore_api.model.string_enum import StringEnum -from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/equilateral_triangle.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/equilateral_triangle.py deleted file mode 100644 index c572964a57..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/equilateral_triangle.py +++ /dev/null @@ -1,153 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class EquilateralTriangle( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_1( - DictSchema - ): - - - class triangleType( - _SchemaEnumMaker( - enum_value_to_name={ - "EquilateralTriangle": "EQUILATERALTRIANGLE", - } - ), - StrSchema - ): - - @classmethod - @property - def EQUILATERALTRIANGLE(cls): - return cls("EquilateralTriangle") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - triangleType: typing.Union[triangleType, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - triangleType=triangleType, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - TriangleInterface, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'EquilateralTriangle': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/file.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/file.py deleted file mode 100644 index 3e68cefa31..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/file.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class File( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Must be named `File` for test. - """ - sourceURI = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - sourceURI: typing.Union[sourceURI, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'File': - return super().__new__( - cls, - *args, - sourceURI=sourceURI, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/file_schema_test_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/file_schema_test_class.py deleted file mode 100644 index ce05803535..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/file_schema_test_class.py +++ /dev/null @@ -1,113 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class FileSchemaTestClass( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def file(cls) -> typing.Type['File']: - return File - - - class files( - ListSchema - ): - - @classmethod - @property - def _items(cls) -> typing.Type['File']: - return File - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - file: typing.Union['File', Unset] = unset, - files: typing.Union[files, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'FileSchemaTestClass': - return super().__new__( - cls, - *args, - file=file, - files=files, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.file import File diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/foo.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/foo.py deleted file mode 100644 index 8d650b5604..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/foo.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Foo( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - bar = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - bar: typing.Union[bar, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Foo': - return super().__new__( - cls, - *args, - bar=bar, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/format_test.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/format_test.py deleted file mode 100644 index 28fb00bce8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/format_test.py +++ /dev/null @@ -1,261 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class FormatTest( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'number', - 'byte', - 'date', - 'password', - )) - - - class integer( - _SchemaValidator( - inclusive_maximum=100, - inclusive_minimum=10, - multiple_of=2, - ), - IntSchema - ): - pass - int32 = Int32Schema - - - class int32withValidations( - _SchemaValidator( - inclusive_maximum=200, - inclusive_minimum=20, - ), - Int32Schema - ): - pass - int64 = Int64Schema - - - class number( - _SchemaValidator( - inclusive_maximum=543.2, - inclusive_minimum=32.1, - multiple_of=32.5, - ), - NumberSchema - ): - pass - - - class _float( - _SchemaValidator( - inclusive_maximum=987.6, - inclusive_minimum=54.3, - ), - Float32Schema - ): - pass - locals()["float"] = _float - del locals()['_float'] - float32 = Float32Schema - - - class double( - _SchemaValidator( - inclusive_maximum=123.4, - inclusive_minimum=67.8, - ), - Float64Schema - ): - pass - float64 = Float64Schema - - - class arrayWithUniqueItems( - _SchemaValidator( - unique_items=True, - ), - ListSchema - ): - _items = NumberSchema - - - class string( - _SchemaValidator( - regex=[{ - 'pattern': r'[a-z]', # noqa: E501 - 'flags': ( - re.IGNORECASE - ) - }], - ), - StrSchema - ): - pass - byte = StrSchema - binary = BinarySchema - date = DateSchema - dateTime = DateTimeSchema - uuid = UUIDSchema - uuidNoExample = UUIDSchema - - - class password( - _SchemaValidator( - max_length=64, - min_length=10, - ), - StrSchema - ): - pass - - - class pattern_with_digits( - _SchemaValidator( - regex=[{ - 'pattern': r'^\d{10}$', # noqa: E501 - }], - ), - StrSchema - ): - pass - - - class pattern_with_digits_and_delimiter( - _SchemaValidator( - regex=[{ - 'pattern': r'^image_\d{1,3}$', # noqa: E501 - 'flags': ( - re.IGNORECASE - ) - }], - ), - StrSchema - ): - pass - noneProp = NoneSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - number: number, - byte: byte, - date: date, - password: password, - integer: typing.Union[integer, Unset] = unset, - int32: typing.Union[int32, Unset] = unset, - int32withValidations: typing.Union[int32withValidations, Unset] = unset, - int64: typing.Union[int64, Unset] = unset, - float32: typing.Union[float32, Unset] = unset, - double: typing.Union[double, Unset] = unset, - float64: typing.Union[float64, Unset] = unset, - arrayWithUniqueItems: typing.Union[arrayWithUniqueItems, Unset] = unset, - string: typing.Union[string, Unset] = unset, - binary: typing.Union[binary, Unset] = unset, - dateTime: typing.Union[dateTime, Unset] = unset, - uuid: typing.Union[uuid, Unset] = unset, - uuidNoExample: typing.Union[uuidNoExample, Unset] = unset, - pattern_with_digits: typing.Union[pattern_with_digits, Unset] = unset, - pattern_with_digits_and_delimiter: typing.Union[pattern_with_digits_and_delimiter, Unset] = unset, - noneProp: typing.Union[noneProp, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'FormatTest': - return super().__new__( - cls, - *args, - number=number, - byte=byte, - date=date, - password=password, - integer=integer, - int32=int32, - int32withValidations=int32withValidations, - int64=int64, - float32=float32, - double=double, - float64=float64, - arrayWithUniqueItems=arrayWithUniqueItems, - string=string, - binary=binary, - dateTime=dateTime, - uuid=uuid, - uuidNoExample=uuidNoExample, - pattern_with_digits=pattern_with_digits, - pattern_with_digits_and_delimiter=pattern_with_digits_and_delimiter, - noneProp=noneProp, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/fruit.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/fruit.py deleted file mode 100644 index bd6051a661..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/fruit.py +++ /dev/null @@ -1,121 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Fruit( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - color = StrSchema - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ], - 'oneOf': [ - Apple, - Banana, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - color: typing.Union[color, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Fruit': - return super().__new__( - cls, - *args, - color=color, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.apple import Apple -from petstore_api.model.banana import Banana diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/fruit_req.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/fruit_req.py deleted file mode 100644 index 3458ea63f6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/fruit_req.py +++ /dev/null @@ -1,120 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class FruitReq( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - oneOf_0 = NoneSchema - return { - 'allOf': [ - ], - 'oneOf': [ - oneOf_0, - AppleReq, - BananaReq, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'FruitReq': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.apple_req import AppleReq -from petstore_api.model.banana_req import BananaReq diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/gm_fruit.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/gm_fruit.py deleted file mode 100644 index cd2ab6559f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/gm_fruit.py +++ /dev/null @@ -1,121 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class GmFruit( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - color = StrSchema - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - Apple, - Banana, - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - color: typing.Union[color, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'GmFruit': - return super().__new__( - cls, - *args, - color=color, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.apple import Apple -from petstore_api.model.banana import Banana diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/grandparent_animal.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/grandparent_animal.py deleted file mode 100644 index 7b6a746409..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/grandparent_animal.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class GrandparentAnimal( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'pet_type', - )) - pet_type = StrSchema - - @classmethod - @property - def _discriminator(cls): - return { - 'pet_type': { - 'ChildCat': ChildCat, - 'ParentPet': ParentPet, - } - } - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - pet_type: pet_type, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'GrandparentAnimal': - return super().__new__( - cls, - *args, - pet_type=pet_type, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.child_cat import ChildCat -from petstore_api.model.parent_pet import ParentPet diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/has_only_read_only.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/has_only_read_only.py deleted file mode 100644 index 4830db9c7d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/has_only_read_only.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class HasOnlyReadOnly( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - bar = StrSchema - foo = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - bar: typing.Union[bar, Unset] = unset, - foo: typing.Union[foo, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'HasOnlyReadOnly': - return super().__new__( - cls, - *args, - bar=bar, - foo=foo, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/health_check_result.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/health_check_result.py deleted file mode 100644 index c48f1c3803..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/health_check_result.py +++ /dev/null @@ -1,115 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class HealthCheckResult( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. - """ - - - class NullableMessage( - _SchemaTypeChecker(typing.Union[NoneClass, str, ]), - StrBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[str, None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'NullableMessage': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - NullableMessage: typing.Union[NullableMessage, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'HealthCheckResult': - return super().__new__( - cls, - *args, - NullableMessage=NullableMessage, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum.py deleted file mode 100644 index 2fc839f1da..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class IntegerEnum( - _SchemaEnumMaker( - enum_value_to_name={ - 0: "POSITIVE_0", - 1: "POSITIVE_1", - 2: "POSITIVE_2", - } - ), - IntSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def POSITIVE_0(cls): - return cls(0) - - @classmethod - @property - def POSITIVE_1(cls): - return cls(1) - - @classmethod - @property - def POSITIVE_2(cls): - return cls(2) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_big.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_big.py deleted file mode 100644 index 3365962262..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_big.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class IntegerEnumBig( - _SchemaEnumMaker( - enum_value_to_name={ - 10: "POSITIVE_10", - 11: "POSITIVE_11", - 12: "POSITIVE_12", - } - ), - IntSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def POSITIVE_10(cls): - return cls(10) - - @classmethod - @property - def POSITIVE_11(cls): - return cls(11) - - @classmethod - @property - def POSITIVE_12(cls): - return cls(12) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_one_value.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_one_value.py deleted file mode 100644 index 706ea7f682..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_one_value.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class IntegerEnumOneValue( - _SchemaEnumMaker( - enum_value_to_name={ - 0: "POSITIVE_0", - } - ), - IntSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def POSITIVE_0(cls): - return cls(0) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_with_default_value.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_with_default_value.py deleted file mode 100644 index c4aac3b348..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_with_default_value.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class IntegerEnumWithDefaultValue( - _SchemaEnumMaker( - enum_value_to_name={ - 0: "POSITIVE_0", - 1: "POSITIVE_1", - 2: "POSITIVE_2", - } - ), - IntSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def POSITIVE_0(cls): - return cls(0) - - @classmethod - @property - def POSITIVE_1(cls): - return cls(1) - - @classmethod - @property - def POSITIVE_2(cls): - return cls(2) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_max10.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_max10.py deleted file mode 100644 index 0915ff33f9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_max10.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class IntegerMax10( - _SchemaValidator( - inclusive_maximum=10, - ), - Int64Schema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_min15.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_min15.py deleted file mode 100644 index cb59a2b7db..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_min15.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class IntegerMin15( - _SchemaValidator( - inclusive_minimum=15, - ), - Int64Schema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/isosceles_triangle.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/isosceles_triangle.py deleted file mode 100644 index 8a3bb200bf..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/isosceles_triangle.py +++ /dev/null @@ -1,153 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class IsoscelesTriangle( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_1( - DictSchema - ): - - - class triangleType( - _SchemaEnumMaker( - enum_value_to_name={ - "IsoscelesTriangle": "ISOSCELESTRIANGLE", - } - ), - StrSchema - ): - - @classmethod - @property - def ISOSCELESTRIANGLE(cls): - return cls("IsoscelesTriangle") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - triangleType: typing.Union[triangleType, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - triangleType=triangleType, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - TriangleInterface, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'IsoscelesTriangle': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/mammal.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/mammal.py deleted file mode 100644 index a2eb42d4db..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/mammal.py +++ /dev/null @@ -1,131 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Mammal( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _discriminator(cls): - return { - 'className': { - 'Pig': Pig, - 'whale': Whale, - 'zebra': Zebra, - } - } - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ], - 'oneOf': [ - Whale, - Zebra, - Pig, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Mammal': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.pig import Pig -from petstore_api.model.whale import Whale -from petstore_api.model.zebra import Zebra diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/map_test.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/map_test.py deleted file mode 100644 index a9f8383cb5..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/map_test.py +++ /dev/null @@ -1,206 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MapTest( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class map_map_of_string( - DictSchema - ): - - - class _additional_properties( - DictSchema - ): - _additional_properties = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> '_additional_properties': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'map_map_of_string': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class map_of_enum_string( - DictSchema - ): - - - class _additional_properties( - _SchemaEnumMaker( - enum_value_to_name={ - "UPPER": "UPPER", - "lower": "LOWER", - } - ), - StrSchema - ): - - @classmethod - @property - def UPPER(cls): - return cls("UPPER") - - @classmethod - @property - def LOWER(cls): - return cls("lower") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'map_of_enum_string': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class direct_map( - DictSchema - ): - _additional_properties = BoolSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'direct_map': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - @classmethod - @property - def indirect_map(cls) -> typing.Type['StringBooleanMap']: - return StringBooleanMap - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - map_map_of_string: typing.Union[map_map_of_string, Unset] = unset, - map_of_enum_string: typing.Union[map_of_enum_string, Unset] = unset, - direct_map: typing.Union[direct_map, Unset] = unset, - indirect_map: typing.Union['StringBooleanMap', Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MapTest': - return super().__new__( - cls, - *args, - map_map_of_string=map_map_of_string, - map_of_enum_string=map_of_enum_string, - direct_map=direct_map, - indirect_map=indirect_map, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.string_boolean_map import StringBooleanMap diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/mixed_properties_and_additional_properties_class.py deleted file mode 100644 index 70477d2f5a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ /dev/null @@ -1,126 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class MixedPropertiesAndAdditionalPropertiesClass( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - uuid = UUIDSchema - dateTime = DateTimeSchema - - - class map( - DictSchema - ): - - @classmethod - @property - def _additional_properties(cls) -> typing.Type['Animal']: - return Animal - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'map': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - uuid: typing.Union[uuid, Unset] = unset, - dateTime: typing.Union[dateTime, Unset] = unset, - map: typing.Union[map, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'MixedPropertiesAndAdditionalPropertiesClass': - return super().__new__( - cls, - *args, - uuid=uuid, - dateTime=dateTime, - map=map, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/model200_response.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/model200_response.py deleted file mode 100644 index edca0435ec..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/model200_response.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Model200Response( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - model with an invalid class name for python, starts with a number - """ - name = Int32Schema - _class = StrSchema - locals()["class"] = _class - del locals()['_class'] - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - name: typing.Union[name, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Model200Response': - return super().__new__( - cls, - *args, - name=name, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/model_return.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/model_return.py deleted file mode 100644 index 4fe5b613f5..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/model_return.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ModelReturn( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Model for testing reserved words - """ - _return = Int32Schema - locals()["return"] = _return - del locals()['_return'] - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ModelReturn': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/money.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/money.py deleted file mode 100644 index fc48f495a6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/money.py +++ /dev/null @@ -1,108 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Money( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'amount', - 'currency', - )) - amount = DecimalSchema - - @classmethod - @property - def currency(cls) -> typing.Type['Currency']: - return Currency - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - amount: amount, - currency: currency, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Money': - return super().__new__( - cls, - *args, - amount=amount, - currency=currency, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.currency import Currency diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/name.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/name.py deleted file mode 100644 index f70569b177..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/name.py +++ /dev/null @@ -1,105 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Name( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Model for testing model name same as property name - """ - _required_property_names = set(( - 'name', - )) - name = Int32Schema - snake_case = Int32Schema - _property = StrSchema - locals()["property"] = _property - del locals()['_property'] - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - name: name, - snake_case: typing.Union[snake_case, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Name': - return super().__new__( - cls, - *args, - name=name, - snake_case=snake_case, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/no_additional_properties.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/no_additional_properties.py deleted file mode 100644 index a54984228a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/no_additional_properties.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NoAdditionalProperties( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'id', - )) - id = Int64Schema - petId = Int64Schema - _additional_properties = None - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - id: id, - petId: typing.Union[petId, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - ) -> 'NoAdditionalProperties': - return super().__new__( - cls, - *args, - id=id, - petId=petId, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_class.py deleted file mode 100644 index 71559959bd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_class.py +++ /dev/null @@ -1,419 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NullableClass( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class integer_prop( - _SchemaTypeChecker(typing.Union[NoneClass, decimal.Decimal, ]), - IntBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[int, None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'integer_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - class number_prop( - _SchemaTypeChecker(typing.Union[NoneClass, decimal.Decimal, ]), - NumberBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[float, None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'number_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - class boolean_prop( - _SchemaTypeChecker(typing.Union[NoneClass, BoolClass, ]), - BoolBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[bool, None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'boolean_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - class string_prop( - _SchemaTypeChecker(typing.Union[NoneClass, str, ]), - StrBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[str, None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'string_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - class date_prop( - _SchemaTypeChecker(typing.Union[NoneClass, str, ]), - DateBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'date_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - class datetime_prop( - _SchemaTypeChecker(typing.Union[NoneClass, str, ]), - DateTimeBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'datetime_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - class array_nullable_prop( - _SchemaTypeChecker(typing.Union[tuple, NoneClass, ]), - ListBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[list, tuple, None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'array_nullable_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - class array_and_items_nullable_prop( - _SchemaTypeChecker(typing.Union[tuple, NoneClass, ]), - ListBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[list, tuple, None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'array_and_items_nullable_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) - - - class array_items_nullable( - ListSchema - ): - - - class _items( - _SchemaTypeChecker(typing.Union[frozendict, NoneClass, ]), - DictBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, None, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> '_items': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class object_nullable_prop( - _SchemaTypeChecker(typing.Union[frozendict, NoneClass, ]), - DictBase, - NoneBase, - Schema - ): - _additional_properties = DictSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, None, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'object_nullable_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class object_and_items_nullable_prop( - _SchemaTypeChecker(typing.Union[frozendict, NoneClass, ]), - DictBase, - NoneBase, - Schema - ): - - - class _additional_properties( - _SchemaTypeChecker(typing.Union[frozendict, NoneClass, ]), - DictBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, None, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> '_additional_properties': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - def __new__( - cls, - *args: typing.Union[dict, frozendict, None, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'object_and_items_nullable_prop': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class object_items_nullable( - DictSchema - ): - - - class _additional_properties( - _SchemaTypeChecker(typing.Union[frozendict, NoneClass, ]), - DictBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, None, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> '_additional_properties': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'object_items_nullable': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - class _additional_properties( - _SchemaTypeChecker(typing.Union[frozendict, NoneClass, ]), - DictBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, None, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> '_additional_properties': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - integer_prop: typing.Union[integer_prop, Unset] = unset, - number_prop: typing.Union[number_prop, Unset] = unset, - boolean_prop: typing.Union[boolean_prop, Unset] = unset, - string_prop: typing.Union[string_prop, Unset] = unset, - date_prop: typing.Union[date_prop, Unset] = unset, - datetime_prop: typing.Union[datetime_prop, Unset] = unset, - array_nullable_prop: typing.Union[array_nullable_prop, Unset] = unset, - array_and_items_nullable_prop: typing.Union[array_and_items_nullable_prop, Unset] = unset, - array_items_nullable: typing.Union[array_items_nullable, Unset] = unset, - object_nullable_prop: typing.Union[object_nullable_prop, Unset] = unset, - object_and_items_nullable_prop: typing.Union[object_and_items_nullable_prop, Unset] = unset, - object_items_nullable: typing.Union[object_items_nullable, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'NullableClass': - return super().__new__( - cls, - *args, - integer_prop=integer_prop, - number_prop=number_prop, - boolean_prop=boolean_prop, - string_prop=string_prop, - date_prop=date_prop, - datetime_prop=datetime_prop, - array_nullable_prop=array_nullable_prop, - array_and_items_nullable_prop=array_and_items_nullable_prop, - array_items_nullable=array_items_nullable, - object_nullable_prop=object_nullable_prop, - object_and_items_nullable_prop=object_and_items_nullable_prop, - object_items_nullable=object_items_nullable, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_shape.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_shape.py deleted file mode 100644 index c24703964e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_shape.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NullableShape( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - The value may be a shape or the 'null' value. For a composed schema to validate a null payload, one of its chosen oneOf schemas must be type null or nullable (introduced in OAS schema >= 3.0) - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - oneOf_2 = NoneSchema - return { - 'allOf': [ - ], - 'oneOf': [ - Triangle, - Quadrilateral, - oneOf_2, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'NullableShape': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.quadrilateral import Quadrilateral -from petstore_api.model.triangle import Triangle diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_string.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_string.py deleted file mode 100644 index 7cf3c74f31..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_string.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NullableString( - _SchemaTypeChecker(typing.Union[NoneClass, str, ]), - StrBase, - NoneBase, - Schema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __new__( - cls, - *args: typing.Union[str, None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'NullableString': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number.py deleted file mode 100644 index 47361523e0..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -Number = NumberSchema diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number_only.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number_only.py deleted file mode 100644 index 6f4036faa4..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number_only.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NumberOnly( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - JustNumber = NumberSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - JustNumber: typing.Union[JustNumber, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'NumberOnly': - return super().__new__( - cls, - *args, - JustNumber=JustNumber, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number_with_validations.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number_with_validations.py deleted file mode 100644 index 3963b0b297..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number_with_validations.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class NumberWithValidations( - _SchemaValidator( - inclusive_maximum=20, - inclusive_minimum=10, - ), - NumberSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_interface.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_interface.py deleted file mode 100644 index d8eec30dee..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_interface.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -ObjectInterface = DictSchema diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_model_with_ref_props.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_model_with_ref_props.py deleted file mode 100644 index 11de28c599..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_model_with_ref_props.py +++ /dev/null @@ -1,109 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ObjectModelWithRefProps( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations - """ - - @classmethod - @property - def myNumber(cls) -> typing.Type['NumberWithValidations']: - return NumberWithValidations - myString = StrSchema - myBoolean = BoolSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - myNumber: typing.Union['NumberWithValidations', Unset] = unset, - myString: typing.Union[myString, Unset] = unset, - myBoolean: typing.Union[myBoolean, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ObjectModelWithRefProps': - return super().__new__( - cls, - *args, - myNumber=myNumber, - myString=myString, - myBoolean=myBoolean, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.number_with_validations import NumberWithValidations diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_decimal_properties.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_decimal_properties.py deleted file mode 100644 index 69264d1642..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_decimal_properties.py +++ /dev/null @@ -1,107 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ObjectWithDecimalProperties( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - length = DecimalSchema - width = DecimalSchema - - @classmethod - @property - def cost(cls) -> typing.Type['Money']: - return Money - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - length: typing.Union[length, Unset] = unset, - width: typing.Union[width, Unset] = unset, - cost: typing.Union['Money', Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ObjectWithDecimalProperties': - return super().__new__( - cls, - *args, - length=length, - width=width, - cost=cost, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.money import Money diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_difficultly_named_props.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_difficultly_named_props.py deleted file mode 100644 index f4e66878f9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_difficultly_named_props.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ObjectWithDifficultlyNamedProps( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - model with properties that have invalid names for python - """ - _required_property_names = set(( - '123-list', - )) - special_property_name = Int64Schema - locals()["$special[property.name]"] = special_property_name - del locals()['special_property_name'] - _123_list = StrSchema - locals()["123-list"] = _123_list - del locals()['_123_list'] - _123_number = IntSchema - locals()["123Number"] = _123_number - del locals()['_123_number'] - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ObjectWithDifficultlyNamedProps': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_inline_composition_property.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_inline_composition_property.py deleted file mode 100644 index caff3025fa..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_inline_composition_property.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ObjectWithInlineCompositionProperty( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - class someProp( - ComposedSchema - ): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_0( - _SchemaValidator( - min_length=1, - ), - StrSchema - ): - pass - return { - 'allOf': [ - allOf_0, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'someProp': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - someProp: typing.Union[someProp, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ObjectWithInlineCompositionProperty': - return super().__new__( - cls, - *args, - someProp=someProp, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_validations.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_validations.py deleted file mode 100644 index 1eb29795fb..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_validations.py +++ /dev/null @@ -1,95 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ObjectWithValidations( - _SchemaValidator( - min_properties=2, - ), - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ObjectWithValidations': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/order.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/order.py deleted file mode 100644 index c7a69be916..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/order.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Order( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - id = Int64Schema - petId = Int64Schema - quantity = Int32Schema - shipDate = DateTimeSchema - - - class status( - _SchemaEnumMaker( - enum_value_to_name={ - "placed": "PLACED", - "approved": "APPROVED", - "delivered": "DELIVERED", - } - ), - StrSchema - ): - - @classmethod - @property - def PLACED(cls): - return cls("placed") - - @classmethod - @property - def APPROVED(cls): - return cls("approved") - - @classmethod - @property - def DELIVERED(cls): - return cls("delivered") - complete = BoolSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - id: typing.Union[id, Unset] = unset, - petId: typing.Union[petId, Unset] = unset, - quantity: typing.Union[quantity, Unset] = unset, - shipDate: typing.Union[shipDate, Unset] = unset, - status: typing.Union[status, Unset] = unset, - complete: typing.Union[complete, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Order': - return super().__new__( - cls, - *args, - id=id, - petId=petId, - quantity=quantity, - shipDate=shipDate, - status=status, - complete=complete, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/parent_pet.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/parent_pet.py deleted file mode 100644 index 50bae9f0b7..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/parent_pet.py +++ /dev/null @@ -1,127 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ParentPet( - ComposedBase, - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _discriminator(cls): - return { - 'pet_type': { - 'ChildCat': ChildCat, - } - } - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - GrandparentAnimal, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ParentPet': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.child_cat import ChildCat -from petstore_api.model.grandparent_animal import GrandparentAnimal diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/pet.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/pet.py deleted file mode 100644 index 6b1cd00870..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/pet.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Pet( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Pet object that needs to be added to the store - """ - _required_property_names = set(( - 'name', - 'photoUrls', - )) - id = Int64Schema - - @classmethod - @property - def category(cls) -> typing.Type['Category']: - return Category - name = StrSchema - - - class photoUrls( - ListSchema - ): - _items = StrSchema - - - class tags( - ListSchema - ): - - @classmethod - @property - def _items(cls) -> typing.Type['Tag']: - return Tag - - - class status( - _SchemaEnumMaker( - enum_value_to_name={ - "available": "AVAILABLE", - "pending": "PENDING", - "sold": "SOLD", - } - ), - StrSchema - ): - - @classmethod - @property - def AVAILABLE(cls): - return cls("available") - - @classmethod - @property - def PENDING(cls): - return cls("pending") - - @classmethod - @property - def SOLD(cls): - return cls("sold") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - name: name, - photoUrls: photoUrls, - id: typing.Union[id, Unset] = unset, - category: typing.Union['Category', Unset] = unset, - tags: typing.Union[tags, Unset] = unset, - status: typing.Union[status, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Pet': - return super().__new__( - cls, - *args, - name=name, - photoUrls=photoUrls, - id=id, - category=category, - tags=tags, - status=status, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.category import Category -from petstore_api.model.tag import Tag diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/pig.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/pig.py deleted file mode 100644 index ef89f2a9bd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/pig.py +++ /dev/null @@ -1,128 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Pig( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _discriminator(cls): - return { - 'className': { - 'BasquePig': BasquePig, - 'DanishPig': DanishPig, - } - } - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ], - 'oneOf': [ - BasquePig, - DanishPig, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Pig': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.basque_pig import BasquePig -from petstore_api.model.danish_pig import DanishPig diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/player.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/player.py deleted file mode 100644 index 99e382ec64..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/player.py +++ /dev/null @@ -1,104 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Player( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - a model that includes a self reference this forces properties and additionalProperties to be lazy loaded in python models because the Player class has not fully loaded when defining properties - """ - name = StrSchema - - @classmethod - @property - def enemyPlayer(cls) -> typing.Type['Player']: - return Player - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - name: typing.Union[name, Unset] = unset, - enemyPlayer: typing.Union['Player', Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Player': - return super().__new__( - cls, - *args, - name=name, - enemyPlayer=enemyPlayer, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/quadrilateral.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/quadrilateral.py deleted file mode 100644 index ac2bba6417..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/quadrilateral.py +++ /dev/null @@ -1,128 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Quadrilateral( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _discriminator(cls): - return { - 'quadrilateralType': { - 'ComplexQuadrilateral': ComplexQuadrilateral, - 'SimpleQuadrilateral': SimpleQuadrilateral, - } - } - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ], - 'oneOf': [ - SimpleQuadrilateral, - ComplexQuadrilateral, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Quadrilateral': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral -from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/quadrilateral_interface.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/quadrilateral_interface.py deleted file mode 100644 index bd28482b08..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/quadrilateral_interface.py +++ /dev/null @@ -1,115 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class QuadrilateralInterface( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'shapeType', - 'quadrilateralType', - )) - - - class shapeType( - _SchemaEnumMaker( - enum_value_to_name={ - "Quadrilateral": "QUADRILATERAL", - } - ), - StrSchema - ): - - @classmethod - @property - def QUADRILATERAL(cls): - return cls("Quadrilateral") - quadrilateralType = StrSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - shapeType: shapeType, - quadrilateralType: quadrilateralType, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'QuadrilateralInterface': - return super().__new__( - cls, - *args, - shapeType=shapeType, - quadrilateralType=quadrilateralType, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/read_only_first.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/read_only_first.py deleted file mode 100644 index 496b72a052..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/read_only_first.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ReadOnlyFirst( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - bar = StrSchema - baz = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - bar: typing.Union[bar, Unset] = unset, - baz: typing.Union[baz, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ReadOnlyFirst': - return super().__new__( - cls, - *args, - bar=bar, - baz=baz, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/scalene_triangle.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/scalene_triangle.py deleted file mode 100644 index 8f521da249..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/scalene_triangle.py +++ /dev/null @@ -1,153 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ScaleneTriangle( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_1( - DictSchema - ): - - - class triangleType( - _SchemaEnumMaker( - enum_value_to_name={ - "ScaleneTriangle": "SCALENETRIANGLE", - } - ), - StrSchema - ): - - @classmethod - @property - def SCALENETRIANGLE(cls): - return cls("ScaleneTriangle") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - triangleType: typing.Union[triangleType, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - triangleType=triangleType, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - TriangleInterface, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ScaleneTriangle': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/shape.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/shape.py deleted file mode 100644 index c14b212935..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/shape.py +++ /dev/null @@ -1,128 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Shape( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _discriminator(cls): - return { - 'shapeType': { - 'Quadrilateral': Quadrilateral, - 'Triangle': Triangle, - } - } - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ], - 'oneOf': [ - Triangle, - Quadrilateral, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Shape': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.quadrilateral import Quadrilateral -from petstore_api.model.triangle import Triangle diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/shape_or_null.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/shape_or_null.py deleted file mode 100644 index 71049a6314..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/shape_or_null.py +++ /dev/null @@ -1,132 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class ShapeOrNull( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. - """ - - @classmethod - @property - def _discriminator(cls): - return { - 'shapeType': { - 'Quadrilateral': Quadrilateral, - 'Triangle': Triangle, - } - } - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - oneOf_0 = NoneSchema - return { - 'allOf': [ - ], - 'oneOf': [ - oneOf_0, - Triangle, - Quadrilateral, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'ShapeOrNull': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.quadrilateral import Quadrilateral -from petstore_api.model.triangle import Triangle diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/simple_quadrilateral.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/simple_quadrilateral.py deleted file mode 100644 index 0d65abab0a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/simple_quadrilateral.py +++ /dev/null @@ -1,153 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class SimpleQuadrilateral( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - - - class allOf_1( - DictSchema - ): - - - class quadrilateralType( - _SchemaEnumMaker( - enum_value_to_name={ - "SimpleQuadrilateral": "SIMPLEQUADRILATERAL", - } - ), - StrSchema - ): - - @classmethod - @property - def SIMPLEQUADRILATERAL(cls): - return cls("SimpleQuadrilateral") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - quadrilateralType: typing.Union[quadrilateralType, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'allOf_1': - return super().__new__( - cls, - *args, - quadrilateralType=quadrilateralType, - _configuration=_configuration, - **kwargs, - ) - return { - 'allOf': [ - QuadrilateralInterface, - allOf_1, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SimpleQuadrilateral': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.quadrilateral_interface import QuadrilateralInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/some_object.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/some_object.py deleted file mode 100644 index d7a7460969..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/some_object.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class SomeObject( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ObjectInterface, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SomeObject': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.object_interface import ObjectInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/special_model_name.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/special_model_name.py deleted file mode 100644 index 696e59a4e4..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/special_model_name.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class SpecialModelName( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - model with an invalid class name for python - """ - a = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - a: typing.Union[a, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'SpecialModelName': - return super().__new__( - cls, - *args, - a=a, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string.py deleted file mode 100644 index f3dc03700e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) -String = StrSchema diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_boolean_map.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_boolean_map.py deleted file mode 100644 index 1ef5b11d74..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_boolean_map.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class StringBooleanMap( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _additional_properties = BoolSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'StringBooleanMap': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_enum.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_enum.py deleted file mode 100644 index 4f23fa3c0d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_enum.py +++ /dev/null @@ -1,138 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class StringEnum( - _SchemaTypeChecker(typing.Union[NoneClass, str, ]), - _SchemaEnumMaker( - enum_value_to_name={ - NoneClass.NONE: "NONE", - "placed": "PLACED", - "approved": "APPROVED", - "delivered": "DELIVERED", - "single quoted": "SINGLE_QUOTED", - "multiple\nlines": "MULTIPLE_LINES", - "double quote \n with newline": "DOUBLE_QUOTE_WITH_NEWLINE", - } - ), - StrBase, - NoneBase, - Schema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def NONE(cls): - return cls(None) - - @classmethod - @property - def PLACED(cls): - return cls("placed") - - @classmethod - @property - def APPROVED(cls): - return cls("approved") - - @classmethod - @property - def DELIVERED(cls): - return cls("delivered") - - @classmethod - @property - def SINGLE_QUOTED(cls): - return cls("single quoted") - - @classmethod - @property - def MULTIPLE_LINES(cls): - return cls("multiple\nlines") - - @classmethod - @property - def DOUBLE_QUOTE_WITH_NEWLINE(cls): - return cls("double quote \n with newline") - - def __new__( - cls, - *args: typing.Union[str, None, ], - _configuration: typing.Optional[Configuration] = None, - ) -> 'StringEnum': - return super().__new__( - cls, - *args, - _configuration=_configuration, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_enum_with_default_value.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_enum_with_default_value.py deleted file mode 100644 index 519bf0b4b5..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_enum_with_default_value.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class StringEnumWithDefaultValue( - _SchemaEnumMaker( - enum_value_to_name={ - "placed": "PLACED", - "approved": "APPROVED", - "delivered": "DELIVERED", - } - ), - StrSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def PLACED(cls): - return cls("placed") - - @classmethod - @property - def APPROVED(cls): - return cls("approved") - - @classmethod - @property - def DELIVERED(cls): - return cls("delivered") diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_with_validation.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_with_validation.py deleted file mode 100644 index 9b41e07bf0..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_with_validation.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class StringWithValidation( - _SchemaValidator( - min_length=7, - ), - StrSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/tag.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/tag.py deleted file mode 100644 index f9fbfb67d3..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/tag.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Tag( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - id = Int64Schema - name = StrSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - id: typing.Union[id, Unset] = unset, - name: typing.Union[name, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Tag': - return super().__new__( - cls, - *args, - id=id, - name=name, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/triangle.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/triangle.py deleted file mode 100644 index 7686cdd34c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/triangle.py +++ /dev/null @@ -1,131 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Triangle( - ComposedSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - @classmethod - @property - def _discriminator(cls): - return { - 'triangleType': { - 'EquilateralTriangle': EquilateralTriangle, - 'IsoscelesTriangle': IsoscelesTriangle, - 'ScaleneTriangle': ScaleneTriangle, - } - } - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [ - ], - 'oneOf': [ - EquilateralTriangle, - IsoscelesTriangle, - ScaleneTriangle, - ], - 'anyOf': [ - ], - 'not': - None - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Triangle': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - -from petstore_api.model.equilateral_triangle import EquilateralTriangle -from petstore_api.model.isosceles_triangle import IsoscelesTriangle -from petstore_api.model.scalene_triangle import ScaleneTriangle diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/triangle_interface.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/triangle_interface.py deleted file mode 100644 index 07fae72e4e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/triangle_interface.py +++ /dev/null @@ -1,115 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class TriangleInterface( - AnyTypeSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'shapeType', - 'triangleType', - )) - - - class shapeType( - _SchemaEnumMaker( - enum_value_to_name={ - "Triangle": "TRIANGLE", - } - ), - StrSchema - ): - - @classmethod - @property - def TRIANGLE(cls): - return cls("Triangle") - triangleType = StrSchema - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - shapeType: shapeType, - triangleType: triangleType, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'TriangleInterface': - return super().__new__( - cls, - *args, - shapeType=shapeType, - triangleType=triangleType, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/user.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/user.py deleted file mode 100644 index d640593bbd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/user.py +++ /dev/null @@ -1,191 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class User( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - id = Int64Schema - username = StrSchema - firstName = StrSchema - lastName = StrSchema - email = StrSchema - password = StrSchema - phone = StrSchema - userStatus = Int32Schema - objectWithNoDeclaredProps = DictSchema - - - class objectWithNoDeclaredPropsNullable( - _SchemaTypeChecker(typing.Union[frozendict, NoneClass, ]), - DictBase, - NoneBase, - Schema - ): - - def __new__( - cls, - *args: typing.Union[dict, frozendict, None, ], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'objectWithNoDeclaredPropsNullable': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - anyTypeProp = AnyTypeSchema - - - class anyTypeExceptNullProp( - ComposedSchema - ): - - @classmethod - @property - @functools.cache - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - NotSchema = NoneSchema - return { - 'allOf': [ - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': - NotSchema - } - - def __new__( - cls, - *args: typing.Union[dict, frozendict, str, date, datetime, int, float, decimal.Decimal, None, list, tuple, bytes], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'anyTypeExceptNullProp': - return super().__new__( - cls, - *args, - _configuration=_configuration, - **kwargs, - ) - anyTypePropNullable = AnyTypeSchema - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - id: typing.Union[id, Unset] = unset, - username: typing.Union[username, Unset] = unset, - firstName: typing.Union[firstName, Unset] = unset, - lastName: typing.Union[lastName, Unset] = unset, - email: typing.Union[email, Unset] = unset, - password: typing.Union[password, Unset] = unset, - phone: typing.Union[phone, Unset] = unset, - userStatus: typing.Union[userStatus, Unset] = unset, - objectWithNoDeclaredProps: typing.Union[objectWithNoDeclaredProps, Unset] = unset, - objectWithNoDeclaredPropsNullable: typing.Union[objectWithNoDeclaredPropsNullable, Unset] = unset, - anyTypeProp: typing.Union[anyTypeProp, Unset] = unset, - anyTypeExceptNullProp: typing.Union[anyTypeExceptNullProp, Unset] = unset, - anyTypePropNullable: typing.Union[anyTypePropNullable, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'User': - return super().__new__( - cls, - *args, - id=id, - username=username, - firstName=firstName, - lastName=lastName, - email=email, - password=password, - phone=phone, - userStatus=userStatus, - objectWithNoDeclaredProps=objectWithNoDeclaredProps, - objectWithNoDeclaredPropsNullable=objectWithNoDeclaredPropsNullable, - anyTypeProp=anyTypeProp, - anyTypeExceptNullProp=anyTypeExceptNullProp, - anyTypePropNullable=anyTypePropNullable, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/uuid_string.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/uuid_string.py deleted file mode 100644 index c80979f32f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/uuid_string.py +++ /dev/null @@ -1,82 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class UUIDString( - _SchemaValidator( - min_length=1, - ), - UUIDSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/whale.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/whale.py deleted file mode 100644 index 4bcb2f0e3b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/whale.py +++ /dev/null @@ -1,118 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Whale( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'className', - )) - hasBaleen = BoolSchema - hasTeeth = BoolSchema - - - class className( - _SchemaEnumMaker( - enum_value_to_name={ - "whale": "WHALE", - } - ), - StrSchema - ): - - @classmethod - @property - def WHALE(cls): - return cls("whale") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - className: className, - hasBaleen: typing.Union[hasBaleen, Unset] = unset, - hasTeeth: typing.Union[hasTeeth, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Whale': - return super().__new__( - cls, - *args, - className=className, - hasBaleen=hasBaleen, - hasTeeth=hasTeeth, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/zebra.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/zebra.py deleted file mode 100644 index 51220d5653..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/zebra.py +++ /dev/null @@ -1,141 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import re # noqa: F401 -import sys # noqa: F401 -import typing # noqa: F401 -import functools # noqa: F401 - -from frozendict import frozendict # noqa: F401 - -import decimal # noqa: F401 -from datetime import date, datetime # noqa: F401 -from frozendict import frozendict # noqa: F401 - -from petstore_api.schemas import ( # noqa: F401 - AnyTypeSchema, - ComposedSchema, - DictSchema, - ListSchema, - StrSchema, - IntSchema, - Int32Schema, - Int64Schema, - Float32Schema, - Float64Schema, - NumberSchema, - UUIDSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - BoolSchema, - BinarySchema, - NoneSchema, - none_type, - Configuration, - Unset, - unset, - ComposedBase, - ListBase, - DictBase, - NoneBase, - StrBase, - IntBase, - Int32Base, - Int64Base, - Float32Base, - Float64Base, - NumberBase, - UUIDBase, - DateBase, - DateTimeBase, - BoolBase, - BinaryBase, - Schema, - NoneClass, - BoolClass, - _SchemaValidator, - _SchemaTypeChecker, - _SchemaEnumMaker -) - - -class Zebra( - DictSchema -): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - _required_property_names = set(( - 'className', - )) - - - class type( - _SchemaEnumMaker( - enum_value_to_name={ - "plains": "PLAINS", - "mountain": "MOUNTAIN", - "grevys": "GREVYS", - } - ), - StrSchema - ): - - @classmethod - @property - def PLAINS(cls): - return cls("plains") - - @classmethod - @property - def MOUNTAIN(cls): - return cls("mountain") - - @classmethod - @property - def GREVYS(cls): - return cls("grevys") - - - class className( - _SchemaEnumMaker( - enum_value_to_name={ - "zebra": "ZEBRA", - } - ), - StrSchema - ): - - @classmethod - @property - def ZEBRA(cls): - return cls("zebra") - - - def __new__( - cls, - *args: typing.Union[dict, frozendict, ], - className: className, - type: typing.Union[type, Unset] = unset, - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Type[Schema], - ) -> 'Zebra': - return super().__new__( - cls, - *args, - className=className, - type=type, - _configuration=_configuration, - **kwargs, - ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/__init__.py deleted file mode 100644 index 48f6957f02..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/__init__.py +++ /dev/null @@ -1,124 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -# import all models into this package -# if you have many models here with many references from one model to another this may -# raise a RecursionError -# to avoid this, import only the models that you directly need like: -# from from petstore_api.model.pet import Pet -# or import this package, but before doing it, use: -# import sys -# sys.setrecursionlimit(n) - -from petstore_api.model.additional_properties_class import AdditionalPropertiesClass -from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums -from petstore_api.model.address import Address -from petstore_api.model.animal import Animal -from petstore_api.model.animal_farm import AnimalFarm -from petstore_api.model.any_type_not_string import AnyTypeNotString -from petstore_api.model.api_response import ApiResponse -from petstore_api.model.apple import Apple -from petstore_api.model.apple_req import AppleReq -from petstore_api.model.array_holding_any_type import ArrayHoldingAnyType -from petstore_api.model.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly -from petstore_api.model.array_of_enums import ArrayOfEnums -from petstore_api.model.array_of_number_only import ArrayOfNumberOnly -from petstore_api.model.array_test import ArrayTest -from petstore_api.model.array_with_validations_in_items import ArrayWithValidationsInItems -from petstore_api.model.banana import Banana -from petstore_api.model.banana_req import BananaReq -from petstore_api.model.bar import Bar -from petstore_api.model.basque_pig import BasquePig -from petstore_api.model.boolean import Boolean -from petstore_api.model.boolean_enum import BooleanEnum -from petstore_api.model.capitalization import Capitalization -from petstore_api.model.cat import Cat -from petstore_api.model.category import Category -from petstore_api.model.child_cat import ChildCat -from petstore_api.model.class_model import ClassModel -from petstore_api.model.client import Client -from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral -from petstore_api.model.composed_any_of_different_types_no_validations import ComposedAnyOfDifferentTypesNoValidations -from petstore_api.model.composed_array import ComposedArray -from petstore_api.model.composed_bool import ComposedBool -from petstore_api.model.composed_none import ComposedNone -from petstore_api.model.composed_number import ComposedNumber -from petstore_api.model.composed_object import ComposedObject -from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes -from petstore_api.model.composed_string import ComposedString -from petstore_api.model.currency import Currency -from petstore_api.model.danish_pig import DanishPig -from petstore_api.model.date_time_test import DateTimeTest -from petstore_api.model.date_time_with_validations import DateTimeWithValidations -from petstore_api.model.date_with_validations import DateWithValidations -from petstore_api.model.decimal_payload import DecimalPayload -from petstore_api.model.dog import Dog -from petstore_api.model.drawing import Drawing -from petstore_api.model.enum_arrays import EnumArrays -from petstore_api.model.enum_class import EnumClass -from petstore_api.model.enum_test import EnumTest -from petstore_api.model.equilateral_triangle import EquilateralTriangle -from petstore_api.model.file import File -from petstore_api.model.file_schema_test_class import FileSchemaTestClass -from petstore_api.model.foo import Foo -from petstore_api.model.format_test import FormatTest -from petstore_api.model.fruit import Fruit -from petstore_api.model.fruit_req import FruitReq -from petstore_api.model.gm_fruit import GmFruit -from petstore_api.model.grandparent_animal import GrandparentAnimal -from petstore_api.model.has_only_read_only import HasOnlyReadOnly -from petstore_api.model.health_check_result import HealthCheckResult -from petstore_api.model.integer_enum import IntegerEnum -from petstore_api.model.integer_enum_big import IntegerEnumBig -from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue -from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue -from petstore_api.model.integer_max10 import IntegerMax10 -from petstore_api.model.integer_min15 import IntegerMin15 -from petstore_api.model.isosceles_triangle import IsoscelesTriangle -from petstore_api.model.mammal import Mammal -from petstore_api.model.map_test import MapTest -from petstore_api.model.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass -from petstore_api.model.model200_response import Model200Response -from petstore_api.model.model_return import ModelReturn -from petstore_api.model.money import Money -from petstore_api.model.name import Name -from petstore_api.model.no_additional_properties import NoAdditionalProperties -from petstore_api.model.nullable_class import NullableClass -from petstore_api.model.nullable_shape import NullableShape -from petstore_api.model.nullable_string import NullableString -from petstore_api.model.number import Number -from petstore_api.model.number_only import NumberOnly -from petstore_api.model.number_with_validations import NumberWithValidations -from petstore_api.model.object_interface import ObjectInterface -from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps -from petstore_api.model.object_with_decimal_properties import ObjectWithDecimalProperties -from petstore_api.model.object_with_difficultly_named_props import ObjectWithDifficultlyNamedProps -from petstore_api.model.object_with_inline_composition_property import ObjectWithInlineCompositionProperty -from petstore_api.model.object_with_validations import ObjectWithValidations -from petstore_api.model.order import Order -from petstore_api.model.parent_pet import ParentPet -from petstore_api.model.pet import Pet -from petstore_api.model.pig import Pig -from petstore_api.model.player import Player -from petstore_api.model.quadrilateral import Quadrilateral -from petstore_api.model.quadrilateral_interface import QuadrilateralInterface -from petstore_api.model.read_only_first import ReadOnlyFirst -from petstore_api.model.scalene_triangle import ScaleneTriangle -from petstore_api.model.shape import Shape -from petstore_api.model.shape_or_null import ShapeOrNull -from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral -from petstore_api.model.some_object import SomeObject -from petstore_api.model.special_model_name import SpecialModelName -from petstore_api.model.string import String -from petstore_api.model.string_boolean_map import StringBooleanMap -from petstore_api.model.string_enum import StringEnum -from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue -from petstore_api.model.string_with_validation import StringWithValidation -from petstore_api.model.tag import Tag -from petstore_api.model.triangle import Triangle -from petstore_api.model.triangle_interface import TriangleInterface -from petstore_api.model.uuid_string import UUIDString -from petstore_api.model.user import User -from petstore_api.model.whale import Whale -from petstore_api.model.zebra import Zebra diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/rest.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/rest.py deleted file mode 100644 index 40e35989f9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/rest.py +++ /dev/null @@ -1,253 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import logging -import ssl -from urllib.parse import urlencode -import typing - -import certifi -import urllib3 -from urllib3._collections import HTTPHeaderDict - -from petstore_api.exceptions import ApiException, ApiValueError - - -logger = logging.getLogger(__name__) - - -class RESTClientObject(object): - - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert - else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 - - if configuration.retries is not None: - addition_pool_args['retries'] = configuration.retries - - if configuration.socket_options is not None: - addition_pool_args['socket_options'] = configuration.socket_options - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request( - self, - method: str, - url: str, - headers: typing.Optional[HTTPHeaderDict] = None, - fields: typing.Optional[typing.Tuple[typing.Tuple[str, typing.Any], ...]] = None, - body: typing.Optional[typing.Union[str, bytes]] = None, - stream: bool = False, - timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, - ) -> urllib3.HTTPResponse: - """Perform requests. - - :param method: http request method - :param url: http request url - :param headers: http request headers - :param body: request body, for other types - :param fields: request parameters for - `application/x-www-form-urlencoded` - or `multipart/form-data` - :param stream: if True, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is False. - :param timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] - - if fields and body: - raise ApiValueError( - "body parameter cannot be used with fields parameter." - ) - - fields = fields or {} - headers = headers or {} - - if timeout: - if isinstance(timeout, (int, float)): # noqa: E501,F821 - timeout = urllib3.Timeout(total=timeout) - elif (isinstance(timeout, tuple) and - len(timeout) == 2): - timeout = urllib3.Timeout(connect=timeout[0], read=timeout[1]) - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - if 'Content-Type' not in headers and body is None: - r = self.pool_manager.request( - method, - url, - preload_content=not stream, - timeout=timeout, - headers=headers - ) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 - r = self.pool_manager.request( - method, url, - fields=fields, - encode_multipart=False, - preload_content=not stream, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers['Content-Type'] - r = self.pool_manager.request( - method, url, - fields=fields, - encode_multipart=True, - preload_content=not stream, - timeout=timeout, - headers=headers) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form - elif isinstance(body, str) or isinstance(body, bytes): - request_body = body - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=not stream, - timeout=timeout, - headers=headers) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request(method, url, - preload_content=not stream, - timeout=timeout, - headers=headers) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if not stream: - # log response body - logger.debug("response body: %s", r.data) - - return r - - def GET(self, url, headers=None, stream=False, - timeout=None, fields=None) -> urllib3.HTTPResponse: - return self.request("GET", url, - headers=headers, - stream=stream, - timeout=timeout, - fields=fields) - - def HEAD(self, url, headers=None, stream=False, - timeout=None, fields=None) -> urllib3.HTTPResponse: - return self.request("HEAD", url, - headers=headers, - stream=stream, - timeout=timeout, - fields=fields) - - def OPTIONS(self, url, headers=None, - body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: - return self.request("OPTIONS", url, - headers=headers, - stream=stream, - timeout=timeout, - body=body, fields=fields) - - def DELETE(self, url, headers=None, body=None, - stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: - return self.request("DELETE", url, - headers=headers, - stream=stream, - timeout=timeout, - body=body, fields=fields) - - def POST(self, url, headers=None, - body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: - return self.request("POST", url, - headers=headers, - stream=stream, - timeout=timeout, - body=body, fields=fields) - - def PUT(self, url, headers=None, - body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: - return self.request("PUT", url, - headers=headers, - stream=stream, - timeout=timeout, - body=body, fields=fields) - - def PATCH(self, url, headers=None, - body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: - return self.request("PATCH", url, - headers=headers, - stream=stream, - timeout=timeout, - body=body, fields=fields) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/schemas.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/schemas.py deleted file mode 100644 index 20e903d493..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/schemas.py +++ /dev/null @@ -1,2158 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from collections import defaultdict -from datetime import date, datetime, timedelta # noqa: F401 -import functools -import decimal -import io -import os -import re -import tempfile -import typing -import uuid - -from dateutil.parser.isoparser import isoparser, _takes_ascii -from frozendict import frozendict - -from petstore_api.exceptions import ( - ApiTypeError, - ApiValueError, -) -from petstore_api.configuration import ( - Configuration, -) - - -class Unset(object): - """ - An instance of this class is set as the default value for object type(dict) properties that are optional - When a property has an unset value, that property will not be assigned in the dict - """ - pass - -unset = Unset() - -none_type = type(None) -file_type = io.IOBase - - -class FileIO(io.FileIO): - """ - A class for storing files - Note: this class is not immutable - """ - - def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader]): - if isinstance(arg, (io.FileIO, io.BufferedReader)): - if arg.closed: - raise ApiValueError('Invalid file state; file is closed and must be open') - arg.close() - inst = super(FileIO, cls).__new__(cls, arg.name) - super(FileIO, inst).__init__(arg.name) - return inst - raise ApiValueError('FileIO must be passed arg which contains the open file') - - def __init__(self, arg: typing.Union[io.FileIO, io.BufferedReader]): - pass - - -def update(d: dict, u: dict): - """ - Adds u to d - Where each dict is defaultdict(set) - """ - if not u: - return d - for k, v in u.items(): - if not v: - continue - if k not in d: - d[k] = v - else: - d[k] = d[k] | v - - -class ValidationMetadata(frozendict): - """ - A class storing metadata that is needed to validate OpenApi Schema payloads - """ - def __new__( - cls, - path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), - from_server: bool = False, - configuration: typing.Optional[Configuration] = None, - seen_classes: typing.FrozenSet[typing.Type] = frozenset(), - validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set['Schema']] = frozendict() - ): - """ - Args: - path_to_item: the path to the current data being instantiated. - For {'a': [1]} if the code is handling, 1, then the path is ('args[0]', 'a', 0) - This changes from location to location - from_server: whether or not this data came form the server - True when receiving server data - False when instantiating model with client side data not form the server - This does not change from location to location - configuration: the Configuration instance to use - This is needed because in Configuration: - - one can disable validation checking - This does not change from location to location - seen_classes: when deserializing data that matches multiple schemas, this is used to store - the schemas that have been traversed. This is used to stop processing when a cycle is seen. - This changes from location to location - validated_path_to_schemas: stores the already validated schema classes for a given path location - This does not change from location to location - """ - return super().__new__( - cls, - path_to_item=path_to_item, - from_server=from_server, - configuration=configuration, - seen_classes=seen_classes, - validated_path_to_schemas=validated_path_to_schemas - ) - - def validation_ran_earlier(self, cls: type) -> bool: - validated_schemas = self.validated_path_to_schemas.get(self.path_to_item, set()) - validation_ran_earlier = validated_schemas and cls in validated_schemas - if validation_ran_earlier: - return True - if cls in self.seen_classes: - return True - return False - - @property - def path_to_item(self) -> typing.Tuple[typing.Union[str, int], ...]: - return self.get('path_to_item') - - @property - def from_server(self) -> bool: - return self.get('from_server') - - @property - def configuration(self) -> typing.Optional[Configuration]: - return self.get('configuration') - - @property - def seen_classes(self) -> typing.FrozenSet[typing.Type]: - return self.get('seen_classes') - - @property - def validated_path_to_schemas(self) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set['Schema']]: - return self.get('validated_path_to_schemas') - - -class ValidatorBase: - @staticmethod - def __is_json_validation_enabled(schema_keyword, configuration=None): - """Returns true if JSON schema validation is enabled for the specified - validation keyword. This can be used to skip JSON schema structural validation - as requested in the configuration. - - Args: - schema_keyword (string): the name of a JSON schema validation keyword. - configuration (Configuration): the configuration class. - """ - - return (configuration is None or - not hasattr(configuration, '_disabled_client_side_validations') or - schema_keyword not in configuration._disabled_client_side_validations) - - @staticmethod - def __raise_validation_error_message(value, constraint_msg, constraint_value, path_to_item, additional_txt=""): - raise ApiValueError( - "Invalid value `{value}`, {constraint_msg} `{constraint_value}`{additional_txt} at {path_to_item}".format( - value=value, - constraint_msg=constraint_msg, - constraint_value=constraint_value, - additional_txt=additional_txt, - path_to_item=path_to_item, - ) - ) - - @classmethod - def __check_str_validations(cls, - validations, input_values, - validation_metadata: ValidationMetadata): - - if (cls.__is_json_validation_enabled('maxLength', validation_metadata.configuration) and - 'max_length' in validations and - len(input_values) > validations['max_length']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="length must be less than or equal to", - constraint_value=validations['max_length'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minLength', validation_metadata.configuration) and - 'min_length' in validations and - len(input_values) < validations['min_length']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="length must be greater than or equal to", - constraint_value=validations['min_length'], - path_to_item=validation_metadata.path_to_item - ) - - checked_value = input_values - if (cls.__is_json_validation_enabled('pattern', validation_metadata.configuration) and - 'regex' in validations): - for regex_dict in validations['regex']: - flags = regex_dict.get('flags', 0) - if not re.search(regex_dict['pattern'], checked_value, flags=flags): - if flags != 0: - # Don't print the regex flags if the flags are not - # specified in the OAS document. - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must match regular expression", - constraint_value=regex_dict['pattern'], - path_to_item=validation_metadata.path_to_item, - additional_txt=" with flags=`{}`".format(flags) - ) - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must match regular expression", - constraint_value=regex_dict['pattern'], - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def __check_tuple_validations( - cls, validations, input_values, - validation_metadata: ValidationMetadata): - - if (cls.__is_json_validation_enabled('maxItems', validation_metadata.configuration) and - 'max_items' in validations and - len(input_values) > validations['max_items']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of items must be less than or equal to", - constraint_value=validations['max_items'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minItems', validation_metadata.configuration) and - 'min_items' in validations and - len(input_values) < validations['min_items']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of items must be greater than or equal to", - constraint_value=validations['min_items'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('uniqueItems', validation_metadata.configuration) and - 'unique_items' in validations and validations['unique_items'] and input_values): - unique_items = set(input_values) - if len(input_values) > len(unique_items): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="duplicate items were found, and the tuple must not contain duplicates because", - constraint_value='unique_items==True', - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def __check_dict_validations( - cls, validations, input_values, - validation_metadata: ValidationMetadata): - - if (cls.__is_json_validation_enabled('maxProperties', validation_metadata.configuration) and - 'max_properties' in validations and - len(input_values) > validations['max_properties']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of properties must be less than or equal to", - constraint_value=validations['max_properties'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minProperties', validation_metadata.configuration) and - 'min_properties' in validations and - len(input_values) < validations['min_properties']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="number of properties must be greater than or equal to", - constraint_value=validations['min_properties'], - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def __check_numeric_validations( - cls, validations, input_values, - validation_metadata: ValidationMetadata): - - if cls.__is_json_validation_enabled('multipleOf', - validation_metadata.configuration) and 'multiple_of' in validations: - multiple_of_value = validations['multiple_of'] - if (isinstance(input_values, decimal.Decimal) and - not (float(input_values) / multiple_of_value).is_integer() - ): - # Note 'multipleOf' will be as good as the floating point arithmetic. - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="value must be a multiple of", - constraint_value=multiple_of_value, - path_to_item=validation_metadata.path_to_item - ) - - checking_max_or_min_values = {'exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', - 'inclusive_minimum'}.isdisjoint(validations) is False - if not checking_max_or_min_values: - return - max_val = input_values - min_val = input_values - - if (cls.__is_json_validation_enabled('exclusiveMaximum', validation_metadata.configuration) and - 'exclusive_maximum' in validations and - max_val >= validations['exclusive_maximum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value less than", - constraint_value=validations['exclusive_maximum'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('maximum', validation_metadata.configuration) and - 'inclusive_maximum' in validations and - max_val > validations['inclusive_maximum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value less than or equal to", - constraint_value=validations['inclusive_maximum'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('exclusiveMinimum', validation_metadata.configuration) and - 'exclusive_minimum' in validations and - min_val <= validations['exclusive_minimum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value greater than", - constraint_value=validations['exclusive_maximum'], - path_to_item=validation_metadata.path_to_item - ) - - if (cls.__is_json_validation_enabled('minimum', validation_metadata.configuration) and - 'inclusive_minimum' in validations and - min_val < validations['inclusive_minimum']): - cls.__raise_validation_error_message( - value=input_values, - constraint_msg="must be a value greater than or equal to", - constraint_value=validations['inclusive_minimum'], - path_to_item=validation_metadata.path_to_item - ) - - @classmethod - def _check_validations_for_types( - cls, - validations, - input_values, - validation_metadata: ValidationMetadata - ): - if isinstance(input_values, str): - cls.__check_str_validations(validations, input_values, validation_metadata) - elif isinstance(input_values, tuple): - cls.__check_tuple_validations(validations, input_values, validation_metadata) - elif isinstance(input_values, frozendict): - cls.__check_dict_validations(validations, input_values, validation_metadata) - elif isinstance(input_values, decimal.Decimal): - cls.__check_numeric_validations(validations, input_values, validation_metadata) - - -class Singleton: - """ - Enums and singletons are the same - The same instance is returned for a given key of (cls, arg) - """ - _instances = {} - - def __new__(cls, arg: typing.Any, **kwargs): - key = (cls, arg) - if key not in cls._instances: - if arg in {None, True, False}: - inst = super().__new__(cls) - cls._instances[key] = inst - elif isinstance(arg, BoolClass): - inst = super().__new__(cls) - cls._instances[key] = inst - elif isinstance(arg, NoneClass): - inst = super().__new__(cls) - cls._instances[key] = inst - else: - cls._instances[key] = super().__new__(cls, arg) - return cls._instances[key] - - def __repr__(self): - if isinstance(self, NoneClass): - return f'<{self.__class__.__name__}: None>' - elif isinstance(self, BoolClass): - if bool(self): - return f'<{self.__class__.__name__}: True>' - return f'<{self.__class__.__name__}: False>' - return f'<{self.__class__.__name__}: {super().__repr__()}>' - - -class NoneClass(Singleton): - @classmethod - @property - def NONE(cls): - return cls(None) - - def __bool__(self) -> bool: - return False - - -class BoolClass(Singleton): - @classmethod - @property - def TRUE(cls): - return cls(True) - - @classmethod - @property - def FALSE(cls): - return cls(False) - - @functools.cache - def __bool__(self) -> bool: - for key, instance in self._instances.items(): - if self is instance: - return bool(key[1]) - raise ValueError('Unable to find the boolean value of this instance') - - -class Validator(typing.Protocol): - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - pass - - -def _SchemaValidator(**validations: typing.Union[str, bool, None, int, float, list[dict[str, typing.Union[str, int, float]]]]) -> Validator: - class SchemaValidator(ValidatorBase): - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - SchemaValidator _validate - Validates that validations pass - """ - cls._check_validations_for_types(validations, arg, validation_metadata) - return super()._validate(arg, validation_metadata) - - return SchemaValidator - - -def _SchemaTypeChecker(union_type_cls: typing.Union[typing.Any]) -> Validator: - if typing.get_origin(union_type_cls) is typing.Union: - union_classes = typing.get_args(union_type_cls) - else: - # note: when a union of a single class is passed in, the union disappears - union_classes = tuple([union_type_cls]) - """ - I want the type hint... union_type_cls - and to use it as a base class but when I do, I get - TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases - """ - class SchemaTypeChecker: - @staticmethod - def __get_valid_classes_phrase(input_classes): - """Returns a string phrase describing what types are allowed""" - all_classes = list(input_classes) - all_classes = sorted(all_classes, key=lambda cls: cls.__name__) - all_class_names = [cls.__name__ for cls in all_classes] - if len(all_class_names) == 1: - return "is {0}".format(all_class_names[0]) - return "is one of [{0}]".format(", ".join(all_class_names)) - - @classmethod - def __type_error_message( - cls, var_value=None, var_name=None, valid_classes=None, key_type=None - ): - """ - Keyword Args: - var_value (any): the variable which has the type_error - var_name (str): the name of the variable which has the typ error - valid_classes (tuple): the accepted classes for current_item's - value - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a tuple - """ - key_or_value = "value" - if key_type: - key_or_value = "key" - valid_classes_phrase = cls.__get_valid_classes_phrase(valid_classes) - msg = "Invalid type. Required {1} type {2} and " "passed type was {3}".format( - var_name, - key_or_value, - valid_classes_phrase, - type(var_value).__name__, - ) - return msg - - @classmethod - def _get_type_error(cls, var_value, path_to_item, valid_classes, key_type=False): - error_msg = cls.__type_error_message( - var_name=path_to_item[-1], - var_value=var_value, - valid_classes=valid_classes, - key_type=key_type, - ) - return ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=valid_classes, - key_type=key_type, - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - SchemaTypeChecker _validate - Validates arg's type - """ - arg_type = type(arg) - if arg_type in union_classes: - return super()._validate(arg, validation_metadata) - raise cls._get_type_error( - arg, - validation_metadata.path_to_item, - union_classes, - key_type=False, - ) - - return SchemaTypeChecker - - -class EnumMakerBase: - pass - - -class EnumMakerInterface(Validator): - @classmethod - @property - def _enum_value_to_name( - cls - ) -> typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]: - pass - - -def _SchemaEnumMaker(enum_value_to_name: typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]) -> EnumMakerInterface: - class SchemaEnumMaker(EnumMakerBase): - @classmethod - @property - def _enum_value_to_name( - cls - ) -> typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]: - pass - try: - super_enum_value_to_name = super()._enum_value_to_name - except AttributeError: - return enum_value_to_name - intersection = dict(enum_value_to_name.items() & super_enum_value_to_name.items()) - return intersection - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - SchemaEnumMaker _validate - Validates that arg is in the enum's allowed values - """ - try: - cls._enum_value_to_name[arg] - except KeyError: - raise ApiValueError("Invalid value {} passed in to {}, {}".format(arg, cls, cls._enum_value_to_name)) - return super()._validate(arg, validation_metadata) - - return SchemaEnumMaker - - -class BoolBase: - def is_true(self) -> bool: - """ - A replacement for x is True - True if the instance is a BoolClass True Singleton - """ - if not issubclass(self.__class__, BoolClass): - return False - return bool(self) - - def is_false(self) -> bool: - """ - A replacement for x is False - True if the instance is a BoolClass False Singleton - """ - if not issubclass(self.__class__, BoolClass): - return False - return bool(self) is False - - -class NoneBase: - def is_none(self) -> bool: - """ - A replacement for x is None - True if the instance is a NoneClass None Singleton - """ - if issubclass(self.__class__, NoneClass): - return True - return False - - -class StrBase: - @property - def as_str(self) -> str: - return self - - @property - def as_date(self) -> date: - raise Exception('not implemented') - - @property - def as_datetime(self) -> datetime: - raise Exception('not implemented') - - @property - def as_decimal(self) -> decimal.Decimal: - raise Exception('not implemented') - - @property - def as_uuid(self) -> uuid.UUID: - raise Exception('not implemented') - - -class UUIDBase(StrBase): - @property - @functools.cache - def as_uuid(self) -> uuid.UUID: - return uuid.UUID(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - uuid.UUID(arg) - return True - except ValueError: - raise ApiValueError( - "Invalid value '{}' for type UUID at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: typing.Optional[ValidationMetadata] = None, - ): - """ - UUIDBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class CustomIsoparser(isoparser): - - @_takes_ascii - def parse_isodatetime(self, dt_str): - components, pos = self._parse_isodate(dt_str) - if len(dt_str) > pos: - if self._sep is None or dt_str[pos:pos + 1] == self._sep: - components += self._parse_isotime(dt_str[pos + 1:]) - else: - raise ValueError('String contains unknown ISO components') - - if len(components) > 3 and components[3] == 24: - components[3] = 0 - return datetime(*components) + timedelta(days=1) - - if len(components) <= 3: - raise ValueError('Value is not a datetime') - - return datetime(*components) - - @_takes_ascii - def parse_isodate(self, datestr): - components, pos = self._parse_isodate(datestr) - - if len(datestr) > pos: - raise ValueError('String contains invalid time components') - - if len(components) > 3: - raise ValueError('String contains invalid time components') - - return date(*components) - - -DEFAULT_ISOPARSER = CustomIsoparser() - - -class DateBase(StrBase): - @property - @functools.cache - def as_date(self) -> date: - return DEFAULT_ISOPARSER.parse_isodate(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - DEFAULT_ISOPARSER.parse_isodate(arg) - return True - except ValueError: - raise ApiValueError( - "Value does not conform to the required ISO-8601 date format. " - "Invalid value '{}' for type date at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: typing.Optional[ValidationMetadata] = None, - ): - """ - DateBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class DateTimeBase: - @property - @functools.cache - def as_datetime(self) -> datetime: - return DEFAULT_ISOPARSER.parse_isodatetime(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - DEFAULT_ISOPARSER.parse_isodatetime(arg) - return True - except ValueError: - raise ApiValueError( - "Value does not conform to the required ISO-8601 datetime format. " - "Invalid value '{}' for type datetime at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - DateTimeBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class DecimalBase(StrBase): - """ - A class for storing decimals that are sent over the wire as strings - These schemas must remain based on StrBase rather than NumberBase - because picking base classes must be deterministic - """ - - @property - @functools.cache - def as_decimal(self) -> decimal.Decimal: - return decimal.Decimal(self) - - @classmethod - def _validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): - if isinstance(arg, str): - try: - decimal.Decimal(arg) - return True - except decimal.InvalidOperation: - raise ApiValueError( - "Value cannot be converted to a decimal. " - "Invalid value '{}' for type decimal at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - DecimalBase _validate - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class NumberBase: - @property - def as_int(self) -> int: - try: - return self._as_int - except AttributeError: - """ - Note: for some numbers like 9.0 they could be represented as an - integer but our code chooses to store them as - >>> Decimal('9.0').as_tuple() - DecimalTuple(sign=0, digits=(9, 0), exponent=-1) - so we can tell that the value came from a float and convert it back to a float - during later serialization - """ - if self.as_tuple().exponent < 0: - # this could be represented as an integer but should be represented as a float - # because that's what it was serialized from - raise ApiValueError(f'{self} is not an integer') - self._as_int = int(self) - return self._as_int - - @property - def as_float(self) -> float: - try: - return self._as_float - except AttributeError: - if self.as_tuple().exponent >= 0: - raise ApiValueError(f'{self} is not an float') - self._as_float = float(self) - return self._as_float - - -class ListBase: - @classmethod - def _validate_items(cls, list_items, validation_metadata: ValidationMetadata): - """ - Ensures that: - - values passed in for items are valid - Exceptions will be raised if: - - invalid arguments were passed in - - Args: - list_items: the input list of items - - Raises: - ApiTypeError - for missing required arguments, or for invalid properties - """ - - # if we have definitions for an items schema, use it - # otherwise accept anything - item_cls = getattr(cls, '_items', AnyTypeSchema) - path_to_schemas = {} - for i, value in enumerate(list_items): - item_validation_metadata = ValidationMetadata( - from_server=validation_metadata.from_server, - configuration=validation_metadata.configuration, - path_to_item=validation_metadata.path_to_item+(i,), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - if item_validation_metadata.validation_ran_earlier(item_cls): - continue - other_path_to_schemas = item_cls._validate( - value, validation_metadata=item_validation_metadata) - update(path_to_schemas, other_path_to_schemas) - return path_to_schemas - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - ListBase _validate - We return dynamic classes of different bases depending upon the inputs - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Returns: - new_cls (type): the new class - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - _path_to_schemas = super()._validate(arg, validation_metadata=validation_metadata) - if not isinstance(arg, tuple): - return _path_to_schemas - updated_vm = ValidationMetadata( - configuration=validation_metadata.configuration, - from_server=validation_metadata.from_server, - path_to_item=validation_metadata.path_to_item, - seen_classes=validation_metadata.seen_classes | frozenset({cls}), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - other_path_to_schemas = cls._validate_items(arg, validation_metadata=updated_vm) - update(_path_to_schemas, other_path_to_schemas) - return _path_to_schemas - - @classmethod - def _get_items( - cls: 'Schema', - arg: typing.List[typing.Any], - path_to_item: typing.Tuple[typing.Union[str, int], ...], - path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] - ): - ''' - ListBase _get_items - ''' - list_items = arg - cast_items = [] - # if we have definitions for an items schema, use it - # otherwise accept anything - - cls_item_cls = getattr(cls, '_items', AnyTypeSchema) - for i, value in enumerate(list_items): - item_path_to_item = path_to_item + (i,) - item_cls = path_to_schemas.get(item_path_to_item) - if item_cls is None: - item_cls = cls_item_cls - - if isinstance(value, item_cls): - cast_items.append(value) - continue - - new_value = item_cls._get_new_instance_without_conversion( - value, - item_path_to_item, - path_to_schemas - ) - cast_items.append(new_value) - - return cast_items - - -class Discriminable: - @classmethod - def _ensure_discriminator_value_present(cls, disc_property_name: str, validation_metadata: ValidationMetadata, *args): - if not args or args and disc_property_name not in args[0]: - # The input data does not contain the discriminator property - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '{}' is missing at path: {}".format(disc_property_name, validation_metadata.path_to_item) - ) - - @classmethod - def _get_discriminated_class(cls, disc_property_name: str, disc_payload_value: str): - """ - Used in schemas with discriminators - """ - if not hasattr(cls, '_discriminator'): - return None - disc = cls._discriminator - if disc_property_name not in disc: - return None - discriminated_cls = disc[disc_property_name].get(disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - elif not hasattr(cls, '_composed_schemas'): - return None - # TODO stop traveling if a cycle is hit - for allof_cls in cls._composed_schemas['allOf']: - discriminated_cls = allof_cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - for oneof_cls in cls._composed_schemas['oneOf']: - discriminated_cls = oneof_cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - for anyof_cls in cls._composed_schemas['anyOf']: - discriminated_cls = anyof_cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) - if discriminated_cls is not None: - return discriminated_cls - return None - - -class DictBase(Discriminable): - # subclass properties - _required_property_names = set() - - @classmethod - def _validate_arg_presence(cls, arg): - """ - Ensures that: - - all required arguments are passed in - - the input variable names are valid - - present in properties or - - accepted because additionalProperties exists - Exceptions will be raised if: - - invalid arguments were passed in - - a var_name is invalid if additionProperties == None and var_name not in _properties - - required properties were not passed in - - Args: - arg: the input dict - - Raises: - ApiTypeError - for missing required arguments, or for invalid properties - """ - seen_required_properties = set() - invalid_arguments = [] - for property_name in arg: - if property_name in cls._required_property_names: - seen_required_properties.add(property_name) - elif property_name in cls._property_names: - continue - elif cls._additional_properties: - continue - else: - invalid_arguments.append(property_name) - missing_required_arguments = list(cls._required_property_names - seen_required_properties) - if missing_required_arguments: - missing_required_arguments.sort() - raise ApiTypeError( - "{} is missing {} required argument{}: {}".format( - cls.__name__, - len(missing_required_arguments), - "s" if len(missing_required_arguments) > 1 else "", - missing_required_arguments - ) - ) - if invalid_arguments: - invalid_arguments.sort() - raise ApiTypeError( - "{} was passed {} invalid argument{}: {}".format( - cls.__name__, - len(invalid_arguments), - "s" if len(invalid_arguments) > 1 else "", - invalid_arguments - ) - ) - - @classmethod - def _validate_args(cls, arg, validation_metadata: ValidationMetadata): - """ - Ensures that: - - values passed in for properties are valid - Exceptions will be raised if: - - invalid arguments were passed in - - Args: - arg: the input dict - - Raises: - ApiTypeError - for missing required arguments, or for invalid properties - """ - path_to_schemas = {} - for property_name, value in arg.items(): - if property_name in cls._required_property_names or property_name in cls._property_names: - schema = getattr(cls, property_name) - elif cls._additional_properties: - schema = cls._additional_properties - else: - raise ApiTypeError('Unable to find schema for value={} in class={} at path_to_item={}'.format( - value, cls, validation_metadata.path_to_item+(property_name,) - )) - arg_validation_metadata = ValidationMetadata( - from_server=validation_metadata.from_server, - configuration=validation_metadata.configuration, - path_to_item=validation_metadata.path_to_item+(property_name,), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - if arg_validation_metadata.validation_ran_earlier(schema): - continue - other_path_to_schemas = schema._validate(value, validation_metadata=arg_validation_metadata) - update(path_to_schemas, other_path_to_schemas) - return path_to_schemas - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - DictBase _validate - We return dynamic classes of different bases depending upon the inputs - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Returns: - new_cls (type): the new class - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - if isinstance(arg, cls): - # an instance of the correct type was passed in - return {} - _path_to_schemas = super()._validate(arg, validation_metadata=validation_metadata) - if not isinstance(arg, frozendict): - return _path_to_schemas - cls._validate_arg_presence(arg) - other_path_to_schemas = cls._validate_args(arg, validation_metadata=validation_metadata) - update(_path_to_schemas, other_path_to_schemas) - try: - _discriminator = cls._discriminator - except AttributeError: - return _path_to_schemas - # discriminator exists - disc_prop_name = list(_discriminator.keys())[0] - cls._ensure_discriminator_value_present(disc_prop_name, validation_metadata, arg) - discriminated_cls = cls._get_discriminated_class( - disc_property_name=disc_prop_name, disc_payload_value=arg[disc_prop_name]) - if discriminated_cls is None: - raise ApiValueError( - "Invalid discriminator value was passed in to {}.{} Only the values {} are allowed at {}".format( - cls.__name__, - disc_prop_name, - list(_discriminator[disc_prop_name].keys()), - validation_metadata.path_to_item + (disc_prop_name,) - ) - ) - updated_vm = ValidationMetadata( - configuration=validation_metadata.configuration, - from_server=validation_metadata.from_server, - path_to_item=validation_metadata.path_to_item, - seen_classes=validation_metadata.seen_classes | frozenset({cls}), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - if updated_vm.validation_ran_earlier(discriminated_cls): - return _path_to_schemas - other_path_to_schemas = discriminated_cls._validate(arg, validation_metadata=updated_vm) - update(_path_to_schemas, other_path_to_schemas) - return _path_to_schemas - - @classmethod - @property - def _additional_properties(cls): - return AnyTypeSchema - - @classmethod - @property - @functools.cache - def _property_names(cls): - property_names = set() - for var_name, var_value in cls.__dict__.items(): - # referenced models are classmethods - is_classmethod = type(var_value) is classmethod - if is_classmethod: - property_names.add(var_name) - continue - is_class = type(var_value) is type - if not is_class: - continue - if not issubclass(var_value, Schema): - continue - if var_name == '_additional_properties': - continue - property_names.add(var_name) - property_names = list(property_names) - property_names.sort() - return tuple(property_names) - - @classmethod - def _get_properties( - cls, - arg: typing.Dict[str, typing.Any], - path_to_item: typing.Tuple[typing.Union[str, int], ...], - path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] - ): - """ - DictBase _get_properties, this is how properties are set - These values already passed validation - """ - dict_items = {} - # if we have definitions for property schemas convert values using it - # otherwise accept anything - - for property_name_js, value in arg.items(): - property_cls = getattr(cls, property_name_js, cls._additional_properties) - property_path_to_item = path_to_item + (property_name_js,) - stored_property_cls = path_to_schemas.get(property_path_to_item) - if stored_property_cls: - property_cls = stored_property_cls - - if isinstance(value, property_cls): - dict_items[property_name_js] = value - continue - - new_value = property_cls._get_new_instance_without_conversion( - value, - property_path_to_item, - path_to_schemas - ) - dict_items[property_name_js] = new_value - return dict_items - - def __setattr__(self, name, value): - if not isinstance(self, FileIO): - raise AttributeError('property setting not supported on immutable instances') - - def __getattr__(self, name): - if isinstance(self, frozendict): - # if an attribute does not exist - try: - return self[name] - except KeyError as ex: - raise AttributeError(str(ex)) - return super().__getattr__(self, name) - - def __getattribute__(self, name): - # if an attribute does exist (for example as a class property but not as an instance method) - try: - return self[name] - except (KeyError, TypeError): - return super().__getattribute__(name) - - -inheritable_primitive_types_set = {decimal.Decimal, str, tuple, frozendict, FileIO, bytes, BoolClass, NoneClass} - - -class Schema: - """ - the base class of all swagger/openapi schemas/models - - ensures that: - - payload passes required validations - - payload is of allowed types - - payload value is an allowed enum value - """ - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - Schema _validate - Runs all schema validation logic and - returns a dynamic class of different bases depending upon the input - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Use cases: - 1. inheritable type: string/decimal.Decimal/frozendict/tuple - 2. singletons: bool/None -> uses the base classes BoolClass/NoneClass - - Required Steps: - 1. verify type of input is valid vs the allowed _types - 2. check validations that are applicable for this type of input - 3. if enums exist, check that the value exists in the enum - - Returns: - path_to_schemas: a map of path to schemas - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - base_class = type(arg) - path_to_schemas = {validation_metadata.path_to_item: set()} - path_to_schemas[validation_metadata.path_to_item].add(cls) - path_to_schemas[validation_metadata.path_to_item].add(base_class) - return path_to_schemas - - @staticmethod - def __process_schema_classes( - schema_classes: typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]] - ): - """ - Processes and mutates schema_classes - If a SomeSchema is a subclass of DictSchema then remove DictSchema because it is already included - """ - if len(schema_classes) < 2: - return - x_schema = schema_type_classes & schema_classes - if not x_schema: - return - x_schema = x_schema.pop() - if any(c is not x_schema and issubclass(c, x_schema) for c in schema_classes): - # needed to not have a mro error in get_new_class - schema_classes.remove(x_schema) - - @classmethod - def __get_new_cls( - cls, - arg, - validation_metadata: ValidationMetadata - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], 'Schema']: - """ - Make a new dynamic class and return an instance of that class - We are making an instance of cls, but instead of making cls - make a new class, new_cls - which includes dynamic bases including cls - return an instance of that new class - - Dict property + List Item Assignment Use cases: - 1. value is NOT an instance of the required schema class - the value is validated by _validate - _validate returns a key value pair - where the key is the path to the item, and the value will be the required manufactured class - made out of the matching schemas - 2. value is an instance of the the correct schema type - the value is NOT validated by _validate, _validate only checks that the instance is of the correct schema type - for this value, _validate does NOT return an entry for it in _path_to_schemas - and in list/dict _get_items,_get_properties the value will be directly assigned - because value is of the correct type, and validation was run earlier when the instance was created - """ - _path_to_schemas = {} - if validation_metadata.validated_path_to_schemas: - update(_path_to_schemas, validation_metadata.validated_path_to_schemas) - if not validation_metadata.validation_ran_earlier(cls): - other_path_to_schemas = cls._validate(arg, validation_metadata=validation_metadata) - update(_path_to_schemas, other_path_to_schemas) - # loop through it make a new class for each entry - # do not modify the returned result because it is cached and we would be modifying the cached value - path_to_schemas = {} - for path, schema_classes in _path_to_schemas.items(): - """ - Use cases - 1. N number of schema classes + enum + type != bool/None, classes in path_to_schemas: tuple/frozendict/str/Decimal/bytes/FileIo - needs Singleton added - 2. N number of schema classes + enum + type == bool/None, classes in path_to_schemas: BoolClass/NoneClass - Singleton already added - 3. N number of schema classes, classes in path_to_schemas: BoolClass/NoneClass/tuple/frozendict/str/Decimal/bytes/FileIo - """ - cls.__process_schema_classes(schema_classes) - enum_schema = any( - hasattr(this_cls, '_enum_value_to_name') for this_cls in schema_classes) - inheritable_primitive_type = schema_classes.intersection(inheritable_primitive_types_set) - chosen_schema_classes = schema_classes - inheritable_primitive_type - suffix = tuple(inheritable_primitive_type) - if enum_schema and suffix[0] not in {NoneClass, BoolClass}: - suffix = (Singleton,) + suffix - - used_classes = tuple(sorted(chosen_schema_classes, key=lambda a_cls: a_cls.__name__)) + suffix - mfg_cls = get_new_class(class_name='DynamicSchema', bases=used_classes) - path_to_schemas[path] = mfg_cls - - return path_to_schemas - - @classmethod - def _get_new_instance_without_conversion( - cls: 'Schema', - arg: typing.Any, - path_to_item: typing.Tuple[typing.Union[str, int], ...], - path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] - ): - # We have a Dynamic class and we are making an instance of it - if issubclass(cls, frozendict): - print(cls.__bases__) - properties = cls._get_properties(arg, path_to_item, path_to_schemas) - return super(Schema, cls).__new__(cls, properties) - elif issubclass(cls, tuple): - items = cls._get_items(arg, path_to_item, path_to_schemas) - return super(Schema, cls).__new__(cls, items) - """ - str = openapi str, date, and datetime - decimal.Decimal = openapi int and float - FileIO = openapi binary type and the user inputs a file - bytes = openapi binary type and the user inputs bytes - """ - return super(Schema, cls).__new__(cls, arg) - - @classmethod - def _from_openapi_data( - cls, - arg: typing.Union[ - str, - date, - datetime, - int, - float, - decimal.Decimal, - bool, - None, - 'Schema', - dict, - frozendict, - tuple, - list, - io.FileIO, - io.BufferedReader, - bytes - ], - _configuration: typing.Optional[Configuration] - ): - """ - Schema _from_openapi_data - """ - from_server = True - validated_path_to_schemas = {} - arg = cast_to_allowed_types(arg, from_server, validated_path_to_schemas) - validation_metadata = ValidationMetadata( - from_server=from_server, configuration=_configuration, validated_path_to_schemas=validated_path_to_schemas) - path_to_schemas = cls.__get_new_cls(arg, validation_metadata) - new_cls = path_to_schemas[validation_metadata.path_to_item] - new_inst = new_cls._get_new_instance_without_conversion( - arg, - validation_metadata.path_to_item, - path_to_schemas - ) - return new_inst - - @staticmethod - def __get_input_dict(*args, **kwargs) -> frozendict: - input_dict = {} - if args and isinstance(args[0], (dict, frozendict)): - input_dict.update(args[0]) - if kwargs: - input_dict.update(kwargs) - return frozendict(input_dict) - - @staticmethod - def __remove_unsets(kwargs): - return {key: val for key, val in kwargs.items() if val is not unset} - - def __new__(cls, *args: typing.Union[dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], _configuration: typing.Optional[Configuration] = None, **kwargs: typing.Union[dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset]): - """ - Schema __new__ - - Args: - args (int/float/decimal.Decimal/str/list/tuple/dict/frozendict/bool/None): the value - kwargs (str, int/float/decimal.Decimal/str/list/tuple/dict/frozendict/bool/None): dict values - _configuration: contains the Configuration that enables json schema validation keywords - like minItems, minLength etc - """ - kwargs = cls.__remove_unsets(kwargs) - if not args and not kwargs: - raise TypeError( - 'No input given. args or kwargs must be given.' - ) - if not kwargs and args and not isinstance(args[0], dict): - arg = args[0] - else: - arg = cls.__get_input_dict(*args, **kwargs) - from_server = False - validated_path_to_schemas = {} - arg = cast_to_allowed_types( - arg, from_server, validated_path_to_schemas) - validation_metadata = ValidationMetadata( - configuration=_configuration, from_server=from_server, validated_path_to_schemas=validated_path_to_schemas) - path_to_schemas = cls.__get_new_cls(arg, validation_metadata) - new_cls = path_to_schemas[validation_metadata.path_to_item] - return new_cls._get_new_instance_without_conversion( - arg, - validation_metadata.path_to_item, - path_to_schemas - ) - - def __init__( - self, - *args: typing.Union[ - dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], - _configuration: typing.Optional[Configuration] = None, - **kwargs: typing.Union[ - dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset - ] - ): - """ - this is needed to fix 'Unexpected argument' warning in pycharm - this code does nothing because all Schema instances are immutable - this means that all input data is passed into and used in new, and after the new instance is made - no new attributes are assigned and init is not used - """ - pass - - -def cast_to_allowed_types( - arg: typing.Union[str, date, datetime, uuid.UUID, decimal.Decimal, int, float, None, dict, frozendict, list, tuple, bytes, Schema], - from_server: bool, - validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]], - path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), -) -> typing.Union[frozendict, tuple, decimal.Decimal, str, bytes, BoolClass, NoneClass, FileIO]: - """ - Casts the input payload arg into the allowed types - The input validated_path_to_schemas is mutated by running this function - - When from_server is False then - - date/datetime is cast to str - - int/float is cast to Decimal - - If a Schema instance is passed in it is converted back to a primitive instance because - One may need to validate that data to the original Schema class AND additional different classes - those additional classes will need to be added to the new manufactured class for that payload - If the code didn't do this and kept the payload as a Schema instance it would fail to validate to other - Schema classes and the code wouldn't be able to mfg a new class that includes all valid schemas - TODO: store the validated schema classes in validation_metadata - - Args: - arg: the payload - from_server: whether this payload came from the server or not - validated_path_to_schemas: a dict that stores the validated classes at any path location in the payload - """ - if isinstance(arg, Schema): - # store the already run validations - schema_classes = set() - for cls in arg.__class__.__bases__: - if cls is Singleton: - continue - schema_classes.add(cls) - validated_path_to_schemas[path_to_item] = schema_classes - - if isinstance(arg, str): - return str(arg) - elif isinstance(arg, (dict, frozendict)): - return frozendict({key: cast_to_allowed_types(val, from_server, validated_path_to_schemas, path_to_item + (key,)) for key, val in arg.items()}) - elif isinstance(arg, (bool, BoolClass)): - """ - this check must come before isinstance(arg, (int, float)) - because isinstance(True, int) is True - """ - if arg: - return BoolClass.TRUE - return BoolClass.FALSE - elif isinstance(arg, int): - return decimal.Decimal(arg) - elif isinstance(arg, float): - decimal_from_float = decimal.Decimal(arg) - if decimal_from_float.as_integer_ratio()[1] == 1: - # 9.0 -> Decimal('9.0') - # 3.4028234663852886e+38 -> Decimal('340282346638528859811704183484516925440.0') - return decimal.Decimal(str(decimal_from_float)+'.0') - return decimal_from_float - elif isinstance(arg, (tuple, list)): - return tuple([cast_to_allowed_types(item, from_server, validated_path_to_schemas, path_to_item + (i,)) for i, item in enumerate(arg)]) - elif isinstance(arg, (none_type, NoneClass)): - return NoneClass.NONE - elif isinstance(arg, (date, datetime)): - if not from_server: - return arg.isoformat() - # ApiTypeError will be thrown later by _validate_type - return arg - elif isinstance(arg, uuid.UUID): - if not from_server: - return str(arg) - # ApiTypeError will be thrown later by _validate_type - return arg - elif isinstance(arg, decimal.Decimal): - return decimal.Decimal(arg) - elif isinstance(arg, bytes): - return bytes(arg) - elif isinstance(arg, (io.FileIO, io.BufferedReader)): - return FileIO(arg) - raise ValueError('Invalid type passed in got input={} type={}'.format(arg, type(arg))) - - -class ComposedBase(Discriminable): - - @classmethod - def __get_allof_classes(cls, arg, validation_metadata: ValidationMetadata): - path_to_schemas = defaultdict(set) - for allof_cls in cls._composed_schemas['allOf']: - if validation_metadata.validation_ran_earlier(allof_cls): - continue - other_path_to_schemas = allof_cls._validate(arg, validation_metadata=validation_metadata) - update(path_to_schemas, other_path_to_schemas) - return path_to_schemas - - @classmethod - def __get_oneof_class( - cls, - arg, - discriminated_cls, - validation_metadata: ValidationMetadata, - path_to_schemas: typing.Dict[typing.Tuple, typing.Set[typing.Type[Schema]]] - ): - oneof_classes = [] - path_to_schemas = defaultdict(set) - for oneof_cls in cls._composed_schemas['oneOf']: - if oneof_cls in path_to_schemas[validation_metadata.path_to_item]: - oneof_classes.append(oneof_cls) - continue - if validation_metadata.validation_ran_earlier(oneof_cls): - oneof_classes.append(oneof_cls) - continue - try: - path_to_schemas = oneof_cls._validate(arg, validation_metadata=validation_metadata) - except (ApiValueError, ApiTypeError) as ex: - if discriminated_cls is not None and oneof_cls is discriminated_cls: - raise ex - continue - oneof_classes.append(oneof_cls) - if not oneof_classes: - raise ApiValueError( - "Invalid inputs given to generate an instance of {}. None " - "of the oneOf schemas matched the input data.".format(cls) - ) - elif len(oneof_classes) > 1: - raise ApiValueError( - "Invalid inputs given to generate an instance of {}. Multiple " - "oneOf schemas {} matched the inputs, but a max of one is allowed.".format(cls, oneof_classes) - ) - return path_to_schemas - - @classmethod - def __get_anyof_classes( - cls, - arg, - discriminated_cls, - validation_metadata: ValidationMetadata - ): - anyof_classes = [] - path_to_schemas = defaultdict(set) - for anyof_cls in cls._composed_schemas['anyOf']: - if validation_metadata.validation_ran_earlier(anyof_cls): - anyof_classes.append(anyof_cls) - continue - - try: - other_path_to_schemas = anyof_cls._validate(arg, validation_metadata=validation_metadata) - except (ApiValueError, ApiTypeError) as ex: - if discriminated_cls is not None and anyof_cls is discriminated_cls: - raise ex - continue - anyof_classes.append(anyof_cls) - update(path_to_schemas, other_path_to_schemas) - if not anyof_classes: - raise ApiValueError( - "Invalid inputs given to generate an instance of {}. None " - "of the anyOf schemas matched the input data.".format(cls) - ) - return path_to_schemas - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict, tuple]]]: - """ - ComposedBase _validate - We return dynamic classes of different bases depending upon the inputs - This makes it so: - - the returned instance is always a subclass of our defining schema - - this allows us to check type based on whether an instance is a subclass of a schema - - the returned instance is a serializable type (except for None, True, and False) which are enums - - Returns: - new_cls (type): the new class - - Raises: - ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes - ApiTypeError: when the input type is not in the list of allowed spec types - """ - if isinstance(arg, Schema) and validation_metadata.from_server is False: - if isinstance(arg, cls): - # an instance of the correct type was passed in - return {} - raise ApiTypeError( - 'Incorrect type passed in, required type was {} and passed type was {} at {}'.format( - cls, - type(arg), - validation_metadata.path_to_item - ) - ) - - # validation checking on types, validations, and enums - path_to_schemas = super()._validate(arg, validation_metadata=validation_metadata) - - updated_vm = ValidationMetadata( - configuration=validation_metadata.configuration, - from_server=validation_metadata.from_server, - path_to_item=validation_metadata.path_to_item, - seen_classes=validation_metadata.seen_classes | frozenset({cls}), - validated_path_to_schemas=validation_metadata.validated_path_to_schemas - ) - - # process composed schema - _discriminator = getattr(cls, '_discriminator', None) - discriminated_cls = None - if _discriminator and arg and isinstance(arg, frozendict): - disc_property_name = list(_discriminator.keys())[0] - cls._ensure_discriminator_value_present(disc_property_name, updated_vm, arg) - # get discriminated_cls by looking at the dict in the current class - discriminated_cls = cls._get_discriminated_class( - disc_property_name=disc_property_name, disc_payload_value=arg[disc_property_name]) - if discriminated_cls is None: - raise ApiValueError( - "Invalid discriminator value '{}' was passed in to {}.{} Only the values {} are allowed at {}".format( - arg[disc_property_name], - cls.__name__, - disc_property_name, - list(_discriminator[disc_property_name].keys()), - updated_vm.path_to_item + (disc_property_name,) - ) - ) - - if cls._composed_schemas['allOf']: - other_path_to_schemas = cls.__get_allof_classes(arg, validation_metadata=updated_vm) - update(path_to_schemas, other_path_to_schemas) - if cls._composed_schemas['oneOf']: - other_path_to_schemas = cls.__get_oneof_class( - arg, - discriminated_cls=discriminated_cls, - validation_metadata=updated_vm, - path_to_schemas=path_to_schemas - ) - update(path_to_schemas, other_path_to_schemas) - if cls._composed_schemas['anyOf']: - other_path_to_schemas = cls.__get_anyof_classes( - arg, - discriminated_cls=discriminated_cls, - validation_metadata=updated_vm - ) - update(path_to_schemas, other_path_to_schemas) - not_cls = cls._composed_schemas['not'] - if not_cls: - other_path_to_schemas = None - not_exception = ApiValueError( - "Invalid value '{}' was passed in to {}. Value is invalid because it is disallowed by {}".format( - arg, - cls.__name__, - not_cls.__name__, - ) - ) - if updated_vm.validation_ran_earlier(not_cls): - raise not_exception - - try: - other_path_to_schemas = not_cls._validate(arg, validation_metadata=updated_vm) - except (ApiValueError, ApiTypeError): - pass - if other_path_to_schemas: - raise not_exception - - if discriminated_cls is not None and not updated_vm.validation_ran_earlier(discriminated_cls): - # TODO use an exception from this package here - assert discriminated_cls in path_to_schemas[updated_vm.path_to_item] - return path_to_schemas - - -# DictBase, ListBase, NumberBase, StrBase, BoolBase, NoneBase -class ComposedSchema( - _SchemaTypeChecker(typing.Union[NoneClass, str, decimal.Decimal, BoolClass, tuple, frozendict]), - ComposedBase, - DictBase, - ListBase, - NumberBase, - StrBase, - BoolBase, - NoneBase, - Schema -): - - # subclass properties - _composed_schemas = {} - - @classmethod - def _from_openapi_data(cls, *args: typing.Any, _configuration: typing.Optional[Configuration] = None, **kwargs): - if not args: - if not kwargs: - raise ApiTypeError('{} is missing required input data in args or kwargs'.format(cls.__name__)) - args = (kwargs, ) - return super()._from_openapi_data(args[0], _configuration=_configuration) - - -class ListSchema( - _SchemaTypeChecker(typing.Union[tuple]), - ListBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.List[typing.Any], _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[list, tuple], **kwargs: ValidationMetadata): - return super().__new__(cls, arg, **kwargs) - - -class NoneSchema( - _SchemaTypeChecker(typing.Union[NoneClass]), - NoneBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: None, _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: None, **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class NumberSchema( - _SchemaTypeChecker(typing.Union[decimal.Decimal]), - NumberBase, - Schema -): - """ - This is used for type: number with no format - Both integers AND floats are accepted - """ - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[int, float, decimal.Decimal], _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[decimal.Decimal, int, float], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class IntBase(NumberBase): - @property - def as_int(self) -> int: - try: - return self._as_int - except AttributeError: - self._as_int = int(self) - return self._as_int - - @classmethod - def _validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): - if isinstance(arg, decimal.Decimal): - - denominator = arg.as_integer_ratio()[-1] - if denominator != 1: - raise ApiValueError( - "Invalid value '{}' for type integer at {}".format(arg, validation_metadata.path_to_item) - ) - - @classmethod - def _validate( - cls, - arg, - validation_metadata: ValidationMetadata, - ): - """ - IntBase _validate - TODO what about types = (int, number) -> IntBase, NumberBase? We could drop int and keep number only - """ - cls._validate_format(arg, validation_metadata=validation_metadata) - return super()._validate(arg, validation_metadata=validation_metadata) - - -class IntSchema(IntBase, NumberSchema): - - @classmethod - def _from_openapi_data(cls, arg: int, _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[decimal.Decimal, int], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class Int32Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-2147483648), - inclusive_maximum=decimal.Decimal(2147483647) - ), -): - pass - - -class Int32Schema( - Int32Base, - IntSchema -): - pass - - -class Int64Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-9223372036854775808), - inclusive_maximum=decimal.Decimal(9223372036854775807) - ), -): - pass - - -class Int64Schema( - Int64Base, - IntSchema -): - pass - - -class Float32Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-3.4028234663852886e+38), - inclusive_maximum=decimal.Decimal(3.4028234663852886e+38) - ), -): - pass - - -class Float32Schema( - Float32Base, - NumberSchema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[float, decimal.Decimal], _configuration: typing.Optional[Configuration] = None): - # todo check format - return super()._from_openapi_data(arg, _configuration=_configuration) - - -class Float64Base( - _SchemaValidator( - inclusive_minimum=decimal.Decimal(-1.7976931348623157E+308), - inclusive_maximum=decimal.Decimal(1.7976931348623157E+308) - ), -): - pass - - -class Float64Schema( - Float64Base, - NumberSchema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[float, decimal.Decimal], _configuration: typing.Optional[Configuration] = None): - # todo check format - return super()._from_openapi_data(arg, _configuration=_configuration) - - -class StrSchema( - _SchemaTypeChecker(typing.Union[str]), - StrBase, - Schema -): - """ - date + datetime string types must inherit from this class - That is because one can validate a str payload as both: - - type: string (format unset) - - type: string, format: date - """ - - @classmethod - def _from_openapi_data(cls, arg: typing.Union[str], _configuration: typing.Optional[Configuration] = None) -> 'StrSchema': - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: typing.Union[str, date, datetime, uuid.UUID], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class UUIDSchema(UUIDBase, StrSchema): - - def __new__(cls, arg: typing.Union[str, uuid.UUID], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class DateSchema(DateBase, StrSchema): - - def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class DateTimeSchema(DateTimeBase, StrSchema): - - def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class DecimalSchema(DecimalBase, StrSchema): - - def __new__(cls, arg: typing.Union[str], **kwargs: typing.Union[ValidationMetadata]): - """ - Note: Decimals may not be passed in because cast_to_allowed_types is only invoked once for payloads - which can be simple (str) or complex (dicts or lists with nested values) - Because casting is only done once and recursively casts all values prior to validation then for a potential - client side Decimal input if Decimal was accepted as an input in DecimalSchema then one would not know - if one was using it for a StrSchema (where it should be cast to str) or one is using it for NumberSchema - where it should stay as Decimal. - """ - return super().__new__(cls, arg, **kwargs) - - -class BytesSchema( - _SchemaTypeChecker(typing.Union[bytes]), - Schema, -): - """ - this class will subclass bytes and is immutable - """ - def __new__(cls, arg: typing.Union[bytes], **kwargs: typing.Union[ValidationMetadata]): - return super(Schema, cls).__new__(cls, arg) - - -class FileSchema( - _SchemaTypeChecker(typing.Union[FileIO]), - Schema, -): - """ - This class is NOT immutable - Dynamic classes are built using it for example when AnyType allows in binary data - Al other schema classes ARE immutable - If one wanted to make this immutable one could make this a DictSchema with required properties: - - data = BytesSchema (which would be an immutable bytes based schema) - - file_name = StrSchema - and cast_to_allowed_types would convert bytes and file instances into dicts containing data + file_name - The downside would be that data would be stored in memory which one may not want to do for very large files - - The developer is responsible for closing this file and deleting it - - This class was kept as mutable: - - to allow file reading and writing to disk - - to be able to preserve file name info - """ - - def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader], **kwargs: typing.Union[ValidationMetadata]): - return super(Schema, cls).__new__(cls, arg) - - -class BinaryBase: - pass - - -class BinarySchema( - _SchemaTypeChecker(typing.Union[bytes, FileIO]), - ComposedBase, - BinaryBase, - Schema, -): - - @classmethod - @property - def _composed_schemas(cls): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - return { - 'allOf': [], - 'oneOf': [ - BytesSchema, - FileSchema, - ], - 'anyOf': [ - ], - 'not': None - } - - def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader, bytes], **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg) - - -class BoolSchema( - _SchemaTypeChecker(typing.Union[BoolClass]), - BoolBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: bool, _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, arg: bool, **kwargs: typing.Union[ValidationMetadata]): - return super().__new__(cls, arg, **kwargs) - - -class AnyTypeSchema( - _SchemaTypeChecker( - typing.Union[frozendict, tuple, decimal.Decimal, str, BoolClass, NoneClass, bytes, FileIO] - ), - DictBase, - ListBase, - NumberBase, - StrBase, - BoolBase, - NoneBase, - Schema -): - pass - - -class DictSchema( - _SchemaTypeChecker(typing.Union[frozendict]), - DictBase, - Schema -): - - @classmethod - def _from_openapi_data(cls, arg: typing.Dict[str, typing.Any], _configuration: typing.Optional[Configuration] = None): - return super()._from_openapi_data(arg, _configuration=_configuration) - - def __new__(cls, *args: typing.Union[dict, frozendict], **kwargs: typing.Union[dict, frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, bytes, Schema, Unset, ValidationMetadata]): - return super().__new__(cls, *args, **kwargs) - - -schema_type_classes = set([NoneSchema, DictSchema, ListSchema, NumberSchema, StrSchema, BoolSchema]) - - -def deserialize_file(response_data, configuration, content_disposition=None): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - Args: - param response_data (str): the file data to write - configuration (Configuration): the instance to use to convert files - - Keyword Args: - content_disposition (str): the value of the Content-Disposition - header - - Returns: - (file_type): the deserialized file which is open - The user is responsible for closing and reading the file - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - if isinstance(response_data, str): - # change str to bytes so we can write it - response_data = response_data.encode('utf-8') - f.write(response_data) - - f = open(path, "rb") - return f - - -@functools.cache -def get_new_class( - class_name: str, - bases: typing.Tuple[typing.Type[typing.Union[Schema, typing.Any]], ...] -) -> typing.Type[Schema]: - """ - Returns a new class that is made with the subclass bases - """ - return type(class_name, bases, {}) - - -LOG_CACHE_USAGE = False - - -def log_cache_usage(cache_fn): - if LOG_CACHE_USAGE: - print(cache_fn.__name__, cache_fn.cache_info()) diff --git a/samples/openapi3/client/petstore/python-experimental/pom.xml b/samples/openapi3/client/petstore/python-experimental/pom.xml deleted file mode 100644 index 7e737c3611..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - 4.0.0 - org.openapitools - PythonExperimentalOAS3PetstoreTests - pom - 1.0-SNAPSHOT - Python Experimental OpenAPI3 Petstore Client - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory} - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - test - integration-test - - exec - - - make - - test - - - - - - - - \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-experimental/requirements.txt b/samples/openapi3/client/petstore/python-experimental/requirements.txt deleted file mode 100644 index c9227e58a1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -certifi >= 14.05.14 -frozendict >= 2.0.3 -python_dateutil >= 2.5.3 -setuptools >= 21.0.0 -urllib3 >= 1.15.1 diff --git a/samples/openapi3/client/petstore/python-experimental/setup.py b/samples/openapi3/client/petstore/python-experimental/setup.py deleted file mode 100644 index c0194e5163..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/setup.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from setuptools import setup, find_packages # noqa: H301 - -NAME = "petstore-api" -VERSION = "1.0.0" -# To install the library, run the following -# -# python setup.py install -# -# prerequisite: setuptools -# http://pypi.python.org/pypi/setuptools - -REQUIRES = [ - "urllib3 >= 1.15", - "certifi", - "python-dateutil", - "frozendict >= 2.0.3", - "pem>=19.3.0", - "pycryptodome>=3.9.0", -] - -setup( - name=NAME, - version=VERSION, - description="OpenAPI Petstore", - author="OpenAPI Generator community", - author_email="team@openapitools.org", - url="", - keywords=["OpenAPI", "OpenAPI-Generator", "OpenAPI Petstore"], - python_requires=">=3.9", - install_requires=REQUIRES, - packages=find_packages(exclude=["test", "tests"]), - include_package_data=True, - license="Apache-2.0", - long_description="""\ - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - """ -) diff --git a/samples/openapi3/client/petstore/python-experimental/test-requirements.txt b/samples/openapi3/client/petstore/python-experimental/test-requirements.txt deleted file mode 100644 index 36d9b4fa7a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test-requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -pytest~=4.6.7 # needed for python 3.4 -pytest-cov>=2.8.1 -pytest-randomly==1.2.3 # needed for python 3.4 -pycryptodome>=3.9.0 diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_additional_properties_class.py b/samples/openapi3/client/petstore/python-experimental/test/test_additional_properties_class.py deleted file mode 100644 index 3e0f6a96aa..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_additional_properties_class.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.additional_properties_class import AdditionalPropertiesClass - - -class TestAdditionalPropertiesClass(unittest.TestCase): - """AdditionalPropertiesClass unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_AdditionalPropertiesClass(self): - """Test AdditionalPropertiesClass""" - # FIXME: construct object with mandatory attributes with example values - # model = AdditionalPropertiesClass() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python-experimental/test/test_additional_properties_with_array_of_enums.py deleted file mode 100644 index 4e67ade9dd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_additional_properties_with_array_of_enums.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums - - -class TestAdditionalPropertiesWithArrayOfEnums(unittest.TestCase): - """AdditionalPropertiesWithArrayOfEnums unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_AdditionalPropertiesWithArrayOfEnums(self): - """Test AdditionalPropertiesWithArrayOfEnums""" - # FIXME: construct object with mandatory attributes with example values - # model = AdditionalPropertiesWithArrayOfEnums() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_address.py b/samples/openapi3/client/petstore/python-experimental/test/test_address.py deleted file mode 100644 index 2890381c26..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_address.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.address import Address - - -class TestAddress(unittest.TestCase): - """Address unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Address(self): - """Test Address""" - # FIXME: construct object with mandatory attributes with example values - # model = Address() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_animal.py b/samples/openapi3/client/petstore/python-experimental/test/test_animal.py deleted file mode 100644 index 7e244b29ba..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_animal.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.animal import Animal - - -class TestAnimal(unittest.TestCase): - """Animal unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Animal(self): - """Test Animal""" - # FIXME: construct object with mandatory attributes with example values - # model = Animal() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_animal_farm.py b/samples/openapi3/client/petstore/python-experimental/test/test_animal_farm.py deleted file mode 100644 index f3d8ff2fa8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_animal_farm.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.animal_farm import AnimalFarm - - -class TestAnimalFarm(unittest.TestCase): - """AnimalFarm unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_AnimalFarm(self): - """Test AnimalFarm""" - # FIXME: construct object with mandatory attributes with example values - # model = AnimalFarm() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_another_fake_api.py b/samples/openapi3/client/petstore/python-experimental/test/test_another_fake_api.py deleted file mode 100644 index a2e3736712..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_another_fake_api.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.api.another_fake_api import AnotherFakeApi # noqa: E501 - - -class TestAnotherFakeApi(unittest.TestCase): - """AnotherFakeApi unit test stubs""" - - def setUp(self): - self.api = AnotherFakeApi() # noqa: E501 - - def tearDown(self): - pass - - def test_call_123_test_special_tags(self): - """Test case for call_123_test_special_tags - - To test special tags # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_any_type_not_string.py b/samples/openapi3/client/petstore/python-experimental/test/test_any_type_not_string.py deleted file mode 100644 index 1fc8fb99f2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_any_type_not_string.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.any_type_not_string import AnyTypeNotString - - -class TestAnyTypeNotString(unittest.TestCase): - """AnyTypeNotString unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_AnyTypeNotString(self): - """Test AnyTypeNotString""" - # FIXME: construct object with mandatory attributes with example values - # model = AnyTypeNotString() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_api_response.py b/samples/openapi3/client/petstore/python-experimental/test/test_api_response.py deleted file mode 100644 index c75371329f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_api_response.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.api_response import ApiResponse - - -class TestApiResponse(unittest.TestCase): - """ApiResponse unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ApiResponse(self): - """Test ApiResponse""" - # FIXME: construct object with mandatory attributes with example values - # model = ApiResponse() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_apple.py b/samples/openapi3/client/petstore/python-experimental/test/test_apple.py deleted file mode 100644 index 32f95fa834..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_apple.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.apple import Apple - - -class TestApple(unittest.TestCase): - """Apple unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Apple(self): - """Test Apple""" - # FIXME: construct object with mandatory attributes with example values - # model = Apple() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_apple_req.py b/samples/openapi3/client/petstore/python-experimental/test/test_apple_req.py deleted file mode 100644 index 767c88cd8a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_apple_req.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.apple_req import AppleReq - - -class TestAppleReq(unittest.TestCase): - """AppleReq unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_AppleReq(self): - """Test AppleReq""" - # FIXME: construct object with mandatory attributes with example values - # model = AppleReq() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_array_holding_any_type.py b/samples/openapi3/client/petstore/python-experimental/test/test_array_holding_any_type.py deleted file mode 100644 index bcd5c9c3ec..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_array_holding_any_type.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.array_holding_any_type import ArrayHoldingAnyType - - -class TestArrayHoldingAnyType(unittest.TestCase): - """ArrayHoldingAnyType unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ArrayHoldingAnyType(self): - """Test ArrayHoldingAnyType""" - # FIXME: construct object with mandatory attributes with example values - # model = ArrayHoldingAnyType() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-experimental/test/test_array_of_array_of_number_only.py deleted file mode 100644 index 2ac8010f06..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_array_of_array_of_number_only.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly - - -class TestArrayOfArrayOfNumberOnly(unittest.TestCase): - """ArrayOfArrayOfNumberOnly unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ArrayOfArrayOfNumberOnly(self): - """Test ArrayOfArrayOfNumberOnly""" - # FIXME: construct object with mandatory attributes with example values - # model = ArrayOfArrayOfNumberOnly() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_array_of_enums.py b/samples/openapi3/client/petstore/python-experimental/test/test_array_of_enums.py deleted file mode 100644 index 43e974c180..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_array_of_enums.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.array_of_enums import ArrayOfEnums - - -class TestArrayOfEnums(unittest.TestCase): - """ArrayOfEnums unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ArrayOfEnums(self): - """Test ArrayOfEnums""" - # FIXME: construct object with mandatory attributes with example values - # model = ArrayOfEnums() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_array_of_number_only.py b/samples/openapi3/client/petstore/python-experimental/test/test_array_of_number_only.py deleted file mode 100644 index b0098336e2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_array_of_number_only.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.array_of_number_only import ArrayOfNumberOnly - - -class TestArrayOfNumberOnly(unittest.TestCase): - """ArrayOfNumberOnly unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ArrayOfNumberOnly(self): - """Test ArrayOfNumberOnly""" - # FIXME: construct object with mandatory attributes with example values - # model = ArrayOfNumberOnly() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_array_test.py b/samples/openapi3/client/petstore/python-experimental/test/test_array_test.py deleted file mode 100644 index 4efdf344f3..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_array_test.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.array_test import ArrayTest - - -class TestArrayTest(unittest.TestCase): - """ArrayTest unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ArrayTest(self): - """Test ArrayTest""" - # FIXME: construct object with mandatory attributes with example values - # model = ArrayTest() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_array_with_validations_in_items.py b/samples/openapi3/client/petstore/python-experimental/test/test_array_with_validations_in_items.py deleted file mode 100644 index ae9f92a941..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_array_with_validations_in_items.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.array_with_validations_in_items import ArrayWithValidationsInItems - - -class TestArrayWithValidationsInItems(unittest.TestCase): - """ArrayWithValidationsInItems unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ArrayWithValidationsInItems(self): - """Test ArrayWithValidationsInItems""" - # FIXME: construct object with mandatory attributes with example values - # model = ArrayWithValidationsInItems() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_banana.py b/samples/openapi3/client/petstore/python-experimental/test/test_banana.py deleted file mode 100644 index 693c03a89f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_banana.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.banana import Banana - - -class TestBanana(unittest.TestCase): - """Banana unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Banana(self): - """Test Banana""" - # FIXME: construct object with mandatory attributes with example values - # model = Banana() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_banana_req.py b/samples/openapi3/client/petstore/python-experimental/test/test_banana_req.py deleted file mode 100644 index 683083c66c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_banana_req.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.banana_req import BananaReq - - -class TestBananaReq(unittest.TestCase): - """BananaReq unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_BananaReq(self): - """Test BananaReq""" - # FIXME: construct object with mandatory attributes with example values - # model = BananaReq() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_bar.py b/samples/openapi3/client/petstore/python-experimental/test/test_bar.py deleted file mode 100644 index 6c041955bb..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_bar.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.bar import Bar - - -class TestBar(unittest.TestCase): - """Bar unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Bar(self): - """Test Bar""" - # FIXME: construct object with mandatory attributes with example values - # model = Bar() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_basque_pig.py b/samples/openapi3/client/petstore/python-experimental/test/test_basque_pig.py deleted file mode 100644 index 21c243e7d9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_basque_pig.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.basque_pig import BasquePig - - -class TestBasquePig(unittest.TestCase): - """BasquePig unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_BasquePig(self): - """Test BasquePig""" - # FIXME: construct object with mandatory attributes with example values - # model = BasquePig() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_boolean.py b/samples/openapi3/client/petstore/python-experimental/test/test_boolean.py deleted file mode 100644 index 2ae22b6a2b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_boolean.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.boolean import Boolean - - -class TestBoolean(unittest.TestCase): - """Boolean unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Boolean(self): - """Test Boolean""" - # FIXME: construct object with mandatory attributes with example values - # model = Boolean() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_boolean_enum.py b/samples/openapi3/client/petstore/python-experimental/test/test_boolean_enum.py deleted file mode 100644 index ea61d7186a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_boolean_enum.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.boolean_enum import BooleanEnum - - -class TestBooleanEnum(unittest.TestCase): - """BooleanEnum unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_BooleanEnum(self): - """Test BooleanEnum""" - # FIXME: construct object with mandatory attributes with example values - # model = BooleanEnum() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_capitalization.py b/samples/openapi3/client/petstore/python-experimental/test/test_capitalization.py deleted file mode 100644 index 1b60714649..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_capitalization.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.capitalization import Capitalization - - -class TestCapitalization(unittest.TestCase): - """Capitalization unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Capitalization(self): - """Test Capitalization""" - # FIXME: construct object with mandatory attributes with example values - # model = Capitalization() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_cat.py b/samples/openapi3/client/petstore/python-experimental/test/test_cat.py deleted file mode 100644 index 571f3b9adc..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_cat.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.cat import Cat - - -class TestCat(unittest.TestCase): - """Cat unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Cat(self): - """Test Cat""" - # FIXME: construct object with mandatory attributes with example values - # model = Cat() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_category.py b/samples/openapi3/client/petstore/python-experimental/test/test_category.py deleted file mode 100644 index a37846446a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_category.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.category import Category - - -class TestCategory(unittest.TestCase): - """Category unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Category(self): - """Test Category""" - # FIXME: construct object with mandatory attributes with example values - # model = Category() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_child_cat.py b/samples/openapi3/client/petstore/python-experimental/test/test_child_cat.py deleted file mode 100644 index 3537d0effc..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_child_cat.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.child_cat import ChildCat - - -class TestChildCat(unittest.TestCase): - """ChildCat unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ChildCat(self): - """Test ChildCat""" - # FIXME: construct object with mandatory attributes with example values - # model = ChildCat() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_class_model.py b/samples/openapi3/client/petstore/python-experimental/test/test_class_model.py deleted file mode 100644 index fdbf0e7ff7..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_class_model.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.class_model import ClassModel - - -class TestClassModel(unittest.TestCase): - """ClassModel unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ClassModel(self): - """Test ClassModel""" - # FIXME: construct object with mandatory attributes with example values - # model = ClassModel() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_client.py b/samples/openapi3/client/petstore/python-experimental/test/test_client.py deleted file mode 100644 index 0222983fc2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_client.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.client import Client - - -class TestClient(unittest.TestCase): - """Client unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Client(self): - """Test Client""" - # FIXME: construct object with mandatory attributes with example values - # model = Client() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_complex_quadrilateral.py b/samples/openapi3/client/petstore/python-experimental/test/test_complex_quadrilateral.py deleted file mode 100644 index e31da4be74..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_complex_quadrilateral.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral - - -class TestComplexQuadrilateral(unittest.TestCase): - """ComplexQuadrilateral unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComplexQuadrilateral(self): - """Test ComplexQuadrilateral""" - # FIXME: construct object with mandatory attributes with example values - # model = ComplexQuadrilateral() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_composed_any_of_different_types_no_validations.py b/samples/openapi3/client/petstore/python-experimental/test/test_composed_any_of_different_types_no_validations.py deleted file mode 100644 index 96691e8f9e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_composed_any_of_different_types_no_validations.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.composed_any_of_different_types_no_validations import ComposedAnyOfDifferentTypesNoValidations - - -class TestComposedAnyOfDifferentTypesNoValidations(unittest.TestCase): - """ComposedAnyOfDifferentTypesNoValidations unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedAnyOfDifferentTypesNoValidations(self): - """Test ComposedAnyOfDifferentTypesNoValidations""" - # FIXME: construct object with mandatory attributes with example values - # model = ComposedAnyOfDifferentTypesNoValidations() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_composed_array.py b/samples/openapi3/client/petstore/python-experimental/test/test_composed_array.py deleted file mode 100644 index a83aa868cd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_composed_array.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.composed_array import ComposedArray - - -class TestComposedArray(unittest.TestCase): - """ComposedArray unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedArray(self): - """Test ComposedArray""" - # FIXME: construct object with mandatory attributes with example values - # model = ComposedArray() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_composed_bool.py b/samples/openapi3/client/petstore/python-experimental/test/test_composed_bool.py deleted file mode 100644 index 8ccaed5ee1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_composed_bool.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.composed_bool import ComposedBool - - -class TestComposedBool(unittest.TestCase): - """ComposedBool unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedBool(self): - """Test ComposedBool""" - # FIXME: construct object with mandatory attributes with example values - # model = ComposedBool() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_composed_none.py b/samples/openapi3/client/petstore/python-experimental/test/test_composed_none.py deleted file mode 100644 index 0669698ed2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_composed_none.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.composed_none import ComposedNone - - -class TestComposedNone(unittest.TestCase): - """ComposedNone unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedNone(self): - """Test ComposedNone""" - # FIXME: construct object with mandatory attributes with example values - # model = ComposedNone() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_composed_number.py b/samples/openapi3/client/petstore/python-experimental/test/test_composed_number.py deleted file mode 100644 index 162b7bcaf8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_composed_number.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.composed_number import ComposedNumber - - -class TestComposedNumber(unittest.TestCase): - """ComposedNumber unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedNumber(self): - """Test ComposedNumber""" - # FIXME: construct object with mandatory attributes with example values - # model = ComposedNumber() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_composed_object.py b/samples/openapi3/client/petstore/python-experimental/test/test_composed_object.py deleted file mode 100644 index a2d8b85a34..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_composed_object.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.composed_object import ComposedObject - - -class TestComposedObject(unittest.TestCase): - """ComposedObject unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedObject(self): - """Test ComposedObject""" - # FIXME: construct object with mandatory attributes with example values - # model = ComposedObject() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_composed_one_of_different_types.py b/samples/openapi3/client/petstore/python-experimental/test/test_composed_one_of_different_types.py deleted file mode 100644 index c33fd21e5e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_composed_one_of_different_types.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes - - -class TestComposedOneOfDifferentTypes(unittest.TestCase): - """ComposedOneOfDifferentTypes unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedOneOfDifferentTypes(self): - """Test ComposedOneOfDifferentTypes""" - # FIXME: construct object with mandatory attributes with example values - # model = ComposedOneOfDifferentTypes() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_composed_string.py b/samples/openapi3/client/petstore/python-experimental/test/test_composed_string.py deleted file mode 100644 index 902d75278d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_composed_string.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.composed_string import ComposedString - - -class TestComposedString(unittest.TestCase): - """ComposedString unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedString(self): - """Test ComposedString""" - # FIXME: construct object with mandatory attributes with example values - # model = ComposedString() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_currency.py b/samples/openapi3/client/petstore/python-experimental/test/test_currency.py deleted file mode 100644 index 06f8236b89..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_currency.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.currency import Currency - - -class TestCurrency(unittest.TestCase): - """Currency unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Currency(self): - """Test Currency""" - # FIXME: construct object with mandatory attributes with example values - # model = Currency() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_danish_pig.py b/samples/openapi3/client/petstore/python-experimental/test/test_danish_pig.py deleted file mode 100644 index e1c66fdf6d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_danish_pig.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.danish_pig import DanishPig - - -class TestDanishPig(unittest.TestCase): - """DanishPig unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_DanishPig(self): - """Test DanishPig""" - # FIXME: construct object with mandatory attributes with example values - # model = DanishPig() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_date_time_test.py b/samples/openapi3/client/petstore/python-experimental/test/test_date_time_test.py deleted file mode 100644 index 597abd5ba8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_date_time_test.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.date_time_test import DateTimeTest - - -class TestDateTimeTest(unittest.TestCase): - """DateTimeTest unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_DateTimeTest(self): - """Test DateTimeTest""" - # FIXME: construct object with mandatory attributes with example values - # model = DateTimeTest() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_date_time_with_validations.py b/samples/openapi3/client/petstore/python-experimental/test/test_date_time_with_validations.py deleted file mode 100644 index 7f8c4c3bb4..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_date_time_with_validations.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.date_time_with_validations import DateTimeWithValidations - - -class TestDateTimeWithValidations(unittest.TestCase): - """DateTimeWithValidations unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_DateTimeWithValidations(self): - """Test DateTimeWithValidations""" - # FIXME: construct object with mandatory attributes with example values - # model = DateTimeWithValidations() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_date_with_validations.py b/samples/openapi3/client/petstore/python-experimental/test/test_date_with_validations.py deleted file mode 100644 index 2656d3b91f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_date_with_validations.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.date_with_validations import DateWithValidations - - -class TestDateWithValidations(unittest.TestCase): - """DateWithValidations unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_DateWithValidations(self): - """Test DateWithValidations""" - # FIXME: construct object with mandatory attributes with example values - # model = DateWithValidations() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_decimal_payload.py b/samples/openapi3/client/petstore/python-experimental/test/test_decimal_payload.py deleted file mode 100644 index b50d4fbc8a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_decimal_payload.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.decimal_payload import DecimalPayload - - -class TestDecimalPayload(unittest.TestCase): - """DecimalPayload unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_DecimalPayload(self): - """Test DecimalPayload""" - # FIXME: construct object with mandatory attributes with example values - # model = DecimalPayload() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_default_api.py b/samples/openapi3/client/petstore/python-experimental/test/test_default_api.py deleted file mode 100644 index 2af6b820e0..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_default_api.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.api.default_api import DefaultApi # noqa: E501 - - -class TestDefaultApi(unittest.TestCase): - """DefaultApi unit test stubs""" - - def setUp(self): - self.api = DefaultApi() # noqa: E501 - - def tearDown(self): - pass - - def test_foo_get(self): - """Test case for foo_get - - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_dog.py b/samples/openapi3/client/petstore/python-experimental/test/test_dog.py deleted file mode 100644 index 4adcdd278c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_dog.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.dog import Dog - - -class TestDog(unittest.TestCase): - """Dog unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Dog(self): - """Test Dog""" - # FIXME: construct object with mandatory attributes with example values - # model = Dog() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_drawing.py b/samples/openapi3/client/petstore/python-experimental/test/test_drawing.py deleted file mode 100644 index d08e8a6fbe..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_drawing.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.drawing import Drawing - - -class TestDrawing(unittest.TestCase): - """Drawing unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Drawing(self): - """Test Drawing""" - # FIXME: construct object with mandatory attributes with example values - # model = Drawing() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_enum_arrays.py b/samples/openapi3/client/petstore/python-experimental/test/test_enum_arrays.py deleted file mode 100644 index 55b12169e2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_enum_arrays.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.enum_arrays import EnumArrays - - -class TestEnumArrays(unittest.TestCase): - """EnumArrays unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_EnumArrays(self): - """Test EnumArrays""" - # FIXME: construct object with mandatory attributes with example values - # model = EnumArrays() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_enum_class.py b/samples/openapi3/client/petstore/python-experimental/test/test_enum_class.py deleted file mode 100644 index 18688309ec..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_enum_class.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.enum_class import EnumClass - - -class TestEnumClass(unittest.TestCase): - """EnumClass unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_EnumClass(self): - """Test EnumClass""" - # FIXME: construct object with mandatory attributes with example values - # model = EnumClass() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_enum_test.py b/samples/openapi3/client/petstore/python-experimental/test/test_enum_test.py deleted file mode 100644 index 9952acb682..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_enum_test.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.enum_test import EnumTest - - -class TestEnumTest(unittest.TestCase): - """EnumTest unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_EnumTest(self): - """Test EnumTest""" - # FIXME: construct object with mandatory attributes with example values - # model = EnumTest() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_equilateral_triangle.py b/samples/openapi3/client/petstore/python-experimental/test/test_equilateral_triangle.py deleted file mode 100644 index 62308d48c8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_equilateral_triangle.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.equilateral_triangle import EquilateralTriangle - - -class TestEquilateralTriangle(unittest.TestCase): - """EquilateralTriangle unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_EquilateralTriangle(self): - """Test EquilateralTriangle""" - # FIXME: construct object with mandatory attributes with example values - # model = EquilateralTriangle() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_fake_api.py b/samples/openapi3/client/petstore/python-experimental/test/test_fake_api.py deleted file mode 100644 index 22a984c5ea..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_fake_api.py +++ /dev/null @@ -1,227 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.api.fake_api import FakeApi # noqa: E501 - - -class TestFakeApi(unittest.TestCase): - """FakeApi unit test stubs""" - - def setUp(self): - self.api = FakeApi() # noqa: E501 - - def tearDown(self): - pass - - def test_additional_properties_with_array_of_enums(self): - """Test case for additional_properties_with_array_of_enums - - Additional Properties with Array of Enums # noqa: E501 - """ - pass - - def test_array_model(self): - """Test case for array_model - - """ - pass - - def test_array_of_enums(self): - """Test case for array_of_enums - - Array of Enums # noqa: E501 - """ - pass - - def test_body_with_file_schema(self): - """Test case for body_with_file_schema - - """ - pass - - def test_body_with_query_params(self): - """Test case for body_with_query_params - - """ - pass - - def test_boolean(self): - """Test case for boolean - - """ - pass - - def test_case_sensitive_params(self): - """Test case for case_sensitive_params - - """ - pass - - def test_client_model(self): - """Test case for client_model - - To test \"client\" model # noqa: E501 - """ - pass - - def test_composed_one_of_different_types(self): - """Test case for composed_one_of_different_types - - """ - pass - - def test_endpoint_parameters(self): - """Test case for endpoint_parameters - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 - """ - pass - - def test_enum_parameters(self): - """Test case for enum_parameters - - To test enum parameters # noqa: E501 - """ - pass - - def test_fake_health_get(self): - """Test case for fake_health_get - - Health check endpoint # noqa: E501 - """ - pass - - def test_group_parameters(self): - """Test case for group_parameters - - Fake endpoint to test group parameters (optional) # noqa: E501 - """ - pass - - def test_inline_additional_properties(self): - """Test case for inline_additional_properties - - test inline additionalProperties # noqa: E501 - """ - pass - - def test_inline_composition(self): - """Test case for inline_composition - - testing composed schemas at inline locations # noqa: E501 - """ - pass - - def test_json_form_data(self): - """Test case for json_form_data - - test json serialization of form data # noqa: E501 - """ - pass - - def test_json_with_charset(self): - """Test case for json_with_charset - - json with charset tx and rx # noqa: E501 - """ - pass - - def test_mammal(self): - """Test case for mammal - - """ - pass - - def test_number_with_validations(self): - """Test case for number_with_validations - - """ - pass - - def test_object_in_query(self): - """Test case for object_in_query - - user list # noqa: E501 - """ - pass - - def test_object_model_with_ref_props(self): - """Test case for object_model_with_ref_props - - """ - pass - - def test_parameter_collisions(self): - """Test case for parameter_collisions - - parameter collision case # noqa: E501 - """ - pass - - def test_query_parameter_collection_format(self): - """Test case for query_parameter_collection_format - - """ - pass - - def test_ref_object_in_query(self): - """Test case for ref_object_in_query - - user list # noqa: E501 - """ - pass - - def test_response_without_schema(self): - """Test case for response_without_schema - - receives a response without schema # noqa: E501 - """ - pass - - def test_string(self): - """Test case for string - - """ - pass - - def test_string_enum(self): - """Test case for string_enum - - """ - pass - - def test_upload_download_file(self): - """Test case for upload_download_file - - uploads a file and downloads a file using application/octet-stream # noqa: E501 - """ - pass - - def test_upload_file(self): - """Test case for upload_file - - uploads a file using multipart/form-data # noqa: E501 - """ - pass - - def test_upload_files(self): - """Test case for upload_files - - uploads files using multipart/form-data # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_fake_classname_tags123_api.py b/samples/openapi3/client/petstore/python-experimental/test/test_fake_classname_tags123_api.py deleted file mode 100644 index 705fd1fc9c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_fake_classname_tags123_api.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.api.fake_classname_tags123_api import FakeClassnameTags123Api # noqa: E501 - - -class TestFakeClassnameTags123Api(unittest.TestCase): - """FakeClassnameTags123Api unit test stubs""" - - def setUp(self): - self.api = FakeClassnameTags123Api() # noqa: E501 - - def tearDown(self): - pass - - def test_classname(self): - """Test case for classname - - To test class name in snake case # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_file.py b/samples/openapi3/client/petstore/python-experimental/test/test_file.py deleted file mode 100644 index 240760a67d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_file.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.file import File - - -class TestFile(unittest.TestCase): - """File unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_File(self): - """Test File""" - # FIXME: construct object with mandatory attributes with example values - # model = File() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_file_schema_test_class.py b/samples/openapi3/client/petstore/python-experimental/test/test_file_schema_test_class.py deleted file mode 100644 index fc4828d0ed..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_file_schema_test_class.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.file_schema_test_class import FileSchemaTestClass - - -class TestFileSchemaTestClass(unittest.TestCase): - """FileSchemaTestClass unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_FileSchemaTestClass(self): - """Test FileSchemaTestClass""" - # FIXME: construct object with mandatory attributes with example values - # model = FileSchemaTestClass() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_foo.py b/samples/openapi3/client/petstore/python-experimental/test/test_foo.py deleted file mode 100644 index 4ee6344ea2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_foo.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.foo import Foo - - -class TestFoo(unittest.TestCase): - """Foo unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Foo(self): - """Test Foo""" - # FIXME: construct object with mandatory attributes with example values - # model = Foo() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_format_test.py b/samples/openapi3/client/petstore/python-experimental/test/test_format_test.py deleted file mode 100644 index 46d4794bbe..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_format_test.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.format_test import FormatTest - - -class TestFormatTest(unittest.TestCase): - """FormatTest unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_FormatTest(self): - """Test FormatTest""" - # FIXME: construct object with mandatory attributes with example values - # model = FormatTest() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_fruit.py b/samples/openapi3/client/petstore/python-experimental/test/test_fruit.py deleted file mode 100644 index 490ce5cf95..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_fruit.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.fruit import Fruit - - -class TestFruit(unittest.TestCase): - """Fruit unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Fruit(self): - """Test Fruit""" - # FIXME: construct object with mandatory attributes with example values - # model = Fruit() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_fruit_req.py b/samples/openapi3/client/petstore/python-experimental/test/test_fruit_req.py deleted file mode 100644 index ceae8a9342..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_fruit_req.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.fruit_req import FruitReq - - -class TestFruitReq(unittest.TestCase): - """FruitReq unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_FruitReq(self): - """Test FruitReq""" - # FIXME: construct object with mandatory attributes with example values - # model = FruitReq() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_gm_fruit.py b/samples/openapi3/client/petstore/python-experimental/test/test_gm_fruit.py deleted file mode 100644 index c924c45e55..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_gm_fruit.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.gm_fruit import GmFruit - - -class TestGmFruit(unittest.TestCase): - """GmFruit unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_GmFruit(self): - """Test GmFruit""" - # FIXME: construct object with mandatory attributes with example values - # model = GmFruit() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_grandparent_animal.py b/samples/openapi3/client/petstore/python-experimental/test/test_grandparent_animal.py deleted file mode 100644 index 34edef4006..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_grandparent_animal.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.grandparent_animal import GrandparentAnimal - - -class TestGrandparentAnimal(unittest.TestCase): - """GrandparentAnimal unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_GrandparentAnimal(self): - """Test GrandparentAnimal""" - # FIXME: construct object with mandatory attributes with example values - # model = GrandparentAnimal() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_has_only_read_only.py b/samples/openapi3/client/petstore/python-experimental/test/test_has_only_read_only.py deleted file mode 100644 index 8ed163b762..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_has_only_read_only.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.has_only_read_only import HasOnlyReadOnly - - -class TestHasOnlyReadOnly(unittest.TestCase): - """HasOnlyReadOnly unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_HasOnlyReadOnly(self): - """Test HasOnlyReadOnly""" - # FIXME: construct object with mandatory attributes with example values - # model = HasOnlyReadOnly() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_health_check_result.py b/samples/openapi3/client/petstore/python-experimental/test/test_health_check_result.py deleted file mode 100644 index 2bf06af9a6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_health_check_result.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.health_check_result import HealthCheckResult - - -class TestHealthCheckResult(unittest.TestCase): - """HealthCheckResult unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_HealthCheckResult(self): - """Test HealthCheckResult""" - # FIXME: construct object with mandatory attributes with example values - # model = HealthCheckResult() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum.py b/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum.py deleted file mode 100644 index abd3db17c9..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.integer_enum import IntegerEnum - - -class TestIntegerEnum(unittest.TestCase): - """IntegerEnum unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_IntegerEnum(self): - """Test IntegerEnum""" - # FIXME: construct object with mandatory attributes with example values - # model = IntegerEnum() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_big.py b/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_big.py deleted file mode 100644 index d905b1d640..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_big.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.integer_enum_big import IntegerEnumBig - - -class TestIntegerEnumBig(unittest.TestCase): - """IntegerEnumBig unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_IntegerEnumBig(self): - """Test IntegerEnumBig""" - # FIXME: construct object with mandatory attributes with example values - # model = IntegerEnumBig() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_one_value.py b/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_one_value.py deleted file mode 100644 index f3dee3f395..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_one_value.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue - - -class TestIntegerEnumOneValue(unittest.TestCase): - """IntegerEnumOneValue unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_IntegerEnumOneValue(self): - """Test IntegerEnumOneValue""" - # FIXME: construct object with mandatory attributes with example values - # model = IntegerEnumOneValue() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_with_default_value.py b/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_with_default_value.py deleted file mode 100644 index 48ffddb7b0..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_with_default_value.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue - - -class TestIntegerEnumWithDefaultValue(unittest.TestCase): - """IntegerEnumWithDefaultValue unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_IntegerEnumWithDefaultValue(self): - """Test IntegerEnumWithDefaultValue""" - # FIXME: construct object with mandatory attributes with example values - # model = IntegerEnumWithDefaultValue() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_integer_max10.py b/samples/openapi3/client/petstore/python-experimental/test/test_integer_max10.py deleted file mode 100644 index fd4a0d0793..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_integer_max10.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.integer_max10 import IntegerMax10 - - -class TestIntegerMax10(unittest.TestCase): - """IntegerMax10 unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_IntegerMax10(self): - """Test IntegerMax10""" - # FIXME: construct object with mandatory attributes with example values - # model = IntegerMax10() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_integer_min15.py b/samples/openapi3/client/petstore/python-experimental/test/test_integer_min15.py deleted file mode 100644 index 05898df512..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_integer_min15.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.integer_min15 import IntegerMin15 - - -class TestIntegerMin15(unittest.TestCase): - """IntegerMin15 unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_IntegerMin15(self): - """Test IntegerMin15""" - # FIXME: construct object with mandatory attributes with example values - # model = IntegerMin15() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_isosceles_triangle.py b/samples/openapi3/client/petstore/python-experimental/test/test_isosceles_triangle.py deleted file mode 100644 index c17549e2b1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_isosceles_triangle.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.isosceles_triangle import IsoscelesTriangle - - -class TestIsoscelesTriangle(unittest.TestCase): - """IsoscelesTriangle unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_IsoscelesTriangle(self): - """Test IsoscelesTriangle""" - # FIXME: construct object with mandatory attributes with example values - # model = IsoscelesTriangle() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_mammal.py b/samples/openapi3/client/petstore/python-experimental/test/test_mammal.py deleted file mode 100644 index df83e51461..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_mammal.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.mammal import Mammal - - -class TestMammal(unittest.TestCase): - """Mammal unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Mammal(self): - """Test Mammal""" - # FIXME: construct object with mandatory attributes with example values - # model = Mammal() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_map_test.py b/samples/openapi3/client/petstore/python-experimental/test/test_map_test.py deleted file mode 100644 index 21305dee99..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_map_test.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.map_test import MapTest - - -class TestMapTest(unittest.TestCase): - """MapTest unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_MapTest(self): - """Test MapTest""" - # FIXME: construct object with mandatory attributes with example values - # model = MapTest() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-experimental/test/test_mixed_properties_and_additional_properties_class.py deleted file mode 100644 index 9f54921c69..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_mixed_properties_and_additional_properties_class.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass - - -class TestMixedPropertiesAndAdditionalPropertiesClass(unittest.TestCase): - """MixedPropertiesAndAdditionalPropertiesClass unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_MixedPropertiesAndAdditionalPropertiesClass(self): - """Test MixedPropertiesAndAdditionalPropertiesClass""" - # FIXME: construct object with mandatory attributes with example values - # model = MixedPropertiesAndAdditionalPropertiesClass() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_model200_response.py b/samples/openapi3/client/petstore/python-experimental/test/test_model200_response.py deleted file mode 100644 index 48f8ea5e01..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_model200_response.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.model200_response import Model200Response - - -class TestModel200Response(unittest.TestCase): - """Model200Response unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Model200Response(self): - """Test Model200Response""" - # FIXME: construct object with mandatory attributes with example values - # model = Model200Response() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_model_return.py b/samples/openapi3/client/petstore/python-experimental/test/test_model_return.py deleted file mode 100644 index 79b04d0931..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_model_return.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.model_return import ModelReturn - - -class TestModelReturn(unittest.TestCase): - """ModelReturn unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ModelReturn(self): - """Test ModelReturn""" - # FIXME: construct object with mandatory attributes with example values - # model = ModelReturn() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_money.py b/samples/openapi3/client/petstore/python-experimental/test/test_money.py deleted file mode 100644 index 2eb90df664..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_money.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.money import Money - - -class TestMoney(unittest.TestCase): - """Money unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Money(self): - """Test Money""" - # FIXME: construct object with mandatory attributes with example values - # model = Money() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_name.py b/samples/openapi3/client/petstore/python-experimental/test/test_name.py deleted file mode 100644 index ec115ac670..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_name.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.name import Name - - -class TestName(unittest.TestCase): - """Name unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Name(self): - """Test Name""" - # FIXME: construct object with mandatory attributes with example values - # model = Name() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_no_additional_properties.py b/samples/openapi3/client/petstore/python-experimental/test/test_no_additional_properties.py deleted file mode 100644 index 59ccb034d6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_no_additional_properties.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.no_additional_properties import NoAdditionalProperties - - -class TestNoAdditionalProperties(unittest.TestCase): - """NoAdditionalProperties unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_NoAdditionalProperties(self): - """Test NoAdditionalProperties""" - # FIXME: construct object with mandatory attributes with example values - # model = NoAdditionalProperties() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_nullable_class.py b/samples/openapi3/client/petstore/python-experimental/test/test_nullable_class.py deleted file mode 100644 index 5b4cfeb945..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_nullable_class.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.nullable_class import NullableClass - - -class TestNullableClass(unittest.TestCase): - """NullableClass unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_NullableClass(self): - """Test NullableClass""" - # FIXME: construct object with mandatory attributes with example values - # model = NullableClass() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_nullable_shape.py b/samples/openapi3/client/petstore/python-experimental/test/test_nullable_shape.py deleted file mode 100644 index 697c8d6632..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_nullable_shape.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.nullable_shape import NullableShape - - -class TestNullableShape(unittest.TestCase): - """NullableShape unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_NullableShape(self): - """Test NullableShape""" - # FIXME: construct object with mandatory attributes with example values - # model = NullableShape() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_nullable_string.py b/samples/openapi3/client/petstore/python-experimental/test/test_nullable_string.py deleted file mode 100644 index 38fcd7262b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_nullable_string.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.nullable_string import NullableString - - -class TestNullableString(unittest.TestCase): - """NullableString unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_NullableString(self): - """Test NullableString""" - # FIXME: construct object with mandatory attributes with example values - # model = NullableString() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_number.py b/samples/openapi3/client/petstore/python-experimental/test/test_number.py deleted file mode 100644 index 6f7f55b940..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_number.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.number import Number - - -class TestNumber(unittest.TestCase): - """Number unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Number(self): - """Test Number""" - # FIXME: construct object with mandatory attributes with example values - # model = Number() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_number_only.py b/samples/openapi3/client/petstore/python-experimental/test/test_number_only.py deleted file mode 100644 index 69073964b8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_number_only.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.number_only import NumberOnly - - -class TestNumberOnly(unittest.TestCase): - """NumberOnly unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_NumberOnly(self): - """Test NumberOnly""" - # FIXME: construct object with mandatory attributes with example values - # model = NumberOnly() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_number_with_validations.py b/samples/openapi3/client/petstore/python-experimental/test/test_number_with_validations.py deleted file mode 100644 index b7dbd3ba66..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_number_with_validations.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.number_with_validations import NumberWithValidations - - -class TestNumberWithValidations(unittest.TestCase): - """NumberWithValidations unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_NumberWithValidations(self): - """Test NumberWithValidations""" - # FIXME: construct object with mandatory attributes with example values - # model = NumberWithValidations() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_object_interface.py b/samples/openapi3/client/petstore/python-experimental/test/test_object_interface.py deleted file mode 100644 index 45cd46414d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_object_interface.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.object_interface import ObjectInterface - - -class TestObjectInterface(unittest.TestCase): - """ObjectInterface unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ObjectInterface(self): - """Test ObjectInterface""" - # FIXME: construct object with mandatory attributes with example values - # model = ObjectInterface() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_object_model_with_ref_props.py b/samples/openapi3/client/petstore/python-experimental/test/test_object_model_with_ref_props.py deleted file mode 100644 index 0a1045ece2..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_object_model_with_ref_props.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps - - -class TestObjectModelWithRefProps(unittest.TestCase): - """ObjectModelWithRefProps unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ObjectModelWithRefProps(self): - """Test ObjectModelWithRefProps""" - # FIXME: construct object with mandatory attributes with example values - # model = ObjectModelWithRefProps() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_object_with_decimal_properties.py b/samples/openapi3/client/petstore/python-experimental/test/test_object_with_decimal_properties.py deleted file mode 100644 index f8c4ff1a6c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_object_with_decimal_properties.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.object_with_decimal_properties import ObjectWithDecimalProperties - - -class TestObjectWithDecimalProperties(unittest.TestCase): - """ObjectWithDecimalProperties unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ObjectWithDecimalProperties(self): - """Test ObjectWithDecimalProperties""" - # FIXME: construct object with mandatory attributes with example values - # model = ObjectWithDecimalProperties() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_object_with_difficultly_named_props.py b/samples/openapi3/client/petstore/python-experimental/test/test_object_with_difficultly_named_props.py deleted file mode 100644 index c595983094..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_object_with_difficultly_named_props.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.object_with_difficultly_named_props import ObjectWithDifficultlyNamedProps - - -class TestObjectWithDifficultlyNamedProps(unittest.TestCase): - """ObjectWithDifficultlyNamedProps unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ObjectWithDifficultlyNamedProps(self): - """Test ObjectWithDifficultlyNamedProps""" - # FIXME: construct object with mandatory attributes with example values - # model = ObjectWithDifficultlyNamedProps() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_object_with_inline_composition_property.py b/samples/openapi3/client/petstore/python-experimental/test/test_object_with_inline_composition_property.py deleted file mode 100644 index 442195d94d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_object_with_inline_composition_property.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.object_with_inline_composition_property import ObjectWithInlineCompositionProperty - - -class TestObjectWithInlineCompositionProperty(unittest.TestCase): - """ObjectWithInlineCompositionProperty unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ObjectWithInlineCompositionProperty(self): - """Test ObjectWithInlineCompositionProperty""" - # FIXME: construct object with mandatory attributes with example values - # model = ObjectWithInlineCompositionProperty() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_object_with_validations.py b/samples/openapi3/client/petstore/python-experimental/test/test_object_with_validations.py deleted file mode 100644 index 128755642e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_object_with_validations.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.object_with_validations import ObjectWithValidations - - -class TestObjectWithValidations(unittest.TestCase): - """ObjectWithValidations unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ObjectWithValidations(self): - """Test ObjectWithValidations""" - # FIXME: construct object with mandatory attributes with example values - # model = ObjectWithValidations() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_order.py b/samples/openapi3/client/petstore/python-experimental/test/test_order.py deleted file mode 100644 index bfed83072a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_order.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.order import Order - - -class TestOrder(unittest.TestCase): - """Order unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Order(self): - """Test Order""" - # FIXME: construct object with mandatory attributes with example values - # model = Order() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_parent_pet.py b/samples/openapi3/client/petstore/python-experimental/test/test_parent_pet.py deleted file mode 100644 index 0c9d187652..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_parent_pet.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.parent_pet import ParentPet - - -class TestParentPet(unittest.TestCase): - """ParentPet unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ParentPet(self): - """Test ParentPet""" - # FIXME: construct object with mandatory attributes with example values - # model = ParentPet() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_pet.py b/samples/openapi3/client/petstore/python-experimental/test/test_pet.py deleted file mode 100644 index 133ae47f40..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_pet.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.pet import Pet - - -class TestPet(unittest.TestCase): - """Pet unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Pet(self): - """Test Pet""" - # FIXME: construct object with mandatory attributes with example values - # model = Pet() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_pet_api.py b/samples/openapi3/client/petstore/python-experimental/test/test_pet_api.py deleted file mode 100644 index 494be2ebd8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_pet_api.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.api.pet_api import PetApi # noqa: E501 - - -class TestPetApi(unittest.TestCase): - """PetApi unit test stubs""" - - def setUp(self): - self.api = PetApi() # noqa: E501 - - def tearDown(self): - pass - - def test_add_pet(self): - """Test case for add_pet - - Add a new pet to the store # noqa: E501 - """ - pass - - def test_delete_pet(self): - """Test case for delete_pet - - Deletes a pet # noqa: E501 - """ - pass - - def test_find_pets_by_status(self): - """Test case for find_pets_by_status - - Finds Pets by status # noqa: E501 - """ - pass - - def test_find_pets_by_tags(self): - """Test case for find_pets_by_tags - - Finds Pets by tags # noqa: E501 - """ - pass - - def test_get_pet_by_id(self): - """Test case for get_pet_by_id - - Find pet by ID # noqa: E501 - """ - pass - - def test_update_pet(self): - """Test case for update_pet - - Update an existing pet # noqa: E501 - """ - pass - - def test_update_pet_with_form(self): - """Test case for update_pet_with_form - - Updates a pet in the store with form data # noqa: E501 - """ - pass - - def test_upload_file_with_required_file(self): - """Test case for upload_file_with_required_file - - uploads an image (required) # noqa: E501 - """ - pass - - def test_upload_image(self): - """Test case for upload_image - - uploads an image # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_pig.py b/samples/openapi3/client/petstore/python-experimental/test/test_pig.py deleted file mode 100644 index 547a45679b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_pig.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.pig import Pig - - -class TestPig(unittest.TestCase): - """Pig unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Pig(self): - """Test Pig""" - # FIXME: construct object with mandatory attributes with example values - # model = Pig() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_player.py b/samples/openapi3/client/petstore/python-experimental/test/test_player.py deleted file mode 100644 index b3d3d685d6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_player.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.player import Player - - -class TestPlayer(unittest.TestCase): - """Player unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Player(self): - """Test Player""" - # FIXME: construct object with mandatory attributes with example values - # model = Player() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_quadrilateral.py b/samples/openapi3/client/petstore/python-experimental/test/test_quadrilateral.py deleted file mode 100644 index f21755a58e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_quadrilateral.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.quadrilateral import Quadrilateral - - -class TestQuadrilateral(unittest.TestCase): - """Quadrilateral unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Quadrilateral(self): - """Test Quadrilateral""" - # FIXME: construct object with mandatory attributes with example values - # model = Quadrilateral() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_quadrilateral_interface.py b/samples/openapi3/client/petstore/python-experimental/test/test_quadrilateral_interface.py deleted file mode 100644 index e1d318d031..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_quadrilateral_interface.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.quadrilateral_interface import QuadrilateralInterface - - -class TestQuadrilateralInterface(unittest.TestCase): - """QuadrilateralInterface unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_QuadrilateralInterface(self): - """Test QuadrilateralInterface""" - # FIXME: construct object with mandatory attributes with example values - # model = QuadrilateralInterface() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_read_only_first.py b/samples/openapi3/client/petstore/python-experimental/test/test_read_only_first.py deleted file mode 100644 index ce3245015e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_read_only_first.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.read_only_first import ReadOnlyFirst - - -class TestReadOnlyFirst(unittest.TestCase): - """ReadOnlyFirst unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ReadOnlyFirst(self): - """Test ReadOnlyFirst""" - # FIXME: construct object with mandatory attributes with example values - # model = ReadOnlyFirst() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_scalene_triangle.py b/samples/openapi3/client/petstore/python-experimental/test/test_scalene_triangle.py deleted file mode 100644 index 8e20abb645..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_scalene_triangle.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.scalene_triangle import ScaleneTriangle - - -class TestScaleneTriangle(unittest.TestCase): - """ScaleneTriangle unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ScaleneTriangle(self): - """Test ScaleneTriangle""" - # FIXME: construct object with mandatory attributes with example values - # model = ScaleneTriangle() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_shape.py b/samples/openapi3/client/petstore/python-experimental/test/test_shape.py deleted file mode 100644 index ac59550d53..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_shape.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.shape import Shape - - -class TestShape(unittest.TestCase): - """Shape unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Shape(self): - """Test Shape""" - # FIXME: construct object with mandatory attributes with example values - # model = Shape() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_shape_or_null.py b/samples/openapi3/client/petstore/python-experimental/test/test_shape_or_null.py deleted file mode 100644 index e014a9f0b1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_shape_or_null.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.shape_or_null import ShapeOrNull - - -class TestShapeOrNull(unittest.TestCase): - """ShapeOrNull unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ShapeOrNull(self): - """Test ShapeOrNull""" - # FIXME: construct object with mandatory attributes with example values - # model = ShapeOrNull() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_simple_quadrilateral.py b/samples/openapi3/client/petstore/python-experimental/test/test_simple_quadrilateral.py deleted file mode 100644 index a06f65e3f1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_simple_quadrilateral.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral - - -class TestSimpleQuadrilateral(unittest.TestCase): - """SimpleQuadrilateral unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_SimpleQuadrilateral(self): - """Test SimpleQuadrilateral""" - # FIXME: construct object with mandatory attributes with example values - # model = SimpleQuadrilateral() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_some_object.py b/samples/openapi3/client/petstore/python-experimental/test/test_some_object.py deleted file mode 100644 index f1fe6af158..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_some_object.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.some_object import SomeObject - - -class TestSomeObject(unittest.TestCase): - """SomeObject unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_SomeObject(self): - """Test SomeObject""" - # FIXME: construct object with mandatory attributes with example values - # model = SomeObject() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_special_model_name.py b/samples/openapi3/client/petstore/python-experimental/test/test_special_model_name.py deleted file mode 100644 index bfc1af2691..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_special_model_name.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.special_model_name import SpecialModelName - - -class TestSpecialModelName(unittest.TestCase): - """SpecialModelName unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_SpecialModelName(self): - """Test SpecialModelName""" - # FIXME: construct object with mandatory attributes with example values - # model = SpecialModelName() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_store_api.py b/samples/openapi3/client/petstore/python-experimental/test/test_store_api.py deleted file mode 100644 index 14918e6e47..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_store_api.py +++ /dev/null @@ -1,57 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.api.store_api import StoreApi # noqa: E501 - - -class TestStoreApi(unittest.TestCase): - """StoreApi unit test stubs""" - - def setUp(self): - self.api = StoreApi() # noqa: E501 - - def tearDown(self): - pass - - def test_delete_order(self): - """Test case for delete_order - - Delete purchase order by ID # noqa: E501 - """ - pass - - def test_get_inventory(self): - """Test case for get_inventory - - Returns pet inventories by status # noqa: E501 - """ - pass - - def test_get_order_by_id(self): - """Test case for get_order_by_id - - Find purchase order by ID # noqa: E501 - """ - pass - - def test_place_order(self): - """Test case for place_order - - Place an order for a pet # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_string.py b/samples/openapi3/client/petstore/python-experimental/test/test_string.py deleted file mode 100644 index d3b7bff446..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_string.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.string import String - - -class TestString(unittest.TestCase): - """String unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_String(self): - """Test String""" - # FIXME: construct object with mandatory attributes with example values - # model = String() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_string_boolean_map.py b/samples/openapi3/client/petstore/python-experimental/test/test_string_boolean_map.py deleted file mode 100644 index d211c69d25..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_string_boolean_map.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.string_boolean_map import StringBooleanMap - - -class TestStringBooleanMap(unittest.TestCase): - """StringBooleanMap unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_StringBooleanMap(self): - """Test StringBooleanMap""" - # FIXME: construct object with mandatory attributes with example values - # model = StringBooleanMap() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_string_enum.py b/samples/openapi3/client/petstore/python-experimental/test/test_string_enum.py deleted file mode 100644 index 9e464a1404..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_string_enum.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.string_enum import StringEnum - - -class TestStringEnum(unittest.TestCase): - """StringEnum unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_StringEnum(self): - """Test StringEnum""" - # FIXME: construct object with mandatory attributes with example values - # model = StringEnum() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_string_enum_with_default_value.py b/samples/openapi3/client/petstore/python-experimental/test/test_string_enum_with_default_value.py deleted file mode 100644 index 06aba4d704..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_string_enum_with_default_value.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue - - -class TestStringEnumWithDefaultValue(unittest.TestCase): - """StringEnumWithDefaultValue unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_StringEnumWithDefaultValue(self): - """Test StringEnumWithDefaultValue""" - # FIXME: construct object with mandatory attributes with example values - # model = StringEnumWithDefaultValue() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_string_with_validation.py b/samples/openapi3/client/petstore/python-experimental/test/test_string_with_validation.py deleted file mode 100644 index df7fef9ecd..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_string_with_validation.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.string_with_validation import StringWithValidation - - -class TestStringWithValidation(unittest.TestCase): - """StringWithValidation unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_StringWithValidation(self): - """Test StringWithValidation""" - # FIXME: construct object with mandatory attributes with example values - # model = StringWithValidation() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_tag.py b/samples/openapi3/client/petstore/python-experimental/test/test_tag.py deleted file mode 100644 index 3638a780a8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_tag.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.tag import Tag - - -class TestTag(unittest.TestCase): - """Tag unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Tag(self): - """Test Tag""" - # FIXME: construct object with mandatory attributes with example values - # model = Tag() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_triangle.py b/samples/openapi3/client/petstore/python-experimental/test/test_triangle.py deleted file mode 100644 index 5c51dc41ae..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_triangle.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.triangle import Triangle - - -class TestTriangle(unittest.TestCase): - """Triangle unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Triangle(self): - """Test Triangle""" - # FIXME: construct object with mandatory attributes with example values - # model = Triangle() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_triangle_interface.py b/samples/openapi3/client/petstore/python-experimental/test/test_triangle_interface.py deleted file mode 100644 index fa7414066b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_triangle_interface.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.triangle_interface import TriangleInterface - - -class TestTriangleInterface(unittest.TestCase): - """TriangleInterface unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_TriangleInterface(self): - """Test TriangleInterface""" - # FIXME: construct object with mandatory attributes with example values - # model = TriangleInterface() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_user.py b/samples/openapi3/client/petstore/python-experimental/test/test_user.py deleted file mode 100644 index 24ef5a0097..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_user.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.user import User - - -class TestUser(unittest.TestCase): - """User unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_User(self): - """Test User""" - # FIXME: construct object with mandatory attributes with example values - # model = User() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_user_api.py b/samples/openapi3/client/petstore/python-experimental/test/test_user_api.py deleted file mode 100644 index 3fa565f40f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_user_api.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.api.user_api import UserApi # noqa: E501 - - -class TestUserApi(unittest.TestCase): - """UserApi unit test stubs""" - - def setUp(self): - self.api = UserApi() # noqa: E501 - - def tearDown(self): - pass - - def test_create_user(self): - """Test case for create_user - - Create user # noqa: E501 - """ - pass - - def test_create_users_with_array_input(self): - """Test case for create_users_with_array_input - - Creates list of users with given input array # noqa: E501 - """ - pass - - def test_create_users_with_list_input(self): - """Test case for create_users_with_list_input - - Creates list of users with given input array # noqa: E501 - """ - pass - - def test_delete_user(self): - """Test case for delete_user - - Delete user # noqa: E501 - """ - pass - - def test_get_user_by_name(self): - """Test case for get_user_by_name - - Get user by user name # noqa: E501 - """ - pass - - def test_login_user(self): - """Test case for login_user - - Logs user into the system # noqa: E501 - """ - pass - - def test_logout_user(self): - """Test case for logout_user - - Logs out current logged in user session # noqa: E501 - """ - pass - - def test_update_user(self): - """Test case for update_user - - Updated user # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_uuid_string.py b/samples/openapi3/client/petstore/python-experimental/test/test_uuid_string.py deleted file mode 100644 index 466b7817ac..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_uuid_string.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.uuid_string import UUIDString - - -class TestUUIDString(unittest.TestCase): - """UUIDString unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_UUIDString(self): - """Test UUIDString""" - # FIXME: construct object with mandatory attributes with example values - # model = UUIDString() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_whale.py b/samples/openapi3/client/petstore/python-experimental/test/test_whale.py deleted file mode 100644 index e19eb56a55..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_whale.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.whale import Whale - - -class TestWhale(unittest.TestCase): - """Whale unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Whale(self): - """Test Whale""" - # FIXME: construct object with mandatory attributes with example values - # model = Whale() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_zebra.py b/samples/openapi3/client/petstore/python-experimental/test/test_zebra.py deleted file mode 100644 index 003ad25d87..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/test/test_zebra.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -import petstore_api -from petstore_api.model.zebra import Zebra - - -class TestZebra(unittest.TestCase): - """Zebra unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Zebra(self): - """Test Zebra""" - # FIXME: construct object with mandatory attributes with example values - # model = Zebra() # noqa: E501 - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/__init__.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/__init__.py deleted file mode 100644 index 104cdf76ff..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/__init__.py +++ /dev/null @@ -1,104 +0,0 @@ -import json -import typing -import unittest - -import urllib3 -from urllib3._collections import HTTPHeaderDict - -from petstore_api import api_client - - -class ApiTestMixin(unittest.TestCase): - json_content_type = 'application/json' - user_agent = 'OpenAPI-Generator/1.0.0/python' - - @classmethod - def assert_request_called_with( - cls, - mock_request, - url: str, - method: str = 'POST', - body: typing.Optional[bytes] = None, - content_type: typing.Optional[str] = 'application/json', - fields: typing.Optional[tuple[api_client.RequestField, ...]] = None, - accept_content_type: typing.Optional[str] = 'application/json', - stream: bool = False, - ): - headers = { - 'User-Agent': cls.user_agent - } - if accept_content_type: - headers['Accept'] = accept_content_type - if content_type: - headers['Content-Type'] = content_type - kwargs = dict( - headers=HTTPHeaderDict(headers), - fields=fields, - stream=stream, - timeout=None, - ) - if method != 'GET': - kwargs['body'] = body - mock_request.assert_called_with( - method, - url, - **kwargs - ) - - @classmethod - def assert_pool_manager_request_called_with( - cls, - mock_request, - url: str, - method: str = 'POST', - body: typing.Optional[bytes] = None, - content_type: typing.Optional[str] = 'application/json', - accept_content_type: typing.Optional[str] = 'application/json', - stream: bool = False, - ): - headers = { - 'User-Agent': cls.user_agent - } - if accept_content_type: - headers['Accept'] = accept_content_type - if content_type: - headers['Content-Type'] = content_type - kwargs = dict( - headers=HTTPHeaderDict(headers), - preload_content=not stream, - timeout=None, - ) - if content_type and method != 'GET': - kwargs['body'] = body - mock_request.assert_called_with( - method, - url, - **kwargs - ) - - @staticmethod - def headers_for_content_type(content_type: str) -> dict[str, str]: - return {'content-type': content_type} - - @classmethod - def response( - cls, - body: typing.Union[str, bytes], - status: int = 200, - content_type: str = json_content_type, - headers: typing.Optional[dict[str, str]] = None, - preload_content: bool = True - ) -> urllib3.HTTPResponse: - if headers is None: - headers = {} - headers.update(cls.headers_for_content_type(content_type)) - return urllib3.HTTPResponse( - body, - headers=headers, - status=status, - preload_content=preload_content - ) - - @staticmethod - def json_bytes(in_data: typing.Any) -> bytes: - return json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode('utf-8') diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_animal.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_animal.py deleted file mode 100644 index c5dd6cb2ca..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_animal.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import unittest - -import petstore_api -from petstore_api.model.cat import Cat -from petstore_api.model.dog import Dog -from petstore_api.model.animal import Animal -from petstore_api.schemas import StrSchema, BoolSchema, frozendict - - -class TestAnimal(unittest.TestCase): - """Animal unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testAnimal(self): - """Test Animal""" - - regex_err = ( - r"Invalid discriminator value was passed in to Animal.className " - r"Only the values \['Cat', 'Dog'\] are allowed at \('args\[0\]', 'className'\)" - ) - with self.assertRaisesRegex(petstore_api.ApiValueError, regex_err): - Animal(className='Fox', color='red') - - animal = Animal(className='Cat', color='black') - assert isinstance(animal, Animal) - assert isinstance(animal, frozendict) - assert isinstance(animal, Cat) - assert isinstance(animal, Cat._composed_schemas['allOf'][1]) - assert set(animal.keys()) == {'className', 'color'} - assert animal.className == 'Cat' - assert animal.color == 'black' - assert animal.__class__.color is StrSchema - assert animal.__class__.className is StrSchema - - # pass in optional param - animal = Animal(className='Cat', color='black', declawed=True) - assert isinstance(animal, Animal) - assert isinstance(animal, frozendict) - assert isinstance(animal, Cat) - assert isinstance(animal, Cat._composed_schemas['allOf'][1]) - assert set(animal.keys()) == {'className', 'color', 'declawed'} - assert animal.className == 'Cat' - assert animal.color == 'black' - assert bool(animal.declawed) is True - assert animal.__class__.color is StrSchema - assert animal.__class__.className is StrSchema - assert animal.__class__.declawed is BoolSchema - - # make a Dog - animal = Animal(className='Dog', color='black') - assert isinstance(animal, Animal) - assert isinstance(animal, frozendict) - assert isinstance(animal, Dog) - assert isinstance(animal, Dog._composed_schemas['allOf'][1]) - assert set(animal.keys()) == {'className', 'color'} - assert animal.className == 'Dog' - assert animal.color == 'black' - assert animal.__class__.color is StrSchema - assert animal.__class__.className is StrSchema - - # pass in optional param - animal = Animal(className='Dog', color='black', breed='Labrador') - assert isinstance(animal, Animal) - assert isinstance(animal, frozendict) - assert isinstance(animal, Dog) - assert isinstance(animal, Dog._composed_schemas['allOf'][1]) - assert set(animal.keys()) == {'className', 'color', 'breed'} - assert animal.className == 'Dog' - assert animal.color == 'black' - assert animal.breed == 'Labrador' - assert animal.__class__.color is StrSchema - assert animal.__class__.className is StrSchema - assert animal.__class__.breed is StrSchema - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_any_type_schema.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_any_type_schema.py deleted file mode 100644 index dfe5fc46f3..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_any_type_schema.py +++ /dev/null @@ -1,309 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import unittest -from decimal import Decimal - -import petstore_api -from petstore_api.schemas import ( - AnyTypeSchema, - DictSchema, - ListSchema, - StrSchema, - NumberSchema, - IntSchema, - BoolSchema, - NoneSchema, - DateSchema, - DateTimeSchema, - DecimalSchema, - ComposedSchema, - frozendict, - NoneClass, - BoolClass -) - - -class TestAnyTypeSchema(unittest.TestCase): - - def testDictSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - DictSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model(a=1, b='hi') - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, DictSchema) - assert isinstance(m, frozendict) - assert m == frozendict(a=Decimal(1), b='hi') - - def testListSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - ListSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model([1, 'hi']) - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, ListSchema) - assert isinstance(m, tuple) - assert m == tuple([Decimal(1), 'hi']) - - def testStrSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - StrSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model('hi') - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, StrSchema) - assert isinstance(m, str) - assert m == 'hi' - - def testNumberSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - NumberSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model(1) - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, NumberSchema) - assert isinstance(m, Decimal) - assert m == Decimal(1) - - m = Model(3.14) - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, NumberSchema) - assert isinstance(m, Decimal) - assert m == Decimal(3.14) - - def testIntSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - IntSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model(1) - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, IntSchema) - assert isinstance(m, Decimal) - assert m == Decimal(1) - - with self.assertRaises(petstore_api.exceptions.ApiValueError): - # can't pass in float into Int - m = Model(3.14) - - def testBoolSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - BoolSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model(True) - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, BoolSchema) - assert isinstance(m, BoolClass) - self.assertTrue(m) - - m = Model(False) - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, BoolSchema) - assert isinstance(m, BoolClass) - self.assertFalse(m) - - def testNoneSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - NoneSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model(None) - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, NoneSchema) - assert isinstance(m, NoneClass) - self.assertTrue(m.is_none()) - - def testDateSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - DateSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model('1970-01-01') - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, DateSchema) - assert isinstance(m, str) - assert m == '1970-01-01' - - def testDateTimeSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - DateTimeSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model('2020-01-01T00:00:00') - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, DateTimeSchema) - assert isinstance(m, str) - assert m == '2020-01-01T00:00:00' - - def testDecimalSchema(self): - class Model(ComposedSchema): - - @classmethod - @property - def _composed_schemas(cls): - return { - 'allOf': [ - AnyTypeSchema, - DecimalSchema, - ], - 'oneOf': [ - ], - 'anyOf': [ - ], - 'not': None - } - - m = Model('12.34') - assert isinstance(m, Model) - assert isinstance(m, AnyTypeSchema) - assert isinstance(m, DecimalSchema) - assert isinstance(m, str) - assert m == '12.34' - assert m.as_decimal == Decimal('12.34') - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_boolean_enum.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_boolean_enum.py deleted file mode 100644 index bd343b2847..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_boolean_enum.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import unittest - -import petstore_api -from petstore_api.model.boolean_enum import BooleanEnum - - -class TestBooleanEnum(unittest.TestCase): - """BooleanEnum unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_BooleanEnum(self): - """Test BooleanEnum""" - model = BooleanEnum(True) - assert model is BooleanEnum.TRUE - assert model.is_true() - assert model.is_false() is False - assert repr(model) == '' - with self.assertRaises(petstore_api.ApiValueError): - BooleanEnum(False) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_bool.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_bool.py deleted file mode 100644 index 6e931e9a94..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_bool.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import unittest - -import petstore_api -from petstore_api.model.composed_bool import ComposedBool - - -class TestComposedBool(unittest.TestCase): - """ComposedBool unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedBool(self): - """Test ComposedBool""" - all_values = [None, True, False, 2, 3.14, '', {}, []] - for value in all_values: - if isinstance(value, bool): - model = ComposedBool(value) - if value is True: - self.assertTrue(bool(model)) - self.assertTrue(model.is_true()) - self.assertFalse(model.is_false()) - else: - self.assertTrue(model.is_false()) - self.assertFalse(model.is_true()) - self.assertFalse(bool(model)) - continue - with self.assertRaises(petstore_api.ApiTypeError): - ComposedBool(value) - continue - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_one_of_different_types.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_one_of_different_types.py deleted file mode 100644 index f08dd500b1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_one_of_different_types.py +++ /dev/null @@ -1,107 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest -from datetime import date, datetime, timezone -from dateutil.tz import tzutc - -import petstore_api -from petstore_api.schemas import DateSchema, DateTimeSchema, Singleton, NoneClass, frozendict -from petstore_api.model.animal import Animal -from petstore_api.model.cat import Cat -from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes -from petstore_api.model.number_with_validations import NumberWithValidations - -class TestComposedOneOfDifferentTypes(unittest.TestCase): - """ComposedOneOfDifferentTypes unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_ComposedOneOfDifferentTypes(self): - """Test ComposedOneOfDifferentTypes""" - # we can make an instance that stores float data - inst = ComposedOneOfDifferentTypes(10.0) - assert isinstance(inst, NumberWithValidations) - - # we can make an instance that stores object (dict) data - inst = ComposedOneOfDifferentTypes(className="Cat", color="black") - assert isinstance(inst, ComposedOneOfDifferentTypes) - assert isinstance(inst, Animal) - assert isinstance(inst, Cat) - assert isinstance(inst, frozendict) - - # object that holds 4 properties and is not an Animal - inst = ComposedOneOfDifferentTypes(a="a", b="b", c="c", d="d") - assert isinstance(inst, ComposedOneOfDifferentTypes) - assert not isinstance(inst, Animal) - assert isinstance(inst, frozendict) - - # None - inst = ComposedOneOfDifferentTypes(None) - assert isinstance(inst, ComposedOneOfDifferentTypes) - assert isinstance(inst, Singleton) - assert isinstance(inst, NoneClass) - assert inst.is_none() is True - - # date - inst = ComposedOneOfDifferentTypes._from_openapi_data('2019-01-10') - assert isinstance(inst, ComposedOneOfDifferentTypes) - assert isinstance(inst, DateSchema) - assert isinstance(inst, str) - assert inst.as_date.year == 2019 - assert inst.as_date.month == 1 - assert inst.as_date.day == 10 - - # date - inst = ComposedOneOfDifferentTypes(date(2019, 1, 10)) - assert isinstance(inst, ComposedOneOfDifferentTypes) - assert isinstance(inst, DateSchema) - assert isinstance(inst, str) - assert inst.as_date.year == 2019 - assert inst.as_date.month == 1 - assert inst.as_date.day == 10 - - # date-time - inst = ComposedOneOfDifferentTypes._from_openapi_data('2020-01-02T03:04:05Z') - assert isinstance(inst, ComposedOneOfDifferentTypes) - assert isinstance(inst, DateTimeSchema) - assert isinstance(inst, str) - assert inst.as_datetime.year == 2020 - assert inst.as_datetime.month == 1 - assert inst.as_datetime.day == 2 - assert inst.as_datetime.hour == 3 - assert inst.as_datetime.minute == 4 - assert inst.as_datetime.second == 5 - utc_tz = tzutc() - assert inst.as_datetime.tzinfo == utc_tz - - # date-time - inst = ComposedOneOfDifferentTypes(datetime(2020, 1, 2, 3, 4, 5, tzinfo=timezone.utc)) - assert isinstance(inst, ComposedOneOfDifferentTypes) - assert isinstance(inst, DateTimeSchema) - assert isinstance(inst, str) - assert inst.as_datetime.year == 2020 - assert inst.as_datetime.month == 1 - assert inst.as_datetime.day == 2 - assert inst.as_datetime.hour == 3 - assert inst.as_datetime.minute == 4 - assert inst.as_datetime.second == 5 - assert inst.as_datetime.tzinfo == utc_tz - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_date_time_with_validations.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_date_time_with_validations.py deleted file mode 100644 index 0703a36da1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_date_time_with_validations.py +++ /dev/null @@ -1,87 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import unittest - -import petstore_api -from petstore_api.model.date_time_with_validations import DateTimeWithValidations -from datetime import date, datetime, timezone - - -class TestDateTimeWithValidations(unittest.TestCase): - """DateTimeWithValidations unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testDateTimeWithValidations(self): - """Test DateTimeWithValidations""" - - # works with datetime input - valid_values = [datetime(2020, 1, 1), '2020-01-01T00:00:00'] - expected_datetime = '2020-01-01T00:00:00' - for valid_value in valid_values: - inst = DateTimeWithValidations(valid_value) - assert inst == expected_datetime - - # when passing data in with _from_openapi_data one must use str - with self.assertRaisesRegex( - petstore_api.ApiTypeError, - r"Invalid type. Required value type is str and passed type was datetime at \['args\[0\]'\]" - ): - DateTimeWithValidations._from_openapi_data(datetime(2020, 1, 1)) - - # when passing data _from_openapi_data we can use str - input_value_to_datetime = { - "2020-01-01T00:00:00": datetime(2020, 1, 1, tzinfo=None), - "2020-01-01T00:00:00Z": datetime(2020, 1, 1, tzinfo=timezone.utc), - "2020-01-01T00:00:00+00:00": datetime(2020, 1, 1, tzinfo=timezone.utc) - } - for input_value, expected_datetime in input_value_to_datetime.items(): - inst = DateTimeWithValidations._from_openapi_data(input_value) - assert inst.as_datetime == expected_datetime - - # value error is raised if an invalid string is passed in - with self.assertRaisesRegex( - petstore_api.ApiValueError, - r"Invalid value `abcd`, must match regular expression `.+?` at \('args\[0\]',\)" - ): - DateTimeWithValidations._from_openapi_data("abcd") - - # value error is raised if a date is passed in - with self.assertRaisesRegex( - petstore_api.ApiValueError, - r"Value does not conform to the required ISO-8601 datetime format. Invalid value '2020-01-01' for type datetime at \('args\[0\]',\)" - ): - DateTimeWithValidations(date(2020, 1, 1)) - - # pattern checking with string input - error_regex = r"Invalid value `2019-01-01T00:00:00Z`, must match regular expression `.+?` at \('args\[0\]',\)" - with self.assertRaisesRegex( - petstore_api.ApiValueError, - error_regex - ): - DateTimeWithValidations._from_openapi_data("2019-01-01T00:00:00Z") - # pattern checking with date input - error_regex = r"Invalid value `2019-01-01T00:00:00`, must match regular expression `.+?` at \('args\[0\]',\)" - with self.assertRaisesRegex( - petstore_api.ApiValueError, - error_regex - ): - DateTimeWithValidations(datetime(2019, 1, 1)) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_date_with_validations.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_date_with_validations.py deleted file mode 100644 index e2fcae60f4..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_date_with_validations.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import unittest - -import petstore_api -from petstore_api.model.date_with_validations import DateWithValidations -from datetime import date, datetime - - -class TestDateWithValidations(unittest.TestCase): - """DateWithValidations unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testDateWithValidations(self): - """Test DateWithValidations""" - - # client side date inputs - valid_values = [date(2020, 1, 1), '2020-01-01'] - expected_date = '2020-01-01' - for valid_value in valid_values: - inst = DateWithValidations(valid_value) - assert inst == expected_date - - # when passing data in with _from_openapi_data one must use str - with self.assertRaisesRegex( - petstore_api.ApiTypeError, - r"Invalid type. Required value type is str and passed type was date at \['args\[0\]'\]" - ): - DateWithValidations._from_openapi_data(date(2020, 1, 1)) - - # when passing data in from the server we can use str - valid_values = ["2020-01-01", "2020-01", "2020"] - expected_date = date(2020, 1, 1) - for valid_value in valid_values: - inst = DateWithValidations._from_openapi_data(valid_value) - assert inst.as_date == expected_date - - # value error is raised if an invalid string is passed in - with self.assertRaisesRegex( - petstore_api.ApiValueError, - r"Value does not conform to the required ISO-8601 date format. Invalid value '2020-01-01T00:00:00Z' for type date at \('args\[0\]',\)" - ): - DateWithValidations._from_openapi_data("2020-01-01T00:00:00Z") - - # value error is raised if a datetime is passed in - with self.assertRaisesRegex( - petstore_api.ApiValueError, - r"Value does not conform to the required ISO-8601 date format. Invalid value '2020-01-01T00:00:00' for type date at \('args\[0\]',\)" - ): - DateWithValidations(datetime(2020, 1, 1)) - - # value error is raised if an invalid string is passed in - with self.assertRaisesRegex( - petstore_api.ApiValueError, - r"Invalid value `abcd`, must match regular expression `.+?` at \('args\[0\]',\)" - ): - DateWithValidations._from_openapi_data("abcd") - - # pattern checking for str input - error_regex = r"Invalid value `2019-01-01`, must match regular expression `.+?` at \('args\[0\]',\)" - with self.assertRaisesRegex( - petstore_api.ApiValueError, - error_regex - ): - DateWithValidations._from_openapi_data("2019-01-01") - # pattern checking for date input - with self.assertRaisesRegex( - petstore_api.ApiValueError, - error_regex - ): - DateWithValidations(date(2019, 1, 1)) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_decimal_payload.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_decimal_payload.py deleted file mode 100644 index 25122fc35f..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_decimal_payload.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import decimal -import unittest - -import petstore_api -from petstore_api.schemas import DecimalSchema -from petstore_api.model.decimal_payload import DecimalPayload - - -class TestDecimalPayload(unittest.TestCase): - """DecimalPayload unit test stubs""" - - def test_DecimalPayload(self): - """Test DecimalPayload""" - - m = DecimalPayload('12') - assert isinstance(m, DecimalPayload) - assert isinstance(m, DecimalSchema) - assert isinstance(m, str) - assert m == '12' - assert m.as_decimal == decimal.Decimal('12') - - m = DecimalPayload('12.34') - assert isinstance(m, DecimalPayload) - assert isinstance(m, DecimalSchema) - assert isinstance(m, str) - assert m == '12.34' - assert m.as_decimal == decimal.Decimal('12.34') - - # passing in a Decimal does not work - with self.assertRaises(petstore_api.ApiTypeError): - DecimalPayload(decimal.Decimal('12.34')) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_deserialization.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_deserialization.py deleted file mode 100644 index f3a389d67e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_deserialization.py +++ /dev/null @@ -1,458 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -""" -Run the tests. -$ pip install nose (optional) -$ cd OpenAPIPetstore-python -$ nosetests -v -""" -from collections import namedtuple -from decimal import Decimal -import json -import typing -import unittest - -import urllib3 - -import petstore_api -from petstore_api import api_client -from petstore_api.schemas import NoneClass - - -MockResponse = namedtuple('MockResponse', 'data') - - -class DeserializationTests(unittest.TestCase): - json_content_type = 'application/json' - json_content_type_headers = {'content-type': json_content_type} - configuration = petstore_api.Configuration() - - @classmethod - def __response(cls, data: typing.Any) -> urllib3.HTTPResponse: - return urllib3.HTTPResponse( - json.dumps(data).encode('utf-8'), - headers=cls.json_content_type_headers - ) - - def test_deserialize_shape(self): - """ - - deserialize Shape to an instance of: - - EquilateralTriangle - - IsoscelesTriangle - - IsoscelesTriangle - - ScaleneTriangle - - ComplexQuadrilateral - - SimpleQuadrilateral - by traveling through 2 discriminators - """ - from petstore_api.model import shape, equilateral_triangle - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=shape.Shape), - }, - ) - data = { - 'shapeType': 'Triangle', - 'triangleType': 'EquilateralTriangle', - } - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, self.configuration) - body = deserialized.body - self.assertTrue(isinstance(body, equilateral_triangle.EquilateralTriangle)) - self.assertEqual(body.shapeType, 'Triangle') - self.assertEqual(body.triangleType, 'EquilateralTriangle') - - # invalid quadrilateralType, second discriminator value - data = { - 'shapeType': 'Quadrilateral', - 'quadrilateralType': 'Triangle', - } - response = self.__response(data) - - err_msg = ( - r"Invalid discriminator value was passed in to Quadrilateral.quadrilateralType Only the values " - r"\['ComplexQuadrilateral', 'SimpleQuadrilateral'\] are allowed at \('args\[0\]', 'quadrilateralType'\)" - ) - with self.assertRaisesRegex(petstore_api.ApiValueError, err_msg): - _response_for_200.deserialize(response, self.configuration) - - def test_deserialize_animal(self): - """ - deserialize Animal to a Dog instance - Animal uses a discriminator which has a map built of child classes - that inherrit from Animal - This is the swagger (v2) way of doing something like oneOf composition - """ - from petstore_api.model import animal, dog - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=animal.Animal), - }, - ) - data = { - 'className': 'Dog', - 'color': 'white', - 'breed': 'Jack Russel Terrier' - } - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, self.configuration) - body = deserialized.body - self.assertTrue(isinstance(body, dog.Dog)) - self.assertEqual(body.className, 'Dog') - self.assertEqual(body.color, 'white') - self.assertEqual(body.breed, 'Jack Russel Terrier') - - def test_regex_constraint(self): - """ - Test regex pattern validation. - """ - from petstore_api.model import apple - - # Test with valid regex pattern. - inst = apple.Apple( - cultivar="Akane" - ) - assert isinstance(inst, apple.Apple) - - inst = apple.Apple( - cultivar="Golden Delicious", - origin="cHiLe" - ) - assert isinstance(inst, apple.Apple) - - # Test with invalid regex pattern. - err_regex = r"Invalid value `.+?`, must match regular expression `.+?` at \('args\[0\]', 'cultivar'\)" - with self.assertRaisesRegex( - petstore_api.ApiValueError, - err_regex - ): - inst = apple.Apple( - cultivar="!@#%@$#Akane" - ) - - err_regex = r"Invalid value `.+?`, must match regular expression `.+?` at \('args\[0\]', 'origin'\)" - with self.assertRaisesRegex( - petstore_api.ApiValueError, - err_regex - ): - inst = apple.Apple( - cultivar="Golden Delicious", - origin="!@#%@$#Chile" - ) - - def test_deserialize_mammal(self): - """ - deserialize mammal - mammal is a oneOf composed schema model with discriminator - """ - - # whale test - from petstore_api.model import mammal, zebra, whale - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=mammal.Mammal), - }, - ) - has_baleen = True - has_teeth = False - class_name = 'whale' - data = { - 'hasBaleen': has_baleen, - 'hasTeeth': has_teeth, - 'className': class_name - } - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, self.configuration) - body = deserialized.body - self.assertTrue(isinstance(body, whale.Whale)) - self.assertEqual(bool(body.hasBaleen), has_baleen) - self.assertEqual(bool(body.hasTeeth), has_teeth) - self.assertEqual(body.className, class_name) - - # zebra test - zebra_type = 'plains' - class_name = 'zebra' - data = { - 'type': zebra_type, - 'className': class_name - } - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, self.configuration) - body = deserialized.body - self.assertTrue(isinstance(body, zebra.Zebra)) - self.assertEqual(body.type, zebra_type) - self.assertEqual(body.className, class_name) - - def test_deserialize_float_value(self): - """ - Deserialize floating point values. - """ - from petstore_api.model import banana - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=banana.Banana), - }, - ) - data = { - 'lengthCm': 3.1415 - } - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, self.configuration) - body = deserialized.body - self.assertTrue(isinstance(body, banana.Banana)) - self.assertTrue(isinstance(body.lengthCm, Decimal)) - self.assertEqual(body.lengthCm, 3.1415) - - """ - Float value is serialized without decimal point - The client receive it as an integer, which work because Banana.lengthCm is type number without format - Which accepts int AND float - """ - data = { - 'lengthCm': 3 - } - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, self.configuration) - body = deserialized.body - self.assertTrue(isinstance(body, banana.Banana)) - self.assertTrue(isinstance(body.lengthCm, Decimal)) - self.assertEqual(body.lengthCm, 3) - - def test_deserialize_fruit_null_value(self): - """ - deserialize fruit with null value. - fruitReq is a oneOf composed schema model with discriminator, including 'null' type. - """ - from petstore_api.model import fruit_req - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=fruit_req.FruitReq), - }, - ) - data = None - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, self.configuration) - self.assertTrue(isinstance(deserialized.body, fruit_req.FruitReq)) - self.assertTrue(isinstance(deserialized.body, NoneClass)) - - def test_deserialize_with_additional_properties(self): - """ - Deserialize data with schemas that have the additionalProperties keyword. - Test conditions when additional properties are allowed, not allowed, have - specific types... - """ - - # Dog is allOf with two child schemas. - # The OAS document for Dog does not specify the 'additionalProperties' keyword, - # which means that by default, the Dog schema must allow undeclared properties. - # The additionalProperties keyword is used to control the handling of extra stuff, - # that is, properties whose names are not listed in the properties keyword. - # By default any additional properties are allowed. - from petstore_api.model import dog, mammal, zebra, banana_req - data = { - 'className': 'Dog', - 'color': 'brown', - 'breed': 'golden retriever', - # Below are additional, undeclared properties. - 'group': 'Terrier Group', - 'size': 'medium', - } - response = self.__response(data) - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=dog.Dog), - }, - ) - deserialized = _response_for_200.deserialize(response, self.configuration) - body = deserialized.body - self.assertTrue(isinstance(body, dog.Dog)) - self.assertEqual(body.className, 'Dog') - self.assertEqual(body.color, 'brown') - self.assertEqual(body.breed, 'golden retriever') - self.assertEqual(body.group, 'Terrier Group') - self.assertEqual(body.size, 'medium') - - # The 'zebra' schema allows additional properties by explicitly setting - # additionalProperties: true. - # This is equivalent to 'additionalProperties' not being present. - data = { - 'className': 'zebra', - 'type': 'plains', - # Below are additional, undeclared properties - 'group': 'abc', - 'size': 3, - 'p1': True, - 'p2': ['a', 'b', 123], - } - response = self.__response(data) - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=mammal.Mammal), - }, - ) - deserialized = _response_for_200.deserialize(response, self.configuration) - body = deserialized.body - self.assertTrue(isinstance(body, zebra.Zebra)) - self.assertEqual(body.className, 'zebra') - self.assertEqual(body.type, 'plains') - self.assertEqual(bool(body.p1), True) - - # The 'bananaReq' schema disallows additional properties by explicitly setting - # additionalProperties: false - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=banana_req.BananaReq), - }, - ) - with self.assertRaisesRegex( - petstore_api.exceptions.ApiTypeError, - r"BananaReq was passed 1 invalid argument: \['unknown-group'\]" - ): - data = { - 'lengthCm': 21.2, - 'sweet': False, - # Below are additional, undeclared properties. They are not allowed, - # an exception must be raised. - 'unknown-group': 'abc', - } - response = self.__response(data) - _response_for_200.deserialize(response, self.configuration) - - def test_deserialize_with_additional_properties_and_reference(self): - """ - Deserialize data with schemas that has the additionalProperties keyword - and the schema is specified as a reference ($ref). - """ - from petstore_api.model import drawing - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=drawing.Drawing), - }, - ) - data = { - 'mainShape': { - 'shapeType': 'Triangle', - 'triangleType': 'EquilateralTriangle', - }, - 'shapes': [ - { - 'shapeType': 'Triangle', - 'triangleType': 'IsoscelesTriangle', - }, - { - 'shapeType': 'Quadrilateral', - 'quadrilateralType': 'ComplexQuadrilateral', - }, - ], - 'an_additional_prop': { - 'lengthCm': 4, - 'color': 'yellow' - } - } - response = self.__response(data) - _response_for_200.deserialize(response, self.configuration) - - def test_deserialize_NumberWithValidations(self): - from petstore_api.model.number_with_validations import NumberWithValidations - from petstore_api.api.fake_api_endpoints.number_with_validations import _response_for_200 - - # make sure that an exception is thrown on an invalid type value - with self.assertRaises(petstore_api.ApiTypeError): - response = self.__response('test str') - _response_for_200.deserialize(response, self.configuration) - - # make sure that an exception is thrown on an invalid value - with self.assertRaises(petstore_api.ApiValueError): - response = self.__response(21.0) - _response_for_200.deserialize(response, self.configuration) - - # valid value works - number_val = 11.0 - response = self.__response(number_val) - response = _response_for_200.deserialize(response, self.configuration) - self.assertTrue(isinstance(response.body, NumberWithValidations)) - self.assertEqual(response.body, number_val) - - def test_array_of_enums(self): - from petstore_api.model.array_of_enums import ArrayOfEnums - from petstore_api.api.fake_api_endpoints.array_of_enums import _response_for_200 - from petstore_api.model import string_enum - data = ["placed", None] - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, self.configuration) - assert isinstance(deserialized.body, ArrayOfEnums) - expected_results = ArrayOfEnums([string_enum.StringEnum(v) for v in data]) - assert expected_results == deserialized.body - - def test_multiple_of_deserialization(self): - data = { - 'byte': '3', - 'date': '1970-01-01', - 'password': "abcdefghijkl", - 'integer': 30, - 'number': 65.0, - 'float': 62.4, - } - from petstore_api.model import format_test - _response_for_200 = api_client.OpenApiResponse( - content={ - self.json_content_type: api_client.MediaType(schema=format_test.FormatTest), - }, - ) - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, self.configuration) - self.assertTrue(isinstance(deserialized.body, format_test.FormatTest)) - - with self.assertRaisesRegex( - petstore_api.exceptions.ApiValueError, - r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)" - ): - data = { - 'byte': '3', - 'date': '1970-01-01', - 'password': "abcdefghijkl", - 'integer': 31, # Value is supposed to be multiple of '2'. An error must be raised - 'number': 65.0, - 'float': 62.4, - } - response = self.__response(data) - _response_for_200.deserialize(response, self.configuration) - - # Disable JSON schema validation. No error should be raised during deserialization. - configuration = petstore_api.Configuration() - configuration.disabled_client_side_validations = "multipleOf" - - data = { - 'byte': '3', - 'date': '1970-01-01', - 'password': "abcdefghijkl", - 'integer': 31, # Value is supposed to be multiple of '2' - 'number': 65.0, - 'float': 62.4, - } - response = self.__response(data) - deserialized = _response_for_200.deserialize(response, configuration) - self.assertTrue(isinstance(deserialized.body, format_test.FormatTest)) - - # Disable JSON schema validation but for a different keyword. - # An error should be raised during deserialization. - configuration = petstore_api.Configuration() - configuration.disabled_client_side_validations = "maxItems" - - with self.assertRaisesRegex( - petstore_api.exceptions.ApiValueError, - r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)" - ): - data = { - 'byte': '3', - 'date': '1970-01-01', - 'password': "abcdefghijkl", - 'integer': 31, # Value is supposed to be multiple of '2' - 'number': 65.0, - 'float': 62.4, - } - response = self.__response(data) - _response_for_200.deserialize(response, configuration) diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_discard_unknown_properties.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_discard_unknown_properties.py deleted file mode 100644 index 97d850d56b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_discard_unknown_properties.py +++ /dev/null @@ -1,157 +0,0 @@ -# # coding: utf-8 -# -# # flake8: noqa -# -# """ -# Run the tests. -# $ docker pull swaggerapi/petstore -# $ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore -# $ pip install nose (optional) -# $ cd petstore_api-python -# $ nosetests -v -# """ -# from collections import namedtuple -# import json -# import re -# import unittest -# -# import petstore_api -# from petstore_api.model import cat, dog, isosceles_triangle, banana_req -# from petstore_api import Configuration, signing -# -# from petstore_api.schemas import ( -# file_type, -# model_to_dict, -# ) -# -# MockResponse = namedtuple('MockResponse', 'data') -# -# class DiscardUnknownPropertiesTests(unittest.TestCase): -# -# def test_deserialize_banana_req_do_not_discard_unknown_properties(self): -# """ -# deserialize bananaReq with unknown properties. -# Strict validation is enabled. -# Simple (non-composed) schema scenario. -# """ -# config = Configuration(discard_unknown_keys=False) -# api_client = petstore_api.ApiClient(config) -# data = { -# 'lengthCm': 21.3, -# 'sweet': False, -# # Below is an unknown property not explicitly declared in the OpenAPI document. -# # It should not be in the payload because additional properties (undeclared) are -# # not allowed in the bananaReq schema (additionalProperties: false). -# 'unknown_property': 'a-value' -# } -# response = MockResponse(data=json.dumps(data)) -# -# # Deserializing with strict validation raises an exception because the 'unknown_property' -# # is undeclared. -# with self.assertRaises(petstore_api.exceptions.ApiAttributeError) as cm: -# deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True) -# self.assertTrue(re.match("BananaReq has no attribute 'unknown_property' at.*", str(cm.exception)), -# 'Exception message: {0}'.format(str(cm.exception))) -# -# -# def test_deserialize_isosceles_triangle_do_not_discard_unknown_properties(self): -# """ -# deserialize IsoscelesTriangle with unknown properties. -# Strict validation is enabled. -# Composed schema scenario. -# """ -# config = Configuration(discard_unknown_keys=False) -# api_client = petstore_api.ApiClient(config) -# data = { -# 'shape_type': 'Triangle', -# 'triangle_type': 'EquilateralTriangle', -# # Below is an unknown property not explicitly declared in the OpenAPI document. -# # It should not be in the payload because additional properties (undeclared) are -# # not allowed in the schema (additionalProperties: false). -# 'unknown_property': 'a-value' -# } -# response = MockResponse(data=json.dumps(data)) -# -# # Deserializing with strict validation raises an exception because the 'unknown_property' -# # is undeclared. -# with self.assertRaises(petstore_api.ApiValueError) as cm: -# deserialized = api_client.deserialize(response, ((isosceles_triangle.IsoscelesTriangle),), True) -# self.assertTrue(re.match('.*Not all inputs were used.*unknown_property.*', str(cm.exception)), -# 'Exception message: {0}'.format(str(cm.exception))) -# -# -# def test_deserialize_banana_req_discard_unknown_properties(self): -# """ -# Deserialize bananaReq with unknown properties. -# Discard unknown properties. -# """ -# config = Configuration(discard_unknown_keys=True) -# api_client = petstore_api.ApiClient(config) -# data = { -# 'lengthCm': 21.3, -# 'sweet': False, -# # Below are additional (undeclared) properties not specified in the bananaReq schema. -# 'unknown_property': 'a-value', -# 'more-unknown': [ -# 'a' -# ] -# } -# # The 'unknown_property' is undeclared, which would normally raise an exception, but -# # when discard_unknown_keys is set to True, the unknown properties are discarded. -# response = MockResponse(data=json.dumps(data)) -# deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True) -# self.assertTrue(isinstance(deserialized, banana_req.BananaReq)) -# # Check the 'unknown_property' and 'more-unknown' properties are not present in the -# # output. -# self.assertIn("length_cm", deserialized.to_dict().keys()) -# self.assertNotIn("unknown_property", deserialized.to_dict().keys()) -# self.assertNotIn("more-unknown", deserialized.to_dict().keys()) -# -# def test_deserialize_cat_do_not_discard_unknown_properties(self): -# """ -# Deserialize Cat with unknown properties. -# Strict validation is enabled. -# """ -# config = Configuration(discard_unknown_keys=False) -# api_client = petstore_api.ApiClient(config) -# data = { -# "class_name": "Cat", -# "color": "black", -# "declawed": True, -# "dynamic-property": 12345, -# } -# response = MockResponse(data=json.dumps(data)) -# -# # Deserializing with strict validation does not raise an exception because the even though -# # the 'dynamic-property' is undeclared, the 'Cat' schema defines the additionalProperties -# # attribute. -# deserialized = api_client.deserialize(response, ((cat.Cat),), True) -# self.assertTrue(isinstance(deserialized, cat.Cat)) -# self.assertIn('color', deserialized.to_dict()) -# self.assertEqual(deserialized['color'], 'black') -# -# def test_deserialize_cat_discard_unknown_properties(self): -# """ -# Deserialize Cat with unknown properties. -# Request to discard unknown properties, but Cat is composed schema -# with one inner schema that has 'additionalProperties' set to true. -# """ -# config = Configuration(discard_unknown_keys=True) -# api_client = petstore_api.ApiClient(config) -# data = { -# "class_name": "Cat", -# "color": "black", -# "declawed": True, -# # Below are additional (undeclared) properties. -# "my_additional_property": 123, -# } -# # The 'my_additional_property' is undeclared, but 'Cat' has a 'Address' type through -# # the allOf: [ $ref: '#/components/schemas/Address' ]. -# response = MockResponse(data=json.dumps(data)) -# deserialized = api_client.deserialize(response, ((cat.Cat),), True) -# self.assertTrue(isinstance(deserialized, cat.Cat)) -# # Check the 'unknown_property' and 'more-unknown' properties are not present in the -# # output. -# self.assertIn("declawed", deserialized.to_dict().keys()) -# self.assertIn("my_additional_property", deserialized.to_dict().keys()) -# diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_drawing.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_drawing.py deleted file mode 100644 index ba91979814..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_drawing.py +++ /dev/null @@ -1,163 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.schemas import NoneClass -from petstore_api.model import shape -from petstore_api.model import shape_or_null -from petstore_api.model.drawing import Drawing - - -class TestDrawing(unittest.TestCase): - """Drawing unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_create_instances(self): - """ - Validate instance can be created - """ - - inst = shape.Shape( - shapeType="Triangle", - triangleType="IsoscelesTriangle" - ) - from petstore_api.model.isosceles_triangle import IsoscelesTriangle - assert isinstance(inst, IsoscelesTriangle) - - def test_deserialize_oneof_reference(self): - """ - Validate the scenario when the type of a OAS property is 'oneOf', and the 'oneOf' - schema is specified as a reference ($ref), not an inline 'oneOf' schema. - """ - isosceles_triangle = shape.Shape( - shapeType="Triangle", - triangleType="IsoscelesTriangle" - ) - from petstore_api.model.isosceles_triangle import IsoscelesTriangle - assert isinstance(isosceles_triangle, IsoscelesTriangle) - from petstore_api.model.equilateral_triangle import EquilateralTriangle - - inst = Drawing( - mainShape=isosceles_triangle, - shapes=[ - shape.Shape( - shapeType="Triangle", - triangleType="EquilateralTriangle" - ), - shape.Shape( - shapeType="Triangle", - triangleType="IsoscelesTriangle" - ), - shape.Shape( - shapeType="Triangle", - triangleType="EquilateralTriangle" - ), - shape.Shape( - shapeType="Quadrilateral", - quadrilateralType="ComplexQuadrilateral" - ) - ], - ) - assert isinstance(inst, Drawing) - assert isinstance(inst.mainShape, IsoscelesTriangle) - self.assertEqual(len(inst.shapes), 4) - from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral - assert isinstance(inst.shapes[0], EquilateralTriangle) - assert isinstance(inst.shapes[1], IsoscelesTriangle) - assert isinstance(inst.shapes[2], EquilateralTriangle) - assert isinstance(inst.shapes[3], ComplexQuadrilateral) - - # Validate we cannot assign the None value to mainShape because the 'null' type - # is not one of the allowed types in the 'Shape' schema. - err_msg = (r"Invalid inputs given to generate an instance of .+?Shape.+? " - r"None of the oneOf schemas matched the input data.") - with self.assertRaisesRegex( - petstore_api.ApiValueError, - err_msg - ): - inst = Drawing( - # 'mainShape' has type 'Shape', which is a oneOf [triangle, quadrilateral] - # So the None value should not be allowed and an exception should be raised. - mainShape=None, - ) - - """ - We can pass in a Triangle instance in shapes - Under the hood it is converted into a dict, and that dict payload - does validate as a Shape, so this works - """ - from petstore_api.model.triangle import Triangle - inst = Drawing( - mainShape=isosceles_triangle, - shapes=[ - Triangle( - shapeType="Triangle", - triangleType="EquilateralTriangle" - ) - ] - ) - self.assertEqual(len(inst.shapes), 1) - from petstore_api.model.triangle_interface import TriangleInterface - assert isinstance(inst.shapes[0], shape.Shape) - assert isinstance(inst.shapes[0], Triangle) - assert isinstance(inst.shapes[0], EquilateralTriangle) - assert isinstance(inst.shapes[0], TriangleInterface) - - def test_deserialize_oneof_reference_with_null_type(self): - """ - Validate the scenario when the type of a OAS property is 'oneOf', and the 'oneOf' - schema is specified as a reference ($ref), not an inline 'oneOf' schema. - Further, the 'oneOf' schema has a 'null' type child schema (as introduced in - OpenAPI 3.1). - """ - - # Validate we can assign the None value to shape_or_null, because the 'null' type - # is one of the allowed types in the 'ShapeOrNull' schema. - inst = Drawing( - # 'shapeOrNull' has type 'ShapeOrNull', which is a oneOf [null, triangle, quadrilateral] - shapeOrNull=None, - ) - assert isinstance(inst, Drawing) - self.assertFalse('mainShape' in inst) - self.assertTrue('shapeOrNull' in inst) - self.assertTrue(isinstance(inst.shapeOrNull, NoneClass)) - - def test_deserialize_oneof_reference_with_nullable_type(self): - """ - Validate the scenario when the type of a OAS property is 'oneOf', and the 'oneOf' - schema is specified as a reference ($ref), not an inline 'oneOf' schema. - Further, the 'oneOf' schema has the 'nullable' attribute (as introduced in - OpenAPI 3.0 and deprecated in 3.1). - """ - - # Validate we can assign the None value to nullableShape, because the NullableShape - # has the 'nullable: true' attribute. - inst = Drawing( - # 'nullableShape' has type 'NullableShape', which is a oneOf [triangle, quadrilateral] - # and the 'nullable: true' attribute. - nullableShape=None, - ) - assert isinstance(inst, Drawing) - self.assertFalse('mainShape' in inst) - self.assertTrue('nullableShape' in inst) - self.assertTrue(isinstance(inst.nullableShape, NoneClass)) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fake_api.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fake_api.py deleted file mode 100644 index fb6d11e2af..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fake_api.py +++ /dev/null @@ -1,732 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" -from email.mime import multipart -from email.mime import nonmultipart -import io -import sys -import unittest -import typing -from unittest.mock import patch - -import urllib3 -import petstore_api -from petstore_api import api_client, schemas, exceptions -from petstore_api.api.fake_api import FakeApi # noqa: E501 -from petstore_api.rest import RESTClientObject - -from . import ApiTestMixin - - -class MIMEFormdata(nonmultipart.MIMENonMultipart): - def __init__(self, keyname, *args, **kwargs): - super(MIMEFormdata, self).__init__(*args, **kwargs) - self.add_header( - "Content-Disposition", "form-data; name=\"%s\"" % keyname) - - -class TestFakeApi(ApiTestMixin): - """FakeApi unit test stubs""" - configuration = petstore_api.Configuration() - api = FakeApi(api_client=api_client.ApiClient(configuration=configuration)) - - def test_array_model(self): - from petstore_api.model import animal_farm, animal - - # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_request: - json_data = [{"className": "Cat", "color": "black"}] - mock_request.return_value = self.response( - self.json_bytes(json_data) - ) - - cat = animal.Animal(className="Cat", color="black") - body = animal_farm.AnimalFarm([cat]) - api_response = self.api.array_model(body=body) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', - body=self.json_bytes(json_data) - ) - - assert isinstance(api_response.body, animal_farm.AnimalFarm) - assert api_response.body == body - - def test_recursionlimit(self): - """Test case for recursionlimit - - """ - assert sys.getrecursionlimit() == 1234 - - def test_array_of_enums(self): - from petstore_api.model import array_of_enums, string_enum - - # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_request: - value = [string_enum.StringEnum("placed")] - body = array_of_enums.ArrayOfEnums(value) - value_simple = ["placed"] - mock_request.return_value = self.response( - self.json_bytes(value_simple) - ) - - api_response = self.api.array_of_enums(body=body) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', - body=self.json_bytes(value_simple) - ) - - assert isinstance(api_response.body, array_of_enums.ArrayOfEnums) - assert api_response.body == body - - def test_number_with_validations(self): - from petstore_api.model import number_with_validations - - # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_request: - value = 10.0 - body = number_with_validations.NumberWithValidations(value) - mock_request.return_value = self.response( - self.json_bytes(value) - ) - - api_response = self.api.number_with_validations(body=body) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/refs/number', - body=self.json_bytes(value) - ) - - assert isinstance(api_response.body, number_with_validations.NumberWithValidations) - assert api_response.body == value - - def test_composed_one_of_different_types(self): - from petstore_api.model import composed_one_of_different_types - - # serialization + deserialization works - number = composed_one_of_different_types.ComposedOneOfDifferentTypes(10.0) - cat = composed_one_of_different_types.ComposedOneOfDifferentTypes( - className="Cat", color="black" - ) - none_instance = composed_one_of_different_types.ComposedOneOfDifferentTypes(None) - date_instance = composed_one_of_different_types.ComposedOneOfDifferentTypes('1970-01-01') - cast_to_simple_value = [ - (number, 10.0), - (cat, {"className": "Cat", "color": "black"}), - (none_instance, None), - (date_instance, '1970-01-01'), - ] - for (body, value_simple) in cast_to_simple_value: - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = self.response( - self.json_bytes(value_simple) - ) - - api_response = self.api.composed_one_of_different_types(body=body) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', - body=self.json_bytes(value_simple) - ) - - assert isinstance(api_response.body, composed_one_of_different_types.ComposedOneOfDifferentTypes) - assert api_response.body == body - - # inputting the uncast values into the endpoint also works - for (body, value_simple) in cast_to_simple_value: - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = self.response( - self.json_bytes(value_simple) - ) - - api_response = self.api.composed_one_of_different_types(body=value_simple) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', - body=self.json_bytes(value_simple) - ) - - assert isinstance(api_response.body, composed_one_of_different_types.ComposedOneOfDifferentTypes) - assert api_response.body == body - - def test_string(self): - # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_request: - body = "blah" - value_simple = body - mock_request.return_value = self.response( - self.json_bytes(value_simple) - ) - - api_response = self.api.string(body=body) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/refs/string', - body=self.json_bytes(value_simple) - ) - - assert isinstance(api_response.body, str) - assert api_response.body == value_simple - - def test_string_enum(self): - from petstore_api.model import string_enum - # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_request: - value = "placed" - body = string_enum.StringEnum(value) - mock_request.return_value = self.response( - self.json_bytes(value) - ) - - api_response = self.api.string_enum(body=body) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/refs/enum', - body=self.json_bytes(value) - ) - - assert isinstance(api_response.body, string_enum.StringEnum) - assert api_response.body == value - - def test_mammal(self): - # serialization + deserialization works - from petstore_api.model.mammal import Mammal - with patch.object(RESTClientObject, 'request') as mock_request: - body = Mammal(className="BasquePig") - value_simple = dict(className='BasquePig') - mock_request.return_value = self.response( - self.json_bytes(value_simple) - ) - - api_response = self.api.mammal(body=body) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/refs/mammal', - body=self.json_bytes(value_simple) - ) - - assert isinstance(api_response.body, Mammal) - assert api_response.body == value_simple - - def test_missing_or_unset_required_body(self): - # missing required body - with self.assertRaises(TypeError): - self.api.mammal() - # required body may not be unset - with self.assertRaises(petstore_api.ApiValueError): - self.api.mammal(body=schemas.unset) - - def test_missing_or_unset_required_query_parameter(self): - from petstore_api.model.user import User - user = User({}) - # missing required query param - with self.assertRaises(petstore_api.ApiTypeError): - self.api.body_with_query_params(body=user) - # required query param may not be unset - with self.assertRaises(petstore_api.ApiValueError): - self.api.body_with_query_params(body=schemas.unset, query_params=dict(query=schemas.unset)) - - def test_body_with_query_params(self): - from petstore_api.model import user - with patch.object(RESTClientObject, 'request') as mock_request: - - value_simple = dict( - id=1, - username='first last', - firstName='first', - lastName='last' - ) - body = user.User(**value_simple) - mock_request.return_value = self.response( - b'' - ) - - api_response = self.api.body_with_query_params( - body=body, - query_params=dict(query='hi there') - ) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/body-with-query-params?query=hi%20there', - method='PUT', - body=self.json_bytes(value_simple), - accept_content_type=None - ) - - assert isinstance(api_response.body, api_client.Unset) - assert api_response.response.status == 200 - - def test_upload_download_file_tx_bytes_and_file(self): - """Test case for upload_download_file - uploads a file and downloads a file using application/octet-stream # noqa: E501 - """ - import os - test_file_dir = os.path.realpath( - os.path.join(os.path.dirname(__file__), "..", "testfiles")) - file_name = '1px_pic1.png' - file_path1 = os.path.join(test_file_dir, file_name) - - with open(file_path1, "rb") as some_file: - file_bytes = some_file.read() - file1 = open(file_path1, "rb") - mock_response = self.response( - file_bytes, - content_type='application/octet-stream' - ) - try: - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = mock_response - api_response = self.api.upload_download_file(body=file1) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', - body=file_bytes, - content_type='application/octet-stream', - accept_content_type='application/octet-stream' - ) - self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) - self.assertTrue(isinstance(api_response.body, schemas.BytesSchema)) - self.assertTrue(isinstance(api_response.body, bytes)) - self.assertEqual(api_response.body, file_bytes) - except petstore_api.ApiException as e: - self.fail("upload_file() raised {0} unexpectedly".format(type(e))) - finally: - file1.close() - - # sending just bytes works also - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = mock_response - api_response = self.api.upload_download_file(body=file_bytes) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', - body=file_bytes, - content_type='application/octet-stream', - accept_content_type='application/octet-stream' - ) - self.assertEqual(api_response.body, file_bytes) - - def test_upload_download_file_rx_file(self): - import os - test_file_dir = os.path.realpath( - os.path.join(os.path.dirname(__file__), "..", "testfiles")) - file_name = '1px_pic1.png' - file_path1 = os.path.join(test_file_dir, file_name) - - with open(file_path1, "rb") as some_file: - file_bytes = some_file.read() - - # passing in file1 as the response body simulates a streamed response - file1 = open(file_path1, "rb") - - class StreamableBody: - """ - This class simulates http.client.HTTPResponse for a streamable response - """ - def __init__(self, file: io.BufferedReader): - self.fp = file - - def read(self, *args, **kwargs): - return self.fp.read(*args, **kwargs) - - def close(self): - self.fp.close() - - streamable_body = StreamableBody(file1) - - mock_response = self.response( - streamable_body, - content_type='application/octet-stream', - preload_content=False - ) - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = mock_response - api_response = self.api.upload_download_file(body=file_bytes, stream=True) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', - body=file_bytes, - content_type='application/octet-stream', - accept_content_type='application/octet-stream', - stream=True - ) - self.assertTrue(file1.closed) - self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) - self.assertTrue(isinstance(api_response.body, schemas.FileSchema)) - self.assertTrue(isinstance(api_response.body, schemas.FileIO)) - self.assertEqual(api_response.body.read(), file_bytes) - api_response.body.close() - os.unlink(api_response.body.name) - - file1 = open(file_path1, "rb") - streamable_body = StreamableBody(file1) - saved_file_name = "fileName.abc" - - """ - when streaming is used and the response contains the content disposition header with a filename - that filename is used when saving the file locally - """ - mock_response = self.response( - streamable_body, - content_type='application/octet-stream', - headers={'content-disposition': f'attachment; filename="{saved_file_name}"'}, - preload_content=False - ) - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = mock_response - api_response = self.api.upload_download_file(body=file_bytes, stream=True) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', - body=file_bytes, - content_type='application/octet-stream', - accept_content_type='application/octet-stream', - stream=True - ) - self.assertTrue(file1.closed) - self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) - self.assertTrue(isinstance(api_response.body, schemas.FileSchema)) - self.assertTrue(isinstance(api_response.body, schemas.FileIO)) - self.assertTrue(api_response.body.name.endswith(saved_file_name)) - self.assertEqual(api_response.body.read(), file_bytes) - api_response.body.close() - os.unlink(api_response.body.name) - - def test_upload_file(self): - """Test case for upload_file - uploads a file using multipart/form-data # noqa: E501 - """ - import os - test_file_dir = os.path.realpath( - os.path.join(os.path.dirname(__file__), "..", "testfiles")) - file_name = '1px_pic1.png' - file_path1 = os.path.join(test_file_dir, file_name) - - with open(file_path1, "rb") as some_file: - file_bytes = some_file.read() - file1 = open(file_path1, "rb") - response_json = { - 'code': 200, - 'type': 'blah', - 'message': 'file upload succeeded' - } - try: - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = self.response( - self.json_bytes(response_json) - ) - api_response = self.api.upload_file(body={'file': file1}) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/uploadFile', - fields=( - api_client.RequestField( - name='file', - data=file_bytes, - filename=file_name, - headers={'Content-Type': 'application/octet-stream'} - ), - ), - content_type='multipart/form-data' - ) - self.assertEqual(api_response.body, response_json) - except petstore_api.ApiException as e: - self.fail("upload_file() raised {0} unexpectedly".format(type(e))) - finally: - file1.close() - - # sending just bytes works also - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = self.response( - self.json_bytes(response_json) - ) - api_response = self.api.upload_file(body={'file': file_bytes}) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/uploadFile', - fields=( - api_client.RequestField( - name='file', - data=file_bytes, - headers={'Content-Type': 'application/octet-stream'} - ), - ), - content_type='multipart/form-data' - ) - self.assertEqual(api_response.body, response_json) - - # passing in an array of files to when file only allows one - # raises an exceptions - try: - file = open(file_path1, "rb") - with self.assertRaises(petstore_api.ApiTypeError): - self.api.upload_file(body={'file': [file]}) - finally: - file.close() - - # passing in a closed file raises an exception - with self.assertRaises(ValueError): - file = open(file_path1, "rb") - file.close() - self.api.upload_file(body={'file': file}) - - def test_upload_files(self): - """Test case for upload_files - uploads files using multipart/form-data # noqa: E501 - """ - import os - test_file_dir = os.path.realpath( - os.path.join(os.path.dirname(__file__), "..", "testfiles")) - file_name = '1px_pic1.png' - file_path1 = os.path.join(test_file_dir, file_name) - - with open(file_path1, "rb") as some_file: - file_bytes = some_file.read() - file1 = open(file_path1, "rb") - file2 = open(file_path1, "rb") - response_json = { - 'code': 200, - 'type': 'blah', - 'message': 'file upload succeeded' - } - try: - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = self.response( - self.json_bytes(response_json) - ) - api_response = self.api.upload_files(body={'files': [file1, file2]}) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/uploadFiles', - fields=( - api_client.RequestField( - name='files', - data=file_bytes, - filename=file_name, - headers={'Content-Type': 'application/octet-stream'} - ), - api_client.RequestField( - name='files', - data=file_bytes, - filename=file_name, - headers={'Content-Type': 'application/octet-stream'} - ), - ), - content_type='multipart/form-data' - ) - self.assertEqual(api_response.body, response_json) - except petstore_api.ApiException as e: - self.fail("upload_file() raised {0} unexpectedly".format(type(e))) - finally: - file1.close() - file2.close() - - # sending just bytes works also - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = self.response( - self.json_bytes(response_json) - ) - api_response = self.api.upload_files(body={'files': [file_bytes, file_bytes]}) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/uploadFiles', - fields=( - api_client.RequestField( - name='files', - data=file_bytes, - headers={'Content-Type': 'application/octet-stream'} - ), - api_client.RequestField( - name='files', - data=file_bytes, - headers={'Content-Type': 'application/octet-stream'} - ), - ), - content_type='multipart/form-data' - ) - self.assertEqual(api_response.body, response_json) - - @staticmethod - def __encode_multipart_formdata(fields: typing.Dict[str, typing.Any]) -> multipart.MIMEMultipart: - m = multipart.MIMEMultipart("form-data") - - for field, value in fields.items(): - data = MIMEFormdata(field, "text", "plain") - # data.set_payload(value, charset='us-ascii') - data.set_payload(value) - m.attach(data) - - return m - - @patch.object(RESTClientObject, 'request') - def test_inline_composition(self, mock_request): - """Test case for inline_composition - - testing composed schemas at inline locations # noqa: E501 - """ - single_char_str = 'a' - json_bytes = self.json_bytes(single_char_str) - - # tx and rx json with composition at root level of schema for request + response body - content_type = 'application/json' - mock_request.return_value = self.response( - json_bytes - ) - api_response = self.api.inline_composition( - body=single_char_str, - query_params={ - 'compositionAtRoot': single_char_str, - 'compositionInProperty': {'someProp': single_char_str} - }, - accept_content_types=(content_type,) - ) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/inlineComposition/?compositionAtRoot=a&someProp=a', - accept_content_type=content_type, - content_type=content_type, - body=json_bytes - ) - self.assertEqual(api_response.body, single_char_str) - self.assertTrue(isinstance(api_response.body, schemas.StrSchema)) - - # tx and rx json with composition at property level of schema for request + response body - content_type = 'multipart/form-data' - multipart_response = self.__encode_multipart_formdata(fields={'someProp': single_char_str}) - mock_request.return_value = self.response( - bytes(multipart_response), - content_type=multipart_response.get_content_type() - ) - api_response = self.api.inline_composition( - body={'someProp': single_char_str}, - query_params={ - 'compositionAtRoot': single_char_str, - 'compositionInProperty': {'someProp': single_char_str} - }, - content_type=content_type, - accept_content_types=(content_type,) - ) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/inlineComposition/?compositionAtRoot=a&someProp=a', - accept_content_type=content_type, - content_type=content_type, - fields=( - api_client.RequestField( - name='someProp', - data=single_char_str, - headers={'Content-Type': 'text/plain'} - ), - ), - ) - self.assertEqual(api_response.body, {'someProp': single_char_str}) - self.assertTrue(isinstance(api_response.body.someProp, schemas.StrSchema)) - - # error thrown when a str is input which doesn't meet the composed schema length constraint - invalid_value = '' - variable_locations = 4 - for invalid_index in range(variable_locations): - values = [single_char_str]*variable_locations - values[invalid_index] = invalid_value - with self.assertRaises(exceptions.ApiValueError): - multipart_response = self.__encode_multipart_formdata(fields={'someProp': values[0]}) - mock_request.return_value = self.response( - bytes(multipart_response), - content_type=multipart_response.get_content_type() - ) - self.api.inline_composition( - body={'someProp': values[1]}, - query_params={ - 'compositionAtRoot': values[2], - 'compositionInProperty': {'someProp': values[3]} - }, - content_type=content_type, - accept_content_types=(content_type,) - ) - - def test_json_with_charset(self): - # serialization + deserialization of json with charset works - with patch.object(RESTClientObject, 'request') as mock_request: - body = None - content_type_with_charset = 'application/json; charset=utf-8' - mock_request.return_value = self.response( - self.json_bytes(body), - content_type=content_type_with_charset - ) - - api_response = self.api.json_with_charset(body=body) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/jsonWithCharset', - body=self.json_bytes(body), - content_type=content_type_with_charset, - accept_content_type=content_type_with_charset - ) - - assert isinstance(api_response.body, schemas.AnyTypeSchema) - assert isinstance(api_response.body, schemas.NoneClass) - assert api_response.body.is_none() - - def test_response_without_schema(self): - # received response is not loaded into body because there is no deserialization schema defined - with patch.object(RESTClientObject, 'request') as mock_request: - body = None - content_type = 'application/json' - mock_request.return_value = self.response( - self.json_bytes(body), - ) - - api_response = self.api.response_without_schema() - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/responseWithoutSchema', - method='GET', - accept_content_type='application/json, application/xml', - content_type=None - ) - - assert isinstance(api_response.body, schemas.Unset) - - - with patch.object(RESTClientObject, 'request') as mock_request: - mock_request.return_value = self.response( - 'blah', - content_type='text/plain' - ) - - # when an incorrect content-type is sent back, and exception is raised - with self.assertRaises(exceptions.ApiValueError): - self.api.response_without_schema() - - def test_delete_endpoint_without_request_body(self): - with patch.object(urllib3.PoolManager, 'request') as mock_request: - - body = None - mock_request.return_value = self.response( - self.json_bytes(body), - ) - - api_response = self.api.delete_coffee(path_params=dict(id='1')) - self.assert_pool_manager_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/fake/deleteCoffee/1', - method='DELETE', - content_type=None, - accept_content_type=None, - ) - - assert isinstance(api_response.response, urllib3.HTTPResponse) - assert isinstance(api_response.body, schemas.Unset) - assert isinstance(api_response.headers, schemas.Unset) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_format_test.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_format_test.py deleted file mode 100644 index 9157839531..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_format_test.py +++ /dev/null @@ -1,134 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from decimal import Decimal -import datetime -import unittest - -import petstore_api -from petstore_api.model.format_test import FormatTest -from petstore_api.schemas import BinarySchema, BytesSchema, frozendict, Singleton - - -class TestFormatTest(unittest.TestCase): - """FormatTest unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_FormatTest(self): - """Test FormatTest""" - - required_args = dict( - number=32.5, - byte='a', - date='2021-01-01', - password='abcdefghij' - ) - # int32 - # under min - with self.assertRaises(petstore_api.ApiValueError): - model = FormatTest(int32=-2147483649, **required_args) - # over max - with self.assertRaises(petstore_api.ApiValueError): - model = FormatTest(int32=2147483648, **required_args) - # valid values in range work - valid_values = [-2147483648, 2147483647] - for valid_value in valid_values: - model = FormatTest(int32=valid_value, **required_args) - assert model.int32 == valid_value - - # int64 - # under min - with self.assertRaises(petstore_api.ApiValueError): - model = FormatTest(int64=-9223372036854775809, **required_args) - # over max - with self.assertRaises(petstore_api.ApiValueError): - model = FormatTest(int64=9223372036854775808, **required_args) - # valid values in range work - valid_values = [-9223372036854775808, 9223372036854775807] - for valid_value in valid_values: - model = FormatTest(int64=valid_value, **required_args) - assert model.int64 == valid_value - - # float32 - # under min - with self.assertRaises(petstore_api.ApiValueError): - model = FormatTest(float32=-3.402823466385289e+38, **required_args) - # over max - with self.assertRaises(petstore_api.ApiValueError): - model = FormatTest(float32=3.402823466385289e+38, **required_args) - # valid values in range work - valid_values = [-3.4028234663852886e+38, 3.4028234663852886e+38] - for valid_value in valid_values: - model = FormatTest(float32=valid_value, **required_args) - assert model.float32 == valid_value - - # float64 - # under min, Decimal is used because flat can only store 64bit numbers and the max and min - # take up more space than 64bit - with self.assertRaises(petstore_api.ApiValueError): - model = FormatTest(float64=Decimal('-1.7976931348623157082e+308'), **required_args) - # over max - with self.assertRaises(petstore_api.ApiValueError): - model = FormatTest(float64=Decimal('1.7976931348623157082e+308'), **required_args) - valid_values = [-1.7976931348623157E+308, 1.7976931348623157E+308] - for valid_value in valid_values: - model = FormatTest(float64=valid_value, **required_args) - assert model.float64 == valid_value - - # unique_items with duplicates throws exception - with self.assertRaises(petstore_api.ApiValueError): - model = FormatTest(arrayWithUniqueItems=[0, 1, 1], **required_args) - # no duplicates works - values = [0, 1, 2] - model = FormatTest(arrayWithUniqueItems=values, **required_args) - assert model.arrayWithUniqueItems == tuple(values) - - # __bool__ value of noneProp is False - model = FormatTest(noneProp=None, **required_args) - assert isinstance(model.noneProp, Singleton) - self.assertFalse(model.noneProp) - self.assertTrue(model.noneProp.is_none()) - - # binary check - model = FormatTest(binary=b'123', **required_args) - assert isinstance(model.binary, BinarySchema) - assert isinstance(model.binary, BytesSchema) - assert isinstance(model.binary, bytes) - assert model == frozendict( - binary=b'123', - number=Decimal(32.5), - byte='a', - date='2021-01-01', - password='abcdefghij' - ) - - def test_multiple_of(self): - with self.assertRaisesRegex( - petstore_api.exceptions.ApiValueError, - r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)" - ): - inst = FormatTest( - byte='3', - date=datetime.date(2000, 1, 1), - password="abcdefghijkl", - integer=31, # Value is supposed to be multiple of '2'. An error must be raised - number=65.0, - float=62.4 - ) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fruit.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fruit.py deleted file mode 100644 index ae41790e48..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fruit.py +++ /dev/null @@ -1,171 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from datetime import date -import unittest - -import petstore_api -from petstore_api.model import apple -from petstore_api.model import banana -from petstore_api.model.fruit import Fruit -from petstore_api.schemas import Singleton - - -class TestFruit(unittest.TestCase): - """Fruit unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testFruit(self): - """Test Fruit""" - - # make an instance of Fruit, a composed schema oneOf model - # banana test - length_cm = 20.3 - color = 'yellow' - fruit = Fruit(lengthCm=length_cm, color=color) - # check its properties - self.assertEqual(fruit.lengthCm, length_cm) - self.assertEqual(fruit['lengthCm'], length_cm) - self.assertEqual(fruit.get('lengthCm'), length_cm) - self.assertEqual(getattr(fruit, 'lengthCm'), length_cm) - self.assertEqual(fruit.color, color) - self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) - # check the dict representation - self.assertEqual( - fruit, - { - 'lengthCm': length_cm, - 'color': color - } - ) - # setting values after instance creation is not allowed - with self.assertRaises(TypeError): - fruit['color'] = 'some value' - - # Assert that we can call the builtin hasattr() function. - # hasattr should return False for non-existent attribute. - # Internally hasattr catches the AttributeError exception. - self.assertFalse(hasattr(fruit, 'invalid_variable')) - - # Assert that we can call the builtin hasattr() function. - # hasattr should return True for existent attribute. - self.assertTrue(hasattr(fruit, 'color')) - - # getting a value that doesn't exist raises an exception - # with a key - with self.assertRaises(KeyError): - fruit['cultivar'] - # with getattr - # Per Python doc, if the named attribute does not exist, - # default is returned if provided. - self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value') - self.assertEqual(fruit.get('cultivar'), None) - self.assertEqual(fruit.get('cultivar', 'some value'), 'some value') - - # Per Python doc, if the named attribute does not exist, - # default is returned if provided, otherwise AttributeError is raised. - with self.assertRaises(AttributeError): - getattr(fruit, 'cultivar') - - # make sure that the ModelComposed class properties are correct - # model._composed_schemas stores the anyOf/allOf/oneOf info - self.assertEqual( - fruit._composed_schemas, - { - 'anyOf': [], - 'allOf': [], - 'oneOf': [ - apple.Apple, - banana.Banana, - ], - 'not': None - } - ) - - """ - including extra parameters does not raise an exception - because objects support additional properties by default - """ - kwargs = dict( - color=color, - lengthCm=length_cm, - additional_string='some value', - additional_date='2021-01-02', - ) - - fruit = Fruit._from_openapi_data(**kwargs) - self.assertEqual( - fruit, - kwargs - ) - - fruit = Fruit(**kwargs) - self.assertEqual( - fruit, - kwargs - ) - - # including input parameters for two oneOf instances raise an exception - with self.assertRaises(petstore_api.ApiValueError): - Fruit( - lengthCm=length_cm, - cultivar='granny smith' - ) - - # make an instance of Fruit, a composed schema oneOf model - # apple test - color = 'red' - cultivar = 'golden delicious' - fruit = Fruit(color=color, cultivar=cultivar) - # check its properties - self.assertEqual(fruit.color, color) - self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) - self.assertEqual(fruit.cultivar, cultivar) - self.assertEqual(fruit['cultivar'], cultivar) - self.assertEqual(getattr(fruit, 'cultivar'), cultivar) - # check the dict representation - self.assertEqual( - fruit, - { - 'color': color, - 'cultivar': cultivar - } - ) - - def testFruitNullValue(self): - # Since 'apple' is nullable, validate we can create an apple with the 'null' value. - fruit = apple.Apple(None) - assert isinstance(fruit, Singleton) - assert isinstance(fruit, apple.Apple) - assert fruit.is_none() is True - - # 'banana' is not nullable. - # TODO cast this into ApiTypeError? - with self.assertRaises(TypeError): - banana.Banana(None) - - # Since 'fruit' has oneOf 'apple', 'banana' and 'apple' is nullable, - # validate we can create a fruit with the 'null' value. - fruit = Fruit(None) - assert isinstance(fruit, Singleton) - assert isinstance(fruit, apple.Apple) - assert isinstance(fruit, Fruit) - assert fruit.is_none() is True - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fruit_req.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fruit_req.py deleted file mode 100644 index 1f4f89947d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fruit_req.py +++ /dev/null @@ -1,123 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.model import apple_req -from petstore_api.model import banana_req -from petstore_api.model.fruit_req import FruitReq -from petstore_api.schemas import NoneSchema, Singleton - - -class TestFruitReq(unittest.TestCase): - """FruitReq unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testFruitReq(self): - """Test FruitReq""" - - # make an instance of Fruit, a composed schema oneOf model - # banana test - length_cm = 20.3 - fruit = FruitReq(lengthCm=length_cm) - # check its properties - self.assertEqual(fruit.lengthCm, length_cm) - self.assertEqual(fruit['lengthCm'], length_cm) - self.assertEqual(getattr(fruit, 'lengthCm'), length_cm) - # check the dict representation - self.assertEqual( - fruit, - { - 'lengthCm': length_cm, - } - ) - # setting values after instance creation is not allowed - with self.assertRaises(TypeError): - fruit['lengthCm'] = 'some value' - - # setting values after instance creation is not allowed - with self.assertRaises(AttributeError): - setattr(fruit, 'lengthCm', 'some value') - - # getting a value that doesn't exist raises an exception - # with a key - with self.assertRaises(KeyError): - invalid_variable = fruit['cultivar'] - - # with getattr - self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value') - - with self.assertRaises(AttributeError): - getattr(fruit, 'cultivar') - - # make sure that the ModelComposed class properties are correct - # model._composed_schemas stores the anyOf/allOf/oneOf info - self.assertEqual( - fruit._composed_schemas, - { - 'anyOf': [], - 'allOf': [], - 'oneOf': [ - NoneSchema, - apple_req.AppleReq, - banana_req.BananaReq, - ], - 'not': None - } - ) - - # including extra parameters raises an exception - with self.assertRaises(petstore_api.ApiValueError): - fruit = FruitReq( - length_cm=length_cm, - unknown_property='some value' - ) - - # including input parameters for two oneOf instances raise an exception - with self.assertRaises(petstore_api.ApiValueError): - fruit = FruitReq( - length_cm=length_cm, - cultivar='granny smith' - ) - - # make an instance of Fruit, a composed schema oneOf model - # apple test - cultivar = 'golden delicious' - fruit = FruitReq(cultivar=cultivar) - # check its properties - self.assertEqual(fruit.cultivar, cultivar) - self.assertEqual(fruit['cultivar'], cultivar) - self.assertEqual(getattr(fruit, 'cultivar'), cultivar) - # check the dict representation - self.assertEqual( - fruit, - { - 'cultivar': cultivar - } - ) - - # we can pass in None - fruit = FruitReq(None) - assert isinstance(fruit, Singleton) - assert isinstance(fruit, FruitReq) - assert isinstance(fruit, NoneSchema) - assert fruit.is_none() is True - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_gm_fruit.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_gm_fruit.py deleted file mode 100644 index 22df654e3b..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_gm_fruit.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.model import apple -from petstore_api.model import banana -from petstore_api.model.gm_fruit import GmFruit -from petstore_api.schemas import frozendict - -class TestGmFruit(unittest.TestCase): - """GmFruit unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testGmFruit(self): - """Test GmFruit""" - - # make an instance of GmFruit, a composed schema anyOf model - # banana test - length_cm = 20.3 - color = 'yellow' - cultivar = 'banaple' - fruit = GmFruit(lengthCm=length_cm, color=color, cultivar=cultivar) - assert isinstance(fruit, GmFruit) - assert isinstance(fruit, banana.Banana) - assert isinstance(fruit, apple.Apple) - assert isinstance(fruit, frozendict) - # check its properties - self.assertEqual(fruit.lengthCm, length_cm) - self.assertEqual(fruit['lengthCm'], length_cm) - self.assertEqual(getattr(fruit, 'lengthCm'), length_cm) - self.assertEqual(fruit.color, color) - self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) - # check the dict representation - self.assertEqual( - fruit, - { - 'lengthCm': length_cm, - 'color': color, - 'cultivar': cultivar - } - ) - - with self.assertRaises(KeyError): - invalid_variable = fruit['origin'] - # with getattr - self.assertTrue(getattr(fruit, 'origin', 'some value'), 'some value') - - # make sure that the ModelComposed class properties are correct - # model._composed_schemas stores the anyOf/allOf/oneOf info - self.assertEqual( - fruit._composed_schemas, - { - 'anyOf': [ - apple.Apple, - banana.Banana, - ], - 'allOf': [], - 'oneOf': [], - 'not': None - } - ) - - # including extra parameters works - fruit = GmFruit( - color=color, - length_cm=length_cm, - cultivar=cultivar, - unknown_property='some value' - ) - - # including input parameters for both anyOf instances works - color = 'orange' - color_stored = b'orange' - fruit = GmFruit( - color=color, - cultivar=cultivar, - length_cm=length_cm - ) - self.assertEqual(fruit.color, color) - self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) - self.assertEqual(fruit.cultivar, cultivar) - self.assertEqual(fruit['cultivar'], cultivar) - self.assertEqual(getattr(fruit, 'cultivar'), cultivar) - self.assertEqual(fruit.length_cm, length_cm) - self.assertEqual(fruit['length_cm'], length_cm) - self.assertEqual(getattr(fruit, 'length_cm'), length_cm) - - # make an instance of GmFruit, a composed schema anyOf model - # apple test - color = 'red' - cultivar = 'golden delicious' - origin = 'California' - fruit = GmFruit(color=color, cultivar=cultivar, origin=origin) - # check its properties - self.assertEqual(fruit.color, color) - self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) - self.assertEqual(fruit.cultivar, cultivar) - self.assertEqual(fruit['cultivar'], cultivar) - self.assertEqual(getattr(fruit, 'cultivar'), cultivar) - - self.assertEqual(fruit.origin, origin) - self.assertEqual(fruit['origin'], origin) - self.assertEqual(getattr(fruit, 'origin'), origin) - - # check the dict representation - self.assertEqual( - fruit, - { - 'color': color, - 'cultivar': cultivar, - 'origin': origin, - } - ) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_http_signature.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_http_signature.py deleted file mode 100644 index 9783829e30..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_http_signature.py +++ /dev/null @@ -1,518 +0,0 @@ -# # coding: utf-8 -# -# # flake8: noqa -# -# """ -# Run the tests. -# $ docker pull swaggerapi/petstore -# $ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore -# $ pip install nose (optional) -# $ cd petstore_api-python -# $ nosetests -v -# """ -# -# from collections import namedtuple -# from datetime import datetime, timedelta -# import base64 -# import json -# import os -# import re -# import shutil -# import unittest -# from urllib.parse import urlencode, urlparse -# -# from Crypto.Hash import SHA256, SHA512 -# from Crypto.PublicKey import ECC, RSA -# from Crypto.Signature import pkcs1_15, pss, DSS -# -# import petstore_api -# from petstore_api.model import category, tag, pet -# from petstore_api.api.pet_api import PetApi -# from petstore_api import Configuration, signing -# from petstore_api.rest import ( -# RESTClientObject, -# RESTResponse -# ) -# -# from petstore_api.exceptions import ( -# ApiException, -# ApiValueError, -# ApiTypeError, -# ) -# -# from .util import id_gen -# -# import urllib3 -# -# from unittest.mock import patch -# -# HOST = 'http://localhost/v2' -# -# # This test RSA private key below is published in Appendix C 'Test Values' of -# # https://www.ietf.org/id/draft-cavage-http-signatures-12.txt -# RSA_TEST_PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY----- -# MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF -# NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F -# UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB -# AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA -# QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK -# kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg -# f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u -# 412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc -# mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 -# kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA -# gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW -# G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI -# 7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== -# -----END RSA PRIVATE KEY-----""" -# -# -# class TimeoutWithEqual(urllib3.Timeout): -# def __init__(self, *arg, **kwargs): -# super(TimeoutWithEqual, self).__init__(*arg, **kwargs) -# -# def __eq__(self, other): -# return self._read == other._read and self._connect == other._connect and self.total == other.total -# -# class MockPoolManager(object): -# def __init__(self, tc): -# self._tc = tc -# self._reqs = [] -# -# def expect_request(self, *args, **kwargs): -# self._reqs.append((args, kwargs)) -# -# def set_signing_config(self, signing_cfg): -# self.signing_cfg = signing_cfg -# self._tc.assertIsNotNone(self.signing_cfg) -# self.pubkey = self.signing_cfg.get_public_key() -# self._tc.assertIsNotNone(self.pubkey) -# -# def request(self, *actual_request_target, **actual_request_headers_and_body): -# self._tc.assertTrue(len(self._reqs) > 0) -# expected_results = self._reqs.pop(0) -# self._tc.maxDiff = None -# expected_request_target = expected_results[0] # The expected HTTP method and URL path. -# expected_request_headers_and_body = expected_results[1] # dict that contains the expected body, headers -# self._tc.assertEqual(expected_request_target, actual_request_target) -# # actual_request_headers_and_body is a dict that contains the actual body, headers -# for k, expected in expected_request_headers_and_body.items(): -# self._tc.assertIn(k, actual_request_headers_and_body) -# if k == 'body': -# actual_body = actual_request_headers_and_body[k] -# self._tc.assertEqual(expected, actual_body) -# elif k == 'headers': -# actual_headers = actual_request_headers_and_body[k] -# for expected_header_name, expected_header_value in expected.items(): -# # Validate the generated request contains the expected header. -# self._tc.assertIn(expected_header_name, actual_headers) -# actual_header_value = actual_headers[expected_header_name] -# # Compare the actual value of the header against the expected value. -# pattern = re.compile(expected_header_value) -# m = pattern.match(actual_header_value) -# self._tc.assertTrue(m, msg="Expected:\n{0}\nActual:\n{1}".format( -# expected_header_value,actual_header_value)) -# if expected_header_name == 'Authorization': -# self._validate_authorization_header( -# expected_request_target, actual_headers, actual_header_value) -# elif k == 'timeout': -# self._tc.assertEqual(expected, actual_request_headers_and_body[k]) -# return urllib3.HTTPResponse(status=200, body=b'test') -# -# def _validate_authorization_header(self, request_target, actual_headers, authorization_header): -# """Validate the signature. -# """ -# # Extract (created) -# r1 = re.compile(r'created=([0-9]+)') -# m1 = r1.search(authorization_header) -# self._tc.assertIsNotNone(m1) -# created = m1.group(1) -# -# # Extract list of signed headers -# r1 = re.compile(r'headers="([^"]+)"') -# m1 = r1.search(authorization_header) -# self._tc.assertIsNotNone(m1) -# headers = m1.group(1).split(' ') -# signed_headers_list = [] -# for h in headers: -# if h == '(created)': -# signed_headers_list.append((h, created)) -# elif h == '(request-target)': -# url = request_target[1] -# target_path = urlparse(url).path -# signed_headers_list.append((h, "{0} {1}".format(request_target[0].lower(), target_path))) -# else: -# value = next((v for k, v in actual_headers.items() if k.lower() == h), None) -# self._tc.assertIsNotNone(value) -# signed_headers_list.append((h, value)) -# header_items = [ -# "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list] -# string_to_sign = "\n".join(header_items) -# digest = None -# if self.signing_cfg.hash_algorithm == signing.HASH_SHA512: -# digest = SHA512.new() -# elif self.signing_cfg.hash_algorithm == signing.HASH_SHA256: -# digest = SHA256.new() -# else: -# self._tc.fail("Unsupported hash algorithm: {0}".format(self.signing_cfg.hash_algorithm)) -# digest.update(string_to_sign.encode()) -# b64_body_digest = base64.b64encode(digest.digest()).decode() -# -# # Extract the signature -# r2 = re.compile(r'signature="([^"]+)"') -# m2 = r2.search(authorization_header) -# self._tc.assertIsNotNone(m2) -# b64_signature = m2.group(1) -# signature = base64.b64decode(b64_signature) -# # Build the message -# signing_alg = self.signing_cfg.signing_algorithm -# if signing_alg is None: -# # Determine default -# if isinstance(self.pubkey, RSA.RsaKey): -# signing_alg = signing.ALGORITHM_RSASSA_PSS -# elif isinstance(self.pubkey, ECC.EccKey): -# signing_alg = signing.ALGORITHM_ECDSA_MODE_FIPS_186_3 -# else: -# self._tc.fail("Unsupported key: {0}".format(type(self.pubkey))) -# -# if signing_alg == signing.ALGORITHM_RSASSA_PKCS1v15: -# pkcs1_15.new(self.pubkey).verify(digest, signature) -# elif signing_alg == signing.ALGORITHM_RSASSA_PSS: -# pss.new(self.pubkey).verify(digest, signature) -# elif signing_alg == signing.ALGORITHM_ECDSA_MODE_FIPS_186_3: -# verifier = DSS.new(key=self.pubkey, mode=signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, -# encoding='der') -# verifier.verify(digest, signature) -# elif signing_alg == signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979: -# verifier = DSS.new(key=self.pubkey, mode=signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979, -# encoding='der') -# verifier.verify(digest, signature) -# else: -# self._tc.fail("Unsupported signing algorithm: {0}".format(signing_alg)) -# -# class PetApiTests(unittest.TestCase): -# -# @classmethod -# def setUpClass(cls): -# cls.setUpModels() -# cls.setUpFiles() -# -# @classmethod -# def tearDownClass(cls): -# file_paths = [ -# cls.rsa_key_path, -# cls.rsa4096_key_path, -# cls.ec_p521_key_path, -# ] -# for file_path in file_paths: -# os.unlink(file_path) -# -# @classmethod -# def setUpModels(cls): -# cls.category = category.Category() -# cls.category.id = id_gen() -# cls.category.name = "dog" -# cls.tag = tag.Tag() -# cls.tag.id = id_gen() -# cls.tag.name = "python-pet-tag" -# cls.pet = pet.Pet( -# name="hello kity", -# photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"] -# ) -# cls.pet.id = id_gen() -# cls.pet.status = "sold" -# cls.pet.category = cls.category -# cls.pet.tags = [cls.tag] -# -# @classmethod -# def setUpFiles(cls): -# cls.test_file_dir = os.path.join( -# os.path.dirname(__file__), "..", "testfiles") -# cls.test_file_dir = os.path.realpath(cls.test_file_dir) -# if not os.path.exists(cls.test_file_dir): -# os.mkdir(cls.test_file_dir) -# -# cls.private_key_passphrase = 'test-passphrase' -# cls.rsa_key_path = os.path.join(cls.test_file_dir, 'rsa.pem') -# cls.rsa4096_key_path = os.path.join(cls.test_file_dir, 'rsa4096.pem') -# cls.ec_p521_key_path = os.path.join(cls.test_file_dir, 'ecP521.pem') -# -# if not os.path.exists(cls.rsa_key_path): -# with open(cls.rsa_key_path, 'w') as f: -# f.write(RSA_TEST_PRIVATE_KEY) -# -# if not os.path.exists(cls.rsa4096_key_path): -# key = RSA.generate(4096) -# private_key = key.export_key( -# passphrase=cls.private_key_passphrase, -# protection='PEM' -# ) -# with open(cls.rsa4096_key_path, "wb") as f: -# f.write(private_key) -# -# if not os.path.exists(cls.ec_p521_key_path): -# key = ECC.generate(curve='P-521') -# private_key = key.export_key( -# format='PEM', -# passphrase=cls.private_key_passphrase, -# use_pkcs8=True, -# protection='PBKDF2WithHMAC-SHA1AndAES128-CBC' -# ) -# with open(cls.ec_p521_key_path, "wt") as f: -# f.write(private_key) -# -# def test_valid_http_signature(self): -# privkey_path = self.rsa_key_path -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path=privkey_path, -# private_key_passphrase=self.private_key_passphrase, -# signing_algorithm=signing.ALGORITHM_RSASSA_PKCS1v15, -# signed_headers=[ -# signing.HEADER_REQUEST_TARGET, -# signing.HEADER_CREATED, -# signing.HEADER_HOST, -# signing.HEADER_DATE, -# signing.HEADER_DIGEST, -# 'Content-Type' -# ] -# ) -# config = Configuration(host=HOST, signing_info=signing_cfg) -# # Set the OAuth2 acces_token to None. Here we are interested in testing -# # the HTTP signature scheme. -# config.access_token = None -# -# api_client = petstore_api.ApiClient(config) -# pet_api = PetApi(api_client) -# -# mock_pool = MockPoolManager(self) -# api_client.rest_client.pool_manager = mock_pool -# -# mock_pool.set_signing_config(signing_cfg) -# mock_pool.expect_request('POST', HOST + '/pet', -# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), -# headers={'Content-Type': r'application/json', -# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' -# r'headers="\(request-target\) \(created\) host date digest content-type",' -# r'signature="[a-zA-Z0-9+/=]+"', -# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, -# preload_content=True, timeout=None) -# -# pet_api.add_pet(self.pet) -# -# def test_valid_http_signature_with_defaults(self): -# privkey_path = self.rsa4096_key_path -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path=privkey_path, -# private_key_passphrase=self.private_key_passphrase, -# ) -# config = Configuration(host=HOST, signing_info=signing_cfg) -# # Set the OAuth2 acces_token to None. Here we are interested in testing -# # the HTTP signature scheme. -# config.access_token = None -# -# api_client = petstore_api.ApiClient(config) -# pet_api = PetApi(api_client) -# -# mock_pool = MockPoolManager(self) -# api_client.rest_client.pool_manager = mock_pool -# -# mock_pool.set_signing_config(signing_cfg) -# mock_pool.expect_request('POST', HOST + '/pet', -# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), -# headers={'Content-Type': r'application/json', -# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' -# r'headers="\(created\)",' -# r'signature="[a-zA-Z0-9+/=]+"', -# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, -# preload_content=True, timeout=None) -# -# pet_api.add_pet(self.pet) -# -# def test_valid_http_signature_rsassa_pkcs1v15(self): -# privkey_path = self.rsa4096_key_path -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path=privkey_path, -# private_key_passphrase=self.private_key_passphrase, -# signing_algorithm=signing.ALGORITHM_RSASSA_PKCS1v15, -# signed_headers=[ -# signing.HEADER_REQUEST_TARGET, -# signing.HEADER_CREATED, -# ] -# ) -# config = Configuration(host=HOST, signing_info=signing_cfg) -# # Set the OAuth2 acces_token to None. Here we are interested in testing -# # the HTTP signature scheme. -# config.access_token = None -# -# api_client = petstore_api.ApiClient(config) -# pet_api = PetApi(api_client) -# -# mock_pool = MockPoolManager(self) -# api_client.rest_client.pool_manager = mock_pool -# -# mock_pool.set_signing_config(signing_cfg) -# mock_pool.expect_request('POST', HOST + '/pet', -# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), -# headers={'Content-Type': r'application/json', -# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' -# r'headers="\(request-target\) \(created\)",' -# r'signature="[a-zA-Z0-9+/=]+"', -# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, -# preload_content=True, timeout=None) -# -# pet_api.add_pet(self.pet) -# -# def test_valid_http_signature_rsassa_pss(self): -# privkey_path = self.rsa4096_key_path -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path=privkey_path, -# private_key_passphrase=self.private_key_passphrase, -# signing_algorithm=signing.ALGORITHM_RSASSA_PSS, -# signed_headers=[ -# signing.HEADER_REQUEST_TARGET, -# signing.HEADER_CREATED, -# ] -# ) -# config = Configuration(host=HOST, signing_info=signing_cfg) -# # Set the OAuth2 acces_token to None. Here we are interested in testing -# # the HTTP signature scheme. -# config.access_token = None -# -# api_client = petstore_api.ApiClient(config) -# pet_api = PetApi(api_client) -# -# mock_pool = MockPoolManager(self) -# api_client.rest_client.pool_manager = mock_pool -# -# mock_pool.set_signing_config(signing_cfg) -# mock_pool.expect_request('POST', HOST + '/pet', -# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), -# headers={'Content-Type': r'application/json', -# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' -# r'headers="\(request-target\) \(created\)",' -# r'signature="[a-zA-Z0-9+/=]+"', -# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, -# preload_content=True, timeout=None) -# -# pet_api.add_pet(self.pet) -# -# def test_valid_http_signature_ec_p521(self): -# privkey_path = self.ec_p521_key_path -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path=privkey_path, -# private_key_passphrase=self.private_key_passphrase, -# hash_algorithm=signing.HASH_SHA512, -# signed_headers=[ -# signing.HEADER_REQUEST_TARGET, -# signing.HEADER_CREATED, -# ] -# ) -# config = Configuration(host=HOST, signing_info=signing_cfg) -# # Set the OAuth2 acces_token to None. Here we are interested in testing -# # the HTTP signature scheme. -# config.access_token = None -# -# api_client = petstore_api.ApiClient(config) -# pet_api = PetApi(api_client) -# -# mock_pool = MockPoolManager(self) -# api_client.rest_client.pool_manager = mock_pool -# -# mock_pool.set_signing_config(signing_cfg) -# mock_pool.expect_request('POST', HOST + '/pet', -# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), -# headers={'Content-Type': r'application/json', -# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' -# r'headers="\(request-target\) \(created\)",' -# r'signature="[a-zA-Z0-9+/=]+"', -# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, -# preload_content=True, timeout=None) -# -# pet_api.add_pet(self.pet) -# -# def test_invalid_configuration(self): -# # Signing scheme must be valid. -# with self.assertRaises(Exception) as cm: -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme='foo', -# private_key_path=self.ec_p521_key_path -# ) -# self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)), -# 'Exception message: {0}'.format(str(cm.exception))) -# -# # Signing scheme must be specified. -# with self.assertRaises(Exception) as cm: -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# private_key_path=self.ec_p521_key_path, -# signing_scheme=None -# ) -# self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)), -# 'Exception message: {0}'.format(str(cm.exception))) -# -# # Private key passphrase is missing but key is encrypted. -# with self.assertRaises(Exception) as cm: -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path=self.ec_p521_key_path, -# ) -# self.assertTrue(re.match('Not a valid clear PKCS#8 structure', str(cm.exception)), -# 'Exception message: {0}'.format(str(cm.exception))) -# -# # File containing private key must exist. -# with self.assertRaises(Exception) as cm: -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path='foobar', -# ) -# self.assertTrue(re.match('Private key file does not exist', str(cm.exception)), -# 'Exception message: {0}'.format(str(cm.exception))) -# -# # The max validity must be a positive value. -# with self.assertRaises(Exception) as cm: -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path=self.ec_p521_key_path, -# signature_max_validity=timedelta(hours=-1) -# ) -# self.assertTrue(re.match('The signature max validity must be a positive value', -# str(cm.exception)), -# 'Exception message: {0}'.format(str(cm.exception))) -# -# # Cannot include the 'Authorization' header. -# with self.assertRaises(Exception) as cm: -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path=self.ec_p521_key_path, -# signed_headers=['Authorization'] -# ) -# self.assertTrue(re.match("'Authorization' header cannot be included", str(cm.exception)), -# 'Exception message: {0}'.format(str(cm.exception))) -# -# # Cannot specify duplicate headers. -# with self.assertRaises(Exception) as cm: -# signing_cfg = signing.HttpSigningConfiguration( -# key_id="my-key-id", -# signing_scheme=signing.SCHEME_HS2019, -# private_key_path=self.ec_p521_key_path, -# signed_headers=['Host', 'Date', 'Host'] -# ) -# self.assertTrue(re.match('Cannot have duplicates in the signed_headers parameter', -# str(cm.exception)), -# 'Exception message: {0}'.format(str(cm.exception))) -# diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_integer_enum_one_value.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_integer_enum_one_value.py deleted file mode 100644 index a5d92cd083..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_integer_enum_one_value.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue - - -class TestIntegerEnumOneValue(unittest.TestCase): - """IntegerEnumOneValue unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testIntegerEnumOneValue(self): - """Test IntegerEnumOneValue""" - - with self.assertRaises(TypeError): - """ - a value must be passed in - We cannot auto assign values because that would break composition if - received payloads included this with no inputs and we the 0 value to the data to the incoming payload - One is not allowed to mutate incoming payloads because then: - - order of composed schema ingestion matters - - one can have default value collisions - - the added data will make expected schemas not match payloads - """ - model = IntegerEnumOneValue() - - model = IntegerEnumOneValue(0) - assert model == 0, "We can also pass in the value as a positional arg" - - # one cannot pass the value with the value keyword - with self.assertRaises(TypeError): - model = IntegerEnumOneValue(value=0) - - # one can pass in the enum value - model = IntegerEnumOneValue(IntegerEnumOneValue.POSITIVE_0) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_mammal.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_mammal.py deleted file mode 100644 index 9101280fc6..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_mammal.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.model.mammal import Mammal - - -class TestMammal(unittest.TestCase): - """Mammal unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testMammal(self): - """Test Mammal""" - - # tests that we can make a BasquePig by traveling through discriminator in Pig - m = Mammal(className="BasquePig") - from petstore_api.model import pig - from petstore_api.model import basque_pig - assert isinstance(m, Mammal) - assert isinstance(m, basque_pig.BasquePig) - assert isinstance(m, pig.Pig) - - # can make a Whale - m = Mammal(className="whale") - from petstore_api.model import whale - assert isinstance(m, whale.Whale) - - # can use the enum value - m = Mammal(className=whale.Whale.className.WHALE) - assert isinstance(m, whale.Whale) - - from petstore_api.model import zebra - m = Mammal(className='zebra') - assert isinstance(m, zebra.Zebra) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_money.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_money.py deleted file mode 100644 index a4bd764cc8..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_money.py +++ /dev/null @@ -1,34 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" -import decimal -import unittest - -from petstore_api.model.money import Money - - -class TestMoney(unittest.TestCase): - """Money unit test stubs""" - - def test_Money(self): - """Test Money""" - price = Money( - currency='usd', - amount='10.99' - ) - self.assertEqual(price.amount.as_decimal, decimal.Decimal('10.99')) - self.assertEqual( - price, - dict(currency='usd', amount='10.99') - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_no_additional_properties.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_no_additional_properties.py deleted file mode 100644 index 7aff481132..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_no_additional_properties.py +++ /dev/null @@ -1,64 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.model.no_additional_properties import NoAdditionalProperties - - -class TestNoAdditionalProperties(unittest.TestCase): - """NoAdditionalProperties unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testNoAdditionalProperties(self): - """Test NoAdditionalProperties""" - - # works with only required - inst = NoAdditionalProperties(id=1) - - # works with required + optional - inst = NoAdditionalProperties(id=1, petId=2) - - # needs required - # TODO cast this to ApiTypeError? - with self.assertRaisesRegex( - TypeError, - r"missing 1 required keyword-only argument: 'id'" - ): - NoAdditionalProperties(petId=2) - - # may not be passed additional properties - # TODO cast this to ApiTypeError? - with self.assertRaisesRegex( - TypeError, - r"got an unexpected keyword argument 'invalidArg'" - ): - NoAdditionalProperties(id=2, invalidArg=2) - - # plural example - # TODO cast this to ApiTypeError? - with self.assertRaisesRegex( - TypeError, - r"got an unexpected keyword argument 'firstInvalidArg'" - ): - NoAdditionalProperties(id=2, firstInvalidArg=1, secondInvalidArg=1) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_nullable_string.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_nullable_string.py deleted file mode 100644 index 1949de4837..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_nullable_string.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import unittest - -import petstore_api -from petstore_api.model.nullable_string import NullableString -from petstore_api.schemas import Schema, Singleton - - -class TestNullableString(unittest.TestCase): - """NullableString unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testNullableString(self): - """Test NullableString""" - inst = NullableString(None) - assert isinstance(inst, Singleton) - assert isinstance(inst, NullableString) - assert isinstance(inst, Schema) - assert inst.is_none() is True - assert repr(inst) == '' - - inst = NullableString('approved') - assert inst.is_none() is False - assert isinstance(inst, NullableString) - assert isinstance(inst, Schema) - assert isinstance(inst, str) - assert inst == 'approved' - - invalid_values = [1] - for invalid_value in invalid_values: - with self.assertRaisesRegex( - petstore_api.ApiTypeError, - r"Invalid type. Required value type is one of \[NoneClass, str\] and passed type was Decimal at \['args\[0\]'\]" - ): - NullableString(invalid_value) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_number_with_validations.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_number_with_validations.py deleted file mode 100644 index 5cf1dfaa9c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_number_with_validations.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.model.number_with_validations import NumberWithValidations - - -class TestNumberWithValidations(unittest.TestCase): - """NumberWithValidations unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testNumberWithValidations(self): - """Test NumberWithValidations""" - valid_values = [10.0, 15.0, 20.0] - for valid_value in valid_values: - model = NumberWithValidations(valid_value) - assert model == valid_value - - value_error_msg_pairs = ( - (9.0, r"Invalid value `9.0`, must be a value greater than or equal to `10` at \('args\[0\]',\)"), - (21.0, r"Invalid value `21.0`, must be a value less than or equal to `20` at \('args\[0\]',\)"), - ) - for invalid_value, error_msg in value_error_msg_pairs: - with self.assertRaisesRegex(petstore_api.ApiValueError, error_msg): - NumberWithValidations(invalid_value) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_model_with_ref_props.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_model_with_ref_props.py deleted file mode 100644 index 64a6a4c898..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_model_with_ref_props.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from datetime import date, datetime -import sys -import unittest - -import petstore_api -from petstore_api.schemas import BoolClass, frozendict -from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps -from petstore_api.model.number_with_validations import NumberWithValidations - - -class TestObjectModelWithRefProps(unittest.TestCase): - """ObjectModelWithRefProps unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testObjectModelWithRefProps(self): - """Test ObjectModelWithRefProps""" - self.assertEqual(ObjectModelWithRefProps.myNumber, NumberWithValidations) - - inst = ObjectModelWithRefProps(myNumber=15.0, myString="a", myBoolean=True) - assert isinstance(inst, ObjectModelWithRefProps) - assert isinstance(inst, frozendict) - assert set(inst.keys()) == {"myNumber", "myString", "myBoolean"} - assert inst.myNumber == 15.0 - assert isinstance(inst.myNumber, NumberWithValidations) - assert inst.myString == 'a' - assert isinstance(inst.myString, ObjectModelWithRefProps.myString) - assert bool(inst.myBoolean) is True - assert isinstance(inst.myBoolean, ObjectModelWithRefProps.myBoolean) - assert isinstance(inst.myBoolean, BoolClass) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_inline_composition_property.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_inline_composition_property.py deleted file mode 100644 index 98b902a01e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_inline_composition_property.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -from petstore_api import schemas, exceptions -from petstore_api.model.object_with_inline_composition_property import ObjectWithInlineCompositionProperty - - -class TestObjectWithInlineCompositionProperty(unittest.TestCase): - """ObjectWithInlineCompositionProperty unit test stubs""" - - def test_ObjectWithInlineCompositionProperty(self): - """Test ObjectWithInlineCompositionProperty""" - model = ObjectWithInlineCompositionProperty(someProp='a') - self.assertTrue(isinstance(model.someProp, ObjectWithInlineCompositionProperty.someProp)) - self.assertTrue(isinstance(model.someProp, schemas.StrSchema)) - - # error thrown on length < 1 - with self.assertRaises(exceptions.ApiValueError): - ObjectWithInlineCompositionProperty(someProp='') - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_parent_pet.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_parent_pet.py deleted file mode 100644 index 171310075a..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_parent_pet.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.model.grandparent_animal import GrandparentAnimal -from petstore_api.model.parent_pet import ParentPet - - -class TestParentPet(unittest.TestCase): - """ParentPet unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testParentPet(self): - """Test ParentPet""" - - # test that we can make a ParentPet from a ParentPet - # which requires that we travel back through ParentPet's allOf descendant - # GrandparentAnimal, and we use the descendant's discriminator to make ParentPet - model = ParentPet(pet_type="ParentPet") - assert isinstance(model, ParentPet) - assert isinstance(model, GrandparentAnimal) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_quadrilateral.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_quadrilateral.py deleted file mode 100644 index dff97bc716..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_quadrilateral.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.model import complex_quadrilateral -from petstore_api.model import simple_quadrilateral -from petstore_api.model.quadrilateral import Quadrilateral - - -class TestQuadrilateral(unittest.TestCase): - """Quadrilateral unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testQuadrilateral(self): - """Test Quadrilateral""" - instance = Quadrilateral(shapeType="Quadrilateral", quadrilateralType="ComplexQuadrilateral") - assert isinstance(instance, complex_quadrilateral.ComplexQuadrilateral) - instance = Quadrilateral(shapeType="Quadrilateral", quadrilateralType="SimpleQuadrilateral") - assert isinstance(instance, simple_quadrilateral.SimpleQuadrilateral) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_shape.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_shape.py deleted file mode 100644 index ce8906fdd1..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_shape.py +++ /dev/null @@ -1,117 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.schemas import Singleton, frozendict -from petstore_api.model.shape import Shape -from petstore_api.model import quadrilateral -from petstore_api.model import complex_quadrilateral -from petstore_api.model import simple_quadrilateral -from petstore_api.model import triangle -from petstore_api.model import triangle_interface -from petstore_api.model import equilateral_triangle -from petstore_api.model import isosceles_triangle -from petstore_api.model import scalene_triangle - - -class TestShape(unittest.TestCase): - """Shape unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_recursionlimit(self): - """Test case for recursionlimit - - """ - assert sys.getrecursionlimit() == 1234 - - def testShape(self): - """Test Shape""" - - tri = Shape( - shapeType="Triangle", - triangleType="EquilateralTriangle" - ) - assert isinstance(tri, equilateral_triangle.EquilateralTriangle) - assert isinstance(tri, triangle.Triangle) - assert isinstance(tri, triangle_interface.TriangleInterface) - assert isinstance(tri, Shape) - assert isinstance(tri, frozendict) - assert isinstance(tri.shapeType, str) - assert isinstance(tri.shapeType, Singleton) - - tri = Shape( - shapeType="Triangle", - triangleType="IsoscelesTriangle" - ) - assert isinstance(tri, isosceles_triangle.IsoscelesTriangle) - - tri = Shape( - shapeType="Triangle", - triangleType="ScaleneTriangle" - ) - assert isinstance(tri, scalene_triangle.ScaleneTriangle) - - quad = Shape( - shapeType="Quadrilateral", - quadrilateralType="ComplexQuadrilateral" - ) - assert isinstance(quad, complex_quadrilateral.ComplexQuadrilateral) - - quad = Shape( - shapeType="Quadrilateral", - quadrilateralType="SimpleQuadrilateral" - ) - assert isinstance(quad, simple_quadrilateral.SimpleQuadrilateral) - - # data missing - with self.assertRaisesRegex( - petstore_api.exceptions.ApiValueError, - r"Cannot deserialize input data due to missing discriminator. The discriminator " - r"property 'shapeType' is missing at path: \('args\[0\]',\)" - ): - Shape({}) - - # invalid shape_type (first discriminator). 'Circle' does not exist in the model. - err_msg = ( - r"Invalid discriminator value was passed in to Shape.shapeType Only the values " - r"\['Quadrilateral', 'Triangle'\] are allowed at \('args\[0\]', 'shapeType'\)" - ) - with self.assertRaisesRegex( - petstore_api.ApiValueError, - err_msg - ): - Shape(shapeType="Circle") - - # invalid quadrilateral_type (second discriminator) - err_msg = ( - r"Invalid discriminator value was passed in to Quadrilateral.quadrilateralType Only the values " - r"\['ComplexQuadrilateral', 'SimpleQuadrilateral'\] are allowed at \('args\[0\]', 'quadrilateralType'\)" - ) - with self.assertRaisesRegex( - petstore_api.ApiValueError, - err_msg - ): - Shape( - shapeType="Quadrilateral", - quadrilateralType="Triangle" - ) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_string_enum.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_string_enum.py deleted file mode 100644 index 0485242b37..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_string_enum.py +++ /dev/null @@ -1,57 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import unittest - -import petstore_api -from petstore_api.model.string_enum import StringEnum -from petstore_api.schemas import Singleton, NoneClass - - -class TestStringEnum(unittest.TestCase): - """StringEnum unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testStringEnum(self): - """Test StringEnum""" - inst = StringEnum(None) - assert isinstance(inst, StringEnum) - assert isinstance(inst, NoneClass) - assert repr(inst) == '' - - inst = StringEnum('approved') - assert isinstance(inst, StringEnum) - assert isinstance(inst, Singleton) - assert isinstance(inst, str) - assert inst == 'approved' - assert repr(inst) == "" - - with self.assertRaises(petstore_api.ApiValueError): - StringEnum('garbage') - - # make sure that we can access its allowed_values - assert isinstance(StringEnum.NONE, NoneClass) - assert StringEnum.PLACED == 'placed' - assert StringEnum.APPROVED == 'approved' - assert StringEnum.DELIVERED == 'delivered' - assert StringEnum.DOUBLE_QUOTE_WITH_NEWLINE == "double quote \n with newline" - assert StringEnum.MULTIPLE_LINES == "multiple\nlines" - assert StringEnum.SINGLE_QUOTED == "single quoted" - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_triangle.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_triangle.py deleted file mode 100644 index 286b5b0f9e..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_triangle.py +++ /dev/null @@ -1,38 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import unittest - -from petstore_api.model.equilateral_triangle import EquilateralTriangle -from petstore_api.model.isosceles_triangle import IsoscelesTriangle -from petstore_api.model.scalene_triangle import ScaleneTriangle -from petstore_api.model.triangle import Triangle -from petstore_api.model.triangle_interface import TriangleInterface -from petstore_api.schemas import frozendict - - -class TestTriangle(unittest.TestCase): - """Triangle unit test stubs""" - - def testTriangle(self): - """Test Triangle""" - tri_classes = [EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle] - for tri_class in tri_classes: - tri = Triangle(shapeType="Triangle", triangleType=tri_class.__name__) - assert isinstance(tri, tri_class) - assert isinstance(tri, Triangle) - assert isinstance(tri, TriangleInterface) - assert isinstance(tri, frozendict) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_user_api.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_user_api.py deleted file mode 100644 index ce2598fbfc..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_user_api.py +++ /dev/null @@ -1,108 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" -import unittest -from unittest.mock import patch - -import petstore_api -from petstore_api import api_client -from petstore_api.api.user_api import UserApi -from petstore_api.rest import RESTClientObject - -from . import ApiTestMixin - - -class TestUserApi(ApiTestMixin): - """UserApi unit test stubs""" - configuration = petstore_api.Configuration() - api = UserApi(api_client=api_client.ApiClient(configuration=configuration)) - - def test_create_user(self): - """Test case for create_user - - Create user # noqa: E501 - """ - pass - - def test_create_users_with_array_input(self): - """Test case for create_users_with_array_input - - Creates list of users with given input array # noqa: E501 - """ - pass - - def test_create_users_with_list_input(self): - """Test case for create_users_with_list_input - - Creates list of users with given input array # noqa: E501 - """ - pass - - def test_delete_user(self): - """Test case for delete_user - - Delete user # noqa: E501 - """ - pass - - def test_get_user_by_name(self): - from petstore_api.model import user - - # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_request: - value_simple = dict( - id=1, - username='first last', - firstName='first', - lastName='last' - ) - body = user.User(**value_simple) - mock_request.return_value = self.response( - self.json_bytes(value_simple) - ) - - api_response = self.api.get_user_by_name( - path_params=dict(username='first last') - ) - self.assert_request_called_with( - mock_request, - 'http://petstore.swagger.io:80/v2/user/first%20last', - method='GET', - accept_content_type='application/xml, application/json', - content_type=None - ) - - assert isinstance(api_response.body, user.User) - assert api_response.body == body - - def test_login_user(self): - """Test case for login_user - - Logs user into the system # noqa: E501 - """ - pass - - def test_logout_user(self): - """Test case for logout_user - - Logs out current logged in user session # noqa: E501 - """ - pass - - def test_update_user(self): - """Test case for update_user - - Updated user # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_uuid_string.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_uuid_string.py deleted file mode 100644 index 1f6da7bd97..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_uuid_string.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -import unittest - -from petstore_api import schemas, exceptions -from petstore_api.model.uuid_string import UUIDString -import uuid - - -class TestUUIDString(unittest.TestCase): - """UUIDString unit test stubs""" - - def test_UUIDString(self): - """Test UUIDString""" - uuid_value = '12345678-1234-5678-1234-567812345678' - u = UUIDString(uuid_value) - self.assertEqual(u, uuid_value) - self.assertTrue(isinstance(u, UUIDString)) - self.assertTrue(isinstance(u, schemas.UUIDSchema)) - self.assertTrue(isinstance(u, schemas.StrSchema)) - self.assertTrue(isinstance(u, str)) - self.assertEqual(u.as_uuid, uuid.UUID(uuid_value)) - - # passing in a uuid also works - u = UUIDString(uuid.UUID(uuid_value)) - self.assertEqual(u, uuid_value) - self.assertTrue(isinstance(u, UUIDString)) - self.assertTrue(isinstance(u, schemas.UUIDSchema)) - self.assertTrue(isinstance(u, schemas.StrSchema)) - self.assertTrue(isinstance(u, str)) - self.assertEqual(u.as_uuid, uuid.UUID(uuid_value)) - - # an invalid value does not work - with self.assertRaises(exceptions.ApiValueError): - UUIDString('1') - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_validate.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_validate.py deleted file mode 100644 index 19592fe384..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_validate.py +++ /dev/null @@ -1,281 +0,0 @@ -# coding: utf-8 - -from collections import defaultdict -from decimal import Decimal -import typing -from unittest.mock import patch, call -import unittest - -import petstore_api -from petstore_api.model.string_with_validation import StringWithValidation -from petstore_api.model.string_enum import StringEnum -from petstore_api.model.number_with_validations import NumberWithValidations -from petstore_api.model.array_holding_any_type import ArrayHoldingAnyType -from petstore_api.model.array_with_validations_in_items import ( - ArrayWithValidationsInItems, -) -from petstore_api.model.foo import Foo -from petstore_api.model.animal import Animal -from petstore_api.model.dog import Dog -from petstore_api.model.boolean_enum import BooleanEnum -from petstore_api.model.pig import Pig -from petstore_api.model.danish_pig import DanishPig -from petstore_api.model.gm_fruit import GmFruit -from petstore_api.model.apple import Apple -from petstore_api.model.banana import Banana - -from petstore_api.schemas import ( - AnyTypeSchema, - BoolClass, - NoneClass, - StrSchema, - NumberSchema, - Schema, - ValidationMetadata, - frozendict, -) - - -class TestValidateResults(unittest.TestCase): - def test_str_validate(self): - vm = ValidationMetadata() - path_to_schemas = StringWithValidation._validate( - "abcdefg", validation_metadata=vm - ) - assert path_to_schemas == {("args[0]",): set([StringWithValidation, str])} - - def test_number_validate(self): - vm = ValidationMetadata() - path_to_schemas = NumberWithValidations._validate( - Decimal(11), validation_metadata=vm - ) - assert path_to_schemas == {("args[0]",): set([NumberWithValidations, Decimal])} - - def test_str_enum_validate(self): - vm = ValidationMetadata() - path_to_schemas = StringEnum._validate("placed", validation_metadata=vm) - assert path_to_schemas == {("args[0]",): {str, StringEnum}} - - def test_nullable_enum_validate(self): - vm = ValidationMetadata() - path_to_schemas = StringEnum._validate(NoneClass.NONE, validation_metadata=vm) - assert path_to_schemas == {("args[0]",): {NoneClass, StringEnum}} - - def test_empty_list_validate(self): - vm = ValidationMetadata() - path_to_schemas = ArrayHoldingAnyType._validate((), validation_metadata=vm) - assert path_to_schemas == {("args[0]",): set([ArrayHoldingAnyType, tuple])} - - def test_list_validate(self): - vm = ValidationMetadata() - path_to_schemas = ArrayHoldingAnyType._validate( - (Decimal(1), "a"), validation_metadata=vm - ) - assert path_to_schemas == { - ("args[0]",): set([ArrayHoldingAnyType, tuple]), - ("args[0]", 0): set([AnyTypeSchema, Decimal]), - ("args[0]", 1): set([AnyTypeSchema, str]), - } - - def test_empty_dict_validate(self): - vm = ValidationMetadata() - path_to_schemas = Foo._validate(frozendict({}), validation_metadata=vm) - assert path_to_schemas == {("args[0]",): set([Foo, frozendict])} - - def test_dict_validate(self): - vm = ValidationMetadata() - path_to_schemas = Foo._validate( - frozendict({"bar": "a", "additional": Decimal(0)}), - validation_metadata=vm, - ) - assert path_to_schemas == { - ("args[0]",): set([Foo, frozendict]), - ("args[0]", "bar"): set([StrSchema, str]), - ("args[0]", "additional"): set([AnyTypeSchema, Decimal]), - } - - def test_discriminated_dict_validate(self): - vm = ValidationMetadata() - path_to_schemas = Animal._validate( - frozendict(className="Dog", color="black"), validation_metadata=vm - ) - assert path_to_schemas == { - ("args[0]",): set([Animal, Dog, Dog._composed_schemas['allOf'][1], frozendict]), - ("args[0]", "className"): set([StrSchema, AnyTypeSchema, str]), - ("args[0]", "color"): set([StrSchema, AnyTypeSchema, str]), - } - - def test_bool_enum_validate(self): - vm = ValidationMetadata() - path_to_schemas = BooleanEnum._validate(BoolClass.TRUE, validation_metadata=vm) - assert path_to_schemas == {("args[0]",): {BoolClass, BooleanEnum}} - - def test_oneof_composition_pig_validate(self): - vm = ValidationMetadata() - path_to_schemas = Pig._validate( - frozendict(className="DanishPig"), validation_metadata=vm - ) - assert path_to_schemas == { - ("args[0]",): set([Pig, DanishPig, frozendict]), - ("args[0]", "className"): set([DanishPig.className, AnyTypeSchema, str]), - } - - def test_anyof_composition_gm_fruit_validate(self): - vm = ValidationMetadata() - path_to_schemas = GmFruit._validate( - frozendict(cultivar="GoldenDelicious", lengthCm=Decimal(10)), - validation_metadata=vm, - ) - assert path_to_schemas == { - ("args[0]",): set([GmFruit, Apple, Banana, frozendict]), - ("args[0]", "cultivar"): set([Apple.cultivar, AnyTypeSchema, str]), - ("args[0]", "lengthCm"): set([AnyTypeSchema, NumberSchema, Decimal]), - } - - -class TestValidateCalls(unittest.TestCase): - def test_empty_list_validate(self): - return_value = {("args[0]",): set([ArrayHoldingAnyType, tuple])} - with patch.object( - Schema, "_validate", return_value=return_value - ) as mock_validate: - ArrayHoldingAnyType([]) - assert mock_validate.call_count == 1 - - with patch.object( - Schema, "_validate", return_value=return_value - ) as mock_validate: - ArrayHoldingAnyType._from_openapi_data([]) - assert mock_validate.call_count == 1 - - def test_empty_dict_validate(self): - return_value = {("args[0]",): set([Foo, frozendict])} - with patch.object( - Schema, "_validate", return_value=return_value - ) as mock_validate: - Foo({}) - assert mock_validate.call_count == 1 - - with patch.object( - Schema, "_validate", return_value=return_value - ) as mock_validate: - Foo._from_openapi_data({}) - assert mock_validate.call_count == 1 - - def test_list_validate_direct_instantiation(self): - results = [ - {("args[0]",): {ArrayWithValidationsInItems, tuple}}, - {("args[0]", 0): {ArrayWithValidationsInItems._items, Decimal}} - ] - with patch.object(Schema, "_validate", side_effect=results) as mock_validate: - ArrayWithValidationsInItems([7]) - calls = [ - call( - (Decimal("7"),), - validation_metadata=ValidationMetadata(path_to_item=("args[0]",)) - ), - call( - Decimal("7"), - ValidationMetadata(path_to_item=("args[0]", 0)) - ) - ] - mock_validate.assert_has_calls( - calls - ) - - def test_list_validate_direct_instantiation_cast_item(self): - # item validation is skipped if items are of the correct type - item = ArrayWithValidationsInItems._items(7) - return_value = {("args[0]",): {ArrayWithValidationsInItems, tuple}} - with patch.object(Schema, "_validate", return_value=return_value) as mock_validate: - ArrayWithValidationsInItems([item]) - mock_validate.assert_called_once_with( - tuple([Decimal('7')]), - validation_metadata=ValidationMetadata( - validated_path_to_schemas={('args[0]', 0): {ArrayWithValidationsInItems._items, Decimal}} - ) - ) - - def test_list_validate_from_openai_data_instantiation(self): - - results = [ - {("args[0]",): {ArrayWithValidationsInItems, tuple}}, - {("args[0]", 0): {ArrayWithValidationsInItems._items, Decimal}} - ] - with patch.object(Schema, "_validate", side_effect=results) as mock_validate: - ArrayWithValidationsInItems._from_openapi_data([7]) - calls = [ - call( - (Decimal("7"),), - validation_metadata=ValidationMetadata(path_to_item=("args[0]",), from_server=True) - ), - call( - Decimal("7"), - ValidationMetadata(path_to_item=("args[0]", 0), from_server=True) - ) - ] - mock_validate.assert_has_calls( - calls - ) - - def test_dict_validate_direct_instantiation(self): - call_results = [ - {("args[0]",): {Foo, frozendict}}, - {("args[0]", "bar"): {StrSchema, str}} - ] - with patch.object(Schema, "_validate", side_effect=call_results) as mock_validate: - Foo(bar="a") - calls = [ - call( - frozendict({"bar": "a"}), - validation_metadata=ValidationMetadata(path_to_item=("args[0]",)), - ), - call( - "a", - ValidationMetadata(path_to_item=("args[0]", "bar")), - ), - ] - mock_validate.assert_has_calls( - calls - ) - - def test_dict_validate_direct_instantiation_cast_item(self): - bar = StrSchema("a") - return_value = { - ("args[0]",): {Foo, frozendict} - } - # only the Foo dict is validated because the bar property value was already validated - with patch.object(Schema, "_validate", return_value=return_value) as mock_validate: - Foo(bar=bar) - mock_validate.assert_called_once_with( - frozendict(dict(bar='a')), - validation_metadata=ValidationMetadata( - validated_path_to_schemas={('args[0]', 'bar'): {str, StrSchema}} - ) - ) - - def test_dict_validate_from_openapi_data_instantiation(self): - - return_values = [ - {("args[0]",): {Foo, frozendict}}, - {("args[0]", 'bar'): {StrSchema, str}} - ] - with patch.object(Schema, "_validate", side_effect=return_values) as mock_validate: - Foo._from_openapi_data({"bar": "a"}) - calls = [ - call( - frozendict({"bar": "a"}), - validation_metadata=ValidationMetadata(path_to_item=("args[0]",), from_server=True), - ), - call( - "a", - ValidationMetadata(path_to_item=("args[0]", "bar"), from_server=True), - ), - ] - mock_validate.assert_has_calls( - calls - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_whale.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_whale.py deleted file mode 100644 index 88bd8ed12d..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_whale.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import sys -import unittest - -import petstore_api -from petstore_api.schemas import BoolClass -from petstore_api.model.whale import Whale - - -class TestWhale(unittest.TestCase): - """Whale unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_Whale(self): - # test that the hasBaleen __bool__ method is working, True input - whale = Whale( - className='whale', - hasBaleen=True - ) - assert isinstance(whale.hasBaleen, BoolClass) - self.assertTrue(whale.hasBaleen) - - # test that the hasBaleen __bool__ method is working, False input - whale = Whale( - className='whale', - hasBaleen=False - ) - assert isinstance(whale.hasBaleen, BoolClass) - self.assertFalse(whale.hasBaleen) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tox.ini b/samples/openapi3/client/petstore/python-experimental/tox.ini deleted file mode 100644 index ef7cec358c..0000000000 --- a/samples/openapi3/client/petstore/python-experimental/tox.ini +++ /dev/null @@ -1,9 +0,0 @@ -[tox] -envlist = py39 - -[testenv] -deps=-r{toxinidir}/requirements.txt - -r{toxinidir}/test-requirements.txt - -commands= - pytest --cov=petstore_api diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/pet_api.py index ed1d8d6c50..14cf58697c 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/pet_api.py @@ -104,7 +104,8 @@ class PetApi(object): local_var_hosts = [ 'http://petstore.swagger.io/v2', - 'http://path-server-test.petstore.local/v2' + 'http://path-server-test.petstore.local/v2', + 'http://{server}.swagger.io:{port}/v2' ] local_var_host = local_var_hosts[0] if kwargs.get('_host_index'): @@ -812,7 +813,8 @@ class PetApi(object): local_var_hosts = [ 'http://petstore.swagger.io/v2', - 'http://path-server-test.petstore.local/v2' + 'http://path-server-test.petstore.local/v2', + 'http://{server}.swagger.io:{port}/v2' ] local_var_host = local_var_hosts[0] if kwargs.get('_host_index'): diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/all_of_with_single_ref.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/all_of_with_single_ref.py index 8466199c80..e71b49de25 100644 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/all_of_with_single_ref.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/all_of_with_single_ref.py @@ -57,7 +57,8 @@ class AllOfWithSingleRef(object): if username is not None: self.username = username - self.single_ref_type = single_ref_type + if single_ref_type is not None: + self.single_ref_type = single_ref_type @property def username(self): diff --git a/samples/openapi3/client/petstore/python-prior/.gitignore b/samples/openapi3/client/petstore/python-prior/.gitignore new file mode 100644 index 0000000000..43995bd42f --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/.gitignore @@ -0,0 +1,66 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.venv/ +.python-version +.pytest_cache + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/samples/openapi3/client/petstore/python-prior/.gitlab-ci.yml b/samples/openapi3/client/petstore/python-prior/.gitlab-ci.yml new file mode 100644 index 0000000000..9e84f51761 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/.gitlab-ci.yml @@ -0,0 +1,24 @@ +# ref: https://docs.gitlab.com/ee/ci/README.html + +stages: + - test + +.tests: + stage: test + script: + - pip install -r requirements.txt + - pip install -r test-requirements.txt + - pytest --cov=petstore_api + +test-3.6: + extends: .tests + image: python:3.6-alpine +test-3.7: + extends: .tests + image: python:3.7-alpine +test-3.8: + extends: .tests + image: python:3.8-alpine +test-3.9: + extends: .tests + image: python:3.9-alpine diff --git a/samples/openapi3/client/petstore/python-prior/.openapi-generator-ignore b/samples/openapi3/client/petstore/python-prior/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/.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/openapi3/client/petstore/python-prior/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-prior/.openapi-generator/FILES new file mode 100644 index 0000000000..aa32ba2dee --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/.openapi-generator/FILES @@ -0,0 +1,236 @@ +.gitignore +.gitlab-ci.yml +.travis.yml +README.md +docs/AdditionalPropertiesClass.md +docs/AdditionalPropertiesWithArrayOfEnums.md +docs/Address.md +docs/Animal.md +docs/AnimalFarm.md +docs/AnotherFakeApi.md +docs/ApiResponse.md +docs/Apple.md +docs/AppleReq.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfEnums.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Banana.md +docs/BananaReq.md +docs/BasquePig.md +docs/BooleanEnum.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ChildCat.md +docs/ChildCatAllOf.md +docs/ClassModel.md +docs/Client.md +docs/ComplexQuadrilateral.md +docs/ComposedOneOfNumberWithValidations.md +docs/ComposedSchemaWithPropsAndNoAddProps.md +docs/DanishPig.md +docs/DefaultApi.md +docs/Dog.md +docs/DogAllOf.md +docs/Drawing.md +docs/EgressThresholdOptions.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/EquilateralTriangle.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/File.md +docs/FileSchemaTestClass.md +docs/Foo.md +docs/FooGetDefaultResponse.md +docs/FooObject.md +docs/FormatTest.md +docs/Fruit.md +docs/FruitReq.md +docs/GmFruit.md +docs/GmFruitNoProperties.md +docs/GrandparentAnimal.md +docs/HasOnlyReadOnly.md +docs/HealthCheckResult.md +docs/InlineAdditionalPropertiesRefPayload.md +docs/IntegerEnum.md +docs/IntegerEnumOneValue.md +docs/IntegerEnumWithDefaultValue.md +docs/IsoscelesTriangle.md +docs/Legs.md +docs/List.md +docs/Mammal.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelReturn.md +docs/Mole.md +docs/Name.md +docs/NullableClass.md +docs/NullableShape.md +docs/NumberOnly.md +docs/NumberWithValidations.md +docs/ObjectInterface.md +docs/ObjectModelWithRefProps.md +docs/ObjectWithValidations.md +docs/Order.md +docs/ParentPet.md +docs/Pet.md +docs/PetApi.md +docs/Pig.md +docs/PostInlineAdditionalPropertiesPayloadRequest.md +docs/PostInlineAdditionalPropertiesPayloadRequestArrayDataInner.md +docs/PublishOptions.md +docs/PublishOptionsPublish.md +docs/Quadrilateral.md +docs/QuadrilateralInterface.md +docs/ReadOnlyFirst.md +docs/Readonly.md +docs/ScaleneTriangle.md +docs/Shape.md +docs/ShapeInterface.md +docs/ShapeOrNull.md +docs/SimpleQuadrilateral.md +docs/SomeObject.md +docs/SomeObjectWithSelfAttr.md +docs/SpecialModelName.md +docs/StoreApi.md +docs/StreamOptions.md +docs/StringBooleanMap.md +docs/StringEnum.md +docs/StringEnumWithDefaultValue.md +docs/Tag.md +docs/Triangle.md +docs/TriangleInterface.md +docs/User.md +docs/UserApi.md +docs/Whale.md +docs/Zebra.md +git_push.sh +petstore_api/__init__.py +petstore_api/api/__init__.py +petstore_api/api/another_fake_api.py +petstore_api/api/default_api.py +petstore_api/api/fake_api.py +petstore_api/api/fake_classname_tags123_api.py +petstore_api/api/pet_api.py +petstore_api/api/store_api.py +petstore_api/api/user_api.py +petstore_api/api_client.py +petstore_api/apis/__init__.py +petstore_api/configuration.py +petstore_api/exceptions.py +petstore_api/model/__init__.py +petstore_api/model/additional_properties_class.py +petstore_api/model/additional_properties_with_array_of_enums.py +petstore_api/model/address.py +petstore_api/model/animal.py +petstore_api/model/animal_farm.py +petstore_api/model/api_response.py +petstore_api/model/apple.py +petstore_api/model/apple_req.py +petstore_api/model/array_of_array_of_number_only.py +petstore_api/model/array_of_enums.py +petstore_api/model/array_of_number_only.py +petstore_api/model/array_test.py +petstore_api/model/banana.py +petstore_api/model/banana_req.py +petstore_api/model/basque_pig.py +petstore_api/model/boolean_enum.py +petstore_api/model/capitalization.py +petstore_api/model/cat.py +petstore_api/model/cat_all_of.py +petstore_api/model/category.py +petstore_api/model/child_cat.py +petstore_api/model/child_cat_all_of.py +petstore_api/model/class_model.py +petstore_api/model/client.py +petstore_api/model/complex_quadrilateral.py +petstore_api/model/composed_one_of_number_with_validations.py +petstore_api/model/composed_schema_with_props_and_no_add_props.py +petstore_api/model/danish_pig.py +petstore_api/model/dog.py +petstore_api/model/dog_all_of.py +petstore_api/model/drawing.py +petstore_api/model/egress_threshold_options.py +petstore_api/model/enum_arrays.py +petstore_api/model/enum_class.py +petstore_api/model/enum_test.py +petstore_api/model/equilateral_triangle.py +petstore_api/model/file.py +petstore_api/model/file_schema_test_class.py +petstore_api/model/foo.py +petstore_api/model/foo_get_default_response.py +petstore_api/model/foo_object.py +petstore_api/model/format_test.py +petstore_api/model/fruit.py +petstore_api/model/fruit_req.py +petstore_api/model/gm_fruit.py +petstore_api/model/gm_fruit_no_properties.py +petstore_api/model/grandparent_animal.py +petstore_api/model/has_only_read_only.py +petstore_api/model/health_check_result.py +petstore_api/model/inline_additional_properties_ref_payload.py +petstore_api/model/integer_enum.py +petstore_api/model/integer_enum_one_value.py +petstore_api/model/integer_enum_with_default_value.py +petstore_api/model/isosceles_triangle.py +petstore_api/model/legs.py +petstore_api/model/list.py +petstore_api/model/mammal.py +petstore_api/model/map_test.py +petstore_api/model/mixed_properties_and_additional_properties_class.py +petstore_api/model/model200_response.py +petstore_api/model/model_return.py +petstore_api/model/mole.py +petstore_api/model/name.py +petstore_api/model/nullable_class.py +petstore_api/model/nullable_shape.py +petstore_api/model/number_only.py +petstore_api/model/number_with_validations.py +petstore_api/model/object_interface.py +petstore_api/model/object_model_with_ref_props.py +petstore_api/model/object_with_validations.py +petstore_api/model/order.py +petstore_api/model/parent_pet.py +petstore_api/model/pet.py +petstore_api/model/pig.py +petstore_api/model/post_inline_additional_properties_payload_request.py +petstore_api/model/post_inline_additional_properties_payload_request_array_data_inner.py +petstore_api/model/publish_options.py +petstore_api/model/publish_options_publish.py +petstore_api/model/quadrilateral.py +petstore_api/model/quadrilateral_interface.py +petstore_api/model/read_only_first.py +petstore_api/model/readonly.py +petstore_api/model/scalene_triangle.py +petstore_api/model/shape.py +petstore_api/model/shape_interface.py +petstore_api/model/shape_or_null.py +petstore_api/model/simple_quadrilateral.py +petstore_api/model/some_object.py +petstore_api/model/some_object_with_self_attr.py +petstore_api/model/special_model_name.py +petstore_api/model/stream_options.py +petstore_api/model/string_boolean_map.py +petstore_api/model/string_enum.py +petstore_api/model/string_enum_with_default_value.py +petstore_api/model/tag.py +petstore_api/model/triangle.py +petstore_api/model/triangle_interface.py +petstore_api/model/user.py +petstore_api/model/whale.py +petstore_api/model/zebra.py +petstore_api/model_utils.py +petstore_api/models/__init__.py +petstore_api/rest.py +petstore_api/signing.py +requirements.txt +setup.cfg +setup.py +test-requirements.txt +test/__init__.py +tox.ini diff --git a/samples/openapi3/client/petstore/python-prior/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python-prior/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-prior/.travis.yml b/samples/openapi3/client/petstore/python-prior/.travis.yml new file mode 100644 index 0000000000..1fcc4b1559 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/.travis.yml @@ -0,0 +1,13 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: + - "3.6" + - "3.7" + - "3.8" + - "3.9" +# command to install dependencies +install: + - "pip install -r requirements.txt" + - "pip install -r test-requirements.txt" +# command to run tests +script: pytest --cov=petstore_api diff --git a/samples/openapi3/client/petstore/python-prior/Makefile b/samples/openapi3/client/petstore/python-prior/Makefile new file mode 100644 index 0000000000..f8957d5ed6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/Makefile @@ -0,0 +1,16 @@ +REQUIREMENTS_FILE=dev-requirements.txt +REQUIREMENTS_OUT=dev-requirements.txt.log +SETUP_OUT=*.egg-info +VENV=.venv + +clean: + rm -rf $(REQUIREMENTS_OUT) + rm -rf $(SETUP_OUT) + rm -rf $(VENV) + rm -rf .tox + rm -rf .coverage + find . -name "*.py[oc]" -delete + find . -name "__pycache__" -delete + +test: clean + bash ./test_python.sh diff --git a/samples/openapi3/client/petstore/python-prior/README.md b/samples/openapi3/client/petstore/python-prior/README.md new file mode 100644 index 0000000000..0b59228e6f --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/README.md @@ -0,0 +1,306 @@ +# petstore-api +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonPriorClientCodegen + +## Requirements. + +Python >=3.6 + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: +```python +import petstore_api +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import petstore_api +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python +import datetime +import time +import petstore_api +from pprint import pprint +from petstore_api.api import another_fake_api +from petstore_api.model.client import Client +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = another_fake_api.AnotherFakeApi(api_client) + client = Client( + client="client_example", + ) # Client | client model + + try: + # To test special tags + api_response = api_instance.call_123_test_special_tags(client) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +*DefaultApi* | [**foo_get**](docs/DefaultApi.md#foo_get) | **GET** /foo | +*FakeApi* | [**additional_properties_with_array_of_enums**](docs/FakeApi.md#additional_properties_with_array_of_enums) | **GET** /fake/additional-properties-with-array-of-enums | Additional Properties with Array of Enums +*FakeApi* | [**array_model**](docs/FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | +*FakeApi* | [**array_of_enums**](docs/FakeApi.md#array_of_enums) | **POST** /fake/refs/array-of-enums | Array of Enums +*FakeApi* | [**boolean**](docs/FakeApi.md#boolean) | **POST** /fake/refs/boolean | +*FakeApi* | [**composed_one_of_number_with_validations**](docs/FakeApi.md#composed_one_of_number_with_validations) | **POST** /fake/refs/composed_one_of_number_with_validations | +*FakeApi* | [**download_attachment**](docs/FakeApi.md#download_attachment) | **GET** /{fileName} | downloads a file using Content-Disposition +*FakeApi* | [**enum_test**](docs/FakeApi.md#enum_test) | **POST** /fake/refs/enum-test | Object contains enum properties and array properties containing enums +*FakeApi* | [**fake_health_get**](docs/FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint +*FakeApi* | [**mammal**](docs/FakeApi.md#mammal) | **POST** /fake/refs/mammal | +*FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | +*FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +*FakeApi* | [**post_inline_additional_properties_payload**](docs/FakeApi.md#post_inline_additional_properties_payload) | **POST** /fake/postInlineAdditionalPropertiesPayload | +*FakeApi* | [**post_inline_additional_properties_ref_payload**](docs/FakeApi.md#post_inline_additional_properties_ref_payload) | **POST** /fake/postInlineAdditionalPropertiesRefPayload | +*FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | +*FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | +*FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | +*FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | +*FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeApi* | [**test_query_parameter_collection_format**](docs/FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | +*FakeApi* | [**tx_rx_all_of_model**](docs/FakeApi.md#tx_rx_all_of_model) | **POST** /fake/TxRxAllOfModel | +*FakeApi* | [**tx_rx_any_of_model**](docs/FakeApi.md#tx_rx_any_of_model) | **POST** /fake/TxRxAnyOfModel | +*FakeApi* | [**upload_download_file**](docs/FakeApi.md#upload_download_file) | **POST** /fake/uploadDownloadFile | uploads a file and downloads a file using application/octet-stream +*FakeApi* | [**upload_file**](docs/FakeApi.md#upload_file) | **POST** /fake/uploadFile | uploads a file using multipart/form-data +*FakeApi* | [**upload_files**](docs/FakeApi.md#upload_files) | **POST** /fake/uploadFiles | uploads files using multipart/form-data +*FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AdditionalPropertiesWithArrayOfEnums](docs/AdditionalPropertiesWithArrayOfEnums.md) + - [Address](docs/Address.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ApiResponse](docs/ApiResponse.md) + - [Apple](docs/Apple.md) + - [AppleReq](docs/AppleReq.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfEnums](docs/ArrayOfEnums.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Banana](docs/Banana.md) + - [BananaReq](docs/BananaReq.md) + - [BasquePig](docs/BasquePig.md) + - [BooleanEnum](docs/BooleanEnum.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [ChildCat](docs/ChildCat.md) + - [ChildCatAllOf](docs/ChildCatAllOf.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [ComplexQuadrilateral](docs/ComplexQuadrilateral.md) + - [ComposedOneOfNumberWithValidations](docs/ComposedOneOfNumberWithValidations.md) + - [ComposedSchemaWithPropsAndNoAddProps](docs/ComposedSchemaWithPropsAndNoAddProps.md) + - [DanishPig](docs/DanishPig.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [Drawing](docs/Drawing.md) + - [EgressThresholdOptions](docs/EgressThresholdOptions.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [EquilateralTriangle](docs/EquilateralTriangle.md) + - [File](docs/File.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [Foo](docs/Foo.md) + - [FooGetDefaultResponse](docs/FooGetDefaultResponse.md) + - [FooObject](docs/FooObject.md) + - [FormatTest](docs/FormatTest.md) + - [Fruit](docs/Fruit.md) + - [FruitReq](docs/FruitReq.md) + - [GmFruit](docs/GmFruit.md) + - [GmFruitNoProperties](docs/GmFruitNoProperties.md) + - [GrandparentAnimal](docs/GrandparentAnimal.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [HealthCheckResult](docs/HealthCheckResult.md) + - [InlineAdditionalPropertiesRefPayload](docs/InlineAdditionalPropertiesRefPayload.md) + - [IntegerEnum](docs/IntegerEnum.md) + - [IntegerEnumOneValue](docs/IntegerEnumOneValue.md) + - [IntegerEnumWithDefaultValue](docs/IntegerEnumWithDefaultValue.md) + - [IsoscelesTriangle](docs/IsoscelesTriangle.md) + - [Legs](docs/Legs.md) + - [List](docs/List.md) + - [Mammal](docs/Mammal.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelReturn](docs/ModelReturn.md) + - [Mole](docs/Mole.md) + - [Name](docs/Name.md) + - [NullableClass](docs/NullableClass.md) + - [NullableShape](docs/NullableShape.md) + - [NumberOnly](docs/NumberOnly.md) + - [NumberWithValidations](docs/NumberWithValidations.md) + - [ObjectInterface](docs/ObjectInterface.md) + - [ObjectModelWithRefProps](docs/ObjectModelWithRefProps.md) + - [ObjectWithValidations](docs/ObjectWithValidations.md) + - [Order](docs/Order.md) + - [ParentPet](docs/ParentPet.md) + - [Pet](docs/Pet.md) + - [Pig](docs/Pig.md) + - [PostInlineAdditionalPropertiesPayloadRequest](docs/PostInlineAdditionalPropertiesPayloadRequest.md) + - [PostInlineAdditionalPropertiesPayloadRequestArrayDataInner](docs/PostInlineAdditionalPropertiesPayloadRequestArrayDataInner.md) + - [PublishOptions](docs/PublishOptions.md) + - [PublishOptionsPublish](docs/PublishOptionsPublish.md) + - [Quadrilateral](docs/Quadrilateral.md) + - [QuadrilateralInterface](docs/QuadrilateralInterface.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Readonly](docs/Readonly.md) + - [ScaleneTriangle](docs/ScaleneTriangle.md) + - [Shape](docs/Shape.md) + - [ShapeInterface](docs/ShapeInterface.md) + - [ShapeOrNull](docs/ShapeOrNull.md) + - [SimpleQuadrilateral](docs/SimpleQuadrilateral.md) + - [SomeObject](docs/SomeObject.md) + - [SomeObjectWithSelfAttr](docs/SomeObjectWithSelfAttr.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [StreamOptions](docs/StreamOptions.md) + - [StringBooleanMap](docs/StringBooleanMap.md) + - [StringEnum](docs/StringEnum.md) + - [StringEnumWithDefaultValue](docs/StringEnumWithDefaultValue.md) + - [Tag](docs/Tag.md) + - [Triangle](docs/Triangle.md) + - [TriangleInterface](docs/TriangleInterface.md) + - [User](docs/User.md) + - [Whale](docs/Whale.md) + - [Zebra](docs/Zebra.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + +## bearer_test + +- **Type**: Bearer authentication (JWT) + + +## http_basic_test + +- **Type**: HTTP basic authentication + + +## http_signature_test + +- **Type**: HTTP signature authentication + + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + + +## Author + + + + +## Notes for Large OpenAPI documents +If the OpenAPI document is large, imports in petstore_api.apis and petstore_api.models may fail with a +RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: + +Solution 1: +Use specific imports for apis and models like: +- `from petstore_api.api.default_api import DefaultApi` +- `from petstore_api.model.pet import Pet` + +Solution 2: +Before importing the package, adjust the maximum recursion limit as shown below: +``` +import sys +sys.setrecursionlimit(1500) +import petstore_api +from petstore_api.apis import * +from petstore_api.models import * +``` + diff --git a/samples/openapi3/client/petstore/python-experimental/dev-requirements.txt b/samples/openapi3/client/petstore/python-prior/dev-requirements.txt similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/dev-requirements.txt rename to samples/openapi3/client/petstore/python-prior/dev-requirements.txt diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-prior/docs/AdditionalPropertiesClass.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md rename to samples/openapi3/client/petstore/python-prior/docs/AdditionalPropertiesClass.md diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithArrayOfEnums.md b/samples/openapi3/client/petstore/python-prior/docs/AdditionalPropertiesWithArrayOfEnums.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithArrayOfEnums.md rename to samples/openapi3/client/petstore/python-prior/docs/AdditionalPropertiesWithArrayOfEnums.md diff --git a/samples/openapi3/client/petstore/python/docs/Address.md b/samples/openapi3/client/petstore/python-prior/docs/Address.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Address.md rename to samples/openapi3/client/petstore/python-prior/docs/Address.md diff --git a/samples/openapi3/client/petstore/python/docs/Animal.md b/samples/openapi3/client/petstore/python-prior/docs/Animal.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Animal.md rename to samples/openapi3/client/petstore/python-prior/docs/Animal.md diff --git a/samples/openapi3/client/petstore/python/docs/AnimalFarm.md b/samples/openapi3/client/petstore/python-prior/docs/AnimalFarm.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/AnimalFarm.md rename to samples/openapi3/client/petstore/python-prior/docs/AnimalFarm.md diff --git a/samples/openapi3/client/petstore/python/docs/AnotherFakeApi.md b/samples/openapi3/client/petstore/python-prior/docs/AnotherFakeApi.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/AnotherFakeApi.md rename to samples/openapi3/client/petstore/python-prior/docs/AnotherFakeApi.md diff --git a/samples/openapi3/client/petstore/python/docs/ApiResponse.md b/samples/openapi3/client/petstore/python-prior/docs/ApiResponse.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ApiResponse.md rename to samples/openapi3/client/petstore/python-prior/docs/ApiResponse.md diff --git a/samples/openapi3/client/petstore/python/docs/Apple.md b/samples/openapi3/client/petstore/python-prior/docs/Apple.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Apple.md rename to samples/openapi3/client/petstore/python-prior/docs/Apple.md diff --git a/samples/openapi3/client/petstore/python/docs/AppleReq.md b/samples/openapi3/client/petstore/python-prior/docs/AppleReq.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/AppleReq.md rename to samples/openapi3/client/petstore/python-prior/docs/AppleReq.md diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-prior/docs/ArrayOfArrayOfNumberOnly.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md rename to samples/openapi3/client/petstore/python-prior/docs/ArrayOfArrayOfNumberOnly.md diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfEnums.md b/samples/openapi3/client/petstore/python-prior/docs/ArrayOfEnums.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ArrayOfEnums.md rename to samples/openapi3/client/petstore/python-prior/docs/ArrayOfEnums.md diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-prior/docs/ArrayOfNumberOnly.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md rename to samples/openapi3/client/petstore/python-prior/docs/ArrayOfNumberOnly.md diff --git a/samples/openapi3/client/petstore/python/docs/ArrayTest.md b/samples/openapi3/client/petstore/python-prior/docs/ArrayTest.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ArrayTest.md rename to samples/openapi3/client/petstore/python-prior/docs/ArrayTest.md diff --git a/samples/openapi3/client/petstore/python/docs/Banana.md b/samples/openapi3/client/petstore/python-prior/docs/Banana.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Banana.md rename to samples/openapi3/client/petstore/python-prior/docs/Banana.md diff --git a/samples/openapi3/client/petstore/python/docs/BananaReq.md b/samples/openapi3/client/petstore/python-prior/docs/BananaReq.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/BananaReq.md rename to samples/openapi3/client/petstore/python-prior/docs/BananaReq.md diff --git a/samples/openapi3/client/petstore/python/docs/BasquePig.md b/samples/openapi3/client/petstore/python-prior/docs/BasquePig.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/BasquePig.md rename to samples/openapi3/client/petstore/python-prior/docs/BasquePig.md diff --git a/samples/openapi3/client/petstore/python/docs/BooleanEnum.md b/samples/openapi3/client/petstore/python-prior/docs/BooleanEnum.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/BooleanEnum.md rename to samples/openapi3/client/petstore/python-prior/docs/BooleanEnum.md diff --git a/samples/openapi3/client/petstore/python/docs/Capitalization.md b/samples/openapi3/client/petstore/python-prior/docs/Capitalization.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Capitalization.md rename to samples/openapi3/client/petstore/python-prior/docs/Capitalization.md diff --git a/samples/openapi3/client/petstore/python/docs/Cat.md b/samples/openapi3/client/petstore/python-prior/docs/Cat.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Cat.md rename to samples/openapi3/client/petstore/python-prior/docs/Cat.md diff --git a/samples/openapi3/client/petstore/python/docs/CatAllOf.md b/samples/openapi3/client/petstore/python-prior/docs/CatAllOf.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/CatAllOf.md rename to samples/openapi3/client/petstore/python-prior/docs/CatAllOf.md diff --git a/samples/openapi3/client/petstore/python/docs/Category.md b/samples/openapi3/client/petstore/python-prior/docs/Category.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Category.md rename to samples/openapi3/client/petstore/python-prior/docs/Category.md diff --git a/samples/openapi3/client/petstore/python/docs/ChildCat.md b/samples/openapi3/client/petstore/python-prior/docs/ChildCat.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ChildCat.md rename to samples/openapi3/client/petstore/python-prior/docs/ChildCat.md diff --git a/samples/openapi3/client/petstore/python/docs/ChildCatAllOf.md b/samples/openapi3/client/petstore/python-prior/docs/ChildCatAllOf.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ChildCatAllOf.md rename to samples/openapi3/client/petstore/python-prior/docs/ChildCatAllOf.md diff --git a/samples/openapi3/client/petstore/python/docs/ClassModel.md b/samples/openapi3/client/petstore/python-prior/docs/ClassModel.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ClassModel.md rename to samples/openapi3/client/petstore/python-prior/docs/ClassModel.md diff --git a/samples/openapi3/client/petstore/python/docs/Client.md b/samples/openapi3/client/petstore/python-prior/docs/Client.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Client.md rename to samples/openapi3/client/petstore/python-prior/docs/Client.md diff --git a/samples/openapi3/client/petstore/python/docs/ComplexQuadrilateral.md b/samples/openapi3/client/petstore/python-prior/docs/ComplexQuadrilateral.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ComplexQuadrilateral.md rename to samples/openapi3/client/petstore/python-prior/docs/ComplexQuadrilateral.md diff --git a/samples/openapi3/client/petstore/python/docs/ComposedOneOfNumberWithValidations.md b/samples/openapi3/client/petstore/python-prior/docs/ComposedOneOfNumberWithValidations.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ComposedOneOfNumberWithValidations.md rename to samples/openapi3/client/petstore/python-prior/docs/ComposedOneOfNumberWithValidations.md diff --git a/samples/openapi3/client/petstore/python/docs/ComposedSchemaWithPropsAndNoAddProps.md b/samples/openapi3/client/petstore/python-prior/docs/ComposedSchemaWithPropsAndNoAddProps.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ComposedSchemaWithPropsAndNoAddProps.md rename to samples/openapi3/client/petstore/python-prior/docs/ComposedSchemaWithPropsAndNoAddProps.md diff --git a/samples/openapi3/client/petstore/python/docs/DanishPig.md b/samples/openapi3/client/petstore/python-prior/docs/DanishPig.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/DanishPig.md rename to samples/openapi3/client/petstore/python-prior/docs/DanishPig.md diff --git a/samples/openapi3/client/petstore/python/docs/DefaultApi.md b/samples/openapi3/client/petstore/python-prior/docs/DefaultApi.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/DefaultApi.md rename to samples/openapi3/client/petstore/python-prior/docs/DefaultApi.md diff --git a/samples/openapi3/client/petstore/python/docs/Dog.md b/samples/openapi3/client/petstore/python-prior/docs/Dog.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Dog.md rename to samples/openapi3/client/petstore/python-prior/docs/Dog.md diff --git a/samples/openapi3/client/petstore/python/docs/DogAllOf.md b/samples/openapi3/client/petstore/python-prior/docs/DogAllOf.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/DogAllOf.md rename to samples/openapi3/client/petstore/python-prior/docs/DogAllOf.md diff --git a/samples/openapi3/client/petstore/python/docs/Drawing.md b/samples/openapi3/client/petstore/python-prior/docs/Drawing.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Drawing.md rename to samples/openapi3/client/petstore/python-prior/docs/Drawing.md diff --git a/samples/openapi3/client/petstore/python/docs/EgressThresholdOptions.md b/samples/openapi3/client/petstore/python-prior/docs/EgressThresholdOptions.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/EgressThresholdOptions.md rename to samples/openapi3/client/petstore/python-prior/docs/EgressThresholdOptions.md diff --git a/samples/openapi3/client/petstore/python/docs/EnumArrays.md b/samples/openapi3/client/petstore/python-prior/docs/EnumArrays.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/EnumArrays.md rename to samples/openapi3/client/petstore/python-prior/docs/EnumArrays.md diff --git a/samples/openapi3/client/petstore/python/docs/EnumClass.md b/samples/openapi3/client/petstore/python-prior/docs/EnumClass.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/EnumClass.md rename to samples/openapi3/client/petstore/python-prior/docs/EnumClass.md diff --git a/samples/openapi3/client/petstore/python/docs/EnumTest.md b/samples/openapi3/client/petstore/python-prior/docs/EnumTest.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/EnumTest.md rename to samples/openapi3/client/petstore/python-prior/docs/EnumTest.md diff --git a/samples/openapi3/client/petstore/python/docs/EquilateralTriangle.md b/samples/openapi3/client/petstore/python-prior/docs/EquilateralTriangle.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/EquilateralTriangle.md rename to samples/openapi3/client/petstore/python-prior/docs/EquilateralTriangle.md diff --git a/samples/openapi3/client/petstore/python-prior/docs/FakeApi.md b/samples/openapi3/client/petstore/python-prior/docs/FakeApi.md new file mode 100644 index 0000000000..07ecc5cf92 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/docs/FakeApi.md @@ -0,0 +1,2141 @@ +# petstore_api.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**additional_properties_with_array_of_enums**](FakeApi.md#additional_properties_with_array_of_enums) | **GET** /fake/additional-properties-with-array-of-enums | Additional Properties with Array of Enums +[**array_model**](FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | +[**array_of_enums**](FakeApi.md#array_of_enums) | **POST** /fake/refs/array-of-enums | Array of Enums +[**boolean**](FakeApi.md#boolean) | **POST** /fake/refs/boolean | +[**composed_one_of_number_with_validations**](FakeApi.md#composed_one_of_number_with_validations) | **POST** /fake/refs/composed_one_of_number_with_validations | +[**download_attachment**](FakeApi.md#download_attachment) | **GET** /{fileName} | downloads a file using Content-Disposition +[**enum_test**](FakeApi.md#enum_test) | **POST** /fake/refs/enum-test | Object contains enum properties and array properties containing enums +[**fake_health_get**](FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint +[**mammal**](FakeApi.md#mammal) | **POST** /fake/refs/mammal | +[**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | +[**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +[**post_inline_additional_properties_payload**](FakeApi.md#post_inline_additional_properties_payload) | **POST** /fake/postInlineAdditionalPropertiesPayload | +[**post_inline_additional_properties_ref_payload**](FakeApi.md#post_inline_additional_properties_ref_payload) | **POST** /fake/postInlineAdditionalPropertiesRefPayload | +[**string**](FakeApi.md#string) | **POST** /fake/refs/string | +[**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | +[**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | +[**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | +[**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model +[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +[**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data +[**test_query_parameter_collection_format**](FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | +[**tx_rx_all_of_model**](FakeApi.md#tx_rx_all_of_model) | **POST** /fake/TxRxAllOfModel | +[**tx_rx_any_of_model**](FakeApi.md#tx_rx_any_of_model) | **POST** /fake/TxRxAnyOfModel | +[**upload_download_file**](FakeApi.md#upload_download_file) | **POST** /fake/uploadDownloadFile | uploads a file and downloads a file using application/octet-stream +[**upload_file**](FakeApi.md#upload_file) | **POST** /fake/uploadFile | uploads a file using multipart/form-data +[**upload_files**](FakeApi.md#upload_files) | **POST** /fake/uploadFiles | uploads files using multipart/form-data + + +# **additional_properties_with_array_of_enums** +> AdditionalPropertiesWithArrayOfEnums additional_properties_with_array_of_enums() + +Additional Properties with Array of Enums + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + additional_properties_with_array_of_enums = AdditionalPropertiesWithArrayOfEnums( + key=[ + EnumClass("-efg"), + ], + ) # AdditionalPropertiesWithArrayOfEnums | Input enum (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Additional Properties with Array of Enums + api_response = api_instance.additional_properties_with_array_of_enums(additional_properties_with_array_of_enums=additional_properties_with_array_of_enums) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->additional_properties_with_array_of_enums: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **additional_properties_with_array_of_enums** | [**AdditionalPropertiesWithArrayOfEnums**](AdditionalPropertiesWithArrayOfEnums.md)| Input enum | [optional] + +### Return type + +[**AdditionalPropertiesWithArrayOfEnums**](AdditionalPropertiesWithArrayOfEnums.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Got object with additional properties with array of enums | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **array_model** +> AnimalFarm array_model() + + + +Test serialization of ArrayModel + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.animal_farm import AnimalFarm +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = AnimalFarm([ + Animal(), + ]) # AnimalFarm | Input model (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.array_model(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->array_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**AnimalFarm**](AnimalFarm.md)| Input model | [optional] + +### Return type + +[**AnimalFarm**](AnimalFarm.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output model | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **array_of_enums** +> ArrayOfEnums array_of_enums() + +Array of Enums + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.array_of_enums import ArrayOfEnums +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + array_of_enums = ArrayOfEnums([ + StringEnum("placed"), + ]) # ArrayOfEnums | Input enum (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Array of Enums + api_response = api_instance.array_of_enums(array_of_enums=array_of_enums) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->array_of_enums: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **array_of_enums** | [**ArrayOfEnums**](ArrayOfEnums.md)| Input enum | [optional] + +### Return type + +[**ArrayOfEnums**](ArrayOfEnums.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Got named array of enums | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **boolean** +> bool boolean() + + + +Test serialization of outer boolean types + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = True # bool | Input boolean as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.boolean(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->boolean: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **bool**| Input boolean as post body | [optional] + +### Return type + +**bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output boolean | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **composed_one_of_number_with_validations** +> ComposedOneOfNumberWithValidations composed_one_of_number_with_validations() + + + +Test serialization of object with $refed properties + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.composed_one_of_number_with_validations import ComposedOneOfNumberWithValidations +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + composed_one_of_number_with_validations = ComposedOneOfNumberWithValidations(None) # ComposedOneOfNumberWithValidations | Input model (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.composed_one_of_number_with_validations(composed_one_of_number_with_validations=composed_one_of_number_with_validations) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->composed_one_of_number_with_validations: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **composed_one_of_number_with_validations** | [**ComposedOneOfNumberWithValidations**](ComposedOneOfNumberWithValidations.md)| Input model | [optional] + +### Return type + +[**ComposedOneOfNumberWithValidations**](ComposedOneOfNumberWithValidations.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output model | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **download_attachment** +> file_type download_attachment(file_name) + +downloads a file using Content-Disposition + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + file_name = "fileName_example" # str | file name + + # example passing only required values which don't have defaults set + try: + # downloads a file using Content-Disposition + api_response = api_instance.download_attachment(file_name) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->download_attachment: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **file_name** | **str**| file name | + +### Return type + +**file_type** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | * Content-Disposition - describes the received file. Looks like: 'attachment; filename=fileName.txt'
        | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **enum_test** +> EnumTest enum_test() + +Object contains enum properties and array properties containing enums + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.enum_test import EnumTest +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + enum_test = EnumTest( + enum_string="UPPER", + enum_string_required="UPPER", + enum_integer=1, + enum_number=1.1, + enum_bool=False, + bool_enum=BooleanEnum(True), + string_enum=StringEnum("placed"), + integer_enum=IntegerEnum(0), + string_enum_with_default_value=StringEnumWithDefaultValue("placed"), + integer_enum_with_default_value=IntegerEnumWithDefaultValue(0), + integer_enum_one_value=IntegerEnumOneValue(0), + inline_array_of_str_enum=[ + StringEnum("placed"), + ], + array_of_str_enum=ArrayOfEnums([ + StringEnum("placed"), + ]), + ) # EnumTest | Input object (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Object contains enum properties and array properties containing enums + api_response = api_instance.enum_test(enum_test=enum_test) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->enum_test: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enum_test** | [**EnumTest**](EnumTest.md)| Input object | [optional] + +### Return type + +[**EnumTest**](EnumTest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Got object containing enums | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **fake_health_get** +> HealthCheckResult fake_health_get() + +Health check endpoint + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.health_check_result import HealthCheckResult +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Health check endpoint + api_response = api_instance.fake_health_get() + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->fake_health_get: %s\n" % e) +``` + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | The instance started successfully | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **mammal** +> Mammal mammal(mammal) + + + +Test serialization of mammals + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.mammal import Mammal +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + mammal = Mammal(None) # Mammal | Input mammal + + # example passing only required values which don't have defaults set + try: + api_response = api_instance.mammal(mammal) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->mammal: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **mammal** | [**Mammal**](Mammal.md)| Input mammal | + +### Return type + +[**Mammal**](Mammal.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output mammal | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **number_with_validations** +> NumberWithValidations number_with_validations() + + + +Test serialization of outer number types + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.number_with_validations import NumberWithValidations +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = NumberWithValidations(10) # NumberWithValidations | Input number as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.number_with_validations(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->number_with_validations: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**NumberWithValidations**](NumberWithValidations.md)| Input number as post body | [optional] + +### Return type + +[**NumberWithValidations**](NumberWithValidations.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output number | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **object_model_with_ref_props** +> ObjectModelWithRefProps object_model_with_ref_props() + + + +Test serialization of object with $refed properties + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = ObjectModelWithRefProps( + my_number=NumberWithValidations(10), + my_string="my_string_example", + my_boolean=True, + ) # ObjectModelWithRefProps | Input model (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.object_model_with_ref_props(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**ObjectModelWithRefProps**](ObjectModelWithRefProps.md)| Input model | [optional] + +### Return type + +[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output model | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **post_inline_additional_properties_payload** +> PostInlineAdditionalPropertiesPayloadRequest post_inline_additional_properties_payload() + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.post_inline_additional_properties_payload_request import PostInlineAdditionalPropertiesPayloadRequest +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + post_inline_additional_properties_payload_request = PostInlineAdditionalPropertiesPayloadRequest( + array_data=[ + PostInlineAdditionalPropertiesPayloadRequestArrayDataInner( + labels=[ + "labels_example", + ], + ), + ], + ) # PostInlineAdditionalPropertiesPayloadRequest | (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.post_inline_additional_properties_payload(post_inline_additional_properties_payload_request=post_inline_additional_properties_payload_request) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->post_inline_additional_properties_payload: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **post_inline_additional_properties_payload_request** | [**PostInlineAdditionalPropertiesPayloadRequest**](PostInlineAdditionalPropertiesPayloadRequest.md)| | [optional] + +### Return type + +[**PostInlineAdditionalPropertiesPayloadRequest**](PostInlineAdditionalPropertiesPayloadRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | InlineAdditionalPropertiesPayload | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **post_inline_additional_properties_ref_payload** +> InlineAdditionalPropertiesRefPayload post_inline_additional_properties_ref_payload() + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( + array_data=[ + PostInlineAdditionalPropertiesPayloadRequestArrayDataInner( + labels=[ + "labels_example", + ], + ), + ], + ) # InlineAdditionalPropertiesRefPayload | (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.post_inline_additional_properties_ref_payload(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->post_inline_additional_properties_ref_payload: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **inline_additional_properties_ref_payload** | [**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md)| | [optional] + +### Return type + +[**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | InlineAdditionalPropertiesRefPayload | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **string** +> str string() + + + +Test serialization of outer string types + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = "body_example" # str | Input string as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.string(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **str**| Input string as post body | [optional] + +### Return type + +**str** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output string | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **string_enum** +> StringEnum string_enum() + + + +Test serialization of outer enum + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.string_enum import StringEnum +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = StringEnum("placed") # StringEnum | Input enum (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.string_enum(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string_enum: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**StringEnum**](StringEnum.md)| Input enum | [optional] + +### Return type + +[**StringEnum**](StringEnum.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output enum | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_with_file_schema** +> test_body_with_file_schema(file_schema_test_class) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.file_schema_test_class import FileSchemaTestClass +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + file_schema_test_class = FileSchemaTestClass( + file=File( + source_uri="source_uri_example", + ), + files=[ + File( + source_uri="source_uri_example", + ), + ], + ) # FileSchemaTestClass | + + # example passing only required values which don't have defaults set + try: + api_instance.test_body_with_file_schema(file_schema_test_class) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_body_with_file_schema: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **file_schema_test_class** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_with_query_params** +> test_body_with_query_params(query, user) + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + query = "query_example" # str | + user = User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + object_with_no_declared_props={}, + object_with_no_declared_props_nullable={}, + any_type_prop=None, + any_type_prop_nullable=None, + ) # User | + + # example passing only required values which don't have defaults set + try: + api_instance.test_body_with_query_params(query, user) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_body_with_query_params: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **str**| | + **user** | [**User**](User.md)| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_client_model** +> Client test_client_model(client) + +To test \"client\" model + +To test \"client\" model + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.client import Client +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + client = Client( + client="client_example", + ) # Client | client model + + # example passing only required values which don't have defaults set + try: + # To test \"client\" model + api_response = api_instance.test_client_model(client) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_client_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_endpoint_parameters** +> test_endpoint_parameters(number, double, pattern_without_delimiter, byte) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example + +* Basic Authentication (http_basic_test): + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure HTTP basic authorization: http_basic_test +configuration = petstore_api.Configuration( + username = 'YOUR_USERNAME', + password = 'YOUR_PASSWORD' +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + number = 32.1 # float | None + double = 67.8 # float | None + pattern_without_delimiter = "AUR,rZ#UM/?R,Fp^l6$ARjbhJk C>" # str | None + byte = 'YQ==' # str | None + integer = 10 # int | None (optional) + int32 = 20 # int | None (optional) + int64 = 1 # int | None (optional) + float = 3.14 # float | None (optional) + string = "A" # str | None (optional) + binary = open('/path/to/file', 'rb') # file_type | None (optional) + date = dateutil_parser('1970-01-01').date() # date | None (optional) + date_time = dateutil_parser('2020-02-02T20:20:20.22222Z') # datetime | None (optional) if omitted the server will use the default value of dateutil_parser('2010-02-01T10:20:10.11111+01:00') + password = "password_example" # str | None (optional) + param_callback = "param_callback_example" # str | None (optional) + + # example passing only required values which don't have defaults set + try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **float**| None | + **double** | **float**| None | + **pattern_without_delimiter** | **str**| None | + **byte** | **str**| None | + **integer** | **int**| None | [optional] + **int32** | **int**| None | [optional] + **int64** | **int**| None | [optional] + **float** | **float**| None | [optional] + **string** | **str**| None | [optional] + **binary** | **file_type**| None | [optional] + **date** | **date**| None | [optional] + **date_time** | **datetime**| None | [optional] if omitted the server will use the default value of dateutil_parser('2010-02-01T10:20:10.11111+01:00') + **password** | **str**| None | [optional] + **param_callback** | **str**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid username supplied | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_enum_parameters** +> test_enum_parameters() + +To test enum parameters + +To test enum parameters + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + enum_header_string_array = [ + "$", + ] # [str] | Header parameter enum test (string array) (optional) + enum_header_string = "-efg" # str | Header parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + enum_query_string_array = [ + "$", + ] # [str] | Query parameter enum test (string array) (optional) + enum_query_string = "-efg" # str | Query parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + enum_query_integer = 1 # int | Query parameter enum test (double) (optional) + enum_query_double = 1.1 # float | Query parameter enum test (double) (optional) + enum_form_string_array = [ + "$", + ] # [str] | Form parameter enum test (string array) (optional) if omitted the server will use the default value of "$" + enum_form_string = "-efg" # str | Form parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + + # example passing only required values which don't have defaults set + # and optional values + try: + # To test enum parameters + api_instance.test_enum_parameters(enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double, enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enum_header_string_array** | **[str]**| Header parameter enum test (string array) | [optional] + **enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + **enum_query_string_array** | **[str]**| Query parameter enum test (string array) | [optional] + **enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] + **enum_query_double** | **float**| Query parameter enum test (double) | [optional] + **enum_form_string_array** | **[str]**| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of "$" + **enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid request | - | +**404** | Not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_group_parameters** +> test_group_parameters(required_string_group, required_boolean_group, required_int64_group) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example + +* Bearer (JWT) Authentication (bearer_test): + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization (JWT): bearer_test +configuration = petstore_api.Configuration( + access_token = 'YOUR_BEARER_TOKEN' +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + required_string_group = 1 # int | Required String in group parameters + required_boolean_group = True # bool | Required Boolean in group parameters + required_int64_group = 1 # int | Required Integer in group parameters + string_group = 1 # int | String in group parameters (optional) + boolean_group = True # bool | Boolean in group parameters (optional) + int64_group = 1 # int | Integer in group parameters (optional) + + # example passing only required values which don't have defaults set + try: + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **required_string_group** | **int**| Required String in group parameters | + **required_boolean_group** | **bool**| Required Boolean in group parameters | + **required_int64_group** | **int**| Required Integer in group parameters | + **string_group** | **int**| String in group parameters | [optional] + **boolean_group** | **bool**| Boolean in group parameters | [optional] + **int64_group** | **int**| Integer in group parameters | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Someting wrong | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_inline_additional_properties** +> test_inline_additional_properties(request_body) + +test inline additionalProperties + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + request_body = { + "key": "key_example", + } # {str: (str,)} | request body + + # example passing only required values which don't have defaults set + try: + # test inline additionalProperties + api_instance.test_inline_additional_properties(request_body) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **request_body** | **{str: (str,)}**| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_json_form_data** +> test_json_form_data(param, param2) + +test json serialization of form data + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + param = "param_example" # str | field1 + param2 = "param2_example" # str | field2 + + # example passing only required values which don't have defaults set + try: + # test json serialization of form data + api_instance.test_json_form_data(param, param2) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_json_form_data: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **str**| field1 | + **param2** | **str**| field2 | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_query_parameter_collection_format** +> test_query_parameter_collection_format(pipe, ioutil, http, url, context) + + + +To test the collection format in query parameters + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + pipe = [ + "pipe_example", + ] # [str] | + ioutil = [ + "ioutil_example", + ] # [str] | + http = [ + "http_example", + ] # [str] | + url = [ + "url_example", + ] # [str] | + context = [ + "context_example", + ] # [str] | + + # example passing only required values which don't have defaults set + try: + api_instance.test_query_parameter_collection_format(pipe, ioutil, http, url, context) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_query_parameter_collection_format: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pipe** | **[str]**| | + **ioutil** | **[str]**| | + **http** | **[str]**| | + **url** | **[str]**| | + **context** | **[str]**| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **tx_rx_all_of_model** +> StreamOptions tx_rx_all_of_model() + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.stream_options import StreamOptions +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + stream_options = StreamOptions(None) # StreamOptions | (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.tx_rx_all_of_model(stream_options=stream_options) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->tx_rx_all_of_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **stream_options** | [**StreamOptions**](StreamOptions.md)| | [optional] + +### Return type + +[**StreamOptions**](StreamOptions.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **tx_rx_any_of_model** +> GmFruitNoProperties tx_rx_any_of_model() + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.gm_fruit_no_properties import GmFruitNoProperties +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + gm_fruit_no_properties = GmFruitNoProperties(None) # GmFruitNoProperties | (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.tx_rx_any_of_model(gm_fruit_no_properties=gm_fruit_no_properties) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->tx_rx_any_of_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **gm_fruit_no_properties** | [**GmFruitNoProperties**](GmFruitNoProperties.md)| | [optional] + +### Return type + +[**GmFruitNoProperties**](GmFruitNoProperties.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | TxRxAnyOfModel | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **upload_download_file** +> file_type upload_download_file(body) + +uploads a file and downloads a file using application/octet-stream + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = open('/path/to/file', 'rb') # file_type | + + # example passing only required values which don't have defaults set + try: + # uploads a file and downloads a file using application/octet-stream + api_response = api_instance.upload_download_file(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->upload_download_file: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **file_type**| | + +### Return type + +**file_type** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/octet-stream + - **Accept**: application/octet-stream + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **upload_file** +> ApiResponse upload_file(file) + +uploads a file using multipart/form-data + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.api_response import ApiResponse +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + file = open('/path/to/file', 'rb') # file_type | file to upload + additional_metadata = "additional_metadata_example" # str | Additional data to pass to server (optional) + + # example passing only required values which don't have defaults set + try: + # uploads a file using multipart/form-data + api_response = api_instance.upload_file(file) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->upload_file: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # uploads a file using multipart/form-data + api_response = api_instance.upload_file(file, additional_metadata=additional_metadata) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->upload_file: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **file** | **file_type**| file to upload | + **additional_metadata** | **str**| Additional data to pass to server | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **upload_files** +> ApiResponse upload_files() + +uploads files using multipart/form-data + + + +### Example + + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.api_response import ApiResponse +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + files = [ + open('/path/to/file', 'rb'), + ] # [file_type] | (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + # uploads files using multipart/form-data + api_response = api_instance.upload_files(files=files) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->upload_files: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **files** | **[file_type]**| | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/python-prior/docs/FakeClassnameTags123Api.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/FakeClassnameTags123Api.md rename to samples/openapi3/client/petstore/python-prior/docs/FakeClassnameTags123Api.md diff --git a/samples/openapi3/client/petstore/python/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md b/samples/openapi3/client/petstore/python-prior/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md rename to samples/openapi3/client/petstore/python-prior/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md diff --git a/samples/openapi3/client/petstore/python/docs/File.md b/samples/openapi3/client/petstore/python-prior/docs/File.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/File.md rename to samples/openapi3/client/petstore/python-prior/docs/File.md diff --git a/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python-prior/docs/FileSchemaTestClass.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md rename to samples/openapi3/client/petstore/python-prior/docs/FileSchemaTestClass.md diff --git a/samples/openapi3/client/petstore/python/docs/Foo.md b/samples/openapi3/client/petstore/python-prior/docs/Foo.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Foo.md rename to samples/openapi3/client/petstore/python-prior/docs/Foo.md diff --git a/samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md b/samples/openapi3/client/petstore/python-prior/docs/FooGetDefaultResponse.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md rename to samples/openapi3/client/petstore/python-prior/docs/FooGetDefaultResponse.md diff --git a/samples/openapi3/client/petstore/python/docs/FooObject.md b/samples/openapi3/client/petstore/python-prior/docs/FooObject.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/FooObject.md rename to samples/openapi3/client/petstore/python-prior/docs/FooObject.md diff --git a/samples/openapi3/client/petstore/python/docs/FormatTest.md b/samples/openapi3/client/petstore/python-prior/docs/FormatTest.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/FormatTest.md rename to samples/openapi3/client/petstore/python-prior/docs/FormatTest.md diff --git a/samples/openapi3/client/petstore/python/docs/Fruit.md b/samples/openapi3/client/petstore/python-prior/docs/Fruit.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Fruit.md rename to samples/openapi3/client/petstore/python-prior/docs/Fruit.md diff --git a/samples/openapi3/client/petstore/python/docs/FruitReq.md b/samples/openapi3/client/petstore/python-prior/docs/FruitReq.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/FruitReq.md rename to samples/openapi3/client/petstore/python-prior/docs/FruitReq.md diff --git a/samples/openapi3/client/petstore/python/docs/GmFruit.md b/samples/openapi3/client/petstore/python-prior/docs/GmFruit.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/GmFruit.md rename to samples/openapi3/client/petstore/python-prior/docs/GmFruit.md diff --git a/samples/openapi3/client/petstore/python/docs/GmFruitNoProperties.md b/samples/openapi3/client/petstore/python-prior/docs/GmFruitNoProperties.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/GmFruitNoProperties.md rename to samples/openapi3/client/petstore/python-prior/docs/GmFruitNoProperties.md diff --git a/samples/openapi3/client/petstore/python/docs/GrandparentAnimal.md b/samples/openapi3/client/petstore/python-prior/docs/GrandparentAnimal.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/GrandparentAnimal.md rename to samples/openapi3/client/petstore/python-prior/docs/GrandparentAnimal.md diff --git a/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python-prior/docs/HasOnlyReadOnly.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md rename to samples/openapi3/client/petstore/python-prior/docs/HasOnlyReadOnly.md diff --git a/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python-prior/docs/HealthCheckResult.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/HealthCheckResult.md rename to samples/openapi3/client/petstore/python-prior/docs/HealthCheckResult.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md b/samples/openapi3/client/petstore/python-prior/docs/InlineAdditionalPropertiesRefPayload.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineAdditionalPropertiesRefPayload.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject.md b/samples/openapi3/client/petstore/python-prior/docs/InlineObject.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineObject.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineObject.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject1.md b/samples/openapi3/client/petstore/python-prior/docs/InlineObject1.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineObject1.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineObject1.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject2.md b/samples/openapi3/client/petstore/python-prior/docs/InlineObject2.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineObject2.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineObject2.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject3.md b/samples/openapi3/client/petstore/python-prior/docs/InlineObject3.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineObject3.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineObject3.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject4.md b/samples/openapi3/client/petstore/python-prior/docs/InlineObject4.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineObject4.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineObject4.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject5.md b/samples/openapi3/client/petstore/python-prior/docs/InlineObject5.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineObject5.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineObject5.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject6.md b/samples/openapi3/client/petstore/python-prior/docs/InlineObject6.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineObject6.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineObject6.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineResponse200.md b/samples/openapi3/client/petstore/python-prior/docs/InlineResponse200.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineResponse200.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineResponse200.md diff --git a/samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md b/samples/openapi3/client/petstore/python-prior/docs/InlineResponseDefault.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md rename to samples/openapi3/client/petstore/python-prior/docs/InlineResponseDefault.md diff --git a/samples/openapi3/client/petstore/python/docs/IntegerEnum.md b/samples/openapi3/client/petstore/python-prior/docs/IntegerEnum.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/IntegerEnum.md rename to samples/openapi3/client/petstore/python-prior/docs/IntegerEnum.md diff --git a/samples/openapi3/client/petstore/python/docs/IntegerEnumOneValue.md b/samples/openapi3/client/petstore/python-prior/docs/IntegerEnumOneValue.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/IntegerEnumOneValue.md rename to samples/openapi3/client/petstore/python-prior/docs/IntegerEnumOneValue.md diff --git a/samples/openapi3/client/petstore/python/docs/IntegerEnumWithDefaultValue.md b/samples/openapi3/client/petstore/python-prior/docs/IntegerEnumWithDefaultValue.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/IntegerEnumWithDefaultValue.md rename to samples/openapi3/client/petstore/python-prior/docs/IntegerEnumWithDefaultValue.md diff --git a/samples/openapi3/client/petstore/python/docs/IsoscelesTriangle.md b/samples/openapi3/client/petstore/python-prior/docs/IsoscelesTriangle.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/IsoscelesTriangle.md rename to samples/openapi3/client/petstore/python-prior/docs/IsoscelesTriangle.md diff --git a/samples/openapi3/client/petstore/python/docs/Legs.md b/samples/openapi3/client/petstore/python-prior/docs/Legs.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Legs.md rename to samples/openapi3/client/petstore/python-prior/docs/Legs.md diff --git a/samples/openapi3/client/petstore/python/docs/List.md b/samples/openapi3/client/petstore/python-prior/docs/List.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/List.md rename to samples/openapi3/client/petstore/python-prior/docs/List.md diff --git a/samples/openapi3/client/petstore/python/docs/Mammal.md b/samples/openapi3/client/petstore/python-prior/docs/Mammal.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Mammal.md rename to samples/openapi3/client/petstore/python-prior/docs/Mammal.md diff --git a/samples/openapi3/client/petstore/python/docs/MapTest.md b/samples/openapi3/client/petstore/python-prior/docs/MapTest.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/MapTest.md rename to samples/openapi3/client/petstore/python-prior/docs/MapTest.md diff --git a/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-prior/docs/MixedPropertiesAndAdditionalPropertiesClass.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md rename to samples/openapi3/client/petstore/python-prior/docs/MixedPropertiesAndAdditionalPropertiesClass.md diff --git a/samples/openapi3/client/petstore/python/docs/Model200Response.md b/samples/openapi3/client/petstore/python-prior/docs/Model200Response.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Model200Response.md rename to samples/openapi3/client/petstore/python-prior/docs/Model200Response.md diff --git a/samples/openapi3/client/petstore/python/docs/ModelReturn.md b/samples/openapi3/client/petstore/python-prior/docs/ModelReturn.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ModelReturn.md rename to samples/openapi3/client/petstore/python-prior/docs/ModelReturn.md diff --git a/samples/openapi3/client/petstore/python/docs/Model_200Response.md b/samples/openapi3/client/petstore/python-prior/docs/Model_200Response.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Model_200Response.md rename to samples/openapi3/client/petstore/python-prior/docs/Model_200Response.md diff --git a/samples/openapi3/client/petstore/python/docs/Model_Return.md b/samples/openapi3/client/petstore/python-prior/docs/Model_Return.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Model_Return.md rename to samples/openapi3/client/petstore/python-prior/docs/Model_Return.md diff --git a/samples/openapi3/client/petstore/python/docs/Mole.md b/samples/openapi3/client/petstore/python-prior/docs/Mole.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Mole.md rename to samples/openapi3/client/petstore/python-prior/docs/Mole.md diff --git a/samples/openapi3/client/petstore/python/docs/Name.md b/samples/openapi3/client/petstore/python-prior/docs/Name.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Name.md rename to samples/openapi3/client/petstore/python-prior/docs/Name.md diff --git a/samples/openapi3/client/petstore/python/docs/NullableClass.md b/samples/openapi3/client/petstore/python-prior/docs/NullableClass.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/NullableClass.md rename to samples/openapi3/client/petstore/python-prior/docs/NullableClass.md diff --git a/samples/openapi3/client/petstore/python/docs/NullableShape.md b/samples/openapi3/client/petstore/python-prior/docs/NullableShape.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/NullableShape.md rename to samples/openapi3/client/petstore/python-prior/docs/NullableShape.md diff --git a/samples/openapi3/client/petstore/python/docs/NumberOnly.md b/samples/openapi3/client/petstore/python-prior/docs/NumberOnly.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/NumberOnly.md rename to samples/openapi3/client/petstore/python-prior/docs/NumberOnly.md diff --git a/samples/openapi3/client/petstore/python/docs/NumberWithValidations.md b/samples/openapi3/client/petstore/python-prior/docs/NumberWithValidations.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/NumberWithValidations.md rename to samples/openapi3/client/petstore/python-prior/docs/NumberWithValidations.md diff --git a/samples/openapi3/client/petstore/python/docs/ObjectInterface.md b/samples/openapi3/client/petstore/python-prior/docs/ObjectInterface.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ObjectInterface.md rename to samples/openapi3/client/petstore/python-prior/docs/ObjectInterface.md diff --git a/samples/openapi3/client/petstore/python/docs/ObjectModelWithRefProps.md b/samples/openapi3/client/petstore/python-prior/docs/ObjectModelWithRefProps.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ObjectModelWithRefProps.md rename to samples/openapi3/client/petstore/python-prior/docs/ObjectModelWithRefProps.md diff --git a/samples/openapi3/client/petstore/python/docs/ObjectWithValidations.md b/samples/openapi3/client/petstore/python-prior/docs/ObjectWithValidations.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ObjectWithValidations.md rename to samples/openapi3/client/petstore/python-prior/docs/ObjectWithValidations.md diff --git a/samples/openapi3/client/petstore/python/docs/Order.md b/samples/openapi3/client/petstore/python-prior/docs/Order.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Order.md rename to samples/openapi3/client/petstore/python-prior/docs/Order.md diff --git a/samples/openapi3/client/petstore/python/docs/ParentPet.md b/samples/openapi3/client/petstore/python-prior/docs/ParentPet.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ParentPet.md rename to samples/openapi3/client/petstore/python-prior/docs/ParentPet.md diff --git a/samples/openapi3/client/petstore/python/docs/Pet.md b/samples/openapi3/client/petstore/python-prior/docs/Pet.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Pet.md rename to samples/openapi3/client/petstore/python-prior/docs/Pet.md diff --git a/samples/openapi3/client/petstore/python/docs/PetApi.md b/samples/openapi3/client/petstore/python-prior/docs/PetApi.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/PetApi.md rename to samples/openapi3/client/petstore/python-prior/docs/PetApi.md diff --git a/samples/openapi3/client/petstore/python/docs/Pig.md b/samples/openapi3/client/petstore/python-prior/docs/Pig.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Pig.md rename to samples/openapi3/client/petstore/python-prior/docs/Pig.md diff --git a/samples/openapi3/client/petstore/python/docs/PostInlineAdditionalPropertiesPayloadRequest.md b/samples/openapi3/client/petstore/python-prior/docs/PostInlineAdditionalPropertiesPayloadRequest.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/PostInlineAdditionalPropertiesPayloadRequest.md rename to samples/openapi3/client/petstore/python-prior/docs/PostInlineAdditionalPropertiesPayloadRequest.md diff --git a/samples/openapi3/client/petstore/python/docs/PostInlineAdditionalPropertiesPayloadRequestArrayDataInner.md b/samples/openapi3/client/petstore/python-prior/docs/PostInlineAdditionalPropertiesPayloadRequestArrayDataInner.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/PostInlineAdditionalPropertiesPayloadRequestArrayDataInner.md rename to samples/openapi3/client/petstore/python-prior/docs/PostInlineAdditionalPropertiesPayloadRequestArrayDataInner.md diff --git a/samples/openapi3/client/petstore/python/docs/PublishOptions.md b/samples/openapi3/client/petstore/python-prior/docs/PublishOptions.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/PublishOptions.md rename to samples/openapi3/client/petstore/python-prior/docs/PublishOptions.md diff --git a/samples/openapi3/client/petstore/python/docs/PublishOptionsPublish.md b/samples/openapi3/client/petstore/python-prior/docs/PublishOptionsPublish.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/PublishOptionsPublish.md rename to samples/openapi3/client/petstore/python-prior/docs/PublishOptionsPublish.md diff --git a/samples/openapi3/client/petstore/python/docs/Quadrilateral.md b/samples/openapi3/client/petstore/python-prior/docs/Quadrilateral.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Quadrilateral.md rename to samples/openapi3/client/petstore/python-prior/docs/Quadrilateral.md diff --git a/samples/openapi3/client/petstore/python/docs/QuadrilateralInterface.md b/samples/openapi3/client/petstore/python-prior/docs/QuadrilateralInterface.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/QuadrilateralInterface.md rename to samples/openapi3/client/petstore/python-prior/docs/QuadrilateralInterface.md diff --git a/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python-prior/docs/ReadOnlyFirst.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md rename to samples/openapi3/client/petstore/python-prior/docs/ReadOnlyFirst.md diff --git a/samples/openapi3/client/petstore/python/docs/Readonly.md b/samples/openapi3/client/petstore/python-prior/docs/Readonly.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Readonly.md rename to samples/openapi3/client/petstore/python-prior/docs/Readonly.md diff --git a/samples/openapi3/client/petstore/python/docs/ScaleneTriangle.md b/samples/openapi3/client/petstore/python-prior/docs/ScaleneTriangle.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ScaleneTriangle.md rename to samples/openapi3/client/petstore/python-prior/docs/ScaleneTriangle.md diff --git a/samples/openapi3/client/petstore/python/docs/Shape.md b/samples/openapi3/client/petstore/python-prior/docs/Shape.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Shape.md rename to samples/openapi3/client/petstore/python-prior/docs/Shape.md diff --git a/samples/openapi3/client/petstore/python/docs/ShapeInterface.md b/samples/openapi3/client/petstore/python-prior/docs/ShapeInterface.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ShapeInterface.md rename to samples/openapi3/client/petstore/python-prior/docs/ShapeInterface.md diff --git a/samples/openapi3/client/petstore/python/docs/ShapeOrNull.md b/samples/openapi3/client/petstore/python-prior/docs/ShapeOrNull.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/ShapeOrNull.md rename to samples/openapi3/client/petstore/python-prior/docs/ShapeOrNull.md diff --git a/samples/openapi3/client/petstore/python/docs/SimpleQuadrilateral.md b/samples/openapi3/client/petstore/python-prior/docs/SimpleQuadrilateral.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/SimpleQuadrilateral.md rename to samples/openapi3/client/petstore/python-prior/docs/SimpleQuadrilateral.md diff --git a/samples/openapi3/client/petstore/python/docs/SomeObject.md b/samples/openapi3/client/petstore/python-prior/docs/SomeObject.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/SomeObject.md rename to samples/openapi3/client/petstore/python-prior/docs/SomeObject.md diff --git a/samples/openapi3/client/petstore/python/docs/SomeObjectWithSelfAttr.md b/samples/openapi3/client/petstore/python-prior/docs/SomeObjectWithSelfAttr.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/SomeObjectWithSelfAttr.md rename to samples/openapi3/client/petstore/python-prior/docs/SomeObjectWithSelfAttr.md diff --git a/samples/openapi3/client/petstore/python/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python-prior/docs/SpecialModelName.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/SpecialModelName.md rename to samples/openapi3/client/petstore/python-prior/docs/SpecialModelName.md diff --git a/samples/openapi3/client/petstore/python/docs/StoreApi.md b/samples/openapi3/client/petstore/python-prior/docs/StoreApi.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/StoreApi.md rename to samples/openapi3/client/petstore/python-prior/docs/StoreApi.md diff --git a/samples/openapi3/client/petstore/python/docs/StreamOptions.md b/samples/openapi3/client/petstore/python-prior/docs/StreamOptions.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/StreamOptions.md rename to samples/openapi3/client/petstore/python-prior/docs/StreamOptions.md diff --git a/samples/openapi3/client/petstore/python/docs/StringBooleanMap.md b/samples/openapi3/client/petstore/python-prior/docs/StringBooleanMap.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/StringBooleanMap.md rename to samples/openapi3/client/petstore/python-prior/docs/StringBooleanMap.md diff --git a/samples/openapi3/client/petstore/python/docs/StringEnum.md b/samples/openapi3/client/petstore/python-prior/docs/StringEnum.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/StringEnum.md rename to samples/openapi3/client/petstore/python-prior/docs/StringEnum.md diff --git a/samples/openapi3/client/petstore/python/docs/StringEnumWithDefaultValue.md b/samples/openapi3/client/petstore/python-prior/docs/StringEnumWithDefaultValue.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/StringEnumWithDefaultValue.md rename to samples/openapi3/client/petstore/python-prior/docs/StringEnumWithDefaultValue.md diff --git a/samples/openapi3/client/petstore/python/docs/Tag.md b/samples/openapi3/client/petstore/python-prior/docs/Tag.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Tag.md rename to samples/openapi3/client/petstore/python-prior/docs/Tag.md diff --git a/samples/openapi3/client/petstore/python/docs/Triangle.md b/samples/openapi3/client/petstore/python-prior/docs/Triangle.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Triangle.md rename to samples/openapi3/client/petstore/python-prior/docs/Triangle.md diff --git a/samples/openapi3/client/petstore/python/docs/TriangleInterface.md b/samples/openapi3/client/petstore/python-prior/docs/TriangleInterface.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/TriangleInterface.md rename to samples/openapi3/client/petstore/python-prior/docs/TriangleInterface.md diff --git a/samples/openapi3/client/petstore/python/docs/User.md b/samples/openapi3/client/petstore/python-prior/docs/User.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/User.md rename to samples/openapi3/client/petstore/python-prior/docs/User.md diff --git a/samples/openapi3/client/petstore/python/docs/UserApi.md b/samples/openapi3/client/petstore/python-prior/docs/UserApi.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/UserApi.md rename to samples/openapi3/client/petstore/python-prior/docs/UserApi.md diff --git a/samples/openapi3/client/petstore/python/docs/Whale.md b/samples/openapi3/client/petstore/python-prior/docs/Whale.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Whale.md rename to samples/openapi3/client/petstore/python-prior/docs/Whale.md diff --git a/samples/openapi3/client/petstore/python/docs/Zebra.md b/samples/openapi3/client/petstore/python-prior/docs/Zebra.md similarity index 100% rename from samples/openapi3/client/petstore/python/docs/Zebra.md rename to samples/openapi3/client/petstore/python-prior/docs/Zebra.md diff --git a/samples/openapi3/client/petstore/python-prior/git_push.sh b/samples/openapi3/client/petstore/python-prior/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-prior/petstore_api/__init__.py new file mode 100644 index 0000000000..e79f5c78b2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/__init__.py @@ -0,0 +1,30 @@ +# flake8: noqa + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +__version__ = "1.0.0" + +# import ApiClient +from petstore_api.api_client import ApiClient + +# import Configuration +from petstore_api.configuration import Configuration +from petstore_api.signing import HttpSigningConfiguration + +# import exceptions +from petstore_api.exceptions import OpenApiException +from petstore_api.exceptions import ApiAttributeError +from petstore_api.exceptions import ApiTypeError +from petstore_api.exceptions import ApiValueError +from petstore_api.exceptions import ApiKeyError +from petstore_api.exceptions import ApiException + +__import__('sys').setrecursionlimit(1234) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/__init__.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api/__init__.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/petstore_api/api/__init__.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/api/__init__.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api/another_fake_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/api/another_fake_api.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/api/another_fake_api.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api/default_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/api/default_api.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/api/default_api.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api/fake_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/api/fake_api.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags123_api.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api/fake_classname_tags123_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags123_api.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/api/fake_classname_tags123_api.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api/fake_classname_tags_123_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/api/fake_classname_tags_123_api.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api/pet_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/api/pet_api.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/api/pet_api.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api/store_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/api/store_api.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/api/store_api.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api/user_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/api/user_api.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/api/user_api.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-prior/petstore_api/api_client.py new file mode 100644 index 0000000000..c14f1d0f1b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/api_client.py @@ -0,0 +1,903 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import json +import atexit +import mimetypes +from multiprocessing.pool import ThreadPool +import io +import os +import re +import typing +from urllib.parse import quote +from urllib3.fields import RequestField + + +from petstore_api import rest +from petstore_api.configuration import Configuration +from petstore_api.exceptions import ApiTypeError, ApiValueError, ApiException +from petstore_api.model_utils import ( + ModelNormal, + ModelSimple, + ModelComposed, + check_allowed_values, + check_validations, + date, + datetime, + deserialize_file, + file_type, + model_to_dict, + none_type, + validate_and_convert_types +) + + +class ApiClient(object): + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + :param pool_threads: The number of threads to use for async requests + to the API. More threads means more concurrent API requests. + """ + + _pool = None + + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None, pool_threads=1): + if configuration is None: + configuration = Configuration.get_default_copy() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + if self._pool: + self._pool.close() + self._pool.join() + self._pool = None + if hasattr(atexit, 'unregister'): + atexit.unregister(self.close) + + @property + def pool(self): + """Create thread pool on first request + avoids instantiating unused threadpool for blocking clients. + """ + if self._pool is None: + atexit.register(self.close) + self._pool = ThreadPool(self.pool_threads) + return self._pool + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + def __call_api( + self, + resource_path: str, + method: str, + path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + body: typing.Optional[typing.Any] = None, + post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, + response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + _return_http_data_only: typing.Optional[bool] = None, + collection_formats: typing.Optional[typing.Dict[str, str]] = None, + _preload_content: bool = True, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, + _host: typing.Optional[str] = None, + _check_type: typing.Optional[bool] = None, + _content_type: typing.Optional[str] = None, + _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None + ): + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = self.parameters_to_tuples(query_params, + collection_formats) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) + post_params.extend(self.files_parameters(files)) + if header_params['Content-Type'].startswith("multipart"): + post_params = self.parameters_to_multipart(post_params, + (dict)) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # auth setting + self.update_params_for_auth(header_params, query_params, + auth_settings, resource_path, method, body, + request_auths=_request_auths) + + # request url + if _host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + try: + # perform request and return response + response_data = self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) + except ApiException as e: + e.body = e.body.decode('utf-8') + raise e + + self.last_response = response_data + + return_data = response_data + + if not _preload_content: + return (return_data) + return return_data + + # deserialize response data + if response_type: + if response_type != (file_type,): + encoding = "utf-8" + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) + if match: + encoding = match.group(1) + response_data.data = response_data.data.decode(encoding) + + return_data = self.deserialize( + response_data, + response_type, + _check_type + ) + else: + return_data = None + + if _return_http_data_only: + return (return_data) + else: + return (return_data, response_data.status, + response_data.getheaders()) + + def parameters_to_multipart(self, params, collection_types): + """Get parameters as list of tuples, formatting as json if value is collection_types + + :param params: Parameters as list of two-tuples + :param dict collection_types: Parameter collection types + :return: Parameters as list of tuple or urllib3.fields.RequestField + """ + new_params = [] + if collection_types is None: + collection_types = (dict) + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if isinstance( + v, collection_types): # v is instance of collection_type, formatting as application/json + v = json.dumps(v, ensure_ascii=False).encode("utf-8") + field = RequestField(k, v) + field.make_multipart(content_type="application/json; charset=utf-8") + new_params.append(field) + else: + new_params.append((k, v)) + return new_params + + @classmethod + def sanitize_for_serialization(cls, obj): + """Prepares data for transmission before it is sent with the rest client + If obj is None, return None. + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + If obj is io.IOBase, return the bytes + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if isinstance(obj, (ModelNormal, ModelComposed)): + return { + key: cls.sanitize_for_serialization(val) for key, + val in model_to_dict( + obj, + serialize=True).items()} + elif isinstance(obj, io.IOBase): + return cls.get_file_data_and_close_file(obj) + elif isinstance(obj, (str, int, float, none_type, bool)): + return obj + elif isinstance(obj, (datetime, date)): + return obj.isoformat() + elif isinstance(obj, ModelSimple): + return cls.sanitize_for_serialization(obj.value) + elif isinstance(obj, (list, tuple)): + return [cls.sanitize_for_serialization(item) for item in obj] + if isinstance(obj, dict): + return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()} + raise ApiValueError( + 'Unable to prepare type {} for serialization'.format( + obj.__class__.__name__)) + + def deserialize(self, response, response_type, _check_type): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: For the response, a tuple containing: + valid classes + a list containing valid classes (for list schemas) + a dict containing a tuple of valid classes as the value + Example values: + (str,) + (Pet,) + (float, none_type) + ([int, none_type],) + ({str: (bool, str, int, float, date, datetime, str, none_type)},) + :param _check_type: boolean, whether to check the types of the data + received from the server + :type _check_type: bool + + :return: deserialized object. + """ + # handle file downloading + # save response body into a tmp file and return the instance + if response_type == (file_type,): + content_disposition = response.getheader("Content-Disposition") + return deserialize_file(response.data, self.configuration, + content_disposition=content_disposition) + + # fetch data from response object + try: + received_data = json.loads(response.data) + except ValueError: + received_data = response.data + + # store our data under the key of 'received_data' so users have some + # context if they are deserializing a string and the data type is wrong + deserialized_data = validate_and_convert_types( + received_data, + response_type, + ['received_data'], + True, + _check_type, + configuration=self.configuration + ) + return deserialized_data + + def call_api( + self, + resource_path: str, + method: str, + path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + body: typing.Optional[typing.Any] = None, + post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, + response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + async_req: typing.Optional[bool] = None, + _return_http_data_only: typing.Optional[bool] = None, + collection_formats: typing.Optional[typing.Dict[str, str]] = None, + _preload_content: bool = True, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, + _host: typing.Optional[str] = None, + _check_type: typing.Optional[bool] = None, + _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None + ): + """Makes the HTTP request (synchronous) and returns deserialized data. + + To make an async_req request, set the async_req parameter. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response_type: For the response, a tuple containing: + valid classes + a list containing valid classes (for list schemas) + a dict containing a tuple of valid classes as the value + Example values: + (str,) + (Pet,) + (float, none_type) + ([int, none_type],) + ({str: (bool, str, int, float, date, datetime, str, none_type)},) + :param files: key -> field name, value -> a list of open file + objects for `multipart/form-data`. + :type files: dict + :param async_req bool: execute request asynchronously + :type async_req: bool, optional + :param _return_http_data_only: response data without head status code + and headers + :type _return_http_data_only: bool, optional + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :type collection_formats: dict, optional + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :type _preload_content: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _check_type: boolean describing if the data back from the server + should have its type checked. + :type _check_type: bool, optional + :param _request_auths: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auths: list, optional + :return: + If async_req parameter is True, + the request will be called asynchronously. + The method will return the request thread. + If parameter async_req is False or missing, + then the method will return the response directly. + """ + if not async_req: + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_type, auth_settings, + _return_http_data_only, collection_formats, + _preload_content, _request_timeout, _host, + _check_type, _request_auths=_request_auths) + + return self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, + query_params, + header_params, body, + post_params, files, + response_type, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, _check_type, None, _request_auths)) + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" + if method == "GET": + return self.rest_client.GET(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "HEAD": + return self.rest_client.HEAD(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "OPTIONS": + return self.rest_client.OPTIONS(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "POST": + return self.rest_client.POST(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PUT": + return self.rest_client.PUT(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PATCH": + return self.rest_client.PATCH(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "DELETE": + return self.rest_client.DELETE(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + else: + raise ApiValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + @staticmethod + def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: + file_data = file_instance.read() + file_instance.close() + return file_data + + def files_parameters(self, + files: typing.Optional[typing.Dict[str, + typing.List[io.IOBase]]] = None): + """Builds form parameters. + + :param files: None or a dict with key=param_name and + value is a list of open file objects + :return: List of tuples of form parameters with file data + """ + if files is None: + return [] + + params = [] + for param_name, file_instances in files.items(): + if file_instances is None: + # if the file field is nullable, skip None values + continue + for file_instance in file_instances: + if file_instance is None: + # if the file field is nullable, skip None values + continue + if file_instance.closed is True: + raise ApiValueError( + "Cannot read a closed file. The passed in file_type " + "for %s must be open." % param_name + ) + filename = os.path.basename(file_instance.name) + filedata = self.get_file_data_and_close_file(file_instance) + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([param_name, tuple([filename, filedata, mimetype])])) + + return params + + def select_header_accept(self, accepts): + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return + + accepts = [x.lower() for x in accepts] + + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) + + def select_header_content_type(self, content_types, method=None, body=None): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :param method: http method (e.g. POST, PATCH). + :param body: http body to send. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return None + + content_types = [x.lower() for x in content_types] + + if (method == 'PATCH' and + 'application/json-patch+json' in content_types and + isinstance(body, list)): + return 'application/json-patch+json' + + if 'application/json' in content_types or '*/*' in content_types: + return 'application/json' + else: + return content_types[0] + + def update_params_for_auth(self, headers, queries, auth_settings, + resource_path, method, body, request_auths=None): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :param resource_path: A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method. + :param body: A object representing the body of the HTTP request. + The object type is the return value of _encoder.default(). + :param request_auths: if set, the provided settings will + override the token in the configuration. + """ + if not auth_settings: + return + + if request_auths: + for auth_setting in request_auths: + self._apply_auth_params( + headers, queries, resource_path, method, body, auth_setting) + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, queries, resource_path, method, body, auth_setting) + + def _apply_auth_params(self, headers, queries, resource_path, method, body, auth_setting): + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['key'] + "=" + auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + else: + # The HTTP signature scheme requires multiple HTTP headers + # that are calculated dynamically. + signing_info = self.configuration.signing_info + auth_headers = signing_info.get_http_signature_headers( + resource_path, method, headers, body, queries) + headers.update(auth_headers) + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + +class Endpoint(object): + def __init__(self, settings=None, params_map=None, root_map=None, + headers_map=None, api_client=None, callable=None): + """Creates an endpoint + + Args: + settings (dict): see below key value pairs + 'response_type' (tuple/None): response type + 'auth' (list): a list of auth type keys + 'endpoint_path' (str): the endpoint path + 'operation_id' (str): endpoint string identifier + 'http_method' (str): POST/PUT/PATCH/GET etc + 'servers' (list): list of str servers that this endpoint is at + params_map (dict): see below key value pairs + 'all' (list): list of str endpoint parameter names + 'required' (list): list of required parameter names + 'nullable' (list): list of nullable parameter names + 'enum' (list): list of parameters with enum values + 'validation' (list): list of parameters with validations + root_map + 'validations' (dict): the dict mapping endpoint parameter tuple + paths to their validation dictionaries + 'allowed_values' (dict): the dict mapping endpoint parameter + tuple paths to their allowed_values (enum) dictionaries + 'openapi_types' (dict): param_name to openapi type + 'attribute_map' (dict): param_name to camelCase name + 'location_map' (dict): param_name to 'body', 'file', 'form', + 'header', 'path', 'query' + collection_format_map (dict): param_name to `csv` etc. + headers_map (dict): see below key value pairs + 'accept' (list): list of Accept header strings + 'content_type' (list): list of Content-Type header strings + api_client (ApiClient) api client instance + callable (function): the function which is invoked when the + Endpoint is called + """ + self.settings = settings + self.params_map = params_map + self.params_map['all'].extend([ + 'async_req', + '_host_index', + '_preload_content', + '_request_timeout', + '_return_http_data_only', + '_check_input_type', + '_check_return_type', + '_content_type', + '_spec_property_naming', + '_request_auths' + ]) + self.params_map['nullable'].extend(['_request_timeout']) + self.validations = root_map['validations'] + self.allowed_values = root_map['allowed_values'] + self.openapi_types = root_map['openapi_types'] + extra_types = { + 'async_req': (bool,), + '_host_index': (none_type, int), + '_preload_content': (bool,), + '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), + '_return_http_data_only': (bool,), + '_check_input_type': (bool,), + '_check_return_type': (bool,), + '_spec_property_naming': (bool,), + '_content_type': (none_type, str), + '_request_auths': (none_type, list) + } + self.openapi_types.update(extra_types) + self.attribute_map = root_map['attribute_map'] + self.location_map = root_map['location_map'] + self.collection_format_map = root_map['collection_format_map'] + self.headers_map = headers_map + self.api_client = api_client + self.callable = callable + + def __validate_inputs(self, kwargs): + for param in self.params_map['enum']: + if param in kwargs: + check_allowed_values( + self.allowed_values, + (param,), + kwargs[param] + ) + + for param in self.params_map['validation']: + if param in kwargs: + check_validations( + self.validations, + (param,), + kwargs[param], + configuration=self.api_client.configuration + ) + + if kwargs['_check_input_type'] is False: + return + + for key, value in kwargs.items(): + fixed_val = validate_and_convert_types( + value, + self.openapi_types[key], + [key], + kwargs['_spec_property_naming'], + kwargs['_check_input_type'], + configuration=self.api_client.configuration + ) + kwargs[key] = fixed_val + + def __gather_params(self, kwargs): + params = { + 'body': None, + 'collection_format': {}, + 'file': {}, + 'form': [], + 'header': {}, + 'path': {}, + 'query': [] + } + + for param_name, param_value in kwargs.items(): + param_location = self.location_map.get(param_name) + if param_location is None: + continue + if param_location: + if param_location == 'body': + params['body'] = param_value + continue + base_name = self.attribute_map[param_name] + if (param_location == 'form' and + self.openapi_types[param_name] == (file_type,)): + params['file'][base_name] = [param_value] + elif (param_location == 'form' and + self.openapi_types[param_name] == ([file_type],)): + # param_value is already a list + params['file'][base_name] = param_value + elif param_location in {'form', 'query'}: + param_value_full = (base_name, param_value) + params[param_location].append(param_value_full) + if param_location not in {'form', 'query'}: + params[param_location][base_name] = param_value + collection_format = self.collection_format_map.get(param_name) + if collection_format: + params['collection_format'][base_name] = collection_format + + return params + + def __call__(self, *args, **kwargs): + """ This method is invoked when endpoints are called + Example: + + api_instance = AnotherFakeApi() + api_instance.call_123_test_special_tags # this is an instance of the class Endpoint + api_instance.call_123_test_special_tags() # this invokes api_instance.call_123_test_special_tags.__call__() + which then invokes the callable functions stored in that endpoint at + api_instance.call_123_test_special_tags.callable or self.callable in this class + + """ + return self.callable(self, *args, **kwargs) + + def call_with_http_info(self, **kwargs): + + try: + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) + except IndexError: + if self.settings['servers']: + raise ApiValueError( + "Invalid host index. Must be 0 <= index < %s" % + len(self.settings['servers']) + ) + _host = None + + for key, value in kwargs.items(): + if key not in self.params_map['all']: + raise ApiTypeError( + "Got an unexpected parameter '%s'" + " to method `%s`" % + (key, self.settings['operation_id']) + ) + # only throw this nullable ApiValueError if _check_input_type + # is False, if _check_input_type==True we catch this case + # in self.__validate_inputs + if (key not in self.params_map['nullable'] and value is None + and kwargs['_check_input_type'] is False): + raise ApiValueError( + "Value may not be None for non-nullable parameter `%s`" + " when calling `%s`" % + (key, self.settings['operation_id']) + ) + + for key in self.params_map['required']: + if key not in kwargs.keys(): + raise ApiValueError( + "Missing the required parameter `%s` when calling " + "`%s`" % (key, self.settings['operation_id']) + ) + + self.__validate_inputs(kwargs) + + params = self.__gather_params(kwargs) + + accept_headers_list = self.headers_map['accept'] + if accept_headers_list: + params['header']['Accept'] = self.api_client.select_header_accept( + accept_headers_list) + + if kwargs.get('_content_type'): + params['header']['Content-Type'] = kwargs['_content_type'] + else: + content_type_headers_list = self.headers_map['content_type'] + if content_type_headers_list: + if params['body'] != "": + content_types_list = self.api_client.select_header_content_type( + content_type_headers_list, self.settings['http_method'], + params['body']) + if content_types_list: + params['header']['Content-Type'] = content_types_list + + return self.api_client.call_api( + self.settings['endpoint_path'], self.settings['http_method'], + params['path'], + params['query'], + params['header'], + body=params['body'], + post_params=params['form'], + files=params['file'], + response_type=self.settings['response_type'], + auth_settings=self.settings['auth'], + async_req=kwargs['async_req'], + _check_type=kwargs['_check_return_type'], + _return_http_data_only=kwargs['_return_http_data_only'], + _preload_content=kwargs['_preload_content'], + _request_timeout=kwargs['_request_timeout'], + _host=_host, + _request_auths=kwargs['_request_auths'], + collection_formats=params['collection_format']) diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/apis/__init__.py b/samples/openapi3/client/petstore/python-prior/petstore_api/apis/__init__.py new file mode 100644 index 0000000000..381ad9572b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/apis/__init__.py @@ -0,0 +1,23 @@ + +# flake8: noqa + +# Import all APIs into this package. +# If you have many APIs here with many many models used in each API this may +# raise a `RecursionError`. +# In order to avoid this, import only the API that you directly need like: +# +# from petstore_api.api.another_fake_api import AnotherFakeApi +# +# or import this package, but before doing it, use: +# +# import sys +# sys.setrecursionlimit(n) + +# Import APIs into API package: +from petstore_api.api.another_fake_api import AnotherFakeApi +from petstore_api.api.default_api import DefaultApi +from petstore_api.api.fake_api import FakeApi +from petstore_api.api.fake_classname_tags123_api import FakeClassnameTags123Api +from petstore_api.api.pet_api import PetApi +from petstore_api.api.store_api import StoreApi +from petstore_api.api.user_api import UserApi diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-prior/petstore_api/configuration.py new file mode 100644 index 0000000000..0c4db4c52a --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/configuration.py @@ -0,0 +1,613 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import copy +import logging +import multiprocessing +import sys +import urllib3 + +from http import client as http_client +from petstore_api.exceptions import ApiValueError + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +class Configuration(object): + """NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param host: Base url + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer) + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication + :param password: Password for HTTP basic authentication + :param discard_unknown_keys: Boolean value indicating whether to discard + unknown properties. A server may send a response that includes additional + properties that are not known by the client in the following scenarios: + 1. The OpenAPI document is incomplete, i.e. it does not match the server + implementation. + 2. The client was generated using an older version of the OpenAPI document + and the server has been upgraded since then. + If a schema in the OpenAPI document defines the additionalProperties attribute, + then all undeclared properties received by the server are injected into the + additional properties map. In that case, there are undeclared properties, and + nothing to discard. + :param disabled_client_side_validations (string): Comma-separated list of + JSON schema validation keywords to disable JSON schema structural validation + rules. The following keywords may be specified: multipleOf, maximum, + exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, + maxItems, minItems. + By default, the validation is performed for data generated locally by the client + and data received from the server, independent of any validation performed by + the server side. If the input data does not satisfy the JSON schema validation + rules specified in the OpenAPI document, an exception is raised. + If disabled_client_side_validations is set, structural validation is + disabled. This can be useful to troubleshoot data validation problem, such as + when the OpenAPI document validation rules do not match the actual API data + received by the server. + :param signing_info: Configuration parameters for the HTTP signature security scheme. + Must be an instance of petstore_api.signing.HttpSigningConfiguration + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format + + :Example: + + API Key Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + cookieAuth: # name for the security scheme + type: apiKey + in: cookie + name: JSESSIONID # cookie name + + You can programmatically set the cookie: + +conf = petstore_api.Configuration( + api_key={'cookieAuth': 'abc123'} + api_key_prefix={'cookieAuth': 'JSESSIONID'} +) + + The following cookie will be added to the HTTP request: + Cookie: JSESSIONID abc123 + + HTTP Basic Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + http_basic_auth: + type: http + scheme: basic + + Configure API client with HTTP basic authentication: + +conf = petstore_api.Configuration( + username='the-user', + password='the-password', +) + + + HTTP Signature Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + http_basic_auth: + type: http + scheme: signature + + Configure API client with HTTP signature authentication. Use the 'hs2019' signature scheme, + sign the HTTP requests with the RSA-SSA-PSS signature algorithm, and set the expiration time + of the signature to 5 minutes after the signature has been created. + Note you can use the constants defined in the petstore_api.signing module, and you can + also specify arbitrary HTTP headers to be included in the HTTP signature, except for the + 'Authorization' header, which is used to carry the signature. + + One may be tempted to sign all headers by default, but in practice it rarely works. + This is because explicit proxies, transparent proxies, TLS termination endpoints or + load balancers may add/modify/remove headers. Include the HTTP headers that you know + are not going to be modified in transit. + +conf = petstore_api.Configuration( + signing_info = petstore_api.signing.HttpSigningConfiguration( + key_id = 'my-key-id', + private_key_path = 'rsa.pem', + signing_scheme = petstore_api.signing.SCHEME_HS2019, + signing_algorithm = petstore_api.signing.ALGORITHM_RSASSA_PSS, + signed_headers = [petstore_api.signing.HEADER_REQUEST_TARGET, + petstore_api.signing.HEADER_CREATED, + petstore_api.signing.HEADER_EXPIRES, + petstore_api.signing.HEADER_HOST, + petstore_api.signing.HEADER_DATE, + petstore_api.signing.HEADER_DIGEST, + 'Content-Type', + 'User-Agent' + ], + signature_max_validity = datetime.timedelta(minutes=5) + ) +) + """ + + _default = None + + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + access_token=None, + username=None, password=None, + discard_unknown_keys=False, + disabled_client_side_validations="", + signing_info=None, + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ssl_ca_cert=None, + ): + """Constructor + """ + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.access_token = access_token + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.discard_unknown_keys = discard_unknown_keys + self.disabled_client_side_validations = disabled_client_side_validations + if signing_info is not None: + signing_info.host = host + self.signing_info = signing_info + """The HTTP signing configuration + """ + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("petstore_api") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + self.debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy = None + """Proxy URL + """ + self.no_proxy = None + """bypass proxy for host in the no_proxy list. + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = None + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + # Options to pass down to the underlying urllib3 socket + self.socket_options = None + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) + if name == 'disabled_client_side_validations': + s = set(filter(None, value.split(','))) + for v in s: + if v not in JSON_SCHEMA_VALIDATION_KEYWORDS: + raise ApiValueError( + "Invalid keyword: '{0}''".format(v)) + self._disabled_client_side_validations = s + if name == "signing_info" and value is not None: + # Ensure the host parameter from signing info is the same as + # Configuration.host. + value.host = self.host + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = copy.deepcopy(default) + + @classmethod + def get_default_copy(cls): + """Return new instance of configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration passed by the set_default method. + + :return: The configuration object. + """ + if cls._default is not None: + return copy.deepcopy(cls._default) + return Configuration() + + @property + def logger_file(self): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on http_client debug + http_client.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off http_client debug + http_client.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier, alias=None): + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth = {} + if 'api_key' in self.api_key: + auth['api_key'] = { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': self.get_api_key_with_prefix( + 'api_key', + ), + } + if 'api_key_query' in self.api_key: + auth['api_key_query'] = { + 'type': 'api_key', + 'in': 'query', + 'key': 'api_key_query', + 'value': self.get_api_key_with_prefix( + 'api_key_query', + ), + } + if self.access_token is not None: + auth['bearer_test'] = { + 'type': 'bearer', + 'in': 'header', + 'format': 'JWT', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + if self.username is not None and self.password is not None: + auth['http_basic_test'] = { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_basic_auth_token() + } + if self.signing_info is not None: + auth['http_signature_test'] = { + 'type': 'http-signature', + 'in': 'header', + 'key': 'Authorization', + 'value': None # Signature headers are calculated for every HTTP request + } + if self.access_token is not None: + auth['petstore_auth'] = { + 'type': 'oauth2', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + return auth + + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 1.0.0\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "http://{server}.swagger.io:{port}/v2", + 'description': "petstore server", + 'variables': { + 'server': { + 'description': "No description provided", + 'default_value': "petstore", + 'enum_values': [ + "petstore", + "qa-petstore", + "dev-petstore" + ] + }, + 'port': { + 'description': "No description provided", + 'default_value': "80", + 'enum_values': [ + "80", + "8080" + ] + } + } + }, + { + 'url': "https://localhost:8080/{version}", + 'description': "The local server", + 'variables': { + 'version': { + 'description': "No description provided", + 'default_value': "v2", + 'enum_values': [ + "v1", + "v2" + ] + } + } + } + ] + + def get_host_from_settings(self, index, variables=None, servers=None): + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/exceptions.py b/samples/openapi3/client/petstore/python-prior/petstore_api/exceptions.py similarity index 79% rename from samples/openapi3/client/petstore/python-experimental/petstore_api/exceptions.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/exceptions.py index ed422fd2d0..d223cb4876 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/exceptions.py +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/exceptions.py @@ -1,5 +1,3 @@ -# coding: utf-8 - """ OpenAPI Petstore @@ -99,12 +97,12 @@ class ApiKeyError(OpenApiException, KeyError): class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, api_response: 'petstore_api.api_client.ApiResponse' = None): - if api_response: - self.status = api_response.response.status - self.reason = api_response.response.reason - self.body = api_response.response.data - self.headers = api_response.response.getheaders() + def __init__(self, status=None, reason=None, http_resp=None): + if http_resp: + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() else: self.status = status self.reason = reason @@ -113,7 +111,7 @@ class ApiException(OpenApiException): def __str__(self): """Custom error messages for exception""" - error_message = "({0})\n"\ + error_message = "Status Code: {0}\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: error_message += "HTTP response headers: {0}\n".format( @@ -125,6 +123,30 @@ class ApiException(OpenApiException): return error_message +class NotFoundException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(NotFoundException, self).__init__(status, reason, http_resp) + + +class UnauthorizedException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(UnauthorizedException, self).__init__(status, reason, http_resp) + + +class ForbiddenException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ForbiddenException, self).__init__(status, reason, http_resp) + + +class ServiceException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ServiceException, self).__init__(status, reason, http_resp) + + def render_path(path_to_item): """Returns a string representation of a path""" result = "" diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/__init__.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/__init__.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/petstore_api/model/__init__.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/__init__.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/additional_properties_class.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/additional_properties_class.py new file mode 100644 index 0000000000..307a8c772f --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/additional_properties_class.py @@ -0,0 +1,291 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class AdditionalPropertiesClass(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'map_property': ({str: (str,)},), # noqa: E501 + 'map_of_map_property': ({str: ({str: (str,)},)},), # noqa: E501 + 'anytype_1': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 + 'map_with_undeclared_properties_anytype_1': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + 'map_with_undeclared_properties_anytype_2': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + 'map_with_undeclared_properties_anytype_3': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + 'empty_map': (dict,), # noqa: E501 + 'map_with_undeclared_properties_string': ({str: (str,)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'map_property': 'map_property', # noqa: E501 + 'map_of_map_property': 'map_of_map_property', # noqa: E501 + 'anytype_1': 'anytype_1', # noqa: E501 + 'map_with_undeclared_properties_anytype_1': 'map_with_undeclared_properties_anytype_1', # noqa: E501 + 'map_with_undeclared_properties_anytype_2': 'map_with_undeclared_properties_anytype_2', # noqa: E501 + 'map_with_undeclared_properties_anytype_3': 'map_with_undeclared_properties_anytype_3', # noqa: E501 + 'empty_map': 'empty_map', # noqa: E501 + 'map_with_undeclared_properties_string': 'map_with_undeclared_properties_string', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_property ({str: (str,)}): [optional] # noqa: E501 + map_of_map_property ({str: ({str: (str,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_1 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_2 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_3 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + empty_map (dict): an object with no declared properties and no undeclared properties, hence it's an empty map.. [optional] # noqa: E501 + map_with_undeclared_properties_string ({str: (str,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_property ({str: (str,)}): [optional] # noqa: E501 + map_of_map_property ({str: ({str: (str,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_1 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_2 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_3 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + empty_map (dict): an object with no declared properties and no undeclared properties, hence it's an empty map.. [optional] # noqa: E501 + map_with_undeclared_properties_string ({str: (str,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/additional_properties_with_array_of_enums.py new file mode 100644 index 0000000000..9b33b4689d --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/additional_properties_with_array_of_enums.py @@ -0,0 +1,265 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.enum_class import EnumClass + globals()['EnumClass'] = EnumClass + + +class AdditionalPropertiesWithArrayOfEnums(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return ([EnumClass],) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesWithArrayOfEnums - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesWithArrayOfEnums - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/address.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/address.py new file mode 100644 index 0000000000..6ab1456724 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/address.py @@ -0,0 +1,259 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Address(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (int,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Address - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Address - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/animal.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/animal.py new file mode 100644 index 0000000000..b93180ea05 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/animal.py @@ -0,0 +1,292 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.cat import Cat + from petstore_api.model.dog import Dog + globals()['Cat'] = Cat + globals()['Dog'] = Dog + + +class Animal(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'class_name': (str,), # noqa: E501 + 'color': (str,), # noqa: E501 + 'tail': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'Cat': Cat, + 'Dog': Dog, + } + if not val: + return None + return {'class_name': val} + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'color': 'color', # noqa: E501 + 'tail': 'tail', # noqa: E501 + } + + read_only_vars = { + 'tail', # noqa: E501 + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Animal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, class_name, *args, **kwargs): # noqa: E501 + """Animal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/animal_farm.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/animal_farm.py new file mode 100644 index 0000000000..89062cff69 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/animal_farm.py @@ -0,0 +1,291 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.animal import Animal + globals()['Animal'] = Animal + + +class AnimalFarm(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'value': ([Animal],), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """AnimalFarm - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([Animal]): # noqa: E501 + + Keyword Args: + value ([Animal]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """AnimalFarm - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([Animal]): # noqa: E501 + + Keyword Args: + value ([Animal]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/api_response.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/api_response.py new file mode 100644 index 0000000000..5e21cdaf59 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/api_response.py @@ -0,0 +1,271 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class ApiResponse(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'code': (int,), # noqa: E501 + 'type': (str,), # noqa: E501 + 'message': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'code': 'code', # noqa: E501 + 'type': 'type', # noqa: E501 + 'message': 'message', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ApiResponse - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + code (int): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ApiResponse - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + code (int): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/apple.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/apple.py new file mode 100644 index 0000000000..9909e1994a --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/apple.py @@ -0,0 +1,284 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Apple(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + ('cultivar',): { + 'regex': { + 'pattern': r'^[a-zA-Z\s]*$', # noqa: E501 + }, + }, + ('origin',): { + 'regex': { + 'pattern': r'^[A-Z\s]*$', # noqa: E501 + 'flags': (re.IGNORECASE) + }, + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = True + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'cultivar': (str,), # noqa: E501 + 'origin': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'cultivar': 'cultivar', # noqa: E501 + 'origin': 'origin', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, cultivar, *args, **kwargs): # noqa: E501 + """Apple - a model defined in OpenAPI + + Args: + cultivar (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.cultivar = cultivar + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, cultivar, *args, **kwargs): # noqa: E501 + """Apple - a model defined in OpenAPI + + Args: + cultivar (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.cultivar = cultivar + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/apple_req.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/apple_req.py new file mode 100644 index 0000000000..ce9ae6721e --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/apple_req.py @@ -0,0 +1,267 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class AppleReq(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'cultivar': (str,), # noqa: E501 + 'mealy': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'cultivar': 'cultivar', # noqa: E501 + 'mealy': 'mealy', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, cultivar, *args, **kwargs): # noqa: E501 + """AppleReq - a model defined in OpenAPI + + Args: + cultivar (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + mealy (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.cultivar = cultivar + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, cultivar, *args, **kwargs): # noqa: E501 + """AppleReq - a model defined in OpenAPI + + Args: + cultivar (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + mealy (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.cultivar = cultivar + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_of_array_of_number_only.py new file mode 100644 index 0000000000..41e90e2ae9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_of_array_of_number_only.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class ArrayOfArrayOfNumberOnly(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'array_array_number': ([[float]],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'array_array_number': 'ArrayArrayNumber', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_array_number ([[float]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_array_number ([[float]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_of_enums.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_of_enums.py new file mode 100644 index 0000000000..8ca15fd6c8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_of_enums.py @@ -0,0 +1,291 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.string_enum import StringEnum + globals()['StringEnum'] = StringEnum + + +class ArrayOfEnums(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'value': ([StringEnum],), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """ArrayOfEnums - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([StringEnum]): # noqa: E501 + + Keyword Args: + value ([StringEnum]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """ArrayOfEnums - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([StringEnum]): # noqa: E501 + + Keyword Args: + value ([StringEnum]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_of_number_only.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_of_number_only.py new file mode 100644 index 0000000000..068dc80b1a --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_of_number_only.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class ArrayOfNumberOnly(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'array_number': ([float],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'array_number': 'ArrayNumber', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_number ([float]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_number ([float]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_test.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_test.py new file mode 100644 index 0000000000..119a5ad1fd --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/array_test.py @@ -0,0 +1,277 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.read_only_first import ReadOnlyFirst + globals()['ReadOnlyFirst'] = ReadOnlyFirst + + +class ArrayTest(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'array_of_string': ([str],), # noqa: E501 + 'array_array_of_integer': ([[int]],), # noqa: E501 + 'array_array_of_model': ([[ReadOnlyFirst]],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'array_of_string': 'array_of_string', # noqa: E501 + 'array_array_of_integer': 'array_array_of_integer', # noqa: E501 + 'array_array_of_model': 'array_array_of_model', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_of_string ([str]): [optional] # noqa: E501 + array_array_of_integer ([[int]]): [optional] # noqa: E501 + array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ArrayTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_of_string ([str]): [optional] # noqa: E501 + array_array_of_integer ([[int]]): [optional] # noqa: E501 + array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/banana.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/banana.py new file mode 100644 index 0000000000..f6f6792990 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/banana.py @@ -0,0 +1,269 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Banana(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'length_cm': (float,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'length_cm': 'lengthCm', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, length_cm, *args, **kwargs): # noqa: E501 + """Banana - a model defined in OpenAPI + + Args: + length_cm (float): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.length_cm = length_cm + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, length_cm, *args, **kwargs): # noqa: E501 + """Banana - a model defined in OpenAPI + + Args: + length_cm (float): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.length_cm = length_cm + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/banana_req.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/banana_req.py new file mode 100644 index 0000000000..1e6d97d134 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/banana_req.py @@ -0,0 +1,267 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class BananaReq(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'length_cm': (float,), # noqa: E501 + 'sweet': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'length_cm': 'lengthCm', # noqa: E501 + 'sweet': 'sweet', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, length_cm, *args, **kwargs): # noqa: E501 + """BananaReq - a model defined in OpenAPI + + Args: + length_cm (float): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + sweet (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.length_cm = length_cm + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, length_cm, *args, **kwargs): # noqa: E501 + """BananaReq - a model defined in OpenAPI + + Args: + length_cm (float): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + sweet (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.length_cm = length_cm + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/basque_pig.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/basque_pig.py new file mode 100644 index 0000000000..456066d2ce --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/basque_pig.py @@ -0,0 +1,269 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class BasquePig(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'class_name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'class_name': 'className', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """BasquePig - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, class_name, *args, **kwargs): # noqa: E501 + """BasquePig - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/boolean_enum.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/boolean_enum.py new file mode 100644 index 0000000000..e4002fb8f6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/boolean_enum.py @@ -0,0 +1,281 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class BooleanEnum(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + 'TRUE': True, + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (bool,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """BooleanEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (bool): if omitted defaults to True, must be one of [True, ] # noqa: E501 + + Keyword Args: + value (bool): if omitted defaults to True, must be one of [True, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = True + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """BooleanEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (bool): if omitted defaults to True, must be one of [True, ] # noqa: E501 + + Keyword Args: + value (bool): if omitted defaults to True, must be one of [True, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = True + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/capitalization.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/capitalization.py new file mode 100644 index 0000000000..d57e30d2c8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/capitalization.py @@ -0,0 +1,283 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Capitalization(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'small_camel': (str,), # noqa: E501 + 'capital_camel': (str,), # noqa: E501 + 'small_snake': (str,), # noqa: E501 + 'capital_snake': (str,), # noqa: E501 + 'sca_eth_flow_points': (str,), # noqa: E501 + 'att_name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'small_camel': 'smallCamel', # noqa: E501 + 'capital_camel': 'CapitalCamel', # noqa: E501 + 'small_snake': 'small_Snake', # noqa: E501 + 'capital_snake': 'Capital_Snake', # noqa: E501 + 'sca_eth_flow_points': 'SCA_ETH_Flow_Points', # noqa: E501 + 'att_name': 'ATT_NAME', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Capitalization - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + small_camel (str): [optional] # noqa: E501 + capital_camel (str): [optional] # noqa: E501 + small_snake (str): [optional] # noqa: E501 + capital_snake (str): [optional] # noqa: E501 + sca_eth_flow_points (str): [optional] # noqa: E501 + att_name (str): Name of the pet . [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Capitalization - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + small_camel (str): [optional] # noqa: E501 + capital_camel (str): [optional] # noqa: E501 + small_snake (str): [optional] # noqa: E501 + capital_snake (str): [optional] # noqa: E501 + sca_eth_flow_points (str): [optional] # noqa: E501 + att_name (str): Name of the pet . [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/cat.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/cat.py new file mode 100644 index 0000000000..04a16c4911 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/cat.py @@ -0,0 +1,338 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.animal import Animal + from petstore_api.model.cat_all_of import CatAllOf + globals()['Animal'] = Animal + globals()['CatAllOf'] = CatAllOf + + +class Cat(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'class_name': (str,), # noqa: E501 + 'declawed': (bool,), # noqa: E501 + 'color': (str,), # noqa: E501 + 'tail': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + val = { + } + if not val: + return None + return {'class_name': val} + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'declawed': 'declawed', # noqa: E501 + 'color': 'color', # noqa: E501 + 'tail': 'tail', # noqa: E501 + } + + read_only_vars = { + 'tail', # noqa: E501 + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Cat - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Cat - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + Animal, + CatAllOf, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/cat_all_of.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/cat_all_of.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/category.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/category.py new file mode 100644 index 0000000000..21fb7bd65b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/category.py @@ -0,0 +1,275 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Category(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + 'id': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'id': 'id', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Category - a model defined in OpenAPI + + Args: + + Keyword Args: + name (str): defaults to "default-name" # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + """ + + name = kwargs.get('name', "default-name") + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Category - a model defined in OpenAPI + + Args: + + Keyword Args: + name (str): defaults to "default-name" # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + """ + + name = kwargs.get('name', "default-name") + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/child_cat.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/child_cat.py new file mode 100644 index 0000000000..6d971fd192 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/child_cat.py @@ -0,0 +1,329 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.child_cat_all_of import ChildCatAllOf + from petstore_api.model.parent_pet import ParentPet + globals()['ChildCatAllOf'] = ChildCatAllOf + globals()['ParentPet'] = ParentPet + + +class ChildCat(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pet_type': (str,), # noqa: E501 + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + val = { + } + if not val: + return None + return {'pet_type': val} + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCat - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ChildCat - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ChildCatAllOf, + ParentPet, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/child_cat_all_of.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/child_cat_all_of.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/class_model.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/class_model.py new file mode 100644 index 0000000000..cbbd0ff1e8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/class_model.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class ClassModel(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + '_class': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + '_class': '_class', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ClassModel - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ClassModel - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/client.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/client.py new file mode 100644 index 0000000000..82c5a6ed6b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/client.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Client(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'client': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'client': 'client', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Client - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + client (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Client - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + client (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/complex_quadrilateral.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/complex_quadrilateral.py new file mode 100644 index 0000000000..3ad5b7a718 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/complex_quadrilateral.py @@ -0,0 +1,326 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.quadrilateral_interface import QuadrilateralInterface + from petstore_api.model.shape_interface import ShapeInterface + globals()['QuadrilateralInterface'] = QuadrilateralInterface + globals()['ShapeInterface'] = ShapeInterface + + +class ComplexQuadrilateral(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'shape_type': (str,), # noqa: E501 + 'quadrilateral_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'shape_type': 'shapeType', # noqa: E501 + 'quadrilateral_type': 'quadrilateralType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ComplexQuadrilateral - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ComplexQuadrilateral - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + QuadrilateralInterface, + ShapeInterface, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/composed_one_of_number_with_validations.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/composed_one_of_number_with_validations.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/composed_schema_with_props_and_no_add_props.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/composed_schema_with_props_and_no_add_props.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/danish_pig.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/danish_pig.py new file mode 100644 index 0000000000..3a37b35393 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/danish_pig.py @@ -0,0 +1,269 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class DanishPig(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'class_name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'class_name': 'className', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """DanishPig - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, class_name, *args, **kwargs): # noqa: E501 + """DanishPig - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/dog.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/dog.py new file mode 100644 index 0000000000..f5b4d580f0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/dog.py @@ -0,0 +1,344 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.animal import Animal + from petstore_api.model.dog_all_of import DogAllOf + from petstore_api.model.legs import Legs + globals()['Animal'] = Animal + globals()['DogAllOf'] = DogAllOf + globals()['Legs'] = Legs + + +class Dog(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'class_name': (str,), # noqa: E501 + 'breed': (str,), # noqa: E501 + 'legs': (Legs,), # noqa: E501 + 'color': (str,), # noqa: E501 + 'tail': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + val = { + } + if not val: + return None + return {'class_name': val} + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'breed': 'breed', # noqa: E501 + 'legs': 'legs', # noqa: E501 + 'color': 'color', # noqa: E501 + 'tail': 'tail', # noqa: E501 + } + + read_only_vars = { + 'tail', # noqa: E501 + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Dog - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + legs (Legs): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Dog - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + legs (Legs): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + Animal, + DogAllOf, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/dog_all_of.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/dog_all_of.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/drawing.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/drawing.py new file mode 100644 index 0000000000..c08b8d2a0b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/drawing.py @@ -0,0 +1,287 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.fruit import Fruit + from petstore_api.model.nullable_shape import NullableShape + from petstore_api.model.shape import Shape + from petstore_api.model.shape_or_null import ShapeOrNull + globals()['Fruit'] = Fruit + globals()['NullableShape'] = NullableShape + globals()['Shape'] = Shape + globals()['ShapeOrNull'] = ShapeOrNull + + +class Drawing(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (Fruit,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'main_shape': (Shape,), # noqa: E501 + 'shape_or_null': (ShapeOrNull,), # noqa: E501 + 'nullable_shape': (NullableShape,), # noqa: E501 + 'shapes': ([Shape],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'main_shape': 'mainShape', # noqa: E501 + 'shape_or_null': 'shapeOrNull', # noqa: E501 + 'nullable_shape': 'nullableShape', # noqa: E501 + 'shapes': 'shapes', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Drawing - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + main_shape (Shape): [optional] # noqa: E501 + shape_or_null (ShapeOrNull): [optional] # noqa: E501 + nullable_shape (NullableShape): [optional] # noqa: E501 + shapes ([Shape]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Drawing - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + main_shape (Shape): [optional] # noqa: E501 + shape_or_null (ShapeOrNull): [optional] # noqa: E501 + nullable_shape (NullableShape): [optional] # noqa: E501 + shapes ([Shape]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/egress_threshold_options.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/egress_threshold_options.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/egress_threshold_options.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/egress_threshold_options.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/enum_arrays.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/enum_arrays.py new file mode 100644 index 0000000000..65b981ab7b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/enum_arrays.py @@ -0,0 +1,275 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class EnumArrays(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('just_symbol',): { + '>=': ">=", + '$': "$", + }, + ('array_enum',): { + 'FISH': "fish", + 'CRAB': "crab", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'just_symbol': (str,), # noqa: E501 + 'array_enum': ([str],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'just_symbol': 'just_symbol', # noqa: E501 + 'array_enum': 'array_enum', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EnumArrays - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_symbol (str): [optional] # noqa: E501 + array_enum ([str]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """EnumArrays - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_symbol (str): [optional] # noqa: E501 + array_enum ([str]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/enum_class.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/enum_class.py new file mode 100644 index 0000000000..bf9b682bd0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/enum_class.py @@ -0,0 +1,283 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class EnumClass(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + '_ABC': "_abc", + '-EFG': "-efg", + '(XYZ)': "(xyz)", + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """EnumClass - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "-efg" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """EnumClass - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "-efg" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/enum_test.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/enum_test.py new file mode 100644 index 0000000000..dd47ea4f74 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/enum_test.py @@ -0,0 +1,356 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.array_of_enums import ArrayOfEnums + from petstore_api.model.boolean_enum import BooleanEnum + from petstore_api.model.integer_enum import IntegerEnum + from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue + from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue + from petstore_api.model.string_enum import StringEnum + from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue + globals()['ArrayOfEnums'] = ArrayOfEnums + globals()['BooleanEnum'] = BooleanEnum + globals()['IntegerEnum'] = IntegerEnum + globals()['IntegerEnumOneValue'] = IntegerEnumOneValue + globals()['IntegerEnumWithDefaultValue'] = IntegerEnumWithDefaultValue + globals()['StringEnum'] = StringEnum + globals()['StringEnumWithDefaultValue'] = StringEnumWithDefaultValue + + +class EnumTest(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('enum_string_required',): { + 'UPPER': "UPPER", + 'LOWER': "lower", + 'EMPTY': "", + }, + ('enum_string',): { + 'UPPER': "UPPER", + 'LOWER': "lower", + 'EMPTY': "", + }, + ('enum_integer',): { + '1': 1, + '-1': -1, + }, + ('enum_number',): { + '1.1': 1.1, + '-1.2': -1.2, + }, + ('enum_bool',): { + 'FALSE': False, + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'enum_string_required': (str,), # noqa: E501 + 'enum_string': (str,), # noqa: E501 + 'enum_integer': (int,), # noqa: E501 + 'enum_number': (float,), # noqa: E501 + 'enum_bool': (bool,), # noqa: E501 + 'bool_enum': (BooleanEnum,), # noqa: E501 + 'string_enum': (StringEnum,), # noqa: E501 + 'integer_enum': (IntegerEnum,), # noqa: E501 + 'string_enum_with_default_value': (StringEnumWithDefaultValue,), # noqa: E501 + 'integer_enum_with_default_value': (IntegerEnumWithDefaultValue,), # noqa: E501 + 'integer_enum_one_value': (IntegerEnumOneValue,), # noqa: E501 + 'inline_array_of_str_enum': ([StringEnum],), # noqa: E501 + 'array_of_str_enum': (ArrayOfEnums,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'enum_string_required': 'enum_string_required', # noqa: E501 + 'enum_string': 'enum_string', # noqa: E501 + 'enum_integer': 'enum_integer', # noqa: E501 + 'enum_number': 'enum_number', # noqa: E501 + 'enum_bool': 'enum_bool', # noqa: E501 + 'bool_enum': 'boolEnum', # noqa: E501 + 'string_enum': 'stringEnum', # noqa: E501 + 'integer_enum': 'IntegerEnum', # noqa: E501 + 'string_enum_with_default_value': 'StringEnumWithDefaultValue', # noqa: E501 + 'integer_enum_with_default_value': 'IntegerEnumWithDefaultValue', # noqa: E501 + 'integer_enum_one_value': 'IntegerEnumOneValue', # noqa: E501 + 'inline_array_of_str_enum': 'InlineArrayOfStrEnum', # noqa: E501 + 'array_of_str_enum': 'ArrayOfStrEnum', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, enum_string_required, *args, **kwargs): # noqa: E501 + """EnumTest - a model defined in OpenAPI + + Args: + enum_string_required (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enum_string (str): [optional] # noqa: E501 + enum_integer (int): [optional] # noqa: E501 + enum_number (float): [optional] # noqa: E501 + enum_bool (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + bool_enum (BooleanEnum): [optional] # noqa: E501 + string_enum (StringEnum): [optional] # noqa: E501 + integer_enum (IntegerEnum): [optional] # noqa: E501 + string_enum_with_default_value (StringEnumWithDefaultValue): [optional] # noqa: E501 + integer_enum_with_default_value (IntegerEnumWithDefaultValue): [optional] # noqa: E501 + integer_enum_one_value (IntegerEnumOneValue): [optional] # noqa: E501 + inline_array_of_str_enum ([StringEnum]): [optional] # noqa: E501 + array_of_str_enum (ArrayOfEnums): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.enum_string_required = enum_string_required + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, enum_string_required, *args, **kwargs): # noqa: E501 + """EnumTest - a model defined in OpenAPI + + Args: + enum_string_required (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enum_string (str): [optional] # noqa: E501 + enum_integer (int): [optional] # noqa: E501 + enum_number (float): [optional] # noqa: E501 + enum_bool (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + bool_enum (BooleanEnum): [optional] # noqa: E501 + string_enum (StringEnum): [optional] # noqa: E501 + integer_enum (IntegerEnum): [optional] # noqa: E501 + string_enum_with_default_value (StringEnumWithDefaultValue): [optional] # noqa: E501 + integer_enum_with_default_value (IntegerEnumWithDefaultValue): [optional] # noqa: E501 + integer_enum_one_value (IntegerEnumOneValue): [optional] # noqa: E501 + inline_array_of_str_enum ([StringEnum]): [optional] # noqa: E501 + array_of_str_enum (ArrayOfEnums): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.enum_string_required = enum_string_required + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/equilateral_triangle.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/equilateral_triangle.py new file mode 100644 index 0000000000..47e8e9a64f --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/equilateral_triangle.py @@ -0,0 +1,326 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.shape_interface import ShapeInterface + from petstore_api.model.triangle_interface import TriangleInterface + globals()['ShapeInterface'] = ShapeInterface + globals()['TriangleInterface'] = TriangleInterface + + +class EquilateralTriangle(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'shape_type': (str,), # noqa: E501 + 'triangle_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'shape_type': 'shapeType', # noqa: E501 + 'triangle_type': 'triangleType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EquilateralTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """EquilateralTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ShapeInterface, + TriangleInterface, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/file.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/file.py new file mode 100644 index 0000000000..6d8d65f457 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/file.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class File(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'source_uri': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'source_uri': 'sourceURI', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """File - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + source_uri (str): Test capitalization. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """File - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + source_uri (str): Test capitalization. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/file_schema_test_class.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/file_schema_test_class.py new file mode 100644 index 0000000000..d8db617ffa --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/file_schema_test_class.py @@ -0,0 +1,273 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.file import File + globals()['File'] = File + + +class FileSchemaTestClass(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'file': (File,), # noqa: E501 + 'files': ([File],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'file': 'file', # noqa: E501 + 'files': 'files', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FileSchemaTestClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + file (File): [optional] # noqa: E501 + files ([File]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """FileSchemaTestClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + file (File): [optional] # noqa: E501 + files ([File]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/foo.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/foo.py new file mode 100644 index 0000000000..fd07a6d8ad --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/foo.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Foo(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'bar': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'bar': 'bar', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Foo - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] if omitted the server will use the default value of "bar" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Foo - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] if omitted the server will use the default value of "bar" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/foo_get_default_response.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/foo_get_default_response.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/foo_get_default_response.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/foo_get_default_response.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/foo_object.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/foo_object.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/foo_object.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/foo_object.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/format_test.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/format_test.py new file mode 100644 index 0000000000..5b425f4233 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/format_test.py @@ -0,0 +1,378 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class FormatTest(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + ('number',): { + 'inclusive_maximum': 543.2, + 'inclusive_minimum': 32.1, + 'multiple_of': 32.5, + }, + ('password',): { + 'max_length': 64, + 'min_length': 10, + }, + ('integer',): { + 'inclusive_maximum': 100, + 'inclusive_minimum': 10, + 'multiple_of': 2, + }, + ('int32',): { + 'inclusive_maximum': 200, + 'inclusive_minimum': 20, + }, + ('float',): { + 'inclusive_maximum': 987.6, + 'inclusive_minimum': 54.3, + }, + ('double',): { + 'inclusive_maximum': 123.4, + 'inclusive_minimum': 67.8, + }, + ('string',): { + 'regex': { + 'pattern': r'[a-z]', # noqa: E501 + 'flags': (re.IGNORECASE) + }, + }, + ('pattern_with_digits',): { + 'regex': { + 'pattern': r'^\d{10}$', # noqa: E501 + }, + }, + ('pattern_with_digits_and_delimiter',): { + 'regex': { + 'pattern': r'^image_\d{1,3}$', # noqa: E501 + 'flags': (re.IGNORECASE) + }, + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'number': (float,), # noqa: E501 + 'byte': (str,), # noqa: E501 + 'date': (date,), # noqa: E501 + 'password': (str,), # noqa: E501 + 'integer': (int,), # noqa: E501 + 'int32': (int,), # noqa: E501 + 'int64': (int,), # noqa: E501 + 'float': (float,), # noqa: E501 + 'double': (float,), # noqa: E501 + 'string': (str,), # noqa: E501 + 'binary': (file_type,), # noqa: E501 + 'date_time': (datetime,), # noqa: E501 + 'uuid': (str,), # noqa: E501 + 'uuid_no_example': (str,), # noqa: E501 + 'pattern_with_digits': (str,), # noqa: E501 + 'pattern_with_digits_and_delimiter': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'number': 'number', # noqa: E501 + 'byte': 'byte', # noqa: E501 + 'date': 'date', # noqa: E501 + 'password': 'password', # noqa: E501 + 'integer': 'integer', # noqa: E501 + 'int32': 'int32', # noqa: E501 + 'int64': 'int64', # noqa: E501 + 'float': 'float', # noqa: E501 + 'double': 'double', # noqa: E501 + 'string': 'string', # noqa: E501 + 'binary': 'binary', # noqa: E501 + 'date_time': 'dateTime', # noqa: E501 + 'uuid': 'uuid', # noqa: E501 + 'uuid_no_example': 'uuidNoExample', # noqa: E501 + 'pattern_with_digits': 'pattern_with_digits', # noqa: E501 + 'pattern_with_digits_and_delimiter': 'pattern_with_digits_and_delimiter', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, number, byte, date, password, *args, **kwargs): # noqa: E501 + """FormatTest - a model defined in OpenAPI + + Args: + number (float): + byte (str): + date (date): + password (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer (int): [optional] # noqa: E501 + int32 (int): [optional] # noqa: E501 + int64 (int): [optional] # noqa: E501 + float (float): [optional] # noqa: E501 + double (float): [optional] # noqa: E501 + string (str): [optional] # noqa: E501 + binary (file_type): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + uuid (str): [optional] # noqa: E501 + uuid_no_example (str): [optional] # noqa: E501 + pattern_with_digits (str): A string that is a 10 digit number. Can have leading zeros.. [optional] # noqa: E501 + pattern_with_digits_and_delimiter (str): A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.number = number + self.byte = byte + self.date = date + self.password = password + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, number, byte, date, password, *args, **kwargs): # noqa: E501 + """FormatTest - a model defined in OpenAPI + + Args: + number (float): + byte (str): + date (date): + password (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer (int): [optional] # noqa: E501 + int32 (int): [optional] # noqa: E501 + int64 (int): [optional] # noqa: E501 + float (float): [optional] # noqa: E501 + double (float): [optional] # noqa: E501 + string (str): [optional] # noqa: E501 + binary (file_type): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + uuid (str): [optional] # noqa: E501 + uuid_no_example (str): [optional] # noqa: E501 + pattern_with_digits (str): A string that is a 10 digit number. Can have leading zeros.. [optional] # noqa: E501 + pattern_with_digits_and_delimiter (str): A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.number = number + self.byte = byte + self.date = date + self.password = password + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/fruit.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/fruit.py new file mode 100644 index 0000000000..79952ac853 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/fruit.py @@ -0,0 +1,345 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.apple import Apple + from petstore_api.model.banana import Banana + globals()['Apple'] = Apple + globals()['Banana'] = Banana + + +class Fruit(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + ('cultivar',): { + 'regex': { + 'pattern': r'^[a-zA-Z\s]*$', # noqa: E501 + }, + }, + ('origin',): { + 'regex': { + 'pattern': r'^[A-Z\s]*$', # noqa: E501 + 'flags': (re.IGNORECASE) + }, + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'cultivar': (str,), # noqa: E501 + 'length_cm': (float,), # noqa: E501 + 'color': (str,), # noqa: E501 + 'origin': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'cultivar': 'cultivar', # noqa: E501 + 'length_cm': 'lengthCm', # noqa: E501 + 'color': 'color', # noqa: E501 + 'origin': 'origin', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Fruit - a model defined in OpenAPI + + Keyword Args: + cultivar (str): + length_cm (float): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Fruit - a model defined in OpenAPI + + Keyword Args: + cultivar (str): + length_cm (float): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + Apple, + Banana, + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/fruit_req.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/fruit_req.py new file mode 100644 index 0000000000..62fdc158f5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/fruit_req.py @@ -0,0 +1,335 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.apple_req import AppleReq + from petstore_api.model.banana_req import BananaReq + globals()['AppleReq'] = AppleReq + globals()['BananaReq'] = BananaReq + + +class FruitReq(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'mealy': (bool,), # noqa: E501 + 'sweet': (bool,), # noqa: E501 + 'cultivar': (str,), # noqa: E501 + 'length_cm': (float,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'mealy': 'mealy', # noqa: E501 + 'sweet': 'sweet', # noqa: E501 + 'cultivar': 'cultivar', # noqa: E501 + 'length_cm': 'lengthCm', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FruitReq - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + mealy (bool): [optional] # noqa: E501 + sweet (bool): [optional] # noqa: E501 + cultivar (str): [optional] # noqa: E501 + length_cm (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """FruitReq - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + mealy (bool): [optional] # noqa: E501 + sweet (bool): [optional] # noqa: E501 + cultivar (str): [optional] # noqa: E501 + length_cm (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + AppleReq, + BananaReq, + none_type, + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/gm_fruit.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/gm_fruit.py new file mode 100644 index 0000000000..93f102967f --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/gm_fruit.py @@ -0,0 +1,345 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.apple import Apple + from petstore_api.model.banana import Banana + globals()['Apple'] = Apple + globals()['Banana'] = Banana + + +class GmFruit(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + ('cultivar',): { + 'regex': { + 'pattern': r'^[a-zA-Z\s]*$', # noqa: E501 + }, + }, + ('origin',): { + 'regex': { + 'pattern': r'^[A-Z\s]*$', # noqa: E501 + 'flags': (re.IGNORECASE) + }, + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'cultivar': (str,), # noqa: E501 + 'length_cm': (float,), # noqa: E501 + 'color': (str,), # noqa: E501 + 'origin': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'cultivar': 'cultivar', # noqa: E501 + 'length_cm': 'lengthCm', # noqa: E501 + 'color': 'color', # noqa: E501 + 'origin': 'origin', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """GmFruit - a model defined in OpenAPI + + Keyword Args: + cultivar (str): + length_cm (float): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """GmFruit - a model defined in OpenAPI + + Keyword Args: + cultivar (str): + length_cm (float): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + Apple, + Banana, + ], + 'allOf': [ + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit_no_properties.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/gm_fruit_no_properties.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit_no_properties.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/gm_fruit_no_properties.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/grandparent_animal.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/grandparent_animal.py new file mode 100644 index 0000000000..f6d1b0bb20 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/grandparent_animal.py @@ -0,0 +1,283 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.child_cat import ChildCat + from petstore_api.model.parent_pet import ParentPet + globals()['ChildCat'] = ChildCat + globals()['ParentPet'] = ParentPet + + +class GrandparentAnimal(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pet_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'ChildCat': ChildCat, + 'ParentPet': ParentPet, + } + if not val: + return None + return {'pet_type': val} + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, pet_type, *args, **kwargs): # noqa: E501 + """GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.pet_type = pet_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, pet_type, *args, **kwargs): # noqa: E501 + """GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.pet_type = pet_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/has_only_read_only.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/has_only_read_only.py new file mode 100644 index 0000000000..1ccc67be07 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/has_only_read_only.py @@ -0,0 +1,269 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class HasOnlyReadOnly(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'bar': (str,), # noqa: E501 + 'foo': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'bar': 'bar', # noqa: E501 + 'foo': 'foo', # noqa: E501 + } + + read_only_vars = { + 'bar', # noqa: E501 + 'foo', # noqa: E501 + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HasOnlyReadOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + foo (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """HasOnlyReadOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + foo (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/health_check_result.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/health_check_result.py new file mode 100644 index 0000000000..e0f31297fe --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/health_check_result.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class HealthCheckResult(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'nullable_message': (str, none_type,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'nullable_message': 'NullableMessage', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HealthCheckResult - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + nullable_message (str, none_type): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """HealthCheckResult - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + nullable_message (str, none_type): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/inline_additional_properties_ref_payload.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/inline_additional_properties_ref_payload.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/inline_object6.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/inline_object6.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/inline_response_default.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/inline_response_default.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/integer_enum.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/integer_enum.py new file mode 100644 index 0000000000..de46d21f64 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/integer_enum.py @@ -0,0 +1,291 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class IntegerEnum(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + '0': 0, + '1': 1, + '2': 2, + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (int,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """IntegerEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int):, must be one of [0, 1, 2, ] # noqa: E501 + + Keyword Args: + value (int):, must be one of [0, 1, 2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IntegerEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int):, must be one of [0, 1, 2, ] # noqa: E501 + + Keyword Args: + value (int):, must be one of [0, 1, 2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/integer_enum_one_value.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/integer_enum_one_value.py new file mode 100644 index 0000000000..9091039a21 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/integer_enum_one_value.py @@ -0,0 +1,281 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class IntegerEnumOneValue(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + '0': 0, + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (int,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """IntegerEnumOneValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 + + Keyword Args: + value (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = 0 + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IntegerEnumOneValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 + + Keyword Args: + value (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = 0 + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/integer_enum_with_default_value.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/integer_enum_with_default_value.py new file mode 100644 index 0000000000..f3473cffa2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/integer_enum_with_default_value.py @@ -0,0 +1,283 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class IntegerEnumWithDefaultValue(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + '0': 0, + '1': 1, + '2': 2, + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (int,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """IntegerEnumWithDefaultValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 + + Keyword Args: + value (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = 0 + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IntegerEnumWithDefaultValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 + + Keyword Args: + value (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = 0 + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/isosceles_triangle.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/isosceles_triangle.py new file mode 100644 index 0000000000..162f8fedb5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/isosceles_triangle.py @@ -0,0 +1,326 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.shape_interface import ShapeInterface + from petstore_api.model.triangle_interface import TriangleInterface + globals()['ShapeInterface'] = ShapeInterface + globals()['TriangleInterface'] = TriangleInterface + + +class IsoscelesTriangle(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'shape_type': (str,), # noqa: E501 + 'triangle_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'shape_type': 'shapeType', # noqa: E501 + 'triangle_type': 'triangleType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """IsoscelesTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """IsoscelesTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ShapeInterface, + TriangleInterface, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/legs.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/legs.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/legs.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/legs.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/list.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/list.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/list.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/list.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/mammal.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/mammal.py new file mode 100644 index 0000000000..0a2d927ea7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/mammal.py @@ -0,0 +1,349 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.pig import Pig + from petstore_api.model.whale import Whale + from petstore_api.model.zebra import Zebra + globals()['Pig'] = Pig + globals()['Whale'] = Whale + globals()['Zebra'] = Zebra + + +class Mammal(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('type',): { + 'PLAINS': "plains", + 'MOUNTAIN': "mountain", + 'GREVYS': "grevys", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'class_name': (str,), # noqa: E501 + 'has_baleen': (bool,), # noqa: E501 + 'has_teeth': (bool,), # noqa: E501 + 'type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'Pig': Pig, + 'whale': Whale, + 'zebra': Zebra, + } + if not val: + return None + return {'class_name': val} + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'has_baleen': 'hasBaleen', # noqa: E501 + 'has_teeth': 'hasTeeth', # noqa: E501 + 'type': 'type', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Mammal - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Mammal - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + Pig, + Whale, + Zebra, + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/map_test.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/map_test.py new file mode 100644 index 0000000000..eccf9c9e61 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/map_test.py @@ -0,0 +1,285 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.string_boolean_map import StringBooleanMap + globals()['StringBooleanMap'] = StringBooleanMap + + +class MapTest(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('map_of_enum_string',): { + 'UPPER': "UPPER", + 'LOWER': "lower", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'map_map_of_string': ({str: ({str: (str,)},)},), # noqa: E501 + 'map_of_enum_string': ({str: (str,)},), # noqa: E501 + 'direct_map': ({str: (bool,)},), # noqa: E501 + 'indirect_map': (StringBooleanMap,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'map_map_of_string': 'map_map_of_string', # noqa: E501 + 'map_of_enum_string': 'map_of_enum_string', # noqa: E501 + 'direct_map': 'direct_map', # noqa: E501 + 'indirect_map': 'indirect_map', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MapTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 + direct_map ({str: (bool,)}): [optional] # noqa: E501 + indirect_map (StringBooleanMap): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """MapTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 + direct_map ({str: (bool,)}): [optional] # noqa: E501 + indirect_map (StringBooleanMap): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/mixed_properties_and_additional_properties_class.py new file mode 100644 index 0000000000..4d825b8dd4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -0,0 +1,277 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.animal import Animal + globals()['Animal'] = Animal + + +class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'uuid': (str,), # noqa: E501 + 'date_time': (datetime,), # noqa: E501 + 'map': ({str: (Animal,)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'uuid': 'uuid', # noqa: E501 + 'date_time': 'dateTime', # noqa: E501 + 'map': 'map', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + uuid (str): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + map ({str: (Animal,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + uuid (str): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + map ({str: (Animal,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/model200_response.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/model200_response.py new file mode 100644 index 0000000000..9bebea2423 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/model200_response.py @@ -0,0 +1,267 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Model200Response(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (int,), # noqa: E501 + '_class': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + '_class': 'class', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Model200Response - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (int): [optional] # noqa: E501 + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Model200Response - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (int): [optional] # noqa: E501 + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model_200_response.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/model_200_response.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/model_200_response.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/model_200_response.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/model_return.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/model_return.py new file mode 100644 index 0000000000..f3bd5123dd --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/model_return.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class ModelReturn(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + '_return': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + '_return': 'return', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ModelReturn - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _return (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ModelReturn - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _return (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mole.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/mole.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/mole.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/mole.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/name.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/name.py new file mode 100644 index 0000000000..aec8c8b900 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/name.py @@ -0,0 +1,283 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Name(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (int,), # noqa: E501 + 'snake_case': (int,), # noqa: E501 + '_property': (str,), # noqa: E501 + '_123_number': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'snake_case': 'snake_case', # noqa: E501 + '_property': 'property', # noqa: E501 + '_123_number': '123Number', # noqa: E501 + } + + read_only_vars = { + 'snake_case', # noqa: E501 + '_123_number', # noqa: E501 + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Name - a model defined in OpenAPI + + Args: + name (int): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + snake_case (int): [optional] # noqa: E501 + _property (str): [optional] # noqa: E501 + _123_number (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, name, *args, **kwargs): # noqa: E501 + """Name - a model defined in OpenAPI + + Args: + name (int): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + snake_case (int): [optional] # noqa: E501 + _property (str): [optional] # noqa: E501 + _123_number (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/nullable_class.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/nullable_class.py new file mode 100644 index 0000000000..0c6765a33c --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/nullable_class.py @@ -0,0 +1,311 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class NullableClass(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'integer_prop': (int, none_type,), # noqa: E501 + 'number_prop': (float, none_type,), # noqa: E501 + 'boolean_prop': (bool, none_type,), # noqa: E501 + 'string_prop': (str, none_type,), # noqa: E501 + 'date_prop': (date, none_type,), # noqa: E501 + 'datetime_prop': (datetime, none_type,), # noqa: E501 + 'array_nullable_prop': ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type,), # noqa: E501 + 'array_and_items_nullable_prop': ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type,), # noqa: E501 + 'array_items_nullable': ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type],), # noqa: E501 + 'object_nullable': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type,), # noqa: E501 + 'object_nullable_prop': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type,), # noqa: E501 + 'object_and_items_nullable_prop': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type,), # noqa: E501 + 'object_items_nullable': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'integer_prop': 'integer_prop', # noqa: E501 + 'number_prop': 'number_prop', # noqa: E501 + 'boolean_prop': 'boolean_prop', # noqa: E501 + 'string_prop': 'string_prop', # noqa: E501 + 'date_prop': 'date_prop', # noqa: E501 + 'datetime_prop': 'datetime_prop', # noqa: E501 + 'array_nullable_prop': 'array_nullable_prop', # noqa: E501 + 'array_and_items_nullable_prop': 'array_and_items_nullable_prop', # noqa: E501 + 'array_items_nullable': 'array_items_nullable', # noqa: E501 + 'object_nullable': 'object_nullable', # noqa: E501 + 'object_nullable_prop': 'object_nullable_prop', # noqa: E501 + 'object_and_items_nullable_prop': 'object_and_items_nullable_prop', # noqa: E501 + 'object_items_nullable': 'object_items_nullable', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NullableClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer_prop (int, none_type): [optional] # noqa: E501 + number_prop (float, none_type): [optional] # noqa: E501 + boolean_prop (bool, none_type): [optional] # noqa: E501 + string_prop (str, none_type): [optional] # noqa: E501 + date_prop (date, none_type): [optional] # noqa: E501 + datetime_prop (datetime, none_type): [optional] # noqa: E501 + array_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type): [optional] # noqa: E501 + array_and_items_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type): [optional] # noqa: E501 + array_items_nullable ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type]): [optional] # noqa: E501 + object_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501 + object_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type): [optional] # noqa: E501 + object_and_items_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type): [optional] # noqa: E501 + object_items_nullable ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """NullableClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer_prop (int, none_type): [optional] # noqa: E501 + number_prop (float, none_type): [optional] # noqa: E501 + boolean_prop (bool, none_type): [optional] # noqa: E501 + string_prop (str, none_type): [optional] # noqa: E501 + date_prop (date, none_type): [optional] # noqa: E501 + datetime_prop (datetime, none_type): [optional] # noqa: E501 + array_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type): [optional] # noqa: E501 + array_and_items_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type): [optional] # noqa: E501 + array_items_nullable ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type]): [optional] # noqa: E501 + object_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501 + object_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type): [optional] # noqa: E501 + object_and_items_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type): [optional] # noqa: E501 + object_items_nullable ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/nullable_shape.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/nullable_shape.py new file mode 100644 index 0000000000..75aad1b1b0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/nullable_shape.py @@ -0,0 +1,336 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.quadrilateral import Quadrilateral + from petstore_api.model.triangle import Triangle + globals()['Quadrilateral'] = Quadrilateral + globals()['Triangle'] = Triangle + + +class NullableShape(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = True + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'shape_type': (str,), # noqa: E501 + 'quadrilateral_type': (str,), # noqa: E501 + 'triangle_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + if not val: + return None + return {'shape_type': val} + + attribute_map = { + 'shape_type': 'shapeType', # noqa: E501 + 'quadrilateral_type': 'quadrilateralType', # noqa: E501 + 'triangle_type': 'triangleType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NullableShape - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """NullableShape - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + Quadrilateral, + Triangle, + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/number_only.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/number_only.py new file mode 100644 index 0000000000..7a586085d7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/number_only.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class NumberOnly(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'just_number': (float,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'just_number': 'JustNumber', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_number (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """NumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_number (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/number_with_validations.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/number_with_validations.py new file mode 100644 index 0000000000..67e019ad54 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/number_with_validations.py @@ -0,0 +1,290 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class NumberWithValidations(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + ('value',): { + 'inclusive_maximum': 20, + 'inclusive_minimum': 10, + }, + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (float,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """NumberWithValidations - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (float): # noqa: E501 + + Keyword Args: + value (float): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """NumberWithValidations - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (float): # noqa: E501 + + Keyword Args: + value (float): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/object_interface.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/object_interface.py new file mode 100644 index 0000000000..4f9e0edf98 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/object_interface.py @@ -0,0 +1,259 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class ObjectInterface(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectInterface - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ObjectInterface - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/object_model_with_ref_props.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/object_model_with_ref_props.py new file mode 100644 index 0000000000..085a1533c4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/object_model_with_ref_props.py @@ -0,0 +1,283 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.number_with_validations import NumberWithValidations + from petstore_api.model.readonly import Readonly + globals()['NumberWithValidations'] = NumberWithValidations + globals()['Readonly'] = Readonly + + +class ObjectModelWithRefProps(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'my_number': (NumberWithValidations,), # noqa: E501 + 'my_readonly': (Readonly,), # noqa: E501 + 'my_string': (str,), # noqa: E501 + 'my_boolean': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'my_number': 'my_number', # noqa: E501 + 'my_readonly': 'my_readonly', # noqa: E501 + 'my_string': 'my_string', # noqa: E501 + 'my_boolean': 'my_boolean', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectModelWithRefProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + my_number (NumberWithValidations): [optional] # noqa: E501 + my_readonly (Readonly): [optional] # noqa: E501 + my_string (str): [optional] # noqa: E501 + my_boolean (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ObjectModelWithRefProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + my_number (NumberWithValidations): [optional] # noqa: E501 + my_readonly (Readonly): [optional] # noqa: E501 + my_string (str): [optional] # noqa: E501 + my_boolean (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/object_with_validations.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/object_with_validations.py new file mode 100644 index 0000000000..16e0c1f1a2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/object_with_validations.py @@ -0,0 +1,262 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class ObjectWithValidations(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + ('value',): { + 'min_properties': 1, + }, + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectWithValidations - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ObjectWithValidations - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/order.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/order.py new file mode 100644 index 0000000000..98fe0b8697 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/order.py @@ -0,0 +1,288 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Order(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('status',): { + 'PLACED': "placed", + 'APPROVED': "approved", + 'DELIVERED': "delivered", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'id': (int,), # noqa: E501 + 'pet_id': (int,), # noqa: E501 + 'quantity': (int,), # noqa: E501 + 'ship_date': (datetime,), # noqa: E501 + 'status': (str,), # noqa: E501 + 'complete': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'id': 'id', # noqa: E501 + 'pet_id': 'petId', # noqa: E501 + 'quantity': 'quantity', # noqa: E501 + 'ship_date': 'shipDate', # noqa: E501 + 'status': 'status', # noqa: E501 + 'complete': 'complete', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Order - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + pet_id (int): [optional] # noqa: E501 + quantity (int): [optional] # noqa: E501 + ship_date (datetime): [optional] # noqa: E501 + status (str): Order Status. [optional] # noqa: E501 + complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Order - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + pet_id (int): [optional] # noqa: E501 + quantity (int): [optional] # noqa: E501 + ship_date (datetime): [optional] # noqa: E501 + status (str): Order Status. [optional] # noqa: E501 + complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/parent_pet.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/parent_pet.py new file mode 100644 index 0000000000..8d94006f15 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/parent_pet.py @@ -0,0 +1,326 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.child_cat import ChildCat + from petstore_api.model.grandparent_animal import GrandparentAnimal + globals()['ChildCat'] = ChildCat + globals()['GrandparentAnimal'] = GrandparentAnimal + + +class ParentPet(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pet_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'ChildCat': ChildCat, + } + if not val: + return None + return {'pet_type': val} + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentPet - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ParentPet - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + GrandparentAnimal, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/pet.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/pet.py new file mode 100644 index 0000000000..5eb4041e91 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/pet.py @@ -0,0 +1,304 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.category import Category + from petstore_api.model.tag import Tag + globals()['Category'] = Category + globals()['Tag'] = Tag + + +class Pet(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('status',): { + 'AVAILABLE': "available", + 'PENDING': "pending", + 'SOLD': "sold", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'name': (str,), # noqa: E501 + 'photo_urls': ([str],), # noqa: E501 + 'id': (int,), # noqa: E501 + 'category': (Category,), # noqa: E501 + 'tags': ([Tag],), # noqa: E501 + 'status': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'photo_urls': 'photoUrls', # noqa: E501 + 'id': 'id', # noqa: E501 + 'category': 'category', # noqa: E501 + 'tags': 'tags', # noqa: E501 + 'status': 'status', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, photo_urls, *args, **kwargs): # noqa: E501 + """Pet - a model defined in OpenAPI + + Args: + name (str): + photo_urls ([str]): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + category (Category): [optional] # noqa: E501 + tags ([Tag]): [optional] # noqa: E501 + status (str): pet status in the store. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + self.photo_urls = photo_urls + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, name, photo_urls, *args, **kwargs): # noqa: E501 + """Pet - a model defined in OpenAPI + + Args: + name (str): + photo_urls ([str]): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + category (Category): [optional] # noqa: E501 + tags ([Tag]): [optional] # noqa: E501 + status (str): pet status in the store. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + self.photo_urls = photo_urls + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/pig.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/pig.py new file mode 100644 index 0000000000..5c9bcc5bd0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/pig.py @@ -0,0 +1,328 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.basque_pig import BasquePig + from petstore_api.model.danish_pig import DanishPig + globals()['BasquePig'] = BasquePig + globals()['DanishPig'] = DanishPig + + +class Pig(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'class_name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'BasquePig': BasquePig, + 'DanishPig': DanishPig, + } + if not val: + return None + return {'class_name': val} + + attribute_map = { + 'class_name': 'className', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Pig - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Pig - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + BasquePig, + DanishPig, + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/post_inline_additional_properties_payload_request.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/post_inline_additional_properties_payload_request.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/post_inline_additional_properties_payload_request.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/post_inline_additional_properties_payload_request.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/post_inline_additional_properties_payload_request_array_data_inner.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/post_inline_additional_properties_payload_request_array_data_inner.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/post_inline_additional_properties_payload_request_array_data_inner.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/post_inline_additional_properties_payload_request_array_data_inner.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/publish_options.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/publish_options.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/publish_options.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/publish_options.py diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/publish_options_publish.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/publish_options_publish.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/publish_options_publish.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/publish_options_publish.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/quadrilateral.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/quadrilateral.py new file mode 100644 index 0000000000..ddb76e43e8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/quadrilateral.py @@ -0,0 +1,332 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral + from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral + globals()['ComplexQuadrilateral'] = ComplexQuadrilateral + globals()['SimpleQuadrilateral'] = SimpleQuadrilateral + + +class Quadrilateral(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'quadrilateral_type': (str,), # noqa: E501 + 'shape_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'ComplexQuadrilateral': ComplexQuadrilateral, + 'SimpleQuadrilateral': SimpleQuadrilateral, + } + if not val: + return None + return {'quadrilateral_type': val} + + attribute_map = { + 'quadrilateral_type': 'quadrilateralType', # noqa: E501 + 'shape_type': 'shapeType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Quadrilateral - a model defined in OpenAPI + + Keyword Args: + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + shape_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Quadrilateral - a model defined in OpenAPI + + Keyword Args: + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + shape_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + ComplexQuadrilateral, + SimpleQuadrilateral, + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/quadrilateral_interface.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/quadrilateral_interface.py new file mode 100644 index 0000000000..9f61569c9c --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/quadrilateral_interface.py @@ -0,0 +1,269 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class QuadrilateralInterface(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'quadrilateral_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'quadrilateral_type': 'quadrilateralType', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, quadrilateral_type, *args, **kwargs): # noqa: E501 + """QuadrilateralInterface - a model defined in OpenAPI + + Args: + quadrilateral_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.quadrilateral_type = quadrilateral_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, quadrilateral_type, *args, **kwargs): # noqa: E501 + """QuadrilateralInterface - a model defined in OpenAPI + + Args: + quadrilateral_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.quadrilateral_type = quadrilateral_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/read_only_first.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/read_only_first.py new file mode 100644 index 0000000000..965325c286 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/read_only_first.py @@ -0,0 +1,268 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class ReadOnlyFirst(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'bar': (str,), # noqa: E501 + 'baz': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'bar': 'bar', # noqa: E501 + 'baz': 'baz', # noqa: E501 + } + + read_only_vars = { + 'bar', # noqa: E501 + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ReadOnlyFirst - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + baz (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ReadOnlyFirst - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + baz (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/readonly.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/readonly.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/readonly.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/scalene_triangle.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/scalene_triangle.py new file mode 100644 index 0000000000..6a7bfe81bd --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/scalene_triangle.py @@ -0,0 +1,326 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.shape_interface import ShapeInterface + from petstore_api.model.triangle_interface import TriangleInterface + globals()['ShapeInterface'] = ShapeInterface + globals()['TriangleInterface'] = TriangleInterface + + +class ScaleneTriangle(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'shape_type': (str,), # noqa: E501 + 'triangle_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'shape_type': 'shapeType', # noqa: E501 + 'triangle_type': 'triangleType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ScaleneTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ScaleneTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ShapeInterface, + TriangleInterface, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/shape.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/shape.py new file mode 100644 index 0000000000..0256572402 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/shape.py @@ -0,0 +1,336 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.quadrilateral import Quadrilateral + from petstore_api.model.triangle import Triangle + globals()['Quadrilateral'] = Quadrilateral + globals()['Triangle'] = Triangle + + +class Shape(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'shape_type': (str,), # noqa: E501 + 'quadrilateral_type': (str,), # noqa: E501 + 'triangle_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + if not val: + return None + return {'shape_type': val} + + attribute_map = { + 'shape_type': 'shapeType', # noqa: E501 + 'quadrilateral_type': 'quadrilateralType', # noqa: E501 + 'triangle_type': 'triangleType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Shape - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Shape - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + Quadrilateral, + Triangle, + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/shape_interface.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/shape_interface.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/shape_or_null.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/shape_or_null.py new file mode 100644 index 0000000000..28bd8ecd4b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/shape_or_null.py @@ -0,0 +1,337 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.quadrilateral import Quadrilateral + from petstore_api.model.triangle import Triangle + globals()['Quadrilateral'] = Quadrilateral + globals()['Triangle'] = Triangle + + +class ShapeOrNull(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'shape_type': (str,), # noqa: E501 + 'quadrilateral_type': (str,), # noqa: E501 + 'triangle_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + if not val: + return None + return {'shape_type': val} + + attribute_map = { + 'shape_type': 'shapeType', # noqa: E501 + 'quadrilateral_type': 'quadrilateralType', # noqa: E501 + 'triangle_type': 'triangleType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ShapeOrNull - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ShapeOrNull - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + Quadrilateral, + Triangle, + none_type, + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/simple_quadrilateral.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/simple_quadrilateral.py new file mode 100644 index 0000000000..7c34285120 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/simple_quadrilateral.py @@ -0,0 +1,326 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.quadrilateral_interface import QuadrilateralInterface + from petstore_api.model.shape_interface import ShapeInterface + globals()['QuadrilateralInterface'] = QuadrilateralInterface + globals()['ShapeInterface'] = ShapeInterface + + +class SimpleQuadrilateral(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'shape_type': (str,), # noqa: E501 + 'quadrilateral_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'shape_type': 'shapeType', # noqa: E501 + 'quadrilateral_type': 'quadrilateralType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SimpleQuadrilateral - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """SimpleQuadrilateral - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + QuadrilateralInterface, + ShapeInterface, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/some_object.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/some_object.py new file mode 100644 index 0000000000..cee41c9aa7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/some_object.py @@ -0,0 +1,315 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.object_interface import ObjectInterface + globals()['ObjectInterface'] = ObjectInterface + + +class SomeObject(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SomeObject - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """SomeObject - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ObjectInterface, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/some_object_with_self_attr.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/some_object_with_self_attr.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/special_model_name.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/special_model_name.py new file mode 100644 index 0000000000..6044e5e100 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/special_model_name.py @@ -0,0 +1,263 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class SpecialModelName(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'special_property_name': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'special_property_name': '$special[property.name]', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SpecialModelName - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + special_property_name (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """SpecialModelName - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + special_property_name (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/stream_options.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/stream_options.py similarity index 100% rename from samples/openapi3/client/petstore/python/petstore_api/model/stream_options.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/model/stream_options.py diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/string_boolean_map.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/string_boolean_map.py new file mode 100644 index 0000000000..52b6f39964 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/string_boolean_map.py @@ -0,0 +1,259 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class StringBooleanMap(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """StringBooleanMap - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """StringBooleanMap - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/string_enum.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/string_enum.py new file mode 100644 index 0000000000..0fbdcdc6af --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/string_enum.py @@ -0,0 +1,305 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class StringEnum(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + 'None': None, + 'PLACED': "placed", + 'APPROVED': "approved", + 'DELIVERED': "delivered", + 'SINGLE_QUOTED': "single quoted", + 'MULTIPLE_LINES': '''multiple +lines''', + 'DOUBLE_QUOTE_WITH_NEWLINE': '''double quote + with newline''', + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = True + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """StringEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple +lines''', '''double quote + with newline''', ] # noqa: E501 + + Keyword Args: + value (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple +lines''', '''double quote + with newline''', ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple +lines''', '''double quote + with newline''', ] # noqa: E501 + + Keyword Args: + value (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple +lines''', '''double quote + with newline''', ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/string_enum_with_default_value.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/string_enum_with_default_value.py new file mode 100644 index 0000000000..37775c93ca --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/string_enum_with_default_value.py @@ -0,0 +1,283 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class StringEnumWithDefaultValue(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + 'PLACED': "placed", + 'APPROVED': "approved", + 'DELIVERED': "delivered", + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """StringEnumWithDefaultValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "placed" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnumWithDefaultValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "placed" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/tag.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/tag.py new file mode 100644 index 0000000000..b56728bb6b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/tag.py @@ -0,0 +1,267 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Tag(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'id': (int,), # noqa: E501 + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'id': 'id', # noqa: E501 + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Tag - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Tag - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/triangle.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/triangle.py new file mode 100644 index 0000000000..fd9103c96b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/triangle.py @@ -0,0 +1,336 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.equilateral_triangle import EquilateralTriangle + from petstore_api.model.isosceles_triangle import IsoscelesTriangle + from petstore_api.model.scalene_triangle import ScaleneTriangle + globals()['EquilateralTriangle'] = EquilateralTriangle + globals()['IsoscelesTriangle'] = IsoscelesTriangle + globals()['ScaleneTriangle'] = ScaleneTriangle + + +class Triangle(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'triangle_type': (str,), # noqa: E501 + 'shape_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'EquilateralTriangle': EquilateralTriangle, + 'IsoscelesTriangle': IsoscelesTriangle, + 'ScaleneTriangle': ScaleneTriangle, + } + if not val: + return None + return {'triangle_type': val} + + attribute_map = { + 'triangle_type': 'triangleType', # noqa: E501 + 'shape_type': 'shapeType', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Triangle - a model defined in OpenAPI + + Keyword Args: + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + shape_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Triangle - a model defined in OpenAPI + + Keyword Args: + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + shape_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + EquilateralTriangle, + IsoscelesTriangle, + ScaleneTriangle, + ], + } diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/triangle_interface.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/triangle_interface.py new file mode 100644 index 0000000000..3bb817d86b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/triangle_interface.py @@ -0,0 +1,269 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class TriangleInterface(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'triangle_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'triangle_type': 'triangleType', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, triangle_type, *args, **kwargs): # noqa: E501 + """TriangleInterface - a model defined in OpenAPI + + Args: + triangle_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.triangle_type = triangle_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, triangle_type, *args, **kwargs): # noqa: E501 + """TriangleInterface - a model defined in OpenAPI + + Args: + triangle_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.triangle_type = triangle_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/user.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/user.py new file mode 100644 index 0000000000..a8056b29a2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/user.py @@ -0,0 +1,307 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class User(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'id': (int,), # noqa: E501 + 'username': (str,), # noqa: E501 + 'first_name': (str,), # noqa: E501 + 'last_name': (str,), # noqa: E501 + 'email': (str,), # noqa: E501 + 'password': (str,), # noqa: E501 + 'phone': (str,), # noqa: E501 + 'user_status': (int,), # noqa: E501 + 'object_with_no_declared_props': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 + 'object_with_no_declared_props_nullable': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type,), # noqa: E501 + 'any_type_prop': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 + 'any_type_prop_nullable': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'id': 'id', # noqa: E501 + 'username': 'username', # noqa: E501 + 'first_name': 'firstName', # noqa: E501 + 'last_name': 'lastName', # noqa: E501 + 'email': 'email', # noqa: E501 + 'password': 'password', # noqa: E501 + 'phone': 'phone', # noqa: E501 + 'user_status': 'userStatus', # noqa: E501 + 'object_with_no_declared_props': 'objectWithNoDeclaredProps', # noqa: E501 + 'object_with_no_declared_props_nullable': 'objectWithNoDeclaredPropsNullable', # noqa: E501 + 'any_type_prop': 'anyTypeProp', # noqa: E501 + 'any_type_prop_nullable': 'anyTypePropNullable', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """User - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + username (str): [optional] # noqa: E501 + first_name (str): [optional] # noqa: E501 + last_name (str): [optional] # noqa: E501 + email (str): [optional] # noqa: E501 + password (str): [optional] # noqa: E501 + phone (str): [optional] # noqa: E501 + user_status (int): User Status. [optional] # noqa: E501 + object_with_no_declared_props ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value.. [optional] # noqa: E501 + object_with_no_declared_props_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): test code generation for nullable objects. Value must be a map of strings to values or the 'null' value.. [optional] # noqa: E501 + any_type_prop (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389. [optional] # noqa: E501 + any_type_prop_nullable (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """User - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + username (str): [optional] # noqa: E501 + first_name (str): [optional] # noqa: E501 + last_name (str): [optional] # noqa: E501 + email (str): [optional] # noqa: E501 + password (str): [optional] # noqa: E501 + phone (str): [optional] # noqa: E501 + user_status (int): User Status. [optional] # noqa: E501 + object_with_no_declared_props ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value.. [optional] # noqa: E501 + object_with_no_declared_props_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): test code generation for nullable objects. Value must be a map of strings to values or the 'null' value.. [optional] # noqa: E501 + any_type_prop (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389. [optional] # noqa: E501 + any_type_prop_nullable (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/whale.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/whale.py new file mode 100644 index 0000000000..7c1a842671 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/whale.py @@ -0,0 +1,277 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Whale(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'class_name': (str,), # noqa: E501 + 'has_baleen': (bool,), # noqa: E501 + 'has_teeth': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'has_baleen': 'hasBaleen', # noqa: E501 + 'has_teeth': 'hasTeeth', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Whale - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, class_name, *args, **kwargs): # noqa: E501 + """Whale - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/zebra.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/zebra.py new file mode 100644 index 0000000000..b6d2fe934d --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model/zebra.py @@ -0,0 +1,278 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, + OpenApiModel +) +from petstore_api.exceptions import ApiAttributeError + + + +class Zebra(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('type',): { + 'PLAINS': "plains", + 'MOUNTAIN': "mountain", + 'GREVYS': "grevys", + }, + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'class_name': (str,), # noqa: E501 + 'type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'type': 'type', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Zebra - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', True) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, class_name, *args, **kwargs): # noqa: E501 + """Zebra - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + for arg in args: + if isinstance(arg, dict): + kwargs.update(arg) + else: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model_utils.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model_utils.py new file mode 100644 index 0000000000..ab2d0087df --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/model_utils.py @@ -0,0 +1,2058 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from datetime import date, datetime # noqa: F401 +from copy import deepcopy +import inspect +import io +import os +import pprint +import re +import tempfile +import uuid + +from dateutil.parser import parse + +from petstore_api.exceptions import ( + ApiKeyError, + ApiAttributeError, + ApiTypeError, + ApiValueError, +) + +none_type = type(None) +file_type = io.IOBase + + +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python( + kwargs, _self if isinstance( + _self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + +class cached_property(object): + # this caches the result of the function call for fn with no inputs + # use this as a decorator on function methods that you want converted + # into cached properties + result_key = '_results' + + def __init__(self, fn): + self._fn = fn + + def __get__(self, instance, cls=None): + if self.result_key in vars(self): + return vars(self)[self.result_key] + else: + result = self._fn() + setattr(self, self.result_key, result) + return result + + +PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) + + +def allows_single_value_input(cls): + """ + This function returns True if the input composed schema model or any + descendant model allows a value only input + This is true for cases where oneOf contains items like: + oneOf: + - float + - NumberWithValidation + - StringEnum + - ArrayModel + - null + TODO: lru_cache this + """ + if ( + issubclass(cls, ModelSimple) or + cls in PRIMITIVE_TYPES + ): + return True + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return False + return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) + return False + + +def composed_model_input_classes(cls): + """ + This function returns a list of the possible models that can be accepted as + inputs. + TODO: lru_cache this + """ + if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: + return [cls] + elif issubclass(cls, ModelNormal): + if cls.discriminator is None: + return [cls] + else: + return get_discriminated_classes(cls) + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return [] + if cls.discriminator is None: + input_classes = [] + for c in cls._composed_schemas['oneOf']: + input_classes.extend(composed_model_input_classes(c)) + return input_classes + else: + return get_discriminated_classes(cls) + return [] + + +class OpenApiModel(object): + """The base class for all OpenAPIModels""" + + def set_attribute(self, name, value): + # this is only used to set properties on self + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + + if name in self.openapi_types: + required_types_mixed = self.openapi_types[name] + elif self.additional_properties_type is None: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + path_to_item + ) + elif self.additional_properties_type is not None: + required_types_mixed = self.additional_properties_type + + if get_simple_class(name) != str: + error_msg = type_error_message( + var_name=name, + var_value=name, + valid_classes=(str,), + key_type=True + ) + raise ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=(str,), + key_type=True + ) + + if self._check_type: + value = validate_and_convert_types( + value, required_types_mixed, path_to_item, self._spec_property_naming, + self._check_type, configuration=self._configuration) + if (name,) in self.allowed_values: + check_allowed_values( + self.allowed_values, + (name,), + value + ) + if (name,) in self.validations: + check_validations( + self.validations, + (name,), + value, + self._configuration + ) + self.__dict__['_data_store'][name] = value + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other + + def __setattr__(self, attr, value): + """set the value of an attribute using dot notation: `instance.attr = val`""" + self[attr] = value + + def __getattr__(self, attr): + """get the value of an attribute using dot notation: `instance.attr`""" + return self.__getitem__(attr) + + def __copy__(self): + cls = self.__class__ + if self.get("_spec_property_naming", False): + return cls._new_from_openapi_data(**self.__dict__) + else: + return cls.__new__(cls, **self.__dict__) + + def __deepcopy__(self, memo): + cls = self.__class__ + + if self.get("_spec_property_naming", False): + new_inst = cls._new_from_openapi_data() + else: + new_inst = cls.__new__(cls, **self.__dict__) + + for k, v in self.__dict__.items(): + setattr(new_inst, k, deepcopy(v, memo)) + return new_inst + + + def __new__(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return super(OpenApiModel, cls).__new__(cls) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return super(OpenApiModel, cls).__new__(cls) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = super(OpenApiModel, cls).__new__(cls) + self_inst.__init__(*args, **kwargs) + + if kwargs.get("_spec_property_naming", False): + # when true, implies new is from deserialization + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + else: + new_inst = new_cls.__new__(new_cls, *args, **kwargs) + new_inst.__init__(*args, **kwargs) + + return new_inst + + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + +class ModelSimple(OpenApiModel): + """the parent class of models whose type != object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_str(self): + """Returns the string representation of the model""" + return str(self.value) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + this_val = self._data_store['value'] + that_val = other._data_store['value'] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + return vals_equal + + +class ModelNormal(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +class ModelComposed(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi and have oneOf/allOf/anyOf + + When one sets a property we use var_name_to_model_instances to store the value in + the correct class instances + run any type checking + validation code. + When one gets a property we use var_name_to_model_instances to get the value + from the correct class instances. + This allows multiple composed schemas to contain the same property with additive + constraints on the value. + + _composed_schemas (dict) stores the anyOf/allOf/oneOf classes + key (str): allOf/oneOf/anyOf + value (list): the classes in the XOf definition. + Note: none_type can be included when the openapi document version >= 3.1.0 + _composed_instances (list): stores a list of instances of the composed schemas + defined in _composed_schemas. When properties are accessed in the self instance, + they are returned from the self._data_store or the data stores in the instances + in self._composed_schemas + _var_name_to_model_instances (dict): maps between a variable name on self and + the composed instances (self included) which contain that data + key (str): property name + value (list): list of class instances, self or instances in _composed_instances + which contain the value that the key is referring to. + """ + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None + + __unset_attribute_value__ = object() + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + # get the attribute from the correct instance + model_instances = self._var_name_to_model_instances.get(name) + values = [] + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + v = model_instance._data_store[name] + if v not in values: + values.append(v) + len_values = len(values) + if len_values == 0: + return default + elif len_values == 1: + return values[0] + elif len_values > 1: + raise ApiValueError( + "Values stored for property {0} in {1} differ when looking " + "at self and self's composed instances. All values must be " + "the same".format(name, type(self).__name__), + [e for e in [self._path_to_item, name] if e] + ) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + value = self.get(name, self.__unset_attribute_value__) + if value is self.__unset_attribute_value__: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + return value + + def __contains__(self, name): + """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" + + if name in self.required_properties: + return name in self.__dict__ + + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + return True + + return False + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +COERCION_INDEX_BY_TYPE = { + ModelComposed: 0, + ModelNormal: 1, + ModelSimple: 2, + none_type: 3, # The type of 'None'. + list: 4, + dict: 5, + float: 6, + int: 7, + bool: 8, + datetime: 9, + date: 10, + str: 11, + file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. +} + +# these are used to limit what type conversions we try to do +# when we have a valid type already and we want to try converting +# to another type +UPCONVERSION_TYPE_PAIRS = ( + (str, datetime), + (str, date), + # A float may be serialized as an integer, e.g. '3' is a valid serialized float. + (int, float), + (list, ModelComposed), + (dict, ModelComposed), + (str, ModelComposed), + (int, ModelComposed), + (float, ModelComposed), + (list, ModelComposed), + (list, ModelNormal), + (dict, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), +) + +COERCIBLE_TYPE_PAIRS = { + False: ( # client instantiation of a model with client data + # (dict, ModelComposed), + # (list, ModelComposed), + # (dict, ModelNormal), + # (list, ModelNormal), + # (str, ModelSimple), + # (int, ModelSimple), + # (float, ModelSimple), + # (list, ModelSimple), + # (str, int), + # (str, float), + # (str, datetime), + # (str, date), + # (int, str), + # (float, str), + ), + True: ( # server -> client data + (dict, ModelComposed), + (list, ModelComposed), + (dict, ModelNormal), + (list, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), + # (str, int), + # (str, float), + (str, datetime), + (str, date), + # (int, str), + # (float, str), + (str, file_type) + ), +} + + +def get_simple_class(input_value): + """Returns an input_value's simple class that we will use for type checking + Python2: + float and int will return int, where int is the python3 int backport + str and unicode will return str, where str is the python3 str backport + Note: float and int ARE both instances of int backport + Note: str_py2 and unicode_py2 are NOT both instances of str backport + + Args: + input_value (class/class_instance): the item for which we will return + the simple class + """ + if isinstance(input_value, type): + # input_value is a class + return input_value + elif isinstance(input_value, tuple): + return tuple + elif isinstance(input_value, list): + return list + elif isinstance(input_value, dict): + return dict + elif isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, file_type): + return file_type + elif isinstance(input_value, bool): + # this must be higher than the int check because + # isinstance(True, int) == True + return bool + elif isinstance(input_value, int): + return int + elif isinstance(input_value, datetime): + # this must be higher than the date check because + # isinstance(datetime_instance, date) == True + return datetime + elif isinstance(input_value, date): + return date + elif isinstance(input_value, str): + return str + return type(input_value) + + +def check_allowed_values(allowed_values, input_variable_path, input_values): + """Raises an exception if the input_values are not allowed + + Args: + allowed_values (dict): the allowed_values dict + input_variable_path (tuple): the path to the input variable + input_values (list/str/int/float/date/datetime): the values that we + are checking to see if they are in allowed_values + """ + these_allowed_values = list(allowed_values[input_variable_path].values()) + if (isinstance(input_values, list) + and not set(input_values).issubset( + set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values) - set(these_allowed_values))), + raise ApiValueError( + "Invalid values for `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (isinstance(input_values, dict) + and not set( + input_values.keys()).issubset(set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values.keys()) - set(these_allowed_values))) + raise ApiValueError( + "Invalid keys in `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (not isinstance(input_values, (list, dict)) + and input_values not in these_allowed_values): + raise ApiValueError( + "Invalid value for `%s` (%s), must be one of %s" % + ( + input_variable_path[0], + input_values, + these_allowed_values + ) + ) + + +def is_json_validation_enabled(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + +def check_validations( + validations, input_variable_path, input_values, + configuration=None): + """Raises an exception if the input_values are invalid + + Args: + validations (dict): the validation dictionary. + input_variable_path (tuple): the path to the input variable. + input_values (list/str/int/float/date/datetime): the values that we + are checking. + configuration (Configuration): the configuration class. + """ + + if input_values is None: + return + + current_validations = validations[input_variable_path] + if (is_json_validation_enabled('multipleOf', configuration) and + 'multiple_of' in current_validations and + isinstance(input_values, (int, float)) and + not (float(input_values) / current_validations['multiple_of']).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + raise ApiValueError( + "Invalid value for `%s`, value must be a multiple of " + "`%s`" % ( + input_variable_path[0], + current_validations['multiple_of'] + ) + ) + + if (is_json_validation_enabled('maxLength', configuration) and + 'max_length' in current_validations and + len(input_values) > current_validations['max_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['max_length'] + ) + ) + + if (is_json_validation_enabled('minLength', configuration) and + 'min_length' in current_validations and + len(input_values) < current_validations['min_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be greater than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['min_length'] + ) + ) + + if (is_json_validation_enabled('maxItems', configuration) and + 'max_items' in current_validations and + len(input_values) > current_validations['max_items']): + raise ApiValueError( + "Invalid value for `%s`, number of items must be less than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['max_items'] + ) + ) + + if (is_json_validation_enabled('minItems', configuration) and + 'min_items' in current_validations and + len(input_values) < current_validations['min_items']): + raise ValueError( + "Invalid value for `%s`, number of items must be greater than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['min_items'] + ) + ) + + items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', + 'inclusive_minimum') + if (any(item in current_validations for item in items)): + if isinstance(input_values, list): + max_val = max(input_values) + min_val = min(input_values) + elif isinstance(input_values, dict): + max_val = max(input_values.values()) + min_val = min(input_values.values()) + else: + max_val = input_values + min_val = input_values + + if (is_json_validation_enabled('exclusiveMaximum', configuration) and + 'exclusive_maximum' in current_validations and + max_val >= current_validations['exclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than `%s`" % ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('maximum', configuration) and + 'inclusive_maximum' in current_validations and + max_val > current_validations['inclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['inclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('exclusiveMinimum', configuration) and + 'exclusive_minimum' in current_validations and + min_val <= current_validations['exclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than `%s`" % + ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('minimum', configuration) and + 'inclusive_minimum' in current_validations and + min_val < current_validations['inclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than or equal " + "to `%s`" % ( + input_variable_path[0], + current_validations['inclusive_minimum'] + ) + ) + flags = current_validations.get('regex', {}).get('flags', 0) + if (is_json_validation_enabled('pattern', configuration) and + 'regex' in current_validations and + not re.search(current_validations['regex']['pattern'], + input_values, flags=flags)): + err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( + input_variable_path[0], + current_validations['regex']['pattern'] + ) + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + err_msg = r"%s with flags=`%s`" % (err_msg, flags) + raise ApiValueError(err_msg) + + +def order_response_types(required_types): + """Returns the required types sorted in coercion order + + Args: + required_types (list/tuple): collection of classes or instance of + list or dict with class information inside it. + + Returns: + (list): coercion order sorted collection of classes or instance + of list or dict with class information inside it. + """ + + def index_getter(class_or_instance): + if isinstance(class_or_instance, list): + return COERCION_INDEX_BY_TYPE[list] + elif isinstance(class_or_instance, dict): + return COERCION_INDEX_BY_TYPE[dict] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelComposed)): + return COERCION_INDEX_BY_TYPE[ModelComposed] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelNormal)): + return COERCION_INDEX_BY_TYPE[ModelNormal] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelSimple)): + return COERCION_INDEX_BY_TYPE[ModelSimple] + elif class_or_instance in COERCION_INDEX_BY_TYPE: + return COERCION_INDEX_BY_TYPE[class_or_instance] + raise ApiValueError("Unsupported type: %s" % class_or_instance) + + sorted_types = sorted( + required_types, + key=lambda class_or_instance: index_getter(class_or_instance) + ) + return sorted_types + + +def remove_uncoercible(required_types_classes, current_item, spec_property_naming, + must_convert=True): + """Only keeps the type conversions that are possible + + Args: + required_types_classes (tuple): tuple of classes that are required + these should be ordered by COERCION_INDEX_BY_TYPE + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + current_item (any): the current item (input data) to be converted + + Keyword Args: + must_convert (bool): if True the item to convert is of the wrong + type and we want a big list of coercibles + if False, we want a limited list of coercibles + + Returns: + (list): the remaining coercible required types, classes only + """ + current_type_simple = get_simple_class(current_item) + + results_classes = [] + for required_type_class in required_types_classes: + # convert our models to OpenApiModel + required_type_class_simplified = required_type_class + if isinstance(required_type_class_simplified, type): + if issubclass(required_type_class_simplified, ModelComposed): + required_type_class_simplified = ModelComposed + elif issubclass(required_type_class_simplified, ModelNormal): + required_type_class_simplified = ModelNormal + elif issubclass(required_type_class_simplified, ModelSimple): + required_type_class_simplified = ModelSimple + + if required_type_class_simplified == current_type_simple: + # don't consider converting to one's own class + continue + + class_pair = (current_type_simple, required_type_class_simplified) + if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: + results_classes.append(required_type_class) + elif class_pair in UPCONVERSION_TYPE_PAIRS: + results_classes.append(required_type_class) + return results_classes + + +def get_discriminated_classes(cls): + """ + Returns all the classes that a discriminator converts to + TODO: lru_cache this + """ + possible_classes = [] + key = list(cls.discriminator.keys())[0] + if is_type_nullable(cls): + possible_classes.append(cls) + for discr_cls in cls.discriminator[key].values(): + if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: + possible_classes.extend(get_discriminated_classes(discr_cls)) + else: + possible_classes.append(discr_cls) + return possible_classes + + +def get_possible_classes(cls, from_server_context): + # TODO: lru_cache this + possible_classes = [cls] + if from_server_context: + return possible_classes + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + possible_classes = [] + possible_classes.extend(get_discriminated_classes(cls)) + elif issubclass(cls, ModelComposed): + possible_classes.extend(composed_model_input_classes(cls)) + return possible_classes + + +def get_required_type_classes(required_types_mixed, spec_property_naming): + """Converts the tuple required_types into a tuple and a dict described + below + + Args: + required_types_mixed (tuple/list): will contain either classes or + instance of list or dict + spec_property_naming (bool): if True these values came from the + server, and we use the data types in our endpoints. + If False, we are client side and we need to include + oneOf and discriminator classes inside the data types in our endpoints + + Returns: + (valid_classes, dict_valid_class_to_child_types_mixed): + valid_classes (tuple): the valid classes that the current item + should be + dict_valid_class_to_child_types_mixed (dict): + valid_class (class): this is the key + child_types_mixed (list/dict/tuple): describes the valid child + types + """ + valid_classes = [] + child_req_types_by_current_type = {} + for required_type in required_types_mixed: + if isinstance(required_type, list): + valid_classes.append(list) + child_req_types_by_current_type[list] = required_type + elif isinstance(required_type, tuple): + valid_classes.append(tuple) + child_req_types_by_current_type[tuple] = required_type + elif isinstance(required_type, dict): + valid_classes.append(dict) + child_req_types_by_current_type[dict] = required_type[str] + else: + valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) + return tuple(valid_classes), child_req_types_by_current_type + + +def change_keys_js_to_python(input_dict, model_class): + """ + Converts from javascript_key keys in the input_dict to python_keys in + the output dict using the mapping in model_class. + If the input_dict contains a key which does not declared in the model_class, + the key is added to the output dict as is. The assumption is the model_class + may have undeclared properties (additionalProperties attribute in the OAS + document). + """ + + if getattr(model_class, 'attribute_map', None) is None: + return input_dict + output_dict = {} + reversed_attr_map = {value: key for key, value in + model_class.attribute_map.items()} + for javascript_key, value in input_dict.items(): + python_key = reversed_attr_map.get(javascript_key) + if python_key is None: + # if the key is unknown, it is in error or it is an + # additionalProperties variable + python_key = javascript_key + output_dict[python_key] = value + return output_dict + + +def get_type_error(var_value, path_to_item, valid_classes, key_type=False): + error_msg = type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type + ) + + +def deserialize_primitive(data, klass, path_to_item): + """Deserializes string to primitive type. + + :param data: str/int/float + :param klass: str/class the class to convert to + + :return: int, float, str, bool, date, datetime + """ + additional_message = "" + try: + if klass in {datetime, date}: + additional_message = ( + "If you need your parameter to have a fallback " + "string value, please set its type as `type: {}` in your " + "spec. That allows the value to be any type. " + ) + if klass == datetime: + if len(data) < 8: + raise ValueError("This is not a datetime") + # The string should be in iso8601 datetime format. + parsed_datetime = parse(data) + date_only = ( + parsed_datetime.hour == 0 and + parsed_datetime.minute == 0 and + parsed_datetime.second == 0 and + parsed_datetime.tzinfo is None and + 8 <= len(data) <= 10 + ) + if date_only: + raise ValueError("This is a date, not a datetime") + return parsed_datetime + elif klass == date: + if len(data) < 8: + raise ValueError("This is not a date") + return parse(data).date() + else: + converted_value = klass(data) + if isinstance(data, str) and klass == float: + if str(converted_value) != data: + # '7' -> 7.0 -> '7.0' != '7' + raise ValueError('This is not a float') + return converted_value + except (OverflowError, ValueError) as ex: + # parse can raise OverflowError + raise ApiValueError( + "{0}Failed to parse {1} as {2}".format( + additional_message, repr(data), klass.__name__ + ), + path_to_item=path_to_item + ) from ex + + +def get_discriminator_class(model_class, + discr_name, + discr_value, cls_visited): + """Returns the child class specified by the discriminator. + + Args: + model_class (OpenApiModel): the model class. + discr_name (string): the name of the discriminator property. + discr_value (any): the discriminator value. + cls_visited (list): list of model classes that have been visited. + Used to determine the discriminator class without + visiting circular references indefinitely. + + Returns: + used_model_class (class/None): the chosen child class that will be used + to deserialize the data, for example dog.Dog. + If a class is not found, None is returned. + """ + + if model_class in cls_visited: + # The class has already been visited and no suitable class was found. + return None + cls_visited.append(model_class) + used_model_class = None + if discr_name in model_class.discriminator: + class_name_to_discr_class = model_class.discriminator[discr_name] + used_model_class = class_name_to_discr_class.get(discr_value) + if used_model_class is None: + # We didn't find a discriminated class in class_name_to_discr_class. + # So look in the ancestor or descendant discriminators + # The discriminator mapping may exist in a descendant (anyOf, oneOf) + # or ancestor (allOf). + # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat + # hierarchy, the discriminator mappings may be defined at any level + # in the hierarchy. + # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig + # if we try to make BasquePig from mammal, we need to travel through + # the oneOf descendant discriminators to find BasquePig + descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ + model_class._composed_schemas.get('anyOf', ()) + ancestor_classes = model_class._composed_schemas.get('allOf', ()) + possible_classes = descendant_classes + ancestor_classes + for cls in possible_classes: + # Check if the schema has inherited discriminators. + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + used_model_class = get_discriminator_class( + cls, discr_name, discr_value, cls_visited) + if used_model_class is not None: + return used_model_class + return used_model_class + + +def deserialize_model(model_data, model_class, path_to_item, check_type, + configuration, spec_property_naming): + """Deserializes model_data to model instance. + + Args: + model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model + model_class (OpenApiModel): the model class + path_to_item (list): path to the model in the received data + check_type (bool): whether to check the data tupe for the values in + the model + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + + Returns: + model instance + + Raise: + ApiTypeError + ApiValueError + ApiKeyError + """ + + kw_args = dict(_check_type=check_type, + _path_to_item=path_to_item, + _configuration=configuration, + _spec_property_naming=spec_property_naming) + + if issubclass(model_class, ModelSimple): + return model_class._new_from_openapi_data(model_data, **kw_args) + elif isinstance(model_data, list): + return model_class._new_from_openapi_data(*model_data, **kw_args) + if isinstance(model_data, dict): + kw_args.update(model_data) + return model_class._new_from_openapi_data(**kw_args) + elif isinstance(model_data, PRIMITIVE_TYPES): + return model_class._new_from_openapi_data(model_data, **kw_args) + + +def deserialize_file(response_data, configuration, content_disposition=None): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + Args: + param response_data (str): the file data to write + configuration (Configuration): the instance to use to convert files + + Keyword Args: + content_disposition (str): the value of the Content-Disposition + header + + Returns: + (file_type): the deserialized file which is open + The user is responsible for closing and reading the file + """ + fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition, + flags=re.I) + if filename is not None: + filename = filename.group(1) + else: + filename = "default_" + str(uuid.uuid4()) + + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + if isinstance(response_data, str): + # change str to bytes so we can write it + response_data = response_data.encode('utf-8') + f.write(response_data) + + f = open(path, "rb") + return f + + +def attempt_convert_item(input_value, valid_classes, path_to_item, + configuration, spec_property_naming, key_type=False, + must_convert=False, check_type=True): + """ + Args: + input_value (any): the data to convert + valid_classes (any): the classes that are valid + path_to_item (list): the path to the item to convert + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + key_type (bool): if True we need to convert a key type (not supported) + must_convert (bool): if True we must convert + check_type (bool): if True we check the type or the returned data in + ModelComposed/ModelNormal/ModelSimple instances + + Returns: + instance (any) the fixed item + + Raises: + ApiTypeError + ApiValueError + ApiKeyError + """ + valid_classes_ordered = order_response_types(valid_classes) + valid_classes_coercible = remove_uncoercible( + valid_classes_ordered, input_value, spec_property_naming) + if not valid_classes_coercible or key_type: + # we do not handle keytype errors, json will take care + # of this for us + if configuration is None or not configuration.discard_unknown_keys: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=key_type) + for valid_class in valid_classes_coercible: + try: + if issubclass(valid_class, OpenApiModel): + return deserialize_model(input_value, valid_class, + path_to_item, check_type, + configuration, spec_property_naming) + elif valid_class == file_type: + return deserialize_file(input_value, configuration) + return deserialize_primitive(input_value, valid_class, + path_to_item) + except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: + if must_convert: + raise conversion_exc + # if we have conversion errors when must_convert == False + # we ignore the exception and move on to the next class + continue + # we were unable to convert, must_convert == False + return input_value + + +def is_type_nullable(input_type): + """ + Returns true if None is an allowed value for the specified input_type. + + A type is nullable if at least one of the following conditions is true: + 1. The OAS 'nullable' attribute has been specified, + 1. The type is the 'null' type, + 1. The type is a anyOf/oneOf composed schema, and a child schema is + the 'null' type. + Args: + input_type (type): the class of the input_value that we are + checking + Returns: + bool + """ + if input_type is none_type: + return True + if issubclass(input_type, OpenApiModel) and input_type._nullable: + return True + if issubclass(input_type, ModelComposed): + # If oneOf/anyOf, check if the 'null' type is one of the allowed types. + for t in input_type._composed_schemas.get('oneOf', ()): + if is_type_nullable(t): + return True + for t in input_type._composed_schemas.get('anyOf', ()): + if is_type_nullable(t): + return True + return False + + +def is_valid_type(input_class_simple, valid_classes): + """ + Args: + input_class_simple (class): the class of the input_value that we are + checking + valid_classes (tuple): the valid classes that the current item + should be + Returns: + bool + """ + if issubclass(input_class_simple, OpenApiModel) and \ + valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,): + return True + valid_type = input_class_simple in valid_classes + if not valid_type and ( + issubclass(input_class_simple, OpenApiModel) or + input_class_simple is none_type): + for valid_class in valid_classes: + if input_class_simple is none_type and is_type_nullable(valid_class): + # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. + return True + if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): + continue + discr_propertyname_py = list(valid_class.discriminator.keys())[0] + discriminator_classes = ( + valid_class.discriminator[discr_propertyname_py].values() + ) + valid_type = is_valid_type(input_class_simple, discriminator_classes) + if valid_type: + return True + return valid_type + + +def validate_and_convert_types(input_value, required_types_mixed, path_to_item, + spec_property_naming, _check_type, configuration=None): + """Raises a TypeError is there is a problem, otherwise returns value + + Args: + input_value (any): the data to validate/convert + required_types_mixed (list/dict/tuple): A list of + valid classes, or a list tuples of valid classes, or a dict where + the value is a tuple of value classes + path_to_item: (list) the path to the data being validated + this stores a list of keys or indices to get to the data being + validated + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + _check_type: (boolean) if true, type will be checked and conversion + will be attempted. + configuration: (Configuration): the configuration class to use + when converting file_type items. + If passed, conversion will be attempted when possible + If not passed, no conversions will be attempted and + exceptions will be raised + + Returns: + the correctly typed value + + Raises: + ApiTypeError + """ + results = get_required_type_classes(required_types_mixed, spec_property_naming) + valid_classes, child_req_types_by_current_type = results + + input_class_simple = get_simple_class(input_value) + valid_type = is_valid_type(input_class_simple, valid_classes) + if not valid_type: + if (configuration + or (input_class_simple == dict + and dict not in valid_classes)): + # if input_value is not valid_type try to convert it + converted_instance = attempt_convert_item( + input_value, + valid_classes, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=True, + check_type=_check_type + ) + return converted_instance + else: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=False) + + # input_value's type is in valid_classes + if len(valid_classes) > 1 and configuration: + # there are valid classes which are not the current class + valid_classes_coercible = remove_uncoercible( + valid_classes, input_value, spec_property_naming, must_convert=False) + if valid_classes_coercible: + converted_instance = attempt_convert_item( + input_value, + valid_classes_coercible, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=False, + check_type=_check_type + ) + return converted_instance + + if child_req_types_by_current_type == {}: + # all types are of the required types and there are no more inner + # variables left to look at + return input_value + inner_required_types = child_req_types_by_current_type.get( + type(input_value) + ) + if inner_required_types is None: + # for this type, there are not more inner variables left to look at + return input_value + if isinstance(input_value, list): + if input_value == []: + # allow an empty list + return input_value + for index, inner_value in enumerate(input_value): + inner_path = list(path_to_item) + inner_path.append(index) + input_value[index] = validate_and_convert_types( + inner_value, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + elif isinstance(input_value, dict): + if input_value == {}: + # allow an empty dict + return input_value + for inner_key, inner_val in input_value.items(): + inner_path = list(path_to_item) + inner_path.append(inner_key) + if get_simple_class(inner_key) != str: + raise get_type_error(inner_key, inner_path, valid_classes, + key_type=True) + input_value[inner_key] = validate_and_convert_types( + inner_val, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + return input_value + + +def model_to_dict(model_instance, serialize=True): + """Returns the model properties as a dict + + Args: + model_instance (one of your model instances): the model instance that + will be converted to a dict. + + Keyword Args: + serialize (bool): if True, the keys in the dict will be values from + attribute_map + """ + result = {} + + def extract_item(item): return ( + item[0], model_to_dict( + item[1], serialize=serialize)) if hasattr( + item[1], '_data_store') else item + + model_instances = [model_instance] + if model_instance._composed_schemas: + model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} + for model_instance in model_instances: + for attr, value in model_instance._data_store.items(): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) + if isinstance(value, list): + if not value: + # empty list or None + result[attr] = value + else: + res = [] + for v in value: + if isinstance(v, PRIMITIVE_TYPES) or v is None: + res.append(v) + elif isinstance(v, ModelSimple): + res.append(v.value) + elif isinstance(v, dict): + res.append(dict(map( + extract_item, + v.items() + ))) + else: + res.append(model_to_dict(v, serialize=serialize)) + result[attr] = res + elif isinstance(value, dict): + result[attr] = dict(map( + extract_item, + value.items() + )) + elif isinstance(value, ModelSimple): + result[attr] = value.value + elif hasattr(value, '_data_store'): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] + + return result + + +def type_error_message(var_value=None, var_name=None, valid_classes=None, + key_type=None): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + """ + key_or_value = 'value' + if key_type: + key_or_value = 'key' + valid_classes_phrase = get_valid_classes_phrase(valid_classes) + msg = ( + "Invalid type for variable '{0}'. Required {1} type {2} and " + "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + ) + return msg + + +def get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed + """ + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return 'is {0}'.format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas['allOf']: + + try: + if constant_args.get('_spec_property_naming'): + allof_instance = allof_class._from_openapi_data(**model_args, **constant_args) + else: + allof_instance = allof_class(**model_args, **constant_args) + composed_instances.append(allof_instance) + except Exception as ex: + raise ApiValueError( + "Invalid inputs given to generate an instance of '%s'. The " + "input data was invalid for the allOf schema '%s' in the composed " + "schema '%s'. Error=%s" % ( + allof_class.__name__, + allof_class.__name__, + self.__class__.__name__, + str(ex) + ) + ) from ex + return composed_instances + + +def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): + """ + Find the oneOf schema that matches the input data (e.g. payload). + If exactly one schema matches the input data, an instance of that schema + is returned. + If zero or more than one schema match the input data, an exception is raised. + In OAS 3.x, the payload MUST, by validation, match exactly one of the + schemas described by oneOf. + + Args: + cls: the class we are handling + model_kwargs (dict): var_name to var_value + The input data, e.g. the payload that must match a oneOf schema + in the OpenAPI document. + constant_kwargs (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Kwargs: + model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): + the value to assign to a primitive class or ModelSimple class + Notes: + - this is only passed in when oneOf includes types which are not object + - None is used to suppress handling of model_arg, nullable models are handled in __new__ + + Returns + oneof_instance (instance) + """ + if len(cls._composed_schemas['oneOf']) == 0: + return None + + oneof_instances = [] + # Iterate over each oneOf schema and determine if the input data + # matches the oneOf schemas. + for oneof_class in cls._composed_schemas['oneOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if oneof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + single_value_input = allows_single_value_input(oneof_class) + + try: + if not single_value_input: + if constant_kwargs.get('_spec_property_naming'): + oneof_instance = oneof_class._from_openapi_data( + **model_kwargs, **constant_kwargs) + else: + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) + else: + if issubclass(oneof_class, ModelSimple): + if constant_kwargs.get('_spec_property_naming'): + oneof_instance = oneof_class._from_openapi_data( + model_arg, **constant_kwargs) + else: + oneof_instance = oneof_class(model_arg, **constant_kwargs) + elif oneof_class in PRIMITIVE_TYPES: + oneof_instance = validate_and_convert_types( + model_arg, + (oneof_class,), + constant_kwargs['_path_to_item'], + constant_kwargs['_spec_property_naming'], + constant_kwargs['_check_type'], + configuration=constant_kwargs['_configuration'] + ) + oneof_instances.append(oneof_instance) + except Exception: + pass + if len(oneof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None " + "of the oneOf schemas matched the input data." % + cls.__name__ + ) + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf schemas matched the inputs, but a max of one is allowed." % + cls.__name__ + ) + return oneof_instances[0] + + +def get_anyof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + The input data, e.g. the payload that must match at least one + anyOf child schema in the OpenAPI document. + constant_args (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Returns + anyof_instances (list) + """ + anyof_instances = [] + if len(self._composed_schemas['anyOf']) == 0: + return anyof_instances + + for anyof_class in self._composed_schemas['anyOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if anyof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + try: + if constant_args.get('_spec_property_naming'): + anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args) + else: + anyof_instance = anyof_class(**model_args, **constant_args) + anyof_instances.append(anyof_instance) + except Exception: + pass + if len(anyof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None of the " + "anyOf schemas matched the inputs." % + self.__class__.__name__ + ) + return anyof_instances + + +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names + # before __init__ was called + for instance in composed_instances: + if instance.__class__ in self._composed_schemas['allOf']: + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + else: + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args + + +def validate_get_composed_info(constant_args, model_args, self): + """ + For composed schemas, generate schema instances for + all schemas in the oneOf/anyOf/allOf definition. If additional + properties are allowed, also assign those properties on + all matched schemas that contain additionalProperties. + Openapi schemas are python classes. + + Exceptions are raised if: + - 0 or > 1 oneOf schema matches the model_args input data + - no anyOf schema matches the model_args input data + - any of the allOf schemas do not match the model_args input data + + Args: + constant_args (dict): these are the args that every model requires + model_args (dict): these are the required and optional spec args that + were passed in to make this model + self (class): the class that we are instantiating + This class contains self._composed_schemas + + Returns: + composed_info (list): length three + composed_instances (list): the composed instances which are not + self + var_name_to_model_instances (dict): a dict going from var_name + to the model_instance which holds that var_name + the model_instance may be self or an instance of one of the + classes in self.composed_instances() + additional_properties_model_instances (list): a list of the + model instances which have the property + additional_properties_type. This list can include self + """ + # create composed_instances + composed_instances = [] + allof_instances = get_allof_instances(self, model_args, constant_args) + composed_instances.extend(allof_instances) + oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) + if oneof_instance is not None: + composed_instances.append(oneof_instance) + anyof_instances = get_anyof_instances(self, model_args, constant_args) + composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] + + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) + + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + list( + filter( + lambda x: prop_name in x.openapi_types, composed_instances)) + + return [ + composed_instances, + var_name_to_model_instances, + additional_properties_model_instances, + discarded_args + ] diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-prior/petstore_api/models/__init__.py new file mode 100644 index 0000000000..dd8afc1d8b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/models/__init__.py @@ -0,0 +1,111 @@ +# flake8: noqa + +# import all models into this package +# if you have many models here with many references from one model to another this may +# raise a RecursionError +# to avoid this, import only the models that you directly need like: +# from from petstore_api.model.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) + +from petstore_api.model.additional_properties_class import AdditionalPropertiesClass +from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums +from petstore_api.model.address import Address +from petstore_api.model.animal import Animal +from petstore_api.model.animal_farm import AnimalFarm +from petstore_api.model.api_response import ApiResponse +from petstore_api.model.apple import Apple +from petstore_api.model.apple_req import AppleReq +from petstore_api.model.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly +from petstore_api.model.array_of_enums import ArrayOfEnums +from petstore_api.model.array_of_number_only import ArrayOfNumberOnly +from petstore_api.model.array_test import ArrayTest +from petstore_api.model.banana import Banana +from petstore_api.model.banana_req import BananaReq +from petstore_api.model.basque_pig import BasquePig +from petstore_api.model.boolean_enum import BooleanEnum +from petstore_api.model.capitalization import Capitalization +from petstore_api.model.cat import Cat +from petstore_api.model.cat_all_of import CatAllOf +from petstore_api.model.category import Category +from petstore_api.model.child_cat import ChildCat +from petstore_api.model.child_cat_all_of import ChildCatAllOf +from petstore_api.model.class_model import ClassModel +from petstore_api.model.client import Client +from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral +from petstore_api.model.composed_one_of_number_with_validations import ComposedOneOfNumberWithValidations +from petstore_api.model.composed_schema_with_props_and_no_add_props import ComposedSchemaWithPropsAndNoAddProps +from petstore_api.model.danish_pig import DanishPig +from petstore_api.model.dog import Dog +from petstore_api.model.dog_all_of import DogAllOf +from petstore_api.model.drawing import Drawing +from petstore_api.model.egress_threshold_options import EgressThresholdOptions +from petstore_api.model.enum_arrays import EnumArrays +from petstore_api.model.enum_class import EnumClass +from petstore_api.model.enum_test import EnumTest +from petstore_api.model.equilateral_triangle import EquilateralTriangle +from petstore_api.model.file import File +from petstore_api.model.file_schema_test_class import FileSchemaTestClass +from petstore_api.model.foo import Foo +from petstore_api.model.foo_get_default_response import FooGetDefaultResponse +from petstore_api.model.foo_object import FooObject +from petstore_api.model.format_test import FormatTest +from petstore_api.model.fruit import Fruit +from petstore_api.model.fruit_req import FruitReq +from petstore_api.model.gm_fruit import GmFruit +from petstore_api.model.gm_fruit_no_properties import GmFruitNoProperties +from petstore_api.model.grandparent_animal import GrandparentAnimal +from petstore_api.model.has_only_read_only import HasOnlyReadOnly +from petstore_api.model.health_check_result import HealthCheckResult +from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload +from petstore_api.model.integer_enum import IntegerEnum +from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue +from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue +from petstore_api.model.isosceles_triangle import IsoscelesTriangle +from petstore_api.model.legs import Legs +from petstore_api.model.list import List +from petstore_api.model.mammal import Mammal +from petstore_api.model.map_test import MapTest +from petstore_api.model.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from petstore_api.model.model200_response import Model200Response +from petstore_api.model.model_return import ModelReturn +from petstore_api.model.mole import Mole +from petstore_api.model.name import Name +from petstore_api.model.nullable_class import NullableClass +from petstore_api.model.nullable_shape import NullableShape +from petstore_api.model.number_only import NumberOnly +from petstore_api.model.number_with_validations import NumberWithValidations +from petstore_api.model.object_interface import ObjectInterface +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from petstore_api.model.object_with_validations import ObjectWithValidations +from petstore_api.model.order import Order +from petstore_api.model.parent_pet import ParentPet +from petstore_api.model.pet import Pet +from petstore_api.model.pig import Pig +from petstore_api.model.post_inline_additional_properties_payload_request import PostInlineAdditionalPropertiesPayloadRequest +from petstore_api.model.post_inline_additional_properties_payload_request_array_data_inner import PostInlineAdditionalPropertiesPayloadRequestArrayDataInner +from petstore_api.model.publish_options import PublishOptions +from petstore_api.model.publish_options_publish import PublishOptionsPublish +from petstore_api.model.quadrilateral import Quadrilateral +from petstore_api.model.quadrilateral_interface import QuadrilateralInterface +from petstore_api.model.read_only_first import ReadOnlyFirst +from petstore_api.model.readonly import Readonly +from petstore_api.model.scalene_triangle import ScaleneTriangle +from petstore_api.model.shape import Shape +from petstore_api.model.shape_interface import ShapeInterface +from petstore_api.model.shape_or_null import ShapeOrNull +from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral +from petstore_api.model.some_object import SomeObject +from petstore_api.model.some_object_with_self_attr import SomeObjectWithSelfAttr +from petstore_api.model.special_model_name import SpecialModelName +from petstore_api.model.stream_options import StreamOptions +from petstore_api.model.string_boolean_map import StringBooleanMap +from petstore_api.model.string_enum import StringEnum +from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue +from petstore_api.model.tag import Tag +from petstore_api.model.triangle import Triangle +from petstore_api.model.triangle_interface import TriangleInterface +from petstore_api.model.user import User +from petstore_api.model.whale import Whale +from petstore_api.model.zebra import Zebra diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/rest.py b/samples/openapi3/client/petstore/python-prior/petstore_api/rest.py new file mode 100644 index 0000000000..8ec610c5cc --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/rest.py @@ -0,0 +1,352 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import io +import json +import logging +import re +import ssl +from urllib.parse import urlencode +from urllib.parse import urlparse +from urllib.request import proxy_bypass_environment +import urllib3 +import ipaddress + +from petstore_api.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError + + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.urllib3_response.getheaders() + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.urllib3_response.getheader(name, default) + + +class RESTClientObject(object): + + def __init__(self, configuration, pools_size=4, maxsize=None): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + addition_pool_args = {} + if configuration.assert_hostname is not None: + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + + if configuration.retries is not None: + addition_pool_args['retries'] = configuration.retries + + if configuration.socket_options is not None: + addition_pool_args['socket_options'] = configuration.socket_options + + if maxsize is None: + if configuration.connection_pool_maxsize is not None: + maxsize = configuration.connection_pool_maxsize + else: + maxsize = 4 + + # https pool manager + if configuration.proxy and not should_bypass_proxies( + configuration.host, no_proxy=configuration.no_proxy or ''): + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + **addition_pool_args + ) + + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Perform requests. + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): # noqa: E501,F821 + timeout = urllib3.Timeout(total=_request_timeout) + elif (isinstance(_request_timeout, tuple) and + len(_request_timeout) == 2): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1]) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests + if (method != 'DELETE') and ('Content-Type' not in headers): + headers['Content-Type'] = 'application/json' + if query_params: + url += '?' + urlencode(query_params) + if ('Content-Type' not in headers) or (re.search('json', + headers['Content-Type'], re.IGNORECASE)): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is + # provided in serialized form + elif isinstance(body, str) or isinstance(body, bytes): + request_body = body + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request(method, url, + fields=query_params, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise ApiException(status=0, reason=msg) + + if _preload_content: + r = RESTResponse(r) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + if r.status == 401: + raise UnauthorizedException(http_resp=r) + + if r.status == 403: + raise ForbiddenException(http_resp=r) + + if r.status == 404: + raise NotFoundException(http_resp=r) + + if 500 <= r.status <= 599: + raise ServiceException(http_resp=r) + + raise ApiException(http_resp=r) + + return r + + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + return self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + +# end of class RESTClientObject + + +def is_ipv4(target): + """ Test if IPv4 address or not + """ + try: + chk = ipaddress.IPv4Address(target) + return True + except ipaddress.AddressValueError: + return False + + +def in_ipv4net(target, net): + """ Test if target belongs to given IPv4 network + """ + try: + nw = ipaddress.IPv4Network(net) + ip = ipaddress.IPv4Address(target) + if ip in nw: + return True + return False + except ipaddress.AddressValueError: + return False + except ipaddress.NetmaskValueError: + return False + + +def should_bypass_proxies(url, no_proxy=None): + """ Yet another requests.should_bypass_proxies + Test if proxies should not be used for a particular url. + """ + + parsed = urlparse(url) + + # special cases + if parsed.hostname in [None, '']: + return True + + # special cases + if no_proxy in [None, '']: + return False + if no_proxy == '*': + return True + + no_proxy = no_proxy.lower().replace(' ', ''); + entries = ( + host for host in no_proxy.split(',') if host + ) + + if is_ipv4(parsed.hostname): + for item in entries: + if in_ipv4net(parsed.hostname, item): + return True + return proxy_bypass_environment(parsed.hostname, {'no': no_proxy}) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/signing.py b/samples/openapi3/client/petstore/python-prior/petstore_api/signing.py similarity index 99% rename from samples/openapi3/client/petstore/python-experimental/petstore_api/signing.py rename to samples/openapi3/client/petstore/python-prior/petstore_api/signing.py index 22b3bf2bf1..4ea7d8f779 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/signing.py +++ b/samples/openapi3/client/petstore/python-prior/petstore_api/signing.py @@ -1,4 +1,3 @@ -# coding: utf-8 """ OpenAPI Petstore @@ -8,6 +7,7 @@ Generated by: https://openapi-generator.tech """ + from base64 import b64encode from Crypto.IO import PEM, PKCS8 from Crypto.Hash import SHA256, SHA512 @@ -341,7 +341,7 @@ class HttpSigningConfiguration(object): :return: A tuple of (digest, prefix). The digest is a hashing object that contains the cryptographic digest of the HTTP request. - The prefix is a string that identifies the cryptographc hash. It is used + The prefix is a string that identifies the cryptographic hash. It is used to generate the 'Digest' header as specified in RFC 3230. """ if self.hash_algorithm == HASH_SHA512: diff --git a/samples/openapi3/client/petstore/python-prior/pom.xml b/samples/openapi3/client/petstore/python-prior/pom.xml new file mode 100644 index 0000000000..e7d7d9caf1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + org.openapitools + PythonOAS3PetstoreTests + pom + 1.0-SNAPSHOT + Python OpenAPI3 Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + test + integration-test + + exec + + + make + + test + + + + + + + + diff --git a/samples/openapi3/client/petstore/python-prior/requirements.txt b/samples/openapi3/client/petstore/python-prior/requirements.txt new file mode 100644 index 0000000000..96947f6040 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/requirements.txt @@ -0,0 +1,3 @@ +python_dateutil >= 2.5.3 +setuptools >= 21.0.0 +urllib3 >= 1.25.3 diff --git a/samples/openapi3/client/petstore/python-experimental/setup.cfg b/samples/openapi3/client/petstore/python-prior/setup.cfg similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/setup.cfg rename to samples/openapi3/client/petstore/python-prior/setup.cfg diff --git a/samples/openapi3/client/petstore/python-prior/setup.py b/samples/openapi3/client/petstore/python-prior/setup.py new file mode 100644 index 0000000000..0fdf984806 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/setup.py @@ -0,0 +1,45 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from setuptools import setup, find_packages # noqa: H301 + +NAME = "petstore-api" +VERSION = "1.0.0" +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = [ + "urllib3 >= 1.25.3", + "python-dateutil", + "pem>=19.3.0", + "pycryptodome>=3.9.0", +] + +setup( + name=NAME, + version=VERSION, + description="OpenAPI Petstore", + author="OpenAPI Generator community", + author_email="team@openapitools.org", + url="", + keywords=["OpenAPI", "OpenAPI-Generator", "OpenAPI Petstore"], + python_requires=">=3.6", + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + license="Apache-2.0", + long_description="""\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + """ +) diff --git a/samples/openapi3/client/petstore/python-prior/test-requirements.txt b/samples/openapi3/client/petstore/python-prior/test-requirements.txt new file mode 100644 index 0000000000..4b3736d983 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/test-requirements.txt @@ -0,0 +1,2 @@ +pytest-cov>=2.8.1 +pycryptodome>=3.9.0 diff --git a/samples/openapi3/client/petstore/python-prior/test/__init__.py b/samples/openapi3/client/petstore/python-prior/test/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_additional_properties_class.py b/samples/openapi3/client/petstore/python-prior/test/test_additional_properties_class.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_additional_properties_class.py rename to samples/openapi3/client/petstore/python-prior/test/test_additional_properties_class.py diff --git a/samples/openapi3/client/petstore/python/test/test_additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python-prior/test/test_additional_properties_with_array_of_enums.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_additional_properties_with_array_of_enums.py rename to samples/openapi3/client/petstore/python-prior/test/test_additional_properties_with_array_of_enums.py diff --git a/samples/openapi3/client/petstore/python/test/test_address.py b/samples/openapi3/client/petstore/python-prior/test/test_address.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_address.py rename to samples/openapi3/client/petstore/python-prior/test/test_address.py diff --git a/samples/openapi3/client/petstore/python/test/test_animal.py b/samples/openapi3/client/petstore/python-prior/test/test_animal.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_animal.py rename to samples/openapi3/client/petstore/python-prior/test/test_animal.py diff --git a/samples/openapi3/client/petstore/python/test/test_animal_farm.py b/samples/openapi3/client/petstore/python-prior/test/test_animal_farm.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_animal_farm.py rename to samples/openapi3/client/petstore/python-prior/test/test_animal_farm.py diff --git a/samples/openapi3/client/petstore/python/test/test_another_fake_api.py b/samples/openapi3/client/petstore/python-prior/test/test_another_fake_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_another_fake_api.py rename to samples/openapi3/client/petstore/python-prior/test/test_another_fake_api.py diff --git a/samples/openapi3/client/petstore/python/test/test_api_response.py b/samples/openapi3/client/petstore/python-prior/test/test_api_response.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_api_response.py rename to samples/openapi3/client/petstore/python-prior/test/test_api_response.py diff --git a/samples/openapi3/client/petstore/python/test/test_apple.py b/samples/openapi3/client/petstore/python-prior/test/test_apple.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_apple.py rename to samples/openapi3/client/petstore/python-prior/test/test_apple.py diff --git a/samples/openapi3/client/petstore/python/test/test_apple_req.py b/samples/openapi3/client/petstore/python-prior/test/test_apple_req.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_apple_req.py rename to samples/openapi3/client/petstore/python-prior/test/test_apple_req.py diff --git a/samples/openapi3/client/petstore/python/test/test_array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-prior/test/test_array_of_array_of_number_only.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_array_of_array_of_number_only.py rename to samples/openapi3/client/petstore/python-prior/test/test_array_of_array_of_number_only.py diff --git a/samples/openapi3/client/petstore/python/test/test_array_of_enums.py b/samples/openapi3/client/petstore/python-prior/test/test_array_of_enums.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_array_of_enums.py rename to samples/openapi3/client/petstore/python-prior/test/test_array_of_enums.py diff --git a/samples/openapi3/client/petstore/python/test/test_array_of_number_only.py b/samples/openapi3/client/petstore/python-prior/test/test_array_of_number_only.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_array_of_number_only.py rename to samples/openapi3/client/petstore/python-prior/test/test_array_of_number_only.py diff --git a/samples/openapi3/client/petstore/python/test/test_array_test.py b/samples/openapi3/client/petstore/python-prior/test/test_array_test.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_array_test.py rename to samples/openapi3/client/petstore/python-prior/test/test_array_test.py diff --git a/samples/openapi3/client/petstore/python/test/test_banana.py b/samples/openapi3/client/petstore/python-prior/test/test_banana.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_banana.py rename to samples/openapi3/client/petstore/python-prior/test/test_banana.py diff --git a/samples/openapi3/client/petstore/python/test/test_banana_req.py b/samples/openapi3/client/petstore/python-prior/test/test_banana_req.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_banana_req.py rename to samples/openapi3/client/petstore/python-prior/test/test_banana_req.py diff --git a/samples/openapi3/client/petstore/python/test/test_basque_pig.py b/samples/openapi3/client/petstore/python-prior/test/test_basque_pig.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_basque_pig.py rename to samples/openapi3/client/petstore/python-prior/test/test_basque_pig.py diff --git a/samples/openapi3/client/petstore/python/test/test_boolean_enum.py b/samples/openapi3/client/petstore/python-prior/test/test_boolean_enum.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_boolean_enum.py rename to samples/openapi3/client/petstore/python-prior/test/test_boolean_enum.py diff --git a/samples/openapi3/client/petstore/python/test/test_capitalization.py b/samples/openapi3/client/petstore/python-prior/test/test_capitalization.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_capitalization.py rename to samples/openapi3/client/petstore/python-prior/test/test_capitalization.py diff --git a/samples/openapi3/client/petstore/python/test/test_cat.py b/samples/openapi3/client/petstore/python-prior/test/test_cat.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_cat.py rename to samples/openapi3/client/petstore/python-prior/test/test_cat.py diff --git a/samples/openapi3/client/petstore/python/test/test_cat_all_of.py b/samples/openapi3/client/petstore/python-prior/test/test_cat_all_of.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_cat_all_of.py rename to samples/openapi3/client/petstore/python-prior/test/test_cat_all_of.py diff --git a/samples/openapi3/client/petstore/python/test/test_category.py b/samples/openapi3/client/petstore/python-prior/test/test_category.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_category.py rename to samples/openapi3/client/petstore/python-prior/test/test_category.py diff --git a/samples/openapi3/client/petstore/python/test/test_child_cat.py b/samples/openapi3/client/petstore/python-prior/test/test_child_cat.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_child_cat.py rename to samples/openapi3/client/petstore/python-prior/test/test_child_cat.py diff --git a/samples/openapi3/client/petstore/python/test/test_child_cat_all_of.py b/samples/openapi3/client/petstore/python-prior/test/test_child_cat_all_of.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_child_cat_all_of.py rename to samples/openapi3/client/petstore/python-prior/test/test_child_cat_all_of.py diff --git a/samples/openapi3/client/petstore/python/test/test_class_model.py b/samples/openapi3/client/petstore/python-prior/test/test_class_model.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_class_model.py rename to samples/openapi3/client/petstore/python-prior/test/test_class_model.py diff --git a/samples/openapi3/client/petstore/python/test/test_client.py b/samples/openapi3/client/petstore/python-prior/test/test_client.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_client.py rename to samples/openapi3/client/petstore/python-prior/test/test_client.py diff --git a/samples/openapi3/client/petstore/python/test/test_complex_quadrilateral.py b/samples/openapi3/client/petstore/python-prior/test/test_complex_quadrilateral.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_complex_quadrilateral.py rename to samples/openapi3/client/petstore/python-prior/test/test_complex_quadrilateral.py diff --git a/samples/openapi3/client/petstore/python/test/test_composed_one_of_number_with_validations.py b/samples/openapi3/client/petstore/python-prior/test/test_composed_one_of_number_with_validations.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_composed_one_of_number_with_validations.py rename to samples/openapi3/client/petstore/python-prior/test/test_composed_one_of_number_with_validations.py diff --git a/samples/openapi3/client/petstore/python/test/test_composed_schema_with_props_and_no_add_props.py b/samples/openapi3/client/petstore/python-prior/test/test_composed_schema_with_props_and_no_add_props.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_composed_schema_with_props_and_no_add_props.py rename to samples/openapi3/client/petstore/python-prior/test/test_composed_schema_with_props_and_no_add_props.py diff --git a/samples/openapi3/client/petstore/python/test/test_danish_pig.py b/samples/openapi3/client/petstore/python-prior/test/test_danish_pig.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_danish_pig.py rename to samples/openapi3/client/petstore/python-prior/test/test_danish_pig.py diff --git a/samples/openapi3/client/petstore/python/test/test_default_api.py b/samples/openapi3/client/petstore/python-prior/test/test_default_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_default_api.py rename to samples/openapi3/client/petstore/python-prior/test/test_default_api.py diff --git a/samples/openapi3/client/petstore/python/test/test_dog.py b/samples/openapi3/client/petstore/python-prior/test/test_dog.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_dog.py rename to samples/openapi3/client/petstore/python-prior/test/test_dog.py diff --git a/samples/openapi3/client/petstore/python/test/test_dog_all_of.py b/samples/openapi3/client/petstore/python-prior/test/test_dog_all_of.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_dog_all_of.py rename to samples/openapi3/client/petstore/python-prior/test/test_dog_all_of.py diff --git a/samples/openapi3/client/petstore/python/test/test_drawing.py b/samples/openapi3/client/petstore/python-prior/test/test_drawing.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_drawing.py rename to samples/openapi3/client/petstore/python-prior/test/test_drawing.py diff --git a/samples/openapi3/client/petstore/python/test/test_egress_threshold_options.py b/samples/openapi3/client/petstore/python-prior/test/test_egress_threshold_options.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_egress_threshold_options.py rename to samples/openapi3/client/petstore/python-prior/test/test_egress_threshold_options.py diff --git a/samples/openapi3/client/petstore/python/test/test_enum_arrays.py b/samples/openapi3/client/petstore/python-prior/test/test_enum_arrays.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_enum_arrays.py rename to samples/openapi3/client/petstore/python-prior/test/test_enum_arrays.py diff --git a/samples/openapi3/client/petstore/python/test/test_enum_class.py b/samples/openapi3/client/petstore/python-prior/test/test_enum_class.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_enum_class.py rename to samples/openapi3/client/petstore/python-prior/test/test_enum_class.py diff --git a/samples/openapi3/client/petstore/python/test/test_enum_test.py b/samples/openapi3/client/petstore/python-prior/test/test_enum_test.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_enum_test.py rename to samples/openapi3/client/petstore/python-prior/test/test_enum_test.py diff --git a/samples/openapi3/client/petstore/python/test/test_equilateral_triangle.py b/samples/openapi3/client/petstore/python-prior/test/test_equilateral_triangle.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_equilateral_triangle.py rename to samples/openapi3/client/petstore/python-prior/test/test_equilateral_triangle.py diff --git a/samples/openapi3/client/petstore/python/test/test_fake_api.py b/samples/openapi3/client/petstore/python-prior/test/test_fake_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_fake_api.py rename to samples/openapi3/client/petstore/python-prior/test/test_fake_api.py diff --git a/samples/openapi3/client/petstore/python/test/test_fake_classname_tags123_api.py b/samples/openapi3/client/petstore/python-prior/test/test_fake_classname_tags123_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_fake_classname_tags123_api.py rename to samples/openapi3/client/petstore/python-prior/test/test_fake_classname_tags123_api.py diff --git a/samples/openapi3/client/petstore/python/test/test_fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-prior/test/test_fake_classname_tags_123_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_fake_classname_tags_123_api.py rename to samples/openapi3/client/petstore/python-prior/test/test_fake_classname_tags_123_api.py diff --git a/samples/openapi3/client/petstore/python/test/test_fake_post_inline_additional_properties_payload_array_data.py b/samples/openapi3/client/petstore/python-prior/test/test_fake_post_inline_additional_properties_payload_array_data.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_fake_post_inline_additional_properties_payload_array_data.py rename to samples/openapi3/client/petstore/python-prior/test/test_fake_post_inline_additional_properties_payload_array_data.py diff --git a/samples/openapi3/client/petstore/python/test/test_file.py b/samples/openapi3/client/petstore/python-prior/test/test_file.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_file.py rename to samples/openapi3/client/petstore/python-prior/test/test_file.py diff --git a/samples/openapi3/client/petstore/python/test/test_file_schema_test_class.py b/samples/openapi3/client/petstore/python-prior/test/test_file_schema_test_class.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_file_schema_test_class.py rename to samples/openapi3/client/petstore/python-prior/test/test_file_schema_test_class.py diff --git a/samples/openapi3/client/petstore/python/test/test_foo.py b/samples/openapi3/client/petstore/python-prior/test/test_foo.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_foo.py rename to samples/openapi3/client/petstore/python-prior/test/test_foo.py diff --git a/samples/openapi3/client/petstore/python/test/test_foo_get_default_response.py b/samples/openapi3/client/petstore/python-prior/test/test_foo_get_default_response.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_foo_get_default_response.py rename to samples/openapi3/client/petstore/python-prior/test/test_foo_get_default_response.py diff --git a/samples/openapi3/client/petstore/python/test/test_foo_object.py b/samples/openapi3/client/petstore/python-prior/test/test_foo_object.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_foo_object.py rename to samples/openapi3/client/petstore/python-prior/test/test_foo_object.py diff --git a/samples/openapi3/client/petstore/python/test/test_format_test.py b/samples/openapi3/client/petstore/python-prior/test/test_format_test.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_format_test.py rename to samples/openapi3/client/petstore/python-prior/test/test_format_test.py diff --git a/samples/openapi3/client/petstore/python/test/test_fruit.py b/samples/openapi3/client/petstore/python-prior/test/test_fruit.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_fruit.py rename to samples/openapi3/client/petstore/python-prior/test/test_fruit.py diff --git a/samples/openapi3/client/petstore/python/test/test_fruit_req.py b/samples/openapi3/client/petstore/python-prior/test/test_fruit_req.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_fruit_req.py rename to samples/openapi3/client/petstore/python-prior/test/test_fruit_req.py diff --git a/samples/openapi3/client/petstore/python/test/test_gm_fruit.py b/samples/openapi3/client/petstore/python-prior/test/test_gm_fruit.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_gm_fruit.py rename to samples/openapi3/client/petstore/python-prior/test/test_gm_fruit.py diff --git a/samples/openapi3/client/petstore/python/test/test_gm_fruit_no_properties.py b/samples/openapi3/client/petstore/python-prior/test/test_gm_fruit_no_properties.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_gm_fruit_no_properties.py rename to samples/openapi3/client/petstore/python-prior/test/test_gm_fruit_no_properties.py diff --git a/samples/openapi3/client/petstore/python/test/test_grandparent_animal.py b/samples/openapi3/client/petstore/python-prior/test/test_grandparent_animal.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_grandparent_animal.py rename to samples/openapi3/client/petstore/python-prior/test/test_grandparent_animal.py diff --git a/samples/openapi3/client/petstore/python/test/test_has_only_read_only.py b/samples/openapi3/client/petstore/python-prior/test/test_has_only_read_only.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_has_only_read_only.py rename to samples/openapi3/client/petstore/python-prior/test/test_has_only_read_only.py diff --git a/samples/openapi3/client/petstore/python/test/test_health_check_result.py b/samples/openapi3/client/petstore/python-prior/test/test_health_check_result.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_health_check_result.py rename to samples/openapi3/client/petstore/python-prior/test/test_health_check_result.py diff --git a/samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py b/samples/openapi3/client/petstore/python-prior/test/test_inline_additional_properties_ref_payload.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py rename to samples/openapi3/client/petstore/python-prior/test/test_inline_additional_properties_ref_payload.py diff --git a/samples/openapi3/client/petstore/python/test/test_inline_object6.py b/samples/openapi3/client/petstore/python-prior/test/test_inline_object6.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_inline_object6.py rename to samples/openapi3/client/petstore/python-prior/test/test_inline_object6.py diff --git a/samples/openapi3/client/petstore/python/test/test_inline_response_default.py b/samples/openapi3/client/petstore/python-prior/test/test_inline_response_default.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_inline_response_default.py rename to samples/openapi3/client/petstore/python-prior/test/test_inline_response_default.py diff --git a/samples/openapi3/client/petstore/python/test/test_integer_enum.py b/samples/openapi3/client/petstore/python-prior/test/test_integer_enum.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_integer_enum.py rename to samples/openapi3/client/petstore/python-prior/test/test_integer_enum.py diff --git a/samples/openapi3/client/petstore/python/test/test_integer_enum_one_value.py b/samples/openapi3/client/petstore/python-prior/test/test_integer_enum_one_value.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_integer_enum_one_value.py rename to samples/openapi3/client/petstore/python-prior/test/test_integer_enum_one_value.py diff --git a/samples/openapi3/client/petstore/python/test/test_integer_enum_with_default_value.py b/samples/openapi3/client/petstore/python-prior/test/test_integer_enum_with_default_value.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_integer_enum_with_default_value.py rename to samples/openapi3/client/petstore/python-prior/test/test_integer_enum_with_default_value.py diff --git a/samples/openapi3/client/petstore/python/test/test_isosceles_triangle.py b/samples/openapi3/client/petstore/python-prior/test/test_isosceles_triangle.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_isosceles_triangle.py rename to samples/openapi3/client/petstore/python-prior/test/test_isosceles_triangle.py diff --git a/samples/openapi3/client/petstore/python/test/test_legs.py b/samples/openapi3/client/petstore/python-prior/test/test_legs.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_legs.py rename to samples/openapi3/client/petstore/python-prior/test/test_legs.py diff --git a/samples/openapi3/client/petstore/python/test/test_list.py b/samples/openapi3/client/petstore/python-prior/test/test_list.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_list.py rename to samples/openapi3/client/petstore/python-prior/test/test_list.py diff --git a/samples/openapi3/client/petstore/python/test/test_mammal.py b/samples/openapi3/client/petstore/python-prior/test/test_mammal.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_mammal.py rename to samples/openapi3/client/petstore/python-prior/test/test_mammal.py diff --git a/samples/openapi3/client/petstore/python/test/test_map_test.py b/samples/openapi3/client/petstore/python-prior/test/test_map_test.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_map_test.py rename to samples/openapi3/client/petstore/python-prior/test/test_map_test.py diff --git a/samples/openapi3/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-prior/test/test_mixed_properties_and_additional_properties_class.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_mixed_properties_and_additional_properties_class.py rename to samples/openapi3/client/petstore/python-prior/test/test_mixed_properties_and_additional_properties_class.py diff --git a/samples/openapi3/client/petstore/python/test/test_model200_response.py b/samples/openapi3/client/petstore/python-prior/test/test_model200_response.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_model200_response.py rename to samples/openapi3/client/petstore/python-prior/test/test_model200_response.py diff --git a/samples/openapi3/client/petstore/python/test/test_model_200_response.py b/samples/openapi3/client/petstore/python-prior/test/test_model_200_response.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_model_200_response.py rename to samples/openapi3/client/petstore/python-prior/test/test_model_200_response.py diff --git a/samples/openapi3/client/petstore/python/test/test_model_return.py b/samples/openapi3/client/petstore/python-prior/test/test_model_return.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_model_return.py rename to samples/openapi3/client/petstore/python-prior/test/test_model_return.py diff --git a/samples/openapi3/client/petstore/python/test/test_mole.py b/samples/openapi3/client/petstore/python-prior/test/test_mole.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_mole.py rename to samples/openapi3/client/petstore/python-prior/test/test_mole.py diff --git a/samples/openapi3/client/petstore/python/test/test_name.py b/samples/openapi3/client/petstore/python-prior/test/test_name.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_name.py rename to samples/openapi3/client/petstore/python-prior/test/test_name.py diff --git a/samples/openapi3/client/petstore/python/test/test_nullable_class.py b/samples/openapi3/client/petstore/python-prior/test/test_nullable_class.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_nullable_class.py rename to samples/openapi3/client/petstore/python-prior/test/test_nullable_class.py diff --git a/samples/openapi3/client/petstore/python/test/test_nullable_shape.py b/samples/openapi3/client/petstore/python-prior/test/test_nullable_shape.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_nullable_shape.py rename to samples/openapi3/client/petstore/python-prior/test/test_nullable_shape.py diff --git a/samples/openapi3/client/petstore/python/test/test_number_only.py b/samples/openapi3/client/petstore/python-prior/test/test_number_only.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_number_only.py rename to samples/openapi3/client/petstore/python-prior/test/test_number_only.py diff --git a/samples/openapi3/client/petstore/python/test/test_number_with_validations.py b/samples/openapi3/client/petstore/python-prior/test/test_number_with_validations.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_number_with_validations.py rename to samples/openapi3/client/petstore/python-prior/test/test_number_with_validations.py diff --git a/samples/openapi3/client/petstore/python/test/test_object_interface.py b/samples/openapi3/client/petstore/python-prior/test/test_object_interface.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_object_interface.py rename to samples/openapi3/client/petstore/python-prior/test/test_object_interface.py diff --git a/samples/openapi3/client/petstore/python/test/test_object_model_with_ref_props.py b/samples/openapi3/client/petstore/python-prior/test/test_object_model_with_ref_props.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_object_model_with_ref_props.py rename to samples/openapi3/client/petstore/python-prior/test/test_object_model_with_ref_props.py diff --git a/samples/openapi3/client/petstore/python/test/test_object_with_validations.py b/samples/openapi3/client/petstore/python-prior/test/test_object_with_validations.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_object_with_validations.py rename to samples/openapi3/client/petstore/python-prior/test/test_object_with_validations.py diff --git a/samples/openapi3/client/petstore/python/test/test_order.py b/samples/openapi3/client/petstore/python-prior/test/test_order.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_order.py rename to samples/openapi3/client/petstore/python-prior/test/test_order.py diff --git a/samples/openapi3/client/petstore/python/test/test_parent_pet.py b/samples/openapi3/client/petstore/python-prior/test/test_parent_pet.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_parent_pet.py rename to samples/openapi3/client/petstore/python-prior/test/test_parent_pet.py diff --git a/samples/openapi3/client/petstore/python/test/test_pet.py b/samples/openapi3/client/petstore/python-prior/test/test_pet.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_pet.py rename to samples/openapi3/client/petstore/python-prior/test/test_pet.py diff --git a/samples/openapi3/client/petstore/python/test/test_pet_api.py b/samples/openapi3/client/petstore/python-prior/test/test_pet_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_pet_api.py rename to samples/openapi3/client/petstore/python-prior/test/test_pet_api.py diff --git a/samples/openapi3/client/petstore/python/test/test_pig.py b/samples/openapi3/client/petstore/python-prior/test/test_pig.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_pig.py rename to samples/openapi3/client/petstore/python-prior/test/test_pig.py diff --git a/samples/openapi3/client/petstore/python/test/test_post_inline_additional_properties_payload_request.py b/samples/openapi3/client/petstore/python-prior/test/test_post_inline_additional_properties_payload_request.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_post_inline_additional_properties_payload_request.py rename to samples/openapi3/client/petstore/python-prior/test/test_post_inline_additional_properties_payload_request.py diff --git a/samples/openapi3/client/petstore/python/test/test_post_inline_additional_properties_payload_request_array_data_inner.py b/samples/openapi3/client/petstore/python-prior/test/test_post_inline_additional_properties_payload_request_array_data_inner.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_post_inline_additional_properties_payload_request_array_data_inner.py rename to samples/openapi3/client/petstore/python-prior/test/test_post_inline_additional_properties_payload_request_array_data_inner.py diff --git a/samples/openapi3/client/petstore/python/test/test_publish_options.py b/samples/openapi3/client/petstore/python-prior/test/test_publish_options.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_publish_options.py rename to samples/openapi3/client/petstore/python-prior/test/test_publish_options.py diff --git a/samples/openapi3/client/petstore/python/test/test_publish_options_publish.py b/samples/openapi3/client/petstore/python-prior/test/test_publish_options_publish.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_publish_options_publish.py rename to samples/openapi3/client/petstore/python-prior/test/test_publish_options_publish.py diff --git a/samples/openapi3/client/petstore/python/test/test_quadrilateral.py b/samples/openapi3/client/petstore/python-prior/test/test_quadrilateral.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_quadrilateral.py rename to samples/openapi3/client/petstore/python-prior/test/test_quadrilateral.py diff --git a/samples/openapi3/client/petstore/python/test/test_quadrilateral_interface.py b/samples/openapi3/client/petstore/python-prior/test/test_quadrilateral_interface.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_quadrilateral_interface.py rename to samples/openapi3/client/petstore/python-prior/test/test_quadrilateral_interface.py diff --git a/samples/openapi3/client/petstore/python/test/test_read_only_first.py b/samples/openapi3/client/petstore/python-prior/test/test_read_only_first.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_read_only_first.py rename to samples/openapi3/client/petstore/python-prior/test/test_read_only_first.py diff --git a/samples/openapi3/client/petstore/python/test/test_readonly.py b/samples/openapi3/client/petstore/python-prior/test/test_readonly.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_readonly.py rename to samples/openapi3/client/petstore/python-prior/test/test_readonly.py diff --git a/samples/openapi3/client/petstore/python/test/test_scalene_triangle.py b/samples/openapi3/client/petstore/python-prior/test/test_scalene_triangle.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_scalene_triangle.py rename to samples/openapi3/client/petstore/python-prior/test/test_scalene_triangle.py diff --git a/samples/openapi3/client/petstore/python/test/test_shape.py b/samples/openapi3/client/petstore/python-prior/test/test_shape.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_shape.py rename to samples/openapi3/client/petstore/python-prior/test/test_shape.py diff --git a/samples/openapi3/client/petstore/python/test/test_shape_interface.py b/samples/openapi3/client/petstore/python-prior/test/test_shape_interface.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_shape_interface.py rename to samples/openapi3/client/petstore/python-prior/test/test_shape_interface.py diff --git a/samples/openapi3/client/petstore/python/test/test_shape_or_null.py b/samples/openapi3/client/petstore/python-prior/test/test_shape_or_null.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_shape_or_null.py rename to samples/openapi3/client/petstore/python-prior/test/test_shape_or_null.py diff --git a/samples/openapi3/client/petstore/python/test/test_simple_quadrilateral.py b/samples/openapi3/client/petstore/python-prior/test/test_simple_quadrilateral.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_simple_quadrilateral.py rename to samples/openapi3/client/petstore/python-prior/test/test_simple_quadrilateral.py diff --git a/samples/openapi3/client/petstore/python/test/test_some_object.py b/samples/openapi3/client/petstore/python-prior/test/test_some_object.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_some_object.py rename to samples/openapi3/client/petstore/python-prior/test/test_some_object.py diff --git a/samples/openapi3/client/petstore/python/test/test_some_object_with_self_attr.py b/samples/openapi3/client/petstore/python-prior/test/test_some_object_with_self_attr.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_some_object_with_self_attr.py rename to samples/openapi3/client/petstore/python-prior/test/test_some_object_with_self_attr.py diff --git a/samples/openapi3/client/petstore/python/test/test_special_model_name.py b/samples/openapi3/client/petstore/python-prior/test/test_special_model_name.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_special_model_name.py rename to samples/openapi3/client/petstore/python-prior/test/test_special_model_name.py diff --git a/samples/openapi3/client/petstore/python/test/test_store_api.py b/samples/openapi3/client/petstore/python-prior/test/test_store_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_store_api.py rename to samples/openapi3/client/petstore/python-prior/test/test_store_api.py diff --git a/samples/openapi3/client/petstore/python/test/test_stream_options.py b/samples/openapi3/client/petstore/python-prior/test/test_stream_options.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_stream_options.py rename to samples/openapi3/client/petstore/python-prior/test/test_stream_options.py diff --git a/samples/openapi3/client/petstore/python/test/test_string_boolean_map.py b/samples/openapi3/client/petstore/python-prior/test/test_string_boolean_map.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_string_boolean_map.py rename to samples/openapi3/client/petstore/python-prior/test/test_string_boolean_map.py diff --git a/samples/openapi3/client/petstore/python/test/test_string_enum.py b/samples/openapi3/client/petstore/python-prior/test/test_string_enum.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_string_enum.py rename to samples/openapi3/client/petstore/python-prior/test/test_string_enum.py diff --git a/samples/openapi3/client/petstore/python/test/test_string_enum_with_default_value.py b/samples/openapi3/client/petstore/python-prior/test/test_string_enum_with_default_value.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_string_enum_with_default_value.py rename to samples/openapi3/client/petstore/python-prior/test/test_string_enum_with_default_value.py diff --git a/samples/openapi3/client/petstore/python/test/test_tag.py b/samples/openapi3/client/petstore/python-prior/test/test_tag.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_tag.py rename to samples/openapi3/client/petstore/python-prior/test/test_tag.py diff --git a/samples/openapi3/client/petstore/python/test/test_triangle.py b/samples/openapi3/client/petstore/python-prior/test/test_triangle.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_triangle.py rename to samples/openapi3/client/petstore/python-prior/test/test_triangle.py diff --git a/samples/openapi3/client/petstore/python/test/test_triangle_interface.py b/samples/openapi3/client/petstore/python-prior/test/test_triangle_interface.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_triangle_interface.py rename to samples/openapi3/client/petstore/python-prior/test/test_triangle_interface.py diff --git a/samples/openapi3/client/petstore/python/test/test_user.py b/samples/openapi3/client/petstore/python-prior/test/test_user.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_user.py rename to samples/openapi3/client/petstore/python-prior/test/test_user.py diff --git a/samples/openapi3/client/petstore/python/test/test_user_api.py b/samples/openapi3/client/petstore/python-prior/test/test_user_api.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_user_api.py rename to samples/openapi3/client/petstore/python-prior/test/test_user_api.py diff --git a/samples/openapi3/client/petstore/python/test/test_whale.py b/samples/openapi3/client/petstore/python-prior/test/test_whale.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_whale.py rename to samples/openapi3/client/petstore/python-prior/test/test_whale.py diff --git a/samples/openapi3/client/petstore/python/test/test_zebra.py b/samples/openapi3/client/petstore/python-prior/test/test_zebra.py similarity index 100% rename from samples/openapi3/client/petstore/python/test/test_zebra.py rename to samples/openapi3/client/petstore/python-prior/test/test_zebra.py diff --git a/samples/openapi3/client/petstore/python-experimental/test_python.sh b/samples/openapi3/client/petstore/python-prior/test_python.sh similarity index 79% rename from samples/openapi3/client/petstore/python-experimental/test_python.sh rename to samples/openapi3/client/petstore/python-prior/test_python.sh index 9728a9b531..f617f3adfa 100755 --- a/samples/openapi3/client/petstore/python-experimental/test_python.sh +++ b/samples/openapi3/client/petstore/python-prior/test_python.sh @@ -10,16 +10,14 @@ export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 ### set virtualenv -if [ -z "$VENVV" ]; then - python3 -m venv $VENV +if [ -z "$VIRTUAL_ENV" ]; then + virtualenv $VENV --always-copy source $VENV/bin/activate DEACTIVE=true fi ### install dependencies pip install -r $REQUIREMENTS_FILE | tee -a $REQUIREMENTS_OUT -### locally install the package, needed for pycharm problem checking -pip install -e . ### run tests tox || exit 1 diff --git a/samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic1.png b/samples/openapi3/client/petstore/python-prior/testfiles/1px_pic1.png similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic1.png rename to samples/openapi3/client/petstore/python-prior/testfiles/1px_pic1.png diff --git a/samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic2.png b/samples/openapi3/client/petstore/python-prior/testfiles/1px_pic2.png similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic2.png rename to samples/openapi3/client/petstore/python-prior/testfiles/1px_pic2.png diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/__init__.py b/samples/openapi3/client/petstore/python-prior/tests_manual/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_api_validation.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_api_validation.py similarity index 100% rename from samples/openapi3/client/petstore/python/tests_manual/test_api_validation.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/test_api_validation.py diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_boolean_enum.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_boolean_enum.py new file mode 100644 index 0000000000..09f386f23a --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_boolean_enum.py @@ -0,0 +1,39 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.boolean_enum import BooleanEnum + + +class TestBooleanEnum(unittest.TestCase): + """BooleanEnum unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testBooleanEnum(self): + """Test BooleanEnum""" + model = BooleanEnum(True) + assert model.value is True + + assert BooleanEnum.allowed_values[('value',)]['TRUE'] is True + + with self.assertRaises(petstore_api.ApiValueError): + BooleanEnum(False) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_composed_one_of_number_with_validations.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_composed_one_of_number_with_validations.py similarity index 100% rename from samples/openapi3/client/petstore/python/tests_manual/test_composed_one_of_number_with_validations.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/test_composed_one_of_number_with_validations.py diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_composed_schema_with_props_and_no_add_props.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_composed_schema_with_props_and_no_add_props.py similarity index 100% rename from samples/openapi3/client/petstore/python/tests_manual/test_composed_schema_with_props_and_no_add_props.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/test_composed_schema_with_props_and_no_add_props.py diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_copy.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_copy.py new file mode 100644 index 0000000000..e70fd67b34 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_copy.py @@ -0,0 +1,42 @@ +from copy import deepcopy +import unittest +from petstore_api.model.mammal import Mammal +from petstore_api.model.triangle import Triangle +from petstore_api.model.dog import Dog + +class TestCopy(unittest.TestCase): + """TestCopy unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testDeepCopyOneOf(self): + """test deepcopy""" + obj = deepcopy(Mammal(class_name="whale")) + assert id(deepcopy(obj)) != id(obj) + assert deepcopy(obj) == obj + + def testDeepCopyAllOf(self): + """test deepcopy""" + obj = Triangle(shape_type="Triangle", triangle_type="EquilateralTriangle", foo="blah") + assert id(deepcopy(obj)) != id(obj) + assert deepcopy(obj) == obj + + obj = Triangle._new_from_openapi_data(shape_type="Triangle", triangle_type="EquilateralTriangle", foo="blah") + assert id(deepcopy(obj)) != id(obj) + assert deepcopy(obj) == obj + + obj = Dog._new_from_openapi_data(class_name='Dog', color='white', breed='Jack Russel Terrier') + assert id(deepcopy(obj)) != id(obj) + assert deepcopy(obj) == obj + + obj = Dog(class_name='Dog', color='white', breed='Jack Russel Terrier') + assert id(deepcopy(obj)) != id(obj) + assert deepcopy(obj) == obj + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_deserialization.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_deserialization.py new file mode 100644 index 0000000000..93538160f9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_deserialization.py @@ -0,0 +1,327 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ pip install nose (optional) +$ cd OpenAPIPetstore-python +$ nosetests -v +""" +from collections import namedtuple +import json +import os +import time +import unittest +import datetime + +import petstore_api +from petstore_api.model import ( + shape, + equilateral_triangle, + animal, + dog, + apple, + mammal, + whale, + zebra, + banana, + fruit_req, + drawing, + banana_req, + number_with_validations, +) + + +MockResponse = namedtuple('MockResponse', 'data') + + +class DeserializationTests(unittest.TestCase): + + def setUp(self): + self.api_client = petstore_api.ApiClient() + self.deserialize = self.api_client.deserialize + + def test_deserialize_shape(self): + """ + + deserialize Shape to an instance of: + - EquilateralTriangle + - IsoscelesTriangle + - IsoscelesTriangle + - ScaleneTriangle + - ComplexQuadrilateral + - SimpleQuadrilateral + by traveling through 2 discriminators + """ + shape_type, triangle_type = ['Triangle', 'EquilateralTriangle'] + data = { + 'shapeType': shape_type, + 'triangleType': triangle_type, + } + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, (shape.Shape,), True) + self.assertTrue(isinstance(deserialized, equilateral_triangle.EquilateralTriangle)) + self.assertEqual(deserialized.shape_type, shape_type) + self.assertEqual(deserialized.triangle_type, triangle_type) + + # invalid second discriminator value + shape_type, quadrilateral_type = ['Quadrilateral', 'Triangle'] + data = { + 'shapeType': shape_type, + 'quadrilateralType': quadrilateral_type, + } + response = MockResponse(data=json.dumps(data)) + + err_msg = ("Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '{}'='{}' at path: ()" + ) + with self.assertRaisesRegex( + petstore_api.ApiValueError, + err_msg.format("quadrilateralType", "Triangle") + ): + self.deserialize(response, (shape.Shape,), True) + + def test_deserialize_animal(self): + """ + deserialize Animal to a Dog instance + Animal uses a discriminator which has a map built of child classes + that inherrit from Animal + This is the swagger (v2) way of doing something like oneOf composition + """ + class_name = 'Dog' + color = 'white' + breed = 'Jack Russel Terrier' + data = { + 'className': class_name, + 'color': color, + 'breed': breed + } + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, (animal.Animal,), True) + self.assertTrue(isinstance(deserialized, dog.Dog)) + self.assertEqual(deserialized.class_name, class_name) + self.assertEqual(deserialized.color, color) + self.assertEqual(deserialized.breed, breed) + + def test_regex_constraint(self): + """ + Test regex pattern validation. + """ + + # Test with valid regex pattern. + inst = apple.Apple( + cultivar="Akane" + ) + assert isinstance(inst, apple.Apple) + + # Test with invalid regex pattern in cultivar + err_msg = ("Invalid value for `{}`, must match regular expression `{}`$") + with self.assertRaisesRegex( + petstore_api.ApiValueError, + err_msg.format("cultivar", "[^`]*") + ): + inst = apple.Apple( + cultivar="!@#%@$#Akane" + ) + + # Test with invalid regex pattern in origin + err_msg = ("Invalid value for `{}`, must match regular expression `{}` with flags") + with self.assertRaisesRegex( + petstore_api.ApiValueError, + err_msg.format("origin", "[^`]*") + ): + inst = apple.Apple( + cultivar="Akane", + origin="!@#%@$#Chile" + ) + + def test_deserialize_mammal(self): + """ + deserialize mammal + mammal is a oneOf composed schema model with discriminator + """ + + # whale test + has_baleen = True + has_teeth = False + class_name = 'whale' + data = { + 'hasBaleen': has_baleen, + 'hasTeeth': has_teeth, + 'className': class_name + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (mammal.Mammal,), True) + self.assertTrue(isinstance(deserialized, whale.Whale)) + self.assertEqual(deserialized.has_baleen, has_baleen) + self.assertEqual(deserialized.has_teeth, has_teeth) + self.assertEqual(deserialized.class_name, class_name) + + # zebra test + zebra_type = 'plains' + class_name = 'zebra' + data = { + 'type': zebra_type, + 'className': class_name + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (mammal.Mammal,), True) + self.assertTrue(isinstance(deserialized, zebra.Zebra)) + self.assertEqual(deserialized.type, zebra_type) + self.assertEqual(deserialized.class_name, class_name) + + def test_deserialize_float_value(self): + """ + Deserialize floating point values. + """ + data = { + 'lengthCm': 3.1415 + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (banana.Banana,), True) + self.assertTrue(isinstance(deserialized, banana.Banana)) + self.assertEqual(deserialized.length_cm, 3.1415) + + # Float value is serialized without decimal point + data = { + 'lengthCm': 3 + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (banana.Banana,), True) + self.assertTrue(isinstance(deserialized, banana.Banana)) + self.assertEqual(deserialized.length_cm, 3.0) + + def test_deserialize_fruit_null_value(self): + """ + deserialize fruit with null value. + fruitReq is a oneOf composed schema model with discriminator, including 'null' type. + """ + + # Unmarshal 'null' value + data = None + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (fruit_req.FruitReq, type(None)), True) + self.assertEqual(type(deserialized), type(None)) + + inst = fruit_req.FruitReq(None) + self.assertIsNone(inst) + + def test_deserialize_with_additional_properties(self): + """ + Deserialize data with schemas that have the additionalProperties keyword. + Test conditions when additional properties are allowed, not allowed, have + specific types... + """ + + # Dog is allOf with two child schemas. + # The OAS document for Dog does not specify the 'additionalProperties' keyword, + # which means that by default, the Dog schema must allow undeclared properties. + # The additionalProperties keyword is used to control the handling of extra stuff, + # that is, properties whose names are not listed in the properties keyword. + # By default any additional properties are allowed. + data = { + 'className': 'Dog', + 'color': 'brown', + 'breed': 'golden retriever', + # Below are additional, undeclared properties. + 'group': 'Terrier Group', + 'size': 'medium', + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (dog.Dog,), True) + self.assertEqual(type(deserialized), dog.Dog) + self.assertEqual(deserialized.class_name, 'Dog') + self.assertEqual(deserialized.breed, 'golden retriever') + + # The 'zebra' schema allows additional properties by explicitly setting + # additionalProperties: true. + # This is equivalent to 'additionalProperties' not being present. + data = { + 'class_name': 'zebra', + 'type': 'plains', + # Below are additional, undeclared properties + 'group': 'abc', + 'size': 3, + 'p1': True, + 'p2': [ 'a', 'b', 123], + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (mammal.Mammal,), True) + self.assertEqual(type(deserialized), zebra.Zebra) + self.assertEqual(deserialized.class_name, 'zebra') + self.assertEqual(deserialized.type, 'plains') + self.assertEqual(deserialized.p1, True) + + # The 'bananaReq' schema disallows additional properties by explicitly setting + # additionalProperties: false + err_msg = ("{} has no attribute '{}' at ") + with self.assertRaisesRegex( + petstore_api.exceptions.ApiAttributeError, + err_msg.format("BananaReq", "unknown-group") + ): + data = { + 'lengthCm': 21.2, + 'sweet': False, + # Below are additional, undeclared properties. They are not allowed, + # an exception must be raised. + 'unknown-group': 'abc', + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (banana_req.BananaReq,), True) + self.assertEqual(type(deserialized), banana_req.BananaReq) + self.assertEqual(deserialized.lengthCm, 21) + self.assertEqual(deserialized.p1, True) + + def test_deserialize_with_additional_properties_and_reference(self): + """ + Deserialize data with schemas that has the additionalProperties keyword + and the schema is specified as a reference ($ref). + """ + data = { + 'main_shape': { + 'shape_type': 'Triangle', + 'triangle_type': 'EquilateralTriangle', + }, + 'shapes': [ + { + 'shape_type': 'Triangle', + 'triangle_type': 'IsoscelesTriangle', + }, + { + 'shape_type': 'Quadrilateral', + 'quadrilateral_type': 'ComplexQuadrilateral', + }, + ], + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (drawing.Drawing,), True) + + def test_deserialize_NumberWithValidations(self): + """ deserialize NumberWithValidations """ + # make sure that an exception is thrown on an invalid type value + with self.assertRaises(petstore_api.ApiTypeError): + self.deserialize( + MockResponse(data=json.dumps("test str")), + (number_with_validations.NumberWithValidations,), + True + ) + + # make sure that an exception is thrown on an invalid value + with self.assertRaises(petstore_api.ApiValueError): + self.deserialize( + MockResponse(data=json.dumps(21.0)), + (number_with_validations.NumberWithValidations,), + True + ) + + # valid value works + number_val = 11.0 + response = MockResponse(data=json.dumps(number_val)) + number = self.deserialize(response, + (number_with_validations.NumberWithValidations,), True) + self.assertTrue(isinstance(number, number_with_validations.NumberWithValidations)) + self.assertTrue(number.value == number_val) \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_discard_unknown_properties.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_discard_unknown_properties.py new file mode 100644 index 0000000000..ed1ca736d4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_discard_unknown_properties.py @@ -0,0 +1,173 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ docker pull swaggerapi/petstore +$ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore +$ pip install nose (optional) +$ cd petstore_api-python +$ nosetests -v +""" +from collections import namedtuple +import json +import re +import unittest + +import petstore_api +from petstore_api.model import cat, dog, isosceles_triangle, banana_req, fruit_req +from petstore_api import Configuration, signing + +from petstore_api.model_utils import ( + file_type, + model_to_dict, +) + +MockResponse = namedtuple('MockResponse', 'data') + +class DiscardUnknownPropertiesTests(unittest.TestCase): + + def test_deserialize_banana_req_do_not_discard_unknown_properties(self): + """ + deserialize bananaReq with unknown properties. + Strict validation is enabled. + Simple (non-composed) schema scenario. + """ + config = Configuration(discard_unknown_keys=False) + api_client = petstore_api.ApiClient(config) + data = { + 'lengthCm': 21.3, + 'sweet': False, + # Below is an unknown property not explicitly declared in the OpenAPI document. + # It should not be in the payload because additional properties (undeclared) are + # not allowed in the bananaReq schema (additionalProperties: false). + 'unknown_property': 'a-value' + } + response = MockResponse(data=json.dumps(data)) + + # Deserializing with strict validation raises an exception because the 'unknown_property' + # is undeclared. + with self.assertRaises(petstore_api.exceptions.ApiAttributeError) as cm: + deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True) + self.assertTrue(re.match("BananaReq has no attribute 'unknown_property' at.*", str(cm.exception)), + 'Exception message: {0}'.format(str(cm.exception))) + + + def test_deserialize_fruit_req_do_not_discard_unknown_properties(self): + """ + deserialize FruitReq with unknown properties. + Strict validation is enabled. + Composed schema scenario. + """ + config = Configuration(discard_unknown_keys=False) + api_client = petstore_api.ApiClient(config) + data = { + 'lengthCm': 21.3, + 'sweet': False, + # Below is an unknown property not explicitly declared in the OpenAPI document. + # It should not be in the payload because additional properties (undeclared) are + # not allowed in the schema (additionalProperties: false). + 'unknown_property': 'a-value' + } + response = MockResponse(data=json.dumps(data)) + + # Deserializing with strict validation raises an exception because the 'unknown_property' + # is undeclared. + with self.assertRaisesRegex(petstore_api.ApiValueError, "Invalid inputs given to generate an instance of FruitReq. None of the oneOf schemas matched the input data."): + deserialized = api_client.deserialize(response, ((fruit_req.FruitReq),), True) + + + def test_deserialize_fruit_req_discard_unknown_properties(self): + """ + deserialize FruitReq with unknown properties. + Strict validation is enabled. + Composed schema scenario. + """ + config = Configuration(discard_unknown_keys=True) + api_client = petstore_api.ApiClient(config) + data = { + 'lengthCm': 21.3, + 'sweet': False, + # Below is an unknown property not explicitly declared in the OpenAPI document. + # It should not be in the payload because additional properties (undeclared) are + # not allowed in BananaReq + 'unknown_property': 'a-value' + } + response = MockResponse(data=json.dumps(data)) + deserialized = api_client.deserialize(response, ((fruit_req.FruitReq),), True) + self.assertNotIn("unknown_property", deserialized.to_dict().keys()) + + + def test_deserialize_banana_req_discard_unknown_properties(self): + """ + Deserialize bananaReq with unknown properties. + Discard unknown properties. + """ + config = Configuration(discard_unknown_keys=True) + api_client = petstore_api.ApiClient(config) + data = { + 'lengthCm': 21.3, + 'sweet': False, + # Below are additional (undeclared) properties not specified in the bananaReq schema. + 'unknown_property': 'a-value', + 'more-unknown': [ + 'a' + ] + } + # The 'unknown_property' is undeclared, which would normally raise an exception, but + # when discard_unknown_keys is set to True, the unknown properties are discarded. + response = MockResponse(data=json.dumps(data)) + deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True) + self.assertTrue(isinstance(deserialized, banana_req.BananaReq)) + # Check the 'unknown_property' and 'more-unknown' properties are not present in the + # output. + self.assertIn("length_cm", deserialized.to_dict().keys()) + self.assertNotIn("unknown_property", deserialized.to_dict().keys()) + self.assertNotIn("more-unknown", deserialized.to_dict().keys()) + + def test_deserialize_cat_do_not_discard_unknown_properties(self): + """ + Deserialize Cat with unknown properties. + Strict validation is enabled. + """ + config = Configuration(discard_unknown_keys=False) + api_client = petstore_api.ApiClient(config) + data = { + "class_name": "Cat", + "color": "black", + "declawed": True, + "dynamic-property": 12345, + } + response = MockResponse(data=json.dumps(data)) + + # Deserializing with strict validation does not raise an exception because the even though + # the 'dynamic-property' is undeclared, the 'Cat' schema defines the additionalProperties + # attribute. + deserialized = api_client.deserialize(response, ((cat.Cat),), True) + self.assertTrue(isinstance(deserialized, cat.Cat)) + self.assertIn('color', deserialized.to_dict()) + self.assertEqual(deserialized['color'], 'black') + + def test_deserialize_cat_discard_unknown_properties(self): + """ + Deserialize Cat with unknown properties. + Request to discard unknown properties, but Cat is composed schema + with one inner schema that has 'additionalProperties' set to true. + """ + config = Configuration(discard_unknown_keys=True) + api_client = petstore_api.ApiClient(config) + data = { + "class_name": "Cat", + "color": "black", + "declawed": True, + # Below are additional (undeclared) properties. + "my_additional_property": 123, + } + # The 'my_additional_property' is undeclared + response = MockResponse(data=json.dumps(data)) + deserialized = api_client.deserialize(response, ((cat.Cat),), True) + self.assertTrue(isinstance(deserialized, cat.Cat)) + # Check the 'my_additional_property' is present + self.assertIn("my_additional_property", deserialized.to_dict().keys()) + diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_drawing.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_drawing.py new file mode 100644 index 0000000000..327e01fb84 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_drawing.py @@ -0,0 +1,170 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import nullable_shape +except ImportError: + nullable_shape = sys.modules[ + 'petstore_api.model.nullable_shape'] +try: + from petstore_api.model import shape +except ImportError: + shape = sys.modules[ + 'petstore_api.model.shape'] +try: + from petstore_api.model import shape_or_null +except ImportError: + shape_or_null = sys.modules[ + 'petstore_api.model.shape_or_null'] +from petstore_api.model.drawing import Drawing + + +class TestDrawing(unittest.TestCase): + """Drawing unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_create_instances(self): + """ + Validate instance can be created using pythonic name or OAS names. + """ + + # Validate object can be created using pythonic names. + inst = shape.Shape( + shape_type="Triangle", + triangle_type="IsoscelesTriangle" + ) + from petstore_api.model.isosceles_triangle import IsoscelesTriangle + assert isinstance(inst, IsoscelesTriangle) + + # Validate object can be created using OAS names. + # For example, this can be used to construct objects on the client + # when the input data is available as JSON documents. + data = { + 'shapeType': "Triangle", + 'triangleType': "IsoscelesTriangle" + } + inst = shape.Shape(_spec_property_naming=True, **data) + assert isinstance(inst, IsoscelesTriangle) + + def test_deserialize_oneof_reference(self): + """ + Validate the scenario when the type of a OAS property is 'oneOf', and the 'oneOf' + schema is specified as a reference ($ref), not an inline 'oneOf' schema. + """ + isosceles_triangle = shape.Shape( + shape_type="Triangle", + triangle_type="IsoscelesTriangle" + ) + from petstore_api.model.isosceles_triangle import IsoscelesTriangle + from petstore_api.model.triangle import Triangle + from petstore_api.model.equilateral_triangle import EquilateralTriangle + + assert isinstance(isosceles_triangle, IsoscelesTriangle) + inst = Drawing( + # 'main_shape' has type 'Shape', which is a oneOf [triangle, quadrilateral] + # composed schema. So we should be able to assign a petstore_api.Triangle + # to a 'main_shape'. + main_shape=isosceles_triangle, + shapes=[ + shape.Shape( + shape_type="Triangle", + triangle_type="EquilateralTriangle" + ), + Triangle( + shape_type="Triangle", + triangle_type="IsoscelesTriangle" + ), + EquilateralTriangle( + shape_type="Triangle", + triangle_type="EquilateralTriangle" + ), + shape.Shape( + shape_type="Quadrilateral", + quadrilateral_type="ComplexQuadrilateral" + ), + ], + ) + from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral + assert isinstance(inst, Drawing) + assert isinstance(inst.main_shape, IsoscelesTriangle) + self.assertEqual(len(inst.shapes), 4) + assert isinstance(inst.shapes[0], EquilateralTriangle) + assert isinstance(inst.shapes[1], IsoscelesTriangle) + assert isinstance(inst.shapes[2], EquilateralTriangle) + assert isinstance(inst.shapes[3], ComplexQuadrilateral) + + # Validate we cannot assign the None value to main_shape because the 'null' type + # is not one of the allowed types in the 'Shape' schema. + err_msg = (r"Invalid type for variable '{}'. " + r"Required value type is {} and passed type was {} at {}") + with self.assertRaisesRegex( + petstore_api.ApiTypeError, + err_msg.format(r"main_shape", r"one of \[ComplexQuadrilateral, EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle, SimpleQuadrilateral\]", r"NoneType", r"\['main_shape'\]") + ): + inst = Drawing( + # 'main_shape' has type 'Shape', which is a oneOf [triangle, quadrilateral] + # So the None value should not be allowed and an exception should be raised. + main_shape=None, + ) + + + def test_deserialize_oneof_reference_with_null_type(self): + """ + Validate the scenario when the type of a OAS property is 'oneOf', and the 'oneOf' + schema is specified as a reference ($ref), not an inline 'oneOf' schema. + Further, the 'oneOf' schema has a 'null' type child schema (as introduced in + OpenAPI 3.1). + """ + + # Validate we can assign the None value to shape_or_null, because the 'null' type + # is one of the allowed types in the 'ShapeOrNull' schema. + inst = Drawing( + # 'shape_or_null' has type 'ShapeOrNull', which is a oneOf [null, triangle, quadrilateral] + shape_or_null=None, + ) + assert isinstance(inst, Drawing) + self.assertFalse(hasattr(inst, 'main_shape')) + self.assertTrue(hasattr(inst, 'shape_or_null')) + self.assertIsNone(inst.shape_or_null) + + + def test_deserialize_oneof_reference_with_nullable_type(self): + """ + Validate the scenario when the type of a OAS property is 'oneOf', and the 'oneOf' + schema is specified as a reference ($ref), not an inline 'oneOf' schema. + Further, the 'oneOf' schema has the 'nullable' attribute (as introduced in + OpenAPI 3.0 and deprecated in 3.1). + """ + + # Validate we can assign the None value to nullable_shape, because the NullableShape + # has the 'nullable: true' attribute. + inst = Drawing( + # 'nullable_shape' has type 'NullableShape', which is a oneOf [triangle, quadrilateral] + # and the 'nullable: true' attribute. + nullable_shape=None, + ) + assert isinstance(inst, Drawing) + self.assertFalse(hasattr(inst, 'main_shape')) + self.assertTrue(hasattr(inst, 'nullable_shape')) + self.assertIsNone(inst.nullable_shape) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_enum_test.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_enum_test.py similarity index 100% rename from samples/openapi3/client/petstore/python/tests_manual/test_enum_test.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/test_enum_test.py diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_extra_pool_config_options.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_extra_pool_config_options.py similarity index 93% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_extra_pool_config_options.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/test_extra_pool_config_options.py index 5bf6b989eb..9e49b9e71b 100644 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_extra_pool_config_options.py +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_extra_pool_config_options.py @@ -48,9 +48,9 @@ class TestExtraOptionsForPools(unittest.TestCase): socket_options = ["extra", "socket", "options"] - config = petstore_api.Configuration(host="HOST") + config = petstore_api.Configuration(host="http://somehost.local:8080") config.socket_options = socket_options - config.proxy = True + config.proxy = "http://proxy.local:8080/" with patch("petstore_api.rest.urllib3.ProxyManager", StubProxyManager): api_client = petstore_api.ApiClient(config) diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_fake_api.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_fake_api.py new file mode 100644 index 0000000000..12e391238e --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_fake_api.py @@ -0,0 +1,785 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import sys +from collections import namedtuple +import os +import json +import unittest +from unittest.mock import patch + +import petstore_api +from petstore_api.api.fake_api import FakeApi # noqa: E501 +from petstore_api.rest import RESTClientObject, RESTResponse +from petstore_api.model_utils import file_type, model_to_dict + +HTTPResponse = namedtuple( + 'urllib3_response_HTTPResponse', + ['status', 'reason', 'data', 'getheaders', 'getheader'] +) + +headers = {'Content-Type': 'application/json'} +def get_headers(): + return {} +def get_header(name, default=None): + return {}.get(name, default) + + +class TestFakeApi(unittest.TestCase): + """FakeApi unit test stubs""" + + def setUp(self): + self.api = FakeApi() # noqa: E501 + + def tearDown(self): + pass + + @staticmethod + def mock_response(body_value): + http_response = HTTPResponse( + status=200, + reason='OK', + data=json.dumps(body_value).encode('utf-8'), + getheaders=get_headers, + getheader=get_header + ) + return RESTResponse(http_response) + + @staticmethod + def assert_request_called_with( + mock_method, + url, + accept='application/json', + http_method='POST', + content_type='application/json', + **kwargs + ): + headers = { + 'Accept': accept, + 'User-Agent': 'OpenAPI-Generator/1.0.0/python', + } + if content_type: + headers['Content-Type'] = content_type + used_kwargs = dict( + _preload_content=True, + _request_timeout=None, + headers=headers, + query_params=[] + ) + if 'post_params' in kwargs: + used_kwargs['post_params'] = kwargs['post_params'] + if 'body' in kwargs: + used_kwargs['body'] = kwargs['body'] + if 'post_params' not in used_kwargs: + used_kwargs['post_params'] = [] + mock_method.assert_called_with( + http_method, + url, + **used_kwargs + ) + + def test_array_model(self): + """Test case for array_model + + """ + from petstore_api.model import animal_farm, animal + endpoint = self.api.array_model_endpoint + assert endpoint.openapi_types['body'] == (animal_farm.AnimalFarm,) + assert endpoint.settings['response_type'] == (animal_farm.AnimalFarm,) + + # serialization + deserialization works + with patch.object(RESTClientObject, 'request') as mock_method: + cat = animal.Animal(class_name="Cat", color="black") + body = animal_farm.AnimalFarm([cat]) + json_data = [{"className": "Cat", "color": "black"}] + mock_method.return_value = self.mock_response(json_data) + + response = self.api.array_model(body=body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', + body=json_data, + ) + + assert isinstance(response, animal_farm.AnimalFarm) + assert response == body + + def test_boolean(self): + """Test case for boolean + + """ + endpoint = self.api.boolean_endpoint + assert endpoint.openapi_types['body'] == (bool,) + assert endpoint.settings['response_type'] == (bool,) + + def test_recursionlimit(self): + """Test case for recursionlimit + + """ + assert sys.getrecursionlimit() == 1234 + + def test_fake_health_get(self): + """Test case for fake_health_get + + Health check endpoint # noqa: E501 + """ + pass + + def test_additional_properties_with_array_of_enums(self): + """Test case for additional_properties_with_array_of_enums + + Additional Properties with Array of Enums # noqa: E501 + """ + pass + + def test_enum_test(self): + """Test case for enum_test + + Object contains enum properties and array properties containing enums + """ + from petstore_api.model.enum_test import EnumTest + from petstore_api.model.string_enum import StringEnum + from petstore_api.model.array_of_enums import ArrayOfEnums + + endpoint = self.api.enum_test_endpoint + assert endpoint.openapi_types['enum_test'] == (EnumTest,) + assert endpoint.settings['response_type'] == (EnumTest,) + + # serialization + deserialization works w/ inline array + with patch.object(RESTClientObject, 'request') as mock_method: + body = EnumTest( + enum_string_required='lower', + inline_array_of_str_enum=[StringEnum('approved')] + ) + json_value = {'enum_string_required': 'lower', 'InlineArrayOfStrEnum': ['approved']} + mock_method.return_value = self.mock_response(json_value) + + response = self.api.enum_test(enum_test=body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', + body=json_value, + ) + + assert isinstance(response, EnumTest) + assert response == body + + # serialization + deserialization works w/ refed array + with patch.object(RESTClientObject, 'request') as mock_method: + body = EnumTest( + enum_string_required='lower', + array_of_str_enum=ArrayOfEnums([StringEnum('approved')]) + ) + json_value = {'enum_string_required': 'lower', 'ArrayOfStrEnum': ['approved']} + mock_method.return_value = self.mock_response(json_value) + + response = self.api.enum_test(enum_test=body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', + body=json_value, + ) + + assert isinstance(response, EnumTest) + assert response == body + + + def test_array_of_enums(self): + """Test case for array_of_enums + + Array of Enums # noqa: E501 + """ + from petstore_api.model import array_of_enums, string_enum + endpoint = self.api.array_of_enums_endpoint + assert endpoint.openapi_types['array_of_enums'] == (array_of_enums.ArrayOfEnums,) + assert endpoint.settings['response_type'] == (array_of_enums.ArrayOfEnums,) + + # serialization + deserialization works + with patch.object(RESTClientObject, 'request') as mock_method: + value = [string_enum.StringEnum("placed")] + body = array_of_enums.ArrayOfEnums(value) + value_simple = ["placed"] + mock_method.return_value = self.mock_response(value_simple) + + response = self.api.array_of_enums(array_of_enums=body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', + body=value_simple, + ) + + assert isinstance(response, array_of_enums.ArrayOfEnums) + assert response.value == value + + def test_number_with_validations(self): + """Test case for number_with_validations + + """ + from petstore_api.model import number_with_validations + endpoint = self.api.number_with_validations_endpoint + assert endpoint.openapi_types['body'] == (number_with_validations.NumberWithValidations,) + assert endpoint.settings['response_type'] == (number_with_validations.NumberWithValidations,) + + # serialization + deserialization works + with patch.object(RESTClientObject, 'request') as mock_method: + value = 10.0 + body = number_with_validations.NumberWithValidations(value) + mock_method.return_value = self.mock_response(value) + + response = self.api.number_with_validations(body=body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/number', + body=value, + ) + + assert isinstance(response, number_with_validations.NumberWithValidations) + assert response.value == value + + def test_object_model_with_ref_props(self): + """Test case for object_model_with_ref_props + + """ + from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps + from petstore_api.model.number_with_validations import NumberWithValidations + endpoint = self.api.object_model_with_ref_props_endpoint + assert endpoint.openapi_types['body'] == (ObjectModelWithRefProps,) + assert endpoint.settings['response_type'] == (ObjectModelWithRefProps,) + + json_payloads = [ + {}, # only required + no optional properties works + { # optional properties works + "my_number": 11.0, + "my_string": 'a', + "my_boolean": True, + } + ] + # instantiation works + expected_models = [ + ObjectModelWithRefProps(), + ObjectModelWithRefProps( + my_number=NumberWithValidations(11.0), + my_string='a', + my_boolean=True + ) + ] + + pairs = zip(json_payloads, expected_models) + # serialization + deserialization works + for (json_payload, expected_model) in pairs: + with patch.object(RESTClientObject, 'request') as mock_method: + mock_method.return_value = self.mock_response(json_payload) + + response = self.api.object_model_with_ref_props(body=expected_model) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/object_model_with_ref_props', + body=json_payload, + ) + + assert isinstance(response, expected_model.__class__) + assert response == expected_model + + def test_composed_one_of_number_with_validations(self): + """Test case for composed_one_of_number_with_validations + + """ + from petstore_api.model import animal, composed_one_of_number_with_validations, number_with_validations + endpoint = self.api.composed_one_of_number_with_validations_endpoint + assert endpoint.openapi_types['composed_one_of_number_with_validations'] == ( + composed_one_of_number_with_validations.ComposedOneOfNumberWithValidations,) + assert endpoint.settings['response_type'] == ( + composed_one_of_number_with_validations.ComposedOneOfNumberWithValidations,) + + # serialization + deserialization works + num_with_validations = number_with_validations.NumberWithValidations(10.0) + cat_in_composed = composed_one_of_number_with_validations.ComposedOneOfNumberWithValidations( + class_name="Cat", color="black" + ) + import datetime + date = datetime.date(1970, 1, 1) + body_value_simple = [ + (num_with_validations, 10.0), + (cat_in_composed, {"className": "Cat", "color": "black"}), + (None, None), + (date, '1970-01-01'), + ] + for (body, value_simple) in body_value_simple: + with patch.object(RESTClientObject, 'request') as mock_method: + mock_method.return_value = self.mock_response(value_simple) + + response = self.api.composed_one_of_number_with_validations(composed_one_of_number_with_validations=body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', + body=value_simple, + ) + + assert isinstance(response, body.__class__) + assert response == body + + def test_string(self): + """Test case for string + + """ + endpoint = self.api.string_endpoint + assert endpoint.openapi_types['body'] == (str,) + assert endpoint.settings['response_type'] == (str,) + + # serialization + deserialization works + with patch.object(RESTClientObject, 'request') as mock_method: + body = "blah" + value_simple = body + mock_method.return_value = self.mock_response(value_simple) + + response = self.api.string(body=body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/string', + body=value_simple, + ) + + assert isinstance(response, str) + assert response == value_simple + + def test_string_enum(self): + """Test case for string_enum + + """ + from petstore_api.model import string_enum + endpoint = self.api.string_enum_endpoint + assert endpoint.openapi_types['body'] == (string_enum.StringEnum,) + assert endpoint.settings['response_type'] == (string_enum.StringEnum,) + + # serialization + deserialization works + from petstore_api.rest import RESTClientObject, RESTResponse + with patch.object(RESTClientObject, 'request') as mock_method: + value = "placed" + body = string_enum.StringEnum(value) + mock_method.return_value = self.mock_response(value) + + response = self.api.string_enum(body=body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/enum', + body=value, + ) + + assert isinstance(response, string_enum.StringEnum) + assert response.value == value + + def test_upload_file(self): + # uploads a file + test_file_dir = os.path.realpath( + os.path.join(os.path.dirname(__file__), "..", "testfiles")) + file_path1 = os.path.join(test_file_dir, "1px_pic1.png") + + headers = {} + def get_headers(): + return headers + def get_header(name, default=None): + return headers.get(name, default) + api_respponse = { + 'code': 200, + 'type': 'blah', + 'message': 'file upload succeeded' + } + http_response = HTTPResponse( + status=200, + reason='OK', + data=json.dumps(api_respponse).encode('utf-8'), + getheaders=get_headers, + getheader=get_header + ) + mock_response = RESTResponse(http_response) + file1 = open(file_path1, "rb") + try: + with patch.object(RESTClientObject, 'request') as mock_method: + mock_method.return_value = mock_response + res = self.api.upload_file( + file=file1) + body = None + post_params=[ + ('file', ('1px_pic1.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')), + ] + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/uploadFile', + body=body, post_params=post_params, content_type='multipart/form-data' + ) + except petstore_api.ApiException as e: + self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + finally: + file1.close() + + # passing in an array of files to when file only allows one + # raises an exceptions + try: + file = open(file_path1, "rb") + with self.assertRaises(petstore_api.ApiTypeError) as exc: + self.api.upload_file(file=[file]) + finally: + file.close() + + # passing in a closed file raises an exception + with self.assertRaises(petstore_api.ApiValueError) as exc: + file = open(file_path1, "rb") + file.close() + self.api.upload_file(file=file) + + def test_upload_files(self): + test_file_dir = os.path.realpath( + os.path.join(os.path.dirname(__file__), "..", "testfiles")) + file_path1 = os.path.join(test_file_dir, "1px_pic1.png") + file_path2 = os.path.join(test_file_dir, "1px_pic2.png") + + headers = {} + def get_headers(): + return headers + def get_header(name, default=None): + return headers.get(name, default) + api_respponse = { + 'code': 200, + 'type': 'blah', + 'message': 'file upload succeeded' + } + http_response = HTTPResponse( + status=200, + reason='OK', + data=json.dumps(api_respponse).encode('utf-8'), + getheaders=get_headers, + getheader=get_header + ) + mock_response = RESTResponse(http_response) + file1 = open(file_path1, "rb") + file2 = open(file_path2, "rb") + try: + with patch.object(RESTClientObject, 'request') as mock_method: + mock_method.return_value = mock_response + res = self.api.upload_files( + files=[file1, file2]) + post_params=[ + ('files', ('1px_pic1.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')), + ('files', ('1px_pic2.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')) + ] + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/uploadFiles', + body=None, post_params=post_params, content_type='multipart/form-data' + ) + except petstore_api.ApiException as e: + self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + finally: + file1.close() + file2.close() + + # passing in a single file when an array of file is required + # raises an exception + try: + file = open(file_path1, "rb") + with self.assertRaises(petstore_api.ApiTypeError) as exc: + self.api.upload_files(files=file) + finally: + file.close() + + def test_download_attachment(self): + """Ensures that file deserialization works""" + + # sample from http://www.jtricks.com/download-text + file_name = 'content.txt' + headers_dict = { + 'with_filename': {'Content-Disposition': 'attachment; filename={}'.format(file_name), 'Content-Type': 'text/plain'}, + 'no_filename': {'Content-Disposition': 'attachment;', 'Content-Type': 'text/plain'} + } + def get_headers(*args): + return args + file_data = ( + "You are reading text file that was supposed to be downloaded\r\n" + "to your hard disk. If your browser offered to save you the file," + "\r\nthen it handled the Content-Disposition header correctly." + ) + for key, headers in headers_dict.items(): + def get_header(name, default=None): + return headers_dict[key].get(name, default) + http_response = HTTPResponse( + status=200, + reason='OK', + data=file_data, + getheaders=get_headers(headers), + getheader=get_header + ) + # deserialize response to a file + mock_response = RESTResponse(http_response) + with patch.object(RESTClientObject, 'request') as mock_method: + mock_method.return_value = mock_response + try: + file_object = self.api.download_attachment(file_name='download-text') + self.assert_request_called_with( + mock_method, + 'http://www.jtricks.com/download-text', + http_method='GET', + accept='text/plain', + content_type=None, + ) + self.assertTrue(isinstance(file_object, file_type)) + self.assertFalse(file_object.closed) + self.assertEqual(file_object.read(), file_data.encode('utf-8')) + finally: + file_object.close() + os.unlink(file_object.name) + + def test_upload_download_file(self): + test_file_dir = os.path.realpath( + os.path.join(os.path.dirname(__file__), "..", "testfiles")) + file_path1 = os.path.join(test_file_dir, "1px_pic1.png") + + with open(file_path1, "rb") as f: + expected_file_data = f.read() + + headers = {'Content-Type': 'application/octet-stream'} + def get_headers(): + return headers + def get_header(name, default=None): + return headers.get(name, default) + http_response = HTTPResponse( + status=200, + reason='OK', + data=expected_file_data, + getheaders=get_headers, + getheader=get_header + ) + mock_response = RESTResponse(http_response) + file1 = open(file_path1, "rb") + try: + with patch.object(RESTClientObject, 'request') as mock_method: + mock_method.return_value = mock_response + downloaded_file = self.api.upload_download_file(body=file1) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', + body=expected_file_data, + content_type='application/octet-stream', + accept='application/octet-stream' + ) + + self.assertTrue(isinstance(downloaded_file, file_type)) + self.assertFalse(downloaded_file.closed) + self.assertEqual(downloaded_file.read(), expected_file_data) + except petstore_api.ApiException as e: + self.fail("upload_download_file() raised {0} unexpectedly".format(type(e))) + finally: + file1.close() + downloaded_file.close() + os.unlink(downloaded_file.name) + + def test_test_body_with_file_schema(self): + """Test case for test_body_with_file_schema + + """ + pass + + def test_test_body_with_query_params(self): + """Test case for test_body_with_query_params + + """ + pass + + def test_test_client_model(self): + """Test case for test_client_model + + To test \"client\" model # noqa: E501 + """ + pass + + def test_test_endpoint_parameters(self): + """Test case for test_endpoint_parameters + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + """ + pass + + def test_test_enum_parameters(self): + """Test case for test_enum_parameters + + To test enum parameters # noqa: E501 + """ + pass + + def test_test_group_parameters(self): + """Test case for test_group_parameters + + Fake endpoint to test group parameters (optional) # noqa: E501 + """ + pass + + def test_test_inline_additional_properties(self): + """Test case for test_inline_additional_properties + + test inline additionalProperties # noqa: E501 + """ + pass + + def test_test_json_form_data(self): + """Test case for test_json_form_data + + test json serialization of form data # noqa: E501 + """ + pass + + def test_test_query_parameter_collection_format(self): + """Test case for test_query_parameter_collection_format + + """ + pass + + def test_post_inline_additional_properties_ref_payload(self): + """Test case for postInlineAdditionlPropertiesRefPayload + """ + from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload + from petstore_api.model.post_inline_additional_properties_payload_request_array_data_inner import PostInlineAdditionalPropertiesPayloadRequestArrayDataInner + endpoint = self.api.post_inline_additional_properties_ref_payload_endpoint + assert endpoint.openapi_types['inline_additional_properties_ref_payload'] == (InlineAdditionalPropertiesRefPayload,) + assert endpoint.settings['response_type'] == (InlineAdditionalPropertiesRefPayload,) + + # serialization + deserialization works + from petstore_api.rest import RESTClientObject, RESTResponse + with patch.object(RESTClientObject, 'request') as mock_method: + expected_json_body = { + 'arrayData': [ + { + 'labels': [ + None, + 'foo' + ] + } + ] + } + inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( + array_data=[ + PostInlineAdditionalPropertiesPayloadRequestArrayDataInner(labels=[None, 'foo']) + ] + ) + mock_method.return_value = self.mock_response(expected_json_body) + + response = self.api.post_inline_additional_properties_ref_payload(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/postInlineAdditionalPropertiesRefPayload', + body=expected_json_body + ) + + assert isinstance(response, InlineAdditionalPropertiesRefPayload) + assert model_to_dict(response) == expected_json_body + + def test_post_inline_additional_properties_payload(self): + """Test case for postInlineAdditionlPropertiesPayload + """ + from petstore_api.model.post_inline_additional_properties_payload_request import PostInlineAdditionalPropertiesPayloadRequest + from petstore_api.model.post_inline_additional_properties_payload_request_array_data_inner import PostInlineAdditionalPropertiesPayloadRequestArrayDataInner + endpoint = self.api.post_inline_additional_properties_payload_endpoint + assert endpoint.openapi_types['post_inline_additional_properties_payload_request'] == (PostInlineAdditionalPropertiesPayloadRequest,) + assert endpoint.settings['response_type'] == (PostInlineAdditionalPropertiesPayloadRequest,) + + # serialization + deserialization works + from petstore_api.rest import RESTClientObject, RESTResponse + with patch.object(RESTClientObject, 'request') as mock_method: + expected_json_body = { + 'arrayData': [ + { + 'labels': [ + None, + 'foo' + ] + } + ] + } + post_inline_additional_properties_payload_request = PostInlineAdditionalPropertiesPayloadRequest( + array_data=[ + PostInlineAdditionalPropertiesPayloadRequestArrayDataInner(labels=[None, 'foo']) + ] + ) + mock_method.return_value = self.mock_response(expected_json_body) + + response = self.api.post_inline_additional_properties_payload(post_inline_additional_properties_payload_request=post_inline_additional_properties_payload_request) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/postInlineAdditionalPropertiesPayload', + body=expected_json_body + ) + + assert isinstance(response, PostInlineAdditionalPropertiesPayloadRequest) + assert model_to_dict(response) == expected_json_body + + def test_post_tx_rx_any_of_payload(self): + """Test case for postInlineAdditionlPropertiesPayload + """ + from petstore_api.model.gm_fruit_no_properties import GmFruitNoProperties + endpoint = self.api.tx_rx_any_of_model_endpoint + assert endpoint.openapi_types['gm_fruit_no_properties'] == (GmFruitNoProperties,) + assert endpoint.settings['response_type'] == (GmFruitNoProperties,) + + # serialization + deserialization works + from petstore_api.rest import RESTClientObject, RESTResponse + with patch.object(RESTClientObject, 'request') as mock_method: + expected_json_body = { + 'cultivar': 'Alice', + 'origin': 'Kazakhstan', + 'lengthCm': 7, + } + fruit = GmFruitNoProperties(**expected_json_body) + mock_method.return_value = self.mock_response(expected_json_body) + + response = self.api.tx_rx_any_of_model(gm_fruit_no_properties=fruit) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/TxRxAnyOfModel', + body=expected_json_body + ) + + assert isinstance(response, GmFruitNoProperties) + assert model_to_dict(response) == expected_json_body + + def test_post_tx_rx_all_of_payload(self): + """Test case for postInlineAdditionlPropertiesPayload + """ + from petstore_api.model.stream_options import StreamOptions + from petstore_api.model.publish_options_publish import PublishOptionsPublish + endpoint = self.api.tx_rx_all_of_model_endpoint + assert endpoint.openapi_types['stream_options'] == (StreamOptions,) + assert endpoint.settings['response_type'] == (StreamOptions,) + + # serialization + deserialization works + from petstore_api.rest import RESTClientObject, RESTResponse + with patch.object(RESTClientObject, 'request') as mock_method: + expected_json_body = { + "egressThresholds": { + "person":0.8 + }, + "publish": { + "egressUnknownDetections": False + } + } + stream_option_instance = StreamOptions(**expected_json_body) + mock_method.return_value = self.mock_response(expected_json_body) + + response = self.api.tx_rx_all_of_model(stream_options=stream_option_instance) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/TxRxAllOfModel', + body=expected_json_body + ) + + assert isinstance(response, StreamOptions) + assert model_to_dict(response) == expected_json_body + assert response.publish == PublishOptionsPublish(**{"egress_unknown_detections": False}) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_fruit.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_fruit.py new file mode 100644 index 0000000000..a0f97a4a97 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_fruit.py @@ -0,0 +1,247 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model import apple +from petstore_api.model import banana +from petstore_api.model.fruit import Fruit + + +class TestFruit(unittest.TestCase): + """Fruit unit test stubs""" + + length_cm = 20.3 + color = 'yellow' + + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_fruit_with_additional_props(self): + # including extra parameters works because the oneOf models include additionalProperties + some_value = 'some_value' + some_fruit = Fruit( + color=self.color, + length_cm=self.length_cm, + unknown_property=some_value + ) + assert some_fruit['unknown_property'] == some_value + + def test_fruit_assigning_additional_props_in_client(self): + # setting a value that doesn't exist works because additional_properties_type allows any type + other_fruit = Fruit(length_cm=self.length_cm, color=self.color) + blah = 'blah' + other_fruit['a'] = blah + assert other_fruit.a == blah + + # with setattr + setattr(other_fruit, 'b', blah) + assert other_fruit.b == blah + + self.assertEqual( + other_fruit.to_dict(), + { + 'a': 'blah', + 'b': 'blah', + 'length_cm': self.length_cm, + 'color': self.color + } + ) + + def test_fruit_access_errors(self): + fruit = Fruit(length_cm=self.length_cm, color=self.color) + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(AttributeError): + invalid_variable = fruit['cultivar'] + + # Per Python doc, if the named attribute does not exist, + # default is returned if provided, otherwise AttributeError is raised. + with self.assertRaises(AttributeError): + getattr(fruit, 'cultivar') + + def test_fruit_attribute_access(self): + fruit = Fruit(length_cm=self.length_cm, color=self.color) + + # Assert that we can call the builtin hasattr() function. + # hasattr should return False for non-existent attribute. + # Internally hasattr catches the AttributeError exception. + self.assertFalse(hasattr(fruit, 'invalid_variable')) + + # Assert that we can call the builtin hasattr() function. + # hasattr should return True for existent attribute. + self.assertTrue(hasattr(fruit, 'color')) + + # with getattr + # Per Python doc, if the named attribute does not exist, + # default is returned if provided. + self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value') + self.assertEqual(fruit.get('cultivar'), None) + self.assertEqual(fruit.get('cultivar', 'some value'), 'some value') + + def test_banana_fruit(self): + """Test Fruit""" + + # make an instance of Fruit, a composed schema oneOf model + # banana test + fruit = Fruit(length_cm=self.length_cm, color=self.color) + # check its properties + self.assertEqual(fruit.length_cm, self.length_cm) + self.assertEqual(fruit['length_cm'], self.length_cm) + self.assertEqual(fruit.get('length_cm'), self.length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) + self.assertEqual(fruit.color, self.color) + self.assertEqual(fruit['color'], self.color) + self.assertEqual(getattr(fruit, 'color'), self.color) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'length_cm': self.length_cm, + 'color': self.color + } + ) + + # make sure that the ModelComposed class properties are correct + # model._composed_schemas stores the anyOf/allOf/oneOf info + self.assertEqual( + fruit._composed_schemas, + { + 'anyOf': [], + 'allOf': [], + 'oneOf': [ + apple.Apple, + banana.Banana, + ], + } + ) + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas + self.assertEqual(len(fruit._composed_instances), 1) + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == banana.Banana: + banana_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [banana_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + print(fruit._var_name_to_model_instances) + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'length_cm': [fruit, banana_instance], + } + ) + self.assertEqual( + fruit._additional_properties_model_instances, [fruit] + ) + + # if we modify one of the properties owned by multiple + # model_instances we get an exception when we try to access that + # property because the retrieved values are not all the same + banana_instance.length_cm = 4.56 + with self.assertRaises(petstore_api.ApiValueError): + some_length_cm = fruit.length_cm + + # including input parameters for two oneOf instances raise an exception + with self.assertRaises(petstore_api.ApiValueError): + fruit = Fruit( + length_cm=self.length_cm, + cultivar='granny smith' + ) + + def test_apple_fruit(self): + + # make an instance of Fruit, a composed schema oneOf model + # apple test + color = 'red' + cultivar = 'golden delicious' + fruit = Fruit(color=color, cultivar=cultivar) + # check its properties + self.assertEqual(fruit.color, color) + self.assertEqual(fruit['color'], color) + self.assertEqual(getattr(fruit, 'color'), color) + self.assertEqual(fruit.cultivar, cultivar) + self.assertEqual(fruit['cultivar'], cultivar) + self.assertEqual(getattr(fruit, 'cultivar'), cultivar) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'color': color, + 'cultivar': cultivar + } + ) + + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == apple.Apple: + apple_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [apple_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'cultivar': [fruit, apple_instance], + } + ) + self.assertEqual( + fruit._additional_properties_model_instances, [fruit] + ) + + def test_null_fruit(self): + # Since 'apple' is nullable, validate we can create an apple with the 'null' value. + fruit = apple.Apple(None) + self.assertIsNone(fruit) + + # 'banana' is not nullable. + with self.assertRaises(petstore_api.ApiTypeError): + banana.Banana(None) + + # Since 'fruit' has oneOf 'apple', 'banana' and 'apple' is nullable, + # validate we can create a fruit with the 'null' value. + fruit = Fruit(None) + self.assertIsNone(fruit) + + # Redo the same thing, this time passing a null Apple to the Fruit constructor. + fruit = Fruit(apple.Apple(None)) + self.assertIsNone(fruit) + + def test_fruit_with_invalid_input_type(self): + + """ + color must be a str, color's str type is only defined at the Fruit level + Banana + Apple would allow color to be assigned with any type of value + """ + invalid_value = 1 + with self.assertRaises(petstore_api.ApiTypeError): + fruit = Fruit(color=invalid_value, length_cm=self.length_cm) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_fruit_req.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_fruit_req.py new file mode 100644 index 0000000000..64b710fdd5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_fruit_req.py @@ -0,0 +1,175 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model import apple_req +from petstore_api.model import banana_req +from petstore_api.model.fruit_req import FruitReq + + +class TestFruitReq(unittest.TestCase): + """FruitReq unit test stubs""" + length_cm = 20.3 + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_fruit_access_errors(self): + fruit = FruitReq(length_cm=self.length_cm) + + # setting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(AttributeError): + fruit['invalid_variable'] = 'some value' + # with setattr + with self.assertRaises(AttributeError): + setattr(fruit, 'invalid_variable', 'some value') + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(AttributeError): + invalid_variable = fruit['cultivar'] + + with self.assertRaises(AttributeError): + getattr(fruit, 'cultivar') + + def test_FruitReq_banana(self): + """Test FruitReq""" + + # make an instance of Fruit, a composed schema oneOf model + # banana test + fruit = FruitReq(length_cm=self.length_cm) + # check its properties + self.assertEqual(fruit.length_cm, self.length_cm) + self.assertEqual(fruit['length_cm'], self.length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'length_cm': self.length_cm, + } + ) + + # with getattr + self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value') + + # make sure that the ModelComposed class properties are correct + # model._composed_schemas stores the anyOf/allOf/oneOf info + self.assertEqual( + fruit._composed_schemas, + { + 'anyOf': [], + 'allOf': [], + 'oneOf': [ + apple_req.AppleReq, + banana_req.BananaReq, + type(None), + ], + } + ) + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == banana_req.BananaReq: + banana_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [banana_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'length_cm': [fruit, banana_instance], + } + ) + self.assertEqual( + fruit._additional_properties_model_instances, [fruit] + ) + + # if we modify one of the properties owned by multiple + # model_instances we get an exception when we try to access that + # property because the retrieved values are not all the same + banana_instance.length_cm = 4.56 + with self.assertRaises(petstore_api.ApiValueError): + some_length_cm = fruit.length_cm + + def test_invalid_inputs(self): + # including extra parameters raises an exception + with self.assertRaises(petstore_api.ApiValueError): + fruit = FruitReq( + length_cm=self.length_cm, + unknown_property='some value' + ) + + # including input parameters for two oneOf instances raise an exception + with self.assertRaises(petstore_api.ApiValueError): + fruit = FruitReq( + length_cm=self.length_cm, + cultivar='granny smith' + ) + + def test_FruitReq_apple(self): + """Test FruitReq""" + + # apple test + cultivar = 'golden delicious' + fruit = FruitReq(cultivar=cultivar) + # check its properties + self.assertEqual(fruit.cultivar, cultivar) + self.assertEqual(fruit['cultivar'], cultivar) + self.assertEqual(getattr(fruit, 'cultivar'), cultivar) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'cultivar': cultivar + } + ) + + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == apple_req.AppleReq: + apple_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [apple_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'cultivar': [fruit, apple_instance], + } + ) + self.assertEqual( + fruit._additional_properties_model_instances, [fruit] + ) + + def test_null_fruit(self): + # we can pass in None + fruit = FruitReq(None) + assert fruit is None + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_gm_fruit.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_gm_fruit.py new file mode 100644 index 0000000000..bbe105c59b --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_gm_fruit.py @@ -0,0 +1,217 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model import apple +from petstore_api.model import banana +from petstore_api.model.gm_fruit import GmFruit + + +class TestGmFruit(unittest.TestCase): + """GmFruit unit test stubs""" + length_cm = 20.3 + color = 'yellow' + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_set_addprop_attributes(self): + # setting a value that doesn't exist works because additional_properties_type allows any type + other_fruit = GmFruit(length_cm=self.length_cm, color=self.color) + blah = 'blah' + other_fruit['a'] = blah + assert other_fruit.a == blah + + # with setattr + setattr(other_fruit, 'b', blah) + assert other_fruit.b == blah + + self.assertEqual( + other_fruit.to_dict(), + { + 'a': 'blah', + 'b': 'blah', + 'length_cm': self.length_cm, + 'color': self.color + } + ) + + def test_banana_fruit(self): + """Test GmFruit""" + + # make an instance of GmFruit, a composed schema anyOf model + # banana test + fruit = GmFruit(length_cm=self.length_cm, color=self.color) + # check its properties + self.assertEqual(fruit.length_cm, self.length_cm) + self.assertEqual(fruit['length_cm'], self.length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) + self.assertEqual(fruit.color, self.color) + self.assertEqual(fruit['color'], self.color) + self.assertEqual(getattr(fruit, 'color'), self.color) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'length_cm': self.length_cm, + 'color': self.color + } + ) + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(AttributeError): + invalid_variable = fruit['cultivar'] + # with getattr + self.assertTrue(getattr(fruit, 'cultivar', 'some value'), 'some value') + + with self.assertRaises(AttributeError): + invalid_variable = getattr(fruit, 'cultivar') + + # make sure that the ModelComposed class properties are correct + # model._composed_schemas stores the anyOf/allOf/oneOf info + self.assertEqual( + fruit._composed_schemas, + { + 'anyOf': [ + apple.Apple, + banana.Banana, + ], + 'allOf': [], + 'oneOf': [], + } + ) + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == banana.Banana: + banana_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [banana_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'length_cm': [fruit, banana_instance], + } + ) + self.assertEqual( + fruit._additional_properties_model_instances, [fruit] + ) + + def test_combo_fruit(self): + # including input parameters for both anyOf instances works + cultivar = 'banaple' + color = 'orange' + fruit = GmFruit( + color=color, + cultivar=cultivar, + length_cm=self.length_cm + ) + self.assertEqual(fruit.color, color) + self.assertEqual(fruit['color'], color) + self.assertEqual(getattr(fruit, 'color'), color) + self.assertEqual(fruit.cultivar, cultivar) + self.assertEqual(fruit['cultivar'], cultivar) + self.assertEqual(getattr(fruit, 'cultivar'), cultivar) + self.assertEqual(fruit.length_cm, self.length_cm) + self.assertEqual(fruit['length_cm'], self.length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) + + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == apple.Apple: + apple_instance = composed_instance + elif composed_instance.__class__ == banana.Banana: + banana_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [apple_instance, banana_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'length_cm': [fruit, banana_instance], + 'cultivar': [fruit, apple_instance], + } + ) + self.assertEqual( + fruit._additional_properties_model_instances, [fruit] + ) + + def test_apple_fruit(self): + # apple test + color = 'red' + cultivar = 'golden delicious' + origin = 'California' + fruit = GmFruit(color=color, cultivar=cultivar, origin=origin) + # check its properties + self.assertEqual(fruit.color, color) + self.assertEqual(fruit['color'], color) + self.assertEqual(getattr(fruit, 'color'), color) + self.assertEqual(fruit.cultivar, cultivar) + self.assertEqual(fruit['cultivar'], cultivar) + self.assertEqual(getattr(fruit, 'cultivar'), cultivar) + + self.assertEqual(fruit.origin, origin) + self.assertEqual(fruit['origin'], origin) + self.assertEqual(getattr(fruit, 'origin'), origin) + + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'color': color, + 'cultivar': cultivar, + 'origin': origin, + } + ) + + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == apple.Apple: + apple_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [apple_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'cultivar': [fruit, apple_instance], + 'origin': [fruit, apple_instance], + } + ) + self.assertEqual( + fruit._additional_properties_model_instances, [fruit] + ) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_http_signature.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_http_signature.py new file mode 100644 index 0000000000..c6854d666c --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_http_signature.py @@ -0,0 +1,518 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ docker pull swaggerapi/petstore +$ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore +$ pip install nose (optional) +$ cd petstore_api-python +$ nosetests -v +""" + +from collections import namedtuple +from datetime import datetime, timedelta +import base64 +import json +import os +import re +import shutil +import unittest +from urllib.parse import urlencode, urlparse + +from Crypto.Hash import SHA256, SHA512 +from Crypto.PublicKey import ECC, RSA +from Crypto.Signature import pkcs1_15, pss, DSS + +import petstore_api +from petstore_api.model import category, tag, pet +from petstore_api.api.pet_api import PetApi +from petstore_api import Configuration, signing +from petstore_api.rest import ( + RESTClientObject, + RESTResponse +) + +from petstore_api.exceptions import ( + ApiException, + ApiValueError, + ApiTypeError, +) + +from .util import id_gen + +import urllib3 + +from unittest.mock import patch + +HOST = 'http://localhost/v2' + +# This test RSA private key below is published in Appendix C 'Test Values' of +# https://www.ietf.org/id/draft-cavage-http-signatures-12.txt +RSA_TEST_PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY----- +MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF +NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F +UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB +AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA +QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK +kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg +f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u +412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc +mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 +kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA +gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW +G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI +7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== +-----END RSA PRIVATE KEY-----""" + + +class TimeoutWithEqual(urllib3.Timeout): + def __init__(self, *arg, **kwargs): + super(TimeoutWithEqual, self).__init__(*arg, **kwargs) + + def __eq__(self, other): + return self._read == other._read and self._connect == other._connect and self.total == other.total + +class MockPoolManager(object): + def __init__(self, tc): + self._tc = tc + self._reqs = [] + + def expect_request(self, *args, **kwargs): + self._reqs.append((args, kwargs)) + + def set_signing_config(self, signing_cfg): + self.signing_cfg = signing_cfg + self._tc.assertIsNotNone(self.signing_cfg) + self.pubkey = self.signing_cfg.get_public_key() + self._tc.assertIsNotNone(self.pubkey) + + def request(self, *actual_request_target, **actual_request_headers_and_body): + self._tc.assertTrue(len(self._reqs) > 0) + expected_results = self._reqs.pop(0) + self._tc.maxDiff = None + expected_request_target = expected_results[0] # The expected HTTP method and URL path. + expected_request_headers_and_body = expected_results[1] # dict that contains the expected body, headers + self._tc.assertEqual(expected_request_target, actual_request_target) + # actual_request_headers_and_body is a dict that contains the actual body, headers + for k, expected in expected_request_headers_and_body.items(): + self._tc.assertIn(k, actual_request_headers_and_body) + if k == 'body': + actual_body = actual_request_headers_and_body[k] + self._tc.assertEqual(expected, actual_body) + elif k == 'headers': + actual_headers = actual_request_headers_and_body[k] + for expected_header_name, expected_header_value in expected.items(): + # Validate the generated request contains the expected header. + self._tc.assertIn(expected_header_name, actual_headers) + actual_header_value = actual_headers[expected_header_name] + # Compare the actual value of the header against the expected value. + pattern = re.compile(expected_header_value) + m = pattern.match(actual_header_value) + self._tc.assertTrue(m, msg="Expected:\n{0}\nActual:\n{1}".format( + expected_header_value,actual_header_value)) + if expected_header_name == 'Authorization': + self._validate_authorization_header( + expected_request_target, actual_headers, actual_header_value) + elif k == 'timeout': + self._tc.assertEqual(expected, actual_request_headers_and_body[k]) + return urllib3.HTTPResponse(status=200, body=b'test') + + def _validate_authorization_header(self, request_target, actual_headers, authorization_header): + """Validate the signature. + """ + # Extract (created) + r1 = re.compile(r'created=([0-9]+)') + m1 = r1.search(authorization_header) + self._tc.assertIsNotNone(m1) + created = m1.group(1) + + # Extract list of signed headers + r1 = re.compile(r'headers="([^"]+)"') + m1 = r1.search(authorization_header) + self._tc.assertIsNotNone(m1) + headers = m1.group(1).split(' ') + signed_headers_list = [] + for h in headers: + if h == '(created)': + signed_headers_list.append((h, created)) + elif h == '(request-target)': + url = request_target[1] + target_path = urlparse(url).path + signed_headers_list.append((h, "{0} {1}".format(request_target[0].lower(), target_path))) + else: + value = next((v for k, v in actual_headers.items() if k.lower() == h), None) + self._tc.assertIsNotNone(value) + signed_headers_list.append((h, value)) + header_items = [ + "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list] + string_to_sign = "\n".join(header_items) + digest = None + if self.signing_cfg.hash_algorithm == signing.HASH_SHA512: + digest = SHA512.new() + elif self.signing_cfg.hash_algorithm == signing.HASH_SHA256: + digest = SHA256.new() + else: + self._tc.fail("Unsupported hash algorithm: {0}".format(self.signing_cfg.hash_algorithm)) + digest.update(string_to_sign.encode()) + b64_body_digest = base64.b64encode(digest.digest()).decode() + + # Extract the signature + r2 = re.compile(r'signature="([^"]+)"') + m2 = r2.search(authorization_header) + self._tc.assertIsNotNone(m2) + b64_signature = m2.group(1) + signature = base64.b64decode(b64_signature) + # Build the message + signing_alg = self.signing_cfg.signing_algorithm + if signing_alg is None: + # Determine default + if isinstance(self.pubkey, RSA.RsaKey): + signing_alg = signing.ALGORITHM_RSASSA_PSS + elif isinstance(self.pubkey, ECC.EccKey): + signing_alg = signing.ALGORITHM_ECDSA_MODE_FIPS_186_3 + else: + self._tc.fail("Unsupported key: {0}".format(type(self.pubkey))) + + if signing_alg == signing.ALGORITHM_RSASSA_PKCS1v15: + pkcs1_15.new(self.pubkey).verify(digest, signature) + elif signing_alg == signing.ALGORITHM_RSASSA_PSS: + pss.new(self.pubkey).verify(digest, signature) + elif signing_alg == signing.ALGORITHM_ECDSA_MODE_FIPS_186_3: + verifier = DSS.new(key=self.pubkey, mode=signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, + encoding='der') + verifier.verify(digest, signature) + elif signing_alg == signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979: + verifier = DSS.new(key=self.pubkey, mode=signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979, + encoding='der') + verifier.verify(digest, signature) + else: + self._tc.fail("Unsupported signing algorithm: {0}".format(signing_alg)) + +class PetApiTests(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.setUpModels() + cls.setUpFiles() + + @classmethod + def tearDownClass(cls): + file_paths = [ + cls.rsa_key_path, + cls.rsa4096_key_path, + cls.ec_p521_key_path, + ] + for file_path in file_paths: + os.unlink(file_path) + + @classmethod + def setUpModels(cls): + cls.category = category.Category() + cls.category.id = id_gen() + cls.category.name = "dog" + cls.tag = tag.Tag() + cls.tag.id = id_gen() + cls.tag.name = "python-pet-tag" + cls.pet = pet.Pet( + name="hello kity", + photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"] + ) + cls.pet.id = id_gen() + cls.pet.status = "sold" + cls.pet.category = cls.category + cls.pet.tags = [cls.tag] + + @classmethod + def setUpFiles(cls): + cls.test_file_dir = os.path.join( + os.path.dirname(__file__), "..", "testfiles") + cls.test_file_dir = os.path.realpath(cls.test_file_dir) + if not os.path.exists(cls.test_file_dir): + os.mkdir(cls.test_file_dir) + + cls.private_key_passphrase = 'test-passphrase' + cls.rsa_key_path = os.path.join(cls.test_file_dir, 'rsa.pem') + cls.rsa4096_key_path = os.path.join(cls.test_file_dir, 'rsa4096.pem') + cls.ec_p521_key_path = os.path.join(cls.test_file_dir, 'ecP521.pem') + + if not os.path.exists(cls.rsa_key_path): + with open(cls.rsa_key_path, 'w') as f: + f.write(RSA_TEST_PRIVATE_KEY) + + if not os.path.exists(cls.rsa4096_key_path): + key = RSA.generate(4096) + private_key = key.export_key( + passphrase=cls.private_key_passphrase, + protection='PEM' + ) + with open(cls.rsa4096_key_path, "wb") as f: + f.write(private_key) + + if not os.path.exists(cls.ec_p521_key_path): + key = ECC.generate(curve='P-521') + private_key = key.export_key( + format='PEM', + passphrase=cls.private_key_passphrase, + use_pkcs8=True, + protection='PBKDF2WithHMAC-SHA1AndAES128-CBC' + ) + with open(cls.ec_p521_key_path, "wt") as f: + f.write(private_key) + + def test_valid_http_signature(self): + privkey_path = self.rsa_key_path + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path=privkey_path, + private_key_passphrase=self.private_key_passphrase, + signing_algorithm=signing.ALGORITHM_RSASSA_PKCS1v15, + signed_headers=[ + signing.HEADER_REQUEST_TARGET, + signing.HEADER_CREATED, + signing.HEADER_HOST, + signing.HEADER_DATE, + signing.HEADER_DIGEST, + 'Content-Type' + ] + ) + config = Configuration(host=HOST, signing_info=signing_cfg) + # Set the OAuth2 acces_token to None. Here we are interested in testing + # the HTTP signature scheme. + config.access_token = None + + api_client = petstore_api.ApiClient(config) + pet_api = PetApi(api_client) + + mock_pool = MockPoolManager(self) + api_client.rest_client.pool_manager = mock_pool + + mock_pool.set_signing_config(signing_cfg) + mock_pool.expect_request('POST', HOST + '/pet', + body=json.dumps(api_client.sanitize_for_serialization(self.pet)), + headers={'Content-Type': r'application/json', + 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' + r'headers="\(request-target\) \(created\) host date digest content-type",' + r'signature="[a-zA-Z0-9+/=]+"', + 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, + preload_content=True, timeout=None) + + pet_api.add_pet(self.pet) + + def test_valid_http_signature_with_defaults(self): + privkey_path = self.rsa4096_key_path + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path=privkey_path, + private_key_passphrase=self.private_key_passphrase, + ) + config = Configuration(host=HOST, signing_info=signing_cfg) + # Set the OAuth2 acces_token to None. Here we are interested in testing + # the HTTP signature scheme. + config.access_token = None + + api_client = petstore_api.ApiClient(config) + pet_api = PetApi(api_client) + + mock_pool = MockPoolManager(self) + api_client.rest_client.pool_manager = mock_pool + + mock_pool.set_signing_config(signing_cfg) + mock_pool.expect_request('POST', HOST + '/pet', + body=json.dumps(api_client.sanitize_for_serialization(self.pet)), + headers={'Content-Type': r'application/json', + 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' + r'headers="\(created\)",' + r'signature="[a-zA-Z0-9+/=]+"', + 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, + preload_content=True, timeout=None) + + pet_api.add_pet(self.pet) + + def test_valid_http_signature_rsassa_pkcs1v15(self): + privkey_path = self.rsa4096_key_path + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path=privkey_path, + private_key_passphrase=self.private_key_passphrase, + signing_algorithm=signing.ALGORITHM_RSASSA_PKCS1v15, + signed_headers=[ + signing.HEADER_REQUEST_TARGET, + signing.HEADER_CREATED, + ] + ) + config = Configuration(host=HOST, signing_info=signing_cfg) + # Set the OAuth2 acces_token to None. Here we are interested in testing + # the HTTP signature scheme. + config.access_token = None + + api_client = petstore_api.ApiClient(config) + pet_api = PetApi(api_client) + + mock_pool = MockPoolManager(self) + api_client.rest_client.pool_manager = mock_pool + + mock_pool.set_signing_config(signing_cfg) + mock_pool.expect_request('POST', HOST + '/pet', + body=json.dumps(api_client.sanitize_for_serialization(self.pet)), + headers={'Content-Type': r'application/json', + 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' + r'headers="\(request-target\) \(created\)",' + r'signature="[a-zA-Z0-9+/=]+"', + 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, + preload_content=True, timeout=None) + + pet_api.add_pet(self.pet) + + def test_valid_http_signature_rsassa_pss(self): + privkey_path = self.rsa4096_key_path + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path=privkey_path, + private_key_passphrase=self.private_key_passphrase, + signing_algorithm=signing.ALGORITHM_RSASSA_PSS, + signed_headers=[ + signing.HEADER_REQUEST_TARGET, + signing.HEADER_CREATED, + ] + ) + config = Configuration(host=HOST, signing_info=signing_cfg) + # Set the OAuth2 acces_token to None. Here we are interested in testing + # the HTTP signature scheme. + config.access_token = None + + api_client = petstore_api.ApiClient(config) + pet_api = PetApi(api_client) + + mock_pool = MockPoolManager(self) + api_client.rest_client.pool_manager = mock_pool + + mock_pool.set_signing_config(signing_cfg) + mock_pool.expect_request('POST', HOST + '/pet', + body=json.dumps(api_client.sanitize_for_serialization(self.pet)), + headers={'Content-Type': r'application/json', + 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' + r'headers="\(request-target\) \(created\)",' + r'signature="[a-zA-Z0-9+/=]+"', + 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, + preload_content=True, timeout=None) + + pet_api.add_pet(self.pet) + + def test_valid_http_signature_ec_p521(self): + privkey_path = self.ec_p521_key_path + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path=privkey_path, + private_key_passphrase=self.private_key_passphrase, + hash_algorithm=signing.HASH_SHA512, + signed_headers=[ + signing.HEADER_REQUEST_TARGET, + signing.HEADER_CREATED, + ] + ) + config = Configuration(host=HOST, signing_info=signing_cfg) + # Set the OAuth2 acces_token to None. Here we are interested in testing + # the HTTP signature scheme. + config.access_token = None + + api_client = petstore_api.ApiClient(config) + pet_api = PetApi(api_client) + + mock_pool = MockPoolManager(self) + api_client.rest_client.pool_manager = mock_pool + + mock_pool.set_signing_config(signing_cfg) + mock_pool.expect_request('POST', HOST + '/pet', + body=json.dumps(api_client.sanitize_for_serialization(self.pet)), + headers={'Content-Type': r'application/json', + 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' + r'headers="\(request-target\) \(created\)",' + r'signature="[a-zA-Z0-9+/=]+"', + 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, + preload_content=True, timeout=None) + + pet_api.add_pet(self.pet) + + def test_invalid_configuration(self): + # Signing scheme must be valid. + with self.assertRaises(Exception) as cm: + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme='foo', + private_key_path=self.ec_p521_key_path + ) + self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)), + 'Exception message: {0}'.format(str(cm.exception))) + + # Signing scheme must be specified. + with self.assertRaises(Exception) as cm: + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + private_key_path=self.ec_p521_key_path, + signing_scheme=None + ) + self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)), + 'Exception message: {0}'.format(str(cm.exception))) + + # Private key passphrase is missing but key is encrypted. + with self.assertRaises(Exception) as cm: + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path=self.ec_p521_key_path, + ) + self.assertTrue(re.match('Not a valid clear PKCS#8 structure', str(cm.exception)), + 'Exception message: {0}'.format(str(cm.exception))) + + # File containing private key must exist. + with self.assertRaises(Exception) as cm: + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path='foobar', + ) + self.assertTrue(re.match('Private key file does not exist', str(cm.exception)), + 'Exception message: {0}'.format(str(cm.exception))) + + # The max validity must be a positive value. + with self.assertRaises(Exception) as cm: + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path=self.ec_p521_key_path, + signature_max_validity=timedelta(hours=-1) + ) + self.assertTrue(re.match('The signature max validity must be a positive value', + str(cm.exception)), + 'Exception message: {0}'.format(str(cm.exception))) + + # Cannot include the 'Authorization' header. + with self.assertRaises(Exception) as cm: + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path=self.ec_p521_key_path, + signed_headers=['Authorization'] + ) + self.assertTrue(re.match("'Authorization' header cannot be included", str(cm.exception)), + 'Exception message: {0}'.format(str(cm.exception))) + + # Cannot specify duplicate headers. + with self.assertRaises(Exception) as cm: + signing_cfg = signing.HttpSigningConfiguration( + key_id="my-key-id", + signing_scheme=signing.SCHEME_HS2019, + private_key_path=self.ec_p521_key_path, + signed_headers=['Host', 'Date', 'Host'] + ) + self.assertTrue(re.match('Cannot have duplicates in the signed_headers parameter', + str(cm.exception)), + 'Exception message: {0}'.format(str(cm.exception))) + diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_integer_enum_one_value.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_integer_enum_one_value.py new file mode 100644 index 0000000000..eff7298d9f --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_integer_enum_one_value.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue + + +class TestIntegerEnumOneValue(unittest.TestCase): + """IntegerEnumOneValue unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testIntegerEnumOneValue(self): + """Test IntegerEnumOneValue""" + model = IntegerEnumOneValue() + assert model.value == 0, "With only one option, the value is assigned automatically" + + model = IntegerEnumOneValue(0) + assert model.value == 0, "We can also pass in the value as a positional arg" + + model = IntegerEnumOneValue(value=0) + assert model.value == 0, "We can also pass in the value as a named argument" + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_issue10083.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_issue10083.py similarity index 100% rename from samples/openapi3/client/petstore/python/tests_manual/test_issue10083.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/test_issue10083.py diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_issue10155.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_issue10155.py similarity index 100% rename from samples/openapi3/client/petstore/python/tests_manual/test_issue10155.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/test_issue10155.py diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_mammal.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_mammal.py new file mode 100644 index 0000000000..3ed00dd798 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_mammal.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import whale +except ImportError: + whale = sys.modules[ + 'petstore_api.model.whale'] +try: + from petstore_api.model import zebra +except ImportError: + zebra = sys.modules[ + 'petstore_api.model.zebra'] +from petstore_api.model.mammal import Mammal + + +class TestMammal(unittest.TestCase): + """Mammal unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testMammal(self): + """Test Mammal""" + + # tests that we can make a BasquePig by traveling through descendant discriminator in Pig + model = Mammal(class_name="BasquePig") + from petstore_api.model import basque_pig + assert isinstance(model, basque_pig.BasquePig) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_mole.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_mole.py similarity index 100% rename from samples/openapi3/client/petstore/python/tests_manual/test_mole.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/test_mole.py diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_number_with_validations.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_number_with_validations.py new file mode 100644 index 0000000000..f4264ca82e --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_number_with_validations.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.number_with_validations import NumberWithValidations + + +class TestNumberWithValidations(unittest.TestCase): + """NumberWithValidations unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testNumberWithValidations(self): + """Test NumberWithValidations""" + valid_values = [10.0, 15.0, 20.0] + for valid_value in valid_values: + model = NumberWithValidations(valid_value) + assert model.value == valid_value + + invalid_values = [9.0, 21.0] + for invalid_value in invalid_values: + with self.assertRaises(petstore_api.ApiValueError): + NumberWithValidations(invalid_value) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_object_model_with_ref_props.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_object_model_with_ref_props.py new file mode 100644 index 0000000000..c708237acb --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_object_model_with_ref_props.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import number_with_validations +except ImportError: + number_with_validations = sys.modules[ + 'petstore_api.model.number_with_validations'] +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from petstore_api.model.readonly import Readonly + + +class TestObjectModelWithRefProps(unittest.TestCase): + """ObjectModelWithRefProps unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testObjectModelWithRefProps(self): + """Test ObjectModelWithRefProps""" + from petstore_api.model.number_with_validations import NumberWithValidations + self.assertEqual( + ObjectModelWithRefProps.openapi_types, + { + 'my_number': (NumberWithValidations,), + 'my_readonly': (Readonly,), + 'my_string': (str,), + 'my_boolean': (bool,), + } + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_parent_pet.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_parent_pet.py new file mode 100644 index 0000000000..a57f9b8527 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_parent_pet.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import child_cat +except ImportError: + child_cat = sys.modules[ + 'petstore_api.model.child_cat'] +try: + from petstore_api.model import grandparent_animal +except ImportError: + grandparent_animal = sys.modules[ + 'petstore_api.model.grandparent_animal'] +from petstore_api.model.parent_pet import ParentPet + + +class TestParentPet(unittest.TestCase): + """ParentPet unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testParentPet(self): + """Test ParentPet""" + + # test that we can make a ParentPet from a ParentPet + # which requires that we travel back through ParentPet's allOf descendant + # GrandparentAnimal, and we use the descendant's discriminator to make ParentPet + model = ParentPet(pet_type="ParentPet") + assert isinstance(model, ParentPet) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_quadrilateral.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_quadrilateral.py new file mode 100644 index 0000000000..63f74ae541 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_quadrilateral.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import complex_quadrilateral +except ImportError: + complex_quadrilateral = sys.modules[ + 'petstore_api.model.complex_quadrilateral'] +try: + from petstore_api.model import simple_quadrilateral +except ImportError: + simple_quadrilateral = sys.modules[ + 'petstore_api.model.simple_quadrilateral'] +from petstore_api.model.quadrilateral import Quadrilateral + + +class TestQuadrilateral(unittest.TestCase): + """Quadrilateral unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testQuadrilateral(self): + """Test Quadrilateral""" + instance = Quadrilateral(shape_type="Quadrilateral", quadrilateral_type="ComplexQuadrilateral") + assert isinstance(instance, complex_quadrilateral.ComplexQuadrilateral) + instance = Quadrilateral(shape_type="Quadrilateral", quadrilateral_type="SimpleQuadrilateral") + assert isinstance(instance, simple_quadrilateral.SimpleQuadrilateral) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_shape.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_shape.py new file mode 100644 index 0000000000..a2b59fc6f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_shape.py @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import quadrilateral +except ImportError: + quadrilateral = sys.modules[ + 'petstore_api.model.quadrilateral'] +try: + from petstore_api.model import triangle +except ImportError: + triangle = sys.modules[ + 'petstore_api.model.triangle'] +from petstore_api.model.shape import Shape + + +class TestShape(unittest.TestCase): + """Shape unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_recursionlimit(self): + """Test case for recursionlimit + + """ + assert sys.getrecursionlimit() == 1234 + + def testShape(self): + """Test Shape""" + from petstore_api.model import complex_quadrilateral + from petstore_api.model import simple_quadrilateral + from petstore_api.model import equilateral_triangle + from petstore_api.model import isosceles_triangle + from petstore_api.model import scalene_triangle + + tri = triangle.Triangle( + shape_type="Triangle", + triangle_type="EquilateralTriangle" + ) + assert isinstance(tri, equilateral_triangle.EquilateralTriangle) + + tri = triangle.Triangle( + shape_type="Triangle", + triangle_type="IsoscelesTriangle" + ) + assert isinstance(tri, isosceles_triangle.IsoscelesTriangle) + + tri = triangle.Triangle( + shape_type="Triangle", + triangle_type="ScaleneTriangle" + ) + assert isinstance(tri, scalene_triangle.ScaleneTriangle) + + quad = Shape( + shape_type="Quadrilateral", + quadrilateral_type="ComplexQuadrilateral" + ) + assert isinstance(quad, complex_quadrilateral.ComplexQuadrilateral) + + quad = Shape( + shape_type="Quadrilateral", + quadrilateral_type="SimpleQuadrilateral" + ) + assert isinstance(quad, simple_quadrilateral.SimpleQuadrilateral) + + # No discriminator provided. + err_msg = ("Cannot deserialize input data due to missing discriminator. " + "The discriminator property '{}' is missing at path: ()" + ) + with self.assertRaisesRegex( + petstore_api.ApiValueError, + err_msg.format("shapeType") + ): + Shape() + + # invalid shape_type (first discriminator). 'Circle' does not exist in the model. + err_msg = ("Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '{}'='{}' at path: ()" + ) + with self.assertRaisesRegex( + petstore_api.ApiValueError, + err_msg.format("shapeType", "Circle") + ): + Shape(shape_type="Circle") + + # invalid quadrilateral_type (second discriminator) + with self.assertRaisesRegex( + petstore_api.ApiValueError, + err_msg.format("quadrilateralType", "Triangle") + ): + Shape( + shape_type="Quadrilateral", + quadrilateral_type="Triangle" + ) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_string_enum.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_string_enum.py new file mode 100644 index 0000000000..87092d66d3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_string_enum.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.string_enum import StringEnum + + +class TestStringEnum(unittest.TestCase): + """StringEnum unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testStringEnum(self): + """Test StringEnum""" + inst = StringEnum(None) + self.assertIsNone(inst) + + inst = StringEnum('approved') + assert isinstance(inst, StringEnum) + + with self.assertRaises(petstore_api.ApiValueError): + StringEnum('garbage') + + # make sure that we can access its allowed_values + assert StringEnum.allowed_values[('value',)] == { + 'None': None, + 'PLACED': "placed", + 'APPROVED': "approved", + 'DELIVERED': "delivered", + 'DOUBLE_QUOTE_WITH_NEWLINE': "double quote \n with newline", + 'MULTIPLE_LINES': "multiple\nlines", + 'SINGLE_QUOTED': "single quoted" + } + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_tag.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_tag.py similarity index 100% rename from samples/openapi3/client/petstore/python/tests_manual/test_tag.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/test_tag.py diff --git a/samples/openapi3/client/petstore/python-prior/tests_manual/test_triangle.py b/samples/openapi3/client/petstore/python-prior/tests_manual/test_triangle.py new file mode 100644 index 0000000000..7268022cad --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tests_manual/test_triangle.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import equilateral_triangle +except ImportError: + equilateral_triangle = sys.modules[ + 'petstore_api.model.equilateral_triangle'] +try: + from petstore_api.model import isosceles_triangle +except ImportError: + isosceles_triangle = sys.modules[ + 'petstore_api.model.isosceles_triangle'] +try: + from petstore_api.model import scalene_triangle +except ImportError: + scalene_triangle = sys.modules[ + 'petstore_api.model.scalene_triangle'] +from petstore_api.model.triangle import Triangle + + +class TestTriangle(unittest.TestCase): + """Triangle unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testTriangle(self): + """Test Triangle""" + tri = Triangle(shape_type="Triangle", triangle_type="EquilateralTriangle") + assert isinstance(tri, equilateral_triangle.EquilateralTriangle) + tri = Triangle(shape_type="Triangle", triangle_type="IsoscelesTriangle") + assert isinstance(tri, isosceles_triangle.IsoscelesTriangle) + tri = Triangle(shape_type="Triangle", triangle_type="ScaleneTriangle") + assert isinstance(tri, scalene_triangle.ScaleneTriangle) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/util.py b/samples/openapi3/client/petstore/python-prior/tests_manual/util.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/util.py rename to samples/openapi3/client/petstore/python-prior/tests_manual/util.py diff --git a/samples/openapi3/client/petstore/python-prior/tox.ini b/samples/openapi3/client/petstore/python-prior/tox.ini new file mode 100644 index 0000000000..8989fc3c4d --- /dev/null +++ b/samples/openapi3/client/petstore/python-prior/tox.ini @@ -0,0 +1,9 @@ +[tox] +envlist = py3 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + pytest --cov=petstore_api diff --git a/samples/openapi3/client/petstore/python/.gitignore b/samples/openapi3/client/petstore/python/.gitignore index 43995bd42f..a62e8aba43 100644 --- a/samples/openapi3/client/petstore/python/.gitignore +++ b/samples/openapi3/client/petstore/python/.gitignore @@ -33,6 +33,7 @@ var/ # Installer logs pip-log.txt pip-delete-this-directory.txt +dev-requirements.txt.log # Unit test / coverage reports htmlcov/ diff --git a/samples/openapi3/client/petstore/python/.gitlab-ci.yml b/samples/openapi3/client/petstore/python/.gitlab-ci.yml index 9e84f51761..611e425676 100644 --- a/samples/openapi3/client/petstore/python/.gitlab-ci.yml +++ b/samples/openapi3/client/petstore/python/.gitlab-ci.yml @@ -10,6 +10,9 @@ stages: - pip install -r test-requirements.txt - pytest --cov=petstore_api +test-3.5: + extends: .tests + image: python:3.5-alpine test-3.6: extends: .tests image: python:3.6-alpine @@ -19,6 +22,3 @@ test-3.7: test-3.8: extends: .tests image: python:3.8-alpine -test-3.9: - extends: .tests - image: python:3.9-alpine diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index aa32ba2dee..f805094f7e 100644 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -2,235 +2,392 @@ .gitlab-ci.yml .travis.yml README.md -docs/AdditionalPropertiesClass.md -docs/AdditionalPropertiesWithArrayOfEnums.md -docs/Address.md -docs/Animal.md -docs/AnimalFarm.md -docs/AnotherFakeApi.md -docs/ApiResponse.md -docs/Apple.md -docs/AppleReq.md -docs/ArrayOfArrayOfNumberOnly.md -docs/ArrayOfEnums.md -docs/ArrayOfNumberOnly.md -docs/ArrayTest.md -docs/Banana.md -docs/BananaReq.md -docs/BasquePig.md -docs/BooleanEnum.md -docs/Capitalization.md -docs/Cat.md -docs/CatAllOf.md -docs/Category.md -docs/ChildCat.md -docs/ChildCatAllOf.md -docs/ClassModel.md -docs/Client.md -docs/ComplexQuadrilateral.md -docs/ComposedOneOfNumberWithValidations.md -docs/ComposedSchemaWithPropsAndNoAddProps.md -docs/DanishPig.md -docs/DefaultApi.md -docs/Dog.md -docs/DogAllOf.md -docs/Drawing.md -docs/EgressThresholdOptions.md -docs/EnumArrays.md -docs/EnumClass.md -docs/EnumTest.md -docs/EquilateralTriangle.md -docs/FakeApi.md -docs/FakeClassnameTags123Api.md -docs/File.md -docs/FileSchemaTestClass.md -docs/Foo.md -docs/FooGetDefaultResponse.md -docs/FooObject.md -docs/FormatTest.md -docs/Fruit.md -docs/FruitReq.md -docs/GmFruit.md -docs/GmFruitNoProperties.md -docs/GrandparentAnimal.md -docs/HasOnlyReadOnly.md -docs/HealthCheckResult.md -docs/InlineAdditionalPropertiesRefPayload.md -docs/IntegerEnum.md -docs/IntegerEnumOneValue.md -docs/IntegerEnumWithDefaultValue.md -docs/IsoscelesTriangle.md -docs/Legs.md -docs/List.md -docs/Mammal.md -docs/MapTest.md -docs/MixedPropertiesAndAdditionalPropertiesClass.md -docs/Model200Response.md -docs/ModelReturn.md -docs/Mole.md -docs/Name.md -docs/NullableClass.md -docs/NullableShape.md -docs/NumberOnly.md -docs/NumberWithValidations.md -docs/ObjectInterface.md -docs/ObjectModelWithRefProps.md -docs/ObjectWithValidations.md -docs/Order.md -docs/ParentPet.md -docs/Pet.md -docs/PetApi.md -docs/Pig.md -docs/PostInlineAdditionalPropertiesPayloadRequest.md -docs/PostInlineAdditionalPropertiesPayloadRequestArrayDataInner.md -docs/PublishOptions.md -docs/PublishOptionsPublish.md -docs/Quadrilateral.md -docs/QuadrilateralInterface.md -docs/ReadOnlyFirst.md -docs/Readonly.md -docs/ScaleneTriangle.md -docs/Shape.md -docs/ShapeInterface.md -docs/ShapeOrNull.md -docs/SimpleQuadrilateral.md -docs/SomeObject.md -docs/SomeObjectWithSelfAttr.md -docs/SpecialModelName.md -docs/StoreApi.md -docs/StreamOptions.md -docs/StringBooleanMap.md -docs/StringEnum.md -docs/StringEnumWithDefaultValue.md -docs/Tag.md -docs/Triangle.md -docs/TriangleInterface.md -docs/User.md -docs/UserApi.md -docs/Whale.md -docs/Zebra.md +docs/apis/tags/AnotherFakeApi.md +docs/apis/tags/DefaultApi.md +docs/apis/tags/FakeApi.md +docs/apis/tags/FakeClassnameTags123Api.md +docs/apis/tags/PetApi.md +docs/apis/tags/StoreApi.md +docs/apis/tags/UserApi.md +docs/models/AdditionalPropertiesClass.md +docs/models/AdditionalPropertiesValidator.md +docs/models/AdditionalPropertiesWithArrayOfEnums.md +docs/models/Address.md +docs/models/Animal.md +docs/models/AnimalFarm.md +docs/models/AnyTypeAndFormat.md +docs/models/AnyTypeNotString.md +docs/models/ApiResponse.md +docs/models/Apple.md +docs/models/AppleReq.md +docs/models/ArrayHoldingAnyType.md +docs/models/ArrayOfArrayOfNumberOnly.md +docs/models/ArrayOfEnums.md +docs/models/ArrayOfNumberOnly.md +docs/models/ArrayTest.md +docs/models/ArrayWithValidationsInItems.md +docs/models/Banana.md +docs/models/BananaReq.md +docs/models/Bar.md +docs/models/BasquePig.md +docs/models/Boolean.md +docs/models/BooleanEnum.md +docs/models/Capitalization.md +docs/models/Cat.md +docs/models/Category.md +docs/models/ChildCat.md +docs/models/ClassModel.md +docs/models/Client.md +docs/models/ComplexQuadrilateral.md +docs/models/ComposedAnyOfDifferentTypesNoValidations.md +docs/models/ComposedArray.md +docs/models/ComposedBool.md +docs/models/ComposedNone.md +docs/models/ComposedNumber.md +docs/models/ComposedObject.md +docs/models/ComposedOneOfDifferentTypes.md +docs/models/ComposedString.md +docs/models/Currency.md +docs/models/DanishPig.md +docs/models/DateTimeTest.md +docs/models/DateTimeWithValidations.md +docs/models/DateWithValidations.md +docs/models/DecimalPayload.md +docs/models/Dog.md +docs/models/Drawing.md +docs/models/EnumArrays.md +docs/models/EnumClass.md +docs/models/EnumTest.md +docs/models/EquilateralTriangle.md +docs/models/File.md +docs/models/FileSchemaTestClass.md +docs/models/Foo.md +docs/models/FormatTest.md +docs/models/FromSchema.md +docs/models/Fruit.md +docs/models/FruitReq.md +docs/models/GmFruit.md +docs/models/GrandparentAnimal.md +docs/models/HasOnlyReadOnly.md +docs/models/HealthCheckResult.md +docs/models/IntegerEnum.md +docs/models/IntegerEnumBig.md +docs/models/IntegerEnumOneValue.md +docs/models/IntegerEnumWithDefaultValue.md +docs/models/IntegerMax10.md +docs/models/IntegerMin15.md +docs/models/IsoscelesTriangle.md +docs/models/JSONPatchRequest.md +docs/models/JSONPatchRequestAddReplaceTest.md +docs/models/JSONPatchRequestMoveCopy.md +docs/models/JSONPatchRequestRemove.md +docs/models/Mammal.md +docs/models/MapTest.md +docs/models/MixedPropertiesAndAdditionalPropertiesClass.md +docs/models/Model200Response.md +docs/models/ModelReturn.md +docs/models/Money.md +docs/models/Name.md +docs/models/NoAdditionalProperties.md +docs/models/NullableClass.md +docs/models/NullableShape.md +docs/models/NullableString.md +docs/models/Number.md +docs/models/NumberOnly.md +docs/models/NumberWithValidations.md +docs/models/ObjectInterface.md +docs/models/ObjectModelWithRefProps.md +docs/models/ObjectWithDecimalProperties.md +docs/models/ObjectWithDifficultlyNamedProps.md +docs/models/ObjectWithInlineCompositionProperty.md +docs/models/ObjectWithInvalidNamedRefedProperties.md +docs/models/ObjectWithValidations.md +docs/models/Order.md +docs/models/ParentPet.md +docs/models/Pet.md +docs/models/Pig.md +docs/models/Player.md +docs/models/Quadrilateral.md +docs/models/QuadrilateralInterface.md +docs/models/ReadOnlyFirst.md +docs/models/ScaleneTriangle.md +docs/models/Shape.md +docs/models/ShapeOrNull.md +docs/models/SimpleQuadrilateral.md +docs/models/SomeObject.md +docs/models/SpecialModelName.md +docs/models/String.md +docs/models/StringBooleanMap.md +docs/models/StringEnum.md +docs/models/StringEnumWithDefaultValue.md +docs/models/StringWithValidation.md +docs/models/Tag.md +docs/models/Triangle.md +docs/models/TriangleInterface.md +docs/models/UUIDString.md +docs/models/User.md +docs/models/Whale.md +docs/models/Zebra.md git_push.sh petstore_api/__init__.py -petstore_api/api/__init__.py -petstore_api/api/another_fake_api.py -petstore_api/api/default_api.py -petstore_api/api/fake_api.py -petstore_api/api/fake_classname_tags123_api.py -petstore_api/api/pet_api.py -petstore_api/api/store_api.py -petstore_api/api/user_api.py petstore_api/api_client.py petstore_api/apis/__init__.py +petstore_api/apis/tags/another_fake_api.py +petstore_api/apis/tags/default_api.py +petstore_api/apis/tags/fake_api.py +petstore_api/apis/tags/fake_classname_tags123_api.py +petstore_api/apis/tags/pet_api.py +petstore_api/apis/tags/store_api.py +petstore_api/apis/tags/user_api.py petstore_api/configuration.py petstore_api/exceptions.py petstore_api/model/__init__.py petstore_api/model/additional_properties_class.py +petstore_api/model/additional_properties_class.pyi +petstore_api/model/additional_properties_validator.py +petstore_api/model/additional_properties_validator.pyi petstore_api/model/additional_properties_with_array_of_enums.py +petstore_api/model/additional_properties_with_array_of_enums.pyi petstore_api/model/address.py +petstore_api/model/address.pyi petstore_api/model/animal.py +petstore_api/model/animal.pyi petstore_api/model/animal_farm.py +petstore_api/model/animal_farm.pyi +petstore_api/model/any_type_and_format.py +petstore_api/model/any_type_and_format.pyi +petstore_api/model/any_type_not_string.py +petstore_api/model/any_type_not_string.pyi petstore_api/model/api_response.py +petstore_api/model/api_response.pyi petstore_api/model/apple.py +petstore_api/model/apple.pyi petstore_api/model/apple_req.py +petstore_api/model/apple_req.pyi +petstore_api/model/array_holding_any_type.py +petstore_api/model/array_holding_any_type.pyi petstore_api/model/array_of_array_of_number_only.py +petstore_api/model/array_of_array_of_number_only.pyi petstore_api/model/array_of_enums.py +petstore_api/model/array_of_enums.pyi petstore_api/model/array_of_number_only.py +petstore_api/model/array_of_number_only.pyi petstore_api/model/array_test.py +petstore_api/model/array_test.pyi +petstore_api/model/array_with_validations_in_items.py +petstore_api/model/array_with_validations_in_items.pyi petstore_api/model/banana.py +petstore_api/model/banana.pyi petstore_api/model/banana_req.py +petstore_api/model/banana_req.pyi +petstore_api/model/bar.py +petstore_api/model/bar.pyi petstore_api/model/basque_pig.py +petstore_api/model/basque_pig.pyi +petstore_api/model/boolean.py +petstore_api/model/boolean.pyi petstore_api/model/boolean_enum.py +petstore_api/model/boolean_enum.pyi petstore_api/model/capitalization.py +petstore_api/model/capitalization.pyi petstore_api/model/cat.py -petstore_api/model/cat_all_of.py +petstore_api/model/cat.pyi petstore_api/model/category.py +petstore_api/model/category.pyi petstore_api/model/child_cat.py -petstore_api/model/child_cat_all_of.py +petstore_api/model/child_cat.pyi petstore_api/model/class_model.py +petstore_api/model/class_model.pyi petstore_api/model/client.py +petstore_api/model/client.pyi petstore_api/model/complex_quadrilateral.py -petstore_api/model/composed_one_of_number_with_validations.py -petstore_api/model/composed_schema_with_props_and_no_add_props.py +petstore_api/model/complex_quadrilateral.pyi +petstore_api/model/composed_any_of_different_types_no_validations.py +petstore_api/model/composed_any_of_different_types_no_validations.pyi +petstore_api/model/composed_array.py +petstore_api/model/composed_array.pyi +petstore_api/model/composed_bool.py +petstore_api/model/composed_bool.pyi +petstore_api/model/composed_none.py +petstore_api/model/composed_none.pyi +petstore_api/model/composed_number.py +petstore_api/model/composed_number.pyi +petstore_api/model/composed_object.py +petstore_api/model/composed_object.pyi +petstore_api/model/composed_one_of_different_types.py +petstore_api/model/composed_one_of_different_types.pyi +petstore_api/model/composed_string.py +petstore_api/model/composed_string.pyi +petstore_api/model/currency.py +petstore_api/model/currency.pyi petstore_api/model/danish_pig.py +petstore_api/model/danish_pig.pyi +petstore_api/model/date_time_test.py +petstore_api/model/date_time_test.pyi +petstore_api/model/date_time_with_validations.py +petstore_api/model/date_time_with_validations.pyi +petstore_api/model/date_with_validations.py +petstore_api/model/date_with_validations.pyi +petstore_api/model/decimal_payload.py +petstore_api/model/decimal_payload.pyi petstore_api/model/dog.py -petstore_api/model/dog_all_of.py +petstore_api/model/dog.pyi petstore_api/model/drawing.py -petstore_api/model/egress_threshold_options.py +petstore_api/model/drawing.pyi petstore_api/model/enum_arrays.py +petstore_api/model/enum_arrays.pyi petstore_api/model/enum_class.py +petstore_api/model/enum_class.pyi petstore_api/model/enum_test.py +petstore_api/model/enum_test.pyi petstore_api/model/equilateral_triangle.py +petstore_api/model/equilateral_triangle.pyi petstore_api/model/file.py +petstore_api/model/file.pyi petstore_api/model/file_schema_test_class.py +petstore_api/model/file_schema_test_class.pyi petstore_api/model/foo.py -petstore_api/model/foo_get_default_response.py -petstore_api/model/foo_object.py +petstore_api/model/foo.pyi petstore_api/model/format_test.py +petstore_api/model/format_test.pyi +petstore_api/model/from_schema.py +petstore_api/model/from_schema.pyi petstore_api/model/fruit.py +petstore_api/model/fruit.pyi petstore_api/model/fruit_req.py +petstore_api/model/fruit_req.pyi petstore_api/model/gm_fruit.py -petstore_api/model/gm_fruit_no_properties.py +petstore_api/model/gm_fruit.pyi petstore_api/model/grandparent_animal.py +petstore_api/model/grandparent_animal.pyi petstore_api/model/has_only_read_only.py +petstore_api/model/has_only_read_only.pyi petstore_api/model/health_check_result.py -petstore_api/model/inline_additional_properties_ref_payload.py +petstore_api/model/health_check_result.pyi petstore_api/model/integer_enum.py +petstore_api/model/integer_enum.pyi +petstore_api/model/integer_enum_big.py +petstore_api/model/integer_enum_big.pyi petstore_api/model/integer_enum_one_value.py +petstore_api/model/integer_enum_one_value.pyi petstore_api/model/integer_enum_with_default_value.py +petstore_api/model/integer_enum_with_default_value.pyi +petstore_api/model/integer_max10.py +petstore_api/model/integer_max10.pyi +petstore_api/model/integer_min15.py +petstore_api/model/integer_min15.pyi petstore_api/model/isosceles_triangle.py -petstore_api/model/legs.py -petstore_api/model/list.py +petstore_api/model/isosceles_triangle.pyi +petstore_api/model/json_patch_request.py +petstore_api/model/json_patch_request.pyi +petstore_api/model/json_patch_request_add_replace_test.py +petstore_api/model/json_patch_request_add_replace_test.pyi +petstore_api/model/json_patch_request_move_copy.py +petstore_api/model/json_patch_request_move_copy.pyi +petstore_api/model/json_patch_request_remove.py +petstore_api/model/json_patch_request_remove.pyi petstore_api/model/mammal.py +petstore_api/model/mammal.pyi petstore_api/model/map_test.py +petstore_api/model/map_test.pyi petstore_api/model/mixed_properties_and_additional_properties_class.py +petstore_api/model/mixed_properties_and_additional_properties_class.pyi petstore_api/model/model200_response.py +petstore_api/model/model200_response.pyi petstore_api/model/model_return.py -petstore_api/model/mole.py +petstore_api/model/model_return.pyi +petstore_api/model/money.py +petstore_api/model/money.pyi petstore_api/model/name.py +petstore_api/model/name.pyi +petstore_api/model/no_additional_properties.py +petstore_api/model/no_additional_properties.pyi petstore_api/model/nullable_class.py +petstore_api/model/nullable_class.pyi petstore_api/model/nullable_shape.py +petstore_api/model/nullable_shape.pyi +petstore_api/model/nullable_string.py +petstore_api/model/nullable_string.pyi +petstore_api/model/number.py +petstore_api/model/number.pyi petstore_api/model/number_only.py +petstore_api/model/number_only.pyi petstore_api/model/number_with_validations.py +petstore_api/model/number_with_validations.pyi petstore_api/model/object_interface.py +petstore_api/model/object_interface.pyi petstore_api/model/object_model_with_ref_props.py +petstore_api/model/object_model_with_ref_props.pyi +petstore_api/model/object_with_decimal_properties.py +petstore_api/model/object_with_decimal_properties.pyi +petstore_api/model/object_with_difficultly_named_props.py +petstore_api/model/object_with_difficultly_named_props.pyi +petstore_api/model/object_with_inline_composition_property.py +petstore_api/model/object_with_inline_composition_property.pyi +petstore_api/model/object_with_invalid_named_refed_properties.py +petstore_api/model/object_with_invalid_named_refed_properties.pyi petstore_api/model/object_with_validations.py +petstore_api/model/object_with_validations.pyi petstore_api/model/order.py +petstore_api/model/order.pyi petstore_api/model/parent_pet.py +petstore_api/model/parent_pet.pyi petstore_api/model/pet.py +petstore_api/model/pet.pyi petstore_api/model/pig.py -petstore_api/model/post_inline_additional_properties_payload_request.py -petstore_api/model/post_inline_additional_properties_payload_request_array_data_inner.py -petstore_api/model/publish_options.py -petstore_api/model/publish_options_publish.py +petstore_api/model/pig.pyi +petstore_api/model/player.py +petstore_api/model/player.pyi petstore_api/model/quadrilateral.py +petstore_api/model/quadrilateral.pyi petstore_api/model/quadrilateral_interface.py +petstore_api/model/quadrilateral_interface.pyi petstore_api/model/read_only_first.py -petstore_api/model/readonly.py +petstore_api/model/read_only_first.pyi petstore_api/model/scalene_triangle.py +petstore_api/model/scalene_triangle.pyi petstore_api/model/shape.py -petstore_api/model/shape_interface.py +petstore_api/model/shape.pyi petstore_api/model/shape_or_null.py +petstore_api/model/shape_or_null.pyi petstore_api/model/simple_quadrilateral.py +petstore_api/model/simple_quadrilateral.pyi petstore_api/model/some_object.py -petstore_api/model/some_object_with_self_attr.py +petstore_api/model/some_object.pyi petstore_api/model/special_model_name.py -petstore_api/model/stream_options.py +petstore_api/model/special_model_name.pyi +petstore_api/model/string.py +petstore_api/model/string.pyi petstore_api/model/string_boolean_map.py +petstore_api/model/string_boolean_map.pyi petstore_api/model/string_enum.py +petstore_api/model/string_enum.pyi petstore_api/model/string_enum_with_default_value.py +petstore_api/model/string_enum_with_default_value.pyi +petstore_api/model/string_with_validation.py +petstore_api/model/string_with_validation.pyi petstore_api/model/tag.py +petstore_api/model/tag.pyi petstore_api/model/triangle.py +petstore_api/model/triangle.pyi petstore_api/model/triangle_interface.py +petstore_api/model/triangle_interface.pyi petstore_api/model/user.py +petstore_api/model/user.pyi +petstore_api/model/uuid_string.py +petstore_api/model/uuid_string.pyi petstore_api/model/whale.py +petstore_api/model/whale.pyi petstore_api/model/zebra.py -petstore_api/model_utils.py +petstore_api/model/zebra.pyi petstore_api/models/__init__.py petstore_api/rest.py +petstore_api/schemas.py petstore_api/signing.py requirements.txt setup.cfg setup.py test-requirements.txt test/__init__.py +test/test_models/__init__.py tox.ini diff --git a/samples/openapi3/client/petstore/python/.travis.yml b/samples/openapi3/client/petstore/python/.travis.yml index 1fcc4b1559..f931f0f74b 100644 --- a/samples/openapi3/client/petstore/python/.travis.yml +++ b/samples/openapi3/client/petstore/python/.travis.yml @@ -1,10 +1,10 @@ # ref: https://docs.travis-ci.com/user/languages/python language: python python: + - "3.5" - "3.6" - "3.7" - "3.8" - - "3.9" # command to install dependencies install: - "pip install -r requirements.txt" diff --git a/samples/openapi3/client/petstore/python/Makefile b/samples/openapi3/client/petstore/python/Makefile index f8957d5ed6..863c380ebe 100644 --- a/samples/openapi3/client/petstore/python/Makefile +++ b/samples/openapi3/client/petstore/python/Makefile @@ -1,16 +1,16 @@ REQUIREMENTS_FILE=dev-requirements.txt REQUIREMENTS_OUT=dev-requirements.txt.log SETUP_OUT=*.egg-info -VENV=.venv +VENV=venv clean: - rm -rf $(REQUIREMENTS_OUT) - rm -rf $(SETUP_OUT) - rm -rf $(VENV) - rm -rf .tox - rm -rf .coverage - find . -name "*.py[oc]" -delete - find . -name "__pycache__" -delete + rm -rf $(REQUIREMENTS_OUT) + rm -rf $(SETUP_OUT) + rm -rf $(VENV) + rm -rf .tox + rm -rf .coverage + find . -name "*.py[oc]" -delete + find . -name "__pycache__" -delete test: clean - bash ./test_python.sh + bash ./test_python.sh \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index d877696d65..7c9d0509b7 100644 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -9,7 +9,98 @@ This Python package is automatically generated by the [OpenAPI Generator](https: ## Requirements. -Python >=3.6 +Python >=3.7 + +## Migration from other generators like python and python-legacy + +### Changes +1. This generator uses spec case for all (object) property names and parameter names. + - So if the spec has a property name like camelCase, it will use camelCase rather than camel_case + - So you will need to update how you input and read properties to use spec case +2. Endpoint parameters are stored in dictionaries to prevent collisions (explanation below) + - So you will need to update how you pass data in to endpoints +3. Endpoint responses now include the original response, the deserialized response body, and (todo)the deserialized headers + - So you will need to update your code to use response.body to access deserialized data +4. All validated data is instantiated in an instance that subclasses all validated Schema classes and Decimal/str/list/tuple/frozendict/NoneClass/BoolClass/bytes/io.FileIO + - This means that you can use isinstance to check if a payload validated against a schema class + - This means that no data will be of type None/True/False + - ingested None will subclass NoneClass + - ingested True will subclass BoolClass + - ingested False will subclass BoolClass + - So if you need to check is True/False/None, instead use instance.is_true_oapg()/.is_false_oapg()/.is_none_oapg() +5. All validated class instances are immutable except for ones based on io.File + - This is because if properties were changed after validation, that validation would no longer apply + - So no changing values or property values after a class has been instantiated +6. String + Number types with formats + - String type data is stored as a string and if you need to access types based on its format like date, + date-time, uuid, number etc then you will need to use accessor functions on the instance + - type string + format: See .as_date_oapg, .as_datetime_oapg, .as_decimal_oapg, .as_uuid_oapg + - type number + format: See .as_float_oapg, .as_int_oapg + - this was done because openapi/json-schema defines constraints. string data may be type string with no format + keyword in one schema, and include a format constraint in another schema + - So if you need to access a string format based type, use as_date_oapg/as_datetime_oapg/as_decimal_oapg/as_uuid_oapg + - So if you need to access a number format based type, use as_int_oapg/as_float_oapg +7. Property access on AnyType(type unset) or object(dict) schemas + - Only required keys with valid python names are properties like .someProp and have type hints + - All optional keys may not exist, so properties are not defined for them + - One can access optional values with dict_instance['optionalProp'] and KeyError will be raised if it does not exist + - Use get_item_oapg if you need a way to always get a value whether or not the key exists + - If the key does not exist, schemas.unset is returned from calling dict_instance.get_item_oapg('optionalProp') + - All required and optional keys have type hints for this method, and @typing.overload is used + - A type hint is also generated for additionalProperties accessed using this method + - So you will need to update you code to use some_instance['optionalProp'] to access optional property + and additionalProperty values +8. The location of the api classes has changed + - Api classes are located in your_package.apis.tags.some_api + - This change was made to eliminate redundant code generation + - Legacy generators generated the same endpoint twice if it had > 1 tag on it + - This generator defines an endpoint in one class, then inherits that class to generate + apis by tags and by paths + - This change reduces code and allows quicker run time if you use the path apis + - path apis are at your_package.apis.paths.some_path + - Those apis will only load their needed models, which is less to load than all of the resources needed in a tag api + - So you will need to update your import paths to the api classes + +### Why are Oapg and _oapg used in class and method names? +Classes can have arbitrarily named properties set on them +Endpoints can have arbitrary operationId method names set +For those reasons, I use the prefix Oapg and _oapg to greatly reduce the likelihood of collisions +on protected + public classes/methods. +oapg stands for OpenApi Python Generator. + +### Object property spec case +This was done because when payloads are ingested, they can be validated against N number of schemas. +If the input signature used a different property name then that has mutated the payload. +So SchemaA and SchemaB must both see the camelCase spec named variable. +Also it is possible to send in two properties, named camelCase and camel_case in the same payload. +That use case should be support so spec case is used. + +### Parameter spec case +Parameters can be included in different locations including: +- query +- path +- header +- cookie + +Any of those parameters could use the same parameter names, so if every parameter +was included as an endpoint parameter in a function signature, they would collide. +For that reason, each of those inputs have been separated out into separate typed dictionaries: +- query_params +- path_params +- header_params +- cookie_params + +So when updating your code, you will need to pass endpoint parameters in using those +dictionaries. + +### Endpoint responses +Endpoint responses have been enriched to now include more information. +Any response reom an endpoint will now include the following properties: +response: urllib3.HTTPResponse +body: typing.Union[Unset, Schema] +headers: typing.Union[Unset, TODO] +Note: response header deserialization has not yet been added + ## Installation & Usage ### pip install @@ -45,11 +136,11 @@ import petstore_api Please follow the [installation procedure](#installation--usage) and then run the following: ```python -import datetime +import datetimeimport datetimeimport datetimeimport datetimeimport datetimeimport datetimeimport datetime import time import petstore_api from pprint import pprint -from petstore_api.api import another_fake_api +from petstore_api.apis.tags import another_fake_api from petstore_api.model.client import Client # Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 # See configuration.py for a list of all supported configuration parameters. @@ -58,7 +149,6 @@ configuration = petstore_api.Configuration( ) - # Enter a context with an instance of the API client with petstore_api.ApiClient(configuration) as api_client: # Create an instance of the API class @@ -81,162 +171,185 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags -*DefaultApi* | [**foo_get**](docs/DefaultApi.md#foo_get) | **GET** /foo | -*FakeApi* | [**additional_properties_with_array_of_enums**](docs/FakeApi.md#additional_properties_with_array_of_enums) | **GET** /fake/additional-properties-with-array-of-enums | Additional Properties with Array of Enums -*FakeApi* | [**array_model**](docs/FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | -*FakeApi* | [**array_of_enums**](docs/FakeApi.md#array_of_enums) | **POST** /fake/refs/array-of-enums | Array of Enums -*FakeApi* | [**boolean**](docs/FakeApi.md#boolean) | **POST** /fake/refs/boolean | -*FakeApi* | [**composed_one_of_number_with_validations**](docs/FakeApi.md#composed_one_of_number_with_validations) | **POST** /fake/refs/composed_one_of_number_with_validations | -*FakeApi* | [**download_attachment**](docs/FakeApi.md#download_attachment) | **GET** /{fileName} | downloads a file using Content-Disposition -*FakeApi* | [**enum_test**](docs/FakeApi.md#enum_test) | **POST** /fake/refs/enum-test | Object contains enum properties and array properties containing enums -*FakeApi* | [**fake_health_get**](docs/FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint -*FakeApi* | [**mammal**](docs/FakeApi.md#mammal) | **POST** /fake/refs/mammal | -*FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | -*FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | -*FakeApi* | [**post_inline_additional_properties_payload**](docs/FakeApi.md#post_inline_additional_properties_payload) | **POST** /fake/postInlineAdditionalPropertiesPayload | -*FakeApi* | [**post_inline_additional_properties_ref_payload**](docs/FakeApi.md#post_inline_additional_properties_ref_payload) | **POST** /fake/postInlineAdditionalPropertiesRefPayload | -*FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | -*FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | -*FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | -*FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | -*FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model -*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -*FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data -*FakeApi* | [**test_query_parameter_collection_format**](docs/FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | -*FakeApi* | [**tx_rx_all_of_model**](docs/FakeApi.md#tx_rx_all_of_model) | **POST** /fake/TxRxAllOfModel | -*FakeApi* | [**tx_rx_any_of_model**](docs/FakeApi.md#tx_rx_any_of_model) | **POST** /fake/TxRxAnyOfModel | -*FakeApi* | [**upload_download_file**](docs/FakeApi.md#upload_download_file) | **POST** /fake/uploadDownloadFile | uploads a file and downloads a file using application/octet-stream -*FakeApi* | [**upload_file**](docs/FakeApi.md#upload_file) | **POST** /fake/uploadFile | uploads a file using multipart/form-data -*FakeApi* | [**upload_files**](docs/FakeApi.md#upload_files) | **POST** /fake/uploadFiles | uploads files using multipart/form-data -*FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case -*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet -*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data -*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet -*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user -*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user -*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name -*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system -*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user - +*AnotherFakeApi* | [**call_123_test_special_tags**](docs/apis/tags/AnotherFakeApi.md#call_123_test_special_tags) | **patch** /another-fake/dummy | To test special tags +*DefaultApi* | [**foo_get**](docs/apis/tags/DefaultApi.md#foo_get) | **get** /foo | +*FakeApi* | [**additional_properties_with_array_of_enums**](docs/apis/tags/FakeApi.md#additional_properties_with_array_of_enums) | **get** /fake/additional-properties-with-array-of-enums | Additional Properties with Array of Enums +*FakeApi* | [**array_model**](docs/apis/tags/FakeApi.md#array_model) | **post** /fake/refs/arraymodel | +*FakeApi* | [**array_of_enums**](docs/apis/tags/FakeApi.md#array_of_enums) | **post** /fake/refs/array-of-enums | Array of Enums +*FakeApi* | [**body_with_file_schema**](docs/apis/tags/FakeApi.md#body_with_file_schema) | **put** /fake/body-with-file-schema | +*FakeApi* | [**body_with_query_params**](docs/apis/tags/FakeApi.md#body_with_query_params) | **put** /fake/body-with-query-params | +*FakeApi* | [**boolean**](docs/apis/tags/FakeApi.md#boolean) | **post** /fake/refs/boolean | +*FakeApi* | [**case_sensitive_params**](docs/apis/tags/FakeApi.md#case_sensitive_params) | **put** /fake/case-sensitive-params | +*FakeApi* | [**client_model**](docs/apis/tags/FakeApi.md#client_model) | **patch** /fake | To test \"client\" model +*FakeApi* | [**composed_one_of_different_types**](docs/apis/tags/FakeApi.md#composed_one_of_different_types) | **post** /fake/refs/composed_one_of_number_with_validations | +*FakeApi* | [**delete_coffee**](docs/apis/tags/FakeApi.md#delete_coffee) | **delete** /fake/deleteCoffee/{id} | Delete coffee +*FakeApi* | [**endpoint_parameters**](docs/apis/tags/FakeApi.md#endpoint_parameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**enum_parameters**](docs/apis/tags/FakeApi.md#enum_parameters) | **get** /fake | To test enum parameters +*FakeApi* | [**fake_health_get**](docs/apis/tags/FakeApi.md#fake_health_get) | **get** /fake/health | Health check endpoint +*FakeApi* | [**group_parameters**](docs/apis/tags/FakeApi.md#group_parameters) | **delete** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**inline_additional_properties**](docs/apis/tags/FakeApi.md#inline_additional_properties) | **post** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**inline_composition**](docs/apis/tags/FakeApi.md#inline_composition) | **post** /fake/inlineComposition/ | testing composed schemas at inline locations +*FakeApi* | [**json_form_data**](docs/apis/tags/FakeApi.md#json_form_data) | **get** /fake/jsonFormData | test json serialization of form data +*FakeApi* | [**json_patch**](docs/apis/tags/FakeApi.md#json_patch) | **patch** /fake/jsonPatch | json patch +*FakeApi* | [**json_with_charset**](docs/apis/tags/FakeApi.md#json_with_charset) | **post** /fake/jsonWithCharset | json with charset tx and rx +*FakeApi* | [**mammal**](docs/apis/tags/FakeApi.md#mammal) | **post** /fake/refs/mammal | +*FakeApi* | [**number_with_validations**](docs/apis/tags/FakeApi.md#number_with_validations) | **post** /fake/refs/number | +*FakeApi* | [**object_in_query**](docs/apis/tags/FakeApi.md#object_in_query) | **get** /fake/objInQuery | user list +*FakeApi* | [**object_model_with_ref_props**](docs/apis/tags/FakeApi.md#object_model_with_ref_props) | **post** /fake/refs/object_model_with_ref_props | +*FakeApi* | [**parameter_collisions**](docs/apis/tags/FakeApi.md#parameter_collisions) | **post** /fake/parameterCollisions/{1}/{aB}/{Ab}/{self}/{A-B}/ | parameter collision case +*FakeApi* | [**query_param_with_json_content_type**](docs/apis/tags/FakeApi.md#query_param_with_json_content_type) | **get** /fake/queryParamWithJsonContentType | query param with json content-type +*FakeApi* | [**query_parameter_collection_format**](docs/apis/tags/FakeApi.md#query_parameter_collection_format) | **put** /fake/test-query-paramters | +*FakeApi* | [**ref_object_in_query**](docs/apis/tags/FakeApi.md#ref_object_in_query) | **get** /fake/refObjInQuery | user list +*FakeApi* | [**response_without_schema**](docs/apis/tags/FakeApi.md#response_without_schema) | **get** /fake/responseWithoutSchema | receives a response without schema +*FakeApi* | [**string**](docs/apis/tags/FakeApi.md#string) | **post** /fake/refs/string | +*FakeApi* | [**string_enum**](docs/apis/tags/FakeApi.md#string_enum) | **post** /fake/refs/enum | +*FakeApi* | [**upload_download_file**](docs/apis/tags/FakeApi.md#upload_download_file) | **post** /fake/uploadDownloadFile | uploads a file and downloads a file using application/octet-stream +*FakeApi* | [**upload_file**](docs/apis/tags/FakeApi.md#upload_file) | **post** /fake/uploadFile | uploads a file using multipart/form-data +*FakeApi* | [**upload_files**](docs/apis/tags/FakeApi.md#upload_files) | **post** /fake/uploadFiles | uploads files using multipart/form-data +*FakeClassnameTags123Api* | [**classname**](docs/apis/tags/FakeClassnameTags123Api.md#classname) | **patch** /fake_classname_test | To test class name in snake case +*PetApi* | [**add_pet**](docs/apis/tags/PetApi.md#add_pet) | **post** /pet | Add a new pet to the store +*PetApi* | [**delete_pet**](docs/apis/tags/PetApi.md#delete_pet) | **delete** /pet/{petId} | Deletes a pet +*PetApi* | [**find_pets_by_status**](docs/apis/tags/PetApi.md#find_pets_by_status) | **get** /pet/findByStatus | Finds Pets by status +*PetApi* | [**find_pets_by_tags**](docs/apis/tags/PetApi.md#find_pets_by_tags) | **get** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/apis/tags/PetApi.md#get_pet_by_id) | **get** /pet/{petId} | Find pet by ID +*PetApi* | [**update_pet**](docs/apis/tags/PetApi.md#update_pet) | **put** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/apis/tags/PetApi.md#update_pet_with_form) | **post** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file_with_required_file**](docs/apis/tags/PetApi.md#upload_file_with_required_file) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*PetApi* | [**upload_image**](docs/apis/tags/PetApi.md#upload_image) | **post** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**delete_order**](docs/apis/tags/StoreApi.md#delete_order) | **delete** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**get_inventory**](docs/apis/tags/StoreApi.md#get_inventory) | **get** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_order_by_id**](docs/apis/tags/StoreApi.md#get_order_by_id) | **get** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/apis/tags/StoreApi.md#place_order) | **post** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/apis/tags/UserApi.md#create_user) | **post** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/apis/tags/UserApi.md#create_users_with_array_input) | **post** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/apis/tags/UserApi.md#create_users_with_list_input) | **post** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/apis/tags/UserApi.md#delete_user) | **delete** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/apis/tags/UserApi.md#get_user_by_name) | **get** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/apis/tags/UserApi.md#login_user) | **get** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/apis/tags/UserApi.md#logout_user) | **get** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/apis/tags/UserApi.md#update_user) | **put** /user/{username} | Updated user ## Documentation For Models - - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - - [AdditionalPropertiesWithArrayOfEnums](docs/AdditionalPropertiesWithArrayOfEnums.md) - - [Address](docs/Address.md) - - [Animal](docs/Animal.md) - - [AnimalFarm](docs/AnimalFarm.md) - - [ApiResponse](docs/ApiResponse.md) - - [Apple](docs/Apple.md) - - [AppleReq](docs/AppleReq.md) - - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - - [ArrayOfEnums](docs/ArrayOfEnums.md) - - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - - [ArrayTest](docs/ArrayTest.md) - - [Banana](docs/Banana.md) - - [BananaReq](docs/BananaReq.md) - - [BasquePig](docs/BasquePig.md) - - [BooleanEnum](docs/BooleanEnum.md) - - [Capitalization](docs/Capitalization.md) - - [Cat](docs/Cat.md) - - [CatAllOf](docs/CatAllOf.md) - - [Category](docs/Category.md) - - [ChildCat](docs/ChildCat.md) - - [ChildCatAllOf](docs/ChildCatAllOf.md) - - [ClassModel](docs/ClassModel.md) - - [Client](docs/Client.md) - - [ComplexQuadrilateral](docs/ComplexQuadrilateral.md) - - [ComposedOneOfNumberWithValidations](docs/ComposedOneOfNumberWithValidations.md) - - [ComposedSchemaWithPropsAndNoAddProps](docs/ComposedSchemaWithPropsAndNoAddProps.md) - - [DanishPig](docs/DanishPig.md) - - [Dog](docs/Dog.md) - - [DogAllOf](docs/DogAllOf.md) - - [Drawing](docs/Drawing.md) - - [EgressThresholdOptions](docs/EgressThresholdOptions.md) - - [EnumArrays](docs/EnumArrays.md) - - [EnumClass](docs/EnumClass.md) - - [EnumTest](docs/EnumTest.md) - - [EquilateralTriangle](docs/EquilateralTriangle.md) - - [File](docs/File.md) - - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - - [Foo](docs/Foo.md) - - [FooGetDefaultResponse](docs/FooGetDefaultResponse.md) - - [FooObject](docs/FooObject.md) - - [FormatTest](docs/FormatTest.md) - - [Fruit](docs/Fruit.md) - - [FruitReq](docs/FruitReq.md) - - [GmFruit](docs/GmFruit.md) - - [GmFruitNoProperties](docs/GmFruitNoProperties.md) - - [GrandparentAnimal](docs/GrandparentAnimal.md) - - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - - [HealthCheckResult](docs/HealthCheckResult.md) - - [InlineAdditionalPropertiesRefPayload](docs/InlineAdditionalPropertiesRefPayload.md) - - [IntegerEnum](docs/IntegerEnum.md) - - [IntegerEnumOneValue](docs/IntegerEnumOneValue.md) - - [IntegerEnumWithDefaultValue](docs/IntegerEnumWithDefaultValue.md) - - [IsoscelesTriangle](docs/IsoscelesTriangle.md) - - [Legs](docs/Legs.md) - - [List](docs/List.md) - - [Mammal](docs/Mammal.md) - - [MapTest](docs/MapTest.md) - - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - - [Model200Response](docs/Model200Response.md) - - [ModelReturn](docs/ModelReturn.md) - - [Mole](docs/Mole.md) - - [Name](docs/Name.md) - - [NullableClass](docs/NullableClass.md) - - [NullableShape](docs/NullableShape.md) - - [NumberOnly](docs/NumberOnly.md) - - [NumberWithValidations](docs/NumberWithValidations.md) - - [ObjectInterface](docs/ObjectInterface.md) - - [ObjectModelWithRefProps](docs/ObjectModelWithRefProps.md) - - [ObjectWithValidations](docs/ObjectWithValidations.md) - - [Order](docs/Order.md) - - [ParentPet](docs/ParentPet.md) - - [Pet](docs/Pet.md) - - [Pig](docs/Pig.md) - - [PostInlineAdditionalPropertiesPayloadRequest](docs/PostInlineAdditionalPropertiesPayloadRequest.md) - - [PostInlineAdditionalPropertiesPayloadRequestArrayDataInner](docs/PostInlineAdditionalPropertiesPayloadRequestArrayDataInner.md) - - [PublishOptions](docs/PublishOptions.md) - - [PublishOptionsPublish](docs/PublishOptionsPublish.md) - - [Quadrilateral](docs/Quadrilateral.md) - - [QuadrilateralInterface](docs/QuadrilateralInterface.md) - - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - - [Readonly](docs/Readonly.md) - - [ScaleneTriangle](docs/ScaleneTriangle.md) - - [Shape](docs/Shape.md) - - [ShapeInterface](docs/ShapeInterface.md) - - [ShapeOrNull](docs/ShapeOrNull.md) - - [SimpleQuadrilateral](docs/SimpleQuadrilateral.md) - - [SomeObject](docs/SomeObject.md) - - [SomeObjectWithSelfAttr](docs/SomeObjectWithSelfAttr.md) - - [SpecialModelName](docs/SpecialModelName.md) - - [StreamOptions](docs/StreamOptions.md) - - [StringBooleanMap](docs/StringBooleanMap.md) - - [StringEnum](docs/StringEnum.md) - - [StringEnumWithDefaultValue](docs/StringEnumWithDefaultValue.md) - - [Tag](docs/Tag.md) - - [Triangle](docs/Triangle.md) - - [TriangleInterface](docs/TriangleInterface.md) - - [User](docs/User.md) - - [Whale](docs/Whale.md) - - [Zebra](docs/Zebra.md) - + - [AdditionalPropertiesClass](docs/models/AdditionalPropertiesClass.md) + - [AdditionalPropertiesValidator](docs/models/AdditionalPropertiesValidator.md) + - [AdditionalPropertiesWithArrayOfEnums](docs/models/AdditionalPropertiesWithArrayOfEnums.md) + - [Address](docs/models/Address.md) + - [Animal](docs/models/Animal.md) + - [AnimalFarm](docs/models/AnimalFarm.md) + - [AnyTypeAndFormat](docs/models/AnyTypeAndFormat.md) + - [AnyTypeNotString](docs/models/AnyTypeNotString.md) + - [ApiResponse](docs/models/ApiResponse.md) + - [Apple](docs/models/Apple.md) + - [AppleReq](docs/models/AppleReq.md) + - [ArrayHoldingAnyType](docs/models/ArrayHoldingAnyType.md) + - [ArrayOfArrayOfNumberOnly](docs/models/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfEnums](docs/models/ArrayOfEnums.md) + - [ArrayOfNumberOnly](docs/models/ArrayOfNumberOnly.md) + - [ArrayTest](docs/models/ArrayTest.md) + - [ArrayWithValidationsInItems](docs/models/ArrayWithValidationsInItems.md) + - [Banana](docs/models/Banana.md) + - [BananaReq](docs/models/BananaReq.md) + - [Bar](docs/models/Bar.md) + - [BasquePig](docs/models/BasquePig.md) + - [Boolean](docs/models/Boolean.md) + - [BooleanEnum](docs/models/BooleanEnum.md) + - [Capitalization](docs/models/Capitalization.md) + - [Cat](docs/models/Cat.md) + - [Category](docs/models/Category.md) + - [ChildCat](docs/models/ChildCat.md) + - [ClassModel](docs/models/ClassModel.md) + - [Client](docs/models/Client.md) + - [ComplexQuadrilateral](docs/models/ComplexQuadrilateral.md) + - [ComposedAnyOfDifferentTypesNoValidations](docs/models/ComposedAnyOfDifferentTypesNoValidations.md) + - [ComposedArray](docs/models/ComposedArray.md) + - [ComposedBool](docs/models/ComposedBool.md) + - [ComposedNone](docs/models/ComposedNone.md) + - [ComposedNumber](docs/models/ComposedNumber.md) + - [ComposedObject](docs/models/ComposedObject.md) + - [ComposedOneOfDifferentTypes](docs/models/ComposedOneOfDifferentTypes.md) + - [ComposedString](docs/models/ComposedString.md) + - [Currency](docs/models/Currency.md) + - [DanishPig](docs/models/DanishPig.md) + - [DateTimeTest](docs/models/DateTimeTest.md) + - [DateTimeWithValidations](docs/models/DateTimeWithValidations.md) + - [DateWithValidations](docs/models/DateWithValidations.md) + - [DecimalPayload](docs/models/DecimalPayload.md) + - [Dog](docs/models/Dog.md) + - [Drawing](docs/models/Drawing.md) + - [EnumArrays](docs/models/EnumArrays.md) + - [EnumClass](docs/models/EnumClass.md) + - [EnumTest](docs/models/EnumTest.md) + - [EquilateralTriangle](docs/models/EquilateralTriangle.md) + - [File](docs/models/File.md) + - [FileSchemaTestClass](docs/models/FileSchemaTestClass.md) + - [Foo](docs/models/Foo.md) + - [FormatTest](docs/models/FormatTest.md) + - [FromSchema](docs/models/FromSchema.md) + - [Fruit](docs/models/Fruit.md) + - [FruitReq](docs/models/FruitReq.md) + - [GmFruit](docs/models/GmFruit.md) + - [GrandparentAnimal](docs/models/GrandparentAnimal.md) + - [HasOnlyReadOnly](docs/models/HasOnlyReadOnly.md) + - [HealthCheckResult](docs/models/HealthCheckResult.md) + - [IntegerEnum](docs/models/IntegerEnum.md) + - [IntegerEnumBig](docs/models/IntegerEnumBig.md) + - [IntegerEnumOneValue](docs/models/IntegerEnumOneValue.md) + - [IntegerEnumWithDefaultValue](docs/models/IntegerEnumWithDefaultValue.md) + - [IntegerMax10](docs/models/IntegerMax10.md) + - [IntegerMin15](docs/models/IntegerMin15.md) + - [IsoscelesTriangle](docs/models/IsoscelesTriangle.md) + - [JSONPatchRequest](docs/models/JSONPatchRequest.md) + - [JSONPatchRequestAddReplaceTest](docs/models/JSONPatchRequestAddReplaceTest.md) + - [JSONPatchRequestMoveCopy](docs/models/JSONPatchRequestMoveCopy.md) + - [JSONPatchRequestRemove](docs/models/JSONPatchRequestRemove.md) + - [Mammal](docs/models/Mammal.md) + - [MapTest](docs/models/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/models/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/models/Model200Response.md) + - [ModelReturn](docs/models/ModelReturn.md) + - [Money](docs/models/Money.md) + - [Name](docs/models/Name.md) + - [NoAdditionalProperties](docs/models/NoAdditionalProperties.md) + - [NullableClass](docs/models/NullableClass.md) + - [NullableShape](docs/models/NullableShape.md) + - [NullableString](docs/models/NullableString.md) + - [Number](docs/models/Number.md) + - [NumberOnly](docs/models/NumberOnly.md) + - [NumberWithValidations](docs/models/NumberWithValidations.md) + - [ObjectInterface](docs/models/ObjectInterface.md) + - [ObjectModelWithRefProps](docs/models/ObjectModelWithRefProps.md) + - [ObjectWithDecimalProperties](docs/models/ObjectWithDecimalProperties.md) + - [ObjectWithDifficultlyNamedProps](docs/models/ObjectWithDifficultlyNamedProps.md) + - [ObjectWithInlineCompositionProperty](docs/models/ObjectWithInlineCompositionProperty.md) + - [ObjectWithInvalidNamedRefedProperties](docs/models/ObjectWithInvalidNamedRefedProperties.md) + - [ObjectWithValidations](docs/models/ObjectWithValidations.md) + - [Order](docs/models/Order.md) + - [ParentPet](docs/models/ParentPet.md) + - [Pet](docs/models/Pet.md) + - [Pig](docs/models/Pig.md) + - [Player](docs/models/Player.md) + - [Quadrilateral](docs/models/Quadrilateral.md) + - [QuadrilateralInterface](docs/models/QuadrilateralInterface.md) + - [ReadOnlyFirst](docs/models/ReadOnlyFirst.md) + - [ScaleneTriangle](docs/models/ScaleneTriangle.md) + - [Shape](docs/models/Shape.md) + - [ShapeOrNull](docs/models/ShapeOrNull.md) + - [SimpleQuadrilateral](docs/models/SimpleQuadrilateral.md) + - [SomeObject](docs/models/SomeObject.md) + - [SpecialModelName](docs/models/SpecialModelName.md) + - [String](docs/models/String.md) + - [StringBooleanMap](docs/models/StringBooleanMap.md) + - [StringEnum](docs/models/StringEnum.md) + - [StringEnumWithDefaultValue](docs/models/StringEnumWithDefaultValue.md) + - [StringWithValidation](docs/models/StringWithValidation.md) + - [Tag](docs/models/Tag.md) + - [Triangle](docs/models/Triangle.md) + - [TriangleInterface](docs/models/TriangleInterface.md) + - [UUIDString](docs/models/UUIDString.md) + - [User](docs/models/User.md) + - [Whale](docs/models/Whale.md) + - [Zebra](docs/models/Zebra.md) ## Documentation For Authorization @@ -269,7 +382,7 @@ Class | Method | HTTP request | Description - **Type**: HTTP signature authentication - + Authentication schemes defined for the API: ## petstore_auth - **Type**: OAuth @@ -285,16 +398,21 @@ Class | Method | HTTP request | Description + + + + + ## Notes for Large OpenAPI documents If the OpenAPI document is large, imports in petstore_api.apis and petstore_api.models may fail with a RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: Solution 1: Use specific imports for apis and models like: -- `from petstore_api.api.default_api import DefaultApi` +- `from petstore_api.apis.default_api import DefaultApi` - `from petstore_api.model.pet import Pet` -Solution 2: +Solution 1: Before importing the package, adjust the maximum recursion limit as shown below: ``` import sys @@ -303,4 +421,3 @@ import petstore_api from petstore_api.apis import * from petstore_api.models import * ``` - diff --git a/samples/openapi3/client/petstore/python/docs/FakeApi.md b/samples/openapi3/client/petstore/python/docs/FakeApi.md deleted file mode 100644 index 97d25d3a01..0000000000 --- a/samples/openapi3/client/petstore/python/docs/FakeApi.md +++ /dev/null @@ -1,2141 +0,0 @@ -# petstore_api.FakeApi - -All URIs are relative to *http://petstore.swagger.io:80/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**additional_properties_with_array_of_enums**](FakeApi.md#additional_properties_with_array_of_enums) | **GET** /fake/additional-properties-with-array-of-enums | Additional Properties with Array of Enums -[**array_model**](FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | -[**array_of_enums**](FakeApi.md#array_of_enums) | **POST** /fake/refs/array-of-enums | Array of Enums -[**boolean**](FakeApi.md#boolean) | **POST** /fake/refs/boolean | -[**composed_one_of_number_with_validations**](FakeApi.md#composed_one_of_number_with_validations) | **POST** /fake/refs/composed_one_of_number_with_validations | -[**download_attachment**](FakeApi.md#download_attachment) | **GET** /{fileName} | downloads a file using Content-Disposition -[**enum_test**](FakeApi.md#enum_test) | **POST** /fake/refs/enum-test | Object contains enum properties and array properties containing enums -[**fake_health_get**](FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint -[**mammal**](FakeApi.md#mammal) | **POST** /fake/refs/mammal | -[**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | -[**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | -[**post_inline_additional_properties_payload**](FakeApi.md#post_inline_additional_properties_payload) | **POST** /fake/postInlineAdditionalPropertiesPayload | -[**post_inline_additional_properties_ref_payload**](FakeApi.md#post_inline_additional_properties_ref_payload) | **POST** /fake/postInlineAdditionalPropertiesRefPayload | -[**string**](FakeApi.md#string) | **POST** /fake/refs/string | -[**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | -[**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | -[**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | -[**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model -[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters -[**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) -[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties -[**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data -[**test_query_parameter_collection_format**](FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | -[**tx_rx_all_of_model**](FakeApi.md#tx_rx_all_of_model) | **POST** /fake/TxRxAllOfModel | -[**tx_rx_any_of_model**](FakeApi.md#tx_rx_any_of_model) | **POST** /fake/TxRxAnyOfModel | -[**upload_download_file**](FakeApi.md#upload_download_file) | **POST** /fake/uploadDownloadFile | uploads a file and downloads a file using application/octet-stream -[**upload_file**](FakeApi.md#upload_file) | **POST** /fake/uploadFile | uploads a file using multipart/form-data -[**upload_files**](FakeApi.md#upload_files) | **POST** /fake/uploadFiles | uploads files using multipart/form-data - - -# **additional_properties_with_array_of_enums** -> AdditionalPropertiesWithArrayOfEnums additional_properties_with_array_of_enums() - -Additional Properties with Array of Enums - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - additional_properties_with_array_of_enums = AdditionalPropertiesWithArrayOfEnums( - key=[ - EnumClass("-efg"), - ], - ) # AdditionalPropertiesWithArrayOfEnums | Input enum (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - # Additional Properties with Array of Enums - api_response = api_instance.additional_properties_with_array_of_enums(additional_properties_with_array_of_enums=additional_properties_with_array_of_enums) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->additional_properties_with_array_of_enums: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **additional_properties_with_array_of_enums** | [**AdditionalPropertiesWithArrayOfEnums**](AdditionalPropertiesWithArrayOfEnums.md)| Input enum | [optional] - -### Return type - -[**AdditionalPropertiesWithArrayOfEnums**](AdditionalPropertiesWithArrayOfEnums.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Got object with additional properties with array of enums | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **array_model** -> AnimalFarm array_model() - - - -Test serialization of ArrayModel - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.animal_farm import AnimalFarm -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = AnimalFarm([ - Animal(), - ]) # AnimalFarm | Input model (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.array_model(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->array_model: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**AnimalFarm**](AnimalFarm.md)| Input model | [optional] - -### Return type - -[**AnimalFarm**](AnimalFarm.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output model | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **array_of_enums** -> ArrayOfEnums array_of_enums() - -Array of Enums - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.array_of_enums import ArrayOfEnums -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - array_of_enums = ArrayOfEnums([ - StringEnum("placed"), - ]) # ArrayOfEnums | Input enum (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - # Array of Enums - api_response = api_instance.array_of_enums(array_of_enums=array_of_enums) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->array_of_enums: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **array_of_enums** | [**ArrayOfEnums**](ArrayOfEnums.md)| Input enum | [optional] - -### Return type - -[**ArrayOfEnums**](ArrayOfEnums.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Got named array of enums | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **boolean** -> bool boolean() - - - -Test serialization of outer boolean types - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = True # bool | Input boolean as post body (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.boolean(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->boolean: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **bool**| Input boolean as post body | [optional] - -### Return type - -**bool** - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output boolean | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **composed_one_of_number_with_validations** -> ComposedOneOfNumberWithValidations composed_one_of_number_with_validations() - - - -Test serialization of object with $refed properties - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.composed_one_of_number_with_validations import ComposedOneOfNumberWithValidations -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - composed_one_of_number_with_validations = ComposedOneOfNumberWithValidations(None) # ComposedOneOfNumberWithValidations | Input model (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.composed_one_of_number_with_validations(composed_one_of_number_with_validations=composed_one_of_number_with_validations) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->composed_one_of_number_with_validations: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **composed_one_of_number_with_validations** | [**ComposedOneOfNumberWithValidations**](ComposedOneOfNumberWithValidations.md)| Input model | [optional] - -### Return type - -[**ComposedOneOfNumberWithValidations**](ComposedOneOfNumberWithValidations.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output model | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **download_attachment** -> file_type download_attachment(file_name) - -downloads a file using Content-Disposition - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - file_name = "fileName_example" # str | file name - - # example passing only required values which don't have defaults set - try: - # downloads a file using Content-Disposition - api_response = api_instance.download_attachment(file_name) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->download_attachment: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **file_name** | **str**| file name | - -### Return type - -**file_type** - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: text/plain - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | * Content-Disposition - describes the received file. Looks like: 'attachment; filename=fileName.txt'
        | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **enum_test** -> EnumTest enum_test() - -Object contains enum properties and array properties containing enums - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.enum_test import EnumTest -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - enum_test = EnumTest( - enum_string="UPPER", - enum_string_required="UPPER", - enum_integer=1, - enum_number=1.1, - enum_bool=False, - bool_enum=BooleanEnum(True), - string_enum=StringEnum("placed"), - integer_enum=IntegerEnum(0), - string_enum_with_default_value=StringEnumWithDefaultValue("placed"), - integer_enum_with_default_value=IntegerEnumWithDefaultValue(0), - integer_enum_one_value=IntegerEnumOneValue(0), - inline_array_of_str_enum=[ - StringEnum("placed"), - ], - array_of_str_enum=ArrayOfEnums([ - StringEnum("placed"), - ]), - ) # EnumTest | Input object (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - # Object contains enum properties and array properties containing enums - api_response = api_instance.enum_test(enum_test=enum_test) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->enum_test: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **enum_test** | [**EnumTest**](EnumTest.md)| Input object | [optional] - -### Return type - -[**EnumTest**](EnumTest.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Got object containing enums | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **fake_health_get** -> HealthCheckResult fake_health_get() - -Health check endpoint - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.health_check_result import HealthCheckResult -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - - # example, this endpoint has no required or optional parameters - try: - # Health check endpoint - api_response = api_instance.fake_health_get() - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->fake_health_get: %s\n" % e) -``` - - -### Parameters -This endpoint does not need any parameter. - -### Return type - -[**HealthCheckResult**](HealthCheckResult.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | The instance started successfully | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **mammal** -> Mammal mammal(mammal) - - - -Test serialization of mammals - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.mammal import Mammal -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - mammal = Mammal(None) # Mammal | Input mammal - - # example passing only required values which don't have defaults set - try: - api_response = api_instance.mammal(mammal) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->mammal: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **mammal** | [**Mammal**](Mammal.md)| Input mammal | - -### Return type - -[**Mammal**](Mammal.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output mammal | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **number_with_validations** -> NumberWithValidations number_with_validations() - - - -Test serialization of outer number types - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.number_with_validations import NumberWithValidations -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = NumberWithValidations(10) # NumberWithValidations | Input number as post body (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.number_with_validations(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->number_with_validations: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**NumberWithValidations**](NumberWithValidations.md)| Input number as post body | [optional] - -### Return type - -[**NumberWithValidations**](NumberWithValidations.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output number | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **object_model_with_ref_props** -> ObjectModelWithRefProps object_model_with_ref_props() - - - -Test serialization of object with $refed properties - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = ObjectModelWithRefProps( - my_number=NumberWithValidations(10), - my_string="my_string_example", - my_boolean=True, - ) # ObjectModelWithRefProps | Input model (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.object_model_with_ref_props(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**ObjectModelWithRefProps**](ObjectModelWithRefProps.md)| Input model | [optional] - -### Return type - -[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output model | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **post_inline_additional_properties_payload** -> PostInlineAdditionalPropertiesPayloadRequest post_inline_additional_properties_payload() - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.post_inline_additional_properties_payload_request import PostInlineAdditionalPropertiesPayloadRequest -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - post_inline_additional_properties_payload_request = PostInlineAdditionalPropertiesPayloadRequest( - array_data=[ - PostInlineAdditionalPropertiesPayloadRequestArrayDataInner( - labels=[ - "labels_example", - ], - ), - ], - ) # PostInlineAdditionalPropertiesPayloadRequest | (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.post_inline_additional_properties_payload(post_inline_additional_properties_payload_request=post_inline_additional_properties_payload_request) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->post_inline_additional_properties_payload: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **post_inline_additional_properties_payload_request** | [**PostInlineAdditionalPropertiesPayloadRequest**](PostInlineAdditionalPropertiesPayloadRequest.md)| | [optional] - -### Return type - -[**PostInlineAdditionalPropertiesPayloadRequest**](PostInlineAdditionalPropertiesPayloadRequest.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | InlineAdditionalPropertiesPayload | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **post_inline_additional_properties_ref_payload** -> InlineAdditionalPropertiesRefPayload post_inline_additional_properties_ref_payload() - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( - array_data=[ - PostInlineAdditionalPropertiesPayloadRequestArrayDataInner( - labels=[ - "labels_example", - ], - ), - ], - ) # InlineAdditionalPropertiesRefPayload | (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.post_inline_additional_properties_ref_payload(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->post_inline_additional_properties_ref_payload: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **inline_additional_properties_ref_payload** | [**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md)| | [optional] - -### Return type - -[**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | InlineAdditionalPropertiesRefPayload | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **string** -> str string() - - - -Test serialization of outer string types - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = "body_example" # str | Input string as post body (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.string(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->string: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **str**| Input string as post body | [optional] - -### Return type - -**str** - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output string | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **string_enum** -> StringEnum string_enum() - - - -Test serialization of outer enum - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.string_enum import StringEnum -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = StringEnum("placed") # StringEnum | Input enum (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.string_enum(body=body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->string_enum: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**StringEnum**](StringEnum.md)| Input enum | [optional] - -### Return type - -[**StringEnum**](StringEnum.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Output enum | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_body_with_file_schema** -> test_body_with_file_schema(file_schema_test_class) - - - -For this test, the body for this request much reference a schema named `File`. - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.file_schema_test_class import FileSchemaTestClass -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - file_schema_test_class = FileSchemaTestClass( - file=File( - source_uri="source_uri_example", - ), - files=[ - File( - source_uri="source_uri_example", - ), - ], - ) # FileSchemaTestClass | - - # example passing only required values which don't have defaults set - try: - api_instance.test_body_with_file_schema(file_schema_test_class) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_body_with_file_schema: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **file_schema_test_class** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_body_with_query_params** -> test_body_with_query_params(query, user) - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.user import User -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - query = "query_example" # str | - user = User( - id=1, - username="username_example", - first_name="first_name_example", - last_name="last_name_example", - email="email_example", - password="password_example", - phone="phone_example", - user_status=1, - object_with_no_declared_props={}, - object_with_no_declared_props_nullable={}, - any_type_prop=None, - any_type_prop_nullable=None, - ) # User | - - # example passing only required values which don't have defaults set - try: - api_instance.test_body_with_query_params(query, user) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_body_with_query_params: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **query** | **str**| | - **user** | [**User**](User.md)| | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_client_model** -> Client test_client_model(client) - -To test \"client\" model - -To test \"client\" model - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.client import Client -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - client = Client( - client="client_example", - ) # Client | client model - - # example passing only required values which don't have defaults set - try: - # To test \"client\" model - api_response = api_instance.test_client_model(client) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_client_model: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md)| client model | - -### Return type - -[**Client**](Client.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_endpoint_parameters** -> test_endpoint_parameters(number, double, pattern_without_delimiter, byte) - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - -### Example - -* Basic Authentication (http_basic_test): - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure HTTP basic authorization: http_basic_test -configuration = petstore_api.Configuration( - username = 'YOUR_USERNAME', - password = 'YOUR_PASSWORD' -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - number = 32.1 # float | None - double = 67.8 # float | None - pattern_without_delimiter = "Aj" # str | None - byte = 'YQ==' # str | None - integer = 10 # int | None (optional) - int32 = 20 # int | None (optional) - int64 = 1 # int | None (optional) - float = 3.14 # float | None (optional) - string = "A" # str | None (optional) - binary = open('/path/to/file', 'rb') # file_type | None (optional) - date = dateutil_parser('1970-01-01').date() # date | None (optional) - date_time = dateutil_parser('2020-02-02T20:20:20.22222Z') # datetime | None (optional) if omitted the server will use the default value of dateutil_parser('2010-02-01T10:20:10.11111+01:00') - password = "password_example" # str | None (optional) - param_callback = "param_callback_example" # str | None (optional) - - # example passing only required values which don't have defaults set - try: - # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) - - # example passing only required values which don't have defaults set - # and optional values - try: - # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **number** | **float**| None | - **double** | **float**| None | - **pattern_without_delimiter** | **str**| None | - **byte** | **str**| None | - **integer** | **int**| None | [optional] - **int32** | **int**| None | [optional] - **int64** | **int**| None | [optional] - **float** | **float**| None | [optional] - **string** | **str**| None | [optional] - **binary** | **file_type**| None | [optional] - **date** | **date**| None | [optional] - **date_time** | **datetime**| None | [optional] if omitted the server will use the default value of dateutil_parser('2010-02-01T10:20:10.11111+01:00') - **password** | **str**| None | [optional] - **param_callback** | **str**| None | [optional] - -### Return type - -void (empty response body) - -### Authorization - -[http_basic_test](../README.md#http_basic_test) - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**400** | Invalid username supplied | - | -**404** | User not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_enum_parameters** -> test_enum_parameters() - -To test enum parameters - -To test enum parameters - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - enum_header_string_array = [ - "$", - ] # [str] | Header parameter enum test (string array) (optional) - enum_header_string = "-efg" # str | Header parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" - enum_query_string_array = [ - "$", - ] # [str] | Query parameter enum test (string array) (optional) - enum_query_string = "-efg" # str | Query parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" - enum_query_integer = 1 # int | Query parameter enum test (double) (optional) - enum_query_double = 1.1 # float | Query parameter enum test (double) (optional) - enum_form_string_array = [ - "$", - ] # [str] | Form parameter enum test (string array) (optional) if omitted the server will use the default value of "$" - enum_form_string = "-efg" # str | Form parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" - - # example passing only required values which don't have defaults set - # and optional values - try: - # To test enum parameters - api_instance.test_enum_parameters(enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double, enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **enum_header_string_array** | **[str]**| Header parameter enum test (string array) | [optional] - **enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" - **enum_query_string_array** | **[str]**| Query parameter enum test (string array) | [optional] - **enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" - **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] - **enum_query_double** | **float**| Query parameter enum test (double) | [optional] - **enum_form_string_array** | **[str]**| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of "$" - **enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**400** | Invalid request | - | -**404** | Not found | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_group_parameters** -> test_group_parameters(required_string_group, required_boolean_group, required_int64_group) - -Fake endpoint to test group parameters (optional) - -Fake endpoint to test group parameters (optional) - -### Example - -* Bearer (JWT) Authentication (bearer_test): - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - -# The client must configure the authentication and authorization parameters -# in accordance with the API server security policy. -# Examples for each auth method are provided below, use the example that -# satisfies your auth use case. - -# Configure Bearer authorization (JWT): bearer_test -configuration = petstore_api.Configuration( - access_token = 'YOUR_BEARER_TOKEN' -) - -# Enter a context with an instance of the API client -with petstore_api.ApiClient(configuration) as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - required_string_group = 1 # int | Required String in group parameters - required_boolean_group = True # bool | Required Boolean in group parameters - required_int64_group = 1 # int | Required Integer in group parameters - string_group = 1 # int | String in group parameters (optional) - boolean_group = True # bool | Boolean in group parameters (optional) - int64_group = 1 # int | Integer in group parameters (optional) - - # example passing only required values which don't have defaults set - try: - # Fake endpoint to test group parameters (optional) - api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) - - # example passing only required values which don't have defaults set - # and optional values - try: - # Fake endpoint to test group parameters (optional) - api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **required_string_group** | **int**| Required String in group parameters | - **required_boolean_group** | **bool**| Required Boolean in group parameters | - **required_int64_group** | **int**| Required Integer in group parameters | - **string_group** | **int**| String in group parameters | [optional] - **boolean_group** | **bool**| Boolean in group parameters | [optional] - **int64_group** | **int**| Integer in group parameters | [optional] - -### Return type - -void (empty response body) - -### Authorization - -[bearer_test](../README.md#bearer_test) - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**400** | Someting wrong | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_inline_additional_properties** -> test_inline_additional_properties(request_body) - -test inline additionalProperties - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - request_body = { - "key": "key_example", - } # {str: (str,)} | request body - - # example passing only required values which don't have defaults set - try: - # test inline additionalProperties - api_instance.test_inline_additional_properties(request_body) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **request_body** | **{str: (str,)}**| request body | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_json_form_data** -> test_json_form_data(param, param2) - -test json serialization of form data - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - param = "param_example" # str | field1 - param2 = "param2_example" # str | field2 - - # example passing only required values which don't have defaults set - try: - # test json serialization of form data - api_instance.test_json_form_data(param, param2) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_json_form_data: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **param** | **str**| field1 | - **param2** | **str**| field2 | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **test_query_parameter_collection_format** -> test_query_parameter_collection_format(pipe, ioutil, http, url, context) - - - -To test the collection format in query parameters - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - pipe = [ - "pipe_example", - ] # [str] | - ioutil = [ - "ioutil_example", - ] # [str] | - http = [ - "http_example", - ] # [str] | - url = [ - "url_example", - ] # [str] | - context = [ - "context_example", - ] # [str] | - - # example passing only required values which don't have defaults set - try: - api_instance.test_query_parameter_collection_format(pipe, ioutil, http, url, context) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->test_query_parameter_collection_format: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **pipe** | **[str]**| | - **ioutil** | **[str]**| | - **http** | **[str]**| | - **url** | **[str]**| | - **context** | **[str]**| | - -### Return type - -void (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: Not defined - - **Accept**: Not defined - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | Success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **tx_rx_all_of_model** -> StreamOptions tx_rx_all_of_model() - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.stream_options import StreamOptions -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - stream_options = StreamOptions(None) # StreamOptions | (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.tx_rx_all_of_model(stream_options=stream_options) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->tx_rx_all_of_model: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **stream_options** | [**StreamOptions**](StreamOptions.md)| | [optional] - -### Return type - -[**StreamOptions**](StreamOptions.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | success | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **tx_rx_any_of_model** -> GmFruitNoProperties tx_rx_any_of_model() - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.gm_fruit_no_properties import GmFruitNoProperties -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - gm_fruit_no_properties = GmFruitNoProperties(None) # GmFruitNoProperties | (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.tx_rx_any_of_model(gm_fruit_no_properties=gm_fruit_no_properties) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->tx_rx_any_of_model: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **gm_fruit_no_properties** | [**GmFruitNoProperties**](GmFruitNoProperties.md)| | [optional] - -### Return type - -[**GmFruitNoProperties**](GmFruitNoProperties.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | TxRxAnyOfModel | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **upload_download_file** -> file_type upload_download_file(body) - -uploads a file and downloads a file using application/octet-stream - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - body = open('/path/to/file', 'rb') # file_type | - - # example passing only required values which don't have defaults set - try: - # uploads a file and downloads a file using application/octet-stream - api_response = api_instance.upload_download_file(body) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->upload_download_file: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | **file_type**| | - -### Return type - -**file_type** - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/octet-stream - - **Accept**: application/octet-stream - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **upload_file** -> ApiResponse upload_file(file) - -uploads a file using multipart/form-data - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.api_response import ApiResponse -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - file = open('/path/to/file', 'rb') # file_type | file to upload - additional_metadata = "additional_metadata_example" # str | Additional data to pass to server (optional) - - # example passing only required values which don't have defaults set - try: - # uploads a file using multipart/form-data - api_response = api_instance.upload_file(file) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->upload_file: %s\n" % e) - - # example passing only required values which don't have defaults set - # and optional values - try: - # uploads a file using multipart/form-data - api_response = api_instance.upload_file(file, additional_metadata=additional_metadata) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->upload_file: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **file** | **file_type**| file to upload | - **additional_metadata** | **str**| Additional data to pass to server | [optional] - -### Return type - -[**ApiResponse**](ApiResponse.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: multipart/form-data - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - -# **upload_files** -> ApiResponse upload_files() - -uploads files using multipart/form-data - - - -### Example - - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.api_response import ApiResponse -from pprint import pprint -# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 -# See configuration.py for a list of all supported configuration parameters. -configuration = petstore_api.Configuration( - host = "http://petstore.swagger.io:80/v2" -) - - -# Enter a context with an instance of the API client -with petstore_api.ApiClient() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - files = [ - open('/path/to/file', 'rb'), - ] # [file_type] | (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - # uploads files using multipart/form-data - api_response = api_instance.upload_files(files=files) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->upload_files: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **files** | **[file_type]**| | [optional] - -### Return type - -[**ApiResponse**](ApiResponse.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: multipart/form-data - - **Accept**: application/json - - -### HTTP response details - -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | successful operation | - | - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - diff --git a/samples/openapi3/client/petstore/python/docs/apis/tags/AnotherFakeApi.md b/samples/openapi3/client/petstore/python/docs/apis/tags/AnotherFakeApi.md new file mode 100644 index 0000000000..2a76dabc35 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/apis/tags/AnotherFakeApi.md @@ -0,0 +1,93 @@ + +# petstore_api.apis.tags.another_fake_api.AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call_123_test_special_tags**](#call_123_test_special_tags) | **patch** /another-fake/dummy | To test special tags + +# **call_123_test_special_tags** + +> Client call_123_test_special_tags(client) + +To test special tags + +To test special tags and operation ID starting with number + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import another_fake_api +from petstore_api.model.client import Client +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = another_fake_api.AnotherFakeApi(api_client) + + # example passing only required values which don't have defaults set + body = Client( + client="client_example", + ) + try: + # To test special tags + api_response = api_instance.call_123_test_special_tags( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Client**](../../models/Client.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#call_123_test_special_tags.ApiResponseFor200) | successful operation + +#### call_123_test_special_tags.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Client**](../../models/Client.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/apis/tags/DefaultApi.md b/samples/openapi3/client/petstore/python/docs/apis/tags/DefaultApi.md new file mode 100644 index 0000000000..768d80a1c3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/apis/tags/DefaultApi.md @@ -0,0 +1,76 @@ + +# petstore_api.apis.tags.default_api.DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**foo_get**](#foo_get) | **get** /foo | + +# **foo_get** + +> {str: (bool, date, datetime, dict, float, int, list, str, none_type)} foo_get() + + + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import default_api +from petstore_api.model.foo import Foo +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = default_api.DefaultApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + api_response = api_instance.foo_get() + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling DefaultApi->foo_get: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +default | [ApiResponseForDefault](#foo_get.ApiResponseForDefault) | response + +#### foo_get.ApiResponseForDefault +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor0ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor0ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**string** | [**Foo**]({{complexTypePrefix}}Foo.md) | [**Foo**]({{complexTypePrefix}}Foo.md) | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/apis/tags/FakeApi.md b/samples/openapi3/client/petstore/python/docs/apis/tags/FakeApi.md new file mode 100644 index 0000000000..e869010286 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/apis/tags/FakeApi.md @@ -0,0 +1,3491 @@ + +# petstore_api.apis.tags.fake_api.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**additional_properties_with_array_of_enums**](#additional_properties_with_array_of_enums) | **get** /fake/additional-properties-with-array-of-enums | Additional Properties with Array of Enums +[**array_model**](#array_model) | **post** /fake/refs/arraymodel | +[**array_of_enums**](#array_of_enums) | **post** /fake/refs/array-of-enums | Array of Enums +[**body_with_file_schema**](#body_with_file_schema) | **put** /fake/body-with-file-schema | +[**body_with_query_params**](#body_with_query_params) | **put** /fake/body-with-query-params | +[**boolean**](#boolean) | **post** /fake/refs/boolean | +[**case_sensitive_params**](#case_sensitive_params) | **put** /fake/case-sensitive-params | +[**client_model**](#client_model) | **patch** /fake | To test \"client\" model +[**composed_one_of_different_types**](#composed_one_of_different_types) | **post** /fake/refs/composed_one_of_number_with_validations | +[**delete_coffee**](#delete_coffee) | **delete** /fake/deleteCoffee/{id} | Delete coffee +[**endpoint_parameters**](#endpoint_parameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**enum_parameters**](#enum_parameters) | **get** /fake | To test enum parameters +[**fake_health_get**](#fake_health_get) | **get** /fake/health | Health check endpoint +[**group_parameters**](#group_parameters) | **delete** /fake | Fake endpoint to test group parameters (optional) +[**inline_additional_properties**](#inline_additional_properties) | **post** /fake/inline-additionalProperties | test inline additionalProperties +[**inline_composition**](#inline_composition) | **post** /fake/inlineComposition/ | testing composed schemas at inline locations +[**json_form_data**](#json_form_data) | **get** /fake/jsonFormData | test json serialization of form data +[**json_patch**](#json_patch) | **patch** /fake/jsonPatch | json patch +[**json_with_charset**](#json_with_charset) | **post** /fake/jsonWithCharset | json with charset tx and rx +[**mammal**](#mammal) | **post** /fake/refs/mammal | +[**number_with_validations**](#number_with_validations) | **post** /fake/refs/number | +[**object_in_query**](#object_in_query) | **get** /fake/objInQuery | user list +[**object_model_with_ref_props**](#object_model_with_ref_props) | **post** /fake/refs/object_model_with_ref_props | +[**parameter_collisions**](#parameter_collisions) | **post** /fake/parameterCollisions/{1}/{aB}/{Ab}/{self}/{A-B}/ | parameter collision case +[**query_param_with_json_content_type**](#query_param_with_json_content_type) | **get** /fake/queryParamWithJsonContentType | query param with json content-type +[**query_parameter_collection_format**](#query_parameter_collection_format) | **put** /fake/test-query-paramters | +[**ref_object_in_query**](#ref_object_in_query) | **get** /fake/refObjInQuery | user list +[**response_without_schema**](#response_without_schema) | **get** /fake/responseWithoutSchema | receives a response without schema +[**string**](#string) | **post** /fake/refs/string | +[**string_enum**](#string_enum) | **post** /fake/refs/enum | +[**upload_download_file**](#upload_download_file) | **post** /fake/uploadDownloadFile | uploads a file and downloads a file using application/octet-stream +[**upload_file**](#upload_file) | **post** /fake/uploadFile | uploads a file using multipart/form-data +[**upload_files**](#upload_files) | **post** /fake/uploadFiles | uploads files using multipart/form-data + +# **additional_properties_with_array_of_enums** + +> AdditionalPropertiesWithArrayOfEnums additional_properties_with_array_of_enums() + +Additional Properties with Array of Enums + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = AdditionalPropertiesWithArrayOfEnums( + key=[ + EnumClass("-efg") + ], + ) + try: + # Additional Properties with Array of Enums + api_response = api_instance.additional_properties_with_array_of_enums( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->additional_properties_with_array_of_enums: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalPropertiesWithArrayOfEnums**](../../models/AdditionalPropertiesWithArrayOfEnums.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#additional_properties_with_array_of_enums.ApiResponseFor200) | Got object with additional properties with array of enums + +#### additional_properties_with_array_of_enums.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AdditionalPropertiesWithArrayOfEnums**](../../models/AdditionalPropertiesWithArrayOfEnums.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **array_model** + +> AnimalFarm array_model() + + + +Test serialization of ArrayModel + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.animal_farm import AnimalFarm +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = AnimalFarm([ + Animal() + ]) + try: + api_response = api_instance.array_model( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->array_model: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnimalFarm**](../../models/AnimalFarm.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#array_model.ApiResponseFor200) | Output model + +#### array_model.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**AnimalFarm**](../../models/AnimalFarm.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **array_of_enums** + +> ArrayOfEnums array_of_enums() + +Array of Enums + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.array_of_enums import ArrayOfEnums +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = ArrayOfEnums([ + StringEnum("placed") + ]) + try: + # Array of Enums + api_response = api_instance.array_of_enums( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->array_of_enums: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayOfEnums**](../../models/ArrayOfEnums.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#array_of_enums.ApiResponseFor200) | Got named array of enums + +#### array_of_enums.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ArrayOfEnums**](../../models/ArrayOfEnums.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **body_with_file_schema** + +> body_with_file_schema(file_schema_test_class) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.file_schema_test_class import FileSchemaTestClass +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + body = FileSchemaTestClass( + file=File( + source_uri="source_uri_example", + ), + files=[ + File() + ], + ) + try: + api_response = api_instance.body_with_file_schema( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->body_with_file_schema: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**FileSchemaTestClass**](../../models/FileSchemaTestClass.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#body_with_file_schema.ApiResponseFor200) | Success + +#### body_with_file_schema.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **body_with_query_params** + +> body_with_query_params(queryuser) + + + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + query_params = { + 'query': "query_example", + } + body = User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + object_with_no_declared_props=dict(), + object_with_no_declared_props_nullable=dict(), + any_type_prop=None, + any_type_except_null_prop=None, + any_type_prop_nullable=None, + ) + try: + api_response = api_instance.body_with_query_params( + query_params=query_params, + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->body_with_query_params: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +query_params | RequestQueryParams | | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**User**](../../models/User.md) | | + + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query | QuerySchema | | + + +# QuerySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#body_with_query_params.ApiResponseFor200) | Success + +#### body_with_query_params.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **boolean** + +> bool boolean() + + + +Test serialization of outer boolean types + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = True + try: + api_response = api_instance.boolean( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->boolean: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#boolean.ApiResponseFor200) | Output boolean + +#### boolean.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **case_sensitive_params** + +> case_sensitive_params(some_varsome_var2some_var3) + + + +Ensures that original naming is used in endpoint params, that way we on't have collisions + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + query_params = { + 'someVar': "someVar_example", + 'SomeVar': "SomeVar_example", + 'some_var': "some_var_example", + } + try: + api_response = api_instance.case_sensitive_params( + query_params=query_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->case_sensitive_params: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query_params | RequestQueryParams | | +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +someVar | SomeVarSchema | | +SomeVar | SomeVarSchema | | +some_var | SomeVarSchema | | + + +# SomeVarSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# SomeVarSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# SomeVarSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#case_sensitive_params.ApiResponseFor200) | Success + +#### case_sensitive_params.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **client_model** + +> Client client_model(client) + +To test \"client\" model + +To test \"client\" model + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.client import Client +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + body = Client( + client="client_example", + ) + try: + # To test \"client\" model + api_response = api_instance.client_model( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->client_model: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Client**](../../models/Client.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#client_model.ApiResponseFor200) | successful operation + +#### client_model.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Client**](../../models/Client.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **composed_one_of_different_types** + +> ComposedOneOfDifferentTypes composed_one_of_different_types() + + + +Test serialization of object with $refed properties + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = ComposedOneOfDifferentTypes(None) + try: + api_response = api_instance.composed_one_of_different_types( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->composed_one_of_different_types: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ComposedOneOfDifferentTypes**](../../models/ComposedOneOfDifferentTypes.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#composed_one_of_different_types.ApiResponseFor200) | Output model + +#### composed_one_of_different_types.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ComposedOneOfDifferentTypes**](../../models/ComposedOneOfDifferentTypes.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **delete_coffee** + +> delete_coffee(id) + +Delete coffee + +Delete the coffee identified by the given id, (delete without request body) + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'id': "id_example", + } + try: + # Delete coffee + api_response = api_instance.delete_coffee( + path_params=path_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->delete_coffee: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +path_params | RequestPathParams | | +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +id | IdSchema | | + +# IdSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#delete_coffee.ApiResponseFor200) | OK +default | [ApiResponseForDefault](#delete_coffee.ApiResponseForDefault) | Unexpected error + +#### delete_coffee.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### delete_coffee.ApiResponseForDefault +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **endpoint_parameters** + +> endpoint_parameters() + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example + +* Basic Authentication (http_basic_test): +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure HTTP basic authorization: http_basic_test +configuration = petstore_api.Configuration( + username = 'YOUR_USERNAME', + password = 'YOUR_PASSWORD' +) +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = dict( + integer=10, + int32=20, + int64=1, + number=32.1, + _float=3.14, + double=67.8, + string="a", + pattern_without_delimiter="AUR,rZ#UM/?R,Fp^l6$ARjbhJk C>", + byte='YQ==', + binary=open('/path/to/file', 'rb'), + date="1970-01-01", + date_time="2020-02-02T20:20:20.222220Z", + password="password_example", + callback="callback_example", + ) + try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_response = api_instance.endpoint_parameters( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->endpoint_parameters: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/x-www-form-urlencoded' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationXWwwFormUrlencoded + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**number** | decimal.Decimal, int, float, | decimal.Decimal, | None | +**pattern_without_delimiter** | str, | str, | None | +**byte** | str, | str, | None | +**double** | decimal.Decimal, int, float, | decimal.Decimal, | None | value must be a 64 bit float +**integer** | decimal.Decimal, int, | decimal.Decimal, | None | [optional] +**int32** | decimal.Decimal, int, | decimal.Decimal, | None | [optional] value must be a 32 bit integer +**int64** | decimal.Decimal, int, | decimal.Decimal, | None | [optional] value must be a 64 bit integer +**float** | decimal.Decimal, int, float, | decimal.Decimal, | None | [optional] value must be a 32 bit float +**string** | str, | str, | None | [optional] +**binary** | bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | None | [optional] +**date** | str, date, | str, | None | [optional] value must conform to RFC-3339 full-date YYYY-MM-DD +**dateTime** | str, datetime, | str, | None | [optional] if omitted the server will use the default value of 2010-02-01T10:20:10.11111+01:00value must conform to RFC-3339 date-time +**password** | str, | str, | None | [optional] +**callback** | str, | str, | None | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#endpoint_parameters.ApiResponseFor200) | Success +404 | [ApiResponseFor404](#endpoint_parameters.ApiResponseFor404) | User not found + +#### endpoint_parameters.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### endpoint_parameters.ApiResponseFor404 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +[http_basic_test](../../../README.md#http_basic_test) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **enum_parameters** + +> enum_parameters() + +To test enum parameters + +To test enum parameters + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + query_params = { + 'enum_query_string_array': [ + "$" + ], + 'enum_query_string': "-efg", + 'enum_query_integer': 1, + 'enum_query_double': 1.1, + } + header_params = { + 'enum_header_string_array': [ + "$" + ], + 'enum_header_string': "-efg", + } + body = dict( + enum_form_string_array=[ + "$" + ], + enum_form_string="-efg", + ) + try: + # To test enum parameters + api_response = api_instance.enum_parameters( + query_params=query_params, + header_params=header_params, + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->enum_parameters: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] | optional, default is unset | +query_params | RequestQueryParams | | +header_params | RequestHeaderParams | | +content_type | str | optional, default is 'application/x-www-form-urlencoded' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationXWwwFormUrlencoded + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[enum_form_string_array](#enum_form_string_array)** | list, tuple, | tuple, | Form parameter enum test (string array) | [optional] +**enum_form_string** | str, | str, | Form parameter enum test (string) | [optional] must be one of ["_abc", "-efg", "(xyz)", ] if omitted the server will use the default value of "-efg" +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# enum_form_string_array + +Form parameter enum test (string array) + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | Form parameter enum test (string array) | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | must be one of [">", "$", ] if omitted the server will use the default value of "$" + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +enum_query_string_array | EnumQueryStringArraySchema | | optional +enum_query_string | EnumQueryStringSchema | | optional +enum_query_integer | EnumQueryIntegerSchema | | optional +enum_query_double | EnumQueryDoubleSchema | | optional + + +# EnumQueryStringArraySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | must be one of [">", "$", ] if omitted the server will use the default value of "$" + +# EnumQueryStringSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | must be one of ["_abc", "-efg", "(xyz)", ] if omitted the server will use the default value of "-efg" + +# EnumQueryIntegerSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | must be one of [1, -2, ] value must be a 32 bit integer + +# EnumQueryDoubleSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | must be one of [1.1, -1.2, ] value must be a 64 bit float + +### header_params +#### RequestHeaderParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +enum_header_string_array | EnumHeaderStringArraySchema | | optional +enum_header_string | EnumHeaderStringSchema | | optional + +# EnumHeaderStringArraySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | must be one of [">", "$", ] if omitted the server will use the default value of "$" + +# EnumHeaderStringSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | must be one of ["_abc", "-efg", "(xyz)", ] if omitted the server will use the default value of "-efg" + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#enum_parameters.ApiResponseFor200) | Success +404 | [ApiResponseFor404](#enum_parameters.ApiResponseFor404) | Not found + +#### enum_parameters.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### enum_parameters.ApiResponseFor404 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **fake_health_get** + +> HealthCheckResult fake_health_get() + +Health check endpoint + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.health_check_result import HealthCheckResult +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Health check endpoint + api_response = api_instance.fake_health_get() + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->fake_health_get: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#fake_health_get.ApiResponseFor200) | The instance started successfully + +#### fake_health_get.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**HealthCheckResult**](../../models/HealthCheckResult.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **group_parameters** + +> group_parameters(required_string_grouprequired_boolean_grouprequired_int64_group) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example + +* Bearer (JWT) Authentication (bearer_test): +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization (JWT): bearer_test +configuration = petstore_api.Configuration( + access_token = 'YOUR_BEARER_TOKEN' +) +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + query_params = { + 'required_string_group': 1, + 'required_int64_group': 1, + } + header_params = { + 'required_boolean_group': True, + } + try: + # Fake endpoint to test group parameters (optional) + api_response = api_instance.group_parameters( + query_params=query_params, + header_params=header_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->group_parameters: %s\n" % e) + + # example passing only optional values + query_params = { + 'required_string_group': 1, + 'required_int64_group': 1, + 'string_group': 1, + 'int64_group': 1, + } + header_params = { + 'required_boolean_group': True, + 'boolean_group': True, + } + try: + # Fake endpoint to test group parameters (optional) + api_response = api_instance.group_parameters( + query_params=query_params, + header_params=header_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->group_parameters: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query_params | RequestQueryParams | | +header_params | RequestHeaderParams | | +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +required_string_group | RequiredStringGroupSchema | | +required_int64_group | RequiredInt64GroupSchema | | +string_group | StringGroupSchema | | optional +int64_group | Int64GroupSchema | | optional + + +# RequiredStringGroupSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +# RequiredInt64GroupSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +# StringGroupSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +# Int64GroupSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +### header_params +#### RequestHeaderParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +required_boolean_group | RequiredBooleanGroupSchema | | +boolean_group | BooleanGroupSchema | | optional + +# RequiredBooleanGroupSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +# BooleanGroupSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#group_parameters.ApiResponseFor200) | succeeded + +#### group_parameters.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +[bearer_test](../../../README.md#bearer_test) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **inline_additional_properties** + +> inline_additional_properties(request_body) + +test inline additionalProperties + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + body = dict( + "key": "key_example", + ) + try: + # test inline additionalProperties + api_response = api_instance.inline_additional_properties( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->inline_additional_properties: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | str, | str, | any string name can be used but the value must be the correct type | [optional] + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#inline_additional_properties.ApiResponseFor200) | successful operation + +#### inline_additional_properties.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **inline_composition** + +> bool, date, datetime, dict, float, int, list, str, none_type inline_composition() + +testing composed schemas at inline locations + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + query_params = { + 'compositionAtRoot': None, + 'compositionInProperty': dict( + some_prop=None, + ), + } + body = None + try: + # testing composed schemas at inline locations + api_response = api_instance.inline_composition( + query_params=query_params, + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->inline_composition: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | +query_params | RequestQueryParams | | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', 'multipart/form-data', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | str, | str, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# SchemaForRequestBodyMultipartFormData + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[someProp](#someProp)** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# someProp + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | str, | str, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +compositionAtRoot | CompositionAtRootSchema | | optional +compositionInProperty | CompositionInPropertySchema | | optional + + +# CompositionAtRootSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | str, | str, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# CompositionInPropertySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[someProp](#someProp)** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# someProp + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | str, | str, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#inline_composition.ApiResponseFor200) | success + +#### inline_composition.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, SchemaFor200ResponseBodyMultipartFormData, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | str, | str, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# SchemaFor200ResponseBodyMultipartFormData + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[someProp](#someProp)** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# someProp + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | str, | str, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **json_form_data** + +> json_form_data() + +test json serialization of form data + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = dict( + param="param_example", + param2="param2_example", + ) + try: + # test json serialization of form data + api_response = api_instance.json_form_data( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->json_form_data: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/x-www-form-urlencoded' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationXWwwFormUrlencoded + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**param** | str, | str, | field1 | +**param2** | str, | str, | field2 | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#json_form_data.ApiResponseFor200) | successful operation + +#### json_form_data.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **json_patch** + +> json_patch() + +json patch + +json patch route with a requestBody + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.json_patch_request import JSONPatchRequest +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = JSONPatchRequest([ + None + ]) + try: + # json patch + api_response = api_instance.json_patch( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->json_patch: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json-patch+json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJsonPatchjson +Type | Description | Notes +------------- | ------------- | ------------- +[**JSONPatchRequest**](../../models/JSONPatchRequest.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#json_patch.ApiResponseFor200) | OK + +#### json_patch.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **json_with_charset** + +> bool, date, datetime, dict, float, int, list, str, none_type json_with_charset() + +json with charset tx and rx + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = None + try: + # json with charset tx and rx + api_response = api_instance.json_with_charset( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->json_with_charset: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json; charset=utf-8' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json; charset=utf-8', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJsonCharsetutf8 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#json_with_charset.ApiResponseFor200) | success + +#### json_with_charset.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJsonCharsetutf8, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJsonCharsetutf8 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **mammal** + +> Mammal mammal(mammal) + + + +Test serialization of mammals + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.mammal import Mammal +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + body = Mammal( + has_baleen=True, + has_teeth=True, + class_name="whale", + ) + try: + api_response = api_instance.mammal( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->mammal: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Mammal**](../../models/Mammal.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#mammal.ApiResponseFor200) | Output mammal + +#### mammal.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Mammal**](../../models/Mammal.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **number_with_validations** + +> NumberWithValidations number_with_validations() + + + +Test serialization of outer number types + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.number_with_validations import NumberWithValidations +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = NumberWithValidations(10) + try: + api_response = api_instance.number_with_validations( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->number_with_validations: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NumberWithValidations**](../../models/NumberWithValidations.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#number_with_validations.ApiResponseFor200) | Output number + +#### number_with_validations.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**NumberWithValidations**](../../models/NumberWithValidations.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **object_in_query** + +> object_in_query() + +user list + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + query_params = { + 'mapBean': dict( + keyword="keyword_example", + ), + } + try: + # user list + api_response = api_instance.object_in_query( + query_params=query_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->object_in_query: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query_params | RequestQueryParams | | +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +mapBean | MapBeanSchema | | optional + + +# MapBeanSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**keyword** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#object_in_query.ApiResponseFor200) | ok + +#### object_in_query.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **object_model_with_ref_props** + +> ObjectModelWithRefProps object_model_with_ref_props() + + + +Test serialization of object with $refed properties + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = ObjectModelWithRefProps( + my_number=NumberWithValidations(10), + my_string="my_string_example", + my_boolean=True, + ) + try: + api_response = api_instance.object_model_with_ref_props( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectModelWithRefProps**](../../models/ObjectModelWithRefProps.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#object_model_with_ref_props.ApiResponseFor200) | Output model + +#### object_model_with_ref_props.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ObjectModelWithRefProps**](../../models/ObjectModelWithRefProps.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **parameter_collisions** + +> bool, date, datetime, dict, float, int, list, str, none_type parameter_collisions(_3a_b5ab2_self3a_b6) + +parameter collision case + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + '1': "1_example", + 'aB': "aB_example", + 'Ab': "Ab_example", + 'self': "self_example", + 'A-B': "A-B_example", + } + query_params = { + } + cookie_params = { + } + header_params = { + } + try: + # parameter collision case + api_response = api_instance.parameter_collisions( + path_params=path_params, + query_params=query_params, + header_params=header_params, + cookie_params=cookie_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->parameter_collisions: %s\n" % e) + + # example passing only optional values + path_params = { + '1': "1_example", + 'aB': "aB_example", + 'Ab': "Ab_example", + 'self': "self_example", + 'A-B': "A-B_example", + } + query_params = { + '1': "1_example", + 'aB': "aB_example", + 'Ab': "Ab_example", + 'self': "self_example", + 'A-B': "A-B_example", + } + cookie_params = { + '1': "1_example", + 'aB': "aB_example", + 'Ab': "Ab_example", + 'self': "self_example", + 'A-B': "A-B_example", + } + header_params = { + '1': "1_example", + 'aB': "aB_example", + 'self': "self_example", + 'A-B': "A-B_example", + } + body = None + try: + # parameter collision case + api_response = api_instance.parameter_collisions( + path_params=path_params, + query_params=query_params, + header_params=header_params, + cookie_params=cookie_params, + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->parameter_collisions: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +query_params | RequestQueryParams | | +header_params | RequestHeaderParams | | +path_params | RequestPathParams | | +cookie_params | RequestCookieParams | | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +1 | Model1Schema | | optional +aB | ABSchema | | optional +Ab | AbSchema | | optional +self | ModelSelfSchema | | optional +A-B | ABSchema | | optional + + +# Model1Schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ABSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# AbSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ModelSelfSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ABSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### header_params +#### RequestHeaderParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +1 | Model1Schema | | optional +aB | ABSchema | | optional +self | ModelSelfSchema | | optional +A-B | ABSchema | | optional + +# Model1Schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ABSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ModelSelfSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ABSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +1 | Model1Schema | | +aB | ABSchema | | +Ab | AbSchema | | +self | ModelSelfSchema | | +A-B | ABSchema | | + +# Model1Schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ABSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# AbSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ModelSelfSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ABSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### cookie_params +#### RequestCookieParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +1 | Model1Schema | | optional +aB | ABSchema | | optional +Ab | AbSchema | | optional +self | ModelSelfSchema | | optional +A-B | ABSchema | | optional + +# Model1Schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ABSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# AbSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ModelSelfSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# ABSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#parameter_collisions.ApiResponseFor200) | success + +#### parameter_collisions.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **query_param_with_json_content_type** + +> bool, date, datetime, dict, float, int, list, str, none_type query_param_with_json_content_type(some_param) + +query param with json content-type + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + query_params = { + 'someParam': , + } + try: + # query param with json content-type + api_response = api_instance.query_param_with_json_content_type( + query_params=query_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->query_param_with_json_content_type: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query_params | RequestQueryParams | | +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +someParam | | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#query_param_with_json_content_type.ApiResponseFor200) | success + +#### query_param_with_json_content_type.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **query_parameter_collection_format** + +> query_parameter_collection_format(pipeioutilhttpurlcontextref_param) + + + +To test the collection format in query parameters + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.string_with_validation import StringWithValidation +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + query_params = { + 'pipe': [ + "pipe_example" + ], + 'ioutil': [ + "ioutil_example" + ], + 'http': [ + "http_example" + ], + 'url': [ + "url_example" + ], + 'context': [ + "context_example" + ], + 'refParam': StringWithValidation("refParam_example"), + } + try: + api_response = api_instance.query_parameter_collection_format( + query_params=query_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->query_parameter_collection_format: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query_params | RequestQueryParams | | +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +pipe | PipeSchema | | +ioutil | IoutilSchema | | +http | HttpSchema | | +url | UrlSchema | | +context | ContextSchema | | +refParam | RefParamSchema | | + + +# PipeSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | + +# IoutilSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | + +# HttpSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | + +# UrlSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | + +# ContextSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | + +# RefParamSchema +Type | Description | Notes +------------- | ------------- | ------------- +[**StringWithValidation**](../../models/StringWithValidation.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#query_parameter_collection_format.ApiResponseFor200) | Success + +#### query_parameter_collection_format.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **ref_object_in_query** + +> ref_object_in_query() + +user list + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.foo import Foo +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + query_params = { + 'mapBean': Foo( + bar="bar", + ), + } + try: + # user list + api_response = api_instance.ref_object_in_query( + query_params=query_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->ref_object_in_query: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query_params | RequestQueryParams | | +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +mapBean | MapBeanSchema | | optional + + +# MapBeanSchema +Type | Description | Notes +------------- | ------------- | ------------- +[**Foo**](../../models/Foo.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#ref_object_in_query.ApiResponseFor200) | ok + +#### ref_object_in_query.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **response_without_schema** + +> response_without_schema() + +receives a response without schema + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # receives a response without schema + api_response = api_instance.response_without_schema() + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->response_without_schema: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#response_without_schema.ApiResponseFor200) | contents without schema definition + +#### response_without_schema.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[Unset, Unset, ] | | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **string** + +> str string() + + + +Test serialization of outer string types + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = "body_example" + try: + api_response = api_instance.string( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#string.ApiResponseFor200) | Output string + +#### string.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **string_enum** + +> StringEnum string_enum() + + + +Test serialization of outer enum + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.string_enum import StringEnum +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = StringEnum("placed") + try: + api_response = api_instance.string_enum( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string_enum: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, Unset] | optional, default is unset | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**StringEnum**](../../models/StringEnum.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#string_enum.ApiResponseFor200) | Output enum + +#### string_enum.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**StringEnum**](../../models/StringEnum.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **upload_download_file** + +> file_type upload_download_file(body) + +uploads a file and downloads a file using application/octet-stream + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + body = open('/path/to/file', 'rb') + try: + # uploads a file and downloads a file using application/octet-stream + api_response = api_instance.upload_download_file( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->upload_download_file: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationOctetStream] | required | +content_type | str | optional, default is 'application/octet-stream' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/octet-stream', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationOctetStream + +file to upload + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | file to upload | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#upload_download_file.ApiResponseFor200) | successful operation + +#### upload_download_file.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationOctetStream, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationOctetStream + +file to download + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | file to download | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **upload_file** + +> ApiResponse upload_file() + +uploads a file using multipart/form-data + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.api_response import ApiResponse +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = dict( + additional_metadata="additional_metadata_example", + file=open('/path/to/file', 'rb'), + ) + try: + # uploads a file using multipart/form-data + api_response = api_instance.upload_file( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->upload_file: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | +content_type | str | optional, default is 'multipart/form-data' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyMultipartFormData + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**file** | bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | file to upload | +**additionalMetadata** | str, | str, | Additional data to pass to server | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#upload_file.ApiResponseFor200) | successful operation + +#### upload_file.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ApiResponse**](../../models/ApiResponse.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **upload_files** + +> ApiResponse upload_files() + +uploads files using multipart/form-data + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import fake_api +from petstore_api.model.api_response import ApiResponse +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only optional values + body = dict( + files=[ + open('/path/to/file', 'rb') + ], + ) + try: + # uploads files using multipart/form-data + api_response = api_instance.upload_files( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->upload_files: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | +content_type | str | optional, default is 'multipart/form-data' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyMultipartFormData + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[files](#files)** | list, tuple, | tuple, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# files + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#upload_files.ApiResponseFor200) | successful operation + +#### upload_files.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ApiResponse**](../../models/ApiResponse.md) | | + + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/apis/tags/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/python/docs/apis/tags/FakeClassnameTags123Api.md new file mode 100644 index 0000000000..87b99456ad --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/apis/tags/FakeClassnameTags123Api.md @@ -0,0 +1,104 @@ + +# petstore_api.apis.tags.fake_classname_tags123_api.FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**classname**](#classname) | **patch** /fake_classname_test | To test class name in snake case + +# **classname** + +> Client classname(client) + +To test class name in snake case + +To test class name in snake case + +### Example + +* Api Key Authentication (api_key_query): +```python +import petstore_api +from petstore_api.apis.tags import fake_classname_tags123_api +from petstore_api.model.client import Client +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure API key authorization: api_key_query +configuration.api_key['api_key_query'] = 'YOUR_API_KEY' + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['api_key_query'] = 'Bearer' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_classname_tags123_api.FakeClassnameTags123Api(api_client) + + # example passing only required values which don't have defaults set + body = Client( + client="client_example", + ) + try: + # To test class name in snake case + api_response = api_instance.classname( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeClassnameTags123Api->classname: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Client**](../../models/Client.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#classname.ApiResponseFor200) | successful operation + +#### classname.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Client**](../../models/Client.md) | | + + +### Authorization + +[api_key_query](../../../README.md#api_key_query) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/apis/tags/PetApi.md b/samples/openapi3/client/petstore/python/docs/apis/tags/PetApi.md new file mode 100644 index 0000000000..a295a0d499 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/apis/tags/PetApi.md @@ -0,0 +1,1402 @@ + +# petstore_api.apis.tags.pet_api.PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_pet**](#add_pet) | **post** /pet | Add a new pet to the store +[**delete_pet**](#delete_pet) | **delete** /pet/{petId} | Deletes a pet +[**find_pets_by_status**](#find_pets_by_status) | **get** /pet/findByStatus | Finds Pets by status +[**find_pets_by_tags**](#find_pets_by_tags) | **get** /pet/findByTags | Finds Pets by tags +[**get_pet_by_id**](#get_pet_by_id) | **get** /pet/{petId} | Find pet by ID +[**update_pet**](#update_pet) | **put** /pet | Update an existing pet +[**update_pet_with_form**](#update_pet_with_form) | **post** /pet/{petId} | Updates a pet in the store with form data +[**upload_file_with_required_file**](#upload_file_with_required_file) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +[**upload_image**](#upload_image) | **post** /pet/{petId}/uploadImage | uploads an image + +# **add_pet** + +> add_pet(pet) + +Add a new pet to the store + +Add a new pet to the store + +### Example + +* OAuth Authentication (petstore_auth): +```python +import petstore_api +from petstore_api.apis.tags import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure HTTP message signature: http_signature_test +# The HTTP Signature Header mechanism that can be used by a client to +# authenticate the sender of a message and ensure that particular headers +# have not been modified in transit. +# +# You can specify the signing key-id, private key path, signing scheme, +# signing algorithm, list of signed headers and signature max validity. +# The 'key_id' parameter is an opaque string that the API server can use +# to lookup the client and validate the signature. +# The 'private_key_path' parameter should be the path to a file that +# contains a DER or base-64 encoded private key. +# The 'private_key_passphrase' parameter is optional. Set the passphrase +# if the private key is encrypted. +# The 'signed_headers' parameter is used to specify the list of +# HTTP headers included when generating the signature for the message. +# You can specify HTTP headers that you want to protect with a cryptographic +# signature. Note that proxies may add, modify or remove HTTP headers +# for legitimate reasons, so you should only add headers that you know +# will not be modified. For example, if you want to protect the HTTP request +# body, you can specify the Digest header. In that case, the client calculates +# the digest of the HTTP request body and includes the digest in the message +# signature. +# The 'signature_max_validity' parameter is optional. It is configured as a +# duration to express when the signature ceases to be valid. The client calculates +# the expiration date every time it generates the cryptographic signature +# of an HTTP request. The API server may have its own security policy +# that controls the maximum validity of the signature. The client max validity +# must be lower than the server max validity. +# The time on the client and server must be synchronized, otherwise the +# server may reject the client signature. +# +# The client must use a combination of private key, signing scheme, +# signing algorithm and hash algorithm that matches the security policy of +# the API server. +# +# See petstore_api.signing for a list of all supported parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2", + signing_info = petstore_api.signing.HttpSigningConfiguration( + key_id = 'my-key-id', + private_key_path = 'private_key.pem', + private_key_passphrase = 'YOUR_PASSPHRASE', + signing_scheme = petstore_api.signing.SCHEME_HS2019, + signing_algorithm = petstore_api.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, + hash_algorithm = petstore_api.signing.SCHEME_RSA_SHA256, + signed_headers = [ + petstore_api.signing.HEADER_REQUEST_TARGET, + petstore_api.signing.HEADER_CREATED, + petstore_api.signing.HEADER_EXPIRES, + petstore_api.signing.HEADER_HOST, + petstore_api.signing.HEADER_DATE, + petstore_api.signing.HEADER_DIGEST, + 'Content-Type', + 'Content-Length', + 'User-Agent' + ], + signature_max_validity = datetime.timedelta(minutes=5) + ) +) + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + + # example passing only required values which don't have defaults set + body = Pet( + id=1, + category=Category( + id=1, + name="default-name", + ), + name="doggie", + photo_urls=[ + "photo_urls_example" + ], + tags=[ + Tag( + id=1, + name="name_example", + ) + ], + status="available", + ) + try: + # Add a new pet to the store + api_response = api_instance.add_pet( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->add_pet: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, SchemaForRequestBodyApplicationXml] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +host_index | typing.Optional[int] | default is None | Allows one to select a different host +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Pet**](../../models/Pet.md) | | + + +# SchemaForRequestBodyApplicationXml +Type | Description | Notes +------------- | ------------- | ------------- +[**Pet**](../../models/Pet.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#add_pet.ApiResponseFor200) | Ok +405 | [ApiResponseFor405](#add_pet.ApiResponseFor405) | Invalid input + +#### add_pet.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### add_pet.ApiResponseFor405 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +[http_signature_test](../../../README.md#http_signature_test), [petstore_auth](../../../README.md#petstore_auth) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **delete_pet** + +> delete_pet(pet_id) + +Deletes a pet + +### Example + +* OAuth Authentication (petstore_auth): +```python +import petstore_api +from petstore_api.apis.tags import pet_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'petId': 1, + } + header_params = { + } + try: + # Deletes a pet + api_response = api_instance.delete_pet( + path_params=path_params, + header_params=header_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->delete_pet: %s\n" % e) + + # example passing only optional values + path_params = { + 'petId': 1, + } + header_params = { + 'api_key': "api_key_example", + } + try: + # Deletes a pet + api_response = api_instance.delete_pet( + path_params=path_params, + header_params=header_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->delete_pet: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +header_params | RequestHeaderParams | | +path_params | RequestPathParams | | +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### header_params +#### RequestHeaderParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +api_key | ApiKeySchema | | optional + +# ApiKeySchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +petId | PetIdSchema | | + +# PetIdSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +400 | [ApiResponseFor400](#delete_pet.ApiResponseFor400) | Invalid pet value + +#### delete_pet.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +[petstore_auth](../../../README.md#petstore_auth) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **find_pets_by_status** + +> [Pet] find_pets_by_status(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example + +* OAuth Authentication (petstore_auth): +```python +import petstore_api +from petstore_api.apis.tags import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure HTTP message signature: http_signature_test +# The HTTP Signature Header mechanism that can be used by a client to +# authenticate the sender of a message and ensure that particular headers +# have not been modified in transit. +# +# You can specify the signing key-id, private key path, signing scheme, +# signing algorithm, list of signed headers and signature max validity. +# The 'key_id' parameter is an opaque string that the API server can use +# to lookup the client and validate the signature. +# The 'private_key_path' parameter should be the path to a file that +# contains a DER or base-64 encoded private key. +# The 'private_key_passphrase' parameter is optional. Set the passphrase +# if the private key is encrypted. +# The 'signed_headers' parameter is used to specify the list of +# HTTP headers included when generating the signature for the message. +# You can specify HTTP headers that you want to protect with a cryptographic +# signature. Note that proxies may add, modify or remove HTTP headers +# for legitimate reasons, so you should only add headers that you know +# will not be modified. For example, if you want to protect the HTTP request +# body, you can specify the Digest header. In that case, the client calculates +# the digest of the HTTP request body and includes the digest in the message +# signature. +# The 'signature_max_validity' parameter is optional. It is configured as a +# duration to express when the signature ceases to be valid. The client calculates +# the expiration date every time it generates the cryptographic signature +# of an HTTP request. The API server may have its own security policy +# that controls the maximum validity of the signature. The client max validity +# must be lower than the server max validity. +# The time on the client and server must be synchronized, otherwise the +# server may reject the client signature. +# +# The client must use a combination of private key, signing scheme, +# signing algorithm and hash algorithm that matches the security policy of +# the API server. +# +# See petstore_api.signing for a list of all supported parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2", + signing_info = petstore_api.signing.HttpSigningConfiguration( + key_id = 'my-key-id', + private_key_path = 'private_key.pem', + private_key_passphrase = 'YOUR_PASSPHRASE', + signing_scheme = petstore_api.signing.SCHEME_HS2019, + signing_algorithm = petstore_api.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, + hash_algorithm = petstore_api.signing.SCHEME_RSA_SHA256, + signed_headers = [ + petstore_api.signing.HEADER_REQUEST_TARGET, + petstore_api.signing.HEADER_CREATED, + petstore_api.signing.HEADER_EXPIRES, + petstore_api.signing.HEADER_HOST, + petstore_api.signing.HEADER_DATE, + petstore_api.signing.HEADER_DIGEST, + 'Content-Type', + 'Content-Length', + 'User-Agent' + ], + signature_max_validity = datetime.timedelta(minutes=5) + ) +) + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + + # example passing only required values which don't have defaults set + query_params = { + 'status': [ + "available" + ], + } + try: + # Finds Pets by status + api_response = api_instance.find_pets_by_status( + query_params=query_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->find_pets_by_status: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query_params | RequestQueryParams | | +accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +status | StatusSchema | | + + +# StatusSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | must be one of ["available", "pending", "sold", ] if omitted the server will use the default value of "available" + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#find_pets_by_status.ApiResponseFor200) | successful operation +400 | [ApiResponseFor400](#find_pets_by_status.ApiResponseFor400) | Invalid status value + +#### find_pets_by_status.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationXml + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**Pet**]({{complexTypePrefix}}Pet.md) | [**Pet**]({{complexTypePrefix}}Pet.md) | [**Pet**]({{complexTypePrefix}}Pet.md) | | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**Pet**]({{complexTypePrefix}}Pet.md) | [**Pet**]({{complexTypePrefix}}Pet.md) | [**Pet**]({{complexTypePrefix}}Pet.md) | | + +#### find_pets_by_status.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +[http_signature_test](../../../README.md#http_signature_test), [petstore_auth](../../../README.md#petstore_auth) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **find_pets_by_tags** + +> [Pet] find_pets_by_tags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example + +* OAuth Authentication (petstore_auth): +```python +import petstore_api +from petstore_api.apis.tags import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure HTTP message signature: http_signature_test +# The HTTP Signature Header mechanism that can be used by a client to +# authenticate the sender of a message and ensure that particular headers +# have not been modified in transit. +# +# You can specify the signing key-id, private key path, signing scheme, +# signing algorithm, list of signed headers and signature max validity. +# The 'key_id' parameter is an opaque string that the API server can use +# to lookup the client and validate the signature. +# The 'private_key_path' parameter should be the path to a file that +# contains a DER or base-64 encoded private key. +# The 'private_key_passphrase' parameter is optional. Set the passphrase +# if the private key is encrypted. +# The 'signed_headers' parameter is used to specify the list of +# HTTP headers included when generating the signature for the message. +# You can specify HTTP headers that you want to protect with a cryptographic +# signature. Note that proxies may add, modify or remove HTTP headers +# for legitimate reasons, so you should only add headers that you know +# will not be modified. For example, if you want to protect the HTTP request +# body, you can specify the Digest header. In that case, the client calculates +# the digest of the HTTP request body and includes the digest in the message +# signature. +# The 'signature_max_validity' parameter is optional. It is configured as a +# duration to express when the signature ceases to be valid. The client calculates +# the expiration date every time it generates the cryptographic signature +# of an HTTP request. The API server may have its own security policy +# that controls the maximum validity of the signature. The client max validity +# must be lower than the server max validity. +# The time on the client and server must be synchronized, otherwise the +# server may reject the client signature. +# +# The client must use a combination of private key, signing scheme, +# signing algorithm and hash algorithm that matches the security policy of +# the API server. +# +# See petstore_api.signing for a list of all supported parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2", + signing_info = petstore_api.signing.HttpSigningConfiguration( + key_id = 'my-key-id', + private_key_path = 'private_key.pem', + private_key_passphrase = 'YOUR_PASSPHRASE', + signing_scheme = petstore_api.signing.SCHEME_HS2019, + signing_algorithm = petstore_api.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, + hash_algorithm = petstore_api.signing.SCHEME_RSA_SHA256, + signed_headers = [ + petstore_api.signing.HEADER_REQUEST_TARGET, + petstore_api.signing.HEADER_CREATED, + petstore_api.signing.HEADER_EXPIRES, + petstore_api.signing.HEADER_HOST, + petstore_api.signing.HEADER_DATE, + petstore_api.signing.HEADER_DIGEST, + 'Content-Type', + 'Content-Length', + 'User-Agent' + ], + signature_max_validity = datetime.timedelta(minutes=5) + ) +) + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + + # example passing only required values which don't have defaults set + query_params = { + 'tags': [ + "tags_example" + ], + } + try: + # Finds Pets by tags + api_response = api_instance.find_pets_by_tags( + query_params=query_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->find_pets_by_tags: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query_params | RequestQueryParams | | +accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +tags | TagsSchema | | + + +# TagsSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#find_pets_by_tags.ApiResponseFor200) | successful operation +400 | [ApiResponseFor400](#find_pets_by_tags.ApiResponseFor400) | Invalid tag value + +#### find_pets_by_tags.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationXml + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**Pet**]({{complexTypePrefix}}Pet.md) | [**Pet**]({{complexTypePrefix}}Pet.md) | [**Pet**]({{complexTypePrefix}}Pet.md) | | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**Pet**]({{complexTypePrefix}}Pet.md) | [**Pet**]({{complexTypePrefix}}Pet.md) | [**Pet**]({{complexTypePrefix}}Pet.md) | | + +#### find_pets_by_tags.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +[http_signature_test](../../../README.md#http_signature_test), [petstore_auth](../../../README.md#petstore_auth) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **get_pet_by_id** + +> Pet get_pet_by_id(pet_id) + +Find pet by ID + +Returns a single pet + +### Example + +* Api Key Authentication (api_key): +```python +import petstore_api +from petstore_api.apis.tags import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure API key authorization: api_key +configuration.api_key['api_key'] = 'YOUR_API_KEY' + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['api_key'] = 'Bearer' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'petId': 1, + } + try: + # Find pet by ID + api_response = api_instance.get_pet_by_id( + path_params=path_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->get_pet_by_id: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +path_params | RequestPathParams | | +accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +petId | PetIdSchema | | + +# PetIdSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#get_pet_by_id.ApiResponseFor200) | successful operation +400 | [ApiResponseFor400](#get_pet_by_id.ApiResponseFor400) | Invalid ID supplied +404 | [ApiResponseFor404](#get_pet_by_id.ApiResponseFor404) | Pet not found + +#### get_pet_by_id.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationXml +Type | Description | Notes +------------- | ------------- | ------------- +[**Pet**](../../models/Pet.md) | | + + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Pet**](../../models/Pet.md) | | + + +#### get_pet_by_id.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### get_pet_by_id.ApiResponseFor404 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +[api_key](../../../README.md#api_key) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **update_pet** + +> update_pet(pet) + +Update an existing pet + +### Example + +* OAuth Authentication (petstore_auth): +```python +import petstore_api +from petstore_api.apis.tags import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure HTTP message signature: http_signature_test +# The HTTP Signature Header mechanism that can be used by a client to +# authenticate the sender of a message and ensure that particular headers +# have not been modified in transit. +# +# You can specify the signing key-id, private key path, signing scheme, +# signing algorithm, list of signed headers and signature max validity. +# The 'key_id' parameter is an opaque string that the API server can use +# to lookup the client and validate the signature. +# The 'private_key_path' parameter should be the path to a file that +# contains a DER or base-64 encoded private key. +# The 'private_key_passphrase' parameter is optional. Set the passphrase +# if the private key is encrypted. +# The 'signed_headers' parameter is used to specify the list of +# HTTP headers included when generating the signature for the message. +# You can specify HTTP headers that you want to protect with a cryptographic +# signature. Note that proxies may add, modify or remove HTTP headers +# for legitimate reasons, so you should only add headers that you know +# will not be modified. For example, if you want to protect the HTTP request +# body, you can specify the Digest header. In that case, the client calculates +# the digest of the HTTP request body and includes the digest in the message +# signature. +# The 'signature_max_validity' parameter is optional. It is configured as a +# duration to express when the signature ceases to be valid. The client calculates +# the expiration date every time it generates the cryptographic signature +# of an HTTP request. The API server may have its own security policy +# that controls the maximum validity of the signature. The client max validity +# must be lower than the server max validity. +# The time on the client and server must be synchronized, otherwise the +# server may reject the client signature. +# +# The client must use a combination of private key, signing scheme, +# signing algorithm and hash algorithm that matches the security policy of +# the API server. +# +# See petstore_api.signing for a list of all supported parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2", + signing_info = petstore_api.signing.HttpSigningConfiguration( + key_id = 'my-key-id', + private_key_path = 'private_key.pem', + private_key_passphrase = 'YOUR_PASSPHRASE', + signing_scheme = petstore_api.signing.SCHEME_HS2019, + signing_algorithm = petstore_api.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, + hash_algorithm = petstore_api.signing.SCHEME_RSA_SHA256, + signed_headers = [ + petstore_api.signing.HEADER_REQUEST_TARGET, + petstore_api.signing.HEADER_CREATED, + petstore_api.signing.HEADER_EXPIRES, + petstore_api.signing.HEADER_HOST, + petstore_api.signing.HEADER_DATE, + petstore_api.signing.HEADER_DIGEST, + 'Content-Type', + 'Content-Length', + 'User-Agent' + ], + signature_max_validity = datetime.timedelta(minutes=5) + ) +) + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + + # example passing only required values which don't have defaults set + body = Pet( + id=1, + category=Category( + id=1, + name="default-name", + ), + name="doggie", + photo_urls=[ + "photo_urls_example" + ], + tags=[ + Tag( + id=1, + name="name_example", + ) + ], + status="available", + ) + try: + # Update an existing pet + api_response = api_instance.update_pet( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->update_pet: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson, SchemaForRequestBodyApplicationXml] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +host_index | typing.Optional[int] | default is None | Allows one to select a different host +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Pet**](../../models/Pet.md) | | + + +# SchemaForRequestBodyApplicationXml +Type | Description | Notes +------------- | ------------- | ------------- +[**Pet**](../../models/Pet.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +400 | [ApiResponseFor400](#update_pet.ApiResponseFor400) | Invalid ID supplied +404 | [ApiResponseFor404](#update_pet.ApiResponseFor404) | Pet not found +405 | [ApiResponseFor405](#update_pet.ApiResponseFor405) | Validation exception + +#### update_pet.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### update_pet.ApiResponseFor404 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### update_pet.ApiResponseFor405 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +[http_signature_test](../../../README.md#http_signature_test), [petstore_auth](../../../README.md#petstore_auth) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **update_pet_with_form** + +> update_pet_with_form(pet_id) + +Updates a pet in the store with form data + +### Example + +* OAuth Authentication (petstore_auth): +```python +import petstore_api +from petstore_api.apis.tags import pet_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'petId': 1, + } + try: + # Updates a pet in the store with form data + api_response = api_instance.update_pet_with_form( + path_params=path_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) + + # example passing only optional values + path_params = { + 'petId': 1, + } + body = dict( + name="name_example", + status="status_example", + ) + try: + # Updates a pet in the store with form data + api_response = api_instance.update_pet_with_form( + path_params=path_params, + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, Unset] | optional, default is unset | +path_params | RequestPathParams | | +content_type | str | optional, default is 'application/x-www-form-urlencoded' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationXWwwFormUrlencoded + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**name** | str, | str, | Updated name of the pet | [optional] +**status** | str, | str, | Updated status of the pet | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +petId | PetIdSchema | | + +# PetIdSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +405 | [ApiResponseFor405](#update_pet_with_form.ApiResponseFor405) | Invalid input + +#### update_pet_with_form.ApiResponseFor405 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +[petstore_auth](../../../README.md#petstore_auth) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **upload_file_with_required_file** + +> ApiResponse upload_file_with_required_file(pet_id) + +uploads an image (required) + +### Example + +* OAuth Authentication (petstore_auth): +```python +import petstore_api +from petstore_api.apis.tags import pet_api +from petstore_api.model.api_response import ApiResponse +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'petId': 1, + } + try: + # uploads an image (required) + api_response = api_instance.upload_file_with_required_file( + path_params=path_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_file_with_required_file: %s\n" % e) + + # example passing only optional values + path_params = { + 'petId': 1, + } + body = dict( + additional_metadata="additional_metadata_example", + required_file=open('/path/to/file', 'rb'), + ) + try: + # uploads an image (required) + api_response = api_instance.upload_file_with_required_file( + path_params=path_params, + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_file_with_required_file: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | +path_params | RequestPathParams | | +content_type | str | optional, default is 'multipart/form-data' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyMultipartFormData + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**requiredFile** | bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | file to upload | +**additionalMetadata** | str, | str, | Additional data to pass to server | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +petId | PetIdSchema | | + +# PetIdSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#upload_file_with_required_file.ApiResponseFor200) | successful operation + +#### upload_file_with_required_file.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ApiResponse**](../../models/ApiResponse.md) | | + + +### Authorization + +[petstore_auth](../../../README.md#petstore_auth) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **upload_image** + +> ApiResponse upload_image(pet_id) + +uploads an image + +### Example + +* OAuth Authentication (petstore_auth): +```python +import petstore_api +from petstore_api.apis.tags import pet_api +from petstore_api.model.api_response import ApiResponse +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'petId': 1, + } + try: + # uploads an image + api_response = api_instance.upload_image( + path_params=path_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_image: %s\n" % e) + + # example passing only optional values + path_params = { + 'petId': 1, + } + body = dict( + additional_metadata="additional_metadata_example", + file=open('/path/to/file', 'rb'), + ) + try: + # uploads an image + api_response = api_instance.upload_image( + path_params=path_params, + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_image: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyMultipartFormData, Unset] | optional, default is unset | +path_params | RequestPathParams | | +content_type | str | optional, default is 'multipart/form-data' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyMultipartFormData + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**additionalMetadata** | str, | str, | Additional data to pass to server | [optional] +**file** | bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | file to upload | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +petId | PetIdSchema | | + +# PetIdSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#upload_image.ApiResponseFor200) | successful operation + +#### upload_image.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**ApiResponse**](../../models/ApiResponse.md) | | + + +### Authorization + +[petstore_auth](../../../README.md#petstore_auth) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/apis/tags/StoreApi.md b/samples/openapi3/client/petstore/python/docs/apis/tags/StoreApi.md new file mode 100644 index 0000000000..a75abbcffc --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/apis/tags/StoreApi.md @@ -0,0 +1,391 @@ + +# petstore_api.apis.tags.store_api.StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_order**](#delete_order) | **delete** /store/order/{order_id} | Delete purchase order by ID +[**get_inventory**](#get_inventory) | **get** /store/inventory | Returns pet inventories by status +[**get_order_by_id**](#get_order_by_id) | **get** /store/order/{order_id} | Find purchase order by ID +[**place_order**](#place_order) | **post** /store/order | Place an order for a pet + +# **delete_order** + +> delete_order(order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import store_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = store_api.StoreApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'order_id': "order_id_example", + } + try: + # Delete purchase order by ID + api_response = api_instance.delete_order( + path_params=path_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling StoreApi->delete_order: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +path_params | RequestPathParams | | +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +order_id | OrderIdSchema | | + +# OrderIdSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +400 | [ApiResponseFor400](#delete_order.ApiResponseFor400) | Invalid ID supplied +404 | [ApiResponseFor404](#delete_order.ApiResponseFor404) | Order not found + +#### delete_order.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### delete_order.ApiResponseFor404 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **get_inventory** + +> {str: (int,)} get_inventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example + +* Api Key Authentication (api_key): +```python +import petstore_api +from petstore_api.apis.tags import store_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure API key authorization: api_key +configuration.api_key['api_key'] = 'YOUR_API_KEY' + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['api_key'] = 'Bearer' +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = store_api.StoreApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Returns pet inventories by status + api_response = api_instance.get_inventory() + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling StoreApi->get_inventory: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#get_inventory.ApiResponseFor200) | successful operation + +#### get_inventory.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | decimal.Decimal, int, | decimal.Decimal, | any string name can be used but the value must be the correct type | [optional] value must be a 32 bit integer + +### Authorization + +[api_key](../../../README.md#api_key) + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **get_order_by_id** + +> Order get_order_by_id(order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import store_api +from petstore_api.model.order import Order +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = store_api.StoreApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'order_id': 1, + } + try: + # Find purchase order by ID + api_response = api_instance.get_order_by_id( + path_params=path_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling StoreApi->get_order_by_id: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +path_params | RequestPathParams | | +accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +order_id | OrderIdSchema | | + +# OrderIdSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#get_order_by_id.ApiResponseFor200) | successful operation +400 | [ApiResponseFor400](#get_order_by_id.ApiResponseFor400) | Invalid ID supplied +404 | [ApiResponseFor404](#get_order_by_id.ApiResponseFor404) | Order not found + +#### get_order_by_id.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationXml +Type | Description | Notes +------------- | ------------- | ------------- +[**Order**](../../models/Order.md) | | + + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Order**](../../models/Order.md) | | + + +#### get_order_by_id.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### get_order_by_id.ApiResponseFor404 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **place_order** + +> Order place_order(order) + +Place an order for a pet + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import store_api +from petstore_api.model.order import Order +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = store_api.StoreApi(api_client) + + # example passing only required values which don't have defaults set + body = Order( + id=1, + pet_id=1, + quantity=1, + ship_date="2020-02-02T20:20:20.000222Z", + status="placed", + complete=False, + ) + try: + # Place an order for a pet + api_response = api_instance.place_order( + body=body, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling StoreApi->place_order: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Order**](../../models/Order.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#place_order.ApiResponseFor200) | successful operation +400 | [ApiResponseFor400](#place_order.ApiResponseFor400) | Invalid Order + +#### place_order.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationXml +Type | Description | Notes +------------- | ------------- | ------------- +[**Order**](../../models/Order.md) | | + + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**Order**](../../models/Order.md) | | + + +#### place_order.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/apis/tags/UserApi.md b/samples/openapi3/client/petstore/python/docs/apis/tags/UserApi.md new file mode 100644 index 0000000000..6b0fd83c5d --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/apis/tags/UserApi.md @@ -0,0 +1,794 @@ + +# petstore_api.apis.tags.user_api.UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_user**](#create_user) | **post** /user | Create user +[**create_users_with_array_input**](#create_users_with_array_input) | **post** /user/createWithArray | Creates list of users with given input array +[**create_users_with_list_input**](#create_users_with_list_input) | **post** /user/createWithList | Creates list of users with given input array +[**delete_user**](#delete_user) | **delete** /user/{username} | Delete user +[**get_user_by_name**](#get_user_by_name) | **get** /user/{username} | Get user by user name +[**login_user**](#login_user) | **get** /user/login | Logs user into the system +[**logout_user**](#logout_user) | **get** /user/logout | Logs out current logged in user session +[**update_user**](#update_user) | **put** /user/{username} | Updated user + +# **create_user** + +> create_user(user) + +Create user + +This can only be done by the logged in user. + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + + # example passing only required values which don't have defaults set + body = User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + object_with_no_declared_props=dict(), + object_with_no_declared_props_nullable=dict(), + any_type_prop=None, + any_type_except_null_prop=None, + any_type_prop_nullable=None, + ) + try: + # Create user + api_response = api_instance.create_user( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->create_user: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**User**](../../models/User.md) | | + + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +default | [ApiResponseForDefault](#create_user.ApiResponseForDefault) | successful operation + +#### create_user.ApiResponseForDefault +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **create_users_with_array_input** + +> create_users_with_array_input(user) + +Creates list of users with given input array + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + + # example passing only required values which don't have defaults set + body = [ + User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + object_with_no_declared_props=dict(), + object_with_no_declared_props_nullable=dict(), + any_type_prop=None, + any_type_except_null_prop=None, + any_type_prop_nullable=None, + ) + ] + try: + # Creates list of users with given input array + api_response = api_instance.create_users_with_array_input( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->create_users_with_array_input: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**User**]({{complexTypePrefix}}User.md) | [**User**]({{complexTypePrefix}}User.md) | [**User**]({{complexTypePrefix}}User.md) | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +default | [ApiResponseForDefault](#create_users_with_array_input.ApiResponseForDefault) | successful operation + +#### create_users_with_array_input.ApiResponseForDefault +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **create_users_with_list_input** + +> create_users_with_list_input(user) + +Creates list of users with given input array + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + + # example passing only required values which don't have defaults set + body = [ + User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + object_with_no_declared_props=dict(), + object_with_no_declared_props_nullable=dict(), + any_type_prop=None, + any_type_except_null_prop=None, + any_type_prop_nullable=None, + ) + ] + try: + # Creates list of users with given input array + api_response = api_instance.create_users_with_list_input( + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->create_users_with_list_input: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**User**]({{complexTypePrefix}}User.md) | [**User**]({{complexTypePrefix}}User.md) | [**User**]({{complexTypePrefix}}User.md) | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +default | [ApiResponseForDefault](#create_users_with_list_input.ApiResponseForDefault) | successful operation + +#### create_users_with_list_input.ApiResponseForDefault +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **delete_user** + +> delete_user(username) + +Delete user + +This can only be done by the logged in user. + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import user_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'username': "username_example", + } + try: + # Delete user + api_response = api_instance.delete_user( + path_params=path_params, + ) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->delete_user: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +path_params | RequestPathParams | | +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +username | UsernameSchema | | + +# UsernameSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#delete_user.ApiResponseFor200) | Success +404 | [ApiResponseFor404](#delete_user.ApiResponseFor404) | User not found + +#### delete_user.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### delete_user.ApiResponseFor404 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **get_user_by_name** + +> User get_user_by_name(username) + +Get user by user name + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'username': "username_example", + } + try: + # Get user by user name + api_response = api_instance.get_user_by_name( + path_params=path_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->get_user_by_name: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +path_params | RequestPathParams | | +accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +username | UsernameSchema | | + +# UsernameSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#get_user_by_name.ApiResponseFor200) | successful operation +400 | [ApiResponseFor400](#get_user_by_name.ApiResponseFor400) | Invalid username supplied +404 | [ApiResponseFor404](#get_user_by_name.ApiResponseFor404) | User not found + +#### get_user_by_name.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | +headers | Unset | headers were not defined | + +# SchemaFor200ResponseBodyApplicationXml +Type | Description | Notes +------------- | ------------- | ------------- +[**User**](../../models/User.md) | | + + +# SchemaFor200ResponseBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**User**](../../models/User.md) | | + + +#### get_user_by_name.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### get_user_by_name.ApiResponseFor404 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **login_user** + +> str login_user(usernamepassword) + +Logs user into the system + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import user_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + + # example passing only required values which don't have defaults set + query_params = { + 'username': "username_example", + 'password': "password_example", + } + try: + # Logs user into the system + api_response = api_instance.login_user( + query_params=query_params, + ) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->login_user: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +query_params | RequestQueryParams | | +accept_content_types | typing.Tuple[str] | default is ('application/xml', 'application/json', ) | Tells the server the content type(s) that are accepted by the client +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +username | UsernameSchema | | +password | PasswordSchema | | + + +# UsernameSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# PasswordSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +200 | [ApiResponseFor200](#login_user.ApiResponseFor200) | successful operation +400 | [ApiResponseFor400](#login_user.ApiResponseFor400) | Invalid username/password supplied + +#### login_user.ApiResponseFor200 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | typing.Union[SchemaFor200ResponseBodyApplicationXml, SchemaFor200ResponseBodyApplicationJson, ] | | +headers | ResponseHeadersFor200 | | + +# SchemaFor200ResponseBodyApplicationXml + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# SchemaFor200ResponseBodyApplicationJson + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | +#### ResponseHeadersFor200 + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +X-Rate-Limit | XRateLimitSchema | | optional +X-Expires-After | XExpiresAfterSchema | | optional + +# XRateLimitSchema + +calls per hour allowed by the user + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | calls per hour allowed by the user | value must be a 32 bit integer + +# XExpiresAfterSchema + +date in UTC when token expires + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, datetime, | str, | date in UTC when token expires | value must conform to RFC-3339 date-time + + +#### login_user.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **logout_user** + +> logout_user() + +Logs out current logged in user session + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import user_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Logs out current logged in user session + api_response = api_instance.logout_user() + except petstore_api.ApiException as e: + print("Exception when calling UserApi->logout_user: %s\n" % e) +``` +### Parameters +This endpoint does not need any parameter. + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +default | [ApiResponseForDefault](#logout_user.ApiResponseForDefault) | successful operation + +#### logout_user.ApiResponseForDefault +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + +# **update_user** + +> update_user(usernameuser) + +Updated user + +This can only be done by the logged in user. + +### Example + +```python +import petstore_api +from petstore_api.apis.tags import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + + # example passing only required values which don't have defaults set + path_params = { + 'username': "username_example", + } + body = User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + object_with_no_declared_props=dict(), + object_with_no_declared_props_nullable=dict(), + any_type_prop=None, + any_type_except_null_prop=None, + any_type_prop_nullable=None, + ) + try: + # Updated user + api_response = api_instance.update_user( + path_params=path_params, + body=body, + ) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->update_user: %s\n" % e) +``` +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +body | typing.Union[SchemaForRequestBodyApplicationJson] | required | +path_params | RequestPathParams | | +content_type | str | optional, default is 'application/json' | Selects the schema and serialization of the request body +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + +### body + +# SchemaForRequestBodyApplicationJson +Type | Description | Notes +------------- | ------------- | ------------- +[**User**](../../models/User.md) | | + + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +username | UsernameSchema | | + +# UsernameSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +400 | [ApiResponseFor400](#update_user.ApiResponseFor400) | Invalid user supplied +404 | [ApiResponseFor404](#update_user.ApiResponseFor404) | User not found + +#### update_user.ApiResponseFor400 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +#### update_user.ApiResponseFor404 +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | Unset | body was not defined | +headers | Unset | headers were not defined | + +### Authorization + +No authorization required + +[[Back to top]](#__pageTop) [[Back to API list]](../../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../../README.md#documentation-for-models) [[Back to README]](../../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/models/AdditionalPropertiesClass.md new file mode 100644 index 0000000000..80e4e77099 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/AdditionalPropertiesClass.md @@ -0,0 +1,109 @@ +# petstore_api.model.additional_properties_class.AdditionalPropertiesClass + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[map_property](#map_property)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**[map_of_map_property](#map_of_map_property)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**anytype_1** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**[map_with_undeclared_properties_anytype_1](#map_with_undeclared_properties_anytype_1)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**[map_with_undeclared_properties_anytype_2](#map_with_undeclared_properties_anytype_2)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**[map_with_undeclared_properties_anytype_3](#map_with_undeclared_properties_anytype_3)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**[empty_map](#empty_map)** | dict, frozendict.frozendict, | frozendict.frozendict, | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] +**[map_with_undeclared_properties_string](#map_with_undeclared_properties_string)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# map_property + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | str, | str, | any string name can be used but the value must be the correct type | [optional] + +# map_of_map_property + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[any_string_name](#any_string_name)** | dict, frozendict.frozendict, | frozendict.frozendict, | any string name can be used but the value must be the correct type | [optional] + +# any_string_name + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | str, | str, | any string name can be used but the value must be the correct type | [optional] + +# map_with_undeclared_properties_anytype_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +# map_with_undeclared_properties_anytype_2 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +# map_with_undeclared_properties_anytype_3 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# empty_map + +an object with no declared properties and no undeclared properties, hence it's an empty map. + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | an object with no declared properties and no undeclared properties, hence it's an empty map. | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- + +# map_with_undeclared_properties_string + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | str, | str, | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/AdditionalPropertiesValidator.md b/samples/openapi3/client/petstore/python/docs/models/AdditionalPropertiesValidator.md new file mode 100644 index 0000000000..4a386a3864 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/AdditionalPropertiesValidator.md @@ -0,0 +1,53 @@ +# petstore_api.model.additional_properties_validator.AdditionalPropertiesValidator + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, | frozendict.frozendict, | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, | frozendict.frozendict, | | +[all_of_2](#all_of_2) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# all_of_2 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/AdditionalPropertiesWithArrayOfEnums.md b/samples/openapi3/client/petstore/python/docs/models/AdditionalPropertiesWithArrayOfEnums.md new file mode 100644 index 0000000000..22dd693183 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/AdditionalPropertiesWithArrayOfEnums.md @@ -0,0 +1,26 @@ +# petstore_api.model.additional_properties_with_array_of_enums.AdditionalPropertiesWithArrayOfEnums + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[any_string_name](#any_string_name)** | list, tuple, | tuple, | any string name can be used but the value must be the correct type | [optional] + +# any_string_name + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**EnumClass**](EnumClass.md) | [**EnumClass**](EnumClass.md) | [**EnumClass**](EnumClass.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Address.md b/samples/openapi3/client/petstore/python/docs/models/Address.md new file mode 100644 index 0000000000..1ec43dfd0b --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Address.md @@ -0,0 +1,14 @@ +# petstore_api.model.address.Address + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | decimal.Decimal, int, | decimal.Decimal, | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Animal.md b/samples/openapi3/client/petstore/python/docs/models/Animal.md new file mode 100644 index 0000000000..bf064d289e --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Animal.md @@ -0,0 +1,16 @@ +# petstore_api.model.animal.Animal + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**className** | str, | str, | | +**color** | str, | str, | | [optional] if omitted the server will use the default value of "red" +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/AnimalFarm.md b/samples/openapi3/client/petstore/python/docs/models/AnimalFarm.md new file mode 100644 index 0000000000..f1b1468e77 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/AnimalFarm.md @@ -0,0 +1,14 @@ +# petstore_api.model.animal_farm.AnimalFarm + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**Animal**](Animal.md) | [**Animal**](Animal.md) | [**Animal**](Animal.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/AnyTypeAndFormat.md b/samples/openapi3/client/petstore/python/docs/models/AnyTypeAndFormat.md new file mode 100644 index 0000000000..812e5c6a1e --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/AnyTypeAndFormat.md @@ -0,0 +1,23 @@ +# petstore_api.model.any_type_and_format.AnyTypeAndFormat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**uuid** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] value must be a uuid +**date** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] value must conform to RFC-3339 full-date YYYY-MM-DD +**date-time** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] value must conform to RFC-3339 date-time +**number** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] value must be numeric and storable in decimal.Decimal +**binary** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**int32** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] value must be a 32 bit integer +**int64** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] value must be a 64 bit integer +**double** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] value must be a 64 bit float +**float** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] value must be a 32 bit float +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/AnyTypeNotString.md b/samples/openapi3/client/petstore/python/docs/models/AnyTypeNotString.md new file mode 100644 index 0000000000..ff57ed8d21 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/AnyTypeNotString.md @@ -0,0 +1,22 @@ +# petstore_api.model.any_type_not_string.AnyTypeNotString + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | str, | str, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ApiResponse.md b/samples/openapi3/client/petstore/python/docs/models/ApiResponse.md new file mode 100644 index 0000000000..578aa06cb5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ApiResponse.md @@ -0,0 +1,17 @@ +# petstore_api.model.api_response.ApiResponse + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**code** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 32 bit integer +**type** | str, | str, | | [optional] +**message** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Apple.md b/samples/openapi3/client/petstore/python/docs/models/Apple.md new file mode 100644 index 0000000000..84c3ab8da5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Apple.md @@ -0,0 +1,16 @@ +# petstore_api.model.apple.Apple + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**cultivar** | str, | str, | | +**origin** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/AppleReq.md b/samples/openapi3/client/petstore/python/docs/models/AppleReq.md new file mode 100644 index 0000000000..59e2c1b00c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/AppleReq.md @@ -0,0 +1,15 @@ +# petstore_api.model.apple_req.AppleReq + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**cultivar** | str, | str, | | +**mealy** | bool, | BoolClass, | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ArrayHoldingAnyType.md b/samples/openapi3/client/petstore/python/docs/models/ArrayHoldingAnyType.md new file mode 100644 index 0000000000..7dc14c3018 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ArrayHoldingAnyType.md @@ -0,0 +1,14 @@ +# petstore_api.model.array_holding_any_type.ArrayHoldingAnyType + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | any type can be stored here | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/models/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 0000000000..b3e7a281e0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,39 @@ +# petstore_api.model.array_of_array_of_number_only.ArrayOfArrayOfNumberOnly + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[ArrayArrayNumber](#ArrayArrayNumber)** | list, tuple, | tuple, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# ArrayArrayNumber + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | list, tuple, | tuple, | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | decimal.Decimal, int, float, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ArrayOfEnums.md b/samples/openapi3/client/petstore/python/docs/models/ArrayOfEnums.md new file mode 100644 index 0000000000..dca614b9ae --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ArrayOfEnums.md @@ -0,0 +1,14 @@ +# petstore_api.model.array_of_enums.ArrayOfEnums + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**StringEnum**](StringEnum.md) | [**StringEnum**](StringEnum.md) | [**StringEnum**](StringEnum.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/models/ArrayOfNumberOnly.md new file mode 100644 index 0000000000..271dff52fd --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ArrayOfNumberOnly.md @@ -0,0 +1,27 @@ +# petstore_api.model.array_of_number_only.ArrayOfNumberOnly + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[ArrayNumber](#ArrayNumber)** | list, tuple, | tuple, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# ArrayNumber + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | decimal.Decimal, int, float, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ArrayTest.md b/samples/openapi3/client/petstore/python/docs/models/ArrayTest.md new file mode 100644 index 0000000000..657329575e --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ArrayTest.md @@ -0,0 +1,77 @@ +# petstore_api.model.array_test.ArrayTest + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[array_of_string](#array_of_string)** | list, tuple, | tuple, | | [optional] +**[array_array_of_integer](#array_array_of_integer)** | list, tuple, | tuple, | | [optional] +**[array_array_of_model](#array_array_of_model)** | list, tuple, | tuple, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# array_of_string + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | + +# array_array_of_integer + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | list, tuple, | tuple, | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +# array_array_of_model + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | list, tuple, | tuple, | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**ReadOnlyFirst**](ReadOnlyFirst.md) | [**ReadOnlyFirst**](ReadOnlyFirst.md) | [**ReadOnlyFirst**](ReadOnlyFirst.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ArrayWithValidationsInItems.md b/samples/openapi3/client/petstore/python/docs/models/ArrayWithValidationsInItems.md new file mode 100644 index 0000000000..b81ab8cd5d --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ArrayWithValidationsInItems.md @@ -0,0 +1,14 @@ +# petstore_api.model.array_with_validations_in_items.ArrayWithValidationsInItems + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Banana.md b/samples/openapi3/client/petstore/python/docs/models/Banana.md new file mode 100644 index 0000000000..034c7f7770 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Banana.md @@ -0,0 +1,15 @@ +# petstore_api.model.banana.Banana + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**lengthCm** | decimal.Decimal, int, float, | decimal.Decimal, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/BananaReq.md b/samples/openapi3/client/petstore/python/docs/models/BananaReq.md new file mode 100644 index 0000000000..ae53efbfe9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/BananaReq.md @@ -0,0 +1,15 @@ +# petstore_api.model.banana_req.BananaReq + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**lengthCm** | decimal.Decimal, int, float, | decimal.Decimal, | | +**sweet** | bool, | BoolClass, | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Bar.md b/samples/openapi3/client/petstore/python/docs/models/Bar.md new file mode 100644 index 0000000000..55aa05fa18 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Bar.md @@ -0,0 +1,9 @@ +# petstore_api.model.bar.Bar + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | if omitted the server will use the default value of "bar" + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/BasquePig.md b/samples/openapi3/client/petstore/python/docs/models/BasquePig.md new file mode 100644 index 0000000000..b0860be169 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/BasquePig.md @@ -0,0 +1,15 @@ +# petstore_api.model.basque_pig.BasquePig + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**className** | str, | str, | | must be one of ["BasquePig", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Boolean.md b/samples/openapi3/client/petstore/python/docs/models/Boolean.md new file mode 100644 index 0000000000..c2e0e952ac --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Boolean.md @@ -0,0 +1,9 @@ +# petstore_api.model.boolean.Boolean + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/BooleanEnum.md b/samples/openapi3/client/petstore/python/docs/models/BooleanEnum.md new file mode 100644 index 0000000000..a84330415c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/BooleanEnum.md @@ -0,0 +1,9 @@ +# petstore_api.model.boolean_enum.BooleanEnum + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | must be one of [True, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Capitalization.md b/samples/openapi3/client/petstore/python/docs/models/Capitalization.md new file mode 100644 index 0000000000..cc39af70e1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Capitalization.md @@ -0,0 +1,20 @@ +# petstore_api.model.capitalization.Capitalization + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**smallCamel** | str, | str, | | [optional] +**CapitalCamel** | str, | str, | | [optional] +**small_Snake** | str, | str, | | [optional] +**Capital_Snake** | str, | str, | | [optional] +**SCA_ETH_Flow_Points** | str, | str, | | [optional] +**ATT_NAME** | str, | str, | Name of the pet | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Cat.md b/samples/openapi3/client/petstore/python/docs/models/Cat.md new file mode 100644 index 0000000000..b5e0986f57 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Cat.md @@ -0,0 +1,29 @@ +# petstore_api.model.cat.Cat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[Animal](Animal.md) | [**Animal**](Animal.md) | [**Animal**](Animal.md) | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**declawed** | bool, | BoolClass, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Category.md b/samples/openapi3/client/petstore/python/docs/models/Category.md new file mode 100644 index 0000000000..0087571a3a --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Category.md @@ -0,0 +1,16 @@ +# petstore_api.model.category.Category + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**name** | str, | str, | | if omitted the server will use the default value of "default-name" +**id** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 64 bit integer +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ChildCat.md b/samples/openapi3/client/petstore/python/docs/models/ChildCat.md new file mode 100644 index 0000000000..645ea5062d --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ChildCat.md @@ -0,0 +1,29 @@ +# petstore_api.model.child_cat.ChildCat + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[ParentPet](ParentPet.md) | [**ParentPet**](ParentPet.md) | [**ParentPet**](ParentPet.md) | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**name** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ClassModel.md b/samples/openapi3/client/petstore/python/docs/models/ClassModel.md new file mode 100644 index 0000000000..b1686ebb79 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ClassModel.md @@ -0,0 +1,17 @@ +# petstore_api.model.class_model.ClassModel + +Model for testing model with \"_class\" property + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | Model for testing model with \"_class\" property | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**_class** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Client.md b/samples/openapi3/client/petstore/python/docs/models/Client.md new file mode 100644 index 0000000000..e94c360dd2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Client.md @@ -0,0 +1,15 @@ +# petstore_api.model.client.Client + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**client** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ComplexQuadrilateral.md b/samples/openapi3/client/petstore/python/docs/models/ComplexQuadrilateral.md new file mode 100644 index 0000000000..a00ac0d9da --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ComplexQuadrilateral.md @@ -0,0 +1,29 @@ +# petstore_api.model.complex_quadrilateral.ComplexQuadrilateral + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[QuadrilateralInterface](QuadrilateralInterface.md) | [**QuadrilateralInterface**](QuadrilateralInterface.md) | [**QuadrilateralInterface**](QuadrilateralInterface.md) | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**quadrilateralType** | str, | str, | | [optional] must be one of ["ComplexQuadrilateral", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ComposedAnyOfDifferentTypesNoValidations.md b/samples/openapi3/client/petstore/python/docs/models/ComposedAnyOfDifferentTypesNoValidations.md new file mode 100644 index 0000000000..f4389c50eb --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ComposedAnyOfDifferentTypesNoValidations.md @@ -0,0 +1,147 @@ +# petstore_api.model.composed_any_of_different_types_no_validations.ComposedAnyOfDifferentTypesNoValidations + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[any_of_0](#any_of_0) | dict, frozendict.frozendict, | frozendict.frozendict, | | +[any_of_1](#any_of_1) | str, date, | str, | | value must conform to RFC-3339 full-date YYYY-MM-DD +[any_of_2](#any_of_2) | str, datetime, | str, | | value must conform to RFC-3339 date-time +[any_of_3](#any_of_3) | bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | | +[any_of_4](#any_of_4) | str, | str, | | +[any_of_5](#any_of_5) | str, | str, | | +[any_of_6](#any_of_6) | dict, frozendict.frozendict, | frozendict.frozendict, | | +[any_of_7](#any_of_7) | bool, | BoolClass, | | +[any_of_8](#any_of_8) | None, | NoneClass, | | +[any_of_9](#any_of_9) | list, tuple, | tuple, | | +[any_of_10](#any_of_10) | decimal.Decimal, int, float, | decimal.Decimal, | | +[any_of_11](#any_of_11) | decimal.Decimal, int, float, | decimal.Decimal, | | value must be a 32 bit float +[any_of_12](#any_of_12) | decimal.Decimal, int, float, | decimal.Decimal, | | value must be a 64 bit float +[any_of_13](#any_of_13) | decimal.Decimal, int, | decimal.Decimal, | | +[any_of_14](#any_of_14) | decimal.Decimal, int, | decimal.Decimal, | | value must be a 32 bit integer +[any_of_15](#any_of_15) | decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +# any_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +# any_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, date, | str, | | value must conform to RFC-3339 full-date YYYY-MM-DD + +# any_of_2 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, datetime, | str, | | value must conform to RFC-3339 date-time + +# any_of_3 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | | + +# any_of_4 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# any_of_5 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +# any_of_6 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +# any_of_7 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +# any_of_8 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +# any_of_9 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# any_of_10 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +# any_of_11 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | value must be a 32 bit float + +# any_of_12 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | value must be a 64 bit float + +# any_of_13 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | + +# any_of_14 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 32 bit integer + +# any_of_15 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ComposedArray.md b/samples/openapi3/client/petstore/python/docs/models/ComposedArray.md new file mode 100644 index 0000000000..bc506aa5f8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ComposedArray.md @@ -0,0 +1,14 @@ +# petstore_api.model.composed_array.ComposedArray + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ComposedBool.md b/samples/openapi3/client/petstore/python/docs/models/ComposedBool.md new file mode 100644 index 0000000000..29ed69f72f --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ComposedBool.md @@ -0,0 +1,22 @@ +# petstore_api.model.composed_bool.ComposedBool + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +bool, | BoolClass, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ComposedNone.md b/samples/openapi3/client/petstore/python/docs/models/ComposedNone.md new file mode 100644 index 0000000000..df4ec85f2c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ComposedNone.md @@ -0,0 +1,22 @@ +# petstore_api.model.composed_none.ComposedNone + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ComposedNumber.md b/samples/openapi3/client/petstore/python/docs/models/ComposedNumber.md new file mode 100644 index 0000000000..fa1f87c730 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ComposedNumber.md @@ -0,0 +1,22 @@ +# petstore_api.model.composed_number.ComposedNumber + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ComposedObject.md b/samples/openapi3/client/petstore/python/docs/models/ComposedObject.md new file mode 100644 index 0000000000..ebbbaede6b --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ComposedObject.md @@ -0,0 +1,22 @@ +# petstore_api.model.composed_object.ComposedObject + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ComposedOneOfDifferentTypes.md b/samples/openapi3/client/petstore/python/docs/models/ComposedOneOfDifferentTypes.md new file mode 100644 index 0000000000..0094f7e44c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ComposedOneOfDifferentTypes.md @@ -0,0 +1,63 @@ +# petstore_api.model.composed_one_of_different_types.ComposedOneOfDifferentTypes + +this is a model that allows payloads of type object or number + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | this is a model that allows payloads of type object or number | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[NumberWithValidations](NumberWithValidations.md) | [**NumberWithValidations**](NumberWithValidations.md) | [**NumberWithValidations**](NumberWithValidations.md) | | +[Animal](Animal.md) | [**Animal**](Animal.md) | [**Animal**](Animal.md) | | +[one_of_2](#one_of_2) | None, | NoneClass, | | +[one_of_3](#one_of_3) | str, date, | str, | | value must conform to RFC-3339 full-date YYYY-MM-DD +[one_of_4](#one_of_4) | dict, frozendict.frozendict, | frozendict.frozendict, | | +[one_of_5](#one_of_5) | list, tuple, | tuple, | | +[one_of_6](#one_of_6) | str, datetime, | str, | | value must conform to RFC-3339 date-time + +# one_of_2 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +# one_of_3 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, date, | str, | | value must conform to RFC-3339 full-date YYYY-MM-DD + +# one_of_4 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +# one_of_5 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# one_of_6 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, datetime, | str, | | value must conform to RFC-3339 date-time + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ComposedString.md b/samples/openapi3/client/petstore/python/docs/models/ComposedString.md new file mode 100644 index 0000000000..235511b37a --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ComposedString.md @@ -0,0 +1,22 @@ +# petstore_api.model.composed_string.ComposedString + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Currency.md b/samples/openapi3/client/petstore/python/docs/models/Currency.md new file mode 100644 index 0000000000..eeb1c6a47d --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Currency.md @@ -0,0 +1,9 @@ +# petstore_api.model.currency.Currency + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | must be one of ["eur", "usd", ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/DanishPig.md b/samples/openapi3/client/petstore/python/docs/models/DanishPig.md new file mode 100644 index 0000000000..15917a42ef --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/DanishPig.md @@ -0,0 +1,15 @@ +# petstore_api.model.danish_pig.DanishPig + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**className** | str, | str, | | must be one of ["DanishPig", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/DateTimeTest.md b/samples/openapi3/client/petstore/python/docs/models/DateTimeTest.md new file mode 100644 index 0000000000..ccfc8df593 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/DateTimeTest.md @@ -0,0 +1,9 @@ +# petstore_api.model.date_time_test.DateTimeTest + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, datetime, | str, | | if omitted the server will use the default value of 2010-01-01T10:10:10.000111+01:00value must conform to RFC-3339 date-time + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/DateTimeWithValidations.md b/samples/openapi3/client/petstore/python/docs/models/DateTimeWithValidations.md new file mode 100644 index 0000000000..ed7dfc06d1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/DateTimeWithValidations.md @@ -0,0 +1,9 @@ +# petstore_api.model.date_time_with_validations.DateTimeWithValidations + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, datetime, | str, | | value must conform to RFC-3339 date-time + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/DateWithValidations.md b/samples/openapi3/client/petstore/python/docs/models/DateWithValidations.md new file mode 100644 index 0000000000..97901a33f5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/DateWithValidations.md @@ -0,0 +1,9 @@ +# petstore_api.model.date_with_validations.DateWithValidations + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, date, | str, | | value must conform to RFC-3339 full-date YYYY-MM-DD + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/DecimalPayload.md b/samples/openapi3/client/petstore/python/docs/models/DecimalPayload.md new file mode 100644 index 0000000000..26ef601ff9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/DecimalPayload.md @@ -0,0 +1,9 @@ +# petstore_api.model.decimal_payload.DecimalPayload + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | value must be numeric and storable in decimal.Decimal + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Dog.md b/samples/openapi3/client/petstore/python/docs/models/Dog.md new file mode 100644 index 0000000000..08201e4423 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Dog.md @@ -0,0 +1,29 @@ +# petstore_api.model.dog.Dog + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[Animal](Animal.md) | [**Animal**](Animal.md) | [**Animal**](Animal.md) | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**breed** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Drawing.md b/samples/openapi3/client/petstore/python/docs/models/Drawing.md new file mode 100644 index 0000000000..dce65cbb0b --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Drawing.md @@ -0,0 +1,30 @@ +# petstore_api.model.drawing.Drawing + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**mainShape** | [**Shape**](Shape.md) | [**Shape**](Shape.md) | | [optional] +**shapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] +**nullableShape** | [**NullableShape**](NullableShape.md) | [**NullableShape**](NullableShape.md) | | [optional] +**[shapes](#shapes)** | list, tuple, | tuple, | | [optional] +**any_string_name** | [**Fruit**](Fruit.md) | [**Fruit**](Fruit.md) | any string name can be used but the value must be the correct type | [optional] + +# shapes + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**Shape**](Shape.md) | [**Shape**](Shape.md) | [**Shape**](Shape.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/EnumArrays.md b/samples/openapi3/client/petstore/python/docs/models/EnumArrays.md new file mode 100644 index 0000000000..cfff6ea29b --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/EnumArrays.md @@ -0,0 +1,28 @@ +# petstore_api.model.enum_arrays.EnumArrays + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**just_symbol** | str, | str, | | [optional] must be one of [">=", "$", ] +**[array_enum](#array_enum)** | list, tuple, | tuple, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# array_enum + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | must be one of ["fish", "crab", ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/EnumClass.md b/samples/openapi3/client/petstore/python/docs/models/EnumClass.md new file mode 100644 index 0000000000..9e08aab145 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/EnumClass.md @@ -0,0 +1,9 @@ +# petstore_api.model.enum_class.EnumClass + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | must be one of ["_abc", "-efg", "(xyz)", "COUNT_1M", "COUNT_50M", ] if omitted the server will use the default value of "-efg" + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/EnumTest.md b/samples/openapi3/client/petstore/python/docs/models/EnumTest.md new file mode 100644 index 0000000000..02c3b08a20 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/EnumTest.md @@ -0,0 +1,23 @@ +# petstore_api.model.enum_test.EnumTest + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**enum_string_required** | str, | str, | | must be one of ["UPPER", "lower", "", ] +**enum_string** | str, | str, | | [optional] must be one of ["UPPER", "lower", "", ] +**enum_integer** | decimal.Decimal, int, | decimal.Decimal, | | [optional] must be one of [1, -1, ] value must be a 32 bit integer +**enum_number** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] must be one of [1.1, -1.2, ] value must be a 64 bit float +**stringEnum** | [**StringEnum**](StringEnum.md) | [**StringEnum**](StringEnum.md) | | [optional] +**IntegerEnum** | [**IntegerEnum**](IntegerEnum.md) | [**IntegerEnum**](IntegerEnum.md) | | [optional] +**StringEnumWithDefaultValue** | [**StringEnumWithDefaultValue**](StringEnumWithDefaultValue.md) | [**StringEnumWithDefaultValue**](StringEnumWithDefaultValue.md) | | [optional] +**IntegerEnumWithDefaultValue** | [**IntegerEnumWithDefaultValue**](IntegerEnumWithDefaultValue.md) | [**IntegerEnumWithDefaultValue**](IntegerEnumWithDefaultValue.md) | | [optional] +**IntegerEnumOneValue** | [**IntegerEnumOneValue**](IntegerEnumOneValue.md) | [**IntegerEnumOneValue**](IntegerEnumOneValue.md) | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/EquilateralTriangle.md b/samples/openapi3/client/petstore/python/docs/models/EquilateralTriangle.md new file mode 100644 index 0000000000..96971a1c0c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/EquilateralTriangle.md @@ -0,0 +1,29 @@ +# petstore_api.model.equilateral_triangle.EquilateralTriangle + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[TriangleInterface](TriangleInterface.md) | [**TriangleInterface**](TriangleInterface.md) | [**TriangleInterface**](TriangleInterface.md) | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**triangleType** | str, | str, | | [optional] must be one of ["EquilateralTriangle", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/File.md b/samples/openapi3/client/petstore/python/docs/models/File.md new file mode 100644 index 0000000000..d85669c84f --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/File.md @@ -0,0 +1,17 @@ +# petstore_api.model.file.File + +Must be named `File` for test. + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | Must be named `File` for test. | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**sourceURI** | str, | str, | Test capitalization | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python/docs/models/FileSchemaTestClass.md new file mode 100644 index 0000000000..35dcfdca4e --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/FileSchemaTestClass.md @@ -0,0 +1,28 @@ +# petstore_api.model.file_schema_test_class.FileSchemaTestClass + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**file** | [**File**](File.md) | [**File**](File.md) | | [optional] +**[files](#files)** | list, tuple, | tuple, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# files + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**File**](File.md) | [**File**](File.md) | [**File**](File.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Foo.md b/samples/openapi3/client/petstore/python/docs/models/Foo.md new file mode 100644 index 0000000000..5ea8d33d36 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Foo.md @@ -0,0 +1,15 @@ +# petstore_api.model.foo.Foo + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**bar** | str, | str, | | [optional] if omitted the server will use the default value of "bar" +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/FormatTest.md b/samples/openapi3/client/petstore/python/docs/models/FormatTest.md new file mode 100644 index 0000000000..55ca4583a1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/FormatTest.md @@ -0,0 +1,47 @@ +# petstore_api.model.format_test.FormatTest + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**date** | str, date, | str, | | value must conform to RFC-3339 full-date YYYY-MM-DD +**number** | decimal.Decimal, int, float, | decimal.Decimal, | | +**password** | str, | str, | | +**byte** | str, | str, | | +**integer** | decimal.Decimal, int, | decimal.Decimal, | | [optional] +**int32** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 32 bit integer +**int32withValidations** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 32 bit integer +**int64** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 64 bit integer +**float** | decimal.Decimal, int, float, | decimal.Decimal, | this is a reserved python keyword | [optional] value must be a 32 bit float +**float32** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] value must be a 32 bit float +**double** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] value must be a 64 bit float +**float64** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] value must be a 64 bit float +**[arrayWithUniqueItems](#arrayWithUniqueItems)** | list, tuple, | tuple, | | [optional] +**string** | str, | str, | | [optional] +**binary** | bytes, io.FileIO, io.BufferedReader, | bytes, FileIO, | | [optional] +**dateTime** | str, datetime, | str, | | [optional] value must conform to RFC-3339 date-time +**uuid** | str, uuid.UUID, | str, | | [optional] value must be a uuid +**uuidNoExample** | str, uuid.UUID, | str, | | [optional] value must be a uuid +**pattern_with_digits** | str, | str, | A string that is a 10 digit number. Can have leading zeros. | [optional] +**pattern_with_digits_and_delimiter** | str, | str, | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] +**noneProp** | None, | NoneClass, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# arrayWithUniqueItems + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | decimal.Decimal, int, float, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/FromSchema.md b/samples/openapi3/client/petstore/python/docs/models/FromSchema.md new file mode 100644 index 0000000000..c11c63adb6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/FromSchema.md @@ -0,0 +1,16 @@ +# petstore_api.model.from_schema.FromSchema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**data** | str, | str, | | [optional] +**id** | decimal.Decimal, int, | decimal.Decimal, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Fruit.md b/samples/openapi3/client/petstore/python/docs/models/Fruit.md new file mode 100644 index 0000000000..44d670623f --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Fruit.md @@ -0,0 +1,22 @@ +# petstore_api.model.fruit.Fruit + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**color** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[Apple](Apple.md) | [**Apple**](Apple.md) | [**Apple**](Apple.md) | | +[Banana](Banana.md) | [**Banana**](Banana.md) | [**Banana**](Banana.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/FruitReq.md b/samples/openapi3/client/petstore/python/docs/models/FruitReq.md new file mode 100644 index 0000000000..c4c18e3e4c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/FruitReq.md @@ -0,0 +1,24 @@ +# petstore_api.model.fruit_req.FruitReq + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | None, | NoneClass, | | +[AppleReq](AppleReq.md) | [**AppleReq**](AppleReq.md) | [**AppleReq**](AppleReq.md) | | +[BananaReq](BananaReq.md) | [**BananaReq**](BananaReq.md) | [**BananaReq**](BananaReq.md) | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/GmFruit.md b/samples/openapi3/client/petstore/python/docs/models/GmFruit.md new file mode 100644 index 0000000000..6515df977c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/GmFruit.md @@ -0,0 +1,22 @@ +# petstore_api.model.gm_fruit.GmFruit + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**color** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### anyOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[Apple](Apple.md) | [**Apple**](Apple.md) | [**Apple**](Apple.md) | | +[Banana](Banana.md) | [**Banana**](Banana.md) | [**Banana**](Banana.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/GrandparentAnimal.md b/samples/openapi3/client/petstore/python/docs/models/GrandparentAnimal.md new file mode 100644 index 0000000000..813fe61b95 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/GrandparentAnimal.md @@ -0,0 +1,15 @@ +# petstore_api.model.grandparent_animal.GrandparentAnimal + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**pet_type** | str, | str, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python/docs/models/HasOnlyReadOnly.md new file mode 100644 index 0000000000..d9de17196f --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/HasOnlyReadOnly.md @@ -0,0 +1,16 @@ +# petstore_api.model.has_only_read_only.HasOnlyReadOnly + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**bar** | str, | str, | | [optional] +**foo** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/HealthCheckResult.md b/samples/openapi3/client/petstore/python/docs/models/HealthCheckResult.md new file mode 100644 index 0000000000..0985cffd05 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/HealthCheckResult.md @@ -0,0 +1,17 @@ +# petstore_api.model.health_check_result.HealthCheckResult + +Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**NullableMessage** | None, str, | NoneClass, str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/IntegerEnum.md b/samples/openapi3/client/petstore/python/docs/models/IntegerEnum.md new file mode 100644 index 0000000000..59dd6239f7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/IntegerEnum.md @@ -0,0 +1,9 @@ +# petstore_api.model.integer_enum.IntegerEnum + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | must be one of [0, 1, 2, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/IntegerEnumBig.md b/samples/openapi3/client/petstore/python/docs/models/IntegerEnumBig.md new file mode 100644 index 0000000000..d4891543c0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/IntegerEnumBig.md @@ -0,0 +1,9 @@ +# petstore_api.model.integer_enum_big.IntegerEnumBig + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | must be one of [10, 11, 12, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/IntegerEnumOneValue.md b/samples/openapi3/client/petstore/python/docs/models/IntegerEnumOneValue.md new file mode 100644 index 0000000000..c2dd787bc5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/IntegerEnumOneValue.md @@ -0,0 +1,9 @@ +# petstore_api.model.integer_enum_one_value.IntegerEnumOneValue + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | must be one of [0, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/IntegerEnumWithDefaultValue.md b/samples/openapi3/client/petstore/python/docs/models/IntegerEnumWithDefaultValue.md new file mode 100644 index 0000000000..4eef737f88 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/IntegerEnumWithDefaultValue.md @@ -0,0 +1,9 @@ +# petstore_api.model.integer_enum_with_default_value.IntegerEnumWithDefaultValue + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | must be one of [0, 1, 2, ] if omitted the server will use the default value of 0 + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/IntegerMax10.md b/samples/openapi3/client/petstore/python/docs/models/IntegerMax10.md new file mode 100644 index 0000000000..93f3c28252 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/IntegerMax10.md @@ -0,0 +1,9 @@ +# petstore_api.model.integer_max10.IntegerMax10 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/IntegerMin15.md b/samples/openapi3/client/petstore/python/docs/models/IntegerMin15.md new file mode 100644 index 0000000000..1a900cf7b4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/IntegerMin15.md @@ -0,0 +1,9 @@ +# petstore_api.model.integer_min15.IntegerMin15 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/IsoscelesTriangle.md b/samples/openapi3/client/petstore/python/docs/models/IsoscelesTriangle.md new file mode 100644 index 0000000000..3a05686f41 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/IsoscelesTriangle.md @@ -0,0 +1,29 @@ +# petstore_api.model.isosceles_triangle.IsoscelesTriangle + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[TriangleInterface](TriangleInterface.md) | [**TriangleInterface**](TriangleInterface.md) | [**TriangleInterface**](TriangleInterface.md) | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**triangleType** | str, | str, | | [optional] must be one of ["IsoscelesTriangle", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequest.md b/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequest.md new file mode 100644 index 0000000000..fbc1250292 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequest.md @@ -0,0 +1,29 @@ +# petstore_api.model.json_patch_request.JSONPatchRequest + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[JSONPatchRequestAddReplaceTest](JSONPatchRequestAddReplaceTest.md) | [**JSONPatchRequestAddReplaceTest**](JSONPatchRequestAddReplaceTest.md) | [**JSONPatchRequestAddReplaceTest**](JSONPatchRequestAddReplaceTest.md) | | +[JSONPatchRequestRemove](JSONPatchRequestRemove.md) | [**JSONPatchRequestRemove**](JSONPatchRequestRemove.md) | [**JSONPatchRequestRemove**](JSONPatchRequestRemove.md) | | +[JSONPatchRequestMoveCopy](JSONPatchRequestMoveCopy.md) | [**JSONPatchRequestMoveCopy**](JSONPatchRequestMoveCopy.md) | [**JSONPatchRequestMoveCopy**](JSONPatchRequestMoveCopy.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequestAddReplaceTest.md b/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequestAddReplaceTest.md new file mode 100644 index 0000000000..a95e8f9574 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequestAddReplaceTest.md @@ -0,0 +1,16 @@ +# petstore_api.model.json_patch_request_add_replace_test.JSONPatchRequestAddReplaceTest + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**op** | str, | str, | The operation to perform. | must be one of ["add", "replace", "test", ] +**path** | str, | str, | A JSON Pointer path. | +**value** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | The value to add, replace or test. | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequestMoveCopy.md b/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequestMoveCopy.md new file mode 100644 index 0000000000..56c8fac4b7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequestMoveCopy.md @@ -0,0 +1,16 @@ +# petstore_api.model.json_patch_request_move_copy.JSONPatchRequestMoveCopy + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**op** | str, | str, | The operation to perform. | must be one of ["move", "copy", ] +**path** | str, | str, | A JSON Pointer path. | +**from** | str, | str, | A JSON Pointer path. | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequestRemove.md b/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequestRemove.md new file mode 100644 index 0000000000..a57981c57c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/JSONPatchRequestRemove.md @@ -0,0 +1,15 @@ +# petstore_api.model.json_patch_request_remove.JSONPatchRequestRemove + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**op** | str, | str, | The operation to perform. | must be one of ["remove", ] +**path** | str, | str, | A JSON Pointer path. | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Mammal.md b/samples/openapi3/client/petstore/python/docs/models/Mammal.md new file mode 100644 index 0000000000..12ac20a820 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Mammal.md @@ -0,0 +1,17 @@ +# petstore_api.model.mammal.Mammal + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[Whale](Whale.md) | [**Whale**](Whale.md) | [**Whale**](Whale.md) | | +[Zebra](Zebra.md) | [**Zebra**](Zebra.md) | [**Zebra**](Zebra.md) | | +[Pig](Pig.md) | [**Pig**](Pig.md) | [**Pig**](Pig.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/MapTest.md b/samples/openapi3/client/petstore/python/docs/models/MapTest.md new file mode 100644 index 0000000000..68c8d88295 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/MapTest.md @@ -0,0 +1,66 @@ +# petstore_api.model.map_test.MapTest + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[map_map_of_string](#map_map_of_string)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**[map_of_enum_string](#map_of_enum_string)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**[direct_map](#direct_map)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**indirect_map** | [**StringBooleanMap**](StringBooleanMap.md) | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# map_map_of_string + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[any_string_name](#any_string_name)** | dict, frozendict.frozendict, | frozendict.frozendict, | any string name can be used but the value must be the correct type | [optional] + +# any_string_name + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | str, | str, | any string name can be used but the value must be the correct type | [optional] + +# map_of_enum_string + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | str, | str, | any string name can be used but the value must be the correct type | [optional] must be one of ["UPPER", "lower", ] + +# direct_map + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | bool, | BoolClass, | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 0000000000..f85a43f4c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,29 @@ +# petstore_api.model.mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**uuid** | str, uuid.UUID, | str, | | [optional] value must be a uuid +**dateTime** | str, datetime, | str, | | [optional] value must conform to RFC-3339 date-time +**[map](#map)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# map + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | [**Animal**](Animal.md) | [**Animal**](Animal.md) | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Model200Response.md b/samples/openapi3/client/petstore/python/docs/models/Model200Response.md new file mode 100644 index 0000000000..90e17dd402 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Model200Response.md @@ -0,0 +1,18 @@ +# petstore_api.model.model200_response.Model200Response + +model with an invalid class name for python, starts with a number + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | model with an invalid class name for python, starts with a number | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**name** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 32 bit integer +**class** | str, | str, | this is a reserved python keyword | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ModelReturn.md b/samples/openapi3/client/petstore/python/docs/models/ModelReturn.md new file mode 100644 index 0000000000..d896e1fbac --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ModelReturn.md @@ -0,0 +1,17 @@ +# petstore_api.model.model_return.ModelReturn + +Model for testing reserved words + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | Model for testing reserved words | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**return** | decimal.Decimal, int, | decimal.Decimal, | this is a reserved python keyword | [optional] value must be a 32 bit integer +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Money.md b/samples/openapi3/client/petstore/python/docs/models/Money.md new file mode 100644 index 0000000000..f6e182a846 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Money.md @@ -0,0 +1,16 @@ +# petstore_api.model.money.Money + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**amount** | str, | str, | | value must be numeric and storable in decimal.Decimal +**currency** | [**Currency**](Currency.md) | [**Currency**](Currency.md) | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Name.md b/samples/openapi3/client/petstore/python/docs/models/Name.md new file mode 100644 index 0000000000..9e53cbabab --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Name.md @@ -0,0 +1,19 @@ +# petstore_api.model.name.Name + +Model for testing model name same as property name + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | Model for testing model name same as property name | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**name** | decimal.Decimal, int, | decimal.Decimal, | | value must be a 32 bit integer +**snake_case** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 32 bit integer +**property** | str, | str, | this is a reserved python keyword | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/NoAdditionalProperties.md b/samples/openapi3/client/petstore/python/docs/models/NoAdditionalProperties.md new file mode 100644 index 0000000000..70e6c8c120 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/NoAdditionalProperties.md @@ -0,0 +1,15 @@ +# petstore_api.model.no_additional_properties.NoAdditionalProperties + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**id** | decimal.Decimal, int, | decimal.Decimal, | | value must be a 64 bit integer +**petId** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 64 bit integer + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/NullableClass.md b/samples/openapi3/client/petstore/python/docs/models/NullableClass.md new file mode 100644 index 0000000000..d9ad105914 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/NullableClass.md @@ -0,0 +1,147 @@ +# petstore_api.model.nullable_class.NullableClass + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**integer_prop** | None, decimal.Decimal, int, | NoneClass, decimal.Decimal, | | [optional] +**number_prop** | None, decimal.Decimal, int, float, | NoneClass, decimal.Decimal, | | [optional] +**boolean_prop** | None, bool, | NoneClass, BoolClass, | | [optional] +**string_prop** | None, str, | NoneClass, str, | | [optional] +**date_prop** | None, str, date, | NoneClass, str, | | [optional] value must conform to RFC-3339 full-date YYYY-MM-DD +**datetime_prop** | None, str, datetime, | NoneClass, str, | | [optional] value must conform to RFC-3339 date-time +**[array_nullable_prop](#array_nullable_prop)** | list, tuple, None, | tuple, NoneClass, | | [optional] +**[array_and_items_nullable_prop](#array_and_items_nullable_prop)** | list, tuple, None, | tuple, NoneClass, | | [optional] +**[array_items_nullable](#array_items_nullable)** | list, tuple, | tuple, | | [optional] +**[object_nullable_prop](#object_nullable_prop)** | dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | [optional] +**[object_and_items_nullable_prop](#object_and_items_nullable_prop)** | dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | [optional] +**[object_items_nullable](#object_items_nullable)** | dict, frozendict.frozendict, | frozendict.frozendict, | | [optional] +**[any_string_name](#any_string_name)** | dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | any string name can be used but the value must be the correct type | [optional] + +# array_nullable_prop + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, None, | tuple, NoneClass, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +# array_and_items_nullable_prop + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, None, | tuple, NoneClass, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +# array_items_nullable + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[items](#items) | dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +# items + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +# object_nullable_prop + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[any_string_name](#any_string_name)** | dict, frozendict.frozendict, | frozendict.frozendict, | any string name can be used but the value must be the correct type | [optional] + +# any_string_name + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +# object_and_items_nullable_prop + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[any_string_name](#any_string_name)** | dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | any string name can be used but the value must be the correct type | [optional] + +# any_string_name + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +# object_items_nullable + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[any_string_name](#any_string_name)** | dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | any string name can be used but the value must be the correct type | [optional] + +# any_string_name + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +# any_string_name + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/NullableShape.md b/samples/openapi3/client/petstore/python/docs/models/NullableShape.md new file mode 100644 index 0000000000..9871dfe1e1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/NullableShape.md @@ -0,0 +1,26 @@ +# petstore_api.model.nullable_shape.NullableShape + +The value may be a shape or the 'null' value. For a composed schema to validate a null payload, one of its chosen oneOf schemas must be type null or nullable (introduced in OAS schema >= 3.0) + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | The value may be a shape or the 'null' value. For a composed schema to validate a null payload, one of its chosen oneOf schemas must be type null or nullable (introduced in OAS schema >= 3.0) | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[Triangle](Triangle.md) | [**Triangle**](Triangle.md) | [**Triangle**](Triangle.md) | | +[Quadrilateral](Quadrilateral.md) | [**Quadrilateral**](Quadrilateral.md) | [**Quadrilateral**](Quadrilateral.md) | | +[one_of_2](#one_of_2) | None, | NoneClass, | | + +# one_of_2 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/NullableString.md b/samples/openapi3/client/petstore/python/docs/models/NullableString.md new file mode 100644 index 0000000000..60b4aba316 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/NullableString.md @@ -0,0 +1,9 @@ +# petstore_api.model.nullable_string.NullableString + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, str, | NoneClass, str, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Number.md b/samples/openapi3/client/petstore/python/docs/models/Number.md new file mode 100644 index 0000000000..b1172e284f --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Number.md @@ -0,0 +1,9 @@ +# petstore_api.model.number.Number + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/NumberOnly.md b/samples/openapi3/client/petstore/python/docs/models/NumberOnly.md new file mode 100644 index 0000000000..42996c4e4c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/NumberOnly.md @@ -0,0 +1,15 @@ +# petstore_api.model.number_only.NumberOnly + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**JustNumber** | decimal.Decimal, int, float, | decimal.Decimal, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/NumberWithValidations.md b/samples/openapi3/client/petstore/python/docs/models/NumberWithValidations.md new file mode 100644 index 0000000000..fac4f59efe --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/NumberWithValidations.md @@ -0,0 +1,9 @@ +# petstore_api.model.number_with_validations.NumberWithValidations + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +decimal.Decimal, int, float, | decimal.Decimal, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ObjectInterface.md b/samples/openapi3/client/petstore/python/docs/models/ObjectInterface.md new file mode 100644 index 0000000000..e818da00c6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ObjectInterface.md @@ -0,0 +1,9 @@ +# petstore_api.model.object_interface.ObjectInterface + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ObjectModelWithRefProps.md b/samples/openapi3/client/petstore/python/docs/models/ObjectModelWithRefProps.md new file mode 100644 index 0000000000..8bb001aa77 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ObjectModelWithRefProps.md @@ -0,0 +1,19 @@ +# petstore_api.model.object_model_with_ref_props.ObjectModelWithRefProps + +a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**myNumber** | [**NumberWithValidations**](NumberWithValidations.md) | [**NumberWithValidations**](NumberWithValidations.md) | | [optional] +**myString** | str, | str, | | [optional] +**myBoolean** | bool, | BoolClass, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ObjectWithDecimalProperties.md b/samples/openapi3/client/petstore/python/docs/models/ObjectWithDecimalProperties.md new file mode 100644 index 0000000000..82c1abadd6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ObjectWithDecimalProperties.md @@ -0,0 +1,17 @@ +# petstore_api.model.object_with_decimal_properties.ObjectWithDecimalProperties + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**length** | str, | str, | | [optional] value must be numeric and storable in decimal.Decimal +**width** | str, | str, | | [optional] value must be numeric and storable in decimal.Decimal +**cost** | [**Money**](Money.md) | [**Money**](Money.md) | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ObjectWithDifficultlyNamedProps.md b/samples/openapi3/client/petstore/python/docs/models/ObjectWithDifficultlyNamedProps.md new file mode 100644 index 0000000000..13ca7fa145 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ObjectWithDifficultlyNamedProps.md @@ -0,0 +1,19 @@ +# petstore_api.model.object_with_difficultly_named_props.ObjectWithDifficultlyNamedProps + +model with properties that have invalid names for python + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | model with properties that have invalid names for python | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**123-list** | str, | str, | | +**$special[property.name]** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 64 bit integer +**123Number** | decimal.Decimal, int, | decimal.Decimal, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ObjectWithInlineCompositionProperty.md b/samples/openapi3/client/petstore/python/docs/models/ObjectWithInlineCompositionProperty.md new file mode 100644 index 0000000000..ddf1df4217 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ObjectWithInlineCompositionProperty.md @@ -0,0 +1,35 @@ +# petstore_api.model.object_with_inline_composition_property.ObjectWithInlineCompositionProperty + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[someProp](#someProp)** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# someProp + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[all_of_0](#all_of_0) | str, | str, | | + +# all_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ObjectWithInvalidNamedRefedProperties.md b/samples/openapi3/client/petstore/python/docs/models/ObjectWithInvalidNamedRefedProperties.md new file mode 100644 index 0000000000..d3762cc45c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ObjectWithInvalidNamedRefedProperties.md @@ -0,0 +1,16 @@ +# petstore_api.model.object_with_invalid_named_refed_properties.ObjectWithInvalidNamedRefedProperties + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**!reference** | [**ArrayWithValidationsInItems**](ArrayWithValidationsInItems.md) | [**ArrayWithValidationsInItems**](ArrayWithValidationsInItems.md) | | +**from** | [**FromSchema**](FromSchema.md) | [**FromSchema**](FromSchema.md) | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ObjectWithValidations.md b/samples/openapi3/client/petstore/python/docs/models/ObjectWithValidations.md new file mode 100644 index 0000000000..be9d36e49b --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ObjectWithValidations.md @@ -0,0 +1,9 @@ +# petstore_api.model.object_with_validations.ObjectWithValidations + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Order.md b/samples/openapi3/client/petstore/python/docs/models/Order.md new file mode 100644 index 0000000000..0007dc9178 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Order.md @@ -0,0 +1,20 @@ +# petstore_api.model.order.Order + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**id** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 64 bit integer +**petId** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 64 bit integer +**quantity** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 32 bit integer +**shipDate** | str, datetime, | str, | | [optional] value must conform to RFC-3339 date-time +**status** | str, | str, | Order Status | [optional] must be one of ["placed", "approved", "delivered", ] +**complete** | bool, | BoolClass, | | [optional] if omitted the server will use the default value of False +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ParentPet.md b/samples/openapi3/client/petstore/python/docs/models/ParentPet.md new file mode 100644 index 0000000000..1baad19537 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ParentPet.md @@ -0,0 +1,15 @@ +# petstore_api.model.parent_pet.ParentPet + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[GrandparentAnimal](GrandparentAnimal.md) | [**GrandparentAnimal**](GrandparentAnimal.md) | [**GrandparentAnimal**](GrandparentAnimal.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Pet.md b/samples/openapi3/client/petstore/python/docs/models/Pet.md new file mode 100644 index 0000000000..eacf6aa431 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Pet.md @@ -0,0 +1,46 @@ +# petstore_api.model.pet.Pet + +Pet object that needs to be added to the store + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | Pet object that needs to be added to the store | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**[photoUrls](#photoUrls)** | list, tuple, | tuple, | | +**name** | str, | str, | | +**id** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 64 bit integer +**category** | [**Category**](Category.md) | [**Category**](Category.md) | | [optional] +**[tags](#tags)** | list, tuple, | tuple, | | [optional] +**status** | str, | str, | pet status in the store | [optional] must be one of ["available", "pending", "sold", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# photoUrls + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +items | str, | str, | | + +# tags + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +list, tuple, | tuple, | | + +### Tuple Items +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[**Tag**](Tag.md) | [**Tag**](Tag.md) | [**Tag**](Tag.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Pig.md b/samples/openapi3/client/petstore/python/docs/models/Pig.md new file mode 100644 index 0000000000..33a8aca85e --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Pig.md @@ -0,0 +1,16 @@ +# petstore_api.model.pig.Pig + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[BasquePig](BasquePig.md) | [**BasquePig**](BasquePig.md) | [**BasquePig**](BasquePig.md) | | +[DanishPig](DanishPig.md) | [**DanishPig**](DanishPig.md) | [**DanishPig**](DanishPig.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Player.md b/samples/openapi3/client/petstore/python/docs/models/Player.md new file mode 100644 index 0000000000..98ec6b5d15 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Player.md @@ -0,0 +1,18 @@ +# petstore_api.model.player.Player + +a model that includes a self reference this forces properties and additionalProperties to be lazy loaded in python models because the Player class has not fully loaded when defining properties + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | a model that includes a self reference this forces properties and additionalProperties to be lazy loaded in python models because the Player class has not fully loaded when defining properties | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**name** | str, | str, | | [optional] +**enemyPlayer** | [**Player**](Player.md) | [**Player**](Player.md) | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Quadrilateral.md b/samples/openapi3/client/petstore/python/docs/models/Quadrilateral.md new file mode 100644 index 0000000000..55f1862724 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Quadrilateral.md @@ -0,0 +1,16 @@ +# petstore_api.model.quadrilateral.Quadrilateral + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[SimpleQuadrilateral](SimpleQuadrilateral.md) | [**SimpleQuadrilateral**](SimpleQuadrilateral.md) | [**SimpleQuadrilateral**](SimpleQuadrilateral.md) | | +[ComplexQuadrilateral](ComplexQuadrilateral.md) | [**ComplexQuadrilateral**](ComplexQuadrilateral.md) | [**ComplexQuadrilateral**](ComplexQuadrilateral.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/QuadrilateralInterface.md b/samples/openapi3/client/petstore/python/docs/models/QuadrilateralInterface.md new file mode 100644 index 0000000000..8344d0ffba --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/QuadrilateralInterface.md @@ -0,0 +1,16 @@ +# petstore_api.model.quadrilateral_interface.QuadrilateralInterface + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**shapeType** | str, | str, | | must be one of ["Quadrilateral", ] +**quadrilateralType** | str, | str, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python/docs/models/ReadOnlyFirst.md new file mode 100644 index 0000000000..a8f4053a41 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ReadOnlyFirst.md @@ -0,0 +1,16 @@ +# petstore_api.model.read_only_first.ReadOnlyFirst + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**bar** | str, | str, | | [optional] +**baz** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ScaleneTriangle.md b/samples/openapi3/client/petstore/python/docs/models/ScaleneTriangle.md new file mode 100644 index 0000000000..dde662e47e --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ScaleneTriangle.md @@ -0,0 +1,29 @@ +# petstore_api.model.scalene_triangle.ScaleneTriangle + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[TriangleInterface](TriangleInterface.md) | [**TriangleInterface**](TriangleInterface.md) | [**TriangleInterface**](TriangleInterface.md) | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**triangleType** | str, | str, | | [optional] must be one of ["ScaleneTriangle", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Shape.md b/samples/openapi3/client/petstore/python/docs/models/Shape.md new file mode 100644 index 0000000000..f8bec209ec --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Shape.md @@ -0,0 +1,16 @@ +# petstore_api.model.shape.Shape + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[Triangle](Triangle.md) | [**Triangle**](Triangle.md) | [**Triangle**](Triangle.md) | | +[Quadrilateral](Quadrilateral.md) | [**Quadrilateral**](Quadrilateral.md) | [**Quadrilateral**](Quadrilateral.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/ShapeOrNull.md b/samples/openapi3/client/petstore/python/docs/models/ShapeOrNull.md new file mode 100644 index 0000000000..908b69e058 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/ShapeOrNull.md @@ -0,0 +1,26 @@ +# petstore_api.model.shape_or_null.ShapeOrNull + +The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[one_of_0](#one_of_0) | None, | NoneClass, | | +[Triangle](Triangle.md) | [**Triangle**](Triangle.md) | [**Triangle**](Triangle.md) | | +[Quadrilateral](Quadrilateral.md) | [**Quadrilateral**](Quadrilateral.md) | [**Quadrilateral**](Quadrilateral.md) | | + +# one_of_0 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/SimpleQuadrilateral.md b/samples/openapi3/client/petstore/python/docs/models/SimpleQuadrilateral.md new file mode 100644 index 0000000000..288684f5dc --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/SimpleQuadrilateral.md @@ -0,0 +1,29 @@ +# petstore_api.model.simple_quadrilateral.SimpleQuadrilateral + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[QuadrilateralInterface](QuadrilateralInterface.md) | [**QuadrilateralInterface**](QuadrilateralInterface.md) | [**QuadrilateralInterface**](QuadrilateralInterface.md) | | +[all_of_1](#all_of_1) | dict, frozendict.frozendict, | frozendict.frozendict, | | + +# all_of_1 + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**quadrilateralType** | str, | str, | | [optional] must be one of ["SimpleQuadrilateral", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/SomeObject.md b/samples/openapi3/client/petstore/python/docs/models/SomeObject.md new file mode 100644 index 0000000000..7599329a36 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/SomeObject.md @@ -0,0 +1,15 @@ +# petstore_api.model.some_object.SomeObject + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### allOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[ObjectInterface](ObjectInterface.md) | [**ObjectInterface**](ObjectInterface.md) | [**ObjectInterface**](ObjectInterface.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/SpecialModelName.md b/samples/openapi3/client/petstore/python/docs/models/SpecialModelName.md new file mode 100644 index 0000000000..f40d98660a --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/SpecialModelName.md @@ -0,0 +1,17 @@ +# petstore_api.model.special_model_name.SpecialModelName + +model with an invalid class name for python + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | model with an invalid class name for python | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**a** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/String.md b/samples/openapi3/client/petstore/python/docs/models/String.md new file mode 100644 index 0000000000..75fc685c2c --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/String.md @@ -0,0 +1,9 @@ +# petstore_api.model.string.String + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/StringBooleanMap.md b/samples/openapi3/client/petstore/python/docs/models/StringBooleanMap.md new file mode 100644 index 0000000000..48f1fe881e --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/StringBooleanMap.md @@ -0,0 +1,14 @@ +# petstore_api.model.string_boolean_map.StringBooleanMap + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**any_string_name** | bool, | BoolClass, | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/StringEnum.md b/samples/openapi3/client/petstore/python/docs/models/StringEnum.md new file mode 100644 index 0000000000..06c26a7a1a --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/StringEnum.md @@ -0,0 +1,9 @@ +# petstore_api.model.string_enum.StringEnum + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, str, | NoneClass, str, | | must be one of ["placed", "approved", "delivered", "single quoted", "multiple\nlines", "double quote \n with newline", None, ] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/StringEnumWithDefaultValue.md b/samples/openapi3/client/petstore/python/docs/models/StringEnumWithDefaultValue.md new file mode 100644 index 0000000000..028f1b3733 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/StringEnumWithDefaultValue.md @@ -0,0 +1,9 @@ +# petstore_api.model.string_enum_with_default_value.StringEnumWithDefaultValue + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | must be one of ["placed", "approved", "delivered", ] if omitted the server will use the default value of "placed" + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/StringWithValidation.md b/samples/openapi3/client/petstore/python/docs/models/StringWithValidation.md new file mode 100644 index 0000000000..3effe032b8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/StringWithValidation.md @@ -0,0 +1,9 @@ +# petstore_api.model.string_with_validation.StringWithValidation + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, | str, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Tag.md b/samples/openapi3/client/petstore/python/docs/models/Tag.md new file mode 100644 index 0000000000..7e61a1fffa --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Tag.md @@ -0,0 +1,16 @@ +# petstore_api.model.tag.Tag + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**id** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 64 bit integer +**name** | str, | str, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Triangle.md b/samples/openapi3/client/petstore/python/docs/models/Triangle.md new file mode 100644 index 0000000000..c89258b99f --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Triangle.md @@ -0,0 +1,17 @@ +# petstore_api.model.triangle.Triangle + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### oneOf +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[EquilateralTriangle](EquilateralTriangle.md) | [**EquilateralTriangle**](EquilateralTriangle.md) | [**EquilateralTriangle**](EquilateralTriangle.md) | | +[IsoscelesTriangle](IsoscelesTriangle.md) | [**IsoscelesTriangle**](IsoscelesTriangle.md) | [**IsoscelesTriangle**](IsoscelesTriangle.md) | | +[ScaleneTriangle](ScaleneTriangle.md) | [**ScaleneTriangle**](ScaleneTriangle.md) | [**ScaleneTriangle**](ScaleneTriangle.md) | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/TriangleInterface.md b/samples/openapi3/client/petstore/python/docs/models/TriangleInterface.md new file mode 100644 index 0000000000..259594c788 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/TriangleInterface.md @@ -0,0 +1,16 @@ +# petstore_api.model.triangle_interface.TriangleInterface + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**shapeType** | str, | str, | | must be one of ["Triangle", ] +**triangleType** | str, | str, | | +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/UUIDString.md b/samples/openapi3/client/petstore/python/docs/models/UUIDString.md new file mode 100644 index 0000000000..020676d584 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/UUIDString.md @@ -0,0 +1,9 @@ +# petstore_api.model.uuid_string.UUIDString + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +str, uuid.UUID, | str, | | value must be a uuid + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/User.md b/samples/openapi3/client/petstore/python/docs/models/User.md new file mode 100644 index 0000000000..11da137c64 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/User.md @@ -0,0 +1,67 @@ +# petstore_api.model.user.User + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**id** | decimal.Decimal, int, | decimal.Decimal, | | [optional] value must be a 64 bit integer +**username** | str, | str, | | [optional] +**firstName** | str, | str, | | [optional] +**lastName** | str, | str, | | [optional] +**email** | str, | str, | | [optional] +**password** | str, | str, | | [optional] +**phone** | str, | str, | | [optional] +**userStatus** | decimal.Decimal, int, | decimal.Decimal, | User Status | [optional] value must be a 32 bit integer +**[objectWithNoDeclaredProps](#objectWithNoDeclaredProps)** | dict, frozendict.frozendict, | frozendict.frozendict, | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] +**[objectWithNoDeclaredPropsNullable](#objectWithNoDeclaredPropsNullable)** | dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] +**anyTypeProp** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] +**[anyTypeExceptNullProp](#anyTypeExceptNullProp)** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | any type except 'null' Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. | [optional] +**anyTypePropNullable** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +# objectWithNoDeclaredProps + +test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | + +# objectWithNoDeclaredPropsNullable + +test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, None, | frozendict.frozendict, NoneClass, | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | + +# anyTypeExceptNullProp + +any type except 'null' Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | any type except 'null' Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. | + +### Composed Schemas (allOf/anyOf/oneOf/not) +#### not +Class Name | Input Type | Accessed Type | Description | Notes +------------- | ------------- | ------------- | ------------- | ------------- +[not_schema](#not_schema) | None, | NoneClass, | | + +# not_schema + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +None, | NoneClass, | | + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Whale.md b/samples/openapi3/client/petstore/python/docs/models/Whale.md new file mode 100644 index 0000000000..bd92a1048d --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Whale.md @@ -0,0 +1,17 @@ +# petstore_api.model.whale.Whale + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**className** | str, | str, | | must be one of ["whale", ] +**hasBaleen** | bool, | BoolClass, | | [optional] +**hasTeeth** | bool, | BoolClass, | | [optional] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, int, float, bool, decimal.Decimal, None, list, tuple, bytes, io.FileIO, io.BufferedReader | frozendict.frozendict, str, BoolClass, decimal.Decimal, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/models/Zebra.md b/samples/openapi3/client/petstore/python/docs/models/Zebra.md new file mode 100644 index 0000000000..c710364ef8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/models/Zebra.md @@ -0,0 +1,16 @@ +# petstore_api.model.zebra.Zebra + +## Model Type Info +Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- +dict, frozendict.frozendict, | frozendict.frozendict, | | + +### Dictionary Keys +Key | Input Type | Accessed Type | Description | Notes +------------ | ------------- | ------------- | ------------- | ------------- +**className** | str, | str, | | must be one of ["zebra", ] +**type** | str, | str, | | [optional] must be one of ["plains", "mountain", "grevys", ] +**any_string_name** | dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, | frozendict.frozendict, str, decimal.Decimal, BoolClass, NoneClass, tuple, bytes, FileIO | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/openapi3/client/petstore/python/git_push.sh b/samples/openapi3/client/petstore/python/git_push.sh index f53a75d4fa..ced3be2b0c 100644 --- a/samples/openapi3/client/petstore/python/git_push.sh +++ b/samples/openapi3/client/petstore/python/git_push.sh @@ -1,7 +1,7 @@ #!/bin/sh # ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ # -# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" git_user_id=$1 git_repo_id=$2 @@ -38,14 +38,14 @@ git add . git commit -m "$release_note" # Sets the new remote -git_remote=$(git remote) +git_remote=`git remote` if [ "$git_remote" = "" ]; then # git remote not defined if [ "$GIT_TOKEN" = "" ]; then echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git fi fi @@ -55,3 +55,4 @@ git pull origin master # Pushes (Forces) the changes in the local repository up to the remote repository echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/openapi3/client/petstore/python/petstore_api/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/__init__.py index e79f5c78b2..26b0467759 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/__init__.py @@ -1,3 +1,5 @@ +# coding: utf-8 + # flake8: noqa """ @@ -9,7 +11,6 @@ Generated by: https://openapi-generator.tech """ - __version__ = "1.0.0" # import ApiClient diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/api/__init__.py deleted file mode 100644 index 840e9f0cd9..0000000000 --- a/samples/openapi3/client/petstore/python/petstore_api/api/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# do not import all apis into this module because that uses a lot of memory and stack frames -# if you need the ability to import all apis from one package, import them with -# from petstore_api.apis import AnotherFakeApi diff --git a/samples/openapi3/client/petstore/python/petstore_api/api_client.py b/samples/openapi3/client/petstore/python/petstore_api/api_client.py index c14f1d0f1b..d1b93ab5a6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api_client.py @@ -1,3 +1,4 @@ +# coding: utf-8 """ OpenAPI Petstore @@ -7,39 +8,959 @@ Generated by: https://openapi-generator.tech """ - +from dataclasses import dataclass +from decimal import Decimal +import enum +import email import json -import atexit -import mimetypes -from multiprocessing.pool import ThreadPool -import io import os +import io +import atexit +from multiprocessing.pool import ThreadPool import re +import tempfile import typing -from urllib.parse import quote -from urllib3.fields import RequestField +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict +from urllib.parse import urlparse, quote +from urllib3.fields import RequestField as RequestFieldBase +import frozendict from petstore_api import rest from petstore_api.configuration import Configuration -from petstore_api.exceptions import ApiTypeError, ApiValueError, ApiException -from petstore_api.model_utils import ( - ModelNormal, - ModelSimple, - ModelComposed, - check_allowed_values, - check_validations, +from petstore_api.exceptions import ApiTypeError, ApiValueError +from petstore_api.schemas import ( + NoneClass, + BoolClass, + Schema, + FileIO, + BinarySchema, date, datetime, - deserialize_file, - file_type, - model_to_dict, none_type, - validate_and_convert_types + Unset, + unset, ) -class ApiClient(object): +class RequestField(RequestFieldBase): + def __eq__(self, other): + if not isinstance(other, RequestField): + return False + return self.__dict__ == other.__dict__ + + +class JSONEncoder(json.JSONEncoder): + compact_separators = (',', ':') + + def default(self, obj): + if isinstance(obj, str): + return str(obj) + elif isinstance(obj, float): + return float(obj) + elif isinstance(obj, int): + return int(obj) + elif isinstance(obj, Decimal): + if obj.as_tuple().exponent >= 0: + return int(obj) + return float(obj) + elif isinstance(obj, NoneClass): + return None + elif isinstance(obj, BoolClass): + return bool(obj) + elif isinstance(obj, (dict, frozendict.frozendict)): + return {key: self.default(val) for key, val in obj.items()} + elif isinstance(obj, (list, tuple)): + return [self.default(item) for item in obj] + raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__)) + + +class ParameterInType(enum.Enum): + QUERY = 'query' + HEADER = 'header' + PATH = 'path' + COOKIE = 'cookie' + + +class ParameterStyle(enum.Enum): + MATRIX = 'matrix' + LABEL = 'label' + FORM = 'form' + SIMPLE = 'simple' + SPACE_DELIMITED = 'spaceDelimited' + PIPE_DELIMITED = 'pipeDelimited' + DEEP_OBJECT = 'deepObject' + + +class PrefixSeparatorIterator: + # A class to store prefixes and separators for rfc6570 expansions + + def __init__(self, prefix: str, separator: str): + self.prefix = prefix + self.separator = separator + self.first = True + if separator in {'.', '|', '%20'}: + item_separator = separator + else: + item_separator = ',' + self.item_separator = item_separator + + def __iter__(self): + return self + + def __next__(self): + if self.first: + self.first = False + return self.prefix + return self.separator + + +class ParameterSerializerBase: + @classmethod + def _get_default_explode(cls, style: ParameterStyle) -> bool: + return False + + @staticmethod + def __ref6570_item_value(in_data: typing.Any, percent_encode: bool): + """ + Get representation if str/float/int/None/items in list/ values in dict + None is returned if an item is undefined, use cases are value= + - None + - [] + - {} + - [None, None None] + - {'a': None, 'b': None} + """ + if type(in_data) in {str, float, int}: + if percent_encode: + return quote(str(in_data)) + return str(in_data) + elif isinstance(in_data, none_type): + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return None + elif isinstance(in_data, list) and not in_data: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return None + elif isinstance(in_data, dict) and not in_data: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return None + raise ApiValueError('Unable to generate a ref6570 item representation of {}'.format(in_data)) + + @staticmethod + def _to_dict(name: str, value: str): + return {name: value} + + @classmethod + def __ref6570_str_float_int_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + item_value = cls.__ref6570_item_value(in_data, percent_encode) + if item_value is None or (item_value == '' and prefix_separator_iterator.separator == ';'): + return next(prefix_separator_iterator) + var_name_piece + value_pair_equals = '=' if named_parameter_expansion else '' + return next(prefix_separator_iterator) + var_name_piece + value_pair_equals + item_value + + @classmethod + def __ref6570_list_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + item_values = [cls.__ref6570_item_value(v, percent_encode) for v in in_data] + item_values = [v for v in item_values if v is not None] + if not item_values: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + value_pair_equals = '=' if named_parameter_expansion else '' + if not explode: + return ( + next(prefix_separator_iterator) + + var_name_piece + + value_pair_equals + + prefix_separator_iterator.item_separator.join(item_values) + ) + # exploded + return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( + [var_name_piece + value_pair_equals + val for val in item_values] + ) + + @classmethod + def __ref6570_dict_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator, + var_name_piece: str, + named_parameter_expansion: bool + ) -> str: + in_data_transformed = {key: cls.__ref6570_item_value(val, percent_encode) for key, val in in_data.items()} + in_data_transformed = {key: val for key, val in in_data_transformed.items() if val is not None} + if not in_data_transformed: + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + value_pair_equals = '=' if named_parameter_expansion else '' + if not explode: + return ( + next(prefix_separator_iterator) + + var_name_piece + value_pair_equals + + prefix_separator_iterator.item_separator.join( + prefix_separator_iterator.item_separator.join( + item_pair + ) for item_pair in in_data_transformed.items() + ) + ) + # exploded + return next(prefix_separator_iterator) + next(prefix_separator_iterator).join( + [key + '=' + val for key, val in in_data_transformed.items()] + ) + + @classmethod + def _ref6570_expansion( + cls, + variable_name: str, + in_data: typing.Any, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: PrefixSeparatorIterator + ) -> str: + """ + Separator is for separate variables like dict with explode true, not for array item separation + """ + named_parameter_expansion = prefix_separator_iterator.separator in {'&', ';'} + var_name_piece = variable_name if named_parameter_expansion else '' + if type(in_data) in {str, float, int}: + return cls.__ref6570_str_float_int_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) + elif isinstance(in_data, none_type): + # ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1 + return "" + elif isinstance(in_data, list): + return cls.__ref6570_list_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) + elif isinstance(in_data, dict): + return cls.__ref6570_dict_expansion( + variable_name, + in_data, + explode, + percent_encode, + prefix_separator_iterator, + var_name_piece, + named_parameter_expansion + ) + # bool, bytes, etc + raise ApiValueError('Unable to generate a ref6570 representation of {}'.format(in_data)) + + +class StyleFormSerializer(ParameterSerializerBase): + @classmethod + def _get_default_explode(cls, style: ParameterStyle) -> bool: + if style is ParameterStyle.FORM: + return True + return super()._get_default_explode(style) + + def _serialize_form( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + percent_encode: bool, + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None + ) -> str: + if prefix_separator_iterator is None: + prefix_separator_iterator = PrefixSeparatorIterator('?', '&') + return self._ref6570_expansion( + variable_name=name, + in_data=in_data, + explode=explode, + percent_encode=percent_encode, + prefix_separator_iterator=prefix_separator_iterator + ) + + +class StyleSimpleSerializer(ParameterSerializerBase): + + def _serialize_simple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + percent_encode: bool + ) -> str: + prefix_separator_iterator = PrefixSeparatorIterator('', ',') + return self._ref6570_expansion( + variable_name=name, + in_data=in_data, + explode=explode, + percent_encode=percent_encode, + prefix_separator_iterator=prefix_separator_iterator + ) + + +class JSONDetector: + """ + Works for: + application/json + application/json; charset=UTF-8 + application/json-patch+json + application/geo+json + """ + __json_content_type_pattern = re.compile("application/[^+]*[+]?(json);?.*") + + @classmethod + def _content_type_is_json(cls, content_type: str) -> bool: + if cls.__json_content_type_pattern.match(content_type): + return True + return False + + +@dataclass +class ParameterBase(JSONDetector): + name: str + in_type: ParameterInType + required: bool + style: typing.Optional[ParameterStyle] + explode: typing.Optional[bool] + allow_reserved: typing.Optional[bool] + schema: typing.Optional[typing.Type[Schema]] + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] + + __style_to_in_type = { + ParameterStyle.MATRIX: {ParameterInType.PATH}, + ParameterStyle.LABEL: {ParameterInType.PATH}, + ParameterStyle.FORM: {ParameterInType.QUERY, ParameterInType.COOKIE}, + ParameterStyle.SIMPLE: {ParameterInType.PATH, ParameterInType.HEADER}, + ParameterStyle.SPACE_DELIMITED: {ParameterInType.QUERY}, + ParameterStyle.PIPE_DELIMITED: {ParameterInType.QUERY}, + ParameterStyle.DEEP_OBJECT: {ParameterInType.QUERY}, + } + __in_type_to_default_style = { + ParameterInType.QUERY: ParameterStyle.FORM, + ParameterInType.PATH: ParameterStyle.SIMPLE, + ParameterInType.HEADER: ParameterStyle.SIMPLE, + ParameterInType.COOKIE: ParameterStyle.FORM, + } + __disallowed_header_names = {'Accept', 'Content-Type', 'Authorization'} + _json_encoder = JSONEncoder() + + @classmethod + def __verify_style_to_in_type(cls, style: typing.Optional[ParameterStyle], in_type: ParameterInType): + if style is None: + return + in_type_set = cls.__style_to_in_type[style] + if in_type not in in_type_set: + raise ValueError( + 'Invalid style and in_type combination. For style={} only in_type={} are allowed'.format( + style, in_type_set + ) + ) + + def __init__( + self, + name: str, + in_type: ParameterInType, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + if schema is None and content is None: + raise ValueError('Value missing; Pass in either schema or content') + if schema and content: + raise ValueError('Too many values provided. Both schema and content were provided. Only one may be input') + if name in self.__disallowed_header_names and in_type is ParameterInType.HEADER: + raise ValueError('Invalid name, name may not be one of {}'.format(self.__disallowed_header_names)) + self.__verify_style_to_in_type(style, in_type) + if content is None and style is None: + style = self.__in_type_to_default_style[in_type] + if content is not None and in_type in self.__in_type_to_default_style and len(content) != 1: + raise ValueError('Invalid content length, content length must equal 1') + self.in_type = in_type + self.name = name + self.required = required + self.style = style + self.explode = explode + self.allow_reserved = allow_reserved + self.schema = schema + self.content = content + + def _serialize_json( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + eliminate_whitespace: bool = False + ) -> str: + if eliminate_whitespace: + return json.dumps(in_data, separators=self._json_encoder.compact_separators) + return json.dumps(in_data) + + +class PathParameter(ParameterBase, StyleSimpleSerializer): + + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + super().__init__( + name, + in_type=ParameterInType.PATH, + required=required, + style=style, + explode=explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + def __serialize_label( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Dict[str, str]: + prefix_separator_iterator = PrefixSeparatorIterator('.', '.') + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_matrix( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Dict[str, str]: + prefix_separator_iterator = PrefixSeparatorIterator(';', ';') + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_simple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + ) -> typing.Dict[str, str]: + value = self._serialize_simple( + in_data=in_data, + name=self.name, + explode=self.explode, + percent_encode=True + ) + return self._to_dict(self.name, value) + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> typing.Dict[str, str]: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + simple -> path + path: + returns path_params: dict + label -> path + returns path_params + matrix -> path + returns path_params + """ + if self.style: + if self.style is ParameterStyle.SIMPLE: + return self.__serialize_simple(cast_in_data) + elif self.style is ParameterStyle.LABEL: + return self.__serialize_label(cast_in_data) + elif self.style is ParameterStyle.MATRIX: + return self.__serialize_matrix(cast_in_data) + # self.content will be length one + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data) + return self._to_dict(self.name, value) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class QueryParameter(ParameterBase, StyleFormSerializer): + + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: typing.Optional[bool] = None, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + used_style = ParameterStyle.FORM if style is None else style + used_explode = self._get_default_explode(used_style) if explode is None else explode + + super().__init__( + name, + in_type=ParameterInType.QUERY, + required=required, + style=used_style, + explode=used_explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + def __serialize_space_delimited( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] + ) -> typing.Dict[str, str]: + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_pipe_delimited( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] + ) -> typing.Dict[str, str]: + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + value = self._ref6570_expansion( + variable_name=self.name, + in_data=in_data, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def __serialize_form( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] + ) -> typing.Dict[str, str]: + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + value = self._serialize_form( + in_data, + name=self.name, + explode=self.explode, + percent_encode=True, + prefix_separator_iterator=prefix_separator_iterator + ) + return self._to_dict(self.name, value) + + def get_prefix_separator_iterator(self) -> typing.Optional[PrefixSeparatorIterator]: + if self.style is ParameterStyle.FORM: + return PrefixSeparatorIterator('?', '&') + elif self.style is ParameterStyle.SPACE_DELIMITED: + return PrefixSeparatorIterator('', '%20') + elif self.style is ParameterStyle.PIPE_DELIMITED: + return PrefixSeparatorIterator('', '|') + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict], + prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None + ) -> typing.Dict[str, str]: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + form -> query + query: + - GET/HEAD/DELETE: could use fields + - PUT/POST: must use urlencode to send parameters + returns fields: tuple + spaceDelimited -> query + returns fields + pipeDelimited -> query + returns fields + deepObject -> query, https://github.com/OAI/OpenAPI-Specification/issues/1706 + returns fields + """ + if self.style: + # TODO update query ones to omit setting values when [] {} or None is input + if self.style is ParameterStyle.FORM: + return self.__serialize_form(cast_in_data, prefix_separator_iterator) + elif self.style is ParameterStyle.SPACE_DELIMITED: + return self.__serialize_space_delimited(cast_in_data, prefix_separator_iterator) + elif self.style is ParameterStyle.PIPE_DELIMITED: + return self.__serialize_pipe_delimited(cast_in_data, prefix_separator_iterator) + # self.content will be length one + if prefix_separator_iterator is None: + prefix_separator_iterator = self.get_prefix_separator_iterator() + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data, eliminate_whitespace=True) + return self._to_dict( + self.name, + next(prefix_separator_iterator) + self.name + '=' + quote(value) + ) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class CookieParameter(ParameterBase, StyleFormSerializer): + + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: typing.Optional[bool] = None, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + used_style = ParameterStyle.FORM if style is None and content is None and schema else style + used_explode = self._get_default_explode(used_style) if explode is None else explode + + super().__init__( + name, + in_type=ParameterInType.COOKIE, + required=required, + style=used_style, + explode=used_explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> typing.Dict[str, str]: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + form -> cookie + returns fields: tuple + """ + if self.style: + """ + TODO add escaping of comma, space, equals + or turn encoding on + """ + value = self._serialize_form( + cast_in_data, + explode=self.explode, + name=self.name, + percent_encode=False, + prefix_separator_iterator=PrefixSeparatorIterator('', '&') + ) + return self._to_dict(self.name, value) + # self.content will be length one + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data) + return self._to_dict(self.name, value) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class HeaderParameter(ParameterBase, StyleSimpleSerializer): + def __init__( + self, + name: str, + required: bool = False, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: typing.Optional[bool] = None, + schema: typing.Optional[typing.Type[Schema]] = None, + content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None + ): + super().__init__( + name, + in_type=ParameterInType.HEADER, + required=required, + style=style, + explode=explode, + allow_reserved=allow_reserved, + schema=schema, + content=content + ) + + @staticmethod + def __to_headers(in_data: typing.Tuple[typing.Tuple[str, str], ...]) -> HTTPHeaderDict: + data = tuple(t for t in in_data if t) + headers = HTTPHeaderDict() + if not data: + return headers + headers.extend(data) + return headers + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict] + ) -> HTTPHeaderDict: + if self.schema: + cast_in_data = self.schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + """ + simple -> header + headers: PoolManager needs a mapping, tuple is close + returns headers: dict + """ + if self.style: + value = self._serialize_simple(cast_in_data, self.name, self.explode, False) + return self.__to_headers(((self.name, value),)) + # self.content will be length one + for content_type, schema in self.content.items(): + cast_in_data = schema(in_data) + cast_in_data = self._json_encoder.default(cast_in_data) + if self._content_type_is_json(content_type): + value = self._serialize_json(cast_in_data) + return self.__to_headers(((self.name, value),)) + raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type)) + + +class Encoding: + def __init__( + self, + content_type: str, + headers: typing.Optional[typing.Dict[str, HeaderParameter]] = None, + style: typing.Optional[ParameterStyle] = None, + explode: bool = False, + allow_reserved: bool = False, + ): + self.content_type = content_type + self.headers = headers + self.style = style + self.explode = explode + self.allow_reserved = allow_reserved + + +@dataclass +class MediaType: + """ + Used to store request and response body schema information + encoding: + A map between a property name and its encoding information. + The key, being the property name, MUST exist in the schema as a property. + The encoding object SHALL only apply to requestBody objects when the media type is + multipart or application/x-www-form-urlencoded. + """ + schema: typing.Optional[typing.Type[Schema]] = None + encoding: typing.Optional[typing.Dict[str, Encoding]] = None + + +@dataclass +class ApiResponse: + response: urllib3.HTTPResponse + body: typing.Union[Unset, Schema] + headers: typing.Union[Unset, typing.List[HeaderParameter]] + + def __init__( + self, + response: urllib3.HTTPResponse, + body: typing.Union[Unset, typing.Type[Schema]], + headers: typing.Union[Unset, typing.List[HeaderParameter]] + ): + """ + pycharm needs this to prevent 'Unexpected argument' warnings + """ + self.response = response + self.body = body + self.headers = headers + + +@dataclass +class ApiResponseWithoutDeserialization(ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[Unset, typing.Type[Schema]] = unset + headers: typing.Union[Unset, typing.List[HeaderParameter]] = unset + + +class OpenApiResponse(JSONDetector): + __filename_content_disposition_pattern = re.compile('filename="(.+?)"') + + def __init__( + self, + response_cls: typing.Type[ApiResponse] = ApiResponse, + content: typing.Optional[typing.Dict[str, MediaType]] = None, + headers: typing.Optional[typing.List[HeaderParameter]] = None, + ): + self.headers = headers + if content is not None and len(content) == 0: + raise ValueError('Invalid value for content, the content dict must have >= 1 entry') + self.content = content + self.response_cls = response_cls + + @staticmethod + def __deserialize_json(response: urllib3.HTTPResponse) -> typing.Any: + # python must be >= 3.9 so we can pass in bytes into json.loads + return json.loads(response.data) + + @staticmethod + def __file_name_from_response_url(response_url: typing.Optional[str]) -> typing.Optional[str]: + if response_url is None: + return None + url_path = urlparse(response_url).path + if url_path: + path_basename = os.path.basename(url_path) + if path_basename: + _filename, ext = os.path.splitext(path_basename) + if ext: + return path_basename + return None + + @classmethod + def __file_name_from_content_disposition(cls, content_disposition: typing.Optional[str]) -> typing.Optional[str]: + if content_disposition is None: + return None + match = cls.__filename_content_disposition_pattern.search(content_disposition) + if not match: + return None + return match.group(1) + + def __deserialize_application_octet_stream( + self, response: urllib3.HTTPResponse + ) -> typing.Union[bytes, io.BufferedReader]: + """ + urllib3 use cases: + 1. when preload_content=True (stream=False) then supports_chunked_reads is False and bytes are returned + 2. when preload_content=False (stream=True) then supports_chunked_reads is True and + a file will be written and returned + """ + if response.supports_chunked_reads(): + file_name = ( + self.__file_name_from_content_disposition(response.headers.get('content-disposition')) + or self.__file_name_from_response_url(response.geturl()) + ) + + if file_name is None: + _fd, path = tempfile.mkstemp() + else: + path = os.path.join(tempfile.gettempdir(), file_name) + + with open(path, 'wb') as new_file: + chunk_size = 1024 + while True: + data = response.read(chunk_size) + if not data: + break + new_file.write(data) + # release_conn is needed for streaming connections only + response.release_conn() + new_file = open(path, 'rb') + return new_file + else: + return response.data + + @staticmethod + def __deserialize_multipart_form_data( + response: urllib3.HTTPResponse + ) -> typing.Dict[str, typing.Any]: + msg = email.message_from_bytes(response.data) + return { + part.get_param("name", header="Content-Disposition"): part.get_payload( + decode=True + ).decode(part.get_content_charset()) + if part.get_content_charset() + else part.get_payload() + for part in msg.get_payload() + } + + def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse: + content_type = response.getheader('content-type') + deserialized_body = unset + streamed = response.supports_chunked_reads() + + deserialized_headers = unset + if self.headers is not None: + # TODO add header deserialiation here + pass + + if self.content is not None: + if content_type not in self.content: + raise ApiValueError( + f"Invalid content_type returned. Content_type='{content_type}' was returned " + f"when only {str(set(self.content))} are defined for status_code={str(response.status)}" + ) + body_schema = self.content[content_type].schema + if body_schema is None: + # some specs do not define response content media type schemas + return self.response_cls( + response=response, + headers=deserialized_headers, + body=unset + ) + + if self._content_type_is_json(content_type): + body_data = self.__deserialize_json(response) + elif content_type == 'application/octet-stream': + body_data = self.__deserialize_application_octet_stream(response) + elif content_type.startswith('multipart/form-data'): + body_data = self.__deserialize_multipart_form_data(response) + content_type = 'multipart/form-data' + else: + raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type)) + deserialized_body = body_schema.from_openapi_data_oapg( + body_data, _configuration=configuration) + elif streamed: + response.release_conn() + + return self.response_cls( + response=response, + headers=deserialized_headers, + body=deserialized_body + ) + + +class ApiClient: """Generic API client for OpenAPI client library builds. OpenAPI generic API client. This client handles the client- @@ -63,15 +984,21 @@ class ApiClient(object): _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1): + def __init__( + self, + configuration: typing.Optional[Configuration] = None, + header_name: typing.Optional[str] = None, + header_value: typing.Optional[str] = None, + cookie: typing.Optional[str] = None, + pool_threads: int = 1 + ): if configuration is None: - configuration = Configuration.get_default_copy() + configuration = Configuration() self.configuration = configuration self.pool_threads = pool_threads self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} + self.default_headers = HTTPHeaderDict() if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie @@ -118,298 +1045,86 @@ class ApiClient(object): self, resource_path: str, method: str, - path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - body: typing.Optional[typing.Any] = None, - post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, - response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + headers: typing.Optional[HTTPHeaderDict] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, auth_settings: typing.Optional[typing.List[str]] = None, - _return_http_data_only: typing.Optional[bool] = None, - collection_formats: typing.Optional[typing.Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, - _host: typing.Optional[str] = None, - _check_type: typing.Optional[bool] = None, - _content_type: typing.Optional[str] = None, - _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None - ): - - config = self.configuration + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + host: typing.Optional[str] = None, + ) -> urllib3.HTTPResponse: # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) + used_headers = HTTPHeaderDict(self.default_headers) if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - '{%s}' % k, - quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, - collection_formats) - - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) - post_params.extend(self.files_parameters(files)) - if header_params['Content-Type'].startswith("multipart"): - post_params = self.parameters_to_multipart(post_params, - (dict)) - - # body - if body: - body = self.sanitize_for_serialization(body) + headers['Cookie'] = self.cookie # auth setting - self.update_params_for_auth(header_params, query_params, - auth_settings, resource_path, method, body, - request_auths=_request_auths) + self.update_params_for_auth(used_headers, + auth_settings, resource_path, method, body) + + # must happen after cookie setting and auth setting in case user is overriding those + if headers: + used_headers.update(headers) # request url - if _host is None: + if host is None: url = self.configuration.host + resource_path else: # use server/host defined in path or operation instead - url = _host + resource_path + url = host + resource_path - try: - # perform request and return response - response_data = self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - except ApiException as e: - e.body = e.body.decode('utf-8') - raise e - - self.last_response = response_data - - return_data = response_data - - if not _preload_content: - return (return_data) - return return_data - - # deserialize response data - if response_type: - if response_type != (file_type,): - encoding = "utf-8" - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) - if match: - encoding = match.group(1) - response_data.data = response_data.data.decode(encoding) - - return_data = self.deserialize( - response_data, - response_type, - _check_type - ) - else: - return_data = None - - if _return_http_data_only: - return (return_data) - else: - return (return_data, response_data.status, - response_data.getheaders()) - - def parameters_to_multipart(self, params, collection_types): - """Get parameters as list of tuples, formatting as json if value is collection_types - - :param params: Parameters as list of two-tuples - :param dict collection_types: Parameter collection types - :return: Parameters as list of tuple or urllib3.fields.RequestField - """ - new_params = [] - if collection_types is None: - collection_types = (dict) - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance( - v, collection_types): # v is instance of collection_type, formatting as application/json - v = json.dumps(v, ensure_ascii=False).encode("utf-8") - field = RequestField(k, v) - field.make_multipart(content_type="application/json; charset=utf-8") - new_params.append(field) - else: - new_params.append((k, v)) - return new_params - - @classmethod - def sanitize_for_serialization(cls, obj): - """Prepares data for transmission before it is sent with the rest client - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is OpenAPI model, return the properties dict. - If obj is io.IOBase, return the bytes - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if isinstance(obj, (ModelNormal, ModelComposed)): - return { - key: cls.sanitize_for_serialization(val) for key, - val in model_to_dict( - obj, - serialize=True).items()} - elif isinstance(obj, io.IOBase): - return cls.get_file_data_and_close_file(obj) - elif isinstance(obj, (str, int, float, none_type, bool)): - return obj - elif isinstance(obj, (datetime, date)): - return obj.isoformat() - elif isinstance(obj, ModelSimple): - return cls.sanitize_for_serialization(obj.value) - elif isinstance(obj, (list, tuple)): - return [cls.sanitize_for_serialization(item) for item in obj] - if isinstance(obj, dict): - return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()} - raise ApiValueError( - 'Unable to prepare type {} for serialization'.format( - obj.__class__.__name__)) - - def deserialize(self, response, response_type, _check_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: For the response, a tuple containing: - valid classes - a list containing valid classes (for list schemas) - a dict containing a tuple of valid classes as the value - Example values: - (str,) - (Pet,) - (float, none_type) - ([int, none_type],) - ({str: (bool, str, int, float, date, datetime, str, none_type)},) - :param _check_type: boolean, whether to check the types of the data - received from the server - :type _check_type: bool - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == (file_type,): - content_disposition = response.getheader("Content-Disposition") - return deserialize_file(response.data, self.configuration, - content_disposition=content_disposition) - - # fetch data from response object - try: - received_data = json.loads(response.data) - except ValueError: - received_data = response.data - - # store our data under the key of 'received_data' so users have some - # context if they are deserializing a string and the data type is wrong - deserialized_data = validate_and_convert_types( - received_data, - response_type, - ['received_data'], - True, - _check_type, - configuration=self.configuration + # perform request and return response + response = self.request( + method, + url, + headers=used_headers, + fields=fields, + body=body, + stream=stream, + timeout=timeout, ) - return deserialized_data + return response def call_api( self, resource_path: str, method: str, - path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, - body: typing.Optional[typing.Any] = None, - post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, - files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, - response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + headers: typing.Optional[HTTPHeaderDict] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, auth_settings: typing.Optional[typing.List[str]] = None, async_req: typing.Optional[bool] = None, - _return_http_data_only: typing.Optional[bool] = None, - collection_formats: typing.Optional[typing.Dict[str, str]] = None, - _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, - _host: typing.Optional[str] = None, - _check_type: typing.Optional[bool] = None, - _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None - ): + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + host: typing.Optional[str] = None, + ) -> urllib3.HTTPResponse: """Makes the HTTP request (synchronous) and returns deserialized data. To make an async_req request, set the async_req parameter. :param resource_path: Path to method endpoint. :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be + :param headers: Header parameters to be placed in the request header. :param body: Request body. - :param post_params dict: Request post form parameters, + :param fields: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response_type: For the response, a tuple containing: - valid classes - a list containing valid classes (for list schemas) - a dict containing a tuple of valid classes as the value - Example values: - (str,) - (Pet,) - (float, none_type) - ([int, none_type],) - ({str: (bool, str, int, float, date, datetime, str, none_type)},) - :param files: key -> field name, value -> a list of open file - objects for `multipart/form-data`. - :type files: dict - :param async_req bool: execute request asynchronously - :type async_req: bool, optional - :param _return_http_data_only: response data without head status code - and headers - :type _return_http_data_only: bool, optional - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :type collection_formats: dict, optional - :param _preload_content: if False, the urllib3.HTTPResponse object will + :param auth_settings: Auth Settings names for the request. + :param async_req: execute request asynchronously + :type async_req: bool, optional TODO remove, unused + :param stream: if True, the urllib3.HTTPResponse object will be returned without reading/decoding response - data. Default is True. - :type _preload_content: bool, optional - :param _request_timeout: timeout setting for this request. If one + data. Also when True, if the openapi spec describes a file download, + the data will be written to a local filesystme file and the BinarySchema + instance will also inherit from FileSchema and FileIO + Default is False. + :type stream: bool, optional + :param timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. - :param _check_type: boolean describing if the data back from the server - should have its type checked. - :type _check_type: bool, optional - :param _request_auths: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auths: list, optional + :param host: api endpoint host :return: If async_req parameter is True, the request will be called asynchronously. @@ -417,82 +1132,90 @@ class ApiClient(object): If parameter async_req is False or missing, then the method will return the response directly. """ + if not async_req: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, - _return_http_data_only, collection_formats, - _preload_content, _request_timeout, _host, - _check_type, _request_auths=_request_auths) + return self.__call_api( + resource_path, + method, + headers, + body, + fields, + auth_settings, + stream, + timeout, + host, + ) - return self.pool.apply_async(self.__call_api, (resource_path, - method, path_params, - query_params, - header_params, body, - post_params, files, - response_type, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, _check_type, None, _request_auths)) + return self.pool.apply_async( + self.__call_api, + ( + resource_path, + method, + headers, + body, + json, + fields, + auth_settings, + stream, + timeout, + host, + ) + ) - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): + def request( + self, + method: str, + url: str, + headers: typing.Optional[HTTPHeaderDict] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> urllib3.HTTPResponse: """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.GET(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + stream=stream, + timeout=timeout, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + stream=stream, + timeout=timeout, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, - query_params=query_params, headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + fields=fields, + stream=stream, + timeout=timeout, body=body) elif method == "POST": return self.rest_client.POST(url, - query_params=query_params, headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + fields=fields, + stream=stream, + timeout=timeout, body=body) elif method == "PUT": return self.rest_client.PUT(url, - query_params=query_params, headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + fields=fields, + stream=stream, + timeout=timeout, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, - query_params=query_params, headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + fields=fields, + stream=stream, + timeout=timeout, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, - query_params=query_params, headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, + stream=stream, + timeout=timeout, body=body) else: raise ApiValueError( @@ -500,404 +1223,286 @@ class ApiClient(object): " `POST`, `PATCH`, `PUT` or `DELETE`." ) - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - @staticmethod - def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: - file_data = file_instance.read() - file_instance.close() - return file_data - - def files_parameters(self, - files: typing.Optional[typing.Dict[str, - typing.List[io.IOBase]]] = None): - """Builds form parameters. - - :param files: None or a dict with key=param_name and - value is a list of open file objects - :return: List of tuples of form parameters with file data - """ - if files is None: - return [] - - params = [] - for param_name, file_instances in files.items(): - if file_instances is None: - # if the file field is nullable, skip None values - continue - for file_instance in file_instances: - if file_instance is None: - # if the file field is nullable, skip None values - continue - if file_instance.closed is True: - raise ApiValueError( - "Cannot read a closed file. The passed in file_type " - "for %s must be open." % param_name - ) - filename = os.path.basename(file_instance.name) - filedata = self.get_file_data_and_close_file(file_instance) - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') - params.append( - tuple([param_name, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - accepts = [x.lower() for x in accepts] - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types, method=None, body=None): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :param method: http method (e.g. POST, PATCH). - :param body: http body to send. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return None - - content_types = [x.lower() for x in content_types] - - if (method == 'PATCH' and - 'application/json-patch+json' in content_types and - isinstance(body, list)): - return 'application/json-patch+json' - - if 'application/json' in content_types or '*/*' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, request_auths=None): + def update_params_for_auth(self, headers, auth_settings, + resource_path, method, body): """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. :param resource_path: A string representation of the HTTP request resource path. :param method: A string representation of the HTTP request method. :param body: A object representing the body of the HTTP request. The object type is the return value of _encoder.default(). - :param request_auths: if set, the provided settings will - override the token in the configuration. """ if not auth_settings: return - if request_auths: - for auth_setting in request_auths: - self._apply_auth_params( - headers, queries, resource_path, method, body, auth_setting) - return - for auth in auth_settings: auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params( - headers, queries, resource_path, method, body, auth_setting) - - def _apply_auth_params(self, headers, queries, resource_path, method, body, auth_setting): - if auth_setting['in'] == 'cookie': - headers['Cookie'] = auth_setting['key'] + "=" + auth_setting['value'] - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers[auth_setting['key']] = auth_setting['value'] - else: - # The HTTP signature scheme requires multiple HTTP headers - # that are calculated dynamically. - signing_info = self.configuration.signing_info - auth_headers = signing_info.get_http_signature_headers( - resource_path, method, headers, body, queries) - headers.update(auth_headers) - elif auth_setting['in'] == 'query': - queries.append((auth_setting['key'], auth_setting['value'])) - else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) - - -class Endpoint(object): - def __init__(self, settings=None, params_map=None, root_map=None, - headers_map=None, api_client=None, callable=None): - """Creates an endpoint - - Args: - settings (dict): see below key value pairs - 'response_type' (tuple/None): response type - 'auth' (list): a list of auth type keys - 'endpoint_path' (str): the endpoint path - 'operation_id' (str): endpoint string identifier - 'http_method' (str): POST/PUT/PATCH/GET etc - 'servers' (list): list of str servers that this endpoint is at - params_map (dict): see below key value pairs - 'all' (list): list of str endpoint parameter names - 'required' (list): list of required parameter names - 'nullable' (list): list of nullable parameter names - 'enum' (list): list of parameters with enum values - 'validation' (list): list of parameters with validations - root_map - 'validations' (dict): the dict mapping endpoint parameter tuple - paths to their validation dictionaries - 'allowed_values' (dict): the dict mapping endpoint parameter - tuple paths to their allowed_values (enum) dictionaries - 'openapi_types' (dict): param_name to openapi type - 'attribute_map' (dict): param_name to camelCase name - 'location_map' (dict): param_name to 'body', 'file', 'form', - 'header', 'path', 'query' - collection_format_map (dict): param_name to `csv` etc. - headers_map (dict): see below key value pairs - 'accept' (list): list of Accept header strings - 'content_type' (list): list of Content-Type header strings - api_client (ApiClient) api client instance - callable (function): the function which is invoked when the - Endpoint is called - """ - self.settings = settings - self.params_map = params_map - self.params_map['all'].extend([ - 'async_req', - '_host_index', - '_preload_content', - '_request_timeout', - '_return_http_data_only', - '_check_input_type', - '_check_return_type', - '_content_type', - '_spec_property_naming', - '_request_auths' - ]) - self.params_map['nullable'].extend(['_request_timeout']) - self.validations = root_map['validations'] - self.allowed_values = root_map['allowed_values'] - self.openapi_types = root_map['openapi_types'] - extra_types = { - 'async_req': (bool,), - '_host_index': (none_type, int), - '_preload_content': (bool,), - '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), - '_return_http_data_only': (bool,), - '_check_input_type': (bool,), - '_check_return_type': (bool,), - '_spec_property_naming': (bool,), - '_content_type': (none_type, str), - '_request_auths': (none_type, list) - } - self.openapi_types.update(extra_types) - self.attribute_map = root_map['attribute_map'] - self.location_map = root_map['location_map'] - self.collection_format_map = root_map['collection_format_map'] - self.headers_map = headers_map - self.api_client = api_client - self.callable = callable - - def __validate_inputs(self, kwargs): - for param in self.params_map['enum']: - if param in kwargs: - check_allowed_values( - self.allowed_values, - (param,), - kwargs[param] - ) - - for param in self.params_map['validation']: - if param in kwargs: - check_validations( - self.validations, - (param,), - kwargs[param], - configuration=self.api_client.configuration - ) - - if kwargs['_check_input_type'] is False: - return - - for key, value in kwargs.items(): - fixed_val = validate_and_convert_types( - value, - self.openapi_types[key], - [key], - kwargs['_spec_property_naming'], - kwargs['_check_input_type'], - configuration=self.api_client.configuration - ) - kwargs[key] = fixed_val - - def __gather_params(self, kwargs): - params = { - 'body': None, - 'collection_format': {}, - 'file': {}, - 'form': [], - 'header': {}, - 'path': {}, - 'query': [] - } - - for param_name, param_value in kwargs.items(): - param_location = self.location_map.get(param_name) - if param_location is None: + if not auth_setting: continue - if param_location: - if param_location == 'body': - params['body'] = param_value - continue - base_name = self.attribute_map[param_name] - if (param_location == 'form' and - self.openapi_types[param_name] == (file_type,)): - params['file'][base_name] = [param_value] - elif (param_location == 'form' and - self.openapi_types[param_name] == ([file_type],)): - # param_value is already a list - params['file'][base_name] = param_value - elif param_location in {'form', 'query'}: - param_value_full = (base_name, param_value) - params[param_location].append(param_value_full) - if param_location not in {'form', 'query'}: - params[param_location][base_name] = param_value - collection_format = self.collection_format_map.get(param_name) - if collection_format: - params['collection_format'][base_name] = collection_format + if auth_setting['in'] == 'cookie': + headers.add('Cookie', auth_setting['value']) + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers.add(auth_setting['key'], auth_setting['value']) + else: + # The HTTP signature scheme requires multiple HTTP headers + # that are calculated dynamically. + signing_info = self.configuration.signing_info + querys = tuple() + auth_headers = signing_info.get_http_signature_headers( + resource_path, method, headers, body, querys) + for key, value in auth_headers.items(): + headers.add(key, value) + elif auth_setting['in'] == 'query': + """ TODO implement auth in query + need to pass in prefix_separator_iterator + and need to output resource_path with query params added + """ + raise ApiValueError("Auth in query not yet implemented") + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) - return params - def __call__(self, *args, **kwargs): - """ This method is invoked when endpoints are called - Example: +class Api: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech - api_instance = AnotherFakeApi() - api_instance.call_123_test_special_tags # this is an instance of the class Endpoint - api_instance.call_123_test_special_tags() # this invokes api_instance.call_123_test_special_tags.__call__() - which then invokes the callable functions stored in that endpoint at - api_instance.call_123_test_special_tags.callable or self.callable in this class + Do not edit the class manually. + """ + def __init__(self, api_client: typing.Optional[ApiClient] = None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + @staticmethod + def _verify_typed_dict_inputs_oapg(cls: typing.Type[typing_extensions.TypedDict], data: typing.Dict[str, typing.Any]): """ - return self.callable(self, *args, **kwargs) - - def call_with_http_info(self, **kwargs): - - try: - index = self.api_client.configuration.server_operation_index.get( - self.settings['operation_id'], self.api_client.configuration.server_index - ) if kwargs['_host_index'] is None else kwargs['_host_index'] - server_variables = self.api_client.configuration.server_operation_variables.get( - self.settings['operation_id'], self.api_client.configuration.server_variables + Ensures that: + - required keys are present + - additional properties are not input + - value stored under required keys do not have the value unset + Note: detailed value checking is done in schema classes + """ + missing_required_keys = [] + required_keys_with_unset_values = [] + for required_key in cls.__required_keys__: + if required_key not in data: + missing_required_keys.append(required_key) + continue + value = data[required_key] + if value is unset: + required_keys_with_unset_values.append(required_key) + if missing_required_keys: + raise ApiTypeError( + '{} missing {} required arguments: {}'.format( + cls.__name__, len(missing_required_keys), missing_required_keys + ) + ) + if required_keys_with_unset_values: + raise ApiValueError( + '{} contains invalid unset values for {} required keys: {}'.format( + cls.__name__, len(required_keys_with_unset_values), required_keys_with_unset_values + ) ) - _host = self.api_client.configuration.get_host_from_settings( - index, variables=server_variables, servers=self.settings['servers'] + + disallowed_additional_keys = [] + for key in data: + if key in cls.__required_keys__ or key in cls.__optional_keys__: + continue + disallowed_additional_keys.append(key) + if disallowed_additional_keys: + raise ApiTypeError( + '{} got {} unexpected keyword arguments: {}'.format( + cls.__name__, len(disallowed_additional_keys), disallowed_additional_keys + ) + ) + + def _get_host_oapg( + self, + operation_id: str, + servers: typing.Tuple[typing.Dict[str, str], ...] = tuple(), + host_index: typing.Optional[int] = None + ) -> typing.Optional[str]: + configuration = self.api_client.configuration + try: + if host_index is None: + index = configuration.server_operation_index.get( + operation_id, configuration.server_index + ) + else: + index = host_index + server_variables = configuration.server_operation_variables.get( + operation_id, configuration.server_variables + ) + host = configuration.get_host_from_settings( + index, variables=server_variables, servers=servers ) except IndexError: - if self.settings['servers']: + if servers: raise ApiValueError( "Invalid host index. Must be 0 <= index < %s" % - len(self.settings['servers']) + len(servers) ) - _host = None + host = None + return host - for key, value in kwargs.items(): - if key not in self.params_map['all']: - raise ApiTypeError( - "Got an unexpected parameter '%s'" - " to method `%s`" % - (key, self.settings['operation_id']) - ) - # only throw this nullable ApiValueError if _check_input_type - # is False, if _check_input_type==True we catch this case - # in self.__validate_inputs - if (key not in self.params_map['nullable'] and value is None - and kwargs['_check_input_type'] is False): - raise ApiValueError( - "Value may not be None for non-nullable parameter `%s`" - " when calling `%s`" % - (key, self.settings['operation_id']) - ) - for key in self.params_map['required']: - if key not in kwargs.keys(): - raise ApiValueError( - "Missing the required parameter `%s` when calling " - "`%s`" % (key, self.settings['operation_id']) - ) +class SerializedRequestBody(typing_extensions.TypedDict, total=False): + body: typing.Union[str, bytes] + fields: typing.Tuple[typing.Union[RequestField, typing.Tuple[str, str]], ...] - self.__validate_inputs(kwargs) - params = self.__gather_params(kwargs) +class RequestBody(StyleFormSerializer, JSONDetector): + """ + A request body parameter + content: content_type to MediaType Schema info + """ + __json_encoder = JSONEncoder() - accept_headers_list = self.headers_map['accept'] - if accept_headers_list: - params['header']['Accept'] = self.api_client.select_header_accept( - accept_headers_list) + def __init__( + self, + content: typing.Dict[str, MediaType], + required: bool = False, + ): + self.required = required + if len(content) == 0: + raise ValueError('Invalid value for content, the content dict must have >= 1 entry') + self.content = content - if kwargs.get('_content_type'): - params['header']['Content-Type'] = kwargs['_content_type'] + def __serialize_json( + self, + in_data: typing.Any + ) -> typing.Dict[str, bytes]: + in_data = self.__json_encoder.default(in_data) + json_str = json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode( + "utf-8" + ) + return dict(body=json_str) + + @staticmethod + def __serialize_text_plain(in_data: typing.Any) -> typing.Dict[str, str]: + if isinstance(in_data, frozendict.frozendict): + raise ValueError('Unable to serialize type frozendict.frozendict to text/plain') + elif isinstance(in_data, tuple): + raise ValueError('Unable to serialize type tuple to text/plain') + elif isinstance(in_data, NoneClass): + raise ValueError('Unable to serialize type NoneClass to text/plain') + elif isinstance(in_data, BoolClass): + raise ValueError('Unable to serialize type BoolClass to text/plain') + return dict(body=str(in_data)) + + def __multipart_json_item(self, key: str, value: Schema) -> RequestField: + json_value = self.__json_encoder.default(value) + return RequestField(name=key, data=json.dumps(json_value), headers={'Content-Type': 'application/json'}) + + def __multipart_form_item(self, key: str, value: Schema) -> RequestField: + if isinstance(value, str): + return RequestField(name=key, data=str(value), headers={'Content-Type': 'text/plain'}) + elif isinstance(value, bytes): + return RequestField(name=key, data=value, headers={'Content-Type': 'application/octet-stream'}) + elif isinstance(value, FileIO): + request_field = RequestField( + name=key, + data=value.read(), + filename=os.path.basename(value.name), + headers={'Content-Type': 'application/octet-stream'} + ) + value.close() + return request_field else: - content_type_headers_list = self.headers_map['content_type'] - if content_type_headers_list: - if params['body'] != "": - content_types_list = self.api_client.select_header_content_type( - content_type_headers_list, self.settings['http_method'], - params['body']) - if content_types_list: - params['header']['Content-Type'] = content_types_list + return self.__multipart_json_item(key=key, value=value) - return self.api_client.call_api( - self.settings['endpoint_path'], self.settings['http_method'], - params['path'], - params['query'], - params['header'], - body=params['body'], - post_params=params['form'], - files=params['file'], - response_type=self.settings['response_type'], - auth_settings=self.settings['auth'], - async_req=kwargs['async_req'], - _check_type=kwargs['_check_return_type'], - _return_http_data_only=kwargs['_return_http_data_only'], - _preload_content=kwargs['_preload_content'], - _request_timeout=kwargs['_request_timeout'], - _host=_host, - _request_auths=kwargs['_request_auths'], - collection_formats=params['collection_format']) + def __serialize_multipart_form_data( + self, in_data: Schema + ) -> typing.Dict[str, typing.Tuple[RequestField, ...]]: + if not isinstance(in_data, frozendict.frozendict): + raise ValueError(f'Unable to serialize {in_data} to multipart/form-data because it is not a dict of data') + """ + In a multipart/form-data request body, each schema property, or each element of a schema array property, + takes a section in the payload with an internal header as defined by RFC7578. The serialization strategy + for each property of a multipart/form-data request body can be specified in an associated Encoding Object. + + When passing in multipart types, boundaries MAY be used to separate sections of the content being + transferred – thus, the following default Content-Types are defined for multipart: + + If the (object) property is a primitive, or an array of primitive values, the default Content-Type is text/plain + If the property is complex, or an array of complex values, the default Content-Type is application/json + Question: how is the array of primitives encoded? + If the property is a type: string with a contentEncoding, the default Content-Type is application/octet-stream + """ + fields = [] + for key, value in in_data.items(): + if isinstance(value, tuple): + if value: + # values use explode = True, so the code makes a RequestField for each item with name=key + for item in value: + request_field = self.__multipart_form_item(key=key, value=item) + fields.append(request_field) + else: + # send an empty array as json because exploding will not send it + request_field = self.__multipart_json_item(key=key, value=value) + fields.append(request_field) + else: + request_field = self.__multipart_form_item(key=key, value=value) + fields.append(request_field) + + return dict(fields=tuple(fields)) + + def __serialize_application_octet_stream(self, in_data: BinarySchema) -> typing.Dict[str, bytes]: + if isinstance(in_data, bytes): + return dict(body=in_data) + # FileIO type + result = dict(body=in_data.read()) + in_data.close() + return result + + def __serialize_application_x_www_form_data( + self, in_data: typing.Any + ) -> SerializedRequestBody: + """ + POST submission of form data in body + """ + if not isinstance(in_data, frozendict.frozendict): + raise ValueError( + f'Unable to serialize {in_data} to application/x-www-form-urlencoded because it is not a dict of data') + cast_in_data = self.__json_encoder.default(in_data) + value = self._serialize_form(cast_in_data, name='', explode=True, percent_encode=False) + return dict(body=value) + + def serialize( + self, in_data: typing.Any, content_type: str + ) -> SerializedRequestBody: + """ + If a str is returned then the result will be assigned to data when making the request + If a tuple is returned then the result will be used as fields input in encode_multipart_formdata + Return a tuple of + + The key of the return dict is + - body for application/json + - encode_multipart and fields for multipart/form-data + """ + media_type = self.content[content_type] + if isinstance(in_data, media_type.schema): + cast_in_data = in_data + elif isinstance(in_data, (dict, frozendict.frozendict)) and in_data: + cast_in_data = media_type.schema(**in_data) + else: + cast_in_data = media_type.schema(in_data) + # TODO check for and use encoding if it exists + # and content_type is multipart or application/x-www-form-urlencoded + if self._content_type_is_json(content_type): + return self.__serialize_json(cast_in_data) + elif content_type == 'text/plain': + return self.__serialize_text_plain(cast_in_data) + elif content_type == 'multipart/form-data': + return self.__serialize_multipart_form_data(cast_in_data) + elif content_type == 'application/x-www-form-urlencoded': + return self.__serialize_application_x_www_form_data(cast_in_data) + elif content_type == 'application/octet-stream': + return self.__serialize_application_octet_stream(cast_in_data) + raise NotImplementedError('Serialization has not yet been implemented for {}'.format(content_type)) diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/apis/__init__.py index 381ad9572b..7840f7726f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/apis/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/__init__.py @@ -1,23 +1,3 @@ - -# flake8: noqa - -# Import all APIs into this package. -# If you have many APIs here with many many models used in each API this may -# raise a `RecursionError`. -# In order to avoid this, import only the API that you directly need like: -# -# from petstore_api.api.another_fake_api import AnotherFakeApi -# -# or import this package, but before doing it, use: -# -# import sys -# sys.setrecursionlimit(n) - -# Import APIs into API package: -from petstore_api.api.another_fake_api import AnotherFakeApi -from petstore_api.api.default_api import DefaultApi -from petstore_api.api.fake_api import FakeApi -from petstore_api.api.fake_classname_tags123_api import FakeClassnameTags123Api -from petstore_api.api.pet_api import PetApi -from petstore_api.api.store_api import StoreApi -from petstore_api.api.user_api import UserApi +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints then import them from +# tags, paths, or path_to_api, or tag_to_api \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/path_to_api.py b/samples/openapi3/client/petstore/python/petstore_api/apis/path_to_api.py new file mode 100644 index 0000000000..db788e6105 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/path_to_api.py @@ -0,0 +1,158 @@ +import typing_extensions + +from petstore_api.paths import PathValues +from petstore_api.apis.paths.foo import Foo +from petstore_api.apis.paths.pet import Pet +from petstore_api.apis.paths.pet_find_by_status import PetFindByStatus +from petstore_api.apis.paths.pet_find_by_tags import PetFindByTags +from petstore_api.apis.paths.pet_pet_id import PetPetId +from petstore_api.apis.paths.pet_pet_id_upload_image import PetPetIdUploadImage +from petstore_api.apis.paths.store_inventory import StoreInventory +from petstore_api.apis.paths.store_order import StoreOrder +from petstore_api.apis.paths.store_order_order_id import StoreOrderOrderId +from petstore_api.apis.paths.user import User +from petstore_api.apis.paths.user_create_with_array import UserCreateWithArray +from petstore_api.apis.paths.user_create_with_list import UserCreateWithList +from petstore_api.apis.paths.user_login import UserLogin +from petstore_api.apis.paths.user_logout import UserLogout +from petstore_api.apis.paths.user_username import UserUsername +from petstore_api.apis.paths.fake_classname_test import FakeClassnameTest +from petstore_api.apis.paths.fake import Fake +from petstore_api.apis.paths.fake_refs_number import FakeRefsNumber +from petstore_api.apis.paths.fake_refs_mammal import FakeRefsMammal +from petstore_api.apis.paths.fake_refs_string import FakeRefsString +from petstore_api.apis.paths.fake_refs_boolean import FakeRefsBoolean +from petstore_api.apis.paths.fake_refs_arraymodel import FakeRefsArraymodel +from petstore_api.apis.paths.fake_refs_composed_one_of_number_with_validations import FakeRefsComposedOneOfNumberWithValidations +from petstore_api.apis.paths.fake_refs_object_model_with_ref_props import FakeRefsObjectModelWithRefProps +from petstore_api.apis.paths.fake_refs_enum import FakeRefsEnum +from petstore_api.apis.paths.fake_refs_array_of_enums import FakeRefsArrayOfEnums +from petstore_api.apis.paths.fake_additional_properties_with_array_of_enums import FakeAdditionalPropertiesWithArrayOfEnums +from petstore_api.apis.paths.fake_json_form_data import FakeJsonFormData +from petstore_api.apis.paths.fake_inline_additional_properties import FakeInlineAdditionalProperties +from petstore_api.apis.paths.fake_body_with_query_params import FakeBodyWithQueryParams +from petstore_api.apis.paths.another_fake_dummy import AnotherFakeDummy +from petstore_api.apis.paths.fake_body_with_file_schema import FakeBodyWithFileSchema +from petstore_api.apis.paths.fake_case_sensitive_params import FakeCaseSensitiveParams +from petstore_api.apis.paths.fake_test_query_paramters import FakeTestQueryParamters +from petstore_api.apis.paths.fake_pet_id_upload_image_with_required_file import FakePetIdUploadImageWithRequiredFile +from petstore_api.apis.paths.fake_parameter_collisions_1_a_b_ab_self_a_b_ import FakeParameterCollisions1ABAbSelfAB +from petstore_api.apis.paths.fake_upload_file import FakeUploadFile +from petstore_api.apis.paths.fake_upload_files import FakeUploadFiles +from petstore_api.apis.paths.fake_upload_download_file import FakeUploadDownloadFile +from petstore_api.apis.paths.fake_health import FakeHealth +from petstore_api.apis.paths.fake_inline_composition_ import FakeInlineComposition +from petstore_api.apis.paths.fake_obj_in_query import FakeObjInQuery +from petstore_api.apis.paths.fake_ref_obj_in_query import FakeRefObjInQuery +from petstore_api.apis.paths.fake_json_with_charset import FakeJsonWithCharset +from petstore_api.apis.paths.fake_response_without_schema import FakeResponseWithoutSchema +from petstore_api.apis.paths.fake_json_patch import FakeJsonPatch +from petstore_api.apis.paths.fake_delete_coffee_id import FakeDeleteCoffeeId +from petstore_api.apis.paths.fake_query_param_with_json_content_type import FakeQueryParamWithJsonContentType + +PathToApi = typing_extensions.TypedDict( + 'PathToApi', + { + PathValues.FOO: Foo, + PathValues.PET: Pet, + PathValues.PET_FIND_BY_STATUS: PetFindByStatus, + PathValues.PET_FIND_BY_TAGS: PetFindByTags, + PathValues.PET_PET_ID: PetPetId, + PathValues.PET_PET_ID_UPLOAD_IMAGE: PetPetIdUploadImage, + PathValues.STORE_INVENTORY: StoreInventory, + PathValues.STORE_ORDER: StoreOrder, + PathValues.STORE_ORDER_ORDER_ID: StoreOrderOrderId, + PathValues.USER: User, + PathValues.USER_CREATE_WITH_ARRAY: UserCreateWithArray, + PathValues.USER_CREATE_WITH_LIST: UserCreateWithList, + PathValues.USER_LOGIN: UserLogin, + PathValues.USER_LOGOUT: UserLogout, + PathValues.USER_USERNAME: UserUsername, + PathValues.FAKE_CLASSNAME_TEST: FakeClassnameTest, + PathValues.FAKE: Fake, + PathValues.FAKE_REFS_NUMBER: FakeRefsNumber, + PathValues.FAKE_REFS_MAMMAL: FakeRefsMammal, + PathValues.FAKE_REFS_STRING: FakeRefsString, + PathValues.FAKE_REFS_BOOLEAN: FakeRefsBoolean, + PathValues.FAKE_REFS_ARRAYMODEL: FakeRefsArraymodel, + PathValues.FAKE_REFS_COMPOSED_ONE_OF_NUMBER_WITH_VALIDATIONS: FakeRefsComposedOneOfNumberWithValidations, + PathValues.FAKE_REFS_OBJECT_MODEL_WITH_REF_PROPS: FakeRefsObjectModelWithRefProps, + PathValues.FAKE_REFS_ENUM: FakeRefsEnum, + PathValues.FAKE_REFS_ARRAYOFENUMS: FakeRefsArrayOfEnums, + PathValues.FAKE_ADDITIONALPROPERTIESWITHARRAYOFENUMS: FakeAdditionalPropertiesWithArrayOfEnums, + PathValues.FAKE_JSON_FORM_DATA: FakeJsonFormData, + PathValues.FAKE_INLINEADDITIONAL_PROPERTIES: FakeInlineAdditionalProperties, + PathValues.FAKE_BODYWITHQUERYPARAMS: FakeBodyWithQueryParams, + PathValues.ANOTHERFAKE_DUMMY: AnotherFakeDummy, + PathValues.FAKE_BODYWITHFILESCHEMA: FakeBodyWithFileSchema, + PathValues.FAKE_CASESENSITIVEPARAMS: FakeCaseSensitiveParams, + PathValues.FAKE_TESTQUERYPARAMTERS: FakeTestQueryParamters, + PathValues.FAKE_PET_ID_UPLOAD_IMAGE_WITH_REQUIRED_FILE: FakePetIdUploadImageWithRequiredFile, + PathValues.FAKE_PARAMETER_COLLISIONS_1_A_B_AB_SELF_AB_: FakeParameterCollisions1ABAbSelfAB, + PathValues.FAKE_UPLOAD_FILE: FakeUploadFile, + PathValues.FAKE_UPLOAD_FILES: FakeUploadFiles, + PathValues.FAKE_UPLOAD_DOWNLOAD_FILE: FakeUploadDownloadFile, + PathValues.FAKE_HEALTH: FakeHealth, + PathValues.FAKE_INLINE_COMPOSITION_: FakeInlineComposition, + PathValues.FAKE_OBJ_IN_QUERY: FakeObjInQuery, + PathValues.FAKE_REF_OBJ_IN_QUERY: FakeRefObjInQuery, + PathValues.FAKE_JSON_WITH_CHARSET: FakeJsonWithCharset, + PathValues.FAKE_RESPONSE_WITHOUT_SCHEMA: FakeResponseWithoutSchema, + PathValues.FAKE_JSON_PATCH: FakeJsonPatch, + PathValues.FAKE_DELETE_COFFEE_ID: FakeDeleteCoffeeId, + PathValues.FAKE_QUERY_PARAM_WITH_JSON_CONTENT_TYPE: FakeQueryParamWithJsonContentType, + } +) + +path_to_api = PathToApi( + { + PathValues.FOO: Foo, + PathValues.PET: Pet, + PathValues.PET_FIND_BY_STATUS: PetFindByStatus, + PathValues.PET_FIND_BY_TAGS: PetFindByTags, + PathValues.PET_PET_ID: PetPetId, + PathValues.PET_PET_ID_UPLOAD_IMAGE: PetPetIdUploadImage, + PathValues.STORE_INVENTORY: StoreInventory, + PathValues.STORE_ORDER: StoreOrder, + PathValues.STORE_ORDER_ORDER_ID: StoreOrderOrderId, + PathValues.USER: User, + PathValues.USER_CREATE_WITH_ARRAY: UserCreateWithArray, + PathValues.USER_CREATE_WITH_LIST: UserCreateWithList, + PathValues.USER_LOGIN: UserLogin, + PathValues.USER_LOGOUT: UserLogout, + PathValues.USER_USERNAME: UserUsername, + PathValues.FAKE_CLASSNAME_TEST: FakeClassnameTest, + PathValues.FAKE: Fake, + PathValues.FAKE_REFS_NUMBER: FakeRefsNumber, + PathValues.FAKE_REFS_MAMMAL: FakeRefsMammal, + PathValues.FAKE_REFS_STRING: FakeRefsString, + PathValues.FAKE_REFS_BOOLEAN: FakeRefsBoolean, + PathValues.FAKE_REFS_ARRAYMODEL: FakeRefsArraymodel, + PathValues.FAKE_REFS_COMPOSED_ONE_OF_NUMBER_WITH_VALIDATIONS: FakeRefsComposedOneOfNumberWithValidations, + PathValues.FAKE_REFS_OBJECT_MODEL_WITH_REF_PROPS: FakeRefsObjectModelWithRefProps, + PathValues.FAKE_REFS_ENUM: FakeRefsEnum, + PathValues.FAKE_REFS_ARRAYOFENUMS: FakeRefsArrayOfEnums, + PathValues.FAKE_ADDITIONALPROPERTIESWITHARRAYOFENUMS: FakeAdditionalPropertiesWithArrayOfEnums, + PathValues.FAKE_JSON_FORM_DATA: FakeJsonFormData, + PathValues.FAKE_INLINEADDITIONAL_PROPERTIES: FakeInlineAdditionalProperties, + PathValues.FAKE_BODYWITHQUERYPARAMS: FakeBodyWithQueryParams, + PathValues.ANOTHERFAKE_DUMMY: AnotherFakeDummy, + PathValues.FAKE_BODYWITHFILESCHEMA: FakeBodyWithFileSchema, + PathValues.FAKE_CASESENSITIVEPARAMS: FakeCaseSensitiveParams, + PathValues.FAKE_TESTQUERYPARAMTERS: FakeTestQueryParamters, + PathValues.FAKE_PET_ID_UPLOAD_IMAGE_WITH_REQUIRED_FILE: FakePetIdUploadImageWithRequiredFile, + PathValues.FAKE_PARAMETER_COLLISIONS_1_A_B_AB_SELF_AB_: FakeParameterCollisions1ABAbSelfAB, + PathValues.FAKE_UPLOAD_FILE: FakeUploadFile, + PathValues.FAKE_UPLOAD_FILES: FakeUploadFiles, + PathValues.FAKE_UPLOAD_DOWNLOAD_FILE: FakeUploadDownloadFile, + PathValues.FAKE_HEALTH: FakeHealth, + PathValues.FAKE_INLINE_COMPOSITION_: FakeInlineComposition, + PathValues.FAKE_OBJ_IN_QUERY: FakeObjInQuery, + PathValues.FAKE_REF_OBJ_IN_QUERY: FakeRefObjInQuery, + PathValues.FAKE_JSON_WITH_CHARSET: FakeJsonWithCharset, + PathValues.FAKE_RESPONSE_WITHOUT_SCHEMA: FakeResponseWithoutSchema, + PathValues.FAKE_JSON_PATCH: FakeJsonPatch, + PathValues.FAKE_DELETE_COFFEE_ID: FakeDeleteCoffeeId, + PathValues.FAKE_QUERY_PARAM_WITH_JSON_CONTENT_TYPE: FakeQueryParamWithJsonContentType, + } +) diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/__init__.py new file mode 100644 index 0000000000..a0e17c5536 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/__init__.py @@ -0,0 +1,3 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.apis.path_to_api import path_to_api diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/another_fake_dummy.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/another_fake_dummy.py new file mode 100644 index 0000000000..8fafb8f115 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/another_fake_dummy.py @@ -0,0 +1,7 @@ +from petstore_api.paths.another_fake_dummy.patch import ApiForpatch + + +class AnotherFakeDummy( + ApiForpatch, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake.py new file mode 100644 index 0000000000..f8de5e6f9d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake.py @@ -0,0 +1,13 @@ +from petstore_api.paths.fake.get import ApiForget +from petstore_api.paths.fake.post import ApiForpost +from petstore_api.paths.fake.delete import ApiFordelete +from petstore_api.paths.fake.patch import ApiForpatch + + +class Fake( + ApiForget, + ApiForpost, + ApiFordelete, + ApiForpatch, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_additional_properties_with_array_of_enums.py new file mode 100644 index 0000000000..3df79a3103 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_additional_properties_with_array_of_enums.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_additional_properties_with_array_of_enums.get import ApiForget + + +class FakeAdditionalPropertiesWithArrayOfEnums( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_body_with_file_schema.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_body_with_file_schema.py new file mode 100644 index 0000000000..d95c287ecc --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_body_with_file_schema.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_body_with_file_schema.put import ApiForput + + +class FakeBodyWithFileSchema( + ApiForput, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_body_with_query_params.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_body_with_query_params.py new file mode 100644 index 0000000000..4c77fc0c0d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_body_with_query_params.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_body_with_query_params.put import ApiForput + + +class FakeBodyWithQueryParams( + ApiForput, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_case_sensitive_params.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_case_sensitive_params.py new file mode 100644 index 0000000000..c5dafb43a0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_case_sensitive_params.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_case_sensitive_params.put import ApiForput + + +class FakeCaseSensitiveParams( + ApiForput, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_classname_test.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_classname_test.py new file mode 100644 index 0000000000..090ec6025f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_classname_test.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_classname_test.patch import ApiForpatch + + +class FakeClassnameTest( + ApiForpatch, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_delete_coffee_id.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_delete_coffee_id.py new file mode 100644 index 0000000000..589ba701a7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_delete_coffee_id.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_delete_coffee_id.delete import ApiFordelete + + +class FakeDeleteCoffeeId( + ApiFordelete, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_health.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_health.py new file mode 100644 index 0000000000..fc5bf3258b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_health.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_health.get import ApiForget + + +class FakeHealth( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_inline_additional_properties.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_inline_additional_properties.py new file mode 100644 index 0000000000..57bdd0745a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_inline_additional_properties.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_inline_additional_properties.post import ApiForpost + + +class FakeInlineAdditionalProperties( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_inline_composition_.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_inline_composition_.py new file mode 100644 index 0000000000..9854c250b1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_inline_composition_.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_inline_composition_.post import ApiForpost + + +class FakeInlineComposition( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_json_form_data.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_json_form_data.py new file mode 100644 index 0000000000..1533f9805e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_json_form_data.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_json_form_data.get import ApiForget + + +class FakeJsonFormData( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_json_patch.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_json_patch.py new file mode 100644 index 0000000000..53e563dbdb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_json_patch.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_json_patch.patch import ApiForpatch + + +class FakeJsonPatch( + ApiForpatch, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_json_with_charset.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_json_with_charset.py new file mode 100644 index 0000000000..a1a4c38e67 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_json_with_charset.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_json_with_charset.post import ApiForpost + + +class FakeJsonWithCharset( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_obj_in_query.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_obj_in_query.py new file mode 100644 index 0000000000..a051580814 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_obj_in_query.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_obj_in_query.get import ApiForget + + +class FakeObjInQuery( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_.py new file mode 100644 index 0000000000..e99db37cd9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_parameter_collisions_1_a_b_ab_self_a_b_.post import ApiForpost + + +class FakeParameterCollisions1ABAbSelfAB( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_pet_id_upload_image_with_required_file.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_pet_id_upload_image_with_required_file.py new file mode 100644 index 0000000000..06b4b53bbd --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_pet_id_upload_image_with_required_file.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_pet_id_upload_image_with_required_file.post import ApiForpost + + +class FakePetIdUploadImageWithRequiredFile( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_query_param_with_json_content_type.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_query_param_with_json_content_type.py new file mode 100644 index 0000000000..96aa0592a0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_query_param_with_json_content_type.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_query_param_with_json_content_type.get import ApiForget + + +class FakeQueryParamWithJsonContentType( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_ref_obj_in_query.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_ref_obj_in_query.py new file mode 100644 index 0000000000..5cb347c09c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_ref_obj_in_query.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_ref_obj_in_query.get import ApiForget + + +class FakeRefObjInQuery( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_array_of_enums.py new file mode 100644 index 0000000000..8aca3fb8d0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_array_of_enums.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_refs_array_of_enums.post import ApiForpost + + +class FakeRefsArrayOfEnums( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_arraymodel.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_arraymodel.py new file mode 100644 index 0000000000..de94cbe498 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_arraymodel.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_refs_arraymodel.post import ApiForpost + + +class FakeRefsArraymodel( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_boolean.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_boolean.py new file mode 100644 index 0000000000..d3a08723b2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_boolean.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_refs_boolean.post import ApiForpost + + +class FakeRefsBoolean( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_composed_one_of_number_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_composed_one_of_number_with_validations.py new file mode 100644 index 0000000000..2caf9048a4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_composed_one_of_number_with_validations.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_refs_composed_one_of_number_with_validations.post import ApiForpost + + +class FakeRefsComposedOneOfNumberWithValidations( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_enum.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_enum.py new file mode 100644 index 0000000000..b05f5b2d01 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_enum.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_refs_enum.post import ApiForpost + + +class FakeRefsEnum( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_mammal.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_mammal.py new file mode 100644 index 0000000000..fe0e0b427d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_mammal.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_refs_mammal.post import ApiForpost + + +class FakeRefsMammal( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_number.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_number.py new file mode 100644 index 0000000000..af4111830d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_number.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_refs_number.post import ApiForpost + + +class FakeRefsNumber( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_object_model_with_ref_props.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_object_model_with_ref_props.py new file mode 100644 index 0000000000..1554afa997 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_object_model_with_ref_props.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_refs_object_model_with_ref_props.post import ApiForpost + + +class FakeRefsObjectModelWithRefProps( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_string.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_string.py new file mode 100644 index 0000000000..9420eeb048 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_refs_string.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_refs_string.post import ApiForpost + + +class FakeRefsString( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_response_without_schema.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_response_without_schema.py new file mode 100644 index 0000000000..56590de8d0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_response_without_schema.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_response_without_schema.get import ApiForget + + +class FakeResponseWithoutSchema( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_test_query_paramters.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_test_query_paramters.py new file mode 100644 index 0000000000..ff97fcdf59 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_test_query_paramters.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_test_query_paramters.put import ApiForput + + +class FakeTestQueryParamters( + ApiForput, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_upload_download_file.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_upload_download_file.py new file mode 100644 index 0000000000..f41a00e3e4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_upload_download_file.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_upload_download_file.post import ApiForpost + + +class FakeUploadDownloadFile( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_upload_file.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_upload_file.py new file mode 100644 index 0000000000..b080fcd26c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_upload_file.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_upload_file.post import ApiForpost + + +class FakeUploadFile( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_upload_files.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_upload_files.py new file mode 100644 index 0000000000..6f47e0b8f0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/fake_upload_files.py @@ -0,0 +1,7 @@ +from petstore_api.paths.fake_upload_files.post import ApiForpost + + +class FakeUploadFiles( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/foo.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/foo.py new file mode 100644 index 0000000000..237a0fba70 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/foo.py @@ -0,0 +1,7 @@ +from petstore_api.paths.foo.get import ApiForget + + +class Foo( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet.py new file mode 100644 index 0000000000..8e9f07940b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet.py @@ -0,0 +1,9 @@ +from petstore_api.paths.pet.put import ApiForput +from petstore_api.paths.pet.post import ApiForpost + + +class Pet( + ApiForput, + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_find_by_status.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_find_by_status.py new file mode 100644 index 0000000000..86a6eebf13 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_find_by_status.py @@ -0,0 +1,7 @@ +from petstore_api.paths.pet_find_by_status.get import ApiForget + + +class PetFindByStatus( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_find_by_tags.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_find_by_tags.py new file mode 100644 index 0000000000..c0f4090e4e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_find_by_tags.py @@ -0,0 +1,7 @@ +from petstore_api.paths.pet_find_by_tags.get import ApiForget + + +class PetFindByTags( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_pet_id.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_pet_id.py new file mode 100644 index 0000000000..6290395b83 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_pet_id.py @@ -0,0 +1,11 @@ +from petstore_api.paths.pet_pet_id.get import ApiForget +from petstore_api.paths.pet_pet_id.post import ApiForpost +from petstore_api.paths.pet_pet_id.delete import ApiFordelete + + +class PetPetId( + ApiForget, + ApiForpost, + ApiFordelete, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_pet_id_upload_image.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_pet_id_upload_image.py new file mode 100644 index 0000000000..92bfe39700 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/pet_pet_id_upload_image.py @@ -0,0 +1,7 @@ +from petstore_api.paths.pet_pet_id_upload_image.post import ApiForpost + + +class PetPetIdUploadImage( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/store_inventory.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/store_inventory.py new file mode 100644 index 0000000000..f614016a11 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/store_inventory.py @@ -0,0 +1,7 @@ +from petstore_api.paths.store_inventory.get import ApiForget + + +class StoreInventory( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/store_order.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/store_order.py new file mode 100644 index 0000000000..827bc76647 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/store_order.py @@ -0,0 +1,7 @@ +from petstore_api.paths.store_order.post import ApiForpost + + +class StoreOrder( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/store_order_order_id.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/store_order_order_id.py new file mode 100644 index 0000000000..1436ff0b93 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/store_order_order_id.py @@ -0,0 +1,9 @@ +from petstore_api.paths.store_order_order_id.get import ApiForget +from petstore_api.paths.store_order_order_id.delete import ApiFordelete + + +class StoreOrderOrderId( + ApiForget, + ApiFordelete, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user.py new file mode 100644 index 0000000000..b708c602e7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user.py @@ -0,0 +1,7 @@ +from petstore_api.paths.user.post import ApiForpost + + +class User( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_create_with_array.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_create_with_array.py new file mode 100644 index 0000000000..d3d5904ceb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_create_with_array.py @@ -0,0 +1,7 @@ +from petstore_api.paths.user_create_with_array.post import ApiForpost + + +class UserCreateWithArray( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_create_with_list.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_create_with_list.py new file mode 100644 index 0000000000..f8f3f34d40 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_create_with_list.py @@ -0,0 +1,7 @@ +from petstore_api.paths.user_create_with_list.post import ApiForpost + + +class UserCreateWithList( + ApiForpost, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_login.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_login.py new file mode 100644 index 0000000000..5cd6b4e0f8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_login.py @@ -0,0 +1,7 @@ +from petstore_api.paths.user_login.get import ApiForget + + +class UserLogin( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_logout.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_logout.py new file mode 100644 index 0000000000..621e15a8a3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_logout.py @@ -0,0 +1,7 @@ +from petstore_api.paths.user_logout.get import ApiForget + + +class UserLogout( + ApiForget, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_username.py b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_username.py new file mode 100644 index 0000000000..16710585ee --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/paths/user_username.py @@ -0,0 +1,11 @@ +from petstore_api.paths.user_username.get import ApiForget +from petstore_api.paths.user_username.put import ApiForput +from petstore_api.paths.user_username.delete import ApiFordelete + + +class UserUsername( + ApiForget, + ApiForput, + ApiFordelete, +): + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/tag_to_api.py b/samples/openapi3/client/petstore/python/petstore_api/apis/tag_to_api.py new file mode 100644 index 0000000000..ad42a5d1de --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/tag_to_api.py @@ -0,0 +1,35 @@ +import typing_extensions + +from petstore_api.apis.tags import TagValues +from petstore_api.apis.tags.pet_api import PetApi +from petstore_api.apis.tags.store_api import StoreApi +from petstore_api.apis.tags.user_api import UserApi +from petstore_api.apis.tags.another_fake_api import AnotherFakeApi +from petstore_api.apis.tags.default_api import DefaultApi +from petstore_api.apis.tags.fake_api import FakeApi +from petstore_api.apis.tags.fake_classname_tags123_api import FakeClassnameTags123Api + +TagToApi = typing_extensions.TypedDict( + 'TagToApi', + { + TagValues.PET: PetApi, + TagValues.STORE: StoreApi, + TagValues.USER: UserApi, + TagValues.ANOTHERFAKE: AnotherFakeApi, + TagValues.DEFAULT: DefaultApi, + TagValues.FAKE: FakeApi, + TagValues.FAKE_CLASSNAME_TAGS_123: FakeClassnameTags123Api, + } +) + +tag_to_api = TagToApi( + { + TagValues.PET: PetApi, + TagValues.STORE: StoreApi, + TagValues.USER: UserApi, + TagValues.ANOTHERFAKE: AnotherFakeApi, + TagValues.DEFAULT: DefaultApi, + TagValues.FAKE: FakeApi, + TagValues.FAKE_CLASSNAME_TAGS_123: FakeClassnameTags123Api, + } +) diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/tags/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/__init__.py new file mode 100644 index 0000000000..a8ec6fddd9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/__init__.py @@ -0,0 +1,15 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.apis.tag_to_api import tag_to_api + +import enum + + +class TagValues(str, enum.Enum): + PET = "pet" + STORE = "store" + USER = "user" + ANOTHERFAKE = "$another-fake?" + DEFAULT = "default" + FAKE = "fake" + FAKE_CLASSNAME_TAGS_123 = "fake_classname_tags 123#$%^" diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/another_fake_api.py similarity index 76% rename from samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py rename to samples/openapi3/client/petstore/python/petstore_api/apis/tags/another_fake_api.py index a6e0483cf6..129fbd7510 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/another_fake_api.py @@ -9,13 +9,11 @@ Generated by: https://openapi-generator.tech """ -from petstore_api.api_client import ApiClient -from petstore_api.api.another_fake_api_endpoints.call_123_test_special_tags import Call123TestSpecialTags +from petstore_api.paths.another_fake_dummy.patch import Call123TestSpecialTags class AnotherFakeApi( Call123TestSpecialTags, - ApiClient, ): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/tags/default_api.py b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/default_api.py new file mode 100644 index 0000000000..99639a6994 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/default_api.py @@ -0,0 +1,23 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from petstore_api.paths.foo.get import FooGet + + +class DefaultApi( + FooGet, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/tags/fake_api.py b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/fake_api.py new file mode 100644 index 0000000000..564d77038a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/fake_api.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from petstore_api.paths.fake_additional_properties_with_array_of_enums.get import AdditionalPropertiesWithArrayOfEnums +from petstore_api.paths.fake_refs_arraymodel.post import ArrayModel +from petstore_api.paths.fake_refs_array_of_enums.post import ArrayOfEnums +from petstore_api.paths.fake_body_with_file_schema.put import BodyWithFileSchema +from petstore_api.paths.fake_body_with_query_params.put import BodyWithQueryParams +from petstore_api.paths.fake_refs_boolean.post import Boolean +from petstore_api.paths.fake_case_sensitive_params.put import CaseSensitiveParams +from petstore_api.paths.fake.patch import ClientModel +from petstore_api.paths.fake_refs_composed_one_of_number_with_validations.post import ComposedOneOfDifferentTypes +from petstore_api.paths.fake_delete_coffee_id.delete import DeleteCoffee +from petstore_api.paths.fake.post import EndpointParameters +from petstore_api.paths.fake.get import EnumParameters +from petstore_api.paths.fake_health.get import FakeHealthGet +from petstore_api.paths.fake.delete import GroupParameters +from petstore_api.paths.fake_inline_additional_properties.post import InlineAdditionalProperties +from petstore_api.paths.fake_inline_composition_.post import InlineComposition +from petstore_api.paths.fake_json_form_data.get import JsonFormData +from petstore_api.paths.fake_json_patch.patch import JsonPatch +from petstore_api.paths.fake_json_with_charset.post import JsonWithCharset +from petstore_api.paths.fake_refs_mammal.post import Mammal +from petstore_api.paths.fake_refs_number.post import NumberWithValidations +from petstore_api.paths.fake_obj_in_query.get import ObjectInQuery +from petstore_api.paths.fake_refs_object_model_with_ref_props.post import ObjectModelWithRefProps +from petstore_api.paths.fake_parameter_collisions_1_a_b_ab_self_a_b_.post import ParameterCollisions +from petstore_api.paths.fake_query_param_with_json_content_type.get import QueryParamWithJsonContentType +from petstore_api.paths.fake_test_query_paramters.put import QueryParameterCollectionFormat +from petstore_api.paths.fake_ref_obj_in_query.get import RefObjectInQuery +from petstore_api.paths.fake_response_without_schema.get import ResponseWithoutSchema +from petstore_api.paths.fake_refs_string.post import String +from petstore_api.paths.fake_refs_enum.post import StringEnum +from petstore_api.paths.fake_upload_download_file.post import UploadDownloadFile +from petstore_api.paths.fake_upload_file.post import UploadFile +from petstore_api.paths.fake_upload_files.post import UploadFiles + + +class FakeApi( + AdditionalPropertiesWithArrayOfEnums, + ArrayModel, + ArrayOfEnums, + BodyWithFileSchema, + BodyWithQueryParams, + Boolean, + CaseSensitiveParams, + ClientModel, + ComposedOneOfDifferentTypes, + DeleteCoffee, + EndpointParameters, + EnumParameters, + FakeHealthGet, + GroupParameters, + InlineAdditionalProperties, + InlineComposition, + JsonFormData, + JsonPatch, + JsonWithCharset, + Mammal, + NumberWithValidations, + ObjectInQuery, + ObjectModelWithRefProps, + ParameterCollisions, + QueryParamWithJsonContentType, + QueryParameterCollectionFormat, + RefObjectInQuery, + ResponseWithoutSchema, + String, + StringEnum, + UploadDownloadFile, + UploadFile, + UploadFiles, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags123_api.py b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/fake_classname_tags123_api.py similarity index 78% rename from samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags123_api.py rename to samples/openapi3/client/petstore/python/petstore_api/apis/tags/fake_classname_tags123_api.py index ce7cfd29f7..9997b64ba7 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags123_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/fake_classname_tags123_api.py @@ -9,13 +9,11 @@ Generated by: https://openapi-generator.tech """ -from petstore_api.api_client import ApiClient -from petstore_api.api.fake_classname_tags123_api_endpoints.classname import Classname +from petstore_api.paths.fake_classname_test.patch import Classname class FakeClassnameTags123Api( Classname, - ApiClient, ): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/tags/pet_api.py b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/pet_api.py new file mode 100644 index 0000000000..402e69c9cf --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/pet_api.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from petstore_api.paths.pet.post import AddPet +from petstore_api.paths.pet_pet_id.delete import DeletePet +from petstore_api.paths.pet_find_by_status.get import FindPetsByStatus +from petstore_api.paths.pet_find_by_tags.get import FindPetsByTags +from petstore_api.paths.pet_pet_id.get import GetPetById +from petstore_api.paths.pet.put import UpdatePet +from petstore_api.paths.pet_pet_id.post import UpdatePetWithForm +from petstore_api.paths.fake_pet_id_upload_image_with_required_file.post import UploadFileWithRequiredFile +from petstore_api.paths.pet_pet_id_upload_image.post import UploadImage + + +class PetApi( + AddPet, + DeletePet, + FindPetsByStatus, + FindPetsByTags, + GetPetById, + UpdatePet, + UpdatePetWithForm, + UploadFileWithRequiredFile, + UploadImage, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/tags/store_api.py b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/store_api.py new file mode 100644 index 0000000000..b9e1d09ed5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/store_api.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from petstore_api.paths.store_order_order_id.delete import DeleteOrder +from petstore_api.paths.store_inventory.get import GetInventory +from petstore_api.paths.store_order_order_id.get import GetOrderById +from petstore_api.paths.store_order.post import PlaceOrder + + +class StoreApi( + DeleteOrder, + GetInventory, + GetOrderById, + PlaceOrder, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/apis/tags/user_api.py b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/user_api.py new file mode 100644 index 0000000000..b84994811c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/apis/tags/user_api.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from petstore_api.paths.user.post import CreateUser +from petstore_api.paths.user_create_with_array.post import CreateUsersWithArrayInput +from petstore_api.paths.user_create_with_list.post import CreateUsersWithListInput +from petstore_api.paths.user_username.delete import DeleteUser +from petstore_api.paths.user_username.get import GetUserByName +from petstore_api.paths.user_login.get import LoginUser +from petstore_api.paths.user_logout.get import LogoutUser +from petstore_api.paths.user_username.put import UpdateUser + + +class UserApi( + CreateUser, + CreateUsersWithArrayInput, + CreateUsersWithListInput, + DeleteUser, + GetUserByName, + LoginUser, + LogoutUser, + UpdateUser, +): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/configuration.py b/samples/openapi3/client/petstore/python/petstore_api/configuration.py index 0c4db4c52a..f7c2a3ff91 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python/petstore_api/configuration.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,7 +9,6 @@ Generated by: https://openapi-generator.tech """ - import copy import logging import multiprocessing @@ -21,7 +22,8 @@ from petstore_api.exceptions import ApiValueError JSON_SCHEMA_VALIDATION_KEYWORDS = { 'multipleOf', 'maximum', 'exclusiveMaximum', 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems' + 'minLength', 'pattern', 'maxItems', 'minItems', + 'uniqueItems', 'maxProperties', 'minProperties', } class Configuration(object): @@ -75,8 +77,6 @@ class Configuration(object): :param server_operation_variables: Mapping from operation ID to a mapping with string values to replace variables in templated server configuration. The validation of enums is performed for variables with defined enum values before. - :param ssl_ca_cert: str - the path to a file of concatenated CA certificates - in PEM format :Example: @@ -131,7 +131,7 @@ conf = petstore_api.Configuration( 'Authorization' header, which is used to carry the signature. One may be tempted to sign all headers by default, but in practice it rarely works. - This is because explicit proxies, transparent proxies, TLS termination endpoints or + This is beccause explicit proxies, transparent proxies, TLS termination endpoints or load balancers may add/modify/remove headers. Include the HTTP headers that you know are not going to be modified in transit. @@ -159,14 +159,12 @@ conf = petstore_api.Configuration( def __init__(self, host=None, api_key=None, api_key_prefix=None, - access_token=None, username=None, password=None, discard_unknown_keys=False, disabled_client_side_validations="", signing_info=None, server_index=None, server_variables=None, server_operation_index=None, server_operation_variables=None, - ssl_ca_cert=None, ): """Constructor """ @@ -185,7 +183,6 @@ conf = petstore_api.Configuration( """Temp file folder for downloading files """ # Authentication Settings - self.access_token = access_token self.api_key = {} if api_key: self.api_key = api_key @@ -212,6 +209,9 @@ conf = petstore_api.Configuration( self.signing_info = signing_info """The HTTP signing configuration """ + self.access_token = None + """access token for OAuth/Bearer + """ self.logger = {} """Logging Settings """ @@ -238,7 +238,7 @@ conf = petstore_api.Configuration( Set this to false to skip verifying SSL certificate when calling API from https server. """ - self.ssl_ca_cert = ssl_ca_cert + self.ssl_ca_cert = None """Set this to customize the certificate file to verify the peer. """ self.cert_file = None @@ -262,9 +262,6 @@ conf = petstore_api.Configuration( self.proxy = None """Proxy URL """ - self.no_proxy = None - """bypass proxy for host in the no_proxy list. - """ self.proxy_headers = None """Proxy headers """ @@ -304,7 +301,7 @@ conf = petstore_api.Configuration( "Invalid keyword: '{0}''".format(v)) self._disabled_client_side_validations = s if name == "signing_info" and value is not None: - # Ensure the host parameter from signing info is the same as + # Ensure the host paramater from signing info is the same as # Configuration.host. value.host = self.host @@ -535,7 +532,7 @@ conf = petstore_api.Configuration( "qa-petstore", "dev-petstore" ] - }, + }, 'port': { 'description': "No description provided", 'default_value': "80", @@ -543,8 +540,8 @@ conf = petstore_api.Configuration( "80", "8080" ] + } } - } }, { 'url': "https://localhost:8080/{version}", @@ -557,8 +554,8 @@ conf = petstore_api.Configuration( "v1", "v2" ] + } } - } } ] diff --git a/samples/openapi3/client/petstore/python/petstore_api/exceptions.py b/samples/openapi3/client/petstore/python/petstore_api/exceptions.py index d223cb4876..ed422fd2d0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/exceptions.py +++ b/samples/openapi3/client/petstore/python/petstore_api/exceptions.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -97,12 +99,12 @@ class ApiKeyError(OpenApiException, KeyError): class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() + def __init__(self, status=None, reason=None, api_response: 'petstore_api.api_client.ApiResponse' = None): + if api_response: + self.status = api_response.response.status + self.reason = api_response.response.reason + self.body = api_response.response.data + self.headers = api_response.response.getheaders() else: self.status = status self.reason = reason @@ -111,7 +113,7 @@ class ApiException(OpenApiException): def __str__(self): """Custom error messages for exception""" - error_message = "Status Code: {0}\n"\ + error_message = "({0})\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: error_message += "HTTP response headers: {0}\n".format( @@ -123,30 +125,6 @@ class ApiException(OpenApiException): return error_message -class NotFoundException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(NotFoundException, self).__init__(status, reason, http_resp) - - -class UnauthorizedException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(UnauthorizedException, self).__init__(status, reason, http_resp) - - -class ForbiddenException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ForbiddenException, self).__init__(status, reason, http_resp) - - -class ServiceException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - super(ServiceException, self).__init__(status, reason, http_resp) - - def render_path(path_to_item): """Returns a string representation of a path""" result = "" diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py index 307a8c772f..79ca58cf23 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,285 +9,299 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class AdditionalPropertiesClass(ModelNormal): +class AdditionalPropertiesClass( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'map_property': ({str: (str,)},), # noqa: E501 - 'map_of_map_property': ({str: ({str: (str,)},)},), # noqa: E501 - 'anytype_1': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 - 'map_with_undeclared_properties_anytype_1': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - 'map_with_undeclared_properties_anytype_2': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - 'map_with_undeclared_properties_anytype_3': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - 'empty_map': (dict,), # noqa: E501 - 'map_with_undeclared_properties_string': ({str: (str,)},), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'map_property': 'map_property', # noqa: E501 - 'map_of_map_property': 'map_of_map_property', # noqa: E501 - 'anytype_1': 'anytype_1', # noqa: E501 - 'map_with_undeclared_properties_anytype_1': 'map_with_undeclared_properties_anytype_1', # noqa: E501 - 'map_with_undeclared_properties_anytype_2': 'map_with_undeclared_properties_anytype_2', # noqa: E501 - 'map_with_undeclared_properties_anytype_3': 'map_with_undeclared_properties_anytype_3', # noqa: E501 - 'empty_map': 'empty_map', # noqa: E501 - 'map_with_undeclared_properties_string': 'map_with_undeclared_properties_string', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """AdditionalPropertiesClass - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - map_property ({str: (str,)}): [optional] # noqa: E501 - map_of_map_property ({str: ({str: (str,)},)}): [optional] # noqa: E501 - anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 - map_with_undeclared_properties_anytype_1 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - map_with_undeclared_properties_anytype_2 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - map_with_undeclared_properties_anytype_3 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - empty_map (dict): an object with no declared properties and no undeclared properties, hence it's an empty map.. [optional] # noqa: E501 - map_with_undeclared_properties_string ({str: (str,)}): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + + class map_property( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'map_property': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """AdditionalPropertiesClass - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - map_property ({str: (str,)}): [optional] # noqa: E501 - map_of_map_property ({str: ({str: (str,)},)}): [optional] # noqa: E501 - anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 - map_with_undeclared_properties_anytype_1 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - map_with_undeclared_properties_anytype_2 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - map_with_undeclared_properties_anytype_3 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - empty_map (dict): an object with no declared properties and no undeclared properties, hence it's an empty map.. [optional] # noqa: E501 - map_with_undeclared_properties_string ({str: (str,)}): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + + + class map_of_map_property( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, ], + ) -> 'map_of_map_property': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, ) + anytype_1 = schemas.AnyTypeSchema + map_with_undeclared_properties_anytype_1 = schemas.DictSchema + map_with_undeclared_properties_anytype_2 = schemas.DictSchema + + + class map_with_undeclared_properties_anytype_3( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.AnyTypeSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'map_with_undeclared_properties_anytype_3': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class empty_map( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.NotAnyTypeSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'empty_map': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class map_with_undeclared_properties_string( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'map_with_undeclared_properties_string': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "map_property": map_property, + "map_of_map_property": map_of_map_property, + "anytype_1": anytype_1, + "map_with_undeclared_properties_anytype_1": map_with_undeclared_properties_anytype_1, + "map_with_undeclared_properties_anytype_2": map_with_undeclared_properties_anytype_2, + "map_with_undeclared_properties_anytype_3": map_with_undeclared_properties_anytype_3, + "empty_map": empty_map, + "map_with_undeclared_properties_string": map_with_undeclared_properties_string, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_property"]) -> MetaOapg.properties.map_property: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_of_map_property"]) -> MetaOapg.properties.map_of_map_property: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["anytype_1"]) -> MetaOapg.properties.anytype_1: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_1"]) -> MetaOapg.properties.map_with_undeclared_properties_anytype_1: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_2"]) -> MetaOapg.properties.map_with_undeclared_properties_anytype_2: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_3"]) -> MetaOapg.properties.map_with_undeclared_properties_anytype_3: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["empty_map"]) -> MetaOapg.properties.empty_map: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_with_undeclared_properties_string"]) -> MetaOapg.properties.map_with_undeclared_properties_string: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["map_property", "map_of_map_property", "anytype_1", "map_with_undeclared_properties_anytype_1", "map_with_undeclared_properties_anytype_2", "map_with_undeclared_properties_anytype_3", "empty_map", "map_with_undeclared_properties_string", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_property"]) -> typing.Union[MetaOapg.properties.map_property, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_of_map_property"]) -> typing.Union[MetaOapg.properties.map_of_map_property, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["anytype_1"]) -> typing.Union[MetaOapg.properties.anytype_1, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_1"]) -> typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_1, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_2"]) -> typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_2, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_3"]) -> typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_3, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["empty_map"]) -> typing.Union[MetaOapg.properties.empty_map, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_with_undeclared_properties_string"]) -> typing.Union[MetaOapg.properties.map_with_undeclared_properties_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["map_property", "map_of_map_property", "anytype_1", "map_with_undeclared_properties_anytype_1", "map_with_undeclared_properties_anytype_2", "map_with_undeclared_properties_anytype_3", "empty_map", "map_with_undeclared_properties_string", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + map_property: typing.Union[MetaOapg.properties.map_property, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_of_map_property: typing.Union[MetaOapg.properties.map_of_map_property, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + anytype_1: typing.Union[MetaOapg.properties.anytype_1, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + map_with_undeclared_properties_anytype_1: typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_1, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_with_undeclared_properties_anytype_2: typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_2, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_with_undeclared_properties_anytype_3: typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_3, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + empty_map: typing.Union[MetaOapg.properties.empty_map, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_with_undeclared_properties_string: typing.Union[MetaOapg.properties.map_with_undeclared_properties_string, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AdditionalPropertiesClass': + return super().__new__( + cls, + *args, + map_property=map_property, + map_of_map_property=map_of_map_property, + anytype_1=anytype_1, + map_with_undeclared_properties_anytype_1=map_with_undeclared_properties_anytype_1, + map_with_undeclared_properties_anytype_2=map_with_undeclared_properties_anytype_2, + map_with_undeclared_properties_anytype_3=map_with_undeclared_properties_anytype_3, + empty_map=empty_map, + map_with_undeclared_properties_string=map_with_undeclared_properties_string, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.pyi new file mode 100644 index 0000000000..79ca58cf23 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.pyi @@ -0,0 +1,307 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AdditionalPropertiesClass( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class map_property( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'map_property': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class map_of_map_property( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, ], + ) -> 'map_of_map_property': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + anytype_1 = schemas.AnyTypeSchema + map_with_undeclared_properties_anytype_1 = schemas.DictSchema + map_with_undeclared_properties_anytype_2 = schemas.DictSchema + + + class map_with_undeclared_properties_anytype_3( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.AnyTypeSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'map_with_undeclared_properties_anytype_3': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class empty_map( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.NotAnyTypeSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'empty_map': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class map_with_undeclared_properties_string( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'map_with_undeclared_properties_string': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "map_property": map_property, + "map_of_map_property": map_of_map_property, + "anytype_1": anytype_1, + "map_with_undeclared_properties_anytype_1": map_with_undeclared_properties_anytype_1, + "map_with_undeclared_properties_anytype_2": map_with_undeclared_properties_anytype_2, + "map_with_undeclared_properties_anytype_3": map_with_undeclared_properties_anytype_3, + "empty_map": empty_map, + "map_with_undeclared_properties_string": map_with_undeclared_properties_string, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_property"]) -> MetaOapg.properties.map_property: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_of_map_property"]) -> MetaOapg.properties.map_of_map_property: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["anytype_1"]) -> MetaOapg.properties.anytype_1: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_1"]) -> MetaOapg.properties.map_with_undeclared_properties_anytype_1: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_2"]) -> MetaOapg.properties.map_with_undeclared_properties_anytype_2: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_3"]) -> MetaOapg.properties.map_with_undeclared_properties_anytype_3: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["empty_map"]) -> MetaOapg.properties.empty_map: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_with_undeclared_properties_string"]) -> MetaOapg.properties.map_with_undeclared_properties_string: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["map_property", "map_of_map_property", "anytype_1", "map_with_undeclared_properties_anytype_1", "map_with_undeclared_properties_anytype_2", "map_with_undeclared_properties_anytype_3", "empty_map", "map_with_undeclared_properties_string", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_property"]) -> typing.Union[MetaOapg.properties.map_property, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_of_map_property"]) -> typing.Union[MetaOapg.properties.map_of_map_property, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["anytype_1"]) -> typing.Union[MetaOapg.properties.anytype_1, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_1"]) -> typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_1, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_2"]) -> typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_2, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_with_undeclared_properties_anytype_3"]) -> typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_3, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["empty_map"]) -> typing.Union[MetaOapg.properties.empty_map, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_with_undeclared_properties_string"]) -> typing.Union[MetaOapg.properties.map_with_undeclared_properties_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["map_property", "map_of_map_property", "anytype_1", "map_with_undeclared_properties_anytype_1", "map_with_undeclared_properties_anytype_2", "map_with_undeclared_properties_anytype_3", "empty_map", "map_with_undeclared_properties_string", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + map_property: typing.Union[MetaOapg.properties.map_property, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_of_map_property: typing.Union[MetaOapg.properties.map_of_map_property, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + anytype_1: typing.Union[MetaOapg.properties.anytype_1, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + map_with_undeclared_properties_anytype_1: typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_1, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_with_undeclared_properties_anytype_2: typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_2, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_with_undeclared_properties_anytype_3: typing.Union[MetaOapg.properties.map_with_undeclared_properties_anytype_3, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + empty_map: typing.Union[MetaOapg.properties.empty_map, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_with_undeclared_properties_string: typing.Union[MetaOapg.properties.map_with_undeclared_properties_string, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AdditionalPropertiesClass': + return super().__new__( + cls, + *args, + map_property=map_property, + map_of_map_property=map_of_map_property, + anytype_1=anytype_1, + map_with_undeclared_properties_anytype_1=map_with_undeclared_properties_anytype_1, + map_with_undeclared_properties_anytype_2=map_with_undeclared_properties_anytype_2, + map_with_undeclared_properties_anytype_3=map_with_undeclared_properties_anytype_3, + empty_map=empty_map, + map_with_undeclared_properties_string=map_with_undeclared_properties_string, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_validator.py b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_validator.py new file mode 100644 index 0000000000..e139b25269 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_validator.py @@ -0,0 +1,198 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AdditionalPropertiesValidator( + schemas.ComposedBase, + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.AnyTypeSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + min_length = 3 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_2( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + max_length = 5 + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'all_of_2': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + cls.all_of_2, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AdditionalPropertiesValidator': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_validator.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_validator.pyi new file mode 100644 index 0000000000..aa4a7355b2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_validator.pyi @@ -0,0 +1,196 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AdditionalPropertiesValidator( + schemas.ComposedBase, + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_0( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.AnyTypeSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'all_of_0': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class all_of_2( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'all_of_2': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + cls.all_of_1, + cls.all_of_2, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AdditionalPropertiesValidator': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py index 9b33b4689d..2a0bbc3031 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,259 +9,76 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.enum_class import EnumClass - globals()['EnumClass'] = EnumClass - - -class AdditionalPropertiesWithArrayOfEnums(ModelNormal): +class AdditionalPropertiesWithArrayOfEnums( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + + class additional_properties( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['EnumClass']: + return EnumClass + + def __new__( + cls, + arg: typing.Union[typing.Tuple['EnumClass'], typing.List['EnumClass']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'additional_properties': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'EnumClass': + return super().__getitem__(i) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return ([EnumClass],) # noqa: E501 + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, list, tuple, ], + ) -> 'AdditionalPropertiesWithArrayOfEnums': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """AdditionalPropertiesWithArrayOfEnums - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """AdditionalPropertiesWithArrayOfEnums - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.enum_class import EnumClass diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.pyi new file mode 100644 index 0000000000..2a0bbc3031 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.pyi @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AdditionalPropertiesWithArrayOfEnums( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class additional_properties( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['EnumClass']: + return EnumClass + + def __new__( + cls, + arg: typing.Union[typing.Tuple['EnumClass'], typing.List['EnumClass']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'additional_properties': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'EnumClass': + return super().__getitem__(i) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, list, tuple, ], + ) -> 'AdditionalPropertiesWithArrayOfEnums': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.enum_class import EnumClass diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/address.py b/samples/openapi3/client/petstore/python/petstore_api/model/address.py index 6ab1456724..64fb96cfb9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/address.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/address.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,253 +9,49 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Address(ModelNormal): +class Address( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + additional_properties = schemas.IntSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (int,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Address - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Address - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, decimal.Decimal, int, ], + ) -> 'Address': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/address.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/address.pyi new file mode 100644 index 0000000000..64fb96cfb9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/address.pyi @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Address( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + additional_properties = schemas.IntSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, decimal.Decimal, int, ], + ) -> 'Address': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal.py b/samples/openapi3/client/petstore/python/petstore_api/model/animal.py index b93180ea05..06d7246fa3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,286 +9,97 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.cat import Cat - from petstore_api.model.dog import Dog - globals()['Cat'] = Cat - globals()['Dog'] = Dog - - -class Animal(ModelNormal): +class Animal( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'class_name': (str,), # noqa: E501 - 'color': (str,), # noqa: E501 - 'tail': (bool,), # noqa: E501 + class MetaOapg: + required = { + "className", } + + @staticmethod + def discriminator(): + return { + 'className': { + 'Cat': Cat, + 'Dog': Dog, + } + } + + class properties: + className = schemas.StrSchema + color = schemas.StrSchema + __annotations__ = { + "className": className, + "color": color, + } + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["color"]) -> MetaOapg.properties.color: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className", "color", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["color"]) -> typing.Union[MetaOapg.properties.color, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className", "color", ], str]): + return super().get_item_oapg(name) + - @cached_property - def discriminator(): - lazy_import() - val = { - 'Cat': Cat, - 'Dog': Dog, - } - if not val: - return None - return {'class_name': val} + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + color: typing.Union[MetaOapg.properties.color, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Animal': + return super().__new__( + cls, + *args, + className=className, + color=color, + _configuration=_configuration, + **kwargs, + ) - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'color': 'color', # noqa: E501 - 'tail': 'tail', # noqa: E501 - } - - read_only_vars = { - 'tail', # noqa: E501 - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 - """Animal - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 - tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 - """Animal - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 - tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.cat import Cat +from petstore_api.model.dog import Dog diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/animal.pyi new file mode 100644 index 0000000000..06d7246fa3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal.pyi @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Animal( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "className", + } + + @staticmethod + def discriminator(): + return { + 'className': { + 'Cat': Cat, + 'Dog': Dog, + } + } + + class properties: + className = schemas.StrSchema + color = schemas.StrSchema + __annotations__ = { + "className": className, + "color": color, + } + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["color"]) -> MetaOapg.properties.color: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className", "color", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["color"]) -> typing.Union[MetaOapg.properties.color, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className", "color", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + color: typing.Union[MetaOapg.properties.color, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Animal': + return super().__new__( + cls, + *args, + className=className, + color=color, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.cat import Cat +from petstore_api.model.dog import Dog diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py index 89062cff69..082a4988ce 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,285 +9,48 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.animal import Animal - globals()['Animal'] = Animal - - -class AnimalFarm(ModelSimple): +class AnimalFarm( + schemas.ListSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Animal']: + return Animal - additional_properties_type = None + def __new__( + cls, + arg: typing.Union[typing.Tuple['Animal'], typing.List['Animal']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'AnimalFarm': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) - _nullable = False + def __getitem__(self, i: int) -> 'Animal': + return super().__getitem__(i) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'value': ([Animal],), - } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """AnimalFarm - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] ([Animal]): # noqa: E501 - - Keyword Args: - value ([Animal]): # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """AnimalFarm - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] ([Animal]): # noqa: E501 - - Keyword Args: - value ([Animal]): # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self +from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.pyi new file mode 100644 index 0000000000..082a4988ce --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.pyi @@ -0,0 +1,56 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AnimalFarm( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Animal']: + return Animal + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Animal'], typing.List['Animal']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'AnimalFarm': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Animal': + return super().__getitem__(i) + +from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/any_type_and_format.py b/samples/openapi3/client/petstore/python/petstore_api/model/any_type_and_format.py new file mode 100644 index 0000000000..7bccdfa416 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/any_type_and_format.py @@ -0,0 +1,361 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AnyTypeAndFormat( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class uuid( + schemas.UUIDBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'uuid' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'uuid': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class date( + schemas.DateBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'date' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'date': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class date_time( + schemas.DateTimeBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'date_time': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class number( + schemas.DecimalBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'number' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'number': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class binary( + schemas.BinaryBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'binary' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'binary': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class int32( + schemas.Int32Base, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'int32' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'int32': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class int64( + schemas.Int64Base, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'int64' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'int64': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class double( + schemas.Float64Base, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'double' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'double': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class _float( + schemas.Float32Base, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'float' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> '_float': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "uuid": uuid, + "date": date, + "date-time": date_time, + "number": number, + "binary": binary, + "int32": int32, + "int64": int64, + "double": double, + "float": _float, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["uuid"]) -> MetaOapg.properties.uuid: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date"]) -> MetaOapg.properties.date: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date-time"]) -> MetaOapg.properties.date_time: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["binary"]) -> MetaOapg.properties.binary: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int32"]) -> MetaOapg.properties.int32: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int64"]) -> MetaOapg.properties.int64: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["double"]) -> MetaOapg.properties.double: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float"]) -> MetaOapg.properties._float: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["uuid", "date", "date-time", "number", "binary", "int32", "int64", "double", "float", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["uuid"]) -> typing.Union[MetaOapg.properties.uuid, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date"]) -> typing.Union[MetaOapg.properties.date, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date-time"]) -> typing.Union[MetaOapg.properties.date_time, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["number"]) -> typing.Union[MetaOapg.properties.number, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["binary"]) -> typing.Union[MetaOapg.properties.binary, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int32"]) -> typing.Union[MetaOapg.properties.int32, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int64"]) -> typing.Union[MetaOapg.properties.int64, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["double"]) -> typing.Union[MetaOapg.properties.double, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float"]) -> typing.Union[MetaOapg.properties._float, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["uuid", "date", "date-time", "number", "binary", "int32", "int64", "double", "float", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + uuid: typing.Union[MetaOapg.properties.uuid, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + date: typing.Union[MetaOapg.properties.date, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + number: typing.Union[MetaOapg.properties.number, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + binary: typing.Union[MetaOapg.properties.binary, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + int32: typing.Union[MetaOapg.properties.int32, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + int64: typing.Union[MetaOapg.properties.int64, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + double: typing.Union[MetaOapg.properties.double, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AnyTypeAndFormat': + return super().__new__( + cls, + *args, + uuid=uuid, + date=date, + number=number, + binary=binary, + int32=int32, + int64=int64, + double=double, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/any_type_and_format.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/any_type_and_format.pyi new file mode 100644 index 0000000000..7bccdfa416 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/any_type_and_format.pyi @@ -0,0 +1,361 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AnyTypeAndFormat( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class uuid( + schemas.UUIDBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'uuid' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'uuid': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class date( + schemas.DateBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'date' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'date': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class date_time( + schemas.DateTimeBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'date_time': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class number( + schemas.DecimalBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'number' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'number': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class binary( + schemas.BinaryBase, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'binary' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'binary': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class int32( + schemas.Int32Base, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'int32' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'int32': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class int64( + schemas.Int64Base, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'int64' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'int64': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class double( + schemas.Float64Base, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'double' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'double': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class _float( + schemas.Float32Base, + schemas.AnyTypeSchema, + ): + + + class MetaOapg: + format = 'float' + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> '_float': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "uuid": uuid, + "date": date, + "date-time": date_time, + "number": number, + "binary": binary, + "int32": int32, + "int64": int64, + "double": double, + "float": _float, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["uuid"]) -> MetaOapg.properties.uuid: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date"]) -> MetaOapg.properties.date: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date-time"]) -> MetaOapg.properties.date_time: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["binary"]) -> MetaOapg.properties.binary: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int32"]) -> MetaOapg.properties.int32: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int64"]) -> MetaOapg.properties.int64: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["double"]) -> MetaOapg.properties.double: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float"]) -> MetaOapg.properties._float: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["uuid", "date", "date-time", "number", "binary", "int32", "int64", "double", "float", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["uuid"]) -> typing.Union[MetaOapg.properties.uuid, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date"]) -> typing.Union[MetaOapg.properties.date, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date-time"]) -> typing.Union[MetaOapg.properties.date_time, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["number"]) -> typing.Union[MetaOapg.properties.number, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["binary"]) -> typing.Union[MetaOapg.properties.binary, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int32"]) -> typing.Union[MetaOapg.properties.int32, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int64"]) -> typing.Union[MetaOapg.properties.int64, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["double"]) -> typing.Union[MetaOapg.properties.double, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float"]) -> typing.Union[MetaOapg.properties._float, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["uuid", "date", "date-time", "number", "binary", "int32", "int64", "double", "float", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + uuid: typing.Union[MetaOapg.properties.uuid, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + date: typing.Union[MetaOapg.properties.date, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + number: typing.Union[MetaOapg.properties.number, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + binary: typing.Union[MetaOapg.properties.binary, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + int32: typing.Union[MetaOapg.properties.int32, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + int64: typing.Union[MetaOapg.properties.int64, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + double: typing.Union[MetaOapg.properties.double, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AnyTypeAndFormat': + return super().__new__( + cls, + *args, + uuid=uuid, + date=date, + number=number, + binary=binary, + int32=int32, + int64=int64, + double=double, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/any_type_not_string.py b/samples/openapi3/client/petstore/python/petstore_api/model/any_type_not_string.py new file mode 100644 index 0000000000..993207a77f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/any_type_not_string.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AnyTypeNotString( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + not_schema = schemas.StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AnyTypeNotString': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/any_type_not_string.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/any_type_not_string.pyi new file mode 100644 index 0000000000..993207a77f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/any_type_not_string.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AnyTypeNotString( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + not_schema = schemas.StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'AnyTypeNotString': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py index 5e21cdaf59..236e29d4e7 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,265 +9,90 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class ApiResponse(ModelNormal): +class ApiResponse( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + code = schemas.Int32Schema + type = schemas.StrSchema + message = schemas.StrSchema + __annotations__ = { + "code": code, + "type": type, + "message": message, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["code"]) -> MetaOapg.properties.code: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["type"]) -> MetaOapg.properties.type: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["message"]) -> MetaOapg.properties.message: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["code", "type", "message", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["code"]) -> typing.Union[MetaOapg.properties.code, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["type"]) -> typing.Union[MetaOapg.properties.type, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["message"]) -> typing.Union[MetaOapg.properties.message, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["code", "type", "message", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'code': (int,), # noqa: E501 - 'type': (str,), # noqa: E501 - 'message': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'code': 'code', # noqa: E501 - 'type': 'type', # noqa: E501 - 'message': 'message', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ApiResponse - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - code (int): [optional] # noqa: E501 - type (str): [optional] # noqa: E501 - message (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ApiResponse - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - code (int): [optional] # noqa: E501 - type (str): [optional] # noqa: E501 - message (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + code: typing.Union[MetaOapg.properties.code, decimal.Decimal, int, schemas.Unset] = schemas.unset, + type: typing.Union[MetaOapg.properties.type, str, schemas.Unset] = schemas.unset, + message: typing.Union[MetaOapg.properties.message, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ApiResponse': + return super().__new__( + cls, + *args, + code=code, + type=type, + message=message, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/api_response.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.pyi new file mode 100644 index 0000000000..236e29d4e7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.pyi @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ApiResponse( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + code = schemas.Int32Schema + type = schemas.StrSchema + message = schemas.StrSchema + __annotations__ = { + "code": code, + "type": type, + "message": message, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["code"]) -> MetaOapg.properties.code: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["type"]) -> MetaOapg.properties.type: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["message"]) -> MetaOapg.properties.message: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["code", "type", "message", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["code"]) -> typing.Union[MetaOapg.properties.code, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["type"]) -> typing.Union[MetaOapg.properties.type, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["message"]) -> typing.Union[MetaOapg.properties.message, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["code", "type", "message", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + code: typing.Union[MetaOapg.properties.code, decimal.Decimal, int, schemas.Unset] = schemas.unset, + type: typing.Union[MetaOapg.properties.type, str, schemas.Unset] = schemas.unset, + message: typing.Union[MetaOapg.properties.message, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ApiResponse': + return super().__new__( + cls, + *args, + code=code, + type=type, + message=message, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple.py b/samples/openapi3/client/petstore/python/petstore_api/model/apple.py index 9909e1994a..638edc274d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/apple.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,278 +9,110 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Apple(ModelNormal): +class Apple( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - ('cultivar',): { - 'regex': { - 'pattern': r'^[a-zA-Z\s]*$', # noqa: E501 - }, - }, - ('origin',): { - 'regex': { - 'pattern': r'^[A-Z\s]*$', # noqa: E501 - 'flags': (re.IGNORECASE) - }, - }, - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = True - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'cultivar': (str,), # noqa: E501 - 'origin': (str,), # noqa: E501 + class MetaOapg: + required = { + "cultivar", } + + class properties: + + + class cultivar( + schemas.StrSchema + ): + + + class MetaOapg: + regex=[{ + 'pattern': r'^[a-zA-Z\s]*$', # noqa: E501 + }] + + + class origin( + schemas.StrSchema + ): + + + class MetaOapg: + regex=[{ + 'pattern': r'^[A-Z\s]*$', # noqa: E501 + 'flags': ( + re.IGNORECASE + ) + }] + __annotations__ = { + "cultivar": cultivar, + "origin": origin, + } - @cached_property - def discriminator(): - return None + + cultivar: MetaOapg.properties.cultivar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["cultivar"]) -> MetaOapg.properties.cultivar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["origin"]) -> MetaOapg.properties.origin: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["cultivar", "origin", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["cultivar"]) -> MetaOapg.properties.cultivar: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["origin"]) -> typing.Union[MetaOapg.properties.origin, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["cultivar", "origin", ], str]): + return super().get_item_oapg(name) + - - attribute_map = { - 'cultivar': 'cultivar', # noqa: E501 - 'origin': 'origin', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, cultivar, *args, **kwargs): # noqa: E501 - """Apple - a model defined in OpenAPI - - Args: - cultivar (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - origin (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.cultivar = cultivar - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, cultivar, *args, **kwargs): # noqa: E501 - """Apple - a model defined in OpenAPI - - Args: - cultivar (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - origin (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.cultivar = cultivar - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + origin: typing.Union[MetaOapg.properties.origin, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Apple': + return super().__new__( + cls, + *args, + origin=origin, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/apple.pyi new file mode 100644 index 0000000000..95bd5e3a90 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple.pyi @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Apple( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "cultivar", + } + + class properties: + + + class cultivar( + schemas.StrSchema + ): + pass + + + class origin( + schemas.StrSchema + ): + pass + __annotations__ = { + "cultivar": cultivar, + "origin": origin, + } + + + cultivar: MetaOapg.properties.cultivar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["cultivar"]) -> MetaOapg.properties.cultivar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["origin"]) -> MetaOapg.properties.origin: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["cultivar", "origin", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["cultivar"]) -> MetaOapg.properties.cultivar: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["origin"]) -> typing.Union[MetaOapg.properties.origin, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["cultivar", "origin", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + origin: typing.Union[MetaOapg.properties.origin, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Apple': + return super().__new__( + cls, + *args, + origin=origin, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py index ce9ae6721e..03d83c22cf 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,261 +9,76 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class AppleReq(ModelNormal): +class AppleReq( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - additional_properties_type = None - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'cultivar': (str,), # noqa: E501 - 'mealy': (bool,), # noqa: E501 + class MetaOapg: + required = { + "cultivar", } + + class properties: + cultivar = schemas.StrSchema + mealy = schemas.BoolSchema + __annotations__ = { + "cultivar": cultivar, + "mealy": mealy, + } + additional_properties = schemas.NotAnyTypeSchema + + cultivar: MetaOapg.properties.cultivar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["cultivar"]) -> MetaOapg.properties.cultivar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["mealy"]) -> MetaOapg.properties.mealy: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["cultivar"], typing_extensions.Literal["mealy"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["cultivar"]) -> MetaOapg.properties.cultivar: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["mealy"]) -> typing.Union[MetaOapg.properties.mealy, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["cultivar"], typing_extensions.Literal["mealy"], ]): + return super().get_item_oapg(name) - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'cultivar': 'cultivar', # noqa: E501 - 'mealy': 'mealy', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, cultivar, *args, **kwargs): # noqa: E501 - """AppleReq - a model defined in OpenAPI - - Args: - cultivar (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - mealy (bool): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.cultivar = cultivar - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, cultivar, *args, **kwargs): # noqa: E501 - """AppleReq - a model defined in OpenAPI - - Args: - cultivar (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - mealy (bool): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.cultivar = cultivar - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + cultivar: typing.Union[MetaOapg.properties.cultivar, str, ], + mealy: typing.Union[MetaOapg.properties.mealy, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'AppleReq': + return super().__new__( + cls, + *args, + cultivar=cultivar, + mealy=mealy, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.pyi new file mode 100644 index 0000000000..03d83c22cf --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.pyi @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class AppleReq( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "cultivar", + } + + class properties: + cultivar = schemas.StrSchema + mealy = schemas.BoolSchema + __annotations__ = { + "cultivar": cultivar, + "mealy": mealy, + } + additional_properties = schemas.NotAnyTypeSchema + + cultivar: MetaOapg.properties.cultivar + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["cultivar"]) -> MetaOapg.properties.cultivar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["mealy"]) -> MetaOapg.properties.mealy: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["cultivar"], typing_extensions.Literal["mealy"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["cultivar"]) -> MetaOapg.properties.cultivar: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["mealy"]) -> typing.Union[MetaOapg.properties.mealy, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["cultivar"], typing_extensions.Literal["mealy"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + cultivar: typing.Union[MetaOapg.properties.cultivar, str, ], + mealy: typing.Union[MetaOapg.properties.mealy, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'AppleReq': + return super().__new__( + cls, + *args, + cultivar=cultivar, + mealy=mealy, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_holding_any_type.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_holding_any_type.py new file mode 100644 index 0000000000..19b1c0e1a6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_holding_any_type.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ArrayHoldingAnyType( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayHoldingAnyType': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_holding_any_type.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/array_holding_any_type.pyi new file mode 100644 index 0000000000..19b1c0e1a6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_holding_any_type.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ArrayHoldingAnyType( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayHoldingAnyType': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py index 41e90e2ae9..5237741d83 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,114 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class ArrayOfArrayOfNumberOnly(ModelNormal): +class ArrayOfArrayOfNumberOnly( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'array_array_number': ([[float]],), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'array_array_number': 'ArrayArrayNumber', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - array_array_number ([[float]]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + + class ArrayArrayNumber( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.NumberSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayArrayNumber': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "ArrayArrayNumber": ArrayArrayNumber, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["ArrayArrayNumber"]) -> MetaOapg.properties.ArrayArrayNumber: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["ArrayArrayNumber", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["ArrayArrayNumber"]) -> typing.Union[MetaOapg.properties.ArrayArrayNumber, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["ArrayArrayNumber", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - array_array_number ([[float]]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + ArrayArrayNumber: typing.Union[MetaOapg.properties.ArrayArrayNumber, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ArrayOfArrayOfNumberOnly': + return super().__new__( + cls, + *args, + ArrayArrayNumber=ArrayArrayNumber, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.pyi new file mode 100644 index 0000000000..5237741d83 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.pyi @@ -0,0 +1,122 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ArrayOfArrayOfNumberOnly( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class ArrayArrayNumber( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.NumberSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayArrayNumber': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "ArrayArrayNumber": ArrayArrayNumber, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["ArrayArrayNumber"]) -> MetaOapg.properties.ArrayArrayNumber: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["ArrayArrayNumber", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["ArrayArrayNumber"]) -> typing.Union[MetaOapg.properties.ArrayArrayNumber, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["ArrayArrayNumber", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + ArrayArrayNumber: typing.Union[MetaOapg.properties.ArrayArrayNumber, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ArrayOfArrayOfNumberOnly': + return super().__new__( + cls, + *args, + ArrayArrayNumber=ArrayArrayNumber, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py index 8ca15fd6c8..d7eb9d4838 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,285 +9,48 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.string_enum import StringEnum - globals()['StringEnum'] = StringEnum - - -class ArrayOfEnums(ModelSimple): +class ArrayOfEnums( + schemas.ListSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + @staticmethod + def items() -> typing.Type['StringEnum']: + return StringEnum - additional_properties_type = None + def __new__( + cls, + arg: typing.Union[typing.Tuple['StringEnum'], typing.List['StringEnum']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayOfEnums': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) - _nullable = False + def __getitem__(self, i: int) -> 'StringEnum': + return super().__getitem__(i) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'value': ([StringEnum],), - } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """ArrayOfEnums - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] ([StringEnum]): # noqa: E501 - - Keyword Args: - value ([StringEnum]): # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """ArrayOfEnums - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] ([StringEnum]): # noqa: E501 - - Keyword Args: - value ([StringEnum]): # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self +from petstore_api.model.string_enum import StringEnum diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.pyi new file mode 100644 index 0000000000..d7eb9d4838 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.pyi @@ -0,0 +1,56 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ArrayOfEnums( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['StringEnum']: + return StringEnum + + def __new__( + cls, + arg: typing.Union[typing.Tuple['StringEnum'], typing.List['StringEnum']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayOfEnums': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'StringEnum': + return super().__getitem__(i) + +from petstore_api.model.string_enum import StringEnum diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py index 068dc80b1a..9c5a9b55d2 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,92 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class ArrayOfNumberOnly(ModelNormal): +class ArrayOfNumberOnly( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'array_number': ([float],), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'array_number': 'ArrayNumber', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ArrayOfNumberOnly - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - array_number ([float]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + + class ArrayNumber( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.NumberSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayNumber': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "ArrayNumber": ArrayNumber, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["ArrayNumber"]) -> MetaOapg.properties.ArrayNumber: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["ArrayNumber", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["ArrayNumber"]) -> typing.Union[MetaOapg.properties.ArrayNumber, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["ArrayNumber", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ArrayOfNumberOnly - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - array_number ([float]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + ArrayNumber: typing.Union[MetaOapg.properties.ArrayNumber, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ArrayOfNumberOnly': + return super().__new__( + cls, + *args, + ArrayNumber=ArrayNumber, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.pyi new file mode 100644 index 0000000000..9c5a9b55d2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.pyi @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ArrayOfNumberOnly( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class ArrayNumber( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.NumberSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayNumber': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "ArrayNumber": ArrayNumber, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["ArrayNumber"]) -> MetaOapg.properties.ArrayNumber: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["ArrayNumber", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["ArrayNumber"]) -> typing.Union[MetaOapg.properties.ArrayNumber, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["ArrayNumber", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + ArrayNumber: typing.Union[MetaOapg.properties.ArrayNumber, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ArrayOfNumberOnly': + return super().__new__( + cls, + *args, + ArrayNumber=ArrayNumber, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py index 119a5ad1fd..d53b0df62d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,271 +9,205 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.read_only_first import ReadOnlyFirst - globals()['ReadOnlyFirst'] = ReadOnlyFirst - - -class ArrayTest(ModelNormal): +class ArrayTest( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'array_of_string': ([str],), # noqa: E501 - 'array_array_of_integer': ([[int]],), # noqa: E501 - 'array_array_of_model': ([[ReadOnlyFirst]],), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'array_of_string': 'array_of_string', # noqa: E501 - 'array_array_of_integer': 'array_array_of_integer', # noqa: E501 - 'array_array_of_model': 'array_array_of_model', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ArrayTest - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - array_of_string ([str]): [optional] # noqa: E501 - array_array_of_integer ([[int]]): [optional] # noqa: E501 - array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + + class array_of_string( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_of_string': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ArrayTest - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - array_of_string ([str]): [optional] # noqa: E501 - array_array_of_integer ([[int]]): [optional] # noqa: E501 - array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class array_array_of_integer( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.Int64Schema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_array_of_integer': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class array_array_of_model( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['ReadOnlyFirst']: + return ReadOnlyFirst + + def __new__( + cls, + arg: typing.Union[typing.Tuple['ReadOnlyFirst'], typing.List['ReadOnlyFirst']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'ReadOnlyFirst': + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_array_of_model': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "array_of_string": array_of_string, + "array_array_of_integer": array_array_of_integer, + "array_array_of_model": array_array_of_model, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_of_string"]) -> MetaOapg.properties.array_of_string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_array_of_integer"]) -> MetaOapg.properties.array_array_of_integer: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_array_of_model"]) -> MetaOapg.properties.array_array_of_model: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["array_of_string", "array_array_of_integer", "array_array_of_model", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_of_string"]) -> typing.Union[MetaOapg.properties.array_of_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_array_of_integer"]) -> typing.Union[MetaOapg.properties.array_array_of_integer, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_array_of_model"]) -> typing.Union[MetaOapg.properties.array_array_of_model, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["array_of_string", "array_array_of_integer", "array_array_of_model", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + array_of_string: typing.Union[MetaOapg.properties.array_of_string, list, tuple, schemas.Unset] = schemas.unset, + array_array_of_integer: typing.Union[MetaOapg.properties.array_array_of_integer, list, tuple, schemas.Unset] = schemas.unset, + array_array_of_model: typing.Union[MetaOapg.properties.array_array_of_model, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ArrayTest': + return super().__new__( + cls, + *args, + array_of_string=array_of_string, + array_array_of_integer=array_array_of_integer, + array_array_of_model=array_array_of_model, + _configuration=_configuration, + **kwargs, + ) - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.read_only_first import ReadOnlyFirst diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_test.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.pyi new file mode 100644 index 0000000000..d53b0df62d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.pyi @@ -0,0 +1,213 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ArrayTest( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class array_of_string( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_of_string': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class array_array_of_integer( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.Int64Schema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_array_of_integer': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class array_array_of_model( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['ReadOnlyFirst']: + return ReadOnlyFirst + + def __new__( + cls, + arg: typing.Union[typing.Tuple['ReadOnlyFirst'], typing.List['ReadOnlyFirst']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'items': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'ReadOnlyFirst': + return super().__getitem__(i) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, list, tuple, ]], typing.List[typing.Union[MetaOapg.items, list, tuple, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_array_of_model': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "array_of_string": array_of_string, + "array_array_of_integer": array_array_of_integer, + "array_array_of_model": array_array_of_model, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_of_string"]) -> MetaOapg.properties.array_of_string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_array_of_integer"]) -> MetaOapg.properties.array_array_of_integer: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_array_of_model"]) -> MetaOapg.properties.array_array_of_model: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["array_of_string", "array_array_of_integer", "array_array_of_model", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_of_string"]) -> typing.Union[MetaOapg.properties.array_of_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_array_of_integer"]) -> typing.Union[MetaOapg.properties.array_array_of_integer, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_array_of_model"]) -> typing.Union[MetaOapg.properties.array_array_of_model, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["array_of_string", "array_array_of_integer", "array_array_of_model", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + array_of_string: typing.Union[MetaOapg.properties.array_of_string, list, tuple, schemas.Unset] = schemas.unset, + array_array_of_integer: typing.Union[MetaOapg.properties.array_array_of_integer, list, tuple, schemas.Unset] = schemas.unset, + array_array_of_model: typing.Union[MetaOapg.properties.array_array_of_model, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ArrayTest': + return super().__new__( + cls, + *args, + array_of_string=array_of_string, + array_array_of_integer=array_array_of_integer, + array_array_of_model=array_array_of_model, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.read_only_first import ReadOnlyFirst diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_with_validations_in_items.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_with_validations_in_items.py new file mode 100644 index 0000000000..f68cb1a4c2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_with_validations_in_items.py @@ -0,0 +1,61 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ArrayWithValidationsInItems( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + max_items = 2 + + + class items( + schemas.Int64Schema + ): + + + class MetaOapg: + format = 'int64' + inclusive_maximum = 7 + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayWithValidationsInItems': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_with_validations_in_items.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/array_with_validations_in_items.pyi new file mode 100644 index 0000000000..2f1d07e328 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_with_validations_in_items.pyi @@ -0,0 +1,56 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ArrayWithValidationsInItems( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class items( + schemas.Int64Schema + ): + pass + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ArrayWithValidationsInItems': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana.py b/samples/openapi3/client/petstore/python/petstore_api/model/banana.py index f6f6792990..b3d1c7d792 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/banana.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,263 +9,75 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Banana(ModelNormal): +class Banana( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'length_cm': (float,), # noqa: E501 + class MetaOapg: + required = { + "lengthCm", } + + class properties: + lengthCm = schemas.NumberSchema + __annotations__ = { + "lengthCm": lengthCm, + } + + lengthCm: MetaOapg.properties.lengthCm + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["lengthCm"]) -> MetaOapg.properties.lengthCm: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["lengthCm", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["lengthCm"]) -> MetaOapg.properties.lengthCm: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["lengthCm", ], str]): + return super().get_item_oapg(name) + - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'length_cm': 'lengthCm', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, length_cm, *args, **kwargs): # noqa: E501 - """Banana - a model defined in OpenAPI - - Args: - length_cm (float): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.length_cm = length_cm - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, length_cm, *args, **kwargs): # noqa: E501 - """Banana - a model defined in OpenAPI - - Args: - length_cm (float): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.length_cm = length_cm - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + lengthCm: typing.Union[MetaOapg.properties.lengthCm, decimal.Decimal, int, float, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Banana': + return super().__new__( + cls, + *args, + lengthCm=lengthCm, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/banana.pyi new file mode 100644 index 0000000000..b3d1c7d792 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana.pyi @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Banana( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "lengthCm", + } + + class properties: + lengthCm = schemas.NumberSchema + __annotations__ = { + "lengthCm": lengthCm, + } + + lengthCm: MetaOapg.properties.lengthCm + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["lengthCm"]) -> MetaOapg.properties.lengthCm: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["lengthCm", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["lengthCm"]) -> MetaOapg.properties.lengthCm: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["lengthCm", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + lengthCm: typing.Union[MetaOapg.properties.lengthCm, decimal.Decimal, int, float, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Banana': + return super().__new__( + cls, + *args, + lengthCm=lengthCm, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py index 1e6d97d134..1fdfa7d34a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,261 +9,76 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class BananaReq(ModelNormal): +class BananaReq( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - additional_properties_type = None - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'length_cm': (float,), # noqa: E501 - 'sweet': (bool,), # noqa: E501 + class MetaOapg: + required = { + "lengthCm", } + + class properties: + lengthCm = schemas.NumberSchema + sweet = schemas.BoolSchema + __annotations__ = { + "lengthCm": lengthCm, + "sweet": sweet, + } + additional_properties = schemas.NotAnyTypeSchema + + lengthCm: MetaOapg.properties.lengthCm + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["lengthCm"]) -> MetaOapg.properties.lengthCm: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["sweet"]) -> MetaOapg.properties.sweet: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["lengthCm"], typing_extensions.Literal["sweet"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["lengthCm"]) -> MetaOapg.properties.lengthCm: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["sweet"]) -> typing.Union[MetaOapg.properties.sweet, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["lengthCm"], typing_extensions.Literal["sweet"], ]): + return super().get_item_oapg(name) - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'length_cm': 'lengthCm', # noqa: E501 - 'sweet': 'sweet', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, length_cm, *args, **kwargs): # noqa: E501 - """BananaReq - a model defined in OpenAPI - - Args: - length_cm (float): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - sweet (bool): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.length_cm = length_cm - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, length_cm, *args, **kwargs): # noqa: E501 - """BananaReq - a model defined in OpenAPI - - Args: - length_cm (float): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - sweet (bool): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.length_cm = length_cm - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + lengthCm: typing.Union[MetaOapg.properties.lengthCm, decimal.Decimal, int, float, ], + sweet: typing.Union[MetaOapg.properties.sweet, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'BananaReq': + return super().__new__( + cls, + *args, + lengthCm=lengthCm, + sweet=sweet, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.pyi new file mode 100644 index 0000000000..1fdfa7d34a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.pyi @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class BananaReq( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "lengthCm", + } + + class properties: + lengthCm = schemas.NumberSchema + sweet = schemas.BoolSchema + __annotations__ = { + "lengthCm": lengthCm, + "sweet": sweet, + } + additional_properties = schemas.NotAnyTypeSchema + + lengthCm: MetaOapg.properties.lengthCm + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["lengthCm"]) -> MetaOapg.properties.lengthCm: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["sweet"]) -> MetaOapg.properties.sweet: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["lengthCm"], typing_extensions.Literal["sweet"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["lengthCm"]) -> MetaOapg.properties.lengthCm: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["sweet"]) -> typing.Union[MetaOapg.properties.sweet, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["lengthCm"], typing_extensions.Literal["sweet"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + lengthCm: typing.Union[MetaOapg.properties.lengthCm, decimal.Decimal, int, float, ], + sweet: typing.Union[MetaOapg.properties.sweet, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'BananaReq': + return super().__new__( + cls, + *args, + lengthCm=lengthCm, + sweet=sweet, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/bar.py b/samples/openapi3/client/petstore/python/petstore_api/model/bar.py new file mode 100644 index 0000000000..d100ad83c5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/bar.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +Bar = schemas.StrSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/bar.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/bar.pyi new file mode 100644 index 0000000000..d100ad83c5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/bar.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +Bar = schemas.StrSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py index 456066d2ce..528cfa498b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,263 +9,90 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class BasquePig(ModelNormal): +class BasquePig( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'class_name': (str,), # noqa: E501 + class MetaOapg: + required = { + "className", } + + class properties: + + + class className( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "BasquePig": "BASQUE_PIG", + } + + @schemas.classproperty + def BASQUE_PIG(cls): + return cls("BasquePig") + __annotations__ = { + "className": className, + } + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className", ], str]): + return super().get_item_oapg(name) + - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'class_name': 'className', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 - """BasquePig - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 - """BasquePig - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'BasquePig': + return super().__new__( + cls, + *args, + className=className, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.pyi new file mode 100644 index 0000000000..8b36451f84 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.pyi @@ -0,0 +1,92 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class BasquePig( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "className", + } + + class properties: + + + class className( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def BASQUE_PIG(cls): + return cls("BasquePig") + __annotations__ = { + "className": className, + } + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'BasquePig': + return super().__new__( + cls, + *args, + className=className, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/boolean.py b/samples/openapi3/client/petstore/python/petstore_api/model/boolean.py new file mode 100644 index 0000000000..6f667d4c0b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/boolean.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +Boolean = schemas.BoolSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/boolean.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/boolean.pyi new file mode 100644 index 0000000000..6f667d4c0b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/boolean.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +Boolean = schemas.BoolSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.py index e4002fb8f6..66d5be7131 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,275 +9,36 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class BooleanEnum(ModelSimple): +class BooleanEnum( + schemas.EnumBase, + schemas.BoolSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('value',): { - 'TRUE': True, - }, - } - validations = { - } - - additional_properties_type = None - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (bool,), + class MetaOapg: + enum_value_to_name = { + schemas.BoolClass.TRUE: "TRUE", } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """BooleanEnum - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (bool): if omitted defaults to True, must be one of [True, ] # noqa: E501 - - Keyword Args: - value (bool): if omitted defaults to True, must be one of [True, ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = True - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """BooleanEnum - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (bool): if omitted defaults to True, must be one of [True, ] # noqa: E501 - - Keyword Args: - value (bool): if omitted defaults to True, must be one of [True, ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = True - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self + + @schemas.classproperty + def TRUE(cls): + return cls(True) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.pyi new file mode 100644 index 0000000000..69fe2e6af4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.pyi @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class BooleanEnum( + schemas.EnumBase, + schemas.BoolSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def TRUE(cls): + return cls(True) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py index d57e30d2c8..3dc195865d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,277 +9,120 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Capitalization(ModelNormal): +class Capitalization( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + smallCamel = schemas.StrSchema + CapitalCamel = schemas.StrSchema + small_Snake = schemas.StrSchema + Capital_Snake = schemas.StrSchema + SCA_ETH_Flow_Points = schemas.StrSchema + ATT_NAME = schemas.StrSchema + __annotations__ = { + "smallCamel": smallCamel, + "CapitalCamel": CapitalCamel, + "small_Snake": small_Snake, + "Capital_Snake": Capital_Snake, + "SCA_ETH_Flow_Points": SCA_ETH_Flow_Points, + "ATT_NAME": ATT_NAME, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["smallCamel"]) -> MetaOapg.properties.smallCamel: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["CapitalCamel"]) -> MetaOapg.properties.CapitalCamel: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["small_Snake"]) -> MetaOapg.properties.small_Snake: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["Capital_Snake"]) -> MetaOapg.properties.Capital_Snake: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["SCA_ETH_Flow_Points"]) -> MetaOapg.properties.SCA_ETH_Flow_Points: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["ATT_NAME"]) -> MetaOapg.properties.ATT_NAME: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["smallCamel", "CapitalCamel", "small_Snake", "Capital_Snake", "SCA_ETH_Flow_Points", "ATT_NAME", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["smallCamel"]) -> typing.Union[MetaOapg.properties.smallCamel, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["CapitalCamel"]) -> typing.Union[MetaOapg.properties.CapitalCamel, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["small_Snake"]) -> typing.Union[MetaOapg.properties.small_Snake, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["Capital_Snake"]) -> typing.Union[MetaOapg.properties.Capital_Snake, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["SCA_ETH_Flow_Points"]) -> typing.Union[MetaOapg.properties.SCA_ETH_Flow_Points, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["ATT_NAME"]) -> typing.Union[MetaOapg.properties.ATT_NAME, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["smallCamel", "CapitalCamel", "small_Snake", "Capital_Snake", "SCA_ETH_Flow_Points", "ATT_NAME", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'small_camel': (str,), # noqa: E501 - 'capital_camel': (str,), # noqa: E501 - 'small_snake': (str,), # noqa: E501 - 'capital_snake': (str,), # noqa: E501 - 'sca_eth_flow_points': (str,), # noqa: E501 - 'att_name': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'small_camel': 'smallCamel', # noqa: E501 - 'capital_camel': 'CapitalCamel', # noqa: E501 - 'small_snake': 'small_Snake', # noqa: E501 - 'capital_snake': 'Capital_Snake', # noqa: E501 - 'sca_eth_flow_points': 'SCA_ETH_Flow_Points', # noqa: E501 - 'att_name': 'ATT_NAME', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Capitalization - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - small_camel (str): [optional] # noqa: E501 - capital_camel (str): [optional] # noqa: E501 - small_snake (str): [optional] # noqa: E501 - capital_snake (str): [optional] # noqa: E501 - sca_eth_flow_points (str): [optional] # noqa: E501 - att_name (str): Name of the pet . [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Capitalization - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - small_camel (str): [optional] # noqa: E501 - capital_camel (str): [optional] # noqa: E501 - small_snake (str): [optional] # noqa: E501 - capital_snake (str): [optional] # noqa: E501 - sca_eth_flow_points (str): [optional] # noqa: E501 - att_name (str): Name of the pet . [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + smallCamel: typing.Union[MetaOapg.properties.smallCamel, str, schemas.Unset] = schemas.unset, + CapitalCamel: typing.Union[MetaOapg.properties.CapitalCamel, str, schemas.Unset] = schemas.unset, + small_Snake: typing.Union[MetaOapg.properties.small_Snake, str, schemas.Unset] = schemas.unset, + Capital_Snake: typing.Union[MetaOapg.properties.Capital_Snake, str, schemas.Unset] = schemas.unset, + SCA_ETH_Flow_Points: typing.Union[MetaOapg.properties.SCA_ETH_Flow_Points, str, schemas.Unset] = schemas.unset, + ATT_NAME: typing.Union[MetaOapg.properties.ATT_NAME, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Capitalization': + return super().__new__( + cls, + *args, + smallCamel=smallCamel, + CapitalCamel=CapitalCamel, + small_Snake=small_Snake, + Capital_Snake=Capital_Snake, + SCA_ETH_Flow_Points=SCA_ETH_Flow_Points, + ATT_NAME=ATT_NAME, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.pyi new file mode 100644 index 0000000000..3dc195865d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.pyi @@ -0,0 +1,128 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Capitalization( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + smallCamel = schemas.StrSchema + CapitalCamel = schemas.StrSchema + small_Snake = schemas.StrSchema + Capital_Snake = schemas.StrSchema + SCA_ETH_Flow_Points = schemas.StrSchema + ATT_NAME = schemas.StrSchema + __annotations__ = { + "smallCamel": smallCamel, + "CapitalCamel": CapitalCamel, + "small_Snake": small_Snake, + "Capital_Snake": Capital_Snake, + "SCA_ETH_Flow_Points": SCA_ETH_Flow_Points, + "ATT_NAME": ATT_NAME, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["smallCamel"]) -> MetaOapg.properties.smallCamel: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["CapitalCamel"]) -> MetaOapg.properties.CapitalCamel: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["small_Snake"]) -> MetaOapg.properties.small_Snake: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["Capital_Snake"]) -> MetaOapg.properties.Capital_Snake: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["SCA_ETH_Flow_Points"]) -> MetaOapg.properties.SCA_ETH_Flow_Points: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["ATT_NAME"]) -> MetaOapg.properties.ATT_NAME: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["smallCamel", "CapitalCamel", "small_Snake", "Capital_Snake", "SCA_ETH_Flow_Points", "ATT_NAME", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["smallCamel"]) -> typing.Union[MetaOapg.properties.smallCamel, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["CapitalCamel"]) -> typing.Union[MetaOapg.properties.CapitalCamel, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["small_Snake"]) -> typing.Union[MetaOapg.properties.small_Snake, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["Capital_Snake"]) -> typing.Union[MetaOapg.properties.Capital_Snake, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["SCA_ETH_Flow_Points"]) -> typing.Union[MetaOapg.properties.SCA_ETH_Flow_Points, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["ATT_NAME"]) -> typing.Union[MetaOapg.properties.ATT_NAME, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["smallCamel", "CapitalCamel", "small_Snake", "Capital_Snake", "SCA_ETH_Flow_Points", "ATT_NAME", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + smallCamel: typing.Union[MetaOapg.properties.smallCamel, str, schemas.Unset] = schemas.unset, + CapitalCamel: typing.Union[MetaOapg.properties.CapitalCamel, str, schemas.Unset] = schemas.unset, + small_Snake: typing.Union[MetaOapg.properties.small_Snake, str, schemas.Unset] = schemas.unset, + Capital_Snake: typing.Union[MetaOapg.properties.Capital_Snake, str, schemas.Unset] = schemas.unset, + SCA_ETH_Flow_Points: typing.Union[MetaOapg.properties.SCA_ETH_Flow_Points, str, schemas.Unset] = schemas.unset, + ATT_NAME: typing.Union[MetaOapg.properties.ATT_NAME, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Capitalization': + return super().__new__( + cls, + *args, + smallCamel=smallCamel, + CapitalCamel=CapitalCamel, + small_Snake=small_Snake, + Capital_Snake=Capital_Snake, + SCA_ETH_Flow_Points=SCA_ETH_Flow_Points, + ATT_NAME=ATT_NAME, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/cat.py b/samples/openapi3/client/petstore/python/petstore_api/model/cat.py index 04a16c4911..da07def367 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/cat.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,332 +9,109 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.animal import Animal - from petstore_api.model.cat_all_of import CatAllOf - globals()['Animal'] = Animal - globals()['CatAllOf'] = CatAllOf - - -class Cat(ModelComposed): +class Cat( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + declawed = schemas.BoolSchema + __annotations__ = { + "declawed": declawed, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["declawed"]) -> MetaOapg.properties.declawed: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["declawed", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["declawed"]) -> typing.Union[MetaOapg.properties.declawed, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["declawed", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + declawed: typing.Union[MetaOapg.properties.declawed, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + declawed=declawed, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Animal, + cls.all_of_1, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Cat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'class_name': (str,), # noqa: E501 - 'declawed': (bool,), # noqa: E501 - 'color': (str,), # noqa: E501 - 'tail': (bool,), # noqa: E501 - } - - @cached_property - def discriminator(): - val = { - } - if not val: - return None - return {'class_name': val} - - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'declawed': 'declawed', # noqa: E501 - 'color': 'color', # noqa: E501 - 'tail': 'tail', # noqa: E501 - } - - read_only_vars = { - 'tail', # noqa: E501 - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Cat - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - declawed (bool): [optional] # noqa: E501 - color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 - tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Cat - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - declawed (bool): [optional] # noqa: E501 - color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 - tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - Animal, - CatAllOf, - ], - 'oneOf': [ - ], - } +from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/cat.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/cat.pyi new file mode 100644 index 0000000000..da07def367 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/cat.pyi @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Cat( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + declawed = schemas.BoolSchema + __annotations__ = { + "declawed": declawed, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["declawed"]) -> MetaOapg.properties.declawed: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["declawed", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["declawed"]) -> typing.Union[MetaOapg.properties.declawed, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["declawed", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + declawed: typing.Union[MetaOapg.properties.declawed, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + declawed=declawed, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Animal, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Cat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/category.py b/samples/openapi3/client/petstore/python/petstore_api/model/category.py index 21fb7bd65b..5537a4437b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/category.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/category.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,269 +9,85 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Category(ModelNormal): +class Category( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'name': (str,), # noqa: E501 - 'id': (int,), # noqa: E501 + class MetaOapg: + required = { + "name", } + + class properties: + name = schemas.StrSchema + id = schemas.Int64Schema + __annotations__ = { + "name": name, + "id": id, + } + + name: MetaOapg.properties.name + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "id", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "id", ], str]): + return super().get_item_oapg(name) + - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'name': 'name', # noqa: E501 - 'id': 'id', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Category - a model defined in OpenAPI - - Args: - - Keyword Args: - name (str): defaults to "default-name" # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - """ - - name = kwargs.get('name', "default-name") - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Category - a model defined in OpenAPI - - Args: - - Keyword Args: - name (str): defaults to "default-name" # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - """ - - name = kwargs.get('name', "default-name") - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + name: typing.Union[MetaOapg.properties.name, str, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Category': + return super().__new__( + cls, + *args, + name=name, + id=id, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/category.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/category.pyi new file mode 100644 index 0000000000..5537a4437b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/category.pyi @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Category( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "name", + } + + class properties: + name = schemas.StrSchema + id = schemas.Int64Schema + __annotations__ = { + "name": name, + "id": id, + } + + name: MetaOapg.properties.name + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "id", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "id", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + name: typing.Union[MetaOapg.properties.name, str, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Category': + return super().__new__( + cls, + *args, + name=name, + id=id, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py index 6d971fd192..32db862b8a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,323 +9,109 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.child_cat_all_of import ChildCatAllOf - from petstore_api.model.parent_pet import ParentPet - globals()['ChildCatAllOf'] = ChildCatAllOf - globals()['ParentPet'] = ParentPet - - -class ChildCat(ModelComposed): +class ChildCat( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + name = schemas.StrSchema + __annotations__ = { + "name": name, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + name: typing.Union[MetaOapg.properties.name, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + name=name, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + ParentPet, + cls.all_of_1, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ChildCat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'pet_type': (str,), # noqa: E501 - 'name': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - val = { - } - if not val: - return None - return {'pet_type': val} - - attribute_map = { - 'pet_type': 'pet_type', # noqa: E501 - 'name': 'name', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ChildCat - a model defined in OpenAPI - - Keyword Args: - pet_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - name (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ChildCat - a model defined in OpenAPI - - Keyword Args: - pet_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - name (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ChildCatAllOf, - ParentPet, - ], - 'oneOf': [ - ], - } +from petstore_api.model.parent_pet import ParentPet diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.pyi new file mode 100644 index 0000000000..32db862b8a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.pyi @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ChildCat( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + name = schemas.StrSchema + __annotations__ = { + "name": name, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + name: typing.Union[MetaOapg.properties.name, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + name=name, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + ParentPet, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ChildCat': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.parent_pet import ParentPet diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py index cbbd0ff1e8..75d36e823c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,73 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class ClassModel(ModelNormal): +class ClassModel( + schemas.AnyTypeSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + Model for testing model with "_class" property """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + _class = schemas.StrSchema + __annotations__ = { + "_class": _class, + } - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["_class"]) -> MetaOapg.properties._class: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["_class", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["_class"]) -> typing.Union[MetaOapg.properties._class, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["_class", ], str]): + return super().get_item_oapg(name) + - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - '_class': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - '_class': '_class', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ClassModel - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - _class (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ClassModel - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - _class (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _class: typing.Union[MetaOapg.properties._class, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ClassModel': + return super().__new__( + cls, + *args, + _class=_class, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/class_model.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.pyi new file mode 100644 index 0000000000..75d36e823c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.pyi @@ -0,0 +1,81 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ClassModel( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Model for testing model with "_class" property + """ + + + class MetaOapg: + + class properties: + _class = schemas.StrSchema + __annotations__ = { + "_class": _class, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["_class"]) -> MetaOapg.properties._class: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["_class", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["_class"]) -> typing.Union[MetaOapg.properties._class, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["_class", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _class: typing.Union[MetaOapg.properties._class, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ClassModel': + return super().__new__( + cls, + *args, + _class=_class, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/client.py b/samples/openapi3/client/petstore/python/petstore_api/model/client.py index 82c5a6ed6b..4c7c16b564 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/client.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,70 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Client(ModelNormal): +class Client( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + client = schemas.StrSchema + __annotations__ = { + "client": client, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["client"]) -> MetaOapg.properties.client: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["client", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["client"]) -> typing.Union[MetaOapg.properties.client, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["client", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'client': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'client': 'client', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Client - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - client (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Client - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - client (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + client: typing.Union[MetaOapg.properties.client, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Client': + return super().__new__( + cls, + *args, + client=client, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/client.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/client.pyi new file mode 100644 index 0000000000..4c7c16b564 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/client.pyi @@ -0,0 +1,78 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Client( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + client = schemas.StrSchema + __annotations__ = { + "client": client, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["client"]) -> MetaOapg.properties.client: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["client", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["client"]) -> typing.Union[MetaOapg.properties.client, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["client", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + client: typing.Union[MetaOapg.properties.client, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Client': + return super().__new__( + cls, + *args, + client=client, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py index 3ad5b7a718..434c2c0c77 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,320 +9,124 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.quadrilateral_interface import QuadrilateralInterface - from petstore_api.model.shape_interface import ShapeInterface - globals()['QuadrilateralInterface'] = QuadrilateralInterface - globals()['ShapeInterface'] = ShapeInterface - - -class ComplexQuadrilateral(ModelComposed): +class ComplexQuadrilateral( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'shape_type': (str,), # noqa: E501 - 'quadrilateral_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class quadrilateralType( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "ComplexQuadrilateral": "COMPLEX_QUADRILATERAL", + } + + @schemas.classproperty + def COMPLEX_QUADRILATERAL(cls): + return cls("ComplexQuadrilateral") + __annotations__ = { + "quadrilateralType": quadrilateralType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["quadrilateralType"]) -> MetaOapg.properties.quadrilateralType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["quadrilateralType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["quadrilateralType"]) -> typing.Union[MetaOapg.properties.quadrilateralType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["quadrilateralType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + quadrilateralType: typing.Union[MetaOapg.properties.quadrilateralType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + quadrilateralType=quadrilateralType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + QuadrilateralInterface, + cls.all_of_1, + ] - attribute_map = { - 'shape_type': 'shapeType', # noqa: E501 - 'quadrilateral_type': 'quadrilateralType', # noqa: E501 - } + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ComplexQuadrilateral': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ComplexQuadrilateral - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - quadrilateral_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ComplexQuadrilateral - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - quadrilateral_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - QuadrilateralInterface, - ShapeInterface, - ], - 'oneOf': [ - ], - } +from petstore_api.model.quadrilateral_interface import QuadrilateralInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.pyi new file mode 100644 index 0000000000..43d8724caa --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.pyi @@ -0,0 +1,126 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComplexQuadrilateral( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class quadrilateralType( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def COMPLEX_QUADRILATERAL(cls): + return cls("ComplexQuadrilateral") + __annotations__ = { + "quadrilateralType": quadrilateralType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["quadrilateralType"]) -> MetaOapg.properties.quadrilateralType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["quadrilateralType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["quadrilateralType"]) -> typing.Union[MetaOapg.properties.quadrilateralType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["quadrilateralType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + quadrilateralType: typing.Union[MetaOapg.properties.quadrilateralType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + quadrilateralType=quadrilateralType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + QuadrilateralInterface, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ComplexQuadrilateral': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.quadrilateral_interface import QuadrilateralInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_any_of_different_types_no_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_any_of_different_types_no_validations.py new file mode 100644 index 0000000000..9e077ff0db --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_any_of_different_types_no_validations.py @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedAnyOfDifferentTypesNoValidations( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + any_of_0 = schemas.DictSchema + any_of_1 = schemas.DateSchema + any_of_2 = schemas.DateTimeSchema + any_of_3 = schemas.BinarySchema + any_of_4 = schemas.StrSchema + any_of_5 = schemas.StrSchema + any_of_6 = schemas.DictSchema + any_of_7 = schemas.BoolSchema + any_of_8 = schemas.NoneSchema + + + class any_of_9( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'any_of_9': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + any_of_10 = schemas.NumberSchema + any_of_11 = schemas.Float32Schema + any_of_12 = schemas.Float64Schema + any_of_13 = schemas.IntSchema + any_of_14 = schemas.Int32Schema + any_of_15 = schemas.Int64Schema + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + cls.any_of_2, + cls.any_of_3, + cls.any_of_4, + cls.any_of_5, + cls.any_of_6, + cls.any_of_7, + cls.any_of_8, + cls.any_of_9, + cls.any_of_10, + cls.any_of_11, + cls.any_of_12, + cls.any_of_13, + cls.any_of_14, + cls.any_of_15, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ComposedAnyOfDifferentTypesNoValidations': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_any_of_different_types_no_validations.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/composed_any_of_different_types_no_validations.pyi new file mode 100644 index 0000000000..9e077ff0db --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_any_of_different_types_no_validations.pyi @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedAnyOfDifferentTypesNoValidations( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + any_of_0 = schemas.DictSchema + any_of_1 = schemas.DateSchema + any_of_2 = schemas.DateTimeSchema + any_of_3 = schemas.BinarySchema + any_of_4 = schemas.StrSchema + any_of_5 = schemas.StrSchema + any_of_6 = schemas.DictSchema + any_of_7 = schemas.BoolSchema + any_of_8 = schemas.NoneSchema + + + class any_of_9( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'any_of_9': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + any_of_10 = schemas.NumberSchema + any_of_11 = schemas.Float32Schema + any_of_12 = schemas.Float64Schema + any_of_13 = schemas.IntSchema + any_of_14 = schemas.Int32Schema + any_of_15 = schemas.Int64Schema + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.any_of_0, + cls.any_of_1, + cls.any_of_2, + cls.any_of_3, + cls.any_of_4, + cls.any_of_5, + cls.any_of_6, + cls.any_of_7, + cls.any_of_8, + cls.any_of_9, + cls.any_of_10, + cls.any_of_11, + cls.any_of_12, + cls.any_of_13, + cls.any_of_14, + cls.any_of_15, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ComposedAnyOfDifferentTypesNoValidations': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_array.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_array.py new file mode 100644 index 0000000000..41e7107528 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_array.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedArray( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedArray': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_array.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/composed_array.pyi new file mode 100644 index 0000000000..41e7107528 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_array.pyi @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedArray( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedArray': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_bool.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_bool.py new file mode 100644 index 0000000000..4a42a8626d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_bool.py @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedBool( + schemas.ComposedBase, + schemas.BoolSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[bool, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedBool': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_bool.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/composed_bool.pyi new file mode 100644 index 0000000000..4a42a8626d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_bool.pyi @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedBool( + schemas.ComposedBase, + schemas.BoolSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[bool, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedBool': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_none.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_none.py new file mode 100644 index 0000000000..f442971abb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_none.py @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedNone( + schemas.ComposedBase, + schemas.NoneSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedNone': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_none.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/composed_none.pyi new file mode 100644 index 0000000000..f442971abb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_none.pyi @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedNone( + schemas.ComposedBase, + schemas.NoneSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedNone': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_number.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_number.py new file mode 100644 index 0000000000..36f53dbf21 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_number.py @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedNumber( + schemas.ComposedBase, + schemas.NumberSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[decimal.Decimal, int, float, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedNumber': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_number.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/composed_number.pyi new file mode 100644 index 0000000000..36f53dbf21 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_number.pyi @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedNumber( + schemas.ComposedBase, + schemas.NumberSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[decimal.Decimal, int, float, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedNumber': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_object.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_object.py new file mode 100644 index 0000000000..44171746f1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_object.py @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedObject( + schemas.ComposedBase, + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ComposedObject': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_object.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/composed_object.pyi new file mode 100644 index 0000000000..44171746f1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_object.pyi @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedObject( + schemas.ComposedBase, + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ComposedObject': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_different_types.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_different_types.py new file mode 100644 index 0000000000..b3cf4aea1c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_different_types.py @@ -0,0 +1,137 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedOneOfDifferentTypes( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + this is a model that allows payloads of type object or number + """ + + + class MetaOapg: + one_of_2 = schemas.NoneSchema + one_of_3 = schemas.DateSchema + + + class one_of_4( + schemas.DictSchema + ): + + + class MetaOapg: + max_properties = 4 + min_properties = 4 + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_4': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_5( + schemas.ListSchema + ): + + + class MetaOapg: + max_items = 4 + min_items = 4 + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'one_of_5': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class one_of_6( + schemas.DateTimeSchema + ): + + + class MetaOapg: + format = 'date-time' + regex=[{ + 'pattern': r'^2020.*', # noqa: E501 + }] + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + NumberWithValidations, + Animal, + cls.one_of_2, + cls.one_of_3, + cls.one_of_4, + cls.one_of_5, + cls.one_of_6, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ComposedOneOfDifferentTypes': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.animal import Animal +from petstore_api.model.number_with_validations import NumberWithValidations diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_different_types.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_different_types.pyi new file mode 100644 index 0000000000..0fd6b4dd0f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_different_types.pyi @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedOneOfDifferentTypes( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + this is a model that allows payloads of type object or number + """ + + + class MetaOapg: + one_of_2 = schemas.NoneSchema + one_of_3 = schemas.DateSchema + + + class one_of_4( + schemas.DictSchema + ): + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'one_of_4': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class one_of_5( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.AnyTypeSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'one_of_5': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class one_of_6( + schemas.DateTimeSchema + ): + pass + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + NumberWithValidations, + Animal, + cls.one_of_2, + cls.one_of_3, + cls.one_of_4, + cls.one_of_5, + cls.one_of_6, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ComposedOneOfDifferentTypes': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.animal import Animal +from petstore_api.model.number_with_validations import NumberWithValidations diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_string.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_string.py new file mode 100644 index 0000000000..50d61de169 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_string.py @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedString( + schemas.ComposedBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedString': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_string.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/composed_string.pyi new file mode 100644 index 0000000000..50d61de169 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_string.pyi @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ComposedString( + schemas.ComposedBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + all_of_0 = schemas.AnyTypeSchema + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ComposedString': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/currency.py b/samples/openapi3/client/petstore/python/petstore_api/model/currency.py new file mode 100644 index 0000000000..8714c9adcc --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/currency.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Currency( + schemas.EnumBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + "eur": "EUR", + "usd": "USD", + } + + @schemas.classproperty + def EUR(cls): + return cls("eur") + + @schemas.classproperty + def USD(cls): + return cls("usd") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/currency.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/currency.pyi new file mode 100644 index 0000000000..7706629add --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/currency.pyi @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Currency( + schemas.EnumBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def EUR(cls): + return cls("eur") + + @schemas.classproperty + def USD(cls): + return cls("usd") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py index 3a37b35393..bcffd8ff00 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,263 +9,90 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class DanishPig(ModelNormal): +class DanishPig( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'class_name': (str,), # noqa: E501 + class MetaOapg: + required = { + "className", } + + class properties: + + + class className( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "DanishPig": "DANISH_PIG", + } + + @schemas.classproperty + def DANISH_PIG(cls): + return cls("DanishPig") + __annotations__ = { + "className": className, + } + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className", ], str]): + return super().get_item_oapg(name) + - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'class_name': 'className', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 - """DanishPig - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 - """DanishPig - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'DanishPig': + return super().__new__( + cls, + *args, + className=className, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.pyi new file mode 100644 index 0000000000..9f64db8274 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.pyi @@ -0,0 +1,92 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class DanishPig( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "className", + } + + class properties: + + + class className( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def DANISH_PIG(cls): + return cls("DanishPig") + __annotations__ = { + "className": className, + } + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'DanishPig': + return super().__new__( + cls, + *args, + className=className, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/date_time_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/date_time_test.py new file mode 100644 index 0000000000..1a616cac27 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/date_time_test.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +DateTimeTest = schemas.DateTimeSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/date_time_test.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/date_time_test.pyi new file mode 100644 index 0000000000..1a616cac27 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/date_time_test.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +DateTimeTest = schemas.DateTimeSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/date_time_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/date_time_with_validations.py new file mode 100644 index 0000000000..a5a7858195 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/date_time_with_validations.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class DateTimeWithValidations( + schemas.DateTimeSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'date-time' + regex=[{ + 'pattern': r'^2020.*', # noqa: E501 + }] diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/date_time_with_validations.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/date_time_with_validations.pyi new file mode 100644 index 0000000000..2898b61900 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/date_time_with_validations.pyi @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class DateTimeWithValidations( + schemas.DateTimeSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/date_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/date_with_validations.py new file mode 100644 index 0000000000..82d0122a27 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/date_with_validations.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class DateWithValidations( + schemas.DateSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'date' + regex=[{ + 'pattern': r'^2020.*', # noqa: E501 + }] diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/date_with_validations.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/date_with_validations.pyi new file mode 100644 index 0000000000..52770358d1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/date_with_validations.pyi @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class DateWithValidations( + schemas.DateSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/decimal_payload.py b/samples/openapi3/client/petstore/python/petstore_api/model/decimal_payload.py new file mode 100644 index 0000000000..8e3b63175a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/decimal_payload.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +DecimalPayload = schemas.DecimalSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/decimal_payload.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/decimal_payload.pyi new file mode 100644 index 0000000000..8e3b63175a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/decimal_payload.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +DecimalPayload = schemas.DecimalSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/dog.py b/samples/openapi3/client/petstore/python/petstore_api/model/dog.py index f5b4d580f0..a8dd43038d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/dog.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/dog.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,338 +9,109 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.animal import Animal - from petstore_api.model.dog_all_of import DogAllOf - from petstore_api.model.legs import Legs - globals()['Animal'] = Animal - globals()['DogAllOf'] = DogAllOf - globals()['Legs'] = Legs - - -class Dog(ModelComposed): +class Dog( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + breed = schemas.StrSchema + __annotations__ = { + "breed": breed, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["breed"]) -> MetaOapg.properties.breed: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["breed", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["breed"]) -> typing.Union[MetaOapg.properties.breed, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["breed", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + breed: typing.Union[MetaOapg.properties.breed, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + breed=breed, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Animal, + cls.all_of_1, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Dog': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'class_name': (str,), # noqa: E501 - 'breed': (str,), # noqa: E501 - 'legs': (Legs,), # noqa: E501 - 'color': (str,), # noqa: E501 - 'tail': (bool,), # noqa: E501 - } - - @cached_property - def discriminator(): - val = { - } - if not val: - return None - return {'class_name': val} - - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'breed': 'breed', # noqa: E501 - 'legs': 'legs', # noqa: E501 - 'color': 'color', # noqa: E501 - 'tail': 'tail', # noqa: E501 - } - - read_only_vars = { - 'tail', # noqa: E501 - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Dog - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - breed (str): [optional] # noqa: E501 - legs (Legs): [optional] # noqa: E501 - color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 - tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Dog - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - breed (str): [optional] # noqa: E501 - legs (Legs): [optional] # noqa: E501 - color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 - tail (bool): [optional] if omitted the server will use the default value of True # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - Animal, - DogAllOf, - ], - 'oneOf': [ - ], - } +from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/dog.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/dog.pyi new file mode 100644 index 0000000000..a8dd43038d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/dog.pyi @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Dog( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + breed = schemas.StrSchema + __annotations__ = { + "breed": breed, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["breed"]) -> MetaOapg.properties.breed: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["breed", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["breed"]) -> typing.Union[MetaOapg.properties.breed, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["breed", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + breed: typing.Union[MetaOapg.properties.breed, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + breed=breed, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Animal, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Dog': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py index c08b8d2a0b..9c7b54ae9c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,281 +9,141 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.fruit import Fruit - from petstore_api.model.nullable_shape import NullableShape - from petstore_api.model.shape import Shape - from petstore_api.model.shape_or_null import ShapeOrNull - globals()['Fruit'] = Fruit - globals()['NullableShape'] = NullableShape - globals()['Shape'] = Shape - globals()['ShapeOrNull'] = ShapeOrNull - - -class Drawing(ModelNormal): +class Drawing( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (Fruit,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'main_shape': (Shape,), # noqa: E501 - 'shape_or_null': (ShapeOrNull,), # noqa: E501 - 'nullable_shape': (NullableShape,), # noqa: E501 - 'shapes': ([Shape],), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'main_shape': 'mainShape', # noqa: E501 - 'shape_or_null': 'shapeOrNull', # noqa: E501 - 'nullable_shape': 'nullableShape', # noqa: E501 - 'shapes': 'shapes', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Drawing - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - main_shape (Shape): [optional] # noqa: E501 - shape_or_null (ShapeOrNull): [optional] # noqa: E501 - nullable_shape (NullableShape): [optional] # noqa: E501 - shapes ([Shape]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + @staticmethod + def mainShape() -> typing.Type['Shape']: + return Shape + + @staticmethod + def shapeOrNull() -> typing.Type['ShapeOrNull']: + return ShapeOrNull + + @staticmethod + def nullableShape() -> typing.Type['NullableShape']: + return NullableShape + + + class shapes( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Shape']: + return Shape + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Shape'], typing.List['Shape']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'shapes': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) + + def __getitem__(self, i: int) -> 'Shape': + return super().__getitem__(i) + __annotations__ = { + "mainShape": mainShape, + "shapeOrNull": shapeOrNull, + "nullableShape": nullableShape, + "shapes": shapes, + } + + @staticmethod + def additional_properties() -> typing.Type['Fruit']: + return Fruit + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["mainShape"]) -> 'Shape': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shapeOrNull"]) -> 'ShapeOrNull': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["nullableShape"]) -> 'NullableShape': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shapes"]) -> MetaOapg.properties.shapes: ... + + @typing.overload + def __getitem__(self, name: str) -> 'Fruit': ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["mainShape"], typing_extensions.Literal["shapeOrNull"], typing_extensions.Literal["nullableShape"], typing_extensions.Literal["shapes"], str, ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["mainShape"]) -> typing.Union['Shape', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shapeOrNull"]) -> typing.Union['ShapeOrNull', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["nullableShape"]) -> typing.Union['NullableShape', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shapes"]) -> typing.Union[MetaOapg.properties.shapes, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union['Fruit', schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["mainShape"], typing_extensions.Literal["shapeOrNull"], typing_extensions.Literal["nullableShape"], typing_extensions.Literal["shapes"], str, ]): + return super().get_item_oapg(name) - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + mainShape: typing.Union['Shape', schemas.Unset] = schemas.unset, + shapeOrNull: typing.Union['ShapeOrNull', schemas.Unset] = schemas.unset, + nullableShape: typing.Union['NullableShape', schemas.Unset] = schemas.unset, + shapes: typing.Union[MetaOapg.properties.shapes, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: 'Fruit', + ) -> 'Drawing': + return super().__new__( + cls, + *args, + mainShape=mainShape, + shapeOrNull=shapeOrNull, + nullableShape=nullableShape, + shapes=shapes, + _configuration=_configuration, + **kwargs, + ) - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Drawing - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - main_shape (Shape): [optional] # noqa: E501 - shape_or_null (ShapeOrNull): [optional] # noqa: E501 - nullable_shape (NullableShape): [optional] # noqa: E501 - shapes ([Shape]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.fruit import Fruit +from petstore_api.model.nullable_shape import NullableShape +from petstore_api.model.shape import Shape +from petstore_api.model.shape_or_null import ShapeOrNull diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/drawing.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.pyi new file mode 100644 index 0000000000..9c7b54ae9c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.pyi @@ -0,0 +1,149 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Drawing( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + @staticmethod + def mainShape() -> typing.Type['Shape']: + return Shape + + @staticmethod + def shapeOrNull() -> typing.Type['ShapeOrNull']: + return ShapeOrNull + + @staticmethod + def nullableShape() -> typing.Type['NullableShape']: + return NullableShape + + + class shapes( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Shape']: + return Shape + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Shape'], typing.List['Shape']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'shapes': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Shape': + return super().__getitem__(i) + __annotations__ = { + "mainShape": mainShape, + "shapeOrNull": shapeOrNull, + "nullableShape": nullableShape, + "shapes": shapes, + } + + @staticmethod + def additional_properties() -> typing.Type['Fruit']: + return Fruit + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["mainShape"]) -> 'Shape': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shapeOrNull"]) -> 'ShapeOrNull': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["nullableShape"]) -> 'NullableShape': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shapes"]) -> MetaOapg.properties.shapes: ... + + @typing.overload + def __getitem__(self, name: str) -> 'Fruit': ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["mainShape"], typing_extensions.Literal["shapeOrNull"], typing_extensions.Literal["nullableShape"], typing_extensions.Literal["shapes"], str, ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["mainShape"]) -> typing.Union['Shape', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shapeOrNull"]) -> typing.Union['ShapeOrNull', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["nullableShape"]) -> typing.Union['NullableShape', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shapes"]) -> typing.Union[MetaOapg.properties.shapes, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union['Fruit', schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["mainShape"], typing_extensions.Literal["shapeOrNull"], typing_extensions.Literal["nullableShape"], typing_extensions.Literal["shapes"], str, ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + mainShape: typing.Union['Shape', schemas.Unset] = schemas.unset, + shapeOrNull: typing.Union['ShapeOrNull', schemas.Unset] = schemas.unset, + nullableShape: typing.Union['NullableShape', schemas.Unset] = schemas.unset, + shapes: typing.Union[MetaOapg.properties.shapes, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: 'Fruit', + ) -> 'Drawing': + return super().__new__( + cls, + *args, + mainShape=mainShape, + shapeOrNull=shapeOrNull, + nullableShape=nullableShape, + shapes=shapes, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.fruit import Fruit +from petstore_api.model.nullable_shape import NullableShape +from petstore_api.model.shape import Shape +from petstore_api.model.shape_or_null import ShapeOrNull diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py index 65b981ab7b..1e7e0843da 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,269 +9,142 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class EnumArrays(ModelNormal): +class EnumArrays( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('just_symbol',): { - '>=': ">=", - '$': "$", - }, - ('array_enum',): { - 'FISH': "fish", - 'CRAB': "crab", - }, - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'just_symbol': (str,), # noqa: E501 - 'array_enum': ([str],), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'just_symbol': 'just_symbol', # noqa: E501 - 'array_enum': 'array_enum', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """EnumArrays - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - just_symbol (str): [optional] # noqa: E501 - array_enum ([str]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + + class just_symbol( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + ">=": "GREATER_THAN_EQUALS", + "$": "DOLLAR", + } + + @schemas.classproperty + def GREATER_THAN_EQUALS(cls): + return cls(">=") + + @schemas.classproperty + def DOLLAR(cls): + return cls("$") + + + class array_enum( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "fish": "FISH", + "crab": "CRAB", + } + + @schemas.classproperty + def FISH(cls): + return cls("fish") + + @schemas.classproperty + def CRAB(cls): + return cls("crab") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_enum': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "just_symbol": just_symbol, + "array_enum": array_enum, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["just_symbol"]) -> MetaOapg.properties.just_symbol: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_enum"]) -> MetaOapg.properties.array_enum: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["just_symbol", "array_enum", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["just_symbol"]) -> typing.Union[MetaOapg.properties.just_symbol, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_enum"]) -> typing.Union[MetaOapg.properties.array_enum, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["just_symbol", "array_enum", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """EnumArrays - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - just_symbol (str): [optional] # noqa: E501 - array_enum ([str]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + just_symbol: typing.Union[MetaOapg.properties.just_symbol, str, schemas.Unset] = schemas.unset, + array_enum: typing.Union[MetaOapg.properties.array_enum, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EnumArrays': + return super().__new__( + cls, + *args, + just_symbol=just_symbol, + array_enum=array_enum, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.pyi new file mode 100644 index 0000000000..31b854f7d1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.pyi @@ -0,0 +1,136 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class EnumArrays( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class just_symbol( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def GREATER_THAN_EQUALS(cls): + return cls(">=") + + @schemas.classproperty + def DOLLAR(cls): + return cls("$") + + + class array_enum( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def FISH(cls): + return cls("fish") + + @schemas.classproperty + def CRAB(cls): + return cls("crab") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_enum': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "just_symbol": just_symbol, + "array_enum": array_enum, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["just_symbol"]) -> MetaOapg.properties.just_symbol: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_enum"]) -> MetaOapg.properties.array_enum: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["just_symbol", "array_enum", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["just_symbol"]) -> typing.Union[MetaOapg.properties.just_symbol, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_enum"]) -> typing.Union[MetaOapg.properties.array_enum, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["just_symbol", "array_enum", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + just_symbol: typing.Union[MetaOapg.properties.just_symbol, str, schemas.Unset] = schemas.unset, + array_enum: typing.Union[MetaOapg.properties.array_enum, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EnumArrays': + return super().__new__( + cls, + *args, + just_symbol=just_symbol, + array_enum=array_enum, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py index bf9b682bd0..27018e19a6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,277 +9,56 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class EnumClass(ModelSimple): +class EnumClass( + schemas.EnumBase, + schemas.StrSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('value',): { - '_ABC': "_abc", - '-EFG': "-efg", - '(XYZ)': "(xyz)", - }, - } - validations = { - } - - additional_properties_type = None - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (str,), + class MetaOapg: + enum_value_to_name = { + "_abc": "_ABC", + "-efg": "EFG", + "(xyz)": "XYZ", + "COUNT_1M": "COUNT_1M", + "COUNT_50M": "COUNT_50M", } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """EnumClass - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 - - Keyword Args: - value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = "-efg" - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """EnumClass - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 - - Keyword Args: - value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = "-efg" - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self + + @schemas.classproperty + def _ABC(cls): + return cls("_abc") + + @schemas.classproperty + def EFG(cls): + return cls("-efg") + + @schemas.classproperty + def XYZ(cls): + return cls("(xyz)") + + @schemas.classproperty + def COUNT_1M(cls): + return cls("COUNT_1M") + + @schemas.classproperty + def COUNT_50M(cls): + return cls("COUNT_50M") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.pyi new file mode 100644 index 0000000000..7d43347fd8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.pyi @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class EnumClass( + schemas.EnumBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def _ABC(cls): + return cls("_abc") + + @schemas.classproperty + def EFG(cls): + return cls("-efg") + + @schemas.classproperty + def XYZ(cls): + return cls("(xyz)") + + @schemas.classproperty + def COUNT_1M(cls): + return cls("COUNT_1M") + + @schemas.classproperty + def COUNT_50M(cls): + return cls("COUNT_50M") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py index dd47ea4f74..094073cddc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,350 +9,268 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.array_of_enums import ArrayOfEnums - from petstore_api.model.boolean_enum import BooleanEnum - from petstore_api.model.integer_enum import IntegerEnum - from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue - from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue - from petstore_api.model.string_enum import StringEnum - from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue - globals()['ArrayOfEnums'] = ArrayOfEnums - globals()['BooleanEnum'] = BooleanEnum - globals()['IntegerEnum'] = IntegerEnum - globals()['IntegerEnumOneValue'] = IntegerEnumOneValue - globals()['IntegerEnumWithDefaultValue'] = IntegerEnumWithDefaultValue - globals()['StringEnum'] = StringEnum - globals()['StringEnumWithDefaultValue'] = StringEnumWithDefaultValue - - -class EnumTest(ModelNormal): +class EnumTest( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('enum_string_required',): { - 'UPPER': "UPPER", - 'LOWER': "lower", - 'EMPTY': "", - }, - ('enum_string',): { - 'UPPER': "UPPER", - 'LOWER': "lower", - 'EMPTY': "", - }, - ('enum_integer',): { - '1': 1, - '-1': -1, - }, - ('enum_number',): { - '1.1': 1.1, - '-1.2': -1.2, - }, - ('enum_bool',): { - 'FALSE': False, - }, - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'enum_string_required': (str,), # noqa: E501 - 'enum_string': (str,), # noqa: E501 - 'enum_integer': (int,), # noqa: E501 - 'enum_number': (float,), # noqa: E501 - 'enum_bool': (bool,), # noqa: E501 - 'bool_enum': (BooleanEnum,), # noqa: E501 - 'string_enum': (StringEnum,), # noqa: E501 - 'integer_enum': (IntegerEnum,), # noqa: E501 - 'string_enum_with_default_value': (StringEnumWithDefaultValue,), # noqa: E501 - 'integer_enum_with_default_value': (IntegerEnumWithDefaultValue,), # noqa: E501 - 'integer_enum_one_value': (IntegerEnumOneValue,), # noqa: E501 - 'inline_array_of_str_enum': ([StringEnum],), # noqa: E501 - 'array_of_str_enum': (ArrayOfEnums,), # noqa: E501 + class MetaOapg: + required = { + "enum_string_required", } + + class properties: + + + class enum_string_required( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "UPPER": "UPPER", + "lower": "LOWER", + "": "EMPTY", + } + + @schemas.classproperty + def UPPER(cls): + return cls("UPPER") + + @schemas.classproperty + def LOWER(cls): + return cls("lower") + + @schemas.classproperty + def EMPTY(cls): + return cls("") + + + class enum_string( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "UPPER": "UPPER", + "lower": "LOWER", + "": "EMPTY", + } + + @schemas.classproperty + def UPPER(cls): + return cls("UPPER") + + @schemas.classproperty + def LOWER(cls): + return cls("lower") + + @schemas.classproperty + def EMPTY(cls): + return cls("") + + + class enum_integer( + schemas.EnumBase, + schemas.Int32Schema + ): + + + class MetaOapg: + format = 'int32' + enum_value_to_name = { + 1: "POSITIVE_1", + -1: "NEGATIVE_1", + } + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def NEGATIVE_1(cls): + return cls(-1) + + + class enum_number( + schemas.EnumBase, + schemas.Float64Schema + ): + + + class MetaOapg: + format = 'double' + enum_value_to_name = { + 1.1: "POSITIVE_1_PT_1", + -1.2: "NEGATIVE_1_PT_2", + } + + @schemas.classproperty + def POSITIVE_1_PT_1(cls): + return cls(1.1) + + @schemas.classproperty + def NEGATIVE_1_PT_2(cls): + return cls(-1.2) + + @staticmethod + def stringEnum() -> typing.Type['StringEnum']: + return StringEnum + + @staticmethod + def IntegerEnum() -> typing.Type['IntegerEnum']: + return IntegerEnum + + @staticmethod + def StringEnumWithDefaultValue() -> typing.Type['StringEnumWithDefaultValue']: + return StringEnumWithDefaultValue + + @staticmethod + def IntegerEnumWithDefaultValue() -> typing.Type['IntegerEnumWithDefaultValue']: + return IntegerEnumWithDefaultValue + + @staticmethod + def IntegerEnumOneValue() -> typing.Type['IntegerEnumOneValue']: + return IntegerEnumOneValue + __annotations__ = { + "enum_string_required": enum_string_required, + "enum_string": enum_string, + "enum_integer": enum_integer, + "enum_number": enum_number, + "stringEnum": stringEnum, + "IntegerEnum": IntegerEnum, + "StringEnumWithDefaultValue": StringEnumWithDefaultValue, + "IntegerEnumWithDefaultValue": IntegerEnumWithDefaultValue, + "IntegerEnumOneValue": IntegerEnumOneValue, + } + + enum_string_required: MetaOapg.properties.enum_string_required + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_string_required"]) -> MetaOapg.properties.enum_string_required: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_string"]) -> MetaOapg.properties.enum_string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_integer"]) -> MetaOapg.properties.enum_integer: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_number"]) -> MetaOapg.properties.enum_number: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["stringEnum"]) -> 'StringEnum': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["IntegerEnum"]) -> 'IntegerEnum': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["StringEnumWithDefaultValue"]) -> 'StringEnumWithDefaultValue': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["IntegerEnumWithDefaultValue"]) -> 'IntegerEnumWithDefaultValue': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["IntegerEnumOneValue"]) -> 'IntegerEnumOneValue': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["enum_string_required", "enum_string", "enum_integer", "enum_number", "stringEnum", "IntegerEnum", "StringEnumWithDefaultValue", "IntegerEnumWithDefaultValue", "IntegerEnumOneValue", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_string_required"]) -> MetaOapg.properties.enum_string_required: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_string"]) -> typing.Union[MetaOapg.properties.enum_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_integer"]) -> typing.Union[MetaOapg.properties.enum_integer, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_number"]) -> typing.Union[MetaOapg.properties.enum_number, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["stringEnum"]) -> typing.Union['StringEnum', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["IntegerEnum"]) -> typing.Union['IntegerEnum', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["StringEnumWithDefaultValue"]) -> typing.Union['StringEnumWithDefaultValue', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["IntegerEnumWithDefaultValue"]) -> typing.Union['IntegerEnumWithDefaultValue', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["IntegerEnumOneValue"]) -> typing.Union['IntegerEnumOneValue', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["enum_string_required", "enum_string", "enum_integer", "enum_number", "stringEnum", "IntegerEnum", "StringEnumWithDefaultValue", "IntegerEnumWithDefaultValue", "IntegerEnumOneValue", ], str]): + return super().get_item_oapg(name) + - @cached_property - def discriminator(): - return None + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + enum_string_required: typing.Union[MetaOapg.properties.enum_string_required, str, ], + enum_string: typing.Union[MetaOapg.properties.enum_string, str, schemas.Unset] = schemas.unset, + enum_integer: typing.Union[MetaOapg.properties.enum_integer, decimal.Decimal, int, schemas.Unset] = schemas.unset, + enum_number: typing.Union[MetaOapg.properties.enum_number, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + stringEnum: typing.Union['StringEnum', schemas.Unset] = schemas.unset, + IntegerEnum: typing.Union['IntegerEnum', schemas.Unset] = schemas.unset, + StringEnumWithDefaultValue: typing.Union['StringEnumWithDefaultValue', schemas.Unset] = schemas.unset, + IntegerEnumWithDefaultValue: typing.Union['IntegerEnumWithDefaultValue', schemas.Unset] = schemas.unset, + IntegerEnumOneValue: typing.Union['IntegerEnumOneValue', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EnumTest': + return super().__new__( + cls, + *args, + enum_string_required=enum_string_required, + enum_string=enum_string, + enum_integer=enum_integer, + enum_number=enum_number, + stringEnum=stringEnum, + IntegerEnum=IntegerEnum, + StringEnumWithDefaultValue=StringEnumWithDefaultValue, + IntegerEnumWithDefaultValue=IntegerEnumWithDefaultValue, + IntegerEnumOneValue=IntegerEnumOneValue, + _configuration=_configuration, + **kwargs, + ) - - attribute_map = { - 'enum_string_required': 'enum_string_required', # noqa: E501 - 'enum_string': 'enum_string', # noqa: E501 - 'enum_integer': 'enum_integer', # noqa: E501 - 'enum_number': 'enum_number', # noqa: E501 - 'enum_bool': 'enum_bool', # noqa: E501 - 'bool_enum': 'boolEnum', # noqa: E501 - 'string_enum': 'stringEnum', # noqa: E501 - 'integer_enum': 'IntegerEnum', # noqa: E501 - 'string_enum_with_default_value': 'StringEnumWithDefaultValue', # noqa: E501 - 'integer_enum_with_default_value': 'IntegerEnumWithDefaultValue', # noqa: E501 - 'integer_enum_one_value': 'IntegerEnumOneValue', # noqa: E501 - 'inline_array_of_str_enum': 'InlineArrayOfStrEnum', # noqa: E501 - 'array_of_str_enum': 'ArrayOfStrEnum', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, enum_string_required, *args, **kwargs): # noqa: E501 - """EnumTest - a model defined in OpenAPI - - Args: - enum_string_required (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - enum_string (str): [optional] # noqa: E501 - enum_integer (int): [optional] # noqa: E501 - enum_number (float): [optional] # noqa: E501 - enum_bool (bool): [optional] if omitted the server will use the default value of False # noqa: E501 - bool_enum (BooleanEnum): [optional] # noqa: E501 - string_enum (StringEnum): [optional] # noqa: E501 - integer_enum (IntegerEnum): [optional] # noqa: E501 - string_enum_with_default_value (StringEnumWithDefaultValue): [optional] # noqa: E501 - integer_enum_with_default_value (IntegerEnumWithDefaultValue): [optional] # noqa: E501 - integer_enum_one_value (IntegerEnumOneValue): [optional] # noqa: E501 - inline_array_of_str_enum ([StringEnum]): [optional] # noqa: E501 - array_of_str_enum (ArrayOfEnums): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.enum_string_required = enum_string_required - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, enum_string_required, *args, **kwargs): # noqa: E501 - """EnumTest - a model defined in OpenAPI - - Args: - enum_string_required (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - enum_string (str): [optional] # noqa: E501 - enum_integer (int): [optional] # noqa: E501 - enum_number (float): [optional] # noqa: E501 - enum_bool (bool): [optional] if omitted the server will use the default value of False # noqa: E501 - bool_enum (BooleanEnum): [optional] # noqa: E501 - string_enum (StringEnum): [optional] # noqa: E501 - integer_enum (IntegerEnum): [optional] # noqa: E501 - string_enum_with_default_value (StringEnumWithDefaultValue): [optional] # noqa: E501 - integer_enum_with_default_value (IntegerEnumWithDefaultValue): [optional] # noqa: E501 - integer_enum_one_value (IntegerEnumOneValue): [optional] # noqa: E501 - inline_array_of_str_enum ([StringEnum]): [optional] # noqa: E501 - array_of_str_enum (ArrayOfEnums): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.enum_string_required = enum_string_required - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.integer_enum import IntegerEnum +from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue +from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue +from petstore_api.model.string_enum import StringEnum +from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.pyi new file mode 100644 index 0000000000..1f885dcf36 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.pyi @@ -0,0 +1,244 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class EnumTest( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "enum_string_required", + } + + class properties: + + + class enum_string_required( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def UPPER(cls): + return cls("UPPER") + + @schemas.classproperty + def LOWER(cls): + return cls("lower") + + @schemas.classproperty + def EMPTY(cls): + return cls("") + + + class enum_string( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def UPPER(cls): + return cls("UPPER") + + @schemas.classproperty + def LOWER(cls): + return cls("lower") + + @schemas.classproperty + def EMPTY(cls): + return cls("") + + + class enum_integer( + schemas.EnumBase, + schemas.Int32Schema + ): + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def NEGATIVE_1(cls): + return cls(-1) + + + class enum_number( + schemas.EnumBase, + schemas.Float64Schema + ): + + @schemas.classproperty + def POSITIVE_1_PT_1(cls): + return cls(1.1) + + @schemas.classproperty + def NEGATIVE_1_PT_2(cls): + return cls(-1.2) + + @staticmethod + def stringEnum() -> typing.Type['StringEnum']: + return StringEnum + + @staticmethod + def IntegerEnum() -> typing.Type['IntegerEnum']: + return IntegerEnum + + @staticmethod + def StringEnumWithDefaultValue() -> typing.Type['StringEnumWithDefaultValue']: + return StringEnumWithDefaultValue + + @staticmethod + def IntegerEnumWithDefaultValue() -> typing.Type['IntegerEnumWithDefaultValue']: + return IntegerEnumWithDefaultValue + + @staticmethod + def IntegerEnumOneValue() -> typing.Type['IntegerEnumOneValue']: + return IntegerEnumOneValue + __annotations__ = { + "enum_string_required": enum_string_required, + "enum_string": enum_string, + "enum_integer": enum_integer, + "enum_number": enum_number, + "stringEnum": stringEnum, + "IntegerEnum": IntegerEnum, + "StringEnumWithDefaultValue": StringEnumWithDefaultValue, + "IntegerEnumWithDefaultValue": IntegerEnumWithDefaultValue, + "IntegerEnumOneValue": IntegerEnumOneValue, + } + + enum_string_required: MetaOapg.properties.enum_string_required + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_string_required"]) -> MetaOapg.properties.enum_string_required: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_string"]) -> MetaOapg.properties.enum_string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_integer"]) -> MetaOapg.properties.enum_integer: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_number"]) -> MetaOapg.properties.enum_number: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["stringEnum"]) -> 'StringEnum': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["IntegerEnum"]) -> 'IntegerEnum': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["StringEnumWithDefaultValue"]) -> 'StringEnumWithDefaultValue': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["IntegerEnumWithDefaultValue"]) -> 'IntegerEnumWithDefaultValue': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["IntegerEnumOneValue"]) -> 'IntegerEnumOneValue': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["enum_string_required", "enum_string", "enum_integer", "enum_number", "stringEnum", "IntegerEnum", "StringEnumWithDefaultValue", "IntegerEnumWithDefaultValue", "IntegerEnumOneValue", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_string_required"]) -> MetaOapg.properties.enum_string_required: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_string"]) -> typing.Union[MetaOapg.properties.enum_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_integer"]) -> typing.Union[MetaOapg.properties.enum_integer, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_number"]) -> typing.Union[MetaOapg.properties.enum_number, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["stringEnum"]) -> typing.Union['StringEnum', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["IntegerEnum"]) -> typing.Union['IntegerEnum', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["StringEnumWithDefaultValue"]) -> typing.Union['StringEnumWithDefaultValue', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["IntegerEnumWithDefaultValue"]) -> typing.Union['IntegerEnumWithDefaultValue', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["IntegerEnumOneValue"]) -> typing.Union['IntegerEnumOneValue', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["enum_string_required", "enum_string", "enum_integer", "enum_number", "stringEnum", "IntegerEnum", "StringEnumWithDefaultValue", "IntegerEnumWithDefaultValue", "IntegerEnumOneValue", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + enum_string_required: typing.Union[MetaOapg.properties.enum_string_required, str, ], + enum_string: typing.Union[MetaOapg.properties.enum_string, str, schemas.Unset] = schemas.unset, + enum_integer: typing.Union[MetaOapg.properties.enum_integer, decimal.Decimal, int, schemas.Unset] = schemas.unset, + enum_number: typing.Union[MetaOapg.properties.enum_number, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + stringEnum: typing.Union['StringEnum', schemas.Unset] = schemas.unset, + IntegerEnum: typing.Union['IntegerEnum', schemas.Unset] = schemas.unset, + StringEnumWithDefaultValue: typing.Union['StringEnumWithDefaultValue', schemas.Unset] = schemas.unset, + IntegerEnumWithDefaultValue: typing.Union['IntegerEnumWithDefaultValue', schemas.Unset] = schemas.unset, + IntegerEnumOneValue: typing.Union['IntegerEnumOneValue', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EnumTest': + return super().__new__( + cls, + *args, + enum_string_required=enum_string_required, + enum_string=enum_string, + enum_integer=enum_integer, + enum_number=enum_number, + stringEnum=stringEnum, + IntegerEnum=IntegerEnum, + StringEnumWithDefaultValue=StringEnumWithDefaultValue, + IntegerEnumWithDefaultValue=IntegerEnumWithDefaultValue, + IntegerEnumOneValue=IntegerEnumOneValue, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.integer_enum import IntegerEnum +from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue +from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue +from petstore_api.model.string_enum import StringEnum +from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py index 47e8e9a64f..a45ac99de8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,320 +9,124 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.shape_interface import ShapeInterface - from petstore_api.model.triangle_interface import TriangleInterface - globals()['ShapeInterface'] = ShapeInterface - globals()['TriangleInterface'] = TriangleInterface - - -class EquilateralTriangle(ModelComposed): +class EquilateralTriangle( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'shape_type': (str,), # noqa: E501 - 'triangle_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class triangleType( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "EquilateralTriangle": "EQUILATERAL_TRIANGLE", + } + + @schemas.classproperty + def EQUILATERAL_TRIANGLE(cls): + return cls("EquilateralTriangle") + __annotations__ = { + "triangleType": triangleType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["triangleType"]) -> typing.Union[MetaOapg.properties.triangleType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + triangleType: typing.Union[MetaOapg.properties.triangleType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + triangleType=triangleType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + TriangleInterface, + cls.all_of_1, + ] - attribute_map = { - 'shape_type': 'shapeType', # noqa: E501 - 'triangle_type': 'triangleType', # noqa: E501 - } + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EquilateralTriangle': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """EquilateralTriangle - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - triangle_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """EquilateralTriangle - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - triangle_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ShapeInterface, - TriangleInterface, - ], - 'oneOf': [ - ], - } +from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.pyi new file mode 100644 index 0000000000..7e9d4d3802 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.pyi @@ -0,0 +1,126 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class EquilateralTriangle( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class triangleType( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def EQUILATERAL_TRIANGLE(cls): + return cls("EquilateralTriangle") + __annotations__ = { + "triangleType": triangleType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["triangleType"]) -> typing.Union[MetaOapg.properties.triangleType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + triangleType: typing.Union[MetaOapg.properties.triangleType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + triangleType=triangleType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + TriangleInterface, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'EquilateralTriangle': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file.py b/samples/openapi3/client/petstore/python/petstore_api/model/file.py index 6d8d65f457..886f7a62d3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/file.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,72 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class File(ModelNormal): +class File( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + Must be named `File` for test. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + sourceURI = schemas.StrSchema + __annotations__ = { + "sourceURI": sourceURI, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["sourceURI"]) -> MetaOapg.properties.sourceURI: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["sourceURI", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["sourceURI"]) -> typing.Union[MetaOapg.properties.sourceURI, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["sourceURI", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'source_uri': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'source_uri': 'sourceURI', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """File - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - source_uri (str): Test capitalization. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """File - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - source_uri (str): Test capitalization. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + sourceURI: typing.Union[MetaOapg.properties.sourceURI, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'File': + return super().__new__( + cls, + *args, + sourceURI=sourceURI, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/file.pyi new file mode 100644 index 0000000000..886f7a62d3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file.pyi @@ -0,0 +1,80 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class File( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Must be named `File` for test. + """ + + + class MetaOapg: + + class properties: + sourceURI = schemas.StrSchema + __annotations__ = { + "sourceURI": sourceURI, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["sourceURI"]) -> MetaOapg.properties.sourceURI: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["sourceURI", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["sourceURI"]) -> typing.Union[MetaOapg.properties.sourceURI, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["sourceURI", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + sourceURI: typing.Union[MetaOapg.properties.sourceURI, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'File': + return super().__new__( + cls, + *args, + sourceURI=sourceURI, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py index d8db617ffa..e9320d9a0e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,267 +9,110 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.file import File - globals()['File'] = File - - -class FileSchemaTestClass(ModelNormal): +class FileSchemaTestClass( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'file': (File,), # noqa: E501 - 'files': ([File],), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'file': 'file', # noqa: E501 - 'files': 'files', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """FileSchemaTestClass - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - file (File): [optional] # noqa: E501 - files ([File]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + @staticmethod + def file() -> typing.Type['File']: + return File + + + class files( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['File']: + return File + + def __new__( + cls, + arg: typing.Union[typing.Tuple['File'], typing.List['File']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'files': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) + + def __getitem__(self, i: int) -> 'File': + return super().__getitem__(i) + __annotations__ = { + "file": file, + "files": files, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["file"]) -> 'File': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["files"]) -> MetaOapg.properties.files: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["file", "files", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["file"]) -> typing.Union['File', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["files"]) -> typing.Union[MetaOapg.properties.files, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["file", "files", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + file: typing.Union['File', schemas.Unset] = schemas.unset, + files: typing.Union[MetaOapg.properties.files, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'FileSchemaTestClass': + return super().__new__( + cls, + *args, + file=file, + files=files, + _configuration=_configuration, + **kwargs, + ) - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """FileSchemaTestClass - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - file (File): [optional] # noqa: E501 - files ([File]): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.file import File diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.pyi new file mode 100644 index 0000000000..e9320d9a0e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.pyi @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class FileSchemaTestClass( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + @staticmethod + def file() -> typing.Type['File']: + return File + + + class files( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['File']: + return File + + def __new__( + cls, + arg: typing.Union[typing.Tuple['File'], typing.List['File']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'files': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'File': + return super().__getitem__(i) + __annotations__ = { + "file": file, + "files": files, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["file"]) -> 'File': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["files"]) -> MetaOapg.properties.files: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["file", "files", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["file"]) -> typing.Union['File', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["files"]) -> typing.Union[MetaOapg.properties.files, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["file", "files", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + file: typing.Union['File', schemas.Unset] = schemas.unset, + files: typing.Union[MetaOapg.properties.files, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'FileSchemaTestClass': + return super().__new__( + cls, + *args, + file=file, + files=files, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.file import File diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/foo.py b/samples/openapi3/client/petstore/python/petstore_api/model/foo.py index fd07a6d8ad..ce7d00afa0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/foo.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/foo.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,70 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Foo(ModelNormal): +class Foo( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + bar = schemas.StrSchema + __annotations__ = { + "bar": bar, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'bar': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'bar': 'bar', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Foo - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - bar (str): [optional] if omitted the server will use the default value of "bar" # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Foo - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - bar (str): [optional] if omitted the server will use the default value of "bar" # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Foo': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/foo.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/foo.pyi new file mode 100644 index 0000000000..ce7d00afa0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/foo.pyi @@ -0,0 +1,78 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Foo( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + bar = schemas.StrSchema + __annotations__ = { + "bar": bar, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Foo': + return super().__new__( + cls, + *args, + bar=bar, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py index 5b425f4233..b16b10a048 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,372 +9,398 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class FormatTest(ModelNormal): +class FormatTest( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - ('number',): { - 'inclusive_maximum': 543.2, - 'inclusive_minimum': 32.1, - 'multiple_of': 32.5, - }, - ('password',): { - 'max_length': 64, - 'min_length': 10, - }, - ('integer',): { - 'inclusive_maximum': 100, - 'inclusive_minimum': 10, - 'multiple_of': 2, - }, - ('int32',): { - 'inclusive_maximum': 200, - 'inclusive_minimum': 20, - }, - ('float',): { - 'inclusive_maximum': 987.6, - 'inclusive_minimum': 54.3, - }, - ('double',): { - 'inclusive_maximum': 123.4, - 'inclusive_minimum': 67.8, - }, - ('string',): { - 'regex': { - 'pattern': r'[a-z]', # noqa: E501 - 'flags': (re.IGNORECASE) - }, - }, - ('pattern_with_digits',): { - 'regex': { - 'pattern': r'^\d{10}$', # noqa: E501 - }, - }, - ('pattern_with_digits_and_delimiter',): { - 'regex': { - 'pattern': r'^image_\d{1,3}$', # noqa: E501 - 'flags': (re.IGNORECASE) - }, - }, - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'number': (float,), # noqa: E501 - 'byte': (str,), # noqa: E501 - 'date': (date,), # noqa: E501 - 'password': (str,), # noqa: E501 - 'integer': (int,), # noqa: E501 - 'int32': (int,), # noqa: E501 - 'int64': (int,), # noqa: E501 - 'float': (float,), # noqa: E501 - 'double': (float,), # noqa: E501 - 'string': (str,), # noqa: E501 - 'binary': (file_type,), # noqa: E501 - 'date_time': (datetime,), # noqa: E501 - 'uuid': (str,), # noqa: E501 - 'uuid_no_example': (str,), # noqa: E501 - 'pattern_with_digits': (str,), # noqa: E501 - 'pattern_with_digits_and_delimiter': (str,), # noqa: E501 + class MetaOapg: + required = { + "date", + "number", + "password", + "byte", } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'number': 'number', # noqa: E501 - 'byte': 'byte', # noqa: E501 - 'date': 'date', # noqa: E501 - 'password': 'password', # noqa: E501 - 'integer': 'integer', # noqa: E501 - 'int32': 'int32', # noqa: E501 - 'int64': 'int64', # noqa: E501 - 'float': 'float', # noqa: E501 - 'double': 'double', # noqa: E501 - 'string': 'string', # noqa: E501 - 'binary': 'binary', # noqa: E501 - 'date_time': 'dateTime', # noqa: E501 - 'uuid': 'uuid', # noqa: E501 - 'uuid_no_example': 'uuidNoExample', # noqa: E501 - 'pattern_with_digits': 'pattern_with_digits', # noqa: E501 - 'pattern_with_digits_and_delimiter': 'pattern_with_digits_and_delimiter', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, number, byte, date, password, *args, **kwargs): # noqa: E501 - """FormatTest - a model defined in OpenAPI - - Args: - number (float): - byte (str): - date (date): - password (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - integer (int): [optional] # noqa: E501 - int32 (int): [optional] # noqa: E501 - int64 (int): [optional] # noqa: E501 - float (float): [optional] # noqa: E501 - double (float): [optional] # noqa: E501 - string (str): [optional] # noqa: E501 - binary (file_type): [optional] # noqa: E501 - date_time (datetime): [optional] # noqa: E501 - uuid (str): [optional] # noqa: E501 - uuid_no_example (str): [optional] # noqa: E501 - pattern_with_digits (str): A string that is a 10 digit number. Can have leading zeros.. [optional] # noqa: E501 - pattern_with_digits_and_delimiter (str): A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + + class properties: + + + class number( + schemas.NumberSchema + ): + + + class MetaOapg: + inclusive_maximum = 543.2 + inclusive_minimum = 32.1 + multiple_of = 32.5 + byte = schemas.StrSchema + date = schemas.DateSchema + + + class password( + schemas.StrSchema + ): + + + class MetaOapg: + format = 'password' + max_length = 64 + min_length = 10 + + + class integer( + schemas.IntSchema + ): + + + class MetaOapg: + inclusive_maximum = 100 + inclusive_minimum = 10 + multiple_of = 2 + int32 = schemas.Int32Schema + + + class int32withValidations( + schemas.Int32Schema + ): + + + class MetaOapg: + format = 'int32' + inclusive_maximum = 200 + inclusive_minimum = 20 + int64 = schemas.Int64Schema + + + class _float( + schemas.Float32Schema + ): + + + class MetaOapg: + format = 'float' + inclusive_maximum = 987.6 + inclusive_minimum = 54.3 + float32 = schemas.Float32Schema + + + class double( + schemas.Float64Schema + ): + + + class MetaOapg: + format = 'double' + inclusive_maximum = 123.4 + inclusive_minimum = 67.8 + float64 = schemas.Float64Schema + + + class arrayWithUniqueItems( + schemas.ListSchema + ): + + + class MetaOapg: + unique_items = True + items = schemas.NumberSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'arrayWithUniqueItems': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class string( + schemas.StrSchema + ): + + + class MetaOapg: + regex=[{ + 'pattern': r'[a-z]', # noqa: E501 + 'flags': ( + re.IGNORECASE + ) + }] + binary = schemas.BinarySchema + dateTime = schemas.DateTimeSchema + uuid = schemas.UUIDSchema + uuidNoExample = schemas.UUIDSchema + + + class pattern_with_digits( + schemas.StrSchema + ): + + + class MetaOapg: + regex=[{ + 'pattern': r'^\d{10}$', # noqa: E501 + }] + + + class pattern_with_digits_and_delimiter( + schemas.StrSchema + ): + + + class MetaOapg: + regex=[{ + 'pattern': r'^image_\d{1,3}$', # noqa: E501 + 'flags': ( + re.IGNORECASE + ) + }] + noneProp = schemas.NoneSchema + __annotations__ = { + "number": number, + "byte": byte, + "date": date, + "password": password, + "integer": integer, + "int32": int32, + "int32withValidations": int32withValidations, + "int64": int64, + "float": _float, + "float32": float32, + "double": double, + "float64": float64, + "arrayWithUniqueItems": arrayWithUniqueItems, + "string": string, + "binary": binary, + "dateTime": dateTime, + "uuid": uuid, + "uuidNoExample": uuidNoExample, + "pattern_with_digits": pattern_with_digits, + "pattern_with_digits_and_delimiter": pattern_with_digits_and_delimiter, + "noneProp": noneProp, + } + + date: MetaOapg.properties.date + number: MetaOapg.properties.number + password: MetaOapg.properties.password + byte: MetaOapg.properties.byte + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["byte"]) -> MetaOapg.properties.byte: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date"]) -> MetaOapg.properties.date: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["password"]) -> MetaOapg.properties.password: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["integer"]) -> MetaOapg.properties.integer: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int32"]) -> MetaOapg.properties.int32: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int32withValidations"]) -> MetaOapg.properties.int32withValidations: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int64"]) -> MetaOapg.properties.int64: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float"]) -> MetaOapg.properties._float: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float32"]) -> MetaOapg.properties.float32: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["double"]) -> MetaOapg.properties.double: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float64"]) -> MetaOapg.properties.float64: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["arrayWithUniqueItems"]) -> MetaOapg.properties.arrayWithUniqueItems: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["string"]) -> MetaOapg.properties.string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["binary"]) -> MetaOapg.properties.binary: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["dateTime"]) -> MetaOapg.properties.dateTime: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["uuid"]) -> MetaOapg.properties.uuid: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["uuidNoExample"]) -> MetaOapg.properties.uuidNoExample: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["pattern_with_digits"]) -> MetaOapg.properties.pattern_with_digits: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["pattern_with_digits_and_delimiter"]) -> MetaOapg.properties.pattern_with_digits_and_delimiter: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["noneProp"]) -> MetaOapg.properties.noneProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["number", "byte", "date", "password", "integer", "int32", "int32withValidations", "int64", "float", "float32", "double", "float64", "arrayWithUniqueItems", "string", "binary", "dateTime", "uuid", "uuidNoExample", "pattern_with_digits", "pattern_with_digits_and_delimiter", "noneProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["byte"]) -> MetaOapg.properties.byte: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date"]) -> MetaOapg.properties.date: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["password"]) -> MetaOapg.properties.password: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["integer"]) -> typing.Union[MetaOapg.properties.integer, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int32"]) -> typing.Union[MetaOapg.properties.int32, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int32withValidations"]) -> typing.Union[MetaOapg.properties.int32withValidations, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int64"]) -> typing.Union[MetaOapg.properties.int64, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float"]) -> typing.Union[MetaOapg.properties._float, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float32"]) -> typing.Union[MetaOapg.properties.float32, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["double"]) -> typing.Union[MetaOapg.properties.double, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float64"]) -> typing.Union[MetaOapg.properties.float64, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["arrayWithUniqueItems"]) -> typing.Union[MetaOapg.properties.arrayWithUniqueItems, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["string"]) -> typing.Union[MetaOapg.properties.string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["binary"]) -> typing.Union[MetaOapg.properties.binary, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["dateTime"]) -> typing.Union[MetaOapg.properties.dateTime, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["uuid"]) -> typing.Union[MetaOapg.properties.uuid, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["uuidNoExample"]) -> typing.Union[MetaOapg.properties.uuidNoExample, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["pattern_with_digits"]) -> typing.Union[MetaOapg.properties.pattern_with_digits, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["pattern_with_digits_and_delimiter"]) -> typing.Union[MetaOapg.properties.pattern_with_digits_and_delimiter, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["noneProp"]) -> typing.Union[MetaOapg.properties.noneProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["number", "byte", "date", "password", "integer", "int32", "int32withValidations", "int64", "float", "float32", "double", "float64", "arrayWithUniqueItems", "string", "binary", "dateTime", "uuid", "uuidNoExample", "pattern_with_digits", "pattern_with_digits_and_delimiter", "noneProp", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.number = number - self.byte = byte - self.date = date - self.password = password - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, number, byte, date, password, *args, **kwargs): # noqa: E501 - """FormatTest - a model defined in OpenAPI - - Args: - number (float): - byte (str): - date (date): - password (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - integer (int): [optional] # noqa: E501 - int32 (int): [optional] # noqa: E501 - int64 (int): [optional] # noqa: E501 - float (float): [optional] # noqa: E501 - double (float): [optional] # noqa: E501 - string (str): [optional] # noqa: E501 - binary (file_type): [optional] # noqa: E501 - date_time (datetime): [optional] # noqa: E501 - uuid (str): [optional] # noqa: E501 - uuid_no_example (str): [optional] # noqa: E501 - pattern_with_digits (str): A string that is a 10 digit number. Can have leading zeros.. [optional] # noqa: E501 - pattern_with_digits_and_delimiter (str): A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.number = number - self.byte = byte - self.date = date - self.password = password - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + date: typing.Union[MetaOapg.properties.date, str, date, ], + number: typing.Union[MetaOapg.properties.number, decimal.Decimal, int, float, ], + password: typing.Union[MetaOapg.properties.password, str, ], + byte: typing.Union[MetaOapg.properties.byte, str, ], + integer: typing.Union[MetaOapg.properties.integer, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int32: typing.Union[MetaOapg.properties.int32, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int32withValidations: typing.Union[MetaOapg.properties.int32withValidations, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int64: typing.Union[MetaOapg.properties.int64, decimal.Decimal, int, schemas.Unset] = schemas.unset, + float32: typing.Union[MetaOapg.properties.float32, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + double: typing.Union[MetaOapg.properties.double, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + float64: typing.Union[MetaOapg.properties.float64, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + arrayWithUniqueItems: typing.Union[MetaOapg.properties.arrayWithUniqueItems, list, tuple, schemas.Unset] = schemas.unset, + string: typing.Union[MetaOapg.properties.string, str, schemas.Unset] = schemas.unset, + binary: typing.Union[MetaOapg.properties.binary, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + dateTime: typing.Union[MetaOapg.properties.dateTime, str, datetime, schemas.Unset] = schemas.unset, + uuid: typing.Union[MetaOapg.properties.uuid, str, uuid.UUID, schemas.Unset] = schemas.unset, + uuidNoExample: typing.Union[MetaOapg.properties.uuidNoExample, str, uuid.UUID, schemas.Unset] = schemas.unset, + pattern_with_digits: typing.Union[MetaOapg.properties.pattern_with_digits, str, schemas.Unset] = schemas.unset, + pattern_with_digits_and_delimiter: typing.Union[MetaOapg.properties.pattern_with_digits_and_delimiter, str, schemas.Unset] = schemas.unset, + noneProp: typing.Union[MetaOapg.properties.noneProp, None, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'FormatTest': + return super().__new__( + cls, + *args, + date=date, + number=number, + password=password, + byte=byte, + integer=integer, + int32=int32, + int32withValidations=int32withValidations, + int64=int64, + float32=float32, + double=double, + float64=float64, + arrayWithUniqueItems=arrayWithUniqueItems, + string=string, + binary=binary, + dateTime=dateTime, + uuid=uuid, + uuidNoExample=uuidNoExample, + pattern_with_digits=pattern_with_digits, + pattern_with_digits_and_delimiter=pattern_with_digits_and_delimiter, + noneProp=noneProp, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/format_test.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.pyi new file mode 100644 index 0000000000..dc49d47fd8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.pyi @@ -0,0 +1,354 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class FormatTest( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "date", + "number", + "password", + "byte", + } + + class properties: + + + class number( + schemas.NumberSchema + ): + pass + byte = schemas.StrSchema + date = schemas.DateSchema + + + class password( + schemas.StrSchema + ): + pass + + + class integer( + schemas.IntSchema + ): + pass + int32 = schemas.Int32Schema + + + class int32withValidations( + schemas.Int32Schema + ): + pass + int64 = schemas.Int64Schema + + + class _float( + schemas.Float32Schema + ): + pass + float32 = schemas.Float32Schema + + + class double( + schemas.Float64Schema + ): + pass + float64 = schemas.Float64Schema + + + class arrayWithUniqueItems( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.NumberSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]], typing.List[typing.Union[MetaOapg.items, decimal.Decimal, int, float, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'arrayWithUniqueItems': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class string( + schemas.StrSchema + ): + pass + binary = schemas.BinarySchema + dateTime = schemas.DateTimeSchema + uuid = schemas.UUIDSchema + uuidNoExample = schemas.UUIDSchema + + + class pattern_with_digits( + schemas.StrSchema + ): + pass + + + class pattern_with_digits_and_delimiter( + schemas.StrSchema + ): + pass + noneProp = schemas.NoneSchema + __annotations__ = { + "number": number, + "byte": byte, + "date": date, + "password": password, + "integer": integer, + "int32": int32, + "int32withValidations": int32withValidations, + "int64": int64, + "float": _float, + "float32": float32, + "double": double, + "float64": float64, + "arrayWithUniqueItems": arrayWithUniqueItems, + "string": string, + "binary": binary, + "dateTime": dateTime, + "uuid": uuid, + "uuidNoExample": uuidNoExample, + "pattern_with_digits": pattern_with_digits, + "pattern_with_digits_and_delimiter": pattern_with_digits_and_delimiter, + "noneProp": noneProp, + } + + date: MetaOapg.properties.date + number: MetaOapg.properties.number + password: MetaOapg.properties.password + byte: MetaOapg.properties.byte + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["byte"]) -> MetaOapg.properties.byte: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date"]) -> MetaOapg.properties.date: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["password"]) -> MetaOapg.properties.password: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["integer"]) -> MetaOapg.properties.integer: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int32"]) -> MetaOapg.properties.int32: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int32withValidations"]) -> MetaOapg.properties.int32withValidations: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int64"]) -> MetaOapg.properties.int64: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float"]) -> MetaOapg.properties._float: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float32"]) -> MetaOapg.properties.float32: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["double"]) -> MetaOapg.properties.double: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float64"]) -> MetaOapg.properties.float64: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["arrayWithUniqueItems"]) -> MetaOapg.properties.arrayWithUniqueItems: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["string"]) -> MetaOapg.properties.string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["binary"]) -> MetaOapg.properties.binary: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["dateTime"]) -> MetaOapg.properties.dateTime: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["uuid"]) -> MetaOapg.properties.uuid: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["uuidNoExample"]) -> MetaOapg.properties.uuidNoExample: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["pattern_with_digits"]) -> MetaOapg.properties.pattern_with_digits: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["pattern_with_digits_and_delimiter"]) -> MetaOapg.properties.pattern_with_digits_and_delimiter: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["noneProp"]) -> MetaOapg.properties.noneProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["number", "byte", "date", "password", "integer", "int32", "int32withValidations", "int64", "float", "float32", "double", "float64", "arrayWithUniqueItems", "string", "binary", "dateTime", "uuid", "uuidNoExample", "pattern_with_digits", "pattern_with_digits_and_delimiter", "noneProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["byte"]) -> MetaOapg.properties.byte: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date"]) -> MetaOapg.properties.date: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["password"]) -> MetaOapg.properties.password: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["integer"]) -> typing.Union[MetaOapg.properties.integer, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int32"]) -> typing.Union[MetaOapg.properties.int32, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int32withValidations"]) -> typing.Union[MetaOapg.properties.int32withValidations, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int64"]) -> typing.Union[MetaOapg.properties.int64, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float"]) -> typing.Union[MetaOapg.properties._float, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float32"]) -> typing.Union[MetaOapg.properties.float32, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["double"]) -> typing.Union[MetaOapg.properties.double, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float64"]) -> typing.Union[MetaOapg.properties.float64, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["arrayWithUniqueItems"]) -> typing.Union[MetaOapg.properties.arrayWithUniqueItems, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["string"]) -> typing.Union[MetaOapg.properties.string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["binary"]) -> typing.Union[MetaOapg.properties.binary, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["dateTime"]) -> typing.Union[MetaOapg.properties.dateTime, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["uuid"]) -> typing.Union[MetaOapg.properties.uuid, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["uuidNoExample"]) -> typing.Union[MetaOapg.properties.uuidNoExample, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["pattern_with_digits"]) -> typing.Union[MetaOapg.properties.pattern_with_digits, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["pattern_with_digits_and_delimiter"]) -> typing.Union[MetaOapg.properties.pattern_with_digits_and_delimiter, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["noneProp"]) -> typing.Union[MetaOapg.properties.noneProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["number", "byte", "date", "password", "integer", "int32", "int32withValidations", "int64", "float", "float32", "double", "float64", "arrayWithUniqueItems", "string", "binary", "dateTime", "uuid", "uuidNoExample", "pattern_with_digits", "pattern_with_digits_and_delimiter", "noneProp", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + date: typing.Union[MetaOapg.properties.date, str, date, ], + number: typing.Union[MetaOapg.properties.number, decimal.Decimal, int, float, ], + password: typing.Union[MetaOapg.properties.password, str, ], + byte: typing.Union[MetaOapg.properties.byte, str, ], + integer: typing.Union[MetaOapg.properties.integer, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int32: typing.Union[MetaOapg.properties.int32, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int32withValidations: typing.Union[MetaOapg.properties.int32withValidations, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int64: typing.Union[MetaOapg.properties.int64, decimal.Decimal, int, schemas.Unset] = schemas.unset, + float32: typing.Union[MetaOapg.properties.float32, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + double: typing.Union[MetaOapg.properties.double, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + float64: typing.Union[MetaOapg.properties.float64, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + arrayWithUniqueItems: typing.Union[MetaOapg.properties.arrayWithUniqueItems, list, tuple, schemas.Unset] = schemas.unset, + string: typing.Union[MetaOapg.properties.string, str, schemas.Unset] = schemas.unset, + binary: typing.Union[MetaOapg.properties.binary, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + dateTime: typing.Union[MetaOapg.properties.dateTime, str, datetime, schemas.Unset] = schemas.unset, + uuid: typing.Union[MetaOapg.properties.uuid, str, uuid.UUID, schemas.Unset] = schemas.unset, + uuidNoExample: typing.Union[MetaOapg.properties.uuidNoExample, str, uuid.UUID, schemas.Unset] = schemas.unset, + pattern_with_digits: typing.Union[MetaOapg.properties.pattern_with_digits, str, schemas.Unset] = schemas.unset, + pattern_with_digits_and_delimiter: typing.Union[MetaOapg.properties.pattern_with_digits_and_delimiter, str, schemas.Unset] = schemas.unset, + noneProp: typing.Union[MetaOapg.properties.noneProp, None, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'FormatTest': + return super().__new__( + cls, + *args, + date=date, + number=number, + password=password, + byte=byte, + integer=integer, + int32=int32, + int32withValidations=int32withValidations, + int64=int64, + float32=float32, + double=double, + float64=float64, + arrayWithUniqueItems=arrayWithUniqueItems, + string=string, + binary=binary, + dateTime=dateTime, + uuid=uuid, + uuidNoExample=uuidNoExample, + pattern_with_digits=pattern_with_digits, + pattern_with_digits_and_delimiter=pattern_with_digits_and_delimiter, + noneProp=noneProp, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/from_schema.py b/samples/openapi3/client/petstore/python/petstore_api/model/from_schema.py new file mode 100644 index 0000000000..556b85187c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/from_schema.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class FromSchema( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + data = schemas.StrSchema + id = schemas.IntSchema + __annotations__ = { + "data": data, + "id": id, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["data"]) -> MetaOapg.properties.data: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["data", "id", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["data"]) -> typing.Union[MetaOapg.properties.data, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["data", "id", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + data: typing.Union[MetaOapg.properties.data, str, schemas.Unset] = schemas.unset, + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'FromSchema': + return super().__new__( + cls, + *args, + data=data, + id=id, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/from_schema.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/from_schema.pyi new file mode 100644 index 0000000000..556b85187c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/from_schema.pyi @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class FromSchema( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + data = schemas.StrSchema + id = schemas.IntSchema + __annotations__ = { + "data": data, + "id": id, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["data"]) -> MetaOapg.properties.data: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["data", "id", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["data"]) -> typing.Union[MetaOapg.properties.data, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["data", "id", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + data: typing.Union[MetaOapg.properties.data, str, schemas.Unset] = schemas.unset, + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'FromSchema': + return super().__new__( + cls, + *args, + data=data, + id=id, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py index 79952ac853..056b33f22f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,339 +9,89 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.apple import Apple - from petstore_api.model.banana import Banana - globals()['Apple'] = Apple - globals()['Banana'] = Banana - - -class Fruit(ModelComposed): +class Fruit( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - ('cultivar',): { - 'regex': { - 'pattern': r'^[a-zA-Z\s]*$', # noqa: E501 - }, - }, - ('origin',): { - 'regex': { - 'pattern': r'^[A-Z\s]*$', # noqa: E501 - 'flags': (re.IGNORECASE) - }, - }, - } + class MetaOapg: + + class properties: + color = schemas.StrSchema + __annotations__ = { + "color": color, + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Apple, + Banana, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["color"]) -> MetaOapg.properties.color: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["color", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["color"]) -> typing.Union[MetaOapg.properties.color, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["color", ], str]): + return super().get_item_oapg(name) + - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + color: typing.Union[MetaOapg.properties.color, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Fruit': + return super().__new__( + cls, + *args, + color=color, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'cultivar': (str,), # noqa: E501 - 'length_cm': (float,), # noqa: E501 - 'color': (str,), # noqa: E501 - 'origin': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'cultivar': 'cultivar', # noqa: E501 - 'length_cm': 'lengthCm', # noqa: E501 - 'color': 'color', # noqa: E501 - 'origin': 'origin', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Fruit - a model defined in OpenAPI - - Keyword Args: - cultivar (str): - length_cm (float): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - color (str): [optional] # noqa: E501 - origin (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Fruit - a model defined in OpenAPI - - Keyword Args: - cultivar (str): - length_cm (float): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - color (str): [optional] # noqa: E501 - origin (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - Apple, - Banana, - ], - } +from petstore_api.model.apple import Apple +from petstore_api.model.banana import Banana diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.pyi new file mode 100644 index 0000000000..056b33f22f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.pyi @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Fruit( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + color = schemas.StrSchema + __annotations__ = { + "color": color, + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Apple, + Banana, + ] + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["color"]) -> MetaOapg.properties.color: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["color", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["color"]) -> typing.Union[MetaOapg.properties.color, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["color", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + color: typing.Union[MetaOapg.properties.color, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Fruit': + return super().__new__( + cls, + *args, + color=color, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.apple import Apple +from petstore_api.model.banana import Banana diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py index 62fdc158f5..18879cd45c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,329 +9,62 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.apple_req import AppleReq - from petstore_api.model.banana_req import BananaReq - globals()['AppleReq'] = AppleReq - globals()['BananaReq'] = BananaReq - - -class FruitReq(ModelComposed): +class FruitReq( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'mealy': (bool,), # noqa: E501 - 'sweet': (bool,), # noqa: E501 - 'cultivar': (str,), # noqa: E501 - 'length_cm': (float,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None + class MetaOapg: + one_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + AppleReq, + BananaReq, + ] - attribute_map = { - 'mealy': 'mealy', # noqa: E501 - 'sweet': 'sweet', # noqa: E501 - 'cultivar': 'cultivar', # noqa: E501 - 'length_cm': 'lengthCm', # noqa: E501 - } + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'FruitReq': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """FruitReq - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - mealy (bool): [optional] # noqa: E501 - sweet (bool): [optional] # noqa: E501 - cultivar (str): [optional] # noqa: E501 - length_cm (float): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """FruitReq - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - mealy (bool): [optional] # noqa: E501 - sweet (bool): [optional] # noqa: E501 - cultivar (str): [optional] # noqa: E501 - length_cm (float): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - AppleReq, - BananaReq, - none_type, - ], - } +from petstore_api.model.apple_req import AppleReq +from petstore_api.model.banana_req import BananaReq diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.pyi new file mode 100644 index 0000000000..18879cd45c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.pyi @@ -0,0 +1,70 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class FruitReq( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + one_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + AppleReq, + BananaReq, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'FruitReq': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.apple_req import AppleReq +from petstore_api.model.banana_req import BananaReq diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py index 93f102967f..5646a4704e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,339 +9,89 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.apple import Apple - from petstore_api.model.banana import Banana - globals()['Apple'] = Apple - globals()['Banana'] = Banana - - -class GmFruit(ModelComposed): +class GmFruit( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - ('cultivar',): { - 'regex': { - 'pattern': r'^[a-zA-Z\s]*$', # noqa: E501 - }, - }, - ('origin',): { - 'regex': { - 'pattern': r'^[A-Z\s]*$', # noqa: E501 - 'flags': (re.IGNORECASE) - }, - }, - } + class MetaOapg: + + class properties: + color = schemas.StrSchema + __annotations__ = { + "color": color, + } + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Apple, + Banana, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["color"]) -> MetaOapg.properties.color: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["color", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["color"]) -> typing.Union[MetaOapg.properties.color, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["color", ], str]): + return super().get_item_oapg(name) + - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + color: typing.Union[MetaOapg.properties.color, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'GmFruit': + return super().__new__( + cls, + *args, + color=color, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'cultivar': (str,), # noqa: E501 - 'length_cm': (float,), # noqa: E501 - 'color': (str,), # noqa: E501 - 'origin': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'cultivar': 'cultivar', # noqa: E501 - 'length_cm': 'lengthCm', # noqa: E501 - 'color': 'color', # noqa: E501 - 'origin': 'origin', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """GmFruit - a model defined in OpenAPI - - Keyword Args: - cultivar (str): - length_cm (float): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - color (str): [optional] # noqa: E501 - origin (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """GmFruit - a model defined in OpenAPI - - Keyword Args: - cultivar (str): - length_cm (float): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - color (str): [optional] # noqa: E501 - origin (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - Apple, - Banana, - ], - 'allOf': [ - ], - 'oneOf': [ - ], - } +from petstore_api.model.apple import Apple +from petstore_api.model.banana import Banana diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.pyi new file mode 100644 index 0000000000..5646a4704e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.pyi @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class GmFruit( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + color = schemas.StrSchema + __annotations__ = { + "color": color, + } + + @classmethod + @functools.lru_cache() + def any_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Apple, + Banana, + ] + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["color"]) -> MetaOapg.properties.color: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["color", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["color"]) -> typing.Union[MetaOapg.properties.color, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["color", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + color: typing.Union[MetaOapg.properties.color, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'GmFruit': + return super().__new__( + cls, + *args, + color=color, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.apple import Apple +from petstore_api.model.banana import Banana diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py index f6d1b0bb20..838d96a814 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,277 +9,87 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.child_cat import ChildCat - from petstore_api.model.parent_pet import ParentPet - globals()['ChildCat'] = ChildCat - globals()['ParentPet'] = ParentPet - - -class GrandparentAnimal(ModelNormal): +class GrandparentAnimal( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'pet_type': (str,), # noqa: E501 + class MetaOapg: + required = { + "pet_type", } + + @staticmethod + def discriminator(): + return { + 'pet_type': { + 'ChildCat': ChildCat, + 'ParentPet': ParentPet, + } + } + + class properties: + pet_type = schemas.StrSchema + __annotations__ = { + "pet_type": pet_type, + } + + pet_type: MetaOapg.properties.pet_type + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["pet_type"]) -> MetaOapg.properties.pet_type: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["pet_type", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["pet_type"]) -> MetaOapg.properties.pet_type: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["pet_type", ], str]): + return super().get_item_oapg(name) + - @cached_property - def discriminator(): - lazy_import() - val = { - 'ChildCat': ChildCat, - 'ParentPet': ParentPet, - } - if not val: - return None - return {'pet_type': val} + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + pet_type: typing.Union[MetaOapg.properties.pet_type, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'GrandparentAnimal': + return super().__new__( + cls, + *args, + pet_type=pet_type, + _configuration=_configuration, + **kwargs, + ) - attribute_map = { - 'pet_type': 'pet_type', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, pet_type, *args, **kwargs): # noqa: E501 - """GrandparentAnimal - a model defined in OpenAPI - - Args: - pet_type (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.pet_type = pet_type - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, pet_type, *args, **kwargs): # noqa: E501 - """GrandparentAnimal - a model defined in OpenAPI - - Args: - pet_type (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.pet_type = pet_type - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.child_cat import ChildCat +from petstore_api.model.parent_pet import ParentPet diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.pyi new file mode 100644 index 0000000000..838d96a814 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.pyi @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class GrandparentAnimal( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "pet_type", + } + + @staticmethod + def discriminator(): + return { + 'pet_type': { + 'ChildCat': ChildCat, + 'ParentPet': ParentPet, + } + } + + class properties: + pet_type = schemas.StrSchema + __annotations__ = { + "pet_type": pet_type, + } + + pet_type: MetaOapg.properties.pet_type + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["pet_type"]) -> MetaOapg.properties.pet_type: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["pet_type", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["pet_type"]) -> MetaOapg.properties.pet_type: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["pet_type", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + pet_type: typing.Union[MetaOapg.properties.pet_type, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'GrandparentAnimal': + return super().__new__( + cls, + *args, + pet_type=pet_type, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.child_cat import ChildCat +from petstore_api.model.parent_pet import ParentPet diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py index 1ccc67be07..f56f17aad8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,263 +9,80 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class HasOnlyReadOnly(ModelNormal): +class HasOnlyReadOnly( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + bar = schemas.StrSchema + foo = schemas.StrSchema + __annotations__ = { + "bar": bar, + "foo": foo, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", "foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", "foo", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'bar': (str,), # noqa: E501 - 'foo': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'bar': 'bar', # noqa: E501 - 'foo': 'foo', # noqa: E501 - } - - read_only_vars = { - 'bar', # noqa: E501 - 'foo', # noqa: E501 - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """HasOnlyReadOnly - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - bar (str): [optional] # noqa: E501 - foo (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """HasOnlyReadOnly - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - bar (str): [optional] # noqa: E501 - foo (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'HasOnlyReadOnly': + return super().__new__( + cls, + *args, + bar=bar, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.pyi new file mode 100644 index 0000000000..f56f17aad8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.pyi @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class HasOnlyReadOnly( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + bar = schemas.StrSchema + foo = schemas.StrSchema + __annotations__ = { + "bar": bar, + "foo": foo, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["foo"]) -> MetaOapg.properties.foo: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", "foo", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["foo"]) -> typing.Union[MetaOapg.properties.foo, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", "foo", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + foo: typing.Union[MetaOapg.properties.foo, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'HasOnlyReadOnly': + return super().__new__( + cls, + *args, + bar=bar, + foo=foo, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py index e0f31297fe..840a5ad96f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,91 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class HealthCheckResult(ModelNormal): +class HealthCheckResult( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'nullable_message': (str, none_type,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'nullable_message': 'NullableMessage', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """HealthCheckResult - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - nullable_message (str, none_type): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + + class NullableMessage( + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'NullableMessage': + return super().__new__( + cls, + *args, + _configuration=_configuration, ) + __annotations__ = { + "NullableMessage": NullableMessage, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["NullableMessage"]) -> MetaOapg.properties.NullableMessage: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["NullableMessage", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["NullableMessage"]) -> typing.Union[MetaOapg.properties.NullableMessage, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["NullableMessage", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """HealthCheckResult - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - nullable_message (str, none_type): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + NullableMessage: typing.Union[MetaOapg.properties.NullableMessage, None, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'HealthCheckResult': + return super().__new__( + cls, + *args, + NullableMessage=NullableMessage, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.pyi new file mode 100644 index 0000000000..840a5ad96f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.pyi @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class HealthCheckResult( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + """ + + + class MetaOapg: + + class properties: + + + class NullableMessage( + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'NullableMessage': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + __annotations__ = { + "NullableMessage": NullableMessage, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["NullableMessage"]) -> MetaOapg.properties.NullableMessage: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["NullableMessage", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["NullableMessage"]) -> typing.Union[MetaOapg.properties.NullableMessage, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["NullableMessage", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + NullableMessage: typing.Union[MetaOapg.properties.NullableMessage, None, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'HealthCheckResult': + return super().__new__( + cls, + *args, + NullableMessage=NullableMessage, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py index de46d21f64..18cd8df643 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,285 +9,46 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class IntegerEnum(ModelSimple): +class IntegerEnum( + schemas.EnumBase, + schemas.IntSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('value',): { - '0': 0, - '1': 1, - '2': 2, - }, - } - validations = { - } - - additional_properties_type = None - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (int,), + class MetaOapg: + enum_value_to_name = { + 0: "POSITIVE_0", + 1: "POSITIVE_1", + 2: "POSITIVE_2", } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """IntegerEnum - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int):, must be one of [0, 1, 2, ] # noqa: E501 - - Keyword Args: - value (int):, must be one of [0, 1, 2, ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """IntegerEnum - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int):, must be one of [0, 1, 2, ] # noqa: E501 - - Keyword Args: - value (int):, must be one of [0, 1, 2, ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self + + @schemas.classproperty + def POSITIVE_0(cls): + return cls(0) + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def POSITIVE_2(cls): + return cls(2) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.pyi new file mode 100644 index 0000000000..5f88412337 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.pyi @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IntegerEnum( + schemas.EnumBase, + schemas.IntSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def POSITIVE_0(cls): + return cls(0) + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def POSITIVE_2(cls): + return cls(2) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_big.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_big.py new file mode 100644 index 0000000000..615680bd12 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_big.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IntegerEnumBig( + schemas.EnumBase, + schemas.IntSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + 10: "POSITIVE_10", + 11: "POSITIVE_11", + 12: "POSITIVE_12", + } + + @schemas.classproperty + def POSITIVE_10(cls): + return cls(10) + + @schemas.classproperty + def POSITIVE_11(cls): + return cls(11) + + @schemas.classproperty + def POSITIVE_12(cls): + return cls(12) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_big.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_big.pyi new file mode 100644 index 0000000000..939443fcaa --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_big.pyi @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IntegerEnumBig( + schemas.EnumBase, + schemas.IntSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def POSITIVE_10(cls): + return cls(10) + + @schemas.classproperty + def POSITIVE_11(cls): + return cls(11) + + @schemas.classproperty + def POSITIVE_12(cls): + return cls(12) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py index 9091039a21..6ab7f2f213 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,275 +9,36 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class IntegerEnumOneValue(ModelSimple): +class IntegerEnumOneValue( + schemas.EnumBase, + schemas.IntSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('value',): { - '0': 0, - }, - } - validations = { - } - - additional_properties_type = None - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (int,), + class MetaOapg: + enum_value_to_name = { + 0: "POSITIVE_0", } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """IntegerEnumOneValue - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 - - Keyword Args: - value (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = 0 - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """IntegerEnumOneValue - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 - - Keyword Args: - value (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = 0 - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self + + @schemas.classproperty + def POSITIVE_0(cls): + return cls(0) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.pyi new file mode 100644 index 0000000000..1e911e5f24 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.pyi @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IntegerEnumOneValue( + schemas.EnumBase, + schemas.IntSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def POSITIVE_0(cls): + return cls(0) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py index f3473cffa2..87b44b36f1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,277 +9,46 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class IntegerEnumWithDefaultValue(ModelSimple): +class IntegerEnumWithDefaultValue( + schemas.EnumBase, + schemas.IntSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('value',): { - '0': 0, - '1': 1, - '2': 2, - }, - } - validations = { - } - - additional_properties_type = None - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (int,), + class MetaOapg: + enum_value_to_name = { + 0: "POSITIVE_0", + 1: "POSITIVE_1", + 2: "POSITIVE_2", } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """IntegerEnumWithDefaultValue - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 - - Keyword Args: - value (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = 0 - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """IntegerEnumWithDefaultValue - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 - - Keyword Args: - value (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = 0 - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self + + @schemas.classproperty + def POSITIVE_0(cls): + return cls(0) + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def POSITIVE_2(cls): + return cls(2) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.pyi new file mode 100644 index 0000000000..9ecbb8d163 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.pyi @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IntegerEnumWithDefaultValue( + schemas.EnumBase, + schemas.IntSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def POSITIVE_0(cls): + return cls(0) + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def POSITIVE_2(cls): + return cls(2) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_max10.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_max10.py new file mode 100644 index 0000000000..ac4541fad1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_max10.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IntegerMax10( + schemas.Int64Schema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'int64' + inclusive_maximum = 10 diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_max10.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/integer_max10.pyi new file mode 100644 index 0000000000..7e0c4ee337 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_max10.pyi @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IntegerMax10( + schemas.Int64Schema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_min15.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_min15.py new file mode 100644 index 0000000000..8424c1012a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_min15.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IntegerMin15( + schemas.Int64Schema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'int64' + inclusive_minimum = 15 diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_min15.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/integer_min15.pyi new file mode 100644 index 0000000000..73d4df6c23 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_min15.pyi @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IntegerMin15( + schemas.Int64Schema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py index 162f8fedb5..ddce91c9b9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,320 +9,124 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.shape_interface import ShapeInterface - from petstore_api.model.triangle_interface import TriangleInterface - globals()['ShapeInterface'] = ShapeInterface - globals()['TriangleInterface'] = TriangleInterface - - -class IsoscelesTriangle(ModelComposed): +class IsoscelesTriangle( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'shape_type': (str,), # noqa: E501 - 'triangle_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class triangleType( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "IsoscelesTriangle": "ISOSCELES_TRIANGLE", + } + + @schemas.classproperty + def ISOSCELES_TRIANGLE(cls): + return cls("IsoscelesTriangle") + __annotations__ = { + "triangleType": triangleType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["triangleType"]) -> typing.Union[MetaOapg.properties.triangleType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + triangleType: typing.Union[MetaOapg.properties.triangleType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + triangleType=triangleType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + TriangleInterface, + cls.all_of_1, + ] - attribute_map = { - 'shape_type': 'shapeType', # noqa: E501 - 'triangle_type': 'triangleType', # noqa: E501 - } + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'IsoscelesTriangle': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """IsoscelesTriangle - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - triangle_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """IsoscelesTriangle - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - triangle_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ShapeInterface, - TriangleInterface, - ], - 'oneOf': [ - ], - } +from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.pyi new file mode 100644 index 0000000000..5addd14160 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.pyi @@ -0,0 +1,126 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class IsoscelesTriangle( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class triangleType( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def ISOSCELES_TRIANGLE(cls): + return cls("IsoscelesTriangle") + __annotations__ = { + "triangleType": triangleType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["triangleType"]) -> typing.Union[MetaOapg.properties.triangleType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + triangleType: typing.Union[MetaOapg.properties.triangleType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + triangleType=triangleType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + TriangleInterface, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'IsoscelesTriangle': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request.py b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request.py new file mode 100644 index 0000000000..223b0c5512 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request.py @@ -0,0 +1,92 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class JSONPatchRequest( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class items( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + JSONPatchRequestAddReplaceTest, + JSONPatchRequestRemove, + JSONPatchRequestMoveCopy, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'items': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'JSONPatchRequest': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + +from petstore_api.model.json_patch_request_add_replace_test import JSONPatchRequestAddReplaceTest +from petstore_api.model.json_patch_request_move_copy import JSONPatchRequestMoveCopy +from petstore_api.model.json_patch_request_remove import JSONPatchRequestRemove diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request.pyi new file mode 100644 index 0000000000..223b0c5512 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request.pyi @@ -0,0 +1,92 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class JSONPatchRequest( + schemas.ListSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class items( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + JSONPatchRequestAddReplaceTest, + JSONPatchRequestRemove, + JSONPatchRequestMoveCopy, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'items': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'JSONPatchRequest': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + +from petstore_api.model.json_patch_request_add_replace_test import JSONPatchRequestAddReplaceTest +from petstore_api.model.json_patch_request_move_copy import JSONPatchRequestMoveCopy +from petstore_api.model.json_patch_request_remove import JSONPatchRequestRemove diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_add_replace_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_add_replace_test.py new file mode 100644 index 0000000000..bf95ea98af --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_add_replace_test.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class JSONPatchRequestAddReplaceTest( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "op", + "path", + "value", + } + + class properties: + path = schemas.StrSchema + value = schemas.AnyTypeSchema + + + class op( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "add": "ADD", + "replace": "REPLACE", + "test": "TEST", + } + + @schemas.classproperty + def ADD(cls): + return cls("add") + + @schemas.classproperty + def REPLACE(cls): + return cls("replace") + + @schemas.classproperty + def TEST(cls): + return cls("test") + __annotations__ = { + "path": path, + "value": value, + "op": op, + } + additional_properties = schemas.NotAnyTypeSchema + + op: MetaOapg.properties.op + path: MetaOapg.properties.path + value: MetaOapg.properties.value + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["value"]) -> MetaOapg.properties.value: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], typing_extensions.Literal["value"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["value"]) -> MetaOapg.properties.value: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], typing_extensions.Literal["value"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + op: typing.Union[MetaOapg.properties.op, str, ], + path: typing.Union[MetaOapg.properties.path, str, ], + value: typing.Union[MetaOapg.properties.value, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'JSONPatchRequestAddReplaceTest': + return super().__new__( + cls, + *args, + op=op, + path=path, + value=value, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_add_replace_test.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_add_replace_test.pyi new file mode 100644 index 0000000000..50e1a870bd --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_add_replace_test.pyi @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class JSONPatchRequestAddReplaceTest( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "op", + "path", + "value", + } + + class properties: + path = schemas.StrSchema + value = schemas.AnyTypeSchema + + + class op( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def ADD(cls): + return cls("add") + + @schemas.classproperty + def REPLACE(cls): + return cls("replace") + + @schemas.classproperty + def TEST(cls): + return cls("test") + __annotations__ = { + "path": path, + "value": value, + "op": op, + } + additional_properties = schemas.NotAnyTypeSchema + + op: MetaOapg.properties.op + path: MetaOapg.properties.path + value: MetaOapg.properties.value + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["value"]) -> MetaOapg.properties.value: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], typing_extensions.Literal["value"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["value"]) -> MetaOapg.properties.value: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], typing_extensions.Literal["value"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + op: typing.Union[MetaOapg.properties.op, str, ], + path: typing.Union[MetaOapg.properties.path, str, ], + value: typing.Union[MetaOapg.properties.value, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'JSONPatchRequestAddReplaceTest': + return super().__new__( + cls, + *args, + op=op, + path=path, + value=value, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_move_copy.py b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_move_copy.py new file mode 100644 index 0000000000..0b84fba097 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_move_copy.py @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class JSONPatchRequestMoveCopy( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "op", + "path", + "from", + } + + class properties: + _from = schemas.StrSchema + path = schemas.StrSchema + + + class op( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "move": "MOVE", + "copy": "COPY", + } + + @schemas.classproperty + def MOVE(cls): + return cls("move") + + @schemas.classproperty + def COPY(cls): + return cls("copy") + __annotations__ = { + "from": _from, + "path": path, + "op": op, + } + additional_properties = schemas.NotAnyTypeSchema + + op: MetaOapg.properties.op + path: MetaOapg.properties.path + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["from"]) -> MetaOapg.properties._from: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], typing_extensions.Literal["from"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["from"]) -> MetaOapg.properties._from: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], typing_extensions.Literal["from"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + op: typing.Union[MetaOapg.properties.op, str, ], + path: typing.Union[MetaOapg.properties.path, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'JSONPatchRequestMoveCopy': + return super().__new__( + cls, + *args, + op=op, + path=path, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_move_copy.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_move_copy.pyi new file mode 100644 index 0000000000..0654ee60fb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_move_copy.pyi @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class JSONPatchRequestMoveCopy( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "op", + "path", + "from", + } + + class properties: + _from = schemas.StrSchema + path = schemas.StrSchema + + + class op( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def MOVE(cls): + return cls("move") + + @schemas.classproperty + def COPY(cls): + return cls("copy") + __annotations__ = { + "from": _from, + "path": path, + "op": op, + } + additional_properties = schemas.NotAnyTypeSchema + + op: MetaOapg.properties.op + path: MetaOapg.properties.path + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["from"]) -> MetaOapg.properties._from: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], typing_extensions.Literal["from"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["from"]) -> MetaOapg.properties._from: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], typing_extensions.Literal["from"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + op: typing.Union[MetaOapg.properties.op, str, ], + path: typing.Union[MetaOapg.properties.path, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'JSONPatchRequestMoveCopy': + return super().__new__( + cls, + *args, + op=op, + path=path, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_remove.py b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_remove.py new file mode 100644 index 0000000000..4e15b41cef --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_remove.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class JSONPatchRequestRemove( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "op", + "path", + } + + class properties: + path = schemas.StrSchema + + + class op( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "remove": "REMOVE", + } + + @schemas.classproperty + def REMOVE(cls): + return cls("remove") + __annotations__ = { + "path": path, + "op": op, + } + additional_properties = schemas.NotAnyTypeSchema + + op: MetaOapg.properties.op + path: MetaOapg.properties.path + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + op: typing.Union[MetaOapg.properties.op, str, ], + path: typing.Union[MetaOapg.properties.path, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'JSONPatchRequestRemove': + return super().__new__( + cls, + *args, + op=op, + path=path, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_remove.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_remove.pyi new file mode 100644 index 0000000000..325cbe8a98 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/json_patch_request_remove.pyi @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class JSONPatchRequestRemove( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "op", + "path", + } + + class properties: + path = schemas.StrSchema + + + class op( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def REMOVE(cls): + return cls("remove") + __annotations__ = { + "path": path, + "op": op, + } + additional_properties = schemas.NotAnyTypeSchema + + op: MetaOapg.properties.op + path: MetaOapg.properties.path + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["op"]) -> MetaOapg.properties.op: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["path"]) -> MetaOapg.properties.path: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["op"], typing_extensions.Literal["path"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + op: typing.Union[MetaOapg.properties.op, str, ], + path: typing.Union[MetaOapg.properties.path, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'JSONPatchRequestRemove': + return super().__new__( + cls, + *args, + op=op, + path=path, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py index 0a2d927ea7..e90d419cc6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,343 +9,72 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.pig import Pig - from petstore_api.model.whale import Whale - from petstore_api.model.zebra import Zebra - globals()['Pig'] = Pig - globals()['Whale'] = Whale - globals()['Zebra'] = Zebra - - -class Mammal(ModelComposed): +class Mammal( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('type',): { - 'PLAINS': "plains", - 'MOUNTAIN': "mountain", - 'GREVYS': "grevys", - }, - } - validations = { - } + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'className': { + 'Pig': Pig, + 'whale': Whale, + 'zebra': Zebra, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Whale, + Zebra, + Pig, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Mammal': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'class_name': (str,), # noqa: E501 - 'has_baleen': (bool,), # noqa: E501 - 'has_teeth': (bool,), # noqa: E501 - 'type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - lazy_import() - val = { - 'Pig': Pig, - 'whale': Whale, - 'zebra': Zebra, - } - if not val: - return None - return {'class_name': val} - - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'has_baleen': 'hasBaleen', # noqa: E501 - 'has_teeth': 'hasTeeth', # noqa: E501 - 'type': 'type', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Mammal - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - has_baleen (bool): [optional] # noqa: E501 - has_teeth (bool): [optional] # noqa: E501 - type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Mammal - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - has_baleen (bool): [optional] # noqa: E501 - has_teeth (bool): [optional] # noqa: E501 - type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - Pig, - Whale, - Zebra, - ], - } +from petstore_api.model.pig import Pig +from petstore_api.model.whale import Whale +from petstore_api.model.zebra import Zebra diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mammal.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.pyi new file mode 100644 index 0000000000..e90d419cc6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.pyi @@ -0,0 +1,80 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Mammal( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'className': { + 'Pig': Pig, + 'whale': Whale, + 'zebra': Zebra, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Whale, + Zebra, + Pig, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Mammal': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.pig import Pig +from petstore_api.model.whale import Whale +from petstore_api.model.zebra import Zebra diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py index eccf9c9e61..031503142c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,279 +9,237 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.string_boolean_map import StringBooleanMap - globals()['StringBooleanMap'] = StringBooleanMap - - -class MapTest(ModelNormal): +class MapTest( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('map_of_enum_string',): { - 'UPPER': "UPPER", - 'LOWER': "lower", - }, - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'map_map_of_string': ({str: ({str: (str,)},)},), # noqa: E501 - 'map_of_enum_string': ({str: (str,)},), # noqa: E501 - 'direct_map': ({str: (bool,)},), # noqa: E501 - 'indirect_map': (StringBooleanMap,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'map_map_of_string': 'map_map_of_string', # noqa: E501 - 'map_of_enum_string': 'map_of_enum_string', # noqa: E501 - 'direct_map': 'direct_map', # noqa: E501 - 'indirect_map': 'indirect_map', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """MapTest - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 - map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 - direct_map ({str: (bool,)}): [optional] # noqa: E501 - indirect_map (StringBooleanMap): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + + class map_map_of_string( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, ], + ) -> 'map_map_of_string': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """MapTest - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 - map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 - direct_map ({str: (bool,)}): [optional] # noqa: E501 - indirect_map (StringBooleanMap): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + + + class map_of_enum_string( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "UPPER": "UPPER", + "lower": "LOWER", + } + + @schemas.classproperty + def UPPER(cls): + return cls("UPPER") + + @schemas.classproperty + def LOWER(cls): + return cls("lower") + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'map_of_enum_string': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, ) + + + class direct_map( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.BoolSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'direct_map': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @staticmethod + def indirect_map() -> typing.Type['StringBooleanMap']: + return StringBooleanMap + __annotations__ = { + "map_map_of_string": map_map_of_string, + "map_of_enum_string": map_of_enum_string, + "direct_map": direct_map, + "indirect_map": indirect_map, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_map_of_string"]) -> MetaOapg.properties.map_map_of_string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_of_enum_string"]) -> MetaOapg.properties.map_of_enum_string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["direct_map"]) -> MetaOapg.properties.direct_map: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["indirect_map"]) -> 'StringBooleanMap': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["map_map_of_string", "map_of_enum_string", "direct_map", "indirect_map", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_map_of_string"]) -> typing.Union[MetaOapg.properties.map_map_of_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_of_enum_string"]) -> typing.Union[MetaOapg.properties.map_of_enum_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["direct_map"]) -> typing.Union[MetaOapg.properties.direct_map, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["indirect_map"]) -> typing.Union['StringBooleanMap', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["map_map_of_string", "map_of_enum_string", "direct_map", "indirect_map", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + map_map_of_string: typing.Union[MetaOapg.properties.map_map_of_string, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_of_enum_string: typing.Union[MetaOapg.properties.map_of_enum_string, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + direct_map: typing.Union[MetaOapg.properties.direct_map, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + indirect_map: typing.Union['StringBooleanMap', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MapTest': + return super().__new__( + cls, + *args, + map_map_of_string=map_map_of_string, + map_of_enum_string=map_of_enum_string, + direct_map=direct_map, + indirect_map=indirect_map, + _configuration=_configuration, + **kwargs, + ) - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.string_boolean_map import StringBooleanMap diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/map_test.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.pyi new file mode 100644 index 0000000000..a89ebb2fc8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.pyi @@ -0,0 +1,238 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class MapTest( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class map_map_of_string( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, ], + ) -> 'map_map_of_string': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class map_of_enum_string( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def UPPER(cls): + return cls("UPPER") + + @schemas.classproperty + def LOWER(cls): + return cls("lower") + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'map_of_enum_string': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class direct_map( + schemas.DictSchema + ): + + + class MetaOapg: + additional_properties = schemas.BoolSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'direct_map': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @staticmethod + def indirect_map() -> typing.Type['StringBooleanMap']: + return StringBooleanMap + __annotations__ = { + "map_map_of_string": map_map_of_string, + "map_of_enum_string": map_of_enum_string, + "direct_map": direct_map, + "indirect_map": indirect_map, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_map_of_string"]) -> MetaOapg.properties.map_map_of_string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map_of_enum_string"]) -> MetaOapg.properties.map_of_enum_string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["direct_map"]) -> MetaOapg.properties.direct_map: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["indirect_map"]) -> 'StringBooleanMap': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["map_map_of_string", "map_of_enum_string", "direct_map", "indirect_map", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_map_of_string"]) -> typing.Union[MetaOapg.properties.map_map_of_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map_of_enum_string"]) -> typing.Union[MetaOapg.properties.map_of_enum_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["direct_map"]) -> typing.Union[MetaOapg.properties.direct_map, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["indirect_map"]) -> typing.Union['StringBooleanMap', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["map_map_of_string", "map_of_enum_string", "direct_map", "indirect_map", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + map_map_of_string: typing.Union[MetaOapg.properties.map_map_of_string, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + map_of_enum_string: typing.Union[MetaOapg.properties.map_of_enum_string, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + direct_map: typing.Union[MetaOapg.properties.direct_map, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + indirect_map: typing.Union['StringBooleanMap', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MapTest': + return super().__new__( + cls, + *args, + map_map_of_string=map_map_of_string, + map_of_enum_string=map_of_enum_string, + direct_map=direct_map, + indirect_map=indirect_map, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.string_boolean_map import StringBooleanMap diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py index 4d825b8dd4..b146d15b6a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,271 +9,123 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.animal import Animal - globals()['Animal'] = Animal - - -class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): +class MixedPropertiesAndAdditionalPropertiesClass( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'uuid': (str,), # noqa: E501 - 'date_time': (datetime,), # noqa: E501 - 'map': ({str: (Animal,)},), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'uuid': 'uuid', # noqa: E501 - 'date_time': 'dateTime', # noqa: E501 - 'map': 'map', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - uuid (str): [optional] # noqa: E501 - date_time (datetime): [optional] # noqa: E501 - map ({str: (Animal,)}): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + uuid = schemas.UUIDSchema + dateTime = schemas.DateTimeSchema + + + class map( + schemas.DictSchema + ): + + + class MetaOapg: + + @staticmethod + def additional_properties() -> typing.Type['Animal']: + return Animal + + def __getitem__(self, name: typing.Union[str, ]) -> 'Animal': + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> 'Animal': + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: 'Animal', + ) -> 'map': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, ) + __annotations__ = { + "uuid": uuid, + "dateTime": dateTime, + "map": map, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["uuid"]) -> MetaOapg.properties.uuid: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["dateTime"]) -> MetaOapg.properties.dateTime: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map"]) -> MetaOapg.properties.map: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["uuid", "dateTime", "map", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["uuid"]) -> typing.Union[MetaOapg.properties.uuid, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["dateTime"]) -> typing.Union[MetaOapg.properties.dateTime, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map"]) -> typing.Union[MetaOapg.properties.map, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["uuid", "dateTime", "map", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + uuid: typing.Union[MetaOapg.properties.uuid, str, uuid.UUID, schemas.Unset] = schemas.unset, + dateTime: typing.Union[MetaOapg.properties.dateTime, str, datetime, schemas.Unset] = schemas.unset, + map: typing.Union[MetaOapg.properties.map, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MixedPropertiesAndAdditionalPropertiesClass': + return super().__new__( + cls, + *args, + uuid=uuid, + dateTime=dateTime, + map=map, + _configuration=_configuration, + **kwargs, + ) - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - uuid (str): [optional] # noqa: E501 - date_time (datetime): [optional] # noqa: E501 - map ({str: (Animal,)}): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.pyi new file mode 100644 index 0000000000..b146d15b6a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.pyi @@ -0,0 +1,131 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class MixedPropertiesAndAdditionalPropertiesClass( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + uuid = schemas.UUIDSchema + dateTime = schemas.DateTimeSchema + + + class map( + schemas.DictSchema + ): + + + class MetaOapg: + + @staticmethod + def additional_properties() -> typing.Type['Animal']: + return Animal + + def __getitem__(self, name: typing.Union[str, ]) -> 'Animal': + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> 'Animal': + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: 'Animal', + ) -> 'map': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "uuid": uuid, + "dateTime": dateTime, + "map": map, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["uuid"]) -> MetaOapg.properties.uuid: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["dateTime"]) -> MetaOapg.properties.dateTime: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["map"]) -> MetaOapg.properties.map: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["uuid", "dateTime", "map", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["uuid"]) -> typing.Union[MetaOapg.properties.uuid, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["dateTime"]) -> typing.Union[MetaOapg.properties.dateTime, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["map"]) -> typing.Union[MetaOapg.properties.map, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["uuid", "dateTime", "map", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + uuid: typing.Union[MetaOapg.properties.uuid, str, uuid.UUID, schemas.Unset] = schemas.unset, + dateTime: typing.Union[MetaOapg.properties.dateTime, str, datetime, schemas.Unset] = schemas.unset, + map: typing.Union[MetaOapg.properties.map, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MixedPropertiesAndAdditionalPropertiesClass': + return super().__new__( + cls, + *args, + uuid=uuid, + dateTime=dateTime, + map=map, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.animal import Animal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py index 9bebea2423..7cdc34c576 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,261 +9,81 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Model200Response(ModelNormal): +class Model200Response( + schemas.AnyTypeSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + model with an invalid class name for python, starts with a number """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + name = schemas.Int32Schema + _class = schemas.StrSchema + __annotations__ = { + "name": name, + "class": _class, + } - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["class"]) -> MetaOapg.properties._class: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "class", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["class"]) -> typing.Union[MetaOapg.properties._class, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "class", ], str]): + return super().get_item_oapg(name) + - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'name': (int,), # noqa: E501 - '_class': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'name': 'name', # noqa: E501 - '_class': 'class', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Model200Response - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - name (int): [optional] # noqa: E501 - _class (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Model200Response - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - name (int): [optional] # noqa: E501 - _class (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + name: typing.Union[MetaOapg.properties.name, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Model200Response': + return super().__new__( + cls, + *args, + name=name, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.pyi new file mode 100644 index 0000000000..7cdc34c576 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.pyi @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Model200Response( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + model with an invalid class name for python, starts with a number + """ + + + class MetaOapg: + + class properties: + name = schemas.Int32Schema + _class = schemas.StrSchema + __annotations__ = { + "name": name, + "class": _class, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["class"]) -> MetaOapg.properties._class: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "class", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["class"]) -> typing.Union[MetaOapg.properties._class, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "class", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + name: typing.Union[MetaOapg.properties.name, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Model200Response': + return super().__new__( + cls, + *args, + name=name, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py index f3bd5123dd..1549dc1120 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,71 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class ModelReturn(ModelNormal): +class ModelReturn( + schemas.AnyTypeSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + Model for testing reserved words """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + _return = schemas.Int32Schema + __annotations__ = { + "return": _return, + } - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["return"]) -> MetaOapg.properties._return: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["return", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["return"]) -> typing.Union[MetaOapg.properties._return, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["return", ], str]): + return super().get_item_oapg(name) + - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - '_return': (int,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - '_return': 'return', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ModelReturn - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - _return (int): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ModelReturn - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - _return (int): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ModelReturn': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model_return.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.pyi new file mode 100644 index 0000000000..1549dc1120 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.pyi @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ModelReturn( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Model for testing reserved words + """ + + + class MetaOapg: + + class properties: + _return = schemas.Int32Schema + __annotations__ = { + "return": _return, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["return"]) -> MetaOapg.properties._return: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["return", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["return"]) -> typing.Union[MetaOapg.properties._return, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["return", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ModelReturn': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/money.py b/samples/openapi3/client/petstore/python/petstore_api/model/money.py new file mode 100644 index 0000000000..5804737d2f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/money.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Money( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "amount", + "currency", + } + + class properties: + amount = schemas.DecimalSchema + + @staticmethod + def currency() -> typing.Type['Currency']: + return Currency + __annotations__ = { + "amount": amount, + "currency": currency, + } + + amount: MetaOapg.properties.amount + currency: 'Currency' + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["amount"]) -> MetaOapg.properties.amount: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["currency"]) -> 'Currency': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["amount", "currency", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["amount"]) -> MetaOapg.properties.amount: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["currency"]) -> 'Currency': ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["amount", "currency", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + amount: typing.Union[MetaOapg.properties.amount, str, ], + currency: 'Currency', + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Money': + return super().__new__( + cls, + *args, + amount=amount, + currency=currency, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.currency import Currency diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/money.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/money.pyi new file mode 100644 index 0000000000..5804737d2f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/money.pyi @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Money( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "amount", + "currency", + } + + class properties: + amount = schemas.DecimalSchema + + @staticmethod + def currency() -> typing.Type['Currency']: + return Currency + __annotations__ = { + "amount": amount, + "currency": currency, + } + + amount: MetaOapg.properties.amount + currency: 'Currency' + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["amount"]) -> MetaOapg.properties.amount: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["currency"]) -> 'Currency': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["amount", "currency", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["amount"]) -> MetaOapg.properties.amount: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["currency"]) -> 'Currency': ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["amount", "currency", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + amount: typing.Union[MetaOapg.properties.amount, str, ], + currency: 'Currency', + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Money': + return super().__new__( + cls, + *args, + amount=amount, + currency=currency, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.currency import Currency diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/name.py b/samples/openapi3/client/petstore/python/petstore_api/model/name.py index aec8c8b900..e67d017f24 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/name.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,277 +9,96 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Name(ModelNormal): +class Name( + schemas.AnyTypeSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + Model for testing model name same as property name """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'name': (int,), # noqa: E501 - 'snake_case': (int,), # noqa: E501 - '_property': (str,), # noqa: E501 - '_123_number': (int,), # noqa: E501 + class MetaOapg: + required = { + "name", } + + class properties: + name = schemas.Int32Schema + snake_case = schemas.Int32Schema + _property = schemas.StrSchema + __annotations__ = { + "name": name, + "snake_case": snake_case, + "property": _property, + } - @cached_property - def discriminator(): - return None + + name: MetaOapg.properties.name + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["snake_case"]) -> MetaOapg.properties.snake_case: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["property"]) -> MetaOapg.properties._property: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "snake_case", "property", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["snake_case"]) -> typing.Union[MetaOapg.properties.snake_case, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["property"]) -> typing.Union[MetaOapg.properties._property, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "snake_case", "property", ], str]): + return super().get_item_oapg(name) + - - attribute_map = { - 'name': 'name', # noqa: E501 - 'snake_case': 'snake_case', # noqa: E501 - '_property': 'property', # noqa: E501 - '_123_number': '123Number', # noqa: E501 - } - - read_only_vars = { - 'snake_case', # noqa: E501 - '_123_number', # noqa: E501 - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 - """Name - a model defined in OpenAPI - - Args: - name (int): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - snake_case (int): [optional] # noqa: E501 - _property (str): [optional] # noqa: E501 - _123_number (int): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, name, *args, **kwargs): # noqa: E501 - """Name - a model defined in OpenAPI - - Args: - name (int): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - snake_case (int): [optional] # noqa: E501 - _property (str): [optional] # noqa: E501 - _123_number (int): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + name: typing.Union[MetaOapg.properties.name, decimal.Decimal, int, ], + snake_case: typing.Union[MetaOapg.properties.snake_case, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Name': + return super().__new__( + cls, + *args, + name=name, + snake_case=snake_case, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/name.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/name.pyi new file mode 100644 index 0000000000..e67d017f24 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/name.pyi @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Name( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Model for testing model name same as property name + """ + + + class MetaOapg: + required = { + "name", + } + + class properties: + name = schemas.Int32Schema + snake_case = schemas.Int32Schema + _property = schemas.StrSchema + __annotations__ = { + "name": name, + "snake_case": snake_case, + "property": _property, + } + + + name: MetaOapg.properties.name + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["snake_case"]) -> MetaOapg.properties.snake_case: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["property"]) -> MetaOapg.properties._property: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "snake_case", "property", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["snake_case"]) -> typing.Union[MetaOapg.properties.snake_case, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["property"]) -> typing.Union[MetaOapg.properties._property, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "snake_case", "property", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + name: typing.Union[MetaOapg.properties.name, decimal.Decimal, int, ], + snake_case: typing.Union[MetaOapg.properties.snake_case, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Name': + return super().__new__( + cls, + *args, + name=name, + snake_case=snake_case, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/no_additional_properties.py b/samples/openapi3/client/petstore/python/petstore_api/model/no_additional_properties.py new file mode 100644 index 0000000000..cacfe6027e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/no_additional_properties.py @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class NoAdditionalProperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "id", + } + + class properties: + id = schemas.Int64Schema + petId = schemas.Int64Schema + __annotations__ = { + "id": id, + "petId": petId, + } + additional_properties = schemas.NotAnyTypeSchema + + id: MetaOapg.properties.id + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["petId"]) -> MetaOapg.properties.petId: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["id"], typing_extensions.Literal["petId"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["petId"]) -> typing.Union[MetaOapg.properties.petId, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["id"], typing_extensions.Literal["petId"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, ], + petId: typing.Union[MetaOapg.properties.petId, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'NoAdditionalProperties': + return super().__new__( + cls, + *args, + id=id, + petId=petId, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/no_additional_properties.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/no_additional_properties.pyi new file mode 100644 index 0000000000..cacfe6027e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/no_additional_properties.pyi @@ -0,0 +1,84 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class NoAdditionalProperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "id", + } + + class properties: + id = schemas.Int64Schema + petId = schemas.Int64Schema + __annotations__ = { + "id": id, + "petId": petId, + } + additional_properties = schemas.NotAnyTypeSchema + + id: MetaOapg.properties.id + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["petId"]) -> MetaOapg.properties.petId: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["id"], typing_extensions.Literal["petId"], ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["petId"]) -> typing.Union[MetaOapg.properties.petId, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["id"], typing_extensions.Literal["petId"], ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, ], + petId: typing.Union[MetaOapg.properties.petId, decimal.Decimal, int, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'NoAdditionalProperties': + return super().__new__( + cls, + *args, + id=id, + petId=petId, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py index 0c6765a33c..0d3c13b457 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,305 +9,568 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class NullableClass(ModelNormal): +class NullableClass( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'integer_prop': (int, none_type,), # noqa: E501 - 'number_prop': (float, none_type,), # noqa: E501 - 'boolean_prop': (bool, none_type,), # noqa: E501 - 'string_prop': (str, none_type,), # noqa: E501 - 'date_prop': (date, none_type,), # noqa: E501 - 'datetime_prop': (datetime, none_type,), # noqa: E501 - 'array_nullable_prop': ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type,), # noqa: E501 - 'array_and_items_nullable_prop': ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type,), # noqa: E501 - 'array_items_nullable': ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type],), # noqa: E501 - 'object_nullable': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type,), # noqa: E501 - 'object_nullable_prop': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type,), # noqa: E501 - 'object_and_items_nullable_prop': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type,), # noqa: E501 - 'object_items_nullable': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)},), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'integer_prop': 'integer_prop', # noqa: E501 - 'number_prop': 'number_prop', # noqa: E501 - 'boolean_prop': 'boolean_prop', # noqa: E501 - 'string_prop': 'string_prop', # noqa: E501 - 'date_prop': 'date_prop', # noqa: E501 - 'datetime_prop': 'datetime_prop', # noqa: E501 - 'array_nullable_prop': 'array_nullable_prop', # noqa: E501 - 'array_and_items_nullable_prop': 'array_and_items_nullable_prop', # noqa: E501 - 'array_items_nullable': 'array_items_nullable', # noqa: E501 - 'object_nullable': 'object_nullable', # noqa: E501 - 'object_nullable_prop': 'object_nullable_prop', # noqa: E501 - 'object_and_items_nullable_prop': 'object_and_items_nullable_prop', # noqa: E501 - 'object_items_nullable': 'object_items_nullable', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """NullableClass - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - integer_prop (int, none_type): [optional] # noqa: E501 - number_prop (float, none_type): [optional] # noqa: E501 - boolean_prop (bool, none_type): [optional] # noqa: E501 - string_prop (str, none_type): [optional] # noqa: E501 - date_prop (date, none_type): [optional] # noqa: E501 - datetime_prop (datetime, none_type): [optional] # noqa: E501 - array_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type): [optional] # noqa: E501 - array_and_items_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type): [optional] # noqa: E501 - array_items_nullable ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type]): [optional] # noqa: E501 - object_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501 - object_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type): [optional] # noqa: E501 - object_and_items_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type): [optional] # noqa: E501 - object_items_nullable ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + + + class integer_prop( + schemas.IntBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneDecimalMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'integer_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """NullableClass - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - integer_prop (int, none_type): [optional] # noqa: E501 - number_prop (float, none_type): [optional] # noqa: E501 - boolean_prop (bool, none_type): [optional] # noqa: E501 - string_prop (str, none_type): [optional] # noqa: E501 - date_prop (date, none_type): [optional] # noqa: E501 - datetime_prop (datetime, none_type): [optional] # noqa: E501 - array_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type): [optional] # noqa: E501 - array_and_items_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type): [optional] # noqa: E501 - array_items_nullable ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type]): [optional] # noqa: E501 - object_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501 - object_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type): [optional] # noqa: E501 - object_and_items_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type): [optional] # noqa: E501 - object_items_nullable ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + + + class number_prop( + schemas.NumberBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneDecimalMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, decimal.Decimal, int, float, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'number_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, ) + + + class boolean_prop( + schemas.BoolBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneBoolMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, bool, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'boolean_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class string_prop( + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'string_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class date_prop( + schemas.DateBase, + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin + ): + + + class MetaOapg: + format = 'date' + + + def __new__( + cls, + *args: typing.Union[None, str, date, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'date_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class datetime_prop( + schemas.DateTimeBase, + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin + ): + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[None, str, datetime, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'datetime_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class array_nullable_prop( + schemas.ListBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneTupleMixin + ): + + + class MetaOapg: + items = schemas.DictSchema + + + def __new__( + cls, + *args: typing.Union[list, tuple, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_nullable_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class array_and_items_nullable_prop( + schemas.ListBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneTupleMixin + ): + + + class MetaOapg: + + + class items( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'items': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[list, tuple, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_and_items_nullable_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class array_items_nullable( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'items': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, None, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, None, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_items_nullable': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class object_nullable_prop( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + class MetaOapg: + additional_properties = schemas.DictSchema + + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, ], + ) -> 'object_nullable_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class object_and_items_nullable_prop( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + class MetaOapg: + + + class additional_properties( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, None, ], + ) -> 'object_and_items_nullable_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class object_items_nullable( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, None, ], + ) -> 'object_items_nullable': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "integer_prop": integer_prop, + "number_prop": number_prop, + "boolean_prop": boolean_prop, + "string_prop": string_prop, + "date_prop": date_prop, + "datetime_prop": datetime_prop, + "array_nullable_prop": array_nullable_prop, + "array_and_items_nullable_prop": array_and_items_nullable_prop, + "array_items_nullable": array_items_nullable, + "object_nullable_prop": object_nullable_prop, + "object_and_items_nullable_prop": object_and_items_nullable_prop, + "object_items_nullable": object_items_nullable, + } + + + class additional_properties( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["integer_prop"]) -> MetaOapg.properties.integer_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["number_prop"]) -> MetaOapg.properties.number_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["boolean_prop"]) -> MetaOapg.properties.boolean_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["string_prop"]) -> MetaOapg.properties.string_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date_prop"]) -> MetaOapg.properties.date_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["datetime_prop"]) -> MetaOapg.properties.datetime_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_nullable_prop"]) -> MetaOapg.properties.array_nullable_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_and_items_nullable_prop"]) -> MetaOapg.properties.array_and_items_nullable_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_items_nullable"]) -> MetaOapg.properties.array_items_nullable: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["object_nullable_prop"]) -> MetaOapg.properties.object_nullable_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["object_and_items_nullable_prop"]) -> MetaOapg.properties.object_and_items_nullable_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["object_items_nullable"]) -> MetaOapg.properties.object_items_nullable: ... + + @typing.overload + def __getitem__(self, name: str) -> MetaOapg.additional_properties: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["integer_prop"], typing_extensions.Literal["number_prop"], typing_extensions.Literal["boolean_prop"], typing_extensions.Literal["string_prop"], typing_extensions.Literal["date_prop"], typing_extensions.Literal["datetime_prop"], typing_extensions.Literal["array_nullable_prop"], typing_extensions.Literal["array_and_items_nullable_prop"], typing_extensions.Literal["array_items_nullable"], typing_extensions.Literal["object_nullable_prop"], typing_extensions.Literal["object_and_items_nullable_prop"], typing_extensions.Literal["object_items_nullable"], str, ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["integer_prop"]) -> typing.Union[MetaOapg.properties.integer_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["number_prop"]) -> typing.Union[MetaOapg.properties.number_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["boolean_prop"]) -> typing.Union[MetaOapg.properties.boolean_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["string_prop"]) -> typing.Union[MetaOapg.properties.string_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date_prop"]) -> typing.Union[MetaOapg.properties.date_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["datetime_prop"]) -> typing.Union[MetaOapg.properties.datetime_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_nullable_prop"]) -> typing.Union[MetaOapg.properties.array_nullable_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_and_items_nullable_prop"]) -> typing.Union[MetaOapg.properties.array_and_items_nullable_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_items_nullable"]) -> typing.Union[MetaOapg.properties.array_items_nullable, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["object_nullable_prop"]) -> typing.Union[MetaOapg.properties.object_nullable_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["object_and_items_nullable_prop"]) -> typing.Union[MetaOapg.properties.object_and_items_nullable_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["object_items_nullable"]) -> typing.Union[MetaOapg.properties.object_items_nullable, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[MetaOapg.additional_properties, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["integer_prop"], typing_extensions.Literal["number_prop"], typing_extensions.Literal["boolean_prop"], typing_extensions.Literal["string_prop"], typing_extensions.Literal["date_prop"], typing_extensions.Literal["datetime_prop"], typing_extensions.Literal["array_nullable_prop"], typing_extensions.Literal["array_and_items_nullable_prop"], typing_extensions.Literal["array_items_nullable"], typing_extensions.Literal["object_nullable_prop"], typing_extensions.Literal["object_and_items_nullable_prop"], typing_extensions.Literal["object_items_nullable"], str, ]): + return super().get_item_oapg(name) - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + integer_prop: typing.Union[MetaOapg.properties.integer_prop, None, decimal.Decimal, int, schemas.Unset] = schemas.unset, + number_prop: typing.Union[MetaOapg.properties.number_prop, None, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + boolean_prop: typing.Union[MetaOapg.properties.boolean_prop, None, bool, schemas.Unset] = schemas.unset, + string_prop: typing.Union[MetaOapg.properties.string_prop, None, str, schemas.Unset] = schemas.unset, + date_prop: typing.Union[MetaOapg.properties.date_prop, None, str, date, schemas.Unset] = schemas.unset, + datetime_prop: typing.Union[MetaOapg.properties.datetime_prop, None, str, datetime, schemas.Unset] = schemas.unset, + array_nullable_prop: typing.Union[MetaOapg.properties.array_nullable_prop, list, tuple, None, schemas.Unset] = schemas.unset, + array_and_items_nullable_prop: typing.Union[MetaOapg.properties.array_and_items_nullable_prop, list, tuple, None, schemas.Unset] = schemas.unset, + array_items_nullable: typing.Union[MetaOapg.properties.array_items_nullable, list, tuple, schemas.Unset] = schemas.unset, + object_nullable_prop: typing.Union[MetaOapg.properties.object_nullable_prop, dict, frozendict.frozendict, None, schemas.Unset] = schemas.unset, + object_and_items_nullable_prop: typing.Union[MetaOapg.properties.object_and_items_nullable_prop, dict, frozendict.frozendict, None, schemas.Unset] = schemas.unset, + object_items_nullable: typing.Union[MetaOapg.properties.object_items_nullable, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, None, ], + ) -> 'NullableClass': + return super().__new__( + cls, + *args, + integer_prop=integer_prop, + number_prop=number_prop, + boolean_prop=boolean_prop, + string_prop=string_prop, + date_prop=date_prop, + datetime_prop=datetime_prop, + array_nullable_prop=array_nullable_prop, + array_and_items_nullable_prop=array_and_items_nullable_prop, + array_items_nullable=array_items_nullable, + object_nullable_prop=object_nullable_prop, + object_and_items_nullable_prop=object_and_items_nullable_prop, + object_items_nullable=object_items_nullable, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.pyi new file mode 100644 index 0000000000..0d3c13b457 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.pyi @@ -0,0 +1,576 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class NullableClass( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class integer_prop( + schemas.IntBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneDecimalMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, decimal.Decimal, int, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'integer_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class number_prop( + schemas.NumberBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneDecimalMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, decimal.Decimal, int, float, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'number_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class boolean_prop( + schemas.BoolBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneBoolMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, bool, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'boolean_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class string_prop( + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin + ): + + + def __new__( + cls, + *args: typing.Union[None, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'string_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class date_prop( + schemas.DateBase, + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin + ): + + + class MetaOapg: + format = 'date' + + + def __new__( + cls, + *args: typing.Union[None, str, date, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'date_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class datetime_prop( + schemas.DateTimeBase, + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin + ): + + + class MetaOapg: + format = 'date-time' + + + def __new__( + cls, + *args: typing.Union[None, str, datetime, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'datetime_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class array_nullable_prop( + schemas.ListBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneTupleMixin + ): + + + class MetaOapg: + items = schemas.DictSchema + + + def __new__( + cls, + *args: typing.Union[list, tuple, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_nullable_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class array_and_items_nullable_prop( + schemas.ListBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneTupleMixin + ): + + + class MetaOapg: + + + class items( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'items': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[list, tuple, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_and_items_nullable_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + + class array_items_nullable( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'items': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, dict, frozendict.frozendict, None, ]], typing.List[typing.Union[MetaOapg.items, dict, frozendict.frozendict, None, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'array_items_nullable': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class object_nullable_prop( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + class MetaOapg: + additional_properties = schemas.DictSchema + + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, ], + ) -> 'object_nullable_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class object_and_items_nullable_prop( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + class MetaOapg: + + + class additional_properties( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, None, ], + ) -> 'object_and_items_nullable_prop': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + + class object_items_nullable( + schemas.DictSchema + ): + + + class MetaOapg: + + + class additional_properties( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, None, ], + ) -> 'object_items_nullable': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "integer_prop": integer_prop, + "number_prop": number_prop, + "boolean_prop": boolean_prop, + "string_prop": string_prop, + "date_prop": date_prop, + "datetime_prop": datetime_prop, + "array_nullable_prop": array_nullable_prop, + "array_and_items_nullable_prop": array_and_items_nullable_prop, + "array_items_nullable": array_items_nullable, + "object_nullable_prop": object_nullable_prop, + "object_and_items_nullable_prop": object_and_items_nullable_prop, + "object_items_nullable": object_items_nullable, + } + + + class additional_properties( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'additional_properties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["integer_prop"]) -> MetaOapg.properties.integer_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["number_prop"]) -> MetaOapg.properties.number_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["boolean_prop"]) -> MetaOapg.properties.boolean_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["string_prop"]) -> MetaOapg.properties.string_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date_prop"]) -> MetaOapg.properties.date_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["datetime_prop"]) -> MetaOapg.properties.datetime_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_nullable_prop"]) -> MetaOapg.properties.array_nullable_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_and_items_nullable_prop"]) -> MetaOapg.properties.array_and_items_nullable_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["array_items_nullable"]) -> MetaOapg.properties.array_items_nullable: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["object_nullable_prop"]) -> MetaOapg.properties.object_nullable_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["object_and_items_nullable_prop"]) -> MetaOapg.properties.object_and_items_nullable_prop: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["object_items_nullable"]) -> MetaOapg.properties.object_items_nullable: ... + + @typing.overload + def __getitem__(self, name: str) -> MetaOapg.additional_properties: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["integer_prop"], typing_extensions.Literal["number_prop"], typing_extensions.Literal["boolean_prop"], typing_extensions.Literal["string_prop"], typing_extensions.Literal["date_prop"], typing_extensions.Literal["datetime_prop"], typing_extensions.Literal["array_nullable_prop"], typing_extensions.Literal["array_and_items_nullable_prop"], typing_extensions.Literal["array_items_nullable"], typing_extensions.Literal["object_nullable_prop"], typing_extensions.Literal["object_and_items_nullable_prop"], typing_extensions.Literal["object_items_nullable"], str, ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["integer_prop"]) -> typing.Union[MetaOapg.properties.integer_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["number_prop"]) -> typing.Union[MetaOapg.properties.number_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["boolean_prop"]) -> typing.Union[MetaOapg.properties.boolean_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["string_prop"]) -> typing.Union[MetaOapg.properties.string_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date_prop"]) -> typing.Union[MetaOapg.properties.date_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["datetime_prop"]) -> typing.Union[MetaOapg.properties.datetime_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_nullable_prop"]) -> typing.Union[MetaOapg.properties.array_nullable_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_and_items_nullable_prop"]) -> typing.Union[MetaOapg.properties.array_and_items_nullable_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["array_items_nullable"]) -> typing.Union[MetaOapg.properties.array_items_nullable, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["object_nullable_prop"]) -> typing.Union[MetaOapg.properties.object_nullable_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["object_and_items_nullable_prop"]) -> typing.Union[MetaOapg.properties.object_and_items_nullable_prop, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["object_items_nullable"]) -> typing.Union[MetaOapg.properties.object_items_nullable, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[MetaOapg.additional_properties, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["integer_prop"], typing_extensions.Literal["number_prop"], typing_extensions.Literal["boolean_prop"], typing_extensions.Literal["string_prop"], typing_extensions.Literal["date_prop"], typing_extensions.Literal["datetime_prop"], typing_extensions.Literal["array_nullable_prop"], typing_extensions.Literal["array_and_items_nullable_prop"], typing_extensions.Literal["array_items_nullable"], typing_extensions.Literal["object_nullable_prop"], typing_extensions.Literal["object_and_items_nullable_prop"], typing_extensions.Literal["object_items_nullable"], str, ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + integer_prop: typing.Union[MetaOapg.properties.integer_prop, None, decimal.Decimal, int, schemas.Unset] = schemas.unset, + number_prop: typing.Union[MetaOapg.properties.number_prop, None, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + boolean_prop: typing.Union[MetaOapg.properties.boolean_prop, None, bool, schemas.Unset] = schemas.unset, + string_prop: typing.Union[MetaOapg.properties.string_prop, None, str, schemas.Unset] = schemas.unset, + date_prop: typing.Union[MetaOapg.properties.date_prop, None, str, date, schemas.Unset] = schemas.unset, + datetime_prop: typing.Union[MetaOapg.properties.datetime_prop, None, str, datetime, schemas.Unset] = schemas.unset, + array_nullable_prop: typing.Union[MetaOapg.properties.array_nullable_prop, list, tuple, None, schemas.Unset] = schemas.unset, + array_and_items_nullable_prop: typing.Union[MetaOapg.properties.array_and_items_nullable_prop, list, tuple, None, schemas.Unset] = schemas.unset, + array_items_nullable: typing.Union[MetaOapg.properties.array_items_nullable, list, tuple, schemas.Unset] = schemas.unset, + object_nullable_prop: typing.Union[MetaOapg.properties.object_nullable_prop, dict, frozendict.frozendict, None, schemas.Unset] = schemas.unset, + object_and_items_nullable_prop: typing.Union[MetaOapg.properties.object_and_items_nullable_prop, dict, frozendict.frozendict, None, schemas.Unset] = schemas.unset, + object_items_nullable: typing.Union[MetaOapg.properties.object_items_nullable, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, None, ], + ) -> 'NullableClass': + return super().__new__( + cls, + *args, + integer_prop=integer_prop, + number_prop=number_prop, + boolean_prop=boolean_prop, + string_prop=string_prop, + date_prop=date_prop, + datetime_prop=datetime_prop, + array_nullable_prop=array_nullable_prop, + array_and_items_nullable_prop=array_and_items_nullable_prop, + array_items_nullable=array_items_nullable, + object_nullable_prop=object_nullable_prop, + object_and_items_nullable_prop=object_and_items_nullable_prop, + object_items_nullable=object_items_nullable, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py index 75aad1b1b0..e22e8d824e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,330 +9,64 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.quadrilateral import Quadrilateral - from petstore_api.model.triangle import Triangle - globals()['Quadrilateral'] = Quadrilateral - globals()['Triangle'] = Triangle - - -class NullableShape(ModelComposed): +class NullableShape( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + The value may be a shape or the 'null' value. For a composed schema to validate a null payload, one of its chosen oneOf schemas must be type null or nullable (introduced in OAS schema >= 3.0) """ - allowed_values = { - } - validations = { - } + class MetaOapg: + one_of_2 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Triangle, + Quadrilateral, + cls.one_of_2, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = True + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NullableShape': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'shape_type': (str,), # noqa: E501 - 'quadrilateral_type': (str,), # noqa: E501 - 'triangle_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - lazy_import() - val = { - 'Quadrilateral': Quadrilateral, - 'Triangle': Triangle, - } - if not val: - return None - return {'shape_type': val} - - attribute_map = { - 'shape_type': 'shapeType', # noqa: E501 - 'quadrilateral_type': 'quadrilateralType', # noqa: E501 - 'triangle_type': 'triangleType', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """NullableShape - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - quadrilateral_type (str): [optional] # noqa: E501 - triangle_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """NullableShape - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - quadrilateral_type (str): [optional] # noqa: E501 - triangle_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - Quadrilateral, - Triangle, - ], - } +from petstore_api.model.quadrilateral import Quadrilateral +from petstore_api.model.triangle import Triangle diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.pyi new file mode 100644 index 0000000000..e22e8d824e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.pyi @@ -0,0 +1,72 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class NullableShape( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + The value may be a shape or the 'null' value. For a composed schema to validate a null payload, one of its chosen oneOf schemas must be type null or nullable (introduced in OAS schema >= 3.0) + """ + + + class MetaOapg: + one_of_2 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Triangle, + Quadrilateral, + cls.one_of_2, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NullableShape': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.quadrilateral import Quadrilateral +from petstore_api.model.triangle import Triangle diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_string.py b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_string.py new file mode 100644 index 0000000000..94353cf0fd --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_string.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class NullableString( + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + def __new__( + cls, + *args: typing.Union[None, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'NullableString': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_string.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_string.pyi new file mode 100644 index 0000000000..94353cf0fd --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_string.pyi @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class NullableString( + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + def __new__( + cls, + *args: typing.Union[None, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'NullableString': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number.py b/samples/openapi3/client/petstore/python/petstore_api/model/number.py new file mode 100644 index 0000000000..7210b911ce --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +Number = schemas.NumberSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/number.pyi new file mode 100644 index 0000000000..7210b911ce --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +Number = schemas.NumberSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py index 7a586085d7..91aaaa507b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,70 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class NumberOnly(ModelNormal): +class NumberOnly( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + JustNumber = schemas.NumberSchema + __annotations__ = { + "JustNumber": JustNumber, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["JustNumber"]) -> MetaOapg.properties.JustNumber: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["JustNumber", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["JustNumber"]) -> typing.Union[MetaOapg.properties.JustNumber, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["JustNumber", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'just_number': (float,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'just_number': 'JustNumber', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """NumberOnly - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - just_number (float): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """NumberOnly - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - just_number (float): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + JustNumber: typing.Union[MetaOapg.properties.JustNumber, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NumberOnly': + return super().__new__( + cls, + *args, + JustNumber=JustNumber, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_only.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.pyi new file mode 100644 index 0000000000..91aaaa507b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.pyi @@ -0,0 +1,78 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class NumberOnly( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + JustNumber = schemas.NumberSchema + __annotations__ = { + "JustNumber": JustNumber, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["JustNumber"]) -> MetaOapg.properties.JustNumber: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["JustNumber", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["JustNumber"]) -> typing.Union[MetaOapg.properties.JustNumber, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["JustNumber", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + JustNumber: typing.Union[MetaOapg.properties.JustNumber, decimal.Decimal, int, float, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'NumberOnly': + return super().__new__( + cls, + *args, + JustNumber=JustNumber, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py index 67e019ad54..f8b63e3585 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,284 +9,30 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class NumberWithValidations(ModelSimple): +class NumberWithValidations( + schemas.NumberSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - ('value',): { - 'inclusive_maximum': 20, - 'inclusive_minimum': 10, - }, - } - - additional_properties_type = None - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (float,), - } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """NumberWithValidations - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (float): # noqa: E501 - - Keyword Args: - value (float): # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """NumberWithValidations - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (float): # noqa: E501 - - Keyword Args: - value (float): # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self + class MetaOapg: + inclusive_maximum = 20 + inclusive_minimum = 10 diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.pyi new file mode 100644 index 0000000000..4e92a92006 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.pyi @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class NumberWithValidations( + schemas.NumberSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py index 4f9e0edf98..05dc6ddd56 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,253 +9,16 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 - - -class ObjectInterface(ModelNormal): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. - """ - - allowed_values = { - } - - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ObjectInterface - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ObjectInterface - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api import schemas # noqa: F401 +ObjectInterface = schemas.DictSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.pyi new file mode 100644 index 0000000000..05dc6ddd56 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +ObjectInterface = schemas.DictSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py index 085a1533c4..e68caff871 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,277 +9,97 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.number_with_validations import NumberWithValidations - from petstore_api.model.readonly import Readonly - globals()['NumberWithValidations'] = NumberWithValidations - globals()['Readonly'] = Readonly - - -class ObjectModelWithRefProps(ModelNormal): +class ObjectModelWithRefProps( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + + @staticmethod + def myNumber() -> typing.Type['NumberWithValidations']: + return NumberWithValidations + myString = schemas.StrSchema + myBoolean = schemas.BoolSchema + __annotations__ = { + "myNumber": myNumber, + "myString": myString, + "myBoolean": myBoolean, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["myNumber"]) -> 'NumberWithValidations': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["myString"]) -> MetaOapg.properties.myString: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["myBoolean"]) -> MetaOapg.properties.myBoolean: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["myNumber", "myString", "myBoolean", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["myNumber"]) -> typing.Union['NumberWithValidations', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["myString"]) -> typing.Union[MetaOapg.properties.myString, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["myBoolean"]) -> typing.Union[MetaOapg.properties.myBoolean, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["myNumber", "myString", "myBoolean", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + myNumber: typing.Union['NumberWithValidations', schemas.Unset] = schemas.unset, + myString: typing.Union[MetaOapg.properties.myString, str, schemas.Unset] = schemas.unset, + myBoolean: typing.Union[MetaOapg.properties.myBoolean, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectModelWithRefProps': + return super().__new__( + cls, + *args, + myNumber=myNumber, + myString=myString, + myBoolean=myBoolean, + _configuration=_configuration, + **kwargs, + ) - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'my_number': (NumberWithValidations,), # noqa: E501 - 'my_readonly': (Readonly,), # noqa: E501 - 'my_string': (str,), # noqa: E501 - 'my_boolean': (bool,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'my_number': 'my_number', # noqa: E501 - 'my_readonly': 'my_readonly', # noqa: E501 - 'my_string': 'my_string', # noqa: E501 - 'my_boolean': 'my_boolean', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ObjectModelWithRefProps - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - my_number (NumberWithValidations): [optional] # noqa: E501 - my_readonly (Readonly): [optional] # noqa: E501 - my_string (str): [optional] # noqa: E501 - my_boolean (bool): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ObjectModelWithRefProps - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - my_number (NumberWithValidations): [optional] # noqa: E501 - my_readonly (Readonly): [optional] # noqa: E501 - my_string (str): [optional] # noqa: E501 - my_boolean (bool): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.number_with_validations import NumberWithValidations diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.pyi new file mode 100644 index 0000000000..e68caff871 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.pyi @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectModelWithRefProps( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations + """ + + + class MetaOapg: + + class properties: + + @staticmethod + def myNumber() -> typing.Type['NumberWithValidations']: + return NumberWithValidations + myString = schemas.StrSchema + myBoolean = schemas.BoolSchema + __annotations__ = { + "myNumber": myNumber, + "myString": myString, + "myBoolean": myBoolean, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["myNumber"]) -> 'NumberWithValidations': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["myString"]) -> MetaOapg.properties.myString: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["myBoolean"]) -> MetaOapg.properties.myBoolean: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["myNumber", "myString", "myBoolean", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["myNumber"]) -> typing.Union['NumberWithValidations', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["myString"]) -> typing.Union[MetaOapg.properties.myString, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["myBoolean"]) -> typing.Union[MetaOapg.properties.myBoolean, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["myNumber", "myString", "myBoolean", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + myNumber: typing.Union['NumberWithValidations', schemas.Unset] = schemas.unset, + myString: typing.Union[MetaOapg.properties.myString, str, schemas.Unset] = schemas.unset, + myBoolean: typing.Union[MetaOapg.properties.myBoolean, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectModelWithRefProps': + return super().__new__( + cls, + *args, + myNumber=myNumber, + myString=myString, + myBoolean=myBoolean, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.number_with_validations import NumberWithValidations diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_decimal_properties.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_decimal_properties.py new file mode 100644 index 0000000000..068f21457b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_decimal_properties.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectWithDecimalProperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + length = schemas.DecimalSchema + width = schemas.DecimalSchema + + @staticmethod + def cost() -> typing.Type['Money']: + return Money + __annotations__ = { + "length": length, + "width": width, + "cost": cost, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["length"]) -> MetaOapg.properties.length: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["width"]) -> MetaOapg.properties.width: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["cost"]) -> 'Money': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["length", "width", "cost", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["length"]) -> typing.Union[MetaOapg.properties.length, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["width"]) -> typing.Union[MetaOapg.properties.width, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["cost"]) -> typing.Union['Money', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["length", "width", "cost", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + length: typing.Union[MetaOapg.properties.length, str, schemas.Unset] = schemas.unset, + width: typing.Union[MetaOapg.properties.width, str, schemas.Unset] = schemas.unset, + cost: typing.Union['Money', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithDecimalProperties': + return super().__new__( + cls, + *args, + length=length, + width=width, + cost=cost, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.money import Money diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_decimal_properties.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_decimal_properties.pyi new file mode 100644 index 0000000000..068f21457b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_decimal_properties.pyi @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectWithDecimalProperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + length = schemas.DecimalSchema + width = schemas.DecimalSchema + + @staticmethod + def cost() -> typing.Type['Money']: + return Money + __annotations__ = { + "length": length, + "width": width, + "cost": cost, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["length"]) -> MetaOapg.properties.length: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["width"]) -> MetaOapg.properties.width: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["cost"]) -> 'Money': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["length", "width", "cost", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["length"]) -> typing.Union[MetaOapg.properties.length, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["width"]) -> typing.Union[MetaOapg.properties.width, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["cost"]) -> typing.Union['Money', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["length", "width", "cost", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + length: typing.Union[MetaOapg.properties.length, str, schemas.Unset] = schemas.unset, + width: typing.Union[MetaOapg.properties.width, str, schemas.Unset] = schemas.unset, + cost: typing.Union['Money', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithDecimalProperties': + return super().__new__( + cls, + *args, + length=length, + width=width, + cost=cost, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.money import Money diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_difficultly_named_props.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_difficultly_named_props.py new file mode 100644 index 0000000000..0e6aa7d4a1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_difficultly_named_props.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectWithDifficultlyNamedProps( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + model with properties that have invalid names for python + """ + + + class MetaOapg: + required = { + "123-list", + } + + class properties: + _123_list = schemas.StrSchema + special_property_name = schemas.Int64Schema + _123_number = schemas.IntSchema + __annotations__ = { + "123-list": _123_list, + "$special[property.name]": special_property_name, + "123Number": _123_number, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["123-list"]) -> MetaOapg.properties._123_list: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["$special[property.name]"]) -> MetaOapg.properties.special_property_name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["123Number"]) -> MetaOapg.properties._123_number: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["123-list", "$special[property.name]", "123Number", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["123-list"]) -> MetaOapg.properties._123_list: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["$special[property.name]"]) -> typing.Union[MetaOapg.properties.special_property_name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["123Number"]) -> typing.Union[MetaOapg.properties._123_number, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["123-list", "$special[property.name]", "123Number", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithDifficultlyNamedProps': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_difficultly_named_props.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_difficultly_named_props.pyi new file mode 100644 index 0000000000..0e6aa7d4a1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_difficultly_named_props.pyi @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectWithDifficultlyNamedProps( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + model with properties that have invalid names for python + """ + + + class MetaOapg: + required = { + "123-list", + } + + class properties: + _123_list = schemas.StrSchema + special_property_name = schemas.Int64Schema + _123_number = schemas.IntSchema + __annotations__ = { + "123-list": _123_list, + "$special[property.name]": special_property_name, + "123Number": _123_number, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["123-list"]) -> MetaOapg.properties._123_list: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["$special[property.name]"]) -> MetaOapg.properties.special_property_name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["123Number"]) -> MetaOapg.properties._123_number: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["123-list", "$special[property.name]", "123Number", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["123-list"]) -> MetaOapg.properties._123_list: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["$special[property.name]"]) -> typing.Union[MetaOapg.properties.special_property_name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["123Number"]) -> typing.Union[MetaOapg.properties._123_number, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["123-list", "$special[property.name]", "123Number", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithDifficultlyNamedProps': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_inline_composition_property.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_inline_composition_property.py new file mode 100644 index 0000000000..31e422370f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_inline_composition_property.py @@ -0,0 +1,122 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectWithInlineCompositionProperty( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class someProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + + + class MetaOapg: + min_length = 1 + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'someProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "someProp": someProp, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["someProp"]) -> MetaOapg.properties.someProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["someProp"]) -> typing.Union[MetaOapg.properties.someProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + someProp: typing.Union[MetaOapg.properties.someProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithInlineCompositionProperty': + return super().__new__( + cls, + *args, + someProp=someProp, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_inline_composition_property.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_inline_composition_property.pyi new file mode 100644 index 0000000000..294520bd23 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_inline_composition_property.pyi @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectWithInlineCompositionProperty( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + + + class someProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + pass + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'someProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "someProp": someProp, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["someProp"]) -> MetaOapg.properties.someProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["someProp"]) -> typing.Union[MetaOapg.properties.someProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + someProp: typing.Union[MetaOapg.properties.someProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithInlineCompositionProperty': + return super().__new__( + cls, + *args, + someProp=someProp, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_invalid_named_refed_properties.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_invalid_named_refed_properties.py new file mode 100644 index 0000000000..0efcbfa5f4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_invalid_named_refed_properties.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectWithInvalidNamedRefedProperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "!reference", + "from", + } + + class properties: + + @staticmethod + def _from() -> typing.Type['FromSchema']: + return FromSchema + + @staticmethod + def reference() -> typing.Type['ArrayWithValidationsInItems']: + return ArrayWithValidationsInItems + __annotations__ = { + "from": _from, + "!reference": reference, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["from"]) -> 'FromSchema': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["!reference"]) -> 'ArrayWithValidationsInItems': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["from", "!reference", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["from"]) -> 'FromSchema': ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["!reference"]) -> 'ArrayWithValidationsInItems': ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["from", "!reference", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithInvalidNamedRefedProperties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.array_with_validations_in_items import ArrayWithValidationsInItems +from petstore_api.model.from_schema import FromSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_invalid_named_refed_properties.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_invalid_named_refed_properties.pyi new file mode 100644 index 0000000000..0efcbfa5f4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_invalid_named_refed_properties.pyi @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectWithInvalidNamedRefedProperties( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "!reference", + "from", + } + + class properties: + + @staticmethod + def _from() -> typing.Type['FromSchema']: + return FromSchema + + @staticmethod + def reference() -> typing.Type['ArrayWithValidationsInItems']: + return ArrayWithValidationsInItems + __annotations__ = { + "from": _from, + "!reference": reference, + } + + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["from"]) -> 'FromSchema': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["!reference"]) -> 'ArrayWithValidationsInItems': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["from", "!reference", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["from"]) -> 'FromSchema': ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["!reference"]) -> 'ArrayWithValidationsInItems': ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["from", "!reference", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithInvalidNamedRefedProperties': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.array_with_validations_in_items import ArrayWithValidationsInItems +from petstore_api.model.from_schema import FromSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py index 16e0c1f1a2..50c2269817 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,256 +9,42 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class ObjectWithValidations(ModelNormal): +class ObjectWithValidations( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - ('value',): { - 'min_properties': 1, - }, - } + class MetaOapg: + min_properties = 2 - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ObjectWithValidations - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ObjectWithValidations - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithValidations': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.pyi new file mode 100644 index 0000000000..f45e30eed5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.pyi @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ObjectWithValidations( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ObjectWithValidations': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/order.py b/samples/openapi3/client/petstore/python/petstore_api/model/order.py index 98fe0b8697..6d653b0ab0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/order.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/order.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,282 +9,145 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Order(ModelNormal): +class Order( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('status',): { - 'PLACED': "placed", - 'APPROVED': "approved", - 'DELIVERED': "delivered", - }, - } - validations = { - } + class MetaOapg: + + class properties: + id = schemas.Int64Schema + petId = schemas.Int64Schema + quantity = schemas.Int32Schema + shipDate = schemas.DateTimeSchema + + + class status( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "placed": "PLACED", + "approved": "APPROVED", + "delivered": "DELIVERED", + } + + @schemas.classproperty + def PLACED(cls): + return cls("placed") + + @schemas.classproperty + def APPROVED(cls): + return cls("approved") + + @schemas.classproperty + def DELIVERED(cls): + return cls("delivered") + complete = schemas.BoolSchema + __annotations__ = { + "id": id, + "petId": petId, + "quantity": quantity, + "shipDate": shipDate, + "status": status, + "complete": complete, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["petId"]) -> MetaOapg.properties.petId: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["quantity"]) -> MetaOapg.properties.quantity: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shipDate"]) -> MetaOapg.properties.shipDate: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["status"]) -> MetaOapg.properties.status: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["complete"]) -> MetaOapg.properties.complete: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["id", "petId", "quantity", "shipDate", "status", "complete", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["petId"]) -> typing.Union[MetaOapg.properties.petId, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["quantity"]) -> typing.Union[MetaOapg.properties.quantity, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shipDate"]) -> typing.Union[MetaOapg.properties.shipDate, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["status"]) -> typing.Union[MetaOapg.properties.status, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["complete"]) -> typing.Union[MetaOapg.properties.complete, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["id", "petId", "quantity", "shipDate", "status", "complete", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'id': (int,), # noqa: E501 - 'pet_id': (int,), # noqa: E501 - 'quantity': (int,), # noqa: E501 - 'ship_date': (datetime,), # noqa: E501 - 'status': (str,), # noqa: E501 - 'complete': (bool,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'id': 'id', # noqa: E501 - 'pet_id': 'petId', # noqa: E501 - 'quantity': 'quantity', # noqa: E501 - 'ship_date': 'shipDate', # noqa: E501 - 'status': 'status', # noqa: E501 - 'complete': 'complete', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Order - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - pet_id (int): [optional] # noqa: E501 - quantity (int): [optional] # noqa: E501 - ship_date (datetime): [optional] # noqa: E501 - status (str): Order Status. [optional] # noqa: E501 - complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Order - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - pet_id (int): [optional] # noqa: E501 - quantity (int): [optional] # noqa: E501 - ship_date (datetime): [optional] # noqa: E501 - status (str): Order Status. [optional] # noqa: E501 - complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + petId: typing.Union[MetaOapg.properties.petId, decimal.Decimal, int, schemas.Unset] = schemas.unset, + quantity: typing.Union[MetaOapg.properties.quantity, decimal.Decimal, int, schemas.Unset] = schemas.unset, + shipDate: typing.Union[MetaOapg.properties.shipDate, str, datetime, schemas.Unset] = schemas.unset, + status: typing.Union[MetaOapg.properties.status, str, schemas.Unset] = schemas.unset, + complete: typing.Union[MetaOapg.properties.complete, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Order': + return super().__new__( + cls, + *args, + id=id, + petId=petId, + quantity=quantity, + shipDate=shipDate, + status=status, + complete=complete, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/order.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/order.pyi new file mode 100644 index 0000000000..ccbca89e08 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/order.pyi @@ -0,0 +1,145 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Order( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + id = schemas.Int64Schema + petId = schemas.Int64Schema + quantity = schemas.Int32Schema + shipDate = schemas.DateTimeSchema + + + class status( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def PLACED(cls): + return cls("placed") + + @schemas.classproperty + def APPROVED(cls): + return cls("approved") + + @schemas.classproperty + def DELIVERED(cls): + return cls("delivered") + complete = schemas.BoolSchema + __annotations__ = { + "id": id, + "petId": petId, + "quantity": quantity, + "shipDate": shipDate, + "status": status, + "complete": complete, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["petId"]) -> MetaOapg.properties.petId: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["quantity"]) -> MetaOapg.properties.quantity: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shipDate"]) -> MetaOapg.properties.shipDate: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["status"]) -> MetaOapg.properties.status: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["complete"]) -> MetaOapg.properties.complete: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["id", "petId", "quantity", "shipDate", "status", "complete", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["petId"]) -> typing.Union[MetaOapg.properties.petId, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["quantity"]) -> typing.Union[MetaOapg.properties.quantity, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shipDate"]) -> typing.Union[MetaOapg.properties.shipDate, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["status"]) -> typing.Union[MetaOapg.properties.status, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["complete"]) -> typing.Union[MetaOapg.properties.complete, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["id", "petId", "quantity", "shipDate", "status", "complete", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + petId: typing.Union[MetaOapg.properties.petId, decimal.Decimal, int, schemas.Unset] = schemas.unset, + quantity: typing.Union[MetaOapg.properties.quantity, decimal.Decimal, int, schemas.Unset] = schemas.unset, + shipDate: typing.Union[MetaOapg.properties.shipDate, str, datetime, schemas.Unset] = schemas.unset, + status: typing.Union[MetaOapg.properties.status, str, schemas.Unset] = schemas.unset, + complete: typing.Union[MetaOapg.properties.complete, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Order': + return super().__new__( + cls, + *args, + id=id, + petId=petId, + quantity=quantity, + shipDate=shipDate, + status=status, + complete=complete, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py index 8d94006f15..178eab4e5a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,320 +9,68 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.child_cat import ChildCat - from petstore_api.model.grandparent_animal import GrandparentAnimal - globals()['ChildCat'] = ChildCat - globals()['GrandparentAnimal'] = GrandparentAnimal - - -class ParentPet(ModelComposed): +class ParentPet( + schemas.ComposedBase, + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'pet_type': { + 'ChildCat': ChildCat, + } + } + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + GrandparentAnimal, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ParentPet': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'pet_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - lazy_import() - val = { - 'ChildCat': ChildCat, - } - if not val: - return None - return {'pet_type': val} - - attribute_map = { - 'pet_type': 'pet_type', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ParentPet - a model defined in OpenAPI - - Keyword Args: - pet_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ParentPet - a model defined in OpenAPI - - Keyword Args: - pet_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - GrandparentAnimal, - ], - 'oneOf': [ - ], - } +from petstore_api.model.child_cat import ChildCat +from petstore_api.model.grandparent_animal import GrandparentAnimal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.pyi new file mode 100644 index 0000000000..178eab4e5a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.pyi @@ -0,0 +1,76 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ParentPet( + schemas.ComposedBase, + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'pet_type': { + 'ChildCat': ChildCat, + } + } + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + GrandparentAnimal, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ParentPet': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.child_cat import ChildCat +from petstore_api.model.grandparent_animal import GrandparentAnimal diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pet.py b/samples/openapi3/client/petstore/python/petstore_api/model/pet.py index 5eb4041e91..5b1b6b8275 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pet.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,298 +9,207 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.category import Category - from petstore_api.model.tag import Tag - globals()['Category'] = Category - globals()['Tag'] = Tag - - -class Pet(ModelNormal): +class Pet( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + Pet object that needs to be added to the store """ - allowed_values = { - ('status',): { - 'AVAILABLE': "available", - 'PENDING': "pending", - 'SOLD': "sold", - }, - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'name': (str,), # noqa: E501 - 'photo_urls': ([str],), # noqa: E501 - 'id': (int,), # noqa: E501 - 'category': (Category,), # noqa: E501 - 'tags': ([Tag],), # noqa: E501 - 'status': (str,), # noqa: E501 + class MetaOapg: + required = { + "photoUrls", + "name", } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'name': 'name', # noqa: E501 - 'photo_urls': 'photoUrls', # noqa: E501 - 'id': 'id', # noqa: E501 - 'category': 'category', # noqa: E501 - 'tags': 'tags', # noqa: E501 - 'status': 'status', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, name, photo_urls, *args, **kwargs): # noqa: E501 - """Pet - a model defined in OpenAPI - - Args: - name (str): - photo_urls ([str]): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - category (Category): [optional] # noqa: E501 - tags ([Tag]): [optional] # noqa: E501 - status (str): pet status in the store. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + + class properties: + name = schemas.StrSchema + + + class photoUrls( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'photoUrls': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.name = name - self.photo_urls = photo_urls - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, name, photo_urls, *args, **kwargs): # noqa: E501 - """Pet - a model defined in OpenAPI - - Args: - name (str): - photo_urls ([str]): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - category (Category): [optional] # noqa: E501 - tags ([Tag]): [optional] # noqa: E501 - status (str): pet status in the store. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + id = schemas.Int64Schema + + @staticmethod + def category() -> typing.Type['Category']: + return Category + + + class tags( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Tag']: + return Tag + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Tag'], typing.List['Tag']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'tags': + return super().__new__( + cls, + arg, + _configuration=_configuration, ) + + def __getitem__(self, i: int) -> 'Tag': + return super().__getitem__(i) + + + class status( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "available": "AVAILABLE", + "pending": "PENDING", + "sold": "SOLD", + } + + @schemas.classproperty + def AVAILABLE(cls): + return cls("available") + + @schemas.classproperty + def PENDING(cls): + return cls("pending") + + @schemas.classproperty + def SOLD(cls): + return cls("sold") + __annotations__ = { + "name": name, + "photoUrls": photoUrls, + "id": id, + "category": category, + "tags": tags, + "status": status, + } + + photoUrls: MetaOapg.properties.photoUrls + name: MetaOapg.properties.name + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["photoUrls"]) -> MetaOapg.properties.photoUrls: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["category"]) -> 'Category': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["tags"]) -> MetaOapg.properties.tags: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["status"]) -> MetaOapg.properties.status: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "photoUrls", "id", "category", "tags", "status", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["photoUrls"]) -> MetaOapg.properties.photoUrls: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["category"]) -> typing.Union['Category', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["tags"]) -> typing.Union[MetaOapg.properties.tags, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["status"]) -> typing.Union[MetaOapg.properties.status, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "photoUrls", "id", "category", "tags", "status", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + photoUrls: typing.Union[MetaOapg.properties.photoUrls, list, tuple, ], + name: typing.Union[MetaOapg.properties.name, str, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + category: typing.Union['Category', schemas.Unset] = schemas.unset, + tags: typing.Union[MetaOapg.properties.tags, list, tuple, schemas.Unset] = schemas.unset, + status: typing.Union[MetaOapg.properties.status, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Pet': + return super().__new__( + cls, + *args, + photoUrls=photoUrls, + name=name, + id=id, + category=category, + tags=tags, + status=status, + _configuration=_configuration, + **kwargs, + ) - self.name = name - self.photo_urls = photo_urls - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") +from petstore_api.model.category import Category +from petstore_api.model.tag import Tag diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pet.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/pet.pyi new file mode 100644 index 0000000000..01529098ea --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pet.pyi @@ -0,0 +1,207 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Pet( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Pet object that needs to be added to the store + """ + + + class MetaOapg: + required = { + "photoUrls", + "name", + } + + class properties: + name = schemas.StrSchema + + + class photoUrls( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'photoUrls': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + id = schemas.Int64Schema + + @staticmethod + def category() -> typing.Type['Category']: + return Category + + + class tags( + schemas.ListSchema + ): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Tag']: + return Tag + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Tag'], typing.List['Tag']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'tags': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Tag': + return super().__getitem__(i) + + + class status( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def AVAILABLE(cls): + return cls("available") + + @schemas.classproperty + def PENDING(cls): + return cls("pending") + + @schemas.classproperty + def SOLD(cls): + return cls("sold") + __annotations__ = { + "name": name, + "photoUrls": photoUrls, + "id": id, + "category": category, + "tags": tags, + "status": status, + } + + photoUrls: MetaOapg.properties.photoUrls + name: MetaOapg.properties.name + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["photoUrls"]) -> MetaOapg.properties.photoUrls: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["category"]) -> 'Category': ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["tags"]) -> MetaOapg.properties.tags: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["status"]) -> MetaOapg.properties.status: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "photoUrls", "id", "category", "tags", "status", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["photoUrls"]) -> MetaOapg.properties.photoUrls: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["category"]) -> typing.Union['Category', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["tags"]) -> typing.Union[MetaOapg.properties.tags, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["status"]) -> typing.Union[MetaOapg.properties.status, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "photoUrls", "id", "category", "tags", "status", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + photoUrls: typing.Union[MetaOapg.properties.photoUrls, list, tuple, ], + name: typing.Union[MetaOapg.properties.name, str, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + category: typing.Union['Category', schemas.Unset] = schemas.unset, + tags: typing.Union[MetaOapg.properties.tags, list, tuple, schemas.Unset] = schemas.unset, + status: typing.Union[MetaOapg.properties.status, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Pet': + return super().__new__( + cls, + *args, + photoUrls=photoUrls, + name=name, + id=id, + category=category, + tags=tags, + status=status, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.category import Category +from petstore_api.model.tag import Tag diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/pig.py index 5c9bcc5bd0..db4887c110 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pig.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,322 +9,69 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.basque_pig import BasquePig - from petstore_api.model.danish_pig import DanishPig - globals()['BasquePig'] = BasquePig - globals()['DanishPig'] = DanishPig - - -class Pig(ModelComposed): +class Pig( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'className': { + 'BasquePig': BasquePig, + 'DanishPig': DanishPig, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + BasquePig, + DanishPig, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Pig': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'class_name': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - lazy_import() - val = { - 'BasquePig': BasquePig, - 'DanishPig': DanishPig, - } - if not val: - return None - return {'class_name': val} - - attribute_map = { - 'class_name': 'className', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Pig - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Pig - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - BasquePig, - DanishPig, - ], - } +from petstore_api.model.basque_pig import BasquePig +from petstore_api.model.danish_pig import DanishPig diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pig.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/pig.pyi new file mode 100644 index 0000000000..db4887c110 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pig.pyi @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Pig( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'className': { + 'BasquePig': BasquePig, + 'DanishPig': DanishPig, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + BasquePig, + DanishPig, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Pig': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.basque_pig import BasquePig +from petstore_api.model.danish_pig import DanishPig diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/player.py b/samples/openapi3/client/petstore/python/petstore_api/model/player.py new file mode 100644 index 0000000000..d08a18d2ee --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/player.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Player( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + a model that includes a self reference this forces properties and additionalProperties to be lazy loaded in python models because the Player class has not fully loaded when defining properties + """ + + + class MetaOapg: + + class properties: + name = schemas.StrSchema + + @staticmethod + def enemyPlayer() -> typing.Type['Player']: + return Player + __annotations__ = { + "name": name, + "enemyPlayer": enemyPlayer, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enemyPlayer"]) -> 'Player': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "enemyPlayer", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enemyPlayer"]) -> typing.Union['Player', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "enemyPlayer", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + name: typing.Union[MetaOapg.properties.name, str, schemas.Unset] = schemas.unset, + enemyPlayer: typing.Union['Player', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Player': + return super().__new__( + cls, + *args, + name=name, + enemyPlayer=enemyPlayer, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/player.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/player.pyi new file mode 100644 index 0000000000..d08a18d2ee --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/player.pyi @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Player( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + a model that includes a self reference this forces properties and additionalProperties to be lazy loaded in python models because the Player class has not fully loaded when defining properties + """ + + + class MetaOapg: + + class properties: + name = schemas.StrSchema + + @staticmethod + def enemyPlayer() -> typing.Type['Player']: + return Player + __annotations__ = { + "name": name, + "enemyPlayer": enemyPlayer, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enemyPlayer"]) -> 'Player': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "enemyPlayer", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enemyPlayer"]) -> typing.Union['Player', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "enemyPlayer", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + name: typing.Union[MetaOapg.properties.name, str, schemas.Unset] = schemas.unset, + enemyPlayer: typing.Union['Player', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Player': + return super().__new__( + cls, + *args, + name=name, + enemyPlayer=enemyPlayer, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py index ddb76e43e8..6a9b08fa1f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,326 +9,69 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral - from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral - globals()['ComplexQuadrilateral'] = ComplexQuadrilateral - globals()['SimpleQuadrilateral'] = SimpleQuadrilateral - - -class Quadrilateral(ModelComposed): +class Quadrilateral( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'quadrilateralType': { + 'ComplexQuadrilateral': ComplexQuadrilateral, + 'SimpleQuadrilateral': SimpleQuadrilateral, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + SimpleQuadrilateral, + ComplexQuadrilateral, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Quadrilateral': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'quadrilateral_type': (str,), # noqa: E501 - 'shape_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - lazy_import() - val = { - 'ComplexQuadrilateral': ComplexQuadrilateral, - 'SimpleQuadrilateral': SimpleQuadrilateral, - } - if not val: - return None - return {'quadrilateral_type': val} - - attribute_map = { - 'quadrilateral_type': 'quadrilateralType', # noqa: E501 - 'shape_type': 'shapeType', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Quadrilateral - a model defined in OpenAPI - - Keyword Args: - quadrilateral_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - shape_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Quadrilateral - a model defined in OpenAPI - - Keyword Args: - quadrilateral_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - shape_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - ComplexQuadrilateral, - SimpleQuadrilateral, - ], - } +from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral +from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.pyi new file mode 100644 index 0000000000..6a9b08fa1f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.pyi @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Quadrilateral( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'quadrilateralType': { + 'ComplexQuadrilateral': ComplexQuadrilateral, + 'SimpleQuadrilateral': SimpleQuadrilateral, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + SimpleQuadrilateral, + ComplexQuadrilateral, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Quadrilateral': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral +from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py index 9f61569c9c..90c85c2388 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,263 +9,103 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class QuadrilateralInterface(ModelNormal): +class QuadrilateralInterface( + schemas.AnyTypeSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'quadrilateral_type': (str,), # noqa: E501 + class MetaOapg: + required = { + "shapeType", + "quadrilateralType", } + + class properties: + + + class shapeType( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "Quadrilateral": "QUADRILATERAL", + } + + @schemas.classproperty + def QUADRILATERAL(cls): + return cls("Quadrilateral") + quadrilateralType = schemas.StrSchema + __annotations__ = { + "shapeType": shapeType, + "quadrilateralType": quadrilateralType, + } - @cached_property - def discriminator(): - return None + + shapeType: MetaOapg.properties.shapeType + quadrilateralType: MetaOapg.properties.quadrilateralType + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shapeType"]) -> MetaOapg.properties.shapeType: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["quadrilateralType"]) -> MetaOapg.properties.quadrilateralType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["shapeType", "quadrilateralType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shapeType"]) -> MetaOapg.properties.shapeType: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["quadrilateralType"]) -> MetaOapg.properties.quadrilateralType: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["shapeType", "quadrilateralType", ], str]): + return super().get_item_oapg(name) + - - attribute_map = { - 'quadrilateral_type': 'quadrilateralType', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, quadrilateral_type, *args, **kwargs): # noqa: E501 - """QuadrilateralInterface - a model defined in OpenAPI - - Args: - quadrilateral_type (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.quadrilateral_type = quadrilateral_type - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, quadrilateral_type, *args, **kwargs): # noqa: E501 - """QuadrilateralInterface - a model defined in OpenAPI - - Args: - quadrilateral_type (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.quadrilateral_type = quadrilateral_type - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + shapeType: typing.Union[MetaOapg.properties.shapeType, str, ], + quadrilateralType: typing.Union[MetaOapg.properties.quadrilateralType, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'QuadrilateralInterface': + return super().__new__( + cls, + *args, + shapeType=shapeType, + quadrilateralType=quadrilateralType, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.pyi new file mode 100644 index 0000000000..9250542904 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.pyi @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class QuadrilateralInterface( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "shapeType", + "quadrilateralType", + } + + class properties: + + + class shapeType( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def QUADRILATERAL(cls): + return cls("Quadrilateral") + quadrilateralType = schemas.StrSchema + __annotations__ = { + "shapeType": shapeType, + "quadrilateralType": quadrilateralType, + } + + + shapeType: MetaOapg.properties.shapeType + quadrilateralType: MetaOapg.properties.quadrilateralType + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shapeType"]) -> MetaOapg.properties.shapeType: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["quadrilateralType"]) -> MetaOapg.properties.quadrilateralType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["shapeType", "quadrilateralType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shapeType"]) -> MetaOapg.properties.shapeType: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["quadrilateralType"]) -> MetaOapg.properties.quadrilateralType: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["shapeType", "quadrilateralType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + shapeType: typing.Union[MetaOapg.properties.shapeType, str, ], + quadrilateralType: typing.Union[MetaOapg.properties.quadrilateralType, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'QuadrilateralInterface': + return super().__new__( + cls, + *args, + shapeType=shapeType, + quadrilateralType=quadrilateralType, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py index 965325c286..c849de1906 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,262 +9,80 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class ReadOnlyFirst(ModelNormal): +class ReadOnlyFirst( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + bar = schemas.StrSchema + baz = schemas.StrSchema + __annotations__ = { + "bar": bar, + "baz": baz, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["baz"]) -> MetaOapg.properties.baz: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", "baz", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["baz"]) -> typing.Union[MetaOapg.properties.baz, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", "baz", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'bar': (str,), # noqa: E501 - 'baz': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'bar': 'bar', # noqa: E501 - 'baz': 'baz', # noqa: E501 - } - - read_only_vars = { - 'bar', # noqa: E501 - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ReadOnlyFirst - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - bar (str): [optional] # noqa: E501 - baz (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ReadOnlyFirst - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - bar (str): [optional] # noqa: E501 - baz (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + baz: typing.Union[MetaOapg.properties.baz, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ReadOnlyFirst': + return super().__new__( + cls, + *args, + bar=bar, + baz=baz, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.pyi new file mode 100644 index 0000000000..c849de1906 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.pyi @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ReadOnlyFirst( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + bar = schemas.StrSchema + baz = schemas.StrSchema + __annotations__ = { + "bar": bar, + "baz": baz, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["bar"]) -> MetaOapg.properties.bar: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["baz"]) -> MetaOapg.properties.baz: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["bar", "baz", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["bar"]) -> typing.Union[MetaOapg.properties.bar, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["baz"]) -> typing.Union[MetaOapg.properties.baz, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["bar", "baz", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + bar: typing.Union[MetaOapg.properties.bar, str, schemas.Unset] = schemas.unset, + baz: typing.Union[MetaOapg.properties.baz, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ReadOnlyFirst': + return super().__new__( + cls, + *args, + bar=bar, + baz=baz, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py index 6a7bfe81bd..46083ad564 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,320 +9,124 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.shape_interface import ShapeInterface - from petstore_api.model.triangle_interface import TriangleInterface - globals()['ShapeInterface'] = ShapeInterface - globals()['TriangleInterface'] = TriangleInterface - - -class ScaleneTriangle(ModelComposed): +class ScaleneTriangle( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'shape_type': (str,), # noqa: E501 - 'triangle_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class triangleType( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "ScaleneTriangle": "SCALENE_TRIANGLE", + } + + @schemas.classproperty + def SCALENE_TRIANGLE(cls): + return cls("ScaleneTriangle") + __annotations__ = { + "triangleType": triangleType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["triangleType"]) -> typing.Union[MetaOapg.properties.triangleType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + triangleType: typing.Union[MetaOapg.properties.triangleType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + triangleType=triangleType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + TriangleInterface, + cls.all_of_1, + ] - attribute_map = { - 'shape_type': 'shapeType', # noqa: E501 - 'triangle_type': 'triangleType', # noqa: E501 - } + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ScaleneTriangle': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ScaleneTriangle - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - triangle_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ScaleneTriangle - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - triangle_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ShapeInterface, - TriangleInterface, - ], - 'oneOf': [ - ], - } +from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.pyi new file mode 100644 index 0000000000..b602ba62d5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.pyi @@ -0,0 +1,126 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ScaleneTriangle( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class triangleType( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def SCALENE_TRIANGLE(cls): + return cls("ScaleneTriangle") + __annotations__ = { + "triangleType": triangleType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["triangleType"]) -> typing.Union[MetaOapg.properties.triangleType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["triangleType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + triangleType: typing.Union[MetaOapg.properties.triangleType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + triangleType=triangleType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + TriangleInterface, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ScaleneTriangle': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape.py index 0256572402..bab6e983c8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,330 +9,69 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.quadrilateral import Quadrilateral - from petstore_api.model.triangle import Triangle - globals()['Quadrilateral'] = Quadrilateral - globals()['Triangle'] = Triangle - - -class Shape(ModelComposed): +class Shape( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'shapeType': { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Triangle, + Quadrilateral, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Shape': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'shape_type': (str,), # noqa: E501 - 'quadrilateral_type': (str,), # noqa: E501 - 'triangle_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - lazy_import() - val = { - 'Quadrilateral': Quadrilateral, - 'Triangle': Triangle, - } - if not val: - return None - return {'shape_type': val} - - attribute_map = { - 'shape_type': 'shapeType', # noqa: E501 - 'quadrilateral_type': 'quadrilateralType', # noqa: E501 - 'triangle_type': 'triangleType', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Shape - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - quadrilateral_type (str): [optional] # noqa: E501 - triangle_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Shape - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - quadrilateral_type (str): [optional] # noqa: E501 - triangle_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - Quadrilateral, - Triangle, - ], - } +from petstore_api.model.quadrilateral import Quadrilateral +from petstore_api.model.triangle import Triangle diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/shape.pyi new file mode 100644 index 0000000000..bab6e983c8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape.pyi @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Shape( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'shapeType': { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + Triangle, + Quadrilateral, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Shape': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.quadrilateral import Quadrilateral +from petstore_api.model.triangle import Triangle diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py index 28bd8ecd4b..10342b8d03 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,331 +9,73 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.quadrilateral import Quadrilateral - from petstore_api.model.triangle import Triangle - globals()['Quadrilateral'] = Quadrilateral - globals()['Triangle'] = Triangle - - -class ShapeOrNull(ModelComposed): +class ShapeOrNull( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'shapeType': { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + } + one_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + Triangle, + Quadrilateral, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ShapeOrNull': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'shape_type': (str,), # noqa: E501 - 'quadrilateral_type': (str,), # noqa: E501 - 'triangle_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - lazy_import() - val = { - 'Quadrilateral': Quadrilateral, - 'Triangle': Triangle, - } - if not val: - return None - return {'shape_type': val} - - attribute_map = { - 'shape_type': 'shapeType', # noqa: E501 - 'quadrilateral_type': 'quadrilateralType', # noqa: E501 - 'triangle_type': 'triangleType', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """ShapeOrNull - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - quadrilateral_type (str): [optional] # noqa: E501 - triangle_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """ShapeOrNull - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - quadrilateral_type (str): [optional] # noqa: E501 - triangle_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - Quadrilateral, - Triangle, - none_type, - ], - } +from petstore_api.model.quadrilateral import Quadrilateral +from petstore_api.model.triangle import Triangle diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.pyi new file mode 100644 index 0000000000..10342b8d03 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.pyi @@ -0,0 +1,81 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class ShapeOrNull( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + """ + + + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'shapeType': { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + } + one_of_0 = schemas.NoneSchema + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.one_of_0, + Triangle, + Quadrilateral, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'ShapeOrNull': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.quadrilateral import Quadrilateral +from petstore_api.model.triangle import Triangle diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py index 7c34285120..93d3c1f932 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,320 +9,124 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.quadrilateral_interface import QuadrilateralInterface - from petstore_api.model.shape_interface import ShapeInterface - globals()['QuadrilateralInterface'] = QuadrilateralInterface - globals()['ShapeInterface'] = ShapeInterface - - -class SimpleQuadrilateral(ModelComposed): +class SimpleQuadrilateral( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'shape_type': (str,), # noqa: E501 - 'quadrilateral_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class quadrilateralType( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "SimpleQuadrilateral": "SIMPLE_QUADRILATERAL", + } + + @schemas.classproperty + def SIMPLE_QUADRILATERAL(cls): + return cls("SimpleQuadrilateral") + __annotations__ = { + "quadrilateralType": quadrilateralType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["quadrilateralType"]) -> MetaOapg.properties.quadrilateralType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["quadrilateralType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["quadrilateralType"]) -> typing.Union[MetaOapg.properties.quadrilateralType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["quadrilateralType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + quadrilateralType: typing.Union[MetaOapg.properties.quadrilateralType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + quadrilateralType=quadrilateralType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + QuadrilateralInterface, + cls.all_of_1, + ] - attribute_map = { - 'shape_type': 'shapeType', # noqa: E501 - 'quadrilateral_type': 'quadrilateralType', # noqa: E501 - } + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SimpleQuadrilateral': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """SimpleQuadrilateral - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - quadrilateral_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """SimpleQuadrilateral - a model defined in OpenAPI - - Keyword Args: - shape_type (str): - quadrilateral_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - QuadrilateralInterface, - ShapeInterface, - ], - 'oneOf': [ - ], - } +from petstore_api.model.quadrilateral_interface import QuadrilateralInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.pyi new file mode 100644 index 0000000000..59505edad8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.pyi @@ -0,0 +1,126 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class SimpleQuadrilateral( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + + class all_of_1( + schemas.DictSchema + ): + + + class MetaOapg: + + class properties: + + + class quadrilateralType( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def SIMPLE_QUADRILATERAL(cls): + return cls("SimpleQuadrilateral") + __annotations__ = { + "quadrilateralType": quadrilateralType, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["quadrilateralType"]) -> MetaOapg.properties.quadrilateralType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["quadrilateralType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["quadrilateralType"]) -> typing.Union[MetaOapg.properties.quadrilateralType, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["quadrilateralType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + quadrilateralType: typing.Union[MetaOapg.properties.quadrilateralType, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'all_of_1': + return super().__new__( + cls, + *args, + quadrilateralType=quadrilateralType, + _configuration=_configuration, + **kwargs, + ) + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + QuadrilateralInterface, + cls.all_of_1, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SimpleQuadrilateral': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.quadrilateral_interface import QuadrilateralInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py index cee41c9aa7..3ce8eab0b4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,309 +9,58 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.object_interface import ObjectInterface - globals()['ObjectInterface'] = ObjectInterface - - -class SomeObject(ModelComposed): +class SomeObject( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - } - - @cached_property - def discriminator(): - return None + class MetaOapg: + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + ObjectInterface, + ] - attribute_map = { - } + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SomeObject': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """SomeObject - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """SomeObject - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ObjectInterface, - ], - 'oneOf': [ - ], - } +from petstore_api.model.object_interface import ObjectInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/some_object.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.pyi new file mode 100644 index 0000000000..3ce8eab0b4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.pyi @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class SomeObject( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + ObjectInterface, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SomeObject': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.object_interface import ObjectInterface diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py index 6044e5e100..ca1f5c6ab8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,257 +9,72 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class SpecialModelName(ModelNormal): +class SpecialModelName( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. + model with an invalid class name for python """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + a = schemas.StrSchema + __annotations__ = { + "a": a, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["a"]) -> MetaOapg.properties.a: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["a", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["a"]) -> typing.Union[MetaOapg.properties.a, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["a", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'special_property_name': (int,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'special_property_name': '$special[property.name]', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """SpecialModelName - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - special_property_name (int): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """SpecialModelName - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - special_property_name (int): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + a: typing.Union[MetaOapg.properties.a, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SpecialModelName': + return super().__new__( + cls, + *args, + a=a, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.pyi new file mode 100644 index 0000000000..ca1f5c6ab8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.pyi @@ -0,0 +1,80 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class SpecialModelName( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + model with an invalid class name for python + """ + + + class MetaOapg: + + class properties: + a = schemas.StrSchema + __annotations__ = { + "a": a, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["a"]) -> MetaOapg.properties.a: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["a", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["a"]) -> typing.Union[MetaOapg.properties.a, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["a", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + a: typing.Union[MetaOapg.properties.a, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SpecialModelName': + return super().__new__( + cls, + *args, + a=a, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string.py b/samples/openapi3/client/petstore/python/petstore_api/model/string.py new file mode 100644 index 0000000000..9e0907b426 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +String = schemas.StrSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/string.pyi new file mode 100644 index 0000000000..9e0907b426 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string.pyi @@ -0,0 +1,24 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 +String = schemas.StrSchema diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py index 52b6f39964..9d4a6136b5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,253 +9,49 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class StringBooleanMap(ModelNormal): +class StringBooleanMap( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + additional_properties = schemas.BoolSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """StringBooleanMap - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """StringBooleanMap - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'StringBooleanMap': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.pyi new file mode 100644 index 0000000000..9d4a6136b5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.pyi @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class StringBooleanMap( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + additional_properties = schemas.BoolSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, bool, ], + ) -> 'StringBooleanMap': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py index 0fbdcdc6af..abc1696bc1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,299 +9,81 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class StringEnum(ModelSimple): +class StringEnum( + schemas.EnumBase, + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('value',): { - 'None': None, - 'PLACED': "placed", - 'APPROVED': "approved", - 'DELIVERED': "delivered", - 'SINGLE_QUOTED': "single quoted", - 'MULTIPLE_LINES': '''multiple -lines''', - 'DOUBLE_QUOTE_WITH_NEWLINE': '''double quote - with newline''', - }, - } - validations = { - } - - additional_properties_type = None - - _nullable = True - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (str,), + class MetaOapg: + enum_value_to_name = { + "placed": "PLACED", + "approved": "APPROVED", + "delivered": "DELIVERED", + "single quoted": "SINGLE_QUOTED", + "multiple\nlines": "MULTIPLE_LINES", + "double quote \n with newline": "DOUBLE_QUOTE_WITH_NEWLINE", + schemas.NoneClass.NONE: "NONE", } - - @cached_property - def discriminator(): - return None + + @schemas.classproperty + def PLACED(cls): + return cls("placed") + + @schemas.classproperty + def APPROVED(cls): + return cls("approved") + + @schemas.classproperty + def DELIVERED(cls): + return cls("delivered") + + @schemas.classproperty + def SINGLE_QUOTED(cls): + return cls("single quoted") + + @schemas.classproperty + def MULTIPLE_LINES(cls): + return cls("multiple\nlines") + + @schemas.classproperty + def DOUBLE_QUOTE_WITH_NEWLINE(cls): + return cls("double quote \n with newline") + + @schemas.classproperty + def NONE(cls): + return cls(None) - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """StringEnum - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple -lines''', '''double quote - with newline''', ] # noqa: E501 - - Keyword Args: - value (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple -lines''', '''double quote - with newline''', ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """StringEnum - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple -lines''', '''double quote - with newline''', ] # noqa: E501 - - Keyword Args: - value (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple -lines''', '''double quote - with newline''', ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - raise ApiTypeError( - "value is required, but not passed in args or kwargs and doesn't have default", - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self + def __new__( + cls, + *args: typing.Union[None, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'StringEnum': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.pyi new file mode 100644 index 0000000000..abc1696bc1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.pyi @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class StringEnum( + schemas.EnumBase, + schemas.StrBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneStrMixin +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + enum_value_to_name = { + "placed": "PLACED", + "approved": "APPROVED", + "delivered": "DELIVERED", + "single quoted": "SINGLE_QUOTED", + "multiple\nlines": "MULTIPLE_LINES", + "double quote \n with newline": "DOUBLE_QUOTE_WITH_NEWLINE", + schemas.NoneClass.NONE: "NONE", + } + + @schemas.classproperty + def PLACED(cls): + return cls("placed") + + @schemas.classproperty + def APPROVED(cls): + return cls("approved") + + @schemas.classproperty + def DELIVERED(cls): + return cls("delivered") + + @schemas.classproperty + def SINGLE_QUOTED(cls): + return cls("single quoted") + + @schemas.classproperty + def MULTIPLE_LINES(cls): + return cls("multiple\nlines") + + @schemas.classproperty + def DOUBLE_QUOTE_WITH_NEWLINE(cls): + return cls("double quote \n with newline") + + @schemas.classproperty + def NONE(cls): + return cls(None) + + + def __new__( + cls, + *args: typing.Union[None, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'StringEnum': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py index 37775c93ca..8526009655 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,277 +9,46 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class StringEnumWithDefaultValue(ModelSimple): +class StringEnumWithDefaultValue( + schemas.EnumBase, + schemas.StrSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('value',): { - 'PLACED': "placed", - 'APPROVED': "approved", - 'DELIVERED': "delivered", - }, - } - validations = { - } - - additional_properties_type = None - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'value': (str,), + class MetaOapg: + enum_value_to_name = { + "placed": "PLACED", + "approved": "APPROVED", + "delivered": "DELIVERED", } - - @cached_property - def discriminator(): - return None - - - attribute_map = {} - - read_only_vars = set() - - _composed_schemas = None - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): - """StringEnumWithDefaultValue - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 - - Keyword Args: - value (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = "placed" - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): - """StringEnumWithDefaultValue - a model defined in OpenAPI - - Note that value can be passed either in args or in kwargs, but not in both. - - Args: - args[0] (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 - - Keyword Args: - value (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - # required up here when default value is not given - _path_to_item = kwargs.pop('_path_to_item', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if 'value' in kwargs: - value = kwargs.pop('value') - elif args: - args = list(args) - value = args.pop(0) - else: - value = "placed" - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.value = value - if kwargs: - raise ApiTypeError( - "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( - kwargs, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - return self + + @schemas.classproperty + def PLACED(cls): + return cls("placed") + + @schemas.classproperty + def APPROVED(cls): + return cls("approved") + + @schemas.classproperty + def DELIVERED(cls): + return cls("delivered") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.pyi new file mode 100644 index 0000000000..e51581c628 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.pyi @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class StringEnumWithDefaultValue( + schemas.EnumBase, + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + @schemas.classproperty + def PLACED(cls): + return cls("placed") + + @schemas.classproperty + def APPROVED(cls): + return cls("approved") + + @schemas.classproperty + def DELIVERED(cls): + return cls("delivered") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_with_validation.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_with_validation.py new file mode 100644 index 0000000000..61ff6fcc31 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_with_validation.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class StringWithValidation( + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + min_length = 7 diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_with_validation.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/string_with_validation.pyi new file mode 100644 index 0000000000..df0be02513 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_with_validation.pyi @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class StringWithValidation( + schemas.StrSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/tag.py b/samples/openapi3/client/petstore/python/petstore_api/model/tag.py index b56728bb6b..a0176eead3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/tag.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/tag.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,261 +9,80 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Tag(ModelNormal): +class Tag( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + class properties: + id = schemas.Int64Schema + name = schemas.StrSchema + __annotations__ = { + "id": id, + "name": name, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["id", "name", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["id", "name", ], str]): + return super().get_item_oapg(name) + - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'id': (int,), # noqa: E501 - 'name': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'id': 'id', # noqa: E501 - 'name': 'name', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Tag - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - name (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Tag - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - name (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + name: typing.Union[MetaOapg.properties.name, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Tag': + return super().__new__( + cls, + *args, + id=id, + name=name, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/tag.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/tag.pyi new file mode 100644 index 0000000000..a0176eead3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/tag.pyi @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Tag( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + id = schemas.Int64Schema + name = schemas.StrSchema + __annotations__ = { + "id": id, + "name": name, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["id", "name", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["id", "name", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + name: typing.Union[MetaOapg.properties.name, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Tag': + return super().__new__( + cls, + *args, + id=id, + name=name, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py index fd9103c96b..0701b6d511 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,330 +9,72 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 -def lazy_import(): - from petstore_api.model.equilateral_triangle import EquilateralTriangle - from petstore_api.model.isosceles_triangle import IsoscelesTriangle - from petstore_api.model.scalene_triangle import ScaleneTriangle - globals()['EquilateralTriangle'] = EquilateralTriangle - globals()['IsoscelesTriangle'] = IsoscelesTriangle - globals()['ScaleneTriangle'] = ScaleneTriangle - - -class Triangle(ModelComposed): +class Triangle( + schemas.ComposedSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'triangleType': { + 'EquilateralTriangle': EquilateralTriangle, + 'IsoscelesTriangle': IsoscelesTriangle, + 'ScaleneTriangle': ScaleneTriangle, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + EquilateralTriangle, + IsoscelesTriangle, + ScaleneTriangle, + ] - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - _nullable = False + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Triangle': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'triangle_type': (str,), # noqa: E501 - 'shape_type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - lazy_import() - val = { - 'EquilateralTriangle': EquilateralTriangle, - 'IsoscelesTriangle': IsoscelesTriangle, - 'ScaleneTriangle': ScaleneTriangle, - } - if not val: - return None - return {'triangle_type': val} - - attribute_map = { - 'triangle_type': 'triangleType', # noqa: E501 - 'shape_type': 'shapeType', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Triangle - a model defined in OpenAPI - - Keyword Args: - triangle_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - shape_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Triangle - a model defined in OpenAPI - - Keyword Args: - triangle_type (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - shape_type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - EquilateralTriangle, - IsoscelesTriangle, - ScaleneTriangle, - ], - } +from petstore_api.model.equilateral_triangle import EquilateralTriangle +from petstore_api.model.isosceles_triangle import IsoscelesTriangle +from petstore_api.model.scalene_triangle import ScaleneTriangle diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.pyi new file mode 100644 index 0000000000..0701b6d511 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.pyi @@ -0,0 +1,80 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Triangle( + schemas.ComposedSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + @staticmethod + def discriminator(): + return { + 'triangleType': { + 'EquilateralTriangle': EquilateralTriangle, + 'IsoscelesTriangle': IsoscelesTriangle, + 'ScaleneTriangle': ScaleneTriangle, + } + } + + @classmethod + @functools.lru_cache() + def one_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + EquilateralTriangle, + IsoscelesTriangle, + ScaleneTriangle, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Triangle': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + +from petstore_api.model.equilateral_triangle import EquilateralTriangle +from petstore_api.model.isosceles_triangle import IsoscelesTriangle +from petstore_api.model.scalene_triangle import ScaleneTriangle diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py index 3bb817d86b..7ac28c0031 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,263 +9,103 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class TriangleInterface(ModelNormal): +class TriangleInterface( + schemas.AnyTypeSchema, +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'triangle_type': (str,), # noqa: E501 + class MetaOapg: + required = { + "shapeType", + "triangleType", } + + class properties: + + + class shapeType( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "Triangle": "TRIANGLE", + } + + @schemas.classproperty + def TRIANGLE(cls): + return cls("Triangle") + triangleType = schemas.StrSchema + __annotations__ = { + "shapeType": shapeType, + "triangleType": triangleType, + } - @cached_property - def discriminator(): - return None + + shapeType: MetaOapg.properties.shapeType + triangleType: MetaOapg.properties.triangleType + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shapeType"]) -> MetaOapg.properties.shapeType: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["shapeType", "triangleType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shapeType"]) -> MetaOapg.properties.shapeType: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["shapeType", "triangleType", ], str]): + return super().get_item_oapg(name) + - - attribute_map = { - 'triangle_type': 'triangleType', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, triangle_type, *args, **kwargs): # noqa: E501 - """TriangleInterface - a model defined in OpenAPI - - Args: - triangle_type (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.triangle_type = triangle_type - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, triangle_type, *args, **kwargs): # noqa: E501 - """TriangleInterface - a model defined in OpenAPI - - Args: - triangle_type (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.triangle_type = triangle_type - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + shapeType: typing.Union[MetaOapg.properties.shapeType, str, ], + triangleType: typing.Union[MetaOapg.properties.triangleType, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'TriangleInterface': + return super().__new__( + cls, + *args, + shapeType=shapeType, + triangleType=triangleType, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.pyi new file mode 100644 index 0000000000..86b525d359 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.pyi @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class TriangleInterface( + schemas.AnyTypeSchema, +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "shapeType", + "triangleType", + } + + class properties: + + + class shapeType( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def TRIANGLE(cls): + return cls("Triangle") + triangleType = schemas.StrSchema + __annotations__ = { + "shapeType": shapeType, + "triangleType": triangleType, + } + + + shapeType: MetaOapg.properties.shapeType + triangleType: MetaOapg.properties.triangleType + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["shapeType"]) -> MetaOapg.properties.shapeType: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["shapeType", "triangleType", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["shapeType"]) -> MetaOapg.properties.shapeType: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["triangleType"]) -> MetaOapg.properties.triangleType: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["shapeType", "triangleType", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + shapeType: typing.Union[MetaOapg.properties.shapeType, str, ], + triangleType: typing.Union[MetaOapg.properties.triangleType, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'TriangleInterface': + return super().__new__( + cls, + *args, + shapeType=shapeType, + triangleType=triangleType, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/user.py b/samples/openapi3/client/petstore/python/petstore_api/model/user.py index a8056b29a2..c8beb19d82 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/user.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/user.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,301 +9,233 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class User(ModelNormal): +class User( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'id': (int,), # noqa: E501 - 'username': (str,), # noqa: E501 - 'first_name': (str,), # noqa: E501 - 'last_name': (str,), # noqa: E501 - 'email': (str,), # noqa: E501 - 'password': (str,), # noqa: E501 - 'phone': (str,), # noqa: E501 - 'user_status': (int,), # noqa: E501 - 'object_with_no_declared_props': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - 'object_with_no_declared_props_nullable': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type,), # noqa: E501 - 'any_type_prop': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 - 'any_type_prop_nullable': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 - } - - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'id': 'id', # noqa: E501 - 'username': 'username', # noqa: E501 - 'first_name': 'firstName', # noqa: E501 - 'last_name': 'lastName', # noqa: E501 - 'email': 'email', # noqa: E501 - 'password': 'password', # noqa: E501 - 'phone': 'phone', # noqa: E501 - 'user_status': 'userStatus', # noqa: E501 - 'object_with_no_declared_props': 'objectWithNoDeclaredProps', # noqa: E501 - 'object_with_no_declared_props_nullable': 'objectWithNoDeclaredPropsNullable', # noqa: E501 - 'any_type_prop': 'anyTypeProp', # noqa: E501 - 'any_type_prop_nullable': 'anyTypePropNullable', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """User - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - username (str): [optional] # noqa: E501 - first_name (str): [optional] # noqa: E501 - last_name (str): [optional] # noqa: E501 - email (str): [optional] # noqa: E501 - password (str): [optional] # noqa: E501 - phone (str): [optional] # noqa: E501 - user_status (int): User Status. [optional] # noqa: E501 - object_with_no_declared_props ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value.. [optional] # noqa: E501 - object_with_no_declared_props_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): test code generation for nullable objects. Value must be a map of strings to values or the 'null' value.. [optional] # noqa: E501 - any_type_prop (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389. [optional] # noqa: E501 - any_type_prop_nullable (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values.. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + class MetaOapg: + + class properties: + id = schemas.Int64Schema + username = schemas.StrSchema + firstName = schemas.StrSchema + lastName = schemas.StrSchema + email = schemas.StrSchema + password = schemas.StrSchema + phone = schemas.StrSchema + userStatus = schemas.Int32Schema + objectWithNoDeclaredProps = schemas.DictSchema + + + class objectWithNoDeclaredPropsNullable( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'objectWithNoDeclaredPropsNullable': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """User - a model defined in OpenAPI - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - id (int): [optional] # noqa: E501 - username (str): [optional] # noqa: E501 - first_name (str): [optional] # noqa: E501 - last_name (str): [optional] # noqa: E501 - email (str): [optional] # noqa: E501 - password (str): [optional] # noqa: E501 - phone (str): [optional] # noqa: E501 - user_status (int): User Status. [optional] # noqa: E501 - object_with_no_declared_props ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value.. [optional] # noqa: E501 - object_with_no_declared_props_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): test code generation for nullable objects. Value must be a map of strings to values or the 'null' value.. [optional] # noqa: E501 - any_type_prop (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389. [optional] # noqa: E501 - any_type_prop_nullable (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values.. [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), + anyTypeProp = schemas.AnyTypeSchema + + + class anyTypeExceptNullProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + not_schema = schemas.NoneSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'anyTypeExceptNullProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, ) + anyTypePropNullable = schemas.AnyTypeSchema + __annotations__ = { + "id": id, + "username": username, + "firstName": firstName, + "lastName": lastName, + "email": email, + "password": password, + "phone": phone, + "userStatus": userStatus, + "objectWithNoDeclaredProps": objectWithNoDeclaredProps, + "objectWithNoDeclaredPropsNullable": objectWithNoDeclaredPropsNullable, + "anyTypeProp": anyTypeProp, + "anyTypeExceptNullProp": anyTypeExceptNullProp, + "anyTypePropNullable": anyTypePropNullable, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["username"]) -> MetaOapg.properties.username: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["firstName"]) -> MetaOapg.properties.firstName: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["lastName"]) -> MetaOapg.properties.lastName: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["email"]) -> MetaOapg.properties.email: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["password"]) -> MetaOapg.properties.password: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["phone"]) -> MetaOapg.properties.phone: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["userStatus"]) -> MetaOapg.properties.userStatus: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["objectWithNoDeclaredProps"]) -> MetaOapg.properties.objectWithNoDeclaredProps: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["objectWithNoDeclaredPropsNullable"]) -> MetaOapg.properties.objectWithNoDeclaredPropsNullable: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["anyTypeProp"]) -> MetaOapg.properties.anyTypeProp: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["anyTypeExceptNullProp"]) -> MetaOapg.properties.anyTypeExceptNullProp: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["anyTypePropNullable"]) -> MetaOapg.properties.anyTypePropNullable: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus", "objectWithNoDeclaredProps", "objectWithNoDeclaredPropsNullable", "anyTypeProp", "anyTypeExceptNullProp", "anyTypePropNullable", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["username"]) -> typing.Union[MetaOapg.properties.username, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["firstName"]) -> typing.Union[MetaOapg.properties.firstName, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["lastName"]) -> typing.Union[MetaOapg.properties.lastName, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["email"]) -> typing.Union[MetaOapg.properties.email, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["password"]) -> typing.Union[MetaOapg.properties.password, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["phone"]) -> typing.Union[MetaOapg.properties.phone, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["userStatus"]) -> typing.Union[MetaOapg.properties.userStatus, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["objectWithNoDeclaredProps"]) -> typing.Union[MetaOapg.properties.objectWithNoDeclaredProps, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["objectWithNoDeclaredPropsNullable"]) -> typing.Union[MetaOapg.properties.objectWithNoDeclaredPropsNullable, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["anyTypeProp"]) -> typing.Union[MetaOapg.properties.anyTypeProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["anyTypeExceptNullProp"]) -> typing.Union[MetaOapg.properties.anyTypeExceptNullProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["anyTypePropNullable"]) -> typing.Union[MetaOapg.properties.anyTypePropNullable, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus", "objectWithNoDeclaredProps", "objectWithNoDeclaredPropsNullable", "anyTypeProp", "anyTypeExceptNullProp", "anyTypePropNullable", ], str]): + return super().get_item_oapg(name) + - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + username: typing.Union[MetaOapg.properties.username, str, schemas.Unset] = schemas.unset, + firstName: typing.Union[MetaOapg.properties.firstName, str, schemas.Unset] = schemas.unset, + lastName: typing.Union[MetaOapg.properties.lastName, str, schemas.Unset] = schemas.unset, + email: typing.Union[MetaOapg.properties.email, str, schemas.Unset] = schemas.unset, + password: typing.Union[MetaOapg.properties.password, str, schemas.Unset] = schemas.unset, + phone: typing.Union[MetaOapg.properties.phone, str, schemas.Unset] = schemas.unset, + userStatus: typing.Union[MetaOapg.properties.userStatus, decimal.Decimal, int, schemas.Unset] = schemas.unset, + objectWithNoDeclaredProps: typing.Union[MetaOapg.properties.objectWithNoDeclaredProps, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + objectWithNoDeclaredPropsNullable: typing.Union[MetaOapg.properties.objectWithNoDeclaredPropsNullable, dict, frozendict.frozendict, None, schemas.Unset] = schemas.unset, + anyTypeProp: typing.Union[MetaOapg.properties.anyTypeProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + anyTypeExceptNullProp: typing.Union[MetaOapg.properties.anyTypeExceptNullProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + anyTypePropNullable: typing.Union[MetaOapg.properties.anyTypePropNullable, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'User': + return super().__new__( + cls, + *args, + id=id, + username=username, + firstName=firstName, + lastName=lastName, + email=email, + password=password, + phone=phone, + userStatus=userStatus, + objectWithNoDeclaredProps=objectWithNoDeclaredProps, + objectWithNoDeclaredPropsNullable=objectWithNoDeclaredPropsNullable, + anyTypeProp=anyTypeProp, + anyTypeExceptNullProp=anyTypeExceptNullProp, + anyTypePropNullable=anyTypePropNullable, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/user.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/user.pyi new file mode 100644 index 0000000000..c8beb19d82 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/user.pyi @@ -0,0 +1,241 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class User( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + + class properties: + id = schemas.Int64Schema + username = schemas.StrSchema + firstName = schemas.StrSchema + lastName = schemas.StrSchema + email = schemas.StrSchema + password = schemas.StrSchema + phone = schemas.StrSchema + userStatus = schemas.Int32Schema + objectWithNoDeclaredProps = schemas.DictSchema + + + class objectWithNoDeclaredPropsNullable( + schemas.DictBase, + schemas.NoneBase, + schemas.Schema, + schemas.NoneFrozenDictMixin + ): + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, None, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'objectWithNoDeclaredPropsNullable': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + anyTypeProp = schemas.AnyTypeSchema + + + class anyTypeExceptNullProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + not_schema = schemas.NoneSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'anyTypeExceptNullProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + anyTypePropNullable = schemas.AnyTypeSchema + __annotations__ = { + "id": id, + "username": username, + "firstName": firstName, + "lastName": lastName, + "email": email, + "password": password, + "phone": phone, + "userStatus": userStatus, + "objectWithNoDeclaredProps": objectWithNoDeclaredProps, + "objectWithNoDeclaredPropsNullable": objectWithNoDeclaredPropsNullable, + "anyTypeProp": anyTypeProp, + "anyTypeExceptNullProp": anyTypeExceptNullProp, + "anyTypePropNullable": anyTypePropNullable, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["id"]) -> MetaOapg.properties.id: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["username"]) -> MetaOapg.properties.username: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["firstName"]) -> MetaOapg.properties.firstName: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["lastName"]) -> MetaOapg.properties.lastName: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["email"]) -> MetaOapg.properties.email: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["password"]) -> MetaOapg.properties.password: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["phone"]) -> MetaOapg.properties.phone: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["userStatus"]) -> MetaOapg.properties.userStatus: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["objectWithNoDeclaredProps"]) -> MetaOapg.properties.objectWithNoDeclaredProps: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["objectWithNoDeclaredPropsNullable"]) -> MetaOapg.properties.objectWithNoDeclaredPropsNullable: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["anyTypeProp"]) -> MetaOapg.properties.anyTypeProp: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["anyTypeExceptNullProp"]) -> MetaOapg.properties.anyTypeExceptNullProp: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["anyTypePropNullable"]) -> MetaOapg.properties.anyTypePropNullable: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus", "objectWithNoDeclaredProps", "objectWithNoDeclaredPropsNullable", "anyTypeProp", "anyTypeExceptNullProp", "anyTypePropNullable", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["id"]) -> typing.Union[MetaOapg.properties.id, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["username"]) -> typing.Union[MetaOapg.properties.username, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["firstName"]) -> typing.Union[MetaOapg.properties.firstName, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["lastName"]) -> typing.Union[MetaOapg.properties.lastName, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["email"]) -> typing.Union[MetaOapg.properties.email, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["password"]) -> typing.Union[MetaOapg.properties.password, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["phone"]) -> typing.Union[MetaOapg.properties.phone, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["userStatus"]) -> typing.Union[MetaOapg.properties.userStatus, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["objectWithNoDeclaredProps"]) -> typing.Union[MetaOapg.properties.objectWithNoDeclaredProps, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["objectWithNoDeclaredPropsNullable"]) -> typing.Union[MetaOapg.properties.objectWithNoDeclaredPropsNullable, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["anyTypeProp"]) -> typing.Union[MetaOapg.properties.anyTypeProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["anyTypeExceptNullProp"]) -> typing.Union[MetaOapg.properties.anyTypeExceptNullProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["anyTypePropNullable"]) -> typing.Union[MetaOapg.properties.anyTypePropNullable, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus", "objectWithNoDeclaredProps", "objectWithNoDeclaredPropsNullable", "anyTypeProp", "anyTypeExceptNullProp", "anyTypePropNullable", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + id: typing.Union[MetaOapg.properties.id, decimal.Decimal, int, schemas.Unset] = schemas.unset, + username: typing.Union[MetaOapg.properties.username, str, schemas.Unset] = schemas.unset, + firstName: typing.Union[MetaOapg.properties.firstName, str, schemas.Unset] = schemas.unset, + lastName: typing.Union[MetaOapg.properties.lastName, str, schemas.Unset] = schemas.unset, + email: typing.Union[MetaOapg.properties.email, str, schemas.Unset] = schemas.unset, + password: typing.Union[MetaOapg.properties.password, str, schemas.Unset] = schemas.unset, + phone: typing.Union[MetaOapg.properties.phone, str, schemas.Unset] = schemas.unset, + userStatus: typing.Union[MetaOapg.properties.userStatus, decimal.Decimal, int, schemas.Unset] = schemas.unset, + objectWithNoDeclaredProps: typing.Union[MetaOapg.properties.objectWithNoDeclaredProps, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + objectWithNoDeclaredPropsNullable: typing.Union[MetaOapg.properties.objectWithNoDeclaredPropsNullable, dict, frozendict.frozendict, None, schemas.Unset] = schemas.unset, + anyTypeProp: typing.Union[MetaOapg.properties.anyTypeProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + anyTypeExceptNullProp: typing.Union[MetaOapg.properties.anyTypeExceptNullProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + anyTypePropNullable: typing.Union[MetaOapg.properties.anyTypePropNullable, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'User': + return super().__new__( + cls, + *args, + id=id, + username=username, + firstName=firstName, + lastName=lastName, + email=email, + password=password, + phone=phone, + userStatus=userStatus, + objectWithNoDeclaredProps=objectWithNoDeclaredProps, + objectWithNoDeclaredPropsNullable=objectWithNoDeclaredPropsNullable, + anyTypeProp=anyTypeProp, + anyTypeExceptNullProp=anyTypeExceptNullProp, + anyTypePropNullable=anyTypePropNullable, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/uuid_string.py b/samples/openapi3/client/petstore/python/petstore_api/model/uuid_string.py new file mode 100644 index 0000000000..92a3825e37 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/uuid_string.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class UUIDString( + schemas.UUIDSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + format = 'uuid' + min_length = 1 diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/uuid_string.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/uuid_string.pyi new file mode 100644 index 0000000000..80495060cf --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/uuid_string.pyi @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class UUIDString( + schemas.UUIDSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + pass diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/whale.py b/samples/openapi3/client/petstore/python/petstore_api/model/whale.py index 7c1a842671..b645789bd1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/whale.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/whale.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,271 +9,110 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Whale(ModelNormal): +class Whale( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'class_name': (str,), # noqa: E501 - 'has_baleen': (bool,), # noqa: E501 - 'has_teeth': (bool,), # noqa: E501 + class MetaOapg: + required = { + "className", } + + class properties: + + + class className( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "whale": "WHALE", + } + + @schemas.classproperty + def WHALE(cls): + return cls("whale") + hasBaleen = schemas.BoolSchema + hasTeeth = schemas.BoolSchema + __annotations__ = { + "className": className, + "hasBaleen": hasBaleen, + "hasTeeth": hasTeeth, + } + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["hasBaleen"]) -> MetaOapg.properties.hasBaleen: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["hasTeeth"]) -> MetaOapg.properties.hasTeeth: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className", "hasBaleen", "hasTeeth", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["hasBaleen"]) -> typing.Union[MetaOapg.properties.hasBaleen, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["hasTeeth"]) -> typing.Union[MetaOapg.properties.hasTeeth, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className", "hasBaleen", "hasTeeth", ], str]): + return super().get_item_oapg(name) + - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'has_baleen': 'hasBaleen', # noqa: E501 - 'has_teeth': 'hasTeeth', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 - """Whale - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - has_baleen (bool): [optional] # noqa: E501 - has_teeth (bool): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 - """Whale - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - has_baleen (bool): [optional] # noqa: E501 - has_teeth (bool): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + hasBaleen: typing.Union[MetaOapg.properties.hasBaleen, bool, schemas.Unset] = schemas.unset, + hasTeeth: typing.Union[MetaOapg.properties.hasTeeth, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Whale': + return super().__new__( + cls, + *args, + className=className, + hasBaleen=hasBaleen, + hasTeeth=hasTeeth, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/whale.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/whale.pyi new file mode 100644 index 0000000000..48e2538cb8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/whale.pyi @@ -0,0 +1,112 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Whale( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "className", + } + + class properties: + + + class className( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def WHALE(cls): + return cls("whale") + hasBaleen = schemas.BoolSchema + hasTeeth = schemas.BoolSchema + __annotations__ = { + "className": className, + "hasBaleen": hasBaleen, + "hasTeeth": hasTeeth, + } + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["hasBaleen"]) -> MetaOapg.properties.hasBaleen: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["hasTeeth"]) -> MetaOapg.properties.hasTeeth: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className", "hasBaleen", "hasTeeth", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["hasBaleen"]) -> typing.Union[MetaOapg.properties.hasBaleen, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["hasTeeth"]) -> typing.Union[MetaOapg.properties.hasTeeth, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className", "hasBaleen", "hasTeeth", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + hasBaleen: typing.Union[MetaOapg.properties.hasBaleen, bool, schemas.Unset] = schemas.unset, + hasTeeth: typing.Union[MetaOapg.properties.hasTeeth, bool, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'Whale': + return super().__new__( + cls, + *args, + className=className, + hasBaleen=hasBaleen, + hasTeeth=hasTeeth, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py index b6d2fe934d..960a43f592 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,272 +9,124 @@ Generated by: https://openapi-generator.tech """ - +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 import re # noqa: F401 -import sys # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 - -class Zebra(ModelNormal): +class Zebra( + schemas.DictSchema +): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. """ - allowed_values = { - ('type',): { - 'PLAINS': "plains", - 'MOUNTAIN': "mountain", - 'GREVYS': "grevys", - }, - } - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - return { - 'class_name': (str,), # noqa: E501 - 'type': (str,), # noqa: E501 + class MetaOapg: + required = { + "className", } + + class properties: + + + class className( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "zebra": "ZEBRA", + } + + @schemas.classproperty + def ZEBRA(cls): + return cls("zebra") + + + class type( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "plains": "PLAINS", + "mountain": "MOUNTAIN", + "grevys": "GREVYS", + } + + @schemas.classproperty + def PLAINS(cls): + return cls("plains") + + @schemas.classproperty + def MOUNTAIN(cls): + return cls("mountain") + + @schemas.classproperty + def GREVYS(cls): + return cls("grevys") + __annotations__ = { + "className": className, + "type": type, + } + additional_properties = schemas.AnyTypeSchema + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["type"]) -> MetaOapg.properties.type: ... + + @typing.overload + def __getitem__(self, name: str) -> MetaOapg.additional_properties: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className"], typing_extensions.Literal["type"], str, ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["type"]) -> typing.Union[MetaOapg.properties.type, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[MetaOapg.additional_properties, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className"], typing_extensions.Literal["type"], str, ]): + return super().get_item_oapg(name) - @cached_property - def discriminator(): - return None - - - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'type': 'type', # noqa: E501 - } - - read_only_vars = { - } - - _composed_schemas = {} - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 - """Zebra - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', True) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - ]) - - @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 - """Zebra - a model defined in OpenAPI - - Args: - class_name (str): - - Keyword Args: - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - self.class_name = class_name - for var_name, var_value in kwargs.items(): - if var_name not in self.attribute_map and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self.additional_properties_type is None: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + type: typing.Union[MetaOapg.properties.type, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'Zebra': + return super().__new__( + cls, + *args, + className=className, + type=type, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/zebra.pyi b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.pyi new file mode 100644 index 0000000000..3666395b31 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.pyi @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + +class Zebra( + schemas.DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + + class MetaOapg: + required = { + "className", + } + + class properties: + + + class className( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def ZEBRA(cls): + return cls("zebra") + + + class type( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def PLAINS(cls): + return cls("plains") + + @schemas.classproperty + def MOUNTAIN(cls): + return cls("mountain") + + @schemas.classproperty + def GREVYS(cls): + return cls("grevys") + __annotations__ = { + "className": className, + "type": type, + } + additional_properties = schemas.AnyTypeSchema + + className: MetaOapg.properties.className + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["type"]) -> MetaOapg.properties.type: ... + + @typing.overload + def __getitem__(self, name: str) -> MetaOapg.additional_properties: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["className"], typing_extensions.Literal["type"], str, ]): + # dict_instance[name] accessor + return super().__getitem__(name) + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["className"]) -> MetaOapg.properties.className: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["type"]) -> typing.Union[MetaOapg.properties.type, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[MetaOapg.additional_properties, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["className"], typing_extensions.Literal["type"], str, ]): + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + className: typing.Union[MetaOapg.properties.className, str, ], + type: typing.Union[MetaOapg.properties.type, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + ) -> 'Zebra': + return super().__new__( + cls, + *args, + className=className, + type=type, + _configuration=_configuration, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model_utils.py b/samples/openapi3/client/petstore/python/petstore_api/model_utils.py deleted file mode 100644 index 933ceec6fa..0000000000 --- a/samples/openapi3/client/petstore/python/petstore_api/model_utils.py +++ /dev/null @@ -1,2058 +0,0 @@ -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from datetime import date, datetime # noqa: F401 -from copy import deepcopy -import inspect -import io -import os -import pprint -import re -import tempfile -import uuid - -from dateutil.parser import parse - -from petstore_api.exceptions import ( - ApiKeyError, - ApiAttributeError, - ApiTypeError, - ApiValueError, -) - -none_type = type(None) -file_type = io.IOBase - - -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python( - kwargs, _self if isinstance( - _self, type) else _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - -class cached_property(object): - # this caches the result of the function call for fn with no inputs - # use this as a decorator on function methods that you want converted - # into cached properties - result_key = '_results' - - def __init__(self, fn): - self._fn = fn - - def __get__(self, instance, cls=None): - if self.result_key in vars(self): - return vars(self)[self.result_key] - else: - result = self._fn() - setattr(self, self.result_key, result) - return result - - -PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) - - -def allows_single_value_input(cls): - """ - This function returns True if the input composed schema model or any - descendant model allows a value only input - This is true for cases where oneOf contains items like: - oneOf: - - float - - NumberWithValidation - - StringEnum - - ArrayModel - - null - TODO: lru_cache this - """ - if ( - issubclass(cls, ModelSimple) or - cls in PRIMITIVE_TYPES - ): - return True - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas['oneOf']: - return False - return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) - return False - - -def composed_model_input_classes(cls): - """ - This function returns a list of the possible models that can be accepted as - inputs. - TODO: lru_cache this - """ - if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: - return [cls] - elif issubclass(cls, ModelNormal): - if cls.discriminator is None: - return [cls] - else: - return get_discriminated_classes(cls) - elif issubclass(cls, ModelComposed): - if not cls._composed_schemas['oneOf']: - return [] - if cls.discriminator is None: - input_classes = [] - for c in cls._composed_schemas['oneOf']: - input_classes.extend(composed_model_input_classes(c)) - return input_classes - else: - return get_discriminated_classes(cls) - return [] - - -class OpenApiModel(object): - """The base class for all OpenAPIModels""" - - def set_attribute(self, name, value): - # this is only used to set properties on self - - path_to_item = [] - if self._path_to_item: - path_to_item.extend(self._path_to_item) - path_to_item.append(name) - - if name in self.openapi_types: - required_types_mixed = self.openapi_types[name] - elif self.additional_properties_type is None: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - path_to_item - ) - elif self.additional_properties_type is not None: - required_types_mixed = self.additional_properties_type - - if get_simple_class(name) != str: - error_msg = type_error_message( - var_name=name, - var_value=name, - valid_classes=(str,), - key_type=True - ) - raise ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=(str,), - key_type=True - ) - - if self._check_type: - value = validate_and_convert_types( - value, required_types_mixed, path_to_item, self._spec_property_naming, - self._check_type, configuration=self._configuration) - if (name,) in self.allowed_values: - check_allowed_values( - self.allowed_values, - (name,), - value - ) - if (name,) in self.validations: - check_validations( - self.validations, - (name,), - value, - self._configuration - ) - self.__dict__['_data_store'][name] = value - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other - - def __setattr__(self, attr, value): - """set the value of an attribute using dot notation: `instance.attr = val`""" - self[attr] = value - - def __getattr__(self, attr): - """get the value of an attribute using dot notation: `instance.attr`""" - return self.__getitem__(attr) - - def __copy__(self): - cls = self.__class__ - if self.get("_spec_property_naming", False): - return cls._new_from_openapi_data(**self.__dict__) - else: - return cls.__new__(cls, **self.__dict__) - - def __deepcopy__(self, memo): - cls = self.__class__ - - if self.get("_spec_property_naming", False): - new_inst = cls._new_from_openapi_data() - else: - new_inst = cls.__new__(cls) - - for k, v in self.__dict__.items(): - setattr(new_inst, k, deepcopy(v, memo)) - return new_inst - - - def __new__(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get('_visited_composed_classes', ()) - if ( - cls.discriminator is None or - cls in visited_composed_classes - ): - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: If Animal has a discriminator - # petType and we pass in "Dog", and the class Dog - # allOf includes Animal, we move through Animal - # once using the discriminator, and pick Dog. - # Then in the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return super(OpenApiModel, cls).__new__(cls) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % - (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class( - cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get('_path_to_item', ()) - disc_prop_value = kwargs.get( - discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % - (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return super(OpenApiModel, cls).__new__(cls) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = ( - cls._composed_schemas.get('oneOf', ()) + - cls._composed_schemas.get('anyOf', ())) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get('allOf') and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = super(OpenApiModel, cls).__new__(cls) - self_inst.__init__(*args, **kwargs) - - if kwargs.get("_spec_property_naming", False): - # when true, implies new is from deserialization - new_inst = new_cls._new_from_openapi_data(*args, **kwargs) - else: - new_inst = new_cls.__new__(new_cls, *args, **kwargs) - new_inst.__init__(*args, **kwargs) - - return new_inst - - @classmethod - @convert_js_args_to_python_args - def _new_from_openapi_data(cls, *args, **kwargs): - # this function uses the discriminator to - # pick a new schema/class to instantiate because a discriminator - # propertyName value was passed in - - if len(args) == 1: - arg = args[0] - if arg is None and is_type_nullable(cls): - # The input data is the 'null' value and the type is nullable. - return None - - if issubclass(cls, ModelComposed) and allows_single_value_input(cls): - model_kwargs = {} - oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) - return oneof_instance - - visited_composed_classes = kwargs.get('_visited_composed_classes', ()) - if ( - cls.discriminator is None or - cls in visited_composed_classes - ): - # Use case 1: this openapi schema (cls) does not have a discriminator - # Use case 2: we have already visited this class before and are sure that we - # want to instantiate it this time. We have visited this class deserializing - # a payload with a discriminator. During that process we traveled through - # this class but did not make an instance of it. Now we are making an - # instance of a composed class which contains cls in it, so this time make an instance of cls. - # - # Here's an example of use case 2: If Animal has a discriminator - # petType and we pass in "Dog", and the class Dog - # allOf includes Animal, we move through Animal - # once using the discriminator, and pick Dog. - # Then in the composed schema dog Dog, we will make an instance of the - # Animal class (because Dal has allOf: Animal) but this time we won't travel - # through Animal's discriminator because we passed in - # _visited_composed_classes = (Animal,) - - return cls._from_openapi_data(*args, **kwargs) - - # Get the name and value of the discriminator property. - # The discriminator name is obtained from the discriminator meta-data - # and the discriminator value is obtained from the input data. - discr_propertyname_py = list(cls.discriminator.keys())[0] - discr_propertyname_js = cls.attribute_map[discr_propertyname_py] - if discr_propertyname_js in kwargs: - discr_value = kwargs[discr_propertyname_js] - elif discr_propertyname_py in kwargs: - discr_value = kwargs[discr_propertyname_py] - else: - # The input data does not contain the discriminator property. - path_to_item = kwargs.get('_path_to_item', ()) - raise ApiValueError( - "Cannot deserialize input data due to missing discriminator. " - "The discriminator property '%s' is missing at path: %s" % - (discr_propertyname_js, path_to_item) - ) - - # Implementation note: the last argument to get_discriminator_class - # is a list of visited classes. get_discriminator_class may recursively - # call itself and update the list of visited classes, and the initial - # value must be an empty list. Hence not using 'visited_composed_classes' - new_cls = get_discriminator_class( - cls, discr_propertyname_py, discr_value, []) - if new_cls is None: - path_to_item = kwargs.get('_path_to_item', ()) - disc_prop_value = kwargs.get( - discr_propertyname_js, kwargs.get(discr_propertyname_py)) - raise ApiValueError( - "Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '%s'='%s' at path: %s" % - (discr_propertyname_js, disc_prop_value, path_to_item) - ) - - if new_cls in visited_composed_classes: - # if we are making an instance of a composed schema Descendent - # which allOf includes Ancestor, then Ancestor contains - # a discriminator that includes Descendent. - # So if we make an instance of Descendent, we have to make an - # instance of Ancestor to hold the allOf properties. - # This code detects that use case and makes the instance of Ancestor - # For example: - # When making an instance of Dog, _visited_composed_classes = (Dog,) - # then we make an instance of Animal to include in dog._composed_instances - # so when we are here, cls is Animal - # cls.discriminator != None - # cls not in _visited_composed_classes - # new_cls = Dog - # but we know we know that we already have Dog - # because it is in visited_composed_classes - # so make Animal here - return cls._from_openapi_data(*args, **kwargs) - - # Build a list containing all oneOf and anyOf descendants. - oneof_anyof_classes = None - if cls._composed_schemas is not None: - oneof_anyof_classes = ( - cls._composed_schemas.get('oneOf', ()) + - cls._composed_schemas.get('anyOf', ())) - oneof_anyof_child = new_cls in oneof_anyof_classes - kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) - - if cls._composed_schemas.get('allOf') and oneof_anyof_child: - # Validate that we can make self because when we make the - # new_cls it will not include the allOf validations in self - self_inst = cls._from_openapi_data(*args, **kwargs) - - new_inst = new_cls._new_from_openapi_data(*args, **kwargs) - return new_inst - - -class ModelSimple(OpenApiModel): - """the parent class of models whose type != object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__['_data_store'].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__['_data_store'] - - def to_str(self): - """Returns the string representation of the model""" - return str(self.value) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - this_val = self._data_store['value'] - that_val = other._data_store['value'] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - return vals_equal - - -class ModelNormal(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi""" - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - self.set_attribute(name, value) - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - return self.__dict__['_data_store'].get(name, default) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - if name in self: - return self.get(name) - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - if name in self.required_properties: - return name in self.__dict__ - - return name in self.__dict__['_data_store'] - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -class ModelComposed(OpenApiModel): - """the parent class of models whose type == object in their - swagger/openapi and have oneOf/allOf/anyOf - - When one sets a property we use var_name_to_model_instances to store the value in - the correct class instances + run any type checking + validation code. - When one gets a property we use var_name_to_model_instances to get the value - from the correct class instances. - This allows multiple composed schemas to contain the same property with additive - constraints on the value. - - _composed_schemas (dict) stores the anyOf/allOf/oneOf classes - key (str): allOf/oneOf/anyOf - value (list): the classes in the XOf definition. - Note: none_type can be included when the openapi document version >= 3.1.0 - _composed_instances (list): stores a list of instances of the composed schemas - defined in _composed_schemas. When properties are accessed in the self instance, - they are returned from the self._data_store or the data stores in the instances - in self._composed_schemas - _var_name_to_model_instances (dict): maps between a variable name on self and - the composed instances (self included) which contain that data - key (str): property name - value (list): list of class instances, self or instances in _composed_instances - which contain the value that the key is referring to. - """ - - def __setitem__(self, name, value): - """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" - if name in self.required_properties: - self.__dict__[name] = value - return - - """ - Use cases: - 1. additional_properties_type is None (additionalProperties == False in spec) - Check for property presence in self.openapi_types - if not present then throw an error - if present set in self, set attribute - always set on composed schemas - 2. additional_properties_type exists - set attribute on self - always set on composed schemas - """ - if self.additional_properties_type is None: - """ - For an attribute to exist on a composed schema it must: - - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND - - fulfill schema_requirements in each oneOf/anyOf/allOf schemas - - schema_requirements: - For an attribute to exist on a schema it must: - - be present in properties at the schema OR - - have additionalProperties unset (defaults additionalProperties = any type) OR - - have additionalProperties set - """ - if name not in self.openapi_types: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - # attribute must be set on self and composed instances - self.set_attribute(name, value) - for model_instance in self._composed_instances: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] - return None - - __unset_attribute_value__ = object() - - def get(self, name, default=None): - """returns the value of an attribute or some default value if the attribute was not set""" - if name in self.required_properties: - return self.__dict__[name] - - # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get(name) - values = [] - # A composed model stores self and child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. - # Any property must exist in self and all model instances - # The value stored in all model instances must be the same - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - v = model_instance._data_store[name] - if v not in values: - values.append(v) - len_values = len(values) - if len_values == 0: - return default - elif len_values == 1: - return values[0] - elif len_values > 1: - raise ApiValueError( - "Values stored for property {0} in {1} differ when looking " - "at self and self's composed instances. All values must be " - "the same".format(name, type(self).__name__), - [e for e in [self._path_to_item, name] if e] - ) - - def __getitem__(self, name): - """get the value of an attribute using square-bracket notation: `instance[attr]`""" - value = self.get(name, self.__unset_attribute_value__) - if value is self.__unset_attribute_value__: - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) - return value - - def __contains__(self, name): - """used by `in` operator to check if an attribute value was set in an instance: `'attr' in instance`""" - - if name in self.required_properties: - return name in self.__dict__ - - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) - - if model_instances: - for model_instance in model_instances: - if name in model_instance._data_store: - return True - - return False - - def to_dict(self): - """Returns the model properties as a dict""" - return model_to_dict(self, serialize=False) - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, self.__class__): - return False - - if not set(self._data_store.keys()) == set(other._data_store.keys()): - return False - for _var_name, this_val in self._data_store.items(): - that_val = other._data_store[_var_name] - types = set() - types.add(this_val.__class__) - types.add(that_val.__class__) - vals_equal = this_val == that_val - if not vals_equal: - return False - return True - - -COERCION_INDEX_BY_TYPE = { - ModelComposed: 0, - ModelNormal: 1, - ModelSimple: 2, - none_type: 3, # The type of 'None'. - list: 4, - dict: 5, - float: 6, - int: 7, - bool: 8, - datetime: 9, - date: 10, - str: 11, - file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. -} - -# these are used to limit what type conversions we try to do -# when we have a valid type already and we want to try converting -# to another type -UPCONVERSION_TYPE_PAIRS = ( - (str, datetime), - (str, date), - # A float may be serialized as an integer, e.g. '3' is a valid serialized float. - (int, float), - (list, ModelComposed), - (dict, ModelComposed), - (str, ModelComposed), - (int, ModelComposed), - (float, ModelComposed), - (list, ModelComposed), - (list, ModelNormal), - (dict, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), -) - -COERCIBLE_TYPE_PAIRS = { - False: ( # client instantiation of a model with client data - # (dict, ModelComposed), - # (list, ModelComposed), - # (dict, ModelNormal), - # (list, ModelNormal), - # (str, ModelSimple), - # (int, ModelSimple), - # (float, ModelSimple), - # (list, ModelSimple), - # (str, int), - # (str, float), - # (str, datetime), - # (str, date), - # (int, str), - # (float, str), - ), - True: ( # server -> client data - (dict, ModelComposed), - (list, ModelComposed), - (dict, ModelNormal), - (list, ModelNormal), - (str, ModelSimple), - (int, ModelSimple), - (float, ModelSimple), - (list, ModelSimple), - # (str, int), - # (str, float), - (str, datetime), - (str, date), - # (int, str), - # (float, str), - (str, file_type) - ), -} - - -def get_simple_class(input_value): - """Returns an input_value's simple class that we will use for type checking - Python2: - float and int will return int, where int is the python3 int backport - str and unicode will return str, where str is the python3 str backport - Note: float and int ARE both instances of int backport - Note: str_py2 and unicode_py2 are NOT both instances of str backport - - Args: - input_value (class/class_instance): the item for which we will return - the simple class - """ - if isinstance(input_value, type): - # input_value is a class - return input_value - elif isinstance(input_value, tuple): - return tuple - elif isinstance(input_value, list): - return list - elif isinstance(input_value, dict): - return dict - elif isinstance(input_value, none_type): - return none_type - elif isinstance(input_value, file_type): - return file_type - elif isinstance(input_value, bool): - # this must be higher than the int check because - # isinstance(True, int) == True - return bool - elif isinstance(input_value, int): - return int - elif isinstance(input_value, datetime): - # this must be higher than the date check because - # isinstance(datetime_instance, date) == True - return datetime - elif isinstance(input_value, date): - return date - elif isinstance(input_value, str): - return str - return type(input_value) - - -def check_allowed_values(allowed_values, input_variable_path, input_values): - """Raises an exception if the input_values are not allowed - - Args: - allowed_values (dict): the allowed_values dict - input_variable_path (tuple): the path to the input variable - input_values (list/str/int/float/date/datetime): the values that we - are checking to see if they are in allowed_values - """ - these_allowed_values = list(allowed_values[input_variable_path].values()) - if (isinstance(input_values, list) - and not set(input_values).issubset( - set(these_allowed_values))): - invalid_values = ", ".join( - map(str, set(input_values) - set(these_allowed_values))), - raise ApiValueError( - "Invalid values for `%s` [%s], must be a subset of [%s]" % - ( - input_variable_path[0], - invalid_values, - ", ".join(map(str, these_allowed_values)) - ) - ) - elif (isinstance(input_values, dict) - and not set( - input_values.keys()).issubset(set(these_allowed_values))): - invalid_values = ", ".join( - map(str, set(input_values.keys()) - set(these_allowed_values))) - raise ApiValueError( - "Invalid keys in `%s` [%s], must be a subset of [%s]" % - ( - input_variable_path[0], - invalid_values, - ", ".join(map(str, these_allowed_values)) - ) - ) - elif (not isinstance(input_values, (list, dict)) - and input_values not in these_allowed_values): - raise ApiValueError( - "Invalid value for `%s` (%s), must be one of %s" % - ( - input_variable_path[0], - input_values, - these_allowed_values - ) - ) - - -def is_json_validation_enabled(schema_keyword, configuration=None): - """Returns true if JSON schema validation is enabled for the specified - validation keyword. This can be used to skip JSON schema structural validation - as requested in the configuration. - - Args: - schema_keyword (string): the name of a JSON schema validation keyword. - configuration (Configuration): the configuration class. - """ - - return (configuration is None or - not hasattr(configuration, '_disabled_client_side_validations') or - schema_keyword not in configuration._disabled_client_side_validations) - - -def check_validations( - validations, input_variable_path, input_values, - configuration=None): - """Raises an exception if the input_values are invalid - - Args: - validations (dict): the validation dictionary. - input_variable_path (tuple): the path to the input variable. - input_values (list/str/int/float/date/datetime): the values that we - are checking. - configuration (Configuration): the configuration class. - """ - - if input_values is None: - return - - current_validations = validations[input_variable_path] - if (is_json_validation_enabled('multipleOf', configuration) and - 'multiple_of' in current_validations and - isinstance(input_values, (int, float)) and - not (float(input_values) / current_validations['multiple_of']).is_integer()): - # Note 'multipleOf' will be as good as the floating point arithmetic. - raise ApiValueError( - "Invalid value for `%s`, value must be a multiple of " - "`%s`" % ( - input_variable_path[0], - current_validations['multiple_of'] - ) - ) - - if (is_json_validation_enabled('maxLength', configuration) and - 'max_length' in current_validations and - len(input_values) > current_validations['max_length']): - raise ApiValueError( - "Invalid value for `%s`, length must be less than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['max_length'] - ) - ) - - if (is_json_validation_enabled('minLength', configuration) and - 'min_length' in current_validations and - len(input_values) < current_validations['min_length']): - raise ApiValueError( - "Invalid value for `%s`, length must be greater than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['min_length'] - ) - ) - - if (is_json_validation_enabled('maxItems', configuration) and - 'max_items' in current_validations and - len(input_values) > current_validations['max_items']): - raise ApiValueError( - "Invalid value for `%s`, number of items must be less than or " - "equal to `%s`" % ( - input_variable_path[0], - current_validations['max_items'] - ) - ) - - if (is_json_validation_enabled('minItems', configuration) and - 'min_items' in current_validations and - len(input_values) < current_validations['min_items']): - raise ValueError( - "Invalid value for `%s`, number of items must be greater than or " - "equal to `%s`" % ( - input_variable_path[0], - current_validations['min_items'] - ) - ) - - items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', - 'inclusive_minimum') - if (any(item in current_validations for item in items)): - if isinstance(input_values, list): - max_val = max(input_values) - min_val = min(input_values) - elif isinstance(input_values, dict): - max_val = max(input_values.values()) - min_val = min(input_values.values()) - else: - max_val = input_values - min_val = input_values - - if (is_json_validation_enabled('exclusiveMaximum', configuration) and - 'exclusive_maximum' in current_validations and - max_val >= current_validations['exclusive_maximum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than `%s`" % ( - input_variable_path[0], - current_validations['exclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('maximum', configuration) and - 'inclusive_maximum' in current_validations and - max_val > current_validations['inclusive_maximum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value less than or equal to " - "`%s`" % ( - input_variable_path[0], - current_validations['inclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('exclusiveMinimum', configuration) and - 'exclusive_minimum' in current_validations and - min_val <= current_validations['exclusive_minimum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than `%s`" % - ( - input_variable_path[0], - current_validations['exclusive_maximum'] - ) - ) - - if (is_json_validation_enabled('minimum', configuration) and - 'inclusive_minimum' in current_validations and - min_val < current_validations['inclusive_minimum']): - raise ApiValueError( - "Invalid value for `%s`, must be a value greater than or equal " - "to `%s`" % ( - input_variable_path[0], - current_validations['inclusive_minimum'] - ) - ) - flags = current_validations.get('regex', {}).get('flags', 0) - if (is_json_validation_enabled('pattern', configuration) and - 'regex' in current_validations and - not re.search(current_validations['regex']['pattern'], - input_values, flags=flags)): - err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( - input_variable_path[0], - current_validations['regex']['pattern'] - ) - if flags != 0: - # Don't print the regex flags if the flags are not - # specified in the OAS document. - err_msg = r"%s with flags=`%s`" % (err_msg, flags) - raise ApiValueError(err_msg) - - -def order_response_types(required_types): - """Returns the required types sorted in coercion order - - Args: - required_types (list/tuple): collection of classes or instance of - list or dict with class information inside it. - - Returns: - (list): coercion order sorted collection of classes or instance - of list or dict with class information inside it. - """ - - def index_getter(class_or_instance): - if isinstance(class_or_instance, list): - return COERCION_INDEX_BY_TYPE[list] - elif isinstance(class_or_instance, dict): - return COERCION_INDEX_BY_TYPE[dict] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelComposed)): - return COERCION_INDEX_BY_TYPE[ModelComposed] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelNormal)): - return COERCION_INDEX_BY_TYPE[ModelNormal] - elif (inspect.isclass(class_or_instance) - and issubclass(class_or_instance, ModelSimple)): - return COERCION_INDEX_BY_TYPE[ModelSimple] - elif class_or_instance in COERCION_INDEX_BY_TYPE: - return COERCION_INDEX_BY_TYPE[class_or_instance] - raise ApiValueError("Unsupported type: %s" % class_or_instance) - - sorted_types = sorted( - required_types, - key=lambda class_or_instance: index_getter(class_or_instance) - ) - return sorted_types - - -def remove_uncoercible(required_types_classes, current_item, spec_property_naming, - must_convert=True): - """Only keeps the type conversions that are possible - - Args: - required_types_classes (tuple): tuple of classes that are required - these should be ordered by COERCION_INDEX_BY_TYPE - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - current_item (any): the current item (input data) to be converted - - Keyword Args: - must_convert (bool): if True the item to convert is of the wrong - type and we want a big list of coercibles - if False, we want a limited list of coercibles - - Returns: - (list): the remaining coercible required types, classes only - """ - current_type_simple = get_simple_class(current_item) - - results_classes = [] - for required_type_class in required_types_classes: - # convert our models to OpenApiModel - required_type_class_simplified = required_type_class - if isinstance(required_type_class_simplified, type): - if issubclass(required_type_class_simplified, ModelComposed): - required_type_class_simplified = ModelComposed - elif issubclass(required_type_class_simplified, ModelNormal): - required_type_class_simplified = ModelNormal - elif issubclass(required_type_class_simplified, ModelSimple): - required_type_class_simplified = ModelSimple - - if required_type_class_simplified == current_type_simple: - # don't consider converting to one's own class - continue - - class_pair = (current_type_simple, required_type_class_simplified) - if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: - results_classes.append(required_type_class) - elif class_pair in UPCONVERSION_TYPE_PAIRS: - results_classes.append(required_type_class) - return results_classes - - -def get_discriminated_classes(cls): - """ - Returns all the classes that a discriminator converts to - TODO: lru_cache this - """ - possible_classes = [] - key = list(cls.discriminator.keys())[0] - if is_type_nullable(cls): - possible_classes.append(cls) - for discr_cls in cls.discriminator[key].values(): - if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: - possible_classes.extend(get_discriminated_classes(discr_cls)) - else: - possible_classes.append(discr_cls) - return possible_classes - - -def get_possible_classes(cls, from_server_context): - # TODO: lru_cache this - possible_classes = [cls] - if from_server_context: - return possible_classes - if hasattr(cls, 'discriminator') and cls.discriminator is not None: - possible_classes = [] - possible_classes.extend(get_discriminated_classes(cls)) - elif issubclass(cls, ModelComposed): - possible_classes.extend(composed_model_input_classes(cls)) - return possible_classes - - -def get_required_type_classes(required_types_mixed, spec_property_naming): - """Converts the tuple required_types into a tuple and a dict described - below - - Args: - required_types_mixed (tuple/list): will contain either classes or - instance of list or dict - spec_property_naming (bool): if True these values came from the - server, and we use the data types in our endpoints. - If False, we are client side and we need to include - oneOf and discriminator classes inside the data types in our endpoints - - Returns: - (valid_classes, dict_valid_class_to_child_types_mixed): - valid_classes (tuple): the valid classes that the current item - should be - dict_valid_class_to_child_types_mixed (dict): - valid_class (class): this is the key - child_types_mixed (list/dict/tuple): describes the valid child - types - """ - valid_classes = [] - child_req_types_by_current_type = {} - for required_type in required_types_mixed: - if isinstance(required_type, list): - valid_classes.append(list) - child_req_types_by_current_type[list] = required_type - elif isinstance(required_type, tuple): - valid_classes.append(tuple) - child_req_types_by_current_type[tuple] = required_type - elif isinstance(required_type, dict): - valid_classes.append(dict) - child_req_types_by_current_type[dict] = required_type[str] - else: - valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) - return tuple(valid_classes), child_req_types_by_current_type - - -def change_keys_js_to_python(input_dict, model_class): - """ - Converts from javascript_key keys in the input_dict to python_keys in - the output dict using the mapping in model_class. - If the input_dict contains a key which does not declared in the model_class, - the key is added to the output dict as is. The assumption is the model_class - may have undeclared properties (additionalProperties attribute in the OAS - document). - """ - - if getattr(model_class, 'attribute_map', None) is None: - return input_dict - output_dict = {} - reversed_attr_map = {value: key for key, value in - model_class.attribute_map.items()} - for javascript_key, value in input_dict.items(): - python_key = reversed_attr_map.get(javascript_key) - if python_key is None: - # if the key is unknown, it is in error or it is an - # additionalProperties variable - python_key = javascript_key - output_dict[python_key] = value - return output_dict - - -def get_type_error(var_value, path_to_item, valid_classes, key_type=False): - error_msg = type_error_message( - var_name=path_to_item[-1], - var_value=var_value, - valid_classes=valid_classes, - key_type=key_type - ) - return ApiTypeError( - error_msg, - path_to_item=path_to_item, - valid_classes=valid_classes, - key_type=key_type - ) - - -def deserialize_primitive(data, klass, path_to_item): - """Deserializes string to primitive type. - - :param data: str/int/float - :param klass: str/class the class to convert to - - :return: int, float, str, bool, date, datetime - """ - additional_message = "" - try: - if klass in {datetime, date}: - additional_message = ( - "If you need your parameter to have a fallback " - "string value, please set its type as `type: {}` in your " - "spec. That allows the value to be any type. " - ) - if klass == datetime: - if len(data) < 8: - raise ValueError("This is not a datetime") - # The string should be in iso8601 datetime format. - parsed_datetime = parse(data) - date_only = ( - parsed_datetime.hour == 0 and - parsed_datetime.minute == 0 and - parsed_datetime.second == 0 and - parsed_datetime.tzinfo is None and - 8 <= len(data) <= 10 - ) - if date_only: - raise ValueError("This is a date, not a datetime") - return parsed_datetime - elif klass == date: - if len(data) < 8: - raise ValueError("This is not a date") - return parse(data).date() - else: - converted_value = klass(data) - if isinstance(data, str) and klass == float: - if str(converted_value) != data: - # '7' -> 7.0 -> '7.0' != '7' - raise ValueError('This is not a float') - return converted_value - except (OverflowError, ValueError) as ex: - # parse can raise OverflowError - raise ApiValueError( - "{0}Failed to parse {1} as {2}".format( - additional_message, repr(data), klass.__name__ - ), - path_to_item=path_to_item - ) from ex - - -def get_discriminator_class(model_class, - discr_name, - discr_value, cls_visited): - """Returns the child class specified by the discriminator. - - Args: - model_class (OpenApiModel): the model class. - discr_name (string): the name of the discriminator property. - discr_value (any): the discriminator value. - cls_visited (list): list of model classes that have been visited. - Used to determine the discriminator class without - visiting circular references indefinitely. - - Returns: - used_model_class (class/None): the chosen child class that will be used - to deserialize the data, for example dog.Dog. - If a class is not found, None is returned. - """ - - if model_class in cls_visited: - # The class has already been visited and no suitable class was found. - return None - cls_visited.append(model_class) - used_model_class = None - if discr_name in model_class.discriminator: - class_name_to_discr_class = model_class.discriminator[discr_name] - used_model_class = class_name_to_discr_class.get(discr_value) - if used_model_class is None: - # We didn't find a discriminated class in class_name_to_discr_class. - # So look in the ancestor or descendant discriminators - # The discriminator mapping may exist in a descendant (anyOf, oneOf) - # or ancestor (allOf). - # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat - # hierarchy, the discriminator mappings may be defined at any level - # in the hierarchy. - # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig - # if we try to make BasquePig from mammal, we need to travel through - # the oneOf descendant discriminators to find BasquePig - descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ - model_class._composed_schemas.get('anyOf', ()) - ancestor_classes = model_class._composed_schemas.get('allOf', ()) - possible_classes = descendant_classes + ancestor_classes - for cls in possible_classes: - # Check if the schema has inherited discriminators. - if hasattr(cls, 'discriminator') and cls.discriminator is not None: - used_model_class = get_discriminator_class( - cls, discr_name, discr_value, cls_visited) - if used_model_class is not None: - return used_model_class - return used_model_class - - -def deserialize_model(model_data, model_class, path_to_item, check_type, - configuration, spec_property_naming): - """Deserializes model_data to model instance. - - Args: - model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model - model_class (OpenApiModel): the model class - path_to_item (list): path to the model in the received data - check_type (bool): whether to check the data tupe for the values in - the model - configuration (Configuration): the instance to use to convert files - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - - Returns: - model instance - - Raise: - ApiTypeError - ApiValueError - ApiKeyError - """ - - kw_args = dict(_check_type=check_type, - _path_to_item=path_to_item, - _configuration=configuration, - _spec_property_naming=spec_property_naming) - - if issubclass(model_class, ModelSimple): - return model_class._new_from_openapi_data(model_data, **kw_args) - elif isinstance(model_data, list): - return model_class._new_from_openapi_data(*model_data, **kw_args) - if isinstance(model_data, dict): - kw_args.update(model_data) - return model_class._new_from_openapi_data(**kw_args) - elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class._new_from_openapi_data(model_data, **kw_args) - - -def deserialize_file(response_data, configuration, content_disposition=None): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - Args: - param response_data (str): the file data to write - configuration (Configuration): the instance to use to convert files - - Keyword Args: - content_disposition (str): the value of the Content-Disposition - header - - Returns: - (file_type): the deserialized file which is open - The user is responsible for closing and reading the file - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition, - flags=re.I) - if filename is not None: - filename = filename.group(1) - else: - filename = "default_" + str(uuid.uuid4()) - - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - if isinstance(response_data, str): - # change str to bytes so we can write it - response_data = response_data.encode('utf-8') - f.write(response_data) - - f = open(path, "rb") - return f - - -def attempt_convert_item(input_value, valid_classes, path_to_item, - configuration, spec_property_naming, key_type=False, - must_convert=False, check_type=True): - """ - Args: - input_value (any): the data to convert - valid_classes (any): the classes that are valid - path_to_item (list): the path to the item to convert - configuration (Configuration): the instance to use to convert files - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - key_type (bool): if True we need to convert a key type (not supported) - must_convert (bool): if True we must convert - check_type (bool): if True we check the type or the returned data in - ModelComposed/ModelNormal/ModelSimple instances - - Returns: - instance (any) the fixed item - - Raises: - ApiTypeError - ApiValueError - ApiKeyError - """ - valid_classes_ordered = order_response_types(valid_classes) - valid_classes_coercible = remove_uncoercible( - valid_classes_ordered, input_value, spec_property_naming) - if not valid_classes_coercible or key_type: - # we do not handle keytype errors, json will take care - # of this for us - if configuration is None or not configuration.discard_unknown_keys: - raise get_type_error(input_value, path_to_item, valid_classes, - key_type=key_type) - for valid_class in valid_classes_coercible: - try: - if issubclass(valid_class, OpenApiModel): - return deserialize_model(input_value, valid_class, - path_to_item, check_type, - configuration, spec_property_naming) - elif valid_class == file_type: - return deserialize_file(input_value, configuration) - return deserialize_primitive(input_value, valid_class, - path_to_item) - except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: - if must_convert: - raise conversion_exc - # if we have conversion errors when must_convert == False - # we ignore the exception and move on to the next class - continue - # we were unable to convert, must_convert == False - return input_value - - -def is_type_nullable(input_type): - """ - Returns true if None is an allowed value for the specified input_type. - - A type is nullable if at least one of the following conditions is true: - 1. The OAS 'nullable' attribute has been specified, - 1. The type is the 'null' type, - 1. The type is a anyOf/oneOf composed schema, and a child schema is - the 'null' type. - Args: - input_type (type): the class of the input_value that we are - checking - Returns: - bool - """ - if input_type is none_type: - return True - if issubclass(input_type, OpenApiModel) and input_type._nullable: - return True - if issubclass(input_type, ModelComposed): - # If oneOf/anyOf, check if the 'null' type is one of the allowed types. - for t in input_type._composed_schemas.get('oneOf', ()): - if is_type_nullable(t): - return True - for t in input_type._composed_schemas.get('anyOf', ()): - if is_type_nullable(t): - return True - return False - - -def is_valid_type(input_class_simple, valid_classes): - """ - Args: - input_class_simple (class): the class of the input_value that we are - checking - valid_classes (tuple): the valid classes that the current item - should be - Returns: - bool - """ - if issubclass(input_class_simple, OpenApiModel) and \ - valid_classes == (bool, date, datetime, dict, float, int, list, str, none_type,): - return True - valid_type = input_class_simple in valid_classes - if not valid_type and ( - issubclass(input_class_simple, OpenApiModel) or - input_class_simple is none_type): - for valid_class in valid_classes: - if input_class_simple is none_type and is_type_nullable(valid_class): - # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. - return True - if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): - continue - discr_propertyname_py = list(valid_class.discriminator.keys())[0] - discriminator_classes = ( - valid_class.discriminator[discr_propertyname_py].values() - ) - valid_type = is_valid_type(input_class_simple, discriminator_classes) - if valid_type: - return True - return valid_type - - -def validate_and_convert_types(input_value, required_types_mixed, path_to_item, - spec_property_naming, _check_type, configuration=None): - """Raises a TypeError is there is a problem, otherwise returns value - - Args: - input_value (any): the data to validate/convert - required_types_mixed (list/dict/tuple): A list of - valid classes, or a list tuples of valid classes, or a dict where - the value is a tuple of value classes - path_to_item: (list) the path to the data being validated - this stores a list of keys or indices to get to the data being - validated - spec_property_naming (bool): True if the variable names in the input - data are serialized names as specified in the OpenAPI document. - False if the variables names in the input data are python - variable names in PEP-8 snake case. - _check_type: (boolean) if true, type will be checked and conversion - will be attempted. - configuration: (Configuration): the configuration class to use - when converting file_type items. - If passed, conversion will be attempted when possible - If not passed, no conversions will be attempted and - exceptions will be raised - - Returns: - the correctly typed value - - Raises: - ApiTypeError - """ - results = get_required_type_classes(required_types_mixed, spec_property_naming) - valid_classes, child_req_types_by_current_type = results - - input_class_simple = get_simple_class(input_value) - valid_type = is_valid_type(input_class_simple, valid_classes) - if not valid_type: - if (configuration - or (input_class_simple == dict - and dict not in valid_classes)): - # if input_value is not valid_type try to convert it - converted_instance = attempt_convert_item( - input_value, - valid_classes, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=True, - check_type=_check_type - ) - return converted_instance - else: - raise get_type_error(input_value, path_to_item, valid_classes, - key_type=False) - - # input_value's type is in valid_classes - if len(valid_classes) > 1 and configuration: - # there are valid classes which are not the current class - valid_classes_coercible = remove_uncoercible( - valid_classes, input_value, spec_property_naming, must_convert=False) - if valid_classes_coercible: - converted_instance = attempt_convert_item( - input_value, - valid_classes_coercible, - path_to_item, - configuration, - spec_property_naming, - key_type=False, - must_convert=False, - check_type=_check_type - ) - return converted_instance - - if child_req_types_by_current_type == {}: - # all types are of the required types and there are no more inner - # variables left to look at - return input_value - inner_required_types = child_req_types_by_current_type.get( - type(input_value) - ) - if inner_required_types is None: - # for this type, there are not more inner variables left to look at - return input_value - if isinstance(input_value, list): - if input_value == []: - # allow an empty list - return input_value - for index, inner_value in enumerate(input_value): - inner_path = list(path_to_item) - inner_path.append(index) - input_value[index] = validate_and_convert_types( - inner_value, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration - ) - elif isinstance(input_value, dict): - if input_value == {}: - # allow an empty dict - return input_value - for inner_key, inner_val in input_value.items(): - inner_path = list(path_to_item) - inner_path.append(inner_key) - if get_simple_class(inner_key) != str: - raise get_type_error(inner_key, inner_path, valid_classes, - key_type=True) - input_value[inner_key] = validate_and_convert_types( - inner_val, - inner_required_types, - inner_path, - spec_property_naming, - _check_type, - configuration=configuration - ) - return input_value - - -def model_to_dict(model_instance, serialize=True): - """Returns the model properties as a dict - - Args: - model_instance (one of your model instances): the model instance that - will be converted to a dict. - - Keyword Args: - serialize (bool): if True, the keys in the dict will be values from - attribute_map - """ - result = {} - - def extract_item(item): return ( - item[0], model_to_dict( - item[1], serialize=serialize)) if hasattr( - item[1], '_data_store') else item - - model_instances = [model_instance] - if model_instance._composed_schemas: - model_instances.extend(model_instance._composed_instances) - seen_json_attribute_names = set() - used_fallback_python_attribute_names = set() - py_to_json_map = {} - for model_instance in model_instances: - for attr, value in model_instance._data_store.items(): - if serialize: - # we use get here because additional property key names do not - # exist in attribute_map - try: - attr = model_instance.attribute_map[attr] - py_to_json_map.update(model_instance.attribute_map) - seen_json_attribute_names.add(attr) - except KeyError: - used_fallback_python_attribute_names.add(attr) - if isinstance(value, list): - if not value: - # empty list or None - result[attr] = value - else: - res = [] - for v in value: - if isinstance(v, PRIMITIVE_TYPES) or v is None: - res.append(v) - elif isinstance(v, ModelSimple): - res.append(v.value) - elif isinstance(v, dict): - res.append(dict(map( - extract_item, - v.items() - ))) - else: - res.append(model_to_dict(v, serialize=serialize)) - result[attr] = res - elif isinstance(value, dict): - result[attr] = dict(map( - extract_item, - value.items() - )) - elif isinstance(value, ModelSimple): - result[attr] = value.value - elif hasattr(value, '_data_store'): - result[attr] = model_to_dict(value, serialize=serialize) - else: - result[attr] = value - if serialize: - for python_key in used_fallback_python_attribute_names: - json_key = py_to_json_map.get(python_key) - if json_key is None: - continue - if python_key == json_key: - continue - json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names - if json_key_assigned_no_need_for_python_key: - del result[python_key] - - return result - - -def type_error_message(var_value=None, var_name=None, valid_classes=None, - key_type=None): - """ - Keyword Args: - var_value (any): the variable which has the type_error - var_name (str): the name of the variable which has the typ error - valid_classes (tuple): the accepted classes for current_item's - value - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - """ - key_or_value = 'value' - if key_type: - key_or_value = 'key' - valid_classes_phrase = get_valid_classes_phrase(valid_classes) - msg = ( - "Invalid type for variable '{0}'. Required {1} type {2} and " - "passed type was {3}".format( - var_name, - key_or_value, - valid_classes_phrase, - type(var_value).__name__, - ) - ) - return msg - - -def get_valid_classes_phrase(input_classes): - """Returns a string phrase describing what types are allowed - """ - all_classes = list(input_classes) - all_classes = sorted(all_classes, key=lambda cls: cls.__name__) - all_class_names = [cls.__name__ for cls in all_classes] - if len(all_class_names) == 1: - return 'is {0}'.format(all_class_names[0]) - return "is one of [{0}]".format(", ".join(all_class_names)) - - -def get_allof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - used to make instances - constant_args (dict): - metadata arguments: - _check_type - _path_to_item - _spec_property_naming - _configuration - _visited_composed_classes - - Returns - composed_instances (list) - """ - composed_instances = [] - for allof_class in self._composed_schemas['allOf']: - - try: - if constant_args.get('_spec_property_naming'): - allof_instance = allof_class._from_openapi_data(**model_args, **constant_args) - else: - allof_instance = allof_class(**model_args, **constant_args) - composed_instances.append(allof_instance) - except Exception as ex: - raise ApiValueError( - "Invalid inputs given to generate an instance of '%s'. The " - "input data was invalid for the allOf schema '%s' in the composed " - "schema '%s'. Error=%s" % ( - allof_class.__name__, - allof_class.__name__, - self.__class__.__name__, - str(ex) - ) - ) from ex - return composed_instances - - -def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): - """ - Find the oneOf schema that matches the input data (e.g. payload). - If exactly one schema matches the input data, an instance of that schema - is returned. - If zero or more than one schema match the input data, an exception is raised. - In OAS 3.x, the payload MUST, by validation, match exactly one of the - schemas described by oneOf. - - Args: - cls: the class we are handling - model_kwargs (dict): var_name to var_value - The input data, e.g. the payload that must match a oneOf schema - in the OpenAPI document. - constant_kwargs (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Kwargs: - model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): - the value to assign to a primitive class or ModelSimple class - Notes: - - this is only passed in when oneOf includes types which are not object - - None is used to suppress handling of model_arg, nullable models are handled in __new__ - - Returns - oneof_instance (instance) - """ - if len(cls._composed_schemas['oneOf']) == 0: - return None - - oneof_instances = [] - # Iterate over each oneOf schema and determine if the input data - # matches the oneOf schemas. - for oneof_class in cls._composed_schemas['oneOf']: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if oneof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - single_value_input = allows_single_value_input(oneof_class) - - try: - if not single_value_input: - if constant_kwargs.get('_spec_property_naming'): - oneof_instance = oneof_class._from_openapi_data( - **model_kwargs, **constant_kwargs) - else: - oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) - else: - if issubclass(oneof_class, ModelSimple): - if constant_kwargs.get('_spec_property_naming'): - oneof_instance = oneof_class._from_openapi_data( - model_arg, **constant_kwargs) - else: - oneof_instance = oneof_class(model_arg, **constant_kwargs) - elif oneof_class in PRIMITIVE_TYPES: - oneof_instance = validate_and_convert_types( - model_arg, - (oneof_class,), - constant_kwargs['_path_to_item'], - constant_kwargs['_spec_property_naming'], - constant_kwargs['_check_type'], - configuration=constant_kwargs['_configuration'] - ) - oneof_instances.append(oneof_instance) - except Exception: - pass - if len(oneof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None " - "of the oneOf schemas matched the input data." % - cls.__name__ - ) - elif len(oneof_instances) > 1: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. Multiple " - "oneOf schemas matched the inputs, but a max of one is allowed." % - cls.__name__ - ) - return oneof_instances[0] - - -def get_anyof_instances(self, model_args, constant_args): - """ - Args: - self: the class we are handling - model_args (dict): var_name to var_value - The input data, e.g. the payload that must match at least one - anyOf child schema in the OpenAPI document. - constant_args (dict): var_name to var_value - args that every model requires, including configuration, server - and path to item. - - Returns - anyof_instances (list) - """ - anyof_instances = [] - if len(self._composed_schemas['anyOf']) == 0: - return anyof_instances - - for anyof_class in self._composed_schemas['anyOf']: - # The composed oneOf schema allows the 'null' type and the input data - # is the null value. This is a OAS >= 3.1 feature. - if anyof_class is none_type: - # skip none_types because we are deserializing dict data. - # none_type deserialization is handled in the __new__ method - continue - - try: - if constant_args.get('_spec_property_naming'): - anyof_instance = anyof_class._from_openapi_data(**model_args, **constant_args) - else: - anyof_instance = anyof_class(**model_args, **constant_args) - anyof_instances.append(anyof_instance) - except Exception: - pass - if len(anyof_instances) == 0: - raise ApiValueError( - "Invalid inputs given to generate an instance of %s. None of the " - "anyOf schemas matched the inputs." % - self.__class__.__name__ - ) - return anyof_instances - - -def get_discarded_args(self, composed_instances, model_args): - """ - Gathers the args that were discarded by configuration.discard_unknown_keys - """ - model_arg_keys = model_args.keys() - discarded_args = set() - # arguments passed to self were already converted to python names - # before __init__ was called - for instance in composed_instances: - if instance.__class__ in self._composed_schemas['allOf']: - try: - keys = instance.to_dict().keys() - discarded_keys = model_args - keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - else: - try: - all_keys = set(model_to_dict(instance, serialize=False).keys()) - js_keys = model_to_dict(instance, serialize=True).keys() - all_keys.update(js_keys) - discarded_keys = model_arg_keys - all_keys - discarded_args.update(discarded_keys) - except Exception: - # allOf integer schema will throw exception - pass - return discarded_args - - -def validate_get_composed_info(constant_args, model_args, self): - """ - For composed schemas, generate schema instances for - all schemas in the oneOf/anyOf/allOf definition. If additional - properties are allowed, also assign those properties on - all matched schemas that contain additionalProperties. - Openapi schemas are python classes. - - Exceptions are raised if: - - 0 or > 1 oneOf schema matches the model_args input data - - no anyOf schema matches the model_args input data - - any of the allOf schemas do not match the model_args input data - - Args: - constant_args (dict): these are the args that every model requires - model_args (dict): these are the required and optional spec args that - were passed in to make this model - self (class): the class that we are instantiating - This class contains self._composed_schemas - - Returns: - composed_info (list): length three - composed_instances (list): the composed instances which are not - self - var_name_to_model_instances (dict): a dict going from var_name - to the model_instance which holds that var_name - the model_instance may be self or an instance of one of the - classes in self.composed_instances() - additional_properties_model_instances (list): a list of the - model instances which have the property - additional_properties_type. This list can include self - """ - # create composed_instances - composed_instances = [] - allof_instances = get_allof_instances(self, model_args, constant_args) - composed_instances.extend(allof_instances) - oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) - if oneof_instance is not None: - composed_instances.append(oneof_instance) - anyof_instances = get_anyof_instances(self, model_args, constant_args) - composed_instances.extend(anyof_instances) - """ - set additional_properties_model_instances - additional properties must be evaluated at the schema level - so self's additional properties are most important - If self is a composed schema with: - - no properties defined in self - - additionalProperties: False - Then for object payloads every property is an additional property - and they are not allowed, so only empty dict is allowed - - Properties must be set on all matching schemas - so when a property is assigned toa composed instance, it must be set on all - composed instances regardless of additionalProperties presence - keeping it to prevent breaking changes in v5.0.1 - TODO remove cls._additional_properties_model_instances in 6.0.0 - """ - additional_properties_model_instances = [] - if self.additional_properties_type is not None: - additional_properties_model_instances = [self] - - """ - no need to set properties on self in here, they will be set in __init__ - By here all composed schema oneOf/anyOf/allOf instances have their properties set using - model_args - """ - discarded_args = get_discarded_args(self, composed_instances, model_args) - - # map variable names to composed_instances - var_name_to_model_instances = {} - for prop_name in model_args: - if prop_name not in discarded_args: - var_name_to_model_instances[prop_name] = [self] + list( - filter( - lambda x: prop_name in x.openapi_types, composed_instances)) - - return [ - composed_instances, - var_name_to_model_instances, - additional_properties_model_instances, - discarded_args - ] diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py index dd8afc1d8b..a3f42957f9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -1,3 +1,5 @@ +# coding: utf-8 + # flake8: noqa # import all models into this package @@ -10,37 +12,51 @@ # sys.setrecursionlimit(n) from petstore_api.model.additional_properties_class import AdditionalPropertiesClass +from petstore_api.model.additional_properties_validator import AdditionalPropertiesValidator from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums from petstore_api.model.address import Address from petstore_api.model.animal import Animal from petstore_api.model.animal_farm import AnimalFarm +from petstore_api.model.any_type_and_format import AnyTypeAndFormat +from petstore_api.model.any_type_not_string import AnyTypeNotString from petstore_api.model.api_response import ApiResponse from petstore_api.model.apple import Apple from petstore_api.model.apple_req import AppleReq +from petstore_api.model.array_holding_any_type import ArrayHoldingAnyType from petstore_api.model.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly from petstore_api.model.array_of_enums import ArrayOfEnums from petstore_api.model.array_of_number_only import ArrayOfNumberOnly from petstore_api.model.array_test import ArrayTest +from petstore_api.model.array_with_validations_in_items import ArrayWithValidationsInItems from petstore_api.model.banana import Banana from petstore_api.model.banana_req import BananaReq +from petstore_api.model.bar import Bar from petstore_api.model.basque_pig import BasquePig +from petstore_api.model.boolean import Boolean from petstore_api.model.boolean_enum import BooleanEnum from petstore_api.model.capitalization import Capitalization from petstore_api.model.cat import Cat -from petstore_api.model.cat_all_of import CatAllOf from petstore_api.model.category import Category from petstore_api.model.child_cat import ChildCat -from petstore_api.model.child_cat_all_of import ChildCatAllOf from petstore_api.model.class_model import ClassModel from petstore_api.model.client import Client from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral -from petstore_api.model.composed_one_of_number_with_validations import ComposedOneOfNumberWithValidations -from petstore_api.model.composed_schema_with_props_and_no_add_props import ComposedSchemaWithPropsAndNoAddProps +from petstore_api.model.composed_any_of_different_types_no_validations import ComposedAnyOfDifferentTypesNoValidations +from petstore_api.model.composed_array import ComposedArray +from petstore_api.model.composed_bool import ComposedBool +from petstore_api.model.composed_none import ComposedNone +from petstore_api.model.composed_number import ComposedNumber +from petstore_api.model.composed_object import ComposedObject +from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes +from petstore_api.model.composed_string import ComposedString +from petstore_api.model.currency import Currency from petstore_api.model.danish_pig import DanishPig +from petstore_api.model.date_time_test import DateTimeTest +from petstore_api.model.date_time_with_validations import DateTimeWithValidations +from petstore_api.model.date_with_validations import DateWithValidations +from petstore_api.model.decimal_payload import DecimalPayload from petstore_api.model.dog import Dog -from petstore_api.model.dog_all_of import DogAllOf from petstore_api.model.drawing import Drawing -from petstore_api.model.egress_threshold_options import EgressThresholdOptions from petstore_api.model.enum_arrays import EnumArrays from petstore_api.model.enum_class import EnumClass from petstore_api.model.enum_test import EnumTest @@ -48,64 +64,69 @@ from petstore_api.model.equilateral_triangle import EquilateralTriangle from petstore_api.model.file import File from petstore_api.model.file_schema_test_class import FileSchemaTestClass from petstore_api.model.foo import Foo -from petstore_api.model.foo_get_default_response import FooGetDefaultResponse -from petstore_api.model.foo_object import FooObject from petstore_api.model.format_test import FormatTest +from petstore_api.model.from_schema import FromSchema from petstore_api.model.fruit import Fruit from petstore_api.model.fruit_req import FruitReq from petstore_api.model.gm_fruit import GmFruit -from petstore_api.model.gm_fruit_no_properties import GmFruitNoProperties from petstore_api.model.grandparent_animal import GrandparentAnimal from petstore_api.model.has_only_read_only import HasOnlyReadOnly from petstore_api.model.health_check_result import HealthCheckResult -from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload from petstore_api.model.integer_enum import IntegerEnum +from petstore_api.model.integer_enum_big import IntegerEnumBig from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue +from petstore_api.model.integer_max10 import IntegerMax10 +from petstore_api.model.integer_min15 import IntegerMin15 from petstore_api.model.isosceles_triangle import IsoscelesTriangle -from petstore_api.model.legs import Legs -from petstore_api.model.list import List +from petstore_api.model.json_patch_request import JSONPatchRequest +from petstore_api.model.json_patch_request_add_replace_test import JSONPatchRequestAddReplaceTest +from petstore_api.model.json_patch_request_move_copy import JSONPatchRequestMoveCopy +from petstore_api.model.json_patch_request_remove import JSONPatchRequestRemove from petstore_api.model.mammal import Mammal from petstore_api.model.map_test import MapTest from petstore_api.model.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from petstore_api.model.model200_response import Model200Response from petstore_api.model.model_return import ModelReturn -from petstore_api.model.mole import Mole +from petstore_api.model.money import Money from petstore_api.model.name import Name +from petstore_api.model.no_additional_properties import NoAdditionalProperties from petstore_api.model.nullable_class import NullableClass from petstore_api.model.nullable_shape import NullableShape +from petstore_api.model.nullable_string import NullableString +from petstore_api.model.number import Number from petstore_api.model.number_only import NumberOnly from petstore_api.model.number_with_validations import NumberWithValidations from petstore_api.model.object_interface import ObjectInterface from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from petstore_api.model.object_with_decimal_properties import ObjectWithDecimalProperties +from petstore_api.model.object_with_difficultly_named_props import ObjectWithDifficultlyNamedProps +from petstore_api.model.object_with_inline_composition_property import ObjectWithInlineCompositionProperty +from petstore_api.model.object_with_invalid_named_refed_properties import ObjectWithInvalidNamedRefedProperties from petstore_api.model.object_with_validations import ObjectWithValidations from petstore_api.model.order import Order from petstore_api.model.parent_pet import ParentPet from petstore_api.model.pet import Pet from petstore_api.model.pig import Pig -from petstore_api.model.post_inline_additional_properties_payload_request import PostInlineAdditionalPropertiesPayloadRequest -from petstore_api.model.post_inline_additional_properties_payload_request_array_data_inner import PostInlineAdditionalPropertiesPayloadRequestArrayDataInner -from petstore_api.model.publish_options import PublishOptions -from petstore_api.model.publish_options_publish import PublishOptionsPublish +from petstore_api.model.player import Player from petstore_api.model.quadrilateral import Quadrilateral from petstore_api.model.quadrilateral_interface import QuadrilateralInterface from petstore_api.model.read_only_first import ReadOnlyFirst -from petstore_api.model.readonly import Readonly from petstore_api.model.scalene_triangle import ScaleneTriangle from petstore_api.model.shape import Shape -from petstore_api.model.shape_interface import ShapeInterface from petstore_api.model.shape_or_null import ShapeOrNull from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral from petstore_api.model.some_object import SomeObject -from petstore_api.model.some_object_with_self_attr import SomeObjectWithSelfAttr from petstore_api.model.special_model_name import SpecialModelName -from petstore_api.model.stream_options import StreamOptions +from petstore_api.model.string import String from petstore_api.model.string_boolean_map import StringBooleanMap from petstore_api.model.string_enum import StringEnum from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue +from petstore_api.model.string_with_validation import StringWithValidation from petstore_api.model.tag import Tag from petstore_api.model.triangle import Triangle from petstore_api.model.triangle_interface import TriangleInterface +from petstore_api.model.uuid_string import UUIDString from petstore_api.model.user import User from petstore_api.model.whale import Whale from petstore_api.model.zebra import Zebra diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/__init__.py new file mode 100644 index 0000000000..9b8c0ff4bb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/__init__.py @@ -0,0 +1,56 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.apis.path_to_api import path_to_api + +import enum + + +class PathValues(str, enum.Enum): + FOO = "/foo" + PET = "/pet" + PET_FIND_BY_STATUS = "/pet/findByStatus" + PET_FIND_BY_TAGS = "/pet/findByTags" + PET_PET_ID = "/pet/{petId}" + PET_PET_ID_UPLOAD_IMAGE = "/pet/{petId}/uploadImage" + STORE_INVENTORY = "/store/inventory" + STORE_ORDER = "/store/order" + STORE_ORDER_ORDER_ID = "/store/order/{order_id}" + USER = "/user" + USER_CREATE_WITH_ARRAY = "/user/createWithArray" + USER_CREATE_WITH_LIST = "/user/createWithList" + USER_LOGIN = "/user/login" + USER_LOGOUT = "/user/logout" + USER_USERNAME = "/user/{username}" + FAKE_CLASSNAME_TEST = "/fake_classname_test" + FAKE = "/fake" + FAKE_REFS_NUMBER = "/fake/refs/number" + FAKE_REFS_MAMMAL = "/fake/refs/mammal" + FAKE_REFS_STRING = "/fake/refs/string" + FAKE_REFS_BOOLEAN = "/fake/refs/boolean" + FAKE_REFS_ARRAYMODEL = "/fake/refs/arraymodel" + FAKE_REFS_COMPOSED_ONE_OF_NUMBER_WITH_VALIDATIONS = "/fake/refs/composed_one_of_number_with_validations" + FAKE_REFS_OBJECT_MODEL_WITH_REF_PROPS = "/fake/refs/object_model_with_ref_props" + FAKE_REFS_ENUM = "/fake/refs/enum" + FAKE_REFS_ARRAYOFENUMS = "/fake/refs/array-of-enums" + FAKE_ADDITIONALPROPERTIESWITHARRAYOFENUMS = "/fake/additional-properties-with-array-of-enums" + FAKE_JSON_FORM_DATA = "/fake/jsonFormData" + FAKE_INLINEADDITIONAL_PROPERTIES = "/fake/inline-additionalProperties" + FAKE_BODYWITHQUERYPARAMS = "/fake/body-with-query-params" + ANOTHERFAKE_DUMMY = "/another-fake/dummy" + FAKE_BODYWITHFILESCHEMA = "/fake/body-with-file-schema" + FAKE_CASESENSITIVEPARAMS = "/fake/case-sensitive-params" + FAKE_TESTQUERYPARAMTERS = "/fake/test-query-paramters" + FAKE_PET_ID_UPLOAD_IMAGE_WITH_REQUIRED_FILE = "/fake/{petId}/uploadImageWithRequiredFile" + FAKE_PARAMETER_COLLISIONS_1_A_B_AB_SELF_AB_ = "/fake/parameterCollisions/{1}/{aB}/{Ab}/{self}/{A-B}/" + FAKE_UPLOAD_FILE = "/fake/uploadFile" + FAKE_UPLOAD_FILES = "/fake/uploadFiles" + FAKE_UPLOAD_DOWNLOAD_FILE = "/fake/uploadDownloadFile" + FAKE_HEALTH = "/fake/health" + FAKE_INLINE_COMPOSITION_ = "/fake/inlineComposition/" + FAKE_OBJ_IN_QUERY = "/fake/objInQuery" + FAKE_REF_OBJ_IN_QUERY = "/fake/refObjInQuery" + FAKE_JSON_WITH_CHARSET = "/fake/jsonWithCharset" + FAKE_RESPONSE_WITHOUT_SCHEMA = "/fake/responseWithoutSchema" + FAKE_JSON_PATCH = "/fake/jsonPatch" + FAKE_DELETE_COFFEE_ID = "/fake/deleteCoffee/{id}" + FAKE_QUERY_PARAM_WITH_JSON_CONTENT_TYPE = "/fake/queryParamWithJsonContentType" diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/another_fake_dummy/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/another_fake_dummy/__init__.py new file mode 100644 index 0000000000..565ab17736 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/another_fake_dummy/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.another_fake_dummy import Api + +from petstore_api.paths import PathValues + +path = PathValues.ANOTHERFAKE_DUMMY \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/another_fake_dummy/patch.py b/samples/openapi3/client/petstore/python/petstore_api/paths/another_fake_dummy/patch.py new file mode 100644 index 0000000000..35b18c4fde --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/another_fake_dummy/patch.py @@ -0,0 +1,329 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.client import Client + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Client + + +request_body_client = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationJson = Client + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + To test special tags + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_client.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='patch'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class Call123TestSpecialTags(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._call_123_test_special_tags_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpatch(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._call_123_test_special_tags_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/another_fake_dummy/patch.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/another_fake_dummy/patch.pyi new file mode 100644 index 0000000000..5c7dfa4851 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/another_fake_dummy/patch.pyi @@ -0,0 +1,324 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.client import Client + +# body param +SchemaForRequestBodyApplicationJson = Client + + +request_body_client = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationJson = Client + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _call_123_test_special_tags_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + To test special tags + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_client.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='patch'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class Call123TestSpecialTags(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def call_123_test_special_tags( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._call_123_test_special_tags_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpatch(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._call_123_test_special_tags_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/__init__.py new file mode 100644 index 0000000000..6e6df72bd8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake/delete.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/delete.py new file mode 100644 index 0000000000..17e3ac6559 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/delete.py @@ -0,0 +1,347 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Query params +RequiredStringGroupSchema = schemas.IntSchema +RequiredInt64GroupSchema = schemas.Int64Schema +StringGroupSchema = schemas.IntSchema +Int64GroupSchema = schemas.Int64Schema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'required_string_group': typing.Union[RequiredStringGroupSchema, decimal.Decimal, int, ], + 'required_int64_group': typing.Union[RequiredInt64GroupSchema, decimal.Decimal, int, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'string_group': typing.Union[StringGroupSchema, decimal.Decimal, int, ], + 'int64_group': typing.Union[Int64GroupSchema, decimal.Decimal, int, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_required_string_group = api_client.QueryParameter( + name="required_string_group", + style=api_client.ParameterStyle.FORM, + schema=RequiredStringGroupSchema, + required=True, + explode=True, +) +request_query_required_int64_group = api_client.QueryParameter( + name="required_int64_group", + style=api_client.ParameterStyle.FORM, + schema=RequiredInt64GroupSchema, + required=True, + explode=True, +) +request_query_string_group = api_client.QueryParameter( + name="string_group", + style=api_client.ParameterStyle.FORM, + schema=StringGroupSchema, + explode=True, +) +request_query_int64_group = api_client.QueryParameter( + name="int64_group", + style=api_client.ParameterStyle.FORM, + schema=Int64GroupSchema, + explode=True, +) +# Header params +RequiredBooleanGroupSchema = schemas.BoolSchema +BooleanGroupSchema = schemas.BoolSchema +RequestRequiredHeaderParams = typing_extensions.TypedDict( + 'RequestRequiredHeaderParams', + { + 'required_boolean_group': typing.Union[RequiredBooleanGroupSchema, bool, ], + } +) +RequestOptionalHeaderParams = typing_extensions.TypedDict( + 'RequestOptionalHeaderParams', + { + 'boolean_group': typing.Union[BooleanGroupSchema, bool, ], + }, + total=False +) + + +class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): + pass + + +request_header_required_boolean_group = api_client.HeaderParameter( + name="required_boolean_group", + style=api_client.ParameterStyle.SIMPLE, + schema=RequiredBooleanGroupSchema, + required=True, +) +request_header_boolean_group = api_client.HeaderParameter( + name="boolean_group", + style=api_client.ParameterStyle.SIMPLE, + schema=BooleanGroupSchema, +) +_auth = [ + 'bearer_test', +] + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _group_parameters_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _group_parameters_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _group_parameters_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _group_parameters_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Fake endpoint to test group parameters (optional) + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + self._verify_typed_dict_inputs_oapg(RequestHeaderParams, header_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_required_string_group, + request_query_required_int64_group, + request_query_string_group, + request_query_int64_group, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + for parameter in ( + request_header_required_boolean_group, + request_header_boolean_group, + ): + parameter_data = header_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _headers.extend(serialized_data) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GroupParameters(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def group_parameters( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def group_parameters( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def group_parameters( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def group_parameters( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._group_parameters_oapg( + query_params=query_params, + header_params=header_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def delete( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._group_parameters_oapg( + query_params=query_params, + header_params=header_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake/delete.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/delete.pyi new file mode 100644 index 0000000000..c88235a264 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/delete.pyi @@ -0,0 +1,339 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Query params +RequiredStringGroupSchema = schemas.IntSchema +RequiredInt64GroupSchema = schemas.Int64Schema +StringGroupSchema = schemas.IntSchema +Int64GroupSchema = schemas.Int64Schema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'required_string_group': typing.Union[RequiredStringGroupSchema, decimal.Decimal, int, ], + 'required_int64_group': typing.Union[RequiredInt64GroupSchema, decimal.Decimal, int, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'string_group': typing.Union[StringGroupSchema, decimal.Decimal, int, ], + 'int64_group': typing.Union[Int64GroupSchema, decimal.Decimal, int, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_required_string_group = api_client.QueryParameter( + name="required_string_group", + style=api_client.ParameterStyle.FORM, + schema=RequiredStringGroupSchema, + required=True, + explode=True, +) +request_query_required_int64_group = api_client.QueryParameter( + name="required_int64_group", + style=api_client.ParameterStyle.FORM, + schema=RequiredInt64GroupSchema, + required=True, + explode=True, +) +request_query_string_group = api_client.QueryParameter( + name="string_group", + style=api_client.ParameterStyle.FORM, + schema=StringGroupSchema, + explode=True, +) +request_query_int64_group = api_client.QueryParameter( + name="int64_group", + style=api_client.ParameterStyle.FORM, + schema=Int64GroupSchema, + explode=True, +) +# Header params +RequiredBooleanGroupSchema = schemas.BoolSchema +BooleanGroupSchema = schemas.BoolSchema +RequestRequiredHeaderParams = typing_extensions.TypedDict( + 'RequestRequiredHeaderParams', + { + 'required_boolean_group': typing.Union[RequiredBooleanGroupSchema, bool, ], + } +) +RequestOptionalHeaderParams = typing_extensions.TypedDict( + 'RequestOptionalHeaderParams', + { + 'boolean_group': typing.Union[BooleanGroupSchema, bool, ], + }, + total=False +) + + +class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): + pass + + +request_header_required_boolean_group = api_client.HeaderParameter( + name="required_boolean_group", + style=api_client.ParameterStyle.SIMPLE, + schema=RequiredBooleanGroupSchema, + required=True, +) +request_header_boolean_group = api_client.HeaderParameter( + name="boolean_group", + style=api_client.ParameterStyle.SIMPLE, + schema=BooleanGroupSchema, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _group_parameters_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _group_parameters_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _group_parameters_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _group_parameters_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Fake endpoint to test group parameters (optional) + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + self._verify_typed_dict_inputs_oapg(RequestHeaderParams, header_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_required_string_group, + request_query_required_int64_group, + request_query_string_group, + request_query_int64_group, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + for parameter in ( + request_header_required_boolean_group, + request_header_boolean_group, + ): + parameter_data = header_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _headers.extend(serialized_data) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GroupParameters(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def group_parameters( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def group_parameters( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def group_parameters( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def group_parameters( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._group_parameters_oapg( + query_params=query_params, + header_params=header_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def delete( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._group_parameters_oapg( + query_params=query_params, + header_params=header_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/get.py new file mode 100644 index 0000000000..f56f26eac5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/get.py @@ -0,0 +1,752 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Query params + + +class EnumQueryStringArraySchema( + schemas.ListSchema +): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + ">": "GREATER_THAN", + "$": "DOLLAR", + } + + @schemas.classproperty + def GREATER_THAN(cls): + return cls(">") + + @schemas.classproperty + def DOLLAR(cls): + return cls("$") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'EnumQueryStringArraySchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class EnumQueryStringSchema( + schemas.EnumBase, + schemas.StrSchema +): + + + class MetaOapg: + enum_value_to_name = { + "_abc": "_ABC", + "-efg": "EFG", + "(xyz)": "XYZ", + } + + @schemas.classproperty + def _ABC(cls): + return cls("_abc") + + @schemas.classproperty + def EFG(cls): + return cls("-efg") + + @schemas.classproperty + def XYZ(cls): + return cls("(xyz)") + + +class EnumQueryIntegerSchema( + schemas.EnumBase, + schemas.Int32Schema +): + + + class MetaOapg: + format = 'int32' + enum_value_to_name = { + 1: "POSITIVE_1", + -2: "NEGATIVE_2", + } + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def NEGATIVE_2(cls): + return cls(-2) + + +class EnumQueryDoubleSchema( + schemas.EnumBase, + schemas.Float64Schema +): + + + class MetaOapg: + format = 'double' + enum_value_to_name = { + 1.1: "POSITIVE_1_PT_1", + -1.2: "NEGATIVE_1_PT_2", + } + + @schemas.classproperty + def POSITIVE_1_PT_1(cls): + return cls(1.1) + + @schemas.classproperty + def NEGATIVE_1_PT_2(cls): + return cls(-1.2) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'enum_query_string_array': typing.Union[EnumQueryStringArraySchema, list, tuple, ], + 'enum_query_string': typing.Union[EnumQueryStringSchema, str, ], + 'enum_query_integer': typing.Union[EnumQueryIntegerSchema, decimal.Decimal, int, ], + 'enum_query_double': typing.Union[EnumQueryDoubleSchema, decimal.Decimal, int, float, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_enum_query_string_array = api_client.QueryParameter( + name="enum_query_string_array", + style=api_client.ParameterStyle.FORM, + schema=EnumQueryStringArraySchema, + explode=True, +) +request_query_enum_query_string = api_client.QueryParameter( + name="enum_query_string", + style=api_client.ParameterStyle.FORM, + schema=EnumQueryStringSchema, + explode=True, +) +request_query_enum_query_integer = api_client.QueryParameter( + name="enum_query_integer", + style=api_client.ParameterStyle.FORM, + schema=EnumQueryIntegerSchema, + explode=True, +) +request_query_enum_query_double = api_client.QueryParameter( + name="enum_query_double", + style=api_client.ParameterStyle.FORM, + schema=EnumQueryDoubleSchema, + explode=True, +) +# Header params + + +class EnumHeaderStringArraySchema( + schemas.ListSchema +): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + ">": "GREATER_THAN", + "$": "DOLLAR", + } + + @schemas.classproperty + def GREATER_THAN(cls): + return cls(">") + + @schemas.classproperty + def DOLLAR(cls): + return cls("$") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'EnumHeaderStringArraySchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class EnumHeaderStringSchema( + schemas.EnumBase, + schemas.StrSchema +): + + + class MetaOapg: + enum_value_to_name = { + "_abc": "_ABC", + "-efg": "EFG", + "(xyz)": "XYZ", + } + + @schemas.classproperty + def _ABC(cls): + return cls("_abc") + + @schemas.classproperty + def EFG(cls): + return cls("-efg") + + @schemas.classproperty + def XYZ(cls): + return cls("(xyz)") +RequestRequiredHeaderParams = typing_extensions.TypedDict( + 'RequestRequiredHeaderParams', + { + } +) +RequestOptionalHeaderParams = typing_extensions.TypedDict( + 'RequestOptionalHeaderParams', + { + 'enum_header_string_array': typing.Union[EnumHeaderStringArraySchema, list, tuple, ], + 'enum_header_string': typing.Union[EnumHeaderStringSchema, str, ], + }, + total=False +) + + +class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): + pass + + +request_header_enum_header_string_array = api_client.HeaderParameter( + name="enum_header_string_array", + style=api_client.ParameterStyle.SIMPLE, + schema=EnumHeaderStringArraySchema, +) +request_header_enum_header_string = api_client.HeaderParameter( + name="enum_header_string", + style=api_client.ParameterStyle.SIMPLE, + schema=EnumHeaderStringSchema, +) +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class enum_form_string_array( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + ">": "GREATER_THAN", + "$": "DOLLAR", + } + + @schemas.classproperty + def GREATER_THAN(cls): + return cls(">") + + @schemas.classproperty + def DOLLAR(cls): + return cls("$") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'enum_form_string_array': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class enum_form_string( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "_abc": "_ABC", + "-efg": "EFG", + "(xyz)": "XYZ", + } + + @schemas.classproperty + def _ABC(cls): + return cls("_abc") + + @schemas.classproperty + def EFG(cls): + return cls("-efg") + + @schemas.classproperty + def XYZ(cls): + return cls("(xyz)") + __annotations__ = { + "enum_form_string_array": enum_form_string_array, + "enum_form_string": enum_form_string, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_form_string_array"]) -> MetaOapg.properties.enum_form_string_array: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_form_string"]) -> MetaOapg.properties.enum_form_string: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["enum_form_string_array", "enum_form_string", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_form_string_array"]) -> typing.Union[MetaOapg.properties.enum_form_string_array, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_form_string"]) -> typing.Union[MetaOapg.properties.enum_form_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["enum_form_string_array", "enum_form_string", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + enum_form_string_array: typing.Union[MetaOapg.properties.enum_form_string_array, list, tuple, schemas.Unset] = schemas.unset, + enum_form_string: typing.Union[MetaOapg.properties.enum_form_string, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': + return super().__new__( + cls, + *args, + enum_form_string_array=enum_form_string_array, + enum_form_string=enum_form_string, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/x-www-form-urlencoded': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), + }, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_status_code_to_response = { + '200': _response_for_200, + '404': _response_for_404, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _enum_parameters_oapg( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _enum_parameters_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _enum_parameters_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _enum_parameters_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _enum_parameters_oapg( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + To test enum parameters + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + self._verify_typed_dict_inputs_oapg(RequestHeaderParams, header_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_enum_query_string_array, + request_query_enum_query_string, + request_query_enum_query_integer, + request_query_enum_query_double, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + for parameter in ( + request_header_enum_header_string_array, + request_header_enum_header_string, + ): + parameter_data = header_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _headers.extend(serialized_data) + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class EnumParameters(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def enum_parameters( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def enum_parameters( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def enum_parameters( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def enum_parameters( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def enum_parameters( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._enum_parameters_oapg( + body=body, + query_params=query_params, + header_params=header_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def get( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._enum_parameters_oapg( + body=body, + query_params=query_params, + header_params=header_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/get.pyi new file mode 100644 index 0000000000..a2468eb18d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/get.pyi @@ -0,0 +1,685 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Query params + + +class EnumQueryStringArraySchema( + schemas.ListSchema +): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def GREATER_THAN(cls): + return cls(">") + + @schemas.classproperty + def DOLLAR(cls): + return cls("$") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'EnumQueryStringArraySchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class EnumQueryStringSchema( + schemas.EnumBase, + schemas.StrSchema +): + + @schemas.classproperty + def _ABC(cls): + return cls("_abc") + + @schemas.classproperty + def EFG(cls): + return cls("-efg") + + @schemas.classproperty + def XYZ(cls): + return cls("(xyz)") + + +class EnumQueryIntegerSchema( + schemas.EnumBase, + schemas.Int32Schema +): + + @schemas.classproperty + def POSITIVE_1(cls): + return cls(1) + + @schemas.classproperty + def NEGATIVE_2(cls): + return cls(-2) + + +class EnumQueryDoubleSchema( + schemas.EnumBase, + schemas.Float64Schema +): + + @schemas.classproperty + def POSITIVE_1_PT_1(cls): + return cls(1.1) + + @schemas.classproperty + def NEGATIVE_1_PT_2(cls): + return cls(-1.2) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'enum_query_string_array': typing.Union[EnumQueryStringArraySchema, list, tuple, ], + 'enum_query_string': typing.Union[EnumQueryStringSchema, str, ], + 'enum_query_integer': typing.Union[EnumQueryIntegerSchema, decimal.Decimal, int, ], + 'enum_query_double': typing.Union[EnumQueryDoubleSchema, decimal.Decimal, int, float, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_enum_query_string_array = api_client.QueryParameter( + name="enum_query_string_array", + style=api_client.ParameterStyle.FORM, + schema=EnumQueryStringArraySchema, + explode=True, +) +request_query_enum_query_string = api_client.QueryParameter( + name="enum_query_string", + style=api_client.ParameterStyle.FORM, + schema=EnumQueryStringSchema, + explode=True, +) +request_query_enum_query_integer = api_client.QueryParameter( + name="enum_query_integer", + style=api_client.ParameterStyle.FORM, + schema=EnumQueryIntegerSchema, + explode=True, +) +request_query_enum_query_double = api_client.QueryParameter( + name="enum_query_double", + style=api_client.ParameterStyle.FORM, + schema=EnumQueryDoubleSchema, + explode=True, +) +# Header params + + +class EnumHeaderStringArraySchema( + schemas.ListSchema +): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def GREATER_THAN(cls): + return cls(">") + + @schemas.classproperty + def DOLLAR(cls): + return cls("$") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'EnumHeaderStringArraySchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class EnumHeaderStringSchema( + schemas.EnumBase, + schemas.StrSchema +): + + @schemas.classproperty + def _ABC(cls): + return cls("_abc") + + @schemas.classproperty + def EFG(cls): + return cls("-efg") + + @schemas.classproperty + def XYZ(cls): + return cls("(xyz)") +RequestRequiredHeaderParams = typing_extensions.TypedDict( + 'RequestRequiredHeaderParams', + { + } +) +RequestOptionalHeaderParams = typing_extensions.TypedDict( + 'RequestOptionalHeaderParams', + { + 'enum_header_string_array': typing.Union[EnumHeaderStringArraySchema, list, tuple, ], + 'enum_header_string': typing.Union[EnumHeaderStringSchema, str, ], + }, + total=False +) + + +class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): + pass + + +request_header_enum_header_string_array = api_client.HeaderParameter( + name="enum_header_string_array", + style=api_client.ParameterStyle.SIMPLE, + schema=EnumHeaderStringArraySchema, +) +request_header_enum_header_string = api_client.HeaderParameter( + name="enum_header_string", + style=api_client.ParameterStyle.SIMPLE, + schema=EnumHeaderStringSchema, +) +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class enum_form_string_array( + schemas.ListSchema + ): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def GREATER_THAN(cls): + return cls(">") + + @schemas.classproperty + def DOLLAR(cls): + return cls("$") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'enum_form_string_array': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + + class enum_form_string( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def _ABC(cls): + return cls("_abc") + + @schemas.classproperty + def EFG(cls): + return cls("-efg") + + @schemas.classproperty + def XYZ(cls): + return cls("(xyz)") + __annotations__ = { + "enum_form_string_array": enum_form_string_array, + "enum_form_string": enum_form_string, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_form_string_array"]) -> MetaOapg.properties.enum_form_string_array: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["enum_form_string"]) -> MetaOapg.properties.enum_form_string: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["enum_form_string_array", "enum_form_string", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_form_string_array"]) -> typing.Union[MetaOapg.properties.enum_form_string_array, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["enum_form_string"]) -> typing.Union[MetaOapg.properties.enum_form_string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["enum_form_string_array", "enum_form_string", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + enum_form_string_array: typing.Union[MetaOapg.properties.enum_form_string_array, list, tuple, schemas.Unset] = schemas.unset, + enum_form_string: typing.Union[MetaOapg.properties.enum_form_string, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': + return super().__new__( + cls, + *args, + enum_form_string_array=enum_form_string_array, + enum_form_string=enum_form_string, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/x-www-form-urlencoded': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), + }, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _enum_parameters_oapg( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _enum_parameters_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _enum_parameters_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _enum_parameters_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _enum_parameters_oapg( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + To test enum parameters + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + self._verify_typed_dict_inputs_oapg(RequestHeaderParams, header_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_enum_query_string_array, + request_query_enum_query_string, + request_query_enum_query_integer, + request_query_enum_query_double, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + for parameter in ( + request_header_enum_header_string_array, + request_header_enum_header_string, + ): + parameter_data = header_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _headers.extend(serialized_data) + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class EnumParameters(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def enum_parameters( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def enum_parameters( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def enum_parameters( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def enum_parameters( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def enum_parameters( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._enum_parameters_oapg( + body=body, + query_params=query_params, + header_params=header_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def get( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._enum_parameters_oapg( + body=body, + query_params=query_params, + header_params=header_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake/patch.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/patch.py new file mode 100644 index 0000000000..5a5927a2b0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/patch.py @@ -0,0 +1,329 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.client import Client + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Client + + +request_body_client = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationJson = Client + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + To test \"client\" model + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_client.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='patch'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ClientModel(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._client_model_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpatch(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._client_model_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake/patch.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/patch.pyi new file mode 100644 index 0000000000..1cd6c45377 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/patch.pyi @@ -0,0 +1,324 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.client import Client + +# body param +SchemaForRequestBodyApplicationJson = Client + + +request_body_client = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationJson = Client + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _client_model_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + To test \"client\" model + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_client.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='patch'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ClientModel(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def client_model( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._client_model_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpatch(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._client_model_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/post.py new file mode 100644 index 0000000000..5bded5d3e0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/post.py @@ -0,0 +1,579 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + schemas.DictSchema +): + + + class MetaOapg: + required = { + "number", + "pattern_without_delimiter", + "byte", + "double", + } + + class properties: + + + class integer( + schemas.IntSchema + ): + + + class MetaOapg: + inclusive_maximum = 100 + inclusive_minimum = 10 + + + class int32( + schemas.Int32Schema + ): + + + class MetaOapg: + format = 'int32' + inclusive_maximum = 200 + inclusive_minimum = 20 + int64 = schemas.Int64Schema + + + class number( + schemas.NumberSchema + ): + + + class MetaOapg: + inclusive_maximum = 543.2 + inclusive_minimum = 32.1 + + + class _float( + schemas.Float32Schema + ): + + + class MetaOapg: + format = 'float' + inclusive_maximum = 987.6 + + + class double( + schemas.Float64Schema + ): + + + class MetaOapg: + format = 'double' + inclusive_maximum = 123.4 + inclusive_minimum = 67.8 + + + class string( + schemas.StrSchema + ): + + + class MetaOapg: + regex=[{ + 'pattern': r'[a-z]', # noqa: E501 + 'flags': ( + re.IGNORECASE + ) + }] + + + class pattern_without_delimiter( + schemas.StrSchema + ): + + + class MetaOapg: + regex=[{ + 'pattern': r'^[A-Z].*', # noqa: E501 + }] + byte = schemas.StrSchema + binary = schemas.BinarySchema + date = schemas.DateSchema + dateTime = schemas.DateTimeSchema + + + class password( + schemas.StrSchema + ): + + + class MetaOapg: + format = 'password' + max_length = 64 + min_length = 10 + callback = schemas.StrSchema + __annotations__ = { + "integer": integer, + "int32": int32, + "int64": int64, + "number": number, + "float": _float, + "double": double, + "string": string, + "pattern_without_delimiter": pattern_without_delimiter, + "byte": byte, + "binary": binary, + "date": date, + "dateTime": dateTime, + "password": password, + "callback": callback, + } + + number: MetaOapg.properties.number + pattern_without_delimiter: MetaOapg.properties.pattern_without_delimiter + byte: MetaOapg.properties.byte + double: MetaOapg.properties.double + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["integer"]) -> MetaOapg.properties.integer: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int32"]) -> MetaOapg.properties.int32: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int64"]) -> MetaOapg.properties.int64: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float"]) -> MetaOapg.properties._float: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["double"]) -> MetaOapg.properties.double: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["string"]) -> MetaOapg.properties.string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["pattern_without_delimiter"]) -> MetaOapg.properties.pattern_without_delimiter: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["byte"]) -> MetaOapg.properties.byte: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["binary"]) -> MetaOapg.properties.binary: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date"]) -> MetaOapg.properties.date: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["dateTime"]) -> MetaOapg.properties.dateTime: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["password"]) -> MetaOapg.properties.password: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["callback"]) -> MetaOapg.properties.callback: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["integer", "int32", "int64", "number", "float", "double", "string", "pattern_without_delimiter", "byte", "binary", "date", "dateTime", "password", "callback", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["integer"]) -> typing.Union[MetaOapg.properties.integer, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int32"]) -> typing.Union[MetaOapg.properties.int32, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int64"]) -> typing.Union[MetaOapg.properties.int64, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float"]) -> typing.Union[MetaOapg.properties._float, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["double"]) -> MetaOapg.properties.double: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["string"]) -> typing.Union[MetaOapg.properties.string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["pattern_without_delimiter"]) -> MetaOapg.properties.pattern_without_delimiter: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["byte"]) -> MetaOapg.properties.byte: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["binary"]) -> typing.Union[MetaOapg.properties.binary, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date"]) -> typing.Union[MetaOapg.properties.date, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["dateTime"]) -> typing.Union[MetaOapg.properties.dateTime, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["password"]) -> typing.Union[MetaOapg.properties.password, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["callback"]) -> typing.Union[MetaOapg.properties.callback, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["integer", "int32", "int64", "number", "float", "double", "string", "pattern_without_delimiter", "byte", "binary", "date", "dateTime", "password", "callback", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + number: typing.Union[MetaOapg.properties.number, decimal.Decimal, int, float, ], + pattern_without_delimiter: typing.Union[MetaOapg.properties.pattern_without_delimiter, str, ], + byte: typing.Union[MetaOapg.properties.byte, str, ], + double: typing.Union[MetaOapg.properties.double, decimal.Decimal, int, float, ], + integer: typing.Union[MetaOapg.properties.integer, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int32: typing.Union[MetaOapg.properties.int32, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int64: typing.Union[MetaOapg.properties.int64, decimal.Decimal, int, schemas.Unset] = schemas.unset, + string: typing.Union[MetaOapg.properties.string, str, schemas.Unset] = schemas.unset, + binary: typing.Union[MetaOapg.properties.binary, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + date: typing.Union[MetaOapg.properties.date, str, date, schemas.Unset] = schemas.unset, + dateTime: typing.Union[MetaOapg.properties.dateTime, str, datetime, schemas.Unset] = schemas.unset, + password: typing.Union[MetaOapg.properties.password, str, schemas.Unset] = schemas.unset, + callback: typing.Union[MetaOapg.properties.callback, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': + return super().__new__( + cls, + *args, + number=number, + pattern_without_delimiter=pattern_without_delimiter, + byte=byte, + double=double, + integer=integer, + int32=int32, + int64=int64, + string=string, + binary=binary, + date=date, + dateTime=dateTime, + password=password, + callback=callback, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/x-www-form-urlencoded': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), + }, +) +_auth = [ + 'http_basic_test', +] + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_status_code_to_response = { + '200': _response_for_200, + '404': _response_for_404, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _endpoint_parameters_oapg( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _endpoint_parameters_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _endpoint_parameters_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _endpoint_parameters_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _endpoint_parameters_oapg( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class EndpointParameters(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def endpoint_parameters( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def endpoint_parameters( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def endpoint_parameters( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def endpoint_parameters( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def endpoint_parameters( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._endpoint_parameters_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._endpoint_parameters_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/post.pyi new file mode 100644 index 0000000000..a7dc2f6dec --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake/post.pyi @@ -0,0 +1,530 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + schemas.DictSchema +): + + + class MetaOapg: + required = { + "number", + "pattern_without_delimiter", + "byte", + "double", + } + + class properties: + + + class integer( + schemas.IntSchema + ): + pass + + + class int32( + schemas.Int32Schema + ): + pass + int64 = schemas.Int64Schema + + + class number( + schemas.NumberSchema + ): + pass + + + class _float( + schemas.Float32Schema + ): + pass + + + class double( + schemas.Float64Schema + ): + pass + + + class string( + schemas.StrSchema + ): + pass + + + class pattern_without_delimiter( + schemas.StrSchema + ): + pass + byte = schemas.StrSchema + binary = schemas.BinarySchema + date = schemas.DateSchema + dateTime = schemas.DateTimeSchema + + + class password( + schemas.StrSchema + ): + pass + callback = schemas.StrSchema + __annotations__ = { + "integer": integer, + "int32": int32, + "int64": int64, + "number": number, + "float": _float, + "double": double, + "string": string, + "pattern_without_delimiter": pattern_without_delimiter, + "byte": byte, + "binary": binary, + "date": date, + "dateTime": dateTime, + "password": password, + "callback": callback, + } + + number: MetaOapg.properties.number + pattern_without_delimiter: MetaOapg.properties.pattern_without_delimiter + byte: MetaOapg.properties.byte + double: MetaOapg.properties.double + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["integer"]) -> MetaOapg.properties.integer: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int32"]) -> MetaOapg.properties.int32: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["int64"]) -> MetaOapg.properties.int64: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["float"]) -> MetaOapg.properties._float: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["double"]) -> MetaOapg.properties.double: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["string"]) -> MetaOapg.properties.string: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["pattern_without_delimiter"]) -> MetaOapg.properties.pattern_without_delimiter: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["byte"]) -> MetaOapg.properties.byte: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["binary"]) -> MetaOapg.properties.binary: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["date"]) -> MetaOapg.properties.date: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["dateTime"]) -> MetaOapg.properties.dateTime: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["password"]) -> MetaOapg.properties.password: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["callback"]) -> MetaOapg.properties.callback: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["integer", "int32", "int64", "number", "float", "double", "string", "pattern_without_delimiter", "byte", "binary", "date", "dateTime", "password", "callback", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["integer"]) -> typing.Union[MetaOapg.properties.integer, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int32"]) -> typing.Union[MetaOapg.properties.int32, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["int64"]) -> typing.Union[MetaOapg.properties.int64, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["number"]) -> MetaOapg.properties.number: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["float"]) -> typing.Union[MetaOapg.properties._float, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["double"]) -> MetaOapg.properties.double: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["string"]) -> typing.Union[MetaOapg.properties.string, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["pattern_without_delimiter"]) -> MetaOapg.properties.pattern_without_delimiter: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["byte"]) -> MetaOapg.properties.byte: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["binary"]) -> typing.Union[MetaOapg.properties.binary, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["date"]) -> typing.Union[MetaOapg.properties.date, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["dateTime"]) -> typing.Union[MetaOapg.properties.dateTime, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["password"]) -> typing.Union[MetaOapg.properties.password, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["callback"]) -> typing.Union[MetaOapg.properties.callback, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["integer", "int32", "int64", "number", "float", "double", "string", "pattern_without_delimiter", "byte", "binary", "date", "dateTime", "password", "callback", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + number: typing.Union[MetaOapg.properties.number, decimal.Decimal, int, float, ], + pattern_without_delimiter: typing.Union[MetaOapg.properties.pattern_without_delimiter, str, ], + byte: typing.Union[MetaOapg.properties.byte, str, ], + double: typing.Union[MetaOapg.properties.double, decimal.Decimal, int, float, ], + integer: typing.Union[MetaOapg.properties.integer, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int32: typing.Union[MetaOapg.properties.int32, decimal.Decimal, int, schemas.Unset] = schemas.unset, + int64: typing.Union[MetaOapg.properties.int64, decimal.Decimal, int, schemas.Unset] = schemas.unset, + string: typing.Union[MetaOapg.properties.string, str, schemas.Unset] = schemas.unset, + binary: typing.Union[MetaOapg.properties.binary, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + date: typing.Union[MetaOapg.properties.date, str, date, schemas.Unset] = schemas.unset, + dateTime: typing.Union[MetaOapg.properties.dateTime, str, datetime, schemas.Unset] = schemas.unset, + password: typing.Union[MetaOapg.properties.password, str, schemas.Unset] = schemas.unset, + callback: typing.Union[MetaOapg.properties.callback, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': + return super().__new__( + cls, + *args, + number=number, + pattern_without_delimiter=pattern_without_delimiter, + byte=byte, + double=double, + integer=integer, + int32=int32, + int64=int64, + string=string, + binary=binary, + date=date, + dateTime=dateTime, + password=password, + callback=callback, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/x-www-form-urlencoded': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), + }, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _endpoint_parameters_oapg( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _endpoint_parameters_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _endpoint_parameters_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _endpoint_parameters_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _endpoint_parameters_oapg( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class EndpointParameters(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def endpoint_parameters( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def endpoint_parameters( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def endpoint_parameters( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def endpoint_parameters( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def endpoint_parameters( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._endpoint_parameters_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._endpoint_parameters_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_additional_properties_with_array_of_enums/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_additional_properties_with_array_of_enums/__init__.py new file mode 100644 index 0000000000..704e7f24d9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_additional_properties_with_array_of_enums/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_additional_properties_with_array_of_enums import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_ADDITIONALPROPERTIESWITHARRAYOFENUMS \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_additional_properties_with_array_of_enums/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_additional_properties_with_array_of_enums/get.py new file mode 100644 index 0000000000..c76f1c5798 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_additional_properties_with_array_of_enums/get.py @@ -0,0 +1,326 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AdditionalPropertiesWithArrayOfEnums + + +request_body_additional_properties_with_array_of_enums = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = AdditionalPropertiesWithArrayOfEnums + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _additional_properties_with_array_of_enums_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _additional_properties_with_array_of_enums_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _additional_properties_with_array_of_enums_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _additional_properties_with_array_of_enums_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _additional_properties_with_array_of_enums_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Additional Properties with Array of Enums + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_additional_properties_with_array_of_enums.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class AdditionalPropertiesWithArrayOfEnums(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def additional_properties_with_array_of_enums( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def additional_properties_with_array_of_enums( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def additional_properties_with_array_of_enums( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def additional_properties_with_array_of_enums( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def additional_properties_with_array_of_enums( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._additional_properties_with_array_of_enums_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def get( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._additional_properties_with_array_of_enums_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_additional_properties_with_array_of_enums/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_additional_properties_with_array_of_enums/get.pyi new file mode 100644 index 0000000000..13981bf475 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_additional_properties_with_array_of_enums/get.pyi @@ -0,0 +1,321 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums + +# body param +SchemaForRequestBodyApplicationJson = AdditionalPropertiesWithArrayOfEnums + + +request_body_additional_properties_with_array_of_enums = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = AdditionalPropertiesWithArrayOfEnums + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _additional_properties_with_array_of_enums_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _additional_properties_with_array_of_enums_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _additional_properties_with_array_of_enums_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _additional_properties_with_array_of_enums_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _additional_properties_with_array_of_enums_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Additional Properties with Array of Enums + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_additional_properties_with_array_of_enums.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class AdditionalPropertiesWithArrayOfEnums(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def additional_properties_with_array_of_enums( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def additional_properties_with_array_of_enums( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def additional_properties_with_array_of_enums( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def additional_properties_with_array_of_enums( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def additional_properties_with_array_of_enums( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._additional_properties_with_array_of_enums_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def get( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._additional_properties_with_array_of_enums_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_file_schema/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_file_schema/__init__.py new file mode 100644 index 0000000000..cae3a5325e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_file_schema/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_body_with_file_schema import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_BODYWITHFILESCHEMA \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_file_schema/put.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_file_schema/put.py new file mode 100644 index 0000000000..481882c97f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_file_schema/put.py @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.file_schema_test_class import FileSchemaTestClass + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = FileSchemaTestClass + + +request_body_file_schema_test_class = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_file_schema_test_class.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class BodyWithFileSchema(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._body_with_file_schema_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._body_with_file_schema_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_file_schema/put.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_file_schema/put.pyi new file mode 100644 index 0000000000..7785729eb2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_file_schema/put.pyi @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.file_schema_test_class import FileSchemaTestClass + +# body param +SchemaForRequestBodyApplicationJson = FileSchemaTestClass + + +request_body_file_schema_test_class = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _body_with_file_schema_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_file_schema_test_class.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class BodyWithFileSchema(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def body_with_file_schema( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._body_with_file_schema_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._body_with_file_schema_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_query_params/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_query_params/__init__.py new file mode 100644 index 0000000000..c79334843e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_query_params/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_body_with_query_params import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_BODYWITHQUERYPARAMS \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_query_params/put.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_query_params/put.py new file mode 100644 index 0000000000..03d8d0b48f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_query_params/put.py @@ -0,0 +1,356 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +from . import path + +# Query params +QuerySchema = schemas.StrSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'query': typing.Union[QuerySchema, str, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_query = api_client.QueryParameter( + name="query", + style=api_client.ParameterStyle.FORM, + schema=QuerySchema, + required=True, + explode=True, +) +# body param +SchemaForRequestBodyApplicationJson = User + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_query, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class BodyWithQueryParams(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._body_with_query_params_oapg( + body=body, + query_params=query_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._body_with_query_params_oapg( + body=body, + query_params=query_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_query_params/put.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_query_params/put.pyi new file mode 100644 index 0000000000..6e34838b84 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_body_with_query_params/put.pyi @@ -0,0 +1,351 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +# Query params +QuerySchema = schemas.StrSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'query': typing.Union[QuerySchema, str, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_query = api_client.QueryParameter( + name="query", + style=api_client.ParameterStyle.FORM, + schema=QuerySchema, + required=True, + explode=True, +) +# body param +SchemaForRequestBodyApplicationJson = User + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _body_with_query_params_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_query, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class BodyWithQueryParams(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def body_with_query_params( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._body_with_query_params_oapg( + body=body, + query_params=query_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._body_with_query_params_oapg( + body=body, + query_params=query_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_case_sensitive_params/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_case_sensitive_params/__init__.py new file mode 100644 index 0000000000..dcc9e69f9b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_case_sensitive_params/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_case_sensitive_params import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_CASESENSITIVEPARAMS \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_case_sensitive_params/put.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_case_sensitive_params/put.py new file mode 100644 index 0000000000..971de7cf96 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_case_sensitive_params/put.py @@ -0,0 +1,273 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Query params +SomeVarSchema = schemas.StrSchema +SomeVarSchema = schemas.StrSchema +SomeVarSchema = schemas.StrSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'someVar': typing.Union[SomeVarSchema, str, ], + 'SomeVar': typing.Union[SomeVarSchema, str, ], + 'some_var': typing.Union[SomeVarSchema, str, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_some_var = api_client.QueryParameter( + name="someVar", + style=api_client.ParameterStyle.FORM, + schema=SomeVarSchema, + required=True, + explode=True, +) +request_query_some_var2 = api_client.QueryParameter( + name="SomeVar", + style=api_client.ParameterStyle.FORM, + schema=SomeVarSchema, + required=True, + explode=True, +) +request_query_some_var3 = api_client.QueryParameter( + name="some_var", + style=api_client.ParameterStyle.FORM, + schema=SomeVarSchema, + required=True, + explode=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _case_sensitive_params_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _case_sensitive_params_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _case_sensitive_params_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _case_sensitive_params_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_some_var, + request_query_some_var2, + request_query_some_var3, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CaseSensitiveParams(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def case_sensitive_params( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def case_sensitive_params( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def case_sensitive_params( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def case_sensitive_params( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._case_sensitive_params_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._case_sensitive_params_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_case_sensitive_params/put.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_case_sensitive_params/put.pyi new file mode 100644 index 0000000000..69c3adfb97 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_case_sensitive_params/put.pyi @@ -0,0 +1,268 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Query params +SomeVarSchema = schemas.StrSchema +SomeVarSchema = schemas.StrSchema +SomeVarSchema = schemas.StrSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'someVar': typing.Union[SomeVarSchema, str, ], + 'SomeVar': typing.Union[SomeVarSchema, str, ], + 'some_var': typing.Union[SomeVarSchema, str, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_some_var = api_client.QueryParameter( + name="someVar", + style=api_client.ParameterStyle.FORM, + schema=SomeVarSchema, + required=True, + explode=True, +) +request_query_some_var2 = api_client.QueryParameter( + name="SomeVar", + style=api_client.ParameterStyle.FORM, + schema=SomeVarSchema, + required=True, + explode=True, +) +request_query_some_var3 = api_client.QueryParameter( + name="some_var", + style=api_client.ParameterStyle.FORM, + schema=SomeVarSchema, + required=True, + explode=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _case_sensitive_params_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _case_sensitive_params_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _case_sensitive_params_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _case_sensitive_params_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_some_var, + request_query_some_var2, + request_query_some_var3, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CaseSensitiveParams(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def case_sensitive_params( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def case_sensitive_params( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def case_sensitive_params( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def case_sensitive_params( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._case_sensitive_params_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._case_sensitive_params_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_classname_test/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_classname_test/__init__.py new file mode 100644 index 0000000000..d162dcc8f6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_classname_test/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_classname_test import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_CLASSNAME_TEST \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_classname_test/patch.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_classname_test/patch.py new file mode 100644 index 0000000000..72a085dbaf --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_classname_test/patch.py @@ -0,0 +1,333 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.client import Client + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Client + + +request_body_client = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +_auth = [ + 'api_key_query', +] +SchemaFor200ResponseBodyApplicationJson = Client + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + To test class name in snake case + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_client.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='patch'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class Classname(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._classname_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpatch(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._classname_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_classname_test/patch.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_classname_test/patch.pyi new file mode 100644 index 0000000000..055301928b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_classname_test/patch.pyi @@ -0,0 +1,325 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.client import Client + +# body param +SchemaForRequestBodyApplicationJson = Client + + +request_body_client = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationJson = Client + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _classname_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + To test class name in snake case + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_client.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='patch'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class Classname(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def classname( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._classname_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpatch(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def patch( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._classname_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_delete_coffee_id/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_delete_coffee_id/__init__.py new file mode 100644 index 0000000000..810d63883b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_delete_coffee_id/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_delete_coffee_id import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_DELETE_COFFEE_ID \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_delete_coffee_id/delete.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_delete_coffee_id/delete.py new file mode 100644 index 0000000000..6aeab76eac --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_delete_coffee_id/delete.py @@ -0,0 +1,276 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Path params +IdSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'id': typing.Union[IdSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_id = api_client.PathParameter( + name="id", + style=api_client.ParameterStyle.SIMPLE, + schema=IdSchema, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) +_status_code_to_response = { + '200': _response_for_200, + 'default': _response_for_default, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _delete_coffee_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + ]: ... + + @typing.overload + def _delete_coffee_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _delete_coffee_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _delete_coffee_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Delete coffee + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DeleteCoffee(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def delete_coffee( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + ]: ... + + @typing.overload + def delete_coffee( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete_coffee( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete_coffee( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_coffee_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + ]: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_coffee_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_delete_coffee_id/delete.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_delete_coffee_id/delete.pyi new file mode 100644 index 0000000000..7a0240795e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_delete_coffee_id/delete.pyi @@ -0,0 +1,270 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Path params +IdSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'id': typing.Union[IdSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_id = api_client.PathParameter( + name="id", + style=api_client.ParameterStyle.SIMPLE, + schema=IdSchema, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _delete_coffee_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + ]: ... + + @typing.overload + def _delete_coffee_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _delete_coffee_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _delete_coffee_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Delete coffee + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DeleteCoffee(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def delete_coffee( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + ]: ... + + @typing.overload + def delete_coffee( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete_coffee( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete_coffee( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_coffee_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + ]: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_coffee_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_health/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_health/__init__.py new file mode 100644 index 0000000000..d113dc832c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_health/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_health import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_HEALTH \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_health/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_health/get.py new file mode 100644 index 0000000000..f3ebfb0b65 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_health/get.py @@ -0,0 +1,232 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.health_check_result import HealthCheckResult + +from . import path + +SchemaFor200ResponseBodyApplicationJson = HealthCheckResult + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _fake_health_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _fake_health_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _fake_health_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _fake_health_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Health check endpoint + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class FakeHealthGet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def fake_health_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def fake_health_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def fake_health_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def fake_health_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._fake_health_get_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._fake_health_get_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_health/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_health/get.pyi new file mode 100644 index 0000000000..f63161e2d2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_health/get.pyi @@ -0,0 +1,227 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.health_check_result import HealthCheckResult + +SchemaFor200ResponseBodyApplicationJson = HealthCheckResult + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _fake_health_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _fake_health_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _fake_health_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _fake_health_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Health check endpoint + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class FakeHealthGet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def fake_health_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def fake_health_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def fake_health_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def fake_health_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._fake_health_get_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._fake_health_get_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_additional_properties/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_additional_properties/__init__.py new file mode 100644 index 0000000000..4f2ec020c5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_additional_properties/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_inline_additional_properties import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_INLINEADDITIONAL_PROPERTIES \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_additional_properties/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_additional_properties/post.py new file mode 100644 index 0000000000..2363305f7c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_additional_properties/post.py @@ -0,0 +1,325 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.DictSchema +): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_request_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + test inline additionalProperties + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_request_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class InlineAdditionalProperties(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._inline_additional_properties_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._inline_additional_properties_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_additional_properties/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_additional_properties/post.pyi new file mode 100644 index 0000000000..71113ab91a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_additional_properties/post.pyi @@ -0,0 +1,320 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.DictSchema +): + + + class MetaOapg: + additional_properties = schemas.StrSchema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, str, ], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +request_body_request_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _inline_additional_properties_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + test inline additionalProperties + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_request_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class InlineAdditionalProperties(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def inline_additional_properties( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._inline_additional_properties_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,dict, frozendict.frozendict, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._inline_additional_properties_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_composition_/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_composition_/__init__.py new file mode 100644 index 0000000000..b3a8a01127 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_composition_/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_inline_composition_ import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_INLINE_COMPOSITION_ \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_composition_/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_composition_/post.py new file mode 100644 index 0000000000..d7904db7a8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_composition_/post.py @@ -0,0 +1,851 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Query params + + +class CompositionAtRootSchema( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + + + class MetaOapg: + min_length = 1 + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'CompositionAtRootSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +class CompositionInPropertySchema( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class someProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + + + class MetaOapg: + min_length = 1 + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'someProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "someProp": someProp, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["someProp"]) -> MetaOapg.properties.someProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["someProp"]) -> typing.Union[MetaOapg.properties.someProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + someProp: typing.Union[MetaOapg.properties.someProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'CompositionInPropertySchema': + return super().__new__( + cls, + *args, + someProp=someProp, + _configuration=_configuration, + **kwargs, + ) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'compositionAtRoot': typing.Union[CompositionAtRootSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + 'compositionInProperty': typing.Union[CompositionInPropertySchema, dict, frozendict.frozendict, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_composition_at_root = api_client.QueryParameter( + name="compositionAtRoot", + style=api_client.ParameterStyle.FORM, + schema=CompositionAtRootSchema, + explode=True, +) +request_query_composition_in_property = api_client.QueryParameter( + name="compositionInProperty", + style=api_client.ParameterStyle.FORM, + schema=CompositionInPropertySchema, + explode=True, +) +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + + + class MetaOapg: + min_length = 1 + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class someProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + + + class MetaOapg: + min_length = 1 + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'someProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "someProp": someProp, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["someProp"]) -> MetaOapg.properties.someProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["someProp"]) -> typing.Union[MetaOapg.properties.someProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + someProp: typing.Union[MetaOapg.properties.someProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + someProp=someProp, + _configuration=_configuration, + **kwargs, + ) + + +request_body_any_type = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + + + class MetaOapg: + min_length = 1 + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +class SchemaFor200ResponseBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class someProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + + + class MetaOapg: + min_length = 1 + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'someProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "someProp": someProp, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["someProp"]) -> MetaOapg.properties.someProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["someProp"]) -> typing.Union[MetaOapg.properties.someProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + someProp: typing.Union[MetaOapg.properties.someProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyMultipartFormData': + return super().__new__( + cls, + *args, + someProp=someProp, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + SchemaFor200ResponseBodyMultipartFormData, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + 'multipart/form-data': api_client.MediaType( + schema=SchemaFor200ResponseBodyMultipartFormData), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', + 'multipart/form-data', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _inline_composition_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _inline_composition_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"], + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _inline_composition_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _inline_composition_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _inline_composition_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _inline_composition_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + testing composed schemas at inline locations + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_composition_at_root, + request_query_composition_in_property, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_any_type.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class InlineComposition(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def inline_composition( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def inline_composition( + self, + content_type: typing_extensions.Literal["multipart/form-data"], + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def inline_composition( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def inline_composition( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def inline_composition( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def inline_composition( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._inline_composition_oapg( + body=body, + query_params=query_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"], + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._inline_composition_oapg( + body=body, + query_params=query_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_composition_/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_composition_/post.pyi new file mode 100644 index 0000000000..56503791e7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_inline_composition_/post.pyi @@ -0,0 +1,828 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Query params + + +class CompositionAtRootSchema( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + pass + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'CompositionAtRootSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +class CompositionInPropertySchema( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class someProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + pass + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'someProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "someProp": someProp, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["someProp"]) -> MetaOapg.properties.someProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["someProp"]) -> typing.Union[MetaOapg.properties.someProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + someProp: typing.Union[MetaOapg.properties.someProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'CompositionInPropertySchema': + return super().__new__( + cls, + *args, + someProp=someProp, + _configuration=_configuration, + **kwargs, + ) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'compositionAtRoot': typing.Union[CompositionAtRootSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + 'compositionInProperty': typing.Union[CompositionInPropertySchema, dict, frozendict.frozendict, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_composition_at_root = api_client.QueryParameter( + name="compositionAtRoot", + style=api_client.ParameterStyle.FORM, + schema=CompositionAtRootSchema, + explode=True, +) +request_query_composition_in_property = api_client.QueryParameter( + name="compositionInProperty", + style=api_client.ParameterStyle.FORM, + schema=CompositionInPropertySchema, + explode=True, +) +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + pass + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class someProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + pass + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'someProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "someProp": someProp, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["someProp"]) -> MetaOapg.properties.someProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["someProp"]) -> typing.Union[MetaOapg.properties.someProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + someProp: typing.Union[MetaOapg.properties.someProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + someProp=someProp, + _configuration=_configuration, + **kwargs, + ) + + +request_body_any_type = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ComposedSchema, +): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + pass + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +class SchemaFor200ResponseBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class someProp( + schemas.ComposedSchema, + ): + + + class MetaOapg: + + + class all_of_0( + schemas.StrSchema + ): + pass + + @classmethod + @functools.lru_cache() + def all_of(cls): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error because the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return [ + cls.all_of_0, + ] + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'someProp': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + __annotations__ = { + "someProp": someProp, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["someProp"]) -> MetaOapg.properties.someProp: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["someProp"]) -> typing.Union[MetaOapg.properties.someProp, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["someProp", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + someProp: typing.Union[MetaOapg.properties.someProp, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor200ResponseBodyMultipartFormData': + return super().__new__( + cls, + *args, + someProp=someProp, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + SchemaFor200ResponseBodyMultipartFormData, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + 'multipart/form-data': api_client.MediaType( + schema=SchemaFor200ResponseBodyMultipartFormData), + }, +) +_all_accept_content_types = ( + 'application/json', + 'multipart/form-data', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _inline_composition_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _inline_composition_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"], + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _inline_composition_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _inline_composition_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _inline_composition_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _inline_composition_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + testing composed schemas at inline locations + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_composition_at_root, + request_query_composition_in_property, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_any_type.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class InlineComposition(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def inline_composition( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def inline_composition( + self, + content_type: typing_extensions.Literal["multipart/form-data"], + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def inline_composition( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def inline_composition( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def inline_composition( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def inline_composition( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._inline_composition_oapg( + body=body, + query_params=query_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"], + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._inline_composition_oapg( + body=body, + query_params=query_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_form_data/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_form_data/__init__.py new file mode 100644 index 0000000000..e66fc38772 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_form_data/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_json_form_data import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_JSON_FORM_DATA \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_form_data/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_form_data/get.py new file mode 100644 index 0000000000..262f5e3a77 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_form_data/get.py @@ -0,0 +1,360 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + schemas.DictSchema +): + + + class MetaOapg: + required = { + "param", + "param2", + } + + class properties: + param = schemas.StrSchema + param2 = schemas.StrSchema + __annotations__ = { + "param": param, + "param2": param2, + } + + param: MetaOapg.properties.param + param2: MetaOapg.properties.param2 + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["param"]) -> MetaOapg.properties.param: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["param2"]) -> MetaOapg.properties.param2: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["param", "param2", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["param"]) -> MetaOapg.properties.param: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["param2"]) -> MetaOapg.properties.param2: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["param", "param2", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + param: typing.Union[MetaOapg.properties.param, str, ], + param2: typing.Union[MetaOapg.properties.param2, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': + return super().__new__( + cls, + *args, + param=param, + param2=param2, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/x-www-form-urlencoded': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), + }, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _json_form_data_oapg( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _json_form_data_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _json_form_data_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _json_form_data_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _json_form_data_oapg( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + test json serialization of form data + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class JsonFormData(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def json_form_data( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def json_form_data( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def json_form_data( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def json_form_data( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def json_form_data( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_form_data_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def get( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_form_data_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_form_data/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_form_data/get.pyi new file mode 100644 index 0000000000..e1ce657827 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_form_data/get.pyi @@ -0,0 +1,355 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + schemas.DictSchema +): + + + class MetaOapg: + required = { + "param", + "param2", + } + + class properties: + param = schemas.StrSchema + param2 = schemas.StrSchema + __annotations__ = { + "param": param, + "param2": param2, + } + + param: MetaOapg.properties.param + param2: MetaOapg.properties.param2 + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["param"]) -> MetaOapg.properties.param: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["param2"]) -> MetaOapg.properties.param2: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["param", "param2", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["param"]) -> MetaOapg.properties.param: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["param2"]) -> MetaOapg.properties.param2: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["param", "param2", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + param: typing.Union[MetaOapg.properties.param, str, ], + param2: typing.Union[MetaOapg.properties.param2, str, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': + return super().__new__( + cls, + *args, + param=param, + param2=param2, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/x-www-form-urlencoded': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), + }, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _json_form_data_oapg( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _json_form_data_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _json_form_data_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _json_form_data_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _json_form_data_oapg( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + test json serialization of form data + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class JsonFormData(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def json_form_data( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def json_form_data( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def json_form_data( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def json_form_data( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def json_form_data( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_form_data_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def get( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_form_data_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_patch/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_patch/__init__.py new file mode 100644 index 0000000000..b302e74cce --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_patch/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_json_patch import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_JSON_PATCH \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_patch/patch.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_patch/patch.py new file mode 100644 index 0000000000..d55867cd11 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_patch/patch.py @@ -0,0 +1,296 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.json_patch_request import JSONPatchRequest + +from . import path + +# body param +SchemaForRequestBodyApplicationJsonPatchjson = JSONPatchRequest + + +request_body_json_patch_request = api_client.RequestBody( + content={ + 'application/json-patch+json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJsonPatchjson), + }, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _json_patch_oapg( + self, + content_type: typing_extensions.Literal["application/json-patch+json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _json_patch_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _json_patch_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _json_patch_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _json_patch_oapg( + self, + content_type: str = 'application/json-patch+json', + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + json patch + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_json_patch_request.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='patch'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class JsonPatch(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def json_patch( + self, + content_type: typing_extensions.Literal["application/json-patch+json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def json_patch( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def json_patch( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def json_patch( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def json_patch( + self, + content_type: str = 'application/json-patch+json', + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_patch_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpatch(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def patch( + self, + content_type: typing_extensions.Literal["application/json-patch+json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def patch( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def patch( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def patch( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def patch( + self, + content_type: str = 'application/json-patch+json', + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_patch_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_patch/patch.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_patch/patch.pyi new file mode 100644 index 0000000000..3322e593cc --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_patch/patch.pyi @@ -0,0 +1,291 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.json_patch_request import JSONPatchRequest + +# body param +SchemaForRequestBodyApplicationJsonPatchjson = JSONPatchRequest + + +request_body_json_patch_request = api_client.RequestBody( + content={ + 'application/json-patch+json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJsonPatchjson), + }, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _json_patch_oapg( + self, + content_type: typing_extensions.Literal["application/json-patch+json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _json_patch_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _json_patch_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _json_patch_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _json_patch_oapg( + self, + content_type: str = 'application/json-patch+json', + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + json patch + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_json_patch_request.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='patch'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class JsonPatch(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def json_patch( + self, + content_type: typing_extensions.Literal["application/json-patch+json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def json_patch( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def json_patch( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def json_patch( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def json_patch( + self, + content_type: str = 'application/json-patch+json', + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_patch_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpatch(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def patch( + self, + content_type: typing_extensions.Literal["application/json-patch+json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def patch( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def patch( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def patch( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def patch( + self, + content_type: str = 'application/json-patch+json', + body: typing.Union[SchemaForRequestBodyApplicationJsonPatchjson, schemas.Unset] = schemas.unset, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_patch_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_with_charset/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_with_charset/__init__.py new file mode 100644 index 0000000000..3adee6e9d6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_with_charset/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_json_with_charset import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_JSON_WITH_CHARSET \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_with_charset/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_with_charset/post.py new file mode 100644 index 0000000000..7e075373a3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_with_charset/post.py @@ -0,0 +1,324 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationJsonCharsetutf8 = schemas.AnyTypeSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json; charset=utf-8': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJsonCharsetutf8), + }, +) +SchemaFor200ResponseBodyApplicationJsonCharsetutf8 = schemas.AnyTypeSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJsonCharsetutf8, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json; charset=utf-8': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJsonCharsetutf8), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json; charset=utf-8', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _json_with_charset_oapg( + self, + content_type: typing_extensions.Literal["application/json; charset=utf-8"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _json_with_charset_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _json_with_charset_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _json_with_charset_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _json_with_charset_oapg( + self, + content_type: str = 'application/json; charset=utf-8', + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + json with charset tx and rx + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class JsonWithCharset(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def json_with_charset( + self, + content_type: typing_extensions.Literal["application/json; charset=utf-8"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def json_with_charset( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def json_with_charset( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def json_with_charset( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def json_with_charset( + self, + content_type: str = 'application/json; charset=utf-8', + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_with_charset_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json; charset=utf-8"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json; charset=utf-8', + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_with_charset_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_with_charset/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_with_charset/post.pyi new file mode 100644 index 0000000000..5246ee555a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_json_with_charset/post.pyi @@ -0,0 +1,319 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationJsonCharsetutf8 = schemas.AnyTypeSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json; charset=utf-8': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJsonCharsetutf8), + }, +) +SchemaFor200ResponseBodyApplicationJsonCharsetutf8 = schemas.AnyTypeSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJsonCharsetutf8, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json; charset=utf-8': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJsonCharsetutf8), + }, +) +_all_accept_content_types = ( + 'application/json; charset=utf-8', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _json_with_charset_oapg( + self, + content_type: typing_extensions.Literal["application/json; charset=utf-8"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _json_with_charset_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _json_with_charset_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _json_with_charset_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _json_with_charset_oapg( + self, + content_type: str = 'application/json; charset=utf-8', + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + json with charset tx and rx + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class JsonWithCharset(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def json_with_charset( + self, + content_type: typing_extensions.Literal["application/json; charset=utf-8"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def json_with_charset( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def json_with_charset( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def json_with_charset( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def json_with_charset( + self, + content_type: str = 'application/json; charset=utf-8', + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_with_charset_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json; charset=utf-8"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json; charset=utf-8', + body: typing.Union[SchemaForRequestBodyApplicationJsonCharsetutf8, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._json_with_charset_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_obj_in_query/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_obj_in_query/__init__.py new file mode 100644 index 0000000000..758109e7c0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_obj_in_query/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_obj_in_query import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_OBJ_IN_QUERY \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_obj_in_query/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_obj_in_query/get.py new file mode 100644 index 0000000000..60e361c9b3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_obj_in_query/get.py @@ -0,0 +1,302 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Query params + + +class MapBeanSchema( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + keyword = schemas.StrSchema + __annotations__ = { + "keyword": keyword, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["keyword"]) -> MetaOapg.properties.keyword: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["keyword", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["keyword"]) -> typing.Union[MetaOapg.properties.keyword, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["keyword", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + keyword: typing.Union[MetaOapg.properties.keyword, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MapBeanSchema': + return super().__new__( + cls, + *args, + keyword=keyword, + _configuration=_configuration, + **kwargs, + ) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'mapBean': typing.Union[MapBeanSchema, dict, frozendict.frozendict, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_map_bean = api_client.QueryParameter( + name="mapBean", + style=api_client.ParameterStyle.DEEP_OBJECT, + schema=MapBeanSchema, + explode=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + user list + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_map_bean, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ObjectInQuery(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._object_in_query_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._object_in_query_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_obj_in_query/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_obj_in_query/get.pyi new file mode 100644 index 0000000000..f6bcadc02c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_obj_in_query/get.pyi @@ -0,0 +1,297 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Query params + + +class MapBeanSchema( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + keyword = schemas.StrSchema + __annotations__ = { + "keyword": keyword, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["keyword"]) -> MetaOapg.properties.keyword: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["keyword", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["keyword"]) -> typing.Union[MetaOapg.properties.keyword, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["keyword", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + keyword: typing.Union[MetaOapg.properties.keyword, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'MapBeanSchema': + return super().__new__( + cls, + *args, + keyword=keyword, + _configuration=_configuration, + **kwargs, + ) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'mapBean': typing.Union[MapBeanSchema, dict, frozendict.frozendict, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_map_bean = api_client.QueryParameter( + name="mapBean", + style=api_client.ParameterStyle.DEEP_OBJECT, + schema=MapBeanSchema, + explode=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + user list + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_map_bean, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ObjectInQuery(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._object_in_query_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._object_in_query_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_/__init__.py new file mode 100644 index 0000000000..e82cc25a7d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_parameter_collisions_1_a_b_ab_self_a_b_ import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_PARAMETER_COLLISIONS_1_A_B_AB_SELF_AB_ \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_/post.py new file mode 100644 index 0000000000..4f12ff8fad --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_/post.py @@ -0,0 +1,661 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Query params +Model1Schema = schemas.StrSchema +ABSchema = schemas.StrSchema +AbSchema = schemas.StrSchema +ModelSelfSchema = schemas.StrSchema +ABSchema = schemas.StrSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + '1': typing.Union[Model1Schema, str, ], + 'aB': typing.Union[ABSchema, str, ], + 'Ab': typing.Union[AbSchema, str, ], + 'self': typing.Union[ModelSelfSchema, str, ], + 'A-B': typing.Union[ABSchema, str, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query__1 = api_client.QueryParameter( + name="1", + style=api_client.ParameterStyle.FORM, + schema=Model1Schema, + explode=True, +) +request_query_a_b = api_client.QueryParameter( + name="aB", + style=api_client.ParameterStyle.FORM, + schema=ABSchema, + explode=True, +) +request_query_ab = api_client.QueryParameter( + name="Ab", + style=api_client.ParameterStyle.FORM, + schema=AbSchema, + explode=True, +) +request_query__self = api_client.QueryParameter( + name="self", + style=api_client.ParameterStyle.FORM, + schema=ModelSelfSchema, + explode=True, +) +request_query_a_b2 = api_client.QueryParameter( + name="A-B", + style=api_client.ParameterStyle.FORM, + schema=ABSchema, + explode=True, +) +# Header params +Model1Schema = schemas.StrSchema +ABSchema = schemas.StrSchema +ModelSelfSchema = schemas.StrSchema +ABSchema = schemas.StrSchema +RequestRequiredHeaderParams = typing_extensions.TypedDict( + 'RequestRequiredHeaderParams', + { + } +) +RequestOptionalHeaderParams = typing_extensions.TypedDict( + 'RequestOptionalHeaderParams', + { + '1': typing.Union[Model1Schema, str, ], + 'aB': typing.Union[ABSchema, str, ], + 'self': typing.Union[ModelSelfSchema, str, ], + 'A-B': typing.Union[ABSchema, str, ], + }, + total=False +) + + +class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): + pass + + +request_header__2 = api_client.HeaderParameter( + name="1", + style=api_client.ParameterStyle.SIMPLE, + schema=Model1Schema, +) +request_header_a_b3 = api_client.HeaderParameter( + name="aB", + style=api_client.ParameterStyle.SIMPLE, + schema=ABSchema, +) +request_header__self2 = api_client.HeaderParameter( + name="self", + style=api_client.ParameterStyle.SIMPLE, + schema=ModelSelfSchema, +) +request_header_a_b4 = api_client.HeaderParameter( + name="A-B", + style=api_client.ParameterStyle.SIMPLE, + schema=ABSchema, +) +# Path params +Model1Schema = schemas.StrSchema +ABSchema = schemas.StrSchema +AbSchema = schemas.StrSchema +ModelSelfSchema = schemas.StrSchema +ABSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + '1': typing.Union[Model1Schema, str, ], + 'aB': typing.Union[ABSchema, str, ], + 'Ab': typing.Union[AbSchema, str, ], + 'self': typing.Union[ModelSelfSchema, str, ], + 'A-B': typing.Union[ABSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path__3 = api_client.PathParameter( + name="1", + style=api_client.ParameterStyle.SIMPLE, + schema=Model1Schema, + required=True, +) +request_path_a_b5 = api_client.PathParameter( + name="aB", + style=api_client.ParameterStyle.SIMPLE, + schema=ABSchema, + required=True, +) +request_path_ab2 = api_client.PathParameter( + name="Ab", + style=api_client.ParameterStyle.SIMPLE, + schema=AbSchema, + required=True, +) +request_path__self3 = api_client.PathParameter( + name="self", + style=api_client.ParameterStyle.SIMPLE, + schema=ModelSelfSchema, + required=True, +) +request_path_a_b6 = api_client.PathParameter( + name="A-B", + style=api_client.ParameterStyle.SIMPLE, + schema=ABSchema, + required=True, +) +# Cookie params +Model1Schema = schemas.StrSchema +ABSchema = schemas.StrSchema +AbSchema = schemas.StrSchema +ModelSelfSchema = schemas.StrSchema +ABSchema = schemas.StrSchema +RequestRequiredCookieParams = typing_extensions.TypedDict( + 'RequestRequiredCookieParams', + { + } +) +RequestOptionalCookieParams = typing_extensions.TypedDict( + 'RequestOptionalCookieParams', + { + '1': typing.Union[Model1Schema, str, ], + 'aB': typing.Union[ABSchema, str, ], + 'Ab': typing.Union[AbSchema, str, ], + 'self': typing.Union[ModelSelfSchema, str, ], + 'A-B': typing.Union[ABSchema, str, ], + }, + total=False +) + + +class RequestCookieParams(RequestRequiredCookieParams, RequestOptionalCookieParams): + pass + + +request_cookie__4 = api_client.CookieParameter( + name="1", + style=api_client.ParameterStyle.FORM, + schema=Model1Schema, + explode=True, +) +request_cookie_a_b7 = api_client.CookieParameter( + name="aB", + style=api_client.ParameterStyle.FORM, + schema=ABSchema, + explode=True, +) +request_cookie_ab3 = api_client.CookieParameter( + name="Ab", + style=api_client.ParameterStyle.FORM, + schema=AbSchema, + explode=True, +) +request_cookie__self4 = api_client.CookieParameter( + name="self", + style=api_client.ParameterStyle.FORM, + schema=ModelSelfSchema, + explode=True, +) +request_cookie_a_b8 = api_client.CookieParameter( + name="A-B", + style=api_client.ParameterStyle.FORM, + schema=ABSchema, + explode=True, +) +# body param +SchemaForRequestBodyApplicationJson = schemas.AnyTypeSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = schemas.AnyTypeSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _parameter_collisions_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _parameter_collisions_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _parameter_collisions_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _parameter_collisions_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _parameter_collisions_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + parameter collision case + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + self._verify_typed_dict_inputs_oapg(RequestHeaderParams, header_params) + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + self._verify_typed_dict_inputs_oapg(RequestCookieParams, cookie_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path__3, + request_path_a_b5, + request_path_ab2, + request_path__self3, + request_path_a_b6, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + prefix_separator_iterator = None + for parameter in ( + request_query__1, + request_query_a_b, + request_query_ab, + request_query__self, + request_query_a_b2, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + for parameter in ( + request_header__2, + request_header_a_b3, + request_header__self2, + request_header_a_b4, + ): + parameter_data = header_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _headers.extend(serialized_data) + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ParameterCollisions(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def parameter_collisions( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def parameter_collisions( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def parameter_collisions( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def parameter_collisions( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def parameter_collisions( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._parameter_collisions_oapg( + body=body, + query_params=query_params, + header_params=header_params, + path_params=path_params, + cookie_params=cookie_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._parameter_collisions_oapg( + body=body, + query_params=query_params, + header_params=header_params, + path_params=path_params, + cookie_params=cookie_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_/post.pyi new file mode 100644 index 0000000000..b24853ab38 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_parameter_collisions_1_a_b_ab_self_a_b_/post.pyi @@ -0,0 +1,656 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Query params +Model1Schema = schemas.StrSchema +ABSchema = schemas.StrSchema +AbSchema = schemas.StrSchema +ModelSelfSchema = schemas.StrSchema +ABSchema = schemas.StrSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + '1': typing.Union[Model1Schema, str, ], + 'aB': typing.Union[ABSchema, str, ], + 'Ab': typing.Union[AbSchema, str, ], + 'self': typing.Union[ModelSelfSchema, str, ], + 'A-B': typing.Union[ABSchema, str, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query__1 = api_client.QueryParameter( + name="1", + style=api_client.ParameterStyle.FORM, + schema=Model1Schema, + explode=True, +) +request_query_a_b = api_client.QueryParameter( + name="aB", + style=api_client.ParameterStyle.FORM, + schema=ABSchema, + explode=True, +) +request_query_ab = api_client.QueryParameter( + name="Ab", + style=api_client.ParameterStyle.FORM, + schema=AbSchema, + explode=True, +) +request_query__self = api_client.QueryParameter( + name="self", + style=api_client.ParameterStyle.FORM, + schema=ModelSelfSchema, + explode=True, +) +request_query_a_b2 = api_client.QueryParameter( + name="A-B", + style=api_client.ParameterStyle.FORM, + schema=ABSchema, + explode=True, +) +# Header params +Model1Schema = schemas.StrSchema +ABSchema = schemas.StrSchema +ModelSelfSchema = schemas.StrSchema +ABSchema = schemas.StrSchema +RequestRequiredHeaderParams = typing_extensions.TypedDict( + 'RequestRequiredHeaderParams', + { + } +) +RequestOptionalHeaderParams = typing_extensions.TypedDict( + 'RequestOptionalHeaderParams', + { + '1': typing.Union[Model1Schema, str, ], + 'aB': typing.Union[ABSchema, str, ], + 'self': typing.Union[ModelSelfSchema, str, ], + 'A-B': typing.Union[ABSchema, str, ], + }, + total=False +) + + +class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): + pass + + +request_header__2 = api_client.HeaderParameter( + name="1", + style=api_client.ParameterStyle.SIMPLE, + schema=Model1Schema, +) +request_header_a_b3 = api_client.HeaderParameter( + name="aB", + style=api_client.ParameterStyle.SIMPLE, + schema=ABSchema, +) +request_header__self2 = api_client.HeaderParameter( + name="self", + style=api_client.ParameterStyle.SIMPLE, + schema=ModelSelfSchema, +) +request_header_a_b4 = api_client.HeaderParameter( + name="A-B", + style=api_client.ParameterStyle.SIMPLE, + schema=ABSchema, +) +# Path params +Model1Schema = schemas.StrSchema +ABSchema = schemas.StrSchema +AbSchema = schemas.StrSchema +ModelSelfSchema = schemas.StrSchema +ABSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + '1': typing.Union[Model1Schema, str, ], + 'aB': typing.Union[ABSchema, str, ], + 'Ab': typing.Union[AbSchema, str, ], + 'self': typing.Union[ModelSelfSchema, str, ], + 'A-B': typing.Union[ABSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path__3 = api_client.PathParameter( + name="1", + style=api_client.ParameterStyle.SIMPLE, + schema=Model1Schema, + required=True, +) +request_path_a_b5 = api_client.PathParameter( + name="aB", + style=api_client.ParameterStyle.SIMPLE, + schema=ABSchema, + required=True, +) +request_path_ab2 = api_client.PathParameter( + name="Ab", + style=api_client.ParameterStyle.SIMPLE, + schema=AbSchema, + required=True, +) +request_path__self3 = api_client.PathParameter( + name="self", + style=api_client.ParameterStyle.SIMPLE, + schema=ModelSelfSchema, + required=True, +) +request_path_a_b6 = api_client.PathParameter( + name="A-B", + style=api_client.ParameterStyle.SIMPLE, + schema=ABSchema, + required=True, +) +# Cookie params +Model1Schema = schemas.StrSchema +ABSchema = schemas.StrSchema +AbSchema = schemas.StrSchema +ModelSelfSchema = schemas.StrSchema +ABSchema = schemas.StrSchema +RequestRequiredCookieParams = typing_extensions.TypedDict( + 'RequestRequiredCookieParams', + { + } +) +RequestOptionalCookieParams = typing_extensions.TypedDict( + 'RequestOptionalCookieParams', + { + '1': typing.Union[Model1Schema, str, ], + 'aB': typing.Union[ABSchema, str, ], + 'Ab': typing.Union[AbSchema, str, ], + 'self': typing.Union[ModelSelfSchema, str, ], + 'A-B': typing.Union[ABSchema, str, ], + }, + total=False +) + + +class RequestCookieParams(RequestRequiredCookieParams, RequestOptionalCookieParams): + pass + + +request_cookie__4 = api_client.CookieParameter( + name="1", + style=api_client.ParameterStyle.FORM, + schema=Model1Schema, + explode=True, +) +request_cookie_a_b7 = api_client.CookieParameter( + name="aB", + style=api_client.ParameterStyle.FORM, + schema=ABSchema, + explode=True, +) +request_cookie_ab3 = api_client.CookieParameter( + name="Ab", + style=api_client.ParameterStyle.FORM, + schema=AbSchema, + explode=True, +) +request_cookie__self4 = api_client.CookieParameter( + name="self", + style=api_client.ParameterStyle.FORM, + schema=ModelSelfSchema, + explode=True, +) +request_cookie_a_b8 = api_client.CookieParameter( + name="A-B", + style=api_client.ParameterStyle.FORM, + schema=ABSchema, + explode=True, +) +# body param +SchemaForRequestBodyApplicationJson = schemas.AnyTypeSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = schemas.AnyTypeSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _parameter_collisions_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _parameter_collisions_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _parameter_collisions_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _parameter_collisions_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _parameter_collisions_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + parameter collision case + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + self._verify_typed_dict_inputs_oapg(RequestHeaderParams, header_params) + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + self._verify_typed_dict_inputs_oapg(RequestCookieParams, cookie_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path__3, + request_path_a_b5, + request_path_ab2, + request_path__self3, + request_path_a_b6, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + prefix_separator_iterator = None + for parameter in ( + request_query__1, + request_query_a_b, + request_query_ab, + request_query__self, + request_query_a_b2, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + for parameter in ( + request_header__2, + request_header_a_b3, + request_header__self2, + request_header_a_b4, + ): + parameter_data = header_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _headers.extend(serialized_data) + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ParameterCollisions(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def parameter_collisions( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def parameter_collisions( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def parameter_collisions( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def parameter_collisions( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def parameter_collisions( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._parameter_collisions_oapg( + body=body, + query_params=query_params, + header_params=header_params, + path_params=path_params, + cookie_params=cookie_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + query_params: RequestQueryParams = frozendict.frozendict(), + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + cookie_params: RequestCookieParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._parameter_collisions_oapg( + body=body, + query_params=query_params, + header_params=header_params, + path_params=path_params, + cookie_params=cookie_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_pet_id_upload_image_with_required_file/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_pet_id_upload_image_with_required_file/__init__.py new file mode 100644 index 0000000000..5463e57769 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_pet_id_upload_image_with_required_file/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_pet_id_upload_image_with_required_file import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_PET_ID_UPLOAD_IMAGE_WITH_REQUIRED_FILE \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_pet_id_upload_image_with_required_file/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_pet_id_upload_image_with_required_file/post.py new file mode 100644 index 0000000000..d5fb0a61b0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_pet_id_upload_image_with_required_file/post.py @@ -0,0 +1,451 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.api_response import ApiResponse + +from . import path + +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) +# body param + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + required = { + "requiredFile", + } + + class properties: + additionalMetadata = schemas.StrSchema + requiredFile = schemas.BinarySchema + __annotations__ = { + "additionalMetadata": additionalMetadata, + "requiredFile": requiredFile, + } + + requiredFile: MetaOapg.properties.requiredFile + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["additionalMetadata"]) -> MetaOapg.properties.additionalMetadata: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["requiredFile"]) -> MetaOapg.properties.requiredFile: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "requiredFile", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["additionalMetadata"]) -> typing.Union[MetaOapg.properties.additionalMetadata, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["requiredFile"]) -> MetaOapg.properties.requiredFile: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "requiredFile", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + requiredFile: typing.Union[MetaOapg.properties.requiredFile, bytes, io.FileIO, io.BufferedReader, ], + additionalMetadata: typing.Union[MetaOapg.properties.additionalMetadata, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + requiredFile=requiredFile, + additionalMetadata=additionalMetadata, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) +_auth = [ + 'petstore_auth', +] +SchemaFor200ResponseBodyApplicationJson = ApiResponse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_file_with_required_file_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_file_with_required_file_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_file_with_required_file_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_file_with_required_file_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_file_with_required_file_oapg( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads an image (required) + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadFileWithRequiredFile(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_file_with_required_file( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_file_with_required_file( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_file_with_required_file( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_file_with_required_file( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_file_with_required_file( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_file_with_required_file_oapg( + body=body, + path_params=path_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_file_with_required_file_oapg( + body=body, + path_params=path_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_pet_id_upload_image_with_required_file/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_pet_id_upload_image_with_required_file/post.pyi new file mode 100644 index 0000000000..94f430e8bb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_pet_id_upload_image_with_required_file/post.pyi @@ -0,0 +1,443 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.api_response import ApiResponse + +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) +# body param + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + required = { + "requiredFile", + } + + class properties: + additionalMetadata = schemas.StrSchema + requiredFile = schemas.BinarySchema + __annotations__ = { + "additionalMetadata": additionalMetadata, + "requiredFile": requiredFile, + } + + requiredFile: MetaOapg.properties.requiredFile + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["additionalMetadata"]) -> MetaOapg.properties.additionalMetadata: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["requiredFile"]) -> MetaOapg.properties.requiredFile: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "requiredFile", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["additionalMetadata"]) -> typing.Union[MetaOapg.properties.additionalMetadata, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["requiredFile"]) -> MetaOapg.properties.requiredFile: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "requiredFile", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + requiredFile: typing.Union[MetaOapg.properties.requiredFile, bytes, io.FileIO, io.BufferedReader, ], + additionalMetadata: typing.Union[MetaOapg.properties.additionalMetadata, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + requiredFile=requiredFile, + additionalMetadata=additionalMetadata, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) +SchemaFor200ResponseBodyApplicationJson = ApiResponse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_file_with_required_file_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_file_with_required_file_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_file_with_required_file_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_file_with_required_file_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_file_with_required_file_oapg( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads an image (required) + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadFileWithRequiredFile(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_file_with_required_file( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_file_with_required_file( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_file_with_required_file( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_file_with_required_file( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_file_with_required_file( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_file_with_required_file_oapg( + body=body, + path_params=path_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_file_with_required_file_oapg( + body=body, + path_params=path_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_query_param_with_json_content_type/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_query_param_with_json_content_type/__init__.py new file mode 100644 index 0000000000..d6a09bc162 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_query_param_with_json_content_type/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_query_param_with_json_content_type import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_QUERY_PARAM_WITH_JSON_CONTENT_TYPE \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_query_param_with_json_content_type/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_query_param_with_json_content_type/get.py new file mode 100644 index 0000000000..6c26877167 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_query_param_with_json_content_type/get.py @@ -0,0 +1,285 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Query params +SchemaForRequestParameterSomeParamApplicationJson = schemas.AnyTypeSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'someParam': typing.Union[SchemaForRequestParameterSomeParamApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_some_param = api_client.QueryParameter( + name="someParam", + content={ + "application/json": SchemaForRequestParameterSomeParamApplicationJson, + }, + required=True, +) +SchemaFor200ResponseBodyApplicationJson = schemas.AnyTypeSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _query_param_with_json_content_type_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _query_param_with_json_content_type_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _query_param_with_json_content_type_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _query_param_with_json_content_type_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + query param with json content-type + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_some_param, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class QueryParamWithJsonContentType(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def query_param_with_json_content_type( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def query_param_with_json_content_type( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def query_param_with_json_content_type( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def query_param_with_json_content_type( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._query_param_with_json_content_type_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._query_param_with_json_content_type_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_query_param_with_json_content_type/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_query_param_with_json_content_type/get.pyi new file mode 100644 index 0000000000..9d042a631f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_query_param_with_json_content_type/get.pyi @@ -0,0 +1,280 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Query params +SchemaForRequestParameterSomeParamApplicationJson = schemas.AnyTypeSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'someParam': typing.Union[SchemaForRequestParameterSomeParamApplicationJson, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_some_param = api_client.QueryParameter( + name="someParam", + content={ + "application/json": SchemaForRequestParameterSomeParamApplicationJson, + }, + required=True, +) +SchemaFor200ResponseBodyApplicationJson = schemas.AnyTypeSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _query_param_with_json_content_type_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _query_param_with_json_content_type_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _query_param_with_json_content_type_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _query_param_with_json_content_type_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + query param with json content-type + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_some_param, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class QueryParamWithJsonContentType(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def query_param_with_json_content_type( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def query_param_with_json_content_type( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def query_param_with_json_content_type( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def query_param_with_json_content_type( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._query_param_with_json_content_type_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._query_param_with_json_content_type_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_ref_obj_in_query/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_ref_obj_in_query/__init__.py new file mode 100644 index 0000000000..f14640328a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_ref_obj_in_query/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_ref_obj_in_query import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REF_OBJ_IN_QUERY \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_ref_obj_in_query/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_ref_obj_in_query/get.py new file mode 100644 index 0000000000..adf8895586 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_ref_obj_in_query/get.py @@ -0,0 +1,255 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.foo import Foo + +from . import path + +# Query params +MapBeanSchema = Foo +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'mapBean': typing.Union[MapBeanSchema, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_map_bean = api_client.QueryParameter( + name="mapBean", + style=api_client.ParameterStyle.DEEP_OBJECT, + schema=MapBeanSchema, + explode=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _ref_object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _ref_object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _ref_object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _ref_object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + user list + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_map_bean, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class RefObjectInQuery(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def ref_object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def ref_object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def ref_object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def ref_object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._ref_object_in_query_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._ref_object_in_query_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_ref_obj_in_query/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_ref_obj_in_query/get.pyi new file mode 100644 index 0000000000..8c34a12749 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_ref_obj_in_query/get.pyi @@ -0,0 +1,250 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.foo import Foo + +# Query params +MapBeanSchema = Foo +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + 'mapBean': typing.Union[MapBeanSchema, ], + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_map_bean = api_client.QueryParameter( + name="mapBean", + style=api_client.ParameterStyle.DEEP_OBJECT, + schema=MapBeanSchema, + explode=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _ref_object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _ref_object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _ref_object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _ref_object_in_query_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + user list + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_map_bean, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class RefObjectInQuery(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def ref_object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def ref_object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def ref_object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def ref_object_in_query( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._ref_object_in_query_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._ref_object_in_query_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_array_of_enums/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_array_of_enums/__init__.py new file mode 100644 index 0000000000..59f3e61b17 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_array_of_enums/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_refs_array_of_enums import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REFS_ARRAYOFENUMS \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_array_of_enums/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_array_of_enums/post.py new file mode 100644 index 0000000000..f8ec75ce3e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_array_of_enums/post.py @@ -0,0 +1,326 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.array_of_enums import ArrayOfEnums + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = ArrayOfEnums + + +request_body_array_of_enums = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = ArrayOfEnums + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _array_of_enums_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _array_of_enums_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _array_of_enums_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _array_of_enums_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _array_of_enums_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Array of Enums + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_array_of_enums.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ArrayOfEnums(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def array_of_enums( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def array_of_enums( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def array_of_enums( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def array_of_enums( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def array_of_enums( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._array_of_enums_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._array_of_enums_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_array_of_enums/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_array_of_enums/post.pyi new file mode 100644 index 0000000000..ac0fb2920f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_array_of_enums/post.pyi @@ -0,0 +1,321 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.array_of_enums import ArrayOfEnums + +# body param +SchemaForRequestBodyApplicationJson = ArrayOfEnums + + +request_body_array_of_enums = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = ArrayOfEnums + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _array_of_enums_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _array_of_enums_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _array_of_enums_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _array_of_enums_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _array_of_enums_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Array of Enums + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_array_of_enums.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ArrayOfEnums(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def array_of_enums( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def array_of_enums( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def array_of_enums( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def array_of_enums( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def array_of_enums( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._array_of_enums_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._array_of_enums_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_arraymodel/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_arraymodel/__init__.py new file mode 100644 index 0000000000..c90c733063 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_arraymodel/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_refs_arraymodel import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REFS_ARRAYMODEL \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_arraymodel/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_arraymodel/post.py new file mode 100644 index 0000000000..cebbb40e5f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_arraymodel/post.py @@ -0,0 +1,325 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.animal_farm import AnimalFarm + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = AnimalFarm + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = AnimalFarm + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _array_model_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _array_model_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _array_model_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _array_model_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _array_model_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ArrayModel(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def array_model( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def array_model( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def array_model( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def array_model( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def array_model( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._array_model_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._array_model_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_arraymodel/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_arraymodel/post.pyi new file mode 100644 index 0000000000..ed802fd8c6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_arraymodel/post.pyi @@ -0,0 +1,320 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.animal_farm import AnimalFarm + +# body param +SchemaForRequestBodyApplicationJson = AnimalFarm + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = AnimalFarm + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _array_model_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _array_model_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _array_model_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _array_model_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _array_model_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ArrayModel(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def array_model( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def array_model( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def array_model( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def array_model( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def array_model( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._array_model_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._array_model_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_boolean/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_boolean/__init__.py new file mode 100644 index 0000000000..0c4592391c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_boolean/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_refs_boolean import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REFS_BOOLEAN \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_boolean/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_boolean/post.py new file mode 100644 index 0000000000..6eee57e2c6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_boolean/post.py @@ -0,0 +1,323 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = schemas.BoolSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = schemas.BoolSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _boolean_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _boolean_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _boolean_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _boolean_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _boolean_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class Boolean(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def boolean( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def boolean( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def boolean( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def boolean( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def boolean( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._boolean_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._boolean_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_boolean/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_boolean/post.pyi new file mode 100644 index 0000000000..7a975a27bc --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_boolean/post.pyi @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationJson = schemas.BoolSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = schemas.BoolSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _boolean_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _boolean_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _boolean_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _boolean_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _boolean_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class Boolean(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def boolean( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def boolean( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def boolean( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def boolean( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def boolean( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._boolean_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, bool, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._boolean_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_composed_one_of_number_with_validations/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_composed_one_of_number_with_validations/__init__.py new file mode 100644 index 0000000000..0d1296a31b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_composed_one_of_number_with_validations/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_refs_composed_one_of_number_with_validations import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REFS_COMPOSED_ONE_OF_NUMBER_WITH_VALIDATIONS \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_composed_one_of_number_with_validations/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_composed_one_of_number_with_validations/post.py new file mode 100644 index 0000000000..84acaf1702 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_composed_one_of_number_with_validations/post.py @@ -0,0 +1,325 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = ComposedOneOfDifferentTypes + + +request_body_composed_one_of_different_types = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = ComposedOneOfDifferentTypes + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _composed_one_of_different_types_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _composed_one_of_different_types_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _composed_one_of_different_types_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _composed_one_of_different_types_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _composed_one_of_different_types_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_composed_one_of_different_types.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ComposedOneOfDifferentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def composed_one_of_different_types( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def composed_one_of_different_types( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def composed_one_of_different_types( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def composed_one_of_different_types( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def composed_one_of_different_types( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._composed_one_of_different_types_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._composed_one_of_different_types_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_composed_one_of_number_with_validations/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_composed_one_of_number_with_validations/post.pyi new file mode 100644 index 0000000000..30d5f91dba --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_composed_one_of_number_with_validations/post.pyi @@ -0,0 +1,320 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes + +# body param +SchemaForRequestBodyApplicationJson = ComposedOneOfDifferentTypes + + +request_body_composed_one_of_different_types = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = ComposedOneOfDifferentTypes + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _composed_one_of_different_types_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _composed_one_of_different_types_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _composed_one_of_different_types_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _composed_one_of_different_types_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _composed_one_of_different_types_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_composed_one_of_different_types.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ComposedOneOfDifferentTypes(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def composed_one_of_different_types( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def composed_one_of_different_types( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def composed_one_of_different_types( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def composed_one_of_different_types( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def composed_one_of_different_types( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._composed_one_of_different_types_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._composed_one_of_different_types_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_enum/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_enum/__init__.py new file mode 100644 index 0000000000..f383b11507 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_enum/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_refs_enum import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REFS_ENUM \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_enum/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_enum/post.py new file mode 100644 index 0000000000..4b953d0500 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_enum/post.py @@ -0,0 +1,325 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.string_enum import StringEnum + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = StringEnum + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = StringEnum + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _string_enum_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _string_enum_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _string_enum_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _string_enum_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _string_enum_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class StringEnum(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def string_enum( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def string_enum( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def string_enum( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def string_enum( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def string_enum( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._string_enum_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._string_enum_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_enum/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_enum/post.pyi new file mode 100644 index 0000000000..ea4b1fe2ff --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_enum/post.pyi @@ -0,0 +1,320 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.string_enum import StringEnum + +# body param +SchemaForRequestBodyApplicationJson = StringEnum + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = StringEnum + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _string_enum_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _string_enum_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _string_enum_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _string_enum_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _string_enum_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class StringEnum(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def string_enum( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def string_enum( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def string_enum( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def string_enum( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def string_enum( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._string_enum_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._string_enum_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_mammal/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_mammal/__init__.py new file mode 100644 index 0000000000..8714057f41 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_mammal/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_refs_mammal import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REFS_MAMMAL \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_mammal/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_mammal/post.py new file mode 100644 index 0000000000..dfeb527472 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_mammal/post.py @@ -0,0 +1,328 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.mammal import Mammal + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Mammal + + +request_body_mammal = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationJson = Mammal + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_mammal.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class Mammal(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._mammal_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._mammal_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_mammal/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_mammal/post.pyi new file mode 100644 index 0000000000..24137e6fa5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_mammal/post.pyi @@ -0,0 +1,323 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.mammal import Mammal + +# body param +SchemaForRequestBodyApplicationJson = Mammal + + +request_body_mammal = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationJson = Mammal + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _mammal_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_mammal.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class Mammal(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def mammal( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._mammal_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._mammal_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_number/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_number/__init__.py new file mode 100644 index 0000000000..7ca1c08dff --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_number/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_refs_number import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REFS_NUMBER \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_number/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_number/post.py new file mode 100644 index 0000000000..ab8e5088e5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_number/post.py @@ -0,0 +1,325 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.number_with_validations import NumberWithValidations + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = NumberWithValidations + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = NumberWithValidations + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _number_with_validations_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _number_with_validations_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _number_with_validations_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _number_with_validations_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _number_with_validations_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class NumberWithValidations(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def number_with_validations( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def number_with_validations( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def number_with_validations( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def number_with_validations( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def number_with_validations( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._number_with_validations_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._number_with_validations_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_number/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_number/post.pyi new file mode 100644 index 0000000000..8fb5defd56 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_number/post.pyi @@ -0,0 +1,320 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.number_with_validations import NumberWithValidations + +# body param +SchemaForRequestBodyApplicationJson = NumberWithValidations + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = NumberWithValidations + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _number_with_validations_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _number_with_validations_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _number_with_validations_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _number_with_validations_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _number_with_validations_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class NumberWithValidations(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def number_with_validations( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def number_with_validations( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def number_with_validations( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def number_with_validations( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def number_with_validations( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._number_with_validations_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._number_with_validations_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_object_model_with_ref_props/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_object_model_with_ref_props/__init__.py new file mode 100644 index 0000000000..75f2332128 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_object_model_with_ref_props/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_refs_object_model_with_ref_props import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REFS_OBJECT_MODEL_WITH_REF_PROPS \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_object_model_with_ref_props/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_object_model_with_ref_props/post.py new file mode 100644 index 0000000000..9df4ea7f15 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_object_model_with_ref_props/post.py @@ -0,0 +1,325 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = ObjectModelWithRefProps + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = ObjectModelWithRefProps + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _object_model_with_ref_props_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _object_model_with_ref_props_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _object_model_with_ref_props_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _object_model_with_ref_props_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _object_model_with_ref_props_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ObjectModelWithRefProps(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def object_model_with_ref_props( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def object_model_with_ref_props( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def object_model_with_ref_props( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def object_model_with_ref_props( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def object_model_with_ref_props( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._object_model_with_ref_props_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._object_model_with_ref_props_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_object_model_with_ref_props/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_object_model_with_ref_props/post.pyi new file mode 100644 index 0000000000..7ad3021226 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_object_model_with_ref_props/post.pyi @@ -0,0 +1,320 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps + +# body param +SchemaForRequestBodyApplicationJson = ObjectModelWithRefProps + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = ObjectModelWithRefProps + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _object_model_with_ref_props_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _object_model_with_ref_props_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _object_model_with_ref_props_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _object_model_with_ref_props_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _object_model_with_ref_props_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ObjectModelWithRefProps(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def object_model_with_ref_props( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def object_model_with_ref_props( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def object_model_with_ref_props( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def object_model_with_ref_props( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def object_model_with_ref_props( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._object_model_with_ref_props_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._object_model_with_ref_props_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_string/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_string/__init__.py new file mode 100644 index 0000000000..5f3cba3f0c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_string/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_refs_string import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_REFS_STRING \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_string/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_string/post.py new file mode 100644 index 0000000000..6e12c6a77c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_string/post.py @@ -0,0 +1,323 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = schemas.StrSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = schemas.StrSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _string_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _string_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _string_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _string_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _string_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class String(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def string( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def string( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def string( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def string( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def string( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._string_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._string_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_string/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_string/post.pyi new file mode 100644 index 0000000000..0e7d1fb36c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_refs_string/post.pyi @@ -0,0 +1,318 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationJson = schemas.StrSchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, +) +SchemaFor200ResponseBodyApplicationJson = schemas.StrSchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _string_oapg( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _string_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _string_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _string_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _string_oapg( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class String(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def string( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def string( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def string( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def string( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def string( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._string_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/json"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/json', + body: typing.Union[SchemaForRequestBodyApplicationJson, str, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._string_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_response_without_schema/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_response_without_schema/__init__.py new file mode 100644 index 0000000000..52d9f34614 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_response_without_schema/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_response_without_schema import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_RESPONSE_WITHOUT_SCHEMA \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_response_without_schema/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_response_without_schema/get.py new file mode 100644 index 0000000000..f286d0d05a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_response_without_schema/get.py @@ -0,0 +1,231 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + schemas.Unset, + schemas.Unset, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType(), + 'application/xml': api_client.MediaType(), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', + 'application/xml', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _response_without_schema_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _response_without_schema_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _response_without_schema_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _response_without_schema_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + receives a response without schema + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ResponseWithoutSchema(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def response_without_schema( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def response_without_schema( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def response_without_schema( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def response_without_schema( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._response_without_schema_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._response_without_schema_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_response_without_schema/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_response_without_schema/get.pyi new file mode 100644 index 0000000000..e562a50173 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_response_without_schema/get.pyi @@ -0,0 +1,226 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + schemas.Unset, + schemas.Unset, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType(), + 'application/xml': api_client.MediaType(), + }, +) +_all_accept_content_types = ( + 'application/json', + 'application/xml', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _response_without_schema_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _response_without_schema_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _response_without_schema_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _response_without_schema_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + receives a response without schema + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class ResponseWithoutSchema(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def response_without_schema( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def response_without_schema( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def response_without_schema( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def response_without_schema( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._response_without_schema_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._response_without_schema_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_test_query_paramters/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_test_query_paramters/__init__.py new file mode 100644 index 0000000000..ada9798153 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_test_query_paramters/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_test_query_paramters import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_TESTQUERYPARAMTERS \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_test_query_paramters/put.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_test_query_paramters/put.py new file mode 100644 index 0000000000..760ceea2ce --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_test_query_paramters/put.py @@ -0,0 +1,412 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.string_with_validation import StringWithValidation + +from . import path + +# Query params + + +class PipeSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'PipeSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class IoutilSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'IoutilSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class HttpSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'HttpSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class UrlSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'UrlSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class ContextSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ContextSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) +RefParamSchema = StringWithValidation +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'pipe': typing.Union[PipeSchema, list, tuple, ], + 'ioutil': typing.Union[IoutilSchema, list, tuple, ], + 'http': typing.Union[HttpSchema, list, tuple, ], + 'url': typing.Union[UrlSchema, list, tuple, ], + 'context': typing.Union[ContextSchema, list, tuple, ], + 'refParam': typing.Union[RefParamSchema, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_pipe = api_client.QueryParameter( + name="pipe", + style=api_client.ParameterStyle.FORM, + schema=PipeSchema, + required=True, + explode=True, +) +request_query_ioutil = api_client.QueryParameter( + name="ioutil", + style=api_client.ParameterStyle.FORM, + schema=IoutilSchema, + required=True, +) +request_query_http = api_client.QueryParameter( + name="http", + style=api_client.ParameterStyle.SPACE_DELIMITED, + schema=HttpSchema, + required=True, +) +request_query_url = api_client.QueryParameter( + name="url", + style=api_client.ParameterStyle.FORM, + schema=UrlSchema, + required=True, +) +request_query_context = api_client.QueryParameter( + name="context", + style=api_client.ParameterStyle.FORM, + schema=ContextSchema, + required=True, + explode=True, +) +request_query_ref_param = api_client.QueryParameter( + name="refParam", + style=api_client.ParameterStyle.FORM, + schema=RefParamSchema, + required=True, + explode=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) +_status_code_to_response = { + '200': _response_for_200, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _query_parameter_collection_format_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _query_parameter_collection_format_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _query_parameter_collection_format_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _query_parameter_collection_format_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_pipe, + request_query_ioutil, + request_query_http, + request_query_url, + request_query_context, + request_query_ref_param, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class QueryParameterCollectionFormat(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def query_parameter_collection_format( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def query_parameter_collection_format( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def query_parameter_collection_format( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def query_parameter_collection_format( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._query_parameter_collection_format_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._query_parameter_collection_format_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_test_query_paramters/put.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_test_query_paramters/put.pyi new file mode 100644 index 0000000000..7923932d13 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_test_query_paramters/put.pyi @@ -0,0 +1,407 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.string_with_validation import StringWithValidation + +# Query params + + +class PipeSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'PipeSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class IoutilSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'IoutilSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class HttpSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'HttpSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class UrlSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'UrlSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + + +class ContextSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'ContextSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) +RefParamSchema = StringWithValidation +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'pipe': typing.Union[PipeSchema, list, tuple, ], + 'ioutil': typing.Union[IoutilSchema, list, tuple, ], + 'http': typing.Union[HttpSchema, list, tuple, ], + 'url': typing.Union[UrlSchema, list, tuple, ], + 'context': typing.Union[ContextSchema, list, tuple, ], + 'refParam': typing.Union[RefParamSchema, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_pipe = api_client.QueryParameter( + name="pipe", + style=api_client.ParameterStyle.FORM, + schema=PipeSchema, + required=True, + explode=True, +) +request_query_ioutil = api_client.QueryParameter( + name="ioutil", + style=api_client.ParameterStyle.FORM, + schema=IoutilSchema, + required=True, +) +request_query_http = api_client.QueryParameter( + name="http", + style=api_client.ParameterStyle.SPACE_DELIMITED, + schema=HttpSchema, + required=True, +) +request_query_url = api_client.QueryParameter( + name="url", + style=api_client.ParameterStyle.FORM, + schema=UrlSchema, + required=True, +) +request_query_context = api_client.QueryParameter( + name="context", + style=api_client.ParameterStyle.FORM, + schema=ContextSchema, + required=True, + explode=True, +) +request_query_ref_param = api_client.QueryParameter( + name="refParam", + style=api_client.ParameterStyle.FORM, + schema=RefParamSchema, + required=True, + explode=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _query_parameter_collection_format_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _query_parameter_collection_format_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _query_parameter_collection_format_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _query_parameter_collection_format_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_pipe, + request_query_ioutil, + request_query_http, + request_query_url, + request_query_context, + request_query_ref_param, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class QueryParameterCollectionFormat(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def query_parameter_collection_format( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def query_parameter_collection_format( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def query_parameter_collection_format( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def query_parameter_collection_format( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._query_parameter_collection_format_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._query_parameter_collection_format_oapg( + query_params=query_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_download_file/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_download_file/__init__.py new file mode 100644 index 0000000000..b7321672f1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_download_file/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_upload_download_file import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_UPLOAD_DOWNLOAD_FILE \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_download_file/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_download_file/post.py new file mode 100644 index 0000000000..9686e6ede5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_download_file/post.py @@ -0,0 +1,327 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# body param +SchemaForRequestBodyApplicationOctetStream = schemas.BinarySchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/octet-stream': api_client.MediaType( + schema=SchemaForRequestBodyApplicationOctetStream), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationOctetStream = schemas.BinarySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationOctetStream, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/octet-stream': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationOctetStream), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/octet-stream', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/octet-stream"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/octet-stream', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads a file and downloads a file using application/octet-stream + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadDownloadFile(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/octet-stream"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/octet-stream', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_download_file_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/octet-stream"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/octet-stream', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_download_file_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_download_file/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_download_file/post.pyi new file mode 100644 index 0000000000..a6086fbd0d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_download_file/post.pyi @@ -0,0 +1,322 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# body param +SchemaForRequestBodyApplicationOctetStream = schemas.BinarySchema + + +request_body_body = api_client.RequestBody( + content={ + 'application/octet-stream': api_client.MediaType( + schema=SchemaForRequestBodyApplicationOctetStream), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationOctetStream = schemas.BinarySchema + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationOctetStream, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/octet-stream': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationOctetStream), + }, +) +_all_accept_content_types = ( + 'application/octet-stream', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/octet-stream"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_download_file_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/octet-stream', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads a file and downloads a file using application/octet-stream + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadDownloadFile(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/octet-stream"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_download_file( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/octet-stream', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_download_file_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: typing_extensions.Literal["application/octet-stream"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationOctetStream,bytes, io.FileIO, io.BufferedReader, ], + content_type: str = 'application/octet-stream', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_download_file_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_file/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_file/__init__.py new file mode 100644 index 0000000000..3f4bf5709f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_file/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_upload_file import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_UPLOAD_FILE \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_file/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_file/post.py new file mode 100644 index 0000000000..867654e95f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_file/post.py @@ -0,0 +1,390 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.api_response import ApiResponse + +from . import path + +# body param + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + required = { + "file", + } + + class properties: + additionalMetadata = schemas.StrSchema + file = schemas.BinarySchema + __annotations__ = { + "additionalMetadata": additionalMetadata, + "file": file, + } + + file: MetaOapg.properties.file + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["additionalMetadata"]) -> MetaOapg.properties.additionalMetadata: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["file"]) -> MetaOapg.properties.file: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "file", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["additionalMetadata"]) -> typing.Union[MetaOapg.properties.additionalMetadata, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["file"]) -> MetaOapg.properties.file: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "file", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + file: typing.Union[MetaOapg.properties.file, bytes, io.FileIO, io.BufferedReader, ], + additionalMetadata: typing.Union[MetaOapg.properties.additionalMetadata, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + file=file, + additionalMetadata=additionalMetadata, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) +SchemaFor200ResponseBodyApplicationJson = ApiResponse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_file_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_file_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_file_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_file_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_file_oapg( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads a file using multipart/form-data + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadFile(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_file( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_file( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_file( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_file( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_file( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_file_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_file_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_file/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_file/post.pyi new file mode 100644 index 0000000000..c77969fbf7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_file/post.pyi @@ -0,0 +1,385 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.api_response import ApiResponse + +# body param + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + required = { + "file", + } + + class properties: + additionalMetadata = schemas.StrSchema + file = schemas.BinarySchema + __annotations__ = { + "additionalMetadata": additionalMetadata, + "file": file, + } + + file: MetaOapg.properties.file + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["additionalMetadata"]) -> MetaOapg.properties.additionalMetadata: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["file"]) -> MetaOapg.properties.file: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "file", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["additionalMetadata"]) -> typing.Union[MetaOapg.properties.additionalMetadata, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["file"]) -> MetaOapg.properties.file: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "file", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + file: typing.Union[MetaOapg.properties.file, bytes, io.FileIO, io.BufferedReader, ], + additionalMetadata: typing.Union[MetaOapg.properties.additionalMetadata, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + file=file, + additionalMetadata=additionalMetadata, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) +SchemaFor200ResponseBodyApplicationJson = ApiResponse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_file_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_file_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_file_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_file_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_file_oapg( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads a file using multipart/form-data + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadFile(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_file( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_file( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_file( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_file( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_file( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_file_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_file_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_files/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_files/__init__.py new file mode 100644 index 0000000000..20c593a329 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_files/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.fake_upload_files import Api + +from petstore_api.paths import PathValues + +path = PathValues.FAKE_UPLOAD_FILES \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_files/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_files/post.py new file mode 100644 index 0000000000..4284b0119c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_files/post.py @@ -0,0 +1,397 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.api_response import ApiResponse + +from . import path + +# body param + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class files( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.BinarySchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'files': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "files": files, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["files"]) -> MetaOapg.properties.files: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["files", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["files"]) -> typing.Union[MetaOapg.properties.files, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["files", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + files: typing.Union[MetaOapg.properties.files, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + files=files, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) +SchemaFor200ResponseBodyApplicationJson = ApiResponse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_files_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_files_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_files_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_files_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_files_oapg( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads files using multipart/form-data + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadFiles(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_files( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_files( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_files( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_files( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_files( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_files_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_files_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_files/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_files/post.pyi new file mode 100644 index 0000000000..2b1e1f508f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/fake_upload_files/post.pyi @@ -0,0 +1,392 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.api_response import ApiResponse + +# body param + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + + class files( + schemas.ListSchema + ): + + + class MetaOapg: + items = schemas.BinarySchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, bytes, io.FileIO, io.BufferedReader, ]], typing.List[typing.Union[MetaOapg.items, bytes, io.FileIO, io.BufferedReader, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'files': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) + __annotations__ = { + "files": files, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["files"]) -> MetaOapg.properties.files: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["files", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["files"]) -> typing.Union[MetaOapg.properties.files, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["files", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + files: typing.Union[MetaOapg.properties.files, list, tuple, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + files=files, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) +SchemaFor200ResponseBodyApplicationJson = ApiResponse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_files_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_files_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_files_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_files_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_files_oapg( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads files using multipart/form-data + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadFiles(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_files( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_files( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_files( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_files( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_files( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_files_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_files_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/foo/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/foo/__init__.py new file mode 100644 index 0000000000..e7bea652ad --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/foo/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.foo import Api + +from petstore_api.paths import PathValues + +path = PathValues.FOO \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/foo/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/foo/get.py new file mode 100644 index 0000000000..bde734e758 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/foo/get.py @@ -0,0 +1,287 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.foo import Foo + +from . import path + + + +class SchemaFor0ResponseBodyApplicationJson( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + @staticmethod + def string() -> typing.Type['Foo']: + return Foo + __annotations__ = { + "string": string, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["string"]) -> 'Foo': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["string", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["string"]) -> typing.Union['Foo', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["string", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + string: typing.Union['Foo', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor0ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + string=string, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor0ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor0ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + 'default': _response_for_default, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _foo_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _foo_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _foo_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _foo_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class FooGet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def foo_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def foo_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def foo_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def foo_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._foo_get_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._foo_get_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/foo/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/foo/get.pyi new file mode 100644 index 0000000000..4c5f088f78 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/foo/get.pyi @@ -0,0 +1,282 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.foo import Foo + + + +class SchemaFor0ResponseBodyApplicationJson( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + + @staticmethod + def string() -> typing.Type['Foo']: + return Foo + __annotations__ = { + "string": string, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["string"]) -> 'Foo': ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["string", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["string"]) -> typing.Union['Foo', schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["string", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + string: typing.Union['Foo', schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaFor0ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + string=string, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor0ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor0ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _foo_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _foo_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _foo_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _foo_get_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class FooGet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def foo_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def foo_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def foo_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def foo_get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._foo_get_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._foo_get_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/__init__.py new file mode 100644 index 0000000000..a52ddaccdb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.pet import Api + +from petstore_api.paths import PathValues + +path = PathValues.PET \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/post.py new file mode 100644 index 0000000000..eab76eab72 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/post.py @@ -0,0 +1,389 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Pet +SchemaForRequestBodyApplicationXml = Pet + + +request_body_pet = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + 'application/xml': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXml), + }, + required=True, +) +_auth = [ + 'http_signature_test', + 'petstore_auth', +] +_servers = ( + { + 'url': "https://petstore.swagger.io/v2", + 'description': "No description provided", + }, + { + 'url': "https://path-server-test.petstore.local/v2", + 'description': "No description provided", + }, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseFor405(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_405 = api_client.OpenApiResponse( + response_cls=ApiResponseFor405, +) +_status_code_to_response = { + '200': _response_for_200, + '405': _response_for_405, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Add a new pet to the store + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_pet.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + host = self._get_host_oapg('add_pet', _servers, host_index) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + host=host, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class AddPet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._add_pet_oapg( + body=body, + content_type=content_type, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._add_pet_oapg( + body=body, + content_type=content_type, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/post.pyi new file mode 100644 index 0000000000..844a49f709 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/post.pyi @@ -0,0 +1,369 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +# body param +SchemaForRequestBodyApplicationJson = Pet +SchemaForRequestBodyApplicationXml = Pet + + +request_body_pet = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + 'application/xml': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXml), + }, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseFor405(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_405 = api_client.OpenApiResponse( + response_cls=ApiResponseFor405, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _add_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Add a new pet to the store + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_pet.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + host = self._get_host_oapg('add_pet', _servers, host_index) + + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + host=host, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class AddPet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def add_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._add_pet_oapg( + body=body, + content_type=content_type, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._add_pet_oapg( + body=body, + content_type=content_type, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet/put.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/put.py new file mode 100644 index 0000000000..455320b56c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/put.py @@ -0,0 +1,372 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Pet +SchemaForRequestBodyApplicationXml = Pet + + +request_body_pet = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + 'application/xml': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXml), + }, + required=True, +) +_auth = [ + 'http_signature_test', + 'petstore_auth', +] +_servers = ( + { + 'url': "https://petstore.swagger.io/v2", + 'description': "No description provided", + }, + { + 'url': "https://path-server-test.petstore.local/v2", + 'description': "No description provided", + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) + + +@dataclass +class ApiResponseFor405(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_405 = api_client.OpenApiResponse( + response_cls=ApiResponseFor405, +) +_status_code_to_response = { + '400': _response_for_400, + '404': _response_for_404, + '405': _response_for_405, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Update an existing pet + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_pet.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + host = self._get_host_oapg('update_pet', _servers, host_index) + + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + host=host, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UpdatePet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_pet_oapg( + body=body, + content_type=content_type, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_pet_oapg( + body=body, + content_type=content_type, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet/put.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/put.pyi new file mode 100644 index 0000000000..925cf09510 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet/put.pyi @@ -0,0 +1,351 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +# body param +SchemaForRequestBodyApplicationJson = Pet +SchemaForRequestBodyApplicationXml = Pet + + +request_body_pet = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + 'application/xml': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXml), + }, + required=True, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) + + +@dataclass +class ApiResponseFor405(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_405 = api_client.OpenApiResponse( + response_cls=ApiResponseFor405, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _update_pet_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Update an existing pet + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_pet.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + host = self._get_host_oapg('update_pet', _servers, host_index) + + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + host=host, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UpdatePet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def update_pet( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_pet_oapg( + body=body, + content_type=content_type, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationXml,], + content_type: typing_extensions.Literal["application/xml"], + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = ..., + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,SchemaForRequestBodyApplicationXml,], + content_type: str = 'application/json', + host_index: typing.Optional[int] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_pet_oapg( + body=body, + content_type=content_type, + host_index=host_index, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_status/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_status/__init__.py new file mode 100644 index 0000000000..f0f9ca9ac2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_status/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.pet_find_by_status import Api + +from petstore_api.paths import PathValues + +path = PathValues.PET_FIND_BY_STATUS \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_status/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_status/get.py new file mode 100644 index 0000000000..bca423ad68 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_status/get.py @@ -0,0 +1,406 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +from . import path + +# Query params + + +class StatusSchema( + schemas.ListSchema +): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + + class MetaOapg: + enum_value_to_name = { + "available": "AVAILABLE", + "pending": "PENDING", + "sold": "SOLD", + } + + @schemas.classproperty + def AVAILABLE(cls): + return cls("available") + + @schemas.classproperty + def PENDING(cls): + return cls("pending") + + @schemas.classproperty + def SOLD(cls): + return cls("sold") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'StatusSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'status': typing.Union[StatusSchema, list, tuple, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_status = api_client.QueryParameter( + name="status", + style=api_client.ParameterStyle.FORM, + schema=StatusSchema, + required=True, +) +_auth = [ + 'http_signature_test', + 'petstore_auth', +] + + +class SchemaFor200ResponseBodyApplicationXml( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Pet']: + return Pet + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Pet'], typing.List['Pet']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaFor200ResponseBodyApplicationXml': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Pet': + return super().__getitem__(i) + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Pet']: + return Pet + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Pet'], typing.List['Pet']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Pet': + return super().__getitem__(i) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) +_status_code_to_response = { + '200': _response_for_200, + '400': _response_for_400, +} +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _find_pets_by_status_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _find_pets_by_status_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _find_pets_by_status_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _find_pets_by_status_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Finds Pets by status + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_status, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class FindPetsByStatus(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def find_pets_by_status( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def find_pets_by_status( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def find_pets_by_status( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def find_pets_by_status( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._find_pets_by_status_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._find_pets_by_status_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_status/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_status/get.pyi new file mode 100644 index 0000000000..e19a803673 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_status/get.pyi @@ -0,0 +1,388 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +# Query params + + +class StatusSchema( + schemas.ListSchema +): + + + class MetaOapg: + + + class items( + schemas.EnumBase, + schemas.StrSchema + ): + + @schemas.classproperty + def AVAILABLE(cls): + return cls("available") + + @schemas.classproperty + def PENDING(cls): + return cls("pending") + + @schemas.classproperty + def SOLD(cls): + return cls("sold") + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'StatusSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'status': typing.Union[StatusSchema, list, tuple, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_status = api_client.QueryParameter( + name="status", + style=api_client.ParameterStyle.FORM, + schema=StatusSchema, + required=True, +) + + +class SchemaFor200ResponseBodyApplicationXml( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Pet']: + return Pet + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Pet'], typing.List['Pet']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaFor200ResponseBodyApplicationXml': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Pet': + return super().__getitem__(i) + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Pet']: + return Pet + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Pet'], typing.List['Pet']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Pet': + return super().__getitem__(i) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _find_pets_by_status_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _find_pets_by_status_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _find_pets_by_status_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _find_pets_by_status_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Finds Pets by status + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_status, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class FindPetsByStatus(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def find_pets_by_status( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def find_pets_by_status( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def find_pets_by_status( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def find_pets_by_status( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._find_pets_by_status_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._find_pets_by_status_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_tags/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_tags/__init__.py new file mode 100644 index 0000000000..55063b645e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_tags/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.pet_find_by_tags import Api + +from petstore_api.paths import PathValues + +path = PathValues.PET_FIND_BY_TAGS \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_tags/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_tags/get.py new file mode 100644 index 0000000000..982aeb15c2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_tags/get.py @@ -0,0 +1,381 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +from . import path + +# Query params + + +class TagsSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'TagsSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'tags': typing.Union[TagsSchema, list, tuple, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_tags = api_client.QueryParameter( + name="tags", + style=api_client.ParameterStyle.FORM, + schema=TagsSchema, + required=True, +) +_auth = [ + 'http_signature_test', + 'petstore_auth', +] + + +class SchemaFor200ResponseBodyApplicationXml( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Pet']: + return Pet + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Pet'], typing.List['Pet']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaFor200ResponseBodyApplicationXml': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Pet': + return super().__getitem__(i) + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Pet']: + return Pet + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Pet'], typing.List['Pet']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Pet': + return super().__getitem__(i) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) +_status_code_to_response = { + '200': _response_for_200, + '400': _response_for_400, +} +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _find_pets_by_tags_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _find_pets_by_tags_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _find_pets_by_tags_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _find_pets_by_tags_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Finds Pets by tags + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_tags, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class FindPetsByTags(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def find_pets_by_tags( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def find_pets_by_tags( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def find_pets_by_tags( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def find_pets_by_tags( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._find_pets_by_tags_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._find_pets_by_tags_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_tags/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_tags/get.pyi new file mode 100644 index 0000000000..c48153b2ff --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_find_by_tags/get.pyi @@ -0,0 +1,371 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +# Query params + + +class TagsSchema( + schemas.ListSchema +): + + + class MetaOapg: + items = schemas.StrSchema + + def __new__( + cls, + arg: typing.Union[typing.Tuple[typing.Union[MetaOapg.items, str, ]], typing.List[typing.Union[MetaOapg.items, str, ]]], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'TagsSchema': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> MetaOapg.items: + return super().__getitem__(i) +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'tags': typing.Union[TagsSchema, list, tuple, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_tags = api_client.QueryParameter( + name="tags", + style=api_client.ParameterStyle.FORM, + schema=TagsSchema, + required=True, +) + + +class SchemaFor200ResponseBodyApplicationXml( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Pet']: + return Pet + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Pet'], typing.List['Pet']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaFor200ResponseBodyApplicationXml': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Pet': + return super().__getitem__(i) + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['Pet']: + return Pet + + def __new__( + cls, + arg: typing.Union[typing.Tuple['Pet'], typing.List['Pet']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'Pet': + return super().__getitem__(i) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _find_pets_by_tags_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _find_pets_by_tags_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _find_pets_by_tags_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _find_pets_by_tags_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Finds Pets by tags + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_tags, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class FindPetsByTags(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def find_pets_by_tags( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def find_pets_by_tags( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def find_pets_by_tags( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def find_pets_by_tags( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._find_pets_by_tags_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._find_pets_by_tags_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/__init__.py new file mode 100644 index 0000000000..b165f84146 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.pet_pet_id import Api + +from petstore_api.paths import PathValues + +path = PathValues.PET_PET_ID \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/delete.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/delete.py new file mode 100644 index 0000000000..ae048dfccc --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/delete.py @@ -0,0 +1,297 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Header params +ApiKeySchema = schemas.StrSchema +RequestRequiredHeaderParams = typing_extensions.TypedDict( + 'RequestRequiredHeaderParams', + { + } +) +RequestOptionalHeaderParams = typing_extensions.TypedDict( + 'RequestOptionalHeaderParams', + { + 'api_key': typing.Union[ApiKeySchema, str, ], + }, + total=False +) + + +class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): + pass + + +request_header_api_key = api_client.HeaderParameter( + name="api_key", + style=api_client.ParameterStyle.SIMPLE, + schema=ApiKeySchema, +) +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) +_auth = [ + 'petstore_auth', +] + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) +_status_code_to_response = { + '400': _response_for_400, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _delete_pet_oapg( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _delete_pet_oapg( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _delete_pet_oapg( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _delete_pet_oapg( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Deletes a pet + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestHeaderParams, header_params) + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + for parameter in ( + request_header_api_key, + ): + parameter_data = header_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _headers.extend(serialized_data) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DeletePet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def delete_pet( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def delete_pet( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete_pet( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete_pet( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_pet_oapg( + header_params=header_params, + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def delete( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_pet_oapg( + header_params=header_params, + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/delete.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/delete.pyi new file mode 100644 index 0000000000..2a56be3473 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/delete.pyi @@ -0,0 +1,289 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Header params +ApiKeySchema = schemas.StrSchema +RequestRequiredHeaderParams = typing_extensions.TypedDict( + 'RequestRequiredHeaderParams', + { + } +) +RequestOptionalHeaderParams = typing_extensions.TypedDict( + 'RequestOptionalHeaderParams', + { + 'api_key': typing.Union[ApiKeySchema, str, ], + }, + total=False +) + + +class RequestHeaderParams(RequestRequiredHeaderParams, RequestOptionalHeaderParams): + pass + + +request_header_api_key = api_client.HeaderParameter( + name="api_key", + style=api_client.ParameterStyle.SIMPLE, + schema=ApiKeySchema, +) +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _delete_pet_oapg( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _delete_pet_oapg( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _delete_pet_oapg( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _delete_pet_oapg( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Deletes a pet + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestHeaderParams, header_params) + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + for parameter in ( + request_header_api_key, + ): + parameter_data = header_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _headers.extend(serialized_data) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DeletePet(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def delete_pet( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def delete_pet( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete_pet( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete_pet( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_pet_oapg( + header_params=header_params, + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def delete( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + header_params: RequestHeaderParams = frozendict.frozendict(), + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_pet_oapg( + header_params=header_params, + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/get.py new file mode 100644 index 0000000000..b170ee4485 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/get.py @@ -0,0 +1,321 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +from . import path + +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) +_auth = [ + 'api_key', +] +SchemaFor200ResponseBodyApplicationXml = Pet +SchemaFor200ResponseBodyApplicationJson = Pet + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_status_code_to_response = { + '200': _response_for_200, + '400': _response_for_400, + '404': _response_for_404, +} +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _get_pet_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _get_pet_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _get_pet_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _get_pet_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Find pet by ID + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GetPetById(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def get_pet_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get_pet_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get_pet_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get_pet_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_pet_by_id_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_pet_by_id_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/get.pyi new file mode 100644 index 0000000000..4ed83baee2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/get.pyi @@ -0,0 +1,311 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.pet import Pet + +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) +SchemaFor200ResponseBodyApplicationXml = Pet +SchemaFor200ResponseBodyApplicationJson = Pet + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _get_pet_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _get_pet_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _get_pet_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _get_pet_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Find pet by ID + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GetPetById(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def get_pet_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get_pet_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get_pet_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get_pet_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_pet_by_id_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_pet_by_id_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/post.py new file mode 100644 index 0000000000..101ac83216 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/post.py @@ -0,0 +1,393 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + name = schemas.StrSchema + status = schemas.StrSchema + __annotations__ = { + "name": name, + "status": status, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["status"]) -> MetaOapg.properties.status: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "status", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["status"]) -> typing.Union[MetaOapg.properties.status, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "status", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + name: typing.Union[MetaOapg.properties.name, str, schemas.Unset] = schemas.unset, + status: typing.Union[MetaOapg.properties.status, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': + return super().__new__( + cls, + *args, + name=name, + status=status, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/x-www-form-urlencoded': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), + }, +) +_auth = [ + 'petstore_auth', +] + + +@dataclass +class ApiResponseFor405(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_405 = api_client.OpenApiResponse( + response_cls=ApiResponseFor405, +) +_status_code_to_response = { + '405': _response_for_405, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _update_pet_with_form_oapg( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _update_pet_with_form_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_pet_with_form_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_pet_with_form_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _update_pet_with_form_oapg( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Updates a pet in the store with form data + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UpdatePetWithForm(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def update_pet_with_form( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def update_pet_with_form( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_pet_with_form( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_pet_with_form( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def update_pet_with_form( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_pet_with_form_oapg( + body=body, + path_params=path_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_pet_with_form_oapg( + body=body, + path_params=path_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/post.pyi new file mode 100644 index 0000000000..f2be056a38 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id/post.pyi @@ -0,0 +1,385 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + name = schemas.StrSchema + status = schemas.StrSchema + __annotations__ = { + "name": name, + "status": status, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["name"]) -> MetaOapg.properties.name: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["status"]) -> MetaOapg.properties.status: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["name", "status", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["name"]) -> typing.Union[MetaOapg.properties.name, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["status"]) -> typing.Union[MetaOapg.properties.status, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["name", "status", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + name: typing.Union[MetaOapg.properties.name, str, schemas.Unset] = schemas.unset, + status: typing.Union[MetaOapg.properties.status, str, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyApplicationXWwwFormUrlencoded': + return super().__new__( + cls, + *args, + name=name, + status=status, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'application/x-www-form-urlencoded': api_client.MediaType( + schema=SchemaForRequestBodyApplicationXWwwFormUrlencoded), + }, +) + + +@dataclass +class ApiResponseFor405(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_405 = api_client.OpenApiResponse( + response_cls=ApiResponseFor405, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _update_pet_with_form_oapg( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _update_pet_with_form_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_pet_with_form_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_pet_with_form_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _update_pet_with_form_oapg( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Updates a pet in the store with form data + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UpdatePetWithForm(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def update_pet_with_form( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def update_pet_with_form( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_pet_with_form( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_pet_with_form( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def update_pet_with_form( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_pet_with_form_oapg( + body=body, + path_params=path_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["application/x-www-form-urlencoded"] = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'application/x-www-form-urlencoded', + body: typing.Union[SchemaForRequestBodyApplicationXWwwFormUrlencoded, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_pet_with_form_oapg( + body=body, + path_params=path_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id_upload_image/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id_upload_image/__init__.py new file mode 100644 index 0000000000..6af43e84e1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id_upload_image/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.pet_pet_id_upload_image import Api + +from petstore_api.paths import PathValues + +path = PathValues.PET_PET_ID_UPLOAD_IMAGE \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id_upload_image/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id_upload_image/post.py new file mode 100644 index 0000000000..196f0beccf --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id_upload_image/post.py @@ -0,0 +1,446 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.api_response import ApiResponse + +from . import path + +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) +# body param + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + additionalMetadata = schemas.StrSchema + file = schemas.BinarySchema + __annotations__ = { + "additionalMetadata": additionalMetadata, + "file": file, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["additionalMetadata"]) -> MetaOapg.properties.additionalMetadata: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["file"]) -> MetaOapg.properties.file: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "file", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["additionalMetadata"]) -> typing.Union[MetaOapg.properties.additionalMetadata, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["file"]) -> typing.Union[MetaOapg.properties.file, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "file", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + additionalMetadata: typing.Union[MetaOapg.properties.additionalMetadata, str, schemas.Unset] = schemas.unset, + file: typing.Union[MetaOapg.properties.file, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + additionalMetadata=additionalMetadata, + file=file, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) +_auth = [ + 'petstore_auth', +] +SchemaFor200ResponseBodyApplicationJson = ApiResponse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_image_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_image_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_image_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_image_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_image_oapg( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads an image + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadImage(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_image( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_image( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_image( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_image( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_image( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_image_oapg( + body=body, + path_params=path_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_image_oapg( + body=body, + path_params=path_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id_upload_image/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id_upload_image/post.pyi new file mode 100644 index 0000000000..84c05ddf6e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/pet_pet_id_upload_image/post.pyi @@ -0,0 +1,438 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.api_response import ApiResponse + +# Path params +PetIdSchema = schemas.Int64Schema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'petId': typing.Union[PetIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_pet_id = api_client.PathParameter( + name="petId", + style=api_client.ParameterStyle.SIMPLE, + schema=PetIdSchema, + required=True, +) +# body param + + +class SchemaForRequestBodyMultipartFormData( + schemas.DictSchema +): + + + class MetaOapg: + + class properties: + additionalMetadata = schemas.StrSchema + file = schemas.BinarySchema + __annotations__ = { + "additionalMetadata": additionalMetadata, + "file": file, + } + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["additionalMetadata"]) -> MetaOapg.properties.additionalMetadata: ... + + @typing.overload + def __getitem__(self, name: typing_extensions.Literal["file"]) -> MetaOapg.properties.file: ... + + @typing.overload + def __getitem__(self, name: str) -> schemas.UnsetAnyTypeSchema: ... + + def __getitem__(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "file", ], str]): + # dict_instance[name] accessor + return super().__getitem__(name) + + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["additionalMetadata"]) -> typing.Union[MetaOapg.properties.additionalMetadata, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: typing_extensions.Literal["file"]) -> typing.Union[MetaOapg.properties.file, schemas.Unset]: ... + + @typing.overload + def get_item_oapg(self, name: str) -> typing.Union[schemas.UnsetAnyTypeSchema, schemas.Unset]: ... + + def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["additionalMetadata", "file", ], str]): + return super().get_item_oapg(name) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + additionalMetadata: typing.Union[MetaOapg.properties.additionalMetadata, str, schemas.Unset] = schemas.unset, + file: typing.Union[MetaOapg.properties.file, bytes, io.FileIO, io.BufferedReader, schemas.Unset] = schemas.unset, + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[schemas.AnyTypeSchema, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, None, list, tuple, bytes], + ) -> 'SchemaForRequestBodyMultipartFormData': + return super().__new__( + cls, + *args, + additionalMetadata=additionalMetadata, + file=file, + _configuration=_configuration, + **kwargs, + ) + + +request_body_body = api_client.RequestBody( + content={ + 'multipart/form-data': api_client.MediaType( + schema=SchemaForRequestBodyMultipartFormData), + }, +) +SchemaFor200ResponseBodyApplicationJson = ApiResponse + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _upload_image_oapg( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _upload_image_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _upload_image_oapg( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _upload_image_oapg( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _upload_image_oapg( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + uploads an image + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_pet_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + _fields = None + _body = None + if body is not schemas.unset: + serialized_data = request_body_body.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UploadImage(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def upload_image( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def upload_image( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def upload_image( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def upload_image( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def upload_image( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_image_oapg( + body=body, + path_params=path_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + content_type: typing_extensions.Literal["multipart/form-data"] = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + content_type: str = ..., + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + content_type: str = 'multipart/form-data', + body: typing.Union[SchemaForRequestBodyMultipartFormData, dict, frozendict.frozendict, schemas.Unset] = schemas.unset, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._upload_image_oapg( + body=body, + path_params=path_params, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_inventory/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/store_inventory/__init__.py new file mode 100644 index 0000000000..265c07e7bb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_inventory/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.store_inventory import Api + +from petstore_api.paths import PathValues + +path = PathValues.STORE_INVENTORY \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_inventory/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/store_inventory/get.py new file mode 100644 index 0000000000..4f9f0eb1f7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_inventory/get.py @@ -0,0 +1,262 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +_auth = [ + 'api_key', +] + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.DictSchema +): + + + class MetaOapg: + additional_properties = schemas.Int32Schema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, decimal.Decimal, int, ], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_status_code_to_response = { + '200': _response_for_200, +} +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _get_inventory_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _get_inventory_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _get_inventory_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _get_inventory_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Returns pet inventories by status + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GetInventory(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def get_inventory( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get_inventory( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get_inventory( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get_inventory( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_inventory_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_inventory_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_inventory/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/store_inventory/get.pyi new file mode 100644 index 0000000000..30d769a9d3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_inventory/get.pyi @@ -0,0 +1,254 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + + +class SchemaFor200ResponseBodyApplicationJson( + schemas.DictSchema +): + + + class MetaOapg: + additional_properties = schemas.Int32Schema + + def __getitem__(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + # dict_instance[name] accessor + return super().__getitem__(name) + + def get_item_oapg(self, name: typing.Union[str, ]) -> MetaOapg.additional_properties: + return super().get_item_oapg(name) + + def __new__( + cls, + *args: typing.Union[dict, frozendict.frozendict, ], + _configuration: typing.Optional[schemas.Configuration] = None, + **kwargs: typing.Union[MetaOapg.additional_properties, decimal.Decimal, int, ], + ) -> 'SchemaFor200ResponseBodyApplicationJson': + return super().__new__( + cls, + *args, + _configuration=_configuration, + **kwargs, + ) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) +_all_accept_content_types = ( + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _get_inventory_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _get_inventory_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _get_inventory_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _get_inventory_oapg( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Returns pet inventories by status + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + auth_settings=_auth, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GetInventory(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def get_inventory( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get_inventory( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get_inventory( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get_inventory( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_inventory_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_inventory_oapg( + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_order/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order/__init__.py new file mode 100644 index 0000000000..2cefcb1299 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.store_order import Api + +from petstore_api.paths import PathValues + +path = PathValues.STORE_ORDER \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_order/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order/post.py new file mode 100644 index 0000000000..a92da10efb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order/post.py @@ -0,0 +1,347 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.order import Order + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = Order + + +request_body_order = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationXml = Order +SchemaFor200ResponseBodyApplicationJson = Order + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) +_status_code_to_response = { + '200': _response_for_200, + '400': _response_for_400, +} +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Place an order for a pet + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_order.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PlaceOrder(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._place_order_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._place_order_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_order/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order/post.pyi new file mode 100644 index 0000000000..20ad57939b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order/post.pyi @@ -0,0 +1,341 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.order import Order + +# body param +SchemaForRequestBodyApplicationJson = Order + + +request_body_order = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) +SchemaFor200ResponseBodyApplicationXml = Order +SchemaFor200ResponseBodyApplicationJson = Order + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _place_order_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Place an order for a pet + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_order.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class PlaceOrder(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def place_order( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._place_order_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._place_order_oapg( + body=body, + content_type=content_type, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/__init__.py new file mode 100644 index 0000000000..435dc45124 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.store_order_order_id import Api + +from petstore_api.paths import PathValues + +path = PathValues.STORE_ORDER_ORDER_ID \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/delete.py b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/delete.py new file mode 100644 index 0000000000..65f49c91e4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/delete.py @@ -0,0 +1,254 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Path params +OrderIdSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'order_id': typing.Union[OrderIdSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_order_id = api_client.PathParameter( + name="order_id", + style=api_client.ParameterStyle.SIMPLE, + schema=OrderIdSchema, + required=True, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_status_code_to_response = { + '400': _response_for_400, + '404': _response_for_404, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _delete_order_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _delete_order_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _delete_order_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _delete_order_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Delete purchase order by ID + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_order_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DeleteOrder(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def delete_order( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def delete_order( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete_order( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete_order( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_order_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_order_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/delete.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/delete.pyi new file mode 100644 index 0000000000..74af6d4a61 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/delete.pyi @@ -0,0 +1,248 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Path params +OrderIdSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'order_id': typing.Union[OrderIdSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_order_id = api_client.PathParameter( + name="order_id", + style=api_client.ParameterStyle.SIMPLE, + schema=OrderIdSchema, + required=True, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _delete_order_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _delete_order_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _delete_order_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _delete_order_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Delete purchase order by ID + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_order_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DeleteOrder(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def delete_order( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def delete_order( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete_order( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete_order( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_order_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_order_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/get.py new file mode 100644 index 0000000000..9c920df2a9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/get.py @@ -0,0 +1,327 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.order import Order + +from . import path + +# Path params + + +class OrderIdSchema( + schemas.Int64Schema +): + + + class MetaOapg: + format = 'int64' + inclusive_maximum = 5 + inclusive_minimum = 1 +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'order_id': typing.Union[OrderIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_order_id = api_client.PathParameter( + name="order_id", + style=api_client.ParameterStyle.SIMPLE, + schema=OrderIdSchema, + required=True, +) +SchemaFor200ResponseBodyApplicationXml = Order +SchemaFor200ResponseBodyApplicationJson = Order + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_status_code_to_response = { + '200': _response_for_200, + '400': _response_for_400, + '404': _response_for_404, +} +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _get_order_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _get_order_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _get_order_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _get_order_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Find purchase order by ID + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_order_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GetOrderById(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def get_order_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get_order_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get_order_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get_order_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_order_by_id_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_order_by_id_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/get.pyi new file mode 100644 index 0000000000..a421c4ab4a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/store_order_order_id/get.pyi @@ -0,0 +1,315 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.order import Order + +# Path params + + +class OrderIdSchema( + schemas.Int64Schema +): + pass +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'order_id': typing.Union[OrderIdSchema, decimal.Decimal, int, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_order_id = api_client.PathParameter( + name="order_id", + style=api_client.ParameterStyle.SIMPLE, + schema=OrderIdSchema, + required=True, +) +SchemaFor200ResponseBodyApplicationXml = Order +SchemaFor200ResponseBodyApplicationJson = Order + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _get_order_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _get_order_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _get_order_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _get_order_by_id_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Find purchase order by ID + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_order_id, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GetOrderById(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def get_order_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get_order_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get_order_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get_order_by_id( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_order_by_id_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_order_by_id_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user/__init__.py new file mode 100644 index 0000000000..9cb59c35fb --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.user import Api + +from petstore_api.paths import PathValues + +path = PathValues.USER \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user/post.py new file mode 100644 index 0000000000..08cfcc902c --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user/post.py @@ -0,0 +1,303 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +from . import path + +# body param +SchemaForRequestBodyApplicationJson = User + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) +_status_code_to_response = { + 'default': _response_for_default, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Create user + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CreateUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_user_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_user_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/user/post.pyi new file mode 100644 index 0000000000..df85a246c2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user/post.pyi @@ -0,0 +1,298 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +# body param +SchemaForRequestBodyApplicationJson = User + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _create_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Create user + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CreateUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def create_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_user_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_user_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_array/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_array/__init__.py new file mode 100644 index 0000000000..984db1ea2b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_array/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.user_create_with_array import Api + +from petstore_api.paths import PathValues + +path = PathValues.USER_CREATE_WITH_ARRAY \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_array/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_array/post.py new file mode 100644 index 0000000000..d596822b47 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_array/post.py @@ -0,0 +1,328 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['User']: + return User + + def __new__( + cls, + arg: typing.Union[typing.Tuple['User'], typing.List['User']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'User': + return super().__getitem__(i) + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) +_status_code_to_response = { + 'default': _response_for_default, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Creates list of users with given input array + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CreateUsersWithArrayInput(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_users_with_array_input_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_users_with_array_input_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_array/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_array/post.pyi new file mode 100644 index 0000000000..6c83bb4f8b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_array/post.pyi @@ -0,0 +1,323 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['User']: + return User + + def __new__( + cls, + arg: typing.Union[typing.Tuple['User'], typing.List['User']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'User': + return super().__getitem__(i) + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _create_users_with_array_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Creates list of users with given input array + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CreateUsersWithArrayInput(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def create_users_with_array_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_users_with_array_input_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_users_with_array_input_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_list/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_list/__init__.py new file mode 100644 index 0000000000..3930d4bbca --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_list/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.user_create_with_list import Api + +from petstore_api.paths import PathValues + +path = PathValues.USER_CREATE_WITH_LIST \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_list/post.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_list/post.py new file mode 100644 index 0000000000..fd0fe46f1b --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_list/post.py @@ -0,0 +1,328 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +from . import path + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['User']: + return User + + def __new__( + cls, + arg: typing.Union[typing.Tuple['User'], typing.List['User']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'User': + return super().__getitem__(i) + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) +_status_code_to_response = { + 'default': _response_for_default, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Creates list of users with given input array + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CreateUsersWithListInput(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_users_with_list_input_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_users_with_list_input_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_list/post.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_list/post.pyi new file mode 100644 index 0000000000..ef9c94f622 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_create_with_list/post.pyi @@ -0,0 +1,323 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +# body param + + +class SchemaForRequestBodyApplicationJson( + schemas.ListSchema +): + + + class MetaOapg: + + @staticmethod + def items() -> typing.Type['User']: + return User + + def __new__( + cls, + arg: typing.Union[typing.Tuple['User'], typing.List['User']], + _configuration: typing.Optional[schemas.Configuration] = None, + ) -> 'SchemaForRequestBodyApplicationJson': + return super().__new__( + cls, + arg, + _configuration=_configuration, + ) + + def __getitem__(self, i: int) -> 'User': + return super().__getitem__(i) + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _create_users_with_list_input_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Creates list of users with given input array + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='post'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class CreateUsersWithListInput(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def create_users_with_list_input( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_users_with_list_input_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForpost(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: typing_extensions.Literal["application/json"] = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = ..., + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def post( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,list, tuple, ], + content_type: str = 'application/json', + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._create_users_with_list_input_oapg( + body=body, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_login/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_login/__init__.py new file mode 100644 index 0000000000..7dbf363c10 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_login/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.user_login import Api + +from petstore_api.paths import PathValues + +path = PathValues.USER_LOGIN \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_login/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_login/get.py new file mode 100644 index 0000000000..acbe1ccb1d --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_login/get.py @@ -0,0 +1,336 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Query params +UsernameSchema = schemas.StrSchema +PasswordSchema = schemas.StrSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'username': typing.Union[UsernameSchema, str, ], + 'password': typing.Union[PasswordSchema, str, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_username = api_client.QueryParameter( + name="username", + style=api_client.ParameterStyle.FORM, + schema=UsernameSchema, + required=True, + explode=True, +) +request_query_password = api_client.QueryParameter( + name="password", + style=api_client.ParameterStyle.FORM, + schema=PasswordSchema, + required=True, + explode=True, +) +XRateLimitSchema = schemas.Int32Schema +x_rate_limit_parameter = api_client.HeaderParameter( + name="X-Rate-Limit", + style=api_client.ParameterStyle.SIMPLE, + schema=XRateLimitSchema, +) +XExpiresAfterSchema = schemas.DateTimeSchema +x_expires_after_parameter = api_client.HeaderParameter( + name="X-Expires-After", + style=api_client.ParameterStyle.SIMPLE, + schema=XExpiresAfterSchema, +) +SchemaFor200ResponseBodyApplicationXml = schemas.StrSchema +SchemaFor200ResponseBodyApplicationJson = schemas.StrSchema +ResponseHeadersFor200 = typing_extensions.TypedDict( + 'ResponseHeadersFor200', + { + 'X-Rate-Limit': XRateLimitSchema, + 'X-Expires-After': XExpiresAfterSchema, + } +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: ResponseHeadersFor200 + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, + headers=[ + x_rate_limit_parameter, + x_expires_after_parameter, + ] +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) +_status_code_to_response = { + '200': _response_for_200, + '400': _response_for_400, +} +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _login_user_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _login_user_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _login_user_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _login_user_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Logs user into the system + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_username, + request_query_password, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class LoginUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def login_user( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def login_user( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def login_user( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def login_user( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._login_user_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._login_user_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_login/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/user_login/get.pyi new file mode 100644 index 0000000000..651fb8afc4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_login/get.pyi @@ -0,0 +1,320 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Query params +UsernameSchema = schemas.StrSchema +PasswordSchema = schemas.StrSchema +RequestRequiredQueryParams = typing_extensions.TypedDict( + 'RequestRequiredQueryParams', + { + 'username': typing.Union[UsernameSchema, str, ], + 'password': typing.Union[PasswordSchema, str, ], + } +) +RequestOptionalQueryParams = typing_extensions.TypedDict( + 'RequestOptionalQueryParams', + { + }, + total=False +) + + +class RequestQueryParams(RequestRequiredQueryParams, RequestOptionalQueryParams): + pass + + +request_query_username = api_client.QueryParameter( + name="username", + style=api_client.ParameterStyle.FORM, + schema=UsernameSchema, + required=True, + explode=True, +) +request_query_password = api_client.QueryParameter( + name="password", + style=api_client.ParameterStyle.FORM, + schema=PasswordSchema, + required=True, + explode=True, +) +XRateLimitSchema = schemas.Int32Schema +XExpiresAfterSchema = schemas.DateTimeSchema +SchemaFor200ResponseBodyApplicationXml = schemas.StrSchema +SchemaFor200ResponseBodyApplicationJson = schemas.StrSchema +ResponseHeadersFor200 = typing_extensions.TypedDict( + 'ResponseHeadersFor200', + { + 'X-Rate-Limit': XRateLimitSchema, + 'X-Expires-After': XExpiresAfterSchema, + } +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: ResponseHeadersFor200 + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, + headers=[ + x_rate_limit_parameter, + x_expires_after_parameter, + ] +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _login_user_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _login_user_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _login_user_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _login_user_oapg( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Logs user into the system + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestQueryParams, query_params) + used_path = path.value + + prefix_separator_iterator = None + for parameter in ( + request_query_username, + request_query_password, + ): + parameter_data = query_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + if prefix_separator_iterator is None: + prefix_separator_iterator = parameter.get_prefix_separator_iterator() + serialized_data = parameter.serialize(parameter_data, prefix_separator_iterator) + for serialized_value in serialized_data.values(): + used_path += serialized_value + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class LoginUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def login_user( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def login_user( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def login_user( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def login_user( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._login_user_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + query_params: RequestQueryParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._login_user_oapg( + query_params=query_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_logout/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_logout/__init__.py new file mode 100644 index 0000000000..625c23c6d0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_logout/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.user_logout import Api + +from petstore_api.paths import PathValues + +path = PathValues.USER_LOGOUT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_logout/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_logout/get.py new file mode 100644 index 0000000000..085a4ba675 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_logout/get.py @@ -0,0 +1,203 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) +_status_code_to_response = { + 'default': _response_for_default, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _logout_user_oapg( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _logout_user_oapg( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _logout_user_oapg( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _logout_user_oapg( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Logs out current logged in user session + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class LogoutUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def logout_user( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def logout_user( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def logout_user( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def logout_user( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._logout_user_oapg( + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def get( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._logout_user_oapg( + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_logout/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/user_logout/get.pyi new file mode 100644 index 0000000000..52192b6406 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_logout/get.pyi @@ -0,0 +1,198 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + + + +@dataclass +class ApiResponseForDefault(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_default = api_client.OpenApiResponse( + response_cls=ApiResponseForDefault, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _logout_user_oapg( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def _logout_user_oapg( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _logout_user_oapg( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _logout_user_oapg( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Logs out current logged in user session + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + used_path = path.value + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + default_response = _status_code_to_response.get('default') + if default_response: + api_response = default_response.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class LogoutUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def logout_user( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def logout_user( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def logout_user( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def logout_user( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._logout_user_oapg( + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseForDefault, + ]: ... + + @typing.overload + def get( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseForDefault, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._logout_user_oapg( + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/__init__.py new file mode 100644 index 0000000000..c78d37255f --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/__init__.py @@ -0,0 +1,7 @@ +# do not import all endpoints into this module because that uses a lot of memory and stack frames +# if you need the ability to import all endpoints from this module, import them with +# from petstore_api.paths.user_username import Api + +from petstore_api.paths import PathValues + +path = PathValues.USER_USERNAME \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/delete.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/delete.py new file mode 100644 index 0000000000..1fbeabb724 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/delete.py @@ -0,0 +1,266 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from . import path + +# Path params +UsernameSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'username': typing.Union[UsernameSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_username = api_client.PathParameter( + name="username", + style=api_client.ParameterStyle.SIMPLE, + schema=UsernameSchema, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_status_code_to_response = { + '200': _response_for_200, + '404': _response_for_404, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _delete_user_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _delete_user_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _delete_user_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _delete_user_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Delete user + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_username, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DeleteUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def delete_user( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def delete_user( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete_user( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete_user( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_user_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_user_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/delete.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/delete.pyi new file mode 100644 index 0000000000..3bc4ec391e --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/delete.pyi @@ -0,0 +1,260 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +# Path params +UsernameSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'username': typing.Union[UsernameSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_username = api_client.PathParameter( + name="username", + style=api_client.ParameterStyle.SIMPLE, + schema=UsernameSchema, + required=True, +) + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _delete_user_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _delete_user_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _delete_user_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _delete_user_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Delete user + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_username, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=used_path, + method='delete'.upper(), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class DeleteUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def delete_user( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def delete_user( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete_user( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete_user( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_user_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiFordelete(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def delete( + self, + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._delete_user_oapg( + path_params=path_params, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/get.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/get.py new file mode 100644 index 0000000000..a75bc873e1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/get.py @@ -0,0 +1,317 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +from . import path + +# Path params +UsernameSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'username': typing.Union[UsernameSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_username = api_client.PathParameter( + name="username", + style=api_client.ParameterStyle.SIMPLE, + schema=UsernameSchema, + required=True, +) +SchemaFor200ResponseBodyApplicationXml = User +SchemaFor200ResponseBodyApplicationJson = User + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_status_code_to_response = { + '200': _response_for_200, + '400': _response_for_400, + '404': _response_for_404, +} +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _get_user_by_name_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _get_user_by_name_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _get_user_by_name_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _get_user_by_name_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Get user by user name + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_username, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GetUserByName(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def get_user_by_name( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get_user_by_name( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get_user_by_name( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get_user_by_name( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_user_by_name_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_user_by_name_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/get.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/get.pyi new file mode 100644 index 0000000000..60b333602a --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/get.pyi @@ -0,0 +1,310 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +# Path params +UsernameSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'username': typing.Union[UsernameSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_username = api_client.PathParameter( + name="username", + style=api_client.ParameterStyle.SIMPLE, + schema=UsernameSchema, + required=True, +) +SchemaFor200ResponseBodyApplicationXml = User +SchemaFor200ResponseBodyApplicationJson = User + + +@dataclass +class ApiResponseFor200(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: typing.Union[ + SchemaFor200ResponseBodyApplicationXml, + SchemaFor200ResponseBodyApplicationJson, + ] + headers: schemas.Unset = schemas.unset + + +_response_for_200 = api_client.OpenApiResponse( + response_cls=ApiResponseFor200, + content={ + 'application/xml': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationXml), + 'application/json': api_client.MediaType( + schema=SchemaFor200ResponseBodyApplicationJson), + }, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_all_accept_content_types = ( + 'application/xml', + 'application/json', +) + + +class BaseApi(api_client.Api): + @typing.overload + def _get_user_by_name_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def _get_user_by_name_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _get_user_by_name_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _get_user_by_name_oapg( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Get user by user name + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_username, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + if accept_content_types: + for accept_content_type in accept_content_types: + _headers.add('Accept', accept_content_type) + + response = self.api_client.call_api( + resource_path=used_path, + method='get'.upper(), + headers=_headers, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class GetUserByName(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def get_user_by_name( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get_user_by_name( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get_user_by_name( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get_user_by_name( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_user_by_name_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForget(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> typing.Union[ + ApiResponseFor200, + ]: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def get( + self, + path_params: RequestPathParams = frozendict.frozendict(), + accept_content_types: typing.Tuple[str] = _all_accept_content_types, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._get_user_by_name_oapg( + path_params=path_params, + accept_content_types=accept_content_types, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/put.py b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/put.py new file mode 100644 index 0000000000..5a5445aff9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/put.py @@ -0,0 +1,348 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +from . import path + +# Path params +UsernameSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'username': typing.Union[UsernameSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_username = api_client.PathParameter( + name="username", + style=api_client.ParameterStyle.SIMPLE, + schema=UsernameSchema, + required=True, +) +# body param +SchemaForRequestBodyApplicationJson = User + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) +_status_code_to_response = { + '400': _response_for_400, + '404': _response_for_404, +} + + +class BaseApi(api_client.Api): + @typing.overload + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Updated user + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_username, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UpdateUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_user_oapg( + body=body, + path_params=path_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_user_oapg( + body=body, + path_params=path_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/put.pyi b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/put.pyi new file mode 100644 index 0000000000..864e5bfac3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/paths/user_username/put.pyi @@ -0,0 +1,342 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +from dataclasses import dataclass +import typing_extensions +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from datetime import date, datetime # noqa: F401 +import decimal # noqa: F401 +import functools # noqa: F401 +import io # noqa: F401 +import re # noqa: F401 +import typing # noqa: F401 +import typing_extensions # noqa: F401 +import uuid # noqa: F401 + +import frozendict # noqa: F401 + +from petstore_api import schemas # noqa: F401 + +from petstore_api.model.user import User + +# Path params +UsernameSchema = schemas.StrSchema +RequestRequiredPathParams = typing_extensions.TypedDict( + 'RequestRequiredPathParams', + { + 'username': typing.Union[UsernameSchema, str, ], + } +) +RequestOptionalPathParams = typing_extensions.TypedDict( + 'RequestOptionalPathParams', + { + }, + total=False +) + + +class RequestPathParams(RequestRequiredPathParams, RequestOptionalPathParams): + pass + + +request_path_username = api_client.PathParameter( + name="username", + style=api_client.ParameterStyle.SIMPLE, + schema=UsernameSchema, + required=True, +) +# body param +SchemaForRequestBodyApplicationJson = User + + +request_body_user = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType( + schema=SchemaForRequestBodyApplicationJson), + }, + required=True, +) + + +@dataclass +class ApiResponseFor400(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_400 = api_client.OpenApiResponse( + response_cls=ApiResponseFor400, +) + + +@dataclass +class ApiResponseFor404(api_client.ApiResponse): + response: urllib3.HTTPResponse + body: schemas.Unset = schemas.unset + headers: schemas.Unset = schemas.unset + + +_response_for_404 = api_client.OpenApiResponse( + response_cls=ApiResponseFor404, +) + + +class BaseApi(api_client.Api): + @typing.overload + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def _update_user_oapg( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + """ + Updated user + :param skip_deserialization: If true then api_response.response will be set but + api_response.body and api_response.headers will not be deserialized into schema + class instances + """ + self._verify_typed_dict_inputs_oapg(RequestPathParams, path_params) + used_path = path.value + + _path_params = {} + for parameter in ( + request_path_username, + ): + parameter_data = path_params.get(parameter.name, schemas.unset) + if parameter_data is schemas.unset: + continue + serialized_data = parameter.serialize(parameter_data) + _path_params.update(serialized_data) + + for k, v in _path_params.items(): + used_path = used_path.replace('{%s}' % k, v) + + _headers = HTTPHeaderDict() + # TODO add cookie handling + + if body is schemas.unset: + raise exceptions.ApiValueError( + 'The required body parameter has an invalid value of: unset. Set a valid value instead') + _fields = None + _body = None + serialized_data = request_body_user.serialize(body, content_type) + _headers.add('Content-Type', content_type) + if 'fields' in serialized_data: + _fields = serialized_data['fields'] + elif 'body' in serialized_data: + _body = serialized_data['body'] + response = self.api_client.call_api( + resource_path=used_path, + method='put'.upper(), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + else: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + + if not 200 <= response.status <= 299: + raise exceptions.ApiException(api_response=api_response) + + return api_response + + +class UpdateUser(BaseApi): + # this class is used by api classes that refer to endpoints with operationId fn names + + @typing.overload + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def update_user( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_user_oapg( + body=body, + path_params=path_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + +class ApiForput(BaseApi): + # this class is used by api classes that refer to endpoints by path and http method names + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: typing_extensions.Literal["application/json"] = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: typing_extensions.Literal[False] = ..., + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + skip_deserialization: typing_extensions.Literal[True], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> api_client.ApiResponseWithoutDeserialization: ... + + @typing.overload + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = ..., + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = ..., + ) -> typing.Union[ + api_client.ApiResponseWithoutDeserialization, + ]: ... + + def put( + self, + body: typing.Union[SchemaForRequestBodyApplicationJson,], + content_type: str = 'application/json', + path_params: RequestPathParams = frozendict.frozendict(), + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + skip_deserialization: bool = False, + ): + return self._update_user_oapg( + body=body, + path_params=path_params, + content_type=content_type, + stream=stream, + timeout=timeout, + skip_deserialization=skip_deserialization + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/rest.py b/samples/openapi3/client/petstore/python/petstore_api/rest.py index 8ec610c5cc..40e35989f9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python/petstore_api/rest.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,41 +9,21 @@ Generated by: https://openapi-generator.tech """ - -import io -import json import logging -import re import ssl from urllib.parse import urlencode -from urllib.parse import urlparse -from urllib.request import proxy_bypass_environment -import urllib3 -import ipaddress +import typing -from petstore_api.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError +import certifi +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api.exceptions import ApiException, ApiValueError logger = logging.getLogger(__name__) -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.getheader(name, default) - - class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=None): @@ -57,6 +39,13 @@ class RESTClientObject(object): else: cert_reqs = ssl.CERT_NONE + # ca_certs + if configuration.ssl_ca_cert: + ca_certs = configuration.ssl_ca_cert + else: + # if not set certificate file, use Mozilla's root certificates. + ca_certs = certifi.where() + addition_pool_args = {} if configuration.assert_hostname is not None: addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 @@ -74,13 +63,12 @@ class RESTClientObject(object): maxsize = 4 # https pool manager - if configuration.proxy and not should_bypass_proxies( - configuration.host, no_proxy=configuration.no_proxy or ''): + if configuration.proxy: self.pool_manager = urllib3.ProxyManager( num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, + ca_certs=ca_certs, cert_file=configuration.cert_file, key_file=configuration.key_file, proxy_url=configuration.proxy, @@ -92,79 +80,75 @@ class RESTClientObject(object): num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, + ca_certs=ca_certs, cert_file=configuration.cert_file, key_file=configuration.key_file, **addition_pool_args ) - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + def request( + self, + method: str, + url: str, + headers: typing.Optional[HTTPHeaderDict] = None, + fields: typing.Optional[typing.Tuple[typing.Tuple[str, typing.Any], ...]] = None, + body: typing.Optional[typing.Union[str, bytes]] = None, + stream: bool = False, + timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + ) -> urllib3.HTTPResponse: """Perform requests. :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param body: request body, for other types + :param fields: request parameters for + `application/x-www-form-urlencoded` + or `multipart/form-data` + :param stream: if True, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is False. + :param timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] - if post_params and body: + if fields and body: raise ApiValueError( - "body parameter cannot be used with post_params parameter." + "body parameter cannot be used with fields parameter." ) - post_params = post_params or {} + fields = fields or {} headers = headers or {} - timeout = None - if _request_timeout: - if isinstance(_request_timeout, (int, float)): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) + if timeout: + if isinstance(timeout, (int, float)): # noqa: E501,F821 + timeout = urllib3.Timeout(total=timeout) + elif (isinstance(timeout, tuple) and + len(timeout) == 2): + timeout = urllib3.Timeout(connect=timeout[0], read=timeout[1]) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests - if (method != 'DELETE') and ('Content-Type' not in headers): - headers['Content-Type'] = 'application/json' - if query_params: - url += '?' + urlencode(query_params) - if ('Content-Type' not in headers) or (re.search('json', - headers['Content-Type'], re.IGNORECASE)): - request_body = None - if body is not None: - request_body = json.dumps(body) + if 'Content-Type' not in headers and body is None: r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, + method, + url, + preload_content=not stream, timeout=timeout, - headers=headers) + headers=headers + ) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 r = self.pool_manager.request( method, url, - fields=post_params, + fields=fields, encode_multipart=False, - preload_content=_preload_content, + preload_content=not stream, timeout=timeout, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': @@ -174,9 +158,9 @@ class RESTClientObject(object): del headers['Content-Type'] r = self.pool_manager.request( method, url, - fields=post_params, + fields=fields, encode_multipart=True, - preload_content=_preload_content, + preload_content=not stream, timeout=timeout, headers=headers) # Pass a `string` parameter directly in the body to support @@ -187,7 +171,7 @@ class RESTClientObject(object): r = self.pool_manager.request( method, url, body=request_body, - preload_content=_preload_content, + preload_content=not stream, timeout=timeout, headers=headers) else: @@ -199,154 +183,71 @@ class RESTClientObject(object): # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, - fields=query_params, - preload_content=_preload_content, + preload_content=not stream, timeout=timeout, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) - if _preload_content: - r = RESTResponse(r) - + if not stream: # log response body logger.debug("response body: %s", r.data) - if not 200 <= r.status <= 299: - if r.status == 401: - raise UnauthorizedException(http_resp=r) - - if r.status == 403: - raise ForbiddenException(http_resp=r) - - if r.status == 404: - raise NotFoundException(http_resp=r) - - if 500 <= r.status <= 599: - raise ServiceException(http_resp=r) - - raise ApiException(http_resp=r) - return r - def GET(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): + def GET(self, url, headers=None, stream=False, + timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("GET", url, headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) + stream=stream, + timeout=timeout, + fields=fields) - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): + def HEAD(self, url, headers=None, stream=False, + timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("HEAD", url, headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) + stream=stream, + timeout=timeout, + fields=fields) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): + def OPTIONS(self, url, headers=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("OPTIONS", url, headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + stream=stream, + timeout=timeout, + body=body, fields=fields) - def DELETE(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): + def DELETE(self, url, headers=None, body=None, + stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("DELETE", url, headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + stream=stream, + timeout=timeout, + body=body, fields=fields) - def POST(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): + def POST(self, url, headers=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("POST", url, headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + stream=stream, + timeout=timeout, + body=body, fields=fields) - def PUT(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): + def PUT(self, url, headers=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("PUT", url, headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + stream=stream, + timeout=timeout, + body=body, fields=fields) - def PATCH(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): + def PATCH(self, url, headers=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: return self.request("PATCH", url, headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - -# end of class RESTClientObject - - -def is_ipv4(target): - """ Test if IPv4 address or not - """ - try: - chk = ipaddress.IPv4Address(target) - return True - except ipaddress.AddressValueError: - return False - - -def in_ipv4net(target, net): - """ Test if target belongs to given IPv4 network - """ - try: - nw = ipaddress.IPv4Network(net) - ip = ipaddress.IPv4Address(target) - if ip in nw: - return True - return False - except ipaddress.AddressValueError: - return False - except ipaddress.NetmaskValueError: - return False - - -def should_bypass_proxies(url, no_proxy=None): - """ Yet another requests.should_bypass_proxies - Test if proxies should not be used for a particular url. - """ - - parsed = urlparse(url) - - # special cases - if parsed.hostname in [None, '']: - return True - - # special cases - if no_proxy in [None, '']: - return False - if no_proxy == '*': - return True - - no_proxy = no_proxy.lower().replace(' ', ''); - entries = ( - host for host in no_proxy.split(',') if host - ) - - if is_ipv4(parsed.hostname): - for item in entries: - if in_ipv4net(parsed.hostname, item): - return True - return proxy_bypass_environment(parsed.hostname, {'no': no_proxy}) + stream=stream, + timeout=timeout, + body=body, fields=fields) diff --git a/samples/openapi3/client/petstore/python/petstore_api/schemas.py b/samples/openapi3/client/petstore/python/petstore_api/schemas.py new file mode 100644 index 0000000000..18d0e8c4a5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/schemas.py @@ -0,0 +1,2462 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from collections import defaultdict +from datetime import date, datetime, timedelta # noqa: F401 +import functools +import decimal +import io +import re +import types +import typing +import uuid + +from dateutil.parser.isoparser import isoparser, _takes_ascii +import frozendict + +from petstore_api.exceptions import ( + ApiTypeError, + ApiValueError, +) +from petstore_api.configuration import ( + Configuration, +) + + +class Unset(object): + """ + An instance of this class is set as the default value for object type(dict) properties that are optional + When a property has an unset value, that property will not be assigned in the dict + """ + pass + +unset = Unset() + +none_type = type(None) +file_type = io.IOBase + + +class FileIO(io.FileIO): + """ + A class for storing files + Note: this class is not immutable + """ + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader]): + if isinstance(arg, (io.FileIO, io.BufferedReader)): + if arg.closed: + raise ApiValueError('Invalid file state; file is closed and must be open') + arg.close() + inst = super(FileIO, cls).__new__(cls, arg.name) + super(FileIO, inst).__init__(arg.name) + return inst + raise ApiValueError('FileIO must be passed arg which contains the open file') + + def __init__(self, arg: typing.Union[io.FileIO, io.BufferedReader]): + pass + + +def update(d: dict, u: dict): + """ + Adds u to d + Where each dict is defaultdict(set) + """ + if not u: + return d + for k, v in u.items(): + if k not in d: + d[k] = v + else: + d[k] = d[k] | v + + +class ValidationMetadata(frozendict.frozendict): + """ + A class storing metadata that is needed to validate OpenApi Schema payloads + """ + def __new__( + cls, + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), + from_server: bool = False, + configuration: typing.Optional[Configuration] = None, + seen_classes: typing.FrozenSet[typing.Type] = frozenset(), + validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]] = frozendict.frozendict() + ): + """ + Args: + path_to_item: the path to the current data being instantiated. + For {'a': [1]} if the code is handling, 1, then the path is ('args[0]', 'a', 0) + This changes from location to location + from_server: whether or not this data came form the server + True when receiving server data + False when instantiating model with client side data not form the server + This does not change from location to location + configuration: the Configuration instance to use + This is needed because in Configuration: + - one can disable validation checking + This does not change from location to location + seen_classes: when deserializing data that matches multiple schemas, this is used to store + the schemas that have been traversed. This is used to stop processing when a cycle is seen. + This changes from location to location + validated_path_to_schemas: stores the already validated schema classes for a given path location + This does not change from location to location + """ + return super().__new__( + cls, + path_to_item=path_to_item, + from_server=from_server, + configuration=configuration, + seen_classes=seen_classes, + validated_path_to_schemas=validated_path_to_schemas + ) + + def validation_ran_earlier(self, cls: type) -> bool: + validated_schemas = self.validated_path_to_schemas.get(self.path_to_item, set()) + validation_ran_earlier = validated_schemas and cls in validated_schemas + if validation_ran_earlier: + return True + if cls in self.seen_classes: + return True + return False + + @property + def path_to_item(self) -> typing.Tuple[typing.Union[str, int], ...]: + return self.get('path_to_item') + + @property + def from_server(self) -> bool: + return self.get('from_server') + + @property + def configuration(self) -> typing.Optional[Configuration]: + return self.get('configuration') + + @property + def seen_classes(self) -> typing.FrozenSet[typing.Type]: + return self.get('seen_classes') + + @property + def validated_path_to_schemas(self) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Type]]: + return self.get('validated_path_to_schemas') + + +class Singleton: + """ + Enums and singletons are the same + The same instance is returned for a given key of (cls, arg) + """ + _instances = {} + + def __new__(cls, arg: typing.Any, **kwargs): + """ + cls base classes: BoolClass, NoneClass, str, decimal.Decimal + The 3rd key is used in the tuple below for a corner case where an enum contains integer 1 + However 1.0 can also be ingested into that enum schema because 1.0 == 1 and + Decimal('1.0') == Decimal('1') + But if we omitted the 3rd value in the key, then Decimal('1.0') would be stored as Decimal('1') + and json serializing that instance would be '1' rather than the expected '1.0' + Adding the 3rd value, the str of arg ensures that 1.0 -> Decimal('1.0') which is serialized as 1.0 + """ + key = (cls, arg, str(arg)) + if key not in cls._instances: + if isinstance(arg, (none_type, bool, BoolClass, NoneClass)): + inst = super().__new__(cls) + cls._instances[key] = inst + else: + cls._instances[key] = super().__new__(cls, arg) + return cls._instances[key] + + def __repr__(self): + if isinstance(self, NoneClass): + return f'<{self.__class__.__name__}: None>' + elif isinstance(self, BoolClass): + if bool(self): + return f'<{self.__class__.__name__}: True>' + return f'<{self.__class__.__name__}: False>' + return f'<{self.__class__.__name__}: {super().__repr__()}>' + + +class classproperty: + + def __init__(self, fget): + self.fget = fget + + def __get__(self, owner_self, owner_cls): + return self.fget(owner_cls) + + +class NoneClass(Singleton): + @classproperty + def NONE(cls): + return cls(None) + + def __bool__(self) -> bool: + return False + + +class BoolClass(Singleton): + @classproperty + def TRUE(cls): + return cls(True) + + @classproperty + def FALSE(cls): + return cls(False) + + @functools.lru_cache() + def __bool__(self) -> bool: + for key, instance in self._instances.items(): + if self is instance: + return bool(key[1]) + raise ValueError('Unable to find the boolean value of this instance') + + +class MetaOapgTyped: + exclusive_maximum: typing.Union[int, float] + inclusive_maximum: typing.Union[int, float] + exclusive_minimum: typing.Union[int, float] + inclusive_minimum: typing.Union[int, float] + max_items: int + min_items: int + discriminator: typing.Dict[str, typing.Dict[str, typing.Type['Schema']]] + + + class properties: + # to hold object properties + pass + + additional_properties: typing.Optional[typing.Type['Schema']] + max_properties: int + min_properties: int + all_of: typing.List[typing.Type['Schema']] + one_of: typing.List[typing.Type['Schema']] + any_of: typing.List[typing.Type['Schema']] + not_schema: typing.Type['Schema'] + max_length: int + min_length: int + items: typing.Type['Schema'] + + +class Schema: + """ + the base class of all swagger/openapi schemas/models + """ + __inheritable_primitive_types_set = {decimal.Decimal, str, tuple, frozendict.frozendict, FileIO, bytes, BoolClass, NoneClass} + _types: typing.Set[typing.Type] + MetaOapg = MetaOapgTyped + + @staticmethod + def __get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed""" + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return "is {0}".format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + @staticmethod + def _get_class_oapg(item_cls: typing.Union[types.FunctionType, staticmethod, typing.Type['Schema']]) -> typing.Type['Schema']: + if isinstance(item_cls, types.FunctionType): + # referenced schema + return item_cls() + elif isinstance(item_cls, staticmethod): + # referenced schema + return item_cls.__func__() + return item_cls + + @classmethod + def __type_error_message( + cls, var_value=None, var_name=None, valid_classes=None, key_type=None + ): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a tuple + """ + key_or_value = "value" + if key_type: + key_or_value = "key" + valid_classes_phrase = cls.__get_valid_classes_phrase(valid_classes) + msg = "Invalid type. Required {1} type {2} and " "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + return msg + + @classmethod + def __get_type_error(cls, var_value, path_to_item, valid_classes, key_type=False): + error_msg = cls.__type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type, + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type, + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + Schema _validate_oapg + All keyword validation except for type checking was done in calling stack frames + If those validations passed, the validated classes are collected in path_to_schemas + + Returns: + path_to_schemas: a map of path to schemas + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + base_class = type(arg) + if base_class not in cls._types: + raise cls.__get_type_error( + arg, + validation_metadata.path_to_item, + cls._types, + key_type=False, + ) + + path_to_schemas = {validation_metadata.path_to_item: set()} + path_to_schemas[validation_metadata.path_to_item].add(cls) + path_to_schemas[validation_metadata.path_to_item].add(base_class) + return path_to_schemas + + @staticmethod + def _process_schema_classes_oapg( + schema_classes: typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]] + ): + """ + Processes and mutates schema_classes + If a SomeSchema is a subclass of DictSchema then remove DictSchema because it is already included + """ + if len(schema_classes) < 2: + return + if len(schema_classes) > 2 and UnsetAnyTypeSchema in schema_classes: + schema_classes.remove(UnsetAnyTypeSchema) + x_schema = schema_type_classes & schema_classes + if not x_schema: + return + x_schema = x_schema.pop() + if any(c is not x_schema and issubclass(c, x_schema) for c in schema_classes): + # needed to not have a mro error in get_new_class + schema_classes.remove(x_schema) + + @classmethod + def __get_new_cls( + cls, + arg, + validation_metadata: ValidationMetadata + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']]: + """ + Make a new dynamic class and return an instance of that class + We are making an instance of cls, but instead of making cls + make a new class, new_cls + which includes dynamic bases including cls + return an instance of that new class + + Dict property + List Item Assignment Use cases: + 1. value is NOT an instance of the required schema class + the value is validated by _validate_oapg + _validate_oapg returns a key value pair + where the key is the path to the item, and the value will be the required manufactured class + made out of the matching schemas + 2. value is an instance of the the correct schema type + the value is NOT validated by _validate_oapg, _validate_oapg only checks that the instance is of the correct schema type + for this value, _validate_oapg does NOT return an entry for it in _path_to_schemas + and in list/dict _get_items_oapg,_get_properties_oapg the value will be directly assigned + because value is of the correct type, and validation was run earlier when the instance was created + """ + _path_to_schemas = {} + if validation_metadata.validated_path_to_schemas: + update(_path_to_schemas, validation_metadata.validated_path_to_schemas) + if not validation_metadata.validation_ran_earlier(cls): + other_path_to_schemas = cls._validate_oapg(arg, validation_metadata=validation_metadata) + update(_path_to_schemas, other_path_to_schemas) + # loop through it make a new class for each entry + # do not modify the returned result because it is cached and we would be modifying the cached value + path_to_schemas = {} + for path, schema_classes in _path_to_schemas.items(): + """ + Use cases + 1. N number of schema classes + enum + type != bool/None, classes in path_to_schemas: tuple/frozendict.frozendict/str/Decimal/bytes/FileIo + needs Singleton added + 2. N number of schema classes + enum + type == bool/None, classes in path_to_schemas: BoolClass/NoneClass + Singleton already added + 3. N number of schema classes, classes in path_to_schemas: BoolClass/NoneClass/tuple/frozendict.frozendict/str/Decimal/bytes/FileIo + """ + cls._process_schema_classes_oapg(schema_classes) + enum_schema = any( + issubclass(this_cls, EnumBase) for this_cls in schema_classes) + inheritable_primitive_type = schema_classes.intersection(cls.__inheritable_primitive_types_set) + chosen_schema_classes = schema_classes - inheritable_primitive_type + suffix = tuple(inheritable_primitive_type) + if enum_schema and suffix[0] not in {NoneClass, BoolClass}: + suffix = (Singleton,) + suffix + + used_classes = tuple(sorted(chosen_schema_classes, key=lambda a_cls: a_cls.__name__)) + suffix + mfg_cls = get_new_class(class_name='DynamicSchema', bases=used_classes) + path_to_schemas[path] = mfg_cls + + return path_to_schemas + + @classmethod + def _get_new_instance_without_conversion_oapg( + cls, + arg: typing.Any, + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + # We have a Dynamic class and we are making an instance of it + if issubclass(cls, frozendict.frozendict) and issubclass(cls, DictBase): + properties = cls._get_properties_oapg(arg, path_to_item, path_to_schemas) + return super(Schema, cls).__new__(cls, properties) + elif issubclass(cls, tuple) and issubclass(cls, ListBase): + items = cls._get_items_oapg(arg, path_to_item, path_to_schemas) + return super(Schema, cls).__new__(cls, items) + """ + str = openapi str, date, and datetime + decimal.Decimal = openapi int and float + FileIO = openapi binary type and the user inputs a file + bytes = openapi binary type and the user inputs bytes + """ + return super(Schema, cls).__new__(cls, arg) + + @classmethod + def from_openapi_data_oapg( + cls, + arg: typing.Union[ + str, + date, + datetime, + int, + float, + decimal.Decimal, + bool, + None, + 'Schema', + dict, + frozendict.frozendict, + tuple, + list, + io.FileIO, + io.BufferedReader, + bytes + ], + _configuration: typing.Optional[Configuration] + ): + """ + Schema from_openapi_data_oapg + """ + from_server = True + validated_path_to_schemas = {} + arg = cast_to_allowed_types(arg, from_server, validated_path_to_schemas) + validation_metadata = ValidationMetadata( + from_server=from_server, configuration=_configuration, validated_path_to_schemas=validated_path_to_schemas) + path_to_schemas = cls.__get_new_cls(arg, validation_metadata) + new_cls = path_to_schemas[validation_metadata.path_to_item] + new_inst = new_cls._get_new_instance_without_conversion_oapg( + arg, + validation_metadata.path_to_item, + path_to_schemas + ) + return new_inst + + @staticmethod + def __get_input_dict(*args, **kwargs) -> frozendict.frozendict: + input_dict = {} + if args and isinstance(args[0], (dict, frozendict.frozendict)): + input_dict.update(args[0]) + if kwargs: + input_dict.update(kwargs) + return frozendict.frozendict(input_dict) + + @staticmethod + def __remove_unsets(kwargs): + return {key: val for key, val in kwargs.items() if val is not unset} + + def __new__(cls, *args: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], _configuration: typing.Optional[Configuration] = None, **kwargs: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset]): + """ + Schema __new__ + + Args: + args (int/float/decimal.Decimal/str/list/tuple/dict/frozendict.frozendict/bool/None): the value + kwargs (str, int/float/decimal.Decimal/str/list/tuple/dict/frozendict.frozendict/bool/None): dict values + _configuration: contains the Configuration that enables json schema validation keywords + like minItems, minLength etc + + Note: double underscores are used here because pycharm thinks that these variables + are instance properties if they are named normally :( + """ + __kwargs = cls.__remove_unsets(kwargs) + if not args and not __kwargs: + raise TypeError( + 'No input given. args or kwargs must be given.' + ) + if not __kwargs and args and not isinstance(args[0], dict): + __arg = args[0] + else: + __arg = cls.__get_input_dict(*args, **__kwargs) + __from_server = False + __validated_path_to_schemas = {} + __arg = cast_to_allowed_types( + __arg, __from_server, __validated_path_to_schemas) + __validation_metadata = ValidationMetadata( + configuration=_configuration, from_server=__from_server, validated_path_to_schemas=__validated_path_to_schemas) + __path_to_schemas = cls.__get_new_cls(__arg, __validation_metadata) + __new_cls = __path_to_schemas[__validation_metadata.path_to_item] + return __new_cls._get_new_instance_without_conversion_oapg( + __arg, + __validation_metadata.path_to_item, + __path_to_schemas + ) + + def __init__( + self, + *args: typing.Union[ + dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema'], + _configuration: typing.Optional[Configuration] = None, + **kwargs: typing.Union[ + dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset + ] + ): + """ + this is needed to fix 'Unexpected argument' warning in pycharm + this code does nothing because all Schema instances are immutable + this means that all input data is passed into and used in new, and after the new instance is made + no new attributes are assigned and init is not used + """ + pass + +""" +import itertools +data_types = ('None', 'FrozenDict', 'Tuple', 'Str', 'Decimal', 'Bool') +type_to_cls = { + 'None': 'NoneClass', + 'FrozenDict': 'frozendict.frozendict', + 'Tuple': 'tuple', + 'Str': 'str', + 'Decimal': 'decimal.Decimal', + 'Bool': 'BoolClass' +} +cls_tuples = [v for v in itertools.combinations(data_types, 5)] +typed_classes = [f"class {''.join(cls_tuple)}Mixin({', '.join(type_to_cls[typ] for typ in cls_tuple)}):\n pass" for cls_tuple in cls_tuples] +for cls in typed_classes: + print(cls) +object_classes = [f"{''.join(cls_tuple)}Mixin = object" for cls_tuple in cls_tuples] +for cls in object_classes: + print(cls) +""" +if typing.TYPE_CHECKING: + # qty 1 + NoneMixin = NoneClass + FrozenDictMixin = frozendict.frozendict + TupleMixin = tuple + StrMixin = str + DecimalMixin = decimal.Decimal + BoolMixin = BoolClass + BytesMixin = bytes + FileMixin = FileIO + # qty 2 + class BinaryMixin(bytes, FileIO): + pass + class NoneFrozenDictMixin(NoneClass, frozendict.frozendict): + pass + class NoneTupleMixin(NoneClass, tuple): + pass + class NoneStrMixin(NoneClass, str): + pass + class NoneDecimalMixin(NoneClass, decimal.Decimal): + pass + class NoneBoolMixin(NoneClass, BoolClass): + pass + class FrozenDictTupleMixin(frozendict.frozendict, tuple): + pass + class FrozenDictStrMixin(frozendict.frozendict, str): + pass + class FrozenDictDecimalMixin(frozendict.frozendict, decimal.Decimal): + pass + class FrozenDictBoolMixin(frozendict.frozendict, BoolClass): + pass + class TupleStrMixin(tuple, str): + pass + class TupleDecimalMixin(tuple, decimal.Decimal): + pass + class TupleBoolMixin(tuple, BoolClass): + pass + class StrDecimalMixin(str, decimal.Decimal): + pass + class StrBoolMixin(str, BoolClass): + pass + class DecimalBoolMixin(decimal.Decimal, BoolClass): + pass + # qty 3 + class NoneFrozenDictTupleMixin(NoneClass, frozendict.frozendict, tuple): + pass + class NoneFrozenDictStrMixin(NoneClass, frozendict.frozendict, str): + pass + class NoneFrozenDictDecimalMixin(NoneClass, frozendict.frozendict, decimal.Decimal): + pass + class NoneFrozenDictBoolMixin(NoneClass, frozendict.frozendict, BoolClass): + pass + class NoneTupleStrMixin(NoneClass, tuple, str): + pass + class NoneTupleDecimalMixin(NoneClass, tuple, decimal.Decimal): + pass + class NoneTupleBoolMixin(NoneClass, tuple, BoolClass): + pass + class NoneStrDecimalMixin(NoneClass, str, decimal.Decimal): + pass + class NoneStrBoolMixin(NoneClass, str, BoolClass): + pass + class NoneDecimalBoolMixin(NoneClass, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrMixin(frozendict.frozendict, tuple, str): + pass + class FrozenDictTupleDecimalMixin(frozendict.frozendict, tuple, decimal.Decimal): + pass + class FrozenDictTupleBoolMixin(frozendict.frozendict, tuple, BoolClass): + pass + class FrozenDictStrDecimalMixin(frozendict.frozendict, str, decimal.Decimal): + pass + class FrozenDictStrBoolMixin(frozendict.frozendict, str, BoolClass): + pass + class FrozenDictDecimalBoolMixin(frozendict.frozendict, decimal.Decimal, BoolClass): + pass + class TupleStrDecimalMixin(tuple, str, decimal.Decimal): + pass + class TupleStrBoolMixin(tuple, str, BoolClass): + pass + class TupleDecimalBoolMixin(tuple, decimal.Decimal, BoolClass): + pass + class StrDecimalBoolMixin(str, decimal.Decimal, BoolClass): + pass + # qty 4 + class NoneFrozenDictTupleStrMixin(NoneClass, frozendict.frozendict, tuple, str): + pass + class NoneFrozenDictTupleDecimalMixin(NoneClass, frozendict.frozendict, tuple, decimal.Decimal): + pass + class NoneFrozenDictTupleBoolMixin(NoneClass, frozendict.frozendict, tuple, BoolClass): + pass + class NoneFrozenDictStrDecimalMixin(NoneClass, frozendict.frozendict, str, decimal.Decimal): + pass + class NoneFrozenDictStrBoolMixin(NoneClass, frozendict.frozendict, str, BoolClass): + pass + class NoneFrozenDictDecimalBoolMixin(NoneClass, frozendict.frozendict, decimal.Decimal, BoolClass): + pass + class NoneTupleStrDecimalMixin(NoneClass, tuple, str, decimal.Decimal): + pass + class NoneTupleStrBoolMixin(NoneClass, tuple, str, BoolClass): + pass + class NoneTupleDecimalBoolMixin(NoneClass, tuple, decimal.Decimal, BoolClass): + pass + class NoneStrDecimalBoolMixin(NoneClass, str, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrDecimalMixin(frozendict.frozendict, tuple, str, decimal.Decimal): + pass + class FrozenDictTupleStrBoolMixin(frozendict.frozendict, tuple, str, BoolClass): + pass + class FrozenDictTupleDecimalBoolMixin(frozendict.frozendict, tuple, decimal.Decimal, BoolClass): + pass + class FrozenDictStrDecimalBoolMixin(frozendict.frozendict, str, decimal.Decimal, BoolClass): + pass + class TupleStrDecimalBoolMixin(tuple, str, decimal.Decimal, BoolClass): + pass + # qty 5 + class NoneFrozenDictTupleStrDecimalMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal): + pass + class NoneFrozenDictTupleStrBoolMixin(NoneClass, frozendict.frozendict, tuple, str, BoolClass): + pass + class NoneFrozenDictTupleDecimalBoolMixin(NoneClass, frozendict.frozendict, tuple, decimal.Decimal, BoolClass): + pass + class NoneFrozenDictStrDecimalBoolMixin(NoneClass, frozendict.frozendict, str, decimal.Decimal, BoolClass): + pass + class NoneTupleStrDecimalBoolMixin(NoneClass, tuple, str, decimal.Decimal, BoolClass): + pass + class FrozenDictTupleStrDecimalBoolMixin(frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass): + pass + # qty 6 + class NoneFrozenDictTupleStrDecimalBoolMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass): + pass + # qty 8 + class NoneFrozenDictTupleStrDecimalBoolFileBytesMixin(NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass, FileIO, bytes): + pass +else: + # qty 1 + class NoneMixin: + _types = {NoneClass} + class FrozenDictMixin: + _types = {frozendict.frozendict} + class TupleMixin: + _types = {tuple} + class StrMixin: + _types = {str} + class DecimalMixin: + _types = {decimal.Decimal} + class BoolMixin: + _types = {BoolClass} + class BytesMixin: + _types = {bytes} + class FileMixin: + _types = {FileIO} + # qty 2 + class BinaryMixin: + _types = {bytes, FileIO} + class NoneFrozenDictMixin: + _types = {NoneClass, frozendict.frozendict} + class NoneTupleMixin: + _types = {NoneClass, tuple} + class NoneStrMixin: + _types = {NoneClass, str} + class NoneDecimalMixin: + _types = {NoneClass, decimal.Decimal} + class NoneBoolMixin: + _types = {NoneClass, BoolClass} + class FrozenDictTupleMixin: + _types = {frozendict.frozendict, tuple} + class FrozenDictStrMixin: + _types = {frozendict.frozendict, str} + class FrozenDictDecimalMixin: + _types = {frozendict.frozendict, decimal.Decimal} + class FrozenDictBoolMixin: + _types = {frozendict.frozendict, BoolClass} + class TupleStrMixin: + _types = {tuple, str} + class TupleDecimalMixin: + _types = {tuple, decimal.Decimal} + class TupleBoolMixin: + _types = {tuple, BoolClass} + class StrDecimalMixin: + _types = {str, decimal.Decimal} + class StrBoolMixin: + _types = {str, BoolClass} + class DecimalBoolMixin: + _types = {decimal.Decimal, BoolClass} + # qty 3 + class NoneFrozenDictTupleMixin: + _types = {NoneClass, frozendict.frozendict, tuple} + class NoneFrozenDictStrMixin: + _types = {NoneClass, frozendict.frozendict, str} + class NoneFrozenDictDecimalMixin: + _types = {NoneClass, frozendict.frozendict, decimal.Decimal} + class NoneFrozenDictBoolMixin: + _types = {NoneClass, frozendict.frozendict, BoolClass} + class NoneTupleStrMixin: + _types = {NoneClass, tuple, str} + class NoneTupleDecimalMixin: + _types = {NoneClass, tuple, decimal.Decimal} + class NoneTupleBoolMixin: + _types = {NoneClass, tuple, BoolClass} + class NoneStrDecimalMixin: + _types = {NoneClass, str, decimal.Decimal} + class NoneStrBoolMixin: + _types = {NoneClass, str, BoolClass} + class NoneDecimalBoolMixin: + _types = {NoneClass, decimal.Decimal, BoolClass} + class FrozenDictTupleStrMixin: + _types = {frozendict.frozendict, tuple, str} + class FrozenDictTupleDecimalMixin: + _types = {frozendict.frozendict, tuple, decimal.Decimal} + class FrozenDictTupleBoolMixin: + _types = {frozendict.frozendict, tuple, BoolClass} + class FrozenDictStrDecimalMixin: + _types = {frozendict.frozendict, str, decimal.Decimal} + class FrozenDictStrBoolMixin: + _types = {frozendict.frozendict, str, BoolClass} + class FrozenDictDecimalBoolMixin: + _types = {frozendict.frozendict, decimal.Decimal, BoolClass} + class TupleStrDecimalMixin: + _types = {tuple, str, decimal.Decimal} + class TupleStrBoolMixin: + _types = {tuple, str, BoolClass} + class TupleDecimalBoolMixin: + _types = {tuple, decimal.Decimal, BoolClass} + class StrDecimalBoolMixin: + _types = {str, decimal.Decimal, BoolClass} + # qty 4 + class NoneFrozenDictTupleStrMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str} + class NoneFrozenDictTupleDecimalMixin: + _types = {NoneClass, frozendict.frozendict, tuple, decimal.Decimal} + class NoneFrozenDictTupleBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, BoolClass} + class NoneFrozenDictStrDecimalMixin: + _types = {NoneClass, frozendict.frozendict, str, decimal.Decimal} + class NoneFrozenDictStrBoolMixin: + _types = {NoneClass, frozendict.frozendict, str, BoolClass} + class NoneFrozenDictDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, decimal.Decimal, BoolClass} + class NoneTupleStrDecimalMixin: + _types = {NoneClass, tuple, str, decimal.Decimal} + class NoneTupleStrBoolMixin: + _types = {NoneClass, tuple, str, BoolClass} + class NoneTupleDecimalBoolMixin: + _types = {NoneClass, tuple, decimal.Decimal, BoolClass} + class NoneStrDecimalBoolMixin: + _types = {NoneClass, str, decimal.Decimal, BoolClass} + class FrozenDictTupleStrDecimalMixin: + _types = {frozendict.frozendict, tuple, str, decimal.Decimal} + class FrozenDictTupleStrBoolMixin: + _types = {frozendict.frozendict, tuple, str, BoolClass} + class FrozenDictTupleDecimalBoolMixin: + _types = {frozendict.frozendict, tuple, decimal.Decimal, BoolClass} + class FrozenDictStrDecimalBoolMixin: + _types = {frozendict.frozendict, str, decimal.Decimal, BoolClass} + class TupleStrDecimalBoolMixin: + _types = {tuple, str, decimal.Decimal, BoolClass} + # qty 5 + class NoneFrozenDictTupleStrDecimalMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal} + class NoneFrozenDictTupleStrBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, BoolClass} + class NoneFrozenDictTupleDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, decimal.Decimal, BoolClass} + class NoneFrozenDictStrDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, str, decimal.Decimal, BoolClass} + class NoneTupleStrDecimalBoolMixin: + _types = {NoneClass, tuple, str, decimal.Decimal, BoolClass} + class FrozenDictTupleStrDecimalBoolMixin: + _types = {frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass} + # qty 6 + class NoneFrozenDictTupleStrDecimalBoolMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass} + # qty 8 + class NoneFrozenDictTupleStrDecimalBoolFileBytesMixin: + _types = {NoneClass, frozendict.frozendict, tuple, str, decimal.Decimal, BoolClass, FileIO, bytes} + + +class ValidatorBase: + @staticmethod + def _is_json_validation_enabled_oapg(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + Note: the suffix _oapg stands for openapi python (experimental) generator and + it has been added to prevent collisions with other methods and properties + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + @staticmethod + def _raise_validation_errror_message_oapg(value, constraint_msg, constraint_value, path_to_item, additional_txt=""): + raise ApiValueError( + "Invalid value `{value}`, {constraint_msg} `{constraint_value}`{additional_txt} at {path_to_item}".format( + value=value, + constraint_msg=constraint_msg, + constraint_value=constraint_value, + additional_txt=additional_txt, + path_to_item=path_to_item, + ) + ) + + +class EnumBase: + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + EnumBase _validate_oapg + Validates that arg is in the enum's allowed values + """ + try: + cls.MetaOapg.enum_value_to_name[arg] + except KeyError: + raise ApiValueError("Invalid value {} passed in to {}, allowed_values={}".format(arg, cls, cls.MetaOapg.enum_value_to_name.keys())) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class BoolBase: + def is_true_oapg(self) -> bool: + """ + A replacement for x is True + True if the instance is a BoolClass True Singleton + """ + if not issubclass(self.__class__, BoolClass): + return False + return bool(self) + + def is_false_oapg(self) -> bool: + """ + A replacement for x is False + True if the instance is a BoolClass False Singleton + """ + if not issubclass(self.__class__, BoolClass): + return False + return bool(self) is False + + +class NoneBase: + def is_none_oapg(self) -> bool: + """ + A replacement for x is None + True if the instance is a NoneClass None Singleton + """ + if issubclass(self.__class__, NoneClass): + return True + return False + + +class StrBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @property + def as_str_oapg(self) -> str: + return self + + @property + def as_date_oapg(self) -> date: + raise Exception('not implemented') + + @property + def as_datetime_oapg(self) -> datetime: + raise Exception('not implemented') + + @property + def as_decimal_oapg(self) -> decimal.Decimal: + raise Exception('not implemented') + + @property + def as_uuid_oapg(self) -> uuid.UUID: + raise Exception('not implemented') + + @classmethod + def __check_str_validations( + cls, + arg: str, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxLength', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_length') and + len(arg) > cls.MetaOapg.max_length): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="length must be less than or equal to", + constraint_value=cls.MetaOapg.max_length, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minLength', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_length') and + len(arg) < cls.MetaOapg.min_length): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="length must be greater than or equal to", + constraint_value=cls.MetaOapg.min_length, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('pattern', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'regex')): + for regex_dict in cls.MetaOapg.regex: + flags = regex_dict.get('flags', 0) + if not re.search(regex_dict['pattern'], arg, flags=flags): + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must match regular expression", + constraint_value=regex_dict['pattern'], + path_to_item=validation_metadata.path_to_item, + additional_txt=" with flags=`{}`".format(flags) + ) + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must match regular expression", + constraint_value=regex_dict['pattern'], + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + StrBase _validate_oapg + Validates that validations pass + """ + if isinstance(arg, str): + cls.__check_str_validations(arg, validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class UUIDBase: + @property + @functools.lru_cache() + def as_uuid_oapg(self) -> uuid.UUID: + return uuid.UUID(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + uuid.UUID(arg) + return True + except ValueError: + raise ApiValueError( + "Invalid value '{}' for type UUID at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: typing.Optional[ValidationMetadata] = None, + ): + """ + UUIDBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class CustomIsoparser(isoparser): + + @_takes_ascii + def parse_isodatetime(self, dt_str): + components, pos = self._parse_isodate(dt_str) + if len(dt_str) > pos: + if self._sep is None or dt_str[pos:pos + 1] == self._sep: + components += self._parse_isotime(dt_str[pos + 1:]) + else: + raise ValueError('String contains unknown ISO components') + + if len(components) > 3 and components[3] == 24: + components[3] = 0 + return datetime(*components) + timedelta(days=1) + + if len(components) <= 3: + raise ValueError('Value is not a datetime') + + return datetime(*components) + + @_takes_ascii + def parse_isodate(self, datestr): + components, pos = self._parse_isodate(datestr) + + if len(datestr) > pos: + raise ValueError('String contains invalid time components') + + if len(components) > 3: + raise ValueError('String contains invalid time components') + + return date(*components) + + +DEFAULT_ISOPARSER = CustomIsoparser() + + +class DateBase: + @property + @functools.lru_cache() + def as_date_oapg(self) -> date: + return DEFAULT_ISOPARSER.parse_isodate(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + DEFAULT_ISOPARSER.parse_isodate(arg) + return True + except ValueError: + raise ApiValueError( + "Value does not conform to the required ISO-8601 date format. " + "Invalid value '{}' for type date at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: typing.Optional[ValidationMetadata] = None, + ): + """ + DateBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class DateTimeBase: + @property + @functools.lru_cache() + def as_datetime_oapg(self) -> datetime: + return DEFAULT_ISOPARSER.parse_isodatetime(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + DEFAULT_ISOPARSER.parse_isodatetime(arg) + return True + except ValueError: + raise ApiValueError( + "Value does not conform to the required ISO-8601 datetime format. " + "Invalid value '{}' for type datetime at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DateTimeBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class DecimalBase: + """ + A class for storing decimals that are sent over the wire as strings + These schemas must remain based on StrBase rather than NumberBase + because picking base classes must be deterministic + """ + + @property + @functools.lru_cache() + def as_decimal_oapg(self) -> decimal.Decimal: + return decimal.Decimal(self) + + @classmethod + def __validate_format(cls, arg: typing.Optional[str], validation_metadata: ValidationMetadata): + if isinstance(arg, str): + try: + decimal.Decimal(arg) + return True + except decimal.InvalidOperation: + raise ApiValueError( + "Value cannot be converted to a decimal. " + "Invalid value '{}' for type decimal at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DecimalBase _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class NumberBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @property + def as_int_oapg(self) -> int: + try: + return self._as_int + except AttributeError: + """ + Note: for some numbers like 9.0 they could be represented as an + integer but our code chooses to store them as + >>> Decimal('9.0').as_tuple() + DecimalTuple(sign=0, digits=(9, 0), exponent=-1) + so we can tell that the value came from a float and convert it back to a float + during later serialization + """ + if self.as_tuple().exponent < 0: + # this could be represented as an integer but should be represented as a float + # because that's what it was serialized from + raise ApiValueError(f'{self} is not an integer') + self._as_int = int(self) + return self._as_int + + @property + def as_float_oapg(self) -> float: + try: + return self._as_float + except AttributeError: + if self.as_tuple().exponent >= 0: + raise ApiValueError(f'{self} is not an float') + self._as_float = float(self) + return self._as_float + + @classmethod + def __check_numeric_validations( + cls, + arg, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if cls._is_json_validation_enabled_oapg('multipleOf', + validation_metadata.configuration) and hasattr(cls.MetaOapg, 'multiple_of'): + multiple_of_value = cls.MetaOapg.multiple_of + if (not (float(arg) / multiple_of_value).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="value must be a multiple of", + constraint_value=multiple_of_value, + path_to_item=validation_metadata.path_to_item + ) + + checking_max_or_min_values = any( + hasattr(cls.MetaOapg, validation_key) for validation_key in { + 'exclusive_maximum', + 'inclusive_maximum', + 'exclusive_minimum', + 'inclusive_minimum', + } + ) + if not checking_max_or_min_values: + return + + if (cls._is_json_validation_enabled_oapg('exclusiveMaximum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'exclusive_maximum') and + arg >= cls.MetaOapg.exclusive_maximum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value less than", + constraint_value=cls.MetaOapg.exclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('maximum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'inclusive_maximum') and + arg > cls.MetaOapg.inclusive_maximum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value less than or equal to", + constraint_value=cls.MetaOapg.inclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('exclusiveMinimum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'exclusive_minimum') and + arg <= cls.MetaOapg.exclusive_minimum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value greater than", + constraint_value=cls.MetaOapg.exclusive_maximum, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minimum', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'inclusive_minimum') and + arg < cls.MetaOapg.inclusive_minimum): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="must be a value greater than or equal to", + constraint_value=cls.MetaOapg.inclusive_minimum, + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + NumberBase _validate_oapg + Validates that validations pass + """ + if isinstance(arg, decimal.Decimal): + cls.__check_numeric_validations(arg, validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class ListBase(ValidatorBase): + MetaOapg: MetaOapgTyped + + @classmethod + def __validate_items(cls, list_items, validation_metadata: ValidationMetadata): + """ + Ensures that: + - values passed in for items are valid + Exceptions will be raised if: + - invalid arguments were passed in + + Args: + list_items: the input list of items + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + + # if we have definitions for an items schema, use it + # otherwise accept anything + item_cls = getattr(cls.MetaOapg, 'items', UnsetAnyTypeSchema) + item_cls = cls._get_class_oapg(item_cls) + path_to_schemas = {} + for i, value in enumerate(list_items): + item_validation_metadata = ValidationMetadata( + from_server=validation_metadata.from_server, + configuration=validation_metadata.configuration, + path_to_item=validation_metadata.path_to_item+(i,), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if item_validation_metadata.validation_ran_earlier(item_cls): + continue + other_path_to_schemas = item_cls._validate_oapg( + value, validation_metadata=item_validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __check_tuple_validations( + cls, arg, + validation_metadata: ValidationMetadata): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_items') and + len(arg) > cls.MetaOapg.max_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of items must be less than or equal to", + constraint_value=cls.MetaOapg.max_items, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_items') and + len(arg) < cls.MetaOapg.min_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of items must be greater than or equal to", + constraint_value=cls.MetaOapg.min_items, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('uniqueItems', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'unique_items') and cls.MetaOapg.unique_items and arg): + unique_items = set(arg) + if len(arg) > len(unique_items): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="duplicate items were found, and the tuple must not contain duplicates because", + constraint_value='unique_items==True', + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + ListBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + if isinstance(arg, tuple): + cls.__check_tuple_validations(arg, validation_metadata) + _path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + if not isinstance(arg, tuple): + return _path_to_schemas + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + other_path_to_schemas = cls.__validate_items(arg, validation_metadata=updated_vm) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_items_oapg( + cls: 'Schema', + arg: typing.List[typing.Any], + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + ''' + ListBase _get_items_oapg + ''' + cast_items = [] + + for i, value in enumerate(arg): + item_path_to_item = path_to_item + (i,) + item_cls = path_to_schemas[item_path_to_item] + new_value = item_cls._get_new_instance_without_conversion_oapg( + value, + item_path_to_item, + path_to_schemas + ) + cast_items.append(new_value) + + return cast_items + + +class Discriminable: + MetaOapg: MetaOapgTyped + + @classmethod + def _ensure_discriminator_value_present_oapg(cls, disc_property_name: str, validation_metadata: ValidationMetadata, *args): + if not args or args and disc_property_name not in args[0]: + # The input data does not contain the discriminator property + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '{}' is missing at path: {}".format(disc_property_name, validation_metadata.path_to_item) + ) + + @classmethod + def get_discriminated_class_oapg(cls, disc_property_name: str, disc_payload_value: str): + """ + Used in schemas with discriminators + """ + if not hasattr(cls.MetaOapg, 'discriminator'): + return None + disc = cls.MetaOapg.discriminator() + if disc_property_name not in disc: + return None + discriminated_cls = disc[disc_property_name].get(disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if not hasattr(cls, 'MetaOapg'): + return None + elif not ( + hasattr(cls.MetaOapg, 'all_of') or + hasattr(cls.MetaOapg, 'one_of') or + hasattr(cls.MetaOapg, 'any_of') + ): + return None + # TODO stop traveling if a cycle is hit + if hasattr(cls.MetaOapg, 'all_of'): + for allof_cls in cls.MetaOapg.all_of(): + discriminated_cls = allof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if hasattr(cls.MetaOapg, 'one_of'): + for oneof_cls in cls.MetaOapg.one_of(): + discriminated_cls = oneof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + if hasattr(cls.MetaOapg, 'any_of'): + for anyof_cls in cls.MetaOapg.any_of(): + discriminated_cls = anyof_cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=disc_payload_value) + if discriminated_cls is not None: + return discriminated_cls + return None + + +class DictBase(Discriminable, ValidatorBase): + + @classmethod + def __validate_arg_presence(cls, arg): + """ + Ensures that: + - all required arguments are passed in + - the input variable names are valid + - present in properties or + - accepted because additionalProperties exists + Exceptions will be raised if: + - invalid arguments were passed in + - a var_name is invalid if additional_properties == NotAnyTypeSchema + and var_name not in properties.__annotations__ + - required properties were not passed in + + Args: + arg: the input dict + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + seen_required_properties = set() + invalid_arguments = [] + required_property_names = getattr(cls.MetaOapg, 'required', set()) + additional_properties = getattr(cls.MetaOapg, 'additional_properties', UnsetAnyTypeSchema) + properties = getattr(cls.MetaOapg, 'properties', {}) + property_annotations = getattr(properties, '__annotations__', {}) + for property_name in arg: + if property_name in required_property_names: + seen_required_properties.add(property_name) + elif property_name in property_annotations: + continue + elif additional_properties is not NotAnyTypeSchema: + continue + else: + invalid_arguments.append(property_name) + missing_required_arguments = list(required_property_names - seen_required_properties) + if missing_required_arguments: + missing_required_arguments.sort() + raise ApiTypeError( + "{} is missing {} required argument{}: {}".format( + cls.__name__, + len(missing_required_arguments), + "s" if len(missing_required_arguments) > 1 else "", + missing_required_arguments + ) + ) + if invalid_arguments: + invalid_arguments.sort() + raise ApiTypeError( + "{} was passed {} invalid argument{}: {}".format( + cls.__name__, + len(invalid_arguments), + "s" if len(invalid_arguments) > 1 else "", + invalid_arguments + ) + ) + + @classmethod + def __validate_args(cls, arg, validation_metadata: ValidationMetadata): + """ + Ensures that: + - values passed in for properties are valid + Exceptions will be raised if: + - invalid arguments were passed in + + Args: + arg: the input dict + + Raises: + ApiTypeError - for missing required arguments, or for invalid properties + """ + path_to_schemas = {} + additional_properties = getattr(cls.MetaOapg, 'additional_properties', UnsetAnyTypeSchema) + properties = getattr(cls.MetaOapg, 'properties', {}) + property_annotations = getattr(properties, '__annotations__', {}) + for property_name, value in arg.items(): + path_to_item = validation_metadata.path_to_item+(property_name,) + if property_name in property_annotations: + schema = property_annotations[property_name] + elif additional_properties is not NotAnyTypeSchema: + if additional_properties is UnsetAnyTypeSchema: + """ + If additionalProperties is unset and this path_to_item does not yet have + any validations on it, validate it. + If it already has validations on it, skip this validation. + """ + if path_to_item in path_to_schemas: + continue + schema = additional_properties + else: + raise ApiTypeError('Unable to find schema for value={} in class={} at path_to_item={}'.format( + value, cls, validation_metadata.path_to_item+(property_name,) + )) + schema = cls._get_class_oapg(schema) + arg_validation_metadata = ValidationMetadata( + from_server=validation_metadata.from_server, + configuration=validation_metadata.configuration, + path_to_item=path_to_item, + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if arg_validation_metadata.validation_ran_earlier(schema): + continue + other_path_to_schemas = schema._validate_oapg(value, validation_metadata=arg_validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __check_dict_validations( + cls, + arg, + validation_metadata: ValidationMetadata + ): + if not hasattr(cls, 'MetaOapg'): + return + if (cls._is_json_validation_enabled_oapg('maxProperties', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'max_properties') and + len(arg) > cls.MetaOapg.max_properties): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of properties must be less than or equal to", + constraint_value=cls.MetaOapg.max_properties, + path_to_item=validation_metadata.path_to_item + ) + + if (cls._is_json_validation_enabled_oapg('minProperties', validation_metadata.configuration) and + hasattr(cls.MetaOapg, 'min_properties') and + len(arg) < cls.MetaOapg.min_properties): + cls._raise_validation_errror_message_oapg( + value=arg, + constraint_msg="number of properties must be greater than or equal to", + constraint_value=cls.MetaOapg.min_properties, + path_to_item=validation_metadata.path_to_item + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + DictBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + if isinstance(arg, frozendict.frozendict): + cls.__check_dict_validations(arg, validation_metadata) + _path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + if not isinstance(arg, frozendict.frozendict): + return _path_to_schemas + cls.__validate_arg_presence(arg) + other_path_to_schemas = cls.__validate_args(arg, validation_metadata=validation_metadata) + update(_path_to_schemas, other_path_to_schemas) + try: + discriminator = cls.MetaOapg.discriminator() + except AttributeError: + return _path_to_schemas + # discriminator exists + disc_prop_name = list(discriminator.keys())[0] + cls._ensure_discriminator_value_present_oapg(disc_prop_name, validation_metadata, arg) + discriminated_cls = cls.get_discriminated_class_oapg( + disc_property_name=disc_prop_name, disc_payload_value=arg[disc_prop_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value was passed in to {}.{} Only the values {} are allowed at {}".format( + cls.__name__, + disc_prop_name, + list(discriminator[disc_prop_name].keys()), + validation_metadata.path_to_item + (disc_prop_name,) + ) + ) + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + if updated_vm.validation_ran_earlier(discriminated_cls): + return _path_to_schemas + other_path_to_schemas = discriminated_cls._validate_oapg(arg, validation_metadata=updated_vm) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_properties_oapg( + cls, + arg: typing.Dict[str, typing.Any], + path_to_item: typing.Tuple[typing.Union[str, int], ...], + path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Type['Schema']] + ): + """ + DictBase _get_properties_oapg, this is how properties are set + These values already passed validation + """ + dict_items = {} + + for property_name_js, value in arg.items(): + property_path_to_item = path_to_item + (property_name_js,) + property_cls = path_to_schemas[property_path_to_item] + new_value = property_cls._get_new_instance_without_conversion_oapg( + value, + property_path_to_item, + path_to_schemas + ) + dict_items[property_name_js] = new_value + + return dict_items + + def __setattr__(self, name: str, value: typing.Any): + if not isinstance(self, FileIO): + raise AttributeError('property setting not supported on immutable instances') + + def __getattr__(self, name: str): + """ + for instance.name access + Properties are only type hinted for required properties + so that hasattr(instance, 'optionalProp') is False when that key is not present + """ + if not isinstance(self, frozendict.frozendict): + return super().__getattr__(name) + if name not in self.__class__.__annotations__: + raise AttributeError(f"{self} has no attribute '{name}'") + try: + value = self[name] + return value + except KeyError as ex: + raise AttributeError(str(ex)) + + def __getitem__(self, name: str): + """ + dict_instance[name] accessor + key errors thrown + """ + if not isinstance(self, frozendict.frozendict): + return super().__getattr__(name) + return super().__getitem__(name) + + def get_item_oapg(self, name: str) -> typing.Union['AnyTypeSchema', Unset]: + # dict_instance[name] accessor + if not isinstance(self, frozendict.frozendict): + raise NotImplementedError() + try: + return super().__getitem__(name) + except KeyError: + return unset + + +def cast_to_allowed_types( + arg: typing.Union[str, date, datetime, uuid.UUID, decimal.Decimal, int, float, None, dict, frozendict.frozendict, list, tuple, bytes, Schema, io.FileIO, io.BufferedReader], + from_server: bool, + validated_path_to_schemas: typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]], + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), +) -> typing.Union[frozendict.frozendict, tuple, decimal.Decimal, str, bytes, BoolClass, NoneClass, FileIO]: + """ + Casts the input payload arg into the allowed types + The input validated_path_to_schemas is mutated by running this function + + When from_server is False then + - date/datetime is cast to str + - int/float is cast to Decimal + + If a Schema instance is passed in it is converted back to a primitive instance because + One may need to validate that data to the original Schema class AND additional different classes + those additional classes will need to be added to the new manufactured class for that payload + If the code didn't do this and kept the payload as a Schema instance it would fail to validate to other + Schema classes and the code wouldn't be able to mfg a new class that includes all valid schemas + TODO: store the validated schema classes in validation_metadata + + Args: + arg: the payload + from_server: whether this payload came from the server or not + validated_path_to_schemas: a dict that stores the validated classes at any path location in the payload + """ + if isinstance(arg, Schema): + # store the already run validations + schema_classes = set() + source_schema_was_unset = len(arg.__class__.__bases__) == 2 and UnsetAnyTypeSchema in arg.__class__.__bases__ + if not source_schema_was_unset: + """ + Do not include UnsetAnyTypeSchema and its base class because + it did not exist in the original spec schema definition + It was added to ensure that all instances are of type Schema and the allowed base types + """ + for cls in arg.__class__.__bases__: + if cls is Singleton: + # Skip Singleton + continue + schema_classes.add(cls) + validated_path_to_schemas[path_to_item] = schema_classes + + type_error = ApiTypeError(f"Invalid type. Required value type is str and passed type was {type(arg)} at {path_to_item}") + if isinstance(arg, str): + return str(arg) + elif isinstance(arg, (dict, frozendict.frozendict)): + return frozendict.frozendict({key: cast_to_allowed_types(val, from_server, validated_path_to_schemas, path_to_item + (key,)) for key, val in arg.items()}) + elif isinstance(arg, (bool, BoolClass)): + """ + this check must come before isinstance(arg, (int, float)) + because isinstance(True, int) is True + """ + if arg: + return BoolClass.TRUE + return BoolClass.FALSE + elif isinstance(arg, int): + return decimal.Decimal(arg) + elif isinstance(arg, float): + decimal_from_float = decimal.Decimal(arg) + if decimal_from_float.as_integer_ratio()[1] == 1: + # 9.0 -> Decimal('9.0') + # 3.4028234663852886e+38 -> Decimal('340282346638528859811704183484516925440.0') + return decimal.Decimal(str(decimal_from_float)+'.0') + return decimal_from_float + elif isinstance(arg, (tuple, list)): + return tuple([cast_to_allowed_types(item, from_server, validated_path_to_schemas, path_to_item + (i,)) for i, item in enumerate(arg)]) + elif isinstance(arg, (none_type, NoneClass)): + return NoneClass.NONE + elif isinstance(arg, (date, datetime)): + if not from_server: + return arg.isoformat() + raise type_error + elif isinstance(arg, uuid.UUID): + if not from_server: + return str(arg) + raise type_error + elif isinstance(arg, decimal.Decimal): + return decimal.Decimal(arg) + elif isinstance(arg, bytes): + return bytes(arg) + elif isinstance(arg, (io.FileIO, io.BufferedReader)): + return FileIO(arg) + raise ValueError('Invalid type passed in got input={} type={}'.format(arg, type(arg))) + + +class ComposedBase(Discriminable): + + @classmethod + def __get_allof_classes(cls, arg, validation_metadata: ValidationMetadata): + path_to_schemas = defaultdict(set) + for allof_cls in cls.MetaOapg.all_of(): + if validation_metadata.validation_ran_earlier(allof_cls): + continue + other_path_to_schemas = allof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __get_oneof_class( + cls, + arg, + discriminated_cls, + validation_metadata: ValidationMetadata, + ): + oneof_classes = [] + path_to_schemas = defaultdict(set) + for oneof_cls in cls.MetaOapg.one_of(): + if oneof_cls in path_to_schemas[validation_metadata.path_to_item]: + oneof_classes.append(oneof_cls) + continue + if validation_metadata.validation_ran_earlier(oneof_cls): + oneof_classes.append(oneof_cls) + continue + try: + path_to_schemas = oneof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and oneof_cls is discriminated_cls: + raise ex + continue + oneof_classes.append(oneof_cls) + if not oneof_classes: + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. None " + "of the oneOf schemas matched the input data.".format(cls) + ) + elif len(oneof_classes) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. Multiple " + "oneOf schemas {} matched the inputs, but a max of one is allowed.".format(cls, oneof_classes) + ) + # exactly one class matches + return path_to_schemas + + @classmethod + def __get_anyof_classes( + cls, + arg, + discriminated_cls, + validation_metadata: ValidationMetadata + ): + anyof_classes = [] + path_to_schemas = defaultdict(set) + for anyof_cls in cls.MetaOapg.any_of(): + if validation_metadata.validation_ran_earlier(anyof_cls): + anyof_classes.append(anyof_cls) + continue + + try: + other_path_to_schemas = anyof_cls._validate_oapg(arg, validation_metadata=validation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and anyof_cls is discriminated_cls: + raise ex + continue + anyof_classes.append(anyof_cls) + update(path_to_schemas, other_path_to_schemas) + if not anyof_classes: + raise ApiValueError( + "Invalid inputs given to generate an instance of {}. None " + "of the anyOf schemas matched the input data.".format(cls) + ) + return path_to_schemas + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]: + """ + ComposedBase _validate_oapg + We return dynamic classes of different bases depending upon the inputs + This makes it so: + - the returned instance is always a subclass of our defining schema + - this allows us to check type based on whether an instance is a subclass of a schema + - the returned instance is a serializable type (except for None, True, and False) which are enums + + Returns: + new_cls (type): the new class + + Raises: + ApiValueError: when a string can't be converted into a date or datetime and it must be one of those classes + ApiTypeError: when the input type is not in the list of allowed spec types + """ + # validation checking on types, validations, and enums + path_to_schemas = super()._validate_oapg(arg, validation_metadata=validation_metadata) + + updated_vm = ValidationMetadata( + configuration=validation_metadata.configuration, + from_server=validation_metadata.from_server, + path_to_item=validation_metadata.path_to_item, + seen_classes=validation_metadata.seen_classes | frozenset({cls}), + validated_path_to_schemas=validation_metadata.validated_path_to_schemas + ) + + # process composed schema + discriminator = None + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'discriminator'): + discriminator = cls.MetaOapg.discriminator() + discriminated_cls = None + if discriminator and arg and isinstance(arg, frozendict.frozendict): + disc_property_name = list(discriminator.keys())[0] + cls._ensure_discriminator_value_present_oapg(disc_property_name, updated_vm, arg) + # get discriminated_cls by looking at the dict in the current class + discriminated_cls = cls.get_discriminated_class_oapg( + disc_property_name=disc_property_name, disc_payload_value=arg[disc_property_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value '{}' was passed in to {}.{} Only the values {} are allowed at {}".format( + arg[disc_property_name], + cls.__name__, + disc_property_name, + list(discriminator[disc_property_name].keys()), + updated_vm.path_to_item + (disc_property_name,) + ) + ) + + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'all_of'): + other_path_to_schemas = cls.__get_allof_classes(arg, validation_metadata=updated_vm) + update(path_to_schemas, other_path_to_schemas) + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'one_of'): + other_path_to_schemas = cls.__get_oneof_class( + arg, + discriminated_cls=discriminated_cls, + validation_metadata=updated_vm + ) + update(path_to_schemas, other_path_to_schemas) + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'any_of'): + other_path_to_schemas = cls.__get_anyof_classes( + arg, + discriminated_cls=discriminated_cls, + validation_metadata=updated_vm + ) + update(path_to_schemas, other_path_to_schemas) + not_cls = None + if hasattr(cls, 'MetaOapg') and hasattr(cls.MetaOapg, 'not_schema'): + not_cls = cls.MetaOapg.not_schema + not_cls = cls._get_class_oapg(not_cls) + if not_cls: + other_path_to_schemas = None + not_exception = ApiValueError( + "Invalid value '{}' was passed in to {}. Value is invalid because it is disallowed by {}".format( + arg, + cls.__name__, + not_cls.__name__, + ) + ) + if updated_vm.validation_ran_earlier(not_cls): + raise not_exception + + try: + other_path_to_schemas = not_cls._validate_oapg(arg, validation_metadata=updated_vm) + except (ApiValueError, ApiTypeError): + pass + if other_path_to_schemas: + raise not_exception + + if discriminated_cls is not None and not updated_vm.validation_ran_earlier(discriminated_cls): + # TODO use an exception from this package here + assert discriminated_cls in path_to_schemas[updated_vm.path_to_item] + return path_to_schemas + + +# DictBase, ListBase, NumberBase, StrBase, BoolBase, NoneBase +class ComposedSchema( + ComposedBase, + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema, + NoneFrozenDictTupleStrDecimalBoolMixin +): + @classmethod + def from_openapi_data_oapg(cls, *args: typing.Any, _configuration: typing.Optional[Configuration] = None, **kwargs): + if not args: + if not kwargs: + raise ApiTypeError('{} is missing required input data in args or kwargs'.format(cls.__name__)) + args = (kwargs, ) + return super().from_openapi_data_oapg(args[0], _configuration=_configuration) + + +class ListSchema( + ListBase, + Schema, + TupleMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: typing.List[typing.Any], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[typing.List[typing.Any], typing.Tuple[typing.Any]], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class NoneSchema( + NoneBase, + Schema, + NoneMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: None, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: None, **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class NumberSchema( + NumberBase, + Schema, + DecimalMixin +): + """ + This is used for type: number with no format + Both integers AND floats are accepted + """ + + @classmethod + def from_openapi_data_oapg(cls, arg: typing.Union[int, float], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[decimal.Decimal, int, float], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class IntBase: + @property + def as_int_oapg(self) -> int: + try: + return self._as_int + except AttributeError: + self._as_int = int(self) + return self._as_int + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + + denominator = arg.as_integer_ratio()[-1] + if denominator != 1: + raise ApiValueError( + "Invalid value '{}' for type integer at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + IntBase _validate_oapg + TODO what about types = (int, number) -> IntBase, NumberBase? We could drop int and keep number only + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class IntSchema(IntBase, NumberSchema): + + @classmethod + def from_openapi_data_oapg(cls, arg: int, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[decimal.Decimal, int], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class Int32Base: + __inclusive_minimum = decimal.Decimal(-2147483648) + __inclusive_maximum = decimal.Decimal(2147483647) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal) and arg.as_tuple().exponent == 0: + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type int32 at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Int32Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Int32Schema( + Int32Base, + IntSchema +): + pass + + +class Int64Base: + __inclusive_minimum = decimal.Decimal(-9223372036854775808) + __inclusive_maximum = decimal.Decimal(9223372036854775807) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal) and arg.as_tuple().exponent == 0: + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type int64 at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Int64Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Int64Schema( + Int64Base, + IntSchema +): + pass + + +class Float32Base: + __inclusive_minimum = decimal.Decimal(-3.4028234663852886e+38) + __inclusive_maximum = decimal.Decimal(3.4028234663852886e+38) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type float at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Float32Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + + +class Float32Schema( + Float32Base, + NumberSchema +): + + @classmethod + def from_openapi_data_oapg(cls, arg: float, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + +class Float64Base: + __inclusive_minimum = decimal.Decimal(-1.7976931348623157E+308) + __inclusive_maximum = decimal.Decimal(1.7976931348623157E+308) + + @classmethod + def __validate_format(cls, arg: typing.Optional[decimal.Decimal], validation_metadata: ValidationMetadata): + if isinstance(arg, decimal.Decimal): + if not cls.__inclusive_minimum <= arg <= cls.__inclusive_maximum: + raise ApiValueError( + "Invalid value '{}' for type double at {}".format(arg, validation_metadata.path_to_item) + ) + + @classmethod + def _validate_oapg( + cls, + arg, + validation_metadata: ValidationMetadata, + ): + """ + Float64Base _validate_oapg + """ + cls.__validate_format(arg, validation_metadata=validation_metadata) + return super()._validate_oapg(arg, validation_metadata=validation_metadata) + +class Float64Schema( + Float64Base, + NumberSchema +): + + @classmethod + def from_openapi_data_oapg(cls, arg: float, _configuration: typing.Optional[Configuration] = None): + # todo check format + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + +class StrSchema( + StrBase, + Schema, + StrMixin +): + """ + date + datetime string types must inherit from this class + That is because one can validate a str payload as both: + - type: string (format unset) + - type: string, format: date + """ + + @classmethod + def from_openapi_data_oapg(cls, arg: str, _configuration: typing.Optional[Configuration] = None) -> 'StrSchema': + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: typing.Union[str, date, datetime, uuid.UUID], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class UUIDSchema(UUIDBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, uuid.UUID], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DateSchema(DateBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, date], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DateTimeSchema(DateTimeBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, datetime], **kwargs: Configuration): + return super().__new__(cls, arg, **kwargs) + + +class DecimalSchema(DecimalBase, StrSchema): + + def __new__(cls, arg: str, **kwargs: Configuration): + """ + Note: Decimals may not be passed in because cast_to_allowed_types is only invoked once for payloads + which can be simple (str) or complex (dicts or lists with nested values) + Because casting is only done once and recursively casts all values prior to validation then for a potential + client side Decimal input if Decimal was accepted as an input in DecimalSchema then one would not know + if one was using it for a StrSchema (where it should be cast to str) or one is using it for NumberSchema + where it should stay as Decimal. + """ + return super().__new__(cls, arg, **kwargs) + + +class BytesSchema( + Schema, + BytesMixin +): + """ + this class will subclass bytes and is immutable + """ + def __new__(cls, arg: bytes, **kwargs: Configuration): + return super(Schema, cls).__new__(cls, arg) + + +class FileSchema( + Schema, + FileMixin +): + """ + This class is NOT immutable + Dynamic classes are built using it for example when AnyType allows in binary data + Al other schema classes ARE immutable + If one wanted to make this immutable one could make this a DictSchema with required properties: + - data = BytesSchema (which would be an immutable bytes based schema) + - file_name = StrSchema + and cast_to_allowed_types would convert bytes and file instances into dicts containing data + file_name + The downside would be that data would be stored in memory which one may not want to do for very large files + + The developer is responsible for closing this file and deleting it + + This class was kept as mutable: + - to allow file reading and writing to disk + - to be able to preserve file name info + """ + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader], **kwargs: Configuration): + return super(Schema, cls).__new__(cls, arg) + + +class BinaryBase: + pass + + +class BinarySchema( + ComposedBase, + BinaryBase, + Schema, + BinaryMixin +): + class MetaOapg: + @staticmethod + def one_of(): + return [ + BytesSchema, + FileSchema, + ] + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader, bytes], **kwargs: Configuration): + return super().__new__(cls, arg) + + +class BoolSchema( + BoolBase, + Schema, + BoolMixin +): + + @classmethod + def from_openapi_data_oapg(cls, arg: bool, _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, arg: bool, **kwargs: ValidationMetadata): + return super().__new__(cls, arg, **kwargs) + + +class AnyTypeSchema( + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema, + NoneFrozenDictTupleStrDecimalBoolFileBytesMixin +): + # Python representation of a schema defined as true or {} + pass + + +class UnsetAnyTypeSchema(AnyTypeSchema): + # Used when additionalProperties/items was not explicitly defined and a defining schema is needed + pass + + +class NotAnyTypeSchema( + ComposedSchema, +): + """ + Python representation of a schema defined as false or {'not': {}} + Does not allow inputs in of AnyType + Note: validations on this class are never run because the code knows that no inputs will ever validate + """ + + class MetaOapg: + not_schema = AnyTypeSchema + + def __new__( + cls, + *args, + _configuration: typing.Optional[Configuration] = None, + ) -> 'NotAnyTypeSchema': + return super().__new__( + cls, + *args, + _configuration=_configuration, + ) + + +class DictSchema( + DictBase, + Schema, + FrozenDictMixin +): + @classmethod + def from_openapi_data_oapg(cls, arg: typing.Dict[str, typing.Any], _configuration: typing.Optional[Configuration] = None): + return super().from_openapi_data_oapg(arg, _configuration=_configuration) + + def __new__(cls, *args: typing.Union[dict, frozendict.frozendict], **kwargs: typing.Union[dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, date, datetime, bool, None, bytes, Schema, Unset, ValidationMetadata]): + return super().__new__(cls, *args, **kwargs) + + +schema_type_classes = {NoneSchema, DictSchema, ListSchema, NumberSchema, StrSchema, BoolSchema, AnyTypeSchema} + + +@functools.lru_cache() +def get_new_class( + class_name: str, + bases: typing.Tuple[typing.Type[typing.Union[Schema, typing.Any]], ...] +) -> typing.Type[Schema]: + """ + Returns a new class that is made with the subclass bases + """ + new_cls: typing.Type[Schema] = type(class_name, bases, {}) + return new_cls + + +LOG_CACHE_USAGE = False + + +def log_cache_usage(cache_fn): + if LOG_CACHE_USAGE: + print(cache_fn.__name__, cache_fn.cache_info()) diff --git a/samples/openapi3/client/petstore/python/petstore_api/signing.py b/samples/openapi3/client/petstore/python/petstore_api/signing.py index 4ea7d8f779..22b3bf2bf1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/signing.py +++ b/samples/openapi3/client/petstore/python/petstore_api/signing.py @@ -1,3 +1,4 @@ +# coding: utf-8 """ OpenAPI Petstore @@ -7,7 +8,6 @@ Generated by: https://openapi-generator.tech """ - from base64 import b64encode from Crypto.IO import PEM, PKCS8 from Crypto.Hash import SHA256, SHA512 @@ -341,7 +341,7 @@ class HttpSigningConfiguration(object): :return: A tuple of (digest, prefix). The digest is a hashing object that contains the cryptographic digest of the HTTP request. - The prefix is a string that identifies the cryptographic hash. It is used + The prefix is a string that identifies the cryptographc hash. It is used to generate the 'Digest' header as specified in RFC 3230. """ if self.hash_algorithm == HASH_SHA512: diff --git a/samples/openapi3/client/petstore/python/pom.xml b/samples/openapi3/client/petstore/python/pom.xml index e7d7d9caf1..7e737c3611 100644 --- a/samples/openapi3/client/petstore/python/pom.xml +++ b/samples/openapi3/client/petstore/python/pom.xml @@ -1,10 +1,10 @@ 4.0.0 org.openapitools - PythonOAS3PetstoreTests + PythonExperimentalOAS3PetstoreTests pom 1.0-SNAPSHOT - Python OpenAPI3 Petstore Client + Python Experimental OpenAPI3 Petstore Client @@ -43,4 +43,4 @@ - + \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/requirements.txt b/samples/openapi3/client/petstore/python/requirements.txt index 96947f6040..342f6630cb 100644 --- a/samples/openapi3/client/petstore/python/requirements.txt +++ b/samples/openapi3/client/petstore/python/requirements.txt @@ -1,3 +1,8 @@ -python_dateutil >= 2.5.3 +certifi >= 14.5.14 +frozendict ~= 2.3.4 +pem >= 19.3.0 +pycryptodome >= 3.9.0 +python-dateutil ~= 2.7.0 setuptools >= 21.0.0 -urllib3 >= 1.25.3 +typing_extensions ~= 4.3.0 +urllib3 ~= 1.26.7 diff --git a/samples/openapi3/client/petstore/python/setup.py b/samples/openapi3/client/petstore/python/setup.py index 0fdf984806..992aa9853b 100644 --- a/samples/openapi3/client/petstore/python/setup.py +++ b/samples/openapi3/client/petstore/python/setup.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -7,7 +9,6 @@ Generated by: https://openapi-generator.tech """ - from setuptools import setup, find_packages # noqa: H301 NAME = "petstore-api" @@ -20,10 +21,14 @@ VERSION = "1.0.0" # http://pypi.python.org/pypi/setuptools REQUIRES = [ - "urllib3 >= 1.25.3", - "python-dateutil", - "pem>=19.3.0", - "pycryptodome>=3.9.0", + "certifi >= 14.5.14", + "frozendict ~= 2.3.4", + "pem >= 19.3.0", + "pycryptodome >= 3.9.0", + "python-dateutil ~= 2.7.0", + "setuptools >= 21.0.0", + "typing_extensions ~= 4.3.0", + "urllib3 ~= 1.26.7", ] setup( @@ -34,7 +39,7 @@ setup( author_email="team@openapitools.org", url="", keywords=["OpenAPI", "OpenAPI-Generator", "OpenAPI Petstore"], - python_requires=">=3.6", + python_requires=">=3.7", install_requires=REQUIRES, packages=find_packages(exclude=["test", "tests"]), include_package_data=True, diff --git a/samples/openapi3/client/petstore/python/test-requirements.txt b/samples/openapi3/client/petstore/python/test-requirements.txt index 4b3736d983..36d9b4fa7a 100644 --- a/samples/openapi3/client/petstore/python/test-requirements.txt +++ b/samples/openapi3/client/petstore/python/test-requirements.txt @@ -1,2 +1,4 @@ +pytest~=4.6.7 # needed for python 3.4 pytest-cov>=2.8.1 +pytest-randomly==1.2.3 # needed for python 3.4 pycryptodome>=3.9.0 diff --git a/samples/openapi3/client/petstore/python/test/test_models/__init__.py b/samples/openapi3/client/petstore/python/test/test_models/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_additional_properties_class.py b/samples/openapi3/client/petstore/python/test/test_models/test_additional_properties_class.py new file mode 100644 index 0000000000..672b8b4876 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_additional_properties_class.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.additional_properties_class import AdditionalPropertiesClass +from petstore_api import configuration + + +class TestAdditionalPropertiesClass(unittest.TestCase): + """AdditionalPropertiesClass unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_additional_properties_validator.py b/samples/openapi3/client/petstore/python/test/test_models/test_additional_properties_validator.py new file mode 100644 index 0000000000..fa0fe198d7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_additional_properties_validator.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.additional_properties_validator import AdditionalPropertiesValidator +from petstore_api import configuration + + +class TestAdditionalPropertiesValidator(unittest.TestCase): + """AdditionalPropertiesValidator unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python/test/test_models/test_additional_properties_with_array_of_enums.py new file mode 100644 index 0000000000..02669a5f7f --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_additional_properties_with_array_of_enums.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.additional_properties_with_array_of_enums import AdditionalPropertiesWithArrayOfEnums +from petstore_api import configuration + + +class TestAdditionalPropertiesWithArrayOfEnums(unittest.TestCase): + """AdditionalPropertiesWithArrayOfEnums unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_address.py b/samples/openapi3/client/petstore/python/test/test_models/test_address.py new file mode 100644 index 0000000000..4bd63aebe1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_address.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.address import Address +from petstore_api import configuration + + +class TestAddress(unittest.TestCase): + """Address unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_animal.py b/samples/openapi3/client/petstore/python/test/test_models/test_animal.py new file mode 100644 index 0000000000..4a9b77d617 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_animal.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.animal import Animal +from petstore_api import configuration + + +class TestAnimal(unittest.TestCase): + """Animal unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_animal_farm.py b/samples/openapi3/client/petstore/python/test/test_models/test_animal_farm.py new file mode 100644 index 0000000000..4237b91351 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_animal_farm.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.animal_farm import AnimalFarm +from petstore_api import configuration + + +class TestAnimalFarm(unittest.TestCase): + """AnimalFarm unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_any_type_and_format.py b/samples/openapi3/client/petstore/python/test/test_models/test_any_type_and_format.py new file mode 100644 index 0000000000..dbd95d3b02 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_any_type_and_format.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.any_type_and_format import AnyTypeAndFormat +from petstore_api import configuration + + +class TestAnyTypeAndFormat(unittest.TestCase): + """AnyTypeAndFormat unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_any_type_not_string.py b/samples/openapi3/client/petstore/python/test/test_models/test_any_type_not_string.py new file mode 100644 index 0000000000..74de79873d --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_any_type_not_string.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.any_type_not_string import AnyTypeNotString +from petstore_api import configuration + + +class TestAnyTypeNotString(unittest.TestCase): + """AnyTypeNotString unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_api_response.py b/samples/openapi3/client/petstore/python/test/test_models/test_api_response.py new file mode 100644 index 0000000000..2631b83ff3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_api_response.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.api_response import ApiResponse +from petstore_api import configuration + + +class TestApiResponse(unittest.TestCase): + """ApiResponse unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_apple.py b/samples/openapi3/client/petstore/python/test/test_models/test_apple.py new file mode 100644 index 0000000000..66c9241a73 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_apple.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.apple import Apple +from petstore_api import configuration + + +class TestApple(unittest.TestCase): + """Apple unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_apple_req.py b/samples/openapi3/client/petstore/python/test/test_models/test_apple_req.py new file mode 100644 index 0000000000..4d20e890cf --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_apple_req.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.apple_req import AppleReq +from petstore_api import configuration + + +class TestAppleReq(unittest.TestCase): + """AppleReq unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_array_holding_any_type.py b/samples/openapi3/client/petstore/python/test/test_models/test_array_holding_any_type.py new file mode 100644 index 0000000000..bb9a2603a0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_array_holding_any_type.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.array_holding_any_type import ArrayHoldingAnyType +from petstore_api import configuration + + +class TestArrayHoldingAnyType(unittest.TestCase): + """ArrayHoldingAnyType unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python/test/test_models/test_array_of_array_of_number_only.py new file mode 100644 index 0000000000..9991efe657 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_array_of_array_of_number_only.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly +from petstore_api import configuration + + +class TestArrayOfArrayOfNumberOnly(unittest.TestCase): + """ArrayOfArrayOfNumberOnly unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_array_of_enums.py b/samples/openapi3/client/petstore/python/test/test_models/test_array_of_enums.py new file mode 100644 index 0000000000..1040dabae9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_array_of_enums.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.array_of_enums import ArrayOfEnums +from petstore_api import configuration + + +class TestArrayOfEnums(unittest.TestCase): + """ArrayOfEnums unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_array_of_number_only.py b/samples/openapi3/client/petstore/python/test/test_models/test_array_of_number_only.py new file mode 100644 index 0000000000..9eca2c7a9e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_array_of_number_only.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.array_of_number_only import ArrayOfNumberOnly +from petstore_api import configuration + + +class TestArrayOfNumberOnly(unittest.TestCase): + """ArrayOfNumberOnly unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_array_test.py b/samples/openapi3/client/petstore/python/test/test_models/test_array_test.py new file mode 100644 index 0000000000..3c5610cd20 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_array_test.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.array_test import ArrayTest +from petstore_api import configuration + + +class TestArrayTest(unittest.TestCase): + """ArrayTest unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_array_with_validations_in_items.py b/samples/openapi3/client/petstore/python/test/test_models/test_array_with_validations_in_items.py new file mode 100644 index 0000000000..6c38306b1e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_array_with_validations_in_items.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.array_with_validations_in_items import ArrayWithValidationsInItems +from petstore_api import configuration + + +class TestArrayWithValidationsInItems(unittest.TestCase): + """ArrayWithValidationsInItems unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_banana.py b/samples/openapi3/client/petstore/python/test/test_models/test_banana.py new file mode 100644 index 0000000000..a0406ea1b8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_banana.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.banana import Banana +from petstore_api import configuration + + +class TestBanana(unittest.TestCase): + """Banana unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_banana_req.py b/samples/openapi3/client/petstore/python/test/test_models/test_banana_req.py new file mode 100644 index 0000000000..39ac3c4045 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_banana_req.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.banana_req import BananaReq +from petstore_api import configuration + + +class TestBananaReq(unittest.TestCase): + """BananaReq unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_bar.py b/samples/openapi3/client/petstore/python/test/test_models/test_bar.py new file mode 100644 index 0000000000..52419122ba --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_bar.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.bar import Bar +from petstore_api import configuration + + +class TestBar(unittest.TestCase): + """Bar unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_basque_pig.py b/samples/openapi3/client/petstore/python/test/test_models/test_basque_pig.py new file mode 100644 index 0000000000..f21a84f4dc --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_basque_pig.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.basque_pig import BasquePig +from petstore_api import configuration + + +class TestBasquePig(unittest.TestCase): + """BasquePig unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_boolean.py b/samples/openapi3/client/petstore/python/test/test_models/test_boolean.py new file mode 100644 index 0000000000..cb65350ae5 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_boolean.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.boolean import Boolean +from petstore_api import configuration + + +class TestBoolean(unittest.TestCase): + """Boolean unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_boolean_enum.py b/samples/openapi3/client/petstore/python/test/test_models/test_boolean_enum.py new file mode 100644 index 0000000000..0a1a1fa3cb --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_boolean_enum.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.boolean_enum import BooleanEnum +from petstore_api import configuration + + +class TestBooleanEnum(unittest.TestCase): + """BooleanEnum unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_capitalization.py b/samples/openapi3/client/petstore/python/test/test_models/test_capitalization.py new file mode 100644 index 0000000000..a595cfd15a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_capitalization.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.capitalization import Capitalization +from petstore_api import configuration + + +class TestCapitalization(unittest.TestCase): + """Capitalization unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_cat.py b/samples/openapi3/client/petstore/python/test/test_models/test_cat.py new file mode 100644 index 0000000000..c8330904ba --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_cat.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.cat import Cat +from petstore_api import configuration + + +class TestCat(unittest.TestCase): + """Cat unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_category.py b/samples/openapi3/client/petstore/python/test/test_models/test_category.py new file mode 100644 index 0000000000..ef8f9dcdf4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_category.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.category import Category +from petstore_api import configuration + + +class TestCategory(unittest.TestCase): + """Category unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_child_cat.py b/samples/openapi3/client/petstore/python/test/test_models/test_child_cat.py new file mode 100644 index 0000000000..724f0e593c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_child_cat.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.child_cat import ChildCat +from petstore_api import configuration + + +class TestChildCat(unittest.TestCase): + """ChildCat unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_class_model.py b/samples/openapi3/client/petstore/python/test/test_models/test_class_model.py new file mode 100644 index 0000000000..133ffbab20 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_class_model.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.class_model import ClassModel +from petstore_api import configuration + + +class TestClassModel(unittest.TestCase): + """ClassModel unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_client.py b/samples/openapi3/client/petstore/python/test/test_models/test_client.py new file mode 100644 index 0000000000..6849d17a0e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_client.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.client import Client +from petstore_api import configuration + + +class TestClient(unittest.TestCase): + """Client unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_complex_quadrilateral.py b/samples/openapi3/client/petstore/python/test/test_models/test_complex_quadrilateral.py new file mode 100644 index 0000000000..0391cbde55 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_complex_quadrilateral.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral +from petstore_api import configuration + + +class TestComplexQuadrilateral(unittest.TestCase): + """ComplexQuadrilateral unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_composed_any_of_different_types_no_validations.py b/samples/openapi3/client/petstore/python/test/test_models/test_composed_any_of_different_types_no_validations.py new file mode 100644 index 0000000000..0acd76ea3a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_composed_any_of_different_types_no_validations.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.composed_any_of_different_types_no_validations import ComposedAnyOfDifferentTypesNoValidations +from petstore_api import configuration + + +class TestComposedAnyOfDifferentTypesNoValidations(unittest.TestCase): + """ComposedAnyOfDifferentTypesNoValidations unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_composed_array.py b/samples/openapi3/client/petstore/python/test/test_models/test_composed_array.py new file mode 100644 index 0000000000..20b69b37bc --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_composed_array.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.composed_array import ComposedArray +from petstore_api import configuration + + +class TestComposedArray(unittest.TestCase): + """ComposedArray unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_composed_bool.py b/samples/openapi3/client/petstore/python/test/test_models/test_composed_bool.py new file mode 100644 index 0000000000..24d0a27905 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_composed_bool.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.composed_bool import ComposedBool +from petstore_api import configuration + + +class TestComposedBool(unittest.TestCase): + """ComposedBool unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_composed_none.py b/samples/openapi3/client/petstore/python/test/test_models/test_composed_none.py new file mode 100644 index 0000000000..8fdacab439 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_composed_none.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.composed_none import ComposedNone +from petstore_api import configuration + + +class TestComposedNone(unittest.TestCase): + """ComposedNone unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_composed_number.py b/samples/openapi3/client/petstore/python/test/test_models/test_composed_number.py new file mode 100644 index 0000000000..14a26ab11f --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_composed_number.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.composed_number import ComposedNumber +from petstore_api import configuration + + +class TestComposedNumber(unittest.TestCase): + """ComposedNumber unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_composed_object.py b/samples/openapi3/client/petstore/python/test/test_models/test_composed_object.py new file mode 100644 index 0000000000..dfc7d53560 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_composed_object.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.composed_object import ComposedObject +from petstore_api import configuration + + +class TestComposedObject(unittest.TestCase): + """ComposedObject unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_composed_one_of_different_types.py b/samples/openapi3/client/petstore/python/test/test_models/test_composed_one_of_different_types.py new file mode 100644 index 0000000000..6c003f5468 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_composed_one_of_different_types.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes +from petstore_api import configuration + + +class TestComposedOneOfDifferentTypes(unittest.TestCase): + """ComposedOneOfDifferentTypes unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_composed_string.py b/samples/openapi3/client/petstore/python/test/test_models/test_composed_string.py new file mode 100644 index 0000000000..943dceabba --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_composed_string.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.composed_string import ComposedString +from petstore_api import configuration + + +class TestComposedString(unittest.TestCase): + """ComposedString unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_currency.py b/samples/openapi3/client/petstore/python/test/test_models/test_currency.py new file mode 100644 index 0000000000..cb57f69cfd --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_currency.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.currency import Currency +from petstore_api import configuration + + +class TestCurrency(unittest.TestCase): + """Currency unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_danish_pig.py b/samples/openapi3/client/petstore/python/test/test_models/test_danish_pig.py new file mode 100644 index 0000000000..600c5d2b42 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_danish_pig.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.danish_pig import DanishPig +from petstore_api import configuration + + +class TestDanishPig(unittest.TestCase): + """DanishPig unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_date_time_test.py b/samples/openapi3/client/petstore/python/test/test_models/test_date_time_test.py new file mode 100644 index 0000000000..4dca8a44e0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_date_time_test.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.date_time_test import DateTimeTest +from petstore_api import configuration + + +class TestDateTimeTest(unittest.TestCase): + """DateTimeTest unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_date_time_with_validations.py b/samples/openapi3/client/petstore/python/test/test_models/test_date_time_with_validations.py new file mode 100644 index 0000000000..bb42a49ca2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_date_time_with_validations.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.date_time_with_validations import DateTimeWithValidations +from petstore_api import configuration + + +class TestDateTimeWithValidations(unittest.TestCase): + """DateTimeWithValidations unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_date_with_validations.py b/samples/openapi3/client/petstore/python/test/test_models/test_date_with_validations.py new file mode 100644 index 0000000000..f69834dbe4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_date_with_validations.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.date_with_validations import DateWithValidations +from petstore_api import configuration + + +class TestDateWithValidations(unittest.TestCase): + """DateWithValidations unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_decimal_payload.py b/samples/openapi3/client/petstore/python/test/test_models/test_decimal_payload.py new file mode 100644 index 0000000000..cbdc32d522 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_decimal_payload.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.decimal_payload import DecimalPayload +from petstore_api import configuration + + +class TestDecimalPayload(unittest.TestCase): + """DecimalPayload unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_dog.py b/samples/openapi3/client/petstore/python/test/test_models/test_dog.py new file mode 100644 index 0000000000..b98ff3d616 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_dog.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.dog import Dog +from petstore_api import configuration + + +class TestDog(unittest.TestCase): + """Dog unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_drawing.py b/samples/openapi3/client/petstore/python/test/test_models/test_drawing.py new file mode 100644 index 0000000000..ef7ebae224 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_drawing.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.drawing import Drawing +from petstore_api import configuration + + +class TestDrawing(unittest.TestCase): + """Drawing unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_enum_arrays.py b/samples/openapi3/client/petstore/python/test/test_models/test_enum_arrays.py new file mode 100644 index 0000000000..9677bdb09d --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_enum_arrays.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.enum_arrays import EnumArrays +from petstore_api import configuration + + +class TestEnumArrays(unittest.TestCase): + """EnumArrays unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_enum_class.py b/samples/openapi3/client/petstore/python/test/test_models/test_enum_class.py new file mode 100644 index 0000000000..186d2f9ea4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_enum_class.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.enum_class import EnumClass +from petstore_api import configuration + + +class TestEnumClass(unittest.TestCase): + """EnumClass unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_enum_test.py b/samples/openapi3/client/petstore/python/test/test_models/test_enum_test.py new file mode 100644 index 0000000000..12b5a83ecc --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_enum_test.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.enum_test import EnumTest +from petstore_api import configuration + + +class TestEnumTest(unittest.TestCase): + """EnumTest unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_equilateral_triangle.py b/samples/openapi3/client/petstore/python/test/test_models/test_equilateral_triangle.py new file mode 100644 index 0000000000..a730b002a1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_equilateral_triangle.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.equilateral_triangle import EquilateralTriangle +from petstore_api import configuration + + +class TestEquilateralTriangle(unittest.TestCase): + """EquilateralTriangle unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_file.py b/samples/openapi3/client/petstore/python/test/test_models/test_file.py new file mode 100644 index 0000000000..f16976abaf --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_file.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.file import File +from petstore_api import configuration + + +class TestFile(unittest.TestCase): + """File unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_file_schema_test_class.py b/samples/openapi3/client/petstore/python/test/test_models/test_file_schema_test_class.py new file mode 100644 index 0000000000..804b3929aa --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_file_schema_test_class.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.file_schema_test_class import FileSchemaTestClass +from petstore_api import configuration + + +class TestFileSchemaTestClass(unittest.TestCase): + """FileSchemaTestClass unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_foo.py b/samples/openapi3/client/petstore/python/test/test_models/test_foo.py new file mode 100644 index 0000000000..b7f7f822e3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_foo.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.foo import Foo +from petstore_api import configuration + + +class TestFoo(unittest.TestCase): + """Foo unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_format_test.py b/samples/openapi3/client/petstore/python/test/test_models/test_format_test.py new file mode 100644 index 0000000000..2926014379 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_format_test.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.format_test import FormatTest +from petstore_api import configuration + + +class TestFormatTest(unittest.TestCase): + """FormatTest unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_from_schema.py b/samples/openapi3/client/petstore/python/test/test_models/test_from_schema.py new file mode 100644 index 0000000000..09cf54a1f6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_from_schema.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.from_schema import FromSchema +from petstore_api import configuration + + +class TestFromSchema(unittest.TestCase): + """FromSchema unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_fruit.py b/samples/openapi3/client/petstore/python/test/test_models/test_fruit.py new file mode 100644 index 0000000000..18d6acdbbb --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_fruit.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.fruit import Fruit +from petstore_api import configuration + + +class TestFruit(unittest.TestCase): + """Fruit unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_fruit_req.py b/samples/openapi3/client/petstore/python/test/test_models/test_fruit_req.py new file mode 100644 index 0000000000..b3b595f5f2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_fruit_req.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.fruit_req import FruitReq +from petstore_api import configuration + + +class TestFruitReq(unittest.TestCase): + """FruitReq unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_gm_fruit.py b/samples/openapi3/client/petstore/python/test/test_models/test_gm_fruit.py new file mode 100644 index 0000000000..af0199ec49 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_gm_fruit.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.gm_fruit import GmFruit +from petstore_api import configuration + + +class TestGmFruit(unittest.TestCase): + """GmFruit unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_grandparent_animal.py b/samples/openapi3/client/petstore/python/test/test_models/test_grandparent_animal.py new file mode 100644 index 0000000000..748ebdd5b9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_grandparent_animal.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.grandparent_animal import GrandparentAnimal +from petstore_api import configuration + + +class TestGrandparentAnimal(unittest.TestCase): + """GrandparentAnimal unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_has_only_read_only.py b/samples/openapi3/client/petstore/python/test/test_models/test_has_only_read_only.py new file mode 100644 index 0000000000..84e2c36490 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_has_only_read_only.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.has_only_read_only import HasOnlyReadOnly +from petstore_api import configuration + + +class TestHasOnlyReadOnly(unittest.TestCase): + """HasOnlyReadOnly unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_health_check_result.py b/samples/openapi3/client/petstore/python/test/test_models/test_health_check_result.py new file mode 100644 index 0000000000..cfbd718049 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_health_check_result.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.health_check_result import HealthCheckResult +from petstore_api import configuration + + +class TestHealthCheckResult(unittest.TestCase): + """HealthCheckResult unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum.py b/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum.py new file mode 100644 index 0000000000..7cdaa27f8a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.integer_enum import IntegerEnum +from petstore_api import configuration + + +class TestIntegerEnum(unittest.TestCase): + """IntegerEnum unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum_big.py b/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum_big.py new file mode 100644 index 0000000000..64f39bd58c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum_big.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.integer_enum_big import IntegerEnumBig +from petstore_api import configuration + + +class TestIntegerEnumBig(unittest.TestCase): + """IntegerEnumBig unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum_one_value.py b/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum_one_value.py new file mode 100644 index 0000000000..16052a6086 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum_one_value.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue +from petstore_api import configuration + + +class TestIntegerEnumOneValue(unittest.TestCase): + """IntegerEnumOneValue unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum_with_default_value.py b/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum_with_default_value.py new file mode 100644 index 0000000000..ffa57385fb --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_integer_enum_with_default_value.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.integer_enum_with_default_value import IntegerEnumWithDefaultValue +from petstore_api import configuration + + +class TestIntegerEnumWithDefaultValue(unittest.TestCase): + """IntegerEnumWithDefaultValue unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_integer_max10.py b/samples/openapi3/client/petstore/python/test/test_models/test_integer_max10.py new file mode 100644 index 0000000000..46d8c0a725 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_integer_max10.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.integer_max10 import IntegerMax10 +from petstore_api import configuration + + +class TestIntegerMax10(unittest.TestCase): + """IntegerMax10 unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_integer_min15.py b/samples/openapi3/client/petstore/python/test/test_models/test_integer_min15.py new file mode 100644 index 0000000000..660bf12cd6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_integer_min15.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.integer_min15 import IntegerMin15 +from petstore_api import configuration + + +class TestIntegerMin15(unittest.TestCase): + """IntegerMin15 unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_isosceles_triangle.py b/samples/openapi3/client/petstore/python/test/test_models/test_isosceles_triangle.py new file mode 100644 index 0000000000..4d82f1056a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_isosceles_triangle.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.isosceles_triangle import IsoscelesTriangle +from petstore_api import configuration + + +class TestIsoscelesTriangle(unittest.TestCase): + """IsoscelesTriangle unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request.py b/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request.py new file mode 100644 index 0000000000..87ab0b2761 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.json_patch_request import JSONPatchRequest +from petstore_api import configuration + + +class TestJSONPatchRequest(unittest.TestCase): + """JSONPatchRequest unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request_add_replace_test.py b/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request_add_replace_test.py new file mode 100644 index 0000000000..bcabf025af --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request_add_replace_test.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.json_patch_request_add_replace_test import JSONPatchRequestAddReplaceTest +from petstore_api import configuration + + +class TestJSONPatchRequestAddReplaceTest(unittest.TestCase): + """JSONPatchRequestAddReplaceTest unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request_move_copy.py b/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request_move_copy.py new file mode 100644 index 0000000000..388b38f27a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request_move_copy.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.json_patch_request_move_copy import JSONPatchRequestMoveCopy +from petstore_api import configuration + + +class TestJSONPatchRequestMoveCopy(unittest.TestCase): + """JSONPatchRequestMoveCopy unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request_remove.py b/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request_remove.py new file mode 100644 index 0000000000..fe2001a85c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_json_patch_request_remove.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.json_patch_request_remove import JSONPatchRequestRemove +from petstore_api import configuration + + +class TestJSONPatchRequestRemove(unittest.TestCase): + """JSONPatchRequestRemove unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_mammal.py b/samples/openapi3/client/petstore/python/test/test_models/test_mammal.py new file mode 100644 index 0000000000..402d785f46 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_mammal.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.mammal import Mammal +from petstore_api import configuration + + +class TestMammal(unittest.TestCase): + """Mammal unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_map_test.py b/samples/openapi3/client/petstore/python/test/test_models/test_map_test.py new file mode 100644 index 0000000000..c07747e22a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_map_test.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.map_test import MapTest +from petstore_api import configuration + + +class TestMapTest(unittest.TestCase): + """MapTest unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python/test/test_models/test_mixed_properties_and_additional_properties_class.py new file mode 100644 index 0000000000..aa8f05809e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_mixed_properties_and_additional_properties_class.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from petstore_api import configuration + + +class TestMixedPropertiesAndAdditionalPropertiesClass(unittest.TestCase): + """MixedPropertiesAndAdditionalPropertiesClass unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_model200_response.py b/samples/openapi3/client/petstore/python/test/test_models/test_model200_response.py new file mode 100644 index 0000000000..175bce1157 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_model200_response.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.model200_response import Model200Response +from petstore_api import configuration + + +class TestModel200Response(unittest.TestCase): + """Model200Response unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_model_return.py b/samples/openapi3/client/petstore/python/test/test_models/test_model_return.py new file mode 100644 index 0000000000..97cc726a7a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_model_return.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.model_return import ModelReturn +from petstore_api import configuration + + +class TestModelReturn(unittest.TestCase): + """ModelReturn unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_money.py b/samples/openapi3/client/petstore/python/test/test_models/test_money.py new file mode 100644 index 0000000000..51977ceb52 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_money.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.money import Money +from petstore_api import configuration + + +class TestMoney(unittest.TestCase): + """Money unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_name.py b/samples/openapi3/client/petstore/python/test/test_models/test_name.py new file mode 100644 index 0000000000..67aa393738 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_name.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.name import Name +from petstore_api import configuration + + +class TestName(unittest.TestCase): + """Name unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_no_additional_properties.py b/samples/openapi3/client/petstore/python/test/test_models/test_no_additional_properties.py new file mode 100644 index 0000000000..560d41b85b --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_no_additional_properties.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.no_additional_properties import NoAdditionalProperties +from petstore_api import configuration + + +class TestNoAdditionalProperties(unittest.TestCase): + """NoAdditionalProperties unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_nullable_class.py b/samples/openapi3/client/petstore/python/test/test_models/test_nullable_class.py new file mode 100644 index 0000000000..48e6a9dfca --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_nullable_class.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.nullable_class import NullableClass +from petstore_api import configuration + + +class TestNullableClass(unittest.TestCase): + """NullableClass unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_nullable_shape.py b/samples/openapi3/client/petstore/python/test/test_models/test_nullable_shape.py new file mode 100644 index 0000000000..5fbf48eb04 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_nullable_shape.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.nullable_shape import NullableShape +from petstore_api import configuration + + +class TestNullableShape(unittest.TestCase): + """NullableShape unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_nullable_string.py b/samples/openapi3/client/petstore/python/test/test_models/test_nullable_string.py new file mode 100644 index 0000000000..e25a516b7c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_nullable_string.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.nullable_string import NullableString +from petstore_api import configuration + + +class TestNullableString(unittest.TestCase): + """NullableString unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_number.py b/samples/openapi3/client/petstore/python/test/test_models/test_number.py new file mode 100644 index 0000000000..3a82e0c8ac --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_number.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.number import Number +from petstore_api import configuration + + +class TestNumber(unittest.TestCase): + """Number unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_number_only.py b/samples/openapi3/client/petstore/python/test/test_models/test_number_only.py new file mode 100644 index 0000000000..58b824ecd8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_number_only.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.number_only import NumberOnly +from petstore_api import configuration + + +class TestNumberOnly(unittest.TestCase): + """NumberOnly unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_number_with_validations.py b/samples/openapi3/client/petstore/python/test/test_models/test_number_with_validations.py new file mode 100644 index 0000000000..a407491018 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_number_with_validations.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.number_with_validations import NumberWithValidations +from petstore_api import configuration + + +class TestNumberWithValidations(unittest.TestCase): + """NumberWithValidations unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_object_interface.py b/samples/openapi3/client/petstore/python/test/test_models/test_object_interface.py new file mode 100644 index 0000000000..3745bece9d --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_object_interface.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.object_interface import ObjectInterface +from petstore_api import configuration + + +class TestObjectInterface(unittest.TestCase): + """ObjectInterface unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_object_model_with_ref_props.py b/samples/openapi3/client/petstore/python/test/test_models/test_object_model_with_ref_props.py new file mode 100644 index 0000000000..76145b49d0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_object_model_with_ref_props.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from petstore_api import configuration + + +class TestObjectModelWithRefProps(unittest.TestCase): + """ObjectModelWithRefProps unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_object_with_decimal_properties.py b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_decimal_properties.py new file mode 100644 index 0000000000..061eee9471 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_decimal_properties.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.object_with_decimal_properties import ObjectWithDecimalProperties +from petstore_api import configuration + + +class TestObjectWithDecimalProperties(unittest.TestCase): + """ObjectWithDecimalProperties unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_object_with_difficultly_named_props.py b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_difficultly_named_props.py new file mode 100644 index 0000000000..531aa29e49 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_difficultly_named_props.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.object_with_difficultly_named_props import ObjectWithDifficultlyNamedProps +from petstore_api import configuration + + +class TestObjectWithDifficultlyNamedProps(unittest.TestCase): + """ObjectWithDifficultlyNamedProps unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_object_with_inline_composition_property.py b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_inline_composition_property.py new file mode 100644 index 0000000000..4d2ebb2ae4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_inline_composition_property.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.object_with_inline_composition_property import ObjectWithInlineCompositionProperty +from petstore_api import configuration + + +class TestObjectWithInlineCompositionProperty(unittest.TestCase): + """ObjectWithInlineCompositionProperty unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_object_with_invalid_named_refed_properties.py b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_invalid_named_refed_properties.py new file mode 100644 index 0000000000..b4bae2d5e6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_invalid_named_refed_properties.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.object_with_invalid_named_refed_properties import ObjectWithInvalidNamedRefedProperties +from petstore_api import configuration + + +class TestObjectWithInvalidNamedRefedProperties(unittest.TestCase): + """ObjectWithInvalidNamedRefedProperties unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_object_with_validations.py b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_validations.py new file mode 100644 index 0000000000..61aa651da9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_object_with_validations.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.object_with_validations import ObjectWithValidations +from petstore_api import configuration + + +class TestObjectWithValidations(unittest.TestCase): + """ObjectWithValidations unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_order.py b/samples/openapi3/client/petstore/python/test/test_models/test_order.py new file mode 100644 index 0000000000..a46866bc95 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_order.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.order import Order +from petstore_api import configuration + + +class TestOrder(unittest.TestCase): + """Order unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_parent_pet.py b/samples/openapi3/client/petstore/python/test/test_models/test_parent_pet.py new file mode 100644 index 0000000000..1a738ebadc --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_parent_pet.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.parent_pet import ParentPet +from petstore_api import configuration + + +class TestParentPet(unittest.TestCase): + """ParentPet unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_pet.py b/samples/openapi3/client/petstore/python/test/test_models/test_pet.py new file mode 100644 index 0000000000..bfe07aec75 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_pet.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.pet import Pet +from petstore_api import configuration + + +class TestPet(unittest.TestCase): + """Pet unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_pig.py b/samples/openapi3/client/petstore/python/test/test_models/test_pig.py new file mode 100644 index 0000000000..17e9f30ed2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_pig.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.pig import Pig +from petstore_api import configuration + + +class TestPig(unittest.TestCase): + """Pig unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_player.py b/samples/openapi3/client/petstore/python/test/test_models/test_player.py new file mode 100644 index 0000000000..3a8ce50907 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_player.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.player import Player +from petstore_api import configuration + + +class TestPlayer(unittest.TestCase): + """Player unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_quadrilateral.py b/samples/openapi3/client/petstore/python/test/test_models/test_quadrilateral.py new file mode 100644 index 0000000000..14db504bcf --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_quadrilateral.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.quadrilateral import Quadrilateral +from petstore_api import configuration + + +class TestQuadrilateral(unittest.TestCase): + """Quadrilateral unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_quadrilateral_interface.py b/samples/openapi3/client/petstore/python/test/test_models/test_quadrilateral_interface.py new file mode 100644 index 0000000000..bd903fc4f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_quadrilateral_interface.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.quadrilateral_interface import QuadrilateralInterface +from petstore_api import configuration + + +class TestQuadrilateralInterface(unittest.TestCase): + """QuadrilateralInterface unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_read_only_first.py b/samples/openapi3/client/petstore/python/test/test_models/test_read_only_first.py new file mode 100644 index 0000000000..12a8689951 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_read_only_first.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.read_only_first import ReadOnlyFirst +from petstore_api import configuration + + +class TestReadOnlyFirst(unittest.TestCase): + """ReadOnlyFirst unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_scalene_triangle.py b/samples/openapi3/client/petstore/python/test/test_models/test_scalene_triangle.py new file mode 100644 index 0000000000..3d0ba995a6 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_scalene_triangle.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.scalene_triangle import ScaleneTriangle +from petstore_api import configuration + + +class TestScaleneTriangle(unittest.TestCase): + """ScaleneTriangle unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_shape.py b/samples/openapi3/client/petstore/python/test/test_models/test_shape.py new file mode 100644 index 0000000000..644bae29d8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_shape.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.shape import Shape +from petstore_api import configuration + + +class TestShape(unittest.TestCase): + """Shape unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_shape_or_null.py b/samples/openapi3/client/petstore/python/test/test_models/test_shape_or_null.py new file mode 100644 index 0000000000..1c91dc2c7c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_shape_or_null.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.shape_or_null import ShapeOrNull +from petstore_api import configuration + + +class TestShapeOrNull(unittest.TestCase): + """ShapeOrNull unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_simple_quadrilateral.py b/samples/openapi3/client/petstore/python/test/test_models/test_simple_quadrilateral.py new file mode 100644 index 0000000000..d548e8549c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_simple_quadrilateral.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.simple_quadrilateral import SimpleQuadrilateral +from petstore_api import configuration + + +class TestSimpleQuadrilateral(unittest.TestCase): + """SimpleQuadrilateral unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_some_object.py b/samples/openapi3/client/petstore/python/test/test_models/test_some_object.py new file mode 100644 index 0000000000..8e5c966c58 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_some_object.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.some_object import SomeObject +from petstore_api import configuration + + +class TestSomeObject(unittest.TestCase): + """SomeObject unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_special_model_name.py b/samples/openapi3/client/petstore/python/test/test_models/test_special_model_name.py new file mode 100644 index 0000000000..d6f945d069 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_special_model_name.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.special_model_name import SpecialModelName +from petstore_api import configuration + + +class TestSpecialModelName(unittest.TestCase): + """SpecialModelName unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_string.py b/samples/openapi3/client/petstore/python/test/test_models/test_string.py new file mode 100644 index 0000000000..b868db5000 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_string.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.string import String +from petstore_api import configuration + + +class TestString(unittest.TestCase): + """String unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_string_boolean_map.py b/samples/openapi3/client/petstore/python/test/test_models/test_string_boolean_map.py new file mode 100644 index 0000000000..c24f051d9e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_string_boolean_map.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.string_boolean_map import StringBooleanMap +from petstore_api import configuration + + +class TestStringBooleanMap(unittest.TestCase): + """StringBooleanMap unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_string_enum.py b/samples/openapi3/client/petstore/python/test/test_models/test_string_enum.py new file mode 100644 index 0000000000..eb44771116 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_string_enum.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.string_enum import StringEnum +from petstore_api import configuration + + +class TestStringEnum(unittest.TestCase): + """StringEnum unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_string_enum_with_default_value.py b/samples/openapi3/client/petstore/python/test/test_models/test_string_enum_with_default_value.py new file mode 100644 index 0000000000..c7d690c6ad --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_string_enum_with_default_value.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.string_enum_with_default_value import StringEnumWithDefaultValue +from petstore_api import configuration + + +class TestStringEnumWithDefaultValue(unittest.TestCase): + """StringEnumWithDefaultValue unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_string_with_validation.py b/samples/openapi3/client/petstore/python/test/test_models/test_string_with_validation.py new file mode 100644 index 0000000000..3f08996edf --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_string_with_validation.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.string_with_validation import StringWithValidation +from petstore_api import configuration + + +class TestStringWithValidation(unittest.TestCase): + """StringWithValidation unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_tag.py b/samples/openapi3/client/petstore/python/test/test_models/test_tag.py new file mode 100644 index 0000000000..037216a10f --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_tag.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.tag import Tag +from petstore_api import configuration + + +class TestTag(unittest.TestCase): + """Tag unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_triangle.py b/samples/openapi3/client/petstore/python/test/test_models/test_triangle.py new file mode 100644 index 0000000000..853f1e1416 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_triangle.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.triangle import Triangle +from petstore_api import configuration + + +class TestTriangle(unittest.TestCase): + """Triangle unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_triangle_interface.py b/samples/openapi3/client/petstore/python/test/test_models/test_triangle_interface.py new file mode 100644 index 0000000000..75fddda7d9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_triangle_interface.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.triangle_interface import TriangleInterface +from petstore_api import configuration + + +class TestTriangleInterface(unittest.TestCase): + """TriangleInterface unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_user.py b/samples/openapi3/client/petstore/python/test/test_models/test_user.py new file mode 100644 index 0000000000..fcc8d79b3e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_user.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.user import User +from petstore_api import configuration + + +class TestUser(unittest.TestCase): + """User unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_uuid_string.py b/samples/openapi3/client/petstore/python/test/test_models/test_uuid_string.py new file mode 100644 index 0000000000..27a64c0c44 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_uuid_string.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.uuid_string import UUIDString +from petstore_api import configuration + + +class TestUUIDString(unittest.TestCase): + """UUIDString unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_whale.py b/samples/openapi3/client/petstore/python/test/test_models/test_whale.py new file mode 100644 index 0000000000..b3316eb84a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_whale.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.whale import Whale +from petstore_api import configuration + + +class TestWhale(unittest.TestCase): + """Whale unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_models/test_zebra.py b/samples/openapi3/client/petstore/python/test/test_models/test_zebra.py new file mode 100644 index 0000000000..a3ce520e9d --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_models/test_zebra.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.zebra import Zebra +from petstore_api import configuration + + +class TestZebra(unittest.TestCase): + """Zebra unit test stubs""" + _configuration = configuration.Configuration() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/__init__.py new file mode 100644 index 0000000000..1309632d3d --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/__init__.py @@ -0,0 +1,68 @@ +import json +import typing + +import urllib3 +from urllib3._collections import HTTPHeaderDict + + +class ApiTestMixin: + json_content_type = 'application/json' + user_agent = 'OpenAPI-Generator/1.0.0/python' + + @classmethod + def assert_pool_manager_request_called_with( + cls, + mock_request, + url: str, + method: str = 'POST', + body: typing.Optional[bytes] = None, + content_type: typing.Optional[str] = None, + accept_content_type: typing.Optional[str] = None, + stream: bool = False, + ): + headers = { + 'User-Agent': cls.user_agent + } + if accept_content_type: + headers['Accept'] = accept_content_type + if content_type: + headers['Content-Type'] = content_type + kwargs = dict( + headers=HTTPHeaderDict(headers), + preload_content=not stream, + timeout=None, + ) + if content_type and method != 'GET': + kwargs['body'] = body + mock_request.assert_called_with( + method, + url, + **kwargs + ) + + @staticmethod + def headers_for_content_type(content_type: str) -> typing.Dict[str, str]: + return {'content-type': content_type} + + @classmethod + def response( + cls, + body: typing.Union[str, bytes], + status: int = 200, + content_type: str = json_content_type, + headers: typing.Optional[typing.Dict[str, str]] = None, + preload_content: bool = True + ) -> urllib3.HTTPResponse: + if headers is None: + headers = {} + headers.update(cls.headers_for_content_type(content_type)) + return urllib3.HTTPResponse( + body, + headers=headers, + status=status, + preload_content=preload_content + ) + + @staticmethod + def json_bytes(in_data: typing.Any) -> bytes: + return json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode('utf-8') diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_another_fake_dummy/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_another_fake_dummy/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_another_fake_dummy/test_patch.py b/samples/openapi3/client/petstore/python/test/test_paths/test_another_fake_dummy/test_patch.py new file mode 100644 index 0000000000..827d02aaf1 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_another_fake_dummy/test_patch.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.another_fake_dummy import patch # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestAnotherFakeDummy(ApiTestMixin, unittest.TestCase): + """ + AnotherFakeDummy unit test stubs + To test special tags # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = patch.ApiForpatch(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_delete.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_delete.py new file mode 100644 index 0000000000..c22a985325 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_delete.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake import delete # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFake(ApiTestMixin, unittest.TestCase): + """ + Fake unit test stubs + Fake endpoint to test group parameters (optional) # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = delete.ApiFordelete(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_get.py new file mode 100644 index 0000000000..f5ec3b7346 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_get.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFake(ApiTestMixin, unittest.TestCase): + """ + Fake unit test stubs + To test enum parameters # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_patch.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_patch.py new file mode 100644 index 0000000000..e8d79727a0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_patch.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake import patch # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFake(ApiTestMixin, unittest.TestCase): + """ + Fake unit test stubs + To test \"client\" model # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = patch.ApiForpatch(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_post.py new file mode 100644 index 0000000000..714554981c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake/test_post.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFake(ApiTestMixin, unittest.TestCase): + """ + Fake unit test stubs + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_additional_properties_with_array_of_enums/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_additional_properties_with_array_of_enums/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_additional_properties_with_array_of_enums/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_additional_properties_with_array_of_enums/test_get.py new file mode 100644 index 0000000000..7a2c11bd64 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_additional_properties_with_array_of_enums/test_get.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_additional_properties_with_array_of_enums import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeAdditionalPropertiesWithArrayOfEnums(ApiTestMixin, unittest.TestCase): + """ + FakeAdditionalPropertiesWithArrayOfEnums unit test stubs + Additional Properties with Array of Enums # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_file_schema/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_file_schema/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_file_schema/test_put.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_file_schema/test_put.py new file mode 100644 index 0000000000..792ba93a1e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_file_schema/test_put.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_body_with_file_schema import put # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeBodyWithFileSchema(ApiTestMixin, unittest.TestCase): + """ + FakeBodyWithFileSchema unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = put.ApiForput(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_query_params/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_query_params/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_query_params/test_put.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_query_params/test_put.py new file mode 100644 index 0000000000..24385ae529 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_body_with_query_params/test_put.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_body_with_query_params import put # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeBodyWithQueryParams(ApiTestMixin, unittest.TestCase): + """ + FakeBodyWithQueryParams unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = put.ApiForput(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_case_sensitive_params/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_case_sensitive_params/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_case_sensitive_params/test_put.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_case_sensitive_params/test_put.py new file mode 100644 index 0000000000..1f1cb36476 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_case_sensitive_params/test_put.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_case_sensitive_params import put # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeCaseSensitiveParams(ApiTestMixin, unittest.TestCase): + """ + FakeCaseSensitiveParams unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = put.ApiForput(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_classname_test/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_classname_test/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_classname_test/test_patch.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_classname_test/test_patch.py new file mode 100644 index 0000000000..51c483bdc0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_classname_test/test_patch.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_classname_test import patch # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeClassnameTest(ApiTestMixin, unittest.TestCase): + """ + FakeClassnameTest unit test stubs + To test class name in snake case # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = patch.ApiForpatch(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_delete_coffee_id/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_delete_coffee_id/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_delete_coffee_id/test_delete.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_delete_coffee_id/test_delete.py new file mode 100644 index 0000000000..a002c547aa --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_delete_coffee_id/test_delete.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_delete_coffee_id import delete # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeDeleteCoffeeId(ApiTestMixin, unittest.TestCase): + """ + FakeDeleteCoffeeId unit test stubs + Delete coffee # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = delete.ApiFordelete(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_health/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_health/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_health/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_health/test_get.py new file mode 100644 index 0000000000..dd6f2a5485 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_health/test_get.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_health import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeHealth(ApiTestMixin, unittest.TestCase): + """ + FakeHealth unit test stubs + Health check endpoint # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_additional_properties/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_additional_properties/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_additional_properties/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_additional_properties/test_post.py new file mode 100644 index 0000000000..a1b5801b82 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_additional_properties/test_post.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_inline_additional_properties import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeInlineAdditionalProperties(ApiTestMixin, unittest.TestCase): + """ + FakeInlineAdditionalProperties unit test stubs + test inline additionalProperties # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_composition_/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_composition_/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_composition_/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_composition_/test_post.py new file mode 100644 index 0000000000..fe16f7a458 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_inline_composition_/test_post.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_inline_composition_ import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeInlineComposition(ApiTestMixin, unittest.TestCase): + """ + FakeInlineComposition unit test stubs + testing composed schemas at inline locations # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_form_data/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_form_data/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_form_data/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_form_data/test_get.py new file mode 100644 index 0000000000..2c10640ca3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_form_data/test_get.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_json_form_data import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeJsonFormData(ApiTestMixin, unittest.TestCase): + """ + FakeJsonFormData unit test stubs + test json serialization of form data # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_patch/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_patch/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_patch/test_patch.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_patch/test_patch.py new file mode 100644 index 0000000000..add02d961a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_patch/test_patch.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_json_patch import patch # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeJsonPatch(ApiTestMixin, unittest.TestCase): + """ + FakeJsonPatch unit test stubs + json patch # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = patch.ApiForpatch(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_with_charset/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_with_charset/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_with_charset/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_with_charset/test_post.py new file mode 100644 index 0000000000..26105cad9f --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_json_with_charset/test_post.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_json_with_charset import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeJsonWithCharset(ApiTestMixin, unittest.TestCase): + """ + FakeJsonWithCharset unit test stubs + json with charset tx and rx # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_obj_in_query/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_obj_in_query/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_obj_in_query/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_obj_in_query/test_get.py new file mode 100644 index 0000000000..fc11f501a4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_obj_in_query/test_get.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_obj_in_query import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeObjInQuery(ApiTestMixin, unittest.TestCase): + """ + FakeObjInQuery unit test stubs + user list # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_parameter_collisions_1_a_b_ab_self_a_b_/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_parameter_collisions_1_a_b_ab_self_a_b_/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_parameter_collisions_1_a_b_ab_self_a_b_/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_parameter_collisions_1_a_b_ab_self_a_b_/test_post.py new file mode 100644 index 0000000000..8bf351c3dc --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_parameter_collisions_1_a_b_ab_self_a_b_/test_post.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_parameter_collisions_1_a_b_ab_self_a_b_ import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeParameterCollisions1ABAbSelfAB(ApiTestMixin, unittest.TestCase): + """ + FakeParameterCollisions1ABAbSelfAB unit test stubs + parameter collision case # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_pet_id_upload_image_with_required_file/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_pet_id_upload_image_with_required_file/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_pet_id_upload_image_with_required_file/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_pet_id_upload_image_with_required_file/test_post.py new file mode 100644 index 0000000000..23bc55d273 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_pet_id_upload_image_with_required_file/test_post.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_pet_id_upload_image_with_required_file import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakePetIdUploadImageWithRequiredFile(ApiTestMixin, unittest.TestCase): + """ + FakePetIdUploadImageWithRequiredFile unit test stubs + uploads an image (required) # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_query_param_with_json_content_type/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_query_param_with_json_content_type/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_query_param_with_json_content_type/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_query_param_with_json_content_type/test_get.py new file mode 100644 index 0000000000..fe890aad78 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_query_param_with_json_content_type/test_get.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_query_param_with_json_content_type import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeQueryParamWithJsonContentType(ApiTestMixin, unittest.TestCase): + """ + FakeQueryParamWithJsonContentType unit test stubs + query param with json content-type # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_ref_obj_in_query/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_ref_obj_in_query/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_ref_obj_in_query/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_ref_obj_in_query/test_get.py new file mode 100644 index 0000000000..61edf55e3d --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_ref_obj_in_query/test_get.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_ref_obj_in_query import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefObjInQuery(ApiTestMixin, unittest.TestCase): + """ + FakeRefObjInQuery unit test stubs + user list # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_array_of_enums/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_array_of_enums/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_array_of_enums/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_array_of_enums/test_post.py new file mode 100644 index 0000000000..28aedd8c2c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_array_of_enums/test_post.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_refs_array_of_enums import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefsArrayOfEnums(ApiTestMixin, unittest.TestCase): + """ + FakeRefsArrayOfEnums unit test stubs + Array of Enums # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_arraymodel/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_arraymodel/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_arraymodel/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_arraymodel/test_post.py new file mode 100644 index 0000000000..a252701f4e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_arraymodel/test_post.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_refs_arraymodel import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefsArraymodel(ApiTestMixin, unittest.TestCase): + """ + FakeRefsArraymodel unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_boolean/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_boolean/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_boolean/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_boolean/test_post.py new file mode 100644 index 0000000000..3ac8fd5b4a --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_boolean/test_post.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_refs_boolean import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefsBoolean(ApiTestMixin, unittest.TestCase): + """ + FakeRefsBoolean unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_composed_one_of_number_with_validations/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_composed_one_of_number_with_validations/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_composed_one_of_number_with_validations/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_composed_one_of_number_with_validations/test_post.py new file mode 100644 index 0000000000..d5963d8503 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_composed_one_of_number_with_validations/test_post.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_refs_composed_one_of_number_with_validations import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefsComposedOneOfNumberWithValidations(ApiTestMixin, unittest.TestCase): + """ + FakeRefsComposedOneOfNumberWithValidations unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_enum/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_enum/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_enum/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_enum/test_post.py new file mode 100644 index 0000000000..fde250a49e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_enum/test_post.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_refs_enum import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefsEnum(ApiTestMixin, unittest.TestCase): + """ + FakeRefsEnum unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_mammal/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_mammal/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_mammal/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_mammal/test_post.py new file mode 100644 index 0000000000..a692191f47 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_mammal/test_post.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_refs_mammal import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefsMammal(ApiTestMixin, unittest.TestCase): + """ + FakeRefsMammal unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_number/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_number/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_number/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_number/test_post.py new file mode 100644 index 0000000000..b398b419ba --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_number/test_post.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_refs_number import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefsNumber(ApiTestMixin, unittest.TestCase): + """ + FakeRefsNumber unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_object_model_with_ref_props/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_object_model_with_ref_props/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_object_model_with_ref_props/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_object_model_with_ref_props/test_post.py new file mode 100644 index 0000000000..f6c51016d9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_object_model_with_ref_props/test_post.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_refs_object_model_with_ref_props import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefsObjectModelWithRefProps(ApiTestMixin, unittest.TestCase): + """ + FakeRefsObjectModelWithRefProps unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_string/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_string/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_string/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_string/test_post.py new file mode 100644 index 0000000000..b7eaa83842 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_refs_string/test_post.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_refs_string import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeRefsString(ApiTestMixin, unittest.TestCase): + """ + FakeRefsString unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_response_without_schema/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_response_without_schema/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_response_without_schema/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_response_without_schema/test_get.py new file mode 100644 index 0000000000..bcab7c9646 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_response_without_schema/test_get.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_response_without_schema import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeResponseWithoutSchema(ApiTestMixin, unittest.TestCase): + """ + FakeResponseWithoutSchema unit test stubs + receives a response without schema # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_test_query_paramters/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_test_query_paramters/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_test_query_paramters/test_put.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_test_query_paramters/test_put.py new file mode 100644 index 0000000000..e358588324 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_test_query_paramters/test_put.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_test_query_paramters import put # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeTestQueryParamters(ApiTestMixin, unittest.TestCase): + """ + FakeTestQueryParamters unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = put.ApiForput(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_download_file/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_download_file/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_download_file/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_download_file/test_post.py new file mode 100644 index 0000000000..5c04409466 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_download_file/test_post.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_upload_download_file import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeUploadDownloadFile(ApiTestMixin, unittest.TestCase): + """ + FakeUploadDownloadFile unit test stubs + uploads a file and downloads a file using application/octet-stream # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_file/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_file/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_file/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_file/test_post.py new file mode 100644 index 0000000000..d877e592ac --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_file/test_post.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_upload_file import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeUploadFile(ApiTestMixin, unittest.TestCase): + """ + FakeUploadFile unit test stubs + uploads a file using multipart/form-data # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_files/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_files/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_files/test_post.py new file mode 100644 index 0000000000..b0123d36ae --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_fake_upload_files/test_post.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_upload_files import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFakeUploadFiles(ApiTestMixin, unittest.TestCase): + """ + FakeUploadFiles unit test stubs + uploads files using multipart/form-data # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_foo/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_foo/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_foo/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_foo/test_get.py new file mode 100644 index 0000000000..809b636d6c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_foo/test_get.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.foo import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestFoo(ApiTestMixin, unittest.TestCase): + """ + Foo unit test stubs + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 0 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet/test_post.py new file mode 100644 index 0000000000..5016a08a9c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_pet/test_post.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.pet import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestPet(ApiTestMixin, unittest.TestCase): + """ + Pet unit test stubs + Add a new pet to the store # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet/test_put.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet/test_put.py new file mode 100644 index 0000000000..903536c66d --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_pet/test_put.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.pet import put # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestPet(ApiTestMixin, unittest.TestCase): + """ + Pet unit test stubs + Update an existing pet # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = put.ApiForput(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 400 + response_body = '' + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_status/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_status/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_status/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_status/test_get.py new file mode 100644 index 0000000000..2251f64e1b --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_status/test_get.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.pet_find_by_status import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestPetFindByStatus(ApiTestMixin, unittest.TestCase): + """ + PetFindByStatus unit test stubs + Finds Pets by status # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_tags/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_tags/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_tags/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_tags/test_get.py new file mode 100644 index 0000000000..48671bad4f --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_find_by_tags/test_get.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.pet_find_by_tags import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestPetFindByTags(ApiTestMixin, unittest.TestCase): + """ + PetFindByTags unit test stubs + Finds Pets by tags # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/test_delete.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/test_delete.py new file mode 100644 index 0000000000..04b0355911 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/test_delete.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.pet_pet_id import delete # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestPetPetId(ApiTestMixin, unittest.TestCase): + """ + PetPetId unit test stubs + Deletes a pet # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = delete.ApiFordelete(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 400 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/test_get.py new file mode 100644 index 0000000000..78e02c339c --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/test_get.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.pet_pet_id import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestPetPetId(ApiTestMixin, unittest.TestCase): + """ + PetPetId unit test stubs + Find pet by ID # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/test_post.py new file mode 100644 index 0000000000..6c6c9e60ad --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id/test_post.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.pet_pet_id import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestPetPetId(ApiTestMixin, unittest.TestCase): + """ + PetPetId unit test stubs + Updates a pet in the store with form data # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 405 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id_upload_image/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id_upload_image/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id_upload_image/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id_upload_image/test_post.py new file mode 100644 index 0000000000..b25f4ef89b --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_pet_pet_id_upload_image/test_post.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.pet_pet_id_upload_image import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestPetPetIdUploadImage(ApiTestMixin, unittest.TestCase): + """ + PetPetIdUploadImage unit test stubs + uploads an image # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_store_inventory/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_store_inventory/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_store_inventory/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_store_inventory/test_get.py new file mode 100644 index 0000000000..e1363824ef --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_store_inventory/test_get.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.store_inventory import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestStoreInventory(ApiTestMixin, unittest.TestCase): + """ + StoreInventory unit test stubs + Returns pet inventories by status # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_store_order/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_store_order/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_store_order/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_store_order/test_post.py new file mode 100644 index 0000000000..69adb4340e --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_store_order/test_post.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.store_order import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestStoreOrder(ApiTestMixin, unittest.TestCase): + """ + StoreOrder unit test stubs + Place an order for a pet # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_store_order_order_id/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_store_order_order_id/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_store_order_order_id/test_delete.py b/samples/openapi3/client/petstore/python/test/test_paths/test_store_order_order_id/test_delete.py new file mode 100644 index 0000000000..3b229d2b1b --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_store_order_order_id/test_delete.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.store_order_order_id import delete # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestStoreOrderOrderId(ApiTestMixin, unittest.TestCase): + """ + StoreOrderOrderId unit test stubs + Delete purchase order by ID # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = delete.ApiFordelete(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 400 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_store_order_order_id/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_store_order_order_id/test_get.py new file mode 100644 index 0000000000..55a5443d97 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_store_order_order_id/test_get.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.store_order_order_id import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestStoreOrderOrderId(ApiTestMixin, unittest.TestCase): + """ + StoreOrderOrderId unit test stubs + Find purchase order by ID # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user/test_post.py new file mode 100644 index 0000000000..0b494f2ba2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_user/test_post.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.user import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestUser(ApiTestMixin, unittest.TestCase): + """ + User unit test stubs + Create user # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 0 + response_body = '' + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_array/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_array/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_array/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_array/test_post.py new file mode 100644 index 0000000000..a6ed9b4d73 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_array/test_post.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.user_create_with_array import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestUserCreateWithArray(ApiTestMixin, unittest.TestCase): + """ + UserCreateWithArray unit test stubs + Creates list of users with given input array # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 0 + response_body = '' + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_list/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_list/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_list/test_post.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_list/test_post.py new file mode 100644 index 0000000000..173e669239 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_user_create_with_list/test_post.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.user_create_with_list import post # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestUserCreateWithList(ApiTestMixin, unittest.TestCase): + """ + UserCreateWithList unit test stubs + Creates list of users with given input array # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = post.ApiForpost(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 0 + response_body = '' + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_login/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_login/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_login/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_login/test_get.py new file mode 100644 index 0000000000..ad71bc1d4f --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_user_login/test_get.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.user_login import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestUserLogin(ApiTestMixin, unittest.TestCase): + """ + UserLogin unit test stubs + Logs user into the system # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_logout/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_logout/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_logout/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_logout/test_get.py new file mode 100644 index 0000000000..9329c79fb2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_user_logout/test_get.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.user_logout import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestUserLogout(ApiTestMixin, unittest.TestCase): + """ + UserLogout unit test stubs + Logs out current logged in user session # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 0 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/__init__.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/test_delete.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/test_delete.py new file mode 100644 index 0000000000..4ea2cc0f52 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/test_delete.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.user_username import delete # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestUserUsername(ApiTestMixin, unittest.TestCase): + """ + UserUsername unit test stubs + Delete user # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = delete.ApiFordelete(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + response_body = '' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/test_get.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/test_get.py new file mode 100644 index 0000000000..c56b8bd1e4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/test_get.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.user_username import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestUserUsername(ApiTestMixin, unittest.TestCase): + """ + UserUsername unit test stubs + Get user by user name # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = get.ApiForget(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 200 + + + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/test_put.py b/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/test_put.py new file mode 100644 index 0000000000..6e94769a58 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_paths/test_user_username/test_put.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.user_username import put # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from .. import ApiTestMixin + + +class TestUserUsername(ApiTestMixin, unittest.TestCase): + """ + UserUsername unit test stubs + Updated user # noqa: E501 + """ + _configuration = configuration.Configuration() + + def setUp(self): + used_api_client = api_client.ApiClient(configuration=self._configuration) + self.api = put.ApiForput(api_client=used_api_client) # noqa: E501 + + def tearDown(self): + pass + + response_status = 400 + response_body = '' + + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test_python.sh b/samples/openapi3/client/petstore/python/test_python.sh index f617f3adfa..9728a9b531 100755 --- a/samples/openapi3/client/petstore/python/test_python.sh +++ b/samples/openapi3/client/petstore/python/test_python.sh @@ -10,14 +10,16 @@ export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 ### set virtualenv -if [ -z "$VIRTUAL_ENV" ]; then - virtualenv $VENV --always-copy +if [ -z "$VENVV" ]; then + python3 -m venv $VENV source $VENV/bin/activate DEACTIVE=true fi ### install dependencies pip install -r $REQUIREMENTS_FILE | tee -a $REQUIREMENTS_OUT +### locally install the package, needed for pycharm problem checking +pip install -e . ### run tests tox || exit 1 diff --git a/samples/openapi3/client/petstore/python/tests_manual/__init__.py b/samples/openapi3/client/petstore/python/tests_manual/__init__.py index e69de29bb2..6aabd3fc7f 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/__init__.py +++ b/samples/openapi3/client/petstore/python/tests_manual/__init__.py @@ -0,0 +1,108 @@ +import collections +import json +import typing +import unittest + +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client + +ParamTestCase = collections.namedtuple('ParamTestCase', 'payload expected_serialization explode', defaults=[False]) + + +class ApiTestMixin(unittest.TestCase): + json_content_type = 'application/json' + user_agent = 'OpenAPI-Generator/1.0.0/python' + + @classmethod + def assert_request_called_with( + cls, + mock_request, + url: str, + method: str = 'POST', + body: typing.Optional[bytes] = None, + content_type: typing.Optional[str] = 'application/json', + fields: typing.Optional[typing.Tuple[api_client.RequestField, ...]] = None, + accept_content_type: typing.Optional[str] = 'application/json', + stream: bool = False, + ): + headers = { + 'User-Agent': cls.user_agent + } + if accept_content_type: + headers['Accept'] = accept_content_type + if content_type: + headers['Content-Type'] = content_type + kwargs = dict( + headers=HTTPHeaderDict(headers), + fields=fields, + stream=stream, + timeout=None, + ) + if method != 'GET': + kwargs['body'] = body + mock_request.assert_called_with( + method, + url, + **kwargs + ) + + @classmethod + def assert_pool_manager_request_called_with( + cls, + mock_request, + url: str, + method: str = 'POST', + body: typing.Optional[bytes] = None, + content_type: typing.Optional[str] = 'application/json', + accept_content_type: typing.Optional[str] = 'application/json', + stream: bool = False, + headers: typing.Optional[typing.Dict] = None + ): + if headers is None: + headers = {} + headers['User-Agent'] = cls.user_agent + if accept_content_type: + headers['Accept'] = accept_content_type + if content_type: + headers['Content-Type'] = content_type + kwargs = dict( + headers=HTTPHeaderDict(headers), + preload_content=not stream, + timeout=None, + ) + if content_type and method != 'GET': + kwargs['body'] = body + mock_request.assert_called_with( + method, + url, + **kwargs + ) + + @staticmethod + def headers_for_content_type(content_type: str) -> typing.Dict[str, str]: + return {'content-type': content_type} + + @classmethod + def response( + cls, + body: typing.Union[str, bytes], + status: int = 200, + content_type: str = json_content_type, + headers: typing.Optional[typing.Dict[str, str]] = None, + preload_content: bool = True + ) -> urllib3.HTTPResponse: + if headers is None: + headers = {} + headers.update(cls.headers_for_content_type(content_type)) + return urllib3.HTTPResponse( + body, + headers=headers, + status=status, + preload_content=preload_content + ) + + @staticmethod + def json_bytes(in_data: typing.Any) -> bytes: + return json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode('utf-8') diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_additional_properties_class.py b/samples/openapi3/client/petstore/python/tests_manual/test_additional_properties_class.py new file mode 100644 index 0000000000..589beb05cd --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_additional_properties_class.py @@ -0,0 +1,35 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +from petstore_api.model.additional_properties_class import AdditionalPropertiesClass +from petstore_api import schemas + + +class TestAdditionalPropertiesClass(unittest.TestCase): + """AdditionalPropertiesClass unit test stubs""" + + def test_additional_properties_class(self): + inst = AdditionalPropertiesClass({}) + with self.assertRaises(KeyError): + inst["map_property"] + assert inst.get_item_oapg("map_property") is schemas.unset + with self.assertRaises(AttributeError): + inst.map_property + + inst = AdditionalPropertiesClass(map_property={}) + map_property = inst["map_property"] + assert map_property == {} + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_additional_properties_validator.py b/samples/openapi3/client/petstore/python/tests_manual/test_additional_properties_validator.py new file mode 100644 index 0000000000..a54404c542 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_additional_properties_validator.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +from petstore_api.model.additional_properties_validator import AdditionalPropertiesValidator +from petstore_api import schemas, exceptions + + +class TestAdditionalPropertiesValidator(unittest.TestCase): + """AdditionalPropertiesValidator unit test stubs""" + + def test_additional_properties_validator(self): + with self.assertRaises(exceptions.ApiValueError): + AdditionalPropertiesValidator(tooShort='ab') + + with self.assertRaises(exceptions.ApiValueError): + AdditionalPropertiesValidator(tooLong='abcdef') + + inst = AdditionalPropertiesValidator(addProp='abc') + add_prop = inst['addProp'] + assert add_prop == 'abc' + assert isinstance(add_prop, str) + assert isinstance(add_prop, schemas.AnyTypeSchema) + assert isinstance(add_prop, AdditionalPropertiesValidator.MetaOapg.all_of()[1].MetaOapg.additional_properties) + assert isinstance(add_prop, AdditionalPropertiesValidator.MetaOapg.all_of()[2].MetaOapg.additional_properties) + assert not isinstance(add_prop, schemas.UnsetAnyTypeSchema) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_animal.py b/samples/openapi3/client/petstore/python/tests_manual/test_animal.py new file mode 100644 index 0000000000..68bb19bd24 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_animal.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import unittest + +import frozendict + +import petstore_api +from petstore_api.model.cat import Cat +from petstore_api.model.dog import Dog +from petstore_api.model.animal import Animal +from petstore_api.schemas import StrSchema, BoolSchema + + +class TestAnimal(unittest.TestCase): + """Animal unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAnimal(self): + """Test Animal""" + + regex_err = ( + r"Invalid discriminator value was passed in to Animal.className " + r"Only the values \['Cat', 'Dog'\] are allowed at \('args\[0\]', 'className'\)" + ) + with self.assertRaisesRegex(petstore_api.ApiValueError, regex_err): + Animal(className='Fox', color='red') + + animal = Animal(className='Cat', color='black') + assert isinstance(animal, frozendict.frozendict) + assert isinstance(animal, Cat) + assert isinstance(animal, Cat.MetaOapg.all_of()[1]) + assert isinstance(animal, Animal) + assert set(animal.keys()) == {'className', 'color'} + assert animal.className == 'Cat' + assert animal["color"] == 'black' + assert isinstance(animal["color"], StrSchema) + assert isinstance(animal.className, StrSchema) + + # pass in optional param + animal = Animal(className='Cat', color='black', declawed=True) + assert isinstance(animal, Animal) + assert isinstance(animal, frozendict.frozendict) + assert isinstance(animal, Cat) + assert isinstance(animal, Cat.MetaOapg.all_of()[1]) + assert set(animal.keys()) == {'className', 'color', 'declawed'} + assert animal.className == 'Cat' + assert animal["color"] == 'black' + assert bool(animal["declawed"]) is True + assert isinstance(animal["color"], StrSchema) + assert isinstance(animal.className, StrSchema) + assert isinstance(animal["declawed"], BoolSchema) + + # make a Dog + animal = Animal(className='Dog', color='black') + assert isinstance(animal, Animal) + assert isinstance(animal, frozendict.frozendict) + assert isinstance(animal, Dog) + assert isinstance(animal, Dog.MetaOapg.all_of()[1]) + assert set(animal.keys()) == {'className', 'color'} + assert animal.className == 'Dog' + assert animal["color"] == 'black' + assert isinstance(animal["color"], StrSchema) + assert isinstance(animal.className, StrSchema) + + # pass in optional param + animal = Animal(className='Dog', color='black', breed='Labrador') + assert isinstance(animal, Animal) + assert isinstance(animal, frozendict.frozendict) + assert isinstance(animal, Dog) + assert isinstance(animal, Dog.MetaOapg.all_of()[1]) + assert set(animal.keys()) == {'className', 'color', 'breed'} + assert animal.className == 'Dog' + assert animal["color"] == 'black' + assert animal["breed"] == 'Labrador' + assert isinstance(animal.className, StrSchema) + assert isinstance(animal["color"], StrSchema) + assert isinstance(animal["breed"], StrSchema) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_any_type_and_format.py b/samples/openapi3/client/petstore/python/tests_manual/test_any_type_and_format.py new file mode 100644 index 0000000000..3882982711 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_any_type_and_format.py @@ -0,0 +1,237 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import datetime +import decimal +import unittest +import uuid + +from petstore_api.model.any_type_and_format import AnyTypeAndFormat +from petstore_api import exceptions + + +class TestAnyTypeAndFormat(unittest.TestCase): + """AnyTypeAndFormat unit test stubs""" + + def test_uuid(self): + valid_uuid_str = '12345678-1234-5678-1234-567812345678' + valid_values = [ + valid_uuid_str, + {}, + uuid.UUID(valid_uuid_str), + 1, + 3.14, + decimal.Decimal('3.14'), + True, + None, + [], + (), + b'abc' + ] + for valid_value in valid_values: + AnyTypeAndFormat(uuid=valid_value) + + # an invalid value does not work + with self.assertRaises(exceptions.ApiValueError): + AnyTypeAndFormat(uuid='1') + + def test_date(self): + valid_values = [ + '2022-01-02', + {}, + datetime.date(2022, 1, 2), + 1, + 3.14, + decimal.Decimal('3.14'), + True, + None, + [], + (), + b'abc' + ] + for valid_value in valid_values: + AnyTypeAndFormat(date=valid_value) + + # an invalid value does not work + with self.assertRaises(exceptions.ApiValueError): + AnyTypeAndFormat(date='1') + + def test_date_time(self): + valid_values = [ + "2020-01-01T00:00:00", + {}, + datetime.datetime(2020, 1, 1), + 1, + 3.14, + decimal.Decimal('3.14'), + True, + None, + [], + (), + b'abc' + ] + for valid_value in valid_values: + AnyTypeAndFormat({'date-time': valid_value}) + + # an invalid value does not work + with self.assertRaises(exceptions.ApiValueError): + AnyTypeAndFormat({'date-time': 'abcd'}) + + def test_number(self): + valid_values = [ + '3.14', + {}, + 1, + 3.14, + decimal.Decimal('3.14'), + True, + None, + [], + (), + b'abc' + ] + for valid_value in valid_values: + AnyTypeAndFormat(number=valid_value) + + # an invalid value does not work + with self.assertRaises(exceptions.ApiValueError): + AnyTypeAndFormat(number='a') + + def test_int32(self): + min_bound = decimal.Decimal(-2147483648) + max_bound = decimal.Decimal(2147483647) + under_min_number = min_bound - decimal.Decimal('0.1') + over_max_number = max_bound + decimal.Decimal('0.1') + valid_values = [ + 'a', + {}, + 1, + 3.14, + min_bound, + max_bound, + under_min_number, + over_max_number, + True, + None, + [], + (), + b'abc' + ] + for valid_value in valid_values: + AnyTypeAndFormat(int32=valid_value) + + # invalid values do not work + invalid_values = ( + min_bound - 1, + max_bound + 1 + ) + for invalid_value in invalid_values: + with self.assertRaises(exceptions.ApiValueError): + AnyTypeAndFormat(int32=invalid_value) + + def test_int64(self): + min_bound = decimal.Decimal(-9223372036854775808) + max_bound = decimal.Decimal(9223372036854775807) + under_min_number = min_bound - decimal.Decimal('0.1') + over_max_number = max_bound + decimal.Decimal('0.1') + valid_values = [ + 'a', + {}, + 1, + 3.14, + min_bound, + max_bound, + under_min_number, + over_max_number, + True, + None, + [], + (), + b'abc' + ] + for valid_value in valid_values: + AnyTypeAndFormat(int64=valid_value) + + # invalid values do not work + invalid_values = ( + min_bound - 1, + max_bound + 1 + ) + for invalid_value in invalid_values: + with self.assertRaises(exceptions.ApiValueError): + AnyTypeAndFormat(int64=invalid_value) + + def test_float(self): + min_bound = decimal.Decimal(-3.4028234663852886e+38) + max_bound = decimal.Decimal(3.4028234663852886e+38) + valid_values = [ + 'a', + {}, + 1, + 3.14, + min_bound, + max_bound, + True, + None, + [], + (), + b'abc' + ] + for valid_value in valid_values: + AnyTypeAndFormat(double=valid_value) + + # invalid values do not work + invalid_values = ( + min_bound - decimal.Decimal('0.1'), + max_bound + decimal.Decimal('0.1'), + min_bound - 1, + max_bound + 1 + ) + for invalid_value in invalid_values: + with self.assertRaises(exceptions.ApiValueError): + AnyTypeAndFormat(float=invalid_value) + + def test_double(self): + min_bound = decimal.Decimal(-1.7976931348623157E+308) + max_bound = decimal.Decimal(1.7976931348623157E+308) + valid_values = [ + 'a', + {}, + 1, + 3.14, + min_bound, + max_bound, + True, + None, + [], + (), + b'abc' + ] + for valid_value in valid_values: + AnyTypeAndFormat(double=valid_value) + + with decimal.localcontext() as ctx: + ctx.prec = 310 + # local higher precision context needed to correctly create these numbers + invalid_values = ( + min_bound - decimal.Decimal('0.1'), + max_bound + decimal.Decimal('0.1'), + min_bound - 1, + max_bound + 1 + ) + # invalid values do not work + for invalid_value in invalid_values: + with self.assertRaises(exceptions.ApiValueError): + AnyTypeAndFormat(double=invalid_value) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_any_type_not_string.py b/samples/openapi3/client/petstore/python/tests_manual/test_any_type_not_string.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_any_type_not_string.py rename to samples/openapi3/client/petstore/python/tests_manual/test_any_type_not_string.py diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_any_type_schema.py b/samples/openapi3/client/petstore/python/tests_manual/test_any_type_schema.py new file mode 100644 index 0000000000..15f498bcc0 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_any_type_schema.py @@ -0,0 +1,230 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import unittest +from decimal import Decimal + +import frozendict + +import petstore_api +from petstore_api.schemas import ( + AnyTypeSchema, + DictSchema, + ListSchema, + StrSchema, + NumberSchema, + IntSchema, + BoolSchema, + NoneSchema, + DateSchema, + DateTimeSchema, + DecimalSchema, + ComposedSchema, + NoneClass, + BoolClass +) + + +class TestAnyTypeSchema(unittest.TestCase): + + def testDictSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + DictSchema, + ] + + m = Model(a=1, b='hi') + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, DictSchema) + assert isinstance(m, frozendict.frozendict) + assert m == frozendict.frozendict(a=Decimal(1), b='hi') + + def testListSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + ListSchema, + ] + + m = Model([1, 'hi']) + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, ListSchema) + assert isinstance(m, tuple) + assert m == tuple([Decimal(1), 'hi']) + + def testStrSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + StrSchema, + ] + + m = Model('hi') + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, StrSchema) + assert isinstance(m, str) + assert m == 'hi' + + def testNumberSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + NumberSchema, + ] + + m = Model(1) + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, NumberSchema) + assert isinstance(m, Decimal) + assert m == Decimal(1) + + m = Model(3.14) + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, NumberSchema) + assert isinstance(m, Decimal) + assert m == Decimal(3.14) + + def testIntSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + IntSchema, + ] + + m = Model(1) + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, IntSchema) + assert isinstance(m, Decimal) + assert m == Decimal(1) + + with self.assertRaises(petstore_api.exceptions.ApiValueError): + # can't pass in float into Int + Model(3.14) + + def testBoolSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + BoolSchema, + ] + + m = Model(True) + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, BoolSchema) + assert isinstance(m, BoolClass) + self.assertTrue(m) + + m = Model(False) + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, BoolSchema) + assert isinstance(m, BoolClass) + self.assertFalse(m) + + def testNoneSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + NoneSchema, + ] + + m = Model(None) + self.assertTrue(m.is_none_oapg()) + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, NoneSchema) + assert isinstance(m, NoneClass) + + def testDateSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + DateSchema, + ] + + m = Model('1970-01-01') + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, DateSchema) + assert isinstance(m, str) + assert m == '1970-01-01' + + def testDateTimeSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + DateTimeSchema, + ] + + m = Model('2020-01-01T00:00:00') + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, DateTimeSchema) + assert isinstance(m, str) + assert m == '2020-01-01T00:00:00' + + def testDecimalSchema(self): + class Model(ComposedSchema): + class MetaOapg: + @staticmethod + def all_of(): + return [ + AnyTypeSchema, + DecimalSchema, + ] + + m = Model('12.34') + assert m == '12.34' + assert m.as_decimal_oapg == Decimal('12.34') + assert isinstance(m, Model) + assert isinstance(m, AnyTypeSchema) + assert isinstance(m, DecimalSchema) + assert isinstance(m, str) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_array_holding_any_type.py b/samples/openapi3/client/petstore/python/tests_manual/test_array_holding_any_type.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_array_holding_any_type.py rename to samples/openapi3/client/petstore/python/tests_manual/test_array_holding_any_type.py diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_array_with_validations_in_items.py b/samples/openapi3/client/petstore/python/tests_manual/test_array_with_validations_in_items.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_array_with_validations_in_items.py rename to samples/openapi3/client/petstore/python/tests_manual/test_array_with_validations_in_items.py diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_boolean_enum.py b/samples/openapi3/client/petstore/python/tests_manual/test_boolean_enum.py index 09f386f23a..530755c068 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_boolean_enum.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_boolean_enum.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -8,7 +10,6 @@ """ -import sys import unittest import petstore_api @@ -24,13 +25,13 @@ class TestBooleanEnum(unittest.TestCase): def tearDown(self): pass - def testBooleanEnum(self): + def test_BooleanEnum(self): """Test BooleanEnum""" model = BooleanEnum(True) - assert model.value is True - - assert BooleanEnum.allowed_values[('value',)]['TRUE'] is True - + assert model is BooleanEnum.TRUE + assert model.is_true_oapg() + assert model.is_false_oapg() is False + assert repr(model) == '' with self.assertRaises(petstore_api.ApiValueError): BooleanEnum(False) diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_object_schemas.py b/samples/openapi3/client/petstore/python/tests_manual/test_combine_object_schemas.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_object_schemas.py rename to samples/openapi3/client/petstore/python/tests_manual/test_combine_object_schemas.py diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_schemas.py b/samples/openapi3/client/petstore/python/tests_manual/test_combine_schemas.py similarity index 82% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_schemas.py rename to samples/openapi3/client/petstore/python/tests_manual/test_combine_schemas.py index 403d9709f8..f77f71ec46 100644 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_schemas.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_combine_schemas.py @@ -32,14 +32,10 @@ class TestCombineNonObjectSchemas(unittest.TestCase): class EnumPlusPrim(IntegerMax10, IntegerEnumOneValue): pass - assert EnumPlusPrim._enum_value_to_name == {0: "POSITIVE_0"} - # order of base classes does not matter class EnumPlusPrim(IntegerEnumOneValue, IntegerMax10): pass - assert EnumPlusPrim._enum_value_to_name == {0: "POSITIVE_0"} - enum_value = EnumPlusPrim.POSITIVE_0 assert isinstance(enum_value, EnumPlusPrim) assert isinstance(enum_value, Singleton) @@ -59,16 +55,12 @@ class TestCombineNonObjectSchemas(unittest.TestCase): assert isinstance(val, decimal.Decimal) def test_valid_enum_plus_enum(self): - class IntegerOneEnum(IntegerEnum, IntegerEnumOneValue): - pass - - assert IntegerOneEnum._enum_value_to_name == {0: "POSITIVE_0"} - - # order of base classes does not matter class IntegerOneEnum(IntegerEnumOneValue, IntegerEnum): pass - assert IntegerOneEnum._enum_value_to_name == {0: "POSITIVE_0"} + # order of base classes does not matter + class IntegerOneEnum(IntegerEnum, IntegerEnumOneValue): + pass enum_value = IntegerOneEnum.POSITIVE_0 assert isinstance(enum_value, IntegerOneEnum) @@ -77,12 +69,6 @@ class TestCombineNonObjectSchemas(unittest.TestCase): # we can access this enum from our class assert IntegerOneEnum.POSITIVE_0 == 0 - # accessing invalid enum throws an exception - invalid_enums = ['POSITIVE_1', 'POSITIVE_2'] - for invalid_enum in invalid_enums: - with self.assertRaises(petstore_api.ApiValueError): - getattr(IntegerOneEnum, invalid_enum) - if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_composed_bool.py b/samples/openapi3/client/petstore/python/tests_manual/test_composed_bool.py new file mode 100644 index 0000000000..45eb149106 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_composed_bool.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import unittest + +import petstore_api +from petstore_api.model.composed_bool import ComposedBool + + +class TestComposedBool(unittest.TestCase): + """ComposedBool unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_ComposedBool(self): + """Test ComposedBool""" + all_values = [None, True, False, 2, 3.14, '', {}, []] + for value in all_values: + if isinstance(value, bool): + model = ComposedBool(value) + if value is True: + self.assertTrue(bool(model)) + self.assertTrue(model.is_true_oapg()) + self.assertFalse(model.is_false_oapg()) + else: + self.assertTrue(model.is_false_oapg()) + self.assertFalse(model.is_true_oapg()) + self.assertFalse(bool(model)) + continue + with self.assertRaises(petstore_api.ApiTypeError): + ComposedBool(value) + continue + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_none.py b/samples/openapi3/client/petstore/python/tests_manual/test_composed_none.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_none.py rename to samples/openapi3/client/petstore/python/tests_manual/test_composed_none.py diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_number.py b/samples/openapi3/client/petstore/python/tests_manual/test_composed_number.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_number.py rename to samples/openapi3/client/petstore/python/tests_manual/test_composed_number.py diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_object.py b/samples/openapi3/client/petstore/python/tests_manual/test_composed_object.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_object.py rename to samples/openapi3/client/petstore/python/tests_manual/test_composed_object.py diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_composed_one_of_different_types.py b/samples/openapi3/client/petstore/python/tests_manual/test_composed_one_of_different_types.py new file mode 100644 index 0000000000..e98af8bb8f --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_composed_one_of_different_types.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import unittest +from datetime import date, datetime, timezone +from dateutil.tz import tzutc + +import frozendict + +from petstore_api.schemas import DateSchema, DateTimeSchema, Singleton, NoneClass +from petstore_api.model.animal import Animal +from petstore_api.model.cat import Cat +from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes +from petstore_api.model.number_with_validations import NumberWithValidations + +class TestComposedOneOfDifferentTypes(unittest.TestCase): + """ComposedOneOfDifferentTypes unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_ComposedOneOfDifferentTypes(self): + """Test ComposedOneOfDifferentTypes""" + # we can make an instance that stores float data + inst = ComposedOneOfDifferentTypes(10.0) + assert isinstance(inst, NumberWithValidations) + + # we can make an instance that stores object (dict) data + inst = ComposedOneOfDifferentTypes(className="Cat", color="black") + assert isinstance(inst, ComposedOneOfDifferentTypes) + assert isinstance(inst, Animal) + assert isinstance(inst, Cat) + assert isinstance(inst, frozendict.frozendict) + + # object that holds 4 properties and is not an Animal + inst = ComposedOneOfDifferentTypes(a="a", b="b", c="c", d="d") + assert isinstance(inst, ComposedOneOfDifferentTypes) + assert not isinstance(inst, Animal) + assert isinstance(inst, frozendict.frozendict) + + # None + inst = ComposedOneOfDifferentTypes(None) + inst.is_none_oapg() + assert isinstance(inst, ComposedOneOfDifferentTypes) + assert isinstance(inst, Singleton) + assert isinstance(inst, NoneClass) + assert inst.is_none_oapg() is True + + # date + inst = ComposedOneOfDifferentTypes.from_openapi_data_oapg('2019-01-10') + assert isinstance(inst, ComposedOneOfDifferentTypes) + assert isinstance(inst, DateSchema) + assert isinstance(inst, str) + assert inst.as_date_oapg.year == 2019 + assert inst.as_date_oapg.month == 1 + assert inst.as_date_oapg.day == 10 + + # date + inst = ComposedOneOfDifferentTypes(date(2019, 1, 10)) + assert isinstance(inst, ComposedOneOfDifferentTypes) + assert isinstance(inst, DateSchema) + assert isinstance(inst, str) + assert inst.as_date_oapg.year == 2019 + assert inst.as_date_oapg.month == 1 + assert inst.as_date_oapg.day == 10 + + # date-time + inst = ComposedOneOfDifferentTypes.from_openapi_data_oapg('2020-01-02T03:04:05Z') + assert isinstance(inst, ComposedOneOfDifferentTypes) + assert isinstance(inst, DateTimeSchema) + assert isinstance(inst, str) + assert inst.as_datetime_oapg.year == 2020 + assert inst.as_datetime_oapg.month == 1 + assert inst.as_datetime_oapg.day == 2 + assert inst.as_datetime_oapg.hour == 3 + assert inst.as_datetime_oapg.minute == 4 + assert inst.as_datetime_oapg.second == 5 + utc_tz = tzutc() + assert inst.as_datetime_oapg.tzinfo == utc_tz + + # date-time + inst = ComposedOneOfDifferentTypes(datetime(2020, 1, 2, 3, 4, 5, tzinfo=timezone.utc)) + assert isinstance(inst, ComposedOneOfDifferentTypes) + assert isinstance(inst, DateTimeSchema) + assert isinstance(inst, str) + assert inst.as_datetime_oapg.year == 2020 + assert inst.as_datetime_oapg.month == 1 + assert inst.as_datetime_oapg.day == 2 + assert inst.as_datetime_oapg.hour == 3 + assert inst.as_datetime_oapg.minute == 4 + assert inst.as_datetime_oapg.second == 5 + assert inst.as_datetime_oapg.tzinfo == utc_tz + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_string.py b/samples/openapi3/client/petstore/python/tests_manual/test_composed_string.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_string.py rename to samples/openapi3/client/petstore/python/tests_manual/test_composed_string.py diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_configuration.py b/samples/openapi3/client/petstore/python/tests_manual/test_configuration.py similarity index 88% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_configuration.py rename to samples/openapi3/client/petstore/python/tests_manual/test_configuration.py index b3162c0686..1d11ed6cae 100644 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_configuration.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_configuration.py @@ -17,14 +17,14 @@ from urllib3._collections import HTTPHeaderDict import petstore_api from petstore_api.api_client import ApiClient -from petstore_api.api import pet_api +from petstore_api.apis.tags import pet_api class ConfigurationTests(unittest.TestCase): def test_configuration(self): config = petstore_api.Configuration() - config.host = 'http://localhost/' + config.host = 'https://localhost/' config.disabled_client_side_validations = ("multipleOf,maximum,exclusiveMaximum,minimum,exclusiveMinimum," "maxLength,minLength,pattern,maxItems,minItems") @@ -34,7 +34,7 @@ class ConfigurationTests(unittest.TestCase): def test_servers(self): config = petstore_api.Configuration(server_index=1, server_variables={'version': 'v1'}) - client = pet_api.ApiClient(configuration=config) + client = ApiClient(configuration=config) api = pet_api.PetApi(client) with patch.object(ApiClient, 'request') as mock_request: @@ -42,13 +42,13 @@ class ConfigurationTests(unittest.TestCase): api.add_pet({'name': 'pet', 'photoUrls': []}) mock_request.assert_called_with( 'POST', - 'http://path-server-test.petstore.local/v2/pet', + 'https://path-server-test.petstore.local/v2/pet', headers=HTTPHeaderDict({ 'Content-Type': 'application/json', 'User-Agent': 'OpenAPI-Generator/1.0.0/python' }), fields=None, - body=b'{"name":"pet","photoUrls":[]}', + body=b'{"photoUrls":[],"name":"pet"}', stream=False, timeout=None, ) diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_copy.py b/samples/openapi3/client/petstore/python/tests_manual/test_copy.py deleted file mode 100644 index 35bd9a31a2..0000000000 --- a/samples/openapi3/client/petstore/python/tests_manual/test_copy.py +++ /dev/null @@ -1,34 +0,0 @@ -from copy import deepcopy -import unittest -from petstore_api.model.mammal import Mammal -from petstore_api.model.triangle import Triangle - - -class TestCopy(unittest.TestCase): - """TestCopy unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def testDeepCopyOneOf(self): - """test deepcopy""" - obj = deepcopy(Mammal(class_name="whale")) - assert id(deepcopy(obj)) != id(obj) - assert deepcopy(obj) == obj - - def testDeepCopyAllOf(self): - """test deepcopy""" - obj = Triangle(shape_type="Triangle", triangle_type="EquilateralTriangle", foo="blah") - assert id(deepcopy(obj)) != id(obj) - assert deepcopy(obj) == obj - - obj = Triangle._new_from_openapi_data(shape_type="Triangle", triangle_type="EquilateralTriangle", foo="blah") - assert id(deepcopy(obj)) != id(obj) - assert deepcopy(obj) == obj - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_date_time_with_validations.py b/samples/openapi3/client/petstore/python/tests_manual/test_date_time_with_validations.py new file mode 100644 index 0000000000..336cb29cb3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_date_time_with_validations.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import unittest + +import petstore_api +from petstore_api.model.date_time_with_validations import DateTimeWithValidations +from datetime import date, datetime, timezone + + +class TestDateTimeWithValidations(unittest.TestCase): + """DateTimeWithValidations unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testDateTimeWithValidations(self): + """Test DateTimeWithValidations""" + + # works with datetime input + valid_values = [datetime(2020, 1, 1), '2020-01-01T00:00:00'] + expected_datetime = '2020-01-01T00:00:00' + for valid_value in valid_values: + inst = DateTimeWithValidations(valid_value) + assert inst == expected_datetime + + # when passing data in with from_openapi_data_oapg one must use str + with self.assertRaisesRegex( + petstore_api.ApiTypeError, + r"Invalid type. Required value type is str and passed " + r"type was at \('args\[0\]',\)" + ): + DateTimeWithValidations.from_openapi_data_oapg(datetime(2020, 1, 1)) + + # when passing data from_openapi_data_oapg we can use str + input_value_to_datetime = { + "2020-01-01T00:00:00": datetime(2020, 1, 1, tzinfo=None), + "2020-01-01T00:00:00Z": datetime(2020, 1, 1, tzinfo=timezone.utc), + "2020-01-01T00:00:00+00:00": datetime(2020, 1, 1, tzinfo=timezone.utc) + } + for input_value, expected_datetime in input_value_to_datetime.items(): + inst = DateTimeWithValidations.from_openapi_data_oapg(input_value) + assert inst.as_datetime_oapg == expected_datetime + + # value error is raised if an invalid string is passed in + with self.assertRaisesRegex( + petstore_api.ApiValueError, + r"Value does not conform to the required ISO-8601 datetime format. Invalid value 'abcd' for type datetime at \('args\[0\]',\)" + ): + DateTimeWithValidations.from_openapi_data_oapg("abcd") + + # value error is raised if a date is passed in + with self.assertRaisesRegex( + petstore_api.ApiValueError, + r"Value does not conform to the required ISO-8601 datetime format. Invalid value '2020-01-01' for type datetime at \('args\[0\]',\)" + ): + DateTimeWithValidations(date(2020, 1, 1)) + + # pattern checking with string input + error_regex = r"Invalid value `2019-01-01T00:00:00Z`, must match regular expression `.+?` at \('args\[0\]',\)" + with self.assertRaisesRegex( + petstore_api.ApiValueError, + error_regex + ): + DateTimeWithValidations.from_openapi_data_oapg("2019-01-01T00:00:00Z") + # pattern checking with date input + error_regex = r"Invalid value `2019-01-01T00:00:00`, must match regular expression `.+?` at \('args\[0\]',\)" + with self.assertRaisesRegex( + petstore_api.ApiValueError, + error_regex + ): + DateTimeWithValidations(datetime(2019, 1, 1)) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_date_with_validations.py b/samples/openapi3/client/petstore/python/tests_manual/test_date_with_validations.py new file mode 100644 index 0000000000..658470df0e --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_date_with_validations.py @@ -0,0 +1,92 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import unittest + +import petstore_api +from petstore_api.model.date_with_validations import DateWithValidations +from datetime import date, datetime + + +class TestDateWithValidations(unittest.TestCase): + """DateWithValidations unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testDateWithValidations(self): + """Test DateWithValidations""" + + # client side date inputs + valid_values = [date(2020, 1, 1), '2020-01-01'] + expected_date = '2020-01-01' + for valid_value in valid_values: + inst = DateWithValidations(valid_value) + assert inst == expected_date + + # when passing data in with from_openapi_data_oapg one must use str + with self.assertRaisesRegex( + petstore_api.ApiTypeError, + r"Invalid type. Required value type is str and passed " + r"type was at \('args\[0\]',\)" + + ): + DateWithValidations.from_openapi_data_oapg(date(2020, 1, 1)) + + # when passing data in from the server we can use str + valid_values = ["2020-01-01", "2020-01", "2020"] + expected_date = date(2020, 1, 1) + for valid_value in valid_values: + inst = DateWithValidations.from_openapi_data_oapg(valid_value) + assert inst.as_date_oapg == expected_date + + # value error is raised if an invalid string is passed in + with self.assertRaisesRegex( + petstore_api.ApiValueError, + r"Value does not conform to the required ISO-8601 date format. Invalid value '2020-01-01T00:00:00Z' for type date at \('args\[0\]',\)" + ): + DateWithValidations.from_openapi_data_oapg("2020-01-01T00:00:00Z") + + # value error is raised if a datetime is passed in + with self.assertRaisesRegex( + petstore_api.ApiValueError, + r"Value does not conform to the required ISO-8601 date format. Invalid value '2020-01-01T00:00:00' for type date at \('args\[0\]',\)" + ): + DateWithValidations(datetime(2020, 1, 1)) + + # value error is raised if an invalid string is passed in + with self.assertRaisesRegex( + petstore_api.ApiValueError, + r"Value does not conform to the required ISO-8601 date format. Invalid value 'abcd' for type date at \('args\[0\]',\)" + ): + DateWithValidations.from_openapi_data_oapg("abcd") + + # pattern checking for str input + error_regex = r"Invalid value `2019-01-01`, must match regular expression `.+?` at \('args\[0\]',\)" + with self.assertRaisesRegex( + petstore_api.ApiValueError, + error_regex + ): + DateWithValidations.from_openapi_data_oapg("2019-01-01") + # pattern checking for date input + with self.assertRaisesRegex( + petstore_api.ApiValueError, + error_regex + ): + DateWithValidations(date(2019, 1, 1)) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_decimal_payload.py b/samples/openapi3/client/petstore/python/tests_manual/test_decimal_payload.py new file mode 100644 index 0000000000..58f77cbf21 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_decimal_payload.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import decimal +import unittest + +import petstore_api +from petstore_api.schemas import DecimalSchema +from petstore_api.model.decimal_payload import DecimalPayload + + +class TestDecimalPayload(unittest.TestCase): + """DecimalPayload unit test stubs""" + + def test_DecimalPayload(self): + """Test DecimalPayload""" + + m = DecimalPayload('12') + assert isinstance(m, DecimalPayload) + assert isinstance(m, DecimalSchema) + assert isinstance(m, str) + assert m == '12' + assert m.as_decimal_oapg == decimal.Decimal('12') + + m = DecimalPayload('12.34') + assert isinstance(m, DecimalPayload) + assert isinstance(m, DecimalSchema) + assert isinstance(m, str) + assert m == '12.34' + assert m.as_decimal_oapg == decimal.Decimal('12.34') + + # passing in a Decimal does not work + with self.assertRaises(petstore_api.ApiTypeError): + DecimalPayload(decimal.Decimal('12.34')) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_deserialization.py b/samples/openapi3/client/petstore/python/tests_manual/test_deserialization.py index 93538160f9..7c0300fbcd 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_deserialization.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_deserialization.py @@ -9,38 +9,32 @@ $ cd OpenAPIPetstore-python $ nosetests -v """ from collections import namedtuple +from decimal import Decimal import json -import os -import time +import typing import unittest -import datetime + +import urllib3 import petstore_api -from petstore_api.model import ( - shape, - equilateral_triangle, - animal, - dog, - apple, - mammal, - whale, - zebra, - banana, - fruit_req, - drawing, - banana_req, - number_with_validations, -) +from petstore_api import api_client +from petstore_api.schemas import NoneClass MockResponse = namedtuple('MockResponse', 'data') class DeserializationTests(unittest.TestCase): + json_content_type = 'application/json' + json_content_type_headers = {'content-type': json_content_type} + configuration = petstore_api.Configuration() - def setUp(self): - self.api_client = petstore_api.ApiClient() - self.deserialize = self.api_client.deserialize + @classmethod + def __response(cls, data: typing.Any) -> urllib3.HTTPResponse: + return urllib3.HTTPResponse( + json.dumps(data).encode('utf-8'), + headers=cls.json_content_type_headers + ) def test_deserialize_shape(self): """ @@ -54,35 +48,36 @@ class DeserializationTests(unittest.TestCase): - SimpleQuadrilateral by traveling through 2 discriminators """ - shape_type, triangle_type = ['Triangle', 'EquilateralTriangle'] - data = { - 'shapeType': shape_type, - 'triangleType': triangle_type, - } - response = MockResponse(data=json.dumps(data)) - - deserialized = self.deserialize(response, (shape.Shape,), True) - self.assertTrue(isinstance(deserialized, equilateral_triangle.EquilateralTriangle)) - self.assertEqual(deserialized.shape_type, shape_type) - self.assertEqual(deserialized.triangle_type, triangle_type) - - # invalid second discriminator value - shape_type, quadrilateral_type = ['Quadrilateral', 'Triangle'] - data = { - 'shapeType': shape_type, - 'quadrilateralType': quadrilateral_type, - } - response = MockResponse(data=json.dumps(data)) - - err_msg = ("Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '{}'='{}' at path: ()" + from petstore_api.model import shape, equilateral_triangle + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=shape.Shape), + }, ) - with self.assertRaisesRegex( - petstore_api.ApiValueError, - err_msg.format("quadrilateralType", "Triangle") - ): - self.deserialize(response, (shape.Shape,), True) + data = { + 'shapeType': 'Triangle', + 'triangleType': 'EquilateralTriangle', + } + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, self.configuration) + body = deserialized.body + self.assertTrue(isinstance(body, equilateral_triangle.EquilateralTriangle)) + self.assertEqual(body['shapeType'], 'Triangle') + self.assertEqual(body['triangleType'], 'EquilateralTriangle') + + # invalid quadrilateralType, second discriminator value + data = { + 'shapeType': 'Quadrilateral', + 'quadrilateralType': 'Triangle', + } + response = self.__response(data) + + err_msg = ( + r"Invalid discriminator value was passed in to Quadrilateral.quadrilateralType Only the values " + r"\['ComplexQuadrilateral', 'SimpleQuadrilateral'\] are allowed at \('args\[0\]', 'quadrilateralType'\)" + ) + with self.assertRaisesRegex(petstore_api.ApiValueError, err_msg): + _response_for_200.deserialize(response, self.configuration) def test_deserialize_animal(self): """ @@ -91,26 +86,30 @@ class DeserializationTests(unittest.TestCase): that inherrit from Animal This is the swagger (v2) way of doing something like oneOf composition """ - class_name = 'Dog' - color = 'white' - breed = 'Jack Russel Terrier' + from petstore_api.model import animal, dog + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=animal.Animal), + }, + ) data = { - 'className': class_name, - 'color': color, - 'breed': breed + 'className': 'Dog', + 'color': 'white', + 'breed': 'Jack Russel Terrier' } - response = MockResponse(data=json.dumps(data)) - - deserialized = self.deserialize(response, (animal.Animal,), True) - self.assertTrue(isinstance(deserialized, dog.Dog)) - self.assertEqual(deserialized.class_name, class_name) - self.assertEqual(deserialized.color, color) - self.assertEqual(deserialized.breed, breed) + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, self.configuration) + body = deserialized.body + self.assertTrue(isinstance(body, dog.Dog)) + self.assertEqual(body['className'], 'Dog') + self.assertEqual(body['color'], 'white') + self.assertEqual(body['breed'], 'Jack Russel Terrier') def test_regex_constraint(self): """ Test regex pattern validation. """ + from petstore_api.model import apple # Test with valid regex pattern. inst = apple.Apple( @@ -118,24 +117,29 @@ class DeserializationTests(unittest.TestCase): ) assert isinstance(inst, apple.Apple) - # Test with invalid regex pattern in cultivar - err_msg = ("Invalid value for `{}`, must match regular expression `{}`$") + inst = apple.Apple( + cultivar="Golden Delicious", + origin="cHiLe" + ) + assert isinstance(inst, apple.Apple) + + # Test with invalid regex pattern. + err_regex = r"Invalid value `.+?`, must match regular expression `.+?` at \('args\[0\]', 'cultivar'\)" with self.assertRaisesRegex( petstore_api.ApiValueError, - err_msg.format("cultivar", "[^`]*") + err_regex ): inst = apple.Apple( cultivar="!@#%@$#Akane" ) - # Test with invalid regex pattern in origin - err_msg = ("Invalid value for `{}`, must match regular expression `{}` with flags") + err_regex = r"Invalid value `.+?`, must match regular expression `.+?` at \('args\[0\]', 'origin'\)" with self.assertRaisesRegex( petstore_api.ApiValueError, - err_msg.format("origin", "[^`]*") + err_regex ): inst = apple.Apple( - cultivar="Akane", + cultivar="Golden Delicious", origin="!@#%@$#Chile" ) @@ -146,6 +150,12 @@ class DeserializationTests(unittest.TestCase): """ # whale test + from petstore_api.model import mammal, zebra, whale + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=mammal.Mammal), + }, + ) has_baleen = True has_teeth = False class_name = 'whale' @@ -154,12 +164,13 @@ class DeserializationTests(unittest.TestCase): 'hasTeeth': has_teeth, 'className': class_name } - response = MockResponse(data=json.dumps(data)) - deserialized = self.deserialize(response, (mammal.Mammal,), True) - self.assertTrue(isinstance(deserialized, whale.Whale)) - self.assertEqual(deserialized.has_baleen, has_baleen) - self.assertEqual(deserialized.has_teeth, has_teeth) - self.assertEqual(deserialized.class_name, class_name) + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, self.configuration) + body = deserialized.body + self.assertTrue(isinstance(body, whale.Whale)) + self.assertEqual(bool(body['hasBaleen']), has_baleen) + self.assertEqual(bool(body['hasTeeth']), has_teeth) + self.assertEqual(body.className, class_name) # zebra test zebra_type = 'plains' @@ -168,47 +179,64 @@ class DeserializationTests(unittest.TestCase): 'type': zebra_type, 'className': class_name } - response = MockResponse(data=json.dumps(data)) - deserialized = self.deserialize(response, (mammal.Mammal,), True) - self.assertTrue(isinstance(deserialized, zebra.Zebra)) - self.assertEqual(deserialized.type, zebra_type) - self.assertEqual(deserialized.class_name, class_name) + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, self.configuration) + body = deserialized.body + self.assertTrue(isinstance(body, zebra.Zebra)) + self.assertEqual(body['type'], zebra_type) + self.assertEqual(body.className, class_name) def test_deserialize_float_value(self): """ Deserialize floating point values. """ + from petstore_api.model import banana + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=banana.Banana), + }, + ) data = { 'lengthCm': 3.1415 } - response = MockResponse(data=json.dumps(data)) - deserialized = self.deserialize(response, (banana.Banana,), True) - self.assertTrue(isinstance(deserialized, banana.Banana)) - self.assertEqual(deserialized.length_cm, 3.1415) + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, self.configuration) + body = deserialized.body + self.assertTrue(isinstance(body, banana.Banana)) + self.assertTrue(isinstance(body.lengthCm, Decimal)) + self.assertEqual(body.lengthCm, 3.1415) - # Float value is serialized without decimal point + """ + Float value is serialized without decimal point + The client receive it as an integer, which work because Banana.lengthCm is type number without format + Which accepts int AND float + """ data = { 'lengthCm': 3 } - response = MockResponse(data=json.dumps(data)) - deserialized = self.deserialize(response, (banana.Banana,), True) - self.assertTrue(isinstance(deserialized, banana.Banana)) - self.assertEqual(deserialized.length_cm, 3.0) + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, self.configuration) + body = deserialized.body + self.assertTrue(isinstance(body, banana.Banana)) + self.assertTrue(isinstance(body.lengthCm, Decimal)) + self.assertEqual(body.lengthCm, 3) def test_deserialize_fruit_null_value(self): """ deserialize fruit with null value. fruitReq is a oneOf composed schema model with discriminator, including 'null' type. """ - - # Unmarshal 'null' value + from petstore_api.model import fruit_req + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=fruit_req.FruitReq), + }, + ) data = None - response = MockResponse(data=json.dumps(data)) - deserialized = self.deserialize(response, (fruit_req.FruitReq, type(None)), True) - self.assertEqual(type(deserialized), type(None)) - - inst = fruit_req.FruitReq(None) - self.assertIsNone(inst) + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, self.configuration) + self.assertTrue(isinstance(deserialized.body, fruit_req.FruitReq)) + self.assertTrue(isinstance(deserialized.body, NoneClass)) def test_deserialize_with_additional_properties(self): """ @@ -223,6 +251,7 @@ class DeserializationTests(unittest.TestCase): # The additionalProperties keyword is used to control the handling of extra stuff, # that is, properties whose names are not listed in the properties keyword. # By default any additional properties are allowed. + from petstore_api.model import dog, mammal, zebra, banana_req data = { 'className': 'Dog', 'color': 'brown', @@ -231,37 +260,56 @@ class DeserializationTests(unittest.TestCase): 'group': 'Terrier Group', 'size': 'medium', } - response = MockResponse(data=json.dumps(data)) - deserialized = self.deserialize(response, (dog.Dog,), True) - self.assertEqual(type(deserialized), dog.Dog) - self.assertEqual(deserialized.class_name, 'Dog') - self.assertEqual(deserialized.breed, 'golden retriever') + response = self.__response(data) + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=dog.Dog), + }, + ) + deserialized = _response_for_200.deserialize(response, self.configuration) + body = deserialized.body + self.assertTrue(isinstance(body, dog.Dog)) + self.assertEqual(body['className'], 'Dog') + self.assertEqual(body['color'], 'brown') + self.assertEqual(body['breed'], 'golden retriever') + self.assertEqual(body['group'], 'Terrier Group') + self.assertEqual(body['size'], 'medium') # The 'zebra' schema allows additional properties by explicitly setting # additionalProperties: true. # This is equivalent to 'additionalProperties' not being present. data = { - 'class_name': 'zebra', + 'className': 'zebra', 'type': 'plains', # Below are additional, undeclared properties 'group': 'abc', 'size': 3, 'p1': True, - 'p2': [ 'a', 'b', 123], + 'p2': ['a', 'b', 123], } - response = MockResponse(data=json.dumps(data)) - deserialized = self.deserialize(response, (mammal.Mammal,), True) - self.assertEqual(type(deserialized), zebra.Zebra) - self.assertEqual(deserialized.class_name, 'zebra') - self.assertEqual(deserialized.type, 'plains') - self.assertEqual(deserialized.p1, True) + response = self.__response(data) + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=mammal.Mammal), + }, + ) + deserialized = _response_for_200.deserialize(response, self.configuration) + body = deserialized.body + self.assertTrue(isinstance(body, zebra.Zebra)) + self.assertEqual(body['className'], 'zebra') + self.assertEqual(body['type'], 'plains') + self.assertEqual(bool(body['p1']), True) # The 'bananaReq' schema disallows additional properties by explicitly setting # additionalProperties: false - err_msg = ("{} has no attribute '{}' at ") + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=banana_req.BananaReq), + }, + ) with self.assertRaisesRegex( - petstore_api.exceptions.ApiAttributeError, - err_msg.format("BananaReq", "unknown-group") + petstore_api.exceptions.ApiTypeError, + r"BananaReq was passed 1 invalid argument: \['unknown-group'\]" ): data = { 'lengthCm': 21.2, @@ -270,58 +318,141 @@ class DeserializationTests(unittest.TestCase): # an exception must be raised. 'unknown-group': 'abc', } - response = MockResponse(data=json.dumps(data)) - deserialized = self.deserialize(response, (banana_req.BananaReq,), True) - self.assertEqual(type(deserialized), banana_req.BananaReq) - self.assertEqual(deserialized.lengthCm, 21) - self.assertEqual(deserialized.p1, True) + response = self.__response(data) + _response_for_200.deserialize(response, self.configuration) def test_deserialize_with_additional_properties_and_reference(self): """ Deserialize data with schemas that has the additionalProperties keyword and the schema is specified as a reference ($ref). """ + from petstore_api.model import drawing + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=drawing.Drawing), + }, + ) data = { - 'main_shape': { - 'shape_type': 'Triangle', - 'triangle_type': 'EquilateralTriangle', + 'mainShape': { + 'shapeType': 'Triangle', + 'triangleType': 'EquilateralTriangle', }, 'shapes': [ { - 'shape_type': 'Triangle', - 'triangle_type': 'IsoscelesTriangle', + 'shapeType': 'Triangle', + 'triangleType': 'IsoscelesTriangle', }, { - 'shape_type': 'Quadrilateral', - 'quadrilateral_type': 'ComplexQuadrilateral', + 'shapeType': 'Quadrilateral', + 'quadrilateralType': 'ComplexQuadrilateral', }, ], + 'an_additional_prop': { + 'lengthCm': 4, + 'color': 'yellow' + } } - response = MockResponse(data=json.dumps(data)) - deserialized = self.deserialize(response, (drawing.Drawing,), True) + response = self.__response(data) + _response_for_200.deserialize(response, self.configuration) def test_deserialize_NumberWithValidations(self): - """ deserialize NumberWithValidations """ + from petstore_api.model.number_with_validations import NumberWithValidations + from petstore_api.paths.fake_refs_number.post import _response_for_200 + # make sure that an exception is thrown on an invalid type value with self.assertRaises(petstore_api.ApiTypeError): - self.deserialize( - MockResponse(data=json.dumps("test str")), - (number_with_validations.NumberWithValidations,), - True - ) + response = self.__response('test str') + _response_for_200.deserialize(response, self.configuration) # make sure that an exception is thrown on an invalid value with self.assertRaises(petstore_api.ApiValueError): - self.deserialize( - MockResponse(data=json.dumps(21.0)), - (number_with_validations.NumberWithValidations,), - True - ) + response = self.__response(21.0) + _response_for_200.deserialize(response, self.configuration) # valid value works number_val = 11.0 - response = MockResponse(data=json.dumps(number_val)) - number = self.deserialize(response, - (number_with_validations.NumberWithValidations,), True) - self.assertTrue(isinstance(number, number_with_validations.NumberWithValidations)) - self.assertTrue(number.value == number_val) \ No newline at end of file + response = self.__response(number_val) + response = _response_for_200.deserialize(response, self.configuration) + self.assertTrue(isinstance(response.body, NumberWithValidations)) + self.assertEqual(response.body, number_val) + + def test_array_of_enums(self): + from petstore_api.model.array_of_enums import ArrayOfEnums + from petstore_api.paths.fake_refs_array_of_enums.post import _response_for_200 + from petstore_api.model import string_enum + data = ["placed", None] + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, self.configuration) + assert isinstance(deserialized.body, ArrayOfEnums) + expected_results = ArrayOfEnums([string_enum.StringEnum(v) for v in data]) + assert expected_results == deserialized.body + + def test_multiple_of_deserialization(self): + data = { + 'byte': '3', + 'date': '1970-01-01', + 'password': "abcdefghijkl", + 'integer': 30, + 'number': 65.0, + 'float': 62.4, + } + from petstore_api.model import format_test + _response_for_200 = api_client.OpenApiResponse( + content={ + self.json_content_type: api_client.MediaType(schema=format_test.FormatTest), + }, + ) + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, self.configuration) + self.assertTrue(isinstance(deserialized.body, format_test.FormatTest)) + + with self.assertRaisesRegex( + petstore_api.exceptions.ApiValueError, + r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)" + ): + data = { + 'byte': '3', + 'date': '1970-01-01', + 'password': "abcdefghijkl", + 'integer': 31, # Value is supposed to be multiple of '2'. An error must be raised + 'number': 65.0, + 'float': 62.4, + } + response = self.__response(data) + _response_for_200.deserialize(response, self.configuration) + + # Disable JSON schema validation. No error should be raised during deserialization. + configuration = petstore_api.Configuration() + configuration.disabled_client_side_validations = "multipleOf" + + data = { + 'byte': '3', + 'date': '1970-01-01', + 'password': "abcdefghijkl", + 'integer': 31, # Value is supposed to be multiple of '2' + 'number': 65.0, + 'float': 62.4, + } + response = self.__response(data) + deserialized = _response_for_200.deserialize(response, configuration) + self.assertTrue(isinstance(deserialized.body, format_test.FormatTest)) + + # Disable JSON schema validation but for a different keyword. + # An error should be raised during deserialization. + configuration = petstore_api.Configuration() + configuration.disabled_client_side_validations = "maxItems" + + with self.assertRaisesRegex( + petstore_api.exceptions.ApiValueError, + r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)" + ): + data = { + 'byte': '3', + 'date': '1970-01-01', + 'password': "abcdefghijkl", + 'integer': 31, # Value is supposed to be multiple of '2' + 'number': 65.0, + 'float': 62.4, + } + response = self.__response(data) + _response_for_200.deserialize(response, configuration) diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_discard_unknown_properties.py b/samples/openapi3/client/petstore/python/tests_manual/test_discard_unknown_properties.py index ed1ca736d4..97d850d56b 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_discard_unknown_properties.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_discard_unknown_properties.py @@ -1,173 +1,157 @@ -# coding: utf-8 - -# flake8: noqa - -""" -Run the tests. -$ docker pull swaggerapi/petstore -$ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore -$ pip install nose (optional) -$ cd petstore_api-python -$ nosetests -v -""" -from collections import namedtuple -import json -import re -import unittest - -import petstore_api -from petstore_api.model import cat, dog, isosceles_triangle, banana_req, fruit_req -from petstore_api import Configuration, signing - -from petstore_api.model_utils import ( - file_type, - model_to_dict, -) - -MockResponse = namedtuple('MockResponse', 'data') - -class DiscardUnknownPropertiesTests(unittest.TestCase): - - def test_deserialize_banana_req_do_not_discard_unknown_properties(self): - """ - deserialize bananaReq with unknown properties. - Strict validation is enabled. - Simple (non-composed) schema scenario. - """ - config = Configuration(discard_unknown_keys=False) - api_client = petstore_api.ApiClient(config) - data = { - 'lengthCm': 21.3, - 'sweet': False, - # Below is an unknown property not explicitly declared in the OpenAPI document. - # It should not be in the payload because additional properties (undeclared) are - # not allowed in the bananaReq schema (additionalProperties: false). - 'unknown_property': 'a-value' - } - response = MockResponse(data=json.dumps(data)) - - # Deserializing with strict validation raises an exception because the 'unknown_property' - # is undeclared. - with self.assertRaises(petstore_api.exceptions.ApiAttributeError) as cm: - deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True) - self.assertTrue(re.match("BananaReq has no attribute 'unknown_property' at.*", str(cm.exception)), - 'Exception message: {0}'.format(str(cm.exception))) - - - def test_deserialize_fruit_req_do_not_discard_unknown_properties(self): - """ - deserialize FruitReq with unknown properties. - Strict validation is enabled. - Composed schema scenario. - """ - config = Configuration(discard_unknown_keys=False) - api_client = petstore_api.ApiClient(config) - data = { - 'lengthCm': 21.3, - 'sweet': False, - # Below is an unknown property not explicitly declared in the OpenAPI document. - # It should not be in the payload because additional properties (undeclared) are - # not allowed in the schema (additionalProperties: false). - 'unknown_property': 'a-value' - } - response = MockResponse(data=json.dumps(data)) - - # Deserializing with strict validation raises an exception because the 'unknown_property' - # is undeclared. - with self.assertRaisesRegex(petstore_api.ApiValueError, "Invalid inputs given to generate an instance of FruitReq. None of the oneOf schemas matched the input data."): - deserialized = api_client.deserialize(response, ((fruit_req.FruitReq),), True) - - - def test_deserialize_fruit_req_discard_unknown_properties(self): - """ - deserialize FruitReq with unknown properties. - Strict validation is enabled. - Composed schema scenario. - """ - config = Configuration(discard_unknown_keys=True) - api_client = petstore_api.ApiClient(config) - data = { - 'lengthCm': 21.3, - 'sweet': False, - # Below is an unknown property not explicitly declared in the OpenAPI document. - # It should not be in the payload because additional properties (undeclared) are - # not allowed in BananaReq - 'unknown_property': 'a-value' - } - response = MockResponse(data=json.dumps(data)) - deserialized = api_client.deserialize(response, ((fruit_req.FruitReq),), True) - self.assertNotIn("unknown_property", deserialized.to_dict().keys()) - - - def test_deserialize_banana_req_discard_unknown_properties(self): - """ - Deserialize bananaReq with unknown properties. - Discard unknown properties. - """ - config = Configuration(discard_unknown_keys=True) - api_client = petstore_api.ApiClient(config) - data = { - 'lengthCm': 21.3, - 'sweet': False, - # Below are additional (undeclared) properties not specified in the bananaReq schema. - 'unknown_property': 'a-value', - 'more-unknown': [ - 'a' - ] - } - # The 'unknown_property' is undeclared, which would normally raise an exception, but - # when discard_unknown_keys is set to True, the unknown properties are discarded. - response = MockResponse(data=json.dumps(data)) - deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True) - self.assertTrue(isinstance(deserialized, banana_req.BananaReq)) - # Check the 'unknown_property' and 'more-unknown' properties are not present in the - # output. - self.assertIn("length_cm", deserialized.to_dict().keys()) - self.assertNotIn("unknown_property", deserialized.to_dict().keys()) - self.assertNotIn("more-unknown", deserialized.to_dict().keys()) - - def test_deserialize_cat_do_not_discard_unknown_properties(self): - """ - Deserialize Cat with unknown properties. - Strict validation is enabled. - """ - config = Configuration(discard_unknown_keys=False) - api_client = petstore_api.ApiClient(config) - data = { - "class_name": "Cat", - "color": "black", - "declawed": True, - "dynamic-property": 12345, - } - response = MockResponse(data=json.dumps(data)) - - # Deserializing with strict validation does not raise an exception because the even though - # the 'dynamic-property' is undeclared, the 'Cat' schema defines the additionalProperties - # attribute. - deserialized = api_client.deserialize(response, ((cat.Cat),), True) - self.assertTrue(isinstance(deserialized, cat.Cat)) - self.assertIn('color', deserialized.to_dict()) - self.assertEqual(deserialized['color'], 'black') - - def test_deserialize_cat_discard_unknown_properties(self): - """ - Deserialize Cat with unknown properties. - Request to discard unknown properties, but Cat is composed schema - with one inner schema that has 'additionalProperties' set to true. - """ - config = Configuration(discard_unknown_keys=True) - api_client = petstore_api.ApiClient(config) - data = { - "class_name": "Cat", - "color": "black", - "declawed": True, - # Below are additional (undeclared) properties. - "my_additional_property": 123, - } - # The 'my_additional_property' is undeclared - response = MockResponse(data=json.dumps(data)) - deserialized = api_client.deserialize(response, ((cat.Cat),), True) - self.assertTrue(isinstance(deserialized, cat.Cat)) - # Check the 'my_additional_property' is present - self.assertIn("my_additional_property", deserialized.to_dict().keys()) - +# # coding: utf-8 +# +# # flake8: noqa +# +# """ +# Run the tests. +# $ docker pull swaggerapi/petstore +# $ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore +# $ pip install nose (optional) +# $ cd petstore_api-python +# $ nosetests -v +# """ +# from collections import namedtuple +# import json +# import re +# import unittest +# +# import petstore_api +# from petstore_api.model import cat, dog, isosceles_triangle, banana_req +# from petstore_api import Configuration, signing +# +# from petstore_api.schemas import ( +# file_type, +# model_to_dict, +# ) +# +# MockResponse = namedtuple('MockResponse', 'data') +# +# class DiscardUnknownPropertiesTests(unittest.TestCase): +# +# def test_deserialize_banana_req_do_not_discard_unknown_properties(self): +# """ +# deserialize bananaReq with unknown properties. +# Strict validation is enabled. +# Simple (non-composed) schema scenario. +# """ +# config = Configuration(discard_unknown_keys=False) +# api_client = petstore_api.ApiClient(config) +# data = { +# 'lengthCm': 21.3, +# 'sweet': False, +# # Below is an unknown property not explicitly declared in the OpenAPI document. +# # It should not be in the payload because additional properties (undeclared) are +# # not allowed in the bananaReq schema (additionalProperties: false). +# 'unknown_property': 'a-value' +# } +# response = MockResponse(data=json.dumps(data)) +# +# # Deserializing with strict validation raises an exception because the 'unknown_property' +# # is undeclared. +# with self.assertRaises(petstore_api.exceptions.ApiAttributeError) as cm: +# deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True) +# self.assertTrue(re.match("BananaReq has no attribute 'unknown_property' at.*", str(cm.exception)), +# 'Exception message: {0}'.format(str(cm.exception))) +# +# +# def test_deserialize_isosceles_triangle_do_not_discard_unknown_properties(self): +# """ +# deserialize IsoscelesTriangle with unknown properties. +# Strict validation is enabled. +# Composed schema scenario. +# """ +# config = Configuration(discard_unknown_keys=False) +# api_client = petstore_api.ApiClient(config) +# data = { +# 'shape_type': 'Triangle', +# 'triangle_type': 'EquilateralTriangle', +# # Below is an unknown property not explicitly declared in the OpenAPI document. +# # It should not be in the payload because additional properties (undeclared) are +# # not allowed in the schema (additionalProperties: false). +# 'unknown_property': 'a-value' +# } +# response = MockResponse(data=json.dumps(data)) +# +# # Deserializing with strict validation raises an exception because the 'unknown_property' +# # is undeclared. +# with self.assertRaises(petstore_api.ApiValueError) as cm: +# deserialized = api_client.deserialize(response, ((isosceles_triangle.IsoscelesTriangle),), True) +# self.assertTrue(re.match('.*Not all inputs were used.*unknown_property.*', str(cm.exception)), +# 'Exception message: {0}'.format(str(cm.exception))) +# +# +# def test_deserialize_banana_req_discard_unknown_properties(self): +# """ +# Deserialize bananaReq with unknown properties. +# Discard unknown properties. +# """ +# config = Configuration(discard_unknown_keys=True) +# api_client = petstore_api.ApiClient(config) +# data = { +# 'lengthCm': 21.3, +# 'sweet': False, +# # Below are additional (undeclared) properties not specified in the bananaReq schema. +# 'unknown_property': 'a-value', +# 'more-unknown': [ +# 'a' +# ] +# } +# # The 'unknown_property' is undeclared, which would normally raise an exception, but +# # when discard_unknown_keys is set to True, the unknown properties are discarded. +# response = MockResponse(data=json.dumps(data)) +# deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True) +# self.assertTrue(isinstance(deserialized, banana_req.BananaReq)) +# # Check the 'unknown_property' and 'more-unknown' properties are not present in the +# # output. +# self.assertIn("length_cm", deserialized.to_dict().keys()) +# self.assertNotIn("unknown_property", deserialized.to_dict().keys()) +# self.assertNotIn("more-unknown", deserialized.to_dict().keys()) +# +# def test_deserialize_cat_do_not_discard_unknown_properties(self): +# """ +# Deserialize Cat with unknown properties. +# Strict validation is enabled. +# """ +# config = Configuration(discard_unknown_keys=False) +# api_client = petstore_api.ApiClient(config) +# data = { +# "class_name": "Cat", +# "color": "black", +# "declawed": True, +# "dynamic-property": 12345, +# } +# response = MockResponse(data=json.dumps(data)) +# +# # Deserializing with strict validation does not raise an exception because the even though +# # the 'dynamic-property' is undeclared, the 'Cat' schema defines the additionalProperties +# # attribute. +# deserialized = api_client.deserialize(response, ((cat.Cat),), True) +# self.assertTrue(isinstance(deserialized, cat.Cat)) +# self.assertIn('color', deserialized.to_dict()) +# self.assertEqual(deserialized['color'], 'black') +# +# def test_deserialize_cat_discard_unknown_properties(self): +# """ +# Deserialize Cat with unknown properties. +# Request to discard unknown properties, but Cat is composed schema +# with one inner schema that has 'additionalProperties' set to true. +# """ +# config = Configuration(discard_unknown_keys=True) +# api_client = petstore_api.ApiClient(config) +# data = { +# "class_name": "Cat", +# "color": "black", +# "declawed": True, +# # Below are additional (undeclared) properties. +# "my_additional_property": 123, +# } +# # The 'my_additional_property' is undeclared, but 'Cat' has a 'Address' type through +# # the allOf: [ $ref: '#/components/schemas/Address' ]. +# response = MockResponse(data=json.dumps(data)) +# deserialized = api_client.deserialize(response, ((cat.Cat),), True) +# self.assertTrue(isinstance(deserialized, cat.Cat)) +# # Check the 'unknown_property' and 'more-unknown' properties are not present in the +# # output. +# self.assertIn("declawed", deserialized.to_dict().keys()) +# self.assertIn("my_additional_property", deserialized.to_dict().keys()) +# diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_drawing.py b/samples/openapi3/client/petstore/python/tests_manual/test_drawing.py index 327e01fb84..2febc75e36 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_drawing.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_drawing.py @@ -14,21 +14,9 @@ import sys import unittest import petstore_api -try: - from petstore_api.model import nullable_shape -except ImportError: - nullable_shape = sys.modules[ - 'petstore_api.model.nullable_shape'] -try: - from petstore_api.model import shape -except ImportError: - shape = sys.modules[ - 'petstore_api.model.shape'] -try: - from petstore_api.model import shape_or_null -except ImportError: - shape_or_null = sys.modules[ - 'petstore_api.model.shape_or_null'] +from petstore_api.schemas import NoneClass +from petstore_api.model import shape +from petstore_api.model import shape_or_null from petstore_api.model.drawing import Drawing @@ -43,88 +31,95 @@ class TestDrawing(unittest.TestCase): def test_create_instances(self): """ - Validate instance can be created using pythonic name or OAS names. + Validate instance can be created """ - # Validate object can be created using pythonic names. inst = shape.Shape( - shape_type="Triangle", - triangle_type="IsoscelesTriangle" + shapeType="Triangle", + triangleType="IsoscelesTriangle" ) from petstore_api.model.isosceles_triangle import IsoscelesTriangle assert isinstance(inst, IsoscelesTriangle) - # Validate object can be created using OAS names. - # For example, this can be used to construct objects on the client - # when the input data is available as JSON documents. - data = { - 'shapeType': "Triangle", - 'triangleType': "IsoscelesTriangle" - } - inst = shape.Shape(_spec_property_naming=True, **data) - assert isinstance(inst, IsoscelesTriangle) - def test_deserialize_oneof_reference(self): """ Validate the scenario when the type of a OAS property is 'oneOf', and the 'oneOf' schema is specified as a reference ($ref), not an inline 'oneOf' schema. """ isosceles_triangle = shape.Shape( - shape_type="Triangle", - triangle_type="IsoscelesTriangle" + shapeType="Triangle", + triangleType="IsoscelesTriangle" ) from petstore_api.model.isosceles_triangle import IsoscelesTriangle - from petstore_api.model.triangle import Triangle + assert isinstance(isosceles_triangle, IsoscelesTriangle) from petstore_api.model.equilateral_triangle import EquilateralTriangle - assert isinstance(isosceles_triangle, IsoscelesTriangle) inst = Drawing( - # 'main_shape' has type 'Shape', which is a oneOf [triangle, quadrilateral] - # composed schema. So we should be able to assign a petstore_api.Triangle - # to a 'main_shape'. - main_shape=isosceles_triangle, + mainShape=isosceles_triangle, shapes=[ shape.Shape( - shape_type="Triangle", - triangle_type="EquilateralTriangle" - ), - Triangle( - shape_type="Triangle", - triangle_type="IsoscelesTriangle" - ), - EquilateralTriangle( - shape_type="Triangle", - triangle_type="EquilateralTriangle" + shapeType="Triangle", + triangleType="EquilateralTriangle" ), shape.Shape( - shape_type="Quadrilateral", - quadrilateral_type="ComplexQuadrilateral" + shapeType="Triangle", + triangleType="IsoscelesTriangle" ), + shape.Shape( + shapeType="Triangle", + triangleType="EquilateralTriangle" + ), + shape.Shape( + shapeType="Quadrilateral", + quadrilateralType="ComplexQuadrilateral" + ) ], ) - from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral assert isinstance(inst, Drawing) - assert isinstance(inst.main_shape, IsoscelesTriangle) - self.assertEqual(len(inst.shapes), 4) - assert isinstance(inst.shapes[0], EquilateralTriangle) - assert isinstance(inst.shapes[1], IsoscelesTriangle) - assert isinstance(inst.shapes[2], EquilateralTriangle) - assert isinstance(inst.shapes[3], ComplexQuadrilateral) + assert isinstance(inst["mainShape"], IsoscelesTriangle) + self.assertEqual(len(inst["shapes"]), 4) + from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral + assert isinstance(inst["shapes"][0], EquilateralTriangle) + assert isinstance(inst["shapes"][1], IsoscelesTriangle) + assert isinstance(inst["shapes"][2], EquilateralTriangle) + assert isinstance(inst["shapes"][3], ComplexQuadrilateral) - # Validate we cannot assign the None value to main_shape because the 'null' type + # Validate we cannot assign the None value to mainShape because the 'null' type # is not one of the allowed types in the 'Shape' schema. - err_msg = (r"Invalid type for variable '{}'. " - r"Required value type is {} and passed type was {} at {}") + err_msg = (r"Invalid inputs given to generate an instance of .+?Shape.+? " + r"None of the oneOf schemas matched the input data.") with self.assertRaisesRegex( - petstore_api.ApiTypeError, - err_msg.format(r"main_shape", r"one of \[ComplexQuadrilateral, EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle, SimpleQuadrilateral\]", r"NoneType", r"\['main_shape'\]") + petstore_api.ApiValueError, + err_msg ): - inst = Drawing( - # 'main_shape' has type 'Shape', which is a oneOf [triangle, quadrilateral] + Drawing( + # 'mainShape' has type 'Shape', which is a oneOf [triangle, quadrilateral] # So the None value should not be allowed and an exception should be raised. - main_shape=None, + mainShape=None, ) + """ + We can pass in a Triangle instance in shapes + Under the hood it is converted into a dict, and that dict payload + does validate as a Shape, so this works + """ + from petstore_api.model.triangle import Triangle + inst = Drawing( + mainShape=isosceles_triangle, + shapes=[ + Triangle( + shapeType="Triangle", + triangleType="EquilateralTriangle" + ) + ] + ) + self.assertEqual(len(inst["shapes"]), 1) + from petstore_api.model.triangle_interface import TriangleInterface + shapes = inst["shapes"] + assert isinstance(shapes[0], shape.Shape) + assert isinstance(shapes[0], Triangle) + assert isinstance(shapes[0], EquilateralTriangle) + assert isinstance(shapes[0], TriangleInterface) def test_deserialize_oneof_reference_with_null_type(self): """ @@ -137,14 +132,13 @@ class TestDrawing(unittest.TestCase): # Validate we can assign the None value to shape_or_null, because the 'null' type # is one of the allowed types in the 'ShapeOrNull' schema. inst = Drawing( - # 'shape_or_null' has type 'ShapeOrNull', which is a oneOf [null, triangle, quadrilateral] - shape_or_null=None, + # 'shapeOrNull' has type 'ShapeOrNull', which is a oneOf [null, triangle, quadrilateral] + shapeOrNull=None, ) assert isinstance(inst, Drawing) - self.assertFalse(hasattr(inst, 'main_shape')) - self.assertTrue(hasattr(inst, 'shape_or_null')) - self.assertIsNone(inst.shape_or_null) - + self.assertFalse('mainShape' in inst) + self.assertTrue('shapeOrNull' in inst) + self.assertTrue(isinstance(inst["shapeOrNull"], NoneClass)) def test_deserialize_oneof_reference_with_nullable_type(self): """ @@ -154,17 +148,18 @@ class TestDrawing(unittest.TestCase): OpenAPI 3.0 and deprecated in 3.1). """ - # Validate we can assign the None value to nullable_shape, because the NullableShape + # Validate we can assign the None value to nullableShape, because the NullableShape # has the 'nullable: true' attribute. inst = Drawing( - # 'nullable_shape' has type 'NullableShape', which is a oneOf [triangle, quadrilateral] + # 'nullableShape' has type 'NullableShape', which is a oneOf [triangle, quadrilateral] # and the 'nullable: true' attribute. - nullable_shape=None, + nullableShape=None, ) assert isinstance(inst, Drawing) - self.assertFalse(hasattr(inst, 'main_shape')) - self.assertTrue(hasattr(inst, 'nullable_shape')) - self.assertIsNone(inst.nullable_shape) + self.assertFalse('mainShape' in inst) + self.assertTrue('nullableShape' in inst) + self.assertTrue(isinstance(inst["nullableShape"], NoneClass)) + if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_extra_pool_config_options.py b/samples/openapi3/client/petstore/python/tests_manual/test_extra_pool_config_options.py index 9e49b9e71b..5bf6b989eb 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_extra_pool_config_options.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_extra_pool_config_options.py @@ -48,9 +48,9 @@ class TestExtraOptionsForPools(unittest.TestCase): socket_options = ["extra", "socket", "options"] - config = petstore_api.Configuration(host="http://somehost.local:8080") + config = petstore_api.Configuration(host="HOST") config.socket_options = socket_options - config.proxy = "http://proxy.local:8080/" + config.proxy = True with patch("petstore_api.rest.urllib3.ProxyManager", StubProxyManager): api_client = petstore_api.ApiClient(config) diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py b/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py index 12e391238e..7ce4a60e8f 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py @@ -8,117 +8,56 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ - +from email.mime import multipart +from email.mime import nonmultipart +import io import sys -from collections import namedtuple -import os -import json import unittest +import typing from unittest.mock import patch +import urllib3 import petstore_api -from petstore_api.api.fake_api import FakeApi # noqa: E501 -from petstore_api.rest import RESTClientObject, RESTResponse -from petstore_api.model_utils import file_type, model_to_dict +from petstore_api import api_client, schemas, exceptions +from petstore_api.apis.tags.fake_api import FakeApi # noqa: E501 +from petstore_api.rest import RESTClientObject -HTTPResponse = namedtuple( - 'urllib3_response_HTTPResponse', - ['status', 'reason', 'data', 'getheaders', 'getheader'] -) - -headers = {'Content-Type': 'application/json'} -def get_headers(): - return {} -def get_header(name, default=None): - return {}.get(name, default) +from . import ApiTestMixin -class TestFakeApi(unittest.TestCase): +class MIMEFormdata(nonmultipart.MIMENonMultipart): + def __init__(self, keyname, *args, **kwargs): + super(MIMEFormdata, self).__init__(*args, **kwargs) + self.add_header( + "Content-Disposition", "form-data; name=\"%s\"" % keyname) + + +class TestFakeApi(ApiTestMixin): """FakeApi unit test stubs""" - - def setUp(self): - self.api = FakeApi() # noqa: E501 - - def tearDown(self): - pass - - @staticmethod - def mock_response(body_value): - http_response = HTTPResponse( - status=200, - reason='OK', - data=json.dumps(body_value).encode('utf-8'), - getheaders=get_headers, - getheader=get_header - ) - return RESTResponse(http_response) - - @staticmethod - def assert_request_called_with( - mock_method, - url, - accept='application/json', - http_method='POST', - content_type='application/json', - **kwargs - ): - headers = { - 'Accept': accept, - 'User-Agent': 'OpenAPI-Generator/1.0.0/python', - } - if content_type: - headers['Content-Type'] = content_type - used_kwargs = dict( - _preload_content=True, - _request_timeout=None, - headers=headers, - query_params=[] - ) - if 'post_params' in kwargs: - used_kwargs['post_params'] = kwargs['post_params'] - if 'body' in kwargs: - used_kwargs['body'] = kwargs['body'] - if 'post_params' not in used_kwargs: - used_kwargs['post_params'] = [] - mock_method.assert_called_with( - http_method, - url, - **used_kwargs - ) + configuration = petstore_api.Configuration() + api = FakeApi(api_client=api_client.ApiClient(configuration=configuration)) def test_array_model(self): - """Test case for array_model - - """ from petstore_api.model import animal_farm, animal - endpoint = self.api.array_model_endpoint - assert endpoint.openapi_types['body'] == (animal_farm.AnimalFarm,) - assert endpoint.settings['response_type'] == (animal_farm.AnimalFarm,) # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_method: - cat = animal.Animal(class_name="Cat", color="black") - body = animal_farm.AnimalFarm([cat]) + with patch.object(RESTClientObject, 'request') as mock_request: json_data = [{"className": "Cat", "color": "black"}] - mock_method.return_value = self.mock_response(json_data) - - response = self.api.array_model(body=body) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', - body=json_data, + mock_request.return_value = self.response( + self.json_bytes(json_data) ) - assert isinstance(response, animal_farm.AnimalFarm) - assert response == body + cat = animal.Animal(className="Cat", color="black") + body = animal_farm.AnimalFarm([cat]) + api_response = self.api.array_model(body=body) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', + body=self.json_bytes(json_data) + ) - def test_boolean(self): - """Test case for boolean - - """ - endpoint = self.api.boolean_endpoint - assert endpoint.openapi_types['body'] == (bool,) - assert endpoint.settings['response_type'] == (bool,) + assert isinstance(api_response.body, animal_farm.AnimalFarm) + assert api_response.body == body def test_recursionlimit(self): """Test case for recursionlimit @@ -126,660 +65,741 @@ class TestFakeApi(unittest.TestCase): """ assert sys.getrecursionlimit() == 1234 - def test_fake_health_get(self): - """Test case for fake_health_get - - Health check endpoint # noqa: E501 - """ - pass - - def test_additional_properties_with_array_of_enums(self): - """Test case for additional_properties_with_array_of_enums - - Additional Properties with Array of Enums # noqa: E501 - """ - pass - - def test_enum_test(self): - """Test case for enum_test - - Object contains enum properties and array properties containing enums - """ - from petstore_api.model.enum_test import EnumTest - from petstore_api.model.string_enum import StringEnum - from petstore_api.model.array_of_enums import ArrayOfEnums - - endpoint = self.api.enum_test_endpoint - assert endpoint.openapi_types['enum_test'] == (EnumTest,) - assert endpoint.settings['response_type'] == (EnumTest,) - - # serialization + deserialization works w/ inline array - with patch.object(RESTClientObject, 'request') as mock_method: - body = EnumTest( - enum_string_required='lower', - inline_array_of_str_enum=[StringEnum('approved')] - ) - json_value = {'enum_string_required': 'lower', 'InlineArrayOfStrEnum': ['approved']} - mock_method.return_value = self.mock_response(json_value) - - response = self.api.enum_test(enum_test=body) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', - body=json_value, - ) - - assert isinstance(response, EnumTest) - assert response == body - - # serialization + deserialization works w/ refed array - with patch.object(RESTClientObject, 'request') as mock_method: - body = EnumTest( - enum_string_required='lower', - array_of_str_enum=ArrayOfEnums([StringEnum('approved')]) - ) - json_value = {'enum_string_required': 'lower', 'ArrayOfStrEnum': ['approved']} - mock_method.return_value = self.mock_response(json_value) - - response = self.api.enum_test(enum_test=body) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', - body=json_value, - ) - - assert isinstance(response, EnumTest) - assert response == body - - def test_array_of_enums(self): - """Test case for array_of_enums - - Array of Enums # noqa: E501 - """ from petstore_api.model import array_of_enums, string_enum - endpoint = self.api.array_of_enums_endpoint - assert endpoint.openapi_types['array_of_enums'] == (array_of_enums.ArrayOfEnums,) - assert endpoint.settings['response_type'] == (array_of_enums.ArrayOfEnums,) # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_method: + with patch.object(RESTClientObject, 'request') as mock_request: value = [string_enum.StringEnum("placed")] body = array_of_enums.ArrayOfEnums(value) value_simple = ["placed"] - mock_method.return_value = self.mock_response(value_simple) - - response = self.api.array_of_enums(array_of_enums=body) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', - body=value_simple, + mock_request.return_value = self.response( + self.json_bytes(value_simple) ) - assert isinstance(response, array_of_enums.ArrayOfEnums) - assert response.value == value + api_response = self.api.array_of_enums(body=body) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', + body=self.json_bytes(value_simple) + ) + + assert isinstance(api_response.body, array_of_enums.ArrayOfEnums) + assert api_response.body == body def test_number_with_validations(self): - """Test case for number_with_validations - - """ from petstore_api.model import number_with_validations - endpoint = self.api.number_with_validations_endpoint - assert endpoint.openapi_types['body'] == (number_with_validations.NumberWithValidations,) - assert endpoint.settings['response_type'] == (number_with_validations.NumberWithValidations,) # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_method: + with patch.object(RESTClientObject, 'request') as mock_request: value = 10.0 body = number_with_validations.NumberWithValidations(value) - mock_method.return_value = self.mock_response(value) + mock_request.return_value = self.response( + self.json_bytes(value) + ) - response = self.api.number_with_validations(body=body) + api_response = self.api.number_with_validations(body=body) self.assert_request_called_with( - mock_method, + mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/number', - body=value, + body=self.json_bytes(value) ) - assert isinstance(response, number_with_validations.NumberWithValidations) - assert response.value == value + assert isinstance(api_response.body, number_with_validations.NumberWithValidations) + assert api_response.body == value - def test_object_model_with_ref_props(self): - """Test case for object_model_with_ref_props - - """ - from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps - from petstore_api.model.number_with_validations import NumberWithValidations - endpoint = self.api.object_model_with_ref_props_endpoint - assert endpoint.openapi_types['body'] == (ObjectModelWithRefProps,) - assert endpoint.settings['response_type'] == (ObjectModelWithRefProps,) - - json_payloads = [ - {}, # only required + no optional properties works - { # optional properties works - "my_number": 11.0, - "my_string": 'a', - "my_boolean": True, - } - ] - # instantiation works - expected_models = [ - ObjectModelWithRefProps(), - ObjectModelWithRefProps( - my_number=NumberWithValidations(11.0), - my_string='a', - my_boolean=True - ) - ] - - pairs = zip(json_payloads, expected_models) - # serialization + deserialization works - for (json_payload, expected_model) in pairs: - with patch.object(RESTClientObject, 'request') as mock_method: - mock_method.return_value = self.mock_response(json_payload) - - response = self.api.object_model_with_ref_props(body=expected_model) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/refs/object_model_with_ref_props', - body=json_payload, - ) - - assert isinstance(response, expected_model.__class__) - assert response == expected_model - - def test_composed_one_of_number_with_validations(self): - """Test case for composed_one_of_number_with_validations - - """ - from petstore_api.model import animal, composed_one_of_number_with_validations, number_with_validations - endpoint = self.api.composed_one_of_number_with_validations_endpoint - assert endpoint.openapi_types['composed_one_of_number_with_validations'] == ( - composed_one_of_number_with_validations.ComposedOneOfNumberWithValidations,) - assert endpoint.settings['response_type'] == ( - composed_one_of_number_with_validations.ComposedOneOfNumberWithValidations,) + def test_composed_one_of_different_types(self): + from petstore_api.model import composed_one_of_different_types # serialization + deserialization works - num_with_validations = number_with_validations.NumberWithValidations(10.0) - cat_in_composed = composed_one_of_number_with_validations.ComposedOneOfNumberWithValidations( - class_name="Cat", color="black" + number = composed_one_of_different_types.ComposedOneOfDifferentTypes(10.0) + cat = composed_one_of_different_types.ComposedOneOfDifferentTypes( + className="Cat", color="black" ) - import datetime - date = datetime.date(1970, 1, 1) - body_value_simple = [ - (num_with_validations, 10.0), - (cat_in_composed, {"className": "Cat", "color": "black"}), - (None, None), - (date, '1970-01-01'), + none_instance = composed_one_of_different_types.ComposedOneOfDifferentTypes(None) + date_instance = composed_one_of_different_types.ComposedOneOfDifferentTypes('1970-01-01') + cast_to_simple_value = [ + (number, 10.0), + (cat, {"className": "Cat", "color": "black"}), + (none_instance, None), + (date_instance, '1970-01-01'), ] - for (body, value_simple) in body_value_simple: - with patch.object(RESTClientObject, 'request') as mock_method: - mock_method.return_value = self.mock_response(value_simple) - - response = self.api.composed_one_of_number_with_validations(composed_one_of_number_with_validations=body) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', - body=value_simple, + for (body, value_simple) in cast_to_simple_value: + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = self.response( + self.json_bytes(value_simple) ) - assert isinstance(response, body.__class__) - assert response == body + api_response = self.api.composed_one_of_different_types(body=body) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', + body=self.json_bytes(value_simple) + ) + + assert isinstance(api_response.body, composed_one_of_different_types.ComposedOneOfDifferentTypes) + assert api_response.body == body + + # inputting the uncast values into the endpoint also works + for (body, value_simple) in cast_to_simple_value: + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = self.response( + self.json_bytes(value_simple) + ) + + api_response = self.api.composed_one_of_different_types(body=value_simple) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', + body=self.json_bytes(value_simple) + ) + + assert isinstance(api_response.body, composed_one_of_different_types.ComposedOneOfDifferentTypes) + assert api_response.body == body def test_string(self): - """Test case for string - - """ - endpoint = self.api.string_endpoint - assert endpoint.openapi_types['body'] == (str,) - assert endpoint.settings['response_type'] == (str,) - # serialization + deserialization works - with patch.object(RESTClientObject, 'request') as mock_method: + with patch.object(RESTClientObject, 'request') as mock_request: body = "blah" value_simple = body - mock_method.return_value = self.mock_response(value_simple) - - response = self.api.string(body=body) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/refs/string', - body=value_simple, + mock_request.return_value = self.response( + self.json_bytes(value_simple) ) - assert isinstance(response, str) - assert response == value_simple + api_response = self.api.string(body=body) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/refs/string', + body=self.json_bytes(value_simple) + ) + + assert isinstance(api_response.body, str) + assert api_response.body == value_simple def test_string_enum(self): - """Test case for string_enum - - """ from petstore_api.model import string_enum - endpoint = self.api.string_enum_endpoint - assert endpoint.openapi_types['body'] == (string_enum.StringEnum,) - assert endpoint.settings['response_type'] == (string_enum.StringEnum,) - # serialization + deserialization works - from petstore_api.rest import RESTClientObject, RESTResponse - with patch.object(RESTClientObject, 'request') as mock_method: + with patch.object(RESTClientObject, 'request') as mock_request: value = "placed" body = string_enum.StringEnum(value) - mock_method.return_value = self.mock_response(value) - - response = self.api.string_enum(body=body) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/refs/enum', - body=value, + mock_request.return_value = self.response( + self.json_bytes(value) ) - assert isinstance(response, string_enum.StringEnum) - assert response.value == value + api_response = self.api.string_enum(body=body) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/refs/enum', + body=self.json_bytes(value) + ) - def test_upload_file(self): - # uploads a file + assert isinstance(api_response.body, string_enum.StringEnum) + assert api_response.body == value + + def test_mammal(self): + # serialization + deserialization works + from petstore_api.model.mammal import Mammal + with patch.object(RESTClientObject, 'request') as mock_request: + body = Mammal(className="BasquePig") + value_simple = dict(className='BasquePig') + mock_request.return_value = self.response( + self.json_bytes(value_simple) + ) + + api_response = self.api.mammal(body=body) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/refs/mammal', + body=self.json_bytes(value_simple) + ) + + assert isinstance(api_response.body, Mammal) + assert api_response.body == value_simple + + def test_missing_or_unset_required_body(self): + # missing required body + with self.assertRaises(TypeError): + self.api.mammal() + # required body may not be unset + with self.assertRaises(petstore_api.ApiValueError): + self.api.mammal(body=schemas.unset) + + def test_missing_or_unset_required_query_parameter(self): + from petstore_api.model.user import User + user = User({}) + # missing required query param + with self.assertRaises(petstore_api.ApiTypeError): + self.api.body_with_query_params(body=user) + # required query param may not be unset + with self.assertRaises(petstore_api.ApiValueError): + self.api.body_with_query_params(body=schemas.unset, query_params=dict(query=schemas.unset)) + + def test_body_with_query_params(self): + from petstore_api.model import user + with patch.object(RESTClientObject, 'request') as mock_request: + + value_simple = dict( + id=1, + username='first last', + firstName='first', + lastName='last' + ) + body = user.User(**value_simple) + mock_request.return_value = self.response( + b'' + ) + + api_response = self.api.body_with_query_params( + body=body, + query_params=dict(query='hi there') + ) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/body-with-query-params?query=hi%20there', + method='PUT', + body=self.json_bytes(value_simple), + accept_content_type=None + ) + + assert isinstance(api_response.body, api_client.Unset) + assert api_response.response.status == 200 + + def test_upload_download_file_tx_bytes_and_file(self): + """Test case for upload_download_file + uploads a file and downloads a file using application/octet-stream # noqa: E501 + """ + import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) - file_path1 = os.path.join(test_file_dir, "1px_pic1.png") + file_name = '1px_pic1.png' + file_path1 = os.path.join(test_file_dir, file_name) - headers = {} - def get_headers(): - return headers - def get_header(name, default=None): - return headers.get(name, default) - api_respponse = { - 'code': 200, - 'type': 'blah', - 'message': 'file upload succeeded' - } - http_response = HTTPResponse( - status=200, - reason='OK', - data=json.dumps(api_respponse).encode('utf-8'), - getheaders=get_headers, - getheader=get_header - ) - mock_response = RESTResponse(http_response) + with open(file_path1, "rb") as some_file: + file_bytes = some_file.read() file1 = open(file_path1, "rb") + mock_response = self.response( + file_bytes, + content_type='application/octet-stream' + ) try: - with patch.object(RESTClientObject, 'request') as mock_method: - mock_method.return_value = mock_response - res = self.api.upload_file( - file=file1) - body = None - post_params=[ - ('file', ('1px_pic1.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')), - ] + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = mock_response + api_response = self.api.upload_download_file(body=file1) self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/uploadFile', - body=body, post_params=post_params, content_type='multipart/form-data' + mock_request, + 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', + body=file_bytes, + content_type='application/octet-stream', + accept_content_type='application/octet-stream' ) + self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) + self.assertTrue(isinstance(api_response.body, schemas.BytesSchema)) + self.assertTrue(isinstance(api_response.body, bytes)) + self.assertEqual(api_response.body, file_bytes) except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.close() - # passing in an array of files to when file only allows one - # raises an exceptions - try: - file = open(file_path1, "rb") - with self.assertRaises(petstore_api.ApiTypeError) as exc: - self.api.upload_file(file=[file]) - finally: - file.close() + # sending just bytes works also + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = mock_response + api_response = self.api.upload_download_file(body=file_bytes) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', + body=file_bytes, + content_type='application/octet-stream', + accept_content_type='application/octet-stream' + ) + self.assertEqual(api_response.body, file_bytes) - # passing in a closed file raises an exception - with self.assertRaises(petstore_api.ApiValueError) as exc: - file = open(file_path1, "rb") - file.close() - self.api.upload_file(file=file) - - def test_upload_files(self): + def test_upload_download_file_rx_file(self): + import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) - file_path1 = os.path.join(test_file_dir, "1px_pic1.png") - file_path2 = os.path.join(test_file_dir, "1px_pic2.png") + file_name = '1px_pic1.png' + file_path1 = os.path.join(test_file_dir, file_name) - headers = {} - def get_headers(): - return headers - def get_header(name, default=None): - return headers.get(name, default) - api_respponse = { + with open(file_path1, "rb") as some_file: + file_bytes = some_file.read() + + # passing in file1 as the response body simulates a streamed response + file1 = open(file_path1, "rb") + + class StreamableBody: + """ + This class simulates http.client.HTTPResponse for a streamable response + """ + def __init__(self, file: io.BufferedReader): + self.fp = file + + def read(self, *args, **kwargs): + return self.fp.read(*args, **kwargs) + + def close(self): + self.fp.close() + + streamable_body = StreamableBody(file1) + + mock_response = self.response( + streamable_body, + content_type='application/octet-stream', + preload_content=False + ) + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = mock_response + api_response = self.api.upload_download_file(body=file_bytes, stream=True) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', + body=file_bytes, + content_type='application/octet-stream', + accept_content_type='application/octet-stream', + stream=True + ) + self.assertTrue(file1.closed) + self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) + self.assertTrue(isinstance(api_response.body, schemas.FileSchema)) + self.assertTrue(isinstance(api_response.body, schemas.FileIO)) + self.assertEqual(api_response.body.read(), file_bytes) + api_response.body.close() + os.unlink(api_response.body.name) + + file1 = open(file_path1, "rb") + streamable_body = StreamableBody(file1) + saved_file_name = "fileName.abc" + + """ + when streaming is used and the response contains the content disposition header with a filename + that filename is used when saving the file locally + """ + mock_response = self.response( + streamable_body, + content_type='application/octet-stream', + headers={'content-disposition': f'attachment; filename="{saved_file_name}"'}, + preload_content=False + ) + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = mock_response + api_response = self.api.upload_download_file(body=file_bytes, stream=True) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', + body=file_bytes, + content_type='application/octet-stream', + accept_content_type='application/octet-stream', + stream=True + ) + self.assertTrue(file1.closed) + self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) + self.assertTrue(isinstance(api_response.body, schemas.FileSchema)) + self.assertTrue(isinstance(api_response.body, schemas.FileIO)) + self.assertTrue(api_response.body.name.endswith(saved_file_name)) + self.assertEqual(api_response.body.read(), file_bytes) + api_response.body.close() + os.unlink(api_response.body.name) + + """ + when streaming is used and the response contains the content disposition header without a filename + the url of response is used to extract the filename. + """ + file1 = open(file_path1, "rb") + streamable_body = StreamableBody(file1) + expected_filename = "the_file.ext" + + no_filename_mock_response = self.response( + streamable_body, + content_type='application/octet-stream', + headers={'content-disposition': 'attachment'}, + preload_content=False + ) + + with patch.object(RESTClientObject, 'request') as mock_request: + no_filename_mock_response.geturl = lambda: f'http://foo.bar/{expected_filename}' + mock_request.return_value = no_filename_mock_response + api_response = self.api.upload_download_file(body=file_bytes, stream=True) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', + body=file_bytes, + content_type='application/octet-stream', + accept_content_type='application/octet-stream', + stream=True + ) + self.assertTrue(file1.closed) + self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) + self.assertTrue(isinstance(api_response.body, schemas.FileSchema)) + self.assertTrue(isinstance(api_response.body, schemas.FileIO)) + self.assertTrue(api_response.body.name.endswith(expected_filename)) + self.assertEqual(api_response.body.read(), file_bytes) + api_response.body.close() + os.unlink(api_response.body.name) + + def test_upload_file(self): + """Test case for upload_file + uploads a file using multipart/form-data # noqa: E501 + """ + import os + test_file_dir = os.path.realpath( + os.path.join(os.path.dirname(__file__), "..", "testfiles")) + file_name = '1px_pic1.png' + file_path1 = os.path.join(test_file_dir, file_name) + + with open(file_path1, "rb") as some_file: + file_bytes = some_file.read() + file1 = open(file_path1, "rb") + response_json = { 'code': 200, 'type': 'blah', 'message': 'file upload succeeded' } - http_response = HTTPResponse( - status=200, - reason='OK', - data=json.dumps(api_respponse).encode('utf-8'), - getheaders=get_headers, - getheader=get_header - ) - mock_response = RESTResponse(http_response) - file1 = open(file_path1, "rb") - file2 = open(file_path2, "rb") try: - with patch.object(RESTClientObject, 'request') as mock_method: - mock_method.return_value = mock_response - res = self.api.upload_files( - files=[file1, file2]) - post_params=[ - ('files', ('1px_pic1.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')), - ('files', ('1px_pic2.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')) - ] - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/uploadFiles', - body=None, post_params=post_params, content_type='multipart/form-data' + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = self.response( + self.json_bytes(response_json) ) + api_response = self.api.upload_file(body={'file': file1}) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/uploadFile', + fields=( + api_client.RequestField( + name='file', + data=file_bytes, + filename=file_name, + headers={'Content-Type': 'application/octet-stream'} + ), + ), + content_type='multipart/form-data' + ) + self.assertEqual(api_response.body, response_json) + except petstore_api.ApiException as e: + self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + finally: + file1.close() + + # sending just bytes works also + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = self.response( + self.json_bytes(response_json) + ) + api_response = self.api.upload_file(body={'file': file_bytes}) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/uploadFile', + fields=( + api_client.RequestField( + name='file', + data=file_bytes, + headers={'Content-Type': 'application/octet-stream'} + ), + ), + content_type='multipart/form-data' + ) + self.assertEqual(api_response.body, response_json) + + # passing in an array of files to when file only allows one + # raises an exceptions + try: + file = open(file_path1, "rb") + with self.assertRaises(petstore_api.ApiTypeError): + self.api.upload_file(body={'file': [file]}) + finally: + file.close() + + # passing in a closed file raises an exception + with self.assertRaises(ValueError): + file = open(file_path1, "rb") + file.close() + self.api.upload_file(body={'file': file}) + + def test_upload_files(self): + """Test case for upload_files + uploads files using multipart/form-data # noqa: E501 + """ + import os + test_file_dir = os.path.realpath( + os.path.join(os.path.dirname(__file__), "..", "testfiles")) + file_name = '1px_pic1.png' + file_path1 = os.path.join(test_file_dir, file_name) + + with open(file_path1, "rb") as some_file: + file_bytes = some_file.read() + file1 = open(file_path1, "rb") + file2 = open(file_path1, "rb") + response_json = { + 'code': 200, + 'type': 'blah', + 'message': 'file upload succeeded' + } + try: + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = self.response( + self.json_bytes(response_json) + ) + api_response = self.api.upload_files(body={'files': [file1, file2]}) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/uploadFiles', + fields=( + api_client.RequestField( + name='files', + data=file_bytes, + filename=file_name, + headers={'Content-Type': 'application/octet-stream'} + ), + api_client.RequestField( + name='files', + data=file_bytes, + filename=file_name, + headers={'Content-Type': 'application/octet-stream'} + ), + ), + content_type='multipart/form-data' + ) + self.assertEqual(api_response.body, response_json) except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.close() file2.close() - # passing in a single file when an array of file is required - # raises an exception - try: - file = open(file_path1, "rb") - with self.assertRaises(petstore_api.ApiTypeError) as exc: - self.api.upload_files(files=file) - finally: - file.close() - - def test_download_attachment(self): - """Ensures that file deserialization works""" - - # sample from http://www.jtricks.com/download-text - file_name = 'content.txt' - headers_dict = { - 'with_filename': {'Content-Disposition': 'attachment; filename={}'.format(file_name), 'Content-Type': 'text/plain'}, - 'no_filename': {'Content-Disposition': 'attachment;', 'Content-Type': 'text/plain'} - } - def get_headers(*args): - return args - file_data = ( - "You are reading text file that was supposed to be downloaded\r\n" - "to your hard disk. If your browser offered to save you the file," - "\r\nthen it handled the Content-Disposition header correctly." - ) - for key, headers in headers_dict.items(): - def get_header(name, default=None): - return headers_dict[key].get(name, default) - http_response = HTTPResponse( - status=200, - reason='OK', - data=file_data, - getheaders=get_headers(headers), - getheader=get_header + # sending just bytes works also + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = self.response( + self.json_bytes(response_json) ) - # deserialize response to a file - mock_response = RESTResponse(http_response) - with patch.object(RESTClientObject, 'request') as mock_method: - mock_method.return_value = mock_response - try: - file_object = self.api.download_attachment(file_name='download-text') - self.assert_request_called_with( - mock_method, - 'http://www.jtricks.com/download-text', - http_method='GET', - accept='text/plain', - content_type=None, + api_response = self.api.upload_files(body={'files': [file_bytes, file_bytes]}) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/uploadFiles', + fields=( + api_client.RequestField( + name='files', + data=file_bytes, + headers={'Content-Type': 'application/octet-stream'} + ), + api_client.RequestField( + name='files', + data=file_bytes, + headers={'Content-Type': 'application/octet-stream'} + ), + ), + content_type='multipart/form-data' + ) + self.assertEqual(api_response.body, response_json) + + @staticmethod + def __encode_multipart_formdata(fields: typing.Dict[str, typing.Any]) -> multipart.MIMEMultipart: + m = multipart.MIMEMultipart("form-data") + + for field, value in fields.items(): + data = MIMEFormdata(field, "text", "plain") + # data.set_payload(value, charset='us-ascii') + data.set_payload(value) + m.attach(data) + + return m + + @patch.object(RESTClientObject, 'request') + def test_inline_composition(self, mock_request): + """Test case for inline_composition + + testing composed schemas at inline locations # noqa: E501 + """ + single_char_str = 'a' + json_bytes = self.json_bytes(single_char_str) + + # tx and rx json with composition at root level of schema for request + response body + content_type = 'application/json' + mock_request.return_value = self.response( + json_bytes + ) + api_response = self.api.inline_composition( + body=single_char_str, + query_params={ + 'compositionAtRoot': single_char_str, + 'compositionInProperty': {'someProp': single_char_str} + }, + accept_content_types=(content_type,) + ) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/inlineComposition/?compositionAtRoot=a&someProp=a', + accept_content_type=content_type, + content_type=content_type, + body=json_bytes + ) + self.assertEqual(api_response.body, single_char_str) + self.assertTrue(isinstance(api_response.body, schemas.StrSchema)) + + # tx and rx json with composition at property level of schema for request + response body + content_type = 'multipart/form-data' + multipart_response = self.__encode_multipart_formdata(fields={'someProp': single_char_str}) + mock_request.return_value = self.response( + bytes(multipart_response), + content_type=multipart_response.get_content_type() + ) + api_response = self.api.inline_composition( + body={'someProp': single_char_str}, + query_params={ + 'compositionAtRoot': single_char_str, + 'compositionInProperty': {'someProp': single_char_str} + }, + content_type=content_type, + accept_content_types=(content_type,) + ) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/inlineComposition/?compositionAtRoot=a&someProp=a', + accept_content_type=content_type, + content_type=content_type, + fields=( + api_client.RequestField( + name='someProp', + data=single_char_str, + headers={'Content-Type': 'text/plain'} + ), + ), + ) + self.assertEqual(api_response.body, {'someProp': single_char_str}) + self.assertTrue(isinstance(api_response.body["someProp"], schemas.StrSchema)) + + # error thrown when a str is input which doesn't meet the composed schema length constraint + invalid_value = '' + variable_locations = 4 + for invalid_index in range(variable_locations): + values = [single_char_str]*variable_locations + values[invalid_index] = invalid_value + with self.assertRaises(exceptions.ApiValueError): + multipart_response = self.__encode_multipart_formdata(fields={'someProp': values[0]}) + mock_request.return_value = self.response( + bytes(multipart_response), + content_type=multipart_response.get_content_type() + ) + self.api.inline_composition( + body={'someProp': values[1]}, + query_params={ + 'compositionAtRoot': values[2], + 'compositionInProperty': {'someProp': values[3]} + }, + content_type=content_type, + accept_content_types=(content_type,) + ) + + def test_json_with_charset(self): + # serialization + deserialization of json with charset works + with patch.object(RESTClientObject, 'request') as mock_request: + body = None + content_type_with_charset = 'application/json; charset=utf-8' + mock_request.return_value = self.response( + self.json_bytes(body), + content_type=content_type_with_charset + ) + + api_response = self.api.json_with_charset(body=body) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/jsonWithCharset', + body=self.json_bytes(body), + content_type=content_type_with_charset, + accept_content_type=content_type_with_charset + ) + + assert isinstance(api_response.body, schemas.AnyTypeSchema) + assert isinstance(api_response.body, schemas.NoneClass) + assert api_response.body.is_none_oapg() + + def test_response_without_schema(self): + # received response is not loaded into body because there is no deserialization schema defined + with patch.object(RESTClientObject, 'request') as mock_request: + body = None + content_type = 'application/json' + mock_request.return_value = self.response( + self.json_bytes(body), + ) + + api_response = self.api.response_without_schema() + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/responseWithoutSchema', + method='GET', + accept_content_type='application/json, application/xml', + content_type=None + ) + + assert isinstance(api_response.body, schemas.Unset) + + + with patch.object(RESTClientObject, 'request') as mock_request: + mock_request.return_value = self.response( + 'blah', + content_type='text/plain' + ) + + # when an incorrect content-type is sent back, and exception is raised + with self.assertRaises(exceptions.ApiValueError): + self.api.response_without_schema() + + def test_delete_endpoint_without_request_body(self): + with patch.object(urllib3.PoolManager, 'request') as mock_request: + + body = None + mock_request.return_value = self.response( + self.json_bytes(body), + ) + + api_response = self.api.delete_coffee(path_params=dict(id='1')) + self.assert_pool_manager_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/deleteCoffee/1', + method='DELETE', + content_type=None, + accept_content_type=None, + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + assert isinstance(api_response.headers, schemas.Unset) + + def test_json_patch(self): + with patch.object(urllib3.PoolManager, 'request') as mock_request: + from petstore_api.model import json_patch_request + from petstore_api.model import json_patch_request_add_replace_test + + mock_request.return_value = self.response("") + body = json_patch_request.JSONPatchRequest( + [ + json_patch_request_add_replace_test.JSONPatchRequestAddReplaceTest( + op='add', + path='/a/b/c', + value='foo', ) - self.assertTrue(isinstance(file_object, file_type)) - self.assertFalse(file_object.closed) - self.assertEqual(file_object.read(), file_data.encode('utf-8')) - finally: - file_object.close() - os.unlink(file_object.name) - - def test_upload_download_file(self): - test_file_dir = os.path.realpath( - os.path.join(os.path.dirname(__file__), "..", "testfiles")) - file_path1 = os.path.join(test_file_dir, "1px_pic1.png") - - with open(file_path1, "rb") as f: - expected_file_data = f.read() - - headers = {'Content-Type': 'application/octet-stream'} - def get_headers(): - return headers - def get_header(name, default=None): - return headers.get(name, default) - http_response = HTTPResponse( - status=200, - reason='OK', - data=expected_file_data, - getheaders=get_headers, - getheader=get_header - ) - mock_response = RESTResponse(http_response) - file1 = open(file_path1, "rb") - try: - with patch.object(RESTClientObject, 'request') as mock_method: - mock_method.return_value = mock_response - downloaded_file = self.api.upload_download_file(body=file1) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', - body=expected_file_data, - content_type='application/octet-stream', - accept='application/octet-stream' - ) - - self.assertTrue(isinstance(downloaded_file, file_type)) - self.assertFalse(downloaded_file.closed) - self.assertEqual(downloaded_file.read(), expected_file_data) - except petstore_api.ApiException as e: - self.fail("upload_download_file() raised {0} unexpectedly".format(type(e))) - finally: - file1.close() - downloaded_file.close() - os.unlink(downloaded_file.name) - - def test_test_body_with_file_schema(self): - """Test case for test_body_with_file_schema - - """ - pass - - def test_test_body_with_query_params(self): - """Test case for test_body_with_query_params - - """ - pass - - def test_test_client_model(self): - """Test case for test_client_model - - To test \"client\" model # noqa: E501 - """ - pass - - def test_test_endpoint_parameters(self): - """Test case for test_endpoint_parameters - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 - """ - pass - - def test_test_enum_parameters(self): - """Test case for test_enum_parameters - - To test enum parameters # noqa: E501 - """ - pass - - def test_test_group_parameters(self): - """Test case for test_group_parameters - - Fake endpoint to test group parameters (optional) # noqa: E501 - """ - pass - - def test_test_inline_additional_properties(self): - """Test case for test_inline_additional_properties - - test inline additionalProperties # noqa: E501 - """ - pass - - def test_test_json_form_data(self): - """Test case for test_json_form_data - - test json serialization of form data # noqa: E501 - """ - pass - - def test_test_query_parameter_collection_format(self): - """Test case for test_query_parameter_collection_format - - """ - pass - - def test_post_inline_additional_properties_ref_payload(self): - """Test case for postInlineAdditionlPropertiesRefPayload - """ - from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload - from petstore_api.model.post_inline_additional_properties_payload_request_array_data_inner import PostInlineAdditionalPropertiesPayloadRequestArrayDataInner - endpoint = self.api.post_inline_additional_properties_ref_payload_endpoint - assert endpoint.openapi_types['inline_additional_properties_ref_payload'] == (InlineAdditionalPropertiesRefPayload,) - assert endpoint.settings['response_type'] == (InlineAdditionalPropertiesRefPayload,) - - # serialization + deserialization works - from petstore_api.rest import RESTClientObject, RESTResponse - with patch.object(RESTClientObject, 'request') as mock_method: - expected_json_body = { - 'arrayData': [ - { - 'labels': [ - None, - 'foo' - ] - } - ] - } - inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( - array_data=[ - PostInlineAdditionalPropertiesPayloadRequestArrayDataInner(labels=[None, 'foo']) ] ) - mock_method.return_value = self.mock_response(expected_json_body) - - response = self.api.post_inline_additional_properties_ref_payload(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/postInlineAdditionalPropertiesRefPayload', - body=expected_json_body + api_response = self.api.json_patch(body=body) + json_body = [ + { + 'op': 'add', + 'path': '/a/b/c', + 'value': 'foo' + } + ] + self.assert_pool_manager_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/fake/jsonPatch', + body=self.json_bytes(json_body), + method='PATCH', + content_type='application/json-patch+json', + accept_content_type=None, ) - assert isinstance(response, InlineAdditionalPropertiesRefPayload) - assert model_to_dict(response) == expected_json_body + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + assert isinstance(api_response.headers, schemas.Unset) + assert api_response.response.status == 200 - def test_post_inline_additional_properties_payload(self): - """Test case for postInlineAdditionlPropertiesPayload - """ - from petstore_api.model.post_inline_additional_properties_payload_request import PostInlineAdditionalPropertiesPayloadRequest - from petstore_api.model.post_inline_additional_properties_payload_request_array_data_inner import PostInlineAdditionalPropertiesPayloadRequestArrayDataInner - endpoint = self.api.post_inline_additional_properties_payload_endpoint - assert endpoint.openapi_types['post_inline_additional_properties_payload_request'] == (PostInlineAdditionalPropertiesPayloadRequest,) - assert endpoint.settings['response_type'] == (PostInlineAdditionalPropertiesPayloadRequest,) - - # serialization + deserialization works - from petstore_api.rest import RESTClientObject, RESTResponse - with patch.object(RESTClientObject, 'request') as mock_method: - expected_json_body = { - 'arrayData': [ - { - 'labels': [ - None, - 'foo' - ] - } - ] - } - post_inline_additional_properties_payload_request = PostInlineAdditionalPropertiesPayloadRequest( - array_data=[ - PostInlineAdditionalPropertiesPayloadRequestArrayDataInner(labels=[None, 'foo']) - ] - ) - mock_method.return_value = self.mock_response(expected_json_body) - - response = self.api.post_inline_additional_properties_payload(post_inline_additional_properties_payload_request=post_inline_additional_properties_payload_request) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/postInlineAdditionalPropertiesPayload', - body=expected_json_body - ) - - assert isinstance(response, PostInlineAdditionalPropertiesPayloadRequest) - assert model_to_dict(response) == expected_json_body - - def test_post_tx_rx_any_of_payload(self): - """Test case for postInlineAdditionlPropertiesPayload - """ - from petstore_api.model.gm_fruit_no_properties import GmFruitNoProperties - endpoint = self.api.tx_rx_any_of_model_endpoint - assert endpoint.openapi_types['gm_fruit_no_properties'] == (GmFruitNoProperties,) - assert endpoint.settings['response_type'] == (GmFruitNoProperties,) - - # serialization + deserialization works - from petstore_api.rest import RESTClientObject, RESTResponse - with patch.object(RESTClientObject, 'request') as mock_method: - expected_json_body = { - 'cultivar': 'Alice', - 'origin': 'Kazakhstan', - 'lengthCm': 7, - } - fruit = GmFruitNoProperties(**expected_json_body) - mock_method.return_value = self.mock_response(expected_json_body) - - response = self.api.tx_rx_any_of_model(gm_fruit_no_properties=fruit) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/TxRxAnyOfModel', - body=expected_json_body - ) - - assert isinstance(response, GmFruitNoProperties) - assert model_to_dict(response) == expected_json_body - - def test_post_tx_rx_all_of_payload(self): - """Test case for postInlineAdditionlPropertiesPayload - """ - from petstore_api.model.stream_options import StreamOptions - from petstore_api.model.publish_options_publish import PublishOptionsPublish - endpoint = self.api.tx_rx_all_of_model_endpoint - assert endpoint.openapi_types['stream_options'] == (StreamOptions,) - assert endpoint.settings['response_type'] == (StreamOptions,) - - # serialization + deserialization works - from petstore_api.rest import RESTClientObject, RESTResponse - with patch.object(RESTClientObject, 'request') as mock_method: - expected_json_body = { - "egressThresholds": { - "person":0.8 - }, - "publish": { - "egressUnknownDetections": False - } - } - stream_option_instance = StreamOptions(**expected_json_body) - mock_method.return_value = self.mock_response(expected_json_body) - - response = self.api.tx_rx_all_of_model(stream_options=stream_option_instance) - self.assert_request_called_with( - mock_method, - 'http://petstore.swagger.io:80/v2/fake/TxRxAllOfModel', - body=expected_json_body - ) - - assert isinstance(response, StreamOptions) - assert model_to_dict(response) == expected_json_body - assert response.publish == PublishOptionsPublish(**{"egress_unknown_detections": False}) if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_format_test.py b/samples/openapi3/client/petstore/python/tests_manual/test_format_test.py new file mode 100644 index 0000000000..960d095751 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_format_test.py @@ -0,0 +1,137 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from decimal import Decimal +import datetime +import unittest + +import frozendict + +import petstore_api +from petstore_api.model.format_test import FormatTest +from petstore_api.schemas import BinarySchema, BytesSchema, Singleton + + +class TestFormatTest(unittest.TestCase): + """FormatTest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_FormatTest(self): + """Test FormatTest""" + + required_args = dict( + number=32.5, + byte='a', + date='2021-01-01', + password='abcdefghij' + ) + # int32 + # under min + with self.assertRaises(petstore_api.ApiValueError): + model = FormatTest(int32=-2147483649, **required_args) + # over max + with self.assertRaises(petstore_api.ApiValueError): + model = FormatTest(int32=2147483648, **required_args) + # valid values in range work + valid_values = [-2147483648, 2147483647] + for valid_value in valid_values: + model = FormatTest(int32=valid_value, **required_args) + assert model["int32"] == valid_value + + # int64 + # under min + with self.assertRaises(petstore_api.ApiValueError): + FormatTest(int64=-9223372036854775809, **required_args) + # over max + with self.assertRaises(petstore_api.ApiValueError): + FormatTest(int64=9223372036854775808, **required_args) + # valid values in range work + valid_values = [-9223372036854775808, 9223372036854775807] + for valid_value in valid_values: + model = FormatTest(int64=valid_value, **required_args) + assert model["int64"] == valid_value + + # float32 + # under min + with self.assertRaises(petstore_api.ApiValueError): + FormatTest(float32=-3.402823466385289e+38, **required_args) + # over max + with self.assertRaises(petstore_api.ApiValueError): + FormatTest(float32=3.402823466385289e+38, **required_args) + # valid values in range work + valid_values = [-3.4028234663852886e+38, 3.4028234663852886e+38] + for valid_value in valid_values: + model = FormatTest(float32=valid_value, **required_args) + assert model["float32"] == valid_value + + # float64 + # under min, Decimal is used because flat can only store 64bit numbers and the max and min + # take up more space than 64bit + with self.assertRaises(petstore_api.ApiValueError): + FormatTest(float64=Decimal('-1.7976931348623157082e+308'), **required_args) + # over max + with self.assertRaises(petstore_api.ApiValueError): + FormatTest(float64=Decimal('1.7976931348623157082e+308'), **required_args) + valid_values = [-1.7976931348623157E+308, 1.7976931348623157E+308] + for valid_value in valid_values: + model = FormatTest(float64=valid_value, **required_args) + assert model["float64"] == valid_value + + # unique_items with duplicates throws exception + with self.assertRaises(petstore_api.ApiValueError): + FormatTest(arrayWithUniqueItems=[0, 1, 1], **required_args) + # no duplicates works + values = [0, 1, 2] + model = FormatTest(arrayWithUniqueItems=values, **required_args) + assert model["arrayWithUniqueItems"] == tuple(values) + + # __bool__ value of noneProp is False + model = FormatTest(noneProp=None, **required_args) + assert isinstance(model["noneProp"], Singleton) + self.assertFalse(model["noneProp"]) + self.assertTrue(model["noneProp"].is_none_oapg()) + + # binary check + model = FormatTest(binary=b'123', **required_args) + assert isinstance(model["binary"], BinarySchema) + assert isinstance(model["binary"], BytesSchema) + assert isinstance(model["binary"], bytes) + assert model == frozendict.frozendict( + binary=b'123', + number=Decimal(32.5), + byte='a', + date='2021-01-01', + password='abcdefghij' + ) + + def test_multiple_of(self): + with self.assertRaisesRegex( + petstore_api.exceptions.ApiValueError, + r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)" + ): + FormatTest( + byte='3', + date=datetime.date(2000, 1, 1), + password="abcdefghijkl", + integer=31, # Value is supposed to be multiple of '2'. An error must be raised + number=65.0, + float=62.4 + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_fruit.py b/samples/openapi3/client/petstore/python/tests_manual/test_fruit.py index a0f97a4a97..6f1a226555 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_fruit.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_fruit.py @@ -9,238 +9,125 @@ Generated by: https://openapi-generator.tech """ - -import sys import unittest import petstore_api from petstore_api.model import apple from petstore_api.model import banana from petstore_api.model.fruit import Fruit +from petstore_api import schemas class TestFruit(unittest.TestCase): """Fruit unit test stubs""" - length_cm = 20.3 - color = 'yellow' - - - def setUp(self): - pass - - def tearDown(self): - pass - - def test_fruit_with_additional_props(self): - # including extra parameters works because the oneOf models include additionalProperties - some_value = 'some_value' - some_fruit = Fruit( - color=self.color, - length_cm=self.length_cm, - unknown_property=some_value - ) - assert some_fruit['unknown_property'] == some_value - - def test_fruit_assigning_additional_props_in_client(self): - # setting a value that doesn't exist works because additional_properties_type allows any type - other_fruit = Fruit(length_cm=self.length_cm, color=self.color) - blah = 'blah' - other_fruit['a'] = blah - assert other_fruit.a == blah - - # with setattr - setattr(other_fruit, 'b', blah) - assert other_fruit.b == blah - - self.assertEqual( - other_fruit.to_dict(), - { - 'a': 'blah', - 'b': 'blah', - 'length_cm': self.length_cm, - 'color': self.color - } - ) - - def test_fruit_access_errors(self): - fruit = Fruit(length_cm=self.length_cm, color=self.color) - - # getting a value that doesn't exist raises an exception - # with a key - with self.assertRaises(AttributeError): - invalid_variable = fruit['cultivar'] - - # Per Python doc, if the named attribute does not exist, - # default is returned if provided, otherwise AttributeError is raised. - with self.assertRaises(AttributeError): - getattr(fruit, 'cultivar') - - def test_fruit_attribute_access(self): - fruit = Fruit(length_cm=self.length_cm, color=self.color) - - # Assert that we can call the builtin hasattr() function. - # hasattr should return False for non-existent attribute. - # Internally hasattr catches the AttributeError exception. - self.assertFalse(hasattr(fruit, 'invalid_variable')) - - # Assert that we can call the builtin hasattr() function. - # hasattr should return True for existent attribute. - self.assertTrue(hasattr(fruit, 'color')) - - # with getattr - # Per Python doc, if the named attribute does not exist, - # default is returned if provided. - self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value') - self.assertEqual(fruit.get('cultivar'), None) - self.assertEqual(fruit.get('cultivar', 'some value'), 'some value') - - def test_banana_fruit(self): + def testFruit(self): """Test Fruit""" # make an instance of Fruit, a composed schema oneOf model # banana test - fruit = Fruit(length_cm=self.length_cm, color=self.color) + length_cm = 20.3 + color = 'yellow' + fruit = Fruit(lengthCm=length_cm, color=color) # check its properties - self.assertEqual(fruit.length_cm, self.length_cm) - self.assertEqual(fruit['length_cm'], self.length_cm) - self.assertEqual(fruit.get('length_cm'), self.length_cm) - self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) - self.assertEqual(fruit.color, self.color) - self.assertEqual(fruit['color'], self.color) - self.assertEqual(getattr(fruit, 'color'), self.color) + self.assertEqual(fruit['lengthCm'], length_cm) + self.assertEqual(fruit.get('lengthCm'), length_cm) + self.assertEqual(fruit['color'], color) + self.assertEqual(fruit.get('color'), color) + # check the dict representation self.assertEqual( - fruit.to_dict(), + fruit, { - 'length_cm': self.length_cm, - 'color': self.color + 'lengthCm': length_cm, + 'color': color } ) + # setting values after instance creation is not allowed + with self.assertRaises(TypeError): + fruit['color'] = 'some value' + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(KeyError): + assert fruit['cultivar'] + assert fruit.get_item_oapg('cultivar') is schemas.unset # make sure that the ModelComposed class properties are correct - # model._composed_schemas stores the anyOf/allOf/oneOf info self.assertEqual( - fruit._composed_schemas, - { - 'anyOf': [], - 'allOf': [], - 'oneOf': [ - apple.Apple, - banana.Banana, - ], - } - ) - # model._composed_instances is a list of the instances that were - # made from the anyOf/allOf/OneOf classes in model._composed_schemas - self.assertEqual(len(fruit._composed_instances), 1) - for composed_instance in fruit._composed_instances: - if composed_instance.__class__ == banana.Banana: - banana_instance = composed_instance - self.assertEqual( - fruit._composed_instances, - [banana_instance] - ) - # model._var_name_to_model_instances maps the variable name to the - # model instances which store that variable - print(fruit._var_name_to_model_instances) - self.assertEqual( - fruit._var_name_to_model_instances, - { - 'color': [fruit], - 'length_cm': [fruit, banana_instance], - } - ) - self.assertEqual( - fruit._additional_properties_model_instances, [fruit] + Fruit.MetaOapg.one_of(), + [ + apple.Apple, + banana.Banana, + ], ) - # if we modify one of the properties owned by multiple - # model_instances we get an exception when we try to access that - # property because the retrieved values are not all the same - banana_instance.length_cm = 4.56 - with self.assertRaises(petstore_api.ApiValueError): - some_length_cm = fruit.length_cm + """ + including extra parameters does not raise an exception + because objects support additional properties by default + """ + kwargs = dict( + color=color, + lengthCm=length_cm, + additional_string='some value', + additional_date='2021-01-02', + ) + + fruit = Fruit.from_openapi_data_oapg(**kwargs) + self.assertEqual( + fruit, + kwargs + ) + + fruit = Fruit(**kwargs) + self.assertEqual( + fruit, + kwargs + ) # including input parameters for two oneOf instances raise an exception with self.assertRaises(petstore_api.ApiValueError): - fruit = Fruit( - length_cm=self.length_cm, + Fruit( + lengthCm=length_cm, cultivar='granny smith' ) - def test_apple_fruit(self): - # make an instance of Fruit, a composed schema oneOf model # apple test color = 'red' cultivar = 'golden delicious' fruit = Fruit(color=color, cultivar=cultivar) # check its properties - self.assertEqual(fruit.color, color) self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) - self.assertEqual(fruit.cultivar, cultivar) self.assertEqual(fruit['cultivar'], cultivar) - self.assertEqual(getattr(fruit, 'cultivar'), cultivar) # check the dict representation self.assertEqual( - fruit.to_dict(), + fruit, { 'color': color, 'cultivar': cultivar } ) - # model._composed_instances is a list of the instances that were - # made from the anyOf/allOf/OneOf classes in model._composed_schemas - for composed_instance in fruit._composed_instances: - if composed_instance.__class__ == apple.Apple: - apple_instance = composed_instance - self.assertEqual( - fruit._composed_instances, - [apple_instance] - ) - # model._var_name_to_model_instances maps the variable name to the - # model instances which store that variable - self.assertEqual( - fruit._var_name_to_model_instances, - { - 'color': [fruit], - 'cultivar': [fruit, apple_instance], - } - ) - self.assertEqual( - fruit._additional_properties_model_instances, [fruit] - ) - - def test_null_fruit(self): + def testFruitNullValue(self): # Since 'apple' is nullable, validate we can create an apple with the 'null' value. fruit = apple.Apple(None) - self.assertIsNone(fruit) + assert isinstance(fruit, schemas.Singleton) + assert isinstance(fruit, apple.Apple) + assert fruit.is_none_oapg() is True # 'banana' is not nullable. - with self.assertRaises(petstore_api.ApiTypeError): + # TODO cast this into ApiTypeError? + with self.assertRaises(TypeError): banana.Banana(None) # Since 'fruit' has oneOf 'apple', 'banana' and 'apple' is nullable, # validate we can create a fruit with the 'null' value. fruit = Fruit(None) - self.assertIsNone(fruit) - - # Redo the same thing, this time passing a null Apple to the Fruit constructor. - fruit = Fruit(apple.Apple(None)) - self.assertIsNone(fruit) - - def test_fruit_with_invalid_input_type(self): - - """ - color must be a str, color's str type is only defined at the Fruit level - Banana + Apple would allow color to be assigned with any type of value - """ - invalid_value = 1 - with self.assertRaises(petstore_api.ApiTypeError): - fruit = Fruit(color=invalid_value, length_cm=self.length_cm) + assert isinstance(fruit, schemas.Singleton) + assert isinstance(fruit, apple.Apple) + assert isinstance(fruit, Fruit) + assert fruit.is_none_oapg() is True if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_fruit_req.py b/samples/openapi3/client/petstore/python/tests_manual/test_fruit_req.py index 64b710fdd5..bdabb19364 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_fruit_req.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_fruit_req.py @@ -10,18 +10,17 @@ """ -import sys import unittest import petstore_api from petstore_api.model import apple_req from petstore_api.model import banana_req from petstore_api.model.fruit_req import FruitReq +from petstore_api import schemas class TestFruitReq(unittest.TestCase): """FruitReq unit test stubs""" - length_cm = 20.3 def setUp(self): pass @@ -29,106 +28,71 @@ class TestFruitReq(unittest.TestCase): def tearDown(self): pass - def test_fruit_access_errors(self): - fruit = FruitReq(length_cm=self.length_cm) - - # setting a value that doesn't exist raises an exception - # with a key - with self.assertRaises(AttributeError): - fruit['invalid_variable'] = 'some value' - # with setattr - with self.assertRaises(AttributeError): - setattr(fruit, 'invalid_variable', 'some value') - - # getting a value that doesn't exist raises an exception - # with a key - with self.assertRaises(AttributeError): - invalid_variable = fruit['cultivar'] - - with self.assertRaises(AttributeError): - getattr(fruit, 'cultivar') - - def test_FruitReq_banana(self): + def testFruitReq(self): """Test FruitReq""" # make an instance of Fruit, a composed schema oneOf model # banana test - fruit = FruitReq(length_cm=self.length_cm) + length_cm = 20.3 + fruit = FruitReq(lengthCm=length_cm) # check its properties - self.assertEqual(fruit.length_cm, self.length_cm) - self.assertEqual(fruit['length_cm'], self.length_cm) - self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) + self.assertEqual(fruit.lengthCm, length_cm) + self.assertEqual(fruit['lengthCm'], length_cm) + self.assertEqual(getattr(fruit, 'lengthCm'), length_cm) # check the dict representation self.assertEqual( - fruit.to_dict(), + fruit, { - 'length_cm': self.length_cm, + 'lengthCm': length_cm, } ) + # setting values after instance creation is not allowed + with self.assertRaises(TypeError): + fruit['lengthCm'] = 'some value' + + # setting values after instance creation is not allowed + with self.assertRaises(AttributeError): + setattr(fruit, 'lengthCm', 'some value') + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(KeyError): + fruit['cultivar'] + with self.assertRaises(AttributeError): + fruit.cultivar + assert fruit.get_item_oapg('cultivar') is schemas.unset # with getattr self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value') + with self.assertRaises(AttributeError): + getattr(fruit, 'cultivar') + # make sure that the ModelComposed class properties are correct - # model._composed_schemas stores the anyOf/allOf/oneOf info self.assertEqual( - fruit._composed_schemas, - { - 'anyOf': [], - 'allOf': [], - 'oneOf': [ - apple_req.AppleReq, - banana_req.BananaReq, - type(None), - ], - } - ) - # model._composed_instances is a list of the instances that were - # made from the anyOf/allOf/OneOf classes in model._composed_schemas - for composed_instance in fruit._composed_instances: - if composed_instance.__class__ == banana_req.BananaReq: - banana_instance = composed_instance - self.assertEqual( - fruit._composed_instances, - [banana_instance] - ) - # model._var_name_to_model_instances maps the variable name to the - # model instances which store that variable - self.assertEqual( - fruit._var_name_to_model_instances, - { - 'length_cm': [fruit, banana_instance], - } - ) - self.assertEqual( - fruit._additional_properties_model_instances, [fruit] + FruitReq.MetaOapg.one_of(), + [ + schemas.NoneSchema, + apple_req.AppleReq, + banana_req.BananaReq, + ], ) - # if we modify one of the properties owned by multiple - # model_instances we get an exception when we try to access that - # property because the retrieved values are not all the same - banana_instance.length_cm = 4.56 - with self.assertRaises(petstore_api.ApiValueError): - some_length_cm = fruit.length_cm - - def test_invalid_inputs(self): # including extra parameters raises an exception with self.assertRaises(petstore_api.ApiValueError): - fruit = FruitReq( - length_cm=self.length_cm, + FruitReq( + length_cm=length_cm, unknown_property='some value' ) # including input parameters for two oneOf instances raise an exception with self.assertRaises(petstore_api.ApiValueError): - fruit = FruitReq( - length_cm=self.length_cm, + FruitReq( + length_cm=length_cm, cultivar='granny smith' ) - def test_FruitReq_apple(self): - """Test FruitReq""" - + # make an instance of Fruit, a composed schema oneOf model # apple test cultivar = 'golden delicious' fruit = FruitReq(cultivar=cultivar) @@ -138,37 +102,18 @@ class TestFruitReq(unittest.TestCase): self.assertEqual(getattr(fruit, 'cultivar'), cultivar) # check the dict representation self.assertEqual( - fruit.to_dict(), + fruit, { 'cultivar': cultivar } ) - # model._composed_instances is a list of the instances that were - # made from the anyOf/allOf/OneOf classes in model._composed_schemas - for composed_instance in fruit._composed_instances: - if composed_instance.__class__ == apple_req.AppleReq: - apple_instance = composed_instance - self.assertEqual( - fruit._composed_instances, - [apple_instance] - ) - # model._var_name_to_model_instances maps the variable name to the - # model instances which store that variable - self.assertEqual( - fruit._var_name_to_model_instances, - { - 'cultivar': [fruit, apple_instance], - } - ) - self.assertEqual( - fruit._additional_properties_model_instances, [fruit] - ) - - def test_null_fruit(self): # we can pass in None fruit = FruitReq(None) - assert fruit is None + assert isinstance(fruit, schemas.Singleton) + assert isinstance(fruit, FruitReq) + assert isinstance(fruit, schemas.NoneSchema) + assert fruit.is_none_oapg() is True if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_gm_fruit.py b/samples/openapi3/client/petstore/python/tests_manual/test_gm_fruit.py index bbe105c59b..ad650460a4 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_gm_fruit.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_gm_fruit.py @@ -10,19 +10,17 @@ """ -import sys import unittest -import petstore_api +import frozendict + from petstore_api.model import apple from petstore_api.model import banana from petstore_api.model.gm_fruit import GmFruit - +from petstore_api import schemas class TestGmFruit(unittest.TestCase): """GmFruit unit test stubs""" - length_cm = 20.3 - color = 'yellow' def setUp(self): pass @@ -30,159 +28,88 @@ class TestGmFruit(unittest.TestCase): def tearDown(self): pass - def test_set_addprop_attributes(self): - # setting a value that doesn't exist works because additional_properties_type allows any type - other_fruit = GmFruit(length_cm=self.length_cm, color=self.color) - blah = 'blah' - other_fruit['a'] = blah - assert other_fruit.a == blah - - # with setattr - setattr(other_fruit, 'b', blah) - assert other_fruit.b == blah - - self.assertEqual( - other_fruit.to_dict(), - { - 'a': 'blah', - 'b': 'blah', - 'length_cm': self.length_cm, - 'color': self.color - } - ) - - def test_banana_fruit(self): + def testGmFruit(self): """Test GmFruit""" # make an instance of GmFruit, a composed schema anyOf model # banana test - fruit = GmFruit(length_cm=self.length_cm, color=self.color) + length_cm = 20.3 + color = 'yellow' + cultivar = 'banaple' + fruit = GmFruit(lengthCm=length_cm, color=color, cultivar=cultivar) + assert isinstance(fruit, banana.Banana) + assert isinstance(fruit, apple.Apple) + assert isinstance(fruit, frozendict.frozendict) + assert isinstance(fruit, GmFruit) # check its properties - self.assertEqual(fruit.length_cm, self.length_cm) - self.assertEqual(fruit['length_cm'], self.length_cm) - self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) - self.assertEqual(fruit.color, self.color) - self.assertEqual(fruit['color'], self.color) - self.assertEqual(getattr(fruit, 'color'), self.color) + self.assertEqual(fruit['lengthCm'], length_cm) + self.assertEqual(fruit['color'], color) + # check the dict representation self.assertEqual( - fruit.to_dict(), + fruit, { - 'length_cm': self.length_cm, - 'color': self.color + 'lengthCm': length_cm, + 'color': color, + 'cultivar': cultivar } ) - # getting a value that doesn't exist raises an exception - # with a key + # unset key access raises KeyError + with self.assertRaises(KeyError): + fruit["origin"] with self.assertRaises(AttributeError): - invalid_variable = fruit['cultivar'] - # with getattr - self.assertTrue(getattr(fruit, 'cultivar', 'some value'), 'some value') + fruit.origin + assert fruit.get_item_oapg("origin") is schemas.unset - with self.assertRaises(AttributeError): - invalid_variable = getattr(fruit, 'cultivar') + with self.assertRaises(KeyError): + fruit['unknown_variable'] + assert fruit.get_item_oapg("unknown_variable") is schemas.unset + # with getattr + self.assertTrue(getattr(fruit, 'origin', 'some value'), 'some value') # make sure that the ModelComposed class properties are correct - # model._composed_schemas stores the anyOf/allOf/oneOf info self.assertEqual( - fruit._composed_schemas, - { - 'anyOf': [ - apple.Apple, - banana.Banana, - ], - 'allOf': [], - 'oneOf': [], - } - ) - # model._composed_instances is a list of the instances that were - # made from the anyOf/allOf/OneOf classes in model._composed_schemas - for composed_instance in fruit._composed_instances: - if composed_instance.__class__ == banana.Banana: - banana_instance = composed_instance - self.assertEqual( - fruit._composed_instances, - [banana_instance] - ) - # model._var_name_to_model_instances maps the variable name to the - # model instances which store that variable - self.assertEqual( - fruit._var_name_to_model_instances, - { - 'color': [fruit], - 'length_cm': [fruit, banana_instance], - } - ) - self.assertEqual( - fruit._additional_properties_model_instances, [fruit] + GmFruit.MetaOapg.any_of(), + [ + apple.Apple, + banana.Banana, + ], + ) + + # including extra parameters works + GmFruit( + color=color, + length_cm=length_cm, + cultivar=cultivar, + unknown_property='some value' ) - def test_combo_fruit(self): # including input parameters for both anyOf instances works - cultivar = 'banaple' color = 'orange' fruit = GmFruit( color=color, cultivar=cultivar, - length_cm=self.length_cm + length_cm=length_cm ) - self.assertEqual(fruit.color, color) self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) - self.assertEqual(fruit.cultivar, cultivar) self.assertEqual(fruit['cultivar'], cultivar) - self.assertEqual(getattr(fruit, 'cultivar'), cultivar) - self.assertEqual(fruit.length_cm, self.length_cm) - self.assertEqual(fruit['length_cm'], self.length_cm) - self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) + self.assertEqual(fruit['length_cm'], length_cm) - # model._composed_instances is a list of the instances that were - # made from the anyOf/allOf/OneOf classes in model._composed_schemas - for composed_instance in fruit._composed_instances: - if composed_instance.__class__ == apple.Apple: - apple_instance = composed_instance - elif composed_instance.__class__ == banana.Banana: - banana_instance = composed_instance - self.assertEqual( - fruit._composed_instances, - [apple_instance, banana_instance] - ) - # model._var_name_to_model_instances maps the variable name to the - # model instances which store that variable - self.assertEqual( - fruit._var_name_to_model_instances, - { - 'color': [fruit], - 'length_cm': [fruit, banana_instance], - 'cultivar': [fruit, apple_instance], - } - ) - self.assertEqual( - fruit._additional_properties_model_instances, [fruit] - ) - - def test_apple_fruit(self): + # make an instance of GmFruit, a composed schema anyOf model # apple test color = 'red' cultivar = 'golden delicious' origin = 'California' fruit = GmFruit(color=color, cultivar=cultivar, origin=origin) # check its properties - self.assertEqual(fruit.color, color) self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) - self.assertEqual(fruit.cultivar, cultivar) self.assertEqual(fruit['cultivar'], cultivar) - self.assertEqual(getattr(fruit, 'cultivar'), cultivar) - - self.assertEqual(fruit.origin, origin) self.assertEqual(fruit['origin'], origin) - self.assertEqual(getattr(fruit, 'origin'), origin) # check the dict representation self.assertEqual( - fruit.to_dict(), + fruit, { 'color': color, 'cultivar': cultivar, @@ -190,28 +117,6 @@ class TestGmFruit(unittest.TestCase): } ) - # model._composed_instances is a list of the instances that were - # made from the anyOf/allOf/OneOf classes in model._composed_schemas - for composed_instance in fruit._composed_instances: - if composed_instance.__class__ == apple.Apple: - apple_instance = composed_instance - self.assertEqual( - fruit._composed_instances, - [apple_instance] - ) - # model._var_name_to_model_instances maps the variable name to the - # model instances which store that variable - self.assertEqual( - fruit._var_name_to_model_instances, - { - 'color': [fruit], - 'cultivar': [fruit, apple_instance], - 'origin': [fruit, apple_instance], - } - ) - self.assertEqual( - fruit._additional_properties_model_instances, [fruit] - ) if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_http_signature.py b/samples/openapi3/client/petstore/python/tests_manual/test_http_signature.py index c6854d666c..1db56c65dd 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_http_signature.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_http_signature.py @@ -1,518 +1,518 @@ -# coding: utf-8 - -# flake8: noqa - -""" -Run the tests. -$ docker pull swaggerapi/petstore -$ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore -$ pip install nose (optional) -$ cd petstore_api-python -$ nosetests -v -""" - -from collections import namedtuple -from datetime import datetime, timedelta -import base64 -import json -import os -import re -import shutil -import unittest -from urllib.parse import urlencode, urlparse - -from Crypto.Hash import SHA256, SHA512 -from Crypto.PublicKey import ECC, RSA -from Crypto.Signature import pkcs1_15, pss, DSS - -import petstore_api -from petstore_api.model import category, tag, pet -from petstore_api.api.pet_api import PetApi -from petstore_api import Configuration, signing -from petstore_api.rest import ( - RESTClientObject, - RESTResponse -) - -from petstore_api.exceptions import ( - ApiException, - ApiValueError, - ApiTypeError, -) - -from .util import id_gen - -import urllib3 - -from unittest.mock import patch - -HOST = 'http://localhost/v2' - -# This test RSA private key below is published in Appendix C 'Test Values' of -# https://www.ietf.org/id/draft-cavage-http-signatures-12.txt -RSA_TEST_PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY----- -MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF -NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F -UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB -AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA -QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK -kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg -f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u -412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc -mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 -kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA -gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW -G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI -7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== ------END RSA PRIVATE KEY-----""" - - -class TimeoutWithEqual(urllib3.Timeout): - def __init__(self, *arg, **kwargs): - super(TimeoutWithEqual, self).__init__(*arg, **kwargs) - - def __eq__(self, other): - return self._read == other._read and self._connect == other._connect and self.total == other.total - -class MockPoolManager(object): - def __init__(self, tc): - self._tc = tc - self._reqs = [] - - def expect_request(self, *args, **kwargs): - self._reqs.append((args, kwargs)) - - def set_signing_config(self, signing_cfg): - self.signing_cfg = signing_cfg - self._tc.assertIsNotNone(self.signing_cfg) - self.pubkey = self.signing_cfg.get_public_key() - self._tc.assertIsNotNone(self.pubkey) - - def request(self, *actual_request_target, **actual_request_headers_and_body): - self._tc.assertTrue(len(self._reqs) > 0) - expected_results = self._reqs.pop(0) - self._tc.maxDiff = None - expected_request_target = expected_results[0] # The expected HTTP method and URL path. - expected_request_headers_and_body = expected_results[1] # dict that contains the expected body, headers - self._tc.assertEqual(expected_request_target, actual_request_target) - # actual_request_headers_and_body is a dict that contains the actual body, headers - for k, expected in expected_request_headers_and_body.items(): - self._tc.assertIn(k, actual_request_headers_and_body) - if k == 'body': - actual_body = actual_request_headers_and_body[k] - self._tc.assertEqual(expected, actual_body) - elif k == 'headers': - actual_headers = actual_request_headers_and_body[k] - for expected_header_name, expected_header_value in expected.items(): - # Validate the generated request contains the expected header. - self._tc.assertIn(expected_header_name, actual_headers) - actual_header_value = actual_headers[expected_header_name] - # Compare the actual value of the header against the expected value. - pattern = re.compile(expected_header_value) - m = pattern.match(actual_header_value) - self._tc.assertTrue(m, msg="Expected:\n{0}\nActual:\n{1}".format( - expected_header_value,actual_header_value)) - if expected_header_name == 'Authorization': - self._validate_authorization_header( - expected_request_target, actual_headers, actual_header_value) - elif k == 'timeout': - self._tc.assertEqual(expected, actual_request_headers_and_body[k]) - return urllib3.HTTPResponse(status=200, body=b'test') - - def _validate_authorization_header(self, request_target, actual_headers, authorization_header): - """Validate the signature. - """ - # Extract (created) - r1 = re.compile(r'created=([0-9]+)') - m1 = r1.search(authorization_header) - self._tc.assertIsNotNone(m1) - created = m1.group(1) - - # Extract list of signed headers - r1 = re.compile(r'headers="([^"]+)"') - m1 = r1.search(authorization_header) - self._tc.assertIsNotNone(m1) - headers = m1.group(1).split(' ') - signed_headers_list = [] - for h in headers: - if h == '(created)': - signed_headers_list.append((h, created)) - elif h == '(request-target)': - url = request_target[1] - target_path = urlparse(url).path - signed_headers_list.append((h, "{0} {1}".format(request_target[0].lower(), target_path))) - else: - value = next((v for k, v in actual_headers.items() if k.lower() == h), None) - self._tc.assertIsNotNone(value) - signed_headers_list.append((h, value)) - header_items = [ - "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list] - string_to_sign = "\n".join(header_items) - digest = None - if self.signing_cfg.hash_algorithm == signing.HASH_SHA512: - digest = SHA512.new() - elif self.signing_cfg.hash_algorithm == signing.HASH_SHA256: - digest = SHA256.new() - else: - self._tc.fail("Unsupported hash algorithm: {0}".format(self.signing_cfg.hash_algorithm)) - digest.update(string_to_sign.encode()) - b64_body_digest = base64.b64encode(digest.digest()).decode() - - # Extract the signature - r2 = re.compile(r'signature="([^"]+)"') - m2 = r2.search(authorization_header) - self._tc.assertIsNotNone(m2) - b64_signature = m2.group(1) - signature = base64.b64decode(b64_signature) - # Build the message - signing_alg = self.signing_cfg.signing_algorithm - if signing_alg is None: - # Determine default - if isinstance(self.pubkey, RSA.RsaKey): - signing_alg = signing.ALGORITHM_RSASSA_PSS - elif isinstance(self.pubkey, ECC.EccKey): - signing_alg = signing.ALGORITHM_ECDSA_MODE_FIPS_186_3 - else: - self._tc.fail("Unsupported key: {0}".format(type(self.pubkey))) - - if signing_alg == signing.ALGORITHM_RSASSA_PKCS1v15: - pkcs1_15.new(self.pubkey).verify(digest, signature) - elif signing_alg == signing.ALGORITHM_RSASSA_PSS: - pss.new(self.pubkey).verify(digest, signature) - elif signing_alg == signing.ALGORITHM_ECDSA_MODE_FIPS_186_3: - verifier = DSS.new(key=self.pubkey, mode=signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, - encoding='der') - verifier.verify(digest, signature) - elif signing_alg == signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979: - verifier = DSS.new(key=self.pubkey, mode=signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979, - encoding='der') - verifier.verify(digest, signature) - else: - self._tc.fail("Unsupported signing algorithm: {0}".format(signing_alg)) - -class PetApiTests(unittest.TestCase): - - @classmethod - def setUpClass(cls): - cls.setUpModels() - cls.setUpFiles() - - @classmethod - def tearDownClass(cls): - file_paths = [ - cls.rsa_key_path, - cls.rsa4096_key_path, - cls.ec_p521_key_path, - ] - for file_path in file_paths: - os.unlink(file_path) - - @classmethod - def setUpModels(cls): - cls.category = category.Category() - cls.category.id = id_gen() - cls.category.name = "dog" - cls.tag = tag.Tag() - cls.tag.id = id_gen() - cls.tag.name = "python-pet-tag" - cls.pet = pet.Pet( - name="hello kity", - photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"] - ) - cls.pet.id = id_gen() - cls.pet.status = "sold" - cls.pet.category = cls.category - cls.pet.tags = [cls.tag] - - @classmethod - def setUpFiles(cls): - cls.test_file_dir = os.path.join( - os.path.dirname(__file__), "..", "testfiles") - cls.test_file_dir = os.path.realpath(cls.test_file_dir) - if not os.path.exists(cls.test_file_dir): - os.mkdir(cls.test_file_dir) - - cls.private_key_passphrase = 'test-passphrase' - cls.rsa_key_path = os.path.join(cls.test_file_dir, 'rsa.pem') - cls.rsa4096_key_path = os.path.join(cls.test_file_dir, 'rsa4096.pem') - cls.ec_p521_key_path = os.path.join(cls.test_file_dir, 'ecP521.pem') - - if not os.path.exists(cls.rsa_key_path): - with open(cls.rsa_key_path, 'w') as f: - f.write(RSA_TEST_PRIVATE_KEY) - - if not os.path.exists(cls.rsa4096_key_path): - key = RSA.generate(4096) - private_key = key.export_key( - passphrase=cls.private_key_passphrase, - protection='PEM' - ) - with open(cls.rsa4096_key_path, "wb") as f: - f.write(private_key) - - if not os.path.exists(cls.ec_p521_key_path): - key = ECC.generate(curve='P-521') - private_key = key.export_key( - format='PEM', - passphrase=cls.private_key_passphrase, - use_pkcs8=True, - protection='PBKDF2WithHMAC-SHA1AndAES128-CBC' - ) - with open(cls.ec_p521_key_path, "wt") as f: - f.write(private_key) - - def test_valid_http_signature(self): - privkey_path = self.rsa_key_path - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path=privkey_path, - private_key_passphrase=self.private_key_passphrase, - signing_algorithm=signing.ALGORITHM_RSASSA_PKCS1v15, - signed_headers=[ - signing.HEADER_REQUEST_TARGET, - signing.HEADER_CREATED, - signing.HEADER_HOST, - signing.HEADER_DATE, - signing.HEADER_DIGEST, - 'Content-Type' - ] - ) - config = Configuration(host=HOST, signing_info=signing_cfg) - # Set the OAuth2 acces_token to None. Here we are interested in testing - # the HTTP signature scheme. - config.access_token = None - - api_client = petstore_api.ApiClient(config) - pet_api = PetApi(api_client) - - mock_pool = MockPoolManager(self) - api_client.rest_client.pool_manager = mock_pool - - mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', HOST + '/pet', - body=json.dumps(api_client.sanitize_for_serialization(self.pet)), - headers={'Content-Type': r'application/json', - 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' - r'headers="\(request-target\) \(created\) host date digest content-type",' - r'signature="[a-zA-Z0-9+/=]+"', - 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, - preload_content=True, timeout=None) - - pet_api.add_pet(self.pet) - - def test_valid_http_signature_with_defaults(self): - privkey_path = self.rsa4096_key_path - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path=privkey_path, - private_key_passphrase=self.private_key_passphrase, - ) - config = Configuration(host=HOST, signing_info=signing_cfg) - # Set the OAuth2 acces_token to None. Here we are interested in testing - # the HTTP signature scheme. - config.access_token = None - - api_client = petstore_api.ApiClient(config) - pet_api = PetApi(api_client) - - mock_pool = MockPoolManager(self) - api_client.rest_client.pool_manager = mock_pool - - mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', HOST + '/pet', - body=json.dumps(api_client.sanitize_for_serialization(self.pet)), - headers={'Content-Type': r'application/json', - 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' - r'headers="\(created\)",' - r'signature="[a-zA-Z0-9+/=]+"', - 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, - preload_content=True, timeout=None) - - pet_api.add_pet(self.pet) - - def test_valid_http_signature_rsassa_pkcs1v15(self): - privkey_path = self.rsa4096_key_path - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path=privkey_path, - private_key_passphrase=self.private_key_passphrase, - signing_algorithm=signing.ALGORITHM_RSASSA_PKCS1v15, - signed_headers=[ - signing.HEADER_REQUEST_TARGET, - signing.HEADER_CREATED, - ] - ) - config = Configuration(host=HOST, signing_info=signing_cfg) - # Set the OAuth2 acces_token to None. Here we are interested in testing - # the HTTP signature scheme. - config.access_token = None - - api_client = petstore_api.ApiClient(config) - pet_api = PetApi(api_client) - - mock_pool = MockPoolManager(self) - api_client.rest_client.pool_manager = mock_pool - - mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', HOST + '/pet', - body=json.dumps(api_client.sanitize_for_serialization(self.pet)), - headers={'Content-Type': r'application/json', - 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' - r'headers="\(request-target\) \(created\)",' - r'signature="[a-zA-Z0-9+/=]+"', - 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, - preload_content=True, timeout=None) - - pet_api.add_pet(self.pet) - - def test_valid_http_signature_rsassa_pss(self): - privkey_path = self.rsa4096_key_path - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path=privkey_path, - private_key_passphrase=self.private_key_passphrase, - signing_algorithm=signing.ALGORITHM_RSASSA_PSS, - signed_headers=[ - signing.HEADER_REQUEST_TARGET, - signing.HEADER_CREATED, - ] - ) - config = Configuration(host=HOST, signing_info=signing_cfg) - # Set the OAuth2 acces_token to None. Here we are interested in testing - # the HTTP signature scheme. - config.access_token = None - - api_client = petstore_api.ApiClient(config) - pet_api = PetApi(api_client) - - mock_pool = MockPoolManager(self) - api_client.rest_client.pool_manager = mock_pool - - mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', HOST + '/pet', - body=json.dumps(api_client.sanitize_for_serialization(self.pet)), - headers={'Content-Type': r'application/json', - 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' - r'headers="\(request-target\) \(created\)",' - r'signature="[a-zA-Z0-9+/=]+"', - 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, - preload_content=True, timeout=None) - - pet_api.add_pet(self.pet) - - def test_valid_http_signature_ec_p521(self): - privkey_path = self.ec_p521_key_path - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path=privkey_path, - private_key_passphrase=self.private_key_passphrase, - hash_algorithm=signing.HASH_SHA512, - signed_headers=[ - signing.HEADER_REQUEST_TARGET, - signing.HEADER_CREATED, - ] - ) - config = Configuration(host=HOST, signing_info=signing_cfg) - # Set the OAuth2 acces_token to None. Here we are interested in testing - # the HTTP signature scheme. - config.access_token = None - - api_client = petstore_api.ApiClient(config) - pet_api = PetApi(api_client) - - mock_pool = MockPoolManager(self) - api_client.rest_client.pool_manager = mock_pool - - mock_pool.set_signing_config(signing_cfg) - mock_pool.expect_request('POST', HOST + '/pet', - body=json.dumps(api_client.sanitize_for_serialization(self.pet)), - headers={'Content-Type': r'application/json', - 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' - r'headers="\(request-target\) \(created\)",' - r'signature="[a-zA-Z0-9+/=]+"', - 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, - preload_content=True, timeout=None) - - pet_api.add_pet(self.pet) - - def test_invalid_configuration(self): - # Signing scheme must be valid. - with self.assertRaises(Exception) as cm: - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme='foo', - private_key_path=self.ec_p521_key_path - ) - self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)), - 'Exception message: {0}'.format(str(cm.exception))) - - # Signing scheme must be specified. - with self.assertRaises(Exception) as cm: - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - private_key_path=self.ec_p521_key_path, - signing_scheme=None - ) - self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)), - 'Exception message: {0}'.format(str(cm.exception))) - - # Private key passphrase is missing but key is encrypted. - with self.assertRaises(Exception) as cm: - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path=self.ec_p521_key_path, - ) - self.assertTrue(re.match('Not a valid clear PKCS#8 structure', str(cm.exception)), - 'Exception message: {0}'.format(str(cm.exception))) - - # File containing private key must exist. - with self.assertRaises(Exception) as cm: - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path='foobar', - ) - self.assertTrue(re.match('Private key file does not exist', str(cm.exception)), - 'Exception message: {0}'.format(str(cm.exception))) - - # The max validity must be a positive value. - with self.assertRaises(Exception) as cm: - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path=self.ec_p521_key_path, - signature_max_validity=timedelta(hours=-1) - ) - self.assertTrue(re.match('The signature max validity must be a positive value', - str(cm.exception)), - 'Exception message: {0}'.format(str(cm.exception))) - - # Cannot include the 'Authorization' header. - with self.assertRaises(Exception) as cm: - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path=self.ec_p521_key_path, - signed_headers=['Authorization'] - ) - self.assertTrue(re.match("'Authorization' header cannot be included", str(cm.exception)), - 'Exception message: {0}'.format(str(cm.exception))) - - # Cannot specify duplicate headers. - with self.assertRaises(Exception) as cm: - signing_cfg = signing.HttpSigningConfiguration( - key_id="my-key-id", - signing_scheme=signing.SCHEME_HS2019, - private_key_path=self.ec_p521_key_path, - signed_headers=['Host', 'Date', 'Host'] - ) - self.assertTrue(re.match('Cannot have duplicates in the signed_headers parameter', - str(cm.exception)), - 'Exception message: {0}'.format(str(cm.exception))) - +# # coding: utf-8 +# +# # flake8: noqa +# +# """ +# Run the tests. +# $ docker pull swaggerapi/petstore +# $ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore +# $ pip install nose (optional) +# $ cd petstore_api-python +# $ nosetests -v +# """ +# +# from collections import namedtuple +# from datetime import datetime, timedelta +# import base64 +# import json +# import os +# import re +# import shutil +# import unittest +# from urllib.parse import urlencode, urlparse +# +# from Crypto.Hash import SHA256, SHA512 +# from Crypto.PublicKey import ECC, RSA +# from Crypto.Signature import pkcs1_15, pss, DSS +# +# import petstore_api +# from petstore_api.model import category, tag, pet +# from petstore_api.apis.tags.pet_api import PetApi +# from petstore_api import Configuration, signing +# from petstore_api.rest import ( +# RESTClientObject, +# RESTResponse +# ) +# +# from petstore_api.exceptions import ( +# ApiException, +# ApiValueError, +# ApiTypeError, +# ) +# +# from .util import id_gen +# +# import urllib3 +# +# from unittest.mock import patch +# +# HOST = 'http://localhost/v2' +# +# # This test RSA private key below is published in Appendix C 'Test Values' of +# # https://www.ietf.org/id/draft-cavage-http-signatures-12.txt +# RSA_TEST_PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY----- +# MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF +# NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F +# UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB +# AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA +# QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK +# kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg +# f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u +# 412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc +# mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 +# kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA +# gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW +# G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI +# 7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== +# -----END RSA PRIVATE KEY-----""" +# +# +# class TimeoutWithEqual(urllib3.Timeout): +# def __init__(self, *arg, **kwargs): +# super(TimeoutWithEqual, self).__init__(*arg, **kwargs) +# +# def __eq__(self, other): +# return self._read == other._read and self._connect == other._connect and self.total == other.total +# +# class MockPoolManager(object): +# def __init__(self, tc): +# self._tc = tc +# self._reqs = [] +# +# def expect_request(self, *args, **kwargs): +# self._reqs.append((args, kwargs)) +# +# def set_signing_config(self, signing_cfg): +# self.signing_cfg = signing_cfg +# self._tc.assertIsNotNone(self.signing_cfg) +# self.pubkey = self.signing_cfg.get_public_key() +# self._tc.assertIsNotNone(self.pubkey) +# +# def request(self, *actual_request_target, **actual_request_headers_and_body): +# self._tc.assertTrue(len(self._reqs) > 0) +# expected_results = self._reqs.pop(0) +# self._tc.maxDiff = None +# expected_request_target = expected_results[0] # The expected HTTP method and URL path. +# expected_request_headers_and_body = expected_results[1] # dict that contains the expected body, headers +# self._tc.assertEqual(expected_request_target, actual_request_target) +# # actual_request_headers_and_body is a dict that contains the actual body, headers +# for k, expected in expected_request_headers_and_body.items(): +# self._tc.assertIn(k, actual_request_headers_and_body) +# if k == 'body': +# actual_body = actual_request_headers_and_body[k] +# self._tc.assertEqual(expected, actual_body) +# elif k == 'headers': +# actual_headers = actual_request_headers_and_body[k] +# for expected_header_name, expected_header_value in expected.items(): +# # Validate the generated request contains the expected header. +# self._tc.assertIn(expected_header_name, actual_headers) +# actual_header_value = actual_headers[expected_header_name] +# # Compare the actual value of the header against the expected value. +# pattern = re.compile(expected_header_value) +# m = pattern.match(actual_header_value) +# self._tc.assertTrue(m, msg="Expected:\n{0}\nActual:\n{1}".format( +# expected_header_value,actual_header_value)) +# if expected_header_name == 'Authorization': +# self._validate_authorization_header( +# expected_request_target, actual_headers, actual_header_value) +# elif k == 'timeout': +# self._tc.assertEqual(expected, actual_request_headers_and_body[k]) +# return urllib3.HTTPResponse(status=200, body=b'test') +# +# def _validate_authorization_header(self, request_target, actual_headers, authorization_header): +# """Validate the signature. +# """ +# # Extract (created) +# r1 = re.compile(r'created=([0-9]+)') +# m1 = r1.search(authorization_header) +# self._tc.assertIsNotNone(m1) +# created = m1.group(1) +# +# # Extract list of signed headers +# r1 = re.compile(r'headers="([^"]+)"') +# m1 = r1.search(authorization_header) +# self._tc.assertIsNotNone(m1) +# headers = m1.group(1).split(' ') +# signed_headers_list = [] +# for h in headers: +# if h == '(created)': +# signed_headers_list.append((h, created)) +# elif h == '(request-target)': +# url = request_target[1] +# target_path = urlparse(url).path +# signed_headers_list.append((h, "{0} {1}".format(request_target[0].lower(), target_path))) +# else: +# value = next((v for k, v in actual_headers.items() if k.lower() == h), None) +# self._tc.assertIsNotNone(value) +# signed_headers_list.append((h, value)) +# header_items = [ +# "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list] +# string_to_sign = "\n".join(header_items) +# digest = None +# if self.signing_cfg.hash_algorithm == signing.HASH_SHA512: +# digest = SHA512.new() +# elif self.signing_cfg.hash_algorithm == signing.HASH_SHA256: +# digest = SHA256.new() +# else: +# self._tc.fail("Unsupported hash algorithm: {0}".format(self.signing_cfg.hash_algorithm)) +# digest.update(string_to_sign.encode()) +# b64_body_digest = base64.b64encode(digest.digest()).decode() +# +# # Extract the signature +# r2 = re.compile(r'signature="([^"]+)"') +# m2 = r2.search(authorization_header) +# self._tc.assertIsNotNone(m2) +# b64_signature = m2.group(1) +# signature = base64.b64decode(b64_signature) +# # Build the message +# signing_alg = self.signing_cfg.signing_algorithm +# if signing_alg is None: +# # Determine default +# if isinstance(self.pubkey, RSA.RsaKey): +# signing_alg = signing.ALGORITHM_RSASSA_PSS +# elif isinstance(self.pubkey, ECC.EccKey): +# signing_alg = signing.ALGORITHM_ECDSA_MODE_FIPS_186_3 +# else: +# self._tc.fail("Unsupported key: {0}".format(type(self.pubkey))) +# +# if signing_alg == signing.ALGORITHM_RSASSA_PKCS1v15: +# pkcs1_15.new(self.pubkey).verify(digest, signature) +# elif signing_alg == signing.ALGORITHM_RSASSA_PSS: +# pss.new(self.pubkey).verify(digest, signature) +# elif signing_alg == signing.ALGORITHM_ECDSA_MODE_FIPS_186_3: +# verifier = DSS.new(key=self.pubkey, mode=signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, +# encoding='der') +# verifier.verify(digest, signature) +# elif signing_alg == signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979: +# verifier = DSS.new(key=self.pubkey, mode=signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979, +# encoding='der') +# verifier.verify(digest, signature) +# else: +# self._tc.fail("Unsupported signing algorithm: {0}".format(signing_alg)) +# +# class PetApiTests(unittest.TestCase): +# +# @classmethod +# def setUpClass(cls): +# cls.setUpModels() +# cls.setUpFiles() +# +# @classmethod +# def tearDownClass(cls): +# file_paths = [ +# cls.rsa_key_path, +# cls.rsa4096_key_path, +# cls.ec_p521_key_path, +# ] +# for file_path in file_paths: +# os.unlink(file_path) +# +# @classmethod +# def setUpModels(cls): +# cls.category = category.Category() +# cls.category.id = id_gen() +# cls.category.name = "dog" +# cls.tag = tag.Tag() +# cls.tag.id = id_gen() +# cls.tag.name = "python-pet-tag" +# cls.pet = pet.Pet( +# name="hello kity", +# photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"] +# ) +# cls.pet.id = id_gen() +# cls.pet.status = "sold" +# cls.pet.category = cls.category +# cls.pet.tags = [cls.tag] +# +# @classmethod +# def setUpFiles(cls): +# cls.test_file_dir = os.path.join( +# os.path.dirname(__file__), "..", "testfiles") +# cls.test_file_dir = os.path.realpath(cls.test_file_dir) +# if not os.path.exists(cls.test_file_dir): +# os.mkdir(cls.test_file_dir) +# +# cls.private_key_passphrase = 'test-passphrase' +# cls.rsa_key_path = os.path.join(cls.test_file_dir, 'rsa.pem') +# cls.rsa4096_key_path = os.path.join(cls.test_file_dir, 'rsa4096.pem') +# cls.ec_p521_key_path = os.path.join(cls.test_file_dir, 'ecP521.pem') +# +# if not os.path.exists(cls.rsa_key_path): +# with open(cls.rsa_key_path, 'w') as f: +# f.write(RSA_TEST_PRIVATE_KEY) +# +# if not os.path.exists(cls.rsa4096_key_path): +# key = RSA.generate(4096) +# private_key = key.export_key( +# passphrase=cls.private_key_passphrase, +# protection='PEM' +# ) +# with open(cls.rsa4096_key_path, "wb") as f: +# f.write(private_key) +# +# if not os.path.exists(cls.ec_p521_key_path): +# key = ECC.generate(curve='P-521') +# private_key = key.export_key( +# format='PEM', +# passphrase=cls.private_key_passphrase, +# use_pkcs8=True, +# protection='PBKDF2WithHMAC-SHA1AndAES128-CBC' +# ) +# with open(cls.ec_p521_key_path, "wt") as f: +# f.write(private_key) +# +# def test_valid_http_signature(self): +# privkey_path = self.rsa_key_path +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path=privkey_path, +# private_key_passphrase=self.private_key_passphrase, +# signing_algorithm=signing.ALGORITHM_RSASSA_PKCS1v15, +# signed_headers=[ +# signing.HEADER_REQUEST_TARGET, +# signing.HEADER_CREATED, +# signing.HEADER_HOST, +# signing.HEADER_DATE, +# signing.HEADER_DIGEST, +# 'Content-Type' +# ] +# ) +# config = Configuration(host=HOST, signing_info=signing_cfg) +# # Set the OAuth2 acces_token to None. Here we are interested in testing +# # the HTTP signature scheme. +# config.access_token = None +# +# api_client = petstore_api.ApiClient(config) +# pet_api = PetApi(api_client) +# +# mock_pool = MockPoolManager(self) +# api_client.rest_client.pool_manager = mock_pool +# +# mock_pool.set_signing_config(signing_cfg) +# mock_pool.expect_request('POST', HOST + '/pet', +# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), +# headers={'Content-Type': r'application/json', +# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' +# r'headers="\(request-target\) \(created\) host date digest content-type",' +# r'signature="[a-zA-Z0-9+/=]+"', +# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, +# preload_content=True, timeout=None) +# +# pet_api.add_pet(self.pet) +# +# def test_valid_http_signature_with_defaults(self): +# privkey_path = self.rsa4096_key_path +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path=privkey_path, +# private_key_passphrase=self.private_key_passphrase, +# ) +# config = Configuration(host=HOST, signing_info=signing_cfg) +# # Set the OAuth2 acces_token to None. Here we are interested in testing +# # the HTTP signature scheme. +# config.access_token = None +# +# api_client = petstore_api.ApiClient(config) +# pet_api = PetApi(api_client) +# +# mock_pool = MockPoolManager(self) +# api_client.rest_client.pool_manager = mock_pool +# +# mock_pool.set_signing_config(signing_cfg) +# mock_pool.expect_request('POST', HOST + '/pet', +# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), +# headers={'Content-Type': r'application/json', +# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' +# r'headers="\(created\)",' +# r'signature="[a-zA-Z0-9+/=]+"', +# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, +# preload_content=True, timeout=None) +# +# pet_api.add_pet(self.pet) +# +# def test_valid_http_signature_rsassa_pkcs1v15(self): +# privkey_path = self.rsa4096_key_path +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path=privkey_path, +# private_key_passphrase=self.private_key_passphrase, +# signing_algorithm=signing.ALGORITHM_RSASSA_PKCS1v15, +# signed_headers=[ +# signing.HEADER_REQUEST_TARGET, +# signing.HEADER_CREATED, +# ] +# ) +# config = Configuration(host=HOST, signing_info=signing_cfg) +# # Set the OAuth2 acces_token to None. Here we are interested in testing +# # the HTTP signature scheme. +# config.access_token = None +# +# api_client = petstore_api.ApiClient(config) +# pet_api = PetApi(api_client) +# +# mock_pool = MockPoolManager(self) +# api_client.rest_client.pool_manager = mock_pool +# +# mock_pool.set_signing_config(signing_cfg) +# mock_pool.expect_request('POST', HOST + '/pet', +# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), +# headers={'Content-Type': r'application/json', +# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' +# r'headers="\(request-target\) \(created\)",' +# r'signature="[a-zA-Z0-9+/=]+"', +# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, +# preload_content=True, timeout=None) +# +# pet_api.add_pet(self.pet) +# +# def test_valid_http_signature_rsassa_pss(self): +# privkey_path = self.rsa4096_key_path +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path=privkey_path, +# private_key_passphrase=self.private_key_passphrase, +# signing_algorithm=signing.ALGORITHM_RSASSA_PSS, +# signed_headers=[ +# signing.HEADER_REQUEST_TARGET, +# signing.HEADER_CREATED, +# ] +# ) +# config = Configuration(host=HOST, signing_info=signing_cfg) +# # Set the OAuth2 acces_token to None. Here we are interested in testing +# # the HTTP signature scheme. +# config.access_token = None +# +# api_client = petstore_api.ApiClient(config) +# pet_api = PetApi(api_client) +# +# mock_pool = MockPoolManager(self) +# api_client.rest_client.pool_manager = mock_pool +# +# mock_pool.set_signing_config(signing_cfg) +# mock_pool.expect_request('POST', HOST + '/pet', +# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), +# headers={'Content-Type': r'application/json', +# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' +# r'headers="\(request-target\) \(created\)",' +# r'signature="[a-zA-Z0-9+/=]+"', +# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, +# preload_content=True, timeout=None) +# +# pet_api.add_pet(self.pet) +# +# def test_valid_http_signature_ec_p521(self): +# privkey_path = self.ec_p521_key_path +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path=privkey_path, +# private_key_passphrase=self.private_key_passphrase, +# hash_algorithm=signing.HASH_SHA512, +# signed_headers=[ +# signing.HEADER_REQUEST_TARGET, +# signing.HEADER_CREATED, +# ] +# ) +# config = Configuration(host=HOST, signing_info=signing_cfg) +# # Set the OAuth2 acces_token to None. Here we are interested in testing +# # the HTTP signature scheme. +# config.access_token = None +# +# api_client = petstore_api.ApiClient(config) +# pet_api = PetApi(api_client) +# +# mock_pool = MockPoolManager(self) +# api_client.rest_client.pool_manager = mock_pool +# +# mock_pool.set_signing_config(signing_cfg) +# mock_pool.expect_request('POST', HOST + '/pet', +# body=json.dumps(api_client.sanitize_for_serialization(self.pet)), +# headers={'Content-Type': r'application/json', +# 'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,' +# r'headers="\(request-target\) \(created\)",' +# r'signature="[a-zA-Z0-9+/=]+"', +# 'User-Agent': r'OpenAPI-Generator/1.0.0/python'}, +# preload_content=True, timeout=None) +# +# pet_api.add_pet(self.pet) +# +# def test_invalid_configuration(self): +# # Signing scheme must be valid. +# with self.assertRaises(Exception) as cm: +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme='foo', +# private_key_path=self.ec_p521_key_path +# ) +# self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)), +# 'Exception message: {0}'.format(str(cm.exception))) +# +# # Signing scheme must be specified. +# with self.assertRaises(Exception) as cm: +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# private_key_path=self.ec_p521_key_path, +# signing_scheme=None +# ) +# self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)), +# 'Exception message: {0}'.format(str(cm.exception))) +# +# # Private key passphrase is missing but key is encrypted. +# with self.assertRaises(Exception) as cm: +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path=self.ec_p521_key_path, +# ) +# self.assertTrue(re.match('Not a valid clear PKCS#8 structure', str(cm.exception)), +# 'Exception message: {0}'.format(str(cm.exception))) +# +# # File containing private key must exist. +# with self.assertRaises(Exception) as cm: +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path='foobar', +# ) +# self.assertTrue(re.match('Private key file does not exist', str(cm.exception)), +# 'Exception message: {0}'.format(str(cm.exception))) +# +# # The max validity must be a positive value. +# with self.assertRaises(Exception) as cm: +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path=self.ec_p521_key_path, +# signature_max_validity=timedelta(hours=-1) +# ) +# self.assertTrue(re.match('The signature max validity must be a positive value', +# str(cm.exception)), +# 'Exception message: {0}'.format(str(cm.exception))) +# +# # Cannot include the 'Authorization' header. +# with self.assertRaises(Exception) as cm: +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path=self.ec_p521_key_path, +# signed_headers=['Authorization'] +# ) +# self.assertTrue(re.match("'Authorization' header cannot be included", str(cm.exception)), +# 'Exception message: {0}'.format(str(cm.exception))) +# +# # Cannot specify duplicate headers. +# with self.assertRaises(Exception) as cm: +# signing_cfg = signing.HttpSigningConfiguration( +# key_id="my-key-id", +# signing_scheme=signing.SCHEME_HS2019, +# private_key_path=self.ec_p521_key_path, +# signed_headers=['Host', 'Date', 'Host'] +# ) +# self.assertTrue(re.match('Cannot have duplicates in the signed_headers parameter', +# str(cm.exception)), +# 'Exception message: {0}'.format(str(cm.exception))) +# diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_integer_enum_one_value.py b/samples/openapi3/client/petstore/python/tests_manual/test_integer_enum_one_value.py index eff7298d9f..a5d92cd083 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_integer_enum_one_value.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_integer_enum_one_value.py @@ -28,15 +28,28 @@ class TestIntegerEnumOneValue(unittest.TestCase): def testIntegerEnumOneValue(self): """Test IntegerEnumOneValue""" - model = IntegerEnumOneValue() - assert model.value == 0, "With only one option, the value is assigned automatically" + + with self.assertRaises(TypeError): + """ + a value must be passed in + We cannot auto assign values because that would break composition if + received payloads included this with no inputs and we the 0 value to the data to the incoming payload + One is not allowed to mutate incoming payloads because then: + - order of composed schema ingestion matters + - one can have default value collisions + - the added data will make expected schemas not match payloads + """ + model = IntegerEnumOneValue() model = IntegerEnumOneValue(0) - assert model.value == 0, "We can also pass in the value as a positional arg" + assert model == 0, "We can also pass in the value as a positional arg" - model = IntegerEnumOneValue(value=0) - assert model.value == 0, "We can also pass in the value as a named argument" + # one cannot pass the value with the value keyword + with self.assertRaises(TypeError): + model = IntegerEnumOneValue(value=0) + # one can pass in the enum value + model = IntegerEnumOneValue(IntegerEnumOneValue.POSITIVE_0) if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_json_encoder.py b/samples/openapi3/client/petstore/python/tests_manual/test_json_encoder.py similarity index 92% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_json_encoder.py rename to samples/openapi3/client/petstore/python/tests_manual/test_json_encoder.py index 45cce4c0f0..d6cbdfa375 100644 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_json_encoder.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_json_encoder.py @@ -28,7 +28,7 @@ class TestJSONEncoder(unittest.TestCase): schemas.DateTimeSchema: '2020-01-01T00:00:00' } for schema, value in schema_to_value.items(): - inst = schema._from_openapi_data(value) + inst = schema.from_openapi_data_oapg(value) assert value == self.serializer.default(inst) def test_receive_encode_numeric_types(self): @@ -41,7 +41,7 @@ class TestJSONEncoder(unittest.TestCase): 7.14: schemas.NumberSchema, } for value, schema in value_to_schema.items(): - inst = schema._from_openapi_data(value) + inst = schema.from_openapi_data_oapg(value) pre_serialize_value = self.serializer.default(inst) assert value == pre_serialize_value and type(value) == type(pre_serialize_value) diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_mammal.py b/samples/openapi3/client/petstore/python/tests_manual/test_mammal.py index 3ed00dd798..975b02e015 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_mammal.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_mammal.py @@ -14,16 +14,6 @@ import sys import unittest import petstore_api -try: - from petstore_api.model import whale -except ImportError: - whale = sys.modules[ - 'petstore_api.model.whale'] -try: - from petstore_api.model import zebra -except ImportError: - zebra = sys.modules[ - 'petstore_api.model.zebra'] from petstore_api.model.mammal import Mammal @@ -39,10 +29,26 @@ class TestMammal(unittest.TestCase): def testMammal(self): """Test Mammal""" - # tests that we can make a BasquePig by traveling through descendant discriminator in Pig - model = Mammal(class_name="BasquePig") + # tests that we can make a BasquePig by traveling through discriminator in Pig + m = Mammal(className="BasquePig") + from petstore_api.model import pig from petstore_api.model import basque_pig - assert isinstance(model, basque_pig.BasquePig) + assert isinstance(m, Mammal) + assert isinstance(m, basque_pig.BasquePig) + assert isinstance(m, pig.Pig) + + # can make a Whale + m = Mammal(className="whale") + from petstore_api.model import whale + assert isinstance(m, whale.Whale) + + # can use the enum value + m = Mammal(className=whale.Whale.MetaOapg.properties.className.WHALE) + assert isinstance(m, whale.Whale) + + from petstore_api.model import zebra + m = Mammal(className='zebra') + assert isinstance(m, zebra.Zebra) if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_money.py b/samples/openapi3/client/petstore/python/tests_manual/test_money.py new file mode 100644 index 0000000000..060132ef40 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_money.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" +import decimal +import unittest + +from petstore_api.model.money import Money + + +class TestMoney(unittest.TestCase): + """Money unit test stubs""" + + def test_Money(self): + """Test Money""" + price = Money( + currency='usd', + amount='10.99' + ) + self.assertEqual(price.amount.as_decimal_oapg, decimal.Decimal('10.99')) + self.assertEqual( + price, + dict(currency='usd', amount='10.99') + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_no_additional_properties.py b/samples/openapi3/client/petstore/python/tests_manual/test_no_additional_properties.py new file mode 100644 index 0000000000..723f32201b --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_no_additional_properties.py @@ -0,0 +1,73 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import decimal +import unittest + +from petstore_api.model.no_additional_properties import NoAdditionalProperties +from petstore_api import schemas + +class TestNoAdditionalProperties(unittest.TestCase): + """NoAdditionalProperties unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testNoAdditionalProperties(self): + """Test NoAdditionalProperties""" + + # works with only required + inst = NoAdditionalProperties(id=1) + id_by_items = inst["id"] + assert id_by_items == 1 + assert isinstance(id_by_items, (schemas.Int64Schema, decimal.Decimal)) + id_by_property = inst.id + assert id_by_property == 1 + assert isinstance(id_by_property, (schemas.Int64Schema, decimal.Decimal)) + with self.assertRaises(AttributeError): + inst.petId + with self.assertRaises(KeyError): + inst["petId"] + assert inst.get_item_oapg("petId") is schemas.unset + + # works with required + optional + inst = NoAdditionalProperties(id=1, petId=2) + + # needs required + # TODO cast this to ApiTypeError? + with self.assertRaisesRegex( + TypeError, + r"missing 1 required keyword-only argument: 'id'" + ): + NoAdditionalProperties(petId=2) + + # may not be passed additional properties + # TODO cast this to ApiTypeError? + with self.assertRaisesRegex( + TypeError, + r"got an unexpected keyword argument 'invalidArg'" + ): + NoAdditionalProperties(id=2, invalidArg=2) + + # plural example + # TODO cast this to ApiTypeError? + with self.assertRaisesRegex( + TypeError, + r"got an unexpected keyword argument 'firstInvalidArg'" + ): + NoAdditionalProperties(id=2, firstInvalidArg=1, secondInvalidArg=1) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_nullable_string.py b/samples/openapi3/client/petstore/python/tests_manual/test_nullable_string.py new file mode 100644 index 0000000000..2b2616fce9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_nullable_string.py @@ -0,0 +1,55 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import unittest + +import petstore_api +from petstore_api.model.nullable_string import NullableString +from petstore_api.schemas import Schema, Singleton + + +class TestNullableString(unittest.TestCase): + """NullableString unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testNullableString(self): + """Test NullableString""" + inst = NullableString(None) + assert isinstance(inst, Singleton) + assert isinstance(inst, NullableString) + assert isinstance(inst, Schema) + assert inst.is_none_oapg() is True + assert repr(inst) == '' + + inst = NullableString('approved') + assert inst.is_none_oapg() is False + assert isinstance(inst, NullableString) + assert isinstance(inst, Schema) + assert isinstance(inst, str) + assert inst == 'approved' + + invalid_values = [1] + for invalid_value in invalid_values: + with self.assertRaisesRegex( + petstore_api.ApiTypeError, + r"Invalid type. Required value type is one of \[NoneClass, str\] and passed type was Decimal at \['args\[0\]'\]" + ): + NullableString(invalid_value) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_number_with_validations.py b/samples/openapi3/client/petstore/python/tests_manual/test_number_with_validations.py index f4264ca82e..5cf1dfaa9c 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_number_with_validations.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_number_with_validations.py @@ -31,11 +31,14 @@ class TestNumberWithValidations(unittest.TestCase): valid_values = [10.0, 15.0, 20.0] for valid_value in valid_values: model = NumberWithValidations(valid_value) - assert model.value == valid_value + assert model == valid_value - invalid_values = [9.0, 21.0] - for invalid_value in invalid_values: - with self.assertRaises(petstore_api.ApiValueError): + value_error_msg_pairs = ( + (9.0, r"Invalid value `9.0`, must be a value greater than or equal to `10` at \('args\[0\]',\)"), + (21.0, r"Invalid value `21.0`, must be a value less than or equal to `20` at \('args\[0\]',\)"), + ) + for invalid_value, error_msg in value_error_msg_pairs: + with self.assertRaisesRegex(petstore_api.ApiValueError, error_msg): NumberWithValidations(invalid_value) diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_object_model_with_ref_props.py b/samples/openapi3/client/petstore/python/tests_manual/test_object_model_with_ref_props.py index c708237acb..42fc674cd2 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_object_model_with_ref_props.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_object_model_with_ref_props.py @@ -9,18 +9,13 @@ Generated by: https://openapi-generator.tech """ - -import sys import unittest -import petstore_api -try: - from petstore_api.model import number_with_validations -except ImportError: - number_with_validations = sys.modules[ - 'petstore_api.model.number_with_validations'] +import frozendict + +from petstore_api.schemas import BoolClass from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps -from petstore_api.model.readonly import Readonly +from petstore_api.model.number_with_validations import NumberWithValidations class TestObjectModelWithRefProps(unittest.TestCase): @@ -34,16 +29,17 @@ class TestObjectModelWithRefProps(unittest.TestCase): def testObjectModelWithRefProps(self): """Test ObjectModelWithRefProps""" - from petstore_api.model.number_with_validations import NumberWithValidations - self.assertEqual( - ObjectModelWithRefProps.openapi_types, - { - 'my_number': (NumberWithValidations,), - 'my_readonly': (Readonly,), - 'my_string': (str,), - 'my_boolean': (bool,), - } - ) + inst = ObjectModelWithRefProps(myNumber=15.0, myString="a", myBoolean=True) + assert isinstance(inst, ObjectModelWithRefProps) + assert isinstance(inst, frozendict.frozendict) + assert set(inst.keys()) == {"myNumber", "myString", "myBoolean"} + assert inst["myNumber"] == 15.0 + assert isinstance(inst["myNumber"], NumberWithValidations) + assert inst["myString"] == 'a' + assert isinstance(inst["myString"], ObjectModelWithRefProps.MetaOapg.properties.myString) + assert bool(inst["myBoolean"]) is True + assert isinstance(inst["myBoolean"], ObjectModelWithRefProps.MetaOapg.properties.myBoolean) + assert isinstance(inst["myBoolean"], BoolClass) if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_difficultly_named_props.py b/samples/openapi3/client/petstore/python/tests_manual/test_object_with_difficultly_named_props.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_difficultly_named_props.py rename to samples/openapi3/client/petstore/python/tests_manual/test_object_with_difficultly_named_props.py diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_object_with_inline_composition_property.py b/samples/openapi3/client/petstore/python/tests_manual/test_object_with_inline_composition_property.py new file mode 100644 index 0000000000..8105e51eab --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_object_with_inline_composition_property.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +from petstore_api import schemas, exceptions +from petstore_api.model.object_with_inline_composition_property import ObjectWithInlineCompositionProperty + + +class TestObjectWithInlineCompositionProperty(unittest.TestCase): + """ObjectWithInlineCompositionProperty unit test stubs""" + + def test_ObjectWithInlineCompositionProperty(self): + """Test ObjectWithInlineCompositionProperty""" + model = ObjectWithInlineCompositionProperty(someProp='a') + self.assertTrue( + isinstance( + model["someProp"], + ObjectWithInlineCompositionProperty.MetaOapg.properties.someProp + ) + ) + self.assertTrue(isinstance(model["someProp"], schemas.StrSchema)) + + # error thrown on length < 1 + with self.assertRaises(exceptions.ApiValueError): + ObjectWithInlineCompositionProperty(someProp='') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_object_with_invalid_named_refed_properties.py b/samples/openapi3/client/petstore/python/tests_manual/test_object_with_invalid_named_refed_properties.py new file mode 100644 index 0000000000..fb8cf4a988 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_object_with_invalid_named_refed_properties.py @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +import petstore_api +from petstore_api.model.object_with_invalid_named_refed_properties import ObjectWithInvalidNamedRefedProperties +from petstore_api.model.array_with_validations_in_items import ArrayWithValidationsInItems +from petstore_api.model.from_schema import FromSchema + + +class TestObjectWithInvalidNamedRefedProperties(unittest.TestCase): + """ObjectWithInvalidNamedRefedProperties unit test stubs""" + + def test_instantiation_success(self): + array_value = ArrayWithValidationsInItems( + [4, 5] + ) + from_value = FromSchema(data='abc', id=1) + kwargs = { + 'from': from_value, + '!reference': array_value + } + # __new__ creation works + inst = ObjectWithInvalidNamedRefedProperties( + **kwargs + ) + primitive_data = { + 'from': {'data': 'abc', 'id': 1}, + '!reference': (4, 5) + } + assert inst == primitive_data + # from_openapi_data_oapg works + inst = ObjectWithInvalidNamedRefedProperties.from_openapi_data_oapg(primitive_data) + assert inst == primitive_data + + def test_omitting_required_properties_fails(self): + array_value = ArrayWithValidationsInItems( + [4, 5] + ) + from_value = FromSchema(data='abc', id=1) + with self.assertRaises(petstore_api.exceptions.ApiTypeError): + ObjectWithInvalidNamedRefedProperties( + **{ + 'from': from_value, + } + ) + with self.assertRaises(petstore_api.exceptions.ApiTypeError): + ObjectWithInvalidNamedRefedProperties( + **{ + '!reference': array_value + } + ) + with self.assertRaises(petstore_api.exceptions.ApiTypeError): + ObjectWithInvalidNamedRefedProperties.from_openapi_data_oapg( + { + 'from': {'data': 'abc', 'id': 1}, + } + ) + with self.assertRaises(petstore_api.exceptions.ApiTypeError): + ObjectWithInvalidNamedRefedProperties.from_openapi_data_oapg( + { + '!reference': [4, 5] + } + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_validations.py b/samples/openapi3/client/petstore/python/tests_manual/test_object_with_validations.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_validations.py rename to samples/openapi3/client/petstore/python/tests_manual/test_object_with_validations.py diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_parameters.py b/samples/openapi3/client/petstore/python/tests_manual/test_parameters.py similarity index 94% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_parameters.py rename to samples/openapi3/client/petstore/python/tests_manual/test_parameters.py index 86cb821787..75ece111b8 100644 --- a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_parameters.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_parameters.py @@ -13,7 +13,7 @@ import collections from petstore_api import api_client, exceptions, schemas -ParamTestCase = collections.namedtuple('ParamTestCase', 'payload expected_serialization explode', defaults=[False]) +from . import ParamTestCase class TestParameter(unittest.TestCase): @@ -843,8 +843,6 @@ class TestParameter(unittest.TestCase): name=name, schema=schemas.AnyTypeSchema, ) - print(parameter.explode) - print(test_case.payload) serialization = parameter.serialize(test_case.payload) self.assertEqual(serialization, test_case.expected_serialization) @@ -905,7 +903,6 @@ class TestParameter(unittest.TestCase): name=name, schema=schemas.AnyTypeSchema, ) - print(test_case.payload) serialization = parameter.serialize(test_case.payload) self.assertEqual(serialization, test_case.expected_serialization) @@ -933,7 +930,7 @@ class TestParameter(unittest.TestCase): content={'application/json': schemas.AnyTypeSchema} ) - def test_content_json_serialization(self): + def test_header_content_json_serialization(self): name = 'color' test_cases = ( ParamTestCase( @@ -993,6 +990,66 @@ class TestParameter(unittest.TestCase): serialization = parameter.serialize(test_case.payload) self.assertEqual(serialization, test_case.expected_serialization) + def test_query_content_json_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + {'color': '?color=null'} + ), + ParamTestCase( + 1, + {'color': '?color=1'} + ), + ParamTestCase( + 3.14, + {'color': '?color=3.14'} + ), + ParamTestCase( + 'blue', + {'color': '?color=%22blue%22'} + ), + ParamTestCase( + 'hello world', + {'color': '?color=%22hello%20world%22'} + ), + ParamTestCase( + '', + {'color': '?color=%22%22'} + ), + ParamTestCase( + True, + {'color': '?color=true'} + ), + ParamTestCase( + False, + {'color': '?color=false'} + ), + ParamTestCase( + [], + {'color': '?color=%5B%5D'} + ), + ParamTestCase( + ['blue', 'black', 'brown'], + {'color': '?color=%5B%22blue%22%2C%22black%22%2C%22brown%22%5D'} + ), + ParamTestCase( + {}, + {'color': '?color=%7B%7D'} + ), + ParamTestCase( + dict(R=100, G=200, B=150), + {'color': '?color=%7B%22R%22%3A100%2C%22G%22%3A200%2C%22B%22%3A150%7D'} + ), + ) + for test_case in test_cases: + parameter = api_client.QueryParameter( + name=name, + content={'application/json': schemas.AnyTypeSchema} + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + def test_throws_error_for_unimplemented_serialization(self): with self.assertRaises(NotImplementedError): parameter = api_client.HeaderParameter( diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_parent_pet.py b/samples/openapi3/client/petstore/python/tests_manual/test_parent_pet.py index a57f9b8527..171310075a 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_parent_pet.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_parent_pet.py @@ -14,16 +14,7 @@ import sys import unittest import petstore_api -try: - from petstore_api.model import child_cat -except ImportError: - child_cat = sys.modules[ - 'petstore_api.model.child_cat'] -try: - from petstore_api.model import grandparent_animal -except ImportError: - grandparent_animal = sys.modules[ - 'petstore_api.model.grandparent_animal'] +from petstore_api.model.grandparent_animal import GrandparentAnimal from petstore_api.model.parent_pet import ParentPet @@ -44,6 +35,7 @@ class TestParentPet(unittest.TestCase): # GrandparentAnimal, and we use the descendant's discriminator to make ParentPet model = ParentPet(pet_type="ParentPet") assert isinstance(model, ParentPet) + assert isinstance(model, GrandparentAnimal) if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_paths/__init__.py b/samples/openapi3/client/petstore/python/tests_manual/test_paths/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake/__init__.py b/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake/test_get.py b/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake/test_get.py new file mode 100644 index 0000000000..042fe206c4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake/test_get.py @@ -0,0 +1,73 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from ... import ApiTestMixin + + +class TestFake(ApiTestMixin, unittest.TestCase): + """ + Fake unit test stubs + To test enum parameters # noqa: E501 + """ + used_api_client = api_client.ApiClient( + header_name='enum_header_string', + header_value='_abc' + ) + api = get.ApiForget(api_client=used_api_client) + + @patch.object(urllib3.PoolManager, 'request') + def test_passed_in_header_overrides_default(self, mock_request): + mock_request.return_value = self.response(b'') + + api_response = self.api.get(header_params={'enum_header_string': '-efg'}) + self.assert_pool_manager_request_called_with( + mock_request, + f'http://petstore.swagger.io:80/v2/fake', + body=None, + method='GET', + content_type=None, + accept_content_type=None, + headers={'enum_header_string': '-efg'} + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + assert isinstance(api_response.headers, schemas.Unset) + assert api_response.response.status == 200 + + @patch.object(urllib3.PoolManager, 'request') + def test_default_header_used_when_no_header_params_input(self, mock_request): + mock_request.return_value = self.response(b'') + + api_response = self.api.get() + self.assert_pool_manager_request_called_with( + mock_request, + f'http://petstore.swagger.io:80/v2/fake', + body=None, + method='GET', + content_type=None, + accept_content_type=None, + headers={'enum_header_string': '_abc'} + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.Unset) + assert isinstance(api_response.headers, schemas.Unset) + assert api_response.response.status == 200 + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake_query_param_with_json_content_type/__init__.py b/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake_query_param_with_json_content_type/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake_query_param_with_json_content_type/test_get.py b/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake_query_param_with_json_content_type/test_get.py new file mode 100644 index 0000000000..025a4eb2a8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_fake_query_param_with_json_content_type/test_get.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import collections +import unittest +from unittest.mock import patch + +import urllib3 + +import petstore_api +from petstore_api.paths.fake_query_param_with_json_content_type import get # noqa: E501 +from petstore_api import configuration, schemas, api_client + +from ... import ApiTestMixin, ParamTestCase + + +class TestFakeQueryParamWithJsonContentType(ApiTestMixin, unittest.TestCase): + """ + FakeQueryParamWithJsonContentType unit test stubs + query param with json content-type # noqa: E501 + """ + @patch.object(urllib3.PoolManager, 'request') + def test_get(self, mock_request): + used_api_client = api_client.ApiClient() + api = get.ApiForget(api_client=used_api_client) + + response_json = {} + body = self.json_bytes(response_json) + mock_request.return_value = self.response(body) + + test_cases = ( + ParamTestCase( + None, + 'null' + ), + ParamTestCase( + 1, + '1' + ), + ParamTestCase( + 3.14, + '3.14' + ), + ParamTestCase( + 'blue', + '%22blue%22' + ), + ParamTestCase( + 'hello world', + '%22hello%20world%22' + ), + ParamTestCase( + '', + '%22%22' + ), + ParamTestCase( + True, + 'true' + ), + ParamTestCase( + False, + 'false' + ), + ParamTestCase( + [], + '%5B%5D' + ), + ParamTestCase( + ['blue', 'black', 'brown'], + '%5B%22blue%22%2C%22black%22%2C%22brown%22%5D' + ), + ParamTestCase( + {}, + '%7B%7D' + ), + ParamTestCase( + dict(R=100, G=200, B=150), + '%7B%22R%22%3A100%2C%22G%22%3A200%2C%22B%22%3A150%7D' + ), + ) + + for test_case in test_cases: + api_response = api.get(query_params={'someParam': test_case.payload}) + self.assert_pool_manager_request_called_with( + mock_request, + f'http://petstore.swagger.io:80/v2/fake/queryParamWithJsonContentType?someParam={test_case.expected_serialization}', + body=None, + method='GET', + content_type=None, + accept_content_type='application/json', + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, schemas.AnyTypeSchema) + assert isinstance(api_response.body, schemas.frozendict.frozendict) + assert isinstance(api_response.headers, schemas.Unset) + assert api_response.response.status == 200 + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_pet_pet_id/__init__.py b/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_pet_pet_id/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_pet_pet_id/test_get.py b/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_pet_pet_id/test_get.py new file mode 100644 index 0000000000..81cb92cd13 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_paths/test_pet_pet_id/test_get.py @@ -0,0 +1,65 @@ +# coding: utf-8 + +""" + + + Generated by: https://openapi-generator.tech +""" + +import json +import unittest +from unittest.mock import patch + +import urllib3 + +from petstore_api.paths.pet_pet_id import get # noqa: E501 +from petstore_api import configuration, schemas, api_client +from petstore_api.model.pet import Pet + +from ... import ApiTestMixin + + +class TestPetPetId(ApiTestMixin, unittest.TestCase): + """ + PetPetId unit test stubs + Find pet by ID # noqa: E501 + """ + def test_get(self): + config_with_auth = configuration.Configuration(api_key={'api_key': 'someKey'}) + used_api_client = api_client.ApiClient(configuration=config_with_auth) + api = get.ApiForget(api_client=used_api_client) + + with patch.object(urllib3.PoolManager, 'request') as mock_request: + response_json = { + 'photoUrls': [], + 'name': 'Kitty', + 'id': 1, + 'category': { + 'name': 'Cat', + 'id': 1 + }, + 'tags': [], + 'status': 'available' + } + body = self.json_bytes(response_json) + mock_request.return_value = self.response(body) + + api_response = api.get(path_params={'petId': 1}) + self.assert_pool_manager_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/pet/1', + body=None, + method='GET', + content_type=None, + accept_content_type='application/xml, application/json', + headers={'api_key': 'someKey'} + ) + + assert isinstance(api_response.response, urllib3.HTTPResponse) + assert isinstance(api_response.body, Pet) + assert isinstance(api_response.headers, schemas.Unset) + assert api_response.response.status == 200 + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_quadrilateral.py b/samples/openapi3/client/petstore/python/tests_manual/test_quadrilateral.py index 63f74ae541..dff97bc716 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_quadrilateral.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_quadrilateral.py @@ -14,16 +14,8 @@ import sys import unittest import petstore_api -try: - from petstore_api.model import complex_quadrilateral -except ImportError: - complex_quadrilateral = sys.modules[ - 'petstore_api.model.complex_quadrilateral'] -try: - from petstore_api.model import simple_quadrilateral -except ImportError: - simple_quadrilateral = sys.modules[ - 'petstore_api.model.simple_quadrilateral'] +from petstore_api.model import complex_quadrilateral +from petstore_api.model import simple_quadrilateral from petstore_api.model.quadrilateral import Quadrilateral @@ -38,9 +30,9 @@ class TestQuadrilateral(unittest.TestCase): def testQuadrilateral(self): """Test Quadrilateral""" - instance = Quadrilateral(shape_type="Quadrilateral", quadrilateral_type="ComplexQuadrilateral") + instance = Quadrilateral(shapeType="Quadrilateral", quadrilateralType="ComplexQuadrilateral") assert isinstance(instance, complex_quadrilateral.ComplexQuadrilateral) - instance = Quadrilateral(shape_type="Quadrilateral", quadrilateral_type="SimpleQuadrilateral") + instance = Quadrilateral(shapeType="Quadrilateral", quadrilateralType="SimpleQuadrilateral") assert isinstance(instance, simple_quadrilateral.SimpleQuadrilateral) diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_request_body.py b/samples/openapi3/client/petstore/python/tests_manual/test_request_body.py similarity index 100% rename from samples/openapi3/client/petstore/python-experimental/tests_manual/test_request_body.py rename to samples/openapi3/client/petstore/python/tests_manual/test_request_body.py diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_shape.py b/samples/openapi3/client/petstore/python/tests_manual/test_shape.py index a2b59fc6f3..80bab5b805 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_shape.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_shape.py @@ -13,18 +13,18 @@ import sys import unittest +import frozendict + import petstore_api -try: - from petstore_api.model import quadrilateral -except ImportError: - quadrilateral = sys.modules[ - 'petstore_api.model.quadrilateral'] -try: - from petstore_api.model import triangle -except ImportError: - triangle = sys.modules[ - 'petstore_api.model.triangle'] +from petstore_api.schemas import Singleton from petstore_api.model.shape import Shape +from petstore_api.model import complex_quadrilateral +from petstore_api.model import simple_quadrilateral +from petstore_api.model import triangle +from petstore_api.model import triangle_interface +from petstore_api.model import equilateral_triangle +from petstore_api.model import isosceles_triangle +from petstore_api.model import scalene_triangle class TestShape(unittest.TestCase): @@ -44,71 +44,74 @@ class TestShape(unittest.TestCase): def testShape(self): """Test Shape""" - from petstore_api.model import complex_quadrilateral - from petstore_api.model import simple_quadrilateral - from petstore_api.model import equilateral_triangle - from petstore_api.model import isosceles_triangle - from petstore_api.model import scalene_triangle - tri = triangle.Triangle( - shape_type="Triangle", - triangle_type="EquilateralTriangle" + tri = Shape( + shapeType="Triangle", + triangleType="EquilateralTriangle" ) assert isinstance(tri, equilateral_triangle.EquilateralTriangle) + assert isinstance(tri, triangle.Triangle) + assert isinstance(tri, triangle_interface.TriangleInterface) + assert isinstance(tri, Shape) + assert isinstance(tri, frozendict.frozendict) + assert isinstance(tri.shapeType, str) + assert isinstance(tri.shapeType, Singleton) - tri = triangle.Triangle( - shape_type="Triangle", - triangle_type="IsoscelesTriangle" + tri = Shape( + shapeType="Triangle", + triangleType="IsoscelesTriangle" ) assert isinstance(tri, isosceles_triangle.IsoscelesTriangle) - tri = triangle.Triangle( - shape_type="Triangle", - triangle_type="ScaleneTriangle" + tri = Shape( + shapeType="Triangle", + triangleType="ScaleneTriangle" ) assert isinstance(tri, scalene_triangle.ScaleneTriangle) quad = Shape( - shape_type="Quadrilateral", - quadrilateral_type="ComplexQuadrilateral" + shapeType="Quadrilateral", + quadrilateralType="ComplexQuadrilateral" ) assert isinstance(quad, complex_quadrilateral.ComplexQuadrilateral) quad = Shape( - shape_type="Quadrilateral", - quadrilateral_type="SimpleQuadrilateral" + shapeType="Quadrilateral", + quadrilateralType="SimpleQuadrilateral" ) assert isinstance(quad, simple_quadrilateral.SimpleQuadrilateral) - # No discriminator provided. - err_msg = ("Cannot deserialize input data due to missing discriminator. " - "The discriminator property '{}' is missing at path: ()" - ) + # data missing with self.assertRaisesRegex( - petstore_api.ApiValueError, - err_msg.format("shapeType") + petstore_api.exceptions.ApiValueError, + r"Cannot deserialize input data due to missing discriminator. The discriminator " + r"property 'shapeType' is missing at path: \('args\[0\]',\)" ): - Shape() + Shape({}) # invalid shape_type (first discriminator). 'Circle' does not exist in the model. - err_msg = ("Cannot deserialize input data due to invalid discriminator " - "value. The OpenAPI document has no mapping for discriminator " - "property '{}'='{}' at path: ()" - ) + err_msg = ( + r"Invalid discriminator value was passed in to Shape.shapeType Only the values " + r"\['Quadrilateral', 'Triangle'\] are allowed at \('args\[0\]', 'shapeType'\)" + ) with self.assertRaisesRegex( petstore_api.ApiValueError, - err_msg.format("shapeType", "Circle") + err_msg ): - Shape(shape_type="Circle") + Shape(shapeType="Circle") # invalid quadrilateral_type (second discriminator) + err_msg = ( + r"Invalid discriminator value was passed in to Quadrilateral.quadrilateralType Only the values " + r"\['ComplexQuadrilateral', 'SimpleQuadrilateral'\] are allowed at \('args\[0\]', 'quadrilateralType'\)" + ) with self.assertRaisesRegex( petstore_api.ApiValueError, - err_msg.format("quadrilateralType", "Triangle") + err_msg ): Shape( - shape_type="Quadrilateral", - quadrilateral_type="Triangle" + shapeType="Quadrilateral", + quadrilateralType="Triangle" ) if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_string_enum.py b/samples/openapi3/client/petstore/python/tests_manual/test_string_enum.py index 87092d66d3..0485242b37 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_string_enum.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_string_enum.py @@ -10,11 +10,11 @@ """ -import sys import unittest import petstore_api from petstore_api.model.string_enum import StringEnum +from petstore_api.schemas import Singleton, NoneClass class TestStringEnum(unittest.TestCase): @@ -29,24 +29,28 @@ class TestStringEnum(unittest.TestCase): def testStringEnum(self): """Test StringEnum""" inst = StringEnum(None) - self.assertIsNone(inst) + assert isinstance(inst, StringEnum) + assert isinstance(inst, NoneClass) + assert repr(inst) == '' inst = StringEnum('approved') assert isinstance(inst, StringEnum) + assert isinstance(inst, Singleton) + assert isinstance(inst, str) + assert inst == 'approved' + assert repr(inst) == "" with self.assertRaises(petstore_api.ApiValueError): StringEnum('garbage') # make sure that we can access its allowed_values - assert StringEnum.allowed_values[('value',)] == { - 'None': None, - 'PLACED': "placed", - 'APPROVED': "approved", - 'DELIVERED': "delivered", - 'DOUBLE_QUOTE_WITH_NEWLINE': "double quote \n with newline", - 'MULTIPLE_LINES': "multiple\nlines", - 'SINGLE_QUOTED': "single quoted" - } + assert isinstance(StringEnum.NONE, NoneClass) + assert StringEnum.PLACED == 'placed' + assert StringEnum.APPROVED == 'approved' + assert StringEnum.DELIVERED == 'delivered' + assert StringEnum.DOUBLE_QUOTE_WITH_NEWLINE == "double quote \n with newline" + assert StringEnum.MULTIPLE_LINES == "multiple\nlines" + assert StringEnum.SINGLE_QUOTED == "single quoted" if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_triangle.py b/samples/openapi3/client/petstore/python/tests_manual/test_triangle.py index 7268022cad..3d19a8d65f 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_triangle.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_triangle.py @@ -10,45 +10,29 @@ """ -import sys import unittest -import petstore_api -try: - from petstore_api.model import equilateral_triangle -except ImportError: - equilateral_triangle = sys.modules[ - 'petstore_api.model.equilateral_triangle'] -try: - from petstore_api.model import isosceles_triangle -except ImportError: - isosceles_triangle = sys.modules[ - 'petstore_api.model.isosceles_triangle'] -try: - from petstore_api.model import scalene_triangle -except ImportError: - scalene_triangle = sys.modules[ - 'petstore_api.model.scalene_triangle'] +import frozendict + +from petstore_api.model.equilateral_triangle import EquilateralTriangle +from petstore_api.model.isosceles_triangle import IsoscelesTriangle +from petstore_api.model.scalene_triangle import ScaleneTriangle from petstore_api.model.triangle import Triangle +from petstore_api.model.triangle_interface import TriangleInterface class TestTriangle(unittest.TestCase): """Triangle unit test stubs""" - def setUp(self): - pass - - def tearDown(self): - pass - def testTriangle(self): """Test Triangle""" - tri = Triangle(shape_type="Triangle", triangle_type="EquilateralTriangle") - assert isinstance(tri, equilateral_triangle.EquilateralTriangle) - tri = Triangle(shape_type="Triangle", triangle_type="IsoscelesTriangle") - assert isinstance(tri, isosceles_triangle.IsoscelesTriangle) - tri = Triangle(shape_type="Triangle", triangle_type="ScaleneTriangle") - assert isinstance(tri, scalene_triangle.ScaleneTriangle) + tri_classes = [EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle] + for tri_class in tri_classes: + tri = Triangle(shapeType="Triangle", triangleType=tri_class.__name__) + assert isinstance(tri, tri_class) + assert isinstance(tri, Triangle) + assert isinstance(tri, TriangleInterface) + assert isinstance(tri, frozendict.frozendict) if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_user_api.py b/samples/openapi3/client/petstore/python/tests_manual/test_user_api.py new file mode 100644 index 0000000000..5f52c56f5a --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_user_api.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" +import unittest +from unittest.mock import patch + +import petstore_api +from petstore_api import api_client +from petstore_api.apis.tags.user_api import UserApi +from petstore_api.rest import RESTClientObject + +from . import ApiTestMixin + + +class TestUserApi(ApiTestMixin): + """UserApi unit test stubs""" + configuration = petstore_api.Configuration() + api = UserApi(api_client=api_client.ApiClient(configuration=configuration)) + + def test_create_user(self): + """Test case for create_user + + Create user # noqa: E501 + """ + pass + + def test_create_users_with_array_input(self): + """Test case for create_users_with_array_input + + Creates list of users with given input array # noqa: E501 + """ + pass + + def test_create_users_with_list_input(self): + """Test case for create_users_with_list_input + + Creates list of users with given input array # noqa: E501 + """ + pass + + def test_delete_user(self): + """Test case for delete_user + + Delete user # noqa: E501 + """ + pass + + def test_get_user_by_name(self): + from petstore_api.model import user + + # serialization + deserialization works + with patch.object(RESTClientObject, 'request') as mock_request: + value_simple = dict( + id=1, + username='first last', + firstName='first', + lastName='last' + ) + body = user.User(**value_simple) + mock_request.return_value = self.response( + self.json_bytes(value_simple) + ) + + api_response = self.api.get_user_by_name( + path_params=dict(username='first last') + ) + self.assert_request_called_with( + mock_request, + 'http://petstore.swagger.io:80/v2/user/first%20last', + method='GET', + accept_content_type='application/xml, application/json', + content_type=None + ) + + assert isinstance(api_response.body, user.User) + assert api_response.body == body + + def test_login_user(self): + """Test case for login_user + + Logs user into the system # noqa: E501 + """ + pass + + def test_logout_user(self): + """Test case for logout_user + + Logs out current logged in user session # noqa: E501 + """ + pass + + def test_update_user(self): + """Test case for update_user + + Updated user # noqa: E501 + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_uuid_string.py b/samples/openapi3/client/petstore/python/tests_manual/test_uuid_string.py new file mode 100644 index 0000000000..e8715b571a --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_uuid_string.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import unittest + +from petstore_api import schemas, exceptions +from petstore_api.model.uuid_string import UUIDString +import uuid + + +class TestUUIDString(unittest.TestCase): + """UUIDString unit test stubs""" + + def test_UUIDString(self): + """Test UUIDString""" + uuid_value = '12345678-1234-5678-1234-567812345678' + u = UUIDString(uuid_value) + self.assertEqual(u, uuid_value) + self.assertTrue(isinstance(u, UUIDString)) + self.assertTrue(isinstance(u, schemas.UUIDSchema)) + self.assertTrue(isinstance(u, schemas.StrSchema)) + self.assertTrue(isinstance(u, str)) + self.assertEqual(u.as_uuid_oapg, uuid.UUID(uuid_value)) + + # passing in a uuid also works + u = UUIDString(uuid.UUID(uuid_value)) + self.assertEqual(u, uuid_value) + self.assertTrue(isinstance(u, UUIDString)) + self.assertTrue(isinstance(u, schemas.UUIDSchema)) + self.assertTrue(isinstance(u, schemas.StrSchema)) + self.assertTrue(isinstance(u, str)) + self.assertEqual(u.as_uuid_oapg, uuid.UUID(uuid_value)) + + # an invalid value does not work + with self.assertRaises(exceptions.ApiValueError): + UUIDString('1') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_validate.py b/samples/openapi3/client/petstore/python/tests_manual/test_validate.py new file mode 100644 index 0000000000..4a61f9c7f9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_validate.py @@ -0,0 +1,286 @@ +# coding: utf-8 +import decimal +from decimal import Decimal +from unittest.mock import patch, call +import unittest + +import frozendict + +from petstore_api.model.string_with_validation import StringWithValidation +from petstore_api.model.string_enum import StringEnum +from petstore_api.model.number_with_validations import NumberWithValidations +from petstore_api.model.array_holding_any_type import ArrayHoldingAnyType +from petstore_api.model.array_with_validations_in_items import ( + ArrayWithValidationsInItems, +) +from petstore_api.model.foo import Foo +from petstore_api.model.animal import Animal +from petstore_api.model.dog import Dog +from petstore_api.model.boolean_enum import BooleanEnum +from petstore_api.model.pig import Pig +from petstore_api.model.danish_pig import DanishPig +from petstore_api.model.gm_fruit import GmFruit +from petstore_api.model.apple import Apple +from petstore_api.model.banana import Banana +from petstore_api import schemas + +from petstore_api.schemas import ( + AnyTypeSchema, + BoolClass, + NoneClass, + StrSchema, + NumberSchema, + Schema, + ValidationMetadata, +) + + +class TestValidateResults(unittest.TestCase): + def test_str_validate(self): + vm = ValidationMetadata() + path_to_schemas = StringWithValidation._validate_oapg( + "abcdefg", validation_metadata=vm + ) + assert path_to_schemas == {("args[0]",): {StringWithValidation, str}} + + def test_number_validate(self): + vm = ValidationMetadata() + path_to_schemas = NumberWithValidations._validate_oapg( + Decimal(11), validation_metadata=vm + ) + assert path_to_schemas == {("args[0]",): {NumberWithValidations, Decimal}} + + def test_str_enum_validate(self): + vm = ValidationMetadata() + path_to_schemas = StringEnum._validate_oapg("placed", validation_metadata=vm) + assert path_to_schemas == {("args[0]",): {str, StringEnum}} + + def test_nullable_enum_validate(self): + vm = ValidationMetadata() + path_to_schemas = StringEnum._validate_oapg(NoneClass.NONE, validation_metadata=vm) + assert path_to_schemas == {("args[0]",): {NoneClass, StringEnum}} + + def test_empty_list_validate(self): + vm = ValidationMetadata() + path_to_schemas = ArrayHoldingAnyType._validate_oapg((), validation_metadata=vm) + assert path_to_schemas == {("args[0]",): {ArrayHoldingAnyType, tuple}} + + def test_list_validate(self): + vm = ValidationMetadata() + path_to_schemas = ArrayHoldingAnyType._validate_oapg( + (Decimal(1), "a"), validation_metadata=vm + ) + assert path_to_schemas == { + ("args[0]",): {ArrayHoldingAnyType, tuple}, + ("args[0]", 0): {AnyTypeSchema, Decimal}, + ("args[0]", 1): {AnyTypeSchema, str}, + } + + def test_empty_dict_validate(self): + vm = ValidationMetadata() + path_to_schemas = Foo._validate_oapg(frozendict.frozendict({}), validation_metadata=vm) + assert path_to_schemas == {("args[0]",): {Foo, frozendict.frozendict}} + + def test_dict_validate(self): + vm = ValidationMetadata() + path_to_schemas = Foo._validate_oapg( + frozendict.frozendict({"bar": "a", "additional": Decimal(0)}), + validation_metadata=vm, + ) + assert path_to_schemas == { + ("args[0]",): {Foo, frozendict.frozendict}, + ("args[0]", "bar"): {StrSchema, str}, + ("args[0]", "additional"): {schemas.UnsetAnyTypeSchema, decimal.Decimal}, + } + + def test_discriminated_dict_validate(self): + vm = ValidationMetadata() + path_to_schemas = Animal._validate_oapg( + frozendict.frozendict(className="Dog", color="black"), validation_metadata=vm + ) + for path, schema_classes in path_to_schemas.items(): + Animal._process_schema_classes_oapg(schema_classes) + assert path_to_schemas == { + ("args[0]",): {Animal, Dog, Dog.MetaOapg.all_of()[1], frozendict.frozendict}, + ("args[0]", "className"): {StrSchema, str}, + ("args[0]", "color"): {StrSchema, str}, + } + + def test_bool_enum_validate(self): + vm = ValidationMetadata() + path_to_schemas = BooleanEnum._validate_oapg(BoolClass.TRUE, validation_metadata=vm) + assert path_to_schemas == {("args[0]",): {BoolClass, BooleanEnum}} + + def test_oneof_composition_pig_validate(self): + vm = ValidationMetadata() + path_to_schemas = Pig._validate_oapg( + frozendict.frozendict(className="DanishPig"), validation_metadata=vm + ) + for path, schema_classes in path_to_schemas.items(): + Pig._process_schema_classes_oapg(schema_classes) + assert path_to_schemas == { + ("args[0]",): {Pig, DanishPig, frozendict.frozendict}, + ("args[0]", "className"): {DanishPig.MetaOapg.properties.className, str}, + } + + def test_anyof_composition_gm_fruit_validate(self): + vm = ValidationMetadata() + path_to_schemas = GmFruit._validate_oapg( + frozendict.frozendict(cultivar="GoldenDelicious", lengthCm=Decimal(10)), + validation_metadata=vm, + ) + for path, schema_classes in path_to_schemas.items(): + GmFruit._process_schema_classes_oapg(schema_classes) + assert path_to_schemas == { + ("args[0]",): {GmFruit, Apple, Banana, frozendict.frozendict}, + ("args[0]", "cultivar"): {Apple.MetaOapg.properties.cultivar, str}, + ("args[0]", "lengthCm"): {NumberSchema, Decimal}, + } + + +class TestValidateCalls(unittest.TestCase): + def test_empty_list_validate(self): + return_value = {("args[0]",): {ArrayHoldingAnyType, tuple}} + with patch.object( + Schema, "_validate_oapg", return_value=return_value + ) as mock_validate: + ArrayHoldingAnyType([]) + assert mock_validate.call_count == 1 + + with patch.object( + Schema, "_validate_oapg", return_value=return_value + ) as mock_validate: + ArrayHoldingAnyType.from_openapi_data_oapg([]) + assert mock_validate.call_count == 1 + + def test_empty_dict_validate(self): + return_value = {("args[0]",): {Foo, frozendict.frozendict}} + with patch.object( + Schema, "_validate_oapg", return_value=return_value + ) as mock_validate: + Foo({}) + assert mock_validate.call_count == 1 + + with patch.object( + Schema, "_validate_oapg", return_value=return_value + ) as mock_validate: + Foo.from_openapi_data_oapg({}) + assert mock_validate.call_count == 1 + + def test_list_validate_direct_instantiation(self): + results = [ + {("args[0]",): {ArrayWithValidationsInItems, tuple}}, + {("args[0]", 0): {ArrayWithValidationsInItems.MetaOapg.items, Decimal}} + ] + with patch.object(Schema, "_validate_oapg", side_effect=results) as mock_validate: + ArrayWithValidationsInItems([7]) + calls = [ + call( + (Decimal("7"),), + validation_metadata=ValidationMetadata(path_to_item=("args[0]",)) + ), + call( + Decimal("7"), + validation_metadata=ValidationMetadata(path_to_item=("args[0]", 0)) + ) + ] + mock_validate.assert_has_calls( + calls + ) + + def test_list_validate_direct_instantiation_cast_item(self): + # item validation is skipped if items are of the correct type + item = ArrayWithValidationsInItems.MetaOapg.items(7) + return_value = {("args[0]",): {ArrayWithValidationsInItems, tuple}} + with patch.object(Schema, "_validate_oapg", return_value=return_value) as mock_validate: + ArrayWithValidationsInItems([item]) + mock_validate.assert_called_once_with( + tuple([Decimal('7')]), + validation_metadata=ValidationMetadata( + validated_path_to_schemas={('args[0]', 0): {ArrayWithValidationsInItems.MetaOapg.items, Decimal}} + ) + ) + + def test_list_validate_from_openai_data_instantiation(self): + + results = [ + {("args[0]",): {ArrayWithValidationsInItems, tuple}}, + {("args[0]", 0): {ArrayWithValidationsInItems.MetaOapg.items, Decimal}} + ] + with patch.object(Schema, "_validate_oapg", side_effect=results) as mock_validate: + ArrayWithValidationsInItems.from_openapi_data_oapg([7]) + calls = [ + call( + (Decimal("7"),), + validation_metadata=ValidationMetadata(path_to_item=("args[0]",), from_server=True) + ), + call( + Decimal("7"), + validation_metadata=ValidationMetadata(path_to_item=("args[0]", 0), from_server=True) + ) + ] + mock_validate.assert_has_calls( + calls + ) + + def test_dict_validate_direct_instantiation(self): + call_results = [ + {("args[0]",): {Foo, frozendict.frozendict}}, + {("args[0]", "bar"): {StrSchema, str}} + ] + with patch.object(Schema, "_validate_oapg", side_effect=call_results) as mock_validate: + Foo(bar="a") + calls = [ + call( + frozendict.frozendict({"bar": "a"}), + validation_metadata=ValidationMetadata(path_to_item=("args[0]",)), + ), + call( + "a", + validation_metadata=ValidationMetadata(path_to_item=("args[0]", "bar")), + ), + ] + mock_validate.assert_has_calls( + calls + ) + + def test_dict_validate_direct_instantiation_cast_item(self): + bar = StrSchema("a") + return_value = { + ("args[0]",): {Foo, frozendict.frozendict} + } + # only the Foo dict is validated because the bar property value was already validated + with patch.object(Schema, "_validate_oapg", return_value=return_value) as mock_validate: + Foo(bar=bar) + mock_validate.assert_called_once_with( + frozendict.frozendict(dict(bar='a')), + validation_metadata=ValidationMetadata( + validated_path_to_schemas={('args[0]', 'bar'): {str, StrSchema}} + ) + ) + + def test_dict_validate_from_openapi_data_instantiation(self): + + return_values = [ + {("args[0]",): {Foo, frozendict.frozendict}}, + {("args[0]", 'bar'): {StrSchema, str}} + ] + with patch.object(Schema, "_validate_oapg", side_effect=return_values) as mock_validate: + Foo.from_openapi_data_oapg({"bar": "a"}) + calls = [ + call( + frozendict.frozendict({"bar": "a"}), + validation_metadata=ValidationMetadata(path_to_item=("args[0]",), from_server=True), + ), + call( + "a", + validation_metadata=ValidationMetadata(path_to_item=("args[0]", "bar"), from_server=True), + ), + ] + mock_validate.assert_has_calls( + calls + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_whale.py b/samples/openapi3/client/petstore/python/tests_manual/test_whale.py new file mode 100644 index 0000000000..7ce302faf9 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_whale.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.schemas import BoolClass +from petstore_api.model.whale import Whale + + +class TestWhale(unittest.TestCase): + """Whale unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_Whale(self): + # test that the hasBaleen __bool__ method is working, True input + whale = Whale( + className='whale', + hasBaleen=True + ) + assert isinstance(whale["hasBaleen"], BoolClass) + self.assertTrue(whale["hasBaleen"]) + + # test that the hasBaleen __bool__ method is working, False input + whale = Whale( + className='whale', + hasBaleen=False + ) + assert isinstance(whale["hasBaleen"], BoolClass) + self.assertFalse(whale["hasBaleen"]) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tox.ini b/samples/openapi3/client/petstore/python/tox.ini index 8989fc3c4d..e57c17e10c 100644 --- a/samples/openapi3/client/petstore/python/tox.ini +++ b/samples/openapi3/client/petstore/python/tox.ini @@ -1,7 +1,8 @@ [tox] -envlist = py3 +envlist = py37 [testenv] +passenv = PYTHON_VERSION deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt diff --git a/samples/openapi3/client/petstore/spring-cloud-3/pom.xml b/samples/openapi3/client/petstore/spring-cloud-3/pom.xml index f77261a826..5f8ccfd5a7 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3/pom.xml +++ b/samples/openapi3/client/petstore/spring-cloud-3/pom.xml @@ -15,7 +15,7 @@ org.springframework.boot spring-boot-starter-parent - 3.0.0-M3 + 3.0.0-M4 @@ -36,7 +36,7 @@ org.springframework.cloud spring-cloud-starter-parent - 2022.0.0-M2 + 2022.0.0-M3 pom import diff --git a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/PetApi.java index bc1909e9fe..30c58f6915 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/PetApi.java @@ -33,6 +33,7 @@ import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "Pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { /** diff --git a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/StoreApi.java index aaddacafbe..f79189f80f 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "Store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { /** diff --git a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/UserApi.java index 1a9cdcc3ef..cc77390af7 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "User", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { /** diff --git a/samples/openapi3/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java b/samples/openapi3/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java index 35c710eabb..30c8911cee 100644 --- a/samples/openapi3/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "Default", description = "the Default API") +@RequestMapping("${openapi.apiDocumentation.base-path:}") public interface DefaultApi { /** @@ -58,7 +59,7 @@ public interface DefaultApi { ResponseEntity get( @Parameter(name = "date", description = "A date path parameter", required = true) @PathVariable("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date, @NotNull @Parameter(name = "dateTime", description = "A date-time query parameter", required = true) @Valid @RequestParam(value = "dateTime", required = true, defaultValue = "1973-12-19T03:39:57-08:00") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime dateTime, - @Parameter(name = "X-Order-Date", description = "A date header parameter", required = true) @RequestHeader(value = "X-Order-Date", required = true, defaultValue = "1974-01-01") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate xOrderDate, + @NotNull @Parameter(name = "X-Order-Date", description = "A date header parameter", required = true) @RequestHeader(value = "X-Order-Date", required = true, defaultValue = "1974-01-01") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate xOrderDate, @Parameter(name = "loginDate", description = "A date cookie parameter") @CookieValue(name = "loginDate", required = false, defaultValue = "1975-01-01") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate loginDate ); diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/AnotherFakeApi.java index a21b1916ae..84837cf1dd 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "AnotherFake", description = "the AnotherFake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { /** diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeApi.java index d812fa5fd3..8a73dbca10 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeApi.java @@ -41,6 +41,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "Fake", description = "the Fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { /** @@ -372,7 +373,7 @@ public interface FakeApi { ) ResponseEntity testGroupParameters( @NotNull @Parameter(name = "required_string_group", description = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @Parameter(name = "required_int64_group", description = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @Parameter(name = "string_group", description = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @Parameter(name = "boolean_group", description = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java index 794f25a328..94b8e7779b 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "FakeClassnameTags123", description = "the FakeClassnameTags123 API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTags123Api { /** diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/PetApi.java index 39a547ec1c..156699e253 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/PetApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "Pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { /** diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/StoreApi.java index 9430c0809f..ba77c812f4 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "Store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { /** diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/UserApi.java index 5926abfc32..c3bf7df796 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "User", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { /** diff --git a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java index 24e64154f0..6bc73c277e 100644 --- a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "Pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { /** diff --git a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java index b7969c15d8..af22eb0616 100644 --- a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "Store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { /** diff --git a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java index 44d13bc249..adbdbe82f4 100644 --- a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "User", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { /** diff --git a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/PetApi.java index de6b1b5566..02cb551afa 100644 --- a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/PetApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { /** diff --git a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/StoreApi.java index 784aa1c77d..3c83753fb5 100644 --- a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { /** diff --git a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/UserApi.java index 602034cca3..d205905ebb 100644 --- a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { /** diff --git a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java index 05dcb52a67..ca5a307ca0 100644 --- a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java index c0afe718ec..e7ee77cb16 100644 --- a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java index cd4708c1db..06abe291df 100644 --- a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/browser/apis/PetApi.ts index 273352e4f6..514291812d 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/apis/PetApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import {ObjectSerializer} from '../models/ObjectSerializer'; diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/browser/apis/StoreApi.ts index 1eead29227..c60c1d8708 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/apis/StoreApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import {ObjectSerializer} from '../models/ObjectSerializer'; diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/browser/apis/UserApi.ts index 9784393c7a..0331c7117d 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/apis/UserApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import {ObjectSerializer} from '../models/ObjectSerializer'; diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/browser/models/ObjectSerializer.ts index 6c5432f558..a5f5708b12 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/models/ObjectSerializer.ts @@ -1,16 +1,16 @@ -export * from './ApiResponse'; -export * from './Category'; -export * from './Order'; -export * from './Pet'; -export * from './Tag'; -export * from './User'; +export * from '../models/ApiResponse'; +export * from '../models/Category'; +export * from '../models/Order'; +export * from '../models/Pet'; +export * from '../models/Tag'; +export * from '../models/User'; -import { ApiResponse } from './ApiResponse'; -import { Category } from './Category'; -import { Order , OrderStatusEnum } from './Order'; -import { Pet , PetStatusEnum } from './Pet'; -import { Tag } from './Tag'; -import { User } from './User'; +import { ApiResponse } from '../models/ApiResponse'; +import { Category } from '../models/Category'; +import { Order , OrderStatusEnum } from '../models/Order'; +import { Pet , PetStatusEnum } from '../models/Pet'; +import { Tag } from '../models/Tag'; +import { User } from '../models/User'; /* tslint:disable:no-unused-variable */ let primitives = [ @@ -233,6 +233,10 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } + if (mediaType === "text/plain") { + return rawData; + } + if (mediaType === "application/json") { return JSON.parse(rawData); } diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/models/Pet.ts b/samples/openapi3/client/petstore/typescript/builds/browser/models/Pet.ts index 6b191ad8d7..b3a7ddb9f7 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/models/Pet.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/models/Pet.ts @@ -10,8 +10,8 @@ * Do not edit the class manually. */ -import { Category } from './Category'; -import { Tag } from './Tag'; +import { Category } from '../models/Category'; +import { Tag } from '../models/Tag'; import { HttpFile } from '../http/http'; /** diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/models/all.ts b/samples/openapi3/client/petstore/typescript/builds/browser/models/all.ts index 2edba7f0bd..d63b43c967 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/models/all.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/models/all.ts @@ -1,6 +1,6 @@ -export * from './ApiResponse' -export * from './Category' -export * from './Order' -export * from './Pet' -export * from './Tag' -export * from './User' +export * from '../models/ApiResponse' +export * from '../models/Category' +export * from '../models/Order' +export * from '../models/Pet' +export * from '../models/Tag' +export * from '../models/User' diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/types/ObjectParamAPI.ts b/samples/openapi3/client/petstore/typescript/builds/browser/types/ObjectParamAPI.ts index bad3c9fc25..acc26d9ef9 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/types/ObjectParamAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/types/ObjectParamAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { ApiResponse } from '../models/ApiResponse'; diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/browser/types/ObservableAPI.ts index 74f57a7e1c..b5b9a542b2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/types/ObservableAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Observable, of, from } from '../rxjsStub'; import {mergeMap, map} from '../rxjsStub'; diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/browser/types/PromiseAPI.ts index 92d57b673d..7279c47feb 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/types/PromiseAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { ApiResponse } from '../models/ApiResponse'; diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/apis/DefaultApi.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/apis/DefaultApi.ts index 616be727eb..9f7c82dfb4 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/apis/DefaultApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/apis/DefaultApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import {ObjectSerializer} from '../models/ObjectSerializer'; diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/ObjectSerializer.ts index 6b3b745cbb..6317becfd9 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/ObjectSerializer.ts @@ -1,22 +1,22 @@ -export * from './Cat'; -export * from './CatAllOf'; -export * from './Dog'; -export * from './DogAllOf'; -export * from './FilePostRequest'; -export * from './PetByAge'; -export * from './PetByType'; -export * from './PetsFilteredPatchRequest'; -export * from './PetsPatchRequest'; +export * from '../models/Cat'; +export * from '../models/CatAllOf'; +export * from '../models/Dog'; +export * from '../models/DogAllOf'; +export * from '../models/FilePostRequest'; +export * from '../models/PetByAge'; +export * from '../models/PetByType'; +export * from '../models/PetsFilteredPatchRequest'; +export * from '../models/PetsPatchRequest'; -import { Cat } from './Cat'; -import { CatAllOf } from './CatAllOf'; -import { Dog , DogBreedEnum } from './Dog'; -import { DogAllOf , DogAllOfBreedEnum } from './DogAllOf'; -import { FilePostRequest } from './FilePostRequest'; -import { PetByAge } from './PetByAge'; -import { PetByType, PetByTypePetTypeEnum } from './PetByType'; -import { PetsFilteredPatchRequest , PetsFilteredPatchRequestPetTypeEnum } from './PetsFilteredPatchRequest'; -import { PetsPatchRequest , PetsPatchRequestBreedEnum } from './PetsPatchRequest'; +import { Cat } from '../models/Cat'; +import { CatAllOf } from '../models/CatAllOf'; +import { Dog , DogBreedEnum } from '../models/Dog'; +import { DogAllOf , DogAllOfBreedEnum } from '../models/DogAllOf'; +import { FilePostRequest } from '../models/FilePostRequest'; +import { PetByAge } from '../models/PetByAge'; +import { PetByType, PetByTypePetTypeEnum } from '../models/PetByType'; +import { PetsFilteredPatchRequest , PetsFilteredPatchRequestPetTypeEnum } from '../models/PetsFilteredPatchRequest'; +import { PetsPatchRequest , PetsPatchRequestBreedEnum } from '../models/PetsPatchRequest'; /* tslint:disable:no-unused-variable */ let primitives = [ @@ -245,6 +245,10 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } + if (mediaType === "text/plain") { + return rawData; + } + if (mediaType === "application/json") { return JSON.parse(rawData); } diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/PetsFilteredPatchRequest.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/PetsFilteredPatchRequest.ts index 8e4fae3898..12ae18d6b7 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/PetsFilteredPatchRequest.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/PetsFilteredPatchRequest.ts @@ -10,8 +10,8 @@ * Do not edit the class manually. */ -import { PetByAge } from './PetByAge'; -import { PetByType } from './PetByType'; +import { PetByAge } from '../models/PetByAge'; +import { PetByType } from '../models/PetByType'; import { HttpFile } from '../http/http'; export class PetsFilteredPatchRequest { diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/PetsPatchRequest.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/PetsPatchRequest.ts index e035f28053..c68b69a329 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/PetsPatchRequest.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/PetsPatchRequest.ts @@ -10,8 +10,8 @@ * Do not edit the class manually. */ -import { Cat } from './Cat'; -import { Dog } from './Dog'; +import { Cat } from '../models/Cat'; +import { Dog } from '../models/Dog'; import { HttpFile } from '../http/http'; export class PetsPatchRequest { diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/all.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/all.ts index 61fd42f246..029557b7a2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/all.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/all.ts @@ -1,9 +1,9 @@ -export * from './Cat' -export * from './CatAllOf' -export * from './Dog' -export * from './DogAllOf' -export * from './FilePostRequest' -export * from './PetByAge' -export * from './PetByType' -export * from './PetsFilteredPatchRequest' -export * from './PetsPatchRequest' +export * from '../models/Cat' +export * from '../models/CatAllOf' +export * from '../models/Dog' +export * from '../models/DogAllOf' +export * from '../models/FilePostRequest' +export * from '../models/PetByAge' +export * from '../models/PetByType' +export * from '../models/PetsFilteredPatchRequest' +export * from '../models/PetsPatchRequest' diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/ObjectParamAPI.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/ObjectParamAPI.ts index ac317b1e0e..073f655033 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/ObjectParamAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/ObjectParamAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Cat } from '../models/Cat'; diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/ObservableAPI.ts index 15651a2bca..52b5367f4b 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/ObservableAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Observable, of, from } from '../rxjsStub'; import {mergeMap, map} from '../rxjsStub'; diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/PromiseAPI.ts index 91071153a8..a42cc75688 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/types/PromiseAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Cat } from '../models/Cat'; diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts index 3dec522f6e..5b3d37fe35 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import * as FormData from "form-data"; diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts index e26ee9a00b..2682c0fc70 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import * as FormData from "form-data"; diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts index ede979aad4..352b499b37 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import * as FormData from "form-data"; diff --git a/samples/openapi3/client/petstore/typescript/builds/default/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/default/models/ObjectSerializer.ts index 6c5432f558..a5f5708b12 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/models/ObjectSerializer.ts @@ -1,16 +1,16 @@ -export * from './ApiResponse'; -export * from './Category'; -export * from './Order'; -export * from './Pet'; -export * from './Tag'; -export * from './User'; +export * from '../models/ApiResponse'; +export * from '../models/Category'; +export * from '../models/Order'; +export * from '../models/Pet'; +export * from '../models/Tag'; +export * from '../models/User'; -import { ApiResponse } from './ApiResponse'; -import { Category } from './Category'; -import { Order , OrderStatusEnum } from './Order'; -import { Pet , PetStatusEnum } from './Pet'; -import { Tag } from './Tag'; -import { User } from './User'; +import { ApiResponse } from '../models/ApiResponse'; +import { Category } from '../models/Category'; +import { Order , OrderStatusEnum } from '../models/Order'; +import { Pet , PetStatusEnum } from '../models/Pet'; +import { Tag } from '../models/Tag'; +import { User } from '../models/User'; /* tslint:disable:no-unused-variable */ let primitives = [ @@ -233,6 +233,10 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } + if (mediaType === "text/plain") { + return rawData; + } + if (mediaType === "application/json") { return JSON.parse(rawData); } diff --git a/samples/openapi3/client/petstore/typescript/builds/default/models/Pet.ts b/samples/openapi3/client/petstore/typescript/builds/default/models/Pet.ts index 6b191ad8d7..b3a7ddb9f7 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/models/Pet.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/models/Pet.ts @@ -10,8 +10,8 @@ * Do not edit the class manually. */ -import { Category } from './Category'; -import { Tag } from './Tag'; +import { Category } from '../models/Category'; +import { Tag } from '../models/Tag'; import { HttpFile } from '../http/http'; /** diff --git a/samples/openapi3/client/petstore/typescript/builds/default/models/all.ts b/samples/openapi3/client/petstore/typescript/builds/default/models/all.ts index 2edba7f0bd..d63b43c967 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/models/all.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/models/all.ts @@ -1,6 +1,6 @@ -export * from './ApiResponse' -export * from './Category' -export * from './Order' -export * from './Pet' -export * from './Tag' -export * from './User' +export * from '../models/ApiResponse' +export * from '../models/Category' +export * from '../models/Order' +export * from '../models/Pet' +export * from '../models/Tag' +export * from '../models/User' diff --git a/samples/openapi3/client/petstore/typescript/builds/default/package-lock.json b/samples/openapi3/client/petstore/typescript/builds/default/package-lock.json index a21ee9c9e4..1eda7470be 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/package-lock.json +++ b/samples/openapi3/client/petstore/typescript/builds/default/package-lock.json @@ -1,8 +1,173 @@ { "name": "ts-petstore-client", "version": "1.0.0", - "lockfileVersion": 1, + "lockfileVersion": 2, "requires": true, + "packages": { + "": { + "name": "ts-petstore-client", + "version": "1.0.0", + "license": "Unlicense", + "dependencies": { + "@types/node": "*", + "@types/node-fetch": "^2.5.7", + "btoa": "^1.2.1", + "es6-promise": "^4.2.4", + "form-data": "^2.5.0", + "node-fetch": "^2.6.0", + "url-parse": "^1.4.3" + }, + "devDependencies": { + "@types/url-parse": "1.4.4", + "typescript": "^4.0" + } + }, + "node_modules/@types/node": { + "version": "12.12.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.7.tgz", + "integrity": "sha512-E6Zn0rffhgd130zbCbAr/JdXfXkoOUFAKNs/rF8qnafSJ8KYaA/j3oz7dcwal+lYjLA7xvdd5J4wdYpCTlP8+w==" + }, + "node_modules/@types/node-fetch": { + "version": "2.5.7", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.7.tgz", + "integrity": "sha512-o2WVNf5UhWRkxlf6eq+jMZDu7kjgpgJfl4xVNlvryc95O/6F2ld8ztKX+qu+Rjyet93WAWm5LjeX9H5FGkODvw==", + "dependencies": { + "@types/node": "*", + "form-data": "^3.0.0" + } + }, + "node_modules/@types/node-fetch/node_modules/form-data": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.0.tgz", + "integrity": "sha512-CKMFDglpbMi6PyN+brwB9Q/GOw0eAnsrEZDgcsH5Krhz5Od/haKHAX0NmQfha2zPPz0JpWzA7GJHGSnvCRLWsg==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@types/url-parse": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/@types/url-parse/-/url-parse-1.4.4.tgz", + "integrity": "sha512-KtQLad12+4T/NfSxpoDhmr22+fig3T7/08QCgmutYA6QSznSRmEtuL95GrhVV40/0otTEdFc+etRcCTqhh1q5Q==", + "dev": true + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, + "node_modules/btoa": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/btoa/-/btoa-1.2.1.tgz", + "integrity": "sha512-SB4/MIGlsiVkMcHmT+pSmIPoNDoHg+7cMzmt3Uxt628MTz2487DKSqK/fuhFBrkuqrYv5UCEnACpF4dTFNKc/g==", + "bin": { + "btoa": "bin/btoa.js" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/es6-promise": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.5.tgz", + "integrity": "sha512-n6wvpdE43VFtJq+lUDYDBFUwV8TZbuGXLV4D6wKafg13ldznKsyEvatubnmUe31zcvelSzOHF+XbaT+Bl9ObDg==" + }, + "node_modules/form-data": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.1.tgz", + "integrity": "sha512-m21N3WOmEEURgk6B9GLOE4RuWOFf28Lhh9qGYeNlGq4VDXUlJy2th2slBNU8Gp8EzloYZOibZJ7t5ecIrFSjVA==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/mime-db": { + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz", + "integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.24", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz", + "integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==", + "dependencies": { + "mime-db": "1.40.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-fetch": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz", + "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==", + "engines": { + "node": "4.x || >=6.0.0" + } + }, + "node_modules/querystringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.1.0.tgz", + "integrity": "sha512-sluvZZ1YiTLD5jsqZcDmFyV2EwToyXZBfpoVOmktMmW+VEnhgakFHnasVph65fOjGPTWN0Nw3+XQaSeMayr0kg==" + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=" + }, + "node_modules/typescript": { + "version": "4.7.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz", + "integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/url-parse": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.4.3.tgz", + "integrity": "sha512-rh+KuAW36YKo0vClhQzLLveoj8FwPJNu65xLb7Mrt+eZht0IPT0IXgSv8gcMegZ6NvjJUALf6Mf25POlMwD1Fw==", + "dependencies": { + "querystringify": "^2.0.0", + "requires-port": "^1.0.0" + } + } + }, "dependencies": { "@types/node": { "version": "12.12.7", @@ -30,6 +195,12 @@ } } }, + "@types/url-parse": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/@types/url-parse/-/url-parse-1.4.4.tgz", + "integrity": "sha512-KtQLad12+4T/NfSxpoDhmr22+fig3T7/08QCgmutYA6QSznSRmEtuL95GrhVV40/0otTEdFc+etRcCTqhh1q5Q==", + "dev": true + }, "asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -97,9 +268,9 @@ "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=" }, "typescript": { - "version": "3.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.3.tgz", - "integrity": "sha512-D/wqnB2xzNFIcoBG9FG8cXRDjiqSTbG2wd8DMZeQyJlP1vfTkIxH4GKveWaEBYySKIg+USu+E+EDIR47SqnaMQ==", + "version": "4.7.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz", + "integrity": "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==", "dev": true }, "url-parse": { diff --git a/samples/openapi3/client/petstore/typescript/builds/default/types/ObjectParamAPI.ts b/samples/openapi3/client/petstore/typescript/builds/default/types/ObjectParamAPI.ts index bad3c9fc25..acc26d9ef9 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/types/ObjectParamAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/types/ObjectParamAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { ApiResponse } from '../models/ApiResponse'; diff --git a/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts index 74f57a7e1c..b5b9a542b2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Observable, of, from } from '../rxjsStub'; import {mergeMap, map} from '../rxjsStub'; diff --git a/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts index 92d57b673d..7279c47feb 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { ApiResponse } from '../models/ApiResponse'; diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts index 1e06ca4f61..8c2c2bf98b 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi.ts'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts index 95dfda9bf2..b391bc0bad 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi.ts'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts index 6b8aedbb87..cf96436616 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi.ts'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi.ts'; import {Configuration} from '../configuration.ts'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http.ts'; import {ObjectSerializer} from '../models/ObjectSerializer.ts'; diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/deno/models/ObjectSerializer.ts index cfe71122b0..a56a21255c 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/models/ObjectSerializer.ts @@ -1,16 +1,16 @@ -export * from './ApiResponse.ts'; -export * from './Category.ts'; -export * from './Order.ts'; -export * from './Pet.ts'; -export * from './Tag.ts'; -export * from './User.ts'; +export * from '../models/ApiResponse.ts'; +export * from '../models/Category.ts'; +export * from '../models/Order.ts'; +export * from '../models/Pet.ts'; +export * from '../models/Tag.ts'; +export * from '../models/User.ts'; -import { ApiResponse } from './ApiResponse.ts'; -import { Category } from './Category.ts'; -import { Order , OrderStatusEnum } from './Order.ts'; -import { Pet , PetStatusEnum } from './Pet.ts'; -import { Tag } from './Tag.ts'; -import { User } from './User.ts'; +import { ApiResponse } from '../models/ApiResponse.ts'; +import { Category } from '../models/Category.ts'; +import { Order , OrderStatusEnum } from '../models/Order.ts'; +import { Pet , PetStatusEnum } from '../models/Pet.ts'; +import { Tag } from '../models/Tag.ts'; +import { User } from '../models/User.ts'; /* tslint:disable:no-unused-variable */ let primitives = [ @@ -233,6 +233,10 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } + if (mediaType === "text/plain") { + return rawData; + } + if (mediaType === "application/json") { return JSON.parse(rawData); } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/models/Pet.ts b/samples/openapi3/client/petstore/typescript/builds/deno/models/Pet.ts index 111ac11c7d..229681feac 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/models/Pet.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/models/Pet.ts @@ -10,8 +10,8 @@ * Do not edit the class manually. */ -import { Category } from './Category.ts'; -import { Tag } from './Tag.ts'; +import { Category } from '../models/Category.ts'; +import { Tag } from '../models/Tag.ts'; import { HttpFile } from '../http/http.ts'; /** diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/models/all.ts b/samples/openapi3/client/petstore/typescript/builds/deno/models/all.ts index e77f63aa4b..374b1e44e2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/models/all.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/models/all.ts @@ -1,6 +1,6 @@ -export * from './ApiResponse.ts' -export * from './Category.ts' -export * from './Order.ts' -export * from './Pet.ts' -export * from './Tag.ts' -export * from './User.ts' +export * from '../models/ApiResponse.ts' +export * from '../models/Category.ts' +export * from '../models/Order.ts' +export * from '../models/Pet.ts' +export * from '../models/Tag.ts' +export * from '../models/User.ts' diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/types/ObjectParamAPI.ts b/samples/openapi3/client/petstore/typescript/builds/deno/types/ObjectParamAPI.ts index 02d096f08b..271b489d45 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/types/ObjectParamAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/types/ObjectParamAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http.ts'; -import * as models from '../models/all.ts'; import { Configuration} from '../configuration.ts' import { ApiResponse } from '../models/ApiResponse.ts'; diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts index f89d38c2f2..a6524a2188 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http.ts'; -import * as models from '../models/all.ts'; import { Configuration} from '../configuration.ts' import { Observable, of, from } from '../rxjsStub.ts'; import {mergeMap, map} from '../rxjsStub.ts'; diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts index 46e4a78440..fe3712f412 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http.ts'; -import * as models from '../models/all.ts'; import { Configuration} from '../configuration.ts' import { ApiResponse } from '../models/ApiResponse.ts'; diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts index cb12d2bdd8..93928166fc 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import * as FormData from "form-data"; diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts index b3273a793f..8c67bb3abe 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import * as FormData from "form-data"; diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts index 71c9ce26b5..9f81f5e77f 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import * as FormData from "form-data"; diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/models/ObjectSerializer.ts index 6c5432f558..a5f5708b12 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/models/ObjectSerializer.ts @@ -1,16 +1,16 @@ -export * from './ApiResponse'; -export * from './Category'; -export * from './Order'; -export * from './Pet'; -export * from './Tag'; -export * from './User'; +export * from '../models/ApiResponse'; +export * from '../models/Category'; +export * from '../models/Order'; +export * from '../models/Pet'; +export * from '../models/Tag'; +export * from '../models/User'; -import { ApiResponse } from './ApiResponse'; -import { Category } from './Category'; -import { Order , OrderStatusEnum } from './Order'; -import { Pet , PetStatusEnum } from './Pet'; -import { Tag } from './Tag'; -import { User } from './User'; +import { ApiResponse } from '../models/ApiResponse'; +import { Category } from '../models/Category'; +import { Order , OrderStatusEnum } from '../models/Order'; +import { Pet , PetStatusEnum } from '../models/Pet'; +import { Tag } from '../models/Tag'; +import { User } from '../models/User'; /* tslint:disable:no-unused-variable */ let primitives = [ @@ -233,6 +233,10 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } + if (mediaType === "text/plain") { + return rawData; + } + if (mediaType === "application/json") { return JSON.parse(rawData); } diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/models/Pet.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/models/Pet.ts index 6b191ad8d7..b3a7ddb9f7 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/models/Pet.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/models/Pet.ts @@ -10,8 +10,8 @@ * Do not edit the class manually. */ -import { Category } from './Category'; -import { Tag } from './Tag'; +import { Category } from '../models/Category'; +import { Tag } from '../models/Tag'; import { HttpFile } from '../http/http'; /** diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/models/all.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/models/all.ts index 2edba7f0bd..d63b43c967 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/models/all.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/models/all.ts @@ -1,6 +1,6 @@ -export * from './ApiResponse' -export * from './Category' -export * from './Order' -export * from './Pet' -export * from './Tag' -export * from './User' +export * from '../models/ApiResponse' +export * from '../models/Category' +export * from '../models/Order' +export * from '../models/Pet' +export * from '../models/Tag' +export * from '../models/User' diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObjectParamAPI.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObjectParamAPI.ts index bad3c9fc25..acc26d9ef9 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObjectParamAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObjectParamAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { ApiResponse } from '../models/ApiResponse'; diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts index 678d21b81a..ac5eeb4ce5 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Observable, of, from } from '../rxjsStub'; import {mergeMap, map} from '../rxjsStub'; diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts index 072f187628..cf94fea92a 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { injectable, inject, optional } from "inversify"; import { AbstractConfiguration } from "../services/configuration"; diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts index 273352e4f6..514291812d 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import {ObjectSerializer} from '../models/ObjectSerializer'; diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts index 1eead29227..c60c1d8708 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import {ObjectSerializer} from '../models/ObjectSerializer'; diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts index 9784393c7a..0331c7117d 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import {ObjectSerializer} from '../models/ObjectSerializer'; diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/models/ObjectSerializer.ts index 6c5432f558..a5f5708b12 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/models/ObjectSerializer.ts @@ -1,16 +1,16 @@ -export * from './ApiResponse'; -export * from './Category'; -export * from './Order'; -export * from './Pet'; -export * from './Tag'; -export * from './User'; +export * from '../models/ApiResponse'; +export * from '../models/Category'; +export * from '../models/Order'; +export * from '../models/Pet'; +export * from '../models/Tag'; +export * from '../models/User'; -import { ApiResponse } from './ApiResponse'; -import { Category } from './Category'; -import { Order , OrderStatusEnum } from './Order'; -import { Pet , PetStatusEnum } from './Pet'; -import { Tag } from './Tag'; -import { User } from './User'; +import { ApiResponse } from '../models/ApiResponse'; +import { Category } from '../models/Category'; +import { Order , OrderStatusEnum } from '../models/Order'; +import { Pet , PetStatusEnum } from '../models/Pet'; +import { Tag } from '../models/Tag'; +import { User } from '../models/User'; /* tslint:disable:no-unused-variable */ let primitives = [ @@ -233,6 +233,10 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } + if (mediaType === "text/plain") { + return rawData; + } + if (mediaType === "application/json") { return JSON.parse(rawData); } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/models/Pet.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/models/Pet.ts index 6b191ad8d7..b3a7ddb9f7 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/models/Pet.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/models/Pet.ts @@ -10,8 +10,8 @@ * Do not edit the class manually. */ -import { Category } from './Category'; -import { Tag } from './Tag'; +import { Category } from '../models/Category'; +import { Tag } from '../models/Tag'; import { HttpFile } from '../http/http'; /** diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/models/all.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/models/all.ts index 2edba7f0bd..d63b43c967 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/models/all.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/models/all.ts @@ -1,6 +1,6 @@ -export * from './ApiResponse' -export * from './Category' -export * from './Order' -export * from './Pet' -export * from './Tag' -export * from './User' +export * from '../models/ApiResponse' +export * from '../models/Category' +export * from '../models/Order' +export * from '../models/Pet' +export * from '../models/Tag' +export * from '../models/User' diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObjectParamAPI.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObjectParamAPI.ts index bad3c9fc25..acc26d9ef9 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObjectParamAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObjectParamAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { ApiResponse } from '../models/ApiResponse'; diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts index 74f57a7e1c..b5b9a542b2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Observable, of, from } from '../rxjsStub'; import {mergeMap, map} from '../rxjsStub'; diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts index 92d57b673d..7279c47feb 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { ApiResponse } from '../models/ApiResponse'; diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts index 3dec522f6e..5b3d37fe35 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import * as FormData from "form-data"; diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts index e26ee9a00b..2682c0fc70 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import * as FormData from "form-data"; diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts index ede979aad4..352b499b37 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts @@ -1,5 +1,5 @@ // TODO: better import syntax? -import {BaseAPIRequestFactory, RequiredError} from './baseapi'; +import {BaseAPIRequestFactory, RequiredError, COLLECTION_FORMATS} from './baseapi'; import {Configuration} from '../configuration'; import {RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http'; import * as FormData from "form-data"; diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/models/ObjectSerializer.ts index 6c5432f558..a5f5708b12 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/models/ObjectSerializer.ts @@ -1,16 +1,16 @@ -export * from './ApiResponse'; -export * from './Category'; -export * from './Order'; -export * from './Pet'; -export * from './Tag'; -export * from './User'; +export * from '../models/ApiResponse'; +export * from '../models/Category'; +export * from '../models/Order'; +export * from '../models/Pet'; +export * from '../models/Tag'; +export * from '../models/User'; -import { ApiResponse } from './ApiResponse'; -import { Category } from './Category'; -import { Order , OrderStatusEnum } from './Order'; -import { Pet , PetStatusEnum } from './Pet'; -import { Tag } from './Tag'; -import { User } from './User'; +import { ApiResponse } from '../models/ApiResponse'; +import { Category } from '../models/Category'; +import { Order , OrderStatusEnum } from '../models/Order'; +import { Pet , PetStatusEnum } from '../models/Pet'; +import { Tag } from '../models/Tag'; +import { User } from '../models/User'; /* tslint:disable:no-unused-variable */ let primitives = [ @@ -233,6 +233,10 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } + if (mediaType === "text/plain") { + return rawData; + } + if (mediaType === "application/json") { return JSON.parse(rawData); } diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/models/Pet.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/models/Pet.ts index 6b191ad8d7..b3a7ddb9f7 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/models/Pet.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/models/Pet.ts @@ -10,8 +10,8 @@ * Do not edit the class manually. */ -import { Category } from './Category'; -import { Tag } from './Tag'; +import { Category } from '../models/Category'; +import { Tag } from '../models/Tag'; import { HttpFile } from '../http/http'; /** diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/models/all.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/models/all.ts index 2edba7f0bd..d63b43c967 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/models/all.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/models/all.ts @@ -1,6 +1,6 @@ -export * from './ApiResponse' -export * from './Category' -export * from './Order' -export * from './Pet' -export * from './Tag' -export * from './User' +export * from '../models/ApiResponse' +export * from '../models/Category' +export * from '../models/Order' +export * from '../models/Pet' +export * from '../models/Tag' +export * from '../models/User' diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObjectParamAPI.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObjectParamAPI.ts index bad3c9fc25..acc26d9ef9 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObjectParamAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObjectParamAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { ApiResponse } from '../models/ApiResponse'; diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts index 74f57a7e1c..b5b9a542b2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { Observable, of, from } from '../rxjsStub'; import {mergeMap, map} from '../rxjsStub'; diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts index 92d57b673d..7279c47feb 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts @@ -1,5 +1,4 @@ import { ResponseContext, RequestContext, HttpFile } from '../http/http'; -import * as models from '../models/all'; import { Configuration} from '../configuration' import { ApiResponse } from '../models/ApiResponse'; diff --git a/samples/openapi3/client/petstore/typescript/tests/default/package-lock.json b/samples/openapi3/client/petstore/typescript/tests/default/package-lock.json index b50025343d..65c4cf4138 100644 --- a/samples/openapi3/client/petstore/typescript/tests/default/package-lock.json +++ b/samples/openapi3/client/petstore/typescript/tests/default/package-lock.json @@ -40,7 +40,8 @@ "url-parse": "^1.4.3" }, "devDependencies": { - "typescript": "^3.9.3" + "@types/url-parse": "1.4.4", + "typescript": "^4.0" } }, "../../builds/default/node_modules/@types/node": { @@ -3235,11 +3236,12 @@ "requires": { "@types/node": "*", "@types/node-fetch": "^2.5.7", + "@types/url-parse": "1.4.4", "btoa": "^1.2.1", "es6-promise": "^4.2.4", "form-data": "^2.5.0", "node-fetch": "^2.6.0", - "typescript": "^3.9.3", + "typescript": "^4.0", "url-parse": "^1.4.3" }, "dependencies": { diff --git a/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/FILES b/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/FILES index efd990ad5b..fbc216c52a 100644 --- a/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/FILES +++ b/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/FILES @@ -1,4 +1,5 @@ ApiResponse.avsc +ApiResponseStatuses.avsc Category.avsc Order.avsc Pet.avsc diff --git a/samples/openapi3/schema/petstore/avro-schema/ApiResponse.avsc b/samples/openapi3/schema/petstore/avro-schema/ApiResponse.avsc index f105b1688d..c144fbdf28 100644 --- a/samples/openapi3/schema/petstore/avro-schema/ApiResponse.avsc +++ b/samples/openapi3/schema/petstore/avro-schema/ApiResponse.avsc @@ -21,6 +21,15 @@ "type": ["null", "string"], "doc": "", "default": null + }, + { + "name": "statuses", + "type": ["null", { + "type": "array", + "items": "model.ApiResponseStatuses" + }], + "doc": "", + "default": null } ] diff --git a/samples/openapi3/schema/petstore/avro-schema/ApiResponseStatuses.avsc b/samples/openapi3/schema/petstore/avro-schema/ApiResponseStatuses.avsc new file mode 100644 index 0000000000..e531d2b7cc --- /dev/null +++ b/samples/openapi3/schema/petstore/avro-schema/ApiResponseStatuses.avsc @@ -0,0 +1,11 @@ +{ + "namespace": "model", + "type": "enum", + "doc": "", + "name": "ApiResponseStatuses", + "symbols": [ + "success", + "failure", + "timeout" + ] +} diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApi.java b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApi.java index 17ca843531..9d41df1bb2 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApi.java +++ b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "bar", description = "the bar API") +@RequestMapping("${openapi.byRefOrValue.base-path:}") public interface BarApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApiController.java b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApiController.java index 7d23950718..4ff7051020 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApiController.java +++ b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.byRefOrValue.base-path:}") public class BarApiController implements BarApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApi.java b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApi.java index 80aff4f6a7..c1d9f22089 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApi.java +++ b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "foo", description = "the foo API") +@RequestMapping("${openapi.byRefOrValue.base-path:}") public interface FooApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApiController.java b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApiController.java index ea240bf97a..c5a099e7ae 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApiController.java +++ b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.byRefOrValue.base-path:}") public class FooApiController implements FooApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApi.java index 07f39f7abd..0130bbad04 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApiController.java b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApiController.java index b8fa3720a2..7713fe93c4 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApi.java index 3bf89c773c..88951e7399 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApiController.java b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApi.java index 5b1ad253f9..9465bc34e6 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApiController.java b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApi.java index 6463ce41b7..81b9b0ecfb 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApi.java @@ -33,6 +33,7 @@ import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApiController.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApiController.java index 1197295026..d12543b50f 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApiController.java @@ -29,7 +29,6 @@ import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApi.java index a0f0c70e27..2ff2f0b1fc 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApiController.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApiController.java index eaca23c3f8..da7fe83d44 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApi.java index cc9ff9b125..873751586f 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApiController.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApiController.java index 412a400d7d..a2e3c11d32 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import jakarta.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java index ced688a863..13cdf5e54e 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java index b2bd35b022..573b975cd2 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java @@ -42,6 +42,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { @@ -425,7 +426,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @Parameter(name = "required_string_group", description = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @Parameter(name = "required_int64_group", description = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @Parameter(name = "string_group", description = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @Parameter(name = "boolean_group", description = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApiController.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 0c5f22785f..96d8349102 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java index f8720a1814..8a5c836d42 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApiController.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApiController.java index ea6c56e02c..0b88e5980b 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java index ffe97ea0eb..750543b82c 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApiController.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java index d2a33639f3..c34bec3b1c 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApiController.java b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml +++ b/samples/openapi3/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java index ed3d95585a..cb308f4cdb 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -28,6 +28,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default AnotherFakeApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java index e27e2fc20e..7c3f204924 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final AnotherFakeApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java index 2baad94231..6b815c9bfc 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java @@ -38,6 +38,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default FakeApiDelegate getDelegate() { @@ -393,7 +394,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @Parameter(name = "required_string_group", description = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @Parameter(name = "required_int64_group", description = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @Parameter(name = "string_group", description = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @Parameter(name = "boolean_group", description = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java index 726b17779f..8e624ba5fb 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java @@ -37,7 +37,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final FakeApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index b712882bac..dfbb7687dd 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -28,6 +28,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default FakeClassnameTestApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 21e28fe8b2..48a276daf1 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final FakeClassnameTestApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java index ed88936ea3..7ef2dd5fcf 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java @@ -30,6 +30,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default PetApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java index 5ef3de965f..e27c4c3b49 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final PetApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java index 588d52ef3b..a1eca61927 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java @@ -29,6 +29,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default StoreApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java index e9e29a41b4..8c3b33a99a 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final StoreApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java index fa2f7281ce..58e2562b66 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java @@ -30,6 +30,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default UserApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java index 1b48d4a944..58511a0729 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final UserApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/resources/openapi.yaml b/samples/openapi3/server/petstore/springboot-delegate/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/resources/openapi.yaml +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java index ced688a863..13cdf5e54e 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java index 4afd858442..314b96db94 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java @@ -42,6 +42,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApiController.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 0c5f22785f..96d8349102 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java index 677cfcba58..599ca55492 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApiController.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApiController.java index ea6c56e02c..0b88e5980b 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java index ffe97ea0eb..750543b82c 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApiController.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java index d2a33639f3..c34bec3b1c 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApiController.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java index 187b3bc41c..3f65a9859d 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default AnotherFakeApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApiController.java index e27e2fc20e..7c3f204924 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final AnotherFakeApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java index ada108d128..3f4b552493 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java @@ -42,6 +42,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default FakeApiDelegate getDelegate() { @@ -407,7 +408,7 @@ public interface FakeApi { ) default Mono> testGroupParameters( @NotNull @Parameter(name = "required_string_group", description = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @Parameter(name = "required_int64_group", description = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @Parameter(name = "string_group", description = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @Parameter(name = "boolean_group", description = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApiController.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApiController.java index 726b17779f..8e624ba5fb 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApiController.java @@ -37,7 +37,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final FakeApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index e5180902d6..4f225a27b8 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default FakeClassnameTestApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 21e28fe8b2..48a276daf1 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final FakeClassnameTestApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java index 01711dee68..09c7761402 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default PetApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApiController.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApiController.java index 5ef3de965f..e27c4c3b49 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final PetApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java index be58c78d1c..bd63ade03b 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default StoreApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApiController.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApiController.java index e9e29a41b4..8c3b33a99a 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final StoreApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java index 85e52c9e7b..a83a2df75f 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default UserApiDelegate getDelegate() { diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApiController.java b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApiController.java index 1b48d4a944..58511a0729 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final UserApiDelegate delegate; diff --git a/samples/openapi3/server/petstore/springboot-reactive/src/main/resources/openapi.yaml b/samples/openapi3/server/petstore/springboot-reactive/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/openapi3/server/petstore/springboot-reactive/src/main/resources/openapi.yaml +++ b/samples/openapi3/server/petstore/springboot-reactive/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApi.java index 35a3367e3c..34840d57cd 100644 --- a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApi.java @@ -24,6 +24,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApiController.java b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApiController.java index b8fa3720a2..7713fe93c4 100644 --- a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApi.java index b468d0a875..b0e8d4a292 100644 --- a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApi.java @@ -24,6 +24,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApiController.java b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApi.java index dd4597eba3..81a6856aca 100644 --- a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApiController.java b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java index ced688a863..13cdf5e54e 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java index a7cc3cdfb2..c6d2e811f0 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java @@ -42,6 +42,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { @@ -425,7 +426,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @Parameter(name = "required_string_group", description = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @Parameter(name = "required_int64_group", description = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @Parameter(name = "string_group", description = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Optional stringGroup, @Parameter(name = "boolean_group", description = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Optional booleanGroup, diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApiController.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 0c5f22785f..96d8349102 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java index 9b50efad45..848e59d694 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApiController.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApiController.java index ea6c56e02c..0b88e5980b 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java index ffe97ea0eb..750543b82c 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApiController.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java index d2a33639f3..c34bec3b1c 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApiController.java b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml b/samples/openapi3/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/openapi3/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml +++ b/samples/openapi3/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java index 07f39f7abd..0130bbad04 100644 --- a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApiController.java b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApiController.java index b8fa3720a2..7713fe93c4 100644 --- a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java index 3bf89c773c..88951e7399 100644 --- a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApiController.java b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java index 5b1ad253f9..9465bc34e6 100644 --- a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApiController.java b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/aspnetcore-3.0/README.md b/samples/server/petstore/aspnetcore-3.0/README.md index ad46d4e125..833b9bec1a 100644 --- a/samples/server/petstore/aspnetcore-3.0/README.md +++ b/samples/server/petstore/aspnetcore-3.0/README.md @@ -2,6 +2,32 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + ## Run Linux/OS X: diff --git a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Controllers/StoreApi.cs b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Controllers/StoreApi.cs index 2077313f7d..31f24ebfc7 100644 --- a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Controllers/StoreApi.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Controllers var example = exampleJson != null ? JsonConvert.DeserializeObject>(exampleJson) - : default(Dictionary); + : new Dictionary(); //TODO: Change the data returned return new ObjectResult(example); } diff --git a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 41aaf28f1c..3ce9dfa571 100644 --- a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -1,23 +1,24 @@ - Org.OpenAPITools - Org.OpenAPITools + A library generated from a OpenAPI doc + No Copyright + OpenAPI netcoreapp3.0 true true 1.0.0 Org.OpenAPITools Org.OpenAPITools - 4bc22b76-ee61-45c3-aae6-47cee9badaa0 + 373fb14c-6113-4411-a2fa-5c83ae6fad14 Linux ..\.. - - - + + + diff --git a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Startup.cs b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Startup.cs index 70a6b10f05..ce27cdffd9 100644 --- a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Startup.cs +++ b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Startup.cs @@ -80,6 +80,8 @@ namespace Org.OpenAPITools services .AddSwaggerGen(c => { + c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true); + c.SwaggerDoc("1.0.0", new OpenApiInfo { Title = "OpenAPI Petstore", diff --git a/samples/server/petstore/aspnetcore-3.1/README.md b/samples/server/petstore/aspnetcore-3.1/README.md index 82fdf63ad6..cb9541519e 100644 --- a/samples/server/petstore/aspnetcore-3.1/README.md +++ b/samples/server/petstore/aspnetcore-3.1/README.md @@ -2,6 +2,32 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + ## Run Linux/OS X: diff --git a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Controllers/StoreApi.cs b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Controllers/StoreApi.cs index 2077313f7d..31f24ebfc7 100644 --- a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Controllers/StoreApi.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Controllers var example = exampleJson != null ? JsonConvert.DeserializeObject>(exampleJson) - : default(Dictionary); + : new Dictionary(); //TODO: Change the data returned return new ObjectResult(example); } diff --git a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Org.OpenAPITools.csproj index b366d93068..d59cbf3df7 100644 --- a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -1,23 +1,24 @@ - Org.OpenAPITools - Org.OpenAPITools + A library generated from a OpenAPI doc + No Copyright + OpenAPI netcoreapp3.1 true true 1.0.0 Org.OpenAPITools Org.OpenAPITools - 4ddd97dd-77ed-459e-8cd0-dcb2f9e59a70 + 76e9e993-9159-441c-9c5b-fe95e7f4f020 Linux ..\.. - - - + + + diff --git a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Startup.cs b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Startup.cs index d3f0be5bc6..0b156ec434 100644 --- a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Startup.cs +++ b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Startup.cs @@ -80,6 +80,8 @@ namespace Org.OpenAPITools services .AddSwaggerGen(c => { + c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true); + c.SwaggerDoc("1.0.0", new OpenApiInfo { Title = "OpenAPI Petstore", diff --git a/samples/server/petstore/aspnetcore-5.0/README.md b/samples/server/petstore/aspnetcore-5.0/README.md index ca9b3a2e50..be1e97e065 100644 --- a/samples/server/petstore/aspnetcore-5.0/README.md +++ b/samples/server/petstore/aspnetcore-5.0/README.md @@ -2,6 +2,32 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + ## Run Linux/OS X: diff --git a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Controllers/StoreApi.cs b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Controllers/StoreApi.cs index 2077313f7d..31f24ebfc7 100644 --- a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Controllers/StoreApi.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Controllers var example = exampleJson != null ? JsonConvert.DeserializeObject>(exampleJson) - : default(Dictionary); + : new Dictionary(); //TODO: Change the data returned return new ObjectResult(example); } diff --git a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 18d7e89c40..10711ffcf6 100644 --- a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -12,12 +12,13 @@ Linux ..\.. + - + - - - + + + diff --git a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Startup.cs b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Startup.cs index 20cb5b5a94..014f5ef7a1 100644 --- a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Startup.cs +++ b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Startup.cs @@ -80,6 +80,8 @@ namespace Org.OpenAPITools services .AddSwaggerGen(c => { + c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true); + c.SwaggerDoc("1.0.0", new OpenApiInfo { Title = "OpenAPI Petstore", diff --git a/samples/server/petstore/aspnetcore-6.0-pocoModels/README.md b/samples/server/petstore/aspnetcore-6.0-pocoModels/README.md index ef01f590df..34e589967c 100644 --- a/samples/server/petstore/aspnetcore-6.0-pocoModels/README.md +++ b/samples/server/petstore/aspnetcore-6.0-pocoModels/README.md @@ -2,6 +2,32 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + ## Run Linux/OS X: diff --git a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Controllers/StoreApi.cs b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Controllers/StoreApi.cs index 2077313f7d..31f24ebfc7 100644 --- a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Controllers/StoreApi.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Controllers var example = exampleJson != null ? JsonConvert.DeserializeObject>(exampleJson) - : default(Dictionary); + : new Dictionary(); //TODO: Change the data returned return new ObjectResult(example); } diff --git a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 0aaa1b25a4..518a6425bc 100644 --- a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -16,9 +16,9 @@ - - - + + + diff --git a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Startup.cs b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Startup.cs index 5699f01516..aee0229fa2 100644 --- a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Startup.cs +++ b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Startup.cs @@ -80,6 +80,8 @@ namespace Org.OpenAPITools services .AddSwaggerGen(c => { + c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true); + c.SwaggerDoc("1.0.0", new OpenApiInfo { Title = "OpenAPI Petstore", diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator-ignore b/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/.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/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/FILES b/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/FILES new file mode 100644 index 0000000000..fe403832ad --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/FILES @@ -0,0 +1,33 @@ +Org.OpenAPITools.sln +README.md +build.bat +build.sh +src/Org.OpenAPITools.Models/ApiResponse.cs +src/Org.OpenAPITools.Models/Category.cs +src/Org.OpenAPITools.Models/Converters/CustomEnumConverter.cs +src/Org.OpenAPITools.Models/Order.cs +src/Org.OpenAPITools.Models/Org.OpenAPITools.Models.csproj +src/Org.OpenAPITools.Models/Pet.cs +src/Org.OpenAPITools.Models/Tag.cs +src/Org.OpenAPITools.Models/User.cs +src/Org.OpenAPITools/.gitignore +src/Org.OpenAPITools/Attributes/ValidateModelStateAttribute.cs +src/Org.OpenAPITools/Authentication/ApiAuthentication.cs +src/Org.OpenAPITools/Controllers/FakeApi.cs +src/Org.OpenAPITools/Controllers/PetApi.cs +src/Org.OpenAPITools/Controllers/StoreApi.cs +src/Org.OpenAPITools/Controllers/UserApi.cs +src/Org.OpenAPITools/Dockerfile +src/Org.OpenAPITools/Filters/BasePathFilter.cs +src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +src/Org.OpenAPITools/Formatters/InputFormatterStream.cs +src/Org.OpenAPITools/OpenApi/TypeExtensions.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/Program.cs +src/Org.OpenAPITools/Properties/launchSettings.json +src/Org.OpenAPITools/Startup.cs +src/Org.OpenAPITools/appsettings.Development.json +src/Org.OpenAPITools/appsettings.json +src/Org.OpenAPITools/wwwroot/README.md +src/Org.OpenAPITools/wwwroot/index.html +src/Org.OpenAPITools/wwwroot/openapi-original.json diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/Org.OpenAPITools.sln b/samples/server/petstore/aspnetcore-6.0-project4Models/Org.OpenAPITools.sln new file mode 100644 index 0000000000..d229ac688d --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/Org.OpenAPITools.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{3C799344-F285-4669-8FD5-7ED9B795D5C5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Models", "src\Org.OpenAPITools.Models\Org.OpenAPITools.Models.csproj", "{B8D18F25-F379-4B87-ACCC-F8A17E0AED38}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3C799344-F285-4669-8FD5-7ED9B795D5C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3C799344-F285-4669-8FD5-7ED9B795D5C5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3C799344-F285-4669-8FD5-7ED9B795D5C5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3C799344-F285-4669-8FD5-7ED9B795D5C5}.Release|Any CPU.Build.0 = Release|Any CPU + {B8D18F25-F379-4B87-ACCC-F8A17E0AED38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8D18F25-F379-4B87-ACCC-F8A17E0AED38}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8D18F25-F379-4B87-ACCC-F8A17E0AED38}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8D18F25-F379-4B87-ACCC-F8A17E0AED38}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/README.md b/samples/server/petstore/aspnetcore-6.0-project4Models/README.md new file mode 100644 index 0000000000..34e589967c --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/README.md @@ -0,0 +1,50 @@ +# Org.OpenAPITools - ASP.NET Core 6.0 Server + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + +## Run + +Linux/OS X: + +``` +sh build.sh +``` + +Windows: + +``` +build.bat +``` +## Run in Docker + +``` +cd src/Org.OpenAPITools +docker build -t org.openapitools . +docker run -p 5000:8080 org.openapitools +``` diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/build.bat b/samples/server/petstore/aspnetcore-6.0-project4Models/build.bat new file mode 100644 index 0000000000..cd65518e42 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/build.bat @@ -0,0 +1,9 @@ +:: Generated by: https://openapi-generator.tech +:: + +@echo off + +dotnet restore src\Org.OpenAPITools +dotnet build src\Org.OpenAPITools +echo Now, run the following to start the project: dotnet run -p src\Org.OpenAPITools\Org.OpenAPITools.csproj --launch-profile web. +echo. diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/build.sh b/samples/server/petstore/aspnetcore-6.0-project4Models/build.sh new file mode 100644 index 0000000000..afbeddb837 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/build.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# +# Generated by: https://openapi-generator.tech +# + +dotnet restore src/Org.OpenAPITools/ && \ + dotnet build src/Org.OpenAPITools/ && \ + echo "Now, run the following to start the project: dotnet run -p src/Org.OpenAPITools/Org.OpenAPITools.csproj --launch-profile web" diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/ApiResponse.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/ApiResponse.cs new file mode 100644 index 0000000000..7573feaf41 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/ApiResponse.cs @@ -0,0 +1,147 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Linq; +using System.Text; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Org.OpenAPITools.Converters; + +namespace Org.OpenAPITools.Models +{ + /// + /// Describes the result of uploading an image resource + /// + [DataContract] + public partial class ApiResponse : IEquatable + { + /// + /// Gets or Sets Code + /// + [DataMember(Name="code", EmitDefaultValue=true)] + public int Code { get; set; } + + /// + /// Gets or Sets Type + /// + [DataMember(Name="type", EmitDefaultValue=false)] + public string Type { get; set; } + + /// + /// Gets or Sets Message + /// + [DataMember(Name="message", EmitDefaultValue=false)] + public string Message { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ApiResponse {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + if (obj is null) return false; + if (ReferenceEquals(this, obj)) return true; + return obj.GetType() == GetType() && Equals((ApiResponse)obj); + } + + /// + /// Returns true if ApiResponse instances are equal + /// + /// Instance of ApiResponse to be compared + /// Boolean + public bool Equals(ApiResponse other) + { + if (other is null) return false; + if (ReferenceEquals(this, other)) return true; + + return + ( + Code == other.Code || + + Code.Equals(other.Code) + ) && + ( + Type == other.Type || + Type != null && + Type.Equals(other.Type) + ) && + ( + Message == other.Message || + Message != null && + Message.Equals(other.Message) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + var hashCode = 41; + // Suitable nullity checks etc, of course :) + + hashCode = hashCode * 59 + Code.GetHashCode(); + if (Type != null) + hashCode = hashCode * 59 + Type.GetHashCode(); + if (Message != null) + hashCode = hashCode * 59 + Message.GetHashCode(); + return hashCode; + } + } + + #region Operators + #pragma warning disable 1591 + + public static bool operator ==(ApiResponse left, ApiResponse right) + { + return Equals(left, right); + } + + public static bool operator !=(ApiResponse left, ApiResponse right) + { + return !Equals(left, right); + } + + #pragma warning restore 1591 + #endregion Operators + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Category.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Category.cs new file mode 100644 index 0000000000..0d63dc9d7e --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Category.cs @@ -0,0 +1,134 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Linq; +using System.Text; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Org.OpenAPITools.Converters; + +namespace Org.OpenAPITools.Models +{ + /// + /// A category for a pet + /// + [DataContract] + public partial class Category : IEquatable + { + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=true)] + public long Id { get; set; } + + /// + /// Gets or Sets Name + /// + [RegularExpression("^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")] + [DataMember(Name="name", EmitDefaultValue=false)] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Category {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + if (obj is null) return false; + if (ReferenceEquals(this, obj)) return true; + return obj.GetType() == GetType() && Equals((Category)obj); + } + + /// + /// Returns true if Category instances are equal + /// + /// Instance of Category to be compared + /// Boolean + public bool Equals(Category other) + { + if (other is null) return false; + if (ReferenceEquals(this, other)) return true; + + return + ( + Id == other.Id || + + Id.Equals(other.Id) + ) && + ( + Name == other.Name || + Name != null && + Name.Equals(other.Name) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + var hashCode = 41; + // Suitable nullity checks etc, of course :) + + hashCode = hashCode * 59 + Id.GetHashCode(); + if (Name != null) + hashCode = hashCode * 59 + Name.GetHashCode(); + return hashCode; + } + } + + #region Operators + #pragma warning disable 1591 + + public static bool operator ==(Category left, Category right) + { + return Equals(left, right); + } + + public static bool operator !=(Category left, Category right) + { + return !Equals(left, right); + } + + #pragma warning restore 1591 + #endregion Operators + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Converters/CustomEnumConverter.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Converters/CustomEnumConverter.cs new file mode 100644 index 0000000000..00b75a3cc7 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Converters/CustomEnumConverter.cs @@ -0,0 +1,42 @@ +using System; +using System.ComponentModel; +using System.Globalization; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Converters +{ + /// + /// Custom string to enum converter + /// + public class CustomEnumConverter : TypeConverter + { + /// + /// Determine if we can convert a type to an enum + /// + /// + /// + /// + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); + } + + /// + /// Convert from a type value to an enum + /// + /// + /// + /// + /// + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + var s = value as string; + if (string.IsNullOrEmpty(s)) + { + return null; + } + + return JsonConvert.DeserializeObject(@"""" + value.ToString() + @""""); + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Order.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Order.cs new file mode 100644 index 0000000000..1d97257926 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Order.cs @@ -0,0 +1,219 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Linq; +using System.Text; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Org.OpenAPITools.Converters; + +namespace Org.OpenAPITools.Models +{ + /// + /// An order for a pets from the pet store + /// + [DataContract] + public partial class Order : IEquatable + { + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=true)] + public long Id { get; set; } + + /// + /// Gets or Sets PetId + /// + [DataMember(Name="petId", EmitDefaultValue=true)] + public long PetId { get; set; } + + /// + /// Gets or Sets Quantity + /// + [DataMember(Name="quantity", EmitDefaultValue=true)] + public int Quantity { get; set; } + + /// + /// Gets or Sets ShipDate + /// + [DataMember(Name="shipDate", EmitDefaultValue=false)] + public DateTime ShipDate { get; set; } + + + /// + /// Order Status + /// + /// Order Status + [TypeConverter(typeof(CustomEnumConverter))] + [JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public enum StatusEnum + { + + /// + /// Enum PlacedEnum for placed + /// + [EnumMember(Value = "placed")] + PlacedEnum = 1, + + /// + /// Enum ApprovedEnum for approved + /// + [EnumMember(Value = "approved")] + ApprovedEnum = 2, + + /// + /// Enum DeliveredEnum for delivered + /// + [EnumMember(Value = "delivered")] + DeliveredEnum = 3 + } + + /// + /// Order Status + /// + /// Order Status + [DataMember(Name="status", EmitDefaultValue=true)] + public StatusEnum Status { get; set; } + + /// + /// Gets or Sets Complete + /// + [DataMember(Name="complete", EmitDefaultValue=true)] + public bool Complete { get; set; } = false; + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Order {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PetId: ").Append(PetId).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + if (obj is null) return false; + if (ReferenceEquals(this, obj)) return true; + return obj.GetType() == GetType() && Equals((Order)obj); + } + + /// + /// Returns true if Order instances are equal + /// + /// Instance of Order to be compared + /// Boolean + public bool Equals(Order other) + { + if (other is null) return false; + if (ReferenceEquals(this, other)) return true; + + return + ( + Id == other.Id || + + Id.Equals(other.Id) + ) && + ( + PetId == other.PetId || + + PetId.Equals(other.PetId) + ) && + ( + Quantity == other.Quantity || + + Quantity.Equals(other.Quantity) + ) && + ( + ShipDate == other.ShipDate || + ShipDate != null && + ShipDate.Equals(other.ShipDate) + ) && + ( + Status == other.Status || + + Status.Equals(other.Status) + ) && + ( + Complete == other.Complete || + + Complete.Equals(other.Complete) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + var hashCode = 41; + // Suitable nullity checks etc, of course :) + + hashCode = hashCode * 59 + Id.GetHashCode(); + + hashCode = hashCode * 59 + PetId.GetHashCode(); + + hashCode = hashCode * 59 + Quantity.GetHashCode(); + if (ShipDate != null) + hashCode = hashCode * 59 + ShipDate.GetHashCode(); + + hashCode = hashCode * 59 + Status.GetHashCode(); + + hashCode = hashCode * 59 + Complete.GetHashCode(); + return hashCode; + } + } + + #region Operators + #pragma warning disable 1591 + + public static bool operator ==(Order left, Order right) + { + return Equals(left, right); + } + + public static bool operator !=(Order left, Order right) + { + return !Equals(left, right); + } + + #pragma warning restore 1591 + #endregion Operators + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Org.OpenAPITools.Models.csproj b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Org.OpenAPITools.Models.csproj new file mode 100644 index 0000000000..1cb3ba3660 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Org.OpenAPITools.Models.csproj @@ -0,0 +1,23 @@ + + + A library generated from a OpenAPI doc + No Copyright + OpenAPI + net6.0 + true + true + 1.0.0 + Library + Org.OpenAPITools.Models + Org.OpenAPITools.Models + + + + + + + + + + + diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Pet.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Pet.cs new file mode 100644 index 0000000000..762279e4d6 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Pet.cs @@ -0,0 +1,223 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Linq; +using System.Text; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Org.OpenAPITools.Converters; + +namespace Org.OpenAPITools.Models +{ + /// + /// A pet for sale in the pet store + /// + [DataContract] + public partial class Pet : IEquatable + { + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=true)] + public long Id { get; set; } + + /// + /// Gets or Sets Category + /// + [DataMember(Name="category", EmitDefaultValue=false)] + public Category Category { get; set; } + + /// + /// Gets or Sets Name + /// + [Required] + [DataMember(Name="name", EmitDefaultValue=false)] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [Required] + [DataMember(Name="photoUrls", EmitDefaultValue=false)] + public List PhotoUrls { get; set; } + + /// + /// Gets or Sets Tags + /// + [DataMember(Name="tags", EmitDefaultValue=false)] + public List Tags { get; set; } + + + /// + /// pet status in the store + /// + /// pet status in the store + [TypeConverter(typeof(CustomEnumConverter))] + [JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public enum StatusEnum + { + + /// + /// Enum AvailableEnum for available + /// + [EnumMember(Value = "available")] + AvailableEnum = 1, + + /// + /// Enum PendingEnum for pending + /// + [EnumMember(Value = "pending")] + PendingEnum = 2, + + /// + /// Enum SoldEnum for sold + /// + [EnumMember(Value = "sold")] + SoldEnum = 3 + } + + /// + /// pet status in the store + /// + /// pet status in the store + [DataMember(Name="status", EmitDefaultValue=true)] + public StatusEnum Status { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Pet {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Tags: ").Append(Tags).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + if (obj is null) return false; + if (ReferenceEquals(this, obj)) return true; + return obj.GetType() == GetType() && Equals((Pet)obj); + } + + /// + /// Returns true if Pet instances are equal + /// + /// Instance of Pet to be compared + /// Boolean + public bool Equals(Pet other) + { + if (other is null) return false; + if (ReferenceEquals(this, other)) return true; + + return + ( + Id == other.Id || + + Id.Equals(other.Id) + ) && + ( + Category == other.Category || + Category != null && + Category.Equals(other.Category) + ) && + ( + Name == other.Name || + Name != null && + Name.Equals(other.Name) + ) && + ( + PhotoUrls == other.PhotoUrls || + PhotoUrls != null && + other.PhotoUrls != null && + PhotoUrls.SequenceEqual(other.PhotoUrls) + ) && + ( + Tags == other.Tags || + Tags != null && + other.Tags != null && + Tags.SequenceEqual(other.Tags) + ) && + ( + Status == other.Status || + + Status.Equals(other.Status) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + var hashCode = 41; + // Suitable nullity checks etc, of course :) + + hashCode = hashCode * 59 + Id.GetHashCode(); + if (Category != null) + hashCode = hashCode * 59 + Category.GetHashCode(); + if (Name != null) + hashCode = hashCode * 59 + Name.GetHashCode(); + if (PhotoUrls != null) + hashCode = hashCode * 59 + PhotoUrls.GetHashCode(); + if (Tags != null) + hashCode = hashCode * 59 + Tags.GetHashCode(); + + hashCode = hashCode * 59 + Status.GetHashCode(); + return hashCode; + } + } + + #region Operators + #pragma warning disable 1591 + + public static bool operator ==(Pet left, Pet right) + { + return Equals(left, right); + } + + public static bool operator !=(Pet left, Pet right) + { + return !Equals(left, right); + } + + #pragma warning restore 1591 + #endregion Operators + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Tag.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Tag.cs new file mode 100644 index 0000000000..5153ae0c4b --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/Tag.cs @@ -0,0 +1,133 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Linq; +using System.Text; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Org.OpenAPITools.Converters; + +namespace Org.OpenAPITools.Models +{ + /// + /// A tag for a pet + /// + [DataContract] + public partial class Tag : IEquatable + { + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=true)] + public long Id { get; set; } + + /// + /// Gets or Sets Name + /// + [DataMember(Name="name", EmitDefaultValue=false)] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Tag {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + if (obj is null) return false; + if (ReferenceEquals(this, obj)) return true; + return obj.GetType() == GetType() && Equals((Tag)obj); + } + + /// + /// Returns true if Tag instances are equal + /// + /// Instance of Tag to be compared + /// Boolean + public bool Equals(Tag other) + { + if (other is null) return false; + if (ReferenceEquals(this, other)) return true; + + return + ( + Id == other.Id || + + Id.Equals(other.Id) + ) && + ( + Name == other.Name || + Name != null && + Name.Equals(other.Name) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + var hashCode = 41; + // Suitable nullity checks etc, of course :) + + hashCode = hashCode * 59 + Id.GetHashCode(); + if (Name != null) + hashCode = hashCode * 59 + Name.GetHashCode(); + return hashCode; + } + } + + #region Operators + #pragma warning disable 1591 + + public static bool operator ==(Tag left, Tag right) + { + return Equals(left, right); + } + + public static bool operator !=(Tag left, Tag right) + { + return !Equals(left, right); + } + + #pragma warning restore 1591 + #endregion Operators + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/User.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/User.cs new file mode 100644 index 0000000000..a64c031e61 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools.Models/User.cs @@ -0,0 +1,218 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Linq; +using System.Text; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Org.OpenAPITools.Converters; + +namespace Org.OpenAPITools.Models +{ + /// + /// A User who is purchasing from the pet store + /// + [DataContract] + public partial class User : IEquatable + { + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=true)] + public long Id { get; set; } + + /// + /// Gets or Sets Username + /// + [DataMember(Name="username", EmitDefaultValue=false)] + public string Username { get; set; } + + /// + /// Gets or Sets FirstName + /// + [DataMember(Name="firstName", EmitDefaultValue=false)] + public string FirstName { get; set; } + + /// + /// Gets or Sets LastName + /// + [DataMember(Name="lastName", EmitDefaultValue=false)] + public string LastName { get; set; } + + /// + /// Gets or Sets Email + /// + [DataMember(Name="email", EmitDefaultValue=false)] + public string Email { get; set; } + + /// + /// Gets or Sets Password + /// + [DataMember(Name="password", EmitDefaultValue=false)] + public string Password { get; set; } + + /// + /// Gets or Sets Phone + /// + [DataMember(Name="phone", EmitDefaultValue=false)] + public string Phone { get; set; } + + /// + /// User Status + /// + /// User Status + [DataMember(Name="userStatus", EmitDefaultValue=true)] + public int UserStatus { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class User {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + if (obj is null) return false; + if (ReferenceEquals(this, obj)) return true; + return obj.GetType() == GetType() && Equals((User)obj); + } + + /// + /// Returns true if User instances are equal + /// + /// Instance of User to be compared + /// Boolean + public bool Equals(User other) + { + if (other is null) return false; + if (ReferenceEquals(this, other)) return true; + + return + ( + Id == other.Id || + + Id.Equals(other.Id) + ) && + ( + Username == other.Username || + Username != null && + Username.Equals(other.Username) + ) && + ( + FirstName == other.FirstName || + FirstName != null && + FirstName.Equals(other.FirstName) + ) && + ( + LastName == other.LastName || + LastName != null && + LastName.Equals(other.LastName) + ) && + ( + Email == other.Email || + Email != null && + Email.Equals(other.Email) + ) && + ( + Password == other.Password || + Password != null && + Password.Equals(other.Password) + ) && + ( + Phone == other.Phone || + Phone != null && + Phone.Equals(other.Phone) + ) && + ( + UserStatus == other.UserStatus || + + UserStatus.Equals(other.UserStatus) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + var hashCode = 41; + // Suitable nullity checks etc, of course :) + + hashCode = hashCode * 59 + Id.GetHashCode(); + if (Username != null) + hashCode = hashCode * 59 + Username.GetHashCode(); + if (FirstName != null) + hashCode = hashCode * 59 + FirstName.GetHashCode(); + if (LastName != null) + hashCode = hashCode * 59 + LastName.GetHashCode(); + if (Email != null) + hashCode = hashCode * 59 + Email.GetHashCode(); + if (Password != null) + hashCode = hashCode * 59 + Password.GetHashCode(); + if (Phone != null) + hashCode = hashCode * 59 + Phone.GetHashCode(); + + hashCode = hashCode * 59 + UserStatus.GetHashCode(); + return hashCode; + } + } + + #region Operators + #pragma warning disable 1591 + + public static bool operator ==(User left, User right) + { + return Equals(left, right); + } + + public static bool operator !=(User left, User right) + { + return !Equals(left, right); + } + + #pragma warning restore 1591 + #endregion Operators + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/.gitignore b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/.gitignore new file mode 100644 index 0000000000..1ee53850b8 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Attributes/ValidateModelStateAttribute.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Attributes/ValidateModelStateAttribute.cs new file mode 100644 index 0000000000..3ed1bc5b5a --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Attributes/ValidateModelStateAttribute.cs @@ -0,0 +1,61 @@ +using System.ComponentModel.DataAnnotations; +using System.Reflection; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ModelBinding; + +namespace Org.OpenAPITools.Attributes +{ + /// + /// Model state validation attribute + /// + public class ValidateModelStateAttribute : ActionFilterAttribute + { + /// + /// Called before the action method is invoked + /// + /// + public override void OnActionExecuting(ActionExecutingContext context) + { + // Per https://blog.markvincze.com/how-to-validate-action-parameters-with-dataannotation-attributes/ + var descriptor = context.ActionDescriptor as ControllerActionDescriptor; + if (descriptor != null) + { + foreach (var parameter in descriptor.MethodInfo.GetParameters()) + { + object args = null; + if (context.ActionArguments.ContainsKey(parameter.Name)) + { + args = context.ActionArguments[parameter.Name]; + } + + ValidateAttributes(parameter, args, context.ModelState); + } + } + + if (!context.ModelState.IsValid) + { + context.Result = new BadRequestObjectResult(context.ModelState); + } + } + + private void ValidateAttributes(ParameterInfo parameter, object args, ModelStateDictionary modelState) + { + foreach (var attributeData in parameter.CustomAttributes) + { + var attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType); + + var validationAttribute = attributeInstance as ValidationAttribute; + if (validationAttribute != null) + { + var isValid = validationAttribute.IsValid(args); + if (!isValid) + { + modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name)); + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Authentication/ApiAuthentication.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Authentication/ApiAuthentication.cs new file mode 100644 index 0000000000..85be8593fc --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Authentication/ApiAuthentication.cs @@ -0,0 +1,62 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace Org.OpenAPITools.Authentication +{ + /// + /// A requirement that an ApiKey must be present. + /// + public class ApiKeyRequirement : IAuthorizationRequirement + { + /// + /// Get the list of api keys + /// + public IReadOnlyList ApiKeys { get; } + + /// + /// Get the policy name, + /// + public string PolicyName { get; } + + /// + /// Create a new instance of the class. + /// + /// + /// + public ApiKeyRequirement(IEnumerable apiKeys, string policyName) + { + ApiKeys = apiKeys?.ToList() ?? new List(); + PolicyName = policyName; + } + } + + /// + /// Enforce that an api key is present. + /// + public class ApiKeyRequirementHandler : AuthorizationHandler + { + /// + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ApiKeyRequirement requirement) + { + SucceedRequirementIfApiKeyPresentAndValid(context, requirement); + return Task.CompletedTask; + } + + private void SucceedRequirementIfApiKeyPresentAndValid(AuthorizationHandlerContext context, ApiKeyRequirement requirement) + { + + if (context.Resource is AuthorizationFilterContext authorizationFilterContext) + { + var apiKey = authorizationFilterContext.HttpContext.Request.Headers["api_key"].FirstOrDefault(); + if (requirement.PolicyName == "api_key" && apiKey != null && requirement.ApiKeys.Any(requiredApiKey => apiKey == requiredApiKey)) + { + context.Succeed(requirement); + } + } + + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/FakeApi.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/FakeApi.cs new file mode 100644 index 0000000000..8e36c8d2be --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/FakeApi.cs @@ -0,0 +1,49 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Swashbuckle.AspNetCore.Annotations; +using Swashbuckle.AspNetCore.SwaggerGen; +using Newtonsoft.Json; +using Org.OpenAPITools.Attributes; +using Org.OpenAPITools.Models; + +namespace Org.OpenAPITools.Controllers +{ + /// + /// + /// + [ApiController] + public class FakeApiController : ControllerBase + { + /// + /// fake endpoint to test parameter example (object) + /// + /// + /// successful operation + [HttpGet] + [Route("/v2/fake/parameter_example_test")] + [ValidateModelState] + [SwaggerOperation("FakeParameterExampleTest")] + public virtual IActionResult FakeParameterExampleTest([FromQuery (Name = "data")][Required()]Pet data) + { + + //TODO: Uncomment the next line to return response 0 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(0); + + throw new NotImplementedException(); + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/PetApi.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/PetApi.cs new file mode 100644 index 0000000000..982c1a6011 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/PetApi.cs @@ -0,0 +1,260 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Swashbuckle.AspNetCore.Annotations; +using Swashbuckle.AspNetCore.SwaggerGen; +using Newtonsoft.Json; +using Org.OpenAPITools.Attributes; +using Org.OpenAPITools.Models; + +namespace Org.OpenAPITools.Controllers +{ + /// + /// + /// + [ApiController] + public class PetApiController : ControllerBase + { + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// successful operation + /// Invalid input + [HttpPost] + [Route("/v2/pet")] + [Consumes("application/json", "application/xml")] + [ValidateModelState] + [SwaggerOperation("AddPet")] + [SwaggerResponse(statusCode: 200, type: typeof(Pet), description: "successful operation")] + public virtual IActionResult AddPet([FromBody]Pet pet) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(Pet)); + //TODO: Uncomment the next line to return response 405 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(405); + string exampleJson = null; + exampleJson = "{\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}"; + exampleJson = "\n 123456789\n doggie\n \n aeiou\n \n \n \n aeiou\n"; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(Pet); + //TODO: Change the data returned + return new ObjectResult(example); + } + + /// + /// Deletes a pet + /// + /// Pet id to delete + /// + /// Invalid pet value + [HttpDelete] + [Route("/v2/pet/{petId}")] + [ValidateModelState] + [SwaggerOperation("DeletePet")] + public virtual IActionResult DeletePet([FromRoute (Name = "petId")][Required]long petId, [FromHeader]string apiKey) + { + + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + + throw new NotImplementedException(); + } + + /// + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma separated strings + /// Status values that need to be considered for filter (deprecated) + /// successful operation + /// Invalid status value + [HttpGet] + [Route("/v2/pet/findByStatus")] + [ValidateModelState] + [SwaggerOperation("FindPetsByStatus")] + [SwaggerResponse(statusCode: 200, type: typeof(List), description: "successful operation")] + public virtual IActionResult FindPetsByStatus([FromQuery (Name = "status")][Required()]List status) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(List)); + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + string exampleJson = null; + exampleJson = "{\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}"; + exampleJson = "\n 123456789\n doggie\n \n aeiou\n \n \n \n aeiou\n"; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject>(exampleJson) + : default(List); + //TODO: Change the data returned + return new ObjectResult(example); + } + + /// + /// Finds Pets by tags + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// Tags to filter by + /// successful operation + /// Invalid tag value + [HttpGet] + [Route("/v2/pet/findByTags")] + [ValidateModelState] + [SwaggerOperation("FindPetsByTags")] + [SwaggerResponse(statusCode: 200, type: typeof(List), description: "successful operation")] + [Obsolete] + public virtual IActionResult FindPetsByTags([FromQuery (Name = "tags")][Required()]List tags) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(List)); + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + string exampleJson = null; + exampleJson = "{\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}"; + exampleJson = "\n 123456789\n doggie\n \n aeiou\n \n \n \n aeiou\n"; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject>(exampleJson) + : default(List); + //TODO: Change the data returned + return new ObjectResult(example); + } + + /// + /// Find pet by ID + /// + /// Returns a single pet + /// ID of pet to return + /// successful operation + /// Invalid ID supplied + /// Pet not found + [HttpGet] + [Route("/v2/pet/{petId}")] + [Authorize(Policy = "api_key")] + [ValidateModelState] + [SwaggerOperation("GetPetById")] + [SwaggerResponse(statusCode: 200, type: typeof(Pet), description: "successful operation")] + public virtual IActionResult GetPetById([FromRoute (Name = "petId")][Required]long petId) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(Pet)); + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(404); + string exampleJson = null; + exampleJson = "{\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}"; + exampleJson = "\n 123456789\n doggie\n \n aeiou\n \n \n \n aeiou\n"; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(Pet); + //TODO: Change the data returned + return new ObjectResult(example); + } + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// successful operation + /// Invalid ID supplied + /// Pet not found + /// Validation exception + [HttpPut] + [Route("/v2/pet")] + [Consumes("application/json", "application/xml")] + [ValidateModelState] + [SwaggerOperation("UpdatePet")] + [SwaggerResponse(statusCode: 200, type: typeof(Pet), description: "successful operation")] + public virtual IActionResult UpdatePet([FromBody]Pet pet) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(Pet)); + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(404); + //TODO: Uncomment the next line to return response 405 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(405); + string exampleJson = null; + exampleJson = "{\n \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ],\n \"name\" : \"doggie\",\n \"id\" : 0,\n \"category\" : {\n \"name\" : \"name\",\n \"id\" : 6\n },\n \"tags\" : [ {\n \"name\" : \"name\",\n \"id\" : 1\n }, {\n \"name\" : \"name\",\n \"id\" : 1\n } ],\n \"status\" : \"available\"\n}"; + exampleJson = "\n 123456789\n doggie\n \n aeiou\n \n \n \n aeiou\n"; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(Pet); + //TODO: Change the data returned + return new ObjectResult(example); + } + + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated + /// Updated name of the pet + /// Updated status of the pet + /// Invalid input + [HttpPost] + [Route("/v2/pet/{petId}")] + [Consumes("application/x-www-form-urlencoded")] + [ValidateModelState] + [SwaggerOperation("UpdatePetWithForm")] + public virtual IActionResult UpdatePetWithForm([FromRoute (Name = "petId")][Required]long petId, [FromForm (Name = "name")]string name, [FromForm (Name = "status")]string status) + { + + //TODO: Uncomment the next line to return response 405 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(405); + + throw new NotImplementedException(); + } + + /// + /// uploads an image + /// + /// ID of pet to update + /// Additional data to pass to server + /// file to upload + /// successful operation + [HttpPost] + [Route("/v2/pet/{petId}/uploadImage")] + [Consumes("multipart/form-data")] + [ValidateModelState] + [SwaggerOperation("UploadFile")] + [SwaggerResponse(statusCode: 200, type: typeof(ApiResponse), description: "successful operation")] + public virtual IActionResult UploadFile([FromRoute (Name = "petId")][Required]long petId, [FromForm (Name = "additionalMetadata")]string additionalMetadata, IFormFile file) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(ApiResponse)); + string exampleJson = null; + exampleJson = "{\n \"code\" : 0,\n \"type\" : \"type\",\n \"message\" : \"message\"\n}"; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(ApiResponse); + //TODO: Change the data returned + return new ObjectResult(example); + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/StoreApi.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/StoreApi.cs new file mode 100644 index 0000000000..31f24ebfc7 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/StoreApi.cs @@ -0,0 +1,141 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Swashbuckle.AspNetCore.Annotations; +using Swashbuckle.AspNetCore.SwaggerGen; +using Newtonsoft.Json; +using Org.OpenAPITools.Attributes; +using Org.OpenAPITools.Models; + +namespace Org.OpenAPITools.Controllers +{ + /// + /// + /// + [ApiController] + public class StoreApiController : ControllerBase + { + /// + /// Delete purchase order by ID + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// ID of the order that needs to be deleted + /// Invalid ID supplied + /// Order not found + [HttpDelete] + [Route("/v2/store/order/{orderId}")] + [ValidateModelState] + [SwaggerOperation("DeleteOrder")] + public virtual IActionResult DeleteOrder([FromRoute (Name = "orderId")][Required]string orderId) + { + + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(404); + + throw new NotImplementedException(); + } + + /// + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + /// successful operation + [HttpGet] + [Route("/v2/store/inventory")] + [Authorize(Policy = "api_key")] + [ValidateModelState] + [SwaggerOperation("GetInventory")] + [SwaggerResponse(statusCode: 200, type: typeof(Dictionary), description: "successful operation")] + public virtual IActionResult GetInventory() + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(Dictionary)); + string exampleJson = null; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject>(exampleJson) + : new Dictionary(); + //TODO: Change the data returned + return new ObjectResult(example); + } + + /// + /// Find purchase order by ID + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// ID of pet that needs to be fetched + /// successful operation + /// Invalid ID supplied + /// Order not found + [HttpGet] + [Route("/v2/store/order/{orderId}")] + [ValidateModelState] + [SwaggerOperation("GetOrderById")] + [SwaggerResponse(statusCode: 200, type: typeof(Order), description: "successful operation")] + public virtual IActionResult GetOrderById([FromRoute (Name = "orderId")][Required][Range(1, 5)]long orderId) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(Order)); + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(404); + string exampleJson = null; + exampleJson = "{\n \"petId\" : 6,\n \"quantity\" : 1,\n \"id\" : 0,\n \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\",\n \"complete\" : false,\n \"status\" : \"placed\"\n}"; + exampleJson = "\n 123456789\n 123456789\n 123\n 2000-01-23T04:56:07.000Z\n aeiou\n true\n"; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(Order); + //TODO: Change the data returned + return new ObjectResult(example); + } + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// successful operation + /// Invalid Order + [HttpPost] + [Route("/v2/store/order")] + [Consumes("application/json")] + [ValidateModelState] + [SwaggerOperation("PlaceOrder")] + [SwaggerResponse(statusCode: 200, type: typeof(Order), description: "successful operation")] + public virtual IActionResult PlaceOrder([FromBody]Order order) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(Order)); + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + string exampleJson = null; + exampleJson = "{\n \"petId\" : 6,\n \"quantity\" : 1,\n \"id\" : 0,\n \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\",\n \"complete\" : false,\n \"status\" : \"placed\"\n}"; + exampleJson = "\n 123456789\n 123456789\n 123\n 2000-01-23T04:56:07.000Z\n aeiou\n true\n"; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(Order); + //TODO: Change the data returned + return new ObjectResult(example); + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/UserApi.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/UserApi.cs new file mode 100644 index 0000000000..6d7094c81a --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Controllers/UserApi.cs @@ -0,0 +1,218 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Swashbuckle.AspNetCore.Annotations; +using Swashbuckle.AspNetCore.SwaggerGen; +using Newtonsoft.Json; +using Org.OpenAPITools.Attributes; +using Org.OpenAPITools.Models; + +namespace Org.OpenAPITools.Controllers +{ + /// + /// + /// + [ApiController] + public class UserApiController : ControllerBase + { + /// + /// Create user + /// + /// This can only be done by the logged in user. + /// Created user object + /// successful operation + [HttpPost] + [Route("/v2/user")] + [Authorize(Policy = "api_key")] + [Consumes("application/json")] + [ValidateModelState] + [SwaggerOperation("CreateUser")] + public virtual IActionResult CreateUser([FromBody]User user) + { + + //TODO: Uncomment the next line to return response 0 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(0); + + throw new NotImplementedException(); + } + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// successful operation + [HttpPost] + [Route("/v2/user/createWithArray")] + [Authorize(Policy = "api_key")] + [Consumes("application/json")] + [ValidateModelState] + [SwaggerOperation("CreateUsersWithArrayInput")] + public virtual IActionResult CreateUsersWithArrayInput([FromBody]List user) + { + + //TODO: Uncomment the next line to return response 0 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(0); + + throw new NotImplementedException(); + } + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// successful operation + [HttpPost] + [Route("/v2/user/createWithList")] + [Authorize(Policy = "api_key")] + [Consumes("application/json")] + [ValidateModelState] + [SwaggerOperation("CreateUsersWithListInput")] + public virtual IActionResult CreateUsersWithListInput([FromBody]List user) + { + + //TODO: Uncomment the next line to return response 0 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(0); + + throw new NotImplementedException(); + } + + /// + /// Delete user + /// + /// This can only be done by the logged in user. + /// The name that needs to be deleted + /// Invalid username supplied + /// User not found + [HttpDelete] + [Route("/v2/user/{username}")] + [Authorize(Policy = "api_key")] + [ValidateModelState] + [SwaggerOperation("DeleteUser")] + public virtual IActionResult DeleteUser([FromRoute (Name = "username")][Required]string username) + { + + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(404); + + throw new NotImplementedException(); + } + + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + /// successful operation + /// Invalid username supplied + /// User not found + [HttpGet] + [Route("/v2/user/{username}")] + [ValidateModelState] + [SwaggerOperation("GetUserByName")] + [SwaggerResponse(statusCode: 200, type: typeof(User), description: "successful operation")] + public virtual IActionResult GetUserByName([FromRoute (Name = "username")][Required]string username) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(User)); + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(404); + string exampleJson = null; + exampleJson = "{\n \"firstName\" : \"firstName\",\n \"lastName\" : \"lastName\",\n \"password\" : \"password\",\n \"userStatus\" : 6,\n \"phone\" : \"phone\",\n \"id\" : 0,\n \"email\" : \"email\",\n \"username\" : \"username\"\n}"; + exampleJson = "\n 123456789\n aeiou\n aeiou\n aeiou\n aeiou\n aeiou\n aeiou\n 123\n"; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(User); + //TODO: Change the data returned + return new ObjectResult(example); + } + + /// + /// Logs user into the system + /// + /// The user name for login + /// The password for login in clear text + /// successful operation + /// Invalid username/password supplied + [HttpGet] + [Route("/v2/user/login")] + [ValidateModelState] + [SwaggerOperation("LoginUser")] + [SwaggerResponse(statusCode: 200, type: typeof(string), description: "successful operation")] + public virtual IActionResult LoginUser([FromQuery (Name = "username")][Required()][RegularExpression("^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$")]string username, [FromQuery (Name = "password")][Required()]string password) + { + + //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(200, default(string)); + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + string exampleJson = null; + + var example = exampleJson != null + ? JsonConvert.DeserializeObject(exampleJson) + : default(string); + //TODO: Change the data returned + return new ObjectResult(example); + } + + /// + /// Logs out current logged in user session + /// + /// successful operation + [HttpGet] + [Route("/v2/user/logout")] + [Authorize(Policy = "api_key")] + [ValidateModelState] + [SwaggerOperation("LogoutUser")] + public virtual IActionResult LogoutUser() + { + + //TODO: Uncomment the next line to return response 0 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(0); + + throw new NotImplementedException(); + } + + /// + /// Updated user + /// + /// This can only be done by the logged in user. + /// name that need to be deleted + /// Updated user object + /// Invalid user supplied + /// User not found + [HttpPut] + [Route("/v2/user/{username}")] + [Authorize(Policy = "api_key")] + [Consumes("application/json")] + [ValidateModelState] + [SwaggerOperation("UpdateUser")] + public virtual IActionResult UpdateUser([FromRoute (Name = "username")][Required]string username, [FromBody]User user) + { + + //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(400); + //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(404); + + throw new NotImplementedException(); + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Dockerfile b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Dockerfile new file mode 100644 index 0000000000..7184e1ece4 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Dockerfile @@ -0,0 +1,32 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +# Container we use for final publish +FROM mcr.microsoft.com/dotnet/core/aspnet:6.0-buster-slim AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +# Build container +FROM mcr.microsoft.com/dotnet/core/sdk:6.0-buster AS build + +# Copy the code into the container +WORKDIR /src +COPY ["src/Org.OpenAPITools/Org.OpenAPITools.csproj", "Org.OpenAPITools/"] + +# NuGet restore +RUN dotnet restore "Org.OpenAPITools/Org.OpenAPITools.csproj" +COPY ["src/Org.OpenAPITools/", "Org.OpenAPITools/"] + +# Build the API +WORKDIR "Org.OpenAPITools" +RUN dotnet build "Org.OpenAPITools.csproj" -c Release -o /app/build + +# Publish it +FROM build AS publish +RUN dotnet publish "Org.OpenAPITools.csproj" -c Release -o /app/publish + +# Make the final image for publishing +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Org.OpenAPITools.dll"] diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Filters/BasePathFilter.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Filters/BasePathFilter.cs new file mode 100644 index 0000000000..a238545107 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Filters/BasePathFilter.cs @@ -0,0 +1,50 @@ +using System.Linq; +using System.Text.RegularExpressions; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// BasePath Document Filter sets BasePath property of OpenAPI and removes it from the individual URL paths + /// + public class BasePathFilter : IDocumentFilter + { + /// + /// Constructor + /// + /// BasePath to remove from Operations + public BasePathFilter(string basePath) + { + BasePath = basePath; + } + + /// + /// Gets the BasePath of the OpenAPI Doc + /// + /// The BasePath of the OpenAPI Doc + public string BasePath { get; } + + /// + /// Apply the filter + /// + /// OpenApiDocument + /// FilterContext + public void Apply(OpenApiDocument openapiDoc, DocumentFilterContext context) + { + //openapiDoc.BasePath = BasePath; + + var pathsToModify = openapiDoc.Paths.Where(p => p.Key.StartsWith(BasePath)).ToList(); + + foreach (var (key, value) in pathsToModify) + { + if (key.StartsWith(BasePath)) + { + var newKey = Regex.Replace(key, $"^{BasePath}", string.Empty); + openapiDoc.Paths.Remove(key); + openapiDoc.Paths.Add(newKey, value); + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs new file mode 100644 index 0000000000..65d9d46952 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,97 @@ +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs new file mode 100644 index 0000000000..9c437b1919 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs @@ -0,0 +1,32 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.Formatters; + +namespace Org.OpenAPITools.Formatters +{ + // Input Type Formatter to allow model binding to Streams + public class InputFormatterStream : InputFormatter + { + public InputFormatterStream() + { + SupportedMediaTypes.Add("application/octet-stream"); + SupportedMediaTypes.Add("image/jpeg"); + } + + protected override bool CanReadType(Type type) + { + if (type == typeof(Stream)) + { + return true; + } + + return false; + } + + public override Task ReadRequestBodyAsync(InputFormatterContext context) + { + return InputFormatterResult.SuccessAsync(context.HttpContext.Request.Body); + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs new file mode 100644 index 0000000000..b862226f2c --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs @@ -0,0 +1,51 @@ +using System; +using System.Linq; +using System.Text; + +namespace Org.OpenAPITools.OpenApi +{ + /// + /// Replacement utilities from Swashbuckle.AspNetCore.SwaggerGen which are not in 5.x + /// + public static class TypeExtensions + { + /// + /// Produce a friendly name for the type which is unique. + /// + /// + /// + public static string FriendlyId(this Type type, bool fullyQualified = false) + { + var typeName = fullyQualified + ? type.FullNameSansTypeParameters().Replace("+", ".") + : type.Name; + + if (type.IsGenericType) + { + var genericArgumentIds = type.GetGenericArguments() + .Select(t => t.FriendlyId(fullyQualified)) + .ToArray(); + + return new StringBuilder(typeName) + .Replace($"`{genericArgumentIds.Count()}", string.Empty) + .Append($"[{string.Join(",", genericArgumentIds).TrimEnd(',')}]") + .ToString(); + } + + return typeName; + } + + /// + /// Determine the fully qualified type name without type parameters. + /// + /// + public static string FullNameSansTypeParameters(this Type type) + { + var fullName = type.FullName; + if (string.IsNullOrEmpty(fullName)) + fullName = type.Name; + var chopIndex = fullName.IndexOf("[[", StringComparison.Ordinal); + return (chopIndex == -1) ? fullName : fullName.Substring(0, chopIndex); + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 0000000000..00c6efccde --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,27 @@ + + + A library generated from a OpenAPI doc + No Copyright + OpenAPI + net6.0 + true + true + 1.0.0 + Org.OpenAPITools + Org.OpenAPITools + cb87e868-8646-48ef-9bb6-344b537d0d37 + Linux + ..\.. + + + + + + + + + + + + + diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs new file mode 100644 index 0000000000..00ed16ed67 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Properties/launchSettings.json b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Properties/launchSettings.json new file mode 100644 index 0000000000..99cfeea4b9 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Properties/launchSettings.json @@ -0,0 +1,37 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:61788", + "sslPort": 44301 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "openapi", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "OpenAPI": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "openapi", + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Docker": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/openapi", + "publishAllPorts": true, + "useSSL": true + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Startup.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Startup.cs new file mode 100644 index 0000000000..aee0229fa2 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Startup.cs @@ -0,0 +1,156 @@ +/* + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.IO; +using System.Reflection; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.OpenApi.Models; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Serialization; +using Org.OpenAPITools.Authentication; +using Org.OpenAPITools.Filters; +using Org.OpenAPITools.OpenApi; +using Org.OpenAPITools.Formatters; + +namespace Org.OpenAPITools +{ + /// + /// Startup + /// + public class Startup + { + /// + /// Constructor + /// + /// + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + /// + /// The application configuration. + /// + public IConfiguration Configuration { get; } + + /// + /// This method gets called by the runtime. Use this method to add services to the container. + /// + /// + public void ConfigureServices(IServiceCollection services) + { + services.AddTransient(); + services.AddAuthorization(authConfig => + { + authConfig.AddPolicy("api_key", policyBuilder => + { + policyBuilder + .AddRequirements(new ApiKeyRequirement(new[] { "my-secret-key" },"api_key")); + }); + }); + + // Add framework services. + services + // Don't need the full MVC stack for an API, see https://andrewlock.net/comparing-startup-between-the-asp-net-core-3-templates/ + .AddControllers(options => { + options.InputFormatters.Insert(0, new InputFormatterStream()); + }) + .AddNewtonsoftJson(opts => + { + opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); + opts.SerializerSettings.Converters.Add(new StringEnumConverter + { + NamingStrategy = new CamelCaseNamingStrategy() + }); + }); + + services + .AddSwaggerGen(c => + { + c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true); + + c.SwaggerDoc("1.0.0", new OpenApiInfo + { + Title = "OpenAPI Petstore", + Description = "OpenAPI Petstore (ASP.NET Core 6.0)", + TermsOfService = new Uri("https://github.com/openapitools/openapi-generator"), + Contact = new OpenApiContact + { + Name = "OpenAPI-Generator Contributors", + Url = new Uri("https://github.com/openapitools/openapi-generator"), + Email = "" + }, + License = new OpenApiLicense + { + Name = "NoLicense", + Url = new Uri("https://www.apache.org/licenses/LICENSE-2.0.html") + }, + Version = "1.0.0", + }); + c.CustomSchemaIds(type => type.FriendlyId(true)); + c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{Assembly.GetEntryAssembly().GetName().Name}.xml"); + // Sets the basePath property in the OpenAPI document generated + c.DocumentFilter("/v2"); + + // Include DataAnnotation attributes on Controller Action parameters as OpenAPI validation rules (e.g required, pattern, ..) + // Use [ValidateModelState] on Actions to actually validate it in C# as well! + c.OperationFilter(); + }); + services + .AddSwaggerGenNewtonsoftSupport(); + } + + /// + /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + /// + /// + /// + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseHsts(); + } + + app.UseHttpsRedirection(); + app.UseDefaultFiles(); + app.UseStaticFiles(); + app.UseSwagger(c => + { + c.RouteTemplate = "openapi/{documentName}/openapi.json"; + }) + .UseSwaggerUI(c => + { + // set route prefix to openapi, e.g. http://localhost:8080/openapi/index.html + c.RoutePrefix = "openapi"; + //TODO: Either use the SwaggerGen generated OpenAPI contract (generated from C# classes) + c.SwaggerEndpoint("/openapi/1.0.0/openapi.json", "OpenAPI Petstore"); + + //TODO: Or alternatively use the original OpenAPI contract that's included in the static files + // c.SwaggerEndpoint("/openapi-original.json", "OpenAPI Petstore Original"); + }); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/appsettings.Development.json b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/appsettings.Development.json new file mode 100644 index 0000000000..e203e9407e --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/appsettings.json new file mode 100644 index 0000000000..def9159a7d --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/README.md b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/README.md new file mode 100644 index 0000000000..6a0b78471a --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/README.md @@ -0,0 +1,42 @@ +# Welcome to ASP.NET 5 Preview + +We've made some big updates in this release, so it’s **important** that you spend a few minutes to learn what’s new. + +ASP.NET 5 has been rearchitected to make it **lean** and **composable**. It's fully **open source** and available on [GitHub](http://go.microsoft.com/fwlink/?LinkID=517854). +Your new project automatically takes advantage of modern client-side utilities like [Bower](http://go.microsoft.com/fwlink/?LinkId=518004) and [npm](http://go.microsoft.com/fwlink/?LinkId=518005) (to add client-side libraries) and [Gulp](http://go.microsoft.com/fwlink/?LinkId=518007) (for client-side build and automation tasks). + +We hope you enjoy the new capabilities in ASP.NET 5 and Visual Studio 2015. +The ASP.NET Team + +### You've created a new ASP.NET 5 project. [Learn what's new](http://go.microsoft.com/fwlink/?LinkId=518016) + +### This application consists of: +* Sample pages using ASP.NET MVC 6 +* [Gulp](http://go.microsoft.com/fwlink/?LinkId=518007) and [Bower](http://go.microsoft.com/fwlink/?LinkId=518004) for managing client-side resources +* Theming using [Bootstrap](http://go.microsoft.com/fwlink/?LinkID=398939) + +#### NEW CONCEPTS +* [The 'wwwroot' explained](http://go.microsoft.com/fwlink/?LinkId=518008) +* [Configuration in ASP.NET 5](http://go.microsoft.com/fwlink/?LinkId=518012) +* [Dependency Injection](http://go.microsoft.com/fwlink/?LinkId=518013) +* [Razor TagHelpers](http://go.microsoft.com/fwlink/?LinkId=518014) +* [Manage client packages using Gulp](http://go.microsoft.com/fwlink/?LinkID=517849) +* [Develop on different platforms](http://go.microsoft.com/fwlink/?LinkID=517850) + +#### CUSTOMIZE APP +* [Add Controllers and Views](http://go.microsoft.com/fwlink/?LinkID=398600) +* [Add Data using EntityFramework](http://go.microsoft.com/fwlink/?LinkID=398602) +* [Add Authentication using Identity](http://go.microsoft.com/fwlink/?LinkID=398603) +* [Add real time support using SignalR](http://go.microsoft.com/fwlink/?LinkID=398606) +* [Add Class library](http://go.microsoft.com/fwlink/?LinkID=398604) +* [Add Web APIs with MVC 6](http://go.microsoft.com/fwlink/?LinkId=518009) +* [Add client packages using Bower](http://go.microsoft.com/fwlink/?LinkID=517848) + +#### DEPLOY +* [Run your app locally](http://go.microsoft.com/fwlink/?LinkID=517851) +* [Run your app on ASP.NET Core 5](http://go.microsoft.com/fwlink/?LinkID=517852) +* [Run commands in your 'project.json'](http://go.microsoft.com/fwlink/?LinkID=517853) +* [Publish to Microsoft Azure Web Sites](http://go.microsoft.com/fwlink/?LinkID=398609) +* [Publish to the file system](http://go.microsoft.com/fwlink/?LinkId=518019) + +We would love to hear your [feedback](http://go.microsoft.com/fwlink/?LinkId=518015) diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/index.html b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/index.html new file mode 100644 index 0000000000..f3318bc90a --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/index.html @@ -0,0 +1 @@ + diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json new file mode 100644 index 0000000000..257358c060 --- /dev/null +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json @@ -0,0 +1,1099 @@ +{ + "openapi" : "3.0.0", + "info" : { + "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", + "license" : { + "name" : "Apache-2.0", + "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "title" : "OpenAPI Petstore", + "version" : "1.0.0" + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + }, + "servers" : [ { + "url" : "http://petstore.swagger.io/v2" + } ], + "tags" : [ { + "description" : "Everything about your Pets", + "name" : "pet" + }, { + "description" : "Access to Petstore orders", + "name" : "store" + }, { + "description" : "Operations about user", + "name" : "user" + } ], + "paths" : { + "/pet" : { + "post" : { + "description" : "", + "operationId" : "addPet", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Add a new pet to the store", + "tags" : [ "pet" ] + }, + "put" : { + "description" : "", + "operationId" : "updatePet", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + }, + "405" : { + "description" : "Validation exception" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Update an existing pet", + "tags" : [ "pet" ] + } + }, + "/pet/findByStatus" : { + "get" : { + "description" : "Multiple status values can be provided with comma separated strings", + "operationId" : "findPetsByStatus", + "parameters" : [ { + "deprecated" : true, + "description" : "Status values that need to be considered for filter", + "explode" : false, + "in" : "query", + "name" : "status", + "required" : true, + "schema" : { + "items" : { + "default" : "available", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid status value" + } + }, + "security" : [ { + "petstore_auth" : [ "read:pets" ] + } ], + "summary" : "Finds Pets by status", + "tags" : [ "pet" ] + } + }, + "/pet/findByTags" : { + "get" : { + "deprecated" : true, + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "parameters" : [ { + "description" : "Tags to filter by", + "explode" : false, + "in" : "query", + "name" : "tags", + "required" : true, + "schema" : { + "items" : { + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid tag value" + } + }, + "security" : [ { + "petstore_auth" : [ "read:pets" ] + } ], + "summary" : "Finds Pets by tags", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}" : { + "delete" : { + "description" : "", + "operationId" : "deletePet", + "parameters" : [ { + "explode" : false, + "in" : "header", + "name" : "api_key", + "required" : false, + "schema" : { + "type" : "string" + }, + "style" : "simple" + }, { + "description" : "Pet id to delete", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid pet value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Deletes a pet", + "tags" : [ "pet" ] + }, + "get" : { + "description" : "Returns a single pet", + "operationId" : "getPetById", + "parameters" : [ { + "description" : "ID of pet to return", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Find pet by ID", + "tags" : [ "pet" ] + }, + "post" : { + "description" : "", + "operationId" : "updatePetWithForm", + "parameters" : [ { + "description" : "ID of pet that needs to be updated", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "application/x-www-form-urlencoded" : { + "schema" : { + "$ref" : "#/components/schemas/updatePetWithForm_request" + } + } + } + }, + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Updates a pet in the store with form data", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "description" : "", + "operationId" : "uploadFile", + "parameters" : [ { + "description" : "ID of pet to update", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "multipart/form-data" : { + "schema" : { + "$ref" : "#/components/schemas/uploadFile_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ApiResponse" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "uploads an image", + "tags" : [ "pet" ] + } + }, + "/store/inventory" : { + "get" : { + "description" : "Returns a map of status codes to quantities", + "operationId" : "getInventory", + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "additionalProperties" : { + "format" : "int32", + "type" : "integer" + }, + "type" : "object" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Returns pet inventories by status", + "tags" : [ "store" ] + } + }, + "/store/order" : { + "post" : { + "description" : "", + "operationId" : "placeOrder", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "order placed for purchasing the pet", + "required" : true + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid Order" + } + }, + "summary" : "Place an order for a pet", + "tags" : [ "store" ] + } + }, + "/store/order/{orderId}" : { + "delete" : { + "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId" : "deleteOrder", + "parameters" : [ { + "description" : "ID of the order that needs to be deleted", + "explode" : false, + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "summary" : "Delete purchase order by ID", + "tags" : [ "store" ] + }, + "get" : { + "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "operationId" : "getOrderById", + "parameters" : [ { + "description" : "ID of pet that needs to be fetched", + "explode" : false, + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "format" : "int64", + "maximum" : 5, + "minimum" : 1, + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "summary" : "Find purchase order by ID", + "tags" : [ "store" ] + } + }, + "/user" : { + "post" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Created user object", + "required" : true + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Create user", + "tags" : [ "user" ] + } + }, + "/user/createWithArray" : { + "post" : { + "description" : "", + "operationId" : "createUsersWithArrayInput", + "requestBody" : { + "$ref" : "#/components/requestBodies/UserArray" + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ] + } + }, + "/user/createWithList" : { + "post" : { + "description" : "", + "operationId" : "createUsersWithListInput", + "requestBody" : { + "$ref" : "#/components/requestBodies/UserArray" + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ] + } + }, + "/user/login" : { + "get" : { + "description" : "", + "operationId" : "loginUser", + "parameters" : [ { + "description" : "The user name for login", + "explode" : true, + "in" : "query", + "name" : "username", + "required" : true, + "schema" : { + "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", + "type" : "string" + }, + "style" : "form" + }, { + "description" : "The password for login in clear text", + "explode" : true, + "in" : "query", + "name" : "password", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "type" : "string" + } + }, + "application/json" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "successful operation", + "headers" : { + "Set-Cookie" : { + "description" : "Cookie authentication key for use with the `api_key` apiKey authentication.", + "explode" : false, + "schema" : { + "example" : "AUTH_KEY=abcde12345; Path=/; HttpOnly", + "type" : "string" + }, + "style" : "simple" + }, + "X-Rate-Limit" : { + "description" : "calls per hour allowed by the user", + "explode" : false, + "schema" : { + "format" : "int32", + "type" : "integer" + }, + "style" : "simple" + }, + "X-Expires-After" : { + "description" : "date in UTC when token expires", + "explode" : false, + "schema" : { + "format" : "date-time", + "type" : "string" + }, + "style" : "simple" + } + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + }, + "summary" : "Logs user into the system", + "tags" : [ "user" ] + } + }, + "/user/logout" : { + "get" : { + "description" : "", + "operationId" : "logoutUser", + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Logs out current logged in user session", + "tags" : [ "user" ] + } + }, + "/user/{username}" : { + "delete" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "parameters" : [ { + "description" : "The name that needs to be deleted", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Delete user", + "tags" : [ "user" ] + }, + "get" : { + "description" : "", + "operationId" : "getUserByName", + "parameters" : [ { + "description" : "The name that needs to be fetched. Use user1 for testing.", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "summary" : "Get user by user name", + "tags" : [ "user" ] + }, + "put" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "parameters" : [ { + "description" : "name that need to be deleted", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Updated user object", + "required" : true + }, + "responses" : { + "400" : { + "description" : "Invalid user supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Updated user", + "tags" : [ "user" ] + } + }, + "/fake/parameter_example_test" : { + "get" : { + "description" : "", + "operationId" : "fake_parameter_example_test", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "data", + "required" : true, + "schema" : { + "$ref" : "#/components/schemas/Pet" + }, + "style" : "form" + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "summary" : "fake endpoint to test parameter example (object)", + "tags" : [ "fake" ] + } + } + }, + "components" : { + "requestBodies" : { + "UserArray" : { + "content" : { + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/User" + }, + "type" : "array" + } + } + }, + "description" : "List of user object", + "required" : true + }, + "Pet" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "Pet object that needs to be added to the store", + "required" : true + } + }, + "schemas" : { + "Order" : { + "description" : "An order for a pets from the pet store", + "example" : { + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "petId" : { + "format" : "int64", + "type" : "integer" + }, + "quantity" : { + "format" : "int32", + "type" : "integer" + }, + "shipDate" : { + "format" : "date-time", + "type" : "string" + }, + "status" : { + "description" : "Order Status", + "enum" : [ "placed", "approved", "delivered" ], + "type" : "string" + }, + "complete" : { + "default" : false, + "type" : "boolean" + } + }, + "title" : "Pet Order", + "type" : "object", + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "description" : "A category for a pet", + "example" : { + "name" : "name", + "id" : 6 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", + "type" : "string" + } + }, + "title" : "Pet category", + "type" : "object", + "xml" : { + "name" : "Category" + } + }, + "User" : { + "description" : "A User who is purchasing from the pet store", + "example" : { + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "username" : { + "type" : "string" + }, + "firstName" : { + "type" : "string" + }, + "lastName" : { + "type" : "string" + }, + "email" : { + "type" : "string" + }, + "password" : { + "type" : "string" + }, + "phone" : { + "type" : "string" + }, + "userStatus" : { + "description" : "User Status", + "format" : "int32", + "type" : "integer" + } + }, + "title" : "a User", + "type" : "object", + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "description" : "A tag for a pet", + "example" : { + "name" : "name", + "id" : 1 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "type" : "object", + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "description" : "A pet for sale in the pet store", + "example" : { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "category" : { + "$ref" : "#/components/schemas/Category" + }, + "name" : { + "example" : "doggie", + "type" : "string" + }, + "photoUrls" : { + "items" : { + "type" : "string" + }, + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + } + }, + "tags" : { + "items" : { + "$ref" : "#/components/schemas/Tag" + }, + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + } + }, + "status" : { + "deprecated" : true, + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + } + }, + "required" : [ "name", "photoUrls" ], + "title" : "a Pet", + "type" : "object", + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "description" : "Describes the result of uploading an image resource", + "example" : { + "code" : 0, + "type" : "type", + "message" : "message" + }, + "properties" : { + "code" : { + "format" : "int32", + "type" : "integer" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "type" : "object" + }, + "updatePetWithForm_request" : { + "properties" : { + "name" : { + "description" : "Updated name of the pet", + "type" : "string" + }, + "status" : { + "description" : "Updated status of the pet", + "type" : "string" + } + }, + "type" : "object" + }, + "uploadFile_request" : { + "properties" : { + "additionalMetadata" : { + "description" : "Additional data to pass to server", + "type" : "string" + }, + "file" : { + "description" : "file to upload", + "format" : "binary", + "type" : "string" + } + }, + "type" : "object" + } + }, + "securitySchemes" : { + "petstore_auth" : { + "flows" : { + "implicit" : { + "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", + "scopes" : { + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" + } + } + }, + "type" : "oauth2" + }, + "api_key" : { + "in" : "header", + "name" : "api_key", + "type" : "apiKey" + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0/README.md b/samples/server/petstore/aspnetcore-6.0/README.md index ef01f590df..34e589967c 100644 --- a/samples/server/petstore/aspnetcore-6.0/README.md +++ b/samples/server/petstore/aspnetcore-6.0/README.md @@ -2,6 +2,32 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + ## Run Linux/OS X: diff --git a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Controllers/StoreApi.cs b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Controllers/StoreApi.cs index 2077313f7d..31f24ebfc7 100644 --- a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Controllers/StoreApi.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Controllers var example = exampleJson != null ? JsonConvert.DeserializeObject>(exampleJson) - : default(Dictionary); + : new Dictionary(); //TODO: Change the data returned return new ObjectResult(example); } diff --git a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 0aaa1b25a4..518a6425bc 100644 --- a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -16,9 +16,9 @@ - - - + + + diff --git a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Startup.cs b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Startup.cs index 5699f01516..aee0229fa2 100644 --- a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Startup.cs +++ b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Startup.cs @@ -80,6 +80,8 @@ namespace Org.OpenAPITools services .AddSwaggerGen(c => { + c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true); + c.SwaggerDoc("1.0.0", new OpenApiInfo { Title = "OpenAPI Petstore", diff --git a/samples/server/petstore/aspnetcore/README.md b/samples/server/petstore/aspnetcore/README.md index 0dfedef957..8563f76280 100644 --- a/samples/server/petstore/aspnetcore/README.md +++ b/samples/server/petstore/aspnetcore/README.md @@ -2,6 +2,32 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +## Upgrade NuGet Packages + +NuGet packages get frequently updated. + +To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool. + + +Install dotnet-outdated tool: + +``` +dotnet tool install --global dotnet-outdated-tool +``` + +Upgrade only to new minor versions of packages + +``` +dotnet outdated --upgrade --version-lock Major +``` + +Upgrade to all new versions of packages (more likely to include breaking API changes) + +``` +dotnet outdated --upgrade +``` + + ## Run Linux/OS X: diff --git a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Controllers/StoreApi.cs b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Controllers/StoreApi.cs index 9ce84426e2..f815bf3901 100644 --- a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Controllers/StoreApi.cs +++ b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Controllers/StoreApi.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Controllers var example = exampleJson != null ? JsonConvert.DeserializeObject>(exampleJson) - : default(Dictionary); + : new Dictionary(); //TODO: Change the data returned return new ObjectResult(example); } diff --git a/samples/server/petstore/cpp-restbed-deprecated/.gitignore b/samples/server/petstore/cpp-restbed-deprecated/.gitignore new file mode 100644 index 0000000000..4581ef2eee --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/.gitignore @@ -0,0 +1,29 @@ +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app diff --git a/samples/server/petstore/cpp-restbed-deprecated/.openapi-generator-ignore b/samples/server/petstore/cpp-restbed-deprecated/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/.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/server/petstore/cpp-restbed-deprecated/.openapi-generator/FILES b/samples/server/petstore/cpp-restbed-deprecated/.openapi-generator/FILES new file mode 100644 index 0000000000..0537b528d8 --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/.openapi-generator/FILES @@ -0,0 +1,22 @@ +.gitignore +.openapi-generator-ignore +README.md +api/PetApi.cpp +api/PetApi.h +api/StoreApi.cpp +api/StoreApi.h +api/UserApi.cpp +api/UserApi.h +git_push.sh +model/ApiResponse.cpp +model/ApiResponse.h +model/Category.cpp +model/Category.h +model/Order.cpp +model/Order.h +model/Pet.cpp +model/Pet.h +model/Tag.cpp +model/Tag.h +model/User.cpp +model/User.h diff --git a/samples/server/petstore/cpp-restbed/.openapi-generator/VERSION b/samples/server/petstore/cpp-restbed-deprecated/.openapi-generator/VERSION similarity index 100% rename from samples/server/petstore/cpp-restbed/.openapi-generator/VERSION rename to samples/server/petstore/cpp-restbed-deprecated/.openapi-generator/VERSION diff --git a/samples/server/petstore/cpp-restbed/README.md b/samples/server/petstore/cpp-restbed-deprecated/README.md similarity index 100% rename from samples/server/petstore/cpp-restbed/README.md rename to samples/server/petstore/cpp-restbed-deprecated/README.md diff --git a/samples/server/petstore/cpp-restbed-deprecated/api/PetApi.cpp b/samples/server/petstore/cpp-restbed-deprecated/api/PetApi.cpp new file mode 100644 index 0000000000..e80c5f0ccc --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/api/PetApi.cpp @@ -0,0 +1,819 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "PetApi.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +PetApiException::PetApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int PetApiException::getStatus() const +{ + return m_status; +} +const char* PetApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = std::make_shared(pt); + return model; +} + +template +std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector>(); + for (const auto& child: pt) { + arrayRet.emplace_back(std::make_shared(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +PetApiPetResource::PetApiPetResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/"); + this->set_method_handler("POST", + std::bind(&PetApiPetResource::handler_POST_internal, this, + std::placeholders::_1)); + this->set_method_handler("PUT", + std::bind(&PetApiPetResource::handler_PUT_internal, this, + std::placeholders::_1)); +} + +PetApiPetResource::~PetApiPetResource() +{ +} + +std::pair PetApiPetResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto pet = extractJsonModelBodyParam(bodyContent); + + + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(pet); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 405) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 405, result.empty() ? "Invalid input" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void PetApiPetResource::handler_PUT_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // body params or form params here from the body content string + auto pet = extractJsonModelBodyParam(bodyContent); + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_PUT(pet); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "Pet not found" : result, contentType); + return; + } + if (status_code == 405) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 405, result.empty() ? "Validation exception" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +std::pair> PetApiPetResource::handler_POST( + std::shared_ptr const & pet) +{ + throw PetApiException(501, "Not implemented"); +} + +std::pair> PetApiPetResource::handler_PUT( + std::shared_ptr const & pet) +{ + throw PetApiException(501, "Not implemented"); +} + +std::string PetApiPetResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +PetApiPetPetIdResource::PetApiPetPetIdResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/{petId: .*}/"); + this->set_method_handler("DELETE", + std::bind(&PetApiPetPetIdResource::handler_DELETE_internal, this, + std::placeholders::_1)); + this->set_method_handler("GET", + std::bind(&PetApiPetPetIdResource::handler_GET_internal, this, + std::placeholders::_1)); + this->set_method_handler("POST", + std::bind(&PetApiPetPetIdResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +PetApiPetPetIdResource::~PetApiPetPetIdResource() +{ +} + +std::pair PetApiPetPetIdResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetPetIdResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetPetIdResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetPetIdResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetPetIdResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetPetIdResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetPetIdResource::handler_DELETE_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + // Getting the path params + const int64_t petId = getPathParam_petId(request); + + + // Getting the headers + const std::string apiKey = getHeader_api_key(request); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(petId, apiKey); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid pet value" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void PetApiPetPetIdResource::handler_GET_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + + // Getting the path params + const int64_t petId = getPathParam_petId_x_extension(request); + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(petId); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "Pet not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} +// x-extension +void PetApiPetPetIdResource::handler_POST_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + + // Getting the path params + const int64_t petId = getPathParam_petId_x_extension(request); + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(petId, name, status); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 405) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 405, result.empty() ? "Invalid input" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +int PetApiPetPetIdResource::handler_DELETE( + int64_t const & petId, std::string const & apiKey) +{ + throw PetApiException(501, "Not implemented"); +} + +std::pair> PetApiPetPetIdResource::handler_GET( + int64_t const & petId) +{ + throw PetApiException(501, "Not implemented"); +} +int PetApiPetPetIdResource::handler_POST( + int64_t const & petId, std::string const & name, std::string const & status) +{ + throw PetApiException(501, "Not implemented"); +} + +std::string PetApiPetPetIdResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +PetApiPetFindByStatusResource::PetApiPetFindByStatusResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/findByStatus/"); + this->set_method_handler("GET", + std::bind(&PetApiPetFindByStatusResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +PetApiPetFindByStatusResource::~PetApiPetFindByStatusResource() +{ +} + +std::pair PetApiPetFindByStatusResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetFindByStatusResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetFindByStatusResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetFindByStatusResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetFindByStatusResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetFindByStatusResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetFindByStatusResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + // Getting the query params + + + int status_code = 500; + std::vector> resultObject = std::vector>(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(status); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid status value" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair>> PetApiPetFindByStatusResource::handler_GET( + std::vector const & status) +{ + throw PetApiException(501, "Not implemented"); +} + + +std::string PetApiPetFindByStatusResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +PetApiPetFindByTagsResource::PetApiPetFindByTagsResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/findByTags/"); + this->set_method_handler("GET", + std::bind(&PetApiPetFindByTagsResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +PetApiPetFindByTagsResource::~PetApiPetFindByTagsResource() +{ +} + +std::pair PetApiPetFindByTagsResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetFindByTagsResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetFindByTagsResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetFindByTagsResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetFindByTagsResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetFindByTagsResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetFindByTagsResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + // Getting the query params + + + int status_code = 500; + std::vector> resultObject = std::vector>(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(tags); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid tag value" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair>> PetApiPetFindByTagsResource::handler_GET( + std::vector const & tags) +{ + throw PetApiException(501, "Not implemented"); +} + + +std::string PetApiPetFindByTagsResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +PetApiPetPetIdUploadImageResource::PetApiPetPetIdUploadImageResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/{petId: .*}/uploadImage/"); + this->set_method_handler("POST", + std::bind(&PetApiPetPetIdUploadImageResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +PetApiPetPetIdUploadImageResource::~PetApiPetPetIdUploadImageResource() +{ +} + +std::pair PetApiPetPetIdUploadImageResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetPetIdUploadImageResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetPetIdUploadImageResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetPetIdUploadImageResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetPetIdUploadImageResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetPetIdUploadImageResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetPetIdUploadImageResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + // Getting the path params + const int64_t petId = getPathParam_petId(request); + + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(petId, additionalMetadata, file); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair> PetApiPetPetIdUploadImageResource::handler_POST( + int64_t const & petId, std::string const & additionalMetadata, std::string const & file) +{ + throw PetApiException(501, "Not implemented"); +} + + +std::string PetApiPetPetIdUploadImageResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +PetApi::PetApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +PetApi::~PetApi() {} + +void PetApi::setPetApiPetResource(std::shared_ptr spPetApiPetResource) { + m_spPetApiPetResource = spPetApiPetResource; + m_service->publish(m_spPetApiPetResource); +} +void PetApi::setPetApiPetPetIdResource(std::shared_ptr spPetApiPetPetIdResource) { + m_spPetApiPetPetIdResource = spPetApiPetPetIdResource; + m_service->publish(m_spPetApiPetPetIdResource); +} +void PetApi::setPetApiPetFindByStatusResource(std::shared_ptr spPetApiPetFindByStatusResource) { + m_spPetApiPetFindByStatusResource = spPetApiPetFindByStatusResource; + m_service->publish(m_spPetApiPetFindByStatusResource); +} +void PetApi::setPetApiPetFindByTagsResource(std::shared_ptr spPetApiPetFindByTagsResource) { + m_spPetApiPetFindByTagsResource = spPetApiPetFindByTagsResource; + m_service->publish(m_spPetApiPetFindByTagsResource); +} +void PetApi::setPetApiPetPetIdUploadImageResource(std::shared_ptr spPetApiPetPetIdUploadImageResource) { + m_spPetApiPetPetIdUploadImageResource = spPetApiPetPetIdUploadImageResource; + m_service->publish(m_spPetApiPetPetIdUploadImageResource); +} + + +void PetApi::publishDefaultResources() { + if (!m_spPetApiPetResource) { + setPetApiPetResource(std::make_shared()); + } + if (!m_spPetApiPetPetIdResource) { + setPetApiPetPetIdResource(std::make_shared()); + } + if (!m_spPetApiPetFindByStatusResource) { + setPetApiPetFindByStatusResource(std::make_shared()); + } + if (!m_spPetApiPetFindByTagsResource) { + setPetApiPetFindByTagsResource(std::make_shared()); + } + if (!m_spPetApiPetPetIdUploadImageResource) { + setPetApiPetPetIdUploadImageResource(std::make_shared()); + } +} + +std::shared_ptr PetApi::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed-deprecated/api/PetApi.h b/samples/server/petstore/cpp-restbed-deprecated/api/PetApi.h new file mode 100644 index 0000000000..0dbcfba2c5 --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/api/PetApi.h @@ -0,0 +1,370 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PetApi.h + * + * + */ + +#ifndef PetApi_H_ +#define PetApi_H_ + + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "ApiResponse.h" +#include "Pet.h" +#include + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class PetApiException: public std::exception +{ +public: + PetApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +/// +/// Add a new pet to the store +/// +/// +/// +/// +class PetApiPetResource: public restbed::Resource +{ +public: + PetApiPetResource(const std::string& context = "/v2"); + virtual ~PetApiPetResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair> handler_POST( + std::shared_ptr const & pet); + + virtual std::pair> handler_PUT( + std::shared_ptr const & pet); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); + void handler_PUT_internal(const std::shared_ptr session); +}; + + +/// +/// Deletes a pet +/// +/// +/// +/// +class PetApiPetPetIdResource: public restbed::Resource +{ +public: + PetApiPetPetIdResource(const std::string& context = "/v2"); + virtual ~PetApiPetPetIdResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_DELETE( + int64_t const & petId, std::string const & apiKey); + + virtual std::pair> handler_GET( + int64_t const & petId); + virtual int handler_POST( + int64_t const & petId, std::string const & name, std::string const & status); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual int64_t getPathParam_petId(const std::shared_ptr& request) + { + return request->get_path_parameter("petId", 0L); + } + + virtual std::string getHeader_api_key(const std::shared_ptr& request) + { + return request->get_header("api_key", ""); + } + + + virtual int64_t getPathParam_petId_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("petId", 0L); + } + virtual int64_t getPathParam_petId_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("petId", 0L); + } + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_DELETE_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); + void handler_POST_internal(const std::shared_ptr session); +}; + + +/// +/// Finds Pets by status +/// +/// +/// Multiple status values can be provided with comma separated strings +/// +class PetApiPetFindByStatusResource: public restbed::Resource +{ +public: + PetApiPetFindByStatusResource(const std::string& context = "/v2"); + virtual ~PetApiPetFindByStatusResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair>> handler_GET( + std::vector const & status); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + + +/// +/// Finds Pets by tags +/// +/// +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +/// +class PetApiPetFindByTagsResource: public restbed::Resource +{ +public: + PetApiPetFindByTagsResource(const std::string& context = "/v2"); + virtual ~PetApiPetFindByTagsResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair>> handler_GET( + std::vector const & tags); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + + +/// +/// uploads an image +/// +/// +/// +/// +class PetApiPetPetIdUploadImageResource: public restbed::Resource +{ +public: + PetApiPetPetIdUploadImageResource(const std::string& context = "/v2"); + virtual ~PetApiPetPetIdUploadImageResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair> handler_POST( + int64_t const & petId, std::string const & additionalMetadata, std::string const & file); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual int64_t getPathParam_petId(const std::shared_ptr& request) + { + return request->get_path_parameter("petId", 0L); + } + + + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + + + +// +// The restbed service to actually implement the REST server +// +class PetApi +{ +public: + explicit PetApi(std::shared_ptr const& restbedService); + virtual ~PetApi(); + + virtual void setPetApiPetResource(std::shared_ptr spPetApiPetResource); + virtual void setPetApiPetPetIdResource(std::shared_ptr spPetApiPetPetIdResource); + virtual void setPetApiPetFindByStatusResource(std::shared_ptr spPetApiPetFindByStatusResource); + virtual void setPetApiPetFindByTagsResource(std::shared_ptr spPetApiPetFindByTagsResource); + virtual void setPetApiPetPetIdUploadImageResource(std::shared_ptr spPetApiPetPetIdUploadImageResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spPetApiPetResource; + std::shared_ptr m_spPetApiPetPetIdResource; + std::shared_ptr m_spPetApiPetFindByStatusResource; + std::shared_ptr m_spPetApiPetFindByTagsResource; + std::shared_ptr m_spPetApiPetPetIdUploadImageResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* PetApi_H_ */ + diff --git a/samples/server/petstore/cpp-restbed-deprecated/api/StoreApi.cpp b/samples/server/petstore/cpp-restbed-deprecated/api/StoreApi.cpp new file mode 100644 index 0000000000..0ca436e020 --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/api/StoreApi.cpp @@ -0,0 +1,497 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "StoreApi.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +StoreApiException::StoreApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int StoreApiException::getStatus() const +{ + return m_status; +} +const char* StoreApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = std::make_shared(pt); + return model; +} + +template +std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector>(); + for (const auto& child: pt) { + arrayRet.emplace_back(std::make_shared(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +StoreApiStoreOrderOrderIdResource::StoreApiStoreOrderOrderIdResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/store/order/{orderId: .*}/"); + this->set_method_handler("DELETE", + std::bind(&StoreApiStoreOrderOrderIdResource::handler_DELETE_internal, this, + std::placeholders::_1)); + this->set_method_handler("GET", + std::bind(&StoreApiStoreOrderOrderIdResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +StoreApiStoreOrderOrderIdResource::~StoreApiStoreOrderOrderIdResource() +{ +} + +std::pair StoreApiStoreOrderOrderIdResource::handleStoreApiException(const StoreApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair StoreApiStoreOrderOrderIdResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair StoreApiStoreOrderOrderIdResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void StoreApiStoreOrderOrderIdResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void StoreApiStoreOrderOrderIdResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void StoreApiStoreOrderOrderIdResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void StoreApiStoreOrderOrderIdResource::handler_DELETE_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + // Getting the path params + const std::string orderId = getPathParam_orderId(request); + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(orderId); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "Order not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void StoreApiStoreOrderOrderIdResource::handler_GET_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + + // Getting the path params + const int64_t orderId = getPathParam_orderId_x_extension(request); + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(orderId); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "Order not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +int StoreApiStoreOrderOrderIdResource::handler_DELETE( + std::string const & orderId) +{ + throw StoreApiException(501, "Not implemented"); +} + +std::pair> StoreApiStoreOrderOrderIdResource::handler_GET( + int64_t const & orderId) +{ + throw StoreApiException(501, "Not implemented"); +} + +std::string StoreApiStoreOrderOrderIdResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +StoreApiStoreInventoryResource::StoreApiStoreInventoryResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/store/inventory/"); + this->set_method_handler("GET", + std::bind(&StoreApiStoreInventoryResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +StoreApiStoreInventoryResource::~StoreApiStoreInventoryResource() +{ +} + +std::pair StoreApiStoreInventoryResource::handleStoreApiException(const StoreApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair StoreApiStoreInventoryResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair StoreApiStoreInventoryResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void StoreApiStoreInventoryResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void StoreApiStoreInventoryResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void StoreApiStoreInventoryResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void StoreApiStoreInventoryResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + + + int status_code = 500; + std::map resultObject = std::map(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + result = convertMapResponse(resultObject); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair> StoreApiStoreInventoryResource::handler_GET( + ) +{ + throw StoreApiException(501, "Not implemented"); +} + + +std::string StoreApiStoreInventoryResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +StoreApiStoreOrderResource::StoreApiStoreOrderResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/store/order/"); + this->set_method_handler("POST", + std::bind(&StoreApiStoreOrderResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +StoreApiStoreOrderResource::~StoreApiStoreOrderResource() +{ +} + +std::pair StoreApiStoreOrderResource::handleStoreApiException(const StoreApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair StoreApiStoreOrderResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair StoreApiStoreOrderResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void StoreApiStoreOrderResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void StoreApiStoreOrderResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void StoreApiStoreOrderResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void StoreApiStoreOrderResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto order = extractJsonModelBodyParam(bodyContent); + + + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(order); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid Order" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair> StoreApiStoreOrderResource::handler_POST( + std::shared_ptr const & order) +{ + throw StoreApiException(501, "Not implemented"); +} + + +std::string StoreApiStoreOrderResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +StoreApi::StoreApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +StoreApi::~StoreApi() {} + +void StoreApi::setStoreApiStoreOrderOrderIdResource(std::shared_ptr spStoreApiStoreOrderOrderIdResource) { + m_spStoreApiStoreOrderOrderIdResource = spStoreApiStoreOrderOrderIdResource; + m_service->publish(m_spStoreApiStoreOrderOrderIdResource); +} +void StoreApi::setStoreApiStoreInventoryResource(std::shared_ptr spStoreApiStoreInventoryResource) { + m_spStoreApiStoreInventoryResource = spStoreApiStoreInventoryResource; + m_service->publish(m_spStoreApiStoreInventoryResource); +} +void StoreApi::setStoreApiStoreOrderResource(std::shared_ptr spStoreApiStoreOrderResource) { + m_spStoreApiStoreOrderResource = spStoreApiStoreOrderResource; + m_service->publish(m_spStoreApiStoreOrderResource); +} + + +void StoreApi::publishDefaultResources() { + if (!m_spStoreApiStoreOrderOrderIdResource) { + setStoreApiStoreOrderOrderIdResource(std::make_shared()); + } + if (!m_spStoreApiStoreInventoryResource) { + setStoreApiStoreInventoryResource(std::make_shared()); + } + if (!m_spStoreApiStoreOrderResource) { + setStoreApiStoreOrderResource(std::make_shared()); + } +} + +std::shared_ptr StoreApi::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed-deprecated/api/StoreApi.h b/samples/server/petstore/cpp-restbed-deprecated/api/StoreApi.h new file mode 100644 index 0000000000..3c93155624 --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/api/StoreApi.h @@ -0,0 +1,250 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * StoreApi.h + * + * + */ + +#ifndef StoreApi_H_ +#define StoreApi_H_ + + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "Order.h" +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class StoreApiException: public std::exception +{ +public: + StoreApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +/// +/// Delete purchase order by ID +/// +/// +/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +/// +class StoreApiStoreOrderOrderIdResource: public restbed::Resource +{ +public: + StoreApiStoreOrderOrderIdResource(const std::string& context = "/v2"); + virtual ~StoreApiStoreOrderOrderIdResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_DELETE( + std::string const & orderId); + + virtual std::pair> handler_GET( + int64_t const & orderId); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual std::string getPathParam_orderId(const std::shared_ptr& request) + { + return request->get_path_parameter("orderId", ""); + } + + + virtual int64_t getPathParam_orderId_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("orderId", 0L); + } + + virtual std::pair handleStoreApiException(const StoreApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_DELETE_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); +}; + + +/// +/// Returns pet inventories by status +/// +/// +/// Returns a map of status codes to quantities +/// +class StoreApiStoreInventoryResource: public restbed::Resource +{ +public: + StoreApiStoreInventoryResource(const std::string& context = "/v2"); + virtual ~StoreApiStoreInventoryResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair> handler_GET( + ); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleStoreApiException(const StoreApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + + +/// +/// Place an order for a pet +/// +/// +/// +/// +class StoreApiStoreOrderResource: public restbed::Resource +{ +public: + StoreApiStoreOrderResource(const std::string& context = "/v2"); + virtual ~StoreApiStoreOrderResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair> handler_POST( + std::shared_ptr const & order); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleStoreApiException(const StoreApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + + + +// +// The restbed service to actually implement the REST server +// +class StoreApi +{ +public: + explicit StoreApi(std::shared_ptr const& restbedService); + virtual ~StoreApi(); + + virtual void setStoreApiStoreOrderOrderIdResource(std::shared_ptr spStoreApiStoreOrderOrderIdResource); + virtual void setStoreApiStoreInventoryResource(std::shared_ptr spStoreApiStoreInventoryResource); + virtual void setStoreApiStoreOrderResource(std::shared_ptr spStoreApiStoreOrderResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spStoreApiStoreOrderOrderIdResource; + std::shared_ptr m_spStoreApiStoreInventoryResource; + std::shared_ptr m_spStoreApiStoreOrderResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* StoreApi_H_ */ + diff --git a/samples/server/petstore/cpp-restbed-deprecated/api/UserApi.cpp b/samples/server/petstore/cpp-restbed-deprecated/api/UserApi.cpp new file mode 100644 index 0000000000..c865c44aff --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/api/UserApi.cpp @@ -0,0 +1,870 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "UserApi.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +UserApiException::UserApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int UserApiException::getStatus() const +{ + return m_status; +} +const char* UserApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = std::make_shared(pt); + return model; +} + +template +std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector>(); + for (const auto& child: pt) { + arrayRet.emplace_back(std::make_shared(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +UserApiUserResource::UserApiUserResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/"); + this->set_method_handler("POST", + std::bind(&UserApiUserResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +UserApiUserResource::~UserApiUserResource() +{ +} + +std::pair UserApiUserResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto user = extractJsonModelBodyParam(bodyContent); + + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(user); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 0) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserApiUserResource::handler_POST( + std::shared_ptr const & user) +{ + throw UserApiException(501, "Not implemented"); +} + + +std::string UserApiUserResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserCreateWithArrayResource::UserApiUserCreateWithArrayResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/createWithArray/"); + this->set_method_handler("POST", + std::bind(&UserApiUserCreateWithArrayResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +UserApiUserCreateWithArrayResource::~UserApiUserCreateWithArrayResource() +{ +} + +std::pair UserApiUserCreateWithArrayResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserCreateWithArrayResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserCreateWithArrayResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserCreateWithArrayResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserCreateWithArrayResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserCreateWithArrayResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserCreateWithArrayResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto user = extractJsonArrayBodyParam(bodyContent); + + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(user); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 0) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserApiUserCreateWithArrayResource::handler_POST( + std::vector> const & user) +{ + throw UserApiException(501, "Not implemented"); +} + + +std::string UserApiUserCreateWithArrayResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserCreateWithListResource::UserApiUserCreateWithListResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/createWithList/"); + this->set_method_handler("POST", + std::bind(&UserApiUserCreateWithListResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +UserApiUserCreateWithListResource::~UserApiUserCreateWithListResource() +{ +} + +std::pair UserApiUserCreateWithListResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserCreateWithListResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserCreateWithListResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserCreateWithListResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserCreateWithListResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserCreateWithListResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserCreateWithListResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto user = extractJsonArrayBodyParam(bodyContent); + + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(user); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 0) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserApiUserCreateWithListResource::handler_POST( + std::vector> const & user) +{ + throw UserApiException(501, "Not implemented"); +} + + +std::string UserApiUserCreateWithListResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserUsernameResource::UserApiUserUsernameResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/{username: .*}/"); + this->set_method_handler("DELETE", + std::bind(&UserApiUserUsernameResource::handler_DELETE_internal, this, + std::placeholders::_1)); + this->set_method_handler("GET", + std::bind(&UserApiUserUsernameResource::handler_GET_internal, this, + std::placeholders::_1)); + this->set_method_handler("PUT", + std::bind(&UserApiUserUsernameResource::handler_PUT_internal, this, + std::placeholders::_1)); +} + +UserApiUserUsernameResource::~UserApiUserUsernameResource() +{ +} + +std::pair UserApiUserUsernameResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserUsernameResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserUsernameResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserUsernameResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserUsernameResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserUsernameResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserUsernameResource::handler_DELETE_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + // Getting the path params + const std::string username = getPathParam_username(request); + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(username); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid username supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "User not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void UserApiUserUsernameResource::handler_GET_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + + // Getting the path params + const std::string username = getPathParam_username_x_extension(request); + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(username); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid username supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "User not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} +// x-extension +void UserApiUserUsernameResource::handler_PUT_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // body params or form params here from the body content string + auto username = std::make_shared<>(bodyContent); + auto user = extractJsonModelBodyParam(bodyContent); + + // Getting the path params + const std::string username = getPathParam_username_x_extension(request); + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_PUT(username, user); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid user supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "User not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +int UserApiUserUsernameResource::handler_DELETE( + std::string const & username) +{ + throw UserApiException(501, "Not implemented"); +} + +std::pair> UserApiUserUsernameResource::handler_GET( + std::string const & username) +{ + throw UserApiException(501, "Not implemented"); +} +int UserApiUserUsernameResource::handler_PUT( + std::string const & username, std::shared_ptr const & user) +{ + throw UserApiException(501, "Not implemented"); +} + +std::string UserApiUserUsernameResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserLoginResource::UserApiUserLoginResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/login/"); + this->set_method_handler("GET", + std::bind(&UserApiUserLoginResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +UserApiUserLoginResource::~UserApiUserLoginResource() +{ +} + +std::pair UserApiUserLoginResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserLoginResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserLoginResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserLoginResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserLoginResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserLoginResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserLoginResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + // Getting the query params + const std::string username = getQueryParam_username(request); + const std::string password = getQueryParam_password(request); + + + int status_code = 500; + std::string resultObject = ""; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(username, password); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject; + // Description: Cookie authentication key for use with the `api_key` apiKey authentication. + setResponseHeader(session, "Set-Cookie"); + // Description: calls per hour allowed by the user + setResponseHeader(session, "X-Rate-Limit"); + // Description: date in UTC when token expires + setResponseHeader(session, "X-Expires-After"); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid username/password supplied" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair UserApiUserLoginResource::handler_GET( + std::string const & username, std::string const & password) +{ + throw UserApiException(501, "Not implemented"); +} + + +std::string UserApiUserLoginResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserLogoutResource::UserApiUserLogoutResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/logout/"); + this->set_method_handler("GET", + std::bind(&UserApiUserLogoutResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +UserApiUserLogoutResource::~UserApiUserLogoutResource() +{ +} + +std::pair UserApiUserLogoutResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserLogoutResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserLogoutResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserLogoutResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserLogoutResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserLogoutResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserLogoutResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_GET(); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 0) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserApiUserLogoutResource::handler_GET( + ) +{ + throw UserApiException(501, "Not implemented"); +} + + +std::string UserApiUserLogoutResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +UserApi::UserApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +UserApi::~UserApi() {} + +void UserApi::setUserApiUserResource(std::shared_ptr spUserApiUserResource) { + m_spUserApiUserResource = spUserApiUserResource; + m_service->publish(m_spUserApiUserResource); +} +void UserApi::setUserApiUserCreateWithArrayResource(std::shared_ptr spUserApiUserCreateWithArrayResource) { + m_spUserApiUserCreateWithArrayResource = spUserApiUserCreateWithArrayResource; + m_service->publish(m_spUserApiUserCreateWithArrayResource); +} +void UserApi::setUserApiUserCreateWithListResource(std::shared_ptr spUserApiUserCreateWithListResource) { + m_spUserApiUserCreateWithListResource = spUserApiUserCreateWithListResource; + m_service->publish(m_spUserApiUserCreateWithListResource); +} +void UserApi::setUserApiUserUsernameResource(std::shared_ptr spUserApiUserUsernameResource) { + m_spUserApiUserUsernameResource = spUserApiUserUsernameResource; + m_service->publish(m_spUserApiUserUsernameResource); +} +void UserApi::setUserApiUserLoginResource(std::shared_ptr spUserApiUserLoginResource) { + m_spUserApiUserLoginResource = spUserApiUserLoginResource; + m_service->publish(m_spUserApiUserLoginResource); +} +void UserApi::setUserApiUserLogoutResource(std::shared_ptr spUserApiUserLogoutResource) { + m_spUserApiUserLogoutResource = spUserApiUserLogoutResource; + m_service->publish(m_spUserApiUserLogoutResource); +} + + +void UserApi::publishDefaultResources() { + if (!m_spUserApiUserResource) { + setUserApiUserResource(std::make_shared()); + } + if (!m_spUserApiUserCreateWithArrayResource) { + setUserApiUserCreateWithArrayResource(std::make_shared()); + } + if (!m_spUserApiUserCreateWithListResource) { + setUserApiUserCreateWithListResource(std::make_shared()); + } + if (!m_spUserApiUserUsernameResource) { + setUserApiUserUsernameResource(std::make_shared()); + } + if (!m_spUserApiUserLoginResource) { + setUserApiUserLoginResource(std::make_shared()); + } + if (!m_spUserApiUserLogoutResource) { + setUserApiUserLogoutResource(std::make_shared()); + } +} + +std::shared_ptr UserApi::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed-deprecated/api/UserApi.h b/samples/server/petstore/cpp-restbed-deprecated/api/UserApi.h new file mode 100644 index 0000000000..1b80a2733b --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/api/UserApi.h @@ -0,0 +1,417 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * UserApi.h + * + * + */ + +#ifndef UserApi_H_ +#define UserApi_H_ + + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "User.h" +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class UserApiException: public std::exception +{ +public: + UserApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +/// +/// Create user +/// +/// +/// This can only be done by the logged in user. +/// +class UserApiUserResource: public restbed::Resource +{ +public: + UserApiUserResource(const std::string& context = "/v2"); + virtual ~UserApiUserResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_POST( + std::shared_ptr const & user); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + + +/// +/// Creates list of users with given input array +/// +/// +/// +/// +class UserApiUserCreateWithArrayResource: public restbed::Resource +{ +public: + UserApiUserCreateWithArrayResource(const std::string& context = "/v2"); + virtual ~UserApiUserCreateWithArrayResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_POST( + std::vector> const & user); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + + +/// +/// Creates list of users with given input array +/// +/// +/// +/// +class UserApiUserCreateWithListResource: public restbed::Resource +{ +public: + UserApiUserCreateWithListResource(const std::string& context = "/v2"); + virtual ~UserApiUserCreateWithListResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_POST( + std::vector> const & user); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + + +/// +/// Delete user +/// +/// +/// This can only be done by the logged in user. +/// +class UserApiUserUsernameResource: public restbed::Resource +{ +public: + UserApiUserUsernameResource(const std::string& context = "/v2"); + virtual ~UserApiUserUsernameResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_DELETE( + std::string const & username); + + virtual std::pair> handler_GET( + std::string const & username); + virtual int handler_PUT( + std::string const & username, std::shared_ptr const & user); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual std::string getPathParam_username(const std::shared_ptr& request) + { + return request->get_path_parameter("username", ""); + } + + + virtual std::string getPathParam_username_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("username", ""); + } + virtual std::string getPathParam_username_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("username", ""); + } + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_DELETE_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); + void handler_PUT_internal(const std::shared_ptr session); +}; + + +/// +/// Logs user into the system +/// +/// +/// +/// +class UserApiUserLoginResource: public restbed::Resource +{ +public: + UserApiUserLoginResource(const std::string& context = "/v2"); + virtual ~UserApiUserLoginResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_GET( + std::string const & username, std::string const & password); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual std::string getQueryParam_username(const std::shared_ptr& request) + { + return request->get_query_parameter("username", ""); + } + + virtual std::string getQueryParam_password(const std::shared_ptr& request) + { + return request->get_query_parameter("password", ""); + } + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + + +/// +/// Logs out current logged in user session +/// +/// +/// +/// +class UserApiUserLogoutResource: public restbed::Resource +{ +public: + UserApiUserLogoutResource(const std::string& context = "/v2"); + virtual ~UserApiUserLogoutResource(); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_GET( + ); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + + + +// +// The restbed service to actually implement the REST server +// +class UserApi +{ +public: + explicit UserApi(std::shared_ptr const& restbedService); + virtual ~UserApi(); + + virtual void setUserApiUserResource(std::shared_ptr spUserApiUserResource); + virtual void setUserApiUserCreateWithArrayResource(std::shared_ptr spUserApiUserCreateWithArrayResource); + virtual void setUserApiUserCreateWithListResource(std::shared_ptr spUserApiUserCreateWithListResource); + virtual void setUserApiUserUsernameResource(std::shared_ptr spUserApiUserUsernameResource); + virtual void setUserApiUserLoginResource(std::shared_ptr spUserApiUserLoginResource); + virtual void setUserApiUserLogoutResource(std::shared_ptr spUserApiUserLogoutResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spUserApiUserResource; + std::shared_ptr m_spUserApiUserCreateWithArrayResource; + std::shared_ptr m_spUserApiUserCreateWithListResource; + std::shared_ptr m_spUserApiUserUsernameResource; + std::shared_ptr m_spUserApiUserLoginResource; + std::shared_ptr m_spUserApiUserLogoutResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* UserApi_H_ */ + diff --git a/samples/server/petstore/cpp-restbed-deprecated/git_push.sh b/samples/server/petstore/cpp-restbed-deprecated/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/server/petstore/cpp-restbed/model/ApiResponse.cpp b/samples/server/petstore/cpp-restbed-deprecated/model/ApiResponse.cpp similarity index 100% rename from samples/server/petstore/cpp-restbed/model/ApiResponse.cpp rename to samples/server/petstore/cpp-restbed-deprecated/model/ApiResponse.cpp diff --git a/samples/server/petstore/cpp-restbed-deprecated/model/ApiResponse.h b/samples/server/petstore/cpp-restbed-deprecated/model/ApiResponse.h new file mode 100644 index 0000000000..bbf3b51f49 --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/model/ApiResponse.h @@ -0,0 +1,94 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ApiResponse.h + * + * Describes the result of uploading an image resource + */ + +#ifndef ApiResponse_H_ +#define ApiResponse_H_ + + + +#include +#include +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// Describes the result of uploading an image resource +/// +class ApiResponse +{ +public: + ApiResponse() = default; + explicit ApiResponse(boost::property_tree::ptree const& pt); + virtual ~ApiResponse() = default; + + std::string toJsonString(bool prettyJson = false); + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree(); + void fromPropertyTree(boost::property_tree::ptree const& pt); + + ///////////////////////////////////////////// + /// ApiResponse members + + /// + /// + /// + int32_t getCode() const; + void setCode(int32_t value); + + /// + /// + /// + std::string getType() const; + void setType(std::string value); + + /// + /// + /// + std::string getMessage() const; + void setMessage(std::string value); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int32_t m_Code = 0; + std::string m_Type = ""; + std::string m_Message = ""; +}; + +std::vector createApiResponseVectorFromJsonString(const std::string& json); + +} +} +} +} + +#endif /* ApiResponse_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/Category.cpp b/samples/server/petstore/cpp-restbed-deprecated/model/Category.cpp similarity index 100% rename from samples/server/petstore/cpp-restbed/model/Category.cpp rename to samples/server/petstore/cpp-restbed-deprecated/model/Category.cpp diff --git a/samples/server/petstore/cpp-restbed-deprecated/model/Category.h b/samples/server/petstore/cpp-restbed-deprecated/model/Category.h new file mode 100644 index 0000000000..879b425a7d --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/model/Category.h @@ -0,0 +1,87 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Category.h + * + * A category for a pet + */ + +#ifndef Category_H_ +#define Category_H_ + + + +#include +#include +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// A category for a pet +/// +class Category +{ +public: + Category() = default; + explicit Category(boost::property_tree::ptree const& pt); + virtual ~Category() = default; + + std::string toJsonString(bool prettyJson = false); + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree(); + void fromPropertyTree(boost::property_tree::ptree const& pt); + + ///////////////////////////////////////////// + /// Category members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + std::string getName() const; + void setName(std::string value); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; + std::string m_Name = ""; +}; + +std::vector createCategoryVectorFromJsonString(const std::string& json); + +} +} +} +} + +#endif /* Category_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/Order.cpp b/samples/server/petstore/cpp-restbed-deprecated/model/Order.cpp similarity index 100% rename from samples/server/petstore/cpp-restbed/model/Order.cpp rename to samples/server/petstore/cpp-restbed-deprecated/model/Order.cpp diff --git a/samples/server/petstore/cpp-restbed-deprecated/model/Order.h b/samples/server/petstore/cpp-restbed-deprecated/model/Order.h new file mode 100644 index 0000000000..1eac0e12fa --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/model/Order.h @@ -0,0 +1,121 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Order.h + * + * An order for a pets from the pet store + */ + +#ifndef Order_H_ +#define Order_H_ + + + +#include +#include +#include +#include +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// An order for a pets from the pet store +/// +class Order +{ +public: + Order() = default; + explicit Order(boost::property_tree::ptree const& pt); + virtual ~Order() = default; + + std::string toJsonString(bool prettyJson = false); + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree(); + void fromPropertyTree(boost::property_tree::ptree const& pt); + + ///////////////////////////////////////////// + /// Order members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + int64_t getPetId() const; + void setPetId(int64_t value); + + /// + /// + /// + int32_t getQuantity() const; + void setQuantity(int32_t value); + + /// + /// + /// + std::string getShipDate() const; + void setShipDate(std::string value); + + /// + /// Order Status + /// + std::string getStatus() const; + void setStatus(std::string value); + + /// + /// + /// + bool isComplete() const; + void setComplete(bool value); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; + int64_t m_PetId = 0L; + int32_t m_Quantity = 0; + std::string m_ShipDate = ""; + std::string m_Status = ""; + bool m_Complete = false; + const std::array m_StatusEnum = { + "placed","approved","delivered" + }; + +}; + +std::vector createOrderVectorFromJsonString(const std::string& json); + +} +} +} +} + +#endif /* Order_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/Pet.cpp b/samples/server/petstore/cpp-restbed-deprecated/model/Pet.cpp similarity index 100% rename from samples/server/petstore/cpp-restbed/model/Pet.cpp rename to samples/server/petstore/cpp-restbed-deprecated/model/Pet.cpp diff --git a/samples/server/petstore/cpp-restbed-deprecated/model/Pet.h b/samples/server/petstore/cpp-restbed-deprecated/model/Pet.h new file mode 100644 index 0000000000..0ee153980c --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/model/Pet.h @@ -0,0 +1,123 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Pet.h + * + * A pet for sale in the pet store + */ + +#ifndef Pet_H_ +#define Pet_H_ + + + +#include "Tag.h" +#include +#include "Category.h" +#include +#include +#include +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// A pet for sale in the pet store +/// +class Pet +{ +public: + Pet() = default; + explicit Pet(boost::property_tree::ptree const& pt); + virtual ~Pet() = default; + + std::string toJsonString(bool prettyJson = false); + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree(); + void fromPropertyTree(boost::property_tree::ptree const& pt); + + ///////////////////////////////////////////// + /// Pet members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + std::shared_ptr getCategory() const; + void setCategory(std::shared_ptr value); + + /// + /// + /// + std::string getName() const; + void setName(std::string value); + + /// + /// + /// + std::vector getPhotoUrls() const; + void setPhotoUrls(std::vector value); + + /// + /// + /// + std::vector> getTags() const; + void setTags(std::vector> value); + + /// + /// pet status in the store + /// + std::string getStatus() const; + void setStatus(std::string value); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; + std::shared_ptr m_Category; + std::string m_Name = ""; + std::vector m_PhotoUrls; + std::vector> m_Tags; + std::string m_Status = ""; + const std::array m_StatusEnum = { + "available","pending","sold" + }; + +}; + +std::vector createPetVectorFromJsonString(const std::string& json); + +} +} +} +} + +#endif /* Pet_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/Tag.cpp b/samples/server/petstore/cpp-restbed-deprecated/model/Tag.cpp similarity index 100% rename from samples/server/petstore/cpp-restbed/model/Tag.cpp rename to samples/server/petstore/cpp-restbed-deprecated/model/Tag.cpp diff --git a/samples/server/petstore/cpp-restbed-deprecated/model/Tag.h b/samples/server/petstore/cpp-restbed-deprecated/model/Tag.h new file mode 100644 index 0000000000..8900346ad4 --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/model/Tag.h @@ -0,0 +1,87 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Tag.h + * + * A tag for a pet + */ + +#ifndef Tag_H_ +#define Tag_H_ + + + +#include +#include +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// A tag for a pet +/// +class Tag +{ +public: + Tag() = default; + explicit Tag(boost::property_tree::ptree const& pt); + virtual ~Tag() = default; + + std::string toJsonString(bool prettyJson = false); + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree(); + void fromPropertyTree(boost::property_tree::ptree const& pt); + + ///////////////////////////////////////////// + /// Tag members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + std::string getName() const; + void setName(std::string value); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; + std::string m_Name = ""; +}; + +std::vector createTagVectorFromJsonString(const std::string& json); + +} +} +} +} + +#endif /* Tag_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/User.cpp b/samples/server/petstore/cpp-restbed-deprecated/model/User.cpp similarity index 100% rename from samples/server/petstore/cpp-restbed/model/User.cpp rename to samples/server/petstore/cpp-restbed-deprecated/model/User.cpp diff --git a/samples/server/petstore/cpp-restbed-deprecated/model/User.h b/samples/server/petstore/cpp-restbed-deprecated/model/User.h new file mode 100644 index 0000000000..0f62e4e715 --- /dev/null +++ b/samples/server/petstore/cpp-restbed-deprecated/model/User.h @@ -0,0 +1,129 @@ +/** + * 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. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator unset. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * User.h + * + * A User who is purchasing from the pet store + */ + +#ifndef User_H_ +#define User_H_ + + + +#include +#include +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// A User who is purchasing from the pet store +/// +class User +{ +public: + User() = default; + explicit User(boost::property_tree::ptree const& pt); + virtual ~User() = default; + + std::string toJsonString(bool prettyJson = false); + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree(); + void fromPropertyTree(boost::property_tree::ptree const& pt); + + ///////////////////////////////////////////// + /// User members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + std::string getUsername() const; + void setUsername(std::string value); + + /// + /// + /// + std::string getFirstName() const; + void setFirstName(std::string value); + + /// + /// + /// + std::string getLastName() const; + void setLastName(std::string value); + + /// + /// + /// + std::string getEmail() const; + void setEmail(std::string value); + + /// + /// + /// + std::string getPassword() const; + void setPassword(std::string value); + + /// + /// + /// + std::string getPhone() const; + void setPhone(std::string value); + + /// + /// User Status + /// + int32_t getUserStatus() const; + void setUserStatus(int32_t value); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; + std::string m_Username = ""; + std::string m_FirstName = ""; + std::string m_LastName = ""; + std::string m_Email = ""; + std::string m_Password = ""; + std::string m_Phone = ""; + int32_t m_UserStatus = 0; +}; + +std::vector createUserVectorFromJsonString(const std::string& json); + +} +} +} +} + +#endif /* User_H_ */ diff --git a/samples/server/petstore/cpp-restbed/.gitignore b/samples/server/petstore/cpp-restbed/.gitignore index 4581ef2eee..7a62dc6286 100644 --- a/samples/server/petstore/cpp-restbed/.gitignore +++ b/samples/server/petstore/cpp-restbed/.gitignore @@ -1,29 +1,4 @@ -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app +build/ +.idea/ +cmake-build-*/ +*.received.txt diff --git a/samples/server/petstore/cpp-restbed/.openapi-generator/FILES b/samples/server/petstore/cpp-restbed/.openapi-generator/FILES deleted file mode 100644 index f4948ccd7a..0000000000 --- a/samples/server/petstore/cpp-restbed/.openapi-generator/FILES +++ /dev/null @@ -1,21 +0,0 @@ -.gitignore -README.md -api/PetApi.cpp -api/PetApi.h -api/StoreApi.cpp -api/StoreApi.h -api/UserApi.cpp -api/UserApi.h -git_push.sh -model/ApiResponse.cpp -model/ApiResponse.h -model/Category.cpp -model/Category.h -model/Order.cpp -model/Order.h -model/Pet.cpp -model/Pet.h -model/Tag.cpp -model/Tag.h -model/User.cpp -model/User.h diff --git a/samples/server/petstore/cpp-restbed/CMakeLists.txt b/samples/server/petstore/cpp-restbed/CMakeLists.txt new file mode 100644 index 0000000000..bd938a33b5 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_policy(SET CMP0048 NEW) + +project(cpp-restped-server-open-api VERSION 1) +cmake_minimum_required(VERSION 3.16) + +set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH}) +message(${CMAKE_MODULE_PATH}) + +include(dependencies) +include(JavaClientTests) + + +set(CMAKE_CXX_STANDARD 14) + +# Coverage +if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-instr-generate -fcoverage-mapping") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-instr-generate -fcoverage-mapping") + message("Using clang coverage") +elseif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --coverage") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --coverage") +endif() + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") +set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} -lpthread) + +enable_testing() + +add_subdirectory(generated/3_0) +add_subdirectory(test) diff --git a/samples/server/petstore/cpp-restbed/api/PetApi.cpp b/samples/server/petstore/cpp-restbed/api/PetApi.cpp deleted file mode 100644 index 65b08975be..0000000000 --- a/samples/server/petstore/cpp-restbed/api/PetApi.cpp +++ /dev/null @@ -1,803 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "PetApi.h" - -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; - -PetApiException::PetApiException(int status_code, std::string what) - : m_status(status_code), - m_what(what) -{ - -} -int PetApiException::getStatus() const -{ - return m_status; -} -const char* PetApiException::what() const noexcept -{ - return m_what.c_str(); -} - - -template -std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) -{ - std::stringstream sstream(bodyContent); - boost::property_tree::ptree pt; - boost::property_tree::json_parser::read_json(sstream, pt); - - auto model = std::make_shared(pt); - return model; -} - -template -std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) -{ - std::stringstream sstream(bodyContent); - boost::property_tree::ptree pt; - boost::property_tree::json_parser::read_json(sstream, pt); - - auto arrayRet = std::vector>(); - for (const auto& child: pt) { - arrayRet.emplace_back(std::make_shared(child.second)); - } - return arrayRet; -} - -template -std::string convertMapResponse(const std::map& map) -{ - boost::property_tree::ptree pt; - for(const auto &kv: map) { - pt.push_back(boost::property_tree::ptree::value_type( - boost::lexical_cast(kv.first), - boost::property_tree::ptree( - boost::lexical_cast(kv.second)))); - } - std::stringstream sstream; - write_json(sstream, pt); - std::string result = sstream.str(); - return result; -} - -PetApiPetResource::PetApiPetResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/pet/"); - this->set_method_handler("POST", - std::bind(&PetApiPetResource::handler_POST_internal, this, - std::placeholders::_1)); - this->set_method_handler("PUT", - std::bind(&PetApiPetResource::handler_PUT_internal, this, - std::placeholders::_1)); -} - -PetApiPetResource::~PetApiPetResource() -{ -} - -std::pair PetApiPetResource::handlePetApiException(const PetApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair PetApiPetResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair PetApiPetResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void PetApiPetResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void PetApiPetResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void PetApiPetResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void PetApiPetResource::handler_POST_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - std::string bodyContent = extractBodyContent(session); - - // Get body params or form params here from the body content string - auto body = extractJsonModelBodyParam(bodyContent); - - - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_POST(body); - } - catch(const PetApiException& e) { - std::tie(status_code, result) = handlePetApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 405) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 405, result.empty() ? "Invalid input" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - -// x-extension -void PetApiPetResource::handler_PUT_internal(const std::shared_ptr session) { - - const auto request = session->get_request(); - std::string bodyContent = extractBodyContent(session); - - // body params or form params here from the body content string - auto body = extractJsonModelBodyParam(bodyContent); - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_PUT(body); - } - catch(const PetApiException& e) { - std::tie(status_code, result) = handlePetApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); - return; - } - if (status_code == 404) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 404, result.empty() ? "Pet not found" : result, contentType); - return; - } - if (status_code == 405) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 405, result.empty() ? "Validation exception" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - -int PetApiPetResource::handler_POST( - std::shared_ptr const & body) -{ - throw PetApiException(501, "Not implemented"); -} - -int PetApiPetResource::handler_PUT( - std::shared_ptr const & body) -{ - throw PetApiException(501, "Not implemented"); -} - -std::string PetApiPetResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -PetApiPetPetIdResource::PetApiPetPetIdResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/pet/{petId: .*}/"); - this->set_method_handler("DELETE", - std::bind(&PetApiPetPetIdResource::handler_DELETE_internal, this, - std::placeholders::_1)); - this->set_method_handler("GET", - std::bind(&PetApiPetPetIdResource::handler_GET_internal, this, - std::placeholders::_1)); - this->set_method_handler("POST", - std::bind(&PetApiPetPetIdResource::handler_POST_internal, this, - std::placeholders::_1)); -} - -PetApiPetPetIdResource::~PetApiPetPetIdResource() -{ -} - -std::pair PetApiPetPetIdResource::handlePetApiException(const PetApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair PetApiPetPetIdResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair PetApiPetPetIdResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void PetApiPetPetIdResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void PetApiPetPetIdResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void PetApiPetPetIdResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void PetApiPetPetIdResource::handler_DELETE_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - - // Getting the path params - const int64_t petId = getPathParam_petId(request); - - - // Getting the headers - const std::string apiKey = getHeader_api_key(request); - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_DELETE(petId, apiKey); - } - catch(const PetApiException& e) { - std::tie(status_code, result) = handlePetApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid pet value" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - -// x-extension -void PetApiPetPetIdResource::handler_GET_internal(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const int64_t petId = getPathParam_petId_x_extension(request); - - - int status_code = 500; - std::shared_ptr resultObject = std::make_shared(); - std::string result = ""; - - try { - std::tie(status_code, resultObject) = - handler_GET(petId); - } - catch(const PetApiException& e) { - std::tie(status_code, result) = handlePetApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 200) { - result = resultObject->toJsonString(); - - const constexpr auto contentType = "application/json"; - returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); - return; - } - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); - return; - } - if (status_code == 404) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 404, result.empty() ? "Pet not found" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} -// x-extension -void PetApiPetPetIdResource::handler_POST_internal(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const int64_t petId = getPathParam_petId_x_extension(request); - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_POST(petId, name, status); - } - catch(const PetApiException& e) { - std::tie(status_code, result) = handlePetApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 405) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 405, result.empty() ? "Invalid input" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - -int PetApiPetPetIdResource::handler_DELETE( - int64_t const & petId, std::string const & apiKey) -{ - throw PetApiException(501, "Not implemented"); -} - -std::pair> PetApiPetPetIdResource::handler_GET( - int64_t const & petId) -{ - throw PetApiException(501, "Not implemented"); -} -int PetApiPetPetIdResource::handler_POST( - int64_t const & petId, std::string const & name, std::string const & status) -{ - throw PetApiException(501, "Not implemented"); -} - -std::string PetApiPetPetIdResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -PetApiPetFindByStatusResource::PetApiPetFindByStatusResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/pet/findByStatus/"); - this->set_method_handler("GET", - std::bind(&PetApiPetFindByStatusResource::handler_GET_internal, this, - std::placeholders::_1)); -} - -PetApiPetFindByStatusResource::~PetApiPetFindByStatusResource() -{ -} - -std::pair PetApiPetFindByStatusResource::handlePetApiException(const PetApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair PetApiPetFindByStatusResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair PetApiPetFindByStatusResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void PetApiPetFindByStatusResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void PetApiPetFindByStatusResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void PetApiPetFindByStatusResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void PetApiPetFindByStatusResource::handler_GET_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - - - // Getting the query params - - - int status_code = 500; - std::vector> resultObject = std::vector>(); - std::string result = ""; - - try { - std::tie(status_code, resultObject) = - handler_GET(status); - } - catch(const PetApiException& e) { - std::tie(status_code, result) = handlePetApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 200) { - - const constexpr auto contentType = "application/json"; - returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); - return; - } - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid status value" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -std::pair>> PetApiPetFindByStatusResource::handler_GET( - std::vector const & status) -{ - throw PetApiException(501, "Not implemented"); -} - - -std::string PetApiPetFindByStatusResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -PetApiPetFindByTagsResource::PetApiPetFindByTagsResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/pet/findByTags/"); - this->set_method_handler("GET", - std::bind(&PetApiPetFindByTagsResource::handler_GET_internal, this, - std::placeholders::_1)); -} - -PetApiPetFindByTagsResource::~PetApiPetFindByTagsResource() -{ -} - -std::pair PetApiPetFindByTagsResource::handlePetApiException(const PetApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair PetApiPetFindByTagsResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair PetApiPetFindByTagsResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void PetApiPetFindByTagsResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void PetApiPetFindByTagsResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void PetApiPetFindByTagsResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void PetApiPetFindByTagsResource::handler_GET_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - - - // Getting the query params - - - int status_code = 500; - std::vector> resultObject = std::vector>(); - std::string result = ""; - - try { - std::tie(status_code, resultObject) = - handler_GET(tags); - } - catch(const PetApiException& e) { - std::tie(status_code, result) = handlePetApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 200) { - - const constexpr auto contentType = "application/json"; - returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); - return; - } - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid tag value" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -std::pair>> PetApiPetFindByTagsResource::handler_GET( - std::vector const & tags) -{ - throw PetApiException(501, "Not implemented"); -} - - -std::string PetApiPetFindByTagsResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -PetApiPetPetIdUploadImageResource::PetApiPetPetIdUploadImageResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/pet/{petId: .*}/uploadImage/"); - this->set_method_handler("POST", - std::bind(&PetApiPetPetIdUploadImageResource::handler_POST_internal, this, - std::placeholders::_1)); -} - -PetApiPetPetIdUploadImageResource::~PetApiPetPetIdUploadImageResource() -{ -} - -std::pair PetApiPetPetIdUploadImageResource::handlePetApiException(const PetApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair PetApiPetPetIdUploadImageResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair PetApiPetPetIdUploadImageResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void PetApiPetPetIdUploadImageResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void PetApiPetPetIdUploadImageResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void PetApiPetPetIdUploadImageResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void PetApiPetPetIdUploadImageResource::handler_POST_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - - // Getting the path params - const int64_t petId = getPathParam_petId(request); - - - - int status_code = 500; - std::shared_ptr resultObject = std::make_shared(); - std::string result = ""; - - try { - std::tie(status_code, resultObject) = - handler_POST(petId, additionalMetadata, file); - } - catch(const PetApiException& e) { - std::tie(status_code, result) = handlePetApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 200) { - result = resultObject->toJsonString(); - - const constexpr auto contentType = "application/json"; - returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -std::pair> PetApiPetPetIdUploadImageResource::handler_POST( - int64_t const & petId, std::string const & additionalMetadata, std::string const & file) -{ - throw PetApiException(501, "Not implemented"); -} - - -std::string PetApiPetPetIdUploadImageResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} - -PetApi::PetApi(std::shared_ptr const& restbedService) -: m_service(restbedService) -{ -} - -PetApi::~PetApi() {} - -void PetApi::setPetApiPetResource(std::shared_ptr spPetApiPetResource) { - m_spPetApiPetResource = spPetApiPetResource; - m_service->publish(m_spPetApiPetResource); -} -void PetApi::setPetApiPetPetIdResource(std::shared_ptr spPetApiPetPetIdResource) { - m_spPetApiPetPetIdResource = spPetApiPetPetIdResource; - m_service->publish(m_spPetApiPetPetIdResource); -} -void PetApi::setPetApiPetFindByStatusResource(std::shared_ptr spPetApiPetFindByStatusResource) { - m_spPetApiPetFindByStatusResource = spPetApiPetFindByStatusResource; - m_service->publish(m_spPetApiPetFindByStatusResource); -} -void PetApi::setPetApiPetFindByTagsResource(std::shared_ptr spPetApiPetFindByTagsResource) { - m_spPetApiPetFindByTagsResource = spPetApiPetFindByTagsResource; - m_service->publish(m_spPetApiPetFindByTagsResource); -} -void PetApi::setPetApiPetPetIdUploadImageResource(std::shared_ptr spPetApiPetPetIdUploadImageResource) { - m_spPetApiPetPetIdUploadImageResource = spPetApiPetPetIdUploadImageResource; - m_service->publish(m_spPetApiPetPetIdUploadImageResource); -} - - -void PetApi::publishDefaultResources() { - if (!m_spPetApiPetResource) { - setPetApiPetResource(std::make_shared()); - } - if (!m_spPetApiPetPetIdResource) { - setPetApiPetPetIdResource(std::make_shared()); - } - if (!m_spPetApiPetFindByStatusResource) { - setPetApiPetFindByStatusResource(std::make_shared()); - } - if (!m_spPetApiPetFindByTagsResource) { - setPetApiPetFindByTagsResource(std::make_shared()); - } - if (!m_spPetApiPetPetIdUploadImageResource) { - setPetApiPetPetIdUploadImageResource(std::make_shared()); - } -} - -std::shared_ptr PetApi::service() { - return m_service; -} - - -} -} -} -} - diff --git a/samples/server/petstore/cpp-restbed/api/PetApi.h b/samples/server/petstore/cpp-restbed/api/PetApi.h deleted file mode 100644 index 09a6770a95..0000000000 --- a/samples/server/petstore/cpp-restbed/api/PetApi.h +++ /dev/null @@ -1,370 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/* - * PetApi.h - * - * - */ - -#ifndef PetApi_H_ -#define PetApi_H_ - - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "ApiResponse.h" -#include "Pet.h" -#include - -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; - -/// -/// Exception to flag problems in the handlers -/// -class PetApiException: public std::exception -{ -public: - PetApiException(int status_code, std::string what); - - int getStatus() const; - const char* what() const noexcept override; - -private: - int m_status; - std::string m_what; -}; - -/// -/// Add a new pet to the store -/// -/// -/// -/// -class PetApiPetResource: public restbed::Resource -{ -public: - PetApiPetResource(const std::string& context = "/v2"); - virtual ~PetApiPetResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual int handler_POST( - std::shared_ptr const & body); - - virtual int handler_PUT( - std::shared_ptr const & body); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - - - virtual std::pair handlePetApiException(const PetApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_POST_internal(const std::shared_ptr session); - void handler_PUT_internal(const std::shared_ptr session); -}; - - -/// -/// Deletes a pet -/// -/// -/// -/// -class PetApiPetPetIdResource: public restbed::Resource -{ -public: - PetApiPetPetIdResource(const std::string& context = "/v2"); - virtual ~PetApiPetPetIdResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual int handler_DELETE( - int64_t const & petId, std::string const & apiKey); - - virtual std::pair> handler_GET( - int64_t const & petId); - virtual int handler_POST( - int64_t const & petId, std::string const & name, std::string const & status); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - virtual int64_t getPathParam_petId(const std::shared_ptr& request) - { - return request->get_path_parameter("petId", 0L); - } - - virtual std::string getHeader_api_key(const std::shared_ptr& request) - { - return request->get_header("api_key", ""); - } - - - virtual int64_t getPathParam_petId_x_extension(const std::shared_ptr& request) - { - return request->get_path_parameter("petId", 0L); - } - virtual int64_t getPathParam_petId_x_extension(const std::shared_ptr& request) - { - return request->get_path_parameter("petId", 0L); - } - - virtual std::pair handlePetApiException(const PetApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_DELETE_internal(const std::shared_ptr session); - void handler_GET_internal(const std::shared_ptr session); - void handler_POST_internal(const std::shared_ptr session); -}; - - -/// -/// Finds Pets by status -/// -/// -/// Multiple status values can be provided with comma separated strings -/// -class PetApiPetFindByStatusResource: public restbed::Resource -{ -public: - PetApiPetFindByStatusResource(const std::string& context = "/v2"); - virtual ~PetApiPetFindByStatusResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual std::pair>> handler_GET( - std::vector const & status); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - - - virtual std::pair handlePetApiException(const PetApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_GET_internal(const std::shared_ptr session); -}; - - -/// -/// Finds Pets by tags -/// -/// -/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -/// -class PetApiPetFindByTagsResource: public restbed::Resource -{ -public: - PetApiPetFindByTagsResource(const std::string& context = "/v2"); - virtual ~PetApiPetFindByTagsResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual std::pair>> handler_GET( - std::vector const & tags); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - - - virtual std::pair handlePetApiException(const PetApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_GET_internal(const std::shared_ptr session); -}; - - -/// -/// uploads an image -/// -/// -/// -/// -class PetApiPetPetIdUploadImageResource: public restbed::Resource -{ -public: - PetApiPetPetIdUploadImageResource(const std::string& context = "/v2"); - virtual ~PetApiPetPetIdUploadImageResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual std::pair> handler_POST( - int64_t const & petId, std::string const & additionalMetadata, std::string const & file); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - virtual int64_t getPathParam_petId(const std::shared_ptr& request) - { - return request->get_path_parameter("petId", 0L); - } - - - - virtual std::pair handlePetApiException(const PetApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_POST_internal(const std::shared_ptr session); -}; - - - -// -// The restbed service to actually implement the REST server -// -class PetApi -{ -public: - explicit PetApi(std::shared_ptr const& restbedService); - virtual ~PetApi(); - - virtual void setPetApiPetResource(std::shared_ptr spPetApiPetResource); - virtual void setPetApiPetPetIdResource(std::shared_ptr spPetApiPetPetIdResource); - virtual void setPetApiPetFindByStatusResource(std::shared_ptr spPetApiPetFindByStatusResource); - virtual void setPetApiPetFindByTagsResource(std::shared_ptr spPetApiPetFindByTagsResource); - virtual void setPetApiPetPetIdUploadImageResource(std::shared_ptr spPetApiPetPetIdUploadImageResource); - - virtual void publishDefaultResources(); - - virtual std::shared_ptr service(); - -protected: - std::shared_ptr m_spPetApiPetResource; - std::shared_ptr m_spPetApiPetPetIdResource; - std::shared_ptr m_spPetApiPetFindByStatusResource; - std::shared_ptr m_spPetApiPetFindByTagsResource; - std::shared_ptr m_spPetApiPetPetIdUploadImageResource; - -private: - std::shared_ptr m_service; -}; - - -} -} -} -} - -#endif /* PetApi_H_ */ - diff --git a/samples/server/petstore/cpp-restbed/api/StoreApi.cpp b/samples/server/petstore/cpp-restbed/api/StoreApi.cpp deleted file mode 100644 index 784232c611..0000000000 --- a/samples/server/petstore/cpp-restbed/api/StoreApi.cpp +++ /dev/null @@ -1,496 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "StoreApi.h" - -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; - -StoreApiException::StoreApiException(int status_code, std::string what) - : m_status(status_code), - m_what(what) -{ - -} -int StoreApiException::getStatus() const -{ - return m_status; -} -const char* StoreApiException::what() const noexcept -{ - return m_what.c_str(); -} - - -template -std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) -{ - std::stringstream sstream(bodyContent); - boost::property_tree::ptree pt; - boost::property_tree::json_parser::read_json(sstream, pt); - - auto model = std::make_shared(pt); - return model; -} - -template -std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) -{ - std::stringstream sstream(bodyContent); - boost::property_tree::ptree pt; - boost::property_tree::json_parser::read_json(sstream, pt); - - auto arrayRet = std::vector>(); - for (const auto& child: pt) { - arrayRet.emplace_back(std::make_shared(child.second)); - } - return arrayRet; -} - -template -std::string convertMapResponse(const std::map& map) -{ - boost::property_tree::ptree pt; - for(const auto &kv: map) { - pt.push_back(boost::property_tree::ptree::value_type( - boost::lexical_cast(kv.first), - boost::property_tree::ptree( - boost::lexical_cast(kv.second)))); - } - std::stringstream sstream; - write_json(sstream, pt); - std::string result = sstream.str(); - return result; -} - -StoreApiStoreOrderOrderIdResource::StoreApiStoreOrderOrderIdResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/store/order/{orderId: .*}/"); - this->set_method_handler("DELETE", - std::bind(&StoreApiStoreOrderOrderIdResource::handler_DELETE_internal, this, - std::placeholders::_1)); - this->set_method_handler("GET", - std::bind(&StoreApiStoreOrderOrderIdResource::handler_GET_internal, this, - std::placeholders::_1)); -} - -StoreApiStoreOrderOrderIdResource::~StoreApiStoreOrderOrderIdResource() -{ -} - -std::pair StoreApiStoreOrderOrderIdResource::handleStoreApiException(const StoreApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair StoreApiStoreOrderOrderIdResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair StoreApiStoreOrderOrderIdResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void StoreApiStoreOrderOrderIdResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void StoreApiStoreOrderOrderIdResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void StoreApiStoreOrderOrderIdResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void StoreApiStoreOrderOrderIdResource::handler_DELETE_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - - // Getting the path params - const std::string orderId = getPathParam_orderId(request); - - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_DELETE(orderId); - } - catch(const StoreApiException& e) { - std::tie(status_code, result) = handleStoreApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); - return; - } - if (status_code == 404) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 404, result.empty() ? "Order not found" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - -// x-extension -void StoreApiStoreOrderOrderIdResource::handler_GET_internal(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const int64_t orderId = getPathParam_orderId_x_extension(request); - - - int status_code = 500; - std::shared_ptr resultObject = std::make_shared(); - std::string result = ""; - - try { - std::tie(status_code, resultObject) = - handler_GET(orderId); - } - catch(const StoreApiException& e) { - std::tie(status_code, result) = handleStoreApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 200) { - result = resultObject->toJsonString(); - - const constexpr auto contentType = "application/json"; - returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); - return; - } - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); - return; - } - if (status_code == 404) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 404, result.empty() ? "Order not found" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - -int StoreApiStoreOrderOrderIdResource::handler_DELETE( - std::string const & orderId) -{ - throw StoreApiException(501, "Not implemented"); -} - -std::pair> StoreApiStoreOrderOrderIdResource::handler_GET( - int64_t const & orderId) -{ - throw StoreApiException(501, "Not implemented"); -} - -std::string StoreApiStoreOrderOrderIdResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -StoreApiStoreInventoryResource::StoreApiStoreInventoryResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/store/inventory/"); - this->set_method_handler("GET", - std::bind(&StoreApiStoreInventoryResource::handler_GET_internal, this, - std::placeholders::_1)); -} - -StoreApiStoreInventoryResource::~StoreApiStoreInventoryResource() -{ -} - -std::pair StoreApiStoreInventoryResource::handleStoreApiException(const StoreApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair StoreApiStoreInventoryResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair StoreApiStoreInventoryResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void StoreApiStoreInventoryResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void StoreApiStoreInventoryResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void StoreApiStoreInventoryResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void StoreApiStoreInventoryResource::handler_GET_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - - - - - int status_code = 500; - std::map resultObject = std::map(); - std::string result = ""; - - try { - std::tie(status_code, resultObject) = - handler_GET(); - } - catch(const StoreApiException& e) { - std::tie(status_code, result) = handleStoreApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 200) { - result = convertMapResponse(resultObject); - - const constexpr auto contentType = "application/json"; - returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -std::pair> StoreApiStoreInventoryResource::handler_GET( - ) -{ - throw StoreApiException(501, "Not implemented"); -} - - -std::string StoreApiStoreInventoryResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -StoreApiStoreOrderResource::StoreApiStoreOrderResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/store/order/"); - this->set_method_handler("POST", - std::bind(&StoreApiStoreOrderResource::handler_POST_internal, this, - std::placeholders::_1)); -} - -StoreApiStoreOrderResource::~StoreApiStoreOrderResource() -{ -} - -std::pair StoreApiStoreOrderResource::handleStoreApiException(const StoreApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair StoreApiStoreOrderResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair StoreApiStoreOrderResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void StoreApiStoreOrderResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void StoreApiStoreOrderResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void StoreApiStoreOrderResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void StoreApiStoreOrderResource::handler_POST_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - std::string bodyContent = extractBodyContent(session); - - // Get body params or form params here from the body content string - auto body = extractJsonModelBodyParam(bodyContent); - - - - - int status_code = 500; - std::shared_ptr resultObject = std::make_shared(); - std::string result = ""; - - try { - std::tie(status_code, resultObject) = - handler_POST(body); - } - catch(const StoreApiException& e) { - std::tie(status_code, result) = handleStoreApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 200) { - result = resultObject->toJsonString(); - - const constexpr auto contentType = "application/json"; - returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); - return; - } - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid Order" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -std::pair> StoreApiStoreOrderResource::handler_POST( - std::shared_ptr const & body) -{ - throw StoreApiException(501, "Not implemented"); -} - - -std::string StoreApiStoreOrderResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} - -StoreApi::StoreApi(std::shared_ptr const& restbedService) -: m_service(restbedService) -{ -} - -StoreApi::~StoreApi() {} - -void StoreApi::setStoreApiStoreOrderOrderIdResource(std::shared_ptr spStoreApiStoreOrderOrderIdResource) { - m_spStoreApiStoreOrderOrderIdResource = spStoreApiStoreOrderOrderIdResource; - m_service->publish(m_spStoreApiStoreOrderOrderIdResource); -} -void StoreApi::setStoreApiStoreInventoryResource(std::shared_ptr spStoreApiStoreInventoryResource) { - m_spStoreApiStoreInventoryResource = spStoreApiStoreInventoryResource; - m_service->publish(m_spStoreApiStoreInventoryResource); -} -void StoreApi::setStoreApiStoreOrderResource(std::shared_ptr spStoreApiStoreOrderResource) { - m_spStoreApiStoreOrderResource = spStoreApiStoreOrderResource; - m_service->publish(m_spStoreApiStoreOrderResource); -} - - -void StoreApi::publishDefaultResources() { - if (!m_spStoreApiStoreOrderOrderIdResource) { - setStoreApiStoreOrderOrderIdResource(std::make_shared()); - } - if (!m_spStoreApiStoreInventoryResource) { - setStoreApiStoreInventoryResource(std::make_shared()); - } - if (!m_spStoreApiStoreOrderResource) { - setStoreApiStoreOrderResource(std::make_shared()); - } -} - -std::shared_ptr StoreApi::service() { - return m_service; -} - - -} -} -} -} - diff --git a/samples/server/petstore/cpp-restbed/api/StoreApi.h b/samples/server/petstore/cpp-restbed/api/StoreApi.h deleted file mode 100644 index 3c14a48c7e..0000000000 --- a/samples/server/petstore/cpp-restbed/api/StoreApi.h +++ /dev/null @@ -1,250 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/* - * StoreApi.h - * - * - */ - -#ifndef StoreApi_H_ -#define StoreApi_H_ - - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "Order.h" -#include -#include - -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; - -/// -/// Exception to flag problems in the handlers -/// -class StoreApiException: public std::exception -{ -public: - StoreApiException(int status_code, std::string what); - - int getStatus() const; - const char* what() const noexcept override; - -private: - int m_status; - std::string m_what; -}; - -/// -/// Delete purchase order by ID -/// -/// -/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -/// -class StoreApiStoreOrderOrderIdResource: public restbed::Resource -{ -public: - StoreApiStoreOrderOrderIdResource(const std::string& context = "/v2"); - virtual ~StoreApiStoreOrderOrderIdResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual int handler_DELETE( - std::string const & orderId); - - virtual std::pair> handler_GET( - int64_t const & orderId); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - virtual std::string getPathParam_orderId(const std::shared_ptr& request) - { - return request->get_path_parameter("orderId", ""); - } - - - virtual int64_t getPathParam_orderId_x_extension(const std::shared_ptr& request) - { - return request->get_path_parameter("orderId", 0L); - } - - virtual std::pair handleStoreApiException(const StoreApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_DELETE_internal(const std::shared_ptr session); - void handler_GET_internal(const std::shared_ptr session); -}; - - -/// -/// Returns pet inventories by status -/// -/// -/// Returns a map of status codes to quantities -/// -class StoreApiStoreInventoryResource: public restbed::Resource -{ -public: - StoreApiStoreInventoryResource(const std::string& context = "/v2"); - virtual ~StoreApiStoreInventoryResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual std::pair> handler_GET( - ); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - - - virtual std::pair handleStoreApiException(const StoreApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_GET_internal(const std::shared_ptr session); -}; - - -/// -/// Place an order for a pet -/// -/// -/// -/// -class StoreApiStoreOrderResource: public restbed::Resource -{ -public: - StoreApiStoreOrderResource(const std::string& context = "/v2"); - virtual ~StoreApiStoreOrderResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual std::pair> handler_POST( - std::shared_ptr const & body); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - - - virtual std::pair handleStoreApiException(const StoreApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_POST_internal(const std::shared_ptr session); -}; - - - -// -// The restbed service to actually implement the REST server -// -class StoreApi -{ -public: - explicit StoreApi(std::shared_ptr const& restbedService); - virtual ~StoreApi(); - - virtual void setStoreApiStoreOrderOrderIdResource(std::shared_ptr spStoreApiStoreOrderOrderIdResource); - virtual void setStoreApiStoreInventoryResource(std::shared_ptr spStoreApiStoreInventoryResource); - virtual void setStoreApiStoreOrderResource(std::shared_ptr spStoreApiStoreOrderResource); - - virtual void publishDefaultResources(); - - virtual std::shared_ptr service(); - -protected: - std::shared_ptr m_spStoreApiStoreOrderOrderIdResource; - std::shared_ptr m_spStoreApiStoreInventoryResource; - std::shared_ptr m_spStoreApiStoreOrderResource; - -private: - std::shared_ptr m_service; -}; - - -} -} -} -} - -#endif /* StoreApi_H_ */ - diff --git a/samples/server/petstore/cpp-restbed/api/UserApi.cpp b/samples/server/petstore/cpp-restbed/api/UserApi.cpp deleted file mode 100644 index c6485c6e12..0000000000 --- a/samples/server/petstore/cpp-restbed/api/UserApi.cpp +++ /dev/null @@ -1,868 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "UserApi.h" - -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; - -UserApiException::UserApiException(int status_code, std::string what) - : m_status(status_code), - m_what(what) -{ - -} -int UserApiException::getStatus() const -{ - return m_status; -} -const char* UserApiException::what() const noexcept -{ - return m_what.c_str(); -} - - -template -std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) -{ - std::stringstream sstream(bodyContent); - boost::property_tree::ptree pt; - boost::property_tree::json_parser::read_json(sstream, pt); - - auto model = std::make_shared(pt); - return model; -} - -template -std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) -{ - std::stringstream sstream(bodyContent); - boost::property_tree::ptree pt; - boost::property_tree::json_parser::read_json(sstream, pt); - - auto arrayRet = std::vector>(); - for (const auto& child: pt) { - arrayRet.emplace_back(std::make_shared(child.second)); - } - return arrayRet; -} - -template -std::string convertMapResponse(const std::map& map) -{ - boost::property_tree::ptree pt; - for(const auto &kv: map) { - pt.push_back(boost::property_tree::ptree::value_type( - boost::lexical_cast(kv.first), - boost::property_tree::ptree( - boost::lexical_cast(kv.second)))); - } - std::stringstream sstream; - write_json(sstream, pt); - std::string result = sstream.str(); - return result; -} - -UserApiUserResource::UserApiUserResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/user/"); - this->set_method_handler("POST", - std::bind(&UserApiUserResource::handler_POST_internal, this, - std::placeholders::_1)); -} - -UserApiUserResource::~UserApiUserResource() -{ -} - -std::pair UserApiUserResource::handleUserApiException(const UserApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair UserApiUserResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair UserApiUserResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void UserApiUserResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void UserApiUserResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void UserApiUserResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void UserApiUserResource::handler_POST_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - std::string bodyContent = extractBodyContent(session); - - // Get body params or form params here from the body content string - auto body = extractJsonModelBodyParam(bodyContent); - - - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_POST(body); - } - catch(const UserApiException& e) { - std::tie(status_code, result) = handleUserApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 0) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -int UserApiUserResource::handler_POST( - std::shared_ptr const & body) -{ - throw UserApiException(501, "Not implemented"); -} - - -std::string UserApiUserResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -UserApiUserCreateWithArrayResource::UserApiUserCreateWithArrayResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/user/createWithArray/"); - this->set_method_handler("POST", - std::bind(&UserApiUserCreateWithArrayResource::handler_POST_internal, this, - std::placeholders::_1)); -} - -UserApiUserCreateWithArrayResource::~UserApiUserCreateWithArrayResource() -{ -} - -std::pair UserApiUserCreateWithArrayResource::handleUserApiException(const UserApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair UserApiUserCreateWithArrayResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair UserApiUserCreateWithArrayResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void UserApiUserCreateWithArrayResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void UserApiUserCreateWithArrayResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void UserApiUserCreateWithArrayResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void UserApiUserCreateWithArrayResource::handler_POST_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - std::string bodyContent = extractBodyContent(session); - - // Get body params or form params here from the body content string - auto body = extractJsonArrayBodyParam(bodyContent); - - - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_POST(body); - } - catch(const UserApiException& e) { - std::tie(status_code, result) = handleUserApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 0) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -int UserApiUserCreateWithArrayResource::handler_POST( - std::vector> const & body) -{ - throw UserApiException(501, "Not implemented"); -} - - -std::string UserApiUserCreateWithArrayResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -UserApiUserCreateWithListResource::UserApiUserCreateWithListResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/user/createWithList/"); - this->set_method_handler("POST", - std::bind(&UserApiUserCreateWithListResource::handler_POST_internal, this, - std::placeholders::_1)); -} - -UserApiUserCreateWithListResource::~UserApiUserCreateWithListResource() -{ -} - -std::pair UserApiUserCreateWithListResource::handleUserApiException(const UserApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair UserApiUserCreateWithListResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair UserApiUserCreateWithListResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void UserApiUserCreateWithListResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void UserApiUserCreateWithListResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void UserApiUserCreateWithListResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void UserApiUserCreateWithListResource::handler_POST_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - std::string bodyContent = extractBodyContent(session); - - // Get body params or form params here from the body content string - auto body = extractJsonArrayBodyParam(bodyContent); - - - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_POST(body); - } - catch(const UserApiException& e) { - std::tie(status_code, result) = handleUserApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 0) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -int UserApiUserCreateWithListResource::handler_POST( - std::vector> const & body) -{ - throw UserApiException(501, "Not implemented"); -} - - -std::string UserApiUserCreateWithListResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -UserApiUserUsernameResource::UserApiUserUsernameResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/user/{username: .*}/"); - this->set_method_handler("DELETE", - std::bind(&UserApiUserUsernameResource::handler_DELETE_internal, this, - std::placeholders::_1)); - this->set_method_handler("GET", - std::bind(&UserApiUserUsernameResource::handler_GET_internal, this, - std::placeholders::_1)); - this->set_method_handler("PUT", - std::bind(&UserApiUserUsernameResource::handler_PUT_internal, this, - std::placeholders::_1)); -} - -UserApiUserUsernameResource::~UserApiUserUsernameResource() -{ -} - -std::pair UserApiUserUsernameResource::handleUserApiException(const UserApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair UserApiUserUsernameResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair UserApiUserUsernameResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void UserApiUserUsernameResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void UserApiUserUsernameResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void UserApiUserUsernameResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void UserApiUserUsernameResource::handler_DELETE_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - - // Getting the path params - const std::string username = getPathParam_username(request); - - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_DELETE(username); - } - catch(const UserApiException& e) { - std::tie(status_code, result) = handleUserApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid username supplied" : result, contentType); - return; - } - if (status_code == 404) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 404, result.empty() ? "User not found" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - -// x-extension -void UserApiUserUsernameResource::handler_GET_internal(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const std::string username = getPathParam_username_x_extension(request); - - - int status_code = 500; - std::shared_ptr resultObject = std::make_shared(); - std::string result = ""; - - try { - std::tie(status_code, resultObject) = - handler_GET(username); - } - catch(const UserApiException& e) { - std::tie(status_code, result) = handleUserApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 200) { - result = resultObject->toJsonString(); - - const constexpr auto contentType = "application/json"; - returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); - return; - } - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid username supplied" : result, contentType); - return; - } - if (status_code == 404) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 404, result.empty() ? "User not found" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} -// x-extension -void UserApiUserUsernameResource::handler_PUT_internal(const std::shared_ptr session) { - - const auto request = session->get_request(); - std::string bodyContent = extractBodyContent(session); - - // body params or form params here from the body content string - auto username = std::make_shared<>(bodyContent); - auto body = extractJsonModelBodyParam(bodyContent); - - // Getting the path params - const std::string username = getPathParam_username_x_extension(request); - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_PUT(username, body); - } - catch(const UserApiException& e) { - std::tie(status_code, result) = handleUserApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid user supplied" : result, contentType); - return; - } - if (status_code == 404) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 404, result.empty() ? "User not found" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - -int UserApiUserUsernameResource::handler_DELETE( - std::string const & username) -{ - throw UserApiException(501, "Not implemented"); -} - -std::pair> UserApiUserUsernameResource::handler_GET( - std::string const & username) -{ - throw UserApiException(501, "Not implemented"); -} -int UserApiUserUsernameResource::handler_PUT( - std::string const & username, std::shared_ptr const & body) -{ - throw UserApiException(501, "Not implemented"); -} - -std::string UserApiUserUsernameResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -UserApiUserLoginResource::UserApiUserLoginResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/user/login/"); - this->set_method_handler("GET", - std::bind(&UserApiUserLoginResource::handler_GET_internal, this, - std::placeholders::_1)); -} - -UserApiUserLoginResource::~UserApiUserLoginResource() -{ -} - -std::pair UserApiUserLoginResource::handleUserApiException(const UserApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair UserApiUserLoginResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair UserApiUserLoginResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void UserApiUserLoginResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void UserApiUserLoginResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void UserApiUserLoginResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void UserApiUserLoginResource::handler_GET_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - - - // Getting the query params - const std::string username = getQueryParam_username(request); - const std::string password = getQueryParam_password(request); - - - int status_code = 500; - std::string resultObject = ""; - std::string result = ""; - - try { - std::tie(status_code, resultObject) = - handler_GET(username, password); - } - catch(const UserApiException& e) { - std::tie(status_code, result) = handleUserApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 200) { - result = resultObject; - // Description: calls per hour allowed by the user - setResponseHeader(session, "X-Rate-Limit"); - // Description: date in UTC when toekn expires - setResponseHeader(session, "X-Expires-After"); - - const constexpr auto contentType = "application/json"; - returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); - return; - } - if (status_code == 400) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 400, result.empty() ? "Invalid username/password supplied" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -std::pair UserApiUserLoginResource::handler_GET( - std::string const & username, std::string const & password) -{ - throw UserApiException(501, "Not implemented"); -} - - -std::string UserApiUserLoginResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} -UserApiUserLogoutResource::UserApiUserLogoutResource(const std::string& context /* = "/v2" */) -{ - this->set_path(context + "/user/logout/"); - this->set_method_handler("GET", - std::bind(&UserApiUserLogoutResource::handler_GET_internal, this, - std::placeholders::_1)); -} - -UserApiUserLogoutResource::~UserApiUserLogoutResource() -{ -} - -std::pair UserApiUserLogoutResource::handleUserApiException(const UserApiException& e) -{ - return std::make_pair(e.getStatus(), e.what()); -} - -std::pair UserApiUserLogoutResource::handleStdException(const std::exception& e) -{ - return std::make_pair(500, e.what()); -} - -std::pair UserApiUserLogoutResource::handleUnspecifiedException() -{ - return std::make_pair(500, "Unknown exception occurred"); -} - -void UserApiUserLogoutResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) -{ - session->set_header(header, ""); -} - -void UserApiUserLogoutResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) -{ - session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); -} - -void UserApiUserLogoutResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) -{ - session->close(status, result, { {"Connection", "close"} }); -} - -void UserApiUserLogoutResource::handler_GET_internal(const std::shared_ptr session) -{ - const auto request = session->get_request(); - - - - - int status_code = 500; - std::string result = ""; - - try { - status_code = - handler_GET(); - } - catch(const UserApiException& e) { - std::tie(status_code, result) = handleUserApiException(e); - } - catch(const std::exception& e) { - std::tie(status_code, result) = handleStdException(e); - } - catch(...) { - std::tie(status_code, result) = handleUnspecifiedException(); - } - - if (status_code == 0) { - - const constexpr auto contentType = "text/plain"; - returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); - return; - } - defaultSessionClose(session, status_code, result); -} - - -int UserApiUserLogoutResource::handler_GET( - ) -{ - throw UserApiException(501, "Not implemented"); -} - - -std::string UserApiUserLogoutResource::extractBodyContent(const std::shared_ptr& session) { - const auto request = session->get_request(); - int content_length = request->get_header("Content-Length", 0); - std::string bodyContent; - session->fetch(content_length, - [&bodyContent](const std::shared_ptr session, - const restbed::Bytes &body) { - bodyContent = restbed::String::format( - "%.*s\n", (int)body.size(), body.data()); - }); - return bodyContent; -} - -UserApi::UserApi(std::shared_ptr const& restbedService) -: m_service(restbedService) -{ -} - -UserApi::~UserApi() {} - -void UserApi::setUserApiUserResource(std::shared_ptr spUserApiUserResource) { - m_spUserApiUserResource = spUserApiUserResource; - m_service->publish(m_spUserApiUserResource); -} -void UserApi::setUserApiUserCreateWithArrayResource(std::shared_ptr spUserApiUserCreateWithArrayResource) { - m_spUserApiUserCreateWithArrayResource = spUserApiUserCreateWithArrayResource; - m_service->publish(m_spUserApiUserCreateWithArrayResource); -} -void UserApi::setUserApiUserCreateWithListResource(std::shared_ptr spUserApiUserCreateWithListResource) { - m_spUserApiUserCreateWithListResource = spUserApiUserCreateWithListResource; - m_service->publish(m_spUserApiUserCreateWithListResource); -} -void UserApi::setUserApiUserUsernameResource(std::shared_ptr spUserApiUserUsernameResource) { - m_spUserApiUserUsernameResource = spUserApiUserUsernameResource; - m_service->publish(m_spUserApiUserUsernameResource); -} -void UserApi::setUserApiUserLoginResource(std::shared_ptr spUserApiUserLoginResource) { - m_spUserApiUserLoginResource = spUserApiUserLoginResource; - m_service->publish(m_spUserApiUserLoginResource); -} -void UserApi::setUserApiUserLogoutResource(std::shared_ptr spUserApiUserLogoutResource) { - m_spUserApiUserLogoutResource = spUserApiUserLogoutResource; - m_service->publish(m_spUserApiUserLogoutResource); -} - - -void UserApi::publishDefaultResources() { - if (!m_spUserApiUserResource) { - setUserApiUserResource(std::make_shared()); - } - if (!m_spUserApiUserCreateWithArrayResource) { - setUserApiUserCreateWithArrayResource(std::make_shared()); - } - if (!m_spUserApiUserCreateWithListResource) { - setUserApiUserCreateWithListResource(std::make_shared()); - } - if (!m_spUserApiUserUsernameResource) { - setUserApiUserUsernameResource(std::make_shared()); - } - if (!m_spUserApiUserLoginResource) { - setUserApiUserLoginResource(std::make_shared()); - } - if (!m_spUserApiUserLogoutResource) { - setUserApiUserLogoutResource(std::make_shared()); - } -} - -std::shared_ptr UserApi::service() { - return m_service; -} - - -} -} -} -} - diff --git a/samples/server/petstore/cpp-restbed/api/UserApi.h b/samples/server/petstore/cpp-restbed/api/UserApi.h deleted file mode 100644 index ce692f0ea7..0000000000 --- a/samples/server/petstore/cpp-restbed/api/UserApi.h +++ /dev/null @@ -1,417 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/* - * UserApi.h - * - * - */ - -#ifndef UserApi_H_ -#define UserApi_H_ - - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "User.h" -#include -#include - -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; - -/// -/// Exception to flag problems in the handlers -/// -class UserApiException: public std::exception -{ -public: - UserApiException(int status_code, std::string what); - - int getStatus() const; - const char* what() const noexcept override; - -private: - int m_status; - std::string m_what; -}; - -/// -/// Create user -/// -/// -/// This can only be done by the logged in user. -/// -class UserApiUserResource: public restbed::Resource -{ -public: - UserApiUserResource(const std::string& context = "/v2"); - virtual ~UserApiUserResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual int handler_POST( - std::shared_ptr const & body); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - - - virtual std::pair handleUserApiException(const UserApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_POST_internal(const std::shared_ptr session); -}; - - -/// -/// Creates list of users with given input array -/// -/// -/// -/// -class UserApiUserCreateWithArrayResource: public restbed::Resource -{ -public: - UserApiUserCreateWithArrayResource(const std::string& context = "/v2"); - virtual ~UserApiUserCreateWithArrayResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual int handler_POST( - std::vector> const & body); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - - - virtual std::pair handleUserApiException(const UserApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_POST_internal(const std::shared_ptr session); -}; - - -/// -/// Creates list of users with given input array -/// -/// -/// -/// -class UserApiUserCreateWithListResource: public restbed::Resource -{ -public: - UserApiUserCreateWithListResource(const std::string& context = "/v2"); - virtual ~UserApiUserCreateWithListResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual int handler_POST( - std::vector> const & body); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - - - virtual std::pair handleUserApiException(const UserApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_POST_internal(const std::shared_ptr session); -}; - - -/// -/// Delete user -/// -/// -/// This can only be done by the logged in user. -/// -class UserApiUserUsernameResource: public restbed::Resource -{ -public: - UserApiUserUsernameResource(const std::string& context = "/v2"); - virtual ~UserApiUserUsernameResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual int handler_DELETE( - std::string const & username); - - virtual std::pair> handler_GET( - std::string const & username); - virtual int handler_PUT( - std::string const & username, std::shared_ptr const & body); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - virtual std::string getPathParam_username(const std::shared_ptr& request) - { - return request->get_path_parameter("username", ""); - } - - - virtual std::string getPathParam_username_x_extension(const std::shared_ptr& request) - { - return request->get_path_parameter("username", ""); - } - virtual std::string getPathParam_username_x_extension(const std::shared_ptr& request) - { - return request->get_path_parameter("username", ""); - } - - virtual std::pair handleUserApiException(const UserApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_DELETE_internal(const std::shared_ptr session); - void handler_GET_internal(const std::shared_ptr session); - void handler_PUT_internal(const std::shared_ptr session); -}; - - -/// -/// Logs user into the system -/// -/// -/// -/// -class UserApiUserLoginResource: public restbed::Resource -{ -public: - UserApiUserLoginResource(const std::string& context = "/v2"); - virtual ~UserApiUserLoginResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual std::pair handler_GET( - std::string const & username, std::string const & password); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - virtual std::string getQueryParam_username(const std::shared_ptr& request) - { - return request->get_query_parameter("username", ""); - } - - virtual std::string getQueryParam_password(const std::shared_ptr& request) - { - return request->get_query_parameter("password", ""); - } - - - - virtual std::pair handleUserApiException(const UserApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_GET_internal(const std::shared_ptr session); -}; - - -/// -/// Logs out current logged in user session -/// -/// -/// -/// -class UserApiUserLogoutResource: public restbed::Resource -{ -public: - UserApiUserLogoutResource(const std::string& context = "/v2"); - virtual ~UserApiUserLogoutResource(); - -protected: - ////////////////////////////////////////////////////////// - // Override these to implement the server functionality // - ////////////////////////////////////////////////////////// - - virtual int handler_GET( - ); - - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string extractBodyContent(const std::shared_ptr& session); - - - - virtual std::pair handleUserApiException(const UserApiException& e); - virtual std::pair handleStdException(const std::exception& e); - virtual std::pair handleUnspecifiedException(); - - virtual void setResponseHeader(const std::shared_ptr& session, - const std::string& header); - - - virtual void returnResponse(const std::shared_ptr& session, - const int status, const std::string& result, const std::string& contentType); - virtual void defaultSessionClose(const std::shared_ptr& session, - const int status, const std::string& result); - -private: - void handler_GET_internal(const std::shared_ptr session); -}; - - - -// -// The restbed service to actually implement the REST server -// -class UserApi -{ -public: - explicit UserApi(std::shared_ptr const& restbedService); - virtual ~UserApi(); - - virtual void setUserApiUserResource(std::shared_ptr spUserApiUserResource); - virtual void setUserApiUserCreateWithArrayResource(std::shared_ptr spUserApiUserCreateWithArrayResource); - virtual void setUserApiUserCreateWithListResource(std::shared_ptr spUserApiUserCreateWithListResource); - virtual void setUserApiUserUsernameResource(std::shared_ptr spUserApiUserUsernameResource); - virtual void setUserApiUserLoginResource(std::shared_ptr spUserApiUserLoginResource); - virtual void setUserApiUserLogoutResource(std::shared_ptr spUserApiUserLogoutResource); - - virtual void publishDefaultResources(); - - virtual std::shared_ptr service(); - -protected: - std::shared_ptr m_spUserApiUserResource; - std::shared_ptr m_spUserApiUserCreateWithArrayResource; - std::shared_ptr m_spUserApiUserCreateWithListResource; - std::shared_ptr m_spUserApiUserUsernameResource; - std::shared_ptr m_spUserApiUserLoginResource; - std::shared_ptr m_spUserApiUserLogoutResource; - -private: - std::shared_ptr m_service; -}; - - -} -} -} -} - -#endif /* UserApi_H_ */ - diff --git a/samples/server/petstore/cpp-restbed/build_and_test.sh b/samples/server/petstore/cpp-restbed/build_and_test.sh new file mode 100755 index 0000000000..9c3064a4db --- /dev/null +++ b/samples/server/petstore/cpp-restbed/build_and_test.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +set -u +set -e + +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) + +cd ${SCRIPT_DIR} + +rm -rf build + +cmake -S . -B build +cd build +make + +# pure C++ tests +make test -j4 + +# tests with Java client +# run them during development +#make run_all_java_client_test_for_cpp_server \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/cmake/JavaClientTests.cmake b/samples/server/petstore/cpp-restbed/cmake/JavaClientTests.cmake new file mode 100644 index 0000000000..46a23d496c --- /dev/null +++ b/samples/server/petstore/cpp-restbed/cmake/JavaClientTests.cmake @@ -0,0 +1,35 @@ + +add_custom_target(run_all_java_client_test_for_cpp_server) + +define_property(GLOBAL + PROPERTY LAST_JAVA_CLIENT_TEST + BRIEF_DOCS Used to order the tests to run after each other + FULL_DOCS The tests are ordered by defining a dependency chain) +set_property(GLOBAL + PROPERTY LAST_JAVA_CLIENT_TEST run_all_java_client_test_for_cpp_server) + +set(RUN_CLIENT_TESTS_SHELL_TEMPLATE "run_java_client_tests_template.txt") + +function(run_java_client_test_for_cpp_server TARGET_NAME) + set(TEST_SERVER_EXECUTABLE "${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}") + + set(RUN_TESTS_TARGET run_${TARGET_NAME}_test) + configure_file(${CMAKE_SOURCE_DIR}/cmake/${RUN_CLIENT_TESTS_SHELL_TEMPLATE} + ${CMAKE_CURRENT_BINARY_DIR}/${RUN_TESTS_TARGET}.sh + @ONLY) + + add_custom_target(${RUN_TESTS_TARGET} + COMMAND ${CMAKE_CURRENT_BINARY_DIR}/${RUN_TESTS_TARGET}.sh + DEPENDS ${TARGET_NAME} + USES_TERMINAL + COMMENT "Running tests: ${TARGET_NAME}") + + get_property(LAST_TEST + GLOBAL + PROPERTY LAST_JAVA_CLIENT_TEST) + add_dependencies(run_all_java_client_test_for_cpp_server ${RUN_TESTS_TARGET}) + add_dependencies(${LAST_TEST} ${RUN_TESTS_TARGET}) + set_property(GLOBAL + PROPERTY LAST_JAVA_CLIENT_TEST ${RUN_TESTS_TARGET}) + +endfunction() diff --git a/samples/server/petstore/cpp-restbed/cmake/dependencies.cmake b/samples/server/petstore/cpp-restbed/cmake/dependencies.cmake new file mode 100644 index 0000000000..f1e1e740ba --- /dev/null +++ b/samples/server/petstore/cpp-restbed/cmake/dependencies.cmake @@ -0,0 +1,25 @@ + + +include(FetchContent) + +## Restbed +FetchContent_Declare( + restbed + GIT_REPOSITORY https://github.com/Corvusoft/restbed + GIT_TAG 4.7 +) + +set(BUILD_TESTS OFF CACHE BOOL "Disable internal restbed tests") +set(BUILD_SSL OFF CACHE BOOL "Disable SSL") +FetchContent_MakeAvailable(restbed) + +FetchContent_GetProperties(restbed) +if(NOT restbed_POPULATED) + + FetchContent_Populate(restbed) + add_subdirectory(${restbed_SOURCE_DIR} ${restbed_BINARY_DIR}) +endif() + + +## Boost +find_package(Boost 1.7.0 COMPONENTS system unit_test_framework REQUIRED) diff --git a/samples/server/petstore/cpp-restbed/cmake/run_java_client_tests_template.txt b/samples/server/petstore/cpp-restbed/cmake/run_java_client_tests_template.txt new file mode 100755 index 0000000000..eaebefd571 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/cmake/run_java_client_tests_template.txt @@ -0,0 +1,28 @@ +#!/bin/bash +set -u +set -e +#set -x + +SCRIPTPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" +echo "Running ${SCRIPTPATH}" + +echo Running @TEST_SERVER_EXECUTABLE@ +@TEST_SERVER_EXECUTABLE@ & +pid=$! + + +function kill_test_server() +{ + kill -9 $pid +} + +trap kill_test_server EXIT + +echo Running Java client tests +cd "@CMAKE_CURRENT_LIST_DIR@/../../java_client" +./gradlew --no-daemon clean test --tests "test_@TARGET_NAME@.*" -i + +set +e +kill $pid + +echo Done running @TEST_SERVER_EXECUTABLE@ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/.gitignore b/samples/server/petstore/cpp-restbed/generated/3_0/.gitignore new file mode 100644 index 0000000000..4581ef2eee --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/.gitignore @@ -0,0 +1,29 @@ +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator-ignore b/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/.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/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/FILES b/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/FILES new file mode 100644 index 0000000000..ab1dc1a7a7 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/FILES @@ -0,0 +1,116 @@ +.gitignore +CMakeLists.txt +FindRestbedAndBoost.cmake +README.md +api/AnotherFakeApi.cpp +api/AnotherFakeApi.h +api/DefaultApi.cpp +api/DefaultApi.h +api/FakeApi.cpp +api/FakeApi.h +api/FakeClassnameTags123Api.cpp +api/FakeClassnameTags123Api.h +api/PetApi.cpp +api/PetApi.h +api/StoreApi.cpp +api/StoreApi.h +api/UserApi.cpp +api/UserApi.h +git_push.sh +model/AdditionalPropertiesClass.cpp +model/AdditionalPropertiesClass.h +model/AllOfWithSingleRef.cpp +model/AllOfWithSingleRef.h +model/Animal.cpp +model/Animal.h +model/ApiResponse.cpp +model/ApiResponse.h +model/ArrayOfArrayOfNumberOnly.cpp +model/ArrayOfArrayOfNumberOnly.h +model/ArrayOfNumberOnly.cpp +model/ArrayOfNumberOnly.h +model/ArrayTest.cpp +model/ArrayTest.h +model/Capitalization.cpp +model/Capitalization.h +model/Cat.cpp +model/Cat.h +model/Cat_allOf.cpp +model/Cat_allOf.h +model/Category.cpp +model/Category.h +model/ClassModel.cpp +model/ClassModel.h +model/Client.cpp +model/Client.h +model/DeprecatedObject.cpp +model/DeprecatedObject.h +model/Dog.cpp +model/Dog.h +model/Dog_allOf.cpp +model/Dog_allOf.h +model/EnumArrays.cpp +model/EnumArrays.h +model/EnumClass.cpp +model/EnumClass.h +model/Enum_Test.cpp +model/Enum_Test.h +model/File.cpp +model/File.h +model/FileSchemaTestClass.cpp +model/FileSchemaTestClass.h +model/Foo.cpp +model/Foo.h +model/Format_test.cpp +model/Format_test.h +model/HasOnlyReadOnly.cpp +model/HasOnlyReadOnly.h +model/HealthCheckResult.cpp +model/HealthCheckResult.h +model/List.cpp +model/List.h +model/MapTest.cpp +model/MapTest.h +model/MixedPropertiesAndAdditionalPropertiesClass.cpp +model/MixedPropertiesAndAdditionalPropertiesClass.h +model/Name.cpp +model/Name.h +model/NullableClass.cpp +model/NullableClass.h +model/NumberOnly.cpp +model/NumberOnly.h +model/ObjectWithDeprecatedFields.cpp +model/ObjectWithDeprecatedFields.h +model/Order.cpp +model/Order.h +model/OuterComposite.cpp +model/OuterComposite.h +model/OuterEnum.cpp +model/OuterEnum.h +model/OuterEnumDefaultValue.cpp +model/OuterEnumDefaultValue.h +model/OuterEnumInteger.cpp +model/OuterEnumInteger.h +model/OuterEnumIntegerDefaultValue.cpp +model/OuterEnumIntegerDefaultValue.h +model/OuterObjectWithEnumProperty.cpp +model/OuterObjectWithEnumProperty.h +model/Pet.cpp +model/Pet.h +model/ReadOnlyFirst.cpp +model/ReadOnlyFirst.h +model/Return.cpp +model/Return.h +model/SingleRefType.cpp +model/SingleRefType.h +model/Tag.cpp +model/Tag.h +model/User.cpp +model/User.h +model/_foo_get_default_response.cpp +model/_foo_get_default_response.h +model/_special_model_name_.cpp +model/_special_model_name_.h +model/helpers.h +model/r_200_response.cpp +model/r_200_response.h diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/VERSION b/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/CMakeLists.txt b/samples/server/petstore/cpp-restbed/generated/3_0/CMakeLists.txt new file mode 100644 index 0000000000..547aa6c12c --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/CMakeLists.txt @@ -0,0 +1,34 @@ +set(TARGET_NAME org.openapitools.server.apiStubs) + +# Get generated filenames +file(STRINGS "${CMAKE_CURRENT_LIST_DIR}/.openapi-generator/FILES" GENERATED_SOURCES) +list(FILTER GENERATED_SOURCES INCLUDE REGEX ".*cpp$") + +set(GENERATED_SOURCES_INCLUDE_DIRS + ${CMAKE_CURRENT_LIST_DIR}/model + ${CMAKE_CURRENT_LIST_DIR}/api + ${CMAKE_CURRENT_LIST_DIR} +) + + +add_library(${TARGET_NAME} SHARED) + +target_sources(${TARGET_NAME} + PRIVATE + ${GENERATED_SOURCES}) + +target_include_directories(${TARGET_NAME} + PUBLIC + ${GENERATED_SOURCES_INCLUDE_DIRS} +) + + +target_include_directories(${TARGET_NAME} + SYSTEM PUBLIC + ${restbed_SOURCE_DIR}/source) + +target_link_libraries(${TARGET_NAME} + PUBLIC + Boost::system + restbed-shared + -lpthread) diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/FindRestbedAndBoost.cmake b/samples/server/petstore/cpp-restbed/generated/3_0/FindRestbedAndBoost.cmake new file mode 100644 index 0000000000..630464c6fe --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/FindRestbedAndBoost.cmake @@ -0,0 +1,22 @@ + +include(FetchContent) + +## Restbed +FetchContent_Declare( + restbed + GIT_REPOSITORY https://github.com/Corvusoft/restbed + GIT_TAG 4.7 +) + +FetchContent_MakeAvailable(restbed) + +FetchContent_GetProperties(restbed) +if(NOT restbed_POPULATED) + + FetchContent_Populate(restbed) + add_subdirectory(${restbed_SOURCE_DIR} ${restbed_BINARY_DIR}) +endif() + + +## Boost +find_package(Boost 1.7.0 COMPONENTS system REQUIRED) diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/README.md b/samples/server/petstore/cpp-restbed/generated/3_0/README.md new file mode 100644 index 0000000000..f43fbf34d1 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/README.md @@ -0,0 +1,70 @@ +# REST API Server for OpenAPI Petstore + +## Overview +This API Server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. +It uses the [Restbed](https://github.com/Corvusoft/restbed) Framework. + + +## Installation +Put the package under your project folder and import the API stubs. +You need to complete the server stub, as it needs to be connected to a source. + + +## Libraries required +boost_system +ssl (if Restbed was built with SSL Support) +crypto +pthread +restbed + + +## Namespaces +org.openapitools.server.api +org.openapitools.server.model + + +## Example + +The handler functionality can be implemented in two different ways. +Either inherit the given resource and override the handler methods. +Or set a handler lambda to a resource. + +This example shows how this can be done with the pet store API. + +``` +#include "api/StoreApi.h" +#include "api/UserApi.h" + +using namespace org::openapitools::server::api; +using namespace org::openapitools::server::api::StoreApiResources; +using namespace org::openapitools::server::api::UserApiResources; + +/* 1. variant: inherit from the resource and override handler method */ +class MyStoreApiStoreOrderResource : public StoreOrderResource { +public: + std::pair + handler_POST(Order &order) override { + auto ret = Order(); + /* ... add your implementation here .... */ + return std::make_pair(200, ret); + } +}; + +int main() { + const auto service = std::make_shared(); + + auto storeApi = StoreApi(service); + storeApi.setResource(std::make_shared()); + + auto userApi = UserApi(service); + /* 2. variant: implement handler as lambda */ + userApi.getUserResource()->handler_POST_func = [](auto& user) { + /* ... add your implementation here .... */ + return 200;}; + + const auto settings = std::make_shared(); + settings->set_port(1236); + + service->start(settings); +} +``` diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.cpp new file mode 100644 index 0000000000..1d5a7cc6c3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.cpp @@ -0,0 +1,273 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "AnotherFakeApi.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +namespace { +[[maybe_unused]] +std::string selectPreferredContentType(const std::vector& contentTypes) { + if (contentTypes.size() == 0) { + return "application/json"; + } + + if (contentTypes.size() == 1) { + return contentTypes.at(0); + } + + static const std::array preferredTypes = {"json", "xml"}; + for (const auto& preferredType: preferredTypes) { + const auto ret = std::find_if(contentTypes.cbegin(), + contentTypes.cend(), + [preferredType](const std::string& str) { + return str.find(preferredType) != std::string::npos;}); + if (ret != contentTypes.cend()) { + return *ret; + } + } + + return contentTypes.at(0); +} +} + +AnotherFakeApiException::AnotherFakeApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int AnotherFakeApiException::getStatus() const +{ + return m_status; +} +const char* AnotherFakeApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +MODEL_T extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = MODEL_T(pt); + return model; +} + +template +std::vector extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector(); + for (const auto& child: pt) { + arrayRet.emplace_back(MODEL_T(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +namespace AnotherFakeApiResources { +Another_fakeDummyResource::Another_fakeDummyResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/another-fake/dummy"); + this->set_method_handler("PATCH", + std::bind(&Another_fakeDummyResource::handler_PATCH_internal, this, + std::placeholders::_1)); +} + +std::pair Another_fakeDummyResource::handleAnotherFakeApiException(const AnotherFakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair Another_fakeDummyResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair Another_fakeDummyResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void Another_fakeDummyResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void Another_fakeDummyResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void Another_fakeDummyResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void Another_fakeDummyResource::handler_PATCH_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto client = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + Client resultObject = Client{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_PATCH(client); + } + catch(const AnotherFakeApiException& e) { + std::tie(status_code, result) = handleAnotherFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json", + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair Another_fakeDummyResource::handler_PATCH( + Client & client) +{ + return handler_PATCH_func(client); +} + + +std::string Another_fakeDummyResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string Another_fakeDummyResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} + +} /* namespace AnotherFakeApiResources */ + +AnotherFakeApi::AnotherFakeApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +AnotherFakeApi::~AnotherFakeApi() {} + +std::shared_ptr AnotherFakeApi::getAnother_fakeDummyResource() { + if (!m_spAnother_fakeDummyResource) { + setResource(std::make_shared()); + } + return m_spAnother_fakeDummyResource; +} +void AnotherFakeApi::setResource(std::shared_ptr resource) { + m_spAnother_fakeDummyResource = resource; + m_service->publish(m_spAnother_fakeDummyResource); +} +void AnotherFakeApi::setAnotherFakeApiAnother_fakeDummyResource(std::shared_ptr spAnother_fakeDummyResource) { + m_spAnother_fakeDummyResource = spAnother_fakeDummyResource; + m_service->publish(m_spAnother_fakeDummyResource); +} + + +void AnotherFakeApi::publishDefaultResources() { + if (!m_spAnother_fakeDummyResource) { + setResource(std::make_shared()); + } +} + +std::shared_ptr AnotherFakeApi::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.h b/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.h new file mode 100644 index 0000000000..dca1a7f4f8 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.h @@ -0,0 +1,159 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * AnotherFakeApi.h + * + * + */ + +#ifndef AnotherFakeApi_H_ +#define AnotherFakeApi_H_ + + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "Client.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class AnotherFakeApiException: public std::exception +{ +public: + AnotherFakeApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +namespace AnotherFakeApiResources { +/// +/// To test special tags +/// +/// +/// To test special tags and operation ID starting with number +/// +class Another_fakeDummyResource: public restbed::Resource +{ +public: + Another_fakeDummyResource(const std::string& context = "/v2"); + virtual ~Another_fakeDummyResource() = default; + + Another_fakeDummyResource( + const Another_fakeDummyResource& other) = default; // copy constructor + Another_fakeDummyResource(Another_fakeDummyResource&& other) noexcept = default; // move constructor + + Another_fakeDummyResource& operator=(const Another_fakeDummyResource& other) = default; // copy assignment + Another_fakeDummyResource& operator=(Another_fakeDummyResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + Client & client)> handler_PATCH_func = + [](Client &) -> std::pair + { throw AnotherFakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_PATCH( + Client & client); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleAnotherFakeApiException(const AnotherFakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_PATCH_internal(const std::shared_ptr session); +}; + +} /* namespace AnotherFakeApiResources */ + +using AnotherFakeApiAnother_fakeDummyResource [[deprecated]] = AnotherFakeApiResources::Another_fakeDummyResource; + +// +// The restbed service to actually implement the REST server +// +class AnotherFakeApi +{ +public: + explicit AnotherFakeApi(std::shared_ptr const& restbedService); + virtual ~AnotherFakeApi(); + + std::shared_ptr getAnother_fakeDummyResource(); + + void setResource(std::shared_ptr resource); + [[deprecated("use setResource()")]] + virtual void setAnotherFakeApiAnother_fakeDummyResource(std::shared_ptr spAnotherFakeApiAnother_fakeDummyResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spAnother_fakeDummyResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* AnotherFakeApi_H_ */ + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.cpp new file mode 100644 index 0000000000..da893e1bb5 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.cpp @@ -0,0 +1,267 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "DefaultApi.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +namespace { +[[maybe_unused]] +std::string selectPreferredContentType(const std::vector& contentTypes) { + if (contentTypes.size() == 0) { + return "application/json"; + } + + if (contentTypes.size() == 1) { + return contentTypes.at(0); + } + + static const std::array preferredTypes = {"json", "xml"}; + for (const auto& preferredType: preferredTypes) { + const auto ret = std::find_if(contentTypes.cbegin(), + contentTypes.cend(), + [preferredType](const std::string& str) { + return str.find(preferredType) != std::string::npos;}); + if (ret != contentTypes.cend()) { + return *ret; + } + } + + return contentTypes.at(0); +} +} + +DefaultApiException::DefaultApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int DefaultApiException::getStatus() const +{ + return m_status; +} +const char* DefaultApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +MODEL_T extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = MODEL_T(pt); + return model; +} + +template +std::vector extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector(); + for (const auto& child: pt) { + arrayRet.emplace_back(MODEL_T(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +namespace DefaultApiResources { +FooResource::FooResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/foo"); + this->set_method_handler("GET", + std::bind(&FooResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair FooResource::handleDefaultApiException(const DefaultApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FooResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FooResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FooResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FooResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FooResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FooResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + int status_code = 500; + _foo_get_default_response resultObject = _foo_get_default_response{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(); + } + catch(const DefaultApiException& e) { + std::tie(status_code, result) = handleDefaultApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json", + }; + static const std::string acceptTypes{ + }; + + if (status_code == 0) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "response"; + + result = resultObject.toJsonString(); + returnResponse(session, 0, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair FooResource::handler_GET( + ) +{ + return handler_GET_func(); +} + + +std::string FooResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FooResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} + +} /* namespace DefaultApiResources */ + +DefaultApi::DefaultApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +DefaultApi::~DefaultApi() {} + +std::shared_ptr DefaultApi::getFooResource() { + if (!m_spFooResource) { + setResource(std::make_shared()); + } + return m_spFooResource; +} +void DefaultApi::setResource(std::shared_ptr resource) { + m_spFooResource = resource; + m_service->publish(m_spFooResource); +} +void DefaultApi::setDefaultApiFooResource(std::shared_ptr spFooResource) { + m_spFooResource = spFooResource; + m_service->publish(m_spFooResource); +} + + +void DefaultApi::publishDefaultResources() { + if (!m_spFooResource) { + setResource(std::make_shared()); + } +} + +std::shared_ptr DefaultApi::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.h b/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.h new file mode 100644 index 0000000000..632083bd4b --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.h @@ -0,0 +1,159 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * DefaultApi.h + * + * + */ + +#ifndef DefaultApi_H_ +#define DefaultApi_H_ + + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "_foo_get_default_response.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class DefaultApiException: public std::exception +{ +public: + DefaultApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +namespace DefaultApiResources { +/// +/// +/// +/// +/// +/// +class FooResource: public restbed::Resource +{ +public: + FooResource(const std::string& context = "/v2"); + virtual ~FooResource() = default; + + FooResource( + const FooResource& other) = default; // copy constructor + FooResource(FooResource&& other) noexcept = default; // move constructor + + FooResource& operator=(const FooResource& other) = default; // copy assignment + FooResource& operator=(FooResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + )> handler_GET_func = + []() -> std::pair + { throw DefaultApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_GET( + ); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleDefaultApiException(const DefaultApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + +} /* namespace DefaultApiResources */ + +using DefaultApiFooResource [[deprecated]] = DefaultApiResources::FooResource; + +// +// The restbed service to actually implement the REST server +// +class DefaultApi +{ +public: + explicit DefaultApi(std::shared_ptr const& restbedService); + virtual ~DefaultApi(); + + std::shared_ptr getFooResource(); + + void setResource(std::shared_ptr resource); + [[deprecated("use setResource()")]] + virtual void setDefaultApiFooResource(std::shared_ptr spDefaultApiFooResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spFooResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* DefaultApi_H_ */ + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.cpp new file mode 100644 index 0000000000..69680ff827 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.cpp @@ -0,0 +1,2200 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FakeApi.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +namespace { +[[maybe_unused]] +std::string selectPreferredContentType(const std::vector& contentTypes) { + if (contentTypes.size() == 0) { + return "application/json"; + } + + if (contentTypes.size() == 1) { + return contentTypes.at(0); + } + + static const std::array preferredTypes = {"json", "xml"}; + for (const auto& preferredType: preferredTypes) { + const auto ret = std::find_if(contentTypes.cbegin(), + contentTypes.cend(), + [preferredType](const std::string& str) { + return str.find(preferredType) != std::string::npos;}); + if (ret != contentTypes.cend()) { + return *ret; + } + } + + return contentTypes.at(0); +} +} + +FakeApiException::FakeApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int FakeApiException::getStatus() const +{ + return m_status; +} +const char* FakeApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +MODEL_T extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = MODEL_T(pt); + return model; +} + +template +std::vector extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector(); + for (const auto& child: pt) { + arrayRet.emplace_back(MODEL_T(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +namespace FakeApiResources { +FakeHealthResource::FakeHealthResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/health"); + this->set_method_handler("GET", + std::bind(&FakeHealthResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair FakeHealthResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeHealthResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeHealthResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeHealthResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeHealthResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeHealthResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeHealthResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + int status_code = 500; + HealthCheckResult resultObject = HealthCheckResult{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json", + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair FakeHealthResource::handler_GET( + ) +{ + return handler_GET_func(); +} + + +std::string FakeHealthResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeHealthResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeHttp_signature_testResource::FakeHttp_signature_testResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/http-signature-test"); + this->set_method_handler("GET", + std::bind(&FakeHttp_signature_testResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair FakeHttp_signature_testResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeHttp_signature_testResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeHttp_signature_testResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeHttp_signature_testResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeHttp_signature_testResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeHttp_signature_testResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeHttp_signature_testResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto pet = extractJsonModelBodyParam(bodyContent); + // Getting the query params + std::string query1 = request->get_query_parameter("query1", ""); + // Getting the headers + std::string header1 = request->get_header("header_1", ""); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_GET(pet, query1, header1); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, application/xml, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int FakeHttp_signature_testResource::handler_GET( + Pet & pet, std::string & query1, std::string & header1) +{ + return handler_GET_func(pet, query1, header1); +} + + +std::string FakeHttp_signature_testResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeHttp_signature_testResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeOuterBooleanResource::FakeOuterBooleanResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/outer/boolean"); + this->set_method_handler("POST", + std::bind(&FakeOuterBooleanResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair FakeOuterBooleanResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeOuterBooleanResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeOuterBooleanResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeOuterBooleanResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeOuterBooleanResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeOuterBooleanResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeOuterBooleanResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto body = boost::lexical_cast(bodyContent); + + int status_code = 500; + bool resultObject = false; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(body); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "*/*", + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair FakeOuterBooleanResource::handler_POST( + bool & body) +{ + return handler_POST_func(body); +} + + +std::string FakeOuterBooleanResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeOuterBooleanResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeOuterCompositeResource::FakeOuterCompositeResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/outer/composite"); + this->set_method_handler("POST", + std::bind(&FakeOuterCompositeResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair FakeOuterCompositeResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeOuterCompositeResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeOuterCompositeResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeOuterCompositeResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeOuterCompositeResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeOuterCompositeResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeOuterCompositeResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto outerComposite = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + OuterComposite resultObject = OuterComposite{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(outerComposite); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "*/*", + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair FakeOuterCompositeResource::handler_POST( + OuterComposite & outerComposite) +{ + return handler_POST_func(outerComposite); +} + + +std::string FakeOuterCompositeResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeOuterCompositeResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeOuterNumberResource::FakeOuterNumberResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/outer/number"); + this->set_method_handler("POST", + std::bind(&FakeOuterNumberResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair FakeOuterNumberResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeOuterNumberResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeOuterNumberResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeOuterNumberResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeOuterNumberResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeOuterNumberResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeOuterNumberResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto body = boost::lexical_cast(bodyContent); + + int status_code = 500; + double resultObject = 0.0; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(body); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "*/*", + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair FakeOuterNumberResource::handler_POST( + double & body) +{ + return handler_POST_func(body); +} + + +std::string FakeOuterNumberResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeOuterNumberResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeOuterStringResource::FakeOuterStringResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/outer/string"); + this->set_method_handler("POST", + std::bind(&FakeOuterStringResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair FakeOuterStringResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeOuterStringResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeOuterStringResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeOuterStringResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeOuterStringResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeOuterStringResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeOuterStringResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto body = boost::lexical_cast(bodyContent); + + int status_code = 500; + std::string resultObject = ""; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(body); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "*/*", + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject; + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair FakeOuterStringResource::handler_POST( + std::string & body) +{ + return handler_POST_func(body); +} + + +std::string FakeOuterStringResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeOuterStringResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakePropertyEnum_intResource::FakePropertyEnum_intResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/property/enum-int"); + this->set_method_handler("POST", + std::bind(&FakePropertyEnum_intResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair FakePropertyEnum_intResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakePropertyEnum_intResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakePropertyEnum_intResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakePropertyEnum_intResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakePropertyEnum_intResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakePropertyEnum_intResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakePropertyEnum_intResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto outerObjectWithEnumProperty = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + OuterObjectWithEnumProperty resultObject = OuterObjectWithEnumProperty{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(outerObjectWithEnumProperty); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "*/*", + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair FakePropertyEnum_intResource::handler_POST( + OuterObjectWithEnumProperty & outerObjectWithEnumProperty) +{ + return handler_POST_func(outerObjectWithEnumProperty); +} + + +std::string FakePropertyEnum_intResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakePropertyEnum_intResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeBody_with_binaryResource::FakeBody_with_binaryResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/body-with-binary"); + this->set_method_handler("PUT", + std::bind(&FakeBody_with_binaryResource::handler_PUT_internal, this, + std::placeholders::_1)); +} + +std::pair FakeBody_with_binaryResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeBody_with_binaryResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeBody_with_binaryResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeBody_with_binaryResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeBody_with_binaryResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeBody_with_binaryResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeBody_with_binaryResource::handler_PUT_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto body = boost::lexical_cast(bodyContent); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_PUT(body); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "image/png, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int FakeBody_with_binaryResource::handler_PUT( + std::string & body) +{ + return handler_PUT_func(body); +} + + +std::string FakeBody_with_binaryResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeBody_with_binaryResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeBody_with_file_schemaResource::FakeBody_with_file_schemaResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/body-with-file-schema"); + this->set_method_handler("PUT", + std::bind(&FakeBody_with_file_schemaResource::handler_PUT_internal, this, + std::placeholders::_1)); +} + +std::pair FakeBody_with_file_schemaResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeBody_with_file_schemaResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeBody_with_file_schemaResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeBody_with_file_schemaResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeBody_with_file_schemaResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeBody_with_file_schemaResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeBody_with_file_schemaResource::handler_PUT_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto fileSchemaTestClass = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_PUT(fileSchemaTestClass); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int FakeBody_with_file_schemaResource::handler_PUT( + FileSchemaTestClass & fileSchemaTestClass) +{ + return handler_PUT_func(fileSchemaTestClass); +} + + +std::string FakeBody_with_file_schemaResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeBody_with_file_schemaResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeBody_with_query_paramsResource::FakeBody_with_query_paramsResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/body-with-query-params"); + this->set_method_handler("PUT", + std::bind(&FakeBody_with_query_paramsResource::handler_PUT_internal, this, + std::placeholders::_1)); +} + +std::pair FakeBody_with_query_paramsResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeBody_with_query_paramsResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeBody_with_query_paramsResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeBody_with_query_paramsResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeBody_with_query_paramsResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeBody_with_query_paramsResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeBody_with_query_paramsResource::handler_PUT_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto user = extractJsonModelBodyParam(bodyContent); + // Getting the query params + std::string query = request->get_query_parameter("query", ""); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_PUT(query, user); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int FakeBody_with_query_paramsResource::handler_PUT( + std::string & query, User & user) +{ + return handler_PUT_func(query, user); +} + + +std::string FakeBody_with_query_paramsResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeBody_with_query_paramsResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeResource::FakeResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake"); + this->set_method_handler("PATCH", + std::bind(&FakeResource::handler_PATCH_internal, this, + std::placeholders::_1)); + this->set_method_handler("POST", + std::bind(&FakeResource::handler_POST_internal, this, + std::placeholders::_1)); + this->set_method_handler("GET", + std::bind(&FakeResource::handler_GET_internal, this, + std::placeholders::_1)); + this->set_method_handler("DELETE", + std::bind(&FakeResource::handler_DELETE_internal, this, + std::placeholders::_1)); +} + +std::pair FakeResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeResource::handler_PATCH_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto client = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + Client resultObject = Client{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_PATCH(client); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json", + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void FakeResource::handler_POST_internal(const std::shared_ptr session) { + const auto request = session->get_request(); + auto integer = boost::lexical_cast(extractFormParamsFromBody("integer", extractBodyContent(session))); + auto int32 = boost::lexical_cast(extractFormParamsFromBody("int32", extractBodyContent(session))); + auto int64 = boost::lexical_cast(extractFormParamsFromBody("int64", extractBodyContent(session))); + auto number = boost::lexical_cast(extractFormParamsFromBody("number", extractBodyContent(session))); + auto r_float = boost::lexical_cast(extractFormParamsFromBody("r_float", extractBodyContent(session))); + auto r_double = boost::lexical_cast(extractFormParamsFromBody("r_double", extractBodyContent(session))); + auto string = boost::lexical_cast(extractFormParamsFromBody("string", extractBodyContent(session))); + auto patternWithoutDelimiter = boost::lexical_cast(extractFormParamsFromBody("patternWithoutDelimiter", extractBodyContent(session))); + auto byte = boost::lexical_cast(extractFormParamsFromBody("byte", extractBodyContent(session))); + auto binary = boost::lexical_cast(extractFormParamsFromBody("binary", extractBodyContent(session))); + auto date = boost::lexical_cast(extractFormParamsFromBody("date", extractBodyContent(session))); + auto dateTime = boost::lexical_cast(extractFormParamsFromBody("dateTime", extractBodyContent(session))); + auto password = boost::lexical_cast(extractFormParamsFromBody("password", extractBodyContent(session))); + auto callback = boost::lexical_cast(extractFormParamsFromBody("callback", extractBodyContent(session))); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(number, r_double, patternWithoutDelimiter, byte, integer, int32, int64, r_float, string, binary, date, dateTime, password, callback); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/x-www-form-urlencoded, " + }; + + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid username supplied"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 404) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "User not found"; + + returnResponse(session, 404, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} +// x-extension +void FakeResource::handler_GET_internal(const std::shared_ptr session) { + const auto request = session->get_request(); + std::string enumFormStringArray_raw = extractFormParamsFromBody("enumFormStringArray", extractBodyContent(session)); + std::vector enumFormStringArray; + boost::split(enumFormStringArray, enumFormStringArray_raw, boost::is_any_of(",")); + auto enumFormString = boost::lexical_cast(extractFormParamsFromBody("enumFormString", extractBodyContent(session))); + // Getting the query params + std::string enumQueryStringArray_raw = request->get_query_parameter("enumQueryStringArray"); + std::vector enumQueryStringArray; + std::vector enumQueryStringArray_temp; + boost::split(enumQueryStringArray_temp, enumQueryStringArray_raw, boost::is_any_of(",")); + std::copy(enumQueryStringArray_temp.begin(), enumQueryStringArray_temp.end(), std::inserter(enumQueryStringArray, std::next(enumQueryStringArray.begin()))); + std::string enumQueryString = request->get_query_parameter("enumQueryString", "-efg"); + int32_t enumQueryInteger = request->get_query_parameter("enumQueryInteger", 0); + double enumQueryDouble = request->get_query_parameter("enumQueryDouble", 0.0); + std::string enumQueryModelArray_raw = request->get_query_parameter("enumQueryModelArray"); + std::vector enumQueryModelArray; + std::vector enumQueryModelArray_temp; + boost::split(enumQueryModelArray_temp, enumQueryModelArray_raw, boost::is_any_of(",")); + std::transform(enumQueryModelArray_temp.begin(), enumQueryModelArray_temp.end(), std::back_inserter(enumQueryModelArray), [](const auto& i){ EnumClass ret; ret.fromString(i); return ret;}); + // Getting the headers + std::string enumHeaderStringArray_raw = request->get_header("enumHeaderStringArray"); + std::vector enumHeaderStringArray; + boost::split(enumHeaderStringArray, enumHeaderStringArray_raw, boost::is_any_of(",")); + std::string enumHeaderString = request->get_header("enum_header_string", "-efg"); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_GET(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/x-www-form-urlencoded, " + }; + + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid request"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 404) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Not found"; + + returnResponse(session, 404, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} +// x-extension +void FakeResource::handler_DELETE_internal(const std::shared_ptr session) { + const auto request = session->get_request(); + // Getting the query params + int32_t requiredStringGroup = request->get_query_parameter("requiredStringGroup", 0); + int64_t requiredInt64Group = request->get_query_parameter("requiredInt64Group", 0L); + int32_t stringGroup = request->get_query_parameter("stringGroup", 0); + int64_t int64Group = request->get_query_parameter("int64Group", 0L); + // Getting the headers + bool requiredBooleanGroup = request->get_header("required_boolean_group", false); + bool booleanGroup = request->get_header("boolean_group", false); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + }; + + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Someting wrong"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +std::pair FakeResource::handler_PATCH( + Client & client) +{ + return handler_PATCH_func(client); +} + +int FakeResource::handler_POST( + double & number, double & r_double, std::string & patternWithoutDelimiter, std::string & byte, int32_t & integer, int32_t & int32, int64_t & int64, float & r_float, std::string & string, std::string & binary, std::string & date, std::string & dateTime, std::string & password, std::string & callback) +{ + return handler_POST_func(number, r_double, patternWithoutDelimiter, byte, integer, int32, int64, r_float, string, binary, date, dateTime, password, callback); +} +int FakeResource::handler_GET( + std::vector & enumHeaderStringArray, std::string & enumHeaderString, std::vector & enumQueryStringArray, std::string & enumQueryString, int32_t & enumQueryInteger, double & enumQueryDouble, std::vector & enumQueryModelArray, std::vector & enumFormStringArray, std::string & enumFormString) +{ + return handler_GET_func(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString); +} +int FakeResource::handler_DELETE( + int32_t & requiredStringGroup, bool & requiredBooleanGroup, int64_t & requiredInt64Group, int32_t & stringGroup, bool & booleanGroup, int64_t & int64Group) +{ + return handler_DELETE_func(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); +} + +std::string FakeResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeInline_additionalPropertiesResource::FakeInline_additionalPropertiesResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/inline-additionalProperties"); + this->set_method_handler("POST", + std::bind(&FakeInline_additionalPropertiesResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair FakeInline_additionalPropertiesResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeInline_additionalPropertiesResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeInline_additionalPropertiesResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeInline_additionalPropertiesResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeInline_additionalPropertiesResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeInline_additionalPropertiesResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeInline_additionalPropertiesResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + std::map requestBody; // TODO + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(requestBody); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int FakeInline_additionalPropertiesResource::handler_POST( + std::map & requestBody) +{ + return handler_POST_func(requestBody); +} + + +std::string FakeInline_additionalPropertiesResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeInline_additionalPropertiesResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeJsonFormDataResource::FakeJsonFormDataResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/jsonFormData"); + this->set_method_handler("GET", + std::bind(&FakeJsonFormDataResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair FakeJsonFormDataResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeJsonFormDataResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeJsonFormDataResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeJsonFormDataResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeJsonFormDataResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeJsonFormDataResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeJsonFormDataResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + auto param = boost::lexical_cast(extractFormParamsFromBody("param", extractBodyContent(session))); + auto param2 = boost::lexical_cast(extractFormParamsFromBody("param2", extractBodyContent(session))); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_GET(param, param2); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/x-www-form-urlencoded, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int FakeJsonFormDataResource::handler_GET( + std::string & param, std::string & param2) +{ + return handler_GET_func(param, param2); +} + + +std::string FakeJsonFormDataResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeJsonFormDataResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakeTest_query_parametersResource::FakeTest_query_parametersResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/test-query-parameters"); + this->set_method_handler("PUT", + std::bind(&FakeTest_query_parametersResource::handler_PUT_internal, this, + std::placeholders::_1)); +} + +std::pair FakeTest_query_parametersResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeTest_query_parametersResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeTest_query_parametersResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeTest_query_parametersResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeTest_query_parametersResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeTest_query_parametersResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeTest_query_parametersResource::handler_PUT_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // Getting the query params + std::string pipe_raw = request->get_query_parameter("pipe"); + std::vector pipe; + std::vector pipe_temp; + boost::split(pipe_temp, pipe_raw, boost::is_any_of(",")); + std::copy(pipe_temp.begin(), pipe_temp.end(), std::inserter(pipe, std::next(pipe.begin()))); + std::string ioutil_raw = request->get_query_parameter("ioutil"); + std::vector ioutil; + std::vector ioutil_temp; + boost::split(ioutil_temp, ioutil_raw, boost::is_any_of(",")); + std::copy(ioutil_temp.begin(), ioutil_temp.end(), std::inserter(ioutil, std::next(ioutil.begin()))); + std::string http_raw = request->get_query_parameter("http"); + std::vector http; + std::vector http_temp; + boost::split(http_temp, http_raw, boost::is_any_of(",")); + std::copy(http_temp.begin(), http_temp.end(), std::inserter(http, std::next(http.begin()))); + std::string url_raw = request->get_query_parameter("url"); + std::vector url; + std::vector url_temp; + boost::split(url_temp, url_raw, boost::is_any_of(",")); + std::copy(url_temp.begin(), url_temp.end(), std::inserter(url, std::next(url.begin()))); + std::string context_raw = request->get_query_parameter("context"); + std::vector context; + std::vector context_temp; + boost::split(context_temp, context_raw, boost::is_any_of(",")); + std::copy(context_temp.begin(), context_temp.end(), std::inserter(context, std::next(context.begin()))); + std::stringstream language_raw(request->get_query_parameter("language")); + boost::property_tree::ptree language_pt; + boost::property_tree::json_parser::read_json(language_raw,language_pt); + std::map language = std::map{}; + for (auto& item: language_pt) { + language.emplace(item.first, item.second.get_value()); + } + std::string allowEmpty = request->get_query_parameter("allowEmpty", ""); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_PUT(pipe, ioutil, http, url, context, allowEmpty, language); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int FakeTest_query_parametersResource::handler_PUT( + std::vector & pipe, std::vector & ioutil, std::vector & http, std::vector & url, std::vector & context, std::string & allowEmpty, std::map & language) +{ + return handler_PUT_func(pipe, ioutil, http, url, context, allowEmpty, language); +} + + +std::string FakeTest_query_parametersResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeTest_query_parametersResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} + +} /* namespace FakeApiResources */ + +FakeApi::FakeApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +FakeApi::~FakeApi() {} + +std::shared_ptr FakeApi::getFakeHealthResource() { + if (!m_spFakeHealthResource) { + setResource(std::make_shared()); + } + return m_spFakeHealthResource; +} +std::shared_ptr FakeApi::getFakeHttp_signature_testResource() { + if (!m_spFakeHttp_signature_testResource) { + setResource(std::make_shared()); + } + return m_spFakeHttp_signature_testResource; +} +std::shared_ptr FakeApi::getFakeOuterBooleanResource() { + if (!m_spFakeOuterBooleanResource) { + setResource(std::make_shared()); + } + return m_spFakeOuterBooleanResource; +} +std::shared_ptr FakeApi::getFakeOuterCompositeResource() { + if (!m_spFakeOuterCompositeResource) { + setResource(std::make_shared()); + } + return m_spFakeOuterCompositeResource; +} +std::shared_ptr FakeApi::getFakeOuterNumberResource() { + if (!m_spFakeOuterNumberResource) { + setResource(std::make_shared()); + } + return m_spFakeOuterNumberResource; +} +std::shared_ptr FakeApi::getFakeOuterStringResource() { + if (!m_spFakeOuterStringResource) { + setResource(std::make_shared()); + } + return m_spFakeOuterStringResource; +} +std::shared_ptr FakeApi::getFakePropertyEnum_intResource() { + if (!m_spFakePropertyEnum_intResource) { + setResource(std::make_shared()); + } + return m_spFakePropertyEnum_intResource; +} +std::shared_ptr FakeApi::getFakeBody_with_binaryResource() { + if (!m_spFakeBody_with_binaryResource) { + setResource(std::make_shared()); + } + return m_spFakeBody_with_binaryResource; +} +std::shared_ptr FakeApi::getFakeBody_with_file_schemaResource() { + if (!m_spFakeBody_with_file_schemaResource) { + setResource(std::make_shared()); + } + return m_spFakeBody_with_file_schemaResource; +} +std::shared_ptr FakeApi::getFakeBody_with_query_paramsResource() { + if (!m_spFakeBody_with_query_paramsResource) { + setResource(std::make_shared()); + } + return m_spFakeBody_with_query_paramsResource; +} +std::shared_ptr FakeApi::getFakeResource() { + if (!m_spFakeResource) { + setResource(std::make_shared()); + } + return m_spFakeResource; +} +std::shared_ptr FakeApi::getFakeInline_additionalPropertiesResource() { + if (!m_spFakeInline_additionalPropertiesResource) { + setResource(std::make_shared()); + } + return m_spFakeInline_additionalPropertiesResource; +} +std::shared_ptr FakeApi::getFakeJsonFormDataResource() { + if (!m_spFakeJsonFormDataResource) { + setResource(std::make_shared()); + } + return m_spFakeJsonFormDataResource; +} +std::shared_ptr FakeApi::getFakeTest_query_parametersResource() { + if (!m_spFakeTest_query_parametersResource) { + setResource(std::make_shared()); + } + return m_spFakeTest_query_parametersResource; +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeHealthResource = resource; + m_service->publish(m_spFakeHealthResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeHttp_signature_testResource = resource; + m_service->publish(m_spFakeHttp_signature_testResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeOuterBooleanResource = resource; + m_service->publish(m_spFakeOuterBooleanResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeOuterCompositeResource = resource; + m_service->publish(m_spFakeOuterCompositeResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeOuterNumberResource = resource; + m_service->publish(m_spFakeOuterNumberResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeOuterStringResource = resource; + m_service->publish(m_spFakeOuterStringResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakePropertyEnum_intResource = resource; + m_service->publish(m_spFakePropertyEnum_intResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeBody_with_binaryResource = resource; + m_service->publish(m_spFakeBody_with_binaryResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeBody_with_file_schemaResource = resource; + m_service->publish(m_spFakeBody_with_file_schemaResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeBody_with_query_paramsResource = resource; + m_service->publish(m_spFakeBody_with_query_paramsResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeResource = resource; + m_service->publish(m_spFakeResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeInline_additionalPropertiesResource = resource; + m_service->publish(m_spFakeInline_additionalPropertiesResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeJsonFormDataResource = resource; + m_service->publish(m_spFakeJsonFormDataResource); +} +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeTest_query_parametersResource = resource; + m_service->publish(m_spFakeTest_query_parametersResource); +} +void FakeApi::setFakeApiFakeHealthResource(std::shared_ptr spFakeHealthResource) { + m_spFakeHealthResource = spFakeHealthResource; + m_service->publish(m_spFakeHealthResource); +} +void FakeApi::setFakeApiFakeHttp_signature_testResource(std::shared_ptr spFakeHttp_signature_testResource) { + m_spFakeHttp_signature_testResource = spFakeHttp_signature_testResource; + m_service->publish(m_spFakeHttp_signature_testResource); +} +void FakeApi::setFakeApiFakeOuterBooleanResource(std::shared_ptr spFakeOuterBooleanResource) { + m_spFakeOuterBooleanResource = spFakeOuterBooleanResource; + m_service->publish(m_spFakeOuterBooleanResource); +} +void FakeApi::setFakeApiFakeOuterCompositeResource(std::shared_ptr spFakeOuterCompositeResource) { + m_spFakeOuterCompositeResource = spFakeOuterCompositeResource; + m_service->publish(m_spFakeOuterCompositeResource); +} +void FakeApi::setFakeApiFakeOuterNumberResource(std::shared_ptr spFakeOuterNumberResource) { + m_spFakeOuterNumberResource = spFakeOuterNumberResource; + m_service->publish(m_spFakeOuterNumberResource); +} +void FakeApi::setFakeApiFakeOuterStringResource(std::shared_ptr spFakeOuterStringResource) { + m_spFakeOuterStringResource = spFakeOuterStringResource; + m_service->publish(m_spFakeOuterStringResource); +} +void FakeApi::setFakeApiFakePropertyEnum_intResource(std::shared_ptr spFakePropertyEnum_intResource) { + m_spFakePropertyEnum_intResource = spFakePropertyEnum_intResource; + m_service->publish(m_spFakePropertyEnum_intResource); +} +void FakeApi::setFakeApiFakeBody_with_binaryResource(std::shared_ptr spFakeBody_with_binaryResource) { + m_spFakeBody_with_binaryResource = spFakeBody_with_binaryResource; + m_service->publish(m_spFakeBody_with_binaryResource); +} +void FakeApi::setFakeApiFakeBody_with_file_schemaResource(std::shared_ptr spFakeBody_with_file_schemaResource) { + m_spFakeBody_with_file_schemaResource = spFakeBody_with_file_schemaResource; + m_service->publish(m_spFakeBody_with_file_schemaResource); +} +void FakeApi::setFakeApiFakeBody_with_query_paramsResource(std::shared_ptr spFakeBody_with_query_paramsResource) { + m_spFakeBody_with_query_paramsResource = spFakeBody_with_query_paramsResource; + m_service->publish(m_spFakeBody_with_query_paramsResource); +} +void FakeApi::setFakeApiFakeResource(std::shared_ptr spFakeResource) { + m_spFakeResource = spFakeResource; + m_service->publish(m_spFakeResource); +} +void FakeApi::setFakeApiFakeInline_additionalPropertiesResource(std::shared_ptr spFakeInline_additionalPropertiesResource) { + m_spFakeInline_additionalPropertiesResource = spFakeInline_additionalPropertiesResource; + m_service->publish(m_spFakeInline_additionalPropertiesResource); +} +void FakeApi::setFakeApiFakeJsonFormDataResource(std::shared_ptr spFakeJsonFormDataResource) { + m_spFakeJsonFormDataResource = spFakeJsonFormDataResource; + m_service->publish(m_spFakeJsonFormDataResource); +} +void FakeApi::setFakeApiFakeTest_query_parametersResource(std::shared_ptr spFakeTest_query_parametersResource) { + m_spFakeTest_query_parametersResource = spFakeTest_query_parametersResource; + m_service->publish(m_spFakeTest_query_parametersResource); +} + + +void FakeApi::publishDefaultResources() { + if (!m_spFakeHealthResource) { + setResource(std::make_shared()); + } + if (!m_spFakeHttp_signature_testResource) { + setResource(std::make_shared()); + } + if (!m_spFakeOuterBooleanResource) { + setResource(std::make_shared()); + } + if (!m_spFakeOuterCompositeResource) { + setResource(std::make_shared()); + } + if (!m_spFakeOuterNumberResource) { + setResource(std::make_shared()); + } + if (!m_spFakeOuterStringResource) { + setResource(std::make_shared()); + } + if (!m_spFakePropertyEnum_intResource) { + setResource(std::make_shared()); + } + if (!m_spFakeBody_with_binaryResource) { + setResource(std::make_shared()); + } + if (!m_spFakeBody_with_file_schemaResource) { + setResource(std::make_shared()); + } + if (!m_spFakeBody_with_query_paramsResource) { + setResource(std::make_shared()); + } + if (!m_spFakeResource) { + setResource(std::make_shared()); + } + if (!m_spFakeInline_additionalPropertiesResource) { + setResource(std::make_shared()); + } + if (!m_spFakeJsonFormDataResource) { + setResource(std::make_shared()); + } + if (!m_spFakeTest_query_parametersResource) { + setResource(std::make_shared()); + } +} + +std::shared_ptr FakeApi::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.h b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.h new file mode 100644 index 0000000000..9e18249ae2 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.h @@ -0,0 +1,1076 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * FakeApi.h + * + * + */ + +#ifndef FakeApi_H_ +#define FakeApi_H_ + + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "Client.h" +#include "EnumClass.h" +#include "FileSchemaTestClass.h" +#include "HealthCheckResult.h" +#include "OuterComposite.h" +#include "OuterObjectWithEnumProperty.h" +#include "Pet.h" +#include "User.h" +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class FakeApiException: public std::exception +{ +public: + FakeApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +namespace FakeApiResources { +/// +/// Health check endpoint +/// +/// +/// +/// +class FakeHealthResource: public restbed::Resource +{ +public: + FakeHealthResource(const std::string& context = "/v2"); + virtual ~FakeHealthResource() = default; + + FakeHealthResource( + const FakeHealthResource& other) = default; // copy constructor + FakeHealthResource(FakeHealthResource&& other) noexcept = default; // move constructor + + FakeHealthResource& operator=(const FakeHealthResource& other) = default; // copy assignment + FakeHealthResource& operator=(FakeHealthResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + )> handler_GET_func = + []() -> std::pair + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_GET( + ); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + +/// +/// test http signature authentication +/// +/// +/// +/// +class FakeHttp_signature_testResource: public restbed::Resource +{ +public: + FakeHttp_signature_testResource(const std::string& context = "/v2"); + virtual ~FakeHttp_signature_testResource() = default; + + FakeHttp_signature_testResource( + const FakeHttp_signature_testResource& other) = default; // copy constructor + FakeHttp_signature_testResource(FakeHttp_signature_testResource&& other) noexcept = default; // move constructor + + FakeHttp_signature_testResource& operator=(const FakeHttp_signature_testResource& other) = default; // copy assignment + FakeHttp_signature_testResource& operator=(FakeHttp_signature_testResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_GET_func = + [](Pet &, std::string &, std::string &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_GET( + Pet & pet, std::string & query1, std::string & header1); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + +/// +/// +/// +/// +/// Test serialization of outer boolean types +/// +class FakeOuterBooleanResource: public restbed::Resource +{ +public: + FakeOuterBooleanResource(const std::string& context = "/v2"); + virtual ~FakeOuterBooleanResource() = default; + + FakeOuterBooleanResource( + const FakeOuterBooleanResource& other) = default; // copy constructor + FakeOuterBooleanResource(FakeOuterBooleanResource&& other) noexcept = default; // move constructor + + FakeOuterBooleanResource& operator=(const FakeOuterBooleanResource& other) = default; // copy assignment + FakeOuterBooleanResource& operator=(FakeOuterBooleanResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + bool & body)> handler_POST_func = + [](bool &) -> std::pair + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_POST( + bool & body); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// +/// +/// +/// Test serialization of object with outer number type +/// +class FakeOuterCompositeResource: public restbed::Resource +{ +public: + FakeOuterCompositeResource(const std::string& context = "/v2"); + virtual ~FakeOuterCompositeResource() = default; + + FakeOuterCompositeResource( + const FakeOuterCompositeResource& other) = default; // copy constructor + FakeOuterCompositeResource(FakeOuterCompositeResource&& other) noexcept = default; // move constructor + + FakeOuterCompositeResource& operator=(const FakeOuterCompositeResource& other) = default; // copy assignment + FakeOuterCompositeResource& operator=(FakeOuterCompositeResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + OuterComposite & outerComposite)> handler_POST_func = + [](OuterComposite &) -> std::pair + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_POST( + OuterComposite & outerComposite); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// +/// +/// +/// Test serialization of outer number types +/// +class FakeOuterNumberResource: public restbed::Resource +{ +public: + FakeOuterNumberResource(const std::string& context = "/v2"); + virtual ~FakeOuterNumberResource() = default; + + FakeOuterNumberResource( + const FakeOuterNumberResource& other) = default; // copy constructor + FakeOuterNumberResource(FakeOuterNumberResource&& other) noexcept = default; // move constructor + + FakeOuterNumberResource& operator=(const FakeOuterNumberResource& other) = default; // copy assignment + FakeOuterNumberResource& operator=(FakeOuterNumberResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + double & body)> handler_POST_func = + [](double &) -> std::pair + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_POST( + double & body); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// +/// +/// +/// Test serialization of outer string types +/// +class FakeOuterStringResource: public restbed::Resource +{ +public: + FakeOuterStringResource(const std::string& context = "/v2"); + virtual ~FakeOuterStringResource() = default; + + FakeOuterStringResource( + const FakeOuterStringResource& other) = default; // copy constructor + FakeOuterStringResource(FakeOuterStringResource&& other) noexcept = default; // move constructor + + FakeOuterStringResource& operator=(const FakeOuterStringResource& other) = default; // copy assignment + FakeOuterStringResource& operator=(FakeOuterStringResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + std::string & body)> handler_POST_func = + [](std::string &) -> std::pair + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_POST( + std::string & body); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// +/// +/// +/// Test serialization of enum (int) properties with examples +/// +class FakePropertyEnum_intResource: public restbed::Resource +{ +public: + FakePropertyEnum_intResource(const std::string& context = "/v2"); + virtual ~FakePropertyEnum_intResource() = default; + + FakePropertyEnum_intResource( + const FakePropertyEnum_intResource& other) = default; // copy constructor + FakePropertyEnum_intResource(FakePropertyEnum_intResource&& other) noexcept = default; // move constructor + + FakePropertyEnum_intResource& operator=(const FakePropertyEnum_intResource& other) = default; // copy assignment + FakePropertyEnum_intResource& operator=(FakePropertyEnum_intResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + OuterObjectWithEnumProperty & outerObjectWithEnumProperty)> handler_POST_func = + [](OuterObjectWithEnumProperty &) -> std::pair + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_POST( + OuterObjectWithEnumProperty & outerObjectWithEnumProperty); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// +/// +/// +/// For this test, the body has to be a binary file. +/// +class FakeBody_with_binaryResource: public restbed::Resource +{ +public: + FakeBody_with_binaryResource(const std::string& context = "/v2"); + virtual ~FakeBody_with_binaryResource() = default; + + FakeBody_with_binaryResource( + const FakeBody_with_binaryResource& other) = default; // copy constructor + FakeBody_with_binaryResource(FakeBody_with_binaryResource&& other) noexcept = default; // move constructor + + FakeBody_with_binaryResource& operator=(const FakeBody_with_binaryResource& other) = default; // copy assignment + FakeBody_with_binaryResource& operator=(FakeBody_with_binaryResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_PUT_func = + [](std::string &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_PUT( + std::string & body); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_PUT_internal(const std::shared_ptr session); +}; + +/// +/// +/// +/// +/// For this test, the body for this request must reference a schema named `File`. +/// +class FakeBody_with_file_schemaResource: public restbed::Resource +{ +public: + FakeBody_with_file_schemaResource(const std::string& context = "/v2"); + virtual ~FakeBody_with_file_schemaResource() = default; + + FakeBody_with_file_schemaResource( + const FakeBody_with_file_schemaResource& other) = default; // copy constructor + FakeBody_with_file_schemaResource(FakeBody_with_file_schemaResource&& other) noexcept = default; // move constructor + + FakeBody_with_file_schemaResource& operator=(const FakeBody_with_file_schemaResource& other) = default; // copy assignment + FakeBody_with_file_schemaResource& operator=(FakeBody_with_file_schemaResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_PUT_func = + [](FileSchemaTestClass &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_PUT( + FileSchemaTestClass & fileSchemaTestClass); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_PUT_internal(const std::shared_ptr session); +}; + +/// +/// +/// +/// +/// +/// +class FakeBody_with_query_paramsResource: public restbed::Resource +{ +public: + FakeBody_with_query_paramsResource(const std::string& context = "/v2"); + virtual ~FakeBody_with_query_paramsResource() = default; + + FakeBody_with_query_paramsResource( + const FakeBody_with_query_paramsResource& other) = default; // copy constructor + FakeBody_with_query_paramsResource(FakeBody_with_query_paramsResource&& other) noexcept = default; // move constructor + + FakeBody_with_query_paramsResource& operator=(const FakeBody_with_query_paramsResource& other) = default; // copy assignment + FakeBody_with_query_paramsResource& operator=(FakeBody_with_query_paramsResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_PUT_func = + [](std::string &, User &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_PUT( + std::string & query, User & user); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_PUT_internal(const std::shared_ptr session); +}; + +/// +/// To test \"client\" model +/// +/// +/// To test \"client\" model +/// +class FakeResource: public restbed::Resource +{ +public: + FakeResource(const std::string& context = "/v2"); + virtual ~FakeResource() = default; + + FakeResource( + const FakeResource& other) = default; // copy constructor + FakeResource(FakeResource&& other) noexcept = default; // move constructor + + FakeResource& operator=(const FakeResource& other) = default; // copy assignment + FakeResource& operator=(FakeResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + Client & client)> handler_PATCH_func = + [](Client &) -> std::pair + { throw FakeApiException(501, "Not implemented"); }; + + std::function handler_POST_func = + [](double &, double &, std::string &, std::string &, int32_t &, int32_t &, int64_t &, float &, std::string &, std::string &, std::string &, std::string &, std::string &, std::string &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + std::function & enumHeaderStringArray, std::string & enumHeaderString, std::vector & enumQueryStringArray, std::string & enumQueryString, int32_t & enumQueryInteger, double & enumQueryDouble, std::vector & enumQueryModelArray, std::vector & enumFormStringArray, std::string & enumFormString)> handler_GET_func = + [](std::vector &, std::string &, std::vector &, std::string &, int32_t &, double &, std::vector &, std::vector &, std::string &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + std::function handler_DELETE_func = + [](int32_t &, bool &, int64_t &, int32_t &, bool &, int64_t &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_PATCH( + Client & client); + + virtual int handler_POST( + double & number, double & r_double, std::string & patternWithoutDelimiter, std::string & byte, int32_t & integer, int32_t & int32, int64_t & int64, float & r_float, std::string & string, std::string & binary, std::string & date, std::string & dateTime, std::string & password, std::string & callback); + virtual int handler_GET( + std::vector & enumHeaderStringArray, std::string & enumHeaderString, std::vector & enumQueryStringArray, std::string & enumQueryString, int32_t & enumQueryInteger, double & enumQueryDouble, std::vector & enumQueryModelArray, std::vector & enumFormStringArray, std::string & enumFormString); + virtual int handler_DELETE( + int32_t & requiredStringGroup, bool & requiredBooleanGroup, int64_t & requiredInt64Group, int32_t & stringGroup, bool & booleanGroup, int64_t & int64Group); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_PATCH_internal(const std::shared_ptr session); + void handler_POST_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); + void handler_DELETE_internal(const std::shared_ptr session); +}; + +/// +/// test inline additionalProperties +/// +/// +/// +/// +class FakeInline_additionalPropertiesResource: public restbed::Resource +{ +public: + FakeInline_additionalPropertiesResource(const std::string& context = "/v2"); + virtual ~FakeInline_additionalPropertiesResource() = default; + + FakeInline_additionalPropertiesResource( + const FakeInline_additionalPropertiesResource& other) = default; // copy constructor + FakeInline_additionalPropertiesResource(FakeInline_additionalPropertiesResource&& other) noexcept = default; // move constructor + + FakeInline_additionalPropertiesResource& operator=(const FakeInline_additionalPropertiesResource& other) = default; // copy assignment + FakeInline_additionalPropertiesResource& operator=(FakeInline_additionalPropertiesResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function & requestBody)> handler_POST_func = + [](std::map &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_POST( + std::map & requestBody); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// test json serialization of form data +/// +/// +/// +/// +class FakeJsonFormDataResource: public restbed::Resource +{ +public: + FakeJsonFormDataResource(const std::string& context = "/v2"); + virtual ~FakeJsonFormDataResource() = default; + + FakeJsonFormDataResource( + const FakeJsonFormDataResource& other) = default; // copy constructor + FakeJsonFormDataResource(FakeJsonFormDataResource&& other) noexcept = default; // move constructor + + FakeJsonFormDataResource& operator=(const FakeJsonFormDataResource& other) = default; // copy assignment + FakeJsonFormDataResource& operator=(FakeJsonFormDataResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_GET_func = + [](std::string &, std::string &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_GET( + std::string & param, std::string & param2); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + +/// +/// +/// +/// +/// To test the collection format in query parameters +/// +class FakeTest_query_parametersResource: public restbed::Resource +{ +public: + FakeTest_query_parametersResource(const std::string& context = "/v2"); + virtual ~FakeTest_query_parametersResource() = default; + + FakeTest_query_parametersResource( + const FakeTest_query_parametersResource& other) = default; // copy constructor + FakeTest_query_parametersResource(FakeTest_query_parametersResource&& other) noexcept = default; // move constructor + + FakeTest_query_parametersResource& operator=(const FakeTest_query_parametersResource& other) = default; // copy assignment + FakeTest_query_parametersResource& operator=(FakeTest_query_parametersResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function & pipe, std::vector & ioutil, std::vector & http, std::vector & url, std::vector & context, std::string & allowEmpty, std::map & language)> handler_PUT_func = + [](std::vector &, std::vector &, std::vector &, std::vector &, std::vector &, std::string &, std::map &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_PUT( + std::vector & pipe, std::vector & ioutil, std::vector & http, std::vector & url, std::vector & context, std::string & allowEmpty, std::map & language); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_PUT_internal(const std::shared_ptr session); +}; + +} /* namespace FakeApiResources */ + +using FakeApiFakeHealthResource [[deprecated]] = FakeApiResources::FakeHealthResource; +using FakeApiFakeHttp_signature_testResource [[deprecated]] = FakeApiResources::FakeHttp_signature_testResource; +using FakeApiFakeOuterBooleanResource [[deprecated]] = FakeApiResources::FakeOuterBooleanResource; +using FakeApiFakeOuterCompositeResource [[deprecated]] = FakeApiResources::FakeOuterCompositeResource; +using FakeApiFakeOuterNumberResource [[deprecated]] = FakeApiResources::FakeOuterNumberResource; +using FakeApiFakeOuterStringResource [[deprecated]] = FakeApiResources::FakeOuterStringResource; +using FakeApiFakePropertyEnum_intResource [[deprecated]] = FakeApiResources::FakePropertyEnum_intResource; +using FakeApiFakeBody_with_binaryResource [[deprecated]] = FakeApiResources::FakeBody_with_binaryResource; +using FakeApiFakeBody_with_file_schemaResource [[deprecated]] = FakeApiResources::FakeBody_with_file_schemaResource; +using FakeApiFakeBody_with_query_paramsResource [[deprecated]] = FakeApiResources::FakeBody_with_query_paramsResource; +using FakeApiFakeResource [[deprecated]] = FakeApiResources::FakeResource; +using FakeApiFakeInline_additionalPropertiesResource [[deprecated]] = FakeApiResources::FakeInline_additionalPropertiesResource; +using FakeApiFakeJsonFormDataResource [[deprecated]] = FakeApiResources::FakeJsonFormDataResource; +using FakeApiFakeTest_query_parametersResource [[deprecated]] = FakeApiResources::FakeTest_query_parametersResource; + +// +// The restbed service to actually implement the REST server +// +class FakeApi +{ +public: + explicit FakeApi(std::shared_ptr const& restbedService); + virtual ~FakeApi(); + + std::shared_ptr getFakeHealthResource(); + std::shared_ptr getFakeHttp_signature_testResource(); + std::shared_ptr getFakeOuterBooleanResource(); + std::shared_ptr getFakeOuterCompositeResource(); + std::shared_ptr getFakeOuterNumberResource(); + std::shared_ptr getFakeOuterStringResource(); + std::shared_ptr getFakePropertyEnum_intResource(); + std::shared_ptr getFakeBody_with_binaryResource(); + std::shared_ptr getFakeBody_with_file_schemaResource(); + std::shared_ptr getFakeBody_with_query_paramsResource(); + std::shared_ptr getFakeResource(); + std::shared_ptr getFakeInline_additionalPropertiesResource(); + std::shared_ptr getFakeJsonFormDataResource(); + std::shared_ptr getFakeTest_query_parametersResource(); + + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeHealthResource(std::shared_ptr spFakeApiFakeHealthResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeHttp_signature_testResource(std::shared_ptr spFakeApiFakeHttp_signature_testResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeOuterBooleanResource(std::shared_ptr spFakeApiFakeOuterBooleanResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeOuterCompositeResource(std::shared_ptr spFakeApiFakeOuterCompositeResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeOuterNumberResource(std::shared_ptr spFakeApiFakeOuterNumberResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeOuterStringResource(std::shared_ptr spFakeApiFakeOuterStringResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakePropertyEnum_intResource(std::shared_ptr spFakeApiFakePropertyEnum_intResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeBody_with_binaryResource(std::shared_ptr spFakeApiFakeBody_with_binaryResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeBody_with_file_schemaResource(std::shared_ptr spFakeApiFakeBody_with_file_schemaResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeBody_with_query_paramsResource(std::shared_ptr spFakeApiFakeBody_with_query_paramsResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeResource(std::shared_ptr spFakeApiFakeResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeInline_additionalPropertiesResource(std::shared_ptr spFakeApiFakeInline_additionalPropertiesResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeJsonFormDataResource(std::shared_ptr spFakeApiFakeJsonFormDataResource); + [[deprecated("use setResource()")]] + virtual void setFakeApiFakeTest_query_parametersResource(std::shared_ptr spFakeApiFakeTest_query_parametersResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spFakeHealthResource; + std::shared_ptr m_spFakeHttp_signature_testResource; + std::shared_ptr m_spFakeOuterBooleanResource; + std::shared_ptr m_spFakeOuterCompositeResource; + std::shared_ptr m_spFakeOuterNumberResource; + std::shared_ptr m_spFakeOuterStringResource; + std::shared_ptr m_spFakePropertyEnum_intResource; + std::shared_ptr m_spFakeBody_with_binaryResource; + std::shared_ptr m_spFakeBody_with_file_schemaResource; + std::shared_ptr m_spFakeBody_with_query_paramsResource; + std::shared_ptr m_spFakeResource; + std::shared_ptr m_spFakeInline_additionalPropertiesResource; + std::shared_ptr m_spFakeJsonFormDataResource; + std::shared_ptr m_spFakeTest_query_parametersResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* FakeApi_H_ */ + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.cpp new file mode 100644 index 0000000000..5a1d46e469 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.cpp @@ -0,0 +1,273 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FakeClassnameTags123Api.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +namespace { +[[maybe_unused]] +std::string selectPreferredContentType(const std::vector& contentTypes) { + if (contentTypes.size() == 0) { + return "application/json"; + } + + if (contentTypes.size() == 1) { + return contentTypes.at(0); + } + + static const std::array preferredTypes = {"json", "xml"}; + for (const auto& preferredType: preferredTypes) { + const auto ret = std::find_if(contentTypes.cbegin(), + contentTypes.cend(), + [preferredType](const std::string& str) { + return str.find(preferredType) != std::string::npos;}); + if (ret != contentTypes.cend()) { + return *ret; + } + } + + return contentTypes.at(0); +} +} + +FakeClassnameTags123ApiException::FakeClassnameTags123ApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int FakeClassnameTags123ApiException::getStatus() const +{ + return m_status; +} +const char* FakeClassnameTags123ApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +MODEL_T extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = MODEL_T(pt); + return model; +} + +template +std::vector extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector(); + for (const auto& child: pt) { + arrayRet.emplace_back(MODEL_T(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +namespace FakeClassnameTags123ApiResources { +Fake_classname_testResource::Fake_classname_testResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake_classname_test"); + this->set_method_handler("PATCH", + std::bind(&Fake_classname_testResource::handler_PATCH_internal, this, + std::placeholders::_1)); +} + +std::pair Fake_classname_testResource::handleFakeClassnameTags123ApiException(const FakeClassnameTags123ApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair Fake_classname_testResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair Fake_classname_testResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void Fake_classname_testResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void Fake_classname_testResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void Fake_classname_testResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void Fake_classname_testResource::handler_PATCH_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto client = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + Client resultObject = Client{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_PATCH(client); + } + catch(const FakeClassnameTags123ApiException& e) { + std::tie(status_code, result) = handleFakeClassnameTags123ApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json", + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair Fake_classname_testResource::handler_PATCH( + Client & client) +{ + return handler_PATCH_func(client); +} + + +std::string Fake_classname_testResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string Fake_classname_testResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} + +} /* namespace FakeClassnameTags123ApiResources */ + +FakeClassnameTags123Api::FakeClassnameTags123Api(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +FakeClassnameTags123Api::~FakeClassnameTags123Api() {} + +std::shared_ptr FakeClassnameTags123Api::getFake_classname_testResource() { + if (!m_spFake_classname_testResource) { + setResource(std::make_shared()); + } + return m_spFake_classname_testResource; +} +void FakeClassnameTags123Api::setResource(std::shared_ptr resource) { + m_spFake_classname_testResource = resource; + m_service->publish(m_spFake_classname_testResource); +} +void FakeClassnameTags123Api::setFakeClassnameTags123ApiFake_classname_testResource(std::shared_ptr spFake_classname_testResource) { + m_spFake_classname_testResource = spFake_classname_testResource; + m_service->publish(m_spFake_classname_testResource); +} + + +void FakeClassnameTags123Api::publishDefaultResources() { + if (!m_spFake_classname_testResource) { + setResource(std::make_shared()); + } +} + +std::shared_ptr FakeClassnameTags123Api::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.h b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.h new file mode 100644 index 0000000000..2e2f2c1ab1 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.h @@ -0,0 +1,159 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * FakeClassnameTags123Api.h + * + * + */ + +#ifndef FakeClassnameTags123Api_H_ +#define FakeClassnameTags123Api_H_ + + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "Client.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class FakeClassnameTags123ApiException: public std::exception +{ +public: + FakeClassnameTags123ApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +namespace FakeClassnameTags123ApiResources { +/// +/// To test class name in snake case +/// +/// +/// To test class name in snake case +/// +class Fake_classname_testResource: public restbed::Resource +{ +public: + Fake_classname_testResource(const std::string& context = "/v2"); + virtual ~Fake_classname_testResource() = default; + + Fake_classname_testResource( + const Fake_classname_testResource& other) = default; // copy constructor + Fake_classname_testResource(Fake_classname_testResource&& other) noexcept = default; // move constructor + + Fake_classname_testResource& operator=(const Fake_classname_testResource& other) = default; // copy assignment + Fake_classname_testResource& operator=(Fake_classname_testResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + Client & client)> handler_PATCH_func = + [](Client &) -> std::pair + { throw FakeClassnameTags123ApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_PATCH( + Client & client); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeClassnameTags123ApiException(const FakeClassnameTags123ApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_PATCH_internal(const std::shared_ptr session); +}; + +} /* namespace FakeClassnameTags123ApiResources */ + +using FakeClassnameTags123ApiFake_classname_testResource [[deprecated]] = FakeClassnameTags123ApiResources::Fake_classname_testResource; + +// +// The restbed service to actually implement the REST server +// +class FakeClassnameTags123Api +{ +public: + explicit FakeClassnameTags123Api(std::shared_ptr const& restbedService); + virtual ~FakeClassnameTags123Api(); + + std::shared_ptr getFake_classname_testResource(); + + void setResource(std::shared_ptr resource); + [[deprecated("use setResource()")]] + virtual void setFakeClassnameTags123ApiFake_classname_testResource(std::shared_ptr spFakeClassnameTags123ApiFake_classname_testResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spFake_classname_testResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* FakeClassnameTags123Api_H_ */ + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.cpp new file mode 100644 index 0000000000..6e7ea0e754 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.cpp @@ -0,0 +1,1157 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "PetApi.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +namespace { +[[maybe_unused]] +std::string selectPreferredContentType(const std::vector& contentTypes) { + if (contentTypes.size() == 0) { + return "application/json"; + } + + if (contentTypes.size() == 1) { + return contentTypes.at(0); + } + + static const std::array preferredTypes = {"json", "xml"}; + for (const auto& preferredType: preferredTypes) { + const auto ret = std::find_if(contentTypes.cbegin(), + contentTypes.cend(), + [preferredType](const std::string& str) { + return str.find(preferredType) != std::string::npos;}); + if (ret != contentTypes.cend()) { + return *ret; + } + } + + return contentTypes.at(0); +} +} + +PetApiException::PetApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int PetApiException::getStatus() const +{ + return m_status; +} +const char* PetApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +MODEL_T extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = MODEL_T(pt); + return model; +} + +template +std::vector extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector(); + for (const auto& child: pt) { + arrayRet.emplace_back(MODEL_T(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +namespace PetApiResources { +PetResource::PetResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet"); + this->set_method_handler("POST", + std::bind(&PetResource::handler_POST_internal, this, + std::placeholders::_1)); + this->set_method_handler("PUT", + std::bind(&PetResource::handler_PUT_internal, this, + std::placeholders::_1)); +} + +std::pair PetResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void PetResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto pet = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(pet); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, application/xml, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 405) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid input"; + + returnResponse(session, 405, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void PetResource::handler_PUT_internal(const std::shared_ptr session) { + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto pet = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_PUT(pet); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, application/xml, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid ID supplied"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 404) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Pet not found"; + + returnResponse(session, 404, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 405) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Validation exception"; + + returnResponse(session, 405, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +int PetResource::handler_POST( + Pet & pet) +{ + return handler_POST_func(pet); +} + +int PetResource::handler_PUT( + Pet & pet) +{ + return handler_PUT_func(pet); +} + +std::string PetResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string PetResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +PetPetIdResource::PetPetIdResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/{petId: .*}"); + this->set_method_handler("DELETE", + std::bind(&PetPetIdResource::handler_DELETE_internal, this, + std::placeholders::_1)); + this->set_method_handler("GET", + std::bind(&PetPetIdResource::handler_GET_internal, this, + std::placeholders::_1)); + this->set_method_handler("POST", + std::bind(&PetPetIdResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair PetPetIdResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetPetIdResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetPetIdResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetPetIdResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetPetIdResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void PetPetIdResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetPetIdResource::handler_DELETE_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // Getting the path params + int64_t petId = request->get_path_parameter("petId", 0L); + // Getting the headers + std::string apiKey = request->get_header("api_key", ""); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(petId, apiKey); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid pet value"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void PetPetIdResource::handler_GET_internal(const std::shared_ptr session) { + const auto request = session->get_request(); + // Getting the path params + int64_t petId = request->get_path_parameter("petId", 0L); + + int status_code = 500; + Pet resultObject = Pet{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(petId); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/xml","application/json", + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid ID supplied"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 404) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Pet not found"; + + returnResponse(session, 404, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} +// x-extension +void PetPetIdResource::handler_POST_internal(const std::shared_ptr session) { + const auto request = session->get_request(); + auto name = boost::lexical_cast(extractFormParamsFromBody("name", extractBodyContent(session))); + auto status = boost::lexical_cast(extractFormParamsFromBody("status", extractBodyContent(session))); + // Getting the path params + int64_t petId = request->get_path_parameter("petId", 0L); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(petId, name, status); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/x-www-form-urlencoded, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 405) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid input"; + + returnResponse(session, 405, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +int PetPetIdResource::handler_DELETE( + int64_t & petId, std::string & apiKey) +{ + return handler_DELETE_func(petId, apiKey); +} + +std::pair PetPetIdResource::handler_GET( + int64_t & petId) +{ + return handler_GET_func(petId); +} +int PetPetIdResource::handler_POST( + int64_t & petId, std::string & name, std::string & status) +{ + return handler_POST_func(petId, name, status); +} + +std::string PetPetIdResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string PetPetIdResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +PetFindByStatusResource::PetFindByStatusResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/findByStatus"); + this->set_method_handler("GET", + std::bind(&PetFindByStatusResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair PetFindByStatusResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetFindByStatusResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetFindByStatusResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetFindByStatusResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetFindByStatusResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void PetFindByStatusResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetFindByStatusResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // Getting the query params + std::string status_raw = request->get_query_parameter("status"); + std::vector status; + std::vector status_temp; + boost::split(status_temp, status_raw, boost::is_any_of(",")); + std::copy(status_temp.begin(), status_temp.end(), std::inserter(status, std::next(status.begin()))); + + int status_code = 500; + std::vector resultObject = std::vector(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(status); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/xml","application/json", + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid status value"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair> PetFindByStatusResource::handler_GET( + std::vector & status) +{ + return handler_GET_func(status); +} + + +std::string PetFindByStatusResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string PetFindByStatusResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +PetFindByTagsResource::PetFindByTagsResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/findByTags"); + this->set_method_handler("GET", + std::bind(&PetFindByTagsResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair PetFindByTagsResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetFindByTagsResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetFindByTagsResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetFindByTagsResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetFindByTagsResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void PetFindByTagsResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetFindByTagsResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // Getting the query params + std::string tags_raw = request->get_query_parameter("tags"); + std::set tags; + std::vector tags_temp; + boost::split(tags_temp, tags_raw, boost::is_any_of(",")); + std::copy(tags_temp.begin(), tags_temp.end(), std::inserter(tags, std::next(tags.begin()))); + + int status_code = 500; + std::set resultObject = std::set(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(tags); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/xml","application/json", + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid tag value"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair> PetFindByTagsResource::handler_GET( + std::set & tags) +{ + return handler_GET_func(tags); +} + + +std::string PetFindByTagsResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string PetFindByTagsResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +PetPetIdUploadImageResource::PetPetIdUploadImageResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/{petId: .*}/uploadImage"); + this->set_method_handler("POST", + std::bind(&PetPetIdUploadImageResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair PetPetIdUploadImageResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetPetIdUploadImageResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetPetIdUploadImageResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetPetIdUploadImageResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetPetIdUploadImageResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void PetPetIdUploadImageResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetPetIdUploadImageResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + auto additionalMetadata = boost::lexical_cast(extractFormParamsFromBody("additionalMetadata", extractBodyContent(session))); + auto file = boost::lexical_cast(extractFormParamsFromBody("file", extractBodyContent(session))); + // Getting the path params + int64_t petId = request->get_path_parameter("petId", 0L); + + int status_code = 500; + ApiResponse resultObject = ApiResponse{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(petId, additionalMetadata, file); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json", + }; + static const std::string acceptTypes{ + "multipart/form-data, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair PetPetIdUploadImageResource::handler_POST( + int64_t & petId, std::string & additionalMetadata, std::string & file) +{ + return handler_POST_func(petId, additionalMetadata, file); +} + + +std::string PetPetIdUploadImageResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string PetPetIdUploadImageResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +FakePetIdUploadImageWithRequiredFileResource::FakePetIdUploadImageWithRequiredFileResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/fake/{petId: .*}/uploadImageWithRequiredFile"); + this->set_method_handler("POST", + std::bind(&FakePetIdUploadImageWithRequiredFileResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair FakePetIdUploadImageWithRequiredFileResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakePetIdUploadImageWithRequiredFileResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakePetIdUploadImageWithRequiredFileResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakePetIdUploadImageWithRequiredFileResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakePetIdUploadImageWithRequiredFileResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakePetIdUploadImageWithRequiredFileResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakePetIdUploadImageWithRequiredFileResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + auto additionalMetadata = boost::lexical_cast(extractFormParamsFromBody("additionalMetadata", extractBodyContent(session))); + auto requiredFile = boost::lexical_cast(extractFormParamsFromBody("requiredFile", extractBodyContent(session))); + // Getting the path params + int64_t petId = request->get_path_parameter("petId", 0L); + + int status_code = 500; + ApiResponse resultObject = ApiResponse{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(petId, requiredFile, additionalMetadata); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json", + }; + static const std::string acceptTypes{ + "multipart/form-data, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair FakePetIdUploadImageWithRequiredFileResource::handler_POST( + int64_t & petId, std::string & requiredFile, std::string & additionalMetadata) +{ + return handler_POST_func(petId, requiredFile, additionalMetadata); +} + + +std::string FakePetIdUploadImageWithRequiredFileResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakePetIdUploadImageWithRequiredFileResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} + +} /* namespace PetApiResources */ + +PetApi::PetApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +PetApi::~PetApi() {} + +std::shared_ptr PetApi::getPetResource() { + if (!m_spPetResource) { + setResource(std::make_shared()); + } + return m_spPetResource; +} +std::shared_ptr PetApi::getPetPetIdResource() { + if (!m_spPetPetIdResource) { + setResource(std::make_shared()); + } + return m_spPetPetIdResource; +} +std::shared_ptr PetApi::getPetFindByStatusResource() { + if (!m_spPetFindByStatusResource) { + setResource(std::make_shared()); + } + return m_spPetFindByStatusResource; +} +std::shared_ptr PetApi::getPetFindByTagsResource() { + if (!m_spPetFindByTagsResource) { + setResource(std::make_shared()); + } + return m_spPetFindByTagsResource; +} +std::shared_ptr PetApi::getPetPetIdUploadImageResource() { + if (!m_spPetPetIdUploadImageResource) { + setResource(std::make_shared()); + } + return m_spPetPetIdUploadImageResource; +} +std::shared_ptr PetApi::getFakePetIdUploadImageWithRequiredFileResource() { + if (!m_spFakePetIdUploadImageWithRequiredFileResource) { + setResource(std::make_shared()); + } + return m_spFakePetIdUploadImageWithRequiredFileResource; +} +void PetApi::setResource(std::shared_ptr resource) { + m_spPetResource = resource; + m_service->publish(m_spPetResource); +} +void PetApi::setResource(std::shared_ptr resource) { + m_spPetPetIdResource = resource; + m_service->publish(m_spPetPetIdResource); +} +void PetApi::setResource(std::shared_ptr resource) { + m_spPetFindByStatusResource = resource; + m_service->publish(m_spPetFindByStatusResource); +} +void PetApi::setResource(std::shared_ptr resource) { + m_spPetFindByTagsResource = resource; + m_service->publish(m_spPetFindByTagsResource); +} +void PetApi::setResource(std::shared_ptr resource) { + m_spPetPetIdUploadImageResource = resource; + m_service->publish(m_spPetPetIdUploadImageResource); +} +void PetApi::setResource(std::shared_ptr resource) { + m_spFakePetIdUploadImageWithRequiredFileResource = resource; + m_service->publish(m_spFakePetIdUploadImageWithRequiredFileResource); +} +void PetApi::setPetApiPetResource(std::shared_ptr spPetResource) { + m_spPetResource = spPetResource; + m_service->publish(m_spPetResource); +} +void PetApi::setPetApiPetPetIdResource(std::shared_ptr spPetPetIdResource) { + m_spPetPetIdResource = spPetPetIdResource; + m_service->publish(m_spPetPetIdResource); +} +void PetApi::setPetApiPetFindByStatusResource(std::shared_ptr spPetFindByStatusResource) { + m_spPetFindByStatusResource = spPetFindByStatusResource; + m_service->publish(m_spPetFindByStatusResource); +} +void PetApi::setPetApiPetFindByTagsResource(std::shared_ptr spPetFindByTagsResource) { + m_spPetFindByTagsResource = spPetFindByTagsResource; + m_service->publish(m_spPetFindByTagsResource); +} +void PetApi::setPetApiPetPetIdUploadImageResource(std::shared_ptr spPetPetIdUploadImageResource) { + m_spPetPetIdUploadImageResource = spPetPetIdUploadImageResource; + m_service->publish(m_spPetPetIdUploadImageResource); +} +void PetApi::setPetApiFakePetIdUploadImageWithRequiredFileResource(std::shared_ptr spFakePetIdUploadImageWithRequiredFileResource) { + m_spFakePetIdUploadImageWithRequiredFileResource = spFakePetIdUploadImageWithRequiredFileResource; + m_service->publish(m_spFakePetIdUploadImageWithRequiredFileResource); +} + + +void PetApi::publishDefaultResources() { + if (!m_spPetResource) { + setResource(std::make_shared()); + } + if (!m_spPetPetIdResource) { + setResource(std::make_shared()); + } + if (!m_spPetFindByStatusResource) { + setResource(std::make_shared()); + } + if (!m_spPetFindByTagsResource) { + setResource(std::make_shared()); + } + if (!m_spPetPetIdUploadImageResource) { + setResource(std::make_shared()); + } + if (!m_spFakePetIdUploadImageWithRequiredFileResource) { + setResource(std::make_shared()); + } +} + +std::shared_ptr PetApi::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.h b/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.h new file mode 100644 index 0000000000..e7665a0164 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.h @@ -0,0 +1,526 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PetApi.h + * + * + */ + +#ifndef PetApi_H_ +#define PetApi_H_ + + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "ApiResponse.h" +#include "Pet.h" +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class PetApiException: public std::exception +{ +public: + PetApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +namespace PetApiResources { +/// +/// Add a new pet to the store +/// +/// +/// +/// +class PetResource: public restbed::Resource +{ +public: + PetResource(const std::string& context = "/v2"); + virtual ~PetResource() = default; + + PetResource( + const PetResource& other) = default; // copy constructor + PetResource(PetResource&& other) noexcept = default; // move constructor + + PetResource& operator=(const PetResource& other) = default; // copy assignment + PetResource& operator=(PetResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_POST_func = + [](Pet &) -> int + { throw PetApiException(501, "Not implemented"); }; + + std::function handler_PUT_func = + [](Pet &) -> int + { throw PetApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_POST( + Pet & pet); + + virtual int handler_PUT( + Pet & pet); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); + void handler_PUT_internal(const std::shared_ptr session); +}; + +/// +/// Deletes a pet +/// +/// +/// +/// +class PetPetIdResource: public restbed::Resource +{ +public: + PetPetIdResource(const std::string& context = "/v2"); + virtual ~PetPetIdResource() = default; + + PetPetIdResource( + const PetPetIdResource& other) = default; // copy constructor + PetPetIdResource(PetPetIdResource&& other) noexcept = default; // move constructor + + PetPetIdResource& operator=(const PetPetIdResource& other) = default; // copy assignment + PetPetIdResource& operator=(PetPetIdResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_DELETE_func = + [](int64_t &, std::string &) -> int + { throw PetApiException(501, "Not implemented"); }; + + std::function( + int64_t & petId)> handler_GET_func = + [](int64_t &) -> std::pair + { throw PetApiException(501, "Not implemented"); }; + + std::function handler_POST_func = + [](int64_t &, std::string &, std::string &) -> int + { throw PetApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_DELETE( + int64_t & petId, std::string & apiKey); + + virtual std::pair handler_GET( + int64_t & petId); + virtual int handler_POST( + int64_t & petId, std::string & name, std::string & status); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_DELETE_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// Finds Pets by status +/// +/// +/// Multiple status values can be provided with comma separated strings +/// +class PetFindByStatusResource: public restbed::Resource +{ +public: + PetFindByStatusResource(const std::string& context = "/v2"); + virtual ~PetFindByStatusResource() = default; + + PetFindByStatusResource( + const PetFindByStatusResource& other) = default; // copy constructor + PetFindByStatusResource(PetFindByStatusResource&& other) noexcept = default; // move constructor + + PetFindByStatusResource& operator=(const PetFindByStatusResource& other) = default; // copy assignment + PetFindByStatusResource& operator=(PetFindByStatusResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function>( + std::vector & status)> handler_GET_func = + [](std::vector &) -> std::pair> + { throw PetApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair> handler_GET( + std::vector & status); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + +/// +/// Finds Pets by tags +/// +/// +/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +/// +class PetFindByTagsResource: public restbed::Resource +{ +public: + PetFindByTagsResource(const std::string& context = "/v2"); + virtual ~PetFindByTagsResource() = default; + + PetFindByTagsResource( + const PetFindByTagsResource& other) = default; // copy constructor + PetFindByTagsResource(PetFindByTagsResource&& other) noexcept = default; // move constructor + + PetFindByTagsResource& operator=(const PetFindByTagsResource& other) = default; // copy assignment + PetFindByTagsResource& operator=(PetFindByTagsResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function>( + std::set & tags)> handler_GET_func = + [](std::set &) -> std::pair> + { throw PetApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair> handler_GET( + std::set & tags); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + +/// +/// uploads an image +/// +/// +/// +/// +class PetPetIdUploadImageResource: public restbed::Resource +{ +public: + PetPetIdUploadImageResource(const std::string& context = "/v2"); + virtual ~PetPetIdUploadImageResource() = default; + + PetPetIdUploadImageResource( + const PetPetIdUploadImageResource& other) = default; // copy constructor + PetPetIdUploadImageResource(PetPetIdUploadImageResource&& other) noexcept = default; // move constructor + + PetPetIdUploadImageResource& operator=(const PetPetIdUploadImageResource& other) = default; // copy assignment + PetPetIdUploadImageResource& operator=(PetPetIdUploadImageResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + int64_t & petId, std::string & additionalMetadata, std::string & file)> handler_POST_func = + [](int64_t &, std::string &, std::string &) -> std::pair + { throw PetApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_POST( + int64_t & petId, std::string & additionalMetadata, std::string & file); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// uploads an image (required) +/// +/// +/// +/// +class FakePetIdUploadImageWithRequiredFileResource: public restbed::Resource +{ +public: + FakePetIdUploadImageWithRequiredFileResource(const std::string& context = "/v2"); + virtual ~FakePetIdUploadImageWithRequiredFileResource() = default; + + FakePetIdUploadImageWithRequiredFileResource( + const FakePetIdUploadImageWithRequiredFileResource& other) = default; // copy constructor + FakePetIdUploadImageWithRequiredFileResource(FakePetIdUploadImageWithRequiredFileResource&& other) noexcept = default; // move constructor + + FakePetIdUploadImageWithRequiredFileResource& operator=(const FakePetIdUploadImageWithRequiredFileResource& other) = default; // copy assignment + FakePetIdUploadImageWithRequiredFileResource& operator=(FakePetIdUploadImageWithRequiredFileResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + int64_t & petId, std::string & requiredFile, std::string & additionalMetadata)> handler_POST_func = + [](int64_t &, std::string &, std::string &) -> std::pair + { throw PetApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_POST( + int64_t & petId, std::string & requiredFile, std::string & additionalMetadata); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +} /* namespace PetApiResources */ + +using PetApiPetResource [[deprecated]] = PetApiResources::PetResource; +using PetApiPetPetIdResource [[deprecated]] = PetApiResources::PetPetIdResource; +using PetApiPetFindByStatusResource [[deprecated]] = PetApiResources::PetFindByStatusResource; +using PetApiPetFindByTagsResource [[deprecated]] = PetApiResources::PetFindByTagsResource; +using PetApiPetPetIdUploadImageResource [[deprecated]] = PetApiResources::PetPetIdUploadImageResource; +using PetApiFakePetIdUploadImageWithRequiredFileResource [[deprecated]] = PetApiResources::FakePetIdUploadImageWithRequiredFileResource; + +// +// The restbed service to actually implement the REST server +// +class PetApi +{ +public: + explicit PetApi(std::shared_ptr const& restbedService); + virtual ~PetApi(); + + std::shared_ptr getPetResource(); + std::shared_ptr getPetPetIdResource(); + std::shared_ptr getPetFindByStatusResource(); + std::shared_ptr getPetFindByTagsResource(); + std::shared_ptr getPetPetIdUploadImageResource(); + std::shared_ptr getFakePetIdUploadImageWithRequiredFileResource(); + + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + [[deprecated("use setResource()")]] + virtual void setPetApiPetResource(std::shared_ptr spPetApiPetResource); + [[deprecated("use setResource()")]] + virtual void setPetApiPetPetIdResource(std::shared_ptr spPetApiPetPetIdResource); + [[deprecated("use setResource()")]] + virtual void setPetApiPetFindByStatusResource(std::shared_ptr spPetApiPetFindByStatusResource); + [[deprecated("use setResource()")]] + virtual void setPetApiPetFindByTagsResource(std::shared_ptr spPetApiPetFindByTagsResource); + [[deprecated("use setResource()")]] + virtual void setPetApiPetPetIdUploadImageResource(std::shared_ptr spPetApiPetPetIdUploadImageResource); + [[deprecated("use setResource()")]] + virtual void setPetApiFakePetIdUploadImageWithRequiredFileResource(std::shared_ptr spPetApiFakePetIdUploadImageWithRequiredFileResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spPetResource; + std::shared_ptr m_spPetPetIdResource; + std::shared_ptr m_spPetFindByStatusResource; + std::shared_ptr m_spPetFindByTagsResource; + std::shared_ptr m_spPetPetIdUploadImageResource; + std::shared_ptr m_spFakePetIdUploadImageWithRequiredFileResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* PetApi_H_ */ + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.cpp new file mode 100644 index 0000000000..0287dd1ba3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.cpp @@ -0,0 +1,606 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "StoreApi.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +namespace { +[[maybe_unused]] +std::string selectPreferredContentType(const std::vector& contentTypes) { + if (contentTypes.size() == 0) { + return "application/json"; + } + + if (contentTypes.size() == 1) { + return contentTypes.at(0); + } + + static const std::array preferredTypes = {"json", "xml"}; + for (const auto& preferredType: preferredTypes) { + const auto ret = std::find_if(contentTypes.cbegin(), + contentTypes.cend(), + [preferredType](const std::string& str) { + return str.find(preferredType) != std::string::npos;}); + if (ret != contentTypes.cend()) { + return *ret; + } + } + + return contentTypes.at(0); +} +} + +StoreApiException::StoreApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int StoreApiException::getStatus() const +{ + return m_status; +} +const char* StoreApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +MODEL_T extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = MODEL_T(pt); + return model; +} + +template +std::vector extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector(); + for (const auto& child: pt) { + arrayRet.emplace_back(MODEL_T(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +namespace StoreApiResources { +StoreOrderOrder_idResource::StoreOrderOrder_idResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/store/order/{order_id: .*}"); + this->set_method_handler("DELETE", + std::bind(&StoreOrderOrder_idResource::handler_DELETE_internal, this, + std::placeholders::_1)); + this->set_method_handler("GET", + std::bind(&StoreOrderOrder_idResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair StoreOrderOrder_idResource::handleStoreApiException(const StoreApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair StoreOrderOrder_idResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair StoreOrderOrder_idResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void StoreOrderOrder_idResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void StoreOrderOrder_idResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void StoreOrderOrder_idResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void StoreOrderOrder_idResource::handler_DELETE_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // Getting the path params + std::string orderId = request->get_path_parameter("order_id", ""); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(orderId); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + }; + + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid ID supplied"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 404) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Order not found"; + + returnResponse(session, 404, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void StoreOrderOrder_idResource::handler_GET_internal(const std::shared_ptr session) { + const auto request = session->get_request(); + // Getting the path params + int64_t orderId = request->get_path_parameter("order_id", 0L); + + int status_code = 500; + Order resultObject = Order{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(orderId); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/xml","application/json", + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid ID supplied"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 404) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Order not found"; + + returnResponse(session, 404, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +int StoreOrderOrder_idResource::handler_DELETE( + std::string & orderId) +{ + return handler_DELETE_func(orderId); +} + +std::pair StoreOrderOrder_idResource::handler_GET( + int64_t & orderId) +{ + return handler_GET_func(orderId); +} + +std::string StoreOrderOrder_idResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string StoreOrderOrder_idResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +StoreInventoryResource::StoreInventoryResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/store/inventory"); + this->set_method_handler("GET", + std::bind(&StoreInventoryResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair StoreInventoryResource::handleStoreApiException(const StoreApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair StoreInventoryResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair StoreInventoryResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void StoreInventoryResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void StoreInventoryResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void StoreInventoryResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void StoreInventoryResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + int status_code = 500; + std::map resultObject = std::map(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json", + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = convertMapResponse(resultObject); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair> StoreInventoryResource::handler_GET( + ) +{ + return handler_GET_func(); +} + + +std::string StoreInventoryResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string StoreInventoryResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +StoreOrderResource::StoreOrderResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/store/order"); + this->set_method_handler("POST", + std::bind(&StoreOrderResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair StoreOrderResource::handleStoreApiException(const StoreApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair StoreOrderResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair StoreOrderResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void StoreOrderResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void StoreOrderResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void StoreOrderResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void StoreOrderResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto order = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + Order resultObject = Order{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(order); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/xml","application/json", + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid Order"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair StoreOrderResource::handler_POST( + Order & order) +{ + return handler_POST_func(order); +} + + +std::string StoreOrderResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string StoreOrderResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} + +} /* namespace StoreApiResources */ + +StoreApi::StoreApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +StoreApi::~StoreApi() {} + +std::shared_ptr StoreApi::getStoreOrderOrder_idResource() { + if (!m_spStoreOrderOrder_idResource) { + setResource(std::make_shared()); + } + return m_spStoreOrderOrder_idResource; +} +std::shared_ptr StoreApi::getStoreInventoryResource() { + if (!m_spStoreInventoryResource) { + setResource(std::make_shared()); + } + return m_spStoreInventoryResource; +} +std::shared_ptr StoreApi::getStoreOrderResource() { + if (!m_spStoreOrderResource) { + setResource(std::make_shared()); + } + return m_spStoreOrderResource; +} +void StoreApi::setResource(std::shared_ptr resource) { + m_spStoreOrderOrder_idResource = resource; + m_service->publish(m_spStoreOrderOrder_idResource); +} +void StoreApi::setResource(std::shared_ptr resource) { + m_spStoreInventoryResource = resource; + m_service->publish(m_spStoreInventoryResource); +} +void StoreApi::setResource(std::shared_ptr resource) { + m_spStoreOrderResource = resource; + m_service->publish(m_spStoreOrderResource); +} +void StoreApi::setStoreApiStoreOrderOrder_idResource(std::shared_ptr spStoreOrderOrder_idResource) { + m_spStoreOrderOrder_idResource = spStoreOrderOrder_idResource; + m_service->publish(m_spStoreOrderOrder_idResource); +} +void StoreApi::setStoreApiStoreInventoryResource(std::shared_ptr spStoreInventoryResource) { + m_spStoreInventoryResource = spStoreInventoryResource; + m_service->publish(m_spStoreInventoryResource); +} +void StoreApi::setStoreApiStoreOrderResource(std::shared_ptr spStoreOrderResource) { + m_spStoreOrderResource = spStoreOrderResource; + m_service->publish(m_spStoreOrderResource); +} + + +void StoreApi::publishDefaultResources() { + if (!m_spStoreOrderOrder_idResource) { + setResource(std::make_shared()); + } + if (!m_spStoreInventoryResource) { + setResource(std::make_shared()); + } + if (!m_spStoreOrderResource) { + setResource(std::make_shared()); + } +} + +std::shared_ptr StoreApi::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.h b/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.h new file mode 100644 index 0000000000..711053388e --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.h @@ -0,0 +1,305 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * StoreApi.h + * + * + */ + +#ifndef StoreApi_H_ +#define StoreApi_H_ + + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "Order.h" +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class StoreApiException: public std::exception +{ +public: + StoreApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +namespace StoreApiResources { +/// +/// Delete purchase order by ID +/// +/// +/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +/// +class StoreOrderOrder_idResource: public restbed::Resource +{ +public: + StoreOrderOrder_idResource(const std::string& context = "/v2"); + virtual ~StoreOrderOrder_idResource() = default; + + StoreOrderOrder_idResource( + const StoreOrderOrder_idResource& other) = default; // copy constructor + StoreOrderOrder_idResource(StoreOrderOrder_idResource&& other) noexcept = default; // move constructor + + StoreOrderOrder_idResource& operator=(const StoreOrderOrder_idResource& other) = default; // copy assignment + StoreOrderOrder_idResource& operator=(StoreOrderOrder_idResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_DELETE_func = + [](std::string &) -> int + { throw StoreApiException(501, "Not implemented"); }; + + std::function( + int64_t & orderId)> handler_GET_func = + [](int64_t &) -> std::pair + { throw StoreApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_DELETE( + std::string & orderId); + + virtual std::pair handler_GET( + int64_t & orderId); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleStoreApiException(const StoreApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_DELETE_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); +}; + +/// +/// Returns pet inventories by status +/// +/// +/// Returns a map of status codes to quantities +/// +class StoreInventoryResource: public restbed::Resource +{ +public: + StoreInventoryResource(const std::string& context = "/v2"); + virtual ~StoreInventoryResource() = default; + + StoreInventoryResource( + const StoreInventoryResource& other) = default; // copy constructor + StoreInventoryResource(StoreInventoryResource&& other) noexcept = default; // move constructor + + StoreInventoryResource& operator=(const StoreInventoryResource& other) = default; // copy assignment + StoreInventoryResource& operator=(StoreInventoryResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function>( + )> handler_GET_func = + []() -> std::pair> + { throw StoreApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair> handler_GET( + ); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleStoreApiException(const StoreApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + +/// +/// Place an order for a pet +/// +/// +/// +/// +class StoreOrderResource: public restbed::Resource +{ +public: + StoreOrderResource(const std::string& context = "/v2"); + virtual ~StoreOrderResource() = default; + + StoreOrderResource( + const StoreOrderResource& other) = default; // copy constructor + StoreOrderResource(StoreOrderResource&& other) noexcept = default; // move constructor + + StoreOrderResource& operator=(const StoreOrderResource& other) = default; // copy assignment + StoreOrderResource& operator=(StoreOrderResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + Order & order)> handler_POST_func = + [](Order &) -> std::pair + { throw StoreApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_POST( + Order & order); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleStoreApiException(const StoreApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +} /* namespace StoreApiResources */ + +using StoreApiStoreOrderOrder_idResource [[deprecated]] = StoreApiResources::StoreOrderOrder_idResource; +using StoreApiStoreInventoryResource [[deprecated]] = StoreApiResources::StoreInventoryResource; +using StoreApiStoreOrderResource [[deprecated]] = StoreApiResources::StoreOrderResource; + +// +// The restbed service to actually implement the REST server +// +class StoreApi +{ +public: + explicit StoreApi(std::shared_ptr const& restbedService); + virtual ~StoreApi(); + + std::shared_ptr getStoreOrderOrder_idResource(); + std::shared_ptr getStoreInventoryResource(); + std::shared_ptr getStoreOrderResource(); + + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + [[deprecated("use setResource()")]] + virtual void setStoreApiStoreOrderOrder_idResource(std::shared_ptr spStoreApiStoreOrderOrder_idResource); + [[deprecated("use setResource()")]] + virtual void setStoreApiStoreInventoryResource(std::shared_ptr spStoreApiStoreInventoryResource); + [[deprecated("use setResource()")]] + virtual void setStoreApiStoreOrderResource(std::shared_ptr spStoreApiStoreOrderResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spStoreOrderOrder_idResource; + std::shared_ptr m_spStoreInventoryResource; + std::shared_ptr m_spStoreOrderResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* StoreApi_H_ */ + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.cpp new file mode 100644 index 0000000000..43ca7c8807 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.cpp @@ -0,0 +1,1047 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "UserApi.h" + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +namespace { +[[maybe_unused]] +std::string selectPreferredContentType(const std::vector& contentTypes) { + if (contentTypes.size() == 0) { + return "application/json"; + } + + if (contentTypes.size() == 1) { + return contentTypes.at(0); + } + + static const std::array preferredTypes = {"json", "xml"}; + for (const auto& preferredType: preferredTypes) { + const auto ret = std::find_if(contentTypes.cbegin(), + contentTypes.cend(), + [preferredType](const std::string& str) { + return str.find(preferredType) != std::string::npos;}); + if (ret != contentTypes.cend()) { + return *ret; + } + } + + return contentTypes.at(0); +} +} + +UserApiException::UserApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int UserApiException::getStatus() const +{ + return m_status; +} +const char* UserApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +MODEL_T extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = MODEL_T(pt); + return model; +} + +template +std::vector extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector(); + for (const auto& child: pt) { + arrayRet.emplace_back(MODEL_T(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +namespace UserApiResources { +UserResource::UserResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user"); + this->set_method_handler("POST", + std::bind(&UserResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair UserResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void UserResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto user = extractJsonModelBodyParam(bodyContent); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(user); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 0) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "successful operation"; + + returnResponse(session, 0, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserResource::handler_POST( + User & user) +{ + return handler_POST_func(user); +} + + +std::string UserResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string UserResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +UserCreateWithArrayResource::UserCreateWithArrayResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/createWithArray"); + this->set_method_handler("POST", + std::bind(&UserCreateWithArrayResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair UserCreateWithArrayResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserCreateWithArrayResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserCreateWithArrayResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserCreateWithArrayResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserCreateWithArrayResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void UserCreateWithArrayResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserCreateWithArrayResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto user = extractJsonArrayBodyParam(bodyContent); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(user); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 0) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "successful operation"; + + returnResponse(session, 0, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserCreateWithArrayResource::handler_POST( + std::vector & user) +{ + return handler_POST_func(user); +} + + +std::string UserCreateWithArrayResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string UserCreateWithArrayResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +UserCreateWithListResource::UserCreateWithListResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/createWithList"); + this->set_method_handler("POST", + std::bind(&UserCreateWithListResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair UserCreateWithListResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserCreateWithListResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserCreateWithListResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserCreateWithListResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserCreateWithListResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void UserCreateWithListResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserCreateWithListResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto user = extractJsonArrayBodyParam(bodyContent); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(user); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 0) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "successful operation"; + + returnResponse(session, 0, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserCreateWithListResource::handler_POST( + std::vector & user) +{ + return handler_POST_func(user); +} + + +std::string UserCreateWithListResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string UserCreateWithListResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +UserUsernameResource::UserUsernameResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/{username: .*}"); + this->set_method_handler("DELETE", + std::bind(&UserUsernameResource::handler_DELETE_internal, this, + std::placeholders::_1)); + this->set_method_handler("GET", + std::bind(&UserUsernameResource::handler_GET_internal, this, + std::placeholders::_1)); + this->set_method_handler("PUT", + std::bind(&UserUsernameResource::handler_PUT_internal, this, + std::placeholders::_1)); +} + +std::pair UserUsernameResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserUsernameResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserUsernameResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserUsernameResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserUsernameResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void UserUsernameResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserUsernameResource::handler_DELETE_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // Getting the path params + std::string username = request->get_path_parameter("username", ""); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(username); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + }; + + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid username supplied"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 404) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "User not found"; + + returnResponse(session, 404, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void UserUsernameResource::handler_GET_internal(const std::shared_ptr session) { + const auto request = session->get_request(); + // Getting the path params + std::string username = request->get_path_parameter("username", ""); + + int status_code = 500; + User resultObject = User{}; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(username); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/xml","application/json", + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject.toJsonString(); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid username supplied"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 404) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "User not found"; + + returnResponse(session, 404, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} +// x-extension +void UserUsernameResource::handler_PUT_internal(const std::shared_ptr session) { + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + auto user = extractJsonModelBodyParam(bodyContent); + // Getting the path params + std::string username = request->get_path_parameter("username", ""); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_PUT(username, user); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid user supplied"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 404) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "User not found"; + + returnResponse(session, 404, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + +int UserUsernameResource::handler_DELETE( + std::string & username) +{ + return handler_DELETE_func(username); +} + +std::pair UserUsernameResource::handler_GET( + std::string & username) +{ + return handler_GET_func(username); +} +int UserUsernameResource::handler_PUT( + std::string & username, User & user) +{ + return handler_PUT_func(username, user); +} + +std::string UserUsernameResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string UserUsernameResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +UserLoginResource::UserLoginResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/login"); + this->set_method_handler("GET", + std::bind(&UserLoginResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair UserLoginResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserLoginResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserLoginResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserLoginResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserLoginResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void UserLoginResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserLoginResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // Getting the query params + std::string username = request->get_query_parameter("username", ""); + std::string password = request->get_query_parameter("password", ""); + + int status_code = 500; + std::string resultObject = ""; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(username, password); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/xml","application/json", + }; + static const std::string acceptTypes{ + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + result = resultObject; + // Description: calls per hour allowed by the user + setResponseHeader(session, "X-Rate-Limit"); + // Description: date in UTC when token expires + setResponseHeader(session, "X-Expires-After"); + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + if (status_code == 400) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "Invalid username/password supplied"; + + returnResponse(session, 400, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair UserLoginResource::handler_GET( + std::string & username, std::string & password) +{ + return handler_GET_func(username, password); +} + + +std::string UserLoginResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string UserLoginResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} +UserLogoutResource::UserLogoutResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/logout"); + this->set_method_handler("GET", + std::bind(&UserLogoutResource::handler_GET_internal, this, + std::placeholders::_1)); +} + +std::pair UserLogoutResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserLogoutResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserLogoutResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserLogoutResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserLogoutResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void UserLogoutResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserLogoutResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_GET(); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + }; + + if (status_code == 0) { + responseHeaders.insert(std::make_pair("Content-Type", "text/plain")); + result = "successful operation"; + + returnResponse(session, 0, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserLogoutResource::handler_GET( + ) +{ + return handler_GET_func(); +} + + +std::string UserLogoutResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string UserLogoutResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} + +} /* namespace UserApiResources */ + +UserApi::UserApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +UserApi::~UserApi() {} + +std::shared_ptr UserApi::getUserResource() { + if (!m_spUserResource) { + setResource(std::make_shared()); + } + return m_spUserResource; +} +std::shared_ptr UserApi::getUserCreateWithArrayResource() { + if (!m_spUserCreateWithArrayResource) { + setResource(std::make_shared()); + } + return m_spUserCreateWithArrayResource; +} +std::shared_ptr UserApi::getUserCreateWithListResource() { + if (!m_spUserCreateWithListResource) { + setResource(std::make_shared()); + } + return m_spUserCreateWithListResource; +} +std::shared_ptr UserApi::getUserUsernameResource() { + if (!m_spUserUsernameResource) { + setResource(std::make_shared()); + } + return m_spUserUsernameResource; +} +std::shared_ptr UserApi::getUserLoginResource() { + if (!m_spUserLoginResource) { + setResource(std::make_shared()); + } + return m_spUserLoginResource; +} +std::shared_ptr UserApi::getUserLogoutResource() { + if (!m_spUserLogoutResource) { + setResource(std::make_shared()); + } + return m_spUserLogoutResource; +} +void UserApi::setResource(std::shared_ptr resource) { + m_spUserResource = resource; + m_service->publish(m_spUserResource); +} +void UserApi::setResource(std::shared_ptr resource) { + m_spUserCreateWithArrayResource = resource; + m_service->publish(m_spUserCreateWithArrayResource); +} +void UserApi::setResource(std::shared_ptr resource) { + m_spUserCreateWithListResource = resource; + m_service->publish(m_spUserCreateWithListResource); +} +void UserApi::setResource(std::shared_ptr resource) { + m_spUserUsernameResource = resource; + m_service->publish(m_spUserUsernameResource); +} +void UserApi::setResource(std::shared_ptr resource) { + m_spUserLoginResource = resource; + m_service->publish(m_spUserLoginResource); +} +void UserApi::setResource(std::shared_ptr resource) { + m_spUserLogoutResource = resource; + m_service->publish(m_spUserLogoutResource); +} +void UserApi::setUserApiUserResource(std::shared_ptr spUserResource) { + m_spUserResource = spUserResource; + m_service->publish(m_spUserResource); +} +void UserApi::setUserApiUserCreateWithArrayResource(std::shared_ptr spUserCreateWithArrayResource) { + m_spUserCreateWithArrayResource = spUserCreateWithArrayResource; + m_service->publish(m_spUserCreateWithArrayResource); +} +void UserApi::setUserApiUserCreateWithListResource(std::shared_ptr spUserCreateWithListResource) { + m_spUserCreateWithListResource = spUserCreateWithListResource; + m_service->publish(m_spUserCreateWithListResource); +} +void UserApi::setUserApiUserUsernameResource(std::shared_ptr spUserUsernameResource) { + m_spUserUsernameResource = spUserUsernameResource; + m_service->publish(m_spUserUsernameResource); +} +void UserApi::setUserApiUserLoginResource(std::shared_ptr spUserLoginResource) { + m_spUserLoginResource = spUserLoginResource; + m_service->publish(m_spUserLoginResource); +} +void UserApi::setUserApiUserLogoutResource(std::shared_ptr spUserLogoutResource) { + m_spUserLogoutResource = spUserLogoutResource; + m_service->publish(m_spUserLogoutResource); +} + + +void UserApi::publishDefaultResources() { + if (!m_spUserResource) { + setResource(std::make_shared()); + } + if (!m_spUserCreateWithArrayResource) { + setResource(std::make_shared()); + } + if (!m_spUserCreateWithListResource) { + setResource(std::make_shared()); + } + if (!m_spUserUsernameResource) { + setResource(std::make_shared()); + } + if (!m_spUserLoginResource) { + setResource(std::make_shared()); + } + if (!m_spUserLogoutResource) { + setResource(std::make_shared()); + } +} + +std::shared_ptr UserApi::service() { + return m_service; +} + + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.h b/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.h new file mode 100644 index 0000000000..6a94da45c4 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.h @@ -0,0 +1,517 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * UserApi.h + * + * + */ + +#ifndef UserApi_H_ +#define UserApi_H_ + + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "User.h" +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace api { + +using namespace org::openapitools::server::model; + +/// +/// Exception to flag problems in the handlers +/// +class UserApiException: public std::exception +{ +public: + UserApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + +namespace UserApiResources { +/// +/// Create user +/// +/// +/// This can only be done by the logged in user. +/// +class UserResource: public restbed::Resource +{ +public: + UserResource(const std::string& context = "/v2"); + virtual ~UserResource() = default; + + UserResource( + const UserResource& other) = default; // copy constructor + UserResource(UserResource&& other) noexcept = default; // move constructor + + UserResource& operator=(const UserResource& other) = default; // copy assignment + UserResource& operator=(UserResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_POST_func = + [](User &) -> int + { throw UserApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_POST( + User & user); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// Creates list of users with given input array +/// +/// +/// +/// +class UserCreateWithArrayResource: public restbed::Resource +{ +public: + UserCreateWithArrayResource(const std::string& context = "/v2"); + virtual ~UserCreateWithArrayResource() = default; + + UserCreateWithArrayResource( + const UserCreateWithArrayResource& other) = default; // copy constructor + UserCreateWithArrayResource(UserCreateWithArrayResource&& other) noexcept = default; // move constructor + + UserCreateWithArrayResource& operator=(const UserCreateWithArrayResource& other) = default; // copy assignment + UserCreateWithArrayResource& operator=(UserCreateWithArrayResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function & user)> handler_POST_func = + [](std::vector &) -> int + { throw UserApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_POST( + std::vector & user); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// Creates list of users with given input array +/// +/// +/// +/// +class UserCreateWithListResource: public restbed::Resource +{ +public: + UserCreateWithListResource(const std::string& context = "/v2"); + virtual ~UserCreateWithListResource() = default; + + UserCreateWithListResource( + const UserCreateWithListResource& other) = default; // copy constructor + UserCreateWithListResource(UserCreateWithListResource&& other) noexcept = default; // move constructor + + UserCreateWithListResource& operator=(const UserCreateWithListResource& other) = default; // copy assignment + UserCreateWithListResource& operator=(UserCreateWithListResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function & user)> handler_POST_func = + [](std::vector &) -> int + { throw UserApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_POST( + std::vector & user); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// Delete user +/// +/// +/// This can only be done by the logged in user. +/// +class UserUsernameResource: public restbed::Resource +{ +public: + UserUsernameResource(const std::string& context = "/v2"); + virtual ~UserUsernameResource() = default; + + UserUsernameResource( + const UserUsernameResource& other) = default; // copy constructor + UserUsernameResource(UserUsernameResource&& other) noexcept = default; // move constructor + + UserUsernameResource& operator=(const UserUsernameResource& other) = default; // copy assignment + UserUsernameResource& operator=(UserUsernameResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_DELETE_func = + [](std::string &) -> int + { throw UserApiException(501, "Not implemented"); }; + + std::function( + std::string & username)> handler_GET_func = + [](std::string &) -> std::pair + { throw UserApiException(501, "Not implemented"); }; + + std::function handler_PUT_func = + [](std::string &, User &) -> int + { throw UserApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_DELETE( + std::string & username); + + virtual std::pair handler_GET( + std::string & username); + virtual int handler_PUT( + std::string & username, User & user); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_DELETE_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); + void handler_PUT_internal(const std::shared_ptr session); +}; + +/// +/// Logs user into the system +/// +/// +/// +/// +class UserLoginResource: public restbed::Resource +{ +public: + UserLoginResource(const std::string& context = "/v2"); + virtual ~UserLoginResource() = default; + + UserLoginResource( + const UserLoginResource& other) = default; // copy constructor + UserLoginResource(UserLoginResource&& other) noexcept = default; // move constructor + + UserLoginResource& operator=(const UserLoginResource& other) = default; // copy assignment + UserLoginResource& operator=(UserLoginResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function( + std::string & username, std::string & password)> handler_GET_func = + [](std::string &, std::string &) -> std::pair + { throw UserApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual std::pair handler_GET( + std::string & username, std::string & password); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + +/// +/// Logs out current logged in user session +/// +/// +/// +/// +class UserLogoutResource: public restbed::Resource +{ +public: + UserLogoutResource(const std::string& context = "/v2"); + virtual ~UserLogoutResource() = default; + + UserLogoutResource( + const UserLogoutResource& other) = default; // copy constructor + UserLogoutResource(UserLogoutResource&& other) noexcept = default; // move constructor + + UserLogoutResource& operator=(const UserLogoutResource& other) = default; // copy assignment + UserLogoutResource& operator=(UserLogoutResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function handler_GET_func = + []() -> int + { throw UserApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_GET( + ); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_GET_internal(const std::shared_ptr session); +}; + +} /* namespace UserApiResources */ + +using UserApiUserResource [[deprecated]] = UserApiResources::UserResource; +using UserApiUserCreateWithArrayResource [[deprecated]] = UserApiResources::UserCreateWithArrayResource; +using UserApiUserCreateWithListResource [[deprecated]] = UserApiResources::UserCreateWithListResource; +using UserApiUserUsernameResource [[deprecated]] = UserApiResources::UserUsernameResource; +using UserApiUserLoginResource [[deprecated]] = UserApiResources::UserLoginResource; +using UserApiUserLogoutResource [[deprecated]] = UserApiResources::UserLogoutResource; + +// +// The restbed service to actually implement the REST server +// +class UserApi +{ +public: + explicit UserApi(std::shared_ptr const& restbedService); + virtual ~UserApi(); + + std::shared_ptr getUserResource(); + std::shared_ptr getUserCreateWithArrayResource(); + std::shared_ptr getUserCreateWithListResource(); + std::shared_ptr getUserUsernameResource(); + std::shared_ptr getUserLoginResource(); + std::shared_ptr getUserLogoutResource(); + + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); + [[deprecated("use setResource()")]] + virtual void setUserApiUserResource(std::shared_ptr spUserApiUserResource); + [[deprecated("use setResource()")]] + virtual void setUserApiUserCreateWithArrayResource(std::shared_ptr spUserApiUserCreateWithArrayResource); + [[deprecated("use setResource()")]] + virtual void setUserApiUserCreateWithListResource(std::shared_ptr spUserApiUserCreateWithListResource); + [[deprecated("use setResource()")]] + virtual void setUserApiUserUsernameResource(std::shared_ptr spUserApiUserUsernameResource); + [[deprecated("use setResource()")]] + virtual void setUserApiUserLoginResource(std::shared_ptr spUserApiUserLoginResource); + [[deprecated("use setResource()")]] + virtual void setUserApiUserLogoutResource(std::shared_ptr spUserApiUserLogoutResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + +protected: + std::shared_ptr m_spUserResource; + std::shared_ptr m_spUserCreateWithArrayResource; + std::shared_ptr m_spUserCreateWithListResource; + std::shared_ptr m_spUserUsernameResource; + std::shared_ptr m_spUserLoginResource; + std::shared_ptr m_spUserLogoutResource; + +private: + std::shared_ptr m_service; +}; + + +} +} +} +} + +#endif /* UserApi_H_ */ + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/git_push.sh b/samples/server/petstore/cpp-restbed/generated/3_0/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/200_response.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/200_response.cpp new file mode 100644 index 0000000000..c28bfae43a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/200_response.cpp @@ -0,0 +1,118 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.1.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "200_response.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +200_response::200_response(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string 200_response::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void 200_response::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree 200_response::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("name", m_Name); + pt.put("class", m_r_class); + return pt; +} + +void 200_response::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Name = pt.get("name", 0); + m_r_class = pt.get("class", ""); +} + +int32_t 200_response::getName() const +{ + return m_Name; +} + +void 200_response::setName(int32_t value) +{ + m_Name = value; +} + + +std::string 200_response::getRClass() const +{ + return m_r_class; +} + +void 200_response::setRClass(std::string value) +{ + m_r_class = value; +} + + + +std::vector<200_response> create200_responseVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector<200_response>(); + for (const auto& child: pt) { + vec.emplace_back(200_response(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/200_response.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/200_response.h new file mode 100644 index 0000000000..cb325c759f --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/200_response.h @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 6.1.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * 200_response.h + * + * Model for testing model name starting with number + */ + +#ifndef 200_response_H_ +#define 200_response_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// Model for testing model name starting with number +/// +class 200_response +{ +public: + 200_response() = default; + explicit 200_response(boost::property_tree::ptree const& pt); + virtual ~200_response() = default; + + 200_response(const 200_response& other) = default; // copy constructor + 200_response(200_response&& other) noexcept = default; // move constructor + + 200_response& operator=(const 200_response& other) = default; // copy assignment + 200_response& operator=(200_response&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// 200_response members + + /// + /// + /// + int32_t getName() const; + void setName(int32_t value); + + /// + /// + /// + std::string getRClass() const; + void setRClass(std::string value); + +protected: + int32_t m_Name = 0; + std::string m_r_class = ""; +}; + +std::vector<200_response> create200_responseVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt<200_response>(const 200_response& val) { + return val.toPropertyTree(); +} + +template<> +inline 200_response fromPt<200_response>(const boost::property_tree::ptree& pt) { + 200_response ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* 200_response_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.cpp new file mode 100644 index 0000000000..692371c36b --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.cpp @@ -0,0 +1,132 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "AdditionalPropertiesClass.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +AdditionalPropertiesClass::AdditionalPropertiesClass(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string AdditionalPropertiesClass::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void AdditionalPropertiesClass::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree AdditionalPropertiesClass::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + // generate tree for Map_property + if (!m_Map_property.empty()) { + tmp_node = toPt(m_Map_property); + pt.add_child("map_property", tmp_node); + } + tmp_node.clear(); + // generate tree for Map_of_map_property + if (!m_Map_of_map_property.empty()) { + tmp_node = toPt(m_Map_of_map_property); + pt.add_child("map_of_map_property", tmp_node); + } + tmp_node.clear(); + return pt; +} + +void AdditionalPropertiesClass::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + if (pt.get_child_optional("map_property")) { + m_Map_property = fromPt>(pt.get_child("map_property")); + } + if (pt.get_child_optional("map_of_map_property")) { + m_Map_of_map_property = fromPt>>(pt.get_child("map_of_map_property")); + } +} + +std::map AdditionalPropertiesClass::getMapProperty() const +{ + return m_Map_property; +} + +void AdditionalPropertiesClass::setMapProperty(std::map value) +{ + m_Map_property = value; +} + + +std::map> AdditionalPropertiesClass::getMapOfMapProperty() const +{ + return m_Map_of_map_property; +} + +void AdditionalPropertiesClass::setMapOfMapProperty(std::map> value) +{ + m_Map_of_map_property = value; +} + + + +std::vector createAdditionalPropertiesClassVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(AdditionalPropertiesClass(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.h new file mode 100644 index 0000000000..5a000122de --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.h @@ -0,0 +1,97 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * AdditionalPropertiesClass.h + * + * + */ + +#ifndef AdditionalPropertiesClass_H_ +#define AdditionalPropertiesClass_H_ + + + +#include +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class AdditionalPropertiesClass +{ +public: + AdditionalPropertiesClass() = default; + explicit AdditionalPropertiesClass(boost::property_tree::ptree const& pt); + virtual ~AdditionalPropertiesClass() = default; + + AdditionalPropertiesClass(const AdditionalPropertiesClass& other) = default; // copy constructor + AdditionalPropertiesClass(AdditionalPropertiesClass&& other) noexcept = default; // move constructor + + AdditionalPropertiesClass& operator=(const AdditionalPropertiesClass& other) = default; // copy assignment + AdditionalPropertiesClass& operator=(AdditionalPropertiesClass&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// AdditionalPropertiesClass members + + /// + /// + /// + std::map getMapProperty() const; + void setMapProperty(std::map value); + + /// + /// + /// + std::map> getMapOfMapProperty() const; + void setMapOfMapProperty(std::map> value); + +protected: + std::map m_Map_property; + std::map> m_Map_of_map_property; +}; + +std::vector createAdditionalPropertiesClassVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const AdditionalPropertiesClass& val) { + return val.toPropertyTree(); +} + +template<> +inline AdditionalPropertiesClass fromPt(const boost::property_tree::ptree& pt) { + AdditionalPropertiesClass ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* AdditionalPropertiesClass_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.cpp new file mode 100644 index 0000000000..304b8ae116 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.cpp @@ -0,0 +1,120 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "AllOfWithSingleRef.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +AllOfWithSingleRef::AllOfWithSingleRef(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string AllOfWithSingleRef::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void AllOfWithSingleRef::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree AllOfWithSingleRef::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("username", m_Username); + pt.add_child("SingleRefType", m_SingleRefType.toPropertyTree()); + return pt; +} + +void AllOfWithSingleRef::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Username = pt.get("username", ""); + if (pt.get_child_optional("SingleRefType")) { + m_SingleRefType = fromPt(pt.get_child("SingleRefType")); + } +} + +std::string AllOfWithSingleRef::getUsername() const +{ + return m_Username; +} + +void AllOfWithSingleRef::setUsername(std::string value) +{ + m_Username = value; +} + + +SingleRefType AllOfWithSingleRef::getSingleRefType() const +{ + return m_SingleRefType; +} + +void AllOfWithSingleRef::setSingleRefType(SingleRefType value) +{ + m_SingleRefType = value; +} + + + +std::vector createAllOfWithSingleRefVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(AllOfWithSingleRef(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.h new file mode 100644 index 0000000000..cb284e9d4b --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.h @@ -0,0 +1,97 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * AllOfWithSingleRef.h + * + * + */ + +#ifndef AllOfWithSingleRef_H_ +#define AllOfWithSingleRef_H_ + + + +#include +#include "SingleRefType.h" +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class AllOfWithSingleRef +{ +public: + AllOfWithSingleRef() = default; + explicit AllOfWithSingleRef(boost::property_tree::ptree const& pt); + virtual ~AllOfWithSingleRef() = default; + + AllOfWithSingleRef(const AllOfWithSingleRef& other) = default; // copy constructor + AllOfWithSingleRef(AllOfWithSingleRef&& other) noexcept = default; // move constructor + + AllOfWithSingleRef& operator=(const AllOfWithSingleRef& other) = default; // copy assignment + AllOfWithSingleRef& operator=(AllOfWithSingleRef&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// AllOfWithSingleRef members + + /// + /// + /// + std::string getUsername() const; + void setUsername(std::string value); + + /// + /// + /// + SingleRefType getSingleRefType() const; + void setSingleRefType(SingleRefType value); + +protected: + std::string m_Username = ""; + SingleRefType m_SingleRefType; +}; + +std::vector createAllOfWithSingleRefVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const AllOfWithSingleRef& val) { + return val.toPropertyTree(); +} + +template<> +inline AllOfWithSingleRef fromPt(const boost::property_tree::ptree& pt) { + AllOfWithSingleRef ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* AllOfWithSingleRef_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.cpp new file mode 100644 index 0000000000..2447eb1905 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.cpp @@ -0,0 +1,118 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Animal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Animal::Animal(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Animal::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Animal::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Animal::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("className", m_ClassName); + pt.put("color", m_Color); + return pt; +} + +void Animal::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_ClassName = pt.get("className", ""); + m_Color = pt.get("color", "red"); +} + +std::string Animal::getClassName() const +{ + return m_ClassName; +} + +void Animal::setClassName(std::string value) +{ + m_ClassName = value; +} + + +std::string Animal::getColor() const +{ + return m_Color; +} + +void Animal::setColor(std::string value) +{ + m_Color = value; +} + + + +std::vector createAnimalVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Animal(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.h new file mode 100644 index 0000000000..9ae9d299ec --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.h @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Animal.h + * + * + */ + +#ifndef Animal_H_ +#define Animal_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Animal +{ +public: + Animal() = default; + explicit Animal(boost::property_tree::ptree const& pt); + virtual ~Animal() = default; + + Animal(const Animal& other) = default; // copy constructor + Animal(Animal&& other) noexcept = default; // move constructor + + Animal& operator=(const Animal& other) = default; // copy assignment + Animal& operator=(Animal&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Animal members + + /// + /// + /// + std::string getClassName() const; + void setClassName(std::string value); + + /// + /// + /// + std::string getColor() const; + void setColor(std::string value); + +protected: + std::string m_ClassName = ""; + std::string m_Color = "red"; +}; + +std::vector createAnimalVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Animal& val) { + return val.toPropertyTree(); +} + +template<> +inline Animal fromPt(const boost::property_tree::ptree& pt) { + Animal ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Animal_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.cpp new file mode 100644 index 0000000000..524787bed0 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.cpp @@ -0,0 +1,131 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "ApiResponse.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +ApiResponse::ApiResponse(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string ApiResponse::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void ApiResponse::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree ApiResponse::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("code", m_Code); + pt.put("type", m_Type); + pt.put("message", m_Message); + return pt; +} + +void ApiResponse::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Code = pt.get("code", 0); + m_Type = pt.get("type", ""); + m_Message = pt.get("message", ""); +} + +int32_t ApiResponse::getCode() const +{ + return m_Code; +} + +void ApiResponse::setCode(int32_t value) +{ + m_Code = value; +} + + +std::string ApiResponse::getType() const +{ + return m_Type; +} + +void ApiResponse::setType(std::string value) +{ + m_Type = value; +} + + +std::string ApiResponse::getMessage() const +{ + return m_Message; +} + +void ApiResponse::setMessage(std::string value) +{ + m_Message = value; +} + + + +std::vector createApiResponseVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(ApiResponse(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.h new file mode 100644 index 0000000000..ebd3d47bd5 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.h @@ -0,0 +1,103 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ApiResponse.h + * + * + */ + +#ifndef ApiResponse_H_ +#define ApiResponse_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class ApiResponse +{ +public: + ApiResponse() = default; + explicit ApiResponse(boost::property_tree::ptree const& pt); + virtual ~ApiResponse() = default; + + ApiResponse(const ApiResponse& other) = default; // copy constructor + ApiResponse(ApiResponse&& other) noexcept = default; // move constructor + + ApiResponse& operator=(const ApiResponse& other) = default; // copy assignment + ApiResponse& operator=(ApiResponse&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// ApiResponse members + + /// + /// + /// + int32_t getCode() const; + void setCode(int32_t value); + + /// + /// + /// + std::string getType() const; + void setType(std::string value); + + /// + /// + /// + std::string getMessage() const; + void setMessage(std::string value); + +protected: + int32_t m_Code = 0; + std::string m_Type = ""; + std::string m_Message = ""; +}; + +std::vector createApiResponseVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const ApiResponse& val) { + return val.toPropertyTree(); +} + +template<> +inline ApiResponse fromPt(const boost::property_tree::ptree& pt) { + ApiResponse ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* ApiResponse_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.cpp new file mode 100644 index 0000000000..4e57eb9103 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.cpp @@ -0,0 +1,114 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "ArrayOfArrayOfNumberOnly.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +ArrayOfArrayOfNumberOnly::ArrayOfArrayOfNumberOnly(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string ArrayOfArrayOfNumberOnly::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void ArrayOfArrayOfNumberOnly::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree ArrayOfArrayOfNumberOnly::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + // generate tree for ArrayArrayNumber + tmp_node.clear(); + if (!m_ArrayArrayNumber.empty()) { + tmp_node = toPt(m_ArrayArrayNumber); + pt.add_child("ArrayArrayNumber", tmp_node); + tmp_node.clear(); + } + return pt; +} + +void ArrayOfArrayOfNumberOnly::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + // push all items of ArrayArrayNumber into member + if (pt.get_child_optional("ArrayArrayNumber")) { + m_ArrayArrayNumber = fromPt>>(pt.get_child("ArrayArrayNumber")); + } +} + +std::vector> ArrayOfArrayOfNumberOnly::getArrayArrayNumber() const +{ + return m_ArrayArrayNumber; +} + +void ArrayOfArrayOfNumberOnly::setArrayArrayNumber(std::vector> value) +{ + m_ArrayArrayNumber = value; +} + + + +std::vector createArrayOfArrayOfNumberOnlyVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(ArrayOfArrayOfNumberOnly(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.h new file mode 100644 index 0000000000..c96b6a00b6 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ArrayOfArrayOfNumberOnly.h + * + * + */ + +#ifndef ArrayOfArrayOfNumberOnly_H_ +#define ArrayOfArrayOfNumberOnly_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class ArrayOfArrayOfNumberOnly +{ +public: + ArrayOfArrayOfNumberOnly() = default; + explicit ArrayOfArrayOfNumberOnly(boost::property_tree::ptree const& pt); + virtual ~ArrayOfArrayOfNumberOnly() = default; + + ArrayOfArrayOfNumberOnly(const ArrayOfArrayOfNumberOnly& other) = default; // copy constructor + ArrayOfArrayOfNumberOnly(ArrayOfArrayOfNumberOnly&& other) noexcept = default; // move constructor + + ArrayOfArrayOfNumberOnly& operator=(const ArrayOfArrayOfNumberOnly& other) = default; // copy assignment + ArrayOfArrayOfNumberOnly& operator=(ArrayOfArrayOfNumberOnly&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// ArrayOfArrayOfNumberOnly members + + /// + /// + /// + std::vector> getArrayArrayNumber() const; + void setArrayArrayNumber(std::vector> value); + +protected: + std::vector> m_ArrayArrayNumber; +}; + +std::vector createArrayOfArrayOfNumberOnlyVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const ArrayOfArrayOfNumberOnly& val) { + return val.toPropertyTree(); +} + +template<> +inline ArrayOfArrayOfNumberOnly fromPt(const boost::property_tree::ptree& pt) { + ArrayOfArrayOfNumberOnly ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* ArrayOfArrayOfNumberOnly_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.cpp new file mode 100644 index 0000000000..3c9a4f50c1 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.cpp @@ -0,0 +1,114 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "ArrayOfNumberOnly.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +ArrayOfNumberOnly::ArrayOfNumberOnly(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string ArrayOfNumberOnly::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void ArrayOfNumberOnly::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree ArrayOfNumberOnly::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + // generate tree for ArrayNumber + tmp_node.clear(); + if (!m_ArrayNumber.empty()) { + tmp_node = toPt(m_ArrayNumber); + pt.add_child("ArrayNumber", tmp_node); + tmp_node.clear(); + } + return pt; +} + +void ArrayOfNumberOnly::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + // push all items of ArrayNumber into member + if (pt.get_child_optional("ArrayNumber")) { + m_ArrayNumber = fromPt>(pt.get_child("ArrayNumber")); + } +} + +std::vector ArrayOfNumberOnly::getArrayNumber() const +{ + return m_ArrayNumber; +} + +void ArrayOfNumberOnly::setArrayNumber(std::vector value) +{ + m_ArrayNumber = value; +} + + + +std::vector createArrayOfNumberOnlyVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(ArrayOfNumberOnly(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.h new file mode 100644 index 0000000000..0a5c374531 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ArrayOfNumberOnly.h + * + * + */ + +#ifndef ArrayOfNumberOnly_H_ +#define ArrayOfNumberOnly_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class ArrayOfNumberOnly +{ +public: + ArrayOfNumberOnly() = default; + explicit ArrayOfNumberOnly(boost::property_tree::ptree const& pt); + virtual ~ArrayOfNumberOnly() = default; + + ArrayOfNumberOnly(const ArrayOfNumberOnly& other) = default; // copy constructor + ArrayOfNumberOnly(ArrayOfNumberOnly&& other) noexcept = default; // move constructor + + ArrayOfNumberOnly& operator=(const ArrayOfNumberOnly& other) = default; // copy assignment + ArrayOfNumberOnly& operator=(ArrayOfNumberOnly&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// ArrayOfNumberOnly members + + /// + /// + /// + std::vector getArrayNumber() const; + void setArrayNumber(std::vector value); + +protected: + std::vector m_ArrayNumber; +}; + +std::vector createArrayOfNumberOnlyVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const ArrayOfNumberOnly& val) { + return val.toPropertyTree(); +} + +template<> +inline ArrayOfNumberOnly fromPt(const boost::property_tree::ptree& pt) { + ArrayOfNumberOnly ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* ArrayOfNumberOnly_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.cpp new file mode 100644 index 0000000000..73e255caf0 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.cpp @@ -0,0 +1,158 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "ArrayTest.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +ArrayTest::ArrayTest(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string ArrayTest::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void ArrayTest::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree ArrayTest::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + // generate tree for Array_of_string + tmp_node.clear(); + if (!m_Array_of_string.empty()) { + tmp_node = toPt(m_Array_of_string); + pt.add_child("array_of_string", tmp_node); + tmp_node.clear(); + } + // generate tree for Array_array_of_integer + tmp_node.clear(); + if (!m_Array_array_of_integer.empty()) { + tmp_node = toPt(m_Array_array_of_integer); + pt.add_child("array_array_of_integer", tmp_node); + tmp_node.clear(); + } + // generate tree for Array_array_of_model + tmp_node.clear(); + if (!m_Array_array_of_model.empty()) { + tmp_node = toPt(m_Array_array_of_model); + pt.add_child("array_array_of_model", tmp_node); + tmp_node.clear(); + } + return pt; +} + +void ArrayTest::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + // push all items of Array_of_string into member + if (pt.get_child_optional("array_of_string")) { + m_Array_of_string = fromPt>(pt.get_child("array_of_string")); + } + // push all items of Array_array_of_integer into member + if (pt.get_child_optional("array_array_of_integer")) { + m_Array_array_of_integer = fromPt>>(pt.get_child("array_array_of_integer")); + } + // push all items of Array_array_of_model into member + if (pt.get_child_optional("array_array_of_model")) { + m_Array_array_of_model = fromPt>>(pt.get_child("array_array_of_model")); + } +} + +std::vector ArrayTest::getArrayOfString() const +{ + return m_Array_of_string; +} + +void ArrayTest::setArrayOfString(std::vector value) +{ + m_Array_of_string = value; +} + + +std::vector> ArrayTest::getArrayArrayOfInteger() const +{ + return m_Array_array_of_integer; +} + +void ArrayTest::setArrayArrayOfInteger(std::vector> value) +{ + m_Array_array_of_integer = value; +} + + +std::vector> ArrayTest::getArrayArrayOfModel() const +{ + return m_Array_array_of_model; +} + +void ArrayTest::setArrayArrayOfModel(std::vector> value) +{ + m_Array_array_of_model = value; +} + + + +std::vector createArrayTestVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(ArrayTest(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.h new file mode 100644 index 0000000000..eb4f9c7681 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.h @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ArrayTest.h + * + * + */ + +#ifndef ArrayTest_H_ +#define ArrayTest_H_ + + + +#include +#include +#include "ReadOnlyFirst.h" +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class ArrayTest +{ +public: + ArrayTest() = default; + explicit ArrayTest(boost::property_tree::ptree const& pt); + virtual ~ArrayTest() = default; + + ArrayTest(const ArrayTest& other) = default; // copy constructor + ArrayTest(ArrayTest&& other) noexcept = default; // move constructor + + ArrayTest& operator=(const ArrayTest& other) = default; // copy assignment + ArrayTest& operator=(ArrayTest&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// ArrayTest members + + /// + /// + /// + std::vector getArrayOfString() const; + void setArrayOfString(std::vector value); + + /// + /// + /// + std::vector> getArrayArrayOfInteger() const; + void setArrayArrayOfInteger(std::vector> value); + + /// + /// + /// + std::vector> getArrayArrayOfModel() const; + void setArrayArrayOfModel(std::vector> value); + +protected: + std::vector m_Array_of_string; + std::vector> m_Array_array_of_integer; + std::vector> m_Array_array_of_model; +}; + +std::vector createArrayTestVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const ArrayTest& val) { + return val.toPropertyTree(); +} + +template<> +inline ArrayTest fromPt(const boost::property_tree::ptree& pt) { + ArrayTest ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* ArrayTest_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.cpp new file mode 100644 index 0000000000..3834603e14 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.cpp @@ -0,0 +1,170 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Capitalization.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Capitalization::Capitalization(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Capitalization::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Capitalization::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Capitalization::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("smallCamel", m_SmallCamel); + pt.put("CapitalCamel", m_CapitalCamel); + pt.put("small_Snake", m_Small_Snake); + pt.put("Capital_Snake", m_Capital_Snake); + pt.put("SCA_ETH_Flow_Points", m_SCA_ETH_Flow_Points); + pt.put("ATT_NAME", m_ATT_NAME); + return pt; +} + +void Capitalization::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_SmallCamel = pt.get("smallCamel", ""); + m_CapitalCamel = pt.get("CapitalCamel", ""); + m_Small_Snake = pt.get("small_Snake", ""); + m_Capital_Snake = pt.get("Capital_Snake", ""); + m_SCA_ETH_Flow_Points = pt.get("SCA_ETH_Flow_Points", ""); + m_ATT_NAME = pt.get("ATT_NAME", ""); +} + +std::string Capitalization::getSmallCamel() const +{ + return m_SmallCamel; +} + +void Capitalization::setSmallCamel(std::string value) +{ + m_SmallCamel = value; +} + + +std::string Capitalization::getCapitalCamel() const +{ + return m_CapitalCamel; +} + +void Capitalization::setCapitalCamel(std::string value) +{ + m_CapitalCamel = value; +} + + +std::string Capitalization::getSmallSnake() const +{ + return m_Small_Snake; +} + +void Capitalization::setSmallSnake(std::string value) +{ + m_Small_Snake = value; +} + + +std::string Capitalization::getCapitalSnake() const +{ + return m_Capital_Snake; +} + +void Capitalization::setCapitalSnake(std::string value) +{ + m_Capital_Snake = value; +} + + +std::string Capitalization::getSCAETHFlowPoints() const +{ + return m_SCA_ETH_Flow_Points; +} + +void Capitalization::setSCAETHFlowPoints(std::string value) +{ + m_SCA_ETH_Flow_Points = value; +} + + +std::string Capitalization::getATTNAME() const +{ + return m_ATT_NAME; +} + +void Capitalization::setATTNAME(std::string value) +{ + m_ATT_NAME = value; +} + + + +std::vector createCapitalizationVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Capitalization(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.h new file mode 100644 index 0000000000..21399991b2 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.h @@ -0,0 +1,124 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Capitalization.h + * + * + */ + +#ifndef Capitalization_H_ +#define Capitalization_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Capitalization +{ +public: + Capitalization() = default; + explicit Capitalization(boost::property_tree::ptree const& pt); + virtual ~Capitalization() = default; + + Capitalization(const Capitalization& other) = default; // copy constructor + Capitalization(Capitalization&& other) noexcept = default; // move constructor + + Capitalization& operator=(const Capitalization& other) = default; // copy assignment + Capitalization& operator=(Capitalization&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Capitalization members + + /// + /// + /// + std::string getSmallCamel() const; + void setSmallCamel(std::string value); + + /// + /// + /// + std::string getCapitalCamel() const; + void setCapitalCamel(std::string value); + + /// + /// + /// + std::string getSmallSnake() const; + void setSmallSnake(std::string value); + + /// + /// + /// + std::string getCapitalSnake() const; + void setCapitalSnake(std::string value); + + /// + /// + /// + std::string getSCAETHFlowPoints() const; + void setSCAETHFlowPoints(std::string value); + + /// + /// Name of the pet + /// + std::string getATTNAME() const; + void setATTNAME(std::string value); + +protected: + std::string m_SmallCamel = ""; + std::string m_CapitalCamel = ""; + std::string m_Small_Snake = ""; + std::string m_Capital_Snake = ""; + std::string m_SCA_ETH_Flow_Points = ""; + std::string m_ATT_NAME = ""; +}; + +std::vector createCapitalizationVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Capitalization& val) { + return val.toPropertyTree(); +} + +template<> +inline Capitalization fromPt(const boost::property_tree::ptree& pt) { + Capitalization ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Capitalization_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.cpp new file mode 100644 index 0000000000..84a0375a2b --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.cpp @@ -0,0 +1,131 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Cat.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Cat::Cat(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Cat::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Cat::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Cat::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("className", m_ClassName); + pt.put("color", m_Color); + pt.put("declawed", m_Declawed); + return pt; +} + +void Cat::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_ClassName = pt.get("className", ""); + m_Color = pt.get("color", "red"); + m_Declawed = pt.get("declawed", false); +} + +std::string Cat::getClassName() const +{ + return m_ClassName; +} + +void Cat::setClassName(std::string value) +{ + m_ClassName = value; +} + + +std::string Cat::getColor() const +{ + return m_Color; +} + +void Cat::setColor(std::string value) +{ + m_Color = value; +} + + +bool Cat::isDeclawed() const +{ + return m_Declawed; +} + +void Cat::setDeclawed(bool value) +{ + m_Declawed = value; +} + + + +std::vector createCatVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Cat(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.h new file mode 100644 index 0000000000..a71d02e05c --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.h @@ -0,0 +1,106 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Cat.h + * + * + */ + +#ifndef Cat_H_ +#define Cat_H_ + + + +#include +#include "Animal.h" +#include +#include +#include +#include "Animal.h" +#include "Cat_allOf.h" +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Cat : public Animal, public Cat_allOf +{ +public: + Cat() = default; + explicit Cat(boost::property_tree::ptree const& pt); + virtual ~Cat() = default; + + Cat(const Cat& other) = default; // copy constructor + Cat(Cat&& other) noexcept = default; // move constructor + + Cat& operator=(const Cat& other) = default; // copy assignment + Cat& operator=(Cat&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Cat members + + /// + /// + /// + std::string getClassName() const; + void setClassName(std::string value); + + /// + /// + /// + std::string getColor() const; + void setColor(std::string value); + + /// + /// + /// + bool isDeclawed() const; + void setDeclawed(bool value); + +protected: + std::string m_ClassName = ""; + std::string m_Color = "red"; + bool m_Declawed = false; +}; + +std::vector createCatVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Cat& val) { + return val.toPropertyTree(); +} + +template<> +inline Cat fromPt(const boost::property_tree::ptree& pt) { + Cat ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Cat_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat_allOf.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat_allOf.cpp new file mode 100644 index 0000000000..5423997a62 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat_allOf.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Cat_allOf.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Cat_allOf::Cat_allOf(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Cat_allOf::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Cat_allOf::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Cat_allOf::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("declawed", m_Declawed); + return pt; +} + +void Cat_allOf::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Declawed = pt.get("declawed", false); +} + +bool Cat_allOf::isDeclawed() const +{ + return m_Declawed; +} + +void Cat_allOf::setDeclawed(bool value) +{ + m_Declawed = value; +} + + + +std::vector createCat_allOfVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Cat_allOf(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat_allOf.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat_allOf.h new file mode 100644 index 0000000000..a88baee06a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat_allOf.h @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Cat_allOf.h + * + * + */ + +#ifndef Cat_allOf_H_ +#define Cat_allOf_H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Cat_allOf +{ +public: + Cat_allOf() = default; + explicit Cat_allOf(boost::property_tree::ptree const& pt); + virtual ~Cat_allOf() = default; + + Cat_allOf(const Cat_allOf& other) = default; // copy constructor + Cat_allOf(Cat_allOf&& other) noexcept = default; // move constructor + + Cat_allOf& operator=(const Cat_allOf& other) = default; // copy assignment + Cat_allOf& operator=(Cat_allOf&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Cat_allOf members + + /// + /// + /// + bool isDeclawed() const; + void setDeclawed(bool value); + +protected: + bool m_Declawed = false; +}; + +std::vector createCat_allOfVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Cat_allOf& val) { + return val.toPropertyTree(); +} + +template<> +inline Cat_allOf fromPt(const boost::property_tree::ptree& pt) { + Cat_allOf ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Cat_allOf_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.cpp new file mode 100644 index 0000000000..c6b83e1ec5 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.cpp @@ -0,0 +1,118 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Category.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Category::Category(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Category::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Category::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Category::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("id", m_Id); + pt.put("name", m_Name); + return pt; +} + +void Category::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Id = pt.get("id", 0L); + m_Name = pt.get("name", "default-name"); +} + +int64_t Category::getId() const +{ + return m_Id; +} + +void Category::setId(int64_t value) +{ + m_Id = value; +} + + +std::string Category::getName() const +{ + return m_Name; +} + +void Category::setName(std::string value) +{ + m_Name = value; +} + + + +std::vector createCategoryVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Category(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.h new file mode 100644 index 0000000000..3db7179909 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.h @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Category.h + * + * + */ + +#ifndef Category_H_ +#define Category_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Category +{ +public: + Category() = default; + explicit Category(boost::property_tree::ptree const& pt); + virtual ~Category() = default; + + Category(const Category& other) = default; // copy constructor + Category(Category&& other) noexcept = default; // move constructor + + Category& operator=(const Category& other) = default; // copy assignment + Category& operator=(Category&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Category members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + std::string getName() const; + void setName(std::string value); + +protected: + int64_t m_Id = 0L; + std::string m_Name = "default-name"; +}; + +std::vector createCategoryVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Category& val) { + return val.toPropertyTree(); +} + +template<> +inline Category fromPt(const boost::property_tree::ptree& pt) { + Category ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Category_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.cpp new file mode 100644 index 0000000000..fc27078745 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "ClassModel.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +ClassModel::ClassModel(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string ClassModel::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void ClassModel::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree ClassModel::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("_class", m__class); + return pt; +} + +void ClassModel::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m__class = pt.get("_class", ""); +} + +std::string ClassModel::get_Class() const +{ + return m__class; +} + +void ClassModel::set_Class(std::string value) +{ + m__class = value; +} + + + +std::vector createClassModelVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(ClassModel(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.h new file mode 100644 index 0000000000..7d63f85d64 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ClassModel.h + * + * Model for testing model with \"_class\" property + */ + +#ifndef ClassModel_H_ +#define ClassModel_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// Model for testing model with \"_class\" property +/// +class ClassModel +{ +public: + ClassModel() = default; + explicit ClassModel(boost::property_tree::ptree const& pt); + virtual ~ClassModel() = default; + + ClassModel(const ClassModel& other) = default; // copy constructor + ClassModel(ClassModel&& other) noexcept = default; // move constructor + + ClassModel& operator=(const ClassModel& other) = default; // copy assignment + ClassModel& operator=(ClassModel&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// ClassModel members + + /// + /// + /// + std::string get_Class() const; + void set_Class(std::string value); + +protected: + std::string m__class = ""; +}; + +std::vector createClassModelVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const ClassModel& val) { + return val.toPropertyTree(); +} + +template<> +inline ClassModel fromPt(const boost::property_tree::ptree& pt) { + ClassModel ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* ClassModel_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.cpp new file mode 100644 index 0000000000..e67287c4b2 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Client.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Client::Client(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Client::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Client::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Client::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("client", m_Client); + return pt; +} + +void Client::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Client = pt.get("client", ""); +} + +std::string Client::getClient() const +{ + return m_Client; +} + +void Client::setClient(std::string value) +{ + m_Client = value; +} + + + +std::vector createClientVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Client(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.h new file mode 100644 index 0000000000..f7370faa70 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Client.h + * + * + */ + +#ifndef Client_H_ +#define Client_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Client +{ +public: + Client() = default; + explicit Client(boost::property_tree::ptree const& pt); + virtual ~Client() = default; + + Client(const Client& other) = default; // copy constructor + Client(Client&& other) noexcept = default; // move constructor + + Client& operator=(const Client& other) = default; // copy assignment + Client& operator=(Client&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Client members + + /// + /// + /// + std::string getClient() const; + void setClient(std::string value); + +protected: + std::string m_Client = ""; +}; + +std::vector createClientVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Client& val) { + return val.toPropertyTree(); +} + +template<> +inline Client fromPt(const boost::property_tree::ptree& pt) { + Client ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Client_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.cpp new file mode 100644 index 0000000000..743f427a31 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "DeprecatedObject.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +DeprecatedObject::DeprecatedObject(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string DeprecatedObject::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void DeprecatedObject::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree DeprecatedObject::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("name", m_Name); + return pt; +} + +void DeprecatedObject::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Name = pt.get("name", ""); +} + +std::string DeprecatedObject::getName() const +{ + return m_Name; +} + +void DeprecatedObject::setName(std::string value) +{ + m_Name = value; +} + + + +std::vector createDeprecatedObjectVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(DeprecatedObject(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.h new file mode 100644 index 0000000000..00e9d11aa9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * DeprecatedObject.h + * + * + */ + +#ifndef DeprecatedObject_H_ +#define DeprecatedObject_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class DeprecatedObject +{ +public: + DeprecatedObject() = default; + explicit DeprecatedObject(boost::property_tree::ptree const& pt); + virtual ~DeprecatedObject() = default; + + DeprecatedObject(const DeprecatedObject& other) = default; // copy constructor + DeprecatedObject(DeprecatedObject&& other) noexcept = default; // move constructor + + DeprecatedObject& operator=(const DeprecatedObject& other) = default; // copy assignment + DeprecatedObject& operator=(DeprecatedObject&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// DeprecatedObject members + + /// + /// + /// + std::string getName() const; + void setName(std::string value); + +protected: + std::string m_Name = ""; +}; + +std::vector createDeprecatedObjectVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const DeprecatedObject& val) { + return val.toPropertyTree(); +} + +template<> +inline DeprecatedObject fromPt(const boost::property_tree::ptree& pt) { + DeprecatedObject ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* DeprecatedObject_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.cpp new file mode 100644 index 0000000000..69fdc804ca --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.cpp @@ -0,0 +1,131 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Dog.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Dog::Dog(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Dog::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Dog::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Dog::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("className", m_ClassName); + pt.put("color", m_Color); + pt.put("breed", m_Breed); + return pt; +} + +void Dog::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_ClassName = pt.get("className", ""); + m_Color = pt.get("color", "red"); + m_Breed = pt.get("breed", ""); +} + +std::string Dog::getClassName() const +{ + return m_ClassName; +} + +void Dog::setClassName(std::string value) +{ + m_ClassName = value; +} + + +std::string Dog::getColor() const +{ + return m_Color; +} + +void Dog::setColor(std::string value) +{ + m_Color = value; +} + + +std::string Dog::getBreed() const +{ + return m_Breed; +} + +void Dog::setBreed(std::string value) +{ + m_Breed = value; +} + + + +std::vector createDogVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Dog(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.h new file mode 100644 index 0000000000..02519fa1f3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.h @@ -0,0 +1,106 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Dog.h + * + * + */ + +#ifndef Dog_H_ +#define Dog_H_ + + + +#include +#include "Animal.h" +#include +#include +#include +#include "Animal.h" +#include "Dog_allOf.h" +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Dog : public Animal, public Dog_allOf +{ +public: + Dog() = default; + explicit Dog(boost::property_tree::ptree const& pt); + virtual ~Dog() = default; + + Dog(const Dog& other) = default; // copy constructor + Dog(Dog&& other) noexcept = default; // move constructor + + Dog& operator=(const Dog& other) = default; // copy assignment + Dog& operator=(Dog&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Dog members + + /// + /// + /// + std::string getClassName() const; + void setClassName(std::string value); + + /// + /// + /// + std::string getColor() const; + void setColor(std::string value); + + /// + /// + /// + std::string getBreed() const; + void setBreed(std::string value); + +protected: + std::string m_ClassName = ""; + std::string m_Color = "red"; + std::string m_Breed = ""; +}; + +std::vector createDogVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Dog& val) { + return val.toPropertyTree(); +} + +template<> +inline Dog fromPt(const boost::property_tree::ptree& pt) { + Dog ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Dog_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog_allOf.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog_allOf.cpp new file mode 100644 index 0000000000..b79311e32c --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog_allOf.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Dog_allOf.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Dog_allOf::Dog_allOf(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Dog_allOf::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Dog_allOf::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Dog_allOf::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("breed", m_Breed); + return pt; +} + +void Dog_allOf::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Breed = pt.get("breed", ""); +} + +std::string Dog_allOf::getBreed() const +{ + return m_Breed; +} + +void Dog_allOf::setBreed(std::string value) +{ + m_Breed = value; +} + + + +std::vector createDog_allOfVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Dog_allOf(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog_allOf.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog_allOf.h new file mode 100644 index 0000000000..648fe7cc05 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog_allOf.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Dog_allOf.h + * + * + */ + +#ifndef Dog_allOf_H_ +#define Dog_allOf_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Dog_allOf +{ +public: + Dog_allOf() = default; + explicit Dog_allOf(boost::property_tree::ptree const& pt); + virtual ~Dog_allOf() = default; + + Dog_allOf(const Dog_allOf& other) = default; // copy constructor + Dog_allOf(Dog_allOf&& other) noexcept = default; // move constructor + + Dog_allOf& operator=(const Dog_allOf& other) = default; // copy assignment + Dog_allOf& operator=(Dog_allOf&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Dog_allOf members + + /// + /// + /// + std::string getBreed() const; + void setBreed(std::string value); + +protected: + std::string m_Breed = ""; +}; + +std::vector createDog_allOfVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Dog_allOf& val) { + return val.toPropertyTree(); +} + +template<> +inline Dog_allOf fromPt(const boost::property_tree::ptree& pt) { + Dog_allOf ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Dog_allOf_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.cpp new file mode 100644 index 0000000000..b124c4de52 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.cpp @@ -0,0 +1,144 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "EnumArrays.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +EnumArrays::EnumArrays(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string EnumArrays::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void EnumArrays::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree EnumArrays::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("just_symbol", m_Just_symbol); + // generate tree for Array_enum + tmp_node.clear(); + if (!m_Array_enum.empty()) { + tmp_node = toPt(m_Array_enum); + pt.add_child("array_enum", tmp_node); + tmp_node.clear(); + } + return pt; +} + +void EnumArrays::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + setJustSymbol(pt.get("just_symbol", "")); + // push all items of Array_enum into member + if (pt.get_child_optional("array_enum")) { + m_Array_enum = fromPt>(pt.get_child("array_enum")); + } +} + +std::string EnumArrays::getJustSymbol() const +{ + return m_Just_symbol; +} + +void EnumArrays::setJustSymbol(std::string value) +{ + static const std::array allowedValues = { + ">=", "$" + }; + + if (std::find(allowedValues.begin(), allowedValues.end(), value) != allowedValues.end()) { + m_Just_symbol = value; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(value) + " not allowed"); + } +} + + +std::vector EnumArrays::getArrayEnum() const +{ + return m_Array_enum; +} + +void EnumArrays::setArrayEnum(std::vector value) +{ + static const std::array allowedValues = { + "fish", "crab" + }; + + for (const auto &v: value) { + if (std::find(allowedValues.begin(), allowedValues.end(), v) == allowedValues.end()) { + throw std::runtime_error("Value " + boost::lexical_cast(v) + " not allowed"); + } + } +} + + + +std::vector createEnumArraysVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(EnumArrays(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.h new file mode 100644 index 0000000000..f6ffd86311 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.h @@ -0,0 +1,98 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * EnumArrays.h + * + * + */ + +#ifndef EnumArrays_H_ +#define EnumArrays_H_ + + + +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class EnumArrays +{ +public: + EnumArrays() = default; + explicit EnumArrays(boost::property_tree::ptree const& pt); + virtual ~EnumArrays() = default; + + EnumArrays(const EnumArrays& other) = default; // copy constructor + EnumArrays(EnumArrays&& other) noexcept = default; // move constructor + + EnumArrays& operator=(const EnumArrays& other) = default; // copy assignment + EnumArrays& operator=(EnumArrays&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// EnumArrays members + + /// + /// + /// + std::string getJustSymbol() const; + void setJustSymbol(std::string value); + + /// + /// + /// + std::vector getArrayEnum() const; + void setArrayEnum(std::vector value); + +protected: + std::string m_Just_symbol = ""; + std::vector m_Array_enum; +}; + +std::vector createEnumArraysVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const EnumArrays& val) { + return val.toPropertyTree(); +} + +template<> +inline EnumArrays fromPt(const boost::property_tree::ptree& pt) { + EnumArrays ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* EnumArrays_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.cpp new file mode 100644 index 0000000000..eec1e1c01d --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.cpp @@ -0,0 +1,114 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "EnumClass.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +EnumClass::EnumClass(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string EnumClass::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void EnumClass::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree EnumClass::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + return pt; +} + +void EnumClass::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; +} + +std::string EnumClass::toString() const { + return boost::lexical_cast(getEnumValue()); +} + +void EnumClass::fromString(const std::string& str) { + setEnumValue(boost::lexical_cast(str)); +} + +std::string EnumClass::getEnumValue() const { + return m_EnumClassEnumValue; +} + +void EnumClass::setEnumValue(const std::string& val) { + static const std::array allowedValues = { + "_abc", "-efg", "(xyz)" + }; + if (std::find(allowedValues.begin(), allowedValues.end(), val) != allowedValues.end()) { + m_EnumClassEnumValue = val; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(val) + " not allowed"); + } +} + +std::vector createEnumClassVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(EnumClass(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.h new file mode 100644 index 0000000000..0b7afdfe91 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.h @@ -0,0 +1,86 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * EnumClass.h + * + * + */ + +#ifndef EnumClass_H_ +#define EnumClass_H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class EnumClass +{ +public: + EnumClass() = default; + explicit EnumClass(boost::property_tree::ptree const& pt); + virtual ~EnumClass() = default; + + EnumClass(const EnumClass& other) = default; // copy constructor + EnumClass(EnumClass&& other) noexcept = default; // move constructor + + EnumClass& operator=(const EnumClass& other) = default; // copy assignment + EnumClass& operator=(EnumClass&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + std::string toString() const; + void fromString(const std::string& str); + + ///////////////////////////////////////////// + /// EnumClass members + std::string getEnumValue() const; + void setEnumValue(const std::string& val); + +protected: + std::string m_EnumClassEnumValue; +}; + +std::vector createEnumClassVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const EnumClass& val) { + return val.toPropertyTree(); +} + +template<> +inline EnumClass fromPt(const boost::property_tree::ptree& pt) { + EnumClass ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* EnumClass_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.cpp new file mode 100644 index 0000000000..2a74bce3d5 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.cpp @@ -0,0 +1,221 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Enum_Test.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Enum_Test::Enum_Test(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Enum_Test::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Enum_Test::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Enum_Test::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("enum_string", m_Enum_string); + pt.put("enum_string_required", m_Enum_string_required); + pt.put("enum_integer", m_Enum_integer); + pt.put("enum_number", m_Enum_number); + return pt; +} + +void Enum_Test::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + setEnumString(pt.get("enum_string", "")); + setEnumStringRequired(pt.get("enum_string_required", "")); + setEnumInteger(pt.get("enum_integer", 0)); + setEnumNumber(pt.get("enum_number", 0.0)); +} + +std::string Enum_Test::getEnumString() const +{ + return m_Enum_string; +} + +void Enum_Test::setEnumString(std::string value) +{ + static const std::array allowedValues = { + "UPPER", "lower", "" + }; + + if (std::find(allowedValues.begin(), allowedValues.end(), value) != allowedValues.end()) { + m_Enum_string = value; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(value) + " not allowed"); + } +} + + +std::string Enum_Test::getEnumStringRequired() const +{ + return m_Enum_string_required; +} + +void Enum_Test::setEnumStringRequired(std::string value) +{ + static const std::array allowedValues = { + "UPPER", "lower", "" + }; + + if (std::find(allowedValues.begin(), allowedValues.end(), value) != allowedValues.end()) { + m_Enum_string_required = value; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(value) + " not allowed"); + } +} + + +int32_t Enum_Test::getEnumInteger() const +{ + return m_Enum_integer; +} + +void Enum_Test::setEnumInteger(int32_t value) +{ + static const std::array allowedValues = { + 1, -1 + }; + + if (std::find(allowedValues.begin(), allowedValues.end(), value) != allowedValues.end()) { + m_Enum_integer = value; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(value) + " not allowed"); + } +} + + +double Enum_Test::getEnumNumber() const +{ + return m_Enum_number; +} + +void Enum_Test::setEnumNumber(double value) +{ + static const std::array allowedValues = { + 1.1, -1.2 + }; + + if (std::find(allowedValues.begin(), allowedValues.end(), value) != allowedValues.end()) { + m_Enum_number = value; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(value) + " not allowed"); + } +} + + +OuterEnum Enum_Test::getOuterEnum() const +{ + return m_OuterEnum; +} + +void Enum_Test::setOuterEnum(OuterEnum value) +{ + m_OuterEnum = value; +} + + +OuterEnumInteger Enum_Test::getOuterEnumInteger() const +{ + return m_OuterEnumInteger; +} + +void Enum_Test::setOuterEnumInteger(OuterEnumInteger value) +{ + m_OuterEnumInteger = value; +} + + +OuterEnumDefaultValue Enum_Test::getOuterEnumDefaultValue() const +{ + return m_OuterEnumDefaultValue; +} + +void Enum_Test::setOuterEnumDefaultValue(OuterEnumDefaultValue value) +{ + m_OuterEnumDefaultValue = value; +} + + +OuterEnumIntegerDefaultValue Enum_Test::getOuterEnumIntegerDefaultValue() const +{ + return m_OuterEnumIntegerDefaultValue; +} + +void Enum_Test::setOuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue value) +{ + m_OuterEnumIntegerDefaultValue = value; +} + + + +std::vector createEnum_TestVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Enum_Test(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.h new file mode 100644 index 0000000000..2aaa7f00ee --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.h @@ -0,0 +1,143 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Enum_Test.h + * + * + */ + +#ifndef Enum_Test_H_ +#define Enum_Test_H_ + + + +#include "OuterEnumIntegerDefaultValue.h" +#include "OuterEnumInteger.h" +#include "OuterEnum.h" +#include "OuterEnumDefaultValue.h" +#include +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Enum_Test +{ +public: + Enum_Test() = default; + explicit Enum_Test(boost::property_tree::ptree const& pt); + virtual ~Enum_Test() = default; + + Enum_Test(const Enum_Test& other) = default; // copy constructor + Enum_Test(Enum_Test&& other) noexcept = default; // move constructor + + Enum_Test& operator=(const Enum_Test& other) = default; // copy assignment + Enum_Test& operator=(Enum_Test&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Enum_Test members + + /// + /// + /// + std::string getEnumString() const; + void setEnumString(std::string value); + + /// + /// + /// + std::string getEnumStringRequired() const; + void setEnumStringRequired(std::string value); + + /// + /// + /// + int32_t getEnumInteger() const; + void setEnumInteger(int32_t value); + + /// + /// + /// + double getEnumNumber() const; + void setEnumNumber(double value); + + /// + /// + /// + OuterEnum getOuterEnum() const; + void setOuterEnum(OuterEnum value); + + /// + /// + /// + OuterEnumInteger getOuterEnumInteger() const; + void setOuterEnumInteger(OuterEnumInteger value); + + /// + /// + /// + OuterEnumDefaultValue getOuterEnumDefaultValue() const; + void setOuterEnumDefaultValue(OuterEnumDefaultValue value); + + /// + /// + /// + OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() const; + void setOuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue value); + +protected: + std::string m_Enum_string = ""; + std::string m_Enum_string_required = ""; + int32_t m_Enum_integer = 0; + double m_Enum_number = 0.0; + OuterEnum m_OuterEnum = OuterEnum{}; + OuterEnumInteger m_OuterEnumInteger = OuterEnumInteger{}; + OuterEnumDefaultValue m_OuterEnumDefaultValue = OuterEnumDefaultValue{}; + OuterEnumIntegerDefaultValue m_OuterEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue{}; +}; + +std::vector createEnum_TestVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Enum_Test& val) { + return val.toPropertyTree(); +} + +template<> +inline Enum_Test fromPt(const boost::property_tree::ptree& pt) { + Enum_Test ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Enum_Test_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/File.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/File.cpp new file mode 100644 index 0000000000..ecfd265f36 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/File.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "File.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +File::File(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string File::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void File::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree File::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("sourceURI", m_SourceURI); + return pt; +} + +void File::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_SourceURI = pt.get("sourceURI", ""); +} + +std::string File::getSourceURI() const +{ + return m_SourceURI; +} + +void File::setSourceURI(std::string value) +{ + m_SourceURI = value; +} + + + +std::vector createFileVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(File(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/File.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/File.h new file mode 100644 index 0000000000..11985bff2c --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/File.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * File.h + * + * Must be named `File` for test. + */ + +#ifndef File_H_ +#define File_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// Must be named `File` for test. +/// +class File +{ +public: + File() = default; + explicit File(boost::property_tree::ptree const& pt); + virtual ~File() = default; + + File(const File& other) = default; // copy constructor + File(File&& other) noexcept = default; // move constructor + + File& operator=(const File& other) = default; // copy assignment + File& operator=(File&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// File members + + /// + /// Test capitalization + /// + std::string getSourceURI() const; + void setSourceURI(std::string value); + +protected: + std::string m_SourceURI = ""; +}; + +std::vector createFileVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const File& val) { + return val.toPropertyTree(); +} + +template<> +inline File fromPt(const boost::property_tree::ptree& pt) { + File ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* File_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.cpp new file mode 100644 index 0000000000..35dac30067 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.cpp @@ -0,0 +1,129 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "FileSchemaTestClass.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +FileSchemaTestClass::FileSchemaTestClass(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string FileSchemaTestClass::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void FileSchemaTestClass::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree FileSchemaTestClass::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.add_child("file", m_file.toPropertyTree()); + // generate tree for Files + tmp_node.clear(); + if (!m_Files.empty()) { + tmp_node = toPt(m_Files); + pt.add_child("files", tmp_node); + tmp_node.clear(); + } + return pt; +} + +void FileSchemaTestClass::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + if (pt.get_child_optional("file")) { + m_file = fromPt(pt.get_child("file")); + } + // push all items of Files into member + if (pt.get_child_optional("files")) { + m_Files = fromPt>(pt.get_child("files")); + } +} + +File FileSchemaTestClass::getFile() const +{ + return m_file; +} + +void FileSchemaTestClass::setFile(File value) +{ + m_file = value; +} + + +std::vector FileSchemaTestClass::getFiles() const +{ + return m_Files; +} + +void FileSchemaTestClass::setFiles(std::vector value) +{ + m_Files = value; +} + + + +std::vector createFileSchemaTestClassVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(FileSchemaTestClass(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.h new file mode 100644 index 0000000000..057b54ba4a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.h @@ -0,0 +1,97 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * FileSchemaTestClass.h + * + * + */ + +#ifndef FileSchemaTestClass_H_ +#define FileSchemaTestClass_H_ + + + +#include "File.h" +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class FileSchemaTestClass +{ +public: + FileSchemaTestClass() = default; + explicit FileSchemaTestClass(boost::property_tree::ptree const& pt); + virtual ~FileSchemaTestClass() = default; + + FileSchemaTestClass(const FileSchemaTestClass& other) = default; // copy constructor + FileSchemaTestClass(FileSchemaTestClass&& other) noexcept = default; // move constructor + + FileSchemaTestClass& operator=(const FileSchemaTestClass& other) = default; // copy assignment + FileSchemaTestClass& operator=(FileSchemaTestClass&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// FileSchemaTestClass members + + /// + /// + /// + File getFile() const; + void setFile(File value); + + /// + /// + /// + std::vector getFiles() const; + void setFiles(std::vector value); + +protected: + File m_file; + std::vector m_Files; +}; + +std::vector createFileSchemaTestClassVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const FileSchemaTestClass& val) { + return val.toPropertyTree(); +} + +template<> +inline FileSchemaTestClass fromPt(const boost::property_tree::ptree& pt) { + FileSchemaTestClass ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* FileSchemaTestClass_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.cpp new file mode 100644 index 0000000000..a3653c9fbc --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Foo.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Foo::Foo(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Foo::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Foo::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Foo::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("bar", m_Bar); + return pt; +} + +void Foo::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Bar = pt.get("bar", "bar"); +} + +std::string Foo::getBar() const +{ + return m_Bar; +} + +void Foo::setBar(std::string value) +{ + m_Bar = value; +} + + + +std::vector createFooVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Foo(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.h new file mode 100644 index 0000000000..f4783422f3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Foo.h + * + * + */ + +#ifndef Foo_H_ +#define Foo_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Foo +{ +public: + Foo() = default; + explicit Foo(boost::property_tree::ptree const& pt); + virtual ~Foo() = default; + + Foo(const Foo& other) = default; // copy constructor + Foo(Foo&& other) noexcept = default; // move constructor + + Foo& operator=(const Foo& other) = default; // copy assignment + Foo& operator=(Foo&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Foo members + + /// + /// + /// + std::string getBar() const; + void setBar(std::string value); + +protected: + std::string m_Bar = "bar"; +}; + +std::vector createFooVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Foo& val) { + return val.toPropertyTree(); +} + +template<> +inline Foo fromPt(const boost::property_tree::ptree& pt) { + Foo ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Foo_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.cpp new file mode 100644 index 0000000000..40565a64bf --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.cpp @@ -0,0 +1,294 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Format_test.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Format_test::Format_test(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Format_test::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Format_test::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Format_test::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("integer", m_integer); + pt.put("int32", m_Int32); + pt.put("int64", m_Int64); + pt.put("number", m_number); + pt.put("float", m_float); + pt.put("double", m_double); + pt.put("string", m_string); + pt.put("date", m_date); + pt.put("dateTime", m_DateTime); + pt.put("uuid", m_Uuid); + pt.put("password", m_Password); + pt.put("pattern_with_digits", m_Pattern_with_digits); + pt.put("pattern_with_digits_and_delimiter", m_Pattern_with_digits_and_delimiter); + return pt; +} + +void Format_test::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_integer = pt.get("integer", 0); + m_Int32 = pt.get("int32", 0); + m_Int64 = pt.get("int64", 0L); + m_number = pt.get("number", 0.0); + m_float = pt.get("float", 0.0f); + m_double = pt.get("double", 0.0); + m_string = pt.get("string", ""); + m_date = pt.get("date", ""); + m_DateTime = pt.get("dateTime", ""); + m_Uuid = pt.get("uuid", ""); + m_Password = pt.get("password", ""); + m_Pattern_with_digits = pt.get("pattern_with_digits", ""); + m_Pattern_with_digits_and_delimiter = pt.get("pattern_with_digits_and_delimiter", ""); +} + +int32_t Format_test::getInteger() const +{ + return m_integer; +} + +void Format_test::setInteger(int32_t value) +{ + m_integer = value; +} + + +int32_t Format_test::getInt32() const +{ + return m_Int32; +} + +void Format_test::setInt32(int32_t value) +{ + m_Int32 = value; +} + + +int64_t Format_test::getInt64() const +{ + return m_Int64; +} + +void Format_test::setInt64(int64_t value) +{ + m_Int64 = value; +} + + +double Format_test::getNumber() const +{ + return m_number; +} + +void Format_test::setNumber(double value) +{ + m_number = value; +} + + +float Format_test::getFloat() const +{ + return m_float; +} + +void Format_test::setFloat(float value) +{ + m_float = value; +} + + +double Format_test::getDouble() const +{ + return m_double; +} + +void Format_test::setDouble(double value) +{ + m_double = value; +} + + +std::string Format_test::getDecimal() const +{ + return m_decimal; +} + +void Format_test::setDecimal(std::string value) +{ + m_decimal = value; +} + + +std::string Format_test::getString() const +{ + return m_string; +} + +void Format_test::setString(std::string value) +{ + m_string = value; +} + + +std::string Format_test::getByte() const +{ + return m_Byte; +} + +void Format_test::setByte(std::string value) +{ + m_Byte = value; +} + + +std::string Format_test::getBinary() const +{ + return m_binary; +} + +void Format_test::setBinary(std::string value) +{ + m_binary = value; +} + + +std::string Format_test::getDate() const +{ + return m_date; +} + +void Format_test::setDate(std::string value) +{ + m_date = value; +} + + +std::string Format_test::getDateTime() const +{ + return m_DateTime; +} + +void Format_test::setDateTime(std::string value) +{ + m_DateTime = value; +} + + +std::string Format_test::getUuid() const +{ + return m_Uuid; +} + +void Format_test::setUuid(std::string value) +{ + m_Uuid = value; +} + + +std::string Format_test::getPassword() const +{ + return m_Password; +} + +void Format_test::setPassword(std::string value) +{ + m_Password = value; +} + + +std::string Format_test::getPatternWithDigits() const +{ + return m_Pattern_with_digits; +} + +void Format_test::setPatternWithDigits(std::string value) +{ + m_Pattern_with_digits = value; +} + + +std::string Format_test::getPatternWithDigitsAndDelimiter() const +{ + return m_Pattern_with_digits_and_delimiter; +} + +void Format_test::setPatternWithDigitsAndDelimiter(std::string value) +{ + m_Pattern_with_digits_and_delimiter = value; +} + + + +std::vector createFormat_testVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Format_test(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.h new file mode 100644 index 0000000000..8d31d2ae0c --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.h @@ -0,0 +1,194 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Format_test.h + * + * + */ + +#ifndef Format_test_H_ +#define Format_test_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Format_test +{ +public: + Format_test() = default; + explicit Format_test(boost::property_tree::ptree const& pt); + virtual ~Format_test() = default; + + Format_test(const Format_test& other) = default; // copy constructor + Format_test(Format_test&& other) noexcept = default; // move constructor + + Format_test& operator=(const Format_test& other) = default; // copy assignment + Format_test& operator=(Format_test&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Format_test members + + /// + /// + /// + int32_t getInteger() const; + void setInteger(int32_t value); + + /// + /// + /// + int32_t getInt32() const; + void setInt32(int32_t value); + + /// + /// + /// + int64_t getInt64() const; + void setInt64(int64_t value); + + /// + /// + /// + double getNumber() const; + void setNumber(double value); + + /// + /// + /// + float getFloat() const; + void setFloat(float value); + + /// + /// + /// + double getDouble() const; + void setDouble(double value); + + /// + /// + /// + std::string getDecimal() const; + void setDecimal(std::string value); + + /// + /// + /// + std::string getString() const; + void setString(std::string value); + + /// + /// + /// + std::string getByte() const; + void setByte(std::string value); + + /// + /// + /// + std::string getBinary() const; + void setBinary(std::string value); + + /// + /// + /// + std::string getDate() const; + void setDate(std::string value); + + /// + /// + /// + std::string getDateTime() const; + void setDateTime(std::string value); + + /// + /// + /// + std::string getUuid() const; + void setUuid(std::string value); + + /// + /// + /// + std::string getPassword() const; + void setPassword(std::string value); + + /// + /// A string that is a 10 digit number. Can have leading zeros. + /// + std::string getPatternWithDigits() const; + void setPatternWithDigits(std::string value); + + /// + /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + /// + std::string getPatternWithDigitsAndDelimiter() const; + void setPatternWithDigitsAndDelimiter(std::string value); + +protected: + int32_t m_integer = 0; + int32_t m_Int32 = 0; + int64_t m_Int64 = 0L; + double m_number = 0.0; + float m_float = 0.0f; + double m_double = 0.0; + std::string m_decimal = ""; + std::string m_string = ""; + std::string m_Byte = ""; + std::string m_binary = ""; + std::string m_date = ""; + std::string m_DateTime = ""; + std::string m_Uuid = ""; + std::string m_Password = ""; + std::string m_Pattern_with_digits = ""; + std::string m_Pattern_with_digits_and_delimiter = ""; +}; + +std::vector createFormat_testVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Format_test& val) { + return val.toPropertyTree(); +} + +template<> +inline Format_test fromPt(const boost::property_tree::ptree& pt) { + Format_test ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Format_test_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.cpp new file mode 100644 index 0000000000..f6983604fb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.cpp @@ -0,0 +1,118 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "HasOnlyReadOnly.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +HasOnlyReadOnly::HasOnlyReadOnly(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string HasOnlyReadOnly::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void HasOnlyReadOnly::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree HasOnlyReadOnly::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("bar", m_Bar); + pt.put("foo", m_Foo); + return pt; +} + +void HasOnlyReadOnly::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Bar = pt.get("bar", ""); + m_Foo = pt.get("foo", ""); +} + +std::string HasOnlyReadOnly::getBar() const +{ + return m_Bar; +} + +void HasOnlyReadOnly::setBar(std::string value) +{ + m_Bar = value; +} + + +std::string HasOnlyReadOnly::getFoo() const +{ + return m_Foo; +} + +void HasOnlyReadOnly::setFoo(std::string value) +{ + m_Foo = value; +} + + + +std::vector createHasOnlyReadOnlyVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(HasOnlyReadOnly(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.h new file mode 100644 index 0000000000..b022884bc3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.h @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * HasOnlyReadOnly.h + * + * + */ + +#ifndef HasOnlyReadOnly_H_ +#define HasOnlyReadOnly_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class HasOnlyReadOnly +{ +public: + HasOnlyReadOnly() = default; + explicit HasOnlyReadOnly(boost::property_tree::ptree const& pt); + virtual ~HasOnlyReadOnly() = default; + + HasOnlyReadOnly(const HasOnlyReadOnly& other) = default; // copy constructor + HasOnlyReadOnly(HasOnlyReadOnly&& other) noexcept = default; // move constructor + + HasOnlyReadOnly& operator=(const HasOnlyReadOnly& other) = default; // copy assignment + HasOnlyReadOnly& operator=(HasOnlyReadOnly&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// HasOnlyReadOnly members + + /// + /// + /// + std::string getBar() const; + void setBar(std::string value); + + /// + /// + /// + std::string getFoo() const; + void setFoo(std::string value); + +protected: + std::string m_Bar = ""; + std::string m_Foo = ""; +}; + +std::vector createHasOnlyReadOnlyVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const HasOnlyReadOnly& val) { + return val.toPropertyTree(); +} + +template<> +inline HasOnlyReadOnly fromPt(const boost::property_tree::ptree& pt) { + HasOnlyReadOnly ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* HasOnlyReadOnly_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.cpp new file mode 100644 index 0000000000..bc35ae0992 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "HealthCheckResult.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +HealthCheckResult::HealthCheckResult(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string HealthCheckResult::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void HealthCheckResult::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree HealthCheckResult::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("NullableMessage", m_NullableMessage); + return pt; +} + +void HealthCheckResult::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_NullableMessage = pt.get("NullableMessage", ""); +} + +std::string HealthCheckResult::getNullableMessage() const +{ + return m_NullableMessage; +} + +void HealthCheckResult::setNullableMessage(std::string value) +{ + m_NullableMessage = value; +} + + + +std::vector createHealthCheckResultVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(HealthCheckResult(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.h new file mode 100644 index 0000000000..8a7598da16 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * HealthCheckResult.h + * + * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + */ + +#ifndef HealthCheckResult_H_ +#define HealthCheckResult_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. +/// +class HealthCheckResult +{ +public: + HealthCheckResult() = default; + explicit HealthCheckResult(boost::property_tree::ptree const& pt); + virtual ~HealthCheckResult() = default; + + HealthCheckResult(const HealthCheckResult& other) = default; // copy constructor + HealthCheckResult(HealthCheckResult&& other) noexcept = default; // move constructor + + HealthCheckResult& operator=(const HealthCheckResult& other) = default; // copy assignment + HealthCheckResult& operator=(HealthCheckResult&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// HealthCheckResult members + + /// + /// + /// + std::string getNullableMessage() const; + void setNullableMessage(std::string value); + +protected: + std::string m_NullableMessage = ""; +}; + +std::vector createHealthCheckResultVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const HealthCheckResult& val) { + return val.toPropertyTree(); +} + +template<> +inline HealthCheckResult fromPt(const boost::property_tree::ptree& pt) { + HealthCheckResult ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* HealthCheckResult_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/List.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/List.cpp new file mode 100644 index 0000000000..2cf413293b --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/List.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "List.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +List::List(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string List::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void List::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree List::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("123-list", m_r_123_list); + return pt; +} + +void List::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_r_123_list = pt.get("123-list", ""); +} + +std::string List::getR123List() const +{ + return m_r_123_list; +} + +void List::setR123List(std::string value) +{ + m_r_123_list = value; +} + + + +std::vector createListVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(List(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/List.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/List.h new file mode 100644 index 0000000000..7d3aa34fcb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/List.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * List.h + * + * + */ + +#ifndef List_H_ +#define List_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class List +{ +public: + List() = default; + explicit List(boost::property_tree::ptree const& pt); + virtual ~List() = default; + + List(const List& other) = default; // copy constructor + List(List&& other) noexcept = default; // move constructor + + List& operator=(const List& other) = default; // copy assignment + List& operator=(List&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// List members + + /// + /// + /// + std::string getR123List() const; + void setR123List(std::string value); + +protected: + std::string m_r_123_list = ""; +}; + +std::vector createListVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const List& val) { + return val.toPropertyTree(); +} + +template<> +inline List fromPt(const boost::property_tree::ptree& pt) { + List ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* List_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.cpp new file mode 100644 index 0000000000..653c8cd57d --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.cpp @@ -0,0 +1,182 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "MapTest.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +MapTest::MapTest(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string MapTest::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void MapTest::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree MapTest::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + // generate tree for Map_map_of_string + if (!m_Map_map_of_string.empty()) { + tmp_node = toPt(m_Map_map_of_string); + pt.add_child("map_map_of_string", tmp_node); + } + tmp_node.clear(); + // generate tree for Map_of_enum_string + if (!m_Map_of_enum_string.empty()) { + tmp_node = toPt(m_Map_of_enum_string); + pt.add_child("map_of_enum_string", tmp_node); + } + tmp_node.clear(); + // generate tree for Direct_map + if (!m_Direct_map.empty()) { + tmp_node = toPt(m_Direct_map); + pt.add_child("direct_map", tmp_node); + } + tmp_node.clear(); + // generate tree for Indirect_map + if (!m_Indirect_map.empty()) { + tmp_node = toPt(m_Indirect_map); + pt.add_child("indirect_map", tmp_node); + } + tmp_node.clear(); + return pt; +} + +void MapTest::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + if (pt.get_child_optional("map_map_of_string")) { + m_Map_map_of_string = fromPt>>(pt.get_child("map_map_of_string")); + } + if (pt.get_child_optional("map_of_enum_string")) { + m_Map_of_enum_string = fromPt>(pt.get_child("map_of_enum_string")); + } + if (pt.get_child_optional("direct_map")) { + m_Direct_map = fromPt>(pt.get_child("direct_map")); + } + if (pt.get_child_optional("indirect_map")) { + m_Indirect_map = fromPt>(pt.get_child("indirect_map")); + } +} + +std::map> MapTest::getMapMapOfString() const +{ + return m_Map_map_of_string; +} + +void MapTest::setMapMapOfString(std::map> value) +{ + m_Map_map_of_string = value; +} + + +std::map MapTest::getMapOfEnumString() const +{ + return m_Map_of_enum_string; +} + +void MapTest::setMapOfEnumString(std::map value) +{ + static const std::array allowedValues = { + "UPPER", "lower" + }; + + for (const auto &v: value) { + if (std::find(allowedValues.begin(), allowedValues.end(), v.first) == allowedValues.end()) { + throw std::runtime_error("Value " + boost::lexical_cast(v.first) + " not allowed"); + } + } + m_Map_of_enum_string = value; +} + + +std::map MapTest::getDirectMap() const +{ + return m_Direct_map; +} + +void MapTest::setDirectMap(std::map value) +{ + m_Direct_map = value; +} + + +std::map MapTest::getIndirectMap() const +{ + return m_Indirect_map; +} + +void MapTest::setIndirectMap(std::map value) +{ + m_Indirect_map = value; +} + + + +std::vector createMapTestVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(MapTest(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.h new file mode 100644 index 0000000000..28757a32fc --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.h @@ -0,0 +1,112 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * MapTest.h + * + * + */ + +#ifndef MapTest_H_ +#define MapTest_H_ + + + +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class MapTest +{ +public: + MapTest() = default; + explicit MapTest(boost::property_tree::ptree const& pt); + virtual ~MapTest() = default; + + MapTest(const MapTest& other) = default; // copy constructor + MapTest(MapTest&& other) noexcept = default; // move constructor + + MapTest& operator=(const MapTest& other) = default; // copy assignment + MapTest& operator=(MapTest&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// MapTest members + + /// + /// + /// + std::map> getMapMapOfString() const; + void setMapMapOfString(std::map> value); + + /// + /// + /// + std::map getMapOfEnumString() const; + void setMapOfEnumString(std::map value); + + /// + /// + /// + std::map getDirectMap() const; + void setDirectMap(std::map value); + + /// + /// + /// + std::map getIndirectMap() const; + void setIndirectMap(std::map value); + +protected: + std::map> m_Map_map_of_string; + std::map m_Map_of_enum_string; + std::map m_Direct_map; + std::map m_Indirect_map; +}; + +std::vector createMapTestVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const MapTest& val) { + return val.toPropertyTree(); +} + +template<> +inline MapTest fromPt(const boost::property_tree::ptree& pt) { + MapTest ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* MapTest_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.cpp new file mode 100644 index 0000000000..8385194675 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.cpp @@ -0,0 +1,138 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "MixedPropertiesAndAdditionalPropertiesClass.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +MixedPropertiesAndAdditionalPropertiesClass::MixedPropertiesAndAdditionalPropertiesClass(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string MixedPropertiesAndAdditionalPropertiesClass::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void MixedPropertiesAndAdditionalPropertiesClass::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree MixedPropertiesAndAdditionalPropertiesClass::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("uuid", m_Uuid); + pt.put("dateTime", m_DateTime); + // generate tree for map + if (!m_map.empty()) { + tmp_node = toPt(m_map); + pt.add_child("map", tmp_node); + } + tmp_node.clear(); + return pt; +} + +void MixedPropertiesAndAdditionalPropertiesClass::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Uuid = pt.get("uuid", ""); + m_DateTime = pt.get("dateTime", ""); + if (pt.get_child_optional("map")) { + m_map = fromPt>(pt.get_child("map")); + } +} + +std::string MixedPropertiesAndAdditionalPropertiesClass::getUuid() const +{ + return m_Uuid; +} + +void MixedPropertiesAndAdditionalPropertiesClass::setUuid(std::string value) +{ + m_Uuid = value; +} + + +std::string MixedPropertiesAndAdditionalPropertiesClass::getDateTime() const +{ + return m_DateTime; +} + +void MixedPropertiesAndAdditionalPropertiesClass::setDateTime(std::string value) +{ + m_DateTime = value; +} + + +std::map MixedPropertiesAndAdditionalPropertiesClass::getMap() const +{ + return m_map; +} + +void MixedPropertiesAndAdditionalPropertiesClass::setMap(std::map value) +{ + m_map = value; +} + + + +std::vector createMixedPropertiesAndAdditionalPropertiesClassVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(MixedPropertiesAndAdditionalPropertiesClass(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.h new file mode 100644 index 0000000000..08166db74e --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.h @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * MixedPropertiesAndAdditionalPropertiesClass.h + * + * + */ + +#ifndef MixedPropertiesAndAdditionalPropertiesClass_H_ +#define MixedPropertiesAndAdditionalPropertiesClass_H_ + + + +#include +#include +#include "Animal.h" +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class MixedPropertiesAndAdditionalPropertiesClass +{ +public: + MixedPropertiesAndAdditionalPropertiesClass() = default; + explicit MixedPropertiesAndAdditionalPropertiesClass(boost::property_tree::ptree const& pt); + virtual ~MixedPropertiesAndAdditionalPropertiesClass() = default; + + MixedPropertiesAndAdditionalPropertiesClass(const MixedPropertiesAndAdditionalPropertiesClass& other) = default; // copy constructor + MixedPropertiesAndAdditionalPropertiesClass(MixedPropertiesAndAdditionalPropertiesClass&& other) noexcept = default; // move constructor + + MixedPropertiesAndAdditionalPropertiesClass& operator=(const MixedPropertiesAndAdditionalPropertiesClass& other) = default; // copy assignment + MixedPropertiesAndAdditionalPropertiesClass& operator=(MixedPropertiesAndAdditionalPropertiesClass&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// MixedPropertiesAndAdditionalPropertiesClass members + + /// + /// + /// + std::string getUuid() const; + void setUuid(std::string value); + + /// + /// + /// + std::string getDateTime() const; + void setDateTime(std::string value); + + /// + /// + /// + std::map getMap() const; + void setMap(std::map value); + +protected: + std::string m_Uuid = ""; + std::string m_DateTime = ""; + std::map m_map; +}; + +std::vector createMixedPropertiesAndAdditionalPropertiesClassVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const MixedPropertiesAndAdditionalPropertiesClass& val) { + return val.toPropertyTree(); +} + +template<> +inline MixedPropertiesAndAdditionalPropertiesClass fromPt(const boost::property_tree::ptree& pt) { + MixedPropertiesAndAdditionalPropertiesClass ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* MixedPropertiesAndAdditionalPropertiesClass_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.cpp new file mode 100644 index 0000000000..c5b047c3b3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.cpp @@ -0,0 +1,144 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Name.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Name::Name(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Name::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Name::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Name::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("name", m_Name); + pt.put("snake_case", m_Snake_case); + pt.put("property", m_Property); + pt.put("123Number", m_r_123Number); + return pt; +} + +void Name::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Name = pt.get("name", 0); + m_Snake_case = pt.get("snake_case", 0); + m_Property = pt.get("property", ""); + m_r_123Number = pt.get("123Number", 0); +} + +int32_t Name::getName() const +{ + return m_Name; +} + +void Name::setName(int32_t value) +{ + m_Name = value; +} + + +int32_t Name::getSnakeCase() const +{ + return m_Snake_case; +} + +void Name::setSnakeCase(int32_t value) +{ + m_Snake_case = value; +} + + +std::string Name::getProperty() const +{ + return m_Property; +} + +void Name::setProperty(std::string value) +{ + m_Property = value; +} + + +int32_t Name::getR123Number() const +{ + return m_r_123Number; +} + +void Name::setR123Number(int32_t value) +{ + m_r_123Number = value; +} + + + +std::vector createNameVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Name(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.h new file mode 100644 index 0000000000..df4e3d5f7d --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.h @@ -0,0 +1,110 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Name.h + * + * Model for testing model name same as property name + */ + +#ifndef Name_H_ +#define Name_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// Model for testing model name same as property name +/// +class Name +{ +public: + Name() = default; + explicit Name(boost::property_tree::ptree const& pt); + virtual ~Name() = default; + + Name(const Name& other) = default; // copy constructor + Name(Name&& other) noexcept = default; // move constructor + + Name& operator=(const Name& other) = default; // copy assignment + Name& operator=(Name&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Name members + + /// + /// + /// + int32_t getName() const; + void setName(int32_t value); + + /// + /// + /// + int32_t getSnakeCase() const; + void setSnakeCase(int32_t value); + + /// + /// + /// + std::string getProperty() const; + void setProperty(std::string value); + + /// + /// + /// + int32_t getR123Number() const; + void setR123Number(int32_t value); + +protected: + int32_t m_Name = 0; + int32_t m_Snake_case = 0; + std::string m_Property = ""; + int32_t m_r_123Number = 0; +}; + +std::vector createNameVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Name& val) { + return val.toPropertyTree(); +} + +template<> +inline Name fromPt(const boost::property_tree::ptree& pt) { + Name ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Name_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.cpp new file mode 100644 index 0000000000..51de1f5702 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.cpp @@ -0,0 +1,296 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "NullableClass.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +NullableClass::NullableClass(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string NullableClass::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void NullableClass::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree NullableClass::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("integer_prop", m_Integer_prop); + pt.put("number_prop", m_Number_prop); + pt.put("boolean_prop", m_Boolean_prop); + pt.put("string_prop", m_String_prop); + pt.put("date_prop", m_Date_prop); + pt.put("datetime_prop", m_Datetime_prop); + // generate tree for Array_nullable_prop + tmp_node.clear(); + if (!m_Array_nullable_prop.empty()) { + tmp_node = toPt(m_Array_nullable_prop); + pt.add_child("array_nullable_prop", tmp_node); + tmp_node.clear(); + } + // generate tree for Array_and_items_nullable_prop + tmp_node.clear(); + if (!m_Array_and_items_nullable_prop.empty()) { + tmp_node = toPt(m_Array_and_items_nullable_prop); + pt.add_child("array_and_items_nullable_prop", tmp_node); + tmp_node.clear(); + } + // generate tree for Array_items_nullable + tmp_node.clear(); + if (!m_Array_items_nullable.empty()) { + tmp_node = toPt(m_Array_items_nullable); + pt.add_child("array_items_nullable", tmp_node); + tmp_node.clear(); + } + // generate tree for Object_nullable_prop + if (!m_Object_nullable_prop.empty()) { + tmp_node = toPt(m_Object_nullable_prop); + pt.add_child("object_nullable_prop", tmp_node); + } + tmp_node.clear(); + // generate tree for Object_and_items_nullable_prop + if (!m_Object_and_items_nullable_prop.empty()) { + tmp_node = toPt(m_Object_and_items_nullable_prop); + pt.add_child("object_and_items_nullable_prop", tmp_node); + } + tmp_node.clear(); + // generate tree for Object_items_nullable + if (!m_Object_items_nullable.empty()) { + tmp_node = toPt(m_Object_items_nullable); + pt.add_child("object_items_nullable", tmp_node); + } + tmp_node.clear(); + return pt; +} + +void NullableClass::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Integer_prop = pt.get("integer_prop", 0); + m_Number_prop = pt.get("number_prop", 0.0); + m_Boolean_prop = pt.get("boolean_prop", false); + m_String_prop = pt.get("string_prop", ""); + m_Date_prop = pt.get("date_prop", ""); + m_Datetime_prop = pt.get("datetime_prop", ""); + // push all items of Array_nullable_prop into member + if (pt.get_child_optional("array_nullable_prop")) { + m_Array_nullable_prop = fromPt>(pt.get_child("array_nullable_prop")); + } + // push all items of Array_and_items_nullable_prop into member + if (pt.get_child_optional("array_and_items_nullable_prop")) { + m_Array_and_items_nullable_prop = fromPt>(pt.get_child("array_and_items_nullable_prop")); + } + // push all items of Array_items_nullable into member + if (pt.get_child_optional("array_items_nullable")) { + m_Array_items_nullable = fromPt>(pt.get_child("array_items_nullable")); + } + if (pt.get_child_optional("object_nullable_prop")) { + m_Object_nullable_prop = fromPt>(pt.get_child("object_nullable_prop")); + } + if (pt.get_child_optional("object_and_items_nullable_prop")) { + m_Object_and_items_nullable_prop = fromPt>(pt.get_child("object_and_items_nullable_prop")); + } + if (pt.get_child_optional("object_items_nullable")) { + m_Object_items_nullable = fromPt>(pt.get_child("object_items_nullable")); + } +} + +int32_t NullableClass::getIntegerProp() const +{ + return m_Integer_prop; +} + +void NullableClass::setIntegerProp(int32_t value) +{ + m_Integer_prop = value; +} + + +double NullableClass::getNumberProp() const +{ + return m_Number_prop; +} + +void NullableClass::setNumberProp(double value) +{ + m_Number_prop = value; +} + + +bool NullableClass::isBooleanProp() const +{ + return m_Boolean_prop; +} + +void NullableClass::setBooleanProp(bool value) +{ + m_Boolean_prop = value; +} + + +std::string NullableClass::getStringProp() const +{ + return m_String_prop; +} + +void NullableClass::setStringProp(std::string value) +{ + m_String_prop = value; +} + + +std::string NullableClass::getDateProp() const +{ + return m_Date_prop; +} + +void NullableClass::setDateProp(std::string value) +{ + m_Date_prop = value; +} + + +std::string NullableClass::getDatetimeProp() const +{ + return m_Datetime_prop; +} + +void NullableClass::setDatetimeProp(std::string value) +{ + m_Datetime_prop = value; +} + + +std::vector NullableClass::getArrayNullableProp() const +{ + return m_Array_nullable_prop; +} + +void NullableClass::setArrayNullableProp(std::vector value) +{ + m_Array_nullable_prop = value; +} + + +std::vector NullableClass::getArrayAndItemsNullableProp() const +{ + return m_Array_and_items_nullable_prop; +} + +void NullableClass::setArrayAndItemsNullableProp(std::vector value) +{ + m_Array_and_items_nullable_prop = value; +} + + +std::vector NullableClass::getArrayItemsNullable() const +{ + return m_Array_items_nullable; +} + +void NullableClass::setArrayItemsNullable(std::vector value) +{ + m_Array_items_nullable = value; +} + + +std::map NullableClass::getObjectNullableProp() const +{ + return m_Object_nullable_prop; +} + +void NullableClass::setObjectNullableProp(std::map value) +{ + m_Object_nullable_prop = value; +} + + +std::map NullableClass::getObjectAndItemsNullableProp() const +{ + return m_Object_and_items_nullable_prop; +} + +void NullableClass::setObjectAndItemsNullableProp(std::map value) +{ + m_Object_and_items_nullable_prop = value; +} + + +std::map NullableClass::getObjectItemsNullable() const +{ + return m_Object_items_nullable; +} + +void NullableClass::setObjectItemsNullable(std::map value) +{ + m_Object_items_nullable = value; +} + + + +std::vector createNullableClassVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(NullableClass(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.h new file mode 100644 index 0000000000..552dcf6415 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.h @@ -0,0 +1,168 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * NullableClass.h + * + * + */ + +#ifndef NullableClass_H_ +#define NullableClass_H_ + + + +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class NullableClass +{ +public: + NullableClass() = default; + explicit NullableClass(boost::property_tree::ptree const& pt); + virtual ~NullableClass() = default; + + NullableClass(const NullableClass& other) = default; // copy constructor + NullableClass(NullableClass&& other) noexcept = default; // move constructor + + NullableClass& operator=(const NullableClass& other) = default; // copy assignment + NullableClass& operator=(NullableClass&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// NullableClass members + + /// + /// + /// + int32_t getIntegerProp() const; + void setIntegerProp(int32_t value); + + /// + /// + /// + double getNumberProp() const; + void setNumberProp(double value); + + /// + /// + /// + bool isBooleanProp() const; + void setBooleanProp(bool value); + + /// + /// + /// + std::string getStringProp() const; + void setStringProp(std::string value); + + /// + /// + /// + std::string getDateProp() const; + void setDateProp(std::string value); + + /// + /// + /// + std::string getDatetimeProp() const; + void setDatetimeProp(std::string value); + + /// + /// + /// + std::vector getArrayNullableProp() const; + void setArrayNullableProp(std::vector value); + + /// + /// + /// + std::vector getArrayAndItemsNullableProp() const; + void setArrayAndItemsNullableProp(std::vector value); + + /// + /// + /// + std::vector getArrayItemsNullable() const; + void setArrayItemsNullable(std::vector value); + + /// + /// + /// + std::map getObjectNullableProp() const; + void setObjectNullableProp(std::map value); + + /// + /// + /// + std::map getObjectAndItemsNullableProp() const; + void setObjectAndItemsNullableProp(std::map value); + + /// + /// + /// + std::map getObjectItemsNullable() const; + void setObjectItemsNullable(std::map value); + +protected: + int32_t m_Integer_prop = 0; + double m_Number_prop = 0.0; + bool m_Boolean_prop = false; + std::string m_String_prop = ""; + std::string m_Date_prop = ""; + std::string m_Datetime_prop = ""; + std::vector m_Array_nullable_prop; + std::vector m_Array_and_items_nullable_prop; + std::vector m_Array_items_nullable; + std::map m_Object_nullable_prop; + std::map m_Object_and_items_nullable_prop; + std::map m_Object_items_nullable; +}; + +std::vector createNullableClassVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const NullableClass& val) { + return val.toPropertyTree(); +} + +template<> +inline NullableClass fromPt(const boost::property_tree::ptree& pt) { + NullableClass ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* NullableClass_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.cpp new file mode 100644 index 0000000000..55c476d934 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "NumberOnly.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +NumberOnly::NumberOnly(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string NumberOnly::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void NumberOnly::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree NumberOnly::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("JustNumber", m_JustNumber); + return pt; +} + +void NumberOnly::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_JustNumber = pt.get("JustNumber", 0.0); +} + +double NumberOnly::getJustNumber() const +{ + return m_JustNumber; +} + +void NumberOnly::setJustNumber(double value) +{ + m_JustNumber = value; +} + + + +std::vector createNumberOnlyVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(NumberOnly(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.h new file mode 100644 index 0000000000..085fe4c5d1 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.h @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * NumberOnly.h + * + * + */ + +#ifndef NumberOnly_H_ +#define NumberOnly_H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class NumberOnly +{ +public: + NumberOnly() = default; + explicit NumberOnly(boost::property_tree::ptree const& pt); + virtual ~NumberOnly() = default; + + NumberOnly(const NumberOnly& other) = default; // copy constructor + NumberOnly(NumberOnly&& other) noexcept = default; // move constructor + + NumberOnly& operator=(const NumberOnly& other) = default; // copy assignment + NumberOnly& operator=(NumberOnly&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// NumberOnly members + + /// + /// + /// + double getJustNumber() const; + void setJustNumber(double value); + +protected: + double m_JustNumber = 0.0; +}; + +std::vector createNumberOnlyVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const NumberOnly& val) { + return val.toPropertyTree(); +} + +template<> +inline NumberOnly fromPt(const boost::property_tree::ptree& pt) { + NumberOnly ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* NumberOnly_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.cpp new file mode 100644 index 0000000000..0a5477f6dd --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.cpp @@ -0,0 +1,155 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "ObjectWithDeprecatedFields.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +ObjectWithDeprecatedFields::ObjectWithDeprecatedFields(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string ObjectWithDeprecatedFields::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void ObjectWithDeprecatedFields::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree ObjectWithDeprecatedFields::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("uuid", m_Uuid); + pt.put("id", m_Id); + pt.add_child("deprecatedRef", m_DeprecatedRef.toPropertyTree()); + // generate tree for Bars + tmp_node.clear(); + if (!m_Bars.empty()) { + tmp_node = toPt(m_Bars); + pt.add_child("bars", tmp_node); + tmp_node.clear(); + } + return pt; +} + +void ObjectWithDeprecatedFields::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Uuid = pt.get("uuid", ""); + m_Id = pt.get("id", 0.0); + if (pt.get_child_optional("deprecatedRef")) { + m_DeprecatedRef = fromPt(pt.get_child("deprecatedRef")); + } + // push all items of Bars into member + if (pt.get_child_optional("bars")) { + m_Bars = fromPt>(pt.get_child("bars")); + } +} + +std::string ObjectWithDeprecatedFields::getUuid() const +{ + return m_Uuid; +} + +void ObjectWithDeprecatedFields::setUuid(std::string value) +{ + m_Uuid = value; +} + + +double ObjectWithDeprecatedFields::getId() const +{ + return m_Id; +} + +void ObjectWithDeprecatedFields::setId(double value) +{ + m_Id = value; +} + + +DeprecatedObject ObjectWithDeprecatedFields::getDeprecatedRef() const +{ + return m_DeprecatedRef; +} + +void ObjectWithDeprecatedFields::setDeprecatedRef(DeprecatedObject value) +{ + m_DeprecatedRef = value; +} + + +std::vector ObjectWithDeprecatedFields::getBars() const +{ + return m_Bars; +} + +void ObjectWithDeprecatedFields::setBars(std::vector value) +{ + m_Bars = value; +} + + + +std::vector createObjectWithDeprecatedFieldsVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(ObjectWithDeprecatedFields(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.h new file mode 100644 index 0000000000..0a25df04fa --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.h @@ -0,0 +1,112 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ObjectWithDeprecatedFields.h + * + * + */ + +#ifndef ObjectWithDeprecatedFields_H_ +#define ObjectWithDeprecatedFields_H_ + + + +#include +#include "DeprecatedObject.h" +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class ObjectWithDeprecatedFields +{ +public: + ObjectWithDeprecatedFields() = default; + explicit ObjectWithDeprecatedFields(boost::property_tree::ptree const& pt); + virtual ~ObjectWithDeprecatedFields() = default; + + ObjectWithDeprecatedFields(const ObjectWithDeprecatedFields& other) = default; // copy constructor + ObjectWithDeprecatedFields(ObjectWithDeprecatedFields&& other) noexcept = default; // move constructor + + ObjectWithDeprecatedFields& operator=(const ObjectWithDeprecatedFields& other) = default; // copy assignment + ObjectWithDeprecatedFields& operator=(ObjectWithDeprecatedFields&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// ObjectWithDeprecatedFields members + + /// + /// + /// + std::string getUuid() const; + void setUuid(std::string value); + + /// + /// + /// + double getId() const; + void setId(double value); + + /// + /// + /// + DeprecatedObject getDeprecatedRef() const; + void setDeprecatedRef(DeprecatedObject value); + + /// + /// + /// + std::vector getBars() const; + void setBars(std::vector value); + +protected: + std::string m_Uuid = ""; + double m_Id = 0.0; + DeprecatedObject m_DeprecatedRef; + std::vector m_Bars; +}; + +std::vector createObjectWithDeprecatedFieldsVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const ObjectWithDeprecatedFields& val) { + return val.toPropertyTree(); +} + +template<> +inline ObjectWithDeprecatedFields fromPt(const boost::property_tree::ptree& pt) { + ObjectWithDeprecatedFields ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* ObjectWithDeprecatedFields_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.cpp new file mode 100644 index 0000000000..31967c7092 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.cpp @@ -0,0 +1,179 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Order.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Order::Order(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Order::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Order::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Order::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("id", m_Id); + pt.put("petId", m_PetId); + pt.put("quantity", m_Quantity); + pt.put("shipDate", m_ShipDate); + pt.put("status", m_Status); + pt.put("complete", m_Complete); + return pt; +} + +void Order::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Id = pt.get("id", 0L); + m_PetId = pt.get("petId", 0L); + m_Quantity = pt.get("quantity", 0); + m_ShipDate = pt.get("shipDate", ""); + setStatus(pt.get("status", "")); + m_Complete = pt.get("complete", false); +} + +int64_t Order::getId() const +{ + return m_Id; +} + +void Order::setId(int64_t value) +{ + m_Id = value; +} + + +int64_t Order::getPetId() const +{ + return m_PetId; +} + +void Order::setPetId(int64_t value) +{ + m_PetId = value; +} + + +int32_t Order::getQuantity() const +{ + return m_Quantity; +} + +void Order::setQuantity(int32_t value) +{ + m_Quantity = value; +} + + +std::string Order::getShipDate() const +{ + return m_ShipDate; +} + +void Order::setShipDate(std::string value) +{ + m_ShipDate = value; +} + + +std::string Order::getStatus() const +{ + return m_Status; +} + +void Order::setStatus(std::string value) +{ + static const std::array allowedValues = { + "placed", "approved", "delivered" + }; + + if (std::find(allowedValues.begin(), allowedValues.end(), value) != allowedValues.end()) { + m_Status = value; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(value) + " not allowed"); + } +} + + +bool Order::isComplete() const +{ + return m_Complete; +} + +void Order::setComplete(bool value) +{ + m_Complete = value; +} + + + +std::vector createOrderVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Order(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.h new file mode 100644 index 0000000000..e4a7762351 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.h @@ -0,0 +1,125 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Order.h + * + * + */ + +#ifndef Order_H_ +#define Order_H_ + + + +#include +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Order +{ +public: + Order() = default; + explicit Order(boost::property_tree::ptree const& pt); + virtual ~Order() = default; + + Order(const Order& other) = default; // copy constructor + Order(Order&& other) noexcept = default; // move constructor + + Order& operator=(const Order& other) = default; // copy assignment + Order& operator=(Order&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Order members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + int64_t getPetId() const; + void setPetId(int64_t value); + + /// + /// + /// + int32_t getQuantity() const; + void setQuantity(int32_t value); + + /// + /// + /// + std::string getShipDate() const; + void setShipDate(std::string value); + + /// + /// Order Status + /// + std::string getStatus() const; + void setStatus(std::string value); + + /// + /// + /// + bool isComplete() const; + void setComplete(bool value); + +protected: + int64_t m_Id = 0L; + int64_t m_PetId = 0L; + int32_t m_Quantity = 0; + std::string m_ShipDate = ""; + std::string m_Status = ""; + bool m_Complete = false; +}; + +std::vector createOrderVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Order& val) { + return val.toPropertyTree(); +} + +template<> +inline Order fromPt(const boost::property_tree::ptree& pt) { + Order ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Order_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.cpp new file mode 100644 index 0000000000..21c5f3bf2c --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.cpp @@ -0,0 +1,131 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OuterComposite.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +OuterComposite::OuterComposite(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string OuterComposite::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void OuterComposite::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree OuterComposite::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("my_number", m_My_number); + pt.put("my_string", m_My_string); + pt.put("my_boolean", m_My_boolean); + return pt; +} + +void OuterComposite::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_My_number = pt.get("my_number", 0.0); + m_My_string = pt.get("my_string", ""); + m_My_boolean = pt.get("my_boolean", false); +} + +double OuterComposite::getMyNumber() const +{ + return m_My_number; +} + +void OuterComposite::setMyNumber(double value) +{ + m_My_number = value; +} + + +std::string OuterComposite::getMyString() const +{ + return m_My_string; +} + +void OuterComposite::setMyString(std::string value) +{ + m_My_string = value; +} + + +bool OuterComposite::isMyBoolean() const +{ + return m_My_boolean; +} + +void OuterComposite::setMyBoolean(bool value) +{ + m_My_boolean = value; +} + + + +std::vector createOuterCompositeVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(OuterComposite(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.h new file mode 100644 index 0000000000..75d8465983 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.h @@ -0,0 +1,103 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OuterComposite.h + * + * + */ + +#ifndef OuterComposite_H_ +#define OuterComposite_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class OuterComposite +{ +public: + OuterComposite() = default; + explicit OuterComposite(boost::property_tree::ptree const& pt); + virtual ~OuterComposite() = default; + + OuterComposite(const OuterComposite& other) = default; // copy constructor + OuterComposite(OuterComposite&& other) noexcept = default; // move constructor + + OuterComposite& operator=(const OuterComposite& other) = default; // copy assignment + OuterComposite& operator=(OuterComposite&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// OuterComposite members + + /// + /// + /// + double getMyNumber() const; + void setMyNumber(double value); + + /// + /// + /// + std::string getMyString() const; + void setMyString(std::string value); + + /// + /// + /// + bool isMyBoolean() const; + void setMyBoolean(bool value); + +protected: + double m_My_number = 0.0; + std::string m_My_string = ""; + bool m_My_boolean = false; +}; + +std::vector createOuterCompositeVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const OuterComposite& val) { + return val.toPropertyTree(); +} + +template<> +inline OuterComposite fromPt(const boost::property_tree::ptree& pt) { + OuterComposite ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* OuterComposite_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.cpp new file mode 100644 index 0000000000..d0ab587942 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.cpp @@ -0,0 +1,114 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OuterEnum.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +OuterEnum::OuterEnum(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string OuterEnum::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void OuterEnum::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree OuterEnum::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + return pt; +} + +void OuterEnum::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; +} + +std::string OuterEnum::toString() const { + return boost::lexical_cast(getEnumValue()); +} + +void OuterEnum::fromString(const std::string& str) { + setEnumValue(boost::lexical_cast(str)); +} + +std::string OuterEnum::getEnumValue() const { + return m_OuterEnumEnumValue; +} + +void OuterEnum::setEnumValue(const std::string& val) { + static const std::array allowedValues = { + "placed", "approved", "delivered" + }; + if (std::find(allowedValues.begin(), allowedValues.end(), val) != allowedValues.end()) { + m_OuterEnumEnumValue = val; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(val) + " not allowed"); + } +} + +std::vector createOuterEnumVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(OuterEnum(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.h new file mode 100644 index 0000000000..beef6d79ae --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.h @@ -0,0 +1,86 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OuterEnum.h + * + * + */ + +#ifndef OuterEnum_H_ +#define OuterEnum_H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class OuterEnum +{ +public: + OuterEnum() = default; + explicit OuterEnum(boost::property_tree::ptree const& pt); + virtual ~OuterEnum() = default; + + OuterEnum(const OuterEnum& other) = default; // copy constructor + OuterEnum(OuterEnum&& other) noexcept = default; // move constructor + + OuterEnum& operator=(const OuterEnum& other) = default; // copy assignment + OuterEnum& operator=(OuterEnum&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + std::string toString() const; + void fromString(const std::string& str); + + ///////////////////////////////////////////// + /// OuterEnum members + std::string getEnumValue() const; + void setEnumValue(const std::string& val); + +protected: + std::string m_OuterEnumEnumValue; +}; + +std::vector createOuterEnumVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const OuterEnum& val) { + return val.toPropertyTree(); +} + +template<> +inline OuterEnum fromPt(const boost::property_tree::ptree& pt) { + OuterEnum ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* OuterEnum_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.cpp new file mode 100644 index 0000000000..c94acd44a1 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.cpp @@ -0,0 +1,114 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OuterEnumDefaultValue.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +OuterEnumDefaultValue::OuterEnumDefaultValue(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string OuterEnumDefaultValue::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void OuterEnumDefaultValue::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree OuterEnumDefaultValue::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + return pt; +} + +void OuterEnumDefaultValue::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; +} + +std::string OuterEnumDefaultValue::toString() const { + return boost::lexical_cast(getEnumValue()); +} + +void OuterEnumDefaultValue::fromString(const std::string& str) { + setEnumValue(boost::lexical_cast(str)); +} + +std::string OuterEnumDefaultValue::getEnumValue() const { + return m_OuterEnumDefaultValueEnumValue; +} + +void OuterEnumDefaultValue::setEnumValue(const std::string& val) { + static const std::array allowedValues = { + "placed", "approved", "delivered" + }; + if (std::find(allowedValues.begin(), allowedValues.end(), val) != allowedValues.end()) { + m_OuterEnumDefaultValueEnumValue = val; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(val) + " not allowed"); + } +} + +std::vector createOuterEnumDefaultValueVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(OuterEnumDefaultValue(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.h new file mode 100644 index 0000000000..73fe650889 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.h @@ -0,0 +1,86 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OuterEnumDefaultValue.h + * + * + */ + +#ifndef OuterEnumDefaultValue_H_ +#define OuterEnumDefaultValue_H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class OuterEnumDefaultValue +{ +public: + OuterEnumDefaultValue() = default; + explicit OuterEnumDefaultValue(boost::property_tree::ptree const& pt); + virtual ~OuterEnumDefaultValue() = default; + + OuterEnumDefaultValue(const OuterEnumDefaultValue& other) = default; // copy constructor + OuterEnumDefaultValue(OuterEnumDefaultValue&& other) noexcept = default; // move constructor + + OuterEnumDefaultValue& operator=(const OuterEnumDefaultValue& other) = default; // copy assignment + OuterEnumDefaultValue& operator=(OuterEnumDefaultValue&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + std::string toString() const; + void fromString(const std::string& str); + + ///////////////////////////////////////////// + /// OuterEnumDefaultValue members + std::string getEnumValue() const; + void setEnumValue(const std::string& val); + +protected: + std::string m_OuterEnumDefaultValueEnumValue; +}; + +std::vector createOuterEnumDefaultValueVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const OuterEnumDefaultValue& val) { + return val.toPropertyTree(); +} + +template<> +inline OuterEnumDefaultValue fromPt(const boost::property_tree::ptree& pt) { + OuterEnumDefaultValue ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* OuterEnumDefaultValue_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.cpp new file mode 100644 index 0000000000..84bcacfcb3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.cpp @@ -0,0 +1,114 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OuterEnumInteger.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +OuterEnumInteger::OuterEnumInteger(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string OuterEnumInteger::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void OuterEnumInteger::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree OuterEnumInteger::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + return pt; +} + +void OuterEnumInteger::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; +} + +std::string OuterEnumInteger::toString() const { + return boost::lexical_cast(getEnumValue()); +} + +void OuterEnumInteger::fromString(const std::string& str) { + setEnumValue(boost::lexical_cast(str)); +} + +int32_t OuterEnumInteger::getEnumValue() const { + return m_OuterEnumIntegerEnumValue; +} + +void OuterEnumInteger::setEnumValue(const int32_t& val) { + static const std::array allowedValues = { + 0, 1, 2 + }; + if (std::find(allowedValues.begin(), allowedValues.end(), val) != allowedValues.end()) { + m_OuterEnumIntegerEnumValue = val; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(val) + " not allowed"); + } +} + +std::vector createOuterEnumIntegerVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(OuterEnumInteger(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.h new file mode 100644 index 0000000000..e06550b1de --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.h @@ -0,0 +1,86 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OuterEnumInteger.h + * + * + */ + +#ifndef OuterEnumInteger_H_ +#define OuterEnumInteger_H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class OuterEnumInteger +{ +public: + OuterEnumInteger() = default; + explicit OuterEnumInteger(boost::property_tree::ptree const& pt); + virtual ~OuterEnumInteger() = default; + + OuterEnumInteger(const OuterEnumInteger& other) = default; // copy constructor + OuterEnumInteger(OuterEnumInteger&& other) noexcept = default; // move constructor + + OuterEnumInteger& operator=(const OuterEnumInteger& other) = default; // copy assignment + OuterEnumInteger& operator=(OuterEnumInteger&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + std::string toString() const; + void fromString(const std::string& str); + + ///////////////////////////////////////////// + /// OuterEnumInteger members + int32_t getEnumValue() const; + void setEnumValue(const int32_t& val); + +protected: + int32_t m_OuterEnumIntegerEnumValue; +}; + +std::vector createOuterEnumIntegerVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const OuterEnumInteger& val) { + return val.toPropertyTree(); +} + +template<> +inline OuterEnumInteger fromPt(const boost::property_tree::ptree& pt) { + OuterEnumInteger ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* OuterEnumInteger_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.cpp new file mode 100644 index 0000000000..b77d24f29d --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.cpp @@ -0,0 +1,114 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OuterEnumIntegerDefaultValue.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +OuterEnumIntegerDefaultValue::OuterEnumIntegerDefaultValue(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string OuterEnumIntegerDefaultValue::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void OuterEnumIntegerDefaultValue::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree OuterEnumIntegerDefaultValue::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + return pt; +} + +void OuterEnumIntegerDefaultValue::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; +} + +std::string OuterEnumIntegerDefaultValue::toString() const { + return boost::lexical_cast(getEnumValue()); +} + +void OuterEnumIntegerDefaultValue::fromString(const std::string& str) { + setEnumValue(boost::lexical_cast(str)); +} + +int32_t OuterEnumIntegerDefaultValue::getEnumValue() const { + return m_OuterEnumIntegerDefaultValueEnumValue; +} + +void OuterEnumIntegerDefaultValue::setEnumValue(const int32_t& val) { + static const std::array allowedValues = { + 0, 1, 2 + }; + if (std::find(allowedValues.begin(), allowedValues.end(), val) != allowedValues.end()) { + m_OuterEnumIntegerDefaultValueEnumValue = val; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(val) + " not allowed"); + } +} + +std::vector createOuterEnumIntegerDefaultValueVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(OuterEnumIntegerDefaultValue(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.h new file mode 100644 index 0000000000..2bdd560262 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.h @@ -0,0 +1,86 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OuterEnumIntegerDefaultValue.h + * + * + */ + +#ifndef OuterEnumIntegerDefaultValue_H_ +#define OuterEnumIntegerDefaultValue_H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class OuterEnumIntegerDefaultValue +{ +public: + OuterEnumIntegerDefaultValue() = default; + explicit OuterEnumIntegerDefaultValue(boost::property_tree::ptree const& pt); + virtual ~OuterEnumIntegerDefaultValue() = default; + + OuterEnumIntegerDefaultValue(const OuterEnumIntegerDefaultValue& other) = default; // copy constructor + OuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue&& other) noexcept = default; // move constructor + + OuterEnumIntegerDefaultValue& operator=(const OuterEnumIntegerDefaultValue& other) = default; // copy assignment + OuterEnumIntegerDefaultValue& operator=(OuterEnumIntegerDefaultValue&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + std::string toString() const; + void fromString(const std::string& str); + + ///////////////////////////////////////////// + /// OuterEnumIntegerDefaultValue members + int32_t getEnumValue() const; + void setEnumValue(const int32_t& val); + +protected: + int32_t m_OuterEnumIntegerDefaultValueEnumValue; +}; + +std::vector createOuterEnumIntegerDefaultValueVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const OuterEnumIntegerDefaultValue& val) { + return val.toPropertyTree(); +} + +template<> +inline OuterEnumIntegerDefaultValue fromPt(const boost::property_tree::ptree& pt) { + OuterEnumIntegerDefaultValue ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* OuterEnumIntegerDefaultValue_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.cpp new file mode 100644 index 0000000000..57ca5fd896 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.cpp @@ -0,0 +1,103 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "OuterObjectWithEnumProperty.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +OuterObjectWithEnumProperty::OuterObjectWithEnumProperty(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string OuterObjectWithEnumProperty::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void OuterObjectWithEnumProperty::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree OuterObjectWithEnumProperty::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + return pt; +} + +void OuterObjectWithEnumProperty::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; +} + +OuterEnumInteger OuterObjectWithEnumProperty::getValue() const +{ + return m_Value; +} + +void OuterObjectWithEnumProperty::setValue(OuterEnumInteger value) +{ + m_Value = value; +} + + + +std::vector createOuterObjectWithEnumPropertyVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(OuterObjectWithEnumProperty(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.h new file mode 100644 index 0000000000..9a3c133e55 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OuterObjectWithEnumProperty.h + * + * + */ + +#ifndef OuterObjectWithEnumProperty_H_ +#define OuterObjectWithEnumProperty_H_ + + + +#include "OuterEnumInteger.h" +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class OuterObjectWithEnumProperty +{ +public: + OuterObjectWithEnumProperty() = default; + explicit OuterObjectWithEnumProperty(boost::property_tree::ptree const& pt); + virtual ~OuterObjectWithEnumProperty() = default; + + OuterObjectWithEnumProperty(const OuterObjectWithEnumProperty& other) = default; // copy constructor + OuterObjectWithEnumProperty(OuterObjectWithEnumProperty&& other) noexcept = default; // move constructor + + OuterObjectWithEnumProperty& operator=(const OuterObjectWithEnumProperty& other) = default; // copy assignment + OuterObjectWithEnumProperty& operator=(OuterObjectWithEnumProperty&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// OuterObjectWithEnumProperty members + + /// + /// + /// + OuterEnumInteger getValue() const; + void setValue(OuterEnumInteger value); + +protected: + OuterEnumInteger m_Value = OuterEnumInteger{}; +}; + +std::vector createOuterObjectWithEnumPropertyVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const OuterObjectWithEnumProperty& val) { + return val.toPropertyTree(); +} + +template<> +inline OuterObjectWithEnumProperty fromPt(const boost::property_tree::ptree& pt) { + OuterObjectWithEnumProperty ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* OuterObjectWithEnumProperty_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.cpp new file mode 100644 index 0000000000..bcc526f0ad --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.cpp @@ -0,0 +1,199 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Pet.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Pet::Pet(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Pet::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Pet::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Pet::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("id", m_Id); + pt.add_child("category", m_Category.toPropertyTree()); + pt.put("name", m_Name); + // generate tree for PhotoUrls + tmp_node.clear(); + if (!m_PhotoUrls.empty()) { + tmp_node = toPt(m_PhotoUrls); + pt.add_child("photoUrls", tmp_node); + tmp_node.clear(); + } + // generate tree for Tags + tmp_node.clear(); + if (!m_Tags.empty()) { + tmp_node = toPt(m_Tags); + pt.add_child("tags", tmp_node); + tmp_node.clear(); + } + pt.put("status", m_Status); + return pt; +} + +void Pet::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Id = pt.get("id", 0L); + if (pt.get_child_optional("category")) { + m_Category = fromPt(pt.get_child("category")); + } + m_Name = pt.get("name", ""); + // push all items of PhotoUrls into member + if (pt.get_child_optional("photoUrls")) { + m_PhotoUrls = fromPt>(pt.get_child("photoUrls")); + } + // push all items of Tags into member + if (pt.get_child_optional("tags")) { + m_Tags = fromPt>(pt.get_child("tags")); + } + setStatus(pt.get("status", "")); +} + +int64_t Pet::getId() const +{ + return m_Id; +} + +void Pet::setId(int64_t value) +{ + m_Id = value; +} + + +Category Pet::getCategory() const +{ + return m_Category; +} + +void Pet::setCategory(Category value) +{ + m_Category = value; +} + + +std::string Pet::getName() const +{ + return m_Name; +} + +void Pet::setName(std::string value) +{ + m_Name = value; +} + + +std::set Pet::getPhotoUrls() const +{ + return m_PhotoUrls; +} + +void Pet::setPhotoUrls(std::set value) +{ + m_PhotoUrls = value; +} + + +std::vector Pet::getTags() const +{ + return m_Tags; +} + +void Pet::setTags(std::vector value) +{ + m_Tags = value; +} + + +std::string Pet::getStatus() const +{ + return m_Status; +} + +void Pet::setStatus(std::string value) +{ + static const std::array allowedValues = { + "available", "pending", "sold" + }; + + if (std::find(allowedValues.begin(), allowedValues.end(), value) != allowedValues.end()) { + m_Status = value; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(value) + " not allowed"); + } +} + + + +std::vector createPetVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Pet(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.h new file mode 100644 index 0000000000..9dd20bf510 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.h @@ -0,0 +1,129 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Pet.h + * + * + */ + +#ifndef Pet_H_ +#define Pet_H_ + + + +#include "Tag.h" +#include +#include "Category.h" +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Pet +{ +public: + Pet() = default; + explicit Pet(boost::property_tree::ptree const& pt); + virtual ~Pet() = default; + + Pet(const Pet& other) = default; // copy constructor + Pet(Pet&& other) noexcept = default; // move constructor + + Pet& operator=(const Pet& other) = default; // copy assignment + Pet& operator=(Pet&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Pet members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + Category getCategory() const; + void setCategory(Category value); + + /// + /// + /// + std::string getName() const; + void setName(std::string value); + + /// + /// + /// + std::set getPhotoUrls() const; + void setPhotoUrls(std::set value); + + /// + /// + /// + std::vector getTags() const; + void setTags(std::vector value); + + /// + /// pet status in the store + /// + std::string getStatus() const; + void setStatus(std::string value); + +protected: + int64_t m_Id = 0L; + Category m_Category; + std::string m_Name = ""; + std::set m_PhotoUrls; + std::vector m_Tags; + std::string m_Status = ""; +}; + +std::vector createPetVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Pet& val) { + return val.toPropertyTree(); +} + +template<> +inline Pet fromPt(const boost::property_tree::ptree& pt) { + Pet ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Pet_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.cpp new file mode 100644 index 0000000000..5af9549239 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.cpp @@ -0,0 +1,118 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "ReadOnlyFirst.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +ReadOnlyFirst::ReadOnlyFirst(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string ReadOnlyFirst::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void ReadOnlyFirst::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree ReadOnlyFirst::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("bar", m_Bar); + pt.put("baz", m_Baz); + return pt; +} + +void ReadOnlyFirst::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Bar = pt.get("bar", ""); + m_Baz = pt.get("baz", ""); +} + +std::string ReadOnlyFirst::getBar() const +{ + return m_Bar; +} + +void ReadOnlyFirst::setBar(std::string value) +{ + m_Bar = value; +} + + +std::string ReadOnlyFirst::getBaz() const +{ + return m_Baz; +} + +void ReadOnlyFirst::setBaz(std::string value) +{ + m_Baz = value; +} + + + +std::vector createReadOnlyFirstVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(ReadOnlyFirst(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.h new file mode 100644 index 0000000000..517a1202ad --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.h @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * ReadOnlyFirst.h + * + * + */ + +#ifndef ReadOnlyFirst_H_ +#define ReadOnlyFirst_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class ReadOnlyFirst +{ +public: + ReadOnlyFirst() = default; + explicit ReadOnlyFirst(boost::property_tree::ptree const& pt); + virtual ~ReadOnlyFirst() = default; + + ReadOnlyFirst(const ReadOnlyFirst& other) = default; // copy constructor + ReadOnlyFirst(ReadOnlyFirst&& other) noexcept = default; // move constructor + + ReadOnlyFirst& operator=(const ReadOnlyFirst& other) = default; // copy assignment + ReadOnlyFirst& operator=(ReadOnlyFirst&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// ReadOnlyFirst members + + /// + /// + /// + std::string getBar() const; + void setBar(std::string value); + + /// + /// + /// + std::string getBaz() const; + void setBaz(std::string value); + +protected: + std::string m_Bar = ""; + std::string m_Baz = ""; +}; + +std::vector createReadOnlyFirstVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const ReadOnlyFirst& val) { + return val.toPropertyTree(); +} + +template<> +inline ReadOnlyFirst fromPt(const boost::property_tree::ptree& pt) { + ReadOnlyFirst ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* ReadOnlyFirst_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.cpp new file mode 100644 index 0000000000..8b6a65d3a2 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Return.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Return::Return(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Return::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Return::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Return::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("return", m_r_return); + return pt; +} + +void Return::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_r_return = pt.get("return", 0); +} + +int32_t Return::getRReturn() const +{ + return m_r_return; +} + +void Return::setRReturn(int32_t value) +{ + m_r_return = value; +} + + + +std::vector createReturnVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Return(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.h new file mode 100644 index 0000000000..2d73bd0d34 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.h @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Return.h + * + * Model for testing reserved words + */ + +#ifndef Return_H_ +#define Return_H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// Model for testing reserved words +/// +class Return +{ +public: + Return() = default; + explicit Return(boost::property_tree::ptree const& pt); + virtual ~Return() = default; + + Return(const Return& other) = default; // copy constructor + Return(Return&& other) noexcept = default; // move constructor + + Return& operator=(const Return& other) = default; // copy assignment + Return& operator=(Return&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Return members + + /// + /// + /// + int32_t getRReturn() const; + void setRReturn(int32_t value); + +protected: + int32_t m_r_return = 0; +}; + +std::vector createReturnVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Return& val) { + return val.toPropertyTree(); +} + +template<> +inline Return fromPt(const boost::property_tree::ptree& pt) { + Return ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Return_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.cpp new file mode 100644 index 0000000000..5e5c72fa48 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.cpp @@ -0,0 +1,114 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "SingleRefType.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +SingleRefType::SingleRefType(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string SingleRefType::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void SingleRefType::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree SingleRefType::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + return pt; +} + +void SingleRefType::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; +} + +std::string SingleRefType::toString() const { + return boost::lexical_cast(getEnumValue()); +} + +void SingleRefType::fromString(const std::string& str) { + setEnumValue(boost::lexical_cast(str)); +} + +std::string SingleRefType::getEnumValue() const { + return m_SingleRefTypeEnumValue; +} + +void SingleRefType::setEnumValue(const std::string& val) { + static const std::array allowedValues = { + "admin", "user" + }; + if (std::find(allowedValues.begin(), allowedValues.end(), val) != allowedValues.end()) { + m_SingleRefTypeEnumValue = val; + } else { + throw std::runtime_error("Value " + boost::lexical_cast(val) + " not allowed"); + } +} + +std::vector createSingleRefTypeVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(SingleRefType(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.h new file mode 100644 index 0000000000..9c4962f4be --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.h @@ -0,0 +1,86 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * SingleRefType.h + * + * + */ + +#ifndef SingleRefType_H_ +#define SingleRefType_H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class SingleRefType +{ +public: + SingleRefType() = default; + explicit SingleRefType(boost::property_tree::ptree const& pt); + virtual ~SingleRefType() = default; + + SingleRefType(const SingleRefType& other) = default; // copy constructor + SingleRefType(SingleRefType&& other) noexcept = default; // move constructor + + SingleRefType& operator=(const SingleRefType& other) = default; // copy assignment + SingleRefType& operator=(SingleRefType&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + std::string toString() const; + void fromString(const std::string& str); + + ///////////////////////////////////////////// + /// SingleRefType members + std::string getEnumValue() const; + void setEnumValue(const std::string& val); + +protected: + std::string m_SingleRefTypeEnumValue; +}; + +std::vector createSingleRefTypeVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const SingleRefType& val) { + return val.toPropertyTree(); +} + +template<> +inline SingleRefType fromPt(const boost::property_tree::ptree& pt) { + SingleRefType ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* SingleRefType_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.cpp new file mode 100644 index 0000000000..6a072f9ccb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.cpp @@ -0,0 +1,118 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "Tag.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +Tag::Tag(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string Tag::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void Tag::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree Tag::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("id", m_Id); + pt.put("name", m_Name); + return pt; +} + +void Tag::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Id = pt.get("id", 0L); + m_Name = pt.get("name", ""); +} + +int64_t Tag::getId() const +{ + return m_Id; +} + +void Tag::setId(int64_t value) +{ + m_Id = value; +} + + +std::string Tag::getName() const +{ + return m_Name; +} + +void Tag::setName(std::string value) +{ + m_Name = value; +} + + + +std::vector createTagVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Tag(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.h new file mode 100644 index 0000000000..cd74e7d0c5 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.h @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * Tag.h + * + * + */ + +#ifndef Tag_H_ +#define Tag_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class Tag +{ +public: + Tag() = default; + explicit Tag(boost::property_tree::ptree const& pt); + virtual ~Tag() = default; + + Tag(const Tag& other) = default; // copy constructor + Tag(Tag&& other) noexcept = default; // move constructor + + Tag& operator=(const Tag& other) = default; // copy assignment + Tag& operator=(Tag&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// Tag members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + std::string getName() const; + void setName(std::string value); + +protected: + int64_t m_Id = 0L; + std::string m_Name = ""; +}; + +std::vector createTagVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const Tag& val) { + return val.toPropertyTree(); +} + +template<> +inline Tag fromPt(const boost::property_tree::ptree& pt) { + Tag ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* Tag_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/User.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/User.cpp new file mode 100644 index 0000000000..6a3bd4e290 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/User.cpp @@ -0,0 +1,196 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "User.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +User::User(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string User::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void User::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree User::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("id", m_Id); + pt.put("username", m_Username); + pt.put("firstName", m_FirstName); + pt.put("lastName", m_LastName); + pt.put("email", m_Email); + pt.put("password", m_Password); + pt.put("phone", m_Phone); + pt.put("userStatus", m_UserStatus); + return pt; +} + +void User::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Id = pt.get("id", 0L); + m_Username = pt.get("username", ""); + m_FirstName = pt.get("firstName", ""); + m_LastName = pt.get("lastName", ""); + m_Email = pt.get("email", ""); + m_Password = pt.get("password", ""); + m_Phone = pt.get("phone", ""); + m_UserStatus = pt.get("userStatus", 0); +} + +int64_t User::getId() const +{ + return m_Id; +} + +void User::setId(int64_t value) +{ + m_Id = value; +} + + +std::string User::getUsername() const +{ + return m_Username; +} + +void User::setUsername(std::string value) +{ + m_Username = value; +} + + +std::string User::getFirstName() const +{ + return m_FirstName; +} + +void User::setFirstName(std::string value) +{ + m_FirstName = value; +} + + +std::string User::getLastName() const +{ + return m_LastName; +} + +void User::setLastName(std::string value) +{ + m_LastName = value; +} + + +std::string User::getEmail() const +{ + return m_Email; +} + +void User::setEmail(std::string value) +{ + m_Email = value; +} + + +std::string User::getPassword() const +{ + return m_Password; +} + +void User::setPassword(std::string value) +{ + m_Password = value; +} + + +std::string User::getPhone() const +{ + return m_Phone; +} + +void User::setPhone(std::string value) +{ + m_Phone = value; +} + + +int32_t User::getUserStatus() const +{ + return m_UserStatus; +} + +void User::setUserStatus(int32_t value) +{ + m_UserStatus = value; +} + + + +std::vector createUserVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(User(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/User.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/User.h new file mode 100644 index 0000000000..84daeb41cb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/User.h @@ -0,0 +1,138 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * User.h + * + * + */ + +#ifndef User_H_ +#define User_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class User +{ +public: + User() = default; + explicit User(boost::property_tree::ptree const& pt); + virtual ~User() = default; + + User(const User& other) = default; // copy constructor + User(User&& other) noexcept = default; // move constructor + + User& operator=(const User& other) = default; // copy assignment + User& operator=(User&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// User members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t value); + + /// + /// + /// + std::string getUsername() const; + void setUsername(std::string value); + + /// + /// + /// + std::string getFirstName() const; + void setFirstName(std::string value); + + /// + /// + /// + std::string getLastName() const; + void setLastName(std::string value); + + /// + /// + /// + std::string getEmail() const; + void setEmail(std::string value); + + /// + /// + /// + std::string getPassword() const; + void setPassword(std::string value); + + /// + /// + /// + std::string getPhone() const; + void setPhone(std::string value); + + /// + /// User Status + /// + int32_t getUserStatus() const; + void setUserStatus(int32_t value); + +protected: + int64_t m_Id = 0L; + std::string m_Username = ""; + std::string m_FirstName = ""; + std::string m_LastName = ""; + std::string m_Email = ""; + std::string m_Password = ""; + std::string m_Phone = ""; + int32_t m_UserStatus = 0; +}; + +std::vector createUserVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const User& val) { + return val.toPropertyTree(); +} + +template<> +inline User fromPt(const boost::property_tree::ptree& pt) { + User ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* User_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.cpp new file mode 100644 index 0000000000..d0691aae3c --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.cpp @@ -0,0 +1,107 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "_foo_get_default_response.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +_foo_get_default_response::_foo_get_default_response(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string _foo_get_default_response::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void _foo_get_default_response::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree _foo_get_default_response::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.add_child("string", m_string.toPropertyTree()); + return pt; +} + +void _foo_get_default_response::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + if (pt.get_child_optional("string")) { + m_string = fromPt(pt.get_child("string")); + } +} + +Foo _foo_get_default_response::getString() const +{ + return m_string; +} + +void _foo_get_default_response::setString(Foo value) +{ + m_string = value; +} + + + +std::vector<_foo_get_default_response> create_foo_get_default_responseVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector<_foo_get_default_response>(); + for (const auto& child: pt) { + vec.emplace_back(_foo_get_default_response(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.h new file mode 100644 index 0000000000..42f54fe696 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.h @@ -0,0 +1,89 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * _foo_get_default_response.h + * + * + */ + +#ifndef _foo_get_default_response_H_ +#define _foo_get_default_response_H_ + + + +#include "Foo.h" +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class _foo_get_default_response +{ +public: + _foo_get_default_response() = default; + explicit _foo_get_default_response(boost::property_tree::ptree const& pt); + virtual ~_foo_get_default_response() = default; + + _foo_get_default_response(const _foo_get_default_response& other) = default; // copy constructor + _foo_get_default_response(_foo_get_default_response&& other) noexcept = default; // move constructor + + _foo_get_default_response& operator=(const _foo_get_default_response& other) = default; // copy assignment + _foo_get_default_response& operator=(_foo_get_default_response&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// _foo_get_default_response members + + /// + /// + /// + Foo getString() const; + void setString(Foo value); + +protected: + Foo m_string; +}; + +std::vector<_foo_get_default_response> create_foo_get_default_responseVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt<_foo_get_default_response>(const _foo_get_default_response& val) { + return val.toPropertyTree(); +} + +template<> +inline _foo_get_default_response fromPt<_foo_get_default_response>(const boost::property_tree::ptree& pt) { + _foo_get_default_response ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* _foo_get_default_response_H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.cpp new file mode 100644 index 0000000000..6116553948 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.cpp @@ -0,0 +1,105 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "_special_model_name_.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +_special_model_name_::_special_model_name_(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string _special_model_name_::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void _special_model_name_::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree _special_model_name_::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("$special[property.name]", m_special_property_name); + return pt; +} + +void _special_model_name_::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_special_property_name = pt.get("$special[property.name]", 0L); +} + +int64_t _special_model_name_::getSpecialPropertyName() const +{ + return m_special_property_name; +} + +void _special_model_name_::setSpecialPropertyName(int64_t value) +{ + m_special_property_name = value; +} + + + +std::vector<_special_model_name_> create_special_model_name_VectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector<_special_model_name_>(); + for (const auto& child: pt) { + vec.emplace_back(_special_model_name_(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.h new file mode 100644 index 0000000000..96e269f7de --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.h @@ -0,0 +1,88 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * _special_model_name_.h + * + * + */ + +#ifndef _special_model_name__H_ +#define _special_model_name__H_ + + + +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// +/// +class _special_model_name_ +{ +public: + _special_model_name_() = default; + explicit _special_model_name_(boost::property_tree::ptree const& pt); + virtual ~_special_model_name_() = default; + + _special_model_name_(const _special_model_name_& other) = default; // copy constructor + _special_model_name_(_special_model_name_&& other) noexcept = default; // move constructor + + _special_model_name_& operator=(const _special_model_name_& other) = default; // copy assignment + _special_model_name_& operator=(_special_model_name_&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// _special_model_name_ members + + /// + /// + /// + int64_t getSpecialPropertyName() const; + void setSpecialPropertyName(int64_t value); + +protected: + int64_t m_special_property_name = 0L; +}; + +std::vector<_special_model_name_> create_special_model_name_VectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt<_special_model_name_>(const _special_model_name_& val) { + return val.toPropertyTree(); +} + +template<> +inline _special_model_name_ fromPt<_special_model_name_>(const boost::property_tree::ptree& pt) { + _special_model_name_ ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* _special_model_name__H_ */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/helpers.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/helpers.h new file mode 100644 index 0000000000..9808648614 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/helpers.h @@ -0,0 +1,149 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#ifndef OPENAPI_MODELS_HELPER_H_ +#define OPENAPI_MODELS_HELPER_H_ + + + +#include +#include +#include +#include + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +template +boost::property_tree::ptree toPt(const T& val) { + boost::property_tree::ptree pt; + pt.put_value(val); + return pt; +} + +template +boost::property_tree::ptree toPt(const std::vector & vec) { + boost::property_tree::ptree pt; + for (auto &childEntry : vec) { + boost::property_tree::ptree childNode = toPt(childEntry); + pt.push_back(std::make_pair("", childNode)); + } + return pt; +} + +template +boost::property_tree::ptree toPt(const std::map & map) { + boost::property_tree::ptree pt; + for (auto &childEntry : map) { + boost::property_tree::ptree childNode = toPt(childEntry.second); + pt.push_back(boost::property_tree::ptree::value_type(childEntry.first, childNode)); + } + return pt; +} + +template +boost::property_tree::ptree toPt(const std::set & set) { + boost::property_tree::ptree pt; + for (auto &childEntry : set) { + boost::property_tree::ptree childNode = toPt(childEntry); + pt.push_back(std::make_pair("", childNode)); + } + return pt; +} + + +template +struct is_vector +{ + static constexpr bool value = false; +}; + +template +struct is_vector> +{ + static constexpr bool value = true; +}; + +template +struct is_map +{ + static constexpr bool value = false; +}; + +template +struct is_map> +{ + static constexpr bool value = true; +}; + +template +struct is_set +{ + static constexpr bool value = false; +}; + +template +struct is_set> +{ + static constexpr bool value = true; +}; + + +template +std::enable_if_t::value && !is_map::value && !is_set::value, T> +fromPt(const boost::property_tree::ptree& pt) { + return pt.get_value(); +} + +template +std::enable_if_t::value,T> +fromPt(const boost::property_tree::ptree& pt) { + T vec; + for (const auto &child: pt) { + typename T::value_type childElement = fromPt(child.second); + vec.emplace_back(childElement); + } + return vec; +} + +template +std::enable_if_t::value,T> +fromPt(const boost::property_tree::ptree &pt) { + T map; + for (const auto &child: pt) { + using ChildType = typename T::mapped_type; + ChildType childElement = fromPt(child.second); + map.insert(std::make_pair(child.first, childElement)); + } + return map; +} + +template +std::enable_if_t::value,T> +fromPt(const boost::property_tree::ptree& pt) { + T set; + for (const auto &child: pt) { + typename T::value_type childElement = fromPt(child.second); + set.insert(childElement); + } + return set; +} + +} +} +} +} + +#endif /* OPENAPI_MODELS_HELPER_H_ */ \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.cpp new file mode 100644 index 0000000000..6fbf50f705 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.cpp @@ -0,0 +1,118 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + + +#include "r_200_response.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "helpers.h" + +using boost::property_tree::ptree; +using boost::property_tree::read_json; +using boost::property_tree::write_json; + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +r_200_response::r_200_response(boost::property_tree::ptree const& pt) +{ + fromPropertyTree(pt); +} + + +std::string r_200_response::toJsonString(bool prettyJson /* = false */) const +{ + std::stringstream ss; + write_json(ss, this->toPropertyTree(), prettyJson); + // workaround inspired by: https://stackoverflow.com/a/56395440 + std::regex reg("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); + std::string result = std::regex_replace(ss.str(), reg, "$1"); + return result; +} + +void r_200_response::fromJsonString(std::string const& jsonString) +{ + std::stringstream ss(jsonString); + ptree pt; + read_json(ss,pt); + this->fromPropertyTree(pt); +} + +ptree r_200_response::toPropertyTree() const +{ + ptree pt; + ptree tmp_node; + pt.put("name", m_Name); + pt.put("class", m_r_class); + return pt; +} + +void r_200_response::fromPropertyTree(ptree const &pt) +{ + ptree tmp_node; + m_Name = pt.get("name", 0); + m_r_class = pt.get("class", ""); +} + +int32_t r_200_response::getName() const +{ + return m_Name; +} + +void r_200_response::setName(int32_t value) +{ + m_Name = value; +} + + +std::string r_200_response::getRClass() const +{ + return m_r_class; +} + +void r_200_response::setRClass(std::string value) +{ + m_r_class = value; +} + + + +std::vector creater_200_responseVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(r_200_response(child.second)); + } + + return vec; +} + +} +} +} +} + diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.h new file mode 100644 index 0000000000..0d14ade75d --- /dev/null +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.h @@ -0,0 +1,96 @@ +/** + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI-Generator 7.0.0-SNAPSHOT. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * r_200_response.h + * + * Model for testing model name starting with number + */ + +#ifndef r_200_response_H_ +#define r_200_response_H_ + + + +#include +#include +#include +#include +#include "helpers.h" + +namespace org { +namespace openapitools { +namespace server { +namespace model { + +/// +/// Model for testing model name starting with number +/// +class r_200_response +{ +public: + r_200_response() = default; + explicit r_200_response(boost::property_tree::ptree const& pt); + virtual ~r_200_response() = default; + + r_200_response(const r_200_response& other) = default; // copy constructor + r_200_response(r_200_response&& other) noexcept = default; // move constructor + + r_200_response& operator=(const r_200_response& other) = default; // copy assignment + r_200_response& operator=(r_200_response&& other) noexcept = default; // move assignment + + std::string toJsonString(bool prettyJson = false) const; + void fromJsonString(std::string const& jsonString); + boost::property_tree::ptree toPropertyTree() const; + void fromPropertyTree(boost::property_tree::ptree const& pt); + + + ///////////////////////////////////////////// + /// r_200_response members + + /// + /// + /// + int32_t getName() const; + void setName(int32_t value); + + /// + /// + /// + std::string getRClass() const; + void setRClass(std::string value); + +protected: + int32_t m_Name = 0; + std::string m_r_class = ""; +}; + +std::vector creater_200_responseVectorFromJsonString(const std::string& json); + +template<> +inline boost::property_tree::ptree toPt(const r_200_response& val) { + return val.toPropertyTree(); +} + +template<> +inline r_200_response fromPt(const boost::property_tree::ptree& pt) { + r_200_response ret; + ret.fromPropertyTree(pt); + return ret; +} + +} +} +} +} + +#endif /* r_200_response_H_ */ diff --git a/samples/server/petstore/cpp-restbed/git_push.sh b/samples/server/petstore/cpp-restbed/git_push.sh deleted file mode 100644 index ced3be2b0c..0000000000 --- a/samples/server/petstore/cpp-restbed/git_push.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=`git remote` -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' - diff --git a/samples/server/petstore/cpp-restbed/model/ApiResponse.h b/samples/server/petstore/cpp-restbed/model/ApiResponse.h deleted file mode 100644 index b67b10af78..0000000000 --- a/samples/server/petstore/cpp-restbed/model/ApiResponse.h +++ /dev/null @@ -1,94 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/* - * ApiResponse.h - * - * Describes the result of uploading an image resource - */ - -#ifndef ApiResponse_H_ -#define ApiResponse_H_ - - - -#include -#include -#include -#include - -namespace org { -namespace openapitools { -namespace server { -namespace model { - -/// -/// Describes the result of uploading an image resource -/// -class ApiResponse -{ -public: - ApiResponse() = default; - explicit ApiResponse(boost::property_tree::ptree const& pt); - virtual ~ApiResponse() = default; - - std::string toJsonString(bool prettyJson = false); - void fromJsonString(std::string const& jsonString); - boost::property_tree::ptree toPropertyTree(); - void fromPropertyTree(boost::property_tree::ptree const& pt); - - ///////////////////////////////////////////// - /// ApiResponse members - - /// - /// - /// - int32_t getCode() const; - void setCode(int32_t value); - - /// - /// - /// - std::string getType() const; - void setType(std::string value); - - /// - /// - /// - std::string getMessage() const; - void setMessage(std::string value); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string toJsonString_internal(bool prettyJson = false); - virtual void fromJsonString_internal(std::string const& jsonString); - virtual boost::property_tree::ptree toPropertyTree_internal(); - virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); - - -protected: - int32_t m_Code = 0; - std::string m_Type = ""; - std::string m_Message = ""; -}; - -std::vector createApiResponseVectorFromJsonString(const std::string& json); - -} -} -} -} - -#endif /* ApiResponse_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/Category.h b/samples/server/petstore/cpp-restbed/model/Category.h deleted file mode 100644 index 949677e8bf..0000000000 --- a/samples/server/petstore/cpp-restbed/model/Category.h +++ /dev/null @@ -1,87 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/* - * Category.h - * - * A category for a pet - */ - -#ifndef Category_H_ -#define Category_H_ - - - -#include -#include -#include -#include - -namespace org { -namespace openapitools { -namespace server { -namespace model { - -/// -/// A category for a pet -/// -class Category -{ -public: - Category() = default; - explicit Category(boost::property_tree::ptree const& pt); - virtual ~Category() = default; - - std::string toJsonString(bool prettyJson = false); - void fromJsonString(std::string const& jsonString); - boost::property_tree::ptree toPropertyTree(); - void fromPropertyTree(boost::property_tree::ptree const& pt); - - ///////////////////////////////////////////// - /// Category members - - /// - /// - /// - int64_t getId() const; - void setId(int64_t value); - - /// - /// - /// - std::string getName() const; - void setName(std::string value); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string toJsonString_internal(bool prettyJson = false); - virtual void fromJsonString_internal(std::string const& jsonString); - virtual boost::property_tree::ptree toPropertyTree_internal(); - virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); - - -protected: - int64_t m_Id = 0L; - std::string m_Name = ""; -}; - -std::vector createCategoryVectorFromJsonString(const std::string& json); - -} -} -} -} - -#endif /* Category_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/Order.h b/samples/server/petstore/cpp-restbed/model/Order.h deleted file mode 100644 index b10f2daf3a..0000000000 --- a/samples/server/petstore/cpp-restbed/model/Order.h +++ /dev/null @@ -1,121 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/* - * Order.h - * - * An order for a pets from the pet store - */ - -#ifndef Order_H_ -#define Order_H_ - - - -#include -#include -#include -#include -#include -#include - -namespace org { -namespace openapitools { -namespace server { -namespace model { - -/// -/// An order for a pets from the pet store -/// -class Order -{ -public: - Order() = default; - explicit Order(boost::property_tree::ptree const& pt); - virtual ~Order() = default; - - std::string toJsonString(bool prettyJson = false); - void fromJsonString(std::string const& jsonString); - boost::property_tree::ptree toPropertyTree(); - void fromPropertyTree(boost::property_tree::ptree const& pt); - - ///////////////////////////////////////////// - /// Order members - - /// - /// - /// - int64_t getId() const; - void setId(int64_t value); - - /// - /// - /// - int64_t getPetId() const; - void setPetId(int64_t value); - - /// - /// - /// - int32_t getQuantity() const; - void setQuantity(int32_t value); - - /// - /// - /// - std::string getShipDate() const; - void setShipDate(std::string value); - - /// - /// Order Status - /// - std::string getStatus() const; - void setStatus(std::string value); - - /// - /// - /// - bool isComplete() const; - void setComplete(bool value); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string toJsonString_internal(bool prettyJson = false); - virtual void fromJsonString_internal(std::string const& jsonString); - virtual boost::property_tree::ptree toPropertyTree_internal(); - virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); - - -protected: - int64_t m_Id = 0L; - int64_t m_PetId = 0L; - int32_t m_Quantity = 0; - std::string m_ShipDate = ""; - std::string m_Status = ""; - bool m_Complete = false; - const std::array m_StatusEnum = { - "placed","approved","delivered" - }; - -}; - -std::vector createOrderVectorFromJsonString(const std::string& json); - -} -} -} -} - -#endif /* Order_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/Pet.h b/samples/server/petstore/cpp-restbed/model/Pet.h deleted file mode 100644 index 43bd89e15b..0000000000 --- a/samples/server/petstore/cpp-restbed/model/Pet.h +++ /dev/null @@ -1,123 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/* - * Pet.h - * - * A pet for sale in the pet store - */ - -#ifndef Pet_H_ -#define Pet_H_ - - - -#include "Tag.h" -#include -#include "Category.h" -#include -#include -#include -#include -#include - -namespace org { -namespace openapitools { -namespace server { -namespace model { - -/// -/// A pet for sale in the pet store -/// -class Pet -{ -public: - Pet() = default; - explicit Pet(boost::property_tree::ptree const& pt); - virtual ~Pet() = default; - - std::string toJsonString(bool prettyJson = false); - void fromJsonString(std::string const& jsonString); - boost::property_tree::ptree toPropertyTree(); - void fromPropertyTree(boost::property_tree::ptree const& pt); - - ///////////////////////////////////////////// - /// Pet members - - /// - /// - /// - int64_t getId() const; - void setId(int64_t value); - - /// - /// - /// - std::shared_ptr getCategory() const; - void setCategory(std::shared_ptr value); - - /// - /// - /// - std::string getName() const; - void setName(std::string value); - - /// - /// - /// - std::vector getPhotoUrls() const; - void setPhotoUrls(std::vector value); - - /// - /// - /// - std::vector> getTags() const; - void setTags(std::vector> value); - - /// - /// pet status in the store - /// - std::string getStatus() const; - void setStatus(std::string value); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string toJsonString_internal(bool prettyJson = false); - virtual void fromJsonString_internal(std::string const& jsonString); - virtual boost::property_tree::ptree toPropertyTree_internal(); - virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); - - -protected: - int64_t m_Id = 0L; - std::shared_ptr m_Category; - std::string m_Name = ""; - std::vector m_PhotoUrls; - std::vector> m_Tags; - std::string m_Status = ""; - const std::array m_StatusEnum = { - "available","pending","sold" - }; - -}; - -std::vector createPetVectorFromJsonString(const std::string& json); - -} -} -} -} - -#endif /* Pet_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/Tag.h b/samples/server/petstore/cpp-restbed/model/Tag.h deleted file mode 100644 index 82de314f72..0000000000 --- a/samples/server/petstore/cpp-restbed/model/Tag.h +++ /dev/null @@ -1,87 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/* - * Tag.h - * - * A tag for a pet - */ - -#ifndef Tag_H_ -#define Tag_H_ - - - -#include -#include -#include -#include - -namespace org { -namespace openapitools { -namespace server { -namespace model { - -/// -/// A tag for a pet -/// -class Tag -{ -public: - Tag() = default; - explicit Tag(boost::property_tree::ptree const& pt); - virtual ~Tag() = default; - - std::string toJsonString(bool prettyJson = false); - void fromJsonString(std::string const& jsonString); - boost::property_tree::ptree toPropertyTree(); - void fromPropertyTree(boost::property_tree::ptree const& pt); - - ///////////////////////////////////////////// - /// Tag members - - /// - /// - /// - int64_t getId() const; - void setId(int64_t value); - - /// - /// - /// - std::string getName() const; - void setName(std::string value); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string toJsonString_internal(bool prettyJson = false); - virtual void fromJsonString_internal(std::string const& jsonString); - virtual boost::property_tree::ptree toPropertyTree_internal(); - virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); - - -protected: - int64_t m_Id = 0L; - std::string m_Name = ""; -}; - -std::vector createTagVectorFromJsonString(const std::string& json); - -} -} -} -} - -#endif /* Tag_H_ */ diff --git a/samples/server/petstore/cpp-restbed/model/User.h b/samples/server/petstore/cpp-restbed/model/User.h deleted file mode 100644 index dcc3902dad..0000000000 --- a/samples/server/petstore/cpp-restbed/model/User.h +++ /dev/null @@ -1,129 +0,0 @@ -/** - * 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. - * - * The version of the OpenAPI document: 1.0.0 - * - * - * NOTE: This class is auto generated by OpenAPI-Generator unset. - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -/* - * User.h - * - * A User who is purchasing from the pet store - */ - -#ifndef User_H_ -#define User_H_ - - - -#include -#include -#include -#include - -namespace org { -namespace openapitools { -namespace server { -namespace model { - -/// -/// A User who is purchasing from the pet store -/// -class User -{ -public: - User() = default; - explicit User(boost::property_tree::ptree const& pt); - virtual ~User() = default; - - std::string toJsonString(bool prettyJson = false); - void fromJsonString(std::string const& jsonString); - boost::property_tree::ptree toPropertyTree(); - void fromPropertyTree(boost::property_tree::ptree const& pt); - - ///////////////////////////////////////////// - /// User members - - /// - /// - /// - int64_t getId() const; - void setId(int64_t value); - - /// - /// - /// - std::string getUsername() const; - void setUsername(std::string value); - - /// - /// - /// - std::string getFirstName() const; - void setFirstName(std::string value); - - /// - /// - /// - std::string getLastName() const; - void setLastName(std::string value); - - /// - /// - /// - std::string getEmail() const; - void setEmail(std::string value); - - /// - /// - /// - std::string getPassword() const; - void setPassword(std::string value); - - /// - /// - /// - std::string getPhone() const; - void setPhone(std::string value); - - /// - /// User Status - /// - int32_t getUserStatus() const; - void setUserStatus(int32_t value); - -protected: - ////////////////////////////////////// - // Override these for customization // - ////////////////////////////////////// - - virtual std::string toJsonString_internal(bool prettyJson = false); - virtual void fromJsonString_internal(std::string const& jsonString); - virtual boost::property_tree::ptree toPropertyTree_internal(); - virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); - - -protected: - int64_t m_Id = 0L; - std::string m_Username = ""; - std::string m_FirstName = ""; - std::string m_LastName = ""; - std::string m_Email = ""; - std::string m_Password = ""; - std::string m_Phone = ""; - int32_t m_UserStatus = 0; -}; - -std::vector createUserVectorFromJsonString(const std::string& json); - -} -} -} -} - -#endif /* User_H_ */ diff --git a/samples/server/petstore/cpp-restbed/pom.xml b/samples/server/petstore/cpp-restbed/pom.xml new file mode 100644 index 0000000000..9b496524c1 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + org.openapitools + CppRestbedServerTests + pom + 1.0-SNAPSHOT + C++ Restbed Petstore Server + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + build-and-run-restbed + integration-test + + exec + + + ./build_and_test.sh + + + + + + + diff --git a/samples/server/petstore/cpp-restbed/test/CMakeLists.txt b/samples/server/petstore/cpp-restbed/test/CMakeLists.txt new file mode 100644 index 0000000000..1de7e93ba4 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/CMakeLists.txt @@ -0,0 +1,4 @@ + +add_subdirectory(model_tests) +add_subdirectory(api_tests) +add_subdirectory(java_client_tests) \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/api_tests/CMakeLists.txt b/samples/server/petstore/cpp-restbed/test/api_tests/CMakeLists.txt new file mode 100644 index 0000000000..ec3493bf12 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/api_tests/CMakeLists.txt @@ -0,0 +1,23 @@ + +add_executable(api_tests) + +target_sources(api_tests + PRIVATE + main.cpp + store_api_test.cpp + beast_client.cpp +) + +target_include_directories(api_tests + SYSTEM PRIVATE + ${Boost_INCLUDE_DIRS} + #${restbed_SOURCE_DIR}/source +) + +target_link_libraries(api_tests + PRIVATE + ${Boost_LIBRARIES} + org.openapitools.server.apiStubs +) + +add_test(NAME api_tests COMMAND api_tests) diff --git a/samples/server/petstore/cpp-restbed/test/api_tests/beast_client.cpp b/samples/server/petstore/cpp-restbed/test/api_tests/beast_client.cpp new file mode 100644 index 0000000000..fdea3f1557 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/api_tests/beast_client.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "beast_client.h" + +namespace beast = boost::beast; // from +namespace http = beast::http; // from +namespace net = boost::asio; // from +using tcp = net::ip::tcp; // from + + +std::pair requestData(const http::verb verb, + const std::string& target, + const std::string& data) +{ + std::string out; + int status = 0; + + auto const host = "localhost"; + auto const port = "1234"; + int version = 11; + + net::io_context ioc; + + tcp::resolver resolver(ioc); + beast::tcp_stream stream(ioc); + + auto const results = resolver.resolve(host, port); + + stream.connect(results); + + http::request req{verb, target, version}; + req.set(http::field::host, host); + req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); + req.set(http::field::body, data); + + http::write(stream, req); + + beast::flat_buffer buffer; + http::response res; + http::read(stream, buffer, res); + out = boost::beast::buffers_to_string(res.body().data()); + status = static_cast(res.result()); + + beast::error_code ec; + stream.socket().shutdown(tcp::socket::shutdown_both, ec); + + if(ec && ec != beast::errc::not_connected) + throw beast::system_error{ec}; + + return std::make_pair(std::move(status), std::move(out)); +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/api_tests/beast_client.h b/samples/server/petstore/cpp-restbed/test/api_tests/beast_client.h new file mode 100644 index 0000000000..35909fd3da --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/api_tests/beast_client.h @@ -0,0 +1,7 @@ +#pragma once + +#include + +std::pair requestData(const boost::beast::http::verb verb, + const std::string& target, + const std::string& data = ""); diff --git a/samples/server/petstore/cpp-restbed/test/api_tests/main.cpp b/samples/server/petstore/cpp-restbed/test/api_tests/main.cpp new file mode 100644 index 0000000000..4af53a2ba3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/api_tests/main.cpp @@ -0,0 +1,4 @@ +#define BOOST_TEST_MODULE ModelTests + +//#include // static or dynamic boost build +#include // header only boost diff --git a/samples/server/petstore/cpp-restbed/test/api_tests/store_api_test.cpp b/samples/server/petstore/cpp-restbed/test/api_tests/store_api_test.cpp new file mode 100644 index 0000000000..9dac784639 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/api_tests/store_api_test.cpp @@ -0,0 +1,81 @@ +#define BOOST_TEST_INCLUDED + +#include +#include +#include +#include +#include +#include + +#include "api/StoreApi.h" + +#include "beast_client.h" + + +using namespace org::openapitools::server::model; +using namespace org::openapitools::server::api; + +class MyStoreApiStoreInventoryResource : public StoreApiResources::StoreInventoryResource { +public: + virtual std::pair> handler_GET() override { + std::map map; + map["Hello inventory"] = 23; + return std::make_pair(200, std::move(map)); + } + +}; + +std::string formatJson(const std::string& jsonString) { + boost::property_tree::ptree pt; + std::stringstream sstream(jsonString); + read_json(sstream,pt); + write_json(sstream, pt); + return sstream.str(); +} + +BOOST_AUTO_TEST_SUITE(StoreApiTest) + +BOOST_AUTO_TEST_CASE(startService) +{ + auto restbedService = std::make_shared(); + + auto storeApi = StoreApi(restbedService); + std::shared_ptr res = std::make_shared(); + storeApi.setResource(res); + + std::thread thread([&]{ + auto settings = std::make_shared(); + settings->set_port(1234); + restbedService->start(settings); + }); + thread.detach(); + + sleep(1); + + int status = 0; + std::string data; + + // localhost:1234/v2/store/inventory/ + auto response = requestData(boost::beast::http::verb::get, + "/v2/store/inventory/"); + status = response.first; + data = formatJson(response.second); + + const auto expectedJson = formatJson(R"JSON({"Hello inventory": "23"})JSON"); + BOOST_TEST(200 == status); + BOOST_TEST(expectedJson == data); + + // /store/order/{orderId: .*}/ + response = requestData(boost::beast::http::verb::get, + "/v2/store/order/3"); + + status = response.first; + data = response.second; + + BOOST_TEST(404 == status); + BOOST_TEST(data.empty()); + + restbedService->stop(); +} + +BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/CMakeLists.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/CMakeLists.txt new file mode 100644 index 0000000000..141e48c163 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(tests_servers) \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/.gitignore b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/.gitignore new file mode 100644 index 0000000000..ac96206f31 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/.gitignore @@ -0,0 +1 @@ +.gradle/ \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/build.gradle b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/build.gradle new file mode 100644 index 0000000000..ec2aff7519 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/build.gradle @@ -0,0 +1,51 @@ +plugins { + id 'org.springframework.boot' version '2.6.7' + id 'io.spring.dependency-management' version '1.0.11.RELEASE' + id 'java' + id "org.openapi.generator" version "5.4.0" +} + +group 'org.example' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() + mavenLocal() + maven { url "https://repo1.maven.org/maven2" } +} + +dependencies { + compile 'org.springframework.boot:spring-boot-starter-webflux' + implementation group: 'org.openapitools', name: 'jackson-databind-nullable', version: '0.2.2' + implementation group: 'io.swagger', name: 'swagger-annotations', version: '1.6.6' + implementation group: 'com.google.guava', name: 'guava', version: '31.1-jre' + + testImplementation('com.approvaltests:approvaltests:15.3.0') + testImplementation(platform('org.junit:junit-bom:5.8.2')) + testImplementation('org.junit.jupiter:junit-jupiter') + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' + +} + +test { + useJUnitPlatform() +} + + +compileJava.dependsOn tasks.openApiGenerate + +openApiGenerate { + generatorName = "java" + inputSpec = "$rootDir/../../../../../../../modules/openapi-generator/src/test/resources/3_0/petstore.yaml".toString() + outputDir = "$buildDir/generated".toString() + apiPackage = "org.openapi.example.api" + invokerPackage = "org.openapi.example.invoker" + modelPackage = "org.openapi.example.model" + configOptions = [ + dateLibrary: "java8", + library: "webclient" + ] +} + +sourceSets.main.java.srcDirs += "$buildDir/generated/src/main/java".toString() diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradle/wrapper/gradle-wrapper.jar b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..e708b1c023 Binary files /dev/null and b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/openapi3/client/petstore/java/native/gradle/wrapper/gradle-wrapper.properties b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradle/wrapper/gradle-wrapper.properties similarity index 93% rename from samples/openapi3/client/petstore/java/native/gradle/wrapper/gradle-wrapper.properties rename to samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradle/wrapper/gradle-wrapper.properties index ffed3a254e..da9702f9e7 100644 --- a/samples/openapi3/client/petstore/java/native/gradle/wrapper/gradle-wrapper.properties +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradlew b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradlew new file mode 100755 index 0000000000..4f906e0c81 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/samples/openapi3/client/petstore/java/native/gradlew.bat b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradlew.bat similarity index 100% rename from samples/openapi3/client/petstore/java/native/gradlew.bat rename to samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/gradlew.bat diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/settings.gradle b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/settings.gradle new file mode 100644 index 0000000000..af83dec850 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'java_client_for_tests' + diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/helper/ApiClientFactories.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/helper/ApiClientFactories.java new file mode 100644 index 0000000000..7af90cbf9e --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/helper/ApiClientFactories.java @@ -0,0 +1,25 @@ +package helper; + +import org.openapi.example.api.PetApi; +import org.openapi.example.api.StoreApi; +import org.openapi.example.api.UserApi; +import org.openapi.example.invoker.ApiClient; + +public class ApiClientFactories { + public static PetApi setUpPetApi(int port) { + return new PetApi(setUpDefaultApiClient(port)); + } + + public static StoreApi setUpStoreApi(int port) { + return new StoreApi(setUpDefaultApiClient(port)); + } + public static UserApi setUpUserApi(int port) { + return new UserApi(setUpDefaultApiClient(port)); + } + + private static ApiClient setUpDefaultApiClient(int port) { + ApiClient defaultClient = new ApiClient(); + defaultClient.setBasePath("http://localhost:" + String.valueOf(port) + "/v2"); + return defaultClient; + } +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/helper/StripTrailingWhitespaceScrubber.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/helper/StripTrailingWhitespaceScrubber.java new file mode 100644 index 0000000000..14e32987ba --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/helper/StripTrailingWhitespaceScrubber.java @@ -0,0 +1,12 @@ +package helper; + +import org.approvaltests.core.Scrubber; + +class StripTrailingWhitespaceScrubber implements Scrubber { + + @Override + public String scrub(String input) { + String replaced = input.replaceAll("\\s+\n", "\n"); + return replaced.trim(); + } +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/helper/TestingHelper.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/helper/TestingHelper.java new file mode 100644 index 0000000000..e5a649fe6d --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/helper/TestingHelper.java @@ -0,0 +1,69 @@ +package helper; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.approvaltests.Approvals; +import org.approvaltests.core.Options; +import org.springframework.web.reactive.function.client.WebClientRequestException; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +import java.text.SimpleDateFormat; + +public class TestingHelper { + + private static Options removeTrailingSpaces = new Options(new StripTrailingWhitespaceScrubber()); + + public static void approveException(WebClientResponseException exception) { + String message = "Status code: " + exception.getStatusCode() + + "\nReason: " + exception.getResponseBodyAsString() + + "\nResponse headers: " + exception.getHeaders(); + Approvals.verify(message, removeTrailingSpaces); + } + + public static void approveException(WebClientRequestException exception) { + String message = "URI: " + exception.getUri() + + "\nMethod: " + exception.getMethod () + + "\nHeaders: " + exception.getHeaders() + + "\nMessage: " + exception.getMessage(); + Approvals.verify(message, removeTrailingSpaces); + } + + public static void approveResponseAsJson(Object reponseObject) { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + objectMapper.setDateFormat(new StdDateFormat()); + objectMapper.setConfig(objectMapper.getSerializationConfig() + .with(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY) + .with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)); + + String json = ""; + + try { + json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(reponseObject); + } catch (JsonProcessingException e) { + json = e.toString(); + } + Approvals.verify(json, removeTrailingSpaces); + } + + + public static long errorRaisingStringToInt(String errorRisingString) { + if (errorRisingString.equals("ThrowsApiException")) { + return 9100; + } + else if (errorRisingString.equals("ThrowsStdExceptionDerivedException")) { + return 9200; + } + else if (errorRisingString.equals("ThrowsInt")) { + return 9300; + } + + String status = errorRisingString.replace("ReturnsStatus", ""); + + return Integer.parseInt(status); + } +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/PackageSettings.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/PackageSettings.java new file mode 100644 index 0000000000..66720b89e6 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/PackageSettings.java @@ -0,0 +1,8 @@ +package test_default_unimplemented_server_stubs; + +import org.approvaltests.reporters.linux.MeldMergeReporter; + +public class PackageSettings { + public static String UseApprovalSubdirectory = "approval_files"; + public static MeldMergeReporter UseReporter = MeldMergeReporter.INSTANCE; +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/PetApiTest.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/PetApiTest.java new file mode 100644 index 0000000000..48309ef556 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/PetApiTest.java @@ -0,0 +1,65 @@ +package test_default_unimplemented_server_stubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapi.example.api.PetApi; +import org.openapi.example.model.Pet; +import org.springframework.web.reactive.function.client.WebClientResponseException; + + +import static helper.ApiClientFactories.setUpPetApi; +import static helper.TestingHelper.approveException; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class PetApiTest { + + PetApi apiInstance; + + @BeforeEach + void setUp() { + apiInstance = setUpPetApi(1234); + } + + @Test + void addPet() { + Pet pet = new Pet(); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.addPet(pet).block(); + }); + + approveException(exception); + } + + @Test + void deletePet() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deletePet(99L, "myApiKey").block(); + }); + + approveException(exception); + } + + @Test + void getPetById() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getPetById(9L).block(); + }); + + approveException(exception); + } + + @Test + void updatePet() { + Pet pet = new Pet(); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.updatePet(pet).block(); + }); + + approveException(exception); + } + +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/StoreApiTest.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/StoreApiTest.java new file mode 100644 index 0000000000..ba25d24063 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/StoreApiTest.java @@ -0,0 +1,63 @@ +package test_default_unimplemented_server_stubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapi.example.api.StoreApi; +import org.openapi.example.model.Order; +import org.openapi.example.invoker.ApiClient; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +import static helper.ApiClientFactories.setUpStoreApi; +import static org.junit.jupiter.api.Assertions.*; +import static helper.TestingHelper.approveException; + +class StoreApiTest { + + StoreApi apiInstance; + + @BeforeEach + void setUp() { + apiInstance = setUpStoreApi(1234); + } + + @Test + void deleteOrder() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deleteOrder("myOrderId").block(); + }); + + approveException(exception); + } + + @Test + void getInventory() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getInventory().block(); + }); + + approveException(exception); + } + + @Test + void getOrderById() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getOrderById(1L).block(); + }); + + approveException(exception); + } + + @Test + void placeOrder() { + Order order = new Order(); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.placeOrder(order).block(); + }); + + approveException(exception); + } +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/UserApiTest.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/UserApiTest.java new file mode 100644 index 0000000000..56a37c5737 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/UserApiTest.java @@ -0,0 +1,75 @@ +package test_default_unimplemented_server_stubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapi.example.api.UserApi; +import org.openapi.example.model.User; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +import java.util.Arrays; + +import static helper.ApiClientFactories.setUpUserApi; +import static org.junit.jupiter.api.Assertions.*; +import static helper.TestingHelper.approveException; + +class UserApiTest { + + UserApi apiInstance; + + @BeforeEach + void setUp() { + apiInstance = setUpUserApi(1234); + } + + @Test + void createUser() { + User user = new User(); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUser(user).block(); + }); + + approveException(exception); + } + + @Test + void createUsersWithArrayInput() { + User user = new User(); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithArrayInput(Arrays.asList(user)).block(); + }); + + approveException(exception); + } + + @Test + void createUsersWithListInput() { + User user = new User(); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithListInput(Arrays.asList(user)).block(); + }); + approveException(exception); + } + + @Test + void loginUser() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.loginUser("my name", "my password").block(); + }); + + approveException(exception); + } + + @Test + void logoutUser() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.logoutUser().block(); + }); + + approveException(exception); + } +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.addPet.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.addPet.approved.txt new file mode 100644 index 0000000000..4345dec9ee --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.addPet.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Value null not allowed +Response headers: [Content-Type:"text/plain", content-length:"22"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.deletePet.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.deletePet.approved.txt new file mode 100644 index 0000000000..00d009312a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.deletePet.approved.txt @@ -0,0 +1,3 @@ +Status code: 501 NOT_IMPLEMENTED +Reason: Not implemented +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.getPetById.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.getPetById.approved.txt new file mode 100644 index 0000000000..00d009312a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.getPetById.approved.txt @@ -0,0 +1,3 @@ +Status code: 501 NOT_IMPLEMENTED +Reason: Not implemented +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.updatePet.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.updatePet.approved.txt new file mode 100644 index 0000000000..4345dec9ee --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/PetApiTest.updatePet.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Value null not allowed +Response headers: [Content-Type:"text/plain", content-length:"22"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.deleteOrder.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.deleteOrder.approved.txt new file mode 100644 index 0000000000..00d009312a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.deleteOrder.approved.txt @@ -0,0 +1,3 @@ +Status code: 501 NOT_IMPLEMENTED +Reason: Not implemented +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.getInventory.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.getInventory.approved.txt new file mode 100644 index 0000000000..00d009312a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.getInventory.approved.txt @@ -0,0 +1,3 @@ +Status code: 501 NOT_IMPLEMENTED +Reason: Not implemented +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.getOrderById.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.getOrderById.approved.txt new file mode 100644 index 0000000000..00d009312a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.getOrderById.approved.txt @@ -0,0 +1,3 @@ +Status code: 501 NOT_IMPLEMENTED +Reason: Not implemented +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.placeOrder.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.placeOrder.approved.txt new file mode 100644 index 0000000000..4345dec9ee --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/StoreApiTest.placeOrder.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Value null not allowed +Response headers: [Content-Type:"text/plain", content-length:"22"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.createUser.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.createUser.approved.txt new file mode 100644 index 0000000000..00d009312a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.createUser.approved.txt @@ -0,0 +1,3 @@ +Status code: 501 NOT_IMPLEMENTED +Reason: Not implemented +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.createUsersWithArrayInput.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.createUsersWithArrayInput.approved.txt new file mode 100644 index 0000000000..3ec1930af2 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.createUsersWithArrayInput.approved.txt @@ -0,0 +1,3 @@ +Status code: 405 METHOD_NOT_ALLOWED +Reason: +Response headers: [] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.createUsersWithListInput.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.createUsersWithListInput.approved.txt new file mode 100644 index 0000000000..3ec1930af2 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.createUsersWithListInput.approved.txt @@ -0,0 +1,3 @@ +Status code: 405 METHOD_NOT_ALLOWED +Reason: +Response headers: [] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.loginUser.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.loginUser.approved.txt new file mode 100644 index 0000000000..00d009312a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.loginUser.approved.txt @@ -0,0 +1,3 @@ +Status code: 501 NOT_IMPLEMENTED +Reason: Not implemented +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.logoutUser.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.logoutUser.approved.txt new file mode 100644 index 0000000000..00d009312a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_default_unimplemented_server_stubs/approval_files/UserApiTest.logoutUser.approved.txt @@ -0,0 +1,3 @@ +Status code: 501 NOT_IMPLEMENTED +Reason: Not implemented +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/PackageSettings.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/PackageSettings.java new file mode 100644 index 0000000000..be75667bc0 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/PackageSettings.java @@ -0,0 +1,8 @@ +package test_error_handling_server_stubs; + +import org.approvaltests.reporters.linux.MeldMergeReporter; + +public class PackageSettings { + public static String UseApprovalSubdirectory = "approval_files"; + public static MeldMergeReporter UseReporter = MeldMergeReporter.INSTANCE; +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/PetApiTest.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/PetApiTest.java new file mode 100644 index 0000000000..abc320cd76 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/PetApiTest.java @@ -0,0 +1,274 @@ +package test_error_handling_server_stubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapi.example.api.PetApi; +import org.openapi.example.model.Pet; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +import static helper.ApiClientFactories.setUpPetApi; +import static helper.TestingHelper.*; +import static org.junit.jupiter.api.Assertions.*; + +class PetApiTest { + + PetApi apiInstance; + + @BeforeEach + void setUp() { + apiInstance = setUpPetApi(1236); + } + + @Test + void addPetInvalidEnumValue() { + Pet pet = new Pet(); + pet.name("PetWithInvalidStatus"); + pet.status(null); // not allowed + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.addPet(pet).block(); + }); + approveException(exception); + } + + @Test + void addPetThatThrowsApiException() { + Pet pet = new Pet(); + pet.name("ThrowsApiException"); + pet.status(Pet.StatusEnum.SOLD); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.addPet(pet).block(); + }); + approveException(exception); + } + + @Test + void addPetThatThrowsStdExceptionDerivedException() { + Pet pet = new Pet(); + pet.name("ThrowsStdExceptionDerivedException"); + pet.status(Pet.StatusEnum.AVAILABLE); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.addPet(pet).block(); + }); + approveException(exception); + } + + @Test + void addPetThatThrowsInt() { + Pet pet = new Pet(); + pet.name("ThrowsInt"); + pet.status(Pet.StatusEnum.AVAILABLE); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.addPet(pet).block(); + }); + + approveException(exception); + } + + @Test + void addPetThatReturnsStatus200() { + Pet pet = new Pet(); + pet.name("ReturnsStatus200"); + pet.status(Pet.StatusEnum.AVAILABLE); + apiInstance.addPet(pet).block(); + } + + @Test + void addPetThatReturnsStatus405() { + Pet pet = new Pet(); + pet.name("ReturnsStatus405"); + pet.status(Pet.StatusEnum.AVAILABLE); + + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.addPet(pet).block(); + }); + + approveException(exception); + } + + @Test + void deletePetThrowsApiException() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deletePet(1342L, "ThrowsApiException").block(); + }); + approveException(exception); + } + + @Test + void deletePetThrowsStdExceptionDerivedException() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deletePet(1342L, "ThrowsStdExceptionDerivedException").block(); + }); + approveException(exception); + } + + @Test + void deletePetThrowsInt() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deletePet(1342L, "ThrowsInt").block(); + }); + approveException(exception); + } + + @Test + void deletePetReturnsStatus200() { + apiInstance.deletePet(1342L, "ReturnsStatus200").block(); + } + + @Test + void deletePetReturnsStatus400() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deletePet(1342L, "ReturnsStatus400").block(); + }); + approveException(exception); + } + + @Test + void deletePetReturnsStatus300() { + apiInstance.deletePet(1342L, "ReturnsStatus300").block(); + } + + @Test + void getPetByIdThrowsApiException() { + long id = errorRaisingStringToInt("ThrowsApiException"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getPetById(id).block(); + }); + approveException(exception); + } + + @Test + void getPetByIdThrowsStdExceptionDerivedException() { + long id = errorRaisingStringToInt("ThrowsStdExceptionDerivedException"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getPetById(id).block(); + }); + approveException(exception); + } + + @Test + void getPetByIdThrowsInt() { + long id = errorRaisingStringToInt("ThrowsInt"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getPetById(id).block(); + }); + approveException(exception); + } + + @Test + void getPetByIdReturnsStatus200() { + long id = errorRaisingStringToInt("ReturnsStatus200"); + Pet pet = apiInstance.getPetById(id).block(); + approveResponseAsJson(pet); + } + + @Test + void getPetByIdReturnsStatus300() { + long id = errorRaisingStringToInt("ReturnsStatus300"); + Pet pet = apiInstance.getPetById(id).block(); + assertNull(pet); + } + + @Test + void getPetByIdReturnsStatus400() { + long id = errorRaisingStringToInt("ReturnsStatus400"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getPetById(id).block(); + }); + approveException(exception); + } + + @Test + void getPetByIdReturnsStatus404() { + long id = errorRaisingStringToInt("ReturnsStatus404"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getPetById(id).block(); + }); + approveException(exception); + } + + @Test + void updatePetThrowsApiException() { + Pet pet = new Pet(); + pet.name("ThrowsApiException"); + pet.status(Pet.StatusEnum.SOLD); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.updatePet(pet).block(); + }); + approveException(exception); + } + + @Test + void updatePetThrowsStdExceptionDerivedException() { + Pet pet = new Pet(); + pet.name("ThrowsStdExceptionDerivedException"); + pet.status(Pet.StatusEnum.SOLD); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.updatePet(pet).block(); + }); + approveException(exception); + } + + @Test + void updatePetThrowsInt() { + Pet pet = new Pet(); + pet.name("ThrowsInt"); + pet.status(Pet.StatusEnum.SOLD); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.updatePet(pet).block(); + }); + approveException(exception); + } + + + @Test + void updatePetReturnsStatus400() { + Pet pet = new Pet(); + pet.name("ReturnsStatus400"); + pet.status(Pet.StatusEnum.SOLD); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.updatePet(pet).block(); + }); + approveException(exception); + } + + @Test + void updatePetReturnsStatus405() { + Pet pet = new Pet(); + pet.name("ReturnsStatus405"); + pet.status(Pet.StatusEnum.SOLD); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.updatePet(pet).block(); + }); + approveException(exception); + } + @Test + void updatePetReturnsStatus500() { + Pet pet = new Pet(); + pet.name("ReturnsStatus500"); + pet.status(Pet.StatusEnum.SOLD); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.updatePet(pet).block(); + }); + approveException(exception); + } +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/StoreApiTest.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/StoreApiTest.java new file mode 100644 index 0000000000..b0c6f66515 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/StoreApiTest.java @@ -0,0 +1,232 @@ +package test_error_handling_server_stubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapi.example.api.StoreApi; +import org.openapi.example.model.Order; +import org.springframework.core.codec.DecodingException; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +import java.util.Map; + +import static helper.ApiClientFactories.setUpStoreApi; +import static helper.TestingHelper.*; +import static org.junit.jupiter.api.Assertions.*; + +class StoreApiTest { + + StoreApi apiInstance; + + @BeforeEach + void setUp() { + apiInstance = setUpStoreApi(1236); + } + + @Test + void deleteOrderThrowsApiException() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deleteOrder("ThrowsApiException").block(); + }); + approveException(exception); + } + + @Test + void deleteOrderThrowsStdExceptionDerivedException() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deleteOrder("ThrowsStdExceptionDerivedException").block(); + }); + approveException(exception); + } + + @Test + void deleteOrderThrowsInt() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deleteOrder("ThrowsInt").block(); + }); + approveException(exception); + } + + @Test + void deleteOrderReturnsStatus200() { + apiInstance.deleteOrder("ReturnsStatus200").block(); + } + + @Test + void deleteOrderReturnsStatus400() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deleteOrder("ReturnsStatus400").block(); + }); + + approveException(exception); + } + + @Test + void deleteOrderReturnsStatus404() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deleteOrder("ReturnsStatus404").block(); + }); + + approveException(exception); + } + @Test + void deleteOrderReturnsStatus405() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.deleteOrder("ReturnsStatus405").block(); + }); + + approveException(exception); + } + + @Test + void getInventory() { + Map ret = apiInstance.getInventory().block(); + assertNull(ret); + } + + @Test + void getOrderByIdThrowsApiException() { + long id = errorRaisingStringToInt("ThrowsApiException"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getOrderById(id).block(); + }); + approveException(exception); + } + + @Test + void getOrderByIdThrowsStdExceptionDerivedException() { + long id = errorRaisingStringToInt("ThrowsStdExceptionDerivedException"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getOrderById(id).block(); + }); + approveException(exception); + } + + @Test + void getOrderByIdThrowsInt() { + long id = errorRaisingStringToInt("ThrowsInt"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getOrderById(id).block(); + }); + approveException(exception); + } + + @Test + void getOrderByIdReturnsStatus200WithInvalidEnumValue() { + long id = errorRaisingStringToInt("ReturnsStatus200"); + DecodingException exception = assertThrows(DecodingException.class, () -> { + apiInstance.getOrderById(id).block(); + }); + } + + @Test + void getOrderByIdReturnsStatus300() { + long id = errorRaisingStringToInt("ReturnsStatus300"); + Order resp = apiInstance.getOrderById(id).block(); + assertNull(resp); + } + + @Test + void getOrderByIdReturnsStatus400() { + long id = errorRaisingStringToInt("ReturnsStatus400"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getOrderById(id).block(); + }); + approveException(exception); + } + + @Test + void getOrderByIdReturnsStatus404() { + long id = errorRaisingStringToInt("ReturnsStatus404"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.getOrderById(id).block(); + }); + approveException(exception); + } + + @Test + void placeOrderThrowsApiException() { + long id = errorRaisingStringToInt("ThrowsApiException"); + + Order order = new Order(); + order.setId(id); + order.setStatus(Order.StatusEnum.PLACED); + + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.placeOrder(order).block(); + }); + approveException(exception); + + } + + @Test + void placeOrderThrowsStdExceptionDerivedException() { + long id = errorRaisingStringToInt("ThrowsStdExceptionDerivedException"); + + Order order = new Order(); + order.setId(id); + order.setStatus(Order.StatusEnum.PLACED); + + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.placeOrder(order).block(); + }); + approveException(exception); + + } + + @Test + void placeOrderThrowsInt() { + long id = errorRaisingStringToInt("ThrowsInt"); + + Order order = new Order(); + order.setId(id); + order.setStatus(Order.StatusEnum.PLACED); + + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.placeOrder(order).block(); + }); + approveException(exception); + + } + + @Test + void placeOrderReturnsStatus300() { + long id = errorRaisingStringToInt("ReturnsStatus300"); + + Order order = new Order(); + order.setId(id); + order.setStatus(Order.StatusEnum.PLACED); + + Order resp = apiInstance.placeOrder(order).block(); + + assertNull(resp); + } + + @Test + void placeOrderReturnsStatus400() { + long id = errorRaisingStringToInt("ReturnsStatus400"); + + Order order = new Order(); + order.setId(id); + order.setStatus(Order.StatusEnum.PLACED); + + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.placeOrder(order).block(); + }); + approveException(exception); + } +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/UserApiTest.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/UserApiTest.java new file mode 100644 index 0000000000..7815b8e864 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/UserApiTest.java @@ -0,0 +1,303 @@ +package test_error_handling_server_stubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapi.example.api.UserApi; +import org.openapi.example.model.User; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +import java.util.ArrayList; +import java.util.List; + +import static helper.ApiClientFactories.setUpUserApi; +import static helper.TestingHelper.approveException; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class UserApiTest { + + UserApi apiInstance; + + @BeforeEach + void setUp() { + apiInstance = setUpUserApi(1236); + } + + @Test + void createUserThrowsApiException() { + User user = new User(); + user.setFirstName("ThrowsApiException"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUser(user).block(); + }); + approveException(exception); + } + + @Test + void createUserThrowsStdExceptionDerivedException() { + User user = new User(); + user.setFirstName("ThrowsStdExceptionDerivedException"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUser(user).block(); + }); + approveException(exception); + } + + @Test + void createUserThrowsInt() { + User user = new User(); + user.setFirstName("ThrowsInt"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUser(user).block(); + }); + approveException(exception); + } + + @Test + void createUserReturnsStatus0() { + User user = new User(); + user.setFirstName("ReturnsStatus0"); + + apiInstance.createUser(user).block(); + } + + + @Test + void createUserReturnsStatus400() { + User user = new User(); + user.setFirstName("ReturnsStatus400"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUser(user).block(); + }); + approveException(exception); + } + + @Test + void createUserReturnsStatus500() { + User user = new User(); + user.setFirstName("ReturnsStatus500"); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUser(user).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithArrayInputThrowsApiException() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ThrowsApiException"); + users.add(user); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithArrayInput(users).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithArrayInputThrowsStdExceptionDerivedException() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ThrowsStdExceptionDerivedException"); + users.add(user); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithArrayInput(users).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithArrayInputThrowsInt() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ThrowsInt"); + users.add(user); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithArrayInput(users).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithArrayInputReturnsStatus0() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ReturnsStatus0"); + users.add(user); + + apiInstance.createUsersWithArrayInput(users).block(); + } + + @Test + void createUsersWithArrayInputReturnsStatus400() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ReturnsStatus400"); + users.add(user); + + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithArrayInput(users).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithArrayInputReturnsStatus500() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ReturnsStatus500"); + users.add(user); + + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithArrayInput(users).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithListInputThrowsApiException() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ThrowsApiException"); + users.add(user); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithListInput(users).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithListInputThrowsStdExceptionDerivedException() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ThrowsStdExceptionDerivedException"); + users.add(user); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithListInput(users).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithListInputThrowsInt() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ThrowsInt"); + users.add(user); + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithListInput(users).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithListInputReturnsStatus0() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ReturnsStatus0"); + users.add(user); + + apiInstance.createUsersWithListInput(users).block(); + } + + @Test + void createUsersWithListInputReturnsStatus400() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ReturnsStatus400"); + users.add(user); + + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithListInput(users).block(); + }); + approveException(exception); + } + + @Test + void createUsersWithListInputReturnsStatus500() { + List users = new ArrayList<>(); + User user = new User(); + user.setFirstName("ReturnsStatus500"); + users.add(user); + + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.createUsersWithListInput(users).block(); + }); + approveException(exception); + } + + @Test + void loginUserThrowsApiException() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.loginUser("ThrowsApiException", "mypassword").block(); + }); + approveException(exception); + } + + @Test + void loginUserThrowsStdExceptionDerivedException() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.loginUser("ThrowsStdExceptionDerivedException", "mypassword").block(); + }); + approveException(exception); + } + + @Test + void loginUserThrowsInt() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.loginUser("ThrowsInt", "mypassword").block(); + }); + approveException(exception); + } + + @Test + void loginUserReturnsStatus200() { + String resp = apiInstance.loginUser("ReturnsStatus200", "mypassword").block(); + assertEquals("ReturnsStatus200", resp); + } + + @Test + void loginUserReturnsStatus400() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.loginUser("ReturnsStatus400", "mypassword").block(); + }); + approveException(exception); + } + + @Test + void loginUserReturnsStatus500() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.loginUser("ReturnsStatus500", "mypassword").block(); + }); + approveException(exception); + } + + @Test + void logoutUser() { + WebClientResponseException exception = assertThrows( + WebClientResponseException.class, () -> { + apiInstance.logoutUser().block(); + }); + approveException(exception); + } +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetInvalidEnumValue.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetInvalidEnumValue.approved.txt new file mode 100644 index 0000000000..4345dec9ee --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetInvalidEnumValue.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Value null not allowed +Response headers: [Content-Type:"text/plain", content-length:"22"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatReturnsStatus405.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatReturnsStatus405.approved.txt new file mode 100644 index 0000000000..0d8b7af92b --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatReturnsStatus405.approved.txt @@ -0,0 +1,3 @@ +Status code: 405 METHOD_NOT_ALLOWED +Reason: Invalid input +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatThrowsStdExceptionDerivedException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatThrowsStdExceptionDerivedException.approved.txt new file mode 100644 index 0000000000..bc8d2c1aeb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.addPetThatThrowsStdExceptionDerivedException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: std::logic_error raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetReturnsStatus400.approved.txt new file mode 100644 index 0000000000..9ccdd07a3c --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Invalid pet value +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetThrowsStdExceptionDerivedException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetThrowsStdExceptionDerivedException.approved.txt new file mode 100644 index 0000000000..bc8d2c1aeb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.deletePetThrowsStdExceptionDerivedException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: std::logic_error raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdReturnsStatus200.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdReturnsStatus200.approved.txt new file mode 100644 index 0000000000..c03269b46b --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdReturnsStatus200.approved.txt @@ -0,0 +1,11 @@ +{ + "id" : 0, + "category" : { + "id" : 0, + "name" : "default-name" + }, + "name" : "MyPuppy", + "photoUrls" : [ ], + "tags" : null, + "status" : "available" +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdReturnsStatus400.approved.txt new file mode 100644 index 0000000000..59421a5e44 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Invalid ID supplied +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdReturnsStatus404.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdReturnsStatus404.approved.txt new file mode 100644 index 0000000000..98f77ecd9a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdReturnsStatus404.approved.txt @@ -0,0 +1,3 @@ +Status code: 404 NOT_FOUND +Reason: Pet not found +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdThrowsStdExceptionDerivedException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdThrowsStdExceptionDerivedException.approved.txt new file mode 100644 index 0000000000..bc8d2c1aeb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.getPetByIdThrowsStdExceptionDerivedException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: std::logic_error raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetReturnsStatus400.approved.txt new file mode 100644 index 0000000000..59421a5e44 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Invalid ID supplied +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetReturnsStatus405.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetReturnsStatus405.approved.txt new file mode 100644 index 0000000000..7eb5d3588f --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetReturnsStatus405.approved.txt @@ -0,0 +1,3 @@ +Status code: 405 METHOD_NOT_ALLOWED +Reason: Validation exception +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetReturnsStatus500.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetReturnsStatus500.approved.txt new file mode 100644 index 0000000000..8e19ce4591 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetReturnsStatus500.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetThrowsStdExceptionDerivedException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetThrowsStdExceptionDerivedException.approved.txt new file mode 100644 index 0000000000..bc8d2c1aeb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/PetApiTest.updatePetThrowsStdExceptionDerivedException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: std::logic_error raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderReturnsStatus400.approved.txt new file mode 100644 index 0000000000..59421a5e44 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Invalid ID supplied +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderReturnsStatus404.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderReturnsStatus404.approved.txt new file mode 100644 index 0000000000..d905f316fb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderReturnsStatus404.approved.txt @@ -0,0 +1,3 @@ +Status code: 404 NOT_FOUND +Reason: Order not found +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderReturnsStatus405.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderReturnsStatus405.approved.txt new file mode 100644 index 0000000000..4b8f7d15f1 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderReturnsStatus405.approved.txt @@ -0,0 +1,3 @@ +Status code: 405 METHOD_NOT_ALLOWED +Reason: +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderThrowsStdExceptionDerivedException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderThrowsStdExceptionDerivedException.approved.txt new file mode 100644 index 0000000000..bc8d2c1aeb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.deleteOrderThrowsStdExceptionDerivedException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: std::logic_error raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdReturnsStatus400.approved.txt new file mode 100644 index 0000000000..59421a5e44 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Invalid ID supplied +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdReturnsStatus404.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdReturnsStatus404.approved.txt new file mode 100644 index 0000000000..d905f316fb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdReturnsStatus404.approved.txt @@ -0,0 +1,3 @@ +Status code: 404 NOT_FOUND +Reason: Order not found +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdThrowsStdExceptionDerivedException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdThrowsStdExceptionDerivedException.approved.txt new file mode 100644 index 0000000000..bc8d2c1aeb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.getOrderByIdThrowsStdExceptionDerivedException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: std::logic_error raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderReturnsStatus400.approved.txt new file mode 100644 index 0000000000..d951d2bf99 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Invalid Order +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderThrowsStdExceptionDerivedException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderThrowsStdExceptionDerivedException.approved.txt new file mode 100644 index 0000000000..bc8d2c1aeb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/StoreApiTest.placeOrderThrowsStdExceptionDerivedException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: std::logic_error raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserReturnsStatus400.approved.txt new file mode 100644 index 0000000000..32ade16b26 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserReturnsStatus500.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserReturnsStatus500.approved.txt new file mode 100644 index 0000000000..8e19ce4591 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserReturnsStatus500.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserThrowsStdExceptionDerivedException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserThrowsStdExceptionDerivedException.approved.txt new file mode 100644 index 0000000000..bc8d2c1aeb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUserThrowsStdExceptionDerivedException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: std::logic_error raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputReturnsStatus400.approved.txt new file mode 100644 index 0000000000..32ade16b26 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputReturnsStatus500.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputReturnsStatus500.approved.txt new file mode 100644 index 0000000000..8e19ce4591 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputReturnsStatus500.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithArrayInputThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputReturnsStatus400.approved.txt new file mode 100644 index 0000000000..32ade16b26 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputReturnsStatus500.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputReturnsStatus500.approved.txt new file mode 100644 index 0000000000..8e19ce4591 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputReturnsStatus500.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.createUsersWithListInputThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserReturnsStatus400.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserReturnsStatus400.approved.txt new file mode 100644 index 0000000000..534bb97a39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserReturnsStatus400.approved.txt @@ -0,0 +1,3 @@ +Status code: 400 BAD_REQUEST +Reason: Invalid username/password supplied +Response headers: [Connection:"close", Content-Type:"text/plain"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserReturnsStatus500.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserReturnsStatus500.approved.txt new file mode 100644 index 0000000000..8e19ce4591 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserReturnsStatus500.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserThrowsApiException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserThrowsApiException.approved.txt new file mode 100644 index 0000000000..00656c64e9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserThrowsApiException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: ApiException raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserThrowsInt.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserThrowsInt.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserThrowsInt.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserThrowsStdExceptionDerivedException.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserThrowsStdExceptionDerivedException.approved.txt new file mode 100644 index 0000000000..bc8d2c1aeb --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.loginUserThrowsStdExceptionDerivedException.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: std::logic_error raised +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.logoutUser.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.logoutUser.approved.txt new file mode 100644 index 0000000000..5f4c01af39 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_error_handling_server_stubs/approval_files/UserApiTest.logoutUser.approved.txt @@ -0,0 +1,3 @@ +Status code: 500 INTERNAL_SERVER_ERROR +Reason: Unknown exception occurred +Response headers: [Connection:"close"] \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/PackageSettings.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/PackageSettings.java new file mode 100644 index 0000000000..f5ccf2b2b3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/PackageSettings.java @@ -0,0 +1,8 @@ +package test_simple_server_stubs; + +import org.approvaltests.reporters.linux.MeldMergeReporter; + +public class PackageSettings { + public static String UseApprovalSubdirectory = "approval_files"; + public static MeldMergeReporter UseReporter = MeldMergeReporter.INSTANCE; +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/PetApiTest.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/PetApiTest.java new file mode 100644 index 0000000000..e7d3fe4ad7 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/PetApiTest.java @@ -0,0 +1,67 @@ +package test_simple_server_stubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapi.example.api.PetApi; +import org.openapi.example.model.Category; +import org.openapi.example.model.Pet; +import org.openapi.example.model.Tag; +import java.util.List; + +import static helper.ApiClientFactories.setUpPetApi; +import static helper.TestingHelper.approveResponseAsJson; + +class PetApiTest { + + PetApi apiInstance; + + @BeforeEach + void setUp() { + apiInstance = setUpPetApi(1235); + } + + @Test + void addPet() { + Pet pet = createTestPet(); + Pet responsePet = apiInstance.addPet(pet).block(); + approveResponseAsJson(responsePet); + } + + @Test + void deletePet() { + apiInstance.deletePet(1L, "myApiKey").block(); + } + + @Test + void getPetById() { + Pet responsePet = apiInstance.getPetById(99L).block(); + approveResponseAsJson(responsePet); + } + + @Test + void updatePet() { + Pet pet = createTestPet(); + apiInstance.updatePet(pet).block(); + } + + private Pet createTestPet() { + Pet pet = new Pet(); + + pet.setId(12L); + pet.setName("MyPet"); + pet.setStatus(Pet.StatusEnum.SOLD); + + Tag tag = new Tag(); + tag.name("MyTag"); + pet.addTagsItem(tag); + + Category category = new Category(); + category.setId(1L); + category.setName("MyCategory"); + pet.setCategory(category); + + pet.addPhotoUrlsItem("myUrl"); + + return pet; + } +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/StoreApiTest.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/StoreApiTest.java new file mode 100644 index 0000000000..2a17d9aeae --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/StoreApiTest.java @@ -0,0 +1,48 @@ +package test_simple_server_stubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapi.example.api.StoreApi; +import org.openapi.example.model.Order; + +import java.util.Map; + +import static helper.ApiClientFactories.setUpStoreApi; +import static helper.TestingHelper.approveResponseAsJson; +import static org.junit.jupiter.api.Assertions.*; + +class StoreApiTest { + + StoreApi apiInstance; + + @BeforeEach + void setUp() { + apiInstance = setUpStoreApi(1235); + } + + @Test + void deleteOrder() { + apiInstance.deleteOrder("myOrderId").block(); + } + + @Test + void getInventory() { + Map inventory = apiInstance.getInventory().block(); + approveResponseAsJson(inventory); + } + + @Test + void getOrderById() { + Order order = apiInstance.getOrderById(123L).block(); + approveResponseAsJson(order); + } + + @Test + void placeOrder() { + Order order = new Order(); + order.setId(9876L); + order.setStatus(Order.StatusEnum.PLACED); + Order response = apiInstance.placeOrder(order).block(); + approveResponseAsJson(response); + } +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/UserApiTest.java b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/UserApiTest.java new file mode 100644 index 0000000000..7479a5966b --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/UserApiTest.java @@ -0,0 +1,68 @@ +package test_simple_server_stubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapi.example.api.UserApi; +import org.openapi.example.model.User; + +import java.util.ArrayList; +import java.util.List; + +import static helper.ApiClientFactories.setUpUserApi; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class UserApiTest { + + UserApi apiInstance; + + @BeforeEach + void setUp() { + apiInstance = setUpUserApi(1235); + } + + @Test + void createUser() { + User user = new User(); + apiInstance.createUser(user).block(); + } + + @Test + void createUsersWithArrayInput() { + List users = createUsersForTests(); + apiInstance.createUsersWithArrayInput(users).block(); + } + + @Test + void createUsersWithListInput() { + List users = createUsersForTests(); + apiInstance.createUsersWithListInput(users).block(); + } + + @Test + void loginUser() { + final String username = "user1"; + String response = apiInstance.loginUser(username, "pa55w0rd").block(); + assertEquals(response, username); + } + + @Test + void logoutUser() { + apiInstance.logoutUser().block(); + } + + + private static List createUsersForTests() { + List users = new ArrayList<>(); + + User user1 = new User(); + user1.setUsername("User1"); + user1.setId(7L); + users.add(user1); + + User user2 = new User(); + user2.setUsername("User2"); + user2.setId(8L); + users.add(user2); + return users; + } +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/PetApiTest.addPet.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/PetApiTest.addPet.approved.txt new file mode 100644 index 0000000000..cc99464f6e --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/PetApiTest.addPet.approved.txt @@ -0,0 +1,8 @@ +{ + "id" : null, + "category" : null, + "name" : null, + "photoUrls" : [ ], + "tags" : null, + "status" : null +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/PetApiTest.getPetById.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/PetApiTest.getPetById.approved.txt new file mode 100644 index 0000000000..588d5364d1 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/PetApiTest.getPetById.approved.txt @@ -0,0 +1,11 @@ +{ + "id" : 23, + "category" : { + "id" : 0, + "name" : "default-name" + }, + "name" : "HelloPet", + "photoUrls" : [ ], + "tags" : null, + "status" : "available" +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/StoreApiTest.getInventory.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/StoreApiTest.getInventory.approved.txt new file mode 100644 index 0000000000..ce4b5e9473 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/StoreApiTest.getInventory.approved.txt @@ -0,0 +1,4 @@ +{ + "MyPet" : 123, + "OtherPet" : 99 +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/StoreApiTest.getOrderById.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/StoreApiTest.getOrderById.approved.txt new file mode 100644 index 0000000000..b202705043 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/StoreApiTest.getOrderById.approved.txt @@ -0,0 +1,8 @@ +{ + "id" : 123, + "petId" : 4444, + "quantity" : 3, + "shipDate" : "2011-09-21T17:32:28Z", + "status" : "placed", + "complete" : false +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/StoreApiTest.placeOrder.approved.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/StoreApiTest.placeOrder.approved.txt new file mode 100644 index 0000000000..e361d95edf --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/java_client/src/test/java/test_simple_server_stubs/approval_files/StoreApiTest.placeOrder.approved.txt @@ -0,0 +1,8 @@ +{ + "id" : 9876, + "petId" : 0, + "quantity" : 0, + "shipDate" : "2011-01-12T23:24:02Z", + "status" : "placed", + "complete" : false +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/CMakeLists.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/CMakeLists.txt new file mode 100644 index 0000000000..4b06953e81 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/CMakeLists.txt @@ -0,0 +1,3 @@ +add_subdirectory(default_unimplemented_server_stubs) +add_subdirectory(simple_server_stubs) +add_subdirectory(error_handling_server_stubs) \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/default_unimplemented_server_stubs/CMakeLists.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/default_unimplemented_server_stubs/CMakeLists.txt new file mode 100644 index 0000000000..6566d191c5 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/default_unimplemented_server_stubs/CMakeLists.txt @@ -0,0 +1,10 @@ +set(TARGET_NAME default_unimplemented_server_stubs) + +add_executable(${TARGET_NAME}) + +target_sources(${TARGET_NAME} + PRIVATE main.cpp) + +target_link_libraries(${TARGET_NAME} PRIVATE org.openapitools.server.apiStubs) + +run_java_client_test_for_cpp_server(${TARGET_NAME}) \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/default_unimplemented_server_stubs/main.cpp b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/default_unimplemented_server_stubs/main.cpp new file mode 100644 index 0000000000..a2ad83bc60 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/default_unimplemented_server_stubs/main.cpp @@ -0,0 +1,24 @@ +#include "api/PetApi.h" +#include "api/StoreApi.h" +#include "api/UserApi.h" + +using namespace org::openapitools::server::api; + +int main() { + const auto service = std::make_shared(); + + auto petApi = PetApi(service); + petApi.publishDefaultResources(); + + auto storeApi = StoreApi(service); + storeApi.publishDefaultResources(); + + auto userApi = UserApi(service); + userApi.publishDefaultResources(); + + const auto settings = std::make_shared(); + settings->set_port(1234); + + service->start(settings); + +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/error_handling_server_stubs/CMakeLists.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/error_handling_server_stubs/CMakeLists.txt new file mode 100644 index 0000000000..23a4633dba --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/error_handling_server_stubs/CMakeLists.txt @@ -0,0 +1,10 @@ +set(TARGET_NAME error_handling_server_stubs) + +add_executable(${TARGET_NAME}) + +target_sources(${TARGET_NAME} + PRIVATE main.cpp) + +target_link_libraries(${TARGET_NAME} PRIVATE org.openapitools.server.apiStubs) + +run_java_client_test_for_cpp_server(${TARGET_NAME}) \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/error_handling_server_stubs/main.cpp b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/error_handling_server_stubs/main.cpp new file mode 100644 index 0000000000..d151b1c289 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/error_handling_server_stubs/main.cpp @@ -0,0 +1,218 @@ +#include "api/PetApi.h" +#include "api/StoreApi.h" +#include "api/UserApi.h" + +#include + +#include +void sig_handler(int signum){ + printf("\nSIGINT received!\n"); + exit(0); +} + +using namespace org::openapitools::server::api; +using namespace org::openapitools::server::api::PetApiResources; +using namespace org::openapitools::server::api::StoreApiResources; +using namespace org::openapitools::server::api::UserApiResources; + +namespace { +const auto RETURN_STATUS = std::string("ReturnsStatus"); + +bool isReturnStatusString(const std::string &errorType) { + return errorType.rfind(RETURN_STATUS, 0) == 0; +} + +int extractReturnStatus(const std::string &errorType) { + assert(isReturnStatusString(errorType)); + + auto returnValString = errorType; + returnValString.erase(0, RETURN_STATUS.length()); + + return std::stoi(returnValString); +} + + +template +std::pair +raiseErrorForTesting(const RETURN_T &modelObj, + const std::string &errorType) { + if ("ThrowsApiException" == errorType) { + throw API_EXCEPTION_T(500, "ApiException raised"); + } else if ("ThrowsStdExceptionDerivedException" == errorType) { + throw std::logic_error("std::logic_error raised"); + } else if ("ThrowsInt" == errorType) { + throw int(1); + } else if (isReturnStatusString(errorType)) { + auto retStatus = extractReturnStatus(errorType); + return {retStatus, modelObj}; + } + + return std::make_pair(500, modelObj); +} + +std::string intToErrorRaisingString(const int64_t &id) { + std::string errorType; + switch(id) { + case 9100: errorType = "ThrowsApiException"; + break; + case 9200: errorType = "ThrowsStdExceptionDerivedException"; + break; + case 9300: errorType = "ThrowsInt"; + break; + default: errorType = RETURN_STATUS + std::to_string(id); + } + return errorType; +} + +} // namespace + +class MyPetApiPetResource : public PetResource { +public: + int handler_POST(Pet &pet) override { + const std::string &name = pet.getName(); + int status; + Pet pet_; + std::tie(status, pet_) = raiseErrorForTesting(pet, name); + return status; + } + + int handler_PUT(Pet &pet) override { + const std::string &name = pet.getName(); + int status; + Pet pet_; + std::tie(status, pet_) = raiseErrorForTesting(pet, name); + return status; + } +}; + +class MyPetApiPetPetIdResource : public PetPetIdResource { +public: + int handler_DELETE(int64_t &petId, + std::string &api_key) override { + int status; + Pet pet; + std::tie(status, pet) = raiseErrorForTesting(Pet(), api_key); + return status; + } + + std::pair + handler_GET(int64_t &id) override { + std::string errorType = intToErrorRaisingString(id); + + auto pet = Pet(); + pet.setName("MyPuppy"); + pet.setStatus("available"); + + return raiseErrorForTesting(pet, errorType); + } +}; + +class MyStoreApiStoreOrderOrderIdResource : public StoreOrderOrder_idResource { +public: + int handler_DELETE(std::string &orderId) override { + int status; + Pet pet; + std::tie(status, pet) = raiseErrorForTesting(Pet(), orderId); + return status; + } + + std::pair + handler_GET(int64_t &orderId) override { + std::string errorType = intToErrorRaisingString(orderId); + const auto order = Order(); + return raiseErrorForTesting(order, errorType); + } +}; + +class MyStoreApiStoreInventoryResource : public StoreInventoryResource { +public: + std::pair> handler_GET() override { + std::map ret; + return {300, ret}; + } +}; + +class MyStoreApiStoreOrderResource : public StoreOrderResource { +public: + std::pair + handler_POST(Order &order) override { + std::string errorType = intToErrorRaisingString(order.getId()); + return raiseErrorForTesting(order, errorType); + } +}; + +class MyUserApiUserCreateWithArrayResource : public UserCreateWithArrayResource { +public: + int handler_POST(std::vector &user) override { + const auto errorType = user[0].getFirstName(); + int status; + User user_; + std::tie(status, user_) = raiseErrorForTesting(User(), errorType); + return status; + } +}; + +class MyUserApiUserCreateWithListResource : public UserCreateWithListResource { +public: + int handler_POST(std::vector &user) override { + const auto errorType = user[0].getFirstName(); + int status; + User user_; + std::tie(status, user_) = raiseErrorForTesting(User(), errorType); + return status; + } +}; + +class MyUserApiUserLoginResource : public UserLoginResource { +public: + std::pair + handler_GET(std::string &username, + std::string &password) override { + int status; + User user_; + std::tie(status, user_) = raiseErrorForTesting(User(), username); + return {status, username}; + } +}; + +class MyUserApiUserLogoutResource : public UserLogoutResource { +public: + int handler_GET() override { + throw int(5); + } +}; + +int main() { + signal(SIGINT,sig_handler); + + const auto service = std::make_shared(); + + auto petApi = PetApi(service); + petApi.setResource(std::make_shared()); + petApi.setResource(std::make_shared()); + + auto storeApi = StoreApi(service); + storeApi.setResource(std::make_shared()); + storeApi.setResource(std::make_shared()); + storeApi.setResource(std::make_shared()); + + auto userApi = UserApi(service); + userApi.getUserResource()->handler_POST_func = [](auto& user) { + const auto errorType = user.getFirstName(); + int status; + User user_; + std::tie(status, user_) = raiseErrorForTesting(user, errorType); + return status; + }; + userApi.setResource(std::make_shared()); + userApi.setResource(std::make_shared()); + userApi.setResource(std::make_shared()); + userApi.setResource(std::make_shared()); + + + const auto settings = std::make_shared(); + settings->set_port(1236); + + service->start(settings); + +} diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/simple_server_stubs/CMakeLists.txt b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/simple_server_stubs/CMakeLists.txt new file mode 100644 index 0000000000..12361397e4 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/simple_server_stubs/CMakeLists.txt @@ -0,0 +1,10 @@ +set(TARGET_NAME simple_server_stubs) + +add_executable(${TARGET_NAME}) + +target_sources(${TARGET_NAME} + PRIVATE main.cpp) + +target_link_libraries(${TARGET_NAME} PRIVATE org.openapitools.server.apiStubs) + +run_java_client_test_for_cpp_server(${TARGET_NAME}) \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/simple_server_stubs/main.cpp b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/simple_server_stubs/main.cpp new file mode 100644 index 0000000000..8728037272 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/java_client_tests/tests_servers/simple_server_stubs/main.cpp @@ -0,0 +1,154 @@ +#include "api/PetApi.h" +#include "api/StoreApi.h" +#include "api/UserApi.h" + +using namespace org::openapitools::server::api; +using namespace org::openapitools::server::api::PetApiResources; +using namespace org::openapitools::server::api::StoreApiResources; +using namespace org::openapitools::server::api::UserApiResources; + +Pet createPetForTesting_1() { + auto pet = Pet(); + pet.setName("HelloPet"); + pet.setId(23); + pet.setStatus("available"); + return pet; +} + +std::shared_ptr createPetForTesting_2() { + auto pet = std::make_shared(); + pet->setName("HelloPet2"); + pet->setId(44); + pet->setStatus("sold"); + return pet; +} + +class MyPetApiPetResource : public PetResource { +public: + int + handler_POST(Pet &pet) override { + return 200; + } + + int + handler_PUT(Pet &pet) override { + return 200; + } +}; + +class MyPetApiPetPetIdResource : public PetPetIdResource { +public: + int handler_DELETE(int64_t &petId, + std::string &api_key) override { + return 200; + } + + std::pair + handler_GET(int64_t &petId) override { + Pet pet = createPetForTesting_1(); + + return std::make_pair(200, pet); + } +}; + +class MyStoreApiStoreOrderOrderIdResource : public StoreOrderOrder_idResource { +public: + int handler_DELETE(std::string &orderId) override { + return 200; + } + + std::pair + handler_GET(int64_t &orderId) override { + auto order = Order(); + order.setStatus("placed"); + order.setId(orderId); + order.setComplete(false); + order.setPetId(4444L); + order.setQuantity(3); + order.setShipDate("2011-09-21T17:32:28Z"); + + return std::make_pair(200, order); + } +}; + +class MyStoreApiStoreInventoryResource : public StoreInventoryResource { +public: + std::pair> handler_GET() override { + std::map result {{"MyPet", 123}, {"OtherPet", 99}}; + return std::make_pair(200, result); + } +}; + +class MyStoreApiStoreOrderResource: public StoreOrderResource { +public: + std::pair + handler_POST(Order &order) override { + order.setStatus("placed"); + order.setShipDate("2011-01-12T23:24:02Z"); + return {200, order}; + } +}; + +class MyUserApiUserResource : public UserResource { +public: + int handler_POST(User &User) override { + return 200; + } +}; + + +class MyUserApiUserCreateWithArrayResource : public UserCreateWithArrayResource { +public: + int handler_POST(std::vector &User) override { + return 200; + } +}; + +class MyUserApiUserCreateWithListResource : public UserCreateWithListResource { +public: + int handler_POST(std::vector &User) override { + return 200; + } +}; + +class MyUserApiUserLoginResource : public UserLoginResource { +public: + std::pair + handler_GET(std::string &username, + std::string &password) override { + return {200, username}; + } +}; + +class MyUserApiUserLogoutResource : public UserLogoutResource { +public: + int handler_GET() override { + return 200; + } +}; + +int main() { + const auto service = std::make_shared(); + + auto petApi = PetApi(service); + petApi.setResource(std::make_shared()); + petApi.setResource(std::make_shared()); + + auto storeApi = StoreApi(service); + storeApi.setResource(std::make_shared()); + storeApi.setResource(std::make_shared()); + storeApi.setResource(std::make_shared()); + + auto userApi = UserApi(service); + userApi.setResource(std::make_shared()); + userApi.setResource(std::make_shared()); + userApi.setResource(std::make_shared()); + userApi.setResource(std::make_shared()); + userApi.setResource(std::make_shared()); + + const auto settings = std::make_shared(); + settings->set_port(1235); + + service->start(settings); + +} \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/AllOfWithSingleRef_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/AllOfWithSingleRef_test.cpp new file mode 100644 index 0000000000..85ce5f500e --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/AllOfWithSingleRef_test.cpp @@ -0,0 +1,47 @@ + +#define BOOST_TEST_INCLUDED + +#include +#include +#include +#include +#include "test_helper.h" + + +#include "model/AllOfWithSingleRef.h" + +using namespace org::openapitools::server::model; + +namespace { + const std::string jsonForTest = R"( + { + "username" : "string", + "SingleRefType" : { } + } + )"; +} + +BOOST_AUTO_TEST_SUITE(AllOfWithSingleRefModelTest) + +BOOST_AUTO_TEST_CASE(fromJsonAndBack) +{ + auto obj = AllOfWithSingleRef(); + obj.fromJsonString(jsonForTest); + + const auto newJson = obj.toJsonString(); + + TEST_COMPARE_JSON(jsonForTest, newJson); +} + +BOOST_AUTO_TEST_CASE(vectorFromJsonString) +{ + const auto jsonString = "[" + + jsonForTest + + "," + + jsonForTest + + "]"; + const auto vec = createAllOfWithSingleRefVectorFromJsonString(jsonString); + BOOST_TEST(vec.size() == 2); +} + +BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/Animal_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/Animal_test.cpp new file mode 100644 index 0000000000..7d268b90cd --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/Animal_test.cpp @@ -0,0 +1,46 @@ + +#define BOOST_TEST_INCLUDED + +#include +#include +#include +#include +#include "test_helper.h" + + +#include "model/Animal.h" + +using namespace org::openapitools::server::model; + +namespace { + const std::string jsonForTest = R"( +{ + "className" : "string", + "color" : "red" +})"; +} + +BOOST_AUTO_TEST_SUITE(AnimalModelTest) + + BOOST_AUTO_TEST_CASE(fromJsonAndBack) + { + auto obj = Animal(); + obj.fromJsonString(jsonForTest); + + const auto newJson = obj.toJsonString(); + + TEST_COMPARE_JSON(jsonForTest, newJson); + } + + BOOST_AUTO_TEST_CASE(vectorFromJsonString) + { + const auto jsonString = "[" + + jsonForTest + + "," + + jsonForTest + + "]"; + const auto vec = createAnimalVectorFromJsonString(jsonString); + BOOST_TEST(vec.size() == 2); + } + +BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/CMakeLists.txt b/samples/server/petstore/cpp-restbed/test/model_tests/CMakeLists.txt new file mode 100644 index 0000000000..5d48a812cd --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/CMakeLists.txt @@ -0,0 +1,33 @@ + +add_executable(model_tests) + +target_sources(model_tests + PRIVATE + main.cpp + pet_model_test.cpp + tag_model_test.cpp + user_model_test.cpp + category_model_test.cpp + order_model_test.cpp + api_response_model_test.cpp + _foo_get_default_response_test.cpp + _special_model_name_test.cpp + additional_properties_class_test.cpp + AllOfWithSingleRef_test.cpp + Animal_test.cpp +) + +target_include_directories(model_tests + SYSTEM PRIVATE + ${Boost_INCLUDE_DIRS} +) + +target_include_directories(model_tests PRIVATE ${CMAKE_CURRENT_LIST_DIR}) + +target_link_libraries(model_tests + PRIVATE + org.openapitools.server.apiStubs + ${Boost_LIBRARIES}) + + +add_test(NAME model_tests COMMAND model_tests) \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/_foo_get_default_response_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/_foo_get_default_response_test.cpp new file mode 100644 index 0000000000..0d80e7ccf6 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/_foo_get_default_response_test.cpp @@ -0,0 +1,39 @@ +#define BOOST_TEST_INCLUDED +#include +#include +#include +#include + + +#include "model/_foo_get_default_response.h" + +using namespace org::openapitools::server::model; + + +BOOST_AUTO_TEST_SUITE(GetDefaultResponseModelTest) + + BOOST_AUTO_TEST_CASE(toJsonString) + { + auto defaultResponse = _foo_get_default_response(); + auto foo = Foo(); + foo.setBar("bar1"); + defaultResponse.setString(foo); + + const auto jsonString = defaultResponse.toJsonString(); + + auto newDefaultResponse = _foo_get_default_response(); + newDefaultResponse.fromJsonString(jsonString); + + BOOST_TEST(newDefaultResponse.getString().getBar() == "bar1"); + } + + BOOST_AUTO_TEST_CASE(vectorFromJsonString) + { + const auto jsonString = R"([{"string":{"bar":"bar1"}}, {"string":{"bar":"bar2"}}])"; + const auto vec = create_foo_get_default_responseVectorFromJsonString(jsonString); + BOOST_TEST(vec.size() == 2); + BOOST_TEST(vec[0].getString().getBar() == "bar1"); + BOOST_TEST(vec[1].getString().getBar() == "bar2"); + } + +BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/_special_model_name_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/_special_model_name_test.cpp new file mode 100644 index 0000000000..2edac999d9 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/_special_model_name_test.cpp @@ -0,0 +1,48 @@ + +#define BOOST_TEST_INCLUDED + +#include +#include +#include +#include + + +#include "model/_special_model_name_.h" + +using namespace org::openapitools::server::model; + +namespace { +_special_model_name_ create_special_model_name_forTest() { + auto obj = _special_model_name_(); + obj.setSpecialPropertyName(12); + return obj; +} +} + +BOOST_AUTO_TEST_SUITE(special_model_name_ModelTest) + +BOOST_AUTO_TEST_CASE(toJsonString) +{ + const auto obj = create_special_model_name_forTest(); + const auto jsonString = obj.toJsonString(); + + auto newObj = _special_model_name_(); + newObj.fromJsonString(jsonString); + + BOOST_TEST(newObj.getSpecialPropertyName() == 12); +} + +BOOST_AUTO_TEST_CASE(vectorFromJsonString) +{ + const auto obj = create_special_model_name_forTest(); + + const auto jsonString = "[" + + obj.toJsonString() + + "," + + obj.toJsonString() + + "]"; + const auto vec = create_special_model_name_VectorFromJsonString(jsonString); + BOOST_TEST(vec.size() == 2); +} + +BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/additional_properties_class_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/additional_properties_class_test.cpp new file mode 100644 index 0000000000..d636c2749a --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/additional_properties_class_test.cpp @@ -0,0 +1,85 @@ + +#define BOOST_TEST_INCLUDED + +#include +#include +#include +#include + + +#include "model/AdditionalPropertiesClass.h" +#include "test_helper.h" + +using namespace org::openapitools::server::model; + +namespace { + const std::string jsonForTest = R"({ + "map_property" : { + "additionalProp1" : "string", + "additionalProp2" : "string", + "additionalProp3" : "string" + }, + "map_of_map_property" : { + "additionalProp1" : { + "additionalProp1" : "string", + "additionalProp2" : "string", + "additionalProp3" : "string" + }, + "additionalProp2" : { + "additionalProp1" : "string", + "additionalProp2" : "string", + "additionalProp3" : "string" + }, + "additionalProp3" : { + "additionalProp1" : "string", + "additionalProp2" : "string", + "additionalProp3" : "string" + } + } +} + )"; +} + +BOOST_AUTO_TEST_SUITE(AdditionalPropertiesClassModelTest) + +BOOST_AUTO_TEST_CASE(toJsonString) +{ + auto obj = AdditionalPropertiesClass(); + std::map mapProperty; + mapProperty.insert(std::make_pair("foo", "bar")); + obj.setMapProperty(mapProperty); + + const auto jsonString = obj.toJsonString(); + + auto newObj = AdditionalPropertiesClass(); + newObj.fromJsonString(jsonString); + + auto map = newObj.getMapProperty(); + BOOST_TEST(map.size() == 1); + + auto prop = map["foo"]; + BOOST_TEST(prop == "bar"); +} + +BOOST_AUTO_TEST_CASE(fromJsonAndBack) +{ + auto obj = AdditionalPropertiesClass(); + obj.fromJsonString(jsonForTest); + + const auto newJson = obj.toJsonString(); + + TEST_COMPARE_JSON(jsonForTest, newJson); +} + +BOOST_AUTO_TEST_CASE(vectorFromJsonString) +{ + const auto jsonString = "[" + + jsonForTest + + "," + + jsonForTest + + "]"; + const auto vec = createAdditionalPropertiesClassVectorFromJsonString(jsonString); + BOOST_TEST(vec.size() == 2); +} + +BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/api_response_model_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/api_response_model_test.cpp new file mode 100644 index 0000000000..d08635bd74 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/api_response_model_test.cpp @@ -0,0 +1,93 @@ +#define BOOST_TEST_INCLUDED +#include +#include + +#include "model/ApiResponse.h" + +using namespace org::openapitools::server::model; + + +BOOST_AUTO_TEST_SUITE(ApiResponseModelTest) + +BOOST_AUTO_TEST_CASE(toJsonString) +{ + ApiResponse apiResponse; + apiResponse.setCode(404); + apiResponse.setType("Error"); + apiResponse.setMessage("Not available"); + + const auto json = apiResponse.toJsonString(true); + + ApiResponse newResponse; + newResponse.fromJsonString(json); + + BOOST_TEST(newResponse.getCode() == 404); + BOOST_TEST(newResponse.getType() == "Error"); + BOOST_TEST(newResponse.getMessage() == "Not available"); + + +} + +BOOST_AUTO_TEST_CASE(fromJsonString) +{ + const std::string json = R"JSON( +{ + "code": "200", + "type": "Ok", + "message": "Nice!" +} +)JSON"; + + ApiResponse apiResponse; + + apiResponse.fromJsonString(json); + + + BOOST_TEST(apiResponse.getCode() == 200); + BOOST_TEST(apiResponse.getType() == "Ok"); + BOOST_TEST(apiResponse.getMessage() == "Nice!"); +} + + +BOOST_AUTO_TEST_CASE(fromJsonArrayString) +{ + const std::string json = R"JSON( +[{ + "code": "200", + "type": "Ok", + "message": "Nice!" +},{ + "code": "404", + "type": "error", + "message": "bad!" +}] +)JSON"; + + const auto apiResponseVec = createApiResponseVectorFromJsonString(json); + + BOOST_TEST(apiResponseVec.size() == 2); + BOOST_TEST(apiResponseVec[0].getCode() == 200); + BOOST_TEST(apiResponseVec[0].getType() == "Ok"); + BOOST_TEST(apiResponseVec[0].getMessage() == "Nice!"); + BOOST_TEST(apiResponseVec[1].getCode() == 404); + BOOST_TEST(apiResponseVec[1].getType() == "error"); + BOOST_TEST(apiResponseVec[1].getMessage() == "bad!"); +} + +BOOST_AUTO_TEST_CASE(toAndFromPropertyTree) +{ + ApiResponse apiResponse; + apiResponse.setCode(200); + apiResponse.setType("Ack"); + apiResponse.setMessage("cool"); + + const auto pt = apiResponse.toPropertyTree(); + + const auto newApiResponse = ApiResponse(pt); + + BOOST_TEST(newApiResponse.getCode() == 200); + BOOST_TEST(newApiResponse.getType() == "Ack"); + BOOST_TEST(newApiResponse.getMessage() == "cool"); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/category_model_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/category_model_test.cpp new file mode 100644 index 0000000000..5daf866be6 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/category_model_test.cpp @@ -0,0 +1,88 @@ +#define BOOST_TEST_INCLUDED +#include +#include +#include +#include + + +#include "model/Category.h" + +using namespace org::openapitools::server::model; + + +BOOST_AUTO_TEST_SUITE(CategoryModelTest) + +BOOST_AUTO_TEST_CASE(toJsonString) +{ + Category category; + category.setId(1); + category.setName("category1"); + + const auto json = category.toJsonString(false); + + Category newCategory; + newCategory.fromJsonString(json); + + BOOST_TEST(newCategory.getId() == 1); + BOOST_TEST(newCategory.getName() == "category1"); +} + +BOOST_AUTO_TEST_CASE(fromJsonString) +{ + const std::string json = R"JSON( +{ + "id": "23", + "name": "categoryB" +} +)JSON"; + + Category category; + category.fromJsonString(json); + + BOOST_TEST(category.getId() == 23); + BOOST_TEST(category.getName() == "categoryB"); +} + +BOOST_AUTO_TEST_CASE(fromJsonArrayString) +{ + const std::string json = R"JSON( +[{ + "id": "1", + "name": "categoryA" +}, +{ + "id": "2", + "name": "categoryB" +}, +{ + "id": "3", + "name": "categoryC" +}] +)JSON"; + + const auto categoryVec = createCategoryVectorFromJsonString(json); + + BOOST_TEST(categoryVec.size() == 3); + BOOST_TEST(categoryVec[0].getId() == 1); + BOOST_TEST(categoryVec[0].getName() == "categoryA"); + BOOST_TEST(categoryVec[1].getId() == 2); + BOOST_TEST(categoryVec[1].getName() == "categoryB"); + BOOST_TEST(categoryVec[2].getId() == 3); + BOOST_TEST(categoryVec[2].getName() == "categoryC"); + +} + +BOOST_AUTO_TEST_CASE(fromAndToPropertyTree) +{ + Category category; + category.setId(23); + category.setName("categoryX"); + + const auto pt = category.toPropertyTree(); + + const auto newCategory = Category(pt); + BOOST_TEST(newCategory.getId() == 23); + BOOST_TEST(newCategory.getName() == "categoryX"); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/main.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/main.cpp new file mode 100644 index 0000000000..4af53a2ba3 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/main.cpp @@ -0,0 +1,4 @@ +#define BOOST_TEST_MODULE ModelTests + +//#include // static or dynamic boost build +#include // header only boost diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/order_model_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/order_model_test.cpp new file mode 100644 index 0000000000..0fef2d1476 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/order_model_test.cpp @@ -0,0 +1,170 @@ +#define BOOST_TEST_INCLUDED +#include +#include +#include +#include +#include + +#include "model/Order.h" + +using namespace org::openapitools::server::model; + + +BOOST_AUTO_TEST_SUITE(OrderModelTest) + +BOOST_AUTO_TEST_CASE(toJsonString) +{ + Order order; + order.setId(2L); + order.setPetId(3L); + order.setQuantity(6); + order.setShipDate("123"); + order.setStatus("placed"); + order.setComplete(false); + + const auto json = order.toJsonString(true); + + Order newOrder; + newOrder.fromJsonString(json); + + BOOST_TEST(newOrder.getId() == 2L); + BOOST_TEST(newOrder.getPetId() == 3L); + BOOST_TEST(newOrder.getQuantity() == 6); + BOOST_TEST(newOrder.getShipDate() == "123"); + BOOST_TEST(newOrder.getStatus() == "placed"); + BOOST_TEST(newOrder.isComplete() == false); +} + +BOOST_AUTO_TEST_CASE(fromJsonString) +{ + const std::string json = R"JSON( +{ + "id": "22", + "petId": "32", + "quantity": "1", + "shipDate": "999999", + "status": "placed", + "complete": "true" +} +)JSON"; + + Order order; + order.fromJsonString(json); + + BOOST_TEST(order.getId() == 22L); + BOOST_TEST(order.getPetId() == 32L); + BOOST_TEST(order.getQuantity() == 1); + BOOST_TEST(order.getShipDate() == "999999"); + BOOST_TEST(order.getStatus() == "placed"); + BOOST_TEST(order.isComplete() == true); +} + +BOOST_AUTO_TEST_CASE(fromJsonArrayString) +{ + const std::string json = R"JSON( +[{ + "id": "1", + "petId": "1", + "quantity": "1", + "shipDate": "11111", + "status": "placed", + "complete": "true" +},{ + "id": "2", + "petId": "2", + "quantity": "2", + "shipDate": "222222", + "status": "approved", + "complete": "false" +},{ + "id": "3", + "petId": "3", + "quantity": "3", + "shipDate": "33333", + "status": "delivered" +}] +)JSON"; + + const auto orderVec = createOrderVectorFromJsonString(json); + + + BOOST_TEST(orderVec.size() == 3); + BOOST_TEST(orderVec[0].getId() == 1); + BOOST_TEST(orderVec[0].getPetId() == 1); + BOOST_TEST(orderVec[0].getQuantity() == 1); + BOOST_TEST(orderVec[0].getShipDate() == "11111"); + BOOST_TEST(orderVec[0].getStatus() == "placed"); + BOOST_TEST(orderVec[0].isComplete() == true); + BOOST_TEST(orderVec[1].getId() == 2); + BOOST_TEST(orderVec[1].getPetId() == 2); + BOOST_TEST(orderVec[1].getQuantity() == 2); + BOOST_TEST(orderVec[1].getShipDate() == "222222"); + BOOST_TEST(orderVec[1].getStatus() == "approved"); + BOOST_TEST(orderVec[1].isComplete() == false); + BOOST_TEST(orderVec[2].getId() == 3); + BOOST_TEST(orderVec[2].getPetId() == 3); + BOOST_TEST(orderVec[2].getQuantity() == 3); + BOOST_TEST(orderVec[2].getShipDate() == "33333"); + BOOST_TEST(orderVec[2].getStatus() == "delivered"); + BOOST_TEST(orderVec[2].isComplete() == false); +} + +BOOST_AUTO_TEST_CASE(toAndFromPropertyTree) +{ + Order order; + order.setId(1L); + order.setPetId(2L); + order.setQuantity(4); + order.setShipDate("111123"); + order.setStatus("approved"); + order.setComplete(false); + + const auto pt = order.toPropertyTree(); + + const auto newOrder = Order(pt); + + BOOST_TEST(newOrder.getId() == 1L); + BOOST_TEST(newOrder.getPetId() == 2L); + BOOST_TEST(newOrder.getQuantity() == 4); + BOOST_TEST(newOrder.getShipDate() == "111123"); + BOOST_TEST(newOrder.getStatus() == "approved"); + BOOST_TEST(newOrder.isComplete() == false); +} + + +BOOST_DATA_TEST_CASE( + validStatusValues, + boost::unit_test::data::make({"placed","approved","delivered"}), + status) +{ + Order order; + order.setStatus(status); + + BOOST_TEST(order.getStatus() == status); + +} + +BOOST_DATA_TEST_CASE(invalidStatusValues, + boost::unit_test::data::make({"", + "notallowed", + "not available"}), + invalid_status) +{ + bool exceptionCaught = false; + + Order order; + + try { + order.setStatus(invalid_status); + } + catch(const std::runtime_error& excp) { + exceptionCaught = true; + const auto expectedErrorMessage = std::string("Value ") + + invalid_status + + " not allowed"; + BOOST_TEST(excp.what() == expectedErrorMessage); + } + BOOST_TEST(exceptionCaught); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/pet_model_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/pet_model_test.cpp new file mode 100644 index 0000000000..a199d3d240 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/pet_model_test.cpp @@ -0,0 +1,290 @@ +#define BOOST_TEST_INCLUDED +#include +#include +#include +#include +#include +#include +#include + +#include "model/Pet.h" +#include "model/Tag.h" +#include "model/Category.h" + +using namespace org::openapitools::server::model; + +template +boost::property_tree::ptree createPropertyTreeSubArray(const std::initializer_list& data) { + boost::property_tree::ptree tmp_node; + for (const auto &tag : data) { + boost::property_tree::ptree tagEntry; + tagEntry.put("", tag); + tmp_node.push_back(std::make_pair("", tagEntry)); + } + + return tmp_node; +} + +BOOST_AUTO_TEST_SUITE(PetModelTest) + + +BOOST_AUTO_TEST_CASE(toJsonStringWithCategory) +{ + Pet pet; + pet.setId(1); + pet.setName("MyName"); + auto category = Category(); + pet.setCategory(category); + pet.setStatus("pending"); + + const auto json = pet.toJsonString(true); + + Pet newPet; + newPet.fromJsonString(json); + BOOST_TEST(newPet.getId() == 1); + BOOST_TEST(newPet.getName() == "MyName"); + + const auto newCategory = newPet.getCategory(); + BOOST_TEST(newCategory.getName() == "default-name"); + BOOST_TEST(newCategory.getId() == 0); + + +} + +BOOST_AUTO_TEST_CASE(toJsonStringWithTags) +{ + Pet pet; + pet.setId(1); + pet.setName("MyName"); + pet.setStatus("sold"); + + std::vector tags; + auto tag1 = Tag(); + tag1.setName("tag1"); + tag1.setId(1); + tags.emplace_back(tag1); + auto tag2 = Tag(); + tag2.setName("tag2"); + tag2.setId(2); + tags.emplace_back(tag2); + pet.setTags(tags); + + const auto json = pet.toJsonString(true); + + Pet newPet; + newPet.fromJsonString(json); + + BOOST_TEST(newPet.getId() == 1); + BOOST_TEST(newPet.getName() =="MyName"); + + const auto newTags = newPet.getTags(); + BOOST_TEST(newTags.size() == 2); +} + +BOOST_AUTO_TEST_CASE(fromJsonString) +{ + Pet pet; + std::string json = R"JSON( +{ + "id": "23", + "name": "ThePet", + "status": "available" +})JSON"; + + pet.fromJsonString(json); + + BOOST_TEST(pet.getId() == 23); + BOOST_TEST(pet.getName() == "ThePet"); + BOOST_TEST(pet.getStatus() == "available"); +} + +BOOST_AUTO_TEST_CASE(fromJsonArrayString) +{ + Pet pet; + std::string json = R"JSON( +[{ + "id": "23", + "name": "ThePet", + "status": "available" +},{ + "id": "42", + "name": "TheOtherPet", + "status": "available" +}])JSON"; + + const auto petVector = createPetVectorFromJsonString(json); + + BOOST_TEST(petVector.size() == 2); + + BOOST_TEST(petVector[0].getId() == 23); + BOOST_TEST(petVector[0].getName() == "ThePet"); + BOOST_TEST(petVector[0].getStatus() == "available"); + + BOOST_TEST(petVector[1].getId() == 42); + BOOST_TEST(petVector[1].getName() == "TheOtherPet"); + BOOST_TEST(petVector[1].getStatus() == "available"); +} + + +BOOST_AUTO_TEST_CASE(fromJsonAndPropertyTree) +{ + std::stringstream json_stream; + json_stream << R"JSON( +{ + "id": "23", + "name": "ThePet", + "status": "available" +})JSON"; + + boost::property_tree::ptree pt; + boost::property_tree::read_json(json_stream, pt); + + Pet pet{pt}; + + BOOST_TEST(pet.getId() == 23); + BOOST_TEST(pet.getName() == "ThePet"); + BOOST_TEST(pet.getStatus() == "available"); +} + +BOOST_AUTO_TEST_CASE(fromPropertyTree) +{ + + boost::property_tree::ptree pt; + + pt.add("id", 11); + pt.add("status", "available"); + pt.add("name", "Fluffy"); + + boost::property_tree::ptree tags; + boost::property_tree::ptree tagPt1; + tagPt1.add("name", "tag1"); + tagPt1.add("id", 1); + tags.push_back(std::make_pair("", tagPt1)); + boost::property_tree::ptree tagPt2; + tagPt2.add("name", "tag2"); + tagPt2.add("id", 2); + tags.push_back(std::make_pair("", tagPt2)); + pt.add_child("tags", tags); + + pt.add_child("photoUrls", createPropertyTreeSubArray({"www.example.com/photo1", + "www.example.com/photo2"})); + + pt.add("category.name", "Category1"); + pt.add("category.id", 0); + + Pet pet; + pet.fromPropertyTree(pt); + + BOOST_TEST(pet.getName() == "Fluffy"); +} + +BOOST_AUTO_TEST_CASE(toPropertyTree) +{ + Pet pet; + + std::vector tags; + auto tag = Tag(); + tag.setName("Tag1"); + tags.emplace_back(tag); + pet.setTags(tags); + + std::set photoUrls; + photoUrls.insert("www.example.com/photo1"); + photoUrls.insert("www.example.com/photo2"); + pet.setPhotoUrls(photoUrls); + + auto category = Category(); + category.setName("Category1"); + pet.setCategory(category); + + auto pt = pet.toPropertyTree(); + + BOOST_TEST(pt.get("id") == 0); + BOOST_TEST(pt.get("name") == ""); + BOOST_TEST(pt.get("status") == ""); + + auto tagsFromPt = pt.get_child("tags"); + BOOST_TEST(tagsFromPt.size() == 1); + + auto photoUrlsFromPt = pt.get_child("photoUrls"); + BOOST_TEST(photoUrlsFromPt.size() == 2); + + BOOST_TEST(pet.getCategory().getName() == "Category1"); + auto categoryFromPt = pt.get_child("category"); + BOOST_TEST(categoryFromPt.get("name") == "Category1"); +} + +BOOST_AUTO_TEST_CASE(photoUrls) +{ + Pet pet; + std::set photoUrls{"url1", "url2"}; + pet.setPhotoUrls(photoUrls); + + BOOST_TEST(pet.getPhotoUrls().size() == 2); + BOOST_TEST(pet.getPhotoUrls().count("url1") == 1); + BOOST_TEST(pet.getPhotoUrls().count("url2") == 1); +} + +BOOST_AUTO_TEST_CASE(fromJsonWithTags) { + std::string json_str = R"JSON( +{ + "id": "1", + "name": "MyName", + "tags": [ + { + "id": "1", + "name": "tag1" + }, + { + "id": "2", + "name": "tag2" + } + ], + "status": "available" +})JSON"; + + Pet pet; + pet.fromJsonString(json_str); + + BOOST_TEST(pet.getTags().size() == 2); + BOOST_TEST(pet.getTags()[0].getId() == 1); + BOOST_TEST(pet.getTags()[1].getId() == 2); +} + +BOOST_DATA_TEST_CASE(validStatusValues, + boost::unit_test::data::make({"available", + "pending", + "sold"}), + status) +{ + Pet pet; + pet.setStatus(status); + + BOOST_TEST(pet.getStatus() == status); + +} + +BOOST_DATA_TEST_CASE(invalidStatusValues, + boost::unit_test::data::make({"", + "notallowed", + "not available"}), + invalid_status) +{ + bool exceptionCaught = false; + + Pet pet; + + try { + pet.setStatus(invalid_status); + } + catch(const std::runtime_error& excp) { + exceptionCaught = true; + const auto expectedErrorMessage = std::string("Value ") + + invalid_status + + " not allowed"; + BOOST_TEST(excp.what() == expectedErrorMessage); + } + BOOST_TEST(exceptionCaught); +} + +BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/tag_model_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/tag_model_test.cpp new file mode 100644 index 0000000000..8ebfb75eaf --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/tag_model_test.cpp @@ -0,0 +1,84 @@ +#define BOOST_TEST_INCLUDED +#include +#include +#include +#include + +#include "model/Tag.h" + +using namespace org::openapitools::server::model; + + +BOOST_AUTO_TEST_SUITE(TagModelTest) + +BOOST_AUTO_TEST_CASE(toJsonString) +{ + Tag tag; + tag.setId(1); + tag.setName("MyTag"); + const auto json = tag.toJsonString(true); + + Tag newTag; + newTag.fromJsonString(json); + BOOST_TEST(newTag.getId() == 1); + BOOST_TEST(newTag.getName() == "MyTag"); + +} + +BOOST_AUTO_TEST_CASE(fromJsonString) +{ + const std::string json = R"JSON( +{ + "id": 23, + "name": "HelloTag" +})JSON"; + + Tag tag; + tag.fromJsonString(json); + + BOOST_TEST(tag.getId() == 23); + BOOST_TEST(tag.getName() == "HelloTag"); +} + + +BOOST_AUTO_TEST_CASE(fromJsonArrayString) +{ + const std::string json = R"JSON( +[{ + "id": 23, + "name": "HelloTag" +},{ + "id": 42, + "name": "MyTag" +},{ + "id": 13, + "name": "OtherTag" +}])JSON"; + + const auto tagVector = createTagVectorFromJsonString(json); + + BOOST_TEST(tagVector.size() == 3); + BOOST_TEST(tagVector[0].getId() == 23); + BOOST_TEST(tagVector[0].getName() == "HelloTag"); + BOOST_TEST(tagVector[1].getId() == 42); + BOOST_TEST(tagVector[1].getName() == "MyTag"); + BOOST_TEST(tagVector[2].getId() == 13); + BOOST_TEST(tagVector[2].getName() == "OtherTag"); +} + + +BOOST_AUTO_TEST_CASE(ToAndFromPropertyTree) +{ + Tag tag; + tag.setId(42); + tag.setName("AnotherTag"); + + const auto pt = tag.toPropertyTree(); + + const auto newTag = Tag(pt); + + BOOST_TEST(newTag.getId() == 42); + BOOST_TEST(newTag.getName() == "AnotherTag"); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/test_helper.h b/samples/server/petstore/cpp-restbed/test/model_tests/test_helper.h new file mode 100644 index 0000000000..228fdd8837 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/test_helper.h @@ -0,0 +1,20 @@ +#ifndef CPP_RESTPED_SERVER_OPEN_API_TEST_HELPER_H +#define CPP_RESTPED_SERVER_OPEN_API_TEST_HELPER_H + +#include +#include +#include +#include + +#define TEST_COMPARE_JSON(jsonA, jsonB) do { \ + std::stringstream ssA(jsonA); \ + boost::property_tree::ptree ptA; \ + read_json(ssA,ptA); \ + std::stringstream ssB(jsonB); \ + boost::property_tree::ptree ptB; \ + read_json(ssB,ptB); \ + BOOST_TEST(ptA == ptB); \ +} while(0) + + +#endif //CPP_RESTPED_SERVER_OPEN_API_TEST_HELPER_H diff --git a/samples/server/petstore/cpp-restbed/test/model_tests/user_model_test.cpp b/samples/server/petstore/cpp-restbed/test/model_tests/user_model_test.cpp new file mode 100644 index 0000000000..22de8a51f8 --- /dev/null +++ b/samples/server/petstore/cpp-restbed/test/model_tests/user_model_test.cpp @@ -0,0 +1,136 @@ +#define BOOST_TEST_INCLUDED +#include +#include +#include +#include + +#include "model/User.h" + +using namespace org::openapitools::server::model; + + +BOOST_AUTO_TEST_SUITE(UserModelTest) + +BOOST_AUTO_TEST_CASE(toJsonString) +{ + User user; + user.setId(4L); + user.setUsername("User"); + user.setFirstName("First Name"); + user.setLastName("Last Name"); + user.setEmail("user@example.com"); + user.setPassword("passw0rd"); + user.setPhone("1234567890"); + user.setUserStatus(2); + + const auto json = user.toJsonString(true); + + User newUser; + newUser.fromJsonString(json); + + BOOST_TEST(newUser.getId() == 4L); + BOOST_TEST(newUser.getUsername() == "User"); + BOOST_TEST(newUser.getFirstName() == "First Name"); + BOOST_TEST(newUser.getLastName() == "Last Name"); + BOOST_TEST(newUser.getEmail() == "user@example.com"); + BOOST_TEST(newUser.getPassword() == "passw0rd"); + BOOST_TEST(newUser.getPhone() == "1234567890"); + BOOST_TEST(newUser.getUserStatus() == 2); + +} + +BOOST_AUTO_TEST_CASE(fromJsonString) +{ + const std::string json = R"JSON( +{ + "id": "3", + "username": "TheUser", + "firstName": "My Name", + "lastName": "My Last Name", + "email": "user@example.com", + "password": "pa55word", + "phone": "0987654321", + "userStatus": "3" +})JSON"; + + User user; + user.fromJsonString(json); + + BOOST_TEST(user.getId() == 3L); + BOOST_TEST(user.getUsername() == "TheUser"); + BOOST_TEST(user.getFirstName() == "My Name"); + BOOST_TEST(user.getLastName() == "My Last Name"); + BOOST_TEST(user.getEmail() == "user@example.com"); + BOOST_TEST(user.getPassword() == "pa55word"); + BOOST_TEST(user.getPhone() == "0987654321"); + BOOST_TEST(user.getUserStatus() == 3); +} + +BOOST_AUTO_TEST_CASE(toAndFromPropertyTree) +{ + User user; + user.setId(7L); + user.setUsername("User1"); + user.setFirstName("First Name 1"); + user.setLastName("Last Name 1"); + user.setEmail("user1@example.com"); + user.setPassword("passw0rd1"); + user.setPhone("1111122222333"); + user.setUserStatus(23); + + const auto pt = user.toPropertyTree(); + + const auto newUser = User(pt); + + BOOST_TEST(newUser.getId() == 7L); + BOOST_TEST(newUser.getUsername() == "User1"); + BOOST_TEST(newUser.getFirstName() == "First Name 1"); + BOOST_TEST(newUser.getLastName() == "Last Name 1"); + BOOST_TEST(newUser.getEmail() == "user1@example.com"); + BOOST_TEST(newUser.getPassword() == "passw0rd1"); + BOOST_TEST(newUser.getPhone() == "1111122222333"); + BOOST_TEST(newUser.getUserStatus() == 23); +} + + +BOOST_AUTO_TEST_CASE(fromJsonArrayString) { + const std::string json = R"JSON( +[{ + "id": "4", + "username": "TheUser", + "firstName": "My Name", + "lastName": "My Last Name", + "email": "user@example.com", + "password": "pa55word", + "phone": "0987654321", + "userStatus": "3" +},{ + "id": "3", + "username": "TheUser2", + "firstName": "My Name 2", + "lastName": "My Last Name 2", + "email": "user2@example.com", + "password": "pa55word2", + "phone": "098222222", + "userStatus": "22" +},{ + "id": "1", + "username": "TheUser3", + "firstName": "My Name 3", + "lastName": "My Last Name 3", + "email": "user3@example.com", + "password": "pa55word3", + "phone": "098333333", + "userStatus": "33" +}])JSON"; + + const auto userVec = createUserVectorFromJsonString(json); + + BOOST_TEST(userVec.size() == 3); + BOOST_TEST(userVec[0].getUsername() == "TheUser"); + BOOST_TEST(userVec[1].getUsername() == "TheUser2"); + BOOST_TEST(userVec[2].getUsername() == "TheUser3"); + +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/samples/server/petstore/java-helidon-server/mp/.openapi-generator-ignore b/samples/server/petstore/java-helidon-server/mp/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/.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/server/petstore/java-helidon-server/mp/.openapi-generator/FILES b/samples/server/petstore/java-helidon-server/mp/.openapi-generator/FILES new file mode 100644 index 0000000000..9fdbc1aebe --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/.openapi-generator/FILES @@ -0,0 +1,72 @@ +README.md +pom.xml +src/main/java/org/openapitools/server/JavaTimeFormatter.java +src/main/java/org/openapitools/server/RFC3339DateFormat.java +src/main/java/org/openapitools/server/RestApplication.java +src/main/java/org/openapitools/server/api/AnotherFakeService.java +src/main/java/org/openapitools/server/api/AnotherFakeServiceImpl.java +src/main/java/org/openapitools/server/api/DefaultService.java +src/main/java/org/openapitools/server/api/DefaultServiceImpl.java +src/main/java/org/openapitools/server/api/FakeClassnameTags123Service.java +src/main/java/org/openapitools/server/api/FakeClassnameTags123ServiceImpl.java +src/main/java/org/openapitools/server/api/FakeService.java +src/main/java/org/openapitools/server/api/FakeServiceImpl.java +src/main/java/org/openapitools/server/api/PetService.java +src/main/java/org/openapitools/server/api/PetServiceImpl.java +src/main/java/org/openapitools/server/api/StoreService.java +src/main/java/org/openapitools/server/api/StoreServiceImpl.java +src/main/java/org/openapitools/server/api/UserService.java +src/main/java/org/openapitools/server/api/UserServiceImpl.java +src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java +src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java +src/main/java/org/openapitools/server/model/Animal.java +src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java +src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java +src/main/java/org/openapitools/server/model/ArrayTest.java +src/main/java/org/openapitools/server/model/Capitalization.java +src/main/java/org/openapitools/server/model/Cat.java +src/main/java/org/openapitools/server/model/CatAllOf.java +src/main/java/org/openapitools/server/model/Category.java +src/main/java/org/openapitools/server/model/ClassModel.java +src/main/java/org/openapitools/server/model/Client.java +src/main/java/org/openapitools/server/model/DeprecatedObject.java +src/main/java/org/openapitools/server/model/Dog.java +src/main/java/org/openapitools/server/model/DogAllOf.java +src/main/java/org/openapitools/server/model/EnumArrays.java +src/main/java/org/openapitools/server/model/EnumClass.java +src/main/java/org/openapitools/server/model/EnumTest.java +src/main/java/org/openapitools/server/model/FileSchemaTestClass.java +src/main/java/org/openapitools/server/model/Foo.java +src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java +src/main/java/org/openapitools/server/model/FormatTest.java +src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java +src/main/java/org/openapitools/server/model/HealthCheckResult.java +src/main/java/org/openapitools/server/model/MapTest.java +src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java +src/main/java/org/openapitools/server/model/Model200Response.java +src/main/java/org/openapitools/server/model/ModelApiResponse.java +src/main/java/org/openapitools/server/model/ModelFile.java +src/main/java/org/openapitools/server/model/ModelList.java +src/main/java/org/openapitools/server/model/ModelReturn.java +src/main/java/org/openapitools/server/model/Name.java +src/main/java/org/openapitools/server/model/NullableClass.java +src/main/java/org/openapitools/server/model/NumberOnly.java +src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java +src/main/java/org/openapitools/server/model/Order.java +src/main/java/org/openapitools/server/model/OuterComposite.java +src/main/java/org/openapitools/server/model/OuterEnum.java +src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java +src/main/java/org/openapitools/server/model/OuterEnumInteger.java +src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java +src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java +src/main/java/org/openapitools/server/model/Pet.java +src/main/java/org/openapitools/server/model/ReadOnlyFirst.java +src/main/java/org/openapitools/server/model/SingleRefType.java +src/main/java/org/openapitools/server/model/SpecialModelName.java +src/main/java/org/openapitools/server/model/Tag.java +src/main/java/org/openapitools/server/model/User.java +src/main/java/org/openapitools/server/package-info.java +src/main/resources/META-INF/beans.xml +src/main/resources/META-INF/microprofile-config.properties +src/main/resources/META-INF/openapi.yml +src/main/resources/logging.properties diff --git a/samples/server/petstore/java-helidon-server/mp/.openapi-generator/VERSION b/samples/server/petstore/java-helidon-server/mp/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/mp/README.md b/samples/server/petstore/java-helidon-server/mp/README.md new file mode 100644 index 0000000000..582fc1c98e --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/README.md @@ -0,0 +1,74 @@ +# Helidon Server with OpenAPI + +## Build and run + +With JDK11+ +```bash +mvn package +java -jar target/petstore-helidon-server-mp.jar +``` + +## Exercise the application + +``` +curl -X PATCH http://petstore.swagger.io:80/v2 +curl -X GET http://petstore.swagger.io:80/v2 +curl -X GET http://petstore.swagger.io:80/v2/health +curl -X GET http://petstore.swagger.io:80/v2/http-signature-test +curl -X POST http://petstore.swagger.io:80/v2/outer/boolean +curl -X POST http://petstore.swagger.io:80/v2/outer/composite +curl -X POST http://petstore.swagger.io:80/v2/outer/number +curl -X POST http://petstore.swagger.io:80/v2/outer/string +curl -X POST http://petstore.swagger.io:80/v2/property/enum-int +curl -X PUT http://petstore.swagger.io:80/v2/body-with-binary +curl -X PUT http://petstore.swagger.io:80/v2/body-with-file-schema +curl -X PUT http://petstore.swagger.io:80/v2/body-with-query-params +curl -X PATCH http://petstore.swagger.io:80/v2 +curl -X POST http://petstore.swagger.io:80/v2 +curl -X GET http://petstore.swagger.io:80/v2 +curl -X DELETE http://petstore.swagger.io:80/v2 +curl -X POST http://petstore.swagger.io:80/v2/inline-additionalProperties +curl -X GET http://petstore.swagger.io:80/v2/jsonFormData +curl -X PUT http://petstore.swagger.io:80/v2/test-query-parameters +curl -X PATCH http://petstore.swagger.io:80/v2 +curl -X POST http://petstore.swagger.io:80/v2/pet +curl -X DELETE http://petstore.swagger.io:80/v2/pet/{petId} +curl -X GET http://petstore.swagger.io:80/v2/pet/findByStatus +curl -X GET http://petstore.swagger.io:80/v2/pet/findByTags +curl -X GET http://petstore.swagger.io:80/v2/pet/{petId} +curl -X PUT http://petstore.swagger.io:80/v2/pet +curl -X POST http://petstore.swagger.io:80/v2/pet/{petId} +curl -X POST http://petstore.swagger.io:80/v2/pet/{petId}/uploadImage +curl -X POST http://petstore.swagger.io:80/v2/fake/{petId}/uploadImageWithRequiredFile +curl -X DELETE http://petstore.swagger.io:80/v2/order/{order_id} +curl -X GET http://petstore.swagger.io:80/v2/inventory +curl -X GET http://petstore.swagger.io:80/v2/order/{order_id} +curl -X POST http://petstore.swagger.io:80/v2/order +curl -X POST http://petstore.swagger.io:80/v2 +curl -X POST http://petstore.swagger.io:80/v2/createWithArray +curl -X POST http://petstore.swagger.io:80/v2/createWithList +curl -X DELETE http://petstore.swagger.io:80/v2/{username} +curl -X GET http://petstore.swagger.io:80/v2/{username} +curl -X GET http://petstore.swagger.io:80/v2/login +curl -X GET http://petstore.swagger.io:80/v2/logout +curl -X PUT http://petstore.swagger.io:80/v2/{username} + +``` + +## Try health and metrics + +``` +curl -s -X GET http://petstore.swagger.io:80/v2/health +{"outcome":"UP",... +. . . + +# Prometheus Format +curl -s -X GET http://petstore.swagger.io:80/v2/metrics +# TYPE base:gc_g1_young_generation_count gauge +. . . + +# JSON Format +curl -H 'Accept: application/json' -X GET http://petstore.swagger.io:80/v2/metrics +{"base":... +. . . +``` \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/mp/pom.xml b/samples/server/petstore/java-helidon-server/mp/pom.xml new file mode 100644 index 0000000000..2aea52e631 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/pom.xml @@ -0,0 +1,82 @@ + + 4.0.0 + org.openapitools + + io.helidon.applications + helidon-mp + 3.0.1 + + + petstore-helidon-server-mp + petstore-helidon-server-mp + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + 1.0.0 + jar + + + 0.2.3 + + + + + io.helidon.microprofile.bundles + helidon-microprofile-core + + + io.helidon.microprofile.cdi + helidon-microprofile-cdi + + + jakarta.enterprise + jakarta.enterprise.cdi-api + + + jakarta.ws.rs + jakarta.ws.rs-api + + + org.openapitools + jackson-databind-nullable + ${version.jackson.databind.nullable} + + + org.glassfish.jersey.media + jersey-media-json-jackson + + + org.junit.jupiter + junit-jupiter-api + test + + + io.helidon.microprofile.tests + helidon-microprofile-tests-junit5 + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libs + + + + + org.jboss.jandex + jandex-maven-plugin + + + make-index + + + + + + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/JavaTimeFormatter.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/JavaTimeFormatter.java new file mode 100644 index 0000000000..5bb6d6b796 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/JavaTimeFormatter.java @@ -0,0 +1,64 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public class JavaTimeFormatter { + + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + /** + * Format the given {@code OffsetDateTime} object into string. + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/RFC3339DateFormat.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/RFC3339DateFormat.java new file mode 100644 index 0000000000..f47f2f7f98 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/RFC3339DateFormat.java @@ -0,0 +1,50 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/RestApplication.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/RestApplication.java new file mode 100644 index 0000000000..c6e5b490a2 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/RestApplication.java @@ -0,0 +1,11 @@ +package org.openapitools.server; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.ws.rs.ApplicationPath; +import jakarta.ws.rs.core.Application; + +@ApplicationScoped +@ApplicationPath("/v2") +public class RestApplication extends Application { + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/AnotherFakeService.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/AnotherFakeService.java new file mode 100644 index 0000000000..259be05eb5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/AnotherFakeService.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import org.openapitools.server.model.Client; + +import jakarta.ws.rs.*; + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/another-fake/dummy") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public interface AnotherFakeService { + + @PATCH + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + Client call123testSpecialTags(@Valid @NotNull Client client); +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/AnotherFakeServiceImpl.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/AnotherFakeServiceImpl.java new file mode 100644 index 0000000000..dba792a792 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/AnotherFakeServiceImpl.java @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import org.openapitools.server.model.Client; + +import jakarta.ws.rs.*; + + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/another-fake/dummy") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public class AnotherFakeServiceImpl implements AnotherFakeService { + + @PATCH + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + public Client call123testSpecialTags(@Valid @NotNull Client client) { + Client result = null; // Replace with correct business logic. + return result; + } +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/DefaultService.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/DefaultService.java new file mode 100644 index 0000000000..d5c2422a84 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/DefaultService.java @@ -0,0 +1,32 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import org.openapitools.server.model.FooGetDefaultResponse; + +import jakarta.ws.rs.*; + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/foo") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public interface DefaultService { + + @GET + @Produces({ "application/json" }) + FooGetDefaultResponse fooGet(); +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/DefaultServiceImpl.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/DefaultServiceImpl.java new file mode 100644 index 0000000000..c17391e736 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/DefaultServiceImpl.java @@ -0,0 +1,36 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import org.openapitools.server.model.FooGetDefaultResponse; + +import jakarta.ws.rs.*; + + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/foo") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public class DefaultServiceImpl implements DefaultService { + + @GET + @Produces({ "application/json" }) + public FooGetDefaultResponse fooGet() { + FooGetDefaultResponse result = null; // Replace with correct business logic. + return result; + } +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeClassnameTags123Service.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeClassnameTags123Service.java new file mode 100644 index 0000000000..0a3aebe902 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeClassnameTags123Service.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import org.openapitools.server.model.Client; + +import jakarta.ws.rs.*; + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/fake_classname_test") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public interface FakeClassnameTags123Service { + + @PATCH + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + Client testClassname(@Valid @NotNull Client client); +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeClassnameTags123ServiceImpl.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeClassnameTags123ServiceImpl.java new file mode 100644 index 0000000000..0853801d4f --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeClassnameTags123ServiceImpl.java @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import org.openapitools.server.model.Client; + +import jakarta.ws.rs.*; + + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/fake_classname_test") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public class FakeClassnameTags123ServiceImpl implements FakeClassnameTags123Service { + + @PATCH + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + public Client testClassname(@Valid @NotNull Client client) { + Client result = null; // Replace with correct business logic. + return result; + } +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeService.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeService.java new file mode 100644 index 0000000000..130451d090 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeService.java @@ -0,0 +1,125 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import java.math.BigDecimal; +import org.openapitools.server.model.Client; +import org.openapitools.server.model.EnumClass; +import java.io.File; +import org.openapitools.server.model.FileSchemaTestClass; +import org.openapitools.server.model.HealthCheckResult; +import java.time.LocalDate; +import java.util.Map; +import java.time.OffsetDateTime; +import org.openapitools.server.model.OuterComposite; +import org.openapitools.server.model.OuterObjectWithEnumProperty; +import org.openapitools.server.model.Pet; +import org.openapitools.server.model.User; + +import jakarta.ws.rs.*; + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/fake") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public interface FakeService { + + @GET + @Path("/health") + @Produces({ "application/json" }) + HealthCheckResult fakeHealthGet(); + + @GET + @Path("/http-signature-test") + @Consumes({ "application/json", "application/xml" }) + void fakeHttpSignatureTest(@Valid @NotNull Pet pet, @QueryParam("query_1") String query1, @HeaderParam("header_1") String header1); + + @POST + @Path("/outer/boolean") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + Boolean fakeOuterBooleanSerialize(@Valid Boolean body); + + @POST + @Path("/outer/composite") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + OuterComposite fakeOuterCompositeSerialize(@Valid OuterComposite outerComposite); + + @POST + @Path("/outer/number") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + BigDecimal fakeOuterNumberSerialize(@Valid BigDecimal body); + + @POST + @Path("/outer/string") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + String fakeOuterStringSerialize(@Valid String body); + + @POST + @Path("/property/enum-int") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(@Valid @NotNull OuterObjectWithEnumProperty outerObjectWithEnumProperty); + + @PUT + @Path("/body-with-binary") + @Consumes({ "image/png" }) + void testBodyWithBinary(@Valid File body); + + @PUT + @Path("/body-with-file-schema") + @Consumes({ "application/json" }) + void testBodyWithFileSchema(@Valid @NotNull FileSchemaTestClass fileSchemaTestClass); + + @PUT + @Path("/body-with-query-params") + @Consumes({ "application/json" }) + void testBodyWithQueryParams(@QueryParam("query") @NotNull String query, @Valid @NotNull User user); + + @PATCH + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + Client testClientModel(@Valid @NotNull Client client); + + @POST + @Consumes({ "application/x-www-form-urlencoded" }) + void testEndpointParameters(@FormParam(value = "number") BigDecimal number, @FormParam(value = "double") Double _double, @FormParam(value = "pattern_without_delimiter") String patternWithoutDelimiter, @FormParam(value = "byte") byte[] _byte, @FormParam(value = "integer") Integer integer, @FormParam(value = "int32") Integer int32, @FormParam(value = "int64") Long int64, @FormParam(value = "float") Float _float, @FormParam(value = "string") String string, @FormParam(value = "binary") InputStream binaryInputStream, @FormParam(value = "date") LocalDate date, @FormParam(value = "dateTime") OffsetDateTime dateTime, @FormParam(value = "password") String password, @FormParam(value = "callback") String paramCallback); + + @GET + @Consumes({ "application/x-www-form-urlencoded" }) + void testEnumParameters(@HeaderParam("enum_header_string_array") List enumHeaderStringArray, @HeaderParam("enum_header_string") @DefaultValue("-efg") String enumHeaderString, @QueryParam("enum_query_string_array") List enumQueryStringArray, @QueryParam("enum_query_string") @DefaultValue("-efg") String enumQueryString, @QueryParam("enum_query_integer") Integer enumQueryInteger, @QueryParam("enum_query_double") Double enumQueryDouble, @QueryParam("enum_query_model_array") List enumQueryModelArray, @FormParam(value = "enum_form_string_array") List enumFormStringArray, @FormParam(value = "enum_form_string") String enumFormString); + + @DELETE + void testGroupParameters(@QueryParam("required_string_group") @NotNull Integer requiredStringGroup, @HeaderParam("required_boolean_group") @NotNull Boolean requiredBooleanGroup, @QueryParam("required_int64_group") @NotNull Long requiredInt64Group, @QueryParam("string_group") Integer stringGroup, @HeaderParam("boolean_group") Boolean booleanGroup, @QueryParam("int64_group") Long int64Group); + + @POST + @Path("/inline-additionalProperties") + @Consumes({ "application/json" }) + void testInlineAdditionalProperties(@Valid @NotNull Map requestBody); + + @GET + @Path("/jsonFormData") + @Consumes({ "application/x-www-form-urlencoded" }) + void testJsonFormData(@FormParam(value = "param") String param, @FormParam(value = "param2") String param2); + + @PUT + @Path("/test-query-parameters") + void testQueryParameterCollectionFormat(@QueryParam("pipe") @NotNull List pipe, @QueryParam("ioutil") @NotNull List ioutil, @QueryParam("http") @NotNull List http, @QueryParam("url") @NotNull List url, @QueryParam("context") @NotNull List context, @QueryParam("allowEmpty") @NotNull String allowEmpty, @QueryParam("language") Map language); +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeServiceImpl.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeServiceImpl.java new file mode 100644 index 0000000000..d0e402393b --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeServiceImpl.java @@ -0,0 +1,157 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import java.math.BigDecimal; +import org.openapitools.server.model.Client; +import org.openapitools.server.model.EnumClass; +import java.io.File; +import org.openapitools.server.model.FileSchemaTestClass; +import org.openapitools.server.model.HealthCheckResult; +import java.time.LocalDate; +import java.util.Map; +import java.time.OffsetDateTime; +import org.openapitools.server.model.OuterComposite; +import org.openapitools.server.model.OuterObjectWithEnumProperty; +import org.openapitools.server.model.Pet; +import org.openapitools.server.model.User; + +import jakarta.ws.rs.*; + + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/fake") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public class FakeServiceImpl implements FakeService { + + @GET + @Path("/health") + @Produces({ "application/json" }) + public HealthCheckResult fakeHealthGet() { + HealthCheckResult result = null; // Replace with correct business logic. + return result; + } + + @GET + @Path("/http-signature-test") + @Consumes({ "application/json", "application/xml" }) + public void fakeHttpSignatureTest(@Valid @NotNull Pet pet,@QueryParam("query_1") String query1,@HeaderParam("header_1") String header1) { + } + + @POST + @Path("/outer/boolean") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + public Boolean fakeOuterBooleanSerialize(@Valid Boolean body) { + Boolean result = new Boolean(false); // Replace with correct business logic. + return result; + } + + @POST + @Path("/outer/composite") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + public OuterComposite fakeOuterCompositeSerialize(@Valid OuterComposite outerComposite) { + OuterComposite result = null; // Replace with correct business logic. + return result; + } + + @POST + @Path("/outer/number") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + public BigDecimal fakeOuterNumberSerialize(@Valid BigDecimal body) { + BigDecimal result = null; // Replace with correct business logic. + return result; + } + + @POST + @Path("/outer/string") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + public String fakeOuterStringSerialize(@Valid String body) { + String result = ""; // Replace with correct business logic. + return result; + } + + @POST + @Path("/property/enum-int") + @Consumes({ "application/json" }) + @Produces({ "*/*" }) + public OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(@Valid @NotNull OuterObjectWithEnumProperty outerObjectWithEnumProperty) { + OuterObjectWithEnumProperty result = null; // Replace with correct business logic. + return result; + } + + @PUT + @Path("/body-with-binary") + @Consumes({ "image/png" }) + public void testBodyWithBinary(@Valid File body) { + } + + @PUT + @Path("/body-with-file-schema") + @Consumes({ "application/json" }) + public void testBodyWithFileSchema(@Valid @NotNull FileSchemaTestClass fileSchemaTestClass) { + } + + @PUT + @Path("/body-with-query-params") + @Consumes({ "application/json" }) + public void testBodyWithQueryParams(@QueryParam("query") @NotNull String query,@Valid @NotNull User user) { + } + + @PATCH + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + public Client testClientModel(@Valid @NotNull Client client) { + Client result = null; // Replace with correct business logic. + return result; + } + + @POST + @Consumes({ "application/x-www-form-urlencoded" }) + public void testEndpointParameters(@FormParam(value = "number") BigDecimal number,@FormParam(value = "double") Double _double,@FormParam(value = "pattern_without_delimiter") String patternWithoutDelimiter,@FormParam(value = "byte") byte[] _byte,@FormParam(value = "integer") Integer integer,@FormParam(value = "int32") Integer int32,@FormParam(value = "int64") Long int64,@FormParam(value = "float") Float _float,@FormParam(value = "string") String string, @FormParam(value = "binary") InputStream binaryInputStream,@FormParam(value = "date") LocalDate date,@FormParam(value = "dateTime") OffsetDateTime dateTime,@FormParam(value = "password") String password,@FormParam(value = "callback") String paramCallback) { + } + + @GET + @Consumes({ "application/x-www-form-urlencoded" }) + public void testEnumParameters(@HeaderParam("enum_header_string_array") List enumHeaderStringArray,@HeaderParam("enum_header_string") @DefaultValue("-efg") String enumHeaderString,@QueryParam("enum_query_string_array") List enumQueryStringArray,@QueryParam("enum_query_string") @DefaultValue("-efg") String enumQueryString,@QueryParam("enum_query_integer") Integer enumQueryInteger,@QueryParam("enum_query_double") Double enumQueryDouble,@QueryParam("enum_query_model_array") List enumQueryModelArray,@FormParam(value = "enum_form_string_array") List enumFormStringArray,@FormParam(value = "enum_form_string") String enumFormString) { + } + + @DELETE + public void testGroupParameters(@QueryParam("required_string_group") @NotNull Integer requiredStringGroup,@HeaderParam("required_boolean_group") @NotNull Boolean requiredBooleanGroup,@QueryParam("required_int64_group") @NotNull Long requiredInt64Group,@QueryParam("string_group") Integer stringGroup,@HeaderParam("boolean_group") Boolean booleanGroup,@QueryParam("int64_group") Long int64Group) { + } + + @POST + @Path("/inline-additionalProperties") + @Consumes({ "application/json" }) + public void testInlineAdditionalProperties(@Valid @NotNull Map requestBody) { + } + + @GET + @Path("/jsonFormData") + @Consumes({ "application/x-www-form-urlencoded" }) + public void testJsonFormData(@FormParam(value = "param") String param,@FormParam(value = "param2") String param2) { + } + + @PUT + @Path("/test-query-parameters") + public void testQueryParameterCollectionFormat(@QueryParam("pipe") @NotNull List pipe,@QueryParam("ioutil") @NotNull List ioutil,@QueryParam("http") @NotNull List http,@QueryParam("url") @NotNull List url,@QueryParam("context") @NotNull List context,@QueryParam("allowEmpty") @NotNull String allowEmpty,@QueryParam("language") Map language) { + } +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/PetService.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/PetService.java new file mode 100644 index 0000000000..20b812611b --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/PetService.java @@ -0,0 +1,77 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import java.io.File; +import org.openapitools.server.model.ModelApiResponse; +import org.openapitools.server.model.Pet; +import java.util.Set; + +import jakarta.ws.rs.*; + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public interface PetService { + + @POST + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + void addPet(@Valid @NotNull Pet pet); + + @DELETE + @Path("/pet/{petId}") + void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + + @GET + @Path("/pet/findByStatus") + @Produces({ "application/xml", "application/json" }) + List findPetsByStatus(@QueryParam("status") @NotNull List status); + + @GET + @Path("/pet/findByTags") + @Produces({ "application/xml", "application/json" }) + Set findPetsByTags(@QueryParam("tags") @NotNull Set tags); + + @GET + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + Pet getPetById(@PathParam("petId") Long petId); + + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + void updatePet(@Valid @NotNull Pet pet); + + @POST + @Path("/pet/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + void updatePetWithForm(@PathParam("petId") Long petId, @FormParam(value = "name") String name, @FormParam(value = "status") String status); + + @POST + @Path("/pet/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + ModelApiResponse uploadFile(@PathParam("petId") Long petId, @FormParam(value = "additionalMetadata") String additionalMetadata, @FormParam(value = "file") InputStream _fileInputStream); + + @POST + @Path("/fake/{petId}/uploadImageWithRequiredFile") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + ModelApiResponse uploadFileWithRequiredFile(@PathParam("petId") Long petId, @FormParam(value = "requiredFile") InputStream requiredFileInputStream, @FormParam(value = "additionalMetadata") String additionalMetadata); +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/PetServiceImpl.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/PetServiceImpl.java new file mode 100644 index 0000000000..6f6a14e5ec --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/PetServiceImpl.java @@ -0,0 +1,97 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import java.io.File; +import org.openapitools.server.model.ModelApiResponse; +import org.openapitools.server.model.Pet; +import java.util.Set; + +import jakarta.ws.rs.*; + + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public class PetServiceImpl implements PetService { + + @POST + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + public void addPet(@Valid @NotNull Pet pet) { + } + + @DELETE + @Path("/pet/{petId}") + public void deletePet(@PathParam("petId") Long petId,@HeaderParam("api_key") String apiKey) { + } + + @GET + @Path("/pet/findByStatus") + @Produces({ "application/xml", "application/json" }) + public List findPetsByStatus(@QueryParam("status") @NotNull List status) { + List result = java.util.Collections.emptyList(); // Replace with correct business logic. + return result; + } + + @GET + @Path("/pet/findByTags") + @Produces({ "application/xml", "application/json" }) + public Set findPetsByTags(@QueryParam("tags") @NotNull Set tags) { + Set result = java.util.Collections.emptySet(); // Replace with correct business logic. + return result; + } + + @GET + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + public Pet getPetById(@PathParam("petId") Long petId) { + Pet result = null; // Replace with correct business logic. + return result; + } + + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + public void updatePet(@Valid @NotNull Pet pet) { + } + + @POST + @Path("/pet/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + public void updatePetWithForm(@PathParam("petId") Long petId,@FormParam(value = "name") String name,@FormParam(value = "status") String status) { + } + + @POST + @Path("/pet/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + public ModelApiResponse uploadFile(@PathParam("petId") Long petId,@FormParam(value = "additionalMetadata") String additionalMetadata, @FormParam(value = "file") InputStream _fileInputStream) { + ModelApiResponse result = null; // Replace with correct business logic. + return result; + } + + @POST + @Path("/fake/{petId}/uploadImageWithRequiredFile") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + public ModelApiResponse uploadFileWithRequiredFile(@PathParam("petId") Long petId, @FormParam(value = "requiredFile") InputStream requiredFileInputStream,@FormParam(value = "additionalMetadata") String additionalMetadata) { + ModelApiResponse result = null; // Replace with correct business logic. + return result; + } +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/StoreService.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/StoreService.java new file mode 100644 index 0000000000..a2bc50a77b --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/StoreService.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import java.util.Map; +import org.openapitools.server.model.Order; + +import jakarta.ws.rs.*; + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/store") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public interface StoreService { + + @DELETE + @Path("/order/{order_id}") + void deleteOrder(@PathParam("order_id") String orderId); + + @GET + @Path("/inventory") + @Produces({ "application/json" }) + Map getInventory(); + + @GET + @Path("/order/{order_id}") + @Produces({ "application/xml", "application/json" }) + Order getOrderById(@PathParam("order_id") @Min(1L) @Max(5L) Long orderId); + + @POST + @Path("/order") + @Consumes({ "application/json" }) + @Produces({ "application/xml", "application/json" }) + Order placeOrder(@Valid @NotNull Order order); +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/StoreServiceImpl.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/StoreServiceImpl.java new file mode 100644 index 0000000000..f7e722d5f9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/StoreServiceImpl.java @@ -0,0 +1,60 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import java.util.Map; +import org.openapitools.server.model.Order; + +import jakarta.ws.rs.*; + + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/store") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public class StoreServiceImpl implements StoreService { + + @DELETE + @Path("/order/{order_id}") + public void deleteOrder(@PathParam("order_id") String orderId) { + } + + @GET + @Path("/inventory") + @Produces({ "application/json" }) + public Map getInventory() { + Map result = java.util.Collections.emptyMap(); // Replace with correct business logic. + return result; + } + + @GET + @Path("/order/{order_id}") + @Produces({ "application/xml", "application/json" }) + public Order getOrderById(@PathParam("order_id") @Min(1L) @Max(5L) Long orderId) { + Order result = null; // Replace with correct business logic. + return result; + } + + @POST + @Path("/order") + @Consumes({ "application/json" }) + @Produces({ "application/xml", "application/json" }) + public Order placeOrder(@Valid @NotNull Order order) { + Order result = null; // Replace with correct business logic. + return result; + } +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserService.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserService.java new file mode 100644 index 0000000000..3b907684f9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserService.java @@ -0,0 +1,67 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import java.util.List; +import java.time.OffsetDateTime; +import org.openapitools.server.model.User; + +import jakarta.ws.rs.*; + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/user") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public interface UserService { + + @POST + @Consumes({ "application/json" }) + void createUser(@Valid @NotNull User user); + + @POST + @Path("/createWithArray") + @Consumes({ "application/json" }) + void createUsersWithArrayInput(@Valid @NotNull List user); + + @POST + @Path("/createWithList") + @Consumes({ "application/json" }) + void createUsersWithListInput(@Valid @NotNull List user); + + @DELETE + @Path("/{username}") + void deleteUser(@PathParam("username") String username); + + @GET + @Path("/{username}") + @Produces({ "application/xml", "application/json" }) + User getUserByName(@PathParam("username") String username); + + @GET + @Path("/login") + @Produces({ "application/xml", "application/json" }) + String loginUser(@QueryParam("username") @NotNull String username, @QueryParam("password") @NotNull String password); + + @GET + @Path("/logout") + void logoutUser(); + + @PUT + @Path("/{username}") + @Consumes({ "application/json" }) + void updateUser(@PathParam("username") String username, @Valid @NotNull User user); +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserServiceImpl.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserServiceImpl.java new file mode 100644 index 0000000000..b5189292c8 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserServiceImpl.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.api; + +import java.util.List; +import java.time.OffsetDateTime; +import org.openapitools.server.model.User; + +import jakarta.ws.rs.*; + + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +@Path("/user") +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaHelidonServerCodegen") +public class UserServiceImpl implements UserService { + + @POST + @Consumes({ "application/json" }) + public void createUser(@Valid @NotNull User user) { + } + + @POST + @Path("/createWithArray") + @Consumes({ "application/json" }) + public void createUsersWithArrayInput(@Valid @NotNull List user) { + } + + @POST + @Path("/createWithList") + @Consumes({ "application/json" }) + public void createUsersWithListInput(@Valid @NotNull List user) { + } + + @DELETE + @Path("/{username}") + public void deleteUser(@PathParam("username") String username) { + } + + @GET + @Path("/{username}") + @Produces({ "application/xml", "application/json" }) + public User getUserByName(@PathParam("username") String username) { + User result = null; // Replace with correct business logic. + return result; + } + + @GET + @Path("/login") + @Produces({ "application/xml", "application/json" }) + public String loginUser(@QueryParam("username") @NotNull String username,@QueryParam("password") @NotNull String password) { + String result = ""; // Replace with correct business logic. + return result; + } + + @GET + @Path("/logout") + public void logoutUser() { + } + + @PUT + @Path("/{username}") + @Consumes({ "application/json" }) + public void updateUser(@PathParam("username") String username,@Valid @NotNull User user) { + } +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java new file mode 100644 index 0000000000..f5c1e01d9e --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java @@ -0,0 +1,108 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.util.HashMap; +import java.util.Map; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class AdditionalPropertiesClass { + + private Map mapProperty = null; + + private Map> mapOfMapProperty = null; + + /** + * Get mapProperty + * @return mapProperty + **/ + public Map getMapProperty() { + return mapProperty; + } + + /** + * Set mapProperty + **/ + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + /** + * Set mapOfMapProperty + **/ + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java new file mode 100644 index 0000000000..c6f0778d34 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java @@ -0,0 +1,97 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.openapitools.server.model.SingleRefType; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class AllOfWithSingleRef { + + private String username; + + private SingleRefType singleRefType; + + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + + /** + * Set username + **/ + public void setUsername(String username) { + this.username = username; + } + + public AllOfWithSingleRef username(String username) { + this.username = username; + return this; + } + + /** + * Get singleRefType + * @return singleRefType + **/ + public SingleRefType getSingleRefType() { + return singleRefType; + } + + /** + * Set singleRefType + **/ + public void setSingleRefType(SingleRefType singleRefType) { + this.singleRefType = singleRefType; + } + + public AllOfWithSingleRef singleRefType(SingleRefType singleRefType) { + this.singleRefType = singleRefType; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfWithSingleRef {\n"); + + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" singleRefType: ").append(toIndentedString(singleRefType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Animal.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Animal.java new file mode 100644 index 0000000000..da9c02ed0c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Animal.java @@ -0,0 +1,102 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Cat; +import org.openapitools.server.model.Dog; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Animal { + + private String className; + + private String color = "red"; + + /** + * Get className + * @return className + **/ + @NotNull + public String getClassName() { + return className; + } + + /** + * Set className + **/ + public void setClassName(String className) { + this.className = className; + } + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get color + * @return color + **/ + public String getColor() { + return color; + } + + /** + * Set color + **/ + public void setColor(String color) { + this.color = color; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 0000000000..2d384db2ef --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class ArrayOfArrayOfNumberOnly { + + private List> arrayArrayNumber = null; + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + /** + * Set arrayArrayNumber + **/ + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java new file mode 100644 index 0000000000..c97f7e2b9a --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class ArrayOfNumberOnly { + + private List arrayNumber = null; + + /** + * Get arrayNumber + * @return arrayNumber + **/ + public List getArrayNumber() { + return arrayNumber; + } + + /** + * Set arrayNumber + **/ + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayTest.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayTest.java new file mode 100644 index 0000000000..16e36ccd74 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayTest.java @@ -0,0 +1,137 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.ReadOnlyFirst; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class ArrayTest { + + private List arrayOfString = null; + + private List> arrayArrayOfInteger = null; + + private List> arrayArrayOfModel = null; + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @Size(min=0,max=3) public List getArrayOfString() { + return arrayOfString; + } + + /** + * Set arrayOfString + **/ + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + /** + * Set arrayArrayOfInteger + **/ + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + /** + * Set arrayArrayOfModel + **/ + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Capitalization.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Capitalization.java new file mode 100644 index 0000000000..933d2f15d5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Capitalization.java @@ -0,0 +1,191 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Capitalization { + + private String smallCamel; + + private String capitalCamel; + + private String smallSnake; + + private String capitalSnake; + + private String scAETHFlowPoints; + + /** + * Name of the pet + **/ + private String ATT_NAME; + + /** + * Get smallCamel + * @return smallCamel + **/ + public String getSmallCamel() { + return smallCamel; + } + + /** + * Set smallCamel + **/ + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + public String getCapitalCamel() { + return capitalCamel; + } + + /** + * Set capitalCamel + **/ + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + public String getSmallSnake() { + return smallSnake; + } + + /** + * Set smallSnake + **/ + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + public String getCapitalSnake() { + return capitalSnake; + } + + /** + * Set capitalSnake + **/ + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + /** + * Set scAETHFlowPoints + **/ + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + public String getATTNAME() { + return ATT_NAME; + } + + /** + * Set ATT_NAME + **/ + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Cat.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Cat.java new file mode 100644 index 0000000000..78534303e0 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Cat.java @@ -0,0 +1,77 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Animal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Cat extends Animal { + + private Boolean declawed; + + /** + * Get declawed + * @return declawed + **/ + public Boolean getDeclawed() { + return declawed; + } + + /** + * Set declawed + **/ + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/CatAllOf.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/CatAllOf.java new file mode 100644 index 0000000000..e04130db72 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/CatAllOf.java @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class CatAllOf { + + private Boolean declawed; + + /** + * Get declawed + * @return declawed + **/ + public Boolean getDeclawed() { + return declawed; + } + + /** + * Set declawed + **/ + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + public CatAllOf declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CatAllOf {\n"); + + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Category.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Category.java new file mode 100644 index 0000000000..e92a984945 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Category.java @@ -0,0 +1,97 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Category { + + private Long id; + + private String name = "default-name"; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + **/ + @NotNull + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Category name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ClassModel.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ClassModel.java new file mode 100644 index 0000000000..a0b5f1b7eb --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ClassModel.java @@ -0,0 +1,76 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Model for testing model with \"_class\" property + **/ + +public class ClassModel { + + private String propertyClass; + + /** + * Get propertyClass + * @return propertyClass + **/ + public String getPropertyClass() { + return propertyClass; + } + + /** + * Set propertyClass + **/ + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Client.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Client.java new file mode 100644 index 0000000000..522166364a --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Client.java @@ -0,0 +1,73 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Client { + + private String client; + + /** + * Get client + * @return client + **/ + public String getClient() { + return client; + } + + /** + * Set client + **/ + public void setClient(String client) { + this.client = client; + } + + public Client client(String client) { + this.client = client; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/DeprecatedObject.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/DeprecatedObject.java new file mode 100644 index 0000000000..0ea4aa3902 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/DeprecatedObject.java @@ -0,0 +1,73 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class DeprecatedObject { + + private String name; + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public DeprecatedObject name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeprecatedObject {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Dog.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Dog.java new file mode 100644 index 0000000000..e0f8e5a79b --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Dog.java @@ -0,0 +1,77 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Animal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Dog extends Animal { + + private String breed; + + /** + * Get breed + * @return breed + **/ + public String getBreed() { + return breed; + } + + /** + * Set breed + **/ + public void setBreed(String breed) { + this.breed = breed; + } + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/DogAllOf.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/DogAllOf.java new file mode 100644 index 0000000000..6055672091 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/DogAllOf.java @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class DogAllOf { + + private String breed; + + /** + * Get breed + * @return breed + **/ + public String getBreed() { + return breed; + } + + /** + * Set breed + **/ + public void setBreed(String breed) { + this.breed = breed; + } + + public DogAllOf breed(String breed) { + this.breed = breed; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DogAllOf {\n"); + + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumArrays.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumArrays.java new file mode 100644 index 0000000000..9247c5b330 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumArrays.java @@ -0,0 +1,199 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class EnumArrays { + +public enum JustSymbolEnum { + + GREATER_THAN_OR_EQUAL_TO(String.valueOf(">=")), DOLLAR(String.valueOf("$")); + + + private String value; + + JustSymbolEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static JustSymbolEnum fromString(String s) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String value) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + + private JustSymbolEnum justSymbol; + +public enum ArrayEnumEnum { + + FISH(String.valueOf("fish")), CRAB(String.valueOf("crab")); + + + private String value; + + ArrayEnumEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static ArrayEnumEnum fromString(String s) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String value) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + + private List arrayEnum = null; + + /** + * Get justSymbol + * @return justSymbol + **/ + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + /** + * Set justSymbol + **/ + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + public List getArrayEnum() { + return arrayEnum; + } + + /** + * Set arrayEnum + **/ + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumClass.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumClass.java new file mode 100644 index 0000000000..dcd8482b86 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumClass.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumClass fromString(String s) { + for (EnumClass b : EnumClass.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String value) { + for (EnumClass b : EnumClass.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumTest.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumTest.java new file mode 100644 index 0000000000..c5054303fc --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumTest.java @@ -0,0 +1,431 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import org.openapitools.server.model.OuterEnum; +import org.openapitools.server.model.OuterEnumDefaultValue; +import org.openapitools.server.model.OuterEnumInteger; +import org.openapitools.server.model.OuterEnumIntegerDefaultValue; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class EnumTest { + +public enum EnumStringEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); + + + private String value; + + EnumStringEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumStringEnum fromString(String s) { + for (EnumStringEnum b : EnumStringEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @JsonCreator + public static EnumStringEnum fromValue(String value) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + + private EnumStringEnum enumString; + +public enum EnumStringRequiredEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); + + + private String value; + + EnumStringRequiredEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumStringRequiredEnum fromString(String s) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @JsonCreator + public static EnumStringRequiredEnum fromValue(String value) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + + private EnumStringRequiredEnum enumStringRequired; + +public enum EnumIntegerEnum { + + NUMBER_1(Integer.valueOf(1)), NUMBER_MINUS_1(Integer.valueOf(-1)); + + + private Integer value; + + EnumIntegerEnum (Integer v) { + value = v; + } + + public Integer value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into Integer, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumIntegerEnum fromString(String s) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(Integer value) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + + private EnumIntegerEnum enumInteger; + +public enum EnumNumberEnum { + + NUMBER_1_DOT_1(Double.valueOf(1.1)), NUMBER_MINUS_1_DOT_2(Double.valueOf(-1.2)); + + + private Double value; + + EnumNumberEnum (Double v) { + value = v; + } + + public Double value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into Double, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumNumberEnum fromString(String s) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @JsonCreator + public static EnumNumberEnum fromValue(Double value) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + + private EnumNumberEnum enumNumber; + + private OuterEnum outerEnum; + + private OuterEnumInteger outerEnumInteger; + + private OuterEnumDefaultValue outerEnumDefaultValue = OuterEnumDefaultValue.PLACED; + + private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; + + /** + * Get enumString + * @return enumString + **/ + public EnumStringEnum getEnumString() { + return enumString; + } + + /** + * Set enumString + **/ + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumStringRequired + * @return enumStringRequired + **/ + @NotNull + public EnumStringRequiredEnum getEnumStringRequired() { + return enumStringRequired; + } + + /** + * Set enumStringRequired + **/ + public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + } + + public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + /** + * Set enumInteger + **/ + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + /** + * Set enumNumber + **/ + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + public OuterEnum getOuterEnum() { + return outerEnum; + } + + /** + * Set outerEnum + **/ + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnumInteger + * @return outerEnumInteger + **/ + public OuterEnumInteger getOuterEnumInteger() { + return outerEnumInteger; + } + + /** + * Set outerEnumInteger + **/ + public void setOuterEnumInteger(OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + } + + public EnumTest outerEnumInteger(OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + return this; + } + + /** + * Get outerEnumDefaultValue + * @return outerEnumDefaultValue + **/ + public OuterEnumDefaultValue getOuterEnumDefaultValue() { + return outerEnumDefaultValue; + } + + /** + * Set outerEnumDefaultValue + **/ + public void setOuterEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + } + + public EnumTest outerEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + return this; + } + + /** + * Get outerEnumIntegerDefaultValue + * @return outerEnumIntegerDefaultValue + **/ + public OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() { + return outerEnumIntegerDefaultValue; + } + + /** + * Set outerEnumIntegerDefaultValue + **/ + public void setOuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + } + + public EnumTest outerEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumStringRequired: ").append(toIndentedString(enumStringRequired)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append(" outerEnumInteger: ").append(toIndentedString(outerEnumInteger)).append("\n"); + sb.append(" outerEnumDefaultValue: ").append(toIndentedString(outerEnumDefaultValue)).append("\n"); + sb.append(" outerEnumIntegerDefaultValue: ").append(toIndentedString(outerEnumIntegerDefaultValue)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java new file mode 100644 index 0000000000..090b7752f4 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java @@ -0,0 +1,104 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.ModelFile; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class FileSchemaTestClass { + + private ModelFile _file; + + private List files = null; + + /** + * Get _file + * @return _file + **/ + public ModelFile getFile() { + return _file; + } + + /** + * Set _file + **/ + public void setFile(ModelFile _file) { + this._file = _file; + } + + public FileSchemaTestClass _file(ModelFile _file) { + this._file = _file; + return this; + } + + /** + * Get files + * @return files + **/ + public List getFiles() { + return files; + } + + /** + * Set files + **/ + public void setFiles(List files) { + this.files = files; + } + + public FileSchemaTestClass files(List files) { + this.files = files; + return this; + } + + public FileSchemaTestClass addFilesItem(ModelFile filesItem) { + this.files.add(filesItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FileSchemaTestClass {\n"); + + sb.append(" _file: ").append(toIndentedString(_file)).append("\n"); + sb.append(" files: ").append(toIndentedString(files)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Foo.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Foo.java new file mode 100644 index 0000000000..66c97424c4 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Foo.java @@ -0,0 +1,73 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Foo { + + private String bar = "bar"; + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + /** + * Set bar + **/ + public void setBar(String bar) { + this.bar = bar; + } + + public Foo bar(String bar) { + this.bar = bar; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Foo {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java new file mode 100644 index 0000000000..2536010aae --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.openapitools.server.model.Foo; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class FooGetDefaultResponse { + + private Foo string; + + /** + * Get string + * @return string + **/ + public Foo getString() { + return string; + } + + /** + * Set string + **/ + public void setString(Foo string) { + this.string = string; + } + + public FooGetDefaultResponse string(Foo string) { + this.string = string; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FooGetDefaultResponse {\n"); + + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FormatTest.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FormatTest.java new file mode 100644 index 0000000000..ceb79d014d --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FormatTest.java @@ -0,0 +1,444 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class FormatTest { + + private Integer integer; + + private Integer int32; + + private Long int64; + + private BigDecimal number; + + private Float _float; + + private Double _double; + + private BigDecimal decimal; + + private String string; + + private byte[] _byte; + + private File binary; + + private LocalDate date; + + private OffsetDateTime dateTime; + + private UUID uuid; + + private String password; + + /** + * A string that is a 10 digit number. Can have leading zeros. + **/ + private String patternWithDigits; + + /** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + **/ + private String patternWithDigitsAndDelimiter; + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @Min(10) @Max(100) public Integer getInteger() { + return integer; + } + + /** + * Set integer + **/ + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @Min(20) @Max(200) public Integer getInt32() { + return int32; + } + + /** + * Set int32 + **/ + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + public Long getInt64() { + return int64; + } + + /** + * Set int64 + **/ + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @NotNull + @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { + return number; + } + + /** + * Set number + **/ + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { + return _float; + } + + /** + * Set _float + **/ + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { + return _double; + } + + /** + * Set _double + **/ + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get decimal + * @return decimal + **/ + public BigDecimal getDecimal() { + return decimal; + } + + /** + * Set decimal + **/ + public void setDecimal(BigDecimal decimal) { + this.decimal = decimal; + } + + public FormatTest decimal(BigDecimal decimal) { + this.decimal = decimal; + return this; + } + + /** + * Get string + * @return string + **/ + @Pattern(regexp="/[a-z]/i") public String getString() { + return string; + } + + /** + * Set string + **/ + public void setString(String string) { + this.string = string; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @NotNull + public byte[] getByte() { + return _byte; + } + + /** + * Set _byte + **/ + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get binary + * @return binary + **/ + public File getBinary() { + return binary; + } + + /** + * Set binary + **/ + public void setBinary(File binary) { + this.binary = binary; + } + + public FormatTest binary(File binary) { + this.binary = binary; + return this; + } + + /** + * Get date + * @return date + **/ + @NotNull + public LocalDate getDate() { + return date; + } + + /** + * Set date + **/ + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + public OffsetDateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + **/ + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + public UUID getUuid() { + return uuid; + } + + /** + * Set uuid + **/ + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get password + * @return password + **/ + @NotNull + @Size(min=10,max=64) public String getPassword() { + return password; + } + + /** + * Set password + **/ + public void setPassword(String password) { + this.password = password; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * A string that is a 10 digit number. Can have leading zeros. + * @return patternWithDigits + **/ + @Pattern(regexp="^\\d{10}$") public String getPatternWithDigits() { + return patternWithDigits; + } + + /** + * Set patternWithDigits + **/ + public void setPatternWithDigits(String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + } + + public FormatTest patternWithDigits(String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + return this; + } + + /** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + * @return patternWithDigitsAndDelimiter + **/ + @Pattern(regexp="/^image_\\d{1,3}$/i") public String getPatternWithDigitsAndDelimiter() { + return patternWithDigitsAndDelimiter; + } + + /** + * Set patternWithDigitsAndDelimiter + **/ + public void setPatternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + } + + public FormatTest patternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" decimal: ").append(toIndentedString(decimal)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); + sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java new file mode 100644 index 0000000000..82f9d53306 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java @@ -0,0 +1,89 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class HasOnlyReadOnly { + + private String bar; + + private String foo; + + public HasOnlyReadOnly() { + } + + @JsonCreator + public HasOnlyReadOnly( + + @JsonProperty(value="bar") String bar, + + @JsonProperty(value="foo") String foo + ) { + this.bar = bar; + this.foo = foo; + } + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + + /** + * Get foo + * @return foo + **/ + public String getFoo() { + return foo; + } + + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/HealthCheckResult.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/HealthCheckResult.java new file mode 100644 index 0000000000..7ac79cd6f9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/HealthCheckResult.java @@ -0,0 +1,77 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.openapitools.jackson.nullable.JsonNullable; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + **/ + +public class HealthCheckResult { + + private String nullableMessage; + + /** + * Get nullableMessage + * @return nullableMessage + **/ + public String getNullableMessage() { + return nullableMessage; + } + + /** + * Set nullableMessage + **/ + public void setNullableMessage(String nullableMessage) { + this.nullableMessage = nullableMessage; + } + + public HealthCheckResult nullableMessage(String nullableMessage) { + this.nullableMessage = nullableMessage; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HealthCheckResult {\n"); + + sb.append(" nullableMessage: ").append(toIndentedString(nullableMessage)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MapTest.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MapTest.java new file mode 100644 index 0000000000..c36c7ee0cc --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MapTest.java @@ -0,0 +1,213 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class MapTest { + + private Map> mapMapOfString = null; + +public enum InnerEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")); + + + private String value; + + InnerEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static InnerEnum fromString(String s) { + for (InnerEnum b : InnerEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @JsonCreator + public static InnerEnum fromValue(String value) { + for (InnerEnum b : InnerEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + + private Map mapOfEnumString = null; + + private Map directMap = null; + + private Map indirectMap = null; + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + public Map> getMapMapOfString() { + return mapMapOfString; + } + + /** + * Set mapMapOfString + **/ + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + /** + * Set mapOfEnumString + **/ + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get directMap + * @return directMap + **/ + public Map getDirectMap() { + return directMap; + } + + /** + * Set directMap + **/ + public void setDirectMap(Map directMap) { + this.directMap = directMap; + } + + public MapTest directMap(Map directMap) { + this.directMap = directMap; + return this; + } + + public MapTest putDirectMapItem(String key, Boolean directMapItem) { + this.directMap.put(key, directMapItem); + return this; + } + + /** + * Get indirectMap + * @return indirectMap + **/ + public Map getIndirectMap() { + return indirectMap; + } + + /** + * Set indirectMap + **/ + public void setIndirectMap(Map indirectMap) { + this.indirectMap = indirectMap; + } + + public MapTest indirectMap(Map indirectMap) { + this.indirectMap = indirectMap; + return this; + } + + public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { + this.indirectMap.put(key, indirectMapItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append(" directMap: ").append(toIndentedString(directMap)).append("\n"); + sb.append(" indirectMap: ").append(toIndentedString(indirectMap)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 0000000000..1d04eaf6c9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,129 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.openapitools.server.model.Animal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private UUID uuid; + + private OffsetDateTime dateTime; + + private Map map = null; + + /** + * Get uuid + * @return uuid + **/ + public UUID getUuid() { + return uuid; + } + + /** + * Set uuid + **/ + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + public OffsetDateTime getDateTime() { + return dateTime; + } + + /** + * Set dateTime + **/ + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get map + * @return map + **/ + public Map getMap() { + return map; + } + + /** + * Set map + **/ + public void setMap(Map map) { + this.map = map; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Model200Response.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Model200Response.java new file mode 100644 index 0000000000..a091e534c3 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Model200Response.java @@ -0,0 +1,100 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Model for testing model name starting with number + **/ + +public class Model200Response { + + private Integer name; + + private String propertyClass; + + /** + * Get name + * @return name + **/ + public Integer getName() { + return name; + } + + /** + * Set name + **/ + public void setName(Integer name) { + this.name = name; + } + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + public String getPropertyClass() { + return propertyClass; + } + + /** + * Set propertyClass + **/ + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelApiResponse.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelApiResponse.java new file mode 100644 index 0000000000..9d01d1753e --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelApiResponse.java @@ -0,0 +1,120 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class ModelApiResponse { + + private Integer code; + + private String type; + + private String message; + + /** + * Get code + * @return code + **/ + public Integer getCode() { + return code; + } + + /** + * Set code + **/ + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get type + * @return type + **/ + public String getType() { + return type; + } + + /** + * Set type + **/ + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get message + * @return message + **/ + public String getMessage() { + return message; + } + + /** + * Set message + **/ + public void setMessage(String message) { + this.message = message; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelFile.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelFile.java new file mode 100644 index 0000000000..432f843889 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelFile.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Must be named `File` for test. + **/ + +public class ModelFile { + + /** + * Test capitalization + **/ + private String sourceURI; + + /** + * Test capitalization + * @return sourceURI + **/ + public String getSourceURI() { + return sourceURI; + } + + /** + * Set sourceURI + **/ + public void setSourceURI(String sourceURI) { + this.sourceURI = sourceURI; + } + + public ModelFile sourceURI(String sourceURI) { + this.sourceURI = sourceURI; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelFile {\n"); + + sb.append(" sourceURI: ").append(toIndentedString(sourceURI)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelList.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelList.java new file mode 100644 index 0000000000..a8e0e3a4b0 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelList.java @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class ModelList { + + private String _123list; + + /** + * Get _123list + * @return _123list + **/ + public String get123list() { + return _123list; + } + + /** + * Set _123list + **/ + public void set123list(String _123list) { + this._123list = _123list; + } + + public ModelList _123list(String _123list) { + this._123list = _123list; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelList {\n"); + + sb.append(" _123list: ").append(toIndentedString(_123list)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelReturn.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelReturn.java new file mode 100644 index 0000000000..c37c75a2bf --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ModelReturn.java @@ -0,0 +1,77 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Model for testing reserved words + **/ + +public class ModelReturn { + + private Integer _return; + + /** + * Get _return + * @return _return + **/ + public Integer getReturn() { + return _return; + } + + /** + * Set _return + **/ + public void setReturn(Integer _return) { + this._return = _return; + } + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Name.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Name.java new file mode 100644 index 0000000000..bb51b80974 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Name.java @@ -0,0 +1,138 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Model for testing model name same as property name + **/ + +public class Name { + + private Integer name; + + private Integer snakeCase; + + private String property; + + private Integer _123number; + + public Name() { + } + + @JsonCreator + public Name( + + @JsonProperty(value="snake_case") Integer snakeCase, + + @JsonProperty(value="123Number") Integer _123number + ) { + this.snakeCase = snakeCase; + this._123number = _123number; + } + + /** + * Get name + * @return name + **/ + @NotNull + public Integer getName() { + return name; + } + + /** + * Set name + **/ + public void setName(Integer name) { + this.name = name; + } + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + public Integer getSnakeCase() { + return snakeCase; + } + + + /** + * Get property + * @return property + **/ + public String getProperty() { + return property; + } + + /** + * Set property + **/ + public void setProperty(String property) { + this.property = property; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get _123number + * @return _123number + **/ + public Integer get123number() { + return _123number; + } + + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123number: ").append(toIndentedString(_123number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/NullableClass.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/NullableClass.java new file mode 100644 index 0000000000..69e3053bea --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/NullableClass.java @@ -0,0 +1,364 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class NullableClass extends HashMap { + + private Integer integerProp; + + private BigDecimal numberProp; + + private Boolean booleanProp; + + private String stringProp; + + private LocalDate dateProp; + + private OffsetDateTime datetimeProp; + + private List arrayNullableProp = null; + + private List arrayAndItemsNullableProp = null; + + private List arrayItemsNullable = null; + + private Map objectNullableProp = null; + + private Map objectAndItemsNullableProp = null; + + private Map objectItemsNullable = null; + + /** + * Get integerProp + * @return integerProp + **/ + public Integer getIntegerProp() { + return integerProp; + } + + /** + * Set integerProp + **/ + public void setIntegerProp(Integer integerProp) { + this.integerProp = integerProp; + } + + public NullableClass integerProp(Integer integerProp) { + this.integerProp = integerProp; + return this; + } + + /** + * Get numberProp + * @return numberProp + **/ + public BigDecimal getNumberProp() { + return numberProp; + } + + /** + * Set numberProp + **/ + public void setNumberProp(BigDecimal numberProp) { + this.numberProp = numberProp; + } + + public NullableClass numberProp(BigDecimal numberProp) { + this.numberProp = numberProp; + return this; + } + + /** + * Get booleanProp + * @return booleanProp + **/ + public Boolean getBooleanProp() { + return booleanProp; + } + + /** + * Set booleanProp + **/ + public void setBooleanProp(Boolean booleanProp) { + this.booleanProp = booleanProp; + } + + public NullableClass booleanProp(Boolean booleanProp) { + this.booleanProp = booleanProp; + return this; + } + + /** + * Get stringProp + * @return stringProp + **/ + public String getStringProp() { + return stringProp; + } + + /** + * Set stringProp + **/ + public void setStringProp(String stringProp) { + this.stringProp = stringProp; + } + + public NullableClass stringProp(String stringProp) { + this.stringProp = stringProp; + return this; + } + + /** + * Get dateProp + * @return dateProp + **/ + public LocalDate getDateProp() { + return dateProp; + } + + /** + * Set dateProp + **/ + public void setDateProp(LocalDate dateProp) { + this.dateProp = dateProp; + } + + public NullableClass dateProp(LocalDate dateProp) { + this.dateProp = dateProp; + return this; + } + + /** + * Get datetimeProp + * @return datetimeProp + **/ + public OffsetDateTime getDatetimeProp() { + return datetimeProp; + } + + /** + * Set datetimeProp + **/ + public void setDatetimeProp(OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + } + + public NullableClass datetimeProp(OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + return this; + } + + /** + * Get arrayNullableProp + * @return arrayNullableProp + **/ + public List getArrayNullableProp() { + return arrayNullableProp; + } + + /** + * Set arrayNullableProp + **/ + public void setArrayNullableProp(List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + } + + public NullableClass arrayNullableProp(List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + return this; + } + + public NullableClass addArrayNullablePropItem(Object arrayNullablePropItem) { + this.arrayNullableProp.add(arrayNullablePropItem); + return this; + } + + /** + * Get arrayAndItemsNullableProp + * @return arrayAndItemsNullableProp + **/ + public List getArrayAndItemsNullableProp() { + return arrayAndItemsNullableProp; + } + + /** + * Set arrayAndItemsNullableProp + **/ + public void setArrayAndItemsNullableProp(List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + } + + public NullableClass arrayAndItemsNullableProp(List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + return this; + } + + public NullableClass addArrayAndItemsNullablePropItem(Object arrayAndItemsNullablePropItem) { + this.arrayAndItemsNullableProp.add(arrayAndItemsNullablePropItem); + return this; + } + + /** + * Get arrayItemsNullable + * @return arrayItemsNullable + **/ + public List getArrayItemsNullable() { + return arrayItemsNullable; + } + + /** + * Set arrayItemsNullable + **/ + public void setArrayItemsNullable(List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + } + + public NullableClass arrayItemsNullable(List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + return this; + } + + public NullableClass addArrayItemsNullableItem(Object arrayItemsNullableItem) { + this.arrayItemsNullable.add(arrayItemsNullableItem); + return this; + } + + /** + * Get objectNullableProp + * @return objectNullableProp + **/ + public Map getObjectNullableProp() { + return objectNullableProp; + } + + /** + * Set objectNullableProp + **/ + public void setObjectNullableProp(Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + } + + public NullableClass objectNullableProp(Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + return this; + } + + public NullableClass putObjectNullablePropItem(String key, Object objectNullablePropItem) { + this.objectNullableProp.put(key, objectNullablePropItem); + return this; + } + + /** + * Get objectAndItemsNullableProp + * @return objectAndItemsNullableProp + **/ + public Map getObjectAndItemsNullableProp() { + return objectAndItemsNullableProp; + } + + /** + * Set objectAndItemsNullableProp + **/ + public void setObjectAndItemsNullableProp(Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + } + + public NullableClass objectAndItemsNullableProp(Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + return this; + } + + public NullableClass putObjectAndItemsNullablePropItem(String key, Object objectAndItemsNullablePropItem) { + this.objectAndItemsNullableProp.put(key, objectAndItemsNullablePropItem); + return this; + } + + /** + * Get objectItemsNullable + * @return objectItemsNullable + **/ + public Map getObjectItemsNullable() { + return objectItemsNullable; + } + + /** + * Set objectItemsNullable + **/ + public void setObjectItemsNullable(Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + } + + public NullableClass objectItemsNullable(Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + return this; + } + + public NullableClass putObjectItemsNullableItem(String key, Object objectItemsNullableItem) { + this.objectItemsNullable.put(key, objectItemsNullableItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NullableClass {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" integerProp: ").append(toIndentedString(integerProp)).append("\n"); + sb.append(" numberProp: ").append(toIndentedString(numberProp)).append("\n"); + sb.append(" booleanProp: ").append(toIndentedString(booleanProp)).append("\n"); + sb.append(" stringProp: ").append(toIndentedString(stringProp)).append("\n"); + sb.append(" dateProp: ").append(toIndentedString(dateProp)).append("\n"); + sb.append(" datetimeProp: ").append(toIndentedString(datetimeProp)).append("\n"); + sb.append(" arrayNullableProp: ").append(toIndentedString(arrayNullableProp)).append("\n"); + sb.append(" arrayAndItemsNullableProp: ").append(toIndentedString(arrayAndItemsNullableProp)).append("\n"); + sb.append(" arrayItemsNullable: ").append(toIndentedString(arrayItemsNullable)).append("\n"); + sb.append(" objectNullableProp: ").append(toIndentedString(objectNullableProp)).append("\n"); + sb.append(" objectAndItemsNullableProp: ").append(toIndentedString(objectAndItemsNullableProp)).append("\n"); + sb.append(" objectItemsNullable: ").append(toIndentedString(objectItemsNullable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/NumberOnly.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/NumberOnly.java new file mode 100644 index 0000000000..e0761ba551 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/NumberOnly.java @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class NumberOnly { + + private BigDecimal justNumber; + + /** + * Get justNumber + * @return justNumber + **/ + public BigDecimal getJustNumber() { + return justNumber; + } + + /** + * Set justNumber + **/ + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java new file mode 100644 index 0000000000..004f80020d --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java @@ -0,0 +1,157 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.DeprecatedObject; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class ObjectWithDeprecatedFields { + + private String uuid; + + private BigDecimal id; + + private DeprecatedObject deprecatedRef; + + private List bars = null; + + /** + * Get uuid + * @return uuid + **/ + public String getUuid() { + return uuid; + } + + /** + * Set uuid + **/ + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public ObjectWithDeprecatedFields uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get id + * @return id + * @deprecated + **/ + @Deprecated + public BigDecimal getId() { + return id; + } + + /** + * Set id + **/ + public void setId(BigDecimal id) { + this.id = id; + } + + public ObjectWithDeprecatedFields id(BigDecimal id) { + this.id = id; + return this; + } + + /** + * Get deprecatedRef + * @return deprecatedRef + * @deprecated + **/ + @Deprecated + public DeprecatedObject getDeprecatedRef() { + return deprecatedRef; + } + + /** + * Set deprecatedRef + **/ + public void setDeprecatedRef(DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + } + + public ObjectWithDeprecatedFields deprecatedRef(DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + return this; + } + + /** + * Get bars + * @return bars + * @deprecated + **/ + @Deprecated + public List getBars() { + return bars; + } + + /** + * Set bars + **/ + public void setBars(List bars) { + this.bars = bars; + } + + public ObjectWithDeprecatedFields bars(List bars) { + this.bars = bars; + return this; + } + + public ObjectWithDeprecatedFields addBarsItem(String barsItem) { + this.bars.add(barsItem); + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ObjectWithDeprecatedFields {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" deprecatedRef: ").append(toIndentedString(deprecatedRef)).append("\n"); + sb.append(" bars: ").append(toIndentedString(bars)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Order.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Order.java new file mode 100644 index 0000000000..62b985da19 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Order.java @@ -0,0 +1,241 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Order { + + private Long id; + + private Long petId; + + private Integer quantity; + + private OffsetDateTime shipDate; + +public enum StatusEnum { + + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static StatusEnum fromString(String s) { + for (StatusEnum b : StatusEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + + /** + * Order Status + **/ + private StatusEnum status; + + private Boolean complete = false; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get petId + * @return petId + **/ + public Long getPetId() { + return petId; + } + + /** + * Set petId + **/ + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + public Integer getQuantity() { + return quantity; + } + + /** + * Set quantity + **/ + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + public OffsetDateTime getShipDate() { + return shipDate; + } + + /** + * Set shipDate + **/ + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Order Status + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + **/ + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Get complete + * @return complete + **/ + public Boolean getComplete() { + return complete; + } + + /** + * Set complete + **/ + public void setComplete(Boolean complete) { + this.complete = complete; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterComposite.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterComposite.java new file mode 100644 index 0000000000..7d1630e2f5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterComposite.java @@ -0,0 +1,120 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class OuterComposite { + + private BigDecimal myNumber; + + private String myString; + + private Boolean myBoolean; + + /** + * Get myNumber + * @return myNumber + **/ + public BigDecimal getMyNumber() { + return myNumber; + } + + /** + * Set myNumber + **/ + public void setMyNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + } + + public OuterComposite myNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + return this; + } + + /** + * Get myString + * @return myString + **/ + public String getMyString() { + return myString; + } + + /** + * Set myString + **/ + public void setMyString(String myString) { + this.myString = myString; + } + + public OuterComposite myString(String myString) { + this.myString = myString; + return this; + } + + /** + * Get myBoolean + * @return myBoolean + **/ + public Boolean getMyBoolean() { + return myBoolean; + } + + /** + * Set myBoolean + **/ + public void setMyBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + } + + public OuterComposite myBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterComposite {\n"); + + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); + sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnum.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnum.java new file mode 100644 index 0000000000..771c8a4c8f --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnum.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static OuterEnum fromString(String s) { + for (OuterEnum b : OuterEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + return null; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String value) { + for (OuterEnum b : OuterEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java new file mode 100644 index 0000000000..8900e4a6bb --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumDefaultValue + */ +public enum OuterEnumDefaultValue { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnumDefaultValue(String value) { + this.value = value; + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static OuterEnumDefaultValue fromString(String s) { + for (OuterEnumDefaultValue b : OuterEnumDefaultValue.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumDefaultValue fromValue(String value) { + for (OuterEnumDefaultValue b : OuterEnumDefaultValue.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumInteger.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumInteger.java new file mode 100644 index 0000000000..e18841134b --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumInteger.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumInteger + */ +public enum OuterEnumInteger { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumInteger(Integer value) { + this.value = value; + } + + /** + * Convert a String into Integer, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static OuterEnumInteger fromString(String s) { + for (OuterEnumInteger b : OuterEnumInteger.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumInteger fromValue(Integer value) { + for (OuterEnumInteger b : OuterEnumInteger.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java new file mode 100644 index 0000000000..0150c204d6 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumIntegerDefaultValue + */ +public enum OuterEnumIntegerDefaultValue { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumIntegerDefaultValue(Integer value) { + this.value = value; + } + + /** + * Convert a String into Integer, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static OuterEnumIntegerDefaultValue fromString(String s) { + for (OuterEnumIntegerDefaultValue b : OuterEnumIntegerDefaultValue.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumIntegerDefaultValue fromValue(Integer value) { + for (OuterEnumIntegerDefaultValue b : OuterEnumIntegerDefaultValue.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java new file mode 100644 index 0000000000..45002fd1d7 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.openapitools.server.model.OuterEnumInteger; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class OuterObjectWithEnumProperty { + + private OuterEnumInteger value; + + /** + * Get value + * @return value + **/ + @NotNull + public OuterEnumInteger getValue() { + return value; + } + + /** + * Set value + **/ + public void setValue(OuterEnumInteger value) { + this.value = value; + } + + public OuterObjectWithEnumProperty value(OuterEnumInteger value) { + this.value = value; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterObjectWithEnumProperty {\n"); + + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Pet.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Pet.java new file mode 100644 index 0000000000..8cf6295f00 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Pet.java @@ -0,0 +1,260 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.openapitools.server.model.Category; +import org.openapitools.server.model.Tag; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Pet { + + private Long id; + + private Category category; + + private String name; + + private Set photoUrls = new LinkedHashSet<>(); + + private List tags = null; + +public enum StatusEnum { + + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static StatusEnum fromString(String s) { + for (StatusEnum b : StatusEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + + /** + * pet status in the store + **/ + private StatusEnum status; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get category + * @return category + **/ + public Category getCategory() { + return category; + } + + /** + * Set category + **/ + public void setCategory(Category category) { + this.category = category; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get name + * @return name + **/ + @NotNull + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @NotNull + public Set getPhotoUrls() { + return photoUrls; + } + + /** + * Set photoUrls + **/ + @JsonDeserialize(as = LinkedHashSet.class) + public void setPhotoUrls(Set photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet photoUrls(Set photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + public List getTags() { + return tags; + } + + /** + * Set tags + **/ + public void setTags(List tags) { + this.tags = tags; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * pet status in the store + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + **/ + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java new file mode 100644 index 0000000000..3294db20f6 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java @@ -0,0 +1,96 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class ReadOnlyFirst { + + private String bar; + + private String baz; + + public ReadOnlyFirst() { + } + + @JsonCreator + public ReadOnlyFirst( + + @JsonProperty(value="bar") String bar + ) { + this.bar = bar; + } + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + + /** + * Get baz + * @return baz + **/ + public String getBaz() { + return baz; + } + + /** + * Set baz + **/ + public void setBaz(String baz) { + this.baz = baz; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SingleRefType.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SingleRefType.java new file mode 100644 index 0000000000..9442b2914d --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SingleRefType.java @@ -0,0 +1,67 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets SingleRefType + */ +public enum SingleRefType { + + ADMIN("admin"), + + USER("user"); + + private String value; + + SingleRefType(String value) { + this.value = value; + } + + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static SingleRefType fromString(String s) { + for (SingleRefType b : SingleRefType.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static SingleRefType fromValue(String value) { + for (SingleRefType b : SingleRefType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SpecialModelName.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SpecialModelName.java new file mode 100644 index 0000000000..333b4dd35c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SpecialModelName.java @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class SpecialModelName { + + private Long $specialPropertyName; + + /** + * Get $specialPropertyName + * @return $specialPropertyName + **/ + public Long get$SpecialPropertyName() { + return $specialPropertyName; + } + + /** + * Set $specialPropertyName + **/ + public void set$SpecialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + } + + public SpecialModelName $specialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" $specialPropertyName: ").append(toIndentedString($specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Tag.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Tag.java new file mode 100644 index 0000000000..3be9794db1 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Tag.java @@ -0,0 +1,96 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class Tag { + + private Long id; + + private String name; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/User.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/User.java new file mode 100644 index 0000000000..07ab5974ee --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/User.java @@ -0,0 +1,237 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonValue; + + +public class User { + + private Long id; + + private String username; + + private String firstName; + + private String lastName; + + private String email; + + private String password; + + private String phone; + + /** + * User Status + **/ + private Integer userStatus; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + + /** + * Set username + **/ + public void setUsername(String username) { + this.username = username; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + public String getFirstName() { + return firstName; + } + + /** + * Set firstName + **/ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + public String getLastName() { + return lastName; + } + + /** + * Set lastName + **/ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get email + * @return email + **/ + public String getEmail() { + return email; + } + + /** + * Set email + **/ + public void setEmail(String email) { + this.email = email; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get password + * @return password + **/ + public String getPassword() { + return password; + } + + /** + * Set password + **/ + public void setPassword(String password) { + this.password = password; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get phone + * @return phone + **/ + public String getPhone() { + return phone; + } + + /** + * Set phone + **/ + public void setPhone(String phone) { + this.phone = phone; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * User Status + * @return userStatus + **/ + public Integer getUserStatus() { + return userStatus; + } + + /** + * Set userStatus + **/ + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/package-info.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/package-info.java new file mode 100644 index 0000000000..1025e91aed --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/package-info.java @@ -0,0 +1 @@ +package org.openapitools.server; \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/beans.xml b/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..125ef995e5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/beans.xml @@ -0,0 +1,9 @@ + + + + diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/microprofile-config.properties b/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..38988f20e5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,11 @@ +# Microprofile server properties + +# Application properties. This is the default greeting +app.greeting=Hello + +# Microprofile server properties +server.port=8080 +server.host=0.0.0.0 + +# Enable the optional MicroProfile Metrics REST.request metrics +metrics.rest-request.enabled=true diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/openapi.yml b/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/openapi.yml new file mode 100644 index 0000000000..a599f08c0f --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/openapi.yml @@ -0,0 +1,2168 @@ +openapi: 3.0.0 +info: + description: "This spec is mainly for testing Petstore server and contains fake\ + \ endpoints, models. Please do not use this for any other purpose. Special characters:\ + \ \" \\" + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +servers: +- description: petstore server + url: "http://{server}.swagger.io:{port}/v2" + variables: + server: + default: petstore + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" +- description: The local server + url: "https://localhost:8080/{version}" + variables: + version: + default: v2 + enum: + - v1 + - v2 +- description: The local server without variables + url: https://127.0.0.1/no_varaible +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /foo: + get: + responses: + default: + content: + application/json: + schema: + $ref: '#/components/schemas/_foo_get_default_response' + description: response + x-accepts: application/json + /pet: + post: + description: "" + operationId: addPet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + description: Successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + x-content-type: application/json + x-accepts: application/json + put: + description: "" + operationId: updatePet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + description: Successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + "405": + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + x-webclient-blocking: true + x-content-type: application/json + x-accepts: application/json + servers: + - url: http://petstore.swagger.io/v2 + - url: http://path-server-test.petstore.local/v2 + - description: test server with variables + url: "http://{server}.swagger.io:{port}/v2" + variables: + server: + default: petstore + description: target server + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - deprecated: true + description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid status value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by status + tags: + - pet + x-webclient-blocking: true + x-accepts: application/json + /pet/findByTags: + get: + deprecated: true + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + items: + type: string + type: array + uniqueItems: true + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + uniqueItems: true + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + uniqueItems: true + description: successful operation + "400": + description: Invalid tag value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by tags + tags: + - pet + x-webclient-blocking: true + x-accepts: application/json + /pet/{petId}: + delete: + description: "" + operationId: deletePet + parameters: + - explode: false + in: header + name: api_key + required: false + schema: + type: string + style: simple + - description: Pet id to delete + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + description: Successful operation + "400": + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + x-accepts: application/json + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + x-webclient-blocking: true + x-accepts: application/json + post: + description: "" + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/updatePetWithForm_request' + responses: + "200": + description: Successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + /pet/{petId}/uploadImage: + post: + description: "" + operationId: uploadFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFile_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + x-content-type: multipart/form-data + x-accepts: application/json + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + content: + application/json: + schema: + additionalProperties: + format: int32 + type: integer + type: object + description: successful operation + security: + - api_key: [] + summary: Returns pet inventories by status + tags: + - store + x-accepts: application/json + /store/order: + post: + description: "" + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid Order + summary: Place an order for a pet + tags: + - store + x-content-type: application/json + x-accepts: application/json + /store/order/{order_id}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - description: ID of the order that needs to be deleted + explode: false + in: path + name: order_id + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Delete purchase order by ID + tags: + - store + x-accepts: application/json + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generated exceptions + operationId: getOrderById + parameters: + - description: ID of pet that needs to be fetched + explode: false + in: path + name: order_id + required: true + schema: + format: int64 + maximum: 5 + minimum: 1 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Find purchase order by ID + tags: + - store + x-accepts: application/json + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + description: successful operation + summary: Create user + tags: + - user + x-content-type: application/json + x-accepts: application/json + /user/createWithArray: + post: + description: "" + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-content-type: application/json + x-accepts: application/json + /user/createWithList: + post: + description: "" + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-content-type: application/json + x-accepts: application/json + /user/login: + get: + description: "" + operationId: loginUser + parameters: + - description: The user name for login + explode: true + in: query + name: username + required: true + schema: + type: string + style: form + - description: The password for login in clear text + explode: true + in: query + name: password + required: true + schema: + type: string + style: form + responses: + "200": + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + explode: false + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when token expires + explode: false + schema: + format: date-time + type: string + style: simple + "400": + description: Invalid username/password supplied + summary: Logs user into the system + tags: + - user + x-accepts: application/json + /user/logout: + get: + description: "" + operationId: logoutUser + responses: + default: + description: successful operation + summary: Logs out current logged in user session + tags: + - user + x-accepts: application/json + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - description: The name that needs to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Delete user + tags: + - user + x-accepts: application/json + get: + description: "" + operationId: getUserByName + parameters: + - description: The name that needs to be fetched. Use user1 for testing. + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + description: successful operation + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Get user by user name + tags: + - user + x-accepts: application/json + put: + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - description: name that need to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + responses: + "400": + description: Invalid user supplied + "404": + description: User not found + summary: Updated user + tags: + - user + x-content-type: application/json + x-accepts: application/json + /fake_classname_test: + patch: + description: To test class name in snake case + operationId: testClassname + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + security: + - api_key_query: [] + summary: To test class name in snake case + tags: + - fake_classname_tags 123#$%^ + x-content-type: application/json + x-accepts: application/json + /fake: + delete: + description: Fake endpoint to test group parameters (optional) + operationId: testGroupParameters + parameters: + - description: Required String in group parameters + explode: true + in: query + name: required_string_group + required: true + schema: + type: integer + style: form + - description: Required Boolean in group parameters + explode: false + in: header + name: required_boolean_group + required: true + schema: + type: boolean + style: simple + - description: Required Integer in group parameters + explode: true + in: query + name: required_int64_group + required: true + schema: + format: int64 + type: integer + style: form + - description: String in group parameters + explode: true + in: query + name: string_group + required: false + schema: + type: integer + style: form + - description: Boolean in group parameters + explode: false + in: header + name: boolean_group + required: false + schema: + type: boolean + style: simple + - description: Integer in group parameters + explode: true + in: query + name: int64_group + required: false + schema: + format: int64 + type: integer + style: form + responses: + "400": + description: Someting wrong + security: + - bearer_test: [] + summary: Fake endpoint to test group parameters (optional) + tags: + - fake + x-group-parameters: true + x-accepts: application/json + get: + description: To test enum parameters + operationId: testEnumParameters + parameters: + - description: Header parameter enum test (string array) + explode: false + in: header + name: enum_header_string_array + required: false + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: simple + - description: Header parameter enum test (string) + explode: false + in: header + name: enum_header_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: simple + - description: Query parameter enum test (string array) + explode: true + in: query + name: enum_query_string_array + required: false + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: form + - description: Query parameter enum test (string) + explode: true + in: query + name: enum_query_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_integer + required: false + schema: + enum: + - 1 + - -2 + format: int32 + type: integer + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_double + required: false + schema: + enum: + - 1.1 + - -1.2 + format: double + type: number + style: form + - explode: true + in: query + name: enum_query_model_array + required: false + schema: + items: + $ref: '#/components/schemas/EnumClass' + type: array + style: form + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testEnumParameters_request' + responses: + "400": + description: Invalid request + "404": + description: Not found + summary: To test enum parameters + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + patch: + description: To test "client" model + operationId: testClientModel + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test "client" model + tags: + - fake + x-content-type: application/json + x-accepts: application/json + post: + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testEndpointParameters_request' + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + security: + - http_basic_test: [] + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + /fake/outer/number: + post: + description: Test serialization of outer number types + operationId: fakeOuterNumberSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterNumber' + description: Input number as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterNumber' + description: Output number + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/property/enum-int: + post: + description: Test serialization of enum (int) properties with examples + operationId: fakePropertyEnumIntegerSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterObjectWithEnumProperty' + description: Input enum (int) as post body + required: true + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterObjectWithEnumProperty' + description: Output enum (int) + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/outer/string: + post: + description: Test serialization of outer string types + operationId: fakeOuterStringSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterString' + description: Input string as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterString' + description: Output string + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/outer/boolean: + post: + description: Test serialization of outer boolean types + operationId: fakeOuterBooleanSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Input boolean as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Output boolean + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/outer/composite: + post: + description: Test serialization of object with outer number type + operationId: fakeOuterCompositeSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterComposite' + description: Input composite as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterComposite' + description: Output composite + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/jsonFormData: + get: + description: "" + operationId: testJsonFormData + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testJsonFormData_request' + responses: + "200": + description: successful operation + summary: test json serialization of form data + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + /fake/inline-additionalProperties: + post: + description: "" + operationId: testInlineAdditionalProperties + requestBody: + content: + application/json: + schema: + additionalProperties: + type: string + type: object + description: request body + required: true + responses: + "200": + description: successful operation + summary: test inline additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json + /fake/body-with-query-params: + put: + operationId: testBodyWithQueryParams + parameters: + - explode: true + in: query + name: query + required: true + schema: + type: string + style: form + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + responses: + "200": + description: Success + tags: + - fake + x-content-type: application/json + x-accepts: application/json + /another-fake/dummy: + patch: + description: To test special tags and operation ID starting with number + operationId: 123_test_@#$%_special_tags + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test special tags + tags: + - $another-fake? + x-content-type: application/json + x-accepts: application/json + /fake/body-with-file-schema: + put: + description: "For this test, the body for this request must reference a schema\ + \ named `File`." + operationId: testBodyWithFileSchema + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FileSchemaTestClass' + required: true + responses: + "200": + description: Success + tags: + - fake + x-content-type: application/json + x-accepts: application/json + /fake/body-with-binary: + put: + description: "For this test, the body has to be a binary file." + operationId: testBodyWithBinary + requestBody: + content: + image/png: + schema: + format: binary + nullable: true + type: string + description: image to upload + required: true + responses: + "200": + description: Success + tags: + - fake + x-content-type: image/png + x-accepts: application/json + /fake/test-query-parameters: + put: + description: To test the collection format in query parameters + operationId: testQueryParameterCollectionFormat + parameters: + - explode: false + in: query + name: pipe + required: true + schema: + items: + type: string + type: array + style: pipeDelimited + - explode: false + in: query + name: ioutil + required: true + schema: + items: + type: string + type: array + style: form + - explode: false + in: query + name: http + required: true + schema: + items: + type: string + type: array + style: spaceDelimited + - explode: false + in: query + name: url + required: true + schema: + items: + type: string + type: array + style: form + - explode: true + in: query + name: context + required: true + schema: + items: + type: string + type: array + style: form + - explode: true + in: query + name: language + required: false + schema: + additionalProperties: + format: string + type: string + type: object + style: form + - allowEmptyValue: true + explode: true + in: query + name: allowEmpty + required: true + schema: + type: string + style: form + responses: + "200": + description: Success + tags: + - fake + x-accepts: application/json + /fake/{petId}/uploadImageWithRequiredFile: + post: + description: "" + operationId: uploadFileWithRequiredFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFileWithRequiredFile_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image (required) + tags: + - pet + x-content-type: multipart/form-data + x-accepts: application/json + /fake/health: + get: + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/HealthCheckResult' + description: The instance started successfully + summary: Health check endpoint + tags: + - fake + x-accepts: application/json + /fake/http-signature-test: + get: + operationId: fake-http-signature-test + parameters: + - description: query parameter + explode: true + in: query + name: query_1 + required: false + schema: + type: string + style: form + - description: header parameter + explode: false + in: header + name: header_1 + required: false + schema: + type: string + style: simple + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + description: The instance started successfully + security: + - http_signature_test: [] + summary: test http signature authentication + tags: + - fake + x-content-type: application/json + x-accepts: application/json +components: + requestBodies: + UserArray: + content: + application/json: + schema: + items: + $ref: '#/components/schemas/User' + type: array + description: List of user object + required: true + Client: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + schemas: + Foo: + example: + bar: bar + properties: + bar: + default: bar + type: string + type: object + Bar: + default: bar + type: string + Order: + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: 2000-01-23T04:56:07.000+00:00 + complete: false + status: placed + properties: + id: + format: int64 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + type: boolean + type: object + xml: + name: Order + Category: + example: + name: default-name + id: 6 + properties: + id: + format: int64 + type: integer + name: + default: default-name + type: string + required: + - name + type: object + xml: + name: Category + User: + example: + firstName: firstName + lastName: lastName + password: password + userStatus: 6 + phone: phone + id: 0 + email: email + username: username + properties: + id: + format: int64 + type: integer + x-is-unique: true + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + type: object + xml: + name: User + Tag: + example: + name: name + id: 1 + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + xml: + name: Tag + Pet: + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: default-name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + type: integer + x-is-unique: true + category: + $ref: '#/components/schemas/Category' + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + uniqueItems: true + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + xml: + name: Pet + ApiResponse: + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + type: object + Return: + description: Model for testing reserved words + properties: + return: + format: int32 + type: integer + xml: + name: Return + Name: + description: Model for testing model name same as property name + properties: + name: + format: int32 + type: integer + snake_case: + format: int32 + readOnly: true + type: integer + property: + type: string + "123Number": + readOnly: true + type: integer + required: + - name + xml: + name: Name + "200_response": + description: Model for testing model name starting with number + properties: + name: + format: int32 + type: integer + class: + type: string + xml: + name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - $ref: '#/components/schemas/Dog_allOf' + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - $ref: '#/components/schemas/Cat_allOf' + Animal: + discriminator: + propertyName: className + properties: + className: + type: string + color: + default: red + type: string + required: + - className + type: object + AnimalFarm: + items: + $ref: '#/components/schemas/Animal' + type: array + format_test: + properties: + integer: + maximum: 100 + minimum: 10 + type: integer + int32: + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + format: int64 + type: integer + number: + maximum: 543.2 + minimum: 32.1 + type: number + float: + format: float + maximum: 987.6 + minimum: 54.3 + type: number + double: + format: double + maximum: 123.4 + minimum: 67.8 + type: number + decimal: + format: number + type: string + string: + pattern: "/[a-z]/i" + type: string + byte: + format: byte + type: string + binary: + format: binary + type: string + date: + format: date + type: string + dateTime: + format: date-time + type: string + uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + type: string + password: + format: password + maxLength: 64 + minLength: 10 + type: string + pattern_with_digits: + description: A string that is a 10 digit number. Can have leading zeros. + pattern: "^\\d{10}$" + type: string + pattern_with_digits_and_delimiter: + description: A string starting with 'image_' (case insensitive) and one + to three digits following i.e. Image_01. + pattern: "/^image_\\d{1,3}$/i" + type: string + required: + - byte + - date + - number + - password + type: object + EnumClass: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + Enum_Test: + properties: + enum_string: + enum: + - UPPER + - lower + - "" + type: string + enum_string_required: + enum: + - UPPER + - lower + - "" + type: string + enum_integer: + enum: + - 1 + - -1 + format: int32 + type: integer + enum_number: + enum: + - 1.1 + - -1.2 + format: double + type: number + outerEnum: + $ref: '#/components/schemas/OuterEnum' + outerEnumInteger: + $ref: '#/components/schemas/OuterEnumInteger' + outerEnumDefaultValue: + $ref: '#/components/schemas/OuterEnumDefaultValue' + outerEnumIntegerDefaultValue: + $ref: '#/components/schemas/OuterEnumIntegerDefaultValue' + required: + - enum_string_required + type: object + AdditionalPropertiesClass: + properties: + map_property: + additionalProperties: + type: string + type: object + map_of_map_property: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + type: object + MixedPropertiesAndAdditionalPropertiesClass: + properties: + uuid: + format: uuid + type: string + dateTime: + format: date-time + type: string + map: + additionalProperties: + $ref: '#/components/schemas/Animal' + type: object + type: object + List: + properties: + "123-list": + type: string + type: object + Client: + example: + client: client + properties: + client: + type: string + type: object + ReadOnlyFirst: + properties: + bar: + readOnly: true + type: string + baz: + type: string + type: object + hasOnlyReadOnly: + properties: + bar: + readOnly: true + type: string + foo: + readOnly: true + type: string + type: object + Capitalization: + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: | + Name of the pet + type: string + type: object + MapTest: + properties: + map_map_of_string: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + map_of_enum_string: + additionalProperties: + enum: + - UPPER + - lower + type: string + type: object + direct_map: + additionalProperties: + type: boolean + type: object + indirect_map: + additionalProperties: + type: boolean + type: object + type: object + ArrayTest: + properties: + array_of_string: + items: + type: string + maxItems: 3 + minItems: 0 + type: array + array_array_of_integer: + items: + items: + format: int64 + type: integer + type: array + type: array + array_array_of_model: + items: + items: + $ref: '#/components/schemas/ReadOnlyFirst' + type: array + type: array + type: object + NumberOnly: + properties: + JustNumber: + type: number + type: object + ArrayOfNumberOnly: + properties: + ArrayNumber: + items: + type: number + type: array + type: object + ArrayOfArrayOfNumberOnly: + properties: + ArrayArrayNumber: + items: + items: + type: number + type: array + type: array + type: object + EnumArrays: + properties: + just_symbol: + enum: + - '>=' + - $ + type: string + array_enum: + items: + enum: + - fish + - crab + type: string + type: array + type: object + OuterEnum: + enum: + - placed + - approved + - delivered + nullable: true + type: string + OuterEnumInteger: + enum: + - 0 + - 1 + - 2 + example: 2 + type: integer + OuterEnumDefaultValue: + default: placed + enum: + - placed + - approved + - delivered + type: string + OuterEnumIntegerDefaultValue: + default: 0 + enum: + - 0 + - 1 + - 2 + type: integer + OuterComposite: + example: + my_string: my_string + my_number: 0.8008281904610115 + my_boolean: true + properties: + my_number: + type: number + my_string: + type: string + my_boolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + type: object + OuterNumber: + type: number + OuterString: + type: string + OuterBoolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + StringBooleanMap: + additionalProperties: + type: boolean + type: object + FileSchemaTestClass: + example: + file: + sourceURI: sourceURI + files: + - sourceURI: sourceURI + - sourceURI: sourceURI + properties: + file: + $ref: '#/components/schemas/File' + files: + items: + $ref: '#/components/schemas/File' + type: array + type: object + File: + description: Must be named `File` for test. + example: + sourceURI: sourceURI + properties: + sourceURI: + description: Test capitalization + type: string + type: object + _special_model.name_: + properties: + $special[property.name]: + format: int64 + type: integer + xml: + name: "$special[model.name]" + HealthCheckResult: + description: Just a string to inform instance is up and running. Make it nullable + in hope to get it as pointer in generated model. + example: + NullableMessage: NullableMessage + properties: + NullableMessage: + nullable: true + type: string + type: object + NullableClass: + additionalProperties: + nullable: true + type: object + properties: + integer_prop: + nullable: true + type: integer + number_prop: + nullable: true + type: number + boolean_prop: + nullable: true + type: boolean + string_prop: + nullable: true + type: string + date_prop: + format: date + nullable: true + type: string + datetime_prop: + format: date-time + nullable: true + type: string + array_nullable_prop: + items: + type: object + nullable: true + type: array + array_and_items_nullable_prop: + items: + nullable: true + type: object + nullable: true + type: array + array_items_nullable: + items: + nullable: true + type: object + type: array + object_nullable_prop: + additionalProperties: + type: object + nullable: true + type: object + object_and_items_nullable_prop: + additionalProperties: + nullable: true + type: object + nullable: true + type: object + object_items_nullable: + additionalProperties: + nullable: true + type: object + type: object + type: object + OuterObjectWithEnumProperty: + example: + value: 2 + properties: + value: + $ref: '#/components/schemas/OuterEnumInteger' + required: + - value + type: object + DeprecatedObject: + deprecated: true + properties: + name: + type: string + type: object + ObjectWithDeprecatedFields: + properties: + uuid: + type: string + id: + deprecated: true + type: number + deprecatedRef: + $ref: '#/components/schemas/DeprecatedObject' + bars: + deprecated: true + items: + $ref: '#/components/schemas/Bar' + type: array + type: object + AllOfWithSingleRef: + properties: + username: + type: string + SingleRefType: + allOf: + - $ref: '#/components/schemas/SingleRefType' + type: object + SingleRefType: + enum: + - admin + - user + title: SingleRefType + type: string + _foo_get_default_response: + example: + string: + bar: bar + properties: + string: + $ref: '#/components/schemas/Foo' + type: object + updatePetWithForm_request: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + uploadFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + testEnumParameters_request: + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + enum_form_string: + default: -efg + description: Form parameter enum test (string) + enum: + - _abc + - -efg + - (xyz) + type: string + type: object + testEndpointParameters_request: + properties: + integer: + description: None + maximum: 100 + minimum: 10 + type: integer + int32: + description: None + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + description: None + format: int64 + type: integer + number: + description: None + maximum: 543.2 + minimum: 32.1 + type: number + float: + description: None + format: float + maximum: 987.6 + type: number + double: + description: None + format: double + maximum: 123.4 + minimum: 67.8 + type: number + string: + description: None + pattern: "/[a-z]/i" + type: string + pattern_without_delimiter: + description: None + pattern: "^[A-Z].*" + type: string + byte: + description: None + format: byte + type: string + binary: + description: None + format: binary + type: string + date: + description: None + format: date + type: string + dateTime: + description: None + format: date-time + type: string + password: + description: None + format: password + maxLength: 64 + minLength: 10 + type: string + callback: + description: None + type: string + required: + - byte + - double + - number + - pattern_without_delimiter + type: object + testJsonFormData_request: + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + type: object + uploadFileWithRequiredFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + format: binary + type: string + required: + - requiredFile + type: object + Dog_allOf: + properties: + breed: + type: string + type: object + example: null + Cat_allOf: + properties: + declawed: + type: boolean + type: object + example: null + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey + api_key_query: + in: query + name: api_key_query + type: apiKey + http_basic_test: + scheme: basic + type: http + bearer_test: + bearerFormat: JWT + scheme: bearer + type: http + http_signature_test: + scheme: signature + type: http diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/resources/logging.properties b/samples/server/petstore/java-helidon-server/mp/src/main/resources/logging.properties new file mode 100644 index 0000000000..cd238eb661 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/main/resources/logging.properties @@ -0,0 +1,19 @@ + +# Example Logging Configuration File +# For more information see $JAVA_HOME/jre/lib/logging.properties + +# Send messages to the console +handlers=io.helidon.common.HelidonConsoleHandler + +# HelidonConsoleHandler uses a SimpleFormatter subclass that replaces "!thread!" with the current thread +java.util.logging.SimpleFormatter.format=%1$tY.%1$tm.%1$td %1$tH:%1$tM:%1$tS %4$s %3$s !thread!: %5$s%6$s%n + +# Global logging level. Can be overridden by specific loggers +.level=INFO + +# Component specific log levels +#io.helidon.webserver.level=INFO +#io.helidon.config.level=INFO +#io.helidon.security.level=INFO +#io.helidon.common.level=INFO +#io.netty.level=INFO diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/AdditionalPropertiesClassTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/AdditionalPropertiesClassTest.java new file mode 100644 index 0000000000..87b0cf9126 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/AdditionalPropertiesClassTest.java @@ -0,0 +1,50 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for AdditionalPropertiesClass + */ +public class AdditionalPropertiesClassTest { + private final AdditionalPropertiesClass model = new AdditionalPropertiesClass(); + + /** + * Model tests for AdditionalPropertiesClass + */ + @Test + public void testAdditionalPropertiesClass() { + // TODO: test AdditionalPropertiesClass + } + + /** + * Test the property 'mapProperty' + */ + @Test + public void mapPropertyTest() { + // TODO: test mapProperty + } + + /** + * Test the property 'mapOfMapProperty' + */ + @Test + public void mapOfMapPropertyTest() { + // TODO: test mapOfMapProperty + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/AllOfWithSingleRefTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/AllOfWithSingleRefTest.java new file mode 100644 index 0000000000..83a14ba827 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/AllOfWithSingleRefTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.openapitools.server.model.SingleRefType; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for AllOfWithSingleRef + */ +public class AllOfWithSingleRefTest { + private final AllOfWithSingleRef model = new AllOfWithSingleRef(); + + /** + * Model tests for AllOfWithSingleRef + */ + @Test + public void testAllOfWithSingleRef() { + // TODO: test AllOfWithSingleRef + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'singleRefType' + */ + @Test + public void singleRefTypeTest() { + // TODO: test singleRefType + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/AnimalTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/AnimalTest.java new file mode 100644 index 0000000000..1299d46ba6 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/AnimalTest.java @@ -0,0 +1,53 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Cat; +import org.openapitools.server.model.Dog; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Animal + */ +public class AnimalTest { + private final Animal model = new Animal(); + + /** + * Model tests for Animal + */ + @Test + public void testAnimal() { + // TODO: test Animal + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnlyTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnlyTest.java new file mode 100644 index 0000000000..d67cac0b05 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnlyTest.java @@ -0,0 +1,43 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayOfArrayOfNumberOnly + */ +public class ArrayOfArrayOfNumberOnlyTest { + private final ArrayOfArrayOfNumberOnly model = new ArrayOfArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfArrayOfNumberOnly + */ + @Test + public void testArrayOfArrayOfNumberOnly() { + // TODO: test ArrayOfArrayOfNumberOnly + } + + /** + * Test the property 'arrayArrayNumber' + */ + @Test + public void arrayArrayNumberTest() { + // TODO: test arrayArrayNumber + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ArrayOfNumberOnlyTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ArrayOfNumberOnlyTest.java new file mode 100644 index 0000000000..150ba7b070 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ArrayOfNumberOnlyTest.java @@ -0,0 +1,43 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayOfNumberOnly + */ +public class ArrayOfNumberOnlyTest { + private final ArrayOfNumberOnly model = new ArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfNumberOnly + */ + @Test + public void testArrayOfNumberOnly() { + // TODO: test ArrayOfNumberOnly + } + + /** + * Test the property 'arrayNumber' + */ + @Test + public void arrayNumberTest() { + // TODO: test arrayNumber + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ArrayTestTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ArrayTestTest.java new file mode 100644 index 0000000000..a2d4f750e1 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ArrayTestTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.ReadOnlyFirst; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayTest + */ +public class ArrayTestTest { + private final ArrayTest model = new ArrayTest(); + + /** + * Model tests for ArrayTest + */ + @Test + public void testArrayTest() { + // TODO: test ArrayTest + } + + /** + * Test the property 'arrayOfString' + */ + @Test + public void arrayOfStringTest() { + // TODO: test arrayOfString + } + + /** + * Test the property 'arrayArrayOfInteger' + */ + @Test + public void arrayArrayOfIntegerTest() { + // TODO: test arrayArrayOfInteger + } + + /** + * Test the property 'arrayArrayOfModel' + */ + @Test + public void arrayArrayOfModelTest() { + // TODO: test arrayArrayOfModel + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CapitalizationTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CapitalizationTest.java new file mode 100644 index 0000000000..084a2885fc --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CapitalizationTest.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Capitalization + */ +public class CapitalizationTest { + private final Capitalization model = new Capitalization(); + + /** + * Model tests for Capitalization + */ + @Test + public void testCapitalization() { + // TODO: test Capitalization + } + + /** + * Test the property 'smallCamel' + */ + @Test + public void smallCamelTest() { + // TODO: test smallCamel + } + + /** + * Test the property 'capitalCamel' + */ + @Test + public void capitalCamelTest() { + // TODO: test capitalCamel + } + + /** + * Test the property 'smallSnake' + */ + @Test + public void smallSnakeTest() { + // TODO: test smallSnake + } + + /** + * Test the property 'capitalSnake' + */ + @Test + public void capitalSnakeTest() { + // TODO: test capitalSnake + } + + /** + * Test the property 'scAETHFlowPoints' + */ + @Test + public void scAETHFlowPointsTest() { + // TODO: test scAETHFlowPoints + } + + /** + * Test the property 'ATT_NAME' + */ + @Test + public void ATT_NAMETest() { + // TODO: test ATT_NAME + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CatAllOfTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CatAllOfTest.java new file mode 100644 index 0000000000..ab121c24d9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CatAllOfTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for CatAllOf + */ +public class CatAllOfTest { + private final CatAllOf model = new CatAllOf(); + + /** + * Model tests for CatAllOf + */ + @Test + public void testCatAllOf() { + // TODO: test CatAllOf + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CatTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CatTest.java new file mode 100644 index 0000000000..121dcc9756 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CatTest.java @@ -0,0 +1,60 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Animal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Cat + */ +public class CatTest { + private final Cat model = new Cat(); + + /** + * Model tests for Cat + */ + @Test + public void testCat() { + // TODO: test Cat + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CategoryTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CategoryTest.java new file mode 100644 index 0000000000..2618c8fd93 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/CategoryTest.java @@ -0,0 +1,48 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ClassModelTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ClassModelTest.java new file mode 100644 index 0000000000..f62de6d1cc --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ClassModelTest.java @@ -0,0 +1,40 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ClassModel + */ +public class ClassModelTest { + private final ClassModel model = new ClassModel(); + + /** + * Model tests for ClassModel + */ + @Test + public void testClassModel() { + // TODO: test ClassModel + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ClientTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ClientTest.java new file mode 100644 index 0000000000..a9f4c21ebf --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ClientTest.java @@ -0,0 +1,40 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Client + */ +public class ClientTest { + private final Client model = new Client(); + + /** + * Model tests for Client + */ + @Test + public void testClient() { + // TODO: test Client + } + + /** + * Test the property 'client' + */ + @Test + public void clientTest() { + // TODO: test client + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/DeprecatedObjectTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/DeprecatedObjectTest.java new file mode 100644 index 0000000000..9ad380437c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/DeprecatedObjectTest.java @@ -0,0 +1,40 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for DeprecatedObject + */ +public class DeprecatedObjectTest { + private final DeprecatedObject model = new DeprecatedObject(); + + /** + * Model tests for DeprecatedObject + */ + @Test + public void testDeprecatedObject() { + // TODO: test DeprecatedObject + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/DogAllOfTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/DogAllOfTest.java new file mode 100644 index 0000000000..2759c9a2eb --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/DogAllOfTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for DogAllOf + */ +public class DogAllOfTest { + private final DogAllOf model = new DogAllOf(); + + /** + * Model tests for DogAllOf + */ + @Test + public void testDogAllOf() { + // TODO: test DogAllOf + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/DogTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/DogTest.java new file mode 100644 index 0000000000..70765267f0 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/DogTest.java @@ -0,0 +1,60 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Animal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Dog + */ +public class DogTest { + private final Dog model = new Dog(); + + /** + * Model tests for Dog + */ + @Test + public void testDog() { + // TODO: test Dog + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/EnumArraysTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/EnumArraysTest.java new file mode 100644 index 0000000000..42b3832090 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/EnumArraysTest.java @@ -0,0 +1,52 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumArrays + */ +public class EnumArraysTest { + private final EnumArrays model = new EnumArrays(); + + /** + * Model tests for EnumArrays + */ + @Test + public void testEnumArrays() { + // TODO: test EnumArrays + } + + /** + * Test the property 'justSymbol' + */ + @Test + public void justSymbolTest() { + // TODO: test justSymbol + } + + /** + * Test the property 'arrayEnum' + */ + @Test + public void arrayEnumTest() { + // TODO: test arrayEnum + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/EnumClassTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/EnumClassTest.java new file mode 100644 index 0000000000..9c02e17dac --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/EnumClassTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumClass + */ +public class EnumClassTest { + /** + * Model tests for EnumClass + */ + @Test + public void testEnumClass() { + // TODO: test EnumClass + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/EnumTestTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/EnumTestTest.java new file mode 100644 index 0000000000..7c95fed8bb --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/EnumTestTest.java @@ -0,0 +1,104 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import org.openapitools.server.model.OuterEnum; +import org.openapitools.server.model.OuterEnumDefaultValue; +import org.openapitools.server.model.OuterEnumInteger; +import org.openapitools.server.model.OuterEnumIntegerDefaultValue; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumTest + */ +public class EnumTestTest { + private final EnumTest model = new EnumTest(); + + /** + * Model tests for EnumTest + */ + @Test + public void testEnumTest() { + // TODO: test EnumTest + } + + /** + * Test the property 'enumString' + */ + @Test + public void enumStringTest() { + // TODO: test enumString + } + + /** + * Test the property 'enumStringRequired' + */ + @Test + public void enumStringRequiredTest() { + // TODO: test enumStringRequired + } + + /** + * Test the property 'enumInteger' + */ + @Test + public void enumIntegerTest() { + // TODO: test enumInteger + } + + /** + * Test the property 'enumNumber' + */ + @Test + public void enumNumberTest() { + // TODO: test enumNumber + } + + /** + * Test the property 'outerEnum' + */ + @Test + public void outerEnumTest() { + // TODO: test outerEnum + } + + /** + * Test the property 'outerEnumInteger' + */ + @Test + public void outerEnumIntegerTest() { + // TODO: test outerEnumInteger + } + + /** + * Test the property 'outerEnumDefaultValue' + */ + @Test + public void outerEnumDefaultValueTest() { + // TODO: test outerEnumDefaultValue + } + + /** + * Test the property 'outerEnumIntegerDefaultValue' + */ + @Test + public void outerEnumIntegerDefaultValueTest() { + // TODO: test outerEnumIntegerDefaultValue + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FileSchemaTestClassTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FileSchemaTestClassTest.java new file mode 100644 index 0000000000..fbabc01db3 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FileSchemaTestClassTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.ModelFile; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FileSchemaTestClass + */ +public class FileSchemaTestClassTest { + private final FileSchemaTestClass model = new FileSchemaTestClass(); + + /** + * Model tests for FileSchemaTestClass + */ + @Test + public void testFileSchemaTestClass() { + // TODO: test FileSchemaTestClass + } + + /** + * Test the property '_file' + */ + @Test + public void _fileTest() { + // TODO: test _file + } + + /** + * Test the property 'files' + */ + @Test + public void filesTest() { + // TODO: test files + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FooGetDefaultResponseTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FooGetDefaultResponseTest.java new file mode 100644 index 0000000000..d0dc33cef5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FooGetDefaultResponseTest.java @@ -0,0 +1,42 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.openapitools.server.model.Foo; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FooGetDefaultResponse + */ +public class FooGetDefaultResponseTest { + private final FooGetDefaultResponse model = new FooGetDefaultResponse(); + + /** + * Model tests for FooGetDefaultResponse + */ + @Test + public void testFooGetDefaultResponse() { + // TODO: test FooGetDefaultResponse + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FooTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FooTest.java new file mode 100644 index 0000000000..39abe05aad --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FooTest.java @@ -0,0 +1,40 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Foo + */ +public class FooTest { + private final Foo model = new Foo(); + + /** + * Model tests for Foo + */ + @Test + public void testFoo() { + // TODO: test Foo + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FormatTestTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FormatTestTest.java new file mode 100644 index 0000000000..5d98845296 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/FormatTestTest.java @@ -0,0 +1,166 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FormatTest + */ +public class FormatTestTest { + private final FormatTest model = new FormatTest(); + + /** + * Model tests for FormatTest + */ + @Test + public void testFormatTest() { + // TODO: test FormatTest + } + + /** + * Test the property 'integer' + */ + @Test + public void integerTest() { + // TODO: test integer + } + + /** + * Test the property 'int32' + */ + @Test + public void int32Test() { + // TODO: test int32 + } + + /** + * Test the property 'int64' + */ + @Test + public void int64Test() { + // TODO: test int64 + } + + /** + * Test the property 'number' + */ + @Test + public void numberTest() { + // TODO: test number + } + + /** + * Test the property '_float' + */ + @Test + public void _floatTest() { + // TODO: test _float + } + + /** + * Test the property '_double' + */ + @Test + public void _doubleTest() { + // TODO: test _double + } + + /** + * Test the property 'decimal' + */ + @Test + public void decimalTest() { + // TODO: test decimal + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + + /** + * Test the property '_byte' + */ + @Test + public void _byteTest() { + // TODO: test _byte + } + + /** + * Test the property 'binary' + */ + @Test + public void binaryTest() { + // TODO: test binary + } + + /** + * Test the property 'date' + */ + @Test + public void dateTest() { + // TODO: test date + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'patternWithDigits' + */ + @Test + public void patternWithDigitsTest() { + // TODO: test patternWithDigits + } + + /** + * Test the property 'patternWithDigitsAndDelimiter' + */ + @Test + public void patternWithDigitsAndDelimiterTest() { + // TODO: test patternWithDigitsAndDelimiter + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/HasOnlyReadOnlyTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/HasOnlyReadOnlyTest.java new file mode 100644 index 0000000000..5a56ddcc24 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/HasOnlyReadOnlyTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for HasOnlyReadOnly + */ +public class HasOnlyReadOnlyTest { + private final HasOnlyReadOnly model = new HasOnlyReadOnly(); + + /** + * Model tests for HasOnlyReadOnly + */ + @Test + public void testHasOnlyReadOnly() { + // TODO: test HasOnlyReadOnly + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'foo' + */ + @Test + public void fooTest() { + // TODO: test foo + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/HealthCheckResultTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/HealthCheckResultTest.java new file mode 100644 index 0000000000..be4be735e5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/HealthCheckResultTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for HealthCheckResult + */ +public class HealthCheckResultTest { + private final HealthCheckResult model = new HealthCheckResult(); + + /** + * Model tests for HealthCheckResult + */ + @Test + public void testHealthCheckResult() { + // TODO: test HealthCheckResult + } + + /** + * Test the property 'nullableMessage' + */ + @Test + public void nullableMessageTest() { + // TODO: test nullableMessage + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/MapTestTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/MapTestTest.java new file mode 100644 index 0000000000..3c6c9450be --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/MapTestTest.java @@ -0,0 +1,68 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for MapTest + */ +public class MapTestTest { + private final MapTest model = new MapTest(); + + /** + * Model tests for MapTest + */ + @Test + public void testMapTest() { + // TODO: test MapTest + } + + /** + * Test the property 'mapMapOfString' + */ + @Test + public void mapMapOfStringTest() { + // TODO: test mapMapOfString + } + + /** + * Test the property 'mapOfEnumString' + */ + @Test + public void mapOfEnumStringTest() { + // TODO: test mapOfEnumString + } + + /** + * Test the property 'directMap' + */ + @Test + public void directMapTest() { + // TODO: test directMap + } + + /** + * Test the property 'indirectMap' + */ + @Test + public void indirectMapTest() { + // TODO: test indirectMap + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClassTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClassTest.java new file mode 100644 index 0000000000..9b15f918a9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClassTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.openapitools.server.model.Animal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ +public class MixedPropertiesAndAdditionalPropertiesClassTest { + private final MixedPropertiesAndAdditionalPropertiesClass model = new MixedPropertiesAndAdditionalPropertiesClass(); + + /** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ + @Test + public void testMixedPropertiesAndAdditionalPropertiesClass() { + // TODO: test MixedPropertiesAndAdditionalPropertiesClass + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'map' + */ + @Test + public void mapTest() { + // TODO: test map + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/Model200ResponseTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/Model200ResponseTest.java new file mode 100644 index 0000000000..33b6d47572 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/Model200ResponseTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Model200Response + */ +public class Model200ResponseTest { + private final Model200Response model = new Model200Response(); + + /** + * Model tests for Model200Response + */ + @Test + public void testModel200Response() { + // TODO: test Model200Response + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelApiResponseTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelApiResponseTest.java new file mode 100644 index 0000000000..43cb48513c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelApiResponseTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelFileTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelFileTest.java new file mode 100644 index 0000000000..ff03280b7e --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelFileTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelFile + */ +public class ModelFileTest { + private final ModelFile model = new ModelFile(); + + /** + * Model tests for ModelFile + */ + @Test + public void testModelFile() { + // TODO: test ModelFile + } + + /** + * Test the property 'sourceURI' + */ + @Test + public void sourceURITest() { + // TODO: test sourceURI + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelListTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelListTest.java new file mode 100644 index 0000000000..7f228b1913 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelListTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelList + */ +public class ModelListTest { + private final ModelList model = new ModelList(); + + /** + * Model tests for ModelList + */ + @Test + public void testModelList() { + // TODO: test ModelList + } + + /** + * Test the property '_123list' + */ + @Test + public void _123listTest() { + // TODO: test _123list + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelReturnTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelReturnTest.java new file mode 100644 index 0000000000..e6af66eb00 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ModelReturnTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelReturn + */ +public class ModelReturnTest { + private final ModelReturn model = new ModelReturn(); + + /** + * Model tests for ModelReturn + */ + @Test + public void testModelReturn() { + // TODO: test ModelReturn + } + + /** + * Test the property '_return' + */ + @Test + public void _returnTest() { + // TODO: test _return + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/NameTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/NameTest.java new file mode 100644 index 0000000000..13114ab4e7 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/NameTest.java @@ -0,0 +1,64 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Name + */ +public class NameTest { + private final Name model = new Name(); + + /** + * Model tests for Name + */ + @Test + public void testName() { + // TODO: test Name + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'snakeCase' + */ + @Test + public void snakeCaseTest() { + // TODO: test snakeCase + } + + /** + * Test the property 'property' + */ + @Test + public void propertyTest() { + // TODO: test property + } + + /** + * Test the property '_123number' + */ + @Test + public void _123numberTest() { + // TODO: test _123number + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/NullableClassTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/NullableClassTest.java new file mode 100644 index 0000000000..e2f2dd91bf --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/NullableClassTest.java @@ -0,0 +1,136 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for NullableClass + */ +public class NullableClassTest { + private final NullableClass model = new NullableClass(); + + /** + * Model tests for NullableClass + */ + @Test + public void testNullableClass() { + // TODO: test NullableClass + } + + /** + * Test the property 'integerProp' + */ + @Test + public void integerPropTest() { + // TODO: test integerProp + } + + /** + * Test the property 'numberProp' + */ + @Test + public void numberPropTest() { + // TODO: test numberProp + } + + /** + * Test the property 'booleanProp' + */ + @Test + public void booleanPropTest() { + // TODO: test booleanProp + } + + /** + * Test the property 'stringProp' + */ + @Test + public void stringPropTest() { + // TODO: test stringProp + } + + /** + * Test the property 'dateProp' + */ + @Test + public void datePropTest() { + // TODO: test dateProp + } + + /** + * Test the property 'datetimeProp' + */ + @Test + public void datetimePropTest() { + // TODO: test datetimeProp + } + + /** + * Test the property 'arrayNullableProp' + */ + @Test + public void arrayNullablePropTest() { + // TODO: test arrayNullableProp + } + + /** + * Test the property 'arrayAndItemsNullableProp' + */ + @Test + public void arrayAndItemsNullablePropTest() { + // TODO: test arrayAndItemsNullableProp + } + + /** + * Test the property 'arrayItemsNullable' + */ + @Test + public void arrayItemsNullableTest() { + // TODO: test arrayItemsNullable + } + + /** + * Test the property 'objectNullableProp' + */ + @Test + public void objectNullablePropTest() { + // TODO: test objectNullableProp + } + + /** + * Test the property 'objectAndItemsNullableProp' + */ + @Test + public void objectAndItemsNullablePropTest() { + // TODO: test objectAndItemsNullableProp + } + + /** + * Test the property 'objectItemsNullable' + */ + @Test + public void objectItemsNullableTest() { + // TODO: test objectItemsNullable + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/NumberOnlyTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/NumberOnlyTest.java new file mode 100644 index 0000000000..dede232a8f --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/NumberOnlyTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for NumberOnly + */ +public class NumberOnlyTest { + private final NumberOnly model = new NumberOnly(); + + /** + * Model tests for NumberOnly + */ + @Test + public void testNumberOnly() { + // TODO: test NumberOnly + } + + /** + * Test the property 'justNumber' + */ + @Test + public void justNumberTest() { + // TODO: test justNumber + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ObjectWithDeprecatedFieldsTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ObjectWithDeprecatedFieldsTest.java new file mode 100644 index 0000000000..55cf9bedb0 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ObjectWithDeprecatedFieldsTest.java @@ -0,0 +1,68 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.DeprecatedObject; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ObjectWithDeprecatedFields + */ +public class ObjectWithDeprecatedFieldsTest { + private final ObjectWithDeprecatedFields model = new ObjectWithDeprecatedFields(); + + /** + * Model tests for ObjectWithDeprecatedFields + */ + @Test + public void testObjectWithDeprecatedFields() { + // TODO: test ObjectWithDeprecatedFields + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'deprecatedRef' + */ + @Test + public void deprecatedRefTest() { + // TODO: test deprecatedRef + } + + /** + * Test the property 'bars' + */ + @Test + public void barsTest() { + // TODO: test bars + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OrderTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OrderTest.java new file mode 100644 index 0000000000..9060765552 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OrderTest.java @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterCompositeTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterCompositeTest.java new file mode 100644 index 0000000000..f61dfbaf41 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterCompositeTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterComposite + */ +public class OuterCompositeTest { + private final OuterComposite model = new OuterComposite(); + + /** + * Model tests for OuterComposite + */ + @Test + public void testOuterComposite() { + // TODO: test OuterComposite + } + + /** + * Test the property 'myNumber' + */ + @Test + public void myNumberTest() { + // TODO: test myNumber + } + + /** + * Test the property 'myString' + */ + @Test + public void myStringTest() { + // TODO: test myString + } + + /** + * Test the property 'myBoolean' + */ + @Test + public void myBooleanTest() { + // TODO: test myBoolean + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumDefaultValueTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumDefaultValueTest.java new file mode 100644 index 0000000000..55d00b4918 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumDefaultValueTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumDefaultValue + */ +public class OuterEnumDefaultValueTest { + /** + * Model tests for OuterEnumDefaultValue + */ + @Test + public void testOuterEnumDefaultValue() { + // TODO: test OuterEnumDefaultValue + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumIntegerDefaultValueTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumIntegerDefaultValueTest.java new file mode 100644 index 0000000000..6a5e46c612 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumIntegerDefaultValueTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumIntegerDefaultValue + */ +public class OuterEnumIntegerDefaultValueTest { + /** + * Model tests for OuterEnumIntegerDefaultValue + */ + @Test + public void testOuterEnumIntegerDefaultValue() { + // TODO: test OuterEnumIntegerDefaultValue + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumIntegerTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumIntegerTest.java new file mode 100644 index 0000000000..d6c32e321d --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumIntegerTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumInteger + */ +public class OuterEnumIntegerTest { + /** + * Model tests for OuterEnumInteger + */ + @Test + public void testOuterEnumInteger() { + // TODO: test OuterEnumInteger + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumTest.java new file mode 100644 index 0000000000..5ea29d2138 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterEnumTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnum + */ +public class OuterEnumTest { + /** + * Model tests for OuterEnum + */ + @Test + public void testOuterEnum() { + // TODO: test OuterEnum + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterObjectWithEnumPropertyTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterObjectWithEnumPropertyTest.java new file mode 100644 index 0000000000..d40c868a41 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/OuterObjectWithEnumPropertyTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.openapitools.server.model.OuterEnumInteger; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterObjectWithEnumProperty + */ +public class OuterObjectWithEnumPropertyTest { + private final OuterObjectWithEnumProperty model = new OuterObjectWithEnumProperty(); + + /** + * Model tests for OuterObjectWithEnumProperty + */ + @Test + public void testOuterObjectWithEnumProperty() { + // TODO: test OuterObjectWithEnumProperty + } + + /** + * Test the property 'value' + */ + @Test + public void valueTest() { + // TODO: test value + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/PetTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/PetTest.java new file mode 100644 index 0000000000..bc913dd50a --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/PetTest.java @@ -0,0 +1,89 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.openapitools.server.model.Category; +import org.openapitools.server.model.Tag; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ReadOnlyFirstTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ReadOnlyFirstTest.java new file mode 100644 index 0000000000..2fe4c7fc6b --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/ReadOnlyFirstTest.java @@ -0,0 +1,48 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ReadOnlyFirst + */ +public class ReadOnlyFirstTest { + private final ReadOnlyFirst model = new ReadOnlyFirst(); + + /** + * Model tests for ReadOnlyFirst + */ + @Test + public void testReadOnlyFirst() { + // TODO: test ReadOnlyFirst + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'baz' + */ + @Test + public void bazTest() { + // TODO: test baz + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/SingleRefTypeTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/SingleRefTypeTest.java new file mode 100644 index 0000000000..4ae2c23f4c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/SingleRefTypeTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for SingleRefType + */ +public class SingleRefTypeTest { + /** + * Model tests for SingleRefType + */ + @Test + public void testSingleRefType() { + // TODO: test SingleRefType + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/SpecialModelNameTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/SpecialModelNameTest.java new file mode 100644 index 0000000000..809e043f8e --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/SpecialModelNameTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for SpecialModelName + */ +public class SpecialModelNameTest { + private final SpecialModelName model = new SpecialModelName(); + + /** + * Model tests for SpecialModelName + */ + @Test + public void testSpecialModelName() { + // TODO: test SpecialModelName + } + + /** + * Test the property '$specialPropertyName' + */ + @Test + public void $specialPropertyNameTest() { + // TODO: test $specialPropertyName + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/TagTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/TagTest.java new file mode 100644 index 0000000000..4d0d708bf9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/TagTest.java @@ -0,0 +1,48 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/UserTest.java b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/UserTest.java new file mode 100644 index 0000000000..ba936a2080 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/mp/src/test/java/org/openapitools/server/model/UserTest.java @@ -0,0 +1,96 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/.openapi-generator-ignore b/samples/server/petstore/java-helidon-server/se/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/.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/server/petstore/java-helidon-server/se/.openapi-generator/FILES b/samples/server/petstore/java-helidon-server/se/.openapi-generator/FILES new file mode 100644 index 0000000000..93bbc6b3b0 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/.openapi-generator/FILES @@ -0,0 +1,73 @@ +README.md +pom.xml +src/main/java/org/openapitools/server/Main.java +src/main/java/org/openapitools/server/RFC3339DateFormat.java +src/main/java/org/openapitools/server/api/AnotherFakeService.java +src/main/java/org/openapitools/server/api/AnotherFakeServiceImpl.java +src/main/java/org/openapitools/server/api/DefaultService.java +src/main/java/org/openapitools/server/api/DefaultServiceImpl.java +src/main/java/org/openapitools/server/api/FakeClassnameTags123Service.java +src/main/java/org/openapitools/server/api/FakeClassnameTags123ServiceImpl.java +src/main/java/org/openapitools/server/api/FakeService.java +src/main/java/org/openapitools/server/api/FakeServiceImpl.java +src/main/java/org/openapitools/server/api/JsonProvider.java +src/main/java/org/openapitools/server/api/PetService.java +src/main/java/org/openapitools/server/api/PetServiceImpl.java +src/main/java/org/openapitools/server/api/StoreService.java +src/main/java/org/openapitools/server/api/StoreServiceImpl.java +src/main/java/org/openapitools/server/api/UserService.java +src/main/java/org/openapitools/server/api/UserServiceImpl.java +src/main/java/org/openapitools/server/api/ValidatorUtils.java +src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java +src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java +src/main/java/org/openapitools/server/model/Animal.java +src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java +src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java +src/main/java/org/openapitools/server/model/ArrayTest.java +src/main/java/org/openapitools/server/model/Capitalization.java +src/main/java/org/openapitools/server/model/Cat.java +src/main/java/org/openapitools/server/model/CatAllOf.java +src/main/java/org/openapitools/server/model/Category.java +src/main/java/org/openapitools/server/model/ClassModel.java +src/main/java/org/openapitools/server/model/Client.java +src/main/java/org/openapitools/server/model/DeprecatedObject.java +src/main/java/org/openapitools/server/model/Dog.java +src/main/java/org/openapitools/server/model/DogAllOf.java +src/main/java/org/openapitools/server/model/EnumArrays.java +src/main/java/org/openapitools/server/model/EnumClass.java +src/main/java/org/openapitools/server/model/EnumTest.java +src/main/java/org/openapitools/server/model/FileSchemaTestClass.java +src/main/java/org/openapitools/server/model/Foo.java +src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java +src/main/java/org/openapitools/server/model/FormatTest.java +src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java +src/main/java/org/openapitools/server/model/HealthCheckResult.java +src/main/java/org/openapitools/server/model/MapTest.java +src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java +src/main/java/org/openapitools/server/model/Model200Response.java +src/main/java/org/openapitools/server/model/ModelApiResponse.java +src/main/java/org/openapitools/server/model/ModelFile.java +src/main/java/org/openapitools/server/model/ModelList.java +src/main/java/org/openapitools/server/model/ModelReturn.java +src/main/java/org/openapitools/server/model/Name.java +src/main/java/org/openapitools/server/model/NullableClass.java +src/main/java/org/openapitools/server/model/NumberOnly.java +src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java +src/main/java/org/openapitools/server/model/Order.java +src/main/java/org/openapitools/server/model/OuterComposite.java +src/main/java/org/openapitools/server/model/OuterEnum.java +src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java +src/main/java/org/openapitools/server/model/OuterEnumInteger.java +src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java +src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java +src/main/java/org/openapitools/server/model/Pet.java +src/main/java/org/openapitools/server/model/ReadOnlyFirst.java +src/main/java/org/openapitools/server/model/SingleRefType.java +src/main/java/org/openapitools/server/model/SpecialModelName.java +src/main/java/org/openapitools/server/model/Tag.java +src/main/java/org/openapitools/server/model/User.java +src/main/java/org/openapitools/server/package-info.java +src/main/resources/META-INF/openapi.yml +src/main/resources/application.yaml +src/main/resources/logging.properties +src/test/java/org/openapitools/server/MainTest.java diff --git a/samples/server/petstore/java-helidon-server/se/.openapi-generator/VERSION b/samples/server/petstore/java-helidon-server/se/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/se/README.md b/samples/server/petstore/java-helidon-server/se/README.md new file mode 100644 index 0000000000..ed9e99d3ae --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/README.md @@ -0,0 +1,74 @@ +# Helidon SE Server with OpenAPI + +## Build and run + +With JDK11+ +```bash +mvn package +java -jar target/petstore-helidon-server-se.jar +``` + +## Exercise the application + +``` +curl -X PATCH http://petstore.swagger.io:80/v2/another-fake/dummy +curl -X GET http://petstore.swagger.io:80/v2/foo +curl -X GET http://petstore.swagger.io:80/v2/fake/health +curl -X GET http://petstore.swagger.io:80/v2/fake/http-signature-test +curl -X POST http://petstore.swagger.io:80/v2/fake/outer/boolean +curl -X POST http://petstore.swagger.io:80/v2/fake/outer/composite +curl -X POST http://petstore.swagger.io:80/v2/fake/outer/number +curl -X POST http://petstore.swagger.io:80/v2/fake/outer/string +curl -X POST http://petstore.swagger.io:80/v2/fake/property/enum-int +curl -X PUT http://petstore.swagger.io:80/v2/fake/body-with-binary +curl -X PUT http://petstore.swagger.io:80/v2/fake/body-with-file-schema +curl -X PUT http://petstore.swagger.io:80/v2/fake/body-with-query-params +curl -X PATCH http://petstore.swagger.io:80/v2/fake +curl -X POST http://petstore.swagger.io:80/v2/fake +curl -X GET http://petstore.swagger.io:80/v2/fake +curl -X DELETE http://petstore.swagger.io:80/v2/fake +curl -X POST http://petstore.swagger.io:80/v2/fake/inline-additionalProperties +curl -X GET http://petstore.swagger.io:80/v2/fake/jsonFormData +curl -X PUT http://petstore.swagger.io:80/v2/fake/test-query-parameters +curl -X PATCH http://petstore.swagger.io:80/v2/fake_classname_test +curl -X POST http://petstore.swagger.io:80/v2/pet +curl -X DELETE http://petstore.swagger.io:80/v2/pet/{petId} +curl -X GET http://petstore.swagger.io:80/v2/pet/findByStatus +curl -X GET http://petstore.swagger.io:80/v2/pet/findByTags +curl -X GET http://petstore.swagger.io:80/v2/pet/{petId} +curl -X PUT http://petstore.swagger.io:80/v2/pet +curl -X POST http://petstore.swagger.io:80/v2/pet/{petId} +curl -X POST http://petstore.swagger.io:80/v2/pet/{petId}/uploadImage +curl -X POST http://petstore.swagger.io:80/v2/fake/{petId}/uploadImageWithRequiredFile +curl -X DELETE http://petstore.swagger.io:80/v2/store/order/{order_id} +curl -X GET http://petstore.swagger.io:80/v2/store/inventory +curl -X GET http://petstore.swagger.io:80/v2/store/order/{order_id} +curl -X POST http://petstore.swagger.io:80/v2/store/order +curl -X POST http://petstore.swagger.io:80/v2/user +curl -X POST http://petstore.swagger.io:80/v2/user/createWithArray +curl -X POST http://petstore.swagger.io:80/v2/user/createWithList +curl -X DELETE http://petstore.swagger.io:80/v2/user/{username} +curl -X GET http://petstore.swagger.io:80/v2/user/{username} +curl -X GET http://petstore.swagger.io:80/v2/user/login +curl -X GET http://petstore.swagger.io:80/v2/user/logout +curl -X PUT http://petstore.swagger.io:80/v2/user/{username} + +``` + +## Try health and metrics + +``` +curl -s -X GET http://petstore.swagger.io:80/v2/health +{"outcome":"UP",... +. . . + +# Prometheus Format +curl -s -X GET http://petstore.swagger.io:80/v2/metrics +# TYPE base:gc_g1_young_generation_count gauge +. . . + +# JSON Format +curl -H 'Accept: application/json' -X GET http://petstore.swagger.io:80/v2/metrics +{"base":... +. . . +``` \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/se/pom.xml b/samples/server/petstore/java-helidon-server/se/pom.xml new file mode 100644 index 0000000000..cefb0fe5f8 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/pom.xml @@ -0,0 +1,103 @@ + + + 4.0.0 + + io.helidon.applications + helidon-se + 3.0.1 + + + org.openapitools + petstore-helidon-server-se + 1.0.0 + petstore-helidon-server-se + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + + org.openapitools.server.Main + 0.2.3 + + + + + jakarta.validation + jakarta.validation-api + + + io.helidon.webserver + helidon-webserver + + + io.helidon.media + helidon-media-jsonp + + + io.helidon.media + helidon-media-multipart + + + io.helidon.config + helidon-config-yaml + + + io.helidon.health + helidon-health + + + io.helidon.health + helidon-health-checks + + + io.helidon.metrics + helidon-metrics + + + io.helidon.openapi + helidon-openapi + + + org.openapitools + jackson-databind-nullable + ${version.jackson.databind.nullable} + + + io.helidon.media + helidon-media-jackson + + + org.junit.jupiter + junit-jupiter-api + test + + + io.helidon.webclient + helidon-webclient + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libs + + + + + io.helidon.build-tools + helidon-maven-plugin + + + third-party-license-report + + + + + + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/Main.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/Main.java new file mode 100644 index 0000000000..c5a69f3851 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/Main.java @@ -0,0 +1,103 @@ +package org.openapitools.server; + +import org.openapitools.server.api.AnotherFakeServiceImpl; +import org.openapitools.server.api.DefaultServiceImpl; +import org.openapitools.server.api.FakeServiceImpl; +import org.openapitools.server.api.FakeClassnameTags123ServiceImpl; +import org.openapitools.server.api.PetServiceImpl; +import org.openapitools.server.api.StoreServiceImpl; +import org.openapitools.server.api.UserServiceImpl; + +import io.helidon.common.LogConfig; +import io.helidon.common.reactive.Single; +import io.helidon.config.Config; +import io.helidon.health.HealthSupport; +import io.helidon.health.checks.HealthChecks; +import io.helidon.media.jsonp.JsonpSupport; +import io.helidon.media.jackson.JacksonSupport; +import org.openapitools.server.api.JsonProvider; +import io.helidon.metrics.MetricsSupport; +import io.helidon.openapi.OpenAPISupport; +import io.helidon.webserver.Routing; +import io.helidon.webserver.WebServer; + +/** +* The application main class. +*/ +public final class Main { + + /** + * Cannot be instantiated. + */ + private Main() { + } + + /** + * Application main entry point. + * @param args command line arguments. + */ + public static void main(final String[] args) { + startServer(); + } + + /** + * Start the server. + * @return the created {@link WebServer} instance + */ + static Single startServer() { + + // load logging configuration + LogConfig.configureRuntime(); + + // By default this will pick up application.yaml from the classpath + Config config = Config.create(); + + WebServer server = WebServer.builder(createRouting(config)) + .config(config.get("server")) + .addMediaSupport(JsonpSupport.create()) + .addMediaSupport(JacksonSupport.create(JsonProvider.objectMapper())) + .build(); + + Single webserver = server.start(); + + // Try to start the server. If successful, print some info and arrange to + // print a message at shutdown. If unsuccessful, print the exception. + webserver.thenAccept(ws -> { + System.out.println("WEB server is up! http://petstore.swagger.io:80/v2"); + ws.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!")); + }) + .exceptionallyAccept(t -> { + System.err.println("Startup failed: " + t.getMessage()); + t.printStackTrace(System.err); + }); + + return webserver; + } + + /** + * Creates new {@link Routing}. + * + * @return routing configured with JSON support, a health check, and a service + * @param config configuration of this server + */ + private static Routing createRouting(Config config) { + + MetricsSupport metrics = MetricsSupport.create(); + HealthSupport health = HealthSupport.builder() + .addLiveness(HealthChecks.healthChecks()) // Adds a convenient set of checks + .build(); + + return Routing.builder() + .register(OpenAPISupport.create(config.get(OpenAPISupport.Builder.CONFIG_KEY))) + .register(health) // Health at "/health" + .register(metrics) // Metrics at "/metrics" + .register("/", new AnotherFakeServiceImpl()) + .register("/", new DefaultServiceImpl()) + .register("/", new FakeServiceImpl()) + .register("/", new FakeClassnameTags123ServiceImpl()) + .register("/", new PetServiceImpl()) + .register("/", new StoreServiceImpl()) + .register("/", new UserServiceImpl()) + .build(); + } +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/RFC3339DateFormat.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/RFC3339DateFormat.java new file mode 100644 index 0000000000..f47f2f7f98 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/RFC3339DateFormat.java @@ -0,0 +1,50 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/AnotherFakeService.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/AnotherFakeService.java new file mode 100644 index 0000000000..1aae282a7c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/AnotherFakeService.java @@ -0,0 +1,32 @@ +package org.openapitools.server.api; + +import org.openapitools.server.model.Client; +import io.helidon.webserver.Handler; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; +import io.helidon.webserver.Service; + +public interface AnotherFakeService extends Service { + + /** + * A service registers itself by updating the routing rules. + * @param rules the routing rules. + */ + @Override + default void update(Routing.Rules rules) { + rules.patch("/another-fake/dummy", Handler.create(Client.class, this::call123testSpecialTags)); + } + + + /** + * PATCH /another-fake/dummy : To test special tags. + * @param request the server request + * @param response the server response + * @param client client model + */ + void call123testSpecialTags(ServerRequest request, ServerResponse response, Client client); + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/AnotherFakeServiceImpl.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/AnotherFakeServiceImpl.java new file mode 100644 index 0000000000..ecac97ee2d --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/AnotherFakeServiceImpl.java @@ -0,0 +1,22 @@ +package org.openapitools.server.api; + +import org.openapitools.server.model.Client; +import io.helidon.webserver.Handler; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.logging.Logger; + +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; + +public class AnotherFakeServiceImpl implements AnotherFakeService { + + private static final int HTTP_CODE_NOT_IMPLEMENTED = 501; + private static final Logger LOGGER = Logger.getLogger(AnotherFakeService.class.getName()); + private static final ObjectMapper MAPPER = JsonProvider.objectMapper(); + + + public void call123testSpecialTags(ServerRequest request, ServerResponse response, Client client) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/DefaultService.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/DefaultService.java new file mode 100644 index 0000000000..6dcf4beace --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/DefaultService.java @@ -0,0 +1,30 @@ +package org.openapitools.server.api; + +import org.openapitools.server.model.FooGetDefaultResponse; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; +import io.helidon.webserver.Service; + +public interface DefaultService extends Service { + + /** + * A service registers itself by updating the routing rules. + * @param rules the routing rules. + */ + @Override + default void update(Routing.Rules rules) { + rules.get("/foo", this::fooGet); + } + + + /** + * GET /foo. + * @param request the server request + * @param response the server response + */ + void fooGet(ServerRequest request, ServerResponse response); + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/DefaultServiceImpl.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/DefaultServiceImpl.java new file mode 100644 index 0000000000..5d6166d32d --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/DefaultServiceImpl.java @@ -0,0 +1,21 @@ +package org.openapitools.server.api; + +import org.openapitools.server.model.FooGetDefaultResponse; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.logging.Logger; + +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; + +public class DefaultServiceImpl implements DefaultService { + + private static final int HTTP_CODE_NOT_IMPLEMENTED = 501; + private static final Logger LOGGER = Logger.getLogger(DefaultService.class.getName()); + private static final ObjectMapper MAPPER = JsonProvider.objectMapper(); + + + public void fooGet(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeClassnameTags123Service.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeClassnameTags123Service.java new file mode 100644 index 0000000000..64b29bab65 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeClassnameTags123Service.java @@ -0,0 +1,32 @@ +package org.openapitools.server.api; + +import org.openapitools.server.model.Client; +import io.helidon.webserver.Handler; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; +import io.helidon.webserver.Service; + +public interface FakeClassnameTags123Service extends Service { + + /** + * A service registers itself by updating the routing rules. + * @param rules the routing rules. + */ + @Override + default void update(Routing.Rules rules) { + rules.patch("/fake_classname_test", Handler.create(Client.class, this::testClassname)); + } + + + /** + * PATCH /fake_classname_test : To test class name in snake case. + * @param request the server request + * @param response the server response + * @param client client model + */ + void testClassname(ServerRequest request, ServerResponse response, Client client); + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeClassnameTags123ServiceImpl.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeClassnameTags123ServiceImpl.java new file mode 100644 index 0000000000..a4321c9ffd --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeClassnameTags123ServiceImpl.java @@ -0,0 +1,22 @@ +package org.openapitools.server.api; + +import org.openapitools.server.model.Client; +import io.helidon.webserver.Handler; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.logging.Logger; + +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; + +public class FakeClassnameTags123ServiceImpl implements FakeClassnameTags123Service { + + private static final int HTTP_CODE_NOT_IMPLEMENTED = 501; + private static final Logger LOGGER = Logger.getLogger(FakeClassnameTags123Service.class.getName()); + private static final ObjectMapper MAPPER = JsonProvider.objectMapper(); + + + public void testClassname(ServerRequest request, ServerResponse response, Client client) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeService.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeService.java new file mode 100644 index 0000000000..3ab5d37965 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeService.java @@ -0,0 +1,177 @@ +package org.openapitools.server.api; + +import java.math.BigDecimal; +import org.openapitools.server.model.Client; +import org.openapitools.server.model.EnumClass; +import java.io.File; +import org.openapitools.server.model.FileSchemaTestClass; +import io.helidon.webserver.Handler; +import org.openapitools.server.model.HealthCheckResult; +import java.time.LocalDate; +import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.OffsetDateTime; +import org.openapitools.server.model.OuterComposite; +import org.openapitools.server.model.OuterObjectWithEnumProperty; +import org.openapitools.server.model.Pet; +import org.openapitools.server.model.User; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; +import io.helidon.webserver.Service; + +public interface FakeService extends Service { + + /** + * A service registers itself by updating the routing rules. + * @param rules the routing rules. + */ + @Override + default void update(Routing.Rules rules) { + rules.get("/fake/health", this::fakeHealthGet); + rules.get("/fake/http-signature-test", Handler.create(Pet.class, this::fakeHttpSignatureTest)); + rules.post("/fake/outer/boolean", this::fakeOuterBooleanSerialize); + rules.post("/fake/outer/composite", Handler.create(OuterComposite.class, this::fakeOuterCompositeSerialize)); + rules.post("/fake/outer/number", this::fakeOuterNumberSerialize); + rules.post("/fake/outer/string", this::fakeOuterStringSerialize); + rules.post("/fake/property/enum-int", Handler.create(OuterObjectWithEnumProperty.class, this::fakePropertyEnumIntegerSerialize)); + rules.put("/fake/body-with-binary", this::testBodyWithBinary); + rules.put("/fake/body-with-file-schema", Handler.create(FileSchemaTestClass.class, this::testBodyWithFileSchema)); + rules.put("/fake/body-with-query-params", Handler.create(User.class, this::testBodyWithQueryParams)); + rules.patch("/fake", Handler.create(Client.class, this::testClientModel)); + rules.post("/fake", this::testEndpointParameters); + rules.get("/fake", this::testEnumParameters); + rules.delete("/fake", this::testGroupParameters); + rules.post("/fake/inline-additionalProperties", this::testInlineAdditionalProperties); + rules.get("/fake/jsonFormData", this::testJsonFormData); + rules.put("/fake/test-query-parameters", this::testQueryParameterCollectionFormat); + } + + + /** + * GET /fake/health : Health check endpoint. + * @param request the server request + * @param response the server response + */ + void fakeHealthGet(ServerRequest request, ServerResponse response); + + /** + * GET /fake/http-signature-test : test http signature authentication. + * @param request the server request + * @param response the server response + * @param pet Pet object that needs to be added to the store + */ + void fakeHttpSignatureTest(ServerRequest request, ServerResponse response, Pet pet); + + /** + * POST /fake/outer/boolean. + * @param request the server request + * @param response the server response + */ + void fakeOuterBooleanSerialize(ServerRequest request, ServerResponse response); + + /** + * POST /fake/outer/composite. + * @param request the server request + * @param response the server response + * @param outerComposite Input composite as post body + */ + void fakeOuterCompositeSerialize(ServerRequest request, ServerResponse response, OuterComposite outerComposite); + + /** + * POST /fake/outer/number. + * @param request the server request + * @param response the server response + */ + void fakeOuterNumberSerialize(ServerRequest request, ServerResponse response); + + /** + * POST /fake/outer/string. + * @param request the server request + * @param response the server response + */ + void fakeOuterStringSerialize(ServerRequest request, ServerResponse response); + + /** + * POST /fake/property/enum-int. + * @param request the server request + * @param response the server response + * @param outerObjectWithEnumProperty Input enum (int) as post body + */ + void fakePropertyEnumIntegerSerialize(ServerRequest request, ServerResponse response, OuterObjectWithEnumProperty outerObjectWithEnumProperty); + + /** + * PUT /fake/body-with-binary. + * @param request the server request + * @param response the server response + */ + void testBodyWithBinary(ServerRequest request, ServerResponse response); + + /** + * PUT /fake/body-with-file-schema. + * @param request the server request + * @param response the server response + * @param fileSchemaTestClass fileSchemaTestClass + */ + void testBodyWithFileSchema(ServerRequest request, ServerResponse response, FileSchemaTestClass fileSchemaTestClass); + + /** + * PUT /fake/body-with-query-params. + * @param request the server request + * @param response the server response + * @param user user + */ + void testBodyWithQueryParams(ServerRequest request, ServerResponse response, User user); + + /** + * PATCH /fake : To test \"client\" model. + * @param request the server request + * @param response the server response + * @param client client model + */ + void testClientModel(ServerRequest request, ServerResponse response, Client client); + + /** + * POST /fake : Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 . + * @param request the server request + * @param response the server response + */ + void testEndpointParameters(ServerRequest request, ServerResponse response); + + /** + * GET /fake : To test enum parameters. + * @param request the server request + * @param response the server response + */ + void testEnumParameters(ServerRequest request, ServerResponse response); + + /** + * DELETE /fake : Fake endpoint to test group parameters (optional). + * @param request the server request + * @param response the server response + */ + void testGroupParameters(ServerRequest request, ServerResponse response); + + /** + * POST /fake/inline-additionalProperties : test inline additionalProperties. + * @param request the server request + * @param response the server response + */ + void testInlineAdditionalProperties(ServerRequest request, ServerResponse response); + + /** + * GET /fake/jsonFormData : test json serialization of form data. + * @param request the server request + * @param response the server response + */ + void testJsonFormData(ServerRequest request, ServerResponse response); + + /** + * PUT /fake/test-query-parameters. + * @param request the server request + * @param response the server response + */ + void testQueryParameterCollectionFormat(ServerRequest request, ServerResponse response); + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeServiceImpl.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeServiceImpl.java new file mode 100644 index 0000000000..8dbc1c125a --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeServiceImpl.java @@ -0,0 +1,98 @@ +package org.openapitools.server.api; + +import java.math.BigDecimal; +import org.openapitools.server.model.Client; +import org.openapitools.server.model.EnumClass; +import java.io.File; +import org.openapitools.server.model.FileSchemaTestClass; +import io.helidon.webserver.Handler; +import org.openapitools.server.model.HealthCheckResult; +import java.time.LocalDate; +import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.OffsetDateTime; +import org.openapitools.server.model.OuterComposite; +import org.openapitools.server.model.OuterObjectWithEnumProperty; +import org.openapitools.server.model.Pet; +import org.openapitools.server.model.User; +import java.util.logging.Logger; + +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; + +public class FakeServiceImpl implements FakeService { + + private static final int HTTP_CODE_NOT_IMPLEMENTED = 501; + private static final Logger LOGGER = Logger.getLogger(FakeService.class.getName()); + private static final ObjectMapper MAPPER = JsonProvider.objectMapper(); + + + public void fakeHealthGet(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void fakeHttpSignatureTest(ServerRequest request, ServerResponse response, Pet pet) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void fakeOuterBooleanSerialize(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void fakeOuterCompositeSerialize(ServerRequest request, ServerResponse response, OuterComposite outerComposite) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void fakeOuterNumberSerialize(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void fakeOuterStringSerialize(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void fakePropertyEnumIntegerSerialize(ServerRequest request, ServerResponse response, OuterObjectWithEnumProperty outerObjectWithEnumProperty) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testBodyWithBinary(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testBodyWithFileSchema(ServerRequest request, ServerResponse response, FileSchemaTestClass fileSchemaTestClass) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testBodyWithQueryParams(ServerRequest request, ServerResponse response, User user) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testClientModel(ServerRequest request, ServerResponse response, Client client) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testEndpointParameters(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testEnumParameters(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testGroupParameters(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testInlineAdditionalProperties(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testJsonFormData(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void testQueryParameterCollectionFormat(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/JsonProvider.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/JsonProvider.java new file mode 100644 index 0000000000..41f01e882a --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/JsonProvider.java @@ -0,0 +1,20 @@ +package org.openapitools.server.api; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +public class JsonProvider { + + public static ObjectMapper objectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); + mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false); + return mapper; + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/PetService.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/PetService.java new file mode 100644 index 0000000000..6851238e19 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/PetService.java @@ -0,0 +1,100 @@ +package org.openapitools.server.api; + +import java.io.File; +import io.helidon.webserver.Handler; +import org.openapitools.server.model.ModelApiResponse; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openapitools.server.model.Pet; +import java.util.Set; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; +import io.helidon.webserver.Service; + +public interface PetService extends Service { + + /** + * A service registers itself by updating the routing rules. + * @param rules the routing rules. + */ + @Override + default void update(Routing.Rules rules) { + rules.post("/pet", Handler.create(Pet.class, this::addPet)); + rules.delete("/pet/{petId}", this::deletePet); + rules.get("/pet/findByStatus", this::findPetsByStatus); + rules.get("/pet/findByTags", this::findPetsByTags); + rules.get("/pet/{petId}", this::getPetById); + rules.put("/pet", Handler.create(Pet.class, this::updatePet)); + rules.post("/pet/{petId}", this::updatePetWithForm); + rules.post("/pet/{petId}/uploadImage", this::uploadFile); + rules.post("/fake/{petId}/uploadImageWithRequiredFile", this::uploadFileWithRequiredFile); + } + + + /** + * POST /pet : Add a new pet to the store. + * @param request the server request + * @param response the server response + * @param pet Pet object that needs to be added to the store + */ + void addPet(ServerRequest request, ServerResponse response, Pet pet); + + /** + * DELETE /pet/{petId} : Deletes a pet. + * @param request the server request + * @param response the server response + */ + void deletePet(ServerRequest request, ServerResponse response); + + /** + * GET /pet/findByStatus : Finds Pets by status. + * @param request the server request + * @param response the server response + */ + void findPetsByStatus(ServerRequest request, ServerResponse response); + + /** + * GET /pet/findByTags : Finds Pets by tags. + * @param request the server request + * @param response the server response + */ + void findPetsByTags(ServerRequest request, ServerResponse response); + + /** + * GET /pet/{petId} : Find pet by ID. + * @param request the server request + * @param response the server response + */ + void getPetById(ServerRequest request, ServerResponse response); + + /** + * PUT /pet : Update an existing pet. + * @param request the server request + * @param response the server response + * @param pet Pet object that needs to be added to the store + */ + void updatePet(ServerRequest request, ServerResponse response, Pet pet); + + /** + * POST /pet/{petId} : Updates a pet in the store with form data. + * @param request the server request + * @param response the server response + */ + void updatePetWithForm(ServerRequest request, ServerResponse response); + + /** + * POST /pet/{petId}/uploadImage : uploads an image. + * @param request the server request + * @param response the server response + */ + void uploadFile(ServerRequest request, ServerResponse response); + + /** + * POST /fake/{petId}/uploadImageWithRequiredFile : uploads an image (required). + * @param request the server request + * @param response the server response + */ + void uploadFileWithRequiredFile(ServerRequest request, ServerResponse response); + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/PetServiceImpl.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/PetServiceImpl.java new file mode 100644 index 0000000000..7857f6bfa5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/PetServiceImpl.java @@ -0,0 +1,57 @@ +package org.openapitools.server.api; + +import java.io.File; +import io.helidon.webserver.Handler; +import org.openapitools.server.model.ModelApiResponse; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openapitools.server.model.Pet; +import java.util.Set; +import java.util.logging.Logger; + +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; + +public class PetServiceImpl implements PetService { + + private static final int HTTP_CODE_NOT_IMPLEMENTED = 501; + private static final Logger LOGGER = Logger.getLogger(PetService.class.getName()); + private static final ObjectMapper MAPPER = JsonProvider.objectMapper(); + + + public void addPet(ServerRequest request, ServerResponse response, Pet pet) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void deletePet(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void findPetsByStatus(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void findPetsByTags(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void getPetById(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void updatePet(ServerRequest request, ServerResponse response, Pet pet) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void updatePetWithForm(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void uploadFile(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void uploadFileWithRequiredFile(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/StoreService.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/StoreService.java new file mode 100644 index 0000000000..d24b3a027a --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/StoreService.java @@ -0,0 +1,57 @@ +package org.openapitools.server.api; + +import io.helidon.webserver.Handler; +import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openapitools.server.model.Order; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; +import io.helidon.webserver.Service; + +public interface StoreService extends Service { + + /** + * A service registers itself by updating the routing rules. + * @param rules the routing rules. + */ + @Override + default void update(Routing.Rules rules) { + rules.delete("/store/order/{order_id}", this::deleteOrder); + rules.get("/store/inventory", this::getInventory); + rules.get("/store/order/{order_id}", this::getOrderById); + rules.post("/store/order", Handler.create(Order.class, this::placeOrder)); + } + + + /** + * DELETE /store/order/{order_id} : Delete purchase order by ID. + * @param request the server request + * @param response the server response + */ + void deleteOrder(ServerRequest request, ServerResponse response); + + /** + * GET /store/inventory : Returns pet inventories by status. + * @param request the server request + * @param response the server response + */ + void getInventory(ServerRequest request, ServerResponse response); + + /** + * GET /store/order/{order_id} : Find purchase order by ID. + * @param request the server request + * @param response the server response + */ + void getOrderById(ServerRequest request, ServerResponse response); + + /** + * POST /store/order : Place an order for a pet. + * @param request the server request + * @param response the server response + * @param order order placed for purchasing the pet + */ + void placeOrder(ServerRequest request, ServerResponse response, Order order); + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/StoreServiceImpl.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/StoreServiceImpl.java new file mode 100644 index 0000000000..7b51983f8b --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/StoreServiceImpl.java @@ -0,0 +1,35 @@ +package org.openapitools.server.api; + +import io.helidon.webserver.Handler; +import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openapitools.server.model.Order; +import java.util.logging.Logger; + +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; + +public class StoreServiceImpl implements StoreService { + + private static final int HTTP_CODE_NOT_IMPLEMENTED = 501; + private static final Logger LOGGER = Logger.getLogger(StoreService.class.getName()); + private static final ObjectMapper MAPPER = JsonProvider.objectMapper(); + + + public void deleteOrder(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void getInventory(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void getOrderById(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void placeOrder(ServerRequest request, ServerResponse response, Order order) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/UserService.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/UserService.java new file mode 100644 index 0000000000..4db3a7fe69 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/UserService.java @@ -0,0 +1,91 @@ +package org.openapitools.server.api; + +import io.helidon.webserver.Handler; +import java.util.List; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.OffsetDateTime; +import org.openapitools.server.model.User; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; +import io.helidon.webserver.Service; + +public interface UserService extends Service { + + /** + * A service registers itself by updating the routing rules. + * @param rules the routing rules. + */ + @Override + default void update(Routing.Rules rules) { + rules.post("/user", Handler.create(User.class, this::createUser)); + rules.post("/user/createWithArray", this::createUsersWithArrayInput); + rules.post("/user/createWithList", this::createUsersWithListInput); + rules.delete("/user/{username}", this::deleteUser); + rules.get("/user/{username}", this::getUserByName); + rules.get("/user/login", this::loginUser); + rules.get("/user/logout", this::logoutUser); + rules.put("/user/{username}", Handler.create(User.class, this::updateUser)); + } + + + /** + * POST /user : Create user. + * @param request the server request + * @param response the server response + * @param user Created user object + */ + void createUser(ServerRequest request, ServerResponse response, User user); + + /** + * POST /user/createWithArray : Creates list of users with given input array. + * @param request the server request + * @param response the server response + */ + void createUsersWithArrayInput(ServerRequest request, ServerResponse response); + + /** + * POST /user/createWithList : Creates list of users with given input array. + * @param request the server request + * @param response the server response + */ + void createUsersWithListInput(ServerRequest request, ServerResponse response); + + /** + * DELETE /user/{username} : Delete user. + * @param request the server request + * @param response the server response + */ + void deleteUser(ServerRequest request, ServerResponse response); + + /** + * GET /user/{username} : Get user by user name. + * @param request the server request + * @param response the server response + */ + void getUserByName(ServerRequest request, ServerResponse response); + + /** + * GET /user/login : Logs user into the system. + * @param request the server request + * @param response the server response + */ + void loginUser(ServerRequest request, ServerResponse response); + + /** + * GET /user/logout : Logs out current logged in user session. + * @param request the server request + * @param response the server response + */ + void logoutUser(ServerRequest request, ServerResponse response); + + /** + * PUT /user/{username} : Updated user. + * @param request the server request + * @param response the server response + * @param user Updated user object + */ + void updateUser(ServerRequest request, ServerResponse response, User user); + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/UserServiceImpl.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/UserServiceImpl.java new file mode 100644 index 0000000000..2e8dc2916c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/UserServiceImpl.java @@ -0,0 +1,52 @@ +package org.openapitools.server.api; + +import io.helidon.webserver.Handler; +import java.util.List; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.OffsetDateTime; +import org.openapitools.server.model.User; +import java.util.logging.Logger; + +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; + +public class UserServiceImpl implements UserService { + + private static final int HTTP_CODE_NOT_IMPLEMENTED = 501; + private static final Logger LOGGER = Logger.getLogger(UserService.class.getName()); + private static final ObjectMapper MAPPER = JsonProvider.objectMapper(); + + + public void createUser(ServerRequest request, ServerResponse response, User user) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void createUsersWithArrayInput(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void createUsersWithListInput(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void deleteUser(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void getUserByName(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void loginUser(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void logoutUser(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + + public void updateUser(ServerRequest request, ServerResponse response, User user) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/ValidatorUtils.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/ValidatorUtils.java new file mode 100644 index 0000000000..a57963d73f --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/ValidatorUtils.java @@ -0,0 +1,112 @@ +package org.openapitools.server.api; + +import java.lang.reflect.Array; +import java.math.BigDecimal; +import java.util.Collection; +import java.util.Map; +import java.util.Objects; + +import jakarta.validation.ValidationException; + +/** +* Validation utility methods. +*/ +public final class ValidatorUtils { + + public static boolean validateMin(Integer value, Integer min) { + checkNonNull(value); + if (value < min) { + throw new ValidationException(String.format("%s is less than %s", value, min)); + } + return true; + } + + public static boolean validateMax(Integer value, Integer max) { + checkNonNull(value); + if (value > max) { + throw new ValidationException(String.format("%s is more than %s", value, max)); + } + return true; + } + + public static boolean validateSize(Object value, Integer min, Integer max) { + checkNonNull(value); + Integer size = -1; + if (value instanceof Map) { + size = ((Map) value).size(); + } + if (value instanceof CharSequence) { + size = ((CharSequence) value).length(); + } + if (value instanceof Collection) { + size = ((Collection) value).size(); + } + if (value.getClass().isArray()) { + size = Array.getLength(value); + } + if (size == -1) { + throw new ValidationException("Value has incorrect type"); + } + if (min != null) { + validateMin(size, min); + } + if (max != null) { + validateMax(size, max); + } + return true; + } + + public static boolean validatePattern(String value, String pattern) { + checkNonNull(value, pattern); + if (value.matches(pattern)) { + return true; + } + throw new ValidationException(String.format("'%s' does not match the pattern '%s'", value, pattern)); + } + + public static boolean validateMin(BigDecimal value, String stringMinValue, boolean inclusive) { + checkNonNull(value); + BigDecimal minValue = new BigDecimal(stringMinValue); + int result = value.compareTo(minValue); + if (inclusive) { + if (result >= 0) { + return true; + } + } else { + if (result > 0) { + return true; + } + } + throw new ValidationException( + String.format("%s is not valid value. Min value '%s'. Inclusive - %s.", value, stringMinValue, inclusive) + ); + } + + public static boolean validateMax(BigDecimal value, String stringMaxValue, boolean inclusive) { + checkNonNull(value); + BigDecimal maxValue = new BigDecimal(stringMaxValue); + int result = value.compareTo(maxValue); + if (inclusive) { + if (result <= 0) { + return true; + } + } else { + if (result < 0) { + return true; + } + } + throw new ValidationException( + String.format("%s is not valid value. Max value '%s'. Inclusive - %s.", value, stringMaxValue, inclusive) + ); + } + + public static void checkNonNull(Object... args) { + try { + for (Object o : args) { + Objects.requireNonNull(o); + } + } catch (Exception e) { + throw new ValidationException(e); + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java new file mode 100644 index 0000000000..9f9f831237 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java @@ -0,0 +1,85 @@ +package org.openapitools.server.model; + +import java.util.HashMap; +import java.util.Map; + + + +public class AdditionalPropertiesClass { + + private Map mapProperty = new HashMap<>(); + private Map> mapOfMapProperty = new HashMap<>(); + + /** + * Default constructor. + */ + public AdditionalPropertiesClass() { + // JSON-B / Jackson + } + + /** + * Create AdditionalPropertiesClass. + * + * @param mapProperty mapProperty + * @param mapOfMapProperty mapOfMapProperty + */ + public AdditionalPropertiesClass( + Map mapProperty, + Map> mapOfMapProperty + ) { + this.mapProperty = mapProperty; + this.mapOfMapProperty = mapOfMapProperty; + } + + + + /** + * Get mapProperty + * @return mapProperty + */ + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + */ + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java new file mode 100644 index 0000000000..b40d9201c0 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java @@ -0,0 +1,84 @@ +package org.openapitools.server.model; + +import org.openapitools.server.model.SingleRefType; + + + +public class AllOfWithSingleRef { + + private String username; + private SingleRefType singleRefType; + + /** + * Default constructor. + */ + public AllOfWithSingleRef() { + // JSON-B / Jackson + } + + /** + * Create AllOfWithSingleRef. + * + * @param username username + * @param singleRefType singleRefType + */ + public AllOfWithSingleRef( + String username, + SingleRefType singleRefType + ) { + this.username = username; + this.singleRefType = singleRefType; + } + + + + /** + * Get username + * @return username + */ + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + /** + * Get singleRefType + * @return singleRefType + */ + public SingleRefType getSingleRefType() { + return singleRefType; + } + + public void setSingleRefType(SingleRefType singleRefType) { + this.singleRefType = singleRefType; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfWithSingleRef {\n"); + + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" singleRefType: ").append(toIndentedString(singleRefType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Animal.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Animal.java new file mode 100644 index 0000000000..72fd34477f --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Animal.java @@ -0,0 +1,88 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Cat; +import org.openapitools.server.model.Dog; + + + +public class Animal { + + private String className; + private String color = "red"; + + /** + * Default constructor. + */ + public Animal() { + // JSON-B / Jackson + } + + /** + * Create Animal. + * + * @param className className + * @param color color + */ + public Animal( + String className, + String color + ) { + this.className = className; + this.color = color; + } + + + + /** + * Get className + * @return className + */ + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + /** + * Get color + * @return color + */ + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 0000000000..5ba378a420 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,69 @@ +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + +public class ArrayOfArrayOfNumberOnly { + + private List> arrayArrayNumber = new ArrayList<>(); + + /** + * Default constructor. + */ + public ArrayOfArrayOfNumberOnly() { + // JSON-B / Jackson + } + + /** + * Create ArrayOfArrayOfNumberOnly. + * + * @param arrayArrayNumber arrayArrayNumber + */ + public ArrayOfArrayOfNumberOnly( + List> arrayArrayNumber + ) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + */ + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java new file mode 100644 index 0000000000..05e4cfc070 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java @@ -0,0 +1,69 @@ +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + + + +public class ArrayOfNumberOnly { + + private List arrayNumber = new ArrayList<>(); + + /** + * Default constructor. + */ + public ArrayOfNumberOnly() { + // JSON-B / Jackson + } + + /** + * Create ArrayOfNumberOnly. + * + * @param arrayNumber arrayNumber + */ + public ArrayOfNumberOnly( + List arrayNumber + ) { + this.arrayNumber = arrayNumber; + } + + + + /** + * Get arrayNumber + * @return arrayNumber + */ + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayTest.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayTest.java new file mode 100644 index 0000000000..f7eeaade3f --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayTest.java @@ -0,0 +1,103 @@ +package org.openapitools.server.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.ReadOnlyFirst; + + + +public class ArrayTest { + + private List arrayOfString = new ArrayList<>(); + private List> arrayArrayOfInteger = new ArrayList<>(); + private List> arrayArrayOfModel = new ArrayList<>(); + + /** + * Default constructor. + */ + public ArrayTest() { + // JSON-B / Jackson + } + + /** + * Create ArrayTest. + * + * @param arrayOfString arrayOfString + * @param arrayArrayOfInteger arrayArrayOfInteger + * @param arrayArrayOfModel arrayArrayOfModel + */ + public ArrayTest( + List arrayOfString, + List> arrayArrayOfInteger, + List> arrayArrayOfModel + ) { + this.arrayOfString = arrayOfString; + this.arrayArrayOfInteger = arrayArrayOfInteger; + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + + /** + * Get arrayOfString + * @return arrayOfString + */ + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + */ + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + */ + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Capitalization.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Capitalization.java new file mode 100644 index 0000000000..ab3f58fcd4 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Capitalization.java @@ -0,0 +1,151 @@ +package org.openapitools.server.model; + + + + +public class Capitalization { + + private String smallCamel; + private String capitalCamel; + private String smallSnake; + private String capitalSnake; + private String scAETHFlowPoints; + private String ATT_NAME; + + /** + * Default constructor. + */ + public Capitalization() { + // JSON-B / Jackson + } + + /** + * Create Capitalization. + * + * @param smallCamel smallCamel + * @param capitalCamel capitalCamel + * @param smallSnake smallSnake + * @param capitalSnake capitalSnake + * @param scAETHFlowPoints scAETHFlowPoints + * @param ATT_NAME Name of the pet + */ + public Capitalization( + String smallCamel, + String capitalCamel, + String smallSnake, + String capitalSnake, + String scAETHFlowPoints, + String ATT_NAME + ) { + this.smallCamel = smallCamel; + this.capitalCamel = capitalCamel; + this.smallSnake = smallSnake; + this.capitalSnake = capitalSnake; + this.scAETHFlowPoints = scAETHFlowPoints; + this.ATT_NAME = ATT_NAME; + } + + + + /** + * Get smallCamel + * @return smallCamel + */ + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + /** + * Get capitalCamel + * @return capitalCamel + */ + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + /** + * Get smallSnake + * @return smallSnake + */ + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + /** + * Get capitalSnake + * @return capitalSnake + */ + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + */ + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + /** + * Name of the pet + * @return ATT_NAME + */ + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Cat.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Cat.java new file mode 100644 index 0000000000..663f2a8518 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Cat.java @@ -0,0 +1,70 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Animal; + + + +public class Cat extends Animal { + + private Boolean declawed; + + /** + * Default constructor. + */ + public Cat() { + // JSON-B / Jackson + } + + /** + * Create Cat. + * + * @param declawed declawed + */ + public Cat( + Boolean declawed + ) { + this.declawed = declawed; + } + + + + /** + * Get declawed + * @return declawed + */ + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/CatAllOf.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/CatAllOf.java new file mode 100644 index 0000000000..8d2e8a501d --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/CatAllOf.java @@ -0,0 +1,67 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; + + + +public class CatAllOf { + + private Boolean declawed; + + /** + * Default constructor. + */ + public CatAllOf() { + // JSON-B / Jackson + } + + /** + * Create CatAllOf. + * + * @param declawed declawed + */ + public CatAllOf( + Boolean declawed + ) { + this.declawed = declawed; + } + + + + /** + * Get declawed + * @return declawed + */ + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CatAllOf {\n"); + + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Category.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Category.java new file mode 100644 index 0000000000..f449dcdbdc --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Category.java @@ -0,0 +1,83 @@ +package org.openapitools.server.model; + + + + +public class Category { + + private Long id; + private String name = "default-name"; + + /** + * Default constructor. + */ + public Category() { + // JSON-B / Jackson + } + + /** + * Create Category. + * + * @param id id + * @param name name + */ + public Category( + Long id, + String name + ) { + this.id = id; + this.name = name; + } + + + + /** + * Get id + * @return id + */ + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + /** + * Get name + * @return name + */ + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ClassModel.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ClassModel.java new file mode 100644 index 0000000000..ba7528f6dd --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ClassModel.java @@ -0,0 +1,68 @@ +package org.openapitools.server.model; + + + +/** + * Model for testing model with \"_class\" property + */ +public class ClassModel { + + private String propertyClass; + + /** + * Default constructor. + */ + public ClassModel() { + // JSON-B / Jackson + } + + /** + * Create ClassModel. + * + * @param propertyClass propertyClass + */ + public ClassModel( + String propertyClass + ) { + this.propertyClass = propertyClass; + } + + + + /** + * Get propertyClass + * @return propertyClass + */ + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Client.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Client.java new file mode 100644 index 0000000000..76c4d19ab6 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Client.java @@ -0,0 +1,66 @@ +package org.openapitools.server.model; + + + + +public class Client { + + private String client; + + /** + * Default constructor. + */ + public Client() { + // JSON-B / Jackson + } + + /** + * Create Client. + * + * @param client client + */ + public Client( + String client + ) { + this.client = client; + } + + + + /** + * Get client + * @return client + */ + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DeprecatedObject.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DeprecatedObject.java new file mode 100644 index 0000000000..7add1761a8 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DeprecatedObject.java @@ -0,0 +1,66 @@ +package org.openapitools.server.model; + + + + +public class DeprecatedObject { + + private String name; + + /** + * Default constructor. + */ + public DeprecatedObject() { + // JSON-B / Jackson + } + + /** + * Create DeprecatedObject. + * + * @param name name + */ + public DeprecatedObject( + String name + ) { + this.name = name; + } + + + + /** + * Get name + * @return name + */ + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeprecatedObject {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Dog.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Dog.java new file mode 100644 index 0000000000..2c904956ac --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Dog.java @@ -0,0 +1,70 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Animal; + + + +public class Dog extends Animal { + + private String breed; + + /** + * Default constructor. + */ + public Dog() { + // JSON-B / Jackson + } + + /** + * Create Dog. + * + * @param breed breed + */ + public Dog( + String breed + ) { + this.breed = breed; + } + + + + /** + * Get breed + * @return breed + */ + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DogAllOf.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DogAllOf.java new file mode 100644 index 0000000000..f4f1dd5724 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DogAllOf.java @@ -0,0 +1,67 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; + + + +public class DogAllOf { + + private String breed; + + /** + * Default constructor. + */ + public DogAllOf() { + // JSON-B / Jackson + } + + /** + * Create DogAllOf. + * + * @param breed breed + */ + public DogAllOf( + String breed + ) { + this.breed = breed; + } + + + + /** + * Get breed + * @return breed + */ + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DogAllOf {\n"); + + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumArrays.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumArrays.java new file mode 100644 index 0000000000..d7f30e7d96 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumArrays.java @@ -0,0 +1,161 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; + + + +public class EnumArrays { + + + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + + private JustSymbolEnum justSymbol; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + + private List arrayEnum = new ArrayList<>(); + + /** + * Default constructor. + */ + public EnumArrays() { + // JSON-B / Jackson + } + + /** + * Create EnumArrays. + * + * @param justSymbol justSymbol + * @param arrayEnum arrayEnum + */ + public EnumArrays( + JustSymbolEnum justSymbol, + List arrayEnum + ) { + this.justSymbol = justSymbol; + this.arrayEnum = arrayEnum; + } + + + + /** + * Get justSymbol + * @return justSymbol + */ + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + /** + * Get arrayEnum + * @return arrayEnum + */ + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumClass.java new file mode 100644 index 0000000000..d3f6c24ce3 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumClass.java @@ -0,0 +1,44 @@ +package org.openapitools.server.model; + + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets EnumClass + */ + +public enum EnumClass { + + _ABC("_abc"), + _EFG("-efg"), + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumTest.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumTest.java new file mode 100644 index 0000000000..54b36a98ed --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumTest.java @@ -0,0 +1,343 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import org.openapitools.server.model.OuterEnum; +import org.openapitools.server.model.OuterEnumDefaultValue; +import org.openapitools.server.model.OuterEnumInteger; +import org.openapitools.server.model.OuterEnumIntegerDefaultValue; + + + +public class EnumTest { + + + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + LOWER("lower"), + EMPTY(""); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + + private EnumStringEnum enumString; + + /** + * Gets or Sets enumStringRequired + */ + public enum EnumStringRequiredEnum { + UPPER("UPPER"), + LOWER("lower"), + EMPTY(""); + + private String value; + + EnumStringRequiredEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + + @JsonCreator + public static EnumStringRequiredEnum fromValue(String text) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + + private EnumStringRequiredEnum enumStringRequired; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @JsonValue + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + + private EnumIntegerEnum enumInteger; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @JsonValue + public Double getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + + private EnumNumberEnum enumNumber; + private OuterEnum outerEnum; + private OuterEnumInteger outerEnumInteger; + private OuterEnumDefaultValue outerEnumDefaultValue = OuterEnumDefaultValue.PLACED; + private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; + + /** + * Default constructor. + */ + public EnumTest() { + // JSON-B / Jackson + } + + /** + * Create EnumTest. + * + * @param enumString enumString + * @param enumStringRequired enumStringRequired + * @param enumInteger enumInteger + * @param enumNumber enumNumber + * @param outerEnum outerEnum + * @param outerEnumInteger outerEnumInteger + * @param outerEnumDefaultValue outerEnumDefaultValue + * @param outerEnumIntegerDefaultValue outerEnumIntegerDefaultValue + */ + public EnumTest( + EnumStringEnum enumString, + EnumStringRequiredEnum enumStringRequired, + EnumIntegerEnum enumInteger, + EnumNumberEnum enumNumber, + OuterEnum outerEnum, + OuterEnumInteger outerEnumInteger, + OuterEnumDefaultValue outerEnumDefaultValue, + OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue + ) { + this.enumString = enumString; + this.enumStringRequired = enumStringRequired; + this.enumInteger = enumInteger; + this.enumNumber = enumNumber; + this.outerEnum = outerEnum; + this.outerEnumInteger = outerEnumInteger; + this.outerEnumDefaultValue = outerEnumDefaultValue; + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + } + + + + /** + * Get enumString + * @return enumString + */ + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + /** + * Get enumStringRequired + * @return enumStringRequired + */ + public EnumStringRequiredEnum getEnumStringRequired() { + return enumStringRequired; + } + + public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + } + + /** + * Get enumInteger + * @return enumInteger + */ + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + /** + * Get enumNumber + * @return enumNumber + */ + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + /** + * Get outerEnum + * @return outerEnum + */ + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + /** + * Get outerEnumInteger + * @return outerEnumInteger + */ + public OuterEnumInteger getOuterEnumInteger() { + return outerEnumInteger; + } + + public void setOuterEnumInteger(OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + } + + /** + * Get outerEnumDefaultValue + * @return outerEnumDefaultValue + */ + public OuterEnumDefaultValue getOuterEnumDefaultValue() { + return outerEnumDefaultValue; + } + + public void setOuterEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + } + + /** + * Get outerEnumIntegerDefaultValue + * @return outerEnumIntegerDefaultValue + */ + public OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() { + return outerEnumIntegerDefaultValue; + } + + public void setOuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumStringRequired: ").append(toIndentedString(enumStringRequired)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append(" outerEnumInteger: ").append(toIndentedString(outerEnumInteger)).append("\n"); + sb.append(" outerEnumDefaultValue: ").append(toIndentedString(outerEnumDefaultValue)).append("\n"); + sb.append(" outerEnumIntegerDefaultValue: ").append(toIndentedString(outerEnumIntegerDefaultValue)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java new file mode 100644 index 0000000000..1730307fb6 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java @@ -0,0 +1,86 @@ +package org.openapitools.server.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.ModelFile; + + + +public class FileSchemaTestClass { + + private ModelFile _file; + private List files = new ArrayList<>(); + + /** + * Default constructor. + */ + public FileSchemaTestClass() { + // JSON-B / Jackson + } + + /** + * Create FileSchemaTestClass. + * + * @param _file _file + * @param files files + */ + public FileSchemaTestClass( + ModelFile _file, + List files + ) { + this._file = _file; + this.files = files; + } + + + + /** + * Get _file + * @return _file + */ + public ModelFile getFile() { + return _file; + } + + public void setFile(ModelFile _file) { + this._file = _file; + } + + /** + * Get files + * @return files + */ + public List getFiles() { + return files; + } + + public void setFiles(List files) { + this.files = files; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FileSchemaTestClass {\n"); + + sb.append(" _file: ").append(toIndentedString(_file)).append("\n"); + sb.append(" files: ").append(toIndentedString(files)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Foo.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Foo.java new file mode 100644 index 0000000000..6b3869f6f4 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Foo.java @@ -0,0 +1,66 @@ +package org.openapitools.server.model; + + + + +public class Foo { + + private String bar = "bar"; + + /** + * Default constructor. + */ + public Foo() { + // JSON-B / Jackson + } + + /** + * Create Foo. + * + * @param bar bar + */ + public Foo( + String bar + ) { + this.bar = bar; + } + + + + /** + * Get bar + * @return bar + */ + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Foo {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java new file mode 100644 index 0000000000..f4716bdfcd --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java @@ -0,0 +1,68 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.openapitools.server.model.Foo; + + + +public class FooGetDefaultResponse { + + private Foo string; + + /** + * Default constructor. + */ + public FooGetDefaultResponse() { + // JSON-B / Jackson + } + + /** + * Create FooGetDefaultResponse. + * + * @param string string + */ + public FooGetDefaultResponse( + Foo string + ) { + this.string = string; + } + + + + /** + * Get string + * @return string + */ + public Foo getString() { + return string; + } + + public void setString(Foo string) { + this.string = string; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FooGetDefaultResponse {\n"); + + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FormatTest.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FormatTest.java new file mode 100644 index 0000000000..df656b5b83 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FormatTest.java @@ -0,0 +1,337 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; + + + +public class FormatTest { + + private Integer integer; + private Integer int32; + private Long int64; + private BigDecimal number; + private Float _float; + private Double _double; + private BigDecimal decimal; + private String string; + private byte[] _byte; + private File binary; + private LocalDate date; + private OffsetDateTime dateTime; + private UUID uuid; + private String password; + private String patternWithDigits; + private String patternWithDigitsAndDelimiter; + + /** + * Default constructor. + */ + public FormatTest() { + // JSON-B / Jackson + } + + /** + * Create FormatTest. + * + * @param integer integer + * @param int32 int32 + * @param int64 int64 + * @param number number + * @param _float _float + * @param _double _double + * @param decimal decimal + * @param string string + * @param _byte _byte + * @param binary binary + * @param date date + * @param dateTime dateTime + * @param uuid uuid + * @param password password + * @param patternWithDigits A string that is a 10 digit number. Can have leading zeros. + * @param patternWithDigitsAndDelimiter A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + */ + public FormatTest( + Integer integer, + Integer int32, + Long int64, + BigDecimal number, + Float _float, + Double _double, + BigDecimal decimal, + String string, + byte[] _byte, + File binary, + LocalDate date, + OffsetDateTime dateTime, + UUID uuid, + String password, + String patternWithDigits, + String patternWithDigitsAndDelimiter + ) { + this.integer = integer; + this.int32 = int32; + this.int64 = int64; + this.number = number; + this._float = _float; + this._double = _double; + this.decimal = decimal; + this.string = string; + this._byte = _byte; + this.binary = binary; + this.date = date; + this.dateTime = dateTime; + this.uuid = uuid; + this.password = password; + this.patternWithDigits = patternWithDigits; + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + } + + + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + */ + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + */ + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + /** + * Get int64 + * @return int64 + */ + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + */ + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + */ + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + */ + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + /** + * Get decimal + * @return decimal + */ + public BigDecimal getDecimal() { + return decimal; + } + + public void setDecimal(BigDecimal decimal) { + this.decimal = decimal; + } + + /** + * Get string + * @return string + */ + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + /** + * Get _byte + * @return _byte + */ + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + /** + * Get binary + * @return binary + */ + public File getBinary() { + return binary; + } + + public void setBinary(File binary) { + this.binary = binary; + } + + /** + * Get date + * @return date + */ + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + /** + * Get dateTime + * @return dateTime + */ + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + /** + * Get uuid + * @return uuid + */ + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + /** + * Get password + * @return password + */ + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + /** + * A string that is a 10 digit number. Can have leading zeros. + * @return patternWithDigits + */ + public String getPatternWithDigits() { + return patternWithDigits; + } + + public void setPatternWithDigits(String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + } + + /** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + * @return patternWithDigitsAndDelimiter + */ + public String getPatternWithDigitsAndDelimiter() { + return patternWithDigitsAndDelimiter; + } + + public void setPatternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" decimal: ").append(toIndentedString(decimal)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); + sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java new file mode 100644 index 0000000000..b5228bf6e6 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java @@ -0,0 +1,84 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; + + + +public class HasOnlyReadOnly { + + private String bar; + private String foo; + + /** + * Default constructor. + */ + public HasOnlyReadOnly() { + // JSON-B / Jackson + } + + /** + * Create HasOnlyReadOnly. + * + * @param bar bar + * @param foo foo + */ + public HasOnlyReadOnly( + String bar, + String foo + ) { + this.bar = bar; + this.foo = foo; + } + + + + /** + * Get bar + * @return bar + */ + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + /** + * Get foo + * @return foo + */ + public String getFoo() { + return foo; + } + + public void setFoo(String foo) { + this.foo = foo; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HealthCheckResult.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HealthCheckResult.java new file mode 100644 index 0000000000..97e9dba137 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HealthCheckResult.java @@ -0,0 +1,69 @@ +package org.openapitools.server.model; + +import org.openapitools.jackson.nullable.JsonNullable; + + +/** + * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + */ +public class HealthCheckResult { + + private String nullableMessage; + + /** + * Default constructor. + */ + public HealthCheckResult() { + // JSON-B / Jackson + } + + /** + * Create HealthCheckResult. + * + * @param nullableMessage nullableMessage + */ + public HealthCheckResult( + String nullableMessage + ) { + this.nullableMessage = nullableMessage; + } + + + + /** + * Get nullableMessage + * @return nullableMessage + */ + public String getNullableMessage() { + return nullableMessage; + } + + public void setNullableMessage(String nullableMessage) { + this.nullableMessage = nullableMessage; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HealthCheckResult {\n"); + + sb.append(" nullableMessage: ").append(toIndentedString(nullableMessage)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MapTest.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MapTest.java new file mode 100644 index 0000000000..4bef65f6a8 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MapTest.java @@ -0,0 +1,158 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; + + + +public class MapTest { + + private Map> mapMapOfString = new HashMap<>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + + private Map mapOfEnumString = new HashMap<>(); + private Map directMap = new HashMap<>(); + private Map indirectMap = new HashMap<>(); + + /** + * Default constructor. + */ + public MapTest() { + // JSON-B / Jackson + } + + /** + * Create MapTest. + * + * @param mapMapOfString mapMapOfString + * @param mapOfEnumString mapOfEnumString + * @param directMap directMap + * @param indirectMap indirectMap + */ + public MapTest( + Map> mapMapOfString, + Map mapOfEnumString, + Map directMap, + Map indirectMap + ) { + this.mapMapOfString = mapMapOfString; + this.mapOfEnumString = mapOfEnumString; + this.directMap = directMap; + this.indirectMap = indirectMap; + } + + + + /** + * Get mapMapOfString + * @return mapMapOfString + */ + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + */ + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + /** + * Get directMap + * @return directMap + */ + public Map getDirectMap() { + return directMap; + } + + public void setDirectMap(Map directMap) { + this.directMap = directMap; + } + + /** + * Get indirectMap + * @return indirectMap + */ + public Map getIndirectMap() { + return indirectMap; + } + + public void setIndirectMap(Map indirectMap) { + this.indirectMap = indirectMap; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append(" directMap: ").append(toIndentedString(directMap)).append("\n"); + sb.append(" indirectMap: ").append(toIndentedString(indirectMap)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 0000000000..0a6bef328e --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,105 @@ +package org.openapitools.server.model; + +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.openapitools.server.model.Animal; + + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private UUID uuid; + private OffsetDateTime dateTime; + private Map map = new HashMap<>(); + + /** + * Default constructor. + */ + public MixedPropertiesAndAdditionalPropertiesClass() { + // JSON-B / Jackson + } + + /** + * Create MixedPropertiesAndAdditionalPropertiesClass. + * + * @param uuid uuid + * @param dateTime dateTime + * @param map map + */ + public MixedPropertiesAndAdditionalPropertiesClass( + UUID uuid, + OffsetDateTime dateTime, + Map map + ) { + this.uuid = uuid; + this.dateTime = dateTime; + this.map = map; + } + + + + /** + * Get uuid + * @return uuid + */ + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + /** + * Get dateTime + * @return dateTime + */ + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + /** + * Get map + * @return map + */ + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Model200Response.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Model200Response.java new file mode 100644 index 0000000000..dc685bdf99 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Model200Response.java @@ -0,0 +1,86 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; + + +/** + * Model for testing model name starting with number + */ +public class Model200Response { + + private Integer name; + private String propertyClass; + + /** + * Default constructor. + */ + public Model200Response() { + // JSON-B / Jackson + } + + /** + * Create Model200Response. + * + * @param name name + * @param propertyClass propertyClass + */ + public Model200Response( + Integer name, + String propertyClass + ) { + this.name = name; + this.propertyClass = propertyClass; + } + + + + /** + * Get name + * @return name + */ + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get propertyClass + * @return propertyClass + */ + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelApiResponse.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelApiResponse.java new file mode 100644 index 0000000000..10d22866ed --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelApiResponse.java @@ -0,0 +1,101 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; + + + +public class ModelApiResponse { + + private Integer code; + private String type; + private String message; + + /** + * Default constructor. + */ + public ModelApiResponse() { + // JSON-B / Jackson + } + + /** + * Create ModelApiResponse. + * + * @param code code + * @param type type + * @param message message + */ + public ModelApiResponse( + Integer code, + String type, + String message + ) { + this.code = code; + this.type = type; + this.message = message; + } + + + + /** + * Get code + * @return code + */ + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + /** + * Get type + * @return type + */ + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + /** + * Get message + * @return message + */ + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelFile.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelFile.java new file mode 100644 index 0000000000..0721c23130 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelFile.java @@ -0,0 +1,69 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; + + +/** + * Must be named `File` for test. + */ +public class ModelFile { + + private String sourceURI; + + /** + * Default constructor. + */ + public ModelFile() { + // JSON-B / Jackson + } + + /** + * Create ModelFile. + * + * @param sourceURI Test capitalization + */ + public ModelFile( + String sourceURI + ) { + this.sourceURI = sourceURI; + } + + + + /** + * Test capitalization + * @return sourceURI + */ + public String getSourceURI() { + return sourceURI; + } + + public void setSourceURI(String sourceURI) { + this.sourceURI = sourceURI; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelFile {\n"); + + sb.append(" sourceURI: ").append(toIndentedString(sourceURI)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelList.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelList.java new file mode 100644 index 0000000000..6bba122e69 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelList.java @@ -0,0 +1,67 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; + + + +public class ModelList { + + private String _123list; + + /** + * Default constructor. + */ + public ModelList() { + // JSON-B / Jackson + } + + /** + * Create ModelList. + * + * @param _123list _123list + */ + public ModelList( + String _123list + ) { + this._123list = _123list; + } + + + + /** + * Get _123list + * @return _123list + */ + public String get123list() { + return _123list; + } + + public void set123list(String _123list) { + this._123list = _123list; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelList {\n"); + + sb.append(" _123list: ").append(toIndentedString(_123list)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelReturn.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelReturn.java new file mode 100644 index 0000000000..0b9538b4aa --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelReturn.java @@ -0,0 +1,69 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; + + +/** + * Model for testing reserved words + */ +public class ModelReturn { + + private Integer _return; + + /** + * Default constructor. + */ + public ModelReturn() { + // JSON-B / Jackson + } + + /** + * Create ModelReturn. + * + * @param _return _return + */ + public ModelReturn( + Integer _return + ) { + this._return = _return; + } + + + + /** + * Get _return + * @return _return + */ + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Name.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Name.java new file mode 100644 index 0000000000..a081e1d5c1 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Name.java @@ -0,0 +1,119 @@ +package org.openapitools.server.model; + + + +/** + * Model for testing model name same as property name + */ +public class Name { + + private Integer name; + private Integer snakeCase; + private String property; + private Integer _123number; + + /** + * Default constructor. + */ + public Name() { + // JSON-B / Jackson + } + + /** + * Create Name. + * + * @param name name + * @param snakeCase snakeCase + * @param property property + * @param _123number _123number + */ + public Name( + Integer name, + Integer snakeCase, + String property, + Integer _123number + ) { + this.name = name; + this.snakeCase = snakeCase; + this.property = property; + this._123number = _123number; + } + + + + /** + * Get name + * @return name + */ + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + */ + public Integer getSnakeCase() { + return snakeCase; + } + + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + /** + * Get property + * @return property + */ + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123number + * @return _123number + */ + public Integer get123number() { + return _123number; + } + + public void set123number(Integer _123number) { + this._123number = _123number; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123number: ").append(toIndentedString(_123number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NullableClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NullableClass.java new file mode 100644 index 0000000000..2e2c2659cd --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NullableClass.java @@ -0,0 +1,261 @@ +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; + + + +public class NullableClass extends HashMap { + + private Integer integerProp; + private BigDecimal numberProp; + private Boolean booleanProp; + private String stringProp; + private LocalDate dateProp; + private OffsetDateTime datetimeProp; + private List arrayNullableProp = new ArrayList<>(); + private List arrayAndItemsNullableProp = new ArrayList<>(); + private List arrayItemsNullable = new ArrayList<>(); + private Map objectNullableProp = new HashMap<>(); + private Map objectAndItemsNullableProp = new HashMap<>(); + private Map objectItemsNullable = new HashMap<>(); + + /** + * Default constructor. + */ + public NullableClass() { + // JSON-B / Jackson + } + + /** + * Create NullableClass. + * + * @param integerProp integerProp + * @param numberProp numberProp + * @param booleanProp booleanProp + * @param stringProp stringProp + * @param dateProp dateProp + * @param datetimeProp datetimeProp + * @param arrayNullableProp arrayNullableProp + * @param arrayAndItemsNullableProp arrayAndItemsNullableProp + * @param arrayItemsNullable arrayItemsNullable + * @param objectNullableProp objectNullableProp + * @param objectAndItemsNullableProp objectAndItemsNullableProp + * @param objectItemsNullable objectItemsNullable + */ + public NullableClass( + Integer integerProp, + BigDecimal numberProp, + Boolean booleanProp, + String stringProp, + LocalDate dateProp, + OffsetDateTime datetimeProp, + List arrayNullableProp, + List arrayAndItemsNullableProp, + List arrayItemsNullable, + Map objectNullableProp, + Map objectAndItemsNullableProp, + Map objectItemsNullable + ) { + this.integerProp = integerProp; + this.numberProp = numberProp; + this.booleanProp = booleanProp; + this.stringProp = stringProp; + this.dateProp = dateProp; + this.datetimeProp = datetimeProp; + this.arrayNullableProp = arrayNullableProp; + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + this.arrayItemsNullable = arrayItemsNullable; + this.objectNullableProp = objectNullableProp; + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + this.objectItemsNullable = objectItemsNullable; + } + + + + /** + * Get integerProp + * @return integerProp + */ + public Integer getIntegerProp() { + return integerProp; + } + + public void setIntegerProp(Integer integerProp) { + this.integerProp = integerProp; + } + + /** + * Get numberProp + * @return numberProp + */ + public BigDecimal getNumberProp() { + return numberProp; + } + + public void setNumberProp(BigDecimal numberProp) { + this.numberProp = numberProp; + } + + /** + * Get booleanProp + * @return booleanProp + */ + public Boolean getBooleanProp() { + return booleanProp; + } + + public void setBooleanProp(Boolean booleanProp) { + this.booleanProp = booleanProp; + } + + /** + * Get stringProp + * @return stringProp + */ + public String getStringProp() { + return stringProp; + } + + public void setStringProp(String stringProp) { + this.stringProp = stringProp; + } + + /** + * Get dateProp + * @return dateProp + */ + public LocalDate getDateProp() { + return dateProp; + } + + public void setDateProp(LocalDate dateProp) { + this.dateProp = dateProp; + } + + /** + * Get datetimeProp + * @return datetimeProp + */ + public OffsetDateTime getDatetimeProp() { + return datetimeProp; + } + + public void setDatetimeProp(OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + } + + /** + * Get arrayNullableProp + * @return arrayNullableProp + */ + public List getArrayNullableProp() { + return arrayNullableProp; + } + + public void setArrayNullableProp(List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + } + + /** + * Get arrayAndItemsNullableProp + * @return arrayAndItemsNullableProp + */ + public List getArrayAndItemsNullableProp() { + return arrayAndItemsNullableProp; + } + + public void setArrayAndItemsNullableProp(List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + } + + /** + * Get arrayItemsNullable + * @return arrayItemsNullable + */ + public List getArrayItemsNullable() { + return arrayItemsNullable; + } + + public void setArrayItemsNullable(List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + } + + /** + * Get objectNullableProp + * @return objectNullableProp + */ + public Map getObjectNullableProp() { + return objectNullableProp; + } + + public void setObjectNullableProp(Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + } + + /** + * Get objectAndItemsNullableProp + * @return objectAndItemsNullableProp + */ + public Map getObjectAndItemsNullableProp() { + return objectAndItemsNullableProp; + } + + public void setObjectAndItemsNullableProp(Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + } + + /** + * Get objectItemsNullable + * @return objectItemsNullable + */ + public Map getObjectItemsNullable() { + return objectItemsNullable; + } + + public void setObjectItemsNullable(Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NullableClass {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" integerProp: ").append(toIndentedString(integerProp)).append("\n"); + sb.append(" numberProp: ").append(toIndentedString(numberProp)).append("\n"); + sb.append(" booleanProp: ").append(toIndentedString(booleanProp)).append("\n"); + sb.append(" stringProp: ").append(toIndentedString(stringProp)).append("\n"); + sb.append(" dateProp: ").append(toIndentedString(dateProp)).append("\n"); + sb.append(" datetimeProp: ").append(toIndentedString(datetimeProp)).append("\n"); + sb.append(" arrayNullableProp: ").append(toIndentedString(arrayNullableProp)).append("\n"); + sb.append(" arrayAndItemsNullableProp: ").append(toIndentedString(arrayAndItemsNullableProp)).append("\n"); + sb.append(" arrayItemsNullable: ").append(toIndentedString(arrayItemsNullable)).append("\n"); + sb.append(" objectNullableProp: ").append(toIndentedString(objectNullableProp)).append("\n"); + sb.append(" objectAndItemsNullableProp: ").append(toIndentedString(objectAndItemsNullableProp)).append("\n"); + sb.append(" objectItemsNullable: ").append(toIndentedString(objectItemsNullable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NumberOnly.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NumberOnly.java new file mode 100644 index 0000000000..3a003f9709 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NumberOnly.java @@ -0,0 +1,67 @@ +package org.openapitools.server.model; + +import java.math.BigDecimal; + + + +public class NumberOnly { + + private BigDecimal justNumber; + + /** + * Default constructor. + */ + public NumberOnly() { + // JSON-B / Jackson + } + + /** + * Create NumberOnly. + * + * @param justNumber justNumber + */ + public NumberOnly( + BigDecimal justNumber + ) { + this.justNumber = justNumber; + } + + + + /** + * Get justNumber + * @return justNumber + */ + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java new file mode 100644 index 0000000000..57ee9e374e --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java @@ -0,0 +1,121 @@ +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.DeprecatedObject; + + + +public class ObjectWithDeprecatedFields { + + private String uuid; + private BigDecimal id; + private DeprecatedObject deprecatedRef; + private List bars = new ArrayList<>(); + + /** + * Default constructor. + */ + public ObjectWithDeprecatedFields() { + // JSON-B / Jackson + } + + /** + * Create ObjectWithDeprecatedFields. + * + * @param uuid uuid + * @param id id + * @param deprecatedRef deprecatedRef + * @param bars bars + */ + public ObjectWithDeprecatedFields( + String uuid, + BigDecimal id, + DeprecatedObject deprecatedRef, + List bars + ) { + this.uuid = uuid; + this.id = id; + this.deprecatedRef = deprecatedRef; + this.bars = bars; + } + + + + /** + * Get uuid + * @return uuid + */ + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + * Get id + * @return id + */ + public BigDecimal getId() { + return id; + } + + public void setId(BigDecimal id) { + this.id = id; + } + + /** + * Get deprecatedRef + * @return deprecatedRef + */ + public DeprecatedObject getDeprecatedRef() { + return deprecatedRef; + } + + public void setDeprecatedRef(DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + } + + /** + * Get bars + * @return bars + */ + public List getBars() { + return bars; + } + + public void setBars(List bars) { + this.bars = bars; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ObjectWithDeprecatedFields {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" deprecatedRef: ").append(toIndentedString(deprecatedRef)).append("\n"); + sb.append(" bars: ").append(toIndentedString(bars)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Order.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Order.java new file mode 100644 index 0000000000..39a04dc151 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Order.java @@ -0,0 +1,192 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; + + + +public class Order { + + private Long id; + private Long petId; + private Integer quantity; + private OffsetDateTime shipDate; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + + private StatusEnum status; + private Boolean complete = false; + + /** + * Default constructor. + */ + public Order() { + // JSON-B / Jackson + } + + /** + * Create Order. + * + * @param id id + * @param petId petId + * @param quantity quantity + * @param shipDate shipDate + * @param status Order Status + * @param complete complete + */ + public Order( + Long id, + Long petId, + Integer quantity, + OffsetDateTime shipDate, + StatusEnum status, + Boolean complete + ) { + this.id = id; + this.petId = petId; + this.quantity = quantity; + this.shipDate = shipDate; + this.status = status; + this.complete = complete; + } + + + + /** + * Get id + * @return id + */ + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + /** + * Get petId + * @return petId + */ + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + * Get quantity + * @return quantity + */ + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + * Get shipDate + * @return shipDate + */ + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + * @return status + */ + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + * Get complete + * @return complete + */ + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterComposite.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterComposite.java new file mode 100644 index 0000000000..92eb34508d --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterComposite.java @@ -0,0 +1,101 @@ +package org.openapitools.server.model; + +import java.math.BigDecimal; + + + +public class OuterComposite { + + private BigDecimal myNumber; + private String myString; + private Boolean myBoolean; + + /** + * Default constructor. + */ + public OuterComposite() { + // JSON-B / Jackson + } + + /** + * Create OuterComposite. + * + * @param myNumber myNumber + * @param myString myString + * @param myBoolean myBoolean + */ + public OuterComposite( + BigDecimal myNumber, + String myString, + Boolean myBoolean + ) { + this.myNumber = myNumber; + this.myString = myString; + this.myBoolean = myBoolean; + } + + + + /** + * Get myNumber + * @return myNumber + */ + public BigDecimal getMyNumber() { + return myNumber; + } + + public void setMyNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + } + + /** + * Get myString + * @return myString + */ + public String getMyString() { + return myString; + } + + public void setMyString(String myString) { + this.myString = myString; + } + + /** + * Get myBoolean + * @return myBoolean + */ + public Boolean getMyBoolean() { + return myBoolean; + } + + public void setMyBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterComposite {\n"); + + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); + sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnum.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnum.java new file mode 100644 index 0000000000..3cdb4cdeb7 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnum.java @@ -0,0 +1,44 @@ +package org.openapitools.server.model; + + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnum + */ + +public enum OuterEnum { + + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java new file mode 100644 index 0000000000..c8110bd330 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java @@ -0,0 +1,44 @@ +package org.openapitools.server.model; + + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumDefaultValue + */ + +public enum OuterEnumDefaultValue { + + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); + + private String value; + + OuterEnumDefaultValue(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumDefaultValue fromValue(String text) { + for (OuterEnumDefaultValue b : OuterEnumDefaultValue.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumInteger.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumInteger.java new file mode 100644 index 0000000000..b6d2661725 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumInteger.java @@ -0,0 +1,44 @@ +package org.openapitools.server.model; + + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumInteger + */ + +public enum OuterEnumInteger { + + NUMBER_0(0), + NUMBER_1(1), + NUMBER_2(2); + + private Integer value; + + OuterEnumInteger(Integer value) { + this.value = value; + } + + @JsonValue + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumInteger fromValue(String text) { + for (OuterEnumInteger b : OuterEnumInteger.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java new file mode 100644 index 0000000000..af1fe21752 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java @@ -0,0 +1,44 @@ +package org.openapitools.server.model; + + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnumIntegerDefaultValue + */ + +public enum OuterEnumIntegerDefaultValue { + + NUMBER_0(0), + NUMBER_1(1), + NUMBER_2(2); + + private Integer value; + + OuterEnumIntegerDefaultValue(Integer value) { + this.value = value; + } + + @JsonValue + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnumIntegerDefaultValue fromValue(String text) { + for (OuterEnumIntegerDefaultValue b : OuterEnumIntegerDefaultValue.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java new file mode 100644 index 0000000000..7a75e0e3b6 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java @@ -0,0 +1,67 @@ +package org.openapitools.server.model; + +import org.openapitools.server.model.OuterEnumInteger; + + + +public class OuterObjectWithEnumProperty { + + private OuterEnumInteger value; + + /** + * Default constructor. + */ + public OuterObjectWithEnumProperty() { + // JSON-B / Jackson + } + + /** + * Create OuterObjectWithEnumProperty. + * + * @param value value + */ + public OuterObjectWithEnumProperty( + OuterEnumInteger value + ) { + this.value = value; + } + + + + /** + * Get value + * @return value + */ + public OuterEnumInteger getValue() { + return value; + } + + public void setValue(OuterEnumInteger value) { + this.value = value; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterObjectWithEnumProperty {\n"); + + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Pet.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Pet.java new file mode 100644 index 0000000000..a040a9d288 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Pet.java @@ -0,0 +1,198 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.openapitools.server.model.Category; +import org.openapitools.server.model.Tag; + + + +public class Pet { + + private Long id; + private Category category; + private String name; + private Set photoUrls = new LinkedHashSet<>(); + private List tags = new ArrayList<>(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } + } + + + private StatusEnum status; + + /** + * Default constructor. + */ + public Pet() { + // JSON-B / Jackson + } + + /** + * Create Pet. + * + * @param id id + * @param category category + * @param name name + * @param photoUrls photoUrls + * @param tags tags + * @param status pet status in the store + */ + public Pet( + Long id, + Category category, + String name, + Set photoUrls, + List tags, + StatusEnum status + ) { + this.id = id; + this.category = category; + this.name = name; + this.photoUrls = photoUrls; + this.tags = tags; + this.status = status; + } + + + + /** + * Get id + * @return id + */ + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + /** + * Get category + * @return category + */ + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + /** + * Get name + * @return name + */ + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * Get photoUrls + * @return photoUrls + */ + public Set getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(Set photoUrls) { + this.photoUrls = photoUrls; + } + + /** + * Get tags + * @return tags + */ + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + * @return status + */ + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java new file mode 100644 index 0000000000..e62e2270ee --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java @@ -0,0 +1,83 @@ +package org.openapitools.server.model; + + + + +public class ReadOnlyFirst { + + private String bar; + private String baz; + + /** + * Default constructor. + */ + public ReadOnlyFirst() { + // JSON-B / Jackson + } + + /** + * Create ReadOnlyFirst. + * + * @param bar bar + * @param baz baz + */ + public ReadOnlyFirst( + String bar, + String baz + ) { + this.bar = bar; + this.baz = baz; + } + + + + /** + * Get bar + * @return bar + */ + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + /** + * Get baz + * @return baz + */ + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SingleRefType.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SingleRefType.java new file mode 100644 index 0000000000..6689e8a2b6 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SingleRefType.java @@ -0,0 +1,43 @@ +package org.openapitools.server.model; + + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets SingleRefType + */ + +public enum SingleRefType { + + ADMIN("admin"), + USER("user"); + + private String value; + + SingleRefType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static SingleRefType fromValue(String text) { + for (SingleRefType b : SingleRefType.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + text + "'"); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SpecialModelName.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SpecialModelName.java new file mode 100644 index 0000000000..2ab0a37019 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SpecialModelName.java @@ -0,0 +1,67 @@ +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; + + + +public class SpecialModelName { + + private Long $specialPropertyName; + + /** + * Default constructor. + */ + public SpecialModelName() { + // JSON-B / Jackson + } + + /** + * Create SpecialModelName. + * + * @param $specialPropertyName $specialPropertyName + */ + public SpecialModelName( + Long $specialPropertyName + ) { + this.$specialPropertyName = $specialPropertyName; + } + + + + /** + * Get $specialPropertyName + * @return $specialPropertyName + */ + public Long get$SpecialPropertyName() { + return $specialPropertyName; + } + + public void set$SpecialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" $specialPropertyName: ").append(toIndentedString($specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Tag.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Tag.java new file mode 100644 index 0000000000..494d8fcf92 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Tag.java @@ -0,0 +1,83 @@ +package org.openapitools.server.model; + + + + +public class Tag { + + private Long id; + private String name; + + /** + * Default constructor. + */ + public Tag() { + // JSON-B / Jackson + } + + /** + * Create Tag. + * + * @param id id + * @param name name + */ + public Tag( + Long id, + String name + ) { + this.id = id; + this.name = name; + } + + + + /** + * Get id + * @return id + */ + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + /** + * Get name + * @return name + */ + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/User.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/User.java new file mode 100644 index 0000000000..8110b66225 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/User.java @@ -0,0 +1,185 @@ +package org.openapitools.server.model; + + + + +public class User { + + private Long id; + private String username; + private String firstName; + private String lastName; + private String email; + private String password; + private String phone; + private Integer userStatus; + + /** + * Default constructor. + */ + public User() { + // JSON-B / Jackson + } + + /** + * Create User. + * + * @param id id + * @param username username + * @param firstName firstName + * @param lastName lastName + * @param email email + * @param password password + * @param phone phone + * @param userStatus User Status + */ + public User( + Long id, + String username, + String firstName, + String lastName, + String email, + String password, + String phone, + Integer userStatus + ) { + this.id = id; + this.username = username; + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + this.password = password; + this.phone = phone; + this.userStatus = userStatus; + } + + + + /** + * Get id + * @return id + */ + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + /** + * Get username + * @return username + */ + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + /** + * Get firstName + * @return firstName + */ + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * Get lastName + * @return lastName + */ + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * Get email + * @return email + */ + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + /** + * Get password + * @return password + */ + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + /** + * Get phone + * @return phone + */ + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + * @return userStatus + */ + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/package-info.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/package-info.java new file mode 100644 index 0000000000..1025e91aed --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/package-info.java @@ -0,0 +1 @@ +package org.openapitools.server; \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/se/src/main/resources/META-INF/openapi.yml b/samples/server/petstore/java-helidon-server/se/src/main/resources/META-INF/openapi.yml new file mode 100644 index 0000000000..a599f08c0f --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/resources/META-INF/openapi.yml @@ -0,0 +1,2168 @@ +openapi: 3.0.0 +info: + description: "This spec is mainly for testing Petstore server and contains fake\ + \ endpoints, models. Please do not use this for any other purpose. Special characters:\ + \ \" \\" + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +servers: +- description: petstore server + url: "http://{server}.swagger.io:{port}/v2" + variables: + server: + default: petstore + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" +- description: The local server + url: "https://localhost:8080/{version}" + variables: + version: + default: v2 + enum: + - v1 + - v2 +- description: The local server without variables + url: https://127.0.0.1/no_varaible +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /foo: + get: + responses: + default: + content: + application/json: + schema: + $ref: '#/components/schemas/_foo_get_default_response' + description: response + x-accepts: application/json + /pet: + post: + description: "" + operationId: addPet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + description: Successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + x-content-type: application/json + x-accepts: application/json + put: + description: "" + operationId: updatePet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + description: Successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + "405": + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + x-webclient-blocking: true + x-content-type: application/json + x-accepts: application/json + servers: + - url: http://petstore.swagger.io/v2 + - url: http://path-server-test.petstore.local/v2 + - description: test server with variables + url: "http://{server}.swagger.io:{port}/v2" + variables: + server: + default: petstore + description: target server + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - deprecated: true + description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid status value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by status + tags: + - pet + x-webclient-blocking: true + x-accepts: application/json + /pet/findByTags: + get: + deprecated: true + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + items: + type: string + type: array + uniqueItems: true + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + uniqueItems: true + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + uniqueItems: true + description: successful operation + "400": + description: Invalid tag value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by tags + tags: + - pet + x-webclient-blocking: true + x-accepts: application/json + /pet/{petId}: + delete: + description: "" + operationId: deletePet + parameters: + - explode: false + in: header + name: api_key + required: false + schema: + type: string + style: simple + - description: Pet id to delete + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + description: Successful operation + "400": + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + x-accepts: application/json + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + x-webclient-blocking: true + x-accepts: application/json + post: + description: "" + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/updatePetWithForm_request' + responses: + "200": + description: Successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + /pet/{petId}/uploadImage: + post: + description: "" + operationId: uploadFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFile_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + x-content-type: multipart/form-data + x-accepts: application/json + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + content: + application/json: + schema: + additionalProperties: + format: int32 + type: integer + type: object + description: successful operation + security: + - api_key: [] + summary: Returns pet inventories by status + tags: + - store + x-accepts: application/json + /store/order: + post: + description: "" + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid Order + summary: Place an order for a pet + tags: + - store + x-content-type: application/json + x-accepts: application/json + /store/order/{order_id}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - description: ID of the order that needs to be deleted + explode: false + in: path + name: order_id + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Delete purchase order by ID + tags: + - store + x-accepts: application/json + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generated exceptions + operationId: getOrderById + parameters: + - description: ID of pet that needs to be fetched + explode: false + in: path + name: order_id + required: true + schema: + format: int64 + maximum: 5 + minimum: 1 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Find purchase order by ID + tags: + - store + x-accepts: application/json + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + description: successful operation + summary: Create user + tags: + - user + x-content-type: application/json + x-accepts: application/json + /user/createWithArray: + post: + description: "" + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-content-type: application/json + x-accepts: application/json + /user/createWithList: + post: + description: "" + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-content-type: application/json + x-accepts: application/json + /user/login: + get: + description: "" + operationId: loginUser + parameters: + - description: The user name for login + explode: true + in: query + name: username + required: true + schema: + type: string + style: form + - description: The password for login in clear text + explode: true + in: query + name: password + required: true + schema: + type: string + style: form + responses: + "200": + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + explode: false + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when token expires + explode: false + schema: + format: date-time + type: string + style: simple + "400": + description: Invalid username/password supplied + summary: Logs user into the system + tags: + - user + x-accepts: application/json + /user/logout: + get: + description: "" + operationId: logoutUser + responses: + default: + description: successful operation + summary: Logs out current logged in user session + tags: + - user + x-accepts: application/json + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - description: The name that needs to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Delete user + tags: + - user + x-accepts: application/json + get: + description: "" + operationId: getUserByName + parameters: + - description: The name that needs to be fetched. Use user1 for testing. + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + description: successful operation + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Get user by user name + tags: + - user + x-accepts: application/json + put: + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - description: name that need to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + responses: + "400": + description: Invalid user supplied + "404": + description: User not found + summary: Updated user + tags: + - user + x-content-type: application/json + x-accepts: application/json + /fake_classname_test: + patch: + description: To test class name in snake case + operationId: testClassname + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + security: + - api_key_query: [] + summary: To test class name in snake case + tags: + - fake_classname_tags 123#$%^ + x-content-type: application/json + x-accepts: application/json + /fake: + delete: + description: Fake endpoint to test group parameters (optional) + operationId: testGroupParameters + parameters: + - description: Required String in group parameters + explode: true + in: query + name: required_string_group + required: true + schema: + type: integer + style: form + - description: Required Boolean in group parameters + explode: false + in: header + name: required_boolean_group + required: true + schema: + type: boolean + style: simple + - description: Required Integer in group parameters + explode: true + in: query + name: required_int64_group + required: true + schema: + format: int64 + type: integer + style: form + - description: String in group parameters + explode: true + in: query + name: string_group + required: false + schema: + type: integer + style: form + - description: Boolean in group parameters + explode: false + in: header + name: boolean_group + required: false + schema: + type: boolean + style: simple + - description: Integer in group parameters + explode: true + in: query + name: int64_group + required: false + schema: + format: int64 + type: integer + style: form + responses: + "400": + description: Someting wrong + security: + - bearer_test: [] + summary: Fake endpoint to test group parameters (optional) + tags: + - fake + x-group-parameters: true + x-accepts: application/json + get: + description: To test enum parameters + operationId: testEnumParameters + parameters: + - description: Header parameter enum test (string array) + explode: false + in: header + name: enum_header_string_array + required: false + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: simple + - description: Header parameter enum test (string) + explode: false + in: header + name: enum_header_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: simple + - description: Query parameter enum test (string array) + explode: true + in: query + name: enum_query_string_array + required: false + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: form + - description: Query parameter enum test (string) + explode: true + in: query + name: enum_query_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_integer + required: false + schema: + enum: + - 1 + - -2 + format: int32 + type: integer + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_double + required: false + schema: + enum: + - 1.1 + - -1.2 + format: double + type: number + style: form + - explode: true + in: query + name: enum_query_model_array + required: false + schema: + items: + $ref: '#/components/schemas/EnumClass' + type: array + style: form + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testEnumParameters_request' + responses: + "400": + description: Invalid request + "404": + description: Not found + summary: To test enum parameters + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + patch: + description: To test "client" model + operationId: testClientModel + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test "client" model + tags: + - fake + x-content-type: application/json + x-accepts: application/json + post: + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testEndpointParameters_request' + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + security: + - http_basic_test: [] + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + /fake/outer/number: + post: + description: Test serialization of outer number types + operationId: fakeOuterNumberSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterNumber' + description: Input number as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterNumber' + description: Output number + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/property/enum-int: + post: + description: Test serialization of enum (int) properties with examples + operationId: fakePropertyEnumIntegerSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterObjectWithEnumProperty' + description: Input enum (int) as post body + required: true + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterObjectWithEnumProperty' + description: Output enum (int) + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/outer/string: + post: + description: Test serialization of outer string types + operationId: fakeOuterStringSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterString' + description: Input string as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterString' + description: Output string + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/outer/boolean: + post: + description: Test serialization of outer boolean types + operationId: fakeOuterBooleanSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Input boolean as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Output boolean + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/outer/composite: + post: + description: Test serialization of object with outer number type + operationId: fakeOuterCompositeSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterComposite' + description: Input composite as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterComposite' + description: Output composite + tags: + - fake + x-content-type: application/json + x-accepts: '*/*' + /fake/jsonFormData: + get: + description: "" + operationId: testJsonFormData + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/testJsonFormData_request' + responses: + "200": + description: successful operation + summary: test json serialization of form data + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + /fake/inline-additionalProperties: + post: + description: "" + operationId: testInlineAdditionalProperties + requestBody: + content: + application/json: + schema: + additionalProperties: + type: string + type: object + description: request body + required: true + responses: + "200": + description: successful operation + summary: test inline additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json + /fake/body-with-query-params: + put: + operationId: testBodyWithQueryParams + parameters: + - explode: true + in: query + name: query + required: true + schema: + type: string + style: form + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + responses: + "200": + description: Success + tags: + - fake + x-content-type: application/json + x-accepts: application/json + /another-fake/dummy: + patch: + description: To test special tags and operation ID starting with number + operationId: 123_test_@#$%_special_tags + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test special tags + tags: + - $another-fake? + x-content-type: application/json + x-accepts: application/json + /fake/body-with-file-schema: + put: + description: "For this test, the body for this request must reference a schema\ + \ named `File`." + operationId: testBodyWithFileSchema + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FileSchemaTestClass' + required: true + responses: + "200": + description: Success + tags: + - fake + x-content-type: application/json + x-accepts: application/json + /fake/body-with-binary: + put: + description: "For this test, the body has to be a binary file." + operationId: testBodyWithBinary + requestBody: + content: + image/png: + schema: + format: binary + nullable: true + type: string + description: image to upload + required: true + responses: + "200": + description: Success + tags: + - fake + x-content-type: image/png + x-accepts: application/json + /fake/test-query-parameters: + put: + description: To test the collection format in query parameters + operationId: testQueryParameterCollectionFormat + parameters: + - explode: false + in: query + name: pipe + required: true + schema: + items: + type: string + type: array + style: pipeDelimited + - explode: false + in: query + name: ioutil + required: true + schema: + items: + type: string + type: array + style: form + - explode: false + in: query + name: http + required: true + schema: + items: + type: string + type: array + style: spaceDelimited + - explode: false + in: query + name: url + required: true + schema: + items: + type: string + type: array + style: form + - explode: true + in: query + name: context + required: true + schema: + items: + type: string + type: array + style: form + - explode: true + in: query + name: language + required: false + schema: + additionalProperties: + format: string + type: string + type: object + style: form + - allowEmptyValue: true + explode: true + in: query + name: allowEmpty + required: true + schema: + type: string + style: form + responses: + "200": + description: Success + tags: + - fake + x-accepts: application/json + /fake/{petId}/uploadImageWithRequiredFile: + post: + description: "" + operationId: uploadFileWithRequiredFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFileWithRequiredFile_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image (required) + tags: + - pet + x-content-type: multipart/form-data + x-accepts: application/json + /fake/health: + get: + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/HealthCheckResult' + description: The instance started successfully + summary: Health check endpoint + tags: + - fake + x-accepts: application/json + /fake/http-signature-test: + get: + operationId: fake-http-signature-test + parameters: + - description: query parameter + explode: true + in: query + name: query_1 + required: false + schema: + type: string + style: form + - description: header parameter + explode: false + in: header + name: header_1 + required: false + schema: + type: string + style: simple + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + description: The instance started successfully + security: + - http_signature_test: [] + summary: test http signature authentication + tags: + - fake + x-content-type: application/json + x-accepts: application/json +components: + requestBodies: + UserArray: + content: + application/json: + schema: + items: + $ref: '#/components/schemas/User' + type: array + description: List of user object + required: true + Client: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + schemas: + Foo: + example: + bar: bar + properties: + bar: + default: bar + type: string + type: object + Bar: + default: bar + type: string + Order: + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: 2000-01-23T04:56:07.000+00:00 + complete: false + status: placed + properties: + id: + format: int64 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + type: boolean + type: object + xml: + name: Order + Category: + example: + name: default-name + id: 6 + properties: + id: + format: int64 + type: integer + name: + default: default-name + type: string + required: + - name + type: object + xml: + name: Category + User: + example: + firstName: firstName + lastName: lastName + password: password + userStatus: 6 + phone: phone + id: 0 + email: email + username: username + properties: + id: + format: int64 + type: integer + x-is-unique: true + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + type: object + xml: + name: User + Tag: + example: + name: name + id: 1 + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + xml: + name: Tag + Pet: + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: default-name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + type: integer + x-is-unique: true + category: + $ref: '#/components/schemas/Category' + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + uniqueItems: true + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + xml: + name: Pet + ApiResponse: + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + type: object + Return: + description: Model for testing reserved words + properties: + return: + format: int32 + type: integer + xml: + name: Return + Name: + description: Model for testing model name same as property name + properties: + name: + format: int32 + type: integer + snake_case: + format: int32 + readOnly: true + type: integer + property: + type: string + "123Number": + readOnly: true + type: integer + required: + - name + xml: + name: Name + "200_response": + description: Model for testing model name starting with number + properties: + name: + format: int32 + type: integer + class: + type: string + xml: + name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - $ref: '#/components/schemas/Dog_allOf' + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - $ref: '#/components/schemas/Cat_allOf' + Animal: + discriminator: + propertyName: className + properties: + className: + type: string + color: + default: red + type: string + required: + - className + type: object + AnimalFarm: + items: + $ref: '#/components/schemas/Animal' + type: array + format_test: + properties: + integer: + maximum: 100 + minimum: 10 + type: integer + int32: + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + format: int64 + type: integer + number: + maximum: 543.2 + minimum: 32.1 + type: number + float: + format: float + maximum: 987.6 + minimum: 54.3 + type: number + double: + format: double + maximum: 123.4 + minimum: 67.8 + type: number + decimal: + format: number + type: string + string: + pattern: "/[a-z]/i" + type: string + byte: + format: byte + type: string + binary: + format: binary + type: string + date: + format: date + type: string + dateTime: + format: date-time + type: string + uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + type: string + password: + format: password + maxLength: 64 + minLength: 10 + type: string + pattern_with_digits: + description: A string that is a 10 digit number. Can have leading zeros. + pattern: "^\\d{10}$" + type: string + pattern_with_digits_and_delimiter: + description: A string starting with 'image_' (case insensitive) and one + to three digits following i.e. Image_01. + pattern: "/^image_\\d{1,3}$/i" + type: string + required: + - byte + - date + - number + - password + type: object + EnumClass: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + Enum_Test: + properties: + enum_string: + enum: + - UPPER + - lower + - "" + type: string + enum_string_required: + enum: + - UPPER + - lower + - "" + type: string + enum_integer: + enum: + - 1 + - -1 + format: int32 + type: integer + enum_number: + enum: + - 1.1 + - -1.2 + format: double + type: number + outerEnum: + $ref: '#/components/schemas/OuterEnum' + outerEnumInteger: + $ref: '#/components/schemas/OuterEnumInteger' + outerEnumDefaultValue: + $ref: '#/components/schemas/OuterEnumDefaultValue' + outerEnumIntegerDefaultValue: + $ref: '#/components/schemas/OuterEnumIntegerDefaultValue' + required: + - enum_string_required + type: object + AdditionalPropertiesClass: + properties: + map_property: + additionalProperties: + type: string + type: object + map_of_map_property: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + type: object + MixedPropertiesAndAdditionalPropertiesClass: + properties: + uuid: + format: uuid + type: string + dateTime: + format: date-time + type: string + map: + additionalProperties: + $ref: '#/components/schemas/Animal' + type: object + type: object + List: + properties: + "123-list": + type: string + type: object + Client: + example: + client: client + properties: + client: + type: string + type: object + ReadOnlyFirst: + properties: + bar: + readOnly: true + type: string + baz: + type: string + type: object + hasOnlyReadOnly: + properties: + bar: + readOnly: true + type: string + foo: + readOnly: true + type: string + type: object + Capitalization: + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: | + Name of the pet + type: string + type: object + MapTest: + properties: + map_map_of_string: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + map_of_enum_string: + additionalProperties: + enum: + - UPPER + - lower + type: string + type: object + direct_map: + additionalProperties: + type: boolean + type: object + indirect_map: + additionalProperties: + type: boolean + type: object + type: object + ArrayTest: + properties: + array_of_string: + items: + type: string + maxItems: 3 + minItems: 0 + type: array + array_array_of_integer: + items: + items: + format: int64 + type: integer + type: array + type: array + array_array_of_model: + items: + items: + $ref: '#/components/schemas/ReadOnlyFirst' + type: array + type: array + type: object + NumberOnly: + properties: + JustNumber: + type: number + type: object + ArrayOfNumberOnly: + properties: + ArrayNumber: + items: + type: number + type: array + type: object + ArrayOfArrayOfNumberOnly: + properties: + ArrayArrayNumber: + items: + items: + type: number + type: array + type: array + type: object + EnumArrays: + properties: + just_symbol: + enum: + - '>=' + - $ + type: string + array_enum: + items: + enum: + - fish + - crab + type: string + type: array + type: object + OuterEnum: + enum: + - placed + - approved + - delivered + nullable: true + type: string + OuterEnumInteger: + enum: + - 0 + - 1 + - 2 + example: 2 + type: integer + OuterEnumDefaultValue: + default: placed + enum: + - placed + - approved + - delivered + type: string + OuterEnumIntegerDefaultValue: + default: 0 + enum: + - 0 + - 1 + - 2 + type: integer + OuterComposite: + example: + my_string: my_string + my_number: 0.8008281904610115 + my_boolean: true + properties: + my_number: + type: number + my_string: + type: string + my_boolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + type: object + OuterNumber: + type: number + OuterString: + type: string + OuterBoolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + StringBooleanMap: + additionalProperties: + type: boolean + type: object + FileSchemaTestClass: + example: + file: + sourceURI: sourceURI + files: + - sourceURI: sourceURI + - sourceURI: sourceURI + properties: + file: + $ref: '#/components/schemas/File' + files: + items: + $ref: '#/components/schemas/File' + type: array + type: object + File: + description: Must be named `File` for test. + example: + sourceURI: sourceURI + properties: + sourceURI: + description: Test capitalization + type: string + type: object + _special_model.name_: + properties: + $special[property.name]: + format: int64 + type: integer + xml: + name: "$special[model.name]" + HealthCheckResult: + description: Just a string to inform instance is up and running. Make it nullable + in hope to get it as pointer in generated model. + example: + NullableMessage: NullableMessage + properties: + NullableMessage: + nullable: true + type: string + type: object + NullableClass: + additionalProperties: + nullable: true + type: object + properties: + integer_prop: + nullable: true + type: integer + number_prop: + nullable: true + type: number + boolean_prop: + nullable: true + type: boolean + string_prop: + nullable: true + type: string + date_prop: + format: date + nullable: true + type: string + datetime_prop: + format: date-time + nullable: true + type: string + array_nullable_prop: + items: + type: object + nullable: true + type: array + array_and_items_nullable_prop: + items: + nullable: true + type: object + nullable: true + type: array + array_items_nullable: + items: + nullable: true + type: object + type: array + object_nullable_prop: + additionalProperties: + type: object + nullable: true + type: object + object_and_items_nullable_prop: + additionalProperties: + nullable: true + type: object + nullable: true + type: object + object_items_nullable: + additionalProperties: + nullable: true + type: object + type: object + type: object + OuterObjectWithEnumProperty: + example: + value: 2 + properties: + value: + $ref: '#/components/schemas/OuterEnumInteger' + required: + - value + type: object + DeprecatedObject: + deprecated: true + properties: + name: + type: string + type: object + ObjectWithDeprecatedFields: + properties: + uuid: + type: string + id: + deprecated: true + type: number + deprecatedRef: + $ref: '#/components/schemas/DeprecatedObject' + bars: + deprecated: true + items: + $ref: '#/components/schemas/Bar' + type: array + type: object + AllOfWithSingleRef: + properties: + username: + type: string + SingleRefType: + allOf: + - $ref: '#/components/schemas/SingleRefType' + type: object + SingleRefType: + enum: + - admin + - user + title: SingleRefType + type: string + _foo_get_default_response: + example: + string: + bar: bar + properties: + string: + $ref: '#/components/schemas/Foo' + type: object + updatePetWithForm_request: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + uploadFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + testEnumParameters_request: + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + enum_form_string: + default: -efg + description: Form parameter enum test (string) + enum: + - _abc + - -efg + - (xyz) + type: string + type: object + testEndpointParameters_request: + properties: + integer: + description: None + maximum: 100 + minimum: 10 + type: integer + int32: + description: None + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + description: None + format: int64 + type: integer + number: + description: None + maximum: 543.2 + minimum: 32.1 + type: number + float: + description: None + format: float + maximum: 987.6 + type: number + double: + description: None + format: double + maximum: 123.4 + minimum: 67.8 + type: number + string: + description: None + pattern: "/[a-z]/i" + type: string + pattern_without_delimiter: + description: None + pattern: "^[A-Z].*" + type: string + byte: + description: None + format: byte + type: string + binary: + description: None + format: binary + type: string + date: + description: None + format: date + type: string + dateTime: + description: None + format: date-time + type: string + password: + description: None + format: password + maxLength: 64 + minLength: 10 + type: string + callback: + description: None + type: string + required: + - byte + - double + - number + - pattern_without_delimiter + type: object + testJsonFormData_request: + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + type: object + uploadFileWithRequiredFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + format: binary + type: string + required: + - requiredFile + type: object + Dog_allOf: + properties: + breed: + type: string + type: object + example: null + Cat_allOf: + properties: + declawed: + type: boolean + type: object + example: null + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey + api_key_query: + in: query + name: api_key_query + type: apiKey + http_basic_test: + scheme: basic + type: http + bearer_test: + bearerFormat: JWT + scheme: bearer + type: http + http_signature_test: + scheme: signature + type: http diff --git a/samples/server/petstore/java-helidon-server/se/src/main/resources/application.yaml b/samples/server/petstore/java-helidon-server/se/src/main/resources/application.yaml new file mode 100644 index 0000000000..2c0422edc7 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/resources/application.yaml @@ -0,0 +1,3 @@ +server: + port: 8080 + host: petstore.swagger.io diff --git a/samples/server/petstore/java-helidon-server/se/src/main/resources/logging.properties b/samples/server/petstore/java-helidon-server/se/src/main/resources/logging.properties new file mode 100644 index 0000000000..cd238eb661 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/main/resources/logging.properties @@ -0,0 +1,19 @@ + +# Example Logging Configuration File +# For more information see $JAVA_HOME/jre/lib/logging.properties + +# Send messages to the console +handlers=io.helidon.common.HelidonConsoleHandler + +# HelidonConsoleHandler uses a SimpleFormatter subclass that replaces "!thread!" with the current thread +java.util.logging.SimpleFormatter.format=%1$tY.%1$tm.%1$td %1$tH:%1$tM:%1$tS %4$s %3$s !thread!: %5$s%6$s%n + +# Global logging level. Can be overridden by specific loggers +.level=INFO + +# Component specific log levels +#io.helidon.webserver.level=INFO +#io.helidon.config.level=INFO +#io.helidon.security.level=INFO +#io.helidon.common.level=INFO +#io.netty.level=INFO diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/MainTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/MainTest.java new file mode 100644 index 0000000000..3035d3c4fc --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/MainTest.java @@ -0,0 +1,47 @@ +package org.openapitools.server; + +import java.util.Collections; +import java.util.concurrent.TimeUnit; + +import jakarta.json.Json; +import jakarta.json.JsonBuilderFactory; + +import io.helidon.media.jsonp.JsonpSupport; +import io.helidon.webclient.WebClient; +import io.helidon.webserver.WebServer; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public class MainTest { + + private static WebServer webServer; + private static WebClient webClient; + private static final JsonBuilderFactory JSON_BUILDER = Json.createBuilderFactory(Collections.emptyMap()); + + @BeforeAll + public static void startTheServer() throws Exception { + webServer = Main.startServer().await(); + + webClient = WebClient.builder() + .baseUri("http://localhost:" + webServer.port()) + .addMediaSupport(JsonpSupport.create()) + .build(); + } + + @AfterAll + public static void stopServer() throws Exception { + if (webServer != null) { + webServer.shutdown() + .toCompletableFuture() + .get(10, TimeUnit.SECONDS); + } + } + + @Test + public void test() throws Exception { + } +} \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/AdditionalPropertiesClassTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/AdditionalPropertiesClassTest.java new file mode 100644 index 0000000000..87b0cf9126 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/AdditionalPropertiesClassTest.java @@ -0,0 +1,50 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for AdditionalPropertiesClass + */ +public class AdditionalPropertiesClassTest { + private final AdditionalPropertiesClass model = new AdditionalPropertiesClass(); + + /** + * Model tests for AdditionalPropertiesClass + */ + @Test + public void testAdditionalPropertiesClass() { + // TODO: test AdditionalPropertiesClass + } + + /** + * Test the property 'mapProperty' + */ + @Test + public void mapPropertyTest() { + // TODO: test mapProperty + } + + /** + * Test the property 'mapOfMapProperty' + */ + @Test + public void mapOfMapPropertyTest() { + // TODO: test mapOfMapProperty + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/AllOfWithSingleRefTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/AllOfWithSingleRefTest.java new file mode 100644 index 0000000000..83a14ba827 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/AllOfWithSingleRefTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.openapitools.server.model.SingleRefType; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for AllOfWithSingleRef + */ +public class AllOfWithSingleRefTest { + private final AllOfWithSingleRef model = new AllOfWithSingleRef(); + + /** + * Model tests for AllOfWithSingleRef + */ + @Test + public void testAllOfWithSingleRef() { + // TODO: test AllOfWithSingleRef + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'singleRefType' + */ + @Test + public void singleRefTypeTest() { + // TODO: test singleRefType + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/AnimalTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/AnimalTest.java new file mode 100644 index 0000000000..1299d46ba6 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/AnimalTest.java @@ -0,0 +1,53 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Cat; +import org.openapitools.server.model.Dog; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Animal + */ +public class AnimalTest { + private final Animal model = new Animal(); + + /** + * Model tests for Animal + */ + @Test + public void testAnimal() { + // TODO: test Animal + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnlyTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnlyTest.java new file mode 100644 index 0000000000..d67cac0b05 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnlyTest.java @@ -0,0 +1,43 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayOfArrayOfNumberOnly + */ +public class ArrayOfArrayOfNumberOnlyTest { + private final ArrayOfArrayOfNumberOnly model = new ArrayOfArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfArrayOfNumberOnly + */ + @Test + public void testArrayOfArrayOfNumberOnly() { + // TODO: test ArrayOfArrayOfNumberOnly + } + + /** + * Test the property 'arrayArrayNumber' + */ + @Test + public void arrayArrayNumberTest() { + // TODO: test arrayArrayNumber + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ArrayOfNumberOnlyTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ArrayOfNumberOnlyTest.java new file mode 100644 index 0000000000..150ba7b070 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ArrayOfNumberOnlyTest.java @@ -0,0 +1,43 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayOfNumberOnly + */ +public class ArrayOfNumberOnlyTest { + private final ArrayOfNumberOnly model = new ArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfNumberOnly + */ + @Test + public void testArrayOfNumberOnly() { + // TODO: test ArrayOfNumberOnly + } + + /** + * Test the property 'arrayNumber' + */ + @Test + public void arrayNumberTest() { + // TODO: test arrayNumber + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ArrayTestTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ArrayTestTest.java new file mode 100644 index 0000000000..a2d4f750e1 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ArrayTestTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.ReadOnlyFirst; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ArrayTest + */ +public class ArrayTestTest { + private final ArrayTest model = new ArrayTest(); + + /** + * Model tests for ArrayTest + */ + @Test + public void testArrayTest() { + // TODO: test ArrayTest + } + + /** + * Test the property 'arrayOfString' + */ + @Test + public void arrayOfStringTest() { + // TODO: test arrayOfString + } + + /** + * Test the property 'arrayArrayOfInteger' + */ + @Test + public void arrayArrayOfIntegerTest() { + // TODO: test arrayArrayOfInteger + } + + /** + * Test the property 'arrayArrayOfModel' + */ + @Test + public void arrayArrayOfModelTest() { + // TODO: test arrayArrayOfModel + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CapitalizationTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CapitalizationTest.java new file mode 100644 index 0000000000..084a2885fc --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CapitalizationTest.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Capitalization + */ +public class CapitalizationTest { + private final Capitalization model = new Capitalization(); + + /** + * Model tests for Capitalization + */ + @Test + public void testCapitalization() { + // TODO: test Capitalization + } + + /** + * Test the property 'smallCamel' + */ + @Test + public void smallCamelTest() { + // TODO: test smallCamel + } + + /** + * Test the property 'capitalCamel' + */ + @Test + public void capitalCamelTest() { + // TODO: test capitalCamel + } + + /** + * Test the property 'smallSnake' + */ + @Test + public void smallSnakeTest() { + // TODO: test smallSnake + } + + /** + * Test the property 'capitalSnake' + */ + @Test + public void capitalSnakeTest() { + // TODO: test capitalSnake + } + + /** + * Test the property 'scAETHFlowPoints' + */ + @Test + public void scAETHFlowPointsTest() { + // TODO: test scAETHFlowPoints + } + + /** + * Test the property 'ATT_NAME' + */ + @Test + public void ATT_NAMETest() { + // TODO: test ATT_NAME + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CatAllOfTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CatAllOfTest.java new file mode 100644 index 0000000000..ab121c24d9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CatAllOfTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for CatAllOf + */ +public class CatAllOfTest { + private final CatAllOf model = new CatAllOf(); + + /** + * Model tests for CatAllOf + */ + @Test + public void testCatAllOf() { + // TODO: test CatAllOf + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CatTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CatTest.java new file mode 100644 index 0000000000..121dcc9756 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CatTest.java @@ -0,0 +1,60 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Animal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Cat + */ +public class CatTest { + private final Cat model = new Cat(); + + /** + * Model tests for Cat + */ + @Test + public void testCat() { + // TODO: test Cat + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CategoryTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CategoryTest.java new file mode 100644 index 0000000000..2618c8fd93 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/CategoryTest.java @@ -0,0 +1,48 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ClassModelTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ClassModelTest.java new file mode 100644 index 0000000000..f62de6d1cc --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ClassModelTest.java @@ -0,0 +1,40 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ClassModel + */ +public class ClassModelTest { + private final ClassModel model = new ClassModel(); + + /** + * Model tests for ClassModel + */ + @Test + public void testClassModel() { + // TODO: test ClassModel + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ClientTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ClientTest.java new file mode 100644 index 0000000000..a9f4c21ebf --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ClientTest.java @@ -0,0 +1,40 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Client + */ +public class ClientTest { + private final Client model = new Client(); + + /** + * Model tests for Client + */ + @Test + public void testClient() { + // TODO: test Client + } + + /** + * Test the property 'client' + */ + @Test + public void clientTest() { + // TODO: test client + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/DeprecatedObjectTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/DeprecatedObjectTest.java new file mode 100644 index 0000000000..9ad380437c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/DeprecatedObjectTest.java @@ -0,0 +1,40 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for DeprecatedObject + */ +public class DeprecatedObjectTest { + private final DeprecatedObject model = new DeprecatedObject(); + + /** + * Model tests for DeprecatedObject + */ + @Test + public void testDeprecatedObject() { + // TODO: test DeprecatedObject + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/DogAllOfTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/DogAllOfTest.java new file mode 100644 index 0000000000..2759c9a2eb --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/DogAllOfTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for DogAllOf + */ +public class DogAllOfTest { + private final DogAllOf model = new DogAllOf(); + + /** + * Model tests for DogAllOf + */ + @Test + public void testDogAllOf() { + // TODO: test DogAllOf + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/DogTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/DogTest.java new file mode 100644 index 0000000000..70765267f0 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/DogTest.java @@ -0,0 +1,60 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.openapitools.server.model.Animal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Dog + */ +public class DogTest { + private final Dog model = new Dog(); + + /** + * Model tests for Dog + */ + @Test + public void testDog() { + // TODO: test Dog + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/EnumArraysTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/EnumArraysTest.java new file mode 100644 index 0000000000..42b3832090 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/EnumArraysTest.java @@ -0,0 +1,52 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumArrays + */ +public class EnumArraysTest { + private final EnumArrays model = new EnumArrays(); + + /** + * Model tests for EnumArrays + */ + @Test + public void testEnumArrays() { + // TODO: test EnumArrays + } + + /** + * Test the property 'justSymbol' + */ + @Test + public void justSymbolTest() { + // TODO: test justSymbol + } + + /** + * Test the property 'arrayEnum' + */ + @Test + public void arrayEnumTest() { + // TODO: test arrayEnum + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/EnumClassTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/EnumClassTest.java new file mode 100644 index 0000000000..9c02e17dac --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/EnumClassTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumClass + */ +public class EnumClassTest { + /** + * Model tests for EnumClass + */ + @Test + public void testEnumClass() { + // TODO: test EnumClass + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/EnumTestTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/EnumTestTest.java new file mode 100644 index 0000000000..7c95fed8bb --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/EnumTestTest.java @@ -0,0 +1,104 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import org.openapitools.server.model.OuterEnum; +import org.openapitools.server.model.OuterEnumDefaultValue; +import org.openapitools.server.model.OuterEnumInteger; +import org.openapitools.server.model.OuterEnumIntegerDefaultValue; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for EnumTest + */ +public class EnumTestTest { + private final EnumTest model = new EnumTest(); + + /** + * Model tests for EnumTest + */ + @Test + public void testEnumTest() { + // TODO: test EnumTest + } + + /** + * Test the property 'enumString' + */ + @Test + public void enumStringTest() { + // TODO: test enumString + } + + /** + * Test the property 'enumStringRequired' + */ + @Test + public void enumStringRequiredTest() { + // TODO: test enumStringRequired + } + + /** + * Test the property 'enumInteger' + */ + @Test + public void enumIntegerTest() { + // TODO: test enumInteger + } + + /** + * Test the property 'enumNumber' + */ + @Test + public void enumNumberTest() { + // TODO: test enumNumber + } + + /** + * Test the property 'outerEnum' + */ + @Test + public void outerEnumTest() { + // TODO: test outerEnum + } + + /** + * Test the property 'outerEnumInteger' + */ + @Test + public void outerEnumIntegerTest() { + // TODO: test outerEnumInteger + } + + /** + * Test the property 'outerEnumDefaultValue' + */ + @Test + public void outerEnumDefaultValueTest() { + // TODO: test outerEnumDefaultValue + } + + /** + * Test the property 'outerEnumIntegerDefaultValue' + */ + @Test + public void outerEnumIntegerDefaultValueTest() { + // TODO: test outerEnumIntegerDefaultValue + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FileSchemaTestClassTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FileSchemaTestClassTest.java new file mode 100644 index 0000000000..fbabc01db3 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FileSchemaTestClassTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.ModelFile; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FileSchemaTestClass + */ +public class FileSchemaTestClassTest { + private final FileSchemaTestClass model = new FileSchemaTestClass(); + + /** + * Model tests for FileSchemaTestClass + */ + @Test + public void testFileSchemaTestClass() { + // TODO: test FileSchemaTestClass + } + + /** + * Test the property '_file' + */ + @Test + public void _fileTest() { + // TODO: test _file + } + + /** + * Test the property 'files' + */ + @Test + public void filesTest() { + // TODO: test files + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FooGetDefaultResponseTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FooGetDefaultResponseTest.java new file mode 100644 index 0000000000..d0dc33cef5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FooGetDefaultResponseTest.java @@ -0,0 +1,42 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.openapitools.server.model.Foo; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FooGetDefaultResponse + */ +public class FooGetDefaultResponseTest { + private final FooGetDefaultResponse model = new FooGetDefaultResponse(); + + /** + * Model tests for FooGetDefaultResponse + */ + @Test + public void testFooGetDefaultResponse() { + // TODO: test FooGetDefaultResponse + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FooTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FooTest.java new file mode 100644 index 0000000000..39abe05aad --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FooTest.java @@ -0,0 +1,40 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Foo + */ +public class FooTest { + private final Foo model = new Foo(); + + /** + * Model tests for Foo + */ + @Test + public void testFoo() { + // TODO: test Foo + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FormatTestTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FormatTestTest.java new file mode 100644 index 0000000000..5d98845296 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/FormatTestTest.java @@ -0,0 +1,166 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import java.io.File; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for FormatTest + */ +public class FormatTestTest { + private final FormatTest model = new FormatTest(); + + /** + * Model tests for FormatTest + */ + @Test + public void testFormatTest() { + // TODO: test FormatTest + } + + /** + * Test the property 'integer' + */ + @Test + public void integerTest() { + // TODO: test integer + } + + /** + * Test the property 'int32' + */ + @Test + public void int32Test() { + // TODO: test int32 + } + + /** + * Test the property 'int64' + */ + @Test + public void int64Test() { + // TODO: test int64 + } + + /** + * Test the property 'number' + */ + @Test + public void numberTest() { + // TODO: test number + } + + /** + * Test the property '_float' + */ + @Test + public void _floatTest() { + // TODO: test _float + } + + /** + * Test the property '_double' + */ + @Test + public void _doubleTest() { + // TODO: test _double + } + + /** + * Test the property 'decimal' + */ + @Test + public void decimalTest() { + // TODO: test decimal + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + + /** + * Test the property '_byte' + */ + @Test + public void _byteTest() { + // TODO: test _byte + } + + /** + * Test the property 'binary' + */ + @Test + public void binaryTest() { + // TODO: test binary + } + + /** + * Test the property 'date' + */ + @Test + public void dateTest() { + // TODO: test date + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'patternWithDigits' + */ + @Test + public void patternWithDigitsTest() { + // TODO: test patternWithDigits + } + + /** + * Test the property 'patternWithDigitsAndDelimiter' + */ + @Test + public void patternWithDigitsAndDelimiterTest() { + // TODO: test patternWithDigitsAndDelimiter + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/HasOnlyReadOnlyTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/HasOnlyReadOnlyTest.java new file mode 100644 index 0000000000..5a56ddcc24 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/HasOnlyReadOnlyTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for HasOnlyReadOnly + */ +public class HasOnlyReadOnlyTest { + private final HasOnlyReadOnly model = new HasOnlyReadOnly(); + + /** + * Model tests for HasOnlyReadOnly + */ + @Test + public void testHasOnlyReadOnly() { + // TODO: test HasOnlyReadOnly + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'foo' + */ + @Test + public void fooTest() { + // TODO: test foo + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/HealthCheckResultTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/HealthCheckResultTest.java new file mode 100644 index 0000000000..be4be735e5 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/HealthCheckResultTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for HealthCheckResult + */ +public class HealthCheckResultTest { + private final HealthCheckResult model = new HealthCheckResult(); + + /** + * Model tests for HealthCheckResult + */ + @Test + public void testHealthCheckResult() { + // TODO: test HealthCheckResult + } + + /** + * Test the property 'nullableMessage' + */ + @Test + public void nullableMessageTest() { + // TODO: test nullableMessage + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/MapTestTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/MapTestTest.java new file mode 100644 index 0000000000..3c6c9450be --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/MapTestTest.java @@ -0,0 +1,68 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for MapTest + */ +public class MapTestTest { + private final MapTest model = new MapTest(); + + /** + * Model tests for MapTest + */ + @Test + public void testMapTest() { + // TODO: test MapTest + } + + /** + * Test the property 'mapMapOfString' + */ + @Test + public void mapMapOfStringTest() { + // TODO: test mapMapOfString + } + + /** + * Test the property 'mapOfEnumString' + */ + @Test + public void mapOfEnumStringTest() { + // TODO: test mapOfEnumString + } + + /** + * Test the property 'directMap' + */ + @Test + public void directMapTest() { + // TODO: test directMap + } + + /** + * Test the property 'indirectMap' + */ + @Test + public void indirectMapTest() { + // TODO: test indirectMap + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClassTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClassTest.java new file mode 100644 index 0000000000..9b15f918a9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClassTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.openapitools.server.model.Animal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ +public class MixedPropertiesAndAdditionalPropertiesClassTest { + private final MixedPropertiesAndAdditionalPropertiesClass model = new MixedPropertiesAndAdditionalPropertiesClass(); + + /** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ + @Test + public void testMixedPropertiesAndAdditionalPropertiesClass() { + // TODO: test MixedPropertiesAndAdditionalPropertiesClass + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'map' + */ + @Test + public void mapTest() { + // TODO: test map + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/Model200ResponseTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/Model200ResponseTest.java new file mode 100644 index 0000000000..33b6d47572 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/Model200ResponseTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Model200Response + */ +public class Model200ResponseTest { + private final Model200Response model = new Model200Response(); + + /** + * Model tests for Model200Response + */ + @Test + public void testModel200Response() { + // TODO: test Model200Response + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelApiResponseTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelApiResponseTest.java new file mode 100644 index 0000000000..43cb48513c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelApiResponseTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelFileTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelFileTest.java new file mode 100644 index 0000000000..ff03280b7e --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelFileTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelFile + */ +public class ModelFileTest { + private final ModelFile model = new ModelFile(); + + /** + * Model tests for ModelFile + */ + @Test + public void testModelFile() { + // TODO: test ModelFile + } + + /** + * Test the property 'sourceURI' + */ + @Test + public void sourceURITest() { + // TODO: test sourceURI + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelListTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelListTest.java new file mode 100644 index 0000000000..7f228b1913 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelListTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelList + */ +public class ModelListTest { + private final ModelList model = new ModelList(); + + /** + * Model tests for ModelList + */ + @Test + public void testModelList() { + // TODO: test ModelList + } + + /** + * Test the property '_123list' + */ + @Test + public void _123listTest() { + // TODO: test _123list + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelReturnTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelReturnTest.java new file mode 100644 index 0000000000..e6af66eb00 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ModelReturnTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ModelReturn + */ +public class ModelReturnTest { + private final ModelReturn model = new ModelReturn(); + + /** + * Model tests for ModelReturn + */ + @Test + public void testModelReturn() { + // TODO: test ModelReturn + } + + /** + * Test the property '_return' + */ + @Test + public void _returnTest() { + // TODO: test _return + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/NameTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/NameTest.java new file mode 100644 index 0000000000..13114ab4e7 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/NameTest.java @@ -0,0 +1,64 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Name + */ +public class NameTest { + private final Name model = new Name(); + + /** + * Model tests for Name + */ + @Test + public void testName() { + // TODO: test Name + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'snakeCase' + */ + @Test + public void snakeCaseTest() { + // TODO: test snakeCase + } + + /** + * Test the property 'property' + */ + @Test + public void propertyTest() { + // TODO: test property + } + + /** + * Test the property '_123number' + */ + @Test + public void _123numberTest() { + // TODO: test _123number + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/NullableClassTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/NullableClassTest.java new file mode 100644 index 0000000000..e2f2dd91bf --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/NullableClassTest.java @@ -0,0 +1,136 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for NullableClass + */ +public class NullableClassTest { + private final NullableClass model = new NullableClass(); + + /** + * Model tests for NullableClass + */ + @Test + public void testNullableClass() { + // TODO: test NullableClass + } + + /** + * Test the property 'integerProp' + */ + @Test + public void integerPropTest() { + // TODO: test integerProp + } + + /** + * Test the property 'numberProp' + */ + @Test + public void numberPropTest() { + // TODO: test numberProp + } + + /** + * Test the property 'booleanProp' + */ + @Test + public void booleanPropTest() { + // TODO: test booleanProp + } + + /** + * Test the property 'stringProp' + */ + @Test + public void stringPropTest() { + // TODO: test stringProp + } + + /** + * Test the property 'dateProp' + */ + @Test + public void datePropTest() { + // TODO: test dateProp + } + + /** + * Test the property 'datetimeProp' + */ + @Test + public void datetimePropTest() { + // TODO: test datetimeProp + } + + /** + * Test the property 'arrayNullableProp' + */ + @Test + public void arrayNullablePropTest() { + // TODO: test arrayNullableProp + } + + /** + * Test the property 'arrayAndItemsNullableProp' + */ + @Test + public void arrayAndItemsNullablePropTest() { + // TODO: test arrayAndItemsNullableProp + } + + /** + * Test the property 'arrayItemsNullable' + */ + @Test + public void arrayItemsNullableTest() { + // TODO: test arrayItemsNullable + } + + /** + * Test the property 'objectNullableProp' + */ + @Test + public void objectNullablePropTest() { + // TODO: test objectNullableProp + } + + /** + * Test the property 'objectAndItemsNullableProp' + */ + @Test + public void objectAndItemsNullablePropTest() { + // TODO: test objectAndItemsNullableProp + } + + /** + * Test the property 'objectItemsNullable' + */ + @Test + public void objectItemsNullableTest() { + // TODO: test objectItemsNullable + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/NumberOnlyTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/NumberOnlyTest.java new file mode 100644 index 0000000000..dede232a8f --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/NumberOnlyTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for NumberOnly + */ +public class NumberOnlyTest { + private final NumberOnly model = new NumberOnly(); + + /** + * Model tests for NumberOnly + */ + @Test + public void testNumberOnly() { + // TODO: test NumberOnly + } + + /** + * Test the property 'justNumber' + */ + @Test + public void justNumberTest() { + // TODO: test justNumber + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ObjectWithDeprecatedFieldsTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ObjectWithDeprecatedFieldsTest.java new file mode 100644 index 0000000000..55cf9bedb0 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ObjectWithDeprecatedFieldsTest.java @@ -0,0 +1,68 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.server.model.DeprecatedObject; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ObjectWithDeprecatedFields + */ +public class ObjectWithDeprecatedFieldsTest { + private final ObjectWithDeprecatedFields model = new ObjectWithDeprecatedFields(); + + /** + * Model tests for ObjectWithDeprecatedFields + */ + @Test + public void testObjectWithDeprecatedFields() { + // TODO: test ObjectWithDeprecatedFields + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'deprecatedRef' + */ + @Test + public void deprecatedRefTest() { + // TODO: test deprecatedRef + } + + /** + * Test the property 'bars' + */ + @Test + public void barsTest() { + // TODO: test bars + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OrderTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OrderTest.java new file mode 100644 index 0000000000..9060765552 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OrderTest.java @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterCompositeTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterCompositeTest.java new file mode 100644 index 0000000000..f61dfbaf41 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterCompositeTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterComposite + */ +public class OuterCompositeTest { + private final OuterComposite model = new OuterComposite(); + + /** + * Model tests for OuterComposite + */ + @Test + public void testOuterComposite() { + // TODO: test OuterComposite + } + + /** + * Test the property 'myNumber' + */ + @Test + public void myNumberTest() { + // TODO: test myNumber + } + + /** + * Test the property 'myString' + */ + @Test + public void myStringTest() { + // TODO: test myString + } + + /** + * Test the property 'myBoolean' + */ + @Test + public void myBooleanTest() { + // TODO: test myBoolean + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumDefaultValueTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumDefaultValueTest.java new file mode 100644 index 0000000000..55d00b4918 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumDefaultValueTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumDefaultValue + */ +public class OuterEnumDefaultValueTest { + /** + * Model tests for OuterEnumDefaultValue + */ + @Test + public void testOuterEnumDefaultValue() { + // TODO: test OuterEnumDefaultValue + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumIntegerDefaultValueTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumIntegerDefaultValueTest.java new file mode 100644 index 0000000000..6a5e46c612 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumIntegerDefaultValueTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumIntegerDefaultValue + */ +public class OuterEnumIntegerDefaultValueTest { + /** + * Model tests for OuterEnumIntegerDefaultValue + */ + @Test + public void testOuterEnumIntegerDefaultValue() { + // TODO: test OuterEnumIntegerDefaultValue + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumIntegerTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumIntegerTest.java new file mode 100644 index 0000000000..d6c32e321d --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumIntegerTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnumInteger + */ +public class OuterEnumIntegerTest { + /** + * Model tests for OuterEnumInteger + */ + @Test + public void testOuterEnumInteger() { + // TODO: test OuterEnumInteger + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumTest.java new file mode 100644 index 0000000000..5ea29d2138 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterEnumTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterEnum + */ +public class OuterEnumTest { + /** + * Model tests for OuterEnum + */ + @Test + public void testOuterEnum() { + // TODO: test OuterEnum + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterObjectWithEnumPropertyTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterObjectWithEnumPropertyTest.java new file mode 100644 index 0000000000..d40c868a41 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/OuterObjectWithEnumPropertyTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.openapitools.server.model.OuterEnumInteger; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for OuterObjectWithEnumProperty + */ +public class OuterObjectWithEnumPropertyTest { + private final OuterObjectWithEnumProperty model = new OuterObjectWithEnumProperty(); + + /** + * Model tests for OuterObjectWithEnumProperty + */ + @Test + public void testOuterObjectWithEnumProperty() { + // TODO: test OuterObjectWithEnumProperty + } + + /** + * Test the property 'value' + */ + @Test + public void valueTest() { + // TODO: test value + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/PetTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/PetTest.java new file mode 100644 index 0000000000..bc913dd50a --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/PetTest.java @@ -0,0 +1,89 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.openapitools.server.model.Category; +import org.openapitools.server.model.Tag; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ReadOnlyFirstTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ReadOnlyFirstTest.java new file mode 100644 index 0000000000..2fe4c7fc6b --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/ReadOnlyFirstTest.java @@ -0,0 +1,48 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for ReadOnlyFirst + */ +public class ReadOnlyFirstTest { + private final ReadOnlyFirst model = new ReadOnlyFirst(); + + /** + * Model tests for ReadOnlyFirst + */ + @Test + public void testReadOnlyFirst() { + // TODO: test ReadOnlyFirst + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'baz' + */ + @Test + public void bazTest() { + // TODO: test baz + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/SingleRefTypeTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/SingleRefTypeTest.java new file mode 100644 index 0000000000..4ae2c23f4c --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/SingleRefTypeTest.java @@ -0,0 +1,30 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for SingleRefType + */ +public class SingleRefTypeTest { + /** + * Model tests for SingleRefType + */ + @Test + public void testSingleRefType() { + // TODO: test SingleRefType + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/SpecialModelNameTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/SpecialModelNameTest.java new file mode 100644 index 0000000000..809e043f8e --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/SpecialModelNameTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for SpecialModelName + */ +public class SpecialModelNameTest { + private final SpecialModelName model = new SpecialModelName(); + + /** + * Model tests for SpecialModelName + */ + @Test + public void testSpecialModelName() { + // TODO: test SpecialModelName + } + + /** + * Test the property '$specialPropertyName' + */ + @Test + public void $specialPropertyNameTest() { + // TODO: test $specialPropertyName + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/TagTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/TagTest.java new file mode 100644 index 0000000000..4d0d708bf9 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/TagTest.java @@ -0,0 +1,48 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/UserTest.java b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/UserTest.java new file mode 100644 index 0000000000..ba936a2080 --- /dev/null +++ b/samples/server/petstore/java-helidon-server/se/src/test/java/org/openapitools/server/model/UserTest.java @@ -0,0 +1,96 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.server.model; + +import org.junit.jupiter.api.Test; + + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + +} diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/public/openapi.json b/samples/server/petstore/java-play-framework-fake-endpoints/public/openapi.json index f1f6720be9..3178371fbb 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/public/openapi.json +++ b/samples/server/petstore/java-play-framework-fake-endpoints/public/openapi.json @@ -2850,7 +2850,8 @@ "type" : "string" } }, - "type" : "object" + "type" : "object", + "example" : null }, "Cat_allOf" : { "properties" : { @@ -2858,7 +2859,8 @@ "type" : "boolean" } }, - "type" : "object" + "type" : "object", + "example" : null }, "BigCat_allOf" : { "properties" : { @@ -2867,7 +2869,8 @@ "type" : "string" } }, - "type" : "object" + "type" : "object", + "example" : null } }, "securitySchemes" : { diff --git a/samples/server/petstore/java-undertow/dependency-reduced-pom.xml b/samples/server/petstore/java-undertow/dependency-reduced-pom.xml index bbb666bc1d..014e6924e5 100644 --- a/samples/server/petstore/java-undertow/dependency-reduced-pom.xml +++ b/samples/server/petstore/java-undertow/dependency-reduced-pom.xml @@ -135,7 +135,7 @@ 0.1.1 2.10.5 4.1.2 - 2.1.6.Final + 2.2.19.Final 1.7.21 2.10.5.1 UTF-8 @@ -143,3 +143,4 @@ 1.10 + diff --git a/samples/server/petstore/java-undertow/pom.xml b/samples/server/petstore/java-undertow/pom.xml index 211e5ae3c3..600c7f0be9 100644 --- a/samples/server/petstore/java-undertow/pom.xml +++ b/samples/server/petstore/java-undertow/pom.xml @@ -16,8 +16,8 @@ 1.8 UTF-8 0.1.1 - 2.10.5 - 2.10.5.1 + 2.12.7 + 2.12.7 1.7.21 0.5.2 4.5.3 @@ -29,7 +29,7 @@ 1.2.0 4.13.2 2.1.0-beta.124 - 2.1.6.Final + 2.2.19.Final 2.2.0 4.5.13 4.1.2 diff --git a/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java b/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java index 00ff133c1c..a9083dc97b 100644 --- a/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java +++ b/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java @@ -539,10 +539,10 @@ public interface PathHandlerInterface { *

        Response headers: [CodegenProperty{openApiType='integer', baseName='X-Rate-Limit', complexType='null', getter='getxRateLimit', setter='setxRateLimit', description='calls per hour allowed by the user', dataType='Integer', datatypeWithEnum='Integer', dataFormat='int32', name='xRateLimit', min='null', max='null', defaultValue='null', defaultValueWithParam=' = data.X-Rate-Limit;', baseType='Integer', containerType='null', title='null', unescapedDescription='calls per hour allowed by the user', maxLength=null, minLength=null, pattern='null', example='null', jsonSchema='{ "type" : "integer", "format" : "int32" -}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=true, isModel=false, isContainer=false, isString=false, isNumeric=true, isInteger=true, isShort=true, isLong=false, isUnboundedInteger=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=false, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isAnyType=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XRateLimit', nameInSnakeCase='X_RATE_LIMIT', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false, getHasDiscriminatorWithNonEmptyMapping=false, composedSchemas=null, hasMultipleTypes=false}, CodegenProperty{openApiType='string', baseName='X-Expires-After', complexType='Date', getter='getxExpiresAfter', setter='setxExpiresAfter', description='date in UTC when token expires', dataType='Date', datatypeWithEnum='Date', dataFormat='date-time', name='xExpiresAfter', min='null', max='null', defaultValue='null', defaultValueWithParam=' = data.X-Expires-After;', baseType='Date', containerType='null', title='null', unescapedDescription='date in UTC when token expires', maxLength=null, minLength=null, pattern='null', example='null', jsonSchema='{ +}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=true, isModel=false, isContainer=false, isString=false, isNumeric=true, isInteger=true, isShort=true, isLong=false, isUnboundedInteger=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=false, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isInnerEnum=false, isAnyType=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XRateLimit', nameInSnakeCase='X_RATE_LIMIT', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, uniqueItemsBoolean=null, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false, getHasDiscriminatorWithNonEmptyMapping=false, composedSchemas=null, hasMultipleTypes=false, requiredVarsMap=null, ref=null, schemaIsFromAdditionalProperties=false, isBooleanSchemaTrue=false, isBooleanSchemaFalse=false, format=int32, dependentRequired=null, contains=null}, CodegenProperty{openApiType='string', baseName='X-Expires-After', complexType='Date', getter='getxExpiresAfter', setter='setxExpiresAfter', description='date in UTC when token expires', dataType='Date', datatypeWithEnum='Date', dataFormat='date-time', name='xExpiresAfter', min='null', max='null', defaultValue='null', defaultValueWithParam=' = data.X-Expires-After;', baseType='Date', containerType='null', title='null', unescapedDescription='date in UTC when token expires', maxLength=null, minLength=null, pattern='null', example='null', jsonSchema='{ "type" : "string", "format" : "date-time" -}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=false, isModel=false, isContainer=false, isString=false, isNumeric=false, isInteger=false, isShort=false, isLong=false, isUnboundedInteger=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=true, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isAnyType=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XExpiresAfter', nameInSnakeCase='X_EXPIRES_AFTER', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false, getHasDiscriminatorWithNonEmptyMapping=false, composedSchemas=null, hasMultipleTypes=false}]

        +}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=false, isModel=false, isContainer=false, isString=false, isNumeric=false, isInteger=false, isShort=false, isLong=false, isUnboundedInteger=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=true, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isInnerEnum=false, isAnyType=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XExpiresAfter', nameInSnakeCase='X_EXPIRES_AFTER', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, uniqueItemsBoolean=null, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false, getHasDiscriminatorWithNonEmptyMapping=false, composedSchemas=null, hasMultipleTypes=false, requiredVarsMap=null, ref=null, schemaIsFromAdditionalProperties=false, isBooleanSchemaTrue=false, isBooleanSchemaFalse=false, format=date-time, dependentRequired=null, contains=null}]

        * *

        Produces: [{mediaType=application/xml}, {mediaType=application/json}]

        *

        Returns: {@link String}

        diff --git a/samples/server/petstore/java-vertx-web/pom.xml b/samples/server/petstore/java-vertx-web/pom.xml index 10e3649bd8..0c475e0789 100644 --- a/samples/server/petstore/java-vertx-web/pom.xml +++ b/samples/server/petstore/java-vertx-web/pom.xml @@ -20,7 +20,7 @@ 4.2.4 5.7.0 1.7.30 - 2.11.2 + 2.12.7 org.openapitools.vertxweb.server.HttpServerVerticle diff --git a/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/FILES b/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/FILES index 912cd6039b..a5460bdf42 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/FILES +++ b/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/FILES @@ -4,6 +4,7 @@ src/gen/java/org/openapitools/api/AnotherFakeApi.java src/gen/java/org/openapitools/api/FakeApi.java src/gen/java/org/openapitools/api/FakeClassnameTestApi.java src/gen/java/org/openapitools/api/PetApi.java +src/gen/java/org/openapitools/api/RestResourceRoot.java src/gen/java/org/openapitools/api/StoreApi.java src/gen/java/org/openapitools/api/UserApi.java src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java diff --git a/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/VERSION index 5f68295fc1..66672d4e9d 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/VERSION @@ -1 +1 @@ -6.0.0-SNAPSHOT \ No newline at end of file +6.1.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec-interface-response/pom.xml b/samples/server/petstore/jaxrs-spec-interface-response/pom.xml index 9bac70f909..861b090b32 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/pom.xml +++ b/samples/server/petstore/jaxrs-spec-interface-response/pom.xml @@ -93,6 +93,7 @@ 1.8 ${java.version} ${java.version} + UTF-8 2.9.9 4.13.2 2.10.13 diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/AnotherFakeApi.java index 0d7fa5cb4d..6107529c09 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/AnotherFakeApi.java @@ -15,7 +15,8 @@ import javax.validation.Valid; @Path("/another-fake/dummy") @Api(description = "the another-fake API") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public interface AnotherFakeApi { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public interface AnotherFakeApi { @PATCH @Consumes({ "application/json" }) diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeApi.java index 6647d22250..ca6bdded41 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeApi.java @@ -25,7 +25,8 @@ import javax.validation.Valid; @Path("/fake") @Api(description = "the fake API") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public interface FakeApi { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public interface FakeApi { @POST @Path("/create_xml_item") diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTags123Api.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTags123Api.java deleted file mode 100644 index f68a2aede9..0000000000 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTags123Api.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.openapitools.api; - -import org.openapitools.model.Client; - -import javax.ws.rs.*; -import javax.ws.rs.core.Response; - -import io.swagger.annotations.*; - -import java.io.InputStream; -import java.util.Map; -import java.util.List; -import javax.validation.constraints.*; -import javax.validation.Valid; - -@Path("/FakeClassnameTags123") -@Api(description = "the FakeClassnameTags123 API") -public interface FakeClassnameTags123Api { - - @PATCH - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @ApiOperation(value = "To test class name in snake case", notes = "To test class name in snake case", authorizations = { - @Authorization(value = "api_key_query") - }, tags={ "fake_classname_tags 123#$%^" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) - Response testClassname(@Valid Client body); -} diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTestApi.java index 5d1c770b70..e14b0e6205 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTestApi.java @@ -15,7 +15,8 @@ import javax.validation.Valid; @Path("/fake_classname_test") @Api(description = "the fake_classname_test API") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public interface FakeClassnameTestApi { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public interface FakeClassnameTestApi { @PATCH @Consumes({ "application/json" }) diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/PetApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/PetApi.java index 688f409117..5b89589075 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/PetApi.java @@ -18,7 +18,8 @@ import javax.validation.Valid; @Path("/pet") @Api(description = "the pet API") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public interface PetApi { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public interface PetApi { @POST @Consumes({ "application/json", "application/xml" }) diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/RestResourceRoot.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/RestResourceRoot.java new file mode 100644 index 0000000000..96ba6c8d8e --- /dev/null +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/RestResourceRoot.java @@ -0,0 +1,5 @@ +package org.openapitools.api; + +public class RestResourceRoot { + public static final String APPLICATION_PATH = "/v2"; +} diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/StoreApi.java index 06a7a2967e..98797af84d 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/StoreApi.java @@ -16,7 +16,8 @@ import javax.validation.Valid; @Path("/store") @Api(description = "the store API") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public interface StoreApi { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public interface StoreApi { @DELETE @Path("/order/{order_id}") diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/UserApi.java index ed2fcd7dc4..888b96e8cd 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/UserApi.java @@ -17,7 +17,8 @@ import javax.validation.Valid; @Path("/user") @Api(description = "the user API") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public interface UserApi { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public interface UserApi { @POST @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", tags={ "user" }) diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 50c6702c65..749ca0e02c 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -18,8 +18,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesAnyType") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class AdditionalPropertiesAnyType extends HashMap implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class AdditionalPropertiesAnyType extends HashMap implements Serializable { private @Valid String name; /** @@ -30,8 +30,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 3b400ed375..3563c9cdc6 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesArray") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class AdditionalPropertiesArray extends HashMap implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class AdditionalPropertiesArray extends HashMap implements Serializable { private @Valid String name; /** @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index e1dbfa0821..0afb07939f 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -18,8 +18,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesBoolean") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class AdditionalPropertiesBoolean extends HashMap implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class AdditionalPropertiesBoolean extends HashMap implements Serializable { private @Valid String name; /** @@ -30,8 +30,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index d8256b29ea..31b4b91dfb 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -20,16 +20,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesClass") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class AdditionalPropertiesClass implements Serializable { - - private @Valid Map mapString = new HashMap<>(); - private @Valid Map mapNumber = new HashMap<>(); - private @Valid Map mapInteger = new HashMap<>(); - private @Valid Map mapBoolean = new HashMap<>(); - private @Valid Map> mapArrayInteger = new HashMap<>(); - private @Valid Map> mapArrayAnytype = new HashMap<>(); - private @Valid Map> mapMapString = new HashMap<>(); - private @Valid Map> mapMapAnytype = new HashMap<>(); +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class AdditionalPropertiesClass implements Serializable { + private @Valid Map mapString = null; + private @Valid Map mapNumber = null; + private @Valid Map mapInteger = null; + private @Valid Map mapBoolean = null; + private @Valid Map> mapArrayInteger = null; + private @Valid Map> mapArrayAnytype = null; + private @Valid Map> mapMapString = null; + private @Valid Map> mapMapAnytype = null; private @Valid Object anytype1; private @Valid Object anytype2; private @Valid Object anytype3; @@ -42,8 +42,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("map_string") public Map getMapString() { @@ -71,7 +69,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public AdditionalPropertiesClass mapNumber(Map mapNumber) { this.mapNumber = mapNumber; @@ -79,8 +77,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("map_number") public Map getMapNumber() { @@ -108,7 +104,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public AdditionalPropertiesClass mapInteger(Map mapInteger) { this.mapInteger = mapInteger; @@ -116,8 +112,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("map_integer") public Map getMapInteger() { @@ -145,7 +139,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { this.mapBoolean = mapBoolean; @@ -153,8 +147,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("map_boolean") public Map getMapBoolean() { @@ -182,7 +174,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public AdditionalPropertiesClass mapArrayInteger(Map> mapArrayInteger) { this.mapArrayInteger = mapArrayInteger; @@ -190,8 +182,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("map_array_integer") public Map> getMapArrayInteger() { @@ -219,7 +209,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public AdditionalPropertiesClass mapArrayAnytype(Map> mapArrayAnytype) { this.mapArrayAnytype = mapArrayAnytype; @@ -227,8 +217,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("map_array_anytype") public Map> getMapArrayAnytype() { @@ -256,7 +244,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public AdditionalPropertiesClass mapMapString(Map> mapMapString) { this.mapMapString = mapMapString; @@ -264,8 +252,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("map_map_string") public Map> getMapMapString() { @@ -293,7 +279,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public AdditionalPropertiesClass mapMapAnytype(Map> mapMapAnytype) { this.mapMapAnytype = mapMapAnytype; @@ -301,8 +287,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("map_map_anytype") public Map> getMapMapAnytype() { @@ -330,7 +314,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public AdditionalPropertiesClass anytype1(Object anytype1) { this.anytype1 = anytype1; @@ -338,8 +322,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("anytype_1") public Object getAnytype1() { @@ -351,7 +333,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.anytype1 = anytype1; } -/** + /** **/ public AdditionalPropertiesClass anytype2(Object anytype2) { this.anytype2 = anytype2; @@ -359,8 +341,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("anytype_2") public Object getAnytype2() { @@ -372,7 +352,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.anytype2 = anytype2; } -/** + /** **/ public AdditionalPropertiesClass anytype3(Object anytype3) { this.anytype3 = anytype3; @@ -380,8 +360,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("anytype_3") public Object getAnytype3() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index fc85a62ad0..376aa5a7c6 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -18,8 +18,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesInteger") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class AdditionalPropertiesInteger extends HashMap implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class AdditionalPropertiesInteger extends HashMap implements Serializable { private @Valid String name; /** @@ -30,8 +30,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index 2585254710..03cf9a126d 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesNumber") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class AdditionalPropertiesNumber extends HashMap implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class AdditionalPropertiesNumber extends HashMap implements Serializable { private @Valid String name; /** @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index 998b85d511..b9fae3edf8 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -18,8 +18,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesObject") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class AdditionalPropertiesObject extends HashMap implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class AdditionalPropertiesObject extends HashMap implements Serializable { private @Valid String name; /** @@ -30,8 +30,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index b317c03b4c..9790203702 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -18,8 +18,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesString") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class AdditionalPropertiesString extends HashMap implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class AdditionalPropertiesString extends HashMap implements Serializable { private @Valid String name; /** @@ -30,8 +30,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Animal.java index f91fa58723..3548453f12 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Animal.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; @@ -24,8 +25,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Animal") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Animal implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Animal implements Serializable { private @Valid String className; private @Valid String color = "red"; @@ -36,9 +37,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } - - - + @ApiModelProperty(required = true, value = "") @JsonProperty("className") @NotNull @@ -51,15 +50,13 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.className = className; } -/** + /** **/ public Animal color(String color) { this.color = color; return this; } - - @ApiModelProperty(value = "") @JsonProperty("color") @@ -95,7 +92,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Animal {\n"); - + sb.append(" className: ").append(toIndentedString(className)).append("\n"); sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AnimalFarm.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AnimalFarm.java deleted file mode 100644 index 810e56085b..0000000000 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AnimalFarm.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.openapitools.model; - -import java.util.ArrayList; -import java.util.List; -import org.openapitools.model.Animal; -import java.io.Serializable; -import javax.validation.constraints.*; -import javax.validation.Valid; - -import io.swagger.annotations.*; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - - - -public class AnimalFarm extends ArrayList implements Serializable { - - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AnimalFarm animalFarm = (AnimalFarm) o; - return true; - } - - @Override - public int hashCode() { - return Objects.hash(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AnimalFarm {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 6e2646e4da..0385c5e829 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -19,9 +19,9 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ArrayOfArrayOfNumberOnly") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class ArrayOfArrayOfNumberOnly implements Serializable { - - private @Valid List> arrayArrayNumber = new ArrayList<>(); +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class ArrayOfArrayOfNumberOnly implements Serializable { + private @Valid List> arrayArrayNumber = null; /** **/ @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("ArrayArrayNumber") public List> getArrayArrayNumber() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index f2ab424107..cbfdb52003 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -19,9 +19,9 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ArrayOfNumberOnly") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class ArrayOfNumberOnly implements Serializable { - - private @Valid List arrayNumber = new ArrayList<>(); +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class ArrayOfNumberOnly implements Serializable { + private @Valid List arrayNumber = null; /** **/ @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("ArrayNumber") public List getArrayNumber() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayTest.java index 6f2fe46e0c..b2043ee09c 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayTest.java @@ -19,11 +19,11 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ArrayTest") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class ArrayTest implements Serializable { - - private @Valid List arrayOfString = new ArrayList<>(); - private @Valid List> arrayArrayOfInteger = new ArrayList<>(); - private @Valid List> arrayArrayOfModel = new ArrayList<>(); +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class ArrayTest implements Serializable { + private @Valid List arrayOfString = null; + private @Valid List> arrayArrayOfInteger = null; + private @Valid List> arrayArrayOfModel = null; /** **/ @@ -33,8 +33,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("array_of_string") public List getArrayOfString() { @@ -62,7 +60,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; @@ -70,8 +68,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("array_array_of_integer") public List> getArrayArrayOfInteger() { @@ -99,7 +95,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; @@ -107,8 +103,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") public List> getArrayArrayOfModel() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCat.java index 483c60b3d0..fb8229016d 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCat.java @@ -2,7 +2,6 @@ package org.openapitools.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.openapitools.model.BigCatAllOf; import org.openapitools.model.Cat; import java.io.Serializable; import javax.validation.constraints.*; @@ -18,10 +17,9 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("BigCat") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class BigCat extends Cat implements Serializable { - - -public enum KindEnum { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class BigCat extends Cat implements Serializable { + public enum KindEnum { LIONS(String.valueOf("lions")), TIGERS(String.valueOf("tigers")), LEOPARDS(String.valueOf("leopards")), JAGUARS(String.valueOf("jaguars")); @@ -42,6 +40,21 @@ public enum KindEnum { return String.valueOf(value); } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static KindEnum fromString(String s) { + for (KindEnum b : KindEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static KindEnum fromValue(String value) { for (KindEnum b : KindEnum.values()) { @@ -63,8 +76,6 @@ public enum KindEnum { } - - @ApiModelProperty(value = "") @JsonProperty("kind") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCatAllOf.java index 7ba1d7c23f..21427933a9 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -17,10 +17,9 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("BigCat_allOf") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class BigCatAllOf implements Serializable { - - -public enum KindEnum { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class BigCatAllOf implements Serializable { + public enum KindEnum { LIONS(String.valueOf("lions")), TIGERS(String.valueOf("tigers")), LEOPARDS(String.valueOf("leopards")), JAGUARS(String.valueOf("jaguars")); @@ -41,6 +40,21 @@ public enum KindEnum { return String.valueOf(value); } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static KindEnum fromString(String s) { + for (KindEnum b : KindEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static KindEnum fromValue(String value) { for (KindEnum b : KindEnum.values()) { @@ -62,8 +76,6 @@ public enum KindEnum { } - - @ApiModelProperty(value = "") @JsonProperty("kind") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Capitalization.java index 5952965597..862e34ac29 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Capitalization.java @@ -16,8 +16,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Capitalization") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Capitalization implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Capitalization implements Serializable { private @Valid String smallCamel; private @Valid String capitalCamel; private @Valid String smallSnake; @@ -33,8 +33,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("smallCamel") public String getSmallCamel() { @@ -46,7 +44,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.smallCamel = smallCamel; } -/** + /** **/ public Capitalization capitalCamel(String capitalCamel) { this.capitalCamel = capitalCamel; @@ -54,8 +52,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("CapitalCamel") public String getCapitalCamel() { @@ -67,7 +63,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.capitalCamel = capitalCamel; } -/** + /** **/ public Capitalization smallSnake(String smallSnake) { this.smallSnake = smallSnake; @@ -75,8 +71,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("small_Snake") public String getSmallSnake() { @@ -88,7 +82,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.smallSnake = smallSnake; } -/** + /** **/ public Capitalization capitalSnake(String capitalSnake) { this.capitalSnake = capitalSnake; @@ -96,8 +90,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("Capital_Snake") public String getCapitalSnake() { @@ -109,7 +101,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.capitalSnake = capitalSnake; } -/** + /** **/ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { this.scAETHFlowPoints = scAETHFlowPoints; @@ -117,8 +109,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("SCA_ETH_Flow_Points") public String getScAETHFlowPoints() { @@ -130,7 +120,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.scAETHFlowPoints = scAETHFlowPoints; } -/** + /** * Name of the pet **/ public Capitalization ATT_NAME(String ATT_NAME) { @@ -139,8 +129,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "Name of the pet ") @JsonProperty("ATT_NAME") public String getATTNAME() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Cat.java index 948b28d037..7fa39e3522 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Cat.java @@ -3,7 +3,6 @@ package org.openapitools.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.openapitools.model.Animal; -import org.openapitools.model.CatAllOf; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; @@ -18,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Cat") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Cat extends Animal implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Cat extends Animal implements Serializable { private @Valid Boolean declawed; /** @@ -30,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("declawed") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/CatAllOf.java index 2ed18a6de6..491b09cbba 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/CatAllOf.java @@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Cat_allOf") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class CatAllOf implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class CatAllOf implements Serializable { private @Valid Boolean declawed; /** @@ -29,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("declawed") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Category.java index 6d4e8a8799..3ae4d3b4b4 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Category.java @@ -16,8 +16,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Category") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Category implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Category implements Serializable { private @Valid Long id; private @Valid String name = "default-name"; @@ -29,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("id") public Long getId() { @@ -42,7 +40,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.id = id; } -/** + /** **/ public Category name(String name) { this.name = name; @@ -50,8 +48,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("name") @NotNull diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ClassModel.java index fec3c61925..ee9e240aac 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ClassModel.java @@ -18,8 +18,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; **/ @ApiModel(description = "Model for testing model with \"_class\" property") @JsonTypeName("ClassModel") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class ClassModel implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class ClassModel implements Serializable { private @Valid String propertyClass; /** @@ -30,8 +30,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("_class") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Client.java index 74d489b5ac..c3efb2cbd6 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Client.java @@ -16,8 +16,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Client") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Client implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Client implements Serializable { private @Valid String client; /** @@ -28,8 +28,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("client") public String getClient() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Dog.java index 20599ecebc..2e8e10e641 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Dog.java @@ -3,7 +3,6 @@ package org.openapitools.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.openapitools.model.Animal; -import org.openapitools.model.DogAllOf; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; @@ -18,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Dog") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Dog extends Animal implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Dog extends Animal implements Serializable { private @Valid String breed; /** @@ -30,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("breed") public String getBreed() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/DogAllOf.java index 6c7208fe19..a2e595a8a1 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/DogAllOf.java @@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Dog_allOf") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class DogAllOf implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class DogAllOf implements Serializable { private @Valid String breed; /** @@ -29,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("breed") public String getBreed() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumArrays.java index 502d24d9bc..4b2ef0c1c6 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumArrays.java @@ -18,10 +18,9 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("EnumArrays") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class EnumArrays implements Serializable { - - -public enum JustSymbolEnum { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class EnumArrays implements Serializable { + public enum JustSymbolEnum { GREATER_THAN_OR_EQUAL_TO(String.valueOf(">=")), DOLLAR(String.valueOf("$")); @@ -42,6 +41,21 @@ public enum JustSymbolEnum { return String.valueOf(value); } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static JustSymbolEnum fromString(String s) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static JustSymbolEnum fromValue(String value) { for (JustSymbolEnum b : JustSymbolEnum.values()) { @@ -54,8 +68,7 @@ public enum JustSymbolEnum { } private @Valid JustSymbolEnum justSymbol; - -public enum ArrayEnumEnum { + public enum ArrayEnumEnum { FISH(String.valueOf("fish")), CRAB(String.valueOf("crab")); @@ -76,6 +89,21 @@ public enum ArrayEnumEnum { return String.valueOf(value); } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static ArrayEnumEnum fromString(String s) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static ArrayEnumEnum fromValue(String value) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { @@ -87,7 +115,7 @@ public enum ArrayEnumEnum { } } - private @Valid List arrayEnum = new ArrayList<>(); + private @Valid List arrayEnum = null; /** **/ @@ -97,8 +125,6 @@ public enum ArrayEnumEnum { } - - @ApiModelProperty(value = "") @JsonProperty("just_symbol") public JustSymbolEnum getJustSymbol() { @@ -110,7 +136,7 @@ public enum ArrayEnumEnum { this.justSymbol = justSymbol; } -/** + /** **/ public EnumArrays arrayEnum(List arrayEnum) { this.arrayEnum = arrayEnum; @@ -118,8 +144,6 @@ public enum ArrayEnumEnum { } - - @ApiModelProperty(value = "") @JsonProperty("array_enum") public List getArrayEnum() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumClass.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumClass.java index 64c6691771..778c1dfb95 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumClass.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumClass.java @@ -24,6 +24,21 @@ public enum EnumClass { this.value = value; } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumClass fromString(String s) { + for (EnumClass b : EnumClass.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumTest.java index af7ac236ef..b4692c31c4 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumTest.java @@ -18,10 +18,9 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Enum_Test") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class EnumTest implements Serializable { - - -public enum EnumStringEnum { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class EnumTest implements Serializable { + public enum EnumStringEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); @@ -42,6 +41,21 @@ public enum EnumStringEnum { return String.valueOf(value); } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumStringEnum fromString(String s) { + for (EnumStringEnum b : EnumStringEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static EnumStringEnum fromValue(String value) { for (EnumStringEnum b : EnumStringEnum.values()) { @@ -54,8 +68,7 @@ public enum EnumStringEnum { } private @Valid EnumStringEnum enumString; - -public enum EnumStringRequiredEnum { + public enum EnumStringRequiredEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); @@ -76,6 +89,21 @@ public enum EnumStringRequiredEnum { return String.valueOf(value); } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumStringRequiredEnum fromString(String s) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static EnumStringRequiredEnum fromValue(String value) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { @@ -88,8 +116,7 @@ public enum EnumStringRequiredEnum { } private @Valid EnumStringRequiredEnum enumStringRequired; - -public enum EnumIntegerEnum { + public enum EnumIntegerEnum { NUMBER_1(Integer.valueOf(1)), NUMBER_MINUS_1(Integer.valueOf(-1)); @@ -110,6 +137,21 @@ public enum EnumIntegerEnum { return String.valueOf(value); } + /** + * Convert a String into Integer, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumIntegerEnum fromString(String s) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static EnumIntegerEnum fromValue(Integer value) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { @@ -122,8 +164,7 @@ public enum EnumIntegerEnum { } private @Valid EnumIntegerEnum enumInteger; - -public enum EnumNumberEnum { + public enum EnumNumberEnum { NUMBER_1_DOT_1(Double.valueOf(1.1)), NUMBER_MINUS_1_DOT_2(Double.valueOf(-1.2)); @@ -144,6 +185,21 @@ public enum EnumNumberEnum { return String.valueOf(value); } + /** + * Convert a String into Double, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static EnumNumberEnum fromString(String s) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static EnumNumberEnum fromValue(Double value) { for (EnumNumberEnum b : EnumNumberEnum.values()) { @@ -166,8 +222,6 @@ public enum EnumNumberEnum { } - - @ApiModelProperty(value = "") @JsonProperty("enum_string") public EnumStringEnum getEnumString() { @@ -179,7 +233,7 @@ public enum EnumNumberEnum { this.enumString = enumString; } -/** + /** **/ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { this.enumStringRequired = enumStringRequired; @@ -187,8 +241,6 @@ public enum EnumNumberEnum { } - - @ApiModelProperty(required = true, value = "") @JsonProperty("enum_string_required") @NotNull @@ -201,7 +253,7 @@ public enum EnumNumberEnum { this.enumStringRequired = enumStringRequired; } -/** + /** **/ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; @@ -209,8 +261,6 @@ public enum EnumNumberEnum { } - - @ApiModelProperty(value = "") @JsonProperty("enum_integer") public EnumIntegerEnum getEnumInteger() { @@ -222,7 +272,7 @@ public enum EnumNumberEnum { this.enumInteger = enumInteger; } -/** + /** **/ public EnumTest enumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; @@ -230,8 +280,6 @@ public enum EnumNumberEnum { } - - @ApiModelProperty(value = "") @JsonProperty("enum_number") public EnumNumberEnum getEnumNumber() { @@ -243,7 +291,7 @@ public enum EnumNumberEnum { this.enumNumber = enumNumber; } -/** + /** **/ public EnumTest outerEnum(OuterEnum outerEnum) { this.outerEnum = outerEnum; @@ -251,8 +299,6 @@ public enum EnumNumberEnum { } - - @ApiModelProperty(value = "") @JsonProperty("outerEnum") public OuterEnum getOuterEnum() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index f2ee479c5b..8297178d42 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -19,10 +19,10 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("FileSchemaTestClass") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class FileSchemaTestClass implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class FileSchemaTestClass implements Serializable { private @Valid ModelFile _file; - private @Valid List files = new ArrayList<>(); + private @Valid List files = null; /** **/ @@ -32,8 +32,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("file") public ModelFile getFile() { @@ -45,7 +43,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this._file = _file; } -/** + /** **/ public FileSchemaTestClass files(List files) { this.files = files; @@ -53,8 +51,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("files") public List getFiles() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FormatTest.java index c6b8753a4e..8d71c95701 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FormatTest.java @@ -5,6 +5,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.File; import java.math.BigDecimal; +import java.util.Arrays; import java.util.Date; import java.util.UUID; import org.joda.time.LocalDate; @@ -22,8 +23,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("format_test") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class FormatTest implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class FormatTest implements Serializable { private @Valid Integer integer; private @Valid Integer int32; private @Valid Long int64; @@ -49,8 +50,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("integer") @Min(10) @Max(100) public Integer getInteger() { @@ -62,7 +61,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.integer = integer; } -/** + /** * minimum: 20 * maximum: 200 **/ @@ -72,8 +71,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("int32") @Min(20) @Max(200) public Integer getInt32() { @@ -85,7 +82,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.int32 = int32; } -/** + /** **/ public FormatTest int64(Long int64) { this.int64 = int64; @@ -93,8 +90,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("int64") public Long getInt64() { @@ -106,7 +101,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.int64 = int64; } -/** + /** * minimum: 32.1 * maximum: 543.2 **/ @@ -116,8 +111,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("number") @NotNull @@ -130,7 +123,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.number = number; } -/** + /** * minimum: 54.3 * maximum: 987.6 **/ @@ -140,8 +133,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("float") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { @@ -153,7 +144,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this._float = _float; } -/** + /** * minimum: 67.8 * maximum: 123.4 **/ @@ -163,8 +154,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("double") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { @@ -176,7 +165,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this._double = _double; } -/** + /** **/ public FormatTest string(String string) { this.string = string; @@ -184,8 +173,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("string") @Pattern(regexp="/[a-z]/i") public String getString() { @@ -197,7 +184,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.string = string; } -/** + /** **/ public FormatTest _byte(byte[] _byte) { this._byte = _byte; @@ -205,8 +192,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("byte") @NotNull @@ -219,7 +204,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this._byte = _byte; } -/** + /** **/ public FormatTest binary(File binary) { this.binary = binary; @@ -227,8 +212,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("binary") public File getBinary() { @@ -240,7 +223,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.binary = binary; } -/** + /** **/ public FormatTest date(LocalDate date) { this.date = date; @@ -248,8 +231,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("date") @NotNull @@ -262,7 +243,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.date = date; } -/** + /** **/ public FormatTest dateTime(Date dateTime) { this.dateTime = dateTime; @@ -270,8 +251,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("dateTime") public Date getDateTime() { @@ -283,7 +262,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.dateTime = dateTime; } -/** + /** **/ public FormatTest uuid(UUID uuid) { this.uuid = uuid; @@ -291,8 +270,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") @JsonProperty("uuid") public UUID getUuid() { @@ -304,7 +281,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.uuid = uuid; } -/** + /** **/ public FormatTest password(String password) { this.password = password; @@ -312,8 +289,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("password") @NotNull @@ -326,7 +301,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.password = password; } -/** + /** **/ public FormatTest bigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; @@ -334,8 +309,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("BigDecimal") public BigDecimal getBigDecimal() { @@ -364,7 +337,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; Objects.equals(this._float, formatTest._float) && Objects.equals(this._double, formatTest._double) && Objects.equals(this.string, formatTest.string) && - Objects.equals(this._byte, formatTest._byte) && + Arrays.equals(this._byte, formatTest._byte) && Objects.equals(this.binary, formatTest.binary) && Objects.equals(this.date, formatTest.date) && Objects.equals(this.dateTime, formatTest.dateTime) && @@ -375,7 +348,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @Override public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password, bigDecimal); + return Objects.hash(integer, int32, int64, number, _float, _double, string, Arrays.hashCode(_byte), binary, date, dateTime, uuid, password, bigDecimal); } @Override diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 49ca21e5a5..a3ff9057c6 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("hasOnlyReadOnly") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class HasOnlyReadOnly implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class HasOnlyReadOnly implements Serializable { private @Valid String bar; private @Valid String foo; @@ -30,8 +30,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("bar") public String getBar() { @@ -43,7 +41,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.bar = bar; } -/** + /** **/ public HasOnlyReadOnly foo(String foo) { this.foo = foo; @@ -51,8 +49,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("foo") public String getFoo() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MapTest.java index 8d5dece7fb..c45ee600ca 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MapTest.java @@ -3,7 +3,6 @@ package org.openapitools.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.io.Serializable; import javax.validation.constraints.*; @@ -19,11 +18,10 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("MapTest") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class MapTest implements Serializable { - - private @Valid Map> mapMapOfString = new HashMap<>(); - -public enum InnerEnum { +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class MapTest implements Serializable { + private @Valid Map> mapMapOfString = null; + public enum InnerEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")); @@ -44,6 +42,21 @@ public enum InnerEnum { return String.valueOf(value); } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static InnerEnum fromString(String s) { + for (InnerEnum b : InnerEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static InnerEnum fromValue(String value) { for (InnerEnum b : InnerEnum.values()) { @@ -55,9 +68,9 @@ public enum InnerEnum { } } - private @Valid Map mapOfEnumString = new HashMap<>(); - private @Valid Map directMap = new HashMap<>(); - private @Valid Map indirectMap = new HashMap<>(); + private @Valid Map mapOfEnumString = null; + private @Valid Map directMap = null; + private @Valid Map indirectMap = null; /** **/ @@ -67,8 +80,6 @@ public enum InnerEnum { } - - @ApiModelProperty(value = "") @JsonProperty("map_map_of_string") public Map> getMapMapOfString() { @@ -96,7 +107,7 @@ public enum InnerEnum { return this; } -/** + /** **/ public MapTest mapOfEnumString(Map mapOfEnumString) { this.mapOfEnumString = mapOfEnumString; @@ -104,8 +115,6 @@ public enum InnerEnum { } - - @ApiModelProperty(value = "") @JsonProperty("map_of_enum_string") public Map getMapOfEnumString() { @@ -133,7 +142,7 @@ public enum InnerEnum { return this; } -/** + /** **/ public MapTest directMap(Map directMap) { this.directMap = directMap; @@ -141,8 +150,6 @@ public enum InnerEnum { } - - @ApiModelProperty(value = "") @JsonProperty("direct_map") public Map getDirectMap() { @@ -170,7 +177,7 @@ public enum InnerEnum { return this; } -/** + /** **/ public MapTest indirectMap(Map indirectMap) { this.indirectMap = indirectMap; @@ -178,8 +185,6 @@ public enum InnerEnum { } - - @ApiModelProperty(value = "") @JsonProperty("indirect_map") public Map getIndirectMap() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 92d8a9a441..c5e37deb23 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -4,7 +4,6 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.UUID; import org.openapitools.model.Animal; @@ -22,11 +21,11 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("MixedPropertiesAndAdditionalPropertiesClass") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class MixedPropertiesAndAdditionalPropertiesClass implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class MixedPropertiesAndAdditionalPropertiesClass implements Serializable { private @Valid UUID uuid; private @Valid Date dateTime; - private @Valid Map map = new HashMap<>(); + private @Valid Map map = null; /** **/ @@ -36,8 +35,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("uuid") public UUID getUuid() { @@ -49,7 +46,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.uuid = uuid; } -/** + /** **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { this.dateTime = dateTime; @@ -57,8 +54,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("dateTime") public Date getDateTime() { @@ -70,7 +65,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.dateTime = dateTime; } -/** + /** **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; @@ -78,8 +73,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("map") public Map getMap() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Model200Response.java index af86cf00ed..9023f1b364 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Model200Response.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; **/ @ApiModel(description = "Model for testing model name starting with number") @JsonTypeName("200_response") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Model200Response implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Model200Response implements Serializable { private @Valid Integer name; private @Valid String propertyClass; @@ -32,8 +32,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name") public Integer getName() { @@ -45,7 +43,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.name = name; } -/** + /** **/ public Model200Response propertyClass(String propertyClass) { this.propertyClass = propertyClass; @@ -53,8 +51,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("class") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelApiResponse.java index 3bcaaffb3d..58d4e3da8f 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ApiResponse") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class ModelApiResponse implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class ModelApiResponse implements Serializable { private @Valid Integer code; private @Valid String type; private @Valid String message; @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("code") public Integer getCode() { @@ -44,7 +42,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.code = code; } -/** + /** **/ public ModelApiResponse type(String type) { this.type = type; @@ -52,8 +50,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("type") public String getType() { @@ -65,7 +61,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.type = type; } -/** + /** **/ public ModelApiResponse message(String message) { this.message = message; @@ -73,8 +69,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("message") public String getMessage() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelFile.java index 95dfa998db..b68b110209 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelFile.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; **/ @ApiModel(description = "Must be named `File` for test.") @JsonTypeName("File") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class ModelFile implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class ModelFile implements Serializable { private @Valid String sourceURI; /** @@ -32,8 +32,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "Test capitalization") @JsonProperty("sourceURI") public String getSourceURI() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelList.java index ec97de0198..5f5c9d766d 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelList.java @@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("List") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class ModelList implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class ModelList implements Serializable { private @Valid String _123list; /** @@ -29,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("123-list") public String get123list() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelReturn.java index b9055976ff..3af7ec3625 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelReturn.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; **/ @ApiModel(description = "Model for testing reserved words") @JsonTypeName("Return") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class ModelReturn implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class ModelReturn implements Serializable { private @Valid Integer _return; /** @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("return") public Integer getReturn() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Name.java index 54d09365ae..09f3be2cf4 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Name.java @@ -18,8 +18,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; **/ @ApiModel(description = "Model for testing model name same as property name") @JsonTypeName("Name") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Name implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Name implements Serializable { private @Valid Integer name; private @Valid Integer snakeCase; private @Valid String property; @@ -33,8 +33,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("name") @NotNull @@ -47,7 +45,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.name = name; } -/** + /** **/ public Name snakeCase(Integer snakeCase) { this.snakeCase = snakeCase; @@ -55,8 +53,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("snake_case") public Integer getSnakeCase() { @@ -68,7 +64,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.snakeCase = snakeCase; } -/** + /** **/ public Name property(String property) { this.property = property; @@ -76,8 +72,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("property") public String getProperty() { @@ -89,7 +83,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.property = property; } -/** + /** **/ public Name _123number(Integer _123number) { this._123number = _123number; @@ -97,8 +91,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("123Number") public Integer get123number() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/NumberOnly.java index 9ea507266d..d8bba4783f 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/NumberOnly.java @@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("NumberOnly") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class NumberOnly implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class NumberOnly implements Serializable { private @Valid BigDecimal justNumber; /** @@ -29,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("JustNumber") public BigDecimal getJustNumber() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Order.java index e67d3772f9..5a6d37a5d7 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Order.java @@ -17,14 +17,13 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Order") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Order implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Order implements Serializable { private @Valid Long id; private @Valid Long petId; private @Valid Integer quantity; private @Valid Date shipDate; - -public enum StatusEnum { + public enum StatusEnum { PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); @@ -45,6 +44,21 @@ public enum StatusEnum { return String.valueOf(value); } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static StatusEnum fromString(String s) { + for (StatusEnum b : StatusEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { @@ -67,8 +81,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "") @JsonProperty("id") public Long getId() { @@ -80,7 +92,7 @@ public enum StatusEnum { this.id = id; } -/** + /** **/ public Order petId(Long petId) { this.petId = petId; @@ -88,8 +100,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "") @JsonProperty("petId") public Long getPetId() { @@ -101,7 +111,7 @@ public enum StatusEnum { this.petId = petId; } -/** + /** **/ public Order quantity(Integer quantity) { this.quantity = quantity; @@ -109,8 +119,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "") @JsonProperty("quantity") public Integer getQuantity() { @@ -122,7 +130,7 @@ public enum StatusEnum { this.quantity = quantity; } -/** + /** **/ public Order shipDate(Date shipDate) { this.shipDate = shipDate; @@ -130,8 +138,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "") @JsonProperty("shipDate") public Date getShipDate() { @@ -143,7 +149,7 @@ public enum StatusEnum { this.shipDate = shipDate; } -/** + /** * Order Status **/ public Order status(StatusEnum status) { @@ -152,8 +158,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "Order Status") @JsonProperty("status") public StatusEnum getStatus() { @@ -165,7 +169,7 @@ public enum StatusEnum { this.status = status; } -/** + /** **/ public Order complete(Boolean complete) { this.complete = complete; @@ -173,8 +177,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "") @JsonProperty("complete") public Boolean getComplete() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterComposite.java index 95ff03416b..b369e965b6 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterComposite.java @@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("OuterComposite") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class OuterComposite implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class OuterComposite implements Serializable { private @Valid BigDecimal myNumber; private @Valid String myString; private @Valid Boolean myBoolean; @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("my_number") public BigDecimal getMyNumber() { @@ -44,7 +42,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.myNumber = myNumber; } -/** + /** **/ public OuterComposite myString(String myString) { this.myString = myString; @@ -52,8 +50,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("my_string") public String getMyString() { @@ -65,7 +61,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.myString = myString; } -/** + /** **/ public OuterComposite myBoolean(Boolean myBoolean) { this.myBoolean = myBoolean; @@ -73,8 +69,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("my_boolean") public Boolean getMyBoolean() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterEnum.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterEnum.java index fbd86c9bdb..131a96d2ce 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterEnum.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterEnum.java @@ -24,6 +24,21 @@ public enum OuterEnum { this.value = value; } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static OuterEnum fromString(String s) { + for (OuterEnum b : OuterEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Pet.java index 8ec79b936c..509dc7f912 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Pet.java @@ -23,15 +23,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Pet") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Pet implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Pet implements Serializable { private @Valid Long id; private @Valid Category category; private @Valid String name; private @Valid Set photoUrls = new LinkedHashSet<>(); - private @Valid List tags = new ArrayList<>(); - -public enum StatusEnum { + private @Valid List tags = null; + public enum StatusEnum { AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); @@ -52,6 +51,21 @@ public enum StatusEnum { return String.valueOf(value); } + /** + * Convert a String into String, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static StatusEnum fromString(String s) { + for (StatusEnum b : StatusEnum.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected string value '" + s + "'"); + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { @@ -73,8 +87,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "") @JsonProperty("id") public Long getId() { @@ -86,7 +98,7 @@ public enum StatusEnum { this.id = id; } -/** + /** **/ public Pet category(Category category) { this.category = category; @@ -94,8 +106,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "") @JsonProperty("category") public Category getCategory() { @@ -107,7 +117,7 @@ public enum StatusEnum { this.category = category; } -/** + /** **/ public Pet name(String name) { this.name = name; @@ -115,8 +125,6 @@ public enum StatusEnum { } - - @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty("name") @NotNull @@ -129,7 +137,7 @@ public enum StatusEnum { this.name = name; } -/** + /** **/ public Pet photoUrls(Set photoUrls) { this.photoUrls = photoUrls; @@ -137,8 +145,6 @@ public enum StatusEnum { } - - @ApiModelProperty(required = true, value = "") @JsonProperty("photoUrls") @NotNull @@ -168,7 +174,7 @@ public enum StatusEnum { return this; } -/** + /** **/ public Pet tags(List tags) { this.tags = tags; @@ -176,8 +182,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "") @JsonProperty("tags") public List getTags() { @@ -205,7 +209,7 @@ public enum StatusEnum { return this; } -/** + /** * pet status in the store **/ public Pet status(StatusEnum status) { @@ -214,8 +218,6 @@ public enum StatusEnum { } - - @ApiModelProperty(value = "pet status in the store") @JsonProperty("status") public StatusEnum getStatus() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index 71451f9cf6..164caf2e40 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -16,8 +16,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ReadOnlyFirst") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class ReadOnlyFirst implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class ReadOnlyFirst implements Serializable { private @Valid String bar; private @Valid String baz; @@ -29,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("bar") public String getBar() { @@ -42,7 +40,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.bar = bar; } -/** + /** **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; @@ -50,8 +48,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("baz") public String getBaz() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/SpecialModelName.java index 0fc3694ffa..03dbaba2b8 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -17,8 +17,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("$special[model.name]") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class SpecialModelName implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class SpecialModelName implements Serializable { private @Valid Long $specialPropertyName; /** @@ -29,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("$special[property.name]") public Long get$SpecialPropertyName() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/StringBooleanMap.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/StringBooleanMap.java deleted file mode 100644 index e48ad0840a..0000000000 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/StringBooleanMap.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.openapitools.model; - -import java.util.HashMap; -import java.util.Map; -import java.io.Serializable; -import javax.validation.constraints.*; -import javax.validation.Valid; - -import io.swagger.annotations.*; -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - - - -public class StringBooleanMap extends HashMap implements Serializable { - - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - StringBooleanMap stringBooleanMap = (StringBooleanMap) o; - return true; - } - - @Override - public int hashCode() { - return Objects.hash(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class StringBooleanMap {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Tag.java index db7d608abd..56dde36482 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Tag.java @@ -16,8 +16,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Tag") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class Tag implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class Tag implements Serializable { private @Valid Long id; private @Valid String name; @@ -29,8 +29,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("id") public Long getId() { @@ -42,7 +40,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.id = id; } -/** + /** **/ public Tag name(String name) { this.name = name; @@ -50,8 +48,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 98cdf57b7f..5a58d2e4a4 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("TypeHolderDefault") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class TypeHolderDefault implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class TypeHolderDefault implements Serializable { private @Valid String stringItem = "what"; private @Valid BigDecimal numberItem; private @Valid Integer integerItem; @@ -35,8 +35,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("string_item") @NotNull @@ -49,7 +47,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.stringItem = stringItem; } -/** + /** **/ public TypeHolderDefault numberItem(BigDecimal numberItem) { this.numberItem = numberItem; @@ -57,8 +55,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("number_item") @NotNull @@ -71,7 +67,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.numberItem = numberItem; } -/** + /** **/ public TypeHolderDefault integerItem(Integer integerItem) { this.integerItem = integerItem; @@ -79,8 +75,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("integer_item") @NotNull @@ -93,7 +87,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.integerItem = integerItem; } -/** + /** **/ public TypeHolderDefault boolItem(Boolean boolItem) { this.boolItem = boolItem; @@ -101,8 +95,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("bool_item") @NotNull @@ -115,7 +107,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.boolItem = boolItem; } -/** + /** **/ public TypeHolderDefault arrayItem(List arrayItem) { this.arrayItem = arrayItem; @@ -123,8 +115,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(required = true, value = "") @JsonProperty("array_item") @NotNull diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderExample.java index f2fbe66277..1c24650e19 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("TypeHolderExample") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class TypeHolderExample implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class TypeHolderExample implements Serializable { private @Valid String stringItem; private @Valid BigDecimal numberItem; private @Valid Float floatItem; @@ -36,8 +36,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "what", required = true, value = "") @JsonProperty("string_item") @NotNull @@ -50,7 +48,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.stringItem = stringItem; } -/** + /** **/ public TypeHolderExample numberItem(BigDecimal numberItem) { this.numberItem = numberItem; @@ -58,8 +56,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "1.234", required = true, value = "") @JsonProperty("number_item") @NotNull @@ -72,7 +68,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.numberItem = numberItem; } -/** + /** **/ public TypeHolderExample floatItem(Float floatItem) { this.floatItem = floatItem; @@ -80,8 +76,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "1.234", required = true, value = "") @JsonProperty("float_item") @NotNull @@ -94,7 +88,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.floatItem = floatItem; } -/** + /** **/ public TypeHolderExample integerItem(Integer integerItem) { this.integerItem = integerItem; @@ -102,8 +96,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "-2", required = true, value = "") @JsonProperty("integer_item") @NotNull @@ -116,7 +108,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.integerItem = integerItem; } -/** + /** **/ public TypeHolderExample boolItem(Boolean boolItem) { this.boolItem = boolItem; @@ -124,8 +116,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "true", required = true, value = "") @JsonProperty("bool_item") @NotNull @@ -138,7 +128,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.boolItem = boolItem; } -/** + /** **/ public TypeHolderExample arrayItem(List arrayItem) { this.arrayItem = arrayItem; @@ -146,8 +136,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "[0, 1, 2, 3]", required = true, value = "") @JsonProperty("array_item") @NotNull diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/User.java index 271676fb2e..6b0eef1b19 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/User.java @@ -16,8 +16,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("User") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class User implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class User implements Serializable { private @Valid Long id; private @Valid String username; private @Valid String firstName; @@ -35,8 +35,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("id") public Long getId() { @@ -48,7 +46,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.id = id; } -/** + /** **/ public User username(String username) { this.username = username; @@ -56,8 +54,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("username") public String getUsername() { @@ -69,7 +65,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.username = username; } -/** + /** **/ public User firstName(String firstName) { this.firstName = firstName; @@ -77,8 +73,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("firstName") public String getFirstName() { @@ -90,7 +84,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.firstName = firstName; } -/** + /** **/ public User lastName(String lastName) { this.lastName = lastName; @@ -98,8 +92,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("lastName") public String getLastName() { @@ -111,7 +103,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.lastName = lastName; } -/** + /** **/ public User email(String email) { this.email = email; @@ -119,8 +111,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("email") public String getEmail() { @@ -132,7 +122,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.email = email; } -/** + /** **/ public User password(String password) { this.password = password; @@ -140,8 +130,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("password") public String getPassword() { @@ -153,7 +141,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.password = password; } -/** + /** **/ public User phone(String phone) { this.phone = phone; @@ -161,8 +149,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("phone") public String getPhone() { @@ -174,7 +160,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.phone = phone; } -/** + /** * User Status **/ public User userStatus(Integer userStatus) { @@ -183,8 +169,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "User Status") @JsonProperty("userStatus") public Integer getUserStatus() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/XmlItem.java index c70af4c9e3..eff4ff035f 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/XmlItem.java @@ -19,37 +19,37 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("XmlItem") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public class XmlItem implements Serializable { - +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") +public class XmlItem implements Serializable { private @Valid String attributeString; private @Valid BigDecimal attributeNumber; private @Valid Integer attributeInteger; private @Valid Boolean attributeBoolean; - private @Valid List wrappedArray = new ArrayList<>(); + private @Valid List wrappedArray = null; private @Valid String nameString; private @Valid BigDecimal nameNumber; private @Valid Integer nameInteger; private @Valid Boolean nameBoolean; - private @Valid List nameArray = new ArrayList<>(); - private @Valid List nameWrappedArray = new ArrayList<>(); + private @Valid List nameArray = null; + private @Valid List nameWrappedArray = null; private @Valid String prefixString; private @Valid BigDecimal prefixNumber; private @Valid Integer prefixInteger; private @Valid Boolean prefixBoolean; - private @Valid List prefixArray = new ArrayList<>(); - private @Valid List prefixWrappedArray = new ArrayList<>(); + private @Valid List prefixArray = null; + private @Valid List prefixWrappedArray = null; private @Valid String namespaceString; private @Valid BigDecimal namespaceNumber; private @Valid Integer namespaceInteger; private @Valid Boolean namespaceBoolean; - private @Valid List namespaceArray = new ArrayList<>(); - private @Valid List namespaceWrappedArray = new ArrayList<>(); + private @Valid List namespaceArray = null; + private @Valid List namespaceWrappedArray = null; private @Valid String prefixNsString; private @Valid BigDecimal prefixNsNumber; private @Valid Integer prefixNsInteger; private @Valid Boolean prefixNsBoolean; - private @Valid List prefixNsArray = new ArrayList<>(); - private @Valid List prefixNsWrappedArray = new ArrayList<>(); + private @Valid List prefixNsArray = null; + private @Valid List prefixNsWrappedArray = null; /** **/ @@ -59,8 +59,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "string", value = "") @JsonProperty("attribute_string") public String getAttributeString() { @@ -72,7 +70,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.attributeString = attributeString; } -/** + /** **/ public XmlItem attributeNumber(BigDecimal attributeNumber) { this.attributeNumber = attributeNumber; @@ -80,8 +78,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "1.234", value = "") @JsonProperty("attribute_number") public BigDecimal getAttributeNumber() { @@ -93,7 +89,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.attributeNumber = attributeNumber; } -/** + /** **/ public XmlItem attributeInteger(Integer attributeInteger) { this.attributeInteger = attributeInteger; @@ -101,8 +97,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "-2", value = "") @JsonProperty("attribute_integer") public Integer getAttributeInteger() { @@ -114,7 +108,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.attributeInteger = attributeInteger; } -/** + /** **/ public XmlItem attributeBoolean(Boolean attributeBoolean) { this.attributeBoolean = attributeBoolean; @@ -122,8 +116,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "true", value = "") @JsonProperty("attribute_boolean") public Boolean getAttributeBoolean() { @@ -135,7 +127,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.attributeBoolean = attributeBoolean; } -/** + /** **/ public XmlItem wrappedArray(List wrappedArray) { this.wrappedArray = wrappedArray; @@ -143,8 +135,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("wrapped_array") public List getWrappedArray() { @@ -172,7 +162,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public XmlItem nameString(String nameString) { this.nameString = nameString; @@ -180,8 +170,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "string", value = "") @JsonProperty("name_string") public String getNameString() { @@ -193,7 +181,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.nameString = nameString; } -/** + /** **/ public XmlItem nameNumber(BigDecimal nameNumber) { this.nameNumber = nameNumber; @@ -201,8 +189,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "1.234", value = "") @JsonProperty("name_number") public BigDecimal getNameNumber() { @@ -214,7 +200,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.nameNumber = nameNumber; } -/** + /** **/ public XmlItem nameInteger(Integer nameInteger) { this.nameInteger = nameInteger; @@ -222,8 +208,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "-2", value = "") @JsonProperty("name_integer") public Integer getNameInteger() { @@ -235,7 +219,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.nameInteger = nameInteger; } -/** + /** **/ public XmlItem nameBoolean(Boolean nameBoolean) { this.nameBoolean = nameBoolean; @@ -243,8 +227,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "true", value = "") @JsonProperty("name_boolean") public Boolean getNameBoolean() { @@ -256,7 +238,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.nameBoolean = nameBoolean; } -/** + /** **/ public XmlItem nameArray(List nameArray) { this.nameArray = nameArray; @@ -264,8 +246,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name_array") public List getNameArray() { @@ -293,7 +273,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public XmlItem nameWrappedArray(List nameWrappedArray) { this.nameWrappedArray = nameWrappedArray; @@ -301,8 +281,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("name_wrapped_array") public List getNameWrappedArray() { @@ -330,7 +308,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public XmlItem prefixString(String prefixString) { this.prefixString = prefixString; @@ -338,8 +316,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "string", value = "") @JsonProperty("prefix_string") public String getPrefixString() { @@ -351,7 +327,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.prefixString = prefixString; } -/** + /** **/ public XmlItem prefixNumber(BigDecimal prefixNumber) { this.prefixNumber = prefixNumber; @@ -359,8 +335,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "1.234", value = "") @JsonProperty("prefix_number") public BigDecimal getPrefixNumber() { @@ -372,7 +346,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.prefixNumber = prefixNumber; } -/** + /** **/ public XmlItem prefixInteger(Integer prefixInteger) { this.prefixInteger = prefixInteger; @@ -380,8 +354,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "-2", value = "") @JsonProperty("prefix_integer") public Integer getPrefixInteger() { @@ -393,7 +365,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.prefixInteger = prefixInteger; } -/** + /** **/ public XmlItem prefixBoolean(Boolean prefixBoolean) { this.prefixBoolean = prefixBoolean; @@ -401,8 +373,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "true", value = "") @JsonProperty("prefix_boolean") public Boolean getPrefixBoolean() { @@ -414,7 +384,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.prefixBoolean = prefixBoolean; } -/** + /** **/ public XmlItem prefixArray(List prefixArray) { this.prefixArray = prefixArray; @@ -422,8 +392,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("prefix_array") public List getPrefixArray() { @@ -451,7 +419,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public XmlItem prefixWrappedArray(List prefixWrappedArray) { this.prefixWrappedArray = prefixWrappedArray; @@ -459,8 +427,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("prefix_wrapped_array") public List getPrefixWrappedArray() { @@ -488,7 +454,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public XmlItem namespaceString(String namespaceString) { this.namespaceString = namespaceString; @@ -496,8 +462,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "string", value = "") @JsonProperty("namespace_string") public String getNamespaceString() { @@ -509,7 +473,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.namespaceString = namespaceString; } -/** + /** **/ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { this.namespaceNumber = namespaceNumber; @@ -517,8 +481,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "1.234", value = "") @JsonProperty("namespace_number") public BigDecimal getNamespaceNumber() { @@ -530,7 +492,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.namespaceNumber = namespaceNumber; } -/** + /** **/ public XmlItem namespaceInteger(Integer namespaceInteger) { this.namespaceInteger = namespaceInteger; @@ -538,8 +500,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "-2", value = "") @JsonProperty("namespace_integer") public Integer getNamespaceInteger() { @@ -551,7 +511,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.namespaceInteger = namespaceInteger; } -/** + /** **/ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { this.namespaceBoolean = namespaceBoolean; @@ -559,8 +519,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "true", value = "") @JsonProperty("namespace_boolean") public Boolean getNamespaceBoolean() { @@ -572,7 +530,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.namespaceBoolean = namespaceBoolean; } -/** + /** **/ public XmlItem namespaceArray(List namespaceArray) { this.namespaceArray = namespaceArray; @@ -580,8 +538,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("namespace_array") public List getNamespaceArray() { @@ -609,7 +565,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { this.namespaceWrappedArray = namespaceWrappedArray; @@ -617,8 +573,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("namespace_wrapped_array") public List getNamespaceWrappedArray() { @@ -646,7 +600,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public XmlItem prefixNsString(String prefixNsString) { this.prefixNsString = prefixNsString; @@ -654,8 +608,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "string", value = "") @JsonProperty("prefix_ns_string") public String getPrefixNsString() { @@ -667,7 +619,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.prefixNsString = prefixNsString; } -/** + /** **/ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { this.prefixNsNumber = prefixNsNumber; @@ -675,8 +627,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "1.234", value = "") @JsonProperty("prefix_ns_number") public BigDecimal getPrefixNsNumber() { @@ -688,7 +638,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.prefixNsNumber = prefixNsNumber; } -/** + /** **/ public XmlItem prefixNsInteger(Integer prefixNsInteger) { this.prefixNsInteger = prefixNsInteger; @@ -696,8 +646,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "-2", value = "") @JsonProperty("prefix_ns_integer") public Integer getPrefixNsInteger() { @@ -709,7 +657,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.prefixNsInteger = prefixNsInteger; } -/** + /** **/ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { this.prefixNsBoolean = prefixNsBoolean; @@ -717,8 +665,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(example = "true", value = "") @JsonProperty("prefix_ns_boolean") public Boolean getPrefixNsBoolean() { @@ -730,7 +676,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; this.prefixNsBoolean = prefixNsBoolean; } -/** + /** **/ public XmlItem prefixNsArray(List prefixNsArray) { this.prefixNsArray = prefixNsArray; @@ -738,8 +684,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("prefix_ns_array") public List getPrefixNsArray() { @@ -767,7 +711,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; return this; } -/** + /** **/ public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { this.prefixNsWrappedArray = prefixNsWrappedArray; @@ -775,8 +719,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; } - - @ApiModelProperty(value = "") @JsonProperty("prefix_ns_wrapped_array") public List getPrefixNsWrappedArray() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/main/openapi/openapi.yaml b/samples/server/petstore/jaxrs-spec-interface-response/src/main/openapi/openapi.yaml index d02806b2d3..bf1a427641 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/main/openapi/openapi.yaml +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/main/openapi/openapi.yaml @@ -46,7 +46,7 @@ paths: tags: - pet x-codegen-request-body-name: body - x-contentType: application/json + x-content-type: application/json x-accepts: application/json x-tags: - tag: pet @@ -83,7 +83,7 @@ paths: tags: - pet x-codegen-request-body-name: body - x-contentType: application/json + x-content-type: application/json x-accepts: application/json x-tags: - tag: pet @@ -262,13 +262,7 @@ paths: content: application/x-www-form-urlencoded: schema: - properties: - name: - description: Updated name of the pet - type: string - status: - description: Updated status of the pet - type: string + $ref: '#/components/schemas/updatePetWithForm_request' responses: "405": content: {} @@ -280,7 +274,7 @@ paths: summary: Updates a pet in the store with form data tags: - pet - x-contentType: application/x-www-form-urlencoded + x-content-type: application/x-www-form-urlencoded x-accepts: application/json x-tags: - tag: pet @@ -299,14 +293,7 @@ paths: content: multipart/form-data: schema: - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - file: - description: file to upload - format: binary - type: string + $ref: '#/components/schemas/uploadFile_request' responses: "200": content: @@ -321,7 +308,7 @@ paths: summary: uploads an image tags: - pet - x-contentType: multipart/form-data + x-content-type: multipart/form-data x-accepts: application/json x-tags: - tag: pet @@ -374,7 +361,7 @@ paths: tags: - store x-codegen-request-body-name: body - x-contentType: '*/*' + x-content-type: '*/*' x-accepts: application/json x-tags: - tag: store @@ -458,7 +445,7 @@ paths: tags: - user x-codegen-request-body-name: body - x-contentType: '*/*' + x-content-type: '*/*' x-accepts: application/json x-tags: - tag: user @@ -482,7 +469,7 @@ paths: tags: - user x-codegen-request-body-name: body - x-contentType: '*/*' + x-content-type: '*/*' x-accepts: application/json x-tags: - tag: user @@ -506,7 +493,7 @@ paths: tags: - user x-codegen-request-body-name: body - x-contentType: '*/*' + x-content-type: '*/*' x-accepts: application/json x-tags: - tag: user @@ -652,7 +639,7 @@ paths: tags: - user x-codegen-request-body-name: body - x-contentType: '*/*' + x-content-type: '*/*' x-accepts: application/json x-tags: - tag: user @@ -680,7 +667,7 @@ paths: tags: - fake_classname_tags 123#$%^ x-codegen-request-body-name: body - x-contentType: application/json + x-content-type: application/json x-accepts: application/json x-tags: - tag: fake_classname_tags 123#$%^ @@ -807,24 +794,7 @@ paths: content: application/x-www-form-urlencoded: schema: - properties: - enum_form_string_array: - description: Form parameter enum test (string array) - items: - default: $ - enum: - - '>' - - $ - type: string - type: array - enum_form_string: - default: -efg - description: Form parameter enum test (string) - enum: - - _abc - - -efg - - (xyz) - type: string + $ref: '#/components/schemas/testEnumParameters_request' responses: "400": content: {} @@ -835,7 +805,7 @@ paths: summary: To test enum parameters tags: - fake - x-contentType: application/x-www-form-urlencoded + x-content-type: application/x-www-form-urlencoded x-accepts: application/json x-tags: - tag: fake @@ -860,7 +830,7 @@ paths: tags: - fake x-codegen-request-body-name: body - x-contentType: application/json + x-content-type: application/json x-accepts: application/json x-tags: - tag: fake @@ -875,77 +845,7 @@ paths: content: application/x-www-form-urlencoded: schema: - properties: - integer: - description: None - format: int32 - maximum: 100 - minimum: 10 - type: integer - int32: - description: None - format: int32 - maximum: 200 - minimum: 20 - type: integer - int64: - description: None - format: int64 - type: integer - number: - description: None - maximum: 543.2 - minimum: 32.1 - type: number - float: - description: None - format: float - maximum: 987.6 - type: number - double: - description: None - format: double - maximum: 123.4 - minimum: 67.8 - type: number - string: - description: None - pattern: "/[a-z]/i" - type: string - pattern_without_delimiter: - description: None - pattern: "^[A-Z].*" - type: string - byte: - description: None - format: byte - type: string - binary: - description: None - format: binary - type: string - date: - description: None - format: date - type: string - dateTime: - description: None - format: date-time - type: string - password: - description: None - format: password - maxLength: 64 - minLength: 10 - type: string - callback: - description: None - type: string - required: - - byte - - double - - number - - pattern_without_delimiter + $ref: '#/components/schemas/testEndpointParameters_request' required: true responses: "400": @@ -963,7 +863,7 @@ paths: 가짜 엔드 포인트 tags: - fake - x-contentType: application/x-www-form-urlencoded + x-content-type: application/x-www-form-urlencoded x-accepts: application/json x-tags: - tag: fake @@ -988,7 +888,7 @@ paths: tags: - fake x-codegen-request-body-name: body - x-contentType: '*/*' + x-content-type: '*/*' x-accepts: '*/*' x-tags: - tag: fake @@ -1013,7 +913,7 @@ paths: tags: - fake x-codegen-request-body-name: body - x-contentType: '*/*' + x-content-type: '*/*' x-accepts: '*/*' x-tags: - tag: fake @@ -1038,7 +938,7 @@ paths: tags: - fake x-codegen-request-body-name: body - x-contentType: '*/*' + x-content-type: '*/*' x-accepts: '*/*' x-tags: - tag: fake @@ -1063,7 +963,7 @@ paths: tags: - fake x-codegen-request-body-name: body - x-contentType: '*/*' + x-content-type: '*/*' x-accepts: '*/*' x-tags: - tag: fake @@ -1074,16 +974,7 @@ paths: content: application/x-www-form-urlencoded: schema: - properties: - param: - description: field1 - type: string - param2: - description: field2 - type: string - required: - - param - - param2 + $ref: '#/components/schemas/testJsonFormData_request' required: true responses: "200": @@ -1092,7 +983,7 @@ paths: summary: test json serialization of form data tags: - fake - x-contentType: application/x-www-form-urlencoded + x-content-type: application/x-www-form-urlencoded x-accepts: application/json x-tags: - tag: fake @@ -1116,7 +1007,7 @@ paths: tags: - fake x-codegen-request-body-name: param - x-contentType: application/json + x-content-type: application/json x-accepts: application/json x-tags: - tag: fake @@ -1142,7 +1033,7 @@ paths: tags: - fake x-codegen-request-body-name: body - x-contentType: application/json + x-content-type: application/json x-accepts: application/json x-tags: - tag: fake @@ -1180,7 +1071,7 @@ paths: tags: - fake x-codegen-request-body-name: XmlItem - x-contentType: application/xml + x-content-type: application/xml x-accepts: application/json x-tags: - tag: fake @@ -1206,7 +1097,7 @@ paths: tags: - $another-fake? x-codegen-request-body-name: body - x-contentType: application/json + x-content-type: application/json x-accepts: application/json x-tags: - tag: $another-fake? @@ -1228,7 +1119,7 @@ paths: tags: - fake x-codegen-request-body-name: body - x-contentType: application/json + x-content-type: application/json x-accepts: application/json x-tags: - tag: fake @@ -1303,16 +1194,7 @@ paths: content: multipart/form-data: schema: - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - requiredFile: - description: file to upload - format: binary - type: string - required: - - requiredFile + $ref: '#/components/schemas/uploadFileWithRequiredFile_request' required: true responses: "200": @@ -1328,7 +1210,7 @@ paths: summary: uploads an image (required) tags: - pet - x-contentType: multipart/form-data + x-content-type: multipart/form-data x-accepts: application/json x-tags: - tag: pet @@ -2221,6 +2103,136 @@ components: xml: namespace: http://a.com/schema prefix: pre + updatePetWithForm_request: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + uploadFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + testEnumParameters_request: + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + enum_form_string: + default: -efg + description: Form parameter enum test (string) + enum: + - _abc + - -efg + - (xyz) + type: string + testEndpointParameters_request: + properties: + integer: + description: None + format: int32 + maximum: 100 + minimum: 10 + type: integer + int32: + description: None + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + description: None + format: int64 + type: integer + number: + description: None + maximum: 543.2 + minimum: 32.1 + type: number + float: + description: None + format: float + maximum: 987.6 + type: number + double: + description: None + format: double + maximum: 123.4 + minimum: 67.8 + type: number + string: + description: None + pattern: "/[a-z]/i" + type: string + pattern_without_delimiter: + description: None + pattern: "^[A-Z].*" + type: string + byte: + description: None + format: byte + type: string + binary: + description: None + format: binary + type: string + date: + description: None + format: date + type: string + dateTime: + description: None + format: date-time + type: string + password: + description: None + format: password + maxLength: 64 + minLength: 10 + type: string + callback: + description: None + type: string + required: + - byte + - double + - number + - pattern_without_delimiter + testJsonFormData_request: + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + uploadFileWithRequiredFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + format: binary + type: string + required: + - requiredFile Dog_allOf: properties: breed: diff --git a/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/FILES b/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/FILES index 912cd6039b..a5460bdf42 100644 --- a/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/FILES +++ b/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/FILES @@ -4,6 +4,7 @@ src/gen/java/org/openapitools/api/AnotherFakeApi.java src/gen/java/org/openapitools/api/FakeApi.java src/gen/java/org/openapitools/api/FakeClassnameTestApi.java src/gen/java/org/openapitools/api/PetApi.java +src/gen/java/org/openapitools/api/RestResourceRoot.java src/gen/java/org/openapitools/api/StoreApi.java src/gen/java/org/openapitools/api/UserApi.java src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/api/RestResourceRoot.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/api/RestResourceRoot.java new file mode 100644 index 0000000000..96ba6c8d8e --- /dev/null +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/api/RestResourceRoot.java @@ -0,0 +1,5 @@ +package org.openapitools.api; + +public class RestResourceRoot { + public static final String APPLICATION_PATH = "/v2"; +} diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 1c8ec238b7..749ca0e02c 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesAnyType") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesAnyType extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 3d04c06342..3563c9cdc6 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesArray") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesArray extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 8a7da60731..0afb07939f 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesBoolean") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesBoolean extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index dc357d0778..31b4b91dfb 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -22,15 +22,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesClass") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesClass implements Serializable { - - private @Valid Map mapString = new HashMap<>(); - private @Valid Map mapNumber = new HashMap<>(); - private @Valid Map mapInteger = new HashMap<>(); - private @Valid Map mapBoolean = new HashMap<>(); - private @Valid Map> mapArrayInteger = new HashMap<>(); - private @Valid Map> mapArrayAnytype = new HashMap<>(); - private @Valid Map> mapMapString = new HashMap<>(); - private @Valid Map> mapMapAnytype = new HashMap<>(); + private @Valid Map mapString = null; + private @Valid Map mapNumber = null; + private @Valid Map mapInteger = null; + private @Valid Map mapBoolean = null; + private @Valid Map> mapArrayInteger = null; + private @Valid Map> mapArrayAnytype = null; + private @Valid Map> mapMapString = null; + private @Valid Map> mapMapAnytype = null; private @Valid Object anytype1; private @Valid Object anytype2; private @Valid Object anytype3; @@ -70,7 +69,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapNumber(Map mapNumber) { this.mapNumber = mapNumber; @@ -105,7 +104,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapInteger(Map mapInteger) { this.mapInteger = mapInteger; @@ -140,7 +139,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { this.mapBoolean = mapBoolean; @@ -175,7 +174,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapArrayInteger(Map> mapArrayInteger) { this.mapArrayInteger = mapArrayInteger; @@ -210,7 +209,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapArrayAnytype(Map> mapArrayAnytype) { this.mapArrayAnytype = mapArrayAnytype; @@ -245,7 +244,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapMapString(Map> mapMapString) { this.mapMapString = mapMapString; @@ -280,7 +279,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapMapAnytype(Map> mapMapAnytype) { this.mapMapAnytype = mapMapAnytype; @@ -315,7 +314,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass anytype1(Object anytype1) { this.anytype1 = anytype1; @@ -334,7 +333,7 @@ public class AdditionalPropertiesClass implements Serializable { this.anytype1 = anytype1; } -/** + /** **/ public AdditionalPropertiesClass anytype2(Object anytype2) { this.anytype2 = anytype2; @@ -353,7 +352,7 @@ public class AdditionalPropertiesClass implements Serializable { this.anytype2 = anytype2; } -/** + /** **/ public AdditionalPropertiesClass anytype3(Object anytype3) { this.anytype3 = anytype3; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index 4ed241faad..376aa5a7c6 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesInteger") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesInteger extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index c48bafb3b7..03cf9a126d 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesNumber") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesNumber extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index ed49983b82..b9fae3edf8 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesObject") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesObject extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index 2c596592d3..9790203702 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesString") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesString extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Animal.java index 4e53f6e996..3548453f12 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Animal.java @@ -27,7 +27,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Animal") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Animal implements Serializable { - private @Valid String className; private @Valid String color = "red"; @@ -51,7 +50,7 @@ public class Animal implements Serializable { this.className = className; } -/** + /** **/ public Animal color(String color) { this.color = color; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 922a32ea5c..0385c5e829 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -21,8 +21,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ArrayOfArrayOfNumberOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ArrayOfArrayOfNumberOnly implements Serializable { - - private @Valid List> arrayArrayNumber = new ArrayList<>(); + private @Valid List> arrayArrayNumber = null; /** **/ diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index b971245130..cbfdb52003 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -21,8 +21,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ArrayOfNumberOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ArrayOfNumberOnly implements Serializable { - - private @Valid List arrayNumber = new ArrayList<>(); + private @Valid List arrayNumber = null; /** **/ diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayTest.java index 733895ab21..b2043ee09c 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayTest.java @@ -21,10 +21,9 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ArrayTest") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ArrayTest implements Serializable { - - private @Valid List arrayOfString = new ArrayList<>(); - private @Valid List> arrayArrayOfInteger = new ArrayList<>(); - private @Valid List> arrayArrayOfModel = new ArrayList<>(); + private @Valid List arrayOfString = null; + private @Valid List> arrayArrayOfInteger = null; + private @Valid List> arrayArrayOfModel = null; /** **/ @@ -61,7 +60,7 @@ public class ArrayTest implements Serializable { return this; } -/** + /** **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; @@ -96,7 +95,7 @@ public class ArrayTest implements Serializable { return this; } -/** + /** **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCat.java index 3ce3429094..fb8229016d 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCat.java @@ -19,9 +19,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("BigCat") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class BigCat extends Cat implements Serializable { - - -public enum KindEnum { + public enum KindEnum { LIONS(String.valueOf("lions")), TIGERS(String.valueOf("tigers")), LEOPARDS(String.valueOf("leopards")), JAGUARS(String.valueOf("jaguars")); diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCatAllOf.java index 2564d27774..21427933a9 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -19,9 +19,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("BigCat_allOf") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class BigCatAllOf implements Serializable { - - -public enum KindEnum { + public enum KindEnum { LIONS(String.valueOf("lions")), TIGERS(String.valueOf("tigers")), LEOPARDS(String.valueOf("leopards")), JAGUARS(String.valueOf("jaguars")); diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Capitalization.java index ae3e71e9de..862e34ac29 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Capitalization.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Capitalization") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Capitalization implements Serializable { - private @Valid String smallCamel; private @Valid String capitalCamel; private @Valid String smallSnake; @@ -45,7 +44,7 @@ public class Capitalization implements Serializable { this.smallCamel = smallCamel; } -/** + /** **/ public Capitalization capitalCamel(String capitalCamel) { this.capitalCamel = capitalCamel; @@ -64,7 +63,7 @@ public class Capitalization implements Serializable { this.capitalCamel = capitalCamel; } -/** + /** **/ public Capitalization smallSnake(String smallSnake) { this.smallSnake = smallSnake; @@ -83,7 +82,7 @@ public class Capitalization implements Serializable { this.smallSnake = smallSnake; } -/** + /** **/ public Capitalization capitalSnake(String capitalSnake) { this.capitalSnake = capitalSnake; @@ -102,7 +101,7 @@ public class Capitalization implements Serializable { this.capitalSnake = capitalSnake; } -/** + /** **/ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { this.scAETHFlowPoints = scAETHFlowPoints; @@ -121,7 +120,7 @@ public class Capitalization implements Serializable { this.scAETHFlowPoints = scAETHFlowPoints; } -/** + /** * Name of the pet **/ public Capitalization ATT_NAME(String ATT_NAME) { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Cat.java index 89a8109676..7fa39e3522 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Cat.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Cat") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Cat extends Animal implements Serializable { - private @Valid Boolean declawed; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/CatAllOf.java index 4c85fb125e..491b09cbba 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/CatAllOf.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Cat_allOf") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class CatAllOf implements Serializable { - private @Valid Boolean declawed; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Category.java index 5d87f23095..3ae4d3b4b4 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Category.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Category") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Category implements Serializable { - private @Valid Long id; private @Valid String name = "default-name"; @@ -41,7 +40,7 @@ public class Category implements Serializable { this.id = id; } -/** + /** **/ public Category name(String name) { this.name = name; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ClassModel.java index eab0da8615..ee9e240aac 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ClassModel.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ClassModel") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ClassModel implements Serializable { - private @Valid String propertyClass; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Client.java index 40ebc121c6..c3efb2cbd6 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Client.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Client") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Client implements Serializable { - private @Valid String client; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Dog.java index 1bad737c9e..2e8e10e641 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Dog.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Dog") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Dog extends Animal implements Serializable { - private @Valid String breed; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/DogAllOf.java index bb5196f406..a2e595a8a1 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/DogAllOf.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Dog_allOf") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class DogAllOf implements Serializable { - private @Valid String breed; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumArrays.java index 127a6cf3c6..4b2ef0c1c6 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumArrays.java @@ -20,9 +20,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("EnumArrays") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class EnumArrays implements Serializable { - - -public enum JustSymbolEnum { + public enum JustSymbolEnum { GREATER_THAN_OR_EQUAL_TO(String.valueOf(">=")), DOLLAR(String.valueOf("$")); @@ -70,8 +68,7 @@ public enum JustSymbolEnum { } private @Valid JustSymbolEnum justSymbol; - -public enum ArrayEnumEnum { + public enum ArrayEnumEnum { FISH(String.valueOf("fish")), CRAB(String.valueOf("crab")); @@ -118,7 +115,7 @@ public enum ArrayEnumEnum { } } - private @Valid List arrayEnum = new ArrayList<>(); + private @Valid List arrayEnum = null; /** **/ @@ -139,7 +136,7 @@ public enum ArrayEnumEnum { this.justSymbol = justSymbol; } -/** + /** **/ public EnumArrays arrayEnum(List arrayEnum) { this.arrayEnum = arrayEnum; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumTest.java index b1273c7be4..b4692c31c4 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumTest.java @@ -20,9 +20,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Enum_Test") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class EnumTest implements Serializable { - - -public enum EnumStringEnum { + public enum EnumStringEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); @@ -70,8 +68,7 @@ public enum EnumStringEnum { } private @Valid EnumStringEnum enumString; - -public enum EnumStringRequiredEnum { + public enum EnumStringRequiredEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); @@ -119,8 +116,7 @@ public enum EnumStringRequiredEnum { } private @Valid EnumStringRequiredEnum enumStringRequired; - -public enum EnumIntegerEnum { + public enum EnumIntegerEnum { NUMBER_1(Integer.valueOf(1)), NUMBER_MINUS_1(Integer.valueOf(-1)); @@ -168,8 +164,7 @@ public enum EnumIntegerEnum { } private @Valid EnumIntegerEnum enumInteger; - -public enum EnumNumberEnum { + public enum EnumNumberEnum { NUMBER_1_DOT_1(Double.valueOf(1.1)), NUMBER_MINUS_1_DOT_2(Double.valueOf(-1.2)); @@ -238,7 +233,7 @@ public enum EnumNumberEnum { this.enumString = enumString; } -/** + /** **/ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { this.enumStringRequired = enumStringRequired; @@ -258,7 +253,7 @@ public enum EnumNumberEnum { this.enumStringRequired = enumStringRequired; } -/** + /** **/ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; @@ -277,7 +272,7 @@ public enum EnumNumberEnum { this.enumInteger = enumInteger; } -/** + /** **/ public EnumTest enumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; @@ -296,7 +291,7 @@ public enum EnumNumberEnum { this.enumNumber = enumNumber; } -/** + /** **/ public EnumTest outerEnum(OuterEnum outerEnum) { this.outerEnum = outerEnum; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 9960e3877c..8297178d42 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -21,9 +21,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("FileSchemaTestClass") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FileSchemaTestClass implements Serializable { - private @Valid ModelFile _file; - private @Valid List files = new ArrayList<>(); + private @Valid List files = null; /** **/ @@ -44,7 +43,7 @@ public class FileSchemaTestClass implements Serializable { this._file = _file; } -/** + /** **/ public FileSchemaTestClass files(List files) { this.files = files; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FormatTest.java index 82d76ba209..8d71c95701 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FormatTest.java @@ -25,7 +25,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("format_test") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FormatTest implements Serializable { - private @Valid Integer integer; private @Valid Integer int32; private @Valid Long int64; @@ -62,7 +61,7 @@ public class FormatTest implements Serializable { this.integer = integer; } -/** + /** * minimum: 20 * maximum: 200 **/ @@ -83,7 +82,7 @@ public class FormatTest implements Serializable { this.int32 = int32; } -/** + /** **/ public FormatTest int64(Long int64) { this.int64 = int64; @@ -102,7 +101,7 @@ public class FormatTest implements Serializable { this.int64 = int64; } -/** + /** * minimum: 32.1 * maximum: 543.2 **/ @@ -124,7 +123,7 @@ public class FormatTest implements Serializable { this.number = number; } -/** + /** * minimum: 54.3 * maximum: 987.6 **/ @@ -145,7 +144,7 @@ public class FormatTest implements Serializable { this._float = _float; } -/** + /** * minimum: 67.8 * maximum: 123.4 **/ @@ -166,7 +165,7 @@ public class FormatTest implements Serializable { this._double = _double; } -/** + /** **/ public FormatTest string(String string) { this.string = string; @@ -185,7 +184,7 @@ public class FormatTest implements Serializable { this.string = string; } -/** + /** **/ public FormatTest _byte(byte[] _byte) { this._byte = _byte; @@ -205,7 +204,7 @@ public class FormatTest implements Serializable { this._byte = _byte; } -/** + /** **/ public FormatTest binary(File binary) { this.binary = binary; @@ -224,7 +223,7 @@ public class FormatTest implements Serializable { this.binary = binary; } -/** + /** **/ public FormatTest date(LocalDate date) { this.date = date; @@ -244,7 +243,7 @@ public class FormatTest implements Serializable { this.date = date; } -/** + /** **/ public FormatTest dateTime(Date dateTime) { this.dateTime = dateTime; @@ -263,7 +262,7 @@ public class FormatTest implements Serializable { this.dateTime = dateTime; } -/** + /** **/ public FormatTest uuid(UUID uuid) { this.uuid = uuid; @@ -282,7 +281,7 @@ public class FormatTest implements Serializable { this.uuid = uuid; } -/** + /** **/ public FormatTest password(String password) { this.password = password; @@ -302,7 +301,7 @@ public class FormatTest implements Serializable { this.password = password; } -/** + /** **/ public FormatTest bigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index cff655cd95..a3ff9057c6 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("hasOnlyReadOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class HasOnlyReadOnly implements Serializable { - private @Valid String bar; private @Valid String foo; @@ -42,7 +41,7 @@ public class HasOnlyReadOnly implements Serializable { this.bar = bar; } -/** + /** **/ public HasOnlyReadOnly foo(String foo) { this.foo = foo; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MapTest.java index f8706dc8ed..c45ee600ca 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MapTest.java @@ -20,10 +20,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("MapTest") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class MapTest implements Serializable { - - private @Valid Map> mapMapOfString = new HashMap<>(); - -public enum InnerEnum { + private @Valid Map> mapMapOfString = null; + public enum InnerEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")); @@ -70,9 +68,9 @@ public enum InnerEnum { } } - private @Valid Map mapOfEnumString = new HashMap<>(); - private @Valid Map directMap = new HashMap<>(); - private @Valid Map indirectMap = new HashMap<>(); + private @Valid Map mapOfEnumString = null; + private @Valid Map directMap = null; + private @Valid Map indirectMap = null; /** **/ @@ -109,7 +107,7 @@ public enum InnerEnum { return this; } -/** + /** **/ public MapTest mapOfEnumString(Map mapOfEnumString) { this.mapOfEnumString = mapOfEnumString; @@ -144,7 +142,7 @@ public enum InnerEnum { return this; } -/** + /** **/ public MapTest directMap(Map directMap) { this.directMap = directMap; @@ -179,7 +177,7 @@ public enum InnerEnum { return this; } -/** + /** **/ public MapTest indirectMap(Map indirectMap) { this.indirectMap = indirectMap; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 5e34ba9baa..c5e37deb23 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -23,10 +23,9 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("MixedPropertiesAndAdditionalPropertiesClass") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class MixedPropertiesAndAdditionalPropertiesClass implements Serializable { - private @Valid UUID uuid; private @Valid Date dateTime; - private @Valid Map map = new HashMap<>(); + private @Valid Map map = null; /** **/ @@ -47,7 +46,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl this.uuid = uuid; } -/** + /** **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { this.dateTime = dateTime; @@ -66,7 +65,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl this.dateTime = dateTime; } -/** + /** **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Model200Response.java index 872cba205c..9023f1b364 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Model200Response.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("200_response") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Model200Response implements Serializable { - private @Valid Integer name; private @Valid String propertyClass; @@ -44,7 +43,7 @@ public class Model200Response implements Serializable { this.name = name; } -/** + /** **/ public Model200Response propertyClass(String propertyClass) { this.propertyClass = propertyClass; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelApiResponse.java index fecda85f1f..58d4e3da8f 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ApiResponse") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ModelApiResponse implements Serializable { - private @Valid Integer code; private @Valid String type; private @Valid String message; @@ -43,7 +42,7 @@ public class ModelApiResponse implements Serializable { this.code = code; } -/** + /** **/ public ModelApiResponse type(String type) { this.type = type; @@ -62,7 +61,7 @@ public class ModelApiResponse implements Serializable { this.type = type; } -/** + /** **/ public ModelApiResponse message(String message) { this.message = message; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelFile.java index 2fe0824ec3..b68b110209 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelFile.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("File") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ModelFile implements Serializable { - private @Valid String sourceURI; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelList.java index 3eb7f71d5a..5f5c9d766d 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelList.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("List") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ModelList implements Serializable { - private @Valid String _123list; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelReturn.java index 8869a5a3ed..3af7ec3625 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ModelReturn.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Return") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ModelReturn implements Serializable { - private @Valid Integer _return; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Name.java index 893ad44378..09f3be2cf4 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Name.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Name") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Name implements Serializable { - private @Valid Integer name; private @Valid Integer snakeCase; private @Valid String property; @@ -46,7 +45,7 @@ public class Name implements Serializable { this.name = name; } -/** + /** **/ public Name snakeCase(Integer snakeCase) { this.snakeCase = snakeCase; @@ -65,7 +64,7 @@ public class Name implements Serializable { this.snakeCase = snakeCase; } -/** + /** **/ public Name property(String property) { this.property = property; @@ -84,7 +83,7 @@ public class Name implements Serializable { this.property = property; } -/** + /** **/ public Name _123number(Integer _123number) { this._123number = _123number; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/NumberOnly.java index b87e9e4607..d8bba4783f 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/NumberOnly.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("NumberOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class NumberOnly implements Serializable { - private @Valid BigDecimal justNumber; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Order.java index 1b0c3c95a4..5a6d37a5d7 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Order.java @@ -19,13 +19,11 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Order") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Order implements Serializable { - private @Valid Long id; private @Valid Long petId; private @Valid Integer quantity; private @Valid Date shipDate; - -public enum StatusEnum { + public enum StatusEnum { PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); @@ -94,7 +92,7 @@ public enum StatusEnum { this.id = id; } -/** + /** **/ public Order petId(Long petId) { this.petId = petId; @@ -113,7 +111,7 @@ public enum StatusEnum { this.petId = petId; } -/** + /** **/ public Order quantity(Integer quantity) { this.quantity = quantity; @@ -132,7 +130,7 @@ public enum StatusEnum { this.quantity = quantity; } -/** + /** **/ public Order shipDate(Date shipDate) { this.shipDate = shipDate; @@ -151,7 +149,7 @@ public enum StatusEnum { this.shipDate = shipDate; } -/** + /** * Order Status **/ public Order status(StatusEnum status) { @@ -171,7 +169,7 @@ public enum StatusEnum { this.status = status; } -/** + /** **/ public Order complete(Boolean complete) { this.complete = complete; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/OuterComposite.java index 5447ec4524..b369e965b6 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/OuterComposite.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("OuterComposite") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class OuterComposite implements Serializable { - private @Valid BigDecimal myNumber; private @Valid String myString; private @Valid Boolean myBoolean; @@ -43,7 +42,7 @@ public class OuterComposite implements Serializable { this.myNumber = myNumber; } -/** + /** **/ public OuterComposite myString(String myString) { this.myString = myString; @@ -62,7 +61,7 @@ public class OuterComposite implements Serializable { this.myString = myString; } -/** + /** **/ public OuterComposite myBoolean(Boolean myBoolean) { this.myBoolean = myBoolean; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Pet.java index 08542b3e82..509dc7f912 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Pet.java @@ -25,14 +25,12 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Pet") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Pet implements Serializable { - private @Valid Long id; private @Valid Category category; private @Valid String name; private @Valid Set photoUrls = new LinkedHashSet<>(); - private @Valid List tags = new ArrayList<>(); - -public enum StatusEnum { + private @Valid List tags = null; + public enum StatusEnum { AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); @@ -100,7 +98,7 @@ public enum StatusEnum { this.id = id; } -/** + /** **/ public Pet category(Category category) { this.category = category; @@ -119,7 +117,7 @@ public enum StatusEnum { this.category = category; } -/** + /** **/ public Pet name(String name) { this.name = name; @@ -139,7 +137,7 @@ public enum StatusEnum { this.name = name; } -/** + /** **/ public Pet photoUrls(Set photoUrls) { this.photoUrls = photoUrls; @@ -176,7 +174,7 @@ public enum StatusEnum { return this; } -/** + /** **/ public Pet tags(List tags) { this.tags = tags; @@ -211,7 +209,7 @@ public enum StatusEnum { return this; } -/** + /** * pet status in the store **/ public Pet status(StatusEnum status) { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index 4e056fc14a..164caf2e40 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ReadOnlyFirst") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ReadOnlyFirst implements Serializable { - private @Valid String bar; private @Valid String baz; @@ -41,7 +40,7 @@ public class ReadOnlyFirst implements Serializable { this.bar = bar; } -/** + /** **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/SpecialModelName.java index 2ee8a2e342..03dbaba2b8 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("$special[model.name]") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class SpecialModelName implements Serializable { - private @Valid Long $specialPropertyName; /** diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Tag.java index e47ffe2a0a..56dde36482 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Tag.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Tag") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Tag implements Serializable { - private @Valid Long id; private @Valid String name; @@ -41,7 +40,7 @@ public class Tag implements Serializable { this.id = id; } -/** + /** **/ public Tag name(String name) { this.name = name; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 664368158e..5a58d2e4a4 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("TypeHolderDefault") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class TypeHolderDefault implements Serializable { - private @Valid String stringItem = "what"; private @Valid BigDecimal numberItem; private @Valid Integer integerItem; @@ -48,7 +47,7 @@ public class TypeHolderDefault implements Serializable { this.stringItem = stringItem; } -/** + /** **/ public TypeHolderDefault numberItem(BigDecimal numberItem) { this.numberItem = numberItem; @@ -68,7 +67,7 @@ public class TypeHolderDefault implements Serializable { this.numberItem = numberItem; } -/** + /** **/ public TypeHolderDefault integerItem(Integer integerItem) { this.integerItem = integerItem; @@ -88,7 +87,7 @@ public class TypeHolderDefault implements Serializable { this.integerItem = integerItem; } -/** + /** **/ public TypeHolderDefault boolItem(Boolean boolItem) { this.boolItem = boolItem; @@ -108,7 +107,7 @@ public class TypeHolderDefault implements Serializable { this.boolItem = boolItem; } -/** + /** **/ public TypeHolderDefault arrayItem(List arrayItem) { this.arrayItem = arrayItem; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/TypeHolderExample.java index a89ee2042d..1c24650e19 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("TypeHolderExample") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class TypeHolderExample implements Serializable { - private @Valid String stringItem; private @Valid BigDecimal numberItem; private @Valid Float floatItem; @@ -49,7 +48,7 @@ public class TypeHolderExample implements Serializable { this.stringItem = stringItem; } -/** + /** **/ public TypeHolderExample numberItem(BigDecimal numberItem) { this.numberItem = numberItem; @@ -69,7 +68,7 @@ public class TypeHolderExample implements Serializable { this.numberItem = numberItem; } -/** + /** **/ public TypeHolderExample floatItem(Float floatItem) { this.floatItem = floatItem; @@ -89,7 +88,7 @@ public class TypeHolderExample implements Serializable { this.floatItem = floatItem; } -/** + /** **/ public TypeHolderExample integerItem(Integer integerItem) { this.integerItem = integerItem; @@ -109,7 +108,7 @@ public class TypeHolderExample implements Serializable { this.integerItem = integerItem; } -/** + /** **/ public TypeHolderExample boolItem(Boolean boolItem) { this.boolItem = boolItem; @@ -129,7 +128,7 @@ public class TypeHolderExample implements Serializable { this.boolItem = boolItem; } -/** + /** **/ public TypeHolderExample arrayItem(List arrayItem) { this.arrayItem = arrayItem; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/User.java index 6531f72351..6b0eef1b19 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/User.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("User") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class User implements Serializable { - private @Valid Long id; private @Valid String username; private @Valid String firstName; @@ -47,7 +46,7 @@ public class User implements Serializable { this.id = id; } -/** + /** **/ public User username(String username) { this.username = username; @@ -66,7 +65,7 @@ public class User implements Serializable { this.username = username; } -/** + /** **/ public User firstName(String firstName) { this.firstName = firstName; @@ -85,7 +84,7 @@ public class User implements Serializable { this.firstName = firstName; } -/** + /** **/ public User lastName(String lastName) { this.lastName = lastName; @@ -104,7 +103,7 @@ public class User implements Serializable { this.lastName = lastName; } -/** + /** **/ public User email(String email) { this.email = email; @@ -123,7 +122,7 @@ public class User implements Serializable { this.email = email; } -/** + /** **/ public User password(String password) { this.password = password; @@ -142,7 +141,7 @@ public class User implements Serializable { this.password = password; } -/** + /** **/ public User phone(String phone) { this.phone = phone; @@ -161,7 +160,7 @@ public class User implements Serializable { this.phone = phone; } -/** + /** * User Status **/ public User userStatus(Integer userStatus) { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/XmlItem.java index 3172d260c8..eff4ff035f 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/XmlItem.java @@ -21,36 +21,35 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("XmlItem") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class XmlItem implements Serializable { - private @Valid String attributeString; private @Valid BigDecimal attributeNumber; private @Valid Integer attributeInteger; private @Valid Boolean attributeBoolean; - private @Valid List wrappedArray = new ArrayList<>(); + private @Valid List wrappedArray = null; private @Valid String nameString; private @Valid BigDecimal nameNumber; private @Valid Integer nameInteger; private @Valid Boolean nameBoolean; - private @Valid List nameArray = new ArrayList<>(); - private @Valid List nameWrappedArray = new ArrayList<>(); + private @Valid List nameArray = null; + private @Valid List nameWrappedArray = null; private @Valid String prefixString; private @Valid BigDecimal prefixNumber; private @Valid Integer prefixInteger; private @Valid Boolean prefixBoolean; - private @Valid List prefixArray = new ArrayList<>(); - private @Valid List prefixWrappedArray = new ArrayList<>(); + private @Valid List prefixArray = null; + private @Valid List prefixWrappedArray = null; private @Valid String namespaceString; private @Valid BigDecimal namespaceNumber; private @Valid Integer namespaceInteger; private @Valid Boolean namespaceBoolean; - private @Valid List namespaceArray = new ArrayList<>(); - private @Valid List namespaceWrappedArray = new ArrayList<>(); + private @Valid List namespaceArray = null; + private @Valid List namespaceWrappedArray = null; private @Valid String prefixNsString; private @Valid BigDecimal prefixNsNumber; private @Valid Integer prefixNsInteger; private @Valid Boolean prefixNsBoolean; - private @Valid List prefixNsArray = new ArrayList<>(); - private @Valid List prefixNsWrappedArray = new ArrayList<>(); + private @Valid List prefixNsArray = null; + private @Valid List prefixNsWrappedArray = null; /** **/ @@ -71,7 +70,7 @@ public class XmlItem implements Serializable { this.attributeString = attributeString; } -/** + /** **/ public XmlItem attributeNumber(BigDecimal attributeNumber) { this.attributeNumber = attributeNumber; @@ -90,7 +89,7 @@ public class XmlItem implements Serializable { this.attributeNumber = attributeNumber; } -/** + /** **/ public XmlItem attributeInteger(Integer attributeInteger) { this.attributeInteger = attributeInteger; @@ -109,7 +108,7 @@ public class XmlItem implements Serializable { this.attributeInteger = attributeInteger; } -/** + /** **/ public XmlItem attributeBoolean(Boolean attributeBoolean) { this.attributeBoolean = attributeBoolean; @@ -128,7 +127,7 @@ public class XmlItem implements Serializable { this.attributeBoolean = attributeBoolean; } -/** + /** **/ public XmlItem wrappedArray(List wrappedArray) { this.wrappedArray = wrappedArray; @@ -163,7 +162,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem nameString(String nameString) { this.nameString = nameString; @@ -182,7 +181,7 @@ public class XmlItem implements Serializable { this.nameString = nameString; } -/** + /** **/ public XmlItem nameNumber(BigDecimal nameNumber) { this.nameNumber = nameNumber; @@ -201,7 +200,7 @@ public class XmlItem implements Serializable { this.nameNumber = nameNumber; } -/** + /** **/ public XmlItem nameInteger(Integer nameInteger) { this.nameInteger = nameInteger; @@ -220,7 +219,7 @@ public class XmlItem implements Serializable { this.nameInteger = nameInteger; } -/** + /** **/ public XmlItem nameBoolean(Boolean nameBoolean) { this.nameBoolean = nameBoolean; @@ -239,7 +238,7 @@ public class XmlItem implements Serializable { this.nameBoolean = nameBoolean; } -/** + /** **/ public XmlItem nameArray(List nameArray) { this.nameArray = nameArray; @@ -274,7 +273,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem nameWrappedArray(List nameWrappedArray) { this.nameWrappedArray = nameWrappedArray; @@ -309,7 +308,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem prefixString(String prefixString) { this.prefixString = prefixString; @@ -328,7 +327,7 @@ public class XmlItem implements Serializable { this.prefixString = prefixString; } -/** + /** **/ public XmlItem prefixNumber(BigDecimal prefixNumber) { this.prefixNumber = prefixNumber; @@ -347,7 +346,7 @@ public class XmlItem implements Serializable { this.prefixNumber = prefixNumber; } -/** + /** **/ public XmlItem prefixInteger(Integer prefixInteger) { this.prefixInteger = prefixInteger; @@ -366,7 +365,7 @@ public class XmlItem implements Serializable { this.prefixInteger = prefixInteger; } -/** + /** **/ public XmlItem prefixBoolean(Boolean prefixBoolean) { this.prefixBoolean = prefixBoolean; @@ -385,7 +384,7 @@ public class XmlItem implements Serializable { this.prefixBoolean = prefixBoolean; } -/** + /** **/ public XmlItem prefixArray(List prefixArray) { this.prefixArray = prefixArray; @@ -420,7 +419,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem prefixWrappedArray(List prefixWrappedArray) { this.prefixWrappedArray = prefixWrappedArray; @@ -455,7 +454,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem namespaceString(String namespaceString) { this.namespaceString = namespaceString; @@ -474,7 +473,7 @@ public class XmlItem implements Serializable { this.namespaceString = namespaceString; } -/** + /** **/ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { this.namespaceNumber = namespaceNumber; @@ -493,7 +492,7 @@ public class XmlItem implements Serializable { this.namespaceNumber = namespaceNumber; } -/** + /** **/ public XmlItem namespaceInteger(Integer namespaceInteger) { this.namespaceInteger = namespaceInteger; @@ -512,7 +511,7 @@ public class XmlItem implements Serializable { this.namespaceInteger = namespaceInteger; } -/** + /** **/ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { this.namespaceBoolean = namespaceBoolean; @@ -531,7 +530,7 @@ public class XmlItem implements Serializable { this.namespaceBoolean = namespaceBoolean; } -/** + /** **/ public XmlItem namespaceArray(List namespaceArray) { this.namespaceArray = namespaceArray; @@ -566,7 +565,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { this.namespaceWrappedArray = namespaceWrappedArray; @@ -601,7 +600,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem prefixNsString(String prefixNsString) { this.prefixNsString = prefixNsString; @@ -620,7 +619,7 @@ public class XmlItem implements Serializable { this.prefixNsString = prefixNsString; } -/** + /** **/ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { this.prefixNsNumber = prefixNsNumber; @@ -639,7 +638,7 @@ public class XmlItem implements Serializable { this.prefixNsNumber = prefixNsNumber; } -/** + /** **/ public XmlItem prefixNsInteger(Integer prefixNsInteger) { this.prefixNsInteger = prefixNsInteger; @@ -658,7 +657,7 @@ public class XmlItem implements Serializable { this.prefixNsInteger = prefixNsInteger; } -/** + /** **/ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { this.prefixNsBoolean = prefixNsBoolean; @@ -677,7 +676,7 @@ public class XmlItem implements Serializable { this.prefixNsBoolean = prefixNsBoolean; } -/** + /** **/ public XmlItem prefixNsArray(List prefixNsArray) { this.prefixNsArray = prefixNsArray; @@ -712,7 +711,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { this.prefixNsWrappedArray = prefixNsWrappedArray; diff --git a/samples/server/petstore/jaxrs-spec-interface/src/main/openapi/openapi.yaml b/samples/server/petstore/jaxrs-spec-interface/src/main/openapi/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/main/openapi/openapi.yaml +++ b/samples/server/petstore/jaxrs-spec-interface/src/main/openapi/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/jaxrs-spec/.openapi-generator/FILES b/samples/server/petstore/jaxrs-spec/.openapi-generator/FILES index 9ad6a195e8..cf689a825e 100644 --- a/samples/server/petstore/jaxrs-spec/.openapi-generator/FILES +++ b/samples/server/petstore/jaxrs-spec/.openapi-generator/FILES @@ -5,6 +5,7 @@ src/gen/java/org/openapitools/api/FakeApi.java src/gen/java/org/openapitools/api/FakeClassnameTestApi.java src/gen/java/org/openapitools/api/PetApi.java src/gen/java/org/openapitools/api/RestApplication.java +src/gen/java/org/openapitools/api/RestResourceRoot.java src/gen/java/org/openapitools/api/StoreApi.java src/gen/java/org/openapitools/api/UserApi.java src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/RestApplication.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/RestApplication.java index b98d35a4e9..7df2d0fe33 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/RestApplication.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/RestApplication.java @@ -3,7 +3,7 @@ package org.openapitools.api; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; -@ApplicationPath("/v2") +@ApplicationPath(RestResourceRoot.APPLICATION_PATH) public class RestApplication extends Application { } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/RestResourceRoot.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/RestResourceRoot.java new file mode 100644 index 0000000000..96ba6c8d8e --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/RestResourceRoot.java @@ -0,0 +1,5 @@ +package org.openapitools.api; + +public class RestResourceRoot { + public static final String APPLICATION_PATH = "/v2"; +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 1c8ec238b7..749ca0e02c 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesAnyType") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesAnyType extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 3d04c06342..3563c9cdc6 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesArray") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesArray extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 8a7da60731..0afb07939f 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesBoolean") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesBoolean extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index ad43546abf..753265e81e 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -22,24 +22,34 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesClass") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesClass implements Serializable { - - private @Valid Map mapString = new HashMap<>(); - private @Valid Map mapNumber = new HashMap<>(); - private @Valid Map mapInteger = new HashMap<>(); - private @Valid Map mapBoolean = new HashMap<>(); - private @Valid Map> mapArrayInteger = new HashMap<>(); - private @Valid Map> mapArrayAnytype = new HashMap<>(); - private @Valid Map> mapMapString = new HashMap<>(); - private @Valid Map> mapMapAnytype = new HashMap<>(); + private @Valid Map mapString = null; + private @Valid Map mapNumber = null; + private @Valid Map mapInteger = null; + private @Valid Map mapBoolean = null; + private @Valid Map> mapArrayInteger = null; + private @Valid Map> mapArrayAnytype = null; + private @Valid Map> mapMapString = null; + private @Valid Map> mapMapAnytype = null; private @Valid Object anytype1; private @Valid Object anytype2; private @Valid Object anytype3; protected AdditionalPropertiesClass(AdditionalPropertiesClassBuilder b) { - this.mapString = b.mapString;this.mapNumber = b.mapNumber;this.mapInteger = b.mapInteger;this.mapBoolean = b.mapBoolean;this.mapArrayInteger = b.mapArrayInteger;this.mapArrayAnytype = b.mapArrayAnytype;this.mapMapString = b.mapMapString;this.mapMapAnytype = b.mapMapAnytype;this.anytype1 = b.anytype1;this.anytype2 = b.anytype2;this.anytype3 = b.anytype3; + this.mapString = b.mapString; + this.mapNumber = b.mapNumber; + this.mapInteger = b.mapInteger; + this.mapBoolean = b.mapBoolean; + this.mapArrayInteger = b.mapArrayInteger; + this.mapArrayAnytype = b.mapArrayAnytype; + this.mapMapString = b.mapMapString; + this.mapMapAnytype = b.mapMapAnytype; + this.anytype1 = b.anytype1; + this.anytype2 = b.anytype2; + this.anytype3 = b.anytype3; } - public AdditionalPropertiesClass() { } + public AdditionalPropertiesClass() { + } /** **/ @@ -76,7 +86,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapNumber(Map mapNumber) { this.mapNumber = mapNumber; @@ -111,7 +121,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapInteger(Map mapInteger) { this.mapInteger = mapInteger; @@ -146,7 +156,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { this.mapBoolean = mapBoolean; @@ -181,7 +191,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapArrayInteger(Map> mapArrayInteger) { this.mapArrayInteger = mapArrayInteger; @@ -216,7 +226,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapArrayAnytype(Map> mapArrayAnytype) { this.mapArrayAnytype = mapArrayAnytype; @@ -251,7 +261,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapMapString(Map> mapMapString) { this.mapMapString = mapMapString; @@ -286,7 +296,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass mapMapAnytype(Map> mapMapAnytype) { this.mapMapAnytype = mapMapAnytype; @@ -321,7 +331,7 @@ public class AdditionalPropertiesClass implements Serializable { return this; } -/** + /** **/ public AdditionalPropertiesClass anytype1(Object anytype1) { this.anytype1 = anytype1; @@ -340,7 +350,7 @@ public class AdditionalPropertiesClass implements Serializable { this.anytype1 = anytype1; } -/** + /** **/ public AdditionalPropertiesClass anytype2(Object anytype2) { this.anytype2 = anytype2; @@ -359,7 +369,7 @@ public class AdditionalPropertiesClass implements Serializable { this.anytype2 = anytype2; } -/** + /** **/ public AdditionalPropertiesClass anytype3(Object anytype3) { this.anytype3 = anytype3; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index 4ed241faad..376aa5a7c6 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesInteger") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesInteger extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index c48bafb3b7..03cf9a126d 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesNumber") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesNumber extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index ed49983b82..b9fae3edf8 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesObject") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesObject extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index 2c596592d3..9790203702 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("AdditionalPropertiesString") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesString extends HashMap implements Serializable { - private @Valid String name; /** diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Animal.java index 1720d4815a..e046b586ac 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Animal.java @@ -27,15 +27,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Animal") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Animal implements Serializable { - private @Valid String className; private @Valid String color = "red"; protected Animal(AnimalBuilder b) { - this.className = b.className;this.color = b.color; + this.className = b.className; + this.color = b.color; } - public Animal() { } + public Animal() { + } /** **/ @@ -57,7 +58,7 @@ public class Animal implements Serializable { this.className = className; } -/** + /** **/ public Animal color(String color) { this.color = color; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 3bd8b0989c..1f47464d3c 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -21,14 +21,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ArrayOfArrayOfNumberOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ArrayOfArrayOfNumberOnly implements Serializable { - - private @Valid List> arrayArrayNumber = new ArrayList<>(); + private @Valid List> arrayArrayNumber = null; protected ArrayOfArrayOfNumberOnly(ArrayOfArrayOfNumberOnlyBuilder b) { - this.arrayArrayNumber = b.arrayArrayNumber; + this.arrayArrayNumber = b.arrayArrayNumber; } - public ArrayOfArrayOfNumberOnly() { } + public ArrayOfArrayOfNumberOnly() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 811cb2ac9b..bab3b72705 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -21,14 +21,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ArrayOfNumberOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ArrayOfNumberOnly implements Serializable { - - private @Valid List arrayNumber = new ArrayList<>(); + private @Valid List arrayNumber = null; protected ArrayOfNumberOnly(ArrayOfNumberOnlyBuilder b) { - this.arrayNumber = b.arrayNumber; + this.arrayNumber = b.arrayNumber; } - public ArrayOfNumberOnly() { } + public ArrayOfNumberOnly() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayTest.java index 74f1d41b2d..6ff8393ed0 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayTest.java @@ -21,16 +21,18 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ArrayTest") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ArrayTest implements Serializable { - - private @Valid List arrayOfString = new ArrayList<>(); - private @Valid List> arrayArrayOfInteger = new ArrayList<>(); - private @Valid List> arrayArrayOfModel = new ArrayList<>(); + private @Valid List arrayOfString = null; + private @Valid List> arrayArrayOfInteger = null; + private @Valid List> arrayArrayOfModel = null; protected ArrayTest(ArrayTestBuilder b) { - this.arrayOfString = b.arrayOfString;this.arrayArrayOfInteger = b.arrayArrayOfInteger;this.arrayArrayOfModel = b.arrayArrayOfModel; + this.arrayOfString = b.arrayOfString; + this.arrayArrayOfInteger = b.arrayArrayOfInteger; + this.arrayArrayOfModel = b.arrayArrayOfModel; } - public ArrayTest() { } + public ArrayTest() { + } /** **/ @@ -67,7 +69,7 @@ public class ArrayTest implements Serializable { return this; } -/** + /** **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; @@ -102,7 +104,7 @@ public class ArrayTest implements Serializable { return this; } -/** + /** **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCat.java index b07e748746..48dcefd8bd 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCat.java @@ -19,9 +19,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("BigCat") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class BigCat extends Cat implements Serializable { - - -public enum KindEnum { + public enum KindEnum { LIONS(String.valueOf("lions")), TIGERS(String.valueOf("tigers")), LEOPARDS(String.valueOf("leopards")), JAGUARS(String.valueOf("jaguars")); @@ -71,11 +69,12 @@ public enum KindEnum { private @Valid KindEnum kind; protected BigCat(BigCatBuilder b) { - super(b); - this.kind = b.kind; + super(b); + this.kind = b.kind; } - public BigCat() { } + public BigCat() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCatAllOf.java index 75ce8f65b6..0ba47d26cf 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -19,9 +19,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("BigCat_allOf") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class BigCatAllOf implements Serializable { - - -public enum KindEnum { + public enum KindEnum { LIONS(String.valueOf("lions")), TIGERS(String.valueOf("tigers")), LEOPARDS(String.valueOf("leopards")), JAGUARS(String.valueOf("jaguars")); @@ -71,10 +69,11 @@ public enum KindEnum { private @Valid KindEnum kind; protected BigCatAllOf(BigCatAllOfBuilder b) { - this.kind = b.kind; + this.kind = b.kind; } - public BigCatAllOf() { } + public BigCatAllOf() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Capitalization.java index 39eb032f53..3ce8aed585 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Capitalization.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Capitalization") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Capitalization implements Serializable { - private @Valid String smallCamel; private @Valid String capitalCamel; private @Valid String smallSnake; @@ -27,10 +26,16 @@ public class Capitalization implements Serializable { private @Valid String ATT_NAME; protected Capitalization(CapitalizationBuilder b) { - this.smallCamel = b.smallCamel;this.capitalCamel = b.capitalCamel;this.smallSnake = b.smallSnake;this.capitalSnake = b.capitalSnake;this.scAETHFlowPoints = b.scAETHFlowPoints;this.ATT_NAME = b.ATT_NAME; + this.smallCamel = b.smallCamel; + this.capitalCamel = b.capitalCamel; + this.smallSnake = b.smallSnake; + this.capitalSnake = b.capitalSnake; + this.scAETHFlowPoints = b.scAETHFlowPoints; + this.ATT_NAME = b.ATT_NAME; } - public Capitalization() { } + public Capitalization() { + } /** **/ @@ -51,7 +56,7 @@ public class Capitalization implements Serializable { this.smallCamel = smallCamel; } -/** + /** **/ public Capitalization capitalCamel(String capitalCamel) { this.capitalCamel = capitalCamel; @@ -70,7 +75,7 @@ public class Capitalization implements Serializable { this.capitalCamel = capitalCamel; } -/** + /** **/ public Capitalization smallSnake(String smallSnake) { this.smallSnake = smallSnake; @@ -89,7 +94,7 @@ public class Capitalization implements Serializable { this.smallSnake = smallSnake; } -/** + /** **/ public Capitalization capitalSnake(String capitalSnake) { this.capitalSnake = capitalSnake; @@ -108,7 +113,7 @@ public class Capitalization implements Serializable { this.capitalSnake = capitalSnake; } -/** + /** **/ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { this.scAETHFlowPoints = scAETHFlowPoints; @@ -127,7 +132,7 @@ public class Capitalization implements Serializable { this.scAETHFlowPoints = scAETHFlowPoints; } -/** + /** * Name of the pet **/ public Capitalization ATT_NAME(String ATT_NAME) { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Cat.java index 0030579b74..58cad6cc80 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Cat.java @@ -19,15 +19,15 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Cat") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Cat extends Animal implements Serializable { - private @Valid Boolean declawed; protected Cat(CatBuilder b) { - super(b); - this.declawed = b.declawed; + super(b); + this.declawed = b.declawed; } - public Cat() { } + public Cat() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/CatAllOf.java index 38e11b2b12..43aa9b39cd 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/CatAllOf.java @@ -19,14 +19,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Cat_allOf") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class CatAllOf implements Serializable { - private @Valid Boolean declawed; protected CatAllOf(CatAllOfBuilder b) { - this.declawed = b.declawed; + this.declawed = b.declawed; } - public CatAllOf() { } + public CatAllOf() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Category.java index 26f7194ece..24d73db153 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Category.java @@ -18,15 +18,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Category") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Category implements Serializable { - private @Valid Long id; private @Valid String name = "default-name"; protected Category(CategoryBuilder b) { - this.id = b.id;this.name = b.name; + this.id = b.id; + this.name = b.name; } - public Category() { } + public Category() { + } /** **/ @@ -47,7 +48,7 @@ public class Category implements Serializable { this.id = id; } -/** + /** **/ public Category name(String name) { this.name = name; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ClassModel.java index b509e5066b..d5d92b4dbc 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ClassModel.java @@ -20,14 +20,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ClassModel") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ClassModel implements Serializable { - private @Valid String propertyClass; protected ClassModel(ClassModelBuilder b) { - this.propertyClass = b.propertyClass; + this.propertyClass = b.propertyClass; } - public ClassModel() { } + public ClassModel() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Client.java index c29067e60e..899b633922 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Client.java @@ -18,14 +18,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Client") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Client implements Serializable { - private @Valid String client; protected Client(ClientBuilder b) { - this.client = b.client; + this.client = b.client; } - public Client() { } + public Client() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Dog.java index eec73be73b..cad870c8e4 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Dog.java @@ -19,15 +19,15 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Dog") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Dog extends Animal implements Serializable { - private @Valid String breed; protected Dog(DogBuilder b) { - super(b); - this.breed = b.breed; + super(b); + this.breed = b.breed; } - public Dog() { } + public Dog() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/DogAllOf.java index 3154e48fce..1034af7eb2 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/DogAllOf.java @@ -19,14 +19,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Dog_allOf") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class DogAllOf implements Serializable { - private @Valid String breed; protected DogAllOf(DogAllOfBuilder b) { - this.breed = b.breed; + this.breed = b.breed; } - public DogAllOf() { } + public DogAllOf() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumArrays.java index a913109dc6..73891aaba0 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumArrays.java @@ -20,9 +20,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("EnumArrays") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class EnumArrays implements Serializable { - - -public enum JustSymbolEnum { + public enum JustSymbolEnum { GREATER_THAN_OR_EQUAL_TO(String.valueOf(">=")), DOLLAR(String.valueOf("$")); @@ -70,8 +68,7 @@ public enum JustSymbolEnum { } private @Valid JustSymbolEnum justSymbol; - -public enum ArrayEnumEnum { + public enum ArrayEnumEnum { FISH(String.valueOf("fish")), CRAB(String.valueOf("crab")); @@ -118,13 +115,15 @@ public enum ArrayEnumEnum { } } - private @Valid List arrayEnum = new ArrayList<>(); + private @Valid List arrayEnum = null; protected EnumArrays(EnumArraysBuilder b) { - this.justSymbol = b.justSymbol;this.arrayEnum = b.arrayEnum; + this.justSymbol = b.justSymbol; + this.arrayEnum = b.arrayEnum; } - public EnumArrays() { } + public EnumArrays() { + } /** **/ @@ -145,7 +144,7 @@ public enum ArrayEnumEnum { this.justSymbol = justSymbol; } -/** + /** **/ public EnumArrays arrayEnum(List arrayEnum) { this.arrayEnum = arrayEnum; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumTest.java index ef6b27ca19..a5a94a0d35 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumTest.java @@ -20,9 +20,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Enum_Test") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class EnumTest implements Serializable { - - -public enum EnumStringEnum { + public enum EnumStringEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); @@ -70,8 +68,7 @@ public enum EnumStringEnum { } private @Valid EnumStringEnum enumString; - -public enum EnumStringRequiredEnum { + public enum EnumStringRequiredEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); @@ -119,8 +116,7 @@ public enum EnumStringRequiredEnum { } private @Valid EnumStringRequiredEnum enumStringRequired; - -public enum EnumIntegerEnum { + public enum EnumIntegerEnum { NUMBER_1(Integer.valueOf(1)), NUMBER_MINUS_1(Integer.valueOf(-1)); @@ -168,8 +164,7 @@ public enum EnumIntegerEnum { } private @Valid EnumIntegerEnum enumInteger; - -public enum EnumNumberEnum { + public enum EnumNumberEnum { NUMBER_1_DOT_1(Double.valueOf(1.1)), NUMBER_MINUS_1_DOT_2(Double.valueOf(-1.2)); @@ -220,10 +215,15 @@ public enum EnumNumberEnum { private @Valid OuterEnum outerEnum; protected EnumTest(EnumTestBuilder b) { - this.enumString = b.enumString;this.enumStringRequired = b.enumStringRequired;this.enumInteger = b.enumInteger;this.enumNumber = b.enumNumber;this.outerEnum = b.outerEnum; + this.enumString = b.enumString; + this.enumStringRequired = b.enumStringRequired; + this.enumInteger = b.enumInteger; + this.enumNumber = b.enumNumber; + this.outerEnum = b.outerEnum; } - public EnumTest() { } + public EnumTest() { + } /** **/ @@ -244,7 +244,7 @@ public enum EnumNumberEnum { this.enumString = enumString; } -/** + /** **/ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { this.enumStringRequired = enumStringRequired; @@ -264,7 +264,7 @@ public enum EnumNumberEnum { this.enumStringRequired = enumStringRequired; } -/** + /** **/ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; @@ -283,7 +283,7 @@ public enum EnumNumberEnum { this.enumInteger = enumInteger; } -/** + /** **/ public EnumTest enumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; @@ -302,7 +302,7 @@ public enum EnumNumberEnum { this.enumNumber = enumNumber; } -/** + /** **/ public EnumTest outerEnum(OuterEnum outerEnum) { this.outerEnum = outerEnum; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 9e4ef78f38..0a79adf784 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -21,15 +21,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("FileSchemaTestClass") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FileSchemaTestClass implements Serializable { - private @Valid ModelFile _file; - private @Valid List files = new ArrayList<>(); + private @Valid List files = null; protected FileSchemaTestClass(FileSchemaTestClassBuilder b) { - this._file = b._file;this.files = b.files; + this._file = b._file; + this.files = b.files; } - public FileSchemaTestClass() { } + public FileSchemaTestClass() { + } /** **/ @@ -50,7 +51,7 @@ public class FileSchemaTestClass implements Serializable { this._file = _file; } -/** + /** **/ public FileSchemaTestClass files(List files) { this.files = files; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FormatTest.java index c99d0cbba8..f64ed7b22c 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FormatTest.java @@ -25,7 +25,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("format_test") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FormatTest implements Serializable { - private @Valid Integer integer; private @Valid Integer int32; private @Valid Long int64; @@ -42,10 +41,24 @@ public class FormatTest implements Serializable { private @Valid BigDecimal bigDecimal; protected FormatTest(FormatTestBuilder b) { - this.integer = b.integer;this.int32 = b.int32;this.int64 = b.int64;this.number = b.number;this._float = b._float;this._double = b._double;this.string = b.string;this._byte = b._byte;this.binary = b.binary;this.date = b.date;this.dateTime = b.dateTime;this.uuid = b.uuid;this.password = b.password;this.bigDecimal = b.bigDecimal; + this.integer = b.integer; + this.int32 = b.int32; + this.int64 = b.int64; + this.number = b.number; + this._float = b._float; + this._double = b._double; + this.string = b.string; + this._byte = b._byte; + this.binary = b.binary; + this.date = b.date; + this.dateTime = b.dateTime; + this.uuid = b.uuid; + this.password = b.password; + this.bigDecimal = b.bigDecimal; } - public FormatTest() { } + public FormatTest() { + } /** * minimum: 10 @@ -68,7 +81,7 @@ public class FormatTest implements Serializable { this.integer = integer; } -/** + /** * minimum: 20 * maximum: 200 **/ @@ -89,7 +102,7 @@ public class FormatTest implements Serializable { this.int32 = int32; } -/** + /** **/ public FormatTest int64(Long int64) { this.int64 = int64; @@ -108,7 +121,7 @@ public class FormatTest implements Serializable { this.int64 = int64; } -/** + /** * minimum: 32.1 * maximum: 543.2 **/ @@ -130,7 +143,7 @@ public class FormatTest implements Serializable { this.number = number; } -/** + /** * minimum: 54.3 * maximum: 987.6 **/ @@ -151,7 +164,7 @@ public class FormatTest implements Serializable { this._float = _float; } -/** + /** * minimum: 67.8 * maximum: 123.4 **/ @@ -172,7 +185,7 @@ public class FormatTest implements Serializable { this._double = _double; } -/** + /** **/ public FormatTest string(String string) { this.string = string; @@ -191,7 +204,7 @@ public class FormatTest implements Serializable { this.string = string; } -/** + /** **/ public FormatTest _byte(byte[] _byte) { this._byte = _byte; @@ -211,7 +224,7 @@ public class FormatTest implements Serializable { this._byte = _byte; } -/** + /** **/ public FormatTest binary(File binary) { this.binary = binary; @@ -230,7 +243,7 @@ public class FormatTest implements Serializable { this.binary = binary; } -/** + /** **/ public FormatTest date(LocalDate date) { this.date = date; @@ -250,7 +263,7 @@ public class FormatTest implements Serializable { this.date = date; } -/** + /** **/ public FormatTest dateTime(Date dateTime) { this.dateTime = dateTime; @@ -269,7 +282,7 @@ public class FormatTest implements Serializable { this.dateTime = dateTime; } -/** + /** **/ public FormatTest uuid(UUID uuid) { this.uuid = uuid; @@ -288,7 +301,7 @@ public class FormatTest implements Serializable { this.uuid = uuid; } -/** + /** **/ public FormatTest password(String password) { this.password = password; @@ -308,7 +321,7 @@ public class FormatTest implements Serializable { this.password = password; } -/** + /** **/ public FormatTest bigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index ab5b5e4add..e63688b8ce 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -19,15 +19,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("hasOnlyReadOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class HasOnlyReadOnly implements Serializable { - private @Valid String bar; private @Valid String foo; protected HasOnlyReadOnly(HasOnlyReadOnlyBuilder b) { - this.bar = b.bar;this.foo = b.foo; + this.bar = b.bar; + this.foo = b.foo; } - public HasOnlyReadOnly() { } + public HasOnlyReadOnly() { + } /** **/ @@ -48,7 +49,7 @@ public class HasOnlyReadOnly implements Serializable { this.bar = bar; } -/** + /** **/ public HasOnlyReadOnly foo(String foo) { this.foo = foo; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MapTest.java index 969545816f..d857d3073c 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MapTest.java @@ -20,10 +20,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("MapTest") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class MapTest implements Serializable { - - private @Valid Map> mapMapOfString = new HashMap<>(); - -public enum InnerEnum { + private @Valid Map> mapMapOfString = null; + public enum InnerEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")); @@ -70,15 +68,19 @@ public enum InnerEnum { } } - private @Valid Map mapOfEnumString = new HashMap<>(); - private @Valid Map directMap = new HashMap<>(); - private @Valid Map indirectMap = new HashMap<>(); + private @Valid Map mapOfEnumString = null; + private @Valid Map directMap = null; + private @Valid Map indirectMap = null; protected MapTest(MapTestBuilder b) { - this.mapMapOfString = b.mapMapOfString;this.mapOfEnumString = b.mapOfEnumString;this.directMap = b.directMap;this.indirectMap = b.indirectMap; + this.mapMapOfString = b.mapMapOfString; + this.mapOfEnumString = b.mapOfEnumString; + this.directMap = b.directMap; + this.indirectMap = b.indirectMap; } - public MapTest() { } + public MapTest() { + } /** **/ @@ -115,7 +117,7 @@ public enum InnerEnum { return this; } -/** + /** **/ public MapTest mapOfEnumString(Map mapOfEnumString) { this.mapOfEnumString = mapOfEnumString; @@ -150,7 +152,7 @@ public enum InnerEnum { return this; } -/** + /** **/ public MapTest directMap(Map directMap) { this.directMap = directMap; @@ -185,7 +187,7 @@ public enum InnerEnum { return this; } -/** + /** **/ public MapTest indirectMap(Map indirectMap) { this.indirectMap = indirectMap; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index c0f9e0701f..3237d6059a 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -23,16 +23,18 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("MixedPropertiesAndAdditionalPropertiesClass") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class MixedPropertiesAndAdditionalPropertiesClass implements Serializable { - private @Valid UUID uuid; private @Valid Date dateTime; - private @Valid Map map = new HashMap<>(); + private @Valid Map map = null; protected MixedPropertiesAndAdditionalPropertiesClass(MixedPropertiesAndAdditionalPropertiesClassBuilder b) { - this.uuid = b.uuid;this.dateTime = b.dateTime;this.map = b.map; + this.uuid = b.uuid; + this.dateTime = b.dateTime; + this.map = b.map; } - public MixedPropertiesAndAdditionalPropertiesClass() { } + public MixedPropertiesAndAdditionalPropertiesClass() { + } /** **/ @@ -53,7 +55,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl this.uuid = uuid; } -/** + /** **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { this.dateTime = dateTime; @@ -72,7 +74,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializabl this.dateTime = dateTime; } -/** + /** **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Model200Response.java index 2bfa6086e8..61eabc7e50 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Model200Response.java @@ -21,15 +21,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("200_response") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Model200Response implements Serializable { - private @Valid Integer name; private @Valid String propertyClass; protected Model200Response(Model200ResponseBuilder b) { - this.name = b.name;this.propertyClass = b.propertyClass; + this.name = b.name; + this.propertyClass = b.propertyClass; } - public Model200Response() { } + public Model200Response() { + } /** **/ @@ -50,7 +51,7 @@ public class Model200Response implements Serializable { this.name = name; } -/** + /** **/ public Model200Response propertyClass(String propertyClass) { this.propertyClass = propertyClass; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelApiResponse.java index c86e5ffa83..2d7b88df51 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -19,16 +19,18 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ApiResponse") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ModelApiResponse implements Serializable { - private @Valid Integer code; private @Valid String type; private @Valid String message; protected ModelApiResponse(ModelApiResponseBuilder b) { - this.code = b.code;this.type = b.type;this.message = b.message; + this.code = b.code; + this.type = b.type; + this.message = b.message; } - public ModelApiResponse() { } + public ModelApiResponse() { + } /** **/ @@ -49,7 +51,7 @@ public class ModelApiResponse implements Serializable { this.code = code; } -/** + /** **/ public ModelApiResponse type(String type) { this.type = type; @@ -68,7 +70,7 @@ public class ModelApiResponse implements Serializable { this.type = type; } -/** + /** **/ public ModelApiResponse message(String message) { this.message = message; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelFile.java index 6099723d1c..9ed686d7c2 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelFile.java @@ -21,14 +21,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("File") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ModelFile implements Serializable { - private @Valid String sourceURI; protected ModelFile(ModelFileBuilder b) { - this.sourceURI = b.sourceURI; + this.sourceURI = b.sourceURI; } - public ModelFile() { } + public ModelFile() { + } /** * Test capitalization diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelList.java index f61cdb8747..697bcd03cb 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelList.java @@ -19,14 +19,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("List") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ModelList implements Serializable { - private @Valid String _123list; protected ModelList(ModelListBuilder b) { - this._123list = b._123list; + this._123list = b._123list; } - public ModelList() { } + public ModelList() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelReturn.java index 3ddde593b6..54423218e1 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ModelReturn.java @@ -21,14 +21,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Return") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ModelReturn implements Serializable { - private @Valid Integer _return; protected ModelReturn(ModelReturnBuilder b) { - this._return = b._return; + this._return = b._return; } - public ModelReturn() { } + public ModelReturn() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Name.java index 40c1501bf0..6f4930623c 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Name.java @@ -20,17 +20,20 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Name") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Name implements Serializable { - private @Valid Integer name; private @Valid Integer snakeCase; private @Valid String property; private @Valid Integer _123number; protected Name(NameBuilder b) { - this.name = b.name;this.snakeCase = b.snakeCase;this.property = b.property;this._123number = b._123number; + this.name = b.name; + this.snakeCase = b.snakeCase; + this.property = b.property; + this._123number = b._123number; } - public Name() { } + public Name() { + } /** **/ @@ -52,7 +55,7 @@ public class Name implements Serializable { this.name = name; } -/** + /** **/ public Name snakeCase(Integer snakeCase) { this.snakeCase = snakeCase; @@ -71,7 +74,7 @@ public class Name implements Serializable { this.snakeCase = snakeCase; } -/** + /** **/ public Name property(String property) { this.property = property; @@ -90,7 +93,7 @@ public class Name implements Serializable { this.property = property; } -/** + /** **/ public Name _123number(Integer _123number) { this._123number = _123number; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/NumberOnly.java index 00e2e3dde8..3dae706371 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/NumberOnly.java @@ -19,14 +19,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("NumberOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class NumberOnly implements Serializable { - private @Valid BigDecimal justNumber; protected NumberOnly(NumberOnlyBuilder b) { - this.justNumber = b.justNumber; + this.justNumber = b.justNumber; } - public NumberOnly() { } + public NumberOnly() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Order.java index a4f4bb6520..4df5548660 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Order.java @@ -19,13 +19,11 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Order") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Order implements Serializable { - private @Valid Long id; private @Valid Long petId; private @Valid Integer quantity; private @Valid Date shipDate; - -public enum StatusEnum { + public enum StatusEnum { PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); @@ -76,10 +74,16 @@ public enum StatusEnum { private @Valid Boolean complete = false; protected Order(OrderBuilder b) { - this.id = b.id;this.petId = b.petId;this.quantity = b.quantity;this.shipDate = b.shipDate;this.status = b.status;this.complete = b.complete; + this.id = b.id; + this.petId = b.petId; + this.quantity = b.quantity; + this.shipDate = b.shipDate; + this.status = b.status; + this.complete = b.complete; } - public Order() { } + public Order() { + } /** **/ @@ -100,7 +104,7 @@ public enum StatusEnum { this.id = id; } -/** + /** **/ public Order petId(Long petId) { this.petId = petId; @@ -119,7 +123,7 @@ public enum StatusEnum { this.petId = petId; } -/** + /** **/ public Order quantity(Integer quantity) { this.quantity = quantity; @@ -138,7 +142,7 @@ public enum StatusEnum { this.quantity = quantity; } -/** + /** **/ public Order shipDate(Date shipDate) { this.shipDate = shipDate; @@ -157,7 +161,7 @@ public enum StatusEnum { this.shipDate = shipDate; } -/** + /** * Order Status **/ public Order status(StatusEnum status) { @@ -177,7 +181,7 @@ public enum StatusEnum { this.status = status; } -/** + /** **/ public Order complete(Boolean complete) { this.complete = complete; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/OuterComposite.java index 5907ce0e44..c9a4b090f8 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/OuterComposite.java @@ -19,16 +19,18 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("OuterComposite") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class OuterComposite implements Serializable { - private @Valid BigDecimal myNumber; private @Valid String myString; private @Valid Boolean myBoolean; protected OuterComposite(OuterCompositeBuilder b) { - this.myNumber = b.myNumber;this.myString = b.myString;this.myBoolean = b.myBoolean; + this.myNumber = b.myNumber; + this.myString = b.myString; + this.myBoolean = b.myBoolean; } - public OuterComposite() { } + public OuterComposite() { + } /** **/ @@ -49,7 +51,7 @@ public class OuterComposite implements Serializable { this.myNumber = myNumber; } -/** + /** **/ public OuterComposite myString(String myString) { this.myString = myString; @@ -68,7 +70,7 @@ public class OuterComposite implements Serializable { this.myString = myString; } -/** + /** **/ public OuterComposite myBoolean(Boolean myBoolean) { this.myBoolean = myBoolean; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Pet.java index e4fbfaeef1..c91f0b0ac9 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Pet.java @@ -25,14 +25,12 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Pet") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Pet implements Serializable { - private @Valid Long id; private @Valid Category category; private @Valid String name; private @Valid Set photoUrls = new LinkedHashSet<>(); - private @Valid List tags = new ArrayList<>(); - -public enum StatusEnum { + private @Valid List tags = null; + public enum StatusEnum { AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); @@ -82,10 +80,16 @@ public enum StatusEnum { private @Valid StatusEnum status; protected Pet(PetBuilder b) { - this.id = b.id;this.category = b.category;this.name = b.name;this.photoUrls = b.photoUrls;this.tags = b.tags;this.status = b.status; + this.id = b.id; + this.category = b.category; + this.name = b.name; + this.photoUrls = b.photoUrls; + this.tags = b.tags; + this.status = b.status; } - public Pet() { } + public Pet() { + } /** **/ @@ -106,7 +110,7 @@ public enum StatusEnum { this.id = id; } -/** + /** **/ public Pet category(Category category) { this.category = category; @@ -125,7 +129,7 @@ public enum StatusEnum { this.category = category; } -/** + /** **/ public Pet name(String name) { this.name = name; @@ -145,7 +149,7 @@ public enum StatusEnum { this.name = name; } -/** + /** **/ public Pet photoUrls(Set photoUrls) { this.photoUrls = photoUrls; @@ -182,7 +186,7 @@ public enum StatusEnum { return this; } -/** + /** **/ public Pet tags(List tags) { this.tags = tags; @@ -217,7 +221,7 @@ public enum StatusEnum { return this; } -/** + /** * pet status in the store **/ public Pet status(StatusEnum status) { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index 8f56d18eb4..c5373629fa 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -18,15 +18,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("ReadOnlyFirst") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ReadOnlyFirst implements Serializable { - private @Valid String bar; private @Valid String baz; protected ReadOnlyFirst(ReadOnlyFirstBuilder b) { - this.bar = b.bar;this.baz = b.baz; + this.bar = b.bar; + this.baz = b.baz; } - public ReadOnlyFirst() { } + public ReadOnlyFirst() { + } /** **/ @@ -47,7 +48,7 @@ public class ReadOnlyFirst implements Serializable { this.bar = bar; } -/** + /** **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/SpecialModelName.java index bea2aa5419..0faf305fcf 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -19,14 +19,14 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("$special[model.name]") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class SpecialModelName implements Serializable { - private @Valid Long $specialPropertyName; protected SpecialModelName(SpecialModelNameBuilder b) { - this.$specialPropertyName = b.$specialPropertyName; + this.$specialPropertyName = b.$specialPropertyName; } - public SpecialModelName() { } + public SpecialModelName() { + } /** **/ diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Tag.java index 750c151425..c29fb28af0 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Tag.java @@ -18,15 +18,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("Tag") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class Tag implements Serializable { - private @Valid Long id; private @Valid String name; protected Tag(TagBuilder b) { - this.id = b.id;this.name = b.name; + this.id = b.id; + this.name = b.name; } - public Tag() { } + public Tag() { + } /** **/ @@ -47,7 +48,7 @@ public class Tag implements Serializable { this.id = id; } -/** + /** **/ public Tag name(String name) { this.name = name; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 354098bce7..a8a293b2e0 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("TypeHolderDefault") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class TypeHolderDefault implements Serializable { - private @Valid String stringItem = "what"; private @Valid BigDecimal numberItem; private @Valid Integer integerItem; @@ -29,10 +28,15 @@ public class TypeHolderDefault implements Serializable { private @Valid List arrayItem = new ArrayList<>(); protected TypeHolderDefault(TypeHolderDefaultBuilder b) { - this.stringItem = b.stringItem;this.numberItem = b.numberItem;this.integerItem = b.integerItem;this.boolItem = b.boolItem;this.arrayItem = b.arrayItem; + this.stringItem = b.stringItem; + this.numberItem = b.numberItem; + this.integerItem = b.integerItem; + this.boolItem = b.boolItem; + this.arrayItem = b.arrayItem; } - public TypeHolderDefault() { } + public TypeHolderDefault() { + } /** **/ @@ -54,7 +58,7 @@ public class TypeHolderDefault implements Serializable { this.stringItem = stringItem; } -/** + /** **/ public TypeHolderDefault numberItem(BigDecimal numberItem) { this.numberItem = numberItem; @@ -74,7 +78,7 @@ public class TypeHolderDefault implements Serializable { this.numberItem = numberItem; } -/** + /** **/ public TypeHolderDefault integerItem(Integer integerItem) { this.integerItem = integerItem; @@ -94,7 +98,7 @@ public class TypeHolderDefault implements Serializable { this.integerItem = integerItem; } -/** + /** **/ public TypeHolderDefault boolItem(Boolean boolItem) { this.boolItem = boolItem; @@ -114,7 +118,7 @@ public class TypeHolderDefault implements Serializable { this.boolItem = boolItem; } -/** + /** **/ public TypeHolderDefault arrayItem(List arrayItem) { this.arrayItem = arrayItem; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/TypeHolderExample.java index 03b6728e0e..2b48909d9e 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("TypeHolderExample") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class TypeHolderExample implements Serializable { - private @Valid String stringItem; private @Valid BigDecimal numberItem; private @Valid Float floatItem; @@ -30,10 +29,16 @@ public class TypeHolderExample implements Serializable { private @Valid List arrayItem = new ArrayList<>(); protected TypeHolderExample(TypeHolderExampleBuilder b) { - this.stringItem = b.stringItem;this.numberItem = b.numberItem;this.floatItem = b.floatItem;this.integerItem = b.integerItem;this.boolItem = b.boolItem;this.arrayItem = b.arrayItem; + this.stringItem = b.stringItem; + this.numberItem = b.numberItem; + this.floatItem = b.floatItem; + this.integerItem = b.integerItem; + this.boolItem = b.boolItem; + this.arrayItem = b.arrayItem; } - public TypeHolderExample() { } + public TypeHolderExample() { + } /** **/ @@ -55,7 +60,7 @@ public class TypeHolderExample implements Serializable { this.stringItem = stringItem; } -/** + /** **/ public TypeHolderExample numberItem(BigDecimal numberItem) { this.numberItem = numberItem; @@ -75,7 +80,7 @@ public class TypeHolderExample implements Serializable { this.numberItem = numberItem; } -/** + /** **/ public TypeHolderExample floatItem(Float floatItem) { this.floatItem = floatItem; @@ -95,7 +100,7 @@ public class TypeHolderExample implements Serializable { this.floatItem = floatItem; } -/** + /** **/ public TypeHolderExample integerItem(Integer integerItem) { this.integerItem = integerItem; @@ -115,7 +120,7 @@ public class TypeHolderExample implements Serializable { this.integerItem = integerItem; } -/** + /** **/ public TypeHolderExample boolItem(Boolean boolItem) { this.boolItem = boolItem; @@ -135,7 +140,7 @@ public class TypeHolderExample implements Serializable { this.boolItem = boolItem; } -/** + /** **/ public TypeHolderExample arrayItem(List arrayItem) { this.arrayItem = arrayItem; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/User.java index 0ec607846e..27ac9ad24d 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/User.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("User") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class User implements Serializable { - private @Valid Long id; private @Valid String username; private @Valid String firstName; @@ -29,10 +28,18 @@ public class User implements Serializable { private @Valid Integer userStatus; protected User(UserBuilder b) { - this.id = b.id;this.username = b.username;this.firstName = b.firstName;this.lastName = b.lastName;this.email = b.email;this.password = b.password;this.phone = b.phone;this.userStatus = b.userStatus; + this.id = b.id; + this.username = b.username; + this.firstName = b.firstName; + this.lastName = b.lastName; + this.email = b.email; + this.password = b.password; + this.phone = b.phone; + this.userStatus = b.userStatus; } - public User() { } + public User() { + } /** **/ @@ -53,7 +60,7 @@ public class User implements Serializable { this.id = id; } -/** + /** **/ public User username(String username) { this.username = username; @@ -72,7 +79,7 @@ public class User implements Serializable { this.username = username; } -/** + /** **/ public User firstName(String firstName) { this.firstName = firstName; @@ -91,7 +98,7 @@ public class User implements Serializable { this.firstName = firstName; } -/** + /** **/ public User lastName(String lastName) { this.lastName = lastName; @@ -110,7 +117,7 @@ public class User implements Serializable { this.lastName = lastName; } -/** + /** **/ public User email(String email) { this.email = email; @@ -129,7 +136,7 @@ public class User implements Serializable { this.email = email; } -/** + /** **/ public User password(String password) { this.password = password; @@ -148,7 +155,7 @@ public class User implements Serializable { this.password = password; } -/** + /** **/ public User phone(String phone) { this.phone = phone; @@ -167,7 +174,7 @@ public class User implements Serializable { this.phone = phone; } -/** + /** * User Status **/ public User userStatus(Integer userStatus) { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/XmlItem.java index 8923f15e11..a3c4378d80 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/XmlItem.java @@ -21,42 +21,70 @@ import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("XmlItem") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class XmlItem implements Serializable { - private @Valid String attributeString; private @Valid BigDecimal attributeNumber; private @Valid Integer attributeInteger; private @Valid Boolean attributeBoolean; - private @Valid List wrappedArray = new ArrayList<>(); + private @Valid List wrappedArray = null; private @Valid String nameString; private @Valid BigDecimal nameNumber; private @Valid Integer nameInteger; private @Valid Boolean nameBoolean; - private @Valid List nameArray = new ArrayList<>(); - private @Valid List nameWrappedArray = new ArrayList<>(); + private @Valid List nameArray = null; + private @Valid List nameWrappedArray = null; private @Valid String prefixString; private @Valid BigDecimal prefixNumber; private @Valid Integer prefixInteger; private @Valid Boolean prefixBoolean; - private @Valid List prefixArray = new ArrayList<>(); - private @Valid List prefixWrappedArray = new ArrayList<>(); + private @Valid List prefixArray = null; + private @Valid List prefixWrappedArray = null; private @Valid String namespaceString; private @Valid BigDecimal namespaceNumber; private @Valid Integer namespaceInteger; private @Valid Boolean namespaceBoolean; - private @Valid List namespaceArray = new ArrayList<>(); - private @Valid List namespaceWrappedArray = new ArrayList<>(); + private @Valid List namespaceArray = null; + private @Valid List namespaceWrappedArray = null; private @Valid String prefixNsString; private @Valid BigDecimal prefixNsNumber; private @Valid Integer prefixNsInteger; private @Valid Boolean prefixNsBoolean; - private @Valid List prefixNsArray = new ArrayList<>(); - private @Valid List prefixNsWrappedArray = new ArrayList<>(); + private @Valid List prefixNsArray = null; + private @Valid List prefixNsWrappedArray = null; protected XmlItem(XmlItemBuilder b) { - this.attributeString = b.attributeString;this.attributeNumber = b.attributeNumber;this.attributeInteger = b.attributeInteger;this.attributeBoolean = b.attributeBoolean;this.wrappedArray = b.wrappedArray;this.nameString = b.nameString;this.nameNumber = b.nameNumber;this.nameInteger = b.nameInteger;this.nameBoolean = b.nameBoolean;this.nameArray = b.nameArray;this.nameWrappedArray = b.nameWrappedArray;this.prefixString = b.prefixString;this.prefixNumber = b.prefixNumber;this.prefixInteger = b.prefixInteger;this.prefixBoolean = b.prefixBoolean;this.prefixArray = b.prefixArray;this.prefixWrappedArray = b.prefixWrappedArray;this.namespaceString = b.namespaceString;this.namespaceNumber = b.namespaceNumber;this.namespaceInteger = b.namespaceInteger;this.namespaceBoolean = b.namespaceBoolean;this.namespaceArray = b.namespaceArray;this.namespaceWrappedArray = b.namespaceWrappedArray;this.prefixNsString = b.prefixNsString;this.prefixNsNumber = b.prefixNsNumber;this.prefixNsInteger = b.prefixNsInteger;this.prefixNsBoolean = b.prefixNsBoolean;this.prefixNsArray = b.prefixNsArray;this.prefixNsWrappedArray = b.prefixNsWrappedArray; + this.attributeString = b.attributeString; + this.attributeNumber = b.attributeNumber; + this.attributeInteger = b.attributeInteger; + this.attributeBoolean = b.attributeBoolean; + this.wrappedArray = b.wrappedArray; + this.nameString = b.nameString; + this.nameNumber = b.nameNumber; + this.nameInteger = b.nameInteger; + this.nameBoolean = b.nameBoolean; + this.nameArray = b.nameArray; + this.nameWrappedArray = b.nameWrappedArray; + this.prefixString = b.prefixString; + this.prefixNumber = b.prefixNumber; + this.prefixInteger = b.prefixInteger; + this.prefixBoolean = b.prefixBoolean; + this.prefixArray = b.prefixArray; + this.prefixWrappedArray = b.prefixWrappedArray; + this.namespaceString = b.namespaceString; + this.namespaceNumber = b.namespaceNumber; + this.namespaceInteger = b.namespaceInteger; + this.namespaceBoolean = b.namespaceBoolean; + this.namespaceArray = b.namespaceArray; + this.namespaceWrappedArray = b.namespaceWrappedArray; + this.prefixNsString = b.prefixNsString; + this.prefixNsNumber = b.prefixNsNumber; + this.prefixNsInteger = b.prefixNsInteger; + this.prefixNsBoolean = b.prefixNsBoolean; + this.prefixNsArray = b.prefixNsArray; + this.prefixNsWrappedArray = b.prefixNsWrappedArray; } - public XmlItem() { } + public XmlItem() { + } /** **/ @@ -77,7 +105,7 @@ public class XmlItem implements Serializable { this.attributeString = attributeString; } -/** + /** **/ public XmlItem attributeNumber(BigDecimal attributeNumber) { this.attributeNumber = attributeNumber; @@ -96,7 +124,7 @@ public class XmlItem implements Serializable { this.attributeNumber = attributeNumber; } -/** + /** **/ public XmlItem attributeInteger(Integer attributeInteger) { this.attributeInteger = attributeInteger; @@ -115,7 +143,7 @@ public class XmlItem implements Serializable { this.attributeInteger = attributeInteger; } -/** + /** **/ public XmlItem attributeBoolean(Boolean attributeBoolean) { this.attributeBoolean = attributeBoolean; @@ -134,7 +162,7 @@ public class XmlItem implements Serializable { this.attributeBoolean = attributeBoolean; } -/** + /** **/ public XmlItem wrappedArray(List wrappedArray) { this.wrappedArray = wrappedArray; @@ -169,7 +197,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem nameString(String nameString) { this.nameString = nameString; @@ -188,7 +216,7 @@ public class XmlItem implements Serializable { this.nameString = nameString; } -/** + /** **/ public XmlItem nameNumber(BigDecimal nameNumber) { this.nameNumber = nameNumber; @@ -207,7 +235,7 @@ public class XmlItem implements Serializable { this.nameNumber = nameNumber; } -/** + /** **/ public XmlItem nameInteger(Integer nameInteger) { this.nameInteger = nameInteger; @@ -226,7 +254,7 @@ public class XmlItem implements Serializable { this.nameInteger = nameInteger; } -/** + /** **/ public XmlItem nameBoolean(Boolean nameBoolean) { this.nameBoolean = nameBoolean; @@ -245,7 +273,7 @@ public class XmlItem implements Serializable { this.nameBoolean = nameBoolean; } -/** + /** **/ public XmlItem nameArray(List nameArray) { this.nameArray = nameArray; @@ -280,7 +308,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem nameWrappedArray(List nameWrappedArray) { this.nameWrappedArray = nameWrappedArray; @@ -315,7 +343,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem prefixString(String prefixString) { this.prefixString = prefixString; @@ -334,7 +362,7 @@ public class XmlItem implements Serializable { this.prefixString = prefixString; } -/** + /** **/ public XmlItem prefixNumber(BigDecimal prefixNumber) { this.prefixNumber = prefixNumber; @@ -353,7 +381,7 @@ public class XmlItem implements Serializable { this.prefixNumber = prefixNumber; } -/** + /** **/ public XmlItem prefixInteger(Integer prefixInteger) { this.prefixInteger = prefixInteger; @@ -372,7 +400,7 @@ public class XmlItem implements Serializable { this.prefixInteger = prefixInteger; } -/** + /** **/ public XmlItem prefixBoolean(Boolean prefixBoolean) { this.prefixBoolean = prefixBoolean; @@ -391,7 +419,7 @@ public class XmlItem implements Serializable { this.prefixBoolean = prefixBoolean; } -/** + /** **/ public XmlItem prefixArray(List prefixArray) { this.prefixArray = prefixArray; @@ -426,7 +454,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem prefixWrappedArray(List prefixWrappedArray) { this.prefixWrappedArray = prefixWrappedArray; @@ -461,7 +489,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem namespaceString(String namespaceString) { this.namespaceString = namespaceString; @@ -480,7 +508,7 @@ public class XmlItem implements Serializable { this.namespaceString = namespaceString; } -/** + /** **/ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { this.namespaceNumber = namespaceNumber; @@ -499,7 +527,7 @@ public class XmlItem implements Serializable { this.namespaceNumber = namespaceNumber; } -/** + /** **/ public XmlItem namespaceInteger(Integer namespaceInteger) { this.namespaceInteger = namespaceInteger; @@ -518,7 +546,7 @@ public class XmlItem implements Serializable { this.namespaceInteger = namespaceInteger; } -/** + /** **/ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { this.namespaceBoolean = namespaceBoolean; @@ -537,7 +565,7 @@ public class XmlItem implements Serializable { this.namespaceBoolean = namespaceBoolean; } -/** + /** **/ public XmlItem namespaceArray(List namespaceArray) { this.namespaceArray = namespaceArray; @@ -572,7 +600,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { this.namespaceWrappedArray = namespaceWrappedArray; @@ -607,7 +635,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem prefixNsString(String prefixNsString) { this.prefixNsString = prefixNsString; @@ -626,7 +654,7 @@ public class XmlItem implements Serializable { this.prefixNsString = prefixNsString; } -/** + /** **/ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { this.prefixNsNumber = prefixNsNumber; @@ -645,7 +673,7 @@ public class XmlItem implements Serializable { this.prefixNsNumber = prefixNsNumber; } -/** + /** **/ public XmlItem prefixNsInteger(Integer prefixNsInteger) { this.prefixNsInteger = prefixNsInteger; @@ -664,7 +692,7 @@ public class XmlItem implements Serializable { this.prefixNsInteger = prefixNsInteger; } -/** + /** **/ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { this.prefixNsBoolean = prefixNsBoolean; @@ -683,7 +711,7 @@ public class XmlItem implements Serializable { this.prefixNsBoolean = prefixNsBoolean; } -/** + /** **/ public XmlItem prefixNsArray(List prefixNsArray) { this.prefixNsArray = prefixNsArray; @@ -718,7 +746,7 @@ public class XmlItem implements Serializable { return this; } -/** + /** **/ public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { this.prefixNsWrappedArray = prefixNsWrappedArray; diff --git a/samples/server/petstore/jaxrs-spec/src/main/openapi/openapi.yaml b/samples/server/petstore/jaxrs-spec/src/main/openapi/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/openapi/openapi.yaml +++ b/samples/server/petstore/jaxrs-spec/src/main/openapi/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/php-laravel/lib/app/Models/AllOfWithSingleRef.php b/samples/server/petstore/php-laravel/lib/app/Models/AllOfWithSingleRef.php index 24ce4ab5c8..90a2bca8d5 100644 --- a/samples/server/petstore/php-laravel/lib/app/Models/AllOfWithSingleRef.php +++ b/samples/server/petstore/php-laravel/lib/app/Models/AllOfWithSingleRef.php @@ -12,7 +12,7 @@ class AllOfWithSingleRef { /** @var string $username */ public $username = ""; - /** @var SingleRefType|null $singleRefType */ - public $singleRefType = null; + /** @var SingleRefType $singleRefType */ + public $singleRefType; } diff --git a/samples/server/petstore/php-laravel/lib/app/Models/EnumTest.php b/samples/server/petstore/php-laravel/lib/app/Models/EnumTest.php index b188f1e86f..c5088d3f9f 100644 --- a/samples/server/petstore/php-laravel/lib/app/Models/EnumTest.php +++ b/samples/server/petstore/php-laravel/lib/app/Models/EnumTest.php @@ -18,7 +18,7 @@ class EnumTest { /** @var int $enumInteger */ public $enumInteger = 0; - /** @var double $enumNumber */ + /** @var float $enumNumber */ public $enumNumber = 0; /** @var string|null $outerEnum */ diff --git a/samples/server/petstore/php-laravel/lib/app/Models/FormatTest.php b/samples/server/petstore/php-laravel/lib/app/Models/FormatTest.php index d5114123c6..91d9e00087 100644 --- a/samples/server/petstore/php-laravel/lib/app/Models/FormatTest.php +++ b/samples/server/petstore/php-laravel/lib/app/Models/FormatTest.php @@ -24,7 +24,7 @@ class FormatTest { /** @var float $float */ public $float = 0; - /** @var double $double */ + /** @var float $double */ public $double = 0; /** @var float $decimal */ diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/.gitignore b/samples/server/petstore/php-symfony/SymfonyBundle-php/.gitignore index 3f90ef253e..6070e9bfda 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/.gitignore +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/.gitignore @@ -18,7 +18,7 @@ !var/sessions/.gitkeep # Parameters -/app/config/parameters.yml +/app/config/parameters.yaml /app/config/parameters.ini # Managed by Composer diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/FILES b/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/FILES index 6c8bb72be2..e1b272ff1e 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/FILES +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/FILES @@ -20,17 +20,8 @@ Model/Tag.php Model/User.php OpenAPIServerBundle.php README.md -Resources/config/routing.yml -Resources/config/services.yml -Resources/docs/Api/PetApiInterface.md -Resources/docs/Api/StoreApiInterface.md -Resources/docs/Api/UserApiInterface.md -Resources/docs/Model/ApiResponse.md -Resources/docs/Model/Category.md -Resources/docs/Model/Order.md -Resources/docs/Model/Pet.md -Resources/docs/Model/Tag.md -Resources/docs/Model/User.md +Resources/config/routing.yaml +Resources/config/services.yaml Service/JmsSerializer.php Service/SerializerInterface.php Service/StrictJsonDeserializationVisitor.php @@ -40,8 +31,17 @@ Service/TypeMismatchException.php Service/ValidatorInterface.php Tests/AppKernel.php Tests/Controller/ControllerTest.php -Tests/test_config.yml +Tests/test_config.yaml autoload.php composer.json +docs/Api/PetApiInterface.md +docs/Api/StoreApiInterface.md +docs/Api/UserApiInterface.md +docs/Model/ApiResponse.md +docs/Model/Category.md +docs/Model/Order.md +docs/Model/Pet.md +docs/Model/Tag.md +docs/Model/User.md git_push.sh phpunit.xml.dist diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/OpenAPIServerExtension.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/OpenAPIServerExtension.php index 02bd9b82fc..f964670958 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/OpenAPIServerExtension.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/DependencyInjection/OpenAPIServerExtension.php @@ -47,7 +47,7 @@ class OpenAPIServerExtension extends Extension public function load(array $configs, ContainerBuilder $container): void { $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); - $loader->load('services.yml'); + $loader->load('services.yaml'); } public function getAlias(): string diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md index c89ec4ed4f..08ffab2326 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md @@ -60,7 +60,7 @@ Step 3: Register the routes: ```yaml # app/config/routes.yaml open_api_server: - resource: "@OpenAPIServerBundle/Resources/config/routing.yml" + resource: "@OpenAPIServerBundle/Resources/config/routing.yaml" ``` Step 4: Implement the API calls: @@ -99,7 +99,7 @@ class PetApi implements PetApiInterface // An interface is autogenerated Step 5: Tag your API implementation: ```yaml -# config/services.yml +# config/services.yaml services: # ... Acme\MyBundle\Api\PetApi: @@ -117,36 +117,36 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*PetApiInterface* | [**addPet**](Resources/docs/Api/PetApiInterface.md#addpet) | **POST** /pet | Add a new pet to the store -*PetApiInterface* | [**deletePet**](Resources/docs/Api/PetApiInterface.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApiInterface* | [**findPetsByStatus**](Resources/docs/Api/PetApiInterface.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status -*PetApiInterface* | [**findPetsByTags**](Resources/docs/Api/PetApiInterface.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApiInterface* | [**getPetById**](Resources/docs/Api/PetApiInterface.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID -*PetApiInterface* | [**updatePet**](Resources/docs/Api/PetApiInterface.md#updatepet) | **PUT** /pet | Update an existing pet -*PetApiInterface* | [**updatePetWithForm**](Resources/docs/Api/PetApiInterface.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApiInterface* | [**uploadFile**](Resources/docs/Api/PetApiInterface.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image -*StoreApiInterface* | [**deleteOrder**](Resources/docs/Api/StoreApiInterface.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApiInterface* | [**getInventory**](Resources/docs/Api/StoreApiInterface.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApiInterface* | [**getOrderById**](Resources/docs/Api/StoreApiInterface.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID -*StoreApiInterface* | [**placeOrder**](Resources/docs/Api/StoreApiInterface.md#placeorder) | **POST** /store/order | Place an order for a pet -*UserApiInterface* | [**createUser**](Resources/docs/Api/UserApiInterface.md#createuser) | **POST** /user | Create user -*UserApiInterface* | [**createUsersWithArrayInput**](Resources/docs/Api/UserApiInterface.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApiInterface* | [**createUsersWithListInput**](Resources/docs/Api/UserApiInterface.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array -*UserApiInterface* | [**deleteUser**](Resources/docs/Api/UserApiInterface.md#deleteuser) | **DELETE** /user/{username} | Delete user -*UserApiInterface* | [**getUserByName**](Resources/docs/Api/UserApiInterface.md#getuserbyname) | **GET** /user/{username} | Get user by user name -*UserApiInterface* | [**loginUser**](Resources/docs/Api/UserApiInterface.md#loginuser) | **GET** /user/login | Logs user into the system -*UserApiInterface* | [**logoutUser**](Resources/docs/Api/UserApiInterface.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session -*UserApiInterface* | [**updateUser**](Resources/docs/Api/UserApiInterface.md#updateuser) | **PUT** /user/{username} | Updated user +*PetApiInterface* | [**addPet**](docs/Api/PetApiInterface.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApiInterface* | [**deletePet**](docs/Api/PetApiInterface.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApiInterface* | [**findPetsByStatus**](docs/Api/PetApiInterface.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApiInterface* | [**findPetsByTags**](docs/Api/PetApiInterface.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApiInterface* | [**getPetById**](docs/Api/PetApiInterface.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApiInterface* | [**updatePet**](docs/Api/PetApiInterface.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApiInterface* | [**updatePetWithForm**](docs/Api/PetApiInterface.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApiInterface* | [**uploadFile**](docs/Api/PetApiInterface.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApiInterface* | [**deleteOrder**](docs/Api/StoreApiInterface.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApiInterface* | [**getInventory**](docs/Api/StoreApiInterface.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApiInterface* | [**getOrderById**](docs/Api/StoreApiInterface.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApiInterface* | [**placeOrder**](docs/Api/StoreApiInterface.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApiInterface* | [**createUser**](docs/Api/UserApiInterface.md#createuser) | **POST** /user | Create user +*UserApiInterface* | [**createUsersWithArrayInput**](docs/Api/UserApiInterface.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApiInterface* | [**createUsersWithListInput**](docs/Api/UserApiInterface.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApiInterface* | [**deleteUser**](docs/Api/UserApiInterface.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApiInterface* | [**getUserByName**](docs/Api/UserApiInterface.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApiInterface* | [**loginUser**](docs/Api/UserApiInterface.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApiInterface* | [**logoutUser**](docs/Api/UserApiInterface.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApiInterface* | [**updateUser**](docs/Api/UserApiInterface.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models - - [ApiResponse](Resources/docs/Model/ApiResponse.md) - - [Category](Resources/docs/Model/Category.md) - - [Order](Resources/docs/Model/Order.md) - - [Pet](Resources/docs/Model/Pet.md) - - [Tag](Resources/docs/Model/Tag.md) - - [User](Resources/docs/Model/User.md) + - [ApiResponse](docs/Model/ApiResponse.md) + - [Category](docs/Model/Category.md) + - [Order](docs/Model/Order.md) + - [Pet](docs/Model/Pet.md) + - [Tag](docs/Model/Tag.md) + - [User](docs/Model/User.md) ## Documentation For Authorization diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/config/routing.yml b/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/config/routing.yaml similarity index 100% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/config/routing.yml rename to samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/config/routing.yaml diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/config/services.yml b/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/config/services.yaml similarity index 100% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/config/services.yml rename to samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/config/services.yaml diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/AppKernel.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/AppKernel.php index 608b63fdc0..2ce8342f34 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/AppKernel.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/AppKernel.php @@ -24,6 +24,6 @@ class AppKernel extends Kernel */ public function registerContainerConfiguration(LoaderInterface $loader) { - $loader->load(__DIR__.'/test_config.yml'); + $loader->load(__DIR__.'/test_config.yaml'); } } diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/test_config.yaml b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/test_config.yaml new file mode 100644 index 0000000000..9cd9521cbc --- /dev/null +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/test_config.yaml @@ -0,0 +1,8 @@ +imports: + - { resource: "../Resources/config/services.yaml" } + +framework: + secret: "testsecret" + test: ~ + router: + resource: "%kernel.project_dir%/Resources/config/routing.yaml" diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/test_config.yml b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/test_config.yml deleted file mode 100644 index 4c7970ab71..0000000000 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/test_config.yml +++ /dev/null @@ -1,8 +0,0 @@ -imports: - - { resource: "../Resources/config/services.yml" } - -framework: - secret: "testsecret" - test: ~ - router: - resource: "%kernel.project_dir%/Resources/config/routing.yml" diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/autoload.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/autoload.php index b3f278620a..9a070af610 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/autoload.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/autoload.php @@ -16,7 +16,7 @@ * * After registering this autoload function with SPL, the following line * would cause the function to attempt to load the \OpenAPI\Server\Baz\Qux class - * from /path/to/project/./Baz/Qux.php: + * from /path/to/project/Baz/Qux.php: * * new \OpenAPI\Server\Baz\Qux; * @@ -30,7 +30,7 @@ spl_autoload_register(function ($class) { $prefix = 'OpenAPI\\Server\\'; // base directory for the namespace prefix - $base_dir = __DIR__ . '/./'; + $base_dir = __DIR__ . '/'; // does the class use the namespace prefix? $len = strlen($prefix); diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/composer.json b/samples/server/petstore/php-symfony/SymfonyBundle-php/composer.json index 7683bf2cc8..3641be8433 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/composer.json +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/composer.json @@ -33,7 +33,7 @@ }, "autoload": { "psr-4": { - "OpenAPI\\Server\\" : "./" + "OpenAPI\\Server\\" : "" } } } diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/PetApiInterface.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Api/PetApiInterface.md similarity index 99% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/PetApiInterface.md rename to samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Api/PetApiInterface.md index 7b690ea767..6912d64030 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/PetApiInterface.md +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Api/PetApiInterface.md @@ -16,7 +16,7 @@ Method | HTTP request | Description ## Service Declaration ```yaml -# config/services.yml +# config/services.yaml services: # ... Acme\MyBundle\Api\PetApi: diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/StoreApiInterface.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Api/StoreApiInterface.md similarity index 99% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/StoreApiInterface.md rename to samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Api/StoreApiInterface.md index f7c5893d0d..c9aedf55e3 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/StoreApiInterface.md +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Api/StoreApiInterface.md @@ -12,7 +12,7 @@ Method | HTTP request | Description ## Service Declaration ```yaml -# config/services.yml +# config/services.yaml services: # ... Acme\MyBundle\Api\StoreApi: diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/UserApiInterface.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Api/UserApiInterface.md similarity index 99% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/UserApiInterface.md rename to samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Api/UserApiInterface.md index 24eb29aa6b..2c7e3ba262 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/UserApiInterface.md +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Api/UserApiInterface.md @@ -16,7 +16,7 @@ Method | HTTP request | Description ## Service Declaration ```yaml -# config/services.yml +# config/services.yaml services: # ... Acme\MyBundle\Api\UserApi: diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/ApiResponse.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/ApiResponse.md similarity index 100% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/ApiResponse.md rename to samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/ApiResponse.md diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/Category.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/Category.md similarity index 100% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/Category.md rename to samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/Category.md diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/Order.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/Order.md similarity index 100% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/Order.md rename to samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/Order.md diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/Pet.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/Pet.md similarity index 100% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/Pet.md rename to samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/Pet.md diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/Tag.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/Tag.md similarity index 100% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/Tag.md rename to samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/Tag.md diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/User.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/User.md similarity index 100% rename from samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Model/User.md rename to samples/server/petstore/php-symfony/SymfonyBundle-php/docs/Model/User.md diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/phpunit.xml.dist b/samples/server/petstore/php-symfony/SymfonyBundle-php/phpunit.xml.dist index a12d3c3c87..01645d7450 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/phpunit.xml.dist +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/phpunit.xml.dist @@ -9,9 +9,9 @@ xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"> - ././Api - ././Model - ././Controller + ./Api + ./Model + ./Controller diff --git a/samples/server/petstore/python-aiohttp-srclayout/Makefile b/samples/server/petstore/python-aiohttp-srclayout/Makefile index e73e0b9b30..4e8fafc39b 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/Makefile +++ b/samples/server/petstore/python-aiohttp-srclayout/Makefile @@ -12,7 +12,7 @@ clean: find . -name "__pycache__" -delete venv: - python -m venv $(VENV) + python3 -m venv $(VENV) test: clean venv bash ./test_python3.sh diff --git a/samples/server/petstore/python-aiohttp-srclayout/requirements.txt b/samples/server/petstore/python-aiohttp-srclayout/requirements.txt index e0dd796ca9..70c264978d 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/requirements.txt +++ b/samples/server/petstore/python-aiohttp-srclayout/requirements.txt @@ -5,5 +5,5 @@ connexion[aiohttp,swagger-ui] <= 2.3.0; python_version=="3.5" or python_version= # we must peg werkzeug versions below to fix connexion # https://github.com/zalando/connexion/pull/1044 werkzeug == 0.16.1; python_version=="3.5" or python_version=="3.4" -swagger-ui-bundle == 0.0.6 -aiohttp_jinja2 == 1.2.0 +swagger-ui-bundle == 0.0.9 +aiohttp_jinja2 == 1.5.0 diff --git a/samples/server/petstore/python-aiohttp-srclayout/setup.py b/samples/server/petstore/python-aiohttp-srclayout/setup.py index 6f62aec441..5cfff33cdb 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/setup.py +++ b/samples/server/petstore/python-aiohttp-srclayout/setup.py @@ -14,9 +14,9 @@ VERSION = "1.0.0" # http://pypi.python.org/pypi/setuptools REQUIRES = [ - "connexion==2.6.0", - "swagger-ui-bundle==0.0.6", - "aiohttp_jinja2==1.2.0", + "connexion==2.14.1", + "swagger-ui-bundle==0.0.9", + "aiohttp_jinja2==1.5.0", ] setup( diff --git a/samples/server/petstore/python-aiohttp-srclayout/test-requirements.txt b/samples/server/petstore/python-aiohttp-srclayout/test-requirements.txt index 31b28baaf2..bb7df90d4b 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/test-requirements.txt +++ b/samples/server/petstore/python-aiohttp-srclayout/test-requirements.txt @@ -1,4 +1,4 @@ -pytest~=4.6.7 # needed for python 2.7+3.4 +pytest~=7.1.0 pytest-cov>=2.8.1 -pytest-randomly==1.2.3 # needed for python 2.7+3.4 +pytest-randomly>=1.2.3 pytest-aiohttp>=0.3.0 diff --git a/samples/server/petstore/python-aiohttp/Makefile b/samples/server/petstore/python-aiohttp/Makefile index e73e0b9b30..4e8fafc39b 100644 --- a/samples/server/petstore/python-aiohttp/Makefile +++ b/samples/server/petstore/python-aiohttp/Makefile @@ -12,7 +12,7 @@ clean: find . -name "__pycache__" -delete venv: - python -m venv $(VENV) + python3 -m venv $(VENV) test: clean venv bash ./test_python3.sh diff --git a/samples/server/petstore/python-aiohttp/requirements.txt b/samples/server/petstore/python-aiohttp/requirements.txt index e0dd796ca9..70c264978d 100644 --- a/samples/server/petstore/python-aiohttp/requirements.txt +++ b/samples/server/petstore/python-aiohttp/requirements.txt @@ -5,5 +5,5 @@ connexion[aiohttp,swagger-ui] <= 2.3.0; python_version=="3.5" or python_version= # we must peg werkzeug versions below to fix connexion # https://github.com/zalando/connexion/pull/1044 werkzeug == 0.16.1; python_version=="3.5" or python_version=="3.4" -swagger-ui-bundle == 0.0.6 -aiohttp_jinja2 == 1.2.0 +swagger-ui-bundle == 0.0.9 +aiohttp_jinja2 == 1.5.0 diff --git a/samples/server/petstore/python-aiohttp/setup.py b/samples/server/petstore/python-aiohttp/setup.py index b6a25d8966..d464315706 100644 --- a/samples/server/petstore/python-aiohttp/setup.py +++ b/samples/server/petstore/python-aiohttp/setup.py @@ -14,9 +14,9 @@ VERSION = "1.0.0" # http://pypi.python.org/pypi/setuptools REQUIRES = [ - "connexion==2.6.0", - "swagger-ui-bundle==0.0.6", - "aiohttp_jinja2==1.2.0", + "connexion==2.14.1", + "swagger-ui-bundle==0.0.9", + "aiohttp_jinja2==1.5.0", ] setup( diff --git a/samples/server/petstore/python-aiohttp/test-requirements.txt b/samples/server/petstore/python-aiohttp/test-requirements.txt index 31b28baaf2..bb7df90d4b 100644 --- a/samples/server/petstore/python-aiohttp/test-requirements.txt +++ b/samples/server/petstore/python-aiohttp/test-requirements.txt @@ -1,4 +1,4 @@ -pytest~=4.6.7 # needed for python 2.7+3.4 +pytest~=7.1.0 pytest-cov>=2.8.1 -pytest-randomly==1.2.3 # needed for python 2.7+3.4 +pytest-randomly>=1.2.3 pytest-aiohttp>=0.3.0 diff --git a/samples/server/petstore/python-aiohttp/tests/test_pet_controller.py b/samples/server/petstore/python-aiohttp/tests/test_pet_controller.py index 5f6384a34f..de3d3eeb82 100644 --- a/samples/server/petstore/python-aiohttp/tests/test_pet_controller.py +++ b/samples/server/petstore/python-aiohttp/tests/test_pet_controller.py @@ -9,7 +9,7 @@ from openapi_server.models.api_response import ApiResponse from openapi_server.models.pet import Pet -@pytest.mark.skip("Connexion does not support multiple consummes. See https://github.com/zalando/connexion/pull/760") +@pytest.mark.skip("Connexion does not support multiple consumes. See https://github.com/zalando/connexion/pull/760") async def test_add_pet(client): """Test case for add_pet @@ -67,7 +67,7 @@ async def test_find_pets_by_status(client): Finds Pets by status """ - params = [('status', 'available')] + params = [('status', ['available'])] headers = { 'Accept': 'application/json', 'Authorization': 'Bearer special-key', @@ -86,7 +86,7 @@ async def test_find_pets_by_tags(client): Finds Pets by tags """ - params = [('tags', 'tags_example')] + params = [('tags', ['tags_example'])] headers = { 'Accept': 'application/json', 'Authorization': 'Bearer special-key', @@ -117,7 +117,7 @@ async def test_get_pet_by_id(client): assert response.status == 200, 'Response body is : ' + (await response.read()).decode('utf-8') -@pytest.mark.skip("Connexion does not support multiple consummes. See https://github.com/zalando/connexion/pull/760") +@pytest.mark.skip("Connexion does not support multiple consumes. See https://github.com/zalando/connexion/pull/760") async def test_update_pet(client): """Test case for update_pet @@ -189,7 +189,7 @@ async def test_upload_file(client): } data = FormData() data.add_field('additional_metadata', 'additional_metadata_example') - data.add_field('file', (BytesIO(b'some file data'), 'file.txt')) + data.add_field('file', '/path/to/file') response = await client.request( method='POST', path='/v2/pet/{pet_id}/uploadImage'.format(pet_id=56), diff --git a/samples/server/petstore/python-aiohttp/tests/test_store_controller.py b/samples/server/petstore/python-aiohttp/tests/test_store_controller.py index 9d376a5f7a..9625a8b35e 100644 --- a/samples/server/petstore/python-aiohttp/tests/test_store_controller.py +++ b/samples/server/petstore/python-aiohttp/tests/test_store_controller.py @@ -49,7 +49,7 @@ async def test_get_order_by_id(client): } response = await client.request( method='GET', - path='/v2/store/order/{order_id}'.format(order_id=5), + path='/v2/store/order/{order_id}'.format(order_id=1), headers=headers, ) assert response.status == 200, 'Response body is : ' + (await response.read()).decode('utf-8') @@ -61,7 +61,7 @@ async def test_place_order(client): Place an order for a pet """ - body = {} + body = openapi_server.Order() headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', diff --git a/samples/server/petstore/python-aiohttp/tests/test_user_controller.py b/samples/server/petstore/python-aiohttp/tests/test_user_controller.py index 6564329315..c695e4f0c9 100644 --- a/samples/server/petstore/python-aiohttp/tests/test_user_controller.py +++ b/samples/server/petstore/python-aiohttp/tests/test_user_controller.py @@ -13,7 +13,7 @@ async def test_create_user(client): Create user """ - body = {} + body = openapi_server.User() headers = { 'Content-Type': 'application/json', } @@ -32,7 +32,7 @@ async def test_create_users_with_array_input(client): Creates list of users with given input array """ - body = [{}] + body = [openapi_server.User()] headers = { 'Content-Type': 'application/json', } @@ -51,7 +51,7 @@ async def test_create_users_with_list_input(client): Creates list of users with given input array """ - body = [{}] + body = [openapi_server.User()] headers = { 'Content-Type': 'application/json', } @@ -135,7 +135,7 @@ async def test_update_user(client): Updated user """ - body = {} + body = openapi_server.User() headers = { 'Content-Type': 'application/json', } diff --git a/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_pet_controller.py b/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_pet_controller.py index 34b8e534e6..70ce6ad26a 100644 --- a/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_pet_controller.py +++ b/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_pet_controller.py @@ -61,7 +61,7 @@ class TestPetController(BaseTestCase): Finds Pets by status """ - query_string = [('status', 'available')] + query_string = [('status', ['available'])] response = self.client.open( '/v2/pet/findByStatus', method='GET', @@ -74,7 +74,7 @@ class TestPetController(BaseTestCase): Finds Pets by tags """ - query_string = [('tags', 'tags_example')] + query_string = [('tags', ['tags_example'])] response = self.client.open( '/v2/pet/findByTags', method='GET', @@ -144,7 +144,7 @@ class TestPetController(BaseTestCase): uploads an image """ data = dict(additional_metadata='additional_metadata_example', - file=(BytesIO(b'some file data'), 'file.txt')) + file='/path/to/file') response = self.client.open( '/v2/pet/{pet_id}/uploadImage'.format(pet_id=56), method='POST', diff --git a/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_store_controller.py b/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_store_controller.py index 3695ff4a3b..57bd3fa8f8 100644 --- a/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_store_controller.py +++ b/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_store_controller.py @@ -40,7 +40,7 @@ class TestStoreController(BaseTestCase): Find purchase order by ID """ response = self.client.open( - '/v2/store/order/{order_id}'.format(order_id=5), + '/v2/store/order/{order_id}'.format(order_id=1), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -50,7 +50,7 @@ class TestStoreController(BaseTestCase): Place an order for a pet """ - body = {} + body = openapi_server.Order() response = self.client.open( '/v2/store/order', method='POST', diff --git a/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_user_controller.py b/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_user_controller.py index 1ef108621b..e96791b1cc 100644 --- a/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_user_controller.py +++ b/samples/server/petstore/python-blueplanet/app/openapi_server/test/test_user_controller.py @@ -17,7 +17,7 @@ class TestUserController(BaseTestCase): Create user """ - body = {} + body = openapi_server.User() response = self.client.open( '/v2/user', method='POST', @@ -31,7 +31,7 @@ class TestUserController(BaseTestCase): Creates list of users with given input array """ - body = [] + body = [openapi_server.User()] response = self.client.open( '/v2/user/createWithArray', method='POST', @@ -45,7 +45,7 @@ class TestUserController(BaseTestCase): Creates list of users with given input array """ - body = [] + body = [openapi_server.User()] response = self.client.open( '/v2/user/createWithList', method='POST', @@ -106,7 +106,7 @@ class TestUserController(BaseTestCase): Updated user """ - body = {} + body = openapi_server.User() response = self.client.open( '/v2/user/{username}'.format(username='username_example'), method='PUT', diff --git a/samples/server/petstore/python-flask/openapi_server/models/api_response.py b/samples/server/petstore/python-flask/openapi_server/models/api_response.py index 1e23da9c23..b520253a9b 100644 --- a/samples/server/petstore/python-flask/openapi_server/models/api_response.py +++ b/samples/server/petstore/python-flask/openapi_server/models/api_response.py @@ -37,9 +37,9 @@ class ApiResponse(Model): 'message': 'message' } - self._code = code - self._type = type - self._message = message + self.code = code + self.type = type + self.message = message @classmethod def from_dict(cls, dikt) -> 'ApiResponse': diff --git a/samples/server/petstore/python-flask/openapi_server/models/base_model_.py b/samples/server/petstore/python-flask/openapi_server/models/base_model_.py index 961abbf322..916e582ec2 100644 --- a/samples/server/petstore/python-flask/openapi_server/models/base_model_.py +++ b/samples/server/petstore/python-flask/openapi_server/models/base_model_.py @@ -8,7 +8,7 @@ from openapi_server import util T = typing.TypeVar('T') -class Model(): +class Model(object): # openapiTypes: The key is attribute name and the # value is attribute type. openapi_types: typing.Dict[str, type] = {} diff --git a/samples/server/petstore/python-flask/openapi_server/models/category.py b/samples/server/petstore/python-flask/openapi_server/models/category.py index 3a68d86c25..9ae904785b 100644 --- a/samples/server/petstore/python-flask/openapi_server/models/category.py +++ b/samples/server/petstore/python-flask/openapi_server/models/category.py @@ -33,8 +33,8 @@ class Category(Model): 'name': 'name' } - self._id = id - self._name = name + self.id = id + self.name = name @classmethod def from_dict(cls, dikt) -> 'Category': diff --git a/samples/server/petstore/python-flask/openapi_server/models/order.py b/samples/server/petstore/python-flask/openapi_server/models/order.py index aa8a7a71c3..23f061c821 100644 --- a/samples/server/petstore/python-flask/openapi_server/models/order.py +++ b/samples/server/petstore/python-flask/openapi_server/models/order.py @@ -49,12 +49,12 @@ class Order(Model): 'complete': 'complete' } - self._id = id - self._pet_id = pet_id - self._quantity = quantity - self._ship_date = ship_date - self._status = status - self._complete = complete + self.id = id + self.pet_id = pet_id + self.quantity = quantity + self.ship_date = ship_date + self.status = status + self.complete = complete @classmethod def from_dict(cls, dikt) -> 'Order': diff --git a/samples/server/petstore/python-flask/openapi_server/models/pet.py b/samples/server/petstore/python-flask/openapi_server/models/pet.py index e61674165e..377c8accdf 100644 --- a/samples/server/petstore/python-flask/openapi_server/models/pet.py +++ b/samples/server/petstore/python-flask/openapi_server/models/pet.py @@ -53,12 +53,12 @@ class Pet(Model): 'status': 'status' } - self._id = id - self._category = category - self._name = name - self._photo_urls = photo_urls - self._tags = tags - self._status = status + self.id = id + self.category = category + self.name = name + self.photo_urls = photo_urls + self.tags = tags + self.status = status @classmethod def from_dict(cls, dikt) -> 'Pet': diff --git a/samples/server/petstore/python-flask/openapi_server/models/tag.py b/samples/server/petstore/python-flask/openapi_server/models/tag.py index bd6fff1690..deb88936e5 100644 --- a/samples/server/petstore/python-flask/openapi_server/models/tag.py +++ b/samples/server/petstore/python-flask/openapi_server/models/tag.py @@ -33,8 +33,8 @@ class Tag(Model): 'name': 'name' } - self._id = id - self._name = name + self.id = id + self.name = name @classmethod def from_dict(cls, dikt) -> 'Tag': diff --git a/samples/server/petstore/python-flask/openapi_server/models/user.py b/samples/server/petstore/python-flask/openapi_server/models/user.py index 1b1f4bdae7..fdc250d5f0 100644 --- a/samples/server/petstore/python-flask/openapi_server/models/user.py +++ b/samples/server/petstore/python-flask/openapi_server/models/user.py @@ -57,14 +57,14 @@ class User(Model): 'user_status': 'userStatus' } - self._id = id - self._username = username - self._first_name = first_name - self._last_name = last_name - self._email = email - self._password = password - self._phone = phone - self._user_status = user_status + self.id = id + self.username = username + self.first_name = first_name + self.last_name = last_name + self.email = email + self.password = password + self.phone = phone + self.user_status = user_status @classmethod def from_dict(cls, dikt) -> 'User': diff --git a/samples/server/petstore/python-flask/openapi_server/test/test_pet_controller.py b/samples/server/petstore/python-flask/openapi_server/test/test_pet_controller.py index f29ac97214..d1eb1d3266 100644 --- a/samples/server/petstore/python-flask/openapi_server/test/test_pet_controller.py +++ b/samples/server/petstore/python-flask/openapi_server/test/test_pet_controller.py @@ -14,7 +14,7 @@ from openapi_server.test import BaseTestCase class TestPetController(BaseTestCase): """PetController integration test stubs""" - @unittest.skip("Connexion does not support multiple consummes. See https://github.com/zalando/connexion/pull/760") + @unittest.skip("Connexion does not support multiple consumes. See https://github.com/zalando/connexion/pull/760") def test_add_pet(self): """Test case for add_pet @@ -89,7 +89,7 @@ class TestPetController(BaseTestCase): Finds Pets by tags """ - query_string = [('tags', 'tags_example')] + query_string = [('tags', ['tags_example'])] headers = { 'Accept': 'application/json', 'Authorization': 'Bearer special-key', @@ -118,7 +118,7 @@ class TestPetController(BaseTestCase): self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) - @unittest.skip("Connexion does not support multiple consummes. See https://github.com/zalando/connexion/pull/760") + @unittest.skip("Connexion does not support multiple consumes. See https://github.com/zalando/connexion/pull/760") def test_update_pet(self): """Test case for update_pet @@ -187,7 +187,7 @@ class TestPetController(BaseTestCase): 'Authorization': 'Bearer special-key', } data = dict(additional_metadata='additional_metadata_example', - file=(BytesIO(b'some file data'), 'file.txt')) + file='/path/to/file') response = self.client.open( '/v2/pet/{pet_id}/uploadImage'.format(pet_id=56), method='POST', diff --git a/samples/server/petstore/python-flask/openapi_server/test/test_store_controller.py b/samples/server/petstore/python-flask/openapi_server/test/test_store_controller.py index e2d0c7ddd3..43867b1d98 100644 --- a/samples/server/petstore/python-flask/openapi_server/test/test_store_controller.py +++ b/samples/server/petstore/python-flask/openapi_server/test/test_store_controller.py @@ -52,7 +52,7 @@ class TestStoreController(BaseTestCase): 'Accept': 'application/json', } response = self.client.open( - '/v2/store/order/{order_id}'.format(order_id=5), + '/v2/store/order/{order_id}'.format(order_id=1), method='GET', headers=headers) self.assert200(response, @@ -64,7 +64,7 @@ class TestStoreController(BaseTestCase): Place an order for a pet """ - body = {} + body = openapi_server.Order() headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', diff --git a/samples/server/petstore/python-flask/openapi_server/test/test_user_controller.py b/samples/server/petstore/python-flask/openapi_server/test/test_user_controller.py index 172ff22d13..010a72b030 100644 --- a/samples/server/petstore/python-flask/openapi_server/test/test_user_controller.py +++ b/samples/server/petstore/python-flask/openapi_server/test/test_user_controller.py @@ -19,7 +19,7 @@ class TestUserController(BaseTestCase): Create user """ - body = {} + body = openapi_server.User() headers = { 'Content-Type': 'application/json', } @@ -38,7 +38,7 @@ class TestUserController(BaseTestCase): Creates list of users with given input array """ - body = [{}] + body = [openapi_server.User()] headers = { 'Content-Type': 'application/json', } @@ -57,7 +57,7 @@ class TestUserController(BaseTestCase): Creates list of users with given input array """ - body = [{}] + body = [openapi_server.User()] headers = { 'Content-Type': 'application/json', } @@ -137,7 +137,7 @@ class TestUserController(BaseTestCase): Updated user """ - body = {} + body = openapi_server.User() headers = { 'Content-Type': 'application/json', } diff --git a/samples/server/petstore/python-flask/requirements.txt b/samples/server/petstore/python-flask/requirements.txt index 70e1f0c554..be4c8a3a02 100644 --- a/samples/server/petstore/python-flask/requirements.txt +++ b/samples/server/petstore/python-flask/requirements.txt @@ -8,4 +8,4 @@ werkzeug == 0.16.1; python_version=="3.5" or python_version=="3.4" swagger-ui-bundle >= 0.0.2 python_dateutil >= 2.6.0 setuptools >= 21.0.0 -Flask == 1.1.2 +Flask == 2.1.1 diff --git a/samples/server/petstore/python-flask/test-requirements.txt b/samples/server/petstore/python-flask/test-requirements.txt index 0970f28c7c..58f51d6a00 100644 --- a/samples/server/petstore/python-flask/test-requirements.txt +++ b/samples/server/petstore/python-flask/test-requirements.txt @@ -1,4 +1,4 @@ -pytest~=4.6.7 # needed for python 2.7+3.4 +pytest~=7.1.0 pytest-cov>=2.8.1 -pytest-randomly==1.2.3 # needed for python 2.7+3.4 -Flask-Testing==0.8.0 +pytest-randomly>=1.2.3 +Flask-Testing==0.8.1 diff --git a/samples/server/petstore/rust-server/.cargo/config b/samples/server/petstore/rust-server/.cargo/config new file mode 100644 index 0000000000..b8acc9c00c --- /dev/null +++ b/samples/server/petstore/rust-server/.cargo/config @@ -0,0 +1,18 @@ +[build] +rustflags = [ + "-W", "missing_docs", # detects missing documentation for public members + + "-W", "trivial_casts", # detects trivial casts which could be removed + + "-W", "trivial_numeric_casts", # detects trivial casts of numeric types which could be removed + + "-W", "unsafe_code", # usage of `unsafe` code + + "-W", "unused_qualifications", # detects unnecessarily qualified names + + "-W", "unused_extern_crates", # extern crates that are never used + + "-W", "unused_import_braces", # unnecessary braces around an imported item + + "-D", "warnings", # all warnings should be denied +] diff --git a/samples/server/petstore/rust-server/output/multipart-v3/examples/server/server.rs b/samples/server/petstore/rust-server/output/multipart-v3/examples/server/server.rs index 892a189b8e..a031eb139c 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/multipart-v3/examples/server/server.rs @@ -32,6 +32,7 @@ pub async fn create(addr: &str, https: bool) { let service = MakeAllowAllAuthenticator::new(service, "cosmo"); + #[allow(unused_mut)] let mut service = multipart_v3::server::context::MakeAddContext::<_, EmptyContext>::new( service diff --git a/samples/server/petstore/rust-server/output/multipart-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/multipart-v3/src/client/mod.rs index 89f7254441..eaea306af1 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/multipart-v3/src/client/mod.rs @@ -60,7 +60,7 @@ fn into_base_path(input: impl TryInto, } } - let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let host = uri.host().ok_or(ClientInitError::MissingHost)?; let port = uri.port_u16().map(|x| format!(":{}", x)).unwrap_or_default(); Ok(format!("{}://{}{}{}", scheme, host, port, uri.path().trim_end_matches('/'))) } @@ -199,7 +199,7 @@ impl Client, C> where "https" => { let connector = connector.https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; HyperClient::Https(hyper::client::Client::builder().build(connector)) }, _ => { @@ -251,7 +251,7 @@ impl Client, C let https_connector = Connector::builder() .https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -272,7 +272,7 @@ impl Client, C .https() .pin_server_certificate(ca_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -300,7 +300,7 @@ impl Client, C .pin_server_certificate(ca_certificate) .client_authentication(client_key, client_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } } @@ -429,8 +429,8 @@ impl Api for Client where // no such boundary is used. let mut boundary = generate_boundary(); for b in boundary.iter_mut() { - if b == &('/' as u8) { - *b = '=' as u8; + if b == &(b'/') { + *b = b'='; } } @@ -494,18 +494,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 201 => { - let body = response.into_body(); Ok( MultipartRelatedRequestPostResponse::OK ) @@ -647,18 +646,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", multipart_header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 201 => { - let body = response.into_body(); Ok( MultipartRequestPostResponse::OK ) @@ -724,8 +722,8 @@ impl Api for Client where // no such boundary is used. let mut boundary = generate_boundary(); for b in boundary.iter_mut() { - if b == &('/' as u8) { - *b = '=' as u8; + if b == &(b'/') { + *b = b'='; } } @@ -774,18 +772,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( MultipleIdenticalMimeTypesPostResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/multipart-v3/src/lib.rs b/samples/server/petstore/rust-server/output/multipart-v3/src/lib.rs index 95e56d34a3..b1c50ab40a 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/src/lib.rs +++ b/samples/server/petstore/rust-server/output/multipart-v3/src/lib.rs @@ -1,4 +1,6 @@ #![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::blacklisted_name)] use async_trait::async_trait; use futures::Stream; @@ -9,8 +11,8 @@ use serde::{Serialize, Deserialize}; type ServiceError = Box; -pub const BASE_PATH: &'static str = ""; -pub const API_VERSION: &'static str = "1.0.7"; +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "1.0.7"; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum MultipartRelatedRequestPostResponse { @@ -32,6 +34,7 @@ pub enum MultipleIdenticalMimeTypesPostResponse { /// API #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait Api { fn poll_ready(&self, _cx: &mut Context) -> Poll>> { Poll::Ready(Ok(())) @@ -62,6 +65,7 @@ pub trait Api { /// API where `Context` isn't passed on every API call #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait ApiNoContext { fn poll_ready(&self, _cx: &mut Context) -> Poll>>; @@ -95,7 +99,7 @@ pub trait ApiNoContext { pub trait ContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> ContextWrapperExt for T { diff --git a/samples/server/petstore/rust-server/output/multipart-v3/src/models.rs b/samples/server/petstore/rust-server/output/multipart-v3/src/models.rs index ca528ed40a..f94163d910 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/multipart-v3/src/models.rs @@ -21,11 +21,12 @@ pub struct MultipartRelatedRequest { } impl MultipartRelatedRequest { + #[allow(clippy::new_without_default)] pub fn new(required_binary_field: swagger::ByteArray, ) -> MultipartRelatedRequest { MultipartRelatedRequest { object_field: None, optional_binary_field: None, - required_binary_field: required_binary_field, + required_binary_field, } } } @@ -35,16 +36,18 @@ impl MultipartRelatedRequest { /// Should be implemented in a serde serializer impl std::string::ToString for MultipartRelatedRequest { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping object_field in query parameter serialization + let params: Vec> = vec![ + // Skipping object_field in query parameter serialization - // Skipping optional_binary_field in query parameter serialization - // Skipping optional_binary_field in query parameter serialization + // Skipping optional_binary_field in query parameter serialization + // Skipping optional_binary_field in query parameter serialization - // Skipping required_binary_field in query parameter serialization - // Skipping required_binary_field in query parameter serialization + // Skipping required_binary_field in query parameter serialization + // Skipping required_binary_field in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -55,8 +58,9 @@ impl std::str::FromStr for MultipartRelatedRequest { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub object_field: Vec, pub optional_binary_field: Vec, @@ -66,7 +70,7 @@ impl std::str::FromStr for MultipartRelatedRequest { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -76,8 +80,10 @@ impl std::str::FromStr for MultipartRelatedRequest { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "object_field" => intermediate_rep.object_field.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "object_field" => intermediate_rep.object_field.push(::from_str(val).map_err(|x| x.to_string())?), "optional_binary_field" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipartRelatedRequest".to_string()), "required_binary_field" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipartRelatedRequest".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing MultipartRelatedRequest".to_string()) @@ -92,7 +98,7 @@ impl std::str::FromStr for MultipartRelatedRequest { std::result::Result::Ok(MultipartRelatedRequest { object_field: intermediate_rep.object_field.into_iter().next(), optional_binary_field: intermediate_rep.optional_binary_field.into_iter().next(), - required_binary_field: intermediate_rep.required_binary_field.into_iter().next().ok_or("required_binary_field missing in MultipartRelatedRequest".to_string())?, + required_binary_field: intermediate_rep.required_binary_field.into_iter().next().ok_or_else(|| "required_binary_field missing in MultipartRelatedRequest".to_string())?, }) } } @@ -149,9 +155,10 @@ pub struct MultipartRequestObjectField { } impl MultipartRequestObjectField { + #[allow(clippy::new_without_default)] pub fn new(field_a: String, ) -> MultipartRequestObjectField { MultipartRequestObjectField { - field_a: field_a, + field_a, field_b: None, } } @@ -162,18 +169,22 @@ impl MultipartRequestObjectField { /// Should be implemented in a serde serializer impl std::string::ToString for MultipartRequestObjectField { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("field_a".to_string()); - params.push(self.field_a.to_string()); + Some("field_a".to_string()), + Some(self.field_a.to_string()), - if let Some(ref field_b) = self.field_b { - params.push("field_b".to_string()); - params.push(field_b.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - } + self.field_b.as_ref().map(|field_b| { + vec![ + "field_b".to_string(), + field_b.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -184,8 +195,9 @@ impl std::str::FromStr for MultipartRequestObjectField { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub field_a: Vec, pub field_b: Vec>, @@ -194,7 +206,7 @@ impl std::str::FromStr for MultipartRequestObjectField { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -204,8 +216,10 @@ impl std::str::FromStr for MultipartRequestObjectField { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "field_a" => intermediate_rep.field_a.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "field_a" => intermediate_rep.field_a.push(::from_str(val).map_err(|x| x.to_string())?), "field_b" => return std::result::Result::Err("Parsing a container in this style is not supported in MultipartRequestObjectField".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing MultipartRequestObjectField".to_string()) } @@ -217,7 +231,7 @@ impl std::str::FromStr for MultipartRequestObjectField { // Use the intermediate representation to return the struct std::result::Result::Ok(MultipartRequestObjectField { - field_a: intermediate_rep.field_a.into_iter().next().ok_or("field_a missing in MultipartRequestObjectField".to_string())?, + field_a: intermediate_rep.field_a.into_iter().next().ok_or_else(|| "field_a missing in MultipartRequestObjectField".to_string())?, field_b: intermediate_rep.field_b.into_iter().next(), }) } @@ -276,6 +290,7 @@ pub struct MultipleIdenticalMimeTypesPostRequest { } impl MultipleIdenticalMimeTypesPostRequest { + #[allow(clippy::new_without_default)] pub fn new() -> MultipleIdenticalMimeTypesPostRequest { MultipleIdenticalMimeTypesPostRequest { binary1: None, @@ -289,14 +304,16 @@ impl MultipleIdenticalMimeTypesPostRequest { /// Should be implemented in a serde serializer impl std::string::ToString for MultipleIdenticalMimeTypesPostRequest { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping binary1 in query parameter serialization - // Skipping binary1 in query parameter serialization + let params: Vec> = vec![ + // Skipping binary1 in query parameter serialization + // Skipping binary1 in query parameter serialization - // Skipping binary2 in query parameter serialization - // Skipping binary2 in query parameter serialization + // Skipping binary2 in query parameter serialization + // Skipping binary2 in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -307,8 +324,9 @@ impl std::str::FromStr for MultipleIdenticalMimeTypesPostRequest { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub binary1: Vec, pub binary2: Vec, @@ -317,7 +335,7 @@ impl std::str::FromStr for MultipleIdenticalMimeTypesPostRequest { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -327,6 +345,7 @@ impl std::str::FromStr for MultipleIdenticalMimeTypesPostRequest { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { "binary1" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipleIdenticalMimeTypesPostRequest".to_string()), "binary2" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipleIdenticalMimeTypesPostRequest".to_string()), diff --git a/samples/server/petstore/rust-server/output/multipart-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/multipart-v3/src/server/mod.rs index 3330f22362..c3ab4bd0e6 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/multipart-v3/src/server/mod.rs @@ -109,7 +109,7 @@ impl Service where { pub fn new(api_impl: T) -> Self { Service { - api_impl: api_impl, + api_impl, marker: PhantomData } } @@ -122,7 +122,7 @@ impl Clone for Service where fn clone(&self) -> Self { Service { api_impl: self.api_impl.clone(), - marker: self.marker.clone(), + marker: self.marker, } } } @@ -148,10 +148,10 @@ impl hyper::service::Service<(Request, C)> for Service where let (method, uri, headers) = (parts.method, parts.uri, parts.headers); let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); - match &method { + match method { // MultipartRelatedRequestPost - POST /multipart_related_request - &hyper::Method::POST if path.matched(paths::ID_MULTIPART_RELATED_REQUEST) => { + hyper::Method::POST if path.matched(paths::ID_MULTIPART_RELATED_REQUEST) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -165,9 +165,9 @@ impl hyper::service::Service<(Request, C)> for Service where // Extract the top-level content type header. let content_type_mime = headers .get(CONTENT_TYPE) - .ok_or("Missing content-type header".to_string()) + .ok_or_else(|| "Missing content-type header".to_string()) .and_then(|v| v.to_str().map_err(|e| format!("Couldn't read content-type header value for MultipartRelatedRequestPost: {}", e))) - .and_then(|v| v.parse::().map_err(|_e| format!("Couldn't parse content-type header value for MultipartRelatedRequestPost"))); + .and_then(|v| v.parse::().map_err(|_e| "Couldn't parse content-type header value for MultipartRelatedRequestPost".to_string())); // Insert top-level content type header into a Headers object. let mut multi_part_headers = Headers::new(); @@ -202,7 +202,7 @@ impl hyper::service::Service<(Request, C)> for Service where for node in nodes { if let Node::Part(part) = node { let content_type = part.content_type().map(|x| format!("{}",x)); - match content_type.as_ref().map(|x| x.as_str()) { + match content_type.as_deref() { Some("application/json") if param_object_field.is_none() => { // Extract JSON part. let deserializer = &mut serde_json::Deserializer::from_slice(part.body.as_slice()); @@ -244,7 +244,7 @@ impl hyper::service::Service<(Request, C)> for Service where Some(x) => x, None => return Ok(Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Missing required multipart/related parameter required_binary_field"))) + .body(Body::from("Missing required multipart/related parameter required_binary_field".to_string())) .expect("Unable to create Bad Request response for missing multipart/related parameter required_binary_field due to schema")) }; @@ -257,7 +257,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -285,7 +285,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // MultipartRequestPost - POST /multipart_request - &hyper::Method::POST if path.matched(paths::ID_MULTIPART_REQUEST) => { + hyper::Method::POST if path.matched(paths::ID_MULTIPART_REQUEST) => { let boundary = match swagger::multipart::form::boundary(&headers) { Some(boundary) => boundary.to_string(), None => return Ok(Response::builder() @@ -310,7 +310,7 @@ impl hyper::service::Service<(Request, C)> for Service where _ => { return Ok(Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Unable to process all message parts"))) + .body(Body::from("Unable to process all message parts".to_string())) .expect("Unable to create Bad Request response due to failure to process all message")) }, }; @@ -336,7 +336,7 @@ impl hyper::service::Service<(Request, C)> for Service where return Ok( Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Missing required form parameter string_field"))) + .body(Body::from("Missing required form parameter string_field".to_string())) .expect("Unable to create Bad Request due to missing required form parameter string_field")) } }; @@ -400,7 +400,7 @@ impl hyper::service::Service<(Request, C)> for Service where return Ok( Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Missing required form parameter binary_field"))) + .body(Body::from("Missing required form parameter binary_field".to_string())) .expect("Unable to create Bad Request due to missing required form parameter binary_field")) } }; @@ -414,7 +414,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -436,13 +436,13 @@ impl hyper::service::Service<(Request, C)> for Service where }, Err(e) => Ok(Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read multipart body"))) + .body(Body::from("Couldn't read multipart body".to_string())) .expect("Unable to create Bad Request response due to unable read multipart body")), } }, // MultipleIdenticalMimeTypesPost - POST /multiple-identical-mime-types - &hyper::Method::POST if path.matched(paths::ID_MULTIPLE_IDENTICAL_MIME_TYPES) => { + hyper::Method::POST if path.matched(paths::ID_MULTIPLE_IDENTICAL_MIME_TYPES) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -456,9 +456,9 @@ impl hyper::service::Service<(Request, C)> for Service where // Extract the top-level content type header. let content_type_mime = headers .get(CONTENT_TYPE) - .ok_or("Missing content-type header".to_string()) + .ok_or_else(|| "Missing content-type header".to_string()) .and_then(|v| v.to_str().map_err(|e| format!("Couldn't read content-type header value for MultipleIdenticalMimeTypesPost: {}", e))) - .and_then(|v| v.parse::().map_err(|_e| format!("Couldn't parse content-type header value for MultipleIdenticalMimeTypesPost"))); + .and_then(|v| v.parse::().map_err(|_e| "Couldn't parse content-type header value for MultipleIdenticalMimeTypesPost".to_string())); // Insert top-level content type header into a Headers object. let mut multi_part_headers = Headers::new(); @@ -492,7 +492,7 @@ impl hyper::service::Service<(Request, C)> for Service where for node in nodes { if let Node::Part(part) = node { let content_type = part.content_type().map(|x| format!("{}",x)); - match content_type.as_ref().map(|x| x.as_str()) { + match content_type.as_deref() { Some("application/octet-stream") if param_binary1.is_none() => { param_binary1.get_or_insert(swagger::ByteArray(part.body)); }, @@ -523,7 +523,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -565,13 +565,13 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { // MultipartRelatedRequestPost - POST /multipart_related_request - &hyper::Method::POST if path.matched(paths::ID_MULTIPART_RELATED_REQUEST) => Some("MultipartRelatedRequestPost"), + hyper::Method::POST if path.matched(paths::ID_MULTIPART_RELATED_REQUEST) => Some("MultipartRelatedRequestPost"), // MultipartRequestPost - POST /multipart_request - &hyper::Method::POST if path.matched(paths::ID_MULTIPART_REQUEST) => Some("MultipartRequestPost"), + hyper::Method::POST if path.matched(paths::ID_MULTIPART_REQUEST) => Some("MultipartRequestPost"), // MultipleIdenticalMimeTypesPost - POST /multiple-identical-mime-types - &hyper::Method::POST if path.matched(paths::ID_MULTIPLE_IDENTICAL_MIME_TYPES) => Some("MultipleIdenticalMimeTypesPost"), + hyper::Method::POST if path.matched(paths::ID_MULTIPLE_IDENTICAL_MIME_TYPES) => Some("MultipleIdenticalMimeTypesPost"), _ => None, } } diff --git a/samples/server/petstore/rust-server/output/no-example-v3/examples/server/server.rs b/samples/server/petstore/rust-server/output/no-example-v3/examples/server/server.rs index 3bc8fa48fe..55f8d608b5 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/no-example-v3/examples/server/server.rs @@ -32,6 +32,7 @@ pub async fn create(addr: &str, https: bool) { let service = MakeAllowAllAuthenticator::new(service, "cosmo"); + #[allow(unused_mut)] let mut service = no_example_v3::server::context::MakeAddContext::<_, EmptyContext>::new( service diff --git a/samples/server/petstore/rust-server/output/no-example-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/no-example-v3/src/client/mod.rs index bc32420a2d..b8bcf77633 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/no-example-v3/src/client/mod.rs @@ -53,7 +53,7 @@ fn into_base_path(input: impl TryInto, } } - let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let host = uri.host().ok_or(ClientInitError::MissingHost)?; let port = uri.port_u16().map(|x| format!(":{}", x)).unwrap_or_default(); Ok(format!("{}://{}{}{}", scheme, host, port, uri.path().trim_end_matches('/'))) } @@ -192,7 +192,7 @@ impl Client, C> where "https" => { let connector = connector.https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; HyperClient::Https(hyper::client::Client::builder().build(connector)) }, _ => { @@ -244,7 +244,7 @@ impl Client, C let https_connector = Connector::builder() .https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -265,7 +265,7 @@ impl Client, C .https() .pin_server_certificate(ca_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -293,7 +293,7 @@ impl Client, C .pin_server_certificate(ca_certificate) .client_authentication(client_key, client_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } } @@ -425,18 +425,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( OpGetResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/no-example-v3/src/lib.rs b/samples/server/petstore/rust-server/output/no-example-v3/src/lib.rs index 100c47adac..05aca2b05b 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/src/lib.rs +++ b/samples/server/petstore/rust-server/output/no-example-v3/src/lib.rs @@ -1,4 +1,6 @@ #![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::blacklisted_name)] use async_trait::async_trait; use futures::Stream; @@ -9,8 +11,8 @@ use serde::{Serialize, Deserialize}; type ServiceError = Box; -pub const BASE_PATH: &'static str = ""; -pub const API_VERSION: &'static str = "0.0.1"; +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "0.0.1"; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum OpGetResponse { @@ -20,6 +22,7 @@ pub enum OpGetResponse { /// API #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait Api { fn poll_ready(&self, _cx: &mut Context) -> Poll>> { Poll::Ready(Ok(())) @@ -34,6 +37,7 @@ pub trait Api { /// API where `Context` isn't passed on every API call #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait ApiNoContext { fn poll_ready(&self, _cx: &mut Context) -> Poll>>; @@ -51,7 +55,7 @@ pub trait ApiNoContext { pub trait ContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> ContextWrapperExt for T { diff --git a/samples/server/petstore/rust-server/output/no-example-v3/src/models.rs b/samples/server/petstore/rust-server/output/no-example-v3/src/models.rs index fa170060bd..cc90dcda97 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/no-example-v3/src/models.rs @@ -14,6 +14,7 @@ pub struct OpGetRequest { } impl OpGetRequest { + #[allow(clippy::new_without_default)] pub fn new() -> OpGetRequest { OpGetRequest { propery: None, @@ -26,14 +27,18 @@ impl OpGetRequest { /// Should be implemented in a serde serializer impl std::string::ToString for OpGetRequest { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref propery) = self.propery { - params.push("propery".to_string()); - params.push(propery.to_string()); - } + self.propery.as_ref().map(|propery| { + vec![ + "propery".to_string(), + propery.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -44,8 +49,9 @@ impl std::str::FromStr for OpGetRequest { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub propery: Vec, } @@ -53,7 +59,7 @@ impl std::str::FromStr for OpGetRequest { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -63,8 +69,10 @@ impl std::str::FromStr for OpGetRequest { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "propery" => intermediate_rep.propery.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "propery" => intermediate_rep.propery.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing OpGetRequest".to_string()) } } diff --git a/samples/server/petstore/rust-server/output/no-example-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/no-example-v3/src/server/mod.rs index c8cced13d3..6bd3627a91 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/no-example-v3/src/server/mod.rs @@ -98,7 +98,7 @@ impl Service where { pub fn new(api_impl: T) -> Self { Service { - api_impl: api_impl, + api_impl, marker: PhantomData } } @@ -111,7 +111,7 @@ impl Clone for Service where fn clone(&self) -> Self { Service { api_impl: self.api_impl.clone(), - marker: self.marker.clone(), + marker: self.marker, } } } @@ -137,10 +137,10 @@ impl hyper::service::Service<(Request, C)> for Service where let (method, uri, headers) = (parts.method, parts.uri, parts.headers); let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); - match &method { + match method { // OpGet - GET /op - &hyper::Method::GET if path.matched(paths::ID_OP) => { + hyper::Method::GET if path.matched(paths::ID_OP) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -178,7 +178,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -225,9 +225,9 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { // OpGet - GET /op - &hyper::Method::GET if path.matched(paths::ID_OP) => Some("OpGet"), + hyper::Method::GET if path.matched(paths::ID_OP) => Some("OpGet"), _ => None, } } diff --git a/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml index aba7f549ea..43da25ffc9 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml @@ -390,7 +390,7 @@ paths: $ref: '#/components/schemas/StringObject' description: OK tags: - - Repo + - repo - Info /repos: post: @@ -459,11 +459,9 @@ paths: items: $ref: '#/components/schemas/StringObject' type: array - explode: true in: query name: list-of-strings required: false - style: form responses: "200": description: Success @@ -685,12 +683,14 @@ components: - FOO - BAR type: string + example: null _12345AnyOfObject_anyOf: enum: - FOO - BAR - '*' type: string + example: null securitySchemes: authScheme: flows: diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/ObjectHeader.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/ObjectHeader.md index a685cde3a4..c5fb58d312 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/docs/ObjectHeader.md +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/ObjectHeader.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **required_object_header** | **bool** | | -**optional_object_header** | **isize** | | [optional] [default to None] +**optional_object_header** | **i32** | | [optional] [default to None] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/ObjectParam.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/ObjectParam.md index 6191d5e078..caac197917 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/docs/ObjectParam.md +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/ObjectParam.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **required_param** | **bool** | | -**optional_param** | **isize** | | [optional] [default to None] +**optional_param** | **i32** | | [optional] [default to None] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlObject.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlObject.md index c7f413769b..49ab2bec0e 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlObject.md +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlObject.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **inner_string** | **String** | | [optional] [default to None] -**other_inner_rename** | **isize** | | [optional] [default to None] +**other_inner_rename** | **i32** | | [optional] [default to None] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/client/server.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/client/server.rs index fab67f0476..a66747e42d 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/examples/client/server.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/client/server.rs @@ -32,6 +32,7 @@ pub async fn create(addr: &str, https: bool) { let service = MakeAllowAllAuthenticator::new(service, "cosmo"); + #[allow(unused_mut)] let mut service = openapi_v3::server::context::MakeAddContext::<_, EmptyContext>::new( service diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server/server.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/server/server.rs index e2d19e2266..1fde6bbdf1 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server/server.rs @@ -32,6 +32,7 @@ pub async fn create(addr: &str, https: bool) { let service = MakeAllowAllAuthenticator::new(service, "cosmo"); + #[allow(unused_mut)] let mut service = openapi_v3::server::context::MakeAddContext::<_, EmptyContext>::new( service diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/client/callbacks.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/client/callbacks.rs index 082ae5911b..3f3d2b0cf8 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/client/callbacks.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/client/callbacks.rs @@ -38,12 +38,14 @@ mod paths { pub(crate) static ID_REQUEST_QUERY_URL_CALLBACK: usize = 0; lazy_static! { pub static ref REGEX_REQUEST_QUERY_URL_CALLBACK: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^/(?P.*)/callback$") .expect("Unable to create regex for REQUEST_QUERY_URL_CALLBACK"); } pub(crate) static ID_REQUEST_QUERY_URL_CALLBACK_WITH_HEADER: usize = 1; lazy_static! { pub static ref REGEX_REQUEST_QUERY_URL_CALLBACK_WITH_HEADER: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^/(?P.*)/callback-with-header$") .expect("Unable to create regex for REQUEST_QUERY_URL_CALLBACK_WITH_HEADER"); } @@ -112,7 +114,7 @@ impl Service where { pub fn new(api_impl: T) -> Self { Service { - api_impl: api_impl, + api_impl, marker: PhantomData } } @@ -125,7 +127,7 @@ impl Clone for Service where fn clone(&self) -> Self { Service { api_impl: self.api_impl.clone(), - marker: self.marker.clone(), + marker: self.marker, } } } @@ -151,15 +153,15 @@ impl hyper::service::Service<(Request, C)> for Service where let (method, uri, headers) = (parts.method, parts.uri, parts.headers); let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); - match &method { + match method { // CallbackCallbackWithHeaderPost - POST /{$request.query.url}/callback-with-header - &hyper::Method::POST if path.matched(paths::ID_REQUEST_QUERY_URL_CALLBACK_WITH_HEADER) => { + hyper::Method::POST if path.matched(paths::ID_REQUEST_QUERY_URL_CALLBACK_WITH_HEADER) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_REQUEST_QUERY_URL_CALLBACK_WITH_HEADER - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE REQUEST_QUERY_URL_CALLBACK_WITH_HEADER in set but failed match against \"{}\"", path, paths::REGEX_REQUEST_QUERY_URL_CALLBACK_WITH_HEADER.as_str()) ); @@ -193,7 +195,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -215,12 +217,12 @@ impl hyper::service::Service<(Request, C)> for Service where }, // CallbackCallbackPost - POST /{$request.query.url}/callback - &hyper::Method::POST if path.matched(paths::ID_REQUEST_QUERY_URL_CALLBACK) => { + hyper::Method::POST if path.matched(paths::ID_REQUEST_QUERY_URL_CALLBACK) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_REQUEST_QUERY_URL_CALLBACK - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE REQUEST_QUERY_URL_CALLBACK in set but failed match against \"{}\"", path, paths::REGEX_REQUEST_QUERY_URL_CALLBACK.as_str()) ); @@ -233,7 +235,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -268,11 +270,11 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { // CallbackCallbackWithHeaderPost - POST /{$request.query.url}/callback-with-header - &hyper::Method::POST if path.matched(paths::ID_REQUEST_QUERY_URL_CALLBACK_WITH_HEADER) => Some("CallbackCallbackWithHeaderPost"), + hyper::Method::POST if path.matched(paths::ID_REQUEST_QUERY_URL_CALLBACK_WITH_HEADER) => Some("CallbackCallbackWithHeaderPost"), // CallbackCallbackPost - POST /{$request.query.url}/callback - &hyper::Method::POST if path.matched(paths::ID_REQUEST_QUERY_URL_CALLBACK) => Some("CallbackCallbackPost"), + hyper::Method::POST if path.matched(paths::ID_REQUEST_QUERY_URL_CALLBACK) => Some("CallbackCallbackPost"), _ => None, } } diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs index 3e21905952..71a4af7133 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs @@ -80,7 +80,7 @@ fn into_base_path(input: impl TryInto, } } - let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let host = uri.host().ok_or(ClientInitError::MissingHost)?; let port = uri.port_u16().map(|x| format!(":{}", x)).unwrap_or_default(); Ok(format!("{}://{}{}{}", scheme, host, port, uri.path().trim_end_matches('/'))) } @@ -219,7 +219,7 @@ impl Client, C> where "https" => { let connector = connector.https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; HyperClient::Https(hyper::client::Client::builder().build(connector)) }, _ => { @@ -271,7 +271,7 @@ impl Client, C let https_connector = Connector::builder() .https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -292,7 +292,7 @@ impl Client, C .https() .pin_server_certificate(ca_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -320,7 +320,7 @@ impl Client, C .pin_server_certificate(ca_certificate) .client_authentication(client_key, client_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } } @@ -445,13 +445,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -532,7 +532,7 @@ impl Api for Client where let query_string = { let mut query_string = form_urlencoded::Serializer::new("".to_owned()); query_string.append_pair("url", - ¶m_url.to_string()); + ¶m_url); query_string.finish() }; if !query_string.is_empty() { @@ -553,18 +553,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 204 => { - let body = response.into_body(); Ok( CallbackWithHeaderPostResponse::OK ) @@ -627,18 +626,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( ComplexQueryParamGetResponse::Success ) @@ -698,18 +696,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( EnumInPathPathParamGetResponse::Success ) @@ -775,18 +772,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( JsonComplexQueryParamGetResponse::Success ) @@ -845,7 +841,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) @@ -854,6 +850,7 @@ impl Api for Client where // Header parameters request.headers_mut().append( HeaderName::from_static("x-header"), + #[allow(clippy::redundant_clone)] match header::IntoHeaderValue(param_x_header.clone()).try_into() { Ok(header) => header, Err(e) => { @@ -862,12 +859,11 @@ impl Api for Client where }, }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( MandatoryRequestHeaderGetResponse::Success ) @@ -925,13 +921,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -1002,13 +998,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -1158,14 +1154,16 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -1181,12 +1179,11 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( MultipleAuthSchemeGetResponse::CheckThatLimitingToMultipleRequiredAuthSchemesWorks ) @@ -1244,13 +1241,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -1321,18 +1318,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 204 => { - let body = response.into_body(); Ok( OverrideServerGetResponse::Success ) @@ -1405,13 +1401,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -1482,14 +1478,16 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -1505,12 +1503,11 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( ReadonlyAuthSchemeGetResponse::CheckThatLimitingToASingleRequiredAuthSchemeWorks ) @@ -1550,7 +1547,7 @@ impl Api for Client where let query_string = { let mut query_string = form_urlencoded::Serializer::new("".to_owned()); query_string.append_pair("url", - ¶m_url.to_string()); + ¶m_url); query_string.finish() }; if !query_string.is_empty() { @@ -1571,18 +1568,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 204 => { - let body = response.into_body(); Ok( RegisterCallbackPostResponse::OK ) @@ -1649,18 +1645,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( RequiredOctetStreamPutResponse::OK ) @@ -1718,13 +1713,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -1738,8 +1733,7 @@ impl Api for Client where return Err(ApiError(format!("Invalid response header Success-Info for response 200 - {}", e))); }, }; - let response_success_info = response_success_info.0; - response_success_info + response_success_info.0 }, None => return Err(ApiError(String::from("Required response header Success-Info for response 200 was not found."))), }; @@ -1753,8 +1747,7 @@ impl Api for Client where return Err(ApiError(format!("Invalid response header Bool-Header for response 200 - {}", e))); }, }; - let response_bool_header = response_bool_header.0; - Some(response_bool_header) + Some(response_bool_header.0) }, None => None, }; @@ -1768,8 +1761,7 @@ impl Api for Client where return Err(ApiError(format!("Invalid response header Object-Header for response 200 - {}", e))); }, }; - let response_object_header = response_object_header.0; - Some(response_object_header) + Some(response_object_header.0) }, None => None, }; @@ -1785,7 +1777,7 @@ impl Api for Client where })?; Ok(ResponsesWithHeadersGetResponse::Success { - body: body, + body, success_info: response_success_info, bool_header: response_bool_header, object_header: response_object_header, @@ -1802,8 +1794,7 @@ impl Api for Client where return Err(ApiError(format!("Invalid response header Further-Info for response 412 - {}", e))); }, }; - let response_further_info = response_further_info.0; - Some(response_further_info) + Some(response_further_info.0) }, None => None, }; @@ -1817,13 +1808,11 @@ impl Api for Client where return Err(ApiError(format!("Invalid response header Failure-Info for response 412 - {}", e))); }, }; - let response_failure_info = response_failure_info.0; - Some(response_failure_info) + Some(response_failure_info.0) }, None => None, }; - let body = response.into_body(); Ok( ResponsesWithHeadersGetResponse::PreconditionFailed { @@ -1885,13 +1874,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2004,18 +1993,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( UntypedPropertyGetResponse::CheckThatUntypedPropertiesWorks ) @@ -2073,13 +2061,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2152,7 +2140,7 @@ impl Api for Client where }; let body = param_duplicate_xml_object.map(|ref body| { - body.to_xml() + body.as_xml() }); if let Some(body) = body { *request.body_mut() = Body::from(body); @@ -2163,24 +2151,22 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 201 => { - let body = response.into_body(); Ok( XmlExtraPostResponse::OK ) } 400 => { - let body = response.into_body(); Ok( XmlExtraPostResponse::BadRequest ) @@ -2240,7 +2226,7 @@ impl Api for Client where }; let body = param_another_xml_object.map(|ref body| { - body.to_xml() + body.as_xml() }); if let Some(body) = body { *request.body_mut() = Body::from(body); @@ -2251,13 +2237,13 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2277,7 +2263,6 @@ impl Api for Client where ) } 400 => { - let body = response.into_body(); Ok( XmlOtherPostResponse::BadRequest ) @@ -2337,7 +2322,7 @@ impl Api for Client where }; let body = param_another_xml_array.map(|ref body| { - body.to_xml() + body.as_xml() }); if let Some(body) = body { *request.body_mut() = Body::from(body); @@ -2348,24 +2333,22 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 201 => { - let body = response.into_body(); Ok( XmlOtherPutResponse::OK ) } 400 => { - let body = response.into_body(); Ok( XmlOtherPutResponse::BadRequest ) @@ -2425,7 +2408,7 @@ impl Api for Client where }; let body = param_xml_array.map(|ref body| { - body.to_xml() + body.as_xml() }); if let Some(body) = body { *request.body_mut() = Body::from(body); @@ -2436,24 +2419,22 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 201 => { - let body = response.into_body(); Ok( XmlPostResponse::OK ) } 400 => { - let body = response.into_body(); Ok( XmlPostResponse::BadRequest ) @@ -2513,7 +2494,7 @@ impl Api for Client where }; let body = param_xml_object.map(|ref body| { - body.to_xml() + body.as_xml() }); if let Some(body) = body { @@ -2526,24 +2507,22 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 201 => { - let body = response.into_body(); Ok( XmlPutResponse::OK ) } 400 => { - let body = response.into_body(); Ok( XmlPutResponse::BadRequest ) @@ -2611,18 +2590,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( CreateRepoResponse::Success ) @@ -2682,13 +2660,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/context.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/context.rs index 6f03005325..ac1c07864b 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/context.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/context.rs @@ -107,7 +107,7 @@ impl Service> for AddContext(&headers) { + if let Some(bearer) = swagger::auth::from_headers::(headers) { let auth_data = AuthData::Bearer(bearer); let context = context.push(Some(auth_data)); let context = context.push(None::); diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs index 61da16ceba..1f5793d8bf 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs @@ -1,4 +1,6 @@ #![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::blacklisted_name)] use async_trait::async_trait; use futures::Stream; @@ -9,8 +11,8 @@ use serde::{Serialize, Deserialize}; type ServiceError = Box; -pub const BASE_PATH: &'static str = ""; -pub const API_VERSION: &'static str = "1.0.7"; +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "1.0.7"; #[derive(Debug, PartialEq, Serialize, Deserialize)] #[must_use] @@ -272,6 +274,7 @@ pub enum GetRepoInfoResponse { /// API #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait Api { fn poll_ready(&self, _cx: &mut Context) -> Poll>> { Poll::Ready(Ok(())) @@ -407,6 +410,7 @@ pub trait Api { /// API where `Context` isn't passed on every API call #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait ApiNoContext { fn poll_ready(&self, _cx: &mut Context) -> Poll>>; @@ -545,7 +549,7 @@ pub trait ApiNoContext { pub trait ContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> ContextWrapperExt for T { @@ -853,7 +857,7 @@ pub trait CallbackApiNoContext { pub trait CallbackContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> CallbackContextWrapperExt for T { diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs index 8f9ceabecc..2f238bd1d9 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -58,7 +58,7 @@ impl AdditionalPropertiesWithList { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -111,7 +111,7 @@ impl<'a> std::iter::IntoIterator for &'a AnotherXmlArray { type IntoIter = std::slice::Iter<'a, String>; fn into_iter(self) -> Self::IntoIter { - (&self.0).into_iter() + (&self.0).iter() } } @@ -120,7 +120,7 @@ impl<'a> std::iter::IntoIterator for &'a mut AnotherXmlArray { type IntoIter = std::slice::IterMut<'a, String>; fn into_iter(self) -> Self::IntoIter { - (&mut self.0).into_iter() + (&mut self.0).iter_mut() } } @@ -142,7 +142,7 @@ impl std::ops::DerefMut for AnotherXmlArray { /// Should be implemented in a serde serializer impl std::string::ToString for AnotherXmlArray { fn to_string(&self) -> String { - self.iter().map(|x| x.to_string()).collect::>().join(",").to_string() + self.iter().map(|x| x.to_string()).collect::>().join(",") } } @@ -206,7 +206,7 @@ impl AnotherXmlArray { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -259,7 +259,7 @@ impl AnotherXmlInner { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -276,6 +276,7 @@ pub struct AnotherXmlObject { } impl AnotherXmlObject { + #[allow(clippy::new_without_default)] pub fn new() -> AnotherXmlObject { AnotherXmlObject { inner_string: None, @@ -288,14 +289,18 @@ impl AnotherXmlObject { /// Should be implemented in a serde serializer impl std::string::ToString for AnotherXmlObject { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref inner_string) = self.inner_string { - params.push("inner_string".to_string()); - params.push(inner_string.to_string()); - } + self.inner_string.as_ref().map(|inner_string| { + vec![ + "inner_string".to_string(), + inner_string.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -306,8 +311,9 @@ impl std::str::FromStr for AnotherXmlObject { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub inner_string: Vec, } @@ -315,7 +321,7 @@ impl std::str::FromStr for AnotherXmlObject { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -325,8 +331,10 @@ impl std::str::FromStr for AnotherXmlObject { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "inner_string" => intermediate_rep.inner_string.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "inner_string" => intermediate_rep.inner_string.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing AnotherXmlObject".to_string()) } } @@ -391,7 +399,7 @@ impl AnotherXmlObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); @@ -405,6 +413,7 @@ pub struct AnyOfGet202Response { } impl AnyOfGet202Response { + #[allow(clippy::new_without_default)] pub fn new() -> AnyOfGet202Response { AnyOfGet202Response { } @@ -416,8 +425,10 @@ impl AnyOfGet202Response { /// Should be implemented in a serde serializer impl std::string::ToString for AnyOfGet202Response { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - params.join(",").to_string() + let params: Vec> = vec![ + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -428,15 +439,16 @@ impl std::str::FromStr for AnyOfGet202Response { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -446,6 +458,7 @@ impl std::str::FromStr for AnyOfGet202Response { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { _ => return std::result::Result::Err("Unexpected key while parsing AnyOfGet202Response".to_string()) } @@ -504,7 +517,7 @@ impl AnyOfGet202Response { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -516,6 +529,7 @@ pub struct AnyOfObject { } impl AnyOfObject { + #[allow(clippy::new_without_default)] pub fn new() -> AnyOfObject { AnyOfObject { } @@ -527,8 +541,10 @@ impl AnyOfObject { /// Should be implemented in a serde serializer impl std::string::ToString for AnyOfObject { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - params.join(",").to_string() + let params: Vec> = vec![ + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -539,15 +555,16 @@ impl std::str::FromStr for AnyOfObject { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -557,6 +574,7 @@ impl std::str::FromStr for AnyOfObject { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { _ => return std::result::Result::Err("Unexpected key while parsing AnyOfObject".to_string()) } @@ -615,7 +633,7 @@ impl AnyOfObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -629,16 +647,16 @@ impl AnyOfObject { #[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] pub enum AnyOfObjectAnyOf { #[serde(rename = "FOO")] - FOO, + Foo, #[serde(rename = "BAR")] - BAR, + Bar, } impl std::fmt::Display for AnyOfObjectAnyOf { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { - AnyOfObjectAnyOf::FOO => write!(f, "{}", "FOO"), - AnyOfObjectAnyOf::BAR => write!(f, "{}", "BAR"), + AnyOfObjectAnyOf::Foo => write!(f, "FOO"), + AnyOfObjectAnyOf::Bar => write!(f, "BAR"), } } } @@ -648,8 +666,8 @@ impl std::str::FromStr for AnyOfObjectAnyOf { fn from_str(s: &str) -> std::result::Result { match s { - "FOO" => std::result::Result::Ok(AnyOfObjectAnyOf::FOO), - "BAR" => std::result::Result::Ok(AnyOfObjectAnyOf::BAR), + "FOO" => std::result::Result::Ok(AnyOfObjectAnyOf::Foo), + "BAR" => std::result::Result::Ok(AnyOfObjectAnyOf::Bar), _ => std::result::Result::Err(format!("Value not valid: {}", s)), } } @@ -659,7 +677,7 @@ impl AnyOfObjectAnyOf { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -678,9 +696,10 @@ pub struct AnyOfProperty { } impl AnyOfProperty { + #[allow(clippy::new_without_default)] pub fn new(required_any_of: models::AnyOfObject, ) -> AnyOfProperty { AnyOfProperty { - required_any_of: required_any_of, + required_any_of, optional_any_of: None, } } @@ -691,12 +710,14 @@ impl AnyOfProperty { /// Should be implemented in a serde serializer impl std::string::ToString for AnyOfProperty { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping requiredAnyOf in query parameter serialization + let params: Vec> = vec![ + // Skipping requiredAnyOf in query parameter serialization - // Skipping optionalAnyOf in query parameter serialization + // Skipping optionalAnyOf in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -707,8 +728,9 @@ impl std::str::FromStr for AnyOfProperty { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub required_any_of: Vec, pub optional_any_of: Vec, @@ -717,7 +739,7 @@ impl std::str::FromStr for AnyOfProperty { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -727,9 +749,12 @@ impl std::str::FromStr for AnyOfProperty { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "requiredAnyOf" => intermediate_rep.required_any_of.push(::from_str(val).map_err(|x| format!("{}", x))?), - "optionalAnyOf" => intermediate_rep.optional_any_of.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "requiredAnyOf" => intermediate_rep.required_any_of.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "optionalAnyOf" => intermediate_rep.optional_any_of.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing AnyOfProperty".to_string()) } } @@ -740,7 +765,7 @@ impl std::str::FromStr for AnyOfProperty { // Use the intermediate representation to return the struct std::result::Result::Ok(AnyOfProperty { - required_any_of: intermediate_rep.required_any_of.into_iter().next().ok_or("requiredAnyOf missing in AnyOfProperty".to_string())?, + required_any_of: intermediate_rep.required_any_of.into_iter().next().ok_or_else(|| "requiredAnyOf missing in AnyOfProperty".to_string())?, optional_any_of: intermediate_rep.optional_any_of.into_iter().next(), }) } @@ -789,7 +814,7 @@ impl AnyOfProperty { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -810,10 +835,11 @@ pub struct DuplicateXmlObject { } impl DuplicateXmlObject { + #[allow(clippy::new_without_default)] pub fn new(inner_array: models::XmlArray, ) -> DuplicateXmlObject { DuplicateXmlObject { inner_string: None, - inner_array: inner_array, + inner_array, } } } @@ -823,16 +849,20 @@ impl DuplicateXmlObject { /// Should be implemented in a serde serializer impl std::string::ToString for DuplicateXmlObject { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref inner_string) = self.inner_string { - params.push("inner_string".to_string()); - params.push(inner_string.to_string()); - } + self.inner_string.as_ref().map(|inner_string| { + vec![ + "inner_string".to_string(), + inner_string.to_string(), + ].join(",") + }), - // Skipping inner_array in query parameter serialization + // Skipping inner_array in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -843,8 +873,9 @@ impl std::str::FromStr for DuplicateXmlObject { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub inner_string: Vec, pub inner_array: Vec, @@ -853,7 +884,7 @@ impl std::str::FromStr for DuplicateXmlObject { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -863,9 +894,12 @@ impl std::str::FromStr for DuplicateXmlObject { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "inner_string" => intermediate_rep.inner_string.push(::from_str(val).map_err(|x| format!("{}", x))?), - "inner_array" => intermediate_rep.inner_array.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "inner_string" => intermediate_rep.inner_string.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "inner_array" => intermediate_rep.inner_array.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing DuplicateXmlObject".to_string()) } } @@ -877,7 +911,7 @@ impl std::str::FromStr for DuplicateXmlObject { // Use the intermediate representation to return the struct std::result::Result::Ok(DuplicateXmlObject { inner_string: intermediate_rep.inner_string.into_iter().next(), - inner_array: intermediate_rep.inner_array.into_iter().next().ok_or("inner_array missing in DuplicateXmlObject".to_string())?, + inner_array: intermediate_rep.inner_array.into_iter().next().ok_or_else(|| "inner_array missing in DuplicateXmlObject".to_string())?, }) } } @@ -931,7 +965,7 @@ impl DuplicateXmlObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); @@ -949,19 +983,19 @@ impl DuplicateXmlObject { #[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] pub enum EnumWithStarObject { #[serde(rename = "FOO")] - FOO, + Foo, #[serde(rename = "BAR")] - BAR, + Bar, #[serde(rename = "*")] - STAR, + Star, } impl std::fmt::Display for EnumWithStarObject { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { - EnumWithStarObject::FOO => write!(f, "{}", "FOO"), - EnumWithStarObject::BAR => write!(f, "{}", "BAR"), - EnumWithStarObject::STAR => write!(f, "{}", "*"), + EnumWithStarObject::Foo => write!(f, "FOO"), + EnumWithStarObject::Bar => write!(f, "BAR"), + EnumWithStarObject::Star => write!(f, "*"), } } } @@ -971,9 +1005,9 @@ impl std::str::FromStr for EnumWithStarObject { fn from_str(s: &str) -> std::result::Result { match s { - "FOO" => std::result::Result::Ok(EnumWithStarObject::FOO), - "BAR" => std::result::Result::Ok(EnumWithStarObject::BAR), - "*" => std::result::Result::Ok(EnumWithStarObject::STAR), + "FOO" => std::result::Result::Ok(EnumWithStarObject::Foo), + "BAR" => std::result::Result::Ok(EnumWithStarObject::Bar), + "*" => std::result::Result::Ok(EnumWithStarObject::Star), _ => std::result::Result::Err(format!("Value not valid: {}", s)), } } @@ -983,7 +1017,7 @@ impl EnumWithStarObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1035,7 +1069,7 @@ impl Err { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1087,7 +1121,7 @@ impl Error { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1099,6 +1133,7 @@ pub struct Model12345AnyOfObject { } impl Model12345AnyOfObject { + #[allow(clippy::new_without_default)] pub fn new() -> Model12345AnyOfObject { Model12345AnyOfObject { } @@ -1110,8 +1145,10 @@ impl Model12345AnyOfObject { /// Should be implemented in a serde serializer impl std::string::ToString for Model12345AnyOfObject { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - params.join(",").to_string() + let params: Vec> = vec![ + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1122,15 +1159,16 @@ impl std::str::FromStr for Model12345AnyOfObject { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1140,6 +1178,7 @@ impl std::str::FromStr for Model12345AnyOfObject { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { _ => return std::result::Result::Err("Unexpected key while parsing Model12345AnyOfObject".to_string()) } @@ -1198,7 +1237,7 @@ impl Model12345AnyOfObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1212,19 +1251,19 @@ impl Model12345AnyOfObject { #[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] pub enum Model12345AnyOfObjectAnyOf { #[serde(rename = "FOO")] - FOO, + Foo, #[serde(rename = "BAR")] - BAR, + Bar, #[serde(rename = "*")] - STAR, + Star, } impl std::fmt::Display for Model12345AnyOfObjectAnyOf { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { - Model12345AnyOfObjectAnyOf::FOO => write!(f, "{}", "FOO"), - Model12345AnyOfObjectAnyOf::BAR => write!(f, "{}", "BAR"), - Model12345AnyOfObjectAnyOf::STAR => write!(f, "{}", "*"), + Model12345AnyOfObjectAnyOf::Foo => write!(f, "FOO"), + Model12345AnyOfObjectAnyOf::Bar => write!(f, "BAR"), + Model12345AnyOfObjectAnyOf::Star => write!(f, "*"), } } } @@ -1234,9 +1273,9 @@ impl std::str::FromStr for Model12345AnyOfObjectAnyOf { fn from_str(s: &str) -> std::result::Result { match s { - "FOO" => std::result::Result::Ok(Model12345AnyOfObjectAnyOf::FOO), - "BAR" => std::result::Result::Ok(Model12345AnyOfObjectAnyOf::BAR), - "*" => std::result::Result::Ok(Model12345AnyOfObjectAnyOf::STAR), + "FOO" => std::result::Result::Ok(Model12345AnyOfObjectAnyOf::Foo), + "BAR" => std::result::Result::Ok(Model12345AnyOfObjectAnyOf::Bar), + "*" => std::result::Result::Ok(Model12345AnyOfObjectAnyOf::Star), _ => std::result::Result::Err(format!("Value not valid: {}", s)), } } @@ -1246,7 +1285,7 @@ impl Model12345AnyOfObjectAnyOf { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1261,6 +1300,7 @@ pub struct MultigetGet201Response { } impl MultigetGet201Response { + #[allow(clippy::new_without_default)] pub fn new() -> MultigetGet201Response { MultigetGet201Response { foo: None, @@ -1273,14 +1313,18 @@ impl MultigetGet201Response { /// Should be implemented in a serde serializer impl std::string::ToString for MultigetGet201Response { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref foo) = self.foo { - params.push("foo".to_string()); - params.push(foo.to_string()); - } + self.foo.as_ref().map(|foo| { + vec![ + "foo".to_string(), + foo.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1291,8 +1335,9 @@ impl std::str::FromStr for MultigetGet201Response { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub foo: Vec, } @@ -1300,7 +1345,7 @@ impl std::str::FromStr for MultigetGet201Response { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1310,8 +1355,10 @@ impl std::str::FromStr for MultigetGet201Response { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "foo" => intermediate_rep.foo.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "foo" => intermediate_rep.foo.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing MultigetGet201Response".to_string()) } } @@ -1370,7 +1417,7 @@ impl MultigetGet201Response { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1409,7 +1456,7 @@ impl MyId { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1452,7 +1499,7 @@ impl<'a> std::iter::IntoIterator for &'a MyIdList { type IntoIter = std::slice::Iter<'a, i32>; fn into_iter(self) -> Self::IntoIter { - (&self.0).into_iter() + (&self.0).iter() } } @@ -1461,7 +1508,7 @@ impl<'a> std::iter::IntoIterator for &'a mut MyIdList { type IntoIter = std::slice::IterMut<'a, i32>; fn into_iter(self) -> Self::IntoIter { - (&mut self.0).into_iter() + (&mut self.0).iter_mut() } } @@ -1483,7 +1530,7 @@ impl std::ops::DerefMut for MyIdList { /// Should be implemented in a serde serializer impl std::string::ToString for MyIdList { fn to_string(&self) -> String { - self.iter().map(|x| x.to_string()).collect::>().join(",").to_string() + self.iter().map(|x| x.to_string()).collect::>().join(",") } } @@ -1547,7 +1594,7 @@ impl MyIdList { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1585,9 +1632,10 @@ pub struct NullableTest { } impl NullableTest { + #[allow(clippy::new_without_default)] pub fn new(nullable: swagger::Nullable, ) -> NullableTest { NullableTest { - nullable: nullable, + nullable, nullable_with_null_default: None, nullable_with_present_default: Some(swagger::Nullable::Present("default".to_string())), nullable_with_no_default: None, @@ -1601,36 +1649,46 @@ impl NullableTest { /// Should be implemented in a serde serializer impl std::string::ToString for NullableTest { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("nullable".to_string()); - params.push(self.nullable.as_ref().map_or("null".to_string(), |x| x.to_string())); + Some("nullable".to_string()), + Some(self.nullable.as_ref().map_or("null".to_string(), |x| x.to_string())), - if let Some(ref nullable_with_null_default) = self.nullable_with_null_default { - params.push("nullableWithNullDefault".to_string()); - params.push(nullable_with_null_default.as_ref().map_or("null".to_string(), |x| x.to_string())); - } + self.nullable_with_null_default.as_ref().map(|nullable_with_null_default| { + vec![ + "nullableWithNullDefault".to_string(), + nullable_with_null_default.as_ref().map_or("null".to_string(), |x| x.to_string()), + ].join(",") + }), - if let Some(ref nullable_with_present_default) = self.nullable_with_present_default { - params.push("nullableWithPresentDefault".to_string()); - params.push(nullable_with_present_default.as_ref().map_or("null".to_string(), |x| x.to_string())); - } + self.nullable_with_present_default.as_ref().map(|nullable_with_present_default| { + vec![ + "nullableWithPresentDefault".to_string(), + nullable_with_present_default.as_ref().map_or("null".to_string(), |x| x.to_string()), + ].join(",") + }), - if let Some(ref nullable_with_no_default) = self.nullable_with_no_default { - params.push("nullableWithNoDefault".to_string()); - params.push(nullable_with_no_default.as_ref().map_or("null".to_string(), |x| x.to_string())); - } + self.nullable_with_no_default.as_ref().map(|nullable_with_no_default| { + vec![ + "nullableWithNoDefault".to_string(), + nullable_with_no_default.as_ref().map_or("null".to_string(), |x| x.to_string()), + ].join(",") + }), - if let Some(ref nullable_array) = self.nullable_array { - params.push("nullableArray".to_string()); - params.push(nullable_array.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",").to_string())); - } + self.nullable_array.as_ref().map(|nullable_array| { + vec![ + "nullableArray".to_string(), + nullable_array.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",")), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1641,8 +1699,9 @@ impl std::str::FromStr for NullableTest { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub nullable: Vec, pub nullable_with_null_default: Vec, @@ -1654,7 +1713,7 @@ impl std::str::FromStr for NullableTest { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1664,6 +1723,7 @@ impl std::str::FromStr for NullableTest { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { "nullable" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in NullableTest".to_string()), "nullableWithNullDefault" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in NullableTest".to_string()), @@ -1732,7 +1792,7 @@ impl NullableTest { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1745,14 +1805,15 @@ pub struct ObjectHeader { #[serde(rename = "optionalObjectHeader")] #[serde(skip_serializing_if="Option::is_none")] - pub optional_object_header: Option, + pub optional_object_header: Option, } impl ObjectHeader { + #[allow(clippy::new_without_default)] pub fn new(required_object_header: bool, ) -> ObjectHeader { ObjectHeader { - required_object_header: required_object_header, + required_object_header, optional_object_header: None, } } @@ -1763,18 +1824,22 @@ impl ObjectHeader { /// Should be implemented in a serde serializer impl std::string::ToString for ObjectHeader { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("requiredObjectHeader".to_string()); - params.push(self.required_object_header.to_string()); + Some("requiredObjectHeader".to_string()), + Some(self.required_object_header.to_string()), - if let Some(ref optional_object_header) = self.optional_object_header { - params.push("optionalObjectHeader".to_string()); - params.push(optional_object_header.to_string()); - } + self.optional_object_header.as_ref().map(|optional_object_header| { + vec![ + "optionalObjectHeader".to_string(), + optional_object_header.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1785,17 +1850,18 @@ impl std::str::FromStr for ObjectHeader { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub required_object_header: Vec, - pub optional_object_header: Vec, + pub optional_object_header: Vec, } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1805,9 +1871,12 @@ impl std::str::FromStr for ObjectHeader { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "requiredObjectHeader" => intermediate_rep.required_object_header.push(::from_str(val).map_err(|x| format!("{}", x))?), - "optionalObjectHeader" => intermediate_rep.optional_object_header.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "requiredObjectHeader" => intermediate_rep.required_object_header.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "optionalObjectHeader" => intermediate_rep.optional_object_header.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing ObjectHeader".to_string()) } } @@ -1818,7 +1887,7 @@ impl std::str::FromStr for ObjectHeader { // Use the intermediate representation to return the struct std::result::Result::Ok(ObjectHeader { - required_object_header: intermediate_rep.required_object_header.into_iter().next().ok_or("requiredObjectHeader missing in ObjectHeader".to_string())?, + required_object_header: intermediate_rep.required_object_header.into_iter().next().ok_or_else(|| "requiredObjectHeader missing in ObjectHeader".to_string())?, optional_object_header: intermediate_rep.optional_object_header.into_iter().next(), }) } @@ -1867,7 +1936,7 @@ impl ObjectHeader { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1880,14 +1949,15 @@ pub struct ObjectParam { #[serde(rename = "optionalParam")] #[serde(skip_serializing_if="Option::is_none")] - pub optional_param: Option, + pub optional_param: Option, } impl ObjectParam { + #[allow(clippy::new_without_default)] pub fn new(required_param: bool, ) -> ObjectParam { ObjectParam { - required_param: required_param, + required_param, optional_param: None, } } @@ -1898,18 +1968,22 @@ impl ObjectParam { /// Should be implemented in a serde serializer impl std::string::ToString for ObjectParam { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("requiredParam".to_string()); - params.push(self.required_param.to_string()); + Some("requiredParam".to_string()), + Some(self.required_param.to_string()), - if let Some(ref optional_param) = self.optional_param { - params.push("optionalParam".to_string()); - params.push(optional_param.to_string()); - } + self.optional_param.as_ref().map(|optional_param| { + vec![ + "optionalParam".to_string(), + optional_param.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1920,17 +1994,18 @@ impl std::str::FromStr for ObjectParam { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub required_param: Vec, - pub optional_param: Vec, + pub optional_param: Vec, } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1940,9 +2015,12 @@ impl std::str::FromStr for ObjectParam { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "requiredParam" => intermediate_rep.required_param.push(::from_str(val).map_err(|x| format!("{}", x))?), - "optionalParam" => intermediate_rep.optional_param.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "requiredParam" => intermediate_rep.required_param.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "optionalParam" => intermediate_rep.optional_param.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing ObjectParam".to_string()) } } @@ -1953,7 +2031,7 @@ impl std::str::FromStr for ObjectParam { // Use the intermediate representation to return the struct std::result::Result::Ok(ObjectParam { - required_param: intermediate_rep.required_param.into_iter().next().ok_or("requiredParam missing in ObjectParam".to_string())?, + required_param: intermediate_rep.required_param.into_iter().next().ok_or_else(|| "requiredParam missing in ObjectParam".to_string())?, optional_param: intermediate_rep.optional_param.into_iter().next(), }) } @@ -2002,7 +2080,7 @@ impl ObjectParam { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2027,10 +2105,11 @@ pub struct ObjectUntypedProps { } impl ObjectUntypedProps { + #[allow(clippy::new_without_default)] pub fn new(required_untyped: serde_json::Value, required_untyped_nullable: swagger::Nullable, ) -> ObjectUntypedProps { ObjectUntypedProps { - required_untyped: required_untyped, - required_untyped_nullable: required_untyped_nullable, + required_untyped, + required_untyped_nullable, not_required_untyped: None, not_required_untyped_nullable: None, } @@ -2042,16 +2121,18 @@ impl ObjectUntypedProps { /// Should be implemented in a serde serializer impl std::string::ToString for ObjectUntypedProps { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping required_untyped in query parameter serialization + let params: Vec> = vec![ + // Skipping required_untyped in query parameter serialization - // Skipping required_untyped_nullable in query parameter serialization + // Skipping required_untyped_nullable in query parameter serialization - // Skipping not_required_untyped in query parameter serialization + // Skipping not_required_untyped in query parameter serialization - // Skipping not_required_untyped_nullable in query parameter serialization + // Skipping not_required_untyped_nullable in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2062,8 +2143,9 @@ impl std::str::FromStr for ObjectUntypedProps { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub required_untyped: Vec, pub required_untyped_nullable: Vec, @@ -2074,7 +2156,7 @@ impl std::str::FromStr for ObjectUntypedProps { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2084,11 +2166,15 @@ impl std::str::FromStr for ObjectUntypedProps { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "required_untyped" => intermediate_rep.required_untyped.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "required_untyped" => intermediate_rep.required_untyped.push(::from_str(val).map_err(|x| x.to_string())?), "required_untyped_nullable" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in ObjectUntypedProps".to_string()), - "not_required_untyped" => intermediate_rep.not_required_untyped.push(::from_str(val).map_err(|x| format!("{}", x))?), - "not_required_untyped_nullable" => intermediate_rep.not_required_untyped_nullable.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "not_required_untyped" => intermediate_rep.not_required_untyped.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "not_required_untyped_nullable" => intermediate_rep.not_required_untyped_nullable.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing ObjectUntypedProps".to_string()) } } @@ -2099,7 +2185,7 @@ impl std::str::FromStr for ObjectUntypedProps { // Use the intermediate representation to return the struct std::result::Result::Ok(ObjectUntypedProps { - required_untyped: intermediate_rep.required_untyped.into_iter().next().ok_or("required_untyped missing in ObjectUntypedProps".to_string())?, + required_untyped: intermediate_rep.required_untyped.into_iter().next().ok_or_else(|| "required_untyped missing in ObjectUntypedProps".to_string())?, required_untyped_nullable: std::result::Result::Err("Nullable types not supported in ObjectUntypedProps".to_string())?, not_required_untyped: intermediate_rep.not_required_untyped.into_iter().next(), not_required_untyped_nullable: intermediate_rep.not_required_untyped_nullable.into_iter().next(), @@ -2150,7 +2236,7 @@ impl ObjectUntypedProps { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2165,6 +2251,7 @@ pub struct ObjectWithArrayOfObjects { } impl ObjectWithArrayOfObjects { + #[allow(clippy::new_without_default)] pub fn new() -> ObjectWithArrayOfObjects { ObjectWithArrayOfObjects { object_array: None, @@ -2177,14 +2264,18 @@ impl ObjectWithArrayOfObjects { /// Should be implemented in a serde serializer impl std::string::ToString for ObjectWithArrayOfObjects { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref object_array) = self.object_array { - params.push("objectArray".to_string()); - params.push(object_array.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - } + self.object_array.as_ref().map(|object_array| { + vec![ + "objectArray".to_string(), + object_array.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2195,8 +2286,9 @@ impl std::str::FromStr for ObjectWithArrayOfObjects { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub object_array: Vec>, } @@ -2204,7 +2296,7 @@ impl std::str::FromStr for ObjectWithArrayOfObjects { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2214,6 +2306,7 @@ impl std::str::FromStr for ObjectWithArrayOfObjects { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { "objectArray" => return std::result::Result::Err("Parsing a container in this style is not supported in ObjectWithArrayOfObjects".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing ObjectWithArrayOfObjects".to_string()) @@ -2274,7 +2367,7 @@ impl ObjectWithArrayOfObjects { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2326,7 +2419,7 @@ impl Ok { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2337,6 +2430,7 @@ pub struct OneOfGet200Response { } impl OneOfGet200Response { + #[allow(clippy::new_without_default)] pub fn new() -> OneOfGet200Response { OneOfGet200Response { } @@ -2348,8 +2442,10 @@ impl OneOfGet200Response { /// Should be implemented in a serde serializer impl std::string::ToString for OneOfGet200Response { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - params.join(",").to_string() + let params: Vec> = vec![ + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2360,15 +2456,16 @@ impl std::str::FromStr for OneOfGet200Response { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2378,6 +2475,7 @@ impl std::str::FromStr for OneOfGet200Response { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { _ => return std::result::Result::Err("Unexpected key while parsing OneOfGet200Response".to_string()) } @@ -2436,7 +2534,7 @@ impl OneOfGet200Response { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2475,7 +2573,7 @@ impl OptionalObjectHeader { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2514,7 +2612,7 @@ impl RequiredObjectHeader { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2566,7 +2664,7 @@ impl Result { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2580,16 +2678,16 @@ impl Result { #[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] pub enum StringEnum { #[serde(rename = "FOO")] - FOO, + Foo, #[serde(rename = "BAR")] - BAR, + Bar, } impl std::fmt::Display for StringEnum { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { - StringEnum::FOO => write!(f, "{}", "FOO"), - StringEnum::BAR => write!(f, "{}", "BAR"), + StringEnum::Foo => write!(f, "FOO"), + StringEnum::Bar => write!(f, "BAR"), } } } @@ -2599,8 +2697,8 @@ impl std::str::FromStr for StringEnum { fn from_str(s: &str) -> std::result::Result { match s { - "FOO" => std::result::Result::Ok(StringEnum::FOO), - "BAR" => std::result::Result::Ok(StringEnum::BAR), + "FOO" => std::result::Result::Ok(StringEnum::Foo), + "BAR" => std::result::Result::Ok(StringEnum::Bar), _ => std::result::Result::Err(format!("Value not valid: {}", s)), } } @@ -2610,7 +2708,7 @@ impl StringEnum { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2662,7 +2760,7 @@ impl StringObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2702,7 +2800,7 @@ impl UuidObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2755,7 +2853,7 @@ impl<'a> std::iter::IntoIterator for &'a XmlArray { type IntoIter = std::slice::Iter<'a, String>; fn into_iter(self) -> Self::IntoIter { - (&self.0).into_iter() + (&self.0).iter() } } @@ -2764,7 +2862,7 @@ impl<'a> std::iter::IntoIterator for &'a mut XmlArray { type IntoIter = std::slice::IterMut<'a, String>; fn into_iter(self) -> Self::IntoIter { - (&mut self.0).into_iter() + (&mut self.0).iter_mut() } } @@ -2786,7 +2884,7 @@ impl std::ops::DerefMut for XmlArray { /// Should be implemented in a serde serializer impl std::string::ToString for XmlArray { fn to_string(&self) -> String { - self.iter().map(|x| x.to_string()).collect::>().join(",").to_string() + self.iter().map(|x| x.to_string()).collect::>().join(",") } } @@ -2850,7 +2948,7 @@ impl XmlArray { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2903,7 +3001,7 @@ impl XmlInner { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2919,11 +3017,12 @@ pub struct XmlObject { #[serde(rename = "other_inner_rename")] #[serde(skip_serializing_if="Option::is_none")] - pub other_inner_rename: Option, + pub other_inner_rename: Option, } impl XmlObject { + #[allow(clippy::new_without_default)] pub fn new() -> XmlObject { XmlObject { inner_string: None, @@ -2937,20 +3036,26 @@ impl XmlObject { /// Should be implemented in a serde serializer impl std::string::ToString for XmlObject { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref inner_string) = self.inner_string { - params.push("innerString".to_string()); - params.push(inner_string.to_string()); - } + self.inner_string.as_ref().map(|inner_string| { + vec![ + "innerString".to_string(), + inner_string.to_string(), + ].join(",") + }), - if let Some(ref other_inner_rename) = self.other_inner_rename { - params.push("other_inner_rename".to_string()); - params.push(other_inner_rename.to_string()); - } + self.other_inner_rename.as_ref().map(|other_inner_rename| { + vec![ + "other_inner_rename".to_string(), + other_inner_rename.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2961,17 +3066,18 @@ impl std::str::FromStr for XmlObject { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub inner_string: Vec, - pub other_inner_rename: Vec, + pub other_inner_rename: Vec, } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2981,9 +3087,12 @@ impl std::str::FromStr for XmlObject { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "innerString" => intermediate_rep.inner_string.push(::from_str(val).map_err(|x| format!("{}", x))?), - "other_inner_rename" => intermediate_rep.other_inner_rename.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "innerString" => intermediate_rep.inner_string.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "other_inner_rename" => intermediate_rep.other_inner_rename.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing XmlObject".to_string()) } } @@ -3049,7 +3158,7 @@ impl XmlObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/server/callbacks.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/server/callbacks.rs index 8353cb185e..0486992669 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/server/callbacks.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/callbacks.rs @@ -264,7 +264,7 @@ impl CallbackApi for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) @@ -275,6 +275,7 @@ impl CallbackApi for Client where Some(param_information) => { request.headers_mut().append( HeaderName::from_static("information"), + #[allow(clippy::redundant_clone)] match header::IntoHeaderValue(param_information.clone()).try_into() { Ok(header) => header, Err(e) => { @@ -286,12 +287,11 @@ impl CallbackApi for Client where None => {} } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 204 => { - let body = response.into_body(); Ok( CallbackCallbackWithHeaderPostResponse::OK ) @@ -350,18 +350,17 @@ impl CallbackApi for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 204 => { - let body = response.into_body(); Ok( CallbackCallbackPostResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs index 813b8d962d..66216f5a2f 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs @@ -90,6 +90,7 @@ mod paths { pub(crate) static ID_ENUM_IN_PATH_PATH_PARAM: usize = 3; lazy_static! { pub static ref REGEX_ENUM_IN_PATH_PATH_PARAM: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^/enum_in_path/(?P[^/?#]*)$") .expect("Unable to create regex for ENUM_IN_PATH_PATH_PARAM"); } @@ -107,6 +108,7 @@ mod paths { pub(crate) static ID_REPOS_REPOID: usize = 15; lazy_static! { pub static ref REGEX_REPOS_REPOID: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^/repos/(?P[^/?#]*)$") .expect("Unable to create regex for REPOS_REPOID"); } @@ -181,7 +183,7 @@ impl Service where { pub fn new(api_impl: T) -> Self { Service { - api_impl: api_impl, + api_impl, marker: PhantomData } } @@ -194,7 +196,7 @@ impl Clone for Service where fn clone(&self) -> Self { Service { api_impl: self.api_impl.clone(), - marker: self.marker.clone(), + marker: self.marker, } } } @@ -220,10 +222,10 @@ impl hyper::service::Service<(Request, C)> for Service where let (method, uri, headers) = (parts.method, parts.uri, parts.headers); let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); - match &method { + match method { // AnyOfGet - GET /any-of - &hyper::Method::GET if path.matched(paths::ID_ANY_OF) => { + hyper::Method::GET if path.matched(paths::ID_ANY_OF) => { // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); let param_any_of = query_params.iter().filter(|e| e.0 == "any-of").map(|e| e.1.to_owned()) @@ -242,7 +244,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -293,11 +295,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // CallbackWithHeaderPost - POST /callback-with-header - &hyper::Method::POST if path.matched(paths::ID_CALLBACK_WITH_HEADER) => { + hyper::Method::POST if path.matched(paths::ID_CALLBACK_WITH_HEADER) => { // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); let param_url = query_params.iter().filter(|e| e.0 == "url").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_url = match param_url { Some(param_url) => { let param_url = @@ -328,7 +330,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -350,7 +352,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // ComplexQueryParamGet - GET /complex-query-param - &hyper::Method::GET if path.matched(paths::ID_COMPLEX_QUERY_PARAM) => { + hyper::Method::GET if path.matched(paths::ID_COMPLEX_QUERY_PARAM) => { // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); let param_list_of_strings = query_params.iter().filter(|e| e.0 == "list-of-strings").map(|e| e.1.to_owned()) @@ -369,7 +371,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -391,12 +393,12 @@ impl hyper::service::Service<(Request, C)> for Service where }, // EnumInPathPathParamGet - GET /enum_in_path/{path_param} - &hyper::Method::GET if path.matched(paths::ID_ENUM_IN_PATH_PATH_PARAM) => { + hyper::Method::GET if path.matched(paths::ID_ENUM_IN_PATH_PATH_PARAM) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_ENUM_IN_PATH_PATH_PARAM - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE ENUM_IN_PATH_PATH_PARAM in set but failed match against \"{}\"", path, paths::REGEX_ENUM_IN_PATH_PATH_PARAM.as_str()) ); @@ -422,7 +424,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -444,11 +446,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // JsonComplexQueryParamGet - GET /json-complex-query-param - &hyper::Method::GET if path.matched(paths::ID_JSON_COMPLEX_QUERY_PARAM) => { + hyper::Method::GET if path.matched(paths::ID_JSON_COMPLEX_QUERY_PARAM) => { // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); let param_list_of_strings = query_params.iter().filter(|e| e.0 == "list-of-strings").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_list_of_strings = match param_list_of_strings { Some(param_list_of_strings) => { let param_list_of_strings = @@ -472,7 +474,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -494,7 +496,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // MandatoryRequestHeaderGet - GET /mandatory-request-header - &hyper::Method::GET if path.matched(paths::ID_MANDATORY_REQUEST_HEADER) => { + hyper::Method::GET if path.matched(paths::ID_MANDATORY_REQUEST_HEADER) => { // Header parameters let param_x_header = headers.get(HeaderName::from_static("x-header")); @@ -525,7 +527,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -547,14 +549,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // MergePatchJsonGet - GET /merge-patch-json - &hyper::Method::GET if path.matched(paths::ID_MERGE_PATCH_JSON) => { + hyper::Method::GET if path.matched(paths::ID_MERGE_PATCH_JSON) => { let result = api_impl.merge_patch_json_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -583,14 +585,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // MultigetGet - GET /multiget - &hyper::Method::GET if path.matched(paths::ID_MULTIGET) => { + hyper::Method::GET if path.matched(paths::ID_MULTIGET) => { let result = api_impl.multiget_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -685,11 +687,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // MultipleAuthSchemeGet - GET /multiple_auth_scheme - &hyper::Method::GET if path.matched(paths::ID_MULTIPLE_AUTH_SCHEME) => { + hyper::Method::GET if path.matched(paths::ID_MULTIPLE_AUTH_SCHEME) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -722,7 +724,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -744,14 +746,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // OneOfGet - GET /one-of - &hyper::Method::GET if path.matched(paths::ID_ONE_OF) => { + hyper::Method::GET if path.matched(paths::ID_ONE_OF) => { let result = api_impl.one_of_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -780,14 +782,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // OverrideServerGet - GET /override-server - &hyper::Method::GET if path.matched(paths::ID_OVERRIDE_SERVER) => { + hyper::Method::GET if path.matched(paths::ID_OVERRIDE_SERVER) => { let result = api_impl.override_server_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -809,11 +811,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // ParamgetGet - GET /paramget - &hyper::Method::GET if path.matched(paths::ID_PARAMGET) => { + hyper::Method::GET if path.matched(paths::ID_PARAMGET) => { // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); let param_uuid = query_params.iter().filter(|e| e.0 == "uuid").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_uuid = match param_uuid { Some(param_uuid) => { let param_uuid = @@ -830,7 +832,7 @@ impl hyper::service::Service<(Request, C)> for Service where None => None, }; let param_some_object = query_params.iter().filter(|e| e.0 == "someObject").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_some_object = match param_some_object { Some(param_some_object) => { let param_some_object = @@ -847,7 +849,7 @@ impl hyper::service::Service<(Request, C)> for Service where None => None, }; let param_some_list = query_params.iter().filter(|e| e.0 == "someList").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_some_list = match param_some_list { Some(param_some_list) => { let param_some_list = @@ -873,7 +875,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -902,11 +904,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // ReadonlyAuthSchemeGet - GET /readonly_auth_scheme - &hyper::Method::GET if path.matched(paths::ID_READONLY_AUTH_SCHEME) => { + hyper::Method::GET if path.matched(paths::ID_READONLY_AUTH_SCHEME) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -938,7 +940,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -960,11 +962,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // RegisterCallbackPost - POST /register-callback - &hyper::Method::POST if path.matched(paths::ID_REGISTER_CALLBACK) => { + hyper::Method::POST if path.matched(paths::ID_REGISTER_CALLBACK) => { // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); let param_url = query_params.iter().filter(|e| e.0 == "url").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_url = match param_url { Some(param_url) => { let param_url = @@ -995,7 +997,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1017,7 +1019,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // RequiredOctetStreamPut - PUT /required_octet_stream - &hyper::Method::PUT if path.matched(paths::ID_REQUIRED_OCTET_STREAM) => { + hyper::Method::PUT if path.matched(paths::ID_REQUIRED_OCTET_STREAM) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -1044,7 +1046,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1072,14 +1074,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // ResponsesWithHeadersGet - GET /responses_with_headers - &hyper::Method::GET if path.matched(paths::ID_RESPONSES_WITH_HEADERS) => { + hyper::Method::GET if path.matched(paths::ID_RESPONSES_WITH_HEADERS) => { let result = api_impl.responses_with_headers_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1199,14 +1201,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Rfc7807Get - GET /rfc7807 - &hyper::Method::GET if path.matched(paths::ID_RFC7807) => { + hyper::Method::GET if path.matched(paths::ID_RFC7807) => { let result = api_impl.rfc7807_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1257,7 +1259,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // UntypedPropertyGet - GET /untyped_property - &hyper::Method::GET if path.matched(paths::ID_UNTYPED_PROPERTY) => { + hyper::Method::GET if path.matched(paths::ID_UNTYPED_PROPERTY) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -1285,7 +1287,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1320,14 +1322,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // UuidGet - GET /uuid - &hyper::Method::GET if path.matched(paths::ID_UUID) => { + hyper::Method::GET if path.matched(paths::ID_UUID) => { let result = api_impl.uuid_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1356,7 +1358,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // XmlExtraPost - POST /xml_extra - &hyper::Method::POST if path.matched(paths::ID_XML_EXTRA) => { + hyper::Method::POST if path.matched(paths::ID_XML_EXTRA) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -1384,7 +1386,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1423,7 +1425,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // XmlOtherPost - POST /xml_other - &hyper::Method::POST if path.matched(paths::ID_XML_OTHER) => { + hyper::Method::POST if path.matched(paths::ID_XML_OTHER) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -1451,7 +1453,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1501,7 +1503,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // XmlOtherPut - PUT /xml_other - &hyper::Method::PUT if path.matched(paths::ID_XML_OTHER) => { + hyper::Method::PUT if path.matched(paths::ID_XML_OTHER) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -1529,7 +1531,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1568,7 +1570,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // XmlPost - POST /xml - &hyper::Method::POST if path.matched(paths::ID_XML) => { + hyper::Method::POST if path.matched(paths::ID_XML) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -1596,7 +1598,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1635,7 +1637,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // XmlPut - PUT /xml - &hyper::Method::PUT if path.matched(paths::ID_XML) => { + hyper::Method::PUT if path.matched(paths::ID_XML) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -1663,7 +1665,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1702,7 +1704,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // CreateRepo - POST /repos - &hyper::Method::POST if path.matched(paths::ID_REPOS) => { + hyper::Method::POST if path.matched(paths::ID_REPOS) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -1740,7 +1742,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1775,12 +1777,12 @@ impl hyper::service::Service<(Request, C)> for Service where }, // GetRepoInfo - GET /repos/{repoId} - &hyper::Method::GET if path.matched(paths::ID_REPOS_REPOID) => { + hyper::Method::GET if path.matched(paths::ID_REPOS_REPOID) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_REPOS_REPOID - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE REPOS_REPOID in set but failed match against \"{}\"", path, paths::REGEX_REPOS_REPOID.as_str()) ); @@ -1806,7 +1808,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1870,59 +1872,59 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { // AnyOfGet - GET /any-of - &hyper::Method::GET if path.matched(paths::ID_ANY_OF) => Some("AnyOfGet"), + hyper::Method::GET if path.matched(paths::ID_ANY_OF) => Some("AnyOfGet"), // CallbackWithHeaderPost - POST /callback-with-header - &hyper::Method::POST if path.matched(paths::ID_CALLBACK_WITH_HEADER) => Some("CallbackWithHeaderPost"), + hyper::Method::POST if path.matched(paths::ID_CALLBACK_WITH_HEADER) => Some("CallbackWithHeaderPost"), // ComplexQueryParamGet - GET /complex-query-param - &hyper::Method::GET if path.matched(paths::ID_COMPLEX_QUERY_PARAM) => Some("ComplexQueryParamGet"), + hyper::Method::GET if path.matched(paths::ID_COMPLEX_QUERY_PARAM) => Some("ComplexQueryParamGet"), // EnumInPathPathParamGet - GET /enum_in_path/{path_param} - &hyper::Method::GET if path.matched(paths::ID_ENUM_IN_PATH_PATH_PARAM) => Some("EnumInPathPathParamGet"), + hyper::Method::GET if path.matched(paths::ID_ENUM_IN_PATH_PATH_PARAM) => Some("EnumInPathPathParamGet"), // JsonComplexQueryParamGet - GET /json-complex-query-param - &hyper::Method::GET if path.matched(paths::ID_JSON_COMPLEX_QUERY_PARAM) => Some("JsonComplexQueryParamGet"), + hyper::Method::GET if path.matched(paths::ID_JSON_COMPLEX_QUERY_PARAM) => Some("JsonComplexQueryParamGet"), // MandatoryRequestHeaderGet - GET /mandatory-request-header - &hyper::Method::GET if path.matched(paths::ID_MANDATORY_REQUEST_HEADER) => Some("MandatoryRequestHeaderGet"), + hyper::Method::GET if path.matched(paths::ID_MANDATORY_REQUEST_HEADER) => Some("MandatoryRequestHeaderGet"), // MergePatchJsonGet - GET /merge-patch-json - &hyper::Method::GET if path.matched(paths::ID_MERGE_PATCH_JSON) => Some("MergePatchJsonGet"), + hyper::Method::GET if path.matched(paths::ID_MERGE_PATCH_JSON) => Some("MergePatchJsonGet"), // MultigetGet - GET /multiget - &hyper::Method::GET if path.matched(paths::ID_MULTIGET) => Some("MultigetGet"), + hyper::Method::GET if path.matched(paths::ID_MULTIGET) => Some("MultigetGet"), // MultipleAuthSchemeGet - GET /multiple_auth_scheme - &hyper::Method::GET if path.matched(paths::ID_MULTIPLE_AUTH_SCHEME) => Some("MultipleAuthSchemeGet"), + hyper::Method::GET if path.matched(paths::ID_MULTIPLE_AUTH_SCHEME) => Some("MultipleAuthSchemeGet"), // OneOfGet - GET /one-of - &hyper::Method::GET if path.matched(paths::ID_ONE_OF) => Some("OneOfGet"), + hyper::Method::GET if path.matched(paths::ID_ONE_OF) => Some("OneOfGet"), // OverrideServerGet - GET /override-server - &hyper::Method::GET if path.matched(paths::ID_OVERRIDE_SERVER) => Some("OverrideServerGet"), + hyper::Method::GET if path.matched(paths::ID_OVERRIDE_SERVER) => Some("OverrideServerGet"), // ParamgetGet - GET /paramget - &hyper::Method::GET if path.matched(paths::ID_PARAMGET) => Some("ParamgetGet"), + hyper::Method::GET if path.matched(paths::ID_PARAMGET) => Some("ParamgetGet"), // ReadonlyAuthSchemeGet - GET /readonly_auth_scheme - &hyper::Method::GET if path.matched(paths::ID_READONLY_AUTH_SCHEME) => Some("ReadonlyAuthSchemeGet"), + hyper::Method::GET if path.matched(paths::ID_READONLY_AUTH_SCHEME) => Some("ReadonlyAuthSchemeGet"), // RegisterCallbackPost - POST /register-callback - &hyper::Method::POST if path.matched(paths::ID_REGISTER_CALLBACK) => Some("RegisterCallbackPost"), + hyper::Method::POST if path.matched(paths::ID_REGISTER_CALLBACK) => Some("RegisterCallbackPost"), // RequiredOctetStreamPut - PUT /required_octet_stream - &hyper::Method::PUT if path.matched(paths::ID_REQUIRED_OCTET_STREAM) => Some("RequiredOctetStreamPut"), + hyper::Method::PUT if path.matched(paths::ID_REQUIRED_OCTET_STREAM) => Some("RequiredOctetStreamPut"), // ResponsesWithHeadersGet - GET /responses_with_headers - &hyper::Method::GET if path.matched(paths::ID_RESPONSES_WITH_HEADERS) => Some("ResponsesWithHeadersGet"), + hyper::Method::GET if path.matched(paths::ID_RESPONSES_WITH_HEADERS) => Some("ResponsesWithHeadersGet"), // Rfc7807Get - GET /rfc7807 - &hyper::Method::GET if path.matched(paths::ID_RFC7807) => Some("Rfc7807Get"), + hyper::Method::GET if path.matched(paths::ID_RFC7807) => Some("Rfc7807Get"), // UntypedPropertyGet - GET /untyped_property - &hyper::Method::GET if path.matched(paths::ID_UNTYPED_PROPERTY) => Some("UntypedPropertyGet"), + hyper::Method::GET if path.matched(paths::ID_UNTYPED_PROPERTY) => Some("UntypedPropertyGet"), // UuidGet - GET /uuid - &hyper::Method::GET if path.matched(paths::ID_UUID) => Some("UuidGet"), + hyper::Method::GET if path.matched(paths::ID_UUID) => Some("UuidGet"), // XmlExtraPost - POST /xml_extra - &hyper::Method::POST if path.matched(paths::ID_XML_EXTRA) => Some("XmlExtraPost"), + hyper::Method::POST if path.matched(paths::ID_XML_EXTRA) => Some("XmlExtraPost"), // XmlOtherPost - POST /xml_other - &hyper::Method::POST if path.matched(paths::ID_XML_OTHER) => Some("XmlOtherPost"), + hyper::Method::POST if path.matched(paths::ID_XML_OTHER) => Some("XmlOtherPost"), // XmlOtherPut - PUT /xml_other - &hyper::Method::PUT if path.matched(paths::ID_XML_OTHER) => Some("XmlOtherPut"), + hyper::Method::PUT if path.matched(paths::ID_XML_OTHER) => Some("XmlOtherPut"), // XmlPost - POST /xml - &hyper::Method::POST if path.matched(paths::ID_XML) => Some("XmlPost"), + hyper::Method::POST if path.matched(paths::ID_XML) => Some("XmlPost"), // XmlPut - PUT /xml - &hyper::Method::PUT if path.matched(paths::ID_XML) => Some("XmlPut"), + hyper::Method::PUT if path.matched(paths::ID_XML) => Some("XmlPut"), // CreateRepo - POST /repos - &hyper::Method::POST if path.matched(paths::ID_REPOS) => Some("CreateRepo"), + hyper::Method::POST if path.matched(paths::ID_REPOS) => Some("CreateRepo"), // GetRepoInfo - GET /repos/{repoId} - &hyper::Method::GET if path.matched(paths::ID_REPOS_REPOID) => Some("GetRepoInfo"), + hyper::Method::GET if path.matched(paths::ID_REPOS_REPOID) => Some("GetRepoInfo"), _ => None, } } diff --git a/samples/server/petstore/rust-server/output/ops-v3/examples/server/server.rs b/samples/server/petstore/rust-server/output/ops-v3/examples/server/server.rs index ffd7d59c80..0f5e145f34 100644 --- a/samples/server/petstore/rust-server/output/ops-v3/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/ops-v3/examples/server/server.rs @@ -32,6 +32,7 @@ pub async fn create(addr: &str, https: bool) { let service = MakeAllowAllAuthenticator::new(service, "cosmo"); + #[allow(unused_mut)] let mut service = ops_v3::server::context::MakeAddContext::<_, EmptyContext>::new( service diff --git a/samples/server/petstore/rust-server/output/ops-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/ops-v3/src/client/mod.rs index 4d2375e634..f3dbc73c98 100644 --- a/samples/server/petstore/rust-server/output/ops-v3/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/ops-v3/src/client/mod.rs @@ -89,7 +89,7 @@ fn into_base_path(input: impl TryInto, } } - let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let host = uri.host().ok_or(ClientInitError::MissingHost)?; let port = uri.port_u16().map(|x| format!(":{}", x)).unwrap_or_default(); Ok(format!("{}://{}{}{}", scheme, host, port, uri.path().trim_end_matches('/'))) } @@ -228,7 +228,7 @@ impl Client, C> where "https" => { let connector = connector.https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; HyperClient::Https(hyper::client::Client::builder().build(connector)) }, _ => { @@ -280,7 +280,7 @@ impl Client, C let https_connector = Connector::builder() .https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -301,7 +301,7 @@ impl Client, C .https() .pin_server_certificate(ca_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -329,7 +329,7 @@ impl Client, C .pin_server_certificate(ca_certificate) .client_authentication(client_key, client_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } } @@ -449,18 +449,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op10GetResponse::OK ) @@ -518,18 +517,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op11GetResponse::OK ) @@ -587,18 +585,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op12GetResponse::OK ) @@ -656,18 +653,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op13GetResponse::OK ) @@ -725,18 +721,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op14GetResponse::OK ) @@ -794,18 +789,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op15GetResponse::OK ) @@ -863,18 +857,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op16GetResponse::OK ) @@ -932,18 +925,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op17GetResponse::OK ) @@ -1001,18 +993,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op18GetResponse::OK ) @@ -1070,18 +1061,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op19GetResponse::OK ) @@ -1139,18 +1129,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op1GetResponse::OK ) @@ -1208,18 +1197,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op20GetResponse::OK ) @@ -1277,18 +1265,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op21GetResponse::OK ) @@ -1346,18 +1333,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op22GetResponse::OK ) @@ -1415,18 +1401,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op23GetResponse::OK ) @@ -1484,18 +1469,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op24GetResponse::OK ) @@ -1553,18 +1537,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op25GetResponse::OK ) @@ -1622,18 +1605,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op26GetResponse::OK ) @@ -1691,18 +1673,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op27GetResponse::OK ) @@ -1760,18 +1741,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op28GetResponse::OK ) @@ -1829,18 +1809,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op29GetResponse::OK ) @@ -1898,18 +1877,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op2GetResponse::OK ) @@ -1967,18 +1945,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op30GetResponse::OK ) @@ -2036,18 +2013,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op31GetResponse::OK ) @@ -2105,18 +2081,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op32GetResponse::OK ) @@ -2174,18 +2149,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op33GetResponse::OK ) @@ -2243,18 +2217,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op34GetResponse::OK ) @@ -2312,18 +2285,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op35GetResponse::OK ) @@ -2381,18 +2353,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op36GetResponse::OK ) @@ -2450,18 +2421,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op37GetResponse::OK ) @@ -2519,18 +2489,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op3GetResponse::OK ) @@ -2588,18 +2557,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op4GetResponse::OK ) @@ -2657,18 +2625,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op5GetResponse::OK ) @@ -2726,18 +2693,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op6GetResponse::OK ) @@ -2795,18 +2761,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op7GetResponse::OK ) @@ -2864,18 +2829,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op8GetResponse::OK ) @@ -2933,18 +2897,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Op9GetResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/ops-v3/src/lib.rs b/samples/server/petstore/rust-server/output/ops-v3/src/lib.rs index 52793ae078..4cc7e28f73 100644 --- a/samples/server/petstore/rust-server/output/ops-v3/src/lib.rs +++ b/samples/server/petstore/rust-server/output/ops-v3/src/lib.rs @@ -1,4 +1,6 @@ #![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::blacklisted_name)] use async_trait::async_trait; use futures::Stream; @@ -9,8 +11,8 @@ use serde::{Serialize, Deserialize}; type ServiceError = Box; -pub const BASE_PATH: &'static str = ""; -pub const API_VERSION: &'static str = "0.0.1"; +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "0.0.1"; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum Op10GetResponse { @@ -236,6 +238,7 @@ pub enum Op9GetResponse { /// API #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait Api { fn poll_ready(&self, _cx: &mut Context) -> Poll>> { Poll::Ready(Ok(())) @@ -393,6 +396,7 @@ pub trait Api { /// API where `Context` isn't passed on every API call #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait ApiNoContext { fn poll_ready(&self, _cx: &mut Context) -> Poll>>; @@ -553,7 +557,7 @@ pub trait ApiNoContext { pub trait ContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> ContextWrapperExt for T { diff --git a/samples/server/petstore/rust-server/output/ops-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/ops-v3/src/server/mod.rs index 438fe894ae..e27cc1ed58 100644 --- a/samples/server/petstore/rust-server/output/ops-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/ops-v3/src/server/mod.rs @@ -206,7 +206,7 @@ impl Service where { pub fn new(api_impl: T) -> Self { Service { - api_impl: api_impl, + api_impl, marker: PhantomData } } @@ -219,7 +219,7 @@ impl Clone for Service where fn clone(&self) -> Self { Service { api_impl: self.api_impl.clone(), - marker: self.marker.clone(), + marker: self.marker, } } } @@ -245,17 +245,17 @@ impl hyper::service::Service<(Request, C)> for Service where let (method, uri, headers) = (parts.method, parts.uri, parts.headers); let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); - match &method { + match method { // Op10Get - GET /op10 - &hyper::Method::GET if path.matched(paths::ID_OP10) => { + hyper::Method::GET if path.matched(paths::ID_OP10) => { let result = api_impl.op10_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -277,14 +277,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op11Get - GET /op11 - &hyper::Method::GET if path.matched(paths::ID_OP11) => { + hyper::Method::GET if path.matched(paths::ID_OP11) => { let result = api_impl.op11_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -306,14 +306,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op12Get - GET /op12 - &hyper::Method::GET if path.matched(paths::ID_OP12) => { + hyper::Method::GET if path.matched(paths::ID_OP12) => { let result = api_impl.op12_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -335,14 +335,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op13Get - GET /op13 - &hyper::Method::GET if path.matched(paths::ID_OP13) => { + hyper::Method::GET if path.matched(paths::ID_OP13) => { let result = api_impl.op13_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -364,14 +364,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op14Get - GET /op14 - &hyper::Method::GET if path.matched(paths::ID_OP14) => { + hyper::Method::GET if path.matched(paths::ID_OP14) => { let result = api_impl.op14_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -393,14 +393,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op15Get - GET /op15 - &hyper::Method::GET if path.matched(paths::ID_OP15) => { + hyper::Method::GET if path.matched(paths::ID_OP15) => { let result = api_impl.op15_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -422,14 +422,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op16Get - GET /op16 - &hyper::Method::GET if path.matched(paths::ID_OP16) => { + hyper::Method::GET if path.matched(paths::ID_OP16) => { let result = api_impl.op16_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -451,14 +451,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op17Get - GET /op17 - &hyper::Method::GET if path.matched(paths::ID_OP17) => { + hyper::Method::GET if path.matched(paths::ID_OP17) => { let result = api_impl.op17_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -480,14 +480,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op18Get - GET /op18 - &hyper::Method::GET if path.matched(paths::ID_OP18) => { + hyper::Method::GET if path.matched(paths::ID_OP18) => { let result = api_impl.op18_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -509,14 +509,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op19Get - GET /op19 - &hyper::Method::GET if path.matched(paths::ID_OP19) => { + hyper::Method::GET if path.matched(paths::ID_OP19) => { let result = api_impl.op19_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -538,14 +538,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op1Get - GET /op1 - &hyper::Method::GET if path.matched(paths::ID_OP1) => { + hyper::Method::GET if path.matched(paths::ID_OP1) => { let result = api_impl.op1_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -567,14 +567,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op20Get - GET /op20 - &hyper::Method::GET if path.matched(paths::ID_OP20) => { + hyper::Method::GET if path.matched(paths::ID_OP20) => { let result = api_impl.op20_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -596,14 +596,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op21Get - GET /op21 - &hyper::Method::GET if path.matched(paths::ID_OP21) => { + hyper::Method::GET if path.matched(paths::ID_OP21) => { let result = api_impl.op21_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -625,14 +625,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op22Get - GET /op22 - &hyper::Method::GET if path.matched(paths::ID_OP22) => { + hyper::Method::GET if path.matched(paths::ID_OP22) => { let result = api_impl.op22_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -654,14 +654,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op23Get - GET /op23 - &hyper::Method::GET if path.matched(paths::ID_OP23) => { + hyper::Method::GET if path.matched(paths::ID_OP23) => { let result = api_impl.op23_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -683,14 +683,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op24Get - GET /op24 - &hyper::Method::GET if path.matched(paths::ID_OP24) => { + hyper::Method::GET if path.matched(paths::ID_OP24) => { let result = api_impl.op24_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -712,14 +712,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op25Get - GET /op25 - &hyper::Method::GET if path.matched(paths::ID_OP25) => { + hyper::Method::GET if path.matched(paths::ID_OP25) => { let result = api_impl.op25_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -741,14 +741,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op26Get - GET /op26 - &hyper::Method::GET if path.matched(paths::ID_OP26) => { + hyper::Method::GET if path.matched(paths::ID_OP26) => { let result = api_impl.op26_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -770,14 +770,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op27Get - GET /op27 - &hyper::Method::GET if path.matched(paths::ID_OP27) => { + hyper::Method::GET if path.matched(paths::ID_OP27) => { let result = api_impl.op27_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -799,14 +799,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op28Get - GET /op28 - &hyper::Method::GET if path.matched(paths::ID_OP28) => { + hyper::Method::GET if path.matched(paths::ID_OP28) => { let result = api_impl.op28_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -828,14 +828,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op29Get - GET /op29 - &hyper::Method::GET if path.matched(paths::ID_OP29) => { + hyper::Method::GET if path.matched(paths::ID_OP29) => { let result = api_impl.op29_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -857,14 +857,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op2Get - GET /op2 - &hyper::Method::GET if path.matched(paths::ID_OP2) => { + hyper::Method::GET if path.matched(paths::ID_OP2) => { let result = api_impl.op2_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -886,14 +886,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op30Get - GET /op30 - &hyper::Method::GET if path.matched(paths::ID_OP30) => { + hyper::Method::GET if path.matched(paths::ID_OP30) => { let result = api_impl.op30_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -915,14 +915,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op31Get - GET /op31 - &hyper::Method::GET if path.matched(paths::ID_OP31) => { + hyper::Method::GET if path.matched(paths::ID_OP31) => { let result = api_impl.op31_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -944,14 +944,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op32Get - GET /op32 - &hyper::Method::GET if path.matched(paths::ID_OP32) => { + hyper::Method::GET if path.matched(paths::ID_OP32) => { let result = api_impl.op32_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -973,14 +973,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op33Get - GET /op33 - &hyper::Method::GET if path.matched(paths::ID_OP33) => { + hyper::Method::GET if path.matched(paths::ID_OP33) => { let result = api_impl.op33_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1002,14 +1002,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op34Get - GET /op34 - &hyper::Method::GET if path.matched(paths::ID_OP34) => { + hyper::Method::GET if path.matched(paths::ID_OP34) => { let result = api_impl.op34_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1031,14 +1031,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op35Get - GET /op35 - &hyper::Method::GET if path.matched(paths::ID_OP35) => { + hyper::Method::GET if path.matched(paths::ID_OP35) => { let result = api_impl.op35_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1060,14 +1060,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op36Get - GET /op36 - &hyper::Method::GET if path.matched(paths::ID_OP36) => { + hyper::Method::GET if path.matched(paths::ID_OP36) => { let result = api_impl.op36_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1089,14 +1089,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op37Get - GET /op37 - &hyper::Method::GET if path.matched(paths::ID_OP37) => { + hyper::Method::GET if path.matched(paths::ID_OP37) => { let result = api_impl.op37_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1118,14 +1118,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op3Get - GET /op3 - &hyper::Method::GET if path.matched(paths::ID_OP3) => { + hyper::Method::GET if path.matched(paths::ID_OP3) => { let result = api_impl.op3_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1147,14 +1147,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op4Get - GET /op4 - &hyper::Method::GET if path.matched(paths::ID_OP4) => { + hyper::Method::GET if path.matched(paths::ID_OP4) => { let result = api_impl.op4_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1176,14 +1176,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op5Get - GET /op5 - &hyper::Method::GET if path.matched(paths::ID_OP5) => { + hyper::Method::GET if path.matched(paths::ID_OP5) => { let result = api_impl.op5_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1205,14 +1205,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op6Get - GET /op6 - &hyper::Method::GET if path.matched(paths::ID_OP6) => { + hyper::Method::GET if path.matched(paths::ID_OP6) => { let result = api_impl.op6_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1234,14 +1234,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op7Get - GET /op7 - &hyper::Method::GET if path.matched(paths::ID_OP7) => { + hyper::Method::GET if path.matched(paths::ID_OP7) => { let result = api_impl.op7_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1263,14 +1263,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op8Get - GET /op8 - &hyper::Method::GET if path.matched(paths::ID_OP8) => { + hyper::Method::GET if path.matched(paths::ID_OP8) => { let result = api_impl.op8_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1292,14 +1292,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Op9Get - GET /op9 - &hyper::Method::GET if path.matched(paths::ID_OP9) => { + hyper::Method::GET if path.matched(paths::ID_OP9) => { let result = api_impl.op9_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1369,81 +1369,81 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { // Op10Get - GET /op10 - &hyper::Method::GET if path.matched(paths::ID_OP10) => Some("Op10Get"), + hyper::Method::GET if path.matched(paths::ID_OP10) => Some("Op10Get"), // Op11Get - GET /op11 - &hyper::Method::GET if path.matched(paths::ID_OP11) => Some("Op11Get"), + hyper::Method::GET if path.matched(paths::ID_OP11) => Some("Op11Get"), // Op12Get - GET /op12 - &hyper::Method::GET if path.matched(paths::ID_OP12) => Some("Op12Get"), + hyper::Method::GET if path.matched(paths::ID_OP12) => Some("Op12Get"), // Op13Get - GET /op13 - &hyper::Method::GET if path.matched(paths::ID_OP13) => Some("Op13Get"), + hyper::Method::GET if path.matched(paths::ID_OP13) => Some("Op13Get"), // Op14Get - GET /op14 - &hyper::Method::GET if path.matched(paths::ID_OP14) => Some("Op14Get"), + hyper::Method::GET if path.matched(paths::ID_OP14) => Some("Op14Get"), // Op15Get - GET /op15 - &hyper::Method::GET if path.matched(paths::ID_OP15) => Some("Op15Get"), + hyper::Method::GET if path.matched(paths::ID_OP15) => Some("Op15Get"), // Op16Get - GET /op16 - &hyper::Method::GET if path.matched(paths::ID_OP16) => Some("Op16Get"), + hyper::Method::GET if path.matched(paths::ID_OP16) => Some("Op16Get"), // Op17Get - GET /op17 - &hyper::Method::GET if path.matched(paths::ID_OP17) => Some("Op17Get"), + hyper::Method::GET if path.matched(paths::ID_OP17) => Some("Op17Get"), // Op18Get - GET /op18 - &hyper::Method::GET if path.matched(paths::ID_OP18) => Some("Op18Get"), + hyper::Method::GET if path.matched(paths::ID_OP18) => Some("Op18Get"), // Op19Get - GET /op19 - &hyper::Method::GET if path.matched(paths::ID_OP19) => Some("Op19Get"), + hyper::Method::GET if path.matched(paths::ID_OP19) => Some("Op19Get"), // Op1Get - GET /op1 - &hyper::Method::GET if path.matched(paths::ID_OP1) => Some("Op1Get"), + hyper::Method::GET if path.matched(paths::ID_OP1) => Some("Op1Get"), // Op20Get - GET /op20 - &hyper::Method::GET if path.matched(paths::ID_OP20) => Some("Op20Get"), + hyper::Method::GET if path.matched(paths::ID_OP20) => Some("Op20Get"), // Op21Get - GET /op21 - &hyper::Method::GET if path.matched(paths::ID_OP21) => Some("Op21Get"), + hyper::Method::GET if path.matched(paths::ID_OP21) => Some("Op21Get"), // Op22Get - GET /op22 - &hyper::Method::GET if path.matched(paths::ID_OP22) => Some("Op22Get"), + hyper::Method::GET if path.matched(paths::ID_OP22) => Some("Op22Get"), // Op23Get - GET /op23 - &hyper::Method::GET if path.matched(paths::ID_OP23) => Some("Op23Get"), + hyper::Method::GET if path.matched(paths::ID_OP23) => Some("Op23Get"), // Op24Get - GET /op24 - &hyper::Method::GET if path.matched(paths::ID_OP24) => Some("Op24Get"), + hyper::Method::GET if path.matched(paths::ID_OP24) => Some("Op24Get"), // Op25Get - GET /op25 - &hyper::Method::GET if path.matched(paths::ID_OP25) => Some("Op25Get"), + hyper::Method::GET if path.matched(paths::ID_OP25) => Some("Op25Get"), // Op26Get - GET /op26 - &hyper::Method::GET if path.matched(paths::ID_OP26) => Some("Op26Get"), + hyper::Method::GET if path.matched(paths::ID_OP26) => Some("Op26Get"), // Op27Get - GET /op27 - &hyper::Method::GET if path.matched(paths::ID_OP27) => Some("Op27Get"), + hyper::Method::GET if path.matched(paths::ID_OP27) => Some("Op27Get"), // Op28Get - GET /op28 - &hyper::Method::GET if path.matched(paths::ID_OP28) => Some("Op28Get"), + hyper::Method::GET if path.matched(paths::ID_OP28) => Some("Op28Get"), // Op29Get - GET /op29 - &hyper::Method::GET if path.matched(paths::ID_OP29) => Some("Op29Get"), + hyper::Method::GET if path.matched(paths::ID_OP29) => Some("Op29Get"), // Op2Get - GET /op2 - &hyper::Method::GET if path.matched(paths::ID_OP2) => Some("Op2Get"), + hyper::Method::GET if path.matched(paths::ID_OP2) => Some("Op2Get"), // Op30Get - GET /op30 - &hyper::Method::GET if path.matched(paths::ID_OP30) => Some("Op30Get"), + hyper::Method::GET if path.matched(paths::ID_OP30) => Some("Op30Get"), // Op31Get - GET /op31 - &hyper::Method::GET if path.matched(paths::ID_OP31) => Some("Op31Get"), + hyper::Method::GET if path.matched(paths::ID_OP31) => Some("Op31Get"), // Op32Get - GET /op32 - &hyper::Method::GET if path.matched(paths::ID_OP32) => Some("Op32Get"), + hyper::Method::GET if path.matched(paths::ID_OP32) => Some("Op32Get"), // Op33Get - GET /op33 - &hyper::Method::GET if path.matched(paths::ID_OP33) => Some("Op33Get"), + hyper::Method::GET if path.matched(paths::ID_OP33) => Some("Op33Get"), // Op34Get - GET /op34 - &hyper::Method::GET if path.matched(paths::ID_OP34) => Some("Op34Get"), + hyper::Method::GET if path.matched(paths::ID_OP34) => Some("Op34Get"), // Op35Get - GET /op35 - &hyper::Method::GET if path.matched(paths::ID_OP35) => Some("Op35Get"), + hyper::Method::GET if path.matched(paths::ID_OP35) => Some("Op35Get"), // Op36Get - GET /op36 - &hyper::Method::GET if path.matched(paths::ID_OP36) => Some("Op36Get"), + hyper::Method::GET if path.matched(paths::ID_OP36) => Some("Op36Get"), // Op37Get - GET /op37 - &hyper::Method::GET if path.matched(paths::ID_OP37) => Some("Op37Get"), + hyper::Method::GET if path.matched(paths::ID_OP37) => Some("Op37Get"), // Op3Get - GET /op3 - &hyper::Method::GET if path.matched(paths::ID_OP3) => Some("Op3Get"), + hyper::Method::GET if path.matched(paths::ID_OP3) => Some("Op3Get"), // Op4Get - GET /op4 - &hyper::Method::GET if path.matched(paths::ID_OP4) => Some("Op4Get"), + hyper::Method::GET if path.matched(paths::ID_OP4) => Some("Op4Get"), // Op5Get - GET /op5 - &hyper::Method::GET if path.matched(paths::ID_OP5) => Some("Op5Get"), + hyper::Method::GET if path.matched(paths::ID_OP5) => Some("Op5Get"), // Op6Get - GET /op6 - &hyper::Method::GET if path.matched(paths::ID_OP6) => Some("Op6Get"), + hyper::Method::GET if path.matched(paths::ID_OP6) => Some("Op6Get"), // Op7Get - GET /op7 - &hyper::Method::GET if path.matched(paths::ID_OP7) => Some("Op7Get"), + hyper::Method::GET if path.matched(paths::ID_OP7) => Some("Op7Get"), // Op8Get - GET /op8 - &hyper::Method::GET if path.matched(paths::ID_OP8) => Some("Op8Get"), + hyper::Method::GET if path.matched(paths::ID_OP8) => Some("Op8Get"), // Op9Get - GET /op9 - &hyper::Method::GET if path.matched(paths::ID_OP9) => Some("Op9Get"), + hyper::Method::GET if path.matched(paths::ID_OP9) => Some("Op9Get"), _ => None, } } diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES index 03bc5ac350..e258e80b78 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES @@ -18,6 +18,7 @@ docs/ClassModel.md docs/Client.md docs/Dog.md docs/DogAllOf.md +docs/DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket.md docs/EnumArrays.md docs/EnumClass.md docs/EnumTest.md @@ -27,7 +28,6 @@ docs/List.md docs/MapTest.md docs/MixedPropertiesAndAdditionalPropertiesClass.md docs/Model200Response.md -docs/ModelReturn.md docs/Name.md docs/NumberOnly.md docs/ObjectContainingObjectWithOnlyAdditionalProperties.md @@ -40,7 +40,7 @@ docs/OuterNumber.md docs/OuterString.md docs/Pet.md docs/ReadOnlyFirst.md -docs/SpecialModelName.md +docs/Return.md docs/Tag.md docs/User.md docs/another_fake_api.md diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md index 6ba03e0bd3..6f583383df 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md @@ -173,6 +173,7 @@ Method | HTTP request | Description - [Client](docs/Client.md) - [Dog](docs/Dog.md) - [DogAllOf](docs/DogAllOf.md) + - [DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket](docs/DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket.md) - [EnumArrays](docs/EnumArrays.md) - [EnumClass](docs/EnumClass.md) - [EnumTest](docs/EnumTest.md) @@ -182,7 +183,6 @@ Method | HTTP request | Description - [MapTest](docs/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) - - [ModelReturn](docs/ModelReturn.md) - [Name](docs/Name.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectContainingObjectWithOnlyAdditionalProperties](docs/ObjectContainingObjectWithOnlyAdditionalProperties.md) @@ -195,7 +195,7 @@ Method | HTTP request | Description - [OuterString](docs/OuterString.md) - [Pet](docs/Pet.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - - [SpecialModelName](docs/SpecialModelName.md) + - [Return](docs/Return.md) - [Tag](docs/Tag.md) - [User](docs/User.md) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/api/openapi.yaml b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/api/openapi.yaml index 96301e90a4..4c17f555f4 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/api/openapi.yaml @@ -1576,11 +1576,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/ApiResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/ApiResponse.md index f6141874c4..de9b8f1d11 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/ApiResponse.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/ApiResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **i32** | | [optional] [default to None] -**type_** | **String** | | [optional] [default to None] +**r#type** | **String** | | [optional] [default to None] **message** | **String** | | [optional] [default to None] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket.md new file mode 100644 index 0000000000..082df970a2 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket.md @@ -0,0 +1,10 @@ +# DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dollar_special_left_square_bracket_property_period_name_right_square_bracket** | **i64** | | [optional] [default to None] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/ModelReturn.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/ModelReturn.md deleted file mode 100644 index e9d3b87a4a..0000000000 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/ModelReturn.md +++ /dev/null @@ -1,10 +0,0 @@ -# ModelReturn - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**return_** | **i32** | | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/Name.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/Name.md index 74b356ac13..506a2c2880 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/Name.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/Name.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes **name** | **i32** | | **snake_case** | **i32** | | [optional] [readonly] [default to None] **property** | **String** | | [optional] [default to None] -**param_123_number** | **isize** | | [optional] [readonly] [default to None] +**param_123_number** | **i32** | | [optional] [readonly] [default to None] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/Return.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/Return.md new file mode 100644 index 0000000000..f3ed30f889 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/Return.md @@ -0,0 +1,10 @@ +# Return + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#return** | **i32** | | [optional] [default to None] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/SpecialModelName.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/SpecialModelName.md deleted file mode 100644 index 5e3beae9e3..0000000000 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/SpecialModelName.md +++ /dev/null @@ -1,10 +0,0 @@ -# SpecialModelName - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**special_property_name** | **i64** | | [optional] [default to None] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs index e86eaae25f..304590c34f 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs @@ -32,6 +32,7 @@ pub async fn create(addr: &str, https: bool) { let service = MakeAllowAllAuthenticator::new(service, "cosmo"); + #[allow(unused_mut)] let mut service = petstore_with_fake_endpoints_models_for_testing::server::context::MakeAddContext::<_, EmptyContext>::new( service diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs index 9fc14cf319..0ea239e35c 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs @@ -90,7 +90,7 @@ fn into_base_path(input: impl TryInto, } } - let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let host = uri.host().ok_or(ClientInitError::MissingHost)?; let port = uri.port_u16().map(|x| format!(":{}", x)).unwrap_or_default(); Ok(format!("{}://{}{}{}", scheme, host, port, uri.path().trim_end_matches('/'))) } @@ -229,7 +229,7 @@ impl Client, C> where "https" => { let connector = connector.https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; HyperClient::Https(hyper::client::Client::builder().build(connector)) }, _ => { @@ -281,7 +281,7 @@ impl Client, C let https_connector = Connector::builder() .https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -302,7 +302,7 @@ impl Client, C .https() .pin_server_certificate(ca_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -330,7 +330,7 @@ impl Client, C .pin_server_certificate(ca_certificate) .client_authentication(client_key, client_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } } @@ -462,13 +462,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -539,18 +539,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( Call123exampleResponse::Success ) @@ -621,13 +620,13 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -711,13 +710,13 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -801,13 +800,13 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -891,13 +890,13 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -968,18 +967,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( FakeResponseWithNumericalDescriptionResponse::Status200 ) @@ -1039,18 +1037,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( HyphenParamResponse::Success ) @@ -1091,7 +1088,7 @@ impl Api for Client where let query_string = { let mut query_string = form_urlencoded::Serializer::new("".to_owned()); query_string.append_pair("query", - ¶m_query.to_string()); + ¶m_query); query_string.finish() }; if !query_string.is_empty() { @@ -1120,18 +1117,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( TestBodyWithQueryParamsResponse::Success ) @@ -1198,13 +1194,13 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -1313,14 +1309,16 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); *request.body_mut() = Body::from(body.into_bytes()); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Basic(ref basic_header) => { let auth = swagger::auth::Header(basic_header.clone()); @@ -1336,18 +1334,16 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 400 => { - let body = response.into_body(); Ok( TestEndpointParametersResponse::InvalidUsernameSupplied ) } 404 => { - let body = response.into_body(); Ok( TestEndpointParametersResponse::UserNotFound ) @@ -1398,7 +1394,7 @@ impl Api for Client where } if let Some(param_enum_query_string) = param_enum_query_string { query_string.append_pair("enum_query_string", - ¶m_enum_query_string.to_string()); + ¶m_enum_query_string); } if let Some(param_enum_query_integer) = param_enum_query_integer { query_string.append_pair("enum_query_integer", @@ -1439,7 +1435,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); *request.body_mut() = Body::from(body.into_bytes()); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) @@ -1450,6 +1446,7 @@ impl Api for Client where Some(param_enum_header_string_array) => { request.headers_mut().append( HeaderName::from_static("enum_header_string_array"), + #[allow(clippy::redundant_clone)] match header::IntoHeaderValue(param_enum_header_string_array.clone()).try_into() { Ok(header) => header, Err(e) => { @@ -1465,6 +1462,7 @@ impl Api for Client where Some(param_enum_header_string) => { request.headers_mut().append( HeaderName::from_static("enum_header_string"), + #[allow(clippy::redundant_clone)] match header::IntoHeaderValue(param_enum_header_string.clone()).try_into() { Ok(header) => header, Err(e) => { @@ -1476,18 +1474,16 @@ impl Api for Client where None => {} } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 400 => { - let body = response.into_body(); Ok( TestEnumParametersResponse::InvalidRequest ) } 404 => { - let body = response.into_body(); Ok( TestEnumParametersResponse::NotFound ) @@ -1554,18 +1550,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( TestInlineAdditionalPropertiesResponse::SuccessfulOperation ) @@ -1637,18 +1632,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); *request.body_mut() = Body::from(body.into_bytes()); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( TestJsonFormDataResponse::SuccessfulOperation ) @@ -1687,10 +1681,8 @@ impl Api for Client where // Query parameters let query_string = { let mut query_string = form_urlencoded::Serializer::new("".to_owned()); - if let Some(auth_data) = (context as &dyn Has>).get().as_ref() { - if let AuthData::ApiKey(ref api_key) = *auth_data { - query_string.append_pair("api_key_query", api_key); - } + if let Some(AuthData::ApiKey(ref api_key)) = (context as &dyn Has>).get().as_ref() { + query_string.append_pair("api_key_query", api_key); } query_string.finish() }; @@ -1723,20 +1715,22 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { _ => {} } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -1809,7 +1803,7 @@ impl Api for Client where }; // Body parameter - let body = param_body.to_xml(); + let body = param_body.as_xml(); *request.body_mut() = Body::from(body); let header = "application/json"; @@ -1817,14 +1811,16 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -1840,12 +1836,11 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 405 => { - let body = response.into_body(); Ok( AddPetResponse::InvalidInput ) @@ -1906,14 +1901,16 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -1934,6 +1931,7 @@ impl Api for Client where Some(param_api_key) => { request.headers_mut().append( HeaderName::from_static("api_key"), + #[allow(clippy::redundant_clone)] match header::IntoHeaderValue(param_api_key.clone()).try_into() { Ok(header) => header, Err(e) => { @@ -1945,12 +1943,11 @@ impl Api for Client where None => {} } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 400 => { - let body = response.into_body(); Ok( DeletePetResponse::InvalidPetValue ) @@ -2011,14 +2008,16 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -2034,7 +2033,7 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2054,7 +2053,6 @@ impl Api for Client where ) } 400 => { - let body = response.into_body(); Ok( FindPetsByStatusResponse::InvalidStatusValue ) @@ -2115,14 +2113,16 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -2138,7 +2138,7 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2158,7 +2158,6 @@ impl Api for Client where ) } 400 => { - let body = response.into_body(); Ok( FindPetsByTagsResponse::InvalidTagValue ) @@ -2218,20 +2217,22 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { _ => {} } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2251,13 +2252,11 @@ impl Api for Client where ) } 400 => { - let body = response.into_body(); Ok( GetPetByIdResponse::InvalidIDSupplied ) } 404 => { - let body = response.into_body(); Ok( GetPetByIdResponse::PetNotFound ) @@ -2316,7 +2315,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let body = param_body.to_xml(); + let body = param_body.as_xml(); *request.body_mut() = Body::from(body); let header = "application/json"; @@ -2324,14 +2323,16 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -2347,24 +2348,21 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 400 => { - let body = response.into_body(); Ok( UpdatePetResponse::InvalidIDSupplied ) } 404 => { - let body = response.into_body(); Ok( UpdatePetResponse::PetNotFound ) } 405 => { - let body = response.into_body(); Ok( UpdatePetResponse::ValidationException ) @@ -2438,14 +2436,16 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); *request.body_mut() = Body::from(body.into_bytes()); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -2461,12 +2461,11 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 405 => { - let body = response.into_body(); Ok( UpdatePetWithFormResponse::InvalidInput ) @@ -2583,14 +2582,16 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", multipart_header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -2606,7 +2607,7 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2679,24 +2680,22 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 400 => { - let body = response.into_body(); Ok( DeleteOrderResponse::InvalidIDSupplied ) } 404 => { - let body = response.into_body(); Ok( DeleteOrderResponse::OrderNotFound ) @@ -2754,20 +2753,22 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { _ => {} } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2840,13 +2841,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2866,13 +2867,11 @@ impl Api for Client where ) } 400 => { - let body = response.into_body(); Ok( GetOrderByIdResponse::InvalidIDSupplied ) } 404 => { - let body = response.into_body(); Ok( GetOrderByIdResponse::OrderNotFound ) @@ -2941,13 +2940,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -2967,7 +2966,6 @@ impl Api for Client where ) } 400 => { - let body = response.into_body(); Ok( PlaceOrderResponse::InvalidOrder ) @@ -3035,18 +3033,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 0 => { - let body = response.into_body(); Ok( CreateUserResponse::SuccessfulOperation ) @@ -3113,18 +3110,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 0 => { - let body = response.into_body(); Ok( CreateUsersWithArrayInputResponse::SuccessfulOperation ) @@ -3191,18 +3187,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 0 => { - let body = response.into_body(); Ok( CreateUsersWithListInputResponse::SuccessfulOperation ) @@ -3262,24 +3257,22 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 400 => { - let body = response.into_body(); Ok( DeleteUserResponse::InvalidUsernameSupplied ) } 404 => { - let body = response.into_body(); Ok( DeleteUserResponse::UserNotFound ) @@ -3339,13 +3332,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -3365,13 +3358,11 @@ impl Api for Client where ) } 400 => { - let body = response.into_body(); Ok( GetUserByNameResponse::InvalidUsernameSupplied ) } 404 => { - let body = response.into_body(); Ok( GetUserByNameResponse::UserNotFound ) @@ -3412,9 +3403,9 @@ impl Api for Client where let query_string = { let mut query_string = form_urlencoded::Serializer::new("".to_owned()); query_string.append_pair("username", - ¶m_username.to_string()); + ¶m_username); query_string.append_pair("password", - ¶m_password.to_string()); + ¶m_password); query_string.finish() }; if !query_string.is_empty() { @@ -3435,13 +3426,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -3455,8 +3446,7 @@ impl Api for Client where return Err(ApiError(format!("Invalid response header X-Rate-Limit for response 200 - {}", e))); }, }; - let response_x_rate_limit = response_x_rate_limit.0; - Some(response_x_rate_limit) + Some(response_x_rate_limit.0) }, None => None, }; @@ -3470,8 +3460,7 @@ impl Api for Client where return Err(ApiError(format!("Invalid response header X-Expires-After for response 200 - {}", e))); }, }; - let response_x_expires_after = response_x_expires_after.0; - Some(response_x_expires_after) + Some(response_x_expires_after.0) }, None => None, }; @@ -3488,14 +3477,13 @@ impl Api for Client where .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; Ok(LoginUserResponse::SuccessfulOperation { - body: body, + body, x_rate_limit: response_x_rate_limit, x_expires_after: response_x_expires_after, } ) } 400 => { - let body = response.into_body(); Ok( LoginUserResponse::InvalidUsername ) @@ -3553,18 +3541,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 0 => { - let body = response.into_body(); Ok( LogoutUserResponse::SuccessfulOperation ) @@ -3635,24 +3622,22 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 400 => { - let body = response.into_body(); Ok( UpdateUserResponse::InvalidUserSupplied ) } 404 => { - let body = response.into_body(); Ok( UpdateUserResponse::UserNotFound ) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/context.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/context.rs index d9b7113417..dc28f08c1c 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/context.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/context.rs @@ -107,7 +107,7 @@ impl Service> for AddContext); @@ -119,7 +119,7 @@ impl Service> for AddContext Service> for AddContext(&headers) { + if let Some(basic) = swagger::auth::from_headers::(headers) { let auth_data = AuthData::Basic(basic); let context = context.push(Some(auth_data)); let context = context.push(None::); @@ -142,7 +142,7 @@ impl Service> for AddContext(&headers) { + if let Some(bearer) = swagger::auth::from_headers::(headers) { let auth_data = AuthData::Bearer(bearer); let context = context.push(Some(auth_data)); let context = context.push(None::); diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs index c0364fee2a..18a5ecab02 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs @@ -1,4 +1,6 @@ #![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::blacklisted_name)] use async_trait::async_trait; use futures::Stream; @@ -9,8 +11,8 @@ use serde::{Serialize, Deserialize}; type ServiceError = Box; -pub const BASE_PATH: &'static str = "/v2"; -pub const API_VERSION: &'static str = "1.0.0"; +pub const BASE_PATH: &str = "/v2"; +pub const API_VERSION: &str = "1.0.0"; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum TestSpecialTagsResponse { @@ -315,6 +317,7 @@ pub enum UpdateUserResponse { /// API #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait Api { fn poll_ready(&self, _cx: &mut Context) -> Poll>> { Poll::Ready(Ok(())) @@ -550,6 +553,7 @@ pub trait Api { /// API where `Context` isn't passed on every API call #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait ApiNoContext { fn poll_ready(&self, _cx: &mut Context) -> Poll>>; @@ -788,7 +792,7 @@ pub trait ApiNoContext { pub trait ContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> ContextWrapperExt for T { diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs index 1c4d90d71d..faf92e4f9a 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs @@ -18,6 +18,7 @@ pub struct AdditionalPropertiesClass { } impl AdditionalPropertiesClass { + #[allow(clippy::new_without_default)] pub fn new() -> AdditionalPropertiesClass { AdditionalPropertiesClass { map_property: None, @@ -31,13 +32,15 @@ impl AdditionalPropertiesClass { /// Should be implemented in a serde serializer impl std::string::ToString for AdditionalPropertiesClass { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping map_property in query parameter serialization + let params: Vec> = vec![ + // Skipping map_property in query parameter serialization - // Skipping map_of_map_property in query parameter serialization - // Skipping map_of_map_property in query parameter serialization + // Skipping map_of_map_property in query parameter serialization + // Skipping map_of_map_property in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -48,8 +51,9 @@ impl std::str::FromStr for AdditionalPropertiesClass { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub map_property: Vec>, pub map_of_map_property: Vec>>, @@ -58,7 +62,7 @@ impl std::str::FromStr for AdditionalPropertiesClass { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -68,6 +72,7 @@ impl std::str::FromStr for AdditionalPropertiesClass { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { "map_property" => return std::result::Result::Err("Parsing a container in this style is not supported in AdditionalPropertiesClass".to_string()), "map_of_map_property" => return std::result::Result::Err("Parsing a container in this style is not supported in AdditionalPropertiesClass".to_string()), @@ -130,7 +135,7 @@ impl AdditionalPropertiesClass { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -148,9 +153,10 @@ pub struct Animal { } impl Animal { + #[allow(clippy::new_without_default)] pub fn new(class_name: String, ) -> Animal { Animal { - class_name: class_name, + class_name, color: Some("red".to_string()), } } @@ -161,18 +167,22 @@ impl Animal { /// Should be implemented in a serde serializer impl std::string::ToString for Animal { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("className".to_string()); - params.push(self.class_name.to_string()); + Some("className".to_string()), + Some(self.class_name.to_string()), - if let Some(ref color) = self.color { - params.push("color".to_string()); - params.push(color.to_string()); - } + self.color.as_ref().map(|color| { + vec![ + "color".to_string(), + color.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -183,8 +193,9 @@ impl std::str::FromStr for Animal { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub class_name: Vec, pub color: Vec, @@ -193,7 +204,7 @@ impl std::str::FromStr for Animal { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -203,9 +214,12 @@ impl std::str::FromStr for Animal { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "className" => intermediate_rep.class_name.push(::from_str(val).map_err(|x| format!("{}", x))?), - "color" => intermediate_rep.color.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "className" => intermediate_rep.class_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "color" => intermediate_rep.color.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Animal".to_string()) } } @@ -216,7 +230,7 @@ impl std::str::FromStr for Animal { // Use the intermediate representation to return the struct std::result::Result::Ok(Animal { - class_name: intermediate_rep.class_name.into_iter().next().ok_or("className missing in Animal".to_string())?, + class_name: intermediate_rep.class_name.into_iter().next().ok_or_else(|| "className missing in Animal".to_string())?, color: intermediate_rep.color.into_iter().next(), }) } @@ -265,7 +279,7 @@ impl Animal { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -308,7 +322,7 @@ impl<'a> std::iter::IntoIterator for &'a AnimalFarm { type IntoIter = std::slice::Iter<'a, Animal>; fn into_iter(self) -> Self::IntoIter { - (&self.0).into_iter() + (&self.0).iter() } } @@ -317,7 +331,7 @@ impl<'a> std::iter::IntoIterator for &'a mut AnimalFarm { type IntoIter = std::slice::IterMut<'a, Animal>; fn into_iter(self) -> Self::IntoIter { - (&mut self.0).into_iter() + (&mut self.0).iter_mut() } } @@ -339,7 +353,7 @@ impl std::ops::DerefMut for AnimalFarm { /// Should be implemented in a serde serializer impl std::string::ToString for AnimalFarm { fn to_string(&self) -> String { - self.iter().map(|x| x.to_string()).collect::>().join(",").to_string() + self.iter().map(|x| x.to_string()).collect::>().join(",") } } @@ -403,7 +417,7 @@ impl AnimalFarm { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -417,7 +431,7 @@ pub struct ApiResponse { #[serde(rename = "type")] #[serde(skip_serializing_if="Option::is_none")] - pub type_: Option, + pub r#type: Option, #[serde(rename = "message")] #[serde(skip_serializing_if="Option::is_none")] @@ -426,10 +440,11 @@ pub struct ApiResponse { } impl ApiResponse { + #[allow(clippy::new_without_default)] pub fn new() -> ApiResponse { ApiResponse { code: None, - type_: None, + r#type: None, message: None, } } @@ -440,26 +455,34 @@ impl ApiResponse { /// Should be implemented in a serde serializer impl std::string::ToString for ApiResponse { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref code) = self.code { - params.push("code".to_string()); - params.push(code.to_string()); - } + self.code.as_ref().map(|code| { + vec![ + "code".to_string(), + code.to_string(), + ].join(",") + }), - if let Some(ref type_) = self.type_ { - params.push("type".to_string()); - params.push(type_.to_string()); - } + self.r#type.as_ref().map(|r#type| { + vec![ + "type".to_string(), + r#type.to_string(), + ].join(",") + }), - if let Some(ref message) = self.message { - params.push("message".to_string()); - params.push(message.to_string()); - } + self.message.as_ref().map(|message| { + vec![ + "message".to_string(), + message.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -470,18 +493,19 @@ impl std::str::FromStr for ApiResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub code: Vec, - pub type_: Vec, + pub r#type: Vec, pub message: Vec, } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -491,10 +515,14 @@ impl std::str::FromStr for ApiResponse { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "code" => intermediate_rep.code.push(::from_str(val).map_err(|x| format!("{}", x))?), - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "code" => intermediate_rep.code.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "type" => intermediate_rep.r#type.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing ApiResponse".to_string()) } } @@ -506,7 +534,7 @@ impl std::str::FromStr for ApiResponse { // Use the intermediate representation to return the struct std::result::Result::Ok(ApiResponse { code: intermediate_rep.code.into_iter().next(), - type_: intermediate_rep.type_.into_iter().next(), + r#type: intermediate_rep.r#type.into_iter().next(), message: intermediate_rep.message.into_iter().next(), }) } @@ -555,7 +583,7 @@ impl ApiResponse { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -570,6 +598,7 @@ pub struct ArrayOfArrayOfNumberOnly { } impl ArrayOfArrayOfNumberOnly { + #[allow(clippy::new_without_default)] pub fn new() -> ArrayOfArrayOfNumberOnly { ArrayOfArrayOfNumberOnly { array_array_number: None, @@ -582,10 +611,12 @@ impl ArrayOfArrayOfNumberOnly { /// Should be implemented in a serde serializer impl std::string::ToString for ArrayOfArrayOfNumberOnly { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping ArrayArrayNumber in query parameter serialization + let params: Vec> = vec![ + // Skipping ArrayArrayNumber in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -596,8 +627,9 @@ impl std::str::FromStr for ArrayOfArrayOfNumberOnly { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub array_array_number: Vec>>, } @@ -605,7 +637,7 @@ impl std::str::FromStr for ArrayOfArrayOfNumberOnly { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -615,6 +647,7 @@ impl std::str::FromStr for ArrayOfArrayOfNumberOnly { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { "ArrayArrayNumber" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayOfArrayOfNumberOnly".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing ArrayOfArrayOfNumberOnly".to_string()) @@ -675,7 +708,7 @@ impl ArrayOfArrayOfNumberOnly { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -690,6 +723,7 @@ pub struct ArrayOfNumberOnly { } impl ArrayOfNumberOnly { + #[allow(clippy::new_without_default)] pub fn new() -> ArrayOfNumberOnly { ArrayOfNumberOnly { array_number: None, @@ -702,14 +736,18 @@ impl ArrayOfNumberOnly { /// Should be implemented in a serde serializer impl std::string::ToString for ArrayOfNumberOnly { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref array_number) = self.array_number { - params.push("ArrayNumber".to_string()); - params.push(array_number.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - } + self.array_number.as_ref().map(|array_number| { + vec![ + "ArrayNumber".to_string(), + array_number.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -720,8 +758,9 @@ impl std::str::FromStr for ArrayOfNumberOnly { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub array_number: Vec>, } @@ -729,7 +768,7 @@ impl std::str::FromStr for ArrayOfNumberOnly { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -739,6 +778,7 @@ impl std::str::FromStr for ArrayOfNumberOnly { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { "ArrayNumber" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayOfNumberOnly".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing ArrayOfNumberOnly".to_string()) @@ -799,7 +839,7 @@ impl ArrayOfNumberOnly { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -827,6 +867,7 @@ pub struct ArrayTest { } impl ArrayTest { + #[allow(clippy::new_without_default)] pub fn new() -> ArrayTest { ArrayTest { array_of_string: None, @@ -842,24 +883,30 @@ impl ArrayTest { /// Should be implemented in a serde serializer impl std::string::ToString for ArrayTest { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref array_of_string) = self.array_of_string { - params.push("array_of_string".to_string()); - params.push(array_of_string.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - } + self.array_of_string.as_ref().map(|array_of_string| { + vec![ + "array_of_string".to_string(), + array_of_string.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), - // Skipping array_array_of_integer in query parameter serialization + // Skipping array_array_of_integer in query parameter serialization - // Skipping array_array_of_model in query parameter serialization + // Skipping array_array_of_model in query parameter serialization - if let Some(ref array_of_enum) = self.array_of_enum { - params.push("array_of_enum".to_string()); - params.push(array_of_enum.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - } + self.array_of_enum.as_ref().map(|array_of_enum| { + vec![ + "array_of_enum".to_string(), + array_of_enum.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -870,8 +917,9 @@ impl std::str::FromStr for ArrayTest { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub array_of_string: Vec>, pub array_array_of_integer: Vec>>, @@ -882,7 +930,7 @@ impl std::str::FromStr for ArrayTest { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -892,6 +940,7 @@ impl std::str::FromStr for ArrayTest { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { "array_of_string" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayTest".to_string()), "array_array_of_integer" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayTest".to_string()), @@ -958,7 +1007,7 @@ impl ArrayTest { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -994,6 +1043,7 @@ pub struct Capitalization { } impl Capitalization { + #[allow(clippy::new_without_default)] pub fn new() -> Capitalization { Capitalization { small_camel: None, @@ -1011,44 +1061,58 @@ impl Capitalization { /// Should be implemented in a serde serializer impl std::string::ToString for Capitalization { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref small_camel) = self.small_camel { - params.push("smallCamel".to_string()); - params.push(small_camel.to_string()); - } + self.small_camel.as_ref().map(|small_camel| { + vec![ + "smallCamel".to_string(), + small_camel.to_string(), + ].join(",") + }), - if let Some(ref capital_camel) = self.capital_camel { - params.push("CapitalCamel".to_string()); - params.push(capital_camel.to_string()); - } + self.capital_camel.as_ref().map(|capital_camel| { + vec![ + "CapitalCamel".to_string(), + capital_camel.to_string(), + ].join(",") + }), - if let Some(ref small_snake) = self.small_snake { - params.push("small_Snake".to_string()); - params.push(small_snake.to_string()); - } + self.small_snake.as_ref().map(|small_snake| { + vec![ + "small_Snake".to_string(), + small_snake.to_string(), + ].join(",") + }), - if let Some(ref capital_snake) = self.capital_snake { - params.push("Capital_Snake".to_string()); - params.push(capital_snake.to_string()); - } + self.capital_snake.as_ref().map(|capital_snake| { + vec![ + "Capital_Snake".to_string(), + capital_snake.to_string(), + ].join(",") + }), - if let Some(ref sca_eth_flow_points) = self.sca_eth_flow_points { - params.push("SCA_ETH_Flow_Points".to_string()); - params.push(sca_eth_flow_points.to_string()); - } + self.sca_eth_flow_points.as_ref().map(|sca_eth_flow_points| { + vec![ + "SCA_ETH_Flow_Points".to_string(), + sca_eth_flow_points.to_string(), + ].join(",") + }), - if let Some(ref att_name) = self.att_name { - params.push("ATT_NAME".to_string()); - params.push(att_name.to_string()); - } + self.att_name.as_ref().map(|att_name| { + vec![ + "ATT_NAME".to_string(), + att_name.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1059,8 +1123,9 @@ impl std::str::FromStr for Capitalization { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub small_camel: Vec, pub capital_camel: Vec, @@ -1073,7 +1138,7 @@ impl std::str::FromStr for Capitalization { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1083,13 +1148,20 @@ impl std::str::FromStr for Capitalization { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "smallCamel" => intermediate_rep.small_camel.push(::from_str(val).map_err(|x| format!("{}", x))?), - "CapitalCamel" => intermediate_rep.capital_camel.push(::from_str(val).map_err(|x| format!("{}", x))?), - "small_Snake" => intermediate_rep.small_snake.push(::from_str(val).map_err(|x| format!("{}", x))?), - "Capital_Snake" => intermediate_rep.capital_snake.push(::from_str(val).map_err(|x| format!("{}", x))?), - "SCA_ETH_Flow_Points" => intermediate_rep.sca_eth_flow_points.push(::from_str(val).map_err(|x| format!("{}", x))?), - "ATT_NAME" => intermediate_rep.att_name.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "smallCamel" => intermediate_rep.small_camel.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "CapitalCamel" => intermediate_rep.capital_camel.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "small_Snake" => intermediate_rep.small_snake.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "Capital_Snake" => intermediate_rep.capital_snake.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "SCA_ETH_Flow_Points" => intermediate_rep.sca_eth_flow_points.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "ATT_NAME" => intermediate_rep.att_name.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Capitalization".to_string()) } } @@ -1153,7 +1225,7 @@ impl Capitalization { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1175,9 +1247,10 @@ pub struct Cat { } impl Cat { + #[allow(clippy::new_without_default)] pub fn new(class_name: String, ) -> Cat { Cat { - class_name: class_name, + class_name, color: Some("red".to_string()), declawed: None, } @@ -1189,24 +1262,30 @@ impl Cat { /// Should be implemented in a serde serializer impl std::string::ToString for Cat { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("className".to_string()); - params.push(self.class_name.to_string()); + Some("className".to_string()), + Some(self.class_name.to_string()), - if let Some(ref color) = self.color { - params.push("color".to_string()); - params.push(color.to_string()); - } + self.color.as_ref().map(|color| { + vec![ + "color".to_string(), + color.to_string(), + ].join(",") + }), - if let Some(ref declawed) = self.declawed { - params.push("declawed".to_string()); - params.push(declawed.to_string()); - } + self.declawed.as_ref().map(|declawed| { + vec![ + "declawed".to_string(), + declawed.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1217,8 +1296,9 @@ impl std::str::FromStr for Cat { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub class_name: Vec, pub color: Vec, @@ -1228,7 +1308,7 @@ impl std::str::FromStr for Cat { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1238,10 +1318,14 @@ impl std::str::FromStr for Cat { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "className" => intermediate_rep.class_name.push(::from_str(val).map_err(|x| format!("{}", x))?), - "color" => intermediate_rep.color.push(::from_str(val).map_err(|x| format!("{}", x))?), - "declawed" => intermediate_rep.declawed.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "className" => intermediate_rep.class_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "color" => intermediate_rep.color.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "declawed" => intermediate_rep.declawed.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Cat".to_string()) } } @@ -1252,7 +1336,7 @@ impl std::str::FromStr for Cat { // Use the intermediate representation to return the struct std::result::Result::Ok(Cat { - class_name: intermediate_rep.class_name.into_iter().next().ok_or("className missing in Cat".to_string())?, + class_name: intermediate_rep.class_name.into_iter().next().ok_or_else(|| "className missing in Cat".to_string())?, color: intermediate_rep.color.into_iter().next(), declawed: intermediate_rep.declawed.into_iter().next(), }) @@ -1302,7 +1386,7 @@ impl Cat { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1317,6 +1401,7 @@ pub struct CatAllOf { } impl CatAllOf { + #[allow(clippy::new_without_default)] pub fn new() -> CatAllOf { CatAllOf { declawed: None, @@ -1329,14 +1414,18 @@ impl CatAllOf { /// Should be implemented in a serde serializer impl std::string::ToString for CatAllOf { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref declawed) = self.declawed { - params.push("declawed".to_string()); - params.push(declawed.to_string()); - } + self.declawed.as_ref().map(|declawed| { + vec![ + "declawed".to_string(), + declawed.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1347,8 +1436,9 @@ impl std::str::FromStr for CatAllOf { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub declawed: Vec, } @@ -1356,7 +1446,7 @@ impl std::str::FromStr for CatAllOf { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1366,8 +1456,10 @@ impl std::str::FromStr for CatAllOf { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "declawed" => intermediate_rep.declawed.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "declawed" => intermediate_rep.declawed.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing CatAllOf".to_string()) } } @@ -1426,7 +1518,7 @@ impl CatAllOf { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1446,6 +1538,7 @@ pub struct Category { } impl Category { + #[allow(clippy::new_without_default)] pub fn new() -> Category { Category { id: None, @@ -1459,20 +1552,26 @@ impl Category { /// Should be implemented in a serde serializer impl std::string::ToString for Category { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref id) = self.id { - params.push("id".to_string()); - params.push(id.to_string()); - } + self.id.as_ref().map(|id| { + vec![ + "id".to_string(), + id.to_string(), + ].join(",") + }), - if let Some(ref name) = self.name { - params.push("name".to_string()); - params.push(name.to_string()); - } + self.name.as_ref().map(|name| { + vec![ + "name".to_string(), + name.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1483,8 +1582,9 @@ impl std::str::FromStr for Category { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub id: Vec, pub name: Vec, @@ -1493,7 +1593,7 @@ impl std::str::FromStr for Category { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1503,9 +1603,12 @@ impl std::str::FromStr for Category { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| format!("{}", x))?), - "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Category".to_string()) } } @@ -1565,7 +1668,7 @@ impl Category { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1581,6 +1684,7 @@ pub struct ClassModel { } impl ClassModel { + #[allow(clippy::new_without_default)] pub fn new() -> ClassModel { ClassModel { _class: None, @@ -1593,14 +1697,18 @@ impl ClassModel { /// Should be implemented in a serde serializer impl std::string::ToString for ClassModel { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref _class) = self._class { - params.push("_class".to_string()); - params.push(_class.to_string()); - } + self._class.as_ref().map(|_class| { + vec![ + "_class".to_string(), + _class.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1611,8 +1719,9 @@ impl std::str::FromStr for ClassModel { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub _class: Vec, } @@ -1620,7 +1729,7 @@ impl std::str::FromStr for ClassModel { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1630,8 +1739,10 @@ impl std::str::FromStr for ClassModel { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "_class" => intermediate_rep._class.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "_class" => intermediate_rep._class.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing ClassModel".to_string()) } } @@ -1690,7 +1801,7 @@ impl ClassModel { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1705,6 +1816,7 @@ pub struct Client { } impl Client { + #[allow(clippy::new_without_default)] pub fn new() -> Client { Client { client: None, @@ -1717,14 +1829,18 @@ impl Client { /// Should be implemented in a serde serializer impl std::string::ToString for Client { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref client) = self.client { - params.push("client".to_string()); - params.push(client.to_string()); - } + self.client.as_ref().map(|client| { + vec![ + "client".to_string(), + client.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1735,8 +1851,9 @@ impl std::str::FromStr for Client { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub client: Vec, } @@ -1744,7 +1861,7 @@ impl std::str::FromStr for Client { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1754,8 +1871,10 @@ impl std::str::FromStr for Client { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "client" => intermediate_rep.client.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "client" => intermediate_rep.client.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Client".to_string()) } } @@ -1814,7 +1933,7 @@ impl Client { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1836,9 +1955,10 @@ pub struct Dog { } impl Dog { + #[allow(clippy::new_without_default)] pub fn new(class_name: String, ) -> Dog { Dog { - class_name: class_name, + class_name, color: Some("red".to_string()), breed: None, } @@ -1850,24 +1970,30 @@ impl Dog { /// Should be implemented in a serde serializer impl std::string::ToString for Dog { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("className".to_string()); - params.push(self.class_name.to_string()); + Some("className".to_string()), + Some(self.class_name.to_string()), - if let Some(ref color) = self.color { - params.push("color".to_string()); - params.push(color.to_string()); - } + self.color.as_ref().map(|color| { + vec![ + "color".to_string(), + color.to_string(), + ].join(",") + }), - if let Some(ref breed) = self.breed { - params.push("breed".to_string()); - params.push(breed.to_string()); - } + self.breed.as_ref().map(|breed| { + vec![ + "breed".to_string(), + breed.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -1878,8 +2004,9 @@ impl std::str::FromStr for Dog { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub class_name: Vec, pub color: Vec, @@ -1889,7 +2016,7 @@ impl std::str::FromStr for Dog { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -1899,10 +2026,14 @@ impl std::str::FromStr for Dog { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "className" => intermediate_rep.class_name.push(::from_str(val).map_err(|x| format!("{}", x))?), - "color" => intermediate_rep.color.push(::from_str(val).map_err(|x| format!("{}", x))?), - "breed" => intermediate_rep.breed.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "className" => intermediate_rep.class_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "color" => intermediate_rep.color.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "breed" => intermediate_rep.breed.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Dog".to_string()) } } @@ -1913,7 +2044,7 @@ impl std::str::FromStr for Dog { // Use the intermediate representation to return the struct std::result::Result::Ok(Dog { - class_name: intermediate_rep.class_name.into_iter().next().ok_or("className missing in Dog".to_string())?, + class_name: intermediate_rep.class_name.into_iter().next().ok_or_else(|| "className missing in Dog".to_string())?, color: intermediate_rep.color.into_iter().next(), breed: intermediate_rep.breed.into_iter().next(), }) @@ -1963,7 +2094,7 @@ impl Dog { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -1978,6 +2109,7 @@ pub struct DogAllOf { } impl DogAllOf { + #[allow(clippy::new_without_default)] pub fn new() -> DogAllOf { DogAllOf { breed: None, @@ -1990,14 +2122,18 @@ impl DogAllOf { /// Should be implemented in a serde serializer impl std::string::ToString for DogAllOf { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref breed) = self.breed { - params.push("breed".to_string()); - params.push(breed.to_string()); - } + self.breed.as_ref().map(|breed| { + vec![ + "breed".to_string(), + breed.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2008,8 +2144,9 @@ impl std::str::FromStr for DogAllOf { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub breed: Vec, } @@ -2017,7 +2154,7 @@ impl std::str::FromStr for DogAllOf { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2027,8 +2164,10 @@ impl std::str::FromStr for DogAllOf { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "breed" => intermediate_rep.breed.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "breed" => intermediate_rep.breed.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing DogAllOf".to_string()) } } @@ -2087,7 +2226,140 @@ impl DogAllOf { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +#[serde(rename = "$special[model.name]")] +pub struct DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + #[serde(rename = "$special[property.name]")] + #[serde(skip_serializing_if="Option::is_none")] + pub dollar_special_left_square_bracket_property_period_name_right_square_bracket: Option, + +} + +impl DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + #[allow(clippy::new_without_default)] + pub fn new() -> DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + dollar_special_left_square_bracket_property_period_name_right_square_bracket: None, + } + } +} + +/// Converts the DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.dollar_special_left_square_bracket_property_period_name_right_square_bracket.as_ref().map(|dollar_special_left_square_bracket_property_period_name_right_square_bracket| { + vec![ + "$special[property.name]".to_string(), + dollar_special_left_square_bracket_property_period_name_right_square_bracket.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub dollar_special_left_square_bracket_property_period_name_right_square_bracket: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "$special[property.name]" => intermediate_rep.dollar_special_left_square_bracket_property_period_name_right_square_bracket.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + dollar_special_left_square_bracket_property_period_name_right_square_bracket: intermediate_rep.dollar_special_left_square_bracket_property_period_name_right_square_bracket.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + +impl DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2113,6 +2385,7 @@ pub struct EnumArrays { } impl EnumArrays { + #[allow(clippy::new_without_default)] pub fn new() -> EnumArrays { EnumArrays { just_symbol: None, @@ -2127,22 +2400,28 @@ impl EnumArrays { /// Should be implemented in a serde serializer impl std::string::ToString for EnumArrays { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref just_symbol) = self.just_symbol { - params.push("just_symbol".to_string()); - params.push(just_symbol.to_string()); - } + self.just_symbol.as_ref().map(|just_symbol| { + vec![ + "just_symbol".to_string(), + just_symbol.to_string(), + ].join(",") + }), - if let Some(ref array_enum) = self.array_enum { - params.push("array_enum".to_string()); - params.push(array_enum.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - } + self.array_enum.as_ref().map(|array_enum| { + vec![ + "array_enum".to_string(), + array_enum.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), - // Skipping array_array_enum in query parameter serialization + // Skipping array_array_enum in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2153,8 +2432,9 @@ impl std::str::FromStr for EnumArrays { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub just_symbol: Vec, pub array_enum: Vec>, @@ -2164,7 +2444,7 @@ impl std::str::FromStr for EnumArrays { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2174,8 +2454,10 @@ impl std::str::FromStr for EnumArrays { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "just_symbol" => intermediate_rep.just_symbol.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "just_symbol" => intermediate_rep.just_symbol.push(::from_str(val).map_err(|x| x.to_string())?), "array_enum" => return std::result::Result::Err("Parsing a container in this style is not supported in EnumArrays".to_string()), "array_array_enum" => return std::result::Result::Err("Parsing a container in this style is not supported in EnumArrays".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing EnumArrays".to_string()) @@ -2238,7 +2520,7 @@ impl EnumArrays { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2252,19 +2534,19 @@ impl EnumArrays { #[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] pub enum EnumClass { #[serde(rename = "_abc")] - _ABC, + Abc, #[serde(rename = "-efg")] - _EFG, + Efg, #[serde(rename = "(xyz)")] - _XYZ_, + LeftParenthesisXyzRightParenthesis, } impl std::fmt::Display for EnumClass { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { - EnumClass::_ABC => write!(f, "{}", "_abc"), - EnumClass::_EFG => write!(f, "{}", "-efg"), - EnumClass::_XYZ_ => write!(f, "{}", "(xyz)"), + EnumClass::Abc => write!(f, "_abc"), + EnumClass::Efg => write!(f, "-efg"), + EnumClass::LeftParenthesisXyzRightParenthesis => write!(f, "(xyz)"), } } } @@ -2274,9 +2556,9 @@ impl std::str::FromStr for EnumClass { fn from_str(s: &str) -> std::result::Result { match s { - "_abc" => std::result::Result::Ok(EnumClass::_ABC), - "-efg" => std::result::Result::Ok(EnumClass::_EFG), - "(xyz)" => std::result::Result::Ok(EnumClass::_XYZ_), + "_abc" => std::result::Result::Ok(EnumClass::Abc), + "-efg" => std::result::Result::Ok(EnumClass::Efg), + "(xyz)" => std::result::Result::Ok(EnumClass::LeftParenthesisXyzRightParenthesis), _ => std::result::Result::Err(format!("Value not valid: {}", s)), } } @@ -2286,7 +2568,7 @@ impl EnumClass { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2320,10 +2602,11 @@ pub struct EnumTest { } impl EnumTest { + #[allow(clippy::new_without_default)] pub fn new(enum_string_required: String, ) -> EnumTest { EnumTest { enum_string: None, - enum_string_required: enum_string_required, + enum_string_required, enum_integer: None, enum_number: None, outer_enum: None, @@ -2336,32 +2619,40 @@ impl EnumTest { /// Should be implemented in a serde serializer impl std::string::ToString for EnumTest { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref enum_string) = self.enum_string { - params.push("enum_string".to_string()); - params.push(enum_string.to_string()); - } + self.enum_string.as_ref().map(|enum_string| { + vec![ + "enum_string".to_string(), + enum_string.to_string(), + ].join(",") + }), - params.push("enum_string_required".to_string()); - params.push(self.enum_string_required.to_string()); + Some("enum_string_required".to_string()), + Some(self.enum_string_required.to_string()), - if let Some(ref enum_integer) = self.enum_integer { - params.push("enum_integer".to_string()); - params.push(enum_integer.to_string()); - } + self.enum_integer.as_ref().map(|enum_integer| { + vec![ + "enum_integer".to_string(), + enum_integer.to_string(), + ].join(",") + }), - if let Some(ref enum_number) = self.enum_number { - params.push("enum_number".to_string()); - params.push(enum_number.to_string()); - } + self.enum_number.as_ref().map(|enum_number| { + vec![ + "enum_number".to_string(), + enum_number.to_string(), + ].join(",") + }), - // Skipping outerEnum in query parameter serialization + // Skipping outerEnum in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2372,8 +2663,9 @@ impl std::str::FromStr for EnumTest { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub enum_string: Vec, pub enum_string_required: Vec, @@ -2385,7 +2677,7 @@ impl std::str::FromStr for EnumTest { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2395,12 +2687,18 @@ impl std::str::FromStr for EnumTest { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "enum_string" => intermediate_rep.enum_string.push(::from_str(val).map_err(|x| format!("{}", x))?), - "enum_string_required" => intermediate_rep.enum_string_required.push(::from_str(val).map_err(|x| format!("{}", x))?), - "enum_integer" => intermediate_rep.enum_integer.push(::from_str(val).map_err(|x| format!("{}", x))?), - "enum_number" => intermediate_rep.enum_number.push(::from_str(val).map_err(|x| format!("{}", x))?), - "outerEnum" => intermediate_rep.outer_enum.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "enum_string" => intermediate_rep.enum_string.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "enum_string_required" => intermediate_rep.enum_string_required.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "enum_integer" => intermediate_rep.enum_integer.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "enum_number" => intermediate_rep.enum_number.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "outerEnum" => intermediate_rep.outer_enum.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing EnumTest".to_string()) } } @@ -2412,7 +2710,7 @@ impl std::str::FromStr for EnumTest { // Use the intermediate representation to return the struct std::result::Result::Ok(EnumTest { enum_string: intermediate_rep.enum_string.into_iter().next(), - enum_string_required: intermediate_rep.enum_string_required.into_iter().next().ok_or("enum_string_required missing in EnumTest".to_string())?, + enum_string_required: intermediate_rep.enum_string_required.into_iter().next().ok_or_else(|| "enum_string_required missing in EnumTest".to_string())?, enum_integer: intermediate_rep.enum_integer.into_iter().next(), enum_number: intermediate_rep.enum_number.into_iter().next(), outer_enum: intermediate_rep.outer_enum.into_iter().next(), @@ -2463,7 +2761,7 @@ impl EnumTest { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2522,21 +2820,22 @@ pub struct FormatTest { } impl FormatTest { + #[allow(clippy::new_without_default)] pub fn new(number: f64, byte: swagger::ByteArray, date: chrono::DateTime::, password: String, ) -> FormatTest { FormatTest { integer: None, int32: None, int64: None, - number: number, + number, float: None, double: None, string: None, - byte: byte, + byte, binary: None, - date: date, + date, date_time: None, uuid: None, - password: password, + password, } } } @@ -2546,64 +2845,78 @@ impl FormatTest { /// Should be implemented in a serde serializer impl std::string::ToString for FormatTest { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref integer) = self.integer { - params.push("integer".to_string()); - params.push(integer.to_string()); - } + self.integer.as_ref().map(|integer| { + vec![ + "integer".to_string(), + integer.to_string(), + ].join(",") + }), - if let Some(ref int32) = self.int32 { - params.push("int32".to_string()); - params.push(int32.to_string()); - } + self.int32.as_ref().map(|int32| { + vec![ + "int32".to_string(), + int32.to_string(), + ].join(",") + }), - if let Some(ref int64) = self.int64 { - params.push("int64".to_string()); - params.push(int64.to_string()); - } + self.int64.as_ref().map(|int64| { + vec![ + "int64".to_string(), + int64.to_string(), + ].join(",") + }), - params.push("number".to_string()); - params.push(self.number.to_string()); + Some("number".to_string()), + Some(self.number.to_string()), - if let Some(ref float) = self.float { - params.push("float".to_string()); - params.push(float.to_string()); - } + self.float.as_ref().map(|float| { + vec![ + "float".to_string(), + float.to_string(), + ].join(",") + }), - if let Some(ref double) = self.double { - params.push("double".to_string()); - params.push(double.to_string()); - } + self.double.as_ref().map(|double| { + vec![ + "double".to_string(), + double.to_string(), + ].join(",") + }), - if let Some(ref string) = self.string { - params.push("string".to_string()); - params.push(string.to_string()); - } + self.string.as_ref().map(|string| { + vec![ + "string".to_string(), + string.to_string(), + ].join(",") + }), - // Skipping byte in query parameter serialization - // Skipping byte in query parameter serialization + // Skipping byte in query parameter serialization + // Skipping byte in query parameter serialization - // Skipping binary in query parameter serialization - // Skipping binary in query parameter serialization + // Skipping binary in query parameter serialization + // Skipping binary in query parameter serialization - // Skipping date in query parameter serialization + // Skipping date in query parameter serialization - // Skipping dateTime in query parameter serialization + // Skipping dateTime in query parameter serialization - // Skipping uuid in query parameter serialization + // Skipping uuid in query parameter serialization - params.push("password".to_string()); - params.push(self.password.to_string()); + Some("password".to_string()), + Some(self.password.to_string()), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2614,8 +2927,9 @@ impl std::str::FromStr for FormatTest { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub integer: Vec, pub int32: Vec, @@ -2635,7 +2949,7 @@ impl std::str::FromStr for FormatTest { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2645,20 +2959,32 @@ impl std::str::FromStr for FormatTest { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "integer" => intermediate_rep.integer.push(::from_str(val).map_err(|x| format!("{}", x))?), - "int32" => intermediate_rep.int32.push(::from_str(val).map_err(|x| format!("{}", x))?), - "int64" => intermediate_rep.int64.push(::from_str(val).map_err(|x| format!("{}", x))?), - "number" => intermediate_rep.number.push(::from_str(val).map_err(|x| format!("{}", x))?), - "float" => intermediate_rep.float.push(::from_str(val).map_err(|x| format!("{}", x))?), - "double" => intermediate_rep.double.push(::from_str(val).map_err(|x| format!("{}", x))?), - "string" => intermediate_rep.string.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "integer" => intermediate_rep.integer.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "int32" => intermediate_rep.int32.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "int64" => intermediate_rep.int64.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "number" => intermediate_rep.number.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "float" => intermediate_rep.float.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "double" => intermediate_rep.double.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "string" => intermediate_rep.string.push(::from_str(val).map_err(|x| x.to_string())?), "byte" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), "binary" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), - "date" => intermediate_rep.date.push( as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?), - "dateTime" => intermediate_rep.date_time.push( as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?), - "uuid" => intermediate_rep.uuid.push(::from_str(val).map_err(|x| format!("{}", x))?), - "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "date" => intermediate_rep.date.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "dateTime" => intermediate_rep.date_time.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "uuid" => intermediate_rep.uuid.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing FormatTest".to_string()) } } @@ -2672,16 +2998,16 @@ impl std::str::FromStr for FormatTest { integer: intermediate_rep.integer.into_iter().next(), int32: intermediate_rep.int32.into_iter().next(), int64: intermediate_rep.int64.into_iter().next(), - number: intermediate_rep.number.into_iter().next().ok_or("number missing in FormatTest".to_string())?, + number: intermediate_rep.number.into_iter().next().ok_or_else(|| "number missing in FormatTest".to_string())?, float: intermediate_rep.float.into_iter().next(), double: intermediate_rep.double.into_iter().next(), string: intermediate_rep.string.into_iter().next(), - byte: intermediate_rep.byte.into_iter().next().ok_or("byte missing in FormatTest".to_string())?, + byte: intermediate_rep.byte.into_iter().next().ok_or_else(|| "byte missing in FormatTest".to_string())?, binary: intermediate_rep.binary.into_iter().next(), - date: intermediate_rep.date.into_iter().next().ok_or("date missing in FormatTest".to_string())?, + date: intermediate_rep.date.into_iter().next().ok_or_else(|| "date missing in FormatTest".to_string())?, date_time: intermediate_rep.date_time.into_iter().next(), uuid: intermediate_rep.uuid.into_iter().next(), - password: intermediate_rep.password.into_iter().next().ok_or("password missing in FormatTest".to_string())?, + password: intermediate_rep.password.into_iter().next().ok_or_else(|| "password missing in FormatTest".to_string())?, }) } } @@ -2729,7 +3055,7 @@ impl FormatTest { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2748,6 +3074,7 @@ pub struct HasOnlyReadOnly { } impl HasOnlyReadOnly { + #[allow(clippy::new_without_default)] pub fn new() -> HasOnlyReadOnly { HasOnlyReadOnly { bar: None, @@ -2761,20 +3088,26 @@ impl HasOnlyReadOnly { /// Should be implemented in a serde serializer impl std::string::ToString for HasOnlyReadOnly { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref bar) = self.bar { - params.push("bar".to_string()); - params.push(bar.to_string()); - } + self.bar.as_ref().map(|bar| { + vec![ + "bar".to_string(), + bar.to_string(), + ].join(",") + }), - if let Some(ref foo) = self.foo { - params.push("foo".to_string()); - params.push(foo.to_string()); - } + self.foo.as_ref().map(|foo| { + vec![ + "foo".to_string(), + foo.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2785,8 +3118,9 @@ impl std::str::FromStr for HasOnlyReadOnly { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub bar: Vec, pub foo: Vec, @@ -2795,7 +3129,7 @@ impl std::str::FromStr for HasOnlyReadOnly { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2805,9 +3139,12 @@ impl std::str::FromStr for HasOnlyReadOnly { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "bar" => intermediate_rep.bar.push(::from_str(val).map_err(|x| format!("{}", x))?), - "foo" => intermediate_rep.foo.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "bar" => intermediate_rep.bar.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "foo" => intermediate_rep.foo.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing HasOnlyReadOnly".to_string()) } } @@ -2867,7 +3204,7 @@ impl HasOnlyReadOnly { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -2882,6 +3219,7 @@ pub struct List { } impl List { + #[allow(clippy::new_without_default)] pub fn new() -> List { List { param_123_list: None, @@ -2894,14 +3232,18 @@ impl List { /// Should be implemented in a serde serializer impl std::string::ToString for List { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref param_123_list) = self.param_123_list { - params.push("123-list".to_string()); - params.push(param_123_list.to_string()); - } + self.param_123_list.as_ref().map(|param_123_list| { + vec![ + "123-list".to_string(), + param_123_list.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -2912,8 +3254,9 @@ impl std::str::FromStr for List { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub param_123_list: Vec, } @@ -2921,7 +3264,7 @@ impl std::str::FromStr for List { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -2931,8 +3274,10 @@ impl std::str::FromStr for List { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "123-list" => intermediate_rep.param_123_list.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "123-list" => intermediate_rep.param_123_list.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing List".to_string()) } } @@ -2991,7 +3336,7 @@ impl List { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -3016,6 +3361,7 @@ pub struct MapTest { } impl MapTest { + #[allow(clippy::new_without_default)] pub fn new() -> MapTest { MapTest { map_map_of_string: None, @@ -3030,16 +3376,18 @@ impl MapTest { /// Should be implemented in a serde serializer impl std::string::ToString for MapTest { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping map_map_of_string in query parameter serialization - // Skipping map_map_of_string in query parameter serialization + let params: Vec> = vec![ + // Skipping map_map_of_string in query parameter serialization + // Skipping map_map_of_string in query parameter serialization - // Skipping map_map_of_enum in query parameter serialization - // Skipping map_map_of_enum in query parameter serialization + // Skipping map_map_of_enum in query parameter serialization + // Skipping map_map_of_enum in query parameter serialization - // Skipping map_of_enum_string in query parameter serialization + // Skipping map_of_enum_string in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -3050,8 +3398,9 @@ impl std::str::FromStr for MapTest { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub map_map_of_string: Vec>>, pub map_map_of_enum: Vec>>, @@ -3061,7 +3410,7 @@ impl std::str::FromStr for MapTest { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -3071,6 +3420,7 @@ impl std::str::FromStr for MapTest { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { "map_map_of_string" => return std::result::Result::Err("Parsing a container in this style is not supported in MapTest".to_string()), "map_map_of_enum" => return std::result::Result::Err("Parsing a container in this style is not supported in MapTest".to_string()), @@ -3135,7 +3485,7 @@ impl MapTest { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -3158,6 +3508,7 @@ pub struct MixedPropertiesAndAdditionalPropertiesClass { } impl MixedPropertiesAndAdditionalPropertiesClass { + #[allow(clippy::new_without_default)] pub fn new() -> MixedPropertiesAndAdditionalPropertiesClass { MixedPropertiesAndAdditionalPropertiesClass { uuid: None, @@ -3172,15 +3523,17 @@ impl MixedPropertiesAndAdditionalPropertiesClass { /// Should be implemented in a serde serializer impl std::string::ToString for MixedPropertiesAndAdditionalPropertiesClass { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping uuid in query parameter serialization + let params: Vec> = vec![ + // Skipping uuid in query parameter serialization - // Skipping dateTime in query parameter serialization + // Skipping dateTime in query parameter serialization - // Skipping map in query parameter serialization - // Skipping map in query parameter serialization + // Skipping map in query parameter serialization + // Skipping map in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -3191,8 +3544,9 @@ impl std::str::FromStr for MixedPropertiesAndAdditionalPropertiesClass { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub uuid: Vec, pub date_time: Vec>, @@ -3202,7 +3556,7 @@ impl std::str::FromStr for MixedPropertiesAndAdditionalPropertiesClass { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -3212,9 +3566,12 @@ impl std::str::FromStr for MixedPropertiesAndAdditionalPropertiesClass { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "uuid" => intermediate_rep.uuid.push(::from_str(val).map_err(|x| format!("{}", x))?), - "dateTime" => intermediate_rep.date_time.push( as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "uuid" => intermediate_rep.uuid.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "dateTime" => intermediate_rep.date_time.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), "map" => return std::result::Result::Err("Parsing a container in this style is not supported in MixedPropertiesAndAdditionalPropertiesClass".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing MixedPropertiesAndAdditionalPropertiesClass".to_string()) } @@ -3276,7 +3633,7 @@ impl MixedPropertiesAndAdditionalPropertiesClass { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -3297,6 +3654,7 @@ pub struct Model200Response { } impl Model200Response { + #[allow(clippy::new_without_default)] pub fn new() -> Model200Response { Model200Response { name: None, @@ -3310,20 +3668,26 @@ impl Model200Response { /// Should be implemented in a serde serializer impl std::string::ToString for Model200Response { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref name) = self.name { - params.push("name".to_string()); - params.push(name.to_string()); - } + self.name.as_ref().map(|name| { + vec![ + "name".to_string(), + name.to_string(), + ].join(",") + }), - if let Some(ref class) = self.class { - params.push("class".to_string()); - params.push(class.to_string()); - } + self.class.as_ref().map(|class| { + vec![ + "class".to_string(), + class.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -3334,8 +3698,9 @@ impl std::str::FromStr for Model200Response { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub name: Vec, pub class: Vec, @@ -3344,7 +3709,7 @@ impl std::str::FromStr for Model200Response { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -3354,9 +3719,12 @@ impl std::str::FromStr for Model200Response { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| format!("{}", x))?), - "class" => intermediate_rep.class.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "class" => intermediate_rep.class.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Model200Response".to_string()) } } @@ -3416,133 +3784,7 @@ impl Model200Response { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { - serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") - } -} - -/// Model for testing reserved words -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -#[serde(rename = "Return")] -pub struct ModelReturn { - #[serde(rename = "return")] - #[serde(skip_serializing_if="Option::is_none")] - pub return_: Option, - -} - -impl ModelReturn { - pub fn new() -> ModelReturn { - ModelReturn { - return_: None, - } - } -} - -/// Converts the ModelReturn value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for ModelReturn { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - if let Some(ref return_) = self.return_ { - params.push("return".to_string()); - params.push(return_.to_string()); - } - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a ModelReturn value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for ModelReturn { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub return_: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing ModelReturn".to_string()) - }; - - if let Some(key) = key_result { - match key { - "return" => intermediate_rep.return_.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing ModelReturn".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(ModelReturn { - return_: intermediate_rep.return_.into_iter().next(), - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for ModelReturn - value: {} is invalid {}", - hdr_value, e)) - } - } -} - -#[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into ModelReturn - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -impl ModelReturn { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -3565,14 +3807,15 @@ pub struct Name { #[serde(rename = "123Number")] #[serde(skip_serializing_if="Option::is_none")] - pub param_123_number: Option, + pub param_123_number: Option, } impl Name { + #[allow(clippy::new_without_default)] pub fn new(name: i32, ) -> Name { Name { - name: name, + name, snake_case: None, property: None, param_123_number: None, @@ -3585,30 +3828,38 @@ impl Name { /// Should be implemented in a serde serializer impl std::string::ToString for Name { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("name".to_string()); - params.push(self.name.to_string()); + Some("name".to_string()), + Some(self.name.to_string()), - if let Some(ref snake_case) = self.snake_case { - params.push("snake_case".to_string()); - params.push(snake_case.to_string()); - } + self.snake_case.as_ref().map(|snake_case| { + vec![ + "snake_case".to_string(), + snake_case.to_string(), + ].join(",") + }), - if let Some(ref property) = self.property { - params.push("property".to_string()); - params.push(property.to_string()); - } + self.property.as_ref().map(|property| { + vec![ + "property".to_string(), + property.to_string(), + ].join(",") + }), - if let Some(ref param_123_number) = self.param_123_number { - params.push("123Number".to_string()); - params.push(param_123_number.to_string()); - } + self.param_123_number.as_ref().map(|param_123_number| { + vec![ + "123Number".to_string(), + param_123_number.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -3619,19 +3870,20 @@ impl std::str::FromStr for Name { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub name: Vec, pub snake_case: Vec, pub property: Vec, - pub param_123_number: Vec, + pub param_123_number: Vec, } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -3641,11 +3893,16 @@ impl std::str::FromStr for Name { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| format!("{}", x))?), - "snake_case" => intermediate_rep.snake_case.push(::from_str(val).map_err(|x| format!("{}", x))?), - "property" => intermediate_rep.property.push(::from_str(val).map_err(|x| format!("{}", x))?), - "123Number" => intermediate_rep.param_123_number.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "snake_case" => intermediate_rep.snake_case.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "property" => intermediate_rep.property.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "123Number" => intermediate_rep.param_123_number.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Name".to_string()) } } @@ -3656,7 +3913,7 @@ impl std::str::FromStr for Name { // Use the intermediate representation to return the struct std::result::Result::Ok(Name { - name: intermediate_rep.name.into_iter().next().ok_or("name missing in Name".to_string())?, + name: intermediate_rep.name.into_iter().next().ok_or_else(|| "name missing in Name".to_string())?, snake_case: intermediate_rep.snake_case.into_iter().next(), property: intermediate_rep.property.into_iter().next(), param_123_number: intermediate_rep.param_123_number.into_iter().next(), @@ -3707,7 +3964,7 @@ impl Name { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -3722,6 +3979,7 @@ pub struct NumberOnly { } impl NumberOnly { + #[allow(clippy::new_without_default)] pub fn new() -> NumberOnly { NumberOnly { just_number: None, @@ -3734,14 +3992,18 @@ impl NumberOnly { /// Should be implemented in a serde serializer impl std::string::ToString for NumberOnly { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref just_number) = self.just_number { - params.push("JustNumber".to_string()); - params.push(just_number.to_string()); - } + self.just_number.as_ref().map(|just_number| { + vec![ + "JustNumber".to_string(), + just_number.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -3752,8 +4014,9 @@ impl std::str::FromStr for NumberOnly { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub just_number: Vec, } @@ -3761,7 +4024,7 @@ impl std::str::FromStr for NumberOnly { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -3771,8 +4034,10 @@ impl std::str::FromStr for NumberOnly { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "JustNumber" => intermediate_rep.just_number.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "JustNumber" => intermediate_rep.just_number.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing NumberOnly".to_string()) } } @@ -3831,7 +4096,7 @@ impl NumberOnly { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -3846,6 +4111,7 @@ pub struct ObjectContainingObjectWithOnlyAdditionalProperties { } impl ObjectContainingObjectWithOnlyAdditionalProperties { + #[allow(clippy::new_without_default)] pub fn new() -> ObjectContainingObjectWithOnlyAdditionalProperties { ObjectContainingObjectWithOnlyAdditionalProperties { inner: None, @@ -3858,10 +4124,12 @@ impl ObjectContainingObjectWithOnlyAdditionalProperties { /// Should be implemented in a serde serializer impl std::string::ToString for ObjectContainingObjectWithOnlyAdditionalProperties { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping inner in query parameter serialization + let params: Vec> = vec![ + // Skipping inner in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -3872,8 +4140,9 @@ impl std::str::FromStr for ObjectContainingObjectWithOnlyAdditionalProperties { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub inner: Vec, } @@ -3881,7 +4150,7 @@ impl std::str::FromStr for ObjectContainingObjectWithOnlyAdditionalProperties { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -3891,8 +4160,10 @@ impl std::str::FromStr for ObjectContainingObjectWithOnlyAdditionalProperties { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "inner" => intermediate_rep.inner.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "inner" => intermediate_rep.inner.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing ObjectContainingObjectWithOnlyAdditionalProperties".to_string()) } } @@ -3951,7 +4222,7 @@ impl ObjectContainingObjectWithOnlyAdditionalProperties { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4010,7 +4281,7 @@ impl ObjectWithOnlyAdditionalProperties { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4048,6 +4319,7 @@ pub struct Order { } impl Order { + #[allow(clippy::new_without_default)] pub fn new() -> Order { Order { id: None, @@ -4065,40 +4337,52 @@ impl Order { /// Should be implemented in a serde serializer impl std::string::ToString for Order { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref id) = self.id { - params.push("id".to_string()); - params.push(id.to_string()); - } + self.id.as_ref().map(|id| { + vec![ + "id".to_string(), + id.to_string(), + ].join(",") + }), - if let Some(ref pet_id) = self.pet_id { - params.push("petId".to_string()); - params.push(pet_id.to_string()); - } + self.pet_id.as_ref().map(|pet_id| { + vec![ + "petId".to_string(), + pet_id.to_string(), + ].join(",") + }), - if let Some(ref quantity) = self.quantity { - params.push("quantity".to_string()); - params.push(quantity.to_string()); - } + self.quantity.as_ref().map(|quantity| { + vec![ + "quantity".to_string(), + quantity.to_string(), + ].join(",") + }), - // Skipping shipDate in query parameter serialization + // Skipping shipDate in query parameter serialization - if let Some(ref status) = self.status { - params.push("status".to_string()); - params.push(status.to_string()); - } + self.status.as_ref().map(|status| { + vec![ + "status".to_string(), + status.to_string(), + ].join(",") + }), - if let Some(ref complete) = self.complete { - params.push("complete".to_string()); - params.push(complete.to_string()); - } + self.complete.as_ref().map(|complete| { + vec![ + "complete".to_string(), + complete.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -4109,8 +4393,9 @@ impl std::str::FromStr for Order { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub id: Vec, pub pet_id: Vec, @@ -4123,7 +4408,7 @@ impl std::str::FromStr for Order { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -4133,13 +4418,20 @@ impl std::str::FromStr for Order { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| format!("{}", x))?), - "petId" => intermediate_rep.pet_id.push(::from_str(val).map_err(|x| format!("{}", x))?), - "quantity" => intermediate_rep.quantity.push(::from_str(val).map_err(|x| format!("{}", x))?), - "shipDate" => intermediate_rep.ship_date.push( as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?), - "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| format!("{}", x))?), - "complete" => intermediate_rep.complete.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "petId" => intermediate_rep.pet_id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "quantity" => intermediate_rep.quantity.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "shipDate" => intermediate_rep.ship_date.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "complete" => intermediate_rep.complete.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Order".to_string()) } } @@ -4203,7 +4495,7 @@ impl Order { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4242,7 +4534,7 @@ impl OuterBoolean { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4265,6 +4557,7 @@ pub struct OuterComposite { } impl OuterComposite { + #[allow(clippy::new_without_default)] pub fn new() -> OuterComposite { OuterComposite { my_number: None, @@ -4279,26 +4572,34 @@ impl OuterComposite { /// Should be implemented in a serde serializer impl std::string::ToString for OuterComposite { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref my_number) = self.my_number { - params.push("my_number".to_string()); - params.push(my_number.to_string()); - } + self.my_number.as_ref().map(|my_number| { + vec![ + "my_number".to_string(), + my_number.to_string(), + ].join(",") + }), - if let Some(ref my_string) = self.my_string { - params.push("my_string".to_string()); - params.push(my_string.to_string()); - } + self.my_string.as_ref().map(|my_string| { + vec![ + "my_string".to_string(), + my_string.to_string(), + ].join(",") + }), - if let Some(ref my_boolean) = self.my_boolean { - params.push("my_boolean".to_string()); - params.push(my_boolean.to_string()); - } + self.my_boolean.as_ref().map(|my_boolean| { + vec![ + "my_boolean".to_string(), + my_boolean.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -4309,8 +4610,9 @@ impl std::str::FromStr for OuterComposite { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub my_number: Vec, pub my_string: Vec, @@ -4320,7 +4622,7 @@ impl std::str::FromStr for OuterComposite { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -4330,10 +4632,14 @@ impl std::str::FromStr for OuterComposite { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "my_number" => intermediate_rep.my_number.push(::from_str(val).map_err(|x| format!("{}", x))?), - "my_string" => intermediate_rep.my_string.push(::from_str(val).map_err(|x| format!("{}", x))?), - "my_boolean" => intermediate_rep.my_boolean.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "my_number" => intermediate_rep.my_number.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "my_string" => intermediate_rep.my_string.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "my_boolean" => intermediate_rep.my_boolean.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing OuterComposite".to_string()) } } @@ -4394,7 +4700,7 @@ impl OuterComposite { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4408,19 +4714,19 @@ impl OuterComposite { #[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] pub enum OuterEnum { #[serde(rename = "placed")] - PLACED, + Placed, #[serde(rename = "approved")] - APPROVED, + Approved, #[serde(rename = "delivered")] - DELIVERED, + Delivered, } impl std::fmt::Display for OuterEnum { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { - OuterEnum::PLACED => write!(f, "{}", "placed"), - OuterEnum::APPROVED => write!(f, "{}", "approved"), - OuterEnum::DELIVERED => write!(f, "{}", "delivered"), + OuterEnum::Placed => write!(f, "placed"), + OuterEnum::Approved => write!(f, "approved"), + OuterEnum::Delivered => write!(f, "delivered"), } } } @@ -4430,9 +4736,9 @@ impl std::str::FromStr for OuterEnum { fn from_str(s: &str) -> std::result::Result { match s { - "placed" => std::result::Result::Ok(OuterEnum::PLACED), - "approved" => std::result::Result::Ok(OuterEnum::APPROVED), - "delivered" => std::result::Result::Ok(OuterEnum::DELIVERED), + "placed" => std::result::Result::Ok(OuterEnum::Placed), + "approved" => std::result::Result::Ok(OuterEnum::Approved), + "delivered" => std::result::Result::Ok(OuterEnum::Delivered), _ => std::result::Result::Err(format!("Value not valid: {}", s)), } } @@ -4442,7 +4748,7 @@ impl OuterEnum { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4481,7 +4787,7 @@ impl OuterNumber { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4533,7 +4839,7 @@ impl OuterString { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4569,12 +4875,13 @@ pub struct Pet { } impl Pet { + #[allow(clippy::new_without_default)] pub fn new(name: String, photo_urls: Vec, ) -> Pet { Pet { id: None, category: None, - name: name, - photo_urls: photo_urls, + name, + photo_urls, tags: None, status: None, } @@ -4586,32 +4893,38 @@ impl Pet { /// Should be implemented in a serde serializer impl std::string::ToString for Pet { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref id) = self.id { - params.push("id".to_string()); - params.push(id.to_string()); - } + self.id.as_ref().map(|id| { + vec![ + "id".to_string(), + id.to_string(), + ].join(",") + }), - // Skipping category in query parameter serialization + // Skipping category in query parameter serialization - params.push("name".to_string()); - params.push(self.name.to_string()); + Some("name".to_string()), + Some(self.name.to_string()), - params.push("photoUrls".to_string()); - params.push(self.photo_urls.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + Some("photoUrls".to_string()), + Some(self.photo_urls.iter().map(|x| x.to_string()).collect::>().join(",")), - // Skipping tags in query parameter serialization + // Skipping tags in query parameter serialization - if let Some(ref status) = self.status { - params.push("status".to_string()); - params.push(status.to_string()); - } + self.status.as_ref().map(|status| { + vec![ + "status".to_string(), + status.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -4622,8 +4935,9 @@ impl std::str::FromStr for Pet { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub id: Vec, pub category: Vec, @@ -4636,7 +4950,7 @@ impl std::str::FromStr for Pet { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -4646,13 +4960,18 @@ impl std::str::FromStr for Pet { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| format!("{}", x))?), - "category" => intermediate_rep.category.push(::from_str(val).map_err(|x| format!("{}", x))?), - "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "category" => intermediate_rep.category.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), "photoUrls" => return std::result::Result::Err("Parsing a container in this style is not supported in Pet".to_string()), "tags" => return std::result::Result::Err("Parsing a container in this style is not supported in Pet".to_string()), - "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Pet".to_string()) } } @@ -4665,8 +4984,8 @@ impl std::str::FromStr for Pet { std::result::Result::Ok(Pet { id: intermediate_rep.id.into_iter().next(), category: intermediate_rep.category.into_iter().next(), - name: intermediate_rep.name.into_iter().next().ok_or("name missing in Pet".to_string())?, - photo_urls: intermediate_rep.photo_urls.into_iter().next().ok_or("photoUrls missing in Pet".to_string())?, + name: intermediate_rep.name.into_iter().next().ok_or_else(|| "name missing in Pet".to_string())?, + photo_urls: intermediate_rep.photo_urls.into_iter().next().ok_or_else(|| "photoUrls missing in Pet".to_string())?, tags: intermediate_rep.tags.into_iter().next(), status: intermediate_rep.status.into_iter().next(), }) @@ -4716,7 +5035,7 @@ impl Pet { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4735,6 +5054,7 @@ pub struct ReadOnlyFirst { } impl ReadOnlyFirst { + #[allow(clippy::new_without_default)] pub fn new() -> ReadOnlyFirst { ReadOnlyFirst { bar: None, @@ -4748,20 +5068,26 @@ impl ReadOnlyFirst { /// Should be implemented in a serde serializer impl std::string::ToString for ReadOnlyFirst { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref bar) = self.bar { - params.push("bar".to_string()); - params.push(bar.to_string()); - } + self.bar.as_ref().map(|bar| { + vec![ + "bar".to_string(), + bar.to_string(), + ].join(",") + }), - if let Some(ref baz) = self.baz { - params.push("baz".to_string()); - params.push(baz.to_string()); - } + self.baz.as_ref().map(|baz| { + vec![ + "baz".to_string(), + baz.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -4772,8 +5098,9 @@ impl std::str::FromStr for ReadOnlyFirst { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub bar: Vec, pub baz: Vec, @@ -4782,7 +5109,7 @@ impl std::str::FromStr for ReadOnlyFirst { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -4792,9 +5119,12 @@ impl std::str::FromStr for ReadOnlyFirst { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "bar" => intermediate_rep.bar.push(::from_str(val).map_err(|x| format!("{}", x))?), - "baz" => intermediate_rep.baz.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "bar" => intermediate_rep.bar.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "baz" => intermediate_rep.baz.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing ReadOnlyFirst".to_string()) } } @@ -4854,74 +5184,83 @@ impl ReadOnlyFirst { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } +/// Model for testing reserved words #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -#[serde(rename = "$special[model.name]")] -pub struct SpecialModelName { - #[serde(rename = "$special[property.name]")] +#[serde(rename = "Return")] +pub struct Return { + #[serde(rename = "return")] #[serde(skip_serializing_if="Option::is_none")] - pub special_property_name: Option, + pub r#return: Option, } -impl SpecialModelName { - pub fn new() -> SpecialModelName { - SpecialModelName { - special_property_name: None, +impl Return { + #[allow(clippy::new_without_default)] + pub fn new() -> Return { + Return { + r#return: None, } } } -/// Converts the SpecialModelName value to the Query Parameters representation (style=form, explode=false) +/// Converts the Return value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for SpecialModelName { +impl std::string::ToString for Return { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref special_property_name) = self.special_property_name { - params.push("$special[property.name]".to_string()); - params.push(special_property_name.to_string()); - } + self.r#return.as_ref().map(|r#return| { + vec![ + "return".to_string(), + r#return.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } -/// Converts Query Parameters representation (style=form, explode=false) to a SpecialModelName value +/// Converts Query Parameters representation (style=form, explode=false) to a Return value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for SpecialModelName { +impl std::str::FromStr for Return { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { - pub special_property_name: Vec, + pub r#return: Vec, } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing SpecialModelName".to_string()) + None => return std::result::Result::Err("Missing value while parsing Return".to_string()) }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "$special[property.name]" => intermediate_rep.special_property_name.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing SpecialModelName".to_string()) + #[allow(clippy::redundant_clone)] + "return" => intermediate_rep.r#return.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Return".to_string()) } } @@ -4930,40 +5269,40 @@ impl std::str::FromStr for SpecialModelName { } // Use the intermediate representation to return the struct - std::result::Result::Ok(SpecialModelName { - special_property_name: intermediate_rep.special_property_name.into_iter().next(), + std::result::Result::Ok(Return { + r#return: intermediate_rep.r#return.into_iter().next(), }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for SpecialModelName - value: {} is invalid {}", + format!("Invalid header value for Return - value: {} is invalid {}", hdr_value, e)) } } } #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into SpecialModelName - {}", + format!("Unable to convert header value '{}' into Return - {}", value, err)) } }, @@ -4975,11 +5314,11 @@ impl std::convert::TryFrom for header::IntoHeaderVal } -impl SpecialModelName { +impl Return { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -4999,6 +5338,7 @@ pub struct Tag { } impl Tag { + #[allow(clippy::new_without_default)] pub fn new() -> Tag { Tag { id: None, @@ -5012,20 +5352,26 @@ impl Tag { /// Should be implemented in a serde serializer impl std::string::ToString for Tag { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref id) = self.id { - params.push("id".to_string()); - params.push(id.to_string()); - } + self.id.as_ref().map(|id| { + vec![ + "id".to_string(), + id.to_string(), + ].join(",") + }), - if let Some(ref name) = self.name { - params.push("name".to_string()); - params.push(name.to_string()); - } + self.name.as_ref().map(|name| { + vec![ + "name".to_string(), + name.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -5036,8 +5382,9 @@ impl std::str::FromStr for Tag { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub id: Vec, pub name: Vec, @@ -5046,7 +5393,7 @@ impl std::str::FromStr for Tag { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -5056,9 +5403,12 @@ impl std::str::FromStr for Tag { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| format!("{}", x))?), - "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing Tag".to_string()) } } @@ -5118,7 +5468,7 @@ impl Tag { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } @@ -5163,6 +5513,7 @@ pub struct User { } impl User { + #[allow(clippy::new_without_default)] pub fn new() -> User { User { id: None, @@ -5182,56 +5533,74 @@ impl User { /// Should be implemented in a serde serializer impl std::string::ToString for User { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref id) = self.id { - params.push("id".to_string()); - params.push(id.to_string()); - } + self.id.as_ref().map(|id| { + vec![ + "id".to_string(), + id.to_string(), + ].join(",") + }), - if let Some(ref username) = self.username { - params.push("username".to_string()); - params.push(username.to_string()); - } + self.username.as_ref().map(|username| { + vec![ + "username".to_string(), + username.to_string(), + ].join(",") + }), - if let Some(ref first_name) = self.first_name { - params.push("firstName".to_string()); - params.push(first_name.to_string()); - } + self.first_name.as_ref().map(|first_name| { + vec![ + "firstName".to_string(), + first_name.to_string(), + ].join(",") + }), - if let Some(ref last_name) = self.last_name { - params.push("lastName".to_string()); - params.push(last_name.to_string()); - } + self.last_name.as_ref().map(|last_name| { + vec![ + "lastName".to_string(), + last_name.to_string(), + ].join(",") + }), - if let Some(ref email) = self.email { - params.push("email".to_string()); - params.push(email.to_string()); - } + self.email.as_ref().map(|email| { + vec![ + "email".to_string(), + email.to_string(), + ].join(",") + }), - if let Some(ref password) = self.password { - params.push("password".to_string()); - params.push(password.to_string()); - } + self.password.as_ref().map(|password| { + vec![ + "password".to_string(), + password.to_string(), + ].join(",") + }), - if let Some(ref phone) = self.phone { - params.push("phone".to_string()); - params.push(phone.to_string()); - } + self.phone.as_ref().map(|phone| { + vec![ + "phone".to_string(), + phone.to_string(), + ].join(",") + }), - if let Some(ref user_status) = self.user_status { - params.push("userStatus".to_string()); - params.push(user_status.to_string()); - } + self.user_status.as_ref().map(|user_status| { + vec![ + "userStatus".to_string(), + user_status.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -5242,8 +5611,9 @@ impl std::str::FromStr for User { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub id: Vec, pub username: Vec, @@ -5258,7 +5628,7 @@ impl std::str::FromStr for User { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -5268,15 +5638,24 @@ impl std::str::FromStr for User { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| format!("{}", x))?), - "username" => intermediate_rep.username.push(::from_str(val).map_err(|x| format!("{}", x))?), - "firstName" => intermediate_rep.first_name.push(::from_str(val).map_err(|x| format!("{}", x))?), - "lastName" => intermediate_rep.last_name.push(::from_str(val).map_err(|x| format!("{}", x))?), - "email" => intermediate_rep.email.push(::from_str(val).map_err(|x| format!("{}", x))?), - "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| format!("{}", x))?), - "phone" => intermediate_rep.phone.push(::from_str(val).map_err(|x| format!("{}", x))?), - "userStatus" => intermediate_rep.user_status.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "username" => intermediate_rep.username.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "firstName" => intermediate_rep.first_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "lastName" => intermediate_rep.last_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "email" => intermediate_rep.email.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "phone" => intermediate_rep.phone.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "userStatus" => intermediate_rep.user_status.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing User".to_string()) } } @@ -5342,7 +5721,7 @@ impl User { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] - pub(crate) fn to_xml(&self) -> String { + pub(crate) fn as_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } } diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs index 20736c1240..e2366ba364 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs @@ -102,6 +102,7 @@ mod paths { pub(crate) static ID_FAKE_HYPHENPARAM_HYPHEN_PARAM: usize = 3; lazy_static! { pub static ref REGEX_FAKE_HYPHENPARAM_HYPHEN_PARAM: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^/v2/fake/hyphenParam/(?P[^/?#]*)$") .expect("Unable to create regex for FAKE_HYPHENPARAM_HYPHEN_PARAM"); } @@ -120,12 +121,14 @@ mod paths { pub(crate) static ID_PET_PETID: usize = 16; lazy_static! { pub static ref REGEX_PET_PETID: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^/v2/pet/(?P[^/?#]*)$") .expect("Unable to create regex for PET_PETID"); } pub(crate) static ID_PET_PETID_UPLOADIMAGE: usize = 17; lazy_static! { pub static ref REGEX_PET_PETID_UPLOADIMAGE: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^/v2/pet/(?P[^/?#]*)/uploadImage$") .expect("Unable to create regex for PET_PETID_UPLOADIMAGE"); } @@ -134,6 +137,7 @@ mod paths { pub(crate) static ID_STORE_ORDER_ORDER_ID: usize = 20; lazy_static! { pub static ref REGEX_STORE_ORDER_ORDER_ID: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^/v2/store/order/(?P[^/?#]*)$") .expect("Unable to create regex for STORE_ORDER_ORDER_ID"); } @@ -145,6 +149,7 @@ mod paths { pub(crate) static ID_USER_USERNAME: usize = 26; lazy_static! { pub static ref REGEX_USER_USERNAME: regex::Regex = + #[allow(clippy::invalid_regex)] regex::Regex::new(r"^/v2/user/(?P[^/?#]*)$") .expect("Unable to create regex for USER_USERNAME"); } @@ -211,7 +216,7 @@ impl Service where { pub fn new(api_impl: T) -> Self { Service { - api_impl: api_impl, + api_impl, marker: PhantomData } } @@ -224,7 +229,7 @@ impl Clone for Service where fn clone(&self) -> Self { Service { api_impl: self.api_impl.clone(), - marker: self.marker.clone(), + marker: self.marker, } } } @@ -250,10 +255,10 @@ impl hyper::service::Service<(Request, C)> for Service where let (method, uri, headers) = (parts.method, parts.uri, parts.headers); let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); - match &method { + match method { // TestSpecialTags - PATCH /another-fake/dummy - &hyper::Method::PATCH if path.matched(paths::ID_ANOTHER_FAKE_DUMMY) => { + hyper::Method::PATCH if path.matched(paths::ID_ANOTHER_FAKE_DUMMY) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -291,7 +296,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -333,14 +338,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // Call123example - GET /fake/operation-with-numeric-id - &hyper::Method::GET if path.matched(paths::ID_FAKE_OPERATION_WITH_NUMERIC_ID) => { + hyper::Method::GET if path.matched(paths::ID_FAKE_OPERATION_WITH_NUMERIC_ID) => { let result = api_impl.call123example( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -362,7 +367,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // FakeOuterBooleanSerialize - POST /fake/outer/boolean - &hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_BOOLEAN) => { + hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_BOOLEAN) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -390,7 +395,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -432,7 +437,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // FakeOuterCompositeSerialize - POST /fake/outer/composite - &hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_COMPOSITE) => { + hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_COMPOSITE) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -460,7 +465,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -502,7 +507,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // FakeOuterNumberSerialize - POST /fake/outer/number - &hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_NUMBER) => { + hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_NUMBER) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -530,7 +535,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -572,7 +577,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // FakeOuterStringSerialize - POST /fake/outer/string - &hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_STRING) => { + hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_STRING) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -600,7 +605,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -642,14 +647,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // FakeResponseWithNumericalDescription - GET /fake/response-with-numerical-description - &hyper::Method::GET if path.matched(paths::ID_FAKE_RESPONSE_WITH_NUMERICAL_DESCRIPTION) => { + hyper::Method::GET if path.matched(paths::ID_FAKE_RESPONSE_WITH_NUMERICAL_DESCRIPTION) => { let result = api_impl.fake_response_with_numerical_description( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -671,12 +676,12 @@ impl hyper::service::Service<(Request, C)> for Service where }, // HyphenParam - GET /fake/hyphenParam/{hyphen-param} - &hyper::Method::GET if path.matched(paths::ID_FAKE_HYPHENPARAM_HYPHEN_PARAM) => { + hyper::Method::GET if path.matched(paths::ID_FAKE_HYPHENPARAM_HYPHEN_PARAM) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_FAKE_HYPHENPARAM_HYPHEN_PARAM - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE FAKE_HYPHENPARAM_HYPHEN_PARAM in set but failed match against \"{}\"", path, paths::REGEX_FAKE_HYPHENPARAM_HYPHEN_PARAM.as_str()) ); @@ -702,7 +707,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -724,11 +729,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // TestBodyWithQueryParams - PUT /fake/body-with-query-params - &hyper::Method::PUT if path.matched(paths::ID_FAKE_BODY_WITH_QUERY_PARAMS) => { + hyper::Method::PUT if path.matched(paths::ID_FAKE_BODY_WITH_QUERY_PARAMS) => { // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); let param_query = query_params.iter().filter(|e| e.0 == "query").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_query = match param_query { Some(param_query) => { let param_query = @@ -790,7 +795,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -825,7 +830,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // TestClientModel - PATCH /fake - &hyper::Method::PATCH if path.matched(paths::ID_FAKE) => { + hyper::Method::PATCH if path.matched(paths::ID_FAKE) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -863,7 +868,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -905,11 +910,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // TestEndpointParameters - POST /fake - &hyper::Method::POST if path.matched(paths::ID_FAKE) => { + hyper::Method::POST if path.matched(paths::ID_FAKE) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -952,7 +957,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -978,7 +983,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // TestEnumParameters - GET /fake - &hyper::Method::GET if path.matched(paths::ID_FAKE) => { + hyper::Method::GET if path.matched(paths::ID_FAKE) => { // Header parameters let param_enum_header_string_array = headers.get(HeaderName::from_static("enum_header_string_array")); @@ -1028,7 +1033,7 @@ impl hyper::service::Service<(Request, C)> for Service where None }; let param_enum_query_string = query_params.iter().filter(|e| e.0 == "enum_query_string").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_enum_query_string = match param_enum_query_string { Some(param_enum_query_string) => { let param_enum_query_string = @@ -1045,7 +1050,7 @@ impl hyper::service::Service<(Request, C)> for Service where None => None, }; let param_enum_query_integer = query_params.iter().filter(|e| e.0 == "enum_query_integer").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_enum_query_integer = match param_enum_query_integer { Some(param_enum_query_integer) => { let param_enum_query_integer = @@ -1062,7 +1067,7 @@ impl hyper::service::Service<(Request, C)> for Service where None => None, }; let param_enum_query_double = query_params.iter().filter(|e| e.0 == "enum_query_double").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_enum_query_double = match param_enum_query_double { Some(param_enum_query_double) => { let param_enum_query_double = @@ -1095,7 +1100,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1121,7 +1126,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // TestInlineAdditionalProperties - POST /fake/inline-additionalProperties - &hyper::Method::POST if path.matched(paths::ID_FAKE_INLINE_ADDITIONALPROPERTIES) => { + hyper::Method::POST if path.matched(paths::ID_FAKE_INLINE_ADDITIONALPROPERTIES) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -1159,7 +1164,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1194,7 +1199,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // TestJsonFormData - GET /fake/jsonFormData - &hyper::Method::GET if path.matched(paths::ID_FAKE_JSONFORMDATA) => { + hyper::Method::GET if path.matched(paths::ID_FAKE_JSONFORMDATA) => { // Form parameters let param_param = "param_example".to_string(); let param_param2 = "param2_example".to_string(); @@ -1207,7 +1212,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1229,11 +1234,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // TestClassname - PATCH /fake_classname_test - &hyper::Method::PATCH if path.matched(paths::ID_FAKE_CLASSNAME_TEST) => { + hyper::Method::PATCH if path.matched(paths::ID_FAKE_CLASSNAME_TEST) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -1277,7 +1282,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1319,11 +1324,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // AddPet - POST /pet - &hyper::Method::POST if path.matched(paths::ID_PET) => { + hyper::Method::POST if path.matched(paths::ID_PET) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -1387,7 +1392,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1422,11 +1427,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // DeletePet - DELETE /pet/{petId} - &hyper::Method::DELETE if path.matched(paths::ID_PET_PETID) => { + hyper::Method::DELETE if path.matched(paths::ID_PET_PETID) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -1454,10 +1459,10 @@ impl hyper::service::Service<(Request, C)> for Service where } // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_PET_PETID - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE PET_PETID in set but failed match against \"{}\"", path, paths::REGEX_PET_PETID.as_str()) ); @@ -1504,7 +1509,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1526,11 +1531,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // FindPetsByStatus - GET /pet/findByStatus - &hyper::Method::GET if path.matched(paths::ID_PET_FINDBYSTATUS) => { + hyper::Method::GET if path.matched(paths::ID_PET_FINDBYSTATUS) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -1570,7 +1575,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1603,11 +1608,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // FindPetsByTags - GET /pet/findByTags - &hyper::Method::GET if path.matched(paths::ID_PET_FINDBYTAGS) => { + hyper::Method::GET if path.matched(paths::ID_PET_FINDBYTAGS) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -1647,7 +1652,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1680,11 +1685,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // GetPetById - GET /pet/{petId} - &hyper::Method::GET if path.matched(paths::ID_PET_PETID) => { + hyper::Method::GET if path.matched(paths::ID_PET_PETID) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -1692,10 +1697,10 @@ impl hyper::service::Service<(Request, C)> for Service where } // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_PET_PETID - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE PET_PETID in set but failed match against \"{}\"", path, paths::REGEX_PET_PETID.as_str()) ); @@ -1721,7 +1726,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1758,11 +1763,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // UpdatePet - PUT /pet - &hyper::Method::PUT if path.matched(paths::ID_PET) => { + hyper::Method::PUT if path.matched(paths::ID_PET) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -1826,7 +1831,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -1869,11 +1874,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // UpdatePetWithForm - POST /pet/{petId} - &hyper::Method::POST if path.matched(paths::ID_PET_PETID) => { + hyper::Method::POST if path.matched(paths::ID_PET_PETID) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -1901,10 +1906,10 @@ impl hyper::service::Service<(Request, C)> for Service where } // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_PET_PETID - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE PET_PETID in set but failed match against \"{}\"", path, paths::REGEX_PET_PETID.as_str()) ); @@ -1936,7 +1941,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -1958,11 +1963,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // UploadFile - POST /pet/{petId}/uploadImage - &hyper::Method::POST if path.matched(paths::ID_PET_PETID_UPLOADIMAGE) => { + hyper::Method::POST if path.matched(paths::ID_PET_PETID_UPLOADIMAGE) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -1998,10 +2003,10 @@ impl hyper::service::Service<(Request, C)> for Service where }; // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_PET_PETID_UPLOADIMAGE - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE PET_PETID_UPLOADIMAGE in set but failed match against \"{}\"", path, paths::REGEX_PET_PETID_UPLOADIMAGE.as_str()) ); @@ -2036,7 +2041,7 @@ impl hyper::service::Service<(Request, C)> for Service where _ => { return Ok(Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Unable to process all message parts"))) + .body(Body::from("Unable to process all message parts".to_string())) .expect("Unable to create Bad Request response due to failure to process all message")) }, }; @@ -2097,7 +2102,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -2126,18 +2131,18 @@ impl hyper::service::Service<(Request, C)> for Service where }, Err(e) => Ok(Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from(format!("Couldn't read multipart body"))) + .body(Body::from("Couldn't read multipart body".to_string())) .expect("Unable to create Bad Request response due to unable read multipart body")), } }, // DeleteOrder - DELETE /store/order/{order_id} - &hyper::Method::DELETE if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => { + hyper::Method::DELETE if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_STORE_ORDER_ORDER_ID - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE STORE_ORDER_ORDER_ID in set but failed match against \"{}\"", path, paths::REGEX_STORE_ORDER_ORDER_ID.as_str()) ); @@ -2163,7 +2168,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -2189,11 +2194,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // GetInventory - GET /store/inventory - &hyper::Method::GET if path.matched(paths::ID_STORE_INVENTORY) => { + hyper::Method::GET if path.matched(paths::ID_STORE_INVENTORY) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -2206,7 +2211,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -2235,12 +2240,12 @@ impl hyper::service::Service<(Request, C)> for Service where }, // GetOrderById - GET /store/order/{order_id} - &hyper::Method::GET if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => { + hyper::Method::GET if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_STORE_ORDER_ORDER_ID - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE STORE_ORDER_ORDER_ID in set but failed match against \"{}\"", path, paths::REGEX_STORE_ORDER_ORDER_ID.as_str()) ); @@ -2266,7 +2271,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -2303,7 +2308,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // PlaceOrder - POST /store/order - &hyper::Method::POST if path.matched(paths::ID_STORE_ORDER) => { + hyper::Method::POST if path.matched(paths::ID_STORE_ORDER) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -2341,7 +2346,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -2387,7 +2392,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // CreateUser - POST /user - &hyper::Method::POST if path.matched(paths::ID_USER) => { + hyper::Method::POST if path.matched(paths::ID_USER) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -2425,7 +2430,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -2460,7 +2465,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // CreateUsersWithArrayInput - POST /user/createWithArray - &hyper::Method::POST if path.matched(paths::ID_USER_CREATEWITHARRAY) => { + hyper::Method::POST if path.matched(paths::ID_USER_CREATEWITHARRAY) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -2498,7 +2503,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -2533,7 +2538,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // CreateUsersWithListInput - POST /user/createWithList - &hyper::Method::POST if path.matched(paths::ID_USER_CREATEWITHLIST) => { + hyper::Method::POST if path.matched(paths::ID_USER_CREATEWITHLIST) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -2571,7 +2576,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -2606,12 +2611,12 @@ impl hyper::service::Service<(Request, C)> for Service where }, // DeleteUser - DELETE /user/{username} - &hyper::Method::DELETE if path.matched(paths::ID_USER_USERNAME) => { + hyper::Method::DELETE if path.matched(paths::ID_USER_USERNAME) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_USER_USERNAME - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE USER_USERNAME in set but failed match against \"{}\"", path, paths::REGEX_USER_USERNAME.as_str()) ); @@ -2637,7 +2642,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -2663,12 +2668,12 @@ impl hyper::service::Service<(Request, C)> for Service where }, // GetUserByName - GET /user/{username} - &hyper::Method::GET if path.matched(paths::ID_USER_USERNAME) => { + hyper::Method::GET if path.matched(paths::ID_USER_USERNAME) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_USER_USERNAME - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE USER_USERNAME in set but failed match against \"{}\"", path, paths::REGEX_USER_USERNAME.as_str()) ); @@ -2694,7 +2699,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -2731,11 +2736,11 @@ impl hyper::service::Service<(Request, C)> for Service where }, // LoginUser - GET /user/login - &hyper::Method::GET if path.matched(paths::ID_USER_LOGIN) => { + hyper::Method::GET if path.matched(paths::ID_USER_LOGIN) => { // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::>(); let param_username = query_params.iter().filter(|e| e.0 == "username").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_username = match param_username { Some(param_username) => { let param_username = @@ -2759,7 +2764,7 @@ impl hyper::service::Service<(Request, C)> for Service where .expect("Unable to create Bad Request response for missing query parameter username")), }; let param_password = query_params.iter().filter(|e| e.0 == "password").map(|e| e.1.to_owned()) - .nth(0); + .next(); let param_password = match param_password { Some(param_password) => { let param_password = @@ -2791,7 +2796,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -2860,14 +2865,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // LogoutUser - GET /user/logout - &hyper::Method::GET if path.matched(paths::ID_USER_LOGOUT) => { + hyper::Method::GET if path.matched(paths::ID_USER_LOGOUT) => { let result = api_impl.logout_user( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -2889,12 +2894,12 @@ impl hyper::service::Service<(Request, C)> for Service where }, // UpdateUser - PUT /user/{username} - &hyper::Method::PUT if path.matched(paths::ID_USER_USERNAME) => { + hyper::Method::PUT if path.matched(paths::ID_USER_USERNAME) => { // Path parameters - let path: &str = &uri.path().to_string(); + let path: &str = uri.path(); let path_params = paths::REGEX_USER_USERNAME - .captures(&path) + .captures(path) .unwrap_or_else(|| panic!("Path {} matched RE USER_USERNAME in set but failed match against \"{}\"", path, paths::REGEX_USER_USERNAME.as_str()) ); @@ -2951,7 +2956,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -3028,77 +3033,77 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { // TestSpecialTags - PATCH /another-fake/dummy - &hyper::Method::PATCH if path.matched(paths::ID_ANOTHER_FAKE_DUMMY) => Some("TestSpecialTags"), + hyper::Method::PATCH if path.matched(paths::ID_ANOTHER_FAKE_DUMMY) => Some("TestSpecialTags"), // Call123example - GET /fake/operation-with-numeric-id - &hyper::Method::GET if path.matched(paths::ID_FAKE_OPERATION_WITH_NUMERIC_ID) => Some("Call123example"), + hyper::Method::GET if path.matched(paths::ID_FAKE_OPERATION_WITH_NUMERIC_ID) => Some("Call123example"), // FakeOuterBooleanSerialize - POST /fake/outer/boolean - &hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_BOOLEAN) => Some("FakeOuterBooleanSerialize"), + hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_BOOLEAN) => Some("FakeOuterBooleanSerialize"), // FakeOuterCompositeSerialize - POST /fake/outer/composite - &hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_COMPOSITE) => Some("FakeOuterCompositeSerialize"), + hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_COMPOSITE) => Some("FakeOuterCompositeSerialize"), // FakeOuterNumberSerialize - POST /fake/outer/number - &hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_NUMBER) => Some("FakeOuterNumberSerialize"), + hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_NUMBER) => Some("FakeOuterNumberSerialize"), // FakeOuterStringSerialize - POST /fake/outer/string - &hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_STRING) => Some("FakeOuterStringSerialize"), + hyper::Method::POST if path.matched(paths::ID_FAKE_OUTER_STRING) => Some("FakeOuterStringSerialize"), // FakeResponseWithNumericalDescription - GET /fake/response-with-numerical-description - &hyper::Method::GET if path.matched(paths::ID_FAKE_RESPONSE_WITH_NUMERICAL_DESCRIPTION) => Some("FakeResponseWithNumericalDescription"), + hyper::Method::GET if path.matched(paths::ID_FAKE_RESPONSE_WITH_NUMERICAL_DESCRIPTION) => Some("FakeResponseWithNumericalDescription"), // HyphenParam - GET /fake/hyphenParam/{hyphen-param} - &hyper::Method::GET if path.matched(paths::ID_FAKE_HYPHENPARAM_HYPHEN_PARAM) => Some("HyphenParam"), + hyper::Method::GET if path.matched(paths::ID_FAKE_HYPHENPARAM_HYPHEN_PARAM) => Some("HyphenParam"), // TestBodyWithQueryParams - PUT /fake/body-with-query-params - &hyper::Method::PUT if path.matched(paths::ID_FAKE_BODY_WITH_QUERY_PARAMS) => Some("TestBodyWithQueryParams"), + hyper::Method::PUT if path.matched(paths::ID_FAKE_BODY_WITH_QUERY_PARAMS) => Some("TestBodyWithQueryParams"), // TestClientModel - PATCH /fake - &hyper::Method::PATCH if path.matched(paths::ID_FAKE) => Some("TestClientModel"), + hyper::Method::PATCH if path.matched(paths::ID_FAKE) => Some("TestClientModel"), // TestEndpointParameters - POST /fake - &hyper::Method::POST if path.matched(paths::ID_FAKE) => Some("TestEndpointParameters"), + hyper::Method::POST if path.matched(paths::ID_FAKE) => Some("TestEndpointParameters"), // TestEnumParameters - GET /fake - &hyper::Method::GET if path.matched(paths::ID_FAKE) => Some("TestEnumParameters"), + hyper::Method::GET if path.matched(paths::ID_FAKE) => Some("TestEnumParameters"), // TestInlineAdditionalProperties - POST /fake/inline-additionalProperties - &hyper::Method::POST if path.matched(paths::ID_FAKE_INLINE_ADDITIONALPROPERTIES) => Some("TestInlineAdditionalProperties"), + hyper::Method::POST if path.matched(paths::ID_FAKE_INLINE_ADDITIONALPROPERTIES) => Some("TestInlineAdditionalProperties"), // TestJsonFormData - GET /fake/jsonFormData - &hyper::Method::GET if path.matched(paths::ID_FAKE_JSONFORMDATA) => Some("TestJsonFormData"), + hyper::Method::GET if path.matched(paths::ID_FAKE_JSONFORMDATA) => Some("TestJsonFormData"), // TestClassname - PATCH /fake_classname_test - &hyper::Method::PATCH if path.matched(paths::ID_FAKE_CLASSNAME_TEST) => Some("TestClassname"), + hyper::Method::PATCH if path.matched(paths::ID_FAKE_CLASSNAME_TEST) => Some("TestClassname"), // AddPet - POST /pet - &hyper::Method::POST if path.matched(paths::ID_PET) => Some("AddPet"), + hyper::Method::POST if path.matched(paths::ID_PET) => Some("AddPet"), // DeletePet - DELETE /pet/{petId} - &hyper::Method::DELETE if path.matched(paths::ID_PET_PETID) => Some("DeletePet"), + hyper::Method::DELETE if path.matched(paths::ID_PET_PETID) => Some("DeletePet"), // FindPetsByStatus - GET /pet/findByStatus - &hyper::Method::GET if path.matched(paths::ID_PET_FINDBYSTATUS) => Some("FindPetsByStatus"), + hyper::Method::GET if path.matched(paths::ID_PET_FINDBYSTATUS) => Some("FindPetsByStatus"), // FindPetsByTags - GET /pet/findByTags - &hyper::Method::GET if path.matched(paths::ID_PET_FINDBYTAGS) => Some("FindPetsByTags"), + hyper::Method::GET if path.matched(paths::ID_PET_FINDBYTAGS) => Some("FindPetsByTags"), // GetPetById - GET /pet/{petId} - &hyper::Method::GET if path.matched(paths::ID_PET_PETID) => Some("GetPetById"), + hyper::Method::GET if path.matched(paths::ID_PET_PETID) => Some("GetPetById"), // UpdatePet - PUT /pet - &hyper::Method::PUT if path.matched(paths::ID_PET) => Some("UpdatePet"), + hyper::Method::PUT if path.matched(paths::ID_PET) => Some("UpdatePet"), // UpdatePetWithForm - POST /pet/{petId} - &hyper::Method::POST if path.matched(paths::ID_PET_PETID) => Some("UpdatePetWithForm"), + hyper::Method::POST if path.matched(paths::ID_PET_PETID) => Some("UpdatePetWithForm"), // UploadFile - POST /pet/{petId}/uploadImage - &hyper::Method::POST if path.matched(paths::ID_PET_PETID_UPLOADIMAGE) => Some("UploadFile"), + hyper::Method::POST if path.matched(paths::ID_PET_PETID_UPLOADIMAGE) => Some("UploadFile"), // DeleteOrder - DELETE /store/order/{order_id} - &hyper::Method::DELETE if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => Some("DeleteOrder"), + hyper::Method::DELETE if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => Some("DeleteOrder"), // GetInventory - GET /store/inventory - &hyper::Method::GET if path.matched(paths::ID_STORE_INVENTORY) => Some("GetInventory"), + hyper::Method::GET if path.matched(paths::ID_STORE_INVENTORY) => Some("GetInventory"), // GetOrderById - GET /store/order/{order_id} - &hyper::Method::GET if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => Some("GetOrderById"), + hyper::Method::GET if path.matched(paths::ID_STORE_ORDER_ORDER_ID) => Some("GetOrderById"), // PlaceOrder - POST /store/order - &hyper::Method::POST if path.matched(paths::ID_STORE_ORDER) => Some("PlaceOrder"), + hyper::Method::POST if path.matched(paths::ID_STORE_ORDER) => Some("PlaceOrder"), // CreateUser - POST /user - &hyper::Method::POST if path.matched(paths::ID_USER) => Some("CreateUser"), + hyper::Method::POST if path.matched(paths::ID_USER) => Some("CreateUser"), // CreateUsersWithArrayInput - POST /user/createWithArray - &hyper::Method::POST if path.matched(paths::ID_USER_CREATEWITHARRAY) => Some("CreateUsersWithArrayInput"), + hyper::Method::POST if path.matched(paths::ID_USER_CREATEWITHARRAY) => Some("CreateUsersWithArrayInput"), // CreateUsersWithListInput - POST /user/createWithList - &hyper::Method::POST if path.matched(paths::ID_USER_CREATEWITHLIST) => Some("CreateUsersWithListInput"), + hyper::Method::POST if path.matched(paths::ID_USER_CREATEWITHLIST) => Some("CreateUsersWithListInput"), // DeleteUser - DELETE /user/{username} - &hyper::Method::DELETE if path.matched(paths::ID_USER_USERNAME) => Some("DeleteUser"), + hyper::Method::DELETE if path.matched(paths::ID_USER_USERNAME) => Some("DeleteUser"), // GetUserByName - GET /user/{username} - &hyper::Method::GET if path.matched(paths::ID_USER_USERNAME) => Some("GetUserByName"), + hyper::Method::GET if path.matched(paths::ID_USER_USERNAME) => Some("GetUserByName"), // LoginUser - GET /user/login - &hyper::Method::GET if path.matched(paths::ID_USER_LOGIN) => Some("LoginUser"), + hyper::Method::GET if path.matched(paths::ID_USER_LOGIN) => Some("LoginUser"), // LogoutUser - GET /user/logout - &hyper::Method::GET if path.matched(paths::ID_USER_LOGOUT) => Some("LogoutUser"), + hyper::Method::GET if path.matched(paths::ID_USER_LOGOUT) => Some("LogoutUser"), // UpdateUser - PUT /user/{username} - &hyper::Method::PUT if path.matched(paths::ID_USER_USERNAME) => Some("UpdateUser"), + hyper::Method::PUT if path.matched(paths::ID_USER_USERNAME) => Some("UpdateUser"), _ => None, } } diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/examples/server/server.rs b/samples/server/petstore/rust-server/output/ping-bearer-auth/examples/server/server.rs index 19af14b778..3383a22e1a 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/examples/server/server.rs @@ -32,6 +32,7 @@ pub async fn create(addr: &str, https: bool) { let service = MakeAllowAllAuthenticator::new(service, "cosmo"); + #[allow(unused_mut)] let mut service = ping_bearer_auth::server::context::MakeAddContext::<_, EmptyContext>::new( service diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs index e9927156e5..9ce229a207 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs @@ -53,7 +53,7 @@ fn into_base_path(input: impl TryInto, } } - let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let host = uri.host().ok_or(ClientInitError::MissingHost)?; let port = uri.port_u16().map(|x| format!(":{}", x)).unwrap_or_default(); Ok(format!("{}://{}{}{}", scheme, host, port, uri.path().trim_end_matches('/'))) } @@ -192,7 +192,7 @@ impl Client, C> where "https" => { let connector = connector.https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; HyperClient::Https(hyper::client::Client::builder().build(connector)) }, _ => { @@ -244,7 +244,7 @@ impl Client, C let https_connector = Connector::builder() .https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -265,7 +265,7 @@ impl Client, C .https() .pin_server_certificate(ca_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -293,7 +293,7 @@ impl Client, C .pin_server_certificate(ca_certificate) .client_authentication(client_key, client_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } } @@ -413,14 +413,16 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); + #[allow(clippy::collapsible_match)] if let Some(auth_data) = Has::>::get(context).as_ref() { // Currently only authentication with Basic and Bearer are supported + #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { &AuthData::Bearer(ref bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); @@ -436,12 +438,11 @@ impl Api for Client where } } - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 201 => { - let body = response.into_body(); Ok( PingGetResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/context.rs b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/context.rs index 6f03005325..ac1c07864b 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/context.rs +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/context.rs @@ -107,7 +107,7 @@ impl Service> for AddContext(&headers) { + if let Some(bearer) = swagger::auth::from_headers::(headers) { let auth_data = AuthData::Bearer(bearer); let context = context.push(Some(auth_data)); let context = context.push(None::); diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/lib.rs b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/lib.rs index 0f93036c82..5a5c46ba33 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/lib.rs +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/lib.rs @@ -1,4 +1,6 @@ #![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::blacklisted_name)] use async_trait::async_trait; use futures::Stream; @@ -9,8 +11,8 @@ use serde::{Serialize, Deserialize}; type ServiceError = Box; -pub const BASE_PATH: &'static str = ""; -pub const API_VERSION: &'static str = "1.0"; +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "1.0"; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum PingGetResponse { @@ -20,6 +22,7 @@ pub enum PingGetResponse { /// API #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait Api { fn poll_ready(&self, _cx: &mut Context) -> Poll>> { Poll::Ready(Ok(())) @@ -33,6 +36,7 @@ pub trait Api { /// API where `Context` isn't passed on every API call #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait ApiNoContext { fn poll_ready(&self, _cx: &mut Context) -> Poll>>; @@ -49,7 +53,7 @@ pub trait ApiNoContext { pub trait ContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> ContextWrapperExt for T { diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/server/mod.rs b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/server/mod.rs index c62110ced8..0657f06dd6 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/server/mod.rs @@ -98,7 +98,7 @@ impl Service where { pub fn new(api_impl: T) -> Self { Service { - api_impl: api_impl, + api_impl, marker: PhantomData } } @@ -111,7 +111,7 @@ impl Clone for Service where fn clone(&self) -> Self { Service { api_impl: self.api_impl.clone(), - marker: self.marker.clone(), + marker: self.marker, } } } @@ -137,14 +137,14 @@ impl hyper::service::Service<(Request, C)> for Service where let (method, uri, headers) = (parts.method, parts.uri, parts.headers); let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); - match &method { + match method { // PingGet - GET /ping - &hyper::Method::GET if path.matched(paths::ID_PING) => { + hyper::Method::GET if path.matched(paths::ID_PING) => { { - let authorization = match (&context as &dyn Has>).get() { - &Some(ref authorization) => authorization, - &None => return Ok(Response::builder() + let authorization = match *(&context as &dyn Has>).get() { + Some(ref authorization) => authorization, + None => return Ok(Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::from("Unauthenticated")) .expect("Unable to create Authentication Forbidden response")), @@ -157,7 +157,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -191,9 +191,9 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { // PingGet - GET /ping - &hyper::Method::GET if path.matched(paths::ID_PING) => Some("PingGet"), + hyper::Method::GET if path.matched(paths::ID_PING) => Some("PingGet"), _ => None, } } diff --git a/samples/server/petstore/rust-server/output/rust-server-test/docs/ObjectOfObjectsInner.md b/samples/server/petstore/rust-server/output/rust-server-test/docs/ObjectOfObjectsInner.md index 9aa888a5f7..965210d38f 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/docs/ObjectOfObjectsInner.md +++ b/samples/server/petstore/rust-server/output/rust-server-test/docs/ObjectOfObjectsInner.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **required_thing** | **String** | | -**optional_thing** | **isize** | | [optional] [default to None] +**optional_thing** | **i32** | | [optional] [default to None] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/server/server.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/server/server.rs index 143e17a051..ab9e383866 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/server/server.rs @@ -32,6 +32,7 @@ pub async fn create(addr: &str, https: bool) { let service = MakeAllowAllAuthenticator::new(service, "cosmo"); + #[allow(unused_mut)] let mut service = rust_server_test::server::context::MakeAddContext::<_, EmptyContext>::new( service diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs index 623ea11d18..dcda90cd4a 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs @@ -61,7 +61,7 @@ fn into_base_path(input: impl TryInto, } } - let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let host = uri.host().ok_or(ClientInitError::MissingHost)?; let port = uri.port_u16().map(|x| format!(":{}", x)).unwrap_or_default(); Ok(format!("{}://{}{}{}", scheme, host, port, uri.path().trim_end_matches('/'))) } @@ -200,7 +200,7 @@ impl Client, C> where "https" => { let connector = connector.https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; HyperClient::Https(hyper::client::Client::builder().build(connector)) }, _ => { @@ -252,7 +252,7 @@ impl Client, C let https_connector = Connector::builder() .https() .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -273,7 +273,7 @@ impl Client, C .https() .pin_server_certificate(ca_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } @@ -301,7 +301,7 @@ impl Client, C .pin_server_certificate(ca_certificate) .client_authentication(client_key, client_certificate) .build() - .map_err(|e| ClientInitError::SslError(e))?; + .map_err(ClientInitError::SslError)?; Self::try_new_with_connector(base_path, Some("https"), https_connector) } } @@ -421,13 +421,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -498,18 +498,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( DummyGetResponse::Success ) @@ -576,18 +575,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 200 => { - let body = response.into_body(); Ok( DummyPutResponse::Success ) @@ -645,13 +643,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -722,13 +720,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -806,13 +804,13 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -890,18 +888,17 @@ impl Api for Client where Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 204 => { - let body = response.into_body(); Ok( PostYamlResponse::OK ) @@ -959,13 +956,13 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { @@ -1047,18 +1044,17 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); - let header = HeaderValue::from_str(Has::::get(context).0.clone().to_string().as_str()); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e))) }); - let mut response = client_service.call((request, context.clone())) + let response = client_service.call((request, context.clone())) .map_err(|e| ApiError(format!("No response received: {}", e))).await?; match response.status().as_u16() { 204 => { - let body = response.into_body(); Ok( SoloObjectPostResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs index 26fd278564..9d9c1f711c 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs @@ -1,4 +1,6 @@ #![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::blacklisted_name)] use async_trait::async_trait; use futures::Stream; @@ -9,8 +11,8 @@ use serde::{Serialize, Deserialize}; type ServiceError = Box; -pub const BASE_PATH: &'static str = ""; -pub const API_VERSION: &'static str = "2.3.4"; +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "2.3.4"; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum AllOfGetResponse { @@ -73,6 +75,7 @@ pub enum SoloObjectPostResponse { /// API #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait Api { fn poll_ready(&self, _cx: &mut Context) -> Poll>> { Poll::Ready(Ok(())) @@ -127,6 +130,7 @@ pub trait Api { /// API where `Context` isn't passed on every API call #[async_trait] +#[allow(clippy::too_many_arguments, clippy::ptr_arg)] pub trait ApiNoContext { fn poll_ready(&self, _cx: &mut Context) -> Poll>>; @@ -184,7 +188,7 @@ pub trait ApiNoContext { pub trait ContextWrapperExt where Self: Sized { /// Binds this API to a context. - fn with_context(self: Self, context: C) -> ContextWrapper; + fn with_context(self, context: C) -> ContextWrapper; } impl + Send + Sync, C: Clone + Send + Sync> ContextWrapperExt for T { diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs index 381b7632a6..a05942751b 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs @@ -19,10 +19,11 @@ pub struct ANullableContainer { } impl ANullableContainer { + #[allow(clippy::new_without_default)] pub fn new(required_nullable_thing: swagger::Nullable, ) -> ANullableContainer { ANullableContainer { nullable_thing: None, - required_nullable_thing: required_nullable_thing, + required_nullable_thing, } } } @@ -32,18 +33,22 @@ impl ANullableContainer { /// Should be implemented in a serde serializer impl std::string::ToString for ANullableContainer { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref nullable_thing) = self.nullable_thing { - params.push("NullableThing".to_string()); - params.push(nullable_thing.as_ref().map_or("null".to_string(), |x| x.to_string())); - } + self.nullable_thing.as_ref().map(|nullable_thing| { + vec![ + "NullableThing".to_string(), + nullable_thing.as_ref().map_or("null".to_string(), |x| x.to_string()), + ].join(",") + }), - params.push("RequiredNullableThing".to_string()); - params.push(self.required_nullable_thing.as_ref().map_or("null".to_string(), |x| x.to_string())); + Some("RequiredNullableThing".to_string()), + Some(self.required_nullable_thing.as_ref().map_or("null".to_string(), |x| x.to_string())), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -54,8 +59,9 @@ impl std::str::FromStr for ANullableContainer { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub nullable_thing: Vec, pub required_nullable_thing: Vec, @@ -64,7 +70,7 @@ impl std::str::FromStr for ANullableContainer { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -74,6 +80,7 @@ impl std::str::FromStr for ANullableContainer { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { "NullableThing" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in ANullableContainer".to_string()), "RequiredNullableThing" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in ANullableContainer".to_string()), @@ -197,6 +204,7 @@ pub struct AllOfObject { } impl AllOfObject { + #[allow(clippy::new_without_default)] pub fn new() -> AllOfObject { AllOfObject { sample_property: None, @@ -210,20 +218,26 @@ impl AllOfObject { /// Should be implemented in a serde serializer impl std::string::ToString for AllOfObject { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref sample_property) = self.sample_property { - params.push("sampleProperty".to_string()); - params.push(sample_property.to_string()); - } + self.sample_property.as_ref().map(|sample_property| { + vec![ + "sampleProperty".to_string(), + sample_property.to_string(), + ].join(",") + }), - if let Some(ref sample_base_propery) = self.sample_base_propery { - params.push("sampleBasePropery".to_string()); - params.push(sample_base_propery.to_string()); - } + self.sample_base_propery.as_ref().map(|sample_base_propery| { + vec![ + "sampleBasePropery".to_string(), + sample_base_propery.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -234,8 +248,9 @@ impl std::str::FromStr for AllOfObject { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub sample_property: Vec, pub sample_base_propery: Vec, @@ -244,7 +259,7 @@ impl std::str::FromStr for AllOfObject { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -254,9 +269,12 @@ impl std::str::FromStr for AllOfObject { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "sampleProperty" => intermediate_rep.sample_property.push(::from_str(val).map_err(|x| format!("{}", x))?), - "sampleBasePropery" => intermediate_rep.sample_base_propery.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "sampleProperty" => intermediate_rep.sample_property.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "sampleBasePropery" => intermediate_rep.sample_base_propery.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing AllOfObject".to_string()) } } @@ -322,6 +340,7 @@ pub struct BaseAllOf { } impl BaseAllOf { + #[allow(clippy::new_without_default)] pub fn new() -> BaseAllOf { BaseAllOf { sample_base_propery: None, @@ -334,14 +353,18 @@ impl BaseAllOf { /// Should be implemented in a serde serializer impl std::string::ToString for BaseAllOf { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref sample_base_propery) = self.sample_base_propery { - params.push("sampleBasePropery".to_string()); - params.push(sample_base_propery.to_string()); - } + self.sample_base_propery.as_ref().map(|sample_base_propery| { + vec![ + "sampleBasePropery".to_string(), + sample_base_propery.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -352,8 +375,9 @@ impl std::str::FromStr for BaseAllOf { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub sample_base_propery: Vec, } @@ -361,7 +385,7 @@ impl std::str::FromStr for BaseAllOf { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -371,8 +395,10 @@ impl std::str::FromStr for BaseAllOf { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "sampleBasePropery" => intermediate_rep.sample_base_propery.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "sampleBasePropery" => intermediate_rep.sample_base_propery.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing BaseAllOf".to_string()) } } @@ -440,9 +466,10 @@ pub struct DummyPutRequest { } impl DummyPutRequest { + #[allow(clippy::new_without_default)] pub fn new(id: String, ) -> DummyPutRequest { DummyPutRequest { - id: id, + id, password: None, } } @@ -453,18 +480,22 @@ impl DummyPutRequest { /// Should be implemented in a serde serializer impl std::string::ToString for DummyPutRequest { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("id".to_string()); - params.push(self.id.to_string()); + Some("id".to_string()), + Some(self.id.to_string()), - if let Some(ref password) = self.password { - params.push("password".to_string()); - params.push(password.to_string()); - } + self.password.as_ref().map(|password| { + vec![ + "password".to_string(), + password.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -475,8 +506,9 @@ impl std::str::FromStr for DummyPutRequest { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub id: Vec, pub password: Vec, @@ -485,7 +517,7 @@ impl std::str::FromStr for DummyPutRequest { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -495,9 +527,12 @@ impl std::str::FromStr for DummyPutRequest { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| format!("{}", x))?), - "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing DummyPutRequest".to_string()) } } @@ -508,7 +543,7 @@ impl std::str::FromStr for DummyPutRequest { // Use the intermediate representation to return the struct std::result::Result::Ok(DummyPutRequest { - id: intermediate_rep.id.into_iter().next().ok_or("id missing in DummyPutRequest".to_string())?, + id: intermediate_rep.id.into_iter().next().ok_or_else(|| "id missing in DummyPutRequest".to_string())?, password: intermediate_rep.password.into_iter().next(), }) } @@ -565,6 +600,7 @@ pub struct GetYamlResponse { } impl GetYamlResponse { + #[allow(clippy::new_without_default)] pub fn new() -> GetYamlResponse { GetYamlResponse { value: None, @@ -577,14 +613,18 @@ impl GetYamlResponse { /// Should be implemented in a serde serializer impl std::string::ToString for GetYamlResponse { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - if let Some(ref value) = self.value { - params.push("value".to_string()); - params.push(value.to_string()); - } + self.value.as_ref().map(|value| { + vec![ + "value".to_string(), + value.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -595,8 +635,9 @@ impl std::str::FromStr for GetYamlResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub value: Vec, } @@ -604,7 +645,7 @@ impl std::str::FromStr for GetYamlResponse { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -614,8 +655,10 @@ impl std::str::FromStr for GetYamlResponse { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "value" => intermediate_rep.value.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "value" => intermediate_rep.value.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing GetYamlResponse".to_string()) } } @@ -681,6 +724,7 @@ pub struct ObjectOfObjects { } impl ObjectOfObjects { + #[allow(clippy::new_without_default)] pub fn new() -> ObjectOfObjects { ObjectOfObjects { inner: None, @@ -693,10 +737,12 @@ impl ObjectOfObjects { /// Should be implemented in a serde serializer impl std::string::ToString for ObjectOfObjects { fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping inner in query parameter serialization + let params: Vec> = vec![ + // Skipping inner in query parameter serialization - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -707,8 +753,9 @@ impl std::str::FromStr for ObjectOfObjects { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub inner: Vec, } @@ -716,7 +763,7 @@ impl std::str::FromStr for ObjectOfObjects { let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -726,8 +773,10 @@ impl std::str::FromStr for ObjectOfObjects { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "inner" => intermediate_rep.inner.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "inner" => intermediate_rep.inner.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing ObjectOfObjects".to_string()) } } @@ -790,14 +839,15 @@ pub struct ObjectOfObjectsInner { #[serde(rename = "optional_thing")] #[serde(skip_serializing_if="Option::is_none")] - pub optional_thing: Option, + pub optional_thing: Option, } impl ObjectOfObjectsInner { + #[allow(clippy::new_without_default)] pub fn new(required_thing: String, ) -> ObjectOfObjectsInner { ObjectOfObjectsInner { - required_thing: required_thing, + required_thing, optional_thing: None, } } @@ -808,18 +858,22 @@ impl ObjectOfObjectsInner { /// Should be implemented in a serde serializer impl std::string::ToString for ObjectOfObjectsInner { fn to_string(&self) -> String { - let mut params: Vec = vec![]; + let params: Vec> = vec![ - params.push("required_thing".to_string()); - params.push(self.required_thing.to_string()); + Some("required_thing".to_string()), + Some(self.required_thing.to_string()), - if let Some(ref optional_thing) = self.optional_thing { - params.push("optional_thing".to_string()); - params.push(optional_thing.to_string()); - } + self.optional_thing.as_ref().map(|optional_thing| { + vec![ + "optional_thing".to_string(), + optional_thing.to_string(), + ].join(",") + }), - params.join(",").to_string() + ]; + + params.into_iter().flatten().collect::>().join(",") } } @@ -830,17 +884,18 @@ impl std::str::FromStr for ObjectOfObjectsInner { type Err = String; fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. #[derive(Default)] - // An intermediate representation of the struct to use for parsing. + #[allow(dead_code)] struct IntermediateRep { pub required_thing: Vec, - pub optional_thing: Vec, + pub optional_thing: Vec, } let mut intermediate_rep = IntermediateRep::default(); // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); + let mut string_iter = s.split(','); let mut key_result = string_iter.next(); while key_result.is_some() { @@ -850,9 +905,12 @@ impl std::str::FromStr for ObjectOfObjectsInner { }; if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] match key { - "required_thing" => intermediate_rep.required_thing.push(::from_str(val).map_err(|x| format!("{}", x))?), - "optional_thing" => intermediate_rep.optional_thing.push(::from_str(val).map_err(|x| format!("{}", x))?), + #[allow(clippy::redundant_clone)] + "required_thing" => intermediate_rep.required_thing.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "optional_thing" => intermediate_rep.optional_thing.push(::from_str(val).map_err(|x| x.to_string())?), _ => return std::result::Result::Err("Unexpected key while parsing ObjectOfObjectsInner".to_string()) } } @@ -863,7 +921,7 @@ impl std::str::FromStr for ObjectOfObjectsInner { // Use the intermediate representation to return the struct std::result::Result::Ok(ObjectOfObjectsInner { - required_thing: intermediate_rep.required_thing.into_iter().next().ok_or("required_thing missing in ObjectOfObjectsInner".to_string())?, + required_thing: intermediate_rep.required_thing.into_iter().next().ok_or_else(|| "required_thing missing in ObjectOfObjectsInner".to_string())?, optional_thing: intermediate_rep.optional_thing.into_iter().next(), }) } diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs index 2b63c4e1d2..52df96f3ef 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs @@ -120,7 +120,7 @@ impl Service where { pub fn new(api_impl: T) -> Self { Service { - api_impl: api_impl, + api_impl, marker: PhantomData } } @@ -133,7 +133,7 @@ impl Clone for Service where fn clone(&self) -> Self { Service { api_impl: self.api_impl.clone(), - marker: self.marker.clone(), + marker: self.marker, } } } @@ -159,17 +159,17 @@ impl hyper::service::Service<(Request, C)> for Service where let (method, uri, headers) = (parts.method, parts.uri, parts.headers); let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); - match &method { + match method { // AllOfGet - GET /allOf - &hyper::Method::GET if path.matched(paths::ID_ALLOF) => { + hyper::Method::GET if path.matched(paths::ID_ALLOF) => { let result = api_impl.all_of_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -198,14 +198,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // DummyGet - GET /dummy - &hyper::Method::GET if path.matched(paths::ID_DUMMY) => { + hyper::Method::GET if path.matched(paths::ID_DUMMY) => { let result = api_impl.dummy_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -227,7 +227,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // DummyPut - PUT /dummy - &hyper::Method::PUT if path.matched(paths::ID_DUMMY) => { + hyper::Method::PUT if path.matched(paths::ID_DUMMY) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -265,7 +265,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -300,14 +300,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // FileResponseGet - GET /file_response - &hyper::Method::GET if path.matched(paths::ID_FILE_RESPONSE) => { + hyper::Method::GET if path.matched(paths::ID_FILE_RESPONSE) => { let result = api_impl.file_response_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -336,14 +336,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // GetStructuredYaml - GET /get-structured-yaml - &hyper::Method::GET if path.matched(paths::ID_GET_STRUCTURED_YAML) => { + hyper::Method::GET if path.matched(paths::ID_GET_STRUCTURED_YAML) => { let result = api_impl.get_structured_yaml( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -372,7 +372,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // HtmlPost - POST /html - &hyper::Method::POST if path.matched(paths::ID_HTML) => { + hyper::Method::POST if path.matched(paths::ID_HTML) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -405,7 +405,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -440,7 +440,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // PostYaml - POST /post-yaml - &hyper::Method::POST if path.matched(paths::ID_POST_YAML) => { + hyper::Method::POST if path.matched(paths::ID_POST_YAML) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -473,7 +473,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -501,14 +501,14 @@ impl hyper::service::Service<(Request, C)> for Service where }, // RawJsonGet - GET /raw_json - &hyper::Method::GET if path.matched(paths::ID_RAW_JSON) => { + hyper::Method::GET if path.matched(paths::ID_RAW_JSON) => { let result = api_impl.raw_json_get( &context ).await; let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); match result { @@ -537,7 +537,7 @@ impl hyper::service::Service<(Request, C)> for Service where }, // SoloObjectPost - POST /solo-object - &hyper::Method::POST if path.matched(paths::ID_SOLO_OBJECT) => { + hyper::Method::POST if path.matched(paths::ID_SOLO_OBJECT) => { // Body parameters (note that non-required body parameters will ignore garbage // values, rather than causing a 400 response). Produce warning header and logs for // any unused fields. @@ -575,7 +575,7 @@ impl hyper::service::Service<(Request, C)> for Service where let mut response = Response::new(Body::empty()); response.headers_mut().insert( HeaderName::from_static("x-span-id"), - HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); if !unused_elements.is_empty() { @@ -629,25 +629,25 @@ pub struct ApiRequestParser; impl RequestParser for ApiRequestParser { fn parse_operation_id(request: &Request) -> Option<&'static str> { let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); - match request.method() { + match *request.method() { // AllOfGet - GET /allOf - &hyper::Method::GET if path.matched(paths::ID_ALLOF) => Some("AllOfGet"), + hyper::Method::GET if path.matched(paths::ID_ALLOF) => Some("AllOfGet"), // DummyGet - GET /dummy - &hyper::Method::GET if path.matched(paths::ID_DUMMY) => Some("DummyGet"), + hyper::Method::GET if path.matched(paths::ID_DUMMY) => Some("DummyGet"), // DummyPut - PUT /dummy - &hyper::Method::PUT if path.matched(paths::ID_DUMMY) => Some("DummyPut"), + hyper::Method::PUT if path.matched(paths::ID_DUMMY) => Some("DummyPut"), // FileResponseGet - GET /file_response - &hyper::Method::GET if path.matched(paths::ID_FILE_RESPONSE) => Some("FileResponseGet"), + hyper::Method::GET if path.matched(paths::ID_FILE_RESPONSE) => Some("FileResponseGet"), // GetStructuredYaml - GET /get-structured-yaml - &hyper::Method::GET if path.matched(paths::ID_GET_STRUCTURED_YAML) => Some("GetStructuredYaml"), + hyper::Method::GET if path.matched(paths::ID_GET_STRUCTURED_YAML) => Some("GetStructuredYaml"), // HtmlPost - POST /html - &hyper::Method::POST if path.matched(paths::ID_HTML) => Some("HtmlPost"), + hyper::Method::POST if path.matched(paths::ID_HTML) => Some("HtmlPost"), // PostYaml - POST /post-yaml - &hyper::Method::POST if path.matched(paths::ID_POST_YAML) => Some("PostYaml"), + hyper::Method::POST if path.matched(paths::ID_POST_YAML) => Some("PostYaml"), // RawJsonGet - GET /raw_json - &hyper::Method::GET if path.matched(paths::ID_RAW_JSON) => Some("RawJsonGet"), + hyper::Method::GET if path.matched(paths::ID_RAW_JSON) => Some("RawJsonGet"), // SoloObjectPost - POST /solo-object - &hyper::Method::POST if path.matched(paths::ID_SOLO_OBJECT) => Some("SoloObjectPost"), + hyper::Method::POST if path.matched(paths::ID_SOLO_OBJECT) => Some("SoloObjectPost"), _ => None, } } diff --git a/samples/server/petstore/rust-server/pom.xml b/samples/server/petstore/rust-server/pom.xml index eeefcb808a..61e50dcc15 100644 --- a/samples/server/petstore/rust-server/pom.xml +++ b/samples/server/petstore/rust-server/pom.xml @@ -53,6 +53,19 @@ + + clippy + integration-test + + exec + + + cargo + + clippy + + + diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/AnotherFakeApi.java index 2aa59316f5..325eff89d6 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { /** diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeApi.java index a8d9f9ab70..a7d822da3c 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeApi.java @@ -42,6 +42,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { /** @@ -373,7 +374,7 @@ public interface FakeApi { ) ResponseEntity testGroupParameters( @NotNull @Parameter(name = "required_string_group", description = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @Parameter(name = "required_int64_group", description = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @Parameter(name = "string_group", description = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @Parameter(name = "boolean_group", description = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 858a507559..b3818b94a4 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { /** diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/PetApi.java index 81c01a7d22..7673df7645 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/PetApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { /** diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/StoreApi.java index be63fc5251..1ab9dbeeb6 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/StoreApi.java @@ -33,6 +33,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { /** diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/UserApi.java index db9651dd80..613c61ed3c 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/UserApi.java @@ -34,6 +34,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { /** diff --git a/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/api/NullableApi.java b/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/api/NullableApi.java index 4bac42b24f..f86d4f14b7 100644 --- a/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/api/NullableApi.java +++ b/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/api/NullableApi.java @@ -32,6 +32,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Tag(name = "nullable", description = "the nullable API") +@RequestMapping("${openapi.apiDocumentation.base-path:}") public interface NullableApi { default Optional getRequest() { diff --git a/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/model/ObjectWithUniqueItems.java b/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/model/ObjectWithUniqueItems.java index 190950d867..a322f8ae15 100644 --- a/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/model/ObjectWithUniqueItems.java +++ b/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/model/ObjectWithUniqueItems.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Set; import org.openapitools.jackson.nullable.JsonNullable; import org.springframework.format.annotation.DateTimeFormat; +import java.util.NoSuchElementException; import org.openapitools.jackson.nullable.JsonNullable; import java.time.OffsetDateTime; import javax.validation.Valid; @@ -210,9 +211,9 @@ public class ObjectWithUniqueItems { return false; } ObjectWithUniqueItems objectWithUniqueItems = (ObjectWithUniqueItems) o; - return Objects.equals(this.nullSet, objectWithUniqueItems.nullSet) && + return equalsNullable(this.nullSet, objectWithUniqueItems.nullSet) && Objects.equals(this.notNullSet, objectWithUniqueItems.notNullSet) && - Objects.equals(this.nullList, objectWithUniqueItems.nullList) && + equalsNullable(this.nullList, objectWithUniqueItems.nullList) && Objects.equals(this.notNullList, objectWithUniqueItems.notNullList) && Objects.equals(this.notNullDateField, objectWithUniqueItems.notNullDateField) && Objects.equals(this.nullDateField, objectWithUniqueItems.nullDateField); @@ -224,7 +225,7 @@ public class ObjectWithUniqueItems { @Override public int hashCode() { - return Objects.hash(nullSet, notNullSet, nullList, notNullList, notNullDateField, nullDateField); + return Objects.hash(hashCodeNullable(nullSet), notNullSet, hashCodeNullable(nullList), notNullList, notNullDateField, nullDateField); } private static int hashCodeNullable(JsonNullable a) { diff --git a/samples/server/petstore/spring-stubs/.openapi-generator-ignore b/samples/server/petstore/spring-stubs/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/server/petstore/spring-stubs/.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/server/petstore/spring-stubs/.openapi-generator/FILES b/samples/server/petstore/spring-stubs/.openapi-generator/FILES new file mode 100644 index 0000000000..8783779323 --- /dev/null +++ b/samples/server/petstore/spring-stubs/.openapi-generator/FILES @@ -0,0 +1,12 @@ +README.md +pom.xml +src/main/java/org/openapitools/api/ApiUtil.java +src/main/java/org/openapitools/api/PetApi.java +src/main/java/org/openapitools/api/StoreApi.java +src/main/java/org/openapitools/api/UserApi.java +src/main/java/org/openapitools/model/Category.java +src/main/java/org/openapitools/model/ModelApiResponse.java +src/main/java/org/openapitools/model/Order.java +src/main/java/org/openapitools/model/Pet.java +src/main/java/org/openapitools/model/Tag.java +src/main/java/org/openapitools/model/User.java diff --git a/samples/server/petstore/spring-stubs/.openapi-generator/VERSION b/samples/server/petstore/spring-stubs/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/server/petstore/spring-stubs/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-stubs/README.md b/samples/server/petstore/spring-stubs/README.md new file mode 100644 index 0000000000..d43a1de307 --- /dev/null +++ b/samples/server/petstore/spring-stubs/README.md @@ -0,0 +1,27 @@ + +# OpenAPI generated API stub + +Spring Framework stub + + +## Overview +This code was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. +By using the [OpenAPI-Spec](https://openapis.org), you can easily generate an API stub. +This is an example of building API stub interfaces in Java using the Spring framework. + +The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints +by adding ```@Controller``` classes that implement the interface. Eg: +```java +@Controller +public class PetController implements PetApi { +// implement all PetApi methods +} +``` + +You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg: +```java +@FeignClient(name="pet", url="http://petstore.swagger.io/v2") +public interface PetClient extends PetApi { + +} +``` diff --git a/samples/server/petstore/spring-stubs/pom.xml b/samples/server/petstore/spring-stubs/pom.xml new file mode 100644 index 0000000000..1e88f315c0 --- /dev/null +++ b/samples/server/petstore/spring-stubs/pom.xml @@ -0,0 +1,83 @@ + + 4.0.0 + org.openapitools + spring-stubs + jar + spring-stubs + 1.0.0 + + 1.8 + ${java.version} + ${java.version} + UTF-8 + 2.9.2 + 4.10.3 + + + org.springframework.boot + spring-boot-starter-parent + 2.5.14 + + + + src/main/java + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.data + spring-data-commons + + + + io.springfox + springfox-swagger2 + ${springfox.version} + + + org.webjars + swagger-ui + ${swagger-ui.version} + + + org.webjars + webjars-locator-core + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + org.openapitools + jackson-databind-nullable + 0.2.2 + + + + org.springframework.boot + spring-boot-starter-validation + + + com.fasterxml.jackson.core + jackson-databind + + + org.springframework.boot + spring-boot-starter-test + test + + + diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/ApiUtil.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/ApiUtil.java new file mode 100644 index 0000000000..1245b1dd0c --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/ApiUtil.java @@ -0,0 +1,19 @@ +package org.openapitools.api; + +import org.springframework.web.context.request.NativeWebRequest; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class ApiUtil { + public static void setExampleResponse(NativeWebRequest req, String contentType, String example) { + try { + HttpServletResponse res = req.getNativeResponse(HttpServletResponse.class); + res.setCharacterEncoding("UTF-8"); + res.addHeader("Content-Type", contentType); + res.getWriter().print(example); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java new file mode 100644 index 0000000000..0e831f5b79 --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java @@ -0,0 +1,388 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.0.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.api; + +import org.openapitools.model.ModelApiResponse; +import org.openapitools.model.Pet; +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Validated +@Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") +public interface PetApi { + + default Optional getRequest() { + return Optional.empty(); + } + + /** + * POST /pet : Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return Invalid input (status code 405) + */ + @ApiOperation( + tags = { "pet" }, + value = "Add a new pet to the store", + nickname = "addPet", + notes = "", + authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + } + ) + @ApiResponses({ + @ApiResponse(code = 405, message = "Invalid input") + }) + @RequestMapping( + method = RequestMethod.POST, + value = "/pet", + consumes = "application/json" + ) + default ResponseEntity addPet( + @ApiParam(value = "Pet object that needs to be added to the store", required = true) @Valid @RequestBody Pet body + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * DELETE /pet/{petId} : Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return Invalid pet value (status code 400) + */ + @ApiOperation( + tags = { "pet" }, + value = "Deletes a pet", + nickname = "deletePet", + notes = "", + authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + } + ) + @ApiResponses({ + @ApiResponse(code = 400, message = "Invalid pet value") + }) + @RequestMapping( + method = RequestMethod.DELETE, + value = "/pet/{petId}" + ) + default ResponseEntity deletePet( + @ApiParam(value = "Pet id to delete", required = true) @PathVariable("petId") Long petId, + @ApiParam(value = "") @RequestHeader(value = "api_key", required = false) String apiKey + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /pet/findByStatus : Finds Pets by status + * Multiple status values can be provided with comma separated strings + * + * @param status Status values that need to be considered for filter (required) + * @return successful operation (status code 200) + * or Invalid status value (status code 400) + */ + @ApiOperation( + tags = { "pet" }, + value = "Finds Pets by status", + nickname = "findPetsByStatus", + notes = "Multiple status values can be provided with comma separated strings", + response = Pet.class, + responseContainer = "List", + authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + } + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid status value") + }) + @RequestMapping( + method = RequestMethod.GET, + value = "/pet/findByStatus", + produces = "application/json" + ) + default ResponseEntity> findPetsByStatus( + @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /pet/findByTags : Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @param tags Tags to filter by (required) + * @return successful operation (status code 200) + * or Invalid tag value (status code 400) + * @deprecated + */ + @Deprecated + @ApiOperation( + tags = { "pet" }, + value = "Finds Pets by tags", + nickname = "findPetsByTags", + notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + response = Pet.class, + responseContainer = "List", + authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + } + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid tag value") + }) + @RequestMapping( + method = RequestMethod.GET, + value = "/pet/findByTags", + produces = "application/json" + ) + default ResponseEntity> findPetsByTags( + @NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List tags + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /pet/{petId} : Find pet by ID + * Returns a single pet + * + * @param petId ID of pet to return (required) + * @return successful operation (status code 200) + * or Invalid ID supplied (status code 400) + * or Pet not found (status code 404) + */ + @ApiOperation( + tags = { "pet" }, + value = "Find pet by ID", + nickname = "getPetById", + notes = "Returns a single pet", + response = Pet.class, + authorizations = { + @Authorization(value = "api_key") + } + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Pet not found") + }) + @RequestMapping( + method = RequestMethod.GET, + value = "/pet/{petId}", + produces = "application/json" + ) + default ResponseEntity getPetById( + @ApiParam(value = "ID of pet to return", required = true) @PathVariable("petId") Long petId + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * PUT /pet : Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return Invalid ID supplied (status code 400) + * or Pet not found (status code 404) + * or Validation exception (status code 405) + */ + @ApiOperation( + tags = { "pet" }, + value = "Update an existing pet", + nickname = "updatePet", + notes = "", + authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + } + ) + @ApiResponses({ + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Pet not found"), + @ApiResponse(code = 405, message = "Validation exception") + }) + @RequestMapping( + method = RequestMethod.PUT, + value = "/pet", + consumes = "application/json" + ) + default ResponseEntity updatePet( + @ApiParam(value = "Pet object that needs to be added to the store", required = true) @Valid @RequestBody Pet body + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /pet/{petId} : Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return Invalid input (status code 405) + */ + @ApiOperation( + tags = { "pet" }, + value = "Updates a pet in the store with form data", + nickname = "updatePetWithForm", + notes = "", + authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + } + ) + @ApiResponses({ + @ApiResponse(code = 405, message = "Invalid input") + }) + @RequestMapping( + method = RequestMethod.POST, + value = "/pet/{petId}", + consumes = "application/x-www-form-urlencoded" + ) + default ResponseEntity updatePetWithForm( + @ApiParam(value = "ID of pet that needs to be updated", required = true) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet") @Valid @RequestParam(value = "name", required = false) String name, + @ApiParam(value = "Updated status of the pet") @Valid @RequestParam(value = "status", required = false) String status + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /pet/{petId}/uploadImage : uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return successful operation (status code 200) + */ + @ApiOperation( + tags = { "pet" }, + value = "uploads an image", + nickname = "uploadFile", + notes = "", + response = ModelApiResponse.class, + authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + } + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) + }) + @RequestMapping( + method = RequestMethod.POST, + value = "/pet/{petId}/uploadImage", + produces = "application/json", + consumes = "multipart/form-data" + ) + default ResponseEntity uploadFile( + @ApiParam(value = "ID of pet to update", required = true) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server") @Valid @RequestParam(value = "additionalMetadata", required = false) String additionalMetadata, + @ApiParam(value = "file to upload") @RequestPart(value = "file", required = false) MultipartFile file + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + +} diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java new file mode 100644 index 0000000000..570816e0ba --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java @@ -0,0 +1,191 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.0.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.api; + +import java.util.Map; +import org.openapitools.model.Order; +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Validated +@Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") +public interface StoreApi { + + default Optional getRequest() { + return Optional.empty(); + } + + /** + * DELETE /store/order/{orderId} : Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @param orderId ID of the order that needs to be deleted (required) + * @return Invalid ID supplied (status code 400) + * or Order not found (status code 404) + */ + @ApiOperation( + tags = { "store" }, + value = "Delete purchase order by ID", + nickname = "deleteOrder", + notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors" + ) + @ApiResponses({ + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Order not found") + }) + @RequestMapping( + method = RequestMethod.DELETE, + value = "/store/order/{orderId}" + ) + default ResponseEntity deleteOrder( + @ApiParam(value = "ID of the order that needs to be deleted", required = true) @PathVariable("orderId") String orderId + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /store/inventory : Returns pet inventories by status + * Returns a map of status codes to quantities + * + * @return successful operation (status code 200) + */ + @ApiOperation( + tags = { "store" }, + value = "Returns pet inventories by status", + nickname = "getInventory", + notes = "Returns a map of status codes to quantities", + response = Integer.class, + responseContainer = "Map", + authorizations = { + @Authorization(value = "api_key") + } + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") + }) + @RequestMapping( + method = RequestMethod.GET, + value = "/store/inventory", + produces = "application/json" + ) + default ResponseEntity> getInventory( + + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /store/order/{orderId} : Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @param orderId ID of pet that needs to be fetched (required) + * @return successful operation (status code 200) + * or Invalid ID supplied (status code 400) + * or Order not found (status code 404) + */ + @ApiOperation( + tags = { "store" }, + value = "Find purchase order by ID", + nickname = "getOrderById", + notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + response = Order.class + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Order not found") + }) + @RequestMapping( + method = RequestMethod.GET, + value = "/store/order/{orderId}", + produces = "application/json" + ) + default ResponseEntity getOrderById( + @Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched", required = true) @PathVariable("orderId") Long orderId + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /store/order : Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return successful operation (status code 200) + * or Invalid Order (status code 400) + */ + @ApiOperation( + tags = { "store" }, + value = "Place an order for a pet", + nickname = "placeOrder", + notes = "", + response = Order.class + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order") + }) + @RequestMapping( + method = RequestMethod.POST, + value = "/store/order", + produces = "application/json" + ) + default ResponseEntity placeOrder( + @ApiParam(value = "order placed for purchasing the pet", required = true) @Valid @RequestBody Order body + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + +} diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java new file mode 100644 index 0000000000..32f54a60f0 --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java @@ -0,0 +1,286 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.0.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.api; + +import java.util.List; +import java.time.OffsetDateTime; +import org.openapitools.model.User; +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Validated +@Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") +public interface UserApi { + + default Optional getRequest() { + return Optional.empty(); + } + + /** + * POST /user : Create user + * This can only be done by the logged in user. + * + * @param body Created user object (required) + * @return successful operation (status code 200) + */ + @ApiOperation( + tags = { "user" }, + value = "Create user", + nickname = "createUser", + notes = "This can only be done by the logged in user." + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation") + }) + @RequestMapping( + method = RequestMethod.POST, + value = "/user" + ) + default ResponseEntity createUser( + @ApiParam(value = "Created user object", required = true) @Valid @RequestBody User body + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /user/createWithArray : Creates list of users with given input array + * + * @param body List of user object (required) + * @return successful operation (status code 200) + */ + @ApiOperation( + tags = { "user" }, + value = "Creates list of users with given input array", + nickname = "createUsersWithArrayInput", + notes = "" + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation") + }) + @RequestMapping( + method = RequestMethod.POST, + value = "/user/createWithArray" + ) + default ResponseEntity createUsersWithArrayInput( + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /user/createWithList : Creates list of users with given input array + * + * @param body List of user object (required) + * @return successful operation (status code 200) + */ + @ApiOperation( + tags = { "user" }, + value = "Creates list of users with given input array", + nickname = "createUsersWithListInput", + notes = "" + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation") + }) + @RequestMapping( + method = RequestMethod.POST, + value = "/user/createWithList" + ) + default ResponseEntity createUsersWithListInput( + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * DELETE /user/{username} : Delete user + * This can only be done by the logged in user. + * + * @param username The name that needs to be deleted (required) + * @return Invalid username supplied (status code 400) + * or User not found (status code 404) + */ + @ApiOperation( + tags = { "user" }, + value = "Delete user", + nickname = "deleteUser", + notes = "This can only be done by the logged in user." + ) + @ApiResponses({ + @ApiResponse(code = 400, message = "Invalid username supplied"), + @ApiResponse(code = 404, message = "User not found") + }) + @RequestMapping( + method = RequestMethod.DELETE, + value = "/user/{username}" + ) + default ResponseEntity deleteUser( + @ApiParam(value = "The name that needs to be deleted", required = true) @PathVariable("username") String username + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /user/{username} : Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return successful operation (status code 200) + * or Invalid username supplied (status code 400) + * or User not found (status code 404) + */ + @ApiOperation( + tags = { "user" }, + value = "Get user by user name", + nickname = "getUserByName", + notes = "", + response = User.class + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied"), + @ApiResponse(code = 404, message = "User not found") + }) + @RequestMapping( + method = RequestMethod.GET, + value = "/user/{username}", + produces = "application/json" + ) + default ResponseEntity getUserByName( + @ApiParam(value = "The name that needs to be fetched. Use user1 for testing.", required = true) @PathVariable("username") String username + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123 "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /user/login : Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return successful operation (status code 200) + * or Invalid username/password supplied (status code 400) + */ + @ApiOperation( + tags = { "user" }, + value = "Logs user into the system", + nickname = "loginUser", + notes = "", + response = String.class + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied") + }) + @RequestMapping( + method = RequestMethod.GET, + value = "/user/login", + produces = "application/json" + ) + default ResponseEntity loginUser( + @NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /user/logout : Logs out current logged in user session + * + * @return successful operation (status code 200) + */ + @ApiOperation( + tags = { "user" }, + value = "Logs out current logged in user session", + nickname = "logoutUser", + notes = "" + ) + @ApiResponses({ + @ApiResponse(code = 200, message = "successful operation") + }) + @RequestMapping( + method = RequestMethod.GET, + value = "/user/logout" + ) + default ResponseEntity logoutUser( + + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * PUT /user/{username} : Updated user + * This can only be done by the logged in user. + * + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return Invalid user supplied (status code 400) + * or User not found (status code 404) + */ + @ApiOperation( + tags = { "user" }, + value = "Updated user", + nickname = "updateUser", + notes = "This can only be done by the logged in user." + ) + @ApiResponses({ + @ApiResponse(code = 400, message = "Invalid user supplied"), + @ApiResponse(code = 404, message = "User not found") + }) + @RequestMapping( + method = RequestMethod.PUT, + value = "/user/{username}" + ) + default ResponseEntity updateUser( + @ApiParam(value = "name that need to be deleted", required = true) @PathVariable("username") String username, + @ApiParam(value = "Updated user object", required = true) @Valid @RequestBody User body + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + +} diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Category.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Category.java new file mode 100644 index 0000000000..9f5ef4d9f1 --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Category.java @@ -0,0 +1,109 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A category for a pet + */ + +@ApiModel(description = "A category for a pet") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Category { + + @JsonProperty("id") + private Long id; + + @JsonProperty("name") + private String name; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/ModelApiResponse.java new file mode 100644 index 0000000000..52fb11fd3c --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/ModelApiResponse.java @@ -0,0 +1,135 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * Describes the result of uploading an image resource + */ + +@ApiModel(description = "Describes the result of uploading an image resource") +@JsonTypeName("ApiResponse") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class ModelApiResponse { + + @JsonProperty("code") + private Integer code; + + @JsonProperty("type") + private String type; + + @JsonProperty("message") + private String message; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + */ + + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + */ + + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Order.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Order.java new file mode 100644 index 0000000000..66d9df6dfd --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Order.java @@ -0,0 +1,246 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.time.OffsetDateTime; +import org.springframework.format.annotation.DateTimeFormat; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * An order for a pets from the pet store + */ + +@ApiModel(description = "An order for a pets from the pet store") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Order { + + @JsonProperty("id") + private Long id; + + @JsonProperty("petId") + private Long petId; + + @JsonProperty("quantity") + private Integer quantity; + + @JsonProperty("shipDate") + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + private OffsetDateTime shipDate; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + @JsonProperty("status") + private StatusEnum status; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + */ + + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + */ + + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + */ + @Valid + @ApiModelProperty(value = "") + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + */ + + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + */ + + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Pet.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Pet.java new file mode 100644 index 0000000000..1962262aea --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Pet.java @@ -0,0 +1,262 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.model.Category; +import org.openapitools.model.Tag; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A pet for sale in the pet store + */ + +@ApiModel(description = "A pet for sale in the pet store") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Pet { + + @JsonProperty("id") + private Long id; + + @JsonProperty("category") + private Category category; + + @JsonProperty("name") + private String name; + + @JsonProperty("photoUrls") + @Valid + private List photoUrls = new ArrayList<>(); + + @JsonProperty("tags") + @Valid + private List tags = null; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + @JsonProperty("status") + private StatusEnum status; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + @Valid + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @NotNull + @ApiModelProperty(example = "doggie", required = true, value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @NotNull + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @Valid + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + */ + + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Tag.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Tag.java new file mode 100644 index 0000000000..b30aa3fd9a --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/Tag.java @@ -0,0 +1,109 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A tag for a pet + */ + +@ApiModel(description = "A tag for a pet") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Tag { + + @JsonProperty("id") + private Long id; + + @JsonProperty("name") + private String name; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/User.java b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/User.java new file mode 100644 index 0000000000..8d71f0fcc0 --- /dev/null +++ b/samples/server/petstore/spring-stubs/src/main/java/org/openapitools/model/User.java @@ -0,0 +1,253 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A User who is purchasing from the pet store + */ + +@ApiModel(description = "A User who is purchasing from the pet store") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class User { + + @JsonProperty("id") + private Long id; + + @JsonProperty("username") + private String username; + + @JsonProperty("firstName") + private String firstName; + + @JsonProperty("lastName") + private String lastName; + + @JsonProperty("email") + private String email; + + @JsonProperty("password") + private String password; + + @JsonProperty("phone") + private String phone; + + @JsonProperty("userStatus") + private Integer userStatus; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + */ + + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + */ + + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + */ + + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + */ + + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + */ + + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + */ + + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + */ + + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java index 98da5a2971..9639dc3d9d 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java index b909af27be..189ae02002 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java @@ -35,6 +35,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { @@ -430,7 +431,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index d525709bb6..94bc3eee2d 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java index e906b859e9..8c251e2da5 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApiController.java index ea6c56e02c..0b88e5980b 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java index 456477594f..a78bea9027 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java index 939a45adee..1cbe6e97ad 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java index 98da5a2971..9639dc3d9d 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java index b909af27be..189ae02002 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java @@ -35,6 +35,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { @@ -430,7 +431,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index d525709bb6..94bc3eee2d 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java index e906b859e9..8c251e2da5 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApiController.java index ea6c56e02c..0b88e5980b 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java index 456477594f..a78bea9027 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java index 939a45adee..1cbe6e97ad 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-beanvalidation/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-beanvalidation/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java index b2c251180d..5c5f38def6 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -21,6 +21,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default AnotherFakeApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java index e27e2fc20e..7c3f204924 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final AnotherFakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java index 7b8244ca4c..ec57f6e296 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -31,6 +31,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default FakeApiDelegate getDelegate() { @@ -398,7 +399,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApiController.java index 726b17779f..8e624ba5fb 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApiController.java @@ -37,7 +37,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final FakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index e5f5eae7e1..350f4fe6aa 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -21,6 +21,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default FakeClassnameTestApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 21e28fe8b2..48a276daf1 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final FakeClassnameTestApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java index eb44fc72e2..b899db640b 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java @@ -23,6 +23,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default PetApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApiController.java index 5ef3de965f..e27c4c3b49 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final PetApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java index 6a6fb7d889..d50d072542 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java @@ -22,6 +22,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default StoreApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApiController.java index e9e29a41b4..8c3b33a99a 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final StoreApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java index 0de57c58ae..edfa9968d3 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java @@ -23,6 +23,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default UserApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApiController.java index 1b48d4a944..58511a0729 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final UserApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-delegate-j8/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-delegate-j8/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java index b2c251180d..5c5f38def6 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -21,6 +21,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default AnotherFakeApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java index e27e2fc20e..7c3f204924 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final AnotherFakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java index 7b8244ca4c..ec57f6e296 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java @@ -31,6 +31,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default FakeApiDelegate getDelegate() { @@ -398,7 +399,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java index 726b17779f..8e624ba5fb 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java @@ -37,7 +37,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final FakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index e5f5eae7e1..350f4fe6aa 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -21,6 +21,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default FakeClassnameTestApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 21e28fe8b2..48a276daf1 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final FakeClassnameTestApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java index eb44fc72e2..b899db640b 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java @@ -23,6 +23,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default PetApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java index 5ef3de965f..e27c4c3b49 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final PetApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java index 6a6fb7d889..d50d072542 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java @@ -22,6 +22,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default StoreApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java index e9e29a41b4..8c3b33a99a 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final StoreApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java index 0de57c58ae..edfa9968d3 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java @@ -23,6 +23,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default UserApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java index 1b48d4a944..58511a0729 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final UserApiDelegate delegate; diff --git a/samples/server/petstore/springboot-delegate/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-delegate/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/springboot-delegate/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-delegate/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator-ignore b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.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/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/FILES b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/FILES new file mode 100644 index 0000000000..baf10ab6b8 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/FILES @@ -0,0 +1,21 @@ +README.md +pom.xml +src/main/java/org/openapitools/OpenApiGeneratorApplication.java +src/main/java/org/openapitools/RFC3339DateFormat.java +src/main/java/org/openapitools/api/ApiUtil.java +src/main/java/org/openapitools/api/PetApi.java +src/main/java/org/openapitools/api/PetApiController.java +src/main/java/org/openapitools/api/StoreApi.java +src/main/java/org/openapitools/api/StoreApiController.java +src/main/java/org/openapitools/api/UserApi.java +src/main/java/org/openapitools/api/UserApiController.java +src/main/java/org/openapitools/configuration/HomeController.java +src/main/java/org/openapitools/model/Category.java +src/main/java/org/openapitools/model/ModelApiResponse.java +src/main/java/org/openapitools/model/Order.java +src/main/java/org/openapitools/model/Pet.java +src/main/java/org/openapitools/model/Tag.java +src/main/java/org/openapitools/model/User.java +src/main/resources/application.properties +src/main/resources/openapi.yaml +src/test/java/org/openapitools/OpenApiGeneratorApplicationTests.java diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/VERSION b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/VERSION new file mode 100644 index 0000000000..757e674004 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/README.md b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/README.md new file mode 100644 index 0000000000..7e955e8935 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/README.md @@ -0,0 +1,12 @@ +# OpenAPI generated server + +Spring Boot Server + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. +By using the [OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. +This is an example of building a OpenAPI-enabled server in Java using the SpringBoot framework. + + +Start your server as a simple java application +Change default port value in application.properties \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/pom.xml b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/pom.xml new file mode 100644 index 0000000000..c01ae9e9a0 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/pom.xml @@ -0,0 +1,72 @@ + + 4.0.0 + org.openapitools + springboot-implicitHeaders-annotationLibrary + jar + springboot-implicitHeaders-annotationLibrary + 1.0.0 + + 1.8 + ${java.version} + ${java.version} + UTF-8 + + + org.springframework.boot + spring-boot-starter-parent + 2.7.0 + + + + src/main/java + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.data + spring-data-commons + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + org.openapitools + jackson-databind-nullable + 0.2.2 + + + + org.springframework.boot + spring-boot-starter-validation + + + com.fasterxml.jackson.core + jackson-databind + + + org.springframework.boot + spring-boot-starter-test + test + + + diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/OpenApiGeneratorApplication.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/OpenApiGeneratorApplication.java new file mode 100644 index 0000000000..f62fd6d917 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/OpenApiGeneratorApplication.java @@ -0,0 +1,23 @@ +package org.openapitools; + +import com.fasterxml.jackson.databind.Module; +import org.openapitools.jackson.nullable.JsonNullableModule; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = {"org.openapitools", "org.openapitools.api" , "org.openapitools.configuration"}) +public class OpenApiGeneratorApplication { + + public static void main(String[] args) { + SpringApplication.run(OpenApiGeneratorApplication.class, args); + } + + @Bean + public Module jsonNullableModule() { + return new JsonNullableModule(); + } + +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/RFC3339DateFormat.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/RFC3339DateFormat.java new file mode 100644 index 0000000000..bcd3936d8b --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/RFC3339DateFormat.java @@ -0,0 +1,38 @@ +package org.openapitools; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/ApiUtil.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/ApiUtil.java new file mode 100644 index 0000000000..1245b1dd0c --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/ApiUtil.java @@ -0,0 +1,19 @@ +package org.openapitools.api; + +import org.springframework.web.context.request.NativeWebRequest; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class ApiUtil { + public static void setExampleResponse(NativeWebRequest req, String contentType, String example) { + try { + HttpServletResponse res = req.getNativeResponse(HttpServletResponse.class); + res.setCharacterEncoding("UTF-8"); + res.addHeader("Content-Type", contentType); + res.getWriter().print(example); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApi.java new file mode 100644 index 0000000000..9b874b05cf --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApi.java @@ -0,0 +1,292 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.0.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.api; + +import org.openapitools.model.ModelApiResponse; +import org.openapitools.model.Pet; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Validated +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") +public interface PetApi { + + default Optional getRequest() { + return Optional.empty(); + } + + /** + * POST /pet : Add a new pet to the store + * + * + * @param pet Pet object that needs to be added to the store (required) + * @return successful operation (status code 200) + * or Invalid input (status code 405) + */ + @RequestMapping( + method = RequestMethod.POST, + value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" } + ) + default ResponseEntity addPet( + @Valid @RequestBody Pet pet + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * DELETE /pet/{petId} : Deletes a pet + * + * + * @param petId Pet id to delete (required) + * @return Invalid pet value (status code 400) + */ + @RequestMapping( + method = RequestMethod.DELETE, + value = "/pet/{petId}" + ) + default ResponseEntity deletePet( + @PathVariable("petId") Long petId + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /pet/findByStatus : Finds Pets by status + * Multiple status values can be provided with comma separated strings + * + * @param status Status values that need to be considered for filter (required) + * @return successful operation (status code 200) + * or Invalid status value (status code 400) + */ + @RequestMapping( + method = RequestMethod.GET, + value = "/pet/findByStatus", + produces = { "application/xml", "application/json" } + ) + default ResponseEntity> findPetsByStatus( + @NotNull @Valid @RequestParam(value = "status", required = true) List status + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /pet/findByTags : Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @param tags Tags to filter by (required) + * @return successful operation (status code 200) + * or Invalid tag value (status code 400) + * @deprecated + */ + @Deprecated + @RequestMapping( + method = RequestMethod.GET, + value = "/pet/findByTags", + produces = { "application/xml", "application/json" } + ) + default ResponseEntity> findPetsByTags( + @NotNull @Valid @RequestParam(value = "tags", required = true) List tags + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /pet/{petId} : Find pet by ID + * Returns a single pet + * + * @param petId ID of pet to return (required) + * @return successful operation (status code 200) + * or Invalid ID supplied (status code 400) + * or Pet not found (status code 404) + */ + @RequestMapping( + method = RequestMethod.GET, + value = "/pet/{petId}", + produces = { "application/xml", "application/json" } + ) + default ResponseEntity getPetById( + @PathVariable("petId") Long petId + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * PUT /pet : Update an existing pet + * + * + * @param pet Pet object that needs to be added to the store (required) + * @return successful operation (status code 200) + * or Invalid ID supplied (status code 400) + * or Pet not found (status code 404) + * or Validation exception (status code 405) + */ + @RequestMapping( + method = RequestMethod.PUT, + value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" } + ) + default ResponseEntity updatePet( + @Valid @RequestBody Pet pet + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /pet/{petId} : Updates a pet in the store with form data + * + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return Invalid input (status code 405) + */ + @RequestMapping( + method = RequestMethod.POST, + value = "/pet/{petId}", + consumes = { "application/x-www-form-urlencoded" } + ) + default ResponseEntity updatePetWithForm( + @PathVariable("petId") Long petId, + @Valid @RequestParam(value = "name", required = false) String name, + @Valid @RequestParam(value = "status", required = false) String status + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /pet/{petId}/uploadImage : uploads an image + * + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return successful operation (status code 200) + */ + @RequestMapping( + method = RequestMethod.POST, + value = "/pet/{petId}/uploadImage", + produces = { "application/json" }, + consumes = { "multipart/form-data" } + ) + default ResponseEntity uploadFile( + @PathVariable("petId") Long petId, + @Valid @RequestParam(value = "additionalMetadata", required = false) String additionalMetadata, + @RequestPart(value = "file", required = false) MultipartFile file + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + +} diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApiController.java new file mode 100644 index 0000000000..7713fe93c4 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApiController.java @@ -0,0 +1,46 @@ +package org.openapitools.api; + +import org.openapitools.model.ModelApiResponse; +import org.openapitools.model.Pet; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.context.request.NativeWebRequest; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Controller +public class PetApiController implements PetApi { + + private final NativeWebRequest request; + + @Autowired + public PetApiController(NativeWebRequest request) { + this.request = request; + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); + } + +} diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PingApi.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PingApi.java new file mode 100644 index 0000000000..5d7fe56724 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PingApi.java @@ -0,0 +1,47 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.1.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.api; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Validated +public interface PingApi { + + default Optional getRequest() { + return Optional.empty(); + } + + /** + * GET /ping + * + * @return OK (status code 201) + */ + @RequestMapping( + method = RequestMethod.GET, + value = "/ping" + ) + default ResponseEntity pingGet( + + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + +} diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PingApiController.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PingApiController.java new file mode 100644 index 0000000000..b85749b9d1 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PingApiController.java @@ -0,0 +1,45 @@ +package org.openapitools.api; + + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.context.request.NativeWebRequest; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Controller +@RequestMapping("${openapi.pingTest.base-path:}") +public class PingApiController implements PingApi { + + private final NativeWebRequest request; + + @Autowired + public PingApiController(NativeWebRequest request) { + this.request = request; + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); + } + +} diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApi.java new file mode 100644 index 0000000000..b0e8d4a292 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApi.java @@ -0,0 +1,144 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.0.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.api; + +import java.util.Map; +import org.openapitools.model.Order; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Validated +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") +public interface StoreApi { + + default Optional getRequest() { + return Optional.empty(); + } + + /** + * DELETE /store/order/{orderId} : Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @param orderId ID of the order that needs to be deleted (required) + * @return Invalid ID supplied (status code 400) + * or Order not found (status code 404) + */ + @RequestMapping( + method = RequestMethod.DELETE, + value = "/store/order/{orderId}" + ) + default ResponseEntity deleteOrder( + @PathVariable("orderId") String orderId + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /store/inventory : Returns pet inventories by status + * Returns a map of status codes to quantities + * + * @return successful operation (status code 200) + */ + @RequestMapping( + method = RequestMethod.GET, + value = "/store/inventory", + produces = { "application/json" } + ) + default ResponseEntity> getInventory( + + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /store/order/{orderId} : Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @param orderId ID of pet that needs to be fetched (required) + * @return successful operation (status code 200) + * or Invalid ID supplied (status code 400) + * or Order not found (status code 404) + */ + @RequestMapping( + method = RequestMethod.GET, + value = "/store/order/{orderId}", + produces = { "application/xml", "application/json" } + ) + default ResponseEntity getOrderById( + @Min(1L) @Max(5L) @PathVariable("orderId") Long orderId + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /store/order : Place an order for a pet + * + * + * @param order order placed for purchasing the pet (required) + * @return successful operation (status code 200) + * or Invalid Order (status code 400) + */ + @RequestMapping( + method = RequestMethod.POST, + value = "/store/order", + produces = { "application/xml", "application/json" }, + consumes = { "application/json" } + ) + default ResponseEntity placeOrder( + @Valid @RequestBody Order order + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + +} diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApiController.java new file mode 100644 index 0000000000..f8c784ff38 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApiController.java @@ -0,0 +1,46 @@ +package org.openapitools.api; + +import java.util.Map; +import org.openapitools.model.Order; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.context.request.NativeWebRequest; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Controller +public class StoreApiController implements StoreApi { + + private final NativeWebRequest request; + + @Autowired + public StoreApiController(NativeWebRequest request) { + this.request = request; + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); + } + +} diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApi.java new file mode 100644 index 0000000000..81a6856aca --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApi.java @@ -0,0 +1,214 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.0.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.api; + +import java.util.List; +import java.time.OffsetDateTime; +import org.openapitools.model.User; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Validated +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") +public interface UserApi { + + default Optional getRequest() { + return Optional.empty(); + } + + /** + * POST /user : Create user + * This can only be done by the logged in user. + * + * @param user Created user object (required) + * @return successful operation (status code 200) + */ + @RequestMapping( + method = RequestMethod.POST, + value = "/user", + consumes = { "application/json" } + ) + default ResponseEntity createUser( + @Valid @RequestBody User user + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /user/createWithArray : Creates list of users with given input array + * + * + * @param user List of user object (required) + * @return successful operation (status code 200) + */ + @RequestMapping( + method = RequestMethod.POST, + value = "/user/createWithArray", + consumes = { "application/json" } + ) + default ResponseEntity createUsersWithArrayInput( + @Valid @RequestBody List user + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * POST /user/createWithList : Creates list of users with given input array + * + * + * @param user List of user object (required) + * @return successful operation (status code 200) + */ + @RequestMapping( + method = RequestMethod.POST, + value = "/user/createWithList", + consumes = { "application/json" } + ) + default ResponseEntity createUsersWithListInput( + @Valid @RequestBody List user + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * DELETE /user/{username} : Delete user + * This can only be done by the logged in user. + * + * @param username The name that needs to be deleted (required) + * @return Invalid username supplied (status code 400) + * or User not found (status code 404) + */ + @RequestMapping( + method = RequestMethod.DELETE, + value = "/user/{username}" + ) + default ResponseEntity deleteUser( + @PathVariable("username") String username + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /user/{username} : Get user by user name + * + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return successful operation (status code 200) + * or Invalid username supplied (status code 400) + * or User not found (status code 404) + */ + @RequestMapping( + method = RequestMethod.GET, + value = "/user/{username}", + produces = { "application/xml", "application/json" } + ) + default ResponseEntity getUserByName( + @PathVariable("username") String username + ) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123 "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /user/login : Logs user into the system + * + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return successful operation (status code 200) + * or Invalid username/password supplied (status code 400) + */ + @RequestMapping( + method = RequestMethod.GET, + value = "/user/login", + produces = { "application/xml", "application/json" } + ) + default ResponseEntity loginUser( + @NotNull @Pattern(regexp = "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$") @Valid @RequestParam(value = "username", required = true) String username, + @NotNull @Valid @RequestParam(value = "password", required = true) String password + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * GET /user/logout : Logs out current logged in user session + * + * + * @return successful operation (status code 200) + */ + @RequestMapping( + method = RequestMethod.GET, + value = "/user/logout" + ) + default ResponseEntity logoutUser( + + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + + + /** + * PUT /user/{username} : Updated user + * This can only be done by the logged in user. + * + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @return Invalid user supplied (status code 400) + * or User not found (status code 404) + */ + @RequestMapping( + method = RequestMethod.PUT, + value = "/user/{username}", + consumes = { "application/json" } + ) + default ResponseEntity updateUser( + @PathVariable("username") String username, + @Valid @RequestBody User user + ) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } + +} diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApiController.java new file mode 100644 index 0000000000..894bf6db76 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApiController.java @@ -0,0 +1,47 @@ +package org.openapitools.api; + +import java.util.List; +import java.time.OffsetDateTime; +import org.openapitools.model.User; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.context.request.NativeWebRequest; + +import javax.validation.constraints.*; +import javax.validation.Valid; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Controller +public class UserApiController implements UserApi { + + private final NativeWebRequest request; + + @Autowired + public UserApiController(NativeWebRequest request) { + this.request = request; + } + + @Override + public Optional getRequest() { + return Optional.ofNullable(request); + } + +} diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/configuration/HomeController.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/configuration/HomeController.java new file mode 100644 index 0000000000..7073135047 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/configuration/HomeController.java @@ -0,0 +1,13 @@ +package org.openapitools.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Home redirection to OpenAPI api documentation + */ +@Controller +public class HomeController { + +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Category.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Category.java new file mode 100644 index 0000000000..0d2e56dfa3 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Category.java @@ -0,0 +1,104 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A category for a pet + */ + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Category { + + @JsonProperty("id") + private Long id; + + @JsonProperty("name") + private String name; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @Pattern(regexp = "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/ModelApiResponse.java new file mode 100644 index 0000000000..f66ed8b594 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/ModelApiResponse.java @@ -0,0 +1,129 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * Describes the result of uploading an image resource + */ + +@JsonTypeName("ApiResponse") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class ModelApiResponse { + + @JsonProperty("code") + private Integer code; + + @JsonProperty("type") + private String type; + + @JsonProperty("message") + private String message; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + */ + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + */ + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Order.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Order.java new file mode 100644 index 0000000000..aafcfc0cc1 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Order.java @@ -0,0 +1,237 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import org.springframework.format.annotation.DateTimeFormat; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * An order for a pets from the pet store + */ + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Order { + + @JsonProperty("id") + private Long id; + + @JsonProperty("petId") + private Long petId; + + @JsonProperty("quantity") + private Integer quantity; + + @JsonProperty("shipDate") + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) + private OffsetDateTime shipDate; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + @JsonProperty("status") + private StatusEnum status; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + */ + + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + */ + + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + */ + @Valid + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + */ + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + */ + + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Pet.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Pet.java new file mode 100644 index 0000000000..c857f5804a --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Pet.java @@ -0,0 +1,253 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.model.Category; +import org.openapitools.model.Tag; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A pet for sale in the pet store + */ + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Pet { + + @JsonProperty("id") + private Long id; + + @JsonProperty("category") + private Category category; + + @JsonProperty("name") + private String name; + + @JsonProperty("photoUrls") + @Valid + private List photoUrls = new ArrayList<>(); + + @JsonProperty("tags") + @Valid + private List tags = null; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + @JsonProperty("status") + private StatusEnum status; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + @Valid + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @NotNull + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @NotNull + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @Valid + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + */ + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Tag.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Tag.java new file mode 100644 index 0000000000..32f55514e0 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/Tag.java @@ -0,0 +1,104 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A tag for a pet + */ + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Tag { + + @JsonProperty("id") + private Long id; + + @JsonProperty("name") + private String name; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/User.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/User.java new file mode 100644 index 0000000000..16f35830e8 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/model/User.java @@ -0,0 +1,242 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A User who is purchasing from the pet store + */ + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class User { + + @JsonProperty("id") + private Long id; + + @JsonProperty("username") + private String username; + + @JsonProperty("firstName") + private String firstName; + + @JsonProperty("lastName") + private String lastName; + + @JsonProperty("email") + private String email; + + @JsonProperty("password") + private String password; + + @JsonProperty("phone") + private String phone; + + @JsonProperty("userStatus") + private Integer userStatus; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + */ + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + */ + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + */ + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + */ + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + */ + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + */ + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + */ + + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/resources/application.properties b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/resources/application.properties new file mode 100644 index 0000000000..7e90813e59 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8080 +spring.jackson.date-format=org.openapitools.RFC3339DateFormat +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/resources/openapi.yaml new file mode 100644 index 0000000000..b629acd9d7 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/resources/openapi.yaml @@ -0,0 +1,877 @@ +openapi: 3.0.0 +info: + description: "This is a sample server Petstore server. For this sample, you can\ + \ use the api key `special-key` to test the authorization filters." + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: http://petstore.swagger.io/v2 +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /pet: + post: + description: "" + operationId: addPet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: pet + put: + description: "" + operationId: updatePet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + "405": + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: pet + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - deprecated: true + description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid status value + security: + - petstore_auth: + - read:pets + summary: Finds Pets by status + tags: + - pet + x-accepts: application/json + x-tags: + - tag: pet + /pet/findByTags: + get: + deprecated: true + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + items: + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid tag value + security: + - petstore_auth: + - read:pets + summary: Finds Pets by tags + tags: + - pet + x-accepts: application/json + x-tags: + - tag: pet + /pet/{petId}: + delete: + description: "" + operationId: deletePet + parameters: + - explode: false + in: header + name: api_key + required: false + schema: + type: string + style: simple + - description: Pet id to delete + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "400": + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + x-accepts: application/json + x-tags: + - tag: pet + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + x-accepts: application/json + x-tags: + - tag: pet + post: + description: "" + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/updatePetWithForm_request' + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + x-content-type: application/x-www-form-urlencoded + x-accepts: application/json + x-tags: + - tag: pet + /pet/{petId}/uploadImage: + post: + description: "" + operationId: uploadFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFile_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + x-content-type: multipart/form-data + x-accepts: application/json + x-tags: + - tag: pet + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + content: + application/json: + schema: + additionalProperties: + format: int32 + type: integer + type: object + description: successful operation + security: + - api_key: [] + summary: Returns pet inventories by status + tags: + - store + x-accepts: application/json + x-tags: + - tag: store + /store/order: + post: + description: "" + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid Order + summary: Place an order for a pet + tags: + - store + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: store + /store/order/{orderId}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - description: ID of the order that needs to be deleted + explode: false + in: path + name: orderId + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Delete purchase order by ID + tags: + - store + x-accepts: application/json + x-tags: + - tag: store + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generated exceptions + operationId: getOrderById + parameters: + - description: ID of pet that needs to be fetched + explode: false + in: path + name: orderId + required: true + schema: + format: int64 + maximum: 5 + minimum: 1 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Find purchase order by ID + tags: + - store + x-accepts: application/json + x-tags: + - tag: store + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Create user + tags: + - user + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: user + /user/createWithArray: + post: + description: "" + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: user + /user/createWithList: + post: + description: "" + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: user + /user/login: + get: + description: "" + operationId: loginUser + parameters: + - description: The user name for login + explode: true + in: query + name: username + required: true + schema: + pattern: "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" + type: string + style: form + - description: The password for login in clear text + explode: true + in: query + name: password + required: true + schema: + type: string + style: form + responses: + "200": + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + description: successful operation + headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple + X-Rate-Limit: + description: calls per hour allowed by the user + explode: false + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when token expires + explode: false + schema: + format: date-time + type: string + style: simple + "400": + description: Invalid username/password supplied + summary: Logs user into the system + tags: + - user + x-accepts: application/json + x-tags: + - tag: user + /user/logout: + get: + description: "" + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Logs out current logged in user session + tags: + - user + x-accepts: application/json + x-tags: + - tag: user + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - description: The name that needs to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + security: + - api_key: [] + summary: Delete user + tags: + - user + x-accepts: application/json + x-tags: + - tag: user + get: + description: "" + operationId: getUserByName + parameters: + - description: The name that needs to be fetched. Use user1 for testing. + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + description: successful operation + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Get user by user name + tags: + - user + x-accepts: application/json + x-tags: + - tag: user + put: + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - description: name that need to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + responses: + "400": + description: Invalid user supplied + "404": + description: User not found + security: + - api_key: [] + summary: Updated user + tags: + - user + x-content-type: application/json + x-accepts: application/json + x-tags: + - tag: user +components: + requestBodies: + UserArray: + content: + application/json: + schema: + items: + $ref: '#/components/schemas/User' + type: array + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + schemas: + Order: + description: An order for a pets from the pet store + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: 2000-01-23T04:56:07.000+00:00 + complete: false + status: placed + properties: + id: + format: int64 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + type: boolean + title: Pet Order + type: object + xml: + name: Order + Category: + description: A category for a pet + example: + name: name + id: 6 + properties: + id: + format: int64 + type: integer + name: + pattern: "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" + type: string + title: Pet category + type: object + xml: + name: Category + User: + description: A User who is purchasing from the pet store + example: + firstName: firstName + lastName: lastName + password: password + userStatus: 6 + phone: phone + id: 0 + email: email + username: username + properties: + id: + format: int64 + type: integer + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + title: a User + type: object + xml: + name: User + Tag: + description: A tag for a pet + example: + name: name + id: 1 + properties: + id: + format: int64 + type: integer + name: + type: string + title: Pet Tag + type: object + xml: + name: Tag + Pet: + description: A pet for sale in the pet store + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + type: integer + category: + $ref: '#/components/schemas/Category' + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + name: tag + wrapped: true + status: + deprecated: true + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + title: a Pet + type: object + xml: + name: Pet + ApiResponse: + description: Describes the result of uploading an image resource + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + title: An uploaded response + type: object + updatePetWithForm_request: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + uploadFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/test/java/org/openapitools/OpenApiGeneratorApplicationTests.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/test/java/org/openapitools/OpenApiGeneratorApplicationTests.java new file mode 100644 index 0000000000..3681f67e77 --- /dev/null +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/test/java/org/openapitools/OpenApiGeneratorApplicationTests.java @@ -0,0 +1,13 @@ +package org.openapitools; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class OpenApiGeneratorApplicationTests { + + @Test + void contextLoads() { + } + +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java index 98da5a2971..9639dc3d9d 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java index c4895a4c0a..af90677841 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java @@ -35,6 +35,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index d525709bb6..94bc3eee2d 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java index 9f18fc193b..42f386ef35 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApiController.java index ea6c56e02c..0b88e5980b 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java index 456477594f..a78bea9027 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java index 939a45adee..1cbe6e97ad 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java index c38b19bd2f..806d822a6c 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default AnotherFakeApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c9afaab792..ac91b64909 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final AnotherFakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java index 73a981e95f..dee3ba04a0 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java @@ -36,6 +36,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default FakeApiDelegate getDelegate() { @@ -413,7 +414,7 @@ public interface FakeApi { ) default Mono> testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApiController.java index db9b0dff16..113e866839 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final FakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 83b0ea75b6..a6a89059da 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default FakeClassnameTestApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index f98a29c1d7..99cb9416db 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final FakeClassnameTestApiDelegate delegate; diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java index f5dbad2d4c..03b0917629 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java @@ -28,6 +28,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default PetApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApiController.java index 4b6a806bf6..df2e9ebac5 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final PetApiDelegate delegate; diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java index f97d18e198..444e00d868 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default StoreApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApiController.java index 72b8085628..0f1102844b 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final StoreApiDelegate delegate; diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java index bed50b10a6..0888324183 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java @@ -28,6 +28,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default UserApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApiController.java index 6d3effb9ec..840baa1711 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final UserApiDelegate delegate; diff --git a/samples/server/petstore/springboot-reactive/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-reactive/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/springboot-reactive/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-reactive/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java index b2c251180d..5c5f38def6 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -21,6 +21,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default AnotherFakeApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java index e27e2fc20e..7c3f204924 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final AnotherFakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java index 71fda4af0e..32470c9876 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -31,6 +31,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default FakeApiDelegate getDelegate() { @@ -398,7 +399,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApiController.java index 726b17779f..8e624ba5fb 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApiController.java @@ -37,7 +37,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final FakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index e5f5eae7e1..350f4fe6aa 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -21,6 +21,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default FakeClassnameTestApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 21e28fe8b2..48a276daf1 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final FakeClassnameTestApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java index 10e2fe6e90..67481cae1d 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java @@ -24,6 +24,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default PetApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApiController.java index 6656356233..1218abedfa 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final PetApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java index 6a6fb7d889..d50d072542 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java @@ -22,6 +22,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default StoreApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApiController.java index e9e29a41b4..8c3b33a99a 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final StoreApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java index 0de57c58ae..edfa9968d3 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java @@ -23,6 +23,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default UserApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApiController.java index 1b48d4a944..58511a0729 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final UserApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/resources/openapi.yaml index 3e8e64ad1d..81cc16dcab 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/resources/openapi.yaml @@ -2232,11 +2232,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java index b2c251180d..5c5f38def6 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -21,6 +21,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default AnotherFakeApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApiController.java index e27e2fc20e..7c3f204924 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final AnotherFakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java index 71fda4af0e..32470c9876 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java @@ -31,6 +31,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default FakeApiDelegate getDelegate() { @@ -398,7 +399,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApiController.java index 726b17779f..8e624ba5fb 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApiController.java @@ -37,7 +37,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final FakeApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index e5f5eae7e1..350f4fe6aa 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -21,6 +21,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default FakeClassnameTestApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 21e28fe8b2..48a276daf1 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -27,7 +27,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final FakeClassnameTestApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java index 10e2fe6e90..67481cae1d 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java @@ -24,6 +24,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default PetApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApiController.java index 6656356233..1218abedfa 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final PetApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java index 6a6fb7d889..d50d072542 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java @@ -22,6 +22,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default StoreApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApiController.java index e9e29a41b4..8c3b33a99a 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final StoreApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java index 0de57c58ae..edfa9968d3 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java @@ -23,6 +23,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default UserApiDelegate getDelegate() { diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApiController.java index 1b48d4a944..58511a0729 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final UserApiDelegate delegate; diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/resources/openapi.yaml index 3e8e64ad1d..81cc16dcab 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/resources/openapi.yaml @@ -2232,11 +2232,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java index 98da5a2971..9639dc3d9d 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java index 450460894c..c0cf71ab30 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -35,6 +35,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { @@ -430,7 +431,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index d525709bb6..94bc3eee2d 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java index 89304bea32..83b19f85a7 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java @@ -28,6 +28,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApiController.java index ab60617a7e..58de86d8ac 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApiController.java @@ -31,7 +31,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java index 456477594f..a78bea9027 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java index 939a45adee..1cbe6e97ad 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/resources/openapi.yaml index 3e8e64ad1d..81cc16dcab 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/resources/openapi.yaml @@ -2232,11 +2232,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java index 98da5a2971..9639dc3d9d 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java index 450460894c..c0cf71ab30 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java @@ -35,6 +35,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { @@ -430,7 +431,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index d525709bb6..94bc3eee2d 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java index 89304bea32..83b19f85a7 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java @@ -28,6 +28,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApiController.java index ab60617a7e..58de86d8ac 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApiController.java @@ -31,7 +31,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java index 456477594f..a78bea9027 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java index 939a45adee..1cbe6e97ad 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-spring-pageable/src/main/resources/openapi.yaml index 3e8e64ad1d..81cc16dcab 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-spring-pageable/src/main/resources/openapi.yaml @@ -2232,11 +2232,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java index 98da5a2971..9639dc3d9d 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java index 5d8bfc9ed5..c5d286eeb0 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java @@ -35,6 +35,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { @@ -430,7 +431,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Optional stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Optional booleanGroup, diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index d525709bb6..94bc3eee2d 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java index 8ea47c98a2..79171be16c 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApiController.java index ea6c56e02c..0b88e5980b 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java index 456477594f..a78bea9027 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java index 939a45adee..1cbe6e97ad 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java index 86415a4d15..fc7c6df5ec 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java @@ -35,6 +35,7 @@ import javax.annotation.Generated; @Validated @Tag(name = "another-fake", description = "the another-fake API") @VirtualService +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApiController.java index dd5594acb6..8430d80bd9 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java index 48cb8f3816..938b46f031 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java @@ -45,6 +45,7 @@ import javax.annotation.Generated; @Validated @Tag(name = "fake", description = "the fake API") @VirtualService +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { @@ -439,7 +440,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @Parameter(name = "required_string_group", description = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @Parameter(name = "required_boolean_group", description = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @Parameter(name = "required_int64_group", description = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @Parameter(name = "string_group", description = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @Parameter(name = "boolean_group", description = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApiController.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApiController.java index d33842e20d..d733bfab3a 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApiController.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java index 4d6d9ef0a6..45bcd2d630 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java @@ -35,6 +35,7 @@ import javax.annotation.Generated; @Validated @Tag(name = "fake_classname_test", description = "the fake_classname_test API") @VirtualService +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApiController.java index f4d0eedc19..4db741afee 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java index d211867cb6..0780b3fe8d 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java @@ -37,6 +37,7 @@ import javax.annotation.Generated; @Validated @Tag(name = "pet", description = "Everything about your Pets") @VirtualService +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApiController.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApiController.java index 94ea48fcc8..0b171a217d 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApiController.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java index c0d17024ae..474395083f 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java @@ -36,6 +36,7 @@ import javax.annotation.Generated; @Validated @Tag(name = "store", description = "Access to Petstore orders") @VirtualService +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApiController.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApiController.java index bc986cbdf0..1d86545800 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApiController.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java index 08bbe20f01..a563525ce2 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java @@ -37,6 +37,7 @@ import javax.annotation.Generated; @Validated @Tag(name = "user", description = "Operations about user") @VirtualService +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApiController.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApiController.java index 65303c96a8..10575bc75f 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApiController.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot-virtualan/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-virtualan/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-virtualan/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java index 98da5a2971..9639dc3d9d 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface AnotherFakeApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApiController.java index c2db7ca5a8..65c9de6908 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class AnotherFakeApiController implements AnotherFakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java index b909af27be..189ae02002 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java @@ -35,6 +35,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeApi { default Optional getRequest() { @@ -430,7 +431,7 @@ public interface FakeApi { ) default ResponseEntity testGroupParameters( @NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup, - @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, + @NotNull @ApiParam(value = "Required Boolean in group parameters", required = true) @RequestHeader(value = "required_boolean_group", required = true) Boolean requiredBooleanGroup, @NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group, @ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup, @ApiParam(value = "Boolean in group parameters") @RequestHeader(value = "boolean_group", required = false) Boolean booleanGroup, diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApiController.java index 5ae5d5fed9..b30f53bb59 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApiController.java @@ -38,7 +38,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeApiController implements FakeApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index d525709bb6..94bc3eee2d 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -25,6 +25,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface FakeClassnameTestApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 65b695629d..05196793d4 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -28,7 +28,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java index e906b859e9..8c251e2da5 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "Everything about your Pets") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface PetApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApiController.java index ea6c56e02c..0b88e5980b 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class PetApiController implements PetApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java index 456477594f..a78bea9027 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java @@ -26,6 +26,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "Access to Petstore orders") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface StoreApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApiController.java index 1292dc0b72..f8c784ff38 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApiController.java @@ -29,7 +29,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class StoreApiController implements StoreApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java index 939a45adee..1cbe6e97ad 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java @@ -27,6 +27,7 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "Operations about user") +@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public interface UserApi { default Optional getRequest() { diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApiController.java index ca00184d2a..894bf6db76 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApiController.java @@ -30,7 +30,6 @@ import javax.annotation.Generated; @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller -@RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") public class UserApiController implements UserApi { private final NativeWebRequest request; diff --git a/samples/server/petstore/springboot/src/main/resources/openapi.yaml b/samples/server/petstore/springboot/src/main/resources/openapi.yaml index bf1a427641..5fdcfc33ea 100644 --- a/samples/server/petstore/springboot/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot/src/main/resources/openapi.yaml @@ -2238,11 +2238,13 @@ components: breed: type: string type: object + example: null Cat_allOf: properties: declawed: type: boolean type: object + example: null BigCat_allOf: properties: kind: @@ -2253,6 +2255,7 @@ components: - jaguars type: string type: object + example: null securitySchemes: petstore_auth: flows: diff --git a/website/src/dynamic/users.yml b/website/src/dynamic/users.yml index 4396c080f5..46c979332c 100644 --- a/website/src/dynamic/users.yml +++ b/website/src/dynamic/users.yml @@ -58,6 +58,11 @@ image: "img/companies/ebaidu.jpeg" infoLink: "https://e.baidu.com" pinned: false +- + caption: "Bandwidth" + image: "img/companies/bandwidth.png" + infoLink: "https://dev.bandwidth.com/" + pinned: false - caption: "Banzai Cloud" image: "img/companies/banzai_cloud.png" @@ -483,6 +488,11 @@ image: "img/companies/tencent.png" infoLink: "https://www.tencent.com/" pinned: false +- + caption: TileDB + image: "img/companies/tiledb.png" + infoLink: "https://www.tiledb.com/" + pinned: false - caption: The University of Aizu image: "img/companies/uoa.png" diff --git a/website/static/img/companies/bandwidth.png b/website/static/img/companies/bandwidth.png new file mode 100644 index 0000000000..ee19a0b5af Binary files /dev/null and b/website/static/img/companies/bandwidth.png differ diff --git a/website/static/img/companies/tiledb.png b/website/static/img/companies/tiledb.png new file mode 100644 index 0000000000..68dccdcf3c Binary files /dev/null and b/website/static/img/companies/tiledb.png differ diff --git a/website/yarn.lock b/website/yarn.lock index 0d6cccdb15..9a034b0f58 100644 --- a/website/yarn.lock +++ b/website/yarn.lock @@ -1999,9 +1999,9 @@ browserslist@^4.6.4, browserslist@^4.8.3, browserslist@^4.8.5: node-releases "^1.1.47" buffer-from@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" - integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== + version "1.1.2" + resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" + integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== buffer-indexof@^1.0.0: version "1.1.1" @@ -2471,16 +2471,11 @@ comma-separated-tokens@^1.0.0: resolved "https://registry.yarnpkg.com/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz#632b80b6117867a158f1080ad498b2fbe7e3f5ea" integrity sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw== -commander@^2.18.0: +commander@^2.18.0, commander@^2.20.0: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== -commander@^2.20.0: - version "2.20.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.0.tgz#d58bb2b5c1ee8f87b0d340027e9e94e222c5a422" - integrity sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ== - commander@^4.0.0, commander@^4.0.1: version "4.1.1" resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" @@ -2821,9 +2816,9 @@ css-url-regex@^1.1.0: integrity sha1-g4NCMMyfdMRX3lnuvRVD/uuDt+w= css-what@2.1, css-what@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/css-what/-/css-what-2.1.2.tgz#c0876d9d0480927d7d4920dcd72af3595649554d" - integrity sha512-wan8dMWQ0GUeF7DGEPVjhHemVW/vy6xUYmFzRY8RYqgA0JtXC9rJmbScBjqSu6dg9q0lwPQy6ZAmJVr3PPTvqQ== + version "2.1.3" + resolved "https://registry.yarnpkg.com/css-what/-/css-what-2.1.3.tgz#a6d7604573365fe74686c3f311c56513d88285f2" + integrity sha512-a+EPoD+uZiNfh+5fxw2nO9QwFa6nJe2Or35fGY6Ipw1R3R4AGz1d1TEZrCegvw2YTmZ0jXirGYlzxxpYSHwpEg== cssdb@^4.4.0: version "4.4.0" @@ -3486,9 +3481,9 @@ events@^3.0.0: integrity sha512-Rv+u8MLHNOdMjTAFeT3nCjHn2aGlx435FP/sDHNaRhDEMwyI/aB22Kj2qIN8R0cw3z28psEQLYwxVKLsKrMgWg== eventsource@^1.0.7: - version "1.0.7" - resolved "https://registry.yarnpkg.com/eventsource/-/eventsource-1.0.7.tgz#8fbc72c93fcd34088090bc0a4e64f4b5cee6d8d0" - integrity sha512-4Ln17+vVT0k8aWq+t/bF5arcS3EpT9gYtW66EPacdj/mAFevznsnyoHLPy2BA8gbIQeIHoPsvwmfBftfcG//BQ== + version "1.1.1" + resolved "https://registry.yarnpkg.com/eventsource/-/eventsource-1.1.1.tgz#4544a35a57d7120fba4fa4c86cb4023b2c09df2f" + integrity sha512-qV5ZC0h7jYIAOhArFJgSfdyz6rALJyb270714o7ZtNnw2WSJ+eexhKtE0O8LYPRsHZHf2osHKZBxGPvm3kPkCA== dependencies: original "^1.0.0" @@ -8380,9 +8375,9 @@ source-map-resolve@^0.5.0: urix "^0.1.0" source-map-support@~0.5.12: - version "0.5.16" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.16.tgz#0ae069e7fe3ba7538c64c98515e35339eac5a042" - integrity sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ== + version "0.5.21" + resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" + integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" @@ -8787,9 +8782,9 @@ terser-webpack-plugin@^2.2.1: webpack-sources "^1.4.3" terser@^4.1.2, terser@^4.3.9, terser@^4.4.3: - version "4.6.3" - resolved "https://registry.yarnpkg.com/terser/-/terser-4.6.3.tgz#e33aa42461ced5238d352d2df2a67f21921f8d87" - integrity sha512-Lw+ieAXmY69d09IIc/yqeBqXpEQIpDGZqT34ui1QWXIUpR2RjbqEkT8X7Lgex19hslSqcWM5iMN2kM11eMsESQ== + version "4.8.1" + resolved "https://registry.yarnpkg.com/terser/-/terser-4.8.1.tgz#a00e5634562de2239fd404c649051bf6fc21144f" + integrity sha512-4GnLC0x667eJG0ewJTa6z/yXrbLGv80D9Ru6HIpCQmO+Q4PfEtBFi0ObSckqwL6VyQv/7ENJieXHo2ANmdQwgw== dependencies: commander "^2.20.0" source-map "~0.6.1"